branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>SpongeFrogy/cool<file_sep>/2_sem/proga/newton.py import numpy as np import scipy from sympy import * X, Y= symbols('X Y') # 10 variant def f(x): return x**2+4*np.sin(x)-2 # because of -1<=np.sin<=1 and np.sin(x)=np.sim(x+2pi) x_0 between -6 and 2 min = -6 max = 2 x_array = [] #x_n = [] def df(x): return 2*x+4*np.cos(x) def newton(start): x_n = f(start) x_next = x_n - f(x_n)/df(x_n) while abs(x_next-x_n) > 0.0001: x_n = x_next x_next = x_n - f(x_n)/df(x_n) return -x_next def minabs(min_l, min_r): if min_l < 0 and min_r>0: x_array.append(newton(min_l)) x_array.append(newton(min_r)) else: x_array.append(newton(min_r)) return x_array print('минимальный по модулю корень равен',round(np.min([abs(newton(0)),abs(newton(min))]), 3)) # because np.cos and np.sin between -1 and 1 x between -0.5 and 1.5 and y between -0.5 and -2.5 F = Matrix([[sin(X+2) - Y - 1.5], [cos(Y-2) + X - 0.5]]) dF = Matrix([[diff(sin(X+2) - Y - 1.5, X), diff(sin(X+2) - Y - 1.5, Y)], [diff(cos(Y-2) + X - 0.5, X), diff(cos(Y-2) + X - 0.5, Y)]]) #print(F) #print(dF) EF = dF.inv()*F # 1,346 -1.703 print(Matrix([[1], [2]])[1]) def matrix_newton(x_min, y_min): vec_n = Matrix([[x_min], [y_min]]) vec_next = vec_n - EF.evalf(subs={X: vec_n[0], Y: vec_n[1]}) while abs(vec_n[0]-vec_next[0]) > 0.001 or abs(vec_n[1]-vec_next[1])>0.001: vec_n = vec_next vec_next = vec_n - EF.evalf(subs={X: vec_n[0], Y: vec_n[1]}) return vec_n print(matrix_newton(-0.5, 1.5))
6cf6b24f53570ee2eb1cc966c6bf1222d990724b
[ "Python" ]
1
Python
SpongeFrogy/cool
60d5e2febc26fe5a08535b585b75777711e61d34
37beaa1d823bf4ee7ae4e275ce6caeb5ebc6af2e
refs/heads/master
<repo_name>Vincent-Methot/TP2<file_sep>/Python/tp2.py #!/usr/bin/python # -*- coding: utf-8 -*- """Module regroupant les fonctions du tp2 d'IMN530 à l'hiver 2014, par <NAME> et <NAME>. Le projet complet est disponiblque sur https://github.com/Vincent-Methot/TP2""" import numpy as np import nibabel as nib import scipy.interpolate import Image from pylab import * from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import matplotlib.colors as mpc import warnings import time import cv2 from scipy import optimize def openImage(I): """Ouvre des images au format jpeg, png et NifTI et les retourne en numpy array. (si complexe, prend la valeur absolue)""" if isinstance(I, str): if (I[-7:] == '.nii.gz') | (I[-4:] == '.nii'): #J = np.asarray(nib.load(I).get_data(), dtype=float) J = np.asarray(nib.load(I).get_data()) elif (I[-4:] == '.jpg') | (I[-5:] == '.jpeg') | (I[-4:] == '.png'): #J = np.asarray(Image.open(I), dtype=float) J = np.asarray(Image.open(I)) else: print "Formats d'image acceptés: .nii, .nii.gz, .jpg, .png, .jpeg" else: #J = np.abs(np.asarray(I)).astype(float) J = np.abs(np.asarray(I)) # Normalisation de l'image #if rescaleIm: # J = (J - J.min()) / (J - J.min()).max() return J def normalizeIm(I): """ Transforme une image en float et rescale ses valeurs entre 0 et 1.'""" I = I.astype(float) return (I - I.min()) / (I - I.min()).max() def JointHist(I, J, nbin=256, normIm=False): """Calcule l'histogramme conjoint de deux images de même taille (I et J) en divisant leur intervalle de valeurs en 'nbin' sous-intervalles Paramètres ---------- I et J: array. Images (2D) en format NifTi-1, jpg ou png. nbin: int, optionnel. Le nombre de bins pour le calcul de l'histogramme. 256 par défaut. normIm: logique, optionnel. Si True, les images sont normalisées avant le calcul de l'histogramme. Ainsi, la plus basse (haute) valeur de chaque image correspond au preimer (dernier) bin. Si mis à True, peut créer des artéfacts dus aux arrondissements. Défaut: False. Retour ------ H : 2d array. Histogramme conjoint des images I et J Exemple ------- >>> H = tp2.JointHist('../Data/I4.jpg', '../Data/J4.jpg')""" # Ouverture et mises en forme des images en fonction des options entrées et # du format des images I = openImage(I) J = openImage(J) # Gestion de la normalisation des images areImInt = (np.issubdtype(I.dtype, np.integer) & np.issubdtype(J.dtype, np.integer)) if areImInt: # Tests sur le nombre de bins et le nombre de valeurs possibles dans # les images. maxNBytes = np.maximum(I.dtype.itemsize, J.dtype.itemsize) maxNValue = 2 ** (8 * maxNBytes) if nbin < maxNValue and not(normIm): warnings.warn("nbin < le nombre de valeurs possibles dans au moins " "une des deux images. Pour tracer l'histogramme, " "nous devons normaliser les images, ce qui peut " "introduire des artéfacts.") normIm = True minNBytes = np.minimum(I.dtype.itemsize, J.dtype.itemsize) minNValue = 2 ** (8 * minNBytes) if nbin > minNValue and not(normIm): warnings.warn("nbin > nombre de valeurs possibles dans au moins " "une image et aucune normalisation demandée. " "Nous allons normaliser les images, car sinon les " "bins extrêmes ne correspondront à aucune valeur " "possibles.") normIm = True elif not(normIm): warnings.warn("Les images ne contiennent pas des entiers. Malgré " "l'option normIm=False, nous allons donc les normaliser.") normIm = True if normIm: I = np.round(normalizeIm(I) * (nbin - 1)).astype(int) J = np.round(normalizeIm(J) * (nbin - 1)).astype(int) # Calcul de l'histogramme conjoint H = np.zeros([nbin, nbin], dtype=int) for x in range(I.shape[0]): for y in range(I.shape[1]): H[I[x, y], J[x, y]] += 1 return H def verifSommeHisto(I, J, nbin=256): """Vérifie que l'histogramme conjoint de 2 images de même taille comprend bien, lorsque sommé sur toutes ses bins, le nombre de pixels d'une image Retourne True si la condition est vérifiée, False sinon. Paramètres ---------- I et J: Images (2D) en format NifTi-1, jpg ou png. nbin: int, optionnel. Le nombre de bins pour le calcul de l'histogramme. 256 par défaut. Exemple ------- ­>>> tp2.verifSommeHisto('../Data/I1.png','../Data/J1.png'""" jointHist = JointHist(I, J, nbin) I = openImage(I) return I.size == jointHist.sum() def pltJointHist(I, J, nbin=256, normIm=False, colorMap='jet', cLimFrac=[0,1], useLogNorm=True): """Affiche l'histogramme conjoint des images I et J avec l'origine située dans le coin inférieur gauche. Paramètres ---------- I, J, nbin et normIm: paramètres passés directement, dans cet ordre, à JointHist. Voir l'aide de JointHist pour plus d'info. colorMap: string, optionnel. Colormap de l'histogramme affiché. cLimFrac: liste 2x1, optionnelle. Spécifie les limites pour la mise à l'echelle de l'image dans la colormap. Se specifie en terme de fraction du min et du max de l'image. Défaut: [0,1]. useLogNorm: logique, optionnel. Si True, une échelle log est utilisée pour l'intensité de l'image. Défaut: False. Exemple ------- ­>>> tp2.pltJointHist('../Data/I3.jpg','../Data/J3.jpg',cLimFrac = [0,0.0005]) ­>>> tp2.pltJointHist('../Data/I3.jpg','../Data/J3.jpg',useLogNorm=True)""" jointHist = JointHist(I, J, nbin, normIm) mainFig = plt.figure('IMN530 - Histogramme conjoint') mainFig.clf() minMax = [jointHist.min(), jointHist.max()] customClim = [a * b for a, b in zip(cLimFrac, minMax)] # Préparation de la normalisation logarithmique si demandé if not useLogNorm: customNorm = None else: if customClim[0] == 0: customClim[0] = 1e-15 customNorm = mpc.LogNorm(vmin=customClim[0], vmax=customClim[1],clip=True) # Affichage de l'image imAxes = plt.imshow(jointHist, cmap=colorMap, clim=customClim, norm=customNorm, interpolation="none") imAxes.get_axes().invert_yaxis() plt.colorbar() plt.draw() plt.show(block=False) return mainFig, imAxes def SSD(I, J): """Calcule la somme des différences au carré entre 2 images (I et J) de même taille. Paramètres ---------- I et J: array. Images (2D) en format NifTi-1, jpg ou png. nbin: int, optionnel. Le nombre de bins pour le calcul de l'histogramme. 256 par défaut. Retour ------ SSD : int. Somme des différences au carré entre I et J Exemple ------- >>> SSD = tp2.SSD('../Data/I4.jpg', '../Data/J4.jpg')""" I = openImage(I) J = openImage(J) SSD = ((I - J)**2).sum() return SSD def CR(I, J): """Calcule le coefficient de corrélation entre 2 images (I et J) de même taille Paramètres ---------- I et J: array. Images (2D) en format NifTi-1, jpg ou png. Retour ------ CR : int. Coefficient de corrélation entre I et J Exemple ------- >>> CR = tp2.CR('../Data/I4.jpg', '../Data/J4.jpg')""" I = openImage(I) J = openImage(J) covariance = ((I - I.mean()) * (J - J.mean())).sum() autocovI = ((I - I.mean())**2).sum() autocovJ = ((J - J.mean())**2).sum() # Calcul du coefficient de corrélation à partir des covariances CR = covariance / np.sqrt(autocovI * autocovJ) return CR def IM(I, J, nbin=256): """Calcule l'information mutuelle entre 2 images de même taille Paramètres ---------- I et J: array. Images (2D) en format NifTi-1, jpg ou png. nbin: int, optionnel. Le nombre de bins pour le calcul de l'histogramme. 256 par défaut. Retour ------ IM : int. Information mutuelle entre I et J Exemple ------- >>> IM = tp2.IM('../Data/I4.jpg', '../Data/J4.jpg')""" # Définition de P_{ij} H = JointHist(I, J, nbin).astype(float) P = H / H.sum() P[P == 0] = 1e-9 # Définition de P_i et P_j par broadcasting Pi = np.empty(list(P.shape)) Pj = np.empty(list(P.shape)) Pi[:] = P.sum(0) Pj[:] = P.sum(1) Pj = Pj.T # Calcul de l'information mutuelle IM = (P * log(P / (Pi * Pj))).sum() return IM def trans_rigide(theta, omega, phi, p, q, r): """Renvoie la matrice de transformation rigide en coordonnées homogènes Paramètres ---------- theta: angle de rotation autour de x omega: angle de rotation autour de y phi: angle de rotation autour de z (p, q, r): vecteur de translation Voir aussi ---------- gille_test: test d'une transformation à l'aide d'une grille de points""" T = np.array([[1, 0, 0, p], [0, 1, 0, q], [0, 0, 1, r], [0, 0, 0, 1]]) Rx = np.array([[1, 0, 0, 0], [0, np.cos(theta), -np.sin(theta), 0], [0, np.sin(theta), np.cos(theta), 0], [0, 0, 0, 1]]) Ry = np.array([[np.cos(omega), 0, -np.sin(omega), 0], [0, 1, 0, 0], [np.sin(omega), 0, np.cos(omega), 0], [0, 0, 0, 1]]) Rz = np.array([[np.cos(phi), -np.sin(phi), 0, 0], [np.sin(phi), np.cos(phi), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) Transformation = np.dot(T, np.dot(Rz, np.dot(Ry, Rx))) return Transformation def similitude(s, theta, omega, phi, p, q, r): """Revoie la matrice de transformation rigide (+homothétie) en coordonnées homogènes Paramètres ---------- theta: angle de rotation autour de x omega: angle de rotation autour de y phi: angle de rotation autour de z (p, q, r): vecteur de translation Voir aussi ---------- gille_test: test d'une transformation à l'aide d'une grille de points""" Transformation = np.matrix(np.diag([s, s, s, 1])) * trans_rigide(theta, omega, phi, p, q, r) return Transformation def trans_rigide_2D(I, p, q, theta): """Application d'une rotation d'angle 'theta' (en radians) et de centre (0, 0) (coin supérieur gauche) et d'une translation de coordonnée (p, q) à l'image 'I'. La gestion de l'interpolation est effectuée par scipy.interpolate. Paramètres ---------- I : Image (2D) en format NifTi-1, jpg, png, ou ndarray. p : flottant. Translation dans la direction verticale. q : flottant. Translation dans la direction horizontale. theta : angle de rotation (anti-horaire) en radians Retour ------ J : Image I ayant subit une translation de (p, q) et une rotation theta. Exemple ------- >>> J = tp2.trans_rigide_2D('../Data/I1.png', 0.1, 5, 5)""" I = openImage(I) transformation = np.matrix([[np.cos(theta), -np.sin(theta), p], [np.sin(theta), np.cos(theta), q], [0, 0, 1]]) # Création d'une grille de points en coordonnées homogène 2D xi, yi = np.mgrid[:I.shape[0], :I.shape[1]] pointsInitiaux = np.matrix([xi.ravel(), yi.ravel(), ones(xi.shape).ravel()]) pointsFinaux = transformation * pointsInitiaux J = scipy.interpolate.griddata(pointsFinaux[:-1].T, I.ravel(), pointsInitiaux[:-1].T, method='linear', fill_value=0) J.resize(I.shape) return J def rotation(I, theta): """Application d'une rotation d'angle 'theta' (en radians) et de centre (0, 0) (coin supérieur gauche) à l'image 'I'. Utilise la fonction trans_rigide_2D. Exemple ------- >>> J = tp2.rotation('../Data/I1.png', 0.12) Voir aussi ---------- trans_rigide_2D: Effectue une rotation et une translation sur une image""" J = trans_rigide_2D(I, 0, 0, theta) return J def translation(I, p, q): """Retourne une nouvelle image correspondant à la translatée de l'image 'I' par le vecteur t = (p, q) (p et q doivent être des float). La gestion de l'interpolation est effectuée par scipy.interpolate. Utilise la fonction trans_rigide_2D. Exemple ------- >>> J = tp2.translation('../Data/I1.png', 4.5, 6.7) Voir aussi ---------- trans_rigide_2D: Effectue une rotation et une translation sur une image""" J = trans_rigide_2D(I, p, q, 0) return J def rotationcv2(I, theta): """Application d'une rotation d'angle 'theta' (en radians) et de centre (0, 0) (coin supérieur gauche) à l'image 'I'. Utilise cv2 pour la rapidité. Exemple ------- >>> J = tp2.rotation(I, 0.12)""" nRows, nCols = I.shape M = cv2.getRotationMatrix2D((0, 0), theta * 180 / np.pi, 1) J = cv2.warpAffine(I, M, (nCols, nRows)) return J def translationcv2(I, p, q): """Retourne une nouvelle image correspondant à la translatée de l'image 'I' par le vecteur t = (p, q) (p et q peuvent être des float). Utilise cv2 pour la rapidité. Exemple ------- >>> J = tp2.translationcv2(I, 4.5, 6.7)""" rows, cols = I.shape M = np.float32([[1, 0, q], [0, 1, p]]) J = cv2.warpAffine(I, M, (cols, rows)) return J def trans_rigide_2Dcv2(I, p, q, theta): """Application d'une rotation d'angle 'theta' (en radians) et de centre (0, 0) (coin supérieur gauche) et d'une translation de coordonnée (p, q) à l'image 'I' Exemple ------- >>> J = tp2.trans_rigide_2Dcv2(I, 0.1, 5, 5)""" nRows, nCols = I.shape M = cv2.getRotationMatrix2D((0, 0), theta * 180 / np.pi, 1) M[:, 2] = q, p J = cv2.warpAffine(I, M, (nCols, nRows)) return J def rec2dtrans(I, J, stepSize=1e-7, pqConstCptMax=10, minDeltaPq=0.001, nItMax=500, useCv2=True, showEvo=True): """Recalage 2D minimisant la SSD grâce à une descente de gradient à pas fixe en considérant uniquement les translations. L'énergie SSD correspondant à chaque état est sauvegardée. L'image I est translatée pour correspondre à l'image J. Paramètres ---------- I, J: Images (2D) en format NifTi-1, jpg, png, ou ndarray. stepSize: float, optionnel. Pas de gradient constant. pqConstCptMax: int, optionnel. Si la modification de la norme de (p,q) < minDeltaPq pendant pqConstCptMax itérations, la descente s'arrete. minDeltaPq: int, optionnel. Si la modification de la norme de (p,q) < minDeltaPq pendant pqConstCptMax itérations, la descente s'arrete. nItMax: int, optionnel. Nombre maximal d'itérations effectuées showEvo: logical, optionnel. Si True, l'évolution de l'image modifiée est montrée sur une figure. useCv2: Utilisation d'une fonction opencv pour faire la rotatio si désiré, car plus rapide. Retour ------ actualPq: Le vecteur (p,q) à la fin du recalage. ITrans: Image I translatée recalée (du moins en théorie) avec J allSsd: ndarray, SSD calculées à chaque pas du recalage Exemple ------- ­>>> tp2.rec2dtrans("../Data/BrainMRI_1.jpg", "../Data/BrainMRI_2.jpg")""" # Descente de gradient à pas fixe. I = openImage(I) J = openImage(J) I = I.astype(float) J = J.astype(float) prevPq = np.array([0, 0]) grad = np.array([np.inf, np.inf]) # Constantes pour la condition d'arret. pqConstCpt = 0 prevPq = np.array([0, 0]) convReached = False # Array pour stocker les SSD allSsd = np.zeros(nItMax) # Pour la visualisation du recalage if showEvo: showEvoCpt = 0 # Boucle pour le recalage for iIt in range(0, nItMax): # Calcul de l'image translatée if useCv2: ITrans = translationcv2(I, prevPq[0], prevPq[1]) else: ITrans = translation(I, prevPq[0], prevPq[1]) # Calcul du gradient selon p et q (vérifier la concordance avec les # "x" et "y" de la fonction translation) IDiff = (ITrans - J) gradDim0, gradDim1 = np.gradient(ITrans) grad[0] = -2 * (IDiff * gradDim0).sum() grad[1] = -2 * (IDiff * gradDim1).sum() # Mise à jour du vecteur de translation. actualPq = prevPq - stepSize * grad print "{}{}".format("grad = ", grad) print "{}{}".format("[p,q] = ", prevPq) # Calcul et stockage de la SSD allSsd[iIt] = SSD(ITrans, J) print "{}{}".format("SSD actuel: ", allSsd[iIt]) # Montrer l'évolution si demandé if showEvo: showEvoCpt += 1 if showEvoCpt == 20: pltRecalage2D(ITrans, J) time.sleep(0.05) showEvoCpt = 0 # Condition d'arret. if np.linalg.norm(actualPq - prevPq) < minDeltaPq: pqConstCpt += 1 else: pqConstCpt = 0 if pqConstCpt > pqConstCptMax: convReached = True break prevPq = actualPq # Afficher un warning si la fonction s'est arretée en raison du nombre d'it # max if not(convReached): warnings.warn("Le recalage s'est arreté car le nombre d'itérations max" " a été atteint. Le recalage peut ne pas etre optimal.") # Élmination des 0 à la fin de allSsd allSsd = np.delete(allSsd, range(np.minimum(iIt + 1, nItMax), nItMax)) return actualPq, ITrans, allSsd def rec2drot(I, J, stepSize=4e-12, aConstCptMax=10, minDeltaA=0.001, nItMax=500, showEvo=True, useCv2=True): """Recalage 2D minimisant la SSD grâce à une descente de gradient à pas fixe en considérant uniquement les rotations. L'énergie SSD correspondant à chaque état est sauvegardée. L'image I est translatée pour correspondre à l'image J. Paramètres ---------- I, J: Images (2D) en format NifTi-1, jpg, png, ou ndarray. stepSize: float, optionnel. Pas de gradient constant. aConstCptMax: int, optionnel. Si la modification de l'angle < minDeltaA pendant aConstCptMax itérations, la descente s'arrete. minDeltaA: float, optionnel. Si la modification de l'angle < minDeltaA pendant aConstCptMax itérations, la descente s'arrete. nItMax: int, optionnel. Nombre maximal d'itérations effectuées showEvo: logical, optionnel. Si True, l'évolution de l'image modifiée est montrée sur une figure. useCv2: Utilisation d'une fonction opencv pour faire la rotatio si désiré, car plus rapide. Retour ------ actualA: float. Angle de rotation obtenu lors de la sortie de la boucle IRot: Image I rotatée recalée (du moins en théorie) avec J allSsd: ndarray, Exemple ------- ­>>> tp2.rec2drot("../Data/BrainMRI_1.jpg", "../Data/BrainMRI_3.jpg")""" # Descente de gradient à pas fixe. I = openImage(I).astype(float) J = openImage(J).astype(float) prevA = 0 grad = np.inf # Constantes pour la condition d'arret. aConstCpt = 0 # Array pour stocker les SSD allSsd = np.zeros(nItMax) # Pour la visualisation du recalage if showEvo: showEvoCpt = 0 for iIt in range(0, nItMax): # Calcul de l'image translatée if useCv2: IRot = rotationcv2(I, prevA) else: IRot = rotation(I, prevA) # Calcul du gradient selon a IDiff = (IRot - J) coord = np.mgrid[:J.shape[0], :J.shape[1]] gradDim0, gradDim1 = np.gradient(IRot) IDeriv = gradDim0 * (-np.sin(prevA) * coord[0, ...] - np.cos(prevA) * coord[1, ...]) \ + gradDim1 * (np.cos(prevA) * coord[0, ...] - np.sin(prevA) * coord[1, ...]) grad = -2 * (IDiff * IDeriv).sum() # Mise à jour de l'angle de rotation. actualA = prevA - stepSize * grad print "{}{}".format("grad = ", grad) print "{}{}".format("theta = ", actualA) # Calcul et stockage de la SSD allSsd[iIt] = SSD(IRot, J) print "{}{}".format("SSD actuel: ", allSsd[iIt]) # Montrer l'évolution si demandé if showEvo: showEvoCpt += 1 if showEvoCpt == 20: pltRecalage2D(IRot, J) time.sleep(0.05) showEvoCpt = 0 # Condition d'arret. # Incrementation d'un compteur si l'angle ne change pas # plus qu'à une précision de minDeltaA pixel. if np.abs(actualA - prevA) < minDeltaA: aConstCpt += 1 else: aConstCpt = 0 if aConstCpt > aConstCptMax: convReached = True break prevA = actualA # Afficher quelque chose à la sortie de la boucle print "Sortie de la boucle de recalage." # Afficher un warning si la fonction s'est arretée en raison du nombre d'it # max if not(convReached): warnings.warn("Le recalage s'est arreté car le nombre d'itérations max" " a été atteint. Le recalage peut ne pas etre optimal.") # Élmination des 0 à la fin de allSsd allSsd = np.delete(allSsd, range(np.minimum(iIt + 1, nItMax), nItMax)) return actualA, IRot, allSsd def rec2dpasfixe(I, J, stepSize=[5e-8, 5e-8, 2e-12], nItMax=500, minSsdDiff=0.0001, ssdDiffCptMax=10, showEvo=False, useCv2=True): """Recalage 2D minimisant la SSD grâce à une descente de gradient à pas fixe en considérant uniquement les transformations rigides. L'énergie SSD correspondant à chaque état est sauvegardée. L'image I est modifiée pour correspondre à l'image J. Paramètres ---------- I, J: Images (2D) en format NifTi-1, jpg, png, ou ndarray. stepSize: float, optionnel. Pas de gradient constant. Peut être de taille 1 ou 3. minSsdDiff: float, optionnel. Si la SSD change de moins de minSsdDiff pendant ssdDiffCptMax fois, le recalage arrete. ssdDiffCptMax: int, optionnel. Si la SSD change de moins de minSsdDiff pendant ssdDiffCptMax fois, le recalage arrete. nItMax: int, optionnel. Nombre maximal d'itérations effectuées showEvo: logical, optionnel. Si True, l'évolution de l'image modifiée est montrée sur une figure. useCv2: logical, optionnel. Si True, utilise le module cv2 pour les transformations affines. Si False, utilise les fonctions maison. Retour ------ actualPqa: ndarray de taille 3. Paramètres p,q et theta, dans cet ordre. IMod: ndarray. L'image I après recalage. allSsd: ndarray. Toutes les SSD obtenues pendant le recalage. Exemple ------- ­>>> tp2.rec2dpasfixe("../Data/BrainMRI_1.jpg", "../Data/BrainMRI_3.jpg")""" I = openImage(I).astype(float) J = openImage(J).astype(float) prevPqa = np.array([0, 0, 0]) grad = np.array([np.inf, np.inf, np.inf]) # Constantes pour la condition d'arret. ssdDiffCpt = 0 prevPqa = np.array([0, 0, 0]) convReached = False # Array pour stocker les SSD allSsd = np.zeros(nItMax) # Pour la visualisation du recalage if showEvo: showEvoCpt = 0 # Boucle de recalage for iIt in range(0, nItMax): # Calcul de l'image translatée if useCv2: IMod = trans_rigide_2Dcv2(I, prevPqa[0], prevPqa[1], prevPqa[2]) else: IMod = trans_rigide_2D(I, prevPqa[0], prevPqa[1], prevPqa[2]) # Calcul du gradient selon p, q et a IDiff = (IMod - J) gradDim0, gradDim1 = np.gradient(IMod) coord = np.mgrid[:J.shape[0], :J.shape[1]] IDerivA = gradDim0 * (-np.sin(prevPqa[2]) * coord[0, ...] - np.cos(prevPqa[2]) * coord[1, ...]) \ + gradDim1 * (np.cos(prevPqa[2]) * coord[0, ...] - np.sin(prevPqa[2]) * coord[1, ...]) grad[0] = -2 * (IDiff * gradDim0).sum() grad[1] = -2 * (IDiff * gradDim1).sum() grad[2] = -2 * (IDiff * IDerivA).sum() # Mise à jour du vecteur de translation. actualPqa = prevPqa - stepSize * grad print "{}{}".format("grad = ", grad) print "{}{}".format("[p,q, theta] = ", prevPqa) # Calcul et stockage de la SSD allSsd[iIt] = SSD(IMod, J) print "{}{}".format("SSD actuel: ", allSsd[iIt]) # Montrer l'évolution si demandé if showEvo: showEvoCpt += 1 if showEvoCpt == 20: pltRecalage2D(IMod, J) time.sleep(0.05) showEvoCpt = 0 # Condition d'arret. # Condition sur la variation de la SSD ssdDiff = np.abs((allSsd[iIt] - allSsd[iIt - 1]) / allSsd[iIt - 1]) if ssdDiff < minSsdDiff: ssdDiffCpt += 1 else: ssdDiffCpt = 0 if ssdDiffCpt > ssdDiffCptMax: convReached = True break prevPqa = actualPqa # Afficher un warning si la fonction s'est arretée en raison du nombre d'it # max if not(convReached): warnings.warn("Le recalage s'est arreté car le nombre d'itérations max" " a été atteint. Le recalage peut ne pas etre optimal.") # Élmination des 0 à la fin de allSsd allSsd = np.delete(allSsd, range(np.minimum(iIt + 1, nItMax), nItMax)) return actualPqa, IMod, allSsd def rec2doptimize(I, J, stepSize=np.array([1e-2,1e-2,1e-6]), nItMax=1000, minSsdDiff=0.001, ssdDiffCptMax=10, showEvo=False, useCv2=True): """Recalage 2D minimisant la SSD grâce à une descente de gradient avec "line_search" considérant uniquement les transformations rigides. L'énergie SSD correspondant à chaque état est sauvegardée. L'image I est modifiée pour correspondre à l'image J. Paramètres ---------- I, J: Images (2D) en format NifTi-1, jpg, png, ou ndarray. stepSize: float, optionnel. Pas de gradient initial. minSsdDiff: float, optionnel. Si la SSD change de moins de minSsdDiff pendant ssdDiffCptMax fois, le recalage arrete. ssdDiffCptMax: int, optionnel. Si la SSD change de moins de minSsdDiff pendant ssdDiffCptMax fois, le recalage arrete. nItMax: int, optionnel. Nombre maximal d'itérations effectuées showEvo: logical, optionnel. Si True, l'évolution de l'image modifiée est montrée sur une figure. useCv2: logical, optionnel. Si True, utilise le module cv2 pour les transformations affines. Si False, utilise les fonctions maison. Retour ------ actualPqa: ndarray de taille 3. Paramètres p,q et theta, dans cet ordre. allSsd: ndarray. Toutes les SSD obtenues pendant le recalage. Exemple ------- ­>>> tp2.rec2doptimize("../Data/BrainMRI_1.jpg", "../Data/BrainMRI_3.jpg")""" # Descente de gradient à pas fixe. I = openImage(I).astype(float) J = openImage(J).astype(float) prevPqa = np.array([0, 0, 0]) grad = np.array([np.inf, np.inf, np.inf]) # Constantes pour la condition d'arret. ssdDiffCpt = 0 prevPqa = np.array([0, 0, 0]) convReached = False # Array pour stocker les SSD allSsd = np.zeros(nItMax) # Pour la visualisation du recalage if showEvo: showEvoCpt = 0 # Boucle de recalage for iIt in range(0, nItMax): # Calcul de l'image translatée if useCv2: IMod = trans_rigide_2Dcv2(I, prevPqa[0], prevPqa[1], prevPqa[2]) else: IMod = trans_rigide_2D(I, prevPqa[0], prevPqa[1], prevPqa[2]) # Calcul et stockage de la SSD allSsd[iIt] = SSD(IMod, J) # Calcul du gradient selon p, q et a IDiff = (IMod - J) gradDim0, gradDim1 = np.gradient(IMod) coord = np.mgrid[:J.shape[0], :J.shape[1]] IDerivA = gradDim0 * (-np.sin(prevPqa[2]) * coord[0, ...] - np.cos(prevPqa[2]) * coord[1, ...]) \ + gradDim1 * (np.cos(prevPqa[2]) * coord[0, ...] - np.sin(prevPqa[2]) * coord[1, ...]) grad[0] = -2 * (IDiff * gradDim0).sum() grad[1] = -2 * (IDiff * gradDim1).sum() grad[2] = -2 * (IDiff * IDerivA).sum() # Calcul du pas optimal par line_search # ne fonctionne pas... #stepSize, d, d = optimize.line_search(ssdPqa, ssdGradPqa, prevPqa, #grad, args=(I, J)) # Essai avec un simili line_search (si la fonction est plus grande après # le pas, on diminue la taille du pas de moitié). actualStepSize = stepSize pqaTemp = prevPqa - actualStepSize * grad IModTemp = trans_rigide_2Dcv2(I, pqaTemp[0], pqaTemp[1], pqaTemp[2]) ssdTemp = SSD(IModTemp, J) while ssdTemp > allSsd[iIt]: #pdb.set_trace() actualStepSize = actualStepSize * 0.5 pqaTemp = prevPqa - actualStepSize * grad IModTemp = trans_rigide_2Dcv2(I, pqaTemp[0], pqaTemp[1], pqaTemp[2]) ssdTemp = SSD(IModTemp, J) # Mise à jour du vecteur de translation. actualPqa = prevPqa - actualStepSize * grad print "{}{}".format("grad = ", grad) print "{}{}".format("[p,q, theta] = ", prevPqa) print "{}{}".format("SSD actuel: ", allSsd[iIt]) # Montrer l'évolution si demandé if showEvo: showEvoCpt += 1 if showEvoCpt == 20: pltRecalage2D(IMod, J) time.sleep(0.1) showEvoCpt = 0 # Condition d'arret. # Condition sur la variation de la SSD ssdDiff = np.abs((allSsd[iIt] - allSsd[iIt - 1]) / allSsd[iIt - 1]) if ssdDiff < minSsdDiff: ssdDiffCpt += 1 else: ssdDiffCpt = 0 if ssdDiffCpt > ssdDiffCptMax: convReached = True break prevPqa = actualPqa # Afficher un warning si la fonction s'est arretée en raison du nombre d'it # max if not(convReached): warnings.warn("Le recalage s'est arreté car le nombre d'itérations max" " a été atteint. Le recalage peut ne pas etre optimal.") # Élmination des 0 à la fin de allSsd allSsd = np.delete(allSsd, range(np.minimum(iIt + 1, nItMax), nItMax)) return actualPqa, IMod, allSsd def ssdPqa(pqa, *args): """Calcule le SSD en fonction de pqa pour line_search""" IMod = trans_rigide_2Dcv2(args[0], pqa[0], pqa[1], pqa[2]) return SSD(IMod, args[1]) def ssdGradPqa(pqa, *args): """Calcule la dérivée de SSD en fonction de pqa pour line_search""" IMod = trans_rigide_2Dcv2(args[0], pqa[0], pqa[1], pqa[2]) IDiff = (IMod - args[1]) gradDim0, gradDim1 = np.gradient(IMod) coord = np.mgrid[:args[1].shape[0], :args[1].shape[1]] IDerivA = gradDim0 * (-np.sin(pqa[2]) * coord[0, ...] - np.cos(pqa[2]) * coord[1, ...]) \ + gradDim1 * (np.cos(pqa[2]) * coord[0, ...] - np.sin(pqa[2]) * coord[1, ...]) grad = [0, 0, 0] grad[0] = -2 * (IDiff * gradDim0).sum() grad[1] = -2 * (IDiff * gradDim1).sum() grad[2] = -2 * (IDiff * IDerivA).sum() return grad def grille_test(transformation, xmax = 6, ymax = 6, zmax = 2): """Test des transformations à l'aide d'une grille de points. --------------------------------------------------------- transformation: matrice de transformation 3D en coordonnées homogènes xmax, ymax, zmax: limites de la grille de point (min à 0) Exemple: -------- >>> tp2.grille_test([[2, 0, 0, 5.5], [0, 3, 0, 4.5], [0, 0, 1, 4.5], [0, 0, 0, 1]]) >>> tp2.grille_test(tp2.M3)""" fig = plt.figure() ax = fig.add_subplot(111, projection='3d') xis, yis, zis = np.mgrid[:xmax,:ymax,:zmax] pis = np.matrix([xis.ravel(), yis.ravel(), zis.ravel(), ones(xis.shape).ravel()]).T ax.scatter(xis, yis, zis, c='b') pfs = pis * transformation xfs, yfs, zfs, uns = array(pfs.T) ax.scatter(xfs, yfs, zfs, c='r') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.axis('tight') plt.show() def pltRecalage2D(I, J): """Affiche 2 images de même taille ainsi que la différence entre ces deux images Exemple ------- >>> tp2.pltRecalage2D('../Data/I1.png', '../Data/J1.png')""" I = openImage(I) J = openImage(J) mainFig = plt.figure("IMN530 - Recalage images 2D") currAx = plt.subplot(131) plt.imshow(I) plt.title("Image 1") currAx.xaxis.set_visible(False) currAx.yaxis.set_visible(False) currAx = plt.subplot(132) plt.imshow(J) plt.title("Image 2") currAx.xaxis.set_visible(False) currAx.yaxis.set_visible(False) currAx = plt.subplot(133) plt.imshow(np.abs(I - J)) plt.title("Diff abs") currAx.xaxis.set_visible(False) currAx.yaxis.set_visible(False) plt.draw() plt.show(block=False) return mainFig def num4b(showEvo=True): """Fonction qui teste rec2dtrans pour 3 translations aléatoires différentes pour répondre à la question 4.b. du tp2. Paramètres ---------- stepSize, pqConstCptMax, minDeltaPq, nItMax et showEvo: Même param que pour rec2dtrans. Voir aide de cette fonction. Exemple ------- >>> regPq, initPq, allSsd = tp2.num4b()""" I = openImage("../Data/BrainMRI_1.jpg") # Array to store the 3 initial and post-registration translations initPq = np.zeros([2, 3]) regPq = np.zeros([2, 3]) # Make the whole process reproducible np.random.seed(1) # Make array to store ssd allSsd = [0, 0, 0] # Do registration for the 3 translations for iPq in range(0, 3): initPq[:, iPq] = (np.random.rand(2) * np.array(I.shape) - 0.5) / 4 ITrans = translation(I, initPq[0, iPq], initPq[1, iPq]) regPq[:, iPq], dum, allSsd[iPq] = rec2dtrans(ITrans, I, stepSize=stepSize, pqConstCptMax=pqConstCptMax, minDeltaPq=minDeltaPq, nItMax=nItMax, useCv2=useCv2, showEvo=showEvo) return regPq, initPq, allSsd def num4d(stepSize=4e-12, aConstCptMax=10, minDeltaA=0.0001, nItMax=1000, showEvo=True, useCv2=True): """Fonction qui teste rec2drot pour 3 rotations aléatoires différentes pour répondre à la question 4.d. du tp2. Paramètres ---------- stepSize, pqConstCptMax, minDeltaPq, nItMax et showEvo: Même param que pour rec2dtrans. Voir aide de cette fonction. Exemple ------- >>> regA, initA, allSsd = tp2.num4d()""" I = openImage("../Data/BrainMRI_1.jpg") # Array to store the 3 initial and post-registration rotations initA = np.zeros(3) regA = np.zeros(3) # Make the whole process reproducible np.random.seed(1) # Make array to store ssd allSsd = [0, 0, 0] # Do registration for the 3 rotations for iA in range(0, 3): initA[iA] = ((np.random.rand() * 2 - 1) * np.pi) / 8 IRot = rotation(I, initA[iA]) regA[iA], dum, allSsd[iA] = rec2drot(IRot, I, stepSize=stepSize, aConstCptMax=aConstCptMax, minDeltaA=minDeltaA, nItMax=nItMax, showEvo=showEvo, useCv2=useCv2) return regA, initA, allSsd # Transformations de la question 3d M1 = np.matrix([[0.9045, -0.3847, -0.1840, 10.0000], [0.2939, 0.8750, -0.3847, 10.0000], [0.3090, 0.2939, 0.9045, 10.0000], [0.0000, 0.0000, 0.0000, 1.0000]]) M2 = np.matrix([[0.0000, -0.2598, 0.1500, -3.0000], [0.0000, -0.1500, -0.2598, 1.5000], [0.3000, 0.0000, 0.0000, 0.0000], [0.0000, 0.0000, 0.0000, 1.0000]]) M3 = np.matrix([[ 0.7182, -1.3727, -0.5660, 1.8115], [-1.9236, -4.6556, -2.5512, 0.2873], [-0.6426, -1.7985, -1.6285, 0.7404], [ 0.0000, 0.0000, 0.0000, 1.0000]])<file_sep>/ANTS/ants.sh #! /bin/bash # ANTS.sh # Estimation de la transformation non-linéaire ANTS 3 -m MI[t1.nii, flair.nii, 1, 32] -o flair_to_t1.nii.gz -i 30x20x10 -r Gauss[3,1] -t Elast[3] # Application de la transformation non-linéaire WarpImageMultiTransform 3 flair.nii flair_to_t1.nii.gz -R t1.nii flair_to_t1Warp.nii.gz flair_to_t1Affine.txt # Recalage linéaire flirt -dof 6 -cost mutualinfo -in flair.nii -out flair_lineaire.nii.gz -ref t1.nii
7f4691b57b59edfe0662578d0b3ab52680d03fbf
[ "Python", "Shell" ]
2
Python
Vincent-Methot/TP2
333a0a260b2a467a581cfcfdb97556dd73526d95
b288420ed52739da1b921e24bc58258825b83704
refs/heads/master
<file_sep>const request = require('request'); let pokemonRequest = ({name}, callback) => { let options = { method: 'GET', url: `http://pokeapi.co/api/v2/pokemon/${name}` } request(options, (err, res, body) => { if (err) console.log(err); callback(body); }) } module.exports = pokemonRequest; //only 300 requests per day //create request to Pokemon API for info //save only specific props to DB //name, type, #, png, description<file_sep>import React from 'react'; const PokemonSearchHistoryItem = ({changeShowPokemonVal, pokemon}) => ( <div className="searchHistItems"> <img onClick={() => changeShowPokemonVal(pokemon)} src={pokemon.picture}/> <br /> {pokemon.name} </div> ) export default PokemonSearchHistoryItem;<file_sep># Practice-Template If you were starting off with a completely empty folder do steps 1-4, otherwise run npm install and start at #5: //install package.json in directory 1) npm init //install dependencies into package.json file as devs //devs are something you normally would not call in your js/html files 2) create package.json file npm install npm install --save-dev babel-core babel-loader babel-preset-env babel-preset-react express nodemon path webpack //install dependencies into package.json //these you would normally call in your file e.g. "import React from 'react'" 3) npm install --save react react-dom //import webpack (should be provided) 4) copy webpack from prior files //create script in package.json to init webpack and create/monitor files needed 5) "build": "webpack -w" //run script to invoke all dependencies and create bundle.js file //note that you would normally script bundle.js in your index.html file so it would have access to index.jsx and everything else it imports. Note that this webpack has been configured to create certain folders 6) npm run build 7) create your html page and script bundle.js at bottom of your body and start coding!<file_sep>const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/omegak'); const db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log('omegak has been activated'); }) //TODO: schema for pokemon profiles - need update props let pokemonSchema = mongoose.Schema({ id: {type: Number, unique: true}, name: {type: String, unique: true}, picture: String, type: String, }); let Pokemon = mongoose.model('Pokemon', pokemonSchema); let saveProfile = ({id, name, picture, type}) => { let pokemon = new Pokemon({ id: id, name: name, picture: picture, type: type }); pokemon.save(function(err, poke) { if (err) return console.error(err); console.log('saved profile to DB') }); } //Schema for setting initiat pokemon - ID relationship let pokemonIdSchema = mongoose.Schema({ name: {type: String, unique: true}, id: {type: Number, unique: true} }); let ID = mongoose.model('ID', pokemonIdSchema); let saveID = ({id, name}) => { let pokemonId = new ID({ name: name, id: id }) pokemonId.save(function(err, poke) { if (err) return console.error(err); console.log('Saved ID to DB') }) } //TODO: change params | find pokemon let findPokemonInDB = (param, callback) => { Pokemon.find(param, callback); } let findID = (param, callback) => { ID.find(param, callback); } module.exports.saveProfile = saveProfile; module.exports.findPokemonInDB = findPokemonInDB; module.exports.findID = findID module.exports.saveID = saveID;<file_sep>import React from 'react'; import axios from 'axios'; import PokemonProfile from './PokemonProfile'; import Search from './Search'; import PokemonSearchHistory from './PokemonSearchHistory'; class App extends React.Component { constructor(){ super(); this.state = { pokeList: [], showPokemon: '', currentPokemon: {name: 'See Above', id: 0, type: 'Potato', picture: 'http://cdn.playbuzz.com/cdn/UserImages/57ffa0c0-7789-4fef-817e-f3abdefda63f.jpg'}, } this.changeShowPokemonVal = this.changeShowPokemonVal.bind(this); this.componentDidMount = this.componentDidMount.bind(this); this.requestFromServer = this.requestFromServer.bind(this); this.displayPokemon = this.displayPokemon.bind(this); this.getRequest = this.getRequest.bind(this); } changeShowPokemonVal(e) { if (e.target) { this.setState({showPokemon: e.target.value}); } else { this.setState({currentPokemon: e}); } } componentDidMount() { console.log('ComponentDidMount activated!') this.getRequest(null, '/pokemon/all'); } requestFromServer() { var requestedPokemon = this.state.showPokemon; requestedPokemon = requestedPokemon.toLowerCase(); //invoke fetching pokemon gif var catching = { name: 'TRAINERS ARE CATCHING ' + requestedPokemon.toUpperCase(), id: '??????', type: '??????', picture: 'https://media.giphy.com/media/W04QVzelTHsNW/giphy.gif' } this.setState({currentPokemon: catching}) axios.post('/pokemon', {name: requestedPokemon}) .then( () => { console.log('POST success!'); var query = { params: {name: requestedPokemon}}; this.getRequest(query); }) .catch( error => { console.log('FAILED POST: ', error) }) } getRequest(query, url = '/pokemon') { axios.get(url, query) .then( ({data}) => { console.log('GET success!', data) this.setState({pokeList: [...this.state.pokeList, ...data], currentPokemon: data[0]}) }) .catch( err => { console.log('GET error', err); }) } displayPokemon() { var pokeList = this.state.pokeList; var currentPokemon = this.state.showPokemon; currentPokemon = currentPokemon.toLowerCase(); let checkPokeList = pokeList.filter( pokemon => pokemon.name === currentPokemon); if (checkPokeList.length > 0) { console.log('we have it') //setSTate of pokemon from list this.setState({currentPokemon: checkPokeList[0]}); // this.setState } else { this.requestFromServer(); console.log('request from server') } //setStateof showpokemon to '' this.setState({showPokemon: ''}); } render() { let {currentPokemon, showPokemon, pokeList} = this.state; return ( <div className="main"> <h2>Gotta Catch 'em All</h2> <div> <PokemonProfile currentPokemon={currentPokemon}/> </div> <br/> <div> <Search changeShowPokemonVal={this.changeShowPokemonVal} displayPokemon={this.displayPokemon} showPokemon={showPokemon}/> </div> <br/> <div className="searchHist"> <PokemonSearchHistory changeShowPokemonVal={this.changeShowPokemonVal} pokeList={pokeList}/> </div> </div> ) } } export default App;<file_sep>const express = require('express'); const path = require('path'); const bodyParser = require('body-parser'); const db = require('../db/index'); //db.save db.find const pokemonRequest = require('./apiHelpers'); let port = 3060; let app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.use(express.static(path.join(__dirname, '../client/dist'))); //get request for all on load //get request for specific ones app.get('/pokemon', (req, res) => { //need to pass find parameter console.log('GET request received: ', req.url) var requestedPokemon = req.url.split('=')[1]; db.findPokemonInDB({name: requestedPokemon}, function(err, results) { res.status(200).send(results); }) }) app.get('/pokemon/all', (req, res) => { //need to pass find parameter console.log('GET request received for ALl: ', req.url) db.findPokemonInDB({}, function(err, results) { res.status(200).send(results); }) }) app.post('/pokemon', (req, res) => { db.findPokemonInDB(req.body, function(err, results) { if (results.length > 0) { //if in DB, send, else, go to POkemon API res.status(201).send('Send GET request'); } else { pokemonRequest(req.body, function(result) { result = JSON.parse(result); var wrapPokemon = { id: result.id, name: req.body.name, picture: result.sprites.front_default, type: result.types[0].type.name } db.saveProfile(wrapPokemon); res.status(201).send('POST received, now send GET request'); }) } }) }) //TODO: app.get //TODO: app.post //TODO: app.get /* //TODO: router to controller/helper app.listen(port, function() { console.log('Server is listening on port: ', port); })
068c7a46dbc9c076bec9688fcc8d22e69bca3807
[ "JavaScript", "Markdown" ]
6
JavaScript
omegak911/Working-with-Pokemon-API
2ae4dff88d7ec9fc5a9678b65cbab66ca64d7765
7f93d40a8c5ba20da1d6276523f28ffb799abdae
refs/heads/master
<repo_name>adam-rumpf/trilevel-mcnfli-trials<file_sep>/README.md # Computational Trial Generation for Trilevel Network Interdiction Game with Linear Interdependencies A collection of programs used to generate test cases for the main solver of a research project of mine involving a trilevel network interdiction game on an interdependent network. See the main solver [here](https://github.com/adam-rumpf/trilevel-mcnfli). I would not expect these programs to be of use to anyone outside of my research group, but they are provided here for anyone interested. The goal of these programs is to generate two types of computational trial: a [small example problem](#small-scale-test-network) that can be solved exactly for the purposes of testing the solution algorithm, and a collection of [randomly generated test networks](#netgen-files) (along with scripts for editing and preparing the networks) for use in generating empirical computational results. ## Small-Scale Test Network `example_network.nb` is a Mathematica notebook for generating a single test instance of the trilevel network interdiction game with linear interdependencies. The underlying network is based on the example network used in > <NAME> and <NAME>. Linear input dependence model for interdependent civil infrastructure systems with network simplex based solution algorithm. In preparation, 2020. Small subsets of arcs are chosen to be available for protection and destruction. The network interdiction game is then solved by exhaustively searching the three-stage game tree and applying a minimax algorithm. The output file format is based on the NETGEN format used in the main [MCNFLI trial program](https://github.com/adam-rumpf/mcnfli-trials), modified to include defense bounds, destruction bounds, and the defensible and destructible arc sets. ## NETGEN Files `netgen_edit.py` is a collection of Python functions for generating and editing random test instances. The implementation of NETGEN is taken from the main [MCNFLI trial program](https://github.com/adam-rumpf/mcnfli-trials), and the included scripts require the presence of a `netgen.exe` file in their local folder (see the [releases](https://github.com/adam-rumpf/trilevel-mcnfli-trials/releases) page of this repository). The structure of a problem `.min` file is as follows: * Comment lines begin with `c` and are ignored by the solver. * The objective line begins with a `p` and contains the following information in order: * `min` or `max` to indicate the problem sense * number of nodes * number of arcs * `a` or `n` to indicate whether arcs or nodes are treated as parents * number of arcs that can be defended in stage 1 * number of arcs that can be destroyed in stage 2 * Node definitions begin with an `n` and contain the following information in order: * node ID * supply value, assumed to be `0` for unlisted nodes * Arc definitions begin with an `a` and contain the following information in order: * node ID of tail * node ID of head * lower flow bound * upper flow bound * unit flow cost * Interdependencies begin with an `i` and contain the following information in order: * parent ID (arc ID) * child ID (arc ID) * Defensible and destructible arc definitions begin with a `d` or `r`, respectively, and consist only of arc IDs. If no defensible or destructible arcs are listed, then all arcs are assumed to be available. Node IDs and arc IDs are both assumed to begin with `1`. Arc IDs used are assumed to correspond to their position within the complete arc list. The version of NETGEN used [here](https://github.com/adam-rumpf/mcnfli-trials) transforms a network with sink node parents into an equivalent form for which these parents are represented as arcs, and so the parent ID value is always an arc ID. When using this type of file to construct a mathematical program, the supply constraints of source nodes should be relaxed. Supply values do not need to be relaxed when using arcs as parents. <file_sep>/netgen_edit.py """Scripts for editing trilevel network interdiction game NETGEN files. This file includes a variety of small programs for generating and editing NETGEN files for use as computational trials. For the most part these files are meant to follow the standard NETGEN format as described in: <NAME>, <NAME>, and <NAME>. NETGEN: A program for generating large scale capacitated assignment, transportation, and minimum cost flow network problems. Management Science, 20(5):814-821, 1974. The output files include additional information for defining interdependencies and defensible/destructible arc sets. The following scripts are included: call_netgen() -- Calls a standalone NETGEN .exe to generate an interdependent network instance. generate_trials() -- Generates a set of trials with identical parameters but different random seeds. convert_file() -- Converts an MCNFLI NETGEN file into the format required for the trilevel extension. convert_folder() -- Converts all MCNFLI NETGEN files in a folder into the format required for the trilevel extension. generate_converted_trials() -- Generates a set of converted trial files with identical parameters but different random seeds. """ import math import os import random #============================================================================== def call_netgen(file, nodes, arcs, itype, inum, seed=None, sources=None, sinks=None, costs=(0, 100), supply=None, capacities=(100, 500)): """Calls a local standalone NETGEN .exe file to generate a trial. This requires the presence of a file called "netgen.exe" in the local directory. This file is based on the NETGEN implementation from the MCNFLI project, and generates interdependent network instances with no information regarding the trilevel network interdiction game extension, which will be added to the file by the other scripts in this file. Requires the following positional arguments: file -- Name of the output file (excluding the file extension). nodes -- Number of nodes. arcs -- Number of arcs. itype -- Interdependency type (0 for parent nodes, 1 for parent arcs). inum -- Number of interdependencies. Accepts the following optional keyword arguments: seed -- Integer RNG seed for NETGEN. Defaults to a random seed. sources -- Number of source nodes. Defaults to 20% of all nodes (rounded up). sinks -- Number of sink nodes. Defaults to 20% of all nodes (rounded up). costs -- Tuple of arc cost lower bound and upper bound. Defaults to (0, 100). supply -- Total supply value across all source nodes. Defaults to 10,000 per 256 nodes (rounded up). capacities -- Tuple of arc capacity lower bound and upper bound. Defaults to (100, 500). """ # Set unspecified RNG seed to one based on the system time if seed == None: seed = int(10e8 * random.random()) # Set unspecified sources and sinks if sources == None: sources = math.ceil(0.2 * nodes) if sinks == None: sinks = math.ceil(0.2 * nodes) # Set unspecified total supply if supply == None: supply = math.ceil(10000 * (nodes / 256)) # Call the NETGEN program and return the exit code return os.system("netgen.exe "+file+".min "+str(seed)+" "+str(nodes)+" "+ str(sources)+" "+str(sinks)+" "+str(arcs)+" "+ str(costs[0])+" "+str(costs[1])+" "+str(supply)+ " 0 0 100 100 "+str(capacities[0])+" "+str(capacities[1])+ " "+str(itype)+" "+str(inum)) #============================================================================== def generate_trials(file, num, nodes, arcs, itype, inum, sources=None, sinks=None, costs=(0, 100), supply=None, capacities=(100, 500)): """Generates a set of trials using the same parameters. This function acts as a driver for call_netgen() to generate a set of trials using the same set of parameters but different random seeds. Requires the following positional arguments: file -- Base name of the output file (excluding the file extension). All generated trials will be given the specified name followed by a unique number. num -- Number of files to generate. nodes -- Number of nodes. arcs -- Number of arcs. itype -- Interdependency type (0 for parent nodes, 1 for parent arcs). inum -- Number of interdependencies. Accepts the following optional keyword arguments: sources -- Number of source nodes. Defaults to 20% of all nodes (rounded up). sinks -- Number of sink nodes. Defaults to 20% of all nodes (rounded up). costs -- Tuple of arc cost lower bound and upper bound. Defaults to (0, 100). supply -- Total supply value across all source nodes. Defaults to 10,000 per 256 nodes (rounded up). capacities -- Tuple of arc capacity lower bound and upper bound. Defaults to (100, 500). """ # Set unspecified sources and sinks if sources == None: sources = math.ceil(0.2 * nodes) if sinks == None: sinks = math.ceil(0.2 * nodes) # Set unspecified total supply if supply == None: supply = 10000 * math.ceil(nodes / 256) # Main loop i = 1 while i <= num: # Generate file name by concatenating a number fname = file + str(i).zfill(math.ceil(math.log10(num+1))) # Use call_netgen() to generate a trial with an unspecified seed code = call_netgen(fname, nodes, arcs, itype, inum, sources=sources, sinks=sinks, costs=costs, supply=supply, capacities=capacities) # If return code indicates unsuccessful execution, repeat loop if code != 0: continue print("File "+str(i)+" / "+str(num)+" generated.") i += 1 #============================================================================== def convert_file(file, defnum, attnum, defset=[], attset=[], temp="save.tmp", nonsink=False): """Converts an MCNFLI problem file into a trilevel game problem file. The file format for the trilevel network interdiction game is almost completely identical to that of the standard interdependent network file, except that we add comment lines to explain the new attributes, we add defense and attack bounds to the objective line, and we add sets of defensible and destructible arcs to the end of the file. Requires the following positional arguments: file -- Full name of the file to be converted (including the file extension). defnum -- Number of arcs that can be defended during Stage 1. attnum -- Number of arcs that can be attacked during Stage 2. Accepts the following optional keyword arguments: defset -- List of defensible arc IDs (beginning at index 1). Defaults to the empty list, which is treated as allowing all arcs to be defended. attset -- List of destructible arc IDs (beginning at index 1). Defaults to the empty list, which is treated as allowing all arcs to be destroyed. All defensible arcs are assumed to be attackable, so only arcs that can be attacked but not defended need be listed. temp -- Name of a temporary file used during the file conversion process. Defaults to "save.tmp". As a temporary file this only really needs to be changed if that name is already in use within the same directory. nonsink -- An option for automatically making all arcs defensible and destructible except for the artificailly created arcs for networks with nodes as parents. If True, and if the network uses nodes as parents, then defset and attset will be automatically set to include all non-artificial arcs. Defaults to False. """ dset = defset # defensible arc set aset = attset # destructible arc set # Override given arc sets if automatically generating nonsink arcs if nonsink == True: dset = [] aset = [] # Read input file while writing edited copy to a temporary file with open(file, 'r') as fin: with open(temp, 'w') as fout: i = 0 # current line number a = 1 # current arc number for line in fin: i += 1 # Write edited contents for specific lines if (i == 2) and (line[0] == 'c'): # Replace interdependent network comment print("c Modified to generate trilevel interdiction", file=fout) print("c games on interdependent networks", file=fout) elif (i == 23) and (line[0] == 'c'): # Add trilevel game information at end of comments print("c Interdiction Game Moves -", file=fout) print("c Defense Limit: "+str(defnum), file=fout) print("c Attack Limit: "+str(attnum), file=fout) if len(dset) > 0: print("c Defensible Arc Set: "+str(len(defset)), file=fout) elif nonsink == True: print("c Defensible Arc Set: Nonsink", file=fout) else: print("c Defensible Arc Set: All", file=fout) if len(aset) > 0: print("c Attackable Arc Set: "+str(len(attset)), file=fout) elif nonsink == True: print("c Attackable Arc Set: Nonsink", file=fout) else: print("c Attackable Arc Set: All", file=fout) print(line[:-1], file=fout) elif line[0] == 'p': # Add defense/attack limits to end of objective line print(line[:-1]+" "+str(defnum)+" "+str(attnum), file=fout) else: # Otherwise copy the line exactly print(line[:-1], file=fout) # Record nonsink arcs (which have a head listed as 0) if nonsink == True: if line[0] == 'a': if int(line.split()[2]) != 0: dset.append(a) a += 1 # Add additional lines for the defensible and destructible arc sets if len(dset) > 0: for a in dset: print("d "+str(a), file=fout) if len(aset) > 0: for a in attset: print("r "+str(a), file=fout) print("File contents written to temporary file.") # Overwrite original file with temporary file with open(temp, 'r') as fin: with open(file, 'w') as fout: for line in fin: print(line[:-1], file=fout) print("Input file overwritten.") # Delete temporary file os.remove(temp) print("Temporary file deleted.") #============================================================================== def convert_folder(folder, defnum, attnum, defset=[], attset=[], temp="save.tmp", nonsink=False): """Converts a folder of MCNFLI problem files into trilevel game files. Applies convert_file() to all .min files in a specified directory. Only the top level of the specified folder will be affected, not any of its subfolders. Requires the following positional arguments: folder -- Name of the folder whose contents should be converted. defnum -- Number of arcs that can be defended during Stage 1. attnum -- Number of arcs that can be attacked during Stage 2. Accepts the following optional keyword arguments: defset -- List of defensible arc IDs (beginning at index 1). Defaults to the empty list, which is treated as allowing all arcs to be defended. attset -- List of destructible arc IDs (beginning at index 1). Defaults to the empty list, which is treated as allowing all arcs to be destroyed. All defensible arcs are assumed to be attackable, so only arcs that can be attacked but not defended need be listed. temp -- Name of a temporary file used during the file conversion process. Defaults to "save.tmp". As a temporary file this only really needs to be changed if that name is already in use within the specified directory. nonsink -- An option for automatically making all arcs defensible and destructible except for the artificailly created arcs for networks with nodes as parents. If True, and if the network uses nodes as parents, then defset and attset will be automatically set to include all non-artificial arcs. Defaults to False. """ # Get list of file names in the specified folder for (_, _, files) in os.walk(folder): break num = len(files) # number of files to process # Process each file i = 1 for f in files: convert_file(folder+"/"+f, defnum, attnum, defset=defset, attset=attset, temp=temp, nonsink=nonsink) print("File "+str(i)+" / "+str(num)+" processed.") i += 1 #============================================================================== def generate_converted_trials(file, num, nodes, arcs, itype, inum, defnum, attnum, sources=None, sinks=None, costs=(0, 100), supply=None, capacities=(100, 500), defset=[], attset=[], temp="save.tmp", nonsink=False): """Generates a set of converted trials using the same parameters. Similar to generate_trials(), except that it immediately processes all new files using convert_file(). Requires the following positional arguments: file -- Base name of the output file (excluding the file extension). All generated trials will be given the specified name followed by a unique number. num -- Number of files to generate. nodes -- Number of nodes. arcs -- Number of arcs. itype -- Interdependency type (0 for parent nodes, 1 for parent arcs). inum -- Number of interdependencies. defnum -- Number of arcs that can be defended during Stage 1. attnum -- Number of arcs that can be attacked during Stage 2. Accepts the following optional keyword arguments: sources -- Number of source nodes. Defaults to 20% of all nodes (rounded up). sinks -- Number of sink nodes. Defaults to 20% of all nodes (rounded up). costs -- Tuple of arc cost lower bound and upper bound. Defaults to (0, 100). supply -- Total supply value across all source nodes. Defaults to 10,000 per 256 nodes (rounded up). capacities -- Tuple of arc capacity lower bound and upper bound. Defaults to (100, 500). defset -- List of defensible arc IDs (beginning at index 1). Defaults to the empty list, which is treated as allowing all arcs to be defended. attset -- List of destructible arc IDs (beginning at index 1). Defaults to the empty list, which is treated as allowing all arcs to be destroyed. All defensible arcs are assumed to be attackable, so only arcs that can be attacked but not defended need be listed. temp -- Name of a temporary file used during the file conversion process. Defaults to "save.tmp". As a temporary file this only really needs to be changed if that name is already in use within the same directory. nonsink -- An option for automatically making all arcs defensible and destructible except for the artificailly created arcs for networks with nodes as parents. If True, and if the network uses nodes as parents, then defset and attset will be automatically set to include all non-artificial arcs. Defaults to False. """ # Set unspecified sources and sinks if sources == None: sources = math.ceil(0.2 * nodes) if sinks == None: sinks = math.ceil(0.2 * nodes) # Set unspecified total supply if supply == None: supply = 10000 * math.ceil(nodes / 256) # Main loop i = 1 while i <= num: # Generate file name by concatenating a number fname = file + str(i).zfill(math.ceil(math.log10(num+1))) # Use call_netgen() to generate a trial with an unspecified seed code = call_netgen(fname, nodes, arcs, itype, inum, sources=sources, sinks=sinks, costs=costs, supply=supply, capacities=capacities) # If return code indicates unsuccessful execution, repeat loop if code != 0: continue # Use convert_file() to convert the new file convert_file(fname+".min", defnum, attnum, defset=defset, attset=attset, temp=temp, nonsink=nonsink) print("File "+str(i)+" / "+str(num)+" generated.") i += 1
d1797a85df92c88a0831ba75e35d157d3c815e41
[ "Markdown", "Python" ]
2
Markdown
adam-rumpf/trilevel-mcnfli-trials
301a884f0e498f4502543c429efcd2dad148d0b7
3233604870dfe89bd3d470fa04656db0bfbbe802
refs/heads/master
<file_sep>from django.shortcuts import render, redirect from django.http import HttpResponse from src.models import Subject, StudentClass, Session, Term, Student, StudentResult, StudentBehaviouralAssessment, signature, sets from django.db import connection from django.contrib.auth import authenticate from django.contrib import messages from django.contrib.auth.models import User, auth # cursor to move around the database c = connection.cursor() def home(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['<PASSWORD>'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return render(request, 'src/dashboard.html') else: messages.info(request, 'Incorrect Login-in Details') return render(request, 'src/home.html') else: return render(request, 'src/home.html') def resultcreate(request): global students global subject global term global session global classs global class_id global session_id global term_id global subject_id if request.user.is_authenticated: if request.method == 'POST' and "form1" in request.POST: session = request.POST['session'] term = request.POST['term'] classs = request.POST['class'] subject = request.POST['subject'] ses = Session.objects.get(session_name=session) session_id = ses.id trm = Term.objects.get(term_name=term) term_id = trm.id clas = StudentClass.objects.get(class_name=classs) class_id = clas.id subj = Subject.objects.get(subject_name=subject) subject_id = subj.id students = Student.objects.filter(student_class=class_id).all() student_id = [] for i in students: student_id.append(i.id) subjects = Subject.objects.all() classes = StudentClass.objects.all() sessions = Session.objects.all() terms = Term.objects.all() context = { 'subjects': subjects, 'classes': classes, 'students': students } return render(request, 'src/resultcreate.html', context) if request.method == 'POST' and "form2" in request.POST: ses_ids = [] trm_ids = [] clas_ids = [] subj_ids =[] total_score = [] ids = request.POST.getlist('id') names = request.POST.getlist('name') ca1s = request.POST.getlist('ca1') ca1s2 = [int(i) for i in ca1s] ca2s = request.POST.getlist('ca2') ca2s2 = [int(i) for i in ca2s] exams = request.POST.getlist('exams') exams2 = [int(i) for i in exams] for i in range(len(ca1s2)): total_score.append(ca1s2[i] + ca2s2[i] + exams2[i]) for i in students: ses_ids.append(session_id) trm_ids.append(term_id) clas_ids.append(class_id) subj_ids.append(subject_id) clso = int(class_id) sess = int(session_id) trm = int(term_id) sbj = int(subject_id) queryset = StudentResult.objects.filter(session=sess, term=trm, student_class=clso, subject=sbj).exists() if queryset: print("record is already there") else: c.executemany('INSERT INTO src_studentresult (ca1, ca2, exams, total, student_id, student_class_id, subject_id, session_id, term_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', zip(ca1s, ca2s, exams, total_score, ids, clas_ids, subj_ids, ses_ids, trm_ids)) connection.commit() subjects = Subject.objects.all() classes = StudentClass.objects.all() sessions = Session.objects.all() terms = Term.objects.all() context = { 'subjects': subjects, 'classes': classes, 'students': students } return render(request, 'src/resultcreate.html', context) else: subjects = Subject.objects.all() classes = StudentClass.objects.all() context = { 'subjects': subjects, 'classes': classes } return render(request, 'src/resultcreate.html', context) else: return render(request, 'src/home.html') def updateresult(request): global students global subject global term global session global classs global class_id global session_id global term_id global subject_id if request.user.is_authenticated: if request.method == 'POST' and "form1" in request.POST: session = request.POST['session'] term = request.POST['term'] classs = request.POST['class'] subject = request.POST['subject'] ses = Session.objects.get(session_name=session) session_id = ses.id trm = Term.objects.get(term_name=term) term_id = trm.id clas = StudentClass.objects.get(class_name=classs) class_id = clas.id subj = Subject.objects.get(subject_name=subject) subject_id = subj.id students = Student.objects.filter(student_class=class_id).all() student_id = [] all_results = StudentResult.objects.filter(session=session_id, term=term_id, student_class=class_id,subject=subject_id).all() for i in students: student_id.append(i.id) subjects = Subject.objects.all() classes = StudentClass.objects.all() sessions = Session.objects.all() terms = Term.objects.all() result_students_list = zip(all_results, students) context = { 'subjects': subjects, 'classes': classes, 'all_results': all_results, 'result_students_list': result_students_list } return render(request, 'src/updateresult.html', context) if request.method == 'POST' and "form2" in request.POST: ses_ids = [] trm_ids = [] clas_ids = [] subj_ids =[] total_score = [] ids = request.POST.getlist('id') names = request.POST.getlist('name') ca1s = request.POST.getlist('ca1') ca1s2 = [int(i) for i in ca1s] ca2s = request.POST.getlist('ca2') ca2s2 = [int(i) for i in ca2s] exams = request.POST.getlist('exams') exams2 = [int(i) for i in exams] for i in range(len(ca1s2)): total_score.append(ca1s2[i] + ca2s2[i] + exams2[i]) print(total_score) print(ca1s) for i in students: ses_ids.append(session_id) trm_ids.append(term_id) clas_ids.append(class_id) subj_ids.append(subject_id) c.executemany("""UPDATE src_studentresult SET ca1=?, ca2=?, exams=?, total=? WHERE student_id=? AND student_class_id=? AND subject_id=? AND session_id=? AND term_id=?""", zip(ca1s, ca2s, exams, total_score, ids, clas_ids, subj_ids, ses_ids, trm_ids)) connection.commit() subjects = Subject.objects.all() classes = StudentClass.objects.all() sessions = Session.objects.all() terms = Term.objects.all() context = { 'subjects': subjects, 'classes': classes, 'students': students } return render(request, 'src/updateresult.html', context) else: subjects = Subject.objects.all() classes = StudentClass.objects.all() context = { 'subjects': subjects, 'classes': classes } return render(request, 'src/updateresult.html', context) else: return render(request, 'src/home.html') def single_result_update(request): global students global subject global term global session global classs global class_id global session_id global term_id global subject_id global student_qr_id global student_id if request.user.is_authenticated: if request.method == 'POST' and "form1" in request.POST: session = request.POST['session'] term = request.POST['term'] classs = request.POST['class'] subject = request.POST['subject'] student_id = request.POST['student_id'] ses = Session.objects.get(session_name=session) session_id = ses.id trm = Term.objects.get(term_name=term) term_id = trm.id clas = StudentClass.objects.get(class_name=classs) class_id = clas.id subj = Subject.objects.get(subject_name=subject) subject_id = subj.id student = [] student.append(student_id) get_student = StudentResult.objects.get(student=student_id, session=session_id, term=term_id, student_class=class_id, subject=subject_id) subjects = Subject.objects.all() classes = StudentClass.objects.all() context = { 'subjects': subjects, 'classes': classes, 'get_student': get_student, 'student_id': student_id } return render(request, 'src/single_result_update.html', context) if request.method == 'POST' and "form2" in request.POST: ids = request.POST['id'] ca1 = request.POST['ca1'] ca2 = request.POST['ca2'] exams = request.POST['exams'] total_score = int(ca1) + int(ca2) + int(exams) queryy = StudentResult.objects.get(student=ids, session=session_id, term=term_id, student_class=class_id, subject=subject_id) queryy.ca1 = ca1 queryy.save() queryy.ca2 = ca2 queryy.save() queryy.exams = exams queryy.save() queryy.total = total_score queryy.save() subjects = Subject.objects.all() classes = StudentClass.objects.all() context = { 'subjects': subjects, 'classes': classes } return render(request, 'src/single_result_update.html', context) else: subjects = Subject.objects.all() classes = StudentClass.objects.all() context = { 'subjects': subjects, 'classes': classes } return render(request, 'src/single_result_update.html', context) else: return render(request, 'src/home.html') def result_view(request): global class_id global session_id global term_id if request.user.is_authenticated: if request.method == 'POST' and "form1" in request.POST: classes = StudentClass.objects.all() context = { 'classes': classes } session = request.POST['session'] term = request.POST['term'] classs = request.POST['class'] ses = Session.objects.get(session_name=session) session_id = ses.id trm = Term.objects.get(term_name=term) term_id = trm.id clas = StudentClass.objects.get(class_name=classs) class_id = clas.id results = StudentResult.objects.filter(session=session_id, term=term_id, student_class=class_id) bulk = {} print(results) for result in results: ca1_total = 0 ca2_total = 0 exams_total = 0 total = 0 subjects = [] for subject in results: if subject.student == result.student: subjects.append(subject) ca1_total += subject.ca1 ca2_total += subject.ca2 exams_total += subject.exams total += subject.total subject_pos = subject.subject_position grade = subject.grade terms = subject.term sesss = subject.session classs = subject.student_class avr = total/len(subjects) bulk[result.student] = { "student": result.student, "subjects": subjects, "ca1_total": ca1_total, "ca2_total": ca1_total, "exams_total": exams_total, "total": total, "grade": grade, "subject_pos": subject_pos, "terms": terms, "sesss": sesss, "classs": classs, "overal_total": total, "average": round(avr, 2) } print(result.student) classes = StudentClass.objects.all() bhv = StudentBehaviouralAssessment.objects.filter(session=session_id, term=term_id, student_class=class_id) signs = signature.objects.filter(classs=classs).first() some_images = sets.objects.first() context = { 'classes': classes, 'results': bulk, 'bhv': bhv, 'signs': signs, 'some_images':some_images } return render(request, 'src/single_result_view.html', context) else: classes = StudentClass.objects.all() context = { 'classes': classes } return render(request, 'src/result_view.html', context) else: return render(request, 'src/home.html') def settings(request): if request.user.is_authenticated: c.execute("""UPDATE src_studentresult SET subject_position=( SELECT count(*) FROM src_studentresult AS i WHERE i.total > src_studentresult.total AND i.student_class_id = src_studentresult.student_class_id AND i.subject_id = src_studentresult.subject_id AND i.session_id = src_studentresult.session_id AND i.term_id = src_studentresult.term_id) + 1;""") connection.commit() global students global subject global term global session global classs global class_id global session_id global term_id global subject_id global student_id if request.method == 'POST' and "form1" in request.POST: session = request.POST['session'] term = request.POST['term'] classs = request.POST['class'] ses = Session.objects.get(session_name=session) session_id = ses.id trm = Term.objects.get(term_name=term) term_id = trm.id clas = StudentClass.objects.get(class_name=classs) class_id = clas.id students = Student.objects.filter(student_class=class_id).all() student_id = [] for i in students: student_id.append(i.id) print(student_id) classes = StudentClass.objects.all() context = { 'classes': classes, 'students': students } return render(request, 'src/settings.html', context) if request.method == 'POST' and "form2" in request.POST: ses_ids = [] trm_ids = [] clas_ids = [] ids = request.POST.getlist('id') conduct = request.POST.getlist('conduct') punc = request.POST.getlist('punctuality') ded = request.POST.getlist('dedication') part = request.POST.getlist('participation') hosp = request.POST.getlist('hospitality') creat= request.POST.getlist('creativity') phy = request.POST.getlist('physical') neat = request.POST.getlist('neatness') for i in ids: ses_ids.append(session_id) trm_ids.append(term_id) clas_ids.append(class_id) queryset = StudentBehaviouralAssessment.objects.filter(session=session_id, term=term_id, student_class=class_id).exists() if queryset: print("record is already there") else: c.executemany("""INSERT INTO src_studentbehaviouralassessment (conduct, punctuality, dedication, participation, hospitality, neatness, creativity, physical, session_id, student_id, student_class_id, term_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", zip(conduct, punc, ded, part, hosp, neat, creat, phy, ses_ids, ids, clas_ids, trm_ids)) connection.commit() classes = StudentClass.objects.all() context = { 'classes': classes } return render(request, 'src/settings.html', context) else: classes = StudentClass.objects.all() context = { 'classes': classes } return render(request, 'src/settings.html', context) else: return render(request, 'src/home.html') def single_result_view(request): global subject global term global session global classs global class_id global session_id global term_id global subject_id global student_qr_id global students if request.method == 'POST' and "form1" in request.POST: session = request.POST['session'] term = request.POST['term'] student_id = request.POST['student_id'] ses = Session.objects.get(session_name=session) session_id = ses.id trm = Term.objects.get(term_name=term) term_id = trm.id results = StudentResult.objects.filter(session=session_id, term=term_id, student=student_id) bulk = {} for result in results: ca1_total = 0 ca2_total = 0 exams_total = 0 total = 0 subjects = [] for subject in results: if subject.student == result.student: subjects.append(subject) ca1_total += subject.ca1 ca2_total += subject.ca2 exams_total += subject.exams total += subject.total subject_pos = subject.subject_position grade = subject.grade terms = subject.term sesss = subject.session classs = subject.student_class avr = total/len(subjects) bulk[result.student] = { "student": result.student, "subjects": subjects, "ca1_total": ca1_total, "ca2_total": ca1_total, "exams_total": exams_total, "total": total, "grade": grade, "subject_pos": subject_pos, "terms": terms, "sesss": sesss, "classs": classs, "overal_total": total, "average": round(avr, 2) } bhv = StudentBehaviouralAssessment.objects.filter(session=session_id, term=term_id, student=student_id) signs = signature.objects.filter(classs=classs).first() some_images = sets.objects.first() print(some_images) context = { 'results': bulk, 'bhv': bhv, 'signs': signs, 'some_images':some_images } return render(request, 'src/single_result_view.html', context) else: return render(request, 'src/single_result_view1.html') ''' if request.method == 'POST' and "form0" in request.POST: global student_qr_id student = request.POST['students'] student_qry = Student.objects.get(student_name=student, student_class=) student_qr_id = student_qry.id trm = Term.objects.get(term_name=term) term_id = trm.id clas = StudentClass.objects.get(class_name=classs) class_id = clas.id results = StudentResult.objects.filter(session=session_id, term=term_id, student_class=class_id) bulk = {} for result in results: ca1_total = 0 ca2_total = 0 exams_total = 0 total = 0 subjects = [] for subject in results: if subject.student == result.student: subjects.append(subject) ca1_total += subject.ca1 ca2_total += subject.ca2 exams_total += subject.exams total += subject.total subject_pos = subject.subject_position grade = subject.grade terms = subject.term sesss = subject.session classs = subject.student_class avr = total/len(subjects) bulk[result.student] = { "student": result.student, "subjects": subjects, "ca1_total": ca1_total, "ca2_total": ca1_total, "exams_total": exams_total, "total": total, "grade": grade, "subject_pos": subject_pos, "terms": terms, "sesss": sesss, "classs": classs, "overal_total": total, "average": avr } classes = StudentClass.objects.all() bhv = StudentBehaviouralAssessment.objects.filter(session=session_id, term=term_id, student_class=class_id) context = { 'classes': classes, 'results': bulk, 'bhv': bhv } return render(request, 'src/result_view.html', context) else: classes = StudentClass.objects.all() context = { 'classes': classes } return render(request, 'src/result_view.html', context) '''<file_sep>{% extends "src/base.html" %} {% block content %} <div> <h1> Upload Student Behaviours Assessment </h1> <h4> Please Select Session, Term, Class and Subject you wish to upload for </h4> </div> <div class="main"> <form name="form1" method="POST"> {% csrf_token %} <div class="row" style="padding-right: 10px;"> <div class="col"> <select class="form-control" name="session"> <option>Session</option> <option>2019/2020</option> <option>2020/2021</option> <option>2021/2022</option> </select> </div> <div class="col"> <select class="form-control" name="term"> <option>Term</option> <option>First Term</option> <option>Second Term</option> <option>Third Term</option> </select> </div> <div class="col"> <select class="form-control" name="class"> <option>Class</option> {% for i in classes %} <option>{{ i.class_name }}</option> {% endfor %} </select> </div> <button name="form1" type="submit" class="btn btn-primary">GET</button> </div> </form> </div> {% if request.method == 'POST' and "form1" in request.POST %} <div> <h4> Please Insert the students Results approprietly </h4> </div> <div class="row" style="padding-right: 10px;"> <div class="col"> <h6> Student ID </h6> </div> <div class="col"> <h6> Name </h6> </div> <div class="col"> <h6> Conduct </h6> </div> <div class="col"> <h6> Punctuality </h6> </div> <div class="col"> <h6> Dedication </h6> </div> <div class="col"> <h6> Participation in Class </h6> </div> <div class="col"> <h6> Hospitality </h6> </div> <div class="col"> <h6> Neatness </h6> </div> <div class="col"> <h6> Creativity</h6> </div> <div class="col"> <h6> Physical Health </h6> </div> </div> <form name="form2" method="POST"> {% csrf_token %} {% for i in students %} <div class="row" style="padding-right: 10px; padding-left: 10px;"> <div class="col"> <input type="number" class="form-control" value="{{i.id}}" name="id" style="text-align: center;"> </div> <div class="col"> <input type="text" class="form-control" value="{{i.student_name}}" name="name"> </div> <div class="col"> <input type="number" class="form-control" value=0 name="conduct" style="text-align: center;"> </div> <div class="col"> <input type="number" class="form-control" value=0 name="punctuality" style="text-align: center;"> </div> <div class="col"> <input type="number" class="form-control" value=0 name="dedication" style="text-align: center;"> </div> <div class="col"> <input type="number" class="form-control" value=0 name="participation" style="text-align: center;"> </div> <div class="col"> <input type="number" class="form-control" value=0 name="hospitality" style="text-align: center;"> </div> <div class="col"> <input type="number" class="form-control" value=0 name="neatness" style="text-align: center;"> </div> <div class="col"> <input type="number" class="form-control" value=0 name="creativity" style="text-align: center;"> </div> <div class="col"> <input type="number" class="form-control" value=0 name="physical" style="text-align: center;"> </div> </div> {% endfor %} <div style="padding-top: 10px; padding-left: 10px;"> <button name="form2" type="submit" class="btn btn-primary">UPLOAD</button> </div> </form> {% endif %} {% endblock content %} <file_sep># Generated by Django 3.1.2 on 2020-11-30 12:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('src', '0001_initial'), ] operations = [ migrations.CreateModel( name='StudentBehaviouralAssessment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('conduct', models.IntegerField(default=0)), ('punctuality', models.IntegerField(default=0)), ('dedication', models.IntegerField(default=0)), ('participation', models.IntegerField(default=0)), ('hospitality', models.IntegerField(default=0)), ('neatness', models.IntegerField(default=0)), ('creativity', models.IntegerField(default=0)), ('physical', models.IntegerField(default=0)), ('session', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='src.session')), ('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='src.student')), ('student_class', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='src.studentclass')), ('term', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='src.term')), ], ), ] <file_sep>from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('createresult', views.resultcreate, name='resultcreate'), path('updateresult', views.updateresult, name='updateresult'), path('single_result_update', views.single_result_update, name='single_result_update'), path('result_view', views.result_view, name='result_view'), path('settings', views.settings, name='settings'), path('single_result_view', views.single_result_view, name='single_result_view'), ] <file_sep>from django.db import models class Subject(models.Model): subject_name = models.CharField(max_length=100) def __str__(self): return(self.subject_name) class StudentClass(models.Model): class_name = models.CharField(max_length=100) def __str__(self): return(self.class_name) class Session(models.Model): session_name = models.CharField(max_length=100) def __str__(self): return(self.session_name) class Term(models.Model): term_name = models.CharField(max_length=100) def __str__(self): return(self.term_name) class Student(models.Model): student_name = models.CharField(max_length=100) student_class = models.ForeignKey(StudentClass, null=True, on_delete=models.SET_NULL) def __str__(self): return(self.student_name) class StudentResult(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) session = models.ForeignKey(Session, on_delete=models.CASCADE) term = models.ForeignKey(Term, on_delete=models.CASCADE) student_class = models.ForeignKey(StudentClass, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) ca1 = models.IntegerField(default=0) ca2 = models.IntegerField(default=0) exams = models.IntegerField(default=0) total = models.IntegerField(default=0) subject_position = models.IntegerField(default=0) class Meta: ordering = ['session'] def __str__(self): return f'{self.session} {self.term} {self.subject} {self.student}' def grade(self): if (self.ca1 + self.ca2 + self.exams) >=70: return "A" elif (self.ca1 + self.ca2 + self.exams) >= 60: return "B" elif (self.ca1 + self.ca2 + self.exams) >= 50: return "C" elif (self.ca1 + self.ca2 + self.exams) >= 45: return "D" elif (self.ca1 + self.ca2 + self.exams) >= 40: return "E" else: return "F" class StudentBehaviouralAssessment(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) session = models.ForeignKey(Session, on_delete=models.CASCADE) term = models.ForeignKey(Term, on_delete=models.CASCADE) student_class = models.ForeignKey(StudentClass, on_delete=models.CASCADE) conduct = models.IntegerField(default=0) punctuality = models.IntegerField(default=0) dedication = models.IntegerField(default=0) participation = models.IntegerField(default=0) hospitality = models.IntegerField(default=0) neatness = models.IntegerField(default=0) creativity = models.IntegerField(default=0) physical = models.IntegerField(default=0) def __str__(self): return f'{self.session} {self.term} {self.student_class} {self.student}' class signature(models.Model): classs = models.CharField(max_length=100) t_image = models.ImageField(upload_to='signs') p_image = models.ImageField(upload_to='signs') def __str__(self): return self.classs class sets(models.Model): h_image = models.ImageField(upload_to='setting_images') g_image = models.ImageField(upload_to='setting_images')<file_sep>from django.contrib import admin from src.models import Subject, StudentClass, Session, Term, Student, StudentResult, StudentBehaviouralAssessment, signature, sets # Register your models here. admin.site.register(Subject) admin.site.register(StudentClass) admin.site.register(Session) admin.site.register(Term) admin.site.register(Student) admin.site.register(StudentResult) admin.site.register(StudentBehaviouralAssessment) admin.site.register(signature) admin.site.register(sets)<file_sep># Generated by Django 3.1.2 on 2020-12-11 11:02 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('src', '0004_auto_20201211_1137'), ] operations = [ migrations.RenameField( model_name='signature', old_name='image', new_name='t_image', ), migrations.AddField( model_name='signature', name='p_image', field=models.ImageField(default=django.utils.timezone.now, upload_to='signs'), preserve_default=False, ), ] <file_sep># Generated by Django 3.1.2 on 2020-11-17 08:58 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Session', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('session_name', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='Student', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('student_name', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='StudentClass', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('class_name', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='Subject', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('subject_name', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='Term', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('term_name', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='StudentResult', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ca1', models.IntegerField(default=0)), ('ca2', models.IntegerField(default=0)), ('exams', models.IntegerField(default=0)), ('total', models.IntegerField(default=0)), ('subject_position', models.IntegerField(default=0)), ('session', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='src.session')), ('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='src.student')), ('student_class', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='src.studentclass')), ('subject', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='src.subject')), ('term', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='src.term')), ], options={ 'ordering': ['session'], }, ), migrations.AddField( model_name='student', name='student_class', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='src.studentclass'), ), ] <file_sep># Generated by Django 3.1.2 on 2020-12-11 11:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('src', '0005_auto_20201211_1202'), ] operations = [ migrations.CreateModel( name='sets', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('h_image', models.ImageField(upload_to='setting_images')), ('g_image', models.ImageField(upload_to='setting_images')), ], ), ]
34b31e515adb52361f34ed56b0b8643dc4299d15
[ "Python", "HTML" ]
9
Python
sudaniy/RynoB
80bd4dd4cc6c4c9ca56c1caefd6df7fc519a95c9
50f657b54624958b7424818c4552638ff4bd363a
refs/heads/master
<file_sep>// (C) Copyright 2012, <NAME> <<EMAIL>>. All // rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package apr1_crypt import "testing" type testData struct { salt, key, result string } func TestCrypt(t *testing.T) { data := []testData{ { "$apr1$$", "abcdefghijk", "$apr1$$NTjzQjNZnhYRPxN6ryN191", }, { "$apr1$an overlong salt$", "abcdefgh", "$apr1$an overl$iroRZrWCEoQojCkf6p8LC0", }, { "$apr1$12345678$", "Lorem ipsum dolor sit amet", "$apr1$12345678$/DpfgRGBHG8N0cbkmw0Fk/", }, { "$apr1$deadbeef$", "password", "$apr1$deadbeef$NWLhx1Ai4ScyoaAboTFco.", }, { "$apr1$$", "missing salt", "$apr1$$EcorjwkoQz4mYcksVEk6j0", }, { "$apr1$holy-moly-batman$", "1234567", "$apr1$holy-mol$/WX0350ZUEkvQkrrVJsrU.", }, { "$apr1$asdfjkl;$", "A really long password. " + "Longer than a password has any righ" + "t to be. Hey bub, don't mess with t" + "his password.", "$apr1$asdfjkl;$2MbDUb/Bj6qcIIf38PXzp0", }, } for i, d := range data { hash := Crypt(d.key, d.salt) if hash != d.result { t.Errorf("Test %d failed\nExpected: %s\n Saw: %s", i, d.result, hash) } } } func TestVerify(t *testing.T) { data := []string{ "password", "<PASSWORD>", "That's amazing! I've got the same combination on my luggage!", "And change the combination on my luggage!", " random spa c ing.", "94ajflkvjzpe8u3&*j1k513KLJ&*()", } for i, d := range data { hash := Crypt(d, "") if !Verify(d, hash) { t.Errorf("Test %d failed: %s", i, d) } } } func TestGenerateSalt(t *testing.T) { salt := GenerateSalt(0) if len(salt) != len(MagicPrefix)+1 { t.Errorf("Expected len 1, saw len %d", len(salt)) } for i := 1; i <= 8; i++ { salt = GenerateSalt(i) if len(salt) != len(MagicPrefix)+i { t.Errorf("Expected len %d, saw len %d", i, len(salt)) } } salt = GenerateSalt(9) if len(salt) != len(MagicPrefix)+8 { t.Errorf("Expected len 8, saw len %d", len(salt)) } } <file_sep>// (C) Copyright 2012, <NAME> <<EMAIL>>. All // rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sha256_crypt import "testing" func TestCrypt(t *testing.T) { data := [][]string{ { "$5$saltstring", "Hello world!", "$5$saltstring$5B8vYYiY.CVt1RlTTf8KbXBH3hsxY/G" + "NooZaBBGWEc5", }, { "$5$rounds=10000$saltstringsaltstring", "Hello world!", "$5$rounds=10000$saltstringsaltst$3xv.VbSHBb41" + "AL9AvLeujZkZRBAwqFMz2.opqey6IcA", }, { "$5$rounds=5000$toolongsaltstring", "This is just a test", "$5$rounds=5000$toolongsaltstrin$Un/5jzAHMgOGZ" + "5.mWJpuVolil07guHPvOW8mGRcvxa5", }, { "$5$rounds=1400$anotherlongsaltstring", "a very much longer text to encrypt. " + "This one even stretches over more" + "than one line.", "$5$rounds=1400$anotherlongsalts$Rx.j8H.h8HjED" + "GomFU8bDkXm3XIUnzyxf12oP84Bnq1", }, { "$5$rounds=77777$short", "we have a short salt string but not a short password", "$5$rounds=77777$short$JiO1O3ZpDAxGJeaDIuqCoEF" + "ysAe1mZNJRs3pw0KQRd/", }, { "$5$rounds=123456$asaltof16chars..", "a short string", "$5$rounds=123456$asaltof16chars..$gP3VQ/6X7UU" + "EW3HkBn2w1/Ptq2jxPyzV/cZKmF/wJvD", }, { "$5$rounds=10$roundstoolow", "the minimum number is still observed", "$5$rounds=1000$roundstoolow$yfvwcWrQ8l/K0DAWy" + "uPMDNHpIVlTQebY9l/gL972bIC", }, } for i, d := range data { hash := Crypt(d[1], d[0]) if hash != d[2] { t.Errorf("Test %d failed\nExpected: %s\n Saw: %s", i, d[2], hash) } } } func TestVerify(t *testing.T) { data := []string{ "<PASSWORD>", "<PASSWORD>", "That's amazing! I've got the same combination on my luggage!", "And change the combination on my luggage!", " random spa c ing.", "94ajflkvjzpe8u3&*j1k513KLJ&*()", } for i, d := range data { hash := Crypt(d, "") if !Verify(d, hash) { t.Errorf("Test %d failed: %s", i, d) } } } <file_sep>// (C) Copyright 2012, <NAME> <<EMAIL>>. All // rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package sha512_crypt implements Ulrich Drepper's SHA512-Crypt // password hashing algorithm. // // The specification for this algorithm can be found here: // http://www.akkadia.org/drepper/SHA-crypt.txt package sha512_crypt import ( "bytes" "crypto/rand" "crypto/sha512" "fmt" "strconv" . "github.com/ncw/pwhash/common" ) const ( MagicPrefix = "$6$" RandomSalt = "" RoundsDefault = 5000 RoundsMax = 999999999 RoundsMin = 1000 SaltLenMax = 16 SaltLenMin = 1 ) // GenerateSalt creates a random salt parameter string with the random // bytes being of the length provided, and the rounds parameter set as // specified. // // If the length is greater than SaltLenMax, a string of that length // will be returned instead. Similarly, if length is less than // SaltLenMin, a string of that length will be returned instead. // // If rounds is equal to RoundsDefault, then the 'rounds=' part of the // salt parameter string is elided. func GenerateSalt(length, rounds int) string { if length > SaltLenMax { length = SaltLenMax } else if length < SaltLenMin { length = SaltLenMin } rlen := (length * 6 / 8) if (length*6)%8 != 0 { rlen += 1 } if rounds < RoundsMin { rounds = RoundsMin } else if rounds > RoundsMax { rounds = RoundsMax } buf := make([]byte, rlen) rand.Read(buf) salt := Hash64(buf) if rounds == RoundsDefault { return fmt.Sprintf("%s%s", MagicPrefix, salt) } return fmt.Sprintf("%srounds=%d$%s", MagicPrefix, rounds, salt) } // Crypt takes key and salt strings and performs the SHA512-crypt // hashing algorithm on them, returning a full hash string suitable // for storage and later password verification. // // If the salt string is the value RandomSalt, a randomly-generated // salt parameter string will be generated with a length of SaltLenMax // and RoundsDefault number of rounds. func Crypt(keystr, saltstr string) string { var key, salt []byte var rounds, keyLen, saltLen int var roundsdef bool = false key = []byte(keystr) keyLen = len(key) if saltstr == "" { saltstr = GenerateSalt(SaltLenMax, RoundsDefault) } saltbytes := []byte(saltstr) if !bytes.HasPrefix(saltbytes, []byte(MagicPrefix)) { return "invalid prefix" } salttoks := bytes.Split(saltbytes, []byte{'$'}) numtoks := len(salttoks) if numtoks < 3 { return "invalid salt format" } if bytes.HasPrefix(salttoks[2], []byte("rounds=")) { roundsdef = true pr, err := strconv.ParseInt(string(salttoks[2][7:]), 10, 32) if err != nil { return "invalid rounds" } rounds = int(pr) if rounds < RoundsMin { rounds = RoundsMin } else if rounds > RoundsMax { rounds = RoundsMax } salt = salttoks[3] } else { rounds = RoundsDefault salt = salttoks[2] } if len(salt) > 16 { salt = salt[0:16] } saltLen = len(salt) B := sha512.New() B.Write(key) B.Write(salt) B.Write(key) Bsum := B.Sum(nil) A := sha512.New() A.Write(key) A.Write(salt) cnt := keyLen for ; cnt > 64; cnt -= 64 { A.Write(Bsum) } A.Write(Bsum[0:cnt]) for cnt = keyLen; cnt > 0; cnt >>= 1 { if (cnt & 1) != 0 { A.Write(Bsum) } else { A.Write(key) } } Asum := A.Sum(nil) P := sha512.New() for cnt = 0; cnt < keyLen; cnt++ { P.Write(key) } Psum := P.Sum(nil) Pseq := make([]byte, 0, keyLen) for cnt = keyLen; cnt > 64; cnt -= 64 { Pseq = append(Pseq, Psum...) } Pseq = append(Pseq, Psum[0:cnt]...) S := sha512.New() for cnt = 0; cnt < (16 + int(Asum[0])); cnt++ { S.Write(salt) } Ssum := S.Sum(nil) Sseq := make([]byte, 0, saltLen) for cnt = saltLen; cnt > 64; cnt -= 64 { Sseq = append(Sseq, Ssum...) } Sseq = append(Sseq, Ssum[0:cnt]...) Csum := Asum for cnt = 0; cnt < rounds; cnt++ { C := sha512.New() if (cnt & 1) != 0 { C.Write(Pseq) } else { C.Write(Csum) } if (cnt % 3) != 0 { C.Write(Sseq) } if (cnt % 7) != 0 { C.Write(Pseq) } if (cnt & 1) != 0 { C.Write(Csum) } else { C.Write(Pseq) } Csum = C.Sum(nil) } buf := bytes.NewBuffer(make([]byte, 0, 123)) buf.WriteString(MagicPrefix) if roundsdef { buf.WriteString(fmt.Sprintf("rounds=%d$", rounds)) } buf.Write(salt) buf.WriteByte('$') buf.Write(Hash64([]byte{ Csum[42], Csum[21], Csum[0], Csum[1], Csum[43], Csum[22], Csum[23], Csum[2], Csum[44], Csum[45], Csum[24], Csum[3], Csum[4], Csum[46], Csum[25], Csum[26], Csum[5], Csum[47], Csum[48], Csum[27], Csum[6], Csum[7], Csum[49], Csum[28], Csum[29], Csum[8], Csum[50], Csum[51], Csum[30], Csum[9], Csum[10], Csum[52], Csum[31], Csum[32], Csum[11], Csum[53], Csum[54], Csum[33], Csum[12], Csum[13], Csum[55], Csum[34], Csum[35], Csum[14], Csum[56], Csum[57], Csum[36], Csum[15], Csum[16], Csum[58], Csum[37], Csum[38], Csum[17], Csum[59], Csum[60], Csum[39], Csum[18], Csum[19], Csum[61], Csum[40], Csum[41], Csum[20], Csum[62], Csum[63], })) return buf.String() } // Verify hashes a key using the same salt parameters as the given // hash string, and if the results match, it returns true. func Verify(key, hash string) bool { nhash := Crypt(key, hash) if hash == nhash { return true } return false } <file_sep>// (C) Copyright 2012, <NAME> <<EMAIL>>. All // rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sha512_crypt import "testing" func TestCrypt(t *testing.T) { data := [][]string{ { "$6$saltstring", "Hello world!", "$6$saltstring$svn8UoSVapNtMuq1ukKS4tPQd8iKwSM" + "HWjl/O817G3uBnIFNjnQJuesI68u4OTLiBFdc" + "bYEdFCoEOfaS35inz1", }, { "$6$rounds=10000$saltstringsaltstring", "Hello world!", "$6$rounds=10000$saltstringsaltst$OW1/O6BYHV6B" + "cXZu8QVeXbDWra3Oeqh0sbHbbMCVNSnCM/Urj" + "mM0Dp8vOuZeHBy/YTBmSK6H9qs/y3RnOaw5v.", }, { "$6$rounds=5000$toolongsaltstring", "This is just a test", "$6$rounds=5000$toolongsaltstrin$lQ8jolhgVRVhY" + "4b5pZKaysCLi0QBxGoNeKQzQ3glMhwllF7oGD" + "ZxUhx1yxdYcz/e1JSbq3y6JMxxl8audkUEm0", }, { "$6$rounds=1400$anotherlongsaltstring", "a very much longer text to encrypt. " + "This one even stretches over more" + "than one line.", "$6$rounds=1400$anotherlongsalts$POfYwTEok97VW" + "cjxIiSOjiykti.o/pQs.wPvMxQ6Fm7I6IoYN3" + "CmLs66x9t0oSwbtEW7o7UmJEiDwGqd8p4ur1", }, { "$6$rounds=77777$short", "we have a short salt string but not a short password", "$6$rounds=77777$short$WuQyW2YR.hBNpjjRhpYD/if" + "Iw05xdfeEyQoMxIXbkvr0gge1a1x3yRULJ5CC" + "aUeOxFmtlcGZelFl5CxtgfiAc0", }, { "$6$rounds=123456$asaltof16chars..", "a short string", "$6$rounds=123456$asaltof16chars..$BtCwjqMJGx5" + "hrJhZywWvt0RLE8uZ4oPwcelCjmw2kSYu.Ec6" + "ycULevoBK25fs2xXgMNrCzIMVcgEJAstJeonj1", }, { "$6$rounds=10$roundstoolow", "the minimum number is still observed", "$6$rounds=1000$roundstoolow$kUMsbe306n21p9R.F" + "RkW3IGn.S9NPN0x50YhH1xhLsPuWGsUSklZt5" + "8jaTfF4ZEQpyUNGc0dqbpBYYBaHHrsX.", }, } for i, d := range data { hash := Crypt(d[1], d[0]) if hash != d[2] { t.Errorf("Test %d failed\nExpected: %s\n Saw: %s", i, d[2], hash) } } } func TestVerify(t *testing.T) { data := []string{ "<PASSWORD>", "<PASSWORD>", "That's amazing! I've got the same combination on my luggage!", "And change the combination on my luggage!", " random spa c ing.", "94ajflkvjzpe8u3&*j1k513KLJ&*()", } for i, d := range data { hash := Crypt(d, "") if !Verify(d, hash) { t.Errorf("Test %d failed: %s", i, d) } } } <file_sep>// (C) Copyright 2012, <NAME> <<EMAIL>>. All // rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package pwhash implements many common password hashing algorithms. package pwhash <file_sep>// (C) Copyright 2012, <NAME> <<EMAIL>>. All // rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package apr1_crypt implements the standard Unix MD5-Crypt algorithm // created by <NAME> for FreeBSD, and modified by the Apache // project. // // The only change from MD5-Crypt is the use of the magic constant // "$apr1$" instead of "$1$". The algorithms are otherwise identical. package apr1_crypt import ( "bytes" "crypto/md5" "crypto/rand" "fmt" . "github.com/ncw/pwhash/common" ) const ( MagicPrefix = "$apr1$" RandomSalt = "" SaltLenMax = 8 SaltLenMin = 1 // Real minimum is 0, but that isn't useful. ) // Generate a random salt parameter string of a given length. // // If the length is greater than SaltLenMax, a string of that length // will be returned instead. Similarly, if length is less than // SaltLenMin, a string of that length will be returned instead. func GenerateSalt(length int) string { if length > SaltLenMax { length = SaltLenMax } else if length < SaltLenMin { length = SaltLenMin } rlen := (length * 6 / 8) if (length*6)%8 != 0 { rlen += 1 } buf := make([]byte, rlen) rand.Read(buf) salt := Hash64(buf) return fmt.Sprintf("%s%s", MagicPrefix, salt[:length]) } // Crypt takes key and salt strings and performs the MD5-Crypt hashing // algorithm on them, returning a full hash string suitable for storage // and later password verification. // // If the salt string is the value RandomSalt, a randomly-generated salt // parameter string will be generated of length SaltLenMax. func Crypt(keystr, saltstr string) string { var key, salt []byte var keyLen, saltLen int key = []byte(keystr) keyLen = len(key) if saltstr == "" { saltstr = GenerateSalt(SaltLenMax) } saltbytes := []byte(saltstr) if !bytes.HasPrefix(saltbytes, []byte(MagicPrefix)) { return "invalid magic prefix" } salttoks := bytes.Split(saltbytes, []byte{'$'}) numtoks := len(salttoks) if numtoks < 3 { return "invalid salt format" } else { salt = salttoks[2] } if len(salt) > 8 { salt = salt[0:8] } saltLen = len(salt) B := md5.New() B.Write(key) B.Write(salt) B.Write(key) Bsum := B.Sum(nil) A := md5.New() A.Write(key) A.Write([]byte(MagicPrefix)) A.Write(salt) cnt := keyLen for ; cnt > 16; cnt -= 16 { A.Write(Bsum) } A.Write(Bsum[0:cnt]) for cnt = keyLen; cnt > 0; cnt >>= 1 { if (cnt & 1) == 0 { A.Write(key[0:1]) } else { A.Write([]byte{0}) } } Asum := A.Sum(nil) Csum := Asum for round := 0; round < 1000; round++ { C := md5.New() if (round & 1) != 0 { C.Write(key) } else { C.Write(Csum) } if (round % 3) != 0 { C.Write(salt) } if (round % 7) != 0 { C.Write(key) } if (round & 1) == 0 { C.Write(key) } else { C.Write(Csum) } Csum = C.Sum(nil) } buf := make([]byte, 0, 23+len(MagicPrefix)+saltLen) buf = append(buf, MagicPrefix...) buf = append(buf, salt...) buf = append(buf, '$') buf = append(buf, Hash64([]byte{ Csum[12], Csum[6], Csum[0], Csum[13], Csum[7], Csum[1], Csum[14], Csum[8], Csum[2], Csum[15], Csum[9], Csum[3], Csum[5], Csum[10], Csum[4], Csum[11], })...) return string(buf) } // Verify hashes a key using the same salt parameters as the given // hash string, and if the results match, it returns true. func Verify(key, hash string) bool { nhash := Crypt(key, hash) if hash == nhash { return true } return false }
fa860a891e2355652e7e86a8acf1bbc001cc4dda
[ "Go" ]
6
Go
Nanitor/pwhash
b2a8830c6a99b38af20d8de1e20033c4b27e3434
b74e45378737731b70379cdfae9b3490c251c936
refs/heads/master
<file_sep># cpit405-assignment-4<file_sep>// 1. Array declaration var images = [['title', 'points', 'views', 'src'], ['title', 'points', 'views', 'src'], ['title', 'points', 'views', 'src'], ['title', 'points', 'views', 'src'], ['title', 'points', 'views', 'src'], ]; var dropList = document.getElementById("sort"); // 2. API var flag = true; function doClick() { dropList.value = "none"; var searchTerm = document.getElementById('search').value; var xhttp = new XMLHttpRequest(); // When the request is successful, finished, and response is ready, execute these function xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var resObj = JSON.parse(xhttp.responseText); for (var i =0; i<5; i++) { images[i].src= resObj.data[i].link; images[i].title= resObj.data[i].title; images[i].points= resObj.data[i].points; images[i].views= resObj.data[i].views; // images[i].dateUploaded= resObj.data[i].Date; } if(flag){ createDomElem(); flag = false; } else{ reCreateDomElem(); } } } // Send an asynchronous HTTP GET request to the given end point (url) xhttp.open("GET", "https://api.imgur.com/3/gallery/search/top/all/1?q=" + searchTerm, true); xhttp.setRequestHeader("Authorization", "Client-ID f0993144ea9ba7b") xhttp.send(); } // 3. Sort your array (images) by the selected key function sortElements() { if(dropList.value != "none"){ if(dropList.value == "title") images.sort(title); if(dropList.value == "points") images.sort(points); if(dropList.value == "views") images.sort(views); // if(dropList.value == "recent"){ // images.sort(dates); // } reCreateDomElem(); } } function title(a, b) { var nameA = a.title.toLowerCase() var nameB = b.title.toLowerCase(); if (nameA < nameB) return -1; if (nameA > nameB) return 1; return 0; } function points(a,b) { if (a.points < b.points) return 1; if (a.points > b.points) return -1; return 0; } function views(a,b) { if (a.views < b.views) return 1; if (a.views > b.views) return -1; return 0; } // function dates(a, b) { // var dateA = new Date(a.dateUploaded); // var dateB = new Date(b.dateUploaded); // return dateB - dateA; // } // 4. Regenerate your HTML elements using the new sorted array function createDomElem(){ var ulElement = document.getElementById("my-list"); for(var i=0; i<images.length; i++){ var liElement1=document.createElement("li"); var imageElemnt = document.createElement("IMG"); var div = document.createElement("div"); div.style.background = "brown"; div.style.color = "white"; div.innerHTML = images[i].title+'<br>'+ 'Points: '+images[i].points+ '&nbsp;&nbsp;&nbsp;&nbsp; Views: '+images[i].views; imageElemnt.src = images[i].src; liElement1.appendChild(imageElemnt); liElement1.appendChild(div); ulElement.appendChild(liElement1); } } function reCreateDomElem(){ var ulElement = document.getElementById("my-list"); for(var i=0; i<images.length; i++){ var liElement1=document.createElement("li"); var imageElemnt = document.createElement("IMG"); var div = document.createElement("div"); div.style.background = "brown"; div.style.color = "white"; div.innerHTML = images[i].title+'<br>'+ 'Points: '+images[i].points+ '&nbsp;&nbsp;&nbsp;&nbsp; Views: '+images[i].views; imageElemnt.src = images[i].src; liElement1.appendChild(imageElemnt); liElement1.appendChild(div); ulElement.replaceChild(liElement1, ulElement.children[i]); } }
072511477c984b22dda1e57ce37c721a8c0eb5b4
[ "Markdown", "JavaScript" ]
2
Markdown
Ziad-7/cpit405-assignment-4
2a8302a9fa075e091bfbee18c9d3bdb5671e6a3a
acb0b0c11a938b3ca0348fc185aa2e970f869920
refs/heads/master
<repo_name>y00j/todo-frontend<file_sep>/src/App.js import './App.css'; import React, {Component} from 'react' const BASE_URL = 'http://localhost:8080/api/' class App extends Component{ state = { incomplete: [], complete: [], newTask: "" } componentDidMount() { const url = `${BASE_URL}todos`; console.log(url) fetch(url) .then((result) => result.json()) .then(({incomplete, complete}) => { this.setState({ incomplete, complete }) }) } incompleteTodos() { const { incomplete } = this.state; const result = incomplete.map((task, idx) => <li key={idx}> <input onChange={(e) => {this.handleRadioSelect(idx, e)}} type="radio" value={idx}/> <label>{task}</label> </li> ); return <ul>{result}</ul>; } completeTodos() { const {complete} = this.state; const result = complete.map((task, idx) => <li key={idx}>{task}</li>); return <ul>{result}</ul> } handleRadioSelect(idx, e) { const {incomplete, complete} = this.state; const removed = incomplete.splice(idx, 1); complete.push(...removed); const url = `${BASE_URL}updateTodos`; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ incomplete, complete }) }) .then(res => res.json()) .then(({incomplete, complete}) => { this.setState({incomplete, complete}) e.target.checked = false; }) } handleChange(event) { this.setState({ newTask: event.target.value }); } handleClick() { const {incomplete, complete} = this.state; incomplete.unshift(this.state.newTask); const url = `${BASE_URL}updateTodos`; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ incomplete, complete }) }) .then(res => res.json()) .then(({incomplete, complete}) => { this.setState({incomplete, complete, newTask: ""}) }) } render() { return ( <div className="App"> <h1>A Crappy Todo REACT App</h1> <input type="text" value={this.state.newTask} placeholder="add a task" onChange={(event) => this.handleChange(event)} ></input> <button onClick={() => this.handleClick()}>add</button> <h2>Tasks:</h2> {this.incompleteTodos()} <h2>Complete:</h2> {this.completeTodos()} </div> ); } } export default App;
ad003bf2b6805f05dbcf1306b08f2a4cc54f9269
[ "JavaScript" ]
1
JavaScript
y00j/todo-frontend
cb4cf92588d0aea2e3b941a74f08bbac67502ba8
70b04ab658337c9397aeb4c395a035d844a4f18a
refs/heads/master
<repo_name>rbalaga/node_examples<file_sep>/NodeMongoDB/server.js const mongoClient = require('mongodb').MongoClient; const assert = require('assert'); const operations = require('./operations'); var server = 'mongodb://testuser:<EMAIL>@<EMAIL>:33558/testapp'; const dbname = 'testapp'; mongoClient.connect(server).then((client) => { console.log('Connected to server successfully.'); const db = client.db(dbname); const collection = db.collection('dishes'); //Callback hell is implemented. operations.insertDocument(db, { "name": "rammohan1", "description": "testing from coursera method." }, collection) .then((result) => { console.log('Inserted document : \n' + JSON.stringify(result.ops) + '\n'); return operations.findDocuments(db, collection); }) .then((docs) => { console.log('Found: \n' + JSON.stringify(docs) + '\n'); return operations.updateDocument(db, { "name": "rammohan1" }, { "education": "graduate" }, collection); }) .then((result) => { console.log("Updated document :", JSON.stringify(result.result) + '\n'); return operations.findDocuments(db, collection); }) .then((docs) => { console.log("Found documents : \n", JSON.stringify(docs)); return db.dropCollection('dishes'); }) .then((res) => { client.close(); }) .catch((error) => { console.log("Error : " + error) }); }) .catch((error) => { console.log("Error : " + error) }); <file_sep>/NodeMongoDB/operations.js const assert = require('assert'); exports.insertDocument = (db, document, collection, callback) => { return collection.insertOne(document); }; exports.findDocuments = (db, collection, callback) => { return collection.find({}).toArray(); }; exports.updateDocument = (db, document, update, collection, callback) => { return collection.updateOne(document, {$set : update}, null); }; exports.deleteDocument = (db, document, collection, callback) => { return collection.deleteOne(document); };<file_sep>/NodeMongoose/server.js 'use strict'; var mongoose = require('mongoose'); var Dishes = require('./models/Dishes'); var dbUrl = 'mongodb://testuser:<EMAIL>:33558/testapp'; const conn = mongoose.connect(dbUrl); conn.then((db) => { console.log('Connected to mongoose server..'); Dishes.create({ name: "Uthappizzaa", description: "Its not at all good taste" }) .then((dish) => { console.log(dish); return Dishes.findByIdAndUpdate(dish._id, { $set: { description : "Updated test description" } },{ new : true }) .exec(); }) .then((dish) => { console.log(dish); dish.comments.push({ rating: 5, comment: "Test comment", author: '<NAME>' }); return dish.save(); }) .then((dish) => { console.log(dish); return db.collection('dishes').drop(); }) .then(() => { return db.close(); }) .catch((err) => { console.log('Error Occured : ' + err.message); }); }) <file_sep>/NodeExpresssGenerator/README.md # NodeExpresssGenerator <file_sep>/NodeExample/README.md # NodeExample ### HTTP Verbs 1. GET 1. POST 1. DELETE 1. PUT 1. HEAD 1. TRACE 1. OPTIONS 1. CONNECT ### HTTP Response codes 200 - ok 201 - created 301 - moved permanently 304 - not modified 400 - Bad request 401 - Unautherized 403 - Foridden 404 - Not Found 422 - Unprocessable entry 500 - Internal server error 505 - HTTP version not supported ### HTTP Response XML - eXtensible markup language JSON - * Javascript Object Notation http://www.json.org * Self describing * Easy to understand * Ordered list of values ## HTTP mod ### Node HTTP Module `const http = require('http');` ### creating server `const server = http.createServer((req, res) => { ... });` ### Starting server `server.listen(port, ...);` ### Reading from request and setting response req.headers, req.body res.setHeader('Content-Type', 'text/html'); res.statusCode = 200; res.write('Hello'); res.end('<html><body><h1>Hello World</h1></body></html>'); ## Node PATH module ` const path = require('path'); path.resolve('./public' + fileUrl); path.extname(filePath); ` ## Node FS module ` const fs = require('fs') fs.exists(filepath, function(exists){...}) fs.createReadStream(filePath).pipe(res); ` <file_sep>/NodeMongoose/README.md # NodeMongoose <file_sep>/NodeExample/server.js var rect = require('./rect'); var solveRect = (x, y) => { rect(x, y, (err, rectangle) => { if (err) { console.log('ERROR: ' + err.message); } else { console.log('Rect area : ' + rectangle.area()); console.log('Rect perimeter : ' + rectangle.perimeter()); } }); console.log('This is after rectangle call'); }; solveRect(2, 4); solveRect(9, 2); solveRect(0, 2); solveRect('a', 1);<file_sep>/Node-Express/index.js //'use strict'; var express = require('express'); //webserver var http = require('http'); var morgan = require('morgan'); //logs server requests. var bodyParser = require('body-parser'); var dishRouter = require('./routes/dishRouter'); var promosRouter = require('./routes/promoRouter'); var leadersRouter = require('./routes/leaderRouter'); const port = 3421; //process.env.PORT const hostname = 'localhost'; const app = express(); app.use(morgan('dev')); //for using only in development time for logging the sever requests. app.use(express.static(__dirname + '/public')); app.use(bodyParser.json()); app.use('/dishes', dishRouter); app.use('/promotions', promosRouter); app.use('/leaders', leadersRouter); app.use((req, res, next) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); res.end('<html><body><h1>Welcome to express server</h1></body></html>'); }); const server = http.createServer(app); server.listen(port, hostname, () => { console.log(`Server is running at http://${hostname}:${port}`); }); <file_sep>/NodeMongoDB/README.md # NodeMongoDB
92deacc575605d46131538f10a816e3e1f4dc137
[ "JavaScript", "Markdown" ]
9
JavaScript
rbalaga/node_examples
84c74f972056d15f063841196701ba88b6852299
b540decc921c66de0defabb5b01e04f7514bf78b
refs/heads/master
<repo_name>Aswinikumar02/pipeline<file_sep>/test.js var google=require('google'); var https=require("https"); var url="https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Washington,DC&destinations=New+York+City,NY&key=<KEY>"; var request=https.get(url,function(response) { response.on("data",function(chunk) { console.log(JSON.parse(chunk)); }); });
3036ecdc752a2b98a9d2e20ebf4b149394400328
[ "JavaScript" ]
1
JavaScript
Aswinikumar02/pipeline
2b97c5cc224a57049169837b7db8252d46c9403a
b95cefbd8e80b10f07448d3d2764e2d7d3eaed15
refs/heads/master
<repo_name>DonGiulio/coronatest<file_sep>/src/Donate.js import React from 'react'; import { Alert } from 'reactstrap'; import { useTranslation } from 'react-i18next'; import ReactMarkdown from 'react-markdown'; const Donate = () => { const [t] = useTranslation(); return( <Alert color="warning"> <ReactMarkdown source={ t('common:main.donate.text') } /> <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top"> <input type="hidden" name="cmd" value="_donations" /> <input type="hidden" name="business" value="JSH62QG97XDUN" /> <input type="hidden" name="currency_code" value="EUR" /> <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" border="0" name="submit" title="PayPal - The safer, easier way to pay online!" alt="Donate with PayPal button" /> <img alt="" border="0" src="https://www.paypal.com/en_IT/i/scr/pixel.gif" width="1" height="1" /> </form> </Alert> )} export default Donate;<file_sep>/test/calculations-test.js import test from 'tape'; import {calculatePoints, assignCategoriesToAnswers} from "../src/calculations"; import {categories, questions, answers} from './fixtures'; import rewire from "rewire"; test("totalForCategory", (t) => { const md = rewire("../src/calculations.js") const totalForCategory = md.__get__("totalForCategory"); t.ok(totalForCategory, "totalForCategory should be ok"); const category = categories[0]; const total = totalForCategory(questions, category); t.ok(total, "total should be ok"); t.equals(total, 100, "total should be 100"); t.end() }) test("totalsByCategory", (t) => { const md = rewire("../src/calculations.js") const totalsByCategory = md.__get__("totalsByCategory"); t.ok(totalsByCategory, "totalsByCategory should be ok"); const totals = totalsByCategory(questions, categories); t.ok(totals, "totals should be ok") t.equals(totals["cat1"], 100, "cat1 total should be 100, was " + totals["cat1"]); t.equals(totals["cat2"], 30, "cat2 total should be 30, was " + totals["cat2"]); t.end(); }) test("countAnswersInCategory", (t) => { const md = rewire("../src/calculations.js") const countAnswersInCategory = md.__get__("countAnswersInCategory"); t.ok(countAnswersInCategory, "countAnswersInCategory is an object"); const category = categories[0]; const total = countAnswersInCategory(answers, category); t.ok(total, "total is not ok") t.equals(total, 30, "cat1 total should be 30, was " + total); t.end(); }) test("answersByCategory", (t) => { const md = rewire("../src/calculations.js") const answersByCategory = md.__get__("answersByCategory"); t.ok(answersByCategory, "answersByCategory is an object"); const totals = answersByCategory(answers, categories); t.ok(totals, "totals should be ok") t.equals(totals["cat1"], 30, "cat1 total should be 30 was " + totals["cat1"]); t.equals(totals["cat2"], 12, "cat2 total should be 12 was " + totals["cat2"]); t.end(); }) test("calculatePoints", (t) => { const points = calculatePoints(questions, answers, categories); t.ok(points, "points should be ok"); t.equal(Object.keys(points).length, 2, "categories counted " + Object.keys(points).length); t.equal(points["cat1"], 30, "points of cat1 was be 30, was " + points["cat1"]); t.equal(points["cat2"], 40, "points of cat2 should be 40, was " + points["cat2"]); t.end() });<file_sep>/src/ShowTest.js import React from 'react'; import PropTypes from 'prop-types'; import Question from "./Question"; import {Alert, Button, Form, FormGroup} from 'reactstrap'; import { withTranslation } from 'react-i18next'; const MissingQuestion = (({t, question, missingQuestions}) => { if(new Set(missingQuestions).has(question.id)){ return <Alert color="warning">{ t('common:q.questions.required') }</Alert> } else { return(null) } }) class ShowTest extends React.Component { render(){ return( <Form onSubmit={this.props.handleSubmit}> { Object.values(this.props.questions).map((question, index) => <FormGroup key={index+1}> <MissingQuestion t={this.props.t} question={question} missingQuestions={this.props.missingQuestions}/> <Question question={question} addAnswer={this.props.addAnswer} removeAnswer={this.props.removeAnswer} index={index + 1}/> <hr/> </FormGroup>) } <Button color="primary" type="submit">Results</Button> </Form> ) } } ShowTest.propTypes = { t: PropTypes.func, questions: PropTypes.array, missingQuestions: PropTypes.array, handleSubmit: PropTypes.func, addAnswer: PropTypes.func, removeAnswer: PropTypes.func, }; export default withTranslation()(ShowTest); <file_sep>/src/inspect.js function censor(censor) { var i = 0; return function(key, value) { if ( i !== 0 && typeof censor === "object" && typeof value === "object" && censor === value ) { return "[Circular]"; } // seems to be a harded maximum of 30 serialized objects? // if (i >= 30) { // return "[Unknown]"; // } // so we know we aren't using the original object anymore ++i; return value; }; } const inspect = (object, name = null) => { let type = {}.toString.call(object).match(/\s([a-zA-Z]+)/)[1].toLowerCase(); // let json = JSON.stringify(object, null, 2); // let json = stringify(object, null, 2); let json = JSON.stringify(object, censor(object), 2); // let json = stringify(object, null, 2); console.log(`Inspecting: ${name}, TYPE: ${type} --- JSON: ${json}`); }; export default inspect; <file_sep>/src/categories.js const categories = [ { "id": 1, "category": "common:q.category.conditions.name", "answers": [ { "id": 1, "min_points": 0, "max_points": 40, "title": "common:q.category.low", "color": "info", "description": "common:q.category.conditions.low" }, { "id": 2, "min_points": 40, "max_points": 60, "title": "common:q.category.mid", "color": "warning", "description": "common:q.category.conditions.mid" }, { "id": 3, "min_points": 61, "max_points": 100, "title": "common:q.category.high", "color": "danger", "description": "common:q.category.conditions.high" } ] }, { "id": 2, "category": "common:q.category.exposure.name", "answers": [ { "id": 1, "min_points": 0, "max_points": 40, "title": "common:q.category.low", "color": "info", "description": "common:q.category.exposure.low" }, { "id": 2, "min_points": 40, "max_points": 60, "title": "common:q.category.mid", "color": "warning", "description": "common:q.category.exposure.mid" }, { "id": 3, "min_points": 61, "max_points": 100, "title": "common:q.category.high", "color": "danger", "description": "common:q.category.exposure.high" } ] }, { "id": 3, "category": "common:q.category.gravity.name", "answers": [ { "id": 1, "min_points": 0, "max_points": 40, "title": "common:q.category.low", "color": "info", "description": "common:q.category.gravity.low" }, { "id": 2, "min_points": 40, "max_points": 60, "title": "common:q.category.mid", "color": "warning", "description": "common:q.category.gravity.mid" }, { "id": 3, "min_points": 61, "max_points": 100, "title": "common:q.category.high", "color": "danger", "description": "common:q.category.gravity.high" } ] } ] export default categories;<file_sep>/src/Answer.js import React from 'react'; import PropTypes from 'prop-types'; import {Label} from 'reactstrap'; import { withTranslation } from 'react-i18next'; class Answer extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); } handleChange(event){ if(event.target.checked){ this.props.addAnswer(this.props.answer, this.props.question); } else { this.props.removeAnswer(this.props.answer) } } render(){ const {t} = this.props; return ( <div> <Label> <input name={this.props.question.id} type={this.props.question.type} onChange={this.handleChange}/> &nbsp;{t(this.props.answer.answer)} </Label> </div> ) } } Answer.propTypes = { t: PropTypes.func, question: PropTypes.object, answer: PropTypes.object, type: PropTypes.string, addAnswer: PropTypes.func, removeAnswer: PropTypes.func }; export default withTranslation()(Answer);<file_sep>/src/Description.js import React from 'react'; import { Alert } from 'reactstrap'; import { useTranslation } from 'react-i18next'; import ReactMarkdown from 'react-markdown'; const Description = () => { const [t] = useTranslation(); return(<div> <ReactMarkdown source={t('common:main.description.message')} /> <Alert color="danger"> <ReactMarkdown source={ t('common:main.description.alert') } /> </Alert> </div>)} export default Description;<file_sep>/src/Share.js import React from 'react'; import { Alert } from 'reactstrap'; import { useTranslation } from 'react-i18next'; import ReactMarkdown from 'react-markdown'; import Facebook from 'react-sharingbuttons/dist/buttons/Facebook'; import Twitter from 'react-sharingbuttons/dist/buttons/Twitter'; import Email from 'react-sharingbuttons/dist/buttons/Email'; import Reddit from 'react-sharingbuttons/dist/buttons/Reddit'; const Share = () => { const [t] = useTranslation(); const url = "https://covid19.rorobea.com/" return( <Alert color="success"> <ReactMarkdown source={t('common:main.share.text')} /> <Email url={url} subject={ t('common:main.share.email.subject') } /> <Facebook url={url} /> <Twitter url={url} shareText={ t('common:main.share.twitter.shareText') } /> <Reddit url={url} /> </Alert> )} export default Share;<file_sep>/src/App.js import React from 'react'; import PropTypes from 'prop-types'; import './App.css'; import {Navbar} from 'reactstrap'; import { withTranslation } from 'react-i18next'; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; import Test from "./Test"; import Privacy from "./Privacy"; import Donate from "./Donate"; import Share from "./Share"; import Language from "./Language"; import Article from './pages/Article'; class App extends React.Component { componentDidMount(){ console.log("component did mount"); async function fetchData () { try { const response = await fetch('/access', {method: 'PUT' }); console.log("response received", response); } catch (err) { console.log(err.message); } } fetchData() console.log("componend finished didmounting") } render(){ return ( <div className="App container"> <Router> <Navbar color="light" light expand="md"> <nav> <Link to="/" className="navbar-brand" > <h1> <img src="/logo.png" width="50px" height="50px" className="d-inline-block align-top" alt="Logo" /> { this.props.t('common:main.title') } </h1> </Link> <Link to="/" className="nav-item" >Test</Link> </nav> </Navbar> <Language className="float-right"/> <hr/> <Privacy /> <Donate /> <Share /> {/* A <Switch> looks through its children <Route>s and renders the first one that matches the current URL. */} <Switch> <Route path="/article"> <Article /> </Route> <Route path="/"> <Test /> </Route> </Switch> </Router> <Donate /> <Share /> </div> ) } } Test.propTypes = { t: PropTypes.func }; export default withTranslation()(App); <file_sep>/src/Test.js import React from 'react'; import { useTranslation } from 'react-i18next'; import questions from "./questions"; import categories from "./categories"; import DoTest from "./DoTest"; const Test = () => { const [t] = useTranslation(); return ( <div className="Test"> <h1>{ t('common:main.test.title') }</h1> <DoTest questions={questions} categories={categories}/> </div> ); } export default Test; <file_sep>/src/questions.js const questions = [ { "id": "general_conditions", "question": "common:q.questions.general_conditions.question", "category": "common:q.category.conditions.name", "type": "radio", "points": 100, "answers": [ { "id": "general_conditions.feel_great", "answer": "common:q.questions.general_conditions.feel_great", "value": 0 }, { "id": "general_conditions.exhausted", "answer": "common:q.questions.general_conditions.exhausted", "value": 200 } ] }, { "id": "breathing", "question": "common:q.questions.breathing.question", "category": "common:q.category.conditions.name", "type": "radio", "points": 100, "answers": [ { "id": "breathing.well", "answer": "common:q.questions.breathing.well", "value": 0 }, { "id": "breathing.hard", "answer": "common:q.questions.breathing.hard", "value": 150 } ] }, { "id": "pains", "question": "common:q.questions.pains.question", "category": "common:q.category.conditions.name", "type": "radio", "points": 100, "answers": [ { "id": "pains.hard", "answer": "common:q.questions.pains.none", "value": 150 }, { "id": "pains.well", "answer": "common:q.questions.pains.have", "value": 0 } ] }, { "id": "headache", "question": "common:q.questions.headache.question", "category": "common:q.category.conditions.name", "type": "radio", "points": 100, "answers": [ { "id": "headache.none", "answer": "common:q.questions.headache.none", "value": 0 }, { "id": "headache.have", "answer": "common:q.questions.headache.have", "value": 150 } ] }, { "id": "chills", "question": "common:q.questions.chills.question", "category": "common:q.category.conditions.name", "type": "radio", "points": 100, "answers": [ { "id": "chills.hard", "answer": "common:q.questions.chills.none", "value": 150 }, { "id": "chills.well", "answer": "common:q.questions.chills.have", "value": 0 } ] }, { "id": "perception", "question": "common:q.questions.perception.question", "category": "common:q.category.conditions.name", "type": "radio", "points": 100, "answers": [ { "id": "perception.ok", "answer": "common:q.questions.perception.ok", "value": 0 }, { "id": "perception.no_smell", "answer": "common:q.questions.perception.no_smell", "value": 80 } ] }, { "id": "temperature", "question": "common:q.questions.temperature.question", "category": "common:q.category.conditions.name", "type": "radio", "points": 100, "answers": [ { "id": "temperature.none", "answer": "common:q.questions.temperature.none", "value": 0 }, { "id": "temperature.mid", "answer": "common:q.questions.temperature.mid", "value": 150 }, { "id": "temperature.high", "answer": "common:q.questions.temperature.high", "value": 300 }, ] }, { "id": "cough", "question": "common:q.questions.cough.question", "category": "common:q.category.conditions.name", "type": "radio", "points": 100, "answers": [ { "id": "cough.none", "answer": "common:q.questions.cough.none", "value": 0 }, { "id": "cough.wet", "answer": "common:q.questions.cough.wet", "value": 60 }, { "id": "cough.dry", "answer": "common:q.questions.cough.dry", "value": 160 } ] }, { "id": "mucus", "question": "common:q.questions.mucus.question", "category": "common:q.category.conditions.name", "type": "radio", "points": 100, "answers": [ { "id": "mucus.none", "answer": "common:q.questions.mucus.none", "value": 0 }, { "id": "mucus.have", "answer": "common:q.questions.mucus.have", "value": 90 } ] }, { "id": "throat", "question": "common:q.questions.throat.question", "category": "common:q.category.conditions.name", "type": "radio", "points": 100, "answers": [ { "id": "throat.ok", "answer": "common:q.questions.throat.ok", "value": 0 }, { "id": "throat.itches", "answer": "common:q.questions.throat.itches", "value": 20 }, { "id": "throat.aches", "answer": "common:q.questions.throat.aches", "value": 60 } ] }, { "id": "conditions", "question": "common:q.questions.conditions.question", "category": "common:q.category.gravity.name", "type": "radio", "points": 100, "answers": [ { "id": "conditions.none", "answer": "common:q.questions.conditions.none", "value": 0 }, { "id": "conditions.have", "answer": "common:q.questions.conditions.have", "value": 130 } ] }, { "id": "hypertension", "question": "common:q.questions.hypertension.question", "category": "common:q.category.gravity.name", "type": "radio", "points": 100, "answers": [ { "id": "hypertension.none", "answer": "common:q.questions.hypertension.none", "value": 0 }, { "id": "hypertension.have", "answer": "common:q.questions.hypertension.have", "value": 100 } ] }, { "id": "cardiovascular", "question": "common:q.questions.cardiovascular.question", "category": "common:q.category.gravity.name", "type": "radio", "points": 100, "answers": [ { "id": "cardiovascular.none", "answer": "common:q.questions.cardiovascular.none", "value": 0 }, { "id": "cardiovascular.have", "answer": "common:q.questions.cardiovascular.have", "value": 100 } ] }, { "id": "cholesterol", "question": "common:q.questions.cholesterol.question", "category": "common:q.category.gravity.name", "type": "radio", "points": 100, "answers": [ { "id": "cholesterol.none", "answer": "common:q.questions.cholesterol.none", "value": 0 }, { "id": "cholesterol.have", "answer": "common:q.questions.cholesterol.have", "value": 100 } ] }, { "id": "age", "question": "common:q.questions.age.question", "category": "common:q.category.gravity.name", "type": "radio", "points": 100, "answers": [ { "id": "age.40", "answer": "common:q.questions.age.40", "value": 40 }, { "id": "age.60", "answer": "common:q.questions.age.60", "value": 80 }, { "id": "age.80", "answer": "common:q.questions.age.80", "value": 120 }, { "id": "age.100", "answer": "common:q.questions.age.100", "value": 170 } ] }, { "id": "gender", "question": "common:q.questions.gender.question", "category": "common:q.category.gravity.name", "type": "radio", "points": 100, "answers": [ { "id": "gender.female", "answer": "common:q.questions.gender.female", "value": 60 }, { "id": "gender.male", "answer": "common:q.questions.gender.male", "value": 120 } ] }, { "id": "location", "question": "common:q.questions.location.question", "category": "common:q.category.exposure.name", "type": "radio", "points": 100, "answers": [ { "id": "location.remote", "answer": "common:q.questions.location.remote", "value": 20 }, { "id": "location.no", "answer": "common:q.questions.location.no", "value": 40 }, { "id": "location.some", "answer": "common:q.questions.location.some", "value": 100 }, { "id": "location.great", "answer": "common:q.questions.location.great", "value": 150 } ] }, { "id": "precautions", "question": "common:q.questions.precautions.question", "category": "common:q.category.exposure.name", "type": "checkbox", "points": -80, "answers": [ { "id": "precautions.mask", "answer": "common:q.questions.precautions.mask", "value": -10 }, { "id": "precautions.gloves", "answer": "common:q.questions.precautions.gloves", "value": -10 }, { "id": "precautions.distance", "answer": "common:q.questions.precautions.distance", "value": -50 }, { "id": "precautions.wash_hands_quick", "answer": "common:q.questions.precautions.wash_hands_quick", "value": -30 }, { "id": "precautions.wash_hands_thoroughly", "answer": "common:q.questions.precautions.wash_hands_thoroughly", "value": -80 } ] }, { "id": "contacts", "question": "common:q.questions.contacts.question", "category": "common:q.category.exposure.name", "type": "radio", "points": 100, "answers": [ { "id": "contacts.normal", "answer": "common:q.questions.contacts.normal", "value": 60 }, { "id": "contacts.crowd", "answer": "common:q.questions.contacts.crowd", "value": 180 }, { "id": "contacts.infected_no_protection", "answer": "common:q.questions.contacts.infected_no_protection", "value": 180 }, { "id": "contacts.infected_with_protection", "answer": "common:q.questions.contacts.infected_with_protection", "value": 120 }, { "id": "contacts.distanza", "answer": "common:q.questions.contacts.no_one", "value": 0 } ] }, { "id": "immuno", "question": "common:q.questions.immuno.question", "category": "common:q.category.exposure.name", "type": "radio", "points": 100, "answers": [ { "id": "immuno.normal", "answer": "common:q.questions.immuno.normal", "value": 30 }, { "id": "immuno.depressed", "answer": "common:q.questions.immuno.depressed", "value": 150 } ] }, { "id": "family", "question": "common:q.questions.family.question", "category": "common:q.category.exposure.name", "type": "radio", "points": 100, "answers": [ { "id": "family.safe", "answer": "common:q.questions.family.safe", "value": 20 }, { "id": "family.exposed", "answer": "common:q.questions.family.exposed", "value": 300 } ] } ] export default questions;<file_sep>/src/Question.js import React from 'react'; import PropTypes from 'prop-types'; import { useTranslation } from 'react-i18next'; import Answer from "./Answer"; const Question = (props) => { const [t] = useTranslation(); return( <div> <strong>{props.index}</strong>. {t(props.question.question)}: { props.question.answers.map((answer) => <Answer key={answer.id} question={props.question} answer={answer} addAnswer={props.addAnswer} removeAnswer={props.removeAnswer} />) } </div>) } Question.propTypes = { question: PropTypes.object, addAnswer: PropTypes.func, removeAnswer: PropTypes.func, index: PropTypes.number }; export default Question;<file_sep>/src/Results.js import React from 'react'; import PropTypes from 'prop-types'; import { useTranslation } from 'react-i18next'; import ReactMarkdown from 'react-markdown'; import {Button, Alert} from 'reactstrap'; const NoData = (t, category) => <Alert color="secondary"> { t('common:q.category.no_data', {category: t(category.category)}) } </Alert> const Result = (t, points, category, explanation) => <Alert color={explanation.color} key={t(category.category)} > <div> <h2>{t(category.category)}</h2> </div> <div> <h3>{t(explanation.title)}</h3> <ReactMarkdown source={ t(explanation.description) } /> </div> </Alert> const Results = (props) => { const [t] = useTranslation() return( <div> <h2>{ t('common:q.category.results') }</h2> { Object.values(props.categories).map((category) => { const points = props.points[category.category]; const explanation = Object.values(category.answers).filter( (answer) => answer.min_points < points && points <= answer.max_points )[0] if(typeof explanation === 'undefined'){ return(NoData(t, category)) } else { return (Result(t, points, category, explanation)) } }) } <p> <Button onClick={props.retest}>Redo the test</Button> </p> </div>) } Results.propTypes = { points: PropTypes.array, categories: PropTypes.array, retest: PropTypes.func }; export default Results;
5e557eb934d139eb9f1b4ca5b3e7b7cab9e7df60
[ "JavaScript" ]
13
JavaScript
DonGiulio/coronatest
b0d1399133562b24f69246b02360c001edaac591
31cdbdd30571ee53d092ae9fad96920bb2a67b46
refs/heads/master
<repo_name>ivanlares/Pitch-Perfect<file_sep>/Pitch Perfect/RecordedAudio.swift // // RecordedAudio.swift // Pitch Perfect // // Created by <NAME> on 11/26/14. // Copyright (c) 2014 ivan. All rights reserved. // import Foundation class RecordedAudio: NSObject{ var filePathUrl:NSURL var title: String init(filePathUrl:NSURL, title: String){ self.filePathUrl = filePathUrl self.title = title super.init() } }<file_sep>/Pitch Perfect/RecordSoundsViewController.swift // // RecordSoundsViewController.swift // Pitch Perfect // // Created by <NAME> on 11/21/14. // Copyright (c) 2014 ivan. All rights reserved. // import UIKit import AVFoundation class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate { @IBOutlet weak var recordingLabel: UILabel! @IBOutlet weak var stopButton: UIButton! @IBOutlet weak var recordButton: UIButton! var audioRecorder: AVAudioRecorder? var recordedAudio: RecordedAudio? override func viewWillAppear(animated: Bool){ stopButton.hidden = true recordButton.enabled = true recordingLabel.hidden = false recordingLabel.text = "Tap to record" } @IBAction func stopRecording(sender: UIButton) { recordingLabel.hidden = true audioRecorder?.stop() let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setActive(false) } catch let error as NSError{ print(error.localizedDescription) } } @IBAction func recordAudio(sender: UIButton) { recordingLabel.text = "Recording" stopButton.hidden = false recordButton.enabled = false let filePath = NSURL.fileURLWithPath(NSTemporaryDirectory() + "PitchPerfect") let session = AVAudioSession.sharedInstance() do { try session.setCategory(AVAudioSessionCategoryPlayAndRecord) } catch let error as NSError { print(error.localizedDescription) } do { audioRecorder = try AVAudioRecorder(URL: filePath, settings: [String:AnyObject]()) } catch let error as NSError { print(error.localizedDescription) audioRecorder = nil } audioRecorder?.delegate = self audioRecorder?.meteringEnabled = true audioRecorder?.prepareToRecord() audioRecorder?.record() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "stopRecording"{ let playSoundsVC = segue.destinationViewController as! PlaySoundsViewController let data: RecordedAudio = sender as! RecordedAudio playSoundsVC.receivedAudio = data } } func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) { if(flag){ recordedAudio = RecordedAudio(filePathUrl: recorder.url, title: recorder.url.lastPathComponent!) self.performSegueWithIdentifier("stopRecording", sender: recordedAudio) } else { print("Recording was not successfull") recordingLabel.attributedText = NSAttributedString(string: "Recording was not successfull", attributes: [NSForegroundColorAttributeName:UIColor.redColor()]) recordingLabel.hidden = false recordButton.enabled = true stopButton.hidden = true } } }
2381e265041131bb245507e46d3370c2f3c73db4
[ "Swift" ]
2
Swift
ivanlares/Pitch-Perfect
67dba959ec098ec8b985fca54da29537f9281bff
3fc7bc93c356d003cf5711b0a2da5f4ea0fab93e
refs/heads/main
<file_sep>package dev.leap.frog.Mixin; import dev.leap.frog.LeapFrog; import net.minecraft.client.Minecraft; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(Minecraft.class) public class MixinMinecraft { @Inject(method = "shutdown", at = @At("HEAD")) public void onShutdown(CallbackInfo ci) { //LeapFrog.getFileManager().save(); } @Inject(method = "crashed", at = @At("HEAD")) public void onCrash(CallbackInfo ci) { //LeapFrog.getFileManager().save(); } } <file_sep>package dev.leap.frog.Mixin; import dev.leap.frog.LeapFrog; import dev.leap.frog.Manager.CapeManager; import net.minecraft.client.entity.AbstractClientPlayer; import net.minecraft.client.network.NetworkPlayerInfo; import net.minecraft.util.ResourceLocation; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import javax.annotation.Nullable; import java.util.Objects; import java.util.UUID; @Mixin(AbstractClientPlayer.class) public abstract class MixinAbstractClientPlayer { @Shadow @Nullable protected abstract NetworkPlayerInfo getPlayerInfo(); @Inject(method = "getLocationCape", at = @At(value = "HEAD"), cancellable = true) public void drawCapes(CallbackInfoReturnable<ResourceLocation> cir) { UUID uuid = Objects.requireNonNull(getPlayerInfo()).getGameProfile().getId(); if(LeapFrog.getModuleManager().getModuleName("Capes").isToggled() && LeapFrog.getCapeManager().hasCape(uuid)) { cir.setReturnValue(new ResourceLocation("cocked.png")); } else if(LeapFrog.getCapeManager().hasDevCape(uuid)) { cir.setReturnValue(new ResourceLocation("dev-cape.png")); } } } <file_sep>package dev.leap.frog.Module.World; import com.mojang.authlib.GameProfile; import dev.leap.frog.Module.Module; import dev.leap.frog.Settings.Setting; import me.zero.alpine.fork.listener.EventHandler; import me.zero.alpine.fork.listener.Listener; import net.minecraft.client.entity.EntityOtherPlayerMP; import net.minecraft.init.Enchantments; import net.minecraft.init.Items; import net.minecraft.inventory.ItemStackHelper; import net.minecraft.item.Item; import net.minecraft.item.ItemEndCrystal; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumHand; import net.minecraft.world.GameType; import net.minecraftforge.fml.common.network.FMLNetworkEvent; import java.util.UUID; public class FakePlayer extends Module { public FakePlayer() { super("Fake player", "Summons fake player to world", Type.WORLD); } private EntityOtherPlayerMP player; Setting<Boolean> copyInventory = create("Copy Inventory", false); @Override public void onEnable() { if(mc.world == null) { toggle(); return; } player = new EntityOtherPlayerMP(mc.world, new GameProfile(UUID.fromString("069a79f4-44e9-4726-a5be-fca90e38aaf5"), "Leapfrog tester")); player.copyLocationAndAnglesFrom(mc.player); player.rotationYawHead = mc.player.rotationYawHead; mc.world.addEntityToWorld(-100, player); } @Override public void onUpdate() { if(copyInventory.getValue()) { player.inventory.copyInventory(mc.player.inventory); } else { player.inventory.clear(); } } @Override public void onDisable() { mc.world.removeEntity(player); } @EventHandler private Listener<FMLNetworkEvent.ClientDisconnectionFromServerEvent> disconnection = new Listener<>(event -> { toggle(); }); } <file_sep>package dev.leap.frog.Module.Combat; import dev.leap.frog.Event.Network.EventPacket; import dev.leap.frog.Module.Module; import dev.leap.frog.Settings.Setting; import me.zero.alpine.fork.listener.EventHandler; import me.zero.alpine.fork.listener.Listener; import net.minecraft.entity.EntityLivingBase; import net.minecraft.network.play.client.CPacketPlayer; import net.minecraft.network.play.client.CPacketUseEntity; public class Criticals extends Module { public Criticals() { super("Critical", "Hits criticals on entites", Type.COMBAT); } Setting<Mode> mode = create("mode", Mode.Normal); private enum Mode { Normal, Packet, Jump } @EventHandler private Listener<EventPacket.SendPacket> sendPacketListener = new Listener<>(event -> { if(event.getPacket() instanceof CPacketUseEntity) { CPacketUseEntity packet = (CPacketUseEntity) event.getPacket(); if (packet.action == CPacketUseEntity.Action.ATTACK) { // if(packet.getEntityFromWorld(mc.world) instanceof EntityLivingBase && !mc.gameSettings.keyBindJump.isKeyDown()) if (mode.getValue() == Mode.Normal) { mc.player.connection.sendPacket(new CPacketPlayer.Position(mc.player.posX, mc.player.posY + 1.0f, mc.player.posZ, false)); mc.player.connection.sendPacket(new CPacketPlayer.Position(mc.player.posX, mc.player.posY, mc.player.posZ, false)); } else if(mode.getValue() == Mode.Packet) { mc.player.connection.sendPacket(new CPacketPlayer.Position(mc.player.posX, mc.player.posY + 0.1, mc.player.posZ, false)); mc.player.connection.sendPacket(new CPacketPlayer.Position(mc.player.posX, mc.player.posY, mc.player.posZ, false)); mc.player.connection.sendPacket(new CPacketPlayer.Position(mc.player.posX, mc.player.posY + 0.1, mc.player.posZ, false)); mc.player.connection.sendPacket(new CPacketPlayer.Position(mc.player.posX, mc.player.posY, mc.player.posZ, false)); } else if(mode.getValue() == Mode.Jump) { mc.player.jump(); mc.player.motionY /= 2.0; } } } }); } <file_sep># Leapfrog-Client Leapfrog client is a utility mod for anarchy servers (blah blah blah you know the rest). If you need any support or have any interests regarding the client you can join [here](https://discord.gg/fT5JVKVUyt) ***This client is not finished yet*** ## Download You can use the [release](https://github.com/biggiemedium/Leapfrog-Client/tags) page to find all the latest buildable sources When you download the jar you put the file into your mods folder and run with minecraftforge ## Contributers If you want to contribute to Leapfrog client DM me px#0881 on discord and message me. Big thank you to [Boncorde](https://github.com/PalitXD) for being helping through the entire development process Some code was sampled from these clients, feel free to check them out: [Aurora](https://github.com/Memeszz/Aurora-public) [Salhack](https://github.com/ionar2/spidermod) [Xulu](https://github.com/Elementars/Xulu-v1.5.2) ## Building You can build the project by running **gradlew setupDecompWorkspace** and **gradlew build**. If your using eclipse you also need to run **gradlew eclipse**. And for IntelliJ you need to run **gradlew genIntellijRuns** If you need any support for building you can join the discord [here](https://discord.gg/fT5JVKVUyt) <file_sep>package dev.leap.frog.GUI.ClickGUI.Components; import dev.leap.frog.GUI.ClickGUI.ModuleButton; import dev.leap.frog.Util.Listeners.IComponent; import dev.leap.frog.Util.Render.Colorutil; import net.minecraft.client.Minecraft; import java.awt.*; import java.io.IOException; public class Component implements IComponent { protected Minecraft mc = Minecraft.getMinecraft(); private int x; private int y; private int width; private int height; private ModuleButton moduleButton; public boolean shown; public Component(ModuleButton button, int x, int y, int width, int height) { this.moduleButton = button; this.x = x; this.y = y; this. width = width; this.height = height; } public void draw(int mouseX, int mouseY) { } public void mouseClicked(int mouseX, int mouseY, int button) throws IOException { } public void mouseReleased(int mouseX, int mouseY, int state) { } public void keyTyped(char typedChar, int keyCode) throws IOException { } protected boolean isHovered(int mouseX, int mouseY) { return mouseX > getX() + 2 && mouseY > getY() && mouseX < getX() + 2 + getWidth() && mouseY < getY() + getHeight() - 1; } protected boolean isShown() { return shown; } public int getDeafultHeight() { return 0; } public Minecraft getMc() { return mc; } public void setMc(Minecraft mc) { this.mc = mc; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public ModuleButton getModuleButton() { return moduleButton; } } <file_sep>package dev.leap.frog.Event.Movement; import dev.leap.frog.Event.LeapFrogEvent; public class EventPlayerRightClick extends LeapFrogEvent { } <file_sep>package dev.leap.frog.Event.Render; import dev.leap.frog.Event.LeapFrogEvent; public class EventRenderHurtCam extends LeapFrogEvent { public float Ticks; public EventRenderHurtCam(float p_Ticks) { super(); Ticks = p_Ticks; } } <file_sep>package dev.leap.frog.Command.Commands; import com.mojang.realmsclient.gui.ChatFormatting; import dev.leap.frog.Command.Command; import dev.leap.frog.LeapFrog; import dev.leap.frog.Module.Module; public class Toggle extends Command { public Toggle() { super("Toggle", "Toggles mod for you", new String[0]); } @Override public void execute(String[] args) { if(args.length <= 1) { sendMessage("Something went wrong"); return; } Module m = LeapFrog.getModuleManager().getModuleName(args[1]); if(m == null) { sendMessage("Module does not exist!"); } else { if(m.isToggled()) { m.toggle(); sendMessage(ChatFormatting.RED + "Toggled " + ChatFormatting.RESET + m.getName()); } else { m.setToggled(true); sendMessage(ChatFormatting.GREEN + "Toggled " + ChatFormatting.RESET + m.getName()); } } } } <file_sep>package dev.leap.frog.Util.Render; import com.mojang.realmsclient.gui.ChatFormatting; import dev.leap.frog.Manager.UtilManager; import dev.leap.frog.Module.Module; import dev.leap.frog.Util.Wrapper; import net.minecraft.client.Minecraft; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.Style; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.event.HoverEvent; import net.minecraftforge.client.event.ClientChatReceivedEvent; public class Chatutil extends UtilManager { public static ChatFormatting red = ChatFormatting.RED; public static ChatFormatting blue = ChatFormatting.BLUE; public static ChatFormatting white = ChatFormatting.WHITE; public static String prefix = ChatFormatting.GREEN + "LeapFrog > " + ChatFormatting.WHITE; public static void sendClientSideMessgage(String message) { if (Wrapper.getMC().ingameGUI != null && Wrapper.getPlayer() != null) Wrapper.getMC().ingameGUI.getChatGUI().printChatMessage(new TextComponentString(prefix + message)); } public static void setModuleMessage(Module module) { if(module.isToggled()) { removeableMessage(module.getName() + ChatFormatting.GREEN + " Enabled"); } else { removeableMessage(module.getName() + ChatFormatting.RED + " Disabled"); } } public static void removeableMessage(String message) { if(Wrapper.getPlayer() != null) { ITextComponent text = new TextComponentString(prefix + message).setStyle(new Style().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("Leap Frog")))); Wrapper.getMC().ingameGUI.getChatGUI().printChatMessageWithOptionalDeletion(text, 5936); } } } <file_sep>package dev.leap.frog.Manager; import dev.leap.frog.GUI.Click; import dev.leap.frog.GUI.ClickGUI.Frame; import dev.leap.frog.LeapFrog; import dev.leap.frog.Module.Module; import dev.leap.frog.Module.ui.ClickGUIModule; import dev.leap.frog.Util.Entity.Friendutil; import org.lwjgl.input.Keyboard; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Iterator; public class FileManager { private String directoryleapfrog = "Leapfrog/"; private String directoryModule = "/Module/"; private String directoryGUI = "/GUI/"; private String directoryFriends = "/Friends/"; private String directoryBinds = "/Binds/"; public void verifyDirectory() { File leapfrog = new File("Leapfrog/"); File module = new File(directoryleapfrog + directoryModule); File gui = new File(directoryleapfrog + directoryGUI); File friends = new File(directoryleapfrog + directoryFriends); File binds = new File(directoryleapfrog + directoryBinds); if(!leapfrog.exists()) { leapfrog.mkdirs(); } if(!module.exists()) { module.mkdirs(); } if(!gui.exists()) { gui.mkdirs(); } if(!friends.exists()) { friends.mkdirs(); } if(!binds.exists()) { binds.mkdirs(); } } public boolean doesDirectoryExist() { File leapfrog = new File("Leapfrog/"); return leapfrog.exists(); } public void saveFriends() throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(getDirectoryFriends() + "friends.json")); Iterator iterator = FriendManager.getFriend().iterator(); while (iterator.hasNext()) { Friendutil f = (Friendutil) iterator.next(); writer.write(f.getName()); writer.write("\r\n"); } writer.close(); } public void loadFriend() throws IOException { FileInputStream fstream = new FileInputStream(getDirectoryFriends() + "friends.json"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FriendManager.getFriend().clear(); String line; while ((line = br.readLine()) != null) { LeapFrog.getFriendManager().addFriend(line); } br.close(); } public void saveModule() throws IOException { for(Module m : LeapFrog.getModuleManager().getModules()) { BufferedWriter writer = new BufferedWriter(new FileWriter(getDirectoryModule() + m.getName() + ".txt")); // change to json in future maybe? writer.write("Module:" + m.getName() + "\r\n"); writer.write("Toggled:" + m.isToggled() + "\r\n"); writer.write("Bind:" + m.getKey() + "\r\n"); writer.write("Hidden:" + m.isHidden() + "\r\n"); writer.close(); } } public void loadModule() throws IOException { for(Module m : LeapFrog.getModuleManager().getModules()) { BufferedReader reader = new BufferedReader(new FileReader(getDirectoryModule() + m.getName() + ".txt")); String line; Module mod = null; while ((line = reader.readLine()) != null) { String[] regex = line.split(":"); switch(regex[0]) { case "Module": LeapFrog.getModuleManager().getModuleName(regex[1]); break; case "Toggled": if(mod != null && Boolean.parseBoolean(regex[1])) { mod.setToggled(true); } case "Bind": assert mod != null; mod.setKey(Keyboard.getKeyIndex(regex[1])); break; case "Hidden": if(mod != null && Boolean.parseBoolean(regex[1])) { mod.setHidden(true); } } } reader.close(); } } public void saveOpen() throws IOException { for(Frame f : Click.INSTANCE.getFrame()) { BufferedWriter writer = new BufferedWriter(new FileWriter(getDirectoryGUI() + f.getName() + ".txt")); writer.write("Open: " + f.isOpen()); writer.close(); } } public void loadOpen() throws IOException { for(Frame f : Click.INSTANCE.getFrame()) { BufferedReader reader = new BufferedReader(new FileReader(getDirectoryGUI() + f.getName() + ".txt")); String line; while((line = reader.readLine()) != null) { if(line.toLowerCase().startsWith("open") && line.toLowerCase().contains("true")) { f.setOpen(true); } else { f.setOpen(false); } } reader.close(); } } public void load() { try { loadFriend(); loadModule(); saveOpen(); } catch (Exception e) { verifyDirectory(); } } public void save() { try { saveModule(); saveFriends(); saveOpen(); } catch (Exception e) { e.printStackTrace(); } } public void saveFriendsOnly() { try { saveFriends(); } catch (Exception e) { } } public String getDirectoryleapfrog() { return directoryleapfrog; } public String getDirectoryModule() { return directoryleapfrog + directoryModule; } public String getDirectoryGUI() { return directoryleapfrog + directoryGUI; } public String getDirectoryFriends() { return directoryleapfrog + directoryFriends; } public String getDirectoryBinds() { return directoryleapfrog + directoryBinds; } } <file_sep>buildscript { repositories { maven { url = 'https://sizableshrimp.me/maven' } jcenter() maven { url = "http://files.minecraftforge.net/maven" } maven { name = 'spongepowered-repo' url = 'https://repo.spongepowered.org/maven/' } } dependencies { classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT' classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.3' classpath 'org.spongepowered:mixingradle:0.6-SNAPSHOT' } } apply plugin: 'net.minecraftforge.gradle.forge' apply plugin: 'com.github.johnrengelman.shadow' apply plugin: 'org.spongepowered.mixin' //Only edit below this line, the above code adds and enables the necessary things for Forge to be setup. version = "1.0" group = "dev.leap.frog" archivesBaseName = "LeapFrog" sourceCompatibility = targetCompatibility = '1.8' compileJava { sourceCompatibility = targetCompatibility = '1.8' } repositories { maven { name = 'spongepowered-repo' url = 'https://repo.spongepowered.org/maven/' } maven { name = "jitpack.io" url = "https://jitpack.io" } mavenCentral() jcenter() } minecraft { version = "1.12.2-14.23.0.2531" runDir = "run" coreMod = "dev.leap.frog.Mixin.MixinLoaderForge" mappings = "snapshot_20171003" } dependencies { // DO NOT UPDATE MIXINS compile("org.spongepowered:mixin:0.7.11-SNAPSHOT") { exclude module: 'launchwrapper' exclude module: 'gson' exclude module: 'guava' exclude module: 'commons-io' } compile "com.github.biggiemedium:Alpine:1.9" compile 'club.minnced:java-discord-rpc:2.0.2' compile group: 'net.jodah', name: 'typetools', version: '0.5.0' } processResources { inputs.property "version", project.version inputs.property "mcversion", project.minecraft.version from(sourceSets.main.resources.srcDirs) { include 'mcmod.info' expand 'version':project.version, 'mcversion':project.minecraft.version } from(sourceSets.main.resources.srcDirs) { exclude 'mcmod.info' } rename "(.+_at.cfg)", 'META-INF/$1'; }<file_sep>package dev.leap.frog.Mixin; import dev.leap.frog.Event.Render.EventRenderRain; import dev.leap.frog.Event.World.EventEntityRemoved; import dev.leap.frog.Event.World.EventSetDayTime; import dev.leap.frog.LeapFrog; import net.minecraft.entity.Entity; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(World.class) public class MixinWorld { @Inject(method = "getRainStrength", at = @At("HEAD"), cancellable = true) public void eventCancelRain(float delta, CallbackInfoReturnable<Float> cir) { EventRenderRain packet = new EventRenderRain(); LeapFrog.EVENT_BUS.post(packet); if(packet.isCancelled()) { cir.cancel(); cir.setReturnValue(0.0f); } } @Inject(method = "removeEntity", at = @At("HEAD"), cancellable = true) public void entityRemoved(Entity entityIn, CallbackInfo ci) { EventEntityRemoved packet = new EventEntityRemoved(entityIn); LeapFrog.EVENT_BUS.post(packet); if(packet.isCancelled()) { ci.cancel(); } } @Inject(method = "setTotalWorldTime", at = @At("TAIL"), cancellable = true) public void setDayTime(long worldTime, CallbackInfo ci) { EventSetDayTime packet = new EventSetDayTime(worldTime); LeapFrog.EVENT_BUS.post(packet); if(packet.isCancelled()) { ci.cancel(); } } } <file_sep>package dev.leap.frog.Module.ui; import dev.leap.frog.LeapFrog; import dev.leap.frog.Module.Module; public class HudEditorModule extends Module { public HudEditorModule() { super("HudEditor", "Allows you to edit your on screen HUD", Type.CLIENT); } @Override public void onEnable() { LeapFrog.getModuleManager().getModule(ClickGUIModule.class).setToggled(false); } } <file_sep>package dev.leap.frog.GUI.ClickGUI.Components; import dev.leap.frog.GUI.ClickGUI.ModuleButton; import dev.leap.frog.LeapFrog; import dev.leap.frog.Module.ui.ClickGUIModule; import dev.leap.frog.Util.Render.Colorutil; import dev.leap.frog.Util.Render.Renderutil; import dev.leap.frog.Util.Wrapper; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.init.SoundEvents; import java.awt.*; import java.io.IOException; public class HiddenButton extends Component { public HiddenButton(int x, int y, ModuleButton button) { super(button, x, y, button.getWidth(), 13); } @Override public void draw(int mouseX, int mouseY) { Renderutil.drawRect(getX(), getY(), getX() + 2, getY() + getHeight(), new Color(10, 10, 10, 200).getRGB()); Renderutil.drawRect(getX() + 2, getY(), getX() + 2 + getWidth(), getY() + getHeight() - 1, handleColor(mouseX, mouseY)); Renderutil.drawRect(getX() + 2, getY() + getHeight() - 1, getX() + 2 + getWidth(), getY() + getHeight(), new Color(10, 10, 10, 200).getRGB()); Wrapper.getMC().fontRenderer.drawStringWithShadow(getModuleButton().getModule().isHidden() ? "UnHide" : "Hide", getX() + 4, getY() + 2, -1); } private int handleColor(int mouseX, int mouseY){ Color color = getModuleButton().getModule().isHidden() ? Colorutil.subComponentColor() : new Color(50, 50, 50, 200); return isHovered(mouseX, mouseY) ? (getModuleButton().getModule().isHidden() ? color.darker().darker().getRGB() : color.brighter().brighter().getRGB()) : color.getRGB(); } @Override public void mouseClicked(int mouseX, int mouseY, int button) throws IOException { if(isHovered(mouseX, mouseY)) { if(button == 0) { getModuleButton().getModule().setHidden(!getModuleButton().getModule().isHidden()); } if(ClickGUIModule.INSTANCE.clickSound.getValue() && LeapFrog.getModuleManager().getModule(ClickGUIModule.class).isToggled()) { mc.getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(SoundEvents.UI_BUTTON_CLICK, 1.0f)); } } } } <file_sep>package dev.leap.frog.Util.Listeners; /* we are using the same thing for old GUI except swapping abstract class with interface also rewriting this shit -Boncorde: this wont work your not gonna be able to render these things lol -PX: do you even know how an interface works? */ import net.minecraft.client.Minecraft; import java.io.IOException; public interface IComponent { void draw(int mouseX, int mouseY); void mouseClicked(int mouseX, int mouseY, int button) throws IOException; void mouseReleased(int mouseX, int mouseY, int state); void keyTyped(char typedChar, int keyCode) throws IOException; } <file_sep>package dev.leap.frog.Module.Misc; import dev.leap.frog.Event.Network.EventPacket; import dev.leap.frog.Module.Module; import dev.leap.frog.Settings.Setting; import me.zero.alpine.fork.listener.EventHandler; import me.zero.alpine.fork.listener.Listener; import net.minecraft.client.audio.SoundHandler; import net.minecraft.init.SoundEvents; import net.minecraft.network.play.server.SPacketSoundEffect; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraftforge.fml.common.eventhandler.Event; public class AntiSound extends Module { public AntiSound() { super("AntiSound", "Prevents sound from rendering", Type.MISC); } Setting<Boolean> explosion = create("Explosions", true); Setting<Boolean> wither = create("Wither", false); Setting<Boolean> rain = create("Rain", false); @EventHandler private Listener<EventPacket.ReceivePacket> packetListener = new Listener<>(event -> { if(event.getPacket() instanceof SPacketSoundEffect) { SPacketSoundEffect packet = (SPacketSoundEffect) event.getPacket(); if(packet.getCategory() == SoundCategory.BLOCKS && packet.getSound() == SoundEvents.ENTITY_GENERIC_EXPLODE && explosion.getValue()) { event.cancel(); } if(packet.getCategory() == SoundCategory.BLOCKS && packet.getSound() == SoundEvents.ENTITY_WITHER_SPAWN && wither.getValue()) { event.cancel(); } if(packet.getCategory() == SoundCategory.BLOCKS && packet.getSound() == SoundEvents.ENTITY_WITHER_HURT && wither.getValue()) { event.cancel(); } if(packet.getCategory() == SoundCategory.BLOCKS && packet.getSound() == SoundEvents.WEATHER_RAIN && rain.getValue()) { event.cancel(); } } }); } <file_sep>package dev.leap.frog.Module.Render; import dev.leap.frog.Module.Module; public class Capes extends Module { public Capes() { super("Capes", "Shows capes on players", Type.RENDER); setToggled(true); } } <file_sep>package dev.leap.frog.Mixin; import dev.leap.frog.Event.Movement.EventEntityCollision; import dev.leap.frog.LeapFrog; import net.minecraft.entity.Entity; import net.minecraft.entity.MoverType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(Entity.class) public class MixinEntity { @Shadow public void move(MoverType type, double x, double y, double z) { } @Shadow public double motionX; @Shadow public double motionY; @Shadow public double motionZ; @Inject(method = "applyEntityCollision", at = @At("HEAD"), cancellable = true) public void onCollision(Entity entityIn, CallbackInfo ci) { EventEntityCollision event = new EventEntityCollision(); LeapFrog.EVENT_BUS.post(event); if(event.isCancelled()) { ci.cancel(); } } @Redirect(method = "applyEntityCollision", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;addVelocity(DDD)V")) public void removeSlow(Entity entity, double x, double y, double z) { if(!LeapFrog.getModuleManager().getModuleName("NoSlow").isToggled()) { entity.motionX += x; entity.motionY += y; entity.motionZ += z; entity.isAirBorne = true; } } } <file_sep>package dev.leap.frog.Util.Listeners; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.world.World; public interface Util { Minecraft mc = Minecraft.getMinecraft(); World world = mc.world; EntityPlayerSP player = mc.player; } <file_sep>package dev.leap.frog.Module.Client; import dev.leap.frog.Event.Network.EventPacket; import dev.leap.frog.Module.Module; import me.zero.alpine.fork.listener.EventHandler; import me.zero.alpine.fork.listener.Listener; import net.minecraft.network.play.client.CPacketChatMessage; public class Suffix extends Module { public Suffix() { super("Suffix", "Suffix", Type.CLIENT); } // | L e a p f r o g private String suffix = " \u23D0 \u029f\u1d07\u1d00\u1d18\ua730\u0280\u1d0f\u0262"; @EventHandler private Listener<EventPacket.SendPacket> sendPacketListener = new Listener<>(event -> { if((event.getPacket() instanceof CPacketChatMessage)) { String message = ((CPacketChatMessage) event.getPacket()).getMessage(); if (message.startsWith("/")) return; // checking for command prefix if (message.startsWith("\\"))return; if (message.startsWith("!")) return; if (message.startsWith(":")) return; if (message.startsWith(";")) return; if (message.startsWith(".")) return; if (message.startsWith(",")) return; if (message.startsWith("@")) return; if (message.startsWith("&")) return; if (message.startsWith("*")) return; if (message.startsWith("$")) return; if (message.startsWith("#")) return; if (message.startsWith("(")) return; if (message.startsWith(")")) return; message += suffix; if(message.length() >= 250) { message = message.substring(0, 250); } ((CPacketChatMessage) event.getPacket()).message = message; } }); } <file_sep>package dev.leap.frog.Module.Movement; import dev.leap.frog.Event.Network.EventPacket; import dev.leap.frog.Module.Module; import me.zero.alpine.fork.listener.EventHandler; import me.zero.alpine.fork.listener.Listener; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.server.SPacketPlayerPosLook; public class NoRotate extends Module { public NoRotate() { super("NoRotate", "stops server side rotations", Type.MOVEMENT); } @EventHandler private Listener<EventPacket.ReceivePacket> packetListener = new Listener<>(event -> { if(event.getPacket() instanceof SPacketPlayerPosLook) { SPacketPlayerPosLook packet = (SPacketPlayerPosLook) event.getPacket(); packet.pitch = mc.player.rotationPitch; packet.yaw = mc.player.rotationYaw; } }); } <file_sep>package dev.leap.frog.Module.Misc; import dev.leap.frog.Module.Module; import dev.leap.frog.Settings.Setting; import net.minecraft.item.Item; import net.minecraft.item.ItemEndCrystal; import net.minecraft.item.ItemExpBottle; public class FastUse extends Module { public FastUse() { super("FastUse", "Lets you interact faster", Type.MISC); } Setting<Boolean> xp = create("XP", true); Setting<Boolean> crystals = create("Crystal", true); @Override public void onUpdate() { Item mainHand = mc.player.getHeldItemMainhand().getItem(); Item offHand = mc.player.getHeldItemOffhand().getItem(); if(xp.getValue() && mainHand instanceof ItemExpBottle || offHand instanceof ItemExpBottle) { mc.rightClickDelayTimer = 0; } if(crystals.getValue() && mainHand instanceof ItemEndCrystal || offHand instanceof ItemEndCrystal) { mc.rightClickDelayTimer = 0; } if(!xp.getValue() && !crystals.getValue()) { mc.rightClickDelayTimer = 0; } } } <file_sep>package dev.leap.frog.Event.Render; import dev.leap.frog.Event.LeapFrogEvent; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.math.Vec3d; public class RenderEvent extends LeapFrogEvent { private final ScaledResolution res = new ScaledResolution(Minecraft.getMinecraft()); private final Tessellator tessellator; private final Vec3d render_pos; public RenderEvent(Tessellator tessellator, Vec3d pos) { super(); this.tessellator = tessellator; this.render_pos = pos; } public Tessellator getTessellator() { return this.tessellator; } public Vec3d getRenderPos() { return render_pos; } public BufferBuilder getBufferBuild() { return this.tessellator.getBuffer(); } public void setTranslation(Vec3d pos) { getBufferBuild().setTranslation(- pos.x, - pos.y, - pos.z); } public void resetTranslation() { setTranslation(render_pos); } public double getScreenWidth() { return res.getScaledWidth_double(); } public double getScreenHeight() { return res.getScaledHeight_double(); } } <file_sep>package dev.leap.frog.Module.Combat; import dev.leap.frog.Event.Movement.EventPlayerStoppedUsingItem; import dev.leap.frog.Event.Network.EventPacketUpdate; import dev.leap.frog.Module.Module; import dev.leap.frog.Settings.Setting; import dev.leap.frog.Util.Entity.Playerutil; import dev.leap.frog.Util.Wrapper; import me.zero.alpine.fork.listener.EventHandler; import me.zero.alpine.fork.listener.Listener; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.item.EntityEnderCrystal; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.ClickType; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; public class OffHand extends Module { public OffHand() { super("OffHand", "Puts item in your offhand", Type.COMBAT); } Setting<Integer> health = create("Fallback", 13, 0, 36); Setting<itemOffhand> item = create("Item", itemOffhand.Gapple); Setting<AutoGapple> autoGapple = create("Auto Gapple", AutoGapple.Constant); Setting<Boolean> lethalCrystal = create("Lethal crystal", true); private enum itemOffhand { Gapple, Crystal, Pearl } private enum AutoGapple { None, Constant, Inhole } @Override public void onUpdate() { // keep only GUI screen of GUIContainer or it will be slow if (mc.currentScreen instanceof GuiContainer || mc.world == null || mc.player == null || mc.player.ticksExisted < 10) return; if (item.getValue() == itemOffhand.Gapple) { if (!shouldTotem()) { if (!(mc.player.getHeldItemOffhand() != ItemStack.EMPTY && mc.player.getHeldItemOffhand().getItem() == Items.GOLDEN_APPLE)) { final int slotGapple = getGapSlot() < 9 ? getGapSlot() + 36 : getGapSlot(); if (getGapSlot() != -1) { mc.playerController.windowClick(0, slotGapple, 0, ClickType.PICKUP, mc.player); mc.playerController.windowClick(0, 45, 0, ClickType.PICKUP, mc.player); mc.playerController.windowClick(0, slotGapple, 0, ClickType.PICKUP, mc.player); } } } else if (!(mc.player.getHeldItemOffhand() != ItemStack.EMPTY && mc.player.getHeldItemOffhand().getItem() == Items.TOTEM_OF_UNDYING)) { final int slot = getTotemSlot() < 9 ? getTotemSlot() + 36 : getTotemSlot(); if (getTotemSlot() != -1) { mc.playerController.windowClick(0, slot, 0, ClickType.PICKUP, mc.player); mc.playerController.windowClick(0, 45, 0, ClickType.PICKUP, mc.player); mc.playerController.windowClick(0, slot, 0, ClickType.PICKUP, mc.player); } } } if (item.getValue() == itemOffhand.Pearl) { if (!shouldTotem()) { if (!(mc.player.getHeldItemOffhand() != ItemStack.EMPTY && mc.player.getHeldItemOffhand().getItem() == Items.ENDER_PEARL)) { final int pearlSlot = getPearlSlot() < 9 ? getPearlSlot() + 36 : getPearlSlot(); if (getPearlSlot() != -1) { mc.playerController.windowClick(0, pearlSlot, 0, ClickType.PICKUP, mc.player); mc.playerController.windowClick(0, 45, 0, ClickType.PICKUP, mc.player); mc.playerController.windowClick(0, pearlSlot, 0, ClickType.PICKUP, mc.player); } } } else if (!(mc.player.getHeldItemOffhand() != ItemStack.EMPTY && mc.player.getHeldItemOffhand().getItem() == Items.TOTEM_OF_UNDYING)) { final int slot = getPearlSlot() < 9 ? getPearlSlot() + 36 : getPearlSlot(); if (getPearlSlot() != -1) { mc.playerController.windowClick(0, slot, 0, ClickType.PICKUP, mc.player); mc.playerController.windowClick(0, 45, 0, ClickType.PICKUP, mc.player); mc.playerController.windowClick(0, slot, 0, ClickType.PICKUP, mc.player); } } } if (item.getValue() == itemOffhand.Crystal) { if (!shouldTotem() || getItems(Items.TOTEM_OF_UNDYING) == 0) { if (!(mc.player.getHeldItemOffhand() != ItemStack.EMPTY && mc.player.getHeldItemOffhand().getItem() == Items.END_CRYSTAL)) { final int slot = getCrystalSlot() < 9 ? getCrystalSlot() + 36 : getCrystalSlot(); if (getCrystalSlot() != -1) { mc.playerController.windowClick(0, slot, 0, ClickType.PICKUP, mc.player); mc.playerController.windowClick(0, 45, 0, ClickType.PICKUP, mc.player); mc.playerController.windowClick(0, slot, 0, ClickType.PICKUP, mc.player); } } } else if (!(mc.player.getHeldItemOffhand() != ItemStack.EMPTY && mc.player.getHeldItemOffhand().getItem() == Items.TOTEM_OF_UNDYING)) { final int slot = getTotemSlot() < 9 ? getTotemSlot() + 36 : getTotemSlot(); if (getTotemSlot() != -1) { mc.playerController.windowClick(0, slot, 0, ClickType.PICKUP, mc.player); mc.playerController.windowClick(0, 45, 0, ClickType.PICKUP, mc.player); mc.playerController.windowClick(0, slot, 0, ClickType.PICKUP, mc.player); } } } if(!isPlayerInHole() && autoGapple.getValue() != AutoGapple.Inhole) { mc.gameSettings.keyBindUseItem.pressed = false; } } @EventHandler private Listener<EventPacketUpdate> listener = new Listener<>(event -> { if(mc.player == null || mc.world == null) return; // auto gapple methods if (autoGapple.getValue() == AutoGapple.Inhole && isPlayerInHole()) { if (mc.player.getHeldItemOffhand().getItem() == Items.GOLDEN_APPLE) { if (mc.currentScreen == null) { mc.gameSettings.keyBindUseItem.pressed = true; } else { mc.playerController.processRightClick(mc.player, mc.world, EnumHand.OFF_HAND); } } } if(autoGapple.getValue() == AutoGapple.Constant) { if(mc.player.getHeldItemOffhand().getItem() == Items.GOLDEN_APPLE && !Playerutil.isEating()) { if(mc.currentScreen == null) { mc.gameSettings.keyBindUseItem.pressed = true; } else { mc.playerController.processRightClick(mc.player, mc.world, EnumHand.OFF_HAND); } } } }); @EventHandler private Listener<EventPlayerStoppedUsingItem> itemListener = new Listener<>(event -> { if(Playerutil.isEating()) { event.cancel(); } }); @Override public void onDisable() { final int slot = getTotemSlot() < 9 ? getTotemSlot() + 36 : getTotemSlot(); if (getTotemSlot() != -1) { mc.playerController.windowClick(0, slot, 0, ClickType.PICKUP, mc.player); mc.playerController.windowClick(0, 45, 0, ClickType.PICKUP, mc.player); mc.playerController.windowClick(0, slot, 0, ClickType.PICKUP, mc.player); } } private boolean shouldTotem() { if (mc.player != null) { return (mc.player.getItemStackFromSlot(EntityEquipmentSlot.CHEST).getItem() == Items.ELYTRA || mc.player.getHealth() + mc.player.getAbsorptionAmount() <= health.getValue() || (lethalCrystal.getValue() && isGapplesAABBEmpty())); } return (Playerutil.getPlayerHealth()) <= health.getValue() || mc.player.getItemStackFromSlot(EntityEquipmentSlot.CHEST).getItem() == Items.ELYTRA || (lethalCrystal.getValue() && isGapplesAABBEmpty()); } private boolean isEmpty(BlockPos pos) { return mc.world.getEntitiesWithinAABBExcludingEntity(null, new AxisAlignedBB(pos)).stream().noneMatch(e -> e instanceof EntityEnderCrystal); } public static int getItems(Item i) { return Wrapper.getMC().player.inventory.mainInventory.stream().filter(itemStack -> itemStack.getItem() == i).mapToInt(ItemStack::getCount).sum() + Wrapper.getMC().player.inventory.offHandInventory.stream().filter(itemStack -> itemStack.getItem() == i).mapToInt(ItemStack::getCount).sum(); } private boolean isGapplesAABBEmpty() { return !isEmpty(mc.player.getPosition().add(1, 0, 0)) || !isEmpty(mc.player.getPosition().add(-1, 0, 0)) || !isEmpty(mc.player.getPosition().add(0, 0, 1)) || !isEmpty(mc.player.getPosition().add(0, 0, -1)) || !isEmpty(mc.player.getPosition()); } private boolean isPlayerInHole() { BlockPos pos = Playerutil.getPlayerPosFloored(); return mc.world.getBlockState(pos.east()).getBlock() != Blocks.AIR && mc.world.getBlockState(pos.west()).getBlock() != Blocks.AIR && mc.world.getBlockState(pos.north()).getBlock() != Blocks.AIR && mc.world.getBlockState(pos.south()).getBlock() != Blocks.AIR; } int getGapSlot() { int gapSlot = -1; for (int i = 45; i > 0; i--) { if (mc.player.inventory.getStackInSlot(i).getItem() == Items.GOLDEN_APPLE) { gapSlot = i; break; } } return gapSlot; } int getPearlSlot() { int gapSlot = -1; for (int i = 45; i > 0; i--) { if (mc.player.inventory.getStackInSlot(i).getItem() == Items.ENDER_PEARL) { gapSlot = i; break; } } return gapSlot; } int getCrystalSlot() { int crystalSlot = -1; for (int i = 45; i > 0; i--) { if (mc.player.inventory.getStackInSlot(i).getItem() == Items.END_CRYSTAL) { crystalSlot = i; break; } } return crystalSlot; } int getTotemSlot() { int totemSlot = -1; for (int i = 45; i > 0; i--) { if (mc.player.inventory.getStackInSlot(i).getItem() == Items.TOTEM_OF_UNDYING) { totemSlot = i; break; } } return totemSlot; } public static OffHand INSTANCE = new OffHand(); } <file_sep>package dev.leap.frog.Module.Render; import dev.leap.frog.Event.Render.EventRenderNameTag; import dev.leap.frog.Module.Module; import me.zero.alpine.fork.listener.EventHandler; import me.zero.alpine.fork.listener.Listener; public class NameTags extends Module { public NameTags() { super("NameTags", "Shows information about the player above their heads", Type.RENDER); } @SuppressWarnings("unused") @EventHandler private Listener<EventRenderNameTag> tagListener = new Listener<>(event -> { event.cancel(); }); } <file_sep>package dev.leap.frog.Event.Network; import dev.leap.frog.Event.LeapFrogEvent; import net.minecraft.network.Packet; public class EventPacket extends LeapFrogEvent { private final Packet packet; public EventPacket(Packet packet) { super(); this.packet = packet; } public Packet getPacket() { return packet; } public static class SendPacket extends EventPacket{ public SendPacket(Packet packet) { super(packet); } } public static class ReceivePacket extends EventPacket { public ReceivePacket(Packet packet) { super(packet); } } } <file_sep>package dev.leap.frog.Event.World; import dev.leap.frog.Event.LeapFrogEvent; import net.minecraft.util.DamageSource; public class EventAttackEnderCrystal extends LeapFrogEvent { private DamageSource source; public EventAttackEnderCrystal(DamageSource source) { this.source = source; } public DamageSource getSource() { return source; } public void setSource(DamageSource source) { this.source = source; } } <file_sep>package dev.leap.frog.Command; import com.mojang.realmsclient.gui.ChatFormatting; import dev.leap.frog.Manager.UtilManager; import dev.leap.frog.Util.Wrapper; import net.minecraft.client.Minecraft; import net.minecraft.util.text.TextComponentString; import java.util.List; public abstract class Command extends UtilManager { private String name; private String description; private String[] commands; private String prefix; public Command(String name, String description, String[] syntax) { this.name = name; this.description = description; this.commands = syntax; this.prefix = "."; } public void commandCheck(String[] args) { if(args.length < 1 && args[1].equalsIgnoreCase("help")) { this.sendChatMessage("An error has occured"); return; } } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public abstract void execute(String[] args); protected void sendChatMessage(String message) { if(!UtilManager.nullCheck()) { mc.ingameGUI.getChatGUI().printChatMessage(new TextComponentString( ChatFormatting.GREEN + "Leapfrog >" + ChatFormatting.RESET + " " + message)); } } public String[] getCommands() { return commands; } public void setCommands(String[] commands) { this.commands = commands; } } <file_sep>package dev.leap.frog.Module.Misc; import com.mojang.realmsclient.gui.ChatFormatting; import dev.leap.frog.Event.Network.EventPacket; import dev.leap.frog.Event.Network.EventPacketUpdate; import dev.leap.frog.LeapFrog; import dev.leap.frog.Manager.FriendManager; import dev.leap.frog.Manager.UtilManager; import dev.leap.frog.Module.Client.AutoEZ; import dev.leap.frog.Module.Module; import dev.leap.frog.Settings.Setting; import dev.leap.frog.Util.Render.Chatutil; import me.zero.alpine.fork.listener.EventHandler; import me.zero.alpine.fork.listener.Listener; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.play.server.SPacketEntityStatus; import net.minecraft.util.text.TextComponentString; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; public class TotemPopCounter extends Module { public TotemPopCounter() { super("TotemPopCounter", "Counts nearby players that have popped totems", Type.MISC); } private HashMap<String, Integer> pops = new HashMap<>(); Setting<Boolean> ignoreFriends = create("IgnoreFriends", false); Setting<Boolean> msgPlayer = create("Msg User", false); Setting<Boolean> suffix = create("Suffix", true); @Override public void onUpdate() { if(pops == null && !UtilManager.nullCheck()) { pops = new HashMap<>(); } for (EntityPlayer player : mc.world.playerEntities) { if(!pops.containsKey(player.getName())) continue; if(player.getHealth() <= 0 || player.isDead) { if(pops.containsKey(player.getName())) { Chatutil.sendClientSideMessgage(player.getName() + " " + "has died after popping " + pops.get(player.getName()) + " " + "totems"); pops.remove(player.getName()); } } } } @EventHandler private Listener<EventPacket.ReceivePacket> receivePacketListener = new Listener<>(event -> { if(UtilManager.nullCheck()) return; if(event.getPacket() instanceof SPacketEntityStatus) { SPacketEntityStatus packet = (SPacketEntityStatus) event.getPacket(); if(packet.getOpCode() == 35) { Entity e = packet.getEntity(mc.world); if(e == null || e == mc.player) return; int totalpops = 1; if (pops.containsKey(e.getName())) { totalpops = pops.get(e.getName()); pops.put(e.getName(), totalpops++); } else { pops.put(e.getName(), totalpops); } if(e == mc.player) return; if(ignoreFriends.getValue() && FriendManager.isFriend(e.getName())) return; if(msgPlayer.getValue() && !LeapFrog.getModuleManager().getModule(AutoEZ.class).isToggled()) { mc.player.sendChatMessage("/msg " + e.getName() + " " + "You're poppin!" + " " + UtilManager.getSuffix()); } if(suffix.getValue()) { Chatutil.sendMessage("Player " + ChatFormatting.RED + e.getName() + ChatFormatting.RESET + " " + "has popped " + totalpops + " times!" + UtilManager.getSuffix()); } else { Chatutil.sendMessage("Player " + ChatFormatting.RED + e.getName() + ChatFormatting.RESET + " " + "has popped " + totalpops + " times!"); } } } }); } <file_sep>package dev.leap.frog.Event.Movement; import dev.leap.frog.Event.LeapFrogEvent; public class EventPlayerMotionUpdate extends LeapFrogEvent { public int stage; public EventPlayerMotionUpdate(int stage) { super(); this.stage = stage; } } <file_sep>package dev.leap.frog.Module.Combat; import dev.leap.frog.Event.Movement.EventEntityCollision; import dev.leap.frog.Event.Network.EventPacket; import dev.leap.frog.Module.Module; import dev.leap.frog.Settings.Setting; import me.zero.alpine.fork.listener.EventHandler; import me.zero.alpine.fork.listener.Listener; import net.minecraft.network.play.server.SPacketEntityVelocity; import net.minecraft.network.play.server.SPacketExplosion; import org.lwjgl.input.Keyboard; public class Velocity extends Module { public Velocity() { super("Velocity", "Makes you take no knockback", Type.COMBAT); setKey(Keyboard.KEY_M); } Setting<Boolean> push = create("Push", true); Setting<Boolean> explosion = create("explosion", true); @EventHandler private Listener<EventPacket.ReceivePacket> move = new Listener<>(event -> { if(explosion.getValue() && event.getPacket() instanceof SPacketExplosion) { event.cancel(); } if(explosion.getValue() && event.getPacket() instanceof SPacketEntityVelocity) { event.cancel(); } }); @EventHandler private Listener<EventEntityCollision> collision = new Listener<>(event-> { if(push.getValue()) event.cancel(); }); } <file_sep>package dev.leap.frog; import dev.leap.frog.Event.EventProcessor; import dev.leap.frog.Manager.*; import dev.leap.frog.Module.Module; import dev.leap.frog.Util.Network.Sessionutil; import dev.leap.frog.Manager.CapeManager; import dev.leap.frog.Util.Wrapper; import me.zero.alpine.fork.bus.EventBus; import me.zero.alpine.fork.bus.EventManager; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.Display; @Mod(modid = LeapFrog.MODID, version = LeapFrog.VERSION) public class LeapFrog { public static final String MODID = "leapfrog"; public static final String VERSION = "1.0"; public static final EventBus EVENT_BUS = new EventManager(); public static final Logger log = LogManager.getLogger("leap"); private static ModuleManager moduleManager; private static SettingManager settingManager; private static DiscordManager discordManager; private static CommandManager commandManager; private static CapeManager capeManager; public static FriendManager friendManager; private static EventProcessor eventManager; private static FileManager fileManager; private static HudManager hudManager; @EventHandler public void init(FMLInitializationEvent event) { System.out.println("Starting Client"); MinecraftForge.EVENT_BUS.register(this); log.info("Starting Client"); //register managers settingManager = new SettingManager(); // settings manager must come BEFORE module manager or returns null fileManager = new FileManager(); moduleManager = new ModuleManager(); eventManager = new EventProcessor(); hudManager = new HudManager(); capeManager = new CapeManager(); commandManager = new CommandManager(); discordManager = new DiscordManager(); friendManager = new FriendManager(); hudManager = new HudManager(); fileManager.load(); Display.setTitle("LeapFrog Client"); } public static ModuleManager getModuleManager() { return moduleManager; } public static SettingManager getSettingManager() { return settingManager; } public static FileManager getFileManager() { return fileManager; } public static DiscordManager getDiscordManager() { return discordManager; } public static EventProcessor getEventProcessor() { return eventManager; } public static CapeManager getCapeManager() { return capeManager; } public static FriendManager getFriendManager() { return friendManager; } @SubscribeEvent public void key(InputEvent e) { if(Wrapper.getMC().world == null || Wrapper.getMC().player == null) return; try { if(Keyboard.isCreated()) { if(Keyboard.getEventKeyState()) { int keyCode = Keyboard.getEventKey(); if(keyCode <= 0) return; for(Module m : moduleManager.modules) { if(m.getKey() == keyCode && keyCode > 0) { m.toggle(); } } } } } catch (Exception q) { q.printStackTrace(); } } } <file_sep>package dev.leap.frog.GUI.HUD; import dev.leap.frog.Manager.UtilManager; public class Component extends UtilManager { private int x; private int y; private int width; private int height; private String name; public Component(int width, int height, String Name){ this.x = width; this.y = height; this.name = Name; } public void Render(int mouseX, int mouseY){ this.Render(mouseX,mouseY); } public void Click(int mouseX, int mouseY, int mouseButton){ } } <file_sep>package dev.leap.frog.Manager; import club.minnced.discord.rpc.DiscordEventHandlers; import club.minnced.discord.rpc.DiscordRPC; import club.minnced.discord.rpc.DiscordRichPresence; import club.minnced.discord.rpc.DiscordUser; import dev.leap.frog.LeapFrog; import dev.leap.frog.Util.Entity.Playerutil; import dev.leap.frog.Util.Render.Chatutil; import me.zero.alpine.fork.listener.EventHandler; import me.zero.alpine.fork.listener.Listener; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreenServerList; import net.minecraft.util.math.MathHelper; import net.minecraftforge.client.event.ClientChatEvent; import net.minecraftforge.client.event.ClientChatReceivedEvent; import javax.annotation.Nullable; import java.util.Objects; public class DiscordManager { private DiscordRichPresence discordRichPresence = new DiscordRichPresence(); private Minecraft mc = Minecraft.getMinecraft(); private DiscordRichPresence presence = new DiscordRichPresence(); private Thread thread; private DiscordRPC lib = DiscordRPC.INSTANCE; public DiscordManager() { Start(); } public void Start() { String applicationId = "830252222372773908"; String steamId = ""; DiscordEventHandlers handlers = new DiscordEventHandlers(); handlers.ready = (user) -> System.out.println("Ready!"); lib.Discord_Initialize(applicationId, handlers, true, steamId); lib.Discord_UpdatePresence(presence); presence.largeImageKey = "leapfrog512"; this.thread = new Thread(() -> { while (!Thread.currentThread().isInterrupted()) { lib.Discord_RunCallbacks(); presence.details = setDetails(); presence.state = setState(); lib.Discord_UpdatePresence(presence); try { Thread.sleep(2000); } catch (InterruptedException ignored) { } } }, "RPC-Callback-Handler"); thread.start(); } public void Stop() { if(!this.thread.isInterrupted() || thread.isAlive()) { this.thread.interrupt(); this.lib.Discord_Shutdown(); this.lib.Discord_ClearPresence(); return; } } private String setState() { // mc.player != null will run first String back = discordRichPresence.state; if(mc.player == null) return "Main menu"; if(mc.world != null && LeapFrog.getModuleManager().getModuleName("ClickGUI").isToggled()) { return "Configuring Client"; } if(mc.player.moveStrafing != 0 && mc.player.moveForward != 0) { return "Moving " + Playerutil.getSpeedInKM() + " KM/H"; } if(mc.player.isElytraFlying()) { return "Zooming"; } return back; } private String setDetails() { String detail = discordRichPresence.details; if(mc.player == null) return "Leapfrog on top!"; if(mc.isSingleplayer()) { return mc.player.getName() + " | " + "Singleplayer"; } if(mc.player != null && !mc.isSingleplayer() && !(Objects.requireNonNull(mc.getCurrentServerData()).serverIP == null)) { return mc.player.getName() + " | " + "Multiplayer"; } return detail; } } <file_sep>package dev.leap.frog.Module.Exploit; import dev.leap.frog.Event.Movement.EventPlayerMotionUpdate; import dev.leap.frog.Module.Module; import me.zero.alpine.fork.listener.EventHandler; import me.zero.alpine.fork.listener.Listener; import net.minecraft.network.play.client.CPacketPlayer; import org.lwjgl.input.Keyboard; public class ElytraBypass extends Module { public ElytraBypass() { super("ElytraFlyBypass", "Allows you to fly in 2b!", Type.EXPLOIT); setKey(Keyboard.KEY_P); } @EventHandler public Listener<EventPlayerMotionUpdate> MotionListener = new Listener<>(event-> { mc.player.noClip = true; double down = 0; mc.player.connection.sendPacket(new CPacketPlayer.PositionRotation(mc.player.posX + mc.player.motionX, mc.player.posY - 1337, mc.player.posZ + mc.player.motionZ, mc.player.rotationYaw, mc.player.rotationPitch, true)); }); } <file_sep>package dev.leap.frog.Mixin; import dev.leap.frog.Event.Network.EventPacket; import dev.leap.frog.LeapFrog; import io.netty.channel.ChannelHandlerContext; import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(NetworkManager.class) public class MixinNetworkManager { @Inject(method = "channelRead0", at = @At("HEAD"), cancellable = true) private void receive(ChannelHandlerContext context, Packet<?> packet, CallbackInfo callback) { EventPacket eventPacket = new EventPacket.ReceivePacket(packet); LeapFrog.EVENT_BUS.post(eventPacket); if (eventPacket.isCancelled()) { callback.cancel(); } } @Inject(method = "sendPacket(Lnet/minecraft/network/Packet;)V", at = @At("HEAD"), cancellable = true) private void send(Packet<?> packet, CallbackInfo callback) { EventPacket eventPacket = new EventPacket.SendPacket(packet); LeapFrog.EVENT_BUS.post(eventPacket); if (eventPacket.isCancelled()) { callback.cancel(); } } @Inject(method = "exceptionCaught", at = @At("HEAD"), cancellable = true) private void exception(ChannelHandlerContext exc, Throwable exc_, CallbackInfo callback) { if (exc_ instanceof Exception) { callback.cancel(); } } } <file_sep>package dev.leap.frog.Module.Render; import dev.leap.frog.Event.Render.RenderEvent; import dev.leap.frog.Manager.UtilManager; import dev.leap.frog.Module.Module; import dev.leap.frog.Settings.Setting; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import java.util.ArrayList; public class HoleESP extends Module { public HoleESP() { super("HoleESP", "Shows holes that are safe nearby", Type.RENDER); } Setting<Integer> distance = create("Distance", 75, 0, 250); private ArrayList<BlockPos> holes = new ArrayList<>(); private double x; private double y; private double z; private BlockPos playerPosition = new BlockPos(x, y, z); @Override public void onUpdate() { x = mc.player.posX; y = mc.player.posY; z = mc.player.posZ; holes.clear(); Vec3d position = new Vec3d(x, y, z); for(BlockPos pos : holes) { } } @Override public void onRender(RenderEvent event) { if(UtilManager.nullCheck()) return; if(!holes.isEmpty() && holes != null) { holes.forEach(hole -> { }); } } } <file_sep>package dev.leap.frog.Mixin; import dev.leap.frog.Event.Render.EventRenderBlockFall; import dev.leap.frog.LeapFrog; import net.minecraft.client.renderer.entity.RenderFallingBlock; import net.minecraft.entity.item.EntityFallingBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(RenderFallingBlock.class) public class MixinFallingBlock { @Inject(method = "doRender", at = @At("HEAD"), cancellable = true) public void onRender(EntityFallingBlock entity, double x, double y, double z, float entityYaw, float partialTicks, CallbackInfo ci) { EventRenderBlockFall packet = new EventRenderBlockFall(); LeapFrog.EVENT_BUS.post(packet); if(packet.isCancelled()) { ci.cancel(); } } } <file_sep>package dev.leap.frog.Event.World; import dev.leap.frog.Event.LeapFrogEvent; import net.minecraft.entity.Entity; public class EventEntityRemoved extends LeapFrogEvent { private Entity entity; public EventEntityRemoved(Entity entity) { this.entity = entity; } } <file_sep>package dev.leap.frog.Event.Network; import dev.leap.frog.Event.LeapFrogEvent; public class EventPacketUpdate extends LeapFrogEvent { } <file_sep>package dev.leap.frog.Util.Math; import dev.leap.frog.Manager.UtilManager; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.util.math.Vec3d; public class Mathutil extends UtilManager { public static double[] directionSpeed(double speed) { final Minecraft mc = Minecraft.getMinecraft(); float forward = mc.player.movementInput.moveForward; float side = mc.player.movementInput.moveStrafe; float yaw = mc.player.prevRotationYaw + (mc.player.rotationYaw - mc.player.prevRotationYaw) * mc.getRenderPartialTicks(); if (forward != 0) { if (side > 0) { yaw += (forward > 0 ? -45 : 45); } else if (side < 0) { yaw += (forward > 0 ? 45 : -45); } side = 0; // forward = clamp(forward, 0, 1); if (forward > 0) { forward = 1; } else if (forward < 0) { forward = -1; } } final double sin = Math.sin(Math.toRadians(yaw + 90)); final double cos = Math.cos(Math.toRadians(yaw + 90)); final double posX = (forward * speed * cos + side * speed * sin); final double posZ = (forward * speed * sin - side * speed * cos); return new double[] { posX, posZ }; } public static Vec3d process(Entity entity, double x, double y, double z) { return new Vec3d( (entity.posX - entity.lastTickPosX) * x, (entity.posY - entity.lastTickPosY) * y, (entity.posZ - entity.lastTickPosZ) * z); } public static Vec3d getInterpolatedPos(Entity entity, double ticks) { // render event return new Vec3d(entity.lastTickPosX, entity.lastTickPosY, entity.lastTickPosZ).add(process(entity, ticks, ticks, ticks)); // x, y, z. } } <file_sep>package dev.leap.frog.Manager; import dev.leap.frog.Command.Command; import dev.leap.frog.Command.Commands.Toggle; import dev.leap.frog.Util.Render.Chatutil; import me.zero.alpine.fork.listener.EventHandler; import me.zero.alpine.fork.listener.Listener; import net.minecraftforge.client.event.ClientChatEvent; import java.util.ArrayList; import java.util.List; public class CommandManager { public static List<Command> commands = new ArrayList<>(); private String prefix = "."; public CommandManager() { if(commands == null) { commands = new ArrayList<>(); } Add(new Toggle()); } public void Add(Command command) { commands.add(command); } @EventHandler private Listener<ClientChatEvent> clientChatEventListener = new Listener<>(event -> { if(event.getMessage().startsWith(prefix)) { event.setCanceled(true); Chatutil.sendMessage("message"); } else { return; } }); } <file_sep>package dev.leap.frog.Mixin; import dev.leap.frog.Event.Movement.EventPlayerMove; import dev.leap.frog.Event.Network.EventPacketUpdate; import dev.leap.frog.LeapFrog; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.MoverType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(EntityPlayerSP.class) public class MixinEntityPlayerSP { @Inject(method = "move", at = @At("HEAD"), cancellable = true) public void playerUpdate(MoverType type, double x, double y, double z, CallbackInfo ci) { EventPlayerMove event = new EventPlayerMove(type, x, y, z); LeapFrog.EVENT_BUS.post(event); if(ci.isCancelled()) { event.cancel(); } } @Inject(method = "onUpdate", at = @At("HEAD"), cancellable = true) public void updateEvent(CallbackInfo ci) { EventPacketUpdate packet = new EventPacketUpdate(); LeapFrog.EVENT_BUS.post(packet); if(packet.isCancelled()) { ci.cancel(); } } } <file_sep>package dev.leap.frog.Module.Combat; import dev.leap.frog.LeapFrog; import dev.leap.frog.Module.Module; import dev.leap.frog.Settings.Setting; import dev.leap.frog.Util.Entity.Playerutil; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.init.Items; import net.minecraft.inventory.ClickType; import net.minecraft.item.ItemStack; public class AutoTotem extends Module { // TODO: Rewite so return methods + fix offhand glitches public AutoTotem() { super("Auto Totem", "Puts totem in offhand", Type.COMBAT); } Setting<Boolean> soft = create("Soft", true); public int totems; boolean moving = false; boolean returnI = false; @Override public void onUpdate() { // if you change the instace of current screen it will slow down if(mc.player == null) return; if (mc.currentScreen instanceof GuiContainer || LeapFrog.getModuleManager().getModule(OffHand.class).isToggled() && OffHand.INSTANCE.health.getValue() < Playerutil.getPlayerHealth()) return; if (mc.player.getHeldItemOffhand().getItem() != Items.TOTEM_OF_UNDYING) { if (returnI) { int t = -1; for (int i = 0; i < 45; i++) { if (mc.player.inventory.getStackInSlot(i).isEmpty()) { t = i; break; } } if (t == -1) { return; } mc.playerController.windowClick(0, t < 9 ? t + 36 : t, 0, ClickType.PICKUP, mc.player); returnI = false; } totems = mc.player.inventory.mainInventory.stream().filter(itemStack -> itemStack.getItem() == Items.TOTEM_OF_UNDYING).mapToInt(ItemStack::getCount).sum(); if (mc.player.getHeldItemOffhand().getItem() == Items.TOTEM_OF_UNDYING) { totems++; } else { if (soft.getValue() && !mc.player.getHeldItemOffhand().isEmpty()) { return; } if (moving) { mc.playerController.windowClick(0, 45, 0, ClickType.PICKUP, mc.player); moving = false; if (!mc.player.inventory.getItemStack().isEmpty()) { returnI = true; } return; } if (mc.player.inventory.getItemStack().isEmpty()) { if (totems == 0) { return; } int t = -1; for (int i = 0; i < 45; i++) { if (mc.player.inventory.getStackInSlot(i).getItem() == Items.TOTEM_OF_UNDYING) { t = i; break; } } if (t == -1) { return; } mc.playerController.windowClick(0, t < 9 ? t + 36 : t, 0, ClickType.PICKUP, mc.player); moving = true; } else if (!soft.getValue()) { int t = -1; for (int i = 0; i < 45; i++) { if (mc.player.inventory.getStackInSlot(i).isEmpty()) { t = i; break; } } if (t == -1) { return; } mc.playerController.windowClick(0, t < 9 ? t + 36 : t, 0, ClickType.PICKUP, mc.player); } } } } } <file_sep>package dev.leap.frog.Event.World; import dev.leap.frog.Event.LeapFrogEvent; public class EventSetDayTime extends LeapFrogEvent { long time; public EventSetDayTime(long time) { this.time = time; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } } <file_sep>package dev.leap.frog.Event.Movement; import dev.leap.frog.Event.LeapFrogEvent; public class EventPlayerTravel extends LeapFrogEvent { } <file_sep>package dev.leap.frog.Module.Combat; import dev.leap.frog.Event.Network.EventPacket; import dev.leap.frog.LeapFrog; import dev.leap.frog.Manager.FriendManager; import dev.leap.frog.Module.Module; import dev.leap.frog.Settings.Setting; import dev.leap.frog.Util.Entity.Entityutil; import me.zero.alpine.fork.listener.EventHandler; import me.zero.alpine.fork.listener.Listener; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.monster.IMob; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.entity.passive.IAnimals; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemSword; import net.minecraft.network.play.client.CPacketPlayerDigging; import net.minecraft.network.play.client.CPacketUseEntity; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraftforge.fml.common.Mod; import org.lwjgl.input.Keyboard; public class KillAura extends Module { public KillAura() { super("KillAura", "Attacks entites for you", Type.COMBAT); } Setting<Integer> distance = create("Distance", 5, 0, 10); Setting<Boolean> delay = create("Delay", true); // vanilla hit delay Setting<Boolean> rotate = create("Rotate", true); Setting<Boolean> smartCheck = create("Smart check", true); Setting<Boolean> switchSlot = create("Switch slot", true); Setting<Boolean> players = create("Players", true); Setting<Boolean> hostiles = create("Hostiles", false); Setting<Boolean> passive = create("Passive", true); Setting<Boolean> ignoreFriends = create("Ignore friends", true); @Override public void onUpdate() { if(mc.player == null || mc.player.isDead || mc.world.loadedEntityList.isEmpty()) return; if(switchSlot.getValue() && mc.player.getHeldItemMainhand().getItem() instanceof ItemSword) { swapItems(); } } private void swapItems() { int slot = -1; for(int i = 0; i < 9; i++) { if(mc.player.inventory.getStackInSlot(i).getItem() instanceof ItemSword) { slot = i; mc.player.inventory.currentItem = i; mc.playerController.updateController(); break; } } } } <file_sep>package dev.leap.frog.Module.Combat; import dev.leap.frog.Manager.FriendManager; import dev.leap.frog.Module.Module; import dev.leap.frog.Settings.Setting; import dev.leap.frog.Util.Block.Blockutil; import dev.leap.frog.Util.Entity.Entityutil; import dev.leap.frog.Util.Render.Chatutil; import net.minecraft.block.Block; import net.minecraft.block.BlockEnderChest; import net.minecraft.block.BlockObsidian; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.network.play.client.CPacketEntityAction; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class AutoTrap extends Module { // TODO: Rewrite AutoTrap public AutoTrap() { super("Auto Trap", "Traps enemies", Type.COMBAT); } Setting<TrapMode> mode = create("Mode", TrapMode.Normal); Setting<Boolean> notify = create("Notify", true); Setting<Integer> blocksperTick = create("Ticks", 4, 0, 8); Setting<Boolean> toggle = create("Toggle", true); Setting<Boolean> rotate = create("Rotate", true); private String lastTickTargetName = ""; private int playerHotbarSlot = -1; private int lastHotbarSlot = -1; private boolean isSneaking = false; private int offsetStep = 0; private boolean firstRun = true; @Override public void onEnable() { if(mc.player == null) { toggle(); return; } firstRun = true; playerHotbarSlot = mc.player.inventory.currentItem; lastHotbarSlot = -1; if (notify.getValue()) { Chatutil.setModuleMessage(this); } } @Override public void onDisable() { if (mc.player == null | mc.world == null) return; if (lastHotbarSlot != playerHotbarSlot && playerHotbarSlot != -1) mc.player.inventory.currentItem = playerHotbarSlot; if (isSneaking) { mc.player.connection.sendPacket(new CPacketEntityAction(mc.player, CPacketEntityAction.Action.STOP_SNEAKING)); isSneaking = false; } playerHotbarSlot = -1; lastHotbarSlot = -1; if (notify.getValue()) { Chatutil.setModuleMessage(this); } } @Override public void onUpdate() { EntityPlayer target = findClosestTarget(); if(target == null) { if(firstRun) { firstRun = false; if(notify.getValue()) { Chatutil.sendClientSideMessgage("Auto trap waiting for target"); } } return; } if(findObsidianInHotbar() == -1) { if(notify.getValue()) { Chatutil.sendClientSideMessgage("No obsidian found! toggling"); } toggle(); return; } if (firstRun) { firstRun = false; lastTickTargetName = target.getName(); if (notify.getValue()) { Chatutil.sendClientSideMessgage("Enabled next target " + lastTickTargetName); } } else if (!lastTickTargetName.equals(target.getName())) { lastTickTargetName = target.getName(); offsetStep = 0; if (notify.getValue()) { Chatutil.sendClientSideMessgage("New target found " + lastTickTargetName); } } if (toggle.getValue()) { if (Entityutil.IsEntityTrapped(target)) { toggle(); return; } } final List<Vec3d> placeTargets = new ArrayList<Vec3d>(); switch(mode.getValue()) { case Normal: Collections.addAll(placeTargets, offsetsDefault); case Face: Collections.addAll(placeTargets, facePlace); case Feet: Collections.addAll(placeTargets, feetPlace); } int blocksPlaced = 0; while (blocksPlaced < this.blocksperTick.getValue()) { if (offsetStep >= placeTargets.size()) { offsetStep = 0; break; } final BlockPos offset_pos = new BlockPos((Vec3d) placeTargets.get(offsetStep)); final BlockPos target_pos = new BlockPos(target.getPositionVector()).down().add(offset_pos.getX(), offset_pos.getY(), offset_pos.getZ()); boolean shouldTryPlace = true; if (!mc.world.getBlockState(target_pos).getMaterial().isReplaceable()) shouldTryPlace = false; for (final Entity entity : mc.world.getEntitiesWithinAABBExcludingEntity((Entity) null, new AxisAlignedBB(target_pos))) { if (!(entity instanceof EntityItem) && !(entity instanceof EntityXPOrb)) { shouldTryPlace = false; break; } } if (shouldTryPlace && Blockutil.placeBlock(target_pos, findObsidianInHotbar(), rotate.getValue(), rotate.getValue(), EnumHand.MAIN_HAND)) { ++blocksPlaced; } offsetStep++; } } public EntityPlayer findClosestTarget() { if (mc.world.playerEntities.isEmpty()) return null; EntityPlayer closestTarget = null; for (final EntityPlayer target : mc.world.playerEntities) { if (target == mc.player) continue; if (FriendManager.isFriend(target.getName())) continue; if (!Entityutil.isLiving((Entity)target)) continue; if (target.getHealth() <= 0.0f) continue; if (closestTarget != null) if (mc.player.getDistance(target) > mc.player.getDistance(closestTarget)) continue; closestTarget = target; } return closestTarget; } private int findObsidianInHotbar() { for (int i = 0; i < 9; ++i) { final ItemStack stack = mc.player.inventory.getStackInSlot(i); if (stack != ItemStack.EMPTY && stack.getItem() instanceof ItemBlock) { final Block block = ((ItemBlock) stack.getItem()).getBlock(); if (block instanceof BlockEnderChest) return i; else if (block instanceof BlockObsidian) return i; } } return -1; } private Vec3d[] facePlace = new Vec3d[] { new Vec3d(0.0, 0.0, -1.0), new Vec3d(1.0, 0.0, 0.0), new Vec3d(0.0, 0.0, 1.0), new Vec3d(-1.0, 0.0, 0.0), new Vec3d(0.0, 1.0, -1.0), new Vec3d(1.0, 1.0, 0.0), new Vec3d(0.0, 1.0, 1.0), new Vec3d(-1.0, 1.0, 0.0), new Vec3d(0.0, 2.0, -1.0), new Vec3d(0.0, 3.0, -1.0), new Vec3d(0.0, 3.0, 1.0), new Vec3d(1.0, 3.0, 0.0), new Vec3d(-1.0, 3.0, 0.0), new Vec3d(0.0, 3.0, 0.0) }; private Vec3d[] feetPlace = new Vec3d[] { new Vec3d(0.0, 0.0, -1.0), new Vec3d(1.0, 0.0, 0.0), new Vec3d(0.0, 0.0, 1.0), new Vec3d(-1.0, 0.0, 0.0), new Vec3d(0.0, 1.0, -1.0), new Vec3d(0.0, 2.0, -1.0), new Vec3d(1.0, 2.0, 0.0), new Vec3d(0.0, 2.0, 1.0), new Vec3d(-1.0, 2.0, 0.0), new Vec3d(0.0, 3.0, -1.0), new Vec3d(0.0, 3.0, 1.0), new Vec3d(1.0, 3.0, 0.0), new Vec3d(-1.0, 3.0, 0.0), new Vec3d(0.0, 3.0, 0.0) }; private Vec3d[] offsetsDefault = new Vec3d[] { new Vec3d(0.0, 0.0, -1.0), new Vec3d(1.0, 0.0, 0.0), new Vec3d(0.0, 0.0, 1.0), new Vec3d(-1.0, 0.0, 0.0), new Vec3d(0.0, 1.0, -1.0), new Vec3d(1.0, 1.0, 0.0), new Vec3d(0.0, 1.0, 1.0), new Vec3d(-1.0, 1.0, 0.0), new Vec3d(0.0, 2.0, -1.0), new Vec3d(1.0, 2.0, 0.0), new Vec3d(0.0, 2.0, 1.0), new Vec3d(-1.0, 2.0, 0.0), new Vec3d(0.0, 3.0, -1.0), new Vec3d(0.0, 3.0, 0.0) }; private enum TrapMode { Normal, Feet, Face } } <file_sep>package dev.leap.frog.Event.Movement; import dev.leap.frog.Event.LeapFrogEvent; public class EventPlayerStoppedUsingItem extends LeapFrogEvent { }
3bbd6f992504db4a89ea40268eec08e8ff691990
[ "Markdown", "Java", "Gradle" ]
50
Java
lolix-notepad/Leapfrog-Client
f0d281752c58a710159e3dff6a258f515a02a150
899c696be8667764e0a19d417dbc3351c0d52092
refs/heads/master
<repo_name>Maxim-Doronin/KnowledgeBase<file_sep>/KnowledgeBase-WebServer/src/java/com/knowledge/utils/MapHelper.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.knowledge.utils; import java.util.Map; import java.util.Map.Entry; /** * * @author doro1 */ public class MapHelper { public static String map2str(Map<Integer, String> map) { String result = ""; for (Entry<Integer, String> entry : map.entrySet()) { result += String.valueOf(entry.getKey()) + " : " + entry.getValue() + "\n"; } return result; } } <file_sep>/KnowledgeBase-WebServer/src/java/com/knowledge/ws/KnowledgeBaseWebService.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.knowledge.ws; import com.knowledge.session.KnowledgeBaseSession; import com.knowledge.session.KnowledgeBaseSessionLocal; import com.knowledge.utils.MapHelper; import java.util.List; import java.util.Map; import javax.ejb.EJB; import javax.jws.WebService; import javax.ejb.Stateless; import javax.jws.WebMethod; /** * * @author doro1 */ @WebService(serviceName = "KnowledgeBaseWebService") public class KnowledgeBaseWebService { @EJB private KnowledgeBaseSessionLocal session; @WebMethod() public int addNewRecord(String title, String summary) { return session.addNewRecord(title, summary); } @WebMethod() public void addTag(int recordId, List<Integer> tagIds) { session.addTag(recordId, tagIds); } @WebMethod() public void addFile(int recordId, String fileName, byte[] fileData) { session.addFile(recordId, fileName, fileData); } @WebMethod() public int createTag(String tagName){ return session.createTag(tagName); } @WebMethod() public byte[] getFile(int recordId, String fileName) { return session.getFile(recordId, fileName); } @WebMethod() public void removeTag(int tagId) { session.removeTag(tagId); } @WebMethod() public String getTagMap() { return MapHelper.map2str(session.getTagMap()); } @WebMethod() public String getRecordMap() { return MapHelper.map2str(session.getRecordMap()); } @WebMethod() public String getTaggedRecords(int tagId) { return MapHelper.map2str(session.getTaggedRecords(tagId)); } @WebMethod() public String sayHello(String str) { return "hello" + str; } }
3cee2d4a2cce0d5dc8a732da03d162add0b6aac8
[ "Java" ]
2
Java
Maxim-Doronin/KnowledgeBase
de548d56b488e7eb3eea8ccb625a9f5b32716c58
26541b8ff208933c693fd6acaa5f3ba0681d118a
refs/heads/master
<file_sep>var fs = require('fs'); var write_to_file = function(data){ fs.appendFile("neurosky_data", data, function(err){ if(err){ console.log(err); } else{ console.log("Successfully saved data"); } }) } var data_stream = function(data){ if( data.poorSignalLevel == 0){ var data_to_write = data.eSense.attention+","+data.eSense.meditation write_to_file( data_to_write+"\n" ) counter+=1; } console.log(data.poorSignalLevel, counter); } exports.data_stream = data_stream; exports.write_to_file = write_to_file;
2a685497db47720ce6f1717c8508058efefdf205
[ "JavaScript" ]
1
JavaScript
mdimarco/Brite
751291fe6740f5f9fa623ff3a8d4507a7cbfc850
ca4b653e2018b5f7c831b21c961c768b25834689
refs/heads/master
<repo_name>ekokman/calendar<file_sep>/README.rst Данный проект предствалет календарь с днями рождения коллег. Возможно выполнение следующий действий: - Добавлять новые дни рождения коллег - Просматривать список из всех дней рождений коллег - Просматривать список дней рождений за указанный месяц - Удалять дни рождения коллег - Искаь дни рождения коллеги по его имени Для работы проекта требуется: - Установить и настроить виртуальное окружение - Установить зависимость от пакетов pip версии 18.0 или выше с помощь команды pip install -r requirements.txt - Запустить проект с помощью команды python3 -m app.main <file_sep>/requirements.txt click==6.7 future==0.16.0 pkg-resources==0.0.0 PTable==0.9.2 six==1.11.0 wcwidth==0.1.7 <file_sep>/app/main.py from .commands import cli, add, delete, list_full, search_month, search cli.add_command(add) cli.add_command(delete) cli.add_command(list_full) cli.add_command(search) cli.add_command(search_month) if __name__ == '__main__': cli()<file_sep>/app/models.py import json import uuid import os import datetime from pathlib import Path from collections import namedtuple from prettytable import PrettyTable class Person(object): def __init__(self, name, surname, dob): self.id = uuid.uuid4().hex self.name = name self.surname = surname self.dob = dob def __eq__(self, other): return self.name == other.name and self.surname == other.surname and \ self.dob == other.dob def to_dict(self): dict_of_person = {'id': self.id, 'name': self.name, 'surname': self.surname, 'dob': self.dob} return dict_of_person class PersonList(object): def __init__(self, storage): self.data = storage.read() self.storage = storage self.counter = -1 self.data_of_person = self.from_dict() self.index = len(self.data) def __len__(self): return len(self.data) def __iter__(self): return self def __next__(self): if self.counter <= (len(self) - 2): self.counter += 1 return self.data_of_person[self.counter] else: raise StopIteration def append(self, new_person): self.data.append(new_person.to_dict()) return self.data def save(self): self.storage.write(self.data) def from_dict(self): self.data_of_person = [] for i in self.data: d_named = namedtuple("Person", i.keys())(*i.values()) person_from_dict = Person(d_named.name, d_named.surname, d_named.dob) self.data_of_person.append(person_from_dict) return self.data_of_person def show(self, output_format): if output_format == 'table': table = Table() for item in self.data: table.add_row(item) table.get_table() def search_by_name(self, name): list_of_names = [] for item in self.data: if name in item['name']: list_of_names.append(item) if len(list_of_names) >= 1: return list_of_names else: raise Exception("Person with this name is not on the list.") def delete_person(self, id_of_person): count_id = 0 del_i = 0 for item in self.data: if item['id'].startswith(id_of_person): count_id += 1 del_i = item if count_id >= 2: raise Exception("Id is repeated") if count_id == 0: raise Exception("There is no person with this id in the list") else: self.data.remove(del_i) return self.data def search_by_month(self, month): list_of_month = [] for item in self.data: dob = datetime.datetime.strptime(item['dob'], '%d-%m-%Y') if int(month) == dob.month: list_of_month.append(item) if len(list_of_month) >= 1: return list_of_month else: raise Exception("Person happy birthday this month is not on the list") def show_searched_person(self, searched, output_format): if output_format == 'table': table = Table() for item in searched: table.add_row(item) table.get_table() class FileStorage(object): def __init__(self, path): self.path = path if not os.path.exists(self.path): self.create() def read(self): with open(self.path, 'r') as myfile: return json.loads(myfile.read()) def write(self, data): with open(self.path, 'w') as myfile: json.dump(data, myfile) def create(self): with open(self.path, 'tw') as myfile: myfile.write('[]') @classmethod def home_dir(cls): home_dir = str(Path.home()) full_path = os.path.join(home_dir, 'store.txt') return cls(full_path) class Table(object): def __init__(self): self.x = PrettyTable() self.x.field_names = ["Id", "Name", "Surname", "Dob"] def get_table(self): print(self.x) def add_row(self, i): self.x.add_row([i['id'], i['name'], i['surname'], i['dob']])<file_sep>/app/commands.py from . import models import click def init_person_list(): file_storage = models.FileStorage.home_dir() person_list = models.PersonList(file_storage) return person_list @click.group() def cli(): pass @click.command() @click.option('--name', '-n', help='Enter name') @click.option('--surname', '-s', help='Enter surname') @click.option('--dob', '-d', help='The date of birth format "dd-mm-yyyy"') def add(name, surname, dob): person_list = init_person_list() name = name.capitalize() surname = surname.capitalize() person = models.Person(name, surname, dob) if person in person_list: raise Exception("Person already exist") else: person_list.append(person) person_list.save() @click.command() @click.option('--id_of_person', '-i', help='Enter the id of the person you want to delete') def delete(id_of_person): person_list = init_person_list() person_list.delete_person(id_of_person) person_list.save() @click.command() def list_full(): person_list = init_person_list() person_list.show(output_format='table') @click.command() @click.option('--name', '-n', help='Enter the name of person you want to find') def search(name): person_list = init_person_list() name = name.capitalize() searched = person_list.search_by_name(name) person_list.show_searched_person(searched, output_format='table') @click.command() @click.option('--month', '-m', help='Enter your birth month to search') def search_month(month): person_list = init_person_list() searched = person_list.search_by_month(month) person_list.show_searched_person(searched, output_format='table')
d53fed2a5d939f978a3726e953be0a221ab4dfd3
[ "Python", "Text", "reStructuredText" ]
5
reStructuredText
ekokman/calendar
521d502966972b000fd8bfd9b6fcf145a47079bd
3f82b781a51907009c34e21b9305d8291a430a9d
refs/heads/master
<repo_name>mmarziano/js-looping-and-iteration-map-lab-v-000<file_sep>/index.js // Code your solution in this file. let drivers; function lowerCaseDrivers(array) { const lowerCaseDrivers = array.map(function(driver) { return driver.toLowerCase()}); return lowerCaseDrivers; } function nameToAttributes(drivers) { return drivers.map(function (driver) { const driverFirstName = driver.split(' ')[0]; const driverLastName = driver.split(' ')[1]; return { firstName: driverFirstName, lastName: driverLastName }; }); } function attributesToPhrase(drivers) { return drivers.map(function(driver) { const firstName = driver.name; const hometown = driver.hometown; return(`${firstName} is from ${hometown}`); }); }
19fc8f683da29d416ee3e38b122a5193fe63980c
[ "JavaScript" ]
1
JavaScript
mmarziano/js-looping-and-iteration-map-lab-v-000
fe9c506985fa609d9670611c07e4b536454d2da4
9be0d6c122b172026ab6425f439750f0273ec40b
refs/heads/master
<repo_name>OisinA/GeneticAlgorithms<file_sep>/src/com/oisinaylward/genetics/Population.java package com.oisinaylward.genetics; public class Population { private Snake[] snakes; public Population(int populationSize, boolean initialise) { snakes = new Snake[populationSize]; if(initialise) { for(int i = 0; i < populationSize; i++) { Snake s = new Snake(); addSnake(i, s); } } } public Snake getFittest() { Snake s = snakes[0]; for(int i = 1; i < snakes.length; i++) { if(s.getFitness() < snakes[i].getFitness()) { s = snakes[i]; } } return s; } public int getSize() { return snakes.length; } public Snake getSnake(int index) { return snakes[index]; } public void addSnake(int index, Snake s) { snakes[index] = s; } } <file_sep>/src/com/oisinaylward/genetics/Main.java package com.oisinaylward.genetics; public class Main { public static final Gene[] SOLUTION = {Gene.BEAK, Gene.CLAWS, Gene.POISON, Gene.SPEECH, Gene.CLEVER, Gene.FLIGHT}; public static void main(String[] args) { Population p = new Population(50, true); boolean isPerfect = false; int generations = 1; while(!isPerfect) { p = Genetics.evolve(p); generations++; int perfect = 0; Snake s = p.getFittest(); for(Gene g : s.getGenes()) { if(isInSolution(g)) { perfect++; } } if(perfect == 6) { break; } else { System.out.println("#" + generations + ": " + s); } } System.out.println("-------------------------"); System.out.println("Finished!"); System.out.println(p.getFittest().toString()); System.out.println("Fitness: " + p.getFittest().getFitness()); System.out.println("Generations: " + generations); System.out.println("-------------------------"); } public static boolean isInSolution(Gene g) { for(Gene gene : SOLUTION) { if(gene == g) { return true; } } return false; } } <file_sep>/README.md GeneticAlgorithms ================= A program I made in Java, to test Genetic Algorithms. <file_sep>/src/com/oisinaylward/genetics/Genetics.java package com.oisinaylward.genetics; import java.util.Random; public class Genetics { private static final double mutationRate = 0.05; private static final boolean elitism = false; private static final int tournamentSize = 5; public static Population evolve(Population p) { Population population = new Population(p.getSize(), false); int elitismOffset = 0; if(elitism) { population.addSnake(0, p.getFittest()); elitismOffset = 1; } for(int i = elitismOffset; i < population.getSize(); i++) { Snake parent1 = tournamentSelection(p); Snake parent2 = tournamentSelection(p); Snake child = crossover(parent1, parent2); population.addSnake(i, child); } for(int i = elitismOffset; i < population.getSize(); i++) { Snake s = population.getSnake(i); mutate(s); } return population; } public static Snake crossover(Snake parent1, Snake parent2) { Snake child = new Snake(); int takenFromOne = 0; for(int i = 0; i < 6; i++) { Gene g = parent1.getGenes()[i]; child.setGene(takenFromOne, g); takenFromOne++; } int takenFromTwo = 3; for(int i = 3; i < 6; i++) { if(takenFromTwo < 6) { for(Gene gene : child.getGenes()) { for(Gene g : parent2.getGenes()) { if(!child.containsGene(g)) { child.setGene(child.getIndex(gene), g); } } } } } System.out.println(child); return child; } public static void mutate(Snake s) { for(int i = 0; i < s.getGenes().length; i++) { if(Math.random() < mutationRate) { s.setGene(i, Gene.values()[new Random().nextInt(Gene.values().length)]); } } } public static Snake tournamentSelection(Population p) { Population population = new Population(tournamentSize, false); for(int i = 0; i < tournamentSize; i++) { int randomID = new Random().nextInt(p.getSize()); population.addSnake(i, p.getSnake(randomID)); } return population.getFittest(); } } <file_sep>/src/com/oisinaylward/genetics/Gene.java package com.oisinaylward.genetics; public enum Gene { FLIGHT, SCALES, BEAK, WRIGGLE, WHEELS, CLAWS, POISON, LEGS, CLEVER, SPEECH, ADVANCEDKNOWLEDGE, CREATEIDEAS, TEETH, HAIR, NOSE, CODE, SENSEOFTIME, EYESIGHT, SUPERHEARING, SUPERSMELL, ARMS; }
29588473021e3d35b5721a9b497836ef4a4cb3d7
[ "Markdown", "Java" ]
5
Java
OisinA/GeneticAlgorithms
6a9c5f999bd0e039c46412d2cf74c478df236c16
889d84ab21b180495c38c2f555e36c22a78f93f9
refs/heads/master
<repo_name>james-poore/movie-search-website<file_sep>/site.rb require 'rubygems' require 'bundler' require 'themoviedb' require 'pp' Bundler.require # Sinatra Configuration set :port, 4567 set :logging, true set :environment, :production # TMDB Configuration tmdb_api_key_file = File.open(File.join(File.dirname(__FILE__), "config/tmdb_api_key"), mode = "r") Tmdb::Api.key(tmdb_api_key_file.readline) Tmdb::Api.language("en") configuration = Tmdb::Configuration.new #Pages get '/' do now_playing = Tmdb::Movie.now_playing haml :home, :locals => {:now_playing => now_playing} end get '/movie/:movie_id' do |movie_id| movie = Tmdb::Movie.detail(movie_id) cast = Tmdb::Movie.casts(movie_id) similar_movies = Tmdb::Movie.similar_movies(movie_id) trailers = Tmdb::Movie.trailers(movie_id) images = Tmdb::Movie.images(movie_id)['backdrops'] haml :movie_info, :locals => {:movie => movie, :cast => cast, :similar_movies => similar_movies, :trailers => trailers, :images => images} end get '/tv/:show_id' do |show_id| show = Tmdb::TV.detail(show_id) cast = Tmdb::TV.cast(show_id) images = Tmdb::TV.images(show_id)['backdrops'] haml :show_info, :locals => {:show => show, :cast => cast, :images => images} end get '/person/:person_id' do |person_id| person = Tmdb::Person.detail(person_id) credits = Tmdb::Person.credits(person_id)['cast'] haml :person_info, :locals => {:person => person, :credits => credits} end get '/movies' do popular_movies = Tmdb::Movie.popular haml :movies, :locals => {:popular_movies => popular_movies} end get '/tv' do popular_shows = Tmdb::TV.popular haml :shows, :locals => {:popular_shows => popular_shows} end get '/people' do popular_people = Tmdb::Person.popular haml :people, :locals => {:popular_people => popular_people} end post '/search' do search_string = params[:search_string] # Search movies and people movies = Tmdb::Movie.find(search_string) people = Tmdb::Person.find(search_string) shows = Tmdb::TV.find(search_string) haml :search_results, :locals => {:movies => movies, :people => people, :shows => shows} end<file_sep>/README.md # movie-search-website Website that uses TMDB's API to search movies, TV shows, and actors <file_sep>/Gemfile source 'https://rubygems.org' ruby '2.0.0' gem 'sinatra', require: 'sinatra' gem 'haml' gem 'rake' gem 'daemons' # gem 'ruby-tmdb3' gem 'themoviedb' <file_sep>/daemon.rb require 'rubygems' gem 'daemons' require 'daemons' ENV['BUNDLE_GEMFILE'] ||= File.join(Dir.pwd, 'Gemfile') pwd = File.dirname(File.expand_path(__FILE__)) file = pwd + '/site.rb' Daemons.run_proc( 'site', # name of daemon :log_output => true ) do exec "ruby #{file}" end
d82b3d8e72720ed88da145c6e116ddee3a313c33
[ "Markdown", "Ruby" ]
4
Ruby
james-poore/movie-search-website
a36f757e483398205e69226aaebffa0b76435565
6aee261d063efd2b0f0fb1011e266d03aecbafb4
refs/heads/master
<repo_name>draptik/csharp-lambda-intro<file_sep>/code/LambdaDemos.Tests/FooExtensions.cs namespace LambdaDemos.Tests { public static class FooExtensions { public static int AddOne(this int i) { return i + 1; } } }<file_sep>/code/LambdaDemos.Tests/Demos.cs using System; using FluentAssertions; using Xunit; namespace LambdaDemos.Tests { public class Demos { public class HelloWorld { private static int Add(int a, int b) { return a + b; } [Fact] public void Adding_two_numbers_works() { Add(1, 2).Should().Be(3); } // TODO Intro to Expression Body vs Statement // TODO Intro to Extension Methods } public class ExtensionMethodDemo { // GOAL: Enrich some class // // Example: c# string class // // Option 1: Derive from String class (not allowed in C#, but in Java!) // class MyString : String // { // } // Option 2: Extension methods // NOTE: Extension classes in c# can't be nested! [Fact] public void ExtensionDemo_works_classic() // ReSharper disable once InvokeAsExtensionMethod => FooExtensions.AddOne(123).Should().Be(124); [Fact] public void ExtensionDemo_works() => 123.AddOne().Should().Be(124); } public class SingleInputSingleOutput { private static int AddOne(int i) => i + 1; [Fact] public void AddOne_works() => AddOne(1).Should().Be(2); private static int NumberOfDigits(int i) => i.ToString().Length; [Theory] [InlineData(1, 1)] [InlineData(12, 2)] [InlineData(123, 3)] public void NumberOfDigits_works(int input, int expected) => NumberOfDigits(input).Should().Be(expected); } public class WhatIsAFunction { [Fact] public void Function_works1() { // string -> int Func<string, int> foo = s => 42; foo("12345678").Should().Be(42); } [Fact] public void Function_works2() { // string -> int Func<string, int> foo = s => s.Length; foo("12345678").Should().Be(8); } [Fact] public void Function_works3() { // void -> int // No input, only output Func<int> foo = () => 42; foo().Should().Be(42); } } public class UsingAFunction { public class MyClass { public static int DoSomethingWithFunction(string s, Func<string, int> func) => func(s); } // string -> int Func<string, int> foo = s => s.Length; [Fact] public void DoSomethingWithFunction_works() => MyClass.DoSomethingWithFunction("abc", foo).Should().Be(3); } } }
be2818994b973043fa2291e9c651af3171e961fd
[ "C#" ]
2
C#
draptik/csharp-lambda-intro
f55e102c538ca4b9b49242195a1a1107a63b1bd6
6223863f403e4d757cce6879c36e669567e20702
refs/heads/master
<file_sep># NodeMCU Flasher (Easy) # [Download this file ESP8266Flasher.zip](https://github.com/tretyakovsa/Sonoff_Loader/raw/master/ESP8266Flasher.zip) <file_sep>#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino //Need libraries #include <ESP8266WebServer.h> #include <DNSServer.h> #include <WiFiManager.h> //https://github.com/tzapu/WiFiManager #include <ESP8266httpUpdate.h> #define TRIGGER_PIN 0 #define LED_PIN 13 // Светодиод void setup() { Serial.begin(115200); Serial.println("\n Starting"); pinMode(TRIGGER_PIN, INPUT); // Подключаемся к wifi если подключения нет уходим в основной цикл. pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, HIGH); WiFiManager wifiManager; wifiManager.autoConnect("sonoff-loader"); digitalWrite(LED_PIN, LOW); // } void loop() { // Проверяем подключины мы к роутеру и если да делаем перепрошивку модуля с сервера if (WiFi.status() == WL_CONNECTED) { digitalWrite(LED_PIN, HIGH); digitalWrite(LED_PIN, LOW); Serial.println("ESP Update"); //Обновляем оба файла с сервера webUpdate(); } } void webUpdate() { // отключаем перезагрузку после обновления FS ESPhttpUpdate.rebootOnUpdate(false); //Обнавляем FS t_httpUpdate_return ret = ESPhttpUpdate.updateSpiffs("http://backup.privet.lv/esp/sonoff/spiffs.0xBB000_flash_size_1Mb.256Kb_2017.10.11.bin"); // включаем перезагрузку после прошивки digitalWrite(LED_PIN, HIGH); ESPhttpUpdate.rebootOnUpdate(true); // Перепрошиваем модуль t_httpUpdate_return ret1 = ESPhttpUpdate.update("http://backup.privet.lv/esp/sonoff/build.0x00000_flash_size_1Mb.256Kb_2017.10.11.bin"); } <file_sep># Sonoff Loader (Arduino) ![alt](https://raw.githubusercontent.com/tretyakovsa/Sonoff_Loader/master/tutorial/screen.png) #### Used Libraries ``` #include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino //Need libraries #include <ESP8266WebServer.h> #include <DNSServer.h> #include <WiFiManager.h> //https://github.com/tzapu/WiFiManager #include <ESP8266httpUpdate.h> ``` ## Upload instruction ### [NodeMCU Flasher (Easy)](https://github.com/tretyakovsa/Sonoff_Loader/tree/master/ESP8266Flasher) ## Work example (Video) [![IMAGE ALT TEXT HERE](https://img.youtube.com/vi/0DNJrF5F8aM/0.jpg)](https://www.youtube.com/watch?v=0DNJrF5F8aM) [![IMAGE ALT TEXT HERE](https://img.youtube.com/vi/NrIrLw1rOdk/0.jpg)](https://www.youtube.com/watch?v=NrIrLw1rOdk&list=PL6NJTNxbvy-IPTDQk8XjTV41oRrFafrRi) ### Schematic ![alt](https://raw.githubusercontent.com/tretyakovsa/Sonoff_Loader/master/tutorial/sonoff.jpg) ## Othe... #### Sonoff: [https://github.com/tretyakovsa/Sonoff_WiFi_switch](https://github.com/tretyakovsa/Sonoff_WiFi_switch) #### Jalousie: [https://github.com/tretyakovsa/jaluzi](https://github.com/tretyakovsa/jaluzi) #### RGB: [https://github.com/renat2985/rgb](https://github.com/renat2985/rgb) #### Themes you can download here: [http://bootswatch.com/](http://bootswatch.com/) ## Donation If you like this project, you can give me a cup of coffee :) ### PayPal [![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=W4PURUNKWMRJW&lc=AU&item_name=esp8266&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted) ### WebMoney - USD Z242847016348 - RUS R466173026928 - EUR E555861976545
be5db8e22af08bfa714205b4e6896e7b4ba4251a
[ "Markdown", "C++" ]
3
Markdown
tretyakovsa/Sonoff_Loader
63e12b3dcb1923f4156b985d663b9fce8c0879d4
8a81d058a8d7db4340e8b7dbf828f22da49a5a3f
refs/heads/master
<repo_name>neistuff/Pymon<file_sep>/sounds/lv1/TODO.md Faut mettre les sons du lv 1 ici, Quentin. T'occupe pas de ce fichier, je l'enlèverai (lui ainsi que tous les fichiers inutiles) quand on rendra le truc. En bref, j'ferai le nettoyage a la fin. <file_sep>/repartition.md # Répartition des tâches : launcher : fait menu : fait par Antoine Unlock : fait par Antoine Lock : fait par Quentin levels (sons) : Fait par Quentin winsound, a faire ossaudiodev levels (random + list) : Fait par Quentin Jokers : fait par Quentin levels (fenêtre) : fait par Antoine Survival : fait par best : fait par Antoine debug : fait par Antoine, aidé par Quentin site : a faire si temps <file_sep>/sounds/lv2/TODO.md Comme pour le lv1 <file_sep>/README.md # Pymon Je me doute bien que personne ne lira le Readme, m'enfin bon. *Pymon* est un jeu de reconnaissance musicale codé en Python. C'est un projet de fin d'année d'ISN. (c) <NAME> et <NAME>. Bienvenue ! Vous avez le droit de le modifier et/ou de le redistribuer en précisant que l'original vient de nous et sans le vendre. Merci. Aussi, merci de ne pas toucher aux fichiers dans les dossiers "sounds" et "data". Cela pourrait entraîner des dysfonctionnements. Amusez vous bien ! :) --- ### English README Pretty sure nobody will ever read this, but anyway. *Pymon* is a musical recognition game created in Python. It's a project I've been making with a friend for the final exam of high school in IT. (c) <NAME> and <NAME>. Welcome ! You can edit the code and redistribute it with credit please, and without selling it. Thanks ! Oh and btw, the sounds are missing, because GitHub can't host sounds. Sorry. I may upload them somewhere one day. And don't touch the "data" files, this would cause the program to dysfunction. Have fun ! :) P.S.: Oh and sorry, but the whole game is in french because I don't attempt any english-speaking person to play this (it was not meant to, basically). Maybe I'll translate it, I really don't know. <file_sep>/pymon.py ##Petit message : #Pymon (c) <NAME> et <NAME>. Bienvenue dans le code source. Vous avez le droit de le modifier et/ou de le redistribuer en précisant que l'original vient de nous et sans le vendre. Merci. #-------------- Nota bene :----------------------- #Le programme est conçu pour tourner sous Windows uniquement pour l'instant, Linux devait être implanté, mais la documentation sur la librairie destinée a jouer les sons sous Linux (ossaudiodev) est insuffisante. Les tailles des fenêtres sont conçues pour avoir la dimension parfaite pour Windows 7/Aero désactivé. Ainsi, suivant l'OS/le thème, l'agencement peut ne pas être parfait. Cependant, cela est purement esthétique et n'affecte en rien le fonctionnement global du programme. Bon jeu ! ##Importation des modules from tkinter import * #Interface from random import * #Aleatoire import winsound #Lecture des sons # /!\ winsound s'importe comme sa et pas autrement ## Listes permetant de faire fonctionner le jeu # Les differentes listes de références suivant les niveau listNote_tuto=['sounds/tutorial/tuto_do.wav','sounds/tutorial/tuto_re.wav','sounds/tutorial/tuto_mi.wav','sounds/tutorial/tuto_fa.wav','sounds/tutorial/tuto_sol.wav','sounds/tutorial/tuto_la.wav','sounds/tutorial/tuto_si.wav'] # Fichier audio pouvant sortir au tuto listNote_lvl1=['sounds/lv1/lvl1_do.wav','sounds/lv1/lvl1_re.wav','sounds/lv1/lvl1_mi.wav','sounds/lv1/lvl1_fa.wav','sounds/lv1/lvl1_sol.wav','sounds/lv1/lvl1_la.wav','sounds/lv1/lvl1_si.wav'] # Fichier audio pouvant sortir au lvl 1 listNote_lvl2=['sounds/lv2/lvl2_do.wav','sounds/lv2/lvl2_re.wav','sounds/lv2/lvl2_mi.wav','sounds/lv2/lvl2_fa.wav','sounds/lv2/lvl2_sol.wav','sounds/lv2/lvl2_la.wav','sounds/lv2/lvl2_si.wav'] # Fichier audio pouvant sortir au lvl 2 listNote_lvl3=['sounds/lv3/lvl3_do.wav','sounds/lv3/lvl3_re.wav','sounds/lv3/lvl3_mi.wav','sounds/lv3/lvl3_fa.wav','sounds/lv3/lvl3_sol.wav','sounds/lv3/lvl3_la.wav','sounds/lv3/lvl3_si.wav'] # Fichier audio pouvant sortir au lvl 3 listNote_sur=['sounds/survival/sur_do.wav','sounds/survival/sur_re.wav','sounds/survival/sur_mi.wav','sounds/survival/sur_fa.wav','sounds/survival/sur_sol.wav','sounds/survival/sur_la.wav','sounds/survival/sur_si.wav'] # Fichier audio pouvant sortir au survival # Les différentes touches qui seront liés plus tard aux notes listKeyboard=['q','s','d','f','k','l','m'] ##Strings pour une couleur hexadécimale (purement esthétique) grisClair="#dedede" grisFonce="#3d3d3d" vertClair="#2fab3d" jauneClair="#fffd47" orangeClair="#ffab48" rougeClair="#ff2e2e" bleuClair="#5367ff" ##Définitions des fonctions permettant de définir l'OS de l'utilisateur global OSWin #Pour le réutiliser dans le reste du programme def OSchosenWin(): global OSWin OSWin=1 def OSchosenUnix(): global OSWin OSWin=0 ##Définition du launcher #Définition d'une fenêtre qui demande a l'utilisateur son OS et adapte la librairie en fonction def launch(): #Définition de la fenêtre launcher=Tk() launcher.title("Pymon launcher") def launcherCloseWin(): launcher.destroy() menu() OSchosenWin() def launcherCloseUnix(): launcher.destroy() menu() OSchosenUnix() #Afin de fermer la fenêtre en ouvrant le menu, on doit définir une fonction codant pour ça, sinon on doit #coder la fermeture de la fenêtre en tant que commande sur le bouton, mais dans ce cas là, on doit mettre "menu()" #en fin de fonction car on ne peut pas mettre plus de deux commandes sur un bouton. #On pouvait donc quitter le launcher sans choisir d'OS et le menu se lance quand même. #Définition des boutons. Ils doivent prendre toute la fenêtre donc pack() est plus utile OSquestion=Label(launcher,text="Bienvenue dans Pymon ! Choisissez votre OS :",anchor=CENTER,justify=CENTER) OSquestion.pack(fill=BOTH) unixButton=Button(launcher,text="Windows",command=launcherCloseWin,bg="blue",activebackground=bleuClair) unixButton.pack(fill=BOTH) #Ainsi, l'utilisateur ne peut pas lancer le programme sans choisir d'OS #(grâce a la fonction launcherClose que l'on vient de créer). #Il peut quitter le launcher manuellement, mais dans ce cas le programme s'arrête. winButton=Button(launcher,text="Linux",command=launcherCloseUnix,bg="orange",activebackground=orangeClair) winButton.pack(fill=BOTH) warning=Label(launcher,text="Attention !\nLinux ne fonctionne pas pour l'instant.",fg="red") warning.pack() #Lancement du launcher launcher.mainloop() ##Création de la fonction a invoquer en cas de niveau bloqué : une fenêtre avec un message d'erreur. def unlockError(): unlockingError=Tk() unlockingError.title("Pymon - Erreur !") unlockingErrorMessage=Label(unlockingError,text="Veuillez finir le niveau précédent avant !",bg=rougeClair) unlockingErrorMessage.pack(fill=BOTH) ##Fenêtres de Game Over, de Level Complete et de Try Again def gameOver(): gameOverWindow=Tk() gameOverWindow.title("Pymon - Game Over !") gameOverMessage1=Label(gameOverWindow,text="-=-=-=-=-=- GAME OVER -=-=-=-=-=-",bg=rougeClair) gameOverMessage1.pack(fill=BOTH) gameOverMessage2=Label(gameOverWindow,text="Raté ! Vous n'avez pas rentré la bonne suite de notes.",bg=rougeClair) gameOverMessage2.pack(fill=BOTH) gameOverWindow.mainloop() menu() def levelComplete(): levelCompleteWindow=Tk() levelCompleteWindow.title("Pymon - Niveau réussi !") levelCompleteMessage1=Label(levelCompleteWindow,text="-=-=-=-=-=- LEVEL COMPLETE -=-=-=-=-=-",bg=vertClair) levelCompleteMessage1.pack(fill=BOTH) levelCompleteMessage2=Label(levelCompleteWindow,text="Vous avez réussi le niveau ! Félicitations ! Vous pouvez passer au suivant.",bg=vertClair) levelCompleteMessage2.pack(fill=BOTH) levelCompleteWindow.mainloop() menu() def tryAgain(): tryAgainWindow=Tk() tryAgainWindow.title("Pymon - Score insuffisant !") tryAgainMessage1=Label(tryAgainWindow,text="Vous avez réussi le niveau !",bg=jauneClair) tryAgainMessage1.pack(fill=BOTH) tryAgainMessage2=Label(tryAgainWindow,text="La prochaine fois, faites le avec moins de jokers, cependant.",bg=jauneClair) tryAgainMessage2.pack(fill=BOTH) tryAgainWindow.mainloop() menu() ## Fonction 'lock' super simple a la fin du lvl def lock (lvl) : fichier=open("data/unlock.txt","r") unlockingStatus=fichier.readline() unlockingStatus=int(unlockingStatus) fichier.close() if unlockingStatus<=lvl : #s'il n'a jamais fais se niveau il faut le faire paser au niveu sup lvl=lvl+1 fichier=open("data/unlock.txt","w") fichier.write(str(lvl)) fichier.close () ## Fonction des niveaux def lvlFunc(lvl, ref, nb, lvlUp): # Nombre de note à la fin du niveau, 'ref' est la liste de note pour le lvl global RepHistory #Ces deux variables doivent être en global pour leur réutilisation avec valider(). global reponse #Elles sont de toute manière réinitialisées a chaque lancement du niveau. NoteHistory=[] #Liste répertoriant les notes sortie KbHistory=[] #Liste répertoriant les keyboard sortie RepHistory=[] # Liste répertoriant les réponses utilisateur score=0 # Comptabilise le total des points du joueur le long du niveau error=0 # Comptabilise les erreurs fait par l'utilisateur reponse='' #Création de la fenêtre levelWindow=Tk() levelWindow.title("Pymon - Niveau") levelMessage=Label(levelWindow,text="Bienvenue dans un des niveaux de Pymon !\nRépétez correctement la suite de notes jouées\npour réussir le niveau. Bonne chance !",bg=bleuClair) levelMessage.pack(fill=BOTH) answer=Entry(levelWindow) #La zone ou la réponse sera saisie answer.pack() def valider(): #Cette fonction sert pour le bouton "Valider". Elle prend la réponse, la transforme et permet la vérification de la réponse. reponse=answer.get() global RepHistory #Il faut redéfinir RepHistory comme global ici, sinon on ne peut pas l'utiliser. RepHistory=list(reponse) answer.delete(0,END) #Vide le widget Entry levelWindow.quit() #Pour quitter la fenêtre validerButton=Button(levelWindow,text="Valider",command=valider) validerButton.pack() #Création d'un bouton de retour au menu. Il provoque l'arrêt du niveau et donc la fait buguer, mais peu importe, #puisque lorsque la fonction se relancera, tout est réinitialisé et elle fonctionne comme normalement. def retourMenu(): levelWindow.destroy() menu() menuBack=Button(levelWindow,text="Retourner au menu",command=retourMenu) menuBack.pack() for i in range (nb): # suivant la difficulté changer le 3 # #Evite de relancer la boucle après un game over if error==0: #Variables servant aux boucles while plus bas sound=0 check=0 # Tire un nombre au hasard dans les liste de références plus haut et attribut une note à une touche et les 'stock' dans des list c=randrange(0,6) NoteHistory.append(ref [c]) KbHistory.append(listKeyboard[c]) # Joue la liste des fichiers audios contenant les 'anciennes' et la nouvelle note while sound!=i+1 : #Ici, il devait y avoir "if OSWin==1:" pour lancer le son avec Winsound, ne fonctionnant que sous Windows. #Le problème, c'est qu'on nous dit qu'"OSWin n'est pas défini" (alors qu'il l'est) winsound.PlaySound(NoteHistory [sound],winsound.SND_FILENAME) #else: #On comptait utiliser ossaudiodev pour jouer le son sous Linux, mais la documentation étant insuffisante, on n'a pas pu. #Cependant, nous sommes conscients que le programme ne marche par conséquent qu'avec Windows. sound=sound+1 levelWindow.mainloop() # Compare un à un les éléments des liste contenant la réponse de l'utilisateur et les réponses attendu try : while check!=i+1 : if KbHistory[check]==RepHistory[check] : score=score+100 # Attribution du score afin de débloquer les niveau suivants check=check+1 elif 'h'==RepHistory[check]: # Vérifie si la liste ne contient pas d'aide if score<200 : # Pas de score négatif c'est peu encourageant score=0 else : score=score-200 check=check+1 elif KbHistory[check]!=RepHistory[check]: # Compte les erreurs error=error+1 levelWindow.destroy() #si une erreur est détectée, on quitte la fenêtre et la boucle for. break #Cela évite de continuer la vérification. except IndexError : error=error+1 levelWindow.destroy() break if error!=0 : # Et n'affiche qu'une page de 'gameOver' pour toutes les erreurs gameOver() #Fermeture de la fenêtre à la fin de la boucle for si il a réussi (s'il a raté, la fenêtre se ferme dans le while plus haut) #En réalité, c'est limite surperflu, cela évite juste de fermer une deuxième fois la fenêtre en sortant de la boucle si #l'utilisateur a raté le niveau. Ca évite juste un message d'erreur mais n'empêche pas le bon fonctionnement du programme. else: levelWindow.destroy() # Bloc qui permet ou non au joueur d'aller au niveau supérieur grâce à son score if score>lvlUp : lock(lvl) levelComplete() elif score<lvlUp and error==0: # si son score est inférieur au minimum fixé en arguments (lvlUp) et que ce n'est pas du à un game over : tryAgain() ## le tuto def tutoriel(): global RepHistory #Ces deux variables doivent être en global pour leur réutilisation avec valider(). global reponse #Elles sont de toute manière réinitialisées a chaque lancement du niveau. NoteHistory=[] # Initialise la liste qui collecte les notes sorties précédement KbHistory=[] # Initialise la liste qui collecte les lettres attendu pour avoir tous les points RepHistory=[] global reponse reponse="" error=0 # Comptabilise les erreurs fait par l'utilisateur #Création de la fenêtre tutorielWindowP(resentation) tutorielWindowP=Tk() tutorielWindowP.title("Pymon - Tutoriel") tutorielMessage=Label(tutorielWindowP,text="Bonjour, vous voici dans le tutoriel du Pymon,\nun niveau ô combien honorable dans ce jeu de reconnaissance et mémorisation de notes.\nEn effet, c'est dans cette partie que vous apprendrez les bases avant d'être livré à vous même", bg=bleuClair) tutorielMessage.pack(fill=BOTH) tutorielMessage1=Label(tutorielWindowP,text="Pour commencer voyons ensemble les notes.\nLes notes à reconnaitre sont : do, re, mi, fa, sol, la, si et ont respectivement comme lettres associées : q, s, d, f, k, l, m", bg=bleuClair) tutorielMessage1.pack(fill=BOTH) suiteButton=Button(tutorielWindowP,text="Passons à la suite ",command=tutorielWindowP.destroy) suiteButton.pack() tutorielWindowP.mainloop () def valider(): #Cette fonction sert pour le bouton "Valider". Elle prend la réponse, la transforme et permet la vérification de la réponse. reponse=answer.get() answer.delete(0,END) #Vide le widget Entry tutorielWindow.destroy() #Pour quitter la fenêtre for c in range (7): # Boucle qui joue une à une les notes listTuto=['do','re','mi','fa','sol','la','si'] # Liste qui permet d'aider le joueur pour le tutoriel #Création de la fenêtre tutorielWindow tutorielWindow=Tk() tutorielWindow.title("Pymon - Tutoriel") tutorielMessage4=Label(tutorielWindow, text= "La note jouée est un ") tutorielMessage4.pack(fill=BOTH) tutorielMessage5=Label(tutorielWindow, text= listTuto[c]) tutorielMessage5.pack(fill=BOTH) tutorielMessage6=Label(tutorielWindow, text= "Il faut taper la lettre :") tutorielMessage6.pack(fill=BOTH) tutorielMessage7=Label(tutorielWindow, text= listKeyboard[c]) tutorielMessage7.pack(fill=BOTH) answer=Entry(tutorielWindow) #La zone ou la réponse sera saisie answer.pack() validerButton=Button(tutorielWindow,text="Valider",command=valider) validerButton.pack() winsound.PlaySound(listNote_tuto[c],winsound.SND_FILENAME) tutorielWindow.mainloop() # Petit récapitulatif dans les conditions normal d'utilisation du jeu for c in range (7): winsound.PlaySound(listNote_tuto[c],winsound.SND_FILENAME) NoteHistory.append(listNote_tuto[c]) KbHistory.append(listKeyboard[c]) #Création de la fenêtre tutoRecapWindow=Tk() tutoRecapWindow.title("Pymon - Tutoriel") tutoRecapMessage=Label(tutoRecapWindow,text="Un petit récapitulatif, nous avons jouer toutes les notes dans l'ordre\nBonne chance !",bg=bleuClair) tutoRecapMessage.pack(fill=BOTH) recap=Entry(tutoRecapWindow) #La zone ou la réponse sera saisie recap.pack() def valider1 (): #Cette fonction sert pour le bouton "Valider". Elle prend la réponse, la transforme et permet la vérification de la réponse. reponse=recap.get() global RepHistory #Il faut redéfinir RepHistory comme global ici, sinon on ne peut pas l'utiliser. RepHistory=list(reponse) recap.delete(0,END) #Vide le widget Entry tutorielWindow.quit() #Pour quitter la fenêtre validerButton=Button(tutoRecapWindow,text="Valider",command=valider1) validerButton.pack() tutoRecapWindow.mainloop () for j in range (7): if KbHistory[j]==RepHistory[j] : error+=0 #histoire de pas avoir un if vide, et de limiter les possibles erreurs, on laisse la variable error telle quelle else: # Compte les erreurs error=error+1 tutoRecapWindow.destroy() #si une erreur est détectée, on quitte la fenêtre et la boucle for. break #Cela évite de continuer la vérification. if error!=0 : # Et n'affiche qu'une page de 'gameOver' pour toutes les erreurs gameOver() #Fermeture de la fenêtre à la fin de la boucle for si il a réussi (s'il a raté, la fenêtre se ferme dans le while plus haut) #l'utilisateur a raté le niveau. Ca évite juste un message d'erreur mais n'empêche pas le bon fonctionnement du programme. else: tutoRecapWindow.destroy() lock (0) levelComplete() ##Le SURVIVAL DE LA MORT #Fenêtre de game over du survival def survivalGameOver(): survivalGOWindow=Tk() survivalGOWindow.title=("Pymon - Survival : Game Over...") survivalGameOverMessage=Label(survivalGOWindow,text="Dommage... Veuillez rentrer votre nom.\nVotre score est de :") survivalGameOverMessage.pack(fill=BOTH) survivalScorePrint=Label(survivalGOWindow,text=scoreSurvival) survivalScorePrint.pack(fill=BOTH) survivalPseudoEntry=Entry(survivalGOWindow) survivalPseudoEntry.pack() def survivalWrite(): #La fonction qui écrit le score dans un fichier survivalPseudo=survivalPseudoEntry.get() survivalScore=open("data/survivalScore.txt","a") survivalScore.write(survivalPseudo) survivalScore.write(" : ") survivalScore.write(str(scoreSurvival)) #On doit le convertir en string pour l'écrire dans le fichier des meilleurs scores survivalScore.write("\n") survivalScore.close() survivalGOWindow.destroy() menu() survivalScoreValider=Button(survivalGOWindow,text="Valider",command=survivalWrite) #Bouton pour valider le nom et lancer l'enregistrement survivalScoreValider.pack() survivalGOWindow.mainloop() #Le Survival en lui-même def survival(): #Initialisation des variables global RepHistory #Tout comme dans la fonction des niveaux, il faut définir les variables comme global. global reponse NoteHistory=[] #Liste répertoriant les notes sortie KbHistory=[] #Liste répertoriant les keyboard sortie RepHistory=[] # Liste répertoriant les réponses utilisateur global scoreSurvival #En global aussi, pour la fonction survivalGameOver scoreSurvival=0 # Comptabilise le total des points du joueur le long du niveau error=0 # Comptabilise les erreurs fait par l'utilisateur i=0 #Pour remplacer le i de la boucle for du niveau survivalWindow=Tk() survivalWindow.title("Pymon - SURVIVAL !!") survivalMessage=Label(survivalWindow,text="Bienvenue dans le Survival. Les développeurs déclinent toute responsabilité\nen cas de mort, trouble mental, folie, ou toute autre altération\nqui pourrait vous être causée.",bg=rougeClair) survivalMessage.pack(fill=BOTH) survivalMessage2=Label(survivalWindow,text="Ce niveau est sans fin. La liste de notes s'allongera a l'infini, jusqu'a la moindre erreur.\nUne note juste : +100. Une fausse ? -200.\nVotre score sera comptabilisé.\n\nBonne chance.",bg=rougeClair) survivalMessage2.pack(fill=BOTH) answer=Entry(survivalWindow) answer.pack() def valider(): #Cette fonction sert pour le bouton "Valider". Elle prend la réponse, la transforme et permet la vérification de la réponse. reponse=answer.get() global RepHistory #Il faut redéfinir RepHistory comme global ici, sinon on ne peut pas l'utiliser. RepHistory=list(reponse) answer.delete(0,END) #Vide le widget Entry survivalWindow.quit() #Pour quitter la fenêtre validerButton=Button(survivalWindow,text="Valider",command=valider) validerButton.pack() #Création d'un bouton de retour au menu. Il provoque l'arrêt du niveau et donc la fait buguer, mais peu importe, #puisque lorsque la fonction se relancera, tout est réinitialisé et elle fonctionne comme normalement. def retourMenu(): survivalWindow.destroy() menu() menuBack=Button(survivalWindow,text="Retourner au menu",command=retourMenu) menuBack.pack() while error==0: #Variables pour les boucles while plus bas sound=0 check=0 # Tire un nombre au hasard dans les liste de références plus haut et attribut une note à une touche et les 'stock' dans des list c=randrange(0,6) NoteHistory.append(listNote_sur[c]) KbHistory.append(listKeyboard[c]) # Joue la liste des fichiers audios contenant les 'anciennes' et la nouvelle note while sound!=i+1 : #Ici, il devait y avoir "if OSWin==1:" pour lancer le son avec Winsound, ne fonctionnant que sous Windows. #Le problème, c'est qu'on nous dit qu'"OSWin n'est pas défini" (alors qu'il l'est) winsound.PlaySound(NoteHistory [sound],winsound.SND_FILENAME) #else: #On comptait utiliser ossaudiodev pour jouer le son sous Linux, mais la documentation étant insuffisante, on n'a pas pu. #Cependant, nous sommes conscients que le programme ne marche par conséquent qu'avec Windows. sound=sound+1 survivalWindow.mainloop() try: # Compare un à un les éléments des liste contenant la réponse de l'utilisateur et les réponses attendu while check!=i+1 : if KbHistory[check]==RepHistory[check] : scoreSurvival=scoreSurvival+100 # Attribution du score pour l'enregidtrer plus tard check=check+1 elif 'h'==RepHistory[check]: # Vérifie si la liste ne contient pas d'aide scoreSurvival=scoreSurvival-200 check=check+1 elif KbHistory[check]!=RepHistory[check]: # Compte les erreurs error=error+1 survivalWindow.destroy() #si une erreur est détectée, on quitte la fenêtre et la boucle for. break #Cela évite de continuer la vérification. except IndexError : error=error+1 levelWindow.destroy() break if error!=0 : # Et n'affiche qu'une page de 'gameOver' pour toutes les erreurs survivalGameOver() i+=1 ##Définition de la fonction codant pour les meilleurs scores du Survival def survivalScoreFunc(): #Ouverture du fichier survivalScore=open("data/survivalScore.txt","r") listScore=survivalScore.readlines() #"listScore" est une liste qui compte chaque ligne comme un élément de la liste #Création de la fenêtre displayScore=Tk() displayScore.title("Pymon - Scores du Survival") phraseScore=Label(displayScore,text="Ceci sont les scores obtenus par les joueurs sur le Survival :") phraseScore.pack(fill=BOTH) #Création de la listbox pour afficher les scores printScore=Listbox(displayScore) sizeListScore=len(listScore) #Définition de la variable correspondant a la longueur de la liste listScore i=0 #Boucle pour afficher chaque élément de listScore dans la listbox for i in range(sizeListScore): printScore.insert(i,listScore[i]) printScore.pack(fill=BOTH) #Label précisant que la liste est défilable infoDefil=Label(displayScore,text="Il est possible de faire défiler la liste",fg="grey") infoDefil.pack(fill=BOTH) #Bouton de retour au menu menuBack=Button(displayScore,text="Retour au menu",command=displayScore.destroy,bg="grey",activebackground=grisClair) menuBack.pack(fill=BOTH) #Fermeture du fichier survivalScore.close() #Lancement de la fenêtre displayScore.mainloop() ##Création du Menu Principal def menu(): #Vérification du déblocage des niveaux a l'aide d'un fichier unlock=open("data/unlock.txt","r") unlockingStatus=unlock.readline() unlockingStatus=int(unlockingStatus) #Initialisation des variables level1Unlock=False level2Unlock=False level3Unlock=False #Paramétrage des variables if unlockingStatus==0: level1Unlock=False level2Unlock=False level3Unlock=False elif unlockingStatus==1: level1Unlock=True level2Unlock=False level3Unlock=False elif unlockingStatus==2: level1Unlock=True level2Unlock=True level3Unlock=False elif unlockingStatus==3: level1Unlock=True level2Unlock=True level3Unlock=True else: print("C'était marqué dans le readme de pas toucher aux fichiers. Pourquoi vous l'avez fait ?!") #Ces fonctions sont appellées par les boutons pour le déblocage des niveaux. #Au départ, nous avions fait une fonction qui prenait des paramètres, mais ça ne fonctionnait pas #avec le command des boutons de Tkinter. Il a donc fallu faire des fonctions sans paramètres #qui vérifient si telles variables sont True ou False et agit en fonction. def unlockLevel1(): if level1Unlock==True: menuWindow.destroy() lvlFunc(1,listNote_lvl1,5,1100) else: unlockError() def unlockLevel2(): if level2Unlock==True: menuWindow.destroy() lvlFunc(2,listNote_lvl2,10,4700) else: unlockError() def unlockLevel3(): if level3Unlock==True: menuWindow.destroy() lvlFunc(3,listNote_lvl3,15,10200) else: unlockError() #Création de la fenêtre menuWindow=Tk() menuWindow.title("Pymon") menuWindow.geometry("350x300") #Création d'une mini-fonction pour la fermeture du menu et lancement du tutoriel/survival afin de fonctionner avec les boutons. def tutoStart(): menuWindow.destroy() tutoriel() def survivalStart(): menuWindow.destroy() survival() #Création de chaque bouton et Labels décoratifs title=Label(menuWindow,text="Bienvenue dans Pymon !",anchor=CENTER,justify=CENTER) title.pack(fill=BOTH) tuto=Button(menuWindow,text="Tutoriel",bg="green",activebackground=vertClair,command=tutoStart) tuto.pack(fill=BOTH) lvs=Label(menuWindow,text="-=-=-=-=- Niveaux -=-=-=-=-",anchor=CENTER,justify=CENTER) lvs.pack(fill=BOTH) lv1=Button(menuWindow,text="Niveau 1",bg="yellow",activebackground=jauneClair,command=unlockLevel1) lv1.pack(fill=BOTH) lv2=Button(menuWindow,text="Niveau 2",bg="orange",activebackground=orangeClair,command=unlockLevel2) lv2.pack(fill=BOTH) lv3=Button(menuWindow,text="Niveau 3",bg="red",activebackground=rougeClair,command=unlockLevel3) lv3.pack(fill=BOTH) danger=Label(menuWindow,text="!!!! DANGER !!!!",anchor=CENTER,justify=CENTER,fg="red") danger.pack(fill=BOTH) survivalButton=Button(menuWindow,text="Survival !",bg="black",fg="white",activebackground=grisFonce,command=survivalStart) survivalButton.pack(fill=BOTH) separation=Label(menuWindow,text="-=-=-=-=-=-=-=-=-=-=-=-=-",anchor=CENTER,justify=CENTER) separation.pack(fill=BOTH) survivalScore=Button(menuWindow,text="Scores du Survival",command=survivalScoreFunc,bg="grey",activebackground=grisClair) survivalScore.pack(fill=BOTH) commands=Label(menuWindow,text="Commandes : qsdfklm - h pour un joker",fg='grey') commands.pack(fill=BOTH) warning=Label(menuWindow,text="ATTENTION ! Ce programme est calibré avec des minuscules.\nPar conséquent, veuillez ne pas utiliser de majuscules.",fg='grey') warning.pack(fill=BOTH) vide=Label(menuWindow,text="",anchor=CENTER,justify=CENTER) vide.pack(fill=BOTH) #Lancement de la fenêtre menuWindow.mainloop() ## Lancement du programme ## launch() <file_sep>/sounds/lv3/TODO.md comme tout le reste
ed371c0dd0dc503a823aa9c37ab4f2aeb7e2a6b1
[ "Markdown", "Python" ]
6
Markdown
neistuff/Pymon
05ab7d5555fc5e7c061956edee5ea3c34b01fd05
42626faf96b703d1cd9d557a22feb62781f2fae8
refs/heads/master
<file_sep>from django.db import models class UploadedFiles(models.Model): uploaded_file = models.FileField(upload_to='files/%Y/%m/%d') <file_sep>from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from .forms import UploadFileForm from .models import UploadedFiles def index(request): return HttpResponse("Hello, world. You're at the polls index.") def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): new_file = UploadedFiles(uploaded_file=request.FILES['uploading_file']) new_file.save() file_name = request.FILES['uploading_file'].name return HttpResponse("{file_name}.".format(file_name=file_name)) else: form = UploadFileForm() return render(request, 'upload/upload.html', {'form': form}) <file_sep>import os.path from django.conf import settings def handle_uploaded_file(f): abs_file_path = os.path.join(settings.MEDIA_ROOT, f.name) with open(abs_file_path, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) <file_sep># Django1.11 を使用して、簡素なupload 機能を実現したい。 ## branch の説明 1. without_model - model が必要ない。Form オブジェクトに渡されたFile オブジェクトをハンドラに渡して、保存するだけ。 2. master - model が必要。
1cff6d874e395239ed930cf8ebfcd2e3adcfbd7e
[ "Markdown", "Python" ]
4
Python
sinzee/upload_file
0d3c5747bfa0667f7a0f47ac2bd37a0d1a0586e2
598aa4cbacc1aeb35d791646d7644d9d6eb0620d
refs/heads/master
<repo_name>tazeek/Titanic-Analysis<file_sep>/train.py from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.tree import DecisionTreeClassifier import pandas as pd import numpy as np def getFamily(family): return 1 if family <= 3 else 0 def getPerson(passenger): age,sex = passenger return 'child' if age < 16 else sex def organizeData(df): # Drop the 'embarked' column as there is no relationship to help it df.drop(['Embarked'], axis=1,inplace=True) # Convert from float to integers df['Fare'] = df['Fare'].astype(int) # Get average age, standard deviation and NaN values of dataframe average_age_titanic = df["Age"].mean() std_age_titanic = df["Age"].std() count_nan_age_titanic = df["Age"].isnull().sum() # Generate random numbers to fill in the missing values missing_val = np.random.randint(average_age_titanic - std_age_titanic, average_age_titanic + std_age_titanic, size = count_nan_age_titanic) # Fill in missing values with missing_val df["Age"][np.isnan(df["Age"])] = missing_val # Convert Age from float to int df['Age'] = df['Age'].astype(int) # Use Pclass dummies, rename columns, then rejoin pclass_dummies = pd.get_dummies(df['Pclass']) pclass_dummies.columns = ["Class_1", "Class_2", "Class_3"] # Drop Class_3 since it has a very low survival chance pclass_dummies.drop(['Class_3'], axis=1, inplace=True) df = df.join(pclass_dummies) # Drop 'Pclass' column to avoid redundancy df.drop(['Pclass'],axis=1,inplace=True) # Combine 'Parch' and 'SibSp' into one column called 'Family' df['Family'] = df['Parch'] + df['SibSp'] # If family of 3 or less, mark as 1. Otherwise, 0 df['Small_Family'] = df[['Family']].apply(getFamily, axis=1) # If family present, mark as 1. Otherwise, 0 df['Family'].loc[df['Family'] > 0] = 1 df['Family'].loc[df['Family'] == 0] = 0 # Drop 'Parch' and 'SibSp' to avoid redundancy df = df.drop(['SibSp','Parch'], axis=1) # Store in 'Person' column df['Person'] = df[['Age','Sex']].apply(getPerson,axis=1) # Use dummies, rename columns, then rejoin gender_dummies = pd.get_dummies(df['Person']) gender_dummies.columns = ['Child','Female','Male'] # Drop 'Male' since it has a very low survival chance gender_dummies.drop(['Male'], axis=1, inplace=True) df = df.join(gender_dummies) # Drop 'Pclass' column to avoid redundancy df.drop(['Sex'],axis=1,inplace=True) # Drop unnecessary fields df.drop(['Name','Ticket','Cabin','Person'], axis=1, inplace=True) # Return the processed dataframe return df # Load the training and test data train = pd.read_csv('train.csv', dtype={"Age": np.float64}) test = pd.read_csv('test.csv', dtype={"Age": np.float64}) # Missing "Fare" value in titanic_test. Fill it with the median test["Fare"].fillna(test["Fare"].median(), inplace=True) # Preproces the training and testing train = organizeData(train) test = organizeData(test) train.drop("PassengerId", axis=1, inplace=True) # MACHINE LEARNING BEGINS HERE X_train = train.drop("Survived",axis=1) Y_train = train["Survived"] X_test = test.drop("PassengerId",axis=1).copy() tree = DecisionTreeClassifier(criterion='entropy',max_depth=5,min_samples_split=10,random_state=0) tree.fit(X_train, Y_train) Y_pred = tree.predict(X_test) print(tree.score(X_train, Y_train) * 100 ) # MACHINE LEARNING ENDS HERE submission = pd.DataFrame({ "PassengerId": test["PassengerId"], "Survived": Y_pred }) submission.to_csv('titanic.csv', index=False)
102dba29fc6e4174be66d4f1ad8765baa3616edf
[ "Python" ]
1
Python
tazeek/Titanic-Analysis
a3ecf99ca9fa1c637c3aaa486c0047c5be4b5d45
17d63c12fa7d47f95258b6da4a77f6b118b4b268
refs/heads/master
<file_sep>import React from 'react'; import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom' import './App.css'; import { Navbar } from './app/Navbar' import { ClassList } from './features/class/ClassList' import { RaceList } from './features/race/RaceList' import { TraitList } from './features/trait/TraitList' import { SingleRacePage } from './features/race/SingleRacePage' import { SingleClassPage } from './features/class/SingleClassPage' import { SingleTraitPage } from './features/trait/SingleTraitPage' function App() { return ( <Router> <Navbar /> <div className="App"> <Switch> <Route exact path="/" render={() => ( <React.Fragment> <div class="flexbox-container"> <ClassList /> <RaceList /> <TraitList /> </div> </React.Fragment> )} /> <Route exact path="/races/:raceUrl" component={SingleRacePage} /> <Route exact path="/classes/:classUrl" component={SingleClassPage} /> <Route exact path="/traits/:traitUrl" component={SingleTraitPage} /> <Redirect to="/" /> </Switch> </div> </Router> ); } export default App; <file_sep>import React, { useEffect } from 'react' import { useSelector, useDispatch } from 'react-redux' import { fetchSingleRace } from './raceSlice' export const SingleRacePage = ({ match }) => { const dispatch = useDispatch(); const { raceUrl } = match.params; const raceStatus = useSelector(state => state.race.singlestatus); useEffect(() => { if (raceStatus === 'idle') { dispatch(fetchSingleRace(raceUrl)) } }, [raceStatus, raceUrl, dispatch]) const race = useSelector(state => state.race.selected) return ( <section> <article className="race"> <h2>{race["name"]}</h2> <p className="race-content">{race["alignment"]}</p> </article> </section> ) }<file_sep># DND React App <file_sep>import React, { useEffect } from 'react' import { useDispatch, useSelector } from 'react-redux' import { Link } from 'react-router-dom' import { resetSingleClassStatus } from './classSlice' export const ClassList = () => { const dispatch = useDispatch(); const classes = useSelector(state => state.classes.list) const classStatus = useSelector(state => state.classes.singlestatus) useEffect(() => { if (classStatus !== 'idle') { dispatch(resetSingleClassStatus()) } }, [classStatus, dispatch]) const renderedClasses = classes.map(classVal => ( <article className="class-excerpt" key={classVal.index}> <Link to={classVal.url}> <h3>{classVal.name}</h3> </Link> </article> )) return ( <section className="classes-list"> <h2>Classes</h2> {renderedClasses} </section> ) }<file_sep>import React, { useEffect } from 'react' import { useSelector, useDispatch } from 'react-redux' import { fetchSingleClass } from './classSlice' export const SingleClassPage = ({ match }) => { const dispatch = useDispatch(); const { classUrl } = match.params; const classStatus = useSelector(state => state.classes.singlestatus) useEffect(() => { if (classStatus === 'idle') { dispatch(fetchSingleClass(classUrl)) } }, [classStatus, classUrl, dispatch]) const classObj = useSelector(state => state.classes.selected) return ( <section> <article className="class"> <h2>{classObj["name"]}</h2> <p className="class-content">{classObj["hit_die"]}</p> </article> </section> ) }
5a9861cd1bbe4293f9d6318c7adfac0984130682
[ "JavaScript", "Markdown" ]
5
JavaScript
jcadavez/dnd-react-app
ca3682f5c8a420041e1e4afb736c84a2e84a01b2
d5aaaaf2868db7e1658ce73afd05c304e83bff1a
refs/heads/master
<file_sep>using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.Taxonomy; using System; using System.Text.RegularExpressions; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions { internal class SiteCollectionTermSetIdToken : TokenDefinition { private string _value; public SiteCollectionTermSetIdToken(Web web, string termsetName, Guid id) : base(web, $"{{sitecollectiontermsetid:{Regex.Escape(termsetName)}}}") { _value = id.ToString(); } public override string GetReplaceValue() { if (string.IsNullOrEmpty(CacheValue)) { CacheValue = _value; } return CacheValue; } } }<file_sep>using Microsoft.SharePoint.Client; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions { internal class SiteToken : TokenDefinition { public SiteToken(Web web) : base(web, "~site", "{site}") { } public override string GetReplaceValue() { if (CacheValue == null) { this.Web.EnsureProperty(w => w.Url); using (ClientContext context = this.Web.Context.Clone(this.Web.Url)) { context.Load(context.Web, w => w.ServerRelativeUrl); context.ExecuteQueryRetry(); CacheValue = context.Web.ServerRelativeUrl.TrimEnd('/'); } } return CacheValue; } } }<file_sep>using Microsoft.SharePoint.Client; using System; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions { internal class RoleDefinitionToken : TokenDefinition { private string name; public RoleDefinitionToken(Web web, RoleDefinition definition) : base(web, $"{{roledefinition:{definition.RoleTypeKind}}}") { name = definition.EnsureProperty(r => r.Name); } public override string GetReplaceValue() { if (string.IsNullOrEmpty(CacheValue)) { CacheValue = name; } return CacheValue; } } }<file_sep>using Microsoft.SharePoint.Client; using System; using System.Text.RegularExpressions; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions { internal class ListViewIdToken : TokenDefinition { private string _viewId = null; public ListViewIdToken(Web web, string listTitle, string viewTitle, Guid viewId) : base(web, $"{{viewid:{Regex.Escape(listTitle)},{Regex.Escape(viewTitle)}}}") { _viewId = viewId.ToString(); } public override string GetReplaceValue() { if (string.IsNullOrEmpty(CacheValue)) { CacheValue = _viewId; } return CacheValue; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using OfficeDevPnP.Core.Framework.Provisioning.Model; using OfficeDevPnP.Core.Utilities; using System.Xml.Serialization; using OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.Serializers; using System.Collections; using System.Reflection; namespace OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml { internal abstract class XmlPnPSchemaBaseSerializer<TSchemaTemplate> : IXMLSchemaFormatter, ITemplateFormatter where TSchemaTemplate: new() { private TemplateProviderBase _provider; private Stream _referenceSchema; protected TemplateProviderBase Provider => _provider; public XmlPnPSchemaBaseSerializer(Stream referenceSchema) { if (referenceSchema == null) { throw new ArgumentNullException("referenceSchema"); } this._referenceSchema = referenceSchema; } public abstract string NamespacePrefix { get; } public abstract string NamespaceUri { get; } public void Initialize(TemplateProviderBase provider) { this._provider = provider; } public bool IsValid(Stream template) { if (template == null) { throw new ArgumentNullException(nameof(template)); } // Load the template into an XDocument XDocument xml = XDocument.Load(template); // Prepare the XML Schema Set XmlSchemaSet schemas = new XmlSchemaSet(); this._referenceSchema.Seek(0, SeekOrigin.Begin); schemas.Add(((IXMLSchemaFormatter)this).NamespaceUri, new XmlTextReader(this._referenceSchema)); Boolean result = true; xml.Validate(schemas, (o, e) => { Diagnostics.Log.Error(e.Exception, "SchemaFormatter", "Template is not valid: {0}", e.Message); result = false; }); return (result); } protected Object ProcessInputStream(Stream template, string identifier, ProvisioningTemplate result) { if (template == null) { throw new ArgumentNullException(nameof(template)); } // Crate a copy of the source stream MemoryStream sourceStream = new MemoryStream(); template.CopyTo(sourceStream); sourceStream.Position = 0; // Check the provided template against the XML schema if (!this.IsValid(sourceStream)) { // TODO: Use resource file throw new ApplicationException("The provided template is not valid!"); } sourceStream.Position = 0; XDocument xml = XDocument.Load(sourceStream); XNamespace pnp = this.NamespaceUri; // Prepare a variable to hold the single source formatted template TSchemaTemplate source = default(TSchemaTemplate); // Determine if we're working on a wrapped ProvisioningTemplate or not if (xml.Root.Name == pnp + "Provisioning") { // Deserialize the whole wrapper Object wrapper = null; var wrapperType = Type.GetType($"{PnPSerializationScope.Current?.BaseSchemaNamespace}.Provisioning, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}", true); XmlSerializer xmlSerializer = new XmlSerializer(wrapperType); using (var reader = xml.Root.CreateReader()) { wrapper = xmlSerializer.Deserialize(reader); } // Handle the Parameters of the schema wrapper, if any var tps = new TemplateParametersSerializer(); tps.Deserialize(wrapper, result); // Handle the Localizations of the schema wrapper, if any var ls = new LocalizationsSerializer(); ls.Deserialize(wrapper, result); // Get the list of templates, if any, wrapped by the wrapper var wrapperTemplates = wrapperType.GetProperty("Templates", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase).GetValue(wrapper); if (wrapperTemplates != null) { // Search for the requested Provisioning Template foreach (var templates in (IEnumerable)wrapperTemplates) { // Let's see if we have an in-place template with the provided ID or if we don't have a provided ID at all var provisioningTemplates = templates.GetType() .GetProperty("ProvisioningTemplate", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase).GetValue(templates); if (provisioningTemplates != null) { foreach (var t in (IEnumerable)provisioningTemplates) { var templateId = (String)t.GetType().GetProperty("ID", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase).GetValue(t); if ((templateId != null && templateId == identifier) || String.IsNullOrEmpty(identifier)) { source = (TSchemaTemplate)t; } } if (source == null) { var provisioningTemplateFiles = templates.GetType() .GetProperty("ProvisioningTemplateFile", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase).GetValue(templates); // If we don't have a template, but there are external file references if (source == null && provisioningTemplateFiles != null) { foreach (var f in (IEnumerable)provisioningTemplateFiles) { var templateId = (String)f.GetType().GetProperty("ID", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase).GetValue(f); if ((templateId != null && templateId == identifier) || String.IsNullOrEmpty(identifier)) { // Let's see if we have an external file for the template var externalFile = (String)f.GetType().GetProperty("File", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase).GetValue(f); Stream externalFileStream = this.Provider.Connector.GetFileStream(externalFile); xml = XDocument.Load(externalFileStream); if (xml.Root.Name != pnp + "ProvisioningTemplate") { throw new ApplicationException("Invalid external file format. Expected a ProvisioningTemplate file!"); } else { source = XMLSerializer.Deserialize<TSchemaTemplate>(xml); } } } } } } if (source != null) { break; } } } } else if (xml.Root.Name == pnp + "ProvisioningTemplate") { var IdAttribute = xml.Root.Attribute("ID"); // If there is a provided ID, and if it doesn't equal the current ID if (!String.IsNullOrEmpty(identifier) && IdAttribute != null && IdAttribute.Value != identifier) { // TODO: Use resource file throw new ApplicationException("The provided template identifier is not available!"); } else { source = XMLSerializer.Deserialize<TSchemaTemplate>(xml); } } return (source); } public ProvisioningTemplate ToProvisioningTemplate(Stream template) { return (this.ToProvisioningTemplate(template, null)); } public ProvisioningTemplate ToProvisioningTemplate(Stream template, string identifier) { using (var scope = new PnPSerializationScope(typeof(TSchemaTemplate))) { // Prepare a variable to hold the resulting ProvisioningTemplate instance var result = new ProvisioningTemplate(); // Prepare a variable to hold the single source formatted template var source = ProcessInputStream(template, identifier, result); DeserializeTemplate(source, result); return (result); } } protected virtual void DeserializeTemplate(Object persistenceTemplate, ProvisioningTemplate template) { // Get all serializers to run in automated mode, ordered by DeserializationSequence var currentAssembly = this.GetType().Assembly; XMLPnPSchemaVersion currentSchemaVersion = GetCurrentSchemaVersion(); var serializers = currentAssembly.GetTypes() .Where(t => t.GetInterface(typeof(IPnPSchemaSerializer).FullName) != null && t.BaseType.Name == typeof(Xml.PnPBaseSchemaSerializer<>).Name) .Where(t => { var a = t.GetCustomAttributes<TemplateSchemaSerializerAttribute>(false).FirstOrDefault(); return (a.MinimalSupportedSchemaVersion <= currentSchemaVersion && a.DeserializationSequence >= 0); }) .OrderByDescending(s => { var a = s.GetCustomAttributes<TemplateSchemaSerializerAttribute>(false).FirstOrDefault(); return (a.MinimalSupportedSchemaVersion); } ) .GroupBy(t => t.BaseType.GenericTypeArguments.FirstOrDefault()?.FullName) .OrderBy(g => { var maxInGroup = g.OrderByDescending(s => { var a = s.GetCustomAttributes<TemplateSchemaSerializerAttribute>(false).FirstOrDefault(); return (a.MinimalSupportedSchemaVersion); } ).FirstOrDefault(); return (maxInGroup.GetCustomAttributes<TemplateSchemaSerializerAttribute>(false).FirstOrDefault()?.SerializationSequence); }); foreach (var group in serializers) { var serializerType = group.FirstOrDefault(); if (serializerType != null) { var serializer = Activator.CreateInstance(serializerType) as IPnPSchemaSerializer; if (serializer != null) { serializer.Deserialize(persistenceTemplate, template); } } } } public Stream ToFormattedTemplate(ProvisioningTemplate template) { if (template == null) { throw new ArgumentNullException(nameof(template)); } using (var scope = new PnPSerializationScope(typeof(TSchemaTemplate))) { var result = new TSchemaTemplate(); // Create the wrapper var wrapperType = Type.GetType($"{PnPSerializationScope.Current?.BaseSchemaNamespace}.Provisioning, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}", true); Object wrapper = Activator.CreateInstance(wrapperType); // Create the Preferences var preferencesType = Type.GetType($"{PnPSerializationScope.Current?.BaseSchemaNamespace}.Preferences, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}", true); Object preferences = Activator.CreateInstance(preferencesType); wrapper.GetType().GetProperty("Preferences", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase).SetValue(wrapper, preferences); // Handle the Parameters of the schema wrapper, if any var tps = new TemplateParametersSerializer(); tps.Serialize(template, wrapper); // Handle the Localizations of the schema wrapper, if any var ls = new LocalizationsSerializer(); ls.Serialize(template, wrapper); // Configure the Generator preferences.GetType().GetProperty("Generator", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase).SetValue(preferences, this.GetType().Assembly.FullName); // Configure the output Template var templatesType = Type.GetType($"{PnPSerializationScope.Current?.BaseSchemaNamespace}.Templates, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}", true); var templates = Array.CreateInstance(templatesType, 1); var templatesItem = Activator.CreateInstance(templatesType); templatesItem.GetType().GetProperty("ID", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase).SetValue(templatesItem, $"CONTAINER-{template.Id}"); var provisioningTemplates = Array.CreateInstance(typeof(TSchemaTemplate), 1); provisioningTemplates.SetValue(result, 0); templatesItem.GetType().GetProperty("ProvisioningTemplate", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase).SetValue(templatesItem, provisioningTemplates); templates.SetValue(templatesItem, 0); wrapperType.GetProperty("Templates", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase).SetValue(wrapper, templates); SerializeTemplate(template, result); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add(((IXMLSchemaFormatter)this).NamespacePrefix, ((IXMLSchemaFormatter)this).NamespaceUri); MemoryStream output = new MemoryStream(); XmlSerializer xmlSerializer = new XmlSerializer(wrapperType); if (ns != null) { xmlSerializer.Serialize(output, wrapper, ns); } else { xmlSerializer.Serialize(output, wrapper); } output.Position = 0; return (output); } } protected virtual void SerializeTemplate(ProvisioningTemplate template, Object persistenceTemplate) { // Get all serializers to run in automated mode, ordered by DeserializationSequence var currentAssembly = this.GetType().Assembly; XMLPnPSchemaVersion currentSchemaVersion = GetCurrentSchemaVersion(); var serializers = currentAssembly.GetTypes() .Where(t => t.GetInterface(typeof(IPnPSchemaSerializer).FullName) != null && t.BaseType.Name == typeof(Xml.PnPBaseSchemaSerializer<>).Name) .Where(t => { var a = t.GetCustomAttributes<TemplateSchemaSerializerAttribute>(false).FirstOrDefault(); return (a.MinimalSupportedSchemaVersion <= currentSchemaVersion && a.SerializationSequence >= 0); }) .OrderByDescending(s => { var a = s.GetCustomAttributes<TemplateSchemaSerializerAttribute>(false).FirstOrDefault(); return (a.MinimalSupportedSchemaVersion); } ) .GroupBy(t => t.BaseType.GenericTypeArguments.FirstOrDefault()?.FullName) .OrderBy(g => { var maxInGroup = g.OrderByDescending(s => { var a = s.GetCustomAttributes<TemplateSchemaSerializerAttribute>(false).FirstOrDefault(); return (a.MinimalSupportedSchemaVersion); } ).FirstOrDefault(); return (maxInGroup.GetCustomAttributes<TemplateSchemaSerializerAttribute>(false).FirstOrDefault()?.DeserializationSequence); }); foreach (var group in serializers) { var serializerType = group.FirstOrDefault(); if (serializerType != null) { var serializer = Activator.CreateInstance(serializerType) as IPnPSchemaSerializer; if (serializer != null) { serializer.Serialize(template, persistenceTemplate); } } } } private static XMLPnPSchemaVersion GetCurrentSchemaVersion() { var currentSchemaTemplateNamespace = typeof(TSchemaTemplate).Namespace; var currentSchemaVersionString = $"V{currentSchemaTemplateNamespace.Substring(currentSchemaTemplateNamespace.IndexOf(".Xml.") + 6)}"; var currentSchemaVersion = (XMLPnPSchemaVersion)Enum.Parse(typeof(XMLPnPSchemaVersion), currentSchemaVersionString); return currentSchemaVersion; } } } <file_sep>using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.Taxonomy; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions { internal class KeywordsTermStoreIdToken : TokenDefinition { public KeywordsTermStoreIdToken(Web web) : base(web, "~keywordstermstoreid", "{keywordstermstoreid}") { } public override string GetReplaceValue() { if (CacheValue == null) { this.Web.EnsureProperty(w => w.Url); using (ClientContext context = this.Web.Context.Clone(this.Web.Url)) { TaxonomySession session = TaxonomySession.GetTaxonomySession(context); var termStore = session.GetDefaultKeywordsTermStore(); context.Load(termStore, t => t.Id); context.ExecuteQueryRetry(); CacheValue = termStore.Id.ToString(); } } return CacheValue; } } }<file_sep># 16.1 folder - SharePoint Online # [![SharePointPnPCoreOnline](https://img.shields.io/nuget/v/SharePointPnPCoreOnline.svg)](https://www.nuget.org/packages/SharePointPnPCoreOnline/) It is normally updated with the latest release of [SharePoint Online CSOM components](http://www.nuget.org/packages/Microsoft.SharePointOnline.CSOM) Current version is based on CSOM version **16.1.6112.1200** # 16.0 folder - SharePoint 2016 (On-Premises) # [![SharePointPnPCore2016](https://img.shields.io/nuget/v/SharePointPnPCore2016.svg)](https://www.nuget.org/packages/SharePointPnPCore2016/) Current version is based on **SharePoint Server 2016 RTM** version # 15 folder - SharePoint 2013 (On-Premises) # [![SharePointPnPCore2013](https://img.shields.io/nuget/v/SharePointPnPCore2013.svg)](https://www.nuget.org/packages/SharePointPnPCore2013/) Current version is based on version **15.0.4801.1000** (March 2016 CU) Version History - Version up until April 15th 2015: version deployed with the March 2015 CU (version **15.0.4701.1000**) - Version up until March 12th 2015: version deployed with the February 2015 CU (version **15.0.4693.1000**) - Version up until February 12th 2015: version deployed with the December 2014 CU (version **15.0.4675.1000**) - Version up until December 14th 2014: version as SharePoint Server 2013 Client Components SDK (version **15.0.4641.1000**) - Version up until September 3th 2014: version deployed with the April 2014 CU (version **15.0.4605.1000**) - Up until version 2.0 of Office AMS (=old CodePlex release): SharePoint Server 2013 Client Components SDK (version **15.0.4420.1017**) <img src="https://telemetry.sharepointpnp.com/pnp-sites-core/assemblies" /> <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Microsoft.IdentityModel.Clients.ActiveDirectory; namespace OfficeDevPnP.Core.Utilities { /// <summary> /// Class deals with Token Caching of file /// </summary> public class FileTokenCache : TokenCache { public string CacheFilePath; private static readonly object FileLock = new object(); /// <summary> /// Constructor for FileTokenCache class /// </summary> /// <param name="filePath">Path of the file</param> public FileTokenCache(string filePath = @".\TokenCache.dat") { CacheFilePath = filePath; this.AfterAccess = AfterAccessNotification; this.BeforeAccess = BeforeAccessNotification; lock (FileLock) { this.Deserialize(File.Exists(CacheFilePath) ? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath), null, DataProtectionScope.CurrentUser) : null); } } /// <summary> /// Clears the Cached file path /// </summary> public override void Clear() { base.Clear(); File.Delete(CacheFilePath); } void BeforeAccessNotification(TokenCacheNotificationArgs args) { lock (FileLock) { this.Deserialize(File.Exists(CacheFilePath) ? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath), null, DataProtectionScope.CurrentUser) : null); } } void AfterAccessNotification(TokenCacheNotificationArgs args) { if (this.HasStateChanged) { lock (FileLock) { File.WriteAllBytes(CacheFilePath, ProtectedData.Protect(this.Serialize(), null, DataProtectionScope.CurrentUser)); this.HasStateChanged = false; } } } } } <file_sep>using Microsoft.SharePoint.Client; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions { internal class SiteOwnerToken : TokenDefinition { public SiteOwnerToken(Web web) : base(web, "~siteowner", "{siteowner}") { } public override string GetReplaceValue() { if (CacheValue == null) { this.Web.EnsureProperty(w => w.Url); using (ClientContext context = this.Web.Context.Clone(this.Web.Url)) { var site = context.Site; context.Load(site, s => s.Owner); context.ExecuteQueryRetry(); CacheValue = site.Owner.LoginName; } } return CacheValue; } } }<file_sep>Office 365 Developer PnP Core Component Provisioning Engine Tokens ================================================================== ### Summary ### The Office 365 Developer PnP Core Provisioning Engine supports certain tokens which will be replaced by corresponding values during provisioning. These tokens can be used to make the template site collection independent for instance. Below all the supported tokens are listed: |Token|Example|Output example|Description |-----|-------|-----------|----- |{contenttypeid:&lt;name&gt;}|{contenttypeid:Reservations}|0x0102004F51EFDEA49C49668EF9C6744C8CF87D|Will return the id of the content type by name.| |{currentuserfullname}|{currentuserfullname}|Test User|Will return the full name of the user. Notice, does not work when using app only authentication.| |{currentuserid}|{currentuserid}|12|Will return the current user id, as present in the Site User Info List| |{currentuserloginname}|{currentuserloginname}|i:0#.f\|membership\|<EMAIL>|Returns the current login name of the user. Notice that this does not work when using app only authentication| |{datenow}|{datenow}|2017-01-13T22:53:15.908Z|Returns the current date and time converted to UTC and formatted as "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK"| |{fieldtitle:&lt;internalname&gt;}|{fieldtitle:Title}|Title|Returns the title (displayname) of a field by its internal name| |{groupid:&lt;name&gt;}|{groupid:Site Members}|5|Returns the id of the group by name| |{guid}|{guid}|678149a4-208e-491e-9e93-a2b0d754f5e4|Returns a new guid without { }. Write {{guid}} to return a guid in the shape of {678149a4-208e-491e-9e93-a2b0d754f5e4}| |{keywordstermstoreid}|{keywordstermstoreid}|FDF19D89-A82F-4AB9-9BB5-B49E6CA5212E|Will return the ID/Guid of the keyword term store, without { }. If you want a ID with { } around the value, use the token as follows: {{keywordstermstoreid}}| |{listid:&lt;name&gt;}|{listid:Demo List}|FDF19D89-A82F-4AB9-9BB5-B49E6CA5212E|Will return the ID of the list specified by the parameter, which is the title of the list. If you want a ID with { } around the value, use the token as follows: {{listid:Demo List}}| |{listurl:&lt;name&gt;}|{listurl:Demo List}|lists/demolist|Will return the url of the list specified by the parameter, which is the title of the list.| |{viewid:&lt;ListName&gt;,&lt;ViewName&gt;}|{viewid:MyList,MyView}|ddc063cb-0c0e-4ce1-821c-a1f629992e42|Returns the id of a given view in a list without { }. Write {{viewid:MyList,MyView}} to return an id in the shape of {ddc063cb-0c0e-4ce1-821c-a1f629992e42}| |{loc:&lt;token&gt;}<br/>{localize:&lt;token&gt;}<br/>{localization:&lt;token&gt;}<br/>{resource:&lt;token&gt;}<br/>{res:&lt;token&gt;}|{resource:MyListName}|Mijn lijst|Returns a token from an embedded resource file in a template for the current language of the web you are provisioning to.| |{masterpagecatalog}|{masterpagecatalog}|/sites/demo/_catalogs/masterpage|Will return the server relative url of the masterpage catalog for the current site.| |{parameter:&lt;name&gt;}|{parameter:DefaultGroup}|string value|Will return the value of the parameter as specified in the template.| |{roledefinition:&lt;name&gt;}|{roledefinition:Administrator}|Object of type RoleDefinition|Returns a roledefinition, to be used in Security elements of the template. Eg. Administrator, Contributor, Reader| |{sitecollectionid}|{sitecollectionid}|73170a53-c1ce-4cd0-9569-e464069f1a69|Returns the id of the current site collection. Write {{sitecollectionid}} to return the id in the shape of {73170a53-c1ce-4cd0-9569-e464069f1a69}| |{sitecollectiontermgroupid}|{sitecollectiontermgroupid}|2235e428-83a9-4486-9583-64dd454f9918|Returns the id of the current site collection term group. This group is not present by default in SharePoint 2013 and 2016, but if the token is encountered in the template and the group does not exist, it will be created.| |{sitecollectiontermgroupname}|{sitecollectiontermgroupname}|Site Collection - mytenant.sharepoint.com-sites-demo|Returns the name of the site collection term group. You can use this value also in as a nested token, alike {termsetid:{sitecollectiontermgroupname}:mytermset}| |{sitecollectiontermsetid:&lt;name&gt;}|{sitecollectiontermsetid:Departments}|52a3abcd-4dec-4b9a-b5ba-f9220f8d47bd|Returns the id of a specific termset in the site collection term group.| |{sitecollectiontermstoreid}|{sitecollectiontermstoreid}|FDF19D89-A82F-4AB9-9BB5-B49E6CA5212E|Will return the ID/Guid of the site collection term store without enclosing { }. If you want a ID with { } around the value, use the token as follows: {{sitecollectiontermstoreid}}.| |{sitecollection}|{sitecollection}|/sites/demo|Will return the server relative URL of the current site collection rootweb| |{siteid}|{siteid}|cb779dae-0b29-4cec-b3ac-9983d3389ad0|Returns the id of the current web.| |{sitename}|{sitename}|My Demo Site|Returns the title of the current web.| |{siteowner}|{siteowner}|i:0#.f\|membership\|<EMAIL>|Returns the login name of the current owner of the site.| |{site}|{site}|/sites/demo/test|Will returm the server relative URL of the current web.| |{termsetid:&lt;Group&gt;:&lt;Set&gt;}|{termsetid:TestGroup:TestSet}|FDF19D89-A82F-4AB9-9BB5-B49E6CA5212|Will return the ID of the termset that is residing under the specified group. If you want a ID with { } around the value, use the token as follows: {{termsetid:TestGroup:TestSet}}.| |{termstoreid:&lt;name&gt;}|{termstoreid:ExtraStore}|d42bcad2-0603-4b86-8e3d-72177f4519ca|Returns the id of a termstore by its name.| |{themecatalog}|{themecatalog}|/sites/demo/_catalogs/theme|Will return the server relative url of the current site theme catalog.| |{webpartid:&lt;name&gt;}|{webpartid:MyWebPart}|767245f6-5f47-4cb5-b558-bcc04956bb7b|Returns the id of a webpart by its name.| <img src="https://telemetry.sharepointpnp.com/pnp-sites-core/core/provisioningenginetokens" /> <file_sep>using Microsoft.SharePoint.Client; using Newtonsoft.Json.Linq; using OfficeDevPnP.Core.Diagnostics; using OfficeDevPnP.Core.Framework.Provisioning.Model; using OfficeDevPnP.Core.Utilities; using System; using System.Linq; using OfficeDevPnP.Core.Utilities.CanvasControl; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers { #if !ONPREMISES internal class ObjectClientSidePages: ObjectHandlerBase { public override string Name { get { return "ClientSidePages"; } } public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { web.EnsureProperties(w => w.ServerRelativeUrl); foreach (var clientSidePage in template.ClientSidePages) { // determine pages library string pagesLibrary = "SitePages"; string pageName = $"{System.IO.Path.GetFileNameWithoutExtension(clientSidePage.PageName)}.aspx"; string url = $"{pagesLibrary}/{pageName}"; url = UrlUtility.Combine(web.ServerRelativeUrl, url); var exists = true; try { var file = web.GetFileByServerRelativeUrl(url); web.Context.Load(file); web.Context.ExecuteQueryRetry(); } catch (ServerException ex) { if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException") { exists = false; } } Pages.ClientSidePage page = null; if (exists) { if (clientSidePage.Overwrite) { // Get the existing page page = web.LoadClientSidePage(pageName); // Clear the page page.ClearPage(); } else { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ClientSidePages_NoOverWrite, pageName); continue; } } else { // Create new client side page page = web.AddClientSidePage(pageName); } // Load existing available controls var componentsToAdd = page.AvailableClientSideComponents().ToList(); // if no section specified then add a default single column section if (!clientSidePage.Sections.Any()) { clientSidePage.Sections.Add(new CanvasSection() { Type = CanvasSectionType.OneColumn, Order = 10 }); } int sectionCount = -1; // Apply the "layout" and content foreach(var section in clientSidePage.Sections) { sectionCount++; switch (section.Type) { case CanvasSectionType.OneColumn: page.AddSection(Pages.CanvasSectionTemplate.OneColumn, section.Order); break; case CanvasSectionType.OneColumnFullWidth: page.AddSection(Pages.CanvasSectionTemplate.OneColumnFullWidth, section.Order); break; case CanvasSectionType.TwoColumn: page.AddSection(Pages.CanvasSectionTemplate.TwoColumn, section.Order); break; case CanvasSectionType.ThreeColumn: page.AddSection(Pages.CanvasSectionTemplate.ThreeColumn, section.Order); break; case CanvasSectionType.TwoColumnLeft: page.AddSection(Pages.CanvasSectionTemplate.TwoColumnLeft, section.Order); break; case CanvasSectionType.TwoColumnRight: page.AddSection(Pages.CanvasSectionTemplate.TwoColumnRight, section.Order); break; default: page.AddSection(Pages.CanvasSectionTemplate.OneColumn, section.Order); break; } // Add controls to the section if (section.Controls.Any()) { // Safety measure: reset column order to 1 for columns marked with 0 or lower foreach(var control in section.Controls.Where(p => p.Column <= 0).ToList()) { control.Column = 1; } foreach(CanvasControl control in section.Controls) { Pages.ClientSideComponent baseControl = null; // Is it a text control? if (control.Type == WebPartType.Text) { Pages.ClientSideText textControl = new Pages.ClientSideText(); if (control.ControlProperties.Any()) { var textProperty = control.ControlProperties.First(); textControl.Text = textProperty.Value; // Reduce column number by 1 due 0 start indexing page.AddControl(textControl, page.Sections[sectionCount].Columns[control.Column - 1], control.Order); } } // It is a web part else { // apply token parsing on the web part properties control.JsonControlData = parser.ParseString(control.JsonControlData); // perform processing of web part properties (e.g. include listid property based list title property) var webPartPostProcessor = CanvasControlPostProcessorFactory.Resolve(control); webPartPostProcessor.Process(control, page); // Is a custom developed client side web part (3rd party) if (control.Type == WebPartType.Custom) { if (!string.IsNullOrEmpty(control.CustomWebPartName)) { baseControl = componentsToAdd.FirstOrDefault(p => p.Name.Equals(control.CustomWebPartName, StringComparison.InvariantCultureIgnoreCase)); } else if (control.ControlId != Guid.Empty) { baseControl = componentsToAdd.FirstOrDefault(p => p.Id.Equals($"{{{control.ControlId.ToString()}}}", StringComparison.CurrentCultureIgnoreCase)); } } // Is an OOB client side web part (1st party) else { string webPartName = ""; switch (control.Type) { case WebPartType.Image: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Image); break; case WebPartType.BingMap: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.BingMap); break; case WebPartType.ContentEmbed: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.ContentEmbed); break; case WebPartType.ContentRollup: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.ContentRollup); break; case WebPartType.DocumentEmbed: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.DocumentEmbed); break; case WebPartType.Events: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Events); break; case WebPartType.GroupCalendar: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.GroupCalendar); break; case WebPartType.Hero: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Hero); break; case WebPartType.ImageGallery: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.ImageGallery); break; case WebPartType.LinkPreview: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.LinkPreview); break; case WebPartType.List: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.List); break; case WebPartType.NewsFeed: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.NewsFeed); break; case WebPartType.NewsReel: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.NewsReel); break; case WebPartType.PageTitle: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.PageTitle); break; case WebPartType.People: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.People); break; case WebPartType.PowerBIReportEmbed: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.PowerBIReportEmbed); break; case WebPartType.QuickChart: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.QuickChart); break; case WebPartType.QuickLinks: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.QuickLinks); break; case WebPartType.SiteActivity: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.SiteActivity); break; case WebPartType.VideoEmbed: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.VideoEmbed); break; case WebPartType.YammerEmbed: webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.YammerEmbed); break; } baseControl = componentsToAdd.FirstOrDefault(p => p.Name.Equals(webPartName, StringComparison.InvariantCultureIgnoreCase)); } if (baseControl != null) { Pages.ClientSideWebPart myWebPart = new Pages.ClientSideWebPart(baseControl) { Order = control.Order }; // Reduce column number by 1 due 0 start indexing page.AddControl(myWebPart, page.Sections[sectionCount].Columns[control.Column - 1], control.Order); // set properties using json string if (!String.IsNullOrEmpty(control.JsonControlData)) { myWebPart.PropertiesJson = control.JsonControlData; } // set using property collection if (control.ControlProperties.Any()) { // grab the "default" properties so we can deduct their types, needed to correctly apply the set properties var controlManifest = JObject.Parse(baseControl.Manifest); JToken controlProperties = null; if (controlManifest != null) { controlProperties = controlManifest.SelectToken("preconfiguredEntries[0].properties"); } foreach (var property in control.ControlProperties) { Type propertyType = typeof(string); if (controlProperties != null) { var defaultProperty = controlProperties.SelectToken(property.Key, false); if (defaultProperty != null) { propertyType = Type.GetType($"System.{defaultProperty.Type.ToString()}"); if (propertyType == null) { if (defaultProperty.Type.ToString().Equals("integer", StringComparison.InvariantCultureIgnoreCase)) { propertyType = typeof(int); } } } } myWebPart.Properties[property.Key] = JToken.FromObject(Convert.ChangeType(parser.ParseString(property.Value), propertyType)); } } } else { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ClientSidePages_BaseControlNotFound, control.ControlId, control.CustomWebPartName); } } } } } // Persist the page page.Save(pageName); // Make it a news page if requested if (clientSidePage.PromoteAsNewsArticle) { page.PromoteAsNewsArticle(); } } } return parser; } public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { using (new PnPMonitoredScope(this.Name)) { // Impossible to return all files in the site currently // If a base template is specified then use that one to "cleanup" the generated template model if (creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate); } } return template; } private ProvisioningTemplate CleanupEntities(ProvisioningTemplate template, ProvisioningTemplate baseTemplate) { return template; } public override bool WillProvision(Web web, ProvisioningTemplate template) { if (!_willProvision.HasValue) { _willProvision = template.ClientSidePages.Any(); } return _willProvision.Value; } public override bool WillExtract(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { if (!_willExtract.HasValue) { _willExtract = false; } return _willExtract.Value; } } #endif } <file_sep>using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.Taxonomy; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions { internal class SiteCollectionTermStoreIdToken : TokenDefinition { public SiteCollectionTermStoreIdToken(Web web) : base(web, "~sitecollectiontermstoreid", "{sitecollectiontermstoreid}") { } public override string GetReplaceValue() { if (CacheValue == null) { this.Web.EnsureProperty(w => w.Url); using (ClientContext context = this.Web.Context.Clone(this.Web.Url)) { TaxonomySession session = TaxonomySession.GetTaxonomySession(context); var termStore = session.GetDefaultSiteCollectionTermStore(); context.Load(termStore, t => t.Id); context.ExecuteQueryRetry(); if (termStore != null) { CacheValue = termStore.Id.ToString(); } } } return CacheValue; } } }<file_sep>using Microsoft.SharePoint.Client; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions { internal class AuthenticationRealmToken : TokenDefinition { public AuthenticationRealmToken(Web web) : base(web, "~authenticationrealm", "~realm", "{authenticationrealm}", "{realm}") { } public override string GetReplaceValue() { return Web.GetAuthenticationRealm().ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace OfficeDevPnP.Core.Utilities { public static class PnPCoreUtilities { /// <summary> /// Get's a tag that identifies the PnP Core library /// </summary> /// <returns>PnP Core library identification tag</returns> public static string PnPCoreVersionTag { get { return (PnPCoreVersionTagLazy.Value); } } private static Lazy<String> PnPCoreVersionTagLazy = new Lazy<String>( () => { Assembly coreAssembly = Assembly.GetExecutingAssembly(); String result = $"PnPCore:{((AssemblyFileVersionAttribute) coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version.Split('.')[2]}"; return (result); }, true); /// <summary> /// Get's a tag that identifies the PnP Core library for UserAgent string /// </summary> /// <returns>PnP Core library identification user-agent</returns> public static string PnPCoreUserAgent { get { return (PnPCoreUserAgentLazy.Value); } } private static Lazy<String> PnPCoreUserAgentLazy = new Lazy<String>( () => { Assembly coreAssembly = Assembly.GetExecutingAssembly(); String result = $"NONISV|SharePointPnP|PnPCore/{((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version}"; return (result); }, true); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.SharePoint.Client; using OfficeDevPnP.Core.Framework.Provisioning.Model; using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.Extensions; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers { internal class ObjectLocalization : ObjectHandlerBase { public override string Name { get { return "Localization"; } } public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { if (creationInfo.PersistMultiLanguageResources) { #if !SP2013 template = UserResourceExtensions.SaveResourceValues(template, creationInfo); #endif } return template; } public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { return parser; } public override bool WillExtract(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { return creationInfo.PersistMultiLanguageResources; } public override bool WillProvision(Web web, ProvisioningTemplate template) { return false; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.Resolvers { internal class FoldersFromSchemaToModelTypeResolver : ITypeResolver { public string Name => this.GetType().Name; public bool CustomCollectionResolver => false; public object Resolve(object source, Dictionary<String, IResolver> resolvers = null, Boolean recursive = false) { var result = new List<Model.Folder>(); var folders = source.GetPublicInstancePropertyValue("Folders"); if (null == folders) { folders = source.GetPublicInstancePropertyValue("Folder1"); } resolvers = new Dictionary<string, IResolver>(); resolvers.Add($"{typeof(Model.Folder).FullName}.Folders", new FoldersFromSchemaToModelTypeResolver()); resolvers.Add($"{typeof(Model.Folder).FullName}.Security", new SecurityFromSchemaToModelTypeResolver()); if (null != folders) { foreach (var f in ((IEnumerable)folders)) { var targetItem = new Model.Folder(); PnPObjectsMapper.MapProperties(f, targetItem, resolvers, recursive); result.Add(targetItem); } } return (result); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OfficeDevPnP.Core.Framework.Provisioning.Model { /// <summary> /// Collection of TermGroup objects /// </summary> public partial class TermGroupCollection : ProvisioningTemplateCollection<TermGroup> { /// <summary> /// Constructor for TermGroupCollection class /// </summary> /// <param name="parentTemplate">Parent provisioning template</param> public TermGroupCollection(ProvisioningTemplate parentTemplate) : base(parentTemplate) { } } } <file_sep>using OfficeDevPnP.Core.Framework.Provisioning.Connectors; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using OfficeDevPnP.Core.Framework.Provisioning.Model; namespace OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml { public class XMLOpenXMLTemplateProvider : XMLTemplateProvider { public XMLOpenXMLTemplateProvider(string packageFileName, FileConnectorBase persistenceConnector, String author = null, X509Certificate2 signingCertificate = null) : base(new OpenXMLConnector(packageFileName, persistenceConnector, author, signingCertificate)) { } public XMLOpenXMLTemplateProvider(OpenXMLConnector openXMLConnector) : base(openXMLConnector) { } } } <file_sep>using Microsoft.SharePoint.Client; using System; using System.Text.RegularExpressions; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions { internal class GroupIdToken : TokenDefinition { private readonly int _groupId = 0; public GroupIdToken(Web web, string name, int groupId) : base(web, $"{{groupid:{Regex.Escape(name)}}}") { _groupId = groupId; } public override string GetReplaceValue() { if (string.IsNullOrEmpty(CacheValue)) { CacheValue = _groupId.ToString(); } return CacheValue; } } }<file_sep>using System; using System.ComponentModel; using Microsoft.Online.SharePoint.TenantAdministration; using OfficeDevPnP.Core; using OfficeDevPnP.Core.Entities; using OfficeDevPnP.Core.Utilities; namespace Microsoft.SharePoint.Client { /// <summary> /// Class for deprecated tenant extension methods /// </summary> public static partial class TenantExtensions { #if !ONPREMISES /// <summary> /// Adds a package to the tenants app catalog and by default deploys it if the package is a client side package (sppkg) /// </summary> /// <param name="tenant">Tenant to operate against</param> /// <param name="spPkgName">Name of the package to upload (e.g. demo.sppkg) </param> /// <param name="spPkgPath">Path on the filesystem where this package is stored</param> /// <param name="autoDeploy">Automatically deploy the package, only applies to client side packages (sppkg)</param> /// <param name="overwrite">Overwrite the package if it was already listed in the app catalog</param> /// <returns>The ListItem of the added package row</returns> [Obsolete("Please use the DeployApplicationPackageToAppCatalog extension method on the Web class. This method will be removed in the October 2017 release.")] public static ListItem DeployApplicationPackageToAppCatalog(this Tenant tenant, string spPkgName, string spPkgPath, bool autoDeploy = true, bool overwrite = true) { var appCatalogSite = tenant.GetAppCatalog(); if (appCatalogSite == null) { throw new ArgumentException("No app catalog site found, please ensure the site exists or specify the site as parameter. Note that the app catalog site is retrieved via search, so take in account the indexing time."); } return DeployApplicationPackageToAppCatalogImplementation(tenant, appCatalogSite.ToString(), spPkgName, spPkgPath, autoDeploy, false, overwrite); } /// <summary> /// Adds a package to the tenants app catalog and by default deploys it if the package is a client side package (sppkg) /// </summary> /// <param name="tenant">Tenant to operate against</param> /// <param name="spPkgName">Name of the package to upload (e.g. demo.sppkg) </param> /// <param name="spPkgPath">Path on the filesystem where this package is stored</param> /// <param name="autoDeploy">Automatically deploy the package, only applies to client side packages (sppkg)</param> /// <param name="skipFeatureDeployment">Skip the feature deployment step, allows for a one-time central deployment of your solution</param> /// <param name="overwrite">Overwrite the package if it was already listed in the app catalog</param> /// <returns>The ListItem of the added package row</returns> [Obsolete("Please use the DeployApplicationPackageToAppCatalog extension method on the Web class. This method will be removed in the October 2017 release.")] public static ListItem DeployApplicationPackageToAppCatalog(this Tenant tenant, string spPkgName, string spPkgPath, bool autoDeploy = true, bool skipFeatureDeployment = true, bool overwrite = true) { var appCatalogSite = tenant.GetAppCatalog(); if (appCatalogSite == null) { throw new ArgumentException("No app catalog site found, please ensure the site exists or specify the site as parameter. Note that the app catalog site is retrieved via search, so take in account the indexing time."); } return DeployApplicationPackageToAppCatalogImplementation(tenant, appCatalogSite.ToString(), spPkgName, spPkgPath, autoDeploy, skipFeatureDeployment, overwrite); } /// <summary> /// Adds a package to the tenants app catalog and by default deploys it if the package is a client side package (sppkg) /// </summary> /// <param name="tenant">Tenant to operate against</param> /// <param name="appCatalogSiteUrl">Full url to the tenant admin site (e.g. https://contoso.sharepoint.com/sites/apps) </param> /// <param name="spPkgName">Name of the package to upload (e.g. demo.sppkg) </param> /// <param name="spPkgPath">Path on the filesystem where this package is stored</param> /// <param name="autoDeploy">Automatically deploy the package, only applies to client side packages (sppkg)</param> /// <param name="overwrite">Overwrite the package if it was already listed in the app catalog</param> /// <returns>The ListItem of the added package row</returns> [Obsolete("Please use the DeployApplicationPackageToAppCatalog overloads on the Web class that don't require you to specify the appCatalogSiteUrl parameter. This method will be removed in the October 2017 release.")] public static ListItem DeployApplicationPackageToAppCatalog(this Tenant tenant, string appCatalogSiteUrl, string spPkgName, string spPkgPath, bool autoDeploy = true, bool overwrite = true) { return DeployApplicationPackageToAppCatalogImplementation(tenant, appCatalogSiteUrl, spPkgName, spPkgPath, autoDeploy, false, overwrite); } private static ListItem DeployApplicationPackageToAppCatalogImplementation(this Tenant tenant, string appCatalogSiteUrl, string spPkgName, string spPkgPath, bool autoDeploy, bool skipFeatureDeployment, bool overwrite) { if (String.IsNullOrEmpty(appCatalogSiteUrl)) { throw new ArgumentException("Please specify a app catalog site url"); } Uri catalogUri; if (!Uri.TryCreate(appCatalogSiteUrl, UriKind.Absolute, out catalogUri)) { throw new ArgumentException("Please specify a valid app catalog site url"); } if (String.IsNullOrEmpty(spPkgName)) { throw new ArgumentException("Please specify a package name"); } if (String.IsNullOrEmpty(spPkgPath)) { throw new ArgumentException("Please specify a package path"); } using (var appCatalogContext = tenant.Context.Clone(catalogUri)) { List catalog = appCatalogContext.Web.GetListByUrl("appcatalog"); if (catalog == null) { throw new Exception($"No app catalog found...did you provide a valid app catalog site?"); } Folder rootFolder = catalog.RootFolder; // Upload package var sppkgFile = rootFolder.UploadFile(spPkgName, System.IO.Path.Combine(spPkgPath, spPkgName), overwrite); if (sppkgFile == null) { throw new Exception($"Upload of {spPkgName} failed"); } if ((autoDeploy || skipFeatureDeployment) && System.IO.Path.GetExtension(spPkgName).ToLower() == ".sppkg") { // Trigger "deployment" by setting the IsClientSideSolutionDeployed bool to true which triggers // an event receiver that will process the sppkg file and update the client side componenent manifest list sppkgFile.ListItemAllFields["IsClientSideSolutionDeployed"] = autoDeploy; // deal with "upgrading" solutions sppkgFile.ListItemAllFields["IsClientSideSolutionCurrentVersionDeployed"] = autoDeploy; // Allow for a central deployment of the solution, no need to install the solution in the individual site collections. // Only works when the solution is not using feature framework to "configure" the site upon solution installation sppkgFile.ListItemAllFields["SkipFeatureDeployment"] = skipFeatureDeployment; sppkgFile.ListItemAllFields.Update(); } appCatalogContext.Load(sppkgFile.ListItemAllFields); appCatalogContext.ExecuteQueryRetry(); return sppkgFile.ListItemAllFields; } } #endif } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using Microsoft.SharePoint.Client; using Microsoft.VisualStudio.TestTools.UnitTesting; using OfficeDevPnP.Core.Framework.Provisioning.Model; using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers; using System.Xml.Linq; namespace OfficeDevPnP.Core.Tests.Framework.ObjectHandlers { [TestClass] public class ObjectListInstanceTests { private const string ElementSchema = @"<Field xmlns=""http://schemas.microsoft.com/sharepoint/v3"" Name=""DemoField"" StaticName=""DemoField"" DisplayName=""Test Field"" Type=""Text"" ID=""{7E5E53E4-86C2-4A64-9F2E-FDFECE6219E0}"" Group=""PnP"" Required=""true""/>"; private Guid fieldId = Guid.Parse("{7E5E53E4-86C2-4A64-9F2E-FDFECE6219E0}"); private const string CalculatedFieldElementSchema = @"<Field Name=""CalculatedField"" StaticName=""CalculatedField"" DisplayName=""Test Calculated Field"" Type=""Calculated"" ResultType=""Text"" ID=""{D1A33456-9FEB-4D8E-AFFA-177EACCE4B70}"" Group=""PnP"" ReadOnly=""TRUE"" ><Formula>=DemoField&amp;""DemoField""</Formula><FieldRefs><FieldRef Name=""DemoField"" ID=""{7E5E53E4-86C2-4A64-9F2E-FDFECE6219E0}"" /></FieldRefs></Field>"; private const string TokenizedCalculatedFieldElementSchema = @"<Field Name=""CalculatedField"" StaticName=""CalculatedField"" DisplayName=""Test Calculated Field"" Type=""Calculated"" ResultType=""Text"" ID=""{D1A33456-9FEB-4D8E-AFFA-177EACCE4B70}"" Group=""PnP"" ReadOnly=""TRUE"" ><Formula>=[{fieldtitle:DemoField}]&amp;""DemoField""</Formula></Field>"; private Guid calculatedFieldId = Guid.Parse("{D1A33456-9FEB-4D8E-AFFA-177EACCE4B70}"); private string listName; private string datarowListName; [TestInitialize] public void Initialize() { listName = string.Format("Test_{0}", DateTime.Now.Ticks); datarowListName = $"DataRowTest_{DateTime.Now.Ticks}"; } [TestCleanup] public void CleanUp() { using (var ctx = TestCommon.CreateClientContext()) { bool isDirty = false; var list = ctx.Web.GetListByUrl(string.Format("lists/{0}", listName)); if (list == null) list = ctx.Web.GetListByUrl(listName); if (list != null) { list.DeleteObject(); isDirty = true; } // Clean all data row test list instances, also after a previous test case failed. DeleteDataRowLists(ctx); var field = ctx.Web.GetFieldById<FieldText>(fieldId); // Guid matches ID in field caml. var calculatedField = ctx.Web.GetFieldById<FieldCalculated>(calculatedFieldId); // Guid matches ID in field caml. if (field != null) { field.DeleteObject(); isDirty = true; } if (calculatedField != null) { calculatedField.DeleteObject(); isDirty = true; } if (isDirty) { ctx.ExecuteQueryRetry(); } } } private void DeleteDataRowLists(ClientContext cc) { cc.Load(cc.Web.Lists, f => f.Include(t => t.Title)); cc.ExecuteQueryRetry(); foreach (var list in cc.Web.Lists.ToList()) { if (list.Title.StartsWith("DataRowTest_")) { list.DeleteObject(); } } cc.ExecuteQueryRetry(); } [TestMethod] public void CanProvisionObjects() { var template = new ProvisioningTemplate(); var listInstance = new Core.Framework.Provisioning.Model.ListInstance(); listInstance.Url = string.Format("lists/{0}", listName); listInstance.Title = listName; listInstance.TemplateType = (int)ListTemplateType.GenericList; Dictionary<string, string> dataValues = new Dictionary<string, string>(); dataValues.Add("Title", "Test"); DataRow dataRow = new DataRow(dataValues); listInstance.DataRows.Add(dataRow); template.Lists.Add(listInstance); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); // Create the List parser = new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); // Load DataRows new ObjectListInstanceDataRows().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var list = ctx.Web.GetListByUrl(listInstance.Url); Assert.IsNotNull(list); var items = list.GetItems(CamlQuery.CreateAllItemsQuery()); ctx.Load(items, itms => itms.Include(item => item["Title"])); ctx.ExecuteQueryRetry(); Assert.IsTrue(items.Count == 1); Assert.IsTrue(items[0]["Title"].ToString() == "Test"); } } [TestMethod] public void CanCreateEntities() { using (var ctx = TestCommon.CreateClientContext()) { // Load the base template which will be used for the comparison work var creationInfo = new ProvisioningTemplateCreationInformation(ctx.Web) { BaseTemplate = ctx.Web.GetBaseTemplate() }; var template = new ProvisioningTemplate(); template = new ObjectListInstance().ExtractObjects(ctx.Web, template, creationInfo); Assert.IsTrue(template.Lists.Any()); } } [TestMethod] public void CanTokensBeUsedInListInstance() { using (var ctx = TestCommon.CreateClientContext()) { // Create list instance var template = new ProvisioningTemplate(); var listUrl = string.Format("lists/{0}", listName); var listTitle = listName + "_Title"; var listDesc = listName + "_Description"; template.Parameters.Add("listTitle", listTitle); template.Parameters.Add("listDesc", listDesc); template.Lists.Add(new Core.Framework.Provisioning.Model.ListInstance { Url = listUrl, Title = "{parameter:listTitle}", Description = "{parameter:listDesc}", TemplateType = (int)ListTemplateType.GenericList }); ctx.Web.ApplyProvisioningTemplate(template); var list = ctx.Web.GetListByUrl(listUrl, l => l.Title, l => l.Description); Assert.IsNotNull(list); Assert.AreEqual(listTitle, list.Title); Assert.AreEqual(listDesc, list.Description); // Update list instance var updatedTemplate = new ProvisioningTemplate(); var updatedTitle = listName + "_UpdatedTitle"; var updatedDesc = listName + "_UpdatedDescription"; updatedTemplate.Parameters.Add("listTitle", updatedTitle); updatedTemplate.Parameters.Add("listDesc", updatedDesc); updatedTemplate.Lists.Add(new Core.Framework.Provisioning.Model.ListInstance { Url = listUrl, Title = "{parameter:listTitle}", Description = "{parameter:listDesc}", TemplateType = (int)ListTemplateType.GenericList }); ctx.Web.ApplyProvisioningTemplate(updatedTemplate); var updatedList = ctx.Web.GetListByUrl(listUrl, l => l.Title, l => l.Description); Assert.AreEqual(updatedTitle, updatedList.Title); Assert.AreEqual(updatedDesc, updatedList.Description); } } [TestMethod] public void FolderContentTypeShouldNotBeRemovedFromProvisionedDocumentLibraries() { using (var ctx = TestCommon.CreateClientContext()) { var listInstance = new Core.Framework.Provisioning.Model.ListInstance(); listInstance.Url = listName; listInstance.Title = listName; listInstance.TemplateType = (int)ListTemplateType.DocumentLibrary; listInstance.ContentTypesEnabled = true; listInstance.RemoveExistingContentTypes = true; listInstance.ContentTypeBindings.Add(new ContentTypeBinding { ContentTypeId = BuiltInContentTypeId.DublinCoreName, Default = true }); var template = new ProvisioningTemplate(); template.Lists.Add(listInstance); ctx.Web.ApplyProvisioningTemplate(template); var list = ctx.Web.GetListByUrl(listName); var contentTypes = list.EnsureProperty(l => l.ContentTypes); Assert.IsTrue(contentTypes.Any(ct => ct.StringId.StartsWith(BuiltInContentTypeId.Folder + "00")), "Folder content type should not be removed from a document library."); } } [TestMethod] public void DefaultContentTypeShouldBeRemovedFromProvisionedAssetLibraries() { using (var ctx = TestCommon.CreateClientContext()) { // Arrange var listInstance = new Core.Framework.Provisioning.Model.ListInstance(); listInstance.Url = $"lists/{listName}"; listInstance.Title = listName; // An asset must be created by using the // template type AND the template feature id listInstance.TemplateType = 851; listInstance.TemplateFeatureID = new Guid("4bcccd62-dcaf-46dc-a7d4-e38277ef33f4"); // Also attachements are not allowed on an asset list listInstance.EnableAttachments = false; listInstance.ContentTypesEnabled = true; listInstance.RemoveExistingContentTypes = true; listInstance.ContentTypeBindings.Add(new ContentTypeBinding { ContentTypeId = BuiltInContentTypeId.DublinCoreName, Default = true }); var template = new ProvisioningTemplate(); template.Lists.Add(listInstance); // Act ctx.Web.ApplyProvisioningTemplate(template); var list = ctx.Web.GetListByUrl(listInstance.Url); var contentTypes = list.EnsureProperty(l => l.ContentTypes); // Assert // Asset list should only have the custom content type we defined // and the folder content type Assert.AreEqual(contentTypes.Count, 2); } } [TestMethod] public void UpdatedListTitleShouldBeAvailableAsToken() { var listUrl = string.Format("lists/{0}", listName); var listId = ""; // Create the initial list using (var ctx = TestCommon.CreateClientContext()) { var list = ctx.Web.Lists.Add(new ListCreationInformation() { Title = listName, TemplateType = (int)ListTemplateType.GenericList, Url = listUrl }); list.EnsureProperty(l => l.Id); ctx.ExecuteQueryRetry(); listId = list.Id.ToString(); } // Update list Title using a provisioning template // - Using a clean clientcontext to catch all possible "property not loaded" problems using (var ctx = TestCommon.CreateClientContext()) { var updatedListTitle = listName + "_edit"; var template = new ProvisioningTemplate(); var listInstance = new Core.Framework.Provisioning.Model.ListInstance(); listInstance.Url = listUrl; listInstance.Title = updatedListTitle; listInstance.TemplateType = (int)ListTemplateType.GenericList; template.Lists.Add(listInstance); var mockProviderType = typeof(MockProviderForListInstanceTests); var providerConfig = "{listid:" + updatedListTitle + "}+{listurl:" + updatedListTitle + "}"; template.Providers.Add(new Provider() { Assembly = mockProviderType.Assembly.FullName, Type = mockProviderType.FullName, Enabled = true, Configuration = providerConfig }); ctx.Web.ApplyProvisioningTemplate(template); } // Verify that tokens have been replaced var expectedConfig = string.Format("{0}+{1}", listId, listUrl).ToLower(); Assert.AreEqual(expectedConfig, MockProviderForListInstanceTests.ConfigurationData.ToLower(), "Updated list title is not available as a token."); } class MockProviderForListInstanceTests : OfficeDevPnP.Core.Framework.Provisioning.Extensibility.IProvisioningExtensibilityProvider { public static string ConfigurationData { get; private set; } public void ProcessRequest(ClientContext ctx, ProvisioningTemplate template, string configurationData) { ConfigurationData = configurationData; } } [TestMethod] public void CanProvisionCalculatedFieldRefInListInstance() { var template = new ProvisioningTemplate(); template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field() { SchemaXml = ElementSchema }); template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field() { SchemaXml = TokenizedCalculatedFieldElementSchema }); var listInstance = new ListInstance(); listInstance.Url = string.Format("lists/{0}", listName); listInstance.Title = listName; listInstance.TemplateType = (int)ListTemplateType.GenericList; var referencedField = new FieldRef(); referencedField.Id = fieldId; listInstance.FieldRefs.Add(referencedField); var calculatedFieldRef = new FieldRef(); calculatedFieldRef.Id = calculatedFieldId; listInstance.FieldRefs.Add(calculatedFieldRef); template.Lists.Add(listInstance); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectField().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var list = ctx.Web.GetListByUrl(listInstance.Url); Assert.IsNotNull(list); var rf = list.GetFieldById<FieldText>(fieldId); var f = list.GetFieldById<FieldCalculated>(calculatedFieldId); Assert.IsNotNull(rf, "Referenced field not added"); Assert.IsNotNull(f); Assert.IsInstanceOfType(f, typeof(FieldCalculated)); Assert.IsFalse(f.Formula.Contains('#') || f.Formula.Contains('?'), "Calculated field was not provisioned properly"); } } [TestMethod] public void CanUpdateCalculatedFieldRefInListInstance() { var template = new ProvisioningTemplate(); template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field() { SchemaXml = ElementSchema }); template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field() { SchemaXml = TokenizedCalculatedFieldElementSchema }); var listInstance = new ListInstance(); listInstance.Url = string.Format("lists/{0}", listName); listInstance.Title = listName; listInstance.TemplateType = (int)ListTemplateType.GenericList; var referencedField = new FieldRef(); referencedField.Id = fieldId; listInstance.FieldRefs.Add(referencedField); var calculatedFieldRef = new FieldRef(); calculatedFieldRef.Id = calculatedFieldId; listInstance.FieldRefs.Add(calculatedFieldRef); template.Lists.Add(listInstance); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectField().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var list = ctx.Web.GetListByUrl(listInstance.Url); Assert.IsNotNull(list); var rf = list.GetFieldById<FieldText>(fieldId); var f1 = list.GetFieldById<FieldCalculated>(calculatedFieldId); Assert.IsNotNull(rf, "Referenced field not added"); Assert.IsNotNull(f1); Assert.IsInstanceOfType(f1, typeof(FieldCalculated)); Assert.IsFalse(f1.Formula.Contains('#') || f1.Formula.Contains('?'), "Calculated field was not provisioned properly the first time"); new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var f2 = list.GetFieldById<FieldCalculated>(calculatedFieldId); Assert.IsNotNull(f2); Assert.IsInstanceOfType(f2, typeof(FieldCalculated)); Assert.IsFalse(f2.Formula.Contains('#') || f2.Formula.Contains('?'), "Calculated field was not provisioned properly the second time"); } } [TestMethod] public void CanProvisionCalculatedFieldInListInstance() { var template = new ProvisioningTemplate(); var listInstance = new ListInstance(); template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field() { SchemaXml = ElementSchema }); listInstance.Url = string.Format("lists/{0}", listName); listInstance.Title = listName; listInstance.TemplateType = (int)ListTemplateType.GenericList; var referencedField = new FieldRef(); referencedField.Id = fieldId; listInstance.FieldRefs.Add(referencedField); var calculatedField = new Core.Framework.Provisioning.Model.Field(); calculatedField.SchemaXml = TokenizedCalculatedFieldElementSchema; listInstance.Fields.Add(calculatedField); template.Lists.Add(listInstance); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectField().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var list = ctx.Web.GetListByUrl(listInstance.Url); Assert.IsNotNull(list); var rf = list.GetFieldById<FieldText>(fieldId); var f = list.GetFieldById<FieldCalculated>(calculatedFieldId); Assert.IsNotNull(rf, "Referenced field not added"); Assert.IsNotNull(f); Assert.IsInstanceOfType(f, typeof(FieldCalculated)); Assert.IsFalse(f.Formula.Contains('#') || f.Formula.Contains('?'), "Calculated field was not provisioned properly"); } } [TestMethod] public void CanProvisionCalculatedFieldLocallyInListInstance() { //This test will fail as tokens does not support this scenario. //The test serves as a reminder that this is not supported and needs to be fixed in a future release. var template = new ProvisioningTemplate(); var listInstance = new ListInstance(); listInstance.Url = string.Format("lists/{0}", listName); listInstance.Title = listName; listInstance.TemplateType = (int)ListTemplateType.GenericList; var referencedField = new Core.Framework.Provisioning.Model.Field(); referencedField.SchemaXml = ElementSchema; listInstance.Fields.Add(referencedField); var calculatedField = new Core.Framework.Provisioning.Model.Field(); calculatedField.SchemaXml = TokenizedCalculatedFieldElementSchema; listInstance.Fields.Add(calculatedField); template.Lists.Add(listInstance); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var list = ctx.Web.GetListByUrl(listInstance.Url); Assert.IsNotNull(list); var rf = list.GetFieldById<FieldText>(fieldId); var f = list.GetFieldById<FieldCalculated>(calculatedFieldId); Assert.IsNotNull(rf, "Referenced field not added"); Assert.IsNotNull(f); Assert.IsInstanceOfType(f, typeof(FieldCalculated)); Assert.IsFalse(f.Formula.Contains('#') || f.Formula.Contains('?'), "Calculated field was not provisioned properly"); } } [TestMethod] public void CanUpdateCalculatedFieldInListInstance() { var template = new ProvisioningTemplate(); var listInstance = new ListInstance(); template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field() { SchemaXml = ElementSchema }); listInstance.Url = string.Format("lists/{0}", listName); listInstance.Title = listName; listInstance.TemplateType = (int)ListTemplateType.GenericList; var referencedField = new FieldRef(); referencedField.Id = fieldId; listInstance.FieldRefs.Add(referencedField); var calculatedField = new Core.Framework.Provisioning.Model.Field(); calculatedField.SchemaXml = TokenizedCalculatedFieldElementSchema; listInstance.Fields.Add(calculatedField); template.Lists.Add(listInstance); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectField().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var list = ctx.Web.GetListByUrl(listInstance.Url); Assert.IsNotNull(list); var rf = list.GetFieldById<FieldText>(fieldId); var f1 = list.GetFieldById<FieldCalculated>(calculatedFieldId); Assert.IsNotNull(rf, "Referenced field not added"); Assert.IsNotNull(f1); Assert.IsInstanceOfType(f1, typeof(FieldCalculated)); Assert.IsFalse(f1.Formula.Contains('#') || f1.Formula.Contains('?'), "Calculated field was not provisioned properly the first time"); new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var f2 = list.GetFieldById<FieldCalculated>(calculatedFieldId); Assert.IsNotNull(f2); Assert.IsInstanceOfType(f2, typeof(FieldCalculated)); Assert.IsFalse(f2.Formula.Contains('#') || f2.Formula.Contains('?'), "Calculated field was not provisioned properly the second time"); } } [TestMethod] public void CanExtractCalculatedFieldFromListInstance() { var template = new ProvisioningTemplate(); var listInstance = new ListInstance(); template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field() { SchemaXml = ElementSchema }); listInstance.Url = string.Format("lists/{0}", listName); listInstance.Title = listName; listInstance.TemplateType = (int)ListTemplateType.GenericList; var referencedField = new FieldRef(); referencedField.Id = fieldId; listInstance.FieldRefs.Add(referencedField); var calculatedField = new Core.Framework.Provisioning.Model.Field(); calculatedField.SchemaXml = TokenizedCalculatedFieldElementSchema; listInstance.Fields.Add(calculatedField); template.Lists.Add(listInstance); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectField().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var list = ctx.Web.GetListByUrl(listInstance.Url); Assert.IsNotNull(list); var rf = list.GetFieldById<FieldText>(fieldId); var f = list.GetFieldById<FieldCalculated>(calculatedFieldId); Assert.IsNotNull(rf, "Referenced field not added"); Assert.IsNotNull(f); Assert.IsInstanceOfType(f, typeof(FieldCalculated)); Assert.IsFalse(f.Formula.Contains('#') || f.Formula.Contains('?'), "Calculated field was not provisioned properly"); var extractedTemplate = new ProvisioningTemplate(); var provisioningTemplateCreationInformation = new ProvisioningTemplateCreationInformation(ctx.Web); new ObjectListInstance().ExtractObjects(ctx.Web, extractedTemplate, provisioningTemplateCreationInformation); XElement fieldElement = XElement.Parse(extractedTemplate.Lists.First(l => l.Title == listName).Fields.First(cf => Guid.Parse(XElement.Parse(cf.SchemaXml).Attribute("ID").Value).Equals(calculatedFieldId)).SchemaXml); var formula = fieldElement.Descendants("Formula").FirstOrDefault(); Assert.AreEqual(@"=[{fieldtitle:DemoField}]&""DemoField""", formula.Value, true, "Calculated field formula is not extracted properly"); } } [TestMethod] public void DataRowsAreBeingSkippedIfAlreadyInplace() { using (var ctx = TestCommon.CreateClientContext()) { var template = new ProvisioningTemplate(); template.TemplateCultureInfo = "1033"; var listinstance = new ListInstance() { Title = datarowListName, Url = $"lists/{datarowListName}", TemplateType = 100, }; listinstance.Fields.Add(new Core.Framework.Provisioning.Model.Field() { SchemaXml = $@"<Field Type=""Text"" DisplayName=""Key"" Required=""FALSE"" EnforceUniqueValues=""FALSE"" Indexed=""FALSE"" MaxLength=""255"" ID=""{(Guid.NewGuid().ToString("B"))}"" StaticName=""Key"" Name=""Key"" />" }); var datarows = new List<DataRow>() { new DataRow(new Dictionary<string, string>{ { "Title", "Test -1-"}, { "Key", "1" } }, "1" ), new DataRow(new Dictionary<string,string>{{ "Title" ,"Test -2-"}, { "Key", "2" } }, "2"), new DataRow(new Dictionary<string,string>{{ "Title" ,"Test -3-"}, { "Key", "3" } }, "3") }; listinstance.DataRows.AddRange(datarows); template.Lists.Add(listinstance); ctx.Web.ApplyProvisioningTemplate(template); var rowCount = ctx.Web.GetListByTitle(datarowListName).ItemCount; Assert.IsTrue(rowCount == 3, "Row count not equals 3"); listinstance.DataRows.KeyColumn = "Key"; listinstance.DataRows.UpdateBehavior = UpdateBehavior.Skip; ctx.Web.ApplyProvisioningTemplate(template); rowCount = ctx.Web.GetListByTitle(datarowListName).ItemCount; Assert.IsTrue(rowCount == 3, "Row count not equals 3"); listinstance.DataRows.UpdateBehavior = UpdateBehavior.Overwrite; ctx.Web.ApplyProvisioningTemplate(template); rowCount = ctx.Web.GetListByTitle(datarowListName).ItemCount; Assert.IsTrue(rowCount == 3, "Row count not equals 3"); listinstance.DataRows.Add(new DataRow(new Dictionary<string, string> { { "Title", "Test -4-" }, { "Key", "4" } }, "4")); ctx.Web.ApplyProvisioningTemplate(template); rowCount = ctx.Web.GetListByTitle(datarowListName).ItemCount; Assert.IsTrue(rowCount == 4, "Row count not equals 4"); } } } }<file_sep>using OfficeDevPnP.Core.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OfficeDevPnP.Core.Framework.Provisioning.Model { /// <summary> /// Defines a ClientSidePage /// </summary> public partial class ClientSidePage : BaseModel, IEquatable<ClientSidePage> { #region Private Members private CanvasSectionCollection _sections; #endregion #region Public Members /// <summary> /// Gets or sets the sections /// </summary> public CanvasSectionCollection Sections { get { return _sections; } private set { _sections = value; } } /// <summary> /// Defines the Page Name of the Client Side Page, required attribute. /// </summary> public String PageName { get; set; } /// <summary> /// Defines whether to promote the page as a news article, optional attribute /// </summary> public Boolean PromoteAsNewsArticle { get; set; } /// <summary> /// Defines whether the page can be overwritten if it exists /// </summary> public Boolean Overwrite { get; set; } #endregion #region Constructors /// <summary> /// Constructor for ClientSidePage class /// </summary> public ClientSidePage() { this._sections = new CanvasSectionCollection(this.ParentTemplate); } #endregion #region Comparison code /// <summary> /// Gets the hash code /// </summary> /// <returns>Returns HashCode</returns> public override int GetHashCode() { return (String.Format("{0}|{1}|{2}|", this.Sections.Aggregate(0, (acc, next) => acc += (next != null ? next.GetHashCode() : 0)), PageName?.GetHashCode() ?? 0, PromoteAsNewsArticle.GetHashCode(), Overwrite.GetHashCode() ).GetHashCode()); } /// <summary> /// Compares object with ClientSidePage class /// </summary> /// <param name="obj">Object that represents ClientSidePage</param> /// <returns>Checks whether object is ClientSidePage class</returns> public override bool Equals(object obj) { if (!(obj is ClientSidePage)) { return (false); } return (Equals((ClientSidePage)obj)); } /// <summary> /// Compares ClientSidePage object based on Sections, PagesLibrary, and PromoteAsNewsArticle /// </summary> /// <param name="other">ClientSidePage Class object</param> /// <returns>true if the ClientSidePage object is equal to the current object; otherwise, false.</returns> public bool Equals(ClientSidePage other) { if (other == null) { return (false); } return (this.Sections.DeepEquals(other.Sections) && this.PageName == other.PageName && this.PromoteAsNewsArticle == other.PromoteAsNewsArticle && this.Overwrite == other.Overwrite ); } #endregion } } <file_sep>using Microsoft.SharePoint.Client; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions { internal class CurrentUserLoginNameToken : TokenDefinition { public CurrentUserLoginNameToken(Web web) : base(web, "~currentuserloginname", "{currentuserloginname}") { } public override string GetReplaceValue() { if (CacheValue == null) { this.Web.EnsureProperty(w => w.Url); using (ClientContext context = this.Web.Context.Clone(this.Web.Url)) { var currentUser = context.Web.EnsureProperty(w => w.CurrentUser); CacheValue = currentUser.LoginName; } } return CacheValue; } } }<file_sep>using Newtonsoft.Json; namespace OfficeDevPnP.Core.Pages { #if !ONPREMISES #region Classes to support json (de-)serialization of control/webpart data #region Control data /// <summary> /// Base class representing the json control data that will describe a control versus the zones and sections on a page /// </summary> public class ClientSideCanvasPosition { /// <summary> /// Gets or sets JsonProperty "zoneIndex" /// </summary> [JsonProperty(PropertyName = "zoneIndex")] public float ZoneIndex { get; set; } /// <summary> /// Gets or sets JsonProperty "sectionIndex" /// </summary> [JsonProperty(PropertyName = "sectionIndex")] public int SectionIndex { get; set; } /// <summary> /// Gets or sets JsonProperty "sectionFactor" /// </summary> [JsonProperty(PropertyName = "sectionFactor", NullValueHandling = NullValueHandling.Ignore)] public int? SectionFactor { get; set; } } /// <summary> /// Class representing the json control data that will describe a control versus the zones and sections on a page /// </summary> public class ClientSideCanvasControlPosition: ClientSideCanvasPosition { /// <summary> /// Gets or sets JsonProperty "controlIndex" /// </summary> [JsonProperty(PropertyName = "controlIndex")] public float ControlIndex { get; set; } } /// <summary> /// Base class representing the json control data that will be included in each client side control (de-)serialization (data-sp-controldata attribute) /// </summary> public class ClientSideCanvasData { /// <summary> /// Gets or sets JsonProperty "position" /// </summary> [JsonProperty(PropertyName = "position")] public ClientSideCanvasPosition Position { get; set; } } /// <summary> /// Base class representing the json control data that will be included in each client side control (de-)serialization (data-sp-controldata attribute) /// </summary> public class ClientSideCanvasControlData { /// <summary> /// Gets or sets JsonProperty "controlType" /// </summary> [JsonProperty(PropertyName = "controlType")] public int ControlType { get; set; } /// <summary> /// Gets or sets JsonProperty "id" /// </summary> [JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Gets or sets JsonProperty "position" /// </summary> [JsonProperty(PropertyName = "position")] public ClientSideCanvasControlPosition Position { get; set; } } /// <summary> /// Control data for controls of type 4 (= text control) /// </summary> public class ClientSideTextControlData : ClientSideCanvasControlData { /// <summary> /// Gets or sets JsonProperty "editorType" /// </summary> [JsonProperty(PropertyName = "editorType")] public string EditorType { get; set; } } /// <summary> /// Control data for controls of type 3 (= client side web parts) /// </summary> public class ClientSideWebPartControlData : ClientSideCanvasControlData { /// <summary> /// Gets or sets JsonProperty "webPartId" /// </summary> [JsonProperty(PropertyName = "webPartId")] public string WebPartId { get; set; } } #endregion #region WebPart data /// <summary> /// Json web part data that will be included in each client side web part (de-)serialization (data-sp-webpartdata) /// </summary> public class ClientSideWebPartData { /// <summary> /// Gets or sets JsonProperty "id" /// </summary> [JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Gets or sets JsonProperty "instanceId" /// </summary> [JsonProperty(PropertyName = "instanceId")] public string InstanceId { get; set; } /// <summary> /// Gets or sets JsonProperty "title" /// </summary> [JsonProperty(PropertyName = "title")] public string Title { get; set; } /// <summary> /// Gets or sets JsonProperty "description" /// </summary> [JsonProperty(PropertyName = "description")] public string Description { get; set; } /// <summary> /// Gets or sets JsonProperty "dataVersion" /// </summary> [JsonProperty(PropertyName = "dataVersion")] public string DataVersion { get; set; } /// <summary> /// Gets or sets JsonProperty "properties" /// </summary> [JsonProperty(PropertyName = "properties")] public string Properties { get; set; } } #endregion #endregion #endif } <file_sep>using Microsoft.Online.SharePoint.TenantAdministration; using Microsoft.SharePoint.Client; using Microsoft.VisualStudio.TestTools.UnitTesting; using OfficeDevPnP.Core.Entities; using System; using System.Collections.Generic; using System.Configuration; namespace OfficeDevPnP.Core.Tests.Framework.Functional { [TestClass()] public abstract class FunctionalTestBase { private static string sitecollectionNamePrefix = "TestPnPSC_12345_"; internal static string centralSiteCollectionUrl = ""; internal static string centralSubSiteUrl = ""; internal const string centralSubSiteName = "sub"; internal static bool debugMode = false; internal string sitecollectionName = ""; #region Test preparation public static void ClassInitBase(TestContext context, bool noScriptSite = false) { // Drop all previously created site collections to keep the environment clean using (var tenantContext = TestCommon.CreateTenantClientContext()) { if (!debugMode) { CleanupAllTestSiteCollections(tenantContext); // Each class inheriting from this base class gets a central test site collection, so let's create that one var tenant = new Tenant(tenantContext); centralSiteCollectionUrl = CreateTestSiteCollection(tenant, sitecollectionNamePrefix + Guid.NewGuid().ToString()); // Add a default sub site centralSubSiteUrl = CreateTestSubSite(tenant, centralSiteCollectionUrl, centralSubSiteName); #if !ONPREMISES // Apply noscript setting if (noScriptSite) { Console.WriteLine("Setting site {0} as NoScript", centralSiteCollectionUrl); tenant.SetSiteProperties(centralSiteCollectionUrl, noScriptSite: true); } #endif } } } public static void ClassCleanupBase() { if (!debugMode) { using (var tenantContext = TestCommon.CreateTenantClientContext()) { #if !ONPREMISES CleanupAllTestSiteCollections(tenantContext); #else // first cleanup the just created one...most likely it's not indexed yet try { Tenant t = new Tenant(tenantContext); t.DeleteSiteCollection(centralSiteCollectionUrl); } catch { } // Use search based site collection retrieval to delete the one's that are left over from failed test cases CleanupAllTestSiteCollections(tenantContext); #endif } } } [TestInitialize()] public virtual void Initialize() { sitecollectionName = sitecollectionNamePrefix + Guid.NewGuid().ToString(); } #endregion #region Helper methods #if !ONPREMISES internal static string CreateTestSiteCollection(Tenant tenant, string sitecollectionName) { try { string devSiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"]; string siteToCreateUrl = GetTestSiteCollectionName(devSiteUrl, sitecollectionName); string siteOwnerLogin = ConfigurationManager.AppSettings["SPOUserName"]; if (TestCommon.AppOnlyTesting()) { using (var clientContext = TestCommon.CreateClientContext()) { List<UserEntity> admins = clientContext.Web.GetAdministrators(); siteOwnerLogin = admins[0].LoginName.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries)[2]; } } SiteEntity siteToCreate = new SiteEntity() { Url = siteToCreateUrl, Template = "STS#0", Title = "Test", Description = "Test site collection", SiteOwnerLogin = siteOwnerLogin, Lcid = 1033, StorageMaximumLevel = 100, UserCodeMaximumLevel = 0 }; tenant.CreateSiteCollection(siteToCreate, false, true); return siteToCreateUrl; } catch (Exception ex) { Console.WriteLine(ex.ToDetailedString(tenant.Context)); throw; } } private static void CleanupAllTestSiteCollections(ClientContext tenantContext) { var tenant = new Tenant(tenantContext); try { var siteCols = tenant.GetSiteCollections(); foreach (var siteCol in siteCols) { if (siteCol.Url.Contains(sitecollectionNamePrefix)) { try { // Drop the site collection from the recycle bin if (tenant.CheckIfSiteExists(siteCol.Url, "Recycled")) { tenant.DeleteSiteCollectionFromRecycleBin(siteCol.Url, false); } else { // Eat the exceptions: would occur if the site collection is already in the recycle bin. try { // ensure the site collection in unlocked state before deleting tenant.SetSiteLockState(siteCol.Url, SiteLockState.Unlock); } catch { } // delete the site collection, do not use the recyle bin tenant.DeleteSiteCollection(siteCol.Url, false); } } catch (Exception ex) { // eat all exceptions Console.WriteLine(ex.ToDetailedString(tenant.Context)); } } } } // catch exceptions with the GetSiteCollections call and log them so we can grab the corelation ID catch (Exception ex) { Console.WriteLine(ex.ToDetailedString(tenant.Context)); throw; } } internal static string CreateTestSubSite(Tenant tenant, string sitecollectionUrl, string subSiteName) { try { // Create a sub site in the central site collection using (var cc = TestCommon.CreateClientContext(sitecollectionUrl)) { //Create sub site SiteEntity sub = new SiteEntity() { Title = "Sub site for engine testing", Url = subSiteName, Description = "" }; var subWeb = cc.Web.CreateWeb(sub); subWeb.EnsureProperty(t => t.Url); return subWeb.Url; } } catch(Exception ex) { Console.WriteLine(ex.ToDetailedString()); throw; } // Below approach is not working on edog...to be investigated //// create a sub site in the central site collection //Site site = tenant.GetSiteByUrl(sitecollectionUrl); //tenant.Context.Load(site); //tenant.Context.ExecuteQueryRetry(); //Web web = site.RootWeb; //web.Context.Load(web); //web.Context.ExecuteQueryRetry(); ////Create sub site //SiteEntity sub = new SiteEntity() { Title = "Sub site for engine testing", Url = subSiteName, Description = "" }; //var subWeb = web.CreateWeb(sub); //subWeb.EnsureProperty(t => t.Url); //return subWeb.Url; } #else private static string CreateTestSiteCollection(Tenant tenant, string sitecollectionName, bool isNoScriptSite = false) { string devSiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"]; string siteOwnerLogin = string.Format("{0}\\{1}", ConfigurationManager.AppSettings["OnPremDomain"], ConfigurationManager.AppSettings["OnPremUserName"]); if (TestCommon.AppOnlyTesting()) { using (var clientContext = TestCommon.CreateClientContext()) { List<UserEntity> admins = clientContext.Web.GetAdministrators(); siteOwnerLogin = admins[0].LoginName.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries)[1]; } } string siteToCreateUrl = GetTestSiteCollectionName(devSiteUrl, sitecollectionName); SiteEntity siteToCreate = new SiteEntity() { Url = siteToCreateUrl, Template = "STS#0", Title = "Test", Description = "Test site collection", SiteOwnerLogin = siteOwnerLogin, Lcid = 1033, }; tenant.CreateSiteCollection(siteToCreate); // Create the default groups using (ClientContext cc = new ClientContext(siteToCreateUrl)) { var owners = cc.Web.AddGroup("Test Owners", "", true, false); var members = cc.Web.AddGroup("Test Members", "", true, false); var visitors = cc.Web.AddGroup("Test Visitors", "", true, true); cc.Web.AssociateDefaultGroups(owners, members, visitors); } return siteToCreateUrl; } internal static string CreateTestSubSite(Tenant tenant, string sitecollectionUrl, string subSiteName) { using (ClientContext cc = new ClientContext(sitecollectionUrl)) { //Create sub site SiteEntity sub = new SiteEntity() { Title = "Sub site for engine testing", Url = subSiteName, Description = "" }; var subWeb = cc.Web.CreateWeb(sub); subWeb.EnsureProperty(t => t.Url); return subWeb.Url; } } private static void CleanupAllTestSiteCollections(ClientContext tenantContext) { string devSiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"]; var tenant = new Tenant(tenantContext); try { using (ClientContext cc = tenantContext.Clone(devSiteUrl)) { var sites = cc.Web.SiteSearch(); foreach(var site in sites) { if (site.Url.ToLower().Contains(sitecollectionNamePrefix.ToLower())) { tenant.DeleteSiteCollection(site.Url); } } } } catch { } } private void CleanupCreatedTestSiteCollections(ClientContext tenantContext) { string devSiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"]; String testSiteCollection = GetTestSiteCollectionName(devSiteUrl, sitecollectionName); //Ensure the test site collection was deleted and removed from recyclebin var tenant = new Tenant(tenantContext); try { tenant.DeleteSiteCollection(testSiteCollection); } catch { } } #endif private static string GetTestSiteCollectionName(string devSiteUrl, string siteCollection) { Uri u = new Uri(devSiteUrl); string host = String.Format("{0}://{1}", u.Scheme, u.DnsSafeHost); string path = u.AbsolutePath; if (path.EndsWith("/")) { path = path.Substring(0, path.Length - 1); } path = path.Substring(0, path.LastIndexOf('/')); return string.Format("{0}{1}/{2}", host, path, siteCollection); } #endregion } } <file_sep>using System; using Microsoft.SharePoint.Client; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using OfficeDevPnP.Core.Entities; using System.Linq; using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers; using OfficeDevPnP.Core.Framework.Provisioning.Model; using OfficeDevPnP.Core.Framework.Provisioning.Connectors; using OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml; #if !ONPREMISES using OfficeDevPnP.Core.Pages; #endif namespace OfficeDevPnP.Core.Tests.Authentication { #if !ONPREMISES [TestClass] public class ClientSidePagesTests { #region Test initialization [ClassInitialize()] public static void ClassInit(TestContext context) { } [ClassCleanup()] public static void ClassCleanup() { using (var clientContext = TestCommon.CreateClientContext()) { } } #endregion //[TestMethod] //public void PageTest() //{ // using (var clientContext = TestCommon.CreateClientContext("https://bertonline.sharepoint.com/sites/bert1")) // { // ProvisioningTemplateCreationInformation ptci = new ProvisioningTemplateCreationInformation(clientContext.Web) // { // // Limit the amount of handlers in this demo // HandlersToProcess = Handlers.PageContents, // // Create FileSystemConnector, so that we can store composed files temporarely somewhere // FileConnector = new FileSystemConnector(@"C:\temp", ""), // //PersistBrandingFiles = true, // ProgressDelegate = delegate (String message, Int32 progress, Int32 total) // { // // Only to output progress for console UI // Console.WriteLine("{0:00}/{1:00} - {2}", progress, total, message); // } // }; // // Execute actual extraction of the tepmplate // ProvisioningTemplate template = clientContext.Web.GetProvisioningTemplate(ptci); // // Serialize to XML using the beta 201705 schema // XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(@"C:\temp", ""); // var formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2017_05); // provider.SaveAs(template, "PnPProvisioningDemo201705.xml", formatter); // } //} //[TestMethod] //public void Page2Test() //{ // using (var clientContext = TestCommon.CreateClientContext("https://bertonline.sharepoint.com/sites/bert1")) // { // ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation() // { // HandlersToProcess = Handlers.PageContents, // ProgressDelegate = delegate (String message, Int32 progress, Int32 total) // { // // Only to output progress for console UI // Console.WriteLine("{0:00}/{1:00} - {2}", progress, total, message); // } // }; // XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(@"c:\temp", ""); // ProvisioningTemplate sourceTemplate = provider.GetTemplate("PnPProvisioningDemo201705_load.xml"); // // Execute actual extraction of the tepmplate // clientContext.Web.ApplyProvisioningTemplate(sourceTemplate); // } //} //[TestMethod] //public void BertTest4() //{ // using (var cc = TestCommon.CreateClientContext("https://bertonline.sharepoint.com/sites/bert1")) // { // var newPage = new Pages.ClientSidePage(cc); // //newPage.AddZone(CanvasZoneTemplate.OneColumn, 1); // var imageWebPart = newPage.InstantiateDefaultWebPart(DefaultClientSideWebParts.Image); // imageWebPart.Properties["imageSourceType"] = 2; // imageWebPart.Properties["siteId"] = "c827cb03-d059-4956-83d0-cd60e02e3b41"; // imageWebPart.Properties["webId"] = "9fafd7c0-e8c3-4a3c-9e87-4232c481ca26"; // imageWebPart.Properties["listId"] = "78d1b1ac-7590-49e7-b812-55f37c018c4b"; // imageWebPart.Properties["uniqueId"] = "3C27A419-66D0-4C36-BF24-BD6147719052"; // imageWebPart.Properties["imgWidth"] = 1002; // imageWebPart.Properties["imgHeight"] = 469; // newPage.AddControl(imageWebPart); // //var t1 = new ClientSideText() // //{ // // Text = "t1" // //}; // //var t2 = new ClientSideText() // //{ // // Text = "t2" // //}; // //newPage.AddControl(t1, 0); // //newPage.AddControl(t2, 1); // //newPage.AddControl(t1, newPage.Zones[0].Sections[0], 2); // //newPage.AddControl(t2, newPage.Zones[0].Sections[0], 1); // newPage.Save("B1.aspx"); // } //} #region Helper methods #endregion } #endif } <file_sep>using Microsoft.SharePoint.Client; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions { internal class MasterPageCatalogToken : TokenDefinition { public MasterPageCatalogToken(Web web) : base(web, "~masterpagecatalog","{masterpagecatalog}") { } public override string GetReplaceValue() { if (this.CacheValue == null) { this.Web.EnsureProperty(w => w.Url); using (ClientContext context = this.Web.Context.Clone(this.Web.Url)) { List catalog; // Check if the current web is a sub-site if (Web.IsSubSite()) { // Master page URL needs to be retrieved from the rootweb var rootWeb = context.Site.RootWeb; catalog = rootWeb.GetCatalog((int)ListTemplateType.MasterPageCatalog); } else { catalog = context.Web.GetCatalog((int)ListTemplateType.MasterPageCatalog); } context.Load(catalog, c => c.RootFolder.ServerRelativeUrl); context.ExecuteQueryRetry(); CacheValue = catalog.RootFolder.ServerRelativeUrl; } } return CacheValue; } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.Resolvers { internal class FoldersFromModelToSchemaTypeResolver : ITypeResolver { public string Name => this.GetType().Name; public bool CustomCollectionResolver => false; public object Resolve(object source, Dictionary<String, IResolver> resolvers = null, Boolean recursive = false) { Array result = null; Object modelSource = source as Model.ListInstance; if (modelSource == null) { modelSource = source as Model.Folder; } if (modelSource != null) { Model.FolderCollection sourceFolders = modelSource.GetPublicInstancePropertyValue("Folders") as Model.FolderCollection; if (sourceFolders != null) { var folderTypeName = $"{PnPSerializationScope.Current?.BaseSchemaNamespace}.Folder, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}"; var folderType = Type.GetType(folderTypeName, true); result = Array.CreateInstance(folderType, sourceFolders.Count); resolvers = new Dictionary<string, IResolver>(); resolvers.Add($"{folderType}.Folder1", new FoldersFromModelToSchemaTypeResolver()); resolvers.Add($"{folderType}.Security", new SecurityFromModelToSchemaTypeResolver()); for (Int32 c = 0; c < sourceFolders.Count; c++) { var targetFolderItem = Activator.CreateInstance(folderType); PnPObjectsMapper.MapProperties(sourceFolders[c], targetFolderItem, resolvers, recursive); result.SetValue(targetFolderItem, c); } } } return (result.Length > 0 ? result : null); } } } <file_sep>using Microsoft.SharePoint.Client; using OfficeDevPnP.Core.Diagnostics; using OfficeDevPnP.Core.Framework.Provisioning.Model; using OfficeDevPnP.Core.Utilities; using System; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers { #if !ONPREMISES internal class ObjectClientSidePageContents: ObjectContentHandlerBase { public override string Name { get { return "Client Side Page Contents"; } } public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { // This handler only extracts contents and adds them to the Files and Pages collection. return parser; } public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { using (var scope = new PnPMonitoredScope(this.Name)) { // Extract the Home Page web.EnsureProperties(w => w.RootFolder.WelcomePage, w => w.ServerRelativeUrl, w => w.Url); var homePageUrl = web.RootFolder.WelcomePage; var homepageName = System.IO.Path.GetFileName(web.RootFolder.WelcomePage); if (string.IsNullOrEmpty(homepageName)) { homepageName = "Home.aspx"; } try { var homePage = web.LoadClientSidePage(homepageName); if (homePage.Sections.Count == 0 && homePage.Controls.Count == 0) { // This is default home page which was not customized...and as such there's no page definition stored in the list item. We don't need to extact this page. scope.LogInfo(CoreResources.Provisioning_ObjectHandlers_ClientSidePageContents_DefaultHomePage); } else { // Create the page var homePageInstance = new ClientSidePage() { PageName = homepageName, PromoteAsNewsArticle = false, Overwrite = false, }; // Add the sections foreach (var section in homePage.Sections) { // Set order var sectionInstance = new CanvasSection() { Order = section.Order, }; // Set section type switch (section.Type) { case Pages.CanvasSectionTemplate.OneColumn: sectionInstance.Type = CanvasSectionType.OneColumn; break; case Pages.CanvasSectionTemplate.TwoColumn: sectionInstance.Type = CanvasSectionType.TwoColumn; break; case Pages.CanvasSectionTemplate.TwoColumnLeft: sectionInstance.Type = CanvasSectionType.TwoColumnLeft; break; case Pages.CanvasSectionTemplate.TwoColumnRight: sectionInstance.Type = CanvasSectionType.TwoColumnRight; break; case Pages.CanvasSectionTemplate.ThreeColumn: sectionInstance.Type = CanvasSectionType.ThreeColumn; break; case Pages.CanvasSectionTemplate.OneColumnFullWidth: sectionInstance.Type = CanvasSectionType.OneColumnFullWidth; break; default: sectionInstance.Type = CanvasSectionType.OneColumn; break; } // Add controls to section foreach (var column in section.Columns) { foreach (var control in column.Controls) { // Create control CanvasControl controlInstance = new CanvasControl() { Column = column.Order, ControlId = control.InstanceId, Order = control.Order, }; // Set control type if (control.Type == typeof(Pages.ClientSideText)) { controlInstance.Type = WebPartType.Text; // Set text content controlInstance.ControlProperties = new System.Collections.Generic.Dictionary<string, string>(1) { { "Text", (control as Pages.ClientSideText).Text } }; } else { // set ControlId to webpart id controlInstance.ControlId = Guid.Parse((control as Pages.ClientSideWebPart).WebPartId); var webPartType = Pages.ClientSidePage.NameToClientSideWebPartEnum((control as Pages.ClientSideWebPart).WebPartId); switch (webPartType) { case Pages.DefaultClientSideWebParts.ContentRollup: controlInstance.Type = WebPartType.ContentRollup; break; case Pages.DefaultClientSideWebParts.BingMap: controlInstance.Type = WebPartType.BingMap; break; case Pages.DefaultClientSideWebParts.ContentEmbed: controlInstance.Type = WebPartType.ContentEmbed; break; case Pages.DefaultClientSideWebParts.DocumentEmbed: controlInstance.Type = WebPartType.DocumentEmbed; break; case Pages.DefaultClientSideWebParts.Image: controlInstance.Type = WebPartType.Image; break; case Pages.DefaultClientSideWebParts.ImageGallery: controlInstance.Type = WebPartType.ImageGallery; break; case Pages.DefaultClientSideWebParts.LinkPreview: controlInstance.Type = WebPartType.LinkPreview; break; case Pages.DefaultClientSideWebParts.NewsFeed: controlInstance.Type = WebPartType.NewsFeed; break; case Pages.DefaultClientSideWebParts.NewsReel: controlInstance.Type = WebPartType.NewsReel; break; case Pages.DefaultClientSideWebParts.PowerBIReportEmbed: controlInstance.Type = WebPartType.PowerBIReportEmbed; break; case Pages.DefaultClientSideWebParts.QuickChart: controlInstance.Type = WebPartType.QuickChart; break; case Pages.DefaultClientSideWebParts.SiteActivity: controlInstance.Type = WebPartType.SiteActivity; break; case Pages.DefaultClientSideWebParts.VideoEmbed: controlInstance.Type = WebPartType.VideoEmbed; break; case Pages.DefaultClientSideWebParts.YammerEmbed: controlInstance.Type = WebPartType.YammerEmbed; break; case Pages.DefaultClientSideWebParts.Events: controlInstance.Type = WebPartType.Events; break; case Pages.DefaultClientSideWebParts.GroupCalendar: controlInstance.Type = WebPartType.GroupCalendar; break; case Pages.DefaultClientSideWebParts.Hero: controlInstance.Type = WebPartType.Hero; break; case Pages.DefaultClientSideWebParts.List: controlInstance.Type = WebPartType.List; break; case Pages.DefaultClientSideWebParts.PageTitle: controlInstance.Type = WebPartType.PageTitle; break; case Pages.DefaultClientSideWebParts.People: controlInstance.Type = WebPartType.People; break; case Pages.DefaultClientSideWebParts.QuickLinks: controlInstance.Type = WebPartType.QuickLinks; break; case Pages.DefaultClientSideWebParts.ThirdParty: controlInstance.Type = WebPartType.Custom; break; default: controlInstance.Type = WebPartType.Custom; break; } // set the control properties controlInstance.JsonControlData = (control as Pages.ClientSideWebPart).PropertiesJson; } // add control to section sectionInstance.Controls.Add(controlInstance); } } homePageInstance.Sections.Add(sectionInstance); } // Renumber the sections...when editing modern homepages you can end up with section with order 0.5 or 0.75...let's ensure we render section as of 1 int sectionOrder = 1; foreach(var sectionInstance in homePageInstance.Sections) { sectionInstance.Order = sectionOrder; sectionOrder++; } // Add the page to the template template.ClientSidePages.Add(homePageInstance); // Set the homepage if (template.WebSettings == null) { template.WebSettings = new WebSettings(); } template.WebSettings.WelcomePage = homePageUrl; } } catch (ArgumentException ex) { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ClientSidePageContents_NoValidPage, ex.Message); } // If a base template is specified then use that one to "cleanup" the generated template model if (creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate); } } return template; } private ProvisioningTemplate CleanupEntities(ProvisioningTemplate template, ProvisioningTemplate baseTemplate) { return template; } public override bool WillProvision(Web web, ProvisioningTemplate template) { if (!_willProvision.HasValue) { _willProvision = false; } return _willProvision.Value; } public override bool WillExtract(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { if (!_willExtract.HasValue) { _willExtract = true; } return _willExtract.Value; } } #endif } <file_sep>using System; using Microsoft.SharePoint.Client; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using OfficeDevPnP.Core.Entities; using System.Linq; namespace OfficeDevPnP.Core.Tests.Authentication { #if !ONPREMISES [TestClass] public class AuthenticationTests { private static string UserName; #region Test initialization [ClassInitialize()] public static void ClassInit(TestContext context) { using (var clientContext = TestCommon.CreateClientContext()) { List<UserEntity> admins = clientContext.Web.GetAdministrators(); UserName = admins[0].LoginName.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries)[2]; } } [ClassCleanup()] public static void ClassCleanup() { using (var clientContext = TestCommon.CreateClientContext()) { DeleteListsImplementation(clientContext); } } #endregion /// <summary> /// Important: the Azure AD you're using here needs to be consented first, otherwise you'll get an access denied. /// Consenting can be done by taking this URL and replacing the client_id parameter value with yours: https://login.microsoftonline.com/common/oauth2/authorize?state=e82ea723-7112-472c-94d4-6e66c0ca52b6&response_type=code+id_token&scope=openid&nonce=c328d2df-43d1-4e4d-a884-7cfb492beadc&client_id=b77caa50-d9ba-4b30-aad6-a40effa2ecd0&redirect_uri=https:%2f%2flocalhost:44304%2fHome%2f&resource=https:%2f%2fgraph.windows.net%2f&prompt=admin_consent&response_mode=form_post /// To debug this catch the returned access token and look http://jwt.calebb.net/ to see if the token contains roles claims /// </summary> [TestMethod] public void AzureADAuthFullControlPermissionTest() { string siteUrl = TestCommon.DevSiteUrl; string spoUserName = AuthenticationTests.UserName; string azureADCertPfxPassword = TestCommon.AzureADCertPfxPassword; string azureADClientId = TestCommon.AzureADClientId; if (String.IsNullOrEmpty(azureADCertPfxPassword) || String.IsNullOrEmpty(azureADClientId) || String.IsNullOrEmpty(spoUserName) || String.IsNullOrEmpty(siteUrl)) { Assert.Inconclusive("Not enough information to execute this test is passed via the app.config file."); } ClientContext cc = null; try { string domain = spoUserName.Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries)[1]; // Instantiate a ClientContext object based on the defined Azure AD application if (new Uri(siteUrl).DnsSafeHost.Contains("spoppe.com")) { cc = new AuthenticationManager().GetAzureADAppOnlyAuthenticatedContext(siteUrl, azureADClientId, domain, @"resources\PnPAzureAppTest.pfx", azureADCertPfxPassword, AzureEnvironment.PPE); } else { cc = new AuthenticationManager().GetAzureADAppOnlyAuthenticatedContext(siteUrl, azureADClientId, domain, @"resources\PnPAzureAppTest.pfx", azureADCertPfxPassword); } // Check if we can read a property from the site cc.Load(cc.Web, w => w.Title); cc.ExecuteQueryRetry(); Console.WriteLine(String.Format("Site title: {0}", cc.Web.Title)); // Verify manage permissions by creating a new list - see https://technet.microsoft.com/en-us/library/cc721640.aspx var list = cc.Web.CreateList(ListTemplateType.DocumentLibrary, "Test_list_" + DateTime.Now.ToFileTime(), false); // Verify full control by enumerating permissions - see https://technet.microsoft.com/en-us/library/cc721640.aspx var roleAssignments = cc.Web.GetAllUniqueRoleAssignments(); // Nothing blew up...so we're good :-) } finally { cc.Dispose(); } } #region Helper methods private static void DeleteListsImplementation(ClientContext cc) { cc.Load(cc.Web.Lists, f => f.Include(t => t.Title)); cc.ExecuteQueryRetry(); foreach (var list in cc.Web.Lists.ToList()) { if (list.Title.StartsWith("Test_list_")) { list.DeleteObject(); } } cc.ExecuteQueryRetry(); } #endregion } #endif } <file_sep>using Microsoft.SharePoint.Client; using System.Text.RegularExpressions; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions { internal class RoleDefinitionIdToken : TokenDefinition { private readonly int _roleDefinitionId = 0; public RoleDefinitionIdToken(Web web, string name, int roleDefinitionId) : base(web, $"{{roledefinitionid:{Regex.Escape(name)}}}") { _roleDefinitionId = roleDefinitionId; } public override string GetReplaceValue() { if (string.IsNullOrEmpty(CacheValue)) { CacheValue = _roleDefinitionId.ToString(); } return CacheValue; } } } <file_sep>using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.Taxonomy; using System; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions { internal class SiteCollectionTermGroupIdToken : TokenDefinition { public SiteCollectionTermGroupIdToken(Web web) : base(web, "~sitecollectiontermgroupid", "{sitecollectiontermgroupid}") { } public override string GetReplaceValue() { if (string.IsNullOrEmpty(CacheValue)) { // The token is requested. Check if the group exists and if not, create it this.Web.EnsureProperty(w => w.Url); using (ClientContext context = this.Web.Context.Clone(this.Web.Url)) { var site = context.Site; var session = TaxonomySession.GetTaxonomySession(context); var termstore = session.GetDefaultSiteCollectionTermStore(); var termGroup = termstore.GetSiteCollectionGroup(site, true); context.Load(termGroup); context.ExecuteQueryRetry(); CacheValue = termGroup.Id.ToString(); } } return CacheValue; } } }
9faa82ba23c8b8fa39946e6722ae9a6a0f1c5b0d
[ "Markdown", "C#" ]
32
C#
justdevelopment/PnP-Sites-Core
b44d575afc2e2eef34ddc38060a56af3b7c7b4b7
9c1bc211cda0c033bed5e1248397caa76d4e8e36
refs/heads/master
<file_sep>from __future__ import unicode_literals from django.apps import AppConfig class CoinfConfig(AppConfig): name = 'CoInf' <file_sep>from django.contrib import admin # Register your models here. from .models import Departaments admin.site.register(Departaments) from .models import Usuaris admin.site.register(Usuaris) from .models import Incidencies admin.site.register(Incidencies) from .models import Compres admin.site.register(Compres) from .models import Material admin.site.register(Material) <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-04-24 10:19 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('CoInf', '0001_initial'), ] operations = [ migrations.AlterField( model_name='usuaris', name='email', field=models.CharField(max_length=30), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-08 10:34 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('CoInf', '0003_auto_20170508_1029'), ] operations = [ migrations.RemoveField( model_name='compres', name='numero', ), ] <file_sep>from __future__ import unicode_literals from django.db import models from datetime import datetime class Departaments(models.Model): """docstring for Missatges""" nom=models.CharField(max_length=20,default='') email=models.CharField(max_length=20,default='') """incidencia=models.CharField(max_length=120)""" """usuaris=models.ManyToManyField(Usuaris)""" def __str__(self): return self.nom class Usuaris(models.Model): """docstring for Login""" nom=models.CharField(max_length=20) cognoms=models.CharField(max_length=20) email=models.CharField(max_length=30) tipus=models.CharField(max_length=20) departament=models.ManyToManyField(Departaments) contrasenya=models.CharField(max_length=64) def __str__(self): return self.nom class Incidencies(models.Model): """docstring for Hashtags""" """identificador=models.IntegerField(default=0)""" """departament=models.ForeignKey(Departaments)""" nom=models.CharField(max_length=50, default='') departament=models.ManyToManyField(Departaments) estat=models.CharField(max_length=20, default='oberta') descripcion=models.TextField(max_length=400,default='') def __str__(self): return self.nom class Material(models.Model): """docstring for Hashtags""" nom=models.CharField(max_length=20) quantitat=models.IntegerField(default=0) """idcompras=models.ForeignKey(Compres,related_name='+')""" """idcompras=models.ManyToManyField(Compres)""" caracteristiques=models.CharField(max_length=120) def __str__(self): return self.nom class Compres(models.Model): """docstring for Hashtags""" """identificador=models.IntegerField(default=0)""" """departament=models.ForeignKey(Departaments)""" departament=models.ManyToManyField(Departaments) material=models.ForeignKey(Material,default='') quantitat=models.IntegerField(default=1) pressupost=models.IntegerField(default=0) def __str__(self): return str(self.numero)<file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-03-16 18:37 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('CoInf', '0003_compres_pressupost'), ] operations = [ migrations.AlterField( model_name='incidencies', name='estat', field=models.CharField(default='oberta', max_length=20), ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-03-15 09:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('CoInf', '0002_compres_quantitat'), ] operations = [ migrations.AddField( model_name='compres', name='pressupost', field=models.IntegerField(default=0), ), ] <file_sep>from django.shortcuts import render from django.http import HttpResponse from django.views.generic.edit import CreateView from django.views.generic.list import ListView from CoInf.models import * def index(request): return HttpResponse("Hello. You're at the CoInf index.") # Create your views here. class CompresCreateView(CreateView): model = Compres # indiquem la plantilla personalitzada i els camps que han d'apareixer al formulari # veureu que la plantilla es molt senzilla ja que fa tot el formulari amb {{form.as_p}} template_name = "compres.html" fields = ['departament','material','quantitat','pressupost'] class IncidenciesCreateView(CreateView): model = Incidencies # indiquem la plantilla personalitzada i els camps que han d'apareixer al formulari # veureu que la plantilla es molt senzilla ja que fa tot el formulari amb {{form.as_p}} template_name = "incidencies.html" fields = ['nom','departament','estat','descripcion'] class CompresListView(ListView): model = Compres template_name = "compresfet.html" # si no posem template_name agafara per defecte karaoke/item_list.html def get_queryset(self): # nomes posem els items que estiguin per cantar return Compres.objects.all() #.filter(fet=False) class IncidenciesListView(ListView): model = Incidencies template_name = "incidenciesfet.html" # si no posem template_name agafara per defecte karaoke/item_list.html def get_queryset(self): # nomes posem els items que estiguin per cantar return Incidencies.objects.all() #.filter(fet=False) class IncidenciesDescListView(ListView): model = Incidencies template_name = "incidenciesdescription.html" # si no posem template_name agafara per defecte karaoke/item_list.html def get_queryset(self): # nomes posem els items que estiguin per cantar return Incidencies.objects.all() def detail(request, question_id): return HttpResponse("You're looking at incidence %s." % incidencies_id) def results(request, question_id): response = "You're looking the information of the incidence %s." return HttpResponse(response % incidencies_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-03-24 10:54 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Compres', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('numero', models.IntegerField(default=0)), ('quantitat', models.IntegerField(default=1)), ('pressupost', models.IntegerField(default=0)), ], ), migrations.CreateModel( name='Departaments', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nom', models.CharField(default='', max_length=20)), ('email', models.CharField(default='', max_length=20)), ], ), migrations.CreateModel( name='Incidencies', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nom', models.CharField(default='', max_length=50)), ('estat', models.CharField(default='oberta', max_length=20)), ('descripcion', models.CharField(default='', max_length=200)), ('departament', models.ManyToManyField(to='CoInf.Departaments')), ], ), migrations.CreateModel( name='Material', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nom', models.CharField(max_length=20)), ('quantitat', models.IntegerField(default=0)), ('caracteristiques', models.CharField(max_length=120)), ], ), migrations.CreateModel( name='Usuaris', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nom', models.CharField(max_length=20)), ('cognoms', models.CharField(max_length=20)), ('email', models.CharField(max_length=20)), ('tipus', models.CharField(max_length=20)), ('contrasenya', models.CharField(max_length=64)), ('departament', models.ManyToManyField(to='CoInf.Departaments')), ], ), migrations.AddField( model_name='compres', name='departament', field=models.ManyToManyField(to='CoInf.Departaments'), ), migrations.AddField( model_name='compres', name='material', field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, to='CoInf.Material'), ), ] <file_sep>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^compres/', views.CompresCreateView.as_view(success_url='/CoInf/fet'), name="compres" ), url(r'^incidencies/', views.IncidenciesCreateView.as_view(success_url="/CoInf/Infet"), name="incidencies" ), url(r'^fet/', views.CompresListView.as_view()), url(r'^Infet/', views.IncidenciesListView.as_view()), url(r'^Indesc/',views.IncidenciesDescListView.as_view()), ]
6aaecd544ecef76bc59af1e6cad515b732fa3f64
[ "Python" ]
10
Python
makunete/DJANGO-Practicas
f8ec30dc293cc3ca05fb514ea1ec8b0597ee30c9
d8d7b68b583691ffb10d80ff1298885cf7705dae
refs/heads/master
<repo_name>Draem/MGM<file_sep>/src/com/minehut/mgm/event/DestroyableBreakEvent.java package com.minehut.mgm.event; import com.minehut.mgm.match.Match; import com.minehut.mgm.module.modules.destroyable.Destroyable; import com.minehut.mgm.module.modules.team.TeamModule; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; /** * Created by luke on 5/31/15. */ public class DestroyableBreakEvent extends Event { private Destroyable destroyable; private Player breaker; public DestroyableBreakEvent(Destroyable destroyable, Player breaker) { this.destroyable = destroyable; this.breaker = breaker; } public Destroyable getDestroyable() { return destroyable; } public Player getBreaker() { return breaker; } private static final HandlerList handlers = new HandlerList(); public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } } <file_sep>/src/com/minehut/mgm/game/coreModules/tab/TabModule.java package com.minehut.mgm.game.coreModules.tab; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolManager; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.wrappers.WrappedChatComponent; import com.minehut.mgm.GameHandler; import com.minehut.mgm.MGM; import com.minehut.mgm.game.coreModules.timer.GameTimer; import com.minehut.mgm.module.Module; import com.minehut.mgm.util.C; import com.minehut.mgm.util.PlayerUtils; import com.minehut.mgm.util.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; /** * Created by luke on 6/8/15. */ public class TabModule implements Module { int taskID; private ProtocolManager protocolManager; public TabModule() { this.protocolManager = ProtocolLibrary.getProtocolManager(); this.taskID = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(MGM.getInstance(), new Runnable() { @Override public void run() { for (Player player : Bukkit.getServer().getOnlinePlayers()) { updatePlayer(player); } } }, 20L, 20L); } public void updatePlayer(Player player) { String timerColor = ""; switch (GameHandler.getHandler().getMatch().getState()) { case STARTING: timerColor = C.gold; break; case PLAYING: timerColor = C.green; break; default : timerColor = C.red; } String header = C.gray + "You are playing on " + C.aqua + "mc.minehut.com"; String footer = C.gray + "Time: " + timerColor + StringUtils.formatTime(GameTimer.getTimeInSeconds()) + C.white + " - " + C.gray + "Map: " + C.white + GameHandler.getHandler().getMatch().getLoadedMap().getName() + C.white + " - " + C.gray + "Gamemode: " + C.white + C.bold + GameHandler.getHandler().getMatch().getGame().getName(); PlayerUtils.setTab(player, header, footer); } private String fixColors(String s) { return ChatColor.translateAlternateColorCodes('&', s); } @Override public void unload() { Bukkit.getServer().getScheduler().cancelTask(this.taskID); } } <file_sep>/src/com/minehut/mgm/game/kit/KitManager.java package com.minehut.mgm.game.kit; import com.minehut.commons.common.chat.C; import com.minehut.commons.common.chat.F; import com.minehut.commons.common.items.EnchantGlow; import com.minehut.commons.common.items.ItemStackFactory; import com.minehut.commons.common.sound.S; import com.minehut.core.Core; import com.minehut.core.player.PlayerInfo; import com.minehut.core.player.Rank; import com.minehut.mgm.GameHandler; import com.minehut.mgm.MGM; import com.minehut.mgm.game.kit.kitPlayer.GamePlayer; import com.minehut.mgm.game.kit.kitPlayer.GamePlayerManager; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by luke on 6/14/15. */ public class KitManager implements Listener { private GamePlayerManager gamePlayerManager; public static String kitMenuName = C.underline + "Kit Menu"; public KitManager() { this.gamePlayerManager = new GamePlayerManager(this); MGM.getInstance().getServer().getPluginManager().registerEvents(this, MGM.getInstance()); } public Kit getDefaultKit() { for (Kit kit : GameHandler.getHandler().getMatch().getGame().getKits()) { if (kit.getPrice() == 0) { return kit; } } return null; } public List<Kit> getFreeKits() { List<Kit> freeKits = new ArrayList<>(); for (Kit kit : this.getKits()) { if (kit.getPrice() == 0) { freeKits.add(kit); } } return freeKits; } @EventHandler public void onInventoryClick(InventoryClickEvent event) { if (event.getInventory().getName().equalsIgnoreCase(kitMenuName)) { event.setCancelled(true); Player player = (Player) event.getWhoClicked(); /* Air Click */ if (event.getCurrentItem().getType() == null) { S.click(player); return; } /* Kit Click */ Kit kit = getKitFromMaterial(event.getCurrentItem().getType()); if (kit != null) { GamePlayer gamePlayer = this.gamePlayerManager.getGamePlayer(player); /* Owns Kit */ if (gamePlayer.hasKit(kit)) { gamePlayer.setSelectedKit(kit); player.closeInventory(); S.playSound(player, Sound.ANVIL_LAND); player.sendMessage(""); F.message(player, "Kits", "You have equipped " + C.red + C.bold + kit.getName()); player.sendMessage(""); return; } /* Doesn't own kit */ else { PlayerInfo playerInfo = Core.getInstance().getPlayerInfo(player); if (playerInfo.hasEnoughForCreditsPurchase(kit.getPrice())) { if(playerInfo.getRank().has(null, kit.getRank(), false)) { gamePlayer.addOwnedKit(kit); gamePlayer.setSelectedKit(kit); player.closeInventory(); F.broadcast("Kits", C.aqua + player.getName() + C.yellow + " has unlocked " + C.green + C.bold + kit.getName()); S.playSound(player, Sound.LEVEL_UP); Bukkit.getServer().getScheduler().runTaskAsynchronously(MGM.getInstance(), new Runnable() { @Override public void run() { Core.getInstance().addCredits(player, -kit.getPrice(), "Purchase " + C.yellow + C.bold + kit.getName()); gamePlayerManager.saveKits(gamePlayer); } }); return; /* Doesn't have required rank */ } else { S.playSound(player, Sound.GLASS); F.message(player, "Kits", "This kit requires rank " + kit.getRank()); return; } } /* Not enough credits */ else { S.playSound(player, Sound.GLASS); F.message(player, "Kits", "You do not have enough credits!"); return; } } } } } public Kit getKitFromMaterial(Material material) { for (Kit kit : this.getKits()) { if (kit.getIcon() == material) { return kit; } } return null; } public void openKitMenu(Player player) { Inventory inventory = Bukkit.getServer().createInventory(null, 27, kitMenuName); int i = 1; for (Kit kit : this.getKits()) { GamePlayer gamePlayer = this.gamePlayerManager.getGamePlayer(player); boolean owned = gamePlayer.hasKit(kit); String ownedMessage; if (owned) { ownedMessage = C.green + C.bold + "OWNED"; } else { ownedMessage = C.red + C.bold + "UNOWNED"; } String rankMessage; if(kit.getRank() != Rank.regular) { rankMessage = C.yellow + "Requires Rank " + kit.getRank().getTag(); } else { rankMessage = ""; } boolean equipped = false; if (owned && gamePlayer.getSelectedKit() == kit) { equipped = true; } String equippedMessage = ""; if (equipped) { equippedMessage = C.green + C.bold + " [SELECTED]"; } ItemStack kitItem = ItemStackFactory.createItem( kit.getIcon(), C.yellow + C.bold + kit.getName() + equippedMessage, Arrays.asList( "", ownedMessage, C.gray + "Price: " + C.yellow + kit.getPrice(), rankMessage)); if (equipped) { EnchantGlow.addGlow(kitItem); } inventory.setItem(i, kitItem); i += 2; if (i == 9) { i += 2; } else if (i == 17) { i += 4; } } player.openInventory(inventory); S.click(player); } public GamePlayerManager getGamePlayerManager() { return gamePlayerManager; } public List<Kit> getKits() { return GameHandler.getGameHandler().getMatch().getGame().getKits(); } } <file_sep>/src/com/minehut/mgm/module/modules/noLeave/NoLeaveModuleBuilder.java package com.minehut.mgm.module.modules.noLeave; import com.minehut.mgm.match.Match; import com.minehut.mgm.module.Module; import com.minehut.mgm.module.ModuleBuilder; import com.minehut.mgm.module.modules.region.Region; import com.minehut.mgm.module.modules.safezone.SafezoneModule; import com.minehut.mgm.module.modules.team.TeamModule; import com.minehut.mgm.util.RegionUtils; import com.minehut.mgm.util.TeamUtils; import org.jdom2.Element; import java.util.ArrayList; /** * Created by luke on 6/8/15. */ public class NoLeaveModuleBuilder implements ModuleBuilder { @Override public ArrayList<Module> load(Match match) { ArrayList<Module> results = new ArrayList<>(); Element filters = match.getDocument().getRootElement().getChild("filters"); if(filters == null) return null; Element node = filters.getChild("noleave"); if(node == null) return null; Region region = RegionUtils.getRegion(node.getAttributeValue("region")); results.add(new NoLeaveModule(region)); return results; } } <file_sep>/src/com/minehut/mgm/util/ParseUtils.java package com.minehut.mgm.util; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.jdom2.Element; import java.util.ArrayList; import java.util.List; /** * Created by luke on 6/1/15. */ public class ParseUtils { public static ItemStack getItem(Element element) { int amount = 1; if (element.getAttributeValue("amount") != null) { try { amount = NumUtils.parseInt(element.getAttributeValue("amount")); } catch (NumberFormatException e) { } } ItemStack itemStack; if (element.getText().contains(":")) itemStack = new ItemStack(Material.matchMaterial(element.getText().split(":")[0]), amount, (short) NumUtils.parseInt(element.getText().split(":")[1])); else itemStack = new ItemStack(Material.matchMaterial(element.getText()), amount); if (element.getAttributeValue("damage") != null) { itemStack.setDurability(Short.parseShort(element.getAttributeValue("damage"))); } if (element.getAttributeValue("data") != null) { itemStack.setDurability(Short.parseShort(element.getAttributeValue("data"))); } try { for (String raw : element.getAttributeValue("enchantment").split(";")) { String[] enchant = raw.split(":"); try { itemStack.addUnsafeEnchantment(Enchantment.getByName(StringUtils.getTechnicalName(enchant[0])), NumUtils.parseInt(enchant[1])); } catch (ArrayIndexOutOfBoundsException e) { itemStack.addUnsafeEnchantment(Enchantment.getByName(StringUtils.getTechnicalName(enchant[0])), 1); } } } catch (NullPointerException e) { } ItemMeta meta = itemStack.getItemMeta(); if (element.getAttributeValue("name") != null) { meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', element.getAttributeValue("name"))); } if (element.getAttributeValue("lore") != null) { ArrayList<String> lore = new ArrayList<>(); for (String raw : element.getAttributeValue("lore").split("\\|")) { String colored = ChatColor.translateAlternateColorCodes('&', raw); lore.add(colored); } meta.setLore(lore); } if (element.getAttributeValue("potions") != null) { String potions = element.getAttributeValue("potions"); if (potions.contains(";")) { for (String potion : potions.split(";")) { String[] parse = potion.split(":"); PotionEffect effect = new PotionEffect(PotionEffectType.getByName(parse[0].toUpperCase().replaceAll(" ", "_")), NumUtils.parseInt(parse[1]), NumUtils.parseInt(parse[2])); ((PotionMeta) meta).addCustomEffect(effect, true); } } else { String[] parse = potions.split(":"); PotionEffect effect = new PotionEffect(PotionEffectType.getByName(parse[0].toUpperCase().replaceAll(" ", "_")), NumUtils.parseInt(parse[1]), NumUtils.parseInt(parse[2])); ((PotionMeta) meta).addCustomEffect(effect, true); } } itemStack.setItemMeta(meta); String attributes = element.getAttributeValue("attributes"); if (attributes != null) { // itemStack = setAttributes(itemStack, attributes); //todo attributes } return itemStack; } public static ChatColor parseChatColor(String string) { for (ChatColor color : ChatColor.values()) { if (color.name().equals(StringUtils.getTechnicalName(string))) return color; } return ChatColor.WHITE; } public static DyeColor parseDyeColor(String string) { for (DyeColor color : DyeColor.values()) { if (color.name().equals(StringUtils.getTechnicalName(string))) return color; } return DyeColor.WHITE; } public static Color getColorFromChatColor(ChatColor color) { if (color == ChatColor.BLUE) { return Color.BLUE; } else if (color == ChatColor.RED) { return Color.RED; } else if (color == ChatColor.AQUA) { return Color.AQUA; } else if (color == ChatColor.GREEN) { return Color.GREEN; } else if (color == ChatColor.DARK_PURPLE) { return Color.PURPLE; } else { return Color.AQUA; } } public static PotionEffect getPotion(Element potion) { PotionEffectType type = PotionEffectType.getByName(StringUtils.getTechnicalName(potion.getText())); int duration = NumUtils.parseInt(potion.getAttributeValue("duration")) == Integer.MAX_VALUE ? NumUtils.parseInt(potion.getAttributeValue("duration")) : NumUtils.parseInt(potion.getAttributeValue("duration")) * 20; int amplifier = 0; boolean ambient = false; if (potion.getAttributeValue("amplifier") != null) { amplifier = NumUtils.parseInt(potion.getAttributeValue("amplifier")) - 1; } if (potion.getAttributeValue("ambient") != null) { ambient = Boolean.parseBoolean(potion.getAttributeValue("ambient").toUpperCase()); } return new PotionEffect(type, duration, amplifier, ambient); } } <file_sep>/src/com/minehut/mgm/game/Game.java package com.minehut.mgm.game; import com.minehut.commons.common.chat.C; import com.minehut.core.Core; import com.minehut.mgm.GameHandler; import com.minehut.mgm.event.TeamWinEvent; import com.minehut.mgm.game.coreModules.chat.ChatModule; import com.minehut.mgm.game.coreModules.damage.CustomDamageEvent; import com.minehut.mgm.game.coreModules.damage.CustomDeathEvent; import com.minehut.mgm.game.coreModules.damage.DamageManagerModuleBuilder; import com.minehut.mgm.game.coreModules.respawn.RespawnModule; import com.minehut.mgm.game.coreModules.spectator.SpectatorModule; import com.minehut.mgm.game.coreModules.tab.TabModule; import com.minehut.mgm.game.coreModules.teamPicker.TeamPickerModule; import com.minehut.mgm.game.coreModules.timer.GameTimer; import com.minehut.mgm.game.coreModules.tntTracker.TntTracker; import com.minehut.mgm.game.kit.Kit; import com.minehut.mgm.module.modules.build.BuildModuleBuilder; import com.minehut.mgm.module.modules.destroyable.DestroyableBuilder; import com.minehut.mgm.module.modules.destroyable.DestroyableBreakManagerModule; import com.minehut.mgm.MGM; import com.minehut.mgm.game.coreModules.peace.PeaceModule; import com.minehut.mgm.game.coreModules.postgame.PostgameModule; import com.minehut.mgm.game.coreModules.pregame.PregameModule; import com.minehut.mgm.game.coreModules.teamManager.TeamManagerModule; import com.minehut.mgm.game.coreModules.wrapper.WrapperModule; import com.minehut.mgm.match.Match; import com.minehut.mgm.module.Module; import com.minehut.mgm.module.ModuleBuilder; import com.minehut.mgm.module.modules.grenade.GrenadeModuleBuilder; import com.minehut.mgm.module.modules.hunger.HungerModuleBuilder; import com.minehut.mgm.module.modules.instakill.InstakillModuleBuilder; import com.minehut.mgm.module.modules.itemdrop.ItemDropModuleBuilder; import com.minehut.mgm.module.modules.noExplode.NoExplodeModuleBuilder; import com.minehut.mgm.module.modules.noLeave.NoLeaveModuleBuilder; import com.minehut.mgm.module.modules.noModify.NoModifyModuleBuilder; import com.minehut.mgm.module.modules.region.RegionBuilder; import com.minehut.mgm.module.modules.safezone.SafezoneModuleBuilder; import com.minehut.mgm.module.modules.score.ScoreModuleBuilder; import com.minehut.mgm.module.modules.spawn.SpawnBuilder; import com.minehut.mgm.module.modules.spawnProtection.SpawnProtectionModuleBuilder; import com.minehut.mgm.module.modules.team.TeamModuleBuilder; import com.minehut.mgm.module.modules.tntProtection.TntProtectionModuleBuilder; import com.minehut.mgm.util.CreditUtils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.player.PlayerJoinEvent; import java.util.ArrayList; import java.util.List; /** * Created by luke on 6/2/15. */ public abstract class Game implements Listener { private Match match; public ArrayList<Module> modules; public ArrayList<ModuleBuilder> builders; public String name; public List<Kit> kits; private int killCredits; private int killXP; public Game(Match match, String name, List<Kit> kits) { this.match = match; this.name = name; this.kits = kits; this.modules = new ArrayList<>(); this.builders = new ArrayList<>(); this.killCredits = 2; this.killXP = 4; } public abstract void unload(); public abstract void postModulesLoaded(); public void addBuilder(ModuleBuilder builder) { this.builders.add(builder); } public void loadModules() { this.defineOptionalModules(); this.defineRequiredModules(); /* Register Module Listeners */ for (Module module : this.modules) { MGM.getInstance().getServer().getPluginManager().registerEvents(module, MGM.getInstance()); } /* Register Kit Listeners */ for (Kit kit : this.kits) { MGM.getInstance().getServer().getPluginManager().registerEvents(kit, MGM.getInstance()); } /* Register Game Listener */ MGM.getInstance().getServer().getPluginManager().registerEvents(this, MGM.getInstance()); this.postModulesLoaded(); } public void defineOptionalModules() { this.addBuilder(new RegionBuilder()); this.addBuilder(new TeamModuleBuilder()); this.addBuilder(new DestroyableBuilder()); this.addBuilder(new DamageManagerModuleBuilder()); this.addBuilder(new HungerModuleBuilder()); this.addBuilder(new SpawnBuilder()); this.addBuilder(new InstakillModuleBuilder()); this.addBuilder(new SafezoneModuleBuilder()); this.addBuilder(new ItemDropModuleBuilder()); this.addBuilder(new BuildModuleBuilder()); this.addBuilder(new GrenadeModuleBuilder()); this.addBuilder(new TntProtectionModuleBuilder()); this.addBuilder(new ScoreModuleBuilder()); this.addBuilder(new NoLeaveModuleBuilder()); this.addBuilder(new NoModifyModuleBuilder()); this.addBuilder(new SpawnProtectionModuleBuilder()); this.addBuilder(new NoExplodeModuleBuilder()); for (ModuleBuilder moduleBuilder : builders) { ArrayList<Module> result = moduleBuilder.load(match); if(result != null) { for (Module module : result) { if (module != null) { this.modules.add(module); } } } } } public void defineRequiredModules() { /* Required Modules */ this.modules.add(new PregameModule()); this.modules.add(new TeamManagerModule()); this.modules.add(new PeaceModule()); this.modules.add(new PostgameModule()); this.modules.add(new WrapperModule()); this.modules.add(new GameTimer()); this.modules.add(new TabModule()); this.modules.add(new RespawnModule()); this.modules.add(new ChatModule()); this.modules.add(new SpectatorModule()); this.modules.add(new TntTracker()); this.modules.add(new TeamPickerModule()); } public <T extends Module> ArrayList<T> getModules(Class<T> clazz) { ArrayList<T> results = new ArrayList<T>(); for (Module module : this.modules) { if (clazz.isInstance(module)) results.add((T) module); } return results; } public <T extends Module> Module getModule(Class<T> clazz) { for (Module module : this.modules) { if (clazz.isInstance(module)) return (T) module; } return null; } public void unregisterModules() { for (Module module : this.modules) { module.unload(); } for (Kit kit : this.kits) { kit.unload(); } this.unload(); } @EventHandler public void onVoidDamage(CustomDamageEvent event) { if(!GameHandler.getHandler().getMatch().isRunning()) return; if (event.getEventCause() == EntityDamageEvent.DamageCause.VOID) { event.setDamage(999); } } @EventHandler public void onGameEnd(TeamWinEvent event) { for (Player player : Bukkit.getServer().getOnlinePlayers()) { if(event.getWinningTeam().getPlayers().contains(player)) { Core.getInstance().addCredits(player, CreditUtils.getCreditsWithBonuses(player, 10), "Win a Game"); GameHandler.getGameHandler().getKitManager().getGamePlayerManager().addXP(player, 10); } else { Core.getInstance().addCredits(player, CreditUtils.getCreditsWithBonuses(player, 6), "Finish a Game"); GameHandler.getGameHandler().getKitManager().getGamePlayerManager().addXP(player, 8); } } } @EventHandler public void onKill(CustomDeathEvent event) { if (event.getDeadPlayer() != null && event.getKillerPlayer() != null) { if (event.getDeadPlayer() != event.getKillerPlayer()) { Core.getInstance().addCredits(event.getKillerPlayer(), CreditUtils.getCreditsWithBonuses(event.getKillerPlayer(), this.killCredits), "Kill an Enemy"); GameHandler.getGameHandler().getKitManager().getGamePlayerManager().addXP(event.getKillerPlayer(), this.killXP); } } } public int getKillCredits() { return killCredits; } public void setKillCredits(int killCredits) { this.killCredits = killCredits; } public int getKillXP() { return killXP; } public void setKillXP(int killXP) { this.killXP = killXP; } public String getName() { return name; } public ArrayList<Module> getModules() { return modules; } public List<Kit> getKits() { return kits; } } <file_sep>/src/com/minehut/mgm/module/modules/region/RegionBuilder.java package com.minehut.mgm.module.modules.region; import com.minehut.mgm.GameHandler; import com.minehut.mgm.match.Match; import com.minehut.mgm.module.Module; import com.minehut.mgm.module.ModuleBuilder; import com.minehut.mgm.util.LocationUtils; import org.bukkit.Location; import org.jdom2.Element; import java.util.ArrayList; import java.util.List; /** * Created by luke on 6/7/15. */ public class RegionBuilder implements ModuleBuilder { @Override public ArrayList<Module> load(Match match) { ArrayList<Module> results = new ArrayList<>(); Element regions = match.getDocument().getRootElement().getChild("regions"); /* Cubes */ List<Element> cubes = regions.getChildren("cube"); for (Element node : cubes) { String name = node.getAttributeValue("name"); Location loc1 = LocationUtils.convert(GameHandler.getGameHandler().getMatchWorld(), node.getAttributeValue("min")); Location loc2 = LocationUtils.convert(GameHandler.getGameHandler().getMatchWorld(), node.getAttributeValue("max")); results.add(new Region(name, loc1, loc2)); } /* Cylinders */ List<Element> cylinders = regions.getChildren("cyl"); for (Element node : cylinders) { String name = node.getAttributeValue("name"); Location center = LocationUtils.convert(GameHandler.getGameHandler().getMatchWorld(), node.getAttributeValue("center")); int radius = Integer.parseInt(node.getAttributeValue("radius")); int height = Integer.parseInt(node.getAttributeValue("height")); results.add(new Region(name, center, radius, height)); } return results; } } <file_sep>/src/com/minehut/mgm/module/modules/hunger/HungerModule.java package com.minehut.mgm.module.modules.hunger; import com.minehut.mgm.module.Module; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.entity.FoodLevelChangeEvent; /** * Created by luke on 6/7/15. */ public class HungerModule implements Module { private final boolean hungerEnabled; public HungerModule(boolean hungerEnabled) { this.hungerEnabled = hungerEnabled; } @Override public void unload() { HandlerList.unregisterAll(this); } @EventHandler public void onHungerDepletion(FoodLevelChangeEvent event) { if (!hungerEnabled) { event.setCancelled(true); } } } <file_sep>/src/com/minehut/mgm/module/modules/instakill/InstakillModuleBuilder.java package com.minehut.mgm.module.modules.instakill; import com.minehut.mgm.match.Match; import com.minehut.mgm.module.Module; import com.minehut.mgm.module.ModuleBuilder; import com.minehut.mgm.module.modules.hunger.HungerModule; import java.util.ArrayList; /** * Created by luke on 6/7/15. */ public class InstakillModuleBuilder implements ModuleBuilder { @Override public ArrayList<Module> load(Match match) { ArrayList<Module> results = new ArrayList<>(); if (match.getDocument().getRootElement().getChild("instakill") != null) { results.add(new InstakillModule()); } return results; } } <file_sep>/src/com/minehut/mgm/util/CreditUtils.java package com.minehut.mgm.util; import com.minehut.core.Core; import com.minehut.core.player.Rank; import org.bukkit.entity.Player; /** * Created by luke on 6/16/15. */ public class CreditUtils { public static long getCreditsWithBonuses(Player player, long amount) { Rank rank = Core.getInstance().getPlayerInfo(player).getRank(); if (rank.has(null, Rank.Champ, false)) { return (long) (3.0 * amount); } else if (rank.has(null, Rank.Legend, false)) { return (long) (2.5 * amount); } else if (rank.has(null, Rank.Super, false)) { return (long) (2.0 * amount); } else if (rank.has(null, Rank.Mega, false)) { return (long) (1.5 * amount); } else { return (long) (1.0 * amount); } } } <file_sep>/src/com/minehut/mgm/module/modules/tntProtection/TntProtectionModule.java package com.minehut.mgm.module.modules.tntProtection; import com.minehut.mgm.MGM; import com.minehut.mgm.module.Module; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.TNTPrimed; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; import java.util.ArrayList; import java.util.List; /** * Created by luke on 6/7/15. */ public class TntProtectionModule implements Module { public TntProtectionModule() { } @Override public void unload() { HandlerList.unregisterAll(this); } @EventHandler public void onEntityExplode(EntityExplodeEvent event) { if (event.getEntity() instanceof TNTPrimed) { List<Block> toRemove = new ArrayList<>(); for (Block block : event.blockList()) { toRemove.add(block); } for (Block block : toRemove) { event.blockList().remove(block); } } } } <file_sep>/src/com/minehut/mgm/game/games/tnt/kits/BlasterKit.java package com.minehut.mgm.game.games.tnt.kits; import com.minehut.commons.common.items.ItemStackFactory; import com.minehut.mgm.game.kit.Kit; import org.bukkit.Material; import org.bukkit.entity.Player; /** * Created by luke on 6/14/15. */ public class BlasterKit extends Kit { public BlasterKit() { super("Blaster", Material.TNT, 0); super.addItem(Material.TNT, 64); super.addItem(Material.STONE_BUTTON, 64); super.addItem(Material.REDSTONE_TORCH_ON, 64); super.addItem(Material.WATER_BUCKET, 64); super.addItem(Material.REDSTONE, 64); super.addItem(Material.REDSTONE, 64); super.addItem(Material.LEVER, 64); super.addItem(ItemStackFactory.createItem(Material.COBBLESTONE, 64)); super.addItem(ItemStackFactory.createItem(Material.COBBLESTONE, 64)); super.addItem(ItemStackFactory.createItem(Material.COBBLESTONE, 64)); super.addItem(ItemStackFactory.createItem(Material.COBBLESTONE, 64)); super.addItem(Material.TNT, 64); super.addItem(Material.TNT, 64); super.addItem(Material.TNT, 64); super.addItem(Material.TNT, 64); } @Override public void onApply(Player player) { } @Override public void extraUnload() { } } <file_sep>/src/com/minehut/mgm/event/TeamWinEvent.java package com.minehut.mgm.event; import com.minehut.mgm.match.Match; import com.minehut.mgm.module.modules.team.TeamModule; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; /** * Created by luke on 5/31/15. */ public class TeamWinEvent extends Event { private Match match; private TeamModule winningTeam; public TeamWinEvent(Match match, TeamModule winningTeam) { this.match = match; this.winningTeam = winningTeam; } public TeamModule getWinningTeam() { return winningTeam; } public Match getMatch() { return match; } private static final HandlerList handlers = new HandlerList(); public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } } <file_sep>/src/com/minehut/mgm/command/CycleCommand.java package com.minehut.mgm.command; import com.minehut.commons.common.chat.F; import com.minehut.core.command.Command; import com.minehut.core.player.Rank; import com.minehut.mgm.MGM; import com.minehut.mgm.util.C; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; /** * Created by luke on 5/31/15. */ public class CycleCommand extends Command { public CycleCommand(JavaPlugin plugin) { super(plugin, "cycle", Rank.Mod); } @Override public boolean call(Player player, ArrayList<String> arrayList) { F.broadcast(C.red + C.bold + player.getName() + C.white + " has cycled maps"); MGM.getInstance().getGameHandler().cycleAndMakeMatch(); return false; } } <file_sep>/src/com/minehut/mgm/module/modules/noExplode/NoExplodeModule.java package com.minehut.mgm.module.modules.noExplode; import com.minehut.commons.common.chat.F; import com.minehut.mgm.game.coreModules.tntTracker.TntTracker; import com.minehut.mgm.module.Module; import com.minehut.mgm.module.modules.region.Region; import com.minehut.mgm.module.modules.team.TeamModule; import com.minehut.mgm.util.TeamUtils; import org.bukkit.Bukkit; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.entity.TNTPrimed; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityExplodeEvent; import java.util.ArrayList; import java.util.List; /** * Created by luke on 6/8/15. */ public class NoExplodeModule implements Module { @Override public void unload() { HandlerList.unregisterAll(this); } public Region region; public TeamModule team; public NoExplodeModule(Region region, TeamModule teamModule) { this.region = region; this.team = teamModule; } @EventHandler public void onEntityExplode(EntityExplodeEvent event) { if (event.getEntity() instanceof TNTPrimed) { if (event.getEntity().hasMetadata("source")) { Player realDamager = Bukkit.getServer().getPlayer(TntTracker.getWhoPlaced(event.getEntity())); if(realDamager != null) { if (TeamUtils.getTeamByPlayer(realDamager) == this.team) { List<Block> toRemove = new ArrayList<>(); for (Block block : event.blockList()) { if (this.region.insideRegion(block.getLocation())) { toRemove.add(block); } } if (toRemove != null) { for (Block block : toRemove) { event.blockList().remove(block); } } } } } } } } <file_sep>/src/com/minehut/mgm/game/games/dtw/kits/tankKit/TankKit.java package com.minehut.mgm.game.games.dtw.kits.tankKit; import com.minehut.commons.common.items.ItemStackFactory; import com.minehut.mgm.game.kit.Kit; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; /** * Created by luke on 6/14/15. */ public class TankKit extends Kit { public TankKit() { super("Tank", Material.DIAMOND_CHESTPLATE, 150); super.addItem(ItemStackFactory.createItem(Material.WOOD_SWORD, Enchantment.KNOCKBACK, 1)); super.addItem(Material.WOOD_AXE); super.addItem(ItemStackFactory.createItem(Material.WOOD, 32)); super.addItem(ItemStackFactory.createItem(Material.LOG, 8)); super.addItem(Material.LEATHER_HELMET); super.addItem(ItemStackFactory.createItem(Material.DIAMOND_CHESTPLATE, Enchantment.PROTECTION_PROJECTILE, 2)); super.addItem(ItemStackFactory.createItem(Material.DIAMOND_LEGGINGS, Enchantment.PROTECTION_PROJECTILE, 2)); super.addItem(Material.LEATHER_BOOTS); } @Override public void onApply(Player player) { player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, Integer.MAX_VALUE, 1)); player.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, Integer.MAX_VALUE, 1)); player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, Integer.MAX_VALUE, 1)); } @Override public void extraUnload() { } } <file_sep>/src/com/minehut/mgm/game/coreModules/chat/ChatModule.java package com.minehut.mgm.game.coreModules.chat; import com.minehut.commons.common.level.Level; import com.minehut.commons.common.player.ChatUtil; import com.minehut.core.Core; import com.minehut.core.player.PlayerInfo; import com.minehut.core.player.Rank; import com.minehut.mgm.GameHandler; import com.minehut.mgm.game.kit.kitPlayer.GamePlayer; import com.minehut.mgm.module.Module; import com.minehut.mgm.module.modules.team.TeamModule; import com.minehut.mgm.util.C; import com.minehut.mgm.util.TeamUtils; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.player.AsyncPlayerChatEvent; /** * Created by luke on 6/8/15. */ public class ChatModule implements Module { public ChatModule() { } @Override public void unload() { HandlerList.unregisterAll(this); } @EventHandler public void onChat(AsyncPlayerChatEvent event) { if(event.isCancelled()) return; Player player = event.getPlayer(); PlayerInfo playerInfo = Core.getInstance().getPlayerInfo(player); GamePlayer gamePlayer = GameHandler.getGameHandler().getKitManager().getGamePlayerManager().getGamePlayer(player); TeamModule team = TeamUtils.getTeamByPlayer(event.getPlayer()); int level = (int) gamePlayer.getLevel(); if (playerInfo.getRank().has(null, Rank.Admin, false)) { event.setFormat( playerInfo.getRank().getTag() + Level.getLevelColor(level) + level + " " + C.white + event.getPlayer().getName() + team.getColor() + " » " + C.green + "%2$s"); } else if (playerInfo.getRank().has(null, Rank.Mod, false)) { event.setFormat( playerInfo.getRank().getTag() + Level.getLevelColor(level) + level + " " + C.white + event.getPlayer().getName() + team.getColor() + " » " + C.yellow + "%2$s"); } else { event.setFormat( playerInfo.getRank().getTag() + Level.getLevelColor(level) + level + " " + C.white + event.getPlayer().getName() + team.getColor() + " » " + C.white + "%2$s"); } } } <file_sep>/src/com/minehut/mgm/command/SetNextCommand.java package com.minehut.mgm.command; import com.minehut.commons.common.chat.F; import com.minehut.core.command.Command; import com.minehut.core.player.Rank; import com.minehut.mgm.GameHandler; import com.minehut.mgm.MGM; import com.minehut.mgm.rotation.LoadedMap; import com.minehut.mgm.util.C; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.Arrays; /** * Created by luke on 5/31/15. */ public class SetNextCommand extends Command { public SetNextCommand(JavaPlugin plugin) { super(plugin, "setnext", Arrays.asList("sn"), Rank.Mod); } @Override public boolean call(Player player, ArrayList<String> args) { if(args == null || args.size() < 1) { player.sendMessage(C.red + "/setnext (map)"); return false; } String mapName = args.get(0); for (String s : args) { if (args.indexOf(s) != 0) { mapName += " " + s; } } LoadedMap nextMap = getMap(mapName); if (nextMap == null) { F.message(player, "Maps", "Couldn't find map " + C.aqua + mapName); } else if (nextMap == GameHandler.getGameHandler().getMatch().getLoadedMap()) { F.message(player, "Maps", "Next map cannot be same as the current map"); } else { setCycleMap(nextMap); F.broadcast("Maps", C.red + C.bold + player.getName() + C.yellow + " set the next map to " + C.aqua + nextMap.getName()); } return false; } private static LoadedMap getMap(String input) { input = input.toLowerCase().replaceAll(" ", ""); LoadedMap result = null; for (LoadedMap loadedMap : GameHandler.getGameHandler().getRotation().getLoaded()) { if (loadedMap.getName().equalsIgnoreCase(input.toLowerCase())) { result = loadedMap; } } if (result == null) { for (LoadedMap loadedMap : GameHandler.getGameHandler().getRotation().getLoaded()) { if (loadedMap.getName().toLowerCase().startsWith(input.toLowerCase())) { result = loadedMap; } } } return result; } private static void setCycleMap(LoadedMap map) { GameHandler.getGameHandler().getCycle().setMap(map); } } <file_sep>/src/com/minehut/mgm/module/modules/score/ScoreModuleBuilder.java package com.minehut.mgm.module.modules.score; import com.minehut.mgm.match.Match; import com.minehut.mgm.module.Module; import com.minehut.mgm.module.ModuleBuilder; import com.minehut.mgm.module.modules.grenade.GrenadeModule; import org.jdom2.Element; import java.util.ArrayList; /** * Created by luke on 6/7/15. */ public class ScoreModuleBuilder implements ModuleBuilder { @Override public ArrayList<Module> load(Match match) { ArrayList<Module> results = new ArrayList<>(); Element element = match.getDocument().getRootElement().getChild("scores"); if (element != null) { int target = Integer.parseInt(element.getAttributeValue("target")); results.add(new ScoreModule(target)); } return results; } } <file_sep>/src/com/minehut/mgm/MGM.java package com.minehut.mgm; import com.minehut.commons.common.chat.F; import com.minehut.commons.common.sound.S; import com.minehut.core.Core; import com.minehut.core.player.PlayerInfo; import com.minehut.core.player.Rank; import com.minehut.mgm.command.*; import com.minehut.mgm.util.C; import com.minehut.status.Status; import com.mongodb.Bytes; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.MongoClient; import org.bukkit.Bukkit; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.java.JavaPlugin; /** * Created by luke on 5/30/15. */ public class MGM extends JavaPlugin implements Listener { private static MGM instance; private GameHandler gameHandler; /* Database */ private MongoClient mongo; private DB db; @Override public void onEnable() { this.instance = this; Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); this.connect(); /* Commands */ this.registerCommands(); try { this.gameHandler = new GameHandler(); } catch (Exception e) { F.log("failed to initiate game handler"); e.printStackTrace(); } /* Status */ Status.getStatus().startStatusUpload("TNT", "dev", "echo", "Destroy the enemy team's wool core."); // Status.getStatus().startStatusUpload("DTW", "warzone", "bravo", "Destroy the enemy team's wool core."); this.getServer().getPluginManager().registerEvents(this, this); } private void connect() { try { this.mongo = new MongoClient("localhost", 27017); this.db = mongo.getDB("minehut"); db.addOption(Bytes.QUERYOPTION_NOTIMEOUT); if (this.db == null) { F.log("Failed to connect to Database."); return; } } catch (Exception e) { F.log("Failed to connect to Database."); } } private void registerCommands() { new CycleCommand(this); new EndCommand(this); new StartCommand(this); new PauseCommand(this); new JoinCommand(this); new LeaveCommand(this); new KitCommand(this); new KitsCommand(this); new SetNextCommand(this); new MapsCommand(this); new LoadMapsCommand(this); } @EventHandler(priority= EventPriority.HIGHEST) public void onSignChange(SignChangeEvent event) { boolean safe = true; for (String line : event.getLines()) { if (line.length()>200) { event.setCancelled(true); safe=false; break; } } if (!safe) { event.setLine(0, ""); event.setLine(1, ""); event.setLine(2, ""); event.setLine(3, ""); for (PlayerInfo playerInfo : Core.getInstance().getPlayersInfos()) { if (playerInfo.getRank().has(null, Rank.Mod, false)) { Player staff = Bukkit.getPlayer(playerInfo.getUuid()); S.playSound(staff, Sound.GHAST_SCREAM); F.message(staff, "Cheat", C.aqua + event.getPlayer().getName() + C.red + " attempted the Sign Exploit Hack"); } } S.playSound(event.getPlayer(), Sound.GHAST_SCREAM); event.getPlayer().sendMessage(""); event.getPlayer().sendMessage(C.green + "such sign, much long, wow, so ban"); event.getPlayer().sendMessage(""); } } public DB getDb() { return db; } public MongoClient getMongo() { return mongo; } public static MGM getInstance() { return instance; } public GameHandler getGameHandler() { return gameHandler; } } <file_sep>/src/com/minehut/mgm/module/modules/hunger/HungerModuleBuilder.java package com.minehut.mgm.module.modules.hunger; import com.minehut.mgm.match.Match; import com.minehut.mgm.module.Module; import com.minehut.mgm.module.ModuleBuilder; import java.util.ArrayList; /** * Created by luke on 6/7/15. */ public class HungerModuleBuilder implements ModuleBuilder { @Override public ArrayList<Module> load(Match match) { ArrayList<Module> results = new ArrayList<>(); try { String data = match.getDocument().getRootElement().getChild("hunger").getChildText("depletion"); if (data.equalsIgnoreCase("off")) { results.add(new HungerModule(false)); } else { results.add(new HungerModule(true)); } } catch (NullPointerException e) { results.add(new HungerModule(true)); } return results; } } <file_sep>/src/com/minehut/mgm/module/modules/score/ScoreModule.java package com.minehut.mgm.module.modules.score; import com.minehut.mgm.GameHandler; import com.minehut.mgm.MGM; import com.minehut.mgm.event.TeamWinEvent; import com.minehut.mgm.game.coreModules.damage.CustomDeathEvent; import com.minehut.mgm.module.Module; import com.minehut.mgm.module.modules.team.TeamModule; import com.minehut.mgm.util.TeamUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.TNTPrimed; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; import java.util.HashMap; /** * Created by luke on 6/7/15. */ public class ScoreModule implements Module { private int targetScore; private HashMap<TeamModule, Integer> scores; public ScoreModule(int targetScore) { this.targetScore = targetScore; this.scores = new HashMap<>(); for (TeamModule teamModule : TeamUtils.getTeams()) { this.scores.put(teamModule, 0); } } @EventHandler(priority = EventPriority.MONITOR) public void onDeath(CustomDeathEvent event) { if (event.getDeadPlayer() != null && event.getKillerPlayer() != null) { /* Suicide */ if(event.getDeadPlayer() == event.getKillerPlayer()) return; TeamModule team = TeamUtils.getTeamByPlayer(event.getKillerPlayer()); this.scores.put(team, this.scores.get(team) + 1); if (this.scores.get(team) >= this.targetScore) { Bukkit.getServer().getPluginManager().callEvent(new TeamWinEvent(GameHandler.getGameHandler().getMatch(), team)); } } } public TeamModule getWinningTeam() { TeamModule winningTeam = null; for (TeamModule team : this.scores.keySet()) { if (team == null) { winningTeam = team; } else { if (this.scores.get(team) > this.scores.get(winningTeam)) { winningTeam = team; } } } return winningTeam; } public int getTargetScore() { return targetScore; } @Override public void unload() { HandlerList.unregisterAll(this); } } <file_sep>/src/com/minehut/mgm/game/kit/Kit.java package com.minehut.mgm.game.kit; import com.minehut.commons.common.items.ArmorType; import com.minehut.core.player.Rank; import com.minehut.mgm.GameHandler; import com.minehut.mgm.module.Module; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.LeatherArmorMeta; import java.util.ArrayList; import java.util.HashMap; /** * Created by luke on 6/12/15. */ public abstract class Kit implements Module { public HashMap<ItemStack, Integer> items; public ArrayList<Ability> abilities; public String name; public Material icon; public long price; public Rank rank; public double maxHealth; public Kit(String name, Material icon, long price) { this.name = name; this.icon = icon; this.price = price; this.maxHealth = 20; this.rank = Rank.regular; this.items = new HashMap<>(); this.abilities = new ArrayList<>(); } public Kit(String name, Material icon, long price, Rank rank) { this.name = name; this.icon = icon; this.price = price; this.maxHealth = 20; this.rank = rank; this.items = new HashMap<>(); this.abilities = new ArrayList<>(); } public void addAbility(Ability ability) { this.addItem(ability.getItemStack()); this.abilities.add(ability); } public void setAbility(Ability ability, int slot) { this.setItem(ability.getItemStack(), slot); this.abilities.add(ability); } public void addItem(ItemStack itemStack) { if (this.items.isEmpty()) { this.items.put(itemStack, 0); return; } for (int i = 0; i < 35; i++) { if (!this.items.containsValue(i)) { this.items.put(itemStack, i); return; } } } public void addItem(Material material) { ItemStack itemStack = new ItemStack(material); this.addItem(itemStack); } public void addItem(Material material, int amount) { ItemStack itemStack = new ItemStack(material); itemStack.setAmount(amount); this.addItem(itemStack); } public void setItem(ItemStack itemStack, int slot) { this.items.put(itemStack, slot); } public void apply(Player player, Color color) { player.getInventory().clear(); player.setMaxHealth(this.maxHealth); player.setHealth(player.getMaxHealth()); for (ItemStack item : this.items.keySet()) { if (ArmorType.getArmorType(item) == ArmorType.helmet) { if (item.getType() == Material.LEATHER_HELMET) { LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta(); meta.setColor(color); item.setItemMeta(meta); } player.getInventory().setHelmet(item); } else if (ArmorType.getArmorType(item) == ArmorType.chestplate) { if (item.getType() == Material.LEATHER_CHESTPLATE) { LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta(); meta.setColor(color); item.setItemMeta(meta); } player.getInventory().setChestplate(item); } else if (ArmorType.getArmorType(item) == ArmorType.leggings) { if (item.getType() == Material.LEATHER_LEGGINGS) { LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta(); meta.setColor(color); item.setItemMeta(meta); } player.getInventory().setLeggings(item); } else if (ArmorType.getArmorType(item) == ArmorType.boots) { if (item.getType() == Material.LEATHER_BOOTS) { LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta(); meta.setColor(color); item.setItemMeta(meta); } player.getInventory().setBoots(item); } else { player.getInventory().setItem(items.get(item), item); } } this.onApply(player); } public abstract void onApply(Player player); @Override public void unload() { HandlerList.unregisterAll(this); if(!this.abilities.isEmpty()) { for (Ability ability : this.abilities) { ability.unload(); } } this.extraUnload(); } public boolean usingThisKit(Player player) { return GameHandler.getGameHandler().getKitManager().getGamePlayerManager().getGamePlayer(player).getSelectedKit() == this; } public abstract void extraUnload(); public HashMap<ItemStack, Integer> getItems() { return items; } public ArrayList<Ability> getAbilities() { return abilities; } public String getName() { return name; } public Material getIcon() { return icon; } public long getPrice() { return price; } public double getMaxHealth() { return maxHealth; } public void setMaxHealth(double maxHealth) { this.maxHealth = maxHealth; } public Rank getRank() { return rank; } } <file_sep>/src/com/minehut/mgm/game/games/dtw/kits/grenadierKit/GrenadierKit.java package com.minehut.mgm.game.games.dtw.kits.grenadierKit; import com.minehut.commons.common.items.ItemStackFactory; import com.minehut.core.player.Rank; import com.minehut.mgm.MGM; import com.minehut.mgm.game.coreModules.damage.CustomDeathEvent; import com.minehut.mgm.game.kit.Kit; import com.minehut.mgm.util.C; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.block.Block; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.TNTPrimed; import org.bukkit.event.EventHandler; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; import java.util.ArrayList; import java.util.List; /** * Created by luke on 6/14/15. */ public class GrenadierKit extends Kit { private ItemStack tnt; public GrenadierKit() { super("Grenadier", Material.TNT, 4000, Rank.Mega); super.addItem(Material.STONE_SWORD); super.addItem(Material.BOW); super.addItem(Material.WOOD_AXE); this.tnt = ItemStackFactory.createItem(Material.TNT, C.red + C.bold + "Grenade"); tnt.setAmount(2); super.addItem(tnt); super.addItem(ItemStackFactory.createItem(Material.WOOD, 32)); super.addItem(ItemStackFactory.createItem(Material.LOG, 8)); super.setItem(ItemStackFactory.createItem(Material.ARROW, 64), 8); super.addItem(Material.LEATHER_HELMET); super.addItem(Material.GOLD_CHESTPLATE); super.addItem(Material.LEATHER_LEGGINGS); super.addItem(Material.LEATHER_BOOTS); } @EventHandler public void onKill(CustomDeathEvent event) { if (event.getKillerPlayer() != null && event.getDeadPlayer() != null) { if (event.getKillerPlayer() != event.getDeadPlayer()) { if (super.usingThisKit(event.getKillerPlayer())) { ItemStack singleTNT = this.tnt = ItemStackFactory.createItem(Material.TNT, C.red + C.bold + "Grenade"); event.getKillerPlayer().getInventory().addItem(singleTNT); event.getKillerPlayer().updateInventory(); event.getKillerPlayer().playSound(event.getKillerPlayer().getEyeLocation(), Sound.ITEM_PICKUP, 10, 10); } } } } @EventHandler public void onEntityExplode(EntityExplodeEvent event) { if (event.getEntity() instanceof TNTPrimed) { List<Block> toRemove = new ArrayList<>(); for (Block block : event.blockList()) { toRemove.add(block); } for (Block block : toRemove) { event.blockList().remove(block); } } } @EventHandler public void onGrenadeThrow(PlayerInteractEvent event) { Player player = event.getPlayer(); if(player.getItemInHand().getType() != null) { if(player.getItemInHand().getType() == Material.TNT) { if(super.usingThisKit(player)) { if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { TNTPrimed tnt = (TNTPrimed) player.getWorld().spawnEntity(player.getLocation(), EntityType.PRIMED_TNT); tnt.setVelocity(player.getLocation().getDirection().multiply(1.15)); tnt.setMetadata("source", new FixedMetadataValue(MGM.getInstance(), player.getUniqueId())); ItemStack updatedItem = player.getItemInHand(); updatedItem.setAmount(player.getItemInHand().getAmount() - 1); player.setItemInHand(updatedItem); player.updateInventory(); player.playSound(player.getEyeLocation(), Sound.ITEM_PICKUP, 10, 1); } } } } } @EventHandler public void onBlockPlace(BlockPlaceEvent event) { if (event.getBlock().getType() != null) { if (event.getBlock().getType() == Material.TNT) { event.setCancelled(true); event.getPlayer().updateInventory(); } } } @Override public void onApply(Player player) { } @Override public void extraUnload() { } } <file_sep>/src/com/minehut/mgm/game/games/dtw/kits/stigmaKit/StigmaKit.java package com.minehut.mgm.game.games.dtw.kits.stigmaKit; import com.minehut.commons.common.chat.F; import com.minehut.commons.common.fireworks.Fireworks; import com.minehut.commons.common.items.ItemStackFactory; import com.minehut.commons.common.multimap.MultiMap; import com.minehut.commons.common.particles.ParticleEffect; import com.minehut.commons.common.sound.S; import com.minehut.mgm.GameHandler; import com.minehut.mgm.MGM; import com.minehut.mgm.game.coreModules.damage.CustomDamageEvent; import com.minehut.mgm.game.kit.Kit; import com.minehut.mgm.game.kit.kitPlayer.GamePlayer; import com.minehut.mgm.util.C; import com.minehut.mgm.util.TeamUtils; import org.bukkit.Bukkit; import org.bukkit.Effect; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.FishHook; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.ProjectileHitEvent; import org.bukkit.event.player.PlayerFishEvent; import java.util.ArrayList; import java.util.UUID; /** * Created by luke on 6/14/15. */ public class StigmaKit extends Kit { // Killer - Hurt - Time private MultiMap<UUID, UUID, Integer> marks; private int runnableID; private static int markTime = 4; public StigmaKit() { super("Stigma", Material.FISHING_ROD, 1000); super.addItem(Material.STONE_SWORD); super.addItem(ItemStackFactory.createItem(Material.FISHING_ROD, C.red + "Target Marker")); super.addItem(Material.BOW); super.addItem(Material.STONE_AXE); super.addItem(ItemStackFactory.createItem(Material.WOOD, 32)); super.addItem(ItemStackFactory.createItem(Material.LOG, 8)); super.setItem(ItemStackFactory.createItem(Material.ARROW, 64), 8); super.addItem(Material.LEATHER_HELMET); super.addItem(Material.LEATHER_CHESTPLATE); super.addItem(Material.LEATHER_BOOTS); this.marks = new MultiMap<>(); this.runnableID = this.countdownMarkTimes(); } // @EventHandler // public void onHookHit(PlayerFishEvent event) { // if(!GameHandler.getHandler().getMatch().isRunning()) return; // // if (event.getCaught() instanceof Player) { // Player hit = (Player) event.getCaught(); // // if (!TeamUtils.onSameTeam(event.getPlayer(), hit)) { // GamePlayer hitGamePlayer = GameHandler.getGameHandler().getKitManager().getGamePlayerManager().getGamePlayer(hit); // hitGamePlayer.setLastDamagedFrom(event.getPlayer().getUniqueId()); // // this.marks.put(event.getPlayer().getUniqueId(), hit.getUniqueId(), markTime); // event.getPlayer().sendMessage(C.red + "Target Marked"); // } // } // } @EventHandler(priority = EventPriority.LOW) public void hookLand(CustomDamageEvent event) { if (event.getHurtPlayer() != null && event.getDamagerPlayer() != null) { if (event.getProjectile() != null) { if (event.getProjectile() instanceof FishHook) { if (!TeamUtils.onSameTeam(event.getDamagerPlayer(), event.getHurtPlayer())) { GamePlayer hitGamePlayer = GameHandler.getGameHandler().getKitManager().getGamePlayerManager().getGamePlayer(event.getHurtPlayer()); hitGamePlayer.setLastDamagedFrom(event.getDamagerPlayer().getUniqueId()); this.marks.put(event.getDamagerPlayer().getUniqueId(), event.getHurtPlayer().getUniqueId(), markTime); ParticleEffect.SPELL_INSTANT.display((float) .2, (float) .2, (float) .2, 0, 20, event.getHurtPlayer().getEyeLocation(), 50); S.playSound(event.getDamagerPlayer(), Sound.ARROW_HIT); event.getProjectile().remove(); } else { event.setCancelled(true); //todo move friendly fire to somewhere else } } } } } @EventHandler public void onDamage(CustomDamageEvent event) { if(event.isCancelled()) return; if (event.getProjectile() != null && event.getProjectile() instanceof FishHook) { return; } if (event.getHurtPlayer() != null && event.getDamagerPlayer() != null) { if (this.marks.containsKey(event.getDamagerPlayer().getUniqueId())) { this.marks.getFirstValue(event.getDamagerPlayer().getUniqueId()).toString().equalsIgnoreCase(event.getHurtPlayer().getUniqueId().toString()); event.setDamage(event.getDamage() + 11); ParticleEffect.LAVA.display((float) .2, (float) .2, (float) .2, 0, 20, event.getHurtPlayer().getEyeLocation(), 50); event.getHurtPlayer().getEyeLocation().getWorld().playSound(event.getHurtPlayer().getEyeLocation(), Sound.GLASS, 10, 1); this.marks.remove(event.getDamagerPlayer().getUniqueId()); } } } private int countdownMarkTimes() { return Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(MGM.getInstance(), new Runnable() { @Override public void run() { if (!marks.isEmpty()) { ArrayList<UUID> remove = new ArrayList<UUID>(); for (UUID uuid : marks.keySet()) { int time = marks.getSecondValue(uuid); if (time <= 0) { remove.add(uuid); } else { marks.put(uuid, marks.getFirstValue(uuid), time - 1); } } } } }, 20L, 20L); } @Override public void onApply(Player player) { } @Override public void extraUnload() { Bukkit.getServer().getScheduler().cancelTask(this.runnableID); } } <file_sep>/src/com/minehut/mgm/module/modules/noModify/NoModifyModuleBuilder.java package com.minehut.mgm.module.modules.noModify; import com.minehut.mgm.match.Match; import com.minehut.mgm.module.Module; import com.minehut.mgm.module.ModuleBuilder; import com.minehut.mgm.module.modules.region.Region; import com.minehut.mgm.module.modules.safezone.SafezoneModule; import com.minehut.mgm.module.modules.team.TeamModule; import com.minehut.mgm.util.RegionUtils; import com.minehut.mgm.util.TeamUtils; import org.jdom2.Document; import org.jdom2.Element; import java.util.ArrayList; import java.util.List; /** * Created by luke on 6/8/15. */ public class NoModifyModuleBuilder implements ModuleBuilder { @Override public ArrayList<Module> load(Match match) { ArrayList<Module> results = new ArrayList<>(); Document doc = match.getDocument(); Element filters = doc.getRootElement().getChild("filters"); if(filters == null) return null; List<Element> elements = filters.getChildren(); if(elements == null) return null; for (Element node : elements) { if(!node.getName().equalsIgnoreCase("nomodify")) continue; Region region = RegionUtils.getRegion(node.getAttributeValue("region")); results.add(new NoModifyModule(region)); } return results; } } <file_sep>/src/com/minehut/mgm/command/JoinCommand.java package com.minehut.mgm.command; import com.minehut.commons.common.chat.F; import com.minehut.core.command.Command; import com.minehut.core.player.Rank; import com.minehut.mgm.GameHandler; import com.minehut.mgm.module.modules.team.TeamModule; import com.minehut.mgm.util.PlayerUtils; import com.minehut.mgm.util.TeamUtils; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; /** * Created by luke on 6/8/15. */ public class JoinCommand extends Command { public JoinCommand(JavaPlugin plugin) { super(plugin, "join", Rank.regular); } @Override public boolean call(Player player, ArrayList<String> arrayList) { if (!TeamUtils.getSpectators().contains(player)) { F.warning(player, "You are already on a team"); return true; } TeamModule team = TeamUtils.getTeamWithFewestPlayers(); team.add(player); return false; } } <file_sep>/src/com/minehut/mgm/module/modules/grenade/GrenadeModule.java package com.minehut.mgm.module.modules.grenade; import com.minehut.commons.common.sound.S; import com.minehut.mgm.MGM; import com.minehut.mgm.module.Module; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.TNTPrimed; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; /** * Created by luke on 6/7/15. */ public class GrenadeModule implements Module { public GrenadeModule() { } @Override public void unload() { HandlerList.unregisterAll(this); } @EventHandler public void onGrenadeThrow(PlayerInteractEvent event) { Player player = event.getPlayer(); if(player.getItemInHand().getType() != null) { if(player.getItemInHand().getType() == Material.TNT) { if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { TNTPrimed tnt = (TNTPrimed) player.getWorld().spawnEntity(player.getLocation(), EntityType.PRIMED_TNT); tnt.setVelocity(player.getLocation().getDirection().multiply(1.15)); tnt.setMetadata("source", new FixedMetadataValue(MGM.getInstance(), player.getUniqueId())); ItemStack updatedItem = player.getItemInHand(); updatedItem.setAmount(player.getItemInHand().getAmount() - 1); player.setItemInHand(updatedItem); player.updateInventory(); player.playSound(player.getEyeLocation(), Sound.ITEM_PICKUP, 10, 1); } } } } @EventHandler public void onBlockPlace(BlockPlaceEvent event) { if (event.getBlock().getType() != null) { if (event.getBlock().getType() == Material.TNT) { event.setCancelled(true); event.getPlayer().updateInventory(); } } } } <file_sep>/src/com/minehut/mgm/util/RegionUtils.java package com.minehut.mgm.util; import com.minehut.mgm.GameHandler; import com.minehut.mgm.module.modules.region.Region; /** * Created by luke on 6/7/15. */ public class RegionUtils { public static Region getRegion(String name) { for (Region region : GameHandler.getHandler().getMatch().getGame().getModules(Region.class)) { if (region.getName().equalsIgnoreCase(name)) { return region; } } return null; } } <file_sep>/src/com/minehut/mgm/game/games/dtw/kits/infiltratorKit/InfiltratorKit.java package com.minehut.mgm.game.games.dtw.kits.infiltratorKit; import com.minehut.commons.common.items.ItemStackFactory; import com.minehut.mgm.game.kit.Kit; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; /** * Created by luke on 6/14/15. */ public class InfiltratorKit extends Kit { public InfiltratorKit() { super("Infiltrator", Material.LADDER, 450); super.addItem(ItemStackFactory.createItem(Material.GOLD_AXE, Enchantment.DIG_SPEED, 2)); super.addItem(Material.BOW); super.addItem(ItemStackFactory.createItem(Material.LADDER, 32)); super.addItem(ItemStackFactory.createItem(Material.WOOD, 32)); super.addItem(ItemStackFactory.createItem(Material.LOG, 8)); super.setItem(ItemStackFactory.createItem(Material.ARROW, 64), 8); super.addItem(Material.LEATHER_HELMET); super.addItem(Material.LEATHER_LEGGINGS); super.addItem(ItemStackFactory.createItem(Material.CHAINMAIL_BOOTS, Enchantment.PROTECTION_FALL, 2)); } @Override public void onApply(Player player) { player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 2)); } @Override public void extraUnload() { } } <file_sep>/src/com/minehut/mgm/module/modules/destroyable/DestroyableBreakManagerModule.java package com.minehut.mgm.module.modules.destroyable; import com.minehut.commons.common.chat.C; import com.minehut.commons.common.chat.F; import com.minehut.commons.common.sound.S; import com.minehut.mgm.GameHandler; import com.minehut.mgm.event.DestroyableBreakEvent; import com.minehut.mgm.module.Module; import com.minehut.mgm.util.DestroyableUtils; import com.minehut.mgm.util.TeamUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; import org.bukkit.event.block.BlockBreakEvent; /** * Created by luke on 6/7/15. */ public class DestroyableBreakManagerModule implements Module { @EventHandler(priority = EventPriority.HIGH) public void onDestroyableBreak(BlockBreakEvent event) { if(event.isCancelled()) return; if(!GameHandler.getGameHandler().getMatch().isRunning()) return; for (Destroyable destroyable : DestroyableUtils.getAllDestroyables()) { Destroyable.DestroyableBreakAttempt attempt = destroyable.getBreakAttempt(event.getPlayer(), event.getBlock()); if (attempt == Destroyable.DestroyableBreakAttempt.SUCCESSFUL) { S.playSound(Sound.FIREWORK_TWINKLE); F.broadcast(TeamUtils.getTeamByPlayer(event.getPlayer()).getColor() + C.bold + event.getPlayer().getDisplayName() + C.gray + " destroyed a " + destroyable.getTeam().getDisplayName() + C.aqua + " " + destroyable.getName()); Bukkit.getServer().getPluginManager().callEvent(new DestroyableBreakEvent(destroyable, event.getPlayer())); event.getBlock().setType(Material.AIR); } else if (attempt == Destroyable.DestroyableBreakAttempt.OWNS) { F.noPerm(event.getPlayer(), "Don't break your team's objective maggot"); event.setCancelled(true); } } } @Override public void unload() { HandlerList.unregisterAll(this); } } <file_sep>/src/com/minehut/mgm/game/games/dtw/kits/warriorKit/WarriorKit.java package com.minehut.mgm.game.games.dtw.kits.warriorKit; import com.minehut.commons.common.items.ItemStackFactory; import com.minehut.mgm.game.kit.Kit; import org.bukkit.Material; import org.bukkit.entity.Player; /** * Created by luke on 6/14/15. */ public class WarriorKit extends Kit { public WarriorKit() { super("Warrior", Material.STONE_SWORD, 0); super.addItem(Material.STONE_SWORD); super.addItem(Material.BOW); super.addItem(Material.STONE_AXE); super.addItem(ItemStackFactory.createItem(Material.WOOD, 32)); super.addItem(ItemStackFactory.createItem(Material.LOG, 8)); super.setItem(ItemStackFactory.createItem(Material.ARROW, 32), 8); super.addItem(Material.LEATHER_HELMET); super.addItem(Material.LEATHER_CHESTPLATE); super.addItem(Material.LEATHER_LEGGINGS); super.addItem(Material.LEATHER_BOOTS); } @Override public void onApply(Player player) { } @Override public void extraUnload() { } } <file_sep>/src/com/minehut/mgm/game/coreModules/spectator/SpectatorModule.java package com.minehut.mgm.game.coreModules.spectator; import com.minehut.mgm.GameHandler; import com.minehut.mgm.game.coreModules.damage.CustomDamageEvent; import com.minehut.mgm.module.Module; import com.minehut.mgm.util.TeamUtils; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.inventory.InventoryDragEvent; import org.bukkit.event.inventory.InventoryMoveItemEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerPickupItemEvent; /** * Created by luke on 6/8/15. */ public class SpectatorModule implements Module { public SpectatorModule() { } @EventHandler (priority = EventPriority.LOW) public void onDamage(CustomDamageEvent event) { if (event.getDamagerPlayer() != null) { if (TeamUtils.isSpectator(event.getDamagerPlayer())) { event.setCancelled(true); } } if (event.getHurtPlayer() != null) { if (TeamUtils.isSpectator(event.getHurtPlayer())) { event.setCancelled(true); } } else if(!GameHandler.getGameHandler().getMatch().isRunning()) { event.setCancelled(true); } } @EventHandler public void onBlockPlace(BlockPlaceEvent event) { if(!GameHandler.getGameHandler().getMatch().isRunning()) { event.setCancelled(true); } else if (TeamUtils.isSpectator(event.getPlayer())) { event.setCancelled(true); } } @EventHandler public void onBlockBreak(BlockBreakEvent event) { if(!GameHandler.getGameHandler().getMatch().isRunning()) { event.setCancelled(true); } if (TeamUtils.isSpectator(event.getPlayer())) { event.setCancelled(true); } } @EventHandler public void onDropItem(PlayerDropItemEvent event) { if(!GameHandler.getGameHandler().getMatch().isRunning()) { event.setCancelled(true); } if (TeamUtils.isSpectator(event.getPlayer())) { event.setCancelled(true); } } @EventHandler public void onInvMove(InventoryMoveItemEvent event) { if (TeamUtils.isSpectator((Player) event.getDestination().getHolder())) { event.setCancelled(true); } else if(!GameHandler.getGameHandler().getMatch().isRunning()) { event.setCancelled(true); } } @EventHandler public void onInvMove(InventoryDragEvent event) { if (TeamUtils.isSpectator((Player) event.getWhoClicked())) { event.setCancelled(true); } else if(!GameHandler.getGameHandler().getMatch().isRunning()) { event.setCancelled(true); } } @EventHandler public void onItemPickup(PlayerPickupItemEvent event) { if (TeamUtils.isSpectator(event.getPlayer())) { event.setCancelled(true); } else if(!GameHandler.getGameHandler().getMatch().isRunning()) { event.setCancelled(true); } } @Override public void unload() { HandlerList.unregisterAll(this); } }
dd34843545798dba644a4b0a4c3d08fe785bd5a0
[ "Java" ]
33
Java
Draem/MGM
d4a02aa58b80e8d97620b952272d22c53ec8e6f3
b485c8398896b5a8c871372ba09c5242b3b77d17
refs/heads/master
<file_sep>**Note**: Right now this does not install cmd tools so you will have to run that from the app menu on your own. ## Required Puppet Modules * `boxen` ## Development Write code. Run `script/cibuild` to test it. Check the `script` directory for other useful tools. <file_sep>require 'spec_helper' #describe 'sqldeveloper' do # it do # should contain_package('SQLdeveloper').with({ # :source => 'http://192.168.21.151/sqldeveloper-4.1.1.19.59-macosx.app.zip', # :provider => 'compressed_app' # }) # end #end
40177c24ddadd8141e34ddcd85f1f450189bb33c
[ "Markdown", "Ruby" ]
2
Markdown
elle24/puppet-sqldeveloper
3b33fbfff15f297364d3d466b68d96280474ec7f
29ec7c40d0fe77feb213bab3638158c6771a03c7
refs/heads/master
<file_sep>import aiofiles import asyncio import logging import os def _synchronized(func): async def wrapper(self, *args, **kwargs): await self._lock.acquire() result = await func(self, *args, **kwargs) self._lock.release() return result return wrapper class StorageError(Exception): pass class FileRing: def __init__(self, path, size, rotate_delay_seconds=0): if not isinstance(size, int) and size > 0: raise ValueError('Invalid size {}'.format(size)) logging.info('Initializing ring {} with size {}'.format(path, size)) self._path = path self._data_path = os.path.join(path, 'data') self._current_path = os.path.join(path, 'current') self._size = size self._index = None self._f = None self._lock = asyncio.Lock() self._rotate_delay_seconds = rotate_delay_seconds self._initialize() def _initialize(self): os.makedirs(self._path, exist_ok=True) self._initialize_ring() self._initialize_current_index() def _initialize_ring(self): os.makedirs(self._data_path, exist_ok=True) for i in range(self._size): open(os.path.join(self._data_path, str(i)), 'a') def _initialize_current_index(self): if os.path.lexists(self._current_path): index = self._get_index_from_link(os.readlink(self._current_path)) self._set_index(index) else: self._set_index(0) def _get_index_from_link(self, link): datadir, current_file = os.path.split(link) if not datadir == 'data': raise StorageError('Invalid current link {}'.format(link)) try: index = int(current_file) except ValueError: raise StorageError('Invalid current link {}'.format(link)) if index not in range(self._size): raise StorageError('Invalid current link {} to file outside ring of size {}'.format(link, self._size)) return index def _set_index(self, index): self._index = index if os.path.lexists(self._current_path): os.unlink(self._current_path) os.symlink(os.path.join('data', str(index)), self._current_path) @property def index(self): return self._index async def _open(self): self._f = await aiofiles.open(os.path.join(self._data_path, str(self._index)), 'a') @_synchronized async def start(self): await self._open() @_synchronized async def stop(self): await self._f.close() @_synchronized async def write(self, value): await self._f.write(value) @_synchronized async def flush(self): await self._f.flush() @_synchronized async def rotate(self): new_index = (self._index + 1) % self._size logging.info('Rotating ring: {} -> {}'.format(self._index, new_index)) os.unlink(os.path.join(self._data_path, str(new_index))) await asyncio.sleep(self._rotate_delay_seconds) await self._f.close() self._set_index(new_index) await self._open() <file_sep>from threading import Thread import datetime import logging import time import pytest from freezegun import freeze_time from logrotor.runner import Runner UDP_PORT = 1024 @pytest.fixture def runner(tmpdir): config = { 'flush_every_seconds': 5, 'rotate_every_seconds': 3600, 'storage': { 'path': str(tmpdir), 'size': 5, }, 'endpoints': [{ 'type': 'UdpEndpoint', 'port': UDP_PORT, }], } return Runner(config) @pytest.fixture def runner_thread(runner): return Thread(target=runner.run) def test_runner(send_udp, tmpdir, runner, runner_thread): logging.basicConfig(level=logging.DEBUG) runner_thread.start() time.sleep(1) send_udp('Message'.encode()) time.sleep(1) runner.stop() runner_thread.join(timeout=1) assert tmpdir.join('data', '0').read() == '127.0.0.1 Message\n' def test_runner_rotates_at_given_interval(send_udp, tmpdir, runner, runner_thread): with freeze_time('2017-07-28') as frozen_time: runner_thread.start() time.sleep(1) send_udp('Alice'.encode()) time.sleep(1) frozen_time.tick(delta=datetime.timedelta(seconds=3600)) time.sleep(1) send_udp('Bob'.encode()) time.sleep(1) runner.stop() runner_thread.join(timeout=1) assert tmpdir.join('data', '0').read() == '127.0.0.1 Alice\n' assert tmpdir.join('data', '1').read() == '127.0.0.1 Bob\n' def test_runner_does_not_schedule_rotation_in_0_seconds(tmpdir, runner, runner_thread): with freeze_time('2017-07-28 01:59:59,999') as frozen_time: runner_thread.start() time.sleep(1) runner.stop() runner_thread.join(timeout=1) assert tmpdir.join('current').readlink() == 'data/0' def test_runner_flushes_regularly(tmpdir, runner, runner_thread, send_udp): with freeze_time('2017-07-28') as frozen_time: runner_thread.start() time.sleep(1) send_udp('Alice'.encode()) time.sleep(5) file_content = tmpdir.join('data', '0').read() runner.stop() runner_thread.join(timeout=1) assert file_content == '127.0.0.1 Alice\n' <file_sep>[pytest] addopts = --pep8 pep8maxlinelength = 119 <file_sep>import asyncio import logging from threading import Thread import time from datetime import datetime from logrotor.endpoint import create_endpoint from logrotor.storage import FileRing class Runner: def __init__(self, config): self._loop = asyncio.get_event_loop() self._queue = asyncio.Queue() self._endpoints = self._configure_endpoints(config) self._file_ring = self._configure_file_ring(config) self._consumer_task = None self._rotator_task = None self._running = False self._rotate_interval = config['rotate_every_seconds'] self._flush_interval = config['flush_every_seconds'] def _configure_file_ring(self, config): return FileRing(**config['storage']) def _configure_endpoints(self, config): return [create_endpoint(self._queue, e) for e in config['endpoints']] def run(self): self._running = True logging.info('Starting file ring') start_tasks = [] start_tasks.append(self._loop.create_task(self._file_ring.start())) for endpoint in self._endpoints: logging.info('Starting {}'.format(endpoint.__class__.__name__)) start_tasks.append(self._loop.create_task(endpoint.start(self._loop))) self._loop.run_until_complete(asyncio.gather(*start_tasks)) logging.info('Startup finished') logging.info('Creating queue consumer') self._consumer_task = self._loop.create_task(self._consumer()) logging.info('Creating rotator') self._rotator_task = self._loop.create_task(self._rotator()) logging.info('Creating flusher') self._flusher_task = self._loop.create_task(self._flusher()) logging.info('Running forever') self._loop.run_until_complete(asyncio.gather(self._consumer_task, self._rotator_task, self._flusher_task)) stop_tasks = [] for endpoint in self._endpoints: logging.info('Stopping {}'.format(endpoint.__class__.__name__)) stop_tasks.append(self._loop.create_task(endpoint.stop())) logging.info('Stopping file ring') stop_tasks.append(self._loop.create_task(self._file_ring.stop())) self._loop.run_until_complete(asyncio.gather(*stop_tasks)) logging.info('Shutdown finished') def stop(self): logging.info('Stopping runner') self._running = False @property def is_running(self): return self._running async def _consumer(self): while self._running: if self._queue.empty(): await asyncio.sleep(0.1) else: msg = self._queue.get_nowait() await self._file_ring.write(msg + '\n') async def _rotator(self): while self._running: now = time.time() delta = self._rotate_interval - (now % self._rotate_interval) next_rotation = now + delta logging.info('Scheduling next rotation at {} (in {} seconds)' .format(datetime.fromtimestamp(next_rotation).isoformat(), delta)) while self._running: await asyncio.sleep(1) if time.time() >= next_rotation: await self._file_ring.rotate() break async def _flusher(self): while self._running: for _ in range(int(self._flush_interval)): if not self._running: break await asyncio.sleep(1) logging.debug('Flushing') await self._file_ring.flush() <file_sep>import pytest import asyncio import time from logrotor.storage import FileRing, StorageError ROTATE_DELAY_SECONDS = 2 @pytest.fixture def file_ring(tmpdir): return FileRing(str(tmpdir), 5) @pytest.fixture def file_ring_with_rotate_delay(tmpdir): return FileRing(str(tmpdir), 5, rotate_delay_seconds=ROTATE_DELAY_SECONDS) @pytest.fixture def file_ring_with_existing_index(tmpdir): tmpdir.join('data').mkdir() for i in range(5): tmpdir.join('data', str(i)).write_text('log-' + str(i), 'utf8') tmpdir.join('current').mksymlinkto(tmpdir.join('data', '3'), absolute=False) return FileRing(str(tmpdir), 5) def test_initialize_empty_store(tmpdir, file_ring): files = sorted(f.basename for f in tmpdir.join('data').listdir()) assert files == ['0', '1', '2', '3', '4'] assert tmpdir.join('current').readlink() == 'data/0' assert file_ring.index == 0 def test_open_existing_index(tmpdir, file_ring_with_existing_index): files = sorted(f.basename for f in tmpdir.join('data').listdir()) assert files == ['0', '1', '2', '3', '4'] assert tmpdir.join('current').readlink() == 'data/3' for f in files: assert tmpdir.join('data', f).read() == 'log-' + f assert file_ring_with_existing_index.index == 3 @pytest.mark.parametrize('link', [ '5', '-1', 'abc', ]) def test_open_with_invalid_current_path(tmpdir, link): tmpdir.join('current').mksymlinkto(tmpdir.join('data', link), absolute=False) with pytest.raises(StorageError): FileRing(str(tmpdir), 5) @pytest.mark.asyncio async def test_write(tmpdir, file_ring): msg = 'Test message\n' await file_ring.start() await file_ring.write(msg) await file_ring.stop() assert tmpdir.join('data', '0').read() == msg @pytest.mark.asyncio async def test_write_appends_to_existing_index(tmpdir, file_ring_with_existing_index): await file_ring_with_existing_index.start() msg = 'Test message\n' await file_ring_with_existing_index.write(msg) await file_ring_with_existing_index.flush() assert tmpdir.join('data', '3').read() == 'log-3' + msg @pytest.mark.asyncio async def test_rotate(tmpdir, file_ring): await file_ring.start() await file_ring.write('Alice') await file_ring.rotate() await file_ring.write('Bob') await file_ring.flush() assert file_ring.index == 1 assert tmpdir.join('data', '0').read() == 'Alice' assert tmpdir.join('data', '1').read() == 'Bob' @pytest.mark.asyncio async def test_rotating_clears_file_rotated_to(tmpdir, event_loop, file_ring_with_existing_index): await file_ring_with_existing_index.start() await file_ring_with_existing_index.write('Alice') await file_ring_with_existing_index.rotate() await file_ring_with_existing_index.write('Bob') await file_ring_with_existing_index.flush() assert file_ring_with_existing_index.index == 4 assert tmpdir.join('data', '3').read() == 'log-3Alice' assert tmpdir.join('data', '4').read() == 'Bob' async def measure_file_absence(path): while path.exists(): await asyncio.sleep(0.01) start = time.time() while not path.exists(): await asyncio.sleep(0.01) return time.time() - start @pytest.mark.asyncio async def test_rotate_delays_creation_of_new_file(tmpdir, event_loop, file_ring_with_rotate_delay): await file_ring_with_rotate_delay.start() measurement = event_loop.create_task(measure_file_absence(tmpdir.join('data', '1'))) await file_ring_with_rotate_delay.rotate() delay = await asyncio.wait_for(measurement, timeout=5) assert delay == pytest.approx(ROTATE_DELAY_SECONDS, 0.1) @pytest.mark.asyncio async def test_parallel_execution(tmpdir, event_loop, file_ring): await file_ring.start() tasks = [ event_loop.create_task(file_ring.write('A\n')), event_loop.create_task(file_ring.write('B\n')), event_loop.create_task(file_ring.rotate()), event_loop.create_task(file_ring.write('C\n')), event_loop.create_task(file_ring.write('D\n')), ] await asyncio.gather(*tasks) await file_ring.stop() assert tmpdir.join('data', '0').readlines() == ['A\n', 'B\n'] assert tmpdir.join('data', '1').readlines() == ['C\n', 'D\n'] <file_sep>import asyncio import logging class UdpEndpoint: def __init__(self, out, bind='0.0.0.0', port=None, **kwargs): if port is None or not isinstance(port, int): raise ValueError('No valid port configured for {}'.format(self.__class__.__name__)) self._address = (bind, port) self._protocol = self._get_protocol(out, **kwargs) def _get_protocol(self, out, **kwargs): return UdpProtocol(out, **kwargs) async def start(self, loop): logging.debug('Starting udp endpoint for protocol {} on {}' .format(self._protocol.__class__.__name__, self._address)) self._transport, _ = await loop.create_datagram_endpoint(lambda: self._protocol, local_addr=self._address) async def stop(self): logging.debug('Closing udp endpoint on {}'.format(self._address)) self._transport.close() class UdpProtocol(asyncio.DatagramProtocol): def __init__(self, out, format='{host} {message}', splitlines=False): super().__init__() self._format = format self._out = out if splitlines: self._filter = lambda data: data.splitlines() else: self._filter = lambda data: [data] def datagram_received(self, data, source): host, port = source for message in self._filter(data.decode()): self._out.put_nowait(self._format.format(host=host, port=port, message=message)) <file_sep>import argparse import logging import signal import time import yaml from logrotor.runner import Runner def logrotor(): parser = argparse.ArgumentParser(description='logrotor - a lightweight log store with time-based rotation') parser.add_argument('-c', '--config', help='config file', required=True) parser.add_argument('-v', '--verbose', help='increase verbosity', action='store_true') args = parser.parse_args() loglevel = logging.DEBUG if args.verbose else logging.INFO logging.basicConfig(level=loglevel, format='%(asctime)s %(levelname)-8s %(message)s') with open(args.config) as f: config = yaml.load(f) runner = Runner(config) def signal_handler(_signal, _stack_frame): logging.info('Received {}'.format(signal.Signals(_signal).name)) runner.stop() signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) runner.run() <file_sep>#!/bin/bash docker run --volume $(pwd):/src --workdir /src python:alpine3.6 python /src/setup.py bdist_wheel --dist-dir /src/dist <file_sep>from datetime import datetime from enum import Enum import re import socket class Facility(Enum): KERN, USER, MAIL, DAEMON, AUTH, SYSLOG, LPR, NEWS, UUCP, CRON, AUTHPRIV, FTP = range(12) LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7 = range(16, 24) class Level(Enum): EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG = range(8) TAG_REGEX = re.compile(r'([a-zA-Z0-9]+)(?:\[(\d+)\]|)[:]?[\s]?') class Message: def __init__(self, level, facility, timestamp, hostname, tag, pid, message): self.level = level self.facility = facility self.timestamp = timestamp self.hostname = hostname self.tag = tag self.pid = pid self.message = message def message_to_bytes(message): pri = message.level.value + message.facility.value * 8 tag_with_pid = message.tag if message.pid is not None: tag_with_pid += '[{}]'.format(message.pid) return '<{pri}>{timestamp:%b %e %H:%M:%S} {hostname} {tag_with_pid}: {message}'.format( pri=pri, timestamp=message.timestamp, hostname=message.hostname, tag_with_pid=tag_with_pid, message=message.message).encode() def bytes_to_message(data): data = data.decode() if not data.startswith('<'): raise ValueError('Invalid syslog message {}'.format(data)) pri_end = data.index('>') pri = int(data[1:pri_end]) facility = Facility(int(pri / 8)) level = Level(int(pri % 8)) timestamp_end = pri_end + 16 msg_timestamp = data[pri_end+1:timestamp_end] timestamp = _parse_syslog_timestamp(msg_timestamp) hostname, message = data[timestamp_end:].split(maxsplit=1) tag, pid = None, None tag_match = TAG_REGEX.match(message) if tag_match and tag_match.end() != len(message): tag = tag_match.group(1) pid = tag_match.group(2) pid = int(pid) if pid else None message = message[tag_match.end():] return Message(level, facility, timestamp, hostname, tag, pid, message) def _parse_syslog_timestamp(timestamp): normalized_timestamp = str(datetime.now().year) + ' ' + timestamp return datetime.strptime(normalized_timestamp, '%Y %b %d %H:%M:%S') <file_sep>freezegun pytest pytest-asyncio pytest-benchmark pytest-pep8 <file_sep>from setuptools import setup, find_packages setup( name='logrotor', version='0.1', description='a lightweight log store with time-based rotation', url='https://github.com/tom-mi/logrotor', author='<NAME>', author_email='tom-mi at rfnbrgr.de', license='MIT', packages=find_packages(), install_requires=[ 'aiofiles', 'pyyaml', ], entry_points={ 'console_scripts': [ 'logrotor = logrotor.cli:logrotor', ] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Topic :: System :: Logging', ], ) <file_sep>import asyncio import logging import socket import pytest IP = '127.0.0.1' @pytest.fixture def queue(event_loop): return asyncio.Queue(loop=event_loop) @pytest.fixture def udp_port(): return 1024 @pytest.fixture def target_ip(): return IP @pytest.fixture def send_udp(udp_port, target_ip): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) def sender(message): sock.sendto(message, (target_ip, udp_port)) return sender @pytest.fixture(autouse=True) def enable_logging(): logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)-15s %(lineno)4d %(levelname)-8s %(message)s') <file_sep>import asyncio from logrotor.endpoint.udp import UdpEndpoint import pytest import socket pytestmark = pytest.mark.asyncio async def test_default_settings(event_loop, send_udp, udp_port, queue): endpoint = UdpEndpoint(queue, bind='127.0.0.1', port=udp_port) await endpoint.start(event_loop) send_udp('Test message'.encode()) result = await queue.get() assert result == '127.0.0.1 Test message' async def test_format(event_loop, send_udp, udp_port, queue): endpoint = UdpEndpoint(queue, bind='127.0.0.1', port=udp_port, format='Foo {message}') await endpoint.start(event_loop) send_udp('Test message'.encode()) result = await queue.get() assert result == 'Foo Test message' async def test_splitlines(event_loop, send_udp, udp_port, queue): endpoint = UdpEndpoint(queue, bind='127.0.0.1', port=udp_port, splitlines=True) await endpoint.start(event_loop) send_udp('A\nB'.encode()) results = [await queue.get() for _ in range(2)] assert results == ['127.0.0.1 A', '127.0.0.1 B'] <file_sep># logrotor [![Build Status](https://travis-ci.org/tom-mi/logrotor.svg?branch=master)](https://travis-ci.org/tom-mi/logrotor) a lightweight log store with time-based rotation ## Why The main purpose of this project is to connect [nginx](https://nginx.org/) and [goaccess](https://goaccess.io/) when both services are running as docker containers. It provides a nginx-compatible syslog endpoint to collect access log messages from nginx containers, handles log rotation and has some tweaks to work with goaccess. ## Quickstart A minimal configuration would look like this: ```yaml:config.yml --- rotate_every_seconds: 120 flush_every_seconds: 2 storage: path: ./test_storage size: 5 endpoints: - type: UdpEndpoint port: 1024 ``` The logrotor docker container expects a config file under `/srv/config.yml`. To run with docker: docker run \ --volume $(pwd)/config.yml:/srv/config.yml \ --publish 1024:1024/udp --name test_logrotor reifenbt/logrotor Run without docker (Python 3.6 required): pip install git+https://github.com/tom-mi/logrotor logrotor --config config.yml Send a message: echo -n "Hello World!" | nc -u -c localhost 1024 Read the logs (when running with docker): docker exec test_logrotor cat ./test_storage/current docker exec test_logrotor /bin/sh -c 'cat ./test_storage/data/*' Read the logs (when running without docker): cat ./test_storage/current cat ./test_storage/data/* ## Running with nginx & goaccess docker containers A simple example is contained in the repository. git clone https://github.com/tom-mi/logrotor cd logrotor cd examples/nginx_via_syslog docker-compose up The nginx webserver is reachable under http://localhost:8080/. The goaccess reports are served under http://localhost:8080/report/. ## Advanced Configuration Currently, UDP and syslog (UDP, according to RFC 3164) endpoints are supported. See the following example for all currently available configuration options: ```yaml --- rotate_every_seconds: 30 # required flush_every_seconds: 2 # required storage: path: ./test_storage # required size: 5 # required rotate_delay_seconds: 0 # delay between deleting and re-creating a file during rotation # (used with goaccess) endpoints: - type: UdpEndpoint # required bind: 0.0.0.0 port: 1024 # required format: '{host} {message}' # available variables: host, port, message splitlines: False # split multiline messages and apply format to each line - type: SyslogUdpEndpoint # required bind: 0.0.0.0 port: 514 format: '{timestamp:%b %e %H:%M:%S} {hostname} {message}' # available variables: src_host, src_port, timestamp, level, facility, # hostname, tag, pid, message ``` <file_sep>import asyncio from logrotor.endpoint.udp import UdpEndpoint from logrotor.util.syslog import bytes_to_message class SyslogUdpEndpoint(UdpEndpoint): def __init__(self, out, bind='0.0.0.0', port=514, **kwargs): super().__init__(out, bind=bind, port=port, **kwargs) def _get_protocol(self, out, **kwargs): return SyslogUdpProtocol(out, **kwargs) class SyslogUdpProtocol(asyncio.DatagramProtocol): def __init__(self, out, format='{timestamp:%b %e %H:%M:%S} {hostname} {message}'): super().__init__() self._format = format self._out = out def datagram_received(self, data, source): host, port = source message = bytes_to_message(data) self._out.put_nowait(self._format.format( src_host=host, src_port=port, timestamp=message.timestamp, level=message.level.name, facility=message.facility.name, hostname=message.hostname, tag=message.tag, pid=message.pid, message=message.message )) <file_sep>import asyncio from datetime import datetime from freezegun import freeze_time import pytest from logrotor.endpoint.syslog import SyslogUdpEndpoint from logrotor.util.syslog import message_to_bytes, Level, Facility, Message pytestmark = pytest.mark.asyncio @pytest.fixture def send_syslog(send_udp): def sender(message, level=Level.INFO, facility=Facility.LOCAL7, hostname='localhost', tag='foo', pid=666): message = Message(level, facility, datetime.now(), hostname, tag, pid, message) send_udp(message_to_bytes(message)) return sender async def test_default_settings(event_loop, send_syslog, udp_port, queue): with freeze_time('2018-01-01 02:03:04'): endpoint = SyslogUdpEndpoint(queue, bind='127.0.0.1', port=udp_port) await endpoint.start(event_loop) send_syslog('Test message') result = await asyncio.wait_for(queue.get(), timeout=1) assert result == 'Jan 1 02:03:04 localhost Test message' async def test_all_format_variables(event_loop, send_syslog, udp_port, queue): with freeze_time('2018-01-01 02:03:04'): full_format = '{src_host} {timestamp} {level} {facility} {hostname} {tag} {pid} {message}' endpoint = SyslogUdpEndpoint(queue, bind='127.0.0.1', port=udp_port, format=full_format) await endpoint.start(event_loop) send_syslog('Test message') result = await asyncio.wait_for(queue.get(), timeout=1) assert result == '127.0.0.1 2018-01-01 02:03:04 INFO LOCAL7 localhost foo 666 Test message' <file_sep>from asyncio import Queue import pytest from logrotor.endpoint import create_endpoint pytestmark = pytest.mark.asyncio @pytest.mark.parametrize('minimal_config', [ {'type': 'UdpEndpoint', 'port': 1024}, ]) async def test_create_endpoint(event_loop, queue, minimal_config): endpoint = create_endpoint(queue, minimal_config) await endpoint.start(event_loop) await endpoint.stop() <file_sep>from datetime import datetime from freezegun import freeze_time import pytest from logrotor.util.syslog import message_to_bytes, bytes_to_message, Message, Facility, Level @pytest.mark.parametrize('message,data', [ (Message(Level.CRIT, Facility.KERN, datetime(2018, 7, 28, 1, 2, 3), 'localhost', 'tag', None, 'Test message'), b'<2>Jul 28 01:02:03 localhost tag: Test message'), (Message(Level.ERR, Facility.CRON, datetime(2018, 1, 1, 15, 55, 55), 'localhost', 'tag', None, 'Test message'), b'<75>Jan 1 15:55:55 localhost tag: Test message'), (Message(Level.ERR, Facility.CRON, datetime(2018, 1, 1, 15, 55, 55), 'localhost', 'tag', None, 'Test message'), b'<75>Jan 1 15:55:55 localhost tag: Test message'), ]) @freeze_time('2018-01-01') def test_message_conversion(message, data): assert message_to_bytes(message) == data converted_message = bytes_to_message(data) assert converted_message.level == message.level assert converted_message.facility == message.facility assert converted_message.timestamp == message.timestamp assert converted_message.hostname == message.hostname assert converted_message.tag == message.tag assert converted_message.message == message.message @pytest.mark.parametrize('tag,pid,data,two_way', [ ('tag', None, b'<75>Jan 1 15:55:55 localhost tag: Test', True), ('tag', None, b'<75>Jan 1 15:55:55 localhost tag Test', False), ('tag', 42, b'<75>Jan 1 15:55:55 localhost tag[42]: Test', True), ('tag', 42, b'<75>Jan 1 15:55:55 localhost tag[42] Test', False), ]) @freeze_time('2018-01-01') def test_parse_tags(tag, pid, data, two_way): message = Message(Level.ERR, Facility.CRON, datetime(2018, 1, 1, 15, 55, 55), 'localhost', tag, pid, 'Test') if two_way: assert message_to_bytes(message) == data converted_message = bytes_to_message(data) assert converted_message.level == message.level assert converted_message.facility == message.facility assert converted_message.timestamp == message.timestamp assert converted_message.hostname == message.hostname assert converted_message.tag == message.tag assert converted_message.pid == message.pid assert converted_message.message == message.message def test_syslog_bytes_to_message(benchmark): data = b'<75>Jan 1 15:55:55 localhost tag[42]: Test message' benchmark(bytes_to_message, data) <file_sep>from logrotor.endpoint.udp import UdpEndpoint from logrotor.endpoint.syslog import SyslogUdpEndpoint def create_endpoint(out, config): class_name = config.pop('type') endpoint_class = globals()[class_name] return endpoint_class(out, **config) def class_for_name(module_name, class_name): module = importlib.import_module(module_name) return getattr(module, class_name)
522f5fea57714841a182bfc7d5d80276052ad370
[ "Markdown", "INI", "Python", "Text", "Shell" ]
19
Python
tom-mi/logrotor
e98698ca84697509ca3855ab1b9e598699d40b57
af3c6d826b094cf3f50cc4c599bbb01fd97b024e
refs/heads/master
<repo_name>gmascb/myImages<file_sep>/MyImages/Repositories/IRepository.cs using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace MyImages.Repositories { interface IRepository<T> : IDisposable { void Commit(); void Edit(T Entity); IQueryable<T> FindAll(); IQueryable<T> FindBy(Expression<Func<T, bool>> predicate); T FindById(string id); void Remove(T Entity); void Add(T Entity); void Dispose(); } } <file_sep>/MyImagesUnitTest/UnitTest1.cs using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; using MyImages.Models; using MyImages.Repository; using MyImages.Services; using MyImages.Uow; using System.IO; using Rhino.Mocks; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; using MyImages.Data; //Microsoft.VisualStudio.QualityTools.UnitTestFrameWork //at C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies\ namespace MyImagesUnitTest { [TestClass] public class UnitTest1 { private IImageServices service; private ImageUow uow; [TestInitialize] public void TestInitalize() { service = new ImageServices(); uow = new ImageUow(); /* public static T GenerateStub<T>(params object[] argumentsForConstructor) where T : class; */ //uow.Repository = new MockRepository.GenerateStub<IRepository<ImageModel>>(new ContextApp()); } [TestMethod] public void TestReturnOfRenderImageIsByteArray() { //arrange byte[] array = File.ReadAllBytes("Captura.png"); //act var result = service.RenderImage200PX(array, 100, 100); //arrange Xunit.Assert.IsType(typeof(byte[]), result); } [TestMethod] public void TestValidPngFile() { //arrange FormFile file = buildFile("Captura.png"); //act var result = service.ValidPngFile(file); //arrange Xunit.Assert.True(result); } [TestMethod] public void TestNotValidJpgFile() { //arrange FormFile file = buildFile("Captura2.jpg"); //act var result = service.ValidPngFile(file); //arrange Xunit.Assert.False(result); } [TestMethod] public void TestNumberOfImages() { //uow.Repository.Stub(x => x.FindAll().Count()).Return(8); //Assert.IsTrue(service.ValidNumberOfImagesUploaded(uow)); } private FormFile buildFile(string name) { using (var stream = File.OpenRead(name)) { return new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name)); } } } } <file_sep>/MyImages/Controllers/ImageController.cs using System; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MyImages.Uow; using MyImages.Models; using MyImages.Services; using Microsoft.AspNetCore.Http.Internal; using System.IO; namespace MyImages.Controllers { public class ImageController : Controller { ImageUow _uow; public IImageServices _service = new ImageServices(); public ImageController() { this._uow = new ImageUow(); } // GET: Images public ActionResult Index() { return View(_uow.Repository.FindAll()); } // GET: Images/Details/5 public ActionResult Details(string id) { return View(_uow.Repository.FindById(id)); } // GET: Images/Create public ActionResult Create() { return View(); } // POST: Images/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(ImageModel ImageModel, IFormFile Image) { if (_service.ValidNumberOfImagesUploaded(_uow)) { if (_service.ValidPngFile(Image)) { try { _service.BuildImagesByteArray(ImageModel, Image, _service); _uow.Repository.Add(ImageModel); _uow.Repository.Commit(); return RedirectToAction(nameof(Index)); } catch { return RedirectToAction(nameof(Index)); } } else { return RedirectToAction(nameof(Index)); } } else { return RedirectToAction(nameof(Index)); } } // GET: Images/Edit/5 public ActionResult Edit(string id) { return View(_uow.Repository.FindById(id)); } // POST: Images/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(string id, ImageModel model, IFormFile Image) { if (_service.ValidPngFile(Image)) { try { _service.BuildImagesByteArray(model, Image, _service); _uow.Repository.Edit(model); _uow.Repository.Commit(); return RedirectToAction(nameof(Index)); } catch (Exception e) { return View(); } } else { return RedirectToAction(nameof(Index)); } } // GET: Images/Delete/5 public ActionResult Delete(string id) { return View(_uow.Repository.FindById(id)); } // POST: Images/Delete/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(string id, ImageModel image) { try { this._uow.Repository.Remove(this._uow.Repository.FindById(id)); this._uow.Repository.Commit(); return RedirectToAction(nameof(Index)); } catch { return View(); } } } }<file_sep>/MyImages/Repositories/RepositoryGeneric.cs using Microsoft.EntityFrameworkCore; using MyImages.Data; using MyImages.Models; using MyImages.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace MyImages.Repository { public class RepositoryGeneric<T> : Repositories.IRepository<T> where T : class { ContextApp _context; DbSet<T> _dbSet; public RepositoryGeneric(ContextApp context) { _context = context; _dbSet = _context.Set<T>(); } public void Dispose() { throw new NotImplementedException(); } public void Commit() { _context.SaveChanges(); } public void Edit(T entity) { _context.Entry(entity).State = EntityState.Modified; } public IQueryable<T> FindAll() { return _context.Set<T>(); } public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate) { return _dbSet.Where(predicate); } public T FindById(string id) { return _dbSet.Find(id); } public void Remove(T entity) { _context.Set<T>().Remove(entity); } public void Add(T entity) { _context.Set<T>().Add(entity); } } } <file_sep>/MyImages/Uow/ImageUow.cs using Microsoft.EntityFrameworkCore; using MyImages.Data; using MyImages.Models; using MyImages.Repository; namespace MyImages.Uow { public class ImageUow : DbContext { public ContextApp context = new ContextApp(); public RepositoryGeneric<ImageModel> _repository; public RepositoryGeneric<ImageModel> Repository { get { if (_repository == null) { _repository = new RepositoryGeneric<ImageModel>(context); } return _repository; } } //public void Commit() //{ // context.SaveChanges(); //} } }<file_sep>/MyImages/Services/IImageServices.cs using MyImages.Uow; using Microsoft.AspNetCore.Http; using MyImages.Models; namespace MyImages.Services { public interface IImageServices { bool ValidNumberOfImagesUploaded(ImageUow uow); byte[] RenderImage200PX(byte[] image, int width, int height); bool ValidPngFile(IFormFile File); void BuildImagesByteArray(ImageModel ModelOnly, IFormFile Image, IImageServices service); } } <file_sep>/MyImages/Services/ImageServices.cs using MyImages.Uow; using System; using System.IO; using System.Linq; using static System.Net.Mime.MediaTypeNames; using System.Drawing; using Microsoft.AspNetCore.Http; using Amr; using MyImages.Models; namespace MyImages.Services { public class ImageServices : IImageServices { public bool ValidNumberOfImagesUploaded(ImageUow ImageUow) { return ImageUow.Repository.FindAll().Count() < 8; } public byte[] RenderImage200PX(byte[] image, int width = 200, int height = 200) { using (var stream = new MemoryStream(image)) { var img = System.Drawing.Image.FromStream(stream); var thumbnail = img.GetThumbnailImage(width, height, () => false, IntPtr.Zero); using (var thumbStream = new System.IO.MemoryStream()) { thumbnail.Save(thumbStream, System.Drawing.Imaging.ImageFormat.Jpeg); return thumbStream.GetBuffer(); } } } public bool ValidPngFile(IFormFile File) { if (File?.Length > 0) { return Path.GetExtension(File.FileName).Contains(".png"); } else { return false; } } public void BuildImagesByteArray(ImageModel ModelOnly, IFormFile Image, IImageServices service) { using (var stream = new MemoryStream()) { Image.CopyToAsync(stream); ModelOnly.Image = stream.ToArray(); ModelOnly.Image = service.RenderImage200PX(ModelOnly.Image, 200, 200); } } } } <file_sep>/MyImages/Data/ContextApp.cs using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using MyImages.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace MyImages.Data { public class ContextApp : DbContext { public ContextApp() :base() { } public virtual DbSet<ImageModel> Image { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { IConfigurationRoot configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); var connectionString = configuration.GetValue(typeof(string), "DbCoreConnectionString"); optionsBuilder.UseSqlServer((string)connectionString); } } } }
70d5996841bd13a4a54ca28ac0fa233c6293888f
[ "C#" ]
8
C#
gmascb/myImages
57413dc7967be5349d30812c2694ffca803025d6
83ac55b5a2f0f9daffcf1394a19befee7937cf33
refs/heads/master
<file_sep>import React, { Component } from 'react'; import imagenSan from '../img/San.jpg' import Menu from '../Menu/Menu'; import './Home.css'; import Footer from '../Footer/Footer'; class Home extends Component { render() { return ( <div className="main-container"> <React.Fragment> <Menu /> <div className="Slider"> <img src={imagenSan}/> </div> <div className="Footer"><Footer /></div> </React.Fragment> </div> ); } } export default Home; <file_sep>import React, { Component } from 'react'; import './Card.css'; import { BrowserRouter as Router, Route } from "react-router-dom"; import Home from '../Home/Home'; class Card extends Component { render() { let { image1, image2, image3, image4 } = this.props; return ( <div> <div className="main-card"> <div className="image"> <img className="image-small" src={image1} alt="mascota"> </img> <img className="image-small" src={image2} alt="mascota"> </img> <img className="image-small" src={image3} alt="mascota"> </img> <img className="image-small" src={image4} alt="mascota"> </img> </div> </div> </div> ); } } export default Card;<file_sep>import React, { Component } from 'react'; import './Veterinary.css'; import Postdata from '../../Components/Data/api.json'; class Veterinary extends Component { render() { return ( <div> <div className="main"> {this.state.data[0].id} </div> </div> ); } } export default Veterinary;<file_sep>import React, { Component } from 'react'; import '../TakeCare/TakeCare.css'; import Postdata from '../../Components/Data/api.json'; import Information from '../Information/Information'; import Card from '../Card/Card'; import icon1 from '../img/img1.png'; import icon2 from '../img/img2.png'; import Menu from '../Menu/Menu'; import Footer from '../Footer/Footer'; class TakeCare extends Component { constructor(props) { super(props) this.state = { data: Postdata, } } render() { let dataInformation = this.state.data[2]; return ( <div> < Menu /> <div className="main-take-care"> {"Accedé a la lista de cuidados básicos para tu mascota"} <div className="image-container"> <img className="image" src={icon1} alt="mascota"> </img> <img className="image" src={icon2} alt="mascota"> </img> </div> </div> <div className="Footer"><Footer /></div> </div> ); } } export default TakeCare;<file_sep>import './Footer.css'; import React, { Component } from 'react'; import iconoig from '../img/iconoig.png' import iconomail from '../img/iconomail.png' class Footer extends Component { render() { return ( <div className= "main-footer"> <div className= "icons"> <img className="ig" src={iconoig} /> {'@<EMAIL>'} <img className="mail" src={iconomail}/> {'<EMAIL>'} </div> </div> )} } export default Footer; <file_sep>import React, { Component } from 'react'; import './Adopt.css'; import Postdata from '../../Components/Data/api.json'; import Card from '../Card/Card'; import Information from '../Information/Information'; import icon1 from '../img/icon1.png'; import icon2 from '../img/icon2.png'; import icon3 from '../img/icon3.png'; import icon4 from '../img/icon4.png'; import Menu from '../Menu/Menu'; import Mascota1 from '../img/mascota1.png'; import Mascota2 from '../img/mascota2.png'; import Mascota3 from '../img/mascota3.png'; class Adopt extends Component { constructor(props) { super(props) this.state = { data: Postdata, } } render() { let dataInformation = this.state.data[0].steps; return ( <div> <div className="main-adopt"> < Menu /> <Information information={dataInformation} /> <Card image1={icon1} image2={icon2} image3={icon3} image4={icon4} /> <div className="images"> <img className="image" alt='' src={Mascota1} /> <img className="image" alt='' src={Mascota2} /> <img className="image" alt='' src={Mascota3} /> </div> <div className="text-container"> <div className="text1"> {dataInformation.map((dataDetail, index) => { return <div className="row" key={index}>{dataDetail.text1}</div> })} </div> <div className="text2"> {dataInformation.map((dataDetail, index) => { return <div className="row" key={index}>{dataDetail.text2}</div> })} </div> </div> {/* <Footer /> */} </div> </div> ); } } export default Adopt; <file_sep>import React, { Component } from 'react'; import './WhyAdopt.css'; import Card from '../Card/Card'; import icon1 from '../img/foto1.png'; import icon2 from '../img/foto2.png'; import icon3 from '../img/foto3.png'; import icon4 from '../img/foto4.png'; import Postdata from '../../Components/Data/api.json'; import Information from '../Information/Information'; import Menu from '../Menu/Menu'; import '../Menu/Menu.css'; class whyAdopt extends Component { constructor(props) { super(props) this.state = { data: Postdata, } } render() { let dataInformation = this.state.data[1]; return ( <div> <div className="main-why-adopt"> <Menu /> </div> <Card image1={icon1} image2={icon2} image3={icon3} image4={icon4} text={dataInformation.steps} /> <Information informationText={dataInformation.informationText1} informationText2={dataInformation.informationText2} informationText3={dataInformation.informationText3} /> </div> ); } } export default whyAdopt;<file_sep>import React, { Component } from 'react'; import imagenLogo from '../img/logo.png'; import './Menu.css'; import { Link } from 'react-router-dom'; class Menu extends Component { render() { return ( <div className="main-container"> <React.Fragment> <div className="Menu"> <div className="links1"> <Link to="/adopt"> <div className="OP">¿CÓMO ADOPTAR?</div> </Link> <Link to="/whyadopt"> <div className="OP">¿PORQUÉ ADOPTAR?</div> </Link> </div> <Link to="/"> <img className="logo" alt='' src={imagenLogo} /> </Link> <div className="links2"> <Link to="/takecare"> <div className="OP">CUIDA TU MASCOTA</div> </Link> <Link to="/veterinary"> <div className="OP">VETERINARIAS</div> </Link> </div> </div> </React.Fragment> </div> ); } } export default Menu;
a354fdf2cd240ee4c3115635f17a469db37d5f5c
[ "JavaScript" ]
8
JavaScript
ClubdeMascotas/ClubDeMascotas
68da5c68f6c888527de939b17e42c57c00e5da46
32ce2bb3526c483e2ddab7f36e4a57672b224f66
refs/heads/master
<repo_name>syaifulislam/Arisen-development<file_sep>/database/migrations/2018_12_16_032619_arbar.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class Arbar extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::dropIfExists('arbars'); Schema::dropIfExists('arbar_details'); Schema::create('arbars',function(Blueprint $table){ $table->increments('id'); $table->string('title'); $table->string('sponsor'); $table->string('sponsor_address'); $table->string('sponsor_email'); $table->string('contact_sponsor'); $table->integer('total_player'); $table->integer('joined_player')->default(0); $table->integer('coupon'); $table->text('promo_image_path'); $table->text('coupon_image_path'); $table->integer('generate_id'); $table->timestamps(); $table->softDeletes(); }); Schema::create('arbar_details',function(Blueprint $table){ $table->increments('id'); $table->integer('user_id'); $table->integer('arbar_id'); $table->integer('room_id'); $table->integer('state')->default(0); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // } } <file_sep>/app/Http/Controllers/ForumController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Room; use Sentinel; class ForumController extends Controller { public function index(Request $request){ $dataRoom = Room::select(); if ($request->has('search2')) { $dataRoom = $dataRoom->where('room_name','like','%'.$request->get('search2').'%'); $search = $request->get('search2'); }else{ $search = null; } $dataRoom = $dataRoom->get(); return view('forum',compact('dataRoom','search')); } } <file_sep>/app/Http/Controllers/RoomController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Sentinel; use App\Room; use Carbon\Carbon; use App\JoinRoom; use App\UserRoomPaymentHistory; use App\UserArisan; use App\UserDetails; use App\PaymentHistory; use DB; class RoomController extends Controller { public function index(){ $dataRoom = JoinRoom::with('room')->where('user_id',Sentinel::getUser()->id)->get(); return view('my-room',compact('dataRoom')); } public function create(){ if(Sentinel::getUser()->is_verif == 2){ return redirect()->back()->with('alert', 'Akun Anda Telah Ditolak'); }else if(Sentinel::getUser()->is_verif == 0){ return redirect('/my-account')->with('alert', 'Silahkan Aktivasi Akun Anda Terlebih Dahulu'); } return view('create-room'); } public function createRoom(Request $request){ // period_start_date if($request->has('public')){ $params = $request->except('_token','login','public','private','passwordConfirm','<PASSWORD>'); }else{// kalo dia private $params = $request->except('_token','login','public','private','passwordConfirm'); $params['password'] = md5($params['password']); } if($params['period'] == "Mingguan"){ $params['period_start_date'] = Carbon::now()->addWeek()->format('Y-m-d'); }else if($params['period'] == "Bulanan"){ $params['period_start_date'] = Carbon::now()->addMonth()->format('Y-m-d'); }else{ $params['period_start_date'] = Carbon::now()->addYear()->format('Y-m-d'); } try{ DB::beginTransaction(); $params['period_status'] = 'Belum Mulai'; $params['created_by'] = Sentinel::getUser()->id; $params['total_player_join'] = 0; $params['generate_id'] = rand(10,99).Carbon::now()->setTimezone('+7')->format('Ymd'); $params['created_at'] = Carbon::now()->setTimezone('+7'); $params['updated_at'] = Carbon::now()->setTimezone('+7'); $data = Room::insert($params); $this->addRoom(Sentinel::getUser()->id,$params['generate_id']); DB::commit(); }catch(\Exception $e){ DB::rollback(); return redirect('forum'); } return redirect('/ruangan-arisan/'.$params['generate_id']); } public function room($id){ if(Sentinel::getUser()->is_verif == 2){ return redirect()->back()->with('alert', 'Akun Anda Telah Ditolak'); }else if(Sentinel::getUser()->is_verif == 0){ return redirect('/my-account')->with('alert', 'Silahkan Aktivasi Akun Anda Terlebih Dahulu'); } $data = Room::where('generate_id',$id)->first(); $getTime = Carbon::now()->setTimezone('+7'); $getDataTimes = $data->period_start_date." 07:00:00"; if (Carbon::parse($getDataTimes) <= Carbon::now()) { $boolStart = false; } else { $boolStart = true; } $joinRoom = JoinRoom::where('user_id',Sentinel::getUser()->id)->where('room_id',$data->id)->first(); return view('ruangan-arisan',compact('id','data','getDataTimes','joinRoom','boolStart')); } public function checkPassword($id, Request $request){ $password = md5($request->input('password')); $checkData = Room::where('generate_id',$id)->first(); if($checkData->password == $password){ return response()->json([ "data"=> true, "message"=>"" ]); } return response()->json([ "data"=>false, "message"=>"Password Salah" ]); } public function addRoom($userId,$roomId){ $getDataRoom = Room::where('generate_id',$roomId)->first(); try{ DB::beginTransaction(); $joinRoom = new JoinRoom; $joinRoom->user_id = $userId; $joinRoom->room_id = $getDataRoom->id; $joinRoom->save(); for($i=1;$i<=$getDataRoom->total_player;$i++){ $paymentHistories = new UserRoomPaymentHistory; $paymentHistories->user_id = $userId; $paymentHistories->room_id = $getDataRoom->id; $paymentHistories->period_roll = $i; $paymentHistories->status = 'Belum Bayar'; $paymentHistories->save(); } Room::where('generate_id',$roomId)->increment('total_player_join'); DB::commit(); return redirect('/ruangan-arisan/'.$roomId); }catch(\Exception $e){ DB::rollback(); return redirect('/ruangan-arisan/'.$roomId); } } public function undian($id){ $data = Room::where('generate_id',$id); if ( $data->first() ) { if ( $data->first()->period_status == 'Sudah Selesai' ) { return redirect()->back()->with('alert', 'Room Ini Sudah Selesai'); } else if ($data->first()->total_player > $data->first()->total_player_join) { $data->update(['period_status'=>'Sudah Selesai']); return redirect()->back()->with('alert', 'Total Pemain Tidak Mencukupi'); } $data->update(['period_status'=>'Sedang Berlangsung']); $roomId = $data->first()->id; $pricePerPlayer = $data->first()->price_per_player; $joinRoom = JoinRoom::where('room_id',$roomId)->pluck('user_id'); foreach($joinRoom as $value){ UserDetails::where('user_id',$value)->decrement('money',$pricePerPlayer); PaymentHistory::insert([ 'user_id'=>$value, 'request_nominal'=>$pricePerPlayer, 'payment_type_id'=> 3, 'status'=>'Sudah di Proses' ]); } UserDetails::where('user_id',Sentinel::getUser()->id)->increment('money',$pricePerPlayer*$data->first()->total_player_join); PaymentHistory::insert([ 'user_id'=>Sentinel::getUser()->id, 'request_nominal'=>$pricePerPlayer*$data->first()->total_player_join, 'payment_type_id'=> 3, 'status'=>'Sedang di Proses' ]); if($data->first()->period == "Mingguan"){ $data->update([ 'period_start_date'=>Carbon::parse($data->first()->period_start_date)->addWeek()->format('Y-m-d') ]); }else if($data->first()->period == "Bulanan"){ $data->update([ 'period_start_date'=>Carbon::parse($data->first()->period_start_date)->addMonth()->format('Y-m-d') ]); }else{ $data->update([ 'period_start_date'=>Carbon::parse($data->first()->period_start_date)->addYear()->format('Y-m-d') ]); } $arisan = new UserArisan; $arisan->user_id = Sentinel::getUser()->id; $arisan->room_id = $roomId; $arisan->save(); } return redirect()->back(); } } <file_sep>/app/ArbarDetail.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class ArbarDetail extends Model { use SoftDeletes; protected $fillable = ['user_id','arbar_id','room_id','state']; } <file_sep>/app/Exports/PaymentExport.php <?php namespace App\Exports; use App\PaymentHistory; use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\Exportable; use Carbon\Carbon; use Illuminate\Contracts\View\View; use Maatwebsite\Excel\Concerns\FromView; class PaymentExport implements FromView { use Exportable; /** * @return \Illuminate\Support\Collection */ public function __construct($period) { $this->period = $period; } public function view(): View { if ($this->period == 'mingguan') { $timeStart = Carbon::now()->startOfWeek()->format('Y-m-d'); $timeEnd = Carbon::now()->endOfWeek()->format('Y-m-d'); }else if ($this->period == 'bulanan') { $timeStart = Carbon::now()->startOfMonth()->format('Y-m-d'); $timeEnd = Carbon::now()->endOfMonth()->format('Y-m-d'); }else if ($this->period == 'tahunan') { $timeStart = Carbon::now()->startOfYear()->format('Y-m-d'); $timeEnd = Carbon::now()->endOfYear()->format('Y-m-d'); }else { return view('download-xls', [ 'data' => PaymentHistory::select('users.username', 'payment_historys.request_nominal', 'payment_historys.status', 'payment_types.name', 'payment_historys.created_at') ->leftJoin('payment_types','payment_types.id','payment_historys.payment_type_id') ->leftJoin('users','users.id','payment_historys.user_id')->get() ]); } return view('download-xls', [ 'data' => PaymentHistory::select('users.username', 'payment_historys.request_nominal', 'payment_historys.status', 'payment_types.name', 'payment_historys.created_at') ->leftJoin('payment_types','payment_types.id','payment_historys.payment_type_id') ->leftJoin('users','users.id','payment_historys.user_id') ->whereBetween('payment_historys.created_at',[$timeStart,$timeEnd])->get() ]); } } <file_sep>/routes/web.php <?php use App\Http\Middleware\SentinelCheck; use App\Http\Middleware\SentinelAdmin; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/admin',function(){ return redirect('auth/login'); }); Route::get('detail-saldo',function(){ return view('detail-saldo'); }); // Route::get('ruangan-arisan',function(){ // return view('ruangan-arisan'); // }); Route::get('ruangan-arisan-undian',function(){ return view('ruangan-arisan-undian'); }); Route::get('ruangan-arisan-undian-dapat',function(){ return view('ruangan-arisan-undian-dapat'); }); // Route::get('add-ruangan',function(){ // return view('add-ruangan'); // }); Route::get('/', function(){ if (Sentinel::check()){ if (Sentinel::getUser()->role_user == 'user') { return view('index-login'); }else if(Sentinel::getUser()->role_user == 'admin'){ return redirect('home-admin'); } } return view('index'); // return view('home-index'); }); Route::get('arbar','ArbarController@index'); Route::get('bantuan',function(){ return view('bantuan'); }); Route::get('tentang-kami',function(){ return view('tentang-kami'); }); Route::prefix('auth')->group(function(){ Route::get('/login',function(){ if(Sentinel::check()) return redirect('home-page'); return view('login-page'); }); Route::post('/login','UserController@authenticate'); Route::get('/register',function(){ return view('register-page'); }); Route::post('/register','UserController@registerUsers'); Route::get('/expired',function(){ return view('expired'); }); Route::get('/forgot-password',function(){ return view('forgot-password-page'); }); Route::post('/forgot-password','UserController@forgotPassword'); Route::post('/change-password','UserController@actionChangePassword'); Route::get('/verifEmail/{callback}','UserController@emailVerification'); Route::get('/forgot-password-verification/{callback}','UserController@changePassword'); Route::get('/logout','UserController@logout'); }); Route::group(['middleware'=>SentinelCheck::class],function(){ Route::get('notification-user','NotificationController@index'); // return view('notification-user'); Route::get('/home-page','HomeController@index'); Route::get('/my-account','AccountController@index'); Route::get('/my-room','RoomController@index'); Route::get('/forum','ForumController@index'); Route::post('/verification','AccountController@verification'); Route::get('/create-room','RoomController@create'); Route::get('/tarik','SetorController@index'); Route::get('/setor','SetorController@setorIndex'); Route::post('/setor','SetorController@setorCreate'); Route::post('/create-room','RoomController@createRoom'); Route::post('/request-money','SetorController@requestMoney'); Route::get('/riwayat-keuangan','SetorController@history'); Route::get('/riwayat-permainan','RiwayatPermainanController@index'); Route::get('/ruangan-arisan/{id}','RoomController@room'); Route::post('/roomComment/{id}','RoomCommentController@create'); Route::get('/roomComment/{id}','RoomCommentController@index'); Route::get('/roomComments/{id}','RoomCommentController@update'); Route::put('/checkRoom/{id}','RoomController@checkPassword'); Route::get('/add-room/{id}/{room_id}','RoomController@addRoom'); Route::post('/ambil-arbar/{id}', 'ArbarController@ambilArbar'); Route::get('/undi-arisan/{id}','RoomController@undian'); }); Route::group(['middleware'=>SentinelAdmin::class],function(){ Route::get('home-admin','AdminController@home'); Route::get('laporan-keuangan','AdminController@keuangan'); Route::get('riwayat-keuangan-admin','AdminController@keuangan'); Route::get('arbar-admin', 'AdminController@arbarIndex'); Route::get('setor-dana-admin', 'AdminController@setor'); Route::get('tarik-dana-admin','AdminController@tarik'); Route::get('aktivasi-akun-admin','AdminController@activate'); Route::get('activate/{user_id}/{slug}','AdminController@actionActivate'); Route::get('setor/{id}/{slug}','AdminController@actionSetor'); Route::post('tarik/{id}','AdminController@actionTarik'); Route::post('addAdmin','AdminController@addAdmin'); Route::post('changeAdmin/{id}','AdminController@changeAdmin'); Route::post('download-xls', 'AdminController@download'); Route::get('add-admin','AdminController@superAdmin'); Route::get('denied-user',function(){ return view('denied-user'); }); Route::post('add-arbar', 'AdminController@arbarStore'); Route::get('admin-delete-arbar/{id}', 'AdminController@arbarDelete'); }); Route::get('coming-soon',function(){ return view('coming-soon'); }); Route::get('admin-get-user/{id}','AdminController@getUserActivate'); Route::get('admin-get-setor/{id}','AdminController@getUserSetor'); Route::get('admin-get-tarik/{id}','AdminController@getUserTarik'); Route::get('admin-get-keuangan/{id}','AdminController@getUserKeuangan'); Route::get('admin-get-data/{id}', 'AdminController@getUserAdmin'); Route::get('admin-get-arbar/{id}', 'AdminController@getArbar'); Route::get('arbar-detail/{id}', 'ArbarController@getArbar'); Route::post('arbar-admin-update/{id}', 'AdminController@updateArbar'); Route::get('admin-super-admin',function(){ return view('admin-super-admin'); });<file_sep>/app/Arbar.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Arbar extends Model { use SoftDeletes; protected $fillable = ['title','sponsor','sponsor_address','sponsor_email','contact_sponsor','total_player','joined_player','coupon','promo_image_path','coupon_image_path','generate_id']; } <file_sep>/app/Http/Controllers/ArbarController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Arbar; use App\Room; use App\JoinRoom; use App\ArbarDetail; use App\UserDetails; use App\Notification; use Sentinel; use Carbon\Carbon; class ArbarController extends Controller { public function index(){ $data = Arbar::all(); return view('arbar',compact('data','dataRoom')); } public function getArbar($id){ $data = Arbar::find($id); $dataRoom = JoinRoom::with('room')->where('user_id',Sentinel::getUser()->id)->get(); return response()->json([ "data" => $data, "dataRoom" => $dataRoom ]); } public function ambilArbar(Request $request, $id){ if($request->post('room_id') == null){ return redirect()->back()->with('alert', 'Pilih Ruangan Terlebih Dahulu'); }else{ $room = Room::find($request->post('room_id')); $dataArbar = Arbar::find($id); $dataCheck = ArbarDetail::where('user_id',Sentinel::getUser()->id)->where('arbar_id',$id)->where('room_id',$request->post('room_id'))->first(); $checkSaldo = UserDetails::where('user_id',Sentinel::getUser()->id)->first(); if(!$checkSaldo){ return redirect()->back()->with('alert', 'Silahkan Isi Saldo Terlebih Dahulu'); }else if($checkSaldo->money < $room->price_per_player){ return redirect()->back()->with('alert', 'Saldo Anda Tidak Cukup'); } // all validation if($dataCheck){ return redirect()->back()->with('alert', 'Anda Telah Mengambil Arbar Ini Pada Tanggal '.Carbon::parse($dataCheck->created_at)->format('d F Y H:i:s')); }else if($dataArbar->total_player > $room->total_player_join){ return redirect()->back()->with('alert', 'Total Pemain Tidak Mencukupi'); }else if($dataArbar->coupon == $dataArbar->joined_player){ return redirect()->back()->with('alert', 'Promo Arbar Ini Sudah Penuh'); } // end validation $arbar = new ArbarDetail; $arbar->user_id = Sentinel::getUser()->id; $arbar->room_id = $request->post('room_id'); $arbar->arbar_id = $id; $arbar->save(); $dataArbar->increment('joined_player'); $notif = new Notification; $notif->user_id = Sentinel::getUser()->id; $notif->title = 'Kupon Arbar'; $notif->status = 'info'; $notif->save(); return redirect()->back()->with('alert', 'Berhasil Diambil'); } } } <file_sep>/app/Http/Requests/registerRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class registerRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'first_name' => 'required', 'last_name' => 'required', 'email' => 'required|unique:users,email', 'birth_date' => 'required', 'password' => '<PASSWORD>', 'username' => 'required|unique:users,username' ]; } public function attributes() { return [ 'first_name' => 'Nama Depan', 'last_name' => 'Nama Belakang', 'birth_date' => 'Tanggal Lahir', 'password' => '<PASSWORD>', 'email' => 'Email', 'username' => 'Nama Pengguna' ]; } public function messages() { return [ '*.required' => ':attribute harus di isi', '*.unique' => ':attribute sudah digunakan', // '*.same' => ':attribute tidak cocok', // '*.min' => ':attribute minimal 8 karakter', ]; } } <file_sep>/app/Http/Controllers/RoomCommentController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\RoomComment; use Sentinel; use Carbon\Carbon; class RoomCommentController extends Controller { public function create(Request $request,$id){ RoomComment::insert([ 'user_id' => Sentinel::getUser()->id, 'room_id' => $id, 'comment' => $request->post("comment"), 'created_at'=> Carbon::now()->setTimezone('+7')->format('Y-m-d H:i:s'), 'flag_view' => 0 ]); return response()->json([ "data" => "masuk" ]); } public function index($id){ $data = RoomComment::with('user')->where('room_id',$id)->orderBy('created_at','asc'); $commentView = $data->get(); foreach($commentView as $value){ $value->tanggal = Carbon::parse($value->created_at)->format('M d'); $value->tahun = Carbon::parse($value->created_at)->format('y'); } return response()->json([ "data" => $commentView ]); } public function update($id){ $data = RoomComment::with('user')->where('room_id',$id)->orderBy('created_at','asc'); $commentView = $data->get(); foreach($commentView as $value){ $value->tanggal = Carbon::parse($value->created_at)->format('M d'); $value->tahun = Carbon::parse($value->created_at)->format('y'); } return response()->json([ "data" => $commentView ]); } } <file_sep>/app/UserDetails.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class UserDetails extends Model { use SoftDeletes; protected $table = 'user_details'; protected $fillable = ['user_id','money', 'bank_account_number','bank_account_name','images_path','bank_account_office']; public function user(){ return $this->hasOne(User::class,'id','user_id'); } } <file_sep>/readme.md ## CONFIG UNTUK PUSH - * git stash - * git fetch && git merge - * git stash pop - * git add . && git commit -m "pesan commit" - * git push<file_sep>/app/Http/Controllers/AdminController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\UserDetails; use App\User; use App\Users; use App\PaymentHistory; use App\AdminImage; use App\Arbar; use App\ArbarDetail; use App\Notification; use Sentinel; use Activation; use Storage; use Illuminate\Support\Facades\File; use Carbon\Carbon; use App\Exports\PaymentExport; use Maatwebsite\Excel\Facades\Excel; class AdminController extends Controller { public function superAdmin(){ $data = User::where('role_user','admin')->where('is_super_admin',0)->get(); return view('add-admin',compact('data')); } public function home(){ $data = User::where('role_user','admin')->where('is_super_admin',0)->get(); return view('home-admin',compact('data')); } public function activate(){ $data = UserDetails::with('user')->get(); return view('aktivasi-akun-admin',compact('data')); } public function getUserActivate($id){ $data = UserDetails::with('user')->where('user_id',$id)->first(); return response()->json([ "data" => $data ]); } public function actionActivate($user_id,$slug){ User::where('id',$user_id)->update([ 'is_verif'=>$slug ]); $notif = new Notification; $notif->user_id = $user_id; if($slug == 1){ $notif->status = 'berhasil'; }else{ $notif->status = 'ditolak'; } $notif->title = 'Aktifasi'; $notif->save(); return redirect()->back(); } public function setor(){ $data = PaymentHistory::with('user')->where('payment_type_id',2)->orderBy('created_at','desc')->get(); return view('setor-dana-admin',compact('data')); } public function getUserSetor($id){ $data = PaymentHistory::with('user','user_detail')->where('id',$id)->first(); return response()->json([ "data" => $data ]); } public function actionSetor($id,$slug){ $data = PaymentHistory::where('id',$id); $getNominal = $data->first()->request_nominal; if ($slug == 'Sudah di Proses') { UserDetails::where('user_id',$data->first()->user_id)->increment('money',$getNominal); $data->update([ 'status' => $slug ]); $notif = 'berhasil'; }else{ PaymentHistory::where('id',$id)->update([ 'status' => $slug ]); $notif = 'ditolak'; } $insertNotif = new Notification; $insertNotif->user_id = $data->first()->user_id; $insertNotif->title = 'Setor Dana'; $insertNotif->status = $notif; $insertNotif->save(); return redirect()->back(); } public function tarik(){ $data = PaymentHistory::with('user')->where('payment_type_id',1)->orderBy('created_at','desc')->get(); return view('tarik-dana-admin',compact('data')); } public function getUserTarik($id){ $data = PaymentHistory::with('user','user_detail')->where('id',$id)->first(); return response()->json([ "data" => $data ]); } public function actionTarik(Request $request , $id){ $image = $request->file('fileToUpload'); $fileName = 'tarikKonfirmasi-'.Sentinel::getUser()->id.'.'.time() . '.' . $image->getClientOriginalExtension(); Storage::disk('public')->put($fileName, File::get($image)); $paymentHistory = PaymentHistory::where('id',$id); UserDetails::where('user_id',$paymentHistory->first()->user_id)->decrement('money',$paymentHistory->first()->request_nominal); $paymentHistory->update([ 'status' => 'Sudah di Proses', 'image_path_confirm' => $fileName ]); return redirect()->back(); } public function keuangan(){ $data = PaymentHistory::with('user','user_detail','payment_type')->orderBy('created_at','desc')->get(); return view('riwayat-keuangan-admin',compact('data')); } public function getUserKeuangan($id){ $data = PaymentHistory::with('user','user_detail','payment_type')->find($id); return response()->json([ "data" => $data ]); } public function addAdmin(Request $request){ $credentials = $request->except('_token','passwordConfirm','fileToUpload'); $credentials['is_verif'] = 1; $credentials['role_user'] = 'admin'; $credentials['user_code'] = 'AR-'.Carbon::now()->setTimezone('+7')->format('Ymd').'-'.rand(10000,99999); $register = Sentinel::register($credentials); $user = Sentinel::findById($register->id); $activeUser = Activation::create($user); Activation::complete($user, $activeUser->code); $image = $request->file('fileToUpload'); $fileName = 'adminImage-'.Sentinel::getUser()->id.'.'.time() . '.' . $image->getClientOriginalExtension(); Storage::disk('public')->put($fileName, File::get($image)); AdminImage::insert([ 'user_id' => $register->id, 'image_path' => $fileName ]); return redirect()->back(); } public function getUserAdmin($id){ $data = Users::with('admin_images','user_details')->where('id',$id)->first(); return response()->json([ "data" => $data ]); } public function changeAdmin(Request $request,$id){ if ($request->post('password') == null) { $params = $request->only('first_name','last_name','username','email'); }else{ $params = $request->only('first_name','last_name','username','email','password'); } if ($request->has('fileToUpload')) { $image = $request->file('fileToUpload'); $fileName = 'adminImage-'.Sentinel::getUser()->id.'.'.time() . '.' . $image->getClientOriginalExtension(); Storage::disk('public')->put($fileName, File::get($image)); AdminImage::where('user_id',$id)->update([ 'image_path' => $fileName ]); } $user = Sentinel::findById($id); Sentinel::update($user,$params); return redirect()->back(); } public function download(Request $request){ $period = $request->post('period'); if(!$period){ return redirect()->back(); } if ($period == 'mingguan') { $timeStart = Carbon::now()->startOfWeek()->format('Y-m-d'); $timeEnd = Carbon::now()->endOfWeek()->format('Y-m-d'); }else if ($period == 'bulanan') { $timeStart = Carbon::now()->startOfMonth()->format('Y-m-d'); $timeEnd = Carbon::now()->endOfMonth()->format('Y-m-d'); }else if ($period == 'tahunan') { $timeStart = Carbon::now()->startOfYear()->format('Y-m-d'); $timeEnd = Carbon::now()->endOfYear()->format('Y-m-d'); } return (new PaymentExport($period))->download('Data_Payment_Arisen_'.$period.'_from_'.$timeStart.'_to_'.$timeEnd.'.xlsx'); } public function arbarStore(Request $request){ $params = $request->except('_token','fileToUploadPromo','fileToUploadCoupon'); $params['generate_id'] = (int)Sentinel::getUser()->id.rand(10000,99999); $params['created_at'] = Carbon::now()->setTimezone('+7'); $params['updated_at'] = Carbon::now()->setTimezone('+7'); if ($request->has('fileToUploadPromo')) { $image = $request->file('fileToUploadPromo'); $fileName = 'ArbarPromo-'.Sentinel::getUser()->id.'.'.time() . '.' . $image->getClientOriginalExtension(); Storage::disk('public')->put($fileName, File::get($image)); $params['promo_image_path'] = $fileName; } if ($request->has('fileToUploadCoupon')) { $image = $request->file('fileToUploadCoupon'); $fileName = 'ArbarCoupon-'.Sentinel::getUser()->id.'.'.time() . '.' . $image->getClientOriginalExtension(); Storage::disk('public')->put($fileName, File::get($image)); $params['coupon_image_path'] = $fileName; } Arbar::insert($params); return redirect()->back(); } public function arbarIndex(){ $data = Arbar::all(); return view('arbar-admin',compact('data')); } public function getArbar($id){ $data = Arbar::find($id); return response()->json([ "data" => $data ]); } public function updateArbar(Request $request,$id){ $params = $request->except('_token','fileToUploadPromo','fileToUploadCoupon'); if ($request->has('fileToUploadPromo')) { $image = $request->file('fileToUploadPromo'); $fileName = 'ArbarPromo-'.Sentinel::getUser()->id.'.'.time() . '.' . $image->getClientOriginalExtension(); Storage::disk('public')->put($fileName, File::get($image)); $params['promo_image_path'] = $fileName; } if ($request->has('fileToUploadCoupon')) { $image = $request->file('fileToUploadCoupon'); $fileName = 'ArbarCoupon-'.Sentinel::getUser()->id.'.'.time() . '.' . $image->getClientOriginalExtension(); Storage::disk('public')->put($fileName, File::get($image)); $params['coupon_image_path'] = $fileName; } $data = Arbar::find($id)->update($params); return redirect()->back(); } public function arbarDelete($id){ Arbar::find($id)->delete(); return redirect()->back(); } } <file_sep>/database/migrations/2018_11_14_151104_refund_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class RefundTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::dropIfExists('payment_historys'); Schema::dropIfExists('payment_types'); Schema::create('payment_historys',function(Blueprint $table){ $table->increments('id'); $table->integer('user_id'); $table->integer('request_nominal')->nullable(); $table->integer('payment_type_id'); $table->enum('status', array('Pending','Sedang di Proses','Sudah di Proses','Gagal')); $table->string('image_path')->nullable(); $table->string('image_path_confirm')->nullable(); $table->timestamps(); $table->softDeletes(); }); Schema::create('payment_types',function(Blueprint $table){ $table->increments('id'); $table->enum('name', array('Tarik Dana','Setor Dana','Undian')); $table->timestamps(); $table->softDeletes(); }); DB::table('payment_types')->insert([ 'name' => 'Tarik Dana' ]); DB::table('payment_types')->insert([ 'name' => 'Setor Dana' ]); DB::table('payment_types')->insert([ 'name' => 'Undian' ]); } /** * Reverse the migrations. * * @return void */ public function down() { // } } <file_sep>/app/Http/Controllers/SetorController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Akaunting\Money\Currency; use Akaunting\Money\Money; use App\UserDetails; use App\PaymentHistory; use Sentinel; use Storage; use Carbon\Carbon; use Illuminate\Support\Facades\File; class SetorController extends Controller { public function index(){ $getMoney = UserDetails::where('user_id',Sentinel::getUser()->id)->first(); $myMoney = Money::IDR($getMoney->money,true)->format(); return view('tarik-dana',compact('myMoney')); } public function requestMoney(Request $request){ $params = $request->only('request_nominal'); $params['user_id'] = Sentinel::getUser()->id; $params['payment_type_id'] = 1; $params['status'] = 'Pending'; $params['created_at'] = Carbon::now()->setTimezone('+7')->format('Y-m-d H:i:s'); $params['updated_at'] = Carbon::now()->setTimezone('+7')->format('Y-m-d H:i:s'); PaymentHistory::insert($params); return redirect('riwayat-keuangan'); } public function history(){ $myMoney = Money::IDR(Sentinel::getUser()->money,true)->format(); $getData = PaymentHistory::with('payment_type')->where('user_id',Sentinel::getUser()->id)->orderBy('created_at','desc')->get(); return view('detail-saldo',compact('myMoney','getData')); } public function setorIndex(){ $getMoney = UserDetails::where('user_id',Sentinel::getUser()->id)->first(); $myMoney = Money::IDR($getMoney->money,true)->format(); return view('setor-dana',compact('myMoney')); } public function setorCreate(Request $request){ $image = $request->file('fileToUpload'); $fileName = 'setor-'.Sentinel::getUser()->id.'.'.time() . '.' . $image->getClientOriginalExtension(); Storage::disk('public')->put($fileName, File::get($image)); $params['image_path'] = $fileName; $params['user_id'] = Sentinel::getUser()->id; $params['payment_type_id'] = 2; $params['status'] = 'Pending'; $params['request_nominal'] = $request->post('request_nominal'); $params['created_at'] = Carbon::now()->setTimezone('+7')->format('Y-m-d H:i:s'); $params['updated_at'] = Carbon::now()->setTimezone('+7')->format('Y-m-d H:i:s'); PaymentHistory::insert($params); return redirect('riwayat-keuangan'); } } <file_sep>/database/migrations/2018_11_01_070603_user_details.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class UserDetails extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::dropIfExists('user_details'); Schema::create('user_details', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id'); $table->bigInteger('money')->nullable(); $table->bigInteger('bank_account_number')->nullable(); $table->string('bank_account_name')->nullable(); $table->string('bank_account_office')->nullable(); $table->string('images_path')->nullable(); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // } } <file_sep>/app/Http/Controllers/RiwayatPermainanController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class RiwayatPermainanController extends Controller { public function index(){ return view('riwayat-permainan'); } } <file_sep>/app/PaymentHistory.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class PaymentHistory extends Model { protected $table = 'payment_historys'; protected $fillable = ['user_id','request_nominal','payment_type_id','status','image_path','image_path_confirm','created_at','updated_at']; public function payment_type(){ return $this->hasOne(PaymentType::class,'id','payment_type_id'); } public function user(){ return $this->hasOne(User::class,'id','user_id'); } public function user_detail(){ return $this->hasOne(UserDetails::class,'user_id','user_id'); } } <file_sep>/app/Room.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Room extends Model { protected $fillable = ['room_name','price_per_player','total_player','password','period','created_by','generate_id','total_player_join','period_start_date','created_at','updated_at','period_status']; } <file_sep>/app/Http/Controllers/NotificationController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Notification; use Sentinel; class NotificationController extends Controller { public function index(){ $data = Notification::where('user_id',Sentinel::getUser()->id)->orderBy('created_at','desc')->get(); return view('notification-user',compact('data')); } } <file_sep>/app/Http/Controllers/AccountController.php <?php namespace App\Http\Controllers; use Sentinel; use App\Users; use App\UserDetails; use Illuminate\Http\Request; use Storage; use Illuminate\Support\Facades\File; class AccountController extends Controller { public function index(){ $data = Users::where('id',Sentinel::getUser()->id)->with('user_details')->first(); return view('account-detail',compact('data')); } public function verification(Request $request){ $params = $request->except('_token','fileToUpload','login'); $image = $request->file('fileToUpload'); $fileName = Sentinel::getUser()->id.'.'.time() . '.' . $image->getClientOriginalExtension(); Storage::disk('public')->put($fileName, File::get($image)); $params['user_id'] = Sentinel::getUser()->id; $params['money'] = 0; $params['images_path'] = $fileName; UserDetails::create($params); return redirect()->back(); } } <file_sep>/app/Users.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use Sentinel; use App\UserDetails; use App\AdminImage; class Users extends \Cartalyst\Sentinel\Users\EloquentUser { use SoftDeletes; protected $table = 'users'; protected $fillable = ['first_name','last_name', 'username','email','last_login','birth_date','gender','is_verif','password','role_user','user_code']; protected $hidden = [ 'password', ]; protected $loginNames = ['username']; public function user_details(){ return $this->hasOne('App\UserDetails','user_id'); } public function getMoneyAttribute(){ return UserDetails::where('user_id',Sentinel::getUser()->id)->first() ? UserDetails::where('user_id',Sentinel::getUser()->id)->first()->money : 0; } public function admin_images(){ return $this->hasOne(AdminImage::class,'user_id','id'); } } <file_sep>/app/UserRoomPaymentHistory.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class UserRoomPaymentHistory extends Model { use SoftDeletes; protected $fillable = ['user_id','room_id','period_roll','status']; } <file_sep>/app/Http/Controllers/UserController.php <?php namespace App\Http\Controllers; use Mail; use Sentinel; use Carbon\Carbon; use Illuminate\Http\Request; use Illuminate\Support\Facades\Crypt; use Activation; use App\Users; use App\Http\Requests\registerRequest; use App\Http\Requests\forgotPasswordRequest; class UserController extends Controller { protected $_routeGroup = '/auth'; public function authenticate(Request $request){ try{ $authenticate = Sentinel::authenticate($request->except('_token')); if(!$authenticate){ return redirect()->back()->withErrors(['Nama Pengguna Atau Password Salah']); } return redirect('/'); }catch(\Exception $e){ if($e->getMessage() == 'Your account has not been activated yet.'){ return redirect()->back()->withErrors(['Aktivasi Email Anda Terlebih Dahulu']); } return redirect()->back(); } } public function registerUsers(registerRequest $request){ $credentials = $request->except('_token','confirmPassword'); $credentials['is_verif'] = 0; $credentials['role_user'] = 'user'; $credentials['user_code'] = 'AR-'.Carbon::now()->setTimezone('+7')->format('Ymd').'-'.rand(10000,99999); $register = Sentinel::register($credentials); $encrypt = Crypt::encryptString($register->id.'/'.Carbon::now()->setTimezone('+7')->format('Y-m-d H:i:s')); $url = $request->server->getHeaders()['ORIGIN'].'/auth/verifEmail/'.$encrypt; $data = array( 'id'=>$register->id, 'email'=>$credentials['email'], 'timeRegister'=>Carbon::now()->setTimezone('+7')->format('Y-m-d H:i:s'), 'url'=>$url, 'subject'=>'Active Your Email', 'page'=>'mail-verif' ); $senMail = $this->mail($data); return redirect($this->_routeGroup.'/login')->with('message', 'Silahkan cek email anda'); } public function emailVerification($callback){ $decrypted = Crypt::decryptString($callback); $explodeDecrypt = explode('/',$decrypted); $timeRequest = Carbon::parse($explodeDecrypt[1],'+7'); $timeNow = Carbon::now()->setTimezone('+7'); $timeDiff = $timeRequest->diffInMinutes($timeNow); if($timeDiff > 120){ return redirect($this->_routeGroup.'/expired'); } $user = Sentinel::findById($explodeDecrypt[0]); $activeUser = Activation::create($user); Activation::complete($user, $activeUser->code); return redirect($this->_routeGroup.'/login')->with('message', 'Verifikasi berhasil'); } public function logout(){ Sentinel::logout(); return redirect('/'); } public function forgotPassword(forgotPasswordRequest $request){ $email = $request->input('email'); $findUserByEmail = Users::where('email',$email)->first(); // jika tidak ditemukan user dengan email tersebut if(!$findUserByEmail) return redirect()->back(); $encrypt = Crypt::encryptString($findUserByEmail->id.'/'.Carbon::now()->setTimezone('+7')->format('Y-m-d H:i:s')); $url = $request->server->getHeaders()['ORIGIN'].'/auth/forgot-password-verification/'.$encrypt; $data = array( 'id'=>$findUserByEmail->id, 'email'=>$email, 'timeRegister'=>Carbon::now()->setTimezone('+7')->format('Y-m-d H:i:s'), 'url'=>$url, 'subject'=>'Forgot Password', 'page'=>'mail-forgot-password' ); $senMail = $this->mail($data); return redirect($this->_routeGroup.'/login')->with('message', 'Silahkan cek email anda'); } public function changePassword($callback){ $decrypted = Crypt::decryptString($callback); $explodeDecrypt = explode('/',$decrypted); $timeRequest = Carbon::parse($explodeDecrypt[1],'+7'); $timeNow = Carbon::now()->setTimezone('+7'); $timeDiff = $timeRequest->diffInMinutes($timeNow); if($timeDiff > 120){ return redirect($this->_routeGroup.'/expired'); } $user = Sentinel::findById($explodeDecrypt[0]); return view('change-password',compact('user')); } public function actionChangePassword(Request $request){ $user = Sentinel::findById($request->input('user_id')); Sentinel::update($user,$request->only('password')); return redirect($this->_routeGroup.'/login')->with('message', 'Password berhasil di ubah'); } public function mail($data){ Mail::send($data['page'], $data, function($message) use($data){ $message->to($data['email'], 'Email Verification') ->subject($data['subject']); $message->from('<EMAIL>','Info Arisen'); }); } }
91d2270d7cf5cb562f938962388815acf49140b0
[ "Markdown", "PHP" ]
24
PHP
syaifulislam/Arisen-development
6274ec4a4b16bb3e8a34712598ad764832eb1a99
7d0690b8cddd76df8bc3cc6158a1bc392b38af04
refs/heads/master
<repo_name>KyrieCham/concrete-chunklink<file_sep>/setup.py #!/usr/bin/env python # # Example usage # python setup.py install # from setuptools import setup setup( name='concrete_chunklink', version='0.1', description='Wrapper of the chunklink.pl script used by CoNLL-2000 for use on Concrete Communications.', author='<NAME>', author_email='<EMAIL>', url='http://www.cs.jhu.edu/~mrg/', packages=['concrete_chunklink'], install_requires = ['concrete>=4.4.0<4.8.0'], entry_points={ 'console_scripts': [ 'add_chunks = concrete_chunklink:main', ], }) <file_sep>/README.md Wrapper of the chunklink.pl script used by CoNLL-2000 for use on Concrete Communications. The chunklink.pl script was written by <NAME> with modifications by <NAME>. The original script is available along with a README describing its use. * http://ilk.uvt.nl/team/sabine/chunklink/chunklink_2-2-2000_for_conll.pl * http://ilk.uvt.nl/team/sabine/chunklink/README.html This wrapper was written in order to apply the chunking rules to parse trees annotated on Concrete data. For more information about Concrete see the Getting Started docs. * http://hltcoe.github.io/ # Requirements This library requires: - Perl 5.x - Python 2.7.x - concrete-python 4.3.x or 4.4.x To install concrete-python, use pip as below or see https://github.com/hltcoe/concrete-python for alternate installation instructions. pip install 'concrete>=4.4.0<4.8.0' # Running the add_chunks.py script To run the add_chunks.py script you can either pass in two file paths or two directory paths. python concrete_chunklink/add_chunks.py [--chunklink <path/to/chunklink.pl>] <input path> <output path> If using directories, they must both exists. If using two files, the input file must exist and the output file will be created or overwritten. The script is just a wrapper around a modified version of the chunklink which reads parses from STDIN. The script 'chunklink_2-2-2000_for_conll.pl' is found in the scripts/ directory. This perl script was created for the CoNLL-2000 shared task to convert the PTB to chunks. If you are running add_chunks.py without specifying the path to the chunklink script it will look in the './' and then './scripts/' to try to find it before failing. # Installation For most uses cases, there is no need to install. However, in case you want to use this library as a module, you can run the following: python setup.py install Doing so will also add the entry point 'add_chunks' to your PATH. <file_sep>/concrete_chunklink/add_chunks.py #!/usr/bin/env python # # Example usage: # python concrete_chunklink/add_chunks.py [--chunklink <path/to/chunklink.pl>] <input path> <output path> # ''' ''' import sys import os import optparse import zipfile import subprocess import re import logging import codecs import glob import argparse import json from thrift import TSerialization import concrete import concrete.util from concrete.inspect import get_tokenizations from concrete.inspect import penn_treebank_for_parse from concrete.util import concrete_uuid from concrete.util import read_communication_from_file from concrete.util import write_communication_to_file from concrete.validate import validate_communication from operator import attrgetter import time whitespace = re.compile(r"\s+") def add_chunks_to_dir(in_dir, out_dir, chunklink, fail_on_error): '''Reads a directory containing Communications, adds chunking information, and writes new files in the output directory containing the modified Communications. The directory is not searched recursively for files, only those at the top level are read. ''' if not os.path.isdir(in_dir): raise Exception("ERROR: input path is not a directory: " + in_dir) if not os.path.isdir(out_dir): raise Exception("ERROR: output path is not a directory: " + out_dir) for in_file in glob.glob(os.path.join(in_dir, "*")): logging.info("Processing: %s" % in_file) out_file = os.path.join(out_dir, os.path.basename(in_file)) add_chunks_to_file(in_file, out_file, chunklink, fail_on_error) def add_chunks_to_file(in_file, out_file, chunklink, fail_on_error): '''Reads a Communication file, adds chunking information, and writes a new Communication file containing the annotated version.''' # Deserialize comm = read_communication_from_file(in_file) # Add chunks num_chunked, num_sents = add_chunks_to_comm(comm, chunklink, fail_on_error) logging.info("Chunked %d / %d = %f" % (num_chunked, num_sents, float(num_chunked) / float(num_sents))) # Serialize write_communication_to_file(comm, out_file) def add_chunks_to_comm(comm, chunklink, fail_on_error): '''Converts the first constituency tree of each tokenization to chunks and adds them as a TokenTagging to the communication. comm - Communication to be annotated. chunklink - Path to the modified chunklink perl script. ''' num_sents = 0 num_chunked = 0 try: for tokenization in get_tokenizations(comm): num_sents += 1 try: if tokenization.parseList and len(tokenization.parseList) > 0: parse = tokenization.parseList[0] # Convert concrete Parse to a PTB style parse string to use as stdin for chunklink. ptb_str = '( ' + penn_treebank_for_parse(parse) + ' )\n' ptb_str = ptb_str.encode('ascii', 'replace') logging.debug("PTB string: " + ptb_str) # Run the chunklink script and capture the output. try: # We expect the chunklink script to be a modified version which can read a tree from stdin. p = subprocess.Popen(['perl', chunklink], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) stdouterr = p.communicate(input=ptb_str) chunk_str = stdouterr[0] chunk_err = stdouterr[1] logging.debug("Chunklink stdout:\n" + chunk_str) logging.debug("Chunklink stderr:\n" + chunk_err) chunk_tags = get_chunks(chunk_str) logging.debug("Chunk tags: " + str(chunk_tags)) if len(chunk_tags) != len(tokenization.tokenList.tokenList): raise Exception("ERROR: incorrect number of chunks. expected=%d actual=%d" % (len(tokenization.tokenList.tokenList), len(chunk_tags))) metadata = concrete.AnnotationMetadata() metadata.tool = "Chunklink Constituency Converter" metadata.timestamp = long(time.time()) # Extract the chunks column and create a TokenTagging from it. chunks = concrete.TokenTagging() chunks.uuid = concrete_uuid.generate_UUID() chunks.metadata = metadata chunks.taggingType = "CHUNK" chunks.taggedTokenList = [] for i, chunk in enumerate(chunk_tags): tt = concrete.TaggedToken() tt.tokenIndex = i tt.tag = chunk chunks.taggedTokenList.append(tt) # Add chunks to the list of TokenTaggings. if not tokenization.tokenTaggingList: tokenization.tokenTaggingList = [] tokenization.tokenTaggingList.append(chunks) num_chunked += 1 except subprocess.CalledProcessError as e: logging.error("Chunklink failed on tree: %s" % (ptb_str)) if fail_on_error: raise e except Exception as e: logging.exception("Chunking failed on tokenization") if fail_on_error: raise e except Exception as e: logging.exception("Chunking failed on Communication") if fail_on_error: raise e return num_chunked, num_sents def get_chunks(chunk_str): '''Gets the column of B-I-O tags denoting the chunks from the output of the chunklink script.''' global whitespace chunks = [] lines = chunk_str.split("\n") for line in lines: line = line.strip() if line == "" or line.startswith("#"): continue columns = whitespace.split(line) chunks.append(columns[3]) return chunks def main(): usage = "%prog [options] <input path> <output path>" logging.basicConfig(level=logging.INFO) parser = optparse.OptionParser(usage=usage) parser.add_option( '--fail_on_error', action="store_true", dest="fail_on_error", help="Whether to fail on errors.", default=True) parser.add_option( '--cont_on_error', action="store_false", dest="fail_on_error", help="Whether to continue on errors.") parser.add_option('-c', '--chunklink', help="Path to chunklink perl script") (options, args) = parser.parse_args(sys.argv) if len(args) != 3: parser.print_help() sys.exit(1) in_path = args[1] out_path = args[2] chunklink = options.chunklink if not chunklink: # Guess the location of the chunklink perl script chunklink = 'chunklink_2-2-2000_for_conll.pl' if not os.path.exists(chunklink): chunklink = 'scripts/chunklink_2-2-2000_for_conll.pl' if not os.path.exists(chunklink): raise Exception("Unable to find chunklink script. Specify with option --chunklink") if not os.path.exists(in_path): raise Exception("Input path doesn't exist: " + in_path) if not os.path.exists(chunklink): raise Exception("Chunklink script doesn't exist: " + chunklink) if options.fail_on_error: logging.debug("Exiting on errors.") else: logging.debug("Not exiting on errors.") if os.path.isdir(in_path): add_chunks_to_dir(in_path, out_path, chunklink, options.fail_on_error) else: add_chunks_to_file(in_path, out_path, chunklink, options.fail_on_error) if __name__ == "__main__": main()
06769b93e3a60769a8573d15f47dafae5cbc2d5e
[ "Markdown", "Python" ]
3
Python
KyrieCham/concrete-chunklink
dd94b4179832f3c80be293ccc8b00ef274d89474
af03918f231e323303b0b490ab541a37d9cee73c
refs/heads/master
<file_sep>package com.example.joon.instagramclone.Utils; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.support.annotation.NonNull; import android.util.Log; import android.widget.Toast; import com.example.joon.instagramclone.Home.HomeActivity; import com.example.joon.instagramclone.Model.Photo; import com.example.joon.instagramclone.Model.User; import com.example.joon.instagramclone.Model.UserAccountSettings; import com.example.joon.instagramclone.Model.UserSettings; import com.example.joon.instagramclone.Profile.AccountSettingActivity; import com.example.joon.instagramclone.R; import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class FirebaseMethods { private static final String TAG = "FirebaseMethods"; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthStateListener; private FirebaseDatabase mFirebaseDatabase; private DatabaseReference myRef; private StorageReference mStorageReference; private String userID; //vars private Context mContext; private double mPhotoUploadProgress = 0; public FirebaseMethods(Context context) { mContext = context; mAuth = FirebaseAuth.getInstance(); mFirebaseDatabase = FirebaseDatabase.getInstance(); myRef = mFirebaseDatabase.getReference(); mStorageReference = FirebaseStorage.getInstance().getReference(); if (mAuth.getCurrentUser() != null) { userID = mAuth.getCurrentUser().getUid(); } } public int getImageCount(DataSnapshot dataSnapshot) { int count = 0; for (DataSnapshot ds : dataSnapshot.child(mContext.getString(R.string.dbname_user_photos)) .child(FirebaseAuth.getInstance().getCurrentUser().getUid()).getChildren()) { count++; } return count; } public void uploadNewPhoto(String photoType, final String caption, final int imageCount, final String imgURL, Bitmap bm) { /** * save profile photo into the firebase database */ Log.d(TAG, "uploadNewPhoto: uploading new image photo"); FilePaths filepath = new FilePaths(); // case1) new photo if (photoType.equals(mContext.getString(R.string.new_photo))) { Log.d(TAG, "uploadNewPhoto: uploading new 'photo'."); String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid(); // same as userID, just not to cause another error final StorageReference storageReference = mStorageReference.child(filepath.FIREBASE_IMAGE_STORAGE + "/" + user_id + "/photo" + (imageCount + 1)); //conver image url to bitmap if (bm == null) { bm = ImageManager.getBitmap(imgURL); } byte[] bytes = ImageManager.getBytesFromBitmap(bm, 100); UploadTask uploadTask = null; uploadTask = storageReference.putBytes(bytes); uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.d(TAG, "onFailure: photo update faild" + e.getMessage()); Toast.makeText(mContext, "Photo update failed.", Toast.LENGTH_SHORT).show(); } }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { taskSnapshot.getTask().continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() { @Override public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception { if (!task.isSuccessful()) { throw task.getException(); } // Continue with the task to get the download URL return storageReference.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { if (task.isSuccessful()) { Uri downloadUri = task.getResult(); Toast.makeText(mContext, "photo upload success", Toast.LENGTH_SHORT).show(); /** * add the new photo to 'photos' and 'user_photos' */ addNewPhotoToDatabase(caption, downloadUri.toString()); //setProfilePhoto(downloadUri.toString()); } else { Toast.makeText(mContext, "failed to downlaod url", Toast.LENGTH_SHORT).show(); // Handle failures // ... } } }); /** * navigate to the main so the user can see updated photos */ Intent intent = new Intent(mContext, HomeActivity.class); mContext.startActivity(intent); } }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { double progress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount(); if (progress - 15 > mPhotoUploadProgress) { Toast.makeText(mContext, "photo upload progress: " + String.format("%.0f", progress) + "%", Toast.LENGTH_SHORT).show(); mPhotoUploadProgress = progress; } } }); } else if (photoType.equals(mContext.getString(R.string.profile_photo))) { // case2) new profile photo Log.d(TAG, "uploadNewPhoto: uploading new PROFILE photo"); String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid(); final StorageReference storageReference = mStorageReference .child(filepath.FIREBASE_IMAGE_STORAGE + "/" + user_id + "/profile_photo"); //convert image url to bitmap if (bm == null) { bm = ImageManager.getBitmap(imgURL); } byte[] bytes = ImageManager.getBytesFromBitmap(bm, 100); UploadTask uploadTask = null; uploadTask = storageReference.putBytes(bytes); uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { taskSnapshot.getTask().continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() { @Override public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception { if (!task.isSuccessful()) { throw task.getException(); } // Continue with the task to get the download URL return storageReference.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { if (task.isSuccessful()) { Uri downloadUri = task.getResult(); setProfilePhoto(downloadUri.toString()); } else { Toast.makeText(mContext, "failed to downlaod url", Toast.LENGTH_SHORT).show(); // Handle failures // ... } } }); ((AccountSettingActivity) mContext).setViewPager( ((AccountSettingActivity) mContext).pagerAdapter .getFragmentNumber(mContext.getString(R.string.edit_profile_fragment)) ); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Handle any errors Toast.makeText(mContext, "updating the profile photo failed..", Toast.LENGTH_SHORT).show(); } }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { double progress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount(); if (progress - 15 > mPhotoUploadProgress) { Toast.makeText(mContext, "photo upload progress: " + String.format("%.0f", progress) + "%", Toast.LENGTH_SHORT).show(); mPhotoUploadProgress = progress; } } }); } } /** * @param URL */ private void setProfilePhoto(String URL) { Log.d(TAG, "setProfilePhoto: setting new profile photo" + URL); myRef.child(mContext.getString(R.string.dbname_user_accounting_settings)) .child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .child(mContext.getString(R.string.profile_photo)) .setValue(URL); } private String getTimestamp() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("US/Pacific")); return sdf.format(new Date()); } private void addNewPhotoToDatabase(String caption, String url) { Log.d(TAG, "addNewPhotoToDatabase: add photo to the dataabse."); String tags = StringManipulation.getTags(caption); // save in the photo model String newPhotoKey = myRef.child(mContext.getString(R.string.dbname_photos)).push().getKey(); Photo photo = new Photo(); photo.setCaption(caption); photo.setDate_created(getTimestamp()); photo.setImage_path(url); photo.setTags(tags); photo.setUser_id(FirebaseAuth.getInstance().getCurrentUser().getUid()); photo.setPhoto_id(newPhotoKey); // insert data to the firebase myRef.child(mContext.getString(R.string.dbname_user_photos)) .child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .child(newPhotoKey).setValue(photo); myRef.child(mContext.getString(R.string.dbname_photos)) .child(newPhotoKey).setValue(photo); } public void updateUsername(String username) { Log.d(TAG, "updateUsername: updating username to : " + username); myRef.child(mContext.getString(R.string.dbname_users)) .child(userID) .child(mContext.getString(R.string.field_username)) .setValue(username); myRef.child(mContext.getString(R.string.dbname_user_accounting_settings)) .child(userID) .child(mContext.getString(R.string.field_username)) .setValue(username); } public void updateEmail(String email) { Log.d(TAG, "updateUsername: updating email to : " + email); myRef.child(mContext.getString(R.string.dbname_users)) .child(userID) .child(mContext.getString(R.string.field_email)) .setValue(email); } public void updateUserAccountSettings(String displayName, String website, String description, long phoneNumber) { if (displayName != null) { myRef.child(mContext.getString(R.string.dbname_user_accounting_settings)) .child(userID) .child(mContext.getString(R.string.field_display_name)) .setValue(displayName); } if (website != null) { myRef.child(mContext.getString(R.string.dbname_user_accounting_settings)) .child(userID) .child(mContext.getString(R.string.field_website)) .setValue(website); } if (description != null) { myRef.child(mContext.getString(R.string.dbname_user_accounting_settings)) .child(userID) .child(mContext.getString(R.string.field_description)) .setValue(description); } if (phoneNumber != 0) { myRef.child(mContext.getString(R.string.dbname_users)) .child(userID) .child(mContext.getString(R.string.field_phone_number)) .setValue(phoneNumber); } } // public boolean checkIfUsernameExists(String username, DataSnapshot dataSnapshot) { // Log.d(TAG, "checkIfUsernameExists: check if username already exists"); // User user = new User(); // // for (DataSnapshot ds : dataSnapshot.child(userID).getChildren()) { // Log.d(TAG, "checkIfUsernameExists: datasnapshot" + ds); // // user.setUsername(ds.getValue(User.class).getUsername()); // Log.d(TAG, "checkIfUsernameExists: username: " + user.getUsername()); // // if (StringManipulation.expandUsername(user.getUsername()).equals(username)) { // Log.d(TAG, "checkIfUsernameExists: FOUND A MATCH: " + user.getUsername()); // return true; // } // } // return false; // } public void registerNewEmail(final String username, final String email, String password) { mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "createUserWithEmail:success"); Toast.makeText(mContext, "Authentication Success.", Toast.LENGTH_SHORT).show(); // Send verification email sendVerificationEmail(); userID = mAuth.getCurrentUser().getUid(); Log.d(TAG, "onComplete: auth state changed" + userID); } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.getException()); Toast.makeText(mContext, "Authentication failed.", Toast.LENGTH_SHORT).show(); } } }); } /** * send verification when registration is successful */ private void sendVerificationEmail() { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(mContext, "Verification email is sent, check your email", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(mContext, "Can't send verification email", Toast.LENGTH_SHORT).show(); } } }); } } /** * Add new user's info to the users node in the firebase database * Add new user's info to the user_account_settings node in the firebase database * * @param email * @param username * @param description * @param website * @param profile_photo */ public void addNewUser(String email, String username, String description, String website, String profile_photo) { User user = new User(userID, 1, email, StringManipulation.condenseUsername(username)); myRef.child(mContext.getString(R.string.dbname_users)) .child(userID) .setValue(user); UserAccountSettings settings = new UserAccountSettings(description, username, 0, 0, 0, StringManipulation.condenseUsername(username), profile_photo, website,userID); myRef.child(mContext.getString(R.string.dbname_user_accounting_settings)) .child(userID) .setValue(settings); } /** * retrieve the account settings for the user currently logged in. * data base : user_account_settings * * @param dataSnapshot * @return */ public UserSettings getUserSettings(DataSnapshot dataSnapshot) { //Log.d(TAG, "getUserAccountSettings: retrieving user account settings from database"+dataSnapshot); UserAccountSettings settings = new UserAccountSettings(); User user = new User(); // loop through nodes(users and user_account_settings) for (DataSnapshot ds : dataSnapshot.getChildren()) { if (ds.getKey().equals(mContext.getString(R.string.dbname_user_accounting_settings))) { Log.d(TAG, "getUserAccountSettings: datasnapshot" + ds); try { settings.setDisplay_name( ds.child(userID) .getValue(UserAccountSettings.class) .getDisplay_name() ); settings.setUsername( ds.child(userID) .getValue(UserAccountSettings.class) .getUsername() ); settings.setWebsite( ds.child(userID) .getValue(UserAccountSettings.class) .getWebsite() ); settings.setDescription( ds.child(userID) .getValue(UserAccountSettings.class) .getDescription() ); settings.setProfile_photo( ds.child(userID) .getValue(UserAccountSettings.class) .getProfile_photo() ); settings.setPost( ds.child(userID) .getValue(UserAccountSettings.class) .getPost() ); settings.setFollowers( ds.child(userID) .getValue(UserAccountSettings.class) .getFollowers() ); settings.setFollowing( ds.child(userID) .getValue(UserAccountSettings.class) .getFollowing() ); Log.d(TAG, "getUserSettings: retrieved user_account_settings information " + settings.toString()); } catch (NullPointerException e) { Log.e(TAG, "getUserAccountSettings: NullPointerException" + e.getMessage()); } } // users node if (ds.getKey().equals(mContext.getString(R.string.dbname_users))) { try { Log.d(TAG, "getUserAccountSettings: datasnapshot: " + ds); user.setUsername( ds.child(userID) .getValue(User.class) .getUsername() ); user.setEmail( ds.child(userID) .getValue(User.class) .getEmail() ); user.setPhone_number( ds.child(userID) .getValue(User.class) .getPhone_number() ); user.setUser_id( ds.child(userID) .getValue(User.class) .getUser_id() ); Log.d(TAG, "getUserAccountSettings: retrieved users information: " + user.toString()); } catch (NullPointerException e) { Log.e(TAG, "getUserAccountSettings: NullPointerException" + e.getMessage()); } } } /** * return as UserSettings.. work?? ;; */ return new UserSettings(user, settings); } } <file_sep>package com.example.joon.instagramclone.Utils; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.joon.instagramclone.Model.Like; import com.example.joon.instagramclone.Model.Photo; import com.example.joon.instagramclone.Model.User; import com.example.joon.instagramclone.Model.UserAccountSettings; import com.example.joon.instagramclone.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class ViewPostFragment extends Fragment{ private static final String TAG = "ViewPostFragment"; //widgets private SquareImageView mPostImage; private BottomNavigationViewEx bottomNavigationView; private TextView mBackLabel, mCaption, mUsername, mTimestamp,mLikes; private ImageView mBackArrow, mEllipses, mHeartRed, mHeartWhite, mProfileImage, mComment; //firebase private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthStateListener; private FirebaseDatabase mFirebaseDatabase; private DatabaseReference myRef; private FirebaseMethods mFirebaseMethods; //vars private Photo mPhoto; private int mActivityNumber =0; private String photoUsername = ""; private String profilePhotoUrl = ""; private UserAccountSettings mUserAccountSettings; private GestureDetector mGestureDetector; private Heart mHeart; private StringBuilder mUsers; private Boolean mLikedByCurrentUser; private String mLikeString; private User mCurrentUser; public interface OnCommentThreadSelectedListener{ void OnCommentThreadSelectedListener(Photo photo); } OnCommentThreadSelectedListener mOnCommentThreadSelectedListener; public ViewPostFragment(){ super(); setArguments(new Bundle()); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_view_post, container, false); mPostImage = view.findViewById(R.id.post_image); bottomNavigationView = view.findViewById(R.id.bottomNavBar); mBackArrow = view.findViewById(R.id.ivBackArrow); mBackLabel = view.findViewById(R.id.tvBackLabel); mCaption = view.findViewById(R.id.image_caption); mUsername = view.findViewById(R.id.username); mTimestamp = view.findViewById(R.id.image_time_posted); mEllipses = view.findViewById(R.id.ivEllipses); mHeartRed = view.findViewById(R.id.image_heart_red); mHeartWhite = view.findViewById(R.id.image_heart); mProfileImage = view.findViewById(R.id.profile_photo); mLikes = view.findViewById(R.id.tv_likes); mComment = view.findViewById(R.id.speech_bubble); mHeart = new Heart(mHeartWhite, mHeartRed); mGestureDetector = new GestureDetector(getActivity(), new GestureListener()); try{ mPhoto = getPhotoFromBundle(); UniversalImageLoader.setImage(mPhoto.getImage_path(), mPostImage, null,""); mActivityNumber = getActivityNumberFromBundle(); getCurrentUser(); getPhotoDetails(); } catch (NullPointerException e){ Log.e(TAG, "onCreateView: NullPointerException"+ e.getMessage()); } setupFirebaseAuth(); setupBottomNavigationView(); return view; } private void getCurrentUser(){ Log.d(TAG, "getCurrentUser: getting the current user"); DatabaseReference reference = FirebaseDatabase.getInstance().getReference(); Query query = reference.child(getString(R.string.dbname_users)) .orderByChild(getString(R.string.field_user_id)) .equalTo(FirebaseAuth.getInstance().getCurrentUser().getUid()); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for(DataSnapshot ds : dataSnapshot.getChildren()){ mCurrentUser = ds.getValue(User.class); } getLikesString(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void getLikesString(){ Log.d(TAG, "getLikesString: getting likes string"); DatabaseReference reference = FirebaseDatabase.getInstance().getReference(); Query query = reference .child(getString(R.string.dbname_photos)) .child(mPhoto.getPhoto_id()) .child(getString(R.string.field_likes)); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { mUsers = new StringBuilder(); for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){ DatabaseReference reference = FirebaseDatabase.getInstance().getReference(); Query query = reference .child(getString(R.string.dbname_users)) .orderByChild(getString(R.string.field_user_id)) .equalTo(singleSnapshot.getValue(Like.class).getUser_id()); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){ Log.d(TAG, "onDataChange: found like: " + singleSnapshot.getValue(User.class).getUsername()); mUsers.append(singleSnapshot.getValue(User.class).getUsername()); mUsers.append(","); } String[] splitUsers = mUsers.toString().split(","); if(mUsers.toString().contains(mCurrentUser.getUsername())){ mLikedByCurrentUser = true; }else{ mLikedByCurrentUser = false; } int length = splitUsers.length; if(length == 1){ mLikeString = "Like by "+splitUsers[0]; } else if(length == 2){ mLikeString = "Like by "+splitUsers[0]+" and "+splitUsers[1]; } else if(length == 3){ mLikeString = "Like by "+splitUsers[0]+", "+splitUsers[1]+" and "+splitUsers[2]; } else if(length >= 4){ mLikeString = "Like by "+splitUsers[0]+", "+splitUsers[1]+" and "+(splitUsers.length-3)+" others"; } setupWidgets(); } @Override public void onCancelled(DatabaseError databaseError) { } }); } if(!dataSnapshot.exists()){ mLikeString=""; mLikedByCurrentUser=false; setupWidgets(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } /** * class for gesture related to toggle */ public class GestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onDown(MotionEvent e) { Log.d(TAG, "onDown: white heart touch detected."); return true; } @Override public boolean onDoubleTap(MotionEvent e) { Log.d(TAG, "onDoubleTap: double tap detected."); DatabaseReference reference = FirebaseDatabase.getInstance().getReference(); Query query = reference .child(getString(R.string.dbname_photos)) .child(mPhoto.getPhoto_id()) .child(getString(R.string.field_likes)); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) { //case1: Then user already liked the photo String keyID = singleSnapshot.getKey(); if(mLikedByCurrentUser && singleSnapshot.getValue(Like.class).getUser_id() .equals(FirebaseAuth.getInstance().getCurrentUser().getUid())){ myRef.child(getString(R.string.dbname_photos)) .child(mPhoto.getPhoto_id()) .child(getString(R.string.field_likes)) .child(keyID) .removeValue(); myRef.child(getString(R.string.dbname_user_photos)) .child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .child(mPhoto.getPhoto_id()) .child(getString(R.string.field_likes)) .child(keyID) .removeValue(); mHeart.toggleLike(); getLikesString(); } //case2: The user has not liked the photo else if(!mLikedByCurrentUser){ addNewLike(); break; } } if(!dataSnapshot.exists()){ addNewLike(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); return true; } } private void addNewLike() { Log.d(TAG, "addNewLike: adding new like"); String newLikeID = myRef.push().getKey(); Like like = new Like(); like.setUser_id(FirebaseAuth.getInstance().getCurrentUser().getUid()); myRef.child(getString(R.string.dbname_photos)) .child(mPhoto.getPhoto_id()) .child(getString(R.string.field_likes)) .child(newLikeID) .setValue(like); myRef.child(getString(R.string.dbname_photos)) .child(mPhoto.getUser_id()) .child(mPhoto.getPhoto_id()) .child(getString(R.string.field_likes)) .child(newLikeID) .setValue(like); mHeart.toggleLike(); getLikesString(); } private void getPhotoDetails(){ Log.d(TAG, "getPhotoDetails: retrieving photo details."); DatabaseReference reference = FirebaseDatabase.getInstance().getReference(); Query query = reference.child(getString(R.string.dbname_user_accounting_settings)) .orderByChild(getString(R.string.field_user_id)) .equalTo(mPhoto.getUser_id()); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for(DataSnapshot ds : dataSnapshot.getChildren()){ mUserAccountSettings = ds.getValue(UserAccountSettings.class); } //setupWidgets(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void setupWidgets() { String timestampDiff = getTimestampDifference(); if(!timestampDiff.equals("0")){ mTimestamp.setText(timestampDiff+" Days Ago"); } else{ mTimestamp.setText(R.string.string_today); } UniversalImageLoader.setImage(mUserAccountSettings.getProfile_photo(), mProfileImage, null, ""); mUsername.setText(mUserAccountSettings.getUsername()); mLikes.setText(mLikeString); mBackArrow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try{ getActivity().getSupportFragmentManager().popBackStack(); }catch (NullPointerException e){ Log.e(TAG, "onClick: NullPointerException"+e.getMessage() ); } //getActivity().finish(); } }); mComment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "onClick: navigating to the comment page"); mOnCommentThreadSelectedListener.OnCommentThreadSelectedListener(mPhoto); } }); if(mLikedByCurrentUser){ mHeartWhite.setVisibility(View.GONE); mHeartRed.setVisibility(View.VISIBLE); mHeartRed.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return mGestureDetector.onTouchEvent(event); } }); } else{ mHeartWhite.setVisibility(View.VISIBLE); mHeartRed.setVisibility(View.GONE); mHeartWhite.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return mGestureDetector.onTouchEvent(event); } }); } } public String getTimestampDifference() { Log.d(TAG, "getTimestampDifference: "); String differnce = ""; Calendar calendar = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("US/Pacific")); Date today = calendar.getTime(); sdf.format(today); Date timestamp; final String photoTimestamp = mPhoto.getDate_created(); try{ timestamp = sdf.parse(photoTimestamp); differnce = String.valueOf(Math.round(((today.getTime()- timestamp.getTime())/1000/60/60/24))); }catch (ParseException e){ Log.e(TAG, "getTimestampDifference: ParseException"+e.getMessage() ); } return differnce; } private Photo getPhotoFromBundle() { Log.d(TAG, "getPhotoFromBundle: arguments"+getArguments()); Bundle bundle = this.getArguments(); if(bundle!=null){ return bundle.getParcelable(getString(R.string.photo)); } else { return null; } } private int getActivityNumberFromBundle() { Log.d(TAG, "getPhotoFromBundle: arguments"+getArguments()); Bundle bundle = this.getArguments(); if(bundle!=null){ return bundle.getInt(getString(R.string.activity_number)); } else { return 0; } } /** * ----------------------firebase------------------------ */ /** * * check to see if @param user is logged in. */ private void setupFirebaseAuth(){ Log.d(TAG, "setupFirebase: setting up firebase auth"); mAuth = FirebaseAuth.getInstance(); mFirebaseDatabase = FirebaseDatabase.getInstance(); myRef = mFirebaseDatabase.getReference(); mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth){ FirebaseUser user = firebaseAuth.getCurrentUser(); if(user!=null){ Log.d(TAG, "onAuthStateChanged: sign in"+user.getUid()); } else{ Log.d(TAG, "onAuthStateChanged: sign out"); } } }; } @Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. mAuth.addAuthStateListener(mAuthStateListener); } @Override public void onStop() { super.onStop(); // Check if user is signed in (non-null) and update UI accordingly. if(mAuthStateListener!=null) mAuth.removeAuthStateListener(mAuthStateListener); } /** * ----------------------firebase------------------------ */ @Override public void onAttach(Context context) { super.onAttach(context); try { mOnCommentThreadSelectedListener = (OnCommentThreadSelectedListener) getActivity(); } catch (ClassCastException e) { Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage()); } } private void setupBottomNavigationView(){ Log.d(TAG, "setup bottom navigation view"); BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationView); BottomNavigationViewHelper.enableNavigation(getActivity(),getActivity(), bottomNavigationView); Menu menu = bottomNavigationView.getMenu(); MenuItem menuItem = menu.getItem(mActivityNumber); menuItem.setChecked(true); } }
622bf90679692c63e178c69ffb4cc09eae340c90
[ "Java" ]
2
Java
tonext-level/android-instagram-clone
6a4ad6649d980c067d815cf09b3fc398c749b9b8
1c51f57871b4ad2b35c8387e35309512546cd2fc
refs/heads/master
<file_sep>package com.pinduo.auto.error import java.lang.RuntimeException class AppException:RuntimeException { constructor():super() constructor(message:String):super(message) }<file_sep>package com.pinduo.auto.app import android.app.Application import androidx.lifecycle.ProcessLifecycleOwner import cn.vove7.andro_accessibility_api.AccessibilityApi import com.birbit.android.jobqueue.JobManager import com.birbit.android.jobqueue.config.Configuration import com.blankj.utilcode.util.AppUtils import com.blankj.utilcode.util.SPUtils import com.blankj.utilcode.util.ToastUtils import com.blankj.utilcode.util.Utils import com.lzy.okgo.OkGo import com.pinduo.auto.app.manager.AppLifeCycleCallBack import com.pinduo.auto.app.manager.ForebackLifeObserver import com.pinduo.auto.receiver.USBBroadcastReceiver import com.pinduo.auto.service.MyAccessibilityService import com.pinduo.auto.utils.LogUtils import com.pinduo.auto.utils.ToastUtil import com.pinduo.auto.utils.UiHandler import com.pinduo.auto.widget.update.OKHttpUpdateHttpService import com.xuexiang.xupdate.XUpdate import com.xuexiang.xupdate.entity.UpdateError.ERROR.CHECK_NO_NEW_VERSION import com.xuexiang.xupdate.utils.UpdateUtils class MyApplication : Application() { //Main handler private lateinit var uiHandler: UiHandler // 工作队列管理器 private lateinit var jobManager: JobManager private var imei:String = "" //屏幕锁屏唤醒 电量状态 广播 private val usbBroadcastReceiver: USBBroadcastReceiver by lazy { USBBroadcastReceiver() } companion object { @JvmStatic lateinit var instance: MyApplication private set } fun getUiHandler(): UiHandler { return uiHandler } fun getJobManager(): JobManager { return jobManager } fun getIMEI():String{ return imei } fun setIMEI(i:String){ this.imei = i } override fun onCreate() { super.onCreate() instance = this this.uiHandler = UiHandler() configureJobManager() initConfig() } private fun configureJobManager() { jobManager = JobManager(Configuration.Builder(this).build()) } private fun initConfig() { Utils.init(this) SPUtils.getInstance(AppUtils.getAppPackageName()) OkGo.getInstance().init(this) registerActivityLifecycleCallbacks(AppLifeCycleCallBack()) ProcessLifecycleOwner.get().lifecycle.addObserver(ForebackLifeObserver()) AccessibilityApi.apply { BASE_SERVICE_CLS = MyAccessibilityService::class.java // 基础无障碍 GESTURE_SERVICE_CLS = MyAccessibilityService::class.java // 高级无障碍 } USBBroadcastReceiver.registerReceiver(this, usbBroadcastReceiver) XUpdate.get() .debug(true) .isWifiOnly(false) //默认设置只在wifi下检查版本更新 .isGet(true) //默认设置使用get请求检查版本 .isAutoMode(false) //默认设置非自动模式,可根据具体使用配置 // .param("versionCode", UpdateUtils.getVersionCode(this)) //设置默认公共请求参数 // .param("appKey", packageName) .setOnUpdateFailureListener { error -> //设置版本更新出错的监听 if (error.code != CHECK_NO_NEW_VERSION) { //对不同错误进行处理 ToastUtil.showToast(error.toString()) } } .supportSilentInstall(true) //设置是否支持静默安装,默认是true .setIUpdateHttpService(OKHttpUpdateHttpService()) //这个必须设置!实现网络请求功能。 .init(this) } override fun onTerminate() { super.onTerminate() USBBroadcastReceiver.unregisterReceiver(this, usbBroadcastReceiver) LogUtils.logGGQ("app onTerminate") } }<file_sep>package com.pinduo.auto.ui import android.os.Bundle import com.pinduo.auto.R import com.pinduo.auto.base.BaseActivity import kotlinx.android.synthetic.main.activity_test.* class TestActivity : BaseActivity(R.layout.activity_test) { override fun initData(savedInstanceState: Bundle?) { btn_test.setOnClickListener { xUpdate() } } private val url: String = "https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk" private fun xUpdate() { } }<file_sep>package com.pinduo.auto.core.job import com.birbit.android.jobqueue.Job import com.birbit.android.jobqueue.Params import com.pinduo.auto.core.data.TaskData //job 抽象类 abstract class BaseJob(val data: TaskData): Job(Params(PRIORITY).requireNetwork().persist().groupBy("job").addTags("job")) { companion object { const val PRIORITY = 1 } override fun getRetryLimit(): Int { // return super.getRetryLimit() return 0 } }<file_sep>package com.pinduo.auto.ui import android.content.Intent import android.os.Bundle import android.text.TextUtils import com.blankj.utilcode.util.FileIOUtils import com.blankj.utilcode.util.FileUtils import com.blankj.utilcode.util.NetworkUtils import com.google.gson.Gson import com.lzy.okgo.OkGo import com.lzy.okgo.callback.StringCallback import com.lzy.okgo.model.Response import com.pinduo.auto.R import com.pinduo.auto.app.MyApplication import com.pinduo.auto.app.global.Constants import com.pinduo.auto.base.BaseActivity import com.pinduo.auto.db.AppDatabase import com.pinduo.auto.db.dao.Info import com.pinduo.auto.extensions.isResultSuccess import com.pinduo.auto.http.api.ApiService import com.pinduo.auto.http.entity.CommonEntity import com.pinduo.auto.utils.IMEIUtils import com.pinduo.auto.utils.LogUtils import kotlinx.android.synthetic.main.activity_account.* class AccountActivity : BaseActivity(R.layout.activity_account) { override fun initData(savedInstanceState: Bundle?) { tv_imei.setText(IMEIUtils.getDeviceId()) btn_bind.setOnClickListener { val username:String? = et_username.text.toString().trim() val imei:String? = tv_imei.text.toString().trim() LogUtils.logGGQ("username:${username} --- imei:${imei}") if(!NetworkUtils.isConnected()){ showTopMessage("网络异常!") return@setOnClickListener } if(TextUtils.isEmpty(username) || TextUtils.isEmpty(imei)){ showTopMessage("请输入绑定的号码") return@setOnClickListener } httpBindDevice(username!!,imei!!) } } private fun httpBindDevice(username: String, imei: String) { OkGo.get<String>(ApiService.URL_BINDDEVICE) .tag(this) .params(Constants.ApiParams.USERNAME,username) .params(Constants.ApiParams.IMEI,imei) .execute(object : StringCallback(){ override fun onSuccess(response: Response<String>?) { try { response?.let { // 非空 val result:String? = it.body() result?.let {it1 -> val entity: CommonEntity? = Gson().fromJson<CommonEntity>(it1,CommonEntity::class.java) entity?.let {it2 -> if(it2.code.isResultSuccess()){ goHome(username,imei) }else{ showTopMessage(it2.msg) } }?:let { showTopMessage("绑定设备出错!") } }?:let { showTopMessage("绑定设备出错!") } }?:let { //空 showTopMessage("绑定设备出错!") } }catch (e:Exception){ e.stackTrace showTopMessage("绑定设备出错!") } } override fun onError(response: Response<String>?) { super.onError(response) showTopMessage("绑定设备错误!") } }) } private fun goHome(username: String,imei: String) { if (FileUtils.createOrExistsFile(Constants.Path.IMEI_PATH)) { if(FileIOUtils.writeFileFromString(Constants.Path.IMEI_PATH,imei)){ MyApplication.instance.setIMEI(imei) val info = Info().apply { this.imei = imei this.username = username this.userconfig = "篮球" } AppDatabase.getInstance(MyApplication.instance).infoDao().insertInfo(info) startActivity(Intent(AccountActivity@this,HomeActivity::class.java)) this.finish() }else{ showTopMessage("写入文件出错!") } } } }<file_sep>package com.pinduo.auto.utils import android.content.Context import android.provider.Settings import android.text.TextUtils import com.pinduo.auto.service.MyAccessibilityService class AccessibilityServiceUtils { companion object{ fun isAccessibilitySettingsOn(context: Context): Boolean { var accessibilityEnabled = 0 val service = context.packageName + "/" + MyAccessibilityService::class.java.canonicalName try { accessibilityEnabled = Settings.Secure.getInt( context.applicationContext.contentResolver, Settings.Secure.ACCESSIBILITY_ENABLED ) } catch (e: Settings.SettingNotFoundException) { //Log.e(TAG, "Error finding setting, default accessibility to not found: " + e.message) } val mStringColonSplitter = TextUtils.SimpleStringSplitter(':') if (accessibilityEnabled == 1) { val settingValue = Settings.Secure.getString( context.applicationContext.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES ) if (settingValue != null) { mStringColonSplitter.setString(settingValue) while (mStringColonSplitter.hasNext()) { val accessibilityService = mStringColonSplitter.next() if (accessibilityService.equals(service, ignoreCase = true)) { return true } } } } else { //Log.v(TAG, "***ACCESSIBILITY IS DISABLED***") } return false } } }<file_sep>package com.pinduo.auto.utils import android.text.TextUtils import android.view.Gravity import com.blankj.utilcode.util.ColorUtils import com.pinduo.auto.R import com.blankj.utilcode.util.ToastUtils as Toast class ToastUtil { companion object { @JvmStatic fun showToast(s: String?) { if (!TextUtils.isEmpty(s)) { Toast.setBgColor(ColorUtils.getColor(R.color.color_toast)) Toast.showShort(s) } } @JvmStatic fun showTipToast(s: String?) { if (!TextUtils.isEmpty(s)) { Toast.setBgColor(ColorUtils.getColor(R.color.color_toast)) Toast.setGravity(Gravity.CENTER,0,0) Toast.showShort(s) } } } }<file_sep>package com.pinduo.auto.base import android.os.Bundle import android.text.TextUtils import android.view.View import android.widget.TextView import androidx.annotation.LayoutRes import androidx.appcompat.app.AppCompatActivity import com.irozon.sneaker.Sneaker import com.pinduo.auto.R import com.pinduo.auto.utils.Event import com.pinduo.auto.utils.EventBusUtils import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode abstract class BaseActivity(@LayoutRes layoutId:Int) : AppCompatActivity(layoutId), IView { abstract fun initData(savedInstanceState: Bundle?): Unit open fun hasUsedEventBus(): Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (hasUsedEventBus()) { EventBusUtils.register(this) } initData(savedInstanceState) } /** * 顶部提示消息 */ fun showTopMessage(msg: String?) { if (!TextUtils.isEmpty(msg)) { val sneaker = Sneaker.with(this) // Activity, Fragment or ViewGroup val view: View = this.layoutInflater.inflate(R.layout.sneaker_view, sneaker.getView(), false) view.findViewById<TextView>(R.id.tv_message).text = msg sneaker.sneakCustom(view) } } /** * 接收到普通的Event * 封装MAIN线程模式,子类可重写 onEvnetBusReceive, */ @Subscribe(threadMode = ThreadMode.MAIN) open fun <T> onEventBusReceive(event: Event<T>?) { if (event != null) { onEventBusDispense(event) } } /** * 接收到粘性的Event * 封装MAIN线程模式,子类可重写 onStickyEvnetBusReceive, */ @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) open fun <T> onStickyEventBusReceive(event: Event<T>?) { if (event != null) { onStickyEventBusDispense(event) } } /** * 子类重写onEventBusDispense,处理接收到的普通事件 */ open fun <T> onEventBusDispense(event: Event<T>) {} /** * 子类重写onStickyEventBusDispense,处理接收到的粘性事件 */ open fun <T> onStickyEventBusDispense(event: Event<T>) {} override fun onDestroy() { super.onDestroy() if (hasUsedEventBus()) { EventBusUtils.unregister(this) } } }<file_sep>package com.pinduo.auto.im import com.pinduo.auto.http.entity.TaskEntity interface OnSocketListener { fun call(entity: TaskEntity) }<file_sep>package com.pinduo.auto.widget.update; import android.util.SparseArray; import androidx.annotation.NonNull; import com.blankj.utilcode.util.AppUtils; import com.blankj.utilcode.util.GsonUtils; import com.pinduo.auto.utils.LogUtils; import com.xuexiang.xupdate.entity.UpdateEntity; import com.xuexiang.xupdate.listener.IUpdateParseCallback; import com.xuexiang.xupdate.proxy.IUpdateParser; import java.util.ArrayList; /** * 自定义更新解析器 * * @author xuexiang * @since 2018/7/12 下午3:46 */ public class CustomUpdateParser implements IUpdateParser { @Override public UpdateEntity parseJson(String json) throws Exception { return getParseResult(json); } private UpdateEntity getParseResult(String json) { LogUtils.logGGQ("版本更新:"+json); VersionInfo result = GsonUtils.fromJson(json, VersionInfo.class); if (result != null && result.getCode() == 200 && result.getData() != null) { boolean hasUpdate = true; //是否有新版本 boolean isIgnorable = false;//是否可忽略该版本 int versionCode = result.getData().getVersion_code(); //版本号 String versionName = AppUtils.getAppVersionName(); //版本名 String updateContent = "新版本"; //更新内容 // String apkUrl = result.getData().getApk_url(); String apkUrl = "http://cc.pinduocm.com/apkDownload"; // String apkUrl = "http://kf.pinduocm.com/apkdownload"; // String apkUrl = "https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk"; Long apkSize = 0L; return new UpdateEntity() .setHasUpdate(hasUpdate) .setIsIgnorable(isIgnorable) .setVersionCode(versionCode) .setVersionName("新") .setUpdateContent(updateContent) .setDownloadUrl(apkUrl) .setSize(apkSize); } return null; } @Override public void parseJson(String json, @NonNull IUpdateParseCallback callback) throws Exception { //当isAsyncParser为 true时调用该方法, 所以当isAsyncParser为false可以不实现 callback.onParseResult(getParseResult(json)); } @Override public boolean isAsyncParser() { return false; } } <file_sep>package com.pinduo.auto.core.ids import com.pinduo.auto.utils.TaskUtils //抖音 版本区分的id 不是最优方案 class DouyinIds { companion object{ private const val baseId = "com.ss.android.ugc.aweme:id/" fun getb82():String{ if(!TaskUtils.isDouyin1270()){ return baseId+"b2c" } return baseId+"b82" } fun getb9q():String{ if(!TaskUtils.isDouyin1270()){ return baseId+"b40" } return baseId+"b9q" } fun getfvs():String{ if(!TaskUtils.isDouyin1270()){ return baseId+"fga" } return baseId+"fvs" } fun getfhq():String{ if(!TaskUtils.isDouyin1270()){ return baseId+"f3t" } return baseId+"fhq" } fun getfh9():String{ if(!TaskUtils.isDouyin1270()){ return baseId+"f3b" } return baseId+"fh9" } fun getd_e():String{ if(!TaskUtils.isDouyin1270()){ return baseId+"d0q" } return baseId+"d_e" } //todo Main 描述文字 fun geta91():String{ if(!TaskUtils.isDouyin1270()){ return baseId+"a92" } return return baseId+"a91" } // todo Main 评论按钮 fun getahl():String{ //com.ss.android.ugc.aweme:id/ahl 12.7 //com.ss.android.ugc.aweme:id/adk 12.2 if(!TaskUtils.isDouyin1270()){ return baseId+"adk" } return return baseId+"ahl" } // todo Main 点赞按钮 fun getayl():String{ //com.ss.android.ugc.aweme:id/ayl 12.7 //com.ss.android.ugc.aweme:id/atq 12.2 if(!TaskUtils.isDouyin1270()){ return baseId+"atq" } return baseId+"ayl" } //todo Main 评论EditText fun getahq():String{ //com.ss.android.ugc.aweme:id/ahq 12.7 //com.ss.android.ugc.aweme:id/adq 12.2 if(!TaskUtils.isDouyin1270()){ return baseId+"adq" } return baseId+"ahq" } // todo Main 发送按钮 fun getai_():String{ //com.ss.android.ugc.aweme:id/ai_ 12.7 //com.ss.android.ugc.aweme:id/ae9 12.2 if(!TaskUtils.isDouyin1270()){ return baseId+"ae9" } return baseId+"ai_" } // todo Main 关闭编辑X按钮 fun getl4():String{ //com.ss.android.ugc.aweme:id/l4 12.7 //com.ss.android.ugc.aweme:id/ks 12.2 if(!TaskUtils.isDouyin1270()){ return baseId+"ks" } return baseId+"l4" } } }<file_sep>package com.pinduo.auto.http.entity data class CommonEntity(val code:Int,val msg:String = "未知错误")<file_sep>ext { android = [ applicationId: "com.pinduo.auto", compileSdkVersion: 29, buildToolsVersion: "29.0.3", minSdkVersion : 24, targetSdkVersion : 29, versionCode : 104, versionName : "1.0.4" ] version = [ ] dependencies = [ ] }<file_sep>package com.pinduo.auto.core.access import android.accessibilityservice.AccessibilityService import android.os.SystemClock import android.text.TextUtils import cn.vove7.andro_accessibility_api.api.click import cn.vove7.andro_accessibility_api.api.scrollUp import cn.vove7.andro_accessibility_api.api.withId import cn.vove7.andro_accessibility_api.api.withText import com.blankj.utilcode.util.ScreenUtils import com.pinduo.auto.app.MyApplication import com.pinduo.auto.core.ids.DouyinIds import com.pinduo.auto.db.AppDatabase import com.pinduo.auto.utils.* // 养号 class AccountUpAccessbility private constructor() : BaseAccessbility<AccountUpAccessbility>() { private var isSwiped: Boolean = false private lateinit var userconfig: String private val listContains = arrayListOf<String>("服装","衣服","穿搭","上衣","裤子","的") companion object { val INSTANCE: AccountUpAccessbility by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { AccountUpAccessbility() } } init { AppDatabase.getInstance(MyApplication.instance).infoDao() .getCurrentInfo()?.userconfig?.let { userconfig = it // todo 账号属性匹配字段 登录时记录到数据库,目前先写死 } userconfig = "的" // userconfig = "服装,衣服,穿搭,上衣,裤子" // listContains.add("服装") } override fun initService(service: AccessibilityService): AccountUpAccessbility { return super.initService(service) } fun getSwiped(): Boolean = isSwiped fun setSwiped(b: Boolean) { isSwiped = b } private var isClose:Boolean = true private val x = ScreenUtils.getScreenWidth() - 50 private val y = 10 fun doSwipe(minTime:String,maxTime:String){ do { isClose = true userconfig = "" try { WaitUtil.sleep(1000L) withId(DouyinIds.geta91())?.finder?.find()?.let { if(it.isNotEmpty()){ val txt: String? = it.last()?.text?.toString() if (!TextUtils.isEmpty(txt)) { MyApplication.instance.getUiHandler().sendMessage(txt!!) WaitUtil.sleep(2000L) listContains.forEach {t -> if(txt.contains(t)){ userconfig = t } } if (!TextUtils.isEmpty(userconfig)) { MyApplication.instance.getUiHandler().sendMessage("--包含文本-->>${userconfig}") withId(DouyinIds.getayl())?.finder?.find()?.last()?.let {it1 -> val desc:String? = it1.desc() if(!TextUtils.isEmpty(desc) && desc!!.contains("未选中")){ val isClick:Boolean = it1.globalClick() if(isClick)MyApplication.instance.getUiHandler().sendMessage(">>点赞了<<") WaitUtil.sleep(2000L) withId(DouyinIds.getahl())?.globalClick()?.let { it2 -> if(it2){ WaitUtil.sleep(2000L) withId(DouyinIds.getahq())?.trySetText(txt)?.let { it3 -> if(it3){ val isSend:Boolean = withId(DouyinIds.getai_())?.globalClick() if(isSend){ MyApplication.instance.getUiHandler().sendMessage("评论成功->>${txt}") } WaitUtil.sleep(2000L) isClose = withId(DouyinIds.getl4())?.globalClick() } } isClose = withId(DouyinIds.getl4())?.click() } } } } } else { MyApplication.instance.getUiHandler().sendMessage("---不包含文本-->>${userconfig}") } } }else{ MyApplication.instance.getUiHandler().sendMessage("文本节点->>empty") } } } catch (e: Exception) { e.printStackTrace() MyApplication.instance.getUiHandler().sendMessage("未找到文本节点") LogUtils.logGGQ("任务1异常:${e.message}") }finally { //容错处理 如果未点击关闭按钮,双击右上角 if(!isClose){ click(x,y) click(x,y) MyApplication.instance.getUiHandler().sendMessage("任务1容错双击右上角") } } val delayTime:Long = TaskUtils.randomTime(minTime,maxTime) MyApplication.instance.getUiHandler().sendMessage("等待${delayTime/1000L}秒") WaitUtil.sleep(delayTime) NodeUtils.onSwipe(service) }while (getSwiped()) } fun doSwipe10(minTime:String,maxTime:String){ setSwiped(true) do { try { val delayTime:Long = TaskUtils.randomTime(minTime,maxTime) MyApplication.instance.getUiHandler().sendMessage("等待${delayTime/1000L}秒") WaitUtil.sleep(delayTime) NodeUtils.onSwipe(service) }catch (e:Exception){ e.fillInStackTrace() }finally { } }while (getSwiped()) } }<file_sep>package com.pinduo.auto.core.job import com.birbit.android.jobqueue.RetryConstraint import com.pinduo.auto.app.global.Constants import com.pinduo.auto.core.access.AccountUpAccessbility import com.pinduo.auto.core.data.TaskData import com.pinduo.auto.utils.LogUtils class AccountTaskJob(data: TaskData) :BaseJob(data){ @Throws(Throwable::class) override fun onRun() { LogUtils.logGGQ("job onRun:${runGroupId}--${tags}") LogUtils.logGGQ("data:${data.content}") when(data.task){ Constants.Task.task1 ->{ AccountUpAccessbility.INSTANCE.doSwipe10(data.minTime,data.maxTime) } } } override fun shouldReRunOnThrowable( throwable: Throwable, runCount: Int, maxRunCount: Int ): RetryConstraint { LogUtils.logGGQ("job shouldReRunOnThrowable") return RetryConstraint.createExponentialBackoff(runCount, 1000) } override fun onAdded() { LogUtils.logGGQ("job onAdded") } override fun onCancel(cancelReason: Int, throwable: Throwable?) { LogUtils.logGGQ("job onCancel") } }<file_sep>package com.pinduo.auto.widget.observers interface SubjectListener { /** * 添加 */ fun add(key:String,observerListener: ObserverListener) /** * 通知的内容 */ fun notifyObserver(key:String,content: String) /** * 删除 */ fun remove(key:String) }<file_sep>package com.pinduo.auto.core.data import java.io.Serializable /** * 任务队列使用的数据,必须序列化 */ class TaskData(var isExecute:Boolean = false, val delayTime:Long = 1000L,val task:String = "",val zxTime:Long = 0,val minTime:String = "", val maxTime:String = "", val content:String = "",val type:String=""): Serializable<file_sep>package com.pinduo.auto.core.access import android.accessibilityservice.AccessibilityService /** * 无障碍中执行任务的抽象类,所有实现类使用之前都必须先进行初始化 */ abstract class BaseAccessbility<out T> { lateinit var service: AccessibilityService open fun initService(service: AccessibilityService): T { this.service = service return this as T } }<file_sep>package com.pinduo.auto.widget.observers import com.pinduo.auto.app.global.Constants class ObserverManager : SubjectListener { private val task1List = hashSetOf<ObserverListener>() private val task3List = hashSetOf<ObserverListener>() companion object { val instance: ObserverManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { ObserverManager() } } /** * 观察者集合 */ override fun add(key:String,observerListener: ObserverListener) { // 加入队列 when(key){ Constants.Task.task1 ->{ task1List.add(observerListener) } Constants.Task.task3 ->{ task3List.add(observerListener) } } } override fun notifyObserver(key:String,content: String) { // 通知观察者刷新数据 try { when(key){ Constants.Task.task1 ->{ task1List.forEach { it.observer(content) } } Constants.Task.task3 ->{ task3List.forEach { it.observer(content) } } } }catch (e:Exception){ e.printStackTrace() } } override fun remove(key:String) { // 从监听队列删除 when(key){ Constants.Task.task1 ->{ task1List.clear() } Constants.Task.task3 ->{ task3List.clear() } } } }<file_sep>package com.pinduo.auto.ui import android.content.Intent import android.os.Bundle import android.provider.Settings import android.text.TextUtils import android.view.View import com.blankj.utilcode.util.AppUtils import com.lzy.okgo.OkGo import com.pinduo.auto.R import com.pinduo.auto.app.MyApplication import com.pinduo.auto.app.global.Constants import com.pinduo.auto.app.global.EventCode import com.pinduo.auto.base.BaseActivity import com.pinduo.auto.http.api.ApiService import com.pinduo.auto.utils.AccessibilityServiceUtils import com.pinduo.auto.utils.Event import com.pinduo.auto.utils.LogUtils import com.pinduo.auto.utils.ToastUtil import com.pinduo.auto.widget.update.CustomUpdateParser import com.xuexiang.xupdate.XUpdate import com.yhao.floatwindow.FloatWindow import kotlinx.android.synthetic.main.activity_home.* class HomeActivity : BaseActivity(R.layout.activity_home) { private val REQUESTCODE_ACCESSIBILITY: Int = 1001 override fun initData(savedInstanceState: Bundle?) { val douyinVer = AppUtils.getAppVersionName(Constants.GlobalValue.PACKAGE_DOUYIN) if(TextUtils.equals(Constants.Douyin.V1220,douyinVer) || TextUtils.equals(Constants.Douyin.V1270,douyinVer)){ sw_float_window.isChecked = true sw_float_window.setOnCheckedChangeListener { buttonView, isChecked -> if (isChecked) { FloatWindow.get()?.let { if (!it.isShowing) it.show() } } else { FloatWindow.get()?.let { if (it.isShowing) it.hide() } } } tv_douyin.setText("抖音版本:${douyinVer}") // checkVersion() checkAccessibilityPermission() }else{ sw_float_window.visibility = View.GONE tv_douyin.setText("抖音版本:${douyinVer}") tv_douyin.textSize = 36f ToastUtil.showTipToast("抖音版本:${douyinVer}") } tv_apppver.setText("当前版本:${AppUtils.getAppVersionName()}") btn_update.setOnClickListener { checkVersion() } } private fun checkVersion() { MyApplication.instance.getUiHandler().sendMessage("版本更新") val url:String = ApiService.URL_VERINFO XUpdate.newBuild(HomeActivity@this) .updateUrl(url) // .isAutoMode(true) .updateParser(CustomUpdateParser()) .update() } override fun hasUsedEventBus(): Boolean = true private fun checkAccessibilityPermission() { if (AccessibilityServiceUtils.isAccessibilitySettingsOn(MyApplication.instance)) { LogUtils.logGGQ("无障碍已开启") FloatWindow.get()?.let { if (!it.isShowing) it.show() } } else { LogUtils.logGGQ("无障碍未开启") startActivityForResult( Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS), REQUESTCODE_ACCESSIBILITY ) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) LogUtils.logGGQ("requestCode:${requestCode} -- resultCode:${resultCode}") if (requestCode == REQUESTCODE_ACCESSIBILITY) { checkAccessibilityPermission() } } override fun <T> onEventBusDispense(event: Event<T>) { super.onEventBusDispense(event) when(event.code){ EventCode.EVENT_IPORTE ->{ tv_iport?.setText(event.data.toString()) } } } // override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { // if (keyCode == KeyEvent.KEYCODE_BACK) { // this.moveTaskToBack(true) // } // return super.onKeyDown(keyCode, event) // } override fun onDestroy() { super.onDestroy() OkGo.getInstance().cancelAll() } }<file_sep>package com.pinduo.auto.widget.timer interface TimerTickListener { fun onStart(name: String, job: String) fun onTick(tick: Long) fun onMark(mark: Long) fun onStop(name: String, job: String) }<file_sep>package com.pinduo.auto.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.hardware.usb.UsbManager import android.os.BatteryManager import android.text.TextUtils import com.blankj.utilcode.util.ScreenUtils import com.pinduo.auto.app.MyApplication import com.pinduo.auto.utils.LogUtils import com.pinduo.auto.utils.TaskUtils class USBBroadcastReceiver : BroadcastReceiver() { companion object { // private val ACTION_USB_PERMISSION = "com.demo.otgusb.USB_PERMISSION" fun registerReceiver(context: Context, receiver: BroadcastReceiver) { val filter = IntentFilter() filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED) filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED) filter.addAction(Intent.ACTION_BATTERY_CHANGED) filter.addAction(Intent.ACTION_BATTERY_LOW) filter.addAction(Intent.ACTION_BATTERY_OKAY) filter.addAction(Intent.ACTION_POWER_CONNECTED) filter.addAction(Intent.ACTION_POWER_DISCONNECTED) /* 注册屏幕唤醒时的广播 */ filter.addAction(Intent.ACTION_SCREEN_ON) /* 注册机器锁屏时的广播 */ filter.addAction(Intent.ACTION_SCREEN_OFF) context.registerReceiver(receiver, filter) // val mfilter = IntentFilter(ACTION_USB_PERMISSION) // mfilter.addAction("android.hardware.usb.action.USB_STATE") // mfilter.addAction("android.hardware.usb.action.USB_DEVICE_ATTACHED") // mfilter.addAction("android.hardware.usb.action.USB_DEVICE_DETACHED") // context.registerReceiver(receiver, mfilter) } fun unregisterReceiver(context: Context, receiver: BroadcastReceiver) { context.unregisterReceiver(receiver) } } override fun onReceive(context: Context?, intent: Intent?) { intent?.let { val action: String? = it.action if (!TextUtils.isEmpty(action)) { when (action) { // ACTION_USB_PERMISSION ->{ // if(it.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED,false)){ // MyApplication.instance.getUiHandler().sendMessage("同意USB设备访问权限") // }else{ // MyApplication.instance.getUiHandler().sendMessage("拒绝USB设备访问权限") // } // } // // UsbManager.ACTION_USB_DEVICE_ATTACHED -> { // //插入USB设备 // MyApplication.instance.getUiHandler().sendMessage("插入USB设备") // } // // UsbManager.ACTION_USB_DEVICE_DETACHED -> { // //拔出USB设备 // MyApplication.instance.getUiHandler().sendMessage("拔出USB设备") // } Intent.ACTION_BATTERY_CHANGED -> { val isCharging: Boolean = it.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) != 0 if (isCharging) { //剩余电量 val level: Int = it.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) //电量最大值 val scale: Int = it.getIntExtra(BatteryManager.EXTRA_SCALE, -1) //电量百分比 val batteryPct = level / scale MyApplication.instance.getUiHandler() .sendMessage("剩余电量:${level}——最大电量:${scale}") } } Intent.ACTION_BATTERY_LOW -> { //电量过低 MyApplication.instance.getUiHandler().sendMessage("电量过低") } Intent.ACTION_BATTERY_OKAY -> { //电量满 MyApplication.instance.getUiHandler().sendMessage("电量满") } Intent.ACTION_POWER_CONNECTED -> { //电源接通 MyApplication.instance.getUiHandler().sendMessage("电源接通") val x = ScreenUtils.getScreenWidth() val y = ScreenUtils.getScreenHeight() } Intent.ACTION_POWER_DISCONNECTED -> { //电源断开 MyApplication.instance.getUiHandler().sendMessage("电源断开") } Intent.ACTION_SCREEN_ON -> { //屏幕唤醒 MyApplication.instance.getUiHandler().sendMessage("屏幕已唤醒") LogUtils.logGGQ("屏幕唤醒") } Intent.ACTION_SCREEN_OFF -> { //屏幕锁屏 MyApplication.instance.getUiHandler().sendMessage("屏幕已锁屏") LogUtils.logGGQ("屏幕锁屏") TaskUtils.wakeUpAndUnlock() TaskUtils.upScreen() } } } } } }<file_sep>package com.pinduo.auto.extensions import com.pinduo.auto.app.config.Config // 自定义 Int 的 扩展方法 http 的 响应 code internal inline fun Int.isResultSuccess():Boolean{ return Config.SUCCESS_CODE == this || Config.REBIND_CODE == this } <file_sep>package com.pinduo.auto.utils import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking class WaitUtil { companion object{ fun sleep(m:Long = 500L){ //SystemClock.sleep(m) runBlocking { delay(m) } } } }<file_sep>package com.pinduo.auto.im import android.text.TextUtils import com.blankj.utilcode.util.AppUtils import com.blankj.utilcode.util.DeviceUtils import com.blankj.utilcode.util.FileIOUtils import com.google.gson.Gson import com.pinduo.auto.app.MyApplication import com.pinduo.auto.utils.LogUtils import com.pinduo.auto.app.config.Config import com.pinduo.auto.app.global.Constants import com.pinduo.auto.app.global.EventCode import com.pinduo.auto.http.entity.TaskEntity import com.pinduo.auto.utils.Event import com.pinduo.auto.utils.EventBusUtils import io.socket.client.IO import io.socket.client.Socket import io.socket.emitter.Emitter import io.socket.engineio.client.transports.WebSocket import java.net.URISyntaxException class SocketClient private constructor(){ //任务消息 private val EVENT_TASK:String = "task" private val EVENT_IP:String = "ip_port" //收到消息回馈 private val RECEIVE_STATUS:String = "receive_status" private var socket:Socket? = null private var listener: OnSocketListener? = null private val uiHandler by lazy { MyApplication.instance.getUiHandler() } private var imei:String companion object{ val instance: SocketClient by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){ SocketClient() } } init { val opts:IO.Options = IO.Options() opts.reconnectionDelay = 1000L opts.transports = arrayOf(WebSocket.NAME) imei = MyApplication.instance.getIMEI() if(TextUtils.isEmpty(imei)){ imei = FileIOUtils.readFile2String(Constants.Path.IMEI_PATH) MyApplication.instance.setIMEI(imei) } uiHandler.sendMessage("imei:${imei}") try { socket = IO.socket(Config.IO_SERVER_URL,opts) }catch (e: URISyntaxException){ e.printStackTrace() } socket?.on(Socket.EVENT_CONNECT,object : Emitter.Listener{ override fun call(vararg args: Any?) { socket?.let { if(it.connected()){ uiHandler.sendMessage("已连接:"+ it.id()) uiHandler.sendMessage(imei) sendMessage("login",imei) LogUtils.logGGQ("imei:${imei}") uiHandler.sendMessage("APP版本:${AppUtils.getAppVersionName()}") } } } })?.on(Socket.EVENT_CONNECTING,object : Emitter.Listener{ override fun call(vararg args: Any?) { LogUtils.logGGQ("EVENT_CONNECTING") uiHandler.sendMessage("连接中...") } })?.on(Socket.EVENT_DISCONNECT,object : Emitter.Listener{ override fun call(vararg args: Any?) { LogUtils.logGGQ("EVENT_DISCONNECT") uiHandler.sendMessage("连接断开") } })?.on(Socket.EVENT_CONNECT_TIMEOUT,object : Emitter.Listener{ override fun call(vararg args: Any?) { LogUtils.logGGQ("EVENT_CONNECT_TIMEOUT") uiHandler.sendMessage("连接超时") } })?.on(Socket.EVENT_ERROR,object : Emitter.Listener{ override fun call(vararg args: Any?) { LogUtils.logGGQ("EVENT_ERROR") uiHandler.sendMessage("连接错误") } })?.on(Socket.EVENT_RECONNECT,object : Emitter.Listener{ override fun call(vararg args: Any?) { LogUtils.logGGQ("EVENT_RECONNECT") uiHandler.sendMessage("重连") } })?.on(Socket.EVENT_RECONNECTING,object : Emitter.Listener{ override fun call(vararg args: Any?) { LogUtils.logGGQ("EVENT_RECONNECTING") uiHandler.sendMessage("重连中...") } })?.on(Socket.EVENT_RECONNECT_FAILED,object : Emitter.Listener{ override fun call(vararg args: Any?) { LogUtils.logGGQ("EVENT_RECONNECT_FAILED") uiHandler.sendMessage("重连失败") } })?.on(Socket.EVENT_RECONNECT_ERROR,object : Emitter.Listener{ override fun call(vararg args: Any?) { LogUtils.logGGQ("EVENT_RECONNECT_ERROR") uiHandler.sendMessage("重连错误") } })?.on(EVENT_TASK,object :Emitter.Listener{ override fun call(vararg args: Any?) { try { args?.let { val arg = it[0] arg?.let {it1 -> LogUtils.logGGQ("收到消息:${it1}") val taskEntity: TaskEntity = Gson().fromJson<TaskEntity>(it1.toString(), TaskEntity::class.java) listener?.let { it2 -> it2.call(taskEntity) }?:let { LogUtils.logGGQ("listener is null") } }?:let { LogUtils.logGGQ("arg is null") } } }catch (e:Exception){ e.printStackTrace() LogUtils.logGGQ("${EVENT_TASK} error -->>>${e}") uiHandler.sendMessage("数据异常!!!") } } })?.on(EVENT_IP,object :Emitter.Listener{ override fun call(vararg args: Any?) { try { args?.let { val arg = it[0] arg?.let { it1 -> val iport:String = it1.toString() MyApplication.instance.getUiHandler().sendMessage(iport) val event:Event<String> = Event(EventCode.EVENT_IPORTE,iport) EventBusUtils.sendEvent(event) } } }catch (e:Exception){ e.fillInStackTrace() } } }) } fun setListener(listener: OnSocketListener){ this.listener = listener } fun onConnect(){ socket?.connect() } private fun sendMessage(msg:String){ sendMessage(EVENT_TASK,msg) } private fun sendMessage(key:String,msg:String){ socket?.emit(key,msg) uiHandler.sendMessage("${key}---${msg}") } // 回馈 fun onReceiveStatus(){ sendMessage(RECEIVE_STATUS,"1") uiHandler.sendMessage(">>>>>回馈<<<<<<") } // 父任务成功 fun sendParentSuccess(){ sendMessage(EVENT_TASK,"status=101") } // 父任务失败 fun sendParentError(){ sendMessage(EVENT_TASK,"status=100") } // 子任务成功 fun sendSuccess(){ sendMessage(EVENT_TASK,"status=1") } // 子任务失败 fun sendError(){ sendMessage(EVENT_TASK,"status=0") } }<file_sep>package com.pinduo.auto.extensions import android.content.Context import android.view.LayoutInflater //自定义 Context 的 扩展方法 internal inline val Context.layoutInflater: LayoutInflater get() = LayoutInflater.from(this) <file_sep>apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' // walle apply plugin: 'walle' def keystorePropertiesFile = rootProject.file("keystore.properties") def keystoreProperties = new Properties() keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) android { compileSdkVersion rootProject.ext.android["compileSdkVersion"] buildToolsVersion rootProject.ext.android["buildToolsVersion"] kotlinOptions { jvmTarget = '1.8' } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 encoding = 'utf-8' } defaultConfig { applicationId rootProject.ext.android["applicationId"] minSdkVersion rootProject.ext.android["minSdkVersion"] targetSdkVersion rootProject.ext.android["targetSdkVersion"] versionCode rootProject.ext.android["versionCode"] versionName rootProject.ext.android["versionName"] testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" multiDexEnabled true } signingConfigs { debug { storeFile file(keystoreProperties.RELEASE_STOREFILE) storePassword keystoreProperties.RELEASE_STORE_PASSWORD keyAlias keystoreProperties.RELEASE_KEY_ALIAS keyPassword keystoreProperties.RELEASE_KEY_PASSWORD } release { storeFile file(keystoreProperties.RELEASE_STOREFILE) storePassword keystoreProperties.RELEASE_STORE_PASSWORD keyAlias keystoreProperties.RELEASE_KEY_ALIAS keyPassword keystoreProperties.RELEASE_KEY_PASSWORD } } buildTypes { debug { debuggable true minifyEnabled false signingConfig signingConfigs.debug } release { debuggable false //移除无用的资源文件 shrinkResources true zipAlignEnabled true minifyEnabled true signingConfig signingConfigs.release proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } android.applicationVariants.all { variant -> variant.outputs.all { def fileName def date = new Date() def formattedDate = date.format('yyyyMMdd') if (variant.buildType.name.equals('release')) { fileName = "Pinduo_V${variant.mergedFlavor.versionName}_release_${formattedDate}.apk" } else if (variant.buildType.name.equals('debug')) { fileName = "Pinduo_V${variant.mergedFlavor.versionName}_debug_${formattedDate}.apk" } outputFileName = fileName } } sourceSets { main { jniLibs.srcDirs = ['libs'] } } repositories { flatDir { dirs 'libs' } } //添加如下配置就ok了 lintOptions { checkReleaseBuilds false abortOnError false } dexOptions { javaMaxHeapSize "4g" jumboMode = true } } dependencies { def room_version = "2.2.5" implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation 'androidx.core:core-ktx:1.3.2' implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'androidx.constraintlayout:constraintlayout:2.0.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' implementation 'androidx.multidex:multidex:2.0.1' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2' implementation 'org.jetbrains.anko:anko-commons:0.10.8' implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0' implementation 'com.blankj:utilcodex:1.29.0' implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' implementation 'io.reactivex.rxjava2:rxjava:2.2.12' implementation 'com.github.tbruyelle:rxpermissions:0.10.2' // implementation 'com.google.guava:guava:24.1-android' implementation 'com.squareup.okhttp3:okhttp:4.8.0' implementation ('io.socket:socket.io-client:1.0.0') { exclude group: 'org.json', module: 'json' } implementation 'com.lzy.net:okgo:3.0.4' implementation 'com.google.code.gson:gson:2.8.6' implementation 'com.github.yhaolpz:FloatWindow:1.0.9' implementation 'com.aliyun.ams:alicloud-android-utdid:1.1.5.3' implementation 'org.greenrobot:eventbus:3.2.0' kapt 'org.greenrobot:eventbus-annotation-processor:3.2.0' implementation 'com.irozon.sneaker:sneaker:2.0.0' implementation 'com.meituan.android.walle:library:1.1.7' implementation 'com.github.Vove7:Android-Accessibility-Api:1.0.2' implementation 'com.birbit:android-priority-jobqueue:3.0.0' //room 用来保存设备信息 如IMEI 账号类型 等 implementation "androidx.room:room-runtime:$room_version" kapt "androidx.room:room-runtime:$room_version" annotationProcessor "androidx.room:room-compiler:$room_version" kapt "androidx.room:room-compiler:$room_version" implementation "androidx.room:room-rxjava2:$room_version" implementation "androidx.room:room-guava:$room_version" implementation 'androidx.room:room-coroutines:2.1.0-alpha04' androidTestImplementation "androidx.room:room-testing:$room_version" implementation 'com.github.xuexiangjys:XUpdate:2.0.2' implementation 'com.zhy:okhttputils:2.6.2' } apply from: 'multiple-channel.gradle' <file_sep>package com.pinduo.auto.db import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.pinduo.auto.db.dao.Info import com.pinduo.auto.db.dao.InfoDao @Database(entities = [(Info::class)], version = 1, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun infoDao(): InfoDao companion object { @Volatile private var INSTANCE: AppDatabase? = null fun getInstance(context: Context): AppDatabase = INSTANCE ?: synchronized(this) { INSTANCE ?: buildDatabase(context).also { INSTANCE = it } } @Synchronized private fun buildDatabase(context: Context): AppDatabase { if (INSTANCE == null) { INSTANCE = Room .databaseBuilder(context, AppDatabase::class.java, context.packageName + ".db") .allowMainThreadQueries() //在主线程中查询,默认子线程 // .addMigrations(migration_1_2)//迁移数据库使用 .fallbackToDestructiveMigration() .build() } return INSTANCE!! } } val migration_1_2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { // database.execSQL("") } } } <file_sep>package com.pinduo.auto.core.access import android.accessibilityservice.AccessibilityService import android.content.Intent import android.net.Uri import cn.vove7.andro_accessibility_api.AppScope import cn.vove7.andro_accessibility_api.api.waitForPage import com.pinduo.auto.app.MyApplication import com.pinduo.auto.app.global.Constants import com.pinduo.auto.utils.NodeUtils class CommonAccessbility private constructor() : BaseAccessbility<CommonAccessbility>(){ companion object { val INSTANCE: CommonAccessbility by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { CommonAccessbility() } } override fun initService(service: AccessibilityService): CommonAccessbility { return super.initService(service) } fun douyin2Main() { val intent = Intent(Intent.ACTION_VIEW, Uri.parse("snssdk1128://feed?refer=web")) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP) MyApplication.instance.startActivity(intent) } fun douyin2MainWithText(s:String){ douyin2Main() if(waitForPage(AppScope(Constants.GlobalValue.PACKAGE_DOUYIN,Constants.Douyin.PAGE_MAIN),3000L)){ NodeUtils.tryWithText(s) }else{ NodeUtils.tryWithText(s) } } fun ignoreDouyinPage(className:String) { when(className){ Constants.Douyin.PAGE_UPDATE_X,Constants.Douyin.PAGE_UPDATE_Y ->{ NodeUtils.tryWithText("以后再说") } Constants.Douyin.PAGE_YANG ->{ NodeUtils.tryWithText("我知道了") } Constants.Douyin.PAGE_DN ->{ NodeUtils.tryWithText("取消") } Constants.Douyin.PAGE_DB, Constants.Douyin.PAGE_USERPROFIL ->{ NodeUtils.tryWithText("好的") } Constants.Douyin.PAGE_CX ->{ NodeUtils.tryWithText("同意") } Constants.Douyin.PAGE_RECOMMENDCONTACT ->{ NodeUtils.tryWithText("稍后") } Constants.Douyin.PAGE_FLOATVIEW_D ->{ NodeUtils.tryWithText("暂不使用") } } } fun ignoreSougouPage(className: String) { when(className){ Constants.Sougou.PAGE_AGREE ->{ NodeUtils.tryWithId("android:id/button1") } Constants.Sougou.PAGE_CUSTOM ->{ NodeUtils.tryWithId("android:id/button1") } Constants.Sougou.PAGE_UPDATE ->{ NodeUtils.tryWithId("android:id/button2") } Constants.Sougou.PAGE_PROVISION ->{ NodeUtils.tryWithId("android:id/button1") } } } // 6秒内等待抖音 首页 出现 fun waitForMainPage(listener:MainPageListener){ if(waitForPage(AppScope(Constants.GlobalValue.PACKAGE_DOUYIN,Constants.Douyin.PAGE_MAIN),10000L)){ listener.call(true) }else{ listener.call(false) } } interface MainPageListener{ fun call(b:Boolean) } }<file_sep>package com.pinduo.auto import android.content.Intent import android.os.Bundle import android.text.TextUtils import com.blankj.utilcode.util.FileIOUtils import com.blankj.utilcode.util.ToastUtils import com.pinduo.auto.app.MyApplication import com.pinduo.auto.app.global.Constants import com.pinduo.auto.base.BaseActivity import com.pinduo.auto.ui.AccountActivity import com.pinduo.auto.ui.HomeActivity import com.pinduo.auto.ui.TestActivity import com.pinduo.auto.utils.PermissionUtil import com.pinduo.auto.utils.RequestPermission import com.tbruyelle.rxpermissions2.RxPermissions class SplashActivity : BaseActivity(R.layout.activity_splash) { val rxPermissions: RxPermissions = RxPermissions(this) override fun initData(savedInstanceState: Bundle?) { applyPermissions() } override fun onRestart() { super.onRestart() applyPermissions() } private fun applyPermissions() { PermissionUtil.applyPermissions(object : RequestPermission { override fun onRequestPermissionSuccess() { launchTarget() // launchTest() } override fun onRequestPermissionFailure(permissions: List<String>) { ToastUtils.showShort("权限未通过") } override fun onRequestPermissionFailureWithAskNeverAgain(permissions: List<String>) { ToastUtils.showShort("权限未通过") } }, rxPermissions) } private fun launchTarget() { val imei: String? = FileIOUtils.readFile2String(Constants.Path.IMEI_PATH) if(TextUtils.isEmpty(imei)){ startActivity(Intent(SplashActivity@ this, AccountActivity::class.java)) this.finish() }else{ MyApplication.instance.setIMEI(imei!!) startActivity(Intent(SplashActivity@ this, HomeActivity::class.java)) finish() } } private fun launchTest(){ startActivity(Intent(SplashActivity@ this, TestActivity::class.java)) this.finish() } }<file_sep>package com.pinduo.auto.utils import com.blankj.utilcode.util.DeviceUtils class IMEIUtils { companion object{ fun getDeviceId():String?{ return DeviceUtils.getAndroidID() } } }<file_sep>package com.pinduo.auto.db.dao import androidx.room.* @Entity(tableName = "infos") class Info { @PrimaryKey(autoGenerate = true) var id:Long = 0 @ColumnInfo(name = "username") var username:String? = "" @ColumnInfo(name = "imei") var imei:String? = "" @ColumnInfo(name = "userconfig") var userconfig:String? = "" }<file_sep>package com.pinduo.auto.app.config class Config { companion object { const val BASE_URL: String = "http://ceshi.pinduocm.com" // const val BASE_URL: String = "http://pinduocm.com" const val IO_SERVER_URL: String = "http://172.16.31.10:2120" // const val IO_SERVER_URL: String = "http://192.168.3.11:2120" const val SUCCESS_CODE: Int = 200 const val REBIND_CODE: Int = 401 } }<file_sep>package com.pinduo.auto.base interface IView { }<file_sep>package com.pinduo.auto.utils import android.accessibilityservice.AccessibilityService import android.accessibilityservice.GestureDescription import android.text.TextUtils import android.util.Pair import android.view.accessibility.AccessibilityNodeInfo import cn.vove7.andro_accessibility_api.api.withId import cn.vove7.andro_accessibility_api.api.withText import com.blankj.utilcode.util.ScreenUtils import com.pinduo.auto.app.MyApplication import kotlin.random.Random class NodeUtils { companion object { fun onClickById(service: AccessibilityService,id:String):Boolean{ val rootNode = service.rootInActiveWindow if(rootNode == null){ return false }else{ val nodes = rootNode.findAccessibilityNodeInfosByViewId(id) if(nodes.isNullOrEmpty()){ return false }else{ rootNode.recycle() for (i in nodes.indices.reversed()) { if (onClickByNode(nodes[i])) return true } } } return false } fun onClickByNode(node: AccessibilityNodeInfo?): Boolean { node?.let { if (it.isClickable) { return it.performAction(AccessibilityNodeInfo.ACTION_CLICK) } else { val parent = it.parent val b = onClickByNode(parent) parent?.recycle() return b } } return false } fun onClickTextByNode(node: AccessibilityNodeInfo?) { node?.let { for (i in 0 until it.childCount) { if (TextUtils.equals( "android.widget.TextView", it.getChild(i).className) && !TextUtils.isEmpty(it.getChild(i).text)) { onClickByNode(it.getChild(i)) } else { onClickTextByNode(it.getChild(i)) } } } } fun tryWithText(s: String) { try { WaitUtil.sleep(1000L) val isClick: Boolean = withText(s)?.globalClick() MyApplication.instance.getUiHandler().sendMessage("点击--<${s}>--${isClick}") } catch (e: Exception) { e.printStackTrace() LogUtils.logGGQ("tryWithText 异常:${e.fillInStackTrace()}") MyApplication.instance.getUiHandler().sendMessage("点击-<${s}>-异常") } } fun tryWithId(id: String) { try { WaitUtil.sleep(1000L) val isClick: Boolean = withId(id)?.tryClick() MyApplication.instance.getUiHandler().sendMessage("点击--<${id}>--${isClick}") } catch (e: Exception) { e.printStackTrace() LogUtils.logGGQ("tryWithId 异常:${e.fillInStackTrace()}") MyApplication.instance.getUiHandler().sendMessage("点击-<${id}>-异常") } } private val duration: Long = 500L private val width = ScreenUtils.getScreenWidth() //1080 private val height = ScreenUtils.getScreenHeight()//1920 private fun description(path: android.graphics.Path) = GestureDescription.Builder().addStroke( GestureDescription.StrokeDescription( path, 0L, duration ) ).build() fun onSwipe(service: AccessibilityService) { val path = getSwipePath( width / 2 - Random.nextInt(1, 100), 1500 + Random.nextInt(1, 100), Random.nextInt(width / 2, width - 100), height / 2, Random.nextInt(50, width / 3), 300 - Random.nextInt(1, 100) ) service.dispatchGesture( description(path), MyGestureResultCallback(), null ) } private fun getSwipePath( fromX: Int, fromY: Int, cX: Int, cY: Int, toX: Int, toY: Int ): android.graphics.Path { val path = android.graphics.Path() path.moveTo(fromX.toFloat(), fromY.toFloat()) //滑动起点we path.quadTo(cX.toFloat(), cY.toFloat(), toX.toFloat(), toY.toFloat()) return path } } } class MyGestureResultCallback:AccessibilityService.GestureResultCallback(){ override fun onCompleted(gestureDescription: GestureDescription?) { super.onCompleted(gestureDescription) } override fun onCancelled(gestureDescription: GestureDescription?) { super.onCancelled(gestureDescription) } } infix fun <A, B> A.t(that: B): Pair<A, B> = Pair(this, that) <file_sep>package com.pinduo.auto.core.access import android.accessibilityservice.AccessibilityService import android.content.Intent import android.net.Uri import android.text.TextUtils import cn.vove7.andro_accessibility_api.AccessibilityApi import cn.vove7.andro_accessibility_api.api.* import com.blankj.utilcode.util.ScreenUtils import com.pinduo.auto.app.MyApplication import com.pinduo.auto.app.global.Constants import com.pinduo.auto.core.ids.DouyinIds import com.pinduo.auto.im.SocketClient import com.pinduo.auto.utils.LogUtils import com.pinduo.auto.utils.NodeUtils import com.pinduo.auto.utils.TaskUtils import com.pinduo.auto.utils.WaitUtil import com.pinduo.auto.widget.observers.ObserverListener import com.pinduo.auto.widget.observers.ObserverManager import kotlin.random.Random class LivePlayAccessibility private constructor() : BaseAccessbility<LivePlayAccessibility>(), ObserverListener { companion object { val INSTANCE: LivePlayAccessibility by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { LivePlayAccessibility() } } //子任务是否执行成功 private var isSuccess:Boolean = false private var isInRoom: Boolean = false private var liveURI: String = "" private var isLoopSpeak:Boolean = false fun isInLiveRoom(): Boolean = isInRoom fun setInLiveRoom(b: Boolean) { isInRoom = b } fun getLiveURI(): String = liveURI fun setLiveURI(s: String) { liveURI = s } fun getLoopSpeak(): Boolean = isLoopSpeak fun setLoopSpeak(b: Boolean) { isLoopSpeak = b } override fun initService(service: AccessibilityService): LivePlayAccessibility { return super.initService(service) } private var socketClient: SocketClient? = null fun getSocketClient(): SocketClient? = socketClient fun setSocketClient(socket: SocketClient) { this.socketClient = socket } //进入直播间 fun doLiveRoom(zhiboNum: String) { startLiveRoom(zhiboNum) } // 发评论 fun doSpeak(type:String,content: String,delayTime:Long){ setLoopSpeak(false) if(TextUtils.equals("3",type)){ setLoopSpeak(true) doLoopSpeak(content,delayTime) }else{ doSingleSpeak(content,delayTime) } } //普通评论 fun doSingleSpeak(content: String,delayTime:Long){ isSuccess = false try { val txt:String = TaskUtils.getContentRandom(content) if(withId(DouyinIds.getb82())?.tryClick()){ WaitUtil.sleep(1000L) withId(DouyinIds.getb9q())?.childAt(0)?.trySetText(txt)?.let { if(it){ withId(DouyinIds.getfvs())?.tryClick()?.let {it1 -> if(it1){ isSuccess = true MyApplication.instance.getUiHandler().sendMessage("评论成功:${txt}") }else{ MyApplication.instance.getUiHandler().sendMessage("未点击发送") } } }else{ MyApplication.instance.getUiHandler().sendMessage("未设置文本") } } }else{ withId(DouyinIds.getfvs())?.tryClick() } }catch (e:Exception){ e.printStackTrace() MyApplication.instance.getUiHandler().sendMessage("评论失败!!!") try { MyApplication.instance.getUiHandler().sendMessage("尝试评论~!") withId(DouyinIds.getb9q())?.childAt(0)?.trySetText("~")?.let { if(it){ WaitUtil.sleep(2000L) val isTryClick = withId(DouyinIds.getfvs())?.tryClick() MyApplication.instance.getUiHandler().sendMessage("尝试评论->${isTryClick}") } } }catch (e:Exception){ e.fillInStackTrace() MyApplication.instance.getUiHandler().sendMessage("尝试评论~失败!") } }finally { if(isSuccess){ getSocketClient()?.sendSuccess() }else{ getSocketClient()?.sendError() } MyApplication.instance.getUiHandler().sendMessage("间隔时间${delayTime}毫秒") WaitUtil.sleep(delayTime) } } // 循环评论 fun doLoopSpeak(content: String,delayTime:Long){ TaskUtils.initContent(content) val fromTime:Long = delayTime val untilTime:Long = delayTime*2 do { val delay:Long = Random.nextLong(fromTime,untilTime) try { val txt:String = TaskUtils.getContentIndex() if(withId(DouyinIds.getb82())?.tryClick()){ WaitUtil.sleep(1000L) withId(DouyinIds.getb9q())?.childAt(0)?.trySetText(txt)?.let { if(it){ withId(DouyinIds.getfvs())?.tryClick()?.let {it1 -> if(it1){ MyApplication.instance.getUiHandler().sendMessage("评论成功:${txt}") }else{ MyApplication.instance.getUiHandler().sendMessage("未点击发送") } } }else{ MyApplication.instance.getUiHandler().sendMessage("未设置文本") } } }else{ withId(DouyinIds.getfvs())?.tryClick() } }catch (e:Exception){ e.printStackTrace() MyApplication.instance.getUiHandler().sendMessage("评论失败!!!") try { MyApplication.instance.getUiHandler().sendMessage("尝试评论~!") withId(DouyinIds.getb9q())?.childAt(0)?.trySetText("~")?.let { if(it){ WaitUtil.sleep(2000L) val isTryClick = withId(DouyinIds.getfvs())?.tryClick() MyApplication.instance.getUiHandler().sendMessage("尝试评论->${isTryClick}") } } }catch (e:Exception){ e.fillInStackTrace() MyApplication.instance.getUiHandler().sendMessage("尝试评论~失败!") } }finally { MyApplication.instance.getUiHandler().sendMessage("间隔时间${delay}毫秒") WaitUtil.sleep(delay) } }while (getLoopSpeak()) } private fun startLiveRoom(zhiboNum: String) { setLiveURI(zhiboNum) ObserverManager.instance.add(Constants.Task.task3,this) if (!isInLiveRoom() && !TextUtils.isEmpty(getLiveURI())) { inLiveRoom() } } override fun observer(content: String) { LogUtils.logGGQ("监听到页面:${content}") when (content) { Constants.Douyin.PAGE_MAIN -> { MyApplication.instance.getUiHandler().sendMessage("回到首页") setInLiveRoom(false) //如果在任务内回到首页,进入直播间 startLiveRoom(getLiveURI()) } Constants.Douyin.PAGE_LIVE_ROOM -> { MyApplication.instance.getUiHandler().sendMessage("进入直播间") setInLiveRoom(true) } Constants.Douyin.PAGE_LIVE_ANCHOR, Constants.Douyin.PAGE_LIVE_GIFT, Constants.Douyin.PAGE_LIVE_Follow, Constants.Douyin.PAGE_LIVE_MORE ->{ if(isInLiveRoom()) { //被遮挡点击操作 MyApplication.instance.getUiHandler().sendMessage("被遮挡") LogUtils.logGGQ("被遮挡...") val x = ScreenUtils.getScreenWidth() / 2 val y = ScreenUtils.getScreenHeight() / 2 val isClick: Boolean = click(x, y) LogUtils.logGGQ(if (isClick) "点击" else "未点击") } } } } //----------------- // 点赞 private val x = ScreenUtils.getScreenWidth() - 50 private val y = 10 private val delay = 1 private val period = 500 private var clickCount = 0 fun doGiveLike(s:Long){ clickCount = 0 val count = (s / period) try { for (index in 1..count){ if(isInLiveRoom() && AccessibilityApi.isGestureServiceEnable && pressWithTime(x,y,delay)){ clickCount++ } MyApplication.instance.getUiHandler().sendMessage("${count}-->>>${index}次-->${clickCount}次成功") WaitUtil.sleep(500L) } }catch (e:Exception){ e.printStackTrace() MyApplication.instance.getUiHandler().sendMessage("点赞失败!!!") }finally { if(clickCount >= count){ getSocketClient()?.sendSuccess() }else{ getSocketClient()?.sendError() } } } //---------------购物车----- fun doShopCart() { isSuccess = false try { MyApplication.instance.getUiHandler().sendMessage("--开始刷购物车--") val isClickCart:Boolean = withId(DouyinIds.getfhq())?.waitFor(9000L)?.globalClick()?:false if(isClickCart){ MyApplication.instance.getUiHandler().sendMessage("点击了购物车") val isClickShopItem = withId(DouyinIds.getfh9())?.waitFor(9000L)?.tryClick()?:false if(isClickShopItem){ MyApplication.instance.getUiHandler().sendMessage("点击了商品") val isClickBuyNow = withText("立即购买")?.waitFor(9000L)?.tryClick()?:false if(isClickBuyNow){ MyApplication.instance.getUiHandler().sendMessage("点击了立即购买") WaitUtil.sleep(3000L) NodeUtils.onClickTextByNode(service.rootInActiveWindow) MyApplication.instance.getUiHandler().sendMessage("下单等待。。。") WaitUtil.sleep(10000L) isSuccess = withText("提交订单")?.waitFor(4000L)?.childAt(0)?.childAt(0)?.childAt(0)?.click()?:false MyApplication.instance.getUiHandler().sendMessage("提交订单返回->${isSuccess}") WaitUtil.sleep(2000L) val isClickGiveUp:Boolean = withText("放弃")?.waitFor(3000L)?.globalClick()?:false if(isClickGiveUp){ MyApplication.instance.getUiHandler().sendMessage("放弃->点击") }else{ back() MyApplication.instance.getUiHandler().sendMessage("放弃->返回") } WaitUtil.sleep(2000L) val isClickBuyBack = withId(DouyinIds.getd_e())?.waitFor(3000L)?.click()?:false if(isClickBuyBack){ MyApplication.instance.getUiHandler().sendMessage("立即购买back-点击") }else{ back() MyApplication.instance.getUiHandler().sendMessage("立即购买back->返回") } WaitUtil.sleep(2000L) val isClickback = back() MyApplication.instance.getUiHandler().sendMessage("返回->${isClickback}") }else{ MyApplication.instance.getUiHandler().sendMessage("没有立即购买") val isClickback1:Boolean = back() MyApplication.instance.getUiHandler().sendMessage("返回1->${isClickback1}") WaitUtil.sleep(2000L) val isClickback2:Boolean = back() MyApplication.instance.getUiHandler().sendMessage("返回2->${isClickback2}") } }else{ val isClickback:Boolean = back() MyApplication.instance.getUiHandler().sendMessage("没有商品->放回:${isClickback}") } }else{ MyApplication.instance.getUiHandler().sendMessage("没有购物车") } }catch (e:Exception){ e.printStackTrace() MyApplication.instance.getUiHandler().sendMessage("购物车失败!!!") }finally { if(isSuccess){ getSocketClient()?.sendSuccess() }else { getSocketClient()?.sendError() } } } private fun inLiveRoom(){ setInLiveRoom(true) val intent = Intent(Intent.ACTION_VIEW, Uri.parse(getLiveURI())) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP) MyApplication.instance.startActivity(intent) MyApplication.instance.getUiHandler().sendMessage("<<<直播间>>>") } } <file_sep>package com.pinduo.auto.app.global class EventCode { companion object{ const val EVENT_IPORTE = 80 } }<file_sep>package com.pinduo.auto.http.api import com.pinduo.auto.app.config.Config class ApiService { companion object{ //绑定设备 const val URL_BINDDEVICE:String = Config.BASE_URL + "/api/task/bind_device" //版本更新 const val URL_VERINFO:String = Config.BASE_URL + "/api/app/appVersionInfo" } }<file_sep>package com.pinduo.auto.utils import android.annotation.SuppressLint import android.app.ActivityManager import android.app.KeyguardManager import android.content.Context import android.content.Context.KEYGUARD_SERVICE import android.content.Intent import android.os.PowerManager import android.text.TextUtils import cn.vove7.andro_accessibility_api.api.scrollUp import com.blankj.utilcode.util.ActivityUtils import com.blankj.utilcode.util.AppUtils import com.pinduo.auto.app.MyApplication import com.pinduo.auto.app.global.Constants import com.pinduo.auto.ui.HomeActivity import java.lang.Exception import kotlin.random.Random class TaskUtils{ companion object{ private var loopIndex:Int = 0 private var arrays:ArrayList<String> = arrayListOf() ///截取评论内容 fun getContentRandom(content:String):String{ if(TextUtils.isEmpty(content)) return "~" if(content.contains(";")){ content.split(";").let { return it[Random.nextInt(it.size)] } } return content } fun getContentList(content: String):ArrayList<String>{ val array = arrayListOf<String>() if(content.contains(";")){ content.split(";").let { array.addAll(it) } }else{ array.add(content) } return array } fun initContent(content: String){ arrays.clear() arrays.addAll(getContentList(content)) } fun getContentIndex():String{ if(arrays.isEmpty()){ return "~" } loopIndex++ if(loopIndex >= arrays.size){ loopIndex = 0 } return arrays[loopIndex] } fun getLoopCount():Int = loopIndex fun randomTime(min:String,max:String):Long{ if(TextUtils.isEmpty(min) || TextUtils.isEmpty(max) || TextUtils.equals(min,"0") || TextUtils.equals(max,"0")){ return 1000L } val tmin:Int = min.toInt() val tmax:Int = max.toInt() if(tmin >= tmax){ return tmin *1000L } val time:Long = Random.nextLong(tmin*1000L,tmax*1000L) return time } fun isDouyin1270():Boolean{ return TextUtils.equals(Constants.Douyin.V1270,AppUtils.getAppVersionName(Constants.GlobalValue.PACKAGE_DOUYIN)) } fun isDouyin1220():Boolean{ return TextUtils.equals(Constants.Douyin.V1220,AppUtils.getAppVersionName(Constants.GlobalValue.PACKAGE_DOUYIN)) } @SuppressLint("InvalidWakeLockTag") fun wakeUpAndUnlock(){ try { // 获取电源管理器对象 val pm:PowerManager? = MyApplication.instance.getSystemService(Context.POWER_SERVICE) as PowerManager pm?.let { if(!it.isInteractive){ val wl: PowerManager.WakeLock = it.newWakeLock( PowerManager.FULL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.ON_AFTER_RELEASE, "bright") wl.acquire(1000L * 600) wl.release() MyApplication.instance.getUiHandler().sendMessage("点亮屏幕") } } val km:KeyguardManager? = MyApplication.instance.getSystemService(KEYGUARD_SERVICE) as KeyguardManager val kLock = km?.newKeyguardLock("unLock") kLock?.let { it.disableKeyguard() } }catch (e:Exception){ e.printStackTrace() } } fun upScreen(){ scrollUp() } fun openHomeAndKill(packageName:String){ // ActivityUtils.startHomeActivity() val homeActivity:Intent = Intent(MyApplication.instance.applicationContext,HomeActivity::class.java) homeActivity.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT MyApplication.instance.applicationContext.startActivity(homeActivity) val am = MyApplication.instance.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager am.killBackgroundProcesses(packageName) } } }<file_sep>package com.pinduo.auto.db.dao import androidx.room.* @Dao interface InfoDao { @Query("SELECT * FROM infos") fun getAllInfo():List<Info> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertInfo(vararg user:Info) @Query("SELECT * FROM infos WHERE id = :id") fun getInfoById(id:Long):Info @Update(onConflict = OnConflictStrategy.REPLACE) fun updateInfo(info: Info) @Delete fun deleteInfo(info:Info) @Query("DELETE FROM infos") fun deleteAll() fun getCurrentInfo():Info?{ val infos = getAllInfo() if(!infos.isEmpty()){ return infos.last() } return null } }<file_sep>package com.pinduo.auto.app.global import android.os.Environment class Constants { object Path { val IMEI_PATH: String = Environment.getExternalStorageDirectory().toString() + "/android/imei.text" } object ApiParams { const val USERNAME = "username" const val IMEI = "imei" } object SaveInfoKey { } object GlobalValue { const val PACKAGE_DOUYIN = "com.ss.android.ugc.aweme" const val PACKAGE_KUAISHOU = "com.smile.gifmaker" const val PACKAGE_SOGOUOEM = "com.sohu.inputmethod.sogouoem" // 搜狗输入法 //启动有抖音10秒的启动时间+10秒的延迟时间 const val plusTime: Long = 20L // 追加时间10秒 } object BundleKey { } object Task { const val douyin = "1" const val kuaishou = "2" const val task0 = "0" const val task1 = "1" const val task2 = "2" const val task3 = "3" const val task4 = "4" const val task5 = "5" const val task6 = "6" const val task7 = "7" const val task8 = "8" const val task9 = "9" } object Douyin { const val V1220 = "12.2.0" const val V1270 = "12.7.0" //抖音首页 const val PAGE_MAIN = "com.ss.android.ugc.aweme.main.MainActivity" //抖音直播页 const val PAGE_LIVE_ROOM = "com.ss.android.ugc.aweme.live.LivePlayActivity" //主播头像弹出框 const val PAGE_LIVE_ANCHOR = "com.bytedance.android.livesdk.widget.LiveBottomSheetDialog" //直播页忽略页面 const val PAGE_LIVE_GIFT = "com.bytedance.android.livesdk.gift.c.a" const val PAGE_LIVE_Follow = "com.bytedance.android.livesdk.chatroom.viewmodule.FollowGuideWidget${'$'}a" const val PAGE_LIVE_MORE = "com.bytedance.android.livesdk.chatroom.viewmodule.toolbar.LiveToolbarMoreDialog" //直播间购物车 const val PAGE_LIVE_CART = "com.bytedance.android.livesdk.livecommerce.dialog.ECBottomDialog" //购物车内立即购买 const val PAGE_CART_BUY_NOW = "com.ss.android.ugc.aweme.commerce.sdk.anchorv3.AnchorV3Activity" //抖音版本更新 以后再说 const val PAGE_UPDATE_X = "com.ss.android.ugc.aweme.update.x" const val PAGE_UPDATE_Y = "com.ss.android.ugc.aweme.update.y" //进入儿童/青少年模式 我知道了 const val PAGE_YANG = "android.app.AlertDialog" //弹出通讯录 取消 const val PAGE_DN = "com.ss.android.ugc.aweme.main.dn" //个人信息 好的 const val PAGE_DB = "com.ss.android.ugc.aweme.main.db" //个人信息 好的 const val PAGE_USERPROFIL = "com.ss.android.ugc.aweme.profile.ui.UserProfileActivity" //个人信息保护指引 同意 const val PAGE_CX = "com.ss.android.ugc.aweme.main.cx" //通知,是件很重要的事情 稍后 const val PAGE_RECOMMENDCONTACT = "com.ss.android.ugc.aweme.friends.ui.RecommendContactActivity" //悬浮窗播放功能上线啦 暂不使用 const val PAGE_FLOATVIEW_D = "com.bytedance.android.livesdk.floatview.d" } object Sougou{ //声明与协议 const val PAGE_AGREE = "android.inputmethodservice.SoftInputWindow" // 定制版声明 const val PAGE_CUSTOM = "eu" //提示升级 const val PAGE_UPDATE = "oq" // 声明与条款 const val PAGE_PROVISION = "color.support.v7.app.AlertDialog" } }<file_sep>package com.pinduo.auto.widget.timer class MyScheduledExecutor private constructor(): Runnable { private var tick:Long = 0L private var totalTime:Long = 0L private var isRuning:Boolean = false private var name:String = "" private var job:String = "" private var tickListener: TimerTickListener? = null companion object { val INSTANCE: MyScheduledExecutor by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){ MyScheduledExecutor() } } fun setListener(listener: TimerTickListener){ this.tickListener = listener } fun isRuning():Boolean{ return isRuning } fun onReStart(name:String,job:String,total:Long){ if(total <= 0) return this.tick = 0L this.name = name this.job = job this.totalTime = total this.isRuning = true this.tickListener?.onStart(name,job) } fun onStop(){ this.isRuning = false this.tickListener?.onStop(name,job) } override fun run() { this.tick++ if(isRuning()){ if(tick < totalTime){ val t:Long = tick % 10 if(t == 0L){ this.tickListener?.onTick(tick) } }else if(tick == totalTime){ this.onStop() } } val mark:Long = tick % 100 if(mark == 0L){ this.tickListener?.onMark(mark) } } }<file_sep>package com.pinduo.auto.widget.update; import java.io.Serializable; /** * 自定义版本检查的结果 * * @author xuexiang * @since 2018/7/11 上午1:03 */ public class VersionInfo implements Serializable { /** * code : 200 * message : 成功 * data : {"version_code":1224,"apk_url":"http://ceshi.pinduocm.com/apkDownload"} */ private int code; private String message; private VersionInfoData data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public VersionInfoData getData() { return data; } public void setData(VersionInfoData data) { this.data = data; } public static class VersionInfoData { /** * version_code : 1224 * apk_url : http://ceshi.pinduocm.com/apkDownload */ private int version_code; private String apk_url; public int getVersion_code() { return version_code; } public void setVersion_code(int version_code) { this.version_code = version_code; } public String getApk_url() { return apk_url; } public void setApk_url(String apk_url) { this.apk_url = apk_url; } } }<file_sep>package com.pinduo.auto.service import android.content.Context import android.text.TextUtils import android.view.View import android.view.accessibility.AccessibilityManager import cn.vove7.andro_accessibility_api.AccessibilityApi import cn.vove7.andro_accessibility_api.AppScope import cn.vove7.andro_accessibility_api.api.scrollUp import cn.vove7.andro_accessibility_api.api.swipe import com.birbit.android.jobqueue.CancelResult import com.birbit.android.jobqueue.Job import com.birbit.android.jobqueue.TagConstraint import com.birbit.android.jobqueue.callback.JobManagerCallback import com.blankj.utilcode.util.IntentUtils import com.pinduo.auto.R import com.pinduo.auto.app.MyApplication import com.pinduo.auto.app.global.Constants import com.pinduo.auto.core.access.AccountUpAccessbility import com.pinduo.auto.core.access.CommonAccessbility import com.pinduo.auto.core.access.LivePlayAccessibility import com.pinduo.auto.core.data.TaskData import com.pinduo.auto.core.job.AccountTaskJob import com.pinduo.auto.core.job.BaseJob import com.pinduo.auto.core.job.LiveTaskJob import com.pinduo.auto.extensions.layoutInflater import com.pinduo.auto.im.OnSocketListener import com.pinduo.auto.im.SocketClient import com.pinduo.auto.utils.LogUtils import com.pinduo.auto.widget.observers.ObserverManager import com.pinduo.auto.widget.timer.MyScheduledExecutor import com.pinduo.auto.widget.timer.TimerTickListener import com.pinduo.auto.http.entity.TaskEntity import com.pinduo.auto.utils.NodeUtils import com.pinduo.auto.utils.TaskUtils import com.pinduo.auto.utils.WaitUtil import com.yhao.floatwindow.* import java.util.concurrent.Executors import java.util.concurrent.TimeUnit class MyAccessibilityService :AccessibilityApi(){ private val socketClient by lazy { SocketClient.instance } private val runnable by lazy { MyScheduledExecutor.INSTANCE } private val initialDelay:Long = 1L private val period:Long = 1L private val max:Long = Long.MAX_VALUE private val service by lazy { Executors.newScheduledThreadPool(4) } private val uiHandler by lazy { MyApplication.instance.getUiHandler() } override val enableListenAppScope: Boolean = true private val floatWindow:FloatWindow.B by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){ val view: View = this.baseContext.layoutInflater.inflate(R.layout.layout_float_view, null) FloatWindow.with(getApplicationContext()) .setView(view) .setWidth(Screen.width, 0.4f) //设置控件宽高 .setHeight(Screen.height, 0.2f) .setX(2) //设置控件初始位置 .setY(2) .setDesktopShow(true) //桌面显示 .setMoveType(MoveType.active) //可拖动,释放后自动回到原位置 .setViewStateListener(MyViewStateListener()) //监听悬浮控件状态改变 .setPermissionListener(MyPermissionListener()) } override fun onPageUpdate(currentScope: AppScope) { super.onPageUpdate(currentScope) currentScope?.let { LogUtils.logQ("className:${it.pageName}") if(TextUtils.equals(Constants.GlobalValue.PACKAGE_DOUYIN,it.packageName)){ CommonAccessbility.INSTANCE.ignoreDouyinPage(it.pageName) when(it.pageName){ Constants.Douyin.PAGE_MAIN, Constants.Douyin.PAGE_LIVE_ROOM, Constants.Douyin.PAGE_LIVE_ANCHOR, Constants.Douyin.PAGE_LIVE_GIFT, Constants.Douyin.PAGE_LIVE_Follow, Constants.Douyin.PAGE_LIVE_MORE ->{ ObserverManager.instance.notifyObserver(Constants.Task.task3,it.pageName) } } }else if(TextUtils.equals(Constants.GlobalValue.PACKAGE_SOGOUOEM,it.packageName)){ CommonAccessbility.INSTANCE.ignoreSougouPage(it.pageName) } } } override fun onCreate() { //must 基础无障碍 baseService = this super.onCreate() //must 高级无障碍 gestureService = this floatWindow.build() CommonAccessbility.INSTANCE.initService(this) LivePlayAccessibility.INSTANCE.initService(this).setSocketClient(socketClient) AccountUpAccessbility.INSTANCE.initService(this) MyApplication.instance.getJobManager().addCallback(object : JobManagerCallback{ override fun onJobRun(job: Job, resultCode: Int) { LogUtils.logGGQ("onJobRun:${(job as BaseJob).data.task}---${resultCode}") } override fun onDone(job: Job) { val data = (job as BaseJob).data LogUtils.logGGQ("onDone:${data.task}") } override fun onAfterJobRun(job: Job, resultCode: Int) { LogUtils.logGGQ("onAfterJobRun:${(job as BaseJob).data.task}---${resultCode}") } override fun onJobCancelled( job: Job, byCancelRequest: Boolean, throwable: Throwable?) { LogUtils.logGGQ("onJobCancelled:${(job as BaseJob).data.task}---${byCancelRequest}---${throwable}") } override fun onJobAdded(job: Job) { LogUtils.logGGQ("onJobAdded:${(job as BaseJob).data.task}") } }) (getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager).addAccessibilityStateChangeListener { LogUtils.logGGQ("AccessibilityManager:${it}") if(it){ FloatWindow.get()?.run { if(!isShowing)show() } }else{ FloatWindow.get()?.run { if(isShowing)hide() } } } runnable.setListener(object : TimerTickListener { override fun onStart(name: String, job: String) { LogUtils.logGGQ("开始任务:${name} --- ${job}") uiHandler.sendMessage("开始任务:${name} --- ${job}") } override fun onTick(tick: Long) { LogUtils.logGGQ("tick:${tick}") uiHandler.sendMessage("tick:${tick}") } override fun onMark(mark: Long) { LogUtils.logGGQ("onMark:${mark}") uiHandler.clearMessage() uiHandler.sendMessage("onMark:${mark}") TaskUtils.wakeUpAndUnlock() } override fun onStop(name: String, job: String) { LogUtils.logGGQ("结束任务:${name} --- ${job}") uiHandler.sendMessage("结束任务:${name} --- ${job}") uiHandler.clearMessage() //重新运行辅助倒计时 runnable.isRuning().let { if(!it){ runnable.onReStart("app","task",max) } } if(TextUtils.equals(Constants.Task.douyin,name)){ when(job){ Constants.Task.task1 ->{ stopTask(job,false) } Constants.Task.task3 ->{ if(LivePlayAccessibility.INSTANCE.isInLiveRoom()){ stopTask(job,false) } } } } } }) socketClient.setListener(object : OnSocketListener { override fun call(entity: TaskEntity) { LogUtils.logGGQ("收到数据:${entity}") val software:String = entity.software val task:String = entity.task val message:String = entity.message if(!TextUtils.isEmpty(message)){ uiHandler.sendMessage(message) } if(!TextUtils.isEmpty(task) && !TextUtils.isEmpty(message) && TextUtils.equals(message,"stop") || TextUtils.equals(message,"cancel") ){ MyApplication.instance.getUiHandler().sendMessage(message) stopTask(task,true) return } if(TextUtils.equals(software,Constants.Task.douyin)){ when(task){ Constants.Task.task1 ->{ // 任务1 接收到数据 要回馈 val zxTime:String = entity.zx_time val minTime:String = entity.min_time val maxTime:String = entity.max_time if(!TextUtils.isEmpty(zxTime)){ CommonAccessbility.INSTANCE.douyin2Main() MyApplication.instance.getUiHandler().sendMessage("收到养号任务") CommonAccessbility.INSTANCE.waitForMainPage(object :CommonAccessbility.MainPageListener{ override fun call(b: Boolean) { if(b){ MyApplication.instance.getUiHandler().sendMessage("冷启动首页") LogUtils.logGGQ("冷启动首页") }else{ LogUtils.logGGQ("热启动首页") MyApplication.instance.getUiHandler().sendMessage("热启动首页") } scrollUp() WaitUtil.sleep(2000L) NodeUtils.tryWithText("推荐") // 任务1 接收到数据 要回馈 socketClient.onReceiveStatus() runnable.onReStart(software,task,zxTime.toLong() + Constants.GlobalValue.plusTime) // AccountUpAccessbility.INSTANCE.setSwiped(true) // AccountUpAccessbility.INSTANCE.doSwipe10(minTime,maxTime) MyApplication.instance.getJobManager().addJobInBackground(AccountTaskJob(TaskData(task = task,minTime = minTime,maxTime = maxTime))){ } } }) }else{ MyApplication.instance.getUiHandler().sendMessage("养号任务总时长有误") } } Constants.Task.task3 -> { // 任务3 接收到数据 要回馈 socketClient.onReceiveStatus() val zxTime:String = entity.zx_time val zhiboNum:String = entity.zhibo_num if(!TextUtils.isEmpty(zxTime) && !TextUtils.isEmpty(zhiboNum)){ runnable.onReStart(software,task,zxTime.toLong() + Constants.GlobalValue.plusTime) LivePlayAccessibility.INSTANCE.doLiveRoom(zhiboNum) } } Constants.Task.task4 -> { val content:String = entity.fayan val type:String = entity.fayan_type var delayTime:Long = 1000L if(!TextUtils.isEmpty(entity.interval) && entity.interval.toInt() > 0){ delayTime = entity.interval.toInt()*1000L } MyApplication.instance.getJobManager().addJobInBackground(LiveTaskJob(TaskData(task = task,type = type,content = content,delayTime = delayTime))){ } } Constants.Task.task6 ->{ val zxTime:String = entity.zhixing_time if(!TextUtils.isEmpty(zxTime) && zxTime.toLong() > 0){ MyApplication.instance.getJobManager().addJobInBackground(LiveTaskJob(TaskData(task = task,zxTime = (zxTime.toLong() * 1000L)))){ //回调 } } } Constants.Task.task9 ->{ MyApplication.instance.getJobManager().addJobInBackground(LiveTaskJob(TaskData(task = task))){ //回调 } } } } } }) } private fun stopTask(task:String,isNormal:Boolean = true) { when(task){ Constants.Task.task1 ->{ //任务结束 停止所有job MyApplication.instance.getJobManager().cancelJobsInBackground(CancelResult.AsyncCancelCallback {cancelResult -> LogUtils.logGGQ("任务结束停止所有job") }, TagConstraint.ALL,"job") socketClient.sendSuccess() AccountUpAccessbility.INSTANCE.setSwiped(false) TaskUtils.openHomeAndKill(Constants.GlobalValue.PACKAGE_DOUYIN) } Constants.Task.task3 -> { //任务结束 停止所有job MyApplication.instance.getJobManager().cancelJobsInBackground(CancelResult.AsyncCancelCallback {cancelResult -> LogUtils.logGGQ("任务结束停止所有job") }, TagConstraint.ALL,"job") if(LivePlayAccessibility.INSTANCE.getLoopSpeak()){ socketClient.sendSuccess() } if (isNormal && LivePlayAccessibility.INSTANCE.isInLiveRoom()) { socketClient.sendParentSuccess() } else { socketClient.sendParentError() } LivePlayAccessibility.INSTANCE.setLoopSpeak(false) LivePlayAccessibility.INSTANCE.setInLiveRoom(false) LivePlayAccessibility.INSTANCE.setLiveURI("") ObserverManager.instance.remove(task) CommonAccessbility.INSTANCE.douyin2MainWithText("推荐") TaskUtils.openHomeAndKill(Constants.GlobalValue.PACKAGE_DOUYIN) } } if(isNormal){ uiHandler.sendMessage("正常结束") }else{ uiHandler.sendMessage("延时结束") } } override fun onServiceConnected() { super.onServiceConnected() socketClient.onConnect() runnable.isRuning().let { if(!it){ service.scheduleAtFixedRate(runnable,initialDelay,period, TimeUnit.SECONDS) runnable.onReStart("app","task",max) } } } override fun onInterrupt() { super.onInterrupt() } override fun onDestroy() { //must 基础无障碍 baseService = null super.onDestroy() //must 高级无障碍 gestureService = null FloatWindow.destroy() } inner class MyViewStateListener : ViewStateListener { override fun onBackToDesktop() { LogUtils.logGGQ("onBackToDesktop") } override fun onMoveAnimStart() { LogUtils.logGGQ("onMoveAnimStart") } override fun onMoveAnimEnd() { LogUtils.logGGQ("onMoveAnimEnd") } override fun onPositionUpdate(x: Int, y: Int) { LogUtils.logGGQ("onPositionUpdate") } override fun onDismiss() { LogUtils.logGGQ("onDismiss") } override fun onShow() { LogUtils.logGGQ("onShow") FloatWindow.get()?.view?.let { uiHandler.initFloater( it.findViewById(R.id.sv_container), it.findViewById(R.id.tv_msg) ) } } override fun onHide() { LogUtils.logGGQ("onHide") } } inner class MyPermissionListener : PermissionListener { override fun onSuccess() { LogUtils.logGGQ("FloatWindow onSuccess") } override fun onFail() { LogUtils.logGGQ("FloatWindow onFail") } } }<file_sep>package com.pinduo.auto.http.entity data class TaskEntity(val code:Int = 0, val status:Int = 0, val message:String = "", val device:String = "", val zx_time:String = "", val software:String = "", val task:String = "", val min_time:String = "", val max_time:String = "", val baifenbi:String = "", val fayan:String = "~", val apk_url:String = "", val apk_version_code:String = "", val other_version_name:String = "", val other_url:String = "", val sw_id_url:String = "", val content:String = "", val interval:String = "", val zhibo_num:String = "", val is_attention:String = "", val hot_num:String = "", val is_send_heart:String = "", val zhixing_time:String = "", val query_task_id:String = "", val p_query_task_id:String = "", val fayan_type:String = "1" // 3循环发言,默认随机发言 )<file_sep>package com.pinduo.auto.utils import android.os.Handler import android.os.Looper import android.widget.ScrollView import android.widget.TextView class UiHandler:Handler(Looper.getMainLooper()) { private val sBuilder by lazy { java.lang.StringBuilder() } private var svContainer:ScrollView? = null private var tvMsg:TextView? = null fun initFloater(sv:ScrollView,tv:TextView){ this.svContainer = sv this.tvMsg = tv } fun sendMessage(msg:String){ post { sBuilder.append(msg) sBuilder.append("\n") tvMsg?.setText(sBuilder.toString()) svContainer?.fullScroll(ScrollView.FOCUS_DOWN) } } fun clearMessage(){ sBuilder.setLength(0) } }<file_sep>package com.pinduo.auto.widget.observers interface ObserverListener { fun observer(content: String) }
30256bbabd48b0474e45bbdc86c714ab777d679f
[ "Java", "Kotlin", "Gradle" ]
47
Kotlin
gaoguanqi/PinduoApp
c42ec2a8cf0a268d1ac8cc7713637369b99a8681
ea79c5a3080cbeea3207ff09d50a016dda14bd6a
refs/heads/master
<repo_name>Rolo96/DockerPython<file_sep>/README.md # Products API (Python Docker) ``` Technological Institute of Costa Rica Project2 CompraTec Teacher: <NAME> Students: <NAME>, <NAME> Script docker swarm ``` ## Products model ``` name: string code: int cost: int amount: int ``` ## API usage ### Consult To consult the products, the following query is used: ``` { GetProducts(code:1){ name code cost amount } } ``` Where you can use any parameter, none or all those specified in the model. ### Insert To insert the products the following mutation is used: ``` mutation{ createProduct(name: "test2", amount: 2, cost: 2, code: 2){ product { id name } } } ``` Where in the result you can consult any of the attributes of the created product. ### Update To update the products the following mutation is used: ``` mutation{ updateProductCost(name: "Test", code:1, cost:1){ product{ name } } } ``` Where the name and code of the product is received as parameters to modify the cost, and in the result you can consult any of the attributes of the updated product. ## Delete To delete the products the following mutation is used: ``` mutation{ deleteProduct(code:1 ){ product{ name } } } ``` Where the code of the product to be deleted is received as a parameter, and in the result you can consult any of the attributes of the deleted product. <file_sep>/database.py from mongoengine import connect from models import Product connect(host='mongomock://localhost') def init_db(): test = Product(name='Test', code = 1, amount = 1, cost = 1) test.save() <file_sep>/models.py from datetime import datetime from mongoengine import Document, EmbeddedDocument from mongoengine.fields import ( DateTimeField, EmbeddedDocumentField, ListField, ReferenceField, StringField,IntField ) class Product(Document): meta = {'collection': 'product'} name = StringField() code = IntField() amount = IntField() cost = IntField() <file_sep>/schema.py import graphene from graphene.relay import Node from graphene_mongo import MongoengineConnectionField, MongoengineObjectType from models import Product as ProductModel class Product(MongoengineObjectType): class Meta: model = ProductModel interfaces = (Node,) class Query(graphene.ObjectType): node = Node.Field() GetProducts = graphene.List(Product, name=graphene.String(), code=graphene.Int(), cost=graphene.Int(), amount=graphene.Int(), ) def resolve_GetProducts(self, info, **kwargs): return list(ProductModel.objects.filter(**kwargs)) class CreateProduct(graphene.Mutation): class Arguments: name = graphene.String(required=True) code = graphene.Int(required=True) amount = graphene.Int(required=True) cost = graphene.Int(required=True) product = graphene.Field(Product) def mutate(self, info, **kwargs): product = ProductModel(**kwargs) product.save() return CreateProduct(product=product) class DeleteProduct(graphene.Mutation): class Arguments: code = graphene.Int(required=True) product = graphene.Field(Product) def mutate(self, info, code): product = ProductModel.objects(code=code).first() if product is not None: product.delete() return DeleteProduct(product=product) class UpdateProductCost(graphene.Mutation): class Arguments: name = graphene.String(required=True) code = graphene.Int(required=True) cost = graphene.Int(required=True) product = graphene.Field(Product) def mutate(self, info, name, code, cost): product = ProductModel.objects(name=name, code=code).first() if product is not None: product.update(cost=cost) return UpdateProductCost(product=product) class Mutation(graphene.ObjectType): create_product = CreateProduct.Field() delete_product = DeleteProduct.Field() update_product_cost = UpdateProductCost.Field() schema = graphene.Schema(query=Query, types=[Product], mutation=Mutation)
334830217cc24ecc2f58d33b7bdf79861e16dd7c
[ "Markdown", "Python" ]
4
Markdown
Rolo96/DockerPython
1676056d6d8dd14f19bacc6ec1b58e8ee2946de7
dfa2e876a1b4744bad1aa922ed1595893669e7e8
refs/heads/master
<file_sep>#include <assert.h> #include <sstream> #include <iostream> #include "CalcFramer.hpp" using namespace std; void CalcFramer::append(string chars) { // PUT YOUR CODE HERE // std::stringstream ss(chars); // string item; // while(std::getline(ss, item, '\n')) { // m_buffer += item.substr(0, item.size()-1); // m_buffer += "CRLF"; // } int j = 0; if (chars[0] == '\n') chars = chars.substr(1); for(int i=0; i<chars.size(); i++) { if( i+1 < chars.size() && chars.substr(i, 2) == "\r\n") { m_buffer += chars.substr(j, i-j); m_buffer += "CRLF"; j = i + 2; } } m_buffer += chars.substr(j); int size = m_buffer.size(); if (m_buffer[size-1] == '\r') { m_buffer += "CRLF"; } // cout << m_buffer << endl; } bool CalcFramer::hasMessage() const { // PUT YOUR CODE HERE // cout << "current Message is:" << m_buffer << endl; for (int i=0; i<m_buffer.size(); i++) { if( i+3 < m_buffer.size() && m_buffer.substr(i, 4) == "CRLF") { return true; } } // cout << "no Message" << endl; return false; } string CalcFramer::topMessage() const { // PUT YOUR CODE HERE string ret = ""; for(int i=0; i<m_buffer.size(); i++) { if( i+3 < m_buffer.size() && m_buffer.substr(i, 4) == "CRLF") { ret = m_buffer.substr(0, i); // if(ret.size()>0)cout << "topMessage is" << ret << endl; // else cout<<"empty"<<endl; return ret; } } return ret; } void CalcFramer::popMessage() { // PUT YOUR CODE HERE for(int i=0; i<m_buffer.size(); i++) { if( i+3 < m_buffer.size() && m_buffer.substr(i, 4) == "CRLF") { if(i+4 < m_buffer.size()) { m_buffer = m_buffer.substr(i+4); } else { m_buffer = ""; } return; } } } void CalcFramer::printToStream(ostream& stream) const { // PUT YOUR CODE HERE string tmp; int j = 0; for(int i=0; i<m_buffer.size(); i++) { if( i+3 < m_buffer.size() && m_buffer.substr(i, 4) == "CRLF") { tmp += m_buffer.substr(j, i-j); j = i + 4; } } stream << tmp; } <file_sep>#ifndef HTTPPARSER_HPP #define HTTPPARSER_HPP #include <string> #include <stdint.h> #include <unordered_map> using namespace std; // Format of http request typedef struct http_request { string method; // GET string URL; string http_version; // HTTP/1.1 unordered_map<string, string> key_values; bool valid; } httpRequest; // Format of http response typedef struct http_response { string http_version; string status; // 200, 400, 403, 404 string text; string body; string path; // requested valid file path unordered_map<string, string> key_values; } httpResponse; class httpParser { public: // parse read-in message into httpRequest format static httpRequest parse(string http_str); // from httpResponse format construct response header static string create_response(httpResponse responseMsg); }; #endif // HTTPPARSER_HPP <file_sep>#ifndef HTTPFRAMER_HPP #define HTTPFRAMER_HPP #include <iostream> class httpFramer { public: // append message to m_buffer void append(std::string chars); // check if buffer contain at least one complete message bool hasMessage() const; // return the first complete message std::string topMessage() const; // pop out the first complete message void popMessage(); protected: std::string m_buffer; }; #endif // HTTPFRAMER_HPP <file_sep>#include <assert.h> #include <sstream> #include <iostream> #include "httpFramer.hpp" using namespace std; void httpFramer::append(string chars) { m_buffer += chars; } bool httpFramer::hasMessage() const { int m_buffer_len = m_buffer.size(); for (int i=0; i<m_buffer_len; i++) { if( i+3 < m_buffer_len && m_buffer.substr(i, 4) == "\r\n\r\n") { return true; } } return false; } string httpFramer::topMessage() const { string ret = ""; int m_buffer_len = m_buffer.size(); for(int i=0; i<m_buffer_len; i++) { if( i+3 < m_buffer_len && m_buffer.substr(i, 4) == "\r\n\r\n") { ret = m_buffer.substr(0, i); return ret; } } return ret; } void httpFramer::popMessage() { int m_buffer_len = m_buffer.size(); for(int i=0; i<m_buffer_len; i++) { if( i+3 < m_buffer_len && m_buffer.substr(i, 4) == "\r\n\r\n") { if(i+4 < m_buffer_len) { m_buffer = m_buffer.substr(i+4); } else { m_buffer = ""; } return; } } } <file_sep>#include <assert.h> #include <sstream> #include <iostream> #include <vector> #include <algorithm> #include "httpParser.hpp" using namespace std; http_request httpParser::parse(std::string http_str) { httpRequest* ret = new httpRequest(); string header; vector<string> pairs; string key_values; if (http_str.size() == 0) { ret->valid = false; return *ret; } ret->valid = true; // parse http_str into header and key_value lines int http_str_len = http_str.size(); for(int i=0; i < http_str_len; i++) { if( i+1 < http_str_len && http_str.substr(i, 2) == "\r\n") { header = http_str.substr(0, i); key_values = http_str.substr(i+2); break; } } int j = 0; int key_values_len = key_values.size(); for(int i=0; i < key_values_len; i++) { if( i+1 < key_values_len && key_values.substr(i, 2) == "\r\n") { pairs.push_back(key_values.substr(j, i-j)); j = i + 2; } } pairs.push_back(key_values.substr(j)); // parse header into httpRequest std::stringstream ss(header); getline(ss, ret->method, ' '); if (ret->method != "GET") { ret->valid = false; return *ret; } getline(ss, ret->URL, ' '); if (ret->URL == "/") { ret->URL = "/index.html"; } getline(ss, ret->http_version); if (ret->http_version != "HTTP/1.1") { ret->valid = false; return *ret; } // parse key_value pairs string key, value; for (string pair: pairs) { pair.erase(std::remove(pair.begin(), pair.end(), ' '), pair.end()); std::stringstream item(pair); // missing colon is invalid if (pair.find(":") == std::string::npos) { ret->valid = false; break; } getline(item, key, ':'); getline(item, value); // empty key is invalid if (key != "") { ret->key_values[key] = value; } else { ret->valid = false; } } if (!ret->key_values.count("Host")) { ret->valid = false; } return *ret; } string httpParser::create_response(httpResponse responseMsg) { string ret; ret = responseMsg.http_version + " " + responseMsg.status + " " + responseMsg.text + "\r\n"; ret = ret + "Server: " + responseMsg.key_values["Server"] + "\r\n"; if (responseMsg.status == "200") ret = ret + "Last-Modified: " + responseMsg.key_values["Last-Modified"] + "\r\n"; ret = ret + "Content-Type: " + responseMsg.key_values["Content-Type"] + "\r\n"; ret = ret + "Content-Length: " + responseMsg.key_values["Content-Length"] + "\r\n"; ret += "\r\n"; if (responseMsg.body != "") { ret += responseMsg.body; ret += "\r\n"; } return ret; } <file_sep>#include <sys/stat.h> /* for struct stat and stat() */ #include "fileHelper.hpp" using namespace std; string get_last_modified(const string abs_path) { struct stat stbuf; ::stat(abs_path.c_str(), &stbuf); struct tm *mtm = gmtime(&stbuf.st_mtime); char buf[256]; int len = strftime(buf, 256, "%A, %d %m %Y %H:%M:%S GMT", mtm); return string(buf, len); } string get_content_type(const string abs_path) { string type = abs_path.substr(abs_path.size()-4); string ret; if (type == ".png") { ret = "image/png"; } else if (type == ".jpg") { ret = "image/jpeg"; } else if (type == "html") { ret = "text/html"; } return ret; } long get_content_Length(const string abs_path) { struct stat stat_buf; int rc = stat(abs_path.c_str(), &stat_buf); return rc == 0 ? stat_buf.st_size : -1; } bool file_exists(const string abs_path) { struct stat st; return ::stat(abs_path.c_str(), &st) == 0; } bool has_permission(const string abs_path) { struct stat st; ::stat(abs_path.c_str(), &st); return st.st_mode & S_IROTH; } <file_sep>CC=g++ CFLAGS=-std=c++11 #-Wall -Wextra -pedantic DEPS = httpd.h httpParser.hpp httpFramer.hpp fileHelper.hpp SRCS = httpd.cpp httpParser.cpp httpFramer.cpp fileHelper.cpp MAIN_SRCS = $(wildcard *.cpp) MAIN_OBJS = $(MAIN_SRCS:.cpp=.o) default: httpd httpd: $(MAIN_OBJS) $(CC) $(CFLAGS) -o $@ $(MAIN_OBJS) -lpthread %.o: %.cpp $(CC) $(CFLAGS) -c -o $@ $< .cpp.o: $(CC) $(CFLAGS) -c $< -o $@ clean: rm -f httpd *.o <file_sep>#include <stdio.h> /* for printf() and fprintf() */ #include <sys/socket.h> /* for recv() and send() */ #include <unistd.h> /* for close() */ #include <iostream> #include <assert.h> #include <inttypes.h> #include "CalcServer.h" #include "CalcFramer.hpp" #include "CalcParser.hpp" using namespace std; void HandleTCPClient(int clntSocket) { // PUT YOUR CODE HERE char readBuffer[2048]; /* Buffer for echo string */ int recvMsgSize; /* Size of received message */ CalcFramer framer; CalcInstruction retCalInstr; string ansStr; /* Receive message from client */ while (1) { // printf("Handling client1"); if ((recvMsgSize = recv(clntSocket, readBuffer, 1024, 0)) <= 0) break; string readStr(readBuffer); framer.append(readStr.substr(0, recvMsgSize)); while (framer.hasMessage()) { /* Contain a full request */ /* parse it */ // printf("Handling client2 \n"); retCalInstr = CalcParser::parse(framer.topMessage()); framer.popMessage(); // when meet blank<CRLF>, send back client if (retCalInstr.operation == "") { ansStr = to_string(CalcParser::accumulator); ansStr += "\r\n"; CalcParser::accumulator = 0; char ans[ansStr.size()+1]; strcpy(ans, ansStr.c_str()); send(clntSocket, ans, ansStr.size(), 0); } } // cout << "ans is:" << ans <<endl; // char array[20]; // array[0] = 0, array[1] = 1; // send(clntSocket, (char*)(&array), 2*sizeof(int), 0); // recvMsgSize = 0; } close(clntSocket); /* Close client socket */ } <file_sep>#include <assert.h> #include <sstream> #include <iostream> #include "CalcParser.hpp" uint64_t CalcParser::accumulator = 0; CalcInstruction CalcParser::parse(std::string insstr) { CalcInstruction ret; // PUT YOUR CODE HERE // if(insstr == "CRLF") { // return ret; // } // cout << "input string is: " << insstr << endl; if (insstr.size() == 0) { return ret; } ret.operation = insstr.substr(0, 3); // cout << "operation is: " << ret.operation << endl; std::istringstream iss(insstr.substr(4)); iss >> ret.value; // cout << "value is: " << ret.value << endl; if(ret.operation == "ADD") { accumulator += ret.value; } else if (ret.operation == "SUB") { accumulator -= ret.value; } else if (ret.operation == "SET") { accumulator = ret.value; } else { // cout << "##################error#########" << endl; } return ret; } <file_sep>#ifndef HTTPD_H #define HTTPD_H #include <string> #include "httpFramer.hpp" #include "httpParser.hpp" #include "fileHelper.hpp" using namespace std; // start http connection void start_httpd(unsigned short port, string doc_root); // receive requests and send responses void handle_connection (int clientSocket, string root); // process input http request and create corresponding http response struct httpResponse process_request(httpRequest requestMsg, string doc_root); #endif // HTTPD_H <file_sep><<<<<<< HEAD Project 2 starter code Copyright (C) <NAME>, 2017, 2018. ## Overview This is the starter code for the Java implementation of SurfStore. ## To build the protocol buffer IDL into auto-generated stubs: $ mvn protobuf:compile protobuf:compile-custom ## To build the code: $ mvn package ## To run the services: $ target/surfstore/bin/runBlockServer $ target/surfstore/bin/runMetadataStore ## To run the client $ target/surfstore/bin/runClient ## To delete all programs and object files $ mvn clean ======= ## Overview This is the starter code for the Java implementation of SurfStore. $ target/surfstore/bin/runBlockServer $ target/surfstore/bin/runMetadataStore For Distributed scenario: $ target/surfstore/bin/runMetadataStore ../configs/configDistributed.txt -n No.MSD ## To run the client $ target/surfstore/bin/runClient Client now supports following commands: $ client /etc/myconfig.txt getversion myfile.txt $ client /etc/myconfig.txt delete myfile.txt $ client /etc/myconfig.txt upload /home/aturing/myfile.txt $ client /etc/myconfig.txt download myfile.txt /home/aturing/downloads $ client /etc/myconfig.txt crash No.MSD $ client /etc/myconfig.txt restore No.MSD $ client /etc/myconfig.txt isCrash No.MSD ## To delete all programs and object files $ mvn clean >>>>>>> 9e400e554965c421fa2eef4f96312a7b0008a084 <file_sep>#include <sys/socket.h> /* for socket(), bind(), and connect() */ #include <sys/sendfile.h> /* for sendfile() */ #include <netinet/in.h> /* for sockaddr_in and inet_ntoa() */ #include <string.h> /* for memset() */ #include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */ #include <thread> /* for thread() */ #include <unistd.h> /* for close() */ #include <fcntl.h> /* for open() and O_RDONLY */ #include <sstream> /* for stringstream */ #include <limits.h> /* for PATH_MAX */ #include <errno.h> /* for errno */ #include "httpd.h" using namespace std; void start_httpd(unsigned short port, string doc_root) { cerr << "Starting server (port: " << port << ", doc_root: " << doc_root << ")" << endl; int serv_sock; int clnt_sock; struct sockaddr_in serv_addr; struct sockaddr_in clnt_addr; if ((serv_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { cerr << "Failed to create socket" << endl; exit(1); } // bind server socket to local port and start listening memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(port); if (::bind(serv_sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { cerr << "Failed to bind" << endl; exit(1); } if (listen(serv_sock, 10) < 0) { cerr << "Failed to listen" << endl; exit(1); } while (1) { // wait for client to connect unsigned int clnt_len = sizeof(clnt_addr); if ((clnt_sock = accept(serv_sock, (struct sockaddr *) &clnt_addr, &clnt_len)) < 0) { cerr << "Failed to accept" << endl; exit(1); } // connected to a client, handle concurrent connects with timeout cerr << "Server: got connection from " << inet_ntoa(clnt_addr.sin_addr) << " port " << ntohs(clnt_addr.sin_port) << endl; struct timeval timeout; timeout.tv_sec = 5; timeout.tv_usec = 0; if (setsockopt (clnt_sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0) { cerr << "setsockopt failed" << endl; exit(1); } if (setsockopt (clnt_sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0) { cerr << "setsockopt failed" << endl; exit(1); } std::thread td(handle_connection, clnt_sock, doc_root); td.detach(); } close(serv_sock); } void handle_connection (int clientSocket, string doc_root) { int clntSocket = clientSocket; const int BUFSIZE = 1024; char readBuffer[BUFSIZE+1]; int recvMsgSize; httpFramer framer; httpRequest requestMsg; httpResponse responseMsg; // Receive message from client while (1) { recvMsgSize = recv(clntSocket, readBuffer, BUFSIZE, 0); // handle time out case and create 400 response if (recvMsgSize < 0 && errno == EWOULDBLOCK) { cout << "Timeout" <<endl; responseMsg.http_version = "HTTP/1.1"; responseMsg.status = "400"; responseMsg.text = "Client Error"; responseMsg.key_values["Server"] = "localhost"; responseMsg.body = "<html><body><h1>400 Client Error</h1></body></html>"; responseMsg.key_values["Content-Type"] = "text/html"; responseMsg.key_values["Content-Length"] = to_string(responseMsg.body.size()); string retMsg = httpParser::create_response(responseMsg); const char *res = retMsg.c_str(); send(clntSocket, res, retMsg.size(), 0); break; } if (recvMsgSize < 0) { cerr << "Failed to receive" << endl; exit(1); } if (recvMsgSize == 0) { break; } // append message read to framer string readStr(readBuffer); framer.append(readStr.substr(0, recvMsgSize)); // while framer receives complete message, parser parses it into http request format while (framer.hasMessage()) { requestMsg = httpParser::parse(framer.topMessage()); framer.popMessage(); // server processes request, parser parses it into http response message responseMsg = process_request(requestMsg, doc_root); string retMsg = httpParser::create_response(responseMsg); // send back response header const char *res = retMsg.c_str(); send(clntSocket, res, retMsg.size(), 0); // if return code is 200, send back file if(responseMsg.status == "200") { int fd; if ((fd = open(responseMsg.path.c_str(), O_RDONLY)) < 0) { cerr << "Failed to read file" << endl; exit(1); } std::stringstream sstream(responseMsg.key_values["Content-Length"]); size_t len; sstream >> len; sendfile(clntSocket, fd, 0, len); close(fd); } if (requestMsg.key_values.count("Connection") && requestMsg.key_values["Connection"] == "close") break; } } close(clntSocket); } httpResponse process_request(httpRequest requestMsg, string doc_root) { httpResponse response; response.http_version = "HTTP/1.1"; // construct http response format if (requestMsg.valid) { string path = doc_root + '/' + requestMsg.URL; char buf[PATH_MAX + 1]; char* rp = ::realpath(path.c_str(), buf); // simplify absolute path // handle different file types if (rp!= NULL) { string abs_path(buf); if (abs_path.size() < doc_root.size() || abs_path.substr(0, doc_root.size()) != doc_root || !file_exists(abs_path)) { response.status = "404"; response.text = "Not Found"; response.key_values["Content-Type"] = "text/html"; } else if (has_permission(abs_path)) { response.status = "200"; response.text = "OK"; response.path = abs_path; response.key_values["Last-Modified"] = get_last_modified(abs_path); response.key_values["Content-Type"] = get_content_type(abs_path); response.key_values["Content-Length"] = to_string(get_content_Length(abs_path)); } else { response.status = "403"; response.text = "Forbidden"; response.body = "<html><body><h1>403 Forbidden</h1></body></html>"; response.key_values["Content-Type"] = "text/html"; response.key_values["Content-Length"] = to_string(response.body.size()); } } else { response.status = "404"; response.text = "Not Found"; response.body = "<html><body><h1>404 Not Found</h1></body></html>"; response.key_values["Content-Type"] = "text/html"; response.key_values["Content-Length"] = to_string(response.body.size()); } } else { response.status = "400"; response.text = "Client Error"; response.body = "<html><body><h1>400 Client Error</h1></body></html>"; response.key_values["Content-Type"] = "text/html"; response.key_values["Content-Length"] = to_string(response.body.size()); } if (requestMsg.key_values.count("Host")) { response.key_values["Server"] = requestMsg.key_values["Host"]; } else { response.key_values["Server"] = "unknown"; } return response; } <file_sep>#ifndef FILEHELPER_HPP #define FILEHELPER_HPP #include <string> using namespace std; // get last modified time of the file, return specific time format string get_last_modified(const string abs_path); // get type of the given file, html, png or jpg string get_content_type(const string abs_path); // get length of file content long get_content_Length(const string abs_path); // check if the given path exists a file bool file_exists(const string abs_path); // check if the corresponding file is "world readable" bool has_permission(const string abs_path); #endif // FILEHELPER_HPP <file_sep>#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <thread> // std::this_thread::sleep_for #include <chrono> // std::chrono::seconds #include <iostream> #include <string> // Client side C/C++ program to demonstrate Socket programming #define BUFSIZE 500 int main(int argc, char *argv[]) { long int port = strtol(argv[1], NULL, 10); std::string doc_root = argv[2]; struct sockaddr_in address; int sock = 0, valread; struct sockaddr_in serv_addr; std::string message = "GET " + doc_root + " HTTP/1.1\r\nHost: localhost\r\nUser-Agent: cse291-tester/1.0\r\n\r\n"; // char hello[BUFSIZE] = "GET /files//web.html HTTP/1.1\r\nHost: localhost\r\nUser-Agent: cse291-tester/1.0\r\n\r\n"; char buffer[1024] = {0}; if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { printf("\n Socket creation error \n"); return -1; } memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\nConnection Failed \n"); return -1; } int len = message.size(); for (int i = 0; i < len; ) { int j = i + rand() % (len - i) + 1; send(sock, message.substr(i, j - i).c_str(), j - i, 0); sleep(1); i = j; } // if (send(sock , message.c_str() , message.length() , 0 ) < 0) { // printf("error"); // }; // printf("Hello message sent\n"); int numRecv; numRecv = recv(sock, buffer, BUFSIZE, 0); // valread = read( sock , buffer, 1024); while(numRecv > 0) { printf("%s\n",buffer ); memset(buffer, 0, sizeof buffer); numRecv = recv(sock, buffer, BUFSIZE, 0); } // printf("%s\n",buffer ); // std::cout << "countdown:\n"; // for (int i=10; i>0; --i) { // std::cout << i << std::endl; // std::this_thread::sleep_for (std::chrono::seconds(1)); // } return 0; }
00ae6adc5fabe8570661ff65686116d00f69eba4
[ "Markdown", "C", "Makefile", "C++" ]
14
C++
yaxuanwang/UCSD_CSE291C_Project
a5ff167353f9f67dbff31904e9c78ec5a53f4d22
2fa6f1cc69078b08b12d905721772c0a3c0fce24
refs/heads/master
<file_sep># QBIndex QBIndex frontEnd Project # install npm install # package command command : npm run dev (run project in development) command : npm run compile (package project to the dist category)<file_sep>/** * Created by xiaolin on 16/12/15. */ import WebpackHotMiddleware from 'webpack-hot-middleware' import applyExpressMiddleware from '../lib/apply-express-middleware' const debug = require('debug')('app:server:webpack-hot') export default (compiler, opts) => { debug('Enable Webpack Hot Module Replacement (HMR).') const middleware = WebpackHotMiddleware(compiler, opts) return async function koaWebpackHMR (ctx, next) { let hasNext = await applyExpressMiddleware(middleware, ctx.req, ctx.res) if (hasNext && next) { await next() } } } <file_sep>/** * Created by xiaolin on 16/12/16. */ require('babel-register') require('es6-promise').polyfill() const config = require('../config') const debug = require('debug')('app:bin:compile') const fs = require('fs-extra') const paths = config.utils_paths const path = require('path') debug('Create webpack compiler.') const compiler = require('webpack')(require('../config/_basic_webpack')) var removeFile = function(_cat){ return new Promise(function(resolve,reject){ fs.remove(_cat, function (err) { if(err)reject(err) else resolve() }) }) } compiler.run(function (err, stats) { const jsonStats = stats.toJson() debug('Webpack compile completed.') var cat = '/Users/sean/work/qbii/trunk/qbii-app/src/main/webapp' var sourcePath = path.join(__dirname,'../dist') var fileName = '' var except = ['cdn'] return ; fs.stat(cat + fileName, function(err, stat) { if(err == null) { if(stat.isDirectory()) { debug('copy file begin......'); fs.readdir(cat + fileName,function(_path,_cat){ _cat.forEach(function(item,index,_sources){ if(index == _sources.length - except.length && item == 'cdn'){ fs.copy(sourcePath,cat+fileName, function(err) { if (err) return console.error(err) debug("success!") }); } else{ item != 'cdn' && removeFile(cat + fileName + '/' + item).then(()=>{ if(index == _sources.length - except.length){ fs.copy(sourcePath,cat+fileName, function(err) { if (err) return console.error(err) debug("success!") }); } }) } }) }) } else if(stat.isFile()) { console.log('文件存在'); } else { console.log('路径存在,但既不是文件,也不是文件夹'); //输出路径对象信息 console.log(stat); } } else if(err.code == 'ENOENT') { debug('copy file begin......') fs.mkdir(cat+fileName,function(err){ fs.copy(sourcePath,cat+fileName, function(err) { if (err) return console.error(err) debug("success!") }); }) } else { console.log('错误:' + err); } }); }) <file_sep>import React, { Component } from 'react' import classNames from 'classnames' import './index.less' class Icon extends Component { url = require(`./symbol-defs.svg`) constructor(props) { super(props) } render() { let { name, size, color, style, className } = this.props color = color || '#000' size = size || 16 name = `icon-${this.props.name}` return ( <svg style={{ width: size + 'px', height: size + 'px', fill: color, ...style }} className={classNames({icon:1,[className]:1})}> {<use xlinkHref={`${this.url}#${name}`}></use>} </svg> ) } } export default Icon<file_sep>import React, { Component }from 'react' import './page.less' import { Link } from 'react-router' import {fetchPosts} from "components/common/fetch"; // import { createCORSRequest } from 'libs/util' // let viHtml = '<div><p></p><p></p><p></p><p></p><p></p></div>'; class NewsDetail extends Component { constructor(props, context) { super(props, context); this.state={ detail:false } } componentWillMount() { let { projectId } = this.props.routeParams; let self = this; //console.log(projectId) ///qbii-app/ let time = Date.now(); fetchPosts("/api/news/getNewsDetail",{id:Number(projectId)},"GET").then((data)=>{ //console.log('返回结果为:',data.result.newsDetail); //debugger; let lTime = Date.now(); let timeout = (lTime-time<1000)?(1000-(lTime-time)):0; //setTimeout(function(){ if(data.code==0){ self.setState({ detail:data.result.newsDetail }) } //},timeout) }) } render() { let {detail} = this.state; let className =" newsDetail-loading-hide",info=detail; let newProps = {}; if(detail===false){ className = "";//mask-loading mask-loading-vi newProps.dangerouslySetInnerHTML = {__html:viHtml} info = {}; //return this.laoding(className); }else{ newProps.dangerouslySetInnerHTML={__html:decodeURIComponent(info.content)}; //console.log(info.content) } // let className = detail===false?" mask-loading mask-loading-vi":" "; // let info = detail===false?{}:detail; return ( <div className={"newsDetail-container"} > <div className="newsDetail-head "> <h2>{info.title}</h2> <div className="newsDetail-auth-info"> <em>{info.createTime&&info.createTime.substring(0,10)}</em> <em>{info.author}</em> <em></em> </div> </div> <div className="newsDetail-body" {...newProps} > </div> <div className="newsDetail-footer"> <em>阅读</em> <em>{info.watched}</em> </div> </div> ) } laoding(className){ return ( <div className={"newsDetail-container newsDetail-loading "+className}> <div className="newsDetail-head "> <h2></h2> <div className="newsDetail-auth-info"> <em></em> <em></em> <em></em> </div> </div> <div className="newsDetail-body"> <div><p></p><p></p><p></p><p></p><p></p></div> </div> <div className="newsDetail-footer"> <em></em> <em></em> </div> </div> ) } } export default NewsDetail <file_sep>import React, { Component, PropTypes } from 'react'; import ReactDom from "react-dom"; import { VelocityComponent,VelocityTransitionGroup } from "velocity-react"; import "./banner.less"; import Vedio from "./vedio"; import Swipe from "components/swipe/swipe"; class Banner extends Component { constructor(props) { super(props); } componentWillMount(){ } typeShow(type,item,i){ switch (type){ case "image":{ return ( <div key={i} className="order-banner-item"> <img src={item.url}/> </div> ); } case "video":{ return ( <div key={i} className="order-banner-item"> <Vedio bgUrl={item.url} src={item.data}/> </div> ); } default:{ return (JSON.stringify(type)); } } } render() { let {className,step} = this.props; let {items} = this.props; let i=0,length = items.length,$lis=[],self = this; while(i<length){ let item = items[i]; i+=1; $lis.push(self.typeShow(item.category,item,i)) } return ( <div className={"order-banner "+className}> {length>=2?(<Swipe min={-(length-1)*step} step={step} className="order-banner-items"> {$lis} </Swipe>):$lis} </div> ) } isSwipe(length){ if(length<1){ return } } } class Item extends Component { constructor(props) { super(props); } render() { let {} = this.props; return ( <div className={"order-banner"}> <div className="order-banner-items"> <div className="order-banner-item"> </div> </div> </div> ) } } Banner.defaultProps = { title:"", items:[], className:"", step:window.innerWidth } export default Banner; <file_sep>import React,{ Component } from 'react' import LinkedStateMixin from 'react-addons-linked-state-mixin' import ReactMixin from 'react-mixin'; import { connect } from 'dva' import CSSModules from 'react-css-modules' import styles from './page.less' import { Link } from 'react-router' import classNames from 'classnames' import { fetchPosts } from "components/common/fetch" import { priceFormat } from 'libs/util' import {Icon} from 'ui' class RollIn extends Component { constructor(props) { super(props) this.state = { canCommit: false, canGetCode: true, isPopShow: false, msg: '转入失败,请稍后重试', codeBtnMsg: '获取验证码', blance: 0, amount: '', pwd: '', code: '', loading: false } this.getBlance() } componentDidMount() { } componentDidUpdate() { } getBlance = () => { fetchPosts('/api/specialUser/qbiiUsableBalance',{},'GET').then(data=>{ if(data.code==0) { this.setState({ blance: data.result.blance }) } }) } handleCommit = () => { let {amount,pwd,code} = this.state let msg = !amount ? '请输入您要转入的金额' : amount <= 0 ? '请输入正确的金额' : !pwd ? '请输入交易密码' : !code ? '请输入验证码' : this.setState({canCommit:true}, ()=>{ if (this.state.canCommit) { this.setState({loading:true}) fetchPosts('/api/specialUser/changeQbii',{ traderPwd: pwd, verifyCode: code, money: amount },'GET').then(data=>{ if(data.code==0) { setTimeout(()=>{ QBFK.Business.go('/') }, 1000); } this.setState({loading:false}) this._pop(data.message) }) } }) !this.state.canCommit && this._pop(msg) } handleGetCode = () => { if (!this.state.canGetCode) {return} fetchPosts('/api/specialUser/sendSmsCode', {}, 'GET').then(data => { if(data.code==0) { let count = 60 const timer = () => { if (count == 0) { this.setState({ codeBtnMsg: '获取验证码', canGetCode: true }) } else { this.setState({codeBtnMsg: `${count--}s 后重新获取`}) setTimeout(timer, 1000); } } timer() this.setState({ canGetCode: false }) } this._pop(data.message) }) } onAmountChange(e){ let reg = /^([0-9]\d*|0)?(\.)?(\d{1,2})?$/, value = e.target.value; if(value === "" || reg.test(value)){ this.setState({amount: value}) } } // <input type="text" placeholder="请输入您要转入的金额" value={amount} onChange={(e)=>this.onAmountChange(e)}/> render() { let { form, amount } = this.state return ( <div styleName="roll-in-container"> <div styleName="top"> <h4>可转余额(元)</h4> <h1>{priceFormat(this.state.blance)}</h1> <p>转入QBII资产,需要将您可提余额账户资产转入QBII账户,立即到账。</p> </div> <div styleName="form"> <div styleName="field"> <span styleName="label">输入金额:</span> <input type="number" placeholder="请输入您要转入的金额" value={amount} onChange={(e)=>this.onAmountChange(e)} min="0.01"/> <div styleName="unit">(元)</div> </div> <div styleName="field"> <span styleName="label" >交易密码:</span> <input type="<PASSWORD>" placeholder="请输入<PASSWORD>" valueLink={this.linkState('pwd')}/> </div> <div styleName="field"> <span styleName="label">手机验证:</span> <input type="text" placeholder="请输入验证码" valueLink={this.linkState('code')}/> <span styleName={classNames('get-code', {'disable':!this.state.canGetCode})} onClick={this.handleGetCode}>{this.state.codeBtnMsg}</span> </div> </div> <div styleName="btn-commit" onClick={this.handleCommit} >确定</div> <div styleName={classNames("pop-container",{active:this.state.isPopShow})}> <div styleName="pop"> {this.state.msg} </div> </div> { this.state.loading ? (<div className="loading-bg"> <div className="loading-item"> <Icon name="spinner" color="#fff" size="32" styleName="loading" /> </div> </div>) : '' } </div> ) } _pop = msg => { this.setState({ msg, isPopShow: true },() => { setTimeout(() => { this.setState({ msg: '', isPopShow: false }) }, 2000); }) } }; function mapStateToProps(state) { return state.home; } function mapDispatchToProps(dispatch) { return { } } RollIn.PropTypes = { enterAnimation: { duration: 2000, animation: "slideDown" }, leaveAnimation:{ duration: 2000, animation:"slideUp" } } ReactMixin(RollIn.prototype, LinkedStateMixin) export default connect(mapStateToProps, mapDispatchToProps)(CSSModules(RollIn, styles, {allowMultiple: true})); <file_sep>import React, { Component, PropTypes } from 'react'; import { VelocityComponent } from "velocity-react"; class Ring extends Component { constructor(props) { super(props); let anAfter = this.getAn(props); this.state = { "doAn":false, "anBefore":{ duration:500, animation:{ height:"70px", rotateZ:0 }, }, "anAfter":{ duration:500, animation:anAfter } } this.handClick = this.handClick.bind(this); } getAn(props){ let {level,totalLevel} = props; //level = level-1; let sunLevel = Number(totalLevel); let rz = (180/sunLevel)*level||0; //let endHeight = rz>135?50:70; let endHeight = (70-50)/sunLevel*level; endHeight = 70 -endHeight; console.log("动画 ",{ height:endHeight, rotateZ:rz }); return { height:endHeight, rotateZ:rz } } componentDidMount(){ var self = this; self.setState({ doAn:true }); } handClick(){ var self = this; console.log("ppppppppp") self.setState({ doAn:!self.state.doAn }) } render() { let {levelName} = this.props; let anProps = this.state.doAn===false?this.state.anBefore:this.state.anAfter; return ( <div className="ring" onClick={this.handClick}> <div className="container-ring"> <span className="outer-ring"></span> <span className="inner-ring"></span> <div className="content-ring"> <span>QBII</span> <span>认证等级</span> <span>{levelName}</span> </div> </div> <VelocityComponent {...anProps}> <div className="container-ring-hide"> <span className="outer-ring"></span> <span className="inner-ring"></span> </div> </VelocityComponent> </div> ) } } Ring.defaultProps = { level: 5, levelName:"Pro", totalLevel:5 } export default Ring;<file_sep> import React, { Component, PropTypes } from 'react'; import Scroll from "components/swipe/scroll"; import "./page.scss"; const Status = { "待审核":"step1", "已生效":"step2", "已取消":"step3", "已结算":"step4", } class OrderList extends Component { constructor(props) { super(props); } componentWillMount(){ } renderItem(item,i){ //debugger; var step = Status[item.statusDes]||"step1"; return(<div key={i} className={"order-list-item "+step}> <p>{item.projectName}</p><div className="exc">{item.statusDes}</div> <div> <span>{item.createTime.substr(0,10)}<em>下单时间</em></span> <span>{item.amountDes+"万"}<em>订单金额</em></span> <span>{item.proportionDes}<em>投资额占比</em></span> </div> </div>) } analysis_data(data){ if(data.code===0){ return data.result.orderList; } return false; } render() { let {scrollOptions} = this.props; let props = Object.assign({},scrollOptions,{ analysis_data:this.analysis_data, renderItem:this.renderItem }) return ( <div className="container-order-list"> <Scroll {...props}/> </div> ) } } /* <Chart projectId={this.props.routeParams.projectId}/> */ OrderList.defaultProps = { type:1, scrollOptions:{ url:"/api/user/userOrderList", pageName:"pageNo", totalProps:{className:'order-list'} } } export default OrderList; //export default withRouter(OrderInfo); //<div className="theme-img"></div> <button><span className="step-download"></span></button> <file_sep>import React, { Component, PropTypes } from 'react'; import ReactDom from "react-dom"; import "./page.less"; import Swipe from "components/swipe/swipe"; class DemoSwipe extends Component { constructor(props) { super(props); } componentWillMount(){ } componentDidMount(){ } render() { let props = { min: -60, max: 0, step: 60, findScroller: ".div1", vertical:true } return ( <Swipe className="demo-swipe" property="translateY" {...props}> <div className="div1">1</div> <div className="div1">2</div> <div className="div1">3</div> <div className="div1">4</div> </Swipe> ) } } DemoSwipe.defaultProps = { } export default DemoSwipe; <file_sep>/** * Created by xiaolin on 16/12/15. */ export default config => ({ compiler_public_path: `http://${config.server_host}:${config.server_port}/` })<file_sep>import React, { Component, PropTypes } from 'react'; import ReactDom from "react-dom"; import "./input.less"; class Input extends Component { constructor(props) { super(props); this.handFocus = this.handFocus.bind(this); this.handBlur = this.handBlur.bind(this); this.handChange = this.handChange.bind(this); this.state = { value:"" } } componentWillMount(){ } handFocus(){ var $in = ReactDom.findDOMNode(this.refs.input); $in.focus(); } handChange(e){ let {maxLength} = this.props; this.setState({ value:e.target.value.substr(0, maxLength) }) } handBlur(){ let {onChange,name} = this.props; onChange && onChange(name, this.state.value); } render() { let {className,title,maxLength,placeholder,type} = this.props; let {value} = this.state; let inProps = { placeholder:title, value, maxLength, type, ref:"input", onChange:this.handChange, onBlur:this.handBlur } return ( <div className={"virtual-input "+className} > <input {...inProps} /> </div> ) } } //onClick={this.handFocus} Input.defaultProps = { maxLength:20, title:"请传入一个title", className:"", placeholder:"", name:"必须要有一个name", type:"text" } // <label>{title}</label> // <i></i> export default Input; /** * * * type: 'success', buttonConfirm: function () { }, errorShow: false, */ //<div className="theme-img"></div><file_sep> import React, { Component, PropTypes } from 'react'; import Scroll from "components/swipe/scroll" import "./page.scss"; import {priceFormat} from 'libs/util' function toThousands(num) { var num = (num || 0).toString(), result = ''; while (num.length > 3) { result = ',' + num.slice(-3) + result; num = num.slice(0, num.length - 3); } if (num) { result = num + result; } return result; }; class ProfitList extends Component { constructor(props) { super(props); } componentWillMount(){ } renderItem(item,i){ //debugger; return(<div key={i} className="profit-list-item" > <p>{item.profitTime.substr(0,7)}</p> <div className="profit-list-item-main"> <div className="profit-list-item-info"> <i>{item.projectName.substr(0,1)}</i> <div> <span>{priceFormat(item.totalAmount/100)+"元"}</span> <em>{item.projectName}</em> </div> </div> <span className="item-icon-right"><i></i></span> <span className="item-tab">{priceFormat(item.profitAmount/100)}<em>利润分红(元)</em></span> <span className="item-tab">{priceFormat(item.assetAmount/100)}<em>股本增值(元)</em></span> </div> </div>) } analysis_data(data){ if(data.code===0){ return data.result.profitList; } return false; } nullRender() { return <div style={{textAlign:'center',paddingTop:'10px'}}>暂无收益</div> } render() { let {scrollOptions} = this.props; let props = Object.assign({},scrollOptions,{ analysis_data:this.analysis_data, renderItem:this.renderItem, nullRender:this.nullRender }) return ( <div className="container-profit-list"> <Scroll {...props}/> </div> ) } } ProfitList.defaultProps = { scrollOptions:{ url:"/api/user/userProfitList", pageName:"pageNo", totalProps:{className:'profit-list'} } } export default ProfitList;<file_sep>import React, { Component } from 'react' import CSSModules from 'react-css-modules' import styles from './page.less' import { Icon } from 'ui' class IconDoc extends Component { constructor(props) { super(props) this.state = { txt: '' } let url = require('components/ui/icon/symbol-defs.svg') getText(url).then( data => { this.setState({ txt: data }) }, function (error) { console.error('Error:', error) }) } render() { let { txt } = this.state if (txt === '') return '' let icons = txt.match(/icon-[A-Za-z0-9-]+(?=")/gm) console.log('Icons count:'+icons.length) return ( <div styleName="home-container"> <ul styleName="icons"> <li><Icon name="spinner" color="#427cf3" size="32" styleName="loading" /><span styleName="title">spinner</span></li> <li><Icon name="home3" color="#427cf3" size="32" style={{ opacity: 0.4 }} /><span styleName="title">home3</span></li> { icons.map((item, index) => { item = item.replace(/icon-/ig, '') return <li key={index}> <Icon name={item} color="#427cf3" size="32" /> <span styleName="title">{item}</span> </li>}) } </ul> </div> ) } } function getText(url) { var promise = new Promise(function (resolve, reject) { var client = new XMLHttpRequest() client.open("GET", url) client.onreadystatechange = handler client.responseType = "text" client.setRequestHeader("Accept", "text/plan") client.send() function handler() { if (this.readyState !== 4) { return } if (this.status === 200) { resolve(this.response) } else { reject(new Error(this.statusText)) } } }) return promise; }; export default CSSModules(IconDoc, styles, { allowMultiple: true });<file_sep> import React, {Component, PropTypes} from 'react'; import * as ReactDOM from 'react-dom'; import {_} from "./help.js"; class Swipe extends Component { constructor(props) { super(props); this.state = { value: props.value, isShowLoad:true }; this.scrollInit = this.scrollInit.bind(this); //this.scrollEnd = this.scrollEnd.bind(this); //this.upFn = this.upFn.bind(this); //this.handleBlur = this.handleBlur.bind(this); } componentWillMount(){ let _this = this; _this.AlloyTouch = false; require.ensure([], () => { _this.AlloyTouch = require("./alloyTouch.js"); }) } componentWillReceiveProps(nextProps){ if(nextProps.isShowLoad!==undefined&&nextProps.isShowLoad!==this.state.isShowLoad){ this.setState({ isShowLoad:nextProps.isShowLoad }) } } componentDidUpdate(prevProps,prevState){ /* if(this.AlloyTouch&&prevState.isShowLoad!==this.state.isShowLoad){ //console.log("掉用这里?") this.scrollInit(); }*/ let {stopPro,property,width,min,max,step,findScroller,vertical,findDis,touchMove} = this.props; if(min==="auto"&&this.alloyTouch&&vertical===true&&property==="translateY"){ // debugger; let target = ReactDOM.findDOMNode(this.refs.swipe); let dom = ReactDOM.findDOMNode(this.refs.touch); //offsetTop let length = -(target.clientHeight-dom.clientHeight); this.alloyTouch.min = length>0?0:length; } } componentDidMount(){ let _this = this; if(_this.AlloyTouch){ _this.scrollInit() }else{ require.ensure([], () => { _this.AlloyTouch = require("./alloyTouch.js"); _this.scrollInit(); }) } } componentWillUnmount(){ //debugger this.alloyTouch&&this.alloyTouch.destory(); } scrollInit(){ let dom = ReactDOM.findDOMNode(this.refs.touch); //offsetTop let target = ReactDOM.findDOMNode(this.refs.swipe); let {intervals,stopPro,property,width,min,max,step,findScroller,vertical,findDis,touchMove} = this.props; let prevTarget = false; //let $ = this.$; // if(findDis!==false){ // let dis = $(findDis,$(dom)).eq(0).width(); // min = -dis; // step = dis; // } //console.log("dom",dom); if(min==="auto"){ min = -1000; min = -((vertical===false?target.offsetWidth:target.offsetHeight)-(vertical===false?dom.offsetWidth:dom.offsetHeight)); console.log(min); min = min>0?0:min; } this.alloyTouch = new this.AlloyTouch({ touch: dom,//反馈触摸的dom target:target, vertical: vertical,//不必需,默认是true代表监听竖直方向touch target: target, //运动的对象 property: property, //被运动的属性 sensitivity: 1,//不必需,触摸区域的灵敏度,默认值为1,可以为负数 factor: 1,//不必需,表示触摸位移与被运动属性映射关系,默认值是1 min: min, //不必需,运动属性的最小值 max: max, //不必需,滚动属性的最大值 step: step, spring: true, //不必需,是否有回弹效果。默认是true inertia: false, //不必需,是否有惯性。默认是true intelligentCorrection: true, stopPro:stopPro, touchStart: function (value,target) { console.log("heheda ",value) }, touchMove:_.throttle(function(){ touchMove(this,arguments); },intervals), }); } render() { let {onClick} = this.props; return ( <div className={this.props.className} ref="touch" style={this.props.style} onClick={onClick}> <div ref="swipe"> {this.props.children} </div> </div> ); } } Swipe.defaultProps={ property:"translateX", width:false, min:0, max:0, step:0, vertical:false, findScroller:false, target:"", className:"", findDis:false, stopPro:true, intervals:300,//间隔时间 touchMove:function(x){ //console.error("sssssss",this,x) }, onClick:function(){ } } module.exports = Swipe; <file_sep> import React, { Component, PropTypes } from 'react'; import { connect } from 'dva'; import {withRouter} from "react-router"; import isObject from "lodash/isObject"; import isArray from "lodash/isArray"; //var moment = require('moment'); import {fetchPosts} from "components/common/fetch"; import {getCookie} from 'libs/util'; import Info from "./info.js"; import "./page.less"; import Vedio from "./vedio"; import Area from "./area.js"; //import Chart from "./chart.js"; class OrderInfo extends Component { constructor(props) { super(props); this.state={ heart:false, data:{ name:"", duration:"",//存续期限 direction:"",//投资方向 1股权 minPrice:"",//认购起点 des:"",//特色亮点, target:"",//目标规模 organization:"",//管理机构 // direction //投资方向 assetsType:"",// type//资本类型 1-本土 organizationType:"",//组织形式 1-有限合伙制 structured:"",//结构化 . 1-是,2-否 exitWay:["",""],//退出形式 trusteeFee:["",""],//认购费 . managementFee:["",""],//管理费 trusteeFee:["",""],//托管费 profit:"",//收益分配 pics:["","",""], video:"", applyFee:["",""] }, startDate:this.formate(), endDate:this.formate(2), disabled:true, now:false } this.getData = this.getData.bind(this); this.handThink = this.handThink.bind(this); this.handHeart = this.handHeart.bind(this); } componentWillMount(){ let levelName = getCookie("level","storage")||"暂无"; //debugger if(levelName!=="暂无"){ this.setState({ disabled:false }) } // const Level={"暂无":0,"C":25,"B":50,"A":75,"PRO":100,"暂无":0}; this.getData(); } formate(num){ // var today = new Date(); // if(num){ // today.setDate(today.getDate()+1); // } // //debugger // return Number(today.getMonth()+1)+"-"+today.getDate(); var today = new Date(); if(num){ today.setDate(today.getDate()+num); } let month = Number(today.getMonth()+1); let date = today.getDate(); return (month<10?("0"+month):month)+"-"+(date<10?("0"+date):date); } getData(){ var self = this; let {projectId} = this.props.routeParams; fetchPosts("/api/project/"+projectId,{},"GET").then((data)=>{ try{ let newData = this.formateData(data,this.state.data); newData.assetsType = newData.assetsType===1?"本土":""; newData.organizationType = newData.organizationType===1?"有限合伙制":""; newData.structured = newData.structured===1?"是":"否";// newData.direction = newData.direction===1?"股权":"";//direction newData.name = data.data.project.name; console.log("data",newData); self.setState({ data:newData }); }catch(errorMsg){ console.log(errorMsg); } }); // fetchPosts("/api/serverTime",{},"GET").then((data)=>{ // self.setState({ // now:new Date() // }) // }) } formateData(data,oldData){ let newState = {}; for(var key in data){ let temp = {}; if(isObject(data[key])&&!isArray(data[key])){ temp = this.formateData(data[key],oldData); }else if(oldData[key]!==undefined){ newState[key] = data[key]; } newState = Object.assign(newState,temp); } return newState; } handThink(){ if(this.state.disabled===true){ return false; } let {projectId} = this.props.routeParams; //this.props.router.push({pathname:"/orderconfirm/"+projectId,state:{minPrice:this.state.data.minPrice},query: { modal: true }}); this.context.router.push({pathname:"/orderconfirm/"+projectId,state:{minPrice:this.state.data.minPrice/10000,maxPrice:this.state.data.target/10000}}); //query: { modal: true },state: { fromDashboard: true } } handHeart(){ this.setState({ heart:!this.state.heart }); } render() { var {data,heart,startDate,endDate} = this.state; return ( <div className="party-info"> <div className="party-temp"> <div className="party-head" style={{backgroundImage:("url("+data.pics[0]+")")}}> <div className="party-logo" style={{backgroundImage:("url("+data.pics[1]+")")}} ></div> </div> <Area className="" title={data.name} hasIcon={false}> <ul className="party-plan"> <li><span>{data.direction}</span><span>投资方向</span></li> <li><span>{data.duration}</span><span>存续期限</span></li> <li><span>{data.minPrice/10000}万</span><span>认购起点</span></li> </ul> </Area> <Area className="area-margin area-bottom" title="项目解析" hasIcon={false}> <Vedio bgUrl={data.pics[2]} src={data.video}/> </Area> <Area className="area-margin" title="项目优势" hasIcon={true} hasLine={true} isClose={true}> <div className="area-p area-duan"> <img src={require("static/imgs/detail/detail-1.png")} alt=""/> </div> </Area> <Area className="area-margin" title="募集说明" hasIcon={false}> <div className="party-step"> <div className="step-row"> <span>申购</span> <span>确认份额</span> </div> <div className="step-row step-arrow"> </div> <div className="step-row"> <span>{startDate}</span> <span>{endDate}</span> <span>持有中</span> </div> <p>现在申购,<span className="date">{endDate.replace("-","月")+"日"}</span>确认份额后产生收益</p> </div> </Area> <Area className="area-margin" title="产品明细" hasIcon={true} hasLine={true}> <ul className="area-rows"> <li><span>目标规模</span><span></span><span>{data.target/10000+"万"}</span></li> <li><span>管理机构</span><span>{data.organization}</span></li> <li><span>投资方向</span><span>{data.direction}</span></li> <li><span>资本类型</span><span>{data.assetsType}</span></li> <li><span>组织形式</span><span>{data.organizationType}</span></li> <li><span>结构化</span><span>{data.structured}</span></li> <li><span>犹豫期</span><span>7天</span></li> <li><span>退出方式</span>{this.renderArrayInfo(data.exitWay)}</li> </ul> </Area> </div> <div className="step-end" > <button disabled={this.state.disabled} className="step-btn-end" onClick={this.handThink} >我有意向</button> </div> </div> ) } renderArrayInfo(param){ if(!param){ retunr (<div className="area-p"></div>) } let re = []; for(let i =0;i<param.length;i++){ re.push(<p key={i}>{param[i]}</p>) } return ( <div className="area-p"> {re} </div> ); } } /* <Chart projectId={this.props.routeParams.projectId}/> */ OrderInfo.defaultProps = { } OrderInfo.contextTypes = { router: React.PropTypes.object.isRequired }; export default OrderInfo; /** * <div className="step-end" > <button onClick={this.handHeart}><span className={"step-heart"+(heart===false?" heart-line":"")} ></span></button> <button disabled={this.state.disabled} className="step-btn-end" onClick={this.handThink} >我有意向</button> </div> * <Area className="area-margin" title="交易须知" hasIcon={true} hasLine={true}> <ul className="area-rows"> <li><span>认购费</span><span>{(data.applyFee&&data.applyFee[1]+"%")||""}</span></li> <li><span>管理费</span><span>{(data.managementFee[1]+"%/年")||""}</span></li> <li><span>托管费</span><span>{(data.trusteeFee[1]+"%/年")||""}</span></li> <li><span>收益分配</span> <div className="area-p"> {data.profit||""} </div> </li> </ul> </Area> */ //export default withRouter(OrderInfo); //<div className="theme-img"></div> <button><span className="step-download"></span></button><file_sep>import React, { Component, PropTypes } from 'react'; import "./page.less"; import { VelocityComponent, VelocityTransitionGroup } from "velocity-react"; import {withRouter} from "react-router"; class AnDemo extends Component { constructor(props) { super(props); this.state = { hovering: false, expanded:false } this.handClick = this.handClick.bind(this); this.handCheck = this.handCheck.bind(this); } handClick() { this.setState({ hovering: !this.state.hovering }); } componentDidMount() { //this.setState({ hovering: !this.state.hovering }); } handCheck(){ this.setState({ expanded: !this.state.expanded }); } render() { let {enterAnimation,leaveAnimation} = this.props; var animationProps; if (this.state.hovering) { animationProps = { duration: 200, animation: { rotateX: 160 } }; } else { animationProps = { duration: 1100, // longer due to swinging animation: { rotateX: [0, 'spring'] } }; } return ( <div className="an-demo" > <VelocityComponent {...animationProps} > <div onClick={this.handClick} className="an-demo-1">sdfsd</div> </VelocityComponent> <button onClick={this.handCheck} >切换状态</button> <VelocityTransitionGroup component="div" className="flex-1" enter={enterAnimation} leave={leaveAnimation}> {this.state.expanded ? this.renderLocations() : null} </VelocityTransitionGroup> </div> ) } renderLocations(){ return ( <div style={{height:"5rem",width:"5rem"}}>heh呵呵呵呵呵呵</div> ) } } AnDemo.defaultProps = { enterAnimation: { duration: 2000, animation: "slideDown" }, leaveAnimation:{ duration: 2000, animation:"slideUp" } } export default withRouter(AnDemo);<file_sep>/** * Created by xiaolin on 17/1/4. */ import React, { PropTypes } from 'react' import ReactDom from "react-dom"; import './index.less' class Dialog extends React.Component { constructor(props, context) { super(props, context); this._buttonConfirm = this._buttonConfirm.bind(this) } _buttonConfirm(){ // //var _name = ReactDom.findDOMNode(this.refs.nameInput); //var _phone = ReactDom.findDOMNode(this.refs.phoneInput); this.props.buttonConfirm(); } render() { if(!this.props.show)return(<div></div>) return ( <div className='sweet-mask'> <div className='sweet-alert showSweetAlert visible block' data-has-cancel-button='false' data-has-confirm-button='true' data-animation='pop'> <Header type={this.props.type}/> <div className='sa-button-container'> <button className='confirm' tabIndex='1' onClick={()=>this._buttonConfirm()}>好的</button> </div> </div> </div>) } } const Header = ({type}) => { return ( <div> { [type].map(function (name) { if (name == 'error') { return (<div className={type == 'success'?'sa-icon sa-'+type+' animate block':'sa-icon sa-'+type+' block'}> <span class="sa-x-mark" key={name}>
 <span className="sa-line sa-left"></span>
 <span className="sa-line sa-right"></span>
 </span></div>) } else if (name == 'info') { return (<div className={type == 'success'?'sa-icon sa-'+type+' animate block':'sa-icon sa-'+type+' block'}> <span className='sa-body' key={name}></span> <span className='sa-dot'></span> </div>) } else if (name == 'success') var domT = [] domT.push(<div className="sa-title">预约成功</div>) domT.push(<div className={type == 'success'?'sa-icon sa-'+type+' animate block':'sa-icon sa-'+type+' block'}> <div className='sa-icon sa-success animate block' key={name}> <span className='sa-line sa-tip animateSuccessTip'></span> <span className='sa-line sa-long animateSuccessLong'></span> <div className='sa-placeholder'></div> <div className='sa-fix'></div> </div></div>) domT.push(<p className="sa-fileds">我们将在10分钟内给您回电</p>) domT.push(<p style={{display: 'block'}} ></p>) return (domT) }) } </div>) } Dialog.defaultProps = { type: 'success', buttonConfirm: function () { }, errorShow: false, data: { name: '', phone: 0 } } export default Dialog<file_sep>//recharts import React, { Component, PropTypes } from 'react'; import ReactDom from "react-dom"; import random from "lodash/random"; import isEqual from "lodash/isEqual"; import { LineChart,XAxis,YAxis,CartesianGrid, Tooltip,Legend,Line} from "recharts"; class CharHour extends Component { constructor(props) { super(props); this.createData = this.createData.bind(this); this.state={ data:[], xTicks:["04","08","12","16","20"] } } componentWillMount(){ this.createData(this.props); } componentWillUpdate(nextProps,nextState){ if(!isEqual(nextProps,this.props)){ this.createData(nextProps); } } createData(props){ let data = [],xTicks=[]; // for(let i = 0,j = 5;i<j;i++){ // let newDate = this.formateYMD(i); //formateYMD .formateDate // data.push({pv:random(-1.9,3),uv:random(-1.9,3),data:newDate}); // xTicks.push(newDate); // } // let length = props.data.length; // for(let i=(length>5?5:(length-1)),j=0;i>=j;i--){ // if(!props.data[i]){ // continue; // } // data.push(props.data[i]); // xTicks.push(props.data[i].hour); // } //debugger this.setState({ data:props.data===false?[]:props.data, //xTicks:xTicks }) } //r日期增加一天 。并格式化为ymd formateYMD(num){ var today = new Date(); if(num){ today.setHours(today.getHours()+num); } let hour = Number(today.getHours()); let date = today.getDate(); return "00"+(date<10?("0"+date):date)+" "+(hour<10?("0"+hour):hour)+":00"; } render() { let {data,xTicks} = this.state; let {className,width,height} = this.props; return ( <div className={"chart-main "+className}> <LineChart width={width} height={height} data={data} > <XAxis padding={{left:10,right:10}} tickCount={3} dataKey="hour" tickFormatter={(data)=>{return data+":00"}} /> <YAxis axisLine={false} tickCount={5} /> <CartesianGrid strokeDasharray="3 3" /> <Line label={true} type="monotone" dataKey="fudongbaifenbi" stroke="#a88872" dot={false} /> </LineChart> </div> ) } } // <Line type="monotone" dataKey="other" stroke="#808291" dot={false}/> CharHour.defaultProps = { width:false, height:false, className:"", data:[] } //return data.substr(4)} export default CharHour; <file_sep>{ data: { project: { assetsId: 1, id: 1, name: "冰穹互娱股权转让计划一期", pics: "http://www.163.com/", projectAssets: { assetsType: 1, category: 1, exit: [ "这是第一条", "这是第二条" ], id: 1, logicId: "BQ_20170104", name: "冰穹互娱股权转让计划", organization: "钱旺", organizationId: 1, organizationType: 1, price: 1400, rating: "AAA", ratio: 10, structured: 1, target: 30000000 }, projectInfo: { applyFee: [ 1, 1 ], assetsRatio: [{ name: "股权增值", value: 100 }, { name: "市场盈利", value: 100 }, { name: "游戏分红", value: 50 }], des: "这是一篇说明", direction: 1, duration: "3+2+1年", feeType: 1, id: 4, managementFee: [ 1, 1 ], minPrice: 1000000, profit: "赚钱就分", projectId: 1, tag1: "+14.67%", tag2: "529款", tag3: "74个", trusteeFee: [ 1, 1 ], video: "http://www.baidu.com/" }, tag: "测试", watched: 2 } }, message: "", returnCode: 0, success: true }<file_sep>export function setCookie(name, value, mode="cookie") { if(mode == "cookie") { var Days = 30; var exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString(); return true; } else if(mode == "storage") { var _localStorage = window.localStorage; if (_localStorage) { _localStorage.setItem(name, value); return true; } return false; } } export function getCookie(name, mode="cookie") { if(mode == "cookie") { var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); if (arr = document.cookie.match(reg)) { return unescape(arr[2]); } else { return null; } } else if(mode == "storage") { var _localStorage = window.localStorage; if (_localStorage) { return _localStorage.getItem(name); } else return null; } } export function delCookie(name, mode="cookie") { if(mode == "cookie") { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval = getCookie(name); if (cval != null) { document.cookie = name + '=' + cval + ";expires=" + exp.toGMTString(); } } else if(mode == "storage") { var _localStorage = window.localStorage; if (_localStorage) { _localStorage.removeItem(name); } } } export function priceFormat(price, n) { n = n >= 0 && n <= 20 ? n : 2; let isMinus = price < 0 price = isMinus ? 0 - price : price price = parseFloat((price + "").replace(/[^\d\.-]/g, "")).toFixed(n) + ""; var l = price.split(".")[0].split("").reverse(), r = price.split(".")[1]; var t = ""; for (var i = 0; i < l.length; i++) { t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : ""); } if(n==0){ return (isMinus?'-':'') + t.split("").reverse().join(""); } else { return (isMinus?'-':'') + t.split("").reverse().join("") + "." + r; } } export function tagStrFormat(str, num) { return /(\d+)(\D+)/ig.exec(str)[num] } export function createCORSRequest(method, url){ let cors_api_host = 'finiyang.com:8080' let cors_api_url = 'http://' + cors_api_host + '/' let slice = [].slice let origin = window.location.protocol + '//' + window.location.host let open = XMLHttpRequest.prototype.open XMLHttpRequest.prototype.open = function() { let args = slice.call(arguments) let targetOrigin = /^https?:\/\/([^\/]+)/i.exec(args[1]) if (targetOrigin && targetOrigin[0].toLowerCase() !== origin && targetOrigin[1] !== cors_api_host) { args[1] = cors_api_url + args[1] } return open.apply(this, args) } let xhr = new XMLHttpRequest() if ("withCredentials" in xhr){ xhr.open(method, url, true) } else { xhr = null } return xhr } <file_sep>import React, { Component, PropTypes } from 'react'; import ReactDom from "react-dom"; import { VelocityComponent,VelocityTransitionGroup } from "velocity-react"; class GrideView extends Component { constructor(props) { super(props); } render() { let {} = this.props; return ( <div className={"area-info "}> </div> ) } } GrideView.defaultProps = { title:"" } export default GrideView; <file_sep>import React, { Component, PropTypes } from 'react'; import ReactDom from "react-dom"; import { VelocityComponent,VelocityTransitionGroup } from "velocity-react"; import "./banner.less"; class Banner extends Component { constructor(props) { super(props); } render() { let {} = this.props; return ( <div className="order-banner"> <div className="order-banner-items"> <div className="order-banner-item"> <a href="www.baidu.com"> <img src='http://ohhkwhqxa.qnssl.com/20161216/bbe637d2c5d036c0dff6ef59833710b5c0c5e62b.JPG?imageMogr2/interlace/1/thumbnail/450x300'/> </a> </div> <div className="order-banner-item"> <a href="www.baidu.com"> <img src='http://ohhkwhqxa.qnssl.com/20161216/0162d2e7741ce293c66da7f1dd2c7f45627c4f19.JPG?imageMogr2/interlace/1/thumbnail/450x300'/> </a> </div> <div className="order-banner-item"> <a href="www.baidu.com"> <img src='http://ohhkwhqxa.qnssl.com/20161216/650b1aaa3b1f8a5b7496d3af3ce9e51089733453.JPG?imageMogr2/interlace/1/thumbnail/450x300'/> </a> </div> </div> </div> ) } } class Item extends Component { constructor(props) { super(props); } render() { let {} = this.props; return ( <div className={"order-banner"}> <div className="order-banner-items"> <div className="order-banner-item"> </div> </div> </div> ) } } Banner.defaultProps = { title:"" } export default Banner; <file_sep>import React, { Component, PropTypes } from 'react'; import "./page.less"; import Ring from "./ring.js"; import RingVi from "./ringVi.js"; import {getCookie} from 'libs/util'; const Level={"暂无":0,"C":25,"B":50,"A":75,"PRO":100,"暂无":0}; class Theme extends Component { constructor(props) { super(props); this.state = { chooseNum:this.getImgIndex() }; this.handClick = this.handClick.bind(this); this.renderUls = this.renderUls.bind(this); this.saveClick = this.saveClick.bind(this); this.buildImage = this.buildImage.bind(this); } getImgIndex(){ return window.localStorage.theme?Number(window.localStorage.theme):0; } saveImgIndex(index){ //console.log("sdssdds",index) window.localStorage.theme = index; //保存图片 。this.urlImage } handClick(e){ var self = this; let target = e.target; if(target.tagName!=="LI"){ target = target.parentNode; } var lis = e.currentTarget.querySelectorAll("li"); for(var i = 0;i<lis.length;i++ ){ if(lis[i]===target){ break; } } //console.log("设置chooseNum",i) i<6&&self.setState({ chooseNum:i }); } //保存主题 saveClick(){ this.saveImgIndex(this.state.chooseNum); typeof QBaoJSBridge!= 'undefined' && QBaoJSBridge.saveImg(this.urlImage) } renderUls(){ let {data} = this.props,$lis=[],{chooseNum} = this.state; for(let i=0;i<data.length;i++){ $lis.push(<li key={i}><span>{data[i].title}</span><span className={chooseNum===i?"layer":"layer hide"}></span></li>); } return ( <ul className="" onClick={this.handClick} >{$lis}</ul> ); } componentDidMount(){ //console.error("父级加载") } buildImage(data){ this.urlImage = data; } render() { let levelName = getCookie("level","storage")||"无"; //debugger; let level = Level[levelName]; //level = 20; //debugger; return ( <div className='theme' style={this.props.style}> <div className="header"> <div className="header-layer"></div> <Ring showNum={this.state.chooseNum} levelName={levelName} level={level}/> <RingVi buildImage={this.buildImage} showNum={this.state.chooseNum} levelName={levelName} level={level}/> </div> <div className="content"> <div className="menu"> <h2>请选择您分享的主题</h2> <div className="menu-box"> {this.renderUls()} </div> </div> </div> <div className="footer" onClick={this.saveClick} style={{display:'flex'}}>保存主题</div> </div> ) } } Theme.defaultProps = { data:[{title:"守望者",url:"static/imgs/theme/sun-header0.jpg"},{title:"实力派",url:"static/imgs/theme/sun-header1.jpg"},{title:"潜行者",url:"static/imgs/theme/sun-header2.jpg"},{title:"勇敢者",url:"static/imgs/theme/sun-header3.jpg"},{title:"领路人",url:"static/imgs/theme/sun-header4.jpg"},{title:"梦想家",url:"static/imgs/theme/sun-header5.jpg"}] } export default Theme; //<Ring buildImage={this.buildImage} showNum={this.state.chooseNum} levelName={levelName} level={level}/> //<div className="theme-img"></div><file_sep>/** * Created by xiaolin on 17/2/9. */ // ------------------------------------ // Resource Import // ------------------------------------ require.ensure([], function(require) { require('react') require('react-redux') require('react-router') require('redux') require('redux-actions') require('redux-simple-router') require('dva') require('fastclick') require('recharts') require('./') } )<file_sep>/** * (NavBar组件) * * @export * @class NavBar * @extends {react} * @author sean on 16/12/29. */ import React, { PropTypes } from 'react' import './index.less' import {Router} from 'dva/router'; import {connect} from 'dva' import classNames from 'classnames' class NavBar extends React.Component { constructor (props, context) { super(props, context) this.state = { title: '', pathName: '' } } _filter (pathname, route) { let _result = route.childRoutes.filter(item => item.path.toLowerCase() == pathname.toLowerCase() || pathname.toLowerCase().match(item.path.toLowerCase().replace(':projectid', '\\\d+'))) return _result.length ? _result[0].name : route.indexRoute.name } _getTitle () { let { pathname } = this.props.location let { route } = this.props switch (route.path == pathname) { case true : this.state.title = route.name break default : this.state.title = this._filter(pathname, route) break } this.state.pathName = pathname } componentDidMount(){ var self = this QBFK.Business.clientGoBack = () => self._handleClick() QBFK.Business.go = (url) => self.context.router.push(url) } _handleClick () { this.state.pathName != '/' && this.context.router.goBack() this.state.pathName == '/' && typeof QBaoJSBridge != 'undefined' && QBaoJSBridge.QBIIClose() } render () { this._getTitle() return ( <div className="qbii-navbar-container"> <div className='qbii-navbar qbii-navbar-light'> <div className='qbii-navbar-left' onClick={() => this._handleClick()}> <span className='left'></span> <span className='left-icon'></span> </div> <div className='qbii-navbar-title'>{this.state.title}</div> <div className='qbii-navbar-right'> <span className={classNames({'right-icon':1,'hide':!this.props.helpShow})} onClick={()=>QBFK.Business.go('/Help')}></span> <span className='right hide'></span> </div> </div> </div> ) } } function mapStateToProps(state) { return state.home; } function mapDispatchToProps(dispatch) { return { } } NavBar.contextTypes = { router: React.PropTypes.object.isRequired }; // NavBar.defaultProps = { // helpShow: false // } export default connect(mapStateToProps, mapDispatchToProps)(NavBar) <file_sep>import React, { Component, PropTypes } from 'react'; import { VelocityComponent } from "velocity-react"; import ReactDom from "react-dom"; import isArray from "lodash/isArray"; let isFirstLoad = false; class Ring extends Component { constructor(props) { super(props); this.draw = this.draw.bind(this); this.state = { images:false, src:"" } } componentWillMount(){ var self = this; } componentWillUpdate(nextProps,nextState){ var self =this; if(nextState.images&&isArray(nextState.images)&&(nextProps.showNum!==this.props.showNum)||this.state.images == false){ console.error("--------------"); let img = new Image(); //debugger img.src = nextState.images[nextProps.showNum]; self.setState({ src:nextState.images[nextProps.showNum] }) // img.addEventListener("load",function(){ // //debugger; // self.draw(70,nextState.images[nextProps.showNum],nextProps.levelName); // }) //window.onload = function(){ //} } setTimeout(function(){ self.draw(nextProps.level,nextState.images[nextProps.showNum],nextProps.levelName); },500) } componentDidMount(){ var self = this; console.error("-------777777777777-------"); require.ensure([],function(a,b,c,d){ let arr = []; for(let i=0;i<6;i++){ arr.push(require("static/imgs/theme/sun-header"+i+".jpg")) } console.error("-----111---"); self.setState({ images:arr }) }); // var self = this; // setTimeout(function(){ // self.draw(70,"static/imgs/theme/sun-header0.jpg","Pro"); // },1000) } getAngle(value) { var min=2.72,max=6.65; return (max - min) / 100 * value + min; } draw(displayValue,url,level){ var self = this; var angle = 0.14, innerAngle = angle; var displayAngle = this.getAngle(displayValue), innerDisplayAngle = displayAngle; var radius = 60, innerRadius = radius - 8, iconRadius = radius - 16; var startX, startY, x, y, length = 88; var img = document.createElement("img"); img.src = url; console.error(url); img.crossOrigin = "anonymous"; img.addEventListener("load",function(){ //let ring = document.getElementById("ring"); //var canvas = document.getElementById("canvas"); var canvas = ReactDom.findDOMNode(self.refs.canvas); let width = canvas.offsetWidth; let height = canvas.offsetHeight; let wi = img.width,hi = img.height; let per = (height)/hi; canvas.width = wi*per; canvas.height = canvas.offsetHeight; var w = canvas.width/2; var h = 100; //debugger; canvas.style.width = wi*per+"px"; //canvas.style.marginLeft = -wi*per/2+"px"; //margin-left var ctx = canvas.getContext("2d"); // ctx.drawImage(img,0,0, wi*per, hi*per); // ctx.restore(); ctx.strokeStyle = "rgba(255, 255, 255, 0.3)"; ctx.beginPath(); ctx.arc(w, h, radius, (1 - angle) * Math.PI, (2 + angle) * Math.PI, false); ctx.lineWidth = 1; ctx.lineCap = "round"; ctx.stroke(); ctx.beginPath(); ctx.arc(w, h, innerRadius, (1 - angle) * Math.PI, (2 + angle) * Math.PI, false); ctx.setLineDash([1,4]) ctx.stroke(); ctx.strokeStyle = "rgb(255, 255, 255)"; ctx.beginPath(); ctx.setLineDash([0]); ctx.arc(w, h, radius, (1 - angle) * Math.PI, displayAngle, false); ctx.stroke(); ctx.beginPath(); ctx.setLineDash([1,3]); ctx.arc(w, h, innerRadius, (1 - innerAngle) * Math.PI, innerDisplayAngle, false); ctx.stroke(); ctx.font="12px Helvetica"; ctx.textAlign = "center"; ctx.fillStyle = "white"; ctx.fillText("QBII",116,70); ctx.fillText("认证等级",116,84); ctx.font="40px Helvetica"; ctx.fillText(level,116,126); // var strDataURI = canvas.toDataURL("image/jpeg"); // self.props.buildImage(strDataURI); // this.setState({ // dataUrl:strDataURI // }) //console.log(strDataURI) },false); } render() { let {levelName} = this.props; let {src} = this.state; return ( <div className="ring-bg" style={{backgroundImage:"url("+src+")"}}> <canvas id="canvas" ref="canvas" className="ring"></canvas> </div> ) } } Ring.defaultProps = { level: 0, showNum:false, levelName:"Pro", totalLevel:5, buildImage:()=>{} } export default Ring; <file_sep>import React, { Component, PropTypes } from 'react'; import ReactDom from "react-dom"; import { VelocityComponent,VelocityTransitionGroup } from "velocity-react"; import Area from "./area.js"; class TextView extends Component { constructor(props) { super(props); } render() { let {title,items} = this.props; return ( <div className="area-p area-duan"> {items&&items[0].data} </div> ) } } TextView.defaultProps = { title:"", item:[], } export default TextView;<file_sep>'use strict' import 'whatwg-fetch' // 可以引入fetch来进行Ajax import size from "lodash/size"; import each from "lodash/each"; import assignIn from "lodash/assignIn"; export const DATA_SAVE = 'DATA_SAVE'; export const FETCH_REQUEST = 'FETCH_REQUEST'; export const FETCH_SUCCESS = 'FETCH_SUCCESS'; export const FETCH_POSTS = 'FETCH_POST'; export const FETCH_CLEAN = 'FETCH_CLEAN'; export const COOKIE_GET = 'COOKIE_GET'; export const ERROR_SAVE = 'ERROR_SAVE'; export const ERROR_CLEAR = 'ERROR_CLEAR'; export function errorSave(key,data){ return { type:ERROR_SAVE, key, data } } export function errorClear(key,data){ return { type:ERROR_CLEAR, key, data } } export function save(key,data){ return { type:DATA_SAVE, key, data } } //获取 cookie export function cookieGet(){ return{ type:"COOKIE_GET" } } /* 请求 开始 */ export function fetchRequest(key) { return { type: FETCH_REQUEST, key } } /*请求接受成功*/ export function fetchSuccess(key, json) { return { type: FETCH_SUCCESS, key, result:json, receivedAt: Date.now() } } export function fetchClean(key) { return { type: FETCH_CLEAN, key } } //body: type.toLocaleUpperCase()==="GET"?"":JSON.stringify(param) /*对外公布请求参数*/ export function fetchPosts(key, url, param, type = "POST",headers={},repType="json") { return (dispatch,getState) => { if(type.toLocaleUpperCase()==="GET"&&size(param)>0){ url +="?"+toExcString(param) } headers = assignIn({},{ 'Accept': 'application/json', 'Content-Type': 'application/json', "Access-Control-Allow-Methods":"PUT,POST,GET,DELETE,OPTIONS" }); //console.log("------------- end ------------------",headers); dispatch(fetchRequest(key)); return fetch(url, { method: type.toLocaleUpperCase(), headers: headers, //credentials: 'same-origin', body: type.toLocaleUpperCase()==="GET"?undefined:(repType=="json"?JSON.stringify(param):param) }) .then((res) => { //console.log(res.status); return res.json(); }) .then((data) => { console.log('收到data', data); dispatch(fetchSuccess(key, data)); if(data&&(data.code===0||data.resultCode==="0"||data.resultCode===0||data.code==="0")){ dispatch(errorClear("common,login")); }else{ console.info("你的请求 内部出错了",data); dispatch(errorSave("common",data)); if(data&&(data.code==="200"||data.code===200||data.resultCode=="200"||data.resultCode==200)){ dispatch(errorSave("login",data)); } } return data; }) /* .catch((e) => { //console.error(e.message); console.info("你的请求报错了,详情=>",e); dispatch(errorSave("common",e)); return e; })*/ } } var toExcString = function(array,type={":":"=",",":"&"}){ let result =""; for(var temp in array){ result+= temp+'='+array[temp]+"&" } return result.substring(-1,result.length-1); }<file_sep> import React, { Component, PropTypes } from 'react'; class Info extends Component { constructor(props) { super(props); } componentWillMount(){ } render() { return ( <p> 农业领域:<br/> 1.科技惠农,高效安全<br/> “雨田一号”具有作业高度低,飘移少,可空中悬停,无需专用起降机场,可远距离遥控操作,提高了喷洒作业安全性等诸多优点。<br/> <br/> 2.节约农药及用水量,降低成本<br/> 无人直升机喷洒技术采用水雾喷洒的方式,至少可以节约20%以上的农药使用量,同比人工操作节水90%,极大的降低了使用成本。<br/> <br/> 3.覆盖密度高,防治效果好<br/> 喷雾药液在单位面积上覆盖密度越高、越均匀,防治效果就越好。在药液雾滴飘移试验反映了用无人机喷洒作业对农药飘失程度的一个优势,作业高度比较低,当药液雾滴从喷洒器喷出时被旋翼的向下气流加速形成气雾流,直接增加了药液雾滴对农作物的穿透性,减少了农药飘失程度,并且药液沉积量和药液覆盖率都优于常规,因而防治效果比传统的好,还可以防止农药对土壤造成污染。 <br/><br/> 工业领域:<br/> 1.航拍航测<br/> 利用携带摄像机装置的无人机,开展大规模航拍,实现空中俯瞰的效果。通过专业级的航拍来为某一领域提供资料,在未来工程测量领域得到广泛应用。<br/> <br/> 2.电力巡检<br/> 我国电网规模已跃居世界首位,国土幅员辽阔,地形相对复杂,气象条件的复杂多变。传统的人工巡检方式存在效率低下、难以管控、危险性高和受制于天气等问题。而通过无人机巡线,不仅可以对输电线路本体缺陷、通道隐患进行快速检测,还能在各种复杂地形、恶劣气候、灾害天气下,及时、准确、高效地获取现场信息,因此可代替人工去完成一些危险的任务。更重要的是,无人机巡线提高了电力维护检修的速度和效率,使许多工作能在完全带电的情况下迅速完成,比人工巡线效率高出40倍。 <br/><br/> 3.消防应用<br/> 一直以来,火灾都是给人类生命财产安全带来巨大危害的灾难之一。一方面,无人机系统可以高效地完成巡护任务,及时发现火情隐患,为防火工作提供便利。另一方面,当火灾发生时,无人机可搭载红外和可见光摄像机监测火灾,经数控遥测电路实时传输到地面控制站,将火点、热点显示在地面站的数字地图上,经过识别系统确定是否是火点,并进行精确的火点定位,为地面消防部门第一时间提供火场地理坐标(经、纬度)。当无人机在火场上方飞行时,还可将火场的轮廓、面积、蔓延速度等数据实时传回地面控制中心,为地面扑火指挥提供可靠信息,使灭火指挥部门迅速有效地组织、布署灭火队伍,提高灭火作战效率,防止救火人员的伤亡。 <br/><br/> 4.环保应用<br/> 无人机因为不受空间与地形限制,效性强,机动性好,巡查范围广等优点,执法部门能够轻易的利用它来找到污染源头和测试污染程度。并且能利用携带了催化剂和气象探测设的无人机在空中进行喷撒,与无人机播撒农药的工作原理一样,在一定区域内消除雾霾。 <br/><br/> 消费娱乐:<br/> 1.VR游戏 <br /> 通过搭载高清摄像头及VR眼镜,能多角度拍摄俯瞰画面,达到身临其境的飞行体验。 <br/> </p> ) } } /* <Chart projectId={this.props.routeParams.projectId}/> */ Info.defaultProps = { type:1 } export default Info; //export default withRouter(OrderInfo); //<div className="theme-img"></div> <button><span className="step-download"></span></button><file_sep>//recharts import React, { Component, PropTypes } from 'react'; import ReactDom from "react-dom"; import random from "lodash/random"; import isEqual from "lodash/isEqual"; import { LineChart,XAxis,YAxis,CartesianGrid, Tooltip,Legend,Line} from "recharts"; class ChartDay extends Component { constructor(props) { super(props); this.createData = this.createData.bind(this); this.state={ data:[], xTicks:[] } } componentWillMount(){ // this.createData(); } componentWillUpdate(nextProps,nextState){ if(!isEqual(nextProps,this.props)){ this.createData(nextProps); } } createData(props){ // let data = []; // for(let i = 0,j = random(30,365);i<j;i++){ // let newDate = this.formateYMD(i); //formateYMD .formateDate // data.push({self:random(-1.9,3),other:random(-1.9,3),date:newDate}); // } let {xTicks,showTick} = this.jisuanDate(props.space); let data = []; for(let i=0,j=props.data.length;i<j;i++){ let temp = props.data[i]; if(temp.date>=xTicks[0]&&temp.date<=xTicks[2]){ data.push(temp); console.log(temp.date); } } this.setState({ data, xTicks:showTick }) } //r日期增加一天 。并格式化为ymd formateYMD(num){ var today = new Date(); if(num){ today.setDate(today.getDate()+num); } let month = Number(today.getMonth()+1); let date = today.getDate(); return today.getFullYear()+"-"+(month<10?("0"+month):month)+"-"+(date<10?("0"+date):date); } //日期增加一天 formateDate(num){ var today = new Date(); if(num){ today.setDate(today.getDate()+num); } return Number(today.getMonth()+1)+"-"+today.getDate(); } //格式化日期为 MD formateMD(data){ console.log("aha . niangzi ",data); //debugger; if(data===""){ return false; } return Number(data.getMonth()+1)+"-"+data.getDate(); } //YMD转换为 Date对象 toDateYMD(ymd,space="-"){ let dataArray = ymd.split(space); let date = new Date(); date.setMonth(dataArray[0]); date.setDate(dataArray[1]); //console.log("时间为:",date); //debugger; return date; } //计算日期的 月间隔 jisuanDate(space=1){ let now = new Date(); //now.setMonth(now.getMonth()+3); space = Number(space); let xTicks = [],showTick=[]; // re.push(this.jisuanMonth(now,-space)); // re.push(this.jisuanMonth(now)); // re.push(this.jisuanMonth(now,space)); if(space==100){ //debugger return { xTicks:["1970-01-01","1970-01-02",this.jisuanMonth(now)], showTick:[] } } xTicks.push(this.jisuanMonth(now,-space*3)); xTicks.push(this.jisuanMonth(now,-space)); xTicks.push(this.jisuanMonth(now)); let num = parseInt(30*3*space/4); showTick.push(this.jisuanMonth(now,-space*3,num)); showTick.push(this.jisuanMonth(now,-space*3,num*2)); showTick.push(this.jisuanMonth(now,-space*3,num*3)); console.log("num",num) console.log("jisuan",xTicks); console.log("jisuan",showTick); return { xTicks, showTick }; } jisuanXdate(){ } //月份相加 jisuanMonth(date,num=0,dayNum=false){ let newDate = new Date(date) ; //debugger; newDate.setMonth(Number(newDate.getMonth())+num); if(dayNum!==false){ //debugger; newDate.setDate(Number(newDate.getDate())+dayNum) } let month = Number(newDate.getMonth())+1; //newDate.setDate(Number(newDate.getDate())-10) let day = newDate.getDate(); console.log("jisuan",num,month,day); return newDate.getFullYear()+"-"+(month<10?("0"+month):month)+"-"+(day<10?("0"+day):day); //return date; } render() { let {data,xTicks} = this.state; let {className,width,height} = this.props; //console.log("时间为 。",this.formateMD(xTicks[0])); //ticks={xTicks} tickFormatter={this.formateMD} margin={{ top: 5, right: -10, left: 5, bottom: 5 }} return ( <div className={"chart-main "+className}> <LineChart width={width} height={height} data={data} > <XAxis dataKey="date" ticks={xTicks} tickFormatter={(data)=>{return data.substr(5)}} /> <YAxis axisLine={false} tickCount={3} /> <CartesianGrid strokeDasharray="3 3" /> <Line labeel={true} type="monotone" dataKey="self" stroke="#a88872" dot={false} /> <Line type="monotone" dataKey="other" stroke="#808291" dot={false}/> </LineChart> </div> ) } } ChartDay.defaultProps = { width:false, height:false, className:"", space:1 } export default ChartDay; <file_sep>import React, { Component }from 'react' import './page.less' import { Link } from 'react-router' // import { createCORSRequest } from 'libs/util' class NewsDetail extends Component { constructor(props, context) { const urls = { 1: "", 2: "", 3: "" } super(props, context) this.state = { content: '' } // let _this = this // let request = createCORSRequest("get", this.state.url); // if (request){ // request.onload = function(e) { // if(this.status == 200||this.status == 304){ // let content = this.responseText.replace(/data-src/g, "src") // content = 'data:text/html;charset=utf-8,' + content // _this.setState({ // content // }) // } // } // request.onreadystatechange = () => {} // request.onerror = () => {} // request.send() // } } componentWillMount() { let { projectId } = this.props.routeParams require.ensure([], () => { let newsContents = require('static/article/news.js').newsContents let content = 'data:text/html;charset=utf-8,' + newsContents[projectId].replace(/data-src/g, "src") this.setState({ content }) }) } render() { return ( <div className="frame-wrap" style={{position: 'absolute',top: 0,left: 0,width: '100%',height:'100%'}}> <iframe src={this.state.content} frameBorder="0" ></iframe> </div> ) } } export default NewsDetail <file_sep>import React, { Component, PropTypes } from 'react'; import ReactDom from "react-dom"; import { VelocityComponent,VelocityTransitionGroup } from "velocity-react"; import "./grideView.less"; class GrideView extends Component { constructor(props) { super(props); } render() { let {items} = this.props; let i=0,length = items.length,$lis=[]; while(i<length){ let item = items[i]; i+=1; $lis.push(<li key={i}><span>{item.title}</span><span>{item.data}</span></li>) } return ( <ul className="party-plan"> {$lis} </ul> ) } } GrideView.defaultProps = { title:"", items:[] } export default GrideView; <file_sep>/** * Created by xiaolin on 16/12/26. */ // ------------------------------------ // Android 4.4 Version Below // ------------------------------------ require('es6-promise').polyfill(); var a = 123456; // ------------------------------------ // Resource Import // ------------------------------------ require.ensure([], function(require) { var dva = require('dva').default var FastClick = require('fastclick') var router = require('./routes') var business = require('./model/business') var model = require('./model') // ------------------------------------ // App Starting // ------------------------------------ const html5ForStartApp = dva() function html5ForLogin(_app) { if (_app) { _app.model(business) _app.model(model) _app.router(router) _app.start('.page-container') } else { html5ForStartApp.model(business) html5ForStartApp.model(model) html5ForStartApp.router(router) html5ForStartApp.start('.page-container') } } // ------------------------------------ // Debug Here // ------------------------------------ html5ForLogin(html5ForStartApp); var b = 123456; // ------------------------------------ // Client Login // ------------------------------------ // if(navigator.userAgent.match(/Android/i)) { // if (typeof QBaoJSBridge != 'undefined') { // QBaoJSBridge.login("mqbii.qbao.com", String(html5ForLogin(html5ForStartApp))); // } // } // else if(navigator.userAgent.match(/iPhone|iPad|iPod/i)) { // if (typeof ioswebview != 'undefined') { // ioswebview.showLoginViewAnd("mqbii.qbao.com", String(html5ForLogin(html5ForStartApp))); // } // } // else { // html5ForLogin(html5ForStartApp); // } // ------------------------------------ // Fast Click Adding For System // ------------------------------------ if ('addEventListener' in document) { document.addEventListener('DOMContentLoaded', function () { FastClick.attach(document.body); }, false); } } )<file_sep>import React from 'react' import './page.less' import { Link } from 'react-router' import { Dialog } from 'ui' class AppS extends React.Component { constructor(props, context) { super(props, context) this.state = { errorShow: true, show: false, data: { name: 'xiaolin', phone: 13391257557 } } } operate() { if (this.state.show) { this.setState({ show:false }); } else if (!this.state.show) { this.setState({ show:true }); } } render() { return (<div className='HomeDo'> <button onClick={()=>this.operate()}>弹窗</button> <Dialog buttonConfirm={()=>this.operate()} show={this.state.show} data={this.state.data}></Dialog> </div>) } } export default AppS <file_sep>import React, { Component, PropTypes } from 'react'; import ReactDom from "react-dom"; import { VelocityComponent,VelocityTransitionGroup } from "velocity-react"; import {withRouter} from "react-router"; import classNames from 'classnames' import CSSModules from 'react-css-modules' import {fetchPosts} from "components/common/fetch"; import styles from './page.less' class News extends Component { constructor(props) { super(props); this.state={ lists:[] } } componentWillMount(){ let self = this; ///qbii-app/ fetchPosts("/api/news/getNewsList",{},"POST").then((data)=>{ // console.log('返回结果为:',data); // debugger; if(data.code==0){ self.setState({ lists:data.result.newsList }) } }) } toDetail(id){ QBFK.Business.go('/NewsDetail/'+id) } render() { let {lists} = this.state; let length = lists.length; let items = [],i=0; //onClick={()=>QBFK.Business.go('/NewsDetail/'+{item.id})} while (i<length) { let item = lists[i]; i += 1; // console.log(item) items.push( <div styleName="item" key={i} onClick={this.toDetail.bind(this,item.id)}> <div styleName="img"> <img src={item.image} alt=""/> </div> <div styleName="item-title"> <p>{item.title}</p> <small>{item.des}</small> </div> </div> ); // statement } return ( <div className=""> {items} </div> ) } } News.defaultProps = { title:"" } export default withRouter(CSSModules(News,styles,{allowMultiple:true})); <file_sep>import React, { Component, PropTypes } from 'react'; import ReactDom from "react-dom"; import {fetchPosts} from "components/common/fetch"; import CharInfo from "./chartInfo"; import ChartHour from "./chartHour"; import ChartDay from "./chartDay"; import random from "lodash/random"; class Chart extends Component { constructor(props) { super(props); this.state={ showFirst:props.showFirst, firstCss:"chart-select", secondCss:"", trend:"", dataFirst:[], dataSecond:[], xTicksSecond:[], showSpace:"threeMonth", style:{ width:false, height:false }, rose:0,//较昨日涨跌幅 roseSecond:0, roseJing:0,//估算净值 roseAbout:0,//估算收益 } this.handClick = this.handClick.bind(this); this.handClickSecond = this.handClickSecond.bind(this); this.setStyle = this.setStyle.bind(this); this.handChangeSpace = this.handChangeSpace.bind(this); this.getFirst = this.getFirst.bind(this); this.getSecond = this.getSecond.bind(this); this.creatFDate = this.creatFDate.bind(this); this.creatHDate = this.creatHDate.bind(this); } componentWillMount(){ this.setStyle(); } componentDidMount(){ var self = this; self.getFirst(); self.getSecond(); // setTimeout(function(){ // //self.creatFDate(); // //self.creatHDate(); // },1500); } creatFDate(data = []){ //let data = []; // for(let i = 0,j = 400;i<=j;i++){ // let newDate = this.formateYMD(i-400); //formateYMD .formateDate // data.push({self:random(-1.9,3),other:random(-1.9,3),date:newDate}); // } let nowDate = this.formateYMD(-1); let yesterday = this.formateYMD(-2); let nowData,yesterdayData; for(let i=0,j=data.length;i<j;i++){ let temp = data[i]; if(nowDate===temp.date){ nowData = Number(temp.self); }else if(yesterday===temp.date){ yesterdayData = Number(temp.self); } } //debugger let rose = "没有前后两天的数据"; if(nowData&&yesterdayData){ rose = (nowData-yesterdayData).toFixed(2); } this.setState({ dataFirst:data, rose:(rose||"暂无") }) } creatHDate(data=[],rose){ // let xTicks=[]; // data = []; // for(let i = 0,j = 16;i<j;i++){ // let newDate = i<10?(0+""+i):i; //formateYMD .formateDate // data.push({shishijingzhi:random(-1.9,3).toFixed(2),shishishouyi:random(-1.9,3).toFixed(2),hour:newDate,fudongbaifenbi:Number(random(-1.9,3).toFixed(2))}); // //xTicks.push(newDate);Number // } // debugger; this.setState({ //xTicksSecond:xTicks, dataSecond:data, roseSecond:rose, roseJing:data[data.length-1].shishijingzhi, roseAbout:data[data.length-1].shishishouyi, }) } //r日期增加一天 。并格式化为ymd formateYMD(num){ var today = new Date(); if(num){ today.setDate(today.getDate()+num); } let month = Number(today.getMonth()+1); let date = today.getDate(); return today.getFullYear()+"-"+(month<10?("0"+month):month)+"-"+(date<10?("0"+date):date); } getFirst(){ var self = this; // debugger let {projectId} = this.props; self.setState({dataFirst:false}); fetchPosts("/api/project/"+projectId+"/profitability",{},"GET").then((data)=>{ try{ self.creatHDate(data.data.value,data.data.zuorizhangfu); }catch(errorMsg){ } self.creatFDate(data.data); // self.setState({ // dataFirst:data // }); }) } getSecond(){ var self = this; let {projectId} = this.props; self.setState({dataSecond:false}); fetchPosts("/api/project/"+projectId+"/evaluate",{},"GET").then((data)=>{ try{ self.creatHDate(data.data.value,data.data.zuorizhangfu); }catch(errorMsg){ } // self.setState({ // dataSecond:data // }); }) } handClick(){ if(this.state.showFirst===false){ this.setState({ firstCss:"chart-select", secondCss:"", showFirst:true }) } } handClickSecond(){ if(this.state.showFirst===true){ this.setState({ firstCss:"", secondCss:"chart-select", showFirst:false }) } } setStyle(){ let width = window.innerWidth; let height = width*(4/5); this.setState({ style:{ width, height } }) } handChangeSpace(e){ console.log("1111",e.target.dataset.space); this.setState({ space:e.target.dataset.space, showSpace:e.target.dataset.key }) } render() { let {firstCss,secondCss,showFirst,dataFirst,dataSecond,xTicksSecond,style,space,showSpace,rose,roseSecond,roseJing,roseAbout} = this.state; return ( <div className="party-chart "> <div className="chart-top"> <span onClick={this.handClick} className={firstCss} >盈利走势</span> <span onClick={this.handClickSecond} className={secondCss} > 实时估值</span></div> <div className="chart-info"> <div className="part-chart-top"> <span className="chart-low-line"></span> <span className="chart-title">{showFirst?"较昨日涨跌幅":"较昨日涨跌幅"}</span> <span className={"chart-num"+(rose>=0?" chart-rose":"")}>{showFirst?rose:roseSecond}%</span> <span className="chart-low-line"></span> </div> <div className="chart-main"> <ChartDay space={space} width={style.width} height={style.height} className={showFirst?"":"hide"} data={dataFirst}/> <ChartHour width={style.width} height={style.height} className={showFirst?"hide":""} data={dataSecond} /> </div> <div className={showFirst?"hide":"part-chart-bottom"}> <div className="bottom-title"> <span className="chart-title ">估算净值:</span> <span className={"chart-num"+(rose>=0?" chart-rose":"")}>{roseJing}</span> <span className="chart-title ">估算收益:</span> <span className={"chart-num"+(rose>=0?" chart-rose":"")}>{roseAbout}%</span> </div> <p className="chart-remark"> <i>i</i>估算值仅供参考,实际涨幅以最新净值为准 </p> </div> <div className={showFirst?"part-chart-bottom":"hide"} > <div className="bottom-title"> <span className="chart-low-line select"></span> <span className="chart-title select-ex">本产品</span> <span className="chart-low-line "></span> <span className="chart-title ">同类目</span> </div> <div className="chart-todo" onClick={this.handChangeSpace}> <span data-space={1} data-key={"threeMonth"} className={showSpace==="threeMonth"?"select":""}>3月</span> <span data-space={2} data-key={"sixMonth"} className={showSpace==="sixMonth"?"select":""}>6月</span> <span data-space={4} data-key={"year"} className={showSpace==="year"?"select":""}>1年</span> <span data-space={100} data-key={"now"} className={showSpace==="now"?"select":""}>至今</span> </div> </div> </div> </div> ) } } Chart.defaultProps = { showFirst:true } export default Chart; <file_sep>/** * Created by xiaolin on 16/12/15. */ import fs from 'fs' import config from './_basic' const debug = require('debug')('app:config') debug('create configuration.') debug(`apply enviroment overrides for NODE_ENV "${config.env}"`) //check env config exit const ovFileName = `/env/_${config.env}` let hasFile,override try { fs.lstatSync(__dirname + ovFileName + `.js`) hasFile = true } catch (e){} console.log('ovFileName',ovFileName) //replace the the server link from config if exit if(hasFile) { override = require(`.` + ovFileName)(config) } else debug(`No configuration overrides found for NODE_ENV "${config.env}"`) export default Object.assign({},config,override)<file_sep>import {fetchPosts} from "components/common/fetch" import { setCookie } from 'libs/util' export default { namespace: 'home', state: { loading: false, levelInfo: { "level" : "" }, userInfo: { "level": "", "assetsDes": 0, "profitDes": 0 }, projList: [], progressInfo: {}, serverTime: '', helpShow: false, isAgreementShow: false }, effects: { // *'fetch' (action, {put, call}) { // yield put({type: 'request', loading: true}) // // let count = yield call((count) => { // return new Promise(resolve => { // setTimeout(() => { // resolve(count + 1) // }, 1000) // }) // }, action.count) // // yield put({ // type: 'response', // loading: false, // count // }) // }, // *getUserId (action, {put, call}) { // yield put({type: 'levelReq', loading: true}) // yield call(() => { // return fetchPosts("/api/user/userId",{},"GET") // .then(data => data.result) // .then(data => { // let levelInfo = call(() => { // return fetchPosts("/api/user/level",{},"GET") // .then(data => data.result) // .catch(err => ({ // "userId" : 111111, // "level" : "暂无" // })) // }, action.levelInfo) // let userInfo = call(() => { // return fetchPosts("/api/user/userInfo",{},"GET") // .then(data => data.result.user) // .catch(err => ({ // "id": 111111, // "level": "暂无", // "assets": 0, // "profit": 0 // })) // }, action.userInfo) // let projList = call(() => { // return fetchPosts("/api/project/1",{},"GET") // .then(data => data.result.project) // .catch(err => ({ // "assetsId": 1, // "id": 1, // "name": "--", // "pics": "", // "tag": "--", // "watched": 0, // "projectAssets": {}, // "projectInfo": { // "assetsRatio": [ // { // "name": "--", // "value": 1 // }, // { // "name": "--", // "value": 1 // }, // { // "name": "--", // "value": 1 // } // ], // "id": 2, // "projectId": 1, // "tag1": "+0%", // "tag2": "0款", // "tag3": "0个", // }, // })) // }, action.projList) // let progressInfo = call(() => { // return fetchPosts("/api/project/1/progress",{},"GET") // .then(data => data.result) // .catch(err => ({ // "amount": 0, // "target": 0, // "user_count": 0 // })) // }, action.progressInfo) // }) // .catch(err => { // console.log(err); // }) // }) // yield call(() => { // setCookie("level",levelInfo.level,"storage"); // }) // yield put({ // type: 'levelRes', // loading: false, // levelInfo, // userInfo, // projList, // progressInfo // }) // }, *getLevel (action, {put, call}) { yield put({type: 'levelReq', loading: true}) let levelInfo = yield call(() => { return fetchPosts("/api/user/level",{},"GET") .then(data => data.result) .catch(err => ({ "userId" : 111111, "level" : "暂无" })) }, action.levelInfo) yield call(() => { setCookie("level",levelInfo.level,"storage"); }) yield put({ type: 'levelRes', loading: false, levelInfo }) }, *getUserInfo (action, {put, call}) { yield put({type: 'userInfoReq', loading: true}) let userInfo = yield call(() => { return fetchPosts("/api/user/userInfo",{},"GET") .then(data => data.result.user ? data.result.user : { "level": "暂无", "assetsDes": 0, "profitDes": 0 }) .catch(err => ({ "id": 111111, "level": "暂无", "assetsDes": 0, "profitDes": 0 })) }, action.userInfo) yield put({ type: 'userInfoRes', loading: false, userInfo }) }, *getProjList (action, {put, call}) { yield put({type: 'projListReq', loading: true}) let serverTime, helpShow let projList = yield call(() => { return fetchPosts("/api/project/list",{},"GET") .then(data => { serverTime = data.serverTime helpShow = data.result.projects.length>0 return data.result.projects }) .catch(err => ({ "assetsId": 1, "id": 1, "name": "--", "pics": [""], "tag": "--", "watched": 0, "projectAssets": {}, "projectInfo": { "assetsRatio": [ { "name": "--", "value": 1 }, { "name": "--", "value": 1 }, { "name": "--", "value": 1 } ], "id": 2, "projectId": 1, "tag1": "+0%", "tag2": "0款", "tag3": "0个", }, })) }, action.projList) yield put({ type: 'projListRes', loading: false, projList, serverTime, helpShow }) }, *getProgressInfo (action, {put, call}) { yield put({type: 'progressInfoReq', loading: true}) let id = action.progressInfo, progressInfo = {} progressInfo[id] = yield call(() => { return fetchPosts("/api/project/"+id+"/progress",{},"GET") .then(data => data.result) .catch(err => ({ "amount": 0, "target": 0, "user_count": 0 })) }, action.progressInfo) yield put({ type: 'progressInfoRes', loading: false, progressInfo }) }, *setHelpStatus(action,{put}) { yield put({type: 'helpShowReq'}) yield put({ type : 'helpShowRes', helpShow:true }) }, *setAgreement(action,{put}) { yield put({type: 'helpShowReq'}) yield put({ type : 'helpShowRes', isAgreementShow:action.isShow }) } }, reducers: { helpShowReq (state, payload) { return {...state, ...payload} }, helpShowRes (state, payload) { return {...state, ...payload} }, levelReq (state, payload) { return {...state, ...payload} }, levelRes (state, payload) { return {...state, ...payload} }, userInfoReq (state, payload) { return {...state, ...payload} }, userInfoRes (state, payload) { return {...state, ...payload} }, projListReq (state, payload) { return {...state, ...payload} }, projListRes (state, payload) { return {...state, ...payload} }, progressInfoReq (state, payload) { return {...state, ...payload} }, progressInfoRes (state, payload) { payload.progressInfo = Object.assign(state.progressInfo, payload.progressInfo) return {...state, ...payload} } } } <file_sep>import {FETCH_REQUEST,FETCH_SUCCESS,FETCH_POST,COOKIE_GET,FETCH_CLEAN,DATA_SAVE,ERROR_SAVE,ERROR_CLEAR} from "./helpAction"; import assignIn from "lodash/assignIn"; import each from "lodash/each"; export function posts(state = {isFetching:false} , action) { switch (action.type) { case FETCH_REQUEST: //console.info("公共的 isFetching",action.key) return assignIn({}, state, { isFetching: true }); case FETCH_SUCCESS: return assignIn({}, state, { isFetching: false, result: action.result, lastUpdated: action.receivedAt }) default: return state } } export function fetch(state = {}, action) { switch (action.type) { case FETCH_CLEAN: var newState = assignIn({}, state); if(action.key){ delete newState[action.key]; } return newState; case FETCH_REQUEST: case FETCH_SUCCESS: return assignIn({}, state, { [action.key]: posts(state[action.key], action) }) default: return state } } export function cookie(state={"X_FREEY_SERVICE":""},action){ switch(action.type){ case COOKIE_GET: var strcookie = document.cookie;//获取cookie字符串 let cookie={}; var arr = strcookie.split(";"); //分割cookie for(var i = 0;i<arr.length;i++){ if(arr.indexOf("=")<0){ continue; } var arrStr = arr.split("="); //对各个cookie进行分割 cookie[arrStr[0]]=arrStr[1]; } console.log("获取所有 cooki",cookie); return assignIn({},state,cookie); default: return state } } export function save(state = {}, action) { //console.log("啊哈 ",action) switch (action.type) { case DATA_SAVE: //console.log("啊哈 ",action) var newState = assignIn({}, state); newState[action.key] = action.data; return newState; default: return state } } export function errorMsg(state = {}, action) { //console.log("啊哈 ",action) switch (action.type) { case ERROR_SAVE: //console.log("啊哈 ",action); var newState = assignIn({}, state); newState[action.key] = action.data; return newState; case ERROR_CLEAR: //console.log("啊哈 ",action) var newState = assignIn({}, state); if(action.key){ let keys = action.key.split(","); each(keys,function(one,index){ newState[one] = action.data; }); }else{ newState = {}; } return newState; default: return state } }<file_sep>import React,{ Component } from 'react' import CSSModules from 'react-css-modules' import styles from './page.less' import Swipe from "components/swipe/swipe"; class About extends Component { constructor(props) { super(props) this.state = { activeIndex : 0 } } slideUpHandler = () => { this.setState({ activeIndex:++this.state.activeIndex }) } slideChangeHandler = (index,next) => { this.setState({ activeIndex:index }) } render() { const slide = { // height: '25%', position: 'relative' } let isQBC = QBFK.Business.isQBClient() let top = isQBC ? 44 : 0 let itemHeight = window.innerHeight-top let swipeProps = { min: -itemHeight*3, max: 0, step: itemHeight, property: "translateY", findScroller: ".slide-item", vertical:true, sensitivity:0.5 } return ( <Swipe styleName="about-container" {...swipeProps} style={{position: 'absolute',left: 0,width: '100%'}}> <div style={slide} className="slide-item"> <div styleName="about-title"></div> <div styleName="about-content"> <p>QBII(Qualified Qbao Institutional Investors) <br/>合格的钱宝投资者</p> <p>QBII的权益:<br/>以投资人的身份参与钱宝主营业务;参与孵化业务获得被孵化公司利润分红和参股股权增值收益;进入钱宝投资人核心社交圈;具备所有业务标的运营权和决策投票权。</p> <p>成为QBII后的收入将额外获得很大一部分的投资收益,除了拿到投资标的额外的分红收益,更将有机会成为PE,与钱宝一起投资已有利润和未来有大量利润从而获得高估值的企业。</p> </div> <div styleName="bottom-wrap"> <span styleName="page">1/4</span> <i styleName="arrow" className="extend" onClick={this.slideUpHandler}></i> </div> </div> <div style={slide} className="slide-item"> <div styleName="about-title"></div> <div styleName="about-content"> <p>QBII背景:<br/>基于钱旺信控强大的资本现金流,依托钱宝网1.6亿注册用户的巨大流量,以“互联网+”武装思维,深度发掘覆盖各个领域的新兴业务,通过生态圈内互联网的融合,迅速孵化出同时具备商业和社会价值的投资标的。</p> <p>创新为王,实业兴国,固本安邦;“痛于民生之窘也,则曰讲求实业”;没有实业,就没有钱旺。</p> </div> <div styleName="bottom-wrap"> <span styleName="page">2/4</span> <i styleName="arrow" className="extend" onClick={this.slideUpHandler}></i> </div> </div> <div style={slide} className="slide-item"> <div styleName="about-title"></div> <div styleName="about-content"> <p>QBII主要标准:</p> <div styleName="level-info"> <p> <span>级别</span> <span>活跃值</span> </p> <p> <span>QBII-PRO</span> <span>80万</span> </p> <p> <span>QBII-A</span> <span>29万</span> </p> <p> <span>QBII-B</span> <span>15万</span> </p> <p> <span>QBII-C</span> <span>8万</span> </p> <p> <span>暂无</span> <span>低于8万</span> </p> </div> <p>QBII必备要素:<br/>有投资能力并具有契约精神、有坚定的信仰、有健全的人格、有完整科学的知识体系和对这个知识体系学习和知识更新能力或者是有意愿成为这样的投资人的钱宝用户。</p> </div> <div styleName="bottom-wrap"> <span styleName="page">3/4</span> <i styleName="arrow" className="extend" onClick={this.slideUpHandler}></i> </div> </div> <div style={slide} className="slide-item"> <div styleName="about-title"></div> <div styleName="about-content"> <p>孵化对象:<br/>1.钱旺信息产业控股集团旗下所有被孵化公司<br/>(如上海商肃网络科技有限公司、上海定菱网络科技有限公司、上海雷悦文化发展有限公司、上海酷雅智能科技有限公司、四川雷神空天科技有限公司、上海友繁智能科技有限公司等等)。</p> <p>2.具备实干能力和创新精神的创业者、企业和企业家。</p> </div> <div styleName="bottom-wrap"> <span styleName="page">4/4</span> </div> </div> </Swipe> ) } } export default CSSModules(About,styles,{allowMultiple:true}) <file_sep>import React,{ Component } from 'react' import { connect } from 'dva' import CSSModules from 'react-css-modules' import styles from './page.less' import classNames from 'classnames' import { PieChart, Pie, Cell } from 'recharts' import { tagStrFormat } from 'libs/util' class ProjectItem extends Component { projectStatus = [ '进行中', '已下架', '未开始', '已结束' ] //进行中,1-已下架,2-项目未开始,3-项目已结束 constructor(props) { super(props) this.state = { } } togglePieShowHandler = () => { this.setState({ }); } render() { return ( <div styleName="item" onClick={()=>QBFK.Business.go('/InfoTpl/'+this.props.projInfo.pageId||"")}> <div styleName="banner"> <span styleName="corner"><i>{this.projectStatus[this.props.projInfo.runStatus]}</i></span> <img src={this.props.projInfo.picCover} alt="" onError={(e)=>{e.target.style.display='none'}} onLoad={(e)=>{e.target.style.display='block'}}/> </div> <div styleName="title"> {this.props.projInfo.name} <small> <i styleName="icon icon-item"></i> <span>{this.props.projInfo.tag}</span> </small> <span styleName="user-tag"></span> </div> </div> ) } checkProjStatus(proj) { let serverTime = (new Date(this.props.serverTime)).getTime() let startTime = (new Date(proj.prostarttime)).getTime() let endTime = (new Date(proj.proendtime)).getTime() return serverTime < startTime ? 0 : serverTime > startTime && serverTime < endTime ? 1 : serverTime > endTime ? 2 : 1 } } function mapStateToProps(state) { return state.home; } function mapDispatchToProps(dispatch) { return { getProgressInfo(progressInfo){ dispatch({type: 'home/getProgressInfo', progressInfo}); } } } export default connect(mapStateToProps, mapDispatchToProps)(CSSModules(ProjectItem,styles,{allowMultiple:true})); <file_sep> import React, { Component, PropTypes } from 'react'; import { connect } from 'dva'; import {withRouter} from "react-router"; import isObject from "lodash/isObject"; import isArray from "lodash/isArray"; //var moment = require('moment'); import {fetchPosts} from "components/common/fetch"; import {getCookie} from 'libs/util'; import Info from "./info.js"; import Banner from "./banner.js"; import GrideView from "./grideView.js"; import ListView from "./listView.js"; import TextView from "./textView.js"; import "./page.less"; import Vedio from "./vedio"; import Area from "./area.js"; //import Chart from "./chart.js"; class OrderInfo extends Component { constructor(props) { super(props); this.state={ heart:false, data:{ name:"", duration:"",//存续期限 direction:"",//投资方向 1股权 minPrice:"",//认购起点 des:"",//特色亮点, target:"",//目标规模 organization:"",//管理机构 // direction //投资方向 assetsType:"",// type//资本类型 1-本土 organizationType:"",//组织形式 1-有限合伙制 structured:"",//结构化 . 1-是,2-否 exitWay:["",""],//退出形式 trusteeFee:["",""],//认购费 . managementFee:["",""],//管理费 trusteeFee:["",""],//托管费 profit:"",//收益分配 pics:["","",""], video:"", applyFee:["",""] }, startDate:this.formate(), endDate:this.formate(2), disabled:false, now:false } this.getData = this.getData.bind(this); this.handThink = this.handThink.bind(this); this.handHeart = this.handHeart.bind(this); } componentWillMount(){ let levelName = getCookie("level","storage")||"暂无"; //debugger if(levelName!=="暂无"){ this.setState({ disabled:false }) } // const Level={"暂无":0,"C":25,"B":50,"A":75,"PRO":100,"暂无":0}; this.getData(); } formate(num){ // var today = new Date(); // if(num){ // today.setDate(today.getDate()+1); // } // //debugger // return Number(today.getMonth()+1)+"-"+today.getDate(); var today = new Date(); if(num){ today.setDate(today.getDate()+num); } let month = Number(today.getMonth()+1); let date = today.getDate(); return (month<10?("0"+month):month)+"-"+(date<10?("0"+date):date); } getData(){ var self = this; let {projectId} = this.props.routeParams; fetchPosts("/api/page/"+projectId,{},"GET").then((data)=>{ self.setState({ data:data.result.page }); }); } formateData(data,oldData){ let newState = {}; for(var key in data){ let temp = {}; if(isObject(data[key])&&!isArray(data[key])){ temp = this.formateData(data[key],oldData); }else if(oldData[key]!==undefined){ newState[key] = data[key]; } newState = Object.assign(newState,temp); } return newState; } handThink(){ if(this.state.disabled===true){ return false; } let {projectId} = this.props.routeParams; //this.props.router.push({pathname:"/orderconfirm/"+projectId,state:{minPrice:this.state.data.minPrice},query: { modal: true }}); this.context.router.push({pathname:"/orderconfirm/"+projectId,state:{minPrice:this.state.data.minPrice/10000,maxPrice:this.state.data.target/10000}}); //query: { modal: true },state: { fromDashboard: true } } handHeart(){ this.setState({ heart:!this.state.heart }); } typeShow(type,items,i){ switch(type){ case "banner":{ return (<Banner key={i} className="party-head" items={items} />); } case "grideView":{ return (<GrideView key={i} items={items}/>); } // case "tap":{ // return (<GrideView items={items}/>); // } case "textView":{ return (<TextView key={i} items={items}/>); } case "listView":{ return (<ListView key={i} items={items}/>); } default:{ //return (JSON.stringify(type)); return undefined } } } render() { var {data,heart,startDate,endDate} = this.state; let modules = data.modules||[]; let i = 0,length = modules.length,$lis=[],self = this; while(i<length){ let modular = modules[i]; i+=1; console.info(modular); if(!modular||!modular.items){ continue; } let {items,category,title} = modular; if(title&&title.text){ //debugger let hadIcon = "textView,listView".indexOf(category)>=0?true:false; let className = "grideView".indexOf(category)>=0?"":"area-margin "; $lis.push( <Area key={i} className={className} title={title.text} hasIcon={hadIcon} hasLine={hadIcon} > {self.typeShow(category,items,i)} </Area> ) }else{ $lis.push(self.typeShow(category,items,i)); } } return ( <div className="party-info"> <div className="party-temp"> {$lis} </div> {/*<div className="step-end" > <button disabled={this.state.disabled} className="step-btn-end" onClick={this.handThink} >我有意向</button> </div>*/} </div> ) } renderArrayInfo(param){ if(!param){ retunr (<div className="area-p"></div>) } let re = []; for(let i =0;i<param.length;i++){ re.push(<p key={i}>{param[i]}</p>) } return ( <div className="area-p"> {re} </div> ); } } OrderInfo.defaultProps = { } OrderInfo.contextTypes = { router: React.PropTypes.object.isRequired }; export default OrderInfo; {/*<Banner className="party-head"/> <Area className="" title={"系双方的时间开放"} hasIcon={false}> <GrideView items={tempGrideViewData}/> </Area> <Area className="area-margin area-bottom" title="项目解析" hasIcon={false}> <Vedio bgUrl={data.pics[2]} src={data.video}/> </Area> <Area className="area-margin" title={"特色亮点"} hasIcon={true} hasLine={true} isClose={true}> <TextView content={"ddsskdskdkdksdiiiiiiiiiiiiiiiiiiiiiiiikks"} /> </Area> <Area className="area-margin" title="募集说明" hasIcon={false}> <div className="party-step"> <div className="step-row"> <span>申购</span> <span>确认份额</span> </div> <div className="step-row step-arrow"> </div> <div className="step-row"> <span>{startDate}</span> <span>{endDate}</span> <span>持有中</span> </div> <p>现在申购,<span className="date">{endDate.replace("-","月")+"日"}</span>确认份额后产生收益</p> </div> </Area> <ListView title="产品明细" items={tempListViewData}/>*/} <file_sep>import React, { Component, PropTypes } from 'react'; import ReactDom from "react-dom"; class Video extends Component { constructor(props) { super(props); this.state={ play:false } this.handPlay = this.handPlay.bind(this); this.handPause = this.handPause.bind(this); } handPlay(){ var domVedio = ReactDom.findDOMNode(this.refs.vedio); domVedio.play(); this.setState({ play:!this.state.play }) } handPause(){ var domVedio = ReactDom.findDOMNode(this.refs.vedio); if(this.state.play===true){ domVedio.pause(); this.setState({ play:!this.state.play }) } } render() { let markCss = this.state.play?"vedio-mark-hide":"vedio-mark"; let {src,bgUrl} = this.props; return ( <div className="party-video"> <div className={markCss} onClick={this.handPause} style={{backgroundImage:("url("+bgUrl+")")}}> <div onClick={this.handPlay} className="vedio-mark-play"> <span></span> </div> </div> {(()=>{ if(src!==""){ <video ref="vedio" className="" src={src}></video> } })()} </div> ) } } Video.defaultProps = { src:"", bgUrl:"" } export default Video;
cc00376ac20469350c53ebd8d0acd1419b1aade2
[ "Markdown", "JavaScript" ]
44
Markdown
daxiangaikafei/QBIndex
78dc22554466436ffbe8a32030b261232a30ebac
05bf5dad56998be4e1ab5f5acf81b6f148a2af99
refs/heads/master
<file_sep> #include "PureEratosthenesSieve.h" #include <cstdlib> // calloc #include <cstring> // memset // after repeated testing, this number seems likely to get me the hightest value; i.e., walking doesn't take too long unsigned PureEratosthenesSieve::PRIME_DIGITS = 1325000000; PureEratosthenesSieve::PureEratosthenesSieve() : PrimeSieve(FIRST_PRIME) { m_allNumbers = (unsigned*)calloc(PRIME_DIGITS, sizeof(unsigned)); // leave the zero, one, and two indices initialized to 0; // set everything else to 1 memset(m_allNumbers + 3, 1, sizeof(unsigned) * PRIME_DIGITS); } PureEratosthenesSieve::~PureEratosthenesSieve() { if(m_allNumbers) { free(m_allNumbers); m_allNumbers = NULL; } } void PureEratosthenesSieve::Calculate() { // all multiples of our current prime number are not prime numbers for(auto incr = m_currentPrime; incr < PRIME_DIGITS; incr += m_currentPrime) { m_allNumbers[incr] = 0; } // walk our current prime forward, past all the multiples of other primes, // until we find a new one auto nextPrime = m_currentPrime; while(nextPrime < PRIME_DIGITS && m_allNumbers[nextPrime] == 0) { ++nextPrime; } // only grab the next prime number if we didn't walk all the way to the end if(nextPrime != PRIME_DIGITS) { m_currentPrime = nextPrime; } m_allNumbers[m_currentPrime] = 0; } <file_sep> #include "NaiveSieve.h" NaiveSieve::NaiveSieve() : PrimeSieve(FIRST_PRIME), m_testNumber(FIRST_PRIME) { } NaiveSieve::~NaiveSieve() { } void NaiveSieve::Calculate() { ++m_testNumber; if(IsPrime(m_testNumber)) m_currentPrime = m_testNumber; } bool NaiveSieve::IsPrime(int number) { for(int i = number - 1; i > 1; --i) { if(number % i == 0) return false; } return true; } <file_sep> #include "PseudoEratosthenesSieve.h" #include <cstdlib> // calloc #include <cstring> // memset int PseudoEratosthenesSieve::PRIME_DIGITS = 100000000; PseudoEratosthenesSieve::PseudoEratosthenesSieve() : PrimeSieve(FIRST_PRIME) { m_allNumbers = (int*)calloc(PRIME_DIGITS, sizeof(int)); // leave the zero, one, and two indices initialized to 0; // set everything else to 1 memset(m_allNumbers + 3, 1, sizeof(int) * PRIME_DIGITS); m_previousPrimes = (int*)calloc(PRIME_DIGITS, sizeof(int)); m_previousPrimesLastIndex = (int*)calloc(PRIME_DIGITS, sizeof(int)); m_previousPrimes[0] = m_currentPrime; m_previousPrimesLastIndex[0] = m_currentPrime; } PseudoEratosthenesSieve::~PseudoEratosthenesSieve() { if(m_allNumbers) { free(m_allNumbers); m_allNumbers = NULL; } if(m_previousPrimes) { free(m_previousPrimes); m_previousPrimes = NULL; } if(m_previousPrimesLastIndex) { free(m_previousPrimesLastIndex); m_previousPrimesLastIndex = NULL; } } void PseudoEratosthenesSieve::Calculate() { int i = 0; // for every known prime ... do { auto prime = m_previousPrimes[i]; // ... calculate at least x multiples of it, where x is our current prime; // this is a little arbitrary, but will keep us from accidentally walking into a non-prime for(int start = 0; start < m_currentPrime; ++start) { auto primeIndex = m_previousPrimesLastIndex[i] + prime; if(primeIndex > PRIME_DIGITS) break; m_allNumbers[primeIndex] = 0; m_previousPrimesLastIndex[i] = primeIndex; } ++i; } while(m_previousPrimes[i] != 0 && i < PRIME_DIGITS); // walk our current prime forward, past all the multiples of other primes, // until we find a new one auto nextPrime = m_currentPrime; while(nextPrime < PRIME_DIGITS && m_allNumbers[nextPrime] == 0) ++nextPrime; // only grab the next prime number if we didn't walk all the way to the end if(nextPrime != PRIME_DIGITS) m_currentPrime = nextPrime; m_allNumbers[m_currentPrime] = 0; m_previousPrimes[i] = m_currentPrime; m_previousPrimesLastIndex[i] = m_currentPrime; } <file_sep> #ifndef PRIMETHREAD_H #define PRIMETHREAD_H #include "PrimeSieve.h" #include <thread> class PrimeThread { public: PrimeThread(); void Start(PrimeSieve* const primeSieve); void Stop(); bool const IsGoing() const; private: PrimeSieve* m_primeSieve; std::thread m_thread; bool m_go; }; #endif <file_sep> #ifndef NAIVESIEVE_H #define NAIVESIEVE_H #include "PrimeSieve.h" class NaiveSieve : public PrimeSieve { public: NaiveSieve(); virtual ~NaiveSieve(); virtual void Calculate(); private: int m_testNumber; bool IsPrime(int number); }; #endif <file_sep> #ifndef PSEUDOERATOSTHENESSIEVE_H #define PSEUDOERATOSTHENESSIEVE_H #include "PrimeSieve.h" class PseudoEratosthenesSieve : public PrimeSieve { public: PseudoEratosthenesSieve(); virtual ~PseudoEratosthenesSieve(); virtual void Calculate(); private: static int PRIME_DIGITS; int* m_allNumbers; int* m_previousPrimes; int* m_previousPrimesLastIndex; }; #endif <file_sep> #include "PrimeThread.h" #include "NaiveSieve.h" #include "PseudoEratosthenesSieve.h" #include "PureEratosthenesSieve.h" #include <iostream> // std::cout, std::cin #include <iomanip> // std::fixed, std::setprecision #include <ctime> // std::clock #include <Windows.h> // SetConsoleCursorPosition, etc. // the NaiveSieve and PseudoEratosthenesSieve are just for the sake of comparison; they are SIGNIFICANTLY slower than the PureEratosthenesSieve //#define PRIME_SIEVE NaiveSieve //#define PRIME_SIEVE PseudoEratosthenesSieve #define PRIME_SIEVE PureEratosthenesSieve #define CurrentTimeXY 0, 0 #define CurrentPrimeXY 0, 2 void SetCursorXY(int x, int y) { COORD xy = {x, y}; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), xy); } int main() { std::cout << std::fixed << std::setprecision(3); auto start = std::clock(); auto current = start; const double maximumDuration = 60; double duration = 0; int m_lastPrime = 0; PRIME_SIEVE sieve; PrimeThread thread; thread.Start(&sieve); do { SetCursorXY(CurrentTimeXY); std::cout << "Current execution duration: " << duration; int currentPrime = sieve.GetCurrentPrime(); if(m_lastPrime != currentPrime) { m_lastPrime = currentPrime; SetCursorXY(CurrentPrimeXY); std::cout << "Highest calculated prime: " << m_lastPrime; } current = std::clock(); } while((duration = ((double)(current - start) / (double)CLOCKS_PER_SEC)) < maximumDuration); // wherever we were when we ran out of time, grab that prime m_lastPrime = sieve.GetCurrentPrime(); SetCursorXY(CurrentTimeXY); std::cout << "Current execution duration: " << maximumDuration; SetCursorXY(CurrentPrimeXY); std::cout << "Maximum calculated prime in sixty seconds: " << m_lastPrime << std::endl; // we displayed our conclusion before stopping the calculation thread, just in case it takes a little // while to close down the thread (it won't, but still) thread.Stop(); std::cout << "Press any key to quit ..."; std::cin.get(); } <file_sep> #ifndef PUREERATOSTHENESSIEVE_H #define PUREERATOSTHENESSIEVE_H #include "PrimeSieve.h" class PureEratosthenesSieve : public PrimeSieve { public: PureEratosthenesSieve(); virtual ~PureEratosthenesSieve(); virtual void Calculate(); private: static unsigned PRIME_DIGITS; unsigned* m_allNumbers; }; #endif <file_sep> #include "PrimeSieve.h" int PrimeSieve::FIRST_PRIME = 2; PrimeSieve::PrimeSieve(int currentPrime) : m_currentPrime(currentPrime) { } PrimeSieve::~PrimeSieve() { } int const PrimeSieve::GetCurrentPrime() const { return m_currentPrime; } <file_sep> #include "PrimeThread.h" void Calculate(PrimeSieve* const sieve, PrimeThread* const thread) { while(thread->IsGoing()) { sieve->Calculate(); } } PrimeThread::PrimeThread() : m_primeSieve(0), m_go(false) { } void PrimeThread::Start(PrimeSieve* const sieve) { m_go = true; m_primeSieve = sieve; m_thread = std::thread(Calculate, m_primeSieve, this); } void PrimeThread::Stop() { m_go = false; m_thread.join(); } bool const PrimeThread::IsGoing() const { return m_go; }<file_sep> #ifndef PRIMESIEVE_H #define PRIMESIEVE_H class PrimeSieve { public: PrimeSieve(int currentPrime); virtual ~PrimeSieve(); virtual void Calculate() = 0; virtual int const GetCurrentPrime() const; protected: static int FIRST_PRIME; int m_currentPrime; }; #endif
fe5050f839dcbd50fffa586c4e26ce36b1398335
[ "C++" ]
11
C++
ianellerromey/NewRelic_PrimeNumber
49bbb003be48e7514a9ab743f1ee993aacbbfa03
68e8778900cd15dd86d5d9b01a27b0fc4c50c4ae
refs/heads/master
<repo_name>mikeAvdeev12/assessment-2b-wolves<file_sep>/routes/index.js const express = require('express'); const bcrypt = require('bcrypt'); const { sessionChecker } = require('../middleware/auth'); const saltRounds = 10; const routes = express.Router(); const User = require('../models/user'); const Party = require('../models/party'); routes .route('/') .get(async (req, res) => { const partyShow = await Party.find(); res.render('index', { title: 'Сrazy new Year partY ', event: 'neW partY', partyShow }); }); routes .route('/signup') .get(sessionChecker, (req, res) => { res.render('signup'); }) .post(async (req, res) => { // console.log(req.body); const { username, password, email } = req.body; const oldUser = await User.findOne({ $or: [{ username }, { email }] }); if (oldUser) { res.json({ status: false }); } else { const user = new User({ username, password: await bcrypt.hash(password, saltRounds), email, }); await user.save(); req.session.user = user; res.json({ status: true }); } }); routes .route('/signin') .get(sessionChecker, (req, res) => { res.render('signin'); }) .post(async (req, res) => { // console.log(req.body); const { email, password } = req.body; const newUser = await User.findOne({ email }); // console.log(newUser); if (newUser && (await bcrypt.compare(password, newUser.password))) { req.session.user = newUser; res.json({ status: true }); } else res.json({ status: false }); }); routes .route('/events') .get((req, res) => { res.render('party'); }) .post(async (req, res, next) => { // console.log(req.body); const name = req.body.name; const location = req.body.location; const starts = req.body.starts; const host = req.session.user.username // console.log(req.body); const party = new Party({ name, location, starts, host }); console.log(party); try { await party.save(); return res.redirect(`/events/${party.id}`); } catch (err) { return res.render('party', { errors: [err] }); } }); routes .route('/events/:id') .get(async (req, res) => { const partyShow = await Party.findById(req.params.id) res.render('details', { partyShow }); }) .delete( async (req, res, next) => { await Party.deleteOne({ _id: req.params.id }); res.json({res: true}); }); routes .route("/update/:id") .get(async (req, res) => { // const user = req.session.user; const party = await Party.findById(req.params.id); res.render("edit", { party }); }) .post(async (req, res) => { const party = await Party.findById(req.params.id); const { name, location, starts } = req.body; party.name = name; party.location = location; party.starts = starts; await party.save(); res.redirect("/"); }); routes .route('/logout') .get(async (req, res, next) => { if (req.session.user && req.cookies.user_sid) { try { await req.session.destroy(); res.clearCookie('user_sid'); res.redirect('/'); } catch (error) { next(error); } } else { res.redirect('/login'); } }); module.exports = routes;<file_sep>/public/js/applicationlogin.js document.forms[0].addEventListener('submit', async (event) => { event.preventDefault(); event.stopPropagation(); const email = document.getElementsByName('emaillog')[0].value; const password = document.getElementsByName('passwordlog')[0].value; const response = await fetch('/signin', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email, password, }), }); const result = await response.json(); if (result.status) { window.location = '/';} else { document.getElementsByName('status-text')[0].innerText = 'Введен неверный username или e-mail'; } }); <file_sep>/models/party.js const mongoose = require('mongoose'); const { Schema, model } = mongoose; const Partyschema = new Schema({ name: String, location: String, starts: Date, host: String, }); module.exports = model('party', Partyschema); <file_sep>/public/js/application.js document.forms[0].addEventListener('submit', async (event) => { event.preventDefault(); event.stopPropagation(); const username = document.getElementsByName('username')[0].value; const password = document.getElementsByName('password')[0].value; const email = document.getElementsByName('email')[0].value; const response = await fetch('/signup', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username, password, email, }), }); const result = await response.json(); if (result.status) { window.location = '/';} else { document.getElementsByName('status-text')[0].innerText = 'Введен неверный username или e-mail'; } }); <file_sep>/public/js/delete.js const entries = document.getElementsByClassName('entry'); for (let i = 0; i < entries.length; i++) { const entry = entries[i]; let del = entry.getElementsByClassName('delete')[0]; del.addEventListener('click', async (event) => { event.preventDefault(); event.stopPropagation(); let id = event.target.id; const response = await fetch(`events/${event.target.id}`, { method: 'delete', headers: { "Content-Type": 'aplication/json', }, body: JSON.stringify({ id: id }) }); const result = await response.json(); console.log(result); entry.remove() }); }; // document.body.addEventListener("click", async e => { // if (e.target.id === "test") { // e.preventDefault(); // const id = e.target.parentNode.parentNode.id; // const resp = await fetch(`/delete/${id}`, { // method: "DELETE" // }); // const data = await resp.json(); // const elem = document.getElementById(data._id); // elem.remove(); // } // });
95098c937adca71b122eeb6054501c203fe9e59f
[ "JavaScript" ]
5
JavaScript
mikeAvdeev12/assessment-2b-wolves
10cc86cec60a6416583fc0612264faedaf480444
7b4c544d61aafaa298c81fd656b8db0320d2b997
refs/heads/master
<repo_name>ImaginariaLS/ls_shistory<file_sep>/templates/language/russian.php <?php return array( 'title' => 'История сессий', 'date' => 'Дата авторизации', 'ip' => 'IP адрес', 'os' => 'ОС', 'agent' => 'Браузер' );<file_sep>/classes/actions/ActionSessions.class.php <?php class PluginSHistory_ActionSessions extends ActionSettings { protected $sMenuSubItemSelect = 'sessions'; public function Init() { /** * Проверяем авторизован ли юзер */ if (!$this->User_IsAuthorization()) { $this->Message_AddErrorSingle($this->Lang_Get('not_access'), $this->Lang_Get('error')); return Router::Action('error'); } $this->oUserCurrent = $this->User_GetUserCurrent(); $this->Viewer_Assign('sTemplateWebPathPlugin', Plugin::GetTemplateWebPath(__CLASS__)); $this->SetDefaultEvent('index'); } function EventIndex() { $this->Viewer_AddHtmlTitle('История сессий'); $userBrowser = $this->PluginSHistory_Sessions_getUserBrowser(); $userOs = $this->PluginSHistory_Sessions_getUserOs(); $gTest = ''; $this->Viewer_Assign('gTest', $gTest); $this->Viewer_Assign('aHistoryRows', $this->PluginSHistory_Sessions_getSessionsRows($this->oUserCurrent->getId())); } protected function RegisterEvent() { $this->AddEvent('index', 'EventIndex'); } } <file_sep>/delete.sql DROP TABLE `prefix_shistory`;<file_sep>/README.md # История сессий (авторизаций пользователя) # Автор lstr1ke <file_sep>/install.sql CREATE TABLE IF NOT EXISTS `prefix_shistory` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `enter_date` date NOT NULL, `enter_time` time NOT NULL, `session_key` varchar(32) NOT NULL, `user_ip` varchar(255) NOT NULL, `user_os` varchar(255) NOT NULL, `user_agent` varchar(255) NOT NULL, PRIMARY KEY (`id`), KEY `user_id` (`user_id`, `session_key`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8 AUTO_INCREMENT = 1; <file_sep>/PluginShistory.class.php <?php if (!class_exists('Plugin')) { die(__FILE__ . ' : Hacking attemp!'); } class PluginSHistory extends Plugin { protected $aInherits = array( 'module' => array('Sessions') ); public function Init() { if ($this->User_IsAuthorization()) { $this->oUserCurrent = $this->User_GetUserCurrent(); $this->PluginSHistory_Sessions_update($this->oUserCurrent); } return true; } public function Activate() { $this->ExportSQL(dirname(__FILE__) . '/install.sql'); return true; } public function Deactivate() { $this->ExportSQL(dirname(__FILE__) . '/delete.sql'); return true; } } <file_sep>/classes/modules/sessions/mapper/Sessions.mapper.class.php <?php class PluginSHistory_ModuleSessions_MapperSessions extends Mapper { function isCurrent($user_id, $session_key) { $table = Config::Get('db.table.shistory'); $sql = "SELECT `id` FROM {$table} WHERE `user_id` = ? AND `session_key` = ? "; if ($aRow = $this->oDb->selectRow($sql, $user_id, $session_key)) { return true; } return false; } function addCurrent($user_id, $session_key, $date, $time, $os, $browser, $ip) { $table_shistory = Config::Get('db.table.shistory'); /* $sql = "SELECT COUNT( * ) as cnt FROM {$table} WHERE `user_id` = ?"; if ($sCnt = $this->oDb->selectRow($sql, $user_id)) { if ($sCnt['cnt'] >= Config::Get('shistoryLimit')) { $this->oDb->query("DELETE FROM {$table} WHERE `user_id` = ? ORDER BY id LIMIT 1", $user_id); } } */ // применена оптимизация https://stackoverflow.com/a/578884/5127037 $sql = " DELETE i1.* FROM {$table_shistory} i1 LEFT JOIN ( SELECT id FROM {$table_shistory} ii ORDER BY id DESC LIMIT ?d ) i2 ON i1.id = i2.id WHERE i2.id IS NULL AND `user_id` = ?d "; $this->oDb->query($sql, Config::Get('shistoryLimit'), $user_id); $sql = " INSERT INTO `{$table_shistory}` ( `user_id`, `enter_date`, `enter_time`, `session_key`, `user_ip`, `user_os`, `user_agent` ) VALUES ( ?,?,?,?,?,?,? ) "; return $this->oDb->query($sql, $user_id, $date, $time, $session_key, $ip, $os, $browser); } function getHistoryRows($user_id) { $table_shistory = Config::Get('db.table.shistory'); $history_limit = Config::Get('shistoryLimit'); $sql = "SELECT `enter_date`, `enter_time`, `user_ip`, `user_os`, `user_agent` FROM {$table_shistory} WHERE `user_id` = ? ORDER BY id DESC LIMIT {$history_limit} "; $aReturn = array(); if ($aRows = $this->oDb->select($sql, $user_id)) { foreach ($aRows as $aRow) $aReturn[] = $aRow; } return $aReturn; } } <file_sep>/classes/modules/sessions/Sessions.class.php <?php class PluginSHistory_ModuleSessions extends Module { protected $oMapper; function init() { $this->oMapper = Engine::GetMapper(__CLASS__); return true; } function update($user) { $sessionData = $user->getSession(); $skey = $sessionData->getSessionKey(); $ip = $sessionData->getSessionIpLast(); $aDate = explode(' ', $sessionData->getSessionDateLast()); if (!$this->oMapper->isCurrent($sessionData->getUserId(), $sessionData->getSessionKey())) { $this->oMapper->addCurrent( $sessionData->getUserId(), $sessionData->getSessionKey(), $aDate[0], $aDate[1], $this->getUserOs(), $this->getUserBrowser(), $sessionData->getSessionIpLast() ); } } function getUserOs() { if (stristr($_SERVER['HTTP_USER_AGENT'], 'Win')) return "Windows"; elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Linux')) return "Linux"; elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Unix')) return "Unix"; elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Mac')) return "Macintosh"; else return "Unknown"; } function getUserBrowser() { if (stristr($_SERVER['HTTP_USER_AGENT'], 'Firefox')) return 'firefox'; elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Chrome')) return 'chrome'; elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Safari')) return 'safari'; elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Opera')) return 'opera'; elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'MSIE 6.0')) return 'ie6'; elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'MSIE 7.0')) return 'ie7'; elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'MSIE 8.0')) return 'ie8'; elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'MSIE 9.0')) return 'ie9'; else return 'unknown'; } function getSessionsRows($user_id) { return $this->oMapper->getHistoryRows($user_id); } } <file_sep>/classes/hooks/HookSHistory.class.php <?php class PluginSHistory_HookSHistory extends Hook { const ConfigKey = 'shistory'; const HooksArray = [ 'template_menu_settings_settings_item' => 'profile', ]; public function RegisterHook() { $plugin_config_key = $this::ConfigKey; foreach ($this::HooksArray as $hook => $callback) { $this->AddHook( $hook, $callback, __CLASS__, Config::Get("plugin.{$plugin_config_key}.hook_priority.{$hook}") ?? 1 ); } } public function profile() { return $this->Viewer_Fetch(Plugin::GetTemplatePath(__CLASS__) . 'inject_profile.tpl'); } } <file_sep>/templates/language/english.php <?php return array( 'title' => 'Session History', 'date' => 'Auth date', 'ip' => 'IP address', 'os' => 'OS', 'agent' => 'Browser' );<file_sep>/config/config.php <?php $config = array(); Config::Set('shistoryLimit', 10); Config::Set('block.rule_sessions', array( 'action' => array( 'sessions', ), 'blocks' => array( 'right' => array('actions/ActionProfile/sidebar.tpl') ) )); Config::Set('router.page.sessions', 'PluginSHistory_ActionSessions'); Config::Set('db.table.shistory', '___db.table.prefix___shistory'); $config['hook_priority'] = [ 'template_menu_settings_settings_item' => -10, ]; return $config;
2cffbd33b60a3defb6061686fd1f0e481ed7c6e6
[ "Markdown", "SQL", "PHP" ]
11
PHP
ImaginariaLS/ls_shistory
f604f627bf2f669c2006ba5817f1d3fba5e1ffeb
e244c9110d589202a424f9c7818032878854c1b5
refs/heads/master
<repo_name>rnarrkus/markwil.so<file_sep>/pages/cv.js import React, { Component } from 'react' import { RichText } from 'prismic-reactjs' import { getResumeAPI } from '../api/api' import Head from 'next/head' import linkResolver from '../helpers/linkResolver' import Layout from '../components/layout' const Resume = ({ resume = [] }) => ( <Layout> <Head> <title key="title"><NAME> | Curriculum Vitae</title> <meta key="og:title" property="og:title" content="<NAME> Curriculum Vitae" /> </Head> <div className='cv flex'> <div className='flexi twelve'> <h1>Curriculum vitae</h1> {resume.map((res, index) => ( <div key={index}> {res.data.company.map((dat, index) => ( <div key={index} className='cv-section' > {dat.url.url ? <p className='cv-section--head'><strong><a href={dat.url.url}>{dat.companyname[0].text}</a></strong>: {dat.position[0].text}</p> : <p className='cv-section--head'><strong>{dat.companyname[0].text}</strong>: {dat.position[0].text}</p>} <small>{dat.timeperiod[0].text}</small> {RichText.render(dat.description, linkResolver)} </div> ))} </div> ))} </div> </div> </Layout> ) Resume.getInitialProps = async () => { const response = await getResumeAPI() return { resume: response.results } } export default Resume <file_sep>/pages/posts.js import { getPostsAPI } from '../api/api' import { linkResolver } from '../helpers/linkResolver' import Layout from '../components/layout' import Link from 'next/link' import '../global/global-styles.css' const Posts = ({ posts = [] }) => ( <Layout> <div className='posts flex'> <div className='flexi twelve'> <div className='posts--content'> <h1>Posts.</h1> <p>Not the ramblings of a mad man 👀</p> <ul className='posts-list'> {posts.map((post, index) => ( <li key={index}> <Link prefetch as={linkResolver(post)} href={`/post?slug=${post.uid}`} passHref > <a>{post.data.title[0].text}</a> </Link> </li> ))} </ul> </div> </div> </div> </Layout> ) Posts.getInitialProps = async () => { const response = await getPostsAPI() return { posts: response.results } } export default Posts <file_sep>/pages/index.js import { getSideProjectsAPI } from '../api/api' import { linkResolver } from '../helpers/linkResolver' import Head from 'next/head' import Layout from '../components/layout' import styles from './index.css' import Link from 'next/link' import '../global/global-styles.css' const Index = ({ projects = [] }) => ( <Layout> <Head> <title key="title"><NAME></title> <meta key="description" name="description" content="UX Designer from Glasgow, Scotland" /> <meta key="og:title" property="og:title" content="<NAME>" /> <meta key="og:description" property="og:description" content="UX Designer from Glasgow, Scotland" /> </Head> <div className='hero flex'> <div className='flexi twelve'> <div className='hero--content'> <h1>Hey 👋</h1> <p>I'm Markus, a UX Designer from sunny Glasgow Scotland, helping companies create beautiful and functional products.</p> <p>Currently working with mixed reality at <a href='https://soluis.com'>Soluis</a>. Previously <a href='https://itison.com'>itison.com</a>.</p> </div> </div> </div> <div className='side-projects flex flexi-top'> <div className='flexi twelve'> <div className='section-title'>On the side</div> </div> {projects.map((side_project, index) => ( <div key={index} className='flexi six'> <Link as={linkResolver(side_project)} href={`/side_project?slug=${side_project.uid}`} passHref > <a><img src={side_project.data.image.url} alt={side_project.data.image.alt} /></a> </Link> <h3>{side_project.data.title[0].text}</h3> <p> <Link prefetch as={linkResolver(side_project)} href={`/side_project?slug=${side_project.uid}`} passHref > <a>{side_project.data.title[0].text}</a> </Link> - {side_project.data.description[0].text} </p> </div> ))} </div> </Layout> ) Index.getInitialProps = async () => { const response = await getSideProjectsAPI() return { projects: response.results } } export default Index <file_sep>/components/footer.js import Link from 'next/link' const Footer = () => ( <footer> <div className='footer flex'> <div className='flexi twelve'> <h3>Say hello.</h3> <a className='button' href='mailto:<EMAIL>'>Email Me</a> <div className='footer--links'> <a href='https://github.com/rnarrkus'>GitHub</a> <a href='https://dribbble.com/1xpng'>Dribbble</a> </div> </div> </div> </footer> ) export default Footer <file_sep>/pages/_app.js import App, { Container } from 'next/app' import React from 'react' import Head from 'next/head' import { SEO } from '../config' export default class MyApp extends App { static async getInitialProps({ Component, router, ctx }) { let pageProps = {} if (Component.getInitialProps) { pageProps = await Component.getInitialProps(ctx) } return { pageProps } } render() { const { Component, pageProps } = this.props return ( <Container> <Head> <title key="title">{SEO.title}</title> <meta key="description" name="description" content={SEO.description} /> <meta key="twitter:card" name="twitter:card" content={SEO.twitter.cardType} /> <meta key="twitter:site" name="twitter:site" content={SEO.twitter.handle} /> <meta key="og:url" property="og:url" content={SEO.openGraph.url} /> <meta key="og:type" property="og:type" content={SEO.openGraph.type} /> <meta key="og:title" property="og:title" content={SEO.openGraph.title} /> <meta key="og:description" property="og:description" content={SEO.openGraph.description} /> <meta key="og:image" property="og:image" content={SEO.openGraph.image} /> <meta key="og:image:width" property="og:image:width" content={SEO.openGraph.imageWidth} /> <meta key="og:image:height" property="og:image:height" content={SEO.openGraph.imageHeight} /> <meta key="og:locale" property="og:locale" content={SEO.openGraph.locale} /> <meta name="viewport" content="initial-scale=1.0, width=device-width, user-scalable=no" /> <meta name="HandheldFriendly" content="true" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="format-detection" content="telephone=no" /> </Head> <Component {...pageProps} /> <script dangerouslySetInnerHTML={{ __html: ` <script async src="https://www.googletagmanager.com/gtag/js?id=UA-178268771-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-178268771-1'); </script> `, }} /> </Container> ) } } <file_sep>/pages/project.js import React, { Component } from 'react' import { RichText } from 'prismic-reactjs' import { getSideProjectAPI } from '../api/api' import Head from 'next/head' import linkResolver from '../helpers/linkResolver' import Layout from '../components/layout' import Link from 'next/link' class Project extends Component { static async getInitialProps(context) { const { slug } = context.query const response = await getSideProjectAPI(slug) return { project: response } } addJSONLD(project) { return { __html: `{ "@context": "http://schema.org", "@type": "BlogPosting", "mainEntityOfPage": { "@type": "WebPage", }, "headline": "${project.og_title[0].text}", "image": [ "${project.og_image.url}" ], "author": { "@type": "Person", "name": "<NAME>" }, "publisher": { "@type": "Organization", "name": "<NAME>", }, "description": "${project.og_description[0].text}" }` }; } render() { const project = this.props.project.data return ( <Layout> <Head> <title key="title">{project.og_title[0].text}</title> <meta key="description" name="description" content={project.og_description[0].text} /> <meta key="og:type" property="og:type" content="article" /> <meta key="og:title" property="og:title" content={project.og_title[0].text} /> <meta key="og:description" property="og:description" content={project.og_description[0].text} /> <meta key="og:image" property="og:image" content={project.og_image.url} /> </Head> <div className='project flex'> <div className='flexi twelve'> <article> <img src={project.image.url} alt={project.image.alt}/> <h1>{project.title.length ? project.title[0].text : ''}</h1> {RichText.render(project.body, linkResolver)} </article> </div> </div> <script type="application/ld+json" dangerouslySetInnerHTML={this.addJSONLD(project)} /> </Layout> ) } } export default Project
d180a470c19ee8d64dc00aabc93114b6856549f0
[ "JavaScript" ]
6
JavaScript
rnarrkus/markwil.so
24a56d9dee3a008bcb6bcc9109d954461e94c041
29b27af6e8796b8acf75d32c03dbf5592e2a8c27
refs/heads/master
<file_sep>import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import opennlp.tools.namefind.NameFinderME; import opennlp.tools.namefind.TokenNameFinderModel; import opennlp.tools.tokenize.SimpleTokenizer; import opennlp.tools.tokenize.Tokenizer; import opennlp.tools.util.InvalidFormatException; import opennlp.tools.util.Span; public class OpenNLP_NER_MultiNames { public static void main(String[] args) throws InvalidFormatException, FileNotFoundException, IOException { String modelPath = "D:\\Projects\\TT_HOME\\opennlp-models\\"; String[] sentences = { "Former first lady <NAME> was taken to a " + "suburban Los Angeles " + "hospital "+"as a precaution" +"Sunday after a " + "fall at her home, an " + "aide said. ", "The 86-year-old Reagan will remain overnight for " + "observation at a hospital in Santa Monica, California, " + "said Joanne " + "Drake, chief of staff for the Reagan Foundation on 23rd July."}; NameFinderME finder = new NameFinderME(new TokenNameFinderModel(new FileInputStream(new File(modelPath + "en-ner-organization.bin")))); Tokenizer tokenizer = SimpleTokenizer.INSTANCE; for (int si = 0; si < sentences.length; si++) { String[] tokens = tokenizer.tokenize(sentences[si]); Span[] names = finder.find(tokens); displayNames(names, tokens); } finder.clearAdaptiveData(); } private static void displayNames(Span[] names, String[] tokens) { for (int si = 0; si < names.length; si++) { StringBuilder cb = new StringBuilder(); for (int ti = names[si].getStart(); ti < names[si].getEnd(); ti++) { cb.append(tokens[ti]).append(" "); } System.out.println(cb.substring(0, cb.length() - 1)); System.out.println("ttype: " + names[si].getType()); } } private static List<String> getPesonalModel() throws IOException { String sCurrentLine; List<String> lst = new ArrayList<String>(); //this should return an object that has all the info about the doc you want BufferedReader br = new BufferedReader(new FileReader("D://msg.txt")); while ((sCurrentLine = br.readLine()) != null) { lst.add(sCurrentLine); } return lst; } } <file_sep>import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import opennlp.tools.namefind.NameFinderME; import opennlp.tools.namefind.TokenNameFinderModel; import opennlp.tools.sentdetect.SentenceDetector; import opennlp.tools.sentdetect.SentenceDetectorME; import opennlp.tools.sentdetect.SentenceModel; import opennlp.tools.tokenize.TokenizerME; import opennlp.tools.tokenize.TokenizerModel; import opennlp.tools.util.Span; public class OpenNLPNER implements Runnable { static TokenizerModel tm = null; static TokenNameFinderModel locModel = null; String doc; NameFinderME myNameFinder; TokenizerME wordBreaker; SentenceDetector sd; public OpenNLPNER() { } public OpenNLPNER(String document, SentenceDetector sd, NameFinderME mf, TokenizerME wordBreaker) { System.out.println("got doc"); this.sd = sd; this.myNameFinder = mf; this.wordBreaker = wordBreaker; doc = document; } private static List<String> getMyDocsFromSomewhere() throws IOException { String sCurrentLine; List<String> lst = new ArrayList<String>(); //this should return an object that has all the info about the doc you want BufferedReader br = new BufferedReader(new FileReader("D://msg.txt")); while ((sCurrentLine = br.readLine()) != null) { lst.add(sCurrentLine); } return lst; } public static void main(String[] args) { try { String modelPath = "D:\\Projects\\TT_HOME\\opennlp-models\\"; if (tm == null) { //user does normal namefinder instantiations... InputStream stream = new FileInputStream(new File(modelPath + "en-token.bin")); // new SentenceDetectorME(new SentenceModel(new FileInputStream(new File(modelPath + "en-sent.zip")))); tm = new TokenizerModel(stream); // new TokenizerME(tm); locModel = new TokenNameFinderModel(new FileInputStream(new File(modelPath + "en-ner-location.bin"))); // new NameFinderME(locModel); } System.out.println("getting data"); List<String> docs = getMyDocsFromSomewhere(); System.out.println("done getting data"); // FileWriter fw = new FileWriter("C:\\apache\\modelbuilder\\sentences.txt"); for (String doc : docs) { // System.out.println(doc); //you could also use the runnable here and launch in a diff thread new OpenNLPNER(doc, new SentenceDetectorME(new SentenceModel(new FileInputStream(new File(modelPath + "en-sent.bin")))), new NameFinderME(locModel), new TokenizerME(tm)).run(); } System.out.println("done"); } catch (Exception ex) { System.out.println(ex); } } @Override public void run() { try { process(doc); } catch (Exception ex) { System.out.println(ex); } } public void process(String document) throws Exception { System.out.println(document); // user instantiates the non static entitylinkerproperty object and constructs is with a pointer to the prop file they need to use String modelPath = "C:\\apache\\entitylinker\\"; //input document myNameFinder.clearAdaptiveData(); //user splits doc to sentences String[] sentences = sd.sentDetect(document); //get the sentence spans Span[] sentenceSpans = sd.sentPosDetect(document); Span[][] allnamesInDoc = new Span[sentenceSpans.length][]; String[][] allTokensInDoc = new String[sentenceSpans.length][]; for (int sentenceIndex = 0; sentenceIndex < sentences.length; sentenceIndex++) { String[] stringTokens = wordBreaker.tokenize(sentences[sentenceIndex]); Span[] tokenSpans = wordBreaker.tokenizePos(sentences[sentenceIndex]); Span[] spans = myNameFinder.find(stringTokens); allnamesInDoc[sentenceIndex] = spans; allTokensInDoc[sentenceIndex] = stringTokens; } //now access the data like this... for (int s = 0; s < sentenceSpans.length; s++) { Span[] namesInSentence = allnamesInDoc[s]; String[] tokensInSentence = allTokensInDoc[s]; String[] entities = Span.spansToStrings(namesInSentence, tokensInSentence); for (String entity : entities) { //start building up the XML here.... System.out.println(entity + " Was in setnence " + s + " @ " + namesInSentence[s].toString()); } } } }<file_sep>import opennlp.tools.util.Span; public class Annotation implements Comparable<Annotation> { private Span span; private String type; private double prob; public Annotation(String type, Span span, double prob) { this.span = span; this.type = type; this.prob = prob; } public Span getSpan() { return span; } public String getType() { return type; } public double getProb() { return prob; } public int compareTo(Annotation a) { int c = span.compareTo(a.span); if (c == 0) { c = Double.compare(prob, a.prob); if (c == 0) { c = type.compareTo(a.type); } } return c; } public String toString() { return type + " " + span + " " + prob; } }
b80fe00d5d38ed0db471d5d81b12a35b9f183aaf
[ "Java" ]
3
Java
xeonee/OpenNLP
4248f72b50b4ba8dc325de54454403557504afc7
1a4913623a8f304ad46f72595b376c7ab59cea67
refs/heads/master
<file_sep>package com.cse396.healthband; import android.support.annotation.NonNull; import android.util.Pair; import com.google.firebase.database.Exclude; import com.google.firebase.database.ServerValue; import java.util.HashMap; /** * @param <U> any object * @param <V> any object * Class to associate two names with two values. */ class TaggedPairs<U, V> { private HashMap<String, Object> timestamp; private Pair<String, U> tag1; private Pair<String, V> tag2; TaggedPairs(String name1, U item1,String name2, V item2){ this.tag1 = new Pair<>(name1, item1); this.tag2 = new Pair<>(name2, item2); } @SuppressWarnings("unchecked") TaggedPairs(String name1, V item1){ this.tag1 = new Pair<>("timestamp",(U) ServerValue.TIMESTAMP); this.tag2 = new Pair<>(name1, item1); } public HashMap<String, Object> getTimestampCreated(){ return timestamp; } String getFirstTag(){ return tag1.first; } String getSecondTag(){ return tag2.first; } U getFirstValue(){ return tag1.second; } V getSecondValue(){ return tag2.second; } @Exclude public long getTimestampCreatedLong(){ return (long)timestamp.get("timestamp"); } @NonNull @Override public String toString() { return tag1.toString() + tag2.toString(); } }
e4dda347a9bd4ebd6256eed7af0d391602157a6a
[ "Java" ]
1
Java
mokumus/HealthBand
ffc9efb021a136e46e9d04c04687a4a3d94c3357
5dfca653fbf2cb315752cb74b54c27fb7c0d281d
refs/heads/master
<file_sep>package com.epam.brest.courses.model; public class Deposit { private Integer depositId; private String depositName; public Integer getDepositId() { return depositId; } public void setDepositId(Integer depositId) { this.depositId = depositId; } public String getDepositName() { return depositName; } public void setDepositName(String depositName) { this.depositName = depositName; } @Override public String toString() { return "Deposit{" + "depositId=" + depositId + ", depositName='" + depositName + '\'' + '}'; } } <file_sep>package com.epam.brest.courses.dao; import com.epam.brest.courses.model.Deposit; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; public class DepositJdbcDaoImpl implements DepositDao { private final NamedParameterJdbcTemplate namedParameterJdbcTemplate; public DepositJdbcDaoImpl(NamedParameterJdbcTemplate namedParameterJdbcTemplate) { this.namedParameterJdbcTemplate = namedParameterJdbcTemplate; } @Override public List<Deposit> getDeposits() { List<Deposit> deposits = namedParameterJdbcTemplate .query("SELECT d.depositId, d.depositName FROM deposit d ORDER BY d.depositName", new DepositRowMapper()); return deposits; } @Override public Deposit getDepartmentById(Integer depositId) { return null; } @Override public Deposit addDepartment(Deposit deposit) { return null; } @Override public void updateDepartment(Deposit deposit) { } @Override public void deleteDepartment(Integer depositId) { } private class DepositRowMapper implements RowMapper<Deposit> { @Override public Deposit mapRow(ResultSet resultSet, int i) throws SQLException { Deposit deposit = new Deposit(); deposit.setDepositId(resultSet.getInt("DEPOSIT_ID")); deposit.setDepositName(resultSet.getString("DEPOSIT_NAME")); return deposit; } } } <file_sep>DROP TABLE IF EXISTS deposit; CREATE TABLE deposit ( depositId INT NOT NULL AUTO_INCREMENT, depositName VARCHAR(255) NOT NULL UNIQUE, PRIMARY KEY (depositId) );<file_sep># avazdusevich-deposit-managment Little piece of banking aplication ![Java CI](https://github.com/Brest-Java-Course-2020/avazdusevich-deposit-managment/workflows/Java%20CI/badge.svg)
6a9ddb9801e8706126a5ae6e6b189306600aa1dc
[ "Markdown", "Java", "SQL" ]
4
Java
Brest-Java-Course-2020/avazdusevich-deposit-managment
4c0fc691f6098805004ada23188a49c2d57b3236
b2f355ab5ed7ce2c0badebbeac0e40ef0ae16350
refs/heads/master
<repo_name>hjm7091/Design_Pattern<file_sep>/AbstractFactoryPattern/README.md ### 추상 팩토리 패턴 * 추상 팩토리 패턴은 관련성 있는 여러 종류의 객체를 일관된 방식으로 생성하는 경우 유용하다. * 엘리베이터를 예로 들면 LG 부품을 사용하는 엘리베이터는 LG의 모터와 문을 이용할 것이다. 만약 엘리베이터가 현대 부품을 사용하려는 경우 엘리베이터의 모터와 문이 일관성 있게 LG에서 현대로 변경되어야 한다. * 이러한 경우에는 부품별로 Factory를 정의하는 대신 관련 객체들을 일관성 있게 생성할 수 있도록 Factory 클래스를 정의하는 것이 효과적이다. * 예를 들어 Motor 클래스를 위한 MotorFactory 클래스와 Door 클래스를 위한 DoorFactory 클래스를 정의하는 대신 LG 부품들을 위한 LGFactory 클래스와 현대 부품들을 위한 HyundaiFactory 클래스를 정의하는 것이 바람직하다. #### 추상 팩토리 패턴 예시 ![ex](https://user-images.githubusercontent.com/28583661/72862584-112b2500-3d11-11ea-9da1-fe0bc9e6ad1a.PNG) <file_sep>/StatePattern/README.md ### 스테이트 패턴 * 스테이트 패턴은 어떤 행위를 수행할 때 상태에 행위를 수행하도록 위임한다. * 스테이트 패턴에서는 시스템의 각 상태를 클래스로 분리해 표현하고, 각 클래스에서 수행하는 행위들을 메서드로 구현한다. * 상태들을 외부로부터 캡슐화하기 위해 인터페이스를 만들어 시스템의 각 상태를 나타내는 클래스로 하여금 실체화하게 한다. * 스트래티지 패턴과 유사함. * 차이점1 -> 스테이트 패턴에서는 행위가 자주 변경되지만 스트래티지 패턴에서는 행위가 한 번 고정되면 자주 변경되지 않는다. * 차이점2 -> 스테이트 패턴에서는 상태 변경을 State 요소를 구현한 클래스 자신이 수행하지만 스트래티지 패턴에서는 Client가 수행한다. 즉, 스트래티지 패턴에서는 행위 시작과 변경이 Client 클래스에서 이루어지며 통제된다. #### before (스테이트 패턴 적용 X) ![before](https://user-images.githubusercontent.com/28583661/71965335-ce624b00-3242-11ea-953a-de276850f934.PNG) #### after (스테이트 패턴 적용 O) ![after](https://user-images.githubusercontent.com/28583661/71969299-ba6e1780-3249-11ea-93e1-1af7c6599562.PNG) #### 스테이트 패턴 예제(벤딩 머신) ![vending](https://user-images.githubusercontent.com/28583661/71976976-0d9c9600-325b-11ea-8b2c-5d275646c538.PNG) * VendingMachine : VendingMachine 클래스는 MoneyBox나 Drinking 클래스에 따라 상태가 달라지며, 상태에 따라 다른 일을 수행함. * Drinking : 음료수에 대한 클래스. 음료수 가격과 재고 데이터를 가짐 * MoneyBox : VendingMachine 클래스가 가진 돈에 대한 클래스 * State : VendingMachine 클래스의 상태를 갖는 인터페이스 * NoMoneyState : 돈이 하나도 없는 상태 * NoEnoughMoneyState : 돈은 있으나 음료를 사기에는 부족한 상태 * EnoughMoneyState : 음료를 사기에 돈이 충분한 상태 * SoldOutState : 음료가 매진된 상태<file_sep>/TemplateMethodPattern/src/ex_after/ReportGenerator.java package ex_after; import java.util.ArrayList; import java.util.List; public abstract class ReportGenerator { public String generate(List<Customer> customers) { List<Customer> selectedCustomers = select(customers); String report = getReportHeader(selectedCustomers); for(int i=0; i<selectedCustomers.size(); i++) { Customer customer = selectedCustomers.get(i); report += getReportForCustomer(customer); } report += getReportFooter(selectedCustomers); return report; } protected List<Customer> select(List<Customer> customers) { List<Customer> selected = new ArrayList<Customer>(); for(Customer customer : customers) if(customerReportCondition(customer)) selected.add(customer); return selected; } protected abstract boolean customerReportCondition(Customer customer); protected abstract String getReportHeader(List<Customer> customers); protected abstract String getReportForCustomer(Customer customer); protected abstract String getReportFooter(List<Customer> customers); } <file_sep>/DesignPattern/chapter5/ex4/Client.java package ex4; public class Client { private static final int INIT_LOCATION[] = {50, 100, 150}; public static void main(String[] args) { Ball[] balls = new Ball[3]; // setStrategy(balls, new HorizonalMoveStrategy(), new RedDrawStrategy()); // setStrategy(balls, new VerticalMoveStrategy(), new BlueDrawStrategy()); setStrategy(balls, new DiagonalMoveStrategy(), new RedDrawStrategy()); new BallFrame(balls); } public static void setStrategy(Ball[] balls, DirectionStrategy directionStrategy, DrawStrategy drawStrategy){ for(int i=0; i<balls.length; i++) { balls[i] = new Ball(INIT_LOCATION[i], INIT_LOCATION[i]); balls[i].setDirectionStrategy(directionStrategy); balls[i].setDrawStrategy(drawStrategy); balls[i].start(); } } } <file_sep>/FactoryMethodPattern/src/ex2/CarState.java package ex2; public abstract class CarState { protected Car car; protected CarState(Car car) { this.car = car; } public void speedDown(int targetSpeed) { System.out.print("Speed: " + car.getSpeed()); if(targetSpeed < car.getSpeed()) car.setSpeed(targetSpeed); System.out.println(" ==> " + car.getSpeed()); } public abstract void speedUp(int targetSpeed); public abstract void engineFailedDetected(); public abstract void engineRepaired(); } <file_sep>/TemplateMethodPattern/README.md ### 템플릿 메서드 패턴 * 템플릿 메서드 패턴은 전체적으로는 동일하면서 부분적으로는 다른 구문으로 구성된 메서드의 코드 중복을 최소화할 때 유용하다. * after 예제처럼 Motor 클래스의 move메서드(템플릿 메서드)는 HyundaiMotor와 LGMotor에서 동일한 기능을 구현하면서 각 하위 클래스에서 구체적으로 정의할 필요가 있는 부분, 즉 moveMotor메서드(primitive or hook메서드) 부분만 각 하위 클래스에서 오버라이드되도록 한다. #### before (템플릿 메서드 패턴 적용 X) ![before](https://user-images.githubusercontent.com/28583661/72605682-948af600-3960-11ea-9dfc-f5f6230056b3.PNG) #### after (템플릿 메서드 패턴 적용 O) ![after](https://user-images.githubusercontent.com/28583661/72605603-71f8dd00-3960-11ea-80ad-7366923af23d.PNG)<file_sep>/StatePattern/src/after/SLEEPING.java package after; public class SLEEPING implements State{ private static SLEEPING sleeping = new SLEEPING(); private SLEEPING() { } public static SLEEPING getInstance() { return sleeping; } @Override public void on_button_pushed(Light light) { light.setState(ON.getInstance()); System.out.println("Light On Back!!"); } @Override public void off_button_pushed(Light light) { light.setState(OFF.getInstance()); System.out.println("Light Off Back!!"); } } <file_sep>/AbstractFactoryPattern/ExampleOfAbstractFactory/motor/HyundaiMotor.java package motor; import direction.Direction; public class HyundaiMotor extends Motor { @Override protected void moveMotor(Direction direction) { System.out.println("move Hyundai Motor"); } } <file_sep>/CommandPattern/src/ex3/ElevatorRequestCommand.java package ex3; public class ElevatorRequestCommand implements Command{ private int destination; private Direction direction; private ElevatorManager manager; public ElevatorRequestCommand(int destination, Direction direction, ElevatorManager manager) { this.destination = destination; this.direction = direction; this.manager = manager; } @Override public void execute() { manager.requestElevator(destination, direction); } } <file_sep>/DesignPattern/chapter5/ex4/DrawStrategy.java package ex4; public abstract class DrawStrategy { public abstract void draw(Ball ball); } <file_sep>/DesignPattern/chapter5/ex4/RedDrawStrategy.java package ex4; import java.awt.Color; public class RedDrawStrategy extends DrawStrategy{ @Override public void draw(Ball ball) { ball.setColor(Color.red); } } <file_sep>/DesignPattern/src/chapter1/Main.java package chapter1; import java.util.Vector; public class Main { public static void main(String[] args) { Student s1 = new Student("manSup"); Student s2 = new Student("gilDong"); Course se = new Course("Software Engineering"); Course dp = new Course("Design Pattern"); Transcript t1 = new Transcript(s1, se); //manSup은 소프트웨어 공학 수강 Transcript t2 = new Transcript(s1, dp); //manSup은 디자인 패턴 수강 Transcript t3 = new Transcript(s2, dp); //gilDong은 디자인 패턴 수강 t1.setDate("2012"); t1.setGrade("B0"); t2.setDate("2012"); t2.setGrade("D+"); t3.setDate("2013"); t3.setGrade("C+"); Vector<Course> courses; courses = s1.getCourses(); for(Course course : courses) { System.out.println(course.getName()); } System.out.println(); Vector<Student> students; students = dp.getStudents(); for(Student student : students) { System.out.println(student.getName()); } } } <file_sep>/FactoryMethodPattern/src/ex1/MotorVendorID.java package ex1; public enum MotorVendorID { LG, HYUNDAI; } <file_sep>/DesignPattern/src/chapter1/Course.java package chapter1; import java.util.Iterator; import java.util.Vector; public class Course { private Vector<Transcript> transcripts; private String name; public Course(String name) { this.name = name; transcripts = new Vector<Transcript>(); } public void addTranscript(Transcript transcript) { transcripts.add(transcript); } public String getName() { return name; } public Vector<Student> getStudents() { Vector<Student> students = new Vector<Student>(); Iterator<Transcript> itor = transcripts.iterator(); while(itor.hasNext()) { Transcript tr = itor.next(); students.add(tr.getStudent()); } return students; } } <file_sep>/FactoryMethodPattern/src/use_factoryMethod/Client.java package use_factoryMethod; public class Client { public static void main(String[] args) { ElevatorManager emWithResponseTimeScheduler = new ElevatorManager(2, SchedulingStrategyID.RESPONSE_TIME); emWithResponseTimeScheduler.requestElevator(10, Direction.UP); ElevatorManager emWithThroughputScheduler = new ElevatorManager(2, SchedulingStrategyID.THROUGHPUT); emWithThroughputScheduler.requestElevator(10, Direction.UP); ElevatorManager emWithDynamicScheduler = new ElevatorManager(2, SchedulingStrategyID.DYNAMIC); emWithDynamicScheduler.requestElevator(10, Direction.UP); } } <file_sep>/DecoratorPattern/src/ex1/Client.java package ex1; public class Client { public static void main(String[] args) { EmailContent simple = new BasicEmailContent("Hello"); System.out.println(simple.getContent()); System.out.println(); EmailContent external = new ExternalDecorator(simple); System.out.println(external.getContent()); System.out.println(); EmailContent secure = new SecureDecorator(simple); System.out.println(secure.getContent()); System.out.println(); EmailContent secureAfterExternal = new SecureDecorator(external); System.out.println(secureAfterExternal.getContent()); } } <file_sep>/ObserverPattern/README.md ### 옵서버 패턴 * 옵서버 패턴은 데이터의 변경이 발생했을 경우 상대 클래스나 객체에 의존하지 않으면서 데이터 변경을 통보하고자 할 때 유용하다. * 옵서버 패턴은 통보 대상 객체의 관리를 Subject 클래스와 Observer 인터페이스로 일반화한다. 그러면 데이터 변경을 통보하는 클래스 (ConcreteSubject)는 통보 대상 클래스나 객체(ConcreteObserver)에 대한 의존성을 없앨 수 있다. 결과적으로 옵서버 패턴은 통보 대상 클래스나 대상 객체의 변경에도 ConcreteSubject 클래스를 수정 없이 그대로 사용할 수 있도록 한다. #### before (옵서버 패턴 적용 X) ![before](https://user-images.githubusercontent.com/28583661/72201986-c2be9080-349d-11ea-9986-8ef81051d0f3.PNG) #### after (옵서버 패턴 적용 O) ![after](https://user-images.githubusercontent.com/28583661/72201987-c2be9080-349d-11ea-936f-b46df7960fab.PNG)<file_sep>/CompoundPattern/src/duck_example/abstract_factory/CountingDuckFactory.java package duck_example.abstract_factory; import duck_example.decorator.QuackCounter; import duck_example.duck.DuckCall; import duck_example.duck.MallardDuck; import duck_example.duck.Quackable; import duck_example.duck.RedheadDuck; import duck_example.duck.RubberDuck; public class CountingDuckFactory extends AbstractDuckFactory { @Override public Quackable createMallardDuck() { return new QuackCounter(new MallardDuck()); } @Override public Quackable createRedheadDuck() { return new QuackCounter(new RedheadDuck()); } @Override public Quackable createDuckCall() { return new QuackCounter(new DuckCall()); } @Override public Quackable createRubberDuck() { return new QuackCounter(new RubberDuck()); } } <file_sep>/DesignPattern/src/chapter1/Car.java package chapter1; public class Car { } <file_sep>/DesignPattern/chapter5/ex4/BallFrame.java package ex4; import java.awt.BorderLayout; import javax.swing.JFrame; public class BallFrame extends JFrame{ private static final long serialVersionUID = 1L; public static final int WIDTH = 500; public static final int HEIGHT = 400; private Field field; public BallFrame(Ball[] balls) { super("Balls"); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new BorderLayout()); field = new Field(balls); Thread th = new Thread(field); th.start(); add(field, BorderLayout.CENTER); setSize(WIDTH, HEIGHT); setVisible(true); } } <file_sep>/AbstractFactoryPattern/ExampleOfAbstractFactory/motor/LGMotor.java package motor; import direction.Direction; public class LGMotor extends Motor{ @Override protected void moveMotor(Direction direction) { System.out.println("move LG Motor"); } } <file_sep>/CommandPattern/src/ex3/Client.java package ex3; public class Client { public static void main(String[] args) { ElevatorController controller1 = new ElevatorController(1); ElevatorController controller2 = new ElevatorController(2); ElevatorManager em = new ElevatorManager(2); em.addController(controller1); em.addController(controller2); Command destinationCommand1stController = new DestinationSelectionCommand(1, controller1); ElevatorButton destinationButton1stFloor = new ElevatorButton(destinationCommand1stController); destinationButton1stFloor.pressed(); Command destinationCommand2ndController = new DestinationSelectionCommand(2, controller2); ElevatorButton destinationButton2ndFloor = new ElevatorButton(destinationCommand2ndController); destinationButton2ndFloor.pressed(); Command requestDonwCommand = new ElevatorRequestCommand(2, Direction.DOWN, em); ElevatorButton requestDownFloorButton2ndFloor = new ElevatorButton(requestDonwCommand); requestDownFloorButton2ndFloor.pressed(); } } <file_sep>/ObserverPattern/src/ex1/Client.java package ex1; public class Client { public static void main(String[] args) { Battery battery = new Battery(); Observer batteryLevelDisplay = new BatteryLevelDisplay(battery); Observer lowerBatteryWarning = new LowerBatteryWarning(battery); battery.attach(batteryLevelDisplay); battery.attach(lowerBatteryWarning); battery.consume(20); battery.consume(50); battery.consume(10); } } <file_sep>/TemplateMethodPattern/src/after/HyundaiMotor.java package after; public class HyundaiMotor extends Motor { public HyundaiMotor(Door door) { super(door); } @Override protected void moveMotor(Direction direction) { System.out.println("HyundaiMotor 구동시킴"); } } <file_sep>/AbstractFactoryPattern/ExampleOfAbstractFactory/factory/HyundaiElevatorFactory.java package factory; import door.Door; import door.HyundaiDoor; import motor.HyundaiMotor; import motor.Motor; public class HyundaiElevatorFactory extends ElevatorFactory{ private Motor motor; private Door door; @Override public Motor createMotor() { if(motor == null) motor = new HyundaiMotor(); return motor; } @Override public Door createDoor() { if(door == null) door = new HyundaiDoor(); return door; } } <file_sep>/FactoryMethodPattern/src/ex2/CarStateFactory.java package ex2; public class CarStateFactory { public static CarState getState(CarStateID stateID, Car car) { CarState state = null; switch (stateID) { case NORMAL: state = NormalState.getInstance(car); break; case LIMP_MODE: state = LimpState.getInstance(car); break; } return state; } } <file_sep>/TemplateMethodPattern/src/ex_after/SimpleReportGenerator.java package ex_after; import java.util.List; public class SimpleReportGenerator extends ReportGenerator{ @Override protected boolean customerReportCondition(Customer customer) { // TODO Auto-generated method stub return true; } @Override protected String getReportHeader(List<Customer> customers) { // TODO Auto-generated method stub return String.format("고객 수: %d명\n", customers.size()); } @Override protected String getReportForCustomer(Customer customer) { // TODO Auto-generated method stub return String.format("%s: %d\n", customer.getName(), customer.getPoint()); } @Override protected String getReportFooter(List<Customer> customers) { // TODO Auto-generated method stub return ""; } } <file_sep>/DecoratorPattern/src/after/Client.java package after; public class Client { public static void main(String[] args) { Display road = new RoadDisplay(); road.draw(); System.out.println(); Display roadWithLane = new LaneDecorator(road); roadWithLane.draw(); System.out.println(); Display roadWithTraffic = new TrafficDecorator(road); roadWithTraffic.draw(); } } <file_sep>/SingletonPattern/README.md ### 싱글턴 패턴 * 싱글턴 패턴은 인스턴스가 오직 하나만 생성되는 것을 보장하고 어디에서든 인스턴스에 접근할 수 있도록 하는 디자인 패턴이다. * 하나의 인스턴스만을 생성하는 책임이 있으며 getInstance 메서드를 통해 모든 클라이언트에게 동일한 인스턴스를 반환하는 작업을 수행함. * 다중 스레드 애플리케이션의 경우 문제가 발생할 수 있다. * 해결책1 -> 정적 변수에 인스턴스를 만들어 바로 초기화하는 방법 * 해결책2 -> 인스턴스를 만드는 메서드에 동기화(synchronized)하는 방법 #### 싱글턴 패턴 예제(티켓 발행 프로그램) ![ticket](https://user-images.githubusercontent.com/28583661/71818078-486fc400-30cb-11ea-9ce1-fe9211be2bed.PNG) * TicketManager : 티켓을 발행할 책임이 있는 클래스. 싱글턴 패턴으로 구현해 유일한 시리얼 번호를 생성한다. * Ticket : 티켓 인터페이스. 시리얼 번호를 설정하고 외부에 알려줄 책임이 있다. * NormalTicket : 정상적인 시리얼 번호가 있는 티켓 * NullTicket : 발행할 수 있는 티켓보다 더 많은 티켓을 요구할 때 발행되는 유효하지 못한 티켓 * UserThread : TicketManager 클래스에게 티켓의 발행을 요구하는 스레드 클래스<file_sep>/FactoryMethodPattern/src/use_factoryMethod/ThroughputScheduler.java package use_factoryMethod; public class ThroughputScheduler implements ElevatorScheduler{ @Override public int selectElevator(ElevatorManager manager, int destination, Direction direction) { return 0; } } <file_sep>/FactoryMethodPattern/README.md ### 팩토리 메서드 패턴 * 팩토리 메서드 패턴은 객체의 생성 코드를 별도의 클래스/메서드로 분리함으로써 객체 생성 방식의 변화에 대비하는데 유용하다. #### before (팩토리 메서드 패턴 적용 X) ![nothing](https://user-images.githubusercontent.com/28583661/72681001-20d51e80-3b03-11ea-9ce6-20f2af3b1730.PNG) #### after (팩토리 메서드 패턴 적용 O) ![factory](https://user-images.githubusercontent.com/28583661/72681012-30546780-3b03-11ea-80a5-2d4b7fd17790.PNG)<file_sep>/AbstractFactoryPattern/Ex/screen/SDScreen.java package screen; import map.Map; public class SDScreen extends Screen { @Override public void drawMap(Map map) { System.out.println("Draw map " + map.getClass().getName() + " on SD screen"); } } <file_sep>/DesignPattern/src/chapter1/Person.java package chapter1; public class Person { private Phone[] phones; private Phone homePhone; private Phone officePhone; private Car car; public Person() { phones = new Phone[2]; } public Phone getPhone(int i) { if(i==0 || i==1) return phones[i]; //0이면 집 전화, 1이면 사무실 전화 return null; } public Phone getHomePhone() { return homePhone; } public void setHomePhone(Phone homePhone) { this.homePhone = homePhone; } public Phone getOfficePhone() { return officePhone; } public void setOfficePhone(Phone officePhone) { this.officePhone = officePhone; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } } <file_sep>/CommandPattern/src/ex3/ElevatorController.java package ex3; public class ElevatorController { private int id; private int curFloor; public ElevatorController(int id) { this.id = id; } public void gotoFloor(int destination) { curFloor = destination; System.out.println("Elevator [" + id + "] Current Floor: " + curFloor); } } <file_sep>/DesignPattern/chapter5/ex3/Book.java package ex3; public class Book { private String name; private int publishYear; private int price; public Book(String name, int publishYear, int price) { this.name = name; this.publishYear = publishYear; this.price = price; } public String getName() { return name; } public int getPublishYear() { return publishYear; } public int getPrice() { return price; } } <file_sep>/CompoundPattern/README.md ### 컴파운드 패턴 * 패턴을 가장 잘 활용하는 방법 가운데 하나로 서로 다른 패턴을 섞어 쓰는 것을 들 수 있다. * 일련의 패턴을 함께 사용하여 다양한 디자인 문제를 해결하는 것을 컴파운드 패턴이라고 한다. ### 컴파운드 패턴 예시 #### 1. Duck 예제 다양한 디자인 패턴 사용 : adapter, decorator, abstract factory, composite, observer ![image](https://user-images.githubusercontent.com/28583661/99894702-b3b58b00-2cc9-11eb-8e0a-6cd37345f1b7.png) #### 2. MVC 패턴 다양한 디자인 패턴 사용 : 뷰(컴포지트 패턴), 컨트롤러(스트래티지 패턴), 모델(옵저버 패턴) ![image](https://user-images.githubusercontent.com/28583661/99898175-cf795b00-2ce2-11eb-8447-77085684248b.png) ### 참고 문헌 Head First Design Patterns. O'REILLY, 한빛미디어. <file_sep>/DesignPattern/src/chapter2/ArrayStack.java package chapter2; public class ArrayStack { public int top; public int[] itemArray; public int stackSize; public ArrayStack(int stackSize) { itemArray = new int[stackSize]; top = -1; this.stackSize = stackSize; } public boolean isEmpty() { return (top == -1); } public boolean isFull() { return (top == (this.stackSize - 1)); } public void push(int item) { if(isFull()) { System.out.println("Inserting fail! Array Stack is full!"); } else { itemArray[++top] = item; System.out.println("Inserted Item : " + item); } } public int pop() { if(isEmpty()) { System.out.println("Deleting fail! Array Stack is empty!"); return -1; } else { return itemArray[top--]; } } public int peek() { if(isEmpty()) { System.out.println("Peeking fail! Array Stack is empty!"); return -1; } else { return itemArray[top]; } } public static void main(String[] args) { ArrayStack st = new ArrayStack(10); st.itemArray[++st.top] = 20; System.out.println(st.itemArray[st.top]); } } <file_sep>/AbstractFactoryPattern/Ex/map/SmallMap.java package map; public class SmallMap extends Map { } <file_sep>/DesignPattern/src/chapter1/Freezer.java package chapter1; public class Freezer extends HomeAppliancies{ @Override public void turnOn() { // TODO Auto-generated method stub } @Override public void turnOff() { // TODO Auto-generated method stub } } <file_sep>/AbstractFactoryPattern/Ex/README.md #### 간단한 내비게이션 예제 ![ex](https://user-images.githubusercontent.com/28583661/72865566-acc19300-3d1b-11ea-95ea-5f74ba057ebe.PNG) #### 추상 팩토리 구성 요소 AbstractFactory : NaviFactory AbstractProduct : GPS, Screen, Map, PathFinder ConcreteFactory : BasicNaviFactory, PremiumNaviFactory ConcreteProduct : CheapGPS, SmallMap, SDScreen, SlowPathFinder, ExpensiveGPS, LargeMap, HDScreen, FastPathFinder Stub : TestGPS, TestScreen, TestMap, TestPathFinder, TestNaviFactory <file_sep>/FactoryMethodPattern/src/use_nothing/ElevatorManager.java package use_nothing; import java.util.ArrayList; import java.util.List; public class ElevatorManager { private List<ElevatorController> controllers; private ThroughputScheduler scheduler; public ElevatorManager(int controllerCount) { controllers = new ArrayList<ElevatorController>(controllerCount); for(int i=0; i<controllerCount; i++) { ElevatorController controller = new ElevatorController(i+1); controllers.add(controller); } scheduler = new ThroughputScheduler(); } public void requestElevator(int destination, Direction direction) { int selectedElevator = scheduler.selectElevator(this, destination, direction); controllers.get(selectedElevator).gotoFloor(destination); } } <file_sep>/README.md ### 1. 객체지향 모델링 ![chapter1](https://user-images.githubusercontent.com/28583661/71540639-79941a00-2990-11ea-8212-47702dd3a46c.PNG) 1) 클래스는 변화의 기본 단위, 공통의 속성과 책임을 갖는 객체들의 집합, 실제 객체를 생성하는 설계도 2) 양방향 연관 관계는 서로의 존재를 안다는 의미, 반면에 단방향 연관 관계는 한 쪽은 알지만 다른 쪽은 모름 3) 집합관계 * 집약관계 -> 전체 객체와 부분 객체의 생명 주기가 다름 * 합성관계 -> 전체 객체가 없어지면 부분 객체도 없어짐 4) 연관 관계 -> 클래스들이 개념상으로 서로 연결되었음을 나타냄, 실선이나 화살표로 표시, 보통은 한 클래스가 다른 클래스에서 제공하는 기능을 사용하는 상황일 때 표시 의존 관계 -> 연관 관계와 비슷하지만 차이점은 두 클래스의 관계가 한 메서드를 실행하는 동안과 같은 매우 짧은 시간만 유지됨, 점선 화살표를 사용해 표시 5) 일반화 관계(상속)는 'is a kind of 관계'지만 실체화 관계(인터페이스)는 'can do this 관계'이다. * * * ### 2. 객체지향 원리 1) 추상화는 사물들의 공통된 특징, 즉 추상적 특징을 파악해 인식의 대상으로 삼는 행위 구체적인 개념보다는 추상적 개념에 의존해야 설계를 유연하게 변경 가능 2) 응집도 : 클래스나 모듈 안의 요소들이 얼마나 밀접하게 관련되어 있는지를 나타냄(높아야 좋음) 결합도 : 어떤 기능을 실행하는 데 다른 클래스나 모듈들에 얼마나 의존적인지를 나타냄(낮아야 좋음) 3) 어떤 클래스의 일부 기능만 재사용하고 싶으면 위임(delegation)을 사용하자 4) 다형성 : 서로 다른 클래스의 객체가 같은 메시지를 받았을 때 각자의 방식으로 동작하는 능력 피터 코드의 상속 규칙 * 자식 클래스와 부모 클래스 사이는 '역할 수행' 관계가 아니어야 한다. * 한 클래스의 인스턴스는 다른 서브 클래스의 객체로 변환할 필요가 절대 없어야 한다. * 자식 클래스가 부모 클래스의 책임을 무시하거나 재정의하지 않고 확장만 수행해야 한다. * 자식 클래스가 단지 일부 기능을 재사용할 목적으로 유틸리티 역할을 수행하는 클래스를 상속하지 않아야 한다. * 자식 클래스가 '역할', '트랜잭션', '디바이스' 등을 특수화해야 한다. * * * ### 3. SOLID 원칙 단일 책임 원칙(Single Responsibility Principle, SRP) * 객체는 단 하나의 책임만을 가져야함 * 책임 -> 해야 하는 것, 할 수 있는 것, 해야하는 것을 잘 할 수 있는 것, 변경 이유 * 시스템에 변경이 발생할 때 기존의 기능에 영향을 주는지를 평가하는 테스트를 회귀 테스트라함 * SRP에 따른 설계를 하면 응집도는 높아지고 더불어 결합도는 낮아짐 개방-폐쇄 원칙(Open Closed Principle, OCP) * 기존의 코드를 변경하지 않으면서 기능을 추가할 수 있도록 설계가 되어야함 * 클래스를 변경하지 않고도 대상 클래스의 환경을 변경할 수 있는 설계가 되어야함 리스코프 치환 원칙(Liskov Substitution Principle, LSP) * 부모 클래스와 자식 클래스 사이의 행위가 일관성이 있어야 한다는 의미 * 자식 클래스는 최소한 자신의 부모 클래스에서 가능한 행위는 수행할 수 있어야함 * LSP를 만족하는 간단한 방법은 재정의하지 않는 것이다. 이는 피터 코드의 상속 규칙에도 명시되어 있음 의존 역전 원칙(Dependency Inversion Principle, DIP) * 의존 관계를 맺을 때 변화하기 쉬운 것 또는 자주 변화하는 것보다는 변화하기 어려운 것, 거의 변화가 없는 것에 의존하라는 원칙 * 인터페이스, 추상클래스 -> 변하지 않는 것, 구체 클래스 -> 변하기 쉬운 것 * DIP를 만족하려면 어떤 클래스가 도움을 받을 때 구체적인 클래스보다는 인터페이스나 추상 클래스와 의존 관계를 맺어야함 인터페이스 분리 원칙(Interface Segregation Principle, ISP) * 인터페이스를 클라이언트에 특화되도록 분리시키라는 설계 원칙 * SRP를 만족하더라도 ISP를 반드시 만족한다고는 할 수 없다. * * * ### 4. 디자인 패턴 패턴은 비슷하거나 동일한 양식 또는 유형들이 반복되어 나타난다는 의미이며, 문제와 해결책도 동일한 유형이나 양식을 통해 쉽게 찾을 수 있음 1) 생성 패턴 : 객체 생성에 관련된 패턴 ex) 추상 팩토리, 팩토리 메서드, 싱글턴 등 2) 구조 패턴 : 클래스나 객체를 조합해 더 큰 구조를 만드는 패턴 ex) 컴퍼지트, 데커레이터 등 3) 행위 패턴 : 객체나 클래스 사이의 알고리즘이나 책임 분배에 관련된 패턴 ex) 옵서버, 스테이트, 스트래티지, 템플릿 메서드, 커맨드 등 순차 다이어그램 ![순차 다이어그램](https://user-images.githubusercontent.com/28583661/71705966-7502b200-2e25-11ea-9b88-aa0e661d1bcf.PNG) 1) 객체들의 상호작용을 나타내는 다이어그램 중 하나, 객체들 사이의 메시지 송신과 순서를 나타냄 2) 생명선 -> 해당 객체가 존재함을 보여줌, 활성 구간 -> 실세로 객체가 연산을 실행하는 상태 3) 비동기 메시지 -> 메시지를 송신한 후 메시지 실행이 끝나기를 기다리지 않고 다음 작업 바로 수행 가능 동기 메시지 -> 메시지의 실행을 요청하는 객체가 메시지의 실행이 종료될 때까지 다음 작업 수행 불가능 4) 가드 -> 메시지가 송신되는 데 만족해야 하는 조건, 응답 -> 메시지가 종료되었음을 표현 * * * ### 참고 문헌 정인상, 채흥석 (2014). 자바 객체지향 디자인 패턴. 한빛미디어. <file_sep>/TemplateMethodPattern/src/before/HyundaiMotor.java package before; public class HyundaiMotor extends Motor { public HyundaiMotor(Door door) { super(door); } private void moveHyundaiMotor(Direction direction) { System.out.println("HyundaiMotor 구동시킴"); } public void move(Direction direction) { MotorStatus motorStatus = getMotorStatus(); if(motorStatus == MotorStatus.MOVING) return; DoorStatus doorStatus = door.getDoorStatus(); if(doorStatus == DoorStatus.OPENED) door.close(); moveHyundaiMotor(direction); setMotorStatus(MotorStatus.MOVING); } } <file_sep>/DesignPattern/chapter5/ex4/VerticalMoveStrategy.java package ex4; public class VerticalMoveStrategy extends DirectionStrategy{ @Override public void move(Ball ball) { ball.setIntervals(0, Ball.INTERVAL); while(true) { ball.setY(ball.getY() + ball.getyInterval()); if((ball.getY()<0 && ball.getyInterval()<0) || (ball.getY() + Ball.SIZE > BallFrame.HEIGHT - 40 && ball.getyInterval()>0)) { ball.setIntervals(0, -ball.getyInterval()); } try { Thread.sleep(30); } catch (InterruptedException e) { e.printStackTrace(); } } } } <file_sep>/DecoratorPattern/src/ex2/ESCDecorator.java package ex2; public class ESCDecorator extends CarOptionDecorator{ private int escPrice; public ESCDecorator(CarComponent decoratedCar, int escPrice) { super(decoratedCar); this.escPrice = escPrice; } @Override public int getPrice() { int price = super.getPrice(); return escPrice + price; } @Override public String getCarInfo() { String carInfo = super.getCarInfo(); return carInfo + " with Electronic Stability Control"; } } <file_sep>/CompositePattern/CompositePattern/before/Computer.java package before; public class Computer { private Body body; private KeyBoard keyBoard; private Monitor monitor; public void addBody(Body body) { this.body = body; } public void addKeyBoard(KeyBoard keyBoard) { this.keyBoard = keyBoard; } public void addMonitor(Monitor monitor) { this.monitor = monitor; } public int getPrice() { int bodyPrice = body.getPrice(); int keyBoardPrice = keyBoard.getPrice(); int monitorPrice = monitor.getPrice(); return bodyPrice + keyBoardPrice + monitorPrice; } public int getPower() { int bodyPower = body.getPower(); int keyBoardPower = keyBoard.getPower(); int monitorPower = monitor.getPower(); return bodyPower + keyBoardPower + monitorPower; } } <file_sep>/AbstractFactoryPattern/Ex/map/TestMap.java package map; public class TestMap extends Map{ } <file_sep>/StatePattern/src/ex5/EnoughMoneyState.java package ex5; public class EnoughMoneyState implements State{ private VendingMachine machine; public EnoughMoneyState(VendingMachine machine) { this.machine = machine; } @Override public void insertMoney(int money) { machine.getMoneyBox().insert(money); System.out.println(money + "원을 넣었습니다."); System.out.println("현재 금액은 " + machine.getMoneyBox().getMoney() + "원입니다."); } @Override public void pushButton(int price) { machine.getDrinking().dispense(); machine.getMoneyBox().dispense(price); System.out.println("음료수가 나왔습니다."); if(machine.getDrinking().getStock()==0) { machine.setState(machine.getSoldOutState()); } else if(machine.getMoneyBox().getMoney() < machine.getDrinking().getPrice()) { machine.setState(machine.getNoEnoughMoneyState()); } else if(machine.getMoneyBox().getMoney()==0) { machine.setState(machine.getNoMoneyState()); } } @Override public void returnMoney() { int tmp = machine.getMoneyBox().returnMoney(); System.out.println(tmp + "원이 반환되었습니다."); machine.setState(machine.getNoMoneyState()); } } <file_sep>/DecoratorPattern/src/ex2/Client.java package ex2; public class Client { public static void main(String[] args) { CarComponent car = new BasicCar(1000); for(String decoratorName : args) { if(decoratorName.equalsIgnoreCase("AirBag")) car = new AirBagDecorator(car, 100); if(decoratorName.equalsIgnoreCase("ESC")) car = new ESCDecorator(car, 50); if(decoratorName.equalsIgnoreCase("Navi")) car = new NaviDecorator(car, 30); if(decoratorName.equalsIgnoreCase("SCC")) car = new SCCDecorator(car, 70); } System.out.println(car.getPrice()); System.out.println(car.getCarInfo()); } } <file_sep>/DecoratorPattern/README.md ### 데커레이터 패턴 * 데커레이터 패턴은 기본 기능에 추가할 수 있는 기능의 종류가 많은 경우에 각 추가 기능을 Decorator 클래스로 정의한 후 필요한 Decorator 객체를 조합함으로써 추가 기능의 조합을 설계하는 방식이다. * 데커레이터 패턴은 기본 기능에 추가할 수 있는 많은 종류의 부가 기능에서 파생되는 다양한 조합을 동적으로 구현할 수 있는 패턴이다. * 예를 들어 기본 도로 표시 기능에 차선 표시, 교통량 표시, 교차로 표시, 단속 카메라 표시의 4가지 추가 기능이 있을 때 추가 기능의 모든 조합은 15가지가 된다. 데커레이터 패턴을 사용하면 개별 추가 기능에 해당하는 Decorator 클래스 4개만 구현하고 개별 추가 기능을 객체의 형태로 조합함으로써 추가 기능의 조합을 구현할 수 있다. #### before (데커레이터 패턴 적용 X) ![before](https://user-images.githubusercontent.com/28583661/72429964-71334000-37d4-11ea-8856-25a1e7663848.PNG) #### after (데커레이터 패턴 적용 O) ![after](https://user-images.githubusercontent.com/28583661/72429966-71cbd680-37d4-11ea-8954-d326f035ae1a.PNG)<file_sep>/CommandPattern/README.md ### 커맨드 패턴 * 커맨드 패턴은 이벤트가 발생했을 때 실행될 기능이 다양하면서도 변경이 필요한 경우에 이벤트를 발생시키는 클래스를 변경하지 않고 재사용하고자 할 때 유용하다. * 커맨드 패턴은 실행될 기능을 캡슐화함으로써 기능의 실행을 요구하는 호출자(Invoker) 클래스와 실제 기능을 실행하는 수신자(Receiver) 클래스 사이의 의존성을 제거한다. 따라서 실행될 기능의 변경에도 호출자 클래스를 수정 없이 그대로 사용할 수 있도록 해준다. #### before (커맨드 패턴 적용 X) ![before](https://user-images.githubusercontent.com/28583661/72197402-24620900-3464-11ea-95dc-9c5b9955f42a.PNG) #### after (커맨드 패턴 적용 O) ![after](https://user-images.githubusercontent.com/28583661/72197556-e6fe7b00-3465-11ea-8a38-8ccdd49eba17.PNG)<file_sep>/CommandPattern/src/code8_4/AlarmOnCommand.java package code8_4; public class AlarmOnCommand implements Command{ private Alarm alarm; public AlarmOnCommand(Alarm alarm) { this.alarm = alarm; } @Override public void execute() { alarm.start(); } } <file_sep>/StrategyPattern/README.md ### 스트래티지 패턴 * 스트래티지 패턴은 전략을 쉽게 바꿀 수 있도록 해주는 디자인 패턴이다. * 스트래티지 패턴은 같은 문제를 해결하는 여러 알고리즘(방식)이 클래스별로 캡슐화되어 있고 이들이 필요할 때 교체될 수 있도록 함으로써 동일한 문제를 다른 알고리즘으로 해결할 수 있게 하는 디자인 패턴이다. #### before (스트래티지 패턴 적용 X) ![before](https://user-images.githubusercontent.com/28583661/71764332-f3e11300-2f29-11ea-9f94-24e6d5ca8bd5.PNG) #### after (스트래티지 패턴 적용 O) ![after](https://user-images.githubusercontent.com/28583661/71764334-f479a980-2f29-11ea-86dc-56c05909f2c6.PNG)<file_sep>/CommandPattern/src/ex1/TwoButtonController.java package ex1; public class TwoButtonController { private TV tv; public TwoButtonController(TV tv) { this.tv = tv; } public void button1Pressed() { tv.power(); } public void button2Pressed() { tv.mute(); } } <file_sep>/CompoundPattern/src/mvc/DJTestDrive.java package mvc; import mvc.controller.BeatController; import mvc.controller.ControllerInterface; import mvc.model.BeatModel; import mvc.model.BeatModelInterface; public class DJTestDrive { public static void main (String[] args) { BeatModelInterface model = new BeatModel(); ControllerInterface controller = new BeatController(model); } } <file_sep>/CompoundPattern/src/duck_example/composite/Flock.java package duck_example.composite; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import duck_example.duck.Quackable; import duck_example.observer.Observer; public class Flock implements Quackable { List<Quackable> quackers = new ArrayList<>(); public void add(Quackable quacker) { this.quackers.add(quacker); } @Override public void quack() { Iterator<Quackable> iterator = quackers.iterator(); while(iterator.hasNext()) { Quackable quacker = iterator.next(); quacker.quack(); } notifyObservers(); } @Override public void registerObserver(Observer observer) { Iterator<Quackable> iterator = quackers.iterator(); while(iterator.hasNext()) { Quackable quacker = iterator.next(); quacker.registerObserver(observer); } } @Override public void notifyObservers() { //nothing } @Override public String toString() { return "Flock"; } } <file_sep>/DecoratorPattern/src/ex1/ExternalDecorator.java package ex1; public class ExternalDecorator extends ContentDecorator{ public ExternalDecorator(EmailContent decoratedContent) { super(decoratedContent); } @Override public String getContent() { String content = super.getContent(); String externalContent = addDisclaimer(content); return externalContent; } private String addDisclaimer(String content) { return content + " Company Disclaimer"; } } <file_sep>/FactoryMethodPattern/src/ex2/Car.java package ex2; public class Car { private int speed; private CarState normalState; private CarState limpState; private CarState curState; public Car() { normalState = CarStateFactory.getState(CarStateID.NORMAL, this); limpState = CarStateFactory.getState(CarStateID.LIMP_MODE, this); curState = normalState; } public CarState getLimpMode() { return limpState; } public void setState(CarState state) { curState = state; } public void speedDown(int targetSpeed) { curState.speedDown(targetSpeed); } public void engineFailedDetected() { curState.engineFailedDetected(); } public void speedUp(int targetSpeed) { curState.speedUp(targetSpeed); } public void engineRepaired() { curState.engineRepaired(); } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public CarState getNormalMode() { return normalState; } } <file_sep>/AbstractFactoryPattern/ExampleOfAbstractFactory/client/Client.java package client; import direction.Direction; import door.Door; import factory.ElevatorFactory; import factory.HyundaiElevatorFactory; import factory.LGElevatorFactory; import motor.Motor; public class Client { public static void main(String[] args) { ElevatorFactory factory = null; String vendorName = "Hyundai"; if(vendorName.equalsIgnoreCase("LG")) factory = new LGElevatorFactory(); else factory = new HyundaiElevatorFactory(); Door door = factory.createDoor(); Motor motor = factory.createMotor(); motor.setDoor(door); door.open(); motor.move(Direction.UP); } } <file_sep>/DesignPattern/src/chapter2/ArrayListStack.java package chapter2; import java.util.ArrayList; public class ArrayListStack { private ArrayList<Integer> items; private int stackSize; public ArrayListStack(int stackSize) { items = new ArrayList<Integer>(stackSize); this.stackSize = stackSize; } public boolean isEmpty() { return items.isEmpty(); } public boolean isFull() { return (items.size() >= (this.stackSize)); } public void push(int item) { if(isFull()) { System.out.println("Inserting fail!"); } else { items.add(new Integer(item)); System.out.println("Inserted Item : " + item); } } public int pop() { if(isEmpty()) { System.out.println("Deleting fail!"); return -1; } else { return items.remove(items.size()-1); } } public int peek() { if(isEmpty()) { System.out.println("Peeking fail!"); return -1; } else { return items.get(items.size()-1); } } public static void main(String[] args) { ArrayListStack st = new ArrayListStack(10); st.push(20); System.out.println(st.peek()); } } <file_sep>/CompositePattern/README.md ### 컴포지트 패턴 * 컴퍼지트 패턴은 전체-부분 관계를 갖는 객체들 사이의 관계를 정의할 때 유용하다. * 클라이언트는 전체와 부분을 구분하지 않고 동일한 인터페이스를 사용할 수 있다. #### before (컴포지트 패턴 적용 X) ![before](https://user-images.githubusercontent.com/28583661/73041815-3307e180-3ea2-11ea-988b-24bc1def9937.PNG) #### after (컴포지트 패턴 적용 O) ![after](https://user-images.githubusercontent.com/28583661/73041821-34d1a500-3ea2-11ea-936a-10790af04795.PNG)
105e92a8a2d608eb46521281ed97ee5befc03d66
[ "Markdown", "Java" ]
61
Markdown
hjm7091/Design_Pattern
a2a51f9d3d41efb151d9edec4f7917c430bb1ff1
ceccd331363d6d4e83fd87e08e642f034631af30
refs/heads/master
<repo_name>datawizzards-za/myp<file_sep>/index.php <!DOCTYPE html> <html lang="en"> <head> <meta charset=utf-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>MYP</title> <!-- Load css styles --> <link rel="stylesheet" type="text/css" href="css/bootstrap.css" /> <link rel="stylesheet" type="text/css" href="css/bootstrap-responsive.css" /> <link rel="stylesheet" type="text/css" href="css/style.css" /> <link rel="stylesheet" type="text/css" href="css/pluton.css" /> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="css/pluton-ie7.css" /> <![endif]--> <link rel="stylesheet" type="text/css" href="css/jquery.cslider.css" /> <link rel="stylesheet" type="text/css" href="css/jquery.bxslider.css" /> <link rel="stylesheet" type="text/css" href="css/animate.css" /> <!-- Fav and touch icons --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="images/ico/apple-touch-icon-144.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="images/ico/apple-touch-icon-114.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="images/apple-touch-icon-72.png"> <link rel="apple-touch-icon-precomposed" href="images/ico/apple-touch-icon-57.png"> <link rel="shortcut icon" href="img/logo_trans.png"> </head> <body> <div class="navbar"> <div class="navbar-inner"> <div class="container"> <a href="./" class="brand"> <img src="img/logo_bg.jpg" width="60" height="50" alt="Logo" /> <!-- This is website logo --> </a> <!-- Navigation button, visible on small resolution --> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <i class="icon-menu"></i> </button> <!-- Main navigation --> <div class="nav-collapse collapse pull-right"> <ul class="nav" id="top-navigation"> <li class="active"><a href="#home">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#partners">Partners</a></li> <li><a href="#projects">Projects</a></li> <li><a href="#clients">Testimonials</a></li> <li><a href="#donors">Donors</a></li> <li><a href="#contact">Contact</a></li> </ul> </div> <!-- End main navigation --> </div> </div> </div> <!-- Start home section --> <div id="home"> <!-- Start cSlider --> <div id="da-slider" class="da-slider"> <div class="triangle"></div> <!-- mask elemet use for masking background image --> <div class="mask"></div> <!-- All slides centred in container element --> <div class="container"> <!-- Start first slide --> <div class="da-slide"> <h2 class="fittext2">Welcome to MYP</h2> <h4>When Activism meets community development.</h4> <p> MYP is a registered NPO focusing on community development. <br /> At MYP, we believe that education is a liberator, as such, we prioritise education as a starting point for all of our community development activities. We seek all the help possible, please continue reading. </p> <a href="#about" class="da-link button">Read more</a> <div class="da-img"> <img src="img/logo_trans.png" alt="image01" width="320"> </div> </div> <!-- End first slide --> <!-- Start second slide --> <div class="da-slide"> <h2>MYP Annual Career Expo</h2> <h4>Because education is a liberator.</h4> <p> We have been hosting a career expo every year since 2013.<br /> The event is aimed at raising awareness among high school learners, creating a culture of knowledge sharing and bridging the gap of access to information. </p> <a href="#projects" class="da-link button">Read more</a> <div class="da-img"> <img src="images/edu.png" width="320" alt="image02"> </div> </div> <!-- End second slide --> <!-- Start third slide <div class="da-slide"> <h2>Revolution</h2> <h4>Customizable</h4> <p>A small river named Duden flows by their place and supplies it with the necessary regelialia. It is a paradisematic country, in which roasted parts of sentences fly into your mouth.</p> <a href="#portfolio" class="da-link button">Read more</a> <div class="da-img"> <img src="images/Slider03.png" width="320" alt="image03"> </div> </div> <!-- Start third slide --> <!-- Start cSlide navigation arrows --> <div class="da-arrows"> <span class="da-arrows-prev"></span> <span class="da-arrows-next"></span> </div> <!-- End cSlide navigation arrows --> </div> </div> </div> <!-- End home section --> <!-- About us section start --> <div class="section primary-section" id="about"> <div class="triangle"></div> <div class="container"> <div class="title"> <h1>Masemola Young Professionals</h1> <h3>Our Village. Our Pride.</h3> <p> Striving for a united, literate community driven by inclusive academic and economic prosperity. </p> </div> <div class="row-fluid"> <div class="span4"> <div class="centered service"> <h3>Values</h3> <p>Effective and Sustainable Community Development. </p> <p>Championing the principles of societal justice, and empowerment of the youth, women, and children. </p> <p>Resolving conflicts and inspiring peace among residents. </p> <p>Enable an environment of dialogue and activism among the youth.</p> </div> </div> <div class="span4"> <div class="centered service"> <h3>Mission</h3> <p>Improve communication and consultative measures.</p> <p>Improve health, safety and security standards.</p> <p>Provide effective education and skills development programmes. </p> <p>Inspire positive social change through information, advocacy and service delivery.</p> </div> </div> <div class="span4"> <div class="centered service"> <h3>Objectives</h3> <p>Identify and confront problems facing the community at large. </p> <p>Identify and pursue economic development opportunities. </p> <p>Promote altruistic values, selflessness, public interest, activism and collective decision making. </p> <p>Improve service delivery and quality of life amongst residents.</p> </div> </div> </div> <hr /> <div class="row-fluid team"> <div class="span6" id="first-person"> <div class="thumbnail"> <img src="images/exco/Ngwato.jpg" alt="<NAME>"> <h3><NAME></h3> <ul class="social"> <li> <a target="_blank" href="https://www.facebook.com/Makakaile"> <span class="icon-facebook-circled"></span> </a> </li> <li> <a target="_blank" href="https://twitter.com/Makakaile"> <span class="icon-twitter-circled"></span> </a> </li> <li> <a target="_blank" href="https://www.linkedin.com/in/marule-mahlase-8bb48b14/"> <span class="icon-linkedin-circled"></span> </a> </li> </ul> <div class="mask"> <h2>Chairperson</h2> <p> Marule is an admitted attorney of the high court. He is an experienced legal advisor with expertise in litigation and legal compliance. A highly dedicated community servant with a passion for mentoring of protégées. </p> </div> </div> </div> <div class="span6" id="second-person"> <div class="thumbnail"> <img src="images/exco/Ntshirile.jpg" alt="<NAME>"> <h3><NAME></h3> <ul class="social"> <li> <a target="_blank" href="https://www.facebook.com/ntshirile.bapela"> <span class="icon-facebook-circled"></span> </a> </li> <li> <a target="_blank" href="#"> <span class="icon-twitter-circled"></span> </a> </li> <li> <a target="_blank" href="https://www.linkedin.com/in/ntshirile-bapela-79672817/"> <span class="icon-linkedin-circled"></span> </a> </li> </ul> <div class="mask"> <h2>Deputy Chairperson</h2> <p> Ntshirile is a Compliance Manager in the financial services industry with a background in finance. She's passionate about people and community development </p> </div> </div> </div> <div class="span12"> <hr /> </div> <div class="span3" id="3-person"> <div class="thumbnail"> <img src="images/exco/Phaphedi.jpg" alt="<NAME>"> <h3><NAME></h3> <ul class="social"> <li> <a target="_blank" href="#"> <span class="icon-facebook-circled"></span> </a> </li> <li> <a target="_blank" href="https://twitter.com/phaphedib"> <span class="icon-twitter-circled"></span> </a> </li> <li> <a target="_blank" href="https://www.linkedin.com/in/phaphedi-bapela-4199b128/"> <span class="icon-linkedin-circled"></span> </a> </li> </ul> <div class="mask"> <h2>General Secretary</h2> <p> Phaphedi holds a baccalaureus technologiae in HR. An experienced HR professional with more than 15 years in the state owned enterprises. He is one of the founding members of MYP. </p> </div> </div> </div> <div class="span3" id="4-person"> <div class="thumbnail"> <img src="images/exco/Ferdinand.jpg" alt="<NAME>"> <h3><NAME></h3> <ul class="social"> <li> <a target="_blank" href="https://www.facebook.com/ferdinand.mokete"> <span class="icon-facebook-circled"></span> </a> </li> <li> <a target="_blank" href="#"> <span class="icon-twitter-circled"></span> </a> </li> <li> <a target="_blank" href="https://www.linkedin.com/in/ferdinand-mokete-5a543530/"> <span class="icon-linkedin-circled"></span> </a> </li> </ul> <div class="mask"> <h2>Treasury</h2> <p> Ferdinand is a charted accountant by profession with a strong passion of teaching. He is a trusted professional advisor with intense involvement in professional development of others. </p> </div> </div> </div> <div class="span3" id="5-person"> <div class="thumbnail"> <img src="images/exco/JT.jpg" alt="<NAME>"> <h3><NAME></h3> <ul class="social"> <li> <a target="_blank" href="https://www.facebook.com/jafta.tshebesebe"> <span class="icon-facebook-circled"></span> </a> </li> <li> <a target="_blank" href="#"> <span class="icon-twitter-circled"></span> </a> </li> <li> <a target="_blank" href="#/"> <span class="icon-linkedin-circled"></span> </a> </li> </ul> <div class="mask"> <h2>Fundraising</h2> <p> Jafta is an accountant by profession. He believes communities can only move forward if they embrace passionate minds and learn from each other. </p> </div> </div> </div> <div class="span3" id="6-person"> <div class="thumbnail"> <img src="images/exco/Mabu.JPG" alt="<NAME>"> <h3><NAME></h3> <ul class="social"> <li> <a target="_blank" href="https://www.facebook.com/mabumanaileng"> <span class="icon-facebook-circled"></span> </a> </li> <li> <a target="_blank" href="https://twitter.com/thisMabu"> <span class="icon-twitter-circled"></span> </a> </li> <li> <a target="_blank" href="https://www.linkedin.com/in/manailengmj/"> <span class="icon-linkedin-circled"></span> </a> </li> </ul> <div class="mask"> <h2>Public Relations</h2> <p> Mabu holds a masters degree in computer science. He is passionate about the role of technology and education for large scale social trasformation. "When I grow up, I want to be like <NAME>." </p> </div> </div> </div> </div> <hr /> <div class="row-fluid"> <div class="span12 fadeInDown animated"> <div class="highlighted-box center"> <h1>Join MYP</h1> <p> MYP membership is open to all community members; University students, primary and high school learners, unemployed youth, enterprenuers and trianed professionals. Moreover, we are constantly looking for volunteers to aid us in our endeavors. Should you be interested, please click the button below. </p> <a href="#contact" class="button">Join Us</a> </div> </div> </div> </div> </div> <!-- About us section end --> <div id="partners" class="section secondary-section fadeInDown animated"> <div class="triangle"></div> <div class="container centered"> <div class="title"> <h1>Our Partners</h1> </div> <div class="sub-section"> <div class=" clearfix"> <div> <h4> "If You Want To Go Fast, Go Alone. If You Want To Go Far, Go Together" </h4> </div> <ul class="client-nav pull-right" hidden> <li id="partner-prev"></li> <li id="partner-next"></li> </ul> </div> <br /> <ul class="row client-slider" id="partner-slider"> <li> <a href="#"> <img src="images/partners/BBMDO.png" alt="BBMDO"> </a> </li> <li> <a target="_blank" href="https://masemolafm.co.za/"> <img src="images/partners/mascomlogo.png" alt="Mascom FM"> </a> </li> <li> <a href="#"> <img src="images/partners/regaogetswe_networks.jpg" alt="Regaogetswe Networks"> </a> </li> </ul> </div> </div> </div> <div class="section secondary-section"> <div class="container centered"> <a href="#contact" class="button">Become a Partner</a> </div> </div> <!-- Portfolio section start --> <div class="section secondary-section " id="projects"> <div class="triangle"></div> <div class="container"> <div class=" title"> <h1>Have You Seen Our Causes?</h1> <p> MYP hosts annual events focusing on causes that are strategically selected based on the organizations priorities and availability of resources. Below are some of the causes we have pursued. </p> </div> <ul class="nav nav-pills"> <li class="filter" data-filter="all"> <a href="#noAction">All</a> </li> <li class="filter" data-filter="expo"> <a href="#noAction">Annual Career Expo</a> </li> <li class="filter" data-filter="mandela-day"> <a href="#noAction">Mandela Day</a> </li> <li class="filter" data-filter="sports"> <a href="#noAction">MYP Sports</a> </li> <li class="filter" data-filter="dispute"> <a href="#noAction">Special Projects</a> </li> </ul> <!-- Start details for portfolio project 1 --> <div id="single-project"> <div id="expo2017" class="toggleDiv row-fluid single-project"> <div class="span6"> <img src="images/projects/proj.png" alt="Expo 2017" /> </div> <div class="span6"> <div class="project-description"> <div class="project-title clearfix"> <h3>Career Expo 2017</h3> <span class="show_hide close"> <i class="icon-cancel"></i> </span> </div> <div class="project-info"> <div> <span>Location</span>Masemola High School, Ga-Masemola</div> <div> <span>Date</span>27 May 2017</div> <div> <span>Partners</span>BBMDO, MasCom FM, Regaogetswe Networks</div> <div> <span>Link</span> <a target="_blank" class="fg" href="https://goo.gl/photos/uj8Rak9ndG4bwMDC8"> Career Expo 2017 Album</a> </div> </div> <p> Your Future is in Your Hands. </p> </div> </div> </div> <!-- End details for portfolio project 1 --> <!-- Start details for portfolio project 2 --> <div id="expo2016" class="toggleDiv row-fluid single-project"> <div class="span6"> <img src="images/projects/proj.png" alt="Expo 2016"> </div> <div class="span6"> <div class="project-description"> <div class="project-title clearfix"> <h3>Career Expo 2016</h3> <span class="show_hide close"> <i class="icon-cancel"></i> </span> </div> <div class="project-info"> <div> <span>Location</span>Masemola High School, Ga-Masemola</div> <div> <span>Date</span>8 May 2016</div> <div> <span>Partners</span>BBMDO, MasCom FM</div> <div> <span>Link</span> <a target="_blank" class="fg" href="https://goo.gl/photos/w52u3keD7TGoYL3K6"> Expo 2016 Album</a> </div> </div> <p> Yes, you can! </p> </div> </div> </div> <!-- End details for portfolio project 2 --> <!-- Start details for portfolio project 3 --> <div id="expo2015" class="toggleDiv row-fluid single-project"> <div class="span6"> <img src="images/projects/proj.png" alt="Expo 2015"> </div> <div class="span6"> <div class="project-description"> <div class="project-title clearfix"> <h3>Career Expo 2015</h3> <span class="show_hide close"> <i class="icon-cancel"></i> </span> </div> <div class="project-info"> <div> <span>Location</span>Masemola High School, Ga-Masemola</div> <div> <span>Date</span>09 May 2015</div> <div> <span>Partners</span>BBMDO, MasCom FM</div> <div> <span>Link</span> <a target="_blank" class="fg" href="https://goo.gl/photos/w52u3keD7TGoYL3K6"> Expo 2015 Album</a> </div> </div> <p> Summary. </p> </div> </div> </div> <!-- End details for portfolio project 3 --> <!-- Start details for portfolio project 4 --> <div id="mandela2016" class="toggleDiv row-fluid single-project"> <div class="span6"> <img src="images/projects/proj.png" alt="Mandela Day 2015"> </div> <div class="span6"> <div class="project-description"> <div class="project-title clearfix"> <h3>Mandela Day 2015</h3> <span class="show_hide close"> <i class="icon-cancel"></i> </span> </div> <div class="project-info"> <div> <span>Location</span>Masemola High School, Ga-Masemola</div> <div> <span>Date</span>18 July 2015</div> <div> <span>Partners</span>BBMDO, MasCom FM</div> <div> <span>Link</span> <a target="_blank" class="fg" href="https://photos.app.goo.gl/8UOnpDbHGwFYY2dk1"> Mandela Day 2015 Album </a> </div> </div> <p> The purpose of this project was to donate learning tools, toys and other items meant for enhancing early childhood learning. We further aimed to improve physical conditions of the centre by painting racks and walls. The donations remain property of the school used by all children forming part of the centre. We believe that endeavours like this contribute to the ultimate goal of improving the quality of education in our villages. </p> </div> </div> </div> <!-- End details for portfolio project 4 --> <!-- Start details for portfolio project 5 --> <div id="dispute2014" class="toggleDiv row-fluid single-project"> <div class="span6"> <img src="images/projects/proj.png" alt="Mascom FM"> </div> <div class="span6"> <div class="project-description"> <div class="project-title clearfix"> <h3>Board Dispute Resolution (Mediation)</h3> <span class="show_hide close"> <i class="icon-cancel"></i> </span> </div> <div class="project-info"> <div> <span>Affected Parties</span>Mascom FM</div> <div> <span>Date</span>2014</div> <div> <span>Partners</span>BBMDO, MasCom FM</div> <div> <span>Link</span> <a target="_blank" class="fg" href="#"> Album not available. </a> </div> </div> <p> Summary </p> </div> </div> </div> <!-- End details for portfolio project 5 --> <!-- Start details for portfolio project 6 --> <div id="dispute2013" class="toggleDiv row-fluid single-project"> <div class="span6"> <img src="images/projects/proj.png" alt="Land Dispute"> </div> <div class="span6"> <div class="project-description"> <div class="project-title clearfix"> <h3>Formal Advice on Land Dispute</h3> <span class="show_hide close"> <i class="icon-cancel"></i> </span> </div> <div class="project-info"> <div> <span>Affected Parties</span>Masemola Royal Council</div> <div> <span>Date</span>2013</div> <div> <span>Partners</span>BBMDO, MasCom FM</div> <div> <span>Link</span> <a target="_blank" class="fg" href="#"> None </a> </div> </div> <p> Summary </p> </div> </div> </div> <!-- End details for portfolio project 6 --> <!-- Start details for portfolio project 7 --> <div id="soccer2016" class="toggleDiv row-fluid single-project"> <div class="span6"> <img src="images/projects/proj.png" alt="Sports 2016"> </div> <div class="span6"> <div class="project-description"> <div class="project-title clearfix"> <h3>MYP Soccer Tournament 2016</h3> <span class="show_hide close"> <i class="icon-cancel"></i> </span> </div> <div class="project-info"> <div> <span>Location</span>Mphane</div> <div> <span>Date</span>25-26th March 2016</div> <div> <span>Partners</span>BBMDO, MasCom FM</div> <div> <span>Link</span> <a target="_blank" class="fg" href="#"> Album not available. </a> </div> </div> <p> Summary. </p> </div> </div> </div> <!-- Start details for portfolio project 6 --> <div id="MYP_Deloitte" class="toggleDiv row-fluid single-project"> <div class="span6"> <img src="images/projects/proj.png" alt="MYP-Deloitte"> </div> <div class="span6"> <div class="project-description"> <div class="project-title clearfix"> <h3>MYP-Deloitte Schools Initiative Programme</h3> <span class="show_hide close"> <i class="icon-cancel"></i> </span> </div> <div class="project-info"> <div> <span>Location</span>Ga-Masemola</div> <div> <span>Date</span>20 March 2015</div> <div> <span>Partners</span>Deloitte</div> <div> <span>Link</span> <a target="_blank" class="fg" href="https://photos.app.goo.gl/LkyZOXpgOPdD27zf2"> Photo Album </a> </div> </div> <p> Having noted that many of the learners in our local schools are struggling to commit their energy and discipline towards their studies, Deloitte conducted an assessment and found that this is largely due to a limited vision of the possibilities after matric. Deloitte developed a strategic approach to combat this problem. Entitled Vision Sessions, this initiative was aimed at engaging learners with the support and consent of the schools governing body to inspire and inform the learners of opportunities in the South African environment and the potential inside themselves. We also share personal success stories of our employees that might have faced adverse difficulties and challenges on their journey to become successful young professionals. </p> </div> </div> </div> <ul id="portfolio-grid" class="thumbnails row"> <li class="span4 mix expo"> <div class="thumbnail"> <img src="images/projects/proj.png" alt="Expo 2017"> <a href="#single-project" class="more show_hide" rel="#expo2017"> <i class="icon-plus"></i> </a> <h3>MYP Career Expo 2017</h3> <div class="mask"></div> </div> </li> <li class="span4 mix mandela-day"> <div class="thumbnail"> <img src="images/projects/proj.png" alt="Mandela Day 2016"> <a href="#single-project" class="show_hide more" rel="#mandela2016"> <i class="icon-plus"></i> </a> <h3>Mandela Day 2015</h3> <div class="mask"></div> </div> </li> <li class="span4 mix sports"> <div class="thumbnail"> <img src="images/projects/proj.png" alt="project 3"> <a href="#single-project" class="more show_hide" rel="#soccer2016"> <i class="icon-plus"></i> </a> <h3>MYP Soccer Tournament 2016</h3> <div class="mask"></div> </div> </li> <li class="span4 mix expo"> <div class="thumbnail"> <img src="images/projects/proj.png" alt="Expo 2016"> <a href="#single-project" class="show_hide more" rel="#expo2016"> <i class="icon-plus"></i> </a> <h3>MYP Career Expo 2016</h3> <div class="mask"></div> </div> </li> <li class="span4 mix dispute"> <div class="thumbnail"> <img src="images/projects/proj.png" alt="Mediation"> <a href="#single-project" class="show_hide more" rel="#dispute2014"> <i class="icon-plus"></i> </a> <h3>Board Dispute Resolution</h3> <div class="mask"></div> </div> </li> <li class="span4 mix expo"> <div class="thumbnail"> <img src="images/projects/proj.png" alt="Expo 2015" /> <a href="#single-project" class="show_hide more" rel="#expo2015"> <i class="icon-plus"></i> </a> <h3>MYP Career Expo 2015</h3> <div class="mask"></div> </div> </li> <li class="span4 mix dispute"> <div class="thumbnail"> <img src="images/projects/proj.png" alt="Land Dispute"> <a href="#single-project" class="show_hide more" rel="#dispute2013"> <i class="icon-plus"></i> </a> <h3>Land Dispute Resolution</h3> <div class="mask"></div> </div> </li> <li class="span4 mix dispute"> <div class="thumbnail"> <img src="images/projects/proj.png" alt="MYP-Deloitte"> <a href="#single-project" class="show_hide more" rel="#MYP_Deloitte"> <i class="icon-plus"></i> </a> <h3>MYP-Deloitte Schools Initiative</h3> <div class="mask"></div> </div> </li> </ul> </div> </div> </div> <!-- Portfolio section end --> <!-- Client section start --> <!-- Client section start --> <div id="clients"> <div class="section primary-section"> <div class="triangle"></div> <div class="container"> <div class="title"> <h1>What People Say</h1> <p> We value feedback, below are some of the things people say about our endeavors. </p> </div> <div class="row"> <div class="span3"> <div class="testimonial"> <p> "A great opportunity to inspire young people." </p> <div class="whopic"> <div class="arrow"></div> <strong> <NAME>, Multotec <small> <i>on Career Expo 2016</i> </small> </strong> </div> </div> </div> <div class="span3"> <div class="testimonial"> <p> "Good job, one day we will join you and build our future." </p> <div class="whopic"> <div class="arrow"></div> <strong> <NAME>, Learner <small> <i>on Career Expo 2017</i> </small> </strong> </div> </div> </div> <div class="span3"> <div class="testimonial"> <p> "I want to thank you guys for wat u done to us today." </p> <div class="whopic"> <div class="arrow"></div> <strong> <NAME>, Learner <small> <i>on Career Expo 2017</i> </small> </strong> </div> </div> </div> <div class="span3"> <div class="testimonial"> <p> "Great work guys,keep it up." </p> <div class="whopic"> <div class="arrow"></div> <strong> <NAME>, Resident. <small> <i>on Career Expo</i> </small> </strong> </div> </div> </div> </div> <p class="testimonial-text"> <a href="#" class="button">Read More</a> <a href="#" class="button">Write a review</a> </p> </div> </div> </div> <div id="donors" class="section secondary-section fadeInDown animated"> <div class="triangle"></div> <div class="container centered"> <div class="title"> <h1>Our Donors</h1> </div> <div class="sub-section"> <div class=" clearfix"> <div> <!-- class="pull-left"> --> <h4>MYP would never accomplish anything without the support of our donors. Below are a few who made our endeavors possible.</h4> </div> <!-- <ul class="client-nav pull-right" hidden> <li id="client-prev"></li> <li id="client-next"></li> </ul> --> </div> <ul class="row client-slider" id="clint-slider" hidden> <li> <a target="_blank" href="https://www.multotec.com/"> <!-- <img src="images/donors/multotec.jpg" alt="Multotec"> --> </a> </li> <li> <a href=""> <!-- <img src="images/donors/client.png" alt="client logo 2"> --> </a> </li> <li> <a href=""> <!-- <img src="images/donors/client.png" alt="client logo 3"> --> </a> </li> </ul> </div> </div> </div> <div class="section secondary-section"> <div class="container centered fadeInDown animated"> <p class="large-text "> MYP is a Non-Profitable Organisation that solely relies on donations, sponsors and community contributions. All financial and/or material resources are most welcome and heartily appreciated. </p> <a href="#contact" class="button">Become a Donor</a> </div> </div> <!-- Newsletter section start <div class="section third-section" hidden> <div class="triangle"></div> <div class="container newsletter"> <div class="sub-section"> <div class="title clearfix"> <div class="pull-left"> <h3>Newsletter</h3> </div> </div> </div> <div id="success-subscribe" class="alert alert-success invisible"> <strong>Well done!</strong>You successfully subscribet to our newsletter.</div> <div class="row-fluid"> <div class="span5"> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> </div> <div class="span7"> <form class="inline-form"> <input type="email" name="email" id="nlmail" class="span8" placeholder="Enter your email" required /> <button id="subscribe" class="button button-sp">Subscribe</button> </form> <div id="err-subscribe" class="error centered">Please provide valid email address.</div> </div> </div> </div> </div> <!-- Newsletter section end --> <!-- Contact section start --> <div id="contact" class="contact"> <div class="section secondary-section"> <div class="triangle"></div> <div class="container"> <div class="title"> <h1>Contact Us</h1> <p> We believe in engagement, we welcome all questions, suggestions and comments. Please feel free to get in touch. </p> </div> </div> <div class="map-wrapper"> <div class="map-canvas" id="map-canvas">Loading map...</div> <div class="container"> <div class="row-fluid"> <div class="span4 contact-form centered"> <h3 id="formHeader" class="animated fadeIn">Send us an email</h3> <div id="successSend" class="alert alert-success invisible"> <strong>All good!</strong> We will revert soonest.</div> <div id="errorSend" class="alert alert-error invisible">There was an error.</div> <form id="contact-form" action="php/mail.php"> <div class="control-group"> <div class="controls"> <input class="span12" type="text" id="name" name="name" placeholder="* Your name..." /> <div class="error left-align" id="err-name">Please enter your name.</div> </div> </div> <div class="control-group"> <div class="controls"> <input class="span12" type="email" name="email" id="email" placeholder="* Your email..." /> <div class="error left-align" id="err-email">Please enter a valid email address.</div> </div> </div> <div class="control-group"> <div class="controls"> <input class="span12" type="text" id="subject" name="subject" placeholder="* Message subject..." /> <div class="error left-align" id="err-name">Please enter the subject of your message.</div> </div> </div> <div class="control-group"> <div class="controls"> <textarea class="span12" name="comment" id="comment" placeholder="* Message"></textarea> <div class="error left-align" id="err-comment">Please enter your message.</div> </div> </div> <div class="control-group"> <div class="controls"> <button id="send-mail" class="message-btn">Send message</button> </div> </div> </form> </div> </div> </div> </div> <div class="container"id="address"> <div class="span9 center contact-info"> <p> 85 Bushpig Ave, Hesteapark, Akasia, 0201. </p> <p class="info-mail"><EMAIL></p> <p>+27 (0) 83 494 3316 </p> <p>+27 (0) 83 578 4817</p> <div class="title"> <h3>Find Us On Social Media </h3> </div> </div> <div class="row-fluid centered"> <ul class="social"> <li><a target="blank" href="https://www.facebook.com/MYP1060/"><span class="icon-facebook-circled"></span></a></li> <li><a target="blank" href="https://twitter.com/myp1060"><span class="icon-twitter-circled"></span></a></li> <li><a target="blank" href="https://www.instagram.com/myp1060/"><span class="icon-instagram"></span></a></li> </ul> </div> </div> </div> </div> <!-- Contact section edn --> <!-- Footer section start --> <div class="footer"> <p> <i>Powered by</i> <a target="_blank" href="http://www.itechhub.co.za">iTechHub</a> &copy; <?php echo date('Y') ?>. </p> </div> <!-- Footer section end --> <!-- ScrollUp button start --> <div class="scrollup"> <a href="#"> <i class="icon-up-open"></i> </a> </div> <!-- ScrollUp button end --> <!-- Include javascript --> <script src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery.mixitup.js"></script> <script type="text/javascript" src="js/bootstrap.js"></script> <script type="text/javascript" src="js/modernizr.custom.js"></script> <script type="text/javascript" src="js/jquery.bxslider.js"></script> <script type="text/javascript" src="js/jquery.cslider.js"></script> <script type="text/javascript" src="js/jquery.placeholder.js"></script> <script type="text/javascript" src="js/jquery.inview.js"></script> <!-- Load google maps api and call initializeMap function defined in app.js --> [if lt IE 9]> <script src="js/respond.min.js"></script> <![endif]--> <script type="text/javascript" src="js/app.js"></script> <script src="https://maps.googleapis.com/maps/api/js?key=<KEY>&callback=initializeMap" async defer> </script> <!-- <script async defer src="https://maps.googleapis.com/maps/api/js?sensor=false&callback=initializeMap"> </script> <!-- css3-mediaqueries.js for IE8 or older --> </body> </html>
f47f1141df57c0f6c23b735fbda4863efd9d814b
[ "PHP" ]
1
PHP
datawizzards-za/myp
12d9e61cc20118191a11d1cee0f8ee23d7f0186c
9bfec5372c8b00c29eeea5913f26167b94119b83
refs/heads/master
<file_sep>// Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. // // Note that the row index starts from 0. // // // In Pascal's triangle, each number is the sum of the two numbers directly above it. // // Example: // // // Input: 3 // Output: [1,3,3,1] // // // Follow up: // // Could you optimize your algorithm to use only O(k) extra space? // class Solution { public List<Integer> getRow(int rowIndex) { List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i <= rowIndex; i++){ list.add(1); for(int k = i-1; k >= 1; k--){ list.set(k, list.get(k-1) + list.get(k)); } } return list; } } <file_sep># Menu - [Menu](#menu) - [Main](#main) * [1. Two sums](#1-two-sums) [TOC] # Main ## 1. Two sums Use map to achieve O(N) time complexity ```java class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < nums.length; i++){ map.put(nums[i], i); } for(int i = 0; i < nums.length; i++){ int num = nums[i]; int complement = target - num; if (map.containsKey(complement) && map.get(complement) != i){ return new int[]{i, map.get(complement)}; } } return nums; } } ``` Time: O(N) Space: O(N) ## 2. Add Two Numbers 1. Use a dummy head to store the head of the linked list 2. Append a node(1) at the tails if carry ==1 ## 94. Binary Tree Inorder Traversal 1. Return if root is null 2. DFS root.left 3. Add root.val to List 4. DFS root.right ```java class Solution { private ArrayList<Integer> list = new ArrayList<>(); public List<Integer> inorderTraversal(TreeNode root) { traverse(root); return list; } void traverse(TreeNode root){ if (root == null) return; traverse(root.left); list.add(root.val); traverse(root.right); } } ``` ## 95. Unique Binray Seach Trees II > **Approach 1: Recursion** > > Let's pick up number `i` out of the sequence `1 ..n` and use it as the root of the current tree. Then there are `i - 1` elements available for the construction of the left subtree and `n - i` elements available for the right subtree. As we [already discussed](https://leetcode.com/articles/unique-binary-search-trees/) that results in `G(i - 1)` different left subtrees and `G(n - i)` different right subtrees, where `G` is a Catalan number. > > ![BST](https://leetcode.com/problems/unique-binary-search-trees-ii/Figures/96_BST.png) > > Now let's repeat the step above for the sequence `1 ... i - 1` to construct all left subtrees, and then for the sequence `i + 1 ... n` to construct all right subtrees. > > This way we have a root `i` and two lists for the possible left and right subtrees. The final step is to loop over both lists to link left and right subtrees to the root. ```java /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<TreeNode> generateTrees(int n) { if (n == 0) return new LinkedList<TreeNode>(); return generate(1, n); } private List<TreeNode> generate(int start, int end){ List<TreeNode> all_trees = new LinkedList<>(); if (start > end){ all_trees.add(null); } for (int i = start; i <= end; i++){ // left sub-branches List<TreeNode> left_trees = generate(start, i-1); // right sub-branches List<TreeNode> right_trees = generate(i+1, end); // combine left branches and right branches by G(start, i-1) * G(i+1, end) // if start == end, G(start, start-1) return [null], G(start+1, end) return [null]. It will only loop once for (TreeNode left : left_trees){ for(TreeNode right: right_trees){ TreeNode current_root = new TreeNode(i); current_root.left = left; current_root.right = right; all_trees.add(current_root); } } } return all_trees; } } ``` ## 96. Unique Binary Search Trees ![img](https://leetcode.com/problems/unique-binary-search-trees/Figures/96_BST.png) 1. Iterate from 0 to n, return G(0, 0, n) 1. Base case: If n = 1, return 1. if n = 2, return 2 2. Let G(i, start, end) denotes root = array[i] 3. count = G(i, start, i-1) * G(i+1, end) //left * right ```java class Solution { private int[] nums = {1,1}; public int numTrees(int n) { if(nums.length-1 < n){ nums = new int[n+1]; nums[0] = 1; nums[1] = 1; } if (nums[n] != 0) return nums[n]; int sum = 0; for(int i = 1; i <= n; i++){ sum += numTrees(i-1) * numTrees(n-i); //sum = left sub * right sub } nums[n] = sum; return sum; } } ``` <file_sep>// Implement int sqrt(int x). // // Compute and return the square root of x, where x is guaranteed to be a non-negative integer. // // Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. // // Example 1: // // // Input: 4 // Output: 2 // // // Example 2: // // // Input: 8 // Output: 2 // Explanation: The square root of 8 is 2.82842..., and since //   the decimal part is truncated, 2 is returned. // // class Solution { public int mySqrt(int x) { if (x < 2) return x; long x_new = (long)x; int start = 2; int end = x/2; while(start <= end){ int mid = (end + start) / 2; long sqr = (long)mid * mid; if(sqr == x) return mid; else if(sqr < x){ start = mid+1; } else{ end = mid-1; } } return end; // if((long)start * start < x){ // return start; // } // else return start-1; } } <file_sep>// Reverse a singly linked list. // // Example: // // // Input: 1->2->3->4->5->NULL // Output: 5->4->3->2->1->NULL // // // Follow up: // // A linked list can be reversed either iteratively or recursively. Could you implement both? // /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseList(ListNode head) { if(head == null) return null; return reverse(null, head); } ListNode reverse(ListNode prev, ListNode curr){ ListNode next = curr.next; curr.next = prev; if (next == null) return curr; return reverse(curr, next); } } <file_sep>// Given a string s , find the length of the longest substring t  that contains at most 2 distinct characters. // // Example 1: // // // Input: "eceba" // Output: 3 // Explanation: t is "ece" which its length is 3. // // // Example 2: // // // Input: "ccaabbb" // Output: 5 // Explanation: t is "aabbb" which its length is 5. // // class Solution { public int lengthOfLongestSubstringTwoDistinct(String s) { int maxLen = 0; int win_left = 0; HashMap<Character, Integer> map = new HashMap<>(); for(int win_right = 0; win_right < s.length(); win_right++){ char next = s.charAt(win_right); if(map.containsKey(next)){ map.put(next, map.get(next) + 1); } else{ map.put(next, 1); } while(map.size() >= 3){ char left_most = s.charAt(win_left); if(map.get(left_most) != 1){ map.put(left_most, map.get(left_most) -1); } else{ map.remove(left_most); } win_left++; } maxLen = Math.max(maxLen, win_right - win_left +1); } return maxLen; } } <file_sep>// // Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. // If there is a tie, the smaller elements are always preferred. // // // Example 1: // // Input: [1,2,3,4,5], k=4, x=3 // Output: [1,2,3,4] // // // // // Example 2: // // Input: [1,2,3,4,5], k=4, x=-1 // Output: [1,2,3,4] // // // // Note: // // The value k is positive and will always be smaller than the length of the sorted array. // Length of the given array is positive and will not exceed 104 // Absolute value of elements in the array and x will not exceed 104 // // // // // // // UPDATE (2017/9/19): // The arr parameter had been changed to an array of integers (instead of a list of integers). Please reload the code definition to get the latest changes. // class Solution { public List<Integer> findClosestElements(int[] arr, int k, int x) { //first find lower bound if(arr == null || arr.length == 0) return new ArrayList<>(); List<Integer> output = new ArrayList<>(); int left =0; int right = arr.length-1; // find lower bound of x while(left <= right){ int mid = left + (right - left)/2; if(arr[mid] < x){ left = mid+1; } else right = mid -1; } if(left == arr.length){ left = arr.length-1; } if(arr[left] != x && left != 0){ if(Math.abs(arr[left] - x) > Math.abs(arr[left-1] - x)){ left = left - 1; } } right = left; while(right - left + 1 < k){ if(left == 0 && right == arr.length-1) break; // if left out of bound if(left == 0){ right++; continue; } // if right out of bound else if(right == arr.length-1){ left--; continue; } if(Math.abs(x - arr[left-1]) <= Math.abs(x-arr[right+1])){ left--; } else{ right++; } } while(left <= right){ output.add(arr[left++]); } return output; } } <file_sep>// Write a function that reverses a string. The input string is given as an array of characters char[]. // // Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. // // You may assume all the characters consist of printable ascii characters. // //   // // // Example 1: // // // Input: ["h","e","l","l","o"] // Output: ["o","l","l","e","h"] // // // // Example 2: // // // Input: ["H","a","n","n","a","h"] // Output: ["h","a","n","n","a","H"] // // // class Solution { public void reverseString(char[] s) { reverse(s); } void reverse(char[] s){ for(int i = 0; i < s.length; i++){ int swap = s.length-1-i; if(i >= swap) return; char temp = s[i]; s[i] = s[swap]; s[swap] = temp; } } } <file_sep># Abstract # Data structures ### Reverse **Array** (Write a **`reverse`** method) ```java public void reverse(int[] nums, int start, int end) { while (start < end) { int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } } int [] a = {1,2}; reverse(a, 0, a.length-1); // a = {2, 1} ``` ## Sorting ### Reverse sort **list** ```java Collections.sort(list, Collections.reverseOrder()); ``` **array** ```java Arrays.sort(array, Collections.reverseOrder()); ``` `Collections.reverseOrder()` returns a comparator for reverser sort. an alternative could be (for numbers!!!) 1. multiply the Array by -1 2. sort 3. multiply once again with -1 Pseudo code: ```java array = -Arrays.sort(-array) ``` ## Auto-Unboxing and Cache ## Digit and Letter `Character.isDigit(string.charAt(index))` ([JavaDoc](https://docs.oracle.com/javase/10/docs/api/java/lang/Character.html#isDigit(char))) will return true if it's a digit `Character.isLetter(string.charAt(index))` ([JavaDoc](https://docs.oracle.com/javase/10/docs/api/java/lang/Character.html#isLetter(char))) will return true if it's a letter ### Conversion between char and int ```java char five = '5; int x = five - '0'; // x = 5 ``` ======= ```java public class Scratch { public static void main(String[] args) { Integer a = 1000, b = 1000; //1 System.out.println(a == b); Integer c = 100, d = 100; //2 System.out.println(c == d); } } ``` **Output:** ```java false true ``` Yep the first output is produced for comparing reference; 'a' and 'b' - these are two different reference. In point 1, actually two references are created which is similar as - ```java Integer a = new Integer(1000); Integer b = new Integer(1000); ``` The second output is produced because the `JVM` tries to save memory, when the `Integer` falls in a range (from -128 to 127). At point 2 no new reference of type Integer is created for 'd'. Instead of creating a new object for the Integer type reference variable 'd', it only assigned with previously created object referenced by 'c'. All of these are done by `JVM`. These memory saving rules are not only for Integer. for memory saving purpose, two instances of the following wrapper objects (while created through boxing), will always be == where their primitive values are the same - - Boolean - Byte - Character from **\u0000** to `\u007f` (7f is 127 in decimal) - Short and Integer from **-128** to **127** >>>>>>> 6fa49a1f945d078bf61ffc3ec14259c0ff96759f ## If Else Condition ```java int a_val = a==null ? 0 : a.val; int b_val = b==null ? 0 : b.val; ``` ## Array ```java int[][] visited = new int[rows][cols]; for(int[] a:visited){ for (int b : a){ System.out.print(b); } System.out.println(""); } ``` output: ``` 00000 00000 00000 00000 ``` ## HashMap Initialize HashMap with default values; ```java // Initialize with no key&value private Map<Integer, Integer> map1 = new HashMap<>(); // Initialize with default key&value private Map<Integer, Integer> map2 = new HashMap<Integer, Integer>(){ { put(0,1); put(1,1); } }; ``` ## ArrayDeque https://www.geeksforgeeks.org/arraydeque-in-java/ ArrayDeque in Java provides a way to apply **resizable-array** in addition to the implementation of the Deque interface. It is also known as **Array Double Ended Queue** or Array Deck. This is a special kind of array that grows and allows users to add or remove an element from both the sides of the queue. Few important features of ArrayDeque are as follows: - Array deques have **no capacity restrictions** and they grow as necessary to support usage. - They are **not thread-safe** which means that in the absence of external synchronization, ArrayDeque does not support concurrent access by multiple threads. - **Null elements are prohibited in the ArrayDeque.** - ArrayDeque class is likely to be faster than Stack when used as a stack. - ArrayDeque class is likely to be faster than LinkedList when used as a queue. **Methods in ArrayDeque:** 1. [add(Element e) :](https://www.geeksforgeeks.org/arraydeque-add-method-in-java/) The method inserts particular element at the end of the deque. 2. [addFirst(Element e) :](https://www.geeksforgeeks.org/arraydeque-addfirst-method-in-java/) The method inserts particular element at the start of the deque. 3. [addLast(Element e) :](https://www.geeksforgeeks.org/arraydeque-addlast-method-in-java/) The method inserts particular element at the end of the deque. It is similiar to add() method 4. [clear() :](https://www.geeksforgeeks.org/arraydeque-clear-method-in-java/) The method removes all deque elements. 5. [size() :](https://www.geeksforgeeks.org/arraydeque-size-method-in-java/) The method returns the no. of elements in deque. 6. [clone() :](https://www.geeksforgeeks.org/arraydeque-clone-method-in-java/) The method copies the deque. 7. [contains(Obj) :](https://www.geeksforgeeks.org/arraydeque-contains-method-in-java/) The method checks whether a deque contains the element or not 8. [Iterator() :](https://www.geeksforgeeks.org/arraydeque-iterator-method-in-java/) The method returns an iterator over the deque. 9. [descendingIterator() :](https://www.geeksforgeeks.org/arraydeque-descendingiterator-method-in-java/) The method returns a reverse order iterator over the deque 10. [element() :](https://www.geeksforgeeks.org/arraydeque-element-method-in-java/) The method returns element at the head of the deque 11. [getFirst():](https://www.geeksforgeeks.org/arraydeque-getfirst-method-in-java/) The method returns first element of the deque 12. [getLast():](https://www.geeksforgeeks.org/arraydeque-getlast-method-in-java/) The method returns last element of the deque 13. [isEmpty():](https://www.geeksforgeeks.org/arraydeque-isempty-method-in-java/) The method checks whether the deque is empty or not. 14. [toArray():](https://www.geeksforgeeks.org/arraydeque-toarray-method-in-java/) The method returns array having the elements of deque. 15. [offer(Element e) :](https://www.geeksforgeeks.org/arraydeque-offer-method-in-java/) The method inserts element at the end of deque. 16. [offerFirst(Element e) :](https://www.geeksforgeeks.org/arraydeque-offerfirst-method-in-java/) The method inserts element at the front of deque. 17. [offerLast(Element e) :](https://www.geeksforgeeks.org/arraydeque-offerlast-method-in-java/) The method inserts element at the end of deque. 18. [peek() :](https://www.geeksforgeeks.org/arraydeque-peek-method-in-java/) The method returns head element without removing it. 19. [peekFirst() :](https://www.geeksforgeeks.org/arraydeque-peekfirst-method-in-java/) The method returns first element without removing it. 20. [peekLast() :](https://www.geeksforgeeks.org/arraydeque-peeklast-method-in-java/) The method returns last element without removing it. 21. [poll() :](https://www.geeksforgeeks.org/arraydeque-poll-method-in-java/) The method returns head element and also removes it 22. [pollFirst() :](https://www.geeksforgeeks.org/arraydeque-pollfirst-method-in-java/) The method returns first element and also removes it 23. [pollLast() :](https://www.geeksforgeeks.org/arraydeque-polllast-method-in-java/) The method returns last element and also removes it 24. [pop() :](https://www.geeksforgeeks.org/arraydeque-pop-method-in-java/) The method pops out an element for stack repesented by deque 25. [push(Element e) :](https://www.geeksforgeeks.org/arraydeque-push-method-in-java/) The method pushes an element onto stack repesented by deque 26. [remove() :](https://www.geeksforgeeks.org/arraydeque-remove-method-in-java/) The method returns head element and also removes it 27. [removeFirst() :](https://www.geeksforgeeks.org/arraydeque-removefirst-method-in-java/) The method returns first element and also removes it 28. [removeLast() :](https://www.geeksforgeeks.org/arraydeque-removelast-method-in-java/) The method returns last element and also removes it 29. [removeFirstOccurrence(Obj) :](https://www.geeksforgeeks.org/arraydeque-removefirstoccurrence-method-in-java/) The method removes the element where it first occur in the deque. 30. [removeLastOccurrence(Obj) :](https://www.geeksforgeeks.org/arraydeque-removelastoccurrence-method-in-java/) The method removes the element where it last occur in the deque. ## Stack **ArrayDeque<>():** APIs: 1. add(obj) //cannot add null 2. removeLast() ```java Deque<TreeNode> stack = new ArrayDeque<>(); stack.add(root); TreeNode curr = stack.removeLast(); ``` **LinkedList<>()** APIs: 1. add(obj) // can be null 2. pollLast() ```java LinkedList<TreeNode> stack = new LinkedList<>(); stack.add(root); TreeNode curr = stack.pollLast(); ``` ## String ### Split use `split("\\s+") ` to split all spaces. ```java String a = "ab cb d"; String[] b = a.split("\\s+"); // b = ["ab", "cb", "d"] ``` # Algorithms ## DFS ### Inorder **1. Using a stack** 1. Create a stack using ArrayDeque<>() 2. Recur if stack is not empty or root is not null 1. Push root to the stack 2. Check if root.left exists. If yes, repeat step 1 3. // Do something 4. Check root.right ```java Public inorder(TreeNode root){ Deque<TreeNode> stack = new ArrayDeque<>(); while(!stack.empty() || root!= null){ //add root.left to stack while(root != null){ stack.add(root); root = root.left; } root = stack.removeLast(); System.out.println("visiting: "+root.val); /** Do something here **/ root = root.right; } } ``` <file_sep>// Given a positive integer num, write a function which returns True if num is a perfect square else False. // // Note: Do not use any built-in library function such as sqrt. // // Example 1: // // // // Input: 16 // Output: true // // // // Example 2: // // // Input: 14 // Output: false // // // class Solution { public boolean isPerfectSquare(int num) { if(num <= 1) return true; long sqr; int left = 2; int right = num/2; while(left <= right){ int mid = (left+right)/2; sqr = (long)mid*mid; if(sqr == num) return true; else if(sqr < num) left = mid+1; else right = mid-1; } return false; } } <file_sep>// The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. // // // // Given an integer n, return all distinct solutions to the n-queens puzzle. // // Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. // // Example: // // // Input: 4 // Output: [ // [".Q..", // Solution 1 // "...Q", // "Q...", // "..Q."], // // ["..Q.", // Solution 2 // "Q...", // "...Q", // ".Q.."] // ] // Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above. // // class Solution { private List<List<String>> output = new ArrayList<List<String>>(); public List<List<String>> solveNQueens(int n) { int[] hills = new int[2*n]; int[] dales = new int[3*n]; int[] cols = new int[n]; LinkedList<String> temp_list = new LinkedList<>(); backtrack(0, n, hills, dales, cols, temp_list); return output; } private boolean isAllowed(int row, int col, int n, int[] hills, int[] dales, int[] cols){ int result = hills[row+col] + dales[row-col+2*n] + cols[col]; return result == 0 ? true :false; } private void backtrack(int row, int n, int[] hills, int[] dales, int[] cols, LinkedList<String> temp_list){ for(int col = 0; col < n; col++){ // if put queen if(isAllowed(row, col, n, hills, dales, cols)){ // put hills[row + col] = 1; dales[row - col + 2*n] = 1; cols[col] = 1; StringBuilder sb = new StringBuilder(""); for(int i = 0; i < col; i++) sb.append('.'); sb.append('Q'); for(int i = col+1; i < n; i++) sb.append('.'); temp_list.addLast(sb.toString()); // update string if(row == n-1){ //update output lists output.add(new LinkedList<>(temp_list)); // System.out.println(temp_list.toString()); } // backtrack else backtrack(row+1, n, hills, dales, cols, temp_list); hills[row + col] = 0; dales[row - col + 2*n] = 0; cols[col] = 0; temp_list.removeLast(); // remove last string } } } } <file_sep>// // Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. // // // // For example, given n = 3, a solution set is: // // // [ // "((()))", // "(()())", // "(())()", // "()(())", // "()()()" // ] // class Solution { List<String> output = new ArrayList<String>(); public List<String> generateParenthesis(int n) { backtrack(0,0,n,""); return output; } void backtrack(int left, int right, int n, String str){ if(left == right && left == n){ output.add(str); } else{ if(left < n){ backtrack(left+1, right, n, str+"("); } if(right < left){ backtrack(left, right+1, n, str+")"); } } } } <file_sep>// Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. // // // push(x) -- Push element x onto stack. // pop() -- Removes the element on top of the stack. // top() -- Get the top element. // getMin() -- Retrieve the minimum element in the stack. // // //   // // Example: // // // MinStack minStack = new MinStack(); // minStack.push(-2); // minStack.push(0); // minStack.push(-3); // minStack.getMin(); --> Returns -3. // minStack.pop(); // minStack.top(); --> Returns 0. // minStack.getMin(); --> Returns -2. // // //   // class MinStack { private LinkedList<Integer> stack = new LinkedList<>(); private LinkedList<Integer> mins = new LinkedList<>(); /** initialize your data structure here. */ public MinStack() { } public void push(int x) { int last_min = (stack.isEmpty()) ? Integer.MAX_VALUE : mins.peekLast(); mins.add(Math.min(last_min, x)); stack.add(x); } public void pop() { if(stack.isEmpty()) return; stack.removeLast(); mins.removeLast(); } public int top() { if(stack.isEmpty()) return -1; return stack.peekLast(); } public int getMin() { if(stack.isEmpty()) return -1; return mins.peekLast(); } } /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */ <file_sep> [TOC] # Algorithms ## Binary Search ```java int size = nums.size(); int l = 0; int r= size-1; while(l<= r) { int mid = (l+r) / 2; if(nums[mid] < target) l = mid+1; else r = mid-1; } if(l == size || nums[l] != target) return {-1, -1}; int left = l; l = 0; r =size-1; while(r >= l) { int mid = (l+r) / 2; if(nums[mid] > target) r = mid-1; else l = mid+1; } return {left, r}; ``` ## Sliding Window ![image-20191218225253739](C:\Users\xk\AppData\Roaming\Typora\typora-user-images\image-20191218225253739.png) ```java class MaxSumSubArrayOfSizeK { public static int findMaxSumSubArray(int k, int[] arr) { int windowSum = 0, maxSum = 0; int windowStart = 0; for (int windowEnd = 0; windowEnd < arr.length; windowEnd++) { windowSum += arr[windowEnd]; // add the next element // slide the window, we don't need to slide if we've not hit the required window size of 'k' if (windowEnd >= k - 1) { maxSum = Math.max(maxSum, windowSum); windowSum -= arr[windowStart]; // subtract the element going out windowStart++; // slide the window ahead } } return maxSum; } public static void main(String[] args) { System.out.println("Maximum sum of a subarray of size K: " + MaxSumSubArrayOfSizeK.findMaxSumSubArray(3, new int[] { 2, 1, 5, 1, 3, 2 })); System.out.println("Maximum sum of a subarray of size K: " + MaxSumSubArrayOfSizeK.findMaxSumSubArray(2, new int[] { 2, 3, 4, 1, 5 })); } ``` ## Sorting ### MergeSort ```java public int [] merge_sort(int [] input) { if (input.length <= 1) { return input; } int pivot = input.length / 2; int [] left_list = merge_sort(Arrays.copyOfRange(input, 0, pivot)); int [] right_list = merge_sort(Arrays.copyOfRange(input, pivot, input.length)); return merge(left_list, right_list); } public int [] merge(int [] left_list, int [] right_list) { int [] ret = new int[left_list.length + right_list.length]; int left_cursor = 0, right_cursor = 0, ret_cursor = 0; while (left_cursor < left_list.length && right_cursor < right_list.length) { if (left_list[left_cursor] < right_list[right_cursor]) { ret[ret_cursor++] = left_list[left_cursor++]; } else { ret[ret_cursor++] = right_list[right_cursor++]; } } // append what is remain the above lists while (left_cursor < left_list.length) { ret[ret_cursor++] = left_list[left_cursor++]; } while (right_cursor < right_list.length) { ret[ret_cursor++] = right_list[right_cursor++]; } return ret; } ``` ## DFS ### Common use ```java int[][] directions = {{0,1}, {0,-1}, {1,0}, {-1, 0}}; int[][] visited = new int[rows][cols]; Queue<int[]> q = new LinkedList<>(); ``` ### Inorder **1. Using a stack** 1. Create a stack using `ArrayDeque<>()` 2. Recursively check if stack is not empty or root is not null 1. Push `root` to the stack 2. Check if `root.left` exists. If yes, repeat step 1 3. `root = stack.pop()` 4. Check root.right ```java Public inorder(TreeNode root){ Deque<TreeNode> stack = new ArrayDeque<>(); while(!stack.empty() || root!= null){ //add root.left to stack while(root != null){ stack.add(root); root = root.left; } root = stack.removeLast(); System.out.println("visiting: "+root.val); /** Do something here **/ root = root.right; } } ``` ## BFS ### Level Order Traversal Approach 1: Recursion Recursively call the function `helper(treeNode, level)`, which takes the current node and its level as the arguments. The helper function does the followings: 1. Since the output is a `List<ArrayList<nodeValue>> levels`, it appends the current node value to the last `level` in levels. 2. If the `treeNode` is not null, call `helper(treeNode.left, level+1)` and `helper(treeNode.right, level+1)`. 3. If the treeNode is null, just return. ```java class Solution { List<List<Integer>> levels = new ArrayList<List<Integer>>(); public void helper(TreeNode node, int level) { // start the current level if (levels.size() == level) levels.add(new ArrayList<Integer>()); // fulfil the current level levels.get(level).add(node.val); // process child nodes for the next level if (node.left != null) helper(node.left, level + 1); if (node.right != null) helper(node.right, level + 1); } public List<List<Integer>> levelOrder(TreeNode root) { if (root == null) return levels; helper(root, 0); return levels; } } ``` **Complexity Analysis** - Time complexity : **O(*N*)** since each node is processed exactly once. - Space complexity :**O(*N*)** to keep the output structure which contains `N` node values. #### Approach 2: Iteration **Algorithm** The recursion above could be rewritten in the iteration form. Let's keep nodes of each tree level in the *queue* structure, which typically orders elements in a **FIFO** (first-in-first-out) manner. In Java one could use [`LinkedList` implementation of the `Queue` interface](https://docs.oracle.com/javase/7/docs/api/java/util/Queue.html). In Python using [`Queue` structure](https://docs.python.org/3/library/queue.html) would be an overkill since it's designed for a safe exchange between multiple threads and hence requires locking which leads to a performance loose. In Python the queue implementation with a fast atomic `append()` and `popleft()` is [`deque`](https://docs.python.org/3/library/collections.html#collections.deque). The zero level contains only one node `root`. The algorithm is simple : - Initiate queue with a `root` and start from the level number `0` : `level = 0`. - While queue is not empty : - Start the current level by adding an empty list into output structure `levels`. - Compute how many elements should be on the current level : it's a queue length. - Pop out all these elements from the queue and add them into the current level. - Push their child nodes into the queue for the next level. - Go to the next level `level++`. ```java class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> levels = new ArrayList<List<Integer>>(); if (root == null) return levels; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); int level = 0; while ( !queue.isEmpty() ) { // start the current level levels.add(new ArrayList<Integer>()); // number of elements in the current level int level_length = queue.size(); for(int i = 0; i < level_length; ++i) { TreeNode node = queue.remove(); // fulfill the current level levels.get(level).add(node.val); // add child nodes of the current level // in the queue for the next level if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } // go to next level level++; } return levels; } } ``` **Complexity Analysis** - Time complexity : **O(*N*)** since each node is processed exactly once. - Space complexity : **O(*N*)** to keep the output structure which contains `N` node values.<file_sep>// Write a program to solve a Sudoku puzzle by filling the empty cells. // // A sudoku solution must satisfy all of the following rules: // // // Each of the digits 1-9 must occur exactly once in each row. // Each of the digits 1-9 must occur exactly once in each column. // Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. // // // Empty cells are indicated by the character '.'. // // // A sudoku puzzle... // // // ...and its solution numbers marked in red. // // Note: // // // The given board contain only digits 1-9 and the character '.'. // You may assume that the given Sudoku puzzle will have a single unique solution. // The given board size is always 9x9. // // class Solution { public void solveSudoku(char[][] board) { int N = 9; int[][] boxes = new int[N+1][N+1]; int[][] rows = new int[N][N+1]; int[][] cols = new int[N][N+1]; for (int row = 0; row < N; row++){ for(int col = 0; col < N; col++){ if(board[row][col] != '.'){ int digit = board[row][col] - '0'; placeNumber(row,col,digit,boxes,rows,cols, board); } } } backtrack(0, 0, boxes, rows, cols, board); } boolean allowed(int row, int col, int digit, int[][] boxes, int[][] rows, int[][]cols, char[][] board){ int box_idx = (row / 3) * 3 + col/3; int result = cols[col][digit] + rows[row][digit] + boxes[box_idx][digit]; return result == 0; } void placeNumber(int row, int col, int digit, int[][] boxes, int[][] rows, int[][]cols, char[][] board){ int box_idx = (row / 3) * 3 + col/3; cols[col][digit] = 1; rows[row][digit] = 1; boxes[box_idx][digit] = 1; board[row][col] = (char)(digit + '0'); } void removeNumber(int row, int col, int digit, int[][] boxes, int[][] rows, int[][]cols, char[][] board){ int box_idx = (row / 3) * 3 + col/3; cols[col][digit] = 0; rows[row][digit] = 0; boxes[box_idx][digit] = 0; board[row][col] = '.'; } boolean backtrack(int row, int col, int[][] boxes, int[][] rows, int[][]cols, char[][] board){ boolean isSolved = false; if(board[row][col] == '.'){ for(int digit = 1; digit <= 9; digit++){ if (allowed(row,col, digit, boxes,rows,cols, board)){ placeNumber(row,col,digit, boxes,rows,cols, board); if(row == 8 && col == 8) return true; //check next cell if(col == 8 && row <= 8){ isSolved = backtrack(row+1, 0, boxes, rows, cols, board); } else if (col < 8){ isSolved = backtrack(row, col+1, boxes, rows, cols, board); } if (isSolved){ return true; } else{ removeNumber(row,col,digit,boxes,rows,cols, board); } } } } else{ if(row == 8 && col == 8) return true; //check next cell if(col == 8 && row <= 8){ isSolved = backtrack(row+1, 0, boxes, rows, cols, board); } else if (col < 8){ isSolved = backtrack(row, col+1, boxes, rows, cols, board); } if (isSolved){ return true; } } return isSolved; } } <file_sep>// Two elements of a binary search tree (BST) are swapped by mistake. // // Recover the tree without changing its structure. // // Example 1: // // // Input: [1,3,null,null,2] // //   1 //   / //  3 //   \ //   2 // // Output: [3,1,null,null,2] // //   3 //   / //  1 //   \ //   2 // // // Example 2: // // // Input: [3,1,4,null,null,2] // // 3 // / \ // 1 4 //   / //   2 // // Output: [2,1,4,null,null,3] // // 2 // / \ // 1 4 //   / //  3 // // // Follow up: // // // A solution using O(n) space is pretty straight forward. // Could you devise a constant space solution? // // /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public void recoverTree(TreeNode root) { List<Integer> nums = new ArrayList<>(); inorder(root, nums); int[] swapped = find_two_swapped_element(nums); recover(root, swapped[0], swapped[1]); } private void inorder(TreeNode root, List<Integer> nums){ if (root == null) return; inorder(root.left, nums); nums.add(root.val); inorder(root.right, nums); } private int[] find_two_swapped_element(List<Integer> nums){ Integer x = null; Integer y = null; // iterate 0...n-1 for(int i = 0; i < nums.size()-1; i++){ if (nums.get(i) > nums.get(i+1)){ y = nums.get(i+1); if(x == null){ x = nums.get(i); } else break; //Break after second swapped element being searched. } } return new int[]{x, y}; } private void recover(TreeNode root, int x, int y){ if (root==null) return; recover(root.left, x, y); if (x == root.val || y == root.val){ root.val = root.val == x ? y : x; } recover(root.right,x ,y); } } <file_sep>// Given two arrays, write a function to compute their intersection. // // Example 1: // // // Input: nums1 = [1,2,2,1], nums2 = [2,2] // Output: [2,2] // // // // Example 2: // // // Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] // Output: [4,9] // // // Note: // // // Each element in the result should appear as many times as it shows in both arrays. // The result can be in any order. // // // Follow up: // // // What if the given array is already sorted? How would you optimize your algorithm? // What if nums1's size is small compared to nums2's size? Which algorithm is better? // What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? // // class Solution { public int[] intersect(int[] nums1, int[] nums2) { //assume n1 > n2 int n1 = nums1.length; int n2 = nums2.length; if(n2 > n1) return intersect(nums2, nums1); HashMap<Integer, Integer> ds = new HashMap<>(); List<Integer> list = new ArrayList<>(); for(int a : nums1){ ds.put(a, ds.getOrDefault(a, 0)+1); } int idx = 0; for(int a : nums2){ if(ds.containsKey(a) && ds.get(a) > 0){ nums1[idx++] = a; ds.put(a, ds.get(a)-1); } } return Arrays.copyOfRange(nums1, 0, idx); } } <file_sep>// Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? // // Example: // // // Input: 3 // Output: 5 // Explanation: // Given n = 3, there are a total of 5 unique BST's: // // 1 3 3 2 1 // \ / / / \ \ // 3 2 1 1 3 2 // / / \ \ // 2 1 2 3 // // class Solution { private Map<Integer, Integer> map = new HashMap<>(); public int numTrees(int n) { if (n <= 1) return 1; if (map.containsKey(n)) return map.get(n); int sum = 0; for (int i = 1; i <= n; i++){ sum += numTrees(i-1) * numTrees(n-i); } map.put(n, sum); return sum; } } <file_sep>// Given two binary strings, return their sum (also a binary string). // // The input strings are both non-empty and contains only characters 1 or 0. // // Example 1: // // // Input: a = "11", b = "1" // Output: "100" // // Example 2: // // // Input: a = "1010", b = "1011" // Output: "10101" // class Solution { public String addBinary(String a, String b) { int a_len = a.length(); int b_len = b.length(); if (a_len > b_len) return addBinary(b, a); StringBuilder sb = new StringBuilder(""); int carry = 0; for(int i = b_len-1, j = a_len-1; i >= 0; i--){ int value = 0; if(j >= 0 && a.charAt(j--) == '1') value++; if(b.charAt(i) == '1') value++; value+= carry; if(value%2 == 1) sb.append('1'); else sb.append('0'); if(value / 2 == 1){ carry = 1; } else carry = 0; System.out.println(sb.toString()); System.out.println("carry: " + carry); } if (carry==1){ sb.append('1'); } sb.reverse(); return sb.toString(); } } <file_sep>// Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. // // // In Pascal's triangle, each number is the sum of the two numbers directly above it. // // Example: // // // Input: 5 // Output: // [ // [1], // [1,1], // [1,2,1], // [1,3,3,1], // [1,4,6,4,1] // ] // // class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> list = new ArrayList<List<Integer>>(); if(numRows== 0) return list; int[][] visited = new int[numRows+1][numRows+1]; visited[1][1] = 1; for(int i = 1; i <= numRows; i++){ List<Integer> list_temp = new ArrayList<Integer>(); for(int k = 1; k <= i; k++){ if(k == 1 || k == i){ visited[i][k] = 1; list_temp.add(1); continue; } visited[i][k] =visited[i-1][k-1] + visited[i-1][k]; list_temp.add(visited[i][k]); } list.add(list_temp); } return list; } } <file_sep>// Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. // // The distance between two adjacent cells is 1. // //   // // Example 1: // // // Input: // [[0,0,0], // [0,1,0], // [0,0,0]] // // Output: // [[0,0,0], //  [0,1,0], //  [0,0,0]] // // // Example 2: // // // Input: // [[0,0,0], // [0,1,0], // [1,1,1]] // // Output: // [[0,0,0], // [0,1,0], // [1,2,1]] // // //   // // Note: // // // The number of elements of the given matrix will not exceed 10,000. // There are at least one 0 in the given matrix. // The cells are adjacent in only four directions: up, down, left and right. // // class Solution { private int[][] directions = {{1,0}, {-1,0}, {0,1}, {0,-1}}; public int[][] updateMatrix(int[][] matrix) { if (matrix.length == 0)return matrix; Queue<int[]> q = new LinkedList<>(); int rows = matrix.length; int cols = matrix[0].length; int[][] dist = new int[rows][cols]; for(int[] a:dist){ Arrays.fill(a, 10001); } for (int row = 0; row < rows; row++){ for (int col = 0; col < cols; col++){ if(matrix[row][col] == 0){ dist[row][col] = 0; q.add(new int[]{row,col}); } } } while (!q.isEmpty()){ int[] node = q.remove(); int row = node[0]; int col = node[1]; for (int i = 0; i < 4; i++){ int row_new = row+directions[i][0]; int col_new = col+directions[i][1]; if(row_new <0 || col_new<0 || row_new >= rows || col_new >= cols){ continue; } if(dist[row][col] + 1 < dist[row_new][col_new]){ dist[row_new][col_new] = dist[row][col] + 1; q.add(new int[]{row_new, col_new}); } } } return dist; } } <file_sep># Set-up ## dependencies spring-aop.jar spring-beans.jar spring-context.jar spring-core.jar spring-expression.jar logging.jar <file_sep>// Given preorder and inorder traversal of a tree, construct the binary tree. // // Note: // You may assume that duplicates do not exist in the tree. // // For example, given // // // preorder = [3,9,20,15,7] // inorder = [9,3,15,20,7] // // Return the following binary tree: // // // 3 // / \ // 9 20 // / \ // 15 7 // /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int[] inorder_1; int[] preorder_1; int preorder_idx = 0; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder.length == 0) return null; preorder_1 = preorder; inorder_1 = inorder; int idx = 0; for (int x : inorder) map.put(x, idx++); return build(0, preorder.length-1); } TreeNode build(int start, int end){ if(start > end) return null; int root_value = preorder_1[preorder_idx]; preorder_idx++; int root_index = map.get(root_value); TreeNode root = new TreeNode(root_value); // left root.left = build(start, root_index-1); //right root.right = build(root_index+1, end); return root; } } <file_sep>// Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. // // Example 1: // // // Input: n = 12 // Output: 3 // Explanation: 12 = 4 + 4 + 4. // // Example 2: // // // Input: n = 13 // Output: 2 // Explanation: 13 = 4 + 9. class Solution { public int numSquares(int n) { // use dp, finally return dp[n] int[] dp = new int[n+1]; dp[0] = 0; for(int i = 1; i <= n; i++){ // find dp[i] // dp[i] = mins(dp[i-first ps], dp[i - second ps].... until i-ps < 0) int min = Integer.MAX_VALUE; for(int sqr_idx = 1; i - sqr_idx*sqr_idx >= 0; sqr_idx++){ min = Math.min(min, dp[i-sqr_idx*sqr_idx]+1); // 1 stands for the count of perfect square(sqr^2) } dp[i] = min; } return dp[n]; } } <file_sep>// Given two arrays, write a function to compute their intersection. // // Example 1: // // // Input: nums1 = [1,2,2,1], nums2 = [2,2] // Output: [2] // // // // Example 2: // // // Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] // Output: [9,4] // // // Note: // // // Each element in the result must be unique. // The result can be in any order. // // //   // class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for(int a : nums1) set1.add(a); for(int b : nums2) set2.add(b); set1.retainAll(set2); int[] output = new int[set1.size()]; int idx = 0; for(int a:set1) output[idx++] = a; return output; } } <file_sep>// Given a collection of distinct integers, return all possible permutations. // // Example: // // // Input: [1,2,3] // Output: // [ // [1,2,3], // [1,3,2], // [2,1,3], // [2,3,1], // [3,1,2], // [3,2,1] // ] // // class Solution { List<List<Integer>> output = new ArrayList<List<Integer>>(); public List<List<Integer>> permute(int[] nums) { int n = nums.length; if(n == 0) return output; int[] visited = new int[n+1]; backtrack(0, n, new LinkedList<Integer>(), nums, visited); return output; } void backtrack(int start, int end, LinkedList<Integer> list, int[] nums, int[] visited){ if(list.size() == end){ output.add(new ArrayList<>(list)); } for(int i = start; i < end; i++){ if(visited[i] == 0){ list.addLast(nums[i]); visited[i] = 1; backtrack(0, end, list, nums, visited); list.removeLast(); visited[i] = 0; } } } } <file_sep>// Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. // // Your algorithm's runtime complexity must be in the order of O(log n). // // If the target is not found in the array, return [-1, -1]. // // Example 1: // // // Input: nums = [5,7,7,8,8,10], target = 8 // Output: [3,4] // // Example 2: // // // Input: nums = [5,7,7,8,8,10], target = 6 // Output: [-1,-1] // class Solution { public int[] searchRange(int[] nums, int target) { int[] output = new int[]{-1,-1}; if(nums == null || nums.length == 0) return output; if(nums.length == 1){ if(nums[0] == target){ return new int[]{0,0}; } else return output; } // find lower bound(the first element bigger or equal to the element) int left = 0, right = nums.length -1; while(left < right){ int mid = left+(right -left)/2; if(nums[mid] >= target){ right = mid; } else{ left = mid+1; } } if(nums[left] != target){ return new int[]{-1,-1}; } else{ output[0] = left; } // left no change // find upper bound(the last element smaller or equal to the target) right = nums.length-1; while(left < right){ int mid = left + (right-left)/2 +1; if (nums[mid] <= target){ left = mid; } else{ right = mid-1; } } output[1] = right; return output; } } <file_sep>// Given an array of integers nums, sort the array in ascending order. // //   // Example 1: // Input: nums = [5,2,3,1] // Output: [1,2,3,5] // Example 2: // Input: nums = [5,1,1,2,0,0] // Output: [0,0,1,1,2,5] // //   // Constraints: // // // 1 <= nums.length <= 50000 // -50000 <= nums[i] <= 50000 // // class Solution { public List<Integer> sortArray(int[] nums) { return mergeSort(nums); } List<Integer> mergeSort(int nums[]){ List<Integer> output = new ArrayList<Integer>(); if(nums.length <= 1){ output.add(nums[0]); return output; } int pivot = nums.length/2; List<Integer> left_list = mergeSort(Arrays.copyOfRange(nums, 0, pivot)); List<Integer> right_list = mergeSort(Arrays.copyOfRange(nums, pivot, nums.length)); return merge(left_list, right_list); } List<Integer> merge(List<Integer> left_list, List<Integer> right_list){ int total_length = left_list.size() + right_list.size(); List<Integer> output = new ArrayList<>(); int left_cursor = 0, right_cursor = 0; while(left_cursor < left_list.size() && right_cursor < right_list.size()){ if(left_list.get(left_cursor) < right_list.get(right_cursor)){ output.add(left_list.get(left_cursor++)); } else{ output.add(right_list.get(right_cursor++)); } } while(left_cursor < left_list.size()){ output.add(left_list.get(left_cursor++)); } while(right_cursor < right_list.size()){ output.add(right_list.get(right_cursor++)); } return output; } } <file_sep>// Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. // // Note: // // // Given target value is a floating point. // You are guaranteed to have only one unique value in the BST that is closest to the target. // // // Example: // // // Input: root = [4,2,5,1,3], target = 3.714286 // // 4 // / \ // 2 5 // / \ // 1 3 // // Output: 4 // // /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int prev = Integer.MIN_VALUE; int curr = Integer.MIN_VALUE; Integer curr_found = null; Integer prev_found = null; public int closestValue(TreeNode root, double target) { if(root.left == null && root.right == null) return root.val; inorder_search(root, target); if(curr_found != null){ if(prev_found == Integer.MIN_VALUE || Math.abs(curr_found-target) < Math.abs(prev_found - target)){ return curr_found; } return prev_found; } return curr; } void inorder_search(TreeNode root, double target){ if(root == null) return; inorder_search(root.left, target); prev = curr; curr = root.val; System.out.println("curr: " + curr); if(curr_found == null && (double)curr >= target){ System.out.println("found " + curr); prev_found = prev; curr_found = curr; return; } inorder_search(root.right, target); } } <file_sep>// Evaluate the value of an arithmetic expression in Reverse Polish Notation. // // Valid operators are +, -, *, /. Each operand may be an integer or another expression. // // Note: // // // Division between two integers should truncate toward zero. // The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation. // // // Example 1: // // // Input: ["2", "1", "+", "3", "*"] // Output: 9 // Explanation: ((2 + 1) * 3) = 9 // // // Example 2: // // // Input: ["4", "13", "5", "/", "+"] // Output: 6 // Explanation: (4 + (13 / 5)) = 6 // // // Example 3: // // // Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] // Output: 22 // Explanation: // ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 // = ((10 * (6 / (12 * -11))) + 17) + 5 // = ((10 * (6 / -132)) + 17) + 5 // = ((10 * 0) + 17) + 5 // = (0 + 17) + 5 // = 17 + 5 // = 22 // // class Solution { public int evalRPN(String[] tokens) { LinkedList<Integer> list = new LinkedList<>(); Set<String> operators = new HashSet<>(); operators.add("+"); operators.add("*"); operators.add("-"); operators.add("/"); for (String str : tokens){ if (!operators.contains(str)){ list.add(Integer.valueOf(str)); continue; } int b = list.removeLast(); int a = list.removeLast(); int c; switch(str){ case "+": c = a+b; break; case "-": c = a-b; break; case "*": c = a*b; break; default: c = a / b; break; } list.add(c); } return list.removeLast(); } } <file_sep>// Given a binary tree, count the number of uni-value subtrees. // // A Uni-value subtree means all nodes of the subtree have the same value. // // Example : // // // Input: root = [5,1,5,5,5,null,5] // // 5 // / \ // 1 5 // / \ \ // 5 5 5 // // Output: 4 // // /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int count = 0; public int countUnivalSubtrees(TreeNode root) { traverse(root, 0); return count; } boolean traverse(TreeNode root, int parentVal){ if (root == null) return true; // if childs are same, count++ if (traverse(root.left, root.val) & traverse(root.right, root.val)){ count++; } else return false; return root.val == parentVal; } } <file_sep>// Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). // // Example: // // // Input: S = "ADOBECODEBANC", T = "ABC" // Output: "BANC" // // // Note: // // // If there is no such window in S that covers all characters in T, return the empty string "". // If there is such window, you are guaranteed that there will always be only one unique minimum window in S. // // class Solution { public String minWindow(String s, String t) { Map<Character, Integer> t_dict = new HashMap<>(); Map<Character, Integer> window_dict = new HashMap<>(); if(s.length() == 0 || t.length() == 0){ return ""; } for(int i = 0; i < t.length(); i++){ char c = t.charAt(i); t_dict.put(c, t_dict.getOrDefault(c, 0) + 1); } int left = 0, right = 0; int[] window_min = {-1, 0, 0};// {length, ;eft, right} int formed = 0; int requried = t_dict.size(); while(right < s.length()){ //append right if not formed char next = s.charAt(right); window_dict.put(next, window_dict.getOrDefault(next, 0)+1); if (t_dict.containsKey(next) && window_dict.get(next).equals(t_dict.get(next))){ formed++; } // System.out.printf("formed: %d left: %d right: %d\n",formed, left, right); // shrink if formed == required, left-- while(formed == requried && left <= right){ //update window_min if(window_min[0] == -1 || window_min[0] > (right-left+1)){ window_min[0] = right-left +1; window_min[1] = left; window_min[2] = right; } char c = s.charAt(left); window_dict.put(c, window_dict.get(c) - 1); if(t_dict.containsKey(c) && t_dict.get(c).intValue() > window_dict.get(c).intValue()){ formed--; } left++; } right++; } return window_min[0] == -1 ? "" : s.substring(window_min[1], window_min[2] + 1); } } <file_sep>## **所有题目列表** | # | Title | Score | Backup | Completed | | ---- | ------------------------------------------------------------ | ----- | ------------------------------------------------------------ | --------- | | 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | | | | | 2 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | | | | | 3 | [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | | 这个系列的所有题都要多做几遍 | | | 4 | [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | | 这题很经典,多做几遍 | | | 5 | [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | | 这题对比动态规划和最优算法 | | | 6 | [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | | | | | 7 | [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | | | | | 8 | [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | | 很考代码能力,容易错 | | | 9 | [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | | | | | 10 | [Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) | | 这题很经典,多做几遍,和#44一起 | | | 11 | [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | | | | | 12 | [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | | | | | 13 | [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | | | | | 14 | [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | | | | | 15 | [3Sum](https://leetcode.com/problems/3sum/) | | | | | 16 | [3Sum Closest](https://leetcode.com/problems/3sum-closest/) | | | | | 17 | [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) | | | | | 18 | [4Sum](https://leetcode.com/problems/4sum/) | | | | | 19 | [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) | | | | | 20 | [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) | | | | | 21 | [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | | | | | 22 | [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/) | | 这题看两遍 | | | 23 | [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | | | | | 24 | [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) | | | | | 25 | [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/) | | | | | 26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | | | | | 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | | | | | 28 | [ Implement strStr()](https://leetcode.com/problems/implement-strstr/) | | | | | 29 | [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | | | | | 30 | [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | | | | | 31 | [Next Permutation](https://leetcode.com/problems/next-permutation/) | | | | | 32 | [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/) | | | | | 33 | [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | | | | | 34 | [Search for a Range](https://leetcode.com/problems/search-for-a-range/) | | | | | 35 | [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | | | | | 36 | [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/#/description) | | | | | 37 | [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/#/description) | | 这道题是典型的back tracking,多做几遍 | | | 38 | [Count and Say](https://leetcode.com/problems/count-and-say/) | | | | | 39 | [Combination Sum](https://leetcode.com/problems/combination-sum/) | | 排列组合系列的题要多做几遍 | | | 40 | [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/) | | | | | 41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/#/description) | | | | | 42 | [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | | | | | 43 | [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | | | | | 44 | [Wildcard Matching](https://leetcode.com/problems/wildcard-matching/) | | 和#10多做几遍 | | | 45 | [Jump Game II](https://leetcode.com/problems/jump-game-ii/#/description) | | | | | 46 | [Permutations](https://leetcode.com/problems/permutations/) | | | | | 47 | [Permutations II](https://leetcode.com/problems/permutations-ii/) | | 多做几遍 | | | 48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | | | | | 49 | [Group Anagrams](https://leetcode.com/problems/anagrams/) | | | | | 50 | [Pow(x, n)](https://leetcode.com/problems/powx-n/) | | | | | 51 | [N-Queens](https://leetcode.com/problems/n-queens/) | | | | | 52 | [N-Queens II](https://leetcode.com/problems/n-queens-ii/) | | | | | 53 | [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) | | | | | 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | | | | | 55 | [Jump Game](https://leetcode.com/problems/jump-game/#/description) | | | | | 56 | [Merge Intervals](https://leetcode.com/problems/merge-intervals/) | | | | | 57 | [Insert Interval](https://leetcode.com/problems/insert-interval/) | | 这题要多做几遍 | | | 60 | [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) | | 这题思路巧妙,多做两遍 | | | 61 | [Rotate List](https://leetcode.com/problems/rotate-list/) | | | | | 66 | [Plus One](https://leetcode.com/problems/plus-one/) | | 这题多看一遍 | | | 67 | [Add Binary](https://leetcode.com/problems/add-binary/) | | | | | 68 | [Text Justification](https://leetcode.com/problems/text-justification/) | | | | | 69 | [Sqrt(x)](https://leetcode.com/problems/sqrtx/) | | | | | 71 | [Simplify Path](https://leetcode.com/problems/simplify-path/) | | | | | 72 | [Edit Distance](https://leetcode.com/problems/edit-distance/) | | | | | 73 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/description/) | | | | | 74 | [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) | | | | | 75 | [Sort Colors](https://leetcode.com/problems/sort-colors/) | | 这题多做几遍,很有意思 | | | 76 | [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | | 这题以及类似的题一定要多做几遍,很经典,参见window | | | 77 | [Combinations](https://leetcode.com/problems/combinations) | | | | | 78 | [Subsets](https://leetcode.com/problems/subsets/) | | | | | 79 | [Word Search](https://leetcode.com/problems/word-search/) | | | | | 80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/) | | | | | 81 | [Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/) | | | | | 82 | [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/) | | | | | 83 | [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) | | | | | 84 | [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) | | | | | 85 | [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/) | | | | | 86 | [Partition List](https://leetcode.com/problems/partition-list/) | | | | | 88 | [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/) | | | | | 90 | [Subsets II](https://leetcode.com/problems/subsets-ii/) | | | | | 91 | [Decode Ways](https://leetcode.com/problems/decode-ways/) | | 这题多做几遍,包括#639 | | | 92 | [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/) | | | | | 93 | [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | | 多看两遍 | | | 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | | | | | 95 | [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | | 多做几遍,递归和DP | | | 96 | [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) | | | | | 98 | [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) | | 注意溢出 | | | 99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/) | | 这题很容易错,要多做几遍 | | | 100 | [Same Tree](https://leetcode.com/problems/same-tree/) | | | | | 101 | [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/) | | | | | 102 | [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) | | | | | 103 | [Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/) | | | | | 104 | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) | | | | | 105 | [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | | | | | 106 | [Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) | | | | | 107 | [Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/) | | | | | 108 | [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | | | | | 109 | [Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | | | | | 110 | [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) | | | | | 111 | [Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/) | | | | | 112 | [Path Sum](https://leetcode.com/problems/path-sum/) | | | | | 113 | [Path Sum II](https://leetcode.com/problems/path-sum-ii/) | | 错了好几次,得多做几遍 | | | 114 | [Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/) | | | | | 116 | [Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/) | | | | | 117 | [Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/) | | | | | 118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/) | | | | | 119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/description/) | | | | | 121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) | | | | | 122 | [Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/) | | | | | 123 | [Best Time to Buy and Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/) | | | | | 124 | [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) | | | | | 125 | [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | | | | | 126 | [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) | | | | | 127 | [Word Ladder](https://leetcode.com/problems/word-ladder/) | | 此题非常经典,务必连同ii多做几遍,将双端BFS吃透 | | | 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) | | | | | 129 | [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) | | | | | 130 | [Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) | | | | | 131 | [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | | | | | 132 | [Palindrome Partitioning II](https://leetcode.com/problems/palindrome-partitioning-ii/) | | | | | 133 | [Clone Graph](https://leetcode.com/problems/clone-graph/) | | 这题不难,多看两遍,BFS方法再做两遍 | | | 135 | [Candy](https://leetcode.com/problems/candy/) | | | | | 138 | [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | | 有一个易错点 | | | 139 | [Word Break](https://leetcode.com/problems/word-break/) | | 多看两遍 | | | 140 | [Word Break II](https://leetcode.com/problems/word-break-ii/) | | 这题多做两遍,很典型 | | | 141 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) | | | | | 142 | [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/) | | | | | 143 | [Reorder List](https://leetcode.com/problems/reorder-list/) | | | | | 144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) | | | | | 145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | | | | | 146 | [LRU Cache](https://leetcode.com/problems/lru-cache/) | | 好题目,多做几遍 | | | 147 | [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/) | | | | | 148 | [Sort List](https://leetcode.com/problems/sort-list) | | | | | 149 | [Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/) | | | | | 150 | [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/) | | | | | 151 | [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/description/) | | 这题虽然不难,但是也错了几次 | | | 152 | [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) | | | | | 153 | [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | | | | | 154 | [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | | | | | 155 | [Min Stack](https://leetcode.com/problems/min-stack/) | | | | | 156 | [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/) | | 这道题挺有意思,多做几遍 | | | 157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/) | | 这题多做几遍,结合#158 | | | 158 | [Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/) | | | | | 159 | [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/) | | 多看两遍 | | | 160 | [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/) | | | | | 161 | [One Edit Distance](https://leetcode.com/problems/one-edit-distance/) | | 和#72做两遍 | | | 162 | [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | | | | | 163 | [Missing Ranges](https://leetcode.com/problems/missing-ranges/) | | 多做几遍,太容易错了 | | | 164 | [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | | | | | 167 | [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | | | | | 168 | [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) | | | | | 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | | | | | 170 | [Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/) | | 这道题再多做一遍 | | | 171 | [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | | | | | 172 | [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | | | | | 173 | [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | | 多留意一下 | | | 179 | [Largest Number](https://leetcode.com/problems/largest-number/) | | | | | 186 | [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/description/) | | | | | 188 | [Best Time to Buy and Sell Stock IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/) | | | | | 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | | | | | 190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | | | | | 198 | [House Robber](https://leetcode.com/problems/house-robber/) | | | | | 199 | [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) | | | | | 200 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | | 这道题很经典,而且方法不止一种,每种方法都多做几遍,包括UF,#305 | | | 203 | [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/) | | | | | 204 | [Count Primes](https://leetcode.com/problems/count-primes/) | | | | | 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | | | | | 207 | [Course Schedule](https://leetcode.com/problems/course-schedule/) | | 典型的拓扑排序 | | | 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | | 和#211多留意,trie很典型 | | | 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | | | | | 210 | [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/) | | | | | 211 | [Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | | | | | 212 | [Word Search II](https://leetcode.com/problems/word-search-ii/) | | | | | 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii/) | | | | | 214 | [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | | | | | 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | | 这题很经典,三种解法都要了然于胸 | | | 216 | [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/) | | | | | 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | | | | | 218 | [The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/) | | 这题多做两遍 | | | 219 | [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | | | | | 220 | [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | | | | | 221 | [Maximal Square](https://leetcode.com/problems/maximal-square/) | | | | | 222 | [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | | 一般的做法会超时 | | | 223 | [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | | | | | 224 | [Basic Calculator](https://leetcode.com/problems/basic-calculator/) | | | | | 225 | [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/) | | | | | 226 | [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | | | | | 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | | | | | 229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | | | | | 230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | | 注意Follow Up | | | 232 | [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | | | | | 233 | [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/) | | | | | 234 | [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) | | | | | 235 | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) | | | | | 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | | 这题很经典,多做几遍,留意节点不在树中的情况 | | | 237 | [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/) | | | | | 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | | | | | 239 | [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/) | | 这题非常经典,多做几遍,包括常规算法(优先队列,treemap)及优化算法双端队列 | | | 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/) | | | | | 241 | [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/) | | | | | 242 | [Valid Anagram](https://leetcode.com/problems/valid-anagram/) | | | | | 243 | [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/) | | | | | 244 | [Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii/) | | | | | 245 | [Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance-iii/) | | | | | 246 | [Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/) | | #247一个系列,多看两遍 | | | 247 | [Strobogrammatic Number II](https://leetcode.com/problems/strobogrammatic-number-ii/) | | 多看两遍 | | | 249 | [Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/) | | | | | 250 | [Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees/) | | 这题要多做几遍 | | | 251 | [Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector/) | | | | | 252 | [Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) | | | | | 253 | [Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) | | | | | 254 | [Factor Combinations](https://leetcode.com/problems/factor-combinations/) | | | | | 255 | [Verify Preorder Sequence in Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/) | | 很简单,粗心错了 | | | 256 | [Paint House](https://leetcode.com/problems/paint-house/) | | | | | 257 | [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | | | | | 259 | [3Sum Smaller](https://leetcode.com/problems/3sum-smaller/) | | 这题虽然简单,但是因为思维定式还是错了几次 | | | 261 | [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/) | | 这题多做几遍 | | | 263 | [Ugly Number](https://leetcode.com/problems/ugly-number/) | | | | | 264 | [Ugly Number II](https://leetcode.com/problems/ugly-number-ii/) | | | | | 265 | [Paint House II](https://leetcode.com/problems/paint-house-ii) | | | | | 266 | [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/) | | | | | 267 | [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/) | | 典型,多看两遍 | | | 268 | [Missing Number](https://leetcode.com/problems/missing-number) | | | | | 269 | [Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) | | 这题要多做几遍 | | | 270 | [Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value/) | | | | | 271 | [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) | | 思路巧妙,多看几遍 | | | 272 | [Closest Binary Search Tree Value II](https://leetcode.com/problems/closest-binary-search-tree-value-ii/) | | 这题非常值得多做几遍,几种写法都试试 | | | 273 | [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) | | 多做几遍,做到bug free | | | 274 | [H-Index](https://leetcode.com/problems/h-index/) | | | | | 275 | [H-Index II](https://leetcode.com/problems/h-index-ii/) | | | | | 277 | [Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/) | | | | | 278 | [First Bad Version](https://leetcode.com/problems/first-bad-version/) | | | | | 279 | [Perfect Squares](https://leetcode.com/problems/perfect-squares/) | | | | | 280 | [Wiggle Sort](https://leetcode.com/problems/wiggle-sort/) | | 思路巧妙,多看两遍 | | | 281 | [Zigzag Iterator](https://leetcode.com/problems/zigzag-iterator/) | | 多做三遍,考虑扩展到k的情况 | | | 282 | [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | | | | | 283 | [Move Zeroes](https://leetcode.com/problems/move-zeroes/) | | | | | 284 | [Peeking Iterator](https://leetcode.com/problems/peeking-iterator/) | | | | | 285 | [Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst/) | | 这道题有意思,要多做几遍 | | | 286 | [Walls and Gates](https://leetcode.com/problems/walls-and-gates/) | | 多看两遍 | | | 287 | [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) | | | | | 288 | [Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/) | | 这题不难,多做两遍,题目意思容易理解错 | | | 289 | [Game of Life](https://leetcode.com/problems/game-of-life/) | | | | | 293 | [Flip Game](https://leetcode.com/problems/flip-game/) | | | | | 294 | [Flip Game II](https://leetcode.com/problems/flip-game-ii/) | | | | | 295 | [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) | | | | | 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | | 好题目,多做做,递归的非递归的 | | | 298 | [Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/) | | 多做三遍,尽可能简洁 | | | 299 | [Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/) | | | | | 300 | [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) | | | | | 301 | [Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) | | 比较难,多做几遍 | | | 302 | [Smallest Rectangle Enclosing Black Pixels](https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/) | | | | | 303 | [Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/) | | | | | 304 | [Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/) | | | | | 305 | [Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/) | | 这题多做几遍,经典的UF | | | 307 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | | 和#303, #304, #308定要多做几遍,掌握BIT | | | 308 | [Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/) | | | | | 309 | [Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) | | | | | 310 | [Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/) | | 这题多做几遍 | | | 311 | [Sparse Matrix Multiplication](https://leetcode.com/problems/sparse-matrix-multiplication/) | | | | | 312 | [Burst Balloons](https://leetcode.com/problems/burst-balloons/) | | | | | 313 | [Super Ugly Number](https://leetcode.com/problems/super-ugly-number/) | | | | | 314 | [Binary Tree Vertical Order Traversal](https://leetcode.com/problems/binary-tree-vertical-order-traversal/) | | | | | 315 | [Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | | | | | 316 | [Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/) | | | | | 317 | [Shortest Distance from All Buildings](https://leetcode.com/problems/shortest-distance-from-all-buildings/) | | 典型的bfs,多做两遍 | | | 319 | [Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | | | | | 320 | [Generalized Abbreviation](https://leetcode.com/problems/generalized-abbreviation/) | | 这题是典型的back tracking,多做几遍 | | | 322 | [Coin Change](https://leetcode.com/problems/coin-change/) | | | | | 323 | [Number of Connected Components in an Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/) | | 典型的图,多看两遍 | | | 324 | [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | | | | | 325 | [Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/) | | 这题思路有意思,多做几遍 | | | 328 | [Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/) | | | | | 329 | [Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | | 这题要多做几遍 | | | 332 | [Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) | | | | | 333 | [Largest BST Subtree](https://leetcode.com/problems/largest-bst-subtree/) | | 这道题虽然不难,但是折腾了很久,一定要多做 | | | 334 | [Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | | | | | 335 | [Self Crossing](https://leetcode.com/problems/self-crossing/) | | | | | 336 | [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | | | | | 337 | [House Robber III](https://leetcode.com/problems/house-robber-iii/) | | 建议再做两遍 | | | 339 | [Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum/) | | | | | 340 | [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/) | | 和#159类似 | | | 341 | [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/) | | 这题有点意思,多做两遍 | | | 344 | [Reverse String](https://leetcode.com/problems/reverse-string/) | | | | | 345 | [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | | | | | 346 | [Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream/) | | | | | 347 | [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | | | | | 349 | [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | | | | | 350 | [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | | | | | 351 | [Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/) | | 这题多做几遍 | | | 357 | [Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/) | | | | | 358 | [Rearrange String k Distance Apart](https://leetcode.com/problems/rearrange-string-k-distance-apart/) | | | | | 359 | [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/) | | 这题如果不考虑空间消耗的话其实很简单 | | | 361 | [Bomb Enemy](https://leetcode.com/problems/bomb-enemy/) | | 这题多做几遍,开始没思路 | | | 364 | [Nested List Weight Sum II](https://leetcode.com/problems/nested-list-weight-sum-ii/) | | | | | 366 | [Find Leaves of Binary Tree](https://leetcode.com/problems/find-leaves-of-binary-tree/) | | 这道题刚开始还没思路 | | | 367 | [Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square) | | | | | 369 | [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/) | | | | | 370 | [Range Addition](https://leetcode.com/problems/range-addition/) | | | | | 373 | [Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums/) | | | | | 374 | [Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/) | | | | | 375 | [Guess Number Higher or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii/) | | | | | 377 | [Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | | | | | 378 | [Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/) | | | | | 380 | [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | | 这道题很有意思,多做几遍 | | | 381 | [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | | | | | 382 | [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | | | | | 384 | [Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | | | | | 387 | [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | | | | | 388 | [Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | | 其实不难,乍看没思路,多做几遍 | | | 391 | [Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | | 这题很trick,多做两遍 | | | 393 | [UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | | 错了很多次,多做几遍 | | | 394 | [Decode String](https://leetcode.com/problems/decode-string/) | | 这题容易错,多做四遍 | | | 395 | [Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | | | | | 398 | [Random Pick Index](https://leetcode.com/problems/random-pick-index/) | | | | | 399 | [Evaluate Division](https://leetcode.com/problems/evaluate-division/) | | 这题多做几遍 | | | 401 | [Binary Watch](https://leetcode.com/problems/binary-watch/) | | | | | 404 | [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | | | | | 406 | [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | | 这题开始没思路,多做几遍 | | | 407 | [Trapping Rain Water II](https://leetcode.com/problems/trapping-rain-water-ii/) | | | | | 408 | [Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/) | | 多做两遍 | | | 409 | [Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) | | | | | 410 | [Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum) | | | | | 412 | [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | | | | | 413 | [Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | | | | | 418 | [Sentence Screen Fitting](https://leetcode.com/problems/sentence-screen-fitting/) | | 这题思路巧妙,多做几遍,常规思路超时 | | | 422 | [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | | | | | 425 | [Word Squares](https://leetcode.com/problems/word-squares/) | | 这题很典型,多做几遍 | | | 436 | [Find Right Interval](https://leetcode.com/problems/find-right-interval/) | | | | | 437 | [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | | 这道题错了很多遍,要重点关注 | | | 438 | [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | | 这道题非常经典,最优解法需要多做几遍,保证once bug free | | | 442 | [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | | | | | 445 | [Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/discuss/) | | | | | 448 | [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array) | | | | | 449 | [Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst) | | 和#297一样 | | | 450 | [Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/) | | 这题非常经典,值得多做十遍 | | | 451 | [Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/) | | | | | 459 | [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | | | | | 477 | [Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | | | | | 480 | [Sliding Window Median](https://leetcode.com/problems/sliding-window-median/) | | | | | 482 | [License Key Formatting](https://leetcode.com/problems/license-key-formatting/) | | | | | 483 | [Smallest Good Base](https://leetcode.com/problems/smallest-good-base/) | | | | | 485 | [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) | | | | | 487 | [Max Consecutive Ones II](https://leetcode.com/problems/max-consecutive-ones-ii/) | | | | | 501 | [Find Mode in Binary Search Tree](https://leetcode.com/problems/find-mode-in-binary-search-tree/) | | 不难,容易错,多做两次 | | | 508 | [Most Frequent Subtree Sum](https://leetcode.com/problems/most-frequent-subtree-sum/submissions/) | | | | | 513 | [Find Bottom Left Tree Value](https://leetcode.com/problems/find-bottom-left-tree-value/) | | | | | 515 | [Find Largest Value in Each Tree Row](https://leetcode.com/problems/find-largest-value-in-each-tree-row/) | | | | | 524 | [Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/) | | | | | 526 | [Beautiful Arrangement](https://leetcode.com/problems/beautiful-arrangement/) | | | | | 535 | [Encode and Decode TinyURL](https://leetcode.com/problems/encode-and-decode-tinyurl/) | | | | | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) | | | | | 541 | [Reverse String II](https://leetcode.com/problems/reverse-string-ii/) | | | | | 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | | 这题易错 | | | 547 | [Friend Circles](https://leetcode.com/problems/friend-circles/) | | | | | 557 | [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) | | | | | 560 | [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) | | | | | 563 | [Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/) | | | | | 564 | [Find the Closest Palindrome](https://leetcode.com/problems/find-the-closest-palindrome/) | | 此题暴力法即可 | | | 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/) | | | | | 606 | [Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/) | | | | | 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/) | | 很简单 | | | 621 | [Task Scheduler](https://leetcode.com/problems/task-scheduler/) | | | | | 637 | [Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/#/description) | | | | | 652 | [Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees/) | | 开始还没思路 | | | 653 | [Two Sum IV - Input is a BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/) | | | | | 654 | [Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/description/) | | | | | 669 | [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) | | | | | 681 | [Next Closest Time](https://leetcode.com/problems/next-closest-time/) | | 这题多做几遍 | | | 683 | [K Empty Slots](https://leetcode.com/problems/k-empty-slots/) | | | | | 684 | [Redundant Connection](https://leetcode.com/problems/redundant-connection/) | | | | | 687 | [Longest Univalue Path](https://leetcode.com/problems/longest-univalue-path/) | | | | | 695 | [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | | | | | 703 | [Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/) | | | | | 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/) | | | | | 814 | [Binary Tree Pruning](https://leetcode.com/problems/binary-tree-pruning/) | | | | | 819 | [Most Common Word](https://leetcode.com/problems/most-common-word/) | | | | | 843 | [Guess the Word](https://leetcode.com/problems/guess-the-word/) | | | | | 844 | [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/) | | | | | 849 | [Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person/) | | | | | 857 | [Minimum Cost to Hire K Workers](https://leetcode.com/problems/minimum-cost-to-hire-k-workers/) | | | | | 872 | [Leaf-Similar Trees](https://leetcode.com/problems/leaf-similar-trees/) | | | | | 889 | [Construct Binary Tree from Preorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/) | | | | | 904 | [Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/) | | | | | 929 | [Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses/) | | | |
628809537e93580079b9b394b1c2115670da3204
[ "Markdown", "Java" ]
32
Java
HUANGXUANKUN/Leetcode-Revision
b597128508f19ad6adf07fddefdf3dd127c0b32b
27f2ff0f8460a1ed0bd8a55f6b13abaa4d69b82d
refs/heads/master
<repo_name>CaoJiayuan/wepy-setup<file_sep>/src/components/base.js import wepy from 'wepy'; import Http from '../mixins/http'; export default class BaseComponent extends wepy.component { mixins = [Http]; } <file_sep>/src/pages/base.js import wepy from 'wepy'; import Http from '../mixins/http'; export default class BasePage extends wepy.page { mixins = [Http]; } <file_sep>/src/mixins/http.js import wepy from 'wepy'; import request from '../common/request'; export default class Http extends wepy.mixin { http = request; } <file_sep>/README.md # Wepy app #### [小程序组件化开发框架: Wepy](https://github.com/Tencent/wepy) #### [微信小程序组件化开发框架wepy开发资源汇总](https://github.com/aben1188/awesome-wepy) ### 开发 1. ```npm install``` 2. ```cp .env.example .env``` 3. 修改.env中的环境变量 4. 运行 ```npm run watch``` 或 ```npm run dev``` ### 开发者工具使用 1. 使用`微信开发者工具`新建项目,本地开发选择`dist`目录。 2. `微信开发者工具`-->详情-->关闭ES6转ES5。<font style="color:red">重要:漏掉此项会运行报错。</font> 3. `微信开发者工具`-->详情-->关闭上传代码时样式自动补全 <font style="color:red">重要:某些情况下漏掉此项会也会运行报错。</font> 4. `微信开发者工具`-->详情-->关闭代码压缩上传 <font style="color:red">重要:开启后,会导致真机computed, props.sync 等等属性失效。[#270](https://github.com/wepyjs/wepy/issues/270)</font> ### 功能 #### 使用包装后的request, 在src/common/request, page和component可以继承BasePage或BaseComponent, 使用this.http来调用接口,使用方法与axios类似 ```js import wepy from 'wepy' import request from './common/request'; // 使用包装后的request export default class extends wepy.app { ...... onLaunch() { request.interceptors.config = config => new Promise(resolve => { // config拦截器可返回Promise //设置api base url config.url = API_URL + config.url; resolve(config) }) request.interceptors.fail = (error, config) => { // do something return Promise.reject(error) } request.interceptors.success = (response, config) => { // do something return Promise.resolve(response) } request.get('/foo', data, config).then(response => console.log(response)).catch(error => console.log(error)) } } ......//component 里面 import BaseComponent from "./base"; export default class Foo extends BaseComponent { onLoad() { this.http.get('/foo', data, config).then(response => console.log(response)).catch(error => console.log(error)) } } ``` #### 使用状态管理(wepy-redux), 封装后的方法在src/store里面,如下counter实例 ```html <template> <view> Num: {{ num }} <button @tap="addNum">Add num</button> </view> </template> <script> import BaseComponent from "./base"; import {mapActions, mapGetters} from "../store"; export default class Counter extends BaseComponent { computed = { ...mapGetters({ num : 'counter.num' }) } methods = { ...mapActions({ addNum : 'counter.add' }) } onLoad() { } } </script> ``` <file_sep>/src/store/index.js import { getStore } from 'wepy-redux' let stores = {}; let states = undefined; let getters = undefined; let actions = undefined; /*** * * @param {Object} modules * @returns {Function} */ function createReducer(modules) { stores = modules; let initState = getStates(); getActions(); return function (state = initState, action) { let type = action.type; let payload = action.payload; let act = objectGet(actions, type); if (typeof act === 'function') { let partials = type.split('.'); let s = state; if (partials.length > 1) { s = state[partials[0]]; } if (payload.length > 1) { act.apply(s, [s, ...payload]) } else { act.apply(s, [s, payload]) } } return state; } } function getModules() { return stores; } function getStates() { if (states !== undefined) { return states; } states = {}; for (let module in stores) { states[module] = stores[module].state } return states; } function getGetters() { if (getters !== undefined) { return getters; } getters = {}; for (let module in stores) { getters[module] = stores[module].getters } return getters; } function getActions() { if (actions !== undefined) { return actions; } actions = {}; for (let module in stores) { actions[module] = stores[module].actions } return actions; } function mapStates(find) { let g = getGetters(); for (let key in find) { let get = find[key]; let fn = objectGet(g, get); find[key] = function (state) { let partials = get.split('.'); let s = state; if (partials.length > 1) { let namespace = partials[0] s = state[namespace]; } return fn(s) } } return find; } function mapActions (find) { let store = getStore(); for (let key in find) { let get = find[key]; find[key] = function (...args) { return store.dispatch({ type : get, payload : args }) } } return find; } function mapGetters(find) { let g = getGetters(); let store = getStore(); let state = store.getState() let subscribed = false for (let key in find) { let get = find[key]; let fn = objectGet(g, get); find[key] = function () { let partials = get.split('.'); let s = state; if (partials.length > 1) { let namespace = partials[0] s = state[namespace]; } let _this = this; if (!subscribed) { store.subscribe(() => { if (_this[key] !== objectGet(states, get)) { _this.$apply() } }) subscribed = true; } return fn(s) } } return find; } function objectGet(object, key, $default) { let clone = simpleClone(object); if (object.hasOwnProperty(key)) { return object[key]; } let partials = key.split('.'); let length = partials.length; for (let i = 0; i < length; i++) { clone = clone[partials[i]]; if (clone === undefined) { return $default } } return clone; } function simpleClone(state) { let copy = (this instanceof Array) ? [] : {}; for (let attr in state) { if (!state.hasOwnProperty(attr)) continue; copy[attr] = state[attr]; } return copy; }; module.exports = { createReducer, mapGetters, mapActions, mapStates, getModules }; <file_sep>/wepy.config.js var prod = process.env.NODE_ENV === 'production'; var dotenv = require('dotenv'); const _ = require('lodash'); module.exports = { wpyExt : '.wpy', eslint : false, compilers: { less : { 'compress': true }, /*sass: { outputStyle: 'compressed' },*/ babel: { 'sourceMap': true, 'presets' : [ 'env' ], 'plugins' : [ 'babel-plugin-transform-class-properties', 'transform-export-extensions', 'transform-decorators-legacy', 'transform-object-rest-spread', 'syntax-export-extensions' ] } }, plugins : {}, appConfig: { noPromiseAPI: ['createSelectorQuery'] } }; if (prod) { dotenv.config({path: '.env.prod'}); delete module.exports.compilers.babel.sourcesMap; // 压缩sass // module.exports.compilers['sass'] = {outputStyle: 'compressed'} // 压缩less module.exports.compilers['less'] = { compress: true }; // 压缩js module.exports.plugins = { uglifyjs: { filter: /\.js$/, config: {} }, imagemin: { filter: /\.(jpg|png|jpeg)$/, config: { 'jpg': { quality: 80 }, 'png': { quality: 80 } } }, filemin : { filter: /\.(json|wxml|xml)$/ }, } } else { dotenv.config({path: '.env'}); } module.exports.plugins.replace = [ { filter: /common\/env\.js$/, config: replaceEnvConfig() } ]; function replaceEnvConfig() { let config = []; _.forEach(process.env, (value, key) => { config.push({ find : new RegExp(`exports\.${key}\\s+=\\s+(.*);`), replace: function () { return `exports.${key}='${value}'`; } }) }); return config; }
8bac353e145f89181ee77ca6e6191f8a09550340
[ "JavaScript", "Markdown" ]
6
JavaScript
CaoJiayuan/wepy-setup
173e3bd878b8a8648f6fd9c487d183ddaa739f04
8311630466eb0087700032abdcdabed8f2e3e200
refs/heads/master
<file_sep>#!/usr/bin/python from test.framework.Task import Task from net.grinder.script import Test from net.grinder.script.Grinder import grinder from UserDict import UserDict import sys from xmlrpclib import * from xml.dom.minidom import parseString def log(message): """Log to the console, the message will include the thread ID""" grinder.logger.info(message) DATE = 0 RESULT = 1 ELAPSED = 2 XML_SIZE = 3 APP_ID = 4 TOTAL_RESULTS = 5 QUERY = 6 START_INDEX = 7 MAX_RESULTS = 8 SORT_ORDER = 9 OBJECT_TYPES = 10 NAMED_ARGUMENTS = 11 def toIntArray(s): if len(s) > 0: return [int(x) for x in s.split(',')] else: return None def toInt(s): if len(s) > 0: return int(s) else: return None def toBoolean(s): if s == '' or s == 'false': return False else: return True def toString(s): return s class VegaSearchTask(Task): def __init__(self): """Initialize properties of class""" Task.__init__(self) self.description = "Run a Vega Search" self.urlDict = {} self.taskId = Task.numberOfTasks '''self.index is used to index into the query array''' self.index = 0 '''self.query is one based and keeps track of the actual number of the query executed''' self.querynum = 1 self.testRun = "" self.nFaults = 0 self.hostID = grinder.properties["grinder.hostID"] '''the prodNightly saved query text file is opened for write and initializes the file for later append''' if self.hostID == "prodNightly": logDir = grinder.properties["grinder.logDirectory"] targetFile = logDir+"/query.txt" self.myQueryFile = open(targetFile, "w") self.myQueryFile.close() def initializeTask(self): """Initializes Instance Variables for this class. This method will be called by the Scenario object that this task belongs to.""" if(not self.urlDict.has_key("url0")): raise Exception(self.__class__.__name__ + ".urlDict is missing values for one or more of the following keys: [url0]. Please define them in the constructor for the parent Scenario.") else: self.parameters = \ { "appQuery": {"query":"myQuery"} } def writeToFile(self, text): #print "Writing query %d" % self.index filename = "%s-%d-page.xml" % ("xmlrpcSearch", self.querynum) logDir = grinder.properties["grinder.logDirectory"] targetFile = logDir+"/"+self.hostID+"/"+filename #print "Log folder and filename is %s" % logDir+"/"+hostID+"/"+filename try: myFile = open(targetFile, "w") s = text.encode('utf-8') print >> myFile, s myFile.close() except Exception, err: log('ERROR: %s\n' % str(err)) def writeSavedQuery(self, query): #print "Saving query %d" % self.index logDir = grinder.properties["grinder.logDirectory"] targetFile = logDir+"/query.txt" try: self.myQueryFile = open(targetFile, "a") print >> self.myQueryFile, query.encode('utf-8') self.myQueryFile.close() except Exception, err: log('ERROR: %s\n' % str(err)) def getProxy(self, url): #log("in getProxy with url: %s" % url) try: s = Test(self.querynum, "xmlrpc search").wrap(ServerProxy(url, None)) except: print "Service returned an error:", sys.exc_info()[0] return s def getQuery(self): #log("in getQuery") #log("before parameterizer") self.callParameterizingMethodFor("run") #log("after parameterizer") query = self.parameters["appQuery"]["query"] #log("searchFilter is : %s" % query) return query def buildArgs(self, argString): args={} searchArIDs=[] #print "argString is %s" % argString argKeyValues = argString.split('|') #should look like key:type:value for nameKeys in argKeyValues : #print "value string is %s " % nameKeys namekeyVals = nameKeys.split(':') if namekeyVals[1]== 'I' : args[namekeyVals[0]]= int(namekeyVals[2]) elif namekeyVals[1]== 'A' : valAr=namekeyVals[2].split(',') for valArVals in valAr : if valArVals != '' : searchArIDs.append(int(valArVals)) args[namekeyVals[0]]=searchArIDs elif namekeyVals[1]== 'B' : if namekeyVals[2] == "true": args[namekeyVals[0]]= True else: args[namekeyVals[0]]= False else: args[namekeyVals[0]]= namekeyVals[2] #print "returning from buildArgs" return args def run(self): #print "in postQuery" try: myterm = self.getQuery() if self.hostID == "prodNightly": lines = myterm["_raw"] """ term may contain multiple queries - we just want 1 """ query = lines.split("\n")[0] else: query = myterm #print "The length after raw of lines is %d" % len(lines) #print "VegaSearchTask query is : %s" % query parts = query.strip().split("\t") if len(parts) < 3: self.index+=1 return if "glgkeynote" in parts[QUERY].decode('utf-8').lower() or parts[QUERY].decode('utf-8').lower() == "technology" or parts[APP_ID] == "IndexSwitch": self.index+=1 return namedArgs = self.buildArgs(parts[NAMED_ARGUMENTS]) testRun = self.getProxy(url=self.urlDict["url0"]) #print '* DATE' + parts[DATE] #print '* RESULT' + parts[RESULT] #print '* ELAPSED' + parts[ELAPSED] #print '* XML_SIZE' + parts[XML_SIZE] #print '* APP_ID' + parts[APP_ID] #print '* TOTAL_RESULTS' + parts[TOTAL_RESULTS] #print '* QUERY' + parts[QUERY] #print '* START_INDEX' + parts[START_INDEX] #print '* MAX_RESULTS' + parts[MAX_RESULTS] #print '* SORT_ORDER' + parts[SORT_ORDER] #print '* OBJECT_TYPES' + parts[OBJECT_TYPES] #print '* NAMED_ARGUMENTS' + parts[NAMED_ARGUMENTS] result = testRun.SimpleSearch.execute(parts[QUERY], parts[APP_ID], toIntArray(parts[OBJECT_TYPES].strip()), 0, 100, int(parts[SORT_ORDER]), namedArgs, {}) '''runs other than a prodNightly will execute queries from the saved query file - create the file here''' if self.hostID == "prodNightly": self.writeSavedQuery(query) if self.hostID != "eclipse": self.writeToFile(result) self.index+=1 self.querynum+=1 except: print "Service returned an error:", sys.exc_info()[0] log("fault on query %d with raw string of %s : " % ( self.index, query )) self.nFaults+=1 self.index+=1 <file_sep>#!/usr/bin/env python from java.lang import * from settings import getKeyValue import com.splunk.Service as Service import com.splunk.Args as Args import com.splunk.ResultsReaderXml as ResultsReaderXml import sys hostname = getKeyValue("splunk","splunk_host") username = getKeyValue("splunk","username") userpw = getKeyValue("splunk","password") my_earliest_time = getKeyValue("splunk", "earliest_time") my_latest_time = getKeyValue("splunk", "latest_time") my_count = getKeyValue("splunk", "num_results") my_search = getKeyValue("splunk", "search_query") #print my_search def splunkSearch(hostID): service = splunkConnect() oneshotSearchArgs = Args.create() #print "value for hostID is %s" % hostID if hostID == "prodNightly": oneshotSearchArgs.put("earliest_time", "-23h@h") oneshotSearchArgs.put("latest_time", "now") else: oneshotSearchArgs.put("earliest_time", my_earliest_time) oneshotSearchArgs.put("latest_time", my_latest_time) oneshotSearchArgs.put("output_mode", "xml") oneshotSearchArgs.put("count", my_count) oneshotSearchQuery = my_search try: stream = service.oneshot(oneshotSearchQuery, oneshotSearchArgs) except Exception, err: sys.stderr.write('ERROR: %s\n' % str(err)) return 1 return splunkResults(stream) def splunkResults(stream): try: reader = ResultsReaderXml(stream) except Exception, err: sys.stderr.write('ERROR: %s\n' % str(err)) return 1 print "Retrieving data from splunk" searchFilters = [] while True: try: myData = reader.getNextEvent() if myData: searchFilters.append(myData) #print myData except Exception, err: break reader.close() print "Splunk reader closed" return searchFilters def splunkConnect(): loginArgs = Args.create() loginArgs.add("host", hostname) print "Connecting to splunkSearch with login args of %s %s %s" % (loginArgs, username, userpw) try: service = Service.connect(loginArgs) service.login(username, userpw) except Exception, err: sys.stderr.write('ERROR: %s\n' % str(err)) return 1 return service <file_sep># Task.py: Base class for all Tasks # Copyright (C) 2009 <NAME> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Base class for all Tasks. class Task: numberOfTasks = 0; def __init__(self): """Initialize properties of class""" self.urlDict = {} self.parameterizingMethods = {} Task.numberOfTasks += 1 def setUrlDict(self, urlDict): """Setter for urlDict property""" self.urlDict = urlDict def getUrlDict(self, urlDict): """Getter for urlDict property""" return self.urlDict def setUrl(self, key, value): """Sets value to 'value' of particular url in URL dict identified by key 'key'""" self.urlDict[key] = value def getUrl(self, key): """Returns value of particular url in URL dict identified by key 'key'""" return self.urlDict[key] def callParameterizingMethodFor(self, key): """Calls parameterizing method associated with page identified by key 'key'""" if(self.parameterizingMethods.has_key(key)): self.parameterizingMethods[key]() def setParameterizingMethodFor(self, key, value): """Sets parameterizing method associated with page identified by key 'key' to method in 'value'""" self.parameterizingMethods[key] = value def getParameterizingMethodFor(self, key): """Returns the parameterizing method associated with page identified by key 'key'""" return self.parameterizingMethods[key] def instrumentMethod(self, test, method_name): """Instrument a method with the given Test.""" unadorned = getattr(self.__class__, method_name) import new method = new.instancemethod(test.wrap(unadorned), None, self.__class__) setattr(self.__class__, method_name, method) <file_sep>from net.grinder.script.Grinder import grinder from test.framework.Scenario import Scenario from test.tasks.search_vega import VegaSearchTask from splunkConnect import splunkSearch from settings import getKeyValue hostID = grinder.properties["grinder.hostID"] if "prod" in hostID: xmlrpc_search_url = getKeyValue("xmlrpc", "url1") else: xmlrpc_search_url = getKeyValue("xmlrpc", "url0") """ Make a new scenario """ myScenario = Scenario(("Vega Search"), {"url0":xmlrpc_search_url}); searchTask = VegaSearchTask.VegaSearchTask() if hostID == "prodNightly": """ Connect to splunk and get last 24 hours of queries """ searchFilters = splunkSearch( hostID ) else: """ Retrieve queries from the prodNightly saved query file """ logDir = grinder.properties["grinder.logDirectory"] searchFilters = [ line.strip() for line in file(logDir+"/query.txt") ] setattr(searchTask, "searchFilters", searchFilters) def parameterizeSearch(self=searchTask): #print "in parameterizeSearch" #index = random.randrange(0,lineCount) #print "index is %d" % index searchFilter = self.searchFilters[self.index]; #print "search Filter is %s" % searchFilter; #queryString = searchFilter["query"]; #print "query string is %s" % queryString; self.parameters["appQuery"]["query"] = searchFilter; #print "returning from parameterizeSearch" searchTask.setParameterizingMethodFor("run", parameterizeSearch) myScenario.addTask(searchTask) class TestRunner: def __init__(self): grinder.properties["grinder.runs"] = str(len(searchFilters)) def __call__(self): myScenario.run()<file_sep>#!/usr/bin/env python import optparse import sys import os import unittest from testscenarios import TestWithScenarios import xmlrunner def get_args(): parser = optparse.OptionParser() parser.add_option("-b", "--beforeLog", action="store", type="string", dest="beforeLog", default="devNightly-0-data.log",help="name of grinder baseline run data.log file.") parser.add_option("-c", "--afterLog", action="store", type="string", dest="afterLog", default="devDeploy-0-data.log", help="name of grinder change run data.log file.") parser.add_option("-l", "--logDir", action="store", type="string", dest="logDir", default="/Users/dgriffis/grinder/MyTests/Search_xmlrpc/log/", help="directory containing grinder data.log files.") return parser def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) LogHeaders = enum('Thread', 'Run', 'Test', 'Start_time', 'Test_time', 'Errors') def buildArray(logDir, fileName): fileTarget = os.path.join(logDir, fileName) #print "Target file is %s" % fileTarget try: array = [ line.strip() for line in file(fileTarget) ] except Exception, err: sys.stderr.write('ERROR: %s\n' % str(err)) sys.exit() return array def _buildScenarios( numoftests): #scenario = [('Row1', dict(param='1')), # ('Row2', dict(param='2')) # ] scenario = [] for x in range(0, numoftests): scenarioName = "scenario_"+str(x) scenario.append( (scenarioName, dict(param=x) )) return scenario class Test(TestWithScenarios): changeAr = [] baselineAr = [] parser = get_args() (options, args) = parser.parse_args() #print "arg values are %s" % args #print "options are %s" % options logDir = options.logDir #print "logdir is %s" % logDir beforeLog = options.beforeLog #print "beforeLog is %s" % beforeLog afterLog = options.afterLog #print "afterLog is %s" % afterLog baselineAr = buildArray(logDir, beforeLog) changeAr = buildArray(logDir, afterLog) scenarios = _buildScenarios( len(baselineAr) ) #print scenarios def setUp(self): self.assertTrue( len(self.baselineAr) == len(self.changeAr) ) def tearDown(self): pass def testLogFileTestRunTimesComparable(self): blLine = self.baselineAr[self.param] chLine = self.changeAr[self.param] blData = blLine.split(",") chData = chLine.split(",") testNum = blData[LogHeaders.Test] if testNum.strip() == "Test": return blVal = int(blData[LogHeaders.Test_time]) chVal = int(chData[LogHeaders.Test_time]) if blVal == 0 and chVal == 0: return pctDiff = 100 - ( float(chVal) / float(blVal) * 100 ) if blVal > chVal else 100 - ( float(blVal) / float(chVal) * 100 ) self.assertLessEqual( pctDiff , 50 ) if __name__ == "__main__": jtlFolder = "/Users/Shared/Jenkins/Home/jobs/Search_xmlrpc/workspace/test-reports" suite = unittest.TestLoader().loadTestsFromTestCase(Test) unittest.TextTestRunner(verbosity=2).run(suite) #xmlrunner.XMLTestRunner(output=jtlFolder).run(suite) <file_sep>#!/usr/bin/env python import yaml def getSettings(): settings_file = open("settings.yaml", 'r') settings = yaml.load(settings_file) settings_file.close() return settings def getKeyValue(myHive, myKey): settings = getSettings() value = "" for (key, item) in settings.items(): #print key if key == myHive: for i in item: #print i for k in i: if k == myKey: value = i[k] break return value def main(): print getKeyValue("splunk", "earliest_time") if __name__ == "__main__": main() <file_sep>#!/usr/bin/env python import os import optparse from xml.dom import minidom import unittest from testscenarios import TestWithScenarios import xmlrunner tagValues = {"councilMemberResult":"councilMemberId", "clientContactResult":"PERSON_ID"} '''values lower than the testBoudary will be flagged as fails''' testBoundary = 0.975 def get_args(): parser = optparse.OptionParser() parser.add_option("-b", "--beforeFolder", action="store", type="string", dest="beforeFolder", default="prodNightly",help="name of folder containing baseline files.") parser.add_option("-c", "--afterFolder", action="store", type="string", dest="afterFolder", default="prodDeploy", help="name of folder containing change files.") parser.add_option("-l", "--logDir", action="store", type="string", dest="logDir", default="/Users/dgriffis/grinder/MyTests/Search_xmlrpc/log/", help="root log directory.") return parser def _getXMLText(element): nodelist = element.childNodes rc = [] for node in nodelist: if node.nodeType == node.TEXT_NODE: rc.append(node.data) return ''.join(rc) def _rank_dists(ranks1, ranks2): """Finds the difference between the values in ranks1 and ranks2 for keys present in both dicts. If the arguments are not dicts, they are converted from (key, rank) sequences. """ ranks1 = dict(ranks1) ranks2 = dict(ranks2) for k, v1 in ranks1.iteritems(): try: yield k, v1 - ranks2[k] except KeyError: pass #@profile def _spearman_correlation(ranks1, ranks2): """Returns the Spearman correlation coefficient for two rankings, which should be dicts or sequences of (key, rank). The coefficient ranges from -1.0 (ranks are opposite) to 1.0 (ranks are identical), and is only calculated for keys in both rankings (for meaningful results, remove keys present in only one list before ranking).""" n = 0 res = 0 #print "ranks1 is",ranks1 #print "ranks2 is",ranks2 ranks1 = sorted(ranks1, key=lambda k: -k[1]) ranks2 = sorted(ranks2, key=lambda k: -k[1]) ranks1 = [(t[0], ix) for ix, t in enumerate(ranks1)] ranks2 = [(t[0], ix) for ix, t in enumerate(ranks2)] for k, d in _rank_dists(ranks1, ranks2): res += d * d n += 1 try: return 1 - (6 * float(res) / (n * (n * n - 1))) except ZeroDivisionError: # Result is undefined if only one item is ranked return 0.0 def _buildRankArray( cms, tagName ): ranking = 1.0 rank = [] for i in cms: id = int(_getXMLText(i.getElementsByTagName(tagName)[0])) rank.append((id,ranking)) ranking+=1.0 return rank def _getTagItems(results, tagItem): return results[0].getElementsByTagName(tagItem) def _buildRanksArrays(fileFolder, testFile): #print fileFolder #print testFile ranks = [(0,0), (1,1)] xmldoc = minidom.parse( os.path.join(fileFolder, testFile ) ) results = xmldoc.getElementsByTagName("results") '''Should have at least 10 results to be relevant''' if int(results[0].getAttribute("count"))<10: return ranks '''search will return results tagged as councilMemberResult or clientContactResult ''' tagName='' cms='' for key in tagValues.keys(): tagItem = key tagName = tagValues[key] cms = _getTagItems(results, tagItem) if len(cms) > 0: break if len(cms) == 0: return ranks ranks1 = _buildRankArray(cms, tagName) #print ranks1 return ranks1 def _buildScenarios(beforeFolder): #scenario = [('scenariotest1', dict(param='xmlrpcSearch-0-page.xml')), # ('scenariotest2', dict(param='xmlrpcSearch-1-page.xml')) # ] scenario = [] for r,d,f in os.walk(beforeFolder): for myFile in f: scenarioName = "scenario_"+myFile[:-4] scenario.append( (scenarioName, dict(param=myFile) )) return scenario class Test(TestWithScenarios): ''' subclass of TestWithScenarios allows display in Jenkins of the unit test testSpearmanCoefficient() together with the filename of the file being tested. ''' ranks1 = [] ranks2 = [] parser = get_args() (options, args) = parser.parse_args() #print "arg values are %s" % args #print "options are %s" % options logDir = options.logDir #print "logdir is %s" % logDir beforeFolder = options.beforeFolder #print "beforeFolder is %s" % beforeFolder afterFolder = options.afterFolder #print "afterFolder is %s" % afterFolder scenarios = _buildScenarios( os.path.join(logDir, beforeFolder )) def setUp( self ): #print 'param=', self.param self.ranks1 = _buildRanksArrays( os.path.join(self.logDir, self.beforeFolder ), self.param ) self.ranks2 = _buildRanksArrays( os.path.join(self.logDir, self.afterFolder ), self.param ) def tearDown(self): pass def testSpearmanCoefficient(self): result = _spearman_correlation(self.ranks1, self.ranks2) #if result < 0.975: # print "spearman for file %s is %f" % ( self.param, result ) # print "ranks1 is",self.ranks1 # print "ranks2 is",self.ranks2 self.assertTrue( result >= testBoundary ) if __name__ == '__main__': #ranks1 = [] #ranks2 = [] #ranks1= [('a', 2.5), ('b', 3.5), ('c', 3.0), ('d', 3.5)] #ranks2= [('c', 3.5), ('b', 4.5), ('e', 1.0), ('d', 1.5)] #ranks1= [(219378, 1.0), (510847, 2.0), (489352, 6.0), (215446, 5.0), (166881, 3.0), (418280, 4.0), (256081, 7.0), (248372, 8.0)] #ranks2= [(219378, 6.0), (510847, 1.0), (489352, 3.0), (215446, 4.0), (166881, 5.0), (418280, 3.0), (256081, 2.0), (248372, 7.0)] #print spearman_correlation(ranks1, ranks2) parser = get_args() (options, args) = parser.parse_args() logDir = options.logDir beforeFolder = options.beforeFolder if "prod" in beforeFolder: jtlFolder = "/Users/Shared/Jenkins/Home/jobs/Search_xmlrpc_runspearman_prod_deploy/workspace/test-reports" else: jtlFolder = "/Users/Shared/Jenkins/Home/jobs/Search_xmlrpc_runspearman_dev_deploy/workspace/test-reports" suite = unittest.TestLoader().loadTestsFromTestCase(Test) #unittest.TextTestRunner(verbosity=2).run(suite) xmlrunner.XMLTestRunner(output=jtlFolder).run(suite)<file_sep># Scenario.py: Scenario class in the torqueo framework. # Copyright (C) 2009 <NAME> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import warnings class Scenario: def __init__(self, description, urlDict): if(len(urlDict.keys()) == 0): raise Exception("Cannot set " + self.__class__.__name__ + ".urlDict to an empty dictionary.") else: self.description = description self.urlDict = urlDict self.tasks = [] def addTask(self, task): if(hasattr(task, "setUrlDict")): task.setUrlDict(self.urlDict) else: raise Exception(task.__class__.__name__ + " does not implement setUrlDict()!") if(hasattr(task, "initializeTask")): task.initializeTask() else: raise Exception(task.__class__.__name__ + " does not implement initializeTask()!") if(hasattr(task, "run")): self.tasks.append(task) else: raise Exception(task.__class__.__name__ + " does not implement run()!") def setUrlDict(self, url): warnings.warn("Scenario.urlDict is a read-only property that can only be initialized in the constructor.") def getUrlDict(self): return self.urlDict def setUrl(self, key, value): warnings.warn("Cannot modify Scenario.urlDict because it is a read-only property") def getUrl(self, key): return self.urlDict[key] urlDict = property(getUrlDict, setUrlDict) def run(self): for task in self.tasks: if(hasattr(task, "run")): task.run() else: raise Exception(task.__class__.__name__ + " does not implement run()!")
4e99ef9acaef4c5889e65f121a3d0f49d2a2ed0e
[ "Python" ]
8
Python
dgriffis/grinderframework
8aca4d5e1a8cf3541489a554c8c3e897f69ffb49
d73e27c68c87958c7032b5770df4b9f72e05113e
refs/heads/master
<repo_name>baba-s/StagePowerPointCreator<file_sep>/README.md # StagePowerPointCreator ## 準備 ```python pip install python-pptx pip install docopt ``` ## 使用例 ```sh python stagePowerPointCreator.py ^ --input-path 【*.png】 ^ --output-path stage.pptx ^ --column 5 ^ --start-x 0.5 ^ --start-y 0.5 ^ --offset-x 4.75 ^ --offset-y 8 ^ --height 7.5 ``` <file_sep>/stagePowerPointCreator.py """ Usage: hoge.py -h hoge.py (--input-path <input-path>) (--output-path <output-path>) (--column <column>) (--start-x <start-x>) (--start-y <start-y>) (--offset-x <offset-x>) (--offset-y <offset-y>) (--height <height>) Options: -h --help Show this screen. --input-path <input-path> Input image folder. --output-path <output-path> Output pptx file path. --column <column> Image column. --start-x <start-x> Image start x. --start-y <start-y> Image start y. --offset-x <offset-x> Image offset x. --offset-y <offset-y> Image offst y. --height <height> Image height. """ from pptx import Presentation from pptx.util import Pt, Inches from glob import glob from docopt import docopt def Centis(length): centi = Inches(length / 2.54) return centi if __name__ == '__main__': args = docopt(__doc__) # Power Point のインスタンス ppt = Presentation() # 白紙レイアウト blank_slide_layout = ppt.slide_layouts[6] # 画像の配置を開始する位置 start_x = Centis(float(args["--start-x"])) start_y = Centis(float(args["--start-y"])) # 画像の配置間隔 offset_x = Centis(float(args["--offset-x"])) offset_y = Centis(float(args["--offset-y"])) image_height = Centis(float(args["--height"])) # スライドに貼り付けるすべての画像ファイル files = glob(args["--input-path"]) fileCount = len(files) # 作成するスライドの数 slide_count = int(len(files) / 10) + 1 column = int(args["--column"]) for i in range(slide_count): # スライドを作成 slide = ppt.slides.add_slide(blank_slide_layout) for j in range(10): # 貼り付ける画像の取得 index = i * 10 + j if fileCount <= index: continue file = files[index] # 画像を貼り付ける位置 x = start_x + j % column * offset_x y = start_y + int(j / column) * offset_y # 画像を貼り付ける slide.shapes.add_picture(file, x, y, height=image_height) # .pptx ファイルを保存 ppt.save(args["--output-path"])
cb68741a5aef96c46baf48b2d0fe301b9f244dcb
[ "Markdown", "Python" ]
2
Markdown
baba-s/StagePowerPointCreator
b8e1e632cb000c497dea1956fb97a825686d27c4
6a65327c9e39c0b1a702bbb4b9d1b26634402b86
refs/heads/master
<repo_name>anjinkristou/Expenses<file_sep>/recordmodel.h #ifndef RECORDMODEL_H #define RECORDMODEL_H #include <QAbstractListModel> #include <QPointer> class Sheet; class RecordModel : public QAbstractListModel { Q_OBJECT Q_PROPERTY(Sheet* sheet READ sheet WRITE setSheet NOTIFY sheetChanged) public: enum RecordRole { PurposeRole = Qt::UserRole, TransactionDateRole, ServiceProviderRole, DescriptionRole, AmountRole }; Q_ENUM(RecordRole) explicit RecordModel(QObject *parent = nullptr); int rowCount(const QModelIndex & = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QHash<int, QByteArray> roleNames() const override; Sheet* sheet() const; public slots: void setSheet(Sheet *sheet); signals: void sheetChanged(Sheet* sheet); private: QPointer<Sheet> m_sheet; }; #endif // RECORDMODEL_H <file_sep>/sheetstatus.h #ifndef SHEETSTATUS_H #define SHEETSTATUS_H #include <QObject> #include <QString> class DataManager; class SheetStatus : public QObject { Q_OBJECT Q_PROPERTY(DataManager* dataManager READ dataManager WRITE setDataManager NOTIFY dataManagerChanged) Q_PROPERTY(int id READ id WRITE setId NOTIFY idChanged) Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) public: explicit SheetStatus(QObject *parent = nullptr); DataManager* dataManager() const; static QString tableName() { return "statuses"; } inline int id() const { return m_id; } inline QString name() const { return m_name; } signals: void dataManagerChanged(DataManager* dataManager); void idChanged(int id); void changed(); void nameChanged(QString name); public slots: void setDataManager(DataManager* dataManager); void setId(int id); void setName(QString name); private: DataManager* m_dataManager; int m_id; QString m_name; void updateFields(); }; #endif // SHEETSTATUS_H <file_sep>/datamanager.h #ifndef DATAMANAGER_H #define DATAMANAGER_H #include <QObject> #include <QSqlDatabase> #include <functional> #include <QVariant> #include <QVariantMap> #include <QString> class DataManager : public QObject { Q_OBJECT public: explicit DataManager(const QString &location, QObject *parent = nullptr); virtual ~DataManager(); void forEach(const QString &table, const std::function<void(int)> &func) const; void forEachDenpendent(const QString &table, const QString &field, const QVariant &value, const std::function<void(int)> &func) const; int add(const QString &table); void remove(const QString &table, int id); QVariantMap fields(const QString &table, int id, const QStringList &fields); void setField(const QString &table, int id, const QString &field, const QVariant &value); private: QSqlDatabase m_database; void createDatabase(); }; #endif // DATAMANAGER_H <file_sep>/sheetmodel.h #ifndef SHEETMODEL_H #define SHEETMODEL_H #include <QAbstractListModel> #include <QPointer> class SheetCollection; class SheetModel : public QAbstractListModel { Q_OBJECT Q_PROPERTY(SheetCollection* sheetCollection READ sheetCollection WRITE setSheetCollection NOTIFY sheetCollectionChanged) public: enum SheetRole { NameRole = Qt::UserRole, submittedDateRole, StatusRole, RecordCountRole, TotalAmountRole }; Q_ENUM(SheetRole) explicit SheetModel(QObject *parent = nullptr); int rowCount(const QModelIndex & = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QHash<int, QByteArray> roleNames() const override; SheetCollection* sheetCollection() const; public slots: void setSheetCollection(SheetCollection *collection); signals: void sheetCollectionChanged(SheetCollection* sheetCollection); private: QPointer<SheetCollection> m_sheetCollection; }; #endif // SHEETMODEL_H <file_sep>/record.cpp #include "record.h" #include <QVariantMap> #include "datamanager.h" Record::Record(QObject *parent) : QObject(parent) , m_id(-1) , m_amount(0) , m_purpose(0) , m_transactionDate(QDate::currentDate()) , m_serviceProvider("No peovider") , m_description("No description") , m_dataManager(nullptr) { connect(this, &Record::amountChanged, this, &Record::changed); connect(this, &Record::purposeChanged, this, &Record::changed); } DataManager *Record::dataManager() const { return m_dataManager; } void Record::setAmount(qreal amount) { qWarning("Floating point comparison needs context sanity check"); if (qFuzzyCompare(m_amount, amount)) return; m_amount = amount; if(m_dataManager){ m_dataManager->setField(tableName(), m_id, "amount", m_amount); } emit amountChanged(m_amount); } void Record::setPurpose(int purpose) { if (m_purpose == purpose) return; m_purpose = purpose; emit purposeChanged(m_purpose); } void Record::setTransactionDate(const QDate &transactionDate) { if (m_transactionDate == transactionDate) return; m_transactionDate = transactionDate; emit transactionDateChanged(m_transactionDate); } void Record::setServiceProvider(const QString &serviceProvider) { if (m_serviceProvider == serviceProvider) return; m_serviceProvider = serviceProvider; emit serviceProviderChanged(m_serviceProvider); } void Record::setDescription(const QString &description) { if (m_description == description) return; m_description = description; emit descriptionChanged(m_description); } void Record::setDataManager(DataManager *dataManager) { if (m_dataManager == dataManager) return; m_dataManager = dataManager; updateFields(); emit dataManagerChanged(m_dataManager); } void Record::updateFields() { if(m_dataManager){ QStringList fileds; fileds << "amount"; QVariantMap props = m_dataManager->fields(tableName(), m_id, fileds); m_amount = props["amount"].toReal(); } } void Record::setId(int id) { if (m_id == id) return; m_id = id; emit idChanged(m_id); } <file_sep>/sheetcollection.h #ifndef SHEETCOLLECTION_H #define SHEETCOLLECTION_H #include <QObject> #include <QVector> #include <QPointer> class Sheet; class DataManager; class SheetCollection : public QObject { Q_OBJECT Q_PROPERTY(DataManager* dataManager READ dataManager WRITE setDataManager NOTIFY dataManagerChanged) public: explicit SheetCollection(DataManager *dataManager = nullptr, QObject *parent = nullptr); void addSheet(Sheet *sheet); int sheetCount() const; Q_INVOKABLE Sheet *sheetAt(int index) const; Q_INVOKABLE Sheet *addSheet(); DataManager* dataManager() const; signals: void dataManagerChanged(DataManager* dataManager); void sheetChanged(int index); void beginInsert(int first, int last); void endInsert(); void beginRemove(int first, int last); void endRemove(); void beginReset(); void endReset(); public slots: void removeAt(int index); void setDataManager(DataManager* dataManager); private: QVector<Sheet *> m_sheets; QPointer<DataManager> m_dataManager; void loadSheets(); }; #endif // SHEETCOLLECTION_H <file_sep>/sheetstatuscollection.cpp #include "sheetstatuscollection.h" #include "datamanager.h" #include "sheetstatus.h" SheetStatusCollection::SheetStatusCollection(DataManager *dataManager, QObject *parent) : QObject(parent) , m_dataManager(dataManager) { if(m_dataManager) { loadStatus(); } if (m_statuses.size() == 0){ SheetStatus *s; s = new SheetStatus(this); addSheetStatus(s); s->setName("Unsubmitted"); s = new SheetStatus(this); addSheetStatus(s); s->setName("Submitted"); s = new SheetStatus(this); addSheetStatus(s); s->setName("Verified"); s = new SheetStatus(this); addSheetStatus(s); s->setName("Reimbursed"); } } DataManager *SheetStatusCollection::dataManager() const { return m_dataManager; } int SheetStatusCollection::sheetStatusCount() const { return m_statuses.size(); } SheetStatus *SheetStatusCollection::sheetStatusAt(int index) const { return m_statuses.at(index); } void SheetStatusCollection::setDataManager(DataManager *dataManager) { if (m_dataManager == dataManager) return; emit beginReset(); m_dataManager = dataManager; qDeleteAll(m_statuses); m_statuses.clear(); endReset(); loadStatus(); emit dataManagerChanged(m_dataManager); } void SheetStatusCollection::loadStatus() { if(m_dataManager){ DataManager *manager = m_dataManager; m_dataManager->forEach(SheetStatus::tableName(), [this, manager](int id){ SheetStatus *s = new SheetStatus(this); s->setId(id); s->setDataManager(manager); addSheetStatus(s); }); } } void SheetStatusCollection::addSheetStatus(SheetStatus *status) { if(status){ int index = m_statuses.size(); beginInsert(index, index); m_statuses.append(status); endInsert(); connect(status, &SheetStatus::changed, this, [index, this](){ emit this->sheetStatusChanged(index); }); if(status->id() < 0 && m_dataManager){ int id = m_dataManager->add(SheetStatus::tableName()); status->setId(id); status->setDataManager(m_dataManager); } } } <file_sep>/sheetstatus.cpp #include "sheetstatus.h" #include "datamanager.h" SheetStatus::SheetStatus(QObject *parent) : QObject(parent) , m_dataManager(nullptr) , m_id(-1) { connect(this, &SheetStatus::nameChanged, this, &SheetStatus::changed); } DataManager *SheetStatus::dataManager() const { return m_dataManager; } void SheetStatus::setDataManager(DataManager *dataManager) { if (m_dataManager == dataManager) return; m_dataManager = dataManager; updateFields(); emit dataManagerChanged(m_dataManager); } void SheetStatus::setId(int id) { if (m_id == id) return; m_id = id; emit idChanged(m_id); } void SheetStatus::setName(QString name) { if (m_name == name) return; m_name = name; if(m_dataManager){ m_dataManager->setField(tableName(), m_id, "name", m_name); } emit nameChanged(m_name); } void SheetStatus::updateFields() { if(m_dataManager){ QStringList fileds; fileds << "name"; QVariantMap props = m_dataManager->fields(tableName(), m_id, fileds); m_name = props["name"].toString(); } } <file_sep>/main.cpp #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QQuickStyle> #include <QStandardPaths> #include <QtDebug> #include "sheet.h" #include "record.h" #include "sheetcollection.h" #include "sheetmodel.h" #include "recordmodel.h" #include "datamanager.h" #include "sheetstatus.h" #include "sheetstatuscollection.h" #include "sheetstatusmodel.h" void registerTypes() { qmlRegisterType<SheetStatus>("com.kristou.expense", 1, 0, "SheetStatus"); qmlRegisterType<SheetStatusModel>("com.kristou.expense", 1, 0, "SheetStatusModel"); qmlRegisterType<SheetStatusCollection>("com.kristou.expense", 1, 0, "SheetStatusCollection"); qmlRegisterType<Sheet>("com.kristou.expense", 1, 0, "Sheet"); qmlRegisterType<SheetModel>("com.kristou.expense", 1, 0, "SheetModel"); qmlRegisterType<SheetCollection>("com.kristou.expense", 1, 0, "SheetCollection"); qmlRegisterType<Record>("com.kristou.expense", 1, 0, "Record"); qmlRegisterType<RecordModel>("com.kristou.expense", 1, 0, "RecordModel"); } int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QQuickStyle::setStyle("Material"); QGuiApplication app(argc, argv); DataManager manager(QStandardPaths::writableLocation(QStandardPaths:: AppDataLocation)); //Test SheetStatusCollection sheetStatusCollection(&manager); SheetCollection sheetCollection(&manager); // collection.setDataManager(&manager); registerTypes(); QQmlApplicationEngine engine; QQmlContext *ctxt = engine.rootContext(); ctxt->setContextProperty("sheetCollection", QVariant::fromValue(&sheetCollection)); ctxt->setContextProperty("sheetStatusCollection", QVariant::fromValue(&sheetStatusCollection)); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); } <file_sep>/sheetmodel.cpp #include "sheetmodel.h" #include "sheetcollection.h" #include "sheet.h" #include <QtDebug> SheetModel::SheetModel(QObject *parent) : QAbstractListModel(parent) , m_sheetCollection(nullptr) { } int SheetModel::rowCount(const QModelIndex &) const { return m_sheetCollection ? m_sheetCollection->sheetCount() : 0; } QVariant SheetModel::data(const QModelIndex &index, int role) const { if (index.row() < rowCount() && m_sheetCollection) switch (role) { case NameRole: return m_sheetCollection->sheetAt(index.row())->name(); case submittedDateRole: return m_sheetCollection->sheetAt(index.row())->submittedDate().toString("yyyy/MM/dd"); case StatusRole: return m_sheetCollection->sheetAt(index.row())->status(); case RecordCountRole: return m_sheetCollection->sheetAt(index.row())->recordCount(); case TotalAmountRole: return m_sheetCollection->sheetAt(index.row())->totalAmount(); default: return QVariant(); } return QVariant(); } QHash<int, QByteArray> SheetModel::roleNames() const { static const QHash<int, QByteArray> roles { { NameRole, "name" }, { submittedDateRole, "submitted_date" }, { StatusRole, "status" }, { RecordCountRole, "record_count" }, { TotalAmountRole, "total_amount" } }; return roles; } SheetCollection *SheetModel::sheetCollection() const { return m_sheetCollection; } void SheetModel::setSheetCollection(SheetCollection *collection) { if(m_sheetCollection != collection){ beginResetModel(); if(m_sheetCollection) m_sheetCollection->disconnect(this); m_sheetCollection = collection; if(collection){ connect(collection, &SheetCollection::sheetChanged, this, [this](int index){ emit this->dataChanged(this->index(index, 0), this->index(index, 0)); }); connect(collection, &SheetCollection::beginInsert, this, [this](int first, int last){ emit this->beginInsertRows(QModelIndex(), first, last); }); connect(collection, &SheetCollection::endInsert, this, &SheetModel::endInsertRows); connect(collection, &SheetCollection::beginRemove, this, [this](int first, int last){ emit this->beginRemoveRows(QModelIndex(), first, last); }); connect(collection, &SheetCollection::endRemove, this, &SheetModel::endRemoveRows); connect(collection, &SheetCollection::beginReset, this, &SheetModel::beginResetModel); connect(collection, &SheetCollection::endReset, this, &SheetModel::endResetModel); } endResetModel(); emit sheetCollectionChanged(collection); } } <file_sep>/sheetstatuscollection.h #ifndef SHEETSTATUSCOLLECTION_H #define SHEETSTATUSCOLLECTION_H #include <QObject> #include <QVector> class DataManager; class SheetStatus; class SheetStatusCollection : public QObject { Q_OBJECT Q_PROPERTY(DataManager* dataManager READ dataManager WRITE setDataManager NOTIFY dataManagerChanged) public: explicit SheetStatusCollection(DataManager *dataManager = nullptr, QObject *parent = nullptr); DataManager* dataManager() const; int sheetStatusCount() const; SheetStatus *sheetStatusAt(int index) const; signals: void dataManagerChanged(DataManager* dataManager); void beginInsert(int first, int last); void endInsert(); void beginRemove(int first, int last); void endRemove(); void beginReset(); void endReset(); void sheetStatusChanged(int index); public slots: void setDataManager(DataManager* dataManager); void addSheetStatus(SheetStatus *status); private: DataManager* m_dataManager; QVector<SheetStatus *> m_statuses; void loadStatus(); }; #endif // SHEETSTATUSCOLLECTION_H <file_sep>/datamanager.cpp #include "datamanager.h" #include <QSqlQuery> #include <QtDebug> #include <QSqlError> #include <QDir> DataManager::DataManager(const QString &location, QObject *parent) : QObject(parent) , m_database(QSqlDatabase::addDatabase("QSQLITE")) { QDir(location).mkdir(location); QString dbLocation = location + "/sheets.db"; m_database.setDatabaseName(dbLocation); qCritical() << "Db:" << dbLocation; if(m_database.open()){ createDatabase(); } else { qDebug() << "Database error"; } } DataManager::~DataManager() { if(m_database.isOpen()) m_database.close(); } void DataManager::forEach(const QString &table, const std::function<void(int)> &func) const { QSqlQuery query(m_database); query.exec(QString("SELECT id FROM %0").arg(table)); while (query.next()) { func(query.value("id").toInt()); } } void DataManager::forEachDenpendent(const QString &table, const QString &field, const QVariant &value, const std::function<void (int)> &func) const { QSqlQuery query(m_database); query.prepare(QString("SELECT id FROM %0 WHERE %1 = :value").arg(table).arg(field)); query.bindValue(":value", value); query.exec(); while (query.next()) { func(query.value("id").toInt()); } } int DataManager::add(const QString &table) { QSqlQuery query(m_database); query.prepare(QString("INSERT INTO %0 DEFAULT VALUES").arg(table)); query.exec(); return query.lastInsertId().toInt(); } void DataManager::remove(const QString &table, int id) { QSqlQuery query(m_database); query.prepare(QString("DELETE FROM %0 WHERE id = :id ").arg(table)); query.bindValue(":id", id); query.exec(); } QVariantMap DataManager::fields(const QString &table, int id, const QStringList &fields) { QSqlQuery query(m_database); query.prepare(QString("SELECT * FROM %0 WHERE id = :id ").arg(table)); query.bindValue(":id", id); query.exec(); query.next(); QVariantMap result; foreach (const QString &prop, fields) { result[prop] = query.value(prop); } return result; } void DataManager::setField(const QString &table, int id, const QString &field, const QVariant &value) { QSqlQuery query(m_database); query.prepare(QString("UPDATE %0 SET %1 = :%1 WHERE id = :id").arg(table).arg(field)); query.bindValue(":id", id); query.bindValue(QString(":%0").arg(field), value); query.exec(); } void DataManager::createDatabase() { QSqlQuery query(m_database); query.exec("CREATE TABLE IF NOT EXISTS statuses (id INTEGER UNIQUE PRIMARY KEY, name VARCHAR(30))"); query.exec("CREATE TABLE IF NOT EXISTS sheets (id INTEGER UNIQUE PRIMARY KEY, name VARCHAR(30), status INTEGER, FOREIGN KEY(status) REFERENCES statuses(id))"); query.exec("CREATE TABLE IF NOT EXISTS records (id INTEGER UNIQUE PRIMARY KEY, amount REAL, sheet INTEGER, FOREIGN KEY(sheet) REFERENCES sheets(id))"); } <file_sep>/sheetstatusmodel.cpp #include "sheetstatusmodel.h" #include "sheetstatuscollection.h" #include "sheetstatus.h" SheetStatusModel::SheetStatusModel(QObject *parent) : QAbstractListModel(parent) { } SheetStatusCollection *SheetStatusModel::sheetStatusCollection() const { return m_sheetStatusCollection; } int SheetStatusModel::rowCount(const QModelIndex &) const { return m_sheetStatusCollection ? m_sheetStatusCollection->sheetStatusCount() : 0; } QVariant SheetStatusModel::data(const QModelIndex &index, int role) const { if (index.row() < rowCount() && m_sheetStatusCollection) switch (role) { case NameRole: return m_sheetStatusCollection->sheetStatusAt(index.row())->name(); case IdRole: return m_sheetStatusCollection->sheetStatusAt(index.row())->id(); default: return QVariant(); } return QVariant(); } QHash<int, QByteArray> SheetStatusModel::roleNames() const { static const QHash<int, QByteArray> roles { { NameRole, "name" }, { IdRole, "id" } }; return roles; } void SheetStatusModel::setSheetStatusCollection(SheetStatusCollection *sheetStatusCollection) { if (m_sheetStatusCollection == sheetStatusCollection) return; beginResetModel(); if(m_sheetStatusCollection) m_sheetStatusCollection->disconnect(this); m_sheetStatusCollection = sheetStatusCollection; if(sheetStatusCollection){ connect(sheetStatusCollection, &SheetStatusCollection::sheetStatusChanged, this, [this](int index){ emit this->dataChanged(this->index(index, 0), this->index(index, 0)); }); connect(sheetStatusCollection, &SheetStatusCollection::beginInsert, this, [this](int first, int last){ emit this->beginInsertRows(QModelIndex(), first, last); }); connect(sheetStatusCollection, &SheetStatusCollection::endInsert, this, &SheetStatusModel::endInsertRows); connect(sheetStatusCollection, &SheetStatusCollection::beginRemove, this, [this](int first, int last){ emit this->beginRemoveRows(QModelIndex(), first, last); }); connect(sheetStatusCollection, &SheetStatusCollection::endRemove, this, &SheetStatusModel::endRemoveRows); connect(sheetStatusCollection, &SheetStatusCollection::beginReset, this, &SheetStatusModel::beginResetModel); connect(sheetStatusCollection, &SheetStatusCollection::endReset, this, &SheetStatusModel::endResetModel); } endResetModel(); emit sheetStatusCollectionChanged(m_sheetStatusCollection); } <file_sep>/sheetstatuses.h #ifndef SHEETSTATUSES_H #define SHEETSTATUSES_H enum SheetStatuses{ PendingStatus = 0, SubmittedStatus }; #endif // SHEETSTATUSES_H <file_sep>/sheet.h #ifndef SHEET_H #define SHEET_H #include <QObject> #include <QString> #include <QDate> #include <QVector> class Record; class DataManager; class Sheet : public QObject { Q_OBJECT Q_PROPERTY(DataManager* dataManager READ dataManager WRITE setDataManager NOTIFY dataManagerChanged) Q_PROPERTY(int id READ id WRITE setId NOTIFY idChanged) Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) Q_PROPERTY(int status READ status WRITE setStatus NOTIFY statusChanged) Q_PROPERTY(int recordCount READ recordCount NOTIFY recordCountChanged) Q_PROPERTY(QDate submittedDate READ submittedDate WRITE setSubmittedDate NOTIFY submittedDateChanged) Q_PROPERTY(qreal totalAmount READ totalAmount NOTIFY totalAmountChanged) public: explicit Sheet(QObject *parent = nullptr); inline QString name() const { return m_name; } inline int status() const { return m_status; } inline int recordCount() const { return m_records.count(); } inline QDate submittedDate() const { return m_submittedDate; } inline int id() const { return m_id; } qreal totalAmount() const; Q_INVOKABLE Record* recordAt(int index) const; DataManager* dataManager() const; Q_INVOKABLE Record *addRecord(); static QString tableName() { return "sheets"; } public slots: void setName(QString name); void setStatus(int status); void setSubmittedDate(const QDate &date); void addRecord(Record* record); void setId(int id); void setDataManager(DataManager* dataManager); signals: void nameChanged(const QString &name); void statusChanged(int status); void recordCountChanged(int count); void submittedDateChanged(const QDate &date); void totalAmountChanged(qreal total); void changed(); void idChanged(int id); void recordChanged(int index); void beginInsert(int first, int last); void endInsert(); void beginRemove(int first, int last); void endRemove(); void beginReset(); void endReset(); void dataManagerChanged(DataManager* dataManager); private: int m_id; QString m_name; int m_status; QDate m_submittedDate; QVector<Record *> m_records; DataManager* m_dataManager; void updateFields(); void loadRecords(); }; #endif // SHEET_H <file_sep>/sheet.cpp #include "sheet.h" #include <QVariantMap> #include "record.h" #include "datamanager.h" Sheet::Sheet(QObject *parent) : QObject(parent) , m_id(-1) , m_name("No name") , m_status(-1) , m_submittedDate(QDate::currentDate()) , m_dataManager(nullptr) { connect(this, &Sheet::nameChanged, this, &Sheet::changed); connect(this, &Sheet::statusChanged, this, &Sheet::changed); connect(this, &Sheet::submittedDateChanged, this, &Sheet::changed); connect(this, &Sheet::recordCountChanged, this, &Sheet::changed); connect(this, &Sheet::recordChanged, this, &Sheet::changed); } qreal Sheet::totalAmount() const { return std::accumulate(m_records.begin(), m_records.end(), 0.0, [](qreal total, Record *record){ return total + record->amount(); }); } Record *Sheet::recordAt(int index) const { return m_records.at(index); } DataManager *Sheet::dataManager() const { return m_dataManager; } void Sheet::setName(QString name) { if (m_name == name) return; m_name = name; if(m_dataManager){ m_dataManager->setField(tableName(), m_id, "name", m_name); } emit nameChanged(m_name); } void Sheet::setStatus(int status) { if (m_status == status) return; m_status = status; if(m_dataManager){ m_dataManager->setField(tableName(), m_id, "status", m_status); } emit statusChanged(m_status); } void Sheet::setSubmittedDate(const QDate &date) { if (m_submittedDate == date) return; m_submittedDate = date; emit submittedDateChanged(m_submittedDate); } void Sheet::addRecord(Record *record) { if(record){ int index = m_records.size(); beginInsert(index, index); m_records.append(record); endInsert(); connect(record, &Record::changed, this, [index, this](){ emit this->recordChanged(index); }); if(record->id() < 0 && m_dataManager){ int id = m_dataManager->add(Record::tableName()); m_dataManager->setField(Record::tableName(), id, "sheet", m_id); record->setId(id); record->setDataManager(m_dataManager); } emit recordCountChanged(m_records.size()); } } Record *Sheet::addRecord() { Record *r = new Record(this); addRecord(r); return r; } void Sheet::setId(int id) { if (m_id == id) return; m_id = id; emit idChanged(m_id); } void Sheet::setDataManager(DataManager *dataManager) { if (m_dataManager == dataManager) return; emit beginReset(); m_dataManager = dataManager; qDeleteAll(m_records); m_records.clear(); endReset(); updateFields(); loadRecords(); emit dataManagerChanged(m_dataManager); } void Sheet::updateFields() { if(m_dataManager){ QStringList fileds; fileds << "name" << "status"; QVariantMap props = m_dataManager->fields(tableName(), m_id, fileds); m_name = props["name"].toString(); m_status = props["status"].toInt(); } } void Sheet::loadRecords() { if(m_dataManager){ DataManager *manager = m_dataManager; m_dataManager->forEachDenpendent(Record::tableName(), "sheet", m_id, [this, manager](int id){ Record *r = new Record(this); r->setId(id); r->setDataManager(manager); addRecord(r); }); } } <file_sep>/sheetstatusmodel.h #ifndef SHEETSTATUSMODEL_H #define SHEETSTATUSMODEL_H #include <QAbstractListModel> #include <QPointer> class SheetStatusCollection; class SheetStatusModel : public QAbstractListModel { Q_OBJECT Q_PROPERTY(SheetStatusCollection* sheetStatusCollection READ sheetStatusCollection WRITE setSheetStatusCollection NOTIFY sheetStatusCollectionChanged) public: enum SheetSatatusRole { NameRole = Qt::UserRole, IdRole, }; Q_ENUM(SheetSatatusRole) explicit SheetStatusModel(QObject *parent = nullptr); SheetStatusCollection* sheetStatusCollection() const; int rowCount(const QModelIndex & = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QHash<int, QByteArray> roleNames() const override; signals: void sheetStatusCollectionChanged(SheetStatusCollection* sheetStatusCollection); public slots: void setSheetStatusCollection(SheetStatusCollection* sheetStatusCollection); private: QPointer<SheetStatusCollection> m_sheetStatusCollection; }; #endif // SHEETSTATUSMODEL_H <file_sep>/sheetcollection.cpp #include "sheetcollection.h" #include "sheet.h" #include "datamanager.h" SheetCollection::SheetCollection(DataManager *dataManager, QObject *parent) : QObject(parent) , m_dataManager(dataManager) { if(m_dataManager) { loadSheets(); } } void SheetCollection::addSheet(Sheet *sheet) { if(sheet){ int index = m_sheets.size(); beginInsert(index, index); m_sheets.append(sheet); endInsert(); connect(sheet, &Sheet::changed, this, [index, this](){ emit this->sheetChanged(index); }); if(sheet->id() < 0 && m_dataManager){ int id = m_dataManager->add(Sheet::tableName()); sheet->setId(id); sheet->setDataManager(m_dataManager); } } } int SheetCollection::sheetCount() const { return m_sheets.size(); } Sheet *SheetCollection::sheetAt(int index) const { return m_sheets.at(index); } Sheet *SheetCollection::addSheet() { Sheet *s = new Sheet(this); addSheet(s); return s; } DataManager *SheetCollection::dataManager() const { return m_dataManager; } void SheetCollection::removeAt(int index) { beginRemove(index, index); Sheet *sheet = m_sheets.takeAt(index); if(m_dataManager){ m_dataManager->remove(Sheet::tableName(), sheet->id()); } sheet->deleteLater(); endRemove(); } void SheetCollection::setDataManager(DataManager *dataManager) { if (m_dataManager == dataManager) return; emit beginReset(); m_dataManager = dataManager; qDeleteAll(m_sheets); m_sheets.clear(); endReset(); loadSheets(); emit dataManagerChanged(m_dataManager); } void SheetCollection::loadSheets() { if(m_dataManager){ DataManager *manager = m_dataManager; m_dataManager->forEach(Sheet::tableName(), [this, manager](int id){ Sheet *s = new Sheet(this); s->setId(id); s->setDataManager(manager); addSheet(s); }); } } <file_sep>/record.h #ifndef RECORD_H #define RECORD_H #include <QObject> #include <QDate> class DataManager; class Record : public QObject { Q_OBJECT Q_PROPERTY(DataManager* dataManager READ dataManager WRITE setDataManager NOTIFY dataManagerChanged) Q_PROPERTY(int id READ id WRITE setId NOTIFY idChanged) Q_PROPERTY(int purpose READ purpose WRITE setPurpose NOTIFY purposeChanged) Q_PROPERTY(qreal amount READ amount WRITE setAmount NOTIFY amountChanged) Q_PROPERTY(QDate transactionDate READ transactionDate WRITE setTransactionDate NOTIFY transactionDateChanged) Q_PROPERTY(QString serviceProvider READ serviceProvider WRITE setServiceProvider NOTIFY serviceProviderChanged) Q_PROPERTY(QString description READ description WRITE setDescription NOTIFY descriptionChanged) public: explicit Record(QObject *parent = nullptr); inline int id() const { return m_id; } inline qreal amount() const { return m_amount; } inline int purpose() const { return m_purpose; } inline QDate transactionDate() const { return m_transactionDate; } inline QString serviceProvider() const { return m_serviceProvider; } inline QString description() const { return m_description; } DataManager* dataManager() const; static QString tableName() { return "records"; } public slots: void setId(int id); void setAmount(qreal amount); void setPurpose(int purpose); void setTransactionDate(const QDate &transactionDate); void setServiceProvider(const QString &serviceProvider); void setDescription(const QString &description); void setDataManager(DataManager* dataManager); signals: void amountChanged(qreal amount); void purposeChanged(int purpose); void transactionDateChanged(const QDate &transactionDate); void serviceProviderChanged(const QString &serviceProvider); void descriptionChanged(const QString &description); void changed(); void dataManagerChanged(DataManager* dataManager); void idChanged(int id); private: int m_id; qreal m_amount; int m_purpose; QDate m_transactionDate; QString m_serviceProvider; QString m_description; DataManager* m_dataManager; void updateFields(); }; #endif // RECORD_H <file_sep>/recordmodel.cpp #include "recordmodel.h" #include "sheet.h" #include "record.h" RecordModel::RecordModel(QObject *parent) : QAbstractListModel(parent) , m_sheet(nullptr) { } int RecordModel::rowCount(const QModelIndex &) const { return m_sheet ? m_sheet->recordCount() : 0; } QVariant RecordModel::data(const QModelIndex &index, int role) const { if (index.row() < rowCount() && m_sheet) switch (role) { case PurposeRole: return m_sheet->recordAt(index.row())->purpose(); case TransactionDateRole: return m_sheet->recordAt(index.row())->transactionDate().toString("yyyy/MM/dd"); case ServiceProviderRole: return m_sheet->recordAt(index.row())->serviceProvider(); case DescriptionRole: return m_sheet->recordAt(index.row())->description(); case AmountRole: return m_sheet->recordAt(index.row())->amount(); default: return QVariant(); } return QVariant(); } QHash<int, QByteArray> RecordModel::roleNames() const { static const QHash<int, QByteArray> roles { { PurposeRole, "purpose" }, { TransactionDateRole, "transaction_date" }, { ServiceProviderRole, "service_provider" }, { DescriptionRole, "description" }, { AmountRole, "amount" } }; return roles; } void RecordModel::setSheet(Sheet *sheet) { if(m_sheet != sheet){ beginResetModel(); if(m_sheet) m_sheet->disconnect(this); m_sheet = sheet; if(m_sheet){ connect(sheet, &Sheet::recordChanged, this, [this](int index){ emit this->dataChanged(this->index(index, 0), this->index(index, 0)); }); connect(sheet, &Sheet::beginInsert, this, [this](int first, int last){ emit this->beginInsertRows(QModelIndex(), first, last); }); connect(sheet, &Sheet::endInsert, this, &RecordModel::endInsertRows); connect(sheet, &Sheet::beginRemove, this, [this](int first, int last){ emit this->beginRemoveRows(QModelIndex(), first, last); }); connect(sheet, &Sheet::endRemove, this, &RecordModel::endRemoveRows); connect(sheet, &Sheet::beginReset, this, &RecordModel::beginResetModel); connect(sheet, &Sheet::endReset, this, &RecordModel::endResetModel); } endResetModel(); emit sheetChanged(sheet); } } Sheet *RecordModel::sheet() const { return m_sheet; }
b31b39437b5679c3e02aeb306443347bd01c5b7b
[ "C", "C++" ]
20
C++
anjinkristou/Expenses
e122ba9a6814c6d2140e0eb23b845740826d0879
29f58126933f80a34e889b3eac50f31ce42be03c
refs/heads/master
<repo_name>t-shimada-motapp/webapp<file_sep>/setup.md ## データベースの作成 ``` > create database homestead; > create user 'homestead'@'localhost' identified by 'secret'; > grant all on homestead.* to homestead@localhost; > flush privileges; ``` ## git clone の後にすること ライブラリ等のインストール ``` $ composer install ``` 環境設定ファイルの作成とアプリケーションキーの作成 ``` $ cp .env.example .env $ php artisan key:generate ``` DBの作成 ``` $ php artisan migrate ``` Admin-LTEのインストール ``` $ cd public $ bower install admin-lte ``` <file_sep>/app/User.php <?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; /** * Indicates if the IDs are auto-incrementing. * * @var bool */ public $incrementing = false; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'user_id', 'password', 'skin', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * Setup model event hooks */ public static function boot() { parent::boot(); self::creating(function ($model) { $model->id = (string) \Illuminate\Support\Str::orderedUuid(); }); } }
9a7751b9d02163d0f633d6f8ef8a3984ffbc791d
[ "Markdown", "PHP" ]
2
Markdown
t-shimada-motapp/webapp
3a644719c90cbc01d1d2444a5965175d0c8649da
88519b68159d9394bf5b22ef531ebb62cc0dd2e0
refs/heads/master
<repo_name>TheMichaelHu/blossom-server<file_sep>/server/main.py from flask import Flask, render_template, request, jsonify from models import Animation app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/animate/<url>') def get_animation(url=None): if url: return jsonify({ "url": url }) else: return "Please provide a url" @app.route('/animate', methods=['GET', 'POST']) def animate(): if request.method == 'POST': if request.form: return submit_url(request.form['url']) return submit_url(request.url) else: return render_template('animate_form.html') def submit_url(url): process_video(url) return render_template("animate_form_submitted.html", url=url) # this is gonna be async probably...depends on how processing takes def process_video(url): animation = Animation(url=url, data="test") animation_key = animation.put() <file_sep>/server/models.py from google.appengine.ext import ndb class Animation(ndb.Model): url = ndb.StringProperty() data = ndb.StringProperty() <file_sep>/process_vid/make_animation.py from os import path from pytube import YouTube import argparse import numpy as np import cv2 import json from sklearn.cluster import KMeans from scipy.spatial.distance import cosine def download_video(url, dest): yt = YouTube(url) video = yt.filter('mp4')[0] filename = yt.filename if not path.isdir(dest): head, tail = path.split(dest) filename = tail.split(".")[0] dest = head yt.set_filename("".join([filename, ".", yt.video_id])) video.download(dest) print("Video saved to:", "".join([dest, "/", yt.filename, ".mp4"])) def generate_animation(vid, dest): emotions = { "look": "io2/look", "think": "io11/think", "look": "io2/look", "distress": "io5/distress", "fear": "io1/fear", "calm": "io8/calm", "sad": "io7/sad", } emote = "" head, tail = path.split(vid) vid_json = {"videoId": tail.split(".")[-2], "triggers": []} cap = cv2.VideoCapture(vid) # Check if camera opened successfully if not cap.isOpened(): print("Error opening video stream or file") # Read until video is completed while(cap.isOpened()): # Capture frame-by-frame ret, frame = cap.read() if ret: color = detect_color(frame) time, emote = handle_color(color, cap.get(cv2.CAP_PROP_POS_MSEC), emote) if time: vid_json["triggers"].append({ "time": time, "emotion": emote, "gesture": emotions[emote], }) print(time, emote) # Press Q on keyboard to exit if cv2.waitKey(25) & 0xFF == ord('q'): break else: break # When everything done, release the video capture object cap.release() # Closes all the frames cv2.destroyAllWindows() if path.isdir(dest): dest = "".join([dest, "/", tail.split(".")[0], ".json"]) with open(dest, 'w+') as dest_file: json.dump(vid_json, dest_file, sort_keys=True, indent=4, separators=(',', ': ')) with open("./demo/gestures.es6", 'w+') as dest_file: dest_file.write("var emotions =\n") json.dump(vid_json, dest_file, sort_keys=True, indent=4, separators=(',', ': ')) def handle_color(color, time, prev_emote): cen_color = color - np.mean(color) colors = { "red": cosine(cen_color, np.array([[0, 0, 1]])), "yellow": cosine(cen_color, np.array([[0, 1, 1]])), "green": cosine(cen_color, np.array([[0, 1, 0]])), "blue": cosine(cen_color, np.array([[1, 0, 0]])), "purple": cosine(cen_color, np.array([[2, 0, 1]])), "pink": cosine(cen_color, np.array([[1, 0, 1]])), "gray": cosine(cen_color, np.array([[1, 1, 1]])), } best_color = min(colors, key=colors.get) if best_color == "red": emote = "fear" elif best_color == "yellow": emote = "calm" elif best_color == "green": emote = "look" elif best_color == "blue": emote = "sad" elif best_color == "purple": emote = "distress" elif best_color == "pink": emote = "think" else: emote = "think" if emote != prev_emote: print(best_color) return [time, emote] if emote != prev_emote else [None, emote] def detect_color(img): image = img.reshape((img.shape[0] * img.shape[1], 3)) kmeans = KMeans(n_clusters=2, max_iter=20, n_init=1) kmeans.fit(image) counts = np.bincount(kmeans.labels_).tolist() center = kmeans.cluster_centers_[counts.index(max(counts))] lower, upper = center - 60, center + 60 cv2.imshow('colors', np.hstack([img, cv2.bitwise_and(img, img, mask=cv2.inRange(img, lower, upper))])) return center if __name__ == "__main__": parser = argparse.ArgumentParser(description='Download and process Youtube videos.') parser.add_argument("-v", "--video", type=str, nargs=1, help="A Youtube video url to download") parser.add_argument("-d", "--destination", type=str, nargs=1, help="The destination dir of any outputs.") parser.add_argument("-p", "--process", type=str, nargs=1, help="Path to a locally stored video to process") args = parser.parse_args() dest = args.destination or ["."] if args.video: download_video(args.video[0], dest[0]) elif args.process: generate_animation(args.process[0], dest[0]) else: print("Type -h or --help for help.") <file_sep>/requirements.txt Flask==0.12.2 pytube <file_sep>/README.md # blossom-server Flask server for producing commands for blossom # video to json script The server and script are currently separated (script is in `./process_vid/`). The script uses a python library to download a video from youtube, and opencv to go through the video frame by frame. ## downloading a video To download a video off youtube, run ``` python process_vid/make_animation.py -v [video url] -d [destination] ``` The destination is optional and defaults to your current directory ## processing a video To process a video that's been downloaded into a json file, run ``` python process_vid/make_animation.py -p [video] -d [destination] ``` The destination is optional and defaults to your current directory # server setup (*Note, just ignore the server stuff for how.*) - Set up Google App Engine, first few steps of [this](https://cloud.google.com/appengine/docs/standard/python/getting-started/python-standard-env#test_the_application) - Make sure running `python --version` gets 2.7.x, not 3.6 or something - Install dependencies with `pip install -t lib -r requirements.txt` - Start the server locally with `dev_appserver.py app.yaml` # deploy to google app engine Just run `gcloud app deploy` # layout So far there is a form `/animate` that takes a url and submits to the same url but as a POST. Once the video is processed, it'll be made available at `/animate/[url]`
9d06be3ba252861e7492ae2f72f407139ae25767
[ "Markdown", "Python", "Text" ]
5
Python
TheMichaelHu/blossom-server
edebc95c95226b5c2a0112f7fe5b6c71bdf6b768
f80f60bd3241188275db5dfa7013e35fe5f9a1ca
refs/heads/master
<repo_name>RetroSuperHero/SysOpy<file_sep>/cw05/zad02/Makefile GCC=gcc MASTER=master SLAVE=slave FLAGS=-Wall FIFO=fifo all: compile ./$(MASTER) $(FIFO) compile: $(GCC) $(MASTER).c -o $(MASTER) $(FLAGS) $(GCC) $(SLAVE).c -o $(SLAVE) $(FLAGS) clear: rm -rf $(MASTER) $(SLAVE) $(FIFO)<file_sep>/cw03/zad01/Makefile GCC=gcc SOURCE=main FLAGS=-Wall PARAMETERS=. all: make compile ./$(SOURCE) $(PARAMETERS) compile: $(GCC) $(SOURCE).c -o $(SOURCE) $(FLAGS) clear: rm -rf $(SOURCE)<file_sep>/cw05/zad02/master.c #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <fcntl.h> int main(int argc, char* argv[]) { if(argc < 2) { printf("Podano za małą liczbę argumentów.\n"); } else { const char* fifoPath = argv[1]; int fifo = mkfifo(fifoPath, 0777); if(!fifo) { int fifoFile = open(fifoPath, O_RDWR); while(1) { char buff[100]; read(fifoFile, buff, 100); printf("--%s\n", buff); } close(fifoFile); } } }<file_sep>/cw03/zad02/main.c #include <stdlib.h> #include <stdio.h> #include <malloc.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <time.h> #include <sys/stat.h> #include<stdarg.h> typedef struct monitor { int noOfCycles; int noOfBackups; clock_t startTime; time_t modificationTime; char* content; int contentSize; } monitor; double clockToTime(clock_t czas) { return (double) (czas) / CLOCKS_PER_SEC; } int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result * 10 + ( string[i] - '0' ); } return result; } char* getDateFromTimestamp(time_t timestamp, struct tm* ts) { char* date = calloc(80, sizeof(char)); *ts = *localtime(&timestamp); strftime(date, 80*sizeof(char), "_%Y-%m-%d_%H-%M-%S", ts); return date; } char* stringCat(char* buffer, int args, ...) { va_list lst; va_start(lst, args); for(int i=0; i<args; ++i) { strcat(buffer, va_arg(lst, char*)); } va_end(lst); return buffer; } void setMonitorLib(char* fileName, char* directory, int timeDelay, int maxTime) { pid_t child_pid = fork(); if(child_pid == 0) { monitor thisMonitor; thisMonitor.noOfCycles = 1; thisMonitor.noOfBackups = 0; thisMonitor.startTime = clock(); thisMonitor.modificationTime = -1; char* filePath = calloc(strlen(fileName) + strlen(directory), sizeof(char)); stringCat(filePath, 2, directory, fileName); while(thisMonitor.noOfCycles*timeDelay + clockToTime(clock() - thisMonitor.startTime) < maxTime) { FILE* file = fopen(filePath, "r"); if(file) { struct tm ts; struct stat st; lstat(fileName, &st); if(thisMonitor.modificationTime != -1 && thisMonitor.modificationTime != st.st_mtime) { char* newFileName = calloc(strlen(fileName) + 30, sizeof(char)); stringCat(newFileName, 3, "./archive/", fileName, getDateFromTimestamp(time(0), &ts)); FILE* newFile = fopen(newFileName, "ab+"); fwrite(thisMonitor.content, sizeof(char), thisMonitor.contentSize, newFile); fclose(newFile); free(newFileName); thisMonitor.noOfBackups++; } if(thisMonitor.modificationTime == -1 || thisMonitor.modificationTime != st.st_mtime) { fseek(file, 0L, SEEK_END); thisMonitor.contentSize = ftell(file); fseek(file, 0L, SEEK_SET); thisMonitor.content = calloc(thisMonitor.contentSize, sizeof(char)); fread(thisMonitor.content, sizeof(char), thisMonitor.contentSize, file); thisMonitor.modificationTime = st.st_mtime; } } else { printf("Problem ze znalezieniem pliku %s\n", filePath); exit(0); } fclose(file); sleep(timeDelay); thisMonitor.noOfCycles++; } free(filePath); exit(thisMonitor.noOfBackups); } } void setMonitorSys(char* fileName, char* directory, int timeDelay, int maxTime) { pid_t child_pid = fork(); if(child_pid == 0) { struct tm ts; struct stat st; monitor thisMonitor; thisMonitor.noOfCycles = 1; thisMonitor.noOfBackups = 1; thisMonitor.startTime = clock(); thisMonitor.modificationTime = st.st_mtime; char* filePath = calloc(strlen(fileName) + strlen(directory), sizeof(char)); stringCat(filePath, 2, directory, fileName); char* command = calloc(999, sizeof(char)); stringCat(command, 5, "cp ", filePath, " ./archive/", fileName, getDateFromTimestamp(time(0), &ts)); system(command); free(command); while(thisMonitor.noOfCycles*timeDelay + clockToTime(clock() - thisMonitor.startTime) < maxTime) { FILE* file = fopen(filePath, "r"); if(file) { lstat(fileName, &st); if(thisMonitor.modificationTime != st.st_mtime) { char* command = calloc(999, sizeof(char)); stringCat(command, 5, "cp ", filePath, " ./archive/", fileName, getDateFromTimestamp(time(0), &ts)); system(command); thisMonitor.noOfBackups++; thisMonitor.modificationTime = st.st_mtime; } } else { printf("Problem ze znalezieniem pliku %s\n", filePath); exit(0); } fclose(file); sleep(timeDelay); thisMonitor.noOfCycles++; } free(filePath); exit(thisMonitor.noOfBackups); } } int main(int argc, char* argv[]) { int numberOfProcesses = 0; if(argc < 4) { printf("Podano złą liczbę argumentów\n"); } else { char* listaPath = argv[1]; int maxTime = stringToInt(argv[2]); int mode = stringToInt(argv[3]); FILE* lista = fopen(listaPath, "r"); if(lista) { fseek(lista, 0L, SEEK_END); int size = ftell(lista); fseek(lista, 0L, SEEK_SET); char* buff = calloc(size, sizeof(char)); if(fread(buff, sizeof(char), size, lista)) { char *line = strtok(buff, " "); while(line) { char* file = line; line = strtok(NULL, " "); char* directory = line; line = strtok(NULL, "\n"); int timeDelay = stringToInt(line); line = strtok(NULL, " "); if(mode == 0) { setMonitorLib(file, directory, timeDelay, maxTime); } else { setMonitorSys(file, directory, timeDelay, maxTime); } numberOfProcesses++; } } free(buff); fclose(lista); } } for(int i=0; i<numberOfProcesses; ++i) { int status; pid_t processId = wait(&status); printf("Proces %d utworzył %d kopii pliku.\n", processId, WEXITSTATUS(status)); } return 0; } <file_sep>/cw03/zad03/tester.sh #!/bin/bash while true do let SEC=`shuf -i $2-$3 -n 1` echo $$ $SEC `date` `head -c $4 /dev/urandom` >> $1 sleep $SEC done<file_sep>/cw04/zad02/main.c #include <stdlib.h> #include <stdio.h> #include <malloc.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <time.h> #include <sys/stat.h> #include <stdarg.h> #include <signal.h> typedef struct monitor { pid_t PID; int stopped; int noOfBackups; clock_t startTime; time_t modificationTime; char* content; int contentSize; int isTerminated; } monitor; typedef struct pidArray { pid_t* pids; int count; } pidArray; pidArray pidArr; monitor thisMonitor; int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result * 10 + ( string[i] - '0' ); } return result; } void sigUSR1(int signum) { thisMonitor.stopped = 1; } void sigUSR2(int signum) { thisMonitor.stopped = 0; } void sigRTMIN(int signum) { printf("Proces o PID %d wykonał %d kopii\n", thisMonitor.PID, thisMonitor.noOfBackups); thisMonitor.isTerminated = 1; } void sigINT(int signum) { for(int i=0; i<pidArr.count; ++i) { kill(pidArr.pids[i], SIGRTMIN); } sleep(1); exit(0); } char* getDateFromTimestamp(time_t timestamp, struct tm* ts) { char* date = calloc(80, sizeof(char)); *ts = *localtime(&timestamp); strftime(date, 80*sizeof(char), "_%Y-%m-%d_%H-%M-%S", ts); return date; } char* stringCat(char* buffer, int args, ...) { va_list lst; va_start(lst, args); for(int i=0; i<args; ++i) { strcat(buffer, va_arg(lst, char*)); } va_end(lst); return buffer; } void setMonitorLib(char* fileName, char* directory, int timeDelay) { pid_t child_pid = fork(); if(child_pid == 0) { thisMonitor.stopped = 0; thisMonitor.PID = getpid(); thisMonitor.noOfBackups = 0; thisMonitor.startTime = clock(); thisMonitor.modificationTime = -1; char* filePath = calloc(strlen(fileName) + strlen(directory), sizeof(char)); stringCat(filePath, 2, directory, fileName); while(!thisMonitor.isTerminated) { FILE* file = fopen(filePath, "r"); if(!thisMonitor.stopped && file) { struct tm ts; struct stat st; lstat(fileName, &st); if(thisMonitor.modificationTime != -1 && thisMonitor.modificationTime != st.st_mtime) { char* newFileName = calloc(strlen(fileName) + 30, sizeof(char)); stringCat(newFileName, 3, "./archive/", fileName, getDateFromTimestamp(time(0), &ts)); FILE* newFile = fopen(newFileName, "ab+"); fwrite(thisMonitor.content, sizeof(char), thisMonitor.contentSize, newFile); fclose(newFile); free(newFileName); thisMonitor.noOfBackups++; } if(thisMonitor.modificationTime == -1 || thisMonitor.modificationTime != st.st_mtime) { fseek(file, 0L, SEEK_END); thisMonitor.contentSize = ftell(file); fseek(file, 0L, SEEK_SET); thisMonitor.content = calloc(thisMonitor.contentSize, sizeof(char)); fread(thisMonitor.content, sizeof(char), thisMonitor.contentSize, file); thisMonitor.modificationTime = st.st_mtime; } } else { printf("Problem ze znalezieniem pliku %s\n", filePath); exit(0); } fclose(file); sleep(timeDelay); } free(filePath); exit(0); } else { pidArr.pids[pidArr.count++] = child_pid; } } int main(int argc, char* argv[]) { int numberOfProcesses = 0; signal(SIGUSR1, sigUSR1); signal(SIGUSR2, sigUSR2); signal(SIGRTMIN, sigRTMIN); signal(SIGINT, sigINT); pidArr.count = 0; pidArr.pids = calloc(10, sizeof(pid_t)); if(argc < 2) { printf("Podano złą liczbę argumentów\n"); } else { char* listaPath = argv[1]; FILE* lista = fopen(listaPath, "r"); if(lista) { fseek(lista, 0L, SEEK_END); int size = ftell(lista); fseek(lista, 0L, SEEK_SET); char* buff = calloc(size, sizeof(char)); if(fread(buff, sizeof(char), size, lista)) { char *line = strtok(buff, " "); while(line) { char* file = line; line = strtok(NULL, " "); char* directory = line; line = strtok(NULL, "\n"); int timeDelay = stringToInt(line); line = strtok(NULL, " "); setMonitorLib(file, directory, timeDelay); numberOfProcesses++; } } free(buff); fclose(lista); } } while(1) { char cmd[20]; char param[20]; scanf("%s", cmd); if(!strcmp(cmd, "LIST")) { for(int i=0; i<pidArr.count; ++i) { printf("PID: %d\n", pidArr.pids[i]); } } else if(!strcmp(cmd, "STOP")) { scanf("%s", param); if(!strcmp(param, "ALL")) { for(int i=0; i<pidArr.count; ++i) { kill(pidArr.pids[i], SIGUSR1); } } else { int sPID = stringToInt(param); int found = 0; for(int i=0; i<pidArr.count && !found; ++i) { if(sPID == pidArr.pids[i]) { found = 1; } } if(found) { kill(sPID, SIGUSR1); } else { printf("Nie ma procesu o podanym PID\n"); } } } else if(!strcmp(cmd, "START")) { if(!strcmp(param, "ALL")) { for(int i=0; i<pidArr.count; ++i) { kill(pidArr.pids[i], SIGUSR2); } } else { int sPID = stringToInt(param); int found = 0; for(int i=0; i<pidArr.count && !found; ++i) { if(sPID == pidArr.pids[i]) { found = 1; } } if(found) { kill(sPID, SIGUSR2); } else { printf("Nie ma procesu o podanym PID\n"); } } } else if(!strcmp(cmd, "END")) { for(int i=0; i<pidArr.count; ++i) { kill(pidArr.pids[i], SIGRTMIN); } sleep(1); return 0; } } return 0; }<file_sep>/cw02/zad02/a/main.c #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <dirent.h> #include <string.h> #include <sys/stat.h> #include <time.h> int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result * 10 + ( string[i] - '0' ); } return result; } char* getType(int fileType) { char* type; switch (fileType) { case DT_REG: type = "file"; break; case DT_DIR: type = "dir"; break; case DT_FIFO: type = "fifo"; break; case DT_SOCK: type = "sock"; break; case DT_CHR: type = "char dev"; break; case DT_BLK: type = "block dev"; break; case DT_LNK: type = "slink"; break; default: type ="error"; break; } return type; } char* getDateFromTimestamp(time_t timestamp, struct tm* ts) { char* date = calloc(80, sizeof(char)); *ts = *localtime(&timestamp); strftime(date, 80*sizeof(char), "%a %Y-%m-%d %H:%M:%S %Z", ts); return date; } void printData(struct dirent* thisDir, struct stat stats, char* newPath, struct tm* ts) { char* type = getType(thisDir->d_type); char* path = realpath(newPath, NULL); char* aDate = getDateFromTimestamp(stats.st_atime, ts); char* mDate = getDateFromTimestamp(stats.st_mtime, ts); printf("%s:\n Pełna ścieżka: %s\n Rodzaj pliku: %s\n Rozmiar pliku: %ld B\n Data ostatniego dostępu: %s\n Data ostatnie modyfikacji: %s\n", thisDir->d_name, path, type, stats.st_size, aDate, mDate); free(aDate); free(mDate); } void searchDir(char* dirName, char mode, int day, int month, int year) { DIR* currentDirectory = opendir(dirName); if(currentDirectory == NULL) { printf("Nie ma takiego katalogu\n"); } else { struct dirent* thisDir; while((thisDir = readdir(currentDirectory)) != NULL) { if(strcmp(thisDir->d_name, ".") && strcmp(thisDir->d_name, "..")) { char* newPath = calloc(1024, sizeof(char)); struct stat stats; strcat(newPath, dirName); strcat(newPath, "/"); strcat(newPath, thisDir->d_name); lstat(newPath, &stats); struct tm ts = *localtime(&stats.st_mtime); if(mode == '=') { if(ts.tm_mday == day && ts.tm_mon == month && ts.tm_year == year) { printData(thisDir, stats, newPath, &ts); } } else if(mode == '<') { if(ts.tm_year < year || (ts.tm_year == year && ts.tm_mon < month) || (ts.tm_year == year && ts.tm_mon == month && ts.tm_mday < day)) { printData(thisDir, stats, newPath, &ts); } } else if(mode == '>') { if(ts.tm_year > year || (ts.tm_year == year && ts.tm_mon > month) || (ts.tm_year == year && ts.tm_mon == month && ts.tm_mday > day)) { printData(thisDir, stats, newPath, &ts); } } if(thisDir->d_type == DT_DIR && thisDir->d_type != DT_LNK) { searchDir(newPath, mode, day, month, year); } free(newPath); } } } } int main(int argc, char* argv[]) { char* startDir = argv[1]; char* mode = argv[2]; char* day = argv[3]; char* month = argv[4]; char* year = argv[5]; if(argc < 6) { printf("Podano złą liczbę argumentów\n"); } else if(strcmp(mode, "=") && strcmp(mode, ">") && strcmp(mode, "<")) { printf("Wprowadzono nieprawidłowy znak porówniania\n"); } else { searchDir(startDir, mode[0], stringToInt(day), stringToInt(month) - 1, stringToInt(year) - 1900); } return 0; }<file_sep>/cw06/zad02/client.c #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #include <signal.h> #include <string.h> #include <time.h> #include <mqueue.h> #include "chat.h" pid_t PID; int thisClient; mqd_t serverQueue; mqd_t thisClientQueue; Message receiveMessage(int queue) { Message message; if(mq_receive(queue, (char *)&message, MESSAGE_SIZE, NULL)) { return message; } else { fprintf(stderr, "Wystąpił problem z odbieraniem wiadomości z kolejki serwera"); exit(1); } } void sendMessageToClient(int queue, long messageType, char* messageText, long clientID, int textLength) { Message message; message.type = messageType; message.clientID = clientID; message.textLength = textLength; if(textLength <= MAX_MESSAGE_LENGTH && textLength >= 0) { strcpy(message.text, messageText); } else { fprintf(stderr, "Wysyłana do klienta wiadomość ma nieprawidłową długość"); exit(1); } printf("Wysyłanie wiadomości: \n Typ: %s \n Klient: %ld\n Treść: %s\n", getTypeName(message.type), message.clientID, message.text); if(mq_send(queue, (char*) &message, MESSAGE_SIZE, 1) == -1){ fprintf(stderr, "Wysyłanie wiadomości do klienta nie powiodło się"); exit(1); } } void manageInputCommand(char* command, size_t commandLength) { if(!strncmp(command, "ECHO", 4)) { sendMessageToClient(serverQueue, ECHO, command + 5, thisClient, commandLength - 5); } else if(!strncmp(command, "2ALL", 4)) { sendMessageToClient(serverQueue, TO_ALL, command + 5, thisClient, commandLength - 5); } else if(!strncmp(command, "FRIENDS", 7)) { sendMessageToClient(serverQueue, FRIENDS, command + 8, thisClient, commandLength - 8); } else if(!strncmp(command, "ADD", 3)) { sendMessageToClient(serverQueue, ADD, command + 4, thisClient, commandLength - 4); } else if(!strncmp(command, "DEL", 3)) { sendMessageToClient(serverQueue, DEL, command + 4, thisClient, commandLength - 4); } else if (strncmp(command, "2FRIENDS", 8) == 0) { sendMessageToClient(serverQueue, TO_FRIENDS, command + 9, thisClient, commandLength - 9); } else if(!strncmp(command, "LIST", 4)) { char* description = "Wyświetlenie listy klientów"; sendMessageToClient(serverQueue, LIST, description, thisClient, strlen(description)); } else if(!strncmp(command, "STOP", 4)) { exit(0); } else { printf("Podano nieprawidłową komendę: %s\n", command); } } void atExit() { if (PID == 0) { char* description = "Wiadomość zakończenia działania"; mq_close(thisClientQueue); char thisQueuePath[15]; sprintf(thisQueuePath, "/%d", getpid()); mq_unlink(thisQueuePath); sendMessageToClient(serverQueue, STOP, description, thisClient, strlen(description)); mq_close(serverQueue); } exit(1); } void handleSIGINT(int signum) { if (PID == 0) { printf("\nSIGINT - kończenie procesu klienta\n"); } exit(0); } int main() { atexit(atExit); signal(SIGINT, handleSIGINT); thisClient = getpid(); struct mq_attr messageAttributes; messageAttributes.mq_maxmsg = MAX_MESSAGES; messageAttributes.mq_msgsize = MESSAGE_SIZE; char thisClientPath[15]; sprintf(thisClientPath, "/%d", thisClient); if((thisClientQueue = mq_open(thisClientPath, O_RDONLY | O_CREAT | O_EXCL, 0666, &messageAttributes)) == -1) { fprintf(stderr, "Wystąpił problem z połączeniem z kolejką serwera"); exit(1); } if((serverQueue = mq_open(SERVER, O_WRONLY)) == -1) { fprintf(stderr, "Wystąpił problem z tworzeniem kolejki dla klienta"); exit(1); } char* description = "Wiadomość nawiązania połączenia"; sendMessageToClient(serverQueue, INIT, description, thisClient, strlen(description)); Message message = receiveMessage(thisClientQueue); thisClient = message.clientID; printf("Klient numer: %d\n", thisClient); if ((PID = fork()) == 0) { while (1) { message = receiveMessage(thisClientQueue); if (message.type == ECHO){ printf("Otrzymano wiadomość: \n Typ: %s \n Klient: %ld\n Treść: %s\n", getTypeName(message.type), message.clientID, message.text); } if (message.type == STOP) { printf("Otrzymano wiadomość: \n Typ: %s \n Klient: %ld\n Treść: %s\n", getTypeName(message.type), message.clientID, message.text); kill(getppid(), SIGUSR1); exit(0); } } } else { size_t MAX_COMMAND_LENGTH = MAX_MESSAGE_LENGTH + 15; char* command = calloc(MAX_COMMAND_LENGTH, sizeof(char)); while (1) { size_t commandLength = getline(&command, &MAX_COMMAND_LENGTH, stdin); manageInputCommand(command, commandLength); } free(command); } }<file_sep>/cw04/zad03/b/catcher.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> void ignore(int signum) { printf("Ignored\n"); } void terminate(int signum) { exit(0); } void receiveAndSend(int sig, siginfo_t *info, void *context) { int signalPid = info->si_pid; kill(signalPid, SIGUSR1); } int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result * 10 + ( string[i] - '0' ); } return result; } int main(int argc, char* argv[]) { printf("%d\n", getpid()); struct sigaction act; act.sa_handler = ignore; sigfillset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGINT, &act, NULL); struct sigaction sa; sa.sa_flags = SA_SIGINFO; sa.sa_sigaction = receiveAndSend; sigaction(SIGUSR1, &sa, NULL); signal(SIGUSR2, terminate); while(1) { } return 0; }<file_sep>/cw07/zad01/shared.h #ifndef SHARED #define SHARED #define SHARED_ADDRESS getenv("HOME") #define SHARED_ID 0xDEAD #define CARRIER_WEIGHT_SEMAPHORE 0 #define CARRIER_LENGTH_SEMAPHORE 1 #define MAX_QUEUE_SIZE 64 typedef struct Package { int packageWeight; pid_t workerID; time_t loadTime; } Package; typedef struct Truck{ int truckCapacity; int currentWeight; } Truck; struct Carrier { int semaphores; int currentQueueIndex; int currentQueueLength; int carrierLength; int carrierCapacity; Package carrierQueue[MAX_QUEUE_SIZE]; } *Carrier; void decrementSem(int semaphores, int semaphoreID, int value) { struct sembuf s; s.sem_flg = 0; s.sem_num = semaphoreID; s.sem_op = -1 * value; semop(semaphores, &s, 1); } void incrementSem(int semaphores, int semaphoreID, int value) { struct sembuf s; s.sem_flg = 0; s.sem_num = semaphoreID; s.sem_op = value; semop(semaphores, &s, 1); } #endif<file_sep>/cw10/client.c #include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #define PORT 8080 int working = 0; int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++) { result = result*10 + (string[i] - '0'); } return result; } void calculate(char* text, int sock) { int words = 0; strtok(text, " \n\r"); while(text) { words++; text = strtok(NULL, " \n\r"); } char* count = calloc(100, sizeof(char)); sprintf(count, "%d", words); send(sock, count, 100, 0); free(count); working = 0; } int main(int argc, char const *argv[]) { int sock = 0; struct sockaddr_in serverAddress; char message[1024]; if(argc != 2) { fprintf(stderr, "Nieprawidłowa liczba argumentów\n"); exit(1); } if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "Tworzenie socketa nie powiodło się\n"); exit(1); } memset(&serverAddress, '0', sizeof(serverAddress)); serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(PORT); if(inet_pton(AF_INET, "127.0.0.1", &serverAddress.sin_addr) <= 0) { fprintf(stderr, "Nieprawidłowy adres\n"); exit(1); } if(connect(sock, (struct sockaddr*) &serverAddress, sizeof(serverAddress)) < 0) { fprintf(stderr, "Połączenie nie powiodło się\n"); exit(1); } send(sock, argv[1], strlen(argv[1]), 0); char* buffer = calloc(20, sizeof(char)); read(sock, buffer, 20); printf("%s\n", buffer); if(!strcmp(buffer, "Już zarejestrowany")) { exit(1); } free(buffer); while(1) { char* message = calloc(100, sizeof(char)); read(sock, message, 100); if(!strcmp(message, "PING")) { send(sock, "PING", 4, 0); } else if(!working) { int textLength = stringToInt(message); char* buffer = calloc(textLength, sizeof(char)); read(sock, buffer, textLength); working = 1; calculate(buffer, sock); free(buffer); } free(message); } return 0; }<file_sep>/cw01/zad01/Makefile CC = gcc CFLAGS = -O -Wall LIB = library both: make static make shared static: $(CC) -c $(LIB).c -o $(LIB).o ar cr $(LIB).a $(LIB).o make clean shared: $(CC) -fPIC -c $(LIB).c -o $(LIB).o $(CC) -fPIC -shared -o lib_$(LIB).so $(LIB).o make clean clean: rm -f *.o<file_sep>/cw07/zad01/loader.c #include <stdio.h> #include <stdlib.h> #include <time.h> #include <errno.h> #include <sys/wait.h> #include <sys/sem.h> #include <sys/shm.h> #include <sys/types.h> #include <signal.h> #include <unistd.h> #include <sys/stat.h> #include <string.h> #include "shared.h" int sharedMemoryId; struct Carrier* carrier; int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result*10 + (string[i] - '0'); } return result; } void putPackage(Package package) { decrementSem(carrier->semaphores, CARRIER_LENGTH_SEMAPHORE, 1); decrementSem(carrier->semaphores, CARRIER_WEIGHT_SEMAPHORE, package.packageWeight); package.loadTime = time(NULL); carrier->carrierQueue[carrier->currentQueueIndex + carrier->currentQueueLength] = package; carrier->currentQueueLength++; printf("Załadowano paczkę:\n PID pracownika: %d\n Waga paczki: %d\n Czas wysłania: %ld\n", package.workerID, package.packageWeight, package.loadTime); } int main(int argc, char **argv) { srand(time(NULL)); if(argc != 3) {} int workers = stringToInt(argv[1]); int maxPackageWeight = stringToInt(argv[2]); key_t sharedMemoryKey = ftok(SHARED_ADDRESS, SHARED_ID); if(sharedMemoryKey == -1) { fprintf(stderr, "Pobieranie klucza nie powiodło się"); exit(1); } sharedMemoryId = shmget(sharedMemoryKey, 0, 0); if (sharedMemoryId == -1) { fprintf(stderr, "Otwieranie dzielonej przestrzeni nie powiodło się"); exit(1); } carrier = shmat(sharedMemoryId, 0, 0); if (carrier == (void*) -1) { fprintf(stderr, "Nie można było dostać się do pamięci współdzielonej"); exit(1); } for(int i=0; i<workers; ++i){ srand(time(NULL)); if(fork() == 0){ int packageWeight = rand() % maxPackageWeight + 1; Package package; package.workerID = getpid(); package.packageWeight = packageWeight; putPackage(package); exit(0); } sleep(1); } for (int i = 0; i<workers; ++i) { wait(NULL); } }<file_sep>/cw01/zad02/Makefile CC = gcc SOURCE=main CFLAGS=-Wall -O LIBPATH=../zad01 LIBNAME=library OUTPUT=raport2.txt PARAMETERS=create_table 20 search_directory . main tmp1 search_directory ../zad01 main tmp2 remove_block 1 search_directory ../zad01 library.h tmp3 search_directory . aa tmp4 search_directory ../../../../Geo Geo tmp5 all: $(CC) -I$(LIBPATH) $(SOURCE).c $(LIBPATH)/$(LIBNAME).c -o $(SOURCE) echo 'Statystyki:\n' >> $(OUTPUT) echo 'Parametry:\n$(PARAMETERS)\n' >> $(OUTPUT) ./$(SOURCE) $(PARAMETERS) >> $(OUTPUT) clean: rm -r $(SOURCE) $(OUTPUT) <file_sep>/cw07/zad01/trucker.c #include <stdio.h> #include <stdlib.h> #include <time.h> #include <errno.h> #include <sys/wait.h> #include <sys/sem.h> #include <sys/shm.h> #include <sys/types.h> #include <signal.h> #include <unistd.h> #include <sys/stat.h> #include <string.h> #include "shared.h" int sharedMemoryId; Truck truck; struct Carrier* carrier; void handleSignal(int signal) { printf("Zamykanie procesu ciężarówki\n"); exit(0); } void atExit() { if(carrier->semaphores != 0) { semctl(carrier->semaphores, 0, IPC_RMID); } if(sharedMemoryId != 0) { shmctl(sharedMemoryId, IPC_RMID, NULL); } } int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result*10 + (string[i] - '0'); } return result; } void initSems(int truckCapacity, int carrierLength, int carrierCapacity) { key_t sharedMemoryKey = ftok(SHARED_ADDRESS, SHARED_ID); if(sharedMemoryKey == -1) { fprintf(stderr, "Pobieranie klucza nie powiodło się"); exit(1); } sharedMemoryId = shmget(sharedMemoryKey, sizeof(struct Carrier), S_IRWXU | IPC_CREAT); if (sharedMemoryId == -1) { fprintf(stderr, "Tworzenie dzielonej przestrzeni nie powiodło się"); exit(1); } carrier = shmat(sharedMemoryId, 0, 0); if (carrier == (void*) -1) { fprintf(stderr, "Nie można było dostać się do pamięci współdzielonej"); exit(1); } carrier->semaphores = semget(sharedMemoryKey, 1, IPC_CREAT | S_IRWXU); if (carrier->semaphores == -1) { fprintf(stderr, "Nie można było utworzyć semafora"); exit(1); } carrier->carrierLength = carrierLength; carrier->carrierCapacity = carrierCapacity; carrier->currentQueueIndex = 0; carrier->currentQueueLength = 0; truck.truckCapacity = truckCapacity; semctl(carrier->semaphores, CARRIER_WEIGHT_SEMAPHORE, SETVAL, carrierCapacity); semctl(carrier->semaphores, CARRIER_LENGTH_SEMAPHORE, SETVAL, carrierLength); } void getPackage() { while (1) { if(carrier->currentQueueLength > 0) { if(carrier->carrierQueue[carrier->currentQueueIndex].packageWeight <= truck.truckCapacity - truck.currentWeight) { Package newPackage = carrier->carrierQueue[carrier->currentQueueIndex]; carrier->currentQueueIndex = (carrier->currentQueueIndex + 1)%MAX_QUEUE_SIZE; carrier->currentQueueLength--; incrementSem(carrier->semaphores, CARRIER_WEIGHT_SEMAPHORE, newPackage.packageWeight); incrementSem(carrier->semaphores, CARRIER_LENGTH_SEMAPHORE, 1); truck.currentWeight += newPackage.packageWeight; printf("Załadowano paczkę:\n PID pracownika: %d\n Waga paczki: %d\n Czas oczekiwania paczki: %ld\n Obecny ładunek ciężarówki: %d\n Pozostała pojemność ciężarówki: %d\n", newPackage.workerID, newPackage.packageWeight, time(NULL) - newPackage.loadTime, truck.currentWeight, truck.truckCapacity - truck.currentWeight); sleep(1); } else { printf("Ciężarówka pełna, odjeżdża\n"); truck.currentWeight = 0; sleep(3); printf("Podjeżdża nowa ciężarówka\n"); } } else { printf("Brak ładunków do zapakowania\n"); sleep(1); } } } int main(int argc, char** argv) { signal(SIGTERM, handleSignal); signal(SIGINT, handleSignal); atexit(atExit); if (argc != 4) { fprintf(stderr, "Podano nieprawidłową ilość argumentów\n"); exit(1); } int truckCapacity = stringToInt(argv[1]); int carrierLength = stringToInt(argv[2]); int carrierCapacity = stringToInt(argv[3]); initSems(truckCapacity, carrierLength, carrierCapacity); printf("Podjeżdża nowa ciężarówka\n"); getPackage(); }<file_sep>/cw05/zad02/slave.c #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <time.h> #include <stdarg.h> int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result * 10 + ( string[i] - '0' ); } return result; } char* stringCat(char* buffer, int args, ...) { va_list lst; va_start(lst, args); for(int i=0; i<args; ++i) { strcat(buffer, va_arg(lst, char*)); } va_end(lst); return buffer; } int main(int argc, char* argv[]) { srand(time(NULL)); if(argc < 3) { printf("Podano za małą liczbę argumentów.\n"); } else { const char* fifoPath = argv[1]; const int N = stringToInt(argv[2]); int fifoFile = open(fifoPath, O_RDWR); printf("%d\n", getpid()); for(int i=0; i<N; ++i) { FILE* date = popen("date", "r"); char buff[80]; fread(buff, sizeof(char), 80, date); pclose(date); char pid[20]; sprintf(pid, "%d", getpid()); char* buffer = calloc(120, sizeof(char)); stringCat(buffer, 3, pid, " ", buff); write(fifoFile, buffer, strlen(buff)); free(buffer); sleep(rand()%3 + 2); } close(fifoFile); } }<file_sep>/cw04/zad01/main2.c #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <signal.h> #include <wait.h> int processPID; void sigSTP(int sig, siginfo_t *siginfo, void *context) { if(!waitpid(processPID, NULL, WNOHANG)) { printf("\nOczekuję na CTRL+Z - kontynuacja albo CTR+C - zakończenie programu\n"); kill(processPID, SIGKILL); } else { if (!(processPID = fork())) { execl("/bin/sh", "sh", "./script.sh", (char *) NULL); } } } void sigINT(int signum){ if(!waitpid(processPID, NULL, WNOHANG)) kill(processPID, SIGKILL); printf("\nOdebrano sygnał SIGINT\n"); exit(1); } void printError(char *message) { printf("%s", message); exit(1); } int main(int argc, char **argv) { struct sigaction act; act.sa_sigaction = &sigSTP; act.sa_flags = SA_SIGINFO; sigaction(SIGTSTP, &act, NULL); signal(SIGINT, sigINT); if (!(processPID = fork())) { execl("/bin/sh", "sh", "./script.sh", (char *) NULL); exit(0); } while(1) {} }<file_sep>/cw06/zad02/Makefile GCC=gcc SOURCE_SERVER=server SOURCE_CLIENT=client FLAGS=-Wall -lrt all: compile ./$(SOURCE_SERVER) compile: $(GCC) $(SOURCE_SERVER).c -o $(SOURCE_SERVER) $(FLAGS) $(GCC) $(SOURCE_CLIENT).c -o $(SOURCE_CLIENT) $(FLAGS) clean: rm -rf $(SOURCE_SERVER) $(SOURCE_CLIENT)<file_sep>/cw04/zad01/Makefile GCC=gcc SOURCE1=main SOURCE2=main2 FLAGS=-Wall all: make compile ./$(SOURCE1) ./$(SOURCE2) compile: $(GCC) $(SOURCE1).c -o $(SOURCE1) $(FLAGS) $(GCC) $(SOURCE2).c -o $(SOURCE2) $(FLAGS) clear: rm -rf $(SOURCE1) $(SOURCE2)<file_sep>/cw02/zad01/main.c #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <time.h> #include <sys/times.h> #include <string.h> double clockToTime(clock_t czas) { return (double) (czas) / CLOCKS_PER_SEC; } double clockToTimes(clock_t czas) { int ticks_per_second = sysconf(_SC_CLK_TCK); return (double) (czas) / ticks_per_second; } int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result * 10 + ( string[i] - '0' ); } return result; } void generate(char* fileName, size_t size, int recordNumber) { FILE* file = fopen(fileName, "w+"); if(file) { char* content = calloc(size, sizeof(char)); if(file) { for(int j=0; j<recordNumber; ++j) { for(int i=0; i<size; ++i) { content[i] = (unsigned char) (rand() % 255 + 1); } fwrite(content, sizeof(char), size, file); } } fclose(file); free(content); } else { printf("Wystąpił błąd przy generowaniu pliku\n"); } } int sortLib(char* fileName, int recordNumber, int recordSize) { FILE* file = fopen(fileName, "r+"); if(file) { char* bufferOne = calloc(recordSize, sizeof(char)); char* bufferTwo = calloc(recordSize, sizeof(char)); char one, two; for(int i=0; i<recordNumber; ++i) { fseek(file, i*recordSize, SEEK_SET); fread(&one, sizeof(char), 1, file); int smallestPosition = i; for(int j=i+1; j<recordNumber; ++j) { fseek(file, j*recordSize, SEEK_SET); fread(&two, sizeof(char), 1, file); if(two < one) { smallestPosition = j; one = two; } } fseek(file, i*recordSize, SEEK_SET); fread(bufferOne, sizeof(char), recordSize, file); fseek(file, smallestPosition*recordSize, SEEK_SET); fread(bufferTwo, sizeof(char), recordSize, file); fseek(file, i*recordSize, SEEK_SET); fwrite(bufferTwo, sizeof(char), recordSize, file); fseek(file, smallestPosition*recordSize, SEEK_SET); fwrite(bufferOne, sizeof(char), recordSize, file); } free(bufferOne); free(bufferTwo); fclose(file); return 0; } else { return -1; } } int sortSys(char* fileName, int recordNumber, int recordSize) { int file = open(fileName, O_RDWR); if(file != -1) { char* bufferOne = calloc(recordSize, sizeof(char)); char* bufferTwo = calloc(recordSize, sizeof(char)); char one, two; for(int i=0; i<recordNumber; ++i) { lseek(file, i*recordSize, SEEK_SET); read(file, &one, 1); int smallestPosition = i; for(int j=i+1; j<recordNumber; ++j) { lseek(file, j*recordSize, SEEK_SET); read(file, &two, 1); if(two < one) { smallestPosition = j; one = two; } } lseek(file, i*recordSize, SEEK_SET); read(file, bufferOne, recordSize); lseek(file, smallestPosition*recordSize, SEEK_SET); read(file, bufferTwo, recordSize); lseek(file, i*recordSize, SEEK_SET); write(file, bufferTwo, recordSize); lseek(file, smallestPosition*recordSize, SEEK_SET); write(file, bufferOne, recordSize); } free(bufferOne); free(bufferTwo); close(file); return 0; } else { return -1; } } int copyLib(char* inputFileName, char* outputFileName, int recordNumber, int recordSize) { FILE* inputFile = fopen(inputFileName, "r+"); FILE* outputFile = fopen(outputFileName, "w+"); if(inputFile) { char* buffer = calloc(recordSize, sizeof(char)); for(int i=0; i<recordNumber; ++i) { fread(buffer, sizeof(char), recordSize, inputFile); fwrite(buffer, sizeof(char), recordSize, outputFile); } free(buffer); fclose(inputFile); fclose(outputFile); return 0; } else { return -1; } } int copySys(char* inputFileName, char* outputFileName, int recordNumber, int recordSize) { int inputFile = open(inputFileName, O_RDONLY); int outputFile = open(outputFileName, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR); if(inputFile != -1 && outputFile != -1) { char* buffer = calloc(recordSize, sizeof(char)); for(int i=0; i<recordNumber; ++i) { read(inputFile, buffer, recordSize); int a = write(outputFile, buffer, recordSize); } free(buffer); close(inputFile); close(outputFile); return 0; } else { return -1; } } void copyTime(int (*func)(char*, char*, int, int), char* inputFile, char* outputFile, int recordNumber, int recordSize, char* type) { struct tms timer; times(&timer); clock_t startUser = timer.tms_utime; clock_t startSystem = timer.tms_stime; clock_t start = clock(); int copySuccess = func(inputFile, outputFile, recordNumber, recordSize); clock_t end = clock(); times(&timer); clock_t endUser = timer.tms_utime; clock_t endSystem = timer.tms_stime; double realTime = clockToTime(end - start); double sysTime = clockToTimes(endSystem - startSystem); double userTime = clockToTimes(endUser - startUser); if(!copySuccess) printf("Czas kopiowanie %s dla %d rekordów o rozmiarze %d:\n Rzeczywisty: %fs\n Jądra: %fs\n Użytkownika: %fs\n\n", type, recordNumber, recordSize, realTime, sysTime, userTime); else printf("Wystąpił błąd przy kopiowaniu plików\n"); } void sortTime(int (*func)(char*, int, int), char* fileName, int recordNumber, int recordSize, char* type) { struct tms timer; times(&timer); clock_t startUser = timer.tms_utime; clock_t startSystem = timer.tms_stime; clock_t start = clock(); int sortSuccess = func(fileName, recordNumber, recordSize); clock_t end = clock(); times(&timer); clock_t endUser = timer.tms_utime; clock_t endSystem = timer.tms_stime; double realTime = clockToTime(end - start); double sysTime = clockToTimes(endSystem - startSystem); double userTime = clockToTimes(endUser - startUser); if(!sortSuccess) printf("Czas sortowanie %s dla %d rekordów o rozmiarze %d:\n Rzeczywisty: %fs\n Jądra: %fs\n Użytkownika: %fs\n\n", type, recordNumber, recordSize, realTime, sysTime, userTime); else printf("Wystąpił błąd przy sortowaniu pliku\n"); } int main(int argc, char* argv[]) { srand(time(NULL)); int currentPosition = 1; while(currentPosition < argc - 1) { if(!strcmp(argv[currentPosition],"generate")) { char* fileName = argv[currentPosition + 1]; int recordNumber = stringToInt(argv[currentPosition + 2]); int recordSize = stringToInt(argv[currentPosition + 3]); generate(fileName, recordSize, recordNumber); currentPosition += 4; } else if(!strcmp(argv[currentPosition],"sort")) { char* fileName = argv[currentPosition + 1]; int recordNumber = stringToInt(argv[currentPosition + 2]); int recordSize = stringToInt(argv[currentPosition + 3]); char* type = argv[currentPosition + 4]; if(!strcmp(type,"sys")) { sortTime(sortSys, fileName, recordNumber, recordSize, type); } else if (!strcmp(type,"lib")) { sortTime(sortLib, fileName, recordNumber, recordSize, type); } else { printf("Nieprawidłowy sposób sortowania"); } currentPosition += 5; } else if(!strcmp(argv[currentPosition],"copy")) { char* inputFileName = argv[currentPosition + 1]; char* outputFileName = argv[currentPosition + 2]; int recordNumber = stringToInt(argv[currentPosition + 3]); int recordSize = stringToInt(argv[currentPosition + 4]); char* type = argv[currentPosition + 5]; if(!strcmp(type,"sys")) { copyTime(copySys, inputFileName, outputFileName, recordNumber, recordSize, type); } else if (!strcmp(type,"lib")) { copyTime(copyLib, inputFileName, outputFileName, recordNumber, recordSize, type); } else { printf("Nieprawidłowy sposób kopiowania"); } currentPosition += 6; } else { printf("Nieprawidłowy format, wpisano %s\n", argv[currentPosition]); currentPosition++; } } return 0; }<file_sep>/cw04/zad03/a/sender.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <signal.h> int noOfReceived = 0; void terminate(int signum) { printf("%d\n", noOfReceived); exit(0); } void receive(int signum) { noOfReceived++; } void killMode(int catcherPID, int noOfSignals) { for(int i=0; i<noOfSignals; ++i) { kill(catcherPID, SIGUSR1); } kill(catcherPID, SIGUSR2); } void sigqueueMode(int catcherPID, int noOfSignals) { for(int i=0; i<noOfSignals; ++i) { const union sigval value; sigqueue(catcherPID, SIGUSR1, value); } const union sigval value; sigqueue(catcherPID, SIGUSR2, value); } void sigrtMode(int catcherPID, int noOfSignals) { for(int i=0; i<noOfSignals; ++i) { kill(catcherPID, SIGRTMIN); } kill(catcherPID, SIGRTMAX); } int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result * 10 + ( string[i] - '0' ); } return result; } int main(int argc, char* argv[]) { signal(SIGUSR1, receive); signal(SIGUSR2, terminate); if(argc < 4) { printf("Podano złą liczbę argumentów\n"); } else { int catcherPID = stringToInt(argv[1]); int noOfSignals = stringToInt(argv[2]); int mode = stringToInt(argv[3]); if(mode == 0) { killMode(catcherPID, noOfSignals); } else if(mode == 1) { sigqueueMode(catcherPID, noOfSignals); } else if(mode == 2) { sigrtMode(catcherPID, noOfSignals); } else { printf("Podano nieprawidłowy tryb\n"); exit(0); } } while(1) { } return 0; }<file_sep>/cw01/zad03/Makefile CC = gcc SOURCE=main CFLAGS=-Wall -Os SRCPATH=../zad02 LIBPATH=../zad01 LIBNAME=library OUTPUT=results3a.txt PARAMETERS=create_table 5 search_directory . main tmp1 search_directory ../zad01 main tmp2 remove_block 1 search_directory ../zad01 library.h tmp3 search_directory . aa tmp4 shared_ver: $(CC) -I$(LIBPATH) $(SRCPATH)/$(SOURCE).c -o $(SOURCE)_shared_ver -L$(LIBPATH) $(LIBPATH)/$(LIBNAME).c -Wl,-rpath,$(LIBPATH) echo "\nOpcje GCC: $(CFLAGS), SHARED_LIB_STATS: \n" >> $(OUTPUT) ./$(SOURCE)_shared_ver $(PARAMETERS) >> $(OUTPUT) static_ver: $(CC) -static -I$(LIBPATH) $(SRCPATH)/$(SOURCE).c -o $(SOURCE)_static_ver -L$(LIBPATH) $(LIBPATH)/$(LIBNAME).c echo "\nOpcje GCC: $(CFLAGS), STATIC_LIB_STATS: \n" >> $(OUTPUT) ./$(SOURCE)_static_ver $(PARAMETERS) >> $(OUTPUT) dynamic_ver: $(CC) -I$(LIBPATH) $(SRCPATH)/$(SOURCE).c -o dyn_$(SOURCE) -L$(LIBPATH) $(LIBPATH)/$(LIBNAME).c -ldl echo "\nOpcje GCC: $(CFLAGS), DYNAMIC_LOADING__STATS: \n" >> $(OUTPUT) ./dyn_$(SOURCE) $(PARAMETERS) >> $(OUTPUT) all: make dynamic_ver make static_ver make shared_ver clean: rm -r $(SOURCE)_shared_ver $(SOURCE)_static_ver dyn_$(SOURCE) $(OUTPUT) <file_sep>/cw05/zad01/Makefile GCC=gcc SOURCE=main FILE=lista FLAGS=-Wall all: compile ./$(SOURCE) $(FILE) compile: $(GCC) $(SOURCE).c -o $(SOURCE) $(FLAGS) clear: rm -rf $(SOURCE)<file_sep>/cw04/zad01/main.c #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> #include <time.h> int tstpNo = 0; void sigINT(int signum) { printf("\nOdebrano sygnał SIGINT\n"); exit(0); } void sigSTP(int signum) { tstpNo++; if(tstpNo%2 == 1) printf("\nOczekuję na CTRL+Z - kontynuacja albo CTR+C - zakończenie programu\n"); } int main() { signal(SIGINT, sigINT); struct sigaction act; act.sa_handler = sigSTP; sigemptyset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGTSTP, &act, NULL); while(1) { time_t t = time(NULL); struct tm tm = *localtime(&t); if(tstpNo%2 == 0) { printf("%d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); sleep(1); } } return 0; }<file_sep>/cw04/zad03/b/sender.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <signal.h> int catcherPID; int noOfSignals; int noSend = 0; int noOfReceived = 0; void sendSignal() { if(noSend < noOfSignals) { kill(catcherPID, SIGUSR1); noSend++; } else { kill(catcherPID, SIGUSR2); printf("Wysłano %d, a otrzymano %d\n", noOfSignals, noOfReceived); exit(0); } } void receive(int signum) { noOfReceived++; sendSignal(); } int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result * 10 + ( string[i] - '0' ); } return result; } int main(int argc, char* argv[]) { signal(SIGUSR1, receive); if(argc < 3) { printf("Podano złą liczbę argumentów\n"); } else { catcherPID = stringToInt(argv[1]); noOfSignals = stringToInt(argv[2]); sendSignal(); } while(1) { } return 0; }<file_sep>/cw08/Makefile GCC=gcc SOURCE=main PARAMETERS1=1 block inFile.pgm filter.txt outFile.pgm PARAMETERS2=2 block inFile.pgm filter.txt outFile.pgm PARAMETERS3=4 block inFile.pgm filter.txt outFile.pgm PARAMETERS4=8 block inFile.pgm filter.txt outFile.pgm PARAMETERS5=1 interleaved inFile.pgm filter.txt outFile.pgm PARAMETERS6=2 interleaved inFile.pgm filter.txt outFile.pgm PARAMETERS7=4 interleaved inFile.pgm filter.txt outFile.pgm PARAMETERS8=8 interleaved inFile.pgm filter.txt outFile.pgm TIMES=Times.txt FLAGS=-Wall -lpthread -lm all: compile ./$(SOURCE) $(PARAMETERS1) >> $(TIMES) ./$(SOURCE) $(PARAMETERS2) >> $(TIMES) ./$(SOURCE) $(PARAMETERS3) >> $(TIMES) ./$(SOURCE) $(PARAMETERS4) >> $(TIMES) ./$(SOURCE) $(PARAMETERS5) >> $(TIMES) ./$(SOURCE) $(PARAMETERS6) >> $(TIMES) ./$(SOURCE) $(PARAMETERS7) >> $(TIMES) ./$(SOURCE) $(PARAMETERS8) >> $(TIMES) compile: $(GCC) $(SOURCE).c -o $(SOURCE) $(FLAGS) clean: rm -rf $(SOURCE) $(TIMES)<file_sep>/cw02/zad01/Makefile CC = gcc SOURCE = main CFLAGS = -Wall -O OUTPUT = wyniki.txt SMALLNUMBER = 1000 BIGNUMBER = 5000 SIZE1 = generate tmp $(SMALLNUMBER) 1 copy tmp tmp2 $(SMALLNUMBER) 1 sys copy tmp tmp3 $(SMALLNUMBER) 1 lib sort tmp2 $(SMALLNUMBER) 1 sys sort tmp3 $(SMALLNUMBER) 1 lib generate tmp $(BIGNUMBER) 1 copy tmp tmp2 $(BIGNUMBER) 1 sys copy tmp tmp3 $(BIGNUMBER) 1 lib sort tmp2 $(BIGNUMBER) 1 sys sort tmp3 $(BIGNUMBER) 1 lib SIZE4 = generate tmp $(SMALLNUMBER) 4 copy tmp tmp2 $(SMALLNUMBER) 4 sys copy tmp tmp3 $(SMALLNUMBER) 4 lib sort tmp2 $(SMALLNUMBER) 4 sys sort tmp3 $(SMALLNUMBER) 4 lib generate tmp $(BIGNUMBER) 4 copy tmp tmp2 $(BIGNUMBER) 4 sys copy tmp tmp3 $(BIGNUMBER) 4 lib sort tmp2 $(BIGNUMBER) 4 sys sort tmp3 $(BIGNUMBER) 4 lib SIZE512 = generate tmp $(SMALLNUMBER) 512 copy tmp tmp2 $(SMALLNUMBER) 512 sys copy tmp tmp3 $(SMALLNUMBER) 512 lib sort tmp2 $(SMALLNUMBER) 512 sys sort tmp3 $(SMALLNUMBER) 512 lib generate tmp $(BIGNUMBER) 512 copy tmp tmp2 $(BIGNUMBER) 512 sys copy tmp tmp3 $(BIGNUMBER) 512 lib sort tmp2 $(BIGNUMBER) 512 sys sort tmp3 $(BIGNUMBER) 512 lib SIZE1024 = generate tmp $(SMALLNUMBER) 1024 copy tmp tmp2 $(SMALLNUMBER) 1024 sys copy tmp tmp3 $(SMALLNUMBER) 1024 lib sort tmp2 $(SMALLNUMBER) 1024 sys sort tmp3 $(SMALLNUMBER) 1024 lib generate tmp $(BIGNUMBER) 1024 copy tmp tmp2 $(BIGNUMBER) 1024 sys copy tmp tmp3 $(BIGNUMBER) 1024 lib sort tmp2 $(BIGNUMBER) 1024 sys sort tmp3 $(BIGNUMBER) 1024 lib SIZE4096 = generate tmp $(SMALLNUMBER) 4096 copy tmp tmp2 $(SMALLNUMBER) 4096 sys copy tmp tmp3 $(SMALLNUMBER) 4096 lib sort tmp2 $(SMALLNUMBER) 4096 sys sort tmp3 $(SMALLNUMBER) 4096 lib generate tmp $(BIGNUMBER) 4096 copy tmp tmp2 $(BIGNUMBER) 4096 sys copy tmp tmp3 $(BIGNUMBER) 4096 lib sort tmp2 $(BIGNUMBER) 4096 sys sort tmp3 $(BIGNUMBER) 4096 lib SIZE8192 = generate tmp $(SMALLNUMBER) 8192 copy tmp tmp2 $(SMALLNUMBER) 8192 sys copy tmp tmp3 $(SMALLNUMBER) 8192 lib sort tmp2 $(SMALLNUMBER) 8192 sys sort tmp3 $(SMALLNUMBER) 8192 lib generate tmp $(BIGNUMBER) 8192 copy tmp tmp2 $(BIGNUMBER) 8192 sys copy tmp tmp3 $(BIGNUMBER) 8192 lib sort tmp2 $(BIGNUMBER) 8192 sys sort tmp3 $(BIGNUMBER) 8192 lib compile: $(CC) $(SOURCE).c -o $(SOURCE) 1: ./$(SOURCE) $(SIZE1) >> $(OUTPUT) 4: ./$(SOURCE) $(SIZE4) >> $(OUTPUT) 512: ./$(SOURCE) $(SIZE512) >> $(OUTPUT) 1024: ./$(SOURCE) $(SIZE1024) >> $(OUTPUT) 4096: ./$(SOURCE) $(SIZE4096) >> $(OUTPUT) 8192: ./$(SOURCE) $(SIZE8192) >> $(OUTPUT) all: make compile make 1 make 4 make 512 make 1024 make 4096 make 8192 clean: rm -r $(SOURCE) $(OUTPUT) <file_sep>/cw04/zad03/a/Makefile GCC=gcc SOURCE1=catcher SOURCE2=sender FLAGS=-Wall compile: $(GCC) $(SOURCE1).c -o $(SOURCE1) $(FLAGS) $(GCC) $(SOURCE2).c -o $(SOURCE2) $(FLAGS) clear: rm -rf $(SOURCE1) $(SOURCE2)<file_sep>/cw01/zad02/main.c #include "../zad01/library.h" #include <sys/times.h> #include <time.h> #include <unistd.h> #include <limits.h> #include <string.h> typedef struct operationTimes { double wholeTime; double userTime; double systemTime; } operationTimes; int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result * 10 + ( string[i] - '0' ); } return result; } double clockToTime(clock_t czas) { return (double) (czas) / CLOCKS_PER_SEC; } double clockToTimes(clock_t czas) { int ticks_per_second = sysconf(_SC_CLK_TCK); return (double) (czas) / ticks_per_second; } int main(int argc, char* argv[]) { int size = stringToInt(argv[2]); int currentPosition = 3; struct tms timer; operationTimes operationTime; blocksContainer* container = createBlocksContainer(size); while(currentPosition < argc - 1) { if(!strcmp(argv[currentPosition],"search_directory")) { char* directory = argv[currentPosition + 1]; char* fileName = argv[currentPosition + 2]; char* tmpFileName = argv[currentPosition + 3]; times(&timer); clock_t startUser = timer.tms_utime; clock_t startSystem = timer.tms_stime; clock_t startClock = clock(); initSearch(container, directory, fileName, tmpFileName); clock_t endClock = clock(); times(&timer); clock_t endUser = timer.tms_utime; clock_t endSystem = timer.tms_stime; operationTime.wholeTime = clockToTime(endClock - startClock); operationTime.userTime = clockToTimes(endUser - startUser); operationTime.systemTime = clockToTimes(endSystem - startSystem); printf("add %s/%s\n Łączny czas: %fs\n Czas uĹĽytkownika: %fs\n Czas jÄ…dra: %fs\n", directory, fileName, operationTime.wholeTime, operationTime.userTime, operationTime.systemTime); currentPosition += 4; } else if(!strcmp(argv[currentPosition],"remove_block")) { int index = stringToInt(argv[currentPosition + 1]); char* file = calloc(container->singleBlockArray[index]->singleBlockSize, sizeof(char)); strcpy(file, container->singleBlockArray[index]->singleBlockContent); times(&timer); clock_t startUser = timer.tms_utime; clock_t startSystem = timer.tms_stime; clock_t startClock = clock(); deleteSingleBlock(container, index); clock_t endClock = clock(); times(&timer); clock_t endUser = timer.tms_utime; clock_t endSystem = timer.tms_stime; operationTime.wholeTime = clockToTime(endClock - startClock); operationTime.userTime = clockToTimes(endUser - startUser); operationTime.systemTime = clockToTimes(endSystem - startSystem); printf("remove /%s\n Łączny czas: %fs\n Czas uĹĽytkownika: %fs\n Czas jÄ…dra: %fs\n", file, operationTime.wholeTime, operationTime.userTime, operationTime.systemTime); free(file); currentPosition += 2; } else { printf("NieprawidĹ‚owy format, wpisano %s\n", argv[currentPosition]); currentPosition++; } } // for(int i=0; i<=container->blocksContainerIndex; ++i) { // printf("%s\n", container->singleBlockArray[i]->singleBlockContent); // } }<file_sep>/cw04/zad03/a/catcher.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> int receivedNo = 0; void ignore(int signum) { printf("Ignored\n"); } void receive(int signum) { receivedNo++; } void send(int sig, siginfo_t *info, void *context) { int signalPid = info->si_pid; for(int i=0; i<receivedNo; ++i) { kill(signalPid, SIGUSR1); } kill(signalPid, SIGUSR2); exit(0); } int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result * 10 + ( string[i] - '0' ); } return result; } int main(int argc, char* argv[]) { printf("%d\n", getpid()); struct sigaction act; act.sa_handler = ignore; sigfillset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGINT, &act, NULL); struct sigaction sa; sa.sa_flags = SA_SIGINFO; sa.sa_sigaction = send; sigaction(SIGUSR2, &sa, NULL); struct sigaction se; se.sa_flags = SA_SIGINFO; se.sa_sigaction = send; sigaction(SIGRTMAX, &se, NULL); signal(SIGUSR1, receive); signal(SIGRTMIN, receive); while(1) { } return 0; }<file_sep>/cw03/zad01/main.c #define _XOPEN_SOURCE 500 #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <string.h> #include <ftw.h> #include <sys/types.h> #include <unistd.h> void printData(const char* path, int pid, char* command) { printf("Katalog: %s\nPID: %d\n", path, pid); system(command); printf("\n"); exit(0); } int checkData(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf) { if(tflag == FTW_D) { pid_t child_pid; child_pid = vfork(); if(child_pid == 0) { char* command = calloc(999, sizeof(char)); strcat(command, "ls -l "); strcat(command, fpath); printData(fpath, (int)getpid(), command); } } return 0; } int main(int argc, char* argv[]) { char* startDir = argv[1]; int flags = 0; flags |= FTW_PHYS; if(argc < 2) { printf("Podano złą liczbę argumentów\n"); } else { nftw(startDir, checkData, 20, flags); } return 0; } <file_sep>/cw08/main.c #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <unistd.h> #include <string.h> #include <pthread.h> #include <math.h> #include <sys/time.h> typedef struct imageMatrix { int width; int height; unsigned char** matrix; } imageMatrix; imageMatrix inFileMatrix; imageMatrix filterMatrix; imageMatrix outFileMatrix; int threadsNo; int max(int first, int second) { return first > second ? first : second; } int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result*10 + (string[i] - '0'); } return result; } long getMicrotime(){ struct timeval currentTime; gettimeofday(&currentTime, NULL); return currentTime.tv_sec * (int)1e6 + currentTime.tv_usec; } void missLines(FILE* file, int linesNo) { char* line = NULL; size_t len; for(int i=0; i<linesNo; ++i) { getline(&line, &len, file); } } void getMatrix(imageMatrix* matrix, FILE* inFile) { missLines(inFile, 2); size_t len = 0; char* line = NULL; if(getline(&line, &len, inFile) != -1) { strtok(line, " "); matrix->width = stringToInt(line); line = strtok(NULL, " \n\r"); matrix->height = stringToInt(line); } matrix->matrix = calloc(matrix->height, sizeof(char*)); for(int i=0; i<matrix->height; ++i) { unsigned char* row = calloc(matrix->width, sizeof(char)); matrix->matrix[i] = row; } missLines(inFile, 1); getline(&line, &len, inFile); line = strtok(NULL, " \n\r"); for(int i=0; i<matrix->height; ++i) { for(int j=0; j<matrix->width; ++j) { if(!line) { getline(&line, &len, inFile); line = strtok(line, " \n\r"); if(!line) break; } matrix->matrix[i][j] = stringToInt(line); line = strtok(NULL, " \n\r"); } } } void getOutMatrix(imageMatrix* matrix) { matrix->height = inFileMatrix.height; matrix->width = inFileMatrix.width; matrix->matrix = calloc(matrix->height, sizeof(char*)); for(int i=0; i<matrix->height; ++i) { unsigned char* row = calloc(matrix->width, sizeof(char)); matrix->matrix[i] = row; for(int j=0; j<matrix->width; ++j) { matrix->matrix[i][j] = 0; } } } void filter(int i, int j) { for(int k=0; k<filterMatrix.height; ++k) { for(int l=0; l<filterMatrix.height; ++l) { int half = (int) ceil(0.5*filterMatrix.width); int processedPixel = inFileMatrix.matrix[max(1, i - half + k)][max(1, j - half + l)]; outFileMatrix.matrix[i][j] += processedPixel * filterMatrix.matrix[k][l]/100; } } } void* blockMode(void* id) { long int start = getMicrotime(); int thisId = *((int *) id) + 1; int height = outFileMatrix.height; int sector = (int) ceil(1.0*height/threadsNo); for(int i=(thisId-1)*sector; i<thisId*sector && i<outFileMatrix.height - filterMatrix.height/2; ++i) { for(int j=0; j<inFileMatrix.width; ++j) { filter(i, j); } } printf(" Czas wątku %d: %ld\n", thisId, getMicrotime() - start); pthread_exit(0); } void* interleavedMode(void* id) { long int start = getMicrotime(); int thisId = *((int *) id) + 1; int height = outFileMatrix.height; for(int i=thisId-1;i<outFileMatrix.height - filterMatrix.height/2; i+=threadsNo) { for(int j=0; j<inFileMatrix.width; ++j) { filter(i, j); } } printf(" Czas wątku %d: %ld\n", thisId, getMicrotime() - start); pthread_exit(0); } void createOutImage(FILE* outFile) { char* text = calloc(20, sizeof(char)); sprintf(text, "P2\n%d %d\n255\n", outFileMatrix.width, outFileMatrix.height); fwrite(text, sizeof(char), strlen(text), outFile); for(int i=0; i<outFileMatrix.height; ++i) { char* buffer = calloc(outFileMatrix.width*4, sizeof(char)); for(int j=0; j<outFileMatrix.width; ++j) { char one[4]; sprintf(one, "%d ", outFileMatrix.matrix[i][j]); strcat(buffer, one); } fwrite(buffer, sizeof(char), strlen(buffer), outFile); free(buffer); } } int main(int argc, char** argv) { long int start = getMicrotime(); if(argc != 6) { fprintf(stderr, "Podano złą liczbę argumentów\n"); exit(0); } FILE* inFile = fopen(argv[3], "r"); FILE* filterFile = fopen(argv[4], "r"); FILE* outFile = fopen(argv[5], "w"); threadsNo = stringToInt(argv[1]); pthread_t threads[threadsNo]; char* mode = argv[2]; printf("%d wątków %s\n", threadsNo, mode); getMatrix(&inFileMatrix, inFile); getMatrix(&filterMatrix, filterFile); getOutMatrix(&outFileMatrix); for(int i=0; i<threadsNo; ++i) { pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); int *arg = malloc(sizeof(*arg)); *arg = i; if(!strcmp(mode, "block")) { pthread_create(&thread, &attr, &blockMode, arg); } else if(!strcmp(mode, "interleaved")) { pthread_create(&thread, &attr, &interleavedMode, arg); } else { fprintf(stderr, "Podano zły tryb\n"); exit(0); } threads[i] = thread; } for(int i=0; i<threadsNo; ++i) { pthread_join(threads[i], NULL); } createOutImage(outFile); printf(" Całkowity czas: %ld\n", getMicrotime() - start); return 0; }<file_sep>/cw01/zad01/library.c #include "library.h" #include <stdlib.h> #include <string.h> #include <stdio.h> blocksContainer* createBlocksContainer(int blocksContainerSize) { blocksContainer* tmpContainer = calloc(1, sizeof(blocksContainer)); tmpContainer->blocksContainerSize = blocksContainerSize; tmpContainer->blocksContainerIndex = -1; tmpContainer->singleBlockArray = calloc(blocksContainerSize, sizeof(singleBlock)); return tmpContainer; } int createSingleBlock(blocksContainer* blocksContainer, int blocksContainerIndex, char* content, int singleBlockSize) { content = realloc(content, singleBlockSize); singleBlock* singleBlock = calloc(1, sizeof(singleBlock)); singleBlock->singleBlockSize = singleBlockSize; singleBlock->singleBlockContent = content; blocksContainer->singleBlockArray[blocksContainerIndex] = singleBlock; return blocksContainerIndex; } void deleteSingleBlock(blocksContainer* blocksContainer, int blockContainerIndex) { if(blockContainerIndex <= blocksContainer->blocksContainerIndex) { free(blocksContainer->singleBlockArray[blockContainerIndex]->singleBlockContent); blocksContainer->singleBlockArray[blockContainerIndex]->singleBlockContent = ""; blocksContainer->singleBlockArray[blockContainerIndex]->singleBlockSize = 0; } } void initSearch(blocksContainer* blocksContainer, char* directory, char* fileName, char* tmpFileName) { blocksContainer->directory = directory; blocksContainer->fileName = fileName; char* command = calloc(STR_DEF_SIZE, sizeof(char)); strcat(command, "find "); strcat(command, directory); strcat(command, " -name "); strcat(command, fileName); strcat(command, " > "); strcat(command, tmpFileName); int systemSuccess = system(command); if(systemSuccess != -1) { FILE* outputFile = fopen(tmpFileName, "r"); char* str = calloc(STR_DEF_SIZE, sizeof(char)); char* content = calloc(STR_DEF_SIZE, sizeof(char)); if(outputFile) { while(fscanf(outputFile,"%s", str)!=EOF) { strcat(content, str); strcat(content, " "); } if(!strcmp(content,"")) { strcat(content, "Nie odnalezniono pliku."); } } if(blocksContainer->blocksContainerSize-1 >= blocksContainer->blocksContainerIndex + 1) { createSingleBlock(blocksContainer, ++blocksContainer->blocksContainerIndex, content, strlen(content)); // printf("Wyszukiwanie %s w %s powiodło się!\n", fileName, directory); } else { printf("Brak miejsca w tablicy na wynik wyszukiwania pliku %s w folderze %s!\n", fileName, directory); } fclose(outputFile); } else { printf("Wywolanie komendy nie powiodło się!\n"); } }<file_sep>/cw03/zad03/Makefile GCC=gcc SOURCE=main FLAGS=-Wall PARAMETERS=lista 30 0 100 100 ARCHIVE=archive all: make compile ./$(SOURCE) $(PARAMETERS) compile: $(GCC) $(SOURCE).c -o $(SOURCE) $(FLAGS) clear: rm -rf $(ARCHIVE) $(SOURCE) mkdir $(ARCHIVE)<file_sep>/cw10/Makefile CC = gcc SERVER=server CLIENT=client FLAGS=-Wall -lpthread -lm all: compile ./$(SERVER) compile: $(CC) $(SERVER).c -o $(SERVER) $(FLAGS) $(CC) $(CLIENT).c -o $(CLIENT) $(FLAGS) clean: rm -rf $(SERVER) $(CLIENT)<file_sep>/cw05/zad01/main.c #include <stdlib.h> #include <sys/types.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <wait.h> int getNumberOfTokens(char* string, char* tokens) { int noOfTokens = 1; char* stringCpy = calloc(strlen(string), sizeof(char)); strcpy(stringCpy, string); strtok(stringCpy, tokens); while(strtok(NULL, tokens)) { noOfTokens++; } free(stringCpy); return noOfTokens; } char** getCommandElements(char *line){ char tokens[3] = {' ','\n','\t'}; int noOfArguments = getNumberOfTokens(line, tokens); char** arguments = calloc(noOfArguments+1, sizeof(char*)); arguments[0] = strtok(line, tokens); for(int i=1; i<noOfArguments; ++i) { arguments[i] = strtok(NULL, tokens); } arguments[noOfArguments] = NULL; return arguments; } void execLine(char* line) { char tokens[1] = {'|'}; int pipes[2][2]; int commandsNumber = getNumberOfTokens(line, tokens); char **commands = calloc(commandsNumber, sizeof(char*)); commands[0] = strtok(line, tokens); for(int i=1; i<commandsNumber; ++i) { commands[i] = strtok(NULL, tokens); } for (int i=0; i<commandsNumber; ++i) { if (i>0) { close(pipes[i % 2][0]); close(pipes[i % 2][1]); } if(pipe(pipes[i % 2]) == -1) { printf("Błąd potoku\n"); exit(-1); } if (fork() == 0) { char** commandElements = getCommandElements(commands[i]); if (i != commandsNumber-1) { close(pipes[i % 2][0]); if (dup2(pipes[i % 2][1], STDOUT_FILENO) < 0) { exit(-1); }; } if (i != 0) { close(pipes[(i + 1) % 2][1]); if (dup2(pipes[(i + 1) % 2][0], STDIN_FILENO) < 0) { close(-1); } } execvp(commandElements[0], commandElements); free(commandElements); exit(0); } } free(commands); close(pipes[commandsNumber % 2][0]); close(pipes[commandsNumber % 2][1]); close(pipes[(commandsNumber + 1) % 2][0]); close(pipes[(commandsNumber + 1) % 2][1]); for(int i=0; i<commandsNumber; ++i) { wait(NULL); } } int main(int argc, char* argv[]) { if(argc < 2) { printf("Podano za małą liczbę argumentów.\n"); } else { char* listaPath = argv[1]; FILE* lista = fopen(listaPath, "r"); if(lista) { fseek(lista, 0L, SEEK_END); int size = ftell(lista); fseek(lista, 0L, SEEK_SET); char* buff = calloc(size, sizeof(char)); if(fread(buff, sizeof(char), size, lista)) { char tokens[1] = {'\n'}; int noOfLines = getNumberOfTokens(buff, tokens); char* lines[noOfLines]; char* first = strtok(buff, "\n"); printf("\n"); for(int i=0; i<noOfLines; ++i) { lines[i] = first; first = strtok(NULL, "\n"); } for(int i=0; i<noOfLines; ++i) { execLine(lines[i]); } } free(buff); } } }<file_sep>/cw01/zad01/library.h #ifndef INC_1_LIBRARY_H #define INC_1_LIBRARY_H #include <stdlib.h> #include <string.h> #include <stdio.h> #define STR_DEF_SIZE 9999 typedef struct singleBlock { char* singleBlockContent; int singleBlockSize; } singleBlock; typedef struct blocksContainer { singleBlock** singleBlockArray; int blocksContainerSize; int blocksContainerIndex; char* directory; char* fileName; } blocksContainer; blocksContainer* createBlocksContainer(int blocksContainerSize); int createSingleBlock(blocksContainer* blocksContainer, int blocksContainerIndex, char* content, int singleBlockSize); void deleteSingleBlock(blocksContainer* blocksContainer, int blockContainerIndex); void initSearch(blocksContainer* blocksContainer, char* directory, char* fileName, char* tmpFileName); #endif<file_sep>/cw10/server.c #include <unistd.h> #include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #include <pthread.h> #include <sys/epoll.h> #include <string.h> #define PORT 8080 typedef struct clients { int index; int working[10]; char** clientsNames; struct epoll_event monitorsEvents[10]; } clients; clients serverClients; int serverFileDescriptor; struct sockaddr_in serverAddress; int addrlen = sizeof(serverAddress); int monitorDescriptor; void readClient(int clientDescriptor) { char* read_buffer = calloc(100, sizeof(char)); int bytes_read = recv(clientDescriptor, read_buffer, 100, MSG_DONTWAIT); if(bytes_read != -1) { printf("Read '%s'\n", read_buffer); for(int i=0; i<serverClients.index; ++i) { if(serverClients.monitorsEvents[i].data.fd == clientDescriptor) { serverClients.working[i] = 0; } } //send(clientDescriptor, read_buffer, strlen(read_buffer), 0); } free(read_buffer); } int clientRegistered(char* clientName) { for(int i=0; i<serverClients.index; ++i) { if(!strcmp(clientName, serverClients.clientsNames[i])) { return 1; } } return 0; } void* acceptClients() { while(1) { int newClientSocket; if((newClientSocket = accept(serverFileDescriptor, (struct sockaddr*) &serverAddress, (socklen_t*) &addrlen)) >= 0) { char* newClientName = calloc(10, sizeof(char)); read(newClientSocket, newClientName, 10); if(!clientRegistered(newClientName)) { serverClients.clientsNames[serverClients.index] = newClientName; serverClients.working[serverClients.index++] = 0; struct epoll_event monitorEvent; monitorEvent.events = EPOLLIN | EPOLLOUT; union epoll_data monitorData; monitorData.fd = newClientSocket; monitorEvent.data = monitorData; send(newClientSocket, "Zarejestrowano", 20, 0); epoll_ctl(monitorDescriptor, EPOLL_CTL_ADD , newClientSocket, &monitorEvent); } else { send(newClientSocket, "Już zarejestrowany", 20, 0); } } } } void* readClients() { while(1) { epoll_wait(monitorDescriptor, serverClients.monitorsEvents, 10, -1); for(int i = 0; i<serverClients.index; i++) { readClient(serverClients.monitorsEvents[i].data.fd); } } } void* readTerminal() { while(1) { char* fileName = calloc(1024, sizeof(char)); scanf("%s", fileName); FILE* textFile = fopen(fileName, "r"); fseek(textFile, 0L, SEEK_END); int fileLength = ftell(textFile); fseek(textFile, 0L, SEEK_SET); char* text = calloc(fileLength, sizeof(char)); char* line; size_t len = 0; while(getline(&line, &len, textFile) != -1) { strcat(text, line); } serverClients.working[0] = 1; char* fileLengthString = calloc(100, sizeof(char)); sprintf(fileLengthString, "%d", fileLength); send(serverClients.monitorsEvents[0].data.fd, fileLengthString, 100, 0); send(serverClients.monitorsEvents[0].data.fd, text, fileLength, 0); free(fileLengthString); free(text); } } int main(int argc, char const *argv[]) { int opt = 1; serverClients.index = 0; serverClients.clientsNames = calloc(10, sizeof(char*)); if(!(serverFileDescriptor = socket(AF_INET, SOCK_STREAM, 0))) { fprintf(stderr, "Tworzenie socketa nie powiodło się\n"); exit(1); } if(setsockopt(serverFileDescriptor, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { fprintf(stderr, "Ustawienie opcji socketa nie powiodło się\n"); exit(1); } serverAddress.sin_family = AF_INET; serverAddress.sin_addr.s_addr = INADDR_ANY; serverAddress.sin_port = htons(PORT); if(bind(serverFileDescriptor, (struct sockaddr*) &serverAddress, sizeof(serverAddress)) < 0) { fprintf(stderr, "Bindowanie socketa nie powiodło się\n"); exit(1); } if(listen(serverFileDescriptor, 10) < 0) { fprintf(stderr, "Nasłuchiwanie socketa nie powiodło się\n"); exit(1); } monitorDescriptor = epoll_create1(0); pthread_t acceptThread; pthread_t readThread; pthread_t terminalThread; pthread_create(&acceptThread, NULL, acceptClients, NULL); pthread_create(&readThread, NULL, readClients, NULL); pthread_create(&terminalThread, NULL, readTerminal, NULL); pthread_join(acceptThread, NULL); pthread_join(readThread, NULL); pthread_join(terminalThread, NULL); return 0; }<file_sep>/cw02/zad02/b/main.c #define _XOPEN_SOURCE 500 #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <dirent.h> #include <string.h> #include <sys/stat.h> #include <time.h> #include <ftw.h> #include <stdint.h> char* mode; int day; int month; int year; int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result * 10 + ( string[i] - '0' ); } return result; } char* getType(int fileType) { char* type; switch (fileType) { case FTW_F: type = "file"; break; case FTW_D: type = "dir"; break; case FTW_SL: type = "slink"; break; default: type ="error"; break; } return type; } char* getDateFromTimestamp(time_t timestamp, struct tm* ts) { char* date = calloc(80, sizeof(char)); *ts = *localtime(&timestamp); strftime(date, 80*sizeof(char), "%a %Y-%m-%d %H:%M:%S %Z", ts); return date; } void printData(int tflag, const struct stat *stats, const char* newPath, struct tm* ts) { char* type = getType(tflag); char* path = realpath(newPath, NULL); char* aDate = getDateFromTimestamp(stats->st_atime, ts); char* mDate = getDateFromTimestamp(stats->st_mtime, ts); printf("%s:\n Pełna ścieżka: %s\n Rodzaj pliku: %s\n Rozmiar pliku: %ld B\n Data ostatniego dostępu: %s\n Data ostatnie modyfikacji: %s\n", newPath, path, type, stats->st_size, aDate, mDate); } int checkData(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf) { struct tm ts = *localtime(&sb->st_mtime); if(mode[0] == '=') { if(ts.tm_mday == day && ts.tm_mon == month && ts.tm_year == year) { printData(tflag, sb, fpath, &ts); } } else if(mode[0] == '<') { if(ts.tm_year < year || (ts.tm_year == year && ts.tm_mon < month) || (ts.tm_year == year && ts.tm_mon == month && ts.tm_mday < day)) { printData(tflag, sb, fpath, &ts); } } else if(mode[0] == '>') { if(ts.tm_year > year || (ts.tm_year == year && ts.tm_mon > month) || (ts.tm_year == year && ts.tm_mon == month && ts.tm_mday > day)) { printData(tflag, sb, fpath, &ts); } } return 0; } int main(int argc, char* argv[]) { char* startDir = argv[1]; mode = argv[2]; day = stringToInt(argv[3]); month = stringToInt(argv[4]) -1; year = stringToInt(argv[5])- 1900; int flags = 0; flags |= FTW_PHYS; if(argc < 6) { printf("Podano złą liczbę argumentów\n"); } else if(strcmp(mode, "=") && strcmp(mode, ">") && strcmp(mode, "<")) { printf("Wprowadzono nieprawidłowy znak porówniania\n"); } else { nftw(startDir, checkData, 20, flags); } return 0; } <file_sep>/cw06/zad02/server.c #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #include <signal.h> #include <string.h> #include <time.h> #include <mqueue.h> #include "chat.h" mqd_t serverQueue; int lastClientIndex = -1; mqd_t clientsQueues[MAX_CLIENTS]; int lastFriendIndex = -1; int friends[MAX_CLIENTS]; Message receiveMessage(int queue) { Message message; if(mq_receive(queue, (char *)&message, MESSAGE_SIZE, NULL)) { return message; } else { fprintf(stderr, "Wystąpił problem z odbieraniem wiadomości z kolejki serwera"); exit(1); } } void sendMessageToClient(int queue, long messageType, char* messageText, long clientID, int textLength) { Message message; message.type = messageType; message.clientID = clientID; message.textLength = textLength; if(textLength <= MAX_MESSAGE_LENGTH && textLength >= 0) { strcpy(message.text, messageText); } else { fprintf(stderr, "Wysyłana do klienta wiadomość ma nieprawidłową długość"); exit(1); } if(mq_send(queue, (char*) &message, MESSAGE_SIZE, 1) == -1) { fprintf(stderr, "Wysyłanie wiadomości do klienta nie powiodło się"); exit(1); } } void manageInitMessage(Message message) { lastClientIndex++; if(lastClientIndex >= MAX_CLIENTS) { fprintf(stderr, "Przekroczono maksymalną liczbę klientów"); exit(1); } char clientQueuePath[15]; sprintf(clientQueuePath, "/%ld", message.clientID); if ((clientsQueues[lastClientIndex] = mq_open(clientQueuePath, O_WRONLY))) { sendMessageToClient(clientsQueues[lastClientIndex], INIT, "Wiadomośc nawiązania połączenia", lastClientIndex, 0); } else { fprintf(stderr, "Wystąpił problem z odnalezieniem kolejki klienta"); exit(1); } } char* addClientAndTimeToText(Message* message) { time_t now; time(&now); char* result = calloc(MAX_MESSAGE_LENGTH + 100, sizeof(char)); sprintf(result, "%s Czas: %s Klient: %ld", message->text, ctime(&now), message->clientID); message->textLength = strlen(result); return result; } void manageEchoMessage(Message message) { char* messageText = addClientAndTimeToText(&message); sendMessageToClient(clientsQueues[message.clientID], ECHO, messageText, 0, message.textLength); free(messageText); } void manageToOneMessage(Message message) { char* messageText = addClientAndTimeToText(&message); sendMessageToClient(clientsQueues[message.clientID], ECHO, messageText, 0, message.textLength); free(messageText); } void manageListMessage(Message message) { char* result = calloc((lastClientIndex+1) * 50, sizeof(char)); for(int i=0; i<=lastClientIndex; ++i) { char part[50]; sprintf(part, "Klient: %d kolejka: %d | ", i, clientsQueues[i]); strcat(result, part); } sendMessageToClient(clientsQueues[message.clientID], ECHO, result, 0, (lastClientIndex+1) * 50); } void manageToAllMessage(Message message) { char* messageText = addClientAndTimeToText(&message); for(int i=0; i<=lastClientIndex; ++i) { if(clientsQueues[i] != 0) { sendMessageToClient(clientsQueues[i], ECHO, messageText, 0, message.textLength); } } free(messageText); } void manageAddFriendsMessage(Message message) { char* friendsString = calloc(message.textLength, sizeof(char)); strcpy(friendsString, message.text); char *friend = strtok(friendsString, " "); while(friend != NULL) { int alreadyInList = 0; int friendID = atoi(friend); lastFriendIndex++; for(int i = 0; i<lastFriendIndex; i++) { if(friends[i] == friendID) { alreadyInList = 1; } } if(alreadyInList) { fprintf(stderr, "Dodano dwóch jednakowych znajomych do listy"); exit(1); } friends[lastFriendIndex] = friendID; if(lastClientIndex >= MAX_CLIENTS) { fprintf(stderr, "Dodano zbyt wielu znajomych do listy"); exit(1); } friend = strtok(NULL, " "); } free(friendsString); } void manageFriendsMessage(Message message) { lastFriendIndex = -1; for(int i = 0; i<MAX_CLIENTS; i++) { friends[i] = -1; } manageAddFriendsMessage(message); } void manageDelFriendsMessage(Message message) { char* friendsString = calloc(message.textLength, sizeof(char)); strcpy(friendsString, message.text); char *friend = strtok(friendsString, " "); while(friend != NULL) { int friendID = atoi(friend); for(int i=0; i<=lastFriendIndex; ++i) { if(friends[i] == friendID) { for(int j=i; j<lastFriendIndex; ++j) { friends[j] = friends[j+1]; } lastFriendIndex--; } } friend = strtok(NULL, " "); } free(friendsString); } void manageToFriendsMessage(Message message) { char* messageText = addClientAndTimeToText(&message); for(int i=0; i<=lastFriendIndex; ++i) { if(clientsQueues[i] != 0) { sendMessageToClient(clientsQueues[friends[i]], ECHO, messageText, 0, message.textLength); } } free(messageText); } void normalizeQueue() { for(int i=0; i<=lastClientIndex; ++i) { if(clientsQueues[i] == 0) { for(int j=i; j<lastClientIndex; ++j) { clientsQueues[j] = clientsQueues[j+1]; } lastClientIndex--; } } } void manageStopMessage(Message message) { clientsQueues[message.clientID] = 0; normalizeQueue(); } void manageReceivedMessage(Message message) { switch (message.type) { case ECHO: manageEchoMessage(message); break; case LIST: manageListMessage(message); break; case FRIENDS: manageFriendsMessage(message); break; case ADD: manageAddFriendsMessage(message); break; case DEL: manageDelFriendsMessage(message); break; case TO_ALL: manageToAllMessage(message); break; case TO_FRIENDS: manageToFriendsMessage(message); break; case TO_ONE: manageToOneMessage(message); break; case STOP: manageStopMessage(message); break; case INIT: manageInitMessage(message); break; } } void atExit() { for (int i = 0; i<=lastClientIndex; ++i) { if (clientsQueues[i] != 0) { char* description = "Wiadomość zakończenia działania"; sendMessageToClient(clientsQueues[i], STOP, description, 0, strlen(description)); mq_close(clientsQueues[i]); receiveMessage(serverQueue); } } mq_close(serverQueue); mq_unlink(SERVER); } void handleSIGINT(int signum) { printf("\nSIGINT - kończenie procesu serwera\n"); exit(0); } int main() { atexit(atExit); signal(SIGINT, handleSIGINT); Message receivedMessage; struct mq_attr messageAttributes; messageAttributes.mq_maxmsg = MAX_MESSAGES; messageAttributes.mq_msgsize = MESSAGE_SIZE; for(int i = 0; i<MAX_CLIENTS; i++){ friends[i] = -1; } if ((serverQueue = mq_open(SERVER, O_RDONLY | O_CREAT | O_EXCL, 0666, &messageAttributes))) { printf("Wystartowano serwer o ID %d\n", serverQueue); while(1) { receivedMessage = receiveMessage(serverQueue); printf("Otrzymano wiadomość: \n Typ: %s \n Klient: %ld\n Treść: %s\n", getTypeName(receivedMessage.type), receivedMessage.clientID, receivedMessage.text); manageReceivedMessage(receivedMessage); } } else { fprintf(stderr, "Wystąpił problem z tworzeniem kolejki dla serwera"); exit(1); } }
42bf4452c6832b7bedd01a8ed92df4c237ba75db
[ "C", "Makefile", "Shell" ]
40
Makefile
RetroSuperHero/SysOpy
d081acbed78f44e3a5302250474ff50a7cb3bf5e
2be222421a8ab92ed78a07f88c2a391b43772115
refs/heads/master
<file_sep>package troubleShootSearch.util; public class MyLogger { // FIXME: Add more enum values as needed for the assignment public static enum DebugLevel { ERRORS, SEARCH, RESULTS, CONSTRUCTOR, IN_RUN }; private static DebugLevel debugLevel; // FIXME: Add switch cases for all the levels public static void setDebugValue (int levelIn) { switch (levelIn) { case 0: debugLevel = DebugLevel.ERRORS; break; case 1: debugLevel = DebugLevel.SEARCH; break; case 2: debugLevel = DebugLevel.RESULTS; break; case 3: debugLevel = DebugLevel.CONSTRUCTOR; break; case 4: debugLevel = DebugLevel.IN_RUN; break; } } public static void setDebugValue (DebugLevel levelIn) { debugLevel = levelIn; } public static void writeMessage (String message , DebugLevel levelIn ) { if (levelIn == debugLevel) System.out.println(message); } public String toString() { return "The debug level has been set to the following " + debugLevel; } }<file_sep># csx42_summer_19_assign_5 Code Template for CSx42 Summer 2019, Assignment-5 <file_sep>package troubleShootSearch.search; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import troubleShootSearch.util.FileProcessor; import troubleShootSearch.visitable.VisitableI; import troubleShootSearch.util.Results; import troubleShootSearch.util.MyLogger; public class SemanticMatch implements SearchI { private Results results; private FileProcessor fp; private Map<String, String> hm; public SemanticMatch(FileProcessor fp, Results results) { this.fp = fp; this.results = results; this.hm = new HashMap<String, String>(); } public void init() { try { String sentence = ""; while (sentence != null) { MyLogger.writeMessage("Initializing semantic meanings...", MyLogger.DebugLevel.IN_RUN); sentence = this.fp.readLine(); if (sentence != null) { String[] arr = sentence.split(":"); hm.put(arr[0], arr[1]); hm.put(arr[1], arr[0]); } } } catch (Exception e) { System.err.println("[Exception Caught]: " + e.getMessage()); e.printStackTrace(); System.exit(1); } } public boolean search(List<String> lt, int id, String keyword) { try { for (String s: lt) { String[] str = keyword.split(" "); for (String temp: str) { // int index = s.indexOf(temp); int index = hm.containsKey(temp) ? s.indexOf(hm.get(temp)) : -1; if (index >= 0) { String msg = "[Semantic Match] Product(" + id + ") with keyword (" + keyword + "): " + s; results.addResult(msg); return true; } } } } catch (Exception e) { System.err.println("[Exception Caught]: " + e.getMessage()); e.printStackTrace(); System.exit(1); } return false; } }<file_sep># visitor_pattern This was my final assignment for Fall-2019 graduate level course Introduction to Design Patterns. <file_sep># CSX42: Assignment 5 ## Name: <NAME> ----------------------------------------------------------------------- ----------------------------------------------------------------------- Following are the commands and the instructions to run ANT on your project. #### Note: build.xml is present in troubleShootSearch/src folder. ----------------------------------------------------------------------- ## Instruction to clean: ####Command: ant -buildfile troubleShootSearch/src/build.xml clean Description: It cleans up all the .class files that were generated when you compiled your code. ----------------------------------------------------------------------- ## Instruction to compile: ####Command: ant -buildfile troubleShootSearch/src/build.xml all Description: Compiles your code and generates .class files inside the BUILD folder. ----------------------------------------------------------------------- ## Instruction to run: ####Command: ant -buildfile troubleShootSearch/src/build.xml run -Dargs="product_info1.txt product_info2.txt product_info3.txt product_info4.txt userInputs.txt output.txt semantic.txt <debug_value>" ----------------------------------------------------------------------- ## Description: I have used visitor pattern for this assignment. ----------------------------------------------------------------------- ### Academic Honesty statement: ----------------------------------------------------------------------- "I have done this assignment completely on my own. I have not copied it, nor have I given my solution to anyone else. I understand that if I am involved in plagiarism or cheating I will have to sign an official form that I have cheated and that this form will be stored in my official university record. I also understand that I will receive a grade of 0 for the involved assignment for my first offense and that I will receive a grade of F for the course for any additional offense."" Date: -- 08/05/2019
383d0c61b39a4fa738e3bf8e89a72d4775c5c604
[ "Markdown", "Java" ]
5
Java
Brisingr1992/visitor_pattern
3a2296a550ecaaa32a0bf8873630122ed06f13fd
b890c4c7a050b56dc679c5587ba895ae35c67923
refs/heads/master
<file_sep>#!/bin/bash export JAVA_HOME=c:/Program\ Files/Java/jdk1.6.0_11 alias ant="/c/asdk/apache-ant-1.7.1/bin/ant" alias emulator="/c/asdk/android-sdk-windows-1.0_r2/tools/emulator.exe" alias adb="/c/asdk/android-sdk-windows-1.0_r2/tools/adb" # To setup build.xml from AndroidManifest.xml: # ../tools/activitycreator.bat com.tulrich.flingers.Flingers # To start emulator: # emulator & # To build & install on emulator: # ant && adb -e install -r bin/Flingers-debug.apk # To build & install on device: # ant && adb -d install -r bin/Flingers-debug.apk # To see logs: # adb -e logcat # To open a shell on the android: # adb -e shell
b8b4e64a7bc36d95a5934f11252a4d191882aed4
[ "Shell" ]
1
Shell
widerules/flingers
952f570b7557d52452ec2a897f47ada4ec31ad5a
4bfb2fb803f5e96165397ceae5bea2b64809d76f
refs/heads/master
<file_sep>from flask import Flask, redirect, session, render_template, request,session, flash, url_for from mysqlconnection import connectToMySQL app = Flask(__name__) app.secret_key = "keep it secret, keep it safe" from flask_bcrypt import Bcrypt bcrypt = Bcrypt(app) import re @app.route("/") def landing_page(): return render_template("index.html") #registration section & validation EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') @app.route("/register", methods=['POST']) # register route def add_users(): is_valid = True if len(request.form['fname']) < 1: is_valid = False flash("Please enter a frist name") return redirect("/") if len(request.form['lname']) < 1: is_valid = False flash("Please enter a last name") return redirect("/") if not EMAIL_REGEX.match(request.form['email']): flash('invalid email address') return redirect('/') if len(request.form['password']) < 1: is_valid = False flash("Please enter a valid password") return redirect("/") if request.form['conf_password'] != request.form['password']: is_valid = False flash("password did not match") return redirect("/") if is_valid: pw_hash = bcrypt.generate_password_hash(request.form['password']) print(pw_hash) mysql = connectToMySQL('team_db') query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at) VALUES (%(fn)s, %(ln)s, %(em)s, %(pw)s, NOW(), NOW());" data = { "fn": request.form["fname"], "ln": request.form["lname"], "em": request.form["email"], "pw": pw_hash } #store in DB redirect to users page new_user_id = mysql.query_db(query,data) flash("User successfully added!") session['greetings'] = request.form["fname"] session['user_id'] = new_user_id return redirect("/profile" ) # Login route @app.route("/login", methods=['POST']) def login(): mysql = connectToMySQL("team_db") query = "SELECT * FROM users WHERE email = %(em)s;" data = { "em" : request.form["email"] } login_information = mysql.query_db(query, data) print(login_information) if login_information: if bcrypt.check_password_hash(login_information[0]['password'], request.form['password']): session['user_id'] = login_information[0]['id'] session['greetings'] = login_information[0]['first_name'] return redirect('/user_page') flash('You could not be logged in check your username and password') return redirect('/') #ajax validation @app.route("/username", methods=['POST']) def username_validation(): print(request.form) found = False mysql = connectToMySQL('dojo_tweets') # connect to the database query = "SELECT email FROM users WHERE email = %(data)s;" data = { "data": request.form["email"] } result = mysql.query_db(query, data) if result: found = True return render_template('partials/user_validation.html', found=found) #log off @app.route('/logout') def logout(): session.clear() return redirect("/") #set up security when register a new user @app.route("/profile") def profile_page(): return render_template("landing_page.html") #forgot password route @app.route("/forgot_pass") def update_pass(): return render_template("forgot_pw.html") # reset password route # resets password if security answer is in the db @app.route("/reset_pw", methods=['POST']) def reset(): reset_pw = False mysql = connectToMySQL('team_db') query = "SELECT * FROM users WHERE email = %(em)s" data = {"em": request.form['email']} user_info = mysql.query_db(query,data) if user_info: reset_pw = True print(reset_pw) if reset_pw: #if there is a user returned from prior query get the security question and store it mysql = connectToMySQL('team_db') query = "SELECT security_question FROM users WHERE email = %(em)s" data = {"em": request.form['email']} question = mysql.query_db(query,data) print(question[0]['security_question']) if question[0]['security_question'] != request.form['question-one'] or request.form['question-two'] or request.form['question-three']: reset_pw = False flash('Security question did not match') return redirect('/forgot_pass') elif question[0]['security_question'] == request.form['question-one'] or request.form['question-two'] or request.form['question-three']: reset_pw = True if reset_pw: mysql = connectToMySQL('team_db') pw_hash = bcrypt.generate_password_hash(request.form['password']) query = "UPDATE users SET password = %(<PASSWORD>)s WHERE email = %(em)s " data = { "new_pw": pw_hash, "em": request.form['email'] } mysql.query_db(query,data) flash('Password Successfully reset!') return redirect('/') return redirect('/forgot_pass') # user sets sec question and is updated in the db @app.route("/security_questions", methods=['POST']) def security(): valid_form = False if len(request.form['question-one']) > 1: valid_form = True form_input = request.form['question-one'] if len(request.form['question-two']) > 1: valid_form = True form_input = request.form['question-two'] if len(request.form['question-three']) > 1: valid_form = True form_input = request.form['question-three'] if valid_form: print(form_input) print(session['user_id']) mysql = connectToMySQL('team_db') query = "UPDATE users SET security_question = %(question)s WHERE id = %(u_id)s" data = { "question": form_input, "u_id": session['user_id'] } mysql.query_db(query,data) # when done setting up profile go to users_page return redirect('/user_page') # renders the landing page for user @app.route("/user_page") def user_page(): mysql = connectToMySQL('team_db') query = "SELECT * FROM posts JOIN users ON users.id = posts.user_id" posts = mysql.query_db(query) # for post in posts: mysql = connectToMySQL('team_db') query = "SELECT * FROM comments JOIN users ON user_id = users.id" comments = mysql.query_db(query) return render_template('user_page.html', posts = posts, all_comments = comments) @app.route("/make_post", methods=['POST']) def post_message(): mysql=connectToMySQL('team_db') query = "INSERT INTO posts (post, created_at, updated_at, user_id) VALUES ( %(post)s, NOW(), NOW(), %(u_id)s) " data = { "post": request.form['post'], "u_id": session['user_id'] } mysql.query_db(query, data) return redirect('/user_page') @app.route("/comment", methods=['POST']) def make_a_comment(): mysql = connectToMySQL('team_db') query = "INSERT INTO comments ( comment, user_id, post_id ) VALUES ( %(comment)s, %(uid)s, %(pid)s )" data = { "comment": request.form['comment_text'], "uid": session['user_id'], "pid": request.form['post_id'] } mysql.query_db(query, data) return redirect('/user_page') @app.route("/delete", methods=['POST']) def delete_post(): mysql = connectToMySQL('team_db') query = "DELETE FROM comments WHERE post_id = %(pid)s" data = { "pid": request.form['post_id'] } mysql.query_db(query, data) mysql = connectToMySQL('team_db') query = "DELETE FROM posts WHERE id = %(pid)s " data = { "pid": request.form['post_id'] } mysql.query_db(query, data) return redirect('/user_page') @app.route("/update/<id>") def update_post(id): mysql = connectToMySQL('team_db') query = "SELECT * FROM posts WHERE id = %(pid)s " data = { "pid": id } post = mysql.query_db(query, data) return render_template('update_post.html', posts = post) @app.route("/update_post", methods=['POST']) def update(): mysql = connectToMySQL('team_db') query = "UPDATE posts SET post = %(update)s WHERE id = %(pid)s " data = { "update": request.form['updated_text'], "pid": request.form['post_id'] } mysql.query_db(query, data) return redirect('/user_page') if __name__=="__main__": app.run(debug=True) <file_sep># solo_project The Goal here was to be able to have team communications happen all in one place to better organize strategically within one team instead of everywhere on various different platforms. In reality it was just to show off abilities of CRUD and Restful Practices from Coding Dojo BootCamp. This project as i've recognized has several security risks and bugs. it's the Minimum Viable Product of something that will continue to grow or possibly be scrapped and reworked knowing the amount of errors that are visible. I'll continue ot display it here to show how far i've from beginning to the future.
99b7760cdc523c03abd5f924b374802c0285c7d7
[ "Markdown", "Python" ]
2
Python
Richand83/solo_project
9ac425052b39e363f64dc9275b7fac879c4be0d7
ab53e5e97a75f311fefe5fb93010c34dfaf1f883
refs/heads/master
<repo_name>inasyrov/realty-plugin<file_sep>/src/SearchQueries/Filters/Taxonomies/Type.php <?php namespace Realty\Plugin\SearchQueries\Filters\Taxonomies; use Realty\Plugin\SearchQueries\Filters\FilterContract; /** * Class Type * @package Realty\Plugin\Queries\Filters\Taxonomies */ class Type implements FilterContract { const DEFAULT_TERM = 'sell'; /** * @inheritdoc */ public function apply() { $term = $this->input(); if (false === $term) { return []; } return [ 'taxonomy' => 'offer_type', 'field' => 'slug', 'terms' => $term, 'include_children' => false, ]; } protected function input() { return filter_input(INPUT_GET, 'type', FILTER_SANITIZE_STRING, [ 'options' => ['default' => static::DEFAULT_TERM], ]); } } <file_sep>/src/hooks/offer.php <?php /** * Add rewrite rules. */ add_action('init', function () { /** @var WP_Rewrite $wp_rewrite */ global $wp_rewrite; $wp_rewrite->add_rewrite_tag('%offer_id%', '([0-9]+)', 'post_type=offer&p='); $wp_rewrite->add_permastruct('offer', '/offer/%offer_id%'); }); /** * Change post type link. */ is_admin() && add_filter('post_type_link', function ($link, $post = null) { $post = get_post($post); if (is_wp_error($post) || 'offer' !== $post->post_type) { return $link; } /** @var WP_Rewrite $wp_rewrite */ global $wp_rewrite; $link = $wp_rewrite->get_extra_permastruct('offer'); $link = str_replace('%offer_id%', $post->ID, $link); $link = home_url(user_trailingslashit($link)); return $link; }); <file_sep>/src/SearchQueries/Commercial.php <?php namespace Realty\Plugin\SearchQueries; use Realty\Plugin\SearchQueries\Filters\Meta\Price; use Realty\Plugin\SearchQueries\Filters\Taxonomies\Category; use Realty\Plugin\SearchQueries\Filters\Taxonomies\Region; use Realty\Plugin\SearchQueries\Filters\Taxonomies\Type; /** * Class Commercial * @package Realty\Plugin\SearchQueries */ class Commercial extends SearchQuery { /** * @inheritdoc */ protected function getPageId() { return (int)carbon_get_theme_option('commercial_archive_page'); } /** * @inheritdoc */ protected function getMetaFilters() { return [ Price::class, ]; } /** * @inheritdoc */ protected function getTaxonomyFilters() { return [ Region::class, Type::class, Category::class, ]; } } <file_sep>/src/Providers/CustomFieldsServiceProvider.php <?php namespace Realty\Plugin\Providers; use Pimple\Container; /** * Class CustomFieldsServiceProvider * @package Realty\Plugin\Providers */ class CustomFieldsServiceProvider implements ServiceProviderContract { /** * @inheritdoc */ public function register(Container $pimple) { } /** * @inheritdoc */ public function boot() { if (!is_admin()) { return; } add_action('carbon_register_fields', function () { require \Realty\Plugin\src_path('customFields/home.php'); require \Realty\Plugin\src_path('customFields/offer.php'); require \Realty\Plugin\src_path('customFields/theme.php'); }); } } <file_sep>/src/Providers/SearchQueriesServiceProvider.php <?php namespace Realty\Plugin\Providers; use Pimple\Container; use Realty\Plugin\SearchQueries\Commercial; use Realty\Plugin\SearchQueries\Offer; /** * Class SearchQueriesServiceProvider * @package Realty\Plugin\Providers */ class SearchQueriesServiceProvider implements ServiceProviderContract { /** * @inheritdoc */ public function register(Container $pimple) { } /** * @inheritdoc */ public function boot() { if (is_admin()) { return; } (new Offer)->init(); (new Commercial)->init(); } } <file_sep>/src/Providers/HooksServiceProvider.php <?php namespace Realty\Plugin\Providers; use Pimple\Container; /** * Class HooksServiceProvider * @package Realty\Plugin\Providers */ class HooksServiceProvider implements ServiceProviderContract { /** * @inheritdoc */ public function register(Container $pimple) { } /** * @inheritdoc */ public function boot() { require \Realty\Plugin\src_path('hooks/offer.php'); } } <file_sep>/src/SearchQueries/Filters/FilterContract.php <?php namespace Realty\Plugin\SearchQueries\Filters; /** * Interface FilterContract * @package Realty\Plugin\SearchQueries\Filters */ interface FilterContract { /** * Apply filter. * * @return array */ public function apply(); } <file_sep>/realty.php <?php /* Plugin Name: Realty Description: Realty is a WordPress plugin. Version: 0.0.1 Author: <NAME> Author URI: mailto:<EMAIL> Text Domain: realty/plugin License: MIT License License URI: http://opensource.org/licenses/MIT */ // Require Composer auto loader if installed on it's own if (file_exists($composer = __DIR__ . '/vendor/autoload.php')) { require_once $composer; } // Load plugin's helper functions require __DIR__ . '/src/helpers.php'; // Boot the plugin (new Realty\Plugin\Plugin(__DIR__))->boot(); <file_sep>/src/helpers.php <?php namespace Realty\Plugin; /** * Get the available plugin binding. * * @param string $binding * * @return PluginContract|mixed * * @SuppressWarnings(PHPMD.StaticAccess) */ function plugin($binding = null) { $instance = Plugin::getInstance(); if (null === $binding) { return $instance; } return $instance[$binding]; } /** * Get the base path. * * @param string $path * * @return string */ function base_path($path = '') { return plugin()->getBasePath() . ($path ? DIRECTORY_SEPARATOR . $path : $path); } /** * Get the base path. * * @param string $path * * @return string */ function src_path($path = '') { return plugin()->getSrcPath() . ($path ? DIRECTORY_SEPARATOR . $path : $path); } <file_sep>/src/customFields/home.php <?php use Carbon_Fields\Container\Container; /** * Promo panel. */ Container::make('post_meta', __('Promo', 'realty/plugin')) ->show_on_page((int)get_option('page_on_front')) ->add_fields(require \Realty\Plugin\src_path('customFields/containers/promo.php')); /** * Add Links panel. */ Container::make('post_meta', __('Add Links', 'realty/plugin')) ->show_on_page((int)get_option('page_on_front')) ->add_fields(require \Realty\Plugin\src_path('customFields/containers/addLinks.php')); /** * Search Links panel. */ Container::make('post_meta', __('Search Links', 'realty/plugin')) ->show_on_page((int)get_option('page_on_front')) ->add_fields(require \Realty\Plugin\src_path('customFields/containers/searchLinks.php')); <file_sep>/src/Providers/CustomPostTypesServiceProvider.php <?php namespace Realty\Plugin\Providers; use Pimple\Container; /** * Class CustomPostTypesServiceProvider * @package Realty\Plugin\Providers */ class CustomPostTypesServiceProvider implements ServiceProviderContract { /** * @inheritdoc */ public function register(Container $pimple) { } /** * @inheritdoc */ public function boot() { require \Realty\Plugin\src_path('customPostTypes/offer.php'); } } <file_sep>/src/SearchQueries/Filters/Meta/Price.php <?php namespace Realty\Plugin\SearchQueries\Filters\Meta; use Realty\Plugin\SearchQueries\Filters\FilterContract; /** * Class Price * @package Realty\Plugin\Queries\Filters\Meta */ class Price implements FilterContract { const DEFAULT_MIN = 0; const DEFAULT_MAX = 9999999999; /** * @inheritdoc */ public function apply() { list($min, $max) = $this->input(); if ($min === static::DEFAULT_MIN && $max === static::DEFAULT_MAX) { return []; } return [ 'key' => '_price', 'value' => [$min, $max], 'compare' => 'BETWEEN', 'type' => 'DECIMAL', ]; } protected function input() { $min = filter_input(INPUT_GET, 'min_price', FILTER_SANITIZE_NUMBER_FLOAT, [ 'flags' => FILTER_FLAG_ALLOW_FRACTION, 'options' => ['min_range' => 0, 'default' => static::DEFAULT_MIN], ]); $max = filter_input(INPUT_GET, 'max_price', FILTER_SANITIZE_NUMBER_FLOAT, [ 'flags' => FILTER_FLAG_ALLOW_FRACTION, 'options' => ['min_range' => 1, 'default' => static::DEFAULT_MAX], ]); return [$min, $max]; } } <file_sep>/src/Providers/ServiceProviderContract.php <?php namespace Realty\Plugin\Providers; use Pimple\ServiceProviderInterface; /** * Interface ServiceProviderContract * @package Realty\Plugin\Providers */ interface ServiceProviderContract extends ServiceProviderInterface { /** * Boot service provider. */ public function boot(); } <file_sep>/src/customFields/containers/offerArchiveSettings.php <?php use Carbon_Fields\Field\Field; return [ Field::make('select', 'offer_archive_page', __('Archive Page', 'realty/plugin')) ->set_options(array_map(function ($page) { return [$page->ID => $page->post_title]; }, get_pages(['sort_column' => 'menu_order']))) ->set_required(true), Field::make('text', 'offer_archive_posts_per_page', __('Posts Per Page', 'realty/plugin')) ->set_required(true), ]; <file_sep>/src/SearchQueries/SearchQuery.php <?php namespace Realty\Plugin\SearchQueries; use Realty\Plugin\SearchQueries\Filters\Sorting; use WP_Query; /** * Class SearchQuery * @package Realty\Plugin\SearchQueries */ abstract class SearchQuery { /** * Init search query. */ public function init() { add_action('pre_get_posts', [$this, 'modifyMainQuery']); } /** * Modify main query. * * @param WP_Query $query */ public function modifyMainQuery(WP_Query $query) { if (!$this->isAllowedModifyQuery($query)) { return; } $this->modifyPageQuery($query); // Apply filters $query->set('meta_query', $this->compileFilters($this->getMetaFilters())); $query->set('tax_query', $this->compileFilters($this->getTaxonomyFilters())); // Sort results $sort = (new Sorting)->arguments(); $query->set('orderby', $sort['orderby']); $query->set('order', $sort['order']); if (isset($sort['meta_key'])) { $query->set('meta_key', $sort['meta_key']); } } /** * Get page ID. * * @return int */ abstract protected function getPageId(); /** * Determine if it's allowed to modify main query. * * @param WP_Query $query * * @return bool * * @SuppressWarnings(PHPMD.CamelCaseVariableName) */ protected function isAllowedModifyQuery(WP_Query $query) { global $wp_rewrite; return $query->is_main_query() && isset($wp_rewrite) && $wp_rewrite->use_verbose_page_rules && isset($query->queried_object_id) && $query->queried_object_id === $this->getPageId(); } /** * Modify page query. * * @param WP_Query $query */ protected function modifyPageQuery(WP_Query $query) { $query->set('post_type', 'offer'); $query->set('page', ''); $query->set('pagename', ''); // Fix conditional functions $query->is_archive = true; $query->is_post_type_archive = true; $query->is_singular = false; $query->is_page = false; } /** * Get meta filters. * * @return array */ abstract protected function getMetaFilters(); /** * Get taxonomy filters. * * @return array */ abstract protected function getTaxonomyFilters(); /** * Compile filters. * * @param array $filters * * @return array */ protected function compileFilters(array $filters) { return array_map(function ($filter) { return (new $filter)->apply(); }, $filters); } } <file_sep>/src/customFields/offer.php <?php use Carbon_Fields\Container\Container; use Carbon_Fields\Field\Field; Container::make('post_meta', __('Offer', 'realty/plugin')) ->show_on_post_type('offer') ->add_fields([ Field::make('map', 'address') ]); <file_sep>/src/customFields/containers/promo.php <?php use Carbon_Fields\Field\Field; return [ Field::make('attachment', 'promo_image', __('Image', 'realty/plugin')) ->set_value_type('url') ->set_required(true), Field::make('text', 'promo_title', __('Title', 'realty/plugin')) ->set_required(true), Field::make('textarea', 'promo_text', __('Text', 'realty/plugin')) ->set_required(true) ->set_rows(4), Field::make('text', 'promo_button_url', __('Button URL', 'realty/plugin')) ->set_required(true) ->set_width(50), Field::make('text', 'promo_button_text', __('Button Text', 'realty/plugin')) ->set_required(true) ->set_width(50), ]; <file_sep>/src/customFields/containers/addLinks.php <?php use Carbon_Fields\Field\Field; return [ /** * Left column. */ Field::make('text', 'add_links_left_link_url', __('Left Link URL', 'realty/plugin')) ->set_required(true) ->set_width(33), Field::make('text', 'add_links_left_link_text', __('Left Link Text', 'realty/plugin')) ->set_required(true) ->set_width(33), Field::make('text', 'add_links_left_link_description', __('Left Link Description', 'realty/plugin')) ->set_required(true) ->set_width(33), /** * Right column. */ Field::make('text', 'add_links_right_link_url', __('Right Link URL', 'realty/plugin')) ->set_required(true) ->set_width(33), Field::make('text', 'add_links_right_link_text', __('Right Link Text', 'realty/plugin')) ->set_required(true) ->set_width(33), Field::make('text', 'add_links_right_link_description', __('Right Link Description', 'realty/plugin')) ->set_required(true) ->set_width(33), /** * Text. */ Field::make('rich_text', 'add_links_text', __('Text', 'realty/plugin')) ->set_required(true), ]; <file_sep>/src/Plugin.php <?php namespace Realty\Plugin; use Pimple\Container; use Pimple\ServiceProviderInterface; use Realty\Plugin\Providers\CustomFieldsServiceProvider; use Realty\Plugin\Providers\CustomPostTypesServiceProvider; use Realty\Plugin\Providers\HooksServiceProvider; use Realty\Plugin\Providers\SearchQueriesServiceProvider; /** * Class Plugin * @package Realty\Plugin */ class Plugin extends Container implements PluginContract { /** * The plugin instance. * * @var static */ protected static $instance; /** * The base path for the plugin installation. * * @var string */ protected $basePath; /** * Collection of service providers. * * @var array */ protected $serviceProviders = []; /** * Indicates if the plugin has booted. * * @var bool */ protected $booted = false; /** * Get the plugin instance. * * @return static */ public static function getInstance() { if (is_null(static::$instance)) { static::$instance = new static; } return static::$instance; } /** * Set the plugin instance. * * @param PluginContract $plugin * * @return static */ public static function setInstance(PluginContract $plugin) { return static::$instance = $plugin; } /** * @inheritdoc */ public function __construct($basePath) { parent::__construct(); $this->setBasePath($basePath); $this->registerBaseBindings(); $this->registerBaseServiceProviders(); } /** * @inheritdoc */ public function getBasePath() { return $this->basePath; } /** * @inheritdoc */ public function setBasePath($basePath) { $this->basePath = rtrim($basePath, '\/'); $this->bindPathsInContainer(); return $this; } /** * @inheritdoc */ public function getSrcPath() { return $this->basePath . DIRECTORY_SEPARATOR . 'src'; } /** * @inheritdoc */ public function register(ServiceProviderInterface $provider, array $options = []) { parent::register($provider, $options); // mark as registered $this->serviceProviders[] = $provider; if ($this->booted) { $this->bootProvider($provider); } return $this; } /** * Determine if the plugin has been booted. * * @return bool */ public function isBooted() { return $this->booted; } /** * Boot the plugin's service providers. */ public function boot() { if ($this->booted) { return; } array_walk($this->serviceProviders, function ($provider) { $this->bootProvider($provider); }); $this->booted = true; } /** * Bind paths in the container. */ protected function bindPathsInContainer() { $this['path.base'] = $this->getBasePath(); $this['path.src'] = $this->getSrcPath(); } /** * Register the base bindings. */ protected function registerBaseBindings() { static::setInstance($this); $this['plugin'] = $this; } /** * Register the base service providers. */ protected function registerBaseServiceProviders() { $this->register(new CustomPostTypesServiceProvider); $this->register(new CustomFieldsServiceProvider); $this->register(new HooksServiceProvider); $this->register(new SearchQueriesServiceProvider); } /** * Boot the given service provider. * * @param ServiceProviderInterface $provider * * @return mixed */ protected function bootProvider(ServiceProviderInterface $provider) { if (method_exists($provider, 'boot')) { return $provider->boot(); } } } <file_sep>/src/customFields/theme.php <?php use Carbon_Fields\Container\Container; /** * Offer options. */ Container::make('theme_options', __('Settings', 'realty/plugin')) ->set_page_parent('edit.php?post_type=offer') ->add_tab( __('Offer Archive', 'realty/plugin'), require \Realty\Plugin\src_path('customFields/containers/offerArchiveSettings.php') ) ->add_tab( __('Commercial Archive', 'realty/plugin'), require \Realty\Plugin\src_path('customFields/containers/commercialArchiveSettings.php') ); <file_sep>/src/PluginContract.php <?php namespace Realty\Plugin; use Realty\Plugin\Support\ServiceProviderContract; /** * Interface PluginContract * @package Realty\Plugin */ interface PluginContract { /** * Create a new plugin instance. * * @param string $basePath */ public function __construct($basePath); /** * Get the base path. * * @return string */ public function getBasePath(); /** * Set the base path for the plugin. * * @param string $basePath * * @return PluginContract */ public function setBasePath($basePath); /** * Get the path to the plugin configuration files. * * @return string */ public function getSrcPath(); /** * Boot the plugin's service providers. */ public function boot(); } <file_sep>/src/customFields/containers/searchLinks.php <?php use Carbon_Fields\Field\Field; return [ Field::make('complex', 'search_links', __('Search Links', 'realty/plugin')) ->setup_labels([ 'singular_name' => __('Search Link', 'realty/plugin'), 'plural_name' => __('Search Links', 'realty/plugin'), ]) ->add_fields([ // @codingStandardsIgnoreStart Field::make('attachment', 'image', __('Image', 'realty/plugin')) ->set_required(true), Field::make('text', 'title', __('Title', 'realty/plugin')) ->set_required(true), Field::make('select', 'offer_type', __('Offer Type', 'realty/plugin')) ->set_required(true) ->set_options(array_map(function (WP_Term $term) { return [$term->slug => $term->name]; }, \Realty\Plugin\Helpers\Taxonomy::types()->terms)) ->set_width(50), Field::make('select', 'offer_category', __('Offer Category', 'realty/plugin')) ->set_required(true) ->set_options(array_map(function (WP_Term $term) { return [$term->slug => $term->name]; }, \Realty\Plugin\Helpers\Taxonomy::categories()->terms)) ->set_width(50) // @codingStandardsIgnoreEnd ]), ]; <file_sep>/src/customPostTypes/offer.php <?php use PostTypes\PostType; // Register Offer post type $offer = new PostType([ 'name' => 'offer', 'singular' => 'Offer', 'plural' => 'Offers', 'slug' => 'offer' ], ['supports' => ['title']]); // Set Offer post type menu icon $offer->icon('dashicons-admin-multisite'); // Set text domain $offer->translation('realty/plugin'); // Register Offer Region taxonomy $offer->taxonomy([ 'name' => 'offer_region', 'singular' => 'Region', 'plural' => 'Regions', 'slug' => 'regions' ]); // Register Offer Type taxonomy $offer->taxonomy([ 'name' => 'offer_type', 'singular' => 'Type', 'plural' => 'Types', 'slug' => 'types' ], ['hierarchical' => false]); // Register Offer Category taxonomy $offer->taxonomy([ 'name' => 'offer_category', 'singular' => 'Category', 'plural' => 'Categories', 'slug' => 'categories' ], ['hierarchical' => false]); // Register Offer Commercial Type taxonomy $offer->taxonomy([ 'name' => 'offer_commercial_type', 'singular' => 'Commercial Type', 'plural' => 'Commercial Types', 'slug' => 'commercial-types' ], ['hierarchical' => false]); // Register Offer Commercial Building Type taxonomy $offer->taxonomy([ 'name' => 'offer_commercial_building_type', 'singular' => 'Commercial Building Type', 'plural' => 'Commercial Building Types', 'slug' => 'commercial-building-types' ], ['hierarchical' => false]); // Set the taxonomy filters $offer->filters(['offer_type', 'offer_category']); // Set the columns $offer->columns()->set([ 'cb' => '<input type="checkbox"/>', 'title' => __('Title', 'realty/plugin'), 'date' => __('Date', 'realty/plugin') ]); // Sortable columns // Populating the columns <file_sep>/src/SearchQueries/Filters/Taxonomies/Region.php <?php namespace Realty\Plugin\SearchQueries\Filters\Taxonomies; use Realty\Plugin\SearchQueries\Filters\FilterContract; /** * Class Region * @package Realty\Plugin\Queries\Filters\Taxonomies */ class Region implements FilterContract { /** * @inheritdoc */ public function apply() { $term = $this->input(); if (false === $term) { return []; } return [ 'taxonomy' => 'offer_region', 'terms' => $term, 'include_children' => false, ]; } protected function input() { return filter_input(INPUT_GET, 'region', FILTER_SANITIZE_NUMBER_INT, [ 'options' => ['min_range' => 1], ]); } } <file_sep>/src/SearchQueries/Filters/Taxonomies/Category.php <?php namespace Realty\Plugin\SearchQueries\Filters\Taxonomies; use Realty\Plugin\SearchQueries\Filters\FilterContract; /** * Class Category * @package Realty\Plugin\Queries\Filters\Taxonomies */ class Category implements FilterContract { const DEFAULT_TERM = 'apartment'; /** * @inheritdoc */ public function apply() { $term = $this->input(); if (false === $term) { return []; } return [ 'taxonomy' => 'offer_category', 'field' => 'slug', 'terms' => $term, 'include_children' => false, ]; } protected function input() { return filter_input(INPUT_GET, 'category', FILTER_SANITIZE_STRING, [ 'options' => ['default' => static::DEFAULT_TERM], ]); } } <file_sep>/src/SearchQueries/Filters/Sorting.php <?php namespace Realty\Plugin\SearchQueries\Filters; /** * Class Sorting * @package Realty\Plugin\SearchQueries\Filters */ class Sorting { /** * Arguments. * * @return array */ public function arguments() { list($orderBy, $order) = $this->input(); // Default case $sort['orderby'] = 'menu_order title'; $sort['order'] = $order; switch ($orderBy) { case 'date': $sort['orderby'] = 'date ID'; break; case 'price': $sort['orderby'] = 'meta_value_num ID'; $sort['meta_key'] = '_price'; break; } return $sort; } /** * Resolve sort input. * * @return array */ protected function input() { $input = filter_input(INPUT_GET, 'sort'); $input = explode('-', $input); $orderBy = !empty($input[0]) ? strtolower($input[0]) : ''; $order = !empty($input[1]) ? $input[1] : ''; $order = 'DESC' === strtoupper($order) ? 'DESC' : 'ASC'; return [$orderBy, $order]; } } <file_sep>/src/Helpers/Taxonomy.php <?php namespace Realty\Plugin\Helpers; use WP_Term_Query; class Taxonomy { /** * Get offer type terms. * * @param bool $refresh * * @return WP_Term_Query * * @SuppressWarnings(PHPMD.BooleanArgumentFlag) */ public static function types($refresh = false) { return static::terms('offer_type', $refresh); } /** * Get offer category terms. * * @param bool $refresh * * @return WP_Term_Query * * @SuppressWarnings(PHPMD.BooleanArgumentFlag) */ public static function categories($refresh = false) { return static::terms('offer_category', $refresh); } /** * Get the given taxonomy terms. * * @param string $taxonomy * @param bool $refresh * * @return WP_Term_Query * * @SuppressWarnings(PHPMD.BooleanArgumentFlag) */ protected static function terms($taxonomy, $refresh = false) { $query = wp_cache_get($taxonomy, 'taxonomy'); if ($refresh || false === $query) { $query = new WP_Term_Query([ 'taxonomy' => $taxonomy, 'hide_empty' => false, ]); if (!is_wp_error($query) && $query->terms) { wp_cache_set($taxonomy, $query, 'taxonomy', 5 * MINUTE_IN_SECONDS); } } return $query; } }
4b529dc03ba3cbc8b1d056a0d3994f6b1945f19e
[ "PHP" ]
27
PHP
inasyrov/realty-plugin
6cbb2e7cbea01c9ccb8111e880e182a48170e13c
a0fb618111e8678c92f87812c32b00c28c4501e1
refs/heads/master
<file_sep>newRealizationsEvent.topic.name=new_realizations newOrderEvent.out.amqp.exchange=new_order_events newOrderEvent.out.amqp.routingKey=new_order_events_rk<file_sep>package com.ms.orderservice.configuration; import com.ms.orderservice.configuration.integration.OrderIntegrationConfiguration; import com.ms.orderservice.service.impl.TestSender; import org.apache.log4j.Logger; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import org.springframework.integration.config.EnableIntegration; @SpringBootApplication @EnableIntegration @ComponentScan("com.ms.orderservice") @Import(OrderIntegrationConfiguration.class) public class OrderApplicationConfiguration { private static final Logger logger = Logger.getLogger(OrderApplicationConfiguration.class); public static void main(String[] args) { ConfigurableApplicationContext run = SpringApplication.run(OrderApplicationConfiguration.class, args); TestSender sender=run.getBean("testSender",TestSender.class); sender.send(); } } <file_sep>server.port = 8071<file_sep>package com.ms.warehouseservice.configuration.integration; public class IntegrationFlowKeys { public static final String NEW_ORDER_OUT_CHANNEL="NewOrderOutChannel"; public static final String PRIORITY_ORDER_PROCESSING_QUEUE="priorityOrderProcessingQueue"; public static final String NOT_PRIORITY_ORDER_PROCESSING_QUEUE="notPriorityOrderProcessingQueue"; } <file_sep>orderReadyEvent.in.amqp.queue=ready_orders_events_queue<file_sep>package com.ms.warehouseservice.configuration.integration; import com.ms.warehouseservice.integration.xsd.OrderReady; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.amqp.Amqp; import org.springframework.integration.dsl.channel.MessageChannels; import org.springframework.messaging.MessageChannel; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.StringWriter; import java.util.concurrent.Executors; @Configuration public class OrderReadyOutgoingFlowConfiguration extends AbstractWarehouseFlowConfiguration{ @Value("${orderReady.out.amqp.exchange}") private String readyOrdersEventOutAmqpExchange; @Value("${orderReady.out.amqp.routingKey}") private String readyOrdersEventOutAmqpRoutingKey; @Bean(name= IntegrationFlowKeys.NEW_ORDER_OUT_CHANNEL) public MessageChannel newOrderOutChannel(){ return MessageChannels.executor(Executors.newCachedThreadPool()).get(); } @Bean public IntegrationFlow amqpOutboundFlow() { return IntegrationFlows.from(newOrderOutChannel()) .transform(this::performMarshalingOrderReady) .handle(Amqp.outboundAdapter(amqpTemplate()) .exchangeName(readyOrdersEventOutAmqpExchange) .routingKey(readyOrdersEventOutAmqpRoutingKey)) .get(); } @Bean public JAXBContext jaxbContextOrderReadyEvent() throws JAXBException { return JAXBContext.newInstance(OrderReady.class); } @Bean @Scope(BeanDefinition.SCOPE_PROTOTYPE) public Marshaller orderReadyEventMarshaler() throws JAXBException { return jaxbContextOrderReadyEvent().createMarshaller(); } protected String performMarshalingOrderReady(OrderReady orderReady) { StringWriter writer = new StringWriter(); try { orderReadyEventMarshaler().marshal(orderReady,writer); } catch (JAXBException e) { e.printStackTrace(); } return writer.toString(); } } <file_sep>server.port = 8072<file_sep><?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.ms.spring.integration.sample</groupId> <artifactId>production-company</artifactId> <version>1.0-SNAPSHOT</version> </parent> <groupId>com.ms.spring.integration.sample</groupId> <artifactId>notification-service</artifactId> <version>1.0-SNAPSHOT</version> <name>notification-service</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jaxb2-maven-plugin</artifactId> <version>2.2</version> <executions> <execution> <id>xjc</id> <goals> <goal>xjc</goal> </goals> </execution> </executions> <configuration> <sources> <source>src/main/resources/xsd</source> </sources> <xjbSources> <xjbSource>src/main/resources/global-binding.xjb</xjbSource> </xjbSources> <packageName>com.ms.notifiactionervice.integration.xsd</packageName> </configuration> </plugin> </plugins> </build> </project> <file_sep>package com.ms.notificationservice.service; public interface MailService { void sendMessageOrderIsReady(String recipient); } <file_sep># spring-integration-dsl-samle<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ms.spring.integration.sample</groupId> <artifactId>production-company</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <name>production-company</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.3.7.RELEASE</spring.version> <spring.integration.version>4.3.12.RELEASE</spring.integration.version> <spring.integration.kafka.version>2.1.0.RELEASE</spring.integration.kafka.version> <spring.integration.dsl.version>1.2.1.RELEASE</spring.integration.dsl.version> <servlet-api.version>2.5</servlet-api.version> <java.version>1.8</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.3.RELEASE</version> </parent> <modules> <module>warehouse-service</module> <module>notification-service</module> <module>accounting-service</module> <module>order-service</module> </modules> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servlet-api.version}</version> <scope>provided</scope> </dependency> <!-- Spring Integration--> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-core</artifactId> <version>${spring.integration.version}</version> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-jms</artifactId> <version>${spring.integration.version}</version> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-amqp</artifactId> <version>${spring.integration.version}</version> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-mqtt</artifactId> <version>${spring.integration.version}</version> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-kafka</artifactId> <version>${spring.integration.kafka.version}</version> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-java-dsl</artifactId> <version>${spring.integration.dsl.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project><file_sep>package com.ms.warehouseservice.service; import com.ms.warehouseservice.integration.xsd.NewOrderEvent; import com.ms.warehouseservice.integration.xsd.OrderReady; public interface OrderReadyMapper { public OrderReady toOrderReady(NewOrderEvent newOrderEvent); } <file_sep>package com.ms.orderservice.configuration.integration; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.amqp.Amqp; import org.springframework.integration.dsl.channel.MessageChannels; import org.springframework.messaging.MessageChannel; import java.util.concurrent.Executors; @Configuration public class OrderOutgoingFlowConfiguration extends AbstractOrderFlowConfiguration { @Value("${newOrderEvent.out.amqp.exchange}") private String newOrderEventOutAmqpExchange; @Value("${newOrderEvent.out.amqp.routingKey}") private String newOrderEventOutAmqpRoutingKey; @Bean(name= IntegrationFlowKeys.NEW_ORDER_OUT_CHANNEL) public MessageChannel newOrderOutChannel(){ return MessageChannels.executor(Executors.newCachedThreadPool()).get(); } @Bean public IntegrationFlow amqpOutboundFlow() { return IntegrationFlows.from(newOrderOutChannel()) .transform(this::performMarshaling) .handle(Amqp.outboundAdapter(amqpTemplate()) .exchangeName(newOrderEventOutAmqpExchange) .routingKey(newOrderEventOutAmqpRoutingKey)) .get(); } } <file_sep>newOrderEvent.in.amqp.queue=new_order_events_queue orderReady.out.amqp.exchange=ready_order_events orderReady.out.amqp.routingKey=ready_orders_rk<file_sep>package com.ms.notificationservice.configuration.integration; import com.ms.notifiactionervice.integration.xsd.OrderReady; import com.ms.notificationservice.service.MailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Scope; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.amqp.Amqp; import org.springframework.integration.dsl.channel.MessageChannels; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import java.util.concurrent.Executors; public class OrderReadyIncommingFlowConfiguration extends AbstractNotificationFlowConfiguration { @Value("${orderReadyEvent.in.amqp.queue}") private String queueOrderReady; @Autowired private MailService mailService; @Bean public IntegrationFlow amqpNewOrderEventInboundFlow() { return IntegrationFlows.from(Amqp.inboundAdapter(rabbitMQConnection(), queueOrderReady)) .channel(MessageChannels.executor(Executors.newCachedThreadPool())) .transform(this::performOrderReadyUnmarshaling) .handle(m -> sentNotifiation((OrderReady) m.getPayload())) .get(); } private void sentNotifiation(OrderReady orderReady) { mailService.sendMessageOrderIsReady(orderReady.getEMail()); } @Bean public JAXBContext jaxbContextOrderReadyEvent() throws JAXBException { return JAXBContext.newInstance(OrderReady.class); } @Bean @Scope(BeanDefinition.SCOPE_PROTOTYPE) public Unmarshaller orderReadyEventUnmarshaler() throws JAXBException { return jaxbContextOrderReadyEvent().createUnmarshaller(); } protected OrderReady performOrderReadyUnmarshaling(String xml) { OrderReady orderReady = null; try { orderReady = (OrderReady) orderReadyEventUnmarshaler().unmarshal(new StringReader(xml)); } catch (JAXBException e) { e.printStackTrace(); } return orderReady; } } <file_sep>package com.ms.warehouseservice.service; import com.ms.warehouseservice.ds.OrderItemDs; public interface OrderPreparationService { void prepare(OrderItemDs orderItemDs, boolean priorityRealization); } <file_sep>package com.ms.orderservice.configuration.integration; import com.ms.orderservice.integration.xsd.NewOrderEvent; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.StringWriter; @Configuration public class AbstractOrderFlowConfiguration { @Bean public CachingConnectionFactory rabbitMQConnection(){ CachingConnectionFactory connectionFactory = new CachingConnectionFactory(); connectionFactory.setHost("127.0.0.1"); connectionFactory.setPort(5672); connectionFactory.setUsername("guest"); connectionFactory.setPassword("<PASSWORD>"); return connectionFactory; } @Bean public AmqpTemplate amqpTemplate() { AmqpTemplate amqpTemplate = new RabbitTemplate(rabbitMQConnection()); return amqpTemplate; } @Bean public JAXBContext jaxbContextNewOrderEvent() throws JAXBException { return JAXBContext.newInstance(NewOrderEvent.class); } @Bean @Scope(BeanDefinition.SCOPE_PROTOTYPE) public Marshaller newOrderEventMarshaler() throws JAXBException { return jaxbContextNewOrderEvent().createMarshaller(); } protected String performMarshaling(NewOrderEvent newOrderEvent) { StringWriter writer = new StringWriter(); try { newOrderEventMarshaler().marshal(newOrderEvent,writer); } catch (JAXBException e) { e.printStackTrace(); } return writer.toString(); } } <file_sep>package com.ms.notificationservice.configuration; import com.ms.notificationservice.configuration.integration.NotificationIntegrationConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import org.springframework.integration.config.EnableIntegration; @SpringBootApplication @EnableIntegration @ComponentScan("com.ms.notificationservice") @Import(NotificationIntegrationConfiguration.class) public class NotificationApplicationConfiguration { public static void main(String[] args) { SpringApplication.run(NotificationApplicationConfiguration.class, args); } } <file_sep>server.port = 8073<file_sep>package com.ms.warehouseservice.ds; public class OrderItemDs { protected int id; protected int itemCode; protected String itemName; protected String itemDescription; protected int numberOfItems; protected String price; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getItemCode() { return itemCode; } public void setItemCode(int itemCode) { this.itemCode = itemCode; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public String getItemDescription() { return itemDescription; } public void setItemDescription(String itemDescription) { this.itemDescription = itemDescription; } public int getNumberOfItems() { return numberOfItems; } public void setNumberOfItems(int numberOfItems) { this.numberOfItems = numberOfItems; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } } <file_sep>package com.ms.warehouseservice.service.impl; import com.ms.warehouseservice.ds.OrderItemDs; import com.ms.warehouseservice.service.OrderItemMapper; import com.ms.warehouseservice.integration.xsd.NewOrderEvent; import org.springframework.stereotype.Service; @Service public class OrderItemMapperImpl implements OrderItemMapper { @Override public OrderItemDs toOrderItemDs(NewOrderEvent.Item item) { OrderItemDs ds = new OrderItemDs(); ds.setId(item.getId()); ds.setItemCode(item.getItemCode()); ds.setItemName(item.getItemName()); ds.setItemDescription(item.getItemDescription()); ds.setPrice(item.getPrice()); ds.setNumberOfItems(item.getNumberOfItems()); return ds; } }
a5b726f833e33823e11e699be254ee20b532619a
[ "Markdown", "Java", "Maven POM", "INI" ]
21
INI
MarcinStachowiak/spring-integration-dsl-samle
dd9da5dcbf07487afb726b2306305187ec3c4e9c
30fc36a7cbc0ca91042e836580e1dc4760339c97
refs/heads/master
<repo_name>fbmedina/proyecto_final<file_sep>/test/models/store_test.rb require 'test_helper' class StoreTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test "A store cant be created with no user" do s = Store.new(name:"<NAME>") assert_not s.valid?, "A store with no user should be invalid" end end <file_sep>/test/controllers/pages_controller_test.rb require 'test_helper' class PagesControllerTest < ActionController::TestCase include Devise::TestHelpers # test "should get index" do # get :index # assert_response :success # end test "logged user should get index" do sign_in(users(:logged)) get :index assert_response :success end test "not logged user should not get index" do get :index assert_response :redirect end end <file_sep>/app/controllers/securities_controller.rb class SecuritiesController < ApplicationController def disclaimer end end <file_sep>/test/controllers/thresholds_controller_test.rb require 'test_helper' class ThresholdsControllerTest < ActionController::TestCase test "should get second_view" do get :second_view assert_response :success end test "should get third_view" do get :third_view assert_response :success end end <file_sep>/app/controllers/pages_controller.rb class PagesController < ApplicationController def index @products = Product.where(best_seller: true) @stores = Store.where(recommended: true) end end <file_sep>/app/controllers/tags_controller.rb class TagsController < ApplicationController load_and_authorize_resource :product load_and_authorize_resource :tag, through: :product def index @tags = ActsAsTaggableOn::Tag.all end def show @tag = ActsAsTaggableOn::Tag.find(params[:id]) @products = Product.tagged_with(@tag.name) end end<file_sep>/app/assets/javascripts/dropdown.js $(document).on("page:change", function() { $('.myMenu ul li').click(function() { $(this).children('ul').slideToggle(250); }); });<file_sep>/app/models/product.rb class Product < ActiveRecord::Base include LikeHelper belongs_to :store has_many :comments, as: :commentable, dependent: :destroy has_many :likes, as: :likeable, dependent: :destroy has_many :user_likes, through: :likes, source: :user has_many :product_wishlists, dependent: :destroy has_many :user_wishlists, through: :product_wishlists has_many :wishlists, through: :product_wishlists validates :name,:photo, :price, presence: true acts_as_taggable mount_uploader :photo, PhotoUploader def to_s self.name end def search_next end def store_next self.store.products.where("id > ?", self.id).order(:id).limit(1).first end def store_previous self.store.products.where("id < ?", self.id).order("id DESC").limit(1).first end def has_next? (self.store.products.where("id > ?", self.id).count > 0) ? true : false end def has_previous? (self.store.products.where("id < ?", self.id).count > 0) ? true : false end end <file_sep>/app/controllers/searches_controller.rb class SearchesController < ApplicationController def index @distance = params[:distance] @first_price = params[:first_price].present? ? params[:first_price] : 0 current_user.latitude = params[:latitude] current_user.longitude = params[:longitude] current_user.save @user = current_user @user_wishlists = @user.user_wishlists @products = Product.all if params[:distance].present? station_ids = Station.near([current_user.latitude, current_user.longitude], @distance, :units => :km).collect(&:id) @products = Product.eager_load(:store => [:station_stores]).where("station_stores.station_id" => station_ids) end if params[:key_word].present? @key_word = params[:key_word] @products = @products.where("LOWER(products.name) LIKE ? OR LOWER(products.description) LIKE ?", "%#{@key_word.downcase}%", "%#{@key_word.downcase}%") end if params[:first_price] && params[:second_price].present? @first_price = params[:first_price] @second_price = params[:second_price] @products = @products.where("(products.price) BETWEEN #{@first_price} AND #{@second_price}") end if params[:tags].present? @tags = params[:tags] @products = @products.tagged_with(@tags, any: true) end end def show index render :index end end <file_sep>/app/controllers/thresholds_controller.rb class ThresholdsController < ApplicationController layout "devise" def second_view end def third_view end end <file_sep>/app/assets/javascripts/accordion_station_field.js $(document).on("page:load ready", function() { $('.stores.new').ready(function () { var speed = '400'; $('.accordion').click(function(event) { if (!$(this).hasClass('active')) { $('.show').slideUp(speed, function(){ $(this).removeClass('show'); }); $(this).toggleClass('active').next().slideDown(speed, function() { $(this).toggleClass('show'); }); } else { $(this).toggleClass('active').next().slideUp(speed, function(){ $(this).removeClass('show'); }); } }); }); $('.stores.edit').ready(function () { var speed = '400'; $('.accordion').click(function(event) { if (!$(this).hasClass('active')) { $('.show').slideUp(speed, function(){ $(this).removeClass('show'); }); $(this).toggleClass('active').next().slideDown(speed, function() { $(this).toggleClass('show'); }); } else { $(this).toggleClass('active').next().slideUp(speed, function(){ $(this).removeClass('show'); }); } }); }); });<file_sep>/config/routes.rb Rails.application.routes.draw do get 'securities/disclaimer' get 'pages/index' resources :stores do resources :comments, module: :stores, only: [:create, :destroy] resources :likes, module: :stores, only: [:create] resources :products do resources :comments, module: :products, only: [:create, :destroy] resources :likes, module: :products, only: [:create] resources :tags end end devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks" } resources :users do resources :user_wishlists end resources :searches do collection do match 'search', to: 'searches#index', via: :post, as: :search end end delete '/remove_from_user_wishlist/:user_wishlist_id/:product_id', to: 'user_wishlists#remove_from_user_wishlist', as: 'remove_from_user_wishlist' post '/add_to_user_wishlist/:user_wishlist_id/:product_id', to: 'user_wishlists#add_to_user_wishlist', as: 'add_to_user_wishlist' root to: "pages#index" end <file_sep>/app/controllers/stores/comments_controller.rb class Stores::CommentsController < CommentsController before_action :set_commentable load_and_authorize_resource :store load_and_authorize_resource :comment, through: :store private def set_commentable @commentable = Store.find(params[:store_id]) end end<file_sep>/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) Line.destroy_all Station.destroy_all Product.destroy_all Store.destroy_all Wishlist.destroy_all User.destroy_all stations = [] profile_avatar = [File.open(Rails.root + "app/assets/images/default_profile_avatar1.png"), File.open(Rails.root + "app/assets/images/default_profile_avatar2.png"), File.open(Rails.root + "app/assets/images/default_profile_avatar3.png"), File.open(Rails.root + "app/assets/images/default_profile_avatar4.png"),File.open(Rails.root + "app/assets/images/default_profile_avatar5.png"), File.open(Rails.root + "app/assets/images/default_profile_avatar6.png")] Wishlist.create( name: "Lo Amo", icon: "love_it.svg" ) Wishlist.create( name: "Lo Odio", icon: "hate_it.svg" ) Wishlist.create( name: "Lo Tengo", icon: "have_it.svg" ) 22.times do |u| User.create!( name: Faker::Name.name, email: Faker::Internet.email, password: "<PASSWORD>", role: 1, gender: "female", avatar: profile_avatar.sample ) end Line.create([{name: "1", alias: 'red'}, {name: "2", alias: 'yellow'}, {name: "4", alias: 'blue'}, {name: "4a", alias: 'light-blue'}, {name: "5", alias: 'green'}]) CSV.foreach(File.join(Rails.root, 'db', 'data', 'metros.csv'), headers: true, encoding: 'UTF-8') do |row| stations << Station.create(row.to_hash) end CSV.foreach(File.join(Rails.root, 'db', 'data', 'stationLines.csv'), headers: true, encoding: 'UTF-8') do |row| StationLine.create(row.to_hash) end Store.create([ { name: "<NAME>", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0021_1-Straberry-Bazar.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0021_1-Straberry-Bazar.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 1, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "Solo Para Mi", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0020_2-Solo-Para-Mi.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0020_2-Solo-Para-Mi.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 2, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "Positivo", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0019_3-Positivo.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0019_3-Positivo.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 3, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "<NAME>", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0018_4-Violeta-Mi-Tienda.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0018_4-Violeta-Mi-Tienda.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 4, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "<NAME>", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0017_5-Tu-Regalo-Chic.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0017_5-Tu-Regalo-Chic.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 5, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "Onitas", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0016_6-Onitas.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0016_6-Onitas.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 6, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "Bohemian Accessories", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0015_7-Bohemian-Accessories.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0015_7-Bohemian-Accessories.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 7, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "<NAME>", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0014_8-Conini-Bazar.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0014_8-Conini-Bazar-copia.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 8, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "Dango Family", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0013_9-Dango-Family.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0013_9-Dango-Family.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 9, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "Ufisa Pink Shop", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0012_10-Ufisa-Pink-Shop.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0012_10-Ufisa-Pink-Shop.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 10, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "Pikaboo", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0011_11-Pikaboo.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0011_11-Pikaboo.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 11, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "Embasémonos", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0010_12-Embasémonos.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0010_12-Embasémonos.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 12, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "<NAME>", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0009_13-Mochilas-de-Lana.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0009_13-Mochilas-de-Lana.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 13, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "The Culto Store", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0008_14-The-Culto-Store.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0008_14-The-Culto-Store.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 14, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "Hydra", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0007_15-Hydra.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0007_15-Hydra.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 15, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "Ruby Tuesday", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0006_16-Ruby-Tuesday.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0006_16-Ruby-Tuesday.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 16, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "Külko", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0005_17-Külko.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0005_17-Jülko.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 17, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "Morenaa", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0004_18-Morenaa.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0004_18-Morenaa.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 18, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "Tienda MCP", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0003_19-Tienda-MCP.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0003_19-Tienda-MCP.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 19, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "Sharlie", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0002_20-Sharlie.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0002_20-Sharlie.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 20, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "<NAME>", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0001_21-Frida-Creaciones.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0001_21-Frida-Creaciones.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 21, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) }, { name: "<NAME>", description: Faker::Lorem.sentence(10), photo: File.open(Rails.root + "app/assets/images/store_photo_0000_La-Hacedora.png"), cover_photo: File.open(Rails.root + "app/assets/images/store_cover_photo_0000_22-La-Hacedora.png"), facebook_link: [nil, Faker::Internet.url("facebook.com")].sample, instagram_link: [nil, Faker::Internet.url("instagram.com")].sample, user_id: 22, phone_number: Faker::Number.number(7), recommended: [true, false, false].sample, stations: stations.sample(5) } ] ) Product.create([ { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_1_0000_Galaxy-Bows.png"), price: 1000, stock: Faker::Number.between(1, 15), store_id: 1, best_seller: [true, false, false].sample, tag_list: "bowtie, humita, ribbon, ropa, accesorio, universo, colores, estrellas, universo, galaxia, hipster" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_1_0001_Taza-Pusheen.png"), price: 5000, stock: Faker::Number.between(1, 15), store_id: 1, best_seller: [true, false, false].sample, tag_list: "taza, loza, gato, pusheen, globo, tierno, fluffy, colores, gris, happy, animales, cerámica" }, { name: "Peluditos con <NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_1_0002_Peludito-Gatos-Rosado.png"), price: 7500, stock: Faker::Number.between(1, 15), store_id: 1, best_seller: [true, false, false].sample, tag_list: "ropa, peludito, peludo, rosado, gato, fluffy, chaleco, suéter, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_1_0003_Tattoo-Choker.png"), price: 700, stock: Faker::Number.between(1, 15), store_id: 1, best_seller: [true, false, false].sample, tag_list: "choker, collar, Fran, negro, 90s, accesorio, plástico" }, { name: "Set de Calcetines con Gatos", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_1_0004_Set-Calcetines-Gatos.png"), price: 9000, stock: Faker::Number.between(1, 15), store_id: 1, best_seller: [true, false, false].sample, tag_list: "ropa, calcetines, gato, tierno, hipster, gatos con ropa, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_1_0005_Cuaderno-Arnold.png"), price: 3500, stock: Faker::Number.between(1, 15), store_id: 1, best_seller: [true, false, false].sample, tag_list: "cuaderno, papelería, Arnold, Hey Arnold, Oye Arnold, corazón, love, azul, amarillo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_1_0006_Bolso-Frida-Kahlo.png"), price: 7000, stock: Faker::Number.between(1, 15), store_id: 1, best_seller: [true, false, false].sample, tag_list: "bolso, cartera, bolsos y carteras, México, Frida, Frida Kahlo, flores, colores" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_1_0007_Bolso-Gato.png"), price: 7000, stock: Faker::Number.between(1, 15), store_id: 1, best_seller: [true, false, false].sample, tag_list: "bolso, cartera, bolsos y carteras, gato, flores, flower crown, corona, crown, universo, estrellas, miau, galaxia" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_2_0000_Collar-Detalles-Morados.png"), price: 3000, stock: Faker::Number.between(1, 15), store_id: 2, best_seller: [true, false, false].sample, tag_list: "collar, accesorio, flores, morado, metálico, gris, collar largo, metal" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_2_0001_Colgante-Buhos-Plateado.png"), price: 3000, stock: Faker::Number.between(1, 15), store_id: 2, best_seller: [true, false, false].sample, tag_list: "collar, colgante, búhos, búho, gris, plateado, tierno, accesorio,collar largo, envejecido, metal" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_2_0002_Anillo-Piedras-Rojizas.png"), price: 2000, stock: Faker::Number.between(1, 15), store_id: 2, best_seller: [true, false, false].sample, tag_list: "anillo, accesorio, plateado, gris, flores, rojo, rojizo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_2_0003_Aros-Hojas-Dorados.png"), price: 2000, stock: Faker::Number.between(1, 15), store_id: 2, best_seller: [true, false, false].sample, tag_list: "aros, accesorio, dorado, hoja, hojas, aros grandes, amarillo" }, { name: "<NAME> con Mano de Fátima", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_2_0004_Pulsera-Plateada.png"), price: 4000, stock: Faker::Number.between(1, 15), store_id: 2, best_seller: [true, false, false].sample, tag_list: "pulsera, accesorio, plateado, gris, corazón, llave, trébol, lucky, lucky charm, religioso, mano de Fátima", }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_2_0005_Aros-Espiral-Dorados.png"), price: 2000, stock: Faker::Number.between(1, 15), store_id: 2, best_seller: [true, false, false].sample, tag_list: "aros, accesorio, dorado, amarillo, hoops, aros grandes, espiral" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_3_0000_Gorro-Totoro.png"), price: 5000, stock: Faker::Number.between(1, 15), store_id: 3, best_seller: [true, false, false].sample, tag_list: "gorro, lana, abrigo, Totoro, gris, blanco, negro, ponpon, orejitas, crochet, tejido, hecho a mano, handmade, anime, Hayao Miyazaki, Miyazaki, Mi <NAME>, My Neightbour Totoro" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_3_0001_Anillo-Meow-Dorado.png"), price: 2000, stock: Faker::Number.between(1, 15), store_id: 3, best_seller: [true, false, false].sample, tag_list: "gato, anillo, accesorio, dorado, amarillo, miau, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_3_0002_Anillo-Meow-Plateado.png"), price: 2000, stock: Faker::Number.between(1, 15), store_id: 3, best_seller: [true, false, false].sample, tag_list: "anillo, gato, accesorio, gris, plateado, tierno, miau, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_3_0003_Aros-Meow.png"), price: 5000, stock: Faker::Number.between(1, 15), store_id: 3, best_seller: [true, false, false].sample, tag_list: "aros, aros pegados, gato, negro, amarillo, tierno, porcelana fría, porcelana, accesorio, hecho a mano, animales, miau, cola" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_3_0004_Aros-Jake.png"), price: 5000, stock: Faker::Number.between(1, 15), store_id: 3, best_seller: [true, false, false].sample, tag_list: "aros, aros pegados, accesorio, Jake, Hora de Aventura, Adventure Time, amarillo, Jake and Finn, perro, animales, porcelana fría" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_3_0005_Llavero-Meow.png"), price: 5000, stock: Faker::Number.between(1, 15), store_id: 3, best_seller: [true, false, false].sample, tag_list: "llavero, llave, gato, gris, happy, keychan, animales, porcelana fría" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_3_0006_Aros-Frida-Kahlo.png"), price: 5000, stock: Faker::Number.between(1, 15), store_id: 3, best_seller: [true, false, false].sample, tag_list: "aros, aros pegados, Frida, Frida Kahlo, Kahlo, flores, flower crown, pretty, colores, porcelana fría, hecho a mano, handmade, México" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_4_0000_Poncho-Tejido-Detalle-Floral.png"), price: 11000, stock: Faker::Number.between(1, 15), store_id: 4, best_seller: [true, false, false].sample, tag_list: "ropa, poncho, tejido, telar, flor, blanco, lana, cuello redondo" }, { name: "<NAME> con Detalles Florales", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_4_0001_Vestido-Azul-Marino-Detalles-Florales.png"), price: 9000, stock: Faker::Number.between(1, 15), store_id: 4, best_seller: [true, false, false].sample, tag_list: "vestido, azul, ropa, flores, talla s, cuello redondo" }, { name: "Collar Inspirado en África", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_4_0002_Collar-Inspirado-en-África-3.png"), price: 7000, stock: Faker::Number.between(1, 15), store_id: 4, best_seller: [true, false, false].sample, tag_list: "collar, collar grande, accesorio, colores, borlas, estilo África, metal, África, hilo, piedras" }, { name: "Collar Inspirado en África", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_4_0003_Collar-Inspirado-en-África-2.png"), price: 7000, stock: Faker::Number.between(1, 15), store_id: 4, best_seller: [true, false, false].sample, tag_list: "collar, accesorio, collar grande, piedras, estilo África, naranjo, verde" }, { name: "Collar Inspirado en África", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_4_0004_Collar-Inspirado-en-África-1.png"), price: 7000, stock: Faker::Number.between(1, 15), store_id: 4, best_seller: [true, false, false].sample, tag_list: "collar, accesorio, collar grande, piedras, estilo África, naranjo, dorado, metal, borlas, hilo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_5_0000_Llaver-Príncipe-Sapo.png"), price: 3000, stock: Faker::Number.between(1, 15), store_id: 5, best_seller: [true, false, false].sample, tag_list: "llavero, keychan, sapo, príncipe sapo, corona, corazón, verde, happy, hecho a mano, handmade, porcelana fría, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_5_0001_Llavero-Gato.png"), price: 3000, stock: Faker::Number.between(1, 15), store_id: 5, best_seller: [true, false, false].sample, tag_list: "llavero, gato, keychan, blanco, porcelana fría, estrellas, hecho a mano, handmade, animales" }, { name: "Llavero Profesión Personalizable", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_5_0002_Llavero-Profesión-Personalizable.png"), price: 7000, stock: Faker::Number.between(1, 15), store_id: 5, best_seller: [true, false, false].sample, tag_list: "llavero, keychan, iphone, diente, dentista, porcelana fría, happy, hecho a mano, handmade, cepillo de dientes, pasta de dientes, pepe, personalizado" }, { name: "<NAME> Personalizable", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_5_0003_Llavero-Pareja-Personalizable.png"), price: 7000, stock: Faker::Number.between(1, 15), store_id: 5, best_seller: [true, false, false].sample, tag_list: "llavero, keychan, porcelana fría, hecho a mano, handmade, pareja, amor, corazón, rosado, mujer, hombre, bailarina, deportista, heteronormativo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_6_0000_Muñeco-Selk'nam.png"), price: 14000, stock: Faker::Number.between(1, 15), store_id: 6, best_seller: [true, false, false].sample, tag_list: "onitas, peluche, plushie, cultura chilena, muñeco, Selk’nam, muñeco Selk’nam, Selknam, muñeco Selknam, patrimonio chileno, blanco, rojo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_6_0001_Muñeca-Violeta-Parra.png"), price: 14000, stock: Faker::Number.between(1, 15), store_id: 6, best_seller: [true, false, false].sample, tag_list: "onitas, peluche, plushie, cultura chilena, muñeca, Violeta, Violeta Parra, guitarra, muñeca Violeta Parra, música" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_6_0002_Muñeco-Pingüino-de-Humboldt.png"), price: 14000, stock: Faker::Number.between(1, 15), store_id: 6, best_seller: [true, false, false].sample, tag_list: "onitas, peluche, plushie, cultura chilena, pingüino, pingüino, pinguino de Humboldt, peluche pinguino, fauna, animales, fauna chilena, blanco, negro, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_6_0003_Muñeco-Zorro-Chilote.png"), price: 14000, stock: Faker::Number.between(1, 15), store_id: 6, best_seller: [true, false, false].sample, tag_list: "onitas, peluche, plushie, cultura chilena, fauna chilena, animales, zorro, zorro chilote, gris, peluche zorro, peluche zorro chilote, animales" }, { name: "<NAME> con Monedas", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_7_0000_Choker-Crochet-con-Monedas.png"), price: 3000, stock: Faker::Number.between(1, 15), store_id: 7, best_seller: [true, false, false].sample, tag_list: "collar, accesorio, choker, crochet, monedas, hilo, blanco, metal" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_7_0001_Collar-Doble-Elefante.png"), price: 3000, stock: Faker::Number.between(1, 15), store_id: 7, best_seller: [true, false, false].sample, tag_list: "collar, accesorio, morado, metal, piedras, bronce, elefante, mostacillas, collar largo, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_7_0002_Collar-Tonos-Otoñales.png"), price: 5000, stock: Faker::Number.between(1, 15), store_id: 7, best_seller: [true, false, false].sample, tag_list: "collar, accesorio, collar largo, bronce, rojo, blanco, metal" }, { name: "<NAME> con Mano de Fátima y Piedra Onix", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_7_0003_Collar-Doble-Mano-Fátima-Piedra-Onix.png"), price: 5000, stock: Faker::Number.between(1, 15), store_id: 7, best_seller: [true, false, false].sample, tag_list: "collar, collar largo, metal, plateado, gris, rojo, mano de Fátima, piedras, piedra, piedra onix, onix, negro, accesorio" }, { name: "<NAME> con Piedra Luna", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_7_0004_Choker-Piedra-Luna.png"), price: 2000, stock: Faker::Number.between(1, 15), store_id: 7, best_seller: [true, false, false].sample, tag_list: "collar, choker, negro, piedras, piedra, piedra luna, blanco, accesorio" }, { name: "Collar con Piedras de Cuarzo y Árbol de la Vida", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_7_0005_Collar-Piedras-Cuarzo-Árbol-de-la-Vida.png"), price: 6000, stock: Faker::Number.between(1, 15), store_id: 7, best_seller: [true, false, false].sample, tag_list: "collar, accesorio, metal, plateado, árbol, árbol de la vida, cuarzo, piedras, piedra, blanco" }, { name: "Collar con Plumas Envejecido", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_7_0006_Collar-Plumas-Envejecido.png"), price: 6000, stock: Faker::Number.between(1, 15), store_id: 7, best_seller: [true, false, false].sample, tag_list: "collar, accesorio, plumas, metal, envejecido, monedas, verde agua" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_8_0000_Polera-Gato.png"), price: 4000, stock: Faker::Number.between(1, 15), store_id: 8, best_seller: [true, false, false].sample, tag_list: "polera, ropa, gato, playa, beach, crema, pelota, colores, crop top, verano, manga corta, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_8_0001_Polera-Flores.png"), price: 4000, stock: Faker::Number.between(1, 15), store_id: 8, best_seller: [true, false, false].sample, tag_list: "polera, ropa, manga corta, celeste, flores, colores, verano" }, { name: "Crop Top Pájaro", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_8_0002_Polera-Pájaro.png"), price: 4000, stock: Faker::Number.between(1, 15), store_id: 8, best_seller: [true, false, false].sample, tag_list: "polera, ropa, colores, manga corta, pájaro, naranjo, azul, verde, gris, corazón, llave, crop top, animales" }, { name: "Crop Top Elefante Feliz", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_8_0003_Polera-Elefante.png"), price: 4000, stock: Faker::Number.between(1, 15), store_id: 8, best_seller: [true, false, false].sample, tag_list: "polera, manga corta, verano, ropa, elefante, corazón, corazones, azul, celeste, colores, happy, love, crop top, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_9_0000_Monedero-Gatito.png"), price: 3500, stock: Faker::Number.between(1, 15), store_id: 9, best_seller: [true, false, false].sample, tag_list: "monedero, gato, blanco, orejitas, útil, azul, gris, big eyes, miau, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_9_0001_Lápices-Corona.png"), price: 1000, stock: Faker::Number.between(1, 15), store_id: 9, best_seller: [true, false, false].sample, tag_list: "lápices, papelería, colores, corona, perla, forever, royalty, lápiz" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_9_0002_Lápices-Gatitos.png"), price: 1000, stock: Faker::Number.between(1, 15), store_id: 9, best_seller: [true, false, false].sample, tag_list: "“lápiz, lápices, gatitos, papelería, kawaii, cafe, blanco, rosado, bowtie, hairbow, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_9_0003_Lápices-Monster-Bigotes.png"), price: 1000, stock: Faker::Number.between(1, 15), store_id: 9, best_seller: [true, false, false].sample, tag_list: "lápiz, lápices, monster, monstruo, bigote, moustache, ojos, i moustache you a question, negro, blanco, colores, celeste, rosado, zebra, rayas, bigote" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_9_0004_Cosmetiquero-Panda-Plush.png"), price: 3500, stock: Faker::Number.between(1, 15), store_id: 9, best_seller: [true, false, false].sample, tag_list: "cosmetiquero, estuche, fluffy, ovo, panda, orejitas, blanco, negro, plush, tierno, animales, kawaii" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_9_0005_Estuche-Gatitos-3.png"), price: 6000, stock: Faker::Number.between(1, 15), store_id: 9, best_seller: [true, false, false].sample, tag_list: "estuche, colores, gato, azul, lápices, lápiz, eco cuero, cats kingdom, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_9_0006_Estuche-Gatitos-2.png"), price: 6000, stock: Faker::Number.between(1, 15), store_id: 9, best_seller: [true, false, false].sample, tag_list: "estuche, colores, gato, lápices, lápiz, eco cuero, cats kingdom, miau, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_9_0007_Estuche-Gatitos.png"), price: 6000, stock: Faker::Number.between(1, 15), store_id: 9, best_seller: [true, false, false].sample, tag_list: "estuche, colores, gato, lápices, lápiz, eco cuero, cats kingdom, miau, gatos con ropa, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_10_0000_Billetera-Amarilla-Gato.png"), price: 11000, stock: Faker::Number.between(1, 15), store_id: 10, best_seller: [true, false, false].sample, tag_list: "billetera, wallet, monedero, cuero, gato, crema, tierno, borla, cute kitten, colores, amarillo, animales, elegante, fancy" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_10_0001_Billetera-Morada.png"), price: 11000, stock: Faker::Number.between(1, 15), store_id: 10, best_seller: [true, false, false].sample, tag_list: "billetera, wallet, monedero, morado, cuero, borla, elegante, bags garden" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_10_0002_Polerón-Hámster.png"), price: 9000, stock: Faker::Number.between(1, 15), store_id: 10, best_seller: [true, false, false].sample, tag_list: "polerón, ropa, hámster, animales, almendra, crema, naranjo, fluffy, tierno, strawberry, frutilla, happy, oversized, baby, big eyes, cuello redondo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_10_0003_Polerón-Conejo.png"), price: 9000, stock: Faker::Number.between(1, 15), store_id: 10, best_seller: [true, false, false].sample, tag_list: "polerón, ropa, conejo, animales, zanahoria, hairbow, fluffy, tierno, blanco, azul, big eyes, cuello redondo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_10_0004_Polerón-Gato-3.png"), price: 9000, stock: Faker::Number.between(1, 15), store_id: 10, best_seller: [true, false, false].sample, tag_list: "polero, ropa, blanco, gato, pez, animales, agua, corazón, love, kiss, tierno, naranjo, azul, cuello redondo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_10_0005_Polerón-Gato-2.png"), price: 9000, stock: Faker::Number.between(1, 15), store_id: 10, best_seller: [true, false, false].sample, tag_list: "polerón, ropa, verde, crema, silla, gato, pájaro, animales, gatos con ropa, comida, ratón, pastel, cuello redondo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_10_0006_Polerón-Gato.png"), price: 9000, stock: Faker::Number.between(1, 15), store_id: 10, best_seller: [true, false, false].sample, tag_list: "polerón, ropa, verde, crema, silla, gato, pájaro, animales, gatos con ropa, comida, ratón, pastel, cuello redondo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_11_0000_Muñeco-Capitán-América.png"), price: 9000, stock: Faker::Number.between(1, 15), store_id: 11, best_seller: [true, false, false].sample, tag_list: "peluche, plushie, capitán, cap, Capitán América, peluche Capitán América, vengadores, avengers, marvel, marvel comics, mcu, <NAME>, estrella, rojo, azul, blanco" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_11_0001_Muñeco-Minion-Superman.png"), price: 11000, stock: Faker::Number.between(1, 15), store_id: 11, best_seller: [true, false, false].sample, tag_list: "peluche, plushie, minion, minions, Superman, dreamworks, peluche minion, peluche minion superman, disfraz, amarillo, rojo, azul, dc, dc comics, disfrazado, disfraz" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_11_0002_Muñeca-Ana.png"), price: 12000, stock: Faker::Number.between(1, 15), store_id: 11, best_seller: [true, false, false].sample, tag_list: "muñeca, peluche, plushie, Anna, peluche Anna, Frozen, Disney, Arendelle, Let It Go, princesa, rosado, naranjo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_11_0003_Muñeco-Spiderman.png"), price: 8000, stock: Faker::Number.between(1, 15), store_id: 11, best_seller: [true, false, false].sample, tag_list: "muñeco, peluche, plushie, Spiderman, Spider man, Spidey, marvel, marvel comics, <NAME>er, rojo, azul, Hombre Araña" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_12_0000_Dulces-Boo.png"), price: 4500, stock: Faker::Number.between(1, 15), store_id: 12, best_seller: [true, false, false].sample, tag_list: "dulces, Boo, kitty, gatito, Monsters Inc, pixar, Disney, monstruo, frasco, morado, comida" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_12_0001_Dulces-Cyberduck.png"), price: 4000, stock: Faker::Number.between(1, 15), store_id: 12, best_seller: [true, false, false].sample, tag_list: "Psyduck, pato, animales, Pokemón, amarillo, dulces, frasco, comida" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_12_0002_Galletas-Cookie-Monster.png"), price: 5000, stock: Faker::Number.between(1, 15), store_id: 12, best_seller: [true, false, false].sample, tag_list: "dulces, galleta, frasco, monstruo, cookie, Cookie Monster, Sesame Street, Plaza Sésamo, azul, comida" }, { name: "Pastillas Para la Buena Suerte de Eugene", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_12_0003_Pastillas-para-la-Buena-SUerte-Eugene.png"), price: 4500, stock: Faker::Number.between(1, 15), store_id: 12, best_seller: [true, false, false].sample, tag_list: "frasco, pastillas, dulces, comida, eugene, naranjo, suerte, lucky, lucky charm, trébol, Hey Arnold, Arnold, Oye Arnold, buena suerte" }, { name: "Pastillas para la Memora de Dory", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_12_0004_Pastillas-para-la-Memoria-Dory.png"), price: 6000, stock: Faker::Number.between(1, 15), store_id: 12, best_seller: [true, false, false].sample, tag_list: "dulces, comida, frasco, Dory, dulces, Finding Dory, Finding Nemo, Buscando a Nemo, Buscando a Dory, memoria, mala memoria, Pixar, Disney, amarillo, azul, pez, animales, pastillas para la memoria" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_12_0005_Pastillas-de-Poder-Goku.png"), price: 5500, stock: Faker::Number.between(1, 15), store_id: 12, best_seller: [true, false, false].sample, tag_list: "frasco, pastillas, comida, Goku, pastillas de poder, dulces, sayayin, Dragon Ball, estrellas, naranjo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_13_0000_Bati-Mochila-de-Lana.png"), price: 15000, stock: Faker::Number.between(1, 15), store_id: 13, best_seller: [true, false, false].sample, tag_list: "mochila, backpack, bolsos y carteras, tejido, lana, crochet, Batman, batimochila, negro, amarillo, gris, DC, DC comics, bolsos y carteras, batiseñal, bat signal" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_13_0001_Mochila-de-Lana-2.png"), price: 14000, stock: Faker::Number.between(1, 15), store_id: 13, best_seller: [true, false, false].sample, tag_list: "mochila, backpack, bolsos y carteras, tejido, lana, crochet, bolsos y carteras, blanco, rosado, hecho a mano, handmade" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_13_0002_Mochila-de-Lana.png"), price: 13000, stock: Faker::Number.between(1, 15), store_id: 13, best_seller: [true, false, false].sample, tag_list: "mochila, backpack, bolsos y carteras, tejido, lana, crochet, amarillo, verde, rojo, hecho a mano, handmade" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_13_0003_Billetera-de-Lana.png"), price: 5000, stock: Faker::Number.between(1, 15), store_id: 13, best_seller: [true, false, false].sample, tag_list: "billetera, wallet, lana, crochet, tejido, hecho a mano, handmade, monedero, azul, rojo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_13_0004_Monedero-de-Lana.png"), price: 4000, stock: Faker::Number.between(1, 15), store_id: 13, best_seller: [true, false, false].sample, tag_list: "billetera, wallet, monedero, crochet, lana, tejido, colores, hecho a mano, handmade, negro" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_13_0005_Monedero-Triangular-de-Lana.png"), price: 4500, stock: Faker::Number.between(1, 15), store_id: 13, best_seller: [true, false, false].sample, tag_list: "billetera, monedero, crochet, tejido, lana, naranjo, azul, celeste, handmade, hecho a mano" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_14_0000_Collar-Snitch-Dorada.png"), price: 6500, stock: Faker::Number.between(1, 15), store_id: 14, best_seller: [true, false, false].sample, tag_list: "collar, accesorio, snitch, dorado, golden snitch, snitch dorada, Harry Potter, HP, alas, envejecido, collar largo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_14_0001_Collar-Casa-Stark.png"), price: 6000, stock: Faker::Number.between(1, 15), store_id: 14, best_seller: [true, false, false].sample, tag_list: "collar, accesorio, collar largo, plateado, gris, lobo, animales, metal, GoT, Game of Thrones, Stark, Starks, house Starks, Winter Is Coming" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_14_0002_Collar-Gato-2.png"), price: 5000, stock: Faker::Number.between(1, 15), store_id: 14, best_seller: [true, false, false].sample, tag_list: "collar, collar largo, accesorio, metal, plateado, gris, gato, animales, blanco, big eyes, tierno" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_14_0003_Llavero-Darth-Vader.png"), price: 3000, stock: Faker::Number.between(1, 15), store_id: 14, best_seller: [true, false, false].sample, tag_list: "llavero, keychan, plateado, gris, envejecido, Darth Vader, Star Wars, Anakin, Anakin Skywalker, May The Force Be With You, May the 4rth" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_14_0004_Collar-Gato.png"), price: 3500, stock: Faker::Number.between(1, 15), store_id: 14, best_seller: [true, false, false].sample, tag_list: "collar, collar largo, accesorio, dorado, perla, piedras, rosado, blanco, gato, animales" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_14_0005_Reloj-Gato.png"), price: 6500, stock: Faker::Number.between(1, 15), store_id: 14, best_seller: [true, false, false].sample, tag_list: "reloj, clock, accesorio, gato, animales, blanco, dorado, miau, bling, cuero" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_14_0006_Audífonos-Baymax.png"), price: 9500, stock: Faker::Number.between(1, 15), store_id: 14, best_seller: [true, false, false].sample, tag_list: "audifonos, earplugs, electronicos, musica, Baymax, Big Hero 6, Grandes Heroes, Disney, Hiro, ba la la la" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_14_0007_Pin-Mano-de-Rey.png"), price: 6000, stock: Faker::Number.between(1, 15), store_id: 14, best_seller: [true, false, false].sample, tag_list: "pin, dorado, GoT, Game of Thrones, mano del rey, kingshand, Tyrion, accesorio, envejecido" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_14_0008_Collar-Espada-Games-Of-Thrones.png"), price: 5000, stock: Faker::Number.between(1, 15), store_id: 14, best_seller: [true, false, false].sample, tag_list: "collar, collar largo, GoT, Game of Thrones, dorado, gris, rojo, accesorio" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_14_0009_Aros-Gira-Tiempo.png"), price: 6000, stock: Faker::Number.between(1, 15), store_id: 14, best_seller: [true, false, false].sample, tag_list: "aros, accesorio, dorado, amarillo, reloj, Harry Potter, HP, giratiempo, time turner, Hermione" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_14_0010_Collar-Gira-Tiempo.png"), price: 7000, stock: Faker::Number.between(1, 15), store_id: 14, best_seller: [true, false, false].sample, tag_list: "collar, collar largo, accesorio, dorado, amarillo, reloj, harry potter, hp, giratiempo, time turner, hermione" }, { name: "Pendrive BB8", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_14_0011_Pendrive-BB8.png"), price: 13000, stock: Faker::Number.between(1, 15), store_id: 14, best_seller: [true, false, false].sample, tag_list: "pendrive, usb, electronicos, BB8, Star Wars, The Force Awakens, Star Wars The Force Awakens, Poe Dameron, robot, naranjo, blanco, plástico" }, { name: "Crop Top", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_15_0000_Crop-Top-Lanilla.png"), price: 4500, stock: Faker::Number.between(1, 15), store_id: 15, best_seller: [true, false, false].sample, tag_list: "polera, ropa, crop top, manga larga, lanilla, negro, crema" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_15_0001_Vestido-Modelo-Corazón.png"), price: 5000, stock: Faker::Number.between(1, 15), store_id: 15, best_seller: [true, false, false].sample, tag_list: "vestido, ropa, verano, corazón, crema, negro, blanco, rayas, talla s" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_15_0002_Bolsa-Cordones-Calavera-Mexicana.png"), price: 4000, stock: Faker::Number.between(1, 15), store_id: 15, best_seller: [true, false, false].sample, tag_list: "bolso, bolsos y carteras, backpack, mochila, skull, calavera, negro, colores, estrella, corazón, moustache, México, polka dots" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_15_0003_Funda-para-Cojín-Ariel-Alternativa.png"), price: 3500, stock: Faker::Number.between(1, 15), store_id: 15, best_seller: [true, false, false].sample, tag_list: "funda, cojín, funda cojín, ropa de cama, almohada, negro, rojo, ariel, disney, la sirenita, sirena, alternativo, princesa, tatuajes, piercings, corset, estrellas, hipster" }, { name: "Bolsa Negra Puntos Blancos", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_15_0004_Bolsa-Negra-Puntos-Blancos.png"), price: 4500, stock: Faker::Number.between(1, 15), store_id: 15, best_seller: [true, false, false].sample, tag_list: "bolsa, bolso, bolsos y carteras, negro, blanco, polka dots" }, { name: "Vestido Negro Puntos Blancos", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_15_0005_Vestido-Negro-Puntos-Blancos.png"), price: 5500, stock: Faker::Number.between(1, 15), store_id: 15, best_seller: [true, false, false].sample, tag_list: "vestido, ropa, negro, blanco, polka dots, talla s, verano" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_16_0000_Polera-Gris-Detalle-Cuello.png"), price: 4000, stock: Faker::Number.between(1, 15), store_id: 16, best_seller: [true, false, false].sample, tag_list: "polera, ropa, gris, negro, manga corta, cuello redondo, talla s" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_16_0001_Polera-Negra-Detalles-Blancos.png"), price: 5500, stock: Faker::Number.between(1, 15), store_id: 16, best_seller: [true, false, false].sample, tag_list: "polera, ropa, negro, blanco, moños, bowties, bows, perlas, manga corta, cuello redondo, talla s" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_16_0002_Chaleco-Negro-Corazones-Blancos.png"), price: 4500, stock: Faker::Number.between(1, 15), store_id: 16, best_seller: [true, false, false].sample, tag_list: "chaleco, ropa, manga larga, corazón, negro, blanco, cuello v, Fran" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_16_0003_Polerón-Gris-Detalle-Cuello.png"), price: 4000, stock: Faker::Number.between(1, 15), store_id: 16, best_seller: [true, false, false].sample, tag_list: "polerón, gris, ropa, chaleco, perla, cuello redondo, manga larga, blanco" }, { name: "Pack de 6 Cupcakes Personalizados", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_17_0000_Cupcakes.png"), price: 3000, stock: Faker::Number.between(1, 15), store_id: 17, best_seller: [true, false, false].sample, tag_list: "cupcakes, comida, muffin, frosting, rico, ñam, verde, rosado" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_17_0001_Cesta-Gourmet-2.png"), price: 7000, stock: Faker::Number.between(1, 15), store_id: 17, best_seller: [true, false, false].sample, tag_list: "cesta, canasto, comida, gift basquet, fruta, frutillas, strawberries, surtido, frasco, tejido, taza, sandwich, madera, gift, regalo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_17_0002_Cesta-Gourmet.png"), price: 9000, stock: Faker::Number.between(1, 15), store_id: 17, best_seller: [true, false, false].sample, tag_list: "cesta, canasto, comida, gift basquet, frasco, madera, pan, frutos secos, vino, queso, surtido, gift, regalo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_18_0000_Cartera-Bordada-2.png"), price: 4500, stock: Faker::Number.between(1, 15), store_id: 18, best_seller: [true, false, false].sample, tag_list: "cartera, bolso, bolsos y carteras, bordado, ponpon, flores, colores, blanco, accesorio" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_18_0001_Cartera-Bordada.png"), price: 4500, stock: Faker::Number.between(1, 15), store_id: 18, best_seller: [true, false, false].sample, tag_list: "cartera, bolso, bolsos y carteras, bordado, ponpon, flores, colores, rosado, accesorio" }, { name: "Aros", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_18_0002_Aros-3.png"), price: 1500, stock: Faker::Number.between(1, 15), store_id: 18, best_seller: [true, false, false].sample, tag_list: "aros, accesorio, aros largos, envejecido, dorado, amarillo, hoops" }, { name: "Aros", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_18_0003_Aros-2.png"), price: 1200, stock: Faker::Number.between(1, 15), store_id: 18, best_seller: [true, false, false].sample, tag_list: "aros, accesorio, plateado, gris, piedra, aros largos" }, { name: "Aros", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_18_0004_Aros-1.png"), price: 900, stock: Faker::Number.between(1, 15), store_id: 18, best_seller: [true, false, false].sample, tag_list: "aros, accesorio, dorado, amarillo, envejecido, hojas" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_19_0000_Polera-Flecos-Beige.png"), price: 3500, stock: Faker::Number.between(1, 15), store_id: 19, best_seller: [true, false, false].sample, tag_list: "polera, ropa, verano, manga corta, flecos, fringe, beige, crema, colores, botones, blanco" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_19_0001_Vestido-Encaje.png"), price: 6000, stock: Faker::Number.between(1, 15), store_id: 19, best_seller: [true, false, false].sample, tag_list: "vestido, ropa, encaje, rojo, rosado, manga corta, verano, talla s" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_19_0002_Chalas-Multicolor.png"), price: 7000, stock: Faker::Number.between(1, 15), store_id: 19, best_seller: [true, false, false].sample, tag_list: "chalas, verano, terraplen, blanco, colores, cuero, verde, suela neumatico, sandalias" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_20_0000_Cartera-de-Mano.png"), price: 3500, stock: Faker::Number.between(1, 15), store_id: 20, best_seller: [true, false, false].sample, tag_list: "cartera, bolsos y carteras, colores, accesorio, dorado, rosado, morado, azul, plateado, trenzado, plástico" }, { name: "Estuche", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_20_0001_Estuche.png"), price: 3500, stock: Faker::Number.between(1, 15), store_id: 20, best_seller: [true, false, false].sample, tag_list: "estuche, lapicero, rosado, plástico, trenzado, billetera, wallet, monedero" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_21_0000_Adorno-Banderines.png"), price: 7000, stock: Faker::Number.between(1, 15), store_id: 21, best_seller: [true, false, false].sample, tag_list: "banderines, banderas, adorno, colgante, banner, colores, flores, rosado, blanco, decoración" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_21_0001_Estuche.png"), price: 4000, stock: Faker::Number.between(1, 15), store_id: 21, best_seller: [true, false, false].sample, tag_list: "estuche, estuche desplegable, lapicero, flores, colores, blanco, pasley, artsy, tela" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_21_0002_Billetera.png"), price: 3000, stock: Faker::Number.between(1, 15), store_id: 21, best_seller: [true, false, false].sample, tag_list: "billetera, tela, wallet, monedero, flores, azul, rojo, amarillo" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_21_0003_Adornos-Calaveras-Mexicanas.png"), price: 2000, stock: Faker::Number.between(1, 15), store_id: 21, best_seller: [true, false, false].sample, tag_list: "adorno, colgante, calavera, skull, México, flores, colores, blanco, azul, rojo, felpa, fieltro, hecho a mano, handmade" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_21_0004_Adorno-Matriuskas.png"), price: 2000, stock: Faker::Number.between(1, 15), store_id: 21, best_seller: [true, false, false].sample, tag_list: "adorno, colgante, mostacillas, matriuska, matrioska, muñecas, muñeca, flores, colores, naranjo, azul, verde, felpa, fieltro, hecho a mano, handmade" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_21_0005_Muñeco-Gato.png"), price: 4500, stock: Faker::Number.between(1, 15), store_id: 21, best_seller: [true, false, false].sample, tag_list: "peluche, plushie, gato, miau, animal, muñeco, muñeco gato, peluche gato, negro, rosado, colores, hecho a mano, handmade" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_22_0000_Macetero-para-Cactus-Gato.png"), price: 6000, stock: Faker::Number.between(1, 15), store_id: 22, best_seller: [true, false, false].sample, tag_list: "macetero, cerámica, gato, miau, animales, negro, macetero chico, macetero gato, plantas, adorno, decoración" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_22_0001_Collar-Gato.png"), price: 3000, stock: Faker::Number.between(1, 15), store_id: 22, best_seller: [true, false, false].sample, tag_list: "collar, collar largo, colgante, gato, animales, negro, cerámica, envejecido, dorado" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_22_0002_Figura-Perro.png"), price: 4000, stock: Faker::Number.between(1, 15), store_id: 22, best_seller: [true, false, false].sample, tag_list: "figura, figura perro, perro, animales, fox terrier, café, cerámica, adorno, decoración" }, { name: "<NAME>", description: Faker::Lorem.sentence(5), photo: File.open(Rails.root + "app/assets/images/product_photo_store_22_0003_Macetero-para-Cactus-Llama.png"), price: 6000, stock: Faker::Number.between(1, 15), store_id: 22, best_seller: [true, false, false].sample, tag_list: "macetero, macetero llama, llama, animales, blanco, colores, cerámica, macetero chico, adorno, decoración, plantas" }, ] )<file_sep>/app/assets/javascripts/slide_link_field.js $(document).on("page:load ready", function() { $('.stores.new').ready(function () { $('.myButton').click(function() { $('.dropDownField').slideToggle(250); }); $('.myButton2').click(function() { $('.dropDownField2').slideToggle(250); }); }); $('.stores.edit').ready(function () { $('.myButton').click(function() { $('.dropDownField').slideToggle(250); }); $('.myButton2').click(function() { $('.dropDownField2').slideToggle(250); }); }); });<file_sep>/app/controllers/products/comments_controller.rb class Products::CommentsController < CommentsController before_action :set_commentable load_and_authorize_resource :product load_and_authorize_resource :comment, through: :product private def set_commentable @store = Store.find(params[:store_id]) @commentable = Product.find(params[:product_id]) end end
ba5b712524dd226dd43511c1b53bbec7dc816c69
[ "JavaScript", "Ruby" ]
16
Ruby
fbmedina/proyecto_final
657ed6032f29f347413013826779fe7005fdbf3a
a117b626bb360f40036b253d07eadb6e2b8d78cf
refs/heads/master
<file_sep>import { Entity, Column, PrimaryGeneratedColumn, BaseEntity } from "typeorm"; export interface User { id: number; email: string; } /** * Represents a single logged in User in the service. This is strictly service level User and does * directly contain any personal information, other than through relations. */ @Entity() export default class UserEntity extends BaseEntity implements User { @PrimaryGeneratedColumn() id: number; @Column({ length: 80 }) email: string; public toJson(): User { return { id: this.id, email: this.email } } } <file_sep>/** * Attempts to load a specific environment variable from process.env. * @param variable Name of the environment variable * @param defaultValue What the value should default to if we cannot find it from environment. Optional. */ const load = (variable: string, defaultValue?: string): string => { if (!process.env[variable]) { if (!defaultValue) { throw `Variable ${variable} not available.`; } else { return defaultValue; } } return process.env[variable]; }; export default load;<file_sep>const chai = require('chai'); const expect = chai.expect; const should = chai.should; const steemitData = require('../release/index'); // TODO configure all console winston messages to be hidden in testing mode describe('steemitData module', () => { it('Connects correctly to steemitdata Mongodb storage', (done) => { steemitData.connect() }); }); <file_sep>// This shim import is required to have metadata reflection working properly with typeorm import "reflect-metadata"; import * as Koa from 'koa'; import * as Router from 'koa-router'; import * as Body from 'koa-body'; import * as Serve from 'koa-static'; import loadEnvironmentVariable from './load-environment-variable'; import database from './database'; const application = new Koa(); const router = new Router(); router.get('/', async (context: Router.IRouterContext, next: Router.IMiddleware) => { context.body = 'Hello World!'; }); router.post('/api/user', async (context: Router.IRouterContext, next: Router.IMiddleware) => { // TODO start using json schema validation for the incoming JSON. Now we just blindly trust it because we are pretty hardcore // TODO start using authentication / authorization const email = context.request.body.email; const user = await database.addUser(email); context.body = user; }); application .use(Body()) .use(router.routes()) .use(router.allowedMethods()) application .listen(loadEnvironmentVariable('PORT')); console.log(`Application running.`); <file_sep># This compose file should only be used for local development and nothing else. version: '2' services: # Using this node.js image to mount the local environment inside it and making sure it runs web: image: node:9.7.1-alpine volumes: - .:/web ports: - "8080:8080" depends_on: - postgres command: [ sh, -c, "cd /web && npm install && node node_modules/nodemon/bin/nodemon.js -L --delay 5 release/index.js" ] environment: PORT: 8080 DATABASE_URL: postgres://dnazizjfebuydj:<PASSWORD>@postgres:5432/d9fnnl736pfc5m links: - "postgres" postgres: # Production uses 10.0 of Postgres from Heroku but this is fine. image: postgres:10.2-alpine environment: # Come up with some mad testing ones for local testing to really make sure the pipeline works locally # as it should. These you cannot typo in place by accident. Impossibru! POSTGRES_USER: dnazizjfebuydj POSTGRES_PASSWORD: <PASSWORD> POSTGRES_DB: d9fnnl736pfc5m # For debugging purposes, expose the same port for host so we can directly connect to it with our db client ports: - "5432:5432" <file_sep># Tracked * [Project](https://github.com/mikaturunen/tracked/projects/1) * [Wiki](https://github.com/mikaturunen/tracked/wiki) ## Running local development environment * TODO: explain it. <file_sep>import { createConnection } from 'typeorm'; import loadEnvironmentVariable from './load-environment-variable' import * as path from 'path' import User from './entities/User'; // Closure pattern to invoke it instantly and store the promise for later use const init = (async () => createConnection({ type: "postgres", // Example: postgres://dnazizjfebuydj:02201<EMAIL>cebb<EMAIL>@ec2-79-125-117-53.eu-west-1.compute.<EMAIL>.com:5432/d9fnnl736pfc5m url: loadEnvironmentVariable('DATABASE_URL'), entities: [ path.join(__dirname, "/entities/*.js") ], synchronize: true }))(); /** * Saves a new user into the database for later use. Creates a UserEntity and returns a User. * @param email Email address for a new user. */ const addUser = async (email: string) => init.then(async connection => { try { const newUser = new User(); newUser.email = email; await newUser.save(); return newUser.toJson(); } catch (error) { console.log(`Could not save UserEntity for new user: ${email}.`); console.log(`Error from saving: ${JSON.stringify(error, null, 2)}.`); throw error; } }); export default { addUser }
6c51bb7a1054e53dd9eb691be329a795a655ffd9
[ "JavaScript", "TypeScript", "YAML", "Markdown" ]
7
TypeScript
mikaturunen/tracked
1a2f60f8dacb627eb4cc2d694ab609b2faa5c5af
39f140d0c15513bdb218068b983d3377a2b3719e
refs/heads/master
<file_sep>## -- These commands create a plot of total emissions of PM2.5 from coal combustion in the United States. ## -- Use the SCC data to subset out the SCC codes associated with coal and combustion > SCCcomb <- grepl(pattern = "comb", SCC$SCC.Level.One, ignore.case = TRUE) ## scrap out combustion ids > SCCcoal <- grepl(pattern = "coal", SCC$SCC.Level.Four, ignore.case = TRUE) ## scrap out coal ids > coalcomb <- (SCCcomb & SCCcoal) ## intersect of combustion and coal ids > SCCcoalcomb <- SCC[coalcomb, ]$SCC ## subset SCC ids against "coal" and "comb" ## -- Create a subsetted data frame from NEI, then plot > NEIcoalcomb <- NEI[NEI$SCC %in% SCCcoalcomb, ] ## subset coal combustion emissions data > coalplot <- ggplot(aes(factor(year), Emissions), data = NEIcoalcomb) > coalplot + geom_bar(stat = "identity", fill = "purple") + labs(x = "Year", y = "Total PM2.5 Emission", title = "PM2.5 Emission from Combusting Coal, US") > dev.copy(png, file = "Emissions_Plot4.png") <file_sep>## -- These commands create a plot of total PM2.5 emissions from vehicles in Baltimore ## -- Create subseted data frame of the values (i.e., vehicles) > vehicle <- grepl("vehicle", SCC$SCC.Level.Two, ignore.case = TRUE) ## find vehicle emissions in the SCC > SCCVehicle <- SCC[vehicle,]$SCC ## subset out id numbers from SCC > NEIVehicle <- NEI[NEI$SCC %in% SCCVehicle,] ## subset vehicles from NEI data ## -- Subset out emissions from Baltimore and sum to find total emissions > NEIVehBalt <- subset(NEIVehicle, fips == "24510") > totalBaltVeh <- aggregate(Emissions ~ year, NEIVehBalt, sum) ## -- Create a plot > plot(totalBaltVeh, type = "l", ylab = "Total PM2.5 Vehicle Pollution", main = "Baltimore PM2.5 Vehicle Pollution") > dev.copy(png, file = "Emissions_Plot5.png") > dev.off() <file_sep>## -- The commands produce a plot of PM2.5 in Baltimore sufficient to show that from 1999 to 2008 ## -- total emissions declined, with an uptick in 2005. > NEIBalt <- subset(NEI, fips == "24510") ## subset to relevant fips > BaltTotal <- aggregate(Emissions ~ year, NEIBalt, sum) ## sum up emissions by year > plot(BaltTotal, type = "l", ylab = "Total PM2.5 Emissions, Baltimore") ## simple plot of total emissions by year > dev.copy(png, file = "Emissions_Plot2.png") <file_sep># Expl-Data-Analysis-Assignment-2 <file_sep>## -- These commands produce plots of PM2.5 Emissions from vehicles in LA County and Baltimore. ## -- Create subseted data frame of the values (i.e., vehicles) > vehicle <- grepl("vehicle", SCC$SCC.Level.Two, ignore.case = TRUE) ## id vehicle emissions from SCC > SCCVehicle <- SCC[vehicle,]$SCC ## subset out id numbers from SCC > NEIVehicle <- NEI[NEI$SCC %in% SCCVehicle,] ## subset vehicles from NEI data ## -- Subset out emissions from LA County and Baltimore > NEIVehBaltLA <- subset(NEIVehicle, fips == "24510" | fips == "06037") ## -- Create Plot > vehicleplot <- ggplot(aes(x = year, y = Emissions), data = NEIVehBaltLA) > vehicleplot + geom_bar(stat = "identity", fill = "purple") + facet_grid(.~fips) + labs(x = "Year", y = "TotalPM2.5 Emission per year", title = "PM2.5 Emissions, LA county and Baltimore") > dev.copy(png, file = "Emissions_Plot6.png") <file_sep>## The following commands produce a plot of total emissions against year sufficient to determine that ## total emissions of PM 2.5 have decreased from 1999 to 2008 ## -- read in data per website instructions -- ## > NEI <- readRDS("summarySCC_PM25.rds") > SCC <- readRDS("Source_Classification_Code.rds") ## -- create a new data frame > total <- aggregate(Emissions ~ year, NEI, sum) > total$year <- as.numeric(total$year) ## --- create plot and copy device to a png > plot(total, type = "l", ylab = "Total Emissions of PM2.5") > dev.copy(png, file = "Emissions_Plot1.png") > dev.off() <file_sep>## -- These commands use ggplots to produce a barplot segmented by source type from the NEI data. > p <- ggplot(aes(x = year, y = Emissions, fill = type), data = NEIBalt) > p + geom_bar(stat = "identity") + facet_grid(.~type) + labs(x = "year", y = "PM2.5 Emissions", title = "PM2.5 Emissions, Baltimore, by Source") > dev.copy(png, file = "Emissions_Plot3.png")
eb1d92f237da3bc2d100ce042fc87970fab2ce78
[ "Markdown", "R" ]
7
R
Rossastoria/Expl-Data-Analysis-Assignment-2
8fb0e819260f3377bca809a955adf734c64026e0
2c7256418782415a89206fc376a1dea2cd926d8d
refs/heads/master
<repo_name>lijieyiin/movie<file_sep>/vue-config.js const webpack = require('webpack'); const path = require('path'); module.exports = { devServer: { host: "0.0.0.0", //ip port: 8080, //端口 // proxy:{//代理方式 // "/api":{ // target:'http://192.168.31.20:3000/', // changeOrigin:true, // wx:true, // pathRewrite:{ // "^/api":'' // } // } // } }, outputdir: '../nodeServer/dist', //构建输出目录 -- 使得打包后自动将dist文件夹复制到 nodeServer chainWebpack: (config) => { config.resolve.alias .set('@', path.resolve(__dirname, './src')) .set('mui', path.resolve(__dirname, './src/assets/mui/js/mui.js')) }, // 配置mui插件 chainWebpack: config => { config.resolve.alias .set("@", path.resolve(__dirname, "./src")) .set("mui", path.resolve(__dirname, "./src/assets/mui/js/mui.js")); }, configureWebpack: { // 增加一个plugins plugins: [ new webpack.ProvidePlugin({ mui: "mui", "window.mui": "mui" }) ] }, lintOnSave: false //取消 eslint 验证 }
8aa8e52d18a619ad061cd979e3bf6cb42861317b
[ "JavaScript" ]
1
JavaScript
lijieyiin/movie
2f9e8cac58ab51e0e5c67e264cbe469bbc534fea
7f591fb086a0d5d9521abc7f7e05b6d403c8414f
refs/heads/master
<repo_name>nettabr/Basic_Calculator_AndroidApp<file_sep>/MainActivity2.java package com.example.textview; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.print.PrinterId; import android.view.View; import android.widget.Button; public class MainActivity2 extends AppCompatActivity { private Button emailBtn; private Button shareBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); Button emailBtn = findViewById(R.id.emailBtn); Button shareBtn = findViewById(R.id.shareBtn); emailBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sendMail(); } }); shareBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent share = new Intent(Intent.ACTION_SEND); share.setType("text/plain"); String shareBody = "Share us"; String shareSubject = "Thanks for the support"; share.putExtra(Intent.EXTRA_SUBJECT,shareSubject); share.putExtra(Intent.EXTRA_TEXT,shareBody); startActivity(Intent.createChooser(share,"Share using")); } }); } public void sendMail(){ Intent intent = new Intent(this, EMailActivity.class); startActivity(intent); } }<file_sep>/README.md # Basic_Calculator_AndroidApp Basic_Calculator_AndroidApp
fa7489d41e415fa368c9149603c2ec5ede012f93
[ "Markdown", "Java" ]
2
Java
nettabr/Basic_Calculator_AndroidApp
2fb46e973ae022b4a7aaea19105f85abc6b41464
35271995b897e94f0b721687205c38c437c28b28
refs/heads/master
<file_sep>import numpy as np def rmse(y_true, y_pred): loss = np.sqrt(np.mean((y_true - y_pred)**2, axis=0)) return loss def rmse_XGBoost(y_pred, y_true): y_true = y_true.get_label() y_pred = y_pred return 'rmse', rmse(y_true, y_pred) def mae(y_true, y_pred): loss = np.mean(np.abs(y_true - y_pred), axis=0) return loss def create_feature_map(features, feature_map_path): outfile = open(feature_map_path, 'w') for i, feat in enumerate(features): outfile.write('{0}\t{1}\tq\n'.format(i, feat)) outfile.close() <file_sep>numpy pandas seaborn >= 0.10 matplotlib.pyplot xgboost operator scikit-learn<file_sep># PredictSales The goal of this project is to predict sales for shops <file_sep>import pandas as pd def merge_data(data_sales, data_store, remove_outliers=False): data_merged = data_sales.merge(data_store, left_on='Store', right_on='Store', how='left') if remove_outliers: # One store with a huge number of customers data_merged = data_merged[data_merged['Customers'] <= 6000] # Two stores with competition before 1980 data_merged = data_merged[(data_merged['CompetitionOpenSinceYear'] >= 1980) | (data_merged['CompetitionOpenSinceYear'] == 0.)] # Two stores with competition distance >= 5000 data_merged = data_merged[data_merged['CompetitionDistance'] <= 5000] return data_merged def preprocessing(data_sales, data_store, remove_outliers=False): # features features = [] # convert date to datetime data_sales['Date'] = pd.to_datetime(data_sales['Date'], format='%Y-%m-%d') # assume store open, if not provided data_sales.fillna(1, inplace=True) # consider only open stores for training data_sales = data_sales[data_sales['Open'] != 0] # merge sales and store data = merge_data(data_sales, data_store, remove_outliers=remove_outliers) # remove NaNs data['CompetitionDistance'].fillna(data['CompetitionDistance'].median(), inplace=True) data.fillna(0, inplace=True) data.loc[data.Open.isnull(), 'Open'] = 1 # Use some properties directly features.extend(['Store', 'CompetitionDistance', 'Promo', 'Promo2', 'SchoolHoliday']) # Label encode some features features.extend(['StoreType', 'Assortment', 'StateHoliday']) data['StoreType'] = data['StoreType'].map({'a': 0, 'b': 3, 'c': 2, 'd': 1}) data['Assortment'] = data['Assortment'].map({'a': 0, 'b': 2, 'c': 1}) data['StateHoliday'] = data['StateHoliday'].map({0: 0, '0': 0, 'a': 1, 'b': 1, 'c': 1}) features.extend(['DayOfWeek', 'Month', 'Day', 'Year', 'WeekOfYear']) data['Year'] = data.Date.dt.year data['Month'] = data.Date.dt.month data['Day'] = data.Date.dt.day data['WeekOfYear'] = data.Date.dt.weekofyear # Calculate time competition open time in months features.append('CompetitionOpen') data['CompetitionOpen'] = 12 * (data.Year - data.CompetitionOpenSinceYear) + \ (data.Month - data.CompetitionOpenSinceMonth) # Promo open time in months features.append('PromoOpen') data['PromoOpen'] = 12 * (data.Year - data.Promo2SinceYear) + (data.WeekOfYear - data.Promo2SinceWeek) / 4.0 data['PromoOpen'] = data.PromoOpen.apply(lambda x: x if x > 0 else 0) data.loc[data.Promo2SinceYear == 0, 'PromoOpen'] = 0 return data, features
1c5fe8aab452f1a9c40938f4cc65a65ade011bb3
[ "Markdown", "Python", "Text" ]
4
Python
BWallyn/PredictSales
9921acca876847c07d53792ec4bb781047a6cabe
2c56f56a37a5b3e90ee077718625b9d148d522b7
refs/heads/master
<file_sep>package com.mesutemre.susa.config; import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DriverManagerDataSource; @Configuration public class SpringUsingStandAloneDataSourceConfig { @Bean public DataSource dataSource(){ DriverManagerDataSource ds = new DriverManagerDataSource(); String url = "jdbc:mysql://localhost:3306/kutuphanesistemi?useUnicode=yes&characterEncoding=UTF-8"; String username = "root"; String password = "<PASSWORD>"; ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setUrl(url); ds.setUsername(username); ds.setPassword(<PASSWORD>); return ds; } } <file_sep>package com.mesutemre.susa.main; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import com.mesutemre.susa.config.SpringUsingStandAloneDataSourceConfig; import com.mesutemre.susa.service.MessageService; @Configuration @Import({SpringUsingStandAloneDataSourceConfig.class}) @ComponentScan(basePackages = "com.mesutemre.susa") public class SpringUsingStandaloneAppMain { @Autowired private MessageService messageService; public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(SpringUsingStandaloneAppMain.class); SpringUsingStandaloneAppMain app = context.getBean(SpringUsingStandaloneAppMain.class); app.start(); } private void start() { messageService.writeMessage("<NAME>..."); } }
d6ae9c1b7ea184952109bdd1e6cc48a78b6736e6
[ "Java" ]
2
Java
mesudemre/SpringStandaloneApplication
8c27c36cd322ac261c056f671b178cbcc3d99d2d
bc3441b3925efcd18a0591bbe17a6e0363b8f658
refs/heads/master
<repo_name>ohasselblad/language-test<file_sep>/src/Account.cpp /* * Account.cpp * * Description: * * * Created by <NAME> on 9/29/11. * */ /* * * If we're going to implement the spaced repetition method in our program, * perhaps we need to make it work through this Account class since it * remembers things between sessions. * */ #include "Account.h" QuizSummary::QuizSummary() :subject(""), testDate(0), score(0.0) { } Account::Account() :name("Geronimo"), results(0), score(100.0), \ datePassed(""), numOfTimesAttempted(0), verbose(false) { } void Account::exportAccount(string name) { } void Account::loadAccount(void) { } string Account::getName() const { return name; } void Account::setVerbose(bool newVal) { verbose = newVal; } void Account::setVerbose() { verbose = !verbose; } bool Account::getVerbose() const { return verbose; } void Account::establishAccount() { char *youAre, *yesOrNo; bool yn = false; rl_bind_key('\t',rl_insert); // disable auto-complete do { cout << endl \ << "Current user is " << name << ".\n" << endl \ << "What is your account name? " \ << "Enter 'guest' to start a temporary guest account" << endl; do { youAre = readline(">> "); } while ( !strcmp(youAre, "\0") ); if ( !strcmp(youAre, "guest") ) { cout << endl \ << "You are picking a guest account. Your data will only be" \ << " active during the current session. Nothing will be saved." \ << " Do you want to continue as a guest?" << endl; } else { cout << endl \ << "You set your account name to '" << youAre \ << "'. Do you want to keep that? (yes or no)" << endl; } yesOrNo = readline(">> "); if ((yesOrNo[0] == 'y' || yesOrNo[0] == 'Y') && not doesAcctExist(youAre)) yn = true; } while (yn == false); setName(youAre); free(youAre); free(yesOrNo); } bool Account::doesAcctExist(string acctName) { /* search xml files to see if one has a name already entered */ return false; // change this obviously } void Account::setName(char * newName) { name = newName; } string Account::whoAreYou() { string acctName; cout << "What is your account name?" << endl; return acctName; } // EOF <file_sep>/include/Numbers.h /* * Numbers.h * * * Created by <NAME> on 11/15/11. * */ #ifndef NUMBERS_H #define NUMBERS_H #include <cmath> #include <cstdlib> #include <ctime> // time(NULL) #include <iomanip> // setw() #include <iostream> #include <limits> // numeric_limits #include <string> #include <vector> #include <boost/random/mersenne_twister.hpp> // mt19937_64 #include <boost/random/uniform_int_distribution.hpp> #include <boost/algorithm/string/trim.hpp> #include <readline/readline.h> #include "functions.h" #include "wordCompare.h" #include "ltest_typedefs.h" #include "Account.h" using std::cerr; using std::cin; using std::cout; using std::endl; using std::numeric_limits; using std::setw; using std::string; extern bool exitToMain; /* rethink the naming of this class */ class Number { usInt numOfItems, numCorrect; long xmin, xmax, currentNum; string numWord; /* private member functions */ void setCustomOptions(); bool inputsAreNotOkay(); string numConst(const long); string auxConst(const usInt); long randNum(boost::random::mt19937_64 &); public: Number(); void setNumber(usInt, long, long); usInt getnumOfItems() const { return numOfItems; } usInt getNumCorrect() const { return numCorrect; } long getxmin() const { return xmin; } long getxmax() const { return xmax; } long getCurrNum() const { return currentNum; } string getNumWord() const { return numWord; } void printNumber(); void getNewNumber(boost::random::mt19937_64 &); void loadOptions(); void incrNumCorrect(); }; usInt getPower(const long); // not in use template <class U, class V> U reduce(U num1, V num2) { return (num1/num2) * num2; } int numbers(Account &); #endif // NUMBERS_H // EOF <file_sep>/src/progPrefs.cpp /* * progPrefs.cpp * * Description: * Functions to control the environment variables of ltest * * * Created by <NAME> on 10/6/11. * */ #include "progPrefs.h" string progPrefs::help(char * progName) { stringstream help; help << "Commandline language learner. Version 1.0 Beta\n" << "Kandy Software. Always wary.\n\n" << "usage:\n" << " " << progName << " [options]\n" << "\n" << "options:\n" << " -h print out this help menu\n" << endl; return help.str(); } void progPrefs::cmdLineInput(int argc, char **argv) { int c; while ( (c = getopt(argc, argv, ":hdl")) != -1) { switch (c) { case 'h': // Print usage info then exit cout << help(argv[0]); exit(0); case '?': cerr << "Option '-" << static_cast<char> (optopt) << "' is not valid." << endl; break; default: cerr << "Invalid commandline options." << endl; help(argv[0]); exit(0); break; } } } usInt progPrefs::changeProgOptions(Account & acct) { usInt option = 0; while (option != 3) { cout << "The following variables are set: \n" \ << "1: verbose = " << (acct.getVerbose()?"on":"off") << '\n' \ << "2: User = " << acct.getName() << '\n' \ << "3: return to main screen.\n" \ << "\n" \ << "Enter a number to change its value." << endl; option = ltest::readint<usInt>(">> "); switch (option) { case 1: acct.setVerbose(); break; case 2: acct.establishAccount(); break; case 3: break; default: cerr << option << " is not a valid option." << endl; break; } } return 0; } // EOF <file_sep>/src/flcrd_quiz.cpp /* * flcrd_quiz.cpp * * Description: * * * Created by <NAME> on 10/19/11. * */ #include "flcrd_quiz.h" int flcrd_quiz(Account & acct) { cout << "Beginning Flashcard Quiz." << endl; chr::system_clock::time_point timeStart; boost::chrono::duration<float> timeDiff; bool isWrong = true, disableHintMsg = false; vector<Flashcard> cards; string response, prompt; SmartPicker * picker; Hint myhint(" ", acct.getVerbose()); /* Choose flashcard set, then input */ cards[0].input(cards,listDicts()); { int index = 1; cout << "Pick how you're quizzed:\n" << " 1. LeastPicked\n" << " 2. Adaptive\n" << " 3. LeastCorrect\n" << " 4. Walk Through\n" << endl; index = ltest::readint<usInt>(">> "); switch (index) { case 1: cout << "You picked LeastPicked" << endl; picker = new LeastPicked; break; case 2: cout << "You picked Adaptive" << endl; picker = new Adaptive(cards.size()); break; case 3: cout << "You picked LeastCorrect" << endl; picker = new LeastCorrect; break; case 4: cout << "You picked WalkThrough" << endl; picker = new WalkThrough; break; default: cout << "Your choice isn't valid, so you're getting LeastPicked" << endl; picker = new LeastPicked; break; } } do { picker->getNextIndex(cards); // could we conditionally set this instead? myhint.setKey(cards[picker->getCurrentIndex()].getWord('B',ltest::randIndex(cards[picker->getCurrentIndex()].size('B')))); string sideAword = cards[picker->getCurrentIndex()].getWord('A',ltest::randIndex(cards[picker->getCurrentIndex()].size('A'))); usInt numOfTries = 0; prompt = sideAword; while (isWrong) { numOfTries++; timeStart = chr::system_clock::now(); response = ltest::readstring(prompt + ": "); timeDiff = chr::system_clock::now() - timeStart; /* options processing */ if ( response[0] == '-' ) /* if hint */ { if ( response[1] == 's' ) break; /* skip word */ else /* deal with response */ cout << myhint.handle(response, disableHintMsg); } else if ( response == "exit" ) { exitToMain = true; break; } else /* no hint, check response */ { /* TODO: if noun, and beginning with el or la (or los or las), and user * gets the article correct, do not require them to keep typing that... */ isWrong = ltest::isInvalidAnswer(response,cards[picker->getCurrentIndex()].getSideB()); if (isWrong) { if (acct.getVerbose()) { cout << "You are " \ << wordCompare::lcsPercent(cards[picker->getCurrentIndex()].getWord('B',0),response) \ << "%% correct.\n" \ << wordCompare::correctness(response,cards[picker->getCurrentIndex()].getWord('B',0)) << endl; } if ( (numOfTries % 5) == 0 && !disableHintMsg) { cout << myhint.help(sideAword.size()) << '\n'; prompt = sideAword; } else prompt = ltest::printWhitespace(sideAword.size()-1); } else if (acct.getVerbose()) cout << "Right!" << endl; } } /* finish this card */ cards[picker->getCurrentIndex()].recordPerformance(numOfTries,isWrong,timeDiff.count()); isWrong = true; // cout << response << " has " << ltest::isAccented(response) << " accents" << endl; } while (!exitToMain); testResults(cards,acct.getVerbose()); delete picker; return 0; } // EOF <file_sep>/src/Numbers.cpp /* * numbers.cpp * * Description: * Quiz of integer numbers. This program constructs numbers into a specified * language, quizzes the user, shows the correctness, and more. Part of * LanguageTest.cpp * * Created by <NAME> on 11/8/11. * */ #include "Numbers.h" /* Load these from a file eventually? */ string zeroTo29[] = {"cero", "uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez", "once", "doce", "trece", "catorce", "quince", "dieciséis", "diecisiete", "dieciocho", "diecinueve", "veinte", "veintiuno", "veintidós", "veintitrés", "veinticuatro", "veinticinco", "veintiséis", "veintisiete", "veintiocho", "veintinueve"}; string tens[] = {"cero", "diez", "veinte", "treinta", "cuarenta", "cincuenta", "sesenta", "setenta", "ochenta", "noventa"}; string hundreds[] = {"cero", "ciento", "doscientos", "trescientos", "cuatrocientos", "quinientos", "seiscientos", "setecientos", "ochocientos", "novecientos"}; //string powersOfTen[] = {"uno", "diez", "cien", "mil", "diez mil", // "cien mil", "millón", "diez millón", "cien millón", // "mil millones", "diez mil millones", // "cien mil millones", "billón", "diez billón"}; string powersOfThousand[] = {"", "mil", "millón", "mil millones", "billón", "mil billones", "trillón", "mil trillones"}; Number::Number() :numOfItems(10), numCorrect(0), \ xmin(0), xmax(1000), currentNum(0), numWord("cero") { } void Number::printNumber() { cout << "Number contains: " << endl; cout << "\t numOfItems = " << numOfItems << endl; cout << "\t xmin = " << xmin << endl; cout << "\t xmax = " << xmax << endl; cout << "\t currentNum = " << currentNum << endl; } void Number::setNumber(usInt newnumOfItems, long newxmin, long newxmax) { numOfItems = newnumOfItems; xmin = newxmin; xmax = newxmax; } void Number::getNewNumber(boost::random::mt19937_64 & gen) { currentNum = randNum(gen); numWord = numConst(currentNum); } long Number::randNum(boost::random::mt19937_64 &gn) { #ifdef DEBUG cout << "Entered randNum" << endl; #endif // DEBUG boost::random::uniform_int_distribution<long> dist(xmin, xmax); #ifdef DEBUG long randomNum = dist(gn); cout << "dist(gn) = " << randomNum << endl; return randomNum; #else return dist(gn); #endif // DEBUG } void Number::incrNumCorrect() { numCorrect++; } bool Number::inputsAreNotOkay() { return !((xmax > xmin) && (numOfItems > 0)); } void Number::setCustomOptions() { bool changeOptions = true; usInt numItems = 10; long xmn = 0, xmx = 10; char * temp = NULL; do { temp = readline("How many items do you want to be quizzed over?\n>> "); numItems = atoi(temp); cout << "Enter a number range: xmin <= x <= xmax\n" \ << "(enter 'max' for the largest value possible,\n" \ << " and 'min' for the smallest value possible.)" << endl; temp = readline("min = "); if (!strcmp(temp,"min")) xmn = numeric_limits<long>::min() ; else xmn = atol(temp); temp = readline("max = "); if (!strcmp(temp,"max")) xmx = numeric_limits<long>::max(); else xmx = atol(temp); cout << "You chose " << numItems << " numbers between " \ << ltest::commaAdder(ltest::numToStr(labs(xmn)),ltest::sgn(xmn)) \ << " and " \ << ltest::commaAdder(ltest::numToStr(labs(xmx)),ltest::sgn(xmx)) \ << "." << endl; temp = readline("Keep these options? (y for yes, r to reset)? "); if (temp[0] == 'y') changeOptions = false; else changeOptions = true; } while (this->inputsAreNotOkay() || changeOptions); this->setNumber(numItems,xmn,xmx); free(temp); } void Number::loadOptions() { int option; char * opt = NULL; cout << "Pick a specific quiz or make your own.\n" \ << "\t1: 0 to 10 (20 times)\n" \ << "\t2: 0 to 100 (30 times)\n" \ << "\t3: 0 to 1000 (30 times)\n" \ << "\t4: -1000 to 1000 (20 times)\n" \ << "\t5: -1E6 to 1E6 (10 times)\n" \ << "\t6: -1E8 to 1E8 (10 times)\n" \ << "\t7: -1E13 to 1E13 (5 times)\n" \ << "\t8: custom\n" \ << "\t9: exit to main screen" << endl; opt = readline(">> "); option = atoi(opt); switch (option) { case 1: this->setNumber(20,0,10); break; case 2: this->setNumber(30,0,100); break; case 3: this->setNumber(30,0,1000); break; case 4: this->setNumber(20,-1000,1000); break; case 5: this->setNumber(10,-100000,100000); break; case 6: this->setNumber(10,-100000000,100000000); break; case 7: this->setNumber(5,-10000000000000,10000000000000); break; case 8: this->setCustomOptions(); break; case 9: exitToMain = true; break; default: this->setNumber(20,0,10); break; } #ifdef DEBUG this->printNumber(); #endif // DEBUG free(opt); } /* Construct numbers of length -LONG_MAX to LONG_MAX in words */ string Number::numConst(const long num) { vector<usInt> nums = ltest::numDecomp(num); string wordString; if (num < -1) wordString = "negativos "; else if (num == -1) wordString = "negativos "; for (int ii = nums.size()-1; ii >= 0; ii--) { wordString += (auxConst(nums.at(ii)) + " " + powersOfThousand[ii]); if (ii > 0) wordString += " "; } boost::algorithm::trim_right(wordString); return wordString; } /* Construct a number between zero and 999 in words */ string Number::auxConst(const usInt var) { string wrdStr; usInt tempVar = var; if ( tempVar >= 1000 ) { cerr << "Error: out of range." << endl; exit(0); } else if ( tempVar < 1000 && tempVar >= 100 ) { wrdStr += hundreds[tempVar / 100]; tempVar %= 100; } if ( tempVar < 100 && tempVar >= 30 ) { ltest::addSpace(wrdStr); wrdStr += tens[tempVar / 10]; if ((var % 10) != 0) wrdStr += (" y " + zeroTo29[tempVar % 10]); } else if ( tempVar < 30 && !((tempVar == 0) xor (var == 0)) ) { ltest::addSpace(wrdStr); wrdStr += zeroTo29[tempVar]; } return wrdStr; } usInt getPower(const long rawInt) { long temp = rawInt; unsigned short mag = 0; cout << setw(9) << "temp" << setw(3) << " mag\n" \ << setw(9) << temp << " " << setw(3) << mag << endl; while (temp >= 10) { mag++; temp /= 10; cout << setw(9) << temp << " " << setw(3) << mag << endl; } return mag; } int numbers(Account & acct) { boost::random::mt19937_64 gen; gen.seed(time(0)); Number nm; bool isCorrect = false; string response; nm.loadOptions(); for (usInt ii = 0; ii < nm.getnumOfItems() && !exitToMain; ii++) { nm.getNewNumber(gen); cout << "What is " << ltest::commaAdder(ltest::numToStr(labs(nm.getCurrNum())), \ ltest::sgn(nm.getCurrNum())) \ << " in Spanish?" << endl; /* TODO: change response to char * to address memory leak? */ response = readline(">> "); isCorrect = (response == nm.getNumWord()); if (ltest::exitProg(response.c_str(),exitToMain)) break; else if ( isCorrect ) { if (acct.getVerbose()) cout << "You're right!" << endl; nm.incrNumCorrect(); } else // if wrong { cout << "You're wrong! The correct response is: '" \ << nm.getNumWord() << "'" << endl; /* Shows first error -- doesn't work with accented words */ cout << response << '\n' \ << ltest::printWhitespace(wordCompare::findFirstError(nm.getNumWord(),response)-1) \ << "^\n" \ << nm.getNumWord() << endl; cout.setf(std::ios::fixed); cout.precision(0); /* Calculates word differences */ cout << "You are off by: " \ << wordCompare::levenshtein(nm.getNumWord(), response)-1 \ << " letters. And your response is " \ << wordCompare::lcsPercent(nm.getNumWord(),response) \ << "% correct." << endl; } isCorrect = false; } cout << "You got " << nm.getNumCorrect() << " correct out of " \ << nm.getnumOfItems() << " (" \ << ltest::frac(nm.getNumCorrect(),nm.getnumOfItems()) * 100.0 \ << "%)." << endl; return 0; } // EOF <file_sep>/src/wordCompare.cpp /* * wordCompare.cpp * * Description: * * * Created by <NAME> on Oct. 2011. * */ #include "wordCompare.h" string wordCompare::correctness(string answer, string key) { stringstream response; int rating = levenshtein(answer,key); response << "Your word is " << levRater(rating) << endl; return response.str(); } usInt wordCompare::findFirstError(string ans, string cmp) { usInt errorPos = 0; for (usInt ii = 0; ii < min(ans.size(),cmp.size()); ii++) { if (ans.at(ii) == cmp.at(ii)) errorPos++; else break; } return errorPos; } string wordCompare::levRater(usInt value) { string howGood; if (value == 1) howGood = "very close!"; else if (value == 2) howGood = "a little off!"; else if (value == 3) howGood = "off by a few letters!"; else if (value >= 4 && value < 8) howGood = "not so great!"; else howGood = "terrible, honestly."; return howGood; } // Levenshtein Distance Edit calculator for two strings /* TODO: move to valarray instead of m[][] ? */ usInt wordCompare::levenshtein(string str1, string str2) { if ( str1.empty() ^ str2.empty() ) return max(str1.length(),str2.length()); else if ( str1.empty() && str2.empty() ) return 0; else { usInt cost; const usInt lenOne = str1.length(), lenTwo = str2.length(); usInt m[lenOne][lenTwo]; for (usInt ii = 0; ii < lenOne; ii++) m[ii][0] = ii+1; for (usInt jj = 0; jj < lenTwo; jj++) m[0][jj] = jj+1; for (usInt ii = 1; ii < lenOne; ii++) { for (usInt jj = 1; jj < lenTwo; jj++) { if (str1[ii] == str2[jj]) cost = 0; else cost = 1; m[ii][jj] = min(m[ii-1][jj] + 1, \ min(m[ii][jj-1] + 1, \ m[ii-1][jj-1] + cost) \ ); } } return m[lenOne-1][lenTwo-1]; } } // Returns a string of the unique letters in string str string wordCompare::unique(string str) { string temp, uniq; uniq.push_back(str.at(0)); cout << "uniq = '" << uniq << "'" << endl; for (usInt ii = 1; ii < str.size(); ii++) { if (uniq.find(str.at(ii)) == string::npos) // if not found in uniq, add it uniq.push_back(str.at(ii)); } return uniq; } float wordCompare::lcsPercent(string answer, string response) { const usInt m = answer.size(); const usInt n = response.size(); float percentCorrect; usInt c[m+1][n+1]; for (usInt ii = 1; ii <= m; ii++) c[ii][0] = 0; for (usInt jj = 0; jj <= n; jj++) c[0][jj] = 0; for (usInt ii = 1; ii <= m; ii++) { for (usInt jj = 1; jj <= n; jj++) { if (answer.at(ii-1) == response.at(jj-1)) c[ii][jj] = c[ii-1][jj-1] + 1; else if (c[ii-1][jj] >= c[ii][jj-1]) c[ii][jj] = c[ii-1][jj]; else c[ii][jj] = c[ii][jj-1]; } } percentCorrect = ltest::frac(c[m][n],m) * 100.0; // percentCorrect = static_cast<float> (c[m][n]) / \ // static_cast<float> (m) * 100; return percentCorrect; } <file_sep>/src/summaryMain.cpp //these all need to be broken down into methods so that the main method fits into a page or so. int main(int argc, char **argv) { /***** Initialize Variables *****/ /***** Take optional input from command line *****/ /***** Input Dictionary *****/ /***** Language Quiz *****/ /***** Summary of Results ******/ /***** Close program *****/ cout << goodbye() << endl; return 0; } <file_sep>/src/Hint.cpp /* * Hint.cpp * * Description: * * * Created by KEPS on 2/10/11. * */ #include "Hint.h" /* TODO: What to do about the verbose variables in Hint.cpp and Hint.h? */ Hint::Hint(string answerKey, bool selectVerbose) :key(answerKey), hintNum(0), verbose(selectVerbose), hint(key.size(),' ') { } // Default constructor Hint::Hint() :key(" "), hintNum(0), verbose(false), hint(" ") { } void Hint::setKey(string answerKey) { key = answerKey; hintNum = 0; hint = ""; while (hint.size() <= key.size()) hint += " "; } void Hint::addLetter(usInt numLetters) { // Add letters if any ' ' are found in substring numLetters += numOfSpaces(string(key,hintNum,string::npos),numLetters); if (isAccented(string(key,hintNum,numLetters+1))) numLetters++; // not sure how to do this if ( hintNum < key.size() ) { if (hintNum + numLetters > key.size()) // Limit num of letters to key size numLetters = key.size() - hintNum; hint.replace(hintNum, numLetters, string(key,hintNum,numLetters)); hintNum += numLetters; } if (hintNum == key.size()) hint += " <-"; } int Hint::numOfSpaces(string str, int numLetters) { usInt isLetter = 0, search = numLetters; for (short ii = 0; ii < search && search <= str.size(); ii++) { if (str.at(ii) != ' ') isLetter++; else search++; } return search - numLetters; } bool Hint::isAccented(string str) { vector<string> set{"á", "é", "í", "ó", "ñ", "ä", "ö", "ü", "å", "ß"}; vector<string>::const_iterator it; bool accent = false; for (it = set.begin(); it != set.end(); it++) { if (str.find(*it) != string::npos) { accent = true; break; } } return accent; } void Hint::addLetter() { if ( hintNum <= key.size() ) { hint.replace(hintNum,1,string(1,key[hintNum])); hintNum++; } if (key.at(hintNum) == ' ') addLetter(); if (hintNum == key.size()) hint += " <-"; } void Hint::fillLetterPlaces() { for (usInt i = hintNum; i < key.size(); i++) { if (key.at(i) != ' ') hint.replace(i,1,"-"); } } void Hint::answer(void) { hint = key + " <-"; } void Hint::disableHints(void) { } string Hint::example(void) { string hint = "an example of usage"; return hint; } string Hint::help(size_t num) { stringstream hint; string ws = ltest::printWhitespace(num); hint << ws << '\a' << endl; hint << ws << "Want a letter? Type '-l'." << endl; hint << ws << "Want more than one letter? Type '-l#', where # = a number 1 - 9." << endl; hint << ws << "Want the answer? Type '-a'." << endl; hint << ws << "Want the number of letters? Type '-n'." << endl; hint << ws << "Want to skip this word? Type '-s'." << endl; hint << ws << "Want help? Type '-h'." << endl; hint << ws << "Want out of here? Type exit." << endl; hint << ws << "Want to turn these messages off? Type '-d' to disable." << endl; return hint.str(); } string Hint::handle(string hintType, bool & disableHintMsg) { stringstream out; switch (hintType[1]) { case 'l': if (hintType[2] == '\0') addLetter(1); else if (atoi(&hintType[2]) < 10 && atoi(&hintType[2]) > 0) addLetter(atoi(&hintType[2])); else addLetter(1); out << "-> " << hint << endl; break; case 'a': answer(); out << "-> " << hint << endl; break; case 'n': fillLetterPlaces(); out << "-> " << hint << endl; break; case 'h': out << help(); break; case 'd': disableHintMsg = !disableHintMsg; } return out.str(); } // skip word should be handled elsewhere... // if synonym hint is selected, create new Hint object with new key // and perform answer() on it. // string Hint::synonym() <file_sep>/include/listDicts.h /* * listfiles.h * * Description: Lists txt files in the specified directory. Similar to the * ls function in Linux * * * Created by <NAME> on 9/13/11. * */ #include <sys/types.h> #include <cstdlib> #include <dirent.h> // what is this used for -- is there a C++ equiv? #include <cerrno> #include <vector> #include <string> #include <iostream> #include <fstream> #include <iomanip> #include <cctype> #include <readline/readline.h> #include "functions.h" #include "ltest_typedefs.h" using std::string; using std::vector; using std::cin; using std::cout; using std::cerr; using std::endl; using std::ios; using std::ifstream; using std::setw; int getTxtFiles(string, vector<string> &); //void listDicts(char[]); string listDicts(); unsigned short numberOfWords(string); <file_sep>/src/Flashcard.cpp /* * Flashcard.cpp * * Description: * * * Created by <NAME> on 9/19/11. * */ #include "Flashcard.h" Flashcard::Flashcard() :sideA(0), sideB(0), data(), weight(0.0) { } void Flashcard::toScreen() { cout << "sideA: " << endl; for (usInt jj = 0; jj < sideA.size() - 1; jj++) cout << sideA[jj] << ", "; cout << sideA[sideA.size()-1] << endl; cout << "sideB: " << endl; for (usInt kk = 0; kk < sideB.size() - 1; kk++) cout << sideB[kk] << ", "; cout << sideB[sideB.size() - 1] << endl; } void Flashcard::recordPerformance(usInt numOfTries, bool isWrong, double responseTime) { data.incrNumAsked(); if (numOfTries == 1 && !isWrong) { data.incrNumCorrect(); data.incrAnsTime(responseTime); } } vector<string> Flashcard::getSideA(void) { return sideA; } string Flashcard::getWord(char side, usInt i) const { if (side == 'A') return sideA[i]; else return sideB[i]; } vector<string> Flashcard::getSideB(void) { return sideB; } usInt Flashcard::size(char side) { if (side == 'A') return sideA.size(); else return sideB.size(); } usInt Flashcard::size(char side, usInt ind) { if (side == 'A') return sideA[ind].size(); else return sideB[ind].size(); } void Flashcard::setWeight(usInt N) { weight = ltest::inverse(N); } void Flashcard::clearWS(void) { sideB.clear(); sideA.clear(); } /* TODO: Have a comment character -- ignore input after this character */ void Flashcard::input(vector<Flashcard> & ws, string inFile) { string temp1, temp2; size_t delimPos = string::npos; ifstream inputFile(inFile.c_str(),ifstream::in); // open file if possible Flashcard tempSet; usInt lineNum = 1, delimWidth = 1; string delimiters[] = {"\t"," "," "," "}; while ( !inputFile.is_open() ) // Get rid of this since listDicts guarantees files? { cout << "File '" << inFile << "' does not exist as specified.\n" << "Enter another filename (or 'exit' to exit): "; cin >> inFile; if (ltest::exitProg(inFile.c_str(),cin.eof())) { cout << endl; exit(0); } else inputFile.open(inFile.c_str(),ifstream::in); cin.clear(); cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); } cout << "Inputting vocabulary from '" << inFile << "'" << endl; while ( !inputFile.eof() ) { getline(inputFile, temp1); /* TODO: Perhaps use * getline(inputFile,temp1,'\t'); \\ gets to tab * getline(inputFile,temp2,); \\ gets after tab * and do some error checking (what if no delimiter? Skip line) */ if (temp1.empty()) continue; // Skip empty lines else if (temp1.find('#') != string::npos) { cout << "Skipping the following line (comment): \n" << '\t' << temp1; continue; } // Find the delimiter for (int ii = 0; ii < 4 && delimPos == string::npos; ii++) { delimPos = temp1.find(delimiters[ii]); delimWidth = delimiters[ii].size(); } if (delimPos == string::npos) // If no delims found, go to next line { cout << "Skipping: '" << temp1 << "'" << endl; temp1.clear(); continue; } temp2 = temp1; // Make a copy of the line read in try // This may be redundant with previous if statement { temp1.erase(0,delimPos + delimWidth); temp2.erase(delimPos,temp2.size() - delimPos); } catch (std::out_of_range &e) { cerr << "Caught: '" << e.what() << "' on line " << lineNum << '\n' << "Type: " << typeid(e).name() << '\n' << "Not inputting '" << temp1 << "'" << endl; continue; } catch ( std::exception &e ) { cerr << "Caught: " << e.what() << '\n' << "Type: " << typeid(e).name() << endl; continue; } // Insert words into tempset insertWords(temp1, tempSet, 1); insertWords(temp2, tempSet, 2); // Put tempset into Flashcard vector ws.push_back(tempSet); // Clear variables for next time through tempSet.clearWS(); temp1.clear(); temp2.clear(); delimPos = string::npos; lineNum++; } cout << endl; inputFile.close(); } void Flashcard::insertWords(string words, Flashcard & tempset, int step) { size_t found; #ifdef DEBUG cout << "words are: '" << words << "'" << endl; #endif // DEBUG while ( words.find(",") != string::npos || \ words.find("|") != string::npos) { if (words.rfind("|") != string::npos) found = words.rfind("|"); else found = words.rfind(","); string tempWord = words.substr(found+1); #ifdef DEBUG cout << "New word: " << tempWord << endl; #endif // DEBUG switch (step) { case 1: #ifdef DEBUG cout << "case : " << step << endl; #endif // DEBUG tempset.sideA.push_back(tempWord); break; case 2: #ifdef DEBUG cout << "case : " << step << endl; #endif // DEBUG tempset.sideB.push_back(tempWord); break; default: break; // What should we do for this case? } words.erase(found); } #ifdef DEBUG cout << "New word: " << words << endl; #endif // DEBUG switch (step) // Otherwise catch non-comma case { case 1: #ifdef DEBUG cout << "case : " << step << endl; #endif // DEBUG tempset.sideA.push_back(words); break; case 2: #ifdef DEBUG cout << "case : " << step << endl; #endif // DEBUG tempset.sideB.push_back(words); break; default: break; // What should we do for this case? } } // EOF <file_sep>/src/SmartPicker.cpp /* * SmartPicker.cpp * * Description: Algorithms for flashcard selection. * Adaptive: probability of card selection based on past performance * through use of boost random library. * * Created by KEPS on 4/10/11. * */ #include "SmartPicker.h" /** SmartPicker members **/ // Default constructor SmartPicker::SmartPicker() :currentIndex(0) { } void SmartPicker::setCurrentIndex(usInt newValue) { currentIndex = newValue; } usInt SmartPicker::getCurrentIndex() const { return currentIndex; } void WalkThrough::getNextIndex(const vector<Flashcard> & cards) { setCurrentIndex((++currentIndex) % cards.size()); } /** LeastCorrect members **/ LeastCorrect::LeastCorrect() :leastCorrectIndices(0), currLowest(0) { } void LeastCorrect::getNextIndex(const vector<Flashcard> & cards) { leastCorrectIndex(cards); } void LeastCorrect::leastCorrectIndex(const vector<Flashcard> & cards) { static usInt lastIndex = numeric_limits<usInt>::max(); if (lastIndex != numeric_limits<usInt>::max()) if (cards[lastIndex].data.getNumCorrect() > currLowest) leastCorrectIndices.remove(lastIndex); if (leastCorrectIndices.empty()) repopulateIndices(cards); std::list<usInt>::const_iterator it = leastCorrectIndices.begin(); for (usInt jj = ltest::randIndex(leastCorrectIndices.size()); jj > 0; jj--) it++; if (*it == currentIndex) setCurrentIndex((*it + 1) % leastCorrectIndices.size()); else setCurrentIndex(*it); lastIndex = *it; } void LeastCorrect::repopulateIndices(const vector<Flashcard> & cards) { currLowest = findSmallest(cards); for (usInt i = 0; i < cards.size(); i++) { if (cards[i].data.getNumCorrect() == currLowest) leastCorrectIndices.push_back(i); } } void LeastCorrect::printIndices() { std::list<usInt>::const_iterator it = leastCorrectIndices.begin(); cout << *it; for (it++; it != leastCorrectIndices.end(); it++ ) cout << ", " << *it; cout << endl; } // Is there a way to generalize this to use numCorrect and numAsked for the same // function? usInt LeastCorrect::findSmallest(const vector<Flashcard> & deck) const { usInt currentLowest = deck[0].data.getNumCorrect(), temp; for (usInt ii = 1; ii < deck.size(); ii++) { temp = deck[ii].data.getNumCorrect(); if (temp < currentLowest) currentLowest = temp; } return currentLowest; } /** LeastPicked members **/ LeastPicked::LeastPicked() :leastPickedIndices(0), currLowest(0) { } void LeastPicked::getNextIndex(const vector<Flashcard> & cards) { // generate new index leastPickedIndex(cards); } void LeastPicked::leastPickedIndex(const vector<Flashcard> & cards) { static usInt lastIndex = numeric_limits<usInt>::max(); if (lastIndex != numeric_limits<usInt>::max()) if (cards[lastIndex].data.getNumAsked() > currLowest) leastPickedIndices.remove(lastIndex); if (leastPickedIndices.empty() ) repopulateIndices(cards); list<usInt>::const_iterator it = leastPickedIndices.begin(); for (int jj = ltest::randIndex(leastPickedIndices.size()); jj > 0; jj--) it++; if (*it == currentIndex) setCurrentIndex((*it + 1) % leastPickedIndices.size()); else setCurrentIndex(*it); lastIndex = *it; } void LeastPicked::repopulateIndices(const vector<Flashcard> & cards) { currLowest = findSmallest(cards); for (usInt i = 0; i < cards.size(); i++) { if (cards[i].data.getNumAsked() == currLowest) leastPickedIndices.push_back(i); } } void LeastPicked::printIndices() { list<usInt>::const_iterator it = leastPickedIndices.begin(); cout << *it; for (it++; it != leastPickedIndices.end(); it++ ) cout << ", " << *it; cout << endl; } // Is there a way to generalize this to use numCorrect and numAsked for the same // function? usInt LeastPicked::findSmallest(const vector<Flashcard> & deck) { usInt currentLowest = deck[0].data.getNumAsked(), temp; for (usInt ii = 1; ii < deck.size(); ii++) { temp = deck[ii].data.getNumAsked(); if (temp < currentLowest) setCurrentLowest(temp); } return currentLowest; } void LeastPicked::setCurrentLowest(usInt newCurrLow) { currLowest = newCurrLow; } /** Adaptive members **/ // Default Constructor Adaptive::Adaptive(int numEntries) :probability(0), gen(static_cast<usInt> (std::time(0))), \ levDistance(0.0), currAnsTime(0.0), isWrong(true) { probability.assign(numEntries,ltest::inverse(numEntries)); } // Desctructor Adaptive::~Adaptive() { probability.clear(); } double Adaptive::weight(bool wrong, double diff) { // weight for answering (non-hints) double weight = 0.0; if (wrong) weight = 0.24 * (1.0 - exp(-0.2 * (diff + levDistance))); else // if correct weight = -0.24 * exp(-0.2 * diff); return weight; } void Adaptive::updateProbsAdvanced(const double wgt, \ const vector<Flashcard> & cards) { // Updates probabilities double probUnasked = 0.0; const double pStar = probability[currentIndex]; int numOfNumAskedIs0 = 0; double alpha = fdim(1.0,pStar), beta; double gamma = 0.01, gamWeight = 1.0; // Experiment with different gammas for (usInt ii = 0; ii < probability.size(); ii++) { if (cards[ii].data.getNumAsked() == 0 && ii != currentIndex) { probUnasked += probability[ii]; numOfNumAskedIs0++; } } // Divide-by-zero guard if (numOfNumAskedIs0 < (probability.size() - 2)) { gamma = 0.01; beta = (gamma * probUnasked / wgt + pStar * alpha) / (alpha - probUnasked); gamWeight = 1.0; } else { beta = pStar; gamWeight = -wgt; gamma = beta; } for (usInt ii = 0; ii < probability.size(); ii++) { if ( ii == currentIndex ) probability[ii] *= fma(wgt,alpha,1.0); else if ( cards[ii].data.getNumAsked() != 0 ) probability[ii] *= fma(-wgt,beta,1.0); else probability[ii] *= fma(gamWeight,gamma,1.0); } } void Adaptive::updateProbsBasic(const double wgt) { const double pStar = probability[currentIndex]; const double alpha = fdim(1.0,pStar), beta = pStar; vector<double>::iterator it; const vector<double>::const_iterator itIndex = (probability.begin() + currentIndex); for (it = probability.begin(); it != probability.end(); it++) { if ( it == itIndex ) *it *= fma(wgt,alpha,1.0); else *it *= fma(-wgt,beta,1.0); } } void Adaptive::getNextIndex(const vector<Flashcard> & cards) { Adaptive::updateProbsAdvanced(weight(isWrong,currAnsTime), cards); static usInt lastIndex = numeric_limits<usInt>::max(); boost::random::discrete_distribution<> dist(probability); do { setCurrentIndex(dist(gen)); } while (currentIndex == lastIndex); lastIndex = currentIndex; } string Adaptive::probabilitySummary(vector<Flashcard> & cards) { stringstream ps; ps << "Summary:\n"; for (usInt ii = 0; ii < cards.size(); ii++) { ps << cards[ii].getWord('B',0) << '\t' << static_cast<int> (100 * probability[ii]) << endl; } return ps.str(); } void Adaptive::setLevDistance(string str1, string str2) { levDistance = static_cast<double> (wordCompare::levenshtein(str1,str2)); } // EOF <file_sep>/include/Account.h /* * Account.h * * Description: * * * Created by <NAME> on 9/29/11. * */ #ifndef ACCOUNT_H #define ACCOUNT_H #include <iostream> #include <string> #include <vector> #include <ctime> #include <readline/readline.h> #include "functions.h" #include "ltest_typedefs.h" using std::cin; using std::cout; using std::endl; using std::string; using std::vector; class QuizSummary { string subject; time_t testDate; float score; public: QuizSummary(); }; class Account { /* Class members */ string name; vector<QuizSummary> results; float score; string datePassed; int numOfTimesAttempted; bool verbose; void importViaXml(void); // Reminder void saveNewResultsToXML(void); // Reminder void setName(char *); public: Account(); void establishAccount(); bool doesAcctExist(string); void exportAccount(string); void loadAccount(); /* Access methods */ string getName() const; string whoAreYou(); void setVerbose(bool); void setVerbose(); bool getVerbose() const; // friend usInt changeProgOptions(Account &); }; #endif // ACCOUNT_H // EOF <file_sep>/src/testResults.cpp /* * testResults.cpp * * Description: Summarizes results of language test LanguageTest.cpp * * * Created by <NAME> on 9/15/11. * */ #include "testResults.h" void testResults(vector<Flashcard> cards, bool isVerbose) { usInt lengthLongestWord = 0; for (usInt i = 0; i < cards.size(); i++) if (ltest::stripParentheses(cards[i].getWord('B',0)).size() > lengthLongestWord) lengthLongestWord = cards[i].size('B',0); cout << endl; cout << endl; cout << setw(lengthLongestWord+13) << "Summary" << endl; for (usInt i = 0; i < lengthLongestWord + 9; i++) cout << "=-"; cout << endl; cout << setw(lengthLongestWord) << "Word" << setw(9) << "Score" << setw(13) << "Reaction" << endl; cout << setw(lengthLongestWord) << "----" << setw(9) << "-----" << setw(13) << "--------" << endl; cout.setf(ios::fixed); cout.precision(2); for (usInt i = 0; i < cards.size(); i++) { cout << setw(lengthLongestWord) \ << ltest::stripParentheses(cards[i].getWord('B',0)); if ( cards[i].data.getNumAsked() > 0 ) { cout << setw(6) << static_cast<int> (cards[i].data.getPercentCorrect()) \ << "% (" << cards[i].data.getNumAsked() << ")" \ << setw(9) << cards[i].data.getAverageCorrectAnswerTime(); } else cout << setw(6) << " -" << setw(12) << " -"; if ( isVerbose ) { cout << setw(15) << cards[i].size('A') << " word" << ((cards[i].size('A')>1)?"s:":":"); for (usInt k = 0; k < cards[i].size('A'); k++) cout << setw(15) << cards[i].getWord('A',k); } cout << endl; } cout << endl; cout << endl; } <file_sep>/include/Flashcard.h /* * Flashcard.h * * Description: * * * Created by <NAME> on 9/11/11. * */ #ifndef FLASHCARD_H #define FLASHCARD_H #include <vector> #include <string> #include <iostream> #include <typeinfo> #include <stdexcept> // catch,try, ... #include <fstream> #include <cstdlib> // exit() #include "WordData.h" #include "functions.h" #include "ltest_typedefs.h" using std::cerr; using std::cout; using std::cin; using std::endl; using std::string; using std::vector; using std::ifstream; class Flashcard { private: vector<string> sideA; vector<string> sideB; // vector<string> remark; should these contain the parentheticals? -- put in "" for non-remarks? void insertWords(string, Flashcard &, int); public: WordData data; double weight; // What is this used for? /* Flashcard constructors, etc. */ Flashcard(); /* public member functions */ void toScreen(); void clearWS(); // Clear wordset (used in input()) WordData getWordData(); void recordPerformance(usInt,bool,double); void setWeight(usInt); string getWord(char,usInt) const; vector<string> getSideA(); vector<string> getSideB(); usInt size(char); // size of card side usInt size(char,usInt); // size of individual word void input(vector<Flashcard> &, string); }; #endif // FLASHCARD_H // EOF <file_sep>/include/progPrefs.h /* * progPrefs.h * * Description: * * * Created by <NAME> on 10/6/11. * */ #ifndef PROGPREFS_H #define PROGPREFS_H #include <iostream> #include <cstdlib> #include <readline/readline.h> #include <getopt.h> #include "functions.h" #include "listDicts.h" #include "ltest_typedefs.h" #include "Account.h" using std::cin; using std::cerr; using std::cout; namespace progPrefs { string help(char *); void cmdLineInput(int, char **); usInt changeProgOptions(Account &); } // progPrefs #endif // PROGPREFS_H // EOF <file_sep>/include/WordData.h /* * worddata.h * * Description: class definition of WordData * * * Created by <NAME> on 9/11/11. * */ #ifndef WORDDATA_H #define WORDDATA_H #include <cmath> #include <iostream> #include "functions.h" #include "ltest_typedefs.h" class WordData { private: usInt numAsked; usInt numCorrect; double answeringTime; public: WordData(); double getPercentCorrect() const; double getAverageCorrectAnswerTime() const; usInt getNumCorrect() const; usInt getNumAsked() const; void incrNumAsked(); void incrNumCorrect(); void incrAnsTime(double); }; #endif // WORDDATA_H // EOF <file_sep>/include/Hint.h /* * Hint.h * * Description: * * * Created by KEPS 2/10/11. * */ #ifndef HINT_H #define HINT_H #include <string> #include <iostream> #include <vector> #include "functions.h" #include "ltest_typedefs.h" using std::cout; using std::endl; using std::string; using std::vector; class Hint { public: string key; usInt hintNum; // keeps track of where in the word the hint is at bool verbose; string handle(string, bool&); Hint(string, bool); Hint(); void setKey(string); string getKey() const { return key; } string help(size_t = 0); private: string hint; void addLetter(usInt); void addLetter(); int numOfSpaces(string,int); void fillLetterPlaces(); void answer(void); void disableHints(void); string example(); string synonym(); bool isAccented(string); }; #endif // HINT_H //could add an int penalty so that each hint results in penalty points. <file_sep>/include/functions.h /* * functions.h * * Description: Header file to go with functions.cpp * * * Created by <NAME> on 9/11/11. * */ #ifndef FUNCTIONS_H #define FUNCTIONS_H #include <cstring> // strcmp() #include <iostream> // cin, cout, endl, etc. #include <limits> // numeric_limits<...>::max(), etc. #include <sstream> // string stream #include <stdexcept> // out_of_range(), exception() #include <string> // string class, member functions #include <typeinfo> // name(), what() #include <vector> // vector class, member functions #include <cstdlib> #include <readline/readline.h> #include "WordData.h" #include "ltest_typedefs.h" #include "Account.h" using std::cin; using std::cout; using std::endl; using std::ifstream; using std::string; using std::stringstream; using std::vector; namespace ltest { void welcomeMessage(); string readstring(string); bool pass(int, int, float, float); usInt isAccented(string); string commaAdder(const string, const bool=true); bool compareAll(vector<string> &, string); bool containsContraction(string); bool isInvalidAnswer(string, vector<string>); string hintOptions(usInt); string ordinal(const int); void addSpace(string &); string charToStr(char *); // TODO: needs work template <class X> X readint(const char * prompt) { char * temp = readline(prompt); while (temp[0] == '\0') temp = readline(prompt); X num = static_cast<X> (atoi(temp)); free(temp); return num; } template <class T> string numToStr(T num) { stringstream ss; ss << num; return ss.str(); } template <class X, class Y> float frac(X numer, Y denom) { return static_cast<float> (numer) / static_cast<float> (denom); } /* returns false if < 0, true if >= 0 */ template <class W> bool sgn(W num) { if (num < 0) return false; else return true; } double reaction(const double, const int); template <class U> U randIndex(const U num) { return static_cast<U> (rand() % num); } template <class Z> string printWhitespace(Z length) { if (length > 0) { string temp(length+1,' '); return temp; } else return ""; } float howWrongIsIt(string,string); vector<string> stripParentheses(vector<string> &); string prompt(const char * = NULL); string stripParentheses(string); string goodbye(const string=""); bool exitProg(const char*,bool=false); int whatDoYouWantToDo(const string); template <class U> double inverse(const U num) { if (num != 0) return (1.0 / static_cast<double> (num)); else return 0; // return a nan() instead? } // Only handles positive numbers template <class X> vector<usInt> numDecomp(const X num) { X tempNum = (num < 0 ? -1.0 : 1.0) * num; vector<usInt> numbers; while (tempNum != 0 || num == 0) { if (num == 0) { numbers.push_back(0); break; } numbers.push_back(tempNum % 1000); tempNum /= 1000; } return numbers; } /* attempt at a more robust input processor */ template <class T> void takeInput(T& val, const char * message = NULL, const char * prmpt = ">> ") { T temp; while (true) { if (cin.eof()) break; if (message != NULL) cout << message << endl; cout << prompt(prmpt); cin >> temp; if (!cin.fail()) break; else { cin.clear(); cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); cout << '\n' << prompt(prmpt); } } val = temp; } } // namespace ltest #endif // FUNCTIONS_H <file_sep>/include/SmartPicker.h /* * SmartPicker.h * * Description: * * * Created by KEPS 4/10/11. * */ #ifndef SMARTPICKER_H #define SMARTPICKER_H #include <cmath> // fma(), fdim(), exp() #include <cstdlib> // exit() #include <ctime> // time() #include <iostream> #include <limits> // numeric_limits #include <list> #include <sstream> // stringstream type #include <string> // string members, objects #include <vector> #include <boost/random/mersenne_twister.hpp> // mt19937_64 #include <boost/random/discrete_distribution.hpp> // discrete_distribution() #include "Flashcard.h" #include "functions.h" #include "wordCompare.h" #include "ltest_typedefs.h" using std::list; using std::vector; using std::string; using std::cout; using std::numeric_limits; /* Should all classes start with a limited set of the vocab and only expand the * list if a certain performance level is reached? For instance, start out with * a set of 10, and if, say, all the words have an 70% correctness, add a few * more words... */ class SmartPicker { protected: usInt currentIndex; void setCurrentIndex(usInt=0); public: SmartPicker(); virtual ~SmartPicker() {}; virtual void getNextIndex(const vector<Flashcard> &) = 0; // Access methods usInt getCurrentIndex() const; }; class WalkThrough: public SmartPicker { public: void getNextIndex(const vector<Flashcard> &); }; class LeastCorrect: public SmartPicker { private: list<usInt> leastCorrectIndices; usInt currLowest; void repopulateIndices(const vector<Flashcard> &); void leastCorrectIndex(const vector<Flashcard> &); usInt findSmallest(const vector<Flashcard> &) const; public: // Constructor LeastCorrect(); void getNextIndex(const vector<Flashcard> &); usInt getNumOfIndices() const; void printIndices(); }; class LeastPicked: public SmartPicker { private: list<usInt> leastPickedIndices; usInt currLowest; void setCurrentLowest(usInt); void leastPickedIndex(const vector<Flashcard> &); void repopulateIndices(const vector<Flashcard> &); usInt findSmallest(const vector<Flashcard> &); public: LeastPicked(); void getNextIndex(const vector<Flashcard> &); void printIndices(); }; class Adaptive: public SmartPicker { private: vector<double> probability; boost::mt19937 gen; double levDistance; double currAnsTime; bool isWrong; double weight(bool,double); public: Adaptive(int); ~Adaptive(); void getNextIndex(const vector<Flashcard> &); void updateProbsAdvanced(const double, const vector<Flashcard> &); void updateProbsBasic(const double); string probabilitySummary(vector<Flashcard> &); void setLevDistance(string,string); }; #endif // SMARTPICKER_H // EOF <file_sep>/include/ltest_typedefs.h /* * ltest_typedefs.h * * Description: * typedefs for ltest * * Created by <NAME> on 12/1/11. * */ typedef unsigned short usInt; typedef unsigned long ulInt; // EOF <file_sep>/src/listDicts.cpp /* * listDicts.cpp * * Description: A function that prints out the available dictionaries. It is * similar to the ls function in *nix operating systems. * * Extension: * -- By pressing the dictionary number, the user can get a description of * the dictionary or preview some of the words. * -- by passing an optional argument to the command line (e.g., -l nouns), * the user can specify the type of dictionary he/she is looking for. * -- By pressing the dictionary number, the user can pick that dictionary * and use it in the program -- easily achieved by using a return type * that is just a string or char *. * * Created by <NAME> on 9/13/11. * */ #include "listDicts.h" #include "functions.h" int getTxtFiles(string dir, vector<string> &files) { DIR *dp; struct dirent *dirp; string temp; if ( (dp = opendir(dir.c_str())) == NULL ) return errno; while ((dirp = readdir(dp)) != NULL) { temp = string(dirp -> d_name); if ( temp.size() > 4 ) if ( !temp.compare(temp.size() - 3, 3, "txt") ) // Only store .txt files files.push_back(temp); } closedir(dp); return 0; } //void listDicts(char dictType[]) /** Perhaps we could pass a character to denote which type of dictionary we want to choose from such as n = nouns, v = sideA, etc. or something fancier eventually? and perhaps different types of sorting of output, which is fairly easy with strings */ string listDicts(void) { string dir("./vocab/"), filePath; char *dictPick = NULL; vector<string> files; vector<string>::const_iterator iter; usInt numOfDicts = 1, dictInt = 0, longestName = 0; int retValue = getTxtFiles(dir,files); rl_bind_key('\t',rl_abort); // disable auto-complete // If directory is not found -- do something different instead? if ( retValue != 0 ) { cerr << "Error " << retValue << ": Could not open the directory '" \ << dir << "'" << endl \ << "Exiting program." << endl; exit(0); } cout << endl; if (!files.empty()) // If files are found { do { for (iter = files.begin(); iter != files.end(); ++iter) if ((*iter).size() > longestName) longestName = (*iter).size(); cout << "The following dictionaries are available: \n" << endl; for (iter = files.begin(), numOfDicts = 1; iter != files.end(); ++iter) { cout << '\t' << setw(2) << numOfDicts << ". " << *iter \ << setw(longestName - (*iter).size() + 9) \ << numberOfWords(dir + *iter) << " words" << endl; numOfDicts++; } cout << "\nChoose a dictionary by number or filter by type:\n" << "\tnouns (n), adjectives (a), verbs (v), phrases (p)\n" << "\t(unimplemented -- this is here as a reminder).\n" << "Enter multiple numbers to combine dictionaries\n" << " example: 12,3,4,9,1 (ehem, not active yet)" << endl; do { dictPick = readline("\n>> "); } while ( !strcmp(dictPick,"\0") ); if (ltest::exitProg(dictPick)) exit(0); dictInt = atoi(dictPick); if (!isdigit(dictPick[0]) || dictInt > files.size() || dictInt <= 0 ) cout << dictPick << " is not a valid choice." << endl; } while ( dictInt > files.size() || dictInt <= 0 ); filePath = dir + files.at(dictInt - 1); } else // If files are not found { // This doesn't handle cases where no files are found... but input() does cout << "No dictionaries found.\n" \ << "Select a dictionary for more information. " \ << "Type 'exit' to exit." << endl; dictPick = readline("\n>> "); if ( ltest::exitProg(dictPick,cin.eof()) ) exit(0); } cout << "You picked " << dictPick << endl; free(dictPick); // returns full path of file, e.g. "./vocab/sideA.txt" return filePath; } /* Counts the number of entries in a quiz file */ usInt numberOfWords(string fileName) { ifstream inFile(fileName.c_str(),ifstream::in); string temp; usInt size = 0; if ( inFile.is_open() ) { while ( !inFile.eof() ) // Have something to skip empty lines? { getline(inFile,temp); if (temp == "") continue; size++; temp.clear(); } inFile.close(); } else cout << "could not open file" << endl; return size; } <file_sep>/include/wordCompare.h /* * wordCompare.h * * Description: * * * Created by <NAME> on 9/26/11. * */ /* TODO: Convert this namespace to a class? */ #ifndef WORDCOMPARE_H #define WORDCOMPARE_H #include <iostream> #include <string> #include <algorithm> // std::max, std::min #include "functions.h" #include "ltest_typedefs.h" using std::max; using std::min; namespace wordCompare { string correctness(string, string); usInt findFirstError(string, string); string levRater(usInt); unsigned short levenshtein(string, string); float wordCompare(string, string); string unique(string); float lcsPercent(string, string); } #endif // WORDCOMPARE_H // EOF <file_sep>/include/flcrd_quiz.h /* * flcrd_quiz.h * * * Created by <NAME> on 10/19/11. * */ #ifndef FLCRD_QUIZ_H #define FLCRD_QUIZ_H #include <cstdlib> #include <string> #include <iostream> #include <vector> #include <boost/chrono.hpp> #include <readline/readline.h> #include "functions.h" #include "Flashcard.h" #include "testResults.h" #include "Hint.h" #include "SmartPicker.h" #include "listDicts.h" #include "ltest_typedefs.h" #include "Account.h" using std::string; using std::cout; using std::vector; using std::endl; extern bool exitToMain; namespace chr = boost::chrono; int flcrd_quiz(Account&); #endif // FLCRD_QUIZ_H <file_sep>/makefile # ***************************************************** # Parameters to control Makefile operation vpath %.cpp src vpath %.h include CXX = g++-mp-4.8 CXXFLAGS = -I include \ -L/opt/local/lib \ -I/opt/local/include \ -lboost_system-mt \ -lboost_chrono-mt \ -lreadline DEBUGFLAGS = -Weffc++ \ -Wall \ #-DDEBUG OPTIM = -O3 -funroll-loops CMAKE_COMMAND = /opt/local/bin/cmake OBJECTS = Account.o \ progPrefs.o \ Flashcard.o \ flcrd_quiz.o \ functions.o \ Hint.o \ listDicts.o \ Numbers.o \ SmartPicker.o \ testResults.o \ wordCompare.o \ WordData.o HEADERS = functions.h \ Flashcard.h \ listDicts.h \ testResults.h \ Hint.h \ progPrefs.h \ wordCompare.h \ SmartPicker.h \ WordData.h \ Account.h \ flcrd_quiz.h \ Numbers.h TESTS = SmartPicker_test # **************************************************** mkcln: ltest #clean ltest: main.o $(OBJECTS) @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --red "Building ltest" $(CXX) $(CXXFLAGS) $(OPTIM) $^ -o ltest main.o: main.cpp $(OBJECTS): %.o: %.cpp @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Building CPP object file\r" $@ $(CXX) $(DEBUGFLAGS) $(OPTIM) -I include -c $< -o $@ -std=c++11 SmartPicker_test: ./testing/SmartPicker_test.cpp $(CXX) $(CXXFLAGS) -I include $< -o $@ -lboost_unit_test_framework #proto: main_prototype.o $(PROTO_OBJECTS) # $(CXX) $(CXXFLAGS) $^ -o proto #$(PROTO_OBJECTS): %.o: %.cpp # $(CXX) -I include -c $< -o $@ .PHONY: clean clean: rm -f $(OBJECTS) main.o <file_sep>/src/WordData.cpp /* * WordData.cpp * * Description: functions for the class WordData * * * Created by <NAME> on 9/11/11. * */ #include "WordData.h" WordData::WordData(void) :numAsked(0), numCorrect(0), answeringTime(0.0) { } double WordData::getPercentCorrect(void) const { return 100.0 * static_cast<double>(numCorrect) * ltest::inverse(numAsked); } double WordData::getAverageCorrectAnswerTime(void) const { return static_cast<double>(answeringTime) * ltest::inverse(numCorrect); } usInt WordData::getNumAsked(void) const { return numAsked; } usInt WordData::getNumCorrect(void) const { return numCorrect; } void WordData::incrNumAsked(void) { numAsked++; } void WordData::incrNumCorrect(void) { numCorrect++; } void WordData::incrAnsTime(double incr) { answeringTime += incr; } <file_sep>/src/main.cpp /* * LanguageTest.cpp * * Language quiz program. * Takes in a two-column file, stores it, and then quizzes and then quizzes * the user on the translations. * * * Created by <NAME> on 4/29/11. * * * Create an alternate mode called 'direct feedback' where the user * instantly learns her/his wrong answer -- or even slighly delayed -- kind of * learning-machine like, and not being in the dark and moving onto another * word instead, which could lead to some mental muddiness and focus on * trouble words. * * Contained lessons/quizzes. Lessons that have a clear ending point so * the student will feel a sense of satisfaction on completing a unit. * They can be performance-related, time-related, number-of-items-related, * or more... * */ #include <cstdlib> #include <iostream> /* TODO: make a map container to contain all the program options such as * toDoOption, etc. * #include <map> */ #include "functions.h" #include "progPrefs.h" #include "Account.h" #include "ltest_typedefs.h" /* Quizzes */ #include "flcrd_quiz.h" #include "Numbers.h" using std::cin; using std::cout; using std::endl; bool exitToMain = false; int main(int argc, char **argv) { /***** Initialize Variables *****/ Account acct; int score; // Do away with this? srand(time(NULL)); // What is this initialized for? /***** Take optional input from command line *****/ progPrefs::cmdLineInput(argc,argv); ltest::welcomeMessage(); acct.establishAccount(); while (true) { usInt toDoOption = ltest::whatDoYouWantToDo(acct.getName()); switch (toDoOption) { case 1: cout << "you chose flash cards" << endl; score = flcrd_quiz(acct); break; case 2: cout << "you chose number quiz" << endl; score = numbers(acct); break; case 3: cout << "you chose conjugations!" << endl; /* run conjugations program */ break; case 4: cout << "you chose fill-in-the-blank" << endl; /* run fill-in-the-blank program */ break; case 5: cout << "you chose the multiple choice quiz!" << endl; /* run multiple-choice program */ break; case 6: cout << "you chose to change the user!" << endl; acct.establishAccount(); break; case 7: cout << "you chose to see your account summary" << endl; /* print account summary */ /* This will include which tests were taken, the dates taken, the scores, etc. */ cout << "***This feature is not yet implemented." << "***Returing to main menu."; break; case 8: cout << "you chose to change some program options" << endl; progPrefs::changeProgOptions(acct); break; case 9: cout << "you chose to exit the program" << endl; cout << ltest::goodbye(acct.getName()) << endl; exit(0); default: cout << toDoOption << " is not a valid option." << endl; break; } exitToMain = false; } return 0; } <file_sep>/include/testResults.h /* * testResults.h * * Description: Header file to testResults.cpp * * * Created by <NAME> on 9/15/11. * */ #ifndef TESTRESULTS_H #define TESTRESULTS_H #include <iomanip> #include <iostream> #include <vector> #include <string> #include "Flashcard.h" #include "WordData.h" #include "functions.h" #include "ltest_typedefs.h" #include "Account.h" using std::cout; using std::endl; using std::ios; using std::setw; using std::vector; void testResults(vector<Flashcard>, bool); // void sorter() #endif // TESTRESULTS_H <file_sep>/testing/TestExample.cpp // Compile with g++ -otest -lboost_unit_test_framework TestExample.cpp -L/opt/local/lib -I/opt/local/include #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE Hint test #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE( test1 ) { BOOST_CHECK( 2==2 ); } BOOST_AUTO_TEST_CASE( test2 ) { BOOST_CHECK( 3==1 ); } //EOF <file_sep>/src/functions.cpp /* * functions.cpp * * Description: * Various non-class functions for LanguageTest.cpp * * * Created by <NAME> on 9/11/11. * */ #include "functions.h" void ltest::welcomeMessage() { cout << "\nWelcome to ltest!" << endl; } string ltest::readstring(string prompt) { char * temp = NULL; do { temp = readline(prompt.c_str()); } while (temp[0] == '\0'); string tempStr(temp); free(temp); return tempStr; } // To be used to verify if a given test has been passed // This is only a prototype bool ltest::pass(int numOfHints, int numEntries, float totalAvgTime, float totalAvgPercent) { int numUnanswered = 0; // Delete this later, for use as prototype only bool passVar = ((numOfHints < (numEntries / 30)) && \ (totalAvgTime < 2.0) && \ (totalAvgPercent > 0.9) && \ (numUnanswered == 0)); return passVar; } float ltest::howWrongIsIt(string test, string compare) { /* * This function will tell the user how wrong their word is if they so * choose to know... There are several ways to say how wrong they are, so * I don't know how to start... AE * Ideas: * - percentage of correct letters? - but in correct order? * - choosing similiar consonant? b instead of v, etc. * - chose correct gender * - etc. * * I think there must be a good algorithm out there we can use. One in * wordCompare measures the levenshtein distance between two words. */ return 0.0; } string ltest::charToStr(char * chars) { stringstream ss; ss << chars; return ss.str(); } void ltest::addSpace(string & temp) { if (!temp.empty()) temp += " "; } usInt ltest::isAccented(string str) { vector<string> set = {"á", "é", "í", "ó", "ñ", "ä", "ö", "ü", "å", "ß"}; usInt accents = 0; for (usInt ii = 1; ii < str.length(); ii++) { for (usInt jj = 0; jj < set.size(); jj++) // if (str[ii] == set[jj]) accents++; } return accents; } string ltest::prompt(const char * prmpt) { return prmpt; } string ltest::commaAdder(const string str, const bool sign) { string word(str); for (short jj = word.size() - 3; jj > 0; jj -= 3) { word.insert(jj,","); } if (!sign) word.insert(0,"-"); return word; } vector<string> ltest::stripParentheses(vector<string> & words) { vector<string> strippedWords = words; for (usInt ii = 0; ii < words.size(); ii++) strippedWords[ii] = stripParentheses(strippedWords[ii]); return strippedWords; } string ltest::stripParentheses(string original) { string strippedWord = original; string paren(" ("); if (strippedWord.find(paren) != string::npos) strippedWord.erase(strippedWord.begin() + strippedWord.find(paren), \ strippedWord.end()); return strippedWord; } bool ltest::containsContraction(string str) { return (str.find('\'') != string::npos); } // Mimics string compare -- returns 'true' if there is no match // I don't like to do all this extra work for each case, but for now it works. // Should we make this a member of the class Flashcard? /* TODO: have a contraction converter: if "I'm" is present, convert to "I am", or at least score it correctly */ /* TODO: Conditionally strip the parenthesis -- only do that operation if necessary * */ bool ltest::isInvalidAnswer(string answer, vector<string> ws) { vector<string> strippedws = stripParentheses(ws); bool isWrong = true; for (usInt ii = 0; ii < ws.size() && isWrong; ii++) if ( !answer.compare(ws[ii]) || !answer.compare(strippedws[ii]) ) { isWrong = false; break; } return isWrong; } string ltest::ordinal(const int num) { string ords[] = { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" }; stringstream ord; ord << num << ords[num % 10]; return ord.str(); } string ltest::goodbye(const string name) { string goodbyes[] = {"Goodbye", "<NAME>", "Sayonara", "¡Adiós", "Adieu", "Ciao", "Tchüss", "Au revoir", "Namaste"}; return goodbyes[randIndex(9)] + (name==""?"":", ") + name + "!"; } // Returns true if 'exit' or 'quit' is entered bool ltest::exitProg(const char * test, bool cinEOF) { bool exiting = (!strcmp(test,"exit") || \ !strcmp(test,"'exit'") || \ !strcmp(test,"quit") || \ !strcmp(test,"'quit'") || \ cinEOF); return exiting; } int ltest::whatDoYouWantToDo(const string name) { string options[] = {"flash cards", "numbers", "conjugations", "fill-in-the-blank", "multiple choice", "change user", "account summary", "set program options", "exit program"}; usInt toDoOption; cout << '\n' << "Hello " << name << ", what do you want to do?\n" << "Here are your options: " << endl; for (usInt ii = 1; ii <= 9; ii++) cout << '\t' << ii << ". " << options[ii - 1] << endl; toDoOption = readint<usInt>(">> "); return toDoOption; } // EOF
6f2e8284702d9c18503d1c71a07d0c28f5f1fbce
[ "C", "Makefile", "C++" ]
29
C++
ohasselblad/language-test
ebc93e4e8bb40083aec83bc1f9d97273069a2b24
8a28e44ea9454b658808b78c81716a4e1d35406e
refs/heads/master
<repo_name>ccamposcr/gorilla_test<file_sep>/js/main.js (function($){ //'use strict'; $('.progress-indicator').progressIndicator({ initialValue:56, target:125 }); //You can set a new progress value following the next steps var progressIndicator1 = $('.progress-indicator').first().data('_progressIndicator'); setTimeout(function(){ progressIndicator1.setProgress(78); },1000); })(jQuery);
8689e4e43aa297b8c39dc08aa8567eb6dfb7c154
[ "JavaScript" ]
1
JavaScript
ccamposcr/gorilla_test
26d113c6bd6fba77aa888eadce5596bc94067279
63009e0205af4706be547e12da45e7dc5e87bbfe
refs/heads/master
<repo_name>15024287710Jackson/DataMiningNaiveBayesClassifier<file_sep>/demo2.py import pandas as pd import math import numpy as np class nativeBayesWithNormaltraining(object): def __init__(self): self.lapsample=None;#laplace self.prior_probability=None; self.condition_likelihood=None; self.finalclasses=None;#result self.prior_classes=None;#the classes of label self.bin =None def calculationOfPriorPro(self,training_label): self.prior_classes=np.unique(training_label)#types pf labels num_prior_classes=len(self.prior_classes)#num 0f types num_training_label=len(training_label)#num of training_label self.prior_probability= {}; for each_class in self.prior_classes: traning_label_each_class= list(training_label).count(each_class)+self.lapsample self.prior_probability[each_class] = traning_label_each_class / (float(num_training_label)+num_prior_classes*self.lapsample) # p = count(y) / count(Y) # print(each_class, self.prior_probability[each_class]) def calcution_conditon_probability(self,eachsatifyCondition,EachtheWholeAttributeValue): juuge_redo=1; type_satify=EachtheWholeAttributeValue total_num_satify=float(len(eachsatifyCondition)) satify_probability={} # for each_satity in type_satify: # cal_satify_probability=np.sum(np.equal(eachsatifyCondition,each_satity))/total_num_satify # satify_probability[each_satity]=cal_satify_probability; # if cal_satify_probability==0: # juuge_redo=1#when conditional probability = 0, use laplace if juuge_redo==1: satify_probability = {}# clear the result for each_satity in type_satify: cal_satify_probability = (np.sum(np.equal(eachsatifyCondition, each_satity))+self.lapsample) / (total_num_satify+len(type_satify)*self.lapsample) satify_probability[each_satity] = cal_satify_probability; # print(satify_probability) return satify_probability def bin_distribution(self,satifyCondition,max_value,min_value):#each bin have at least one sample each_bin_size=(max_value-min_value)/float(self.bin) satisCondi=(np.array(satifyCondition)-min_value)/float(each_bin_size); total_binnum_satify = float(len(satifyCondition)) simply_satis=[] for geshu in range(len(satifyCondition)): if(satifyCondition[geshu]>=max_value): bin_reach=self.bin if (satifyCondition[geshu] <= min_value ): bin_reach = 1 bin_reach=math.ceil(satisCondi[geshu]) # if(satifyCondition[geshu]<max_value and satifyCondition[geshu] > min_value): # for num_size in range(1, self.bin + 1): # if satifyCondition[geshu] >= ((num_size - 1) * each_bin_size + min_value) and satifyCondition[geshu] <= (num_size * each_bin_size + min_value): # bin_reach = num_size # if (satifyCondition[geshu] > (num_size * each_bin_size + min_value)): # bin_reach = self.bin # if (satifyCondition[geshu] < ((num_size - 1) * each_bin_size + min_value)): # bin_reach = 1 simply_satis.append(bin_reach) each_bin_probability={} each_bin_probability['mini'] = min_value each_bin_probability['maxi'] = max_value each_bin_probability['size']=each_bin_size for each_bin_satis in range(1,self.bin+1): each_bin_probability[each_bin_satis] = (np.sum(np.equal(simply_satis, each_bin_satis)) + self.lapsample) / ( total_binnum_satify + self.bin * self.lapsample) return each_bin_probability def judgenumber_float(self,strOfnum): # print(strOfnum) point = '.' if point in str(strOfnum): s = str(strOfnum).split('.') # print(s) if float(s[1]) == 0: return 1 else: return 0 else: return 1 def calculationOfConditionalProbability(self,traning_attribute,training_label): self.condition_likelihood={} self.prior_classes = np.unique(training_label) # types pf labels for each_class in self.prior_classes: self.condition_likelihood[each_class]={} for each_set in range(len(traning_attribute[0])):#num of features if self.judgenumber_float(traning_attribute[0][each_set])==1:#discretization num satifyCondition = traning_attribute[np.equal(training_label,each_class)][:,each_set] theWholeAttributeValue=np.unique(traning_attribute[:,each_set]) #np.equal(training_label,each_class) show the location satify the training_label[i]=each_class[j] self.condition_likelihood[each_class][each_set]=self.calcution_conditon_probability(satifyCondition,theWholeAttributeValue) # print("self.condition_likelihood",self.condition_likelihood) else:#Guassian max_eachset=max(traning_attribute[:, each_set]); min_eachset=min(traning_attribute[:, each_set]); satifyCondition = traning_attribute[np.equal(training_label, each_class)][:, each_set] self.condition_likelihood[each_class][each_set] =self.bin_distribution(satifyCondition,max_eachset,min_eachset) class nativeBayesWithNormaltesting(object): def __init__(self): self.condition_likelihood_for_testing=None; self.prior_probability_for_testing=None; self.result_label=None; self.data_testing=None; self.prior_classes=None; self.bin=None def predict_sample_result(self,each_sample_test): max_posterior_prob={} # calculate the probability of each label given the testing data for index in range(len(self.prior_classes)): prior_label_pro = self.prior_classes[index] map_probability=1.0*self.prior_probability_for_testing[prior_label_pro] feature_probability=self.condition_likelihood_for_testing[self.prior_classes[index]] for each_attribute in range(len(each_sample_test)): if(self.condition_likelihood_for_testing[self.prior_classes[index]][each_attribute].__contains__('size')==False): map_probability*=self.condition_likelihood_for_testing[self.prior_classes[index]][each_attribute][each_sample_test[each_attribute]] else:#use bin size=self.condition_likelihood_for_testing[self.prior_classes[index]][each_attribute]['size'] max_range=self.condition_likelihood_for_testing[self.prior_classes[index]][each_attribute]['maxi'] min_range = self.condition_likelihood_for_testing[self.prior_classes[index]][each_attribute]['mini'] # print('max_range',max_range) # print('min_range',min_range) # print('size',size) # print('each_sample_test[each_attribute]',each_sample_test[each_attribute]) reach_num_bin=(each_sample_test[each_attribute]-min_range)/float(size) # print('reach_num_bin',reach_num_bin) # bin_reach = 1 # for num_size in range(1,self.bin+1): # if each_sample_test[each_attribute]>((num_size-1)*size+min_range) and each_sample_test[each_attribute]<(num_size*size+min_range): # bin_reach=num_size # if(num_size==self.bin): # bin_reach=self.bin if (each_sample_test[each_attribute] >= max_range): bin_reach = self.bin elif (each_sample_test[each_attribute] <= min_range): bin_reach = 1 else: bin_reach = math.ceil(reach_num_bin) # bin_reach = math.ceil(reach_num_bin)#min value # print('bin_reach',bin_reach) sample_pro=self.condition_likelihood_for_testing[self.prior_classes[index]][each_attribute][bin_reach] map_probability =map_probability*sample_pro max_posterior_prob[self.prior_classes[index]]=map_probability # look for the max map and label it ex_max_pro=0; for max_index in range(len(self.prior_classes)): if(max_posterior_prob[self.prior_classes[max_index]]>ex_max_pro): each_label=self.prior_classes[max_index] ex_max_pro=max_posterior_prob[self.prior_classes[max_index]] return each_label def sample_result_foroutput(self,each_sample_test): max_posterior_prob={} # calculate the probability of each label given the testing data for index in range(len(self.prior_classes)): prior_label_pro = self.prior_classes[index] map_probability=1.0*self.prior_probability_for_testing[prior_label_pro] feature_probability=self.condition_likelihood_for_testing[self.prior_classes[index]] for each_attribute in range(len(each_sample_test)): if(self.condition_likelihood_for_testing[self.prior_classes[index]][each_attribute].__contains__('size')==False): map_probability*=self.condition_likelihood_for_testing[self.prior_classes[index]][each_attribute][each_sample_test[each_attribute]] else: size = self.condition_likelihood_for_testing[self.prior_classes[index]][each_attribute]['size'] max_range = self.condition_likelihood_for_testing[self.prior_classes[index]][each_attribute]['maxi'] min_range = self.condition_likelihood_for_testing[self.prior_classes[index]][each_attribute]['mini'] reach_num_bin=(each_sample_test[each_attribute]-min_range)/float(size) if (each_sample_test[each_attribute] >= max_range): bin_reach = self.bin elif (each_sample_test[each_attribute] <= min_range): bin_reach = 1 else: bin_reach = math.ceil(reach_num_bin) sample_pro = self.condition_likelihood_for_testing[self.prior_classes[index]][each_attribute][bin_reach] map_probability = map_probability * sample_pro max_posterior_prob[self.prior_classes[index]]=map_probability return max_posterior_prob def output_five_sample(self,data_testing): result_label=[]; result_num=1; for each_sample in data_testing[:]: result_label.append(self.sample_result_foroutput(each_sample)) result_num+=1; if(result_num>5): return result_label return result_label def predict_whole_sample(self,data_testing): result_label=[]; for each_sample in data_testing[:]: result_label.append(self.predict_sample_result(each_sample)) return result_label if __name__=='__main__': #import data training_data = pd.read_csv("training sample.csv", sep=",") trainingdataSetNP = np.array(training_data) # 将数据由dataframe类型转换为数组类型 training_data_attribute = trainingdataSetNP[:, 0:trainingdataSetNP.shape[1] - 1] # 训练数据x1,x2 training_data_label = trainingdataSetNP[:, trainingdataSetNP.shape[1] - 1] # 训练数据所对应的所属类型Y test_data = pd.read_csv("testing sample.csv", sep=",") testingdataSetNP = np.array(test_data) # 将数据由dataframe类型转换为数组类型 testing_data_attribute = testingdataSetNP[:, 0:testingdataSetNP.shape[1]-1 ] # 训练数据x1,x2 testing_data_label = testingdataSetNP[:, testingdataSetNP.shape[1] - 1] # 训练数据所对应的所属类型Y # training_data_attribute = training_data[training_data.columns.values[0:training_data.shape[1] - 1]] # training_data_label = training_data[training_data.columns.values[training_data.shape[1] - 1:training_data.shape[1]]] # print(training_data_attribute) # print(training_data_label) training_model=nativeBayesWithNormaltraining() training_model.lapsample=1; training_model.bin=9; training_model.calculationOfPriorPro(training_label=training_data_label) # for x in range(len(training_data_attribute[0])-5): # print(x,':',np.unique(training_data_attribute[:,x])) training_model.calculationOfConditionalProbability(traning_attribute=training_data_attribute,training_label= training_data_label) # print(training_model.condition_likelihood) # testing training sample test_training_sample_model = nativeBayesWithNormaltesting() test_training_sample_model.bin = training_model.bin test_training_sample_model.prior_classes=training_model.prior_classes # print('training_model.prior_classes',training_model.prior_classes) test_training_sample_model.data_testing=training_data_attribute test_training_sample_model.condition_likelihood_for_testing=training_model.condition_likelihood test_training_sample_model.prior_probability_for_testing=training_model.prior_probability # print('training_model.prior_probability',training_model.prior_probability) final_result_label=test_training_sample_model.predict_whole_sample(data_testing=training_data_attribute) # print('final_result_label:',len(final_result_label)) # print('training_data_label:',len(training_data_label)) same_sample = sum(1 for a, b in zip(final_result_label, training_data_label) if (a == b)) # print('same_sample:',same_sample) right_pre=float(same_sample)/float(len(final_result_label)) print('The accuracy on training data is ',right_pre) test_testing_sample_model = nativeBayesWithNormaltesting() test_testing_sample_model.bin=training_model.bin test_testing_sample_model.prior_classes=training_model.prior_classes test_testing_sample_model.data_testing=testing_data_attribute test_testing_sample_model.condition_likelihood_for_testing=training_model.condition_likelihood test_testing_sample_model.prior_probability_for_testing=training_model.prior_probability final_result_label_test = test_testing_sample_model.predict_whole_sample(data_testing=testing_data_attribute) test_sample = sum(1 for a, b in zip(final_result_label_test, testing_data_label) if (a == b)) # print('test_sample:', test_sample) test_pre = float(test_sample) / float(len(final_result_label_test)) print('The accuracy on testing data is ',test_pre) testing_data_output = testingdataSetNP[0:5, 0:testingdataSetNP.shape[1] - 1] output_fivesample=test_testing_sample_model.output_five_sample(testing_data_attribute) for num in range(5): # print(testing_data_output[num]) for key in output_fivesample[num].keys(): print('P(',training_data.columns.values[len(training_data.columns.values)-1],'=',key,'|',testing_data_output[num],')=',output_fivesample[num][key]) # print(output_fivesample) print('prior_probability: ',training_model.prior_probability) # print(len(training_data.columns.values)); #Check the column names for key in training_model.condition_likelihood.keys():# high low midian for num_attribute in training_model.condition_likelihood[key].keys():# attribute -----num=012345 if(training_model.condition_likelihood[key][num_attribute].__contains__('size')==False): for each_label in training_model.condition_likelihood[key][num_attribute].keys():#label print('P(',training_data.columns.values[num_attribute],'=',each_label,'|',training_data.columns.values[len(training_data.columns.values)-1],'=',key,')=',training_model.condition_likelihood[key][num_attribute][each_label]) else: size=training_model.condition_likelihood[key][num_attribute]['size'] for each in range(1,training_model.bin+1): print('P(',training_data.columns.values[num_attribute],' from ', (each-1)*size+training_model.condition_likelihood[key][num_attribute]['mini'],' to ',each*size+training_model.condition_likelihood[key][num_attribute]['mini'],' | ',training_data.columns.values[len(training_data.columns.values)-1],'=',key,')=',training_model.condition_likelihood[key][num_attribute][each])<file_sep>/uniquefic.py # umpy库unique函数解析 import numpy as np A = [1, 2, 2, 5,3, 4, 3] a = np.unique(A) B= (1, 2, 2,5, 3, 4, 3) b= np.unique(B) C= ['fgfh','asd','fgfh','asdfds','wrh'] c= np.unique(C) print(a) print(b) print(c) <file_sep>/nytest.py import numpy as np y=1 c=-1 a=[1,1,1,2,2,2,3,3,4] feature=[2,3] for v in feature: print(np.equal(v, a)) t=np.sum(np.equal(v,a)) print(t) <file_sep>/initficOne.py class Student_Grade:#与java类似,面向对象编程,构造了一个对象 def __init__(self): # 类似于c++中的默认构造函数 self.name = None self.grade = None def print_grade(self): print("%s grade is %s" % (self.name, self.grade)) s1 = Student_Grade() # 创建对象s1 s1.name = "Tom" s1.grade = 8 s2 = Student_Grade() # 创建对象s2 s2.name = "Jerry" s2.grade = 7 s1.print_grade() s2.print_grade()<file_sep>/test.py #coding:utf-8 #朴素贝叶斯算法 贝叶斯估计, λ=1 K=2, S=3; λ=1 拉普拉斯平滑 import pandas as pd import numpy as np class NavieBayesB(object): def __init__(self): self.A = 1 # 即λ=1 self.K = 2 self.S = 3 def getTrainSet(self): trainSet = pd.read_csv("training sample.csv", sep=",") trainSetNP = np.array(trainSet) #由dataframe类型转换为数组类型 trainData = trainSetNP[:,0:trainSetNP.shape[1]-1] #训练数据x1,x2 labels = trainSetNP[:,trainSetNP.shape[1]-1] #训练数据所对应的所属类型Y return trainData, labels def classify(self, trainData, labels, features): labels = list(labels) #转换为list类型 #求先验概率 P_y = {} for label in labels: P_y[label] = (labels.count(label) + self.A) / float(len(labels) + self.K*self.A) #求条件概率 P = {} for y in P_y.keys(): y_index = [i for i, label in enumerate(labels) if label == y] # y在labels中的所有下标 y_count = labels.count(y) # y在labels中出现的次数 for j in range(len(features)): pkey = str(features[j]) + '|' + str(y) x_index = [i for i, x in enumerate(trainData[:,j]) if x == features[j]] # x在trainData[:,j]中的所有下标 xy_count = len(set(x_index) & set(y_index)) #x y同时出现的次数 P[pkey] = (xy_count + self.A) / float(y_count + self.S*self.A) #条件概率 #features所属类 F = {} for y in P_y.keys(): F[y] = P_y[y] for x in features: F[y] = F[y] * P[str(x)+'|'+str(y)] features_y = max(F, key=F.get) #概率最大值对应的类别 return features_y if __name__ == '__main__': nb = NavieBayesB() # 训练数据 trainData, labels = nb.getTrainSet() # x1,x2 features = [10] # 该特征应属于哪一类 result = nb.classify(trainData, labels, features) print(features,'属于',result)
bc6b1069c541f9bed0a637bfe2bd1e69d63b7f99
[ "Python" ]
5
Python
15024287710Jackson/DataMiningNaiveBayesClassifier
1cf6ff1652e327d95caa2ad0ab9bd615f3958c66
f305b6f7bb09534cee0c1dc09a00af15743f4ee1
refs/heads/master
<file_sep>function CatalogOnlinerPlugin(current_exchange_rate, settings) { var PriceFilterUtils = (function () { function convertToUSD(belPrice) { if (typeof belPrice === 'undefined') { return belPrice; } belPrice = removeAllButNumber(belPrice); return Math.round(((belPrice / removeAllButNumber(current_exchange_rate)))); } function convertToBYR(price) { return Math.round(((price * removeAllButNumber(current_exchange_rate)))); } function convertCatalogPrice(jNode) { var source = jNode.html(); source = $(source).text(); // if price range if(source.indexOf('-') > 0) { var arr = source.split('-'); var originalFromPrice = arr[0].trim(); var convertedFromPrice = convertToUSD(originalFromPrice); var originalToPrice = arr[1].trim().split('&nbsp;руб.')[0]; var convertedToPrice = convertToUSD(originalToPrice); jNode.html(convertedFromPrice + ' - ' + convertedToPrice + '&nbsp;у.е.'); var tooltipText = originalFromPrice + ' - ' + originalToPrice + ' б.р.'; tooltipText = replaceAll('руб.','',tooltipText); registerTooltip(jNode, tooltipText); } else { var originalPrice = source.trim().split('&nbsp;руб.')[0]; var convertedPrice = convertToUSD(originalPrice); jNode.html(convertedPrice + '&nbsp;у.е.'); var tooltipText = originalPrice + ' б.р.'; tooltipText = replaceAll('руб.','',tooltipText); registerTooltip(jNode, tooltipText); } } function convertInsItemPrice(insItem) { var value = insItem.nextSibling.nodeValue; //14&nbsp;880&nbsp;000 – 16&nbsp;275&nbsp;000 руб. value = replaceAll('&nbsp;','',value); //14880000 – 16275000 руб. var source = value; // if price range if(source.indexOf('–') > 0) { var arr = source.split('–'); var originalFromPrice = arr[0].trim(); var convertedFromPrice = convertToUSD(originalFromPrice); var originalToPrice = arr[1].trim().split(' руб.')[0]; var convertedToPrice = convertToUSD(originalToPrice); insItem.nextSibling.nodeValue = ' ' + convertedFromPrice + ' - ' + convertedToPrice + ' у.е.'; registerTooltip(insItem.parent(), originalFromPrice + ' - ' + originalToPrice + ' б.р.'); } else { var originalPrice = source.trim().split(' руб.')[0]; var convertedPrice = convertToUSD(originalPrice); insItem.nextSibling.nodeValue = ' ' + convertedPrice + ' у.е.'; registerTooltip(insItem.parent(), originalPrice + ' б.р.'); } } function convertProductDetailsPrice(jNode) { var source = null; try{ source = jNode.html(); } catch (e) { console.log(e); } if(typeof source == 'undefined') { return; } // if price range if(source.indexOf('–') > 0) { var arr = source.split('–'); var originalFromPrice = arr[0].trim(); var convertedFromPrice = convertToUSD(originalFromPrice); var originalToPrice = arr[1].trim().split('<small>')[0]; var convertedToPrice = convertToUSD(originalToPrice); jNode.html(convertedFromPrice + ' - ' + convertedToPrice + '&nbsp;у.е.'); var toolTipText = originalFromPrice + ' - ' + originalToPrice + ' б.р.'; toolTipText = replaceAll('<small>','',toolTipText); toolTipText = replaceAll('</small>','',toolTipText); toolTipText = replaceAll('руб.','',toolTipText); registerTooltip(jNode, toolTipText); } else { var originalPrice = source.trim().split('&nbsp;руб.')[0]; var convertedPrice = convertToUSD(originalPrice); jNode.html(convertedPrice + '&nbsp;у.е.'); var toolTipText = originalPrice + ' б.р.'; toolTipText = replaceAll('<small>','',toolTipText); toolTipText = replaceAll('</small>','',toolTipText); toolTipText = replaceAll('руб.','',toolTipText); registerTooltip(jNode, toolTipText); } } function replaceAll(find, replace, str) { return str.replace(new RegExp(find, 'g'), replace); } function registerTooltip(jqNode, tooltipText){ try{ jqNode.tooltipster('destroy'); } catch (e) { } tooltipText = replaceAll('&nbsp;',' ',tooltipText); jqNode.attr('title', tooltipText); jqNode.addClass('tooltip-marker'); } function turnOnTooltipster() { $('.tooltip-marker').tooltipster(); } function updateFakeField(fakeField, realField) { fakeField.val(convertToUSD(realField.val())); registerTooltip(fakeField, realField.val() + " б.р."); } function removeAllButNumber(text) { return text.replace(/[^\d]/g, ''); } function commafy( num ) { var str = num.toString().split('.'); if (str[0].length >= 5) { str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1 '); } if (str[1] && str[1].length >= 5) { str[1] = str[1].replace(/(\d{3})/g, '$1 '); } return str.join('.'); } function convertToByrAndFormat(val) { return PriceFilterUtils.commafy(PriceFilterUtils.convertToBYR(val)) + ' б.р.'; } // 2867&nbsp;500&nbsp;<small>руб.</small> function convertCurrencyPrimary(jqNode) { var source = jqNode.html(); source = replaceAll('&nbsp;','',source); var arr = source.split('<'); var originalPrice = arr[0]; var convertedPrice = convertToUSD(originalPrice); jqNode.html(convertedPrice + ' у.е.'); jqNode.addClass('primaryMarker'); registerTooltip(jqNode, commafy(originalPrice) + ' б.р.'); jqNode.tooltipster(); } function convertCatalogPriceForLaptops(jNode) { var value = jNode.text(); var arr = value.split('руб.'); var children = jNode.children(); var source = arr[0] + 'руб.'; // if price range if(source.indexOf('-') > 0) { var arr = source.split('-'); var originalFromPrice = arr[0].trim(); var convertedFromPrice = convertToUSD(originalFromPrice); var originalToPrice = arr[1].trim().split('руб.')[0]; var convertedToPrice = convertToUSD(originalToPrice); jNode.text(convertedFromPrice + ' - ' + convertedToPrice + ' у.е.'); var tooltipText = originalFromPrice + ' - ' + originalToPrice + ' б.р.'; tooltipText = replaceAll('руб.','',tooltipText); registerTooltip(jNode, tooltipText); } else { var originalPrice = source.trim().split('руб.')[0]; var convertedPrice = convertToUSD(originalPrice); jNode.text(convertedPrice + ' у.е.'); var tooltipText = originalPrice + ' б.р.'; tooltipText = replaceAll('руб.','',tooltipText); registerTooltip(jNode, tooltipText); } $.each(children,function(){ jNode.append($(this)); }); } return { updateFakeField: updateFakeField, removeAllButNumber: removeAllButNumber, convertToUSD: convertToUSD, convertToBYR:convertToBYR, registerTooltip:registerTooltip, turnOnTooltipster:turnOnTooltipster, convertCatalogPrice:convertCatalogPrice, commafy:commafy, convertToByrAndFormat:convertToByrAndFormat, convertProductDetailsPrice:convertProductDetailsPrice, convertCurrencyPrimary:convertCurrencyPrimary, convertInsItemPrice:convertInsItemPrice, convertCatalogPriceForLaptops:convertCatalogPriceForLaptops }; })(); function run() { $(document).ready(function() { var jPriceFromField = $('#smth2'); var jPriceToField = $('#smth3'); jPriceFromField.css({"display": "none"}); jPriceToField.css({"display": "none"}); var jPriceFromFieldFake = $('\<input type="text" size="4" maxlength="5" />'); jPriceFromField.after(jPriceFromFieldFake); var jPriceToFieldFake = $('\<input type="text" size="4" maxlength="5"/>'); jPriceToField.after(jPriceToFieldFake); try{ $(jPriceFromFieldFake)[0].nextSibling.nodeValue = " "; $(jPriceToFieldFake)[0].nextSibling.nodeValue = " у.е. "; } catch(e){} if(jPriceFromField.val() > 0) { jPriceFromFieldFake.val(PriceFilterUtils.convertToUSD(jPriceFromField.val())); } if(jPriceToField.val() > 0) { jPriceToFieldFake.val(PriceFilterUtils.convertToUSD(jPriceToField.val())); } PriceFilterUtils.registerTooltip(jPriceFromFieldFake, PriceFilterUtils.convertToByrAndFormat(jPriceFromFieldFake.val())); jPriceFromFieldFake.on('keyup', function(){ PriceFilterUtils.registerTooltip(jPriceFromFieldFake, PriceFilterUtils.convertToByrAndFormat(jPriceFromFieldFake.val())); jPriceFromFieldFake.tooltipster(); jPriceFromFieldFake.tooltipster('show', function(){}); }); jPriceFromFieldFake.on('blur', function(){ jPriceFromFieldFake.tooltipster('hide', function(){}); }); PriceFilterUtils.registerTooltip(jPriceToFieldFake, PriceFilterUtils.convertToByrAndFormat(jPriceToFieldFake.val())); jPriceToFieldFake.on('keyup', function(){ PriceFilterUtils.registerTooltip(jPriceToFieldFake, PriceFilterUtils.convertToByrAndFormat(jPriceToFieldFake.val())); jPriceToFieldFake.tooltipster(); jPriceToFieldFake.tooltipster('show', function(){}); }); jPriceToFieldFake.on('blur', function(){ jPriceToFieldFake.tooltipster('hide', function(){}); }); $('input[name="search"]').on('click', function () { var fromBYRprice = PriceFilterUtils.convertToBYR(jPriceFromFieldFake.val()); var toBYRprice = PriceFilterUtils.convertToBYR(jPriceToFieldFake.val()); jPriceFromField.val(fromBYRprice); jPriceToField.val(toBYRprice); }); $('div.pprice').each(function(){ PriceFilterUtils.convertCatalogPrice($(this)); }); if(window.location.href.indexOf('catalog.onliner.by/notebook') > 0) { $('td.pprice').each(function(){ PriceFilterUtils.convertCatalogPriceForLaptops($(this)); }); } $('.pgprice').find('a').each(function(){ PriceFilterUtils.convertCatalogPrice($(this)); }); var b_offers_desc__info_sub = $('div.b-offers-desc__info-sub'); var b_offers_desc__info_sub_href = b_offers_desc__info_sub.find('a:first'); if(b_offers_desc__info_sub_href.length == 0) { PriceFilterUtils.convertProductDetailsPrice(b_offers_desc__info_sub); } else { PriceFilterUtils.convertProductDetailsPrice(b_offers_desc__info_sub_href); } $('span.product-aside__price--primary').each(function() { PriceFilterUtils.convertCatalogPrice($(this)); }); $('span.item-i').find('ins').each(function(){ // TODO try { PriceFilterUtils.convertInsItemPrice($(this)[0]); } catch(e) {} }); $(document).arrive('a.js-currency-primary', function() { PriceFilterUtils.convertCurrencyPrimary($(this)); }); PriceFilterUtils.turnOnTooltipster(); }); } return { run: run }; } <file_sep>$(function () { var allowedKeyCodes = [46, 8, 37, 39]; var exchangeRateField = $("#exchangeRate"); exchangeRateField.on('keydown',function(event) { if ($.inArray(event.keyCode,allowedKeyCodes) > -1) { // let it happen, don't do anything } else { // Ensure that it is a number and stop the keypress if (event.keyCode < 48 || event.keyCode > 57 ) { event.preventDefault(); } } }); exchangeRateField.on('paste',function(event) { event.preventDefault(); }); chrome.storage.sync.get("exchangeRate", function(items) { var exchangeRate = items.exchangeRate; var exchangeRateField = $("#exchangeRate"); if (typeof exchangeRate === "undefined" /*|| exchangeRate.trim() == ''*/) { exchangeRate = "14000"; } exchangeRateField.val(exchangeRate); }); function saveExchangeRate(exchangeRate) { chrome.storage.sync.set({ "exchangeRate" : exchangeRate }, function () { console.log("Exchange Rate saved : " + exchangeRate); }); } function validateExchangeRateField() { var exchangeRateValue = exchangeRateField.val(); if(exchangeRateValue.trim() == '' || exchangeRateValue == 0) { exchangeRateField.css('background-color','pink'); exchangeRateField.attr('title','Введите значение больше 0'); return false; } else { exchangeRateField.css('background-color','white'); exchangeRateField.attr('title', ''); return true; } } function makeId() { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for( var i=0; i < 5; i++ ) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } $('#saveBtn').click(function () { if(validateExchangeRateField()) { chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { var exchangeRateValue = exchangeRateField.val(); saveExchangeRate(exchangeRateValue); chrome.tabs.sendMessage(tabs[0].id, { exchangeRate: exchangeRateValue }); window.close(); }); } }); //chrome.tabs.create({url: "options.html"}); //$('#optionsCell').append('\<a href="javascript:void(0);" style="font-size: xx-small;" id="">Настройки</a>'); $('#optionsBtn').on('click', function(){ chrome.tabs.create({url: "options.html"}); }); var informerUrl = 'http://www.ecopress.by/cgi/informer.php?nb=USD,EUR,RUB&vb=USD,EUR,RUB&b=USD,EUR,RUB&inf=f0f8ff&bgc=ffffff&hbgc=cacaff&txtc=000000&htxtc=000000&border=000000&iborder=000000&numc=000000&datec=000080&copyc=000080&plusc=006600&minusc=ff0000&is_b=1&is_ib=1&l=160&random=' + makeId(); var informer = $('\<a href="http://www.ecopress.by" title="Курсы валют на www.ecopress.by" target="_blank"><img border="0" src="' + informerUrl + '" width="160" alt="Курсы валют на www.ecopress.by"></a>'); $('#converterTable').after(informer); }); <file_sep> chrome.runtime.sendMessage({ action: "show" }); chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { window.location.reload(); }); chrome.storage.sync.get(["exchangeRate", "tutByConverter"], function(items) { var currentExchangeRate; if (typeof items.exchangeRate !== "undefined") { currentExchangeRate = items.exchangeRate; } else { currentExchangeRate = 14000; } if(window.location.host == "r.onliner.by") { startOnlinerRentPlugin(currentExchangeRate, {}); } else if(window.location.host == "catalog.onliner.by"){ startOnlinerCatalogPlugin(currentExchangeRate, {}); } else { startTutByCatalogPlugin(currentExchangeRate, {"tutByConverter": items.tutByConverter}); } }); function startOnlinerCatalogPlugin(currentExchangeRate, settings) { new CatalogOnlinerPlugin(currentExchangeRate, settings).run(); } function startOnlinerRentPlugin(currentExchangeRate, settings) { new RentOnlinerPlugin(currentExchangeRate, settings).run(); } function startTutByCatalogPlugin(currentExchangeRate, settings) { new KupiTutByPlugin(currentExchangeRate, settings).run(); } <file_sep>function KupiTutByPlugin(current_exchange_rate, settings) { var PriceFilterUtils = (function () { function convertToUSD(belPrice) { if (typeof belPrice === 'undefined') { return belPrice; } belPrice = removeAllButNumber(belPrice); return Math.round(((belPrice / removeAllButNumber(current_exchange_rate)))); } function registerTooltip(jqNode, tooltipText){ jqNode.attr('title', tooltipText); jqNode.addClass('tooltip-marker'); } function turnOnTooltipster() { $('.tooltip-marker').tooltipster(); } function updateFakeField(fakeField, realField) { fakeField.val(convertToUSD(realField.val())); registerTooltip(fakeField, realField.val() + " б.р."); } function removeAllButNumber(text) { return text.replace(/[^\d]/g, ''); } return { updateFakeField: updateFakeField, removeAllButNumber: removeAllButNumber, convertToUSD: convertToUSD, registerTooltip:registerTooltip, turnOnTooltipster:turnOnTooltipster }; })(); function run() { $(document).arrive('div.convert_wrapper',function() { if(settings.tutByConverter) { $(this).remove(); } }); $(document).ready(function() { var priceList = $(".itemList"); function removeTextFromElement(jqNode) { jqNode.contents().filter(function () { return this.nodeType === 3; }).remove(); } function modifyItemNodeImpl(jqNode) { var propPrice = jqNode.find(".prop_price"); var propPriceParent = propPrice.parent(); removeTextFromElement(propPriceParent); propPrice.each(function (index) { var context = $(this).children().context; var innerHtml = context.innerHTML; PriceFilterUtils.registerTooltip($(this), innerHtml + ' б.р.'); var belPrice = innerHtml; context.innerHTML = (PriceFilterUtils.convertToUSD(belPrice) + " у.е."); if (!(index % 2) && propPrice.length > 1) { context.innerHTML += " - "; } }); } function modifyItemNodes() { priceList.find(".itemList_item").each(function () { modifyItemNodeImpl($(this)); }); } priceList.arrive('.itemList_item', function () { modifyItemNodeImpl($(this)); }); modifyItemNodes(); function modifyPriceNodeImpl(jqNode) { modifyPriceNodeWithPrefixImpl(jqNode, ''); } function modifyPriceNodeWithPrefixImpl(jqNode, prefix) { var blrPrice = jqNode.text(); // if already modified -> skip if(blrPrice.indexOf('у') > 0) { return; } PriceFilterUtils.registerTooltip(jqNode,blrPrice); jqNode.text(prefix + PriceFilterUtils.convertToUSD(PriceFilterUtils.removeAllButNumber(blrPrice)) + ' у.е.'); } $('td[class="price"]').each(function () { modifyPriceNodeImpl($(this)); }); $('span[class="price"]').each(function () { modifyPriceNodeImpl($(this)); }); $('div[class="cItems"]').find('div[class="price"]').each(function () { modifyPriceNodeWithPrefixImpl($(this), 'от '); }); $('#credit_compare').find('p[class="big"]').each(function () { modifyPriceNodeImpl($(this)); }); $('.wardrobe_list').find('div[class="price"]').each(function () { modifyPriceNodeWithPrefixImpl($(this), 'от '); }); var cItems_rowField = $('div[class="cItems_row"]'); cItems_rowField.find('big[class="prop_price"]').each(function () { modifyPriceNodeImpl($(this)); }); cItems_rowField.find('div[class="price"]').each(function () { modifyPriceNodeWithPrefixImpl($(this), 'от '); }); var filterCurrencyField = $('.filter_currency'); var noUiBase = filterCurrencyField.parent().find('.wrapper_slider').find('.noUi-base'); var priceSliderLeft = noUiBase.children()[0]; var priceSliderRight = noUiBase.children()[1]; ObserverUtils.createStyleAttrObserver(priceSliderLeft, function (mutation) { PriceFilterUtils.updateFakeField(jPriceFromFieldFake, jPriceFromField); }); ObserverUtils.createStyleAttrObserver(priceSliderRight, function (mutation) { PriceFilterUtils.updateFakeField(jPriceToFieldFake, jPriceToField); }); $('div[class="filter_currency"]').parent().find('#brandTitle').find('label').text("Цена (у.е.):"); var jPriceFromField = $(filterCurrencyField.parent().find('table[class="fields"]').find('td[class="field"]')[0]).find('input'); jPriceFromField.css({"display": "none"}); var jPriceFromFieldFake = $('\<input type="text" readonly/>'); jPriceFromField.after(jPriceFromFieldFake); if (jPriceFromField.val() !== "") { PriceFilterUtils.updateFakeField(jPriceFromFieldFake, jPriceFromField); } var jPriceToField = $(filterCurrencyField.parent().find('table[class="fields"]').find('td[class="field"]')[1]).find('input'); jPriceToField.css({"display": "none"}); var jPriceToFieldFake = $('\<input type="text" readonly/>'); jPriceToField.after(jPriceToFieldFake); if (jPriceToField.val() !== "") { PriceFilterUtils.updateFakeField(jPriceToFieldFake, jPriceToField); } $($('div[class="item_summary"]').find('.price').find('.in')[0]).find('p').each(function () { var text = $(this).text(); var numbers = text.split('до'); var fromPrice = PriceFilterUtils.convertToUSD(PriceFilterUtils.removeAllButNumber(numbers[0])); var toPrice = PriceFilterUtils.convertToUSD(PriceFilterUtils.removeAllButNumber(numbers[1])); var result = 'от ' + fromPrice + ' до ' + toPrice + ' у.е.'; PriceFilterUtils.registerTooltip($(this),text); $(this).text(result); }); PriceFilterUtils.turnOnTooltipster(); }); } return { run: run }; } <file_sep>Google Chrome Extension: https://chrome.google.com/webstore/detail/bel-price-converter/ilckmdiangobdldoklhngfbanonijome
7a61fd147404f70969eda7c719276683bd314079
[ "JavaScript", "Markdown" ]
5
JavaScript
AAZANOVICH/BelPriceConverter
340bef2a4ef1d71d04b5fbe0e8fcd117b80ef7e9
be06fa33456723f25e78e577b55f907bd1c576bc
refs/heads/master
<repo_name>marcoalonso/ToDoListCoreData<file_sep>/ListaCoreData/ToDoListItem/ToDoListItem+CoreDataClass.swift // // ToDoListItem+CoreDataClass.swift // ListaCoreData // // Created by <NAME> on 23/12/20. // // import Foundation import CoreData @objc(ToDoListItem) public class ToDoListItem: NSManagedObject { }
9943e5e737a50cc95b7105bbbb00eb9c02c9d29b
[ "Swift" ]
1
Swift
marcoalonso/ToDoListCoreData
1658a50409b565a34538449331ab499a26c2df03
cbe32f5a299304cc25f114bbc313b072d9aa3ec7
refs/heads/master
<repo_name>rengawm/stringutil<file_sep>/stringutil.go package stringutil // Capitalize makes every normal letter (a-z) uppercase in the given string func Capitalize(s string) string { r := []rune(s) for i := 0; i < len(r); i++ { r[i] = 's' } return string(r) } // Reverse returns its argument string reversed rune-wise left to right. func Reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } // PluralFix returns "s" if the given number is <> 1, and an empty string otherwise func PluralFix(n int) string { if n == 1 { return "" } return "s" } // ArrayContains returns true if the given string array contains the given value func ArrayContains(array []string, value string) bool { for _, member := range array { if member == value { return true } } return false }
af3a2aeef351590c6701e44e16fe7e0a8f37b38f
[ "Go" ]
1
Go
rengawm/stringutil
d9f4e5641540fb2f8b0a2e9bd6367e9db6e9aca2
7aeaddd637bdff6e1714b7397c156c50eebe2cd9
refs/heads/master
<file_sep>class ApplicationController < ActionController::Base protect_from_forgery with: :exception #before_action :verify_user private def verify_user redirect_to '/' unless !!current_user end def current_user User.find(session[:user_id]) end def log_in session[:user_id] = user.id end end <file_sep>class UsersController < ApplicationController #skip_before_action :verify_user, only: [:new, :create] def index @users = User.all end def show @user = User.find(params[:id]) end def new @user = User.new end def create if @user = User.create(user_params) session[:user_id] = @user.id redirect_to user_path(@user), alert: "You Just Signed Up" else render :new end end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) if @user.update(user_params) redirect_to user_path(@user) else render :edit end end def ride @ride = Ride.new(user_id: current_user.id, attraction_id: params[:format]) msg = @ride.take_ride redirect_to user_path(current_user), alert: msg end private def user_params params.require(:user).permit(:name, :height, :happiness, :nausea, :tickets, :password, :<PASSWORD>) end end
d0958384edafd266739f1d6d5fb4f981b73b22a1
[ "Ruby" ]
2
Ruby
SPerfors/rails-amusement-park-online-web-sp-000
108a24ea2d821c96c0e7a39ca02b247de33095df
74f4f5b7e82737798c43bfc670c6ada5f61f799d
refs/heads/master
<file_sep>from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): username = models.CharField(max_length=150, unique=True) password = models.CharField(max_length=128) email = models.EmailField(unique=True, null=True, blank=True) company_name = models.CharField(max_length=150, null=True, blank=True) country = models.IntegerField(null=True, blank=True) contact_person = models.CharField(max_length=150, null=True, blank=True) details = models.TextField(null=True, blank=True) address = models.TextField(null=True, blank=True) office_phone_country = models.IntegerField(null=True, blank=True) office_phone = models.CharField(max_length=15, null=True, blank=True) mobile_phone_country = models.IntegerField(null=True, blank=True) mobile_phone = models.CharField(max_length=15, null=True, blank=True) tex_id = models.CharField(max_length=13, null=True, blank=True) avatar = models.CharField(max_length=3000, null=True, blank=False) # USERNAME_FIELD = 'username' # REQUIRED_FIELDS = []
a99dc7ad617250811369b6ab146a97bdf84c404f
[ "Python" ]
1
Python
speciesvirus/django-filemanager
d9072897189d4e5009f780cd93b371f861740093
ccab8fbdad9e94ba5555ac6d28faff0bfc10ea43
refs/heads/master
<repo_name>matteo-mastromatteo/ContosoPizzaGroup<file_sep>/ContosoPizza/Models/Event.cs namespace ContosoPizza.Models { public enum EventType { Movie, Book } public class Event { public int Id { get; set; } public EventType Type { get; set; } public string Title { get; set; } public decimal Rating { get; set; } } }<file_sep>/ContosoPizza/Factories/PizzaServiceFactory.cs using ContosoPizza.Abstraction; using ContosoPizzaService.Abstraction; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ContosoPizza.Factories { public class PizzaServiceFactory : IPizzaServiceFactory { protected readonly IEnumerable<IPizzaService> _pizzaServices; public PizzaServiceFactory(IEnumerable<IPizzaService> pizzaServices) { _pizzaServices = pizzaServices; } public IPizzaService GetPizzaService(string pizzaServiceName) { var ps = _pizzaServices.Where(t => t.Name.ToLower() == pizzaServiceName.ToLower()).FirstOrDefault(); if (ps == null) { throw new TypeLoadException($"Il tipo {pizzaServiceName} non è stato trovato."); } return ps; } } } <file_sep>/ContosoPizzaService.MemoryPizzaService/MemoryPizzaService.cs using ContosoPizza.Entities.Models; using ContosoPizzaService.Abstraction; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; namespace ContosoPizzaService.MemoryPizzaService { public class MemoryPizzaService : IPizzaService { protected readonly IConfiguration _Configuration; private MemoryPizzaServiceConfiguration _settings; public string Name => "MemoryPizzaService"; private void LoadSettings() { _settings = new MemoryPizzaServiceConfiguration(); var section = _Configuration.GetSection(Name + "Configuration"); if (!section.Exists()) { throw new ArgumentNullException($"Manca la configurazione {Name}Configuration"); } section.Bind(_settings); } protected virtual List<Pizza> Pizzas { get; set; } protected virtual int nextId { get; set; } = 3; public MemoryPizzaService(IConfiguration configuration) { _Configuration = configuration; LoadSettings(); if (_settings.InitializeDefaultPizzas) { Pizzas = new List<Pizza> { new Pizza { Id = 1, Name = "Classic Italian", IsGlutenFree = false }, new Pizza { Id = 2, Name = "Veggie", IsGlutenFree = true } }; } else { Pizzas = new List<Pizza>(); } } public List<Pizza> GetAll() => Pizzas; public Pizza Get(int id) => Pizzas.FirstOrDefault(p => p.Id == id); public void Add(Pizza pizza) { pizza.Id = nextId++; Pizzas.Add(pizza); } public void Delete(int id) { var pizza = Get(id); if(pizza is null) return; Pizzas.Remove(pizza); } public void Update(Pizza pizza) { var index = Pizzas.FindIndex(p => p.Id == pizza.Id); if(index == -1) return; Pizzas[index] = pizza; } } }<file_sep>/ContosoPizza.Entities/Models/Pizza.cs namespace ContosoPizza.Entities.Models { public class Pizza { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual bool IsGlutenFree { get; set; } } }<file_sep>/ContosoPizza/Abstraction/IPizzaServiceFactory.cs using ContosoPizzaService.Abstraction; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ContosoPizza.Abstraction { public interface IPizzaServiceFactory { IPizzaService GetPizzaService(string pizzaServiceName); } } <file_sep>/ContosoPizzaService.DapperPizzaService/DapperPizzaServiceConfiguration.cs using System; using System.Collections.Generic; using System.Text; namespace ContosoPizzaService.DapperPizzaService { public sealed class DapperPizzaServiceConfiguration { public string ConnectionString { get; set; } } } <file_sep>/ContosoPizzaService.Abstraction/IPizzaService.cs using System; using System.Collections.Generic; using ContosoPizza.Entities.Models; namespace ContosoPizzaService.Abstraction { public interface IPizzaService { string Name { get; } List<Pizza> GetAll(); Pizza Get(int id); void Add(Pizza pizza); void Delete(int id); void Update(Pizza pizza); } } <file_sep>/ContosoPizza/Controllers/PizzaController.cs using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using ContosoPizza.Models; using ContosoPizzaService.Abstraction; using ContosoPizza.Entities.Models; using ContosoPizza.Abstraction; using Microsoft.Extensions.Configuration; using System; namespace ContosoPizza.Controllers { [ApiController] [Route("[controller]")] public class PizzaController : ControllerBase { protected readonly IPizzaServiceFactory _PizzaServiceFactory; protected readonly IConfiguration _Configuration; protected readonly IPizzaService _PizzaService; public PizzaController(IPizzaServiceFactory pizzaServiceFactory, IConfiguration configuration) { _PizzaServiceFactory = pizzaServiceFactory; _Configuration = configuration; var pizzaServiceName = _Configuration.GetValue<string>("PizzaServiceName"); if (pizzaServiceName == null) { throw new ArgumentNullException("Manca la chiave di confgurazione PizzaServiceName."); } _PizzaService = pizzaServiceFactory.GetPizzaService(pizzaServiceName); } // GET all action [HttpGet] public ActionResult<List<Pizza>> GetAll() => _PizzaService.GetAll(); // GET by Id action [HttpGet("{id}")] public ActionResult<Pizza> Get(int id) { var pizza = _PizzaService.Get(id); if (pizza == null) return NotFound(); return pizza; } // POST action [HttpPost] public IActionResult Create(Pizza pizza) { _PizzaService.Add(pizza); return CreatedAtAction(nameof(Create), new { id = pizza.Id }, pizza); } // PUT action [HttpPut("{id}")] public IActionResult Update(int id, Pizza pizza) { if (id != pizza.Id) return BadRequest(); var existingPizza = _PizzaService.Get(id); if (existingPizza is null) return NotFound(); _PizzaService.Update(pizza); return NoContent(); } // DELETE action [HttpDelete("{id}")] public IActionResult Delete(int id) { var pizza = _PizzaService.Get(id); if (pizza is null) return NotFound(); _PizzaService.Delete(id); return NoContent(); } } }<file_sep>/ContosoPizzaService.DapperPizzaService/DapperPizzaService.cs using ContosoPizza.Entities.Models; using ContosoPizzaService.Abstraction; using Dapper; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using Microsoft.Data.SqlClient; using System.Linq; namespace ContosoPizzaService.DapperPizzaService { public class DapperPizzaService : IPizzaService { public string Name => "DapperPizzaService"; protected DapperPizzaServiceConfiguration dapperServiceSettings { get; set; } public DapperPizzaService(IConfiguration configuration) { dapperServiceSettings = new DapperPizzaServiceConfiguration(); var section = configuration.GetSection(Name + "Configuration"); if (!section.Exists()) { throw new ArgumentNullException($"Configurazione {Name}Configuration mancante"); } section.Bind(dapperServiceSettings); } public void Add(Pizza pizza) { using(SqlConnection conn = new SqlConnection(dapperServiceSettings.ConnectionString)) { using (SqlCommand cmd=new SqlCommand()) { conn.Open(); pizza.Id = conn.QuerySingle<int>("Insert into Pizza(Name, IsGlutenFree) values(@Name,@IsGlutenFree);" + "select scope_identity();", new { Name = pizza.Name, IsGlutenFree = pizza.IsGlutenFree }); } } } public void Delete(int id) { using(SqlConnection conn = new SqlConnection(dapperServiceSettings.ConnectionString)) { conn.Execute("Delete from Pizza where id=@id", new { id = id }); } } public Pizza Get(int id) { Pizza result = null; using (SqlConnection conn = new SqlConnection(dapperServiceSettings.ConnectionString)) { conn.Open(); result = conn.QuerySingle<Pizza>("Select * from Pizza where id=@id", new { id = id }); } return result; } public List<Pizza> GetAll() { List<Pizza> result = null; using (SqlConnection conn = new SqlConnection(dapperServiceSettings.ConnectionString)) { conn.Open(); result = conn.Query<Pizza>("Select * from Pizza").ToList(); } return result; } public void Update(Pizza pizza) { using (SqlConnection conn = new SqlConnection(dapperServiceSettings.ConnectionString)) { conn.Execute("Update Pizza set Name=@Name, IsGlutenFree=@IsGlutenFree where id=@Id", pizza); } } } } <file_sep>/ContosoPizzaService.MemoryPizzaService/MemoryPizzaServiceConfiguration.cs using System; using System.Collections.Generic; using System.Text; namespace ContosoPizzaService.MemoryPizzaService { public sealed class MemoryPizzaServiceConfiguration { public bool InitializeDefaultPizzas { get; set; } } } <file_sep>/ContosoPizza/Helpers/PizzaServiceLoader.cs using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Reflection; using System.IO; using ContosoPizzaService.Abstraction; namespace ContosoPizza.Helpers { public static class PizzaServiceLoader { public static void AddPizzaServiceImplementations(this IServiceCollection services) { var types = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll").Select(f => Assembly.LoadFrom(f)).ToList() .SelectMany(a => a.GetTypes() .Where(t => typeof(IPizzaService).IsAssignableFrom(t) && !t.IsAbstract && !t.IsInterface && t.IsClass && t.IsPublic) ) .ToList(); if (types.Count == 0) { throw new TypeLoadException($"Non è stato trovato alcuna implementazione per IPizzaService."); } types.ForEach(t => services.AddSingleton(typeof(IPizzaService), t)); } } }
ac3c91248f995274d44f44d0c4997fff95a68ad6
[ "C#" ]
11
C#
matteo-mastromatteo/ContosoPizzaGroup
acf5109abf6fa635daf9d02b1ff7a4e8ac1b8167
c91c8f85e83ed85f540cf4ad2d590dce2ba9e5ef
refs/heads/master
<file_sep>package main import ( "bytes" "context" "fmt" "image" "net/url" "os" "os/signal" "path/filepath" "strings" "time" "github.com/decred/dcrd/dcrutil/v3" "go.etcd.io/bbolt" "fyne.io/fyne" "fyne.io/fyne/app" "fyne.io/fyne/canvas" "fyne.io/fyne/layout" "fyne.io/fyne/theme" "fyne.io/fyne/widget" ) // Declaring these here to enable button click handlers // have access to them. var ( a = app.New() mainWindow = a.NewWindow("RemindMe") activeReminders = make(map[string][]*Item) lastRunStatuses = make(map[string]int) categoryEntry *widget.Select activeRemindersBox *fyne.Container ) func main() { appDataDir := dcrutil.AppDataDir("remindme", false) err := os.MkdirAll(appDataDir, 0700) if err != nil { fmt.Fprintf(os.Stderr, "failed to create app data directory: %v\n", err) os.Exit(1) } dbPath := filepath.Join(appDataDir, "app.db") db, err = bbolt.Open(dbPath, 0600, &bbolt.Options{Timeout: 1 * time.Second}) if err != nil { fmt.Fprintf(os.Stderr, "failed to open database: %v\n", err) os.Exit(1) } categories, err := categoriesFromDB() if err != nil { fmt.Fprintf(os.Stderr, "failed to fetch categories: %v\n", err) os.Exit(1) } ctx, cancel := context.WithCancel(context.Background()) // Start a goroutine to catch interrupt signal (e.g. ctrl+c) // before starting the api server. On interrupt, kill the // ctx associated with the api server to signal the api // server to stop. killChan := make(chan os.Signal) signal.Notify(killChan, os.Interrupt) go func() { for range killChan { fmt.Println("shutting down...") cancel() a.Quit() return } }() a.Settings().SetTheme(theme.LightTheme()) mainWindow.CenterOnScreen() mainWindow.Resize(fyne.NewSize(500, 300)) categoryEntry = widget.NewSelect(categories, nil) activeRemindersBox = fyne.NewContainerWithLayout(layout.NewVBoxLayout()) errorLabel := widget.NewLabel("") errorLabel.Hide() refreshCategories := func() { errorLabel.SetText("Refreshing...") errorLabel.Show() categories, err := downloadFromAPI() if err != nil { errorLabel.SetText(err.Error()) return } categoryEntry.Options = categories for category := range activeReminders { items, err := categoryItems(category) if err != nil { errorLabel.SetText(err.Error()) return } activeReminders[category] = items } errorLabel.Hide() } refreshCategories() noDelayCheck := widget.NewCheck("No initial delay", nil) startButton := widget.NewButton("Start", func() { if categoryEntry.SelectedIndex() < 0 { errorLabel.SetText("Please select a reminder category") errorLabel.Show() return } selectedCategory := categoryEntry.Selected if _, active := activeReminders[selectedCategory]; active { errorLabel.SetText("Already running reminders for " + selectedCategory) errorLabel.Show() return } items, err := categoryItems(selectedCategory) if err != nil { errorLabel.SetText(err.Error()) errorLabel.Show() return } activeReminders[selectedCategory] = items errorLabel.Hide() startTimer(noDelayCheck.Checked, selectedCategory, ctx) categoryEntry.SetSelectedIndex(-1) }) mainWindow.SetContent(widget.NewVBox( widget.NewHBox(layout.NewSpacer(), widget.NewButton("Refresh", refreshCategories)), errorLabel, widget.NewLabelWithStyle("Reminder categories:", fyne.TextAlignLeading, fyne.TextStyle{Italic: true}), categoryEntry, noDelayCheck, startButton, widget.NewLabelWithStyle("Active reminders", fyne.TextAlignLeading, fyne.TextStyle{Italic: true}), activeRemindersBox, )) lastRunStatuses, err = lastRuns() if err != nil { fmt.Fprintf(os.Stderr, "failed to fetch last runs: %v\n", err) lastRunStatuses = make(map[string]int) } for category := range lastRunStatuses { items, err := categoryItems(category) if err != nil { fmt.Println("failed to fetch items for resumed category ", category, err.Error()) delete(lastRunStatuses, category) continue } activeReminders[category] = items startTimer(false, category, ctx) } mainWindow.SetCloseIntercept(a.Quit) mainWindow.ShowAndRun() } func startTimer(immediateDisplay bool, category string, mainCtx context.Context) { items, exist := activeReminders[category] if !exist || len(items) == 0 { return } lastIndex, exist := lastRunStatuses[category] if !exist { lastIndex = -1 } remaining := len(items) - lastIndex - 1 if remaining == 0 { return } activeLabel := widget.NewLabel(fmt.Sprintf("%s (%d)", category, remaining)) newReminder := widget.NewHBox() killReminder := func() { activeRemindersBox.Remove(newReminder) mainWindow.Canvas().Refresh(activeRemindersBox) delete(activeReminders, category) delete(lastRunStatuses, category) if err := deleteLastRun(category); err != nil { fmt.Println("error deleting last run for ", category, err.Error()) } } ctx, cancel := context.WithCancel(mainCtx) go func() { if immediateDisplay && !showReminder(category, activeLabel) { // show first reminder before starting timer, if immediateDisplay=true return } ticker := time.NewTicker(15 * time.Second) defer func() { ticker.Stop() killReminder() }() for { select { case <-ticker.C: if !showReminder(category, activeLabel) { return } case <-ctx.Done(): return } } }() newReminder.Append(activeLabel) newReminder.Append(layout.NewSpacer()) newReminder.Append(widget.NewButton("X", cancel)) activeRemindersBox.Add(newReminder) } func showReminder(category string, catLabel *widget.Label) bool { items, exist := activeReminders[category] if !exist || len(items) == 0 { return false // no items to display, kill ticker } lastIndex, exist := lastRunStatuses[category] if !exist { lastIndex = -1 } nextIndex := lastIndex + 1 if nextIndex >= len(items) { return false // reached the end, kill ticker } lastRunStatuses[category] = nextIndex if err := saveLastRun(category, nextIndex); err != nil { fmt.Println("error saving last run record for", category, err.Error()) } nextItem := items[nextIndex] var itemUI fyne.CanvasObject var imgSize image.Point switch strings.ToLower(nextItem.Type) { case "text": text := string(nextItem.Content) label := widget.NewLabel(text) label.Wrapping = fyne.TextWrapWord itemUI = label case "image": imgReader := bytes.NewReader(nextItem.Content) img, _, err := image.Decode(imgReader) if err != nil { println(err.Error()) itemUI = widget.NewLabelWithStyle("Error displaying image: "+nextItem.Name, fyne.TextAlignCenter, fyne.TextStyle{Italic: true}) } else { itemUI = canvas.NewImageFromImage(img) imgSize = img.Bounds().Size() } case "link": text := string(nextItem.Content) link, err := url.Parse(text) if err != nil { println(err.Error()) itemUI = widget.NewLabel(text) } else { itemUI = widget.NewHyperlink(text, link) } default: itemUI = widget.NewLabelWithStyle("This is a/an "+nextItem.Type, fyne.TextAlignCenter, fyne.TextStyle{Italic: true}) } w := a.NewWindow(category + ": " + nextItem.Name) w.SetContent(itemUI) winSize := w.Canvas().Size() if strings.ToLower(nextItem.Type) == "image" { winSize = fyne.NewSize(imgSize.X, imgSize.Y) } if winSize.Height < 200 { winSize.Height = 200 } else if winSize.Height > 400 { winSize.Height = 400 } if winSize.Width < 300 { winSize.Width = 300 } else if winSize.Width > 600 { winSize.Width = 600 } w.Resize(winSize) w.Show() remaining := len(items) - nextIndex - 1 catLabel.SetText(fmt.Sprintf("%s (%d)", category, remaining)) return remaining > 0 // only return true if there's more to show } <file_sep>package main import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net" "net/http" "os" "strings" "sync" "github.com/go-chi/chi" "go.etcd.io/bbolt" ) type apiServer struct { db *bbolt.DB } func (api *apiServer) Start(ctx context.Context) error { // Create an HTTP router. mux := chi.NewRouter() // Mount api endpoints. mux.Route("/api", func(r chi.Router) { r.Get("/items", api.allItems) r.Post("/items", api.storeItem) }) // Get ready to serve the API. listenAddr := "0.0.0.0:17778" listener, err := net.Listen("tcp", listenAddr) if err != nil { return fmt.Errorf("Can't listen on %s. web server quitting: %w", listenAddr, err) } httpServer := &http.Server{ Handler: mux, } // Listen for context cancellation in bg and kill the server. go func() { <-ctx.Done() if err := httpServer.Shutdown(context.Background()); err != nil { fmt.Fprintf(os.Stderr, "api server shutdown error: %v\n", err) os.Exit(1) } }() // Start server in bg. var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() err = httpServer.Serve(listener) if errors.Is(err, http.ErrServerClosed) { err = nil } }() fmt.Printf("API live on http://%s\n", listenAddr) wg.Wait() return err } var ( itemContentKey = []byte("content") itemTypeKey = []byte("type") ) type Item struct { Name string `json:"name"` Type string `json:"type"` Content []byte `json:"Content"` } const maxFileBytes = 10_000_000 // 10mb func (api *apiServer) storeItem(w http.ResponseWriter, r *http.Request) { r.ParseMultipartForm(maxFileBytes) category := r.FormValue("category") itemName := r.FormValue("item.name") itemType := strings.ToLower(r.FormValue("item.type")) itemContent := r.FormValue("item.content") var content []byte var hasAttachment bool f, h, err := r.FormFile("item.attachment") if err != nil && !errors.Is(err, http.ErrMissingFile) { fmt.Fprintf(os.Stderr, "Error reading file attachment: %v\n", err) http.Error(w, "error reading file attachment", http.StatusInternalServerError) return } if f != nil { hasAttachment = true buf := bytes.NewBuffer(nil) _, err = io.Copy(buf, f) if err != nil { fmt.Fprintf(os.Stderr, "file bytes copy error: %v\n", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } content = buf.Bytes() } else { content = []byte(itemContent) } switch hasAttachment { case true: fileType := strings.ToLower(h.Header.Get("Content-Type")) if !strings.HasPrefix(fileType, itemType) { http.Error(w, "invalid attachment for "+itemType, http.StatusBadRequest) return } case false: if itemType == "video" || itemType == "image" { http.Error(w, "video or image requires attachment", http.StatusBadRequest) return } } err = api.db.Update(func(tx *bbolt.Tx) error { catBucket, err := tx.CreateBucketIfNotExists([]byte(category)) if err != nil { return fmt.Errorf("failed to open db record for %s", category) } itemBucket, err := catBucket.CreateBucketIfNotExists([]byte(itemName)) if err != nil { return fmt.Errorf("failed to open db record for %s", itemName) } if err = itemBucket.Put(itemTypeKey, []byte(itemType)); err != nil { return err } if err = itemBucket.Put(itemContentKey, content); err != nil { return err } return nil }) if err != nil { fmt.Fprintf(os.Stderr, "Error saving item with attachment (%v): %v\n", hasAttachment, err) http.Error(w, "error saving item", http.StatusInternalServerError) return } api.allItems(w, r) } type Category struct { Name string `json:"name"` Items []*Item `json:"items"` } func (api *apiServer) allItems(w http.ResponseWriter, r *http.Request) { categoriesWithItems := make([]*Category, 0) err := api.db.View(func(tx *bbolt.Tx) error { categories := tx.Cursor() for categoryB, _ := categories.First(); categoryB != nil; categoryB, _ = categories.Next() { category := string(categoryB) categoryBkt := tx.Bucket(categoryB) if categoryBkt == nil { fmt.Fprintf(os.Stderr, "category %s not a db bucket\n", category) continue } categoryItems := categoryBkt.Cursor() items := make([]*Item, 0) for itemB, _ := categoryItems.First(); itemB != nil; itemB, _ = categoryItems.Next() { itemName := string(itemB) itemBkt := categoryBkt.Bucket(itemB) if itemBkt == nil { fmt.Fprintf(os.Stderr, "item %s not a nested db bucket in %s\n", itemName, category) continue } itemType := itemBkt.Get(itemTypeKey) items = append(items, &Item{ Name: itemName, Type: string(itemType), Content: itemBkt.Get(itemContentKey), }) } categoriesWithItems = append(categoriesWithItems, &Category{ Name: category, Items: items, }) } return nil }) if err != nil { fmt.Fprintf(os.Stderr, "Error fetching items from db: %v\n", err) http.Error(w, "error fetching items", http.StatusInternalServerError) return } writeJSON(w, categoriesWithItems) } // writeJSON marshals the provided interface and writes the bytes to the // ResponseWriter. The response code is assumed to be StatusOK. func writeJSON(w http.ResponseWriter, thing interface{}) { writeJSONWithStatus(w, thing, http.StatusOK) } // writeJSON writes marshals the provided interface and writes the bytes to the // ResponseWriter with the specified response code. func writeJSONWithStatus(w http.ResponseWriter, thing interface{}, code int) { w.Header().Set("Content-Type", "application/json; charset=utf-8") b, err := json.Marshal(thing) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(os.Stderr, "JSON encode error: %v\n", err) return } w.WriteHeader(code) _, err = w.Write(append(b, byte('\n'))) if err != nil { fmt.Fprintf(os.Stderr, "Write error: %v\n", err) } } <file_sep>package main import ( "context" "fmt" "os" "os/signal" "path/filepath" "time" "github.com/decred/dcrd/dcrutil/v3" "go.etcd.io/bbolt" ) func main() { appDataDir := dcrutil.AppDataDir("remindme", false) err := os.MkdirAll(appDataDir, 0700) if err != nil { fmt.Fprintf(os.Stderr, "failed to create app data directory: %v\n", err) os.Exit(1) } dbPath := filepath.Join(appDataDir, "bdb.db") db, err := bbolt.Open(dbPath, 0600, &bbolt.Options{Timeout: 1 * time.Second}) if err != nil { fmt.Fprintf(os.Stderr, "failed to open database: %v\n", err) os.Exit(1) } defer func() { if err := db.Close(); err != nil { fmt.Fprintf(os.Stderr, "failed to close db: %v\n", err) } }() ctx, cancel := context.WithCancel(context.Background()) // Start a goroutine to catch interrupt signal (e.g. ctrl+c) // before starting the api server. On interrupt, kill the // ctx associated with the api server to signal the api // server to stop. killChan := make(chan os.Signal) signal.Notify(killChan, os.Interrupt) go func() { for range killChan { fmt.Println("shutting down...") cancel() break } }() api := &apiServer{ db: db, } // go func() { // time.Sleep(5 * time.Second) // resp, err := http.Get("http://0.0.0.0:54321/api/items") // if err != nil { // fmt.Println(err.Error()) // return // } // body, err := ioutil.ReadAll(resp.Body) // if err != nil { // fmt.Println(err.Error()) // return // } // cats := make([]*Category, 0) // err = json.Unmarshal(body, &cats) // if err != nil { // fmt.Fprintf(os.Stderr, "failed to unmarshal JSON request: %v\n", err) // return // } // item := cats[0].Items[1] // println("o") // println(len(item.Attachment)) // }() if err := api.Start(ctx); err != nil { fmt.Fprintf(os.Stderr, "api start error: %v\n", err) } } <file_sep>package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "os" "strconv" "go.etcd.io/bbolt" ) var ( db *bbolt.DB categoriesBkt = []byte("categories") lastRunBktKey = []byte("last_run") itemContentKey = []byte("content") itemTypeKey = []byte("type") ) type Category struct { Name string `json:"name"` Items []*Item `json:"items"` } type Item struct { Name string `json:"name"` Type string `json:"type"` Content []byte `json:"Content"` } func downloadFromAPI() ([]string, error) { resp, err := http.Get("http://172.16.17.32:17778/api/items") if err != nil { return nil, err } body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } catItems := make([]*Category, 0) err = json.Unmarshal(body, &catItems) if err != nil { return nil, err } categories := make([]string, 0, len(catItems)) return categories, db.Update(func(tx *bbolt.Tx) error { for _, category := range catItems { categories = append(categories, category.Name) catsBucket, err := tx.CreateBucketIfNotExists(categoriesBkt) if err != nil { return fmt.Errorf("failed to open db record for all categories") } catBucket, err := catsBucket.CreateBucketIfNotExists([]byte(category.Name)) if err != nil { return fmt.Errorf("failed to open db record for %s", category.Name) } for _, item := range category.Items { itemBucket, err := catBucket.CreateBucketIfNotExists([]byte(item.Name)) if err != nil { return fmt.Errorf("failed to open db record for %s", item.Name) } if err = itemBucket.Put(itemTypeKey, []byte(item.Type)); err != nil { return err } if err = itemBucket.Put(itemContentKey, item.Content); err != nil { return err } } } return nil }) } func categoriesFromDB() (categories []string, err error) { err = db.View(func(tx *bbolt.Tx) error { catsBucket := tx.Bucket(categoriesBkt) if catsBucket == nil { return nil } cats := catsBucket.Cursor() for categoryB, _ := cats.First(); categoryB != nil; categoryB, _ = cats.Next() { categories = append(categories, string(categoryB)) } return nil }) return } func categoryItems(category string) (items []*Item, err error) { err = db.View(func(tx *bbolt.Tx) error { catsBucket := tx.Bucket(categoriesBkt) if catsBucket == nil { return fmt.Errorf("no data downloaded yet!") } categoryBkt := catsBucket.Bucket([]byte(category)) if categoryBkt == nil { return fmt.Errorf("unknown reminder category: %s", category) } categoryItems := categoryBkt.Cursor() for itemB, _ := categoryItems.First(); itemB != nil; itemB, _ = categoryItems.Next() { itemName := string(itemB) itemBkt := categoryBkt.Bucket(itemB) if itemBkt == nil { fmt.Fprintf(os.Stderr, "item %s not a nested db bucket in %s\n", itemName, category) continue } itemType := itemBkt.Get(itemTypeKey) items = append(items, &Item{ Name: itemName, Type: string(itemType), Content: itemBkt.Get(itemContentKey), }) } return nil }) return } func saveLastRun(category string, index int) error { return db.Update(func(tx *bbolt.Tx) error { lastRunBkt, err := tx.CreateBucketIfNotExists(lastRunBktKey) if err != nil { return err } return lastRunBkt.Put([]byte(category), []byte(strconv.Itoa(index))) }) } func deleteLastRun(category string) error { return db.Update(func(tx *bbolt.Tx) error { lastRunBkt, err := tx.CreateBucketIfNotExists(lastRunBktKey) if err != nil { return err } return lastRunBkt.Delete([]byte(category)) }) } func lastRuns() (map[string]int, error) { lastRuns := make(map[string]int) return lastRuns, db.View(func(tx *bbolt.Tx) error { lastRunBkt := tx.Bucket(lastRunBktKey) if lastRunBkt == nil { return nil } records := lastRunBkt.Cursor() for catB, indexB := records.First(); catB != nil; catB, _ = records.Next() { index, err := strconv.Atoi(string(indexB)) if err != nil { fmt.Println(err.Error()) continue } lastRuns[string(catB)] = index } return nil }) } <file_sep>package main import ( "fmt" "go.etcd.io/bbolt" ) // Store stores a value at the specified key in the general-use bucket. func (api *apiServer) Store(b string, k string, v []byte) error { if len(k) == 0 || len(b) == 0 { return fmt.Errorf("cannot store with empty bucket or key") } bucketByte := []byte(b) keyB := []byte(k) return api.db.Update(func(tx *bbolt.Tx) error { bucket, err := tx.CreateBucketIfNotExists(bucketByte) if err != nil { return fmt.Errorf("failed to create key bucket") } return bucket.Put(keyB, v) }) } // Get retrieves value previously stored with Store. func (api *apiServer) Get(b string, k string) ([]byte, error) { if len(k) == 0 || len(b) == 0 { return nil, fmt.Errorf("cannot get with empty bucket or key") } var v []byte bucketByte := []byte(b) keyB := []byte(k) return v, api.db.View(func(tx *bbolt.Tx) error { bucket := tx.Bucket(bucketByte) if bucket == nil { return fmt.Errorf("app bucket not found") } vx := bucket.Get(keyB) if vx == nil { return fmt.Errorf("no value found for %s", k) } // An empty non-nil slice is returned nil without error. if len(vx) > 0 { v = make([]byte, len(vx)) copy(v, vx) } return nil }) } <file_sep>module github.com/itswisdomagain/remindme go 1.15 require ( github.com/decred/dcrd/dcrutil/v3 v3.0.0 github.com/go-chi/chi v1.5.1 go.etcd.io/bbolt v1.3.5 ) <file_sep>module github.com/itswisdomagain/remindme/app go 1.15 require ( fyne.io/fyne v1.4.3 github.com/decred/dcrd/dcrutil/v3 v3.0.0 github.com/getlantern/systray v1.1.0 go.etcd.io/bbolt v1.3.5 )
49764e0be7b9e477f2abc5723b006970e65ac4b9
[ "Go Module", "Go" ]
7
Go
itswisdomagain/remindme
b240be3acda883bad26b9e34046a0f0f9cb50c52
d69b03ad964aeabb791881f90041686983f971b6
refs/heads/master
<repo_name>yzy-hushuo/yzydemo<file_sep>/C76-S3-Pyzy-sc-index/src/main/java/com/yc/index/web/TokenFilter.java package com.yc.index.web; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Component; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; @Component public class TokenFilter extends ZuulFilter{ @Override public boolean shouldFilter() { return true; } @Override public Object run() throws ZuulException { //获取zuul 的请求上下文对象 RequestContext requestContext = RequestContext.getCurrentContext(); //获取Servlet请求对象 HttpServletRequest req = requestContext.getRequest(); //获取令牌 String token = req.getParameter("token"); if(token == null) { //设置是否发送zuul响应 requestContext.setSendZuulResponse(false); //设置结果码401 ==> 4xx 客户端错误 requestContext.setResponseStatusCode(401); //设置响应的信息 requestContext.setResponseBody("{\"result\":\"accessToken is empty!\"}"); } return null; } @Override //pre 前置 ,post 后置,route 路由中,error 错误 public String filterType() { return "pre"; } @Override //拦截的顺序0表示第一个 public int filterOrder() { return 0; } }
cd4ab902f834db9d0fef945f23958e6dd7f3a178
[ "Java" ]
1
Java
yzy-hushuo/yzydemo
ff037a182ee5da535413254bcab2ce7c3ef3e78a
d9c6a34e4a1980e9cf325a3d8acb35af19f71251
refs/heads/master
<file_sep>package hu.tewe.letslearnlol.datagatherer.leagueversion; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author: tewe */ public class LeagueVersion { @JsonProperty("v") private String version; @JsonProperty("l") private String locale; @JsonProperty("cdn") private String cdnUrl; private String dd; private String lg; private String css; @JsonProperty("profileiconmax") private Integer profileIconMax; private String store; @JsonProperty("n") private LeagueVersionDetails leagueVersionDetails; public void setVersion(final String version) { this.version = version; } public String getVersion() { return version; } public void setLocale(final String locale) { this.locale = locale; } public String getLocale() { return locale; } public void setCdnUrl(final String cdnUrl) { this.cdnUrl = cdnUrl; } public String getCdnUrl() { return cdnUrl; } public void setDd(final String dd) { this.dd = dd; } public String getDd() { return dd; } public void setLg(final String lg) { this.lg = lg; } public String getLg() { return lg; } public void setCss(final String css) { this.css = css; } public String getCss() { return css; } public void setProfileIconMax(final Integer profileIconMax) { this.profileIconMax = profileIconMax; } public Integer getProfileIconMax() { return profileIconMax; } public void setStore(final String store) { this.store = store; } public String getStore() { return store; } public void setLeagueVersionDetails(final LeagueVersionDetails leagueVersionDetails) { this.leagueVersionDetails = leagueVersionDetails; } public LeagueVersionDetails getLeagueVersionDetails() { return leagueVersionDetails; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final LeagueVersion that = (LeagueVersion) o; if (locale != null ? !locale.equals(that.locale) : that.locale != null) return false; if (version != null ? !version.equals(that.version) : that.version != null) return false; return true; } @Override public int hashCode() { int result = version != null ? version.hashCode() : 0; result = 31 * result + (locale != null ? locale.hashCode() : 0); return result; } @Override public String toString() { return "version=" + version + ", locale=" + locale; } } <file_sep>package hu.tewe.letslearnlol.datagatherer.leagueversion; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; /** * @author: tewe */ public class LeagueVersionDao { public static final String EUW_REALM_JSON_URL = "http://ddragon.leagueoflegends.com/realms/euw.json"; private ObjectMapper objectMapper; private URL url; private Logger logger = LoggerFactory.getLogger(LeagueVersionDao.class); public LeagueVersionDao(final ObjectMapper objectMapper) { Assert.notNull(objectMapper, "Parameter 'objectMapper' should not be null"); this.objectMapper = objectMapper; try { url = new URL(EUW_REALM_JSON_URL); } catch (MalformedURLException e) { e.printStackTrace(); } } public LeagueVersion getLeagueVersion() { LeagueVersion leagueVersion; try { leagueVersion = objectMapper.readValue(url, LeagueVersion.class); } catch (IOException e) { logger.error("Couldn't access URL {}, cause: {}", url, e.getMessage()); leagueVersion = new LeagueVersion(); } return leagueVersion; } } <file_sep>package hu.tewe.letslearnlol.spikes.jsonparser; import hu.tewe.letslearnlol.datagatherer.leaguechampion.LeagueChampionDetails; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; import java.net.URL; /** * @author: tewe */ public class ChampionJsonParserSpike { public static void main(String[] args) throws IOException { /* JSON provider */ URL url = new URL("http://ddragon.leagueoflegends.com/cdn/4.10.7/data/en_US/champion/Ahri.json"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); LeagueChampionDetails leagueChampionDetails = mapper.readValue(url, LeagueChampionDetails.class); System.out.println(leagueChampionDetails); /* Get all computers */ // Object json = mapper.readValue(url, Object.class); // JsonNode rootNode = mapper.readValue(url, JsonNode.class); // JsonNode champion = rootNode.get("data").get("Ahri"); // JsonFactory jsonFactory = new JsonFactory(); // JsonParser jsonParser = jsonFactory.createJsonParser(url); // while (jsonParser.nextToken() != null) { // if ("Ahri".equals(jsonParser.getCurrentName())) { // Object object = mapper.readValue(jsonParser, Object.class); // System.out.println(object); // } // } /* Print each computer (previously overriding "toString()" method) */ // System.out.println(mapper.writeValueAsString(champion)); } } <file_sep>package hu.tewe.letslearnlol.datagatherer.leaguechampion; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author: tewe */ public class LeagueChampionDetails { private String id; private String key; private String name; @JsonProperty("partype") private String parType; private ChampionDetailsInfo info; public void setId(final String id) { this.id = id; } public String getId() { return id; } public void setKey(final String key) { this.key = key; } public String getKey() { return key; } public void setName(final String name) { this.name = name; } public String getName() { return name; } public void setParType(final String parType) { this.parType = parType; } public String getParType() { return parType; } public ChampionDetailsInfo getInfo() { return info; } public void setInfo(final ChampionDetailsInfo info) { this.info = info; } @Override public String toString() { return "LeagueChampionDetails{" + "id='" + id + '\'' + ", key='" + key + '\'' + ", name='" + name + '\'' + '}'; } } <file_sep>package hu.tewe.letslearnlol.datagatherer.leagueversion; import com.fasterxml.jackson.annotation.JsonProperty; import org.testng.Assert; import org.testng.annotations.Test; import java.lang.reflect.Field; /** * @author: tewe */ public class LeagueVersionDetailsTest { @Test public void testInit() throws Exception { LeagueVersionDetails leagueVersionDetails = new LeagueVersionDetails(); leagueVersionDetails.setItem("4.1.2"); leagueVersionDetails.setRune("4.1.2"); leagueVersionDetails.setMastery("4.1.2"); leagueVersionDetails.setSummoner("4.1.2"); leagueVersionDetails.setChampion("4.1.2"); leagueVersionDetails.setProfileIcon("4.1.2"); leagueVersionDetails.setLanguage("3.14.41"); Assert.assertEquals(leagueVersionDetails.toString(), "item=4.1.2, rune=4.1.2, mastery=4.1.2, summoner=4.1.2, champion=4.1.2, profileIcon=4.1.2, language=3.14.41"); } @Test public void testLeagueVersionDetailsShouldHaveJsonAnnotations() throws Exception { Class<?> classToVerify = LeagueVersionDetails.class; Field field = classToVerify.getDeclaredField("profileIcon"); Assert.assertEquals(field.getAnnotation(JsonProperty.class).value(), "profileicon"); } } <file_sep>package hu.tewe.letslearnlol.datagatherer.leagueversion; import com.fasterxml.jackson.annotation.JsonProperty; import org.testng.Assert; import org.testng.annotations.Test; import java.lang.reflect.Field; import java.util.Locale; /** * @author: tewe */ public class LeagueVersionTest { @Test public void testToString() throws Exception { LeagueVersion leagueVersion = new LeagueVersion(); leagueVersion.setVersion("4.1.2"); leagueVersion.setLocale(Locale.US.toString()); leagueVersion.setCdnUrl("http://ddragon.leagueoflegends.com/cdn"); leagueVersion.setDd("3.14.41"); leagueVersion.setLg("0.152.55"); leagueVersion.setCss("0.152.55"); leagueVersion.setProfileIconMax(28); leagueVersion.setStore(null); leagueVersion.setLeagueVersionDetails(new LeagueVersionDetails()); Assert.assertEquals(leagueVersion.toString(), "version=4.1.2, locale=en_US"); } @Test public void testEqualsAndHashCode() throws Exception { LeagueVersion leagueVersion1 = new LeagueVersion(); leagueVersion1.setVersion("1"); leagueVersion1.setLocale(Locale.US.toString()); LeagueVersion leagueVersion1b = new LeagueVersion(); leagueVersion1b.setVersion("1"); leagueVersion1b.setLocale(Locale.US.toString()); LeagueVersion leagueVersion2 = new LeagueVersion(); leagueVersion2.setVersion("2"); leagueVersion2.setLocale(Locale.US.toString()); Assert.assertEquals(leagueVersion1, leagueVersion1b); Assert.assertEquals(leagueVersion1.hashCode(), leagueVersion1b.hashCode()); Assert.assertNotEquals(leagueVersion1, leagueVersion2); } @Test public void testLeagueVersionShouldHaveJsonAnnotations() throws Exception { Class<?> classToVerify = LeagueVersion.class; Field field = classToVerify.getDeclaredField("version"); Assert.assertEquals(field.getAnnotation(JsonProperty.class).value(), "v"); field = classToVerify.getDeclaredField("locale"); Assert.assertEquals(field.getAnnotation(JsonProperty.class).value(), "l"); field = classToVerify.getDeclaredField("cdnUrl"); Assert.assertEquals(field.getAnnotation(JsonProperty.class).value(), "cdn"); field = classToVerify.getDeclaredField("profileIconMax"); Assert.assertEquals(field.getAnnotation(JsonProperty.class).value(), "profileiconmax"); field = classToVerify.getDeclaredField("leagueVersionDetails"); Assert.assertEquals(field.getAnnotation(JsonProperty.class).value(), "n"); } } <file_sep>package hu.tewe.letslearnlol.datagatherer.leaguechampion; import com.fasterxml.jackson.databind.ObjectMapper; import org.mockito.Mock; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.net.URL; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; /** * @author: tewe */ public class LeagueChampionDaoTest { @Mock private ObjectMapper objectMapper; @BeforeClass public void beforeClass() throws Exception { initMocks(this); } @Test public void testInit() throws Exception { LeagueChampionDao leagueChampionDao = new LeagueChampionDao( "http://ddragon.leagueoflegends.com/cdn/4.11.3/data/en_US/champion/", objectMapper); LeagueChampionDetails expectedLeagueChampionDetails = new LeagueChampionDetails(); expectedLeagueChampionDetails.setId("123"); when(objectMapper.readValue(isA(URL.class), isA(Class.class))).thenReturn(expectedLeagueChampionDetails); LeagueChampionDetails leagueChampionDetails = leagueChampionDao.queryChampion("Ahri"); Assert.assertEquals(leagueChampionDetails, expectedLeagueChampionDetails); } } <file_sep>package hu.tewe.letslearnlol.datagatherer.leaguechampion; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; /** * @author: tewe */ public class LeagueChampionDao { private final static Logger logger = LoggerFactory.getLogger(LeagueChampionDao.class); private final String url; private final ObjectMapper mapper; public LeagueChampionDao(final String url, final ObjectMapper mapper) { this.url = url; this.mapper = mapper; } public LeagueChampionDetails queryChampion(String name) { LeagueChampionDetails leagueChampionDetails = new LeagueChampionDetails(); try { String championUrl = this.url + name + ".json"; logger.info("Champion {} url {}", name, championUrl); URL url = new URL(championUrl); JsonNode jsonNode = mapper.readTree(url); JsonNode championNode = jsonNode.findValue(name); leagueChampionDetails= mapper.treeToValue(championNode, LeagueChampionDetails.class); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return leagueChampionDetails; } }
d21a59cf0560eec850d1e08af5a780d2dae44801
[ "Java" ]
8
Java
tewecske/letslearnlol
0100f2f4fe997eaddcd75e34106cb86ce87e3a1e
166dd0b09b9a09262cd286dd179178563708869f
refs/heads/master
<repo_name>MartijnNieuwenhuizen/personal-fed<file_sep>/src/static/js/utils/pageNavigation.js import getPageHTML from './getPageHTML' const updateHistory = url => { // @Improvement, use push and pop state to handle navigation with JS and add motion // history.pushState(null, '', url) window.location = url } export const navigateToNextPage = mainElement => async url => { const nextPageHTML = await getPageHTML(url) if (!nextPageHTML) { return } const newMainElement = nextPageHTML.querySelector('main') mainElement.innerHTML = newMainElement.innerHTML updateHistory(url) } <file_sep>/src/articles/2-ways-of-managing-layout-in-a-design-system.md # 2 ways of managing layout in a design system A design system is a way to create and manage a cohesive design. Each component in a design system is meticulously created, tested and adjusted to fit the brand and the platform’s need. But what about the glue that sticks all these components together, the layout? How should you manage this? And what happens if you don’t!? ## What happens if you don’t manage your layout Let’s start with the latest question, **"What happens if you don’t manage your layout"**. In the first weeks of development, you won't notice anything, it’s when you start making changes further into the project, that you discover the mistake(problem). If you have no system to make sure the components on the page are evenly distributed, you will end up with a messy design because changing and updating elements has become tough. For instance; you want to change the distance between each section on the page, but find yourself updating the same value in multiple files. Eventually, you will end up with an unmanageable project where updates take way to much time. If you achieve to create and maintain a consistent layout, you will end up with a design where the visual hierarchy is clear and where changes to the layout are simple and quick. ### What is "layout"? So, how should you do this? To be able to answer this question I first want to explain the concept of "layout" to you. A layout exists out of three main elements. Constrains, spacing and flow. ### Constrains Constrains are the maximum sizes, either horizontally and vertically. You can think of the maximum width of a text or the max width of a section inside of a colored block on the homepage. Theses values will make sure your design won’t stretch too far on larger screens and fluidly wrap if there is space that allows it. ### Spacing Spacing is the space between each element in the layout. They make clear what content belongs together and whatnot. They also create white-space and calmness into your design. ### Flow Flow controls how elements wrap. This is only relevant in a fluent design where elements have the opportunity to wrap. Therefore the flow relies on the constraints of each element. ### The difference between layout and a grid A grid is always a layout but a layout isn’t always a grid. This is important to understand the solution in the next chapter. A grid always contains the three elements of layout (constrains, spacing and flow). But when a layout doesn’t contain any flow, it’s not a grid and you can create the layout differently. ## How to manage your layout There are two ways I manage my layouts. Both implementations are very different but can be used in the same project. They are both used in different scenarios. ### Make all values reusable If you want to start with your layout, you should first set all the different values that you need as variables. Theses values will probably match the three elements of the layout. This is how I do it. ### Constrains I want to have different constraints for different types of elements. One for large elements like articles, carousels, etc. One for elements like text, images and one for small elements like cards. I use t-shirt size values like s, xl, m, etc for this because it’s easy to add them and clear when you have too many of them. ```CSS :root { —constrain-l: 50rem; —constrain-m: 27rem; —constrain-s: 10rem; } ``` Next to these t-shirt size values I also set a value for the text constrain that takes a t-shirt size constrain as its value. ```CSS :root { —max-text: var(—constrain-m); } ``` ### Spacings The same system is used to create the spacings, only I start with more than three values. Often there is a certain scale in for these values (like you would have with typography). It's important to discuss these values with your design team before setting them. Because changing them after a while will affect a lot of the designs. ```CSS :root { —spacing-xl: 12.5rem; —spacing-xl: 9rem; —spacing-l: 5.5rem; —spacing-m: 2.3rem; —spacing-s: 1.125rem; —spacing-xs: .3rem; —spacing-xxs: .1rem; } ``` These values rule your design. Therefore, I only use one of these values to declare the spacing between elements. Only if the design team has a very good explanation for them I will create a different value as exception. ### Flow The flow is something I don’t set in variables as that’s already done by CSS itself. There is no need to create a class for justifying items. ## Manage your layout by CSS classes For a simple layout (like blocks stacked on each other) I use CSS classes to control it. You can see them as utility classes. To control the spacing, I create three variables that reflect the correct spacing. Each value is assigned to the correct class that indicates the type of element. The names are `.page-element`, `.section-element` and `.text-element`. For the constrains I do the same. `.page-constrain`, `.section-constrain` and `.text-constrain`. ### The advantages By setting the spaces and constrains with classes, you only have to update one value to affect the layout of the entire website. Because they are set as CSS classes, you can manage the layout entirely from your HTML. No need for components to have any constrains. You can wrap anything in a `div` that contains a layout class and the component will fit nicely into the layout. A small example of a template that handles the layout with CSS classes. ```HTML <main class=“page-constrain”> <section class”page-element”> <h1>Main title</h1> <p>Some nice text</p> </section> <section class”page-element”> <h2>Section title</h2> <p>Some nice text</p> <div class”section-constrain section-element”> // Some component </div> <div class”section-constrain section-element”> // Some component </div> <div class”section-constrain section-element”> // Some component </div> </section> </main> ``` This way you have a nice separation between the components and the layout. Where the components don't have to concern where they are placed on the page. They just have to stretch to the outsides of the box. ### The disadvantage If a layout needs some more configuration or contains the flow aspect, there are better-suited solutions. That's because it's error-prone to add configuration (CCS class or data-element) to each direct child in the layout. It's easy to forget one direct child and break your layout. ## Manege your layout with components If a layout needs a lot of configuration, managing it by components it the way to go. Also if your layout contains Flow (grids), I use components to control the layout. Just a personal preference, because it's clear in your design system you are talking about a grid, not just the basic layout. If there are not too many of these components, I usually call them grid-alpha, grid-beta, etc. If there are too many it’s a good idea to align the naming of the grids with the design team for consistency. ### The implementation A layout component will receive multiple items that need to be rendered inside the grid. They are called grid items. The grid will perform a simple loop and render each component. ```HTML <div class=“grid-alpha”> {for each grid item} <div class=“grid-alpha__item”> // Render the component </div> {end for each grid item} </div> ``` You can use the same variables that are already set for the spacings between each grid item. ### The advantages The big advantage of using a component instead of classes is the way you can control the exceptions or setting. For instance, you have a very basic grid layout, but the size of the gutters can differ. This could be set by a property of the component. A lot of the times, there are multiple exceptions. Therefore you don’t want to add a class for each exception. Because grids have control over each element in the grid, it’s able to manage the flow of the grid items. This is not possible with the CSS classes approach because that’s not in control over all the items within it. The way that grids have the same code interface is also a benefit. Each grid will loop. Therefore it’s very easy to swap grids, without changing anything else. Just change the name grid-alpha to grid-beta and another interface will appear. ## Conclusion It’s only when you start making changes that you discovered that your layout isn’t managed properly. Instead of applying a fix on a single place, you have to update multiple files. This is where you could have managed your layout in a better manner. These are two good approaches that can be used beside each other. Managing your layout with CSS classes and with components. CSS classes should be used for layouts without any flow. The different CSS classes manage the distance between the elements (spacing) and the maximum size (constrains). These classes can be used anywhere you want. If there is a flow aspect to the layout, it’s a better idea to use a component. A component can also receive settings and is very easy to swap with another grid because the code interface is the same. <file_sep>/src/blogs/personal-development-mission.md # My personal development mission My main goal is to **help** people. This should always be done by **adding value**. The solution should be clearer than the previous solution. Never complicate but **simplify.** If something is not clear, **ask why,** no matter who you are talking to. And never accept the answer **"That's just how we do it"**. With that, only build things you **yourself** truly believe in have **lot’s of fun** while doing this! <file_sep>/src/components/layout-article/flow-in-layout/FlowInLayout.js class FlowInLayout { constructor(element, options) { this._element = element this._options = options this._getElements() this._setEventListeners() // Bindings this._handleClick = this._handleClick.bind(this) this._makeTriggersInactive = this._makeTriggersInactive.bind(this) this._setType = this._setType.bind(this) } static _makeTriggerActive(trigger) { trigger.setAttribute('data-active', true) } _getElements() { this._triggers = Array.from( this._element.querySelectorAll(this._options.triggers) ) this._target = this._element.querySelector(this._options.target) } _setEventListeners() { this._triggers.forEach(trigger => trigger.addEventListener('click', e => this._handleClick(e)) ) } _handleClick(e) { this._setType(e.target.dataset.value) this._makeTriggersInactive() FlowInLayout._makeTriggerActive(e.target) } _makeTriggersInactive() { this._triggers.forEach(trigger => trigger.removeAttribute('data-active', true) ) } _setType(value) { this._target.setAttribute('data-type', value) } } export default FlowInLayout <file_sep>/src/components/article-prev/ArticlePrev.js import { navigateToNextPage } from '../../static/js/utils/pageNavigation' export default class ArticlePrev { constructor(element, options) { this._element = element this._options = options this._handleClick = this._handleClick.bind(this) this._handleTransitionEnd = this._handleTransitionEnd.bind(this) this._handleAnimationEnd = this._handleAnimationEnd.bind(this) this._newUrl = '' this._newRootHTML = '' // this._cacheElements() // this._setListeners() } _cacheElements() { const { rootElement, triggerElement, transitionElement } = this._options this._rootElement = document.querySelector(rootElement) this._triggerElement = this._element.querySelector(triggerElement) this._transitionElement = this._element.querySelector(transitionElement) } _setListeners() { this._triggerElement.addEventListener('click', this._handleClick) } _setTransitionEndListener() { this._transitionElement.addEventListener( 'transitionend', this._handleTransitionEnd ) } _removeTransitionEndListener() { this._transitionElement.removeEventListener( 'transitionend', this._handleTransitionEnd ) } _handleClick(event) { event.preventDefault() this._newUrl = event.target.href this._setTransitionEndListener() this._element.setAttribute('data-animate', true) } _handleTransitionEnd() { navigateToNextPage(this._rootElement)(this._newUrl) this._removeTransitionEndListener() this._setTransitionHTML() } _handleAnimationEnd() { this._rootElement.removeEventListener( 'animationend', this._handleAnimationEnd ) } // Set custom HTML to innerHTML as animate out animation _setTransitionHTML() { this._rootElement.innerHTML = ` <div class="foo"> <div class="foo-animation"></div> </div> ` this._rootElement.addEventListener('animationend', this._handleAnimationEnd) } } <file_sep>/src/blogs/personal-coding-guidelines.md # My coding guidelines ## The code itself Code should be **simple.** If it does too much, split it up. Don’t just add code, ask yourself if it’s **simple**, **flat**, **consistent** and **self explanatory**. If not, **change it!** To **simplify**, use **describing names**, and keep the code flat. This way the code is going to **tell a story**. ## The coding mentality Always **enhance** the code you are working on. The fact that you wrote it a while ago, or somebody else wrote it, **doesn’t** mean you can’t improve it. Apply the **boyscout rule** a.k.a. **improve**! Code should be **as simple as possible**. Never **complicate** but **simplify**. Start by learning the **basics** and you will end up loving them. By truly understanding the basics, you can more easily start **learning** new things. Because everything is build upon those basics. <file_sep>/tasks/renderBlogs.js import { blogs as blogsConfig } from '../config' import renderMarkDown from './renderMarkDown' export const renderBlogs = () => renderMarkDown(blogsConfig) <file_sep>/tasks/renderArticles.js import { articles as articlesConfig } from '../config' import renderMarkDown from './renderMarkDown' export const renderArticles = () => renderMarkDown(articlesConfig) <file_sep>/src/static/js/utils/getPageHTML.js export default async url => { try { const response = await fetch(url) const responseAsText = await response.text() const parser = new DOMParser() return parser.parseFromString(responseAsText, 'text/html') } catch (err) { console.warn('Error in fetching next page HTML: ', err) return null } } <file_sep>/readme.md # Personal Front-end <file_sep>/backstop-config.js const glob = require('glob') const options = { src: 'dist', folder: 'templates', protocol: 'http', baseUrl: 'localhost', port: '3000' } const { src, protocol, baseUrl, port } = options const viewports = [ { label: 'small', width: 320, height: 480 }, { label: 'medium', width: 768, height: 768 }, { label: 'xlarge', width: 1500, height: 900 } ] const getLabel = filename => filename.match(`${src}/(.*).html`)[1] const getRoute = filename => filename.replace(`${src}/`, '') const getUrl = filename => `${protocol}://${baseUrl}:${port}/${getRoute(filename)}` const htmlFiles = glob.sync(`${src}/**/*.html`) const scenarios = htmlFiles.map(file => ({ label: getLabel(file), url: getUrl(file) })) module.exports = { id: 'Personal website', viewports, scenarios, paths: { bitmaps_reference: 'backstop_data/bitmaps_reference', bitmaps_test: 'backstop_data/bitmaps_test', casper_scripts: 'backstop_data/casper_scripts', html_report: 'backstop_data/html_report', ci_report: 'backstop_data/ci_report' }, casperFlags: [], engine: 'puppeteer', report: ['browser'], debug: false } <file_sep>/src/blogs/lets-all-stop-creating-the-same-dull-things.md # Let's all stop creating the same dull things I'm fed up with the default 12 column grid, centered text and three blocks to represent your business standpoints. Why, while we have so much room for creativity, keep falling back to the same design principles on the web? Can it be that most designers are not familiar with the new possibilities on the web? Didn't we (as FED's) inform them about these changes? Or are de clients the ones who don't dare to take a chance here? I'm not sure and guess that it - like always - differs in each case. But to be able to do something about this, I want to learn more about design outside of the web. I, therefore, decided to focus on magazine print layout and the art direction that's combined with these designs. My challenges are to translate these thoughts to the web and create examples that prove that it **is possible** and is something that will add value to your design or brand. You can find a series of experiments on my playground [my playground](/playground) <file_sep>/src/components/layout-article/distance-between-elements/DistanceBetweenElements.js class DistanceBetweenElements { constructor(element, options) { this._element = element this._options = options this._getElements() this._setEventListeners() // Bindings this._handleClick = this._handleClick.bind(this) this._makeTriggersInactive = this._makeTriggersInactive.bind(this) this._setType = this._setType.bind(this) } static _makeTriggerActive(trigger) { trigger.setAttribute('data-active', true) } _getElements() { this._triggers = Array.from( this._element.querySelectorAll(this._options.triggers) ) this._target = Array.from( this._element.querySelectorAll(this._options.target) ) } _setEventListeners() { this._triggers.forEach(trigger => trigger.addEventListener('click', e => this._handleClick(e)) ) } _handleClick(e) { this._setType(e.target.dataset.value) this._makeTriggersInactive() DistanceBetweenElements._makeTriggerActive(e.target) } _makeTriggersInactive() { this._triggers.forEach(trigger => trigger.removeAttribute('data-active', true) ) } _setType(value) { this._target.forEach(target => target.setAttribute('data-type', value)) } } export default DistanceBetweenElements <file_sep>/src/blogs/manage-dependencies-for-a-function-inside-a-map.md # Manage dependencies for a function inside a map I often put the functions within a map into separate files. They are there for reusability and easiness to test. This is very nice until you need additional data to function within the map. Take the following example. You have two entities in your store, people and books. What if you want to show the first name of a person and all the titles of the books he has read. You would like to map over the people and combine the first name and all titles of the books he had read into a separate object. A first approach would look something like this: ```javascript const state = { people: [ { id: "12345", firstName: "John", lastName: "Becker", booksRead: ['abc', '123', 'xy9'] } ], books: { abc: { title: "The Hobbit", pages: 879, } 123: { title: "Harry Potter", pages: 462, } xy9: { title: "The Da Vinci Code", pages: 597, } } } const people = state.people.map(person => addBookTitlesToPerson(person, state.books)) ``` But this doesn't look nice to me. Another way is to retrieve the state in the file itself, but that would make testing harder and make is less configurable. Next to that, getting the state on a lot of locations could potentially decrease the performance of your app. I also miss the option for configuration in both cases. Maybe you want to pass in the books a bit earlier or it makes more sense to do it in another location of your app. Luckily there is another way of doing this that is more functional oriented. This makes use of a pattern called **Currying**, this way the function doesn't take all it's arguments up-front, but gradually receives them where it can. ```javascript // Same format as above const state = { ... } const people = state.people.map(addBookTitlesToPerson(state.books)) // Or separated const addBookTitlesToPersonWithBooks = addBookTitlesToPerson(state.books) const people = state.people.map(addBookTitlesToPerson) ``` In that case, addBookTitlesToPerson.js would look something like this: ```javascript // addBookTitlesToPerson.js export default books => person => { const bookTitlesRead = person.booksRead.map(bookId => books[bookId].title) return { ...person, bookTitlesRead } } ``` <file_sep>/src/articles/working-agile-from-a-design-team-perspective.md # Working Agile, from a design team perspective Written for Mirabeau.nl There are a lot of articles published about Agile, but almost all of them feel like they are written from a management perspective and not a member of the Agile development team. I am Martijn, a Front-end Developer at Mirabeau and I would like to share my experiences with a truly Agile workflow. Focus is the key in this workflow, but how to create this? Next to focus, it’s also important to dare to make mistakes. As long as you can learn from them and improve the product with these new insights. ## Focus A team needs focus to work in the most optimal way and deliver the best product for the user. If there is no focus, it’s much easier to work on topics that don’t add sufficient value to the user. A lack of focus can also create separation in a team. Therefore, focus - to my opinion - helps a team to perform and deliver the best product. ## One goal The key to create focus for a team is to have one clear goal. If there are multiple goals for a development team, team members can pick up each goal separately and work on them as individuals. In case there is only one goal, the team is encouraged to collaborate if they want to finish this one goal. Lines between Back-end, Front-end, and Design begin to blur a bit because there is only one thing to strive for. ![List of features with a line of MVP](/static/img/articles/agile/mvp.jpg 'MVP') ### Prioritization This single goal will also help with prioritizing the sprint or backlog with the team. At my latest client, my team created a single list of features/stories. We prioritize this list based on the goal and dependencies. After that, we draw one big line at the point where we think our list of features could function as the first version of a product, also called a Minimal Viable Product (MVP). ![Reprioritized list of features with a line of MVP](/static/img/articles/agile/reprioritize.jpg 'reprioritize') ### Adjusting Of course, you are always learning. Usually, when the first set of features is delivered, new insights will come up. Maybe the stakeholders and the team didn’t fully understand each other. That will become clear in the first demo or after a quick user test. It can become clear that a part of the navigation doesn’t work well or that the login flow is not very intuitive. This is the perfect moment to adjust. Because you have only one goal, it’s much easier to adjust and re-prioritize. Just repeat the flow described above and you have a new prioritized backlog. This could also mean a feature will disappear or become less important due to another feature that already provided a solution. ## Going live We - my team at my latest client - had a deadline, but the pressure wasn’t very high due to the fact we didn’t need to deliver the entire product. Only the minimal amount of features. Only the ones we prioritized as a team and put above the line of MVP. The rest was seen as an enhancement. You need a good product owner and experienced stakeholders to draw a realistic line because it’s quite difficult not to see everything as a must-have. For example: If you want to make it possible for a user to put something in a shopping basket, you could easily implement this without reloading the page. Add a shopping basket animation and show a pop-up in case the user wants to pay directly, or continue shopping. The minimal version only states: ”if the user puts an item in the basket, a call to the back-end is made and the page will get loaded again”. So, possible enhancements are: Prevent page refresh - Show animation when adding to basket - Show pop-up after putting something in the basket Of course, this is different for each brand or product. For our project, this was the minimal version which the stakeholders could approve on. ## Learn by failing We ended up with a richer product than just the MVP that did not contain all must-have features. Along the way, we sometimes failed but learned lessons from our failures and improved based on those lessons. Earlier on I already talked about adjusting based on new insights. In a lot of teams, failure is seen as something not desirable. However for a team to be able to learn, it's critical to accept failure. Maybe even encourage it! At the college I attended, a sign "Fail often, fail hard" was hanging above the door. You will learn by failing therefore, they encouraged us to try. Sometimes we failed, but learned from that. If the product is built with scalability and quick development in mind, it’s not too big of a hit for a team to fail to learn and adjust. ### Our fail Our team failed very hard in the first sprint. We delivered a first version of an advanced search and some search results. This was the core of our product. The search form contained, among other things, a date input. For us, there was only one date important so we created just one date input. This was a bit different for our users. They didn’t want to search for something on a specific date, rather within a date range. And with that, not on all days, but only on specific days on the week. We got these new insights after the demo of the first sprint. We proudly performed a search and showed the search results. Everybody was happy until somebody asked; “And what if I want to buy 60 tickets for each Monday for half a year long? Then I need to search 60 times”. This would mean nobody would use our new tool. So we went back to the drawing board and came up with three new enhancements: - Enhance search with two dates to create a start and end date - Enhance search with "days of the week" filter - Enhance search results to show results multiple results They instantly became the features on the top of our backlog because this was the core of our product. After just half a sprint, the possibility to search in a specific period on specific days of the week was done. ![A sketch of the different versions of the application](/static/img/articles/agile/versions.jpg 'Versions') If we didn't work in an agile process and if we didn't feel that we could fail, learn and adjust, the product would contain a search with one date input and no value to the user. This also wouldn’t have been possible in the case that: - We used waterfall or another process that isn't flexible - Our PO and stakeholders created a scope that was too large and had no room for adjustments, failure, and improvements - We had multiple goals and therefore didn’t have full focus on the core functionalities - We worked with scrum, but never looked back at what we made - We didn’t involve stakeholders and users into our demo’s/process - We didn’t allow ourselves to try, fail and don’t be afraid to learn from this ## To summarize For a team, it's very important to have only one goal. This creates a better collaborating team with a better focus. It also helps in prioritizing the backlog and making adjustments to it. Next to one goal, the possibility and mindset of failing is also very important. If a team feels that the possibility to fail is allowed, a better product can be created. Because a team can look back, review and adjust where needed, a truly agile workflow will help the team to create the best solutions for the user. And not just deliver a product with the requirements that were set at the beginning of the process. This all is only possible if there is only one goal that the entire team can strive to make.
d3ab8fd23bf77f3df8f057a52cf2b59e65dd125f
[ "JavaScript", "Markdown" ]
15
JavaScript
MartijnNieuwenhuizen/personal-fed
bc0216ce78c98df6d48b736c773f42408fb305e8
7513e43985724a47d1f6ec08e2e0cb393b8dfcd8
refs/heads/master
<file_sep>// // FoodOption.swift // FoodSpinner // // Created by <NAME> 2019 on 5/7/19. // Copyright © 2019 <NAME> 2019. All rights reserved. import UIKit class FoodOptions: UIViewController { //OUTLETS AND VARIABLES @IBOutlet weak var tableView: UITableView! var userDefaults = UserDefaults.standard var options = [String]() //INITIAL override func viewDidLoad() { super.viewDidLoad() var savedOptions = userDefaults.array(forKey: "savedOptions") if !(options.isEmpty) { //adds saved options from last time for option in savedOptions! { add((option as! String)) } } } @IBAction func onAddTapped(_ sender: Any) { let alert = UIAlertController(title: "Add a Option", message: nil, preferredStyle: .alert) alert.addTextField { (optionTextField) in optionTextField.placeholder = "option" } let action = UIAlertAction(title: "Add", style: .default) { (_) in guard let option = alert.textFields?.first?.text else {return} print(option) self.add(option) } alert.addAction(action) present(alert, animated: true) } func add(_ option: String) { let index = 0; options.insert(option, at: index) userDefaults.set(options, forKey: "savedOptions") let indexPath = IndexPath(row: index, section: 0) tableView.insertRows(at: [indexPath], with: .left) print(userDefaults.array(forKey: "savedOptions")?.description) } } //EXTENSION extension FoodOptions: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() let option = options[indexPath.row] cell.textLabel?.text = option return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { guard editingStyle == .delete else {return} options.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .automatic) } } <file_sep>// // Spinner.swift // FoodSpinner // // Created by <NAME> 2019 on 5/7/19. // Copyright © 2019 <NAME> 2019. All rights reserved. // import UIKit class Spinner: UIViewController { var userDefaults = UserDefaults.standard @IBOutlet weak var lbl_choice: UILabel! override func viewDidLoad() { super.viewDidLoad() var savedOptions = userDefaults.array(forKey: "savedOptions") } }
6ffbfb2706248fcc7f516c7d41f5cf027943d2be
[ "Swift" ]
2
Swift
jbondad9/FoodSpinner
965b942f2557e7f3ab46a316375e57f92caf1f03
bc8c4b541816bcf0dc0f353cee63b295790dcadb
refs/heads/master
<file_sep>var express = require('express'); var router = express.Router(); var orders = [] router.get('/', function(req, res, next) { res.render('index', {orders}); }); router.get('/form', function(req, res, next) { //console.log(req.query) res.render('form', {}); }); router.post('/form', function(req, res, next) { orders.push({ name: req.body.client, food: req.body.foodName }) //res.render('form', {}); res.status(202).send('Order is made') //res.redirect('/') }); module.exports = router;
266ce1d36d3e9b3a3656f9552fbf3c71277e0763
[ "JavaScript" ]
1
JavaScript
kubines17/myFood
5c5925ec2afcbf634dfc71c53feb6b224706f1d1
5905cc622dd2808cc298181f000cdf2b4638867d
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Article; use App\Http\Model\ArticleCategory; use App\Http\Model\Certificate; use App\Http\Model\Slider; use Barryvdh\Debugbar\Controllers\BaseController; use Illuminate\Http\Request; use Jenssegers\Agent\Agent; use Mews\Captcha\Facades\Captcha; class IndexController extends BaseController { public function index(Request $request) { $data['news_id'] = 2; $data['download_id'] = 5; $data['dynamic_id'] = 3; $data['notice_id'] = 10; $data['category'] = $this->getArticleCategory(); $data['shouye'] = $category = ArticleCategory::where('status', 1)->where('pid', 1)->orderBy('sid', 'asc')->get(); $data['news'] = $this->getArticle($data['news_id']); $data['download'] = $this->getArticle($data['download_id']); $data['dynamic'] = $this->getArticle($data['dynamic_id']); $data['notice'] = $this->getArticle($data['notice_id']); $data['slider'] = $this->getSlider(); return view('index.index', $data); } // 获取幻灯片 function getSlider(){ $slider = Slider::where('status', 1)->orderBy('sid', 'asc')->get(); return $slider; } // 新闻列表 function articleList(Request $request, $category_id=0){ $input = $request->all(); $where = ''; if(isset($input['search'])){ $where['search'] = '%'.$input['search'].'%'; } if(isset($input['type'])){ $where['type'] = $input['type']; } $data['category'] = $this->getArticleCategory(); $current = ArticleCategory::where('status', 1); if( !empty($category_id) ){ $current->where('id', $category_id); $current = $current->first(); $data['currentCategory'] = $current->title; }else{ $data['currentCategory'] = '搜索关键词'; $current = $current->first(); } if( $current->pid == 0 ){ $cid = $category_id; $data['pcategory'] = $data['currentCategory']; }else{ $cid = $current->pid; $pcategory = ArticleCategory::where('id', $cid)->first(); $data['pcategory'] = $pcategory->title; } $data['category_id'] = $category_id; $data['subCategory'] = $this->getArticleCategory($cid); $data['articleList'] = $this->getArticle($category_id, $where); return view('index.lists', $data); } function articleDetails($article_id = 0){ $data['category'] = $this->getArticleCategory(); $data['article'] = Article::where('id', $article_id)->first(); $data['newest'] = Article::where('status', 1)->orderBy('created_at', 'desc')->paginate(10); $data['currentCategory'] = $data['article']->hasOneToCategory()->first(); return view('index.details', $data); } // 获取新闻类别 function getArticleCategory($pid = 0){ $category = ArticleCategory::where('status', 1)->where('pid', $pid)->where('id', '<>', 1)->orderBy('sid', 'asc')->get(); return $category; } // 获取新闻 private function getArticle($category_id, $where = []){ $articles = Article::where('status', 1); if( !empty($category_id) ){ $articles->where('category_id', $category_id); } $type = 'title'; if( is_array($where) && !empty($where) ) { if ($where['type'] == 1) { $type = 'title'; } else if ($where['type'] == 2) { $type = 'content'; } $articles->where($type, 'like', $where['search']); } $articles = $articles->orderBy('updated_at', 'desc')->paginate(20); return $articles; } function notReady(){ $data['category'] = $this->getArticleCategory(); return view('index.notready', $data); } public function zhengjian() { $agent = new Agent(); $data['category'] = $this->getArticleCategory(); $data['page_class'] = $agent->isMobile() || $agent->isTablet() ? 'mobile_page' : 'web_page'; if( $agent->isMobile() || $agent->isTablet() ){ return view('examine.zhengjian_mobile', $data); }else { return view('examine.zhengjian', $data); } } // 证书查询 function search(Request $request){ try{ $input = $request->all(); if( !Captcha::check($input['valid_code']) ){ throw new \Exception("验证码输入错误"); } $candidate = Certificate::where('id_no', trim($input['id_no']))->where('name', trim($input['name']))->get(); if( $candidate->count() <= 0 ){ throw new \Exception("暂无该考生信息"); } return backJson(true, $candidate); } catch (\Exception $e) { return backJson(false, $e->getMessage()); } } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Slider; use Illuminate\Http\Request; use Illuminate\Support\Facades\URL; class SliderController extends Controller { public function index(Request $request) { $data ['category'] = 'articles'; $data ['subCategory'] = 'slider'; $data ['breadcrumb'] = $this->breadcrumb(); $data ['sliderData'] = $this->getSlider('all'); return view('slider.index', $data); } // 获取某一个幻灯片的信息 function getOne(Request $request){ $input = $request->all(); $category = Slider::where('id', $input['id'])->first(); return backJson(true, $category); } // 获取幻灯片 function getSlider($cate = 'all'){ if($cate != 'all') { $where = ['status'=>1]; }else{ $where = []; } $sliderList = Slider::where($where)->orderBy('sid', 'asc')->get()->toArray(); $list = $sliderList; $str = ''; $str .= '<ol class="dd-list">'; foreach ($list as $li) { $str .= $this->genTreeStr($li); } $str .= '</ol>'; return $str; } // 幻灯片数据拼接 function genTreeStr($data){ $str = '<li class="dd-item" data-id="'.$data['id'].'">'; $str .= '<div class="dd-handle dd2-handle">' ; $str .= '<i class="drag-icon ace-icon fa fa-arrows bigger-125"></i>'; $str .= '</div>'; $str .= '<div class="dd2-content">' . $data['title']; if( !$data['status'] ){ $str .= ' <label class="label label-danger label-sm" style="margin:0;">已禁用</label>'; } $str .= '<div class="pull-right action-buttons">'; $str .= '<a class="blue edit_slider" data-id='.$data['id'].' href="javascript:;">'; $str .= '<i class="ace-icon fa fa-pencil bigger-130"></i>'; $str .= '</a>'; $str .= '<a class="blue del_slider" data-id='.$data['id'].' href="javascript:;">'; $str .= '<i class="ace-icon fa fa-trash-o bigger-130"></i>'; $str .= '</a>'; $str .= '</div>'; $str .= '</div>'; $str .= '</li>'; return $str; } // 添加编辑幻灯片 function addSlider(Request $request){ try{ $input = $request->all(); $sliderData = [ 'title' => $input['title'], 'url' => $input['url'], 'src' => $input['src'], 'status' => 1, 'sid' => $input['sid'], ]; if( isset($input['id']) && !empty($input['id']) ){ Slider::where('id', $input['id'])->update($sliderData); $logType = 'edit'; $_success_txt = '幻灯片编辑成功'; }else{ if( !Slider::create($sliderData) ){ throw new \Exception("系统错误, 幻灯片添加错误"); } $logType = 'add'; $_success_txt = '幻灯片添加成功'; } parent::_save_log('slider', $logType, $input['title']); return backJson(true, $_success_txt); } catch (\Exception $e){ return backJson(false, $e->getMessage()); } } // 保存排序值 function saveSort(Request $request){ try{ $input = $request->all(); $sort = $input['sort']; foreach ($sort as $k=>$so){ Slider::where('id', $so['id'])->update(['sid'=>$k]); } return backJson(true, '保存成功'); } catch (\Exception $e){ return backJson(false, $e->getMessage()); } } public function delete(Request $request) { try { if (!isset($request->id) || empty($request->id)) { throw new \Exception("请选择要删除的幻灯片"); } $slider = Slider::findOrFail($request->id); $title = $slider->title; $slider->delete(); parent::_save_log('slider', 'del', $title); return backJson(true, '幻灯片删除成功'); } catch ( \Exception $e ) { return backJson(false, $e->getMessage()); } } /** * 页面面包屑 * * @return array */ private function breadcrumb() { return [ [ 'url' => URL::route('article.index'), 'title' => '幻灯片' ] ]; } } <file_sep><?php namespace App\Http\Model; use Zizaco\Entrust\EntrustRole; class Role extends EntrustRole { protected $table = 'role'; public $timestamps = false; public $guarded = ['id']; } <file_sep>$(function(){ /************************************************** 题目相关 **************************************************/ // 题目的标题 $(document).off('keyup', '.question_title').on('keyup', '.question_title', function(){ $(".prev_question_title span").text( $(this).val() ); }) // 添加选项 $(document).off('click', '.question_add').on('click', '.question_add', function(){ var op = $(this).parents('.question_option').clone(); op.find(":checkbox").prop('checked', false); op.find(":text").val(""); $(".question_option").parent('.form-group').append(op); var prev_op = $(".prev_question_options > .ques_type_ans:first").clone(); prev_op.find('.lbl .lab_txt').text( '' ); $(".prev_question_options").append(prev_op); reSetChar(); }) // 删除选项 $(document).off('click', '.question_minus').on('click', '.question_minus', function(){ if( $('.question_option').length > 1 ) { var _index = $(this).parents('.question_option').index( ); $(this).parents('.question_option').remove(); $(".prev_question_options > div:eq("+(_index - 1)+")").remove(); }else{ show_msg(false, '请至少保留一个选项哦'); return false; } reSetChar(); }) // 选项文字同步 $(document).off('keyup', '.question_option :text').on('keyup', '.question_option :text', function(){ var _index = $(this).parents('.question_option').index( ); $(".prev_question_options > div:eq("+(_index - 1)+")").find('.lbl .lab_txt').text( $(this).val() ); }) // 正确答案同步 $(document).off('click', '.question_option :checkbox').on('click', '.question_option :checkbox', function(){ var _type = $("input[name='question[question_type]']").val(); var _index = $('.question_option').index( $(this).parents('.form-group') ); if( _type != 2 ) { $(this).parents('.question_option').siblings().find(':checkbox').prop('checked', false); } $(".prev_question_options > div:eq("+(_index)+")").find('.ace').prop( 'checked', $(this).prop('checked') ); }) // 上移 $(document).off('click', '.question_arrow_up').on('click', '.question_arrow_up', function(){ var _index = $(this).parents('.question_option').index( ); var onthis=$(this).parents('.question_option'); var getUp=onthis.prev(":not('label')"); $(onthis).after(getUp); var prev_onthis = $(".prev_question_options > div:eq("+ (_index - 1) +")") var prev_getUp=prev_onthis.prev(); $(prev_onthis).after(prev_getUp); reSetChar(); }) // 下移 $(document).off('click', '.question_arrow_down').on('click', '.question_arrow_down', function(){ var _index = $(this).parents('.question_option').index( ); var onthis=$(this).parents('.question_option'); var getdown=onthis.next(); $(getdown).after(onthis); var prev_onthis = $(".prev_question_options > div:eq("+ (_index - 1) +")") var prev_getdown = prev_onthis.next(); $(prev_getdown).after( prev_onthis ); reSetChar() }) // 保存题目 $(document).off('click', '.save_question').on('click', '.save_question', function(){ var _has_ans = false; $(".question_option :checkbox").each(function(i){ $(this).attr('name', "question[options][answer][" + i + "]"); if($(this).prop('checked')){ _has_ans = true; } }) if( !_has_ans ){ show_msg(false, "请设置正确答案"); return false; } _validForm('.question_form', undefined, question_succ) }) // 考试生成方式 $(document).off('click', '.strategy_type').on('click', '.strategy_type', function() { $(this).addClass('btn-primary').siblings().removeClass('btn-primary') $('input[name="strategy"]').val( $(this).data('value') ); }) /************************************************** 题目相关结束 **************************************************/ // 考题分数 $(document).off('change', '.exam-score').on('change', '.exam-score', function() { var nums = $(this).parent().next().find('.exam-nums').val(); $(this).parent().next().next().text( $(this).val() * nums ); getTotalScore(); }) // 题目书 $(document).off('change', '.exam-nums').on('change', '.exam-nums', function() { var socre = $(this).parent().prev().find('.exam-score').val(); $(this).parent().next().text( $(this).val() * socre ); getTotalScore() }) // 添加评级 $(document).off('click', '.add-grade').on('click', '.add-grade', function() { var _par = $(this).parents('.exam-grade-detail').clone(); var _len = $('.exam-grade-detail').length; _par.find("select:first").attr('name', 'examEval['+ (_len+1) +'][min]') _par.find(":text").attr('name', 'examEval['+ (_len+1) +'][name]') _par.find("select:last").attr('name', 'examEval['+ (_len+1) +'][max]') $(this).parents('.exam-grade-detail').parent().append( _par ); }) // 删除评级 $(document).off('click', '.del-grade').on('click', '.del-grade', function() { if( $('.exam-grade-detail').length <= 1 ){ show_msg(false, '至少保留一个'); return ; } $(this).parents('.exam-grade-detail').remove(); }) }) function reSetChar(){ $(".question_option").each(function(i){ $(this).find('.label_char').text( getChar(i)+'.' ); $(".prev_question_options .ques_type_ans:eq("+ i +")").find('.label_char').text( getChar(i)+'.' ) }) } // 计算总分 function getTotalScore(){ var total = 0; $('.exam-score').each(function(){ var nums = $(this).parent().next().find('.exam-nums').val(); total += $(this).val() * nums }) $('input[name="total_score"]').val( total ); $(".totel_score").text( "总分:"+total ); } // 题目提交完成 function question_succ(){ $(".question_form .modal-footer .btn:last").click(); var p = $("#jqgrid-table-1").jqGrid('getGridParam','page'); $("#jqgrid-table-1").jqGrid('setGridParam', { page: p, }).trigger("reloadGrid"); } /** * ajax 封装方法 * @param url * @param data * @param successfn * @private */ function _ajax(url, data, successfn){ data = (data==null || data=="" || typeof(data)=="undefined")? {"date": new Date().getTime()} : data; $.ajax({ type: 'POST', data: data, url: url, dataType: 'json', beforeSend: function () { show_msg('info', '正在操作, 请稍后...'); }, success: function(data){ show_msg(data.code, data.msg, data.url); if( successfn != null || typeof(successfn)=="function") { successfn(data); } } }); } // 表单验证 function _validForm(obj, _btn, _backFunc){ $(obj).Validform({ tiptype:function(msg,o,cssctl){ console.log(o) if(o.type == 3){ show_msg(false, msg); return ; } else if (o.type==1) { show_msg('info', '正在验证表单信息, 请稍后...'); } }, tipSweep:true, ajaxPost:true, beforeSubmit:function(){ $(_btn).attr('disabled', 'disabled') }, callback:function(data){ $(_btn).removeAttr('disabled'); show_msg(data.code, data.msg, null); if( typeof _backFunc == 'function'){ _backFunc(data); } } }); } // 提示消息 function show_msg(_status, _text, _url){ var _class, _icon; if( !_status ){ _icon = '<i class="fa fa-remove"></i> '; _class = 'gritter-error'; }else if( _status == 'info' ){ _icon = '<i class="fa fa-info"></i> '; _class = 'gritter-info'; }else{ _icon = '<i class="fa fa-check"></i> '; _class = 'gritter-success'; } $.gritter.add({ title: _icon + _text, class_name: _class + " gritter-center" }); if( _url != undefined ){ window.location.href = _url; } return false; } // jqgrid 分页图标 function updatePagerIcons(table) { var replacement = { 'ui-icon-seek-first' : 'ace-icon fa fa-angle-double-left bigger-140', 'ui-icon-seek-prev' : 'ace-icon fa fa-angle-left bigger-140', 'ui-icon-seek-next' : 'ace-icon fa fa-angle-right bigger-140', 'ui-icon-seek-end' : 'ace-icon fa fa-angle-double-right bigger-140' }; $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){ var icon = $(this); var $class = $.trim(icon.attr('class').replace('ui-icon', '')); if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]); }) } //获取页面的高度、宽度 function getPageSize() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else { if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } } var windowWidth, windowHeight; if (self.innerHeight) { // all except Explorer if (document.documentElement.clientWidth) { windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else { if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else { if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } } } // for small pages with total height less then height of the viewport if (yScroll < windowHeight) { pageHeight = windowHeight; } else { pageHeight = yScroll; } // for small pages with total width less then width of the viewport if (xScroll < windowWidth) { pageWidth = xScroll; } else { pageWidth = windowWidth; } arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight); return arrayPageSize; } function getChar(i){ if(i >= 0 && i <= 26){ return String.fromCharCode(65 + i); } }<file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Settings; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\URL; use Exception; class SettingsController extends Controller { /* * 首页 */ public function index() { $data ['category'] = 'base'; $data ['subCategory'] = 'settings'; $data ['breadcrumb'] = $this->breadcrumb(); $settings = Settings::get(); foreach($settings as $setting) { $data[$setting->key] = $setting->val; } //dd($data); return view('settings.index', $data); } /* * 保存参数 */ function save(Request $request) { try { DB::beginTransaction(); $settings = $request->all(); foreach($settings as $key=>$val) { if ($key != '_token') { $this->_save($key, $val); } } DB::commit(); return backJson(true, '保存成功'); } catch ( Exception $e ) { DB::rollback(); return backJson(false, $e->getMessage()); } } private function _save($key, $val) { $setting = Settings::where('key', $key)->first(); if (!$setting) { $setting = new Settings(); $setting->key = $key; } $setting->val = $val; $setting->save(); } /* * 页面路径 */ private function breadcrumb() { return [ [ 'url' => URL::route('settings.index'), 'title'=> '系统参数' ] ]; } }<file_sep><?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class ExamQuestionType extends Model { protected $table = 'exam_question_type'; public $timestamps = false; protected $fillable = ['exam_id', 'question_type', 'nums', 'score', 'amount']; } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Exam; use App\Http\Model\Examination; use App\Http\Model\Candidate; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\URL; use Exception; class ExaminationController extends Controller { /* * 首页 */ public function index() { $data ['category'] = 'examines'; $data ['subCategory'] = 'examination'; $data ['breadcrumb'] = $this->breadcrumb(); $exams = Exam::where('state', '=' ,'1')->get(); $data ['exams'] = $exams; return view('examination.index', $data); } /* * 获取 */ function get(Request $request) { $input = $request->all(); $page = isset($input ['rows']) ? $input ['rows'] : env('PAGNATION'); $list = Examination::orderBy('begin_time', 'desc')->paginate($page); foreach ($list as $i=>$row) { $list[$i]['state_text'] = $row->state ? '正常' : '禁用'; } $result = [ 'records' => $list->total(), 'total' => $list->lastPage(), 'rows' => $list->items(), ]; return json_encode($result); } /* * 获取年份 */ public function getYears(Request $req) { // 获取班级开始年份 $years = DB::table('examination')->select(DB::raw('id, year(begin_time) as y, month(begin_time) as m')) ->where('state', '1') ->groupBy('y') ->groupBy('m') ->groupBy('id') ->get(); $year = $tree = []; foreach ($years as $y){ $year[$y->y][$y->m][] = $y->id; } foreach ($year as $k=>$month){ $tree[$k] = [ 'id' => $k, 'text' => $k, 'type' => 'folder', 'level'=>1, ]; if( !empty($month) ){ $mon = []; foreach ($month as $key=>$item){ $mon[$key] = [ 'id' => $k.'-'.$key, 'text' => str_pad($key, 2, "0", STR_PAD_LEFT), 'type' => 'folder', 'level'=>2, ]; if( !empty($item) ){ $cls = []; foreach ($item as $l=>$id) { $info = Examination::where('id', $id)->first(); $cls[] = [ 'id' => $id, 'text' => $info->name, 'type' => 'item', 'level' => 3, ]; } $mon[$key]['additionalParameters']['children'] = $cls; } } $tree[$k]['additionalParameters']['children'] = $mon; } } return backJson(true, $tree); } /* * 添加和修改 */ function edit(Request $request) { try { $input = $request->all(); $data = [ 'code' => trim($input['code']), 't_code' => trim($input['t_code']), 't_times' => $input['t_times'], 'name' => trim($input['name']), 'begin_time' => $input['begin_time'], 'retry_time' => $input['retry_time'], 'address' =>trim($input['address']), 'exam_id' =>$input['exam_id'], 'state' =>$input['state'], ]; if (!isset($data['code']) || $data['code'] == '') { // 自动生成考试号 $year = date('Y', strtotime($data['begin_time'])); $ystr = substr($year, 2, 2); $ret = Examination::select(DB::raw('count(id) as cnt')) ->where(DB::raw('year(begin_time)'), $year)->first(); $count = $ret->cnt; $cstr = str_pad($count+1, 3, '0', STR_PAD_LEFT); $data['code'] = $ystr.$cstr.'1'; } if (!isset($data['t_code']) || $data['t_code'] == '') { // 自动生成记分练习号 $year = date('Y', strtotime($data['begin_time'])); $ystr = substr($year, 2, 2); $ret = Examination::select(DB::raw('count(id) as cnt')) ->where(DB::raw('year(begin_time)'), $year)->first(); $count = $ret->cnt; $cstr = str_pad($count+1, 3, '0', STR_PAD_LEFT); $data['t_code'] = $ystr.$cstr.'2'; } if ($data['code'] == $data['t_code']) { throw new Exception('考试号与记分练习号不能一样,请重试!'); } if (isset($input ['id']) && ! empty($input ['id'])) { $exist = Examination::where([['code', '=', $data['code']],['id', '<>', $input['id']]]) ->orWhere([['t_code', '=', $data['code']],['id', '<>', $input['id']]]) ->first(); $exist2 = Exam::where('p_code', $data['code'])->first(); if ($exist || $exist2) { throw new Exception('无效的考试号,已存在'.$data['code'].'的考试号、记分练习号或练习号,请重新设置!'); } $exist = Examination::where([['code', '=', $data['t_code']],['id', '<>', $input['id']]]) ->orWhere([['t_code', '=', $data['t_code']],['id', '<>', $input['id']]]) ->first(); $exist2 = Exam::where('p_code', $data['t_code'])->first(); if ($exist || $exist2) { throw new Exception('无效的记分练习号,已存在'.$data['t_code'].'的考试号、记分练习号或练习号,请重新设置!'); } Examination::where('id', $input['id'])->update($data); $logType = 'edit'; $_success_txt = '考试信息修改成功'; } else { $exist = Examination::where('code', $data['code'])->orWhere('t_code', $data['code'])->first(); $exist2 = Exam::where('p_code', $data['code'])->first(); if ($exist || $exist2) { throw new Exception('无效的考试号,已存在'.$data['code'].'的考试号、记分练习号或练习号,请重新设置!'); } $exist = Examination::where('code', $data['t_code'])->orWhere('t_code', $data['t_code'])->first(); $exist2 = Exam::where('p_code', $data['t_code'])->first(); if ($exist || $exist2) { throw new Exception('无效的记分练习号,已存在'.$data['t_code'].'的考试号、记分练习号或练习号,请重新设置!'); } if (! Examination::create($data)) { throw new Exception("系统错误, 考试添加失败"); } $logType = 'add'; $_success_txt = '考试添加成功,请尽快导入学生信息!'; } parent::_save_log('examination', $logType, $input['name']); return backJson(true, $_success_txt); } catch ( Exception $e ) { return backJson(false, $e->getMessage()); } } /* * 删除 */ function delete(Request $request) { try { $input = $request->all(); if (! isset($input ['id']) || empty($input ['id'])) { throw new Exception("请选择要删除的考试"); } $info = Examination::where('id', $input['id'])->first(); if( Candidate::where('examination_id', $input ['id'])->count() > 0 ){ throw new Exception("该考试已分配考生, 不能删除"); } if (! Examination::where('id', $input ['id'])->delete()) { throw new Exception("系统错误, 删除失败"); } parent::_save_log('examination', 'del', $info['name']); return backJson(true, '考试删除成功'); } catch ( Exception $e ) { return backJson(false, $e->getMessage()); } } /* * 页面路径 */ private function breadcrumb() { return [ [ 'url' => URL::route('examination.index'), 'title'=> '考试列表' ] ]; } }<file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Module; use App\Http\Model\RoleModule; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\URL; class ModuleController extends Controller { /* * 首页 */ function index() { $data['category'] = 'base'; $data['subCategory'] = 'module'; $data['breadcrumb'] = $this->breadcrumb(); $data['moduleList'] = $this->get(2); $data['moduleData'] = $this->get(1); return view('base.module', $data); } // 获取某一个模块的信息 function getOne(Request $request){ $input = $request->all(); $moduleData = Module::where('id', $input['id'])->first(); return backJson(true, $moduleData); } /* * 获取列表 */ function get($type = 1) { $moduleList = Module::where('state', 1)->orderBy('sid', 'asc')->get()->toArray(); $list = genTree($moduleList); $str = ''; if( $type == 1 ) { $str .= '<ol class="dd-list">'; foreach ($list as $li) { $str .= $this->genTreeStr($li); } $str .= '</ol>'; }else if( $type == 2 ) { foreach ($list as $li) { $num = 0; $str .= "<option value='".$li['id']."'>".$li['name']."</option>"; $str .= $this->getModuleOption($li, $num); } } return $str; } // 获取所有模块 function getList(Request $request){ try{ $input = $request->all(); if( !isset($input['role_id']) ){ return backJson(false, '请选择角色'); } $moduleData = Module::where('state', 1)->orderBy('id', 'asc')->get(); $moduleRole = DB::table('role_module')->where('role_id', $input['role_id'])->get(); $mod = []; foreach ($moduleData as $k=>$module){ $mod[$k]['open'] = true; $mod[$k]['id'] = $module->id; $mod[$k]['pId'] = $module->pid; $mod[$k]['name'] = $module->name; if( $moduleRole->count() > 0 ) { foreach ($moduleRole as $ro) { if( $module->id == $ro->module_id ){ $mod[$k]['checked'] = true; } } } } return backJson(true, $mod); } catch (\Exception $e){ return backJson(false, $e->getMessage()); } } function getModuleOption($data, $num){ $str = ''; $num ++; if( isset($data['children']) ){ foreach ($data['children'] as $children) { $split = str_repeat("&nbsp;", ($num)*6); $str .= '<option value="'.$children['id'].'">'; $str .= $split.$children['name']; $str .= '</option>'; $str .= $this->getModuleOption($children, $num); } } return $str; } function genTreeStr($data){ $str = '<li class="dd-item dd2-item" data-id="'.$data['id'].'">'; $str .= '<div class="dd-handle dd2-handle">' ; $str .= '<i class="normal-icon ace-icon fa fa-'.$data['icon'].' red bigger-130"></i>'; $str .= '<i class="drag-icon ace-icon fa fa-arrows bigger-125"></i>'; $str .= '</div>'; $str .= '<div class="dd2-content">' . $data['name']; $str .= '<div class="pull-right action-buttons">'; $str .= '<a class="blue edit_module" data-id='.$data['id'].' href="javascript:;">'; $str .= '<i class="ace-icon fa fa-pencil bigger-130"></i>'; $str .= '</a>'; $str .= '<a class="blue del_module" data-id='.$data['id'].' href="javascript:;">'; $str .= '<i class="ace-icon fa fa-trash-o bigger-130"></i>'; $str .= '</a>'; $str .= '</div>'; $str .= '</div>'; if( isset($data['children']) ){ foreach ($data['children'] as $children) { $str .= '<ol class="dd-list">'; $str .= $this->genTreeStr($children); $str .= '</ol>'; } } $str .= '</li>'; return $str; } // 保存排序值 function saveSort(Request $request){ try{ $input = $request->all(); $sort = $input['sort']; $s = $this->spellSort($sort, 0); $sortData = array_multi2single($s); foreach ($sortData as $k=>$so){ Module::where('id', $so['id'])->update(['pid'=>$so['pid'], 'sid'=>$k]); } return backJson(true, '保存成功'); } catch (\Exception $e){ return backJson(false, $e->getMessage()); } } /** * @param $sort * @return array */ function spellSort($sort, $pid, $i=0){ foreach ($sort as $s) { $data[$i]['id'] = $s['id']; $data[$i]['pid'] = $pid; if (isset($s['children'])) { $data[$i]['children'] = $this->spellSort($s['children'], $s['id'], $i); } $i++; } return $data; } function doSave(Request $request){ try{ $input = $request->all(); if( !isset($input['name']) || empty($input['name']) ){ throw new \Exception("模块名称不能为空"); } $moduleData = [ 'pid' => $input['parent_id'], 'name' => $input['name'], 'url' => $input['url'], 'icon' => $input['icon'], 'category'=> $input['category'], 'state' => 1, 'type' => 0, 'sid' => 1, ]; if( isset($input['id']) && !empty($input['id']) ){ Module::where('id', $input['id'])->update($moduleData); $logType = 'edit'; $_success_txt = '模块编辑成功'; }else{ if( !Module::create($moduleData) ){ throw new \Exception("系统错误, 模块添加错误"); } $logType = 'add'; $_success_txt = '模块添加成功'; } parent::_save_log('module', $logType, $input['name']); return backJson(true, $_success_txt); } catch (\Exception $e){ return backJson(false, $e->getMessage()); } } // 删除模块 function delete(Request $request){ try { $input = $request->all(); if (!isset($input['id']) || empty($input['id'])) { throw new \Exception("请选择要删除的模块"); } $moduleData = Module::where('id', $input['id'])->first(); if( $moduleData->pid != 0 ){ throw new \Exception("该模块有子模块, 不能删除哦"); } if (!Module::where('id', $input['id'])->delete()) { throw new \Exception("系统错误, 删除失败"); } parent::_save_log('module', 'del', $moduleData['name']); return backJson(true, '删除成功'); } catch (\Exception $e) { return backJson(false, $e->getMessage()); } } /* * 面包屑 */ private function breadcrumb(){ return [ [ 'url' => URL::route('module.index'), 'title'=> '模块管理' ] ]; } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\URL; use Illuminate\Support\Facades\DB; use App\Http\Model\Classes; class PrintAdmissionController extends Controller { public function index() { $data ['category'] = 'reports'; $data ['subCategory'] = 'printAdmission'; $data ['breadcrumb'] = $this->breadcrumb(); return view('report.printAdmission', $data); } function get(Request $req){ try{ $page = isset($req->rows) ? $req->rows : env('PAGNATION'); $cons = []; if (isset($req->beginTime)) { $cons[] = ['training_time', '>=', $req->beginTime.'-01 00:00:00']; } if (isset($req->endTime)) { $endTime = date("Y-m-d H:i:s",strtotime("+1 month",strtotime($req->endTime.'-01 00:00:00'))); $cons[] = ['training_time', '<', $endTime]; } if (isset($req->manType)) { if ($req->manType != '全部') { $cons[] = ['category', '=', $req->manType]; } } if (isset($req->comType)) { if ($req->comType != '全部') { $cons[] = ['company_type', '=', $req->comType]; } } if (!empty($cons) ) { $report = DB::table('students')->select(DB::raw('category, company_type, class_id, sum(case when print_times > 0 then 1 else 0 end) as dys, sum(case when print_times > 1 then 1 else 0 end) as cds, count(*) as rs')) ->leftjoin('classes', 'class_id', '=', 'classes.id') ->where($cons) ->groupBy('category', 'company_type', 'class_id') ->orderBy('class_id') ->paginate($page); } else { $report = DB::table('students')->select(DB::raw('category, company_type, class_id, sum(case when print_times > 0 then 1 else 0 end) as dys, sum(case when print_times > 1 then 1 else 0 end) as cds, count(*) as rs')) ->leftjoin('classes', 'class_id', '=', 'classes.id') ->groupBy('category', 'company_type', 'class_id') ->orderBy('class_id') ->paginate($page); } foreach ($report as $k=>$item) { $class = Classes::findOrFail($item->class_id); $report[$k]->class_name = $class->name; } $data = [ 'records' => $report->total(), 'total' => $report->lastPage(), 'rows' => $report->items() ]; return json_encode($data); } catch (Exception $e) { return; } } private function breadcrumb() { return [ [ 'url' => URL::route('printAdmission.index'), 'title'=> '打印统计' ] ]; } }<file_sep><?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class Students extends Model { protected $table = 'students'; public $timestamps = false; public $guarded = ['id']; function hasoneToClass(){ return $this->hasOne(Classes::class, 'id', 'class_id'); } function hasManyToPrint() { return $this->hasMany(StudentsPrint::class, 'student_id', 'id'); } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Exam; use App\Http\Model\ExamEval; use App\Http\Model\ExamQuestion; use App\Http\Model\ExamQuestionType; use App\Http\Model\Member; use App\Http\Model\Question; use App\Http\Model\QuestionType; use App\Http\Model\Subject; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\URL; use App\Http\Model\Examination; class ExamController extends Controller { function __construct() { parent::__construct(); } public function index(Request $request) { $data['category'] = 'examines'; $data['subCategory'] = 'exam'; $data['breadcrumb'] = $this->breadcrumb(); $data['count'] = $this->getExamTypeQuestion(); $data['subjectData'] = Subject::where('state', '<>', 0)->get(); $data['questionType'] = QuestionType::get(); return view('exam.index', $data); } // 获取题目类型总数 function getExamTypeQuestion(){ $type_count = DB::select('select question_type_id, count(*) as n from question group by question_type_id'); $typeCount = []; foreach ($type_count as $type){ $typeCount[$type->question_type_id] = $type->n; } return $typeCount; } // 获取考试题目 function getQuestion(Request $request){ $input = $request->all(); $questionData = Question::where('state', '<>', 0); if( isset($input['subject_id']) && !empty($input['subject_id']) ){ $questionData->where('subject_id', $input['subject_id']); } $questionData = $questionData->get(); foreach ($questionData as $k=>$question){ $questionData[$k]['name'] = '('.$question->hasOneToType()->first()->name.') '.$question->name; } $examQuestion = ExamQuestion::where('exam_id', $input['exam_id'])->orderBy('sid', 'asc')->get(); $questionTxt = $examQuestionText = ''; $examQuesArr = []; $count = [1=>0, 2=>0, 3=>0]; foreach ($examQuestion as $examques){ $examQuesArr[] = $examques->question_id; $quesData = $examques->hasoneToQuestion()->first(); $examQuestionText .= "<li data-typeid={$quesData->question_type_id} data-value='".$examques->question_id."'>"; $examQuestionText .= "<span class='title' ondblclick='delQuestion(this)'>".'('.$quesData->hasOneToType()->first()->name.') '.$quesData->name."</span>"; $examQuestionText .= "<span class='fa fa-trash-o delete'></span>"; $examQuestionText .= "<span class='fa fa-arrow-circle-o-down down'></span>"; $examQuestionText .= "<span class='fa fa-arrow-circle-o-up up'></span>"; $examQuestionText .= "</li>"; $count[$quesData->question_type_id] += 1; } foreach ($questionData as $question) { $cls = ''; if( in_array($question->id, $examQuesArr) ){ $cls = 'hide'; } $questionTxt .= "<option data-typeid={$question->question_type_id} value='". $question->id ."' class='".$cls."'>{$question->name}</option>"; } return backJson(true, ['questionTxt'=>$questionTxt, 'examQuestion'=>$examQuestionText, 'count'=>$count]); } // 保存考试练习号 function doSavePCode(Request $request) { try { $input = $request->all(); $where = [ ['id', '<>', $input['id']], ['p_code', '=', $input['p_code']] ]; $exist = Exam::where($where)->first(); if ($exist) { throw new \Exception('练习号为'.$input['p_code'].'的考卷已存在,请重新设置练习号!'); } $exist = Examination::where('code', $input['p_code'])->orWhere('t_code', $input['p_code'])->first(); if ($exist) { throw new \Exception('练习号与考试号或记分练习号重复,请重新设置练习号!'); } $data = [ 'p_code' => $input['p_code'], ]; $examInfo = Exam::where('id', $input['id'])->first(); $_success_txt = '考卷不记分练习号设置成功'; if (isset($input ['id']) && ! empty($input ['id'])) { Exam::where('id', $input['id'])->update($data); } parent::_save_log('exam', 'setCode', $examInfo['name']); return backJson(true, $_success_txt); } catch ( \Exception $e ) { return backJson(false, $e->getMessage()); } } // 保存考试信息 function doSave(Request $request){ DB::beginTransaction(); try{ $input = $request->all(); if( empty($input['total_score']) && empty($input['strategy']) ){ // throw new \Exception("您的考试方式为手动生成, 请设置考试题型数量以及分数"); } if( empty($input['subject']) ){ throw new \Exception("请选择考卷科目"); } $examData = [ 'subject_id' => $input['subject'], 'name' => $input['name'], 'duration' => $input['duration'], 'strategy' => $input['strategy'], 'score' => $input['total_score'], 'score_pass' => $input['score_pass'], 'price' => 0, 'des' => $input['des'], 'state' => 1, 'updated_at' => date('Y-m-d H:i:s') ]; if( isset($input['id']) && !empty($input['id']) ){ // 修改考试 $exam_id = $input['id']; $examBack = Exam::where('id', $exam_id)->update($examData); ExamQuestionType::where('exam_id', $exam_id)->delete(); ExamEval::where('exam_id', $exam_id)->delete(); $logType = 'edit'; }else { //创建考试 if (!$examBack = Exam::create($examData)) { throw new \Exception("系统错误, 考卷创建失败"); } $exam_id = $examBack->id; $logType = 'add'; } // 题型分数 foreach ($input['questionType'] as $k=>$questionType){ $examQuestionType = [ 'exam_id' => $exam_id, 'question_type' => $k, 'score' => $questionType['score'], 'nums' => $questionType['nums'], 'amount' => $questionType['score'] * $questionType['nums'] ]; if( !ExamQuestionType::create($examQuestionType) ){ throw new \Exception("系统错误, 考卷题型创建失败"); } } // 考评等级 foreach ($input['examEval'] as $k=>$examEval){ $eval = [ 'exam_id' => $exam_id, 'name' => $examEval['name'], 'min_score' => $examEval['min'], 'max_score' => $examEval['max'], ]; if( !ExamEval::create($eval) ){ throw new \Exception("系统错误, 考卷评级创建失败"); } } parent::_save_log('exam', $logType, $input['name']); DB::commit(); return backJson(true, '考卷创建成功'); } catch (\Exception $e) { DB::rollBack(); return backJson(false, $e->getMessage()); } } // 保存考题 function saveQuestion(Request $request){ try { $input = $request->all(); if( !isset($input['exam_id']) || empty($input['exam_id']) ){ throw new \Exception("请选择考卷"); } if( ExamQuestion::where('exam_id', $input['exam_id'])->count() > 0 ) { // if (!ExamQuestion::where('exam_id', $input['exam_id'])->delete()) { throw new \Exception("创建失败, 原题目删除失败"); } } $ExamQuestion = []; foreach ($input['question'] as $k=>$question){ $ExamQuestion[] = [ 'exam_id' => $input['exam_id'], 'question_id' => $question, 'sid' => $k ]; } $examInfo = Exam::where('id', $input['exam_id'])->first(); if( !ExamQuestion::insert( $ExamQuestion ) ){ throw new \Exception("系统错误, 考卷题目创建失败"); } parent::_save_log('exam', 'setQuestion', $examInfo['name']); return backJson(true, '考卷题目设置成功'); } catch (\Exception $e) { return backJson(false, $e->getMessage()); } } // 获取考试信息 function get(Request $request){ $input = $request->all(); $page = isset( $input['rows'] ) ? $input['rows'] : env('PAGNATION'); $examList = Exam::orderBy('updated_at', 'desc')->paginate($page); foreach ( $examList as $k=>$question){ $examList[$k]->subject = $question->hasOneToSubject()->first()->name; $examList[$k]->subject_id = $question->subject_id; $examList[$k]->strategy_name = !$question->strategy ? '手动生成' : '自动生成'; } $examData = [ 'records' => $examList->total(), 'total'=> $examList->lastPage(), 'rows' => $examList->items() ]; return json_encode($examData); } // 查询得到考试的信息 function getExamInfo(Request $request){ try { $input = $request->all(); $exam['info'] = Exam::where('id', $input['id'])->first(); $exam['eval'] = $exam['info']->hasManyToEval()->get(); $exam['question'] = $exam['info']->hasManyToQuestion()->get(); $exam['questionType'] = $exam['info']->hasManyToQuestionType()->get(); return backJson(true, $exam); } catch (\Exception $e) { return backJson(false, $e->getMessage()); } } // 删除考试 function delete(Request $request){ DB::beginTransaction(); try { $input = $request->all(); if (!isset($input['id']) || empty($input['id'])) { throw new \Exception("请选择要删除的考卷"); } $examInfo = Exam::where('id', $input['id'])->first(); // 删除考试 if (!Exam::where('id', $input['id'])->delete()) { throw new \Exception("系统错误, 考卷删除失败"); } // 删除考试题型 if (!ExamQuestionType::where('exam_id', $input['id'])->delete()) { throw new \Exception("系统错误, 考卷题型删除失败"); } // 删除考试评级 if (!ExamEval::where('exam_id', $input['id'])->delete()) { throw new \Exception("系统错误, 考卷评级删除失败"); } parent::_save_log('exam', 'del', $examInfo['name']); DB::commit(); return backJson(true, '删除成功'); } catch (\Exception $e) { DB::rollBack(); return backJson(false, $e->getMessage()); } } /** * 页面面包屑 * @return array */ private function breadcrumb(){ return [ [ 'url' => URL::route('exam.index'), 'title'=> '考卷列表' ] ]; } } <file_sep><?php $__env->startSection('content'); ?> <?php $target = 'add_form'; ?> <div class="row"> <div class="col-xs-12"> <div class="jqGrid_tools"> <?php echo $__env->make('common.buttons._add', ['add_target'=>$target, 'index'=>1], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php echo $__env->make('common.buttons._edit', ['modal_target'=>$target, 'parms'=>'$("#name").val(rowData.name);$("#duration").val(rowData.duration);$("#id").val(rowData.id);$("#sid").val(rowData.sid);$("#state").val(rowData.state);'], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php echo $__env->make('common.buttons._del', ['url'=>URL::route('trainings.delete')], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> </div> <table id="jqgrid-table-1"></table> <div id="jqgrid-pager-1"></div> </div> </div> <div class="modal fade" role="dialog" id="<?php echo e($target); ?>"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title">添加</h4> </div> <form class="form-horizontal <?php echo e($target); ?>" action="<?php echo e(URL::route('trainings.edit')); ?>" method="POST"> <?php echo e(csrf_field()); ?> <input type="hidden" value="0" name="id" id="id"/> <div class="modal-body"> <!-- #section:elements.form --> <div class="form-group"> <label class="col-sm-2 control-label no-padding-right">课程名称 <span class="text-danger">*</span></label> <div class="col-sm-9"> <input datatype="*" nullmsg="请输入课程名称" type="text" id="name" placeholder="请输入课程名称" name="name" class="col-xs-10 col-sm-10" /> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label no-padding-right"> 学时 <span class="text-danger">*</span></label> <div class="col-sm-9"> <input datatype="num" errormsg="学时格式错误" type="text" id="duration" placeholder="请输入学时" name="duration" class="col-xs-10 col-sm-10" /> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label no-padding-right"> 课程状态 <span class="text-danger">*</span></label> <div class="col-sm-9"> <select name="state" id="state"> <option value="1">正常</option> <option value="0">禁用</option> </select> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label no-padding-right"> 排序 <span class="text-danger">*</span></label> <div class="col-sm-9"> <input type="number" id="sid" datatype="n" errormsg="排序格式错误" maxlength="3" placeholder="排序" name="sid" class="col-xs-10 col-sm-5" /> </div> </div> </div> <div class="modal-footer"> <button class="btn btn-primary ok_btn">保存</button> <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> </div> </form> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div> <?php $__env->stopSection(); ?> <?php $__env->startSection('footer_script'); ?> <?php echo $__env->make('common.jqgrid', [ 'index' => 1, 'url' => URL::route('trainings.get'), 'colnames' => "['ID', '课程名称','学时', '排序', '状态', '状态']", 'colModel' => json_encode([ ['name' => 'id', 'hidden'=>true], ['name' => 'name'], ['name' => 'duration'], ['name' => 'sid', 'hidden'=>true], ['name' => 'state', 'hidden'=>true], ['name' => 'state_text'], ]) ], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php $__env->stopSection(); ?> <?php echo $__env->make('addi.app', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?><file_sep><?php $__env->startSection('content'); ?> <div class="col-sm-10 col-sm-offset-1"> <div class="login-container"> <div class="center"> <h1 style="font-size: 28px;"> <span class="red"><?php echo e(config('app.name')); ?></span> </h1> <h4 class="blue" id="id-company-text"><?php echo e(config('app.subname')); ?></h4> </div> <div class="space-6"></div> <div class="position-relative"> <div id="login-box" class="login-box widget-box no-border visible"> <div class="widget-body"> <div class="widget-main"> <h4 class="header blue lighter bigger"> <i class="ace-icon fa fa-coffee green"></i> 请输入以下用户信息 </h4> <div class="space-6"></div> <form class="form-horizontal" role="form" method="POST" action="<?php echo e(url('/login')); ?>"> <?php echo e(csrf_field()); ?> <fieldset> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input placeholder="请输入邮箱" id="email" type="email" class="form-control" name="email" value="<?php echo e(old('email')); ?>" required autofocus> <i class="ace-icon fa fa-user"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input placeholder="请输入密码" id="password" type="<PASSWORD>" class="form-control" name="password" required> <i class="ace-icon fa fa-lock"></i> </span> </label> <div class="space"></div> <div class="clearfix"> <label class="inline"> <input class="ace" type="checkbox"> <span class="lbl"> 记住我</span> </label> <button type="submit" class="width-35 pull-right btn btn-sm btn-primary"> <i class="ace-icon fa fa-key"></i> <span class="bigger-110">用户登录</span> </button> </div> <div class="space-4"></div> </fieldset> </form> </div><!-- /.widget-main --> <div class="toolbar clearfix"> <div> <a href="#" data-target="#forgot-box" class="forgot-password-link"> <i class="ace-icon fa fa-arrow-left"></i> 忘记密码 </a> </div> <!--<div> <a href="#" data-target="#signup-box" class="user-signup-link"> 还没有账号? <i class="ace-icon fa fa-arrow-right"></i> </a> </div>--> </div> </div><!-- /.widget-body --> </div><!-- /.login-box --> <?php echo $__env->make('auth.forgot', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php echo $__env->make('auth.register', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <div class="navbar-fixed-top align-right" style="display: none;"> <br> &nbsp; <a id="btn-login-dark" href="#">Dark</a> &nbsp; <span class="blue">/</span> &nbsp; <a id="btn-login-blur" href="#">Blur</a> &nbsp; <span class="blue">/</span> &nbsp; <a id="btn-login-light" href="#">Light</a> &nbsp; &nbsp; &nbsp; </div> </div> </div> </div> <?php $__env->stopSection(); ?> <?php echo $__env->make('addi.passport', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?><file_sep><?php /** * Created by PhpStorm. * User: xiaoping * Date: 2017-05-21 * Time: 19:46 */ namespace App\Http\Controllers; use App\Http\Model\Candidate; use App\Http\Model\Examination; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\URL; use Exception; use Maatwebsite\Excel\Facades\Excel; class ScoreController extends Controller { /* * 首页 */ public function index() { $data ['category'] = 'reports'; $data ['subCategory'] = 'score'; $data ['breadcrumb'] = $this->breadcrumb(); return view('report.score', $data); } /* * 获取 */ function get(Request $req){ try{ $page = isset($req->rows) ? $req->rows : env('PAGNATION'); $dates = []; if (isset($req->beginTime)) { $dates[] = ['examination.begin_time', '>=', $req->beginTime]; } if (isset($req->endTime)) { $dates[] = ['examination.begin_time', '<=', $req->endTime]; } $ids = []; if (isset($req->search) && isset($req->level)) { if ($req->level == 1) { // 年查询 $exams = Examination::select(DB::raw('id, year(begin_time) as y')) ->where('state', '1')->where(DB::raw('year(begin_time)'), $req->search)->get(); foreach ($exams as $exam){ $ids[] = $exam->id; } } else if ($req->level == 2) { // 月查询 $yearArr = explode('-', $req->search); $exams = Examination::select(DB::raw('id, month(begin_time) as m')) ->where('state', '1')->where(DB::raw('year(begin_time)'), $yearArr[0])->where(DB::raw('month(begin_time)'), $yearArr[1])->get(); $ids = []; foreach ($exams as $exam){ $ids[] = $exam->id; } } else { // 考试查询 $ids[] = $req->search; } } $name = ''; if (isset($req->idNumber)) { $name = $req->idNumber; } $name = trim($name); if ($ids) { // 树查询 $report = DB::table('candidate')->select(DB::raw('candidate.id as "id", examination.name as "exam_name", examination.retry_time as "retry_time", candidate.name as "name", id_no, candidate.code as "code", paper_time, score_paper, paper_id, paper_retry_time, score_paper_retry, paper_retry_id, paper_time_begin, paper_retry_time_begin')) ->leftjoin('examination', 'examination_id', '=', 'examination.id') ->whereIn('examination_id', $ids) ->orderBy('candidate.name') ->paginate($page); } else { // 综合查询 $report = DB::table('candidate')->select(DB::raw('candidate.id as "id", examination.name as "exam_name", examination.retry_time as "retry_time", candidate.name as "name", id_no, candidate.code as "code", paper_time, score_paper, paper_id, paper_retry_time, score_paper_retry, paper_retry_id, paper_time_begin, paper_retry_time_begin')) ->leftjoin('examination', 'examination_id', '=', 'examination.id') ->where($dates) ->where(function ($query) use ($name) { $query->where('candidate.id_no', 'like', '%'.$name.'%') ->orWhere('candidate.name', 'like', '%'.$name.'%') ->orWhere('candidate.code', 'like', '%'.$name.'%'); })->orderBy('candidate.name') ->paginate($page); } $now = time(); foreach ($report as $k=>$item) { if ($item->paper_id) { $url = URL::route('examine.finish', ['paper_id'=>$item->paper_id, 'type'=>1, 'source'=>1]); $item->paper_id = '<a href="'.$url.'" target="_blank">详细</a>'; $paper_time = date('y年m月d日 H:i-', strtotime($item->paper_time_begin)).date('H:i', strtotime($item->paper_time)); $item->paper_time = $paper_time; } if ($item->paper_retry_id) { $url = URL::route('examine.finish', ['paper_id'=>$item->paper_retry_id, 'type'=>4, 'source'=>1]); $item->paper_retry_id = '<a href="'.$url.'" target="_blank">详细</a>'; $paper_retry_time = date('y年m月d日 H:i-', strtotime($item->paper_retry_time_begin)).date('H:i', strtotime($item->paper_retry_time)); $item->paper_retry_time = $paper_retry_time; } else { $last = strtotime($item->retry_time); if (!$item->paper_id && $now > $last) { $item->score_paper = '缺考'; $item->score_paper_retry = '缺考'; } } } $data = [ 'records' => $report->total(), 'total' => $report->lastPage(), 'rows' => $report->items() ]; return json_encode($data); } catch (Exception $e) { return; } } function export(Request $req) { $dates = []; if (isset($req->beginTime)) { $dates[] = ['examination.begin_time', '>=', $req->beginTime]; } if (isset($req->endTime)) { $dates[] = ['examination.begin_time', '<=', $req->endTime]; } $ids = []; if (isset($req->search) && isset($req->level)) { if ($req->level == 1) { // 年查询 $exams = Examination::select(DB::raw('id, year(begin_time) as y')) ->where('state', '1')->where(DB::raw('year(begin_time)'), $req->search)->get(); foreach ($exams as $exam){ $ids[] = $exam->id; } } else if ($req->level == 2) { // 月查询 $yearArr = explode('-', $req->search); $exams = Examination::select(DB::raw('id, month(begin_time) as m')) ->where('state', '1')->where(DB::raw('year(begin_time)'), $yearArr[0])->where(DB::raw('month(begin_time)'), $yearArr[1])->get(); $ids = []; foreach ($exams as $exam){ $ids[] = $exam->id; } } else { // 考试查询 $ids[] = $req->search; } } $name = ''; if (isset($req->idNumber)) { $name = $req->idNumber; } $name = trim($name); if ($ids) { // 树查询 $report = DB::table('candidate')->select(DB::raw('examination.name as "exam_name", examination.retry_time as "retry_time", candidate.code as "code", candidate.name as "name", id_no, paper_time_begin, paper_time, score_paper, paper_retry_time_begin, paper_retry_time, score_paper_retry, pass_time')) ->leftjoin('examination', 'examination_id', '=', 'examination.id') ->whereIn('examination_id', $ids) ->orderBy('candidate.name') ->get(); } else { // 综合查询 $report = DB::table('candidate')->select(DB::raw('examination.name as "exam_name", examination.retry_time as "retry_time", candidate.code as "code", candidate.name as "name", id_no, paper_time_begin, paper_time, score_paper, paper_retry_time_begin, paper_retry_time, score_paper_retry, pass_time')) ->leftjoin('examination', 'examination_id', '=', 'examination.id') ->where($dates) ->where(function ($query) use ($name) { $query->where('candidate.id_no', 'like', '%'.$name.'%') ->orWhere('candidate.name', 'like', '%'.$name.'%') ->orWhere('candidate.code', 'like', '%'.$name.'%'); })->orderBy('candidate.name') ->get(); } $now = time(); $userInfo = []; $userInfo[0] = ['考试名称', '准考证号', '考生姓名', '身份证号', '考试时间', '考试分数', '补考时间', '补考分数', '考试结果']; $col_exam_name = 0; $col_code = 1; $col_name = 2; $col_id_no = 3; $col_paper_time = 4; $col_score_paper = 5; $col_paper_retry_time = 6; $col_score_paper_retry = 7; $col_pass_time = 8; foreach ($report as $i=>$item) { $k = $i + 1; $userInfo[$k][$col_exam_name] = $item->exam_name; $userInfo[$k][$col_code] = $item->code; $userInfo[$k][$col_name] = $item->name; $userInfo[$k][$col_id_no] = $item->id_no.' '; $userInfo[$k][$col_paper_time] = ''; $userInfo[$k][$col_score_paper] = ''; if ($item->paper_time) { $paper_time = date('y年m月d日 H:i - ', strtotime($item->paper_time_begin)).date('H:i', strtotime($item->paper_time)); $userInfo[$k][$col_paper_time] = $paper_time; $userInfo[$k][$col_score_paper] = $item->score_paper; } $userInfo[$k][$col_paper_retry_time] = ''; $userInfo[$k][$col_score_paper_retry] = ''; if ($item->paper_retry_time) { $paper_retry_time = date('y年m月d日 H:i - ', strtotime($item->paper_retry_time_begin)).date('H:i', strtotime($item->paper_retry_time)); $userInfo[$k][$col_paper_retry_time] = $paper_retry_time; $userInfo[$k][$col_score_paper_retry] = $item->score_paper_retry; } $last = strtotime($item->retry_time); if (!$item->paper_time && !$item->paper_retry_time) { if ($now > $last) { $userInfo[$k][$col_score_paper] = '缺考'; $userInfo[$k][$col_score_paper_retry] = '缺考'; } } $userInfo[$k][$col_pass_time] = '未通过'; if ($item->pass_time) { $userInfo[$k][$col_pass_time] = '已通过'; } } $exportName = '考生成绩'.date('Ymdhi'); Excel::create($exportName, function($excel) use($userInfo) { $excel->sheet('考生成绩', function($sheet) use($userInfo) { $sheet->rows($userInfo); $sheet->setWidth([ 'A' => 30, 'B' => 10, 'C' => 10, 'D' => 20, 'E' => 25, 'F' => 10, 'G' => 25, 'H' => 10, 'I' => 10 ]); $sheet->setColumnFormat([ 'A' => '@', 'B' => '@', 'C' => '@', 'D' => '@', 'E' => '@', 'F' => '@', 'G' => '@', 'H' => '@', 'I' => '@', ]); $sheet->setPageMargin(0.25); }); })->export('xls'); } /* * 页面路径 */ private function breadcrumb() { return [ [ 'url' => URL::route('score.index'), 'title'=> '成绩查询' ] ]; } }<file_sep><?php namespace App\Http\Controllers; use App\Http\Model\User; use App\Http\Model\UserRole; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\URL; use Exception; class UserController extends Controller { /* * 首页 */ public function index() { $data ['category'] = 'base'; $data ['subCategory'] = 'user'; $data ['breadcrumb'] = $this->breadcrumb(); return view('base.user', $data); } /* * 获取用户列表 */ function get(Request $request) { $input = $request->all(); $page = isset($input ['rows']) ? $input ['rows'] : env('PAGNATION'); $userList = User::where('id', '<>', Auth::user() ['id'])->orderBy('created_at', 'desc')->paginate($page); $users = [ 'records' => $userList->total(), 'total' => $userList->lastPage(), 'rows' => $userList->items() ]; return json_encode($users); } // 用户模块关联 function permission(Request $request){ try { $input = $request->all(); if( !isset($input['user_id']) || !isset($input['role']) ){ throw new Exception("请选择用户权限"); } if( UserRole::where('user_id', $input['user_id'])->count() > 0 ){ if( !UserRole::where('user_id', $input['user_id'])->delete() ){ throw new Exception("用户权限删除失败"); } } $userInfo = User::where('id', $input['user_id'])->first(); $userRole = []; foreach ($input['role'] as $k=>$role){ $userRole[$k]['user_id'] = $input['user_id']; $userRole[$k]['role_id'] = $role; } if( !UserRole::insert($userRole)){ throw new Exception("用户权限关联失败"); } parent::_save_log('user', 'permission', $userInfo['name']); return backJson(true, '保存成功'); } catch ( Exception $e ) { return backJson(false, $e->getMessage()); } } // 修改密码 function changepw(Request $request) { try { $input = $request->all(); $user = User::where('id', Auth::user()['id'])->first(); if ( !password_verify($input['oldpasswd'], $user['password']) ){ throw new Exception("原密码不正确,请重试!"); } if(!User::where('id', Auth::user()['id'])->update(['password' => bcrypt($input['newpasswd'])])) { throw new Exception('系统错误,保存新密码出错!'); } parent::_save_log('user', 'repass', $user['name']); return backJson(true, "密码修改成功!"); } catch (Exception $e) { return backJson(false, $e->getMessage()); } } /* * 添加和修改用户 */ function edit(Request $request) { try { $input = $request->all(); $userData = [ 'name' => $input ['name'], 'email' => $input ['email'], 'password' => <PASSWORD>(env('INIT_PASS')) ]; if (isset($input ['id']) && ! empty($input ['id'])) { $checker = [ ['email', '=', $userData['email']], ['id', '<>', $input['id']] ]; if (User::where($checker)->first()) { throw new Exception('用户邮箱已存在,请重试!'); } $userData ['updated_at'] = date('Y-m-d H:i:s'); User::where('id', $input ['id'])->update($userData); $_success_txt = '用户信息修改成功'; $logType = 'edit'; } else { if (User::where('email', $userData['email'])->first()) { throw new Exception('用户邮箱已存在,请重试!'); } $userData ['created_at'] = date('Y-m-d H:i:s'); if (! User::create($userData)) { throw new Exception("系统错误, 用户添加失败"); } $_success_txt = '用户添加成功'; $logType = 'add'; } parent::_save_log('user', $logType, $input['name']); return backJson(true, $_success_txt); } catch ( Exception $e ) { return backJson(false, $e->getMessage()); } } /* * 删除用户 */ function delete(Request $request) { try { $input = $request->all(); if (! isset($input ['id']) || empty($input ['id'])) { throw new Exception("请选择要删除的用户"); } $userInfo = User::where('id', $input['id'])->first(); if (! User::where('id', $input ['id'])->delete()) { throw new Exception("系统错误, 删除失败"); } parent::_save_log('user', 'del', $userInfo['name']); return backJson(true, '删除成功'); } catch ( Exception $e ) { return backJson(false, $e->getMessage()); } } /* * 页面路径 */ private function breadcrumb() { return [ [ 'url' => URL::route('user.index'), 'title'=> '用户列表' ] ]; } } <file_sep><script src="<?php echo e(URL::asset('components/jqGrid/js/jquery.jqGrid.js')); ?>"></script> <script src="<?php echo e(URL::asset('components/jqGrid/js/i18n/grid.locale-cn.js')); ?>"></script> <script> var _width; var _height = getPageSize()[3]; var _top_height = $(".jqGrid_tools").outerHeight() + $("#navbar").outerHeight() + $("#breadcrumbs").outerHeight() + 8 + 27 + 55 + 16 + 8; if( $(".left_tree").length > 0 ){ _width = getPageSize()[0] - $(".left_tree").outerWidth() - 12 ; $(".left_tree .widget-body").height(_height -$("#breadcrumbs").outerHeight() - $("#navbar").outerHeight() - 12 - $(".left_tree .widget-header").outerHeight() ); }else{ _width = getPageSize()[0]; } var _left_menu_width = 205; jQuery(function($) { var grid_selector = "#jqgrid-table-<?php echo e($index); ?>"; var pager_selector = "#jqgrid-pager-<?php echo e($index); ?>"; //resize to fit page size $(window).on('resize.jqGrid', function () { }) //resize on sidebar collapse/expand $(document).on('settings.ace.jqGrid' , function(ev, event_name, collapsed) { if( event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed' ) { //setTimeout is for webkit only to give time for DOM changes and then redraw!!! setTimeout(function() { $(grid_selector).jqGrid( 'setGridWidth', parent_column.width() ); }, 20); } }) jQuery(grid_selector).jqGrid({ url: "<?php echo e($url); ?>", mtype : "POST", datatype: "json", postData : { '_token': "<?php echo e(csrf_token()); ?>", }, autowidth: false, height: _height - _top_height, width: _width - _left_menu_width, colNames: <?php echo $colnames; ?>, colModel: <?php echo $colModel; ?>, viewrecords : true, rownumbers: true, <?php if(isset($multiselect) && $multiselect): ?> multiselect: true, <?php endif; ?> <?php if(isset($rowListShow) && !empty($rowListShow)): ?> rowList: <?php echo $rowListShow; ?>, <?php else: ?> rowList: [20, 40, 80], <?php endif; ?> <?php if(isset($rowNum)): ?> rowNum: <?php echo $rowNum; ?>, <?php else: ?> rowNum: 20, <?php endif; ?> pager : pager_selector, loadComplete : function() { var table = this; setTimeout(function(){ updatePagerIcons(table); }, 0); }, }); }) </script><file_sep><?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class Slider extends Model { protected $table = 'sliders'; public $timestamps = true; public $guarded = [ 'id' ]; } <file_sep><?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class StudentsPrint extends Model { protected $table = 'students_print'; public $timestamps = false; public $guarded = ['id']; function hasOneToStudent(){ return $this->hasOne(Students::class, 'id', 'student_id'); } function hasOneToUser() { return $this->hasOne(User::class, 'id', 'print_user'); } } <file_sep><?php $table_index = isset($index) ? $index : 1; ?> <div style="float: right; width: 500px;"> <div class="input-group"> <input class="form-control search-query" maxlength="20" placeholder="请输入姓名或身份证号码" type="text" id="user"> <span class="input-group-btn"> <button type="button" class="btn btn-info btn-sm" id="search" > <span class="ace-icon fa fa-search icon-on-right bigger-110"></span> 查询 </button> </span> </div> </div> <script> $(document).ready(function(){ $('#search').on('click', function(){ var user = $('#user').val(); $("#jqgrid-table-<?php echo e($table_index); ?>").jqGrid('setGridParam', { url: "<?php echo e(URL::route('students.get')); ?>?user=" + encodeURI(user), page: 1 }).trigger("reloadGrid"); }); }); </script><file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Role; use App\Http\Model\RoleModule; use App\Http\Model\UserRole; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\URL; class RoleController extends Controller { /* * 首页 */ function index() { $data['category'] = 'base'; $data['subCategory'] = 'role'; $data['breadcrumb'] = $this->breadcrumb(); return view('base.role', $data); } /* * 获取列表 */ function get(Request $request) { $input = $request->all(); $page = isset($input['rows']) ? $input['rows'] : env('PAGNATION'); $roleList = Role::paginate($page); foreach ($roleList as $k=>$role){ $roleList[$k]->state = $role->state ? '启用' : '禁用'; } $roles = [ 'records' => $roleList->total(), 'total' => $roleList->lastPage(), 'rows' => $roleList->items() ]; return json_encode($roles); } // 获取 function getList(Request $request){ try { $input = $request->all(); if( !isset($input['user_id']) ){ throw new \Exception("请选择用户"); } $roleList = Role::where('state', 1)->get(); $allRole = $hasRole = ''; $userRoles = UserRole::where('user_id', $input['user_id'])->get(); $userRole = []; if( $userRoles->count() > 0 ){ foreach ( $userRoles as $k=>$usRole){ $userRole[$usRole->role_id]['role_name'] = $usRole->hasoneToRole()->first()->name; } } foreach ($roleList as $k=>$role){ $cls = ''; if( isset($userRole[$role->id]) ){ $cls = 'hide'; $hasRole .= "<li data-value='".$role->id."'>"; $hasRole .= "<span class='title'>{$role->name}</span>"; $hasRole .= "<span class='fa fa-trash-o delete'></span>"; $hasRole .= "<span class='fa fa-arrow-circle-o-down down'>"; $hasRole .= "<span class='fa fa-arrow-circle-o-up up'>"; $hasRole .= "</li>"; } $allRole .= "<option value='".$role->id."' class='".$cls."'>{$role->name}</option>"; } $data['allRole'] = $allRole; $data['hasRole'] = $hasRole; return backJson(true, $data); } catch (\Exception $e) { return backJson(false, $e->getMessage()); } } // 角色关联模块权限 function permission(Request $request){ try { $input = $request->all(); if( !isset($input['module']) || !isset($input['role_id']) ){ throw new \Exception("请选择角色模块"); } $role = Role::where('id', $input['role_id'])->first(); if( DB::table('role_module')->where('role_id', $input['role_id'])->count() > 0 ){ if( !DB::table('role_module')->where('role_id', $input['role_id'])->delete()){ throw new \Exception("角色模块删除失败"); } } $mod = []; foreach ($input['module'] as $module){ $mod[] = [ 'role_id' =>$input['role_id'], 'module_id'=>$module ]; } if( !DB::table('role_module')->insert($mod) ){ throw new \Exception("权限保存失败"); } parent::_save_log('role', 'permission', $role['name']); return backJson(true, '权限保存成功'); } catch (\Exception $e) { return backJson(false, $e->getMessage()); } } /* * 增加或修改角色 */ function edit(Request $request) { try { $input = $request->all(); $roleData = [ 'name' => $input['rolename'], 'des' => $input['des'], 'sid' => $input['sid'], ]; if (isset($input ['id']) && ! empty($input ['id'])) { if (! Role::where('id', $input['id'])->update($roleData)) { throw new Exception("角色更新失败"); } $_success_txt = '角色修改成功'; $logType = 'edit'; } else { if (! Role::create($roleData)) { throw new Exception("角色添加失败"); } $_success_txt = '角色添加成功'; $logType = 'add'; } parent::_save_log('role', $logType, $input['rolename']); return backJson(true, $_success_txt); } catch ( Exception $e ) { return backJson(false, $e->getMessage()); } } /* * 删除角色 */ function delete(Request $request) { try { $input = $request->all(); if (!isset($input['id']) || empty($input['id'])) { throw new \Exception("请选择要删除的角色"); } $roleRel = UserRole::where('role_id', $input['id'])->count(); if( $roleRel > 0 ){ throw new \Exception("已有用户关联该角色, 不能删除"); } $role = Role::where('id', $input['id'])->first(); if (!Role::where('id', $input['id'])->delete()) { throw new \Exception("系统错误, 删除失败"); } parent::_save_log('role', 'del', $role['name']); return backJson(true, '删除成功'); } catch (\Exception $e) { return backJson(false, $e->getMessage()); } } /* * 面包屑 */ private function breadcrumb(){ return [ [ 'url' => URL::route('role.index'), 'title'=> '角色管理' ] ]; } }<file_sep><?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class Examination extends Model { protected $table = 'examination'; public $timestamps = false; public $guarded = ['id']; function hasoneToExam(){ return $this->hasOne(Exam::class, 'id', 'exam_id'); } function hasManyToStu(){ return $this->hasMany(Candidate::class, 'examination_id', 'id'); } function hasManyToEval(){ return $this->hasMany(ExamEval::class, 'exam_id', 'exam_id'); } } ?><file_sep>/* Navicat MySQL Data Transfer Source Server : 本地 Source Server Version : 50626 Source Host : localhost:3306 Source Database : kaoshi Target Server Type : MYSQL Target Server Version : 50626 File Encoding : 65001 Date: 2016-12-02 19:02:18 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for migrations -- ---------------------------- DROP TABLE IF EXISTS `migrations`; CREATE TABLE `migrations` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `migration` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `batch` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- ---------------------------- -- Records of migrations -- ---------------------------- INSERT INTO `migrations` VALUES ('1', '2014_10_12_000000_create_users_table', '1'); INSERT INTO `migrations` VALUES ('2', '2014_10_12_100000_create_password_resets_table', '1'); -- ---------------------------- -- Table structure for password_resets -- ---------------------------- DROP TABLE IF EXISTS `password_resets`; CREATE TABLE `password_resets` ( `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `token` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, KEY `password_resets_email_index` (`email`), KEY `password_resets_token_index` (`token`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- ---------------------------- -- Records of password_resets -- ---------------------------- -- ---------------------------- -- Table structure for users -- ---------------------------- DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `users_email_unique` (`email`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- ---------------------------- -- Records of ks_users -- ---------------------------- INSERT INTO `users` VALUES ('1', '<EMAIL>', '<EMAIL>', '$2y$10$tq.YKlpf2hqoN..dRiotMep4F7p.XnXOhhBQL1357fVTOcOE8D6AG', 'CGG5IKUiFEMrTJnf5QMEZeXLDZNEPsJgSl1eEVvBy4NqSwSOWUccy5WBLc3t', '2016-12-02 10:03:58', '2016-12-02 10:04:43'); SET FOREIGN_KEY_CHECKS=1; <file_sep># examine PHP project based on lavarel, this project is for wangfeng examine是考试部分 examine_print是打听课证部分<file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Answer; use App\Http\Model\ExamQuestion; use App\Http\Model\Member; use App\Http\Model\Question; use App\Http\Model\QuestionType; use App\Http\Model\Subject; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\URL; use App\Http\Model\PaperQuestion; use Maatwebsite\Excel\Facades\Excel; class QuestionController extends Controller { public function index() { $data['category'] = 'questions'; $data['subCategory'] = 'question'; $data['breadcrumb'] = $this->breadcrumb(); $data['question_type'] = QuestionType::get(); return view('question.index', $data); } //添加题目页面 function add(Request $request){ $data['questionData'] = []; $input = $request->all(); if( isset($input['id']) && !empty( $input['id']) ){ $questionData['question'] = Question::where('id', $input['id'])->first(); $questionData['answer'] = $questionData['question']->hasManyToAnswer()->get(); $data['questionData'] = $questionData; $subject_id = $questionData['question']->subject_id; }else{ $subject_id = $input['subject_id']; } $data['subject_id'] = $subject_id; $data['question_type'] = $input['type']; return view('question.add', $data); } // 获取科目数 function getSubject(){ $root[] = [ 'id' => 0, 'text' => '全部', 'type' => 'folder', ]; $children = []; $subjectData = Subject::where('state', '1')->orderBy('sid', 'asc')->get(); foreach ($subjectData as $subject){ $children[] = [ 'id' => $subject->id, 'text' => $subject->name, 'type' => 'item', ]; } $root[0]['additionalParameters']['children'] = $children; return backJson(true, $root); } // 获取题目 function get(Request $request){ $input = $request->all(); $page = isset( $input['rows'] ) ? $input['rows'] : env('PAGNATION'); if( isset($input['subject_id']) && !empty($input['subject_id']) ){ $questionList = Question::where('state', '<>', 0)->where('subject_id', $input['subject_id'])->orderBy('updated_at', 'desc')->paginate($page); }else{ $questionList = Question::where('state', '<>', 0)->orderBy('updated_at', 'desc')->paginate($page); } foreach ( $questionList as $k=>$question){ $questionList[$k]->type_id = $question->hasOneToType()->first()->id; $questionList[$k]->type = $question->hasOneToType()->first()->name; $quesSubject = $question->hasOneToSubject()->first(); if( $quesSubject == null ) { $questionList[$k]->subject = ''; }else{ $questionList[$k]->subject = $quesSubject->name; } } $question = [ 'records' => $questionList->total(), 'total'=> $questionList->lastPage(), 'rows' => $questionList->items() ]; return json_encode($question); } // 题目保存方法 function doAdd(Request $request){ try{ DB::beginTransaction(); $input = $request->all(); $id = $input['question']['id']; $type = $input['question_type']; $title = $input['question']['title']; // $answer_right = $input['question']['options']['answer']; $answers = $input['question']['options']; $subject_id = $input['question']['subject_id']; $question = [ 'question_type_id' => $type, 'name' => $title, 'subject_id' => $subject_id, 'des' => '', 'state' => 1, 'updated_at' => date('Y-m-d H:i:s'), ]; if( isset($id) && !empty($id) ) { // 修改题目 $where = [ ['question_type_id', '=', $question['question_type_id']], ['name', '=', $question['name']], ['subject_id', '=', $question['subject_id']], ['id', '<>', $id], ]; $exist = Question::where($where)->first(); if ($exist) { throw new \Exception('错误, 该题目已经存在,请重试!'); } $quesionDb = Question::where('id', $id)->update($question); $logType = 'edit'; $quesion_id = $id; }else{ // 创建题目 $where = [ ['question_type_id', '=', $question['question_type_id']], ['name', '=', $question['name']], ['subject_id', '=', $question['subject_id']], ]; $exist = Question::where($where)->first(); if ($exist) { throw new \Exception('错误, 该题目已经存在,请重试!'); } if (!$quesionDb = Question::create($question)) { throw new \Exception("系统错误, 题目创建失败"); } $logType = 'add'; $quesion_id = $quesionDb->id; } // 答案 if( isset($id) && !empty($id) ) { // 修改答案 if( ! Answer::where('question_id', $id)->delete() ){ throw new \Exception("系统错误, 原答案删除失败"); } $_question_succ = "题目修改成功"; }else{ $_question_succ = "题目创建成功"; } $answerArr = []; foreach ( $answers['val'] as $key=>$ans) { $answerArr[] = [ 'question_id' => $quesion_id, 'label' => IntToChr($key), 'name' => $ans, 'answer_right' => isset($answers['answer'][$key]) && $answers['answer'][$key] == 'on' ? 1 : 0 ]; } if( ! Answer::insert($answerArr) ){ throw new \Exception("系统错误, 题目选项创建错误"); } parent::_save_log('question', $logType, $title); DB::commit(); return backJson( true , $_question_succ); } catch (\Exception $e){ DB::rollBack(); return backJson(false, $e->getMessage()); } } // 删除题目 function delete(Request $request){ try{ $input = $request->all(); if( !isset($input['id']) || empty($input['id']) ){ throw new \Exception("请选择要删除的题目"); } $questionRel = ExamQuestion::where('question_id', $input['id'])->count(); if( $questionRel > 0 ){ throw new \Exception("已有考试关联该题目, 暂时不能删除"); } $questionRel = PaperQuestion::where('question_id', $input['id'])->count(); if( $questionRel > 0 ){ throw new \Exception("已有考卷关联该题目, 暂时不能删除"); } $question = Question::where('id', $input['id'])->first(); if ( !Question::where( 'id', $input['id'] )->delete() ){ throw new \Exception("系统错误, 题目删除失败"); } parent::_save_log('question', 'del', $question['name']); return backJson(true, '删除成功'); } catch (\Exception $e){ return backJson(false, $e->getMessage()); } } // 导入题库 function import(Request $request){ DB::beginTransaction(); try{ $input = $request->all(); if( !isset($input['subject_id']) || empty($input['subject_id']) ){ throw new Exception("请选择科目"); } $subject_id = $input['subject_id']; $file = $request->file('Filedata'); // 文件是否上传成功 if ( $request->hasFile('Filedata') && $file->isValid()) { // 获取文件相关信息 $originalName = $file->getClientOriginalName(); // 文件原名 $ext = $file->getClientOriginalExtension(); // 扩展名 $realPath = $file->getRealPath(); //临时文件的绝对路径 $type = $file->getClientMimeType(); // image/jpeg $count = 0; // 导入数量 $icount = 0; // 忽略数量 // 上传文件 $filename = 'question_'.date('Y-m-d-H-i-s') . '.' . $ext; // 使用我们新建的uploads本地存储空间(目录) $bool = Storage::disk('public')->put($filename, file_get_contents($realPath)); if( $bool ){ $filePath = public_path().'/imports/'.$filename; Excel::load($filePath, function($reader) use($subject_id, &$count, &$icount){ $char = ['A'=>3, 'B'=>4, 'C'=>5, 'D'=>6, 'E'=>7, 'F'=>8, 'G'=>9, 'H'=>10, 'I'=>11, 'J'=>12, 'K'=>13]; $reader = $reader->getSheet(0); $res = $reader->toArray(); unset($res[0]); foreach ($res as $k=>$ques){ // 0 题型, 1 题目, 2 答案, 3~? 选项 此处最多支持10个选项 if( trim($ques[0]) == '单选题' ){ $data['question_type_id'] = 1; }else if( trim($ques[0]) == '多选题' ){ $data['question_type_id'] = 2; }else if( trim($ques[0]) == '判断题' ){ $data['question_type_id'] = 3; }else{ throw new \Exception("导入的题目中存在未知题型: ".trim($ques[1])); } // 题目 $data['name'] = trim($ques[1]); // 答案 if( empty(trim($ques[2])) ){ throw new \Exception("导入的题目中存在没有答案的题型"); } $right = str_split(trim($ques[2]), 1); $ans_right = []; foreach ($right as $ri){ if( !isset($char[strtoupper($ri)]) ){ throw new \Exception("导入的题目中答案对应的题型错误"); } $ans_right[$char[strtoupper($ri)]] = strtoupper($ri); } $question['question_type_id'] = $data['question_type_id']; $question['subject_id'] = $subject_id; $question['name'] = $data['name']; $question['des'] = ''; $question['state'] = 1; $question['updated_at'] = date('Y-m-d H:i:s'); // 题目重复判断 $where = [ ['question_type_id', '=', $question['question_type_id']], ['name', '=', $question['name']], ['subject_id', '=', $question['subject_id']], ]; $exist = Question::where($where)->first(); if ($exist) { $icount ++; continue; } else { $count ++; } if( !$question_id = Question::create($question) ){ throw new \Exception("导入题目创建失败, 失败的题目是:".$question['name']); } // 选型 for ($i=3; $i<= 13; $i++ ){ if( isset($ques[$i]) ){ $answer['answer_right'] = isset($ans_right[$i]) ? 1 : 0; $answer['name'] = $ques[$i]; $answer['question_id'] = $question_id['id']; $answer['label'] = IntToChr($i-3); if( !Answer::insert($answer) ){ throw new \Exception("导入题目答案创建失败, 失败的答案是:".$answer['name']); } } } } }); }else{ throw new \Exception("导入失败"); } }else{ throw new \Exception("导入失败"); } DB::commit(); parent::_save_log('question', 'import', ''); echo backJson(true, '题目导入成功,实际导入'.$count.'条,忽略'.$icount.'条'); } catch ( Exception $e ) { DB::rollback(); return backJson(false, $e->getMessage()); } } /** * 页面面包屑 * @return array */ private function breadcrumb(){ return [ [ 'url' => URL::route('question.index'), 'title'=> '题目列表' ] ]; } } <file_sep><?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class ExamQuestion extends Model { protected $table = 'exam_question'; public $timestamps = false; public $guarded = ['id']; function hasoneToQuestion(){ return $this->hasOne(Question::class, 'id', 'question_id'); } function hasManyToAnswer(){ return $this->hasMany(Answer::class, 'id', 'question_id'); } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Answer; use App\Http\Model\Member; use App\Http\Model\Question; use App\Http\Model\QuestionType; use App\Http\Model\Subject; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\URL; class TopicController extends Controller { public function index() { $data['category'] = 'topic'; $data['subCategory'] = 'topic'; $data['breadcrumb'] = $this->breadcrumb(); $data['question_type'] = QuestionType::get(); return view('topic.index', $data); } //添加题目页面 function add(Request $request){ $data['questionData'] = []; $input = $request->all(); if( isset($input['id']) && !empty( $input['id']) ){ $questionData['question'] = Question::where('id', $input['id'])->first(); $questionData['answer'] = $questionData['question']->hasManyToAnswer()->get(); $data['questionData'] = $questionData; $subject_id = $questionData['question']->subject_id; }else{ $subject_id = $input['subject_id']; } $data['subject_id'] = $subject_id; $data['topic_type'] = $input['type']; return view('topic.add', $data); } // 获取科目数 function getSubject(){ $subjectData = Subject::orderBy('sid', 'desc')->get(); $sub[] = [ 'id' => 0, 'text' => '全部科目', 'type' => 'folder', ]; foreach ($subjectData as $subject){ $sub[] = [ 'id' => $subject->id, 'text' => $subject->name, 'type' => 'folder', ]; } return backJson(true, $sub); } // 获取题目 function get(Request $request){ $input = $request->all(); $page = isset( $input['rows'] ) ? $input['rows'] : env('PAGNATION'); if( isset($input['subject_id']) && !empty($input['subject_id']) ){ $topicList = Question::where('state', '<>', 0)->where('subject_id', $input['subject_id'])->paginate($page); }else{ $topicList = Question::where('state', '<>', 0)->paginate($page); } foreach ( $topicList as $k=>$topic){ $topicList[$k]->type = $topic->hasOneToType()->first()->name; $topicList[$k]->subject = $topic->hasOneToSubject()->first()->name; } $topic = [ 'records' => $topicList->total(), 'total'=> $topicList->lastPage(), 'rows' => $topicList->items() ]; return json_encode($topic); } // 题目保存方法 function doAdd(Request $request){ try{ DB::beginTransaction(); $input = $request->all(); $id = $input['topic']['id']; $type = $input['topic_type']; $title = $input['topic']['title']; // $answer_right = $input['topic']['options']['answer']; $answers = $input['topic']['options']; $subject_id = $input['topic']['subject_id']; $question = [ 'question_type_id' => $type, 'name' => $title, 'subject_id' => $subject_id, 'des' => '', 'state' => 1, 'sid' => 1, 'updated_at' => date('Y-m-d H:i:s'), ]; if( isset($id) && !empty($id) ) { // 修改题目 if (!$quesionDb = Question::where('id', $id)->update($question)) { throw new \Exception("系统错误, 题目修改失败"); } $quesion_id = $id; }else{ // 创建题目 if (!$quesionDb = Question::create($question)) { throw new \Exception("系统错误, 题目创建失败"); } $quesion_id = $quesionDb->id; } // 答案 if( isset($id) && !empty($id) ) { // 修改答案 if( ! Answer::where('question_id', $id)->delete() ){ throw new \Exception("系统错误, 原答案删除失败"); } $_question_succ = "题目修改成功"; }else{ $_question_succ = "题目创建成功"; } $answerArr = []; foreach ( $answers['val'] as $key=>$ans) { $answerArr[] = [ 'question_id' => $quesion_id, 'name' => $ans, 'answer_right' => isset($answers['answer'][$key]) && $answers['answer'][$key] == 'on' ? 1 : 0 ]; } if( ! Answer::insert($answerArr) ){ throw new \Exception("系统错误, 题目选项创建错误"); } DB::commit(); return backJson( true , $_question_succ); } catch (\Exception $e){ DB::rollBack(); return backJson(false, $e->getMessage()); } } // 删除题目 function delete(Request $request){ try{ $input = $request->all(); if( !isset($input['id']) || empty($input['id']) ){ throw new \Exception("请选择要删除的题目"); } if ( !Question::where( 'id', $input['id'] )->delete() ){ throw new \Exception("系统错误, 题目删除失败"); } return backJson(true, '删除成功'); } catch (\Exception $e){ return backJson(false, $e->getMessage()); } } /** * 页面面包屑 * @return array */ private function breadcrumb(){ return [ [ 'url' => URL::route('topic.index'), 'title'=> '题库管理' ] ]; } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Candidate; use App\Http\Model\Examination; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\URL; use Exception; use Maatwebsite\Excel\Facades\Excel; class CandidateController extends Controller { /* * 首页 */ public function index() { $data ['category'] = 'examines'; $data ['subCategory'] = 'candidate'; $data ['breadcrumb'] = $this->breadcrumb(); return view('candidate.index', $data); } /* * 获取 */ function get(Request $request) { $input = $request->all(); $page = isset($input ['rows']) ? $input ['rows'] : env('PAGNATION'); $select = "id, code, name, exam_time, phone,addr, score_paper, paper_id, score_paper_retry, paper_retry_id, score_practical, practical_id, score_practical_retry, practical_retry_id, exam_time, if(isnull(pass_time),'不通过','通过') as 'pass'"; if( isset($input['search']) && isset($input['level']) ){ if( $input['level'] == 1 ){ // 年查询 $yearsClass = Examination::select(DB::raw('id, year(begin_time) as y')) ->where('state', '1')->where(DB::raw('year(begin_time)'), $input['search'])->get(); $yearArr = []; foreach ($yearsClass as $year){ $yearArr[] = $year->id; } $list = Candidate::whereIn('examination_id', $yearArr)->select(DB::raw($select))->paginate($page); }else if( $input['level'] == 2 ){ // 月查询 $yearArr = explode('-', $input['search']); $yearsClass = Examination::select(DB::raw('id, month(begin_time) as m')) ->where('state', '1')->where(DB::raw('year(begin_time)'), $yearArr[0])->where(DB::raw('month(begin_time)'), $yearArr[1])->get(); $monArr = []; foreach ($yearsClass as $year){ $monArr[] = $year->id; } $list = Candidate::whereIn('examination_id', $monArr)->select(DB::raw($select))->paginate($page); }else{ $list = Candidate::where('examination_id', $input['search'])->select(DB::raw($select))->paginate($page); } } else if(isset($input['user'])){ $con = '%'.$input['user'].'%'; $list = Candidate::where('name', 'like', $con) ->orWhere('id_no', 'like', $con)->select(DB::raw($select))->paginate($page); } else { $list = Candidate::select(DB::raw($select))->paginate($page); } foreach ($list as $k=>$row) { if ($row->paper_id) { $url = URL::route('examine.finish', ['paper_id'=>$row->paper_id, 'type'=>1, 'source'=>1]); $row->score_paper = '<a href="'.$url.'" target="_blank">'.$row->score_paper.'</a>'; } if ($row->paper_retry_id) { $url = URL::route('examine.finish', ['paper_id'=>$row->paper_retry_id, 'type'=>4, 'source'=>1]); $row->score_paper_retry = '<a href="'.$url.'" target="_blank">'.$row->score_paper_retry.'</a>'; } if ($row->practical_id) { $url = URL::route('examine.finish', ['paper_id'=>$row->practical_id, 'type'=>2, 'source'=>1]); $row->score_practical = '<a href="'.$url.'" target="_blank">'.$row->score_practical.'</a>'; } if ($row->practical_retry_id) { $url = URL::route('examine.finish', ['paper_id'=>$row->practical_retry_id, 'type'=>2, 'source'=>1]); $row->score_practical_retry = '<a href="'.$url.'" target="_blank">'.$row->score_practical_retry.'</a>'; } if ($row->pass == '通过') { $list[$k]->pass = '<div style="height:25px;width:60px;line-height:25px;background:rgb(135,184,127);">已通过</div>'; } else { $list[$k]->pass = '<div style="height:25px;width:60px;line-height:25px; background:rgb(208,91,71);">未通过</div>'; } } $result = [ 'records' => $list->total(), 'total' => $list->lastPage(), 'rows' => $list->items() ]; return json_encode($result); } // 获取考生信息 function getInfo(Request $request){ $input = $request->all(); $stuInfo = Candidate::whereIn('id', $input['id'])->get(); $stuk = []; foreach ($stuInfo as $k=>$stu){ $stuInfo[$k]->repeat_time = date('Y年m月', strtotime($stu->hasoneToClass()->first()['repeat_time'])); $stuInfo[$k]->training_time = date('Y-m-d', strtotime($stu->training_time)); $stuInfo[$k]->begin_time = date('Y-m-d', strtotime($stu->hasoneToClass()->first()['begin_time'])); $stuInfo[$k]->end_time = date('Y-m-d', strtotime($stu->hasoneToClass()->first()['end_time'])); $str = ''; $i = 0; foreach ($training as $key=>$tran){ if( $i <6 ) { $tra = $tran->hasoneToTraining()->first(); if( $tra != null ){ $tra = $tra->toArray(); $str .= '<tr>'; $str .= '<td style="width:15%;text-align:center;">' . ($key + 1) . '</td>'; $str .= '<td style="width:70%;text-align:left;">' . $tra['name']. '</td>'; $str .= '<td style="width:15%;text-align:center;">' . floor($tra['duration']) . '</td>'; $str .= '</tr>'; } } $i++; } $stuk[$k] = $str; } $data['info'] = $stuInfo; $data['tran'] = $stuk; return backJson(true, $data); } // 查看考卷 function paper(Request $request, $id) { echo $id; } // 获取考卷信息 function getPaper(Request $request) { $input = $request->all(); $student = Students::where('id', $input['id'])->first(); $print = $student->hasManyToPrint()->get(); foreach ($print as $k=>$item) { $user = $item->hasOneToUser()->first(); $print[$k]->print_user = $user->name; } $result = [ 'rows' => $print, ]; return json_encode($result); } // 导入考生信息 function import(Request $request){ DB::beginTransaction(); try{ $input = Input::get(); if( !isset($input['examination_id']) || empty($input['examination_id']) ){ throw new Exception("请选择考试"); } $examination_id = $input['examination_id']; $file = $request->file('Filedata'); // 文件是否上传成功 if ( $request->hasFile('Filedata') && $file->isValid()) { // 获取文件相关信息 $originalName = $file->getClientOriginalName(); // 文件原名 $ext = $file->getClientOriginalExtension(); // 扩展名 $realPath = $file->getRealPath(); //临时文件的绝对路径 $type = $file->getClientMimeType(); // image/jpeg // 上传文件 $filename = 'can_'.date('Y-m-d-H-i-s') . '.' . $ext; // 使用我们新建的uploads本地存储空间(目录) $bool = Storage::disk('public')->put($filename, file_get_contents($realPath)); if( $bool ){ $filePath = public_path().'/imports/'.$filename; Excel::load($filePath, function($reader) use($examination_id){ $reader = $reader->getSheet(0); $res = $reader->toArray(); unset($res[0]); array_pop($res); foreach ($res as $r){ $data = [ 'examination_id' => $examination_id, 'code' => $r[30], 'name' => $r[1], 'pinyin' => $r[0], 'gender' => $r[2], 'birthday' => $r[3], 'papers_id'=> $r[4], 'task_type'=> $r[5], 'id_no' => $r[6], 'project' => $r[7], 'category' => $r[8], 'education'=> $r[9], 'health' => $r[10], 'job' => $r[11], 'title' => $r[12], 'political'=> $r[13], 'profession_study'=> $r[14], 'profession_job' => $r[15], 'work_time' => $r[16], 'phone' => $r[17], 'company_type'=> $r[18], 'company' => $r[19], 'training_type'=> $r[21], 'training_time'=> $r[22], // 'score_paper' => $r[23], // 'score_paper_retry'=> $r[24], // 'score_practical' => $r[25], // 'score_practical_retry'=> $r[26], 'addr' => $r[27], 'exam_time' => $r[28], // 'pass_time' => $r[29], 'des' => $r[20], ]; if( !Candidate::insert( $data ) ){ throw new Exception("考生信息创建失败"); } } }); }else{ throw new Exception("上传失败"); } }else{ throw new Exception("上传失败"); } DB::commit(); parent::_save_log('candidate', 'import', ''); echo backJson(true, '考生信息创建成功'); } catch ( Exception $e ) { DB::rollback(); return backJson(false, $e->getMessage()); } } // 学生班级 function getExamination(){ $data = Examination::orderBy('sid', 'desc')->get(); $sub = []; foreach ($data as $cls){ $sub[] = [ 'id' => $cls->id, 'text' => $cls->name, 'type' => 'folder', ]; } return backJson(true, $sub); } /* * 删除学生 */ function delete(Request $req) { DB::beginTransaction(); try { if (! isset($req->ids) || empty($req->ids)) { throw new Exception("请选择要删除的考生"); } $stuNames = ''; foreach ($req->ids as $ids){ $stu = Candidate::where('id', $ids)->first(); $stuNames .= $stu['name'].' ,'; } // 删除学生信息 if (! Candidate::whereIn('id', $req->ids)->delete()) { throw new Exception("系统错误, 删除考生失败"); } parent::_save_log('candidate', 'del', $stuNames); DB::commit(); return backJson(true, '删除考生成功'); } catch ( Exception $e ) { DB::rollback(); return backJson(false, $e->getMessage()); } } /* * 页面路径 */ private function breadcrumb() { return [ [ 'url' => URL::route('candidate.index'), 'title'=> '考生列表' ] ]; } }<file_sep><?php $__env->startSection('header_style'); ?> <script src="<?php echo e(URL::asset('components/jqGrid/js/jquery.jqGrid.js')); ?>"></script> <script src="<?php echo e(URL::asset('components/jqGrid/js/i18n/grid.locale-cn.js')); ?>"></script> <style> .ui-datepicker-calendar { display: none; } </style> <?php $__env->stopSection(); ?> <?php $__env->startSection('content'); ?> <div class="row"> <div class="col-xs-12"> <div class="jqGrid_tools clearfix"> <form role="form" method="POST" action="<?php echo e(URL::route('printAdmission.get')); ?>" class="form-horizontal col-sm-12 print_search"> <?php echo e(csrf_field()); ?> <div class="form-group"> <label for="manType" class="col-sm-1 control-label">人员类别</label> <div class="col-sm-3"> <select class="form-control input-sm" id="manType"> <option value="全部">全部</option> <option value="主要负责人">主要负责人</option> <option value="安全生产管理人员">安全生产管理人员</option> </select> </div> <label for="comType" class="col-sm-1 control-label">行业类别</label> <div class="col-sm-3"> <select class="form-control input-sm" id="comType"> <option value="全部">全部</option> <option value="危险化学品生产单位">危险化学品生产单位</option> <option value="危险化学品经营单位">危险化学品经营单位</option> <option value="烟花爆竹经营单位">烟花爆竹经营单位</option> <option value="金融冶炼">金融冶炼</option> </select> </div> </div> <div class="form-group"> <label for="beginTime" class="col-sm-1 control-label">开始时间</label> <div class="col-sm-3"> <div class="input-group"> <input type="date" class="form-control input-sm" id="beginTime"/> <span class="input-group-addon"><i class="ace-icon fa fa-calendar"></i></span> </div> </div> <label for="endTime" class="col-sm-1 control-label">结束时间</label> <div class="col-sm-3"> <div class="input-group"> <input type="date" class="form-control input-sm" id="endTime"/> <span class="input-group-addon"><i class="ace-icon fa fa-calendar"></i></span> </div> </div> <div class="col-sm-1"> <button type="button" class="form-control btn btn-sm btn-primary" id="btn_search"> <span class="ace-icon fa fa-search icon-on-right bigger-110"></span> 查询 </button> </div> </div> </form> </div> <table id="jqgrid-table-1"></table> <div id="jqgrid-pager-1"></div> </div> </div> <?php $__env->stopSection(); ?> <?php $__env->startSection('footer_script'); ?> <script type="text/javascript"> $(document).ready(function(){ $('#beginTime,#endTime').datepicker({ zIndex: 999, changeMonth: true, changeYear: true, dateFormat: 'yy-MM', showButtonPanel: true, onClose: function(dateText, inst) { var month = $("#ui-datepicker-div .ui-datepicker-month option:selected").val();//得到选中的月份值 var year = $("#ui-datepicker-div .ui-datepicker-year option:selected").val();//得到选中的年份值 $(this).val(year+'-'+(parseInt(month)+1));//给input赋值,其中要对月值加1才是实际的月份 } }); $('#btn_search').on('click', function(){ var beginTime = $('#beginTime').val(); var endTime = $('#endTime').val(); var manType = $('#manType').val(); var comType = $('#comType').val(); var cons = []; if (beginTime) { cons.push('beginTime=' + beginTime); } if (endTime) { cons.push('endTime=' + endTime); } cons.push('manType=' + manType); cons.push('comType=' + comType); var con = cons.join('&'); $("#jqgrid-table-1").jqGrid('setGridParam', { url: "<?php echo e(URL::route('printAdmission.get')); ?>?" + encodeURI(con), page: 1 }).trigger("reloadGrid"); }); }); </script> <?php echo $__env->make('common.jqgrid', [ 'index' => 1, 'rowListShow'=> "['20', '40', '60']", 'rowNum' => 20, 'url' => URL::route('printAdmission.get'), 'colnames' => "['人员类别','单位类别','班级', '人数', '已打印人数','重复打印人数']", 'colModel' => json_encode([ ['name' => 'category'], ['name' => 'company_type'], ['name' => 'class_name'], ['name' => 'rs'], ['name' => 'dys'], ['name' => 'cds'], ]) ], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php $__env->stopSection(); ?> <?php echo $__env->make('addi.app', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?><file_sep>(function () { // 获取 wangEditor 构造函数和 jquery var E = window.wangEditor; var $ = window.jQuery; // 用 createMenu 方法创建菜单 E.createMenu(function (check) { // 定义菜单id,不要和其他菜单id重复。编辑器自带的所有菜单id,可通过『参数配置-自定义菜单』一节查看 var menuId = 'sys_img'; // check将检查菜单配置(『参数配置-自定义菜单』一节描述)中是否该菜单id,如果没有,则忽略下面的代码。 if (!check(menuId)) { return; } // this 指向 editor 对象自身 var editor = this; // 创建 menu 对象 var menu = new E.Menu({ editor: editor, // 编辑器对象 id: menuId, // 菜单id title: '上传图片', // 菜单标题 // 正常状态和选中状态下的dom对象,样式需要自定义 $domNormal: $('<a href="#" tabindex="-1"><i class="wangeditor-menu-img-picture"></i></a>'), $domSelected: $('<a href="#" tabindex="-1" class="selected"><i class="wangeditor-menu-img-picture"></i></a>') }); // 菜单正常状态下,点击将触发该事件 menu.clickEvent = function (e) { // 找到当前选区所在的 p 元素 var elem = editor.getRangeElem(); var p = editor.getSelfOrParentByName(elem, 'p'); var $p; if (!p) { // 未找到 p 元素,则忽略 return e.preventDefault(); } $p = $(p); // 使用自定义命令 function commandFn() { var _name = $(editor.$valueContainer.selector).attr('upload_name'); var _item_id = $('#temp_item_id').val(); $.ajax({ type: 'post', url: 'design/load/image/'+_item_id, data: {_token: _csrf_token}, dataType: "json", beforeSend: function () { show_msg('info', '正在加载') }, success: function (data) { $.getScript('static/uploadfive/jquery.uploadifive.min.js') layer.open({ shadeClose: true, type: 1, title: '图片管理', shade: false, offset: 'r', id: 'design_image_dialog', area: ['600px', '500px'], content: htmlspecialchars_decode(data.msg), btn: ['保存', '取消'], yes: function(index, layero){ var selectedImg = $("#user_selected_file").val(); if(selectedImg == ''){ show_msg(false, '请选择或者上传图片'); return ; } editor.$txt.append('<img src="'+ selectedImg +'">'); layer.close(index); } }); } }) // // (new $.zui.ModalTrigger({remote: '/common/upload?name='+ _name})).show(); // $(document).on('click', '.upload_use_image_'+_name, function(){ // var _val = $(this).parents('.modal-content').find("#user_selected_file").val() // editor.$txt.append('<img src="'+ _val +'">'); // $(document).off("click", '.upload_use_image_'+_name); // }) } editor.customCommand(e, commandFn); }; menu.updateSelectedEvent = function (e) { // 获取当前选区所在的父元素 var elem = editor.getRangeElem(); var p = editor.getSelfOrParentByName(elem, 'p'); var $p; var indent; if (!p) { // 未找到 p 元素,则标记为未处于选中状态 return false; } $p = $(p); indent = $p.css('text-indent'); if (!indent || indent === '0px') { // 得到的p,text-indent 属性是 0,则标记为未处于选中状态 return false; } // 找到 p 元素,并且 text-indent 不是 0,则标记为选中状态 return true; }; // 增加到editor对象中 editor.menus[menuId] = menu; }); })();<file_sep><button class="btn btn-sm btn-primary list_import" > <i class="ace-icon fa fa-plus align-top bigger-125"></i> 导入 </button> <div class="modal fade" role="dialog" id="<?php echo e($import_target); ?>"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title">导入学生</h4> </div> <form class="form-horizontal <?php echo e($import_target); ?>" role="form" action="<?php echo e(URL::route('students.import')); ?>" method="POST" enctype="muitipart/form-data"> <?php echo e(csrf_field()); ?> <div class="modal-body"> <div class="form-group"> <label class="col-sm-3 control-label" for="name">导入 <span class="text-danger">*</span></label> <div class="col-sm-6"> <input type="file" id="stus" placeholder="请上传学生信息" name="stus" class="form-control"/> </div> </div> </div> </form> </div> </div> </div> <script> $(function(){ var _class_id; $(".list_import").click(function(){ var treeData = $('#tree2').tree('selectedItems'); if( treeData != '' &&treeData[0].level == 3 ){ _class_id = treeData[0].id; }else{ show_msg(false, '请选择班级'); return false; } $('#<?php echo e($import_target); ?>').modal(); }) $('#stus').uploadifive({ 'buttonClass' : 'btn btn-info', 'buttonText' : '<i class="icon-upload-alt"></i> 点击上传', 'fileType' : '*', 'multi' : false, 'height' : 'auto', 'fileSizeLimit': 10240, 'truncateLength' : 2, 'uploadScript' : "<?php echo e(URL::route('students.import')); ?>", 'onUpload': function () { $("#stus").data('uploadifive').settings.formData = { 'class_id': _class_id, _token : "<?php echo e(csrf_token()); ?>"}; show_msg('info', '正在上传'); }, 'onUploadComplete' : function(file, data) { data = eval('(' + data + ')'); show_msg(data.code, data.msg); if(data.code){ var p = $("#jqgrid-table-1").jqGrid('getGridParam','page'); $("#jqgrid-table-1").jqGrid('setGridParam', { page: p, }).trigger("reloadGrid"); $("#stu_import").find('.close').click() } } }); }) </script><file_sep><?php namespace App\Http\Middleware; use Closure; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; class VerifyCsrfToken extends BaseVerifier { /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'article/getContent', 'score/export', ]; public function handle($request, Closure $next) { if( strpos($request->getRequestUri(), 'examine/') ){ if( in_array(Route::currentRouteName(), ['examine.save', 'examine.get.test']) ){ if( $request->session()->exists('stu_info') == false) { if (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest") { echo backJson(false, "您的session 已到期, 请重新考试"); die(); } } } }else { if( strpos($request->getRequestUri(), 'zhengjian/') ) { }else{ if (Auth::user() === null) { if (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest") { echo backJson(false, "您的session 已到期, 请重新登录后再试"); die(); } } } } return $next($request); } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Log; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Auth; class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; function __construct() { $this->middleware('auth'); } function _save_log($module, $type, $des){ $data = [ 'user_id' => Auth::user()->id, 'module' => logModule()[$module]['name'], 'dt' => date('Y-m-d H:i:s'), 'des' => logModule()[$module]['types'][$type].'-'.$des, ]; if( !Log::create($data) ){ throw new \Exception("日志保存错误"); } } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Log; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\URL; class LogController extends Controller { function __construct() { parent::__construct(); } /* * 首页 */ public function index() { $data ['category'] = 'base'; $data ['subCategory'] = 'log'; $data ['breadcrumb'] = $this->breadcrumb(); return view('base.log', $data); } /* * 获取用户列表 */ function get(Request $request) { $input = $request->all(); $page = isset($input ['rows']) ? $input ['rows'] : env('PAGNATION'); $logList = Log::where('user_id', Auth::user() ['id'])->orderBy('dt', 'desc')->paginate($page); foreach ($logList as $k=>$log){ $logList[$k]->user_name = $log->user_id; $logList[$k]->module_name = logModule()[$log->modulee_id]; } $logs = [ 'records' => $logList->total(), 'total' => $logList->lastPage(), 'rows' => $logList->items() ]; return json_encode($logs); } /* * 页面路径 */ private function breadcrumb() { return [ [ 'url' => URL::route('user.index'), 'title'=> '日志管理' ] ]; } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Article; use App\Http\Model\ArticleCategory; use Illuminate\Http\Request; use Illuminate\Support\Facades\URL; class ArticleCategoryController extends Controller { public function index(Request $request) { $data ['category'] = 'articles'; $data ['subCategory'] = 'articlecategory'; $data ['breadcrumb'] = $this->breadcrumb(); $data['categoryData'] = $this->getCategory(1); $data['categoryList'] = $this->getCategory(2); return view('category.index', $data); } // 获取某一个模块的信息 function getOne(Request $request){ $input = $request->all(); $category = ArticleCategory::where('id', $input['id'])->first(); return backJson(true, $category); } // 获取分类 public function getCategory($type = 1, $cate='all') { if($cate != 'all') { $where = ['status'=>1]; }else{ $where = []; } $categorylist = ArticleCategory::where($where)->orderBy('sid', 'asc')->get()->toArray(); $list = genTree($categorylist); $str = ''; if( $type == 1 ) { $str .= '<ol class="dd-list">'; foreach ($list as $li) { $str .= $this->genTreeStr($li); } $str .= '</ol>'; }else if( $type == 2 ) { foreach ($list as $li) { $num = 0; $str .= "<option value='".$li['id']."'>".$li['title']."</option>"; $str .= $this->getCategoryOption($li, $num); } } return $str; } function getCategoryOption($data, $num){ $str = ''; $num ++; if( isset($data['children']) ){ foreach ($data['children'] as $children) { $split = str_repeat("&nbsp;", ($num)*6); $str .= '<option value="'.$children['id'].'">'; $str .= $split.$children['title']; $str .= '</option>'; $str .= $this->getCategoryOption($children, $num); } } return $str; } function genTreeStr($data){ $str = '<li class="dd-item" data-id="'.$data['id'].'">'; $str .= '<div class="dd-handle dd2-handle">' ; $str .= '<i class="drag-icon ace-icon fa fa-arrows bigger-125"></i>'; $str .= '</div>'; $str .= '<div class="dd2-content">' . $data['title']; if( !$data['status'] ){ $str .= ' <label class="label label-danger label-sm" style="margin:0;">已禁用</label>'; } $str .= '<div class="pull-right action-buttons">'; $str .= '<a class="blue edit_category" data-id='.$data['id'].' href="javascript:;">'; $str .= '<i class="ace-icon fa fa-pencil bigger-130"></i>'; $str .= '</a>'; $str .= '<a class="blue del_category" data-id='.$data['id'].' href="javascript:;">'; $str .= '<i class="ace-icon fa fa-trash-o bigger-130"></i>'; $str .= '</a>'; $str .= '</div>'; $str .= '</div>'; if( isset($data['children']) ){ foreach ($data['children'] as $children) { $str .= '<ol class="dd-list">'; $str .= $this->genTreeStr($children); $str .= '</ol>'; } } $str .= '</li>'; return $str; } // 保存排序值 function saveSort(Request $request){ try{ $input = $request->all(); $sort = $input['sort']; $s = $this->spellSort($sort, 0); $sortData = array_multi2single($s); foreach ($sortData as $k=>$so){ ArticleCategory::where('id', $so['id'])->update(['pid'=>$so['pid'], 'sid'=>$k]); } return backJson(true, '保存成功'); } catch (\Exception $e){ return backJson(false, $e->getMessage()); } } /** * @param $sort * @return array */ function spellSort($sort, $pid, $i=0){ foreach ($sort as $s) { $data[$i]['id'] = $s['id']; $data[$i]['pid'] = $pid; if (isset($s['children'])) { $data[$i]['children'] = $this->spellSort($s['children'], $s['id'], $i); } $i++; } return $data; } // 添加分类方法 public function addCategory(Request $request) { try { $article = null; if (isset($request->id) && !empty($request->id)) { $message = '修改类别'; $operate = 'edit'; $article = ArticleCategory::findOrFail($request->id); $article->title = $request->title; $article->sid = $request->sid; $article->status = $request->status; $article->pid = $request->pid; $article->update(); } else { $message = '添加类别'; $operate = 'add'; $article = new ArticleCategory; $article->title = $request->title; $article->sid = $request->sid; $article->status = $request->status; $article->pid = $request->pid; $article->save(); } parent::_save_log('articleCategory', $operate, $article->title); return backJson(true, $message.'成功!', '/category/index'); } catch (Exception $e) { return backJson(false, $message.'失败:'.$e->getMessage()); } } public function deleteCategory(Request $request) { try { if (!isset($request->id) || empty($request->id)) { throw new \Exception("请选择要删除的新闻类别"); } $parentCategory = ArticleCategory::where('pid', $request->id)->count(); if ( $parentCategory > 0 ) { throw new \Exception("请先删除子类别后再删除出该类别"); } $categoryArticles = Article::where('category_id', $request->id)->count(); if ( $categoryArticles > 0 ) { throw new \Exception("该类别下有相关新闻, 请先删除关联新闻后再删除该类别"); } $articleCategory = ArticleCategory::findOrFail($request->id); $title = $articleCategory->title; $articleCategory->delete(); parent::_save_log('articleCategory', 'del', $title); return backJson(true, '新闻类别删除成功'); } catch ( \Exception $e ) { return backJson(false, $e->getMessage()); } } /** * 页面面包屑 * * @return array */ private function breadcrumb() { return [ [ 'url' => URL::route('article.index'), 'title' => '新闻类别' ] ]; } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Exam; use App\Http\Model\ExamEval; use App\Http\Model\ExamQuestion; use App\Http\Model\ExamQuestionType; use App\Http\Model\Member; use App\Http\Model\Question; use App\Http\Model\QuestionType; use App\Http\Model\Subject; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\URL; class ExamController extends Controller { function __construct() { parent::__construct(); } public function index(Request $request) { $data['category'] = 'examines'; $data['subCategory'] = 'examine'; $data['breadcrumb'] = $this->breadcrumb(); $data['subjectData'] = Subject::where('state', '<>', 0)->get(); $data['questionType'] = QuestionType::get(); return view('exam.index', $data); } // 获取考试题目 function getQuestion(Request $request){ $input = $request->all(); if( isset($input['subject_id']) && !empty($input['subject_id']) ){ $questionData = Question::where('state', '<>', 0)->where('subject_id', $input['subject_id'])->get(); }else{ $questionData = Question::where('state', '<>', 0)->get(); } foreach ($questionData as $k=>$question){ $questionData[$k]['name'] = '('.$question->hasOneToType()->first()->name.') '.$question->name; } $examQuestion = ExamQuestion::where('exam_id', $input['exam_id'])->get(); $questionTxt = $examQuestionText = ''; foreach ($questionData as $question){ $cls = ''; foreach ($examQuestion as $examques){ if( $examques->question_id == $question->id ){ $cls = 'hide'; $examQuestionText .= "<li data-typeid={$question->question_type_id} data-value='".$question->id."' ondblclick='delQuestion(this)'>"; $examQuestionText .= "<span class='title'>{$question->name}</span>"; $examQuestionText .= "<span class='fa fa-trash-o delete'></span>"; $examQuestionText .= "<span class='fa fa-arrow-circle-o-down down'>"; $examQuestionText .= "<span class='fa fa-arrow-circle-o-up up'>"; $examQuestionText .= "</li>"; } } $questionTxt .= "<option data-typeid={$question->question_type_id} value='". $question->id ."' class='".$cls."'>{$question->name}</option>"; } return backJson(true, ['questionTxt'=>$questionTxt, 'examQuestion'=>$examQuestionText]); } // 保存考试信息 function doSave(Request $request){ DB::beginTransaction(); try{ $input = $request->all(); if( empty($input['total_score']) && empty($input['strategy']) ){ // throw new \Exception("您的考试方式为手动生成, 请设置考试题型数量以及分数"); } if( empty($input['subject']) ){ throw new \Exception("请选择考试科目"); } $examData = [ 'subject_id' => $input['subject'], 'name' => $input['name'], 'duration' => $input['duration'], 'strategy' => $input['strategy'], 'score' => $input['total_score'], 'price' => 0, 'des' => $input['des'], 'sid' => 1, 'state' => 1, 'updated_at' => date('Y-m-d H:i:s') ]; if( isset($input['id']) && !empty($input['id']) ){ // 修改考试 $exam_id = $input['id']; if (!$examBack = Exam::where('id', $exam_id)->update($examData)) { throw new \Exception("系统错误, 考试创建失败"); } ExamQuestionType::where('exam_id', $exam_id)->delete(); ExamEval::where('exam_id', $exam_id)->delete(); $logType = 'edit'; }else { //创建考试 if (!$examBack = Exam::create($examData)) { throw new \Exception("系统错误, 考试创建失败"); } $exam_id = $examBack->id; $logType = 'add'; } // 题型分数 foreach ($input['questionType'] as $k=>$questionType){ $examQuestionType = [ 'exam_id' => $exam_id, 'question_type' => $k, 'score' => $questionType['score'], 'nums' => $questionType['nums'], 'amount' => $questionType['score'] * $questionType['nums'] ]; if( !ExamQuestionType::create($examQuestionType) ){ throw new \Exception("系统错误, 考试题型创建失败"); } } // 考评等级 foreach ($input['examEval'] as $k=>$examEval){ $eval = [ 'exam_id' => $exam_id, 'name' => $examEval['name'], 'min_score' => $examEval['min'], 'max_score' => $examEval['max'], ]; if( !ExamEval::create($eval) ){ throw new \Exception("系统错误, 考试评级创建失败"); } } parent::_save_log('exam', $logType, $input['name']); DB::commit(); return backJson(true, '考试创建成功'); } catch (\Exception $e) { DB::rollBack(); return backJson(false, $e->getMessage()); } } // 保存考题 function saveQuestion(Request $request){ try { $input = $request->all(); if( !isset($input['exam_id']) || empty($input['exam_id']) ){ throw new \Exception("请选择考试"); } if( ExamQuestion::where('exam_id', $input['exam_id'])->count() > 0 ) { // if (!ExamQuestion::where('exam_id', $input['exam_id'])->delete()) { throw new \Exception("创建失败, 原题目删除失败"); } } $ExamQuestion = []; foreach ($input['question'] as $k=>$question){ $ExamQuestion[] = [ 'exam_id' => $input['exam_id'], 'question_id' => $question, 'sid' => $k ]; } $examInfo = Exam::where('id', $input['exam_id'])->first(); if( !ExamQuestion::insert( $ExamQuestion ) ){ throw new \Exception("系统错误, 考试题目创建失败"); } parent::_save_log('exam', 'setQuestion', $examInfo['name']); return backJson(true, '考试题目设置成功'); } catch (\Exception $e) { return backJson(false, $e->getMessage()); } } // 获取考试信息 function get(Request $request){ $input = $request->all(); $page = isset( $input['rows'] ) ? $input['rows'] : env('PAGNATION'); $examList = Exam::where('state', '<>', 0)->paginate($page); foreach ( $examList as $k=>$question){ $examList[$k]->subject = $question->hasOneToSubject()->first()->name; $examList[$k]->subject_id = $question->subject_id; $examList[$k]->strategy_name = !$question->strategy ? '手动生成' : '自动生成'; } $examData = [ 'records' => $examList->total(), 'total'=> $examList->lastPage(), 'rows' => $examList->items() ]; return json_encode($examData); } // 查询得到考试的信息 function getExamInfo(Request $request){ try { $input = $request->all(); $exam['info'] = Exam::where('id', $input['id'])->first(); $exam['eval'] = $exam['info']->hasManyToEval()->get(); $exam['question'] = $exam['info']->hasManyToQuestion()->get(); $exam['questionType'] = $exam['info']->hasManyToQuestionType()->get(); return backJson(true, $exam); } catch (\Exception $e) { return backJson(false, $e->getMessage()); } } // 删除考试 function delete(Request $request){ DB::beginTransaction(); try { $input = $request->all(); if (!isset($input['id']) || empty($input['id'])) { throw new \Exception("请选择要删除的考试"); } $examInfo = Exam::where('id', $input['id'])->first(); // 删除考试 if (!Exam::where('id', $input['id'])->delete()) { throw new \Exception("系统错误, 考试删除失败"); } // 删除考试题型 if (!ExamQuestionType::where('exam_id', $input['id'])->delete()) { throw new \Exception("系统错误, 考试题型删除失败"); } // 删除考试评级 if (!ExamEval::where('exam_id', $input['id'])->delete()) { throw new \Exception("系统错误, 考试评级删除失败"); } parent::_save_log('exam', 'del', $examInfo['name']); DB::commit(); return backJson(true, '删除成功'); } catch (\Exception $e) { DB::rollBack(); return backJson(false, $e->getMessage()); } } /** * 页面面包屑 * @return array */ private function breadcrumb(){ return [ [ 'url' => URL::route('exam.index'), 'title'=> '考试列表' ] ]; } } <file_sep><?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class Question extends Model { protected $table = 'question'; public $timestamps = false; public $guarded = ['id']; // 题目关联答案表 function hasManyToAnswer() { return $this->hasMany(Answer::class, 'question_id', 'id'); } // 题目类型关联 function hasOneToType() { return $this->hasOne(QuestionType::class, 'id', 'question_type_id'); } // 题目科目 function hasOneToSubject() { return $this->hasOne(Subject::class, 'id', 'subject_id'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Response; class UploadController extends Controller { function doUpload(){ $file = Input::file("Filedata"); if($file->isValid()){ $userMd5 = md5(Auth::user()->id); $path = 'uploads/'.$userMd5.'/default/'; $realPath = public_path($path); // 绝对路劲 $extension = $file->getClientOriginalExtension(); // 后缀 $newName = date("YmdHis").mt_rand(100, 999).'.'.$extension; $pathUrl = $file -> move( $realPath, $newName ); $image_url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$path.$newName; $image_path = public_path($path.$newName); $handle = fopen(public_path($path.$newName), "r"); $fstat = fstat($handle); // 结束 $data = [ 'code' => true, 'url' => $image_url, 'filename' => basename($image_path), 'filesize' => round($fstat["size"]/1024,2).' KB', 'lasttime' => date("Y-m-d h:i:s",$fstat["mtime"]), ]; return backJson(true, $data); }else{ return backJson(false, '文件上传失败'); } } }<file_sep><?php /** * JSON 返回值 * @param string $code * @param string $msg * @return string */ function backJson($code = false, $msg = '', $url = ''){ return json_encode(['code'=>$code, 'msg'=>$msg, 'url' => $url]); } // 日志记录全部模块 function logModule(){ return [ 'add_news' => '添加新闻', 'edit_news' => '编辑新闻', 'del_news' => '删除新闻', 'add_subject' => '添加科目', 'edit_subject'=> '编辑科目', 'del_subject' => '删除科目', 'add_topic' => '添加题目', 'edit_topic' => '编辑题目', 'del_topic' => '删除题目', 'add_user' => '添加用户', 'edit_user' => '编辑用户', 'del_user' => '删除以用户', 'add_role' => '添加权限', 'edit_role' => '编辑权限', 'del_role' => '删除权限', 'add_module' => '添加模块', 'edit_module' => '编辑模块', 'del_module' => '删除模块', ]; }<file_sep><?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class Settings extends Model { protected $table = 'settings'; public $timestamps = false; } <file_sep><div class="breadcrumbs ace-save-state" id="breadcrumbs"> <ul class="breadcrumb"> <li> <i class="ace-icon fa fa-home home-icon"></i> <a href="<?php echo e(URL::route('home')); ?>">系统主页</a> </li> <?php if( !empty($breadcrumb) ): ?> <?php $__currentLoopData = $breadcrumb; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $k=>$bread): $__env->incrementLoopIndices(); $loop = $__env->getFirstLoop(); ?> <li class="<?php if(count($breadcrumb) == $k + 1): ?> active <?php endif; ?>"> <?php if(count($breadcrumb) != $k + 1 ): ?> <a href="<?php echo e(URL::route('home')); ?>"> <?php endif; ?> <?php echo e($bread['title']); ?> <?php if(count($breadcrumb) != $k + 1 ): ?> <a href="<?php echo e(URL::route('home')); ?>"> <?php endif; ?> </li> <?php endforeach; $__env->popLoop(); $loop = $__env->getFirstLoop(); ?> <?php endif; ?> </ul> </div><file_sep><?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class UserRole extends Model { protected $table = 'user_role'; public $timestamps = false; protected $fillable = ['user_id', 'role_id']; function hasoneToRole(){ return $this->hasOne(Role::class, 'id', 'role_id'); } // 关联模块 function hasManyToRole(){ return $this->hasMany(Role::class, 'id', 'role_id'); } } <file_sep><?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class Exam extends Model { protected $table = 'exam'; public $timestamps = false; public $guarded = ['id']; // 题目科目 function hasOneToSubject(){ return $this->hasOne(Subject::class, 'id', 'subject_id'); } // 考试关联考评 function hasManyToEval(){ return $this->hasMany(ExamEval::class, 'exam_id', 'id'); } // 考试关联题目 function hasManyToQuestion(){ return $this->hasMany(ExamQuestion::class, 'exam_id', 'id'); } // 考试关联题目数量份数 function hasManyToQuestionType(){ return $this->hasMany(ExamQuestionType::class, 'exam_id', 'id'); } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Trainings; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\URL; use Exception; use App\Http\Model\ClassTraining; class TrainingsController extends Controller { /* * 首页 */ public function index() { $data ['category'] = 'training'; $data ['subCategory'] = 'trainings'; $data ['breadcrumb'] = $this->breadcrumb(); return view('trainings.index', $data); } /* * 获取用户列表 */ function get(Request $request) { $input = $request->all(); $page = isset($input ['rows']) ? $input ['rows'] : env('PAGNATION'); $list = Trainings::orderBy('sid', 'asc')->paginate($page); foreach ($list as $i=>$row) { $list[$i]['state_text'] = $row->state ? '正常' : '禁用'; } $result = [ 'records' => $list->total(), 'total' => $list->lastPage(), 'rows' => $list->items() ]; return json_encode($result); } /* * 添加和修改用户 */ function edit(Request $request) { try { $input = $request->all(); $data = [ 'name' => $input['name'], 'duration' => $input['duration'], 'state' =>$input['state'], 'sid' => $input['sid'], ]; if (isset($input ['id']) && ! empty($input ['id'])) { Trainings::where('id', $input['id'])->update($data); $logType = 'edit'; $_success_txt = '课程信息修改成功'; } else { if (! Trainings::create($data)) { throw new Exception("系统错误, 课程添加失败"); } $logType = 'add'; $_success_txt = '课程添加成功'; } parent::_save_log('trainings', $logType, $input['name']); return backJson(true, $_success_txt); } catch ( Exception $e ) { return backJson(false, $e->getMessage()); } } /* * 删除用户 */ function delete(Request $request) { try { $input = $request->all(); if (! isset($input ['id']) || empty($input ['id'])) { throw new Exception("请选择要删除的课程"); } $training = Trainings::where('id', $input['id'])->first(); // 判断是培训是否被班级引用 if (ClassTraining::where('training_id', $input['id'])->count()>0) { throw new Exception('该培训课程已被使用,不允许删除!'); } if (! Trainings::where('id', $input ['id'])->delete()) { throw new Exception("系统错误, 删除失败"); } parent::_save_log('trainings', 'del', $training['name']); return backJson(true, '删除成功'); } catch ( Exception $e ) { return backJson(false, $e->getMessage()); } } /* * 页面路径 */ private function breadcrumb() { return [ [ 'url' => URL::route('trainings.index'), 'title'=> '课程列表' ] ]; } }<file_sep><?php namespace App\Http\Controllers; class HomeController extends Controller { function __construct() { parent::__construct(); } public function index() { $data['category'] = 'home'; $data['subCategory'] = 'home'; return view('home', $data); } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Log; use App\Http\Model\Module; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Http\Request; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; class WebController extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Article; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\URL; class ArticleController extends Controller { public function index(Request $request) { $data ['category'] = 'article'; $data ['subCategory'] = 'articlelist'; $data ['breadcrumb'] = $this->breadcrumb(); return view('article.index', $data); } public function getArticles(Request $request) { $page = isset($request->rows) ? $request->rows : env('PAGNATION'); $list = Article::paginate($page); $roles = [ 'records' => $list->total(), 'total' => $list->lastPage(), 'rows' => $list->items() ]; return json_encode($roles); } public function getContent(Request $request) { try { $article = Article::findOrFail($request->id); return backJson(true, $article->content); } catch (Exception $e) { return backJson(false, '获取新闻内容失败:'.$e->getMessage()); } } public function add(Request $request) { try { $article = null; $message = ''; $operate = 'insert'; if (isset($request->id) && !empty($request->id)) { $message = '修改新闻'; $operate = 'update'; $article = Article::findOrFail($request->id); } else { $message = '新增新闻'; $article = new Article; $article->user_id = Auth::user()->id; } $article->title = $request->title; $article->content = $request->content; $article->author = $request->author; $article->save(); //parent::_save_log('article', $operate, $article->title); return backJson(true, $message.'成功!'); } catch (Exception $e) { return backJson(false, $message.'失败:'.$e->getMessage()); } } public function delete(Request $request) { try { if (!isset($request->id) || empty($request->id)) { throw new \Exception("请选择要删除的新闻"); } $article = Article::findOrFail($request->id); $article->delete(); //parent::_save_log('article', 'delete', $article->title); return backJson(true, '新闻删除成功'); } catch ( \Exception $e ) { return backJson(false, $e->getMessage()); } } /** * 页面面包屑 * * @return array */ private function breadcrumb() { return [ [ 'url' => URL::route('article.index'), 'title' => '新闻列表' ] ]; } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Module; class Category extends Controller { //基础节点ID号 public $intCurrentId; //设置制表符样式 private $arrTabsStyle = array( 'indent' => ' ', 'process' => '├ ', 'end'=>'└ ' ); //验证传入ID【大于0的数字】 private function checkFun($intId) { //$intId优先验证 if(isset($intId)) { $this->intCurrentId = $intId; return true; } //如果$this->intCurrentId 已设置,验证 else { if(isset($this->intCurrentId)) { return true; } else { return false; } } } //根据ID号获取当前节点左右值 private function setCurrentData($intId) { if(false == $this->checkFun($intId)) { return false; } $currentData = Module::where('id', $this->intCurrentId)->first(); dd($currentData); return $currentData; } /* *作用: 设置输出列表数据的制表符样式 *参数: $key:arrTabsStyle的KEY $value:arrTabsStyle的值 */ public function setTabStyle($key, $value = '') { if(isset($this->arrTabsStyle[$key])) { $this->arrTabsStyle[$key] = $value; } } /* *作用: 根据ID号获取当前节点数据 *参数: $intId:可设置的,需读取节点ID号 */ public function getCurrentData($intId) { if(false == $this->checkFun($intId)) { return false; } $map['id'] = $this->intCurrentId; return $this->objCategory->field(array('id','title'))->where($map)->find(); } /* *作用: 获取当前节点的父节点数据 *参数: $intId:需要读取节点的ID */ public function getParentCategoryData($intId) { $arrRoot = $this->setCurrentData($intId); if($arrRoot) { $map['lft'] = array('LT', $arrRoot['lft']); $map['rgt'] = array('GT', $arrRoot['rgt']); return $this->objCategory->where($map)->find(); } else { return false; } } /* *作用: 获取ID下节点列表 *参数: $intId:需要读取节点的父ID $intLevel:目录等级默认到100级 */ public function getCategoryList($intId = 1, $intLevel = 100) { //获取选定节点左右值,得出取值区间 $arrRoot = $this->setCurrentData($intId); if($arrRoot) { //读取数据库符合条件的数据 $map['lft'] = array('BETWEEN', array($arrRoot['lft'], $arrRoot['rgt'])); $arrChildList = $this->objCategory->where($map)->order('lft')->select(); //return $arrChildList; //对取出数据进行格式化 $arrRight = array(); foreach($arrChildList as $v) { if(count($arrRight)) { while ($arrRight[count($arrRight) - 1] < $v['rgt']) { array_pop($arrRight); } } //设置读取目录等级 if($intLevel > count($arrRight)) { $title = $v['title']; //设置输出时的样式 if(count($arrRight)) { $title = $this->arrTabsStyle['process'].$title; } $title = str_repeat($this->arrTabsStyle['indent'], count($arrRight)).$title; $returnCategoryList[] = array('id'=>$v['id'],'title'=>$title,'lft'=>$v['lft'],'rgt'=>$v['rgt']); $arrRight[] = $v['rgt']; } } return $returnCategoryList; } return false; } /* *作用: 获取节点的子节点数 *参数: $intId:需要读取节点的父ID */ public function getCategoryCount($intId) { $arrRoot = $this->setCurrentData($intId); return ($arrRoot['rgt'] - $arrRoot['lft'] - 1) / 2; } /* *作用: 添加节点 *参数: $bolType:true添加到节点前面,false添加到节点尾部 $intId:添加到的父节点 */ public function insertCategory($bolType = false, $intPid) { $arrRoot = $this->setCurrentData($intPid); dd($arrRoot); if($arrRoot) { if($bolType) //true添加到节点前面 { $this->objCategory->where('rgt>'.$arrRoot['lft'])->setInc('rgt',2); $this->objCategory->where('lft>'.$arrRoot['lft'])->setInc('lft',2); //设置当前节点的左右值 $data['lft'] = $arrRoot['lft'] + 1; $data['rgt'] = $arrRoot['lft'] + 2; } else //false添加到节点尾部 { $this->objCategory->where('rgt>='.$arrRoot['rgt'])->setInc('rgt',2); $this->objCategory->where('lft>'.$arrRoot['rgt'])->setInc('lft',2); $data['lft'] = $arrRoot['rgt']; $data['rgt'] = $arrRoot['rgt'] + 1; } return $this->objCategory->add($data); } else { return false; } } /* *作用: 删除节点 *参数: $intId:被删除的节点ID */ public function deleteCategory($intId) { $arrRoot = $this->setCurrentData($intId); if($arrRoot) { $ints = $arrRoot['rgt'] - $arrRoot['lft'] + 1; $map['lft'] = array('BETWEEN', array($arrRoot['lft'], $arrRoot['rgt'])); $this->objCategory->where($map)->delete(); $this->objCategory->where('lft>'.$arrRoot['rgt'])->setDec('lft',$ints); $this->objCategory->where('rgt>'.$arrRoot['rgt'])->setDec('rgt',$ints); return true; } else { return false; } } /* *作用: 更新节点 *参数: $intId:被删除的节点ID */ public function updateCategory() { //读取POST数据存入数组 $data = I('param.'); //父ID等于子ID,直接跳出 if($data['pid'] == $data['id']){return false;} //post.pid和当前父post.old相等说明未改变目录,不更新左右值 if($data['pid'] !== $data['oldpid']) { /**********************************【读取所需的相关值】********************************/ //获取新的父节点的数据 $arrParent = $this->setCurrentData($data['pid']); //取当前节点的数据 $arrCurrent = $this->setCurrentData($data['id']); /* 任务:删除节点 */ /**********************************【A-1:隔离数据】************************************/ //将需要调整位置的左右值+100000 $map['lft'] = array( array('EGT', $arrCurrent['lft']), array('ELT', $arrCurrent['rgt']) ); $this->objCategory->where($map)->setInc('lft',100000); //因为左值已更新,所以条件变化+100000 $map['lft'] = array( array('EGT', $arrCurrent['lft'] + 100000), array('ELT', $arrCurrent['rgt'] + 100000) ); $this->objCategory->where($map)->setInc('rgt',100000); unset($map); /**********************************【A-2:更新正常节点值】******************************/ //获取隔离节点后续更新的步长值 $intStep = $arrCurrent['rgt'] - $arrCurrent['lft'] + 1; //更新节点左右值 $map['lft'] = array( array('GT', $arrCurrent['rgt']), array('LT', 100000) ); $this->objCategory->where($map)->setDec('lft',$intStep); unset($map); $map['rgt'] = array( array('GT', $arrCurrent['rgt']), array('LT', 100000) ); $this->objCategory->where($map)->setDec('rgt',$intStep); unset($map); /* 完成:删除节点 */ /* 任务:更新节点 */ /**********************************【B-1:新父节目点提供下级节点的空间】****************/ $map['lft'] = array( array('GT', $arrParent['lft']), array('LT', 100000) ); $this->objCategory->where($map)->setInc('lft',$intStep); unset($map); $map['rgt'] = array( array('GT', $arrParent['lft']), array('LT', 100000) ); $this->objCategory->where($map)->setInc('rgt',$intStep); unset($map); /**********************************【B-2:将节点放入指定下级的空间】********************/ //获取隔离节点后续更新的步长值 $intStep = 100000 + ($arrCurrent['lft'] - ($arrParent['lft'] + 1)); //更新左右值大于父节点左值的节点的左右值 $map['lft'] = array( array('EGT', $arrCurrent['lft'] + 100000), array('ELT', $arrCurrent['rgt'] + 100000) ); $this->objCategory->where($map)->setDec('lft',$intStep); unset($map); $map['rgt'] = array( array('EGT', $arrCurrent['lft'] + 100000), array('ELT', $arrCurrent['rgt'] + 100000) ); $this->objCategory->where($map)->setDec('rgt',$intStep); } return $this->objCategory->where('id='.$data['id'])->setField('title', $data['title']); } } ?> <file_sep>/*==============================================================*/ /* DBMS name: MySQL 5.0 */ /* Created on: 2017-01-23 11:45:14 */ /*==============================================================*/ drop table if exists answer; drop table if exists article; drop table if exists exam; drop table if exists exam_eval; drop table if exists exam_question; drop table if exists exam_question_type; drop table if exists log_app; drop table if exists log_sys; drop table if exists message; drop table if exists module; drop table if exists notice; drop table if exists organization; drop table if exists paper; drop table if exists paper_question; drop table if exists password_resets; drop table if exists question; drop table if exists question_type; drop table if exists role; drop table if exists role_module; drop table if exists student; drop table if exists subject; drop table if exists user_role; drop table if exists users; /*==============================================================*/ /* Table: answer */ /*==============================================================*/ create table answer ( question_id int not null, id int not null auto_increment, name varchar(200) not null, answer_right int not null, primary key (id) ); /*==============================================================*/ /* Table: article */ /*==============================================================*/ create table article ( id int not null auto_increment, dt datetime not null, author varchar(20) not null, title varchar(50), content varchar(1000) not null, primary key (id) ); /*==============================================================*/ /* Table: exam */ /*==============================================================*/ create table exam ( id int not null auto_increment, subject_id int not null, name varchar(100) not null, duration int not null, price double, strategy int not null, score double not null, des varchar(500), sid int not null, state int not null, primary key (id) ); /*==============================================================*/ /* Table: exam_eval */ /*==============================================================*/ create table exam_eval ( exam_id int not null, id int not null auto_increment, name varchar(20) not null, min_score double not null, max_score double not null, primary key (id) ); /*==============================================================*/ /* Table: exam_question */ /*==============================================================*/ create table exam_question ( exam_id int not null, question_id int not null, sid int not null, primary key (exam_id, question_id) ); /*==============================================================*/ /* Table: exam_question_type */ /*==============================================================*/ create table exam_question_type ( exam_id int not null, question_type int not null, score double not null, amount int not null, primary key (exam_id, question_type) ); /*==============================================================*/ /* Table: log_app */ /*==============================================================*/ create table log_app ( id int not null auto_increment, user_id int not null, module_id int not null, dt datetime not null, des varchar(200) not null, primary key (id) ); /*==============================================================*/ /* Table: log_sys */ /*==============================================================*/ create table log_sys ( id int not null auto_increment, dt datetime not null, module_id int not null, des varchar(200) not null, primary key (id) ); /*==============================================================*/ /* Table: message */ /*==============================================================*/ create table message ( id int not null auto_increment, title varchar(50) not null, ask_dt datetime not null, asker varchar(20) not null, ask_content varchar(200) not null, answer_dt datetime not null, answer varchar(20) not null, answer_content varchar(200) not null, primary key (id) ); /*==============================================================*/ /* Table: module */ /*==============================================================*/ create table module ( id int not null auto_increment, name varchar(50) not null, icon varchar(20) not null, url varchar(100) not null, type int not null, state int not null, sid int not null, lft int not null, rgt int not null, primary key (id) ); /*==============================================================*/ /* Table: notice */ /*==============================================================*/ create table notice ( id int not null auto_increment, type int not null, title varchar(100) not null, content varchar(500) not null, sid int not null, state int not null, primary key (id) ); /*==============================================================*/ /* Table: organization */ /*==============================================================*/ create table organization ( id int not null auto_increment, name varchar(20) not null, tel varchar(20), des varchar(100), sid int not null, lft int not null, rgt int not null, primary key (id) ); /*==============================================================*/ /* Table: paper */ /*==============================================================*/ create table paper ( exam_id int not null, id int not null auto_increment, student_id int not null, dt datetime not null, duration int not null, score double not null, primary key (id) ); /*==============================================================*/ /* Table: paper_question */ /*==============================================================*/ create table paper_question ( paper_id int not null, question_id int not null, answer_id int not null, score double not null, sid int not null, primary key (paper_id, question_id) ); /*==============================================================*/ /* Table: password_resets */ /*==============================================================*/ create table password_resets ( email varchar(255) not null, token varchar(255) not null, created_at timestamp, primary key (email, token) ); /*==============================================================*/ /* Table: question */ /*==============================================================*/ create table question ( id int not null auto_increment, question_type_id int not null, name varchar(500) not null, des varchar(1000), state int not null, sid int not null, primary key (id) ); /*==============================================================*/ /* Table: question_type */ /*==============================================================*/ create table question_type ( id int not null auto_increment, name varchar(50) not null, des varchar(50), primary key (id) ); /*==============================================================*/ /* Table: role */ /*==============================================================*/ create table role ( id int not null auto_increment, name varchar(20) not null, des varchar(100), state int not null, sid int not null, primary key (id) ); /*==============================================================*/ /* Table: role_module */ /*==============================================================*/ create table role_module ( role_id int not null, module_id int not null, primary key (role_id, module_id) ); /*==============================================================*/ /* Table: student */ /*==============================================================*/ create table student ( id int not null auto_increment, name int not null, weixin varchar(50) not null, idnumber varchar(20), cellphone varchar(11), primary key (id) ); /*==============================================================*/ /* Table: subject */ /*==============================================================*/ create table subject ( id int not null auto_increment, name varchar(100) not null, des varchar(500), state int not null, sid int not null, primary key (id) ); /*==============================================================*/ /* Table: user_role */ /*==============================================================*/ create table user_role ( user_id int not null, role_id int not null, primary key (user_id, role_id) ); /*==============================================================*/ /* Table: users */ /*==============================================================*/ create table users ( id int not null auto_increment, name varchar(255) not null, password varchar(255) not null, email varchar(255) not null, remember_token varchar(100), weixin varchar(255), created_at datetime, updated_at datetime, primary key (id) ); <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Answer; use App\Http\Model\ExamQuestion; use App\Http\Model\Member; use App\Http\Model\Question; use App\Http\Model\QuestionType; use App\Http\Model\Subject; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\URL; use App\Http\Model\PaperQuestion; class QuestionController extends Controller { public function index() { $data['category'] = 'questions'; $data['subCategory'] = 'question'; $data['breadcrumb'] = $this->breadcrumb(); $data['question_type'] = QuestionType::get(); return view('question.index', $data); } //添加题目页面 function add(Request $request){ $data['questionData'] = []; $input = $request->all(); if( isset($input['id']) && !empty( $input['id']) ){ $questionData['question'] = Question::where('id', $input['id'])->first(); $questionData['answer'] = $questionData['question']->hasManyToAnswer()->get(); $data['questionData'] = $questionData; $subject_id = $questionData['question']->subject_id; }else{ $subject_id = $input['subject_id']; } $data['subject_id'] = $subject_id; $data['question_type'] = $input['type']; return view('question.add', $data); } // 获取科目数 function getSubject(){ $subjectData = Subject::where('state', '1')->orderBy('sid', 'desc')->get(); $sub[] = [ 'id' => 0, 'text' => '全部科目', 'type' => 'folder', ]; foreach ($subjectData as $subject){ $sub[] = [ 'id' => $subject->id, 'text' => $subject->name, 'type' => 'folder', ]; } return backJson(true, $sub); } // 获取题目 function get(Request $request){ $input = $request->all(); $page = isset( $input['rows'] ) ? $input['rows'] : env('PAGNATION'); if( isset($input['subject_id']) && !empty($input['subject_id']) ){ $questionList = Question::where('state', '<>', 0)->where('subject_id', $input['subject_id'])->paginate($page); }else{ $questionList = Question::where('state', '<>', 0)->paginate($page); } foreach ( $questionList as $k=>$question){ $questionList[$k]->type = $question->hasOneToType()->first()->name; $questionList[$k]->subject = $question->hasOneToSubject()->first()->name; } $question = [ 'records' => $questionList->total(), 'total'=> $questionList->lastPage(), 'rows' => $questionList->items() ]; return json_encode($question); } // 题目保存方法 function doAdd(Request $request){ try{ DB::beginTransaction(); $input = $request->all(); $id = $input['question']['id']; $type = $input['question_type']; $title = $input['question']['title']; // $answer_right = $input['question']['options']['answer']; $answers = $input['question']['options']; $subject_id = $input['question']['subject_id']; $question = [ 'question_type_id' => $type, 'name' => $title, 'subject_id' => $subject_id, 'des' => '', 'state' => 1, 'sid' => 1, 'updated_at' => date('Y-m-d H:i:s'), ]; if( isset($id) && !empty($id) ) { // 修改题目 if (!$quesionDb = Question::where('id', $id)->update($question)) { throw new \Exception("系统错误, 题目修改失败"); } $logType = 'edit'; $quesion_id = $id; }else{ // 创建题目 if (!$quesionDb = Question::create($question)) { throw new \Exception("系统错误, 题目创建失败"); } $logType = 'add'; $quesion_id = $quesionDb->id; } // 答案 if( isset($id) && !empty($id) ) { // 修改答案 if( ! Answer::where('question_id', $id)->delete() ){ throw new \Exception("系统错误, 原答案删除失败"); } $_question_succ = "题目修改成功"; }else{ $_question_succ = "题目创建成功"; } $answerArr = []; foreach ( $answers['val'] as $key=>$ans) { $answerArr[] = [ 'question_id' => $quesion_id, 'name' => $ans, 'answer_right' => isset($answers['answer'][$key]) && $answers['answer'][$key] == 'on' ? 1 : 0 ]; } if( ! Answer::insert($answerArr) ){ throw new \Exception("系统错误, 题目选项创建错误"); } parent::_save_log('question', $logType, $title); DB::commit(); return backJson( true , $_question_succ); } catch (\Exception $e){ DB::rollBack(); return backJson(false, $e->getMessage()); } } // 删除题目 function delete(Request $request){ try{ $input = $request->all(); if( !isset($input['id']) || empty($input['id']) ){ throw new \Exception("请选择要删除的题目"); } $questionRel = ExamQuestion::where('question_id', $input['id'])->count(); if( $questionRel > 0 ){ throw new \Exception("已有考试关联该题目, 暂时不能删除"); } $questionRel = PaperQuestion::where('question_id', $input['id'])->count(); if( $questionRel > 0 ){ throw new \Exception("已有考卷关联该题目, 暂时不能删除"); } $question = Question::where('id', $input['id'])->first(); if ( !Question::where( 'id', $input['id'] )->delete() ){ throw new \Exception("系统错误, 题目删除失败"); } parent::_save_log('question', 'del', $question['name']); return backJson(true, '删除成功'); } catch (\Exception $e){ return backJson(false, $e->getMessage()); } } /** * 页面面包屑 * @return array */ private function breadcrumb(){ return [ [ 'url' => URL::route('question.index'), 'title'=> '题目列表' ] ]; } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\StudentsPrint; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\URL; use Exception; use Maatwebsite\Excel\Facades\Excel; class StudentsPrintController extends Controller { public function index() { // TODO: method stub return; } }<file_sep><button class="btn btn-sm btn-success btn_set_trainings" type="button"><i class="fa fa-cube"></i> 设置课程</button> <div class="modal fade" role="dialog" id="classes_set_trainings"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title">设置课程</h4> </div> <div class="modal-body"> <form class="form-horizontal classes_set_trainings_form clearfix" action="<?php echo e(URL::route('classes.set.trainings')); ?>" method="POST"> <select class="left col-sm-5" multiple="multiple" name="exam_topic"> </select> <div class="col-sm-2 text-center"> <button class="btn btn-primary add_to" type="button">>></button><br><br> <button class="btn btn-primary min_to" type="button"><<</button> </div> <ul class="right list-unstyled spaced col-sm-5 pull-right"> </ul> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> <button class="btn btn-primary ok_btn">保存课程</button> </div> </div> </div> </div> <script> var id; $(document).off('click', '.btn_set_trainings').on('click', '.btn_set_trainings', function(){ var row_id=$("#jqgrid-table-1").jqGrid('getGridParam','selrow'); if( row_id == undefined ){ show_msg(false, '请先选择班级'); return false; } var rowData=$("#jqgrid-table-1").getRowData(row_id); $('#classes_set_trainings').modal({ keyboard: true, }); id = rowData.id; $.ajax({ type: "POST", url: "<?php echo e(URL::route('classes.get.trainings')); ?>", data: {id: id, _token:"<?php echo e(csrf_token()); ?>"}, dataType: "json", success: function(data){ if( data.code ) { $('.classes_set_trainings_form .left').html(data.msg.tranTxt); $('.classes_set_trainings_form .right').html(data.msg.classtran); } } }); }) // 添加 $(document).off('click', '.add_to').on('click', '.add_to', function(){ var exam_topic = $("select[name='exam_topic']").val(); var _li = ''; $.each(exam_topic, function(i, val) { // 遍历name=test的多选框 var option = $("select[name='exam_topic']").find('option[value='+val+']'); option.addClass('hide') var _txt = option.text(); _li += "<li data-value="+val+"><span class='title'>"+_txt+"</span><span class='fa fa-trash-o delete'></span><span class='fa fa-arrow-circle-o-down down'></span><span class='fa fa-arrow-circle-o-up up'></span></li>"; }); $('.classes_set_trainings_form .right').append(_li); }) $(document).off('click', '.classes_set_trainings_form .right span.delete').on('click', '.classes_set_trainings_form .right span.delete', function() { var _val = $(this).parent().data('value'); $(this).parent().remove(); $("select[name='exam_topic']").find("option[value="+_val+"]").removeClass('hide') }) // 上移 $(document).off('click', '.classes_set_trainings_form .right span.up').on('click', '.classes_set_trainings_form .right span.up', function(){ var onthis=$(this).parent('li'); var getUp=onthis.prev(); $(onthis).after(getUp); }) // 下移 $(document).off('click', '.classes_set_trainings_form .right span.down').on('click', '.classes_set_trainings_form .right span.down', function(){ var onthis=$(this).parents('li'); var getdown=onthis.next(); $(getdown).after(onthis); }) $(document).off('click', '#classes_set_trainings .ok_btn').on('click', '#classes_set_trainings .ok_btn', function() { var _val = {}; $('.classes_set_trainings_form li').each(function(i){ _val[i] = $(this).data('value') }) // if( _val[0] == undefined){ // show_msg(false, '请选择课程后保存'); // return ; // } $.ajax({ type: "POST", url: "<?php echo e(URL::route('classes.set.trainings')); ?>", data: {id: id, trans:_val, _token:"<?php echo e(csrf_token()); ?>"}, dataType: "json", success: function(data){ show_msg(true, data.msg) if( data.code ){ window.location.reload(); } } }); }) </script><file_sep>/* Navicat MySQL Data Transfer Source Server : 本地 Source Server Version : 50626 Source Host : localhost:3306 Source Database : kaoshi Target Server Type : MYSQL Target Server Version : 50626 File Encoding : 65001 Date: 2017-03-26 16:59:30 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for article_category -- ---------------------------- DROP TABLE IF EXISTS `article_category`; CREATE TABLE `article_category` ( `id` int(11) NOT NULL AUTO_INCREMENT, `pid` int(11) NOT NULL DEFAULT '0', `title` varchar(500) DEFAULT NULL, `sid` int(3) DEFAULT NULL, `status` tinyint(1) DEFAULT '1', `created_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of article_category -- ---------------------------- INSERT INTO `article_category` VALUES ('3', '0', '11', '1', '1', '2017-03-26 15:10:00', '2017-03-26 15:10:00'); INSERT INTO `article_category` VALUES ('4', '3', '11-111', '1', '1', '2017-03-26 16:19:34', '2017-03-26 16:19:34'); INSERT INTO `article_category` VALUES ('6', '0', '33', '3', '0', '2017-03-26 16:10:44', '2017-03-26 16:10:44'); SET FOREIGN_KEY_CHECKS=1; <file_sep><div id="signup-box" class="signup-box widget-box no-border"> <div class="widget-body"> <div class="widget-main"> <h4 class="header green lighter bigger"> <i class="ace-icon fa fa-users blue"></i> 新用户注册 </h4> <div class="space-6"></div> <p> 请输入以下信息完成注册 </p> <form class="form-horizontal" role="form" method="POST" action="<?php echo e(url('/register')); ?>"> <?php echo e(csrf_field()); ?> <fieldset> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input id="email" type="email" placeholder="请输入用户姓名" class="form-control" name="email" value="<?php echo e(old('email')); ?>" required> <i class="ace-icon fa fa-envelope"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input id="name" type="text" placeholder="请输入用户邮箱" class="form-control" name="name" value="<?php echo e(old('name')); ?>" required autofocus> <i class="ace-icon fa fa-user"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input id="password" type="<PASSWORD>" placeholder="<PASSWORD>" class="form-control" name="password" required> <i class="ace-icon fa fa-lock"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input id="password-confirm" placeholder="请输入确认密码" type="<PASSWORD>" class="form-control" name="password_confirmation" required> <i class="ace-icon fa fa-retweet"></i> </span> </label> <div class="space-24"></div> <div class="clearfix"> <button type="reset" class="width-30 pull-left btn btn-sm"> <i class="ace-icon fa fa-refresh"></i> <span class="bigger-110">重写</span> </button> <button type="submit" class="width-65 pull-right btn btn-sm btn-success"> <span class="bigger-110">注册系统</span> <i class="ace-icon fa fa-arrow-right icon-on-right"></i> </button> </div> </fieldset> </form> </div> <div class="toolbar center"> <a href="#" data-target="#login-box" class="back-to-login-link"> <i class="ace-icon fa fa-arrow-left"></i> 返回到登陆页面 </a> </div> </div><!-- /.widget-body --> </div><!-- /.signup-box --><file_sep><?php $__env->startSection('content'); ?> <?php $target = 'add_form'; ?> <div class="row"> <div class="col-xs-12"> <div class="jqGrid_tools"> <?php echo $__env->make('common.buttons._add', ['add_target'=>$target, 'index'=>1], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php echo $__env->make('common.buttons._edit', ['modal_target'=>$target, 'parms'=>'$("#name").val(rowData.name);$("#begin_time").val(rowData.begin_time);$("#end_time").val(rowData.end_time);$("#repeat_time").val(rowData.repeat_time);$("#id").val(rowData.id);$("#sid").val(rowData.sid);$("#state").val(rowData.state);'], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php if( Auth::user()->id == 1 ): ?> <?php echo $__env->make('common.buttons._del', ['url'=>URL::route('classes.delete')], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php endif; ?> <?php echo $__env->make('common.buttons._set_trainings', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> </div> <table id="jqgrid-table-1"></table> <div id="jqgrid-pager-1"></div> </div> </div> <div class="modal fade" role="dialog" id="<?php echo e($target); ?>"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title">添加</h4> </div> <form class="form-horizontal <?php echo e($target); ?>" role="form" action="<?php echo e(URL::route('classes.edit')); ?>" method="POST"> <?php echo e(csrf_field()); ?> <input type="hidden" value="0" name="id" id="id"/> <div class="modal-body"> <!-- #section:elements.form --> <div class="form-group"> <label class="col-sm-3 control-label" for="name">班级名称 <span class="text-danger">*</span></label> <div class="col-sm-6 input-group input-group-sm"> <input datatype="*" nullmsg="请输入班级名称" type="text" id="name" placeholder="请输入班级名称" name="name" class="form-control"/> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label" for="begin_time">培训开始时间 <span class="text-danger">*</span></label> <div class="col-sm-6 input-group input-group-sm"> <input datatype="date" nullmsg="请输入培训开始时间" type="text" id="begin_time" placeholder="请输入培训开始时间" name="begin_time" class="form-control" /> <span class="input-group-addon"><i class="ace-icon fa fa-calendar"></i></span> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">培训结束时间 <span class="text-danger">*</span></label> <div class="col-sm-6 input-group input-group-sm"> <input datatype="date" nullmsg="输输入培训结束时间" type="text" id="end_time" placeholder="请输入培训结束时间" name="end_time" class="form-control" /> <span class="input-group-addon"><i class="ace-icon fa fa-calendar"></i></span> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">复训时间 <span class="text-danger">*</span></label> <div class="col-sm-6 input-group input-group-sm"> <input datatype="date" nullmsg="输输入复训时间" type="text" id="repeat_time" placeholder="请输入复训时间" name="repeat_time" class="form-control" /> <span class="input-group-addon"><i class="ace-icon fa fa-calendar"></i></span> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label"> 班级状态 <span class="text-danger">*</span></label> <div class="col-sm-6 input-group input-group-sm"> <select name="state" id="state"> <option value="1">正常</option> <option value="0">禁用</option> </select> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label "> 排序 <span class="text-danger">*</span></label> <div class="col-sm-6 input-group input-group-sm"> <input type="number" id="sid" datatype="n" errormsg="排序格式错误" maxlength="3" placeholder="排序" name="sid" class="form-control" /> </div> </div> </div> <div class="modal-footer"> <button class="btn btn-primary ok_btn">保存</button> <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> </div> </form> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div> <?php $__env->stopSection(); ?> <?php $__env->startSection('footer_script'); ?> <script> $(function(){ $("#repeat_time, #end_time, #begin_time").datepicker({ dateFormat:"yy-mm-dd" }); }) </script> <?php echo $__env->make('common.jqgrid', [ 'index' => 1, 'url' => URL::route('classes.get'), 'rowListShow'=> "['20', '40', '60']", 'colnames' => "['ID', '班级名称','培训开始时间', '培训结束时间', '复训时间','排序', '状态', '状态']", 'colModel' => json_encode([ ['name' => 'id', 'hidden'=>true], ['name' => 'name'], ['name' => 'begin_time', 'formatter'=>'date', 'formatoptions'=>'{newformat:"Y-m-d"}'], ['name' => 'end_time','formatter'=>'date', 'formatoptions'=>'{newformat:"Y-m-d"}'], ['name' => 'repeat_time','formatter'=>'date', 'formatoptions'=>'{newformat:"Y-m-d"}'], ['name' => 'sid', 'hidden'=>true], ['name' => 'state', 'hidden'=>true], ['name' => 'state_text'], ]) ], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php $__env->stopSection(); ?> <?php echo $__env->make('addi.app', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?><file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Certificate; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\URL; use Exception; use Maatwebsite\Excel\Facades\Excel; class CertificateController extends Controller { /* * 首页 */ public function index() { $data ['category'] = 'examines'; $data ['subCategory'] = 'certificate'; $data ['breadcrumb'] = $this->breadcrumb(); return view('certificate.index', $data); } function import(Request $req) { DB::beginTransaction(); try{ $import = $req->file('Filedata'); $count = 0; // 文件是否上传成功 if ( $req->hasFile('Filedata') && $import->isValid()) { // 获取文件相关信息 $originalName = $import->getClientOriginalName(); // 文件原名 $ext = $import->getClientOriginalExtension(); // 扩展名 $realPath = $import->getRealPath(); //临时文件的绝对路径 $type = $import->getClientMimeType(); // image/jpeg // 上传文件 $filename = 'cer_'.date('Y-m-d-H-i-s') . '.' . $ext; // 使用我们新建的uploads本地存储空间(目录) $bool = Storage::disk('public')->put($filename, file_get_contents($realPath)); if( $bool ){ $filePath = public_path().'/imports/'.$filename; Excel::load($filePath, function($reader) use(&$count) { $reader = $reader->getSheet(0); $res = $reader->toArray(); $col_name = 0; $col_gender = 0; $col_cerno = 0; $col_education = 0; $col_idno = 0; $col_mantype = 0; $col_comtype = 0; $col_company = 0; $col_vertime = 0; $title = $res[0]; if (count($title) == 48) { // 表二:有资质证号的 $col_name = 0; if ($title[$col_name] != '姓名') { throw new Exception('未找到姓名列,上传的文件格式无效!'); } $col_gender = 1; if ($title[$col_gender] != '性别') { throw new Exception('未找到性别列,上传的文件格式无效!'); } $col_education = 2; if ($title[$col_education] != '文化程度') { throw new Exception('未找到文化程度列,上传的文件格式无效!'); } $col_idno = 4; if ($title[$col_idno] != '身份证号') { throw new Exception('未找到身份证号列,上传的文件格式无效!'); } $col_cerno = 20; if ($title[$col_cerno] != '安全资证号') { throw new Exception('未找到安全资证号列,上传的文件格式无效!'); } $col_mantype = 40; if ($title[$col_mantype] != '证书类型') { throw new Exception('未找到证书类型列,上传的文件格式无效!'); } $col_comtype = 7; if ($title[$col_comtype] != '单位类型') { throw new Exception('未找到单位类型列,上传的文件格式无效!'); } $col_company = 5; if ($title[$col_company] != '单位') { throw new Exception('未找到单位列,上传的文件格式无效!'); } $col_vertime = 47; if ($title[$col_vertime] != '审验时间') { throw new Exception('未找到审验时间列,上传的文件格式无效!'); } } else if (count($title) == 33) { // 表一:无资质证号的 $col_name = 1; if ($title[$col_name] != '姓名') { throw new Exception('未找到姓名列,上传的文件格式无效!'); } $col_gender = 2; if ($title[$col_gender] != '性别') { throw new Exception('未找到性别列,上传的文件格式无效!'); } $col_education = 9; if ($title[$col_education] != '学历') { throw new Exception('未找到学历列,上传的文件格式无效!'); } $col_idno = 6; if ($title[$col_idno] != '身份证') { throw new Exception('未找到身份证列,上传的文件格式无效!'); } $col_cerno = $col_idno; // 无资质证号,使用身份证号代替。 $col_mantype = 8; if ($title[$col_mantype] != '人员类别') { throw new Exception('未找到人员类别列,上传的文件格式无效!'); } $col_comtype = 18; if ($title[$col_comtype] != '单位类别') { throw new Exception('未找到单位类别列,上传的文件格式无效!'); } $col_company = 19; if ($title[$col_company] != '工作单位') { throw new Exception('未找到工作单位列,上传的文件格式无效!'); } $col_vertime = 32; if ($title[$col_vertime] != '审验时间') { throw new Exception('未找到审验时间列,上传的文件格式无效!'); } } else { throw new Exception('导入的文件格式不正确,请重试!'); } // 开始导入 //if (count($res) != count($res, 1)) { // 上面的判断是为了防止只有标题,没有数据 for ($i = 1; $i <count($res); $i ++) { $row = $res[$i]; // 判断是不是空行 $empty = true; for ($j = 0; $j < count($row); $j ++) { if (!empty($row[$j])) { $empty = false; } } if ($empty) continue; $data = [ 'name' => $row[$col_name], 'gender' => ($row[$col_gender] == '男' ? 1: 0), 'education'=> $row[$col_education], 'id_no' => $row[$col_idno], 'cer_no' => $row[$col_cerno], 'man_type' => $row[$col_mantype], 'com_type' => $row[$col_comtype], 'company' => $row[$col_company], 'ver_time' => date('Y-m-d', strtotime($row[$col_vertime].'-01')), 'import_time' => date('Y-m-d H:i:s', time()), ]; $line = $i + 1; // 判断字段是否符合要求 if (empty($data['name'])) { throw new Exception('第'.$line.'行 姓名 为空,不能导入!'); } if (empty($data['id_no'])) { throw new Exception('第'.$line.'行 身份证号 为空,不能导入!'); } if (empty($data['cer_no'])) { throw new Exception('第'.$line.'行 资质证号 为空,不能导入!'); } if (empty($data['man_type'])) { throw new Exception('第'.$line.'行 人员类型 为空,不能导入!'); } if (empty($data['com_type'])) { throw new Exception('第'.$line.'行 企业类型 为空,不能导入!'); } if (empty($data['company'])) { throw new Exception('第'.$line.'行 企业名称 为空,不能导入!'); } if (empty($data['ver_time'])) { throw new Exception('第'.$line.'行 认证日期 为空,不能导入!'); } // 判断是不是已经存在 if (Certificate::where([ ['name', '=', $data['name']], ['id_no', '=', $data['id_no']], ['company', '=', $data['company']], ['man_type', '=', $data['man_type']], ['cer_no', '=', $data['cer_no']], ['ver_time', '=', $data['ver_time']], ['com_type', '=', $data['com_type']] ])->count() > 0) { throw new Exception("证书信息已存在(行号:".$line.", 姓名:".$data['name']."),不允许重复导入!"); } if( !Certificate::insert($data)){ throw new Exception("证书信息创建失败"); } $count ++; } //} }); } else { throw new Exception("上传失败"); } } else { throw new Exception("上传失败"); } DB::commit(); parent::_save_log('cert', 'import', ''); echo backJson(true, '导入成功,共创建'.$count.'条证书信息'); } catch ( Exception $e ) { DB::rollback(); return backJson(false, $e->getMessage()); } } /* * 获取 */ function get(Request $request) { $input = $request->all(); $page = isset($input ['rows']) ? $input['rows'] : env('PAGNATION'); $list = Certificate::whereNotNull('id'); if(isset($input['student_name']) && !empty($input['student_name'])) { $list = $list->where('name', 'like' ,'%'.$input['student_name'].'%'); } if (isset($input['import_time']) && !empty($input['import_time'])) { $time = explode(' - ', $input['import_time']); $list = $list->whereBetween('import_time', [$time[0], $time[1]]); } $list = $list->paginate($page); $result = [ 'records' => $list->total(), 'total' => $list->lastPage(), 'rows' => $list->items() ]; return json_encode($result); } /* * 修改 */ function edit(Request $request) { try { $input = $request->all(); $data = [ 'name' => $input['name'], 'gender' => $input['gender'], 'education' => $input['education'], 'id_no' => $input['id_no'], 'cer_no' =>$input['cer_no'], 'man_type' => $input['man_type'], 'com_type' => $input['com_type'], 'company' => $input['company'], 'ver_time' => $input['ver_time'], ]; if (isset($input ['id']) && ! empty($input ['id'])) { Certificate::where('id', $input['id'])->update($data); $logType = 'edit'; $_success_txt = '证书信息修改成功'; } else { if (! Certificate::create($data)) { throw new Exception("系统错误,证书添加失败"); } $logType = 'add'; $_success_txt = '证书添加成功'; } parent::_save_log('cert', $logType, $input['name']); return backJson(true, $_success_txt); } catch ( Exception $e ) { return backJson(false, $e->getMessage()); } } /* * 删除证书 */ function delete(Request $request) { $input = $request->all(); if (!isset($input['id']) || empty($input['id'])) { throw new \Exception("请选择要删除的证书"); } try { $item = Certificate::where('id', $input['id'])->first(); // 删除考试 Certificate::where('id', $input['id'])->delete(); parent::_save_log('cert', 'del', $item['name']); return backJson(true, '证书删除成功'); } catch (\Exception $e) { return backJson(false, $e->getMessage()); } } /* * 页面路径 */ private function breadcrumb() { return [ [ 'url' => URL::route('certificate.index'), 'title'=> '证书列表' ] ]; } }<file_sep><?php $table_index = isset($index) ? $index : 1; ?> <button class="btn btn-sm btn-primary list_add" > <i class="ace-icon fa fa-plus align-top bigger-125"></i> 新增 </button> <script> $(function(){ $('form.<?php echo e($target); ?> .ok_btn').on('click', function(){ _validForm('form.<?php echo e($target); ?>', null, _completeModal); }) $(".list_add").click(function(){ $('#<?php echo e($target); ?>').modal(); $('#<?php echo e($target); ?>').find("input[name='id']").val(0) $('#<?php echo e($target); ?>').find('form')[0].reset(); if($(".wangEditor-txt").length > 0) { editor.clear() } }) }) function _completeModal(){ $('form.<?php echo e($target); ?> .modal-footer .btn:last').click(); reload(); } function reload() { var p = $("#jqgrid-table-<?php echo e($table_index); ?>").jqGrid('getGridParam','page'); $("#jqgrid-table-<?php echo e($table_index); ?>").jqGrid('setGridParam', { page: p, }).trigger("reloadGrid"); } </script><file_sep><?php $table_index = isset($index) ? $index : 1; ?> <button class="btn btn-danger btn-sm del_list_<?php echo e($table_index); ?>"> <i class="ace-icon fa fa-trash align-top bigger-125 icon-on-right"></i> 删除 </button> <script> $(".del_list_<?php echo e($table_index); ?>").on('click', function(){ var row_id=$("#jqgrid-table-<?php echo e($table_index); ?>").jqGrid('getGridParam','selrow'); if( row_id == undefined ){ show_msg(false, '请选择要删除的数据'); return false; } var rowData=$("#jqgrid-table-<?php echo e($table_index); ?>").getRowData(row_id); bootbox.confirm({ message: "确认要删除该条数据吗?", buttons: { confirm: { label: "确定删除", }, cancel: { label: "取消", } }, callback: function(result) { if (result) { $.ajax({ type: "post", url: "<?php echo e($url); ?>", data: {id: rowData.id, _token: "<?php echo e(csrf_token()); ?>"}, dataType: "json", success: function (data) { show_msg(data.code, data.msg); if (data.code) { $("#jqgrid-table-<?php echo e($table_index); ?>").trigger("reloadGrid"); } } }) } } }); }) </script><file_sep><?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class PaperQuestion extends Model { protected $table = 'paper_question'; public $timestamps = false; protected $fillable = [ 'paper_id', 'question_id', 'answer_id', 'score', 'sid' ]; } <file_sep><?php /** * Created by PhpStorm. * User: xiaoping * Date: 2017-05-21 * Time: 19:46 */ namespace App\Http\Controllers; use App\Http\Model\Candidate; use App\Http\Model\Exam; use App\Http\Model\ExamEval; use App\Http\Model\Examination; use App\Http\Model\Paper; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\URL; use Exception; use Maatwebsite\Excel\Facades\Excel; use PhpParser\Node\Stmt\Foreach_; class ScoreAvgController extends Controller { /* * 首页 */ public function index(Request $request) { $input = $request->all(); $data ['category'] = 'reports'; $data ['subCategory'] = 'scoreavg'; $data ['breadcrumb'] = $this->breadcrumb(); if( !isset($input['exam_id']) || empty($input['exam_id']) ) { $examInfo = Exam::orderBy('id', 'desc')->first(); $data['exam_id'] = $examInfo->id; }else{ $data['exam_id'] = $input['exam_id']; } $colModel1 = [ ['name'=>'exam_name' , 'label'=>'考卷名称'], ['name'=>'examine_name', 'label'=>'考试名称'], ['name'=>'totle_stu' , 'label'=>'总人数'], ['name'=>'miss_stu' , 'label'=>'缺考人数'], ['name'=>'take_stu' , 'label'=>'参考人数'], ]; $colModel2 = [ ['name'=>'pass_stu' , 'label'=>'合格人数'], ['name'=>'pass_prop' , 'label'=>'占比(%)'], ['name'=>'nopass_stu' , 'label'=>'不合格人数'], ['name'=>'nopass_prop', 'label'=>'占比(%)'], ['name'=>'pass_rate' , 'label'=>'通过率(%)'], ]; $examEval = ExamEval::where('exam_id', $data['exam_id'])->orderBy('id', 'asc')->get(); $colModel3 = []; foreach ($examEval as $k=>$eval){ $colModel3[$k]['name'] = 'eval_'.$eval->id; $colModel3[$k]['label'] = $eval->name; } $data['colModel'] = array_merge($colModel1, $colModel3, $colModel2); return view('report.scoreAvg', $data); } /* * 获取 * 考卷名称、考试名称、总人数,缺考人数,参考人数,优秀人数,占比,良好人数,占比,合格人数,占比,不合格人数,占比,通过率 * * */ function get(Request $req, $exam_id){ try{ $page = isset($req->rows) ? $req->rows : env('PAGNATION'); $examInfo = Exam::where('id', $exam_id)->first(); $input = $req->all(); $examinationInfo = Examination::where('exam_id', $exam_id); if( isset($input['beginTime']) && !empty($input['beginTime']) && isset($input['endTime']) && !empty($input['endTime']) ){ $examinationInfo = $examinationInfo->whereBetween('begin_time', [date('Y-m-d H:i:s', strtotime($input['beginTime'])), date('Y-m-d H:i:s', strtotime($input['endTime']))]); } $examinationInfo = $examinationInfo->paginate($page); foreach ($examinationInfo as $k=>$examination){ // 总人数 $total_arr = $examination->hasManyToStu()->get(); $total_stu = $total_arr->count(); $take_stu = $pass_stu = $nopass_stu = $miss_stu = 0; $paperArr = []; foreach ($total_arr as $getStu){ //参考人数 if( !empty($getStu->paper_id) ){ $take_stu ++; // 正式考试 }else{ if( !empty($getStu->paper_retry_id) ){ $take_stu ++; // 补考 }else{ $miss_stu ++; // 缺考 } } // 合格 if( !empty($getStu->pass_time) ){ $pass_stu ++; // 补考 }else{ if( !empty($getStu->paper_id) || !empty($getStu->paper_retry_id) ) { $nopass_stu++; // 没通过 } } } // paper 考试表 $papData = Paper::where('examination_id', $examination->id)->whereIn('type', [1, 4])->get(); foreach ($papData as $key=>$pap){ $paperArr['stu_'.$pap->student_id] = $pap->score; } // 评级 $examEval = $examination->hasManyToEval()->orderBy('id', 'asc')->get(); foreach ($examEval as $ka=>$eval){ $key = 'eval_'.$eval->id; $t = 0; foreach ( $paperArr as $userScore ){ if( $userScore > $eval->min_score && $userScore <= $eval->max_score ){ $t ++; } } $examinationInfo[$k]->$key = $t; } $examinationInfo[$k]->exam_name = $examInfo->name; $examinationInfo[$k]->examine_name = $examination->name; $examinationInfo[$k]->totle_stu = $total_stu; $examinationInfo[$k]->miss_stu = $miss_stu; $examinationInfo[$k]->take_stu = $take_stu; $examinationInfo[$k]->pass_stu = $pass_stu; $examinationInfo[$k]->nopass_stu = $nopass_stu; $examinationInfo[$k]->pass_prop = $total_stu > 0 ? sprintf("%.2f", $pass_stu/$total_stu) : sprintf("%.2f", 0); $examinationInfo[$k]->nopass_prop = $total_stu > 0 ? sprintf("%.2f", $nopass_stu/$total_stu) : sprintf("%.2f", 0); $examinationInfo[$k]->pass_rate = $take_stu > 0 ? sprintf("%.2f", $pass_stu/$take_stu) : sprintf("%.2f", 0); } $data = [ 'records' => $examinationInfo->total(), 'total' => $examinationInfo->lastPage(), 'rows' => $examinationInfo->items() ]; return json_encode($data); } catch (Exception $e) { return backJson(false, $e->getMessage()); } } // 获取考卷 function getExam(Request $request){ $exam_id = $request->get('exam_id'); $examInfo = Exam::orderBy('updated_at', 'desc')->get(); $children = []; foreach ($examInfo as $subject){ $children[] = [ 'id' => $subject->id, 'text' => $subject->name, 'type' => 'item', 'additionalParameters' => ['item-selected'=>$subject->id ==$exam_id ? true : false ], ]; } return backJson(true, $children); } /* * 页面路径 */ private function breadcrumb() { return [ [ 'url' => URL::route('score.index'), 'title'=> '成绩查询' ] ]; } }<file_sep><?php $__env->startSection('header_style'); ?> <script language="javascript" src="<?php echo e(URL::asset('js/LodopFuncs.js')); ?>"></script> <?php $__env->stopSection(); ?> <?php $__env->startSection('content'); ?> <?php $import_target = 'stu_import'; ?> <script src="<?php echo e(URL::asset('components/jqGrid/js/jquery.jqGrid.js')); ?>"></script> <script src="<?php echo e(URL::asset('components/jqGrid/js/i18n/grid.locale-cn.js')); ?>"></script> <link href="<?php echo e(URL::asset('assets/uploadfive/uploadifive.css')); ?>" rel="stylesheet" /> <script src="<?php echo e(URL::asset('assets/uploadfive/jquery.uploadifive.js')); ?>"></script> <div class="row"> <div class="col-xs-3 left_tree"> <div class="widget-box widget-color-blue2"> <div class="widget-header"> <h4 class="widget-title lighter smaller"> 班级列表 </h4> </div> <div class="widget-body"> <div class="widget-main padding-8"> <ul id="tree2"></ul> </div> </div> </div> </div> <div class="col-xs-9"> <div class="jqGrid_tools"> <?php echo $__env->make('common.buttons._import', ['import_target'=>$import_target], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php echo $__env->make('common.buttons._stu_print', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php if( Auth::user()->id == 1 ): ?> <?php echo $__env->make('common.buttons._dels', ['url'=>URL::route('students.delete')], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php endif; ?> <?php echo $__env->make('common.buttons._search', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> </div> <table id="jqgrid-table-1"></table> <div id="jqgrid-pager-1"></div> </div> </div> <div class="modal fade" role="dialog" id="prints"> <div class="modal-dialog modal-sm" style="width:500px"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title">准考证打印记录</h4> </div> <div> <table id="jqgrid-table-2"></table> </div> <div class="modal-footer"> <button type="button" class="btn btn-info" data-dismiss="modal">关闭</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div> <?php $__env->stopSection(); ?> <?php $__env->startSection('footer_script'); ?> <script language="javascript" type="text/javascript"> // 树 var remoteDateSource = function(options, callback) { var $data = null; if(!("name" in options) && !("type" in options)){ $.ajax({ url: "<?php echo e(URL::route('classes.get.years')); ?>", type: 'POST', data: {_token: "<?php echo e(csrf_token()); ?>"}, dataType: 'json', success : function(response) { if( response.code ) callback({ data: response.msg }) }, error: function(response) { //console.log(response); } }); return; } else if("type" in options && options.type == "folder") { if("additionalParameters" in options && "children" in options.additionalParameters) $data = options.additionalParameters.children;//点击父节点,加载子节点 else $data = {}//no data } if($data != null)//this setTimeout is only for mimicking some random delay setTimeout(function(){callback({ data: $data });} , parseInt(Math.random() * 500) + 200); }; $('#tree2').ace_tree({ dataSource: remoteDateSource, loadingHTML:'<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>', 'open-icon' : 'ace-icon fa fa-folder-open', 'close-icon' : 'ace-icon fa fa-folder', 'itemSelect' : true, 'folderSelect': true, 'selected-icon' : null, 'unselected-icon' : null, 'folder-open-icon' : 'ace-icon tree-plus', 'folder-close-icon' : 'ace-icon tree-minus' }) $(document).off('click', ".tree-branch .tree-branch-header, .tree-item ").on('click', ".tree-branch .tree-branch-header, .tree-item ", function(){ var treeData = $('#tree2').tree('selectedItems'); console.log(treeData) $("#jqgrid-table-1").jqGrid('setGridParam',{ url: "<?php echo e(URL::route('students.get')); ?>?search=" + treeData[0].id+"&level="+treeData[0].level, page: 1 }).trigger("reloadGrid"); }) // 刷新学生记录列表 function reload() { var p = $("#jqgrid-table-1").jqGrid('getGridParam','page'); $("#jqgrid-table-1").jqGrid('setGridParam', { page: p, }).trigger("reloadGrid"); } // 初始化打印记录列表 $("#jqgrid-table-2").jqGrid({ mtype: 'post', url: "<?php echo e(URL::route('students.get.print')); ?>", datatype: 'local', page: 1, autowidth: true, viewrecords : true, rownumbers: true, multiselect: false, rowNum: 1000, colNames: ['id', '打印人', '打印时间'], colModel:[ {name: 'id', hidden:true}, {name: 'print_user', width: '200'}, {name: 'print_time', width: '262'} ], }); // 查看打印记录 function ViewStudentPrint(id) { $("#jqgrid-table-2").jqGrid('setGridParam', { datatype: 'json', postData: {id: id, _token: "<?php echo e(csrf_token()); ?>"}, loadComplete: function() { $('#prints').modal({ keyboard: true }); }, }).trigger("reloadGrid"); } </script> <?php echo $__env->make('common.jqgrid', [ 'index' => 1, 'multiselect'=> true, 'rowListShow'=> "['80', '40', '20']", 'rowNum' => 80, 'url' => URL::route('students.get'), 'colnames' => "['ID', '编号', '姓名','电话', '地址','考试时间', '打印次数']", 'colModel' => json_encode([ ['name' => 'id', 'hidden'=>true], ['name' => 'code', 'width'=>'100'], ['name' => 'name', 'width'=>'100'], ['name' => 'phone', 'width'=>'100'], ['name' => 'addr'], ['name' => 'exam_time'], ['name' => 'print_times', 'align'=>'center', 'width'=>'60'], ]) ], array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php $__env->stopSection(); ?> <?php echo $__env->make('addi.app', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?><file_sep>/* Navicat MySQL Data Transfer Source Server : 本地 Source Server Version : 50626 Source Host : localhost:3306 Source Database : kaoshi Target Server Type : MYSQL Target Server Version : 50626 File Encoding : 65001 Date: 2017-02-24 22:50:02 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for answer -- ---------------------------- DROP TABLE IF EXISTS `answer`; CREATE TABLE `answer` ( `id` int(11) NOT NULL AUTO_INCREMENT, `question_id` int(11) NOT NULL, `name` varchar(200) NOT NULL, `answer_right` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of answer -- ---------------------------- INSERT INTO `answer` VALUES ('1', '10', '选项一', '0'); INSERT INTO `answer` VALUES ('2', '10', '111', '1'); INSERT INTO `answer` VALUES ('3', '11', '选项一', '1'); INSERT INTO `answer` VALUES ('4', '11', '111', '0'); INSERT INTO `answer` VALUES ('20', '12', 'D', '0'); INSERT INTO `answer` VALUES ('29', '17', 'A', '0'); INSERT INTO `answer` VALUES ('30', '17', 'B', '0'); INSERT INTO `answer` VALUES ('31', '17', 'C', '0'); INSERT INTO `answer` VALUES ('32', '17', 'D', '1'); INSERT INTO `answer` VALUES ('33', '16', 'B', '1'); INSERT INTO `answer` VALUES ('34', '16', '111', '0'); INSERT INTO `answer` VALUES ('35', '16', 'C', '0'); INSERT INTO `answer` VALUES ('36', '16', 'D', '0'); INSERT INTO `answer` VALUES ('37', '18', '选项一', '1'); INSERT INTO `answer` VALUES ('38', '19', '选项一', '1'); INSERT INTO `answer` VALUES ('39', '19', '选项一', '1'); INSERT INTO `answer` VALUES ('40', '20', '选项一', '0'); INSERT INTO `answer` VALUES ('41', '21', '选项一', '0'); INSERT INTO `answer` VALUES ('46', '23', '选项一', '0'); INSERT INTO `answer` VALUES ('47', '24', '1', '0'); INSERT INTO `answer` VALUES ('48', '24', '12', '0'); INSERT INTO `answer` VALUES ('53', '22', '1', '0'); INSERT INTO `answer` VALUES ('54', '22', '2', '1'); INSERT INTO `answer` VALUES ('55', '22', '3', '0'); INSERT INTO `answer` VALUES ('56', '22', '4', '0'); INSERT INTO `answer` VALUES ('57', '25', 'yes', '1'); INSERT INTO `answer` VALUES ('58', '25', 'no', '0'); -- ---------------------------- -- Table structure for article -- ---------------------------- DROP TABLE IF EXISTS `article`; CREATE TABLE `article` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dt` datetime NOT NULL, `author` varchar(20) NOT NULL, `title` varchar(50) DEFAULT NULL, `content` varchar(1000) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of article -- ---------------------------- INSERT INTO `article` VALUES ('1', '2017-02-14 14:21:25', '<EMAIL>', '123', '<p>123123123<br></p>'); INSERT INTO `article` VALUES ('4', '2017-02-06 10:24:51', '<EMAIL>', '222', ''); -- ---------------------------- -- Table structure for classes -- ---------------------------- DROP TABLE IF EXISTS `classes`; CREATE TABLE `classes` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `begin_time` datetime NOT NULL, `end_time` datetime NOT NULL, `repeat_time` datetime NOT NULL, `state` int(11) NOT NULL, `sid` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of classes -- ---------------------------- INSERT INTO `classes` VALUES ('1', '一班', '2017-02-23 00:00:00', '2017-02-28 00:00:00', '2017-02-28 00:00:00', '1', '1'); INSERT INTO `classes` VALUES ('2', '二班', '2017-02-23 00:00:00', '2017-02-28 00:00:00', '2017-02-28 00:00:00', '1', '1'); INSERT INTO `classes` VALUES ('3', '三班', '2017-02-23 00:00:00', '2017-02-28 00:00:00', '2017-02-28 00:00:00', '1', '2'); INSERT INTO `classes` VALUES ('4', '四班', '2017-02-23 00:00:00', '2017-02-28 00:00:00', '2017-02-28 00:00:00', '1', '1'); INSERT INTO `classes` VALUES ('5', '五班', '2017-02-23 00:00:00', '2017-02-28 00:00:00', '2017-02-28 00:00:00', '1', '1'); -- ---------------------------- -- Table structure for class_training -- ---------------------------- DROP TABLE IF EXISTS `class_training`; CREATE TABLE `class_training` ( `class_id` int(11) NOT NULL, `training_id` int(11) NOT NULL, `sid` int(11) NOT NULL, PRIMARY KEY (`class_id`,`training_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of class_training -- ---------------------------- INSERT INTO `class_training` VALUES ('1', '5', '0'); INSERT INTO `class_training` VALUES ('1', '6', '1'); INSERT INTO `class_training` VALUES ('2', '1', '0'); INSERT INTO `class_training` VALUES ('2', '2', '1'); INSERT INTO `class_training` VALUES ('2', '3', '2'); INSERT INTO `class_training` VALUES ('2', '4', '3'); INSERT INTO `class_training` VALUES ('2', '5', '4'); INSERT INTO `class_training` VALUES ('2', '6', '5'); INSERT INTO `class_training` VALUES ('2', '7', '6'); INSERT INTO `class_training` VALUES ('2', '8', '7'); -- ---------------------------- -- Table structure for exam -- ---------------------------- DROP TABLE IF EXISTS `exam`; CREATE TABLE `exam` ( `id` int(11) NOT NULL AUTO_INCREMENT, `subject_id` int(11) NOT NULL, `name` varchar(100) NOT NULL, `duration` int(11) NOT NULL, `price` double DEFAULT NULL, `strategy` int(11) NOT NULL, `score` double NOT NULL, `des` varchar(500) DEFAULT NULL, `sid` int(11) NOT NULL, `state` int(11) NOT NULL, `updated_at` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of exam -- ---------------------------- INSERT INTO `exam` VALUES ('10', '1', '语文考试1', '601', '0', '1', '77', '1', '1', '1', '2017-02-21 16:14:03'); INSERT INTO `exam` VALUES ('11', '3', '数学考试', '100', '0', '0', '150', '2', '1', '1', '2017-02-21 16:14:05'); -- ---------------------------- -- Table structure for exam_eval -- ---------------------------- DROP TABLE IF EXISTS `exam_eval`; CREATE TABLE `exam_eval` ( `id` int(11) NOT NULL AUTO_INCREMENT, `exam_id` int(11) NOT NULL, `name` varchar(20) NOT NULL, `min_score` double NOT NULL, `max_score` double NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of exam_eval -- ---------------------------- INSERT INTO `exam_eval` VALUES ('4', '11', '111', '0', '60'); INSERT INTO `exam_eval` VALUES ('5', '10', '不及格', '0', '10'); INSERT INTO `exam_eval` VALUES ('6', '10', '及格', '11', '20'); INSERT INTO `exam_eval` VALUES ('7', '10', '好', '21', '30'); INSERT INTO `exam_eval` VALUES ('8', '10', '优秀', '31', '60'); -- ---------------------------- -- Table structure for exam_question -- ---------------------------- DROP TABLE IF EXISTS `exam_question`; CREATE TABLE `exam_question` ( `exam_id` int(11) NOT NULL, `question_id` int(11) NOT NULL, `sid` int(11) NOT NULL, PRIMARY KEY (`exam_id`,`question_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of exam_question -- ---------------------------- INSERT INTO `exam_question` VALUES ('11', '10', '0'); INSERT INTO `exam_question` VALUES ('11', '17', '1'); INSERT INTO `exam_question` VALUES ('11', '18', '2'); INSERT INTO `exam_question` VALUES ('11', '19', '3'); INSERT INTO `exam_question` VALUES ('11', '20', '4'); -- ---------------------------- -- Table structure for exam_question_type -- ---------------------------- DROP TABLE IF EXISTS `exam_question_type`; CREATE TABLE `exam_question_type` ( `exam_id` int(11) NOT NULL, `question_type` int(11) NOT NULL, `nums` int(11) DEFAULT NULL, `score` double NOT NULL, `amount` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of exam_question_type -- ---------------------------- INSERT INTO `exam_question_type` VALUES ('11', '1', '5', '10', '50'); INSERT INTO `exam_question_type` VALUES ('11', '2', '5', '10', '50'); INSERT INTO `exam_question_type` VALUES ('11', '3', '5', '10', '50'); INSERT INTO `exam_question_type` VALUES ('10', '1', '4', '4', '16'); INSERT INTO `exam_question_type` VALUES ('10', '2', '5', '5', '25'); INSERT INTO `exam_question_type` VALUES ('10', '3', '6', '6', '36'); -- ---------------------------- -- Table structure for log_app -- ---------------------------- DROP TABLE IF EXISTS `log_app`; CREATE TABLE `log_app` ( `id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `module_id` int(11) NOT NULL, `dt` datetime NOT NULL, `des` varchar(200) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of log_app -- ---------------------------- -- ---------------------------- -- Table structure for log_sys -- ---------------------------- DROP TABLE IF EXISTS `log_sys`; CREATE TABLE `log_sys` ( `id` int(11) NOT NULL, `dt` datetime NOT NULL, `module_id` int(11) NOT NULL, `des` varchar(200) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of log_sys -- ---------------------------- -- ---------------------------- -- Table structure for message -- ---------------------------- DROP TABLE IF EXISTS `message`; CREATE TABLE `message` ( `id` int(11) NOT NULL, `title` varchar(50) NOT NULL, `ask_dt` datetime NOT NULL, `asker` varchar(20) NOT NULL, `ask_content` varchar(200) NOT NULL, `answer_dt` datetime NOT NULL, `answer` varchar(20) NOT NULL, `answer_content` varchar(200) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of message -- ---------------------------- -- ---------------------------- -- Table structure for module -- ---------------------------- DROP TABLE IF EXISTS `module`; CREATE TABLE `module` ( `id` int(11) NOT NULL AUTO_INCREMENT, `pid` int(11) NOT NULL, `name` varchar(50) NOT NULL, `icon` varchar(20) DEFAULT NULL, `url` varchar(100) NOT NULL, `type` int(11) NOT NULL DEFAULT '0', `state` int(11) NOT NULL DEFAULT '1', `sid` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=117 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of module -- ---------------------------- INSERT INTO `module` VALUES ('101', '0', '系统主页', null, '/home', '0', '1', '1'); INSERT INTO `module` VALUES ('102', '0', '新闻发布', null, '', '0', '1', '1'); INSERT INTO `module` VALUES ('103', '0', '题库管理', null, '', '0', '1', '1'); INSERT INTO `module` VALUES ('104', '0', '考试管理', null, '', '0', '1', '1'); INSERT INTO `module` VALUES ('105', '0', '报表分析', null, '', '0', '1', '1'); INSERT INTO `module` VALUES ('106', '0', '基础管理', null, '', '0', '1', '1'); INSERT INTO `module` VALUES ('107', '102', '新闻管理', null, '/news/index', '0', '1', '1'); INSERT INTO `module` VALUES ('108', '103', '科目管理', null, '/subject/index', '0', '1', '1'); INSERT INTO `module` VALUES ('109', '103', '题库列表', null, '/topic/index', '0', '1', '1'); INSERT INTO `module` VALUES ('110', '104', '考试列表', null, '/exam/index', '0', '1', '1'); INSERT INTO `module` VALUES ('111', '106', '用户管理', null, '/user/index', '0', '1', '1'); INSERT INTO `module` VALUES ('112', '106', '角色模块', null, '/role/index', '0', '1', '1'); INSERT INTO `module` VALUES ('113', '106', '模块管理', null, '/module/index', '0', '1', '1'); INSERT INTO `module` VALUES ('114', '106', '操作日志', null, '/base/logs', '0', '1', '1'); INSERT INTO `module` VALUES ('115', '0', '培训管理', null, '', '0', '1', '1'); INSERT INTO `module` VALUES ('116', '115', '课程培训', null, '/trainings/index', '0', '1', '1'); -- ---------------------------- -- Table structure for notice -- ---------------------------- DROP TABLE IF EXISTS `notice`; CREATE TABLE `notice` ( `id` int(11) NOT NULL AUTO_INCREMENT, `type` int(11) NOT NULL, `title` varchar(100) NOT NULL, `content` varchar(500) NOT NULL, `sid` int(11) NOT NULL, `state` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of notice -- ---------------------------- -- ---------------------------- -- Table structure for organization -- ---------------------------- DROP TABLE IF EXISTS `organization`; CREATE TABLE `organization` ( `id` int(11) NOT NULL, `name` varchar(20) NOT NULL, `tel` varchar(20) DEFAULT NULL, `des` varchar(100) DEFAULT NULL, `sid` int(11) NOT NULL, `lft` int(11) NOT NULL, `rgt` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of organization -- ---------------------------- -- ---------------------------- -- Table structure for paper -- ---------------------------- DROP TABLE IF EXISTS `paper`; CREATE TABLE `paper` ( `id` int(11) NOT NULL, `exam_id` int(11) NOT NULL, `student_id` int(11) NOT NULL, `dt` datetime NOT NULL, `duration` int(11) NOT NULL, `score` double NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of paper -- ---------------------------- -- ---------------------------- -- Table structure for paper_question -- ---------------------------- DROP TABLE IF EXISTS `paper_question`; CREATE TABLE `paper_question` ( `paper_id` int(11) NOT NULL, `question_id` int(11) NOT NULL, `answer_id` int(11) NOT NULL, `score` double NOT NULL, `sid` int(11) NOT NULL, PRIMARY KEY (`paper_id`,`question_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of paper_question -- ---------------------------- -- ---------------------------- -- Table structure for question -- ---------------------------- DROP TABLE IF EXISTS `question`; CREATE TABLE `question` ( `id` int(11) NOT NULL AUTO_INCREMENT, `subject_id` int(11) NOT NULL, `question_type_id` int(11) NOT NULL, `name` varchar(500) NOT NULL, `des` varchar(1000) DEFAULT NULL, `state` int(11) NOT NULL, `sid` int(11) NOT NULL, `updated_at` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=46 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of question -- ---------------------------- INSERT INTO `question` VALUES ('10', '3', '3', '请选择您认为正确的答案', '', '1', '1', '2017-02-21 16:43:39'); INSERT INTO `question` VALUES ('12', '3', '1', '测试测试测试11', '', '1', '1', '2017-02-21 16:43:42'); INSERT INTO `question` VALUES ('17', '3', '1', '测试测试测试333', '', '1', '1', '2017-02-21 16:43:42'); INSERT INTO `question` VALUES ('18', '3', '1', '请选择您认为正确的答案', '', '1', '1', '2017-02-21 16:43:43'); INSERT INTO `question` VALUES ('19', '3', '1', '请选择您认为正确的答案', '', '1', '1', '2017-02-21 16:43:44'); INSERT INTO `question` VALUES ('20', '3', '3', '请选择您认为正确的答案', '', '1', '1', '2017-02-21 16:43:35'); INSERT INTO `question` VALUES ('21', '3', '3', '请选择您认为正确的答案', '', '1', '1', '2017-02-21 16:43:34'); INSERT INTO `question` VALUES ('22', '3', '3', '1+1=1', '', '1', '1', '2017-02-14 18:03:17'); INSERT INTO `question` VALUES ('24', '9', '1', '重力', '', '1', '1', '2017-02-14 17:59:12'); INSERT INTO `question` VALUES ('25', '4', '1', 'english', '', '1', '1', '2017-02-15 14:00:26'); INSERT INTO `question` VALUES ('26', '3', '1', 'ceshiu 1', null, '1', '1', '2017-02-21 16:48:57'); INSERT INTO `question` VALUES ('27', '3', '1', 'ceshi 2', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('28', '3', '1', 'ceshi 3', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('29', '3', '1', 'ceshi 4', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('30', '3', '1', 'ceshi 5', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('31', '3', '1', 'ceshi 6', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('32', '3', '1', 'ceshi 8', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('33', '3', '1', 'ceshi 7', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('34', '3', '1', 'ceshi 9', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('35', '3', '1', 'ceshi 10', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('36', '3', '1', 'ceshi 11', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('37', '3', '1', 'ceshi 12', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('38', '3', '1', 'ceshi 13', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('39', '3', '1', 'ceshi 14', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('40', '3', '1', 'ceshi 15', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('41', '3', '1', 'ceshi 16', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('42', '3', '1', 'ceshi 17', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('43', '3', '1', 'ceshi 18', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('44', '3', '1', 'ceshi 19', null, '1', '1', '2017-02-21 16:48:58'); INSERT INTO `question` VALUES ('45', '3', '1', 'ceshi 20', null, '1', '1', '2017-02-21 16:48:58'); -- ---------------------------- -- Table structure for question_type -- ---------------------------- DROP TABLE IF EXISTS `question_type`; CREATE TABLE `question_type` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `des` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of question_type -- ---------------------------- INSERT INTO `question_type` VALUES ('1', '单选题', null); INSERT INTO `question_type` VALUES ('2', '多选题', null); INSERT INTO `question_type` VALUES ('3', '判断题', null); -- ---------------------------- -- Table structure for role -- ---------------------------- DROP TABLE IF EXISTS `role`; CREATE TABLE `role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL, `des` varchar(100) DEFAULT NULL, `state` int(11) DEFAULT '1', `sid` int(11) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of role -- ---------------------------- INSERT INTO `role` VALUES ('1', '测试', '111', '1', '0'); -- ---------------------------- -- Table structure for role_module -- ---------------------------- DROP TABLE IF EXISTS `role_module`; CREATE TABLE `role_module` ( `role_id` int(11) NOT NULL, `module_id` int(11) NOT NULL, PRIMARY KEY (`role_id`,`module_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of role_module -- ---------------------------- -- ---------------------------- -- Table structure for student -- ---------------------------- DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `id` int(11) NOT NULL, `name` int(11) NOT NULL, `weixin` varchar(50) NOT NULL, `idnumber` varchar(20) DEFAULT NULL, `cellphone` varchar(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of student -- ---------------------------- -- ---------------------------- -- Table structure for students -- ---------------------------- DROP TABLE IF EXISTS `students`; CREATE TABLE `students` ( `id` int(11) NOT NULL AUTO_INCREMENT, `class_id` int(11) NOT NULL, `code` varchar(10) NOT NULL, `name` varchar(20) NOT NULL, `pinyin` varchar(20) DEFAULT NULL, `gender` varchar(11) DEFAULT NULL, `birthday` datetime DEFAULT NULL, `papers_id` varchar(50) DEFAULT NULL, `task_type` varchar(50) DEFAULT NULL, `id_no` varchar(20) DEFAULT NULL, `project` varchar(50) DEFAULT NULL, `category` varchar(50) DEFAULT NULL, `education` varchar(50) DEFAULT NULL, `health` varchar(50) DEFAULT NULL, `job` varchar(50) DEFAULT NULL, `title` varchar(50) DEFAULT NULL, `political` varchar(50) DEFAULT NULL, `profession_study` varchar(50) DEFAULT NULL, `profession_job` varchar(50) DEFAULT NULL, `work_time` datetime DEFAULT NULL, `phone` varchar(50) DEFAULT NULL, `company_type` varchar(50) DEFAULT NULL, `company` varchar(50) DEFAULT NULL, `training_type` varchar(50) DEFAULT NULL, `training_time` datetime DEFAULT NULL, `score_paper` decimal(5,2) DEFAULT NULL, `score_paper_retry` decimal(5,2) DEFAULT NULL, `score_practical` decimal(5,2) DEFAULT NULL, `score_practical_retry` decimal(5,2) DEFAULT NULL, `addr` varchar(50) DEFAULT NULL, `exam_time` datetime DEFAULT NULL, `pass_time` datetime DEFAULT NULL, `des` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=483 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of students -- ---------------------------- INSERT INTO `students` VALUES ('408', '1', '5551668', '吴平', 'WP', '男', '1985-08-23 00:00:00', null, '', '321282198508230833', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18862757017', '危险化学品生产单位', '江苏泰利达新材料股份有限公司', '初培', '2016-07-27 00:00:00', '81.00', '0.00', null, null, '江苏省靖江市西来镇荷花村洼圩埭3-34号', '2016-08-01 09:56:48', null, null); INSERT INTO `students` VALUES ('409', '1', '5551669', '沈佳成', 'SJC', '男', '1987-11-23 00:00:00', null, '', '32068219871123219X', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15190882259', '危险化学品生产单位', '江苏恒峰精细化学股份有限公司', '初培', '2016-07-27 00:00:00', '79.00', '0.00', null, null, '江苏省如皋市白蒲镇万安苑8幢308室', '2016-08-01 09:42:31', null, null); INSERT INTO `students` VALUES ('410', '1', '5551670', '李冬华', 'LDH', '男', '1991-01-05 00:00:00', null, '', '320623199101054239', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15262761979', '危险化学品生产单位', '南通新宙邦电子材料有限公司', '初培', '2016-07-27 00:00:00', '93.00', '0.00', null, null, '南京市鼓楼区新模范马路30号', '2016-08-01 09:48:52', null, null); INSERT INTO `students` VALUES ('411', '1', '5551671', '郝敬磊', 'HJL', '男', '1985-12-30 00:00:00', null, '', '370826198512304073', null, '安全生产管理人员', '硕士', '健康', '安全生产管理人员', null, null, null, null, null, '13602659004', '危险化学品生产单位', '南通新宙邦电子材料有限公司', '初培', '2016-07-27 00:00:00', '92.00', '0.00', null, null, '山东省微山县欢城镇东岗子村北二路090号', '2016-08-01 09:51:29', null, null); INSERT INTO `students` VALUES ('412', '1', '5551672', '杨茜娟', 'YQJ', '女', '1990-10-14 00:00:00', null, '', '320681199010145622', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '1886286630', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '96.00', '0.00', null, null, '江苏省启东市东海镇兴旺村九组533号', '2016-08-01 09:48:36', null, null); INSERT INTO `students` VALUES ('413', '1', '5551673', '吴殿峰', 'WDF', '男', '1987-02-03 00:00:00', null, '', '321084198702032613', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18101673190', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '94.00', '0.00', null, null, '江苏省高邮市汉留镇年合村四组75号', '2016-08-01 09:42:11', null, null); INSERT INTO `students` VALUES ('414', '1', '5551674', '丁杨', 'DY', '男', '1987-07-23 00:00:00', null, '', '420923198707234379', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18862819553', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '92.00', '0.00', null, null, '湖北省云梦县沙河乡杨林村胡家台', '2016-08-01 09:37:36', null, null); INSERT INTO `students` VALUES ('415', '1', '5551675', '陈艳红', 'CYH', '女', '1989-02-09 00:00:00', null, '', '320681198902097027', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13401281989', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '89.00', '0.00', null, null, '江苏省启东市海复镇清虎村一组57号', '2016-08-01 09:41:37', null, null); INSERT INTO `students` VALUES ('416', '1', '5551676', '唐京', 'TJ', '男', '1991-04-09 00:00:00', null, '', '430903199104091533', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15240558689', '危险化学品生产单位', '南通新宙邦电子材料有限公司', '初培', '2016-07-27 00:00:00', '91.00', '0.00', null, null, '武汉市江汉区常青路149号', '2016-08-01 10:03:22', null, null); INSERT INTO `students` VALUES ('417', '1', '5551677', '胡光涛', 'HGT', '男', '1987-09-01 00:00:00', null, '', '321323198709014737', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '13862795827', '危险化学品生产单位', '南通京利锂电新材料有限公司', '初培', '2016-07-27 00:00:00', '77.00', '0.00', null, null, '江苏省泗阳县王集镇跃进村七组7号', '2016-08-01 10:00:04', null, null); INSERT INTO `students` VALUES ('418', '1', '5551678', '张东', 'ZD', '男', '1990-10-27 00:00:00', null, '', '320621199010272414', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '15152434935', '危险化学品生产单位', '南通宝叶化工有限公司', '初培', '2016-07-27 00:00:00', '88.00', '0.00', null, null, '江苏省海安县城东镇堑南村南八组28号', '2016-08-01 10:04:48', null, null); INSERT INTO `students` VALUES ('419', '1', '5551679', '翟连华', 'ZLH', '男', '1982-07-19 00:00:00', null, '', '330522198207196716', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '18868212125', '危险化学品生产单位', '启东韶远化学科技有限公司', '初培', '2016-07-27 00:00:00', '85.00', '0.00', null, null, '浙江省长兴县泗安镇新联村上泗安自然村349号', '2016-08-01 10:05:36', null, null); INSERT INTO `students` VALUES ('420', '1', '5551680', '刘洪波', 'LHB', '男', '1982-01-22 00:00:00', null, '', '320722198201228114', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13812337916', '危险化学品生产单位', '启东韶远化学科技有限公司', '初培', '2016-07-27 00:00:00', '91.00', '0.00', null, null, '江苏省东海县张湾乡新坝村3-51号', '2016-08-01 10:02:07', null, null); INSERT INTO `students` VALUES ('421', '1', '5551681', '陈明', 'CM', '男', '1982-01-02 00:00:00', null, '', '321111198201022713', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13773870596', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '94.00', '0.00', null, null, '江苏省启东市汇龙镇开来华府12号楼1107室', '2016-08-01 09:46:51', null, null); INSERT INTO `students` VALUES ('422', '1', '5551682', '章海兵', 'ZHB', '男', '1983-11-02 00:00:00', null, '', '320682198311026776', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18706295181', '危险化学品生产单位', '南通新宙邦电子材料有限公司', '初培', '2016-07-27 00:00:00', '87.00', '0.00', null, null, '江苏省如皋市搬经镇任庄村十一组46号', '2016-08-01 10:08:40', null, null); INSERT INTO `students` VALUES ('423', '1', '5551683', '宋建华', 'SJH', '女', '1978-02-18 00:00:00', null, '', '412924197802181705', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '13646261797', '危险化学品生产单位', '南通天和树脂有限公司', '初培', '2016-07-27 00:00:00', '85.00', '0.00', null, null, '河南省漯河市源汇区泰山南路659号院1单元102号', '2016-08-01 09:48:49', null, null); INSERT INTO `students` VALUES ('424', '1', '5551684', '孙振佳', 'SZJ', '男', '1988-12-19 00:00:00', null, '', '320721198812191414', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18795759339', '危险化学品生产单位', '上海制皂(集团)如皋有限公司', '初培', '2016-07-27 00:00:00', '84.00', '0.00', null, null, '江苏省赣榆县沙河镇前进村舍庄六队186号', '2016-08-01 09:47:44', null, null); INSERT INTO `students` VALUES ('425', '1', '5551685', '张仲亮', 'ZZL', '男', '1993-01-04 00:00:00', null, '', '32048219930104347X', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15951312954', '危险化学品生产单位', '万洲石化(江苏)有限公司', '初培', '2016-07-27 00:00:00', '0.00', '0.00', null, null, '江苏省金坛市尧塘镇东榭村委双沟坝18号', null, null, null); INSERT INTO `students` VALUES ('426', '1', '5551686', '马莉', 'ML', '女', '1972-07-06 00:00:00', null, '', '650105197207060722', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13916947500', '危险化学品生产单位', '启东江天化工有限公司', '初培', '2016-07-27 00:00:00', '94.00', '0.00', null, null, '上海市浦东新区新浦路673弄8号204室', '2016-08-01 09:49:07', null, null); INSERT INTO `students` VALUES ('427', '1', '5551687', '武坚', 'WJ', '男', '1976-07-16 00:00:00', null, '', '310107197607165413', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '13482262362', '危险化学品生产单位', '启东江天化工有限公司', '初培', '2016-07-27 00:00:00', '78.00', '0.00', null, null, '上海市宝山区通河三村56号501室', '2016-08-01 10:05:32', null, null); INSERT INTO `students` VALUES ('428', '1', '5551688', '杨勇', 'YY', '男', '1973-08-28 00:00:00', null, '', '321081197308287550', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18662856868', '危险化学品生产单位', '南通高盟新材料有限公司', '初培', '2016-07-27 00:00:00', '89.00', '0.00', null, null, '江苏省苏州市工业园区湖畔天城花园24幢803室', '2016-08-01 10:14:02', null, null); INSERT INTO `students` VALUES ('429', '1', '5551689', '成健铭', 'CJM', '男', '1984-12-27 00:00:00', null, '', '320623198412273178', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13512506254', '危险化学品生产单位', '南通高盟新材料有限公司', '初培', '2016-07-27 00:00:00', '93.00', '0.00', null, null, '南京市沿江工业开发区草芳路213号3幢1405室', '2016-08-01 10:45:43', null, null); INSERT INTO `students` VALUES ('430', '1', '5551690', '黄鑫', 'HX', '男', '1981-11-05 00:00:00', null, '', '320684198111054177', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15706287878', '危险化学品生产单位', '南通市争妍颜料化工有限公司', '初培', '2016-07-27 00:00:00', '76.00', '0.00', null, null, '江苏省海门市海门镇民生新村604幢601室', '2016-08-01 09:53:44', null, null); INSERT INTO `students` VALUES ('431', '1', '5551691', '柏海峰', 'BHF', '男', '1983-09-07 00:00:00', null, '', '320684198309070033', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13862868499', '危险化学品生产单位', '上海现代制药海门有限公司', '初培', '2016-07-27 00:00:00', '78.00', '87.00', null, null, '江苏省海门市海门镇大同新村506幢202室', '2016-08-01 10:40:40', null, null); INSERT INTO `students` VALUES ('432', '1', '5551692', '王爱国', 'WAG', '男', '1969-10-15 00:00:00', null, '', '132329196910153813', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15128192996', '危险化学品生产单位', '南通汇顺化工有限公司', '初培', '2016-07-27 00:00:00', '91.00', '0.00', null, null, '河北省新乐市新开路新华胡同南楼2单元401号', '2016-08-01 09:45:26', null, null); INSERT INTO `students` VALUES ('433', '1', '5551668', '吴平', 'WP', '男', '1985-08-23 00:00:00', null, '', '321282198508230833', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18862757017', '危险化学品生产单位', '江苏泰利达新材料股份有限公司', '初培', '2016-07-27 00:00:00', '81.00', '0.00', null, null, '江苏省靖江市西来镇荷花村洼圩埭3-34号', '2016-08-01 09:56:48', null, null); INSERT INTO `students` VALUES ('434', '1', '5551669', '沈佳成', 'SJC', '男', '1987-11-23 00:00:00', null, '', '32068219871123219X', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15190882259', '危险化学品生产单位', '江苏恒峰精细化学股份有限公司', '初培', '2016-07-27 00:00:00', '79.00', '0.00', null, null, '江苏省如皋市白蒲镇万安苑8幢308室', '2016-08-01 09:42:31', null, null); INSERT INTO `students` VALUES ('435', '1', '5551670', '李冬华', 'LDH', '男', '1991-01-05 00:00:00', null, '', '320623199101054239', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15262761979', '危险化学品生产单位', '南通新宙邦电子材料有限公司', '初培', '2016-07-27 00:00:00', '93.00', '0.00', null, null, '南京市鼓楼区新模范马路30号', '2016-08-01 09:48:52', null, null); INSERT INTO `students` VALUES ('436', '1', '5551671', '郝敬磊', 'HJL', '男', '1985-12-30 00:00:00', null, '', '370826198512304073', null, '安全生产管理人员', '硕士', '健康', '安全生产管理人员', null, null, null, null, null, '13602659004', '危险化学品生产单位', '南通新宙邦电子材料有限公司', '初培', '2016-07-27 00:00:00', '92.00', '0.00', null, null, '山东省微山县欢城镇东岗子村北二路090号', '2016-08-01 09:51:29', null, null); INSERT INTO `students` VALUES ('437', '1', '5551672', '杨茜娟', 'YQJ', '女', '1990-10-14 00:00:00', null, '', '320681199010145622', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '1886286630', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '96.00', '0.00', null, null, '江苏省启东市东海镇兴旺村九组533号', '2016-08-01 09:48:36', null, null); INSERT INTO `students` VALUES ('438', '1', '5551673', '吴殿峰', 'WDF', '男', '1987-02-03 00:00:00', null, '', '321084198702032613', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18101673190', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '94.00', '0.00', null, null, '江苏省高邮市汉留镇年合村四组75号', '2016-08-01 09:42:11', null, null); INSERT INTO `students` VALUES ('439', '1', '5551674', '丁杨', 'DY', '男', '1987-07-23 00:00:00', null, '', '420923198707234379', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18862819553', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '92.00', '0.00', null, null, '湖北省云梦县沙河乡杨林村胡家台', '2016-08-01 09:37:36', null, null); INSERT INTO `students` VALUES ('440', '1', '5551675', '陈艳红', 'CYH', '女', '1989-02-09 00:00:00', null, '', '320681198902097027', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13401281989', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '89.00', '0.00', null, null, '江苏省启东市海复镇清虎村一组57号', '2016-08-01 09:41:37', null, null); INSERT INTO `students` VALUES ('441', '1', '5551676', '唐京', 'TJ', '男', '1991-04-09 00:00:00', null, '', '430903199104091533', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15240558689', '危险化学品生产单位', '南通新宙邦电子材料有限公司', '初培', '2016-07-27 00:00:00', '91.00', '0.00', null, null, '武汉市江汉区常青路149号', '2016-08-01 10:03:22', null, null); INSERT INTO `students` VALUES ('442', '1', '5551677', '胡光涛', 'HGT', '男', '1987-09-01 00:00:00', null, '', '321323198709014737', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '13862795827', '危险化学品生产单位', '南通京利锂电新材料有限公司', '初培', '2016-07-27 00:00:00', '77.00', '0.00', null, null, '江苏省泗阳县王集镇跃进村七组7号', '2016-08-01 10:00:04', null, null); INSERT INTO `students` VALUES ('443', '1', '5551678', '张东', 'ZD', '男', '1990-10-27 00:00:00', null, '', '320621199010272414', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '15152434935', '危险化学品生产单位', '南通宝叶化工有限公司', '初培', '2016-07-27 00:00:00', '88.00', '0.00', null, null, '江苏省海安县城东镇堑南村南八组28号', '2016-08-01 10:04:48', null, null); INSERT INTO `students` VALUES ('444', '1', '5551679', '翟连华', 'ZLH', '男', '1982-07-19 00:00:00', null, '', '330522198207196716', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '18868212125', '危险化学品生产单位', '启东韶远化学科技有限公司', '初培', '2016-07-27 00:00:00', '85.00', '0.00', null, null, '浙江省长兴县泗安镇新联村上泗安自然村349号', '2016-08-01 10:05:36', null, null); INSERT INTO `students` VALUES ('445', '1', '5551680', '刘洪波', 'LHB', '男', '1982-01-22 00:00:00', null, '', '320722198201228114', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13812337916', '危险化学品生产单位', '启东韶远化学科技有限公司', '初培', '2016-07-27 00:00:00', '91.00', '0.00', null, null, '江苏省东海县张湾乡新坝村3-51号', '2016-08-01 10:02:07', null, null); INSERT INTO `students` VALUES ('446', '1', '5551681', '陈明', 'CM', '男', '1982-01-02 00:00:00', null, '', '321111198201022713', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13773870596', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '94.00', '0.00', null, null, '江苏省启东市汇龙镇开来华府12号楼1107室', '2016-08-01 09:46:51', null, null); INSERT INTO `students` VALUES ('447', '1', '5551682', '章海兵', 'ZHB', '男', '1983-11-02 00:00:00', null, '', '320682198311026776', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18706295181', '危险化学品生产单位', '南通新宙邦电子材料有限公司', '初培', '2016-07-27 00:00:00', '87.00', '0.00', null, null, '江苏省如皋市搬经镇任庄村十一组46号', '2016-08-01 10:08:40', null, null); INSERT INTO `students` VALUES ('448', '1', '5551683', '宋建华', 'SJH', '女', '1978-02-18 00:00:00', null, '', '412924197802181705', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '13646261797', '危险化学品生产单位', '南通天和树脂有限公司', '初培', '2016-07-27 00:00:00', '85.00', '0.00', null, null, '河南省漯河市源汇区泰山南路659号院1单元102号', '2016-08-01 09:48:49', null, null); INSERT INTO `students` VALUES ('449', '1', '5551684', '孙振佳', 'SZJ', '男', '1988-12-19 00:00:00', null, '', '320721198812191414', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18795759339', '危险化学品生产单位', '上海制皂(集团)如皋有限公司', '初培', '2016-07-27 00:00:00', '84.00', '0.00', null, null, '江苏省赣榆县沙河镇前进村舍庄六队186号', '2016-08-01 09:47:44', null, null); INSERT INTO `students` VALUES ('450', '1', '5551685', '张仲亮', 'ZZL', '男', '1993-01-04 00:00:00', null, '', '32048219930104347X', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15951312954', '危险化学品生产单位', '万洲石化(江苏)有限公司', '初培', '2016-07-27 00:00:00', '0.00', '0.00', null, null, '江苏省金坛市尧塘镇东榭村委双沟坝18号', null, null, null); INSERT INTO `students` VALUES ('451', '1', '5551686', '马莉', 'ML', '女', '1972-07-06 00:00:00', null, '', '650105197207060722', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13916947500', '危险化学品生产单位', '启东江天化工有限公司', '初培', '2016-07-27 00:00:00', '94.00', '0.00', null, null, '上海市浦东新区新浦路673弄8号204室', '2016-08-01 09:49:07', null, null); INSERT INTO `students` VALUES ('452', '1', '5551687', '武坚', 'WJ', '男', '1976-07-16 00:00:00', null, '', '310107197607165413', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '13482262362', '危险化学品生产单位', '启东江天化工有限公司', '初培', '2016-07-27 00:00:00', '78.00', '0.00', null, null, '上海市宝山区通河三村56号501室', '2016-08-01 10:05:32', null, null); INSERT INTO `students` VALUES ('453', '1', '5551688', '杨勇', 'YY', '男', '1973-08-28 00:00:00', null, '', '321081197308287550', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18662856868', '危险化学品生产单位', '南通高盟新材料有限公司', '初培', '2016-07-27 00:00:00', '89.00', '0.00', null, null, '江苏省苏州市工业园区湖畔天城花园24幢803室', '2016-08-01 10:14:02', null, null); INSERT INTO `students` VALUES ('454', '1', '5551689', '成健铭', 'CJM', '男', '1984-12-27 00:00:00', null, '', '320623198412273178', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13512506254', '危险化学品生产单位', '南通高盟新材料有限公司', '初培', '2016-07-27 00:00:00', '93.00', '0.00', null, null, '南京市沿江工业开发区草芳路213号3幢1405室', '2016-08-01 10:45:43', null, null); INSERT INTO `students` VALUES ('455', '1', '5551690', '黄鑫', 'HX', '男', '1981-11-05 00:00:00', null, '', '320684198111054177', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15706287878', '危险化学品生产单位', '南通市争妍颜料化工有限公司', '初培', '2016-07-27 00:00:00', '76.00', '0.00', null, null, '江苏省海门市海门镇民生新村604幢601室', '2016-08-01 09:53:44', null, null); INSERT INTO `students` VALUES ('456', '1', '5551691', '柏海峰', 'BHF', '男', '1983-09-07 00:00:00', null, '', '320684198309070033', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13862868499', '危险化学品生产单位', '上海现代制药海门有限公司', '初培', '2016-07-27 00:00:00', '78.00', '87.00', null, null, '江苏省海门市海门镇大同新村506幢202室', '2016-08-01 10:40:40', null, null); INSERT INTO `students` VALUES ('457', '1', '5551692', '王爱国', 'WAG', '男', '1969-10-15 00:00:00', null, '', '132329196910153813', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15128192996', '危险化学品生产单位', '南通汇顺化工有限公司', '初培', '2016-07-27 00:00:00', '91.00', '0.00', null, null, '河北省新乐市新开路新华胡同南楼2单元401号', '2016-08-01 09:45:26', null, null); INSERT INTO `students` VALUES ('458', '4', '5551668', '吴平', 'WP', '男', '1985-08-23 00:00:00', null, '', '321282198508230833', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18862757017', '危险化学品生产单位', '江苏泰利达新材料股份有限公司', '初培', '2016-07-27 00:00:00', '81.00', '0.00', null, null, '江苏省靖江市西来镇荷花村洼圩埭3-34号', '2016-08-01 09:56:48', null, null); INSERT INTO `students` VALUES ('459', '4', '5551669', '沈佳成', 'SJC', '男', '1987-11-23 00:00:00', null, '', '32068219871123219X', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15190882259', '危险化学品生产单位', '江苏恒峰精细化学股份有限公司', '初培', '2016-07-27 00:00:00', '79.00', '0.00', null, null, '江苏省如皋市白蒲镇万安苑8幢308室', '2016-08-01 09:42:31', null, null); INSERT INTO `students` VALUES ('460', '4', '5551670', '李冬华', 'LDH', '男', '1991-01-05 00:00:00', null, '', '320623199101054239', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15262761979', '危险化学品生产单位', '南通新宙邦电子材料有限公司', '初培', '2016-07-27 00:00:00', '93.00', '0.00', null, null, '南京市鼓楼区新模范马路30号', '2016-08-01 09:48:52', null, null); INSERT INTO `students` VALUES ('461', '4', '5551671', '郝敬磊', 'HJL', '男', '1985-12-30 00:00:00', null, '', '370826198512304073', null, '安全生产管理人员', '硕士', '健康', '安全生产管理人员', null, null, null, null, null, '13602659004', '危险化学品生产单位', '南通新宙邦电子材料有限公司', '初培', '2016-07-27 00:00:00', '92.00', '0.00', null, null, '山东省微山县欢城镇东岗子村北二路090号', '2016-08-01 09:51:29', null, null); INSERT INTO `students` VALUES ('462', '4', '5551672', '杨茜娟', 'YQJ', '女', '1990-10-14 00:00:00', null, '', '320681199010145622', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '1886286630', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '96.00', '0.00', null, null, '江苏省启东市东海镇兴旺村九组533号', '2016-08-01 09:48:36', null, null); INSERT INTO `students` VALUES ('463', '4', '5551673', '吴殿峰', 'WDF', '男', '1987-02-03 00:00:00', null, '', '321084198702032613', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18101673190', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '94.00', '0.00', null, null, '江苏省高邮市汉留镇年合村四组75号', '2016-08-01 09:42:11', null, null); INSERT INTO `students` VALUES ('464', '4', '5551674', '丁杨', 'DY', '男', '1987-07-23 00:00:00', null, '', '420923198707234379', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18862819553', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '92.00', '0.00', null, null, '湖北省云梦县沙河乡杨林村胡家台', '2016-08-01 09:37:36', null, null); INSERT INTO `students` VALUES ('465', '4', '5551675', '陈艳红', 'CYH', '女', '1989-02-09 00:00:00', null, '', '320681198902097027', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13401281989', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '89.00', '0.00', null, null, '江苏省启东市海复镇清虎村一组57号', '2016-08-01 09:41:37', null, null); INSERT INTO `students` VALUES ('466', '4', '5551676', '唐京', 'TJ', '男', '1991-04-09 00:00:00', null, '', '430903199104091533', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15240558689', '危险化学品生产单位', '南通新宙邦电子材料有限公司', '初培', '2016-07-27 00:00:00', '91.00', '0.00', null, null, '武汉市江汉区常青路149号', '2016-08-01 10:03:22', null, null); INSERT INTO `students` VALUES ('467', '4', '5551677', '胡光涛', 'HGT', '男', '1987-09-01 00:00:00', null, '', '321323198709014737', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '13862795827', '危险化学品生产单位', '南通京利锂电新材料有限公司', '初培', '2016-07-27 00:00:00', '77.00', '0.00', null, null, '江苏省泗阳县王集镇跃进村七组7号', '2016-08-01 10:00:04', null, null); INSERT INTO `students` VALUES ('468', '4', '5551678', '张东', 'ZD', '男', '1990-10-27 00:00:00', null, '', '320621199010272414', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '15152434935', '危险化学品生产单位', '南通宝叶化工有限公司', '初培', '2016-07-27 00:00:00', '88.00', '0.00', null, null, '江苏省海安县城东镇堑南村南八组28号', '2016-08-01 10:04:48', null, null); INSERT INTO `students` VALUES ('469', '4', '5551679', '翟连华', 'ZLH', '男', '1982-07-19 00:00:00', null, '', '330522198207196716', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '18868212125', '危险化学品生产单位', '启东韶远化学科技有限公司', '初培', '2016-07-27 00:00:00', '85.00', '0.00', null, null, '浙江省长兴县泗安镇新联村上泗安自然村349号', '2016-08-01 10:05:36', null, null); INSERT INTO `students` VALUES ('470', '4', '5551680', '刘洪波', 'LHB', '男', '1982-01-22 00:00:00', null, '', '320722198201228114', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13812337916', '危险化学品生产单位', '启东韶远化学科技有限公司', '初培', '2016-07-27 00:00:00', '91.00', '0.00', null, null, '江苏省东海县张湾乡新坝村3-51号', '2016-08-01 10:02:07', null, null); INSERT INTO `students` VALUES ('471', '4', '5551681', '陈明', 'CM', '男', '1982-01-02 00:00:00', null, '', '321111198201022713', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13773870596', '危险化学品生产单位', '启东东岳药业有限公司', '初培', '2016-07-27 00:00:00', '94.00', '0.00', null, null, '江苏省启东市汇龙镇开来华府12号楼1107室', '2016-08-01 09:46:51', null, null); INSERT INTO `students` VALUES ('472', '4', '5551682', '章海兵', 'ZHB', '男', '1983-11-02 00:00:00', null, '', '320682198311026776', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18706295181', '危险化学品生产单位', '南通新宙邦电子材料有限公司', '初培', '2016-07-27 00:00:00', '87.00', '0.00', null, null, '江苏省如皋市搬经镇任庄村十一组46号', '2016-08-01 10:08:40', null, null); INSERT INTO `students` VALUES ('473', '4', '5551683', '宋建华', 'SJH', '女', '1978-02-18 00:00:00', null, '', '412924197802181705', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '13646261797', '危险化学品生产单位', '南通天和树脂有限公司', '初培', '2016-07-27 00:00:00', '85.00', '0.00', null, null, '河南省漯河市源汇区泰山南路659号院1单元102号', '2016-08-01 09:48:49', null, null); INSERT INTO `students` VALUES ('474', '4', '5551684', '孙振佳', 'SZJ', '男', '1988-12-19 00:00:00', null, '', '320721198812191414', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18795759339', '危险化学品生产单位', '上海制皂(集团)如皋有限公司', '初培', '2016-07-27 00:00:00', '84.00', '0.00', null, null, '江苏省赣榆县沙河镇前进村舍庄六队186号', '2016-08-01 09:47:44', null, null); INSERT INTO `students` VALUES ('475', '4', '5551685', '张仲亮', 'ZZL', '男', '1993-01-04 00:00:00', null, '', '32048219930104347X', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15951312954', '危险化学品生产单位', '万洲石化(江苏)有限公司', '初培', '2016-07-27 00:00:00', '0.00', '0.00', null, null, '江苏省金坛市尧塘镇东榭村委双沟坝18号', null, null, null); INSERT INTO `students` VALUES ('476', '4', '5551686', '马莉', 'ML', '女', '1972-07-06 00:00:00', null, '', '650105197207060722', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13916947500', '危险化学品生产单位', '启东江天化工有限公司', '初培', '2016-07-27 00:00:00', '94.00', '0.00', null, null, '上海市浦东新区新浦路673弄8号204室', '2016-08-01 09:49:07', null, null); INSERT INTO `students` VALUES ('477', '4', '5551687', '武坚', 'WJ', '男', '1976-07-16 00:00:00', null, '', '310107197607165413', null, '安全生产管理人员', '大专', '健康', '安全生产管理人员', null, null, null, null, null, '13482262362', '危险化学品生产单位', '启东江天化工有限公司', '初培', '2016-07-27 00:00:00', '78.00', '0.00', null, null, '上海市宝山区通河三村56号501室', '2016-08-01 10:05:32', null, null); INSERT INTO `students` VALUES ('478', '4', '5551688', '杨勇', 'YY', '男', '1973-08-28 00:00:00', null, '', '321081197308287550', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '18662856868', '危险化学品生产单位', '南通高盟新材料有限公司', '初培', '2016-07-27 00:00:00', '89.00', '0.00', null, null, '江苏省苏州市工业园区湖畔天城花园24幢803室', '2016-08-01 10:14:02', null, null); INSERT INTO `students` VALUES ('479', '4', '5551689', '成健铭', 'CJM', '男', '1984-12-27 00:00:00', null, '', '320623198412273178', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13512506254', '危险化学品生产单位', '南通高盟新材料有限公司', '初培', '2016-07-27 00:00:00', '93.00', '0.00', null, null, '南京市沿江工业开发区草芳路213号3幢1405室', '2016-08-01 10:45:43', null, null); INSERT INTO `students` VALUES ('480', '4', '5551690', '黄鑫', 'HX', '男', '1981-11-05 00:00:00', null, '', '320684198111054177', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15706287878', '危险化学品生产单位', '南通市争妍颜料化工有限公司', '初培', '2016-07-27 00:00:00', '76.00', '0.00', null, null, '江苏省海门市海门镇民生新村604幢601室', '2016-08-01 09:53:44', null, null); INSERT INTO `students` VALUES ('481', '4', '5551691', '柏海峰', 'BHF', '男', '1983-09-07 00:00:00', null, '', '320684198309070033', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '13862868499', '危险化学品生产单位', '上海现代制药海门有限公司', '初培', '2016-07-27 00:00:00', '78.00', '87.00', null, null, '江苏省海门市海门镇大同新村506幢202室', '2016-08-01 10:40:40', null, null); INSERT INTO `students` VALUES ('482', '4', '5551692', '王爱国', 'WAG', '男', '1969-10-15 00:00:00', null, '', '132329196910153813', null, '安全生产管理人员', '本科', '健康', '安全生产管理人员', null, null, null, null, null, '15128192996', '危险化学品生产单位', '南通汇顺化工有限公司', '初培', '2016-07-27 00:00:00', '91.00', '0.00', null, null, '河北省新乐市新开路新华胡同南楼2单元401号', '2016-08-01 09:45:26', null, null); -- ---------------------------- -- Table structure for subject -- ---------------------------- DROP TABLE IF EXISTS `subject`; CREATE TABLE `subject` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `des` varchar(500) DEFAULT NULL, `state` int(11) NOT NULL, `sid` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of subject -- ---------------------------- INSERT INTO `subject` VALUES ('1', '语文', '科目一的描述信息', '1', '1'); INSERT INTO `subject` VALUES ('3', '数学', '科目二的描述', '1', '11'); INSERT INTO `subject` VALUES ('4', '英语', '111', '1', '1'); INSERT INTO `subject` VALUES ('5', '历史', '1', '1', '1'); INSERT INTO `subject` VALUES ('6', '地理', '1', '1', '1'); INSERT INTO `subject` VALUES ('7', '生物', '1', '1', '1'); INSERT INTO `subject` VALUES ('8', '体育', '1', '1', '1'); INSERT INTO `subject` VALUES ('9', '物理', '1', '1', '1'); INSERT INTO `subject` VALUES ('10', '化学', '1', '1', '1'); INSERT INTO `subject` VALUES ('11', '11', '12', '1', '1'); INSERT INTO `subject` VALUES ('12', '22', '22', '1', '1'); INSERT INTO `subject` VALUES ('13', '33', '33', '1', '3'); INSERT INTO `subject` VALUES ('14', '44', '44', '1', '4'); INSERT INTO `subject` VALUES ('15', '55', '55', '1', '5'); INSERT INTO `subject` VALUES ('16', '66', '66', '1', '6'); INSERT INTO `subject` VALUES ('17', '77', '77', '1', '7'); INSERT INTO `subject` VALUES ('18', '88', '88', '1', '8'); INSERT INTO `subject` VALUES ('19', '99', '99', '1', '9'); INSERT INTO `subject` VALUES ('20', '10101', '10101', '1', '1'); -- ---------------------------- -- Table structure for trainings -- ---------------------------- DROP TABLE IF EXISTS `trainings`; CREATE TABLE `trainings` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `duration` decimal(10,2) NOT NULL, `state` int(11) NOT NULL, `sid` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of trainings -- ---------------------------- INSERT INTO `trainings` VALUES ('1', '语文', '22.00', '1', '1'); INSERT INTO `trainings` VALUES ('2', '数学', '22.00', '1', '1'); INSERT INTO `trainings` VALUES ('3', '英语', '22.00', '1', '1'); INSERT INTO `trainings` VALUES ('4', '物理', '22.00', '1', '1'); INSERT INTO `trainings` VALUES ('5', '化学', '22.00', '1', '1'); INSERT INTO `trainings` VALUES ('6', '地理', '22.00', '1', '1'); INSERT INTO `trainings` VALUES ('7', '历史', '22.00', '1', '1'); INSERT INTO `trainings` VALUES ('8', '生物', '22.00', '1', '1'); -- ---------------------------- -- Table structure for users -- ---------------------------- DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL, `password` varchar(100) NOT NULL, `weixin` varchar(50) DEFAULT NULL, `email` varchar(50) NOT NULL, `remember_token` varchar(200) DEFAULT NULL, `created_at` datetime NOT NULL, `updated_at` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of users -- ---------------------------- INSERT INTO `users` VALUES ('1', 'qweqwe', '$2y$10$tF1JDnMXcWzd6FQ5t0p19er5bJpLdYrf6jwwQXQNjQ8QIIz.Y8Pmq', null, '<EMAIL>', 'vrcLDfTn0UYQzKyQwLGMxd9KJptv0bc0kpNE0QBW7sESoDvbtnsOw941lDek', '2017-01-22 07:25:13', '2017-01-22 10:18:48'); INSERT INTO `users` VALUES ('2', '113322', '$2y$10$K.w6IR9Veu6n9WJjbZq67uUnl4TsIykbVoFTbKl.lOKsr4gtPHJqG', null, '<EMAIL>', null, '2017-01-22 10:32:17', '2017-02-11 14:10:40'); INSERT INTO `users` VALUES ('4', '222241', '$2y$10$TuUU/K6nEmohAw97eJ2TpeDLCvfhwWcYnRoPxP.p5fA8Nq7sCglf6', null, '<EMAIL>', null, '2017-01-22 10:39:42', '2017-02-08 06:16:19'); INSERT INTO `users` VALUES ('5', 'test', '$2y$10$/bm4TWk4MwAVEhnrSRIG2ubeHxM.1ju15vU44IQzINwHOprfZgRt2', null, '<EMAIL>', null, '2017-02-11 14:09:08', '2017-02-11 14:09:08'); -- ---------------------------- -- Table structure for user_role -- ---------------------------- DROP TABLE IF EXISTS `user_role`; CREATE TABLE `user_role` ( `user_id` int(11) NOT NULL, `role_id` int(11) NOT NULL, PRIMARY KEY (`user_id`,`role_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user_role -- ---------------------------- SET FOREIGN_KEY_CHECKS=1; <file_sep><?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class ClassTraining extends Model { protected $table = 'class_training'; public $timestamps = false; // public $guarded = ['id']; protected $fillable = ['class_id', 'training_id', 'sid']; function hasoneToTraining(){ return $this->hasOne(Trainings::class, 'id', 'training_id'); } } <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta charset="utf-8" /> <title><?php echo e(config('app.name')); ?></title> <meta name="description" content="User login page" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> <link rel="stylesheet" href="<?php echo e(URL::asset('assets/css/bootstrap.css')); ?>" /> <link rel="stylesheet" href="<?php echo e(URL::asset('components/font-awesome/css/font-awesome.css')); ?>" /> <link rel="stylesheet" href="<?php echo e(URL::asset('assets/css/ace-fonts.css')); ?>" /> <link rel="stylesheet" href="<?php echo e(URL::asset('assets/css/ace.css')); ?>" /> <!--[if lte IE 9]> <link rel="stylesheet" href="<?php echo e(URL::asset('assets/css/ace-part2.css')); ?>" /> <![endif]--> <link rel="stylesheet" href="<?php echo e(URL::asset('assets/css/ace-rtl.css')); ?>" /> <!--[if lte IE 9]> <link rel="stylesheet" href="<?php echo e(URL::asset('assets/css/ace-ie.css')); ?>" /> <![endif]--> <!--[if lte IE 8]> <script src="<?php echo e(URL::asset('components/html5shiv/dist/html5shiv.min.js')); ?>"></script> <script src="<?php echo e(URL::asset('components/respond/dest/respond.min.js')); ?>"></script> <![endif]--> </head> <body class="login-layout light-login"> <div class="main-container"> <div class="main-content"> <div class="row"> <?php echo $__env->yieldContent('content'); ?> </div> </div> </div> <!--[if !IE]> --> <script src="<?php echo e(URL::asset('components/jquery/dist/jquery.js')); ?>"></script> <!-- <![endif]--> <!--[if IE]> <script src="<?php echo e(URL::asset('components/jquery.1x/dist/jquery.js')); ?>"></script> <![endif]--> <script type="text/javascript"> if('ontouchstart' in document.documentElement) document.write("<script src='../components/_mod/jquery.mobile.custom/jquery.mobile.custom.js'>"+"<"+"/script>"); </script> <!-- inline scripts related to this page --> <script type="text/javascript"> jQuery(function($) { $(document).on('click', '.toolbar a[data-target]', function(e) { e.preventDefault(); var target = $(this).data('target'); $('.widget-box.visible').removeClass('visible');//hide others $(target).addClass('visible');//show target }); }); //you don't need this, just used for changing background jQuery(function($) { $('#btn-login-dark').on('click', function(e) { $('body').attr('class', 'login-layout'); $('#id-text2').attr('class', 'white'); $('#id-company-text').attr('class', 'blue'); e.preventDefault(); }); $('#btn-login-light').on('click', function(e) { $('body').attr('class', 'login-layout light-login'); $('#id-text2').attr('class', 'grey'); $('#id-company-text').attr('class', 'blue'); e.preventDefault(); }); $('#btn-login-blur').on('click', function(e) { $('body').attr('class', 'login-layout blur-login'); $('#id-text2').attr('class', 'white'); $('#id-company-text').attr('class', 'light-blue'); e.preventDefault(); }); }); </script> </body> </html> <file_sep><?php namespace App\Http\Controllers; class SystemController extends Controller { public function index() { $data['category'] = 'member'; $data['subCategory'] = 'memberlist'; return view('system.index', $data); } } <file_sep><?php $table_index = isset($index) ? $index : 1; ?> <button class="btn btn-primary btn-sm list_edit_<?php echo e($table_index); ?>"> <i class="ace-icon fa fa-pencil align-top bigger-125"></i> 编辑 </button> <script> // 编辑角色 $('.list_edit_<?php echo e($table_index); ?>').on('click', function(){ var row_id=$("#jqgrid-table-<?php echo e($table_index); ?>").jqGrid('getGridParam','selrow'); if( row_id == undefined ){ show_msg(false, '请选择要编辑的数据'); return false; } var rowData=$("#jqgrid-table-<?php echo e($table_index); ?>").getRowData(row_id); <?php echo $parms; ?> $('#<?php echo e($modal_target); ?>').modal({ keyboard: true }); }) </script><file_sep><div id="sidebar" class="sidebar responsive ace-save-state" data-sidebar="true" data-sidebar-scroll="true" data-sidebar-hover="true"> <script type="text/javascript"> try{ace.settings.loadState('sidebar')}catch(e){} </script> <div class="sidebar-shortcuts" id="sidebar-shortcuts"> <div class="sidebar-shortcuts-large" id="sidebar-shortcuts-large"> <button class="btn btn-success"> <i class="ace-icon fa fa-signal"></i> </button> <button class="btn btn-info"> <i class="ace-icon fa fa-pencil"></i> </button> <!-- #section:basics/sidebar.layout.shortcuts --> <button class="btn btn-warning"> <i class="ace-icon fa fa-users"></i> </button> <button class="btn btn-danger"> <i class="ace-icon fa fa-cogs"></i> </button> <!-- /section:basics/sidebar.layout.shortcuts --> </div> <div class="sidebar-shortcuts-mini" id="sidebar-shortcuts-mini"> <span class="btn btn-success"></span> <span class="btn btn-info"></span> <span class="btn btn-warning"></span> <span class="btn btn-danger"></span> </div> </div><!-- /.sidebar-shortcuts --> <ul class="nav nav-list" style="top: 0px;"> <li class="<?php if($category == 'home'): ?> active <?php endif; ?>"> <a href="<?php echo e(URL::route('home')); ?>"> <i class="menu-icon fa fa-home"></i> <span class="menu-text"> 系统主页 </span> </a> <b class="arrow"></b> </li> <li class="<?php if($category == 'training'): ?> active open <?php endif; ?>"> <a href="#" class="dropdown-toggle"> <i class="menu-icon fa fa-signal"></i> <span class="menu-text"> 培训管理 </span> <b class="arrow fa fa-angle-down"></b> </a> <b class="arrow"></b> <ul class="submenu"> <li class="<?php if($subCategory == 'trainings'): ?> active <?php endif; ?>"> <a href="<?php echo e(URL::route('trainings.index')); ?>"> <i class="menu-icon fa fa-caret-right"></i> 培训课程 </a> <b class="arrow"></b> </li> </ul> <ul class="submenu"> <li class="<?php if($subCategory == 'classes'): ?> active <?php endif; ?>"> <a href="<?php echo e(URL::route('classes.index')); ?>"> <i class="menu-icon fa fa-caret-right"></i> 班级列表 </a> <b class="arrow"></b> </li> </ul> <ul class="submenu"> <li class="<?php if($subCategory == 'students'): ?> active <?php endif; ?>"> <a href="<?php echo e(URL::route('students.index')); ?>"> <i class="menu-icon fa fa-caret-right"></i> 学生列表 </a> <b class="arrow"></b> </li> </ul> </li> <li class="<?php if($category == 'reports'): ?> active open <?php endif; ?>"> <a href="#" class="dropdown-toggle"> <i class="menu-icon fa fa-bar-chart-o"></i> <span class="menu-text"> 报表管理</span> <b class="arrow fa fa-angle-down"></b> </a> <b class="arrow"></b> <ul class="submenu"> <li class="<?php if($subCategory == 'printAdmission'): ?> active <?php endif; ?>"> <a href="<?php echo e(URL::route('printAdmission.index')); ?>"> <i class="menu-icon fa fa-caret-right"></i> 打印统计 </a> <b class="arrow"></b> </li> </ul> </li> <li class="<?php if($category == 'base'): ?> active open <?php endif; ?>"> <a href="#" class="dropdown-toggle"> <i class="menu-icon fa fa-cog"></i> <span class="menu-text"> 基础管理 </span> <b class="arrow fa fa-angle-down"></b> </a> <b class="arrow"></b> <ul class="submenu"> <li class="<?php if($subCategory == 'user'): ?> active <?php endif; ?>"> <a href="<?php echo e(URL::route('user.index')); ?>"> <i class="menu-icon fa fa-caret-right"></i> 用户管理 </a> <b class="arrow"></b> </li> </ul> </li> </ul><!-- /.nav-list --> <!-- #section:basics/sidebar.layout.minimize --> <div class="sidebar-toggle sidebar-collapse" id="sidebar-collapse"> <i id="sidebar-toggle-icon" class="ace-icon fa fa-angle-double-left ace-save-state" data-icon1="ace-icon fa fa-angle-double-left" data-icon2="ace-icon fa fa-angle-double-right"></i> </div> <!-- /section:basics/sidebar.layout.minimize --> </div> <file_sep><div id="navbar" class="navbar navbar-default ace-save-state"> <div class="navbar-container ace-save-state" id="navbar-container"> <button type="button" class="navbar-toggle menu-toggler pull-left" id="menu-toggler" data-target="#sidebar"> <span class="sr-only">Toggle sidebar</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div class="navbar-header pull-left"> <!-- #section:basics/navbar.layout.brand --> <a href="#" class="navbar-brand"> <small> <i class="fa fa-leaf"></i> <?php echo e(config('app.name')); ?> </small> </a> </div> <div class="navbar-buttons navbar-header pull-right" role="navigation"> <ul class="nav ace-nav"> <li class="purple dropdown-modal"> <a data-toggle="dropdown" class="dropdown-toggle" href="#" aria-expanded="false"> <i class="ace-icon fa fa-bell"></i> <!-- <span class="badge badge-important">0</span> --> </a> <!-- <ul class="dropdown-menu-right dropdown-navbar navbar-pink dropdown-menu dropdown-caret dropdown-close"> <li class="dropdown-header"> <i class="ace-icon fa fa-exclamation-triangle"></i> 8 Notifications </li> <li class="dropdown-content ace-scroll" style="position: relative;"><div class="scroll-track" style="display: none;"><div class="scroll-bar"></div></div><div class="scroll-content" style=""> <ul class="dropdown-menu dropdown-navbar navbar-pink"> <li> <a href="#"> <div class="clearfix"> <span class="pull-left"> <i class="btn btn-xs no-hover btn-info fa fa-twitter"></i> Followers </span> <span class="pull-right badge badge-info">+11</span> </div> </a> </li> </ul> </div></li> <li class="dropdown-footer"> <a href="#"> See all notifications <i class="ace-icon fa fa-arrow-right"></i> </a> </li> </ul>--> </li> <li class="green dropdown-modal"> <a data-toggle="dropdown" class="dropdown-toggle" href="#" aria-expanded="true"> <i class="ace-icon fa fa-envelope"></i> <!-- <span class="badge badge-success">5</span>--> </a> <!-- <ul class="dropdown-menu-right dropdown-navbar dropdown-menu dropdown-caret dropdown-close" style="width: 320px; height: 292px; left: 514px; right: auto; top: 14px;"> <li class="dropdown-header"> <i class="ace-icon fa fa-envelope-o"></i> 5 Messages </li> <li class="dropdown-content ace-scroll" style="position: relative;"><div class="scroll-track scroll-active" style="display: block; height: 218px;"><div class="scroll-bar" style="height: 135px; top: 0px;"></div></div><div class="scroll-content" style="max-height: 218px;"> <ul class="dropdown-menu dropdown-navbar"> <li> <a href="#" class="clearfix"> <img src="../assets/avatars/avatar5.png" class="msg-photo" alt="Fred's Avatar"> <span class="msg-body"> <span class="msg-title"> <span class="blue">Fred:</span> Vestibulum id penatibus et auctor ... </span> <span class="msg-time"> <i class="ace-icon fa fa-clock-o"></i> <span>10:09 am</span> </span> </span> </a> </li> </ul> </div></li> <li class="dropdown-footer"> <a href="inbox.html"> See all messages <i class="ace-icon fa fa-arrow-right"></i> </a> </li> </ul>--> </li> <!-- #section:basics/navbar.user_menu --> <li class="light-blue dropdown-modal"> <a data-toggle="dropdown" href="#" class="dropdown-toggle" aria-expanded="false"> <img class="nav-user-photo" src="../assets/avatars/avatar4.png" alt="Jason's Photo"> <span class="user-info"> <small>Welcome,</small> <?php echo e(Auth::user()->name); ?> </span> <i class="ace-icon fa fa-caret-down"></i> </a> <ul class="user-menu dropdown-menu-right dropdown-menu dropdown-yellow dropdown-caret dropdown-close"> <!-- <li> <a href="<?php echo e(URL::route('sys.index')); ?>"> <i class="ace-icon fa fa-cog"></i> 系统设置 </a> </li>--> <li> <a href="javascript:void();" data-toggle="modal" data-target="#changepw"> <i class="ace-icon fa fa-user"></i> 修改密码 </a> </li> <li class="divider"></li> <li> <a href="<?php echo e(url('/logout')); ?>" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> <i class="ace-icon fa fa-power-off"></i> 退出系统 </a> <form id="logout-form" action="<?php echo e(url('/logout')); ?>" method="POST" style="display: none;"> <?php echo e(csrf_field()); ?> </form> </li> </ul> </li> </ul> </div> </div> </div> <div class="modal fade" role="dialog" id="changepw"> <div class="modal-dialog modal-lg" style="width:500px"> <div class="modal-content"> <form method="post" action="<?php echo e(URL::route('user.changepw')); ?>" role="form" class="form-horizontal"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title">修改密码</h4> </div> <div style="padding:20px;"> <?php echo e(csrf_field()); ?> <div class="form-group"> <label for="oldpasswd" class="col-sm-4 control-label">请输入当前密码</label> <div class="col-sm-8"> <input datatype="*" nullmsg="请输入当前密码" type="password" class="form-control" name="oldpasswd" id="oldpasswd"/> </div> </div> <div class="form-group"> <label for="newpasswd" class="col-sm-4 control-label">请输入新密码</label> <div class="col-sm-8"> <input datatype="*" nullmsg="请输入新密码" type="password" class="form-control" name="newpasswd" id="newpasswd"/> </div> </div> <div class="form-group"> <label for="newpasswd2" class="col-sm-4 control-label">请再输入一次</label> <div class="col-sm-8"> <input datatype="*" errormsg="您两次输入的账号密码不一致!" nullmsg="请再输入一次新密码" recheck="newpasswd" type="password" class="form-control" name="newpasswd2" id="newpasswd2"/> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-info btn_ok">确定</button> <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> </div> </form> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div> <script> $(function(){ $('#changeform .btn_ok').on('click', function(){ _validForm('#changepw form', null, _completeModal); }); }) function _completeModal(){ $('#changepw form .btn:last').click(); $('#changepw').find('form')[0].reset(); } </script><file_sep><?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class Article extends Model { protected $table = 'article'; public $timestamps = true; public $guarded = [ 'id' ]; public function user() { return $this->hasOne(Classes::User, 'id', 'user_id'); } } <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Classes; use App\Http\Model\ClassTraining; use App\Http\Model\Students; use App\Http\Model\StudentsPrint; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\URL; use Exception; use Maatwebsite\Excel\Facades\Excel; class StudentsController extends Controller { /* * 首页 */ public function index() { $data ['category'] = 'training'; $data ['subCategory'] = 'students'; $data ['breadcrumb'] = $this->breadcrumb(); return view('students.index', $data); } /* * 获取 */ function get(Request $request) { $input = $request->all(); $page = isset($input ['rows']) ? $input ['rows'] : env('PAGNATION'); $select = "id, code, name, phone,addr, exam_time, print_times"; if( isset($input['search']) && isset($input['level']) ){ if( $input['level'] == 1 ){ // 年查询 $yearsClass = Classes::select(DB::raw('id, year(begin_time) as y')) ->where('state', '1')->where(DB::raw('year(begin_time)'), $input['search'])->get(); $yearArr = []; foreach ($yearsClass as $year){ $yearArr[] = $year->id; } $list = Students::whereIn('class_id', $yearArr)->select(DB::raw($select))->paginate($page); }else if( $input['level'] == 2 ){ // 月查询 $yearArr = explode('-', $input['search']); $yearsClass = Classes::select(DB::raw('id, month(begin_time) as m')) ->where('state', '1')->where(DB::raw('year(begin_time)'), $yearArr[0])->where(DB::raw('month(begin_time)'), $yearArr[1])->get(); $monArr = []; foreach ($yearsClass as $year){ $monArr[] = $year->id; } $list = Students::whereIn('class_id', $monArr)->select(DB::raw($select))->paginate($page); }else{ $list = Students::where('class_id', $input['search'])->select(DB::raw($select))->paginate($page); } } else if(isset($input['user'])){ $con = '%'.$input['user'].'%'; $list = Students::where('name', 'like', $con) ->orWhere('id_no', 'like', $con)->select(DB::raw($select))->paginate($page); } else { $list = Students::select(DB::raw($select))->paginate($page); } // 设置打印次数按钮 foreach ($list as $k=>$row) { $event = 'ViewStudentPrint('.$row->id.')'; $print = '<button class="btn btn-info btn-xs" style="height:25px;" onclick="javascript:'.$event.'">'.$row->print_times.'</button>'; $list[$k]->print_times = $print; } $result = [ 'records' => $list->total(), 'total' => $list->lastPage(), 'rows' => $list->items() ]; return json_encode($result); } // 获取学生信息 function getInfo(Request $request){ $input = $request->all(); $stuInfo = Students::whereIn('id', $input['id'])->get(); $stuk = []; foreach ($stuInfo as $k=>$stu){ $stuInfo[$k]->repeat_time = date('Y年m月', strtotime($stu->hasoneToClass()->first()['repeat_time'])); $stuInfo[$k]->training_time = date('Y-m-d', strtotime($stu->training_time)); $stuInfo[$k]->begin_time = date('Y-m-d', strtotime($stu->hasoneToClass()->first()['begin_time'])); $stuInfo[$k]->end_time = date('Y-m-d', strtotime($stu->hasoneToClass()->first()['end_time'])); $training = ClassTraining::where('class_id', $stu->class_id)->orderBy('sid', 'asc')->get(); $str = ''; $i = 0; foreach ($training as $key=>$tran){ if( $i <6 ) { $tra = $tran->hasoneToTraining()->first(); if( $tra != null ){ $tra = $tra->toArray(); $str .= '<tr>'; $str .= '<td class="no">' . ($key + 1) . '</td>'; $str .= '<td class="klass">' . $tra['name']. '</td>'; $str .= '<td class="duration">' . floor($tra['duration']) . '</td>'; $str .= '</tr>'; } } $i++; } $stuk[$k] = $str; } $data['info'] = $stuInfo; $data['tran'] = $stuk; return backJson(true, $data); } // 保存打印记录 function addPrint(Request $request) { $input = $request->all(); DB::beginTransaction(); try { $list = Students::whereIn('id', $input['ids'])->get(); foreach($list as $i=>$row) { $print = [ 'student_id' => $row['id'], 'print_user' => Auth::user()->id, 'print_time' => date('Y-m-d H:i:s') ]; // 保存记录 if (!StudentsPrint::create($print)) { throw new \Exception('系统错误,保存打印记录出错!'); } // 保存次数 $count = $row['print_times'] + 1; if (!Students::where('id', $row['id'])->update(['print_times' => $count])) { throw new \Exception('系统错误,保存打印次数出错!'); } } DB::commit(); parent::_save_log('student', 'print', ''); return backJson(true, '打印成功!'); } catch (Exception $e) { DB::rollback(); return backJson(false, $e->getMessage()); } } // 获取打印信息 function getPrint(Request $request) { $input = $request->all(); $student = Students::where('id', $input['id'])->first(); $print = $student->hasManyToPrint()->get(); foreach ($print as $k=>$item) { $user = $item->hasOneToUser()->first(); $print[$k]->print_user = $user->name; } $result = [ 'rows' => $print, ]; return json_encode($result); } // 导入学生信息 function import(Request $request){ DB::beginTransaction(); try{ $input = Input::get(); if( !isset($input['class_id']) || empty($input['class_id']) ){ throw new Exception("请选择班级"); } $class_id = $input['class_id']; $stus = $request->file('Filedata'); $count = 0; // 文件是否上传成功 if ( $request->hasFile('Filedata') && $stus->isValid()) { // 获取文件相关信息 $originalName = $stus->getClientOriginalName(); // 文件原名 $ext = $stus->getClientOriginalExtension(); // 扩展名 $realPath = $stus->getRealPath(); //临时文件的绝对路径 $type = $stus->getClientMimeType(); // image/jpeg // 上传文件 $filename = 'stu_'.date('Y-m-d-H-i-s') . '.' . $ext; // 使用我们新建的uploads本地存储空间(目录) $bool = Storage::disk('public')->put($filename, file_get_contents($realPath)); if( $bool ){ $filePath = public_path().'/imports/'.$filename; Excel::load($filePath, function($reader) use($class_id, &$count){ $reader = $reader->getSheet(0); $res = $reader->toArray(); unset($res[0]); //array_pop($res); foreach ($res as $r){ $data = [ 'class_id' => $class_id, 'code' => $r[30], 'name' => $r[1], 'pinyin' => $r[0], 'gender' => $r[2], 'birthday' => $r[3], 'papers_id'=> $r[4], 'task_type'=> $r[5], 'id_no' => $r[6], 'project' => $r[7], 'category' => $r[8], 'education'=> $r[9], 'health' => $r[10], 'job' => $r[11], 'title' => $r[12], 'political'=> $r[13], 'profession_study'=> $r[14], 'profession_job' => $r[15], 'work_time' => $r[16], 'phone' => $r[17], 'company_type'=> $r[18], 'company' => $r[19], 'training_type'=> $r[21], 'training_time'=> $r[22], 'score_paper' => $r[23], 'score_paper_retry'=> $r[24], 'score_practical' => $r[25], 'score_practical_retry'=> $r[26], 'addr' => $r[27], 'exam_time' => $r[28], 'pass_time' => $r[29], 'des' => $r[20], ]; // 如果为空则忽略 if (empty($data['code']) && empty($data['name']) && empty($data['pinyin']) && empty($data['gender']) && empty($data['birthday']) && empty($data['papers_id']) && empty($data['task_type']) && empty($data['id_no']) && empty($data['project']) && empty($data['category']) && empty($data['education']) && empty($data['health']) && empty($data['job']) && empty($data['title']) && empty($data['political']) && empty($data['profession_study']) && empty($data['profession_job']) && empty($data['work_time']) && empty($data['phone']) && empty($data['company_type']) && empty($data['company']) && empty($data['training_type']) && empty($data['training_time']) && empty($data['score_paper']) && empty($data['score_paper_retry']) && empty($data['score_practical']) && empty($data['score_practical_retry']) && empty($data['addr']) && empty($data['exam_time']) && empty($data['pass_time']) && empty($data['des']) ) { continue; } // 判断学生是不是已经存在 if (Students::where([ ['id_no', '=', $r[6]], ['class_id', '=', $class_id] ])->count() > 0) { throw new Exception("本班级中,身份证号为 ".$r[6]." 的 ".$r[1]." 学员已存在,不允许重复导入!"); } if( !Students::insert( $data ) ){ throw new Exception("学生信息创建失败"); } $count ++; } }); }else{ throw new Exception("上传失败"); } }else{ throw new Exception("上传失败"); } DB::commit(); //parent::_save_log('student', 'import', $filename); echo backJson(true, '导入成功,共创建'.$count.'条学生信息'); } catch ( Exception $e ) { DB::rollback(); return backJson(false, $e->getMessage()); } } // 学生班级 function getClasses(){ $classesData = Classes::orderBy('sid', 'desc')->get(); $sub = []; foreach ($classesData as $cls){ $sub[] = [ 'id' => $cls->id, 'text' => $cls->name, 'type' => 'folder', ]; } return backJson(true, $sub); } // 保存考题 function saveTran(Request $request){ try { $input = $request->all(); if( !isset($input['exam_id']) || empty($input['exam_id']) ){ throw new \Exception("请选择考试"); } if( ExamQuestion::where('exam_id', $input['exam_id'])->count() > 0 ) { // if (!ExamQuestion::where('exam_id', $input['exam_id'])->delete()) { throw new \Exception("创建失败, 原题目删除失败"); } } $ExamQuestion = []; foreach ($input['question'] as $k=>$question){ $ExamQuestion[] = [ 'exam_id' => $input['exam_id'], 'question_id' => $question, 'sid' => $k ]; } if( !ExamQuestion::insert( $ExamQuestion ) ){ throw new \Exception("系统错误, 考试题目创建失败"); } return backJson(true, '考试题目设置成功'); } catch (\Exception $e) { return backJson(false, $e->getMessage()); } } /* * 添加和修改 */ function edit(Request $request) { try { $input = $request->all(); $data = [ 'name' => $input['name'], 'begin_time' => $input['begin_time'], 'end_time' => $input['end_time'], 'repeat_time' => $input['repeat_time'], 'state' =>$input['state'], 'sid' => $input['sid'], ]; $type = 'edit'; if (isset($input ['id']) && ! empty($input ['id'])) { Students::where('id', $input ['id'])->update($data); $_success_txt = '班级信息修改成功'; } else { if (! Students::create($data)) { throw new Exception("系统错误, 班级添加失败"); } $_success_txt = '班级添加成功'; $type = 'add'; } parent::_save_log('student', $type, $input['name']); return backJson(true, $_success_txt); } catch ( Exception $e ) { return backJson(false, $e->getMessage()); } } /* * 删除学生 */ function delete(Request $req) { DB::beginTransaction(); try { if (! isset($req->ids) || empty($req->ids)) { throw new Exception("请选择要删除的学生"); } $stuNames = ''; foreach ($req->ids as $ids){ $stu = Students::where('id', $ids)->first(); $stuNames .= $stu['name'].','; } // 删除打印记录 StudentsPrint::whereIn('student_id', $req->ids)->delete(); // 删除学生信息 if (! Students::whereIn('id', $req->ids)->delete()) { throw new Exception("系统错误, 删除学生失败"); } DB::commit(); parent::_save_log('student', 'del', $stuNames); return backJson(true, '删除学生成功'); } catch ( Exception $e ) { DB::rollback(); return backJson(false, $e->getMessage()); } } /* * 页面路径 */ private function breadcrumb() { return [ [ 'url' => URL::route('students.index'), 'title'=> '学生列表' ] ]; } }<file_sep><?php namespace App\Http\Model; use Zizaco\Entrust\EntrustRole; class RoleModule extends EntrustRole { protected $table = 'role_module'; public $timestamps = false; protected $fillable = ['role_id', 'module_id']; } <file_sep><?php namespace App\Http\Model; use Zizaco\Entrust\EntrustPermission; class Permission extends EntrustPermission { }<file_sep><?php Route::get('/', ['uses'=>'IndexController@index', 'as'=>'index']); // 首页 Route::get('/lists/{category_id}', ['uses'=>'IndexController@articleList', 'as'=>'list']); // 列表 Route::get('/details/{article_id}', ['uses'=>'IndexController@articleDetails', 'as'=>'details']); // 详情 Route::get('/notready', ['uses'=>'IndexController@notready', 'as'=>'notready']); // 正在建设中 Auth::routes(); Route::get('/zhengjian', ['uses'=>'IndexController@zhengjian', 'as'=>'zhengjian']); Route::post('/zhengjian/search', ['uses'=>'IndexController@search', 'as'=>'zhengjian.search']); Route::post('/upload', ['uses'=>'UploadController@doUpload', 'as'=>'upload']); // 考试 Route::get('/examine/login', ['uses'=>'ExamineController@login', 'as'=>'examine.login']); Route::post('/examine/dologin', ['uses'=>'ExamineController@doLogin', 'as'=>'examine.login.do']); Route::group(['middleware'=>['web', 'stu.login']], function(){ Route::get('/examine/index/{type}', ['uses'=>'ExamineController@index', 'as'=>'examine']); Route::post('/examine/save/{type}', ['uses'=>'ExamineController@save', 'as'=>'examine.save']); Route::post('/examine/get/test', ['uses'=>'ExamineController@getTest', 'as'=>'examine.get.test']); }); Route::get('/examine/f/{paper_id}/{type}', ['uses'=>'ExamineController@finish', 'as'=>'examine.finish']); Route::group(['middleware'=>['web', 'menu', 'auth']], function(){ Route::get('/home', ['uses'=>'HomeController@index', 'as'=>'home']); // 新闻管理 Route::get('/article/index', ['uses'=>'ArticleController@index', 'as'=>'article.index']); // 新闻列表 Route::post('/article/get', ['uses'=>'ArticleController@getArticles', 'as'=>'article.get']); // 获取新闻列表 Route::post('/article/add', ['uses'=>'ArticleController@add', 'as'=>'article.add']); // 添加新闻页面 Route::post('/article/get/category', ['uses'=>'ArticleController@getCategory', 'as'=>'article.get.category']); // 获取新闻分类 Route::post('/article/delete', ['uses'=>'ArticleController@delete', 'as'=>'article.delete']); // 删除新闻方法 Route::post('/article/getContent', ['uses'=>'ArticleController@getContent', 'as'=>'article.get.content']); // 获取新闻的内容 Route::get('/article/category', ['uses'=>'ArticleCategoryController@index', 'as'=>'category.index']); // 新闻分类列表 Route::post('/article/category/get', ['uses'=>'ArticleCategoryController@getCategory', 'as'=>'category.get']); // 获取新闻分了你列表 Route::post('/article/category/getone', ['uses'=>'ArticleCategoryController@getOne', 'as'=>'category.get.one']); // 获取新闻列表 Route::post('/article/category/add', ['uses'=>'ArticleCategoryController@addCategory', 'as'=>'category.add']); // 添加新闻分类页面 Route::post('/article/category/delete', ['uses'=>'ArticleCategoryController@deleteCategory', 'as'=>'category.delete']); // 删除新闻分类方法 Route::post('/article/category/savesort', ['uses'=>'ArticleCategoryController@saveSort', 'as'=>'category.save.sort']);// 获取所有的模块 Route::get('/slider/index', ['uses'=>'SliderController@index', 'as'=>'slider.index']);// 首页幻灯片 Route::post('/slider/get', ['uses'=>'SliderController@getSlider', 'as'=>'slider.get']); // 获取幻灯片列表 Route::post('/slider/add', ['uses'=>'SliderController@addSlider', 'as'=>'slider.add']); // 添加幻灯片 Route::post('/slider/savesort', ['uses'=>'SliderController@saveSort', 'as'=>'slider.save.sort']);// 保存幻灯片排序 Route::post('/slider/delete', ['uses'=>'SliderController@delete', 'as'=>'slider.delete']); // 删除幻灯片 Route::post('/slider/getone', ['uses'=>'SliderController@getOne', 'as'=>'slider.get.one']); // 获取单个幻灯片信息 // 题目管理 // 题库 Route::get('/question/index', ['uses'=>'QuestionController@index', 'as'=>'question.index']); // 题目列表 Route::post('/question/get', ['uses'=>'QuestionController@get', 'as'=>'question.get']); // 获取题目列表 Route::get('/question/add', ['uses'=>'QuestionController@add', 'as'=>'question.add']); // 题目添加页 Route::post('/question/add/do', ['uses'=>'QuestionController@doAdd', 'as'=>'question.add.do']); // 添加题目处理方法 Route::post('/question/delete', ['uses'=>'QuestionController@delete', 'as'=>'question.delete']); // 题目删除方法 Route::post('/question/get/subject', ['uses'=>'QuestionController@getSubject', 'as'=>'question.get.subject']); // 题目获取科目 Route::post('/question/import', ['uses'=>'QuestionController@import', 'as'=>'question.import']); // 导入题目 // 考卷 Route::get('/exam/index', ['uses'=>'ExamController@index', 'as'=>'exam.index']); // 考卷 Route::post('/exam/get', ['uses'=>'ExamController@get', 'as'=>'exam.get']); // 考卷列表 Route::post('/exam/delete', ['uses'=>'ExamController@delete', 'as'=>'exam.delete']); // 考卷删除 Route::post('/exam/get/question', ['uses'=>'ExamController@getQuestion', 'as'=>'exam.get.question']); // 获取考卷题目 Route::post('/exam/save', ['uses'=>'ExamController@doSave', 'as'=>'exam.save']); // 保存考卷信息 Route::post('/exam/save/pcode', ['uses'=>'ExamController@doSavePCode', 'as'=>'exam.save.pcode']); // 保存考卷信息练习号 Route::post('/exam/get/info', ['uses'=>'ExamController@getExamInfo', 'as'=>'exam.get.info']); // 获取考卷信息 Route::post('/exam/set/question', ['uses'=>'ExamController@setQuestion', 'as'=>'exam.set.question']); // 设置考题 Route::post('/exam/save/question', ['uses'=>'ExamController@saveQuestion', 'as'=>'exam.save.question']); // 保存考题 // 证书 Route::get('/certificate/index', ['uses'=>'CertificateController@index', 'as'=>'certificate.index']); //证书 Route::post('/certificate/edit', ['uses'=>'CertificateController@edit', 'as'=>'certificate.edit']); Route::post('/certificate/get', ['uses'=>'CertificateController@get', 'as'=>'certificate.get']); Route::post('/certificate/import', ['uses'=>'CertificateController@import', 'as'=>'certificate.import']); // 证书导入 Route::post('/certificate/delete', ['uses'=>'CertificateController@delete', 'as' =>'certificate.delete']); // 证书删除 // 考试 Route::get('/examination/index', ['uses'=>'ExaminationController@index', 'as'=>'examination.index']); // 考试 Route::post('/examination/get', ['uses'=>'ExaminationController@get', 'as'=>'examination.get']); // 考试 Route::post('/examination/edit', ['uses'=>'ExaminationController@edit', 'as'=>'examination.edit']); // 考试 Route::post('/examination/delete', ['uses'=>'ExaminationController@delete', 'as'=>'examination.delete']); // 考试 Route::post('/examination/get/years', ['uses'=>'ExaminationController@getYears', 'as'=>'examination.get.years']); // 获取年 // 考生 Route::get('/candidate/index', ['uses'=>'CandidateController@index', 'as'=>'candidate.index']); //考生列表 Route::post('/candidate/delete', ['uses'=>'CandidateController@delete', 'as'=>'candidate.delete']); // 删除考生 Route::post('/candidate/get', ['uses'=>'CandidateController@get', 'as'=>'candidate.get']); // 获取考生列表 Route::post('/candidate/import', ['uses'=>'CandidateController@import', 'as'=>'candidate.import']); // 考生导入 Route::post('/candidate/get/examination', ['uses'=>'CandidateController@getExamination', 'as'=>'candidate.get.examination']); // 考生关联考试 // 成绩查看 Route::get('/score/index',['uses'=>'ScoreController@index', 'as'=>'score.index']); // 成绩查询 Route::post('/score/get', ['uses'=>'ScoreController@get', 'as'=>'score.get']); // 成绩查询报表 Route::get('score/export', ['uses'=>'ScoreController@export', 'as'=>'score.export']); // 成绩导出 // 成绩评估 Route::get('/evaluation/index', ['uses'=>'EvaluationController@index', 'as'=>'evaluation.index']); // 首页 Route::post('/evaluation/get', ['uses'=>'EvaluationController@get', 'as'=>'evaluation.get']); // 获取数据 // 科目管理 Route::get('/subject/index', ['uses'=>'SubjectController@index', 'as'=>'subject.index']); // 科目列表 Route::post('/subject/get', ['uses'=>'SubjectController@getSubjectList', 'as'=>'subject.get']); // 获取科目列表 Route::post('/subject/add', ['uses'=>'SubjectController@add', 'as'=>'subject.add']); // 科目添加 Route::post('/subject/delete', ['uses'=>'SubjectController@delete', 'as'=>'subject.delete']); // 题目删除方法 // 课程列表 Route::get('/trainings/index', ['uses'=>'TrainingsController@index', 'as'=>'trainings.index']); //课程列表 Route::post('/trainings/get', ['uses'=>'TrainingsController@get', 'as'=>'trainings.get']); // 获取课程列表 Route::post('/trainings/edit', ['uses'=>'TrainingsController@edit','as'=>'trainings.edit']); // 修改课程 Route::post('/trainings/delete', ['uses'=>'TrainingsController@delete', 'as'=>'trainings.delete']); // 删除课程 // 班级列表 Route::get('/classes/index', ['uses'=>'ClassesController@index', 'as'=>'classes.index']); //课程列表 Route::post('/classes/get', ['uses'=>'ClassesController@get', 'as'=>'classes.get']); // 获取课程列表 Route::post('/classes/edit', ['uses'=>'ClassesController@edit','as'=>'classes.edit']); // 修改课程 Route::post('/classes/delete', ['uses'=>'ClassesController@delete', 'as'=>'classes.delete']); // 删除课程 Route::post('/classes/set/trainings', ['uses'=>'ClassesController@setTrainings', 'as'=>'classes.set.trainings']); // 设置考题 Route::post('/classes/get/trainings', ['uses'=>'ClassesController@getTrainings', 'as'=>'classes.get.trainings']); // 设置考题 Route::post('/classes/get/years', ['uses'=>'ClassesController@getYears', 'as'=>'classes.get.years']); // 获取年 // 学生列表 Route::get('/students/index', ['uses'=>'StudentsController@index', 'as'=>'students.index']); //学生列表 Route::post('/students/get', ['uses'=>'StudentsController@get', 'as'=>'students.get']); // 获取学生列表 Route::post('/students/get/info', ['uses'=>'StudentsController@getInfo', 'as'=>'students.get.info']); // 获取学生信息 Route::post('/students/edit', ['uses'=>'StudentsController@edit','as'=>'students.edit']); // 修改学生 Route::post('/students/delete', ['uses'=>'StudentsController@delete', 'as'=>'students.delete']); // 删除学生 Route::post('/students/import', ['uses'=>'StudentsController@import', 'as'=>'students.import']); // 学生导入 Route::post('/students/get/classes', ['uses'=>'StudentsController@getClasses', 'as'=>'students.get.classes']); // 学生关联班级 Route::post('/students/add/print', ['uses'=>'StudentsController@addPrint', 'as'=>'students.add.print']); // 打印记录保存 Route::post('/students/get/print', ['uses'=>'StudentsController@getPrint', 'as'=>'students.get.print']); // 打印记录查询 // 报表 Route::get('/printAdmission/index', ['uses'=>'PrintAdmissionController@index', 'as'=>'printAdmission.index']); // 打印报表 Route::post('/printAdmission/get', ['uses'=>'PrintAdmissionController@get', 'as'=>'printAdmission.get']); // 获取打印列表 Route::get('/scoreAvg/index', ['uses'=>'ScoreAvgController@index', 'as'=>'scoreAvg.index']); // 成绩分布 Route::post('/scoreAvg/get/{exam_id}', ['uses'=>'ScoreAvgController@get', 'as'=>'scoreAvg.get']); // 成绩获取 Route::post('/scoreAvg/getExam', ['uses'=>'ScoreAvgController@getExam', 'as'=>'scoreAvg.getexam']); // 成绩获取 // 系统设置 Route::get('/settings/index', ['uses'=>'SettingsController@index', 'as'=>'settings.index']); // 系统设置首页 Route::post('/settings/save', ['uses'=>'SettingsController@save', 'as'=>'settings.save']); // 保存系统参数 // 用户管理 Route::get('/user/index', ['uses'=>'UserController@index', 'as'=>'user.index']); // 用户管理首页 Route::post('/user/get', ['uses'=>'UserController@get', 'as'=>'user.get']); // 获取用户列表 Route::post('/user/edit', ['uses'=>'UserController@edit', 'as'=>'user.edit']); // 添加用户 Route::post('/user/delete', ['uses'=>'UserController@delete', 'as'=>'user.delete']); // 删除用户 Route::post('/user/permission', ['uses'=>'UserController@permission', 'as'=>'user.permission']); // 用户权限 Route::post('user/changepw', ['uses'=>'UserController@changepw', 'as'=>'user.changepw']); // 角色权限 Route::get('/role/index', ['uses'=>'RoleController@index', 'as'=>'role.index']); // 角色用户首页 Route::post('/role/get', ['uses'=>'RoleController@get', 'as'=>'role.get']); // 获取用户角色 Route::post('/role/edit', ['uses'=>'RoleController@edit', 'as'=>'role.edit']); // 添加角色 Route::post('/role/delete', ['uses'=>'RoleController@delete', 'as'=>'role.delete']); // 删除角色 Route::post('/role/permission', ['uses'=>'RoleController@permission', 'as'=>'role.permission']); // 角色关联模块 Route::post('/role/getList', ['uses'=>'RoleController@getList', 'as'=>'role.get.list']); // 角色关联模块 // 模块管理 Route::get('/module/index', ['uses'=>'ModuleController@index', 'as'=>'module.index']); // 模块管理首页 Route::post('/module/get', ['uses'=>'ModuleController@get', 'as'=>'module.get']); // 获取模块 Route::post('/module/save', ['uses'=>'ModuleController@doSave', 'as'=>'module.save']); // 添加模块 Route::post('/module/delete', ['uses'=>'ModuleController@delete', 'as'=>'module.delete']);// 删除模块 Route::post('/module/get/one', ['uses'=>'ModuleController@getOne', 'as'=>'module.get.one']);// 获取某一个模块的信息 Route::post('/module/get/list', ['uses'=>'ModuleController@getList', 'as'=>'module.get.list']);// 获取所有的模块 Route::post('/module/save/sort', ['uses'=>'ModuleController@saveSort', 'as'=>'module.save.sort']);// 获取所有的模块 Route::get('/base/logs', ['uses'=>'LogController@index', 'as'=>'base.log']);// 日志模块 Route::post('/base/logs/get', ['uses'=>'LogController@get', 'as'=>'base.log.get']); // 获取日志内容 Route::post('/base/logs/delete', ['uses'=>'LogController@delete', 'as'=>'base.log.delete']); // 删除日志 });<file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Answer; use App\Http\Model\Candidate; use App\Http\Model\Exam; use App\Http\Model\ExamEval; use App\Http\Model\Examination; use App\Http\Model\ExamQuestion; use App\Http\Model\ExamQuestionType; use App\Http\Model\Member; use App\Http\Model\Paper; use App\Http\Model\PaperQuestion; use App\Http\Model\Question; use App\Http\Model\Settings; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\URL; use Jenssegers\Agent\Agent; class ExamineController extends WebController { /* * 登录页面 */ function login(){ $ip = get_client_ip(); $isAllow = Settings::get(); $ips = []; if( $isAllow->count() > 0 ){ foreach ($isAllow as $alow){ $alip = explode( "\r\n", trim($alow->val) ); $ips[] = $alip; } } $is = []; foreach ($ips as $ipsArr){ foreach ($ipsArr as $isArr) { $is[] = $isArr; } } $data['is_allow'] = false; if( in_array($ip, $is) || in_array('*', $is) ){ $data['is_allow'] = true; } $agent = new Agent(); $data['page_class'] = $agent->isMobile() || $agent->isTablet() ? 'mobile_page' : 'web_page'; return view('examine.login', $data); } /* * 登录方法 */ function doLogin(Request $request){ try{ $input = $request->all(); if( !isset($input['code']) || !isset($input['exam_code']) ){ throw new \Exception("考试登录信息填写错误"); } // 检测是否正式考试、记分练习、不记分练习 $sess_key = null; $examInfo = Examination::where('code', $input['exam_code'])->orWhere('t_code', $input['exam_code'])->first(); if( $examInfo != null ) { // 正式考试和记分练习需要验证准考证号 $candidate = Candidate::where('code', $input['code'])->where('examination_id', $examInfo->id)->first(); if( $candidate == null ){ throw new \Exception("输入的准考证号有误,请重试"); } $examination = $examInfo->toArray(); if( $examination['code'] == $input['exam_code'] ){ $type = 1; // 正式考试 // 判断是不是补考 $paperData = Paper::where('examination_id', $examination['id'])->where('student_id', $candidate->id)->get()->toArray(); $existsPaper = []; if( !empty($paperData) ) { foreach ($paperData as $pd) { $existsPaper['type_'.$pd['type']] = $pd; } } $examData = Exam::where('id', $examination['exam_id'])->first(); if( ( strtotime($examInfo->begin_time) + $examData->duration * 60 ) < time() && ( strtotime($examInfo->retry_time) + $examData->duration * 60 ) > time() && !isset($existsPaper['type_4']) ){ // 已考过 // 如果没有考试 或者 考试分数低于及格线 if( !isset($existsPaper['type_1']) || ( isset($existsPaper['type_1']) && $examData->score_pass > $existsPaper['type_1']['score'] ) ){ $type = 4; // 补考 } } }else if( $examination['t_code'] == $input['exam_code'] ){ $type = 2; // 记分练习 } $candidateInfo['exam'] = $examination; $candidateInfo['candidate'] = $candidate->toArray(); // 正式考试和记录练习,记录学生信息 }else{ $examData = Exam::where('p_code', $input['exam_code'])->first(); if( $examData != null ) { $type = 3; // 不记分练习 $candidateInfo['exam'] = $examData->toArray(); $candidateInfo['candidate']['id'] = time(); }else{ throw new \Exception("输入的考试号/练习号/模拟号有误,请重试!"); } } // 考试IP判断 $ip = get_client_ip(); if( $type == 1 || $type == 4 ){ $zhengshi = Settings::where('key', 'ksip')->first(); $alip = explode( "\r\n", trim($zhengshi->val) ); if( $zhengshi != null && !in_array($ip, $alip) && !in_array('*', $alip) ){ throw new \Exception("您的IP不允许参加正式考试!"); } }else if( $type == 2 ){ $zhengshi = Settings::where('key', 'jflxip')->first(); $alip = explode( "\r\n", trim($zhengshi->val) ); if( $zhengshi != null && !in_array($ip, $alip) && !in_array('*', $alip) ){ throw new \Exception("您的IP不允许参加计分练习考试!"); } }else if( $type == 3 ){ $zhengshi = Settings::where('key', 'bjflxip')->first(); $alip = explode( "\r\n", trim($zhengshi->val) ); if( $zhengshi != null && !in_array($ip, $alip) && !in_array('*', $alip) ){ throw new \Exception("您的IP不允许参加练习考试!"); } }else{ throw new \Exception("您的IP不允许考试!"); } $sess_key = 'time_'.$candidateInfo['exam']['id'].'_'.$candidateInfo['candidate']['id']; if( $request->session()->exists($sess_key) ){ $request->session()->forget($sess_key); } $request->session()->put('stu_info', $candidateInfo); return backJson(true, '登录成功', URL::route('examine', ['type'=>$type])); } catch (\Exception $e) { return backJson(false, $e->getMessage()); } } /* * 考试页面 */ public function index(Request $request, $type) { $stuData = $request->session()->get('stu_info'); if( $type == 3 ){ $exam_id = $stuData['exam']['id']; }else { $exam_id = $stuData['exam']['exam_id']; } // 检测是否参加过该考试 $examInfo = $this->getExamData($exam_id); $examInfo['kaoshi'] = $stuData['exam']['name']; $data = $this->_check_exam($request, $examInfo, $type); $data['examInfo'] = $examInfo; $data['exam_id'] = $exam_id; if( !$data['examInfo']['strategy'] ) { // 自动 $data['questions'] = $this->getExamQuestion($exam_id); }else{ $data['questions'] = $this->getAutoQuestion($exam_id); } $agent = new Agent(); $data['page_class'] = $agent->isMobile() || $agent->isTablet() ? 'mobile_page' : 'web_page'; // 记录考试时间 $sess_key = 'time_'.$stuData['exam']['id'].'_'.$stuData['candidate']['id']; if( $request->session()->exists($sess_key) ){ $data['exam_start'] = $request->session()->get($sess_key); }else{ $request->session()->put($sess_key, time()); $data['exam_start'] = time(); } $data['stuInfo'] = $stuData; $data['type'] = $type; return view('examine.index', $data); // 正常考试 } // 检查是否符合考试条件 function _check_exam(Request $request, $examInfo, $type){ $stuData = $request->session()->get('stu_info'); $stu_id = null; $data['stuExamType'] = 0; $data['stuExamError'] = ''; if( $type == 1 ){ // 正式考试 $stu_id = $stuData['candidate']['id']; $stuExamExists = Paper::where('student_id', $stu_id)->where('type', 1)->first(); $data['exam_start'] = strtotime($stuData['exam']['begin_time']); if( $stuExamExists != null ){ // 标记 已考过 // 获取及格线 if( empty($stuData['candidate']['pass_time']) && !empty($stuData['candidate']['score_paper_retry']) && !empty($stuData['candidate']['score_paper']) ){ $data['stuExamType'] = 3; $data['stuExamError'] = "您已经参加过该考试"; }else{ $data['stuExamType'] = 8; $data['stuExamError'] = "您已经通过该考试"; } }else if( $data['exam_start'] > time() ){ // 考试未开始 $data['stuExamType'] = 1; $data['stuExamError'] = "您的考试 “".$examInfo['kaoshi']."”, 暂未开始。"; }else if( ($data['exam_start'] + $examInfo['duration'] * 60) < time() ){ // 已过时 $data['stuExamType'] = 2; $data['stuExamError'] = "您的考试 “".$examInfo['kaoshi']."”, 考试时间已过。"; } }else if( $type == 4 ){ // 补考 $examination = $this->getExaminationData($stuData['exam']['id']); if( strtotime($examination->retry_time) > time() ){ // 已过时 $data['stuExamType'] = 6; $data['stuExamError'] = "您的补考 “".$examInfo['kaoshi']."”, 补考暂未开始。"; }else if( (strtotime($examination->retry_time) + $examInfo['duration'] * 60) < time() ){ // 已过时 $data['stuExamType'] = 7; $data['stuExamError'] = "您的补考 “".$examInfo['kaoshi']."”, 补考时间已过。"; } }else if( $type == 2 ){ // 带成绩的考试 次数检测 $stu_id = $stuData['candidate']['id']; $examination = $this->getExaminationData($stuData['exam']['id']); if( $examination == null ){ // 考试信息错误 $data['stuExamType'] = 4; $data['stuExamError'] = "考试信息错误"; }else { $stu_paper_count = Paper::where('student_id', $stu_id)->where('type', 2)->count(); if ($stu_paper_count >= $examination['t_times']) { // 超过测试次数 $data['stuExamType'] = 5; $data['stuExamError'] = "您的测试次数已满"; } } } return $data; } // 获取考试信息 function getExamData($exam_id = 0) { $examData = Exam::where('id', $exam_id)->first(); return $examData; } // 自动生成的题目 function getAutoQuestion($exam_id){ $examQues = ExamQuestionType::where('exam_id', $exam_id)->get(); $examQuesData = $testAns =[]; $count = 0; $examInfo = Exam::where('id', $exam_id)->first(); foreach ($examQues as $ques){ $questionData = Question::where('question_type_id', $ques['question_type'])->where('subject_id', $examInfo['subject_id'])->get(); if( $questionData->count() <= 0 ){ continue ; }else{ $questionData = $questionData->toArray(); } if( $ques['nums'] <= 0 ){ continue; } if( count($questionData) >= $ques['nums'] ){ $nums = $ques['nums']; }else{ $nums = count($questionData); } if( $nums == 1 ) { $questionRandData = [0]; }else{ $questionRandData = array_rand($questionData, $nums); shuffle($questionRandData); // 随机排序 } $questionArr = []; foreach ($questionRandData as $question) { $quesRandData = $questionData[$question]; $answer = Answer::where('question_id', $quesRandData['id'])->get(); $questionArr[] = [ 'exam_id' => $exam_id, 'id' => $quesRandData['id'], 'name' => $quesRandData['name'], 'type' => $ques['question_type'], 'ques' => $answer, ]; $testAns[] = $this->checkAnswer($exam_id, $quesRandData['id']); $count ++; } $examQuestionType = ExamQuestionType::where('exam_id', $exam_id)->where('question_type', $ques['question_type'])->first(); $examQuesData[$ques['question_type']]['score'] = $examQuestionType; $examQuesData[$ques['question_type']]['question'] = $questionArr; } return ['total' => $count, 'data' => $examQuesData, 'testAns'=>$testAns]; } // 获取考试题目 function getExamQuestion($exam_id = 0) { $question = ExamQuestion::where('exam_id', $exam_id)->orderBy('sid', 'asc')->get(); $examQuestionData = $data = $testAns = $qt = $quesCount = []; $count = 0; $examQuestionType = ExamQuestionType::where('exam_id', $exam_id)->get(); if( $examQuestionType->count() > 0 ){ $examQuestionType = $examQuestionType->toArray(); foreach( $examQuestionType as $qtype ){ $qt[$qtype['question_type']] = $qtype; } } foreach ($question as $k=>$ques) { $questionData = $ques->hasoneToQuestion()->first(); if( $qt[$questionData->question_type_id]['nums'] == 0 ){ continue; } if( isset($quesCount[$questionData->question_type_id]) && count($quesCount[$questionData->question_type_id]) >= $qt[$questionData->question_type_id]['nums'] ){ continue ; } $answer = Answer::where('question_id', $questionData->id)->get(); $examQuestionData[] = [ 'exam_id' => $exam_id, 'id' => $questionData->id, 'name' => $questionData->name, 'type' => $questionData->question_type_id, 'ques' => $answer ]; $quesCount[$questionData->question_type_id][] = $examQuestionData; $count ++; $testAns[] = $this->checkAnswer($exam_id, $questionData->id); } foreach ($examQuestionData as $examQues) { if( isset( $qt[$examQues['type']] ) ) { $data[$examQues['type']]['score'] = $qt[$examQues['type']]; }else{ $data[$examQues['type']]['score'] = 0; } $data[$examQues['type']]['question'][] = $examQues; } return ['total' => $count, 'data' => $data, 'testAns'=>$testAns]; } // 提交试卷 function save($type, Request $request) { DB::beginTransaction(); try { $input = $request->all(); $exam = []; $stu_info = $request->session()->get('stu_info'); $examation_id = $stu_info['exam']['id']; $exam_id = $stu_info['exam']['exam_id']; $stu_id = $stu_info['candidate']['id']; $sess_key = 'time_'.$stu_info['exam']['id'].'_'.$stu_info['candidate']['id']; $start_time = strtotime($stu_info['exam']['begin_time']); if( $request->session()->exists($sess_key) ){ $start_time = $request->session()->get($sess_key); // 考生开始考试时间 $request->session()->forget($sess_key); } if( $type == 1 ) { $stuExamExists = Paper::where('student_id', $stu_id)->where('examination_id', $examation_id)->where('type', 1)->first(); if ($stuExamExists != null) { // 考试已参加过判断 throw new \Exception("您已参加过该考试"); } }else if( $type == 2 ){ $stu_paper_count = Paper::where('student_id', $stu_id)->where('type', 2)->count(); $examination = $this->getExaminationData($stu_info['exam']['id']); if( $stu_paper_count >= $examination['t_times'] ){ // 超过测试次数 throw new \Exception("您的测试次数已满"); } } foreach ($input['data'] as $k=>$form) { preg_match_all("/(?:\[)(.*)(?:\])/i",$form[0], $result); $question_id = $result[1][0]; $exam[$question_id][] = $form[1]; } // 存储学生考试数据 $duration = time() - $start_time; $paper = [ 'examination_id' => $examation_id, 'student_id'=> $stu_info['candidate']['id'], 'dt' => date('Y-m-d H:i:s', $start_time), 'duration' => $duration, 'type' => $type, 'score' => 0, ]; if( !$paperData = Paper::create($paper)){ throw new \Exception("提交失败, 请重新提交"); } $i=1; $totalScore = 0; // 获取答案数组 foreach ($exam as $ques=>$ex) { $i++; $answer = $this->checkAnswer($exam_id, $ques); $ans = [ 'paper_id' => $paperData['id'], 'question_id' => $ques, 'answer_id' => $ex[0], 'score' => $answer['ans_id'] == $ex[0] ? $answer['score'] : 0, 'sid' => $i ]; $totalScore += $ans['score']; if( !PaperQuestion::create($ans)){ throw new \Exception("提交失败, 请重新提交"); } } // 存储考试成绩 补考成绩 if( $type == 1 ) { $examData = Exam::where('id', $exam_id)->first(); $examDataUp = [ 'score_paper' => $totalScore, // 总分 'exam_time' => date('Y-m-d H:i:s'), // 考试时间 'paper_id' => $paperData['id'], 'paper_time' => date('Y-m-d H:i:s'), 'paper_time_begin'=> date('Y-m-d H:i:s', $start_time), ]; if( $totalScore >= $examData->score_pass ){ // 考试通过时间 $examDataUp['pass_time'] = date('Y-m-d H:i:s'); } Candidate::where('id', $stu_info['candidate']['id'])->update( $examDataUp ); // 第一次考试成绩 }else if( $type == 2 ) { $countStu = Paper::where('examination_id', $examation_id)->where('student_id', $stu_info['candidate']['id'])->where('type', 2)->count(); if( $countStu <= 1 ){ $first = [ 'score_practical' => $totalScore, 'practical_id' => $paperData['id'], 'practical_time' => date('Y-m-d H:i:s'), 'practical_time_begin'=> date('Y-m-d H:i:s', $start_time), ]; Candidate::where('id', $stu_info['candidate']['id'])->update($first); // 第一次练习成绩 }else { $other = [ 'score_practical_retry' => $totalScore, 'practical_retry_id' => $paperData['id'], 'practical_retry_time' => date('Y-m-d H:i:s'), 'practical_retry_time_begin' => date('Y-m-d H:i:s', $start_time), ]; if ($totalScore > $stu_info['candidate']['score_practical_retry']) { Candidate::where('id', $stu_info['candidate']['id'])->update($other); // 第一次以后的练习成绩中的最高分 } } }else if( $type == 4 ) { $examData = Exam::where('id', $exam_id)->first(); $examDataUp['score_paper_retry'] = $totalScore; $examDataUp['paper_retry_id'] = $paperData['id']; $examDataUp['paper_retry_time'] = date('Y-m-d H:i:s'); $examDataUp['paper_retry_time_begin']= date('Y-m-d H:i:s', $start_time); if( $totalScore >= $examData->score_pass ){ $examDataUp['pass_time'] = date('Y-m-d H:i:s'); } Candidate::where('id', $stu_info['candidate']['id'])->update( $examDataUp );// 补考通过 } Paper::where('id', $paperData['id'])->update(['score'=>$totalScore]); DB::commit(); return backJson(true, '考试提交成功', URL::route('examine.finish', ['paper_id'=>$paperData['id'], 'type'=>$type])); } catch (\Exception $e) { DB::rollback(); return backJson(false, $e->getMessage()); } } //对比答案 function checkAnswer($exam_id, $question_id){ $answerData = Answer::where('question_id', $question_id)->get(); $q = []; foreach ($answerData as $ans){ if( $ans->answer_right ) { $q[$question_id]['ans_id'][] = $ans->id; $q[$question_id]['ans_label'][] = $ans->label; } } $data = []; foreach ($q as $k=>$ansArr){ $type = Question::where('id', $k)->first(); $scoreData = ExamQuestionType::where('question_type', $type->question_type_id)->where('exam_id', $exam_id)->first(); $data['question_id'] = $question_id; $data['ans_id'] = implode(',', $ansArr['ans_id']); $data['ans_label'] = implode(', ', $ansArr['ans_label']); $data['score'] = $scoreData->score; } return $data; } function finish(Request $request, $paper_id, $type){ $data['source'] = false; if( $request->source != null ){ $data['source'] = true; } $paper = Paper::where('id', $paper_id)->first(); $paperQuestion = $paper->hasOneToQuestion()->orderBy('sid', 'asc')->get(); $examination_id = $paper['examination_id']; $exam_info = Examination::where('id', $examination_id)->first(); $exam_id = $exam_info->exam_id; $data['kaoshi'] = $exam_info->name; $data['examInfo'] = $this->getExamData($exam_id); $agent = new Agent(); $data['page_class'] = $agent->isMobile() || $agent->isTablet() ? 'mobile_page' : 'web_page'; $totalRight = $totalScore = $total = 0; $questionType = ExamQuestionType::where('exam_id', $exam_id)->get()->toArray(); $qty = []; foreach ($questionType as $ty){ $qty[$ty['question_type']] = $ty['score']; } foreach ($paperQuestion as $ques){ // 用户答案 if( strpos($ques->answer_id, ',') > 0 ){ $userAnsArr = explode(',', $ques->answer_id); }else{ $userAnsArr = (array) $ques->answer_id; } $userAns = []; foreach($userAnsArr as $ansId){ if( $ansId != 0 ) { $UserAnswerData = Answer::where('id', $ansId)->first()->toArray(); $userAns[] = $UserAnswerData['label']; }else{ $userAns[] = ''; } } // 获取系统题目答案 $rightAns = $this->checkAnswer($exam_id, $ques->question_id); $questioData = Question::where('id', $ques->question_id)->first(); $answerArr = $questioData->hasManyToAnswer()->get()->toArray(); $questions[$questioData['question_type_id']][$ques->question_id] = [ 'exam_id' => $exam_id, 'title' => $questioData['name'], 'type_id' => $questioData['question_type_id'], 'user_ans_id' => $ques->answer_id, 'user_ans_label' => implode(', ', $userAns), 'answer_rigth_id' => $rightAns['ans_id'], 'answer_rigth_label' => $rightAns['ans_label'], 'score' => $ques->score, 'answer' => $answerArr ]; if( isset($qty[$questioData['question_type_id']]) ){ $questions[$questioData['question_type_id']][$ques->question_id]['sys_score'] = $qty[$questioData['question_type_id']]; } if( $ques->answer_id == $rightAns['ans_id'] ){ $totalRight ++; } // 获取正确答案 $totalScore += $ques->score; $total++; } // 获取评级 $examEval = ExamEval::where('exam_id', $exam_id)->where('min_score', '<=', $totalScore)->where('max_score', '>=', $totalScore)->first(); $userEval = $examEval == null ? '' : $examEval['name']; $data['userTotal'] = ['score'=>$totalScore, 'right'=>$totalRight, 'total'=>$total, 'eval'=>$userEval]; $data['questions'] = $questions; $data['type'] = $type; $stuData = Candidate::where('id', $paper->student_id)->first(); $data['stuInfo'] = $stuData; //dd($data); return view('examine.finish', $data); } // 不计分测试获取成绩 function getTest(Request $request){ try{ $input = $request->except('_token'); $exam_id = $input['exam_id']; $res = []; $right_totle = $all_totle = $right_score = $all_score = 0; if( !empty($input['data']) ){ foreach ($input['data'] as $k=>$question){ $checkAns = $this->checkAnswer($exam_id, $k); $checkAns['right'] = false; $all_totle += 1; $all_score += $checkAns['score']; if( $question == $checkAns['ans_id'] ){ $right_totle += 1; $right_score += $checkAns['score']; $checkAns['right'] = true; } $res['result'][] = $checkAns; } $res['right_totle'] = $right_totle; $res['all_totle'] = $all_totle; $res['right_score'] = $right_score; $res['all_score'] = $all_score; // 获取评级 $examEval = ExamEval::where('exam_id', $exam_id)->where('min_score', '<=', $right_score)->where('max_score', '>=', $right_score)->first(); $res['exam_val'] = $examEval == null ? '' : $examEval['name'];; } return backJson(true, $res); } catch (\Exception $e) { return backJson(false, $e->getMessage()); } } // 获取考试信息 private function getExaminationData($examination_id){ $examination = Examination::where('id', $examination_id)->where('state', 1)->first(); return $examination; } } <file_sep><?php namespace App\Http\Controllers; class Upload extends Controller { function doUpload(){ $file = Input::file("Filedata"); if($file->isValid()){ $userMd5 = md5(Auth::user()->id); $path = 'uploads/'.$userMd5.'/default/'; $realPath = public_path($path); // 绝对路劲 $extension = $file->getClientOriginalExtension(); // 后缀 $newName = date("YmdHis").mt_rand(100, 999).'.'.$extension; $pathUrl = $file -> move( $realPath, $newName ); $image_url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$path.$newName; $image_path = public_path($path.$newName); $handle = fopen(public_path($path.$newName), "r"); $fstat = fstat($handle); $imageSize = getimagesize($image_path); // 生成缩略图 $oimgSize = getimagesize($image_path); $thumbPath = 'uploads/'.$userMd5.'/default/thumb/'; if( !is_dir( $thumbPath ) ){ mkdir( $thumbPath, 0777, true ); } $img = Image::make($image_path)->resize($imageSize[0] * 0.1, $imageSize[1] * 0.1); $newImage = $thumbPath.$newName; $img->save($newImage); // 结束 $data = [ 'code' => true, 'url' => $image_url, 'filename' => basename($newImage), 'filesize' => round($fstat["size"]/1024,2).' KB', 'widthheight'=> "宽: {$imageSize[0]}px, 高: {$imageSize[1]}px", 'lasttime' => date("Y-m-d h:i:s",$fstat["mtime"]), ]; return Response::json($data); }else{ return Response::json(['code'=>false, 'msg'=>'文件上传失败']); } } }<file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Subject; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\URL; class SubjectController extends Controller { public function index() { $data['category'] = 'topic'; $data['subCategory'] = 'subject'; $data['breadcrumb'] = $this->breadcrumb(); return view('subject.index', $data); } /** * 获取用户列表数据 * @param Request $request * @return string */ function getSubjectList(Request $request){ $input = $request->all(); $page = isset( $input['rows'] ) ? $input['rows'] : env('PAGNATION'); $subjectList = Subject::where('state', '<>', 0)->paginate($page); foreach ($subjectList as $k=>$sub){ $subjectList[$k]['statetxt'] = $sub->state ? '正常' : '禁用'; } $subject = [ 'records' => $subjectList->total(), 'total'=> $subjectList->lastPage(), 'rows' => $subjectList->items() ]; return json_encode($subject); } // 添加科目 function add(Request $request){ try{ $input = $request->all(); $subjectData = [ 'name' => $input['name'], 'des' => $input['des'], 'state' => $input['state'], 'sid' => $input['sid'], ]; if( isset($input['id']) && !empty($input['id']) ){ if( !Subject::where('id', $input['id'])->update($subjectData) ){ throw new \Exception("系统错误, 科目信息修改失败"); } $_success_txt = '科目信息修改成功'; }else{ if( !Subject::create($subjectData) ){ throw new \Exception("系统错误, 科目添加失败"); } $_success_txt = '科目添加成功'; } return backJson(true, $_success_txt); } catch (\Exception $e){ return backJson(false, $e->getMessage()); } } // 删除科目 function delete(Request $request){ try{ $input = $request->all(); if( !isset($input['id']) || empty($input['id']) ){ throw new \Exception("请选择要删除的科目"); } if ( !Subject::where( 'id', $input['id'] )->delete() ){ throw new \Exception("系统错误, 科目删除失败"); } return backJson(true, '删除成功'); } catch (\Exception $e){ return backJson(false, $e->getMessage()); } } /** * 页面面包屑 * @return array */ private function breadcrumb(){ return [ [ 'url' => URL::route('subject.index'), 'title'=> '科目管理' ] ]; } } <file_sep><?php namespace App\Http\Middleware; use App\Http\Model\Module; use App\Http\Model\RoleModule; use App\Http\Model\UserRole; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; use Closure; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; class GetMenu { public function handle($request, Closure $next) { $request->attributes->set('comData_menu', $this->getMenu()); return $next($request); } function getMenu() { $user = Auth::user()->id; $userRole = UserRole::where('user_id', $user)->get(); if( $user == 1 ){ $module = Module::where('state', 1)->orderBy('sid', 'asc')->get()->toArray(); }else { if ($userRole->count() > 0) { $roleData = $roleModule = []; foreach ($userRole as $role) { $roleData[] = $role->hasManyToRole()->first()->toArray(); } foreach ($roleData as $role) { $roleModule[] = DB::table('role_module')->where('role_id', $role['id'])->get(); } $module = []; foreach ($roleModule as $role) { foreach ($role as $r) { $moduleData = Module::where('id', $r->module_id)->first()->toArray(); $module[] = $moduleData; } } } else { abort(404, '您没有权限访问, 请联系管理员设置权限'); } } return genTree($module); } } <file_sep><button class="btn btn-sm btn-purple btn_print"> <i class="ace-icon fa fa-print align-top bigger-125"></i> 打印再培训记录 </button> <div class="print_page" style="float:left"></div> <div class="print_item hide"> <style type="text/css"> .print_item { height: 207px; width: 638px; overflow: hidden; /* border: 1px red solid; */ padding: 8px 0px 0px 0px; } table { border-collapse: collapse; /* border: 1px yellow solid; */ font-size: 15px; font-family: "黑体", '微软雅黑'; table-layout: fixed; } table caption { height: 22px; } .main { height: 206px; } .left, .right { vertical-align: top; width: 300px; } .left { padding-left: 10px; } .blank { width: 20px; } .left td.no { text-align: center; font-size: 12px; width: 60px; line-height: 16px; border: 1px #ccc solid; } .left td.klass { text-align: left; font-size: 12px; width: 150px; line-height: 16px; border: 1px #ccc solid; } .left td.duration { text-align: center; font-size: 12px; width: 60px; line-height: 16px; border: 1px #ccc solid; } .left td.title { text-align: center; border: 1px #ccc solid; line-height: 16px; font-size: 14px; } .right td.title { font-size: 12px; width: 60px; vertical-align: top; line-height: 16px; } .right td.content { font-size: 12px; width: 220px; line-height: 16px; } .right td.sign { font-size: 12px; text-align: right; height: 30px; padding-right: 45px; } </style> <table class="main"> <tr> <td class="left"> <table> <caption aligh="center">&nbsp;培训课程&nbsp;</caption> <tr> <td class="title no">序号</td> <td class="title klass">课程名称</td> <td class="title duration">学时</td> </tr> <tbody class="lesson"></tbody> </table> <td> <td class="blank"></td> <td class="right"> <table> <caption aligh="center">&nbsp;再培训记录&nbsp;</caption> <tr> <td class="title">姓  名:</td> <td class="content name">薛嵩</td> </tr> <tr> <td class="title">证  号:</td> <td class="content id_no">320683198201239013</td> </tr> <tr> <td class="title">工作单位:</td> <td class="content company">中国石化销售有限公司江苏南通石油分公司南京江宁销售分理部一处</td> </tr> <tr> <td class="title">行业类别:</td> <td class="content company_type">危险化学品生产单位</td> </tr> <tr> <td class="title">人员类别:</td> <td class="content category">主要负责人</td> </tr> <tr> <td class="title">培训时间:</td> <td class="content training_time">2017-03-20至2017-03-21</td> </tr> <tr> <td class="title"></td> <td class="sign">机构印章</td> </tr> <tr> <td class="title">复训提醒:</td> <td class="content repeat_time">请2017年03月前参加再培训</td> </tr> </table> </td> </tr> </table> </div> <script> var LODOP; $('.btn_print').on('click', function () { var ids = $('#jqgrid-table-1').jqGrid('getGridParam', 'selarrrow'); if (ids.length <= 0) { show_msg(false, '请选择要打印的学员'); return false; } $.ajax({ type: 'post', url: '<?php echo e(URL::route("students.get.info")); ?>', data: {id: ids, _token: '<?php echo e(csrf_token()); ?>'}, dataType: 'json', success: function (data) { console.log('ajax back'); if (data.code) doPrint(data); } }); }); function doPrint(data) { LODOP = getLodop(); LODOP.SET_PRINT_PAGESIZE(1, 2100, 2970, 'A4'); LODOP.PRINT_INIT("打印学生信息"); LODOP.SET_PRINT_MODE("POS_BASEON_PAPER", true); LODOP.SET_SHOW_MODE("NP_NO_RESULT", true); var items = data.msg.info; var trans = data.msg.tran; var count = 0; $('.print_page').empty(); for (var i = 0; i < items.length; i++) { var row = $(".print_page").siblings('.print_item').clone().removeClass('hide'); row.find('.name').text(items[i].name); row.find('.id_no').text(items[i].id_no); row.find('.company').text(items[i].company); row.find('.company_type').text(items[i].company_type); row.find('.category').text(items[i].category); row.find('.training_time').text(items[i].begin_time + '至' + items[i].end_time); row.find('.repeat_time').text('请' + items[i].repeat_time + '前参加再培训'); row.find('.left .lesson').html(trans[i]); $('.print_page').append(row); count++; if (count == 5 || i == (items.length - 1)) { // 打印 LODOP.ADD_PRINT_HTM('35', '75', '100%', '100%', $('.print_page').html()); LODOP.NEWPAGE(); // 重置 $('.print_page').empty(); count = 0; } } // 数据装载完成,开始打印 LODOP.PREVIEW(); //LODOP.PRINT(); // 保存打印记录 savePrint(); } function savePrint() { // 保存打印记录 var ids = $("#jqgrid-table-1").jqGrid('getGridParam', 'selarrrow'); $.ajax({ type: 'POST', url: "<?php echo e(URL::route('students.add.print')); ?>", data: {ids: ids, _token: "<?php echo e(csrf_token()); ?>"}, dataType: 'json', success: reload }); }; </script><file_sep><?php /** * JSON 返回值 * @param string $code * @param string $msg * @return string */ function backJson($code = false, $msg = '', $url = ''){ return json_encode(['code'=>$code, 'msg'=>$msg, 'url' => $url]); } /** * 获取客户端真实的IP地址 */ if( ! function_exists("get_client_ip")){ function get_client_ip(){ if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")){ $ip = getenv("HTTP_CLIENT_IP"); }else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")){ $ip = getenv("HTTP_X_FORWARDED_FOR"); }else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) $ip = getenv("REMOTE_ADDR"); else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) $ip = $_SERVER['REMOTE_ADDR']; else $ip = "unknown"; return($ip); } } // 日志记录全部模块 function logModule(){ return [ 'article' => [ 'name' => '新闻管理', 'types' =>['add' => '添加新闻', 'edit' => '编辑新闻', 'del' => '删除新闻'] ], 'articleCategory' => [ 'name' => '新闻类别', 'types' =>['add' => '添加新闻类别', 'edit' => '编辑新闻类别', 'del' => '删除新闻类别'] ], 'subject' => [ 'name' => '科目管理', 'types' =>['add' => '添加科目','edit' => '编辑科目','del' => '删除科目'], ], 'question' => [ 'name' => '题目管理', 'types' =>['add' => '添加题目', 'edit' => '编辑题目', 'del' => '删除题目', 'import' => '导入题目'], ], 'exam' => [ 'name' => '考卷管理', 'types' =>['add' => '添加考卷', 'edit' => '编辑考卷', 'del' => '删除考卷', 'setQuestion'=> '设置考题', 'setCode'=> '设置不计分练习号'], ], 'user' => [ 'name' => '用户管理', 'types'=> ['add' => '添加用户', 'edit' => '编辑用户', 'del' => '删除用户', 'permission' => '设置权限', 'repass'=>'修改密码'], ], 'role' => [ 'name' => '角色管理', 'types'=> ['add' => '添加角色', 'edit' => '编辑角色', 'del' => '删除角色', 'permission' => '设置角色权限'], ], 'module' => [ 'name' => '模块管理', 'types'=> ['add' => '添加模块', 'edit' => '编辑模块', 'del' => '删除模块'], ], 'trainings' => [ 'name' => '培训管理', 'types'=> ['add' => '添加培训', 'edit' => '编辑培训', 'del' => '删除培训'], ], 'classes' => [ 'name' => '班级管理', 'types'=> ['add' => '添加班级', 'edit' => '编辑班级', 'del' => '删除班级', 'setTraining'=>'设置课程'], ], 'student' => [ 'name' => '学生管理', 'types'=> ['import' => '导入学生', 'print' => '打印学生', 'del' => '删除学生'], ], 'slider' => [ 'name' => '幻灯片管理', 'types'=> ['add' => '添加幻灯片', 'edit' => '编辑幻灯片', 'del' => '删除幻灯片'], ], 'examination' => [ 'name' => '考试管理', 'types'=> ['add' => '添加考试', 'edit' => '编辑考试', 'del' => '删除考试'], ], 'candidate' => [ 'name' => '考生管理', 'types'=> ['import' => '导入考生', 'del' => '删除考生'], ], 'cert' => [ 'name' => '证书导入', 'types'=> ['import' => '导入证书', 'edit' => '编辑证书', 'del' => '删除证书', 'add' => '添加证书'], ], ]; } function genTree($items,$id='id',$pid='pid',$son = 'children'){ $tree = array(); //格式化的树 $tmpMap = array(); //临时扁平数据 foreach ($items as $item) { $tmpMap[$item[$id]] = $item; } foreach ($items as $item) { if (isset($tmpMap[$item[$pid]])) { $tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]]; } else { $tree[] = &$tmpMap[$item[$id]]; } } unset($tmpMap); return $tree; } // 多维数组转二位数组 function array_multi2single($data){ static $result=array(); foreach($data as $value){ if(isset($value['children']) && is_array($value['children'])){ $temp = $value; unset($temp['children']); $result[] = $temp; array_multi2single($value['children']); }else{ $result[]=$value; } } return $result; } /** * 多维数组按照某项排序 * @param $multi_array * @param $sort_key * @param int $sort * @return bool */ function multi_array_sort($multi_array,$sort_key,$sort=SORT_ASC){ if(is_array($multi_array)){ foreach ($multi_array as $row_array){ if(is_array($row_array)){ $key_array[] = $row_array[$sort_key]; }else{ return false; } } }else{ return false; } array_multisort($key_array,$sort,$multi_array); return $multi_array; } /** * 数字转字母 (类似于Excel列标) * @param Int $index 索引值 * @param Int $start 字母起始值 * @return String 返回字母 */ function IntToChr($index, $start = 65) { $str = ''; if (floor($index / 26) > 0) { $str .= IntToChr(floor($index / 26)-1); } return $str . chr($index % 26 + $start); } // 大小写转换 function ToDaxie($a){ $da_num=array('零','一','二','三','四','五','六','七','八','九'); return $da_num[$a]; }<file_sep><?php Route::get('/', function () { return view('auth.login'); }); Auth::routes(); Route::group(['middleware'=>['web']], function(){ Route::post('/upload', ['uses'=>'Common\uploadController@doUpload', 'as'=>'upload']); }); Route::get('/home', ['uses'=>'HomeController@index', 'as'=>'home']); // 新闻管理 Route::get('/article/index', ['uses'=>'ArticleController@index', 'as'=>'article.index']); // 新闻列表 Route::post('/article/get', ['uses'=>'ArticleController@getArticles', 'as'=>'article.get']); // 获取新闻列表 Route::post('/article/add', ['uses'=>'ArticleController@add', 'as'=>'article.add']); // 添加新闻页面 Route::post('/article/delete', ['uses'=>'ArticleController@delete', 'as'=>'article.delete']); // 删除新闻方法 Route::post('/article/getContent', ['uses'=>'ArticleController@getContent', 'as'=>'article.get.content']); // 获取新闻的内容 // 题目管理 // 题库 Route::get('/topic/index', ['uses'=>'TopicController@index', 'as'=>'topic.index']); // 题目列表 Route::post('/topic/get', ['uses'=>'TopicController@get', 'as'=>'topic.get']); // 获取题目列表 Route::get('/topic/add', ['uses'=>'TopicController@add', 'as'=>'topic.add']); // 题目添加页 Route::post('/topic/add/do', ['uses'=>'TopicController@doAdd', 'as'=>'topic.add.do']); // 添加题目处理方法 Route::post('/topic/delete', ['uses'=>'TopicController@delete', 'as'=>'topic.delete']); // 题目删除方法 Route::post('/topic/get/subject', ['uses'=>'TopicController@getSubject', 'as'=>'topic.get.subject']); // 题目获取科目 // 考试 Route::get('/exam/index', ['uses'=>'ExamController@index', 'as'=>'exam.index']); // 考试 Route::post('/exam/get', ['uses'=>'ExamController@get', 'as'=>'exam.get']); // 考试列表 Route::post('/exam/delete', ['uses'=>'ExamController@delete', 'as'=>'exam.delete']); // 考试删除 Route::post('/exam/get/topic', ['uses'=>'ExamController@getTopic', 'as'=>'exam.get.topic']); // 获取考试题目 Route::post('/exam/save', ['uses'=>'ExamController@doSave', 'as'=>'exam.save']); // 保存考试信息 Route::post('/exam/get/info', ['uses'=>'ExamController@getExamInfo', 'as'=>'exam.get.info']); // 获取考试信息 Route::post('/exam/set/question', ['uses'=>'ExamController@setQuestion', 'as'=>'exam.set.question']); // 设置考题 Route::post('/exam/save/question', ['uses'=>'ExamController@saveQuestion', 'as'=>'exam.save.question']); // 保存考题 // 科目管理 Route::get('/subject/index', ['uses'=>'SubjectController@index', 'as'=>'subject.index']); // 科目列表 Route::post('/subject/get', ['uses'=>'SubjectController@getSubjectList', 'as'=>'subject.get']); // 获取科目列表 Route::post('/subject/add', ['uses'=>'SubjectController@add', 'as'=>'subject.add']); // 科目添加 Route::post('/subject/delete', ['uses'=>'SubjectController@delete', 'as'=>'subject.delete']); // 题目删除方法 // 课程列表 Route::get('/trainings/index', ['uses'=>'TrainingsController@index', 'as'=>'trainings.index']); //课程列表 Route::post('/trainings/get', ['uses'=>'TrainingsController@get', 'as'=>'trainings.get']); // 获取课程列表 Route::post('/trainings/edit', ['uses'=>'TrainingsController@edit','as'=>'trainings.edit']); // 修改课程 Route::post('/trainings/delete', ['uses'=>'TrainingsController@delete', 'as'=>'trainings.delete']); // 删除课程 // 班级列表 Route::get('/classes/index', ['uses'=>'ClassesController@index', 'as'=>'classes.index']); //课程列表 Route::post('/classes/get', ['uses'=>'ClassesController@get', 'as'=>'classes.get']); // 获取课程列表 Route::post('/classes/edit', ['uses'=>'ClassesController@edit','as'=>'classes.edit']); // 修改课程 Route::post('/classes/delete', ['uses'=>'ClassesController@delete', 'as'=>'classes.delete']); // 删除课程 Route::post('/classes/set/trainings', ['uses'=>'ClassesController@setTrainings', 'as'=>'classes.set.trainings']); // 设置考题 Route::post('/classes/get/trainings', ['uses'=>'ClassesController@getTrainings', 'as'=>'classes.get.trainings']); // 设置考题 Route::post('/classes/get/years', ['uses'=>'ClassesController@getYears', 'as'=>'classes.get.years']); // 获取年 // 学生列表 Route::get('/students/index', ['uses'=>'StudentsController@index', 'as'=>'students.index']); //课程列表 Route::post('/students/get', ['uses'=>'StudentsController@get', 'as'=>'students.get']); // 获取课程列表 Route::post('/students/get/info', ['uses'=>'StudentsController@getInfo', 'as'=>'students.get.info']); // 获取学生信息 Route::post('/students/edit', ['uses'=>'StudentsController@edit','as'=>'students.edit']); // 修改课程 Route::post('/students/delete', ['uses'=>'StudentsController@delete', 'as'=>'students.delete']); // 删除课程 Route::post('/students/import', ['uses'=>'StudentsController@import', 'as'=>'students.import']); // 学生导入 Route::post('/students/get/classes', ['uses'=>'StudentsController@getClasses', 'as'=>'students.get.classes']); // 学生关联班级 Route::post('students/add/print', ['uses'=>'StudentsController@addPrint', 'as'=>'students.add.print']); // 打印记录保存 Route::post('students/get/print', ['uses'=>'StudentsController@getPrint', 'as'=>'students.get.print']); // 打印记录查询 // 报表 Route::get('/printAdmission/index', ['uses'=>'PrintAdmissionController@index', 'as'=>'printAdmission.index']); // 打印报表 Route::post('/printAdmission/get', ['uses'=>'PrintAdmissionController@get', 'as'=>'printAdmission.get']); // 获取打印列表 // 系统设置 Route::get('/sys/index', ['uses'=>'SystemController@index', 'as'=>'sys.index']); // 系统设置首页 // 用户管理 Route::get('/user/index', ['uses'=>'UserController@index', 'as'=>'user.index']); // 用户管理首页 Route::post('/user/get', ['uses'=>'UserController@get', 'as'=>'user.get']); // 获取用户列表 Route::post('/user/edit', ['uses'=>'UserController@edit', 'as'=>'user.edit']); // 添加用户 Route::post('/user/delete', ['uses'=>'UserController@delete', 'as'=>'user.delete']); // 删除用户 Route::post('/user/permission', ['uses'=>'UserController@permission', 'as'=>'user.permission']); // 用户权限 Route::post('user/changepw', ['uses'=>'UserController@changepw', 'as'=>'user.changepw']); // 角色权限 Route::get('/role/index', ['uses'=>'RoleController@index', 'as'=>'role.index']); // 角色用户首页 Route::post('/role/get', ['uses'=>'RoleController@get', 'as'=>'role.get']); // 获取用户角色 Route::post('/role/edit', ['uses'=>'RoleController@edit', 'as'=>'role.edit']); // 添加角色 Route::post('/role/delete', ['uses'=>'RoleController@delete', 'as'=>'role.delete']); // 删除角色 Route::post('/role/permission', ['uses'=>'RoleController@permission', 'as'=>'role.permission']); // 角色关联模块 Route::post('/role/getList', ['uses'=>'RoleController@getList', 'as'=>'role.get.list']); // 角色关联模块 // 模块管理 Route::get('/module/index', ['uses'=>'ModuleController@index', 'as'=>'module.index']); // 模块管理首页 Route::post('/module/get', ['uses'=>'ModuleController@get', 'as'=>'module.get']); // 获取模块 Route::post('/module/save', ['uses'=>'ModuleController@doSave', 'as'=>'module.save']); // 添加模块 Route::post('/module/delete', ['uses'=>'ModuleController@delete', 'as'=>'module.delete']);// 删除模块 Route::post('/module/get/one', ['uses'=>'ModuleController@getOne', 'as'=>'module.get.one']);// 获取某一个模块的信息 Route::post('/module/get/list', ['uses'=>'ModuleController@getList', 'as'=>'module.get.list']);// 获取所有的模块 Route::post('/module/save/sort', ['uses'=>'ModuleController@saveSort', 'as'=>'module.save.sort']);// 获取所有的模块 Route::get('/base/logs', ['uses'=>'LogController@index', 'as'=>'base.log']);// 日志模块 Route::post('/base/logs/get', ['uses'=>'LogController@get', 'as'=>'base.log.get']); // 获取日志内容 <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Classes; use App\Http\Model\ClassTraining; use App\Http\Model\Students; use App\Http\Model\Trainings; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\URL; use Exception; class ClassesController extends Controller { /* * 首页 */ public function index() { $data ['category'] = 'training'; $data ['subCategory'] = 'classes'; $data ['breadcrumb'] = $this->breadcrumb(); return view('classes.index', $data); } /* * 获取 */ function get(Request $request) { $input = $request->all(); $page = isset($input ['rows']) ? $input ['rows'] : env('PAGNATION'); $list = Classes::where('state', '<>', 0)->orderBy('begin_time','desc')->paginate($page); foreach ($list as $i=>$row) { $list[$i]['state_text'] = $row->state ? '正常' : '禁用'; } $result = [ 'records' => $list->total(), 'total' => $list->lastPage(), 'rows' => $list->items() ]; return json_encode($result); } /* * 获取年份 */ public function getYears(Request $req) { // 获取班级开始年份 $years = DB::table('classes')->select(DB::raw('id, year(begin_time) as y, month(begin_time) as m')) ->where('state', '1') ->groupBy('y') ->groupBy('m') ->groupBy('id') ->get(); $year = $tree = []; foreach ($years as $y){ $year[$y->y][$y->m][] = $y->id; } foreach ($year as $k=>$month){ $tree[$k] = [ 'id' => $k, 'text' => $k, 'type' => 'folder', 'level'=>1, ]; if( !empty($month) ){ $mon = []; foreach ($month as $key=>$class){ $mon[$key] = [ 'id' => $k.'-'.$key, 'text' => str_pad($key, 2, "0", STR_PAD_LEFT), 'type' => 'folder', 'level'=>2, ]; if( !empty($class) ){ $cls = []; foreach ($class as $l=>$id) { $classesInfo = Classes::where('id', $id)->first(); $cls[] = [ 'id' => $id, 'text' => $classesInfo->name, 'type' => 'item', 'level' => 3, ]; } $mon[$key]['additionalParameters']['children'] = $cls; } } $tree[$k]['additionalParameters']['children'] = $mon; } } return backJson(true, $tree); } /* * 添加和修改 */ function edit(Request $request) { try { $input = $request->all(); $data = [ 'name' => $input['name'], 'begin_time' => $input['begin_time'], 'end_time' => $input['end_time'], 'repeat_time' => $input['repeat_time'], 'state' =>$input['state'], //'sid' => $input['sid'], ]; if (isset($input ['id']) && ! empty($input ['id'])) { Classes::where('id', $input['id'])->update($data); $logType = 'edit'; $_success_txt = '班级信息修改成功'; } else { if (! Classes::create($data)) { throw new Exception("系统错误, 班级添加失败"); } $logType = 'add'; $_success_txt = '班级添加成功'; } parent::_save_log('classes', $logType, $input['name']); return backJson(true, $_success_txt); } catch ( Exception $e ) { return backJson(false, $e->getMessage()); } } /* * 删除 */ function delete(Request $request) { try { $input = $request->all(); if (! isset($input ['id']) || empty($input ['id'])) { throw new Exception("请选择要删除的班级"); } $classesInfo = Classes::where('id', $input['id'])->first(); if( ClassTraining::where('class_id', $input ['id'])->count() > 0 ){ throw new Exception("该班级已分配课程, 不能删除"); } if( Students::where('class_id', $input ['id'])->count() > 0 ){ throw new Exception("该班级已分配学员, 不能删除"); } if (! Classes::where('id', $input ['id'])->delete()) { throw new Exception("系统错误, 删除失败"); } parent::_save_log('classes', 'del', $classesInfo['name']); return backJson(true, '删除成功'); } catch ( Exception $e ) { return backJson(false, $e->getMessage()); } } // 设置班级课程 function setTrainings(Request $request) { try { $input = $request->all(); if( !isset($input['id']) || empty($input['id']) ){ throw new \Exception("请选择班级"); } $classesInfo = Classes::where('id', $input['id'])->first(); if( ClassTraining::where('class_id', $input['id'])->count() > 0 ) { if (!ClassTraining::where('class_id', $input['id'])->delete()) { throw new \Exception("创建失败, 原班级课程删除失败"); } } $classTran = []; if( isset($input['trans']) ) { foreach ($input['trans'] as $k => $trans) { $classTran[] = [ 'class_id' => $input['id'], 'training_id' => $trans, 'sid' => $k ]; } } if( !ClassTraining::insert( $classTran ) ){ throw new \Exception("系统错误, 课程班级创建失败"); } parent::_save_log('classes', 'setTraining', $classesInfo['name']); return backJson(true, '班级课程创建成功'); } catch (\Exception $e) { return backJson(false, $e->getMessage()); } } // 获取班级信息, 获取班级关联课程信息 function getTrainings(Request $request) { $input = $request->all(); $traningData = Trainings::where('state', '<>', 0)->get(); $classTran = ClassTraining::where('class_id', $input['id'])->orderBy('sid', 'asc')->get(); $classtran = $tranTxt = ''; $clsTran = []; foreach ($classTran as $clst) { $tranData = $clst->hasoneToTraining()->first(); $clsTran[] = $clst->training_id; $classtran .= "<li data-value='" . $clst->training_id . "'>"; $classtran .= "<span class='title'>{$tranData->name}</span>"; $classtran .= "<span class='fa fa-trash-o delete'></span>"; $classtran .= "<span class='fa fa-arrow-circle-o-down down'></span>"; $classtran .= "<span class='fa fa-arrow-circle-o-up up'></span>"; $classtran .= "</li>"; } foreach ($traningData as $tran) { $cls = ''; if( in_array($tran->id, $clsTran) ){ $cls = 'hide'; } $tranTxt .= "<option value='" . $tran->id . "' class='" . $cls . "'>{$tran->name}</option>"; } return backJson(true, ['tranTxt'=>$tranTxt, 'classtran'=>$classtran]); } /* * 页面路径 */ private function breadcrumb() { return [ [ 'url' => URL::route('classes.index'), 'title'=> '班级列表' ] ]; } }<file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Article; use App\Http\Model\ArticleCategory; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\URL; class ArticleController extends Controller { public function index(Request $request) { $data ['category'] = 'articles'; $data ['subCategory'] = 'articlelist'; $data ['breadcrumb'] = $this->breadcrumb(); $cate = new ArticleCategoryController(); $data['categoryList'] = $cate->getCategory(2, 1); return view('article.index', $data); } function getCategory(){ $categoryData = ArticleCategory::where('status', 1)->orderBy('sid', 'asc')->get(); $tree = $catego = []; if( $categoryData->count() >0 ) { $categoryData = $categoryData->toArray(); foreach (genTree($categoryData) as $k=>$cate) { $tree[$k] = [ 'id' => $cate['id'], 'text' => $cate['title'], 'type' => 'folder', 'level' => 1, ]; if( isset($cate['children']) ){ $cls = []; foreach ($cate['children'] as $ch){ $cls[] = [ 'id' => $ch['id'], 'text' => $ch['title'], 'type' => 'folder', 'level' => 2, ]; } $tree[$k]['additionalParameters']['children'] = $cls; } } } return backJson(true, $tree); } public function getArticles(Request $request) { $page = isset($request->rows) ? $request->rows : env('PAGNATION'); $input = $request->all(); $where = []; if( isset($input['search']) ){ $where = ['category_id'=>$input['search']]; } $list = Article::where($where)->orderBy('created_at', 'desc')->paginate($page); foreach ($list as $k => $li) { $catear = $li->hasOneToCategory()->first(); $list[$k]->category = $catear == null ? '' : $catear->title; $url = URL::route('details', ['id'=>$li->id]); $list[$k]->url = "<a target='_blank' href='{$url}'>{$url}</a>"; } $roles = [ 'records' => $list->total(), 'total' => $list->lastPage(), 'rows' => $list->items() ]; return json_encode($roles); } public function getContent(Request $request) { try { $article = Article::findOrFail($request->id); return backJson(true, $article->content); } catch (Exception $e) { return backJson(false, '获取新闻内容失败:'.$e->getMessage()); } } public function add(Request $request) { try { $article = null; $message = ''; $operate = 'add'; if (isset($request->id) && !empty($request->id)) { $message = '修改新闻'; $operate = 'edit'; $article = Article::findOrFail($request->id); $article->category_id = $request->category_id; $article->title = $request->title; $article->content = $request->content; $article->author = $request->author; $article->update(); } else { $message = '新增新闻'; $article = new Article; $article->user_id = Auth::user()->id; $article->category_id = $request->category_id; $article->title = $request->title; $article->content = $request->content; $article->author = $request->author; $article->save(); } parent::_save_log('article', $operate, $article->title); return backJson(true, $message.'成功!'); } catch (Exception $e) { return backJson(false, $message.'失败:'.$e->getMessage()); } } public function delete(Request $request) { try { if (!isset($request->id) || empty($request->id)) { throw new \Exception("请选择要删除的新闻"); } $article = Article::findOrFail($request->id); $title = $article->title; $article->delete(); parent::_save_log('article', 'del', $title); return backJson(true, '新闻删除成功'); } catch ( \Exception $e ) { return backJson(false, $e->getMessage()); } } /** * 页面面包屑 * * @return array */ private function breadcrumb() { return [ [ 'url' => URL::route('article.index'), 'title' => '新闻列表' ] ]; } } <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta charset="utf-8"> <title><?php echo e(config('app.name')); ?></title> <meta name="description" content="overview & stats"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>"> <link rel="stylesheet" href="<?php echo e(URL::asset('assets/css/bootstrap.css')); ?>" /> <link rel="stylesheet" href="<?php echo e(URL::asset('components/font-awesome/css/font-awesome.css')); ?>" /> <link rel="stylesheet" href="<?php echo e(URL::asset('assets/css/ace-fonts.css')); ?>" /> <link id="main-ace-style" class="ace-main-stylesheet" rel="stylesheet" href="<?php echo e(URL::asset('assets/css/ace.css')); ?>" /> <link rel="stylesheet" href="<?php echo e(URL::asset('components/jquery.gritter/css/jquery.gritter.css')); ?>" /> <link rel="stylesheet" href="<?php echo e(URL::asset('components/_mod/jquery-ui/jquery-ui.css')); ?>" /> <link rel="stylesheet" href="<?php echo e(URL::asset('components/_mod/jqgrid/ui.jqgrid.css')); ?>" /> <link rel="stylesheet" href="<?php echo e(URL::asset('assets/css/ace.css')); ?>" class="ace-main-stylesheet" id="main-ace-style" /> <link rel="stylesheet" href="<?php echo e(URL::asset('assets/css/ace-skins.css')); ?>" /> <link rel="stylesheet" href="<?php echo e(URL::asset('css/main.css')); ?>" /> <script src="<?php echo e(URL::asset('components/jquery/dist/jquery.js')); ?>"></script> <script src="<?php echo e(URL::asset('components/bootstrap/dist/js/bootstrap.js')); ?>"></script> <script src="<?php echo e(URL::asset('components/jquery-ui/jquery-ui.js')); ?>"></script> <script src="<?php echo e(URL::asset('components/jquery-ui/ui/i18n/datepicker-zh-CN.js')); ?>"></script> <script src="<?php echo e(URL::asset('assets/js/src/elements.scroller.js')); ?>"></script> <script src="<?php echo e(URL::asset('js/validform.js')); ?>"></script> <script src="<?php echo e(URL::asset('js/validform_Datatype.js')); ?>"></script> <script src="<?php echo e(URL::asset('assets/js/src/ace.js')); ?>"></script> <script src="<?php echo e(URL::asset('assets/js/src/ace.basics.js')); ?>"></script> <script src="<?php echo e(URL::asset('assets/js/src/ace.sidebar.js')); ?>"></script> <script src="<?php echo e(URL::asset('assets/js/src/ace.submenu-hover.js')); ?>"></script> <script src="<?php echo e(URL::asset('components/jquery.gritter/js/jquery.gritter.js')); ?>"></script> <script src="<?php echo e(URL::asset('components/bootbox.js/bootbox.js')); ?>"></script> <script src="<?php echo e(URL::asset('components/_mod/fuelux/tree.js')); ?>"></script> <script src="<?php echo e(URL::asset('assets/js/src/elements.treeview.js')); ?>"></script> <script src="<?php echo e(URL::asset('components/_mod/jquery.nestable/jquery.nestable.js')); ?>"></script> <script src="<?php echo e(URL::asset('js/sco.modal.js')); ?>"></script> <script src="<?php echo e(URL::asset('js/main.js')); ?>"></script> <script> window.Laravel = <?php echo json_encode([ 'csrfToken' => csrf_token(), ]); ?> </script> <?php echo $__env->yieldContent('header_style'); ?> </head> <body class="no-skin"> <?php echo $__env->make('addi.nav', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <div id="main-container" class="main-container ace-save-state"> <?php echo $__env->make('addi.menu', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <div class="main-content"> <div class="main-content-inner"> <?php echo $__env->make('addi.breadcrumb', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> <div class="page-content"> <?php echo $__env->yieldContent('content'); ?> </div> </div> </div> </div> <?php echo $__env->yieldContent('footer_script'); ?> </body> </html> <file_sep><?php namespace App\Http\Controllers; use App\Http\Model\Log; use App\Http\Model\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\URL; class LogController extends Controller { function __construct() { parent::__construct(); } /* * 首页 */ public function index() { $data ['category'] = 'base'; $data ['subCategory'] = 'log'; $data ['breadcrumb'] = $this->breadcrumb(); $data['allUsers'] = User::get()->toArray(); return view('base.log', $data); } /* * 获取用户列表 */ function get(Request $request) { $input = $request->all(); $page = isset($input ['rows']) ? $input ['rows'] : env('PAGNATION'); if( Auth::user()['id'] == 1 ) { $logList = Log::where('user_id', '<>', 0); }else{ $logList = Log::where('user_id', Auth::user()['id']); } if( isset($input['time']) && !empty($input['time']) ){ $time = explode(' 至 ', $input['time']); $logList = $logList->whereBetween('dt', [$time[0], $time[1]]); }else{ $stime = date('Y-m-d H:00:00'); $etime = date("Y-m-d 00:00:00",strtotime("+1 day")); $logList = $logList->whereBetween('dt', [$stime, $etime]); } if( isset($input['content']) && !empty($input['content']) ){ $logList = $logList->where('des','like','%'.$input['content'].'%'); } if( isset($input['user']) && !empty($input['user']) ){ $logList = $logList->where('user_id', $input['user']); } $logList = $logList->orderBy('dt', 'desc')->paginate($page); foreach ($logList as $k=>$log){ $user = $log->hasOneToUser()->first(); if( $user != null ) { $logList[$k]->user_name = $log->hasOneToUser()->first()->name; }else{ $logList[$k]->user_name = ''; } } $logs = [ 'records' => $logList->total(), 'total' => $logList->lastPage(), 'rows' => $logList->items() ]; return json_encode($logs); } /* * 删除 */ function delete(Request $req) { try { $input = $req->all(); if (! isset($input ['ids']) || empty($input ['ids'])) { throw new \Exception("请选择要删除的日志"); } if (! Log::whereIn('id', $input ['ids'])->delete()) { throw new \Exception("系统错误,删除日志失败"); } return backJson(true, '删除日志成功'); } catch ( \Exception $e ) { return backJson(false, $e->getMessage()); } } /* * 页面路径 */ private function breadcrumb() { return [ [ 'url' => URL::route('user.index'), 'title'=> '日志管理' ] ]; } }
4fc3f1fc6a244c2c22788f83eacba21c598482fa
[ "JavaScript", "SQL", "Markdown", "PHP" ]
83
PHP
xp8100/examine
f2da12b47129cf4352a7d7ee58cf99f9a01a3a5b
4b7963394a0ce2be6a2fe96f8462554c9b0f0df9
refs/heads/master
<file_sep>#include <stdlib.h> #include <vector> #include "utils.hpp" /// BUBBLE SORT CHARACTERISTICS /// Average Time: O(n^2) /// Worst Time: O(n^2) /// Space: O(1) void bubble_sort(std::vector<int> *vect) { bool change = true; while (change) { change = false; for (size_t i = 0; i < vect->size() - 1; i++) { if (vect->at(i) > vect->at(i + 1)) { std::swap(vect->at(i), vect->at(i + 1)); change = true; } } } } int main() { std::vector<int> vect = {4, 6, 2, 5, 1, 8, 4, 0, 2, 11, 6}; bubble_sort(&vect); utils::print(vect); return 0; }<file_sep># Memory management notes ## Pointers Positions in memory: Variables: ```cpp Entity entity; // Value based: Local to this function stack frame Entity* entity_ptr = &entity; std::cout << (*entity_ptr).GetField() << std::endl; // Option 1 To get value of pointer std::cout << entity_ptr->GetField() << std::endl; // Option 2 (Wrapper) To get value of pointer ``` Params in functions: ```cpp Something getSomething(const Entity& entity) { // Pass by reference (always protected by const } ``` ```cpp void doSomethingInPlace(Entity* entity) { // Pass pointer } doSomethingInPlace(&entity); // User will knows variable will get changed ``` ## Stack allocation: Example: ```cpp Entity entity("oleguer"); // Value based: Local to this function stack frame std::cout << entity.GetName() << std::endl; ``` **Pros:** - Faster allocation - Automatically "destroyed" when scope is finished **Cons:** - Can only be used in this scope (between these brackets) - Objects can't be very very big (STACK memory is fixed to ~2MB) ## Heap allocation: Example of dinamically allocated memory: ```cpp Entity *entity = new Entity("oleguer"); // Created in heap std::cout << (*entity).GetName() << std::endl; // Access pointer value std::cout << entity->GetName() << std::endl; // Arrow automatically does this for us // As it is a pointer created in heap, // here we could save the pointer and use it in another scope some_entity_pointer = entity; // This is not copying values, just setting another pointer // When we are done with this variable, // we have to free the memory allocated delete entity; // OBS: if we had assigned it to another pointer, // we could have done: delete some_entity_pointer // And would have deleted the same object // (we can do this outside this scope) ``` **Pros:** - Control over life-span of the object - Can hold bigger variables (HEAP memory is expandable) **Cons:** - Slower - Can lead into memory leaks ### The "NEW" KeyWord: - Finds the necessary memory for the specified data type in the HEAP memory. - Returns a pointer to the found address - It also calls the constructor of the object **OBS:** The memory allocating part of **new**, is equivalent to **malloc**: ```cpp // Allocate memory and call constructor: Entity* entity = new Entity(); // Allocate memory but don't call constructor Entity* entity = (Entity*)malloc(sizeof(Entity)); ``` ### The "DELETE" KeyWord: - Calls c function: **free()**, which frees the malloc block memory - Calls destructor of the object **OBS:** If we create a new array, we must delete by **delete[]**: ```cpp int* array = new int[50]; destroy[] array; ``` ## Pointers - Integer that holds a memory adress. **OBS**: type of pointer is irrelevant, its always an integer Example: ```cpp int var = 9; int* ptr = &var; // ptr holds where in memory we are storing var *ptr = 10; // Access the variable from the pointer // Now var has a value of 10 ``` **OBS:** Pointers are also variables, so we could have pointers of pointers (double pointers) ```cpp int var = 9; int* ptr = &var; // ptr is memory address of var int** double_ptr = &ptr; // double_ptr is memory address of ptr ``` ## Smart pointers - Wrapper around raw pointer that automates **new**/**delete** call process in heap memory. ### unique_ptr - Can't be copied (if one dies, it will free the memory its pointing to, so the other will be pointing nowhere) Example: ```cpp include <memory> // Needs to be included to use cmart pointers { std::unique_ptr<Entity> entity = std::make_unique<Entity>(); // Gets created } // Here entity is automatically destroyed (out of scope) ``` ### shared_ptr - Keeps track of how many references are there to that shared_ptr (once it gets to 0, its automatically destroyed) Example: ```cpp include <memory> // Needs to be included to use cmart pointers { std::shared_ptr<Entity> e0; { std::shared_ptr<Entity> entity = std::make_shared<Entity>(); // Gets created (referennces count = 1) e0 = entity; // assigned to e0 (referennces count = 2) } // entity out of scope but doesnt get destryed (referennces count = 1) } // here the memory is freed, all references are dead (references count = 0) ``` ### weak_ptr - Allows you to copy a shared_ptr without increasing ref count (useful to check if something is still alive without keeping it alive) Example: ```cpp include <memory> // Needs to be included to use cmart pointers { std::weak_ptr<Entity> e0; { std::shared_ptr<Entity> entity = std::make_shared<Entity>(); // Gets created (referennces count = 1) e0 = entity; // assigned to e0 but since its weak: (referennces count = 1) } // entity out of scope gets destryed (referennces count = 0) } ``` <file_sep>#pragma once #include <iterator> #include <iostream> #include <stdlib.h> #include <unordered_set> namespace graph { struct Node { int val; std::unordered_set<Node *> childs; Node(const int v) : val(v){}; // Member initialization }; struct Graph { Node *root; explicit Graph(Node *node) : root(node) {} }; // Builds a graph to test the algorithms Graph buildExampleTree() { // OBS: Allocate nodes in heap so we can keep them instantiated // Not sure if its the best option (slower) Node *root = new Node(0); Node *n1 = new Node(1); Node *n2 = new Node(2); Node *n3 = new Node(3); Node *n4 = new Node(4); Node *n5 = new Node(5); Node *n6 = new Node(6); Node *n7 = new Node(7); Node *n8 = new Node(8); Node *n9 = new Node(9); root->childs.insert(n1); root->childs.insert(n2); root->childs.insert(n3); n1->childs.insert(n4); n2->childs.insert(n5); n2->childs.insert(n6); n5->childs.insert(n7); n5->childs.insert(n8); n5->childs.insert(n9); std::cout << "Tree built" << std::endl; return Graph(root); } } // namespace graph<file_sep># Classic Algorithms Data structures and common algorithms playground. As well as some theory notes. Only dependencies are STD library and MPI for parallel implementations. As always more an exercice for me to think their implementation rather than anything useful. ## Theory - [Memory Management in C++](theory/memory_management.md) - LeetCode-like problems approach guide ## Array Sorting - [Bubble Sort](sorting/bubble_sort.cpp) (Serial) - Heap Sort (Serial) - Quick Sort (Serial) - [Merge Sort](sorting/merge_sort_parallel.cpp) (**Parallel**) ## Tree Traversal ### Recursive - [Pre-order DFS](tree_traversal/recursive_tree_traversal.cpp) - [In-order DFS](tree_traversal/recursive_tree_traversal.cpp) - [Post-order DFS](tree_traversal/recursive_tree_traversal.cpp) ### Iterative - [Pre-order DFS](tree_traversal/iterative_tree_traversal.cpp) - [In-order DFS](tree_traversal/iterative_tree_traversal.cpp) - Post-order DFS - [BFS](tree_traversal/iterative_tree_traversal.cpp) ## Graph Search ### Uninformed: - BFS (Breath First Search) - DFS (Depth First Search) ### Informed: #### Without heuristic: - Dijkstra (Expand lowest acquisition_cost node) #### Heuristic available: - Greedy (Expand lowest heuristic node) - A* (Expand lowest heuristic + acquisition_cost node) ## Metaheuristics - Genetic algorithm - Simulated Annealing - Ant Colony - Tabu Search ## Data Structures - [BT](include/binnary_tree.hpp) (Binnary Tree) - BST (Binnary Search Tree) - [Graph](include/graph.hpp) # To test an algorithm If serial algorithm: `./run_serial.sh <path_to_cpp_file>` If parallel algorithm: `./run_parallel.sh <path_to_cpp_file> <processors_to_use>`<file_sep>#pragma once #include <array> #include <iostream> #include <math.h> #include <queue> #include <stdlib.h> #include <string> #include <vector> #include "graph.hpp" namespace utils { // HELPERS --------------------------------------------------- std::vector<float> get_random_vector(size_t size, int seed) { srandom(seed); std::vector<float> vect(size); for (size_t i = 0; i < size; i++) vect[i] = static_cast<float>(rand()) / static_cast<float>(RAND_MAX); return vect; } // TIMING ---------------------------------------------------- // Start timer time_t tic() { return clock(); } // Stop counting time and print timer void toc(time_t t, std::string print) { t = clock() - t; std::cout << "-->[TIME]: " << print << ": " << ((float)t) / CLOCKS_PER_SEC << '\n'; } // PRINTING ------------------------------------------------- // Prints object template <typename T = int> void print(std::vector<T> vec, std::string msg = "") { if (msg != "") std::cout << msg << ": "; for (size_t i = 0; i < vec.size(); i++) std::cout << vec[i] << " "; std::cout << std::endl; } void print(graph::Graph graph) { std::queue<graph::Node *> nodes_to_visit; // Push nodes to list nodes_to_visit.push(graph.root); while (!nodes_to_visit.empty()) { graph::Node *node = nodes_to_visit.front(); nodes_to_visit.pop(); std::cout << node->val << ", "; std::unordered_set<graph::Node *>::iterator it; for (it = node->childs.begin(); it != node->childs.end(); it++) nodes_to_visit.push(*it); } std::cout << std::endl; } } // namespace utils <file_sep># mpic++ is a wrapper around gcc which links mpi libraries mpic++ -I include $1 -o out; mpirun -n $2 out<file_sep>#include <stdlib.h> #include <iostream> #include <iterator> #include <queue> #include <stack> #include <unordered_set> // Define a node of the graph struct Node { int val; std::unordered_set<Node*> childs; Node(const int v) : val(v){}; // Member initialization }; // Define a graph as the root node struct Graph { Node* root; explicit Graph(Node* node) : root(node) {} void BFS() { std::queue<Node*> nodes_to_visit; // Push nodes to list nodes_to_visit.push(root); while (!nodes_to_visit.empty()) { Node* node = nodes_to_visit.front(); nodes_to_visit.pop(); std::cout << node->val << ", "; std::unordered_set<Node*>::iterator it; for (it = node->childs.begin(); it != node->childs.end(); it++) nodes_to_visit.push(*it); } std::cout << std::endl; } void DFS() { std::stack<Node*> nodes_to_visit; nodes_to_visit.push(root); while (!nodes_to_visit.empty()) { Node* node = nodes_to_visit.top(); nodes_to_visit.pop(); std::cout << node->val << ", "; std::unordered_set<Node*>::iterator it; for (it = node->childs.begin(); it != node->childs.end(); ++it) { nodes_to_visit.push(*it); } } std::cout << std::endl; } // BFS Cheking repetition void noRepeatBFS() { std::queue<Node*> nodes_to_visit; std::unordered_set<Node*> visited_nodes; // Make sure we dont repeat nodes nodes_to_visit.push(root); while (!nodes_to_visit.empty()) { Node* node = nodes_to_visit.front(); nodes_to_visit.pop(); visited_nodes.insert(node); std::cout << node->val << ", "; for (auto it = node->childs.begin(); it != node->childs.end(); ++it) { auto finder = visited_nodes.find(*it); if (finder == visited_nodes.end()) // If node not in visited set nodes_to_visit.push(*it); } } std::cout << std::endl; } }; // Builds a graph to test the algorithms Graph constructExampleGraph() { // OBS: Allocate nodes in heap so we can keep them instantiated // Not sure if its the best option (slower) Node* root = new Node(0); Node* n1 = new Node(1); Node* n2 = new Node(2); Node* n3 = new Node(3); Node* n4 = new Node(4); Node* n5 = new Node(5); Node* n6 = new Node(6); Node* n7 = new Node(7); Node* n8 = new Node(8); Node* n9 = new Node(9); root->childs.insert(n1); root->childs.insert(n2); root->childs.insert(n3); n1->childs.insert(n4); n2->childs.insert(n5); n2->childs.insert(n6); n5->childs.insert(n7); n5->childs.insert(n8); n5->childs.insert(n9); std::cout << "Tree built" << std::endl; return Graph(root); } int main() { // Idea, define a graph and implement BFS Graph graph = constructExampleGraph(); graph.BFS(); // Performs a BFS traversal of the graph, printing node values graph.DFS(); // Performs a DFS traversal of the graph, printing node values graph.noRepeatBFS(); // Performs a BFS traversal of the graph without // repetitions, printing node values }<file_sep># Usage: ./run.sh path_to_cpp_file g++ -Wall -I include $1 -o out; ./out<file_sep>#include "stdlib.h" #include <iostream> #include <stack> #include <vector> struct Node { int val; Node* left = NULL; Node* right = NULL; explicit Node(int data) : val(data) {} }; struct BST { Node* root = NULL; explicit BST(Node* node) : root(node) {} void insert(Node* node) { Node* current = root; while (current != NULL) { if (node->val <= current->val) { if (current->left == NULL) { current->left = node; return; } current = current->left; } else { if (current->right == NULL) { current->right = node; return; } current = current->right; } } } void remove(int val) { // Node* current = root; // while (current != NULL) { // if (val < current->val) { // if // } // } } std::vector<Node*> ordered_nodes() { std::vector<Node*> ordered; std::stack<Node*> s; Node *node = root; while (node != NULL || !s.empty()) { while (node != NULL) { // If there is left subtree, explore it s.push(node); node = node->left; } node = s.top(); // Otherwise, go for the top of the list s.pop(); ordered.push_back(node); node = node->right; } return ordered; } Node* build_balanced(const std::vector<Node*>& ordered_nodes, int begin, int end) { if (begin > end) { return NULL; } int mid_ind = (begin + end)/2; Node* mid_node = ordered_nodes[mid_ind]; mid_node->left = build_balanced(ordered_nodes, begin, mid_ind-1); mid_node->right = build_balanced(ordered_nodes, mid_ind+1, end); return mid_node; } void balance() { // OBS: Self-balancing binary search trees are better for the job (red-black tree) // 1. Traverse in order to get sorted array of the nodes std::vector<Node*> nodes = ordered_nodes(); // 2. Build balanced tree from sortted array root = build_balanced(nodes, 0, nodes.size()-1); } void print() { std::vector<Node*> nodes = ordered_nodes(); std::cout << "Inorder: "; for (auto node : nodes) { std::cout << node->val << " "; } std::cout << std::endl; } }; int main() { // Construct sample graph Node* n1 = new Node(1); Node* n2 = new Node(2); Node* n3 = new Node(3); Node* n4 = new Node(4); Node* n5 = new Node(5); Node* n6 = new Node(6); Node* n7 = new Node(7); BST bst(n3); bst.insert(n1); bst.insert(n4); bst.insert(n2); bst.print(); bst.balance(); bst.print(); // Delete graph delete n1; delete n2; delete n3; delete n4; delete n5; delete n6; delete n7; }<file_sep>#pragma once #include <iterator> #include <iostream> #include <stdlib.h> #include <unordered_set> namespace binnary_tree { struct Node { int val; Node* left = NULL; Node* right = NULL; explicit Node(int data) : val(data) {} }; struct Tree { Node *root; explicit Tree(Node *node) : root(node) {} }; // Builds a graph to test the algorithms Tree buildExampleBinTree() { // OBS: Allocate nodes in heap so we can keep them instantiated // Not sure if its the best option (slower) Node* n1 = new Node(1); Node* n2 = new Node(2); Node* n3 = new Node(3); Node* n4 = new Node(4); Node* n5 = new Node(5); Node* n6 = new Node(6); Node* n7 = new Node(7); n1->left = n2; n1->right = n3; n2->left = n4; n2->right = n5; n3->left = n6; n3->right = n7; std::cout << "Tree built" << std::endl; return Tree(n1); } } // namespace binnary_tree<file_sep>#include <algorithm> #include <iostream> #include <stdlib.h> #include <vector> #include "mpi.h" #include "utils.hpp" void mergeSortedVectors(const std::vector<float> &in1, const std::vector<float> &in2, std::vector<float> *out) { // Given two sorted arrays, returns sorted merge int n1 = in1.size(); int n2 = in2.size(); int it1 = 0; int it2 = 0; double val; for (int i = 0; i < n1 + n2; i++) { if (it1 < n1 && it2 < n2) { if (in1[it1] < in2[it2]) { val = in1[it1]; it1++; } else { val = in2[it2]; it2++; } } else if (it1 < n1) { val = in1[it1]; it1++; } else { val = in2[it2]; it2++; } out->at(i) = val; } } void transferVector(const std::vector<float> &in, std::vector<float> *out, size_t start, size_t end) { for (size_t i = start; i < end; i++) out->at(i - start) = in[i]; } int main(int argc, char **argv) { if (argc != 1) { std::cout << "Wrong number of arguments!" << std::endl; return 0; } // Start MPI int p, P; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &P); MPI_Comm_rank(MPI_COMM_WORLD, &p); std::cout << "Process " << p << " of " << P << " started" << std::endl; double start_time = MPI_Wtime(); // Compute vector partition sizes bool even_process = p % 2; bool first_process = (p == 0); bool last_process = (p == P - 1); int N = 100; // Total number of elements int I = N / P; int I_prev = (p - 1 < N % P) ? I + 1 : I; int I_next = (p + 1 < N % P) ? I + 1 : I; I = (p < N % P) ? I + 1 : I; // Initialize vector partition std::vector<float> vect = utils::get_random_vector(I, p); std::vector<float> vect_prev(I_prev); std::vector<float> vect_next(I_next); std::vector<float> merged(2 * I + 2); // Serial sorting of current process' vector std::sort(vect.begin(), vect.end()); // Parallel sorting and merge for (int step = 0; step <= P; step++) { bool even_step = step % 2; if (even_step) { // even step if (even_process && !last_process) { MPI_Send(&vect[0], I, MPI_FLOAT, p + 1, 0, MPI_COMM_WORLD); MPI_Recv(&vect_next[0], I_next, MPI_FLOAT, p + 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); mergeSortedVectors(vect, vect_next, &merged); // Sorted Merge transferVector(merged, &vect, 0, I); // Get Min } if (!even_process && !first_process) { // odd porcess MPI_Recv(&vect_prev[0], I_prev, MPI_FLOAT, p - 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Send(&vect[0], I, MPI_FLOAT, p - 1, 0, MPI_COMM_WORLD); mergeSortedVectors(vect, vect_prev, &merged); // Sorted Merge transferVector(merged, &vect, I_prev, I_prev + I); // Get Max } } else { // odd step if (even_process && !first_process) { MPI_Send(&vect[0], I, MPI_FLOAT, p - 1, 0, MPI_COMM_WORLD); MPI_Recv(&vect_prev[0], I_prev, MPI_FLOAT, p - 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); mergeSortedVectors(vect, vect_prev, &merged); // Sorted Merge transferVector(merged, &vect, I_prev, I_prev + I); // Get Max } if (!even_process && !last_process) { // odd porcess MPI_Recv(&vect_next[0], I_next, MPI_FLOAT, p + 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Send(&vect[0], I, MPI_FLOAT, p + 1, 0, MPI_COMM_WORLD); mergeSortedVectors(vect, vect_next, &merged); // Sorted Merge transferVector(merged, &vect, 0, I); // Get Min } } } std::string print_msg = "Process " + std::to_string(p) + ": "; utils::print<float>(vect, print_msg); MPI_Barrier(MPI_COMM_WORLD); if (p == 0) { double exec_time = MPI_Wtime() - start_time; std::cout << "Execution time: " << exec_time << std::endl; } MPI_Finalize(); }<file_sep>#include "stdlib.h" #include <iostream> #include <stack> #include <queue> #include "binnary_tree.hpp" void DFS_preorder(binnary_tree::Node *node) { if (node == NULL) return; std::cout << node->val << " "; DFS_preorder(node->left); DFS_preorder(node->right); } void DFS_inorder(binnary_tree::Node *node) { if (node == NULL) return; DFS_inorder(node->left); std::cout << node->val << " "; DFS_inorder(node->right); } void DFS_postorder(binnary_tree::Node *node) { if (node == NULL) return; DFS_postorder(node->left); DFS_postorder(node->right); std::cout << node->val << " "; } int main() { // Construct sample graph binnary_tree::Tree tree = binnary_tree::buildExampleBinTree(); // Test traversals std::cout << "Preorder: "; DFS_preorder(tree.root); std::cout << std::endl; std::cout << "Inorder: "; DFS_inorder(tree.root); std::cout << std::endl; std::cout << "Postorder: "; DFS_postorder(tree.root); std::cout << std::endl; }<file_sep>#include "stdlib.h" #include <iostream> #include <stack> #include <queue> #include "binnary_tree.hpp" void DFS_preorder(const binnary_tree::Tree &tree) { std::cout << "Preorder: "; std::stack<binnary_tree::Node*> s; s.push(tree.root); while (!s.empty()) { binnary_tree::Node* node = s.top(); s.pop(); std::cout << node->val << " "; if (node->right != NULL) s.push(node->right); if (node->left != NULL) s.push(node->left); } std::cout << std::endl; } void DFS_inorder(const binnary_tree::Tree &tree) { std::cout << "Inorder: "; std::stack<binnary_tree::Node*> s; binnary_tree::Node *node = tree.root; while (node != NULL || !s.empty()) { while (node != NULL) { // If there is left subtree, explore it s.push(node); node = node->left; } node = s.top(); // Otherwise, go for the top of the list s.pop(); std::cout << node->val << " "; node = node->right; } std::cout << std::endl; } void BFS(const binnary_tree::Tree &tree) { std::cout << "BFS: "; std::queue<binnary_tree::Node*> s; s.push(tree.root); while (!s.empty()) { binnary_tree::Node* node = s.front(); s.pop(); std::cout << node->val << " "; if (node->left != NULL) s.push(node->left); if (node->right != NULL) s.push(node->right); } std::cout << std::endl; } int main() { binnary_tree::Tree tree = binnary_tree::buildExampleBinTree(); // Test traversals DFS_preorder(tree); DFS_inorder(tree); BFS(tree); }
c06586f8fec7e4882f7cc8f4b6b344439b7067ab
[ "Markdown", "C++", "Shell" ]
13
C++
OleguerCanal/algorithms
ee1dcfcc63a129c6d6716443d01673e3c71b14ad
4fa882d703677b0aa49b7fa32afc2ea0a9f2fb2b
refs/heads/master
<file_sep> function expressionCalculator(expr) { if (expr.includes('/ 0')) { throw Error('TypeError: Division by zero.'); } let openbrack = 0; let closebrack = 0; for (let z = 0; z < expr.length; z++) { if (expr[z] == '('){ openbrack += 1; } else if (expr[z] == ')') { closebrack += 1; } } if (closebrack !== openbrack) { throw Error('ExpressionError: Brackets must be paired') } let arr = expr.split(' '); let edit = expr.replace(/[0-9]/gi, ' $& ') if (expr.match(/\s/g) == null) { arr = edit.split(' '); } let stack1 = []; let stack2 = []; let stack3 = []; let obj = { "+": 1, "-": 1, "*": 2, "/": 2, } for (let i = 0; i < arr.length; i++) { if (isNaN(+arr[i]) == false && arr[i] !== "" ) { stack1.push(+arr[i]); } else if (isNaN(+arr[i]) && stack2.length == 0){ stack2.push(arr[i]); } else if (isNaN(+arr[i]) && obj[arr[i]] <= obj[stack2[stack2.length - 1]] && obj[stack2[stack2.length - 1]] !== "("){ if (stack2[stack2.length - 1] == "+") { let add = stack1[stack1.length -2] + stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(add); stack2.pop(); if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "+") { let add4 = stack1[stack1.length -2] + stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(add4); stack2.pop(); stack2.push(arr[i]) } else if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "-") { let sub4 = stack1[stack1.length -2] - stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(sub4); stack2.pop(); stack2.push(arr[i]) } else if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "*") { let mul4 = stack1[stack1.length -2] * stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(mul4); stack2.pop(); stack2.push(arr[i]); } else if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "/") { let div4 = stack1[stack1.length -2] / stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(div4); stack2.pop(); stack2.push(arr[i]); } else { stack2.push(arr[i]); } } else if (stack2[stack2.length - 1] == "-") { let sub = stack1[stack1.length -2] - stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(sub); stack2.pop(); if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "+") { let add4 = stack1[stack1.length -2] + stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(add4); stack2.pop(); stack2.push(arr[i]) } else if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "-") { let sub4 = stack1[stack1.length -2] - stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(sub4); stack2.pop(); stack2.push(arr[i]) } else if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "*") { let mul4 = stack1[stack1.length -2] * stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(mul4); stack2.pop(); stack2.push(arr[i]); } else if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "/") { let div4 = stack1[stack1.length -2] / stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(div4); stack2.pop(); stack2.push(arr[i]); } else { stack2.push(arr[i]); } } else if (stack2[stack2.length - 1] == "*") { let mul = stack1[stack1.length -2] * stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(mul); stack2.pop(); if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "+") { let add4 = stack1[stack1.length -2] + stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(add4); stack2.pop(); stack2.push(arr[i]) } else if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "-") { let sub4 = stack1[stack1.length -2] - stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(sub4); stack2.pop(); stack2.push(arr[i]) } else if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "*") { let mul4 = stack1[stack1.length -2] * stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(mul4); stack2.pop(); stack2.push(arr[i]); } else if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "/") { let div4 = stack1[stack1.length -2] / stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(div4); stack2.pop(); stack2.push(arr[i]); } else { stack2.push(arr[i]); } } else if (stack2[stack2.length - 1] == "/") { let div = stack1[stack1.length -2] / stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(div); stack2.pop(); if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "+") { let add4 = stack1[stack1.length -2] + stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(add4); stack2.pop(); stack2.push(arr[i]) } else if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "-") { let sub4 = stack1[stack1.length -2] - stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(sub4); stack2.pop(); stack2.push(arr[i]) } else if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "*") { let mul4 = stack1[stack1.length -2] * stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(mul4); stack2.pop(); stack2.push(arr[i]); } else if (obj[arr[i]] <= obj[stack2[stack2.length - 1]] && stack2[stack2.length - 1] == "/") { let div4 = stack1[stack1.length -2] / stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(div4); stack2.pop(); stack2.push(arr[i]); } else { stack2.push(arr[i]); } } } else if (isNaN(+arr[i]) && arr[i] !== ")") { stack2.push(arr[i]); } else if (isNaN(+arr[i]) && arr[i] == ")"){ while (stack2[stack2.length - 1] !== "(") { if (stack2[stack2.length - 1] == "+") { let add = stack1[stack1.length -2] + stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(add); stack2.pop(); } else if (stack2[stack2.length - 1] == "-") { let sub = stack1[stack1.length -2] - stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(sub); stack2.pop(); } else if (stack2[stack2.length - 1] == "*") { let mul = stack1[stack1.length -2] * stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(mul); stack2.pop(); } else if (stack2[stack2.length - 1] == "/") { let div = stack1[stack1.length -2] / stack1[stack1.length -1]; stack1.pop(); stack1.pop(); stack1.push(div); stack2.pop(); } } if ((stack2[stack2.length - 1] == "(")) { stack2.pop() } } } for (let j = 0; j < 5; j++){ if (stack2[stack2.length - 1] == "-") { let mini = stack1[stack1.length - 2] - stack1[stack1.length - 1]; stack1.pop(); stack1.pop(); stack1.push(mini); stack2.pop(); } else if (stack2[stack2.length - 1] == "+") { let sum = stack1[stack1.length - 2] + stack1[stack1.length - 1]; stack1.pop(); stack1.pop(); stack1.push(sum); stack2.pop(); } else if (stack2[stack2.length - 1] == "*") { let multic = stack1[stack1.length - 2] * stack1[stack1.length - 1]; stack1.pop(); stack1.pop(); stack1.push(multic); stack2.pop(); } else if (stack2[stack2.length - 1] == "/") { let div2 = stack1[stack1.length - 2] / stack1[stack1.length - 1]; stack1.pop(); stack1.pop(); stack1.push(div2); stack2.pop(); } } /* console.log(stack1) console.log(stack2) console.log(-(stack1[1])) */ return stack1[0]; } module.exports = { expressionCalculator }
7e56022eb781aaae3c1e6aa43ae0421d86b0d1d7
[ "JavaScript" ]
1
JavaScript
diabolicsound/expression-calculator
ec0b4d2b5c400a1259c083616ec830a526071924
07d032b40421a24000461489fbd001ba63822e49
refs/heads/master
<file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, maximum-scale=1, initial-scale=1, user-scalable=0" /> <!--[if IE]><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'><![endif]--> <title>Inscription </title> </head> <body> <div class="container"> <?php if (isset($errors) && !empty($errors)) { foreach ($errors as $error) { echo $error."\n"; } } ?> <form class="form-signin" action="/user/register" method="post"> <h2 class="form-signin-heading">Inscription</h2> <input type="text" name="username" id="username" class="form-control" placeholder="Nom d'utilisateur" required autofocus> <input type="<PASSWORD>" name="pwd" id="pwd" class="form-control" placeholder="Mot de passe" required> <input type="password" name="confirm_pwd" id="confirm_pwd" class="form-control" placeholder="Confirmation mot de passe" required> <button name="submit" class="btn btn-lg btn-primary btn-block" type="submit">Créer un compte</button> <div><a href="/user/login">Se Connecter</a></div> </form> </div> </body> <? include './footer.view.php'; ?> </html><file_sep>#!/usr/bin/env bash composer dump-autoload -o sudo ln -sf /home/hatem/PhpstormProjects/tchat/app/apache/apache.conf /etc/apache2/sites-enabled/chat.conf sudo chown www-data:www-data -R var/ sudo -u www-data chmod -R 755 var/ sudo service apache2 reload<file_sep><?php namespace Chat\Controllers; use Chat\Entities\User; use Chat\Handlers\UserHandler; class UserController extends BaseController { public function isUserLogged() { // if the user is logged in then redirect to home page // if (isset($_SESSION['loggedIn'])) { $this->redirectUrl('/'); } } function loginAction() { $this->isUserLogged(); $params = []; if ('POST' === $_SERVER['REQUEST_METHOD']) { $username = isset($_POST['username']) ? $_POST['username'] : ''; $password = isset($_POST['pwd']) ? $_POST['pwd'] : ''; $user = new User(['username'=>$username,'password'=>$password]); $userHandler = new UserHandler(); $loggedIn = $userHandler->login($user); if ($loggedIn) { $this->redirectUrl('/'); } else { $params['errors'] = $userHandler->getLoginErrors(); } } $this->RenderView('login.view.php', $params); } function logoutAction() { $userHandler = new UserHandler(); $userHandler->logout(); $this->redirectUrl('/user/login'); } function registerAction() { $this->isUserLogged(); $params = []; if ('POST' === $_SERVER['REQUEST_METHOD']) { $username = isset($_POST['username']) ? $_POST['username'] : ''; $password = isset($_POST['pwd']) ? $_POST['pwd'] : ''; $confirmPassword = isset($_POST['confirm_pwd']) ? $_POST['confirm_pwd'] : ''; $user = new User(['username'=>$username,'password'=>$password,'confirmPassword'=>$confirmPassword]); $userHandler = new UserHandler(); $registered = $userHandler->register($user); if ($registered) { $this->redirectUrl('/'); } else { $params['errors'] = $userHandler->getRegisterErrors(); } } $this->RenderView('register.view.php', $params); } } ?> <file_sep><?php namespace Chat\Controllers; class ErrorController { function notFoundAction() { echo '404 not found' ; } } ?> <file_sep><?php namespace Chat\Entities; class Message extends Entity { protected $senderId; protected $createdAt; protected $message; /** * Message constructor. */ public function __construct(array $data) { parent::__construct($data); $this->createdAt=(new \DateTime())->format('d-m-Y H:i'); } /** * @return int */ public function getSenderId() { return $this->senderId; } /** * @param int $senderId * @return $this */ public function setSenderId($senderId) { $this->senderId = $senderId; return $this; } /** * @return string */ public function getCreatedAt() { return $this->createdAt; } /** * @param \DateTime $createdAt * @return $this */ public function setCreatedAt($createdAt) { $this->createdAt = $createdAt; return $this; } /** * @return string */ public function getMessage() { return $this->message; } /** * @param string $message * @return $this */ public function setMessage($message) { $this->message = $message; return $this; } }<file_sep><?php /** * Created by PhpStorm. * User: hatem * Date: 31/01/18 * Time: 15:59 */ namespace Chat\Entities; abstract class Entity { protected $id; /** * Entity constructor. * @var array $data */ public function __construct(array $data) { $this->hydrate($data); } /** * @return int */ public function getId() { return $this->id; } /** * @param int $id * @return $this */ public function setId($id) { $this->id = $id; return $this; } public function toArray() { return get_object_vars($this); } public function hydrate(array $data) { foreach ($data as $key => $value) { $method = 'set'.ucfirst($key); if (method_exists($this, $method)) { $this->$method($value); } } } }<file_sep><?php /** * Created by PhpStorm. * User: hatem * Date: 31/01/18 * Time: 19:29 */ namespace Chat\Handlers; use Chat\Entities\User; use Chat\Repositories\BaseRepository; use Chat\Repositories\RepositoryManager; class UserHandler { /** * @var BaseRepository $entityRepository . */ protected $entityRepository; /** * @var array $errors . */ protected $errors = []; /** * @var array $connectedUsers . */ protected static $connectedUsers = []; /** * UserHandler constructor. */ public function __construct() { $this->entityRepository = RepositoryManager::getRepository('user'); $this->errors = ['login' => [], 'register' => []]; } public function login(User $user) { /**@var User $entity */ $entity = $this->entityRepository->findOne(['username' => $user->getUsername()]); if ($entity) { if (password_verify($user->getPassword(),$entity->getPassword())) { $_SESSION['loggedIn'] = $entity->getId(); $this->addConnectedUser($user); return true; } } $this->addLoginError('Merci de vérifier vos identifiants'); return false; } public function getLoginErrors() { return $this->errors['login']; } public function register(User $user) { if (!$user->getUsername() || !$user->getPassword() || !$user->getConfirmPassword()) { $this->addRegisterError('Tous les champs sont obligatoires!'); } if ($user->getConfirmPassword() !== $user->getPassword()) { $this->addRegisterError('les deux mots de passe doivent etre indentiques!'); } /**@var User $entity */ $entity = $this->entityRepository->findOne(['username' => $user->getUsername()]); if (!$entity) { $user->cryptPassword(); $this->entityRepository->add($user); $_SESSION['loggedIn'] = $user->getId(); $this->addConnectedUser($user); return true; } if ($user->getUsername() === $entity->getUsername()) { $this->addRegisterError('le nom d\'utilisateur existe déja !'); } return false; } public function getRegisterErrors() { return $this->errors['register']; } protected function addLoginError($error) { $this->errors['login'][] = $error; } protected function addRegisterError($error) { $this->errors['register'][] = $error; } public function logout() { /**@var User $entity */ $user = $this->entityRepository->findOne(['id' => $_SESSION['loggedIn']]); if ($user) { $this->removeConnectedUser($user); unset($_SESSION['loggedIn']); } } protected function addConnectedUser(User $user=null) { //todo add connected user// } protected function removeConnectedUser(User $user=null) { //todo remove connected user// } public static function getConnectedUsers() { $connectedUsers=['hatem']; //todo get connected users// return $connectedUsers; } }<file_sep><?php /** * Created by PhpStorm. * User: hatem * Date: 30/01/18 * Time: 17:56 */ class App { static public function handleRequest() { if(!isset($_SESSION)) { session_start(); } $uri = $_SERVER['REQUEST_URI']; // try to extract the controller and action from uri string // list(, $controller, $action) = explode('/', $uri); self::runAction($controller, $action); } public static function runAction($controller, $action) { $controller=($controller)?:'default'; $action=($action)?:'index'; $controller = "Chat\Controllers\\".ucfirst($controller)."Controller"; $action = "{$action}Action"; //validate requested controller and action // if (class_exists($controller)) { $controller = new $controller(); if (method_exists($controller, $action)) { $controller->$action(); die(); } } // if the controller doesn't exist then we redirect to not found action // self::runAction("error", "notFound"); } }<file_sep># Chat MVC An MVC chat application example. ## Requirement : - apache server <=2.4 - php version <= 5.6 ## Configuration : - import the schema in dump/db_chat - Copy the app/apache/apache.conf.dist file to app/apache/apache.conf and replace <PATH_TO_YOUR_PROJECT> by your project path - Copy the app/config/config.php.dist file to app/config/config.php and replace the <db_user> and <db_pwd> by your credentials - Run php composer.phar run-script load-project - Go to http://chat.localhost <file_sep><?php namespace Chat\Repositories; class RepositoryManager { /** * @var string $repositoryName * @return BaseRepository|| null */ public static function getRepository($repositoryName) { $repositoryClass="Chat\Repositories\\".ucfirst($repositoryName.'Repository'); if(class_exists($repositoryClass)){ return new $repositoryClass($repositoryName); }else{ echo 'Error class repository not found'; die; } } }<file_sep><?php /** * Created by PhpStorm. * User: hatem * Date: 31/01/18 * Time: 19:39 */ namespace Chat\Handlers; use Chat\Entities\Message; use Chat\Repositories\BaseRepository; use Chat\Repositories\RepositoryManager; class MessageHandler { /** * @var BaseRepository $entityRepository . */ protected $entityRepository; /** * @var array $errors . */ protected $errors = []; /** * UserHandler constructor. */ public function __construct() { $this->entityRepository = RepositoryManager::getRepository('message'); $this->errors = ['add_message' => []]; } public function add(Message $message) { if (empty($message->getMessage())) { $this->addAddMessageError('Votre message est vide !'); return false; } $this->entityRepository->add($message); return true; } public function getAddMessageErrors() { return $this->errors['add_message']; } protected function addAddMessageError($error) { $this->errors['add_message'][] = $error; } public function getMessages(){ $messages = $this->entityRepository->findAll([],['createdAt'=>'desc'],'array'); return $messages; } }<file_sep><?php namespace Chat\Repositories; class UserRepository extends BaseRepository { public function getTableName() { return 'user'; } }<file_sep><?php namespace Chat\Repositories; class MessageRepository extends BaseRepository { public function getTableName() { return 'message'; } protected function findBy(array $fields = [],$sort=['id'=>'desc']) { $searchValues = []; $statement = "SELECT u.username as senderId ,m.message as message , m.createdAt as createdAt FROM {$this->table} m left join user u on m.senderId=u.id"; if (!empty($fields)) { $statement .= ' where 1=1 '; foreach ($fields as $fieldName => $fieldValue) { $statement .= "AND $fieldName = ? "; $searchValues[] = $fieldValue; } } if(!empty($sort)){ $statement .= ' order by '; foreach ($sort as $key=>$value){ $statement.="$key $value"; } } $query = self::getDBInstance()->prepare($statement); $query->setFetchMode(\PDO::FETCH_ASSOC); $result=$query->execute($searchValues); if ($result) { return $query; } else { var_dump( $query->errorInfo()); die; } } }<file_sep><?php namespace Chat\Controllers; abstract class BaseController { protected function renderView($template, array $vars = array()) { extract($vars); include '../src/Views/'.$template; } protected function redirectUrl($url) { header("location: $url",true,302); exit(); } } ?> <file_sep><?php namespace Chat\Repositories; use Chat\Entities\Entity; abstract class BaseRepository { /** @var null|\PDO $connection */ protected static $connection = null; /** @var string $table */ protected $table; /** @var string $class */ protected $class; public function __construct($class) { self::getDBInstance(); $this->table = $this->getTableName(); $this->class = $class; } /** * @return \PDO */ public static function getDBInstance() { if (!isset(self::$connection)) { try { $config = \Config::getDbConfig(); self::$connection = new \PDO($config['db_dsn'], $config['db_user'], $config['db_pwd']); } catch (\PDOException $e) { echo 'Connection failed: '.$e->getMessage(); die; } } return self::$connection; } public function add(Entity $entity) { $statement = "INSERT INTO {$this->table}("; $statementValues = []; $statementNames = []; $values = []; foreach ($entity->toArray() as $fieldName => $fieldValue) { $statementNames[] = $fieldName; $statementValues[] = "?"; $values[] = $fieldValue; } $statement .= implode(',', $statementNames).') VALUES('.implode(',', $statementValues).')'; $query = self::getDBInstance()->prepare($statement); $result = $query->execute($values); if ($result) { $id = self::getDBInstance()->lastInsertId(); $entity->setId($id); return $id; } else { var_dump( $query->errorInfo()); die; } } public function delete(Entity $entity) { $statement = "DELETE FROM {$this->table} WHERE id = ?"; $query = self::getDBInstance()->prepare($statement); $query->execute($entity->getId()); } public function update(Entity $entity) { $statement = "UPDATE {$this->table} SET ("; $values = []; if (!empty($entity->toArray())) { $statementPieces = []; foreach ($entity->toArray() as $fieldName => $fieldValue) { $statementPieces = "$fieldName = ? "; $values[] = $fieldValue; } $statement .= implode(',', $statementPieces); } $statement .= " WHERE id = ?"; $query = self::getDBInstance()->prepare($statement); $query->execute($values); } public function findOne(array $fields = [],$sort=['id'=>'desc']) { $query = $this->findBy($fields,$sort); $result = $query->fetch(); if($result){ $entity="Chat\Entities\\".ucfirst($this->class); /**@var Entity $entity */ $entity = new $entity($result); return $entity; } return null; } public function findAll(array $fields = [],$sort=['id'=>'desc'],$type='object') { $arrayResult = []; $query = $this->findBy($fields,$sort); $result = $query->fetchAll(); if('object'===$type){ // hydrate the result to an array // foreach ($result as $element) { $entity="Chat\Entities\\".ucfirst($this->class); $arrayResult[] = new $entity($element); } $result=$arrayResult; } return $result; } protected function findBy(array $fields = [],$sort=['id'=>'desc']) { $searchValues = []; $statement = "SELECT * FROM {$this->table}"; if (!empty($fields)) { $statement .= ' where 1=1 '; foreach ($fields as $fieldName => $fieldValue) { $statement .= "AND $fieldName = ? "; $searchValues[] = $fieldValue; } } if(!empty($sort)){ $statement .= ' order by '; foreach ($sort as $key=>$value){ $statement.="$key $value"; } } $query = self::getDBInstance()->prepare($statement); $query->setFetchMode(\PDO::FETCH_ASSOC); $result=$query->execute($searchValues); if ($result) { return $query; } else { var_dump( $query->errorInfo()); die; } } public abstract function getTableName(); }<file_sep><?php namespace Chat\Entities; class User extends Entity { protected $username; protected $password; protected $confirmPassword; /** * @return mixed */ public function getUsername() { return $this->username; } /** * @param mixed $username * @return $this */ public function setUsername($username) { $this->username = $username; return $this; } /** * @return string */ public function getPassword() { return $this->password; } /** * @param string $password * @return $this */ public function setPassword($password) { $this->password = $password; return $this; } /** * @return string */ public function getConfirmPassword() { return $this->confirmPassword; } /** * @param string $confirmPassword * @return $this */ public function setConfirmPassword($confirmPassword) { $this->confirmPassword = $confirmPassword; return $this; } /** * @return $this */ public function cryptPassword() { $this->password = password_hash($this->password, PASSWORD_BCRYPT); return $this; } public function toArray() { $attributes = get_object_vars($this); unset($attributes['confirmPassword']); return $attributes; } }<file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, maximum-scale=1, initial-scale=1, user-scalable=0" /> <!--[if IE]><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'><![endif]--> <title>Chat </title> <!-- CORE CSS --> <link href="/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="/plugins/bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" type="text/css" /> <!-- THEME CSS --> <link href="/css/custom.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="container"> <div><a href="/user/logout">Déconnexion</a></div> <h4> Utilisateurs connectés</h4> <?php if (isset($connectedUsers) && !empty($connectedUsers)) { foreach ($connectedUsers as $connectedUser) { echo $connectedUser."\n"; } } ?> <h4>Discussion</h4> <div id="messages"></div> <h4>Envoyé votre message</h4> <form id="form-message" method="post" action="/"> <input type="text" name="message" id="message" placeholder="Votre message" required="required"> <input type="submit" value="Envoyer"> </form> </div> </body> <script type="text/javascript" src="/js/jquery-2.1.4.min.js"></script> <script type="text/javascript" src="/plugins/bootstrap/js/bootstrap.min.js"></script> <script type="text/javascript" src="/js/front.js"></script> <script type="text/javascript" src="/js/chat.js"></script> </html><file_sep><?php namespace Chat\Controllers; use Chat\Entities\Message; use Chat\Handlers\MessageHandler; use Chat\Handlers\UserHandler; class DefaultController extends BaseController { /** * UserController constructor. */ public function __construct() { //if the user is not logged in and requested a protected resource redirect to login// if (!isset($_SESSION['loggedIn'])) { $this->redirectUrl('/user/login'); } } public function indexAction() { $params = []; $params['connectedUsers'] = UserHandler::getConnectedUsers(); if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest') { $messageHandler = new MessageHandler(); if ('POST' === $_SERVER['REQUEST_METHOD']) { $message = isset($_POST['message']) ? $_POST['message'] : ''; $message = new Message(['message' => $message, 'senderId' => $_SESSION['loggedIn']]); $added = $messageHandler->add($message); if ($added) { $response = ['success' => true]; } else { $response = ['success' => false, 'errors' => $messageHandler->getAddMessageErrors()]; } } else { $messages = $messageHandler->getMessages(); if (!empty($messages)) { $response = ['success' => true, 'messages' => $messages]; } else { $response = ['success' => false]; } } echo json_encode($response); } else { $this->RenderView('chat.view.php', $params); } } } ?>
160639b9e7755679b3cdccdc9e7852b95d303e1f
[ "Markdown", "PHP", "Shell" ]
18
PHP
hatemHsen/chatMvc
6829f5c97dcb56c3f3e8e5efe171cb8928744d97
c032c619d1c93f9fff223a908f715f041dc110be
refs/heads/master
<file_sep>Ruby ==== Almost any version of Ruby will work. It's just so that you can use the helper Rake tasks. Most systems even ship with some version of Ruby (and thus Rake) anymore. ## Installation For additional help, see: * [https://www.ruby-lang.org/en/downloads/](https://www.ruby-lang.org/en/downloads/) * [http://rvm.io/](http://rvm.io/) * [https://github.com/sstephenson/rbenv](https://github.com/sstephenson/rbenv) ## Version I currently run `v2.1.4` <file_sep>Vagrant ======= ## Installation See: http://www.vagrantup.com/downloads.html You should _NOT_ be running the version from RubyGems. ## Version I currently run `v1.6.5` <file_sep>[vagrant] 127.0.0.1 [vagrant:vars] ansible_ssh_port=2222 ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key ansible_ssh_user=vagrant [local:children] vagrant <file_sep># -*- mode: ruby -*- # vi: set ft=ruby : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = '2' Vagrant.configure VAGRANTFILE_API_VERSION do | config | # Every Vagrant virtual environment requires a box to build off of. config.vm.box = 'ubuntu/trusty64' # If true, then any SSH connections made will enable agent forwarding. # Default value: false # config.ssh.forward_agent = true # VMs get 3Gb of RAM (need a min of 2048 + room for OS) # 3Gb = 1024Mb + 2048Mb = 3072Mb config.vm.provider 'virtualbox' do | virtualbox | virtualbox.customize [ 'modifyvm' , :id , '--memory' , '3072' ] end config.vm.provision 'ansible_local' do | ansible | ansible.playbook = 'urbit.yml' ansible.extra_vars = {ansible_ssh_user: 'vagrant'} end end <file_sep>Ansible ======= ## Installation See: http://docs.ansible.com/intro_installation.html **NB: Installation via Homebrew should probably work?** I maintain a local git clone that I checkout specific version tags on. Here is my `.zshrc` snippet to load it when you start a new shell: ```shell # Ansible cd ~/Workspace/OpenSource/ansible source hacking/env-setup -q cd - > /dev/null ``` Obviously, you'll change the initial directory you `cd` into. ## Version I currently run `v1.6.6` <file_sep>require_relative 'util' desc 'Create a backup of your current pier' task :backup => %w( vagrant:up urbit:backup ) desc 'Reset Urbit, backup your pier, and run Arvo' task :breach => %w( vagrant:up urbit:breach urbit:shell ) desc 'Run Arvo ((DEFAULT))' task :shell => %w( vagrant:up urbit:shell ) task :default => :shell namespace :urbit do task :backup do Util.vagrant \ 'cd /vagrant', 'ansible-playbook backup.yml -i hosts/local.ini --connection=local' end task :breach do Util.vagrant \ 'cd /vagrant', 'ansible-playbook breach.yml -i hosts/local.ini --connection=local' end task :shell do name = 'mypier' path = File.expand_path \ name, File.dirname( __FILE__ ) opts = '-v' opts << 'c' unless Dir.exist?( path ) Util.vagrant \ 'vere', opts, "/vagrant/#{ name }", :joiner => ' ' end end namespace :vagrant do task :up do Util.vagrant \ :command => 'up', :opts => [] end end <file_sep>Urbit Vagrant Environment ========================= A simple Vagrant environment that builds Urbit from source in an Ubuntu box and provides a simple Rake task for accessing your Urbit pier shell. ## Installation ### Requirements See `doc/` for instructions on how to install Ansible, Ruby, and Vagrant. ### Steps 1. Clone this project 2. `cd` into the project directory 3. Run `rake` ## Usage Just run `rake`. The first time you run `rake`, it will call `vere` with the '-c' option to create your pier in the `mypier` folder in your project directory. All subsequent invocations of `rake` will not use the '-c' flag and will just log you into your shell. Calling `rake` without any arguments, as recommended above, runs the default task which is `shell`. Run `rake -T` to see a list of helpful tasks. ### Breach In the event that Tlon has breached Urbit and you need to reset, there is a Rake task you can run to reset your pier and create a backup of your old one. ```bash rake breach ``` If you just want to create a backup without resetting your pier, you can do so with the `backup` Rake task. ```bash rake backup ``` ## Helpful Links * [Urbit](http://urbit.org/) * [Urbit Documentation](http://urbit.org/docs/) * [Urbit Source](https://github.com/urbit/urbit) * [Urbit Developers Mailing List](https://groups.google.com/forum/#!forum/urbit-dev) ## Help & Support Please use Github Issues in this repo to describe and discuss problems. Also, feel free to discuss with me in `:chat`. I'm `~binbec-satmep`. Lastly, you can find me elsewhere online. ## Contributing 1. Fork it ( https://github.com/cookrn/urbit-vagrant/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request ## License MIT. See: [LICENSE](https://github.com/cookrn/urbit-vagrant/blob/master/LICENSE) <file_sep>module Util extend self def vagrant( *cmds ) options = cmds.pop if cmds.last.is_a?( Hash ) options ||= Hash.new options[ :command ] ||= 'ssh' options[ :exec ] ||= :system options[ :joiner ] ||= ' && ' options[ :opts ] ||= [ '-c' ] options[ :fail ] = true if options[ :fail ].nil? options[ :join ] = true if options[ :join ].nil? cmd_args = [ options[ :exec ], 'vagrant', options[ :command ] ] cmd_args.concat( options[ :opts ] ) if options[ :opts ].any? if cmds.any? cmd_args.concat( Array( if options[ :join ] cmds.join options[ :joiner ] else cmds end ) ) end result = send *cmd_args if options[ :fail ] && !result warn "Unable to run command: #{ cmd_args.join ' ' }" exit 1 end return result end end
c7eb5cccc1d1029f961a104e707199a13eb153e6
[ "Markdown", "Ruby", "INI" ]
8
Markdown
OCForks/urbit-vagrant
345c4346549eb71539da773624f6b255ef33ceb5
b47649ae91a61b2401e9f5698c15f9128600cd3a
refs/heads/master
<file_sep>(function () { let tooltipButton = document.querySelector('.tooltip__btn--category'); let tooltipBody = document.querySelector('.tooltip__body--category'); tooltipButton.addEventListener('click', function (event) { event.preventDefault(); tooltipBody.classList.toggle('tooltip__body--visible'); }); let tooltipButton2 = document.querySelector('.tooltip__btn--2'); let tooltipBody2 = document.querySelector('.tooltip__body--2'); tooltipButton2.addEventListener('click', function (event) { event.preventDefault(); tooltipBody2.classList.toggle('tooltip__body--visible'); }); document.documentElement.addEventListener("click", function (e) { if (!e.target.closest('.tooltip__btn--category')) { tooltipBody.classList.remove('tooltip__body--visible') } }); document.documentElement.addEventListener("click", function (e) { if (!e.target.closest('.tooltip__btn--2')) { tooltipBody2.classList.remove('tooltip__body--visible') } }); })();
f05a581ba09aa245c97bdaca8261d88a886916ca
[ "JavaScript" ]
1
JavaScript
askomarov/wispo-test
3e6dfa9b3daef99fd82750eff9d40da1c1f31a9c
c86b5386c2582efd72274ec9f4c3b4681e905dc6
refs/heads/master
<repo_name>skywa/ExData_Plotting1<file_sep>/plot3.R #Read in data from 2007/2/1 to 2007/2/2 (text file processed manually) data <- read.csv("C:/Users/swaye/Desktop/mooc/Coursera/4_Exploratory_Data_Analysis/Course Project 1/household_power_consumption_cut.txt", sep=";", na.strings="?") #Combine date and time columns and format data$DateTime <- strptime(paste(data$Date,data$Time),"%Y-%m-%d %H:%M:%S") #Open PNG device png(file = "plot3.png", width = 480, height = 480) #Plot lines of energy sub-metering 1, 2, and 3 with(data, { plot(data$DateTime, data$Sub_metering_1, main="", type = "l", col = "black", xlab = "", ylab = "Energy sub metering") lines(data$DateTime, data$Sub_metering_2, main="", type = "l", col = "red") lines(data$DateTime, data$Sub_metering_3, main="", type = "l", col = "blue")}) legend("topright", lwd=1, lty=c(1,1,1), col = c("black", "red" ,"blue"), legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3")) #Close PNG device dev.off()<file_sep>/plot4.R #Read in data from 2007/2/1 to 2007/2/2 (text file processed manually) data <- read.csv("C:/Users/swaye/Desktop/mooc/Coursera/4_Exploratory_Data_Analysis/Course Project 1/household_power_consumption_cut.txt", sep=";", na.strings="?") #Combine date and time columns and format data$DateTime <- strptime(paste(data$Date,data$Time),"%Y-%m-%d %H:%M:%S") #Open PNG device png(file = "plot4.png", width = 480, height = 480) #Plot 4 plots of Global active power time series, voltage, energy sub-metering 1, 2, and 3, and Global reactive power par(mfrow = c(2, 2)) with(data, { #Global active power plot plot(data$DateTime, data$Global_active_power, type = "l", xlab = "", ylab = "Global Active Power (kilowatts)", main = "") #Voltage plot plot(data$DateTime, data$Voltage, type = "l", xlab = "datetime", ylab = "Voltage", main = "") #Energy sub-metering plots with(data, { plot(data$DateTime, data$Sub_metering_1, main="", type = "l", col = "black", xlab = "", ylab = "Energy sub metering") lines(data$DateTime, data$Sub_metering_2, main="", type = "l", col = "red") lines(data$DateTime, data$Sub_metering_3, main="", type = "l", col = "blue")}) legend("topright", lwd=1, lty=c(1,1,1), col = c("black", "red","blue"), bty = "n", legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3")) #Global reactive power plot plot(data$DateTime, data$Global_reactive_power, type = "l", xlab = "datetime", ylab = "Global_reactive_power", main = "") }) #Close PNG device dev.off()<file_sep>/plot1.R #Read in data from 2007/2/1 to 2007/2/2 (text file processed manually) data <- read.csv("C:/Users/swaye/Desktop/mooc/Coursera/4_Exploratory_Data_Analysis/Course Project 1/household_power_consumption_cut.txt", sep=";", na.strings="?") #Open PNG device png(file = "~\\plot1.png", width = 480, height = 480) #Plot histogram of Global Active Power hist(data$Global_active_power, col = "red", xlab = "Global Active Power (kilowatts)", main = "Global Active Power") #Close PNG device dev.off()<file_sep>/plot2.R #Read in data from 2007/2/1 to 2007/2/2 (text file processed manually) data <- read.csv("C:/Users/swaye/Desktop/mooc/Coursera/4_Exploratory_Data_Analysis/Course Project 1/household_power_consumption_cut.txt", sep=";", na.strings="?") #Combine date and time columns and format data$DateTime <- strptime(paste(data$Date,data$Time),"%Y-%m-%d %H:%M:%S") #Open PNG device png(file = "plot2.png", width = 480, height = 480) #Plot time series of Global Active Power plot(data$DateTime,data$Global_active_power, type = "l", xlab = "", ylab = "Global Active Power (kilowatts)", main = "") #Close PNG device dev.off()
0425416baaf89ed15c2fd54e4b31b5a548d09931
[ "R" ]
4
R
skywa/ExData_Plotting1
fe9e541c0318b6fb26872668948faa2352743e1b
31fe6878a4dc02af926e74630faf0fd3c7a7ed67
refs/heads/master
<file_sep><?php /** * * * */ namespace PrimitivePlus; interface EntityInterface { static function schema(); function checkErrors(); } abstract class Entity implements EntityInterface, \IteratorAggregate, \Countable { const BOOL = 'boolean' , INT = 'integer' , DBL = 'double' , STR = 'string' , CALL = 'callable' , ARR = 'array' , RES = 'resource' , OBJ = 'object' ; private $_storage = array(); private $_freezed = false; static private $_schemaCache = array(); final function __construct() { $class = get_class($this); $schema = $this->schema(); if (! is_array($schema)) { throw new \DomainException("$class::schema() must return array."); } foreach ($schema as $key => $value) { $type = gettype($value); switch ($type) { case self::ARR: if (!is_string($value[0])) { throw new \DomainException( "$class::schema()[$key] must be array(string [, default])." ); } $schema[$key] = $value[0]; $this->_storage[$key] = isset($value[1]) ? $value[1] : null; break; case self::STR: case self::BOOL: case self::INT: case self::RES: case self::DBL: $schema[$key] = $type; $this->_storage[$key] = $value; break; case self::OBJ: $schemaclass = get_class($value); $schema[$key] = $schemaclass; $this->_storage[$key] = $value; break; default: throw new \DomainException("$class::schema()[$key] is invalid."); } } if (!isset(self::$_schemaCache[$class])) { self::$_schemaCache[$class] = $schema; } call_user_func_array(array($this,'init'), func_get_args()); } function init() {} final function __get($label) { if (! array_key_exists($label, $this->_storage)) { throw new \OutOfRangeException(get_class($this) . "->$label is not defined."); } return $this->_storage[$label]; } final function __set($label, $value) { if ($this->_freezed) { throw new \DomainException("Object is freezed."); } $class = get_class($this); $schema = self::$_schemaCache[$class]; if (! array_key_exists($label, $schema)) { throw new \OutOfRangeException("$class->$label is not defined."); } switch ($schema[$label]) { case self::CALL: if (is_callable($value)) { $this->_storage[$label] = $value; return; } break; case self::BOOL: case self::INT: case self::DBL: case self::STR: case self::ARR: case self::OBJ: case self::RESOURCE: if (gettype($value) === $schema[$label]) { $this->_storage[$label] = $value; return; } break; default: if ($value instanceof $schema[$label]) { $this->_storage[$label] = $value; return; } } throw new \InvalidArgumentException("$class->$value must be {$schema[$label]}."); } final function toArray() { return $this->_storage; } final function fromArray(array $newData) { $schema = self::$_schemaCache[get_class($this)]; foreach ($newData as $key => $value) { if (array_key_exists($key, $schema)) { $this->__set($key, $value); } else { trigger_error("$key is not defined. ignored."); } } } final function freeze() { $this->_freezed = true; } function getIterator() { return new \ArrayIterator($this->_storage); } function count() { return count($this->_storage); } /** * for DCI */ final protected static function _cast(self $entity) { $self = new static; $self->_storage =& $entity->_storage; $self->_freezed =& $entity->_freezed; return $self; } } <file_sep><?php namespace PrimitivePlus; class Collection extends \ArrayObject { function join($str) { $self = (array)$this; return implode($str, $self); } function has($needle, $strict=true) { $self = (array)$this; return in_array($needle, $self, $strict); } function __call($method, $args) { $method = preg_replace('/[A-Z]/', '_$0', $method); $lastPos = strlen($method) - 1; if ($method[$lastPos] === '_') { $method = substr($method, 0, -1); $chain = true; } else { $chain = false; } $func = 'array_' . $method; $self = (array)$this; $args = array_merge(array(&$self), $args); if (!function_exists($func)) { throw new \BadMethodCallException; } $res = call_user_func_array($func, $args); if (is_array($res)) { $this->exchangeArray($res); return $this; } elseif ($chain) { $this->exchangeArray($self); return $this; } else { return $res; } } function __toString() { return json_encode($this->toArray()); } function toArray() { $arr = (array)$this; foreach ($arr as &$val) { if ($val instanceof self) { $val = $val->toArray(); } } unset($val); return $arr; } } <file_sep>php-PrimitivePlus ================= Primitive wrapping Classes ## Entity A Class for User-Defined Type in PHP. ```php <?php class Foo extends PrimitivePlus\Entity { static function schema() { return array( 'int' => 0, // integer 'dbl' => 1.1, // double 'str' => 'some text', //string 'boo' => true, //boolean ); } function checkErrors() { return array(); } } $tri = new Foo; $tri->int = 1; // success //$tri->int = '5'; //throw Exception ``` ### for DCI (Data, Context and Interactions) by cast() method ```php <?php class User extends PrimitivePlus\Entity { static function schema() { return array( 'name' => '', 'email' => '<EMAIL>', ); } static function cast(self $user) { return parent::_cast($user); } function checkErrors() { return array(); } } ``` <file_sep><?php use PrimitivePlus\Entity; class User extends Entity { static function schema() { return array( 'name' => '', 'email' => array(self::STR), ); } function checkErrors() { return array(); } static function cast(self $user) { return parent::_cast($user); } } class Administrator extends User { function adminMethod() { return 'adminMethod!'; } } class Viewer extends User { function viewerMethod() { return 'viewerMethod!'; } } class EntityTest extends PHPUnit_Framework_TestCase { /** * @test */ function テストケース() { $user = new User; $user->name = 'taro'; $user->email = '<EMAIL>'; $admin = Administrator::cast($user); $admin->name = 'hanako'; $this->assertEquals('hanako', $user->name); $this->assertEquals('adminMethod!', $admin->adminMethod()); $viewer = Viewer::cast($user); $this->assertEquals('viewerMethod!', $viewer->viewerMethod()); } }
9dcb6fe69abf5631ba7157000ff9ad42367cfd8d
[ "Markdown", "PHP" ]
4
PHP
hirak/php-PrimitivePlus
3639aae0f4530a3cf9b138c200323913174c22d1
f3e58ccbaa59db2c8dc87258e352c7abfdb9ee77
refs/heads/main
<file_sep>from django.db import models from django.core import validators from django.conf import settings from usuario.models import User from core.choices import BRANCH_ACTIVITY, BRANCH_TYPE # Create your models here. class Empregador(models.Model): user = models.OneToOneField (User, related_name='empregador', on_delete=models.CASCADE) cnpj = models.CharField('CNPJ', max_length = 18, blank = False) nome = models.CharField('Nome Fantasia',max_length = 50,null=True, blank=True) ramo = models.CharField( 'Ramo de Atividade', max_length=25, null=True, blank=True, choices=BRANCH_ACTIVITY, ) tipo = models.CharField( 'Tipo da Empresa', max_length=25, null=True, blank=True, choices=BRANCH_TYPE, ) tel1 = models.CharField('Tel(1)',max_length = 12,null=True, blank=True) tel2 = models.CharField('Tel(2)',max_length = 12, null=True, blank=True) logradouro = models.CharField('Endereço',max_length = 100, null=True, blank=True) numeroLog = models.CharField('Número', max_length = 10, null=True, blank=True) bairro = models.CharField('Bairro', max_length = 50, null=True, blank=True) complemento = models.CharField('Complemento', max_length = 100, null=True, blank=True) cep = models.CharField('CEP', max_length = 10, null=True, blank=True) cidade = models.CharField('Cidade', max_length = 50, null=True, blank=True) uf = models.CharField('UF', max_length = 50, null=True, blank=True) def __str__(self): return self.nome <file_sep># Generated by Django 2.0.2 on 2018-04-02 13:38 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Empregador', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('cnpj', models.CharField(max_length=18, verbose_name='CNPJ')), ('nome', models.CharField(blank=True, max_length=50, null=True, verbose_name='Nome Fantasia')), ('ramo', models.CharField(blank=True, choices=[('', ''), ('Industria', 'Indústria'), ('Comercio', 'Comércio'), ('Prestacao de Servicos', 'Prestação de Serviços'), ('Outros', 'Outros')], max_length=25, null=True, verbose_name='Ramo de Atividade')), ('tipo', models.CharField(blank=True, choices=[('', ''), ('MEI', 'MEI - Faturamento até R$ 81 mil'), ('ME', 'ME - Faturamento até R$ 360 mil'), ('EPP', 'EPP - Faturamento até R$ 3,6 milhões'), ('Empresa Normal', 'Empresa Normal - Faturamento superior a R$ 3,6 milhões')], max_length=25, null=True, verbose_name='Tipo da Empresa')), ('tel1', models.CharField(blank=True, max_length=12, null=True, verbose_name='Tel(1)')), ('tel2', models.CharField(blank=True, max_length=12, null=True, verbose_name='Tel(2)')), ('logradouro', models.CharField(blank=True, max_length=100, null=True, verbose_name='Endereço')), ('numeroLog', models.CharField(blank=True, max_length=10, null=True, verbose_name='Número')), ('bairro', models.CharField(blank=True, max_length=50, null=True, verbose_name='Bairro')), ('complemento', models.CharField(blank=True, max_length=100, null=True, verbose_name='Complemento')), ('cep', models.CharField(blank=True, max_length=10, null=True, verbose_name='CEP')), ('cidade', models.CharField(blank=True, max_length=50, null=True, verbose_name='Cidade')), ('uf', models.CharField(blank=True, max_length=50, null=True, verbose_name='UF')), ], ), ] <file_sep>from django.conf.urls import include, url from django.urls import path from django.contrib.auth.views import LoginView, LogoutView from . import views app_name='usuario' urlpatterns = [ path("password_reset", views.password_reset, name='password_reset'), path('confirmar-nova-senha/<key>', views.password_reset_confirm, name='password_reset_confirm'), path('editar-senha/', views.edit_password, name='edit_password'), path('login/', LoginView.as_view(template_name = 'login.html'), name='login'), path('logout/', LogoutView.as_view(next_page= 'core:home'), name='logout'), path('cadastre-se_candidato/', views.register, name='register'), path('cadastre-se_empregador/', views.register_empregador, name='register_empregador'), path('painel/', views.dashboard, name='dashboard'), path('teste/', views.choice_register, name='choice_register'), ] <file_sep># Generated by Django 2.0.2 on 2018-04-03 12:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('vagas', '0002_vaga_inscritos'), ] operations = [ migrations.AlterField( model_name='vaga', name='inscritos', field=models.PositiveSmallIntegerField(blank=True, null=True, verbose_name='Quantidade de inscritos'), ), ] <file_sep>from django.template import Library register = Library() from candidato.models import * from usuario.models import User @register.inclusion_tag('templatetags/experiencia_tag.html') def experienciastag(user): experiencias = Experiencia.objects.filter(candidato = user.candidato) context = { 'experiencias': experiencias, } return context <file_sep>from django.template import Library from django.contrib.auth import authenticate, login, get_user_model register = Library() User = get_user_model() from vagas.models import * from candidato.models import Candidato from usuario.models import User @register.inclusion_tag('templatetags/minhas_candidaturas_tag.html') def minhascandidaturastag(user): candidato = Candidato.objects.get(user_id = user.id) candidaturas = Candidatura.objects.filter(candidato_id = candidato.id) tag = [] for candidatura in candidaturas: if candidatura.vaga.finalizada == False: tag.append(candidatura) context = { 'tag': tag, } return context <file_sep>from django.contrib import admin from usuario.models import * from candidato.models import * from usuario.forms import UserAdminCreationForm, UserForm from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import UserChangeForm from candidato.models import Experiencia, Formacao, Idioma, Candidato class UserAdmin(BaseUserAdmin): add_form = UserAdminCreationForm add_fieldsets = ( (None, { 'fields': ('username', 'name', 'email', 'user_type','<PASSWORD>', '<PASSWORD>') }), ) form = UserForm fieldsets = ( (None, { 'fields': ('username', 'email', 'user_type') }), ('Informações Básicas', { 'fields': ('name',) }), ( 'Permissões', { 'fields': ( 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions' ) } ), ) list_display = ['username', 'name', 'email', 'user_type', 'is_active', 'is_staff', 'date_joined'] admin.site.register(User,UserAdmin) <file_sep>from django.template import Library register = Library() from candidato.models import * from usuario.models import User @register.inclusion_tag('templatetags/idioma_tag.html') def idiomastag(user): idiomas = Idioma.objects.filter(candidato = user.candidato) context = { 'idiomas': idiomas } return context<file_sep>from django.template import Library register = Library() from candidato.models import * from usuario.models import User @register.inclusion_tag('templatetags/pretencoes_tag.html') def pretencoestag(user): pretencoes = Pretencoes.objects.filter(candidato = user.candidato) context = { 'pretencoes': pretencoes } return context <file_sep>from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import authenticate, login, get_user_model from django.contrib.auth.decorators import login_required from django.conf import settings from django.contrib import messages from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .models import * User = get_user_model() # Create your views here. @login_required def mural_de_vagas(request): vagas_list = Vaga.objects.filter(status = True, finalizada = False).order_by('-data_criacao') var_get_search = request.GET.get('search_box', None) if var_get_search: vagas_list = Vaga.objects.filter(status = True, finalizada = False, funcao__icontains=var_get_search).order_by('-data_criacao') paginator = Paginator(vagas_list, 15) try: page = (request.GET.get('page', '1')) except ValueError: page = 1 try: vagas = paginator.page(page) except (EmptyPage, InvalidPage): vagas = paginator.page(1) index = vagas.number - 1 max_index = len(paginator.page_range) start_index = index - 3 if index >= 3 else 0 end_index = index + 3 if index <= max_index - 3 else max_index page_range = paginator.page_range[start_index:end_index] template_name = 'mural_de_vagas.html' return render(request, template_name,{ 'vagas': vagas, 'page_range': page_range, }) @login_required def requisitos(request, id): template_name = 'vaga.html' vaga = Vaga.objects.get(id=id) requisitos = Requisitos.objects.filter(vaga_id = id) context = { 'vaga':vaga, 'requisitos':requisitos, } return render(request, template_name, context) @login_required def inscricao(request, id): template_name = 'mural_de_vagas.html' vaga = Vaga.objects.get(id=id) user=request.user if user.user_type == "Candidato": candidato = user.candidato tag = 0 tag2 = 0 if candidato.escolaridade == 'Fundamental incompleto': tag = 1 elif candidato.escolaridade == 'Fundamental completo': tag = 2 elif candidato.escolaridade == 'Medio incompleto': tag = 3 elif candidato.escolaridade == 'Medio completo': tag = 4 elif candidato.escolaridade == 'Tecnico incompleto': tag = 5 elif candidato.escolaridade == 'Tecnico completo': tag = 6 elif candidato.escolaridade == 'Superior incompleto': tag = 7 elif candidato.escolaridade == 'Superior completo': tag = 8 elif candidato.escolaridade == 'Pos-Graduacao': tag = 9 elif candidato.escolaridade == 'Mestrado': tag = 10 elif candidato.escolaridade == 'Doutorado': tag = 11 else: tag = 12 if vaga.escolaridade == 'Fundamental incompleto' or vaga.escolaridade == '': tag2 = 1 elif vaga.escolaridade == 'Fundamental completo': tag2 = 2 elif vaga.escolaridade == 'Medio incompleto': tag2 = 3 elif vaga.escolaridade == 'Medio completo': tag2 = 4 elif vaga.escolaridade == 'Tecnico incompleto': tag2 = 5 elif vaga.escolaridade == 'Tecnico completo': tag2 = 6 elif vaga.escolaridade == 'Superior incompleto': tag2 = 7 elif vaga.escolaridade == 'Superior completo': tag2 = 8 elif vaga.escolaridade == 'Pos-Graduacao': tag2 = 9 elif vaga.escolaridade == 'Mestrado': tag2 = 10 elif vaga.escolaridade == 'Doutorado': tag2 = 11 else: tag2 = 12 if candidato.escolaridade == None: messages.info( request, 'Inscrição não realizada. Preencha suas informações básicas para poder candidatar-se as vagas.' ) elif tag >= tag2: inscricao, criado = Candidatura.objects.get_or_create(candidato = candidato, vaga = vaga) if criado: messages.success( request, 'A sua inscrição foi realizada com sucesso.' ) else: messages.success( request, 'Você já se cadastrou nessa vaga. Acompanhe suas candidaturas pelo Painel.' ) else: messages.success( request, 'Você não possui a escolaridade mínima exigida para essa vaga.' ) return redirect('vagas:mural_de_vagas') else: messages.info( request, 'Apenas usuários do tipo candidato podem se candidatar em vagas de emprego.' ) return redirect('vagas:mural_de_vagas') <file_sep>from django.shortcuts import render from .forms import ContactForm from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required def home(request): return render(request, 'home.html') def saiba_mais(request): return render(request, 'saiba_mais.html') def contact(request): context = {} if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): context['is_valid'] = True form = ContactForm() else: form = ContactForm() context['form'] = form template_name = 'contact.html' return render(request, template_name, context)<file_sep>from django.shortcuts import render, redirect, get_object_or_404, render_to_response from django.contrib.auth.forms import (UserCreationForm, PasswordChangeForm, SetPasswordForm) from django.contrib.auth import authenticate, login, get_user_model from django.contrib.auth.decorators import login_required from django.conf import settings from django.contrib import messages from dal import autocomplete from usuario.models import User from vagas.models import Candidatura from .models import * from .forms import * User = get_user_model() # Create your views here. @login_required def info_basica(request): template_name = 'info_basica.html' context = {} if request.method == 'POST': form1 = InfoBasicaForm(request.POST, instance=request.user.candidato) form2 = UserForm2(request.POST, instance=request.user) if form1.is_valid() and form2.is_valid(): form1.save() form2.save() messages.success( request, 'Os dados da sua conta foram alterados com sucesso' ) return redirect('usuario:dashboard') else: form1 = InfoBasicaForm(instance=request.user.candidato) form2 = UserForm2(instance=request.user) context = { 'form1':form1, 'form2':form2 } return render(request, template_name, context) @login_required def formacao(request): template_name = 'formacao.html' context = {} if request.method == 'POST': form = FormacaoForm(request.POST) if form.is_valid(): formacao = form.save(commit=False) candidato = Candidato.objects.get(user_id = request.user.id) formacao.candidato_id = candidato.id formacao.save() messages.success( request, 'As informações foram adicionadas com sucesso' ) return redirect('candidato:formacao') else: form = FormacaoForm() context = { 'form':form, } return render(request, template_name, context) @login_required def experiencia(request): template_name = 'experiencia.html' context = {} if request.method == 'POST': form = ExperienciaForm(request.POST) if form.is_valid(): experiencia = form.save(commit=False) candidato = Candidato.objects.get(user_id = request.user.id) experiencia.candidato_id = candidato.id experiencia.save() messages.success( request, 'As informações foram adicionadas com sucesso' ) return redirect('candidato:experiencia') else: form = ExperienciaForm() context = { 'form':form, } return render(request, template_name, context) @login_required def curso(request): template_name = 'curso.html' context = {} if request.method == 'POST': form = CursoForm(request.POST) if form.is_valid(): curso = form.save(commit=False) candidato = Candidato.objects.get(user_id = request.user.id) curso.candidato_id = candidato.id curso.save() messages.success( request, 'As informações foram adicionadas com sucesso' ) return redirect('candidato:curso') else: form = CursoForm() context = { 'form':form, } return render(request, template_name, context) @login_required def idioma(request): template_name = 'idioma.html' context = {} if request.method == 'POST': form = IdiomaForm(request.POST) if form.is_valid(): idioma = form.save(commit=False) candidato = Candidato.objects.get(user_id = request.user.id) idioma.candidato_id = candidato.id idioma.save() messages.success( request, 'As informações foram adicionadas com sucesso' ) return redirect('candidato:idioma') else: form = IdiomaForm() context = { 'form':form, } return render(request, template_name, context) IdiomaForm @login_required def excluir_experiencia(request, id): dado = Experiencia.objects.get(id=id) dado.delete() messages.success( request, 'A experiência foi excluída com sucesso' ) return redirect('candidato:experiencia') @login_required def excluir_formacao(request, id): dado = Formacao.objects.get(id=id) dado.delete() messages.success( request, 'A formação foi excluída com sucesso' ) return redirect('candidato:formacao') @login_required def excluir_curso(request, id): dado = Curso.objects.get(id=id) dado.delete() messages.success( request, 'A formação foi excluída com sucesso' ) return redirect('candidato:curso') @login_required def excluir_idioma(request, id): dado = Idioma.objects.get(id=id) dado.delete() messages.success( request, 'O idioma foi excluído com sucesso' ) return redirect('candidato:idioma') @login_required def editar_experiencia(request, id): template_name = 'experiencia_editar.html' context = {} if request.method == 'POST': form = ExperienciaForm(request.POST, instance = Experiencia.objects.get(id=id)) if form.is_valid(): form.save() messages.success( request, 'Os dados foram atualizados com sucesso' ) return redirect('candidato:experiencia') else: dado = Experiencia.objects.get(id=id) form = ExperienciaForm(instance = dado) context = { 'form':form, } return render(request, template_name, context) @login_required def editar_idioma(request, id): template_name = 'idioma_editar.html' context = {} if request.method == 'POST': form = IdiomaForm(request.POST, instance = Idioma.objects.get(id=id)) if form.is_valid(): form.save() messages.success( request, 'Os dados foram atualizados com sucesso' ) return redirect('candidato:idioma') else: dado = Idioma.objects.get(id=id) form = IdiomaForm(instance = dado) context = { 'form':form, } return render(request, template_name, context) @login_required def editar_formacao(request, id): template_name = 'formacao_editar.html' context = {} if request.method == 'POST': form = FormacaoForm(request.POST, instance = Formacao.objects.get(id=id)) if form.is_valid(): form.save() messages.success( request, 'Os dados foram atualizados com sucesso' ) return redirect('candidato:formacao') else: dado = Formacao.objects.get(id=id) form = FormacaoForm(instance = dado) context = { 'form':form, } return render(request, template_name, context) @login_required def editar_curso(request, id): template_name = 'curso_editar.html' context = {} if request.method == 'POST': form = CursoForm(request.POST, instance = Curso.objects.get(id=id)) if form.is_valid(): form.save() messages.success( request, 'Os dados foram atualizados com sucesso' ) return redirect('candidato:curso') else: dado = Curso.objects.get(id=id) form = CursoForm(instance = dado) context = { 'form':form, } return render(request, template_name, context) @login_required def minhas_candidaturas(request): template_name = 'minhas_candidaturas.html' return render(request, template_name) @login_required def excluir_candidatura(request, id): dado = Candidatura.objects.get(id=id) dado.delete() messages.success( request, 'Sua inscrição foi cancelada com sucesso' ) return redirect('candidato:minhas_candidaturas') @login_required def pretencoes(request): template_name = 'pretencoes.html' context = {} if request.method == 'POST': form = PretencoesForm(request.POST) if form.is_valid(): pretencao = form.save(commit=False) candidato = Candidato.objects.get(user_id = request.user.id) pretencao.candidato_id = candidato.id pretencao.save() messages.success( request, 'As informações foram adicionadas com sucesso' ) return redirect('candidato:pretencoes') else: form = PretencoesForm() context = { 'form':form, } return render(request, template_name, context) @login_required def editar_pretencao(request, id): template_name = 'editar_pretencao.html' context = {} if request.method == 'POST': form = PretencoesForm(request.POST, instance = Pretencoes.objects.get(id=id)) if form.is_valid(): form.save() messages.success( request, 'Os dados foram atualizados com sucesso' ) return redirect('candidato:pretencoes') else: dado = Pretencoes.objects.get(id=id) form = PretencoesForm(instance = dado) context = { 'form':form, } return render(request, template_name, context) @login_required def excluir_pretencao(request, id): dado = Pretencoes.objects.get(id=id) dado.delete() messages.success( request, 'A pretenção foi excluída com sucesso' ) return redirect('candidato:pretencoes') #class PretencoesAutocomplete(autocomplete.Select2QuerySetView): # def get_queryset(self): # # Don't forget to filter out results depending on the visitor ! # if not self.request.user.is_authenticated(): # return Pretencoes.objects.none() # # qs = Pretencoes.objects.all() # # if self.q: # qs = qs.filter(nome_prof__istartswith=self.q) # # return qs<file_sep>from django.contrib import admin from usuario.forms import UserAdminCreationForm, UserForm from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import UserChangeForm from django.conf import settings from .models import Experiencia, Formacao, Idioma, Candidato, Curso, Profissoes, Pretencoes from usuario.models import User class ExperienciaInline(admin.StackedInline): model = Experiencia class FormacaoInline(admin.StackedInline): model = Formacao class IdiomaInline(admin.StackedInline): model = Idioma class CursoInline(admin.StackedInline): model = Curso class PretencoesInline(admin.StackedInline): model = Pretencoes class CandidatoAdmin(admin.ModelAdmin): inlines = (ExperienciaInline, FormacaoInline, IdiomaInline, CursoInline, PretencoesInline ) class OcupacoesAdmin(admin.ModelAdmin): model = Profissoes admin.site.register(Candidato, CandidatoAdmin) admin.site.register(Profissoes, OcupacoesAdmin)<file_sep>from .models import * from usuario.models import User from django.conf import settings from django.forms import * from django.contrib.auth import get_user_model from django.contrib.localflavor.br.forms import BRCPFField,BRCNPJField from vagas.models import Vaga, Requisitos, Candidatura from core.choices import * User = get_user_model() class InfoBasicaForm(ModelForm): cnpj = BRCNPJField(label = '* CNPJ',max_length = 18 , min_length = 14) nome = CharField(label = '* Nome Fantasia', max_length = 50, required = True) ramo = ChoiceField( label = '* Ramo de Atividade', required = True, choices = BRANCH_ACTIVITY, ) tipo = ChoiceField( label = '* Tipo da Empresa', required = True, choices = BRANCH_TYPE, ) class Meta: model = Empregador exclude = ['user'] class UserForm2(ModelForm): name = CharField(label = 'Nome do Operador', max_length = 50) class Meta: model = User fields = ['name', 'email'] class CadastrarVagaForm(ModelForm): escolaridade = ChoiceField( label ='Escolaridade exigida', required=False, choices=EDUCATION_CHOICES, help_text = '*ATENÇÃO* Apenas candidatos com a escolaridade igual ou superior a informada neste campo poderão se candidatar a vaga. Caso queira abrir a inscrição a todos, deixe esse campo em branco.' ) salario = CharField( label = 'Salário', max_length = 20, required = False, help_text = "Ex: 1.500,00. Caso deseje o status 'a combinar', deixe este campo em branco." ) confidencial = BooleanField( label = 'Confidencial', required = False, help_text = 'Marque esta opção caso não deseje divulgar o nome de sua empresa.', widget= CheckboxInput() ) class Meta: model = Vaga exclude = ['empregador', 'status','inscritos','finalizada'] class RequisitosForm(ModelForm): requisito = CharField( label = 'Requisito', max_length = 300, required = False, widget= Textarea(attrs = {'rows':4, 'cols':15}) ) class Meta: model = Requisitos exclude = ['vaga'] class InscritosForm(ModelForm): inscritos = IntegerField( label = 'Quantidade de candidatos selecionados', required = False, ) class Meta: model = Vaga fields = ['inscritos'] <file_sep>from django.db import models import re import datetime from django.core import validators from django.conf import settings from core.choices import * from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin, UserManager) from usuario.models import User from municipios.models import * # Create your models here. class Candidato(models.Model): user = models.OneToOneField(User, related_name='candidato', on_delete=models.CASCADE) cpf = models.CharField('CPF',max_length = 14, blank=False, unique=True) data_nascimento = models.DateField('Data de Nascimento', null=True, blank=True) logradouro = models.CharField('Rua',max_length = 100, null=True, blank=True) numeroLog = models.CharField('Número', max_length = 10, null=True, blank=True) bairro = models.CharField('Bairro', max_length = 50, null=True, blank=True) cidade = models.CharField('Cidade', max_length = 50, null=True, blank=True) uf = models.CharField('UF', max_length = 50, null=True, blank=True) cep = models.CharField('CEP', max_length = 10, null=True, blank=True) complemento = models.CharField('Complemento', max_length = 100, null=True, blank=True) tel1 = models.CharField('Tel(1)', max_length = 12, null=True, blank=True) tel2 = models.CharField('Tel(2)', max_length = 12, null=True, blank=True) obs = models.CharField(max_length = 200, null=True, blank=True) deficiente = models.CharField( 'Portador de deficiência', max_length=5, null=True, blank=True, choices=YESORNOT_CHOICES, ) escolaridade = models.CharField( 'Escolaridade', max_length=25, null=True, blank=True, choices=EDUCATION_CHOICES, ) habilitacao = models.CharField( 'Habilitação', max_length=25, null=True, blank=True, choices=HABILITACAO, ) estado_civil = models.CharField( 'Estado civil', max_length=25, null=True, blank=True, choices=MARITAL_STATUS, ) genero = models.CharField( 'Gênero', max_length=25, null=True, blank=True, choices=GENDER_CHOICES, ) def __str__(self): return self.user.name class Experiencia(models.Model): candidato = models.ForeignKey(Candidato, on_delete=models.CASCADE) empresa = models.CharField('Empresa', max_length = 100, null=True, blank=True) cargo = models.CharField('Cargo', max_length = 100, null=True, blank=True) descricao = models.TextField ('Descrição das atividades', max_length = 1000, null=True, blank=True) data_entrada = models.DateField('Data da contratação', null=True, blank=True) data_saida = models.DateField('Data da saída', null=True, blank=True) def __str__(self): return self.cargo class Formacao(models.Model): candidato = models.ForeignKey(Candidato, on_delete=models.CASCADE, related_name='formacao') grau = models.CharField( 'Nível', max_length=25, null=True, blank=True, choices=EDUCATION_CHOICES_FORMATION, ) instituicao = models.CharField('Instituição' ,max_length = 100, null=True, blank=True) curso = models.CharField('Curso', max_length = 50, null=True, blank=True) data_entrada = models.DateField('Data de Entrada', null=True, blank=True) data_conclusao = models.DateField('Data de Saída', null=True, blank=True) def __str__(self): return self.curso class Idioma(models.Model): candidato = models.ForeignKey(Candidato, on_delete=models.CASCADE) idioma = models.CharField(max_length = 20, null=True, blank=True) nivel = models.CharField( max_length=25, null=True, blank=True, choices=LEVEL, ) def __str__(self): return self.idioma class Curso(models.Model): candidato = models.ForeignKey(Candidato, on_delete=models.CASCADE) tipo = models.CharField( 'Tipo', max_length=25, null=True, blank=True, choices=COURSE_TYPE, ) curso = models.CharField('Curso',max_length=50, null=True, blank=True) instituicao = models.CharField('Instituição',max_length =30, null=True, blank=True) duracao = models.CharField('Duração',max_length=5, null=True, blank=True) data_entrada = models.DateField('Data de Entrada', null=True, blank=True) data_saida = models.DateField('Data de Conclusão', null=True, blank=True) def __str__(self): return self.curso class Profissoes(models.Model): nome_prof = models.CharField('Profissão', max_length=100, null=True, blank=True) def __str__(self): return self.nome_prof class Meta: ordering = ['nome_prof'] verbose_name = 'Profissão' verbose_name_plural = 'Profissões' class Pretencoes(models.Model): candidato = models.ForeignKey(Candidato, on_delete=models.CASCADE) profissao = models.ForeignKey(Profissoes, on_delete=models.CASCADE) experiencia = models.BooleanField ('Tenho experiência na função', default=False) comprovacao = models.BooleanField ('Posso comprovar', default=False) def __str__(self): return self.profissao.nome_prof<file_sep> {% for vaga in vagas %} <div class="well3" id='{{ vaga.id }}'> <div class='row'> <div class='col-xs-10'> <div class='col-xs-10'> <h1 class="splash-head"> Emprego para {{ vaga.funcao }} </h1> </div> <div class='col-xs-8'> <ul class="list-inline"> <li>Local: {{ vaga.local }}</li> {% if vaga.confidencial == True %} <li>Empresa: Confidencial </li> {% else %} <li>Empresa: {{ vaga.empregador.nome }}</li> {% endif %} {% if vaga.escolaridade == '' %} <li>Escolaridade Exigida: Nenhuma </li> {% else %} <li>Escolaridade Exigida: {{ vaga.escolaridade }} </li> {% endif %} <li>Criado: {{ vaga.data_criacao | date:"d M Y"}}</li> </ul> </div> <div class='col-xs-4 text-center'> <a href="{% url 'vagas:requisitos' vaga.id %}" class="pure-button-primary primary-button" role="button">Ver Vaga</a> </div> </div> </div> </div> {% empty %} <div class="pure-u-1 text-center"> <h3>Não temos nenhuma vaga cadastrada no momento</h3> </div> {% endfor %} <center class="pagination"> <ul class="pagination"> <span class="step-links"> {% if vagas.has_previous %} <a id="prev" href="?page={{ vagas.previous_page_number }}">&laquo;</a>&emsp; {% else %} <class="disabled"><span>&laquo;</span>&emsp; {% endif %} <span class="current"> {% for i in page_range %} {% if vagas.number == i %} <a class= "home-menu" href="?page={{ i }}">{{ i }} <span class="sr-only"></span> </a> &emsp; {% else %} <a href="?page={{ i }}"> {{ i }} </a> &emsp; {% endif %} {% endfor %} </span> {% if vagas.has_next %} <a id="next" href="?page={{ vagas.next_page_number }}">&raquo;</a> {% else %} <class="disabled"><span>&raquo;</span> {% endif %} </ul> } } </center><file_sep>{% extends "dashboard_empregador.html" %} {% load crispy_forms_tags %} {% block breadcrumb %} {{ block.super }} <li>/</li> <li><a href="{% url 'empregador:cadastrar_vaga' %}"> Cadastrar Vaga </a></li> {% endblock %} {% block dashboard_content %} <script> $(document).ready(function(){ $("#add-item").click(function(ev) { ev.preventDefault(); var count = $('#order').children().length; var tmplMarkup = $("#item-order").html(); var compiledTmpl = tmplMarkup.replace(/__prefix__/g, count); $("div#order").append(compiledTmpl); // update form count $('#id_product-TOTAL_FORMS').attr('value', count + 1); // some animate to scroll to view our new form $('html, body').animate({ scrollTop: $("#add-item").position().top-200 }, 800); }); }); </script> <form class="pure-form pure-form-stacked" action="" method="POST"> {% csrf_token %} {{ forms|crispy }} {{ formset.management_form }} <div id="order" class="form-inline form-group"> {% for item_order_form in formset %} <div id="item-{{ forloop.counter0 }}"> {{ item_order_form|crispy }} </div> {% endfor %} </div> <!-- <a class="pure-button" id="add-item"><i class="fa fa-plus"></i> Add Requisito</a> --> <div class="form-inline buttons"> <br> <button type="submit" class="pure-button pure-button-primary">Salvar Vaga</button> </div> </form> <script type="text/html" id="item-order"> <div id="item-__prefix__" style="margin-top: 10px"> {{ formset.empty_form|crispy }} </div> </script> {% endblock %}<file_sep>from django import forms from django.core.mail import send_mail from django.conf import settings from .mail import send_mail_template class ContactForm(forms.Form): name = forms.CharField(label='Nome', max_length=100) email = forms.EmailField(label='E-mail') subject = forms.CharField(label='Assunto', max_length=100) message = forms.CharField( label='Mensagem/Dúvida', widget=forms.Textarea ) def send_mail(self, course): context = { 'name': self.cleaned_data['name'], 'email': self.cleaned_data['email'], 'subject': self.cleaned_data['subject'], 'message': self.cleaned_data['message'], } template_name = 'core/contact_email.html' send_mail_template( subject, template_name, context, [settings.CONTACT_EMAIL] ) <file_sep>from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import authenticate, login, get_user_model from django.contrib.auth.decorators import login_required from django.conf import settings from django.contrib import messages from django.forms.models import inlineformset_factory from usuario.models import User from candidato.models import * from vagas.models import Vaga, Candidatura from .models import * from .forms import * User = get_user_model() @login_required def info_basica2(request): template_name = 'info_basica2.html' context = {} if request.method == 'POST': form1 = InfoBasicaForm(request.POST, instance=request.user.empregador) form2 = UserForm2(request.POST, instance=request.user) if form1.is_valid() and form2.is_valid(): form1.save() form2.save() messages.success( request, 'Os dados da sua conta foram alterados com sucesso' ) return redirect('usuario:dashboard') else: form1 = InfoBasicaForm(instance=request.user.empregador) form2 = UserForm2(instance=request.user) context = { 'form1':form1, 'form2':form2 } return render(request, template_name, context) InfoBasicaForm #FALTA IMPLEMENTAR O FORM DINÂMICO @login_required def cadastrar_vaga(request): template_name = 'cadastrar_vaga.html' context = {} CadastrarRequisitosFormSet = inlineformset_factory( Vaga, Requisitos, form=RequisitosForm, fields = '__all__', extra=3, can_delete = False, min_num = 1, validate_min = True, ) if request.method == 'POST': forms = CadastrarVagaForm(request.POST, request.FILES) formset = CadastrarRequisitosFormSet(request.POST, request.FILES) if forms.is_valid(): vaga = forms.save(commit=False) vaga.empregador = request.user.empregador if vaga.empregador.nome == None: messages.success( request, 'A vaga não foi criada. Para criar uma vaga é necessário antes preencher as informações básicas.' ) else: requisito = CadastrarRequisitosFormSet(request.POST, request.FILES, instance = vaga) vaga.save() requisito.save() messages.success( request, 'A vaga foi criada com sucesso' ) return redirect('empregador:cadastrar_vaga') else: forms = CadastrarVagaForm() formset = CadastrarRequisitosFormSet() context = { 'forms':forms, 'formset':formset, } return render(request, template_name, context) def editar_vaga(request, id): template_name = 'editar_vaga.html' context = {} CadastrarRequisitosFormSet = inlineformset_factory( Vaga, Requisitos, form=RequisitosForm, fields = '__all__', extra=3, can_delete = False, min_num = 1, validate_min = True, ) vaga = Vaga.objects.get(id = id) if request.method == 'POST': forms = CadastrarVagaForm(request.POST, request.FILES, instance = vaga) formset = CadastrarRequisitosFormSet(request.POST, request.FILES, instance = vaga) if forms.is_valid(): vaga = forms.save(commit=False) requisito = CadastrarRequisitosFormSet(request.POST, request.FILES, instance = vaga) vaga.save() requisito.save() messages.success( request, 'A vaga foi editada com sucesso' ) return redirect('empregador:minhas_vagas') else: forms = CadastrarVagaForm(instance = vaga) formset = CadastrarRequisitosFormSet(instance = vaga) context = { 'forms':forms, 'formset':formset, } return render(request, template_name, context) @login_required def minhas_vagas(request): template_name = 'minhas_vagas.html' return render(request, template_name) def excluir_vaga(request, id): vaga = Vaga.objects.get(id=id) if request.method == 'POST': form = InscritosForm(request.POST, instance = vaga) vaga = form.save(commit=False) vaga.finalizada = True vaga.save() messages.success(request, 'A vaga foi excluida com sucesso') return redirect('empregador:minhas_vagas') template = 'finalizar_vaga.html' form = InscritosForm() context = { 'vaga': vaga, 'form':form, } return render(request, template, context) def status_vaga(request, id): dado = Vaga.objects.get(id=id) if dado.status: dado.status = False dado.save() messages.success( request, 'Sua vaga foi retirada do nosso mural' ) else: dado.status = True dado.save() messages.success( request, 'Sua vaga agora está à mostra no nosso mural' ) return redirect('empregador:minhas_vagas') @login_required def ver_inscritos(request, id): template_name = 'ver_inscritos.html' dado = Vaga.objects.get(id=id) candidaturas = Candidatura.objects.filter(vaga = dado) var_get_escolaridade = request.GET.get('escolaridade', None) var_get_genero = request.GET.get('genero', None) var_get_deficiente = request.GET.get('deficiente', None) if var_get_escolaridade or var_get_genero or var_get_deficiente: candidaturas = Candidatura.objects.filter(vaga = dado, candidato__escolaridade__contains=var_get_escolaridade, candidato__genero__contains=var_get_genero, candidato__deficiente__contains=var_get_deficiente, ) context = { 'candidaturas':candidaturas, } return render(request, template_name, context) @login_required def detalhes_candidato(request, id): template_name = 'detalhes_candidato.html' candidato = Candidato.objects.get(id=id) formacoes = Formacao.objects.filter(candidato_id = candidato.id) experiencias = Experiencia.objects.filter(candidato_id = candidato.id) idiomas = Idioma.objects.filter(candidato_id = candidato.id) cursos = Curso.objects.filter(candidato_id = candidato.id) context = { 'candidato':candidato, 'formacoes':formacoes, 'experiencias': experiencias, 'idiomas': idiomas, 'cursos' : cursos, } return render(request, template_name, context) <file_sep>{% extends "dashboard_candidato.html" %} {% load minhas_candidaturas_tag %} {% block breadcrumb %} {{ block.super }} <li>/</li> <li><a href="{% url 'candidato:minhas_candidaturas' %}"> Minhas Candidaturas </a></li> {% endblock %} {% block dashboard_content %} {% minhascandidaturastag user %} {% endblock %}<file_sep># Generated by Django 2.0.2 on 2018-04-10 21:26 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('candidato', '0002_candidato_user'), ] operations = [ migrations.AlterModelOptions( name='profissoes', options={'ordering': ['nome_prof'], 'verbose_name': 'Profissão', 'verbose_name_plural': 'Profissões'}, ), ] <file_sep>from django.db import models from usuario.models import User from candidato.models import Candidato from empregador.models import Empregador from core.choices import * # Create your models here. class Vaga (models.Model): empregador = models.ForeignKey(Empregador, related_name='empregador', on_delete=models.CASCADE) funcao = models.CharField ('Função', max_length = 50) descricao = models.TextField ('Descrição das Atividades', max_length = 1000, blank = False) confidencial = models.BooleanField ('Confidencial', default=False) data_criacao = models.DateTimeField('Data de Criação', auto_now_add=True) ultima_modificacao = models.DateTimeField('Última Modificação', auto_now_add=False, auto_now=True) status = models.BooleanField ('Está ativa?', blank=True, default=True) finalizada = models.BooleanField ('Foi finalizada?', blank=True, default=False) inscritos = models.PositiveSmallIntegerField ('Quantidade de inscritos', blank=True, null=True) salario = models.CharField ('Salário', max_length = 20, blank=True, null=True) local = models.CharField ('Cidade', max_length = 50) escolaridade = models.CharField( 'Escolaridade exigida', max_length=25, null=True, blank=True, choices=EDUCATION_CHOICES, ) def __str__(self): return self.funcao def get_vaga_detail_url(self): return u"/vagas/%i" % self.id class Requisitos (models.Model): vaga = models.ForeignKey(Vaga, related_name='vaga_requisito', on_delete=models.CASCADE) requisito = models.TextField('Requisito', max_length=300) def __str__(self): return self.requisito class Candidatura (models.Model): candidato = models.ForeignKey(Candidato, related_name='candiato', on_delete=models.CASCADE) vaga = models.ForeignKey(Vaga, related_name='vaga', on_delete=models.CASCADE) #data_inscricao = models.DateTimeField('Data da Inscrição', auto_now_add=True) def __str__(self): return self.candidato.user.name <file_sep>from django.conf.urls import include, url from django.urls import path from . import views app_name='vagas' urlpatterns = [ path("mural-de-vagas/", views.mural_de_vagas, name='mural_de_vagas'), path("mural-de-vagas/ver-vaga/<id>", views.requisitos, name='requisitos'), path("mural-de-vagas/ver-vaga/inscricao/<id>", views.inscricao, name='inscricao'), ]<file_sep># Generated by Django 2.0.2 on 2018-04-02 13:38 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('empregador', '0001_initial'), ('candidato', '0001_initial'), ] operations = [ migrations.CreateModel( name='Candidatura', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('candidato', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='candiato', to='candidato.Candidato')), ], ), migrations.CreateModel( name='Requisitos', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('requisito', models.TextField(max_length=300, verbose_name='Requisito')), ], ), migrations.CreateModel( name='Vaga', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('funcao', models.CharField(max_length=50, verbose_name='Função')), ('descricao', models.TextField(max_length=1000, verbose_name='Descrição das Atividades')), ('confidencial', models.BooleanField(default=False, verbose_name='Confidencial')), ('data_criacao', models.DateTimeField(auto_now_add=True, verbose_name='Data de Criação')), ('ultima_modificacao', models.DateTimeField(auto_now=True, verbose_name='Última Modificação')), ('status', models.BooleanField(default=True, verbose_name='Está ativa?')), ('finalizada', models.BooleanField(default=False, verbose_name='Foi finalizada?')), ('salario', models.CharField(blank=True, max_length=20, verbose_name='Salário')), ('local', models.CharField(max_length=50, verbose_name='Cidade')), ('escolaridade', models.CharField(blank=True, choices=[('', ''), ('Fundamental incompleto', 'Fundamental incompleto'), ('Fundamental completo', 'Fundamental completo'), ('Medio incompleto', 'Médio incompleto'), ('Medio completo', 'Médio completo'), ('Tecnico incompleto', 'Técnico incompleto'), ('Tecnico completo', 'Técnico completo'), ('Superior incompleto', 'Superior incompleto'), ('Superior completo', 'Superior completo'), ('Pos-Graduacao', 'Pós-Graduação'), ('Mestrado', 'Mestrado'), ('Doutorado', 'Doutorado'), ('PHD', 'PHD')], max_length=25, null=True, verbose_name='Escolaridade exigida')), ('empregador', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='empregador', to='empregador.Empregador')), ], ), migrations.AddField( model_name='requisitos', name='vaga', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='vaga_requisito', to='vagas.Vaga'), ), migrations.AddField( model_name='candidatura', name='vaga', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='vaga', to='vagas.Vaga'), ), ] <file_sep>{% extends "base.html" %} {% block content %} <div class="splash"> <div class="pure-g-r"> <div class="pure-u-1"> <div class="l-box splash-text"> <h1 class="splash-head"> Uma Plataforma de apoio ao trabalhador de SGA-RN </h1> <h2 class="splash-subhead"> O Portal CIESGA realiza intermediação entre empresas que precisam de mão de obra e profissionais que procuram emprego de forma totalmente transparente. </h2> <p> <a href="{% url 'core:home' %}" class="pure-button-primary primary-button">Início</a> <a href="{% url 'usuario:choice_register' %}" class="pure-button-primary secundary-button">Cadastre-se</a> </p> </div> </div> </div> </div> <div class="pure-g-r content-ribbon"> <div class="pure-u"> <div class="l-box"> <h4 class="content-subhead">Portal CIESGA</h4> <pre class="pure-u" align="justify"> Com esta ferramenta pretendemos tornar o processo de encontrar uma vaga de emprego muito mais fácil e transparente, tanto para o cidadão quanto para a empresa que precisa de mão de obra. A Prefeitura de São Gonçalo do Amarante tem colocado seus esforços em trazer novas oportunidades e abrir novas vagas aqui mesmo no município, para que seus moradores não tenham que se deslocar para outras cidades em busca de emprego.<br> Aqui o cidadão fará seu cadastro, com todas os seus dados, e informará suas áreas de interesse profissional. As empresas também farão seus cadastros e poderão disponibilizar vagas a serem preenchidas. Se o candidato for da área de interesse da empresa e atender seus requisitos, automaticamente estará concorrendo àquela vaga. Se não for, mesmo assim poderá tentar concorrer, obviamente não tendo tantas chances de conseguir preenchê-la. Além disso, candidatos e empresas poderão acompanhar vagas abertas, resumo de outros candidatos, quantidade de profissionais concorrendo a uma vaga, dentre outras funcionalidades.<br> Queremos que todos tenham certeza que estão sendo respeitados os critérios de seleção das empresas. Que a administração pública não interfere no processo, garantindo que candidatos às vagas de emprego no município estejam sendo aproveitados de acordo com suas capacidades profissionais. Além disso, através dos cadastros é possível avaliar a realidade do mercado de trabalho local e as necessidades de cursos de qualificação para a população. </pre> </div> </div> </div> {% endblock %}<file_sep>Django==2.0.2 django-autocomplete-light==3.2.10 django-crispy-forms==1.7.2 django-extensions==2.0.7 django-localflavor==2.0 django-municipios==0.8.1 django-ranged-response==0.2.0 django-simple-captcha==0.5.6 django-static-jquery==2.1.4 Pillow==5.0.0 pkg-resources==0.0.0 pygraphviz==1.3.1 pytz==2018.3 six==1.11.0 <file_sep>from django.template import Library from django.contrib.auth import authenticate, login, get_user_model register = Library() User = get_user_model() from vagas.models import * from empregador.models import Empregador from usuario.models import User @register.inclusion_tag('templatetags/minhas_vagas_tag.html') def minhasvagastag(user): empregador = Empregador.objects.get(user_id = user.id) vagas = Vaga.objects.filter(empregador_id = empregador.id, finalizada = False).order_by('-data_criacao') context = { 'vagas': vagas, } return context <file_sep># Generated by Django 2.0.2 on 2018-04-10 21:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('vagas', '0003_auto_20180403_1259'), ] operations = [ migrations.AlterField( model_name='vaga', name='salario', field=models.CharField(blank=True, max_length=20, null=True, verbose_name='Salário'), ), ] <file_sep>from django.contrib import admin from .models import Empregador from vagas.models import * class VagaInline(admin.StackedInline): model = Vaga class EmpregadorAdmin(admin.ModelAdmin): list_display = ('nome', 'cidade', 'bairro') inlines = (VagaInline,) admin.site.register(Empregador, EmpregadorAdmin)<file_sep>from django.contrib.auth.forms import (UserCreationForm, PasswordChangeForm, SetPasswordForm) from django.contrib.auth import authenticate, login, get_user_model from django.contrib.auth.decorators import login_required from django.conf import settings from django.utils.translation import gettext_lazy as _ from usuario.forms import User from .models import Candidato, Experiencia, Formacao, Idioma, Curso, Profissoes, Pretencoes from django.forms import * from django.contrib.localflavor.br.forms import BRCPFField,BRCNPJField #from municipios.widgets import SelectMunicipioWidget from core.choices import * #from dal import autocomplete User = get_user_model() class InfoBasicaForm(ModelForm): cpf = BRCPFField(label = 'CPF*',max_length = 14 , min_length = 11) bairro = CharField(label ='Bairro*', required = True) cidade = CharField(label ='Cidade*', required = True) uf = CharField(label ='UF*', required = True ) tel1 = CharField(label ='Tel(1)*', required = True) #cidade = IntegerField(widget=SelectMunicipioWidget) deficiente = ChoiceField( label = 'Portador de deficiência*', required = True, choices = YESORNOT_CHOICES, ) data_nascimento = DateField( widget= TextInput(attrs={"onkeypress": "return dateMask(this, event);","name":"datNascimento", "id":"datNascimento", "type":"text", "maxlength":"10" } ), label ='Data de Nascimento*', help_text = 'Ex: dd/mm/aaaa', required = True, ) escolaridade = ChoiceField( label = 'Escolaridade*', required = True, choices = EDUCATION_CHOICES ) genero = ChoiceField( label = 'Gênero*', required = True, choices = GENDER_CHOICES ) class Meta: model = Candidato exclude = ['obs', 'user'] class UserForm2(ModelForm): name = CharField(label ='Nome Completo/Social*', required = True) email = CharField(label ='E-mail*', required = True) class Meta: model = User fields = ['name', 'email'] class FormacaoForm(ModelForm): instituicao = CharField(label ='Instituição*', required = True) curso = CharField(label ='Curso*', required = True) data_entrada = DateField( widget= TextInput(attrs={"onkeypress": "return dateMask(this, event);","name":"datNascimento", "id":"datNascimento", "type":"text", "maxlength":"10" } ), label = 'Data da entrada*', required = True, help_text = 'Ex: dd/mm/aaaa') data_conclusao = DateField( widget= TextInput(attrs={"onkeypress": "return dateMask(this, event);","name":"datNascimento", "id":"datNascimento", "type":"text", "maxlength":"10" } ), label = 'Data da conclusão', required = False, help_text = 'Caso não tenha concluído, deixe esse campo em branco.') grau = ChoiceField(label ='Nível*', required = True, choices = EDUCATION_CHOICES_FORMATION) class Meta: model = Formacao exclude = ['candidato'] class ExperienciaForm(ModelForm): empresa = CharField(label ='Empresa*', required = True) cargo = CharField(label ='Cargo*', required = True) data_entrada = DateField( widget= TextInput(attrs={"onkeypress": "return dateMask(this, event);","name":"datNascimento", "id":"datNascimento", "type":"text", "maxlength":"10" } ), label = 'Data da contratação*', required = True, help_text = 'Ex: dd/mm/aaaa') data_saida = DateField( widget= TextInput(attrs={"onkeypress": "return dateMask(this, event);","name":"datNascimento", "id":"datNascimento", "type":"text", "maxlength":"10" } ), label = 'Data da saída', required = False, help_text = 'Caso ainda esteja nesta função, deixe esse campo em branco.') class Meta: model = Experiencia exclude = ['candidato'] class CursoForm(ModelForm): tipo = ChoiceField(label ='Tipo*', required = True, choices = COURSE_TYPE) curso = CharField(label ='Curso*', required = True) instituicao = CharField(label ='Instituição*', required = True) duracao = CharField(label ='Duração*', required = True, help_text = 'Em horas inteiras. Somente Números.') data_entrada = DateField( widget= TextInput(attrs={"onkeypress": "return dateMask(this, event);","name":"datNascimento", "id":"datNascimento", "type":"text", "maxlength":"10" } ), label = 'Data da entrada*', required = True, help_text = 'Ex: dd/mm/aaaa') data_saida = DateField( widget= TextInput(attrs={"onkeypress": "return dateMask(this, event);","name":"datNascimento", "id":"datNascimento", "type":"text", "maxlength":"10" } ), label = 'Data da conclusão', required = False, help_text = 'Caso não tenha concluído, deixe esse campo em branco.') class Meta: model = Curso exclude = ['candidato'] class IdiomaForm(ModelForm): idioma = CharField(label ='Idioma*', required = True) nivel = ChoiceField(label ='Nível*', required = True, choices = LEVEL) class Meta: model = Idioma exclude = ['candidato'] class PretencoesForm(ModelForm): profissao = ModelChoiceField ( label = 'Ocupação', queryset = Profissoes.objects.all(), #widget = autocomplete.Select2(url='candidato:select2_fk'), ) class Meta: model = Pretencoes exclude = ['candidato']<file_sep>from django.template import Library from django.contrib.auth import authenticate, login, get_user_model register = Library() User = get_user_model() from vagas.models import * from empregador.models import Empregador from usuario.models import User @register.inclusion_tag('templatetags/vaga_tag.html') def vagastag(user): vagas = Vaga.objects.filter(status = True, finalizada = False).order_by('-data_criacao') context = { 'vagas': vagas, } return context <file_sep>from django.contrib import admin from candidato.models import Candidato from empregador.models import Empregador from .models import * # Register your models here. class RequisitosInline(admin.StackedInline): model = Requisitos class VagaAdmin(admin.ModelAdmin): inlines = (RequisitosInline,) class CandidaturaAdmin(admin.ModelAdmin): model = Candidatura admin.site.register(Vaga, VagaAdmin) admin.site.register(Candidatura, CandidaturaAdmin)<file_sep># Generated by Django 2.0.2 on 2018-04-02 13:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('vagas', '0001_initial'), ] operations = [ migrations.AddField( model_name='vaga', name='inscritos', field=models.IntegerField(blank=True, null=True, verbose_name='Quantidade de inscritos'), ), ] <file_sep># Portal-Ciesga <file_sep>{% extends "dashboard_candidato.html" %} {% block breadcrumb %} {{ block.super }} <li>/</li> <li><a href="{% url 'candidato:info_basica' %}">Editar Conta</a></li> {% endblock %} {% block dashboard_content %} <script language="JavaScript" type="text/javascript"> function dateMask(inputData, e){ var tecla; if(document.all) // Internet Explorer tecla = event.keyCode; else //Outros Browsers tecla = e.which; if(tecla >= 47 && tecla < 58){ // numeros de 0 a 9 e '/' var data = inputData.value; //se for um numero coloca no input if(tecla > 47 && tecla < 58){ if (data.length == 2 || data.length == 5){ data += '/'; } }else if(tecla == 47){ //se for a barra, so deixa colocar se estiver na posicao certa if (data.length != 2 && data.length != 5){ return false; } } //atualiza o input da data inputData.value = data; return true; }else if(tecla == 8 || tecla == 0) // Backspace, Delete e setas direcionais(para mover o cursor, apenas para FF) return true; else return false; } ///////////////////////////////////// </script> <h2 class="content-subhead">Informações Básicas</h2> <br> <br> <li>Os campos marcados com um asterisco * são de preenchimento obrigatório.</li> <form class="pure-form pure-form-stacked" method="post"> {% csrf_token %} <fieldset> {{ form2.non_field_errors }} {{ form1.non_field_errors }} {% for field in form2 %} <div class="pure-control-group"> {{ field.label_tag }} {{ field }} {{ field.help_text }} {{ field.errors }} </div> {% endfor %} {% for field in form1 %} <div class="pure-control-group"> {{ field.label_tag }} {{ field }} {{ field.help_text }} {{ field.errors }} </div> {% endfor %} <div class="pure-controls"> <button type="submit" class="pure-button pure-button-primary">Salvar Modificações</button> </div> </fieldset> </form> {% endblock %}<file_sep>from django.apps import AppConfig class EmpregadorConfig(AppConfig): name = 'empregador' <file_sep># Generated by Django 2.0.2 on 2018-04-02 13:38 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Candidato', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('cpf', models.CharField(max_length=14, unique=True, verbose_name='CPF')), ('data_nascimento', models.DateField(blank=True, null=True, verbose_name='Data de Nascimento')), ('logradouro', models.CharField(blank=True, max_length=100, null=True, verbose_name='Rua')), ('numeroLog', models.CharField(blank=True, max_length=10, null=True, verbose_name='Número')), ('bairro', models.CharField(blank=True, max_length=50, null=True, verbose_name='Bairro')), ('cidade', models.CharField(blank=True, max_length=50, null=True, verbose_name='Cidade')), ('uf', models.CharField(blank=True, max_length=50, null=True, verbose_name='UF')), ('cep', models.CharField(blank=True, max_length=10, null=True, verbose_name='CEP')), ('complemento', models.CharField(blank=True, max_length=100, null=True, verbose_name='Complemento')), ('tel1', models.CharField(blank=True, max_length=12, null=True, verbose_name='Tel(1)')), ('tel2', models.CharField(blank=True, max_length=12, null=True, verbose_name='Tel(2)')), ('obs', models.CharField(blank=True, max_length=200, null=True)), ('deficiente', models.CharField(blank=True, choices=[('', ''), ('Sim', 'Sim'), ('Nao', 'Não')], max_length=5, null=True, verbose_name='Portador de deficiência')), ('escolaridade', models.CharField(blank=True, choices=[('', ''), ('Fundamental incompleto', 'Fundamental incompleto'), ('Fundamental completo', 'Fundamental completo'), ('Medio incompleto', 'Médio incompleto'), ('Medio completo', 'Médio completo'), ('Tecnico incompleto', 'Técnico incompleto'), ('Tecnico completo', 'Técnico completo'), ('Superior incompleto', 'Superior incompleto'), ('Superior completo', 'Superior completo'), ('Pos-Graduacao', 'Pós-Graduação'), ('Mestrado', 'Mestrado'), ('Doutorado', 'Doutorado'), ('PHD', 'PHD')], max_length=25, null=True, verbose_name='Escolaridade')), ('habilitacao', models.CharField(blank=True, choices=[('', ''), ('A', 'A'), ('AB', 'AB'), ('AC', 'AC'), ('AD', 'AD'), ('B', 'B'), ('C', 'C'), ('D', 'D'), ('E', 'E')], max_length=25, null=True, verbose_name='Habilitação')), ('estado_civil', models.CharField(blank=True, choices=[('', ''), ('Solteiro', 'Solteiro(a)'), ('Casado', 'Casado(a)'), ('Divorciado', 'Divorciado(a)'), ('Outros', 'Outros')], max_length=25, null=True, verbose_name='Estado civil')), ('genero', models.CharField(blank=True, choices=[('', ''), ('Masculino', 'Masculino'), ('Feminino', 'Feminino'), ('Outros', 'Outros')], max_length=25, null=True, verbose_name='Gênero')), ], ), migrations.CreateModel( name='Curso', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('tipo', models.CharField(blank=True, choices=[('', ''), ('Curso de Qualificacao', 'Curso de Qualificação'), ('Curso Profissionalizante', 'Curso Profissionalizante'), ('Palestra', 'Palestra'), ('Simposio', 'Simpósio')], max_length=25, null=True, verbose_name='Tipo')), ('curso', models.CharField(blank=True, max_length=50, null=True, verbose_name='Curso')), ('instituicao', models.CharField(blank=True, max_length=30, null=True, verbose_name='Instituição')), ('duracao', models.CharField(blank=True, max_length=5, null=True, verbose_name='Duração')), ('data_entrada', models.DateField(blank=True, null=True, verbose_name='Data de Entrada')), ('data_saida', models.DateField(blank=True, null=True, verbose_name='Data de Conclusão')), ('candidato', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='candidato.Candidato')), ], ), migrations.CreateModel( name='Experiencia', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('empresa', models.CharField(blank=True, max_length=100, null=True, verbose_name='Empresa')), ('cargo', models.CharField(blank=True, max_length=100, null=True, verbose_name='Cargo')), ('descricao', models.TextField(blank=True, max_length=1000, null=True, verbose_name='Descrição das atividades')), ('data_entrada', models.DateField(blank=True, null=True, verbose_name='Data da contratação')), ('data_saida', models.DateField(blank=True, null=True, verbose_name='Data da saída')), ('candidato', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='candidato.Candidato')), ], ), migrations.CreateModel( name='Formacao', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('grau', models.CharField(blank=True, choices=[('', ''), ('Medio Tecnico', 'Médio Técnico'), ('Superior', 'Superior'), ('Especializacao', 'Especialização'), ('Pos-Graduacao', 'Pós-Graduação'), ('Mestrado', 'Mestrado'), ('Doutorado', 'Doutorado'), ('PHD', 'PHD')], max_length=25, null=True, verbose_name='Nível')), ('instituicao', models.CharField(blank=True, max_length=100, null=True, verbose_name='Instituição')), ('curso', models.CharField(blank=True, max_length=50, null=True, verbose_name='Curso')), ('data_entrada', models.DateField(blank=True, null=True, verbose_name='Data de Entrada')), ('data_conclusao', models.DateField(blank=True, null=True, verbose_name='Data de Saída')), ('candidato', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='formacao', to='candidato.Candidato')), ], ), migrations.CreateModel( name='Idioma', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('idioma', models.CharField(blank=True, max_length=20, null=True)), ('nivel', models.CharField(blank=True, choices=[('', ''), ('Basico', 'Básico'), ('Intermediario', 'Intermediário'), ('Avancado', 'Avançado'), ('Fluente', 'Fluente')], max_length=25, null=True)), ('candidato', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='candidato.Candidato')), ], ), migrations.CreateModel( name='Pretencoes', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('experiencia', models.BooleanField(default=False, verbose_name='Tenho experiência na função')), ('comprovacao', models.BooleanField(default=False, verbose_name='Posso comprovar')), ('candidato', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='candidato.Candidato')), ], ), migrations.CreateModel( name='Profissoes', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nome_prof', models.CharField(blank=True, max_length=100, null=True, verbose_name='Profissão')), ], ), migrations.AddField( model_name='pretencoes', name='profissao', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='candidato.Profissoes'), ), ] <file_sep>from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.forms import (UserCreationForm, PasswordChangeForm, SetPasswordForm) from django.contrib.auth import authenticate, login, get_user_model from django.contrib.auth.decorators import login_required from django.conf import settings from django.contrib import messages from core.utils import generate_hash_key from .forms import RegisterForm, PasswordResetForm, Register_EmpregadorForm from .models import PasswordReset, User User = get_user_model() # Create your views here. def register(request): template_name = 'register.html' if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save() user = authenticate( username=user.username, password=<PASSWORD>.cleaned_data['<PASSWORD>'] ) login(request, user) return redirect('usuario:dashboard') else: form = RegisterForm() context = { 'form': form, } return render(request, template_name, context) def register_empregador(request): template_name = 'register_empregador.html' context = {} if request.method == 'POST': form = Register_EmpregadorForm(request.POST) if form.is_valid(): user = form.save() user = authenticate( username=user.username, password=<PASSWORD>.cleaned_data['<PASSWORD>'] ) login(request, user) return redirect('usuario:dashboard') else: form = Register_EmpregadorForm() context = { 'form': form, } return render(request, template_name, context) def password_reset(request): template_name = 'password_reset.html' context = {} form = PasswordResetForm(request.POST or None) if form.is_valid(): form.save() context['success'] = True context['form'] = form return render(request, template_name, context) def password_reset_confirm(request, key): template_name = 'password_reset_confirm.html' context = {} reset = get_object_or_404(PasswordReset, key=key) form = SetPasswordForm(user=reset.user, data=request.POST or None) if form.is_valid(): form.save() context['success'] = True context['form'] = form return render(request, template_name, context) @login_required def dashboard(request): user=request.user if user.user_type == 'Candidato': template_name = 'dashboard_candidato.html' context = {} return render(request, template_name, context) else : template_name = 'dashboard_empregador.html' context = {} return render(request, template_name, context) @login_required def edit_password(request): user = request.user if user.user_type == 'Candidato': template_name = 'edit_password.html' else: template_name = 'edit_password_empregador.html' context = {} if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() context['success'] = True else: form = PasswordChangeForm(user=request.user) context['form'] = form return render(request, template_name, context) def choice_register(request): return render(request, 'choice_register.html') <file_sep>from django.db import models import re import datetime from django.core import validators from django.conf import settings from core.choices import * from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin, UserManager) from django.contrib.auth.validators import UnicodeUsernameValidator class User(AbstractBaseUser, PermissionsMixin): username_validator = UnicodeUsernameValidator() username = models.CharField( 'Usuário', max_length=30, unique=True, validators=[username_validator], ) name = models.CharField('Nome Completo', max_length=100, blank=True) email = models.EmailField('E-mail', unique=True) is_active = models.BooleanField('Está ativo?', blank=True, default=True) is_staff = models.BooleanField('É da equipe?', blank=True, default=False) date_joined = models.DateTimeField('Data de Entrada', auto_now_add=True) user_type = models.CharField( 'Tipo de Usuário', max_length=25, blank=False, choices=USER_TYPE, ) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return self.name or self.username def get_short_name(self): return self.username def get_full_name(self): return str(self) class Meta: verbose_name = 'Usuario' verbose_name_plural = 'Usuarios' class PasswordReset(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name='Usuario', #related_name='resets', on_delete=models.CASCADE, ) key = models.CharField('Chave', max_length=100, unique=True) created_at = models.DateTimeField('Criado em', auto_now_add=True) confirmed = models.BooleanField('Confirmado?', default=False, blank=True) def __str__(self): return '{0} em {1}'.format(self.user, self.created_at) class Meta: verbose_name = '<NAME>' verbose_name_plural = 'Novas Senhas' ordering = ['-created_at'] <file_sep>from django.conf.urls import include, url from django.urls import path from . import views #from .views import PretencoesAutocomplete from .models import Profissoes, Pretencoes from dal import autocomplete app_name='candidato' urlpatterns = [ path("info_basica", views.info_basica, name='info_basica'), path("formacao", views.formacao, name='formacao'), path("formacao/excluir-formacao/<id>", views.excluir_formacao, name='excluir_formacao'), path("formacao/editar-formacao/<id>", views.editar_formacao, name='editar_formacao'), path("experiencia", views.experiencia, name='experiencia'), path("experiencia/excluir-experiencia/<id>", views.excluir_experiencia, name='excluir_experiencia'), path("experiencia/editar-experiencia/<id>", views.editar_experiencia, name='editar_experiencia'), path("curso", views.curso, name='curso'), path("curso/excluir-curso/<id>", views.excluir_curso, name='excluir_curso'), path("curso/editar-curso/<id>", views.editar_curso, name='editar_curso'), path("idioma", views.idioma, name='idioma'), path("idioma/excluir-idioma/<id>", views.excluir_idioma, name='excluir_idioma'), path("idioma/editar-idioma/<id>", views.editar_idioma, name='editar_idioma'), path("pretencoes", views.pretencoes, name='pretencoes'), path("idioma/excluir-pretencao/<id>", views.excluir_pretencao, name='excluir_pretencao'), path("idioma/editar-pretencao/<id>", views.editar_pretencao, name='editar_pretencao'), #path("ocupacao-autocomplete", views.PretencoesAutocomplete, name='ocupacao_autocomplete'), path('ocupacao-autocomplete',autocomplete.Select2QuerySetView.as_view(model=Profissoes), name='select2_fk'), path("minhas-candidaturas", views.minhas_candidaturas, name='minhas_candidaturas'), path("minhas-candidaturas/excluir-candidatura/<id>", views.excluir_candidatura, name='excluir_candidatura'), ] <file_sep>from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import get_user_model from .models import User from candidato.models import * from empregador.models import * from core.utils import generate_hash_key from core.mail import send_mail_template from .models import PasswordReset from django.contrib.localflavor.br.forms import BRCPFField,BRCNPJField #from captcha.fields import CaptchaField User = get_user_model() class RegisterForm(forms.ModelForm): cpf = BRCPFField(label = 'CPF',max_length = 14 , min_length = 11) password1 = forms.CharField(label='Senha', widget=forms.PasswordInput) password2 = forms.CharField( label='Confirmação de Senha', widget=forms.PasswordInput ) #captcha = CaptchaField() def clean_cpf(self): cpf=self.cleaned_data['cpf'] if Candidato.objects.filter(cpf=cpf).exists(): raise forms.ValidationError('CPF já cadastrado') return cpf def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError('A confirmação não está correta') return password2 def save(self, commit=True): user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data['password1']) user.user_type = "Candidato" if commit: user.save() candidato = Candidato() candidato.user_id = user.id candidato.cpf = self.cleaned_data['cpf'] candidato.save() return user class Meta: model = User fields = ['username', 'email'] class Register_EmpregadorForm(forms.ModelForm): cnpj = BRCNPJField(label = 'CNPJ',max_length = 18 , min_length = 14) password1 = forms.CharField(label='Senha', widget=forms.PasswordInput) password2 = forms.CharField( label='Confirmação de Senha', widget=forms.PasswordInput ) #captcha = CaptchaField() def clean_cpf(self): cpf=self.cleaned_data['cpf'] if Candidato.objects.filter(cpf=cpf).exists(): raise forms.ValidationError('CPF já cadastrado') return cpf def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError('A confirmação não está correta') return password2 def save(self, commit=True): user = super(Register_EmpregadorForm, self).save(commit=False) user.set_password(self.cleaned_data['<PASSWORD>']) user.user_type = "Empregador" if commit: user.save() empregado = Empregador() empregado.user_id = user.id empregado.cnpj = self.cleaned_data['cnpj'] empregado.save() return user class Meta: model = User fields = ['username', 'email'] class PasswordResetForm(forms.Form): email = forms.EmailField(label='Email') def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): return email raise forms.ValidationError( 'Nenhum usuário encontrado com este e-mail' ) def save(self): user = User.objects.get(email=self.cleaned_data['email']) key = generate_hash_key(user.username) reset = PasswordReset(key=key, user=user) reset.save() template_name = 'password_reset_mail.html' subject = 'Criar nova senha no Portal CIESGA' context = { 'reset': reset, } send_mail_template(subject, template_name, context, [user.email]) class UserAdminCreationForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'name'] class UserForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'name', 'user_type','is_active', 'is_staff'] <file_sep>from django.conf.urls import include, url from django.urls import path from . import views app_name='empregador' urlpatterns = [ path("info-basica", views.info_basica2, name='info_basica2'), path("cadastrar-vaga", views.cadastrar_vaga, name='cadastrar_vaga'), path("minhas-vagas", views.minhas_vagas, name='minhas_vagas'), path("minhas-vagas/excluir-vagas/<id>", views.excluir_vaga, name='excluir_vaga'), path("minhas-vagas/editar-vaga/<id>", views.editar_vaga, name='editar_vaga'), path("minhas-vagas/status-vagas/<id>", views.status_vaga, name='status_vaga'), path("minhas-vagas/ver-inscritos/<id>/", views.ver_inscritos, name='ver_inscritos'), path("minhas-vagas/ver-inscritos/detalhes/<id>", views.detalhes_candidato, name='detalhes_candidato'), ] <file_sep>from django.template import Library register = Library() from candidato.models import * from usuario.models import User @register.inclusion_tag('templatetags/cursos_tag.html') def cursostag(user): cursos = Curso.objects.filter(candidato = user.candidato) context = { 'cursos': cursos } return context <file_sep>from django.template import Library register = Library() from candidato.models import * from usuario.models import User @register.inclusion_tag('templatetags/formacoes_tag.html') def formacoestag(user): formacoes = Formacao.objects.filter(candidato = user.candidato) context = { 'formacoes': formacoes } return context <file_sep>import pytz YESORNOT_CHOICES = ( ('',''), ('Sim','Sim'), ('Nao','Não'), ) GENDER_CHOICES = ( ('',''), ('Masculino','Masculino'), ('Feminino', 'Feminino'), ('Outros', 'Outros'), ) EDUCATION_CHOICES = ( ('',''), ('Fundamental incompleto','Fundamental incompleto'), ('Fundamental completo', 'Fundamental completo'), ('Medio incompleto','Médio incompleto'), ('Medio completo','Médio completo'), ('Tecnico incompleto','Técnico incompleto'), ('Tecnico completo', 'Técnico completo'), ('Superior incompleto','Superior incompleto'), ('Superior completo','Superior completo'), ('Pos-Graduacao', 'Pós-Graduação'), ('Mestrado', 'Mestrado'), ('Doutorado', 'Doutorado'), ('PHD', 'PHD') ) EDUCATION_CHOICES_FORMATION = ( ('',''), ('Medio Tecnico','Médio Técnico'), ('Superior','Superior'), ('Especializacao','Especialização'), ('Pos-Graduacao', 'Pós-Graduação'), ('Mestrado', 'Mestrado'), ('Doutorado', 'Doutorado'), ('PHD', 'PHD') ) LEVEL = ( ('',''), ('Basico', 'Básico'), ('Intermediario', 'Intermediário'), ('Avancado', 'Avançado'), ('Fluente', 'Fluente'), ) HABILITACAO = ( ('',''), ('A', 'A'), ('AB', 'AB'), ('AC', 'AC'), ('AD', 'AD'), ('B', 'B'), ('C', 'C'), ('D', 'D'), ('E', 'E'), ) USER_TYPE = ( ('Candidato', 'Candidato'), ('Empregador', 'Empregador'), ) COURSE_TYPE = ( ('',''), ('Curso de Qualificacao', 'Curso de Qualificação'), ('Curso Profissionalizante', 'Curso Profissionalizante'), ('Palestra', 'Palestra'), ('Simposio', 'Simpósio'), ) BRANCH_ACTIVITY = ( ('',''), ('Industria', 'Indústria'), ('Comercio', 'Comércio'), ('Prestacao de Servicos', 'Prestação de Serviços'), ('Outros', 'Outros'), ) BRANCH_TYPE = ( ('',''), ('MEI', 'MEI - Faturamento até R$ 81 mil'), ('ME', 'ME - Faturamento até R$ 360 mil'), ('EPP', 'EPP - Faturamento até R$ 3,6 milhões'), ('Empresa Normal', 'Empresa Normal - Faturamento superior a R$ 3,6 milhões'), ) BRANCH_TYPE = ( ('',''), ('MEI', 'MEI - Faturamento até R$ 81 mil'), ('ME', 'ME - Faturamento até R$ 360 mil'), ('EPP', 'EPP - Faturamento até R$ 3,6 milhões'), ('Empresa Normal', 'Empresa Normal - Faturamento superior a R$ 3,6 milhões'), ) MARITAL_STATUS = ( ('',''), ('Solteiro', 'Solteiro(a)'), ('Casado', 'Casado(a)'), ('Divorciado', 'Divorciado(a)'), ('Outros', 'Outros'), )<file_sep>from django.conf.urls import include, url from django.urls import path from . import views app_name='core' urlpatterns = [ path("", views.home, name='home'), path('contato', views.contact, name='contact'), path('saiba-mais', views.saiba_mais, name='saiba_mais') ]
bb52f9b63c86501fc50f9ac17cb20a7b4c794e1c
[ "Markdown", "Python", "Text", "HTML" ]
46
Python
arthoryuss/Portal-Ciesga
300c4ae314cf617ca6c6679eb09ac73ebd8d2073
cefc0afef575dd2a79853b674a50faf5133e538e
refs/heads/master
<file_sep>--Horst defines: -------------------------------------------------------------- --test NDefines_Graphics.NGraphics.BORDER_WIDTH = 1 NDefines.NNavy.CONVOY_LOSS_HISTORY_TIMEOUT_MONTHS = 3 NDefines.NNavy.NAVAL_COMBAT_RESULT_TIMEOUT_YEARS = 5 NDefines.NAI.GIVE_STATE_CONTROL_MIN_CONTROLLED = 0 -- WAS 1 NDefines.NAI.GIVE_STATE_CONTROL_MIN_CONTROL_DIFF = 0 -- WAS 2 NDefines.NTechnology.MAX_SUBTECHS = 4 --Performance NDefines.NGame.COMBAT_LOG_MAX_MONTHS = 12 NDefines.NGame.LAG_DAYS_FOR_LOWER_SPEED = 300 NDefines.NGame.LAG_DAYS_FOR_PAUSE = 100 NDefines.NCountry.EVENT_PROCESS_OFFSET = 30 NDefines.NDiplomacy.DIPLOMACY_HOURS_BETWEEN_REQUESTS = 12 NDefines.NFocus.MAX_SAVED_FOCUS_PROGRESS = 15 NDefines.NAI.DIPLOMACY_SEND_EXPEDITIONARY_BASE = 0 --------------------------------------------------------------- NDefines.NTrade.ANTI_MONOPOLY_TRADE_FACTOR = -1 -- was -100 | This is added to the factor value when anti-monopoly threshold is exceeded; cucks Soviets/Japan often if the value is vanilla --------------------------------------------------------------- NDefines.NAir.AIR_WING_MAX_SIZE = 1600 -- this can be halved 4 times into 100 stacks (very convinient), up from 1600 | NDefines.NAir.AIR_DEPLOYMENT_DAYS = 0 -- Down from 3 | Makes AC player much more responsive --------------------------------------------------------------- NDefines.NFocus.MAX_SAVED_FOCUS_PROGRESS = 15 --up from 10, should allow for more flexibility with picking focuses while doing something else, like tank templates --------------------------------------------------------------- NDefines.NDiplomacy.NUM_DAYS_TO_ENABLE_KICKING_NEW_MEMBERS_OF_FACTION = 14 -- down from 90 | Number of days before being able to kick a new member of faction NDefines.NDiplomacy.NUM_DAYS_TO_ENABLE_REINVITE_KICKED_NATIONS = 14 -- down from 90 | Number of days before being able to re invite a kicked NDefines.NDiplomacy.GUARANTEE_COST = 1000 NDefines.NDiplomacy.REVOKE_GUARANTEE_COST = 1000 NDefines.NDiplomacy.PEACE_SCORE_PER_PASS = 100.0 -- When you pass once you should get enough points to finish the peace deal NDefines.NDiplomacy.VOLUNTEERS_PER_COUNTRY_ARMY = 1 -- WAS 0.05 | Each army unit owned by the source country contributes this amount of volunteers to the limit. NDefines.NDiplomacy.VOLUNTEERS_DIVISIONS_REQUIRED = 0 -- WAS 30 | This many divisons are required for the country to be able to send volunteers. NDefines.NDiplomacy.FRONT_IS_DANGEROUS = 0 --------------------------------------------------------------- NDefines.NPolitics.DEFAULT_OCCUPATION_POLICY = 4 --HARSHEST --------------------------------------------------------------- NDefines.NProduction.MIN_LICENSE_ACTIVE_DAYS = 1 -- License can be cancelled at any time now, down from 30 | NDefines.NProduction.BASE_LICENSE_IC_COST = 1 -- Was 1, reduced to counter early game boosting, particularly cancerous Germany builds that force Bulgaria players to build a battleship in the black sea for "shore bombardment" via license and imported steel from Germany NDefines.NProduction.MIN_POSSIBLE_TRAINING_MANPOWER = 500000 --------------------------------------------------------------- NDefines.NCountry.SPECIAL_FORCES_CAP_MIN = 1000 -- up from 24 | You can have a minimum of this many special forces battalions, regardless of the number of non-special forces battalions you have, this can also be modified by a country modifier NDefines.NCountry.DAYS_OF_WAR_BEFORE_SURRENDER = 3 -- down from 7 | why not allow Luxembourg to cap faster NDefines.NCountry.NUM_DAYS_TO_FULLY_DELETE_STOCKPILED_EQUIPMENT = 999 NDefines.NCountry.RESISTANCE_STRENGTH_FROM_VP = 0 NDefines.NCountry.RESISTANCE_STRENGTH_FROM_UNIT = 0 NDefines.NCountry.RESISTANCE_STRENGTH_FROM_NEIGHBORS = 0 --------------------------------------------------------------- NDefines.NNavy.TRAINING_ACCIDENT_CHANCES = 0.001 -- down from 0.02 | Chances one ship get damage each hour while on training --------------------------------------------------------------- NDefines.NAI.DIPLOMACY_REJECTED_WAIT_MONTHS_BASE = 24 --up from 4 | should cut down on AI spam NDefines.NAI.DIPLOMACY_ACCEPT_ATTACHE_OPINION_PENALTY = 0 --------------------------------------------------------------- NDefines_Graphics.NGraphics.COMMANDGROUP_PRESET_COLORS_HSV = { 0.0/360.0, 1.0, 1.0, --red 10.0/360.0, 1.0, 1.0, --orange 60.0/360.0, 1.0, 1.0, --yellow 120.0/360.0, 0.75, 1.0, --green 180.0/360.0, 1.0, 1.0, --turq 235.0/360.0, 1.0, 1.0, --blue 260.0/360.0, 1.0, 1.0, --dark purple 300.0/360.0, 1.0, 1.0, --light purple 330.0/360.0, 0, 1.0 --white } NDefines_Graphics.NAirGfx.MAX_MISSILE_BOMBING_SCENARIOS = 0 NDefines_Graphics.NAirGfx.MAX_BOMBING_SCENARIOS = 0 NDefines_Graphics.NAirGfx.MAX_PATROL_SCENARIOS = 0 NDefines_Graphics.NAirGfx.MAX_DOGFIGHTS_SCENARIOS = 0 NDefines_Graphics.NAirGfx.MAX_TRANSPORT_SCENARIOS = 0 NDefines_Graphics.NGraphics.CAMERA_ZOOM_SPEED_DISTANCE_MULT = 20 NDefines_Graphics.NGraphics.MAPICON_GROUP_STRATEGIC_SIZE = 1000 NDefines_Graphics.NGraphics.MAP_ICONS_STATE_HUGE = 100 NDefines_Graphics.NGraphics.GRADIENT_BORDERS_FIELD_COUNTRY_REFRESH = 30 NDefines_Graphics.NGraphics.DECISION_MAP_ICON_DISTANCE_CUTOFF = 100 NDefines_Graphics.NGraphics.NAVAL_COMBAT_DISTANCE_CUTOFF = 1200 NDefines_Graphics.NGraphics.PROVINCE_ANIM_TEXT_DISTANCE_CUTOFF = 200 NDefines_Graphics.NMapMode.MAP_MODE_TERRAIN_TRANSPARENCY = 0.8 NDefines_Graphics.NGraphics.AIRBASE_ICON_DISTANCE_CUTOFF = 600 NDefines_Graphics.NGraphics.NAVALBASE_ICON_DISTANCE_CUTOFF = 600 NDefines_Graphics.NGraphics.RADAR_ICON_DISTANCE_CUTOFF = 150 NDefines_Graphics.NAirGfx.AIRPLANES_ANIMATION_GLOBAL_SPEED_PER_GAMESPEED = {0.3, 0.3, 0.3, 0.3, 0.3, 0.3} NDefines_Graphics.NGraphics.DRAW_MAP_OBJECTS_CUTOFF = 1.0 NDefines_Graphics.NGraphics.VICTORY_POINTS_DISTANCE_CUTOFF = {200, 350, 500} NDefines_Graphics.NGraphics.MAX_MESHES_LOADED_PER_FRAME = 5 NDefines_Graphics.NMapMode.RADAR_ROTATION_SPEED = 0.0 NDefines_Graphics.NMapMode.AIR_RANGE_INDICATOR_ROTATION_SPEED = 0.0000 NDefines_Graphics.NAirGfx.AIRPLANES_SMOOTH_INTERPOLATION_MOVE = 0.02 NDefines_Graphics.NAirGfx.AIRPLANES_SMOOTH_INTERPOLATION_TURN = 0.02 NDefines_Graphics.NInterface.GRIDBOX_ELEMENTS_INTERPOLATION_SPEED = 0.2 NDefines_Graphics.NGraphics.TREE_FADE_NEAR = 150.0 NDefines_Graphics.NGraphics.TREE_FADE_FAR = 250.0 NDefines_Graphics.NGraphics.RESOURCE_MAP_ICON_TEXT_CUTOFF = 400 NDefines_Graphics.NGraphics.UNITS_DISTANCE_CUTOFF = 100 NDefines_Graphics.NGraphics.SHIPS_DISTANCE_CUTOFF = 200 NDefines_Graphics.NGraphics.UNIT_ARROW_DISTANCE_CUTOFF = 500 NDefines_Graphics.NGraphics.UNITS_ICONS_DISTANCE_CUTOFF = 700 NDefines_Graphics.NGraphics.NAVAL_COMBAT_DISTANCE_CUTOFF = 1000 NDefines_Graphics.NGraphics.ADJACENCY_RULE_DISTANCE_CUTOFF = 1300 NDefines_Graphics.NGraphics.LAND_COMBAT_DISTANCE_CUTOFF = 800 NDefines_Graphics.NGraphics.SUPPLY_ICON_DISTANCE_CUTOFF = 1500 NDefines_Graphics.NGraphics.PROV_CONSTRUCTION_ICON_DISTANCE_CUTOFF = 300 NDefines_Graphics.NGraphics.STATE_CONSTRUCTION_ICON_DISTANCE_CUTOFF = 600 NDefines_Graphics.NGraphics.GRADIENT_BORDERS_REFRESH_FREQ = 0.2 NDefines_Graphics.NGraphics.MAPICON_GROUP_PASSES = 5 NDefines_Graphics.NGraphics.DRAW_REFRACTIONS_CUTOFF = 0 NDefines_Graphics.NGraphics.GRADIENT_BORDERS_FIELD_COUNTRY_REFRESH = 40 NDefines_Graphics.NGraphics.WEATHER_DISTANCE_CUTOFF = 50 NDefines_Graphics.NGraphics.MAP_ICONS_GROUP_CAM_DISTANCE = 100 NDefines_Graphics.NGraphics.MAP_ICONS_STATE_GROUP_CAM_DISTANCE = 300 NDefines_Graphics.NGraphics.MAP_ICONS_STRATEGIC_GROUP_CAM_DISTANCE = 400 NDefines_Graphics.NGraphics.MAP_ICONS_STRATEGIC_AREA_HUGE = 250 NDefines_Graphics.NGraphics.MAP_ICONS_COARSE_COUNTRY_GROUPING_DISTANCE = 300 NDefines_Graphics.NGraphics.MAP_ICONS_COARSE_COUNTRY_GROUPING_DISTANCE_STRATEGIC = 0 NDefines_Graphics.NGraphics.BLOOM_WIDTH = 0 NDefines_Graphics.NGraphics.BLOOM_SCALE = 0 NDefines_Graphics.NGraphics.BRIGHT_THRESHOLD = 0 NDefines_Graphics.NGraphics.EMISSIVE_BLOOM_STRENGTH = 0 NDefines_Graphics.NGraphics.DAY_NIGHT_FEATHER = 0.024 NDefines_Graphics.NGraphics.DRAW_SHADOWS_CUTOFF = 0 NDefines_Graphics.NGraphics.DRAW_SHADOWS_FADE_LENGTH = 0 NDefines_Graphics.NGraphics.DRAW_FOW_CUTOFF = 0 NDefines_Graphics.NGraphics.DRAW_FOW_FADE_LENGTH = 0 --HFU defines: NDefines.NDiplomacy.BASE_SEND_ATTACHE_CP_COST = 0 NDefines.NDiplomacy.BASE_SEND_ATTACHE_COST= 100 NDefines.NDiplomacy.TENSION_VOLUNTEER_FORCE_DIVISION = 0.15 NDefines.NDiplomacy.VOLUNTEERS_TRANSFER_SPEED=0 --generals NDefines.NMilitary.UNIT_LEADER_ASSIGN_TRAIT_COST = 0.1 NDefines.NMilitary.FIELD_MARSHAL_XP_RATIO = 0 NDefines.NMilitary.LEADER_EXPERIENCE_SCALE = 0.0 NDefines.NMilitary.ARMY_LEADER_XP_GAIN_PER_UNIT_IN_COMBAT = 0 NDefines.NMilitary.CONSTANT_XP_RATIO_FOR_MULTIPLE_LEADERS_IN_SAME_COMBAT = 0 NDefines.NMilitary.BASE_LEADER_TRAIT_GAIN_XP = 0 NDefines.NMilitary.UNIT_EXPERIENCE_PER_TRAINING_DAY = 0.0000 NDefines.NMilitary.CORPS_COMMANDER_DIVISIONS_CAP = 36 NDefines.NMilitary.FIELD_MARSHAL_DIVISIONS_CAP = 36 NDefines.NMilitary.XP_GAIN_PER_OVERRUN_UNIT = 0 NDefines.NMilitary.XP_GAIN_FOR_SHATTERING = 0 --industry NDefines.NBuildings.MAX_SHARED_SLOTS = 99 --max building slots in a state NDefines.NBuildings.MAX_BUILDING_LEVELS=20 NDefines.NAir.AA_INDUSTRY_AIR_DAMAGE_FACTOR = -0.13 -- -0.12 NDefines.NBuildings.AIRBASE_CAPACITY_MULT = 100 ------------------------------------- --Combat NDefines.NMilitary.LAND_COMBAT_STR_DAMAGE_MODIFIER = 0.06 NDefines.NMilitary.HOURLY_ORG_MOVEMENT_IMPACT = -0.15 NDefines.NMilitary.ZERO_ORG_MOVEMENT_MODIFIER = -0.6 NDefines.NMilitary.RECON_SKILL_IMPACT = 7 NDefines.NMilitary.EXPERIENCE_COMBAT_FACTOR = 0.15 NDefines.NMilitary.COMBAT_MINIMUM_TIME = 2 NDefines.NCountry.REINFORCEMENT_EQUIPMENT_DELIVERY_SPEED = 0.5 NDefines.NCountry.REINFORCEMENT_MANPOWER_DELIVERY_SPEED = 18 NDefines.NCountry.REINFORCEMENT_MANPOWER_CHUNK = 0.08 NDefines.NBuildings.INFRA_TO_SUPPLY = 3 NDefines.NCountry.VP_TO_SUPPLY_BASE = 2 NDefines.NCountry.SUPPLY_PATH_MAX_DISTANCE = 8 NDefines.NMilitary.TACTIC_SWAP_FREQUENCEY = 10 NDefines.NMilitary.EXPERIENCE_LOSS_FACTOR = 0.1 NDefines.NMilitary.SLOWEST_SPEED = 4 --back to 4 NDefines.NMilitary.TRAINING_ATTRITION = 0.02 NDefines.NMilitary.MAX_NAVY_EXPERIENCE = 999 NDefines.NMilitary.MAX_AIR_EXPERIENCE = 999 NDefines.NMilitary.MAX_ARMY_EXPERIENCE = 999 NDefines.NMilitary.BASE_DIVISION_BRIGADE_GROUP_COST = 0 NDefines.NMilitary.BASE_DIVISION_BRIGADE_CHANGE_COST = 0 NDefines.NMilitary.BASE_DIVISION_SUPPORT_SLOT_COST = 0 NDefines.NMilitary.ENCIRCLED_DISBAND_MANPOWER_FACTOR = 0.0 NDefines.NMilitary.RIVER_CROSSING_PENALTY_LARGE = -0.3 NDefines.NNavy.NAVAL_MINES_IN_REGION_MAX = 0 NDefines.NNavy.NAVAL_MINES_IN_REGION_MAX = 0 NDefines.NNavy.NAVAL_MINES_IN_REGION_MAX = 0 NDefines.NNavy.PRIDE_OF_THE_FLEET_UNASSIGN_COST = 0 NDefines.NNavy.CONVOY_DEFENSE_MAX_CONVOY_TO_SHIP_RATIO = 20 NDefines.NNavy.ADMIRAL_TASKFORCE_CAP = 20 ------------------------------------- --Air changes NDefines.NAir.COMBAT_MULTIPLANE_CAP = 2 --vanilla 3 NDefines.NAir.COMBAT_DAMAGE_SCALE = 0.15 -- Vanilla 0,10 NDefines.NAir.DISRUPTION_FACTOR = 5 NDefines.NAir.ESCORT_FACTOR = 2.5 NDefines.NAir.ANTI_AIR_MAXIMUM_DAMAGE_REDUCTION_FACTOR = 0.55 -- Vanilla 0,75 NDefines.NAir.AIR_WING_COUNTRY_XP_FROM_TRAINING_FACTOR = 0.0025 --Vanilla 0,005 NDefines.NNavy.ANTI_AIR_TARGETTING_TO_CHANCE = 0.1 --Vanilla 0,2 NDefines.NNavy.ANTI_AIR_ATTACK_TO_AMOUNT = 0.005 -- Vanilla 0,1 NDefines.NNavy.ANTI_AIR_TARGETING = 0.7 --Vanilla 0,9 NDefines.NMilitary.ENEMY_AIR_SUPERIORITY_SPEED_IMPACT = -0.3 --Vanilla 0.3 NDefines.NMilitary.ENEMY_AIR_SUPERIORITY_IMPACT = -0.45 --Vanilla -0.35 NDefines.NAir.AIR_MORE_GROUND_CREWS_COST = 400.0 NDefines.NAir.ANTI_AIR_PLANE_DAMAGE_FACTOR = 0.6 --Vanilla 0.8 NDefines.NAir.AIR_WING_COUNTRY_XP_FROM_TRAINING_FACTOR = 0.000 NDefines.NAir.ANTI_AIR_ATTACK_TO_DAMAGE_REDUCTION_FACTOR = 2.0 --Paratrooper changes NDefines.NMilitary.PARACHUTE_COMPLETE_ORG = 0.30 -- 33% org on drop NDefines.NMilitary.PARACHUTE_ORG_REGAIN_PENALTY_DURATION = 72 -- 72hrs of org regen 'penalty' NDefines.NMilitary.PARACHUTE_ORG_REGAIN_PENALTY_MULT = -0.50 -- +50% org regen, normal is -80% NDefines.NMilitary.PARACHUTE_DISRUPTED_AA_PENALTY = 2 NDefines.NGame.MISSION_REMOVE_FROM_INTERFACE_DEFAULT=7 <file_sep>NDefines.NProduction.DEFAULT_MAX_NAV_FACTORIES_PER_LINE = 10 NDefines.NProduction.CONVOY_MAX_NAV_FACTORIES_PER_LINE = 15 NDefines.NProduction.CAPITAL_SHIP_MAX_NAV_FACTORIES_PER_LINE = 10 NDefines.NProduction.MIN_NAVAL_EQUIPMENT_CONVERSION_IC_COST_FACTOR = 0.1 -- Minimum fraction of an equipment type's base industry capacity cost to use when converting a naval equipment, such as through ship refitting. NDefines.NProduction.MIN_NAVAL_EQUIPMENT_CONVERSION_RESOURCE_COST_FACTOR = 0.1 -- Minimum fraction of an equipment type's base strategic resource cost to use when converting a naval equipment, such as through ship refitting. NDefines.NProduction.EQUIPMENT_MODULE_ADD_XP_COST = 0.0 -- XP cost for adding a new equipment module in an empty slot when creating an equipment variant. NDefines.NProduction.EQUIPMENT_MODULE_REPLACE_XP_COST = 0.0 -- XP cost for replacing one equipment module with an unrelated module when creating an equipment variant. NDefines.NProduction.EQUIPMENT_MODULE_CONVERT_XP_COST = 0.0 -- XP cost for converting one equipment module to a related module when creating an equipment variant. NDefines.NProduction.EQUIPMENT_MODULE_REMOVE_XP_COST = 0.0 -- XP cost for removing an equipment module and leaving the slot empty when creating an equipment variant. --- Navy NDefines.NNavy.LEADER_EXPERIENCE_SCALE = 0.0 NDefines.NNavy.SCREEN_RATIO_FOR_FULL_SCREENING_FOR_CAPITALS = 2.5 NDefines.NNavy.ANTI_AIR_POW_ON_INCOMING_AIR_DAMAGE = 0.8 --- (0.2 -> 0.8) NDefines.NNavy.SHIP_TO_FLEET_ANTI_AIR_RATIO = 0.01 --- (0.2 -> 0.01) NDefines.NNavy.ANTI_AIR_MULT_ON_INCOMING_AIR_DAMAGE = 0.07 --- (0.15 -> 0.07) NDefines.NNavy.MAX_ANTI_AIR_REDUCTION_EFFECT_ON_INCOMING_AIR_DAMAGE = 0.8 --- (0.5 -> 0.8) NDefines.NNavy.HIGHER_SHIP_RATIO_POSITIONING_PENALTY_FACTOR = 0.3 -- if one side has more ships than the other, that side will get this penalty for each +100% ship ratio it has NDefines.NNavy.MAX_POSITIONING_PENALTY_FROM_HIGHER_SHIP_RATIO = 0.7 -- maximum penalty to get from larger fleets NDefines.NNavy.MAX_POSITIONING_PENALTY_FOR_NEWLY_JOINED_SHIPS = 0.0 -- the accumulated penalty from new ships will be clamped to this value NDefines.NNavy.DAMAGE_PENALTY_ON_MINIMUM_POSITIONING = 0.8 -- damage penalty at 0% positioning NDefines.NNavy.SCREENING_EFFICIENCY_PENALTY_ON_MINIMUM_POSITIONING = 0.4 -- screening efficiency (screen to capital ratio) at 0% positioning NDefines.NNavy.COMBAT_ARMOR_PIERCING_CRITICAL_BONUS = 1.5 -- Bonus to critical chance when shooter armor piercing is higher then target armor. NDefines.NNavy.PRIDE_OF_THE_FLEET_UNASSIGN_COST = 0 -- cost to unassign/replace pride of the fleet NDefines.NNavy.CARRIER_STACK_PENALTY = 5 -- The most efficient is 4 carriers in combat. 5+ brings the penalty to the amount of wings in battle. NDefines.NNavy.CARRIER_STACK_PENALTY_EFFECT = 0.167 -- Each carrier above the optimal amount decreases the amount of airplanes being able to takeoff by such %. NDefines.NNavy.GUN_HIT_PROFILES = { -- hit profiles for guns, if target ih profile is lower the gun will have lower accuracy 85.0, -- big guns 145.0, -- torpedos 40.0, -- small guns } NDefines.NNavy.COMBAT_MIN_DURATION = 12 NDefines.NNavy.MISSION_SPREADS = { -- mission spreads in the case a ship join combat, whih defines their starting position 0.0, -- HOLD 0.0, -- PATROL 0.0, -- STRIKE FORCE 0.0, -- CONVOY RAIDING 0.0, -- CONVOY ESCORT 0.0, -- MINES PLANTING 0.0, -- MINES SWEEPING 0.5, -- TRAIN 0.0, -- RESERVE_FLEET 0.0, -- NAVAL_INVASION_SUPPORT } NDefines.NNavy.ANTI_AIR_ATTACK_TO_AMOUNT = 0.003 -- Balancing value to convert equipment stat anti_air_attack to the random % value of airplanes being hit. NDefines.NNavy.SUBMARINE_REVEAL_POW = 5.0 -- A scaling factor that is applied to the reveal chance in order to make large differences in detection vs visibility more pronounced NDefines.NNavy.COMBAT_DAMAGE_TO_STR_FACTOR = 0.25 -- casting damage value to ship strength multiplier. Use it ot balance the game difficulty. NDefines.NNavy.COMBAT_DAMAGE_TO_ORG_FACTOR = 0.8 -- casting damage value to ship organisation multiplier. Use it to balance the game difficulty. NDefines.NNavy.MAX_ORG_ON_MANUAL_MOVE = 1.0 -- org will clamped to this ratio on manual move NDefines.NNavy.UNIT_TRANSFER_DETECTION_CHANCE_BASE = 2.0 -- unit transfer and naval invasion base chance detection percentage (if this fails, no detection is done on that tick) NDefines.NNavy.ORG_COST_WHILE_MOVING = { -- org cost while the ships are moving 0.4, -- HOLD 0.4, -- PATROL 0.4, -- STRIKE FORCE 0.4, -- CONVOY RAIDING 0.4, -- CONVOY ESCORT 0.4, -- MINES PLANTING 0.4, -- MINES SWEEPING 0.4, -- TRAIN 0.4, -- RESERVE_FLEET 0.4, -- NAVAL_INVASION_SUPPORT } NDefines.NNavy.MISSION_SUPREMACY_RATIOS = { -- supremacy multipliers for different mission types 0.0, -- HOLD 1.0, -- PATROL 0.4, -- STRIKE FORCE 0.5, -- CONVOY RAIDING 0.5, -- CONVOY ESCORT 0.3, -- MINES PLANTING 0.3, -- MINES SWEEPING 0.0, -- TRAIN 0.0, -- RESERVE_FLEET 0.4, -- NAVAL_INVASION_SUPPORT } NDefines.NNavy.CONVOY_DEFENSE_MAX_CONVOY_TO_SHIP_RATIO = 15.0 -- each ship in convoy defense mission can at most cover this many convoys without losing efficiency NDefines.NNavy.CONVOY_ROUTE_SIZE_CONVOY_SCALE = 0.4 -- scales impact of convoy route size (0 to turn off) NDefines.NNavy.SUPREMACY_PER_SHIP_BASE = 15.0 ---Air NDefines.NAir.NAVAL_STRIKE_DAMAGE_TO_STR = 1.0 NDefines.NAir.NAVAL_KAMIKAZE_DAMAGE_MULT = 5.0 -- vanilla is like 20 NDefines.NAir.NAVAL_STRIKE_DAMAGE_TO_ORG = 1.5 NDefines.NAir.NAVAL_STRIKE_DETECTION_BALANCE_FACTOR = 0.5 -- Value used to scale the surface_visibility stats to balance the gameplay, so 100% detection chance still won't spam the strikes. NDefines.NAir.NAVAL_STRIKE_CARRIER_MULTIPLIER = 3.75 -- damage bonus when planes are in naval combat where their carrier is present (and can thus sortie faster and more effectively)
1518ce3bbd044ed45da5ace3fb31ce555e5c18ce
[ "Lua" ]
2
Lua
GenPage/HFU
f9ec215065a761ab475ce190205b058c0fd4121e
087565959f9ab5da59e7f55bdcc1bd63ce7c709d
refs/heads/master
<repo_name>Evdacheva/laba_10<file_sep>/laba10_2/lsba10_2/Program.cs using System; namespace lsba10_2 { class Program { public static void Main(string[] args) { var rnd = new Random(); int[] arr = new int[100]; for (int i = 0; i < arr.Length; i++) { int rndMoney = rnd.Next(0, 7); MoneyGenerator(arr, i, rndMoney); Console.Write(arr[i] + " "); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Отсортированный методом - подсчёта"); CountingSort(arr, 0, arr.Length - 1); foreach (int sortedMoney in arr) { Console.Write(sortedMoney + " "); } Console.ReadKey(); } public static void MoneyGenerator(int[] arr, int i, int rndMoney) { const int Dollars_1 = 0; const int Dollars_2 = 1; const int Dollars_5 = 2; const int Dollars_10 = 3; const int Dollars_20 = 4; const int Dollars_50 = 5; const int Dollars_100 = 6; switch (rndMoney) { case Dollars_1: arr[i] = 1; break; case Dollars_2: arr[i] = 2; break; case Dollars_5: arr[i] = 5; break; case Dollars_10: arr[i] = 10; break; case Dollars_20: arr[i] = 20; break; case Dollars_50: arr[i] = 50; break; case Dollars_100: arr[i] = 100; break; default: break; } } public static void CountingSort(int[] arr, int left, int right) { int min = 0, max = 0; for (int i = left; i <= right; i++) { if (arr[i] < min) { min = arr[i]; } else if (arr[i] > max) { max = arr[i]; } } int bn = max - min + 1; int[] buckets = new int[bn]; for (int i = left; i <= right; i++) { buckets[arr[i] - min]++; } int index = 0; for (int i = min; i <= max; i++) { for (int j = 0; j < buckets[i - min]; j++) { arr[index++] = i; } } } } } <file_sep>/laba10_1/laba10_1/Program.cs using System; using System.IO; using System.Collections.Generic; using System.Linq; namespace laba10_1 { class Program { static void Main(string[] args) { int temp = 0; string path = @"C:\Users\HP\source\repos\laba10_!\sorted.dat"; int[] array = new int[100]; Random rand = new Random(); for (int i = 0; i < array.Length; i++) { array[i] = rand.Next(0, 30); } for (int i = 0; i < array.Length - 1; i++) { for (int j = i + 1; j < array.Length; j++) { if (array[i] > array[j]) { temp = array[i]; array[i] = array[j]; array[j] = temp; } } } int[] array_ascending = array; int[] array_descending = new int[array.Length]; for (int i = array.Length - 1; i > -1; i--) { array_descending[i] = array_ascending[i]; } int cnt = 0; int swap = 0; TimeSpan time = new TimeSpan(); QuickSortAlgoritm quickSort = new QuickSortAlgoritm(); MergeSortAlgoritm mergeSort = new MergeSortAlgoritm(); HeapSortAlgoritm heapSort = new HeapSortAlgoritm(); Console.WriteLine("QuickSort"); var arr = quickSort.QuickSort((int[])randomValue.Clone(), ref cnt, ref swap, ref time); Console.Write($"Массив сгенерированный случайным образом\nЗатраченное время на сортировку - {time} \nколичество сравнений - {cnt} \nколичество перестановок - {swap}\n"); writeInFile(arr); Console.WriteLine("QuickSort"); arr = quickSort.QuickSort((int[])descendingValue.Clone(), ref cnt, ref swap, ref time); Console.Write($"Массив по убыванию\nЗатраченное время на сортировку - {time} \nколичество сравнений - {cnt} \nколичество перестановок - {swap}\n"); writeInFile(arr); Console.WriteLine("QuickSort"); arr = quickSort.QuickSort((int[])ascendingValue.Clone(), ref cnt, ref swap, ref time); Console.Write($"Массив по возростанию\nЗатраченное время на сортировку - {time} \nколичество сравнений - {cnt} \nколичество перестановок - {swap}\n"); writeInFile(arr); Console.WriteLine("\n\n"); Console.WriteLine("MergeSort"); mergeSort.MergeSort((int[])randomValue.Clone(), ref cnt, ref swap, ref time); Console.Write($"Массив сгенерированный случайным образом\nЗатраченное время на сортировку - {time} \nколичество сравнений - {cnt} \nколичество перестановок - {swap}\n"); writeInFile(arr); mergeSort.MergeSort((int[])descendingValue.Clone(), ref cnt, ref swap, ref time); Console.Write($"Массив сгенерированный по убыванию\nЗатраченное время на сортировку - {time} \nколичество сравнений - {cnt} \nколичество перестановок - {swap}\n"); writeInFile(arr); mergeSort.MergeSort((int[])ascendingValue.Clone(), ref cnt, ref swap, ref time); Console.Write($"Массив по возростанию\nЗатраченное время на сортировку - {time} \nколичество сравнений - {cnt} \nколичество перестановок - {swap}\n"); writeInFile(arr); Console.WriteLine("\n\n"); Console.WriteLine("HeapSort"); heapSort.HeapSort((int[])randomValue.Clone(), ref cnt, ref swap, ref time); Console.Write($"Массив сгенерированный случайным образом\nЗатраченное время на сортировку - {time} \nколичество сравнений - {cnt} \nколичество перестановок - {swap}\n"); writeInFile(arr); heapSort.HeapSort((int[])descendingValue.Clone(), ref cnt, ref swap, ref time); Console.Write($"Массив по убыванию\nЗатраченное время на сортировку - {time} \nколичество сравнений - {cnt} \nколичество перестановок - {swap}\n"); writeInFile(arr); heapSort.HeapSort((int[])ascendingValue.Clone(), ref cnt, ref swap, ref time); Console.Write($"Массив по возростанию\nЗатраченное время на сортировку - {time} \nколичество сравнений - {cnt} \nколичество перестановок - {swap}\n"); writeInFile(arr); } private static void check_File_Sorting() { using (BinaryReader reader = new BinaryReader(File.Open(path, FileMode.OpenOrCreate))) { int cnt = lenght; while (true) { if (reader.PeekChar() > -1) { if (reader.ReadInt32() <= reader.ReadInt32()) { cnt -= 2; continue; } } else { if (cnt == 0) { Console.WriteLine("Массив отсортерован"); break; } else { Console.WriteLine("Массив не отсортерован"); break; } } } } } private static void writeInFile(int[] arr) { using (BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.OpenOrCreate))) { foreach (var item in arr) { writer.Write(item); } } check_File_Sorting(); Console.WriteLine("\n"); } //================================================================================================================================================= public class QuickSortAlgoritm { public static void Swap(ref int elem1, ref int elem2) { var temp = elem1; elem1 = elem2; elem2 = temp; } private static int Partition(int[] array, int minIndex, int maxIndex, ref int cnt, ref int swap) { var pivot = minIndex - 1; for (var i = minIndex; i < maxIndex; i++) { cnt++; if (array[i] < array[maxIndex]) { pivot++; swap++; Swap(ref array[pivot], ref array[i]); } } pivot++; swap++; Swap(ref array[pivot], ref array[maxIndex]); return pivot; } private static int[] QuickSort(int[] array, int minIndex, int maxIndex, ref int cnt, ref int swap, ref TimeSpan time) { DateTime dateTime = DateTime.Now; DateTime dateTime1 = DateTime.Now; if (minIndex >= maxIndex) { dateTime1 = DateTime.Now; time = dateTime1 - dateTime; return array; } var pivotIndex = Partition(array, minIndex, maxIndex, ref cnt, ref swap); QuickSort(array, minIndex, pivotIndex - 1, ref cnt, ref swap, ref time); QuickSort(array, pivotIndex + 1, maxIndex, ref cnt, ref swap, ref time); dateTime1 = DateTime.Now; time = dateTime1 - dateTime; return array; } public int[] QuickSort(int[] array, ref int cnt, ref int swap, ref TimeSpan time) { return QuickSort(array, 0, array.Length - 1, ref cnt, ref swap, ref time); } } public class MergeSortAlgoritm { private static void Merge(int[] array, int lowIndex, int middleIndex, int highIndex, ref int cnt, ref int swap) { var left = lowIndex; var right = middleIndex + 1; var tempArray = new int[highIndex - lowIndex + 1]; var index = 0; cnt++; while ((left <= middleIndex) && (right <= highIndex)) { cnt++; if (array[left] < array[right]) { tempArray[index] = array[left]; left++; } else { tempArray[index] = array[right]; right++; } index++; } for (var i = left; i <= middleIndex; i++, swap++) { tempArray[index] = array[i]; index++; } for (var i = right; i <= highIndex; i++, swap++) { tempArray[index] = array[i]; index++; } for (var i = 0; i < tempArray.Length; i++, swap++) { array[lowIndex + i] = tempArray[i]; } } private static int[] MergeSort(int[] array, int lowIndex, int highIndex, ref int cnt, ref int swap, ref TimeSpan time) { DateTime dateTime = DateTime.Now; if (lowIndex < highIndex) { var middleIndex = (lowIndex + highIndex) / 2; MergeSort(array, lowIndex, middleIndex, ref cnt, ref swap, ref time); MergeSort(array, middleIndex + 1, highIndex, ref cnt, ref swap, ref time); Merge(array, lowIndex, middleIndex, highIndex, ref cnt, ref swap); } DateTime dateTime1 = DateTime.Now; time = dateTime1 - dateTime; return array; } public int[] MergeSort(int[] array, ref int cnt, ref int swap, ref TimeSpan time) { return MergeSort(array, 0, array.Length - 1, ref cnt, ref swap, ref time); } } public class HeapSortAlgoritm { private static void Swap(ref int elem1, ref int elem2) { var temp = elem1; elem1 = elem2; elem2 = temp; } public void HeapSort(int[] arr, ref int cnt, ref int swap, ref TimeSpan time) { int n = arr.Length; for (int i = n / 2 - 1; i >= 0; i--) { Heapify(arr, n, i, ref cnt, ref swap, ref time); } for (int i = n - 1; i >= 0; i--) { swap++; Swap(ref arr[0], ref arr[i]); Heapify(arr, i, 0, ref cnt, ref swap, ref time); } } private void Heapify(int[] arr, int n, int i, ref int cnt, ref int swap, ref TimeSpan time) { int largest = i; int left = 2 * i + 1; int right = 2 * i + 2; cnt++; if (left < n && arr[left] > arr[largest]) { largest = left; } cnt++; if (right < n && arr[right] > arr[largest]) { largest = right; } cnt++; if (largest != i) { swap++; Swap(ref arr[i], ref arr[largest]); Heapify(arr, n, largest, ref cnt, ref swap, ref time); } } } } } <file_sep>/laba10_3/laba10_3/Program.cs using System; using System.Collections; using System.Collections.Generic; namespace laba10_3 { class Program { public class Graph { private int vertices = 0; Dictionary<int, List<int>> graph = null; public Graph(Dictionary<int, List<int>> dictionary, int num) { graph = dictionary; vertices = num; } public Stack<int> backChain(int[] p, int start, int end) { int pos = end; var path_stack = new Stack<int>(); path_stack.Push(pos); while (pos != start) { pos = p[pos]; path_stack.Push(pos); } return path_stack; } public Stack<int> DFS(int start, int end) { var stack = new Stack<int>(); int[] Path = new int[vertices]; int[] checkedv = new int[vertices]; stack.Push(start); checkedv[start] = 1; while (stack.Count > 0) { int i = stack.Pop(); for (int j = vertices - 1; j >= 0; j--) { if (graph[i + 1].Contains(j + 1) && checkedv[j] == 0) { checkedv[j] = 1; stack.Push(j); Path[j] = i; if (j == end) { return backChain(Path, start, end); } } } } return null; } public Stack<int> BFS(int startPos, int endPos) { var q = new Queue<int>(); // array for tracking path int[] vPath = new int[vertices]; int[] checkedv = new int[vertices]; q.Enqueue(startPos); checkedv[startPos] = 1; while (q.Count > 0) { int i = q.Dequeue(); for (int j = 0; j < vertices; j++) { if (graph[i + 1].Contains(j + 1) && checkedv[j] == 0) { checkedv[j] = 1; q.Enqueue(j); vPath[j] = i; if (j == endPos) { return backChain(vPath, startPos, endPos); } } } } return null; } static void Main(string[] args) { int[,] matrixAdj = { {0,1,1,0,0,0,0,0}, //1 {1,0,0,0,0,1,1,0}, //2 {1,0,0,1,0,1,0,1}, //3 {0,0,1,0,1,0,0,0}, //4 {0,0,0,1,0,1,0,0}, //5 {0,1,1,0,1,0,0,0}, //6 {0,1,0,0,0,0,0,1}, //7 {0,0,1,0,0,0,1,0} //8 }; var graph = new Graphs(matrixAdj, 8); int X = 0; int Y = 0; Console.Write("Введите вершину "); InitializeAndCheckVar(ref X); Console.Write("Введите вершину "); InitializeAndCheckVar(ref Y); var DFS = graph.DFS(X - 1, Y - 1); Show_path_in_stack(DFS); Console.WriteLine(); var BFS = graph.BFS(X - 1, Y - 1); Show_path_in_stack(BFS); Console.WriteLine(); var graph1 = new Dictionary<int, List<int>>(); graph1[1] = new List<int> { 2, 3 }; graph1[2] = new List<int> { 1, 6, 7 }; graph1[3] = new List<int> { 1, 4, 6, 8 }; graph1[4] = new List<int> { 3, 5 }; graph1[5] = new List<int> { 4, 6 }; graph1[6] = new List<int> { 2, 3, 5 }; graph1[7] = new List<int> { 2, 8 }; graph1[8] = new List<int> { 3, 7 }; var graphLink = new Graphs (graph1, 8); var DFS_Link = graphLink.DFS(X - 1, Y - 1); Show_path_in_stack(DFS_Link); Console.WriteLine(); var BFS_Link = graphLink.BFS(X - 1, Y - 1); Show_path_in_stack(BFS_Link); Console.ReadKey(); } public static void InitializeAndCheckVar(ref int i) { bool Pass = false; while (!Pass) { try { i = Convert.ToInt32(Console.ReadLine()); if (i > 0 && i <= 8) Pass = true; else Console.WriteLine("Значение неверное"); } catch { Console.WriteLine("Значение неверное"); } } } static void Show_path_in_stack(Stack<int> stack) { int cnt = 0; foreach (int i in stack) { Console.Write((cnt == 0) ? Convert.ToString(i + 1) : "->" + (i + 1)); cnt++; } } } } } <file_sep>/laba10_4/laba10_4/Program.cs using System; using System.Collections.Generic; namespace laba10_4 { class Program { public class Graph { //взяли из третьего задания; private int vertices = 0; Dictionary<int, List<int>> graph = null; public Graph(Dictionary<int, List<int>> dictionary, int num) { graph = dictionary; vertices = num; } public Stack<int> backChain(int[] p, int start, int end) { int pos = end; var path_stack = new Stack<int>(); path_stack.Push(pos); while (pos != start) { pos = p[pos]; path_stack.Push(pos); } return path_stack; } public Stack<int> BFS(int startPos, int endPos) { var q = new Queue<int>(); // array for tracking path int[] vPath = new int[vertices]; int[] checkedv = new int[vertices]; q.Enqueue(startPos); checkedv[startPos] = 1; while (q.Count > 0) { int i = q.Dequeue(); for (int j = 0; j < vertices; j++) { if (graph[i + 1].Contains(j + 1) && checkedv[j] == 0) { checkedv[j] = 1; q.Enqueue(j); vPath[j] = i; if (j == endPos) { return backChain(vPath, startPos, endPos); } } } } return null; } } static void Main(string[] args) { int[,] array = { {-1,40,80,-1,-1,-1,-1,-1}, //1 {40,-1,-1,-1,-1,150,80,-1}, //2 {80,-1,-1,60,-1,40,-1,150}, //3 {-1,-1,60,-1,120,-1,-1,-1}, //4 {-1,-1,-1,120,-1,50,-1,-1}, //5 {-1,150,40,-1,50,-1,-1,-1}, //6 {-1,80,-1,-1,-1,-1,-1,150}, //7 {-1,-1,150,-1,-1,-1,150,-1} //8 }; var graph = new Graph(array, 8); int i = 0; InitializeAndCheckVar(ref i); var dictionary_of_distance = new Dictionary<string, int>(); for (int j = 0; j < 8; j++) { if (!dictionary_of_distance.ContainsKey(i + " " + j + 1)) { if (i != j + 1) { var stackBFS = graph.BFS(i - 1, j); how_path_in_stack(stackBFS); Console.WriteLine(); AddToDitionary(stackBFS, array, ref dictionary_of_distance, i); } } } foreach (KeyValuePair<string, int> keyValue in dictionary_of_distance) { if (keyValue.Value <= 200) Console.WriteLine(keyValue.Key + " - " + keyValue.Value); } Console.ReadKey(); } static void AddToDitionary(Stack<int> stack, int[,] a, ref Dictionary<string, int> dict, int start_pos) { int prev_num = -1; int sum = 0; foreach (int i in stack) { if (prev_num == -1) prev_num = i; else { sum += a[prev_num, i]; prev_num = i; dict[(start_pos) + " " + (i + 1)] = sum; } } } static void InitializeAndCheckVar(ref int i) { bool Pass = false; while (!Pass) { try { i = Convert.ToInt32(Console.ReadLine()); if (i > 0 && i <= 8) Pass = true; else Console.WriteLine("Значение неверное"); } catch { Console.WriteLine("Значение неверное"); } } } static void how_path_in_stack(Stack<int> stack) { int cnt = 0; foreach (int i in stack) { Console.WriteLine((cnt == 0) ? Convert.ToString(i + 1) : "->" + (i + 1)); cnt++; } } } } <file_sep>/laba10_!/laba10_!/Program.cs using System; using System.IO; using System.Linq; using System.Collections.Generic; namespace laba10__ { class Program { struct Time { public DateTime dateTime; public TimeSpan timeSpan; public Time(DateTime d, TimeSpan t) { dateTime = d; timeSpan = t; } } static void Main(string[] args) { int temp = 0; string path = @"C:\Users\HP\source\repos\laba10_!\sorted.dat"; int[] array = new int[100]; Random rand = new Random(); for (int i = 0; i < array.Length; i++) { array[i] = rand.Next(0, 30); } for (int i = 0; i < array.Length - 1; i++) { for (int j = i + 1; j < array.Length; j++) { if (array[i] > array[j]) { temp = array[i]; array[i] = array[j]; array[j] = temp; } } } int[] array_ascending = array; int[] array_descending = new int[array.Length]; for (int i = array.Length - 1; i > -1; i--) { array_descending[i] = array_ascending[i]; } using (StreamWriter text = new StreamWriter(path, false)) { Console.WriteLine("Сортировка - слиянием (по возрастанию)"); foreach (int selection in Merge(array)) { text.Write(selection + " "); } Console.WriteLine(); text.WriteLine(); Console.WriteLine("Сортировка - слиянием (отсортированного массива по возрастанию)"); foreach (int selection in Merge(array_ascending)) { text.Write(selection + " "); } Console.WriteLine(); text.WriteLine(); Console.WriteLine("Сортировка - слиянием (отсортированного массива по убыванию)"); foreach (int selection in Merge(array_descending)) { text.Write(selection + " "); } Console.WriteLine(); text.WriteLine(); System.Console.WriteLine("Пирамидальная сортировка: "); foreach (double x in array) { System.Console.Write(x + " "); } PyramidSorting.sorting(array, array.Length); System.Console.WriteLine("\n\nПирамидальная сортировка по возрастанию:"); foreach (double x in array) { System.Console.Write(x + " "); } Console.WriteLine("Быстрая сортировка"); Console.WriteLine("Упорядоченный массив: {0}", string.Join(", ", QuickSort(array))); } Check(path); Console.ReadKey(); } static void Swap(ref int x, ref int y) { var t = x; x = y; y = t; } //метод возвращающий индекс опорного элемента static int Partition(int[] array, int minIndex, int maxIndex) { var pivot = minIndex - 1; for (var i = minIndex; i < maxIndex; i++) { if (array[i] < array[maxIndex]) { pivot++; Swap(ref array[pivot], ref array[i]); } } pivot++; Swap(ref array[pivot], ref array[maxIndex]); return pivot; } //быстрая сортировка static int[] QuickSort(int[] array, int minIndex, int maxIndex) { DateTime start = DateTime.Now; if (minIndex >= maxIndex) { return array; } var pivotIndex = Partition(array, minIndex, maxIndex); QuickSort(array, minIndex, pivotIndex - 1); QuickSort(array, pivotIndex + 1, maxIndex); DateTime finish = DateTime.Now; TimeSpan time_interval = finish - start; Console.WriteLine("Время сортировки:{0};\n Количество сравнений:{1};\n Количество обменов:{2}", time_interval, maxIndex, pivotIndex); return array; } static int[] QuickSort(int[] array) { return QuickSort(array, 0, array.Length - 1); } static void Check(string path) { using (StreamReader textReader = new StreamReader(path)) { bool data_checking = true; string line; while ((line = textReader.ReadLine()) != null) { line = textReader.ReadLine(); if (line != null) { string[] nums = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < nums.Length - 1; i++) { if (Convert.ToInt32(nums[i]) < Convert.ToInt32(nums[i++])) { data_checking = false; break; } } } } if (data_checking) { Console.WriteLine("Сортировка всех функций прошла успешно"); } else { Console.WriteLine("Сортировка прошла неудачно"); } } } static int[] Merge(int[] nums) { DateTime start = DateTime.Now; int l = 1; int r = 1; int mid = 1; int[] temp = new int[r - l + 1]; int i = l, j = mid + 1; int k = 0; for (k = 0; k < temp.Length; k++) { if (i > mid) { temp[k] = nums[j++]; } else if (j > r) { temp[k] = nums[i++]; } else { temp[k] = (nums[i] < nums[j]) ? nums[i++] : nums[j++]; } } // Copy temp array to original array k = 0; i = l; while (k < temp.Length && i <= r) { nums[i++] = temp[k++]; } DateTime finish = DateTime.Now; TimeSpan time_interval = finish - start; Console.WriteLine("Время сортировки:{0};\n Количество сравнений:{1};\n Количество обменов:{2}", time_interval, k, i); return nums; } } } class PyramidSorting { //add 1 element to the pyramid static int add2pyramid(int [] arr, int i, int N) { DateTime start = DateTime.Now; int imax; int buf; if ((2 * i + 2) < N) { if (arr[2 * i + 1] < arr[2 * i + 2]) imax = 2 * i + 2; else imax = 2 * i + 1; } else imax = 2 * i + 1; if (imax >= N) return i; if (arr[i] < arr[imax]) { buf = arr[i]; arr[i] = arr[imax]; arr[imax] = buf; if (imax < N / 2) i = imax; } DateTime finish = DateTime.Now; TimeSpan time_interval = finish - start; Console.WriteLine("Время сортировки:{0};\n Количество сравнений:{1};\n Количество обменов:{2}", time_interval, i, imax); return i; } public static void sorting(int [] arr, int len) { //step 1: building the pyramid for (int i = len / 2 - 1; i >= 0; --i) { long prev_i = i; i = add2pyramid(arr, i, len); if (prev_i != i) ++i; } //step 2: sorting int buf; for (int k = len - 1; k > 0; --k) { buf = arr[0]; arr[0] = arr[k]; arr[k] = buf; int i = 0, prev_i = -1; while (i != prev_i) { prev_i = i; i = add2pyramid(arr, i, k); } } } }
7f4080c644f5153a792d644ad8178d175826b390
[ "C#" ]
5
C#
Evdacheva/laba_10
6411443ca4180e89f3a69cb9bdaa428889e6936d
4458b9fff9f5892819b65d3c9bf1d5b71f50d2d0
refs/heads/master
<repo_name>Techyengineer314/GA_Sample<file_sep>/main.cpp #include<iostream> #include<string> #include<stdio.h> #include<time.h> #include<ctime> //////////////////////////////////////////////////////////////////////////////////////// //This Sample Sets out to attempt a basic Genetic Algorithm to determine the smallest// //Sequence needed to form a provided target number // //////////////////////////////////////////////////////////////////////////////////////// int power(int x, int y) { int ans = 1; for (int i = 0; i < y; i++) ans *= x; return ans; } long swap_bits(long integer1, long integer2, int index) { //swaps bits at the specified index and returns integer 1 swapped long ans = 0, mask1, mask2, xor_mask = 0; for (int i = 0; i <= index; i++) { mask1 = integer1 & power(2, i); mask2 = integer2 & power(2, i); if (mask2 != mask1) { xor_mask += power(2, i); } } ans = integer1 ^ xor_mask; return ans; } int high_search(double *a, int n) { //finds the highest number in the specified 100 element array double ans = 0; int index = 0; for (int i = 0; i < n; i++) { if (a[i] > ans) { index = i; ans = a[i]; } } return index; } int next_high_search(double *a, int index, int n) { //finds the second highest element in the specified 100 element array with the index of the highest element provided double ans = 0; int index1 = 0; for (int i = 0; i < n; i++) { if (a[i] > ans && i != index) { index1 = i; ans = a[i]; } } return index1; } bool digit(int a) { //sees if the integer is within the 0-9 range or not if (a <= 9) { return true; } return false; } bool op(int a) { //sees if the operator is one of the desired operators or not if (a > 20) { return true; } return false; } int main(int argc, char *argv[]) { int index,index2,index3,parent_choice = 0,count1 = 2,xor_mask = 0; int total_runs = 0; int num_run = 0; std::clock_t start; double duration, total_time = 0; start = std::clock(); long seed = time(NULL); srand((unsigned int)seed); std::cout << "The seed is: " << seed << '\n'; double fitness[50]; unsigned long long population[50],parent1,parent2; //sets up the array to store population //expecting somewhere between 100 - 1000 children per generation bool found_number = false, found_op = false, answer_found = false; ////////////////////////////////////////////////////////////////////////// //target number and other various declarations/////////////////////////// ///////////////////////////////////////////////////////////////////////// int target = 20; std::cout << "Enter a Target Number: "; std::cin >> target; std::cout << "The Target Number is: " << target << "\n\n"; std::cout << "Enter Desired number of times to run: "; std::cin >> num_run; std::cout << "The Number of times it wil run is: " << num_run << "\n\n"; total_runs = num_run; long long current_pop = 0; long answer = 0; int currentop = 0, count = 0, generation = 0, overall_generation = 0, nibbler; int total = 0, current = 0, next = 0, nextop = 0; int operator1[8]; char a; //////////////////////// //Beginning algorithms// //////////////////////// while(num_run > 1){ answer_found = false; for (int i = 0; i < 50; i++) { current_pop = 0; for (int j = 0; j < 8; j++) { nibbler = rand() % 15; current_pop += nibbler << j*4; } population[i] = current_pop; //chooses a completely random number between 0 and 0xFFFFFFFF } for (int j = 0; j < 50;j++) { current = 0; found_number = false; found_op = false; nextop = 0; next = 0; total = 0; count = 0; for (int i = 7; i >= 0;i--) { operator1[i] = 0xF & (population[j] >> ((7 - i) * 4)); if (operator1[i] > 9) { switch (operator1[i]) { case 10: operator1[i] = 0x2B; break; case 11: operator1[i] = 0x2D; break; case 12: operator1[i] = 0x2A; break; case 13: operator1[i] = 0x2F; break; case 14: operator1[i] = 0x5E; break; case 15: operator1[i] = 0x25; break; default: operator1[i] = 0x20; } } } for (int i = 0; i < 8;i++) { if (operator1[i] > 9) { a = operator1[i]; std::cout << a << ' '; } else { std::cout << operator1[i] << ' '; } } std::cout << '\n'; ////////////////////////////////////////////////////////////////////// //Beginning algorithm to check for total provided by random solution// ////////////////////////////////////////////////////////////////////// /******************************************************************** Algorithm uses following method to determine solution: Read through operator array until number is found and store that number in current Read through operator array until operation is found and store said operator in current op Read through until next number is found and perform that calculation with that number in next and store it in current num as well as total repeat till end of array handle special cases of no numbers or no operators or one number and 7 operators with search function Also begin a check to determine if there are leading zeroes that should be ignored *********************************************************************/ while (operator1[count] == 0) { count++; if (count == 8) { total = 0; break; } if (operator1[count] > 0x29 && count > 0) { current = 0; found_number = true; currentop = operator1[count]; found_op = true; } else { found_number = false; found_op = false; } } while (count < 7) { next = 20; currentop = 0x20; if (!(currentop == operator1[count])) { found_op = false; } while (!found_number) { if (count > 7) { break; } found_number = digit(operator1[count]); if(found_number) current = operator1[count]; count++; } while (!found_op) { if (count > 7) { break; } found_op = op(operator1[count]); if(found_op) currentop = operator1[count]; count++; } found_number = false; while (!found_number) { if (count > 7) { break; } found_number = digit(operator1[count]); if (found_number) { next = operator1[count]; } count++; } if (total == 0) { total = current; } if (next == 20) break; switch (currentop) { case 0x25: if(!next) break; total = total % next; break; case 0x2A: total *= next; break; case 0x2B: total += next; break; case 0x2D: total -= next; break; case 0x2F: if(!next) break; total /= next; break; case 0x5E: total = power(total,next); break; default: total = total; } } std::cout << "\nThe total is: " << total << '\n'; std::cout << "At population number: " << j << "\nGeneration number: " << generation << '\n' << "Overall Generation number: " << overall_generation << '\n'; if (target == total) { answer = population[j]; std::cout << "An answer is: " << std::hex << answer << std::dec << '\n'; answer_found = true; break; } fitness[j] = 1.0 / (target - total); std::cout << "The fitness of: " << std::hex << population[j] << std::dec<< " is: " << fitness[j] << "\n\n"; } ///////////////////////////////////////////////////////////////////////////////////////////////////// //beginning mutation algorithm will take two best fit numbers and crossover at a random point and // //then will begin flipping bits at random // ///////////////////////////////////////////////////////////////////////////////////////////////////// while (!answer_found) { seed = time(NULL); std::cout << "\nThe NEW seed is: " << seed << "\n\n"; srand((unsigned int)seed);//seeds the ranodm number generator cause random stuff is fun!!!! generation++; count1 = 2; xor_mask = 0; index = high_search(fitness,50); index2 = next_high_search(fitness, index, 50); parent1 = population[index]; parent2 = population[index2]; index3 = rand()%15 + 15;//choosing random index for crossover population[0] = swap_bits(parent1, parent2, index3);//performing crossover population[1] = swap_bits(parent2, parent1, index3); while (count != 50) { //rebuilding population parent_choice = rand() % 2; xor_mask = 0; for (int j = 0; j < 8; j++) { nibbler = rand() % 15; xor_mask += nibbler << j * 4; } population[count] = xor_mask ^ population[parent_choice]; count++; } if (generation > 10 || fitness[index] < 0.00005) { //sees if the generation is too dumb and rebuilds from scratch //AKA Genocide //whoa this comment got dark //no aryan nations here std::cout << "Taking too long\nStarting over with a new base generation\n"; generation = 0; overall_generation++; for (int i = 0; i < 50; i++) { current_pop = 0; for (int j = 0; j < 8; j++) { nibbler = rand() % 15; current_pop += nibbler << j * 4; } population[i] = current_pop; //chooses a completely random number between 0 and 0xFFFFFFFF } } for (int j = 0; j < 50;j++) { current = 0; found_number = false; found_op = false; nextop = 0; next = 0; total = 0; count = 0; for (int i = 7; i >= 0;i--) { operator1[i] = 0xF & (population[j] >> ((7 - i) * 4)); if (operator1[i] > 9) { switch (operator1[i]) { case 10: operator1[i] = 0x2B; break; case 11: operator1[i] = 0x2D; break; case 12: operator1[i] = 0x2A; break; case 13: operator1[i] = 0x2F; break; case 14: operator1[i] = 0x5E; break; case 15: operator1[i] = 0x25; break; default: operator1[i] = 0x20; } } } char a; for (int i = 0; i < 8;i++) { if (operator1[i] > 9) { a = operator1[i]; std::cout << a << ' '; } else { std::cout << operator1[i] << ' '; } } std::cout << '\n'; ////////////////////////////////////////////////////////////////////// //Beginning algorithm to check for total provided by random solution// ////////////////////////////////////////////////////////////////////// /******************************************************************** Algorithm uses following method to determine solution: Read through operator array until number is found and store that number in current Read through operator array until operation is found and store said operator in current op Read through until next number is found and perform that calculation with that number in next and store it in current num as well as total repeat till end of array skipping using the current because theres no need handle special cases of no numbers or no operators or one number and 7 operators with search function Also begin a check to determine if there are leading zeroes that should be ignored *********************************************************************/ while (operator1[count] == 0) {//determines if there are leading zeroes count++; if (count == 8) { total = 0; break; } if (operator1[count] > 0x29 && count > 0) {//determines i if it finds an operation and then uses said operation and 0 as the current number current = 0; found_number = true; currentop = operator1[count]; found_op = true; } else { found_number = false; found_op = false; } } while (count < 7) {//loops through the array next = 20;//default value to avoid confusion and determine if an currentop = 0x20; if (!(currentop == operator1[count])) { found_op = false; } while (!found_number) { if (count > 7) { break; } found_number = digit(operator1[count]); if(found_number) current = operator1[count]; count++; } while (!found_op) { if (count > 7) { break; } found_op = op(operator1[count]); if(found_op) currentop = operator1[count]; count++; } found_number = false; while (!found_number) { if (count > 7) { break; } found_number = digit(operator1[count]); if (found_number) { next = operator1[count]; } count++; } if (total == 0) { total = current; } if (next == 20) break; switch (currentop) { case 0x25: if(!next) break; total = total % next; break; case 0x2A: total *= next; break; case 0x2B: total += next; break; case 0x2D: total -= next; break; case 0x2F: if(!next) break; total /= next; break; case 0x5E: total = power(total,next); break; default: total = total; } } std::cout << "\nThe total is: " << total << '\n'; std::cout << "At population number: " << j << "\nGeneration number: " << generation << '\n' << "Overall generation: " << overall_generation <<'\n'; if (target == total) { answer = population[j]; std::cout << "An answer is: " << std::hex << answer << std::dec << '\n'; answer_found = true; break; } fitness[j] = 1.0 / (target - total); if (fitness < 0) { continue; } std::cout << "The fitness of: " << std::hex<<population[j] << std::dec << " is: " << fitness[j] << "\n\n"; } } duration = (std::clock() - start)/(double) CLOCKS_PER_SEC; total_time+=duration; num_run--; } std::cout << "Answer found in: "<< (double)total_time<< " seconds\n"; return 0; } <file_sep>/README.md # GA_Sample Sample Project in Genetic Algorithm programming, done in C++
4bc9039668fe0ee039e4e0d4eccacf0114647fc0
[ "Markdown", "C++" ]
2
C++
Techyengineer314/GA_Sample
4952d1f81ae27557bb4a58ef9ad1809ac3d2152d
e49f3d38dd3941dc685f265f71b221dff3e13e37
refs/heads/master
<file_sep># SenaryCalculator A Base 6 calculator React Native / EXPO / Yarn <br> To Install: <br> yarn <br> expo start <br> https://expo.io/@trent_mb/SenaryCalculator <br> ![Screenshot](screenshot.png) <file_sep>const regex = /[*+-\/]/g; export default (number, base) => { return number.toString(base) }<file_sep>import React from 'react'; import { Text, StyleSheet, TouchableOpacity } from 'react-native'; export type Props = { number: string, operation: string, onPress: () => void }; // Pure Component const Button = ({ onPress, number, operation }) => ( <TouchableOpacity onPress={onPress} style={styles.buttonContainer} > <Text style={styles.buttonText}>{number || operation}</Text> </TouchableOpacity> ); const styles = StyleSheet.create({ buttonText: { color: '#e0ffe2', fontSize: 22, fontWeight: '500' }, buttonContainer: { flexBasis: '25%', alignSelf: 'stretch', borderWidth: 1, borderColor: 'darkgreen', borderRadius: 0, marginTop: 0, justifyContent: 'center', alignItems: 'center', backgroundColor: 'green' } }); export default Button; <file_sep>const regex = /[*+-\/]/g; export default (char) => { return char.match(regex) }<file_sep>const regex = /[*+-\/]/g; export default (number, base) => { return Number.parseInt(number, base) }<file_sep>const regex = /[*+-\/]/g; export default (number1, number2) => { return `${number1}${number2}` }<file_sep>import React from 'react'; import { StyleSheet, Text, View, Dimensions, SafeAreaView } from 'react-native'; import Button from './components/Button'; import isOperator from './utilities/isOperator'; import joinNumbers from './utilities/joinNumbers'; import baseToDec from './utilities/baseToDec'; import decToBase from './utilities/decToBase'; const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window'); type State = { buttons: Array<string> }; export default class App extends React.Component<State> { state = { buttons: [ { operation: 'C' }, { operation: '+' }, { operation: '-' }, { operation: '*' }, { number: '0' }, { number: '1' }, { number: '2' }, { operation: '/' }, { number: '3' }, { number: '4' }, { number: '5' }, { operation: '=' } ], base: 6, display: '0', evaluate: [] }; onPressButton = (button) => { const { evaluate, display } = this.state; const { number, operation } = button; if (operation === '=') { this.onPressEquals(); return; } if (operation === 'C') { this.onPressClear(); return; } if (!this.validInput(button)) { return; } const newEvaluate = JSON.parse(JSON.stringify(evaluate)); let newDisplay = JSON.parse(JSON.stringify(display)); if (newEvaluate[0] === '0') { newEvaluate.pop(); } if (newDisplay.charAt(0) === '0') { newDisplay = ''; } newEvaluate.push(number || operation); newDisplay = `${newDisplay}${number || operation}`; this.setState({ evaluate: newEvaluate, display: newDisplay }); }; onPressClear = () => { this.setState({ display: '0', evaluate: [] }); }; onPressEquals = () => { const { evaluate, base } = this.state; let evaluationString = ''; let number = ''; evaluate.forEach((str) => { if (!isOperator(str)) { number = joinNumbers(number, str); } else { evaluationString = `${evaluationString}${baseToDec( number, base )}${str}`; number = ''; } }); evaluationString = `${evaluationString}${Number.parseInt(number, base)}`; this.setState({ display: decToBase(eval(evaluationString), base), evaluate: [decToBase(eval(evaluationString), base)] }); }; validInput = (button) => { const { display, evaluate } = this.state; const lastEntry = display.slice(-1)[0]; const firstEntry = display.slice(0)[0]; if (isOperator(lastEntry)) { this.setState({ display: display.replace(/.$/, `${button.operation}`) }); this.setState({ evaluate: evaluate.splice(-1, button.operation) }); if (button.operation) return false; } if (firstEntry === '0' && button.number && button.number === '0') { return false; } return true; }; render() { const { display, buttons } = this.state; return ( <SafeAreaView style={styles.safeViewContainer}> <View style={styles.mainContainer}> <View style={styles.resultContainer}> <Text style={styles.resultText}>{display}</Text> </View> <View style={styles.buttonContainer}> {buttons.map(button => ( <Button key={`button_${button.number || button.operation}`} {...button} onPress={() => this.onPressButton(button)} /> ))} </View> <View style={styles.historyContainer} /> </View> </SafeAreaView> ); } } const styles = StyleSheet.create({ safeViewContainer: { flex: 1, backgroundColor: 'darkgreen' }, mainContainer: { flex: 1 }, resultContainer: { flex: 1, borderWidth: 0, borderColor: 'green', alignItems: 'flex-end', justifyContent: 'center', borderRadius: 0, paddingHorizontal: 10, backgroundColor: 'darkgreen' }, resultText: { color: '#e0ffe2', fontSize: 30 }, buttonContainer: { flex: 5, borderWidth: 0, borderColor: 'green', flexDirection: 'row', flexWrap: 'wrap', alignSelf: 'center', justifyContent: 'center', alignContent: 'stretch' }, historyContainer: { flex: 3, backgroundColor: '#243c26' }, phoneScale: { transform: [ { scaleX: SCREEN_HEIGHT / 750 }, { scaleY: SCREEN_HEIGHT / 750 } ] } });
4a27c074032517a4f193e48ff5af839f35229c13
[ "Markdown", "JavaScript" ]
7
Markdown
UberMC/SenaryCalculator
c623dfcab57a80c776c2afa58a4d8cad0ce26284
f4e0c04f6816d1479035c528ed04a6170fd8b6e8
refs/heads/master
<file_sep># Boozy compotition website <file_sep>setInterval(function() { if ($(".beer").height() == 30) { document.getElementById("drink").innerHTML = "oh, another one?"; $("#drink").click(function() { $(".beer").css("height", "+=330"); }); } if ($(".beer").height() > 30) { document.getElementById("drink").innerHTML = "drink"; $("#drink").click(function() { $(".beer").css("height", "-=80"); }); } }, 500);
7830ffca5d498efdf7d6c586beced850997bb0fd
[ "Markdown", "JavaScript" ]
2
Markdown
chuckysaint/Boozy
a9c511b2d2f501a0b2ab84c6c705917ecd33113b
169f6945824afe2d08c9293a4ba243c419f5b69c
refs/heads/master
<repo_name>Kavanab/ShipmentCreation<file_sep>/src/main/java/com/monsanto/mbt/Widget.java package com.monsanto.mbt; import java.util.Comparator; import java.util.Date; public class Widget { private int serialNumber; private String color; private Date productionDate; public Widget(int serialNumber, String color, Date productionDate) { this.serialNumber = serialNumber; this.color = color; this.productionDate = productionDate; } public int getSerialNumber() { return serialNumber; } public void setSerialNumber(int serialNumber) { this.serialNumber = serialNumber; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public Date getProductionDate() { return productionDate; } public void setProductionDate(Date productionDate) { this.productionDate = productionDate; } @Override public String toString() { //return "Widget [serialNumber=" + serialNumber + ", color=" + color + ", productionDate=" + productionDate + "]"; return "{" + "\"serialNumber\":" + serialNumber + ", \"color\":"+"\""+color+"\""+ ", \"productionDate\":\"" + productionDate +"\""+ '}'; } public static Comparator<Widget> widgetDateComparator = new Comparator<Widget>() { public int compare(Widget o1, Widget o2) { Date d1 = o1.getProductionDate(); Date d2 = o2.getProductionDate(); return d1.compareTo(d2); } }; public static Comparator<Widget> widgetColourComparator = new Comparator<Widget>() { public int compare(Widget o1, Widget o2) { String c1 = o1.getColor(); String c2 = o2.getColor(); return c1.compareTo(c2); } }; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((color == null) ? 0 : color.hashCode()); result = prime * result + ((productionDate == null) ? 0 : productionDate.hashCode()); result = prime * result + serialNumber; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Widget other = (Widget) obj; if (color == null) { if (other.color != null) return false; } else if (!color.equals(other.color)) return false; if (productionDate == null) { if (other.productionDate != null) return false; } else if (!productionDate.equals(other.productionDate)) return false; if (serialNumber != other.serialNumber) return false; return true; } } <file_sep>/src/main/java/com/monsanto/mbt/Shipment.java package com.monsanto.mbt; import java.util.List; public class Shipment { List<Widget> widgetList; public List<Widget> getWidgetList() { return widgetList; } public void setWidgetList(List<Widget> widgetList) { this.widgetList = widgetList; } @Override public String toString() { //return "Shipment [widgetList=" + widgetList + "]"; return "{\"widgets\":" + widgetList + '}'; } }
e182e78c6d92995fdafad1c425dc51adf57952ea
[ "Java" ]
2
Java
Kavanab/ShipmentCreation
0c2b2602a060944ff7050a2d7df669287c82c8d3
48cbbb64f9eb61ba8c5119fd046b6a07869c6928
refs/heads/master
<repo_name>pengan1987/tompda-history<file_sep>/polls/models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Orders(models.Model): id = models.IntegerField(blank=False, null=False, primary_key=True) buyer = models.CharField(max_length=128, blank=True, null=True) seller = models.CharField(max_length=128, blank=True, null=True) trade_date = models.DateTimeField(blank=True, null=True) item = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'orders' <file_sep>/requirements.txt Django==1.11.16 pytz==2018.5 <file_sep>/polls/views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from models import Orders from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render from django.db.models import Q import logging # Create your views here. def index(request): orders_list = Orders.objects.all() page = request.GET.get('page') datesort = request.GET.get('sort') keyword = request.GET.get('keyword') trader = request.GET.get('trader') change_order_link = "" paging_link_tail = "" if trader: change_order_link += ("&trader=" + trader) paging_link_tail += ("&trader=" + trader) if datesort: paging_link_tail += ("&sort=" + datesort) if keyword: change_order_link += ("&keyword=" + keyword) paging_link_tail += ("&keyword=" + keyword) if page: change_order_link += ("&page=" + page) change_order_link += "&sort=date_asc" if datesort == 'date_desc' else '&sort=date_desc' change_order_link = change_order_link.replace("&", "?", 1) logging.warning(change_order_link) if trader: orders_list = orders_list.filter(Q(buyer__startswith=trader) | Q(seller__startswith=trader)) if keyword: orders_list = orders_list.filter(item__icontains=keyword) if datesort == 'date_desc': orders_list = orders_list.order_by('-trade_date') else: orders_list = orders_list.order_by('trade_date') paginator = Paginator(orders_list, 60) try: orders = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. orders = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. orders = paginator.page(paginator.num_pages) index = orders.number - 1 max_index = len(paginator.page_range) start_index = index - 4 if index >= 4 else 0 end_index = index + 5 if index <= max_index - 5 else max_index page_range = list(paginator.page_range)[start_index:end_index] return render(request, 'polls/list.html', {'orders': orders, "page_range": page_range, "paging_link_tail": paging_link_tail, "change_order_link": change_order_link})
7137c28eab8eb17aabc197c5d8a175b95c13b3df
[ "Python", "Text" ]
3
Python
pengan1987/tompda-history
66080611fe017cd153eb1fa74d6cf98cdbec74cf
d40a4da77c197c5bf03ad13d1ac4383a355b0c49
refs/heads/master
<repo_name>riggsgayeta/Experiment-4.2<file_sep>/Experiment 4.2.cpp #include <iostream> #include <string> #include <vector> #define MAX_NUMBER_OF_ELEMENTS 100 int main() { int elements[MAX_NUMBER_OF_ELEMENTS], numberOfElements = 0; std::cout << "Enter number of elements: "; std::cin >> numberOfElements; for (int i = 0; i < numberOfElements; ++i) { std::cout << "Enter Element#" << i + 1 << ": "; std::cin >> elements[i]; } for (int i = 0; i < numberOfElements; ++i) { for (int j = i; j < numberOfElements; ++j) { if (elements[i] > elements[j]) { int temp = elements[i]; elements[i] = elements[j]; elements[j] = temp; } } } for (int i = 0; i < numberOfElements; ++i) { std::cout << elements[i] << " "; } std::cout << std::endl; return 0; }
f0ca51627996d344a79609e81ebb4822f5f137a7
[ "C++" ]
1
C++
riggsgayeta/Experiment-4.2
67fb51345238226e473334a7ca8e41a3fe4db9d7
e97e22db895aa24df4c507f3220b5fe153055677