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/main
<repo_name>Hackmoses/TaskOne<file_sep>/Division/Program.cs using System; namespace Division { class Program { static void Main(string[] args) { int numberOne = 0; int numberTwo = 0; int result = 0; Console.Write("Enter your firstnumber: "); numberOne = int.Parse(Console.ReadLine()); Console.Write("Enter your secondnumber: "); numberTwo = int.Parse(Console.ReadLine()); result = numberOne / numberTwo ; Console.WriteLine("The answer is : " + result); } } }
0041b05b4465798344b3694a714de23a347d55dc
[ "C#" ]
1
C#
Hackmoses/TaskOne
da34255c2f7278ee2cee69031a8dbd931ead9b4a
df7f059c1a8aea86a14fa8d30069a5226caa75cc
refs/heads/main
<file_sep>from back_process import * def sparse_DD(Nx, dx): data = np.ones((3, Nx)) data[1] = -2 * data[1] diags = [-1, 0, 1] D2 = sparse.spdiags(data, diags, Nx, Nx) / (dx ** 2) D2 = sparse.lil_matrix(D2) D2[0, -1] = 1 / (dx ** 2) D2[-1, 0] = 1 / (dx ** 2) return D2 def Dxx(DD, f): dd_f = DD.dot(f) return dd_f def equations_FD(eq, field_slices, parameters, x_grid, operator): if eq == 'PNDLS_forced': U_1 = field_slices[0] U_2 = field_slices[1] alpha = parameters[0] beta = parameters[1] gamma = parameters[2] gamma_1 = gamma[0] gamma_2 = gamma[1] mu = parameters[3] nu = parameters[4] ddU_1 = Dxx(operator, U_1) ddU_2 = Dxx(operator, U_2) F = alpha * ddU_2 + (beta * (U_1 ** 2 + U_2 ** 2) + nu + gamma_2) * U_2 + (gamma_1 - mu) * U_1 G = -alpha * ddU_1 - (beta * (U_1 ** 2 + U_2 ** 2) + nu - gamma_2) * U_1 - (gamma_1 + mu) * U_2 elif eq == 'LLG': U_1 = field_slices[0] U_2 = field_slices[1] nu = parameters[0] gamma = parameters[1] Gamma = parameters[2] delta = parameters[3] mu = parameters[4] alpha = parameters[5] c = parameters[6] ddU_1 = Dxx(operator, U_1) ddU_2 = Dxx(operator, U_2) F = ddU_2 + (nu + gamma * Gamma + (U_1 ** 2 + U_2 ** 2) - 3 * gamma * delta * U_1 * U_2) * U_2 + (gamma - mu + (1 - gamma * alpha) * (U_1 ** 2 + U_2 ** 2) - gamma * delta * U_1 * U_1) * U_1 G = - ddU_1 - (nu - gamma * Gamma + (U_1 ** 2 + U_2 ** 2) + 3 * gamma * delta * U_1 * U_2) * U_1 - (gamma + mu - (c + gamma * alpha) * (U_1 ** 2 + U_2 ** 2) - gamma * delta * U_2 * U_2) * U_2 return np.array([F, G]) def equations_FFT(eq, field_slices, parameters, x_grid, kappa): if eq == 'PNDLS_forced': U_1 = field_slices[0] U_2 = field_slices[1] alpha = parameters[0] beta = parameters[1] gamma = parameters[2] gamma_1 = gamma[0] gamma_2 = gamma[1] mu = parameters[3] nu = parameters[4] Uhat_1 = np.fft.fft(U_1) Uhat_2 = np.fft.fft(U_2) dd_Uhat_1 = -np.power(kappa, 2) * Uhat_1 dd_Uhat_2 = -np.power(kappa, 2) * Uhat_2 U_1 = np.fft.ifft(Uhat_1) U_2 = np.fft.ifft(Uhat_2) ddU_1 = np.fft.ifft(dd_Uhat_1) ddU_2 = np.fft.ifft(dd_Uhat_2) F = alpha * ddU_2 + (beta * (U_1 ** 2 + U_2 ** 2) + nu + gamma_2) * U_2 + (gamma_1 - mu) * U_1 G = -alpha * ddU_1 - (beta * (U_1 ** 2 + U_2 ** 2) + nu - gamma_2) * U_1 - (gamma_1 + mu) * U_2 elif eq == 'PDNLS': U_1 = field_slices[0] U_2 = field_slices[1] alpha = parameters[0] beta = parameters[1] gamma_0 = parameters[2] mu = parameters[3] nu = parameters[4] Uhat_1 = np.fft.fft(U_1) Uhat_2 = np.fft.fft(U_2) dd_Uhat_1 = -np.power(kappa, 2) * Uhat_1 dd_Uhat_2 = -np.power(kappa, 2) * Uhat_2 U_1 = np.fft.ifft(Uhat_1) U_2 = np.fft.ifft(Uhat_2) ddU_1 = np.fft.ifft(dd_Uhat_1) ddU_2 = np.fft.ifft(dd_Uhat_2) F = alpha * ddU_2 + (beta * (U_1 ** 2 + U_2 ** 2) + nu) * U_2 + (gamma_0 - mu) * U_1 G = - alpha * ddU_1 - (beta * (U_1 ** 2 + U_2 ** 2) + nu) * U_1 - (gamma_0 + mu) * U_2 return np.array([F.real, G.real])<file_sep>from back_process import * from functions import * from time_integrators import * if __name__ == '__main__': [tmin, tmax, dt] = [0, 60, 0.01] [xmin, xmax, dx] = [-1.5, 1.5, 0.001] t_grid = np.arange(tmin, tmax + dt, dt) x_grid = np.arange(xmin, xmax, dx) T = tmax Nt = t_grid.shape[0] Nx = x_grid.shape[0] print(Nx) print(Nt) u_real = np.zeros((Nt, Nx)) u_img = np.zeros((Nt, Nx)) k = 10 q = 0.1 omega_01 = 0.2 omega_02 = 1 A_r = 1 A_i = 0 delta_0 = 0.01 sigma = 0.4 envelope = np.exp(- x_grid ** 2 / (2 *sigma ** 2)) # Initial Conditions for i in range(Nt): u_real[i, :] = A_r * envelope * np.cos(np.pi * k * (x_grid + delta_0 * np.sin(omega_02 * t_grid[i]))) u_img[i, :] = A_i * envelope * np.sin(np.pi * k * (x_grid + delta_0 * np.sin(omega_02 * t_grid[i]))) pcm = plt.pcolormesh(x_grid, t_grid, np.sqrt(u_real ** 2 + u_img ** 2), cmap='jet', shading='auto') #pcm = plt.pcolormesh(x_grid, t_grid, u_real, cmap='RdBu', shading='auto') cbar = plt.colorbar(pcm, shrink=1) cbar.set_label('$|u|$', rotation=0, size=20, labelpad=-27, y=1.1) plt.xlim([x_grid[0], x_grid[-1]]) plt.xlabel('$x$', size='20') plt.ylabel('$t$', size='20') plt.grid(linestyle='--', alpha=0.5) plt.show() plt.close()<file_sep>from back_process import * from functions import * from time_integrators import * if __name__ == '__main__': disco = 'F' initial_dir_data = str(disco) + ':/mnustes_science/simulation_data' root = tk.Tk() root.withdraw() directory = filedialog.askdirectory(parent=root, initialdir=initial_dir_data, title='Elección de carpeta') print('Processing ' + str(directory)) Z_img= np.loadtxt(directory + '/field_img.txt', delimiter=',') Z_real = np.loadtxt(directory + '/field_real.txt', delimiter=',') T = np.loadtxt(directory + '/T.txt', delimiter=',') X = np.loadtxt(directory + '/X.txt', delimiter=',') Z_complex = Z_real + 1j * Z_img Z_module = np.abs(Z_complex) Z_arg = np.angle(Z_complex) pcm = plt.pcolormesh(X, T, Z_module, cmap='jet', shading='auto') cbar = plt.colorbar(pcm, shrink=1) cbar.set_label('$R(x, t)$', rotation=0, size=20, labelpad=-27, y=1.1) plt.xlim([X[0], X[-1]]) plt.xlabel('$x$', size='20') plt.ylabel('$t$', size='20') plt.grid(linestyle='--', alpha=0.5) plt.savefig(directory + '/module_spacetime.png', dpi=300) plt.close() pcm = plt.pcolormesh(X, T, Z_arg, cmap='jet', shading='auto') cbar = plt.colorbar(pcm, shrink=1) cbar.set_label('$\\varphi(x, t)$', rotation=0, size=20, labelpad=-20, y=1.1) plt.xlim([X[0], X[-1]]) plt.xlabel('$x$', size='20') plt.ylabel('$t$', size='20') plt.grid(linestyle='--', alpha=0.5) plt.savefig(directory + '/arg_spacetime.png', dpi=300) plt.close()<file_sep>import numpy as np import matplotlib import shutil import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from matplotlib.colors import TwoSlopeNorm import time import datetime from playsound import playsound from scipy.integrate import odeint import scipy.sparse as sparse from scipy import signal from scipy.fftpack import fft, fftshift import tkinter as tk from tkinter import filedialog from basic_units import radians, degrees, cos import os from scipy.signal import hilbert, chirp matplotlib.rcParams['mathtext.fontset'] = 'custom' matplotlib.rcParams['mathtext.rm'] = 'Bitstream Vera Sans' matplotlib.rcParams['mathtext.it'] = 'Bitstream Vera Sans:italic' matplotlib.rcParams['mathtext.bf'] = 'Bitstream Vera Sans:bold' matplotlib.rcParams['mathtext.fontset'] = 'stix' matplotlib.rcParams['font.family'] = 'STIXGeneral' def triangle(length, amplitude): section = length // 4 for direction in (1, -1): for i in range(section): yield i * (amplitude / section) * direction for i in range(section): yield (amplitude - (i * (amplitude / section))) * direction def arnold_tongue_save(gamma_0, mu, nu, file): nu_positive_grid = np.arange(0, 2, 0.01) nu_negative_grid = - np.flip(nu_positive_grid) nu_grid = np.append(nu_negative_grid, nu_positive_grid) plt.plot(nu_positive_grid, np.sqrt(nu_positive_grid ** 2 + mu ** 2), c='k', linestyle='--') plt.fill_between(nu_positive_grid, np.ones(len(nu_positive_grid)) * mu, np.sqrt(nu_positive_grid ** 2 + mu ** 2), facecolor=(92 / 255, 43 / 255, 228 / 255, 0.4)) plt.plot(nu_negative_grid, np.sqrt(nu_negative_grid ** 2 + mu ** 2), c='k', linestyle='--') plt.fill_between(nu_negative_grid, np.ones(len(nu_negative_grid)) * mu, np.sqrt(nu_negative_grid ** 2 + mu ** 2), facecolor=(0, 1, 0, 0.4)) plt.plot(nu_grid, np.ones(len(nu_grid)) * mu, c='k', linestyle='--') plt.fill_between(nu_grid, 2, np.sqrt(nu_grid ** 2 + mu ** 2), facecolor=(1, 0, 0, 0.4)) plt.fill_between(nu_grid, np.ones(len(nu_grid)) * mu, 0, facecolor=(1, 1, 0, 0.4)) plt.scatter(nu, gamma_0, c='k', zorder=10) plt.title('<NAME>', size='25') plt.xlabel('$\\nu$', size='25') plt.ylabel('$\gamma$', size='25') plt.xlim([-1, 1]) plt.ylim([0, 1]) plt.grid(linestyle='--', alpha=0.5) plt.savefig(file + '/arnold_tongue.png') plt.close() def arnold_tongue_show(gamma_0, mu, nu): nu_positive_grid = np.arange(0, 2, 0.01) nu_negative_grid = - np.flip(nu_positive_grid) nu_grid = np.append(nu_negative_grid, nu_positive_grid) plt.plot(nu_positive_grid, np.sqrt(nu_positive_grid ** 2 + mu ** 2), c='k', linestyle='--') plt.fill_between(nu_positive_grid, np.ones(len(nu_positive_grid)) * mu, np.sqrt(nu_positive_grid ** 2 + mu ** 2), facecolor=(92 / 255, 43 / 255, 228 / 255, 0.4)) plt.plot(nu_negative_grid, np.sqrt(nu_negative_grid ** 2 + mu ** 2), c='k', linestyle='--') plt.fill_between(nu_negative_grid, np.ones(len(nu_negative_grid)) * mu, np.sqrt(nu_negative_grid ** 2 + mu ** 2), facecolor=(0, 1, 0, 0.4)) plt.plot(nu_grid, np.ones(len(nu_grid)) * mu, c='k', linestyle='--') plt.fill_between(nu_grid, 2, np.sqrt(nu_grid ** 2 + mu ** 2), facecolor=(1, 0, 0, 0.4)) plt.fill_between(nu_grid, np.ones(len(nu_grid)) * mu, 0, facecolor=(1, 1, 0, 0.4)) plt.scatter(nu, gamma_0, c='k', zorder=10) plt.title('<NAME>', size='25') plt.xlabel('$\\nu$', size='25') plt.ylabel('$\gamma$', size='25') plt.xlim([-1, 1]) plt.ylim([0, 1]) plt.grid(linestyle='--', alpha=0.5) plt.show() def arnold_tongue_exp_show(gamma_0, mu, nu): nu_positive_grid = np.arange(0, 2, 0.01) nu_negative_grid = - np.flip(nu_positive_grid) nu_grid = np.append(nu_negative_grid, nu_positive_grid) plt.plot(nu_positive_grid, np.sqrt(nu_positive_grid ** 2 + mu ** 2), c='k', linestyle='--') plt.fill_between(nu_positive_grid, np.ones(len(nu_positive_grid)) * mu, np.sqrt(nu_positive_grid ** 2 + mu ** 2), facecolor=(92 / 255, 43 / 255, 228 / 255, 0.4)) plt.plot(nu_negative_grid, np.sqrt(nu_negative_grid ** 2 + mu ** 2), c='k', linestyle='--') plt.fill_between(nu_negative_grid, np.ones(len(nu_negative_grid)) * mu, np.sqrt(nu_negative_grid ** 2 + mu ** 2), facecolor=(0, 1, 0, 0.4)) plt.plot(nu_grid, np.ones(len(nu_grid)) * mu, c='k', linestyle='--') plt.fill_between(nu_grid, 2, np.sqrt(nu_grid ** 2 + mu ** 2), facecolor=(1, 0, 0, 0.4)) plt.fill_between(nu_grid, np.ones(len(nu_grid)) * mu, 0, facecolor=(1, 1, 0, 0.4)) plt.scatter(nu, gamma_0, c='k', zorder=10) plt.title('<NAME>', size='25') plt.xlabel('$\\nu$', size='25') plt.ylabel('$\gamma$', size='25') plt.xlim([-0.25, 0.25]) plt.ylim([0, 0.25]) plt.grid(linestyle='--', alpha=0.5) plt.show() def campos_ligeros(campos, n, Nt, Nx, T): t_ligero = np.linspace(0, T, int(Nt / n)) campos_light = [] for k in range(len(campos)): campo_ligero = np.zeros((int(Nt / n), Nx)) for i in range(0, len(campos[k][:, 0]) - 1, n): campo_ligero[int(i / n), :] = campos[k][i, :] campos_light.append(campo_ligero) return campos_light, t_ligero def truncate(num, n): integer = int(num * (10**n))/(10**n) return float(integer) def nombre_pndls_LLG(gamma, mu, nu): mu_st = str(round(float(mu), 4)) gamma_st = str(round(float(gamma), 4)) nu_st = str(round(float(nu), 4)) nombre = '/gaussian/mu=' + mu_st + '/gamma=' + gamma_st + '/nu=' + nu_st return nombre def nombre_pndls_gaussian(gamma, mu, nu, sigma): sigma_st = str(round(float(sigma), 4)) mu_st = str(round(float(mu), 4)) gamma_st = str(round(float(gamma), 4)) nu_st = str(round(float(nu), 4)) nombre = '/gaussian/mu=' + mu_st + '/gamma=' + gamma_st + '/nu=' + nu_st + '/sigma=' + sigma_st return nombre def nombre_pndls_squared(gamma, mu, nu, length): length_st = str(round(float(length), 4)) mu_st = str(round(float(mu), 4)) gamma_st = str(round(float(gamma), 4)) nu_st = str(round(float(nu), 4)) nombre = '/squared/mu=' + mu_st + '/gamma=' + gamma_st + '/nu=' + nu_st + '/length=' + length_st return nombre def nombre_pndls_bigaussian(gamma, mu, nu, sigma1, sigma2, dist, fase): gamma_st = str(truncate(gamma, 4)) mu_st = str(truncate(mu, 4)) nu_st = str(truncate(nu, 4)) sigma1_st = str(truncate(sigma1, 4)) sigma2_st = str(truncate(sigma2, 4)) dist_st = str(truncate(dist, 4)) fase_st = str(truncate(fase / np.pi, 4)) + 'pi' nombre = '/bigaussian/mu=' + mu_st + '/gamma=' + gamma_st + '/nu=' + nu_st + '/fase=' + fase_st + '/sigma_1=' + \ sigma1_st + '_sigma_2=' + sigma2_st + '\\distancia=' + dist_st return nombre def guardar_txt(path, file, **kwargs): # upgradear a diccionario para nombre de variables if file == 'no': pathfile = path else: pathfile = path + file if os.path.exists(pathfile) == False: os.makedirs(pathfile) for key, value in kwargs.items(): np.savetxt(pathfile + '\\' + key + ".txt", value) def guardar_csv(path, file, **kwargs): # upgradear a diccionario para nombre de variables if file == 'no': pathfile = path else: pathfile = path + file if os.path.exists(pathfile) == False: os.makedirs(pathfile) for key, value in kwargs.items(): np.savetxt(pathfile + '\\' + key + ".csv", value) def random_transposition(k, N): return np.transpose(np.array([k] * N))<file_sep>from back_process import * from functions import * from time_integrators import * if __name__ == '__main__': disco = 'F' initial_dir_data = str(disco) + ':/mnustes_science/simulation_data' root = tk.Tk() root.withdraw() directory = filedialog.askdirectory(parent=root, initialdir=initial_dir_data, title='Elección de carpeta') print('Processing ' + str(directory)) Z_img = np.loadtxt(directory + '/field_img.txt', delimiter=',') Z_real = np.loadtxt(directory + '/field_real.txt', delimiter=',') forcing_real = np.loadtxt(directory + '/forcing_img.txt', delimiter=',') T = np.loadtxt(directory + '/T.txt', delimiter=',') X = np.loadtxt(directory + '/X.txt', delimiter=',') Z_complex = Z_real + 1j * Z_img Z_module = np.abs(Z_complex) Z_arg = np.angle(Z_complex) fig = plt.figure() fig.suptitle('Final Profile', fontsize=25) fig.set_figheight(8) fig.set_figwidth(8) ax2 = plt.subplot2grid(shape=(4, 4), loc=(1, 0), colspan=4, rowspan=4) ax1 = plt.subplot2grid(shape=(4, 4), loc=(0, 0), colspan=4) ax1.plot(X, forcing_real, c='k') ax1.set_xlim([X[0], X[-1]]) ax1.set_ylabel("Forcing $\gamma (x)$", fontsize=14) ax1.grid(alpha=0.5, linestyle='--') ax2.plot(X, Z_module[-1, :], c='b', label="$R(x)$") ax2.set_xlabel('x', fontsize=20) ax2.set_ylabel("Amplitude $R(x)$", fontsize=20) ax2.set_xlim([X[0], X[-1]]) ax2.grid(alpha=0.5, c='b', linestyle='--') ax2b = ax2.twinx() ax2b.plot(X, Z_arg[-1, :], c='r', label="$\phi(x)$") ax2b.set_ylabel("Phase $\phi(x)$", fontsize=20) ax2b.set_ylim([-3.14, 3.14]) ax2b.grid(alpha=0.5, c='r', linestyle='--') plt.savefig(directory + '/final_profile.png', dpi=300) plt.show() plt.close()<file_sep>from back_process import * from functions import * from time_integrators import * if __name__ == '__main__': unidad = 1 g = 9790 * unidad L = 480 * unidad l_x = L / 3 l_y = 16 * unidad # +- 2mm d = 20 * unidad n = 5 m = 1 a_ang = 8.1 / 2 f = 13.5 a_mm = 1 + (a_ang / 12) * unidad sigma = l_x / (2 * 2.3482) k_x = np.pi * n / l_x k_y = np.pi * m / l_y k = np.sqrt(0 * k_x ** 2 + k_y ** 2) tau = np.tanh(k * d) w_1 = np.sqrt(g * k * tau) w = (f / 2) * 2 * np.pi GAMMA = 4 * w ** a_mm alpha = (1 / (4 * k ** 2)) * (1 + k * d * ((1 - tau ** 2) / tau)) # término difusivo beta = (k ** 2 / 64) * (6 * tau ** 2 - 5 + 16 * tau ** (-2) - 9 * tau ** (-4)) # término no lineal gamma_0 = GAMMA / (4 * g) # amplitud adimensional nu = 0.5 * ((w / w_1) ** 2 - 1) mu = 0.0125 length = l_x arnold_tongue_show(gamma_0, mu, nu) print('alpha = ' + str(alpha)) print('beta = ' + str(beta)) print('gamma = ' + str(gamma_0)) print('nu = ' + str(nu)) print('mu = ' + str(mu)) print('sigma = ' + str(sigma)) print((2 * w_1) / (2 * np.pi))<file_sep>from functions import * from back_process import * def RK4_complexfields_FD(eq, fields, parameters, x_grid, dt, Nt, operator): N_campos = len(fields) for i in range(Nt - 1): field_slices = [] for k in range(N_campos): field_slices.append(fields[k][i, :]) k_1 = equations_FD(eq, field_slices, parameters, x_grid, operator) k_2 = equations_FD(eq, field_slices + 0.5 * dt * k_1, parameters, x_grid, operator) k_3 = equations_FD(eq, field_slices + 0.5 * dt * k_2, parameters, x_grid, operator) k_4 = equations_FD(eq, field_slices + dt * k_3, parameters, x_grid, operator) fields[:, i + 1, :] = fields[:, i, :] + dt * (k_1 + 2 * k_2 + 2 * k_3 + k_4) / 6 return fields def RK4_complexfields_FFT(eq, fields, parameters, x_grid, dt, Nt, kappa): N_campos = len(fields) for i in range(Nt - 1): field_slices = [] for k in range(N_campos): field_slices.append(fields[k][i, :]) k_1 = equations_FFT(eq, field_slices, parameters, x_grid, kappa) k_2 = equations_FFT(eq, field_slices + 0.5 * dt * np.array(k_1), parameters, x_grid, kappa) k_3 = equations_FFT(eq, field_slices + 0.5 * dt * np.array(k_2), parameters, x_grid, kappa) k_4 = equations_FFT(eq, field_slices + dt * np.array(k_3), parameters, x_grid, kappa) fields[:, i + 1, :] = fields[:, i, :] + dt * (k_1 + 2 * k_2 + 2 * k_3 + k_4) / 6 return fields<file_sep>from back_process import * from functions import * from time_integrators import * if __name__ == '__main__': # Midiendo tiempo inicial now = datetime.datetime.now() print('Hora de Inicio: ' + str(now.hour) + ':' + str(now.minute) + ':' + str(now.second)) time_init = time.time() # Definiendo parámetros eq = 'PNDLS_forced' alpha = 1 beta = 1 gamma_0 = 0.28 mu = 0.1 nu = 0.32 sigma_1 = 3 sigma_2 = 3 d = 20 phase = np.pi * 1 # Ploteo de Lengua de Arnold plot_parameters = 'si' if plot_parameters == 'si': arnold_tongue_show(gamma_0, mu, nu) # Definición de la grilla [tmin, tmax, dt] = [0, 1000, 0.005] [xmin, xmax, dx] = [-60, 60, 0.1] t_grid = np.arange(tmin, tmax + dt, dt) x_grid = np.arange(xmin, xmax, dx) T = tmax Nt = t_grid.shape[0] Nx = x_grid.shape[0] print(Nx) print(Nt) # Initial Conditions U_1 = np.zeros((Nt, Nx)) U_2 = np.zeros((Nt, Nx)) U_10 = 0.01 * np.ones(Nx) U_20 = 0.01 * np.ones(Nx) U_1[0, :] = U_10 U_2[0, :] = U_20 # Empaquetamiento de parametros, forzamientos, campos y derivadas para integración fields = np.array([U_1, U_2]) forcing_real = np.exp(- (x_grid + d / 2) ** 2 / (2 * sigma_1 ** 2)) + np.exp(- (x_grid - d / 2) ** 2 / (2 * sigma_2 ** 2)) * np.cos(phase) forcing_img = np.exp(- (x_grid - d / 2) ** 2 / (2 * sigma_2 ** 2)) * np.sin(phase) gamma = gamma_0 * np.array([forcing_real, forcing_img]) parameters = [alpha, beta, gamma, mu, nu] D2 = sparse_DD(Nx, dx) # Integración temporal final_fields = RK4_complexfields_FD(eq, fields, parameters, x_grid, dt, Nt, D2) # Midiendo tiempo final now = datetime.datetime.now() print('Hora de Término: ' + str(now.hour) + ':' + str(now.minute) + ':' + str(now.second)) time_fin = time.time() print(str(time_fin - time_init) + ' seg') # Aligerando campos U1_light = final_fields[0, 0:-1:100, :] U2_light = final_fields[1, 0:-1:100, :] t_light = t_grid[0:-1:100] # Definiendo variables finales modulo_light = np.power(np.power(U1_light, 2) + np.power(U2_light, 2), 0.5) arg_light = np.arctan2(U1_light, U2_light) # Guardando datos file = 'E:/mnustes_science/simulation_data/FD' subfile = nombre_pndls_bigaussian(gamma_0, mu, nu, sigma_1, sigma_2, d, phase) parameters_np = np.array([alpha, beta, gamma_0, mu, nu]) if not os.path.exists(file + subfile): os.makedirs(file + subfile) np.savetxt(file + subfile + '/field_real.txt', U1_light, delimiter=',') np.savetxt(file + subfile + '/field_img.txt', U2_light, delimiter=',') np.savetxt(file + subfile + '/forcing_real.txt', parameters_np, delimiter=',') np.savetxt(file + subfile + '/forcing_img.txt', gamma[0], delimiter=',') np.savetxt(file + subfile + '/parameters.txt', gamma[1], delimiter=',') # Gráficos pcm = plt.pcolormesh(x_grid, t_light, modulo_light, cmap='jet', shading='auto') cbar = plt.colorbar(pcm, shrink=1) cbar.set_label('$R(x, t)$', rotation=0, size=20, labelpad=-27, y=1.1) plt.xlim([x_grid[0], x_grid[-1]]) plt.xlabel('$x$', size='20') plt.ylabel('$t$', size='20') plt.grid(linestyle='--', alpha=0.5) plt.savefig(file + subfile + '/module_spacetime.png') plt.close() pcm = plt.pcolormesh(x_grid, t_light, arg_light, cmap='jet', shading='auto') cbar = plt.colorbar(pcm, shrink=1) cbar.set_label('$\\varphi(x, t)$', rotation=0, size=20, labelpad=-20, y=1.1) plt.xlim([x_grid[0], x_grid[-1]]) plt.xlabel('$x$', size='20') plt.ylabel('$t$', size='20') plt.grid(linestyle='--', alpha=0.5) plt.savefig(file + subfile + '/arg_spacetime.png') plt.close() nu_positive_grid = np.arange(0, 2, 0.01) nu_negative_grid = - np.flip(nu_positive_grid) nu_grid = np.append(nu_negative_grid, nu_positive_grid) plt.plot(nu_positive_grid, np.sqrt(nu_positive_grid ** 2 + mu ** 2), c='k', linestyle='--') plt.fill_between(nu_positive_grid, np.ones(len(nu_positive_grid)) * mu, np.sqrt(nu_positive_grid ** 2 + mu ** 2), facecolor=(92 / 255, 43 / 255, 228 / 255, 0.4)) plt.plot(nu_negative_grid, np.sqrt(nu_negative_grid ** 2 + mu ** 2), c='k', linestyle='--') plt.fill_between(nu_negative_grid, np.ones(len(nu_negative_grid)) * mu, np.sqrt(nu_negative_grid ** 2 + mu ** 2), facecolor=(0, 1, 0, 0.4)) plt.plot(nu_grid, np.ones(len(nu_grid)) * mu, c='k', linestyle='--') plt.fill_between(nu_grid, 2, np.sqrt(nu_grid ** 2 + mu ** 2), facecolor=(1, 0, 0, 0.4)) plt.fill_between(nu_grid, np.ones(len(nu_grid)) * mu, 0, facecolor=(1, 1, 0, 0.4)) plt.scatter(nu, gamma_0, c='k', zorder=10) plt.title('Arnold Tongue', size='25') plt.xlabel('$\\nu$', size='25') plt.ylabel('$\gamma$', size='25') plt.xlim([-1, 1]) plt.ylim([0, 1]) plt.grid(linestyle='--', alpha=0.5) plt.savefig(file + subfile + '/arnold_tongue.png') plt.close() plt.plot(x_grid, gamma[0], c='b', label="$\gamma_{R}(x)$") plt.plot(x_grid, gamma[1], c='r', label="$\gamma_{I}(x)$") plt.legend(loc="upper right", fontsize=18) plt.title('Forcing at $\gamma_0 = $' + str(gamma_0), size='23') plt.xlabel('$x$', size='20') plt.ylabel('Amplitude', size='20') plt.xlim([x_grid[0], x_grid[-1]]) plt.grid(linestyle='--', alpha=0.5) plt.savefig(file + subfile + '/forcing.png') plt.close()
87db9557767020e14de54fd1d0d3eec57c6e21f1
[ "Python" ]
8
Python
rariveros/pde1d-simulator
a4467e54c886b8a35fb2d881ddeb70ed4571846e
8aa0b7f274dfe44021c91840da13e06cfd13f6a7
refs/heads/master
<repo_name>micahmccallum/regex-lab-online-web-sp-000<file_sep>/lib/regex_lab.rb def starts_with_a_vowel?(word) word == word.match(/[aeiou]+\w*/i)[0] end def words_starting_with_un_and_ending_with_ing(text) text.scan(/un\w+ing/) end def words_five_letters_long(text) text.scan(/\b\w{5}\b/) end def first_word_capitalized_and_ends_with_punctuation?(text) /([A-Z])(.*)([.?!])/.match(text).to_a[0] == text end def valid_phone_number?(phone) phone.scan(/[0-9]/).length == 10 end
d9b4b2b4021915269a25dd73d3feac14536798aa
[ "Ruby" ]
1
Ruby
micahmccallum/regex-lab-online-web-sp-000
80abd71a79fda54207c0e5d5cb7b5c66c3d31c38
77be13978cb476253cc2f779b5f2d1a8f1f8d813
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SyncService { public class MissingData { public string Code { get; set; } public DateTime CreateTime { get; set; } public int MissTimes { get; set; } public bool Status { get; set; } public string Exception { get; set; } public string MCode { get; set; } public string PCode { get; set; } public DateTime Time { get; set; } } public class MissingDataHelper { public static int MaxMissTimes { get; set; } public static string TableName { get; set; } static MissingDataHelper() { MaxMissTimes = 10; TableName = "MissingData"; } public static List<MissingData> GetList(string code) { string cmdText = string.Format("select * from {0} where Code = @Code and Status = 0 and MissTimes <= @MaxMissTimes", TableName); SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("@Code", code), new SqlParameter("@MaxMissTimes", MaxMissTimes) }; return SqlHelper.Default.ExecuteList<MissingData>(cmdText, parameters); } public void InsertMissData(string code, DateTime time, string exception = null, string mCode = null, string pCode = null) { MissingData data = new MissingData(); data.Code = code; data.CreateTime = DateTime.Now; data.Time = DateTime.Today.AddHours(DateTime.Now.Hour); data.Exception = exception; data.MCode = mCode; data.PCode = pCode; } public static void Update(IEnumerable<MissingData> collection) { } public static void Update(MissingData data) { string cmdText = string.Format("update {0} set CreateTime = @CreateTime, MissTimes = @MissTimes, Status = @Status, Exception = @Exception where Code = @Code and MCode = @MCode and PCode = @PCode and Time = @Time"); List<SqlParameter> paramList = new List<SqlParameter>(); paramList.Add(new SqlParameter("Code", data.Code)); paramList.Add(new SqlParameter("CreateTime", data.CreateTime)); paramList.Add(new SqlParameter("Exception", data.Exception)); paramList.Add(new SqlParameter("MCode", data.MCode)); paramList.Add(new SqlParameter("MissTimes", data.MissTimes)); paramList.Add(new SqlParameter("PCode", data.PCode)); paramList.Add(new SqlParameter("Status", data.Status)); paramList.Add(new SqlParameter("Time", data.Time)); SqlHelper.Default.ExecuteNonQuery(cmdText, paramList.ToArray()); } } } <file_sep>using Common.Logging; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace SyncService { /// <summary> /// 数据库表与实体类转换类 /// </summary> public static class DataTableHelper { private static ILog logger; static DataTableHelper() { logger = LogManager.GetLogger("DataTableHelper"); } /// <summary> /// 将DataTable转换为实体类集合 /// </summary> /// <typeparam name="T">实体类</typeparam> /// <param name="dt">DataTable</param> /// <returns>实体类集合</returns> public static List<T> GetList<T>(this DataTable dt) where T : class, new() { PropertyInfo[] properties = typeof(T).GetProperties().Where(t => dt.Columns.Contains(t.Name)).ToArray(); int count = dt.Rows.Count; T[] array = new T[count]; for (int i = 0; i < count; i++) { array[i] = new T(); } foreach (PropertyInfo property in properties) { Type propertyType = property.PropertyType; DataColumn dc = dt.Columns[dt.Columns.IndexOf(property.Name)]; int i = 0; if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { Type underlyingType = Nullable.GetUnderlyingType(property.PropertyType); if (dc.DataType.Equals(underlyingType)) { foreach (DataRow dr in dt.Rows) { if (!Convert.IsDBNull(dr[property.Name])) { property.SetValue(array[i], dr[property.Name]); } i++; } } else { try { foreach (DataRow dr in dt.Rows) { if (!Convert.IsDBNull(dr[property.Name])) { property.SetValue(array[i], Convert.ChangeType(dr[property.Name], underlyingType)); } i++; } } catch (Exception e) { logger.Warn("GetList Convert UnderlyingType Error!", e); } } } else { if (dc.DataType.Equals(property.PropertyType)) { foreach (DataRow dr in dt.Rows) { if (!Convert.IsDBNull(dr[property.Name])) { property.SetValue(array[i], dr[property.Name]); } i++; } } else { try { foreach (DataRow dr in dt.Rows) { if (!Convert.IsDBNull(dr[property.Name])) { property.SetValue(array[i], Convert.ChangeType(dr[property.Name], property.PropertyType)); } i++; } } catch (Exception e) { logger.Warn("GetList Convert Error!", e); } } } } return array.ToList(); } /// <summary> /// 将实体类集合转换为DataTable /// </summary> /// <typeparam name="T">实体类</typeparam> /// <param name="collection">实体类集合</param> /// <param name="tableName">表名</param> /// <param name="preclusiveColumnNames">排除的列名</param> /// <returns>DataTable</returns> public static DataTable GetDataTable<T>(this IEnumerable<T> collection, string tableName, params string[] preclusiveColumnNames) { DataTable dt = new DataTable(); dt.TableName = tableName; PropertyInfo[] properties = typeof(T).GetProperties(); if (preclusiveColumnNames.Any()) { properties = properties.Where(o => !preclusiveColumnNames.Contains(o.Name)).ToArray(); } foreach (PropertyInfo property in properties) { Type propertyType = property.PropertyType; if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { dt.Columns.Add(property.Name, Nullable.GetUnderlyingType(propertyType)); } else { dt.Columns.Add(property.Name, propertyType); } } foreach (T data in collection) { DataRow dr = dt.NewRow(); foreach (PropertyInfo property in properties) { dr[property.Name] = property.GetValue(data) ?? DBNull.Value; } dt.Rows.Add(dr); } return dt; } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SyncService { public class Configuration { public static string Description { get; set; } public static string DisplayName { get; set; } public static string ServiceName { get; set; } public static string DefaultCronExpression { get; set; } public static string SyncAQMSHDataJobCronExpression { get; set; } public static string SyncAQMSHDataJobRecoverCronExpression { get; set; } static Configuration() { Description = ConfigurationManager.AppSettings["Description"]; DisplayName = ConfigurationManager.AppSettings["DisplayName"]; ServiceName = ConfigurationManager.AppSettings["ServiceName"]; DefaultCronExpression = "0 0 0/1 * * ?"; SyncAQMSHDataJobCronExpression = ConfigurationManager.AppSettings["SyncAQMSHDataJobCronExpression"]; SyncAQMSHDataJobRecoverCronExpression = ConfigurationManager.AppSettings["SyncAQMSHDataJobRecoverCronExpression"]; string defaultService = "MyService"; Description = string.IsNullOrWhiteSpace(Description) ? defaultService : Description; DisplayName = string.IsNullOrWhiteSpace(DisplayName) ? defaultService : DisplayName; ServiceName = string.IsNullOrWhiteSpace(ServiceName) ? defaultService : ServiceName; } } } <file_sep>using Common.Logging; using Quartz; using SyncService.Service.SyncNationalAQIPublishDataService; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SyncService.Service { public class SyncAQMSHDataJob : IJob, IRecover { private static ILog logger; public static string CronExpression { get; set; } public static string LiveTableName { get; set; } public static string HistoryTableName { get; set; } public static string Code { get; set; } static SyncAQMSHDataJob() { logger = LogManager.GetLogger<SyncAQMSHDataJob>(); CronExpression = Configuration.SyncAQMSHDataJobCronExpression; LiveTableName = "AQIDataPublishLive"; HistoryTableName = "AQIDataPublishHistory"; } public void Execute(IJobExecutionContext context) { try { object state = SqlHelper.Default.ExecuteScalar(string.Format("select max(TimePoint) from {0}", LiveTableName)); DateTime lastTime = Convert.IsDBNull(state) ? DateTime.MinValue : Convert.ToDateTime(state); List<AQIDataPublishLive> list = new List<AQIDataPublishLive>(); using (SyncNationalAQIPublishDataServiceClient client = new SyncNationalAQIPublishDataServiceClient()) { list = client.GetAQIDataPublishLive().ToList(); } if (list.Any() && list.First().TimePoint > lastTime) { SqlHelper.Default.ExecuteNonQuery(string.Format("delete {0}", LiveTableName)); SqlHelper.Default.Insert(list.GetDataTable<AQIDataPublishLive>(LiveTableName)); SqlHelper.Default.Insert(list.GetDataTable<AQIDataPublishLive>(HistoryTableName)); } else { } } catch (Exception e) { logger.Error("SyncAQMSHData failed.", e); } } } }
476ff57fbd25832176c4e6f93001f1212369cba2
[ "C#" ]
4
C#
xin2015/SyncService
e7fe9bf7640798ebe7d451dba3fdb2f64c8451c7
5ed386b68a5273f5a7e3e4fc5acf021650748d6a
refs/heads/master
<file_sep>import React, { useState } from "react"; import { makeStyles } from "@material-ui/core/styles"; import { Button, TextField, Dialog, DialogContent, Grid, DialogActions, Card, CardContent, Typography, CardActions, } from "@material-ui/core"; const useStyles = makeStyles((theme) => ({ addButton: { position: "fixed", bottom: theme.spacing(2), right: theme.spacing(3), }, textField: { margin: "1rem 0", }, dialogActions: { marginBottom: "1.5rem", }, })); const NoteCard = ({ id, title, description, bgColor, onEdit, onDelete }) => { const classes = useStyles(); const [open, setOpen] = useState(false); const [modifiedTitle, setModifiedTitle] = useState(title); const [modifiedDescription, setModifiedDescription] = useState(description); const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; return ( <> <Dialog maxWidth="sm" fullWidth={true} open={open} onClose={handleClose}> <DialogContent> <TextField variant="outlined" autoFocus fullWidth className={classes.textField} label="Title" value={modifiedTitle} onChange={(e) => setModifiedTitle(e.target.value)} /> <TextField variant="outlined" fullWidth className={classes.textField} multiline rows={4} label="Description" value={modifiedDescription} onChange={(e) => setModifiedDescription(e.target.value)} /> </DialogContent> <DialogActions className={classes.dialogActions}> <Grid container justifyContent="center" spacing={2}> <Grid item> <Button variant="contained" size="large" color="secondary" onClick={() => { onEdit(id, modifiedTitle, modifiedDescription); handleClose(); }} > Save Note </Button> </Grid> </Grid> </DialogActions> </Dialog> <Card style={{ backgroundColor: bgColor }}> <CardContent> <Typography variant="h5" component="h2"> {title} </Typography> <Typography variant="body2" component="p"> {description} </Typography> </CardContent> <CardActions> <Button size="small" variant="contained" style={{ backgroundColor: "#FFFFFF" }} onClick={handleClickOpen} > Edit </Button> <Button size="small" variant="contained" color="secondary" onClick={() => onDelete(id)} > Delete </Button> </CardActions> </Card> </> ); }; export default NoteCard; <file_sep>import React from "react"; import { TextField } from "@material-ui/core"; const SearchField = ({ onSearch }) => { return ( <> <TextField placeholder="Search Notes" style={{ marginBottom: "1.5rem" }} fullWidth variant="outlined" onChange={(e) => onSearch(e.target.value)} required /> </> ); }; export default SearchField; <file_sep># Notes Keeper App <img src="./ui.png" width="100%" alt="UI" /> ### **Description** Concepts used - Arrays properties like map & filter - how to use form in react - event click & handlers <file_sep>import React, { useState } from "react"; import { makeStyles } from "@material-ui/core/styles"; import { Fab, Button, TextField, Dialog, DialogContent, Grid, DialogActions, } from "@material-ui/core"; import { Add } from "@material-ui/icons"; const useStyles = makeStyles((theme) => ({ addButton: { position: "fixed", bottom: theme.spacing(2), right: theme.spacing(3), }, textField: { margin: "1rem 0", }, dialogActions: { marginBottom: "1.5rem", }, })); const FormDialog = ({ onSubmit }) => { const classes = useStyles(); const [open, setOpen] = useState(false); const [note, setNote] = useState({ title: "", description: "" }); const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; const handleSubmit = () => { onSubmit(note.title, note.description); setNote({ title: "", description: "", }); setOpen(false); }; return ( <> <Fab color="secondary" className={classes.addButton} onClick={handleClickOpen} > <Add /> </Fab> <Dialog maxWidth="sm" fullWidth={true} open={open} onClose={handleClose}> <DialogContent> <TextField variant="outlined" autoFocus fullWidth className={classes.textField} label="Title" value={note.title} onChange={(e) => setNote({ ...note, title: e.target.value })} required /> <TextField variant="outlined" fullWidth className={classes.textField} multiline rows={4} label="Description" value={note.description} onChange={(e) => setNote({ ...note, description: e.target.value })} required /> </DialogContent> <DialogActions className={classes.dialogActions}> <Grid container justifyContent="center"> <Grid item> <Button variant="contained" color="secondary" onClose={handleClose} size="large" onClick={handleSubmit} > Save Note </Button> </Grid> </Grid> </DialogActions> </Dialog> </> ); }; export default FormDialog;
406df30e71ce57c06e214a5166007595953d2d65
[ "JavaScript", "Markdown" ]
4
JavaScript
Rishi-121/react-notes-keeper
22d672f0fbd330bcc4f48777d0aafe536f4b209a
fb44f1beab40d8c5cd68589abcdcd688a5c62496
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using StarMiner.Context.Space.Ship.Engine; namespace StarMiner.Context.Space.Ship { public class ShipController : MonoBehaviour { [SerializeField] private Rigidbody2D ship; [SerializeField] private float driveAcceleration; [SerializeField] private float driveDeceleration; [SerializeField] private float maxDriveSpeed; [SerializeField] private float turnAcceleration; [SerializeField] private float turnDeceleration; [SerializeField] private float maxTurnSpeed; private float currentTurnSpeed = 0; [SerializeField] private List<AbstractShipEngine> engines; // Use this for initialization protected void Awake() { } private Vector2 force = new Vector2(); protected void Update() { float horizontalInput = Input.GetAxis("Horizontal"); float verticalInput = Input.GetAxis("Vertical"); // set ship rotation currentTurnSpeed = CalculateCurrentTurnSpeed(horizontalInput) * Time.deltaTime; //ship.rotation += currentTurnSpeed; ship.transform.Rotate(0, 0, currentTurnSpeed); // TODO only run once GetComponentsInChildren<AbstractShipEngine>(engines); float forwardSpeed = 0f; if (verticalInput == 0f) { foreach (AbstractShipEngine e in engines) e.StopEngine(); } else { foreach (AbstractShipEngine e in engines) { e.StartEngine(); e.OnEngineRunning(horizontalInput, verticalInput); forwardSpeed += e.forwardSpeed; } } float rotaZ = (ship.transform.rotation.eulerAngles.z) * Mathf.Deg2Rad; force.x = -Mathf.Sin(rotaZ); force.y = Mathf.Cos(rotaZ); force *= forwardSpeed * Time.deltaTime; ship.AddForce(force); } private float CalculateCurrentTurnSpeed(float horizontalInput) { float oldTurnSpeed = currentTurnSpeed; float newTurnSpeed = oldTurnSpeed + horizontalInput * turnAcceleration; newTurnSpeed -= Mathf.Sign(newTurnSpeed) * Mathf.Min(Mathf.Abs(newTurnSpeed), turnDeceleration); if (horizontalInput == 0f && Mathf.Abs(newTurnSpeed) <= turnDeceleration) newTurnSpeed = 0f; if (oldTurnSpeed <= maxTurnSpeed && newTurnSpeed > maxTurnSpeed) newTurnSpeed = maxTurnSpeed; else if (oldTurnSpeed >= -maxTurnSpeed && newTurnSpeed < -maxTurnSpeed) newTurnSpeed = -maxTurnSpeed; return newTurnSpeed; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using strange.extensions.context.impl; using strange.extensions.command.api; using strange.extensions.command.impl; using strange.extensions.signal.impl; namespace StarMiner.Context { /** * This context uses a signal command binder instead of an event * command binder and as such, dispatches the StartContextSignal * instead of the StartEvent. */ public abstract class MVCSSignalContext : MVCSContext { public MVCSSignalContext(MonoBehaviour contextView) : base(contextView) { } protected override void mapBindings() { base.mapBindings(); mapSignals(); mapCommands(); mapMediators(); } protected abstract void mapSignals(); protected abstract void mapCommands(); protected abstract void mapMediators(); protected override void addCoreComponents() { base.addCoreComponents(); injectionBinder.Unbind<ICommandBinder>(); injectionBinder.Bind<ICommandBinder>().To<SignalCommandBinder>().ToSingleton(); } public override void Launch() { base.Launch(); Signal startSignal = injectionBinder.GetInstance<StartContextSignal>(); startSignal.Dispatch(); } } } <file_sep>using UnityEngine; namespace StarMiner.Context.Space.Ship.Engine { public abstract class AbstractShipEngine : MonoBehaviour { public bool isRunning { get; protected set; } public float forwardSpeed { get; protected set; } public float turnSpeed { get; protected set; } protected abstract void OnEngineStarted(); public abstract void OnEngineRunning(float horizontalInput, float verticalInput); protected abstract void OnEngineStopped(); public void StartEngine() { if (!isRunning) { isRunning = true; OnEngineStarted(); } } public void StopEngine() { if (isRunning) { isRunning = false; OnEngineStopped(); } } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using strange.extensions.context.impl; using StarMiner.Context.Space; namespace StarMiner.Context.Space.View { public class SpaceContextView : ContextView { protected void Awake() { this.context = new SpaceContext(this); } } } <file_sep>using System.IO; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Tilemaps; namespace StarMiner.Context.Space.Ship { public class ShipTileLoader : MonoBehaviour { [SerializeField] private Tilemap shipMap; [SerializeField] private List<TileBase> tilePalette; [SerializeField] private List<GameObject> tileObjects; // Use this for initialization void Start() { FileStream wFile = new FileStream("savedShipTiles.txt", FileMode.Open); byte[,] arr = ReadTileMapFromFile(wFile); LoadFromArray(arr, shipMap); } // Update is called once per frame void Update() { } protected byte[,] ReadTileMapFromFile(FileStream file) { byte[] singleByte = new byte[1]; // read x dimension file.Read(singleByte, 0, 1); int sizeX = (int)singleByte[0]; // read y dimension file.Read(singleByte, 0, 1); int sizeY = (int)singleByte[0]; byte[,] tiles = new byte[sizeY, sizeX]; byte[] line = new byte[sizeX]; for (int y = 0; y < sizeY; y++) { file.Read(line, 0, sizeX); for (int x = 0; x < sizeX; x++) tiles[y, x] = line[x]; } file.Close(); return tiles; } protected void WriteTileMapToFile(FileStream file, Tilemap writtenMap) { BoundsInt bounds = writtenMap.cellBounds; TileBase[] allTiles = writtenMap.GetTilesBlock(bounds); file.WriteByte((byte)bounds.size.x); file.WriteByte((byte)bounds.size.y); int len = allTiles.Length; for (int i = 0; i < len; i++) file.WriteByte(TileToByte(allTiles[i])); file.Close(); } private TileBase ByteToTile(byte b) { if (b > tilePalette.Capacity || b < 0) return null; else return tilePalette[b]; } private byte TileToByte(TileBase tb) { return (byte)tilePalette.IndexOf(tb); } protected void LoadFromArray(byte[,] arr, Tilemap targetMap) { Vector3Int pos = new Vector3Int(); int yLen = arr.GetUpperBound(0); int xLen = arr.GetUpperBound(1); targetMap.ClearAllTiles(); for (int y = yLen - 1; y >= 0; y--) { for (int x = 0; x < xLen; x++) { pos.Set(x - xLen / 2, y - yLen / 2, 0); byte b = arr[y, x]; targetMap.SetTile(pos, ByteToTile(b)); if (b != 255) { GameObject tileLogicObjectPrefab = tileObjects[b]; if (tileLogicObjectPrefab != null) { GameObject tileLogicObject = Instantiate(tileLogicObjectPrefab); tileLogicObject.transform.SetParent(targetMap.transform); Vector3 tileMiddlePos = new Vector3( targetMap.transform.position.x + pos.x + 0.5f, targetMap.transform.position.y + pos.y + 0.5f, 0); tileLogicObject.transform.position = tileMiddlePos; } } } } } protected byte[,] SaveToArray(Tilemap savedMap) { BoundsInt bounds = savedMap.cellBounds; TileBase[] allTiles = savedMap.GetTilesBlock(bounds); int yLen = bounds.size.y; int xLen = bounds.size.x; byte[,] tileBytes = new byte[yLen, xLen]; for (int y = 0; y < yLen; y++) for (int x = 0; x < xLen; x++) tileBytes[y, x] = TileToByte(allTiles[x + y * xLen]); return tileBytes; } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace StarMiner.Context.Space.Ship.Engine { public class ChannelingDriveShipEngine : AbstractShipEngine { [SerializeField] private float driveAcceleration; [SerializeField] private float driveDeceleration; [SerializeField] private float maxDriveSpeed; [SerializeField] private AudioSource driveSound; [SerializeField] private ParticleSystem particles; protected override void OnEngineStarted() { driveSound.Play(); driveSound.pitch = 0; driveSound.volume = 0.2f; particles.Play(); } public override void OnEngineRunning(float horizontalInput, float verticalInput) { forwardSpeed = CalculateCurrentDriveSpeed(verticalInput); driveSound.pitch = Mathf.Abs(verticalInput); driveSound.volume = Mathf.Min(1f, Mathf.Abs(verticalInput) + 0.2f); } protected override void OnEngineStopped() { driveSound.Stop(); forwardSpeed = 0f; particles.Stop(); } private float CalculateCurrentDriveSpeed(float verticalInput) { float oldSpeed = forwardSpeed; float newSpeed = oldSpeed + verticalInput * driveAcceleration; newSpeed -= Mathf.Sign(newSpeed) * Mathf.Min(Mathf.Abs(newSpeed), driveDeceleration); if (verticalInput == 0f && Mathf.Abs(newSpeed) <= driveDeceleration) newSpeed = 0f; if (oldSpeed <= maxDriveSpeed && newSpeed > maxDriveSpeed) newSpeed = maxDriveSpeed; else if (oldSpeed >= -maxDriveSpeed && newSpeed < -maxDriveSpeed) newSpeed = -maxDriveSpeed; return newSpeed; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using strange.extensions.context.impl; using StarMiner.Context.Space.Commands; namespace StarMiner.Context.Space { public class SpaceContext : MVCSSignalContext { public SpaceContext(MonoBehaviour contextView) : base(contextView) { } protected override void mapSignals() { } protected override void mapCommands() { commandBinder.Bind<StartContextSignal>().To<StartSpaceContextCommand>(); } protected override void mapMediators() { } protected override void postBindings() { } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine.Tilemaps; using UnityEngine; namespace StarMiner.Context.Space.Ship { public class ShipCamera : MonoBehaviour { [SerializeField] private Rigidbody2D ship; [SerializeField] private Camera shipCamera; [SerializeField] private float minPaddingFactor = 1f; [SerializeField] private float maxZoomFactor = 3f; [SerializeField] private float zoomMaxGrace; private float zoomCurrentGrace; private float defaultZoom; private Vector3 shipCameraPosition; // Use this for initialization protected void Awake() { shipCameraPosition = new Vector3(); shipCameraPosition.x = ship.position.x; shipCameraPosition.y = ship.position.y; shipCameraPosition.z = shipCamera.transform.position.z; shipCamera.transform.rotation = ship.transform.rotation; defaultZoom = CalculateDefaultZoom(); shipCamera.orthographicSize = defaultZoom; } private float CalculateDefaultZoom() { // calculate the number of ship tiles in both directions Tilemap shipTileMap = ship.GetComponent<Tilemap>(); Vector3Int shipTilesSize = shipTileMap.cellBounds.size; // calculate how many tiles can be displayed by the camera float cameraHeight = shipCamera.orthographicSize * 2; float cameraWidth = cameraHeight * shipCamera.aspect; //Debug.Log("Ship: " + shipTilesSize.x + ", " + shipTilesSize.y); //Debug.Log("Camera: " + cameraWidth + ", " + cameraHeight); //Debug.Log("Result: " + ((shipTilesSize.y / 2f) * (1f + minPaddingFactor)) + " or " + ((shipTilesSize.x / 2f / shipCamera.aspect) * (1f + minPaddingFactor))); // calculate the new camera zoom with ship size dependent padding return Mathf.Max( (shipTilesSize.y / 2f) * (1f + minPaddingFactor), (shipTilesSize.x / 2f / shipCamera.aspect) * (1f + minPaddingFactor) ); } protected void Update() { //float horizontalInput = Input.GetAxis("Horizontal"); //float verticalInput = Input.GetAxis("Vertical"); // set camera shipCameraPosition.Set( Mathf.Lerp(shipCamera.transform.position.x, ship.position.x, 1.00f), Mathf.Lerp(shipCamera.transform.position.y, ship.position.y, 1.00f), shipCamera.transform.position.z ); shipCamera.transform.position = shipCameraPosition; shipCamera.transform.rotation = ship.transform.rotation; shipCamera.orthographicSize = CalculateCameraZoom(); } private float CalculateCameraZoom() { float oldZoom = shipCamera.orthographicSize; // calculate speed-dependent zoom float shipSpeed = ship.velocity.magnitude; float newZoom; newZoom = Mathf.Min( defaultZoom * maxZoomFactor, defaultZoom / 2 + shipSpeed / 2 ); newZoom = Mathf.Max(defaultZoom, newZoom); if (newZoom < oldZoom) { // if we decelerate, wait a bit before zooming in again if (zoomCurrentGrace > 0f) { zoomCurrentGrace -= Time.deltaTime; return oldZoom; } } else if (newZoom > oldZoom || newZoom == defaultZoom) zoomCurrentGrace = zoomMaxGrace; return Mathf.Lerp(oldZoom, newZoom, 0.1f); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using strange.extensions.command.impl; namespace StarMiner.Context.Space.Commands { /** * This command is executed when the space context finished loading. */ public class StartSpaceContextCommand : Command { public override void Execute() { Debug.Log("START"); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using strange.extensions.signal.impl; namespace StarMiner.Context { /** * This signal is fired when a context is launched. */ public class StartContextSignal : Signal { } } <file_sep>using UnityEngine; using System.Collections; namespace StarMiner.Debugging { public class SpeedDisplay : MonoBehaviour { public Rigidbody2D ship; float speed = 0.0f; void Update() { speed = ship.velocity.magnitude; } void OnGUI() { int w = Screen.width; int h = Screen.height; GUIStyle style = new GUIStyle(); Rect rect = new Rect(0, 0, w, h * 2 / 100); style.alignment = TextAnchor.UpperLeft; style.padding.top = h * 2 / 100; style.fontSize = h * 2 / 100; style.normal.textColor = new Color(0.0f, 0.5f, 0.0f, 1.0f); string text = string.Format("Speed: {0:0.00}", speed); GUI.Label(rect, text, style); } } }
7056be3020d68e31ae5338d8a15a11caae90728b
[ "C#" ]
11
C#
r0bzilla/starminer
3deba5b8f090a26496b7448a50a0c04f9f6c1b39
3353822f7c2f2be1e90254ab1a856aa3bc630c83
refs/heads/development
<repo_name>mmplisskin/my_secrets<file_sep>/app/controllers/posts_controller.rb class PostsController < ApplicationController require 'symmetric-encryption' # before_action :authorized? before_action :trial def index @posts = Post.where(ouser_id: current_ouser.id) respond_to do |format| format.html { render } format.json { render json: @posts.to_json(:include => :ouser) } end end def new @post = Post.new @post.recipients.build respond_to do |format| format.html { render } format.json { render json: @posts } end end def show @post = Post.find(params[:id]) respond_to do |format| format.html { render } format.json { render json: @posts } end end def create # binding.pry @post = Post.new(post_params) @post.ouser_id = current_ouser.id if current_ouser #recipient=Recipient.find_or_create_by(email: params[:email]) # Refresh recipients provided by the user refresh_post_recipients(@post, params['post']['emails'].split(',')) if @post.save #@post.recipients << recipient @post.ouser_id = current_ouser.id redirect_to posts_path else flash.now.notice = @post.errors.full_messages render :edit end end def edit # binding.pry @post = Post.find(params[:id]) recipient=Recipient.find_or_create_by(email: params[:email]) end def update @post = Post.find(params[:id]) # Delete all existing recipients @post.recipients.delete_all emails_as_array = params['post']['emails'].split(',') # Add in all recipients fresh emails_as_array.each do |recipient| person = Recipient.find_or_create_by(email: recipient) @post.recipients << person end # Refresh recipients provided by the user if @post.update_attributes(post_params) redirect_to posts_path return end render :edit end def destroy @post = Post.find(params[:id]) @post.destroy redirect_to posts_path end def trial if (current_ouser.paid == false && current_ouser.created_at < 30.days.ago) redirect_to new_charge_path end end private def post_params params.require(:post).permit(:title, :description, :contact_email, :last_update, recipients_attributes: [:email]) end def refresh_post_recipients(the_post, emails_as_array) # Delete all existing recipients the_post.recipients.delete_all # Add in all recipients fresh emails_as_array.each do |recipient| person = Recipient.find_or_create_by(email: recipient) the_post.recipients << person end end end <file_sep>/app/assets/javascripts/application.js //= require jquery2 //= require jquery_ujs //= require bootstrap-sprockets //= require bootstrap-tagsinput //= require jquery.readyselector.js //= require location //= require map.js //= require velocity.min.js $(document).ready(function(){ $(".button-collapse").sideNav(); $("#tags").tagsinput('items') $('.modal-trigger').leanModal(); $('.collapsible').collapsible({ accordion : false }); var acc = $('.collapsible-header') acc.on("click", function(e) { //scroll to the div ON CLICK $(this) .velocity("scroll", { duration: 900, delay: 300, offset: -56, }); }); // var newwindow; // function login(provider_url, width, height) { // var screenX = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft, // screenY = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop, // outerWidth = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.body.clientWidth, // outerHeight = typeof window.outerHeight != 'undefined' ? window.outerHeight : (document.body.clientHeight - 22), // left = parseInt(screenX + ((outerWidth - width) / 2), 10), // top = parseInt(screenY + ((outerHeight - height) / 2.5), 10), // features = ('width=' + width + ',height=' + height + ',left=' + left + ',top=' + top); // // newwindow = window.open(provider_url, 'Login', features); // // if (window.focus) // newwindow.focus(); // // return false; // } }); <file_sep>/app/models/post.rb class Post < ActiveRecord::Base validates :title, presence: true, uniqueness: true, length: {minimum: 8} validates :description, presence: true belongs_to :ouser has_many :post_recipients, dependent: :delete_all has_many :recipients, through: :post_recipients accepts_nested_attributes_for :post_recipients accepts_nested_attributes_for :recipients attr_encrypted :description, random_iv: true, compress: true end <file_sep>/lib/tasks/subscribe.rake namespace :user do desc "Checks db for users that need to pay" task :subscribe => :environment do puts "*****==== checking for users that have not paid =====*****" #do not touch this line or add space it wont work if u add space users = Ouser.where("last_payment < ?", 1.year.ago) #loop over erery user users.each do |user| puts "**==== here is " + user.name + " he has not paid ====**" user.paid = false user.save! end end puts "$%$%$%$%$%$% ALL USER Subscriptions HAVE BEEN ACCOUNTED FOR $%$%$%$%$%$%" end <file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception private def current_ouser @current_ouser ||= Ouser.find_by(id: session[:ouser_id]) end def authorized? redirect_to root_path unless current_ouser end helper_method :current_ouser end <file_sep>/spec/models/post_spec.rb require 'rails_helper' RSpec.describe Post, type: :model do it "is an invalid post without a title" do post = Post.new(title: nil) expect(post).to be_invalid end it "is a valid post without a description" do post= Post.new(title: "test title", description: "test description") expect(post).to be_valid end it "is an invalid post without a description" do post= Post.new(description: nil) expect(post).to be_invalid end it "is a valid post with a title" do post = Post.new(title: "First Post Title", description: "First Post Description") expect(post).to be_valid end it "does not have a unique post title" do post = Post.create(title: "First post title", description: "First post description") post2 = Post.create(title: "First post title", description: "Second post description") expect(post).to be_valid expect(post2).to be_invalid end it "is a unique post title" do post = Post.create(title: "First post title", description: "First post description") post2 = Post.create(title: "second post title", description: "Second post description") expect(post2).to be_valid end it "is an invalid post without a minimum title length of 8 characters" do post= Post.new(title: "123", description: "test description") expect(post).to be_invalid end it "is a valid post with a minimum title length of 8 characters" do post= Post.new(title: "12345678", description: "test description") expect(post).to be_valid end it "is an invalid post without a minimum description length of 15 characters" do post= Post.new(title: "123", description: "test description") expect(post).to be_invalid end it "is a valid post with a minimum description length of 15 characters" do post= Post.new(title: "12345678", description: "test description") expect(post).to be_valid end end <file_sep>/lib/tasks/notify.rake namespace :user do desc "Checks db for inactive users" task :notify => :environment do puts "*****==== checking for inactive users =====*****" #do not touch this line or add space it wont work if u add space users = Ouser.where("updated_at < ?", 26.days.ago) #loop over erery user users.each do |user| puts "**==== here is " + user.name + " he is inactive ====**" @inac_name = user.name @recipient = user.email @title = "Hi " + user.name + " are you Ok?" @description = 'If you do not check in soon your secrets will be delivered ' UserMailer.delay.notify_email(@title,@description,@inac_name,@recipient) end end puts "$%$%$%$%$%$% ALL USERS HAVE BEEN ACCOUNTED FOR $%$%$%$%$%$%" end <file_sep>/app/clock.rb require 'clockwork' require File.expand_path('../../config/boot', __FILE__) require File.expand_path('../../config/environment', __FILE__) module Clockwork handler do |job| puts "Running #{job}" end # every(10.seconds, 'rake alive:check') every(1.week, 'rake recipient clear'){ `rake recipient:clear` } every(10.minutes, 'rake alive'){ `rake user:alive` } every(12.hours , 'rake user notify'){ `rake user:notify` } every(1.day , 'rake user subscribe'){ `rake user:subscribe` } end <file_sep>/config/routes.rb Rails.application.routes.draw do get 'static_pages/about' get 'recipients/index' get 'recipients/show' get 'recipients/new' get 'recipients/edit' get 'recipients/create' get 'recipients/update' get 'recipients/destroy' # resources :static_pages get 'about' => "static_pages#about" # get '/static_pages/about' => 'static_pages#about' #routes for session get "login" => 'sessions#new' post "login" => 'sessions#create' get "otp/:id" => 'sessions#otp', as: :otp post "otp/:id" => 'sessions#otpcreate' delete "logout" => 'sessions#destroy' #route for oauth get '/auth/:provider/callback', to: 'sessions#create', as: :omniauth delete '/logout', to: 'sessions#destroy' post 'i_am_ok' => 'ousers#imalive' resources :posts resources :ousers resources :charges root 'sessions#new' require "sidekiq/web" Sidekiq::Web.use Rack::Auth::Basic do |username, password| username == ENV["SIDEKIQ_USERNAME"] && password == ENV["<PASSWORD>"] end if Rails.env.production? mount Sidekiq::Web, at: "/sidekiq" end <file_sep>/spec/controllers/posts_controller_spec.rb require 'rails_helper' RSpec.describe PostsController, :type => :controller do before :each do @post1 = Post.create(title:"facebook", description: "Deleted it" ) @post2 = Post.create(title:"myspace", description: "No one cares") end let(:valid_attributes) do { :title => "Facebook", :description => "Delete it", } end describe "POST create" do describe "without valid log in" do it "sends user back to log in page" do (expect(response.status).to eq(200)) end end end end<file_sep>/app/helpers/sessions_helper.rb module SessionsHelper def current_user @current_user ||= Ouser.find_by(id: session[:ouser_id]) end end <file_sep>/spec/models/ouser_spec.rb require 'rails_helper' # Custom print function def print arg p arg if true end RSpec.describe Ouser, type: :model do describe "ousers" do it 'should have a defaulted fields' do ouser = FactoryGirl.build(:ouser) # print user expect(ouser.name).to eq "<NAME>" end it 'should allow passed parameters' do ouser = FactoryGirl.build(:ouser, name: "<NAME>") # print user latitude expect(ouser.latitude).to eq 34.0129909 end # build_stubbed() creates a fake id, build() leaves it nil it 'should fill in the id when using .build_stubbed()' do ouser = FactoryGirl.build_stubbed(:ouser) # print user expect(ouser.id).not_to eq nil # What should this equal? end # create() works as expected and saves the model to the database it 'should save to the database when using .create()' do ouser = FactoryGirl.create(:ouser) # print user expect(Ouser.find(ouser.id)).to eq ouser end end end<file_sep>/lib/tasks/alive.rake namespace :user do desc "Checks db for inactive users" task :alive => :environment do puts "*****==== checking for inactive users =====*****" #do not touch this line or add space it wont work if u add space users = Ouser.where("updated_at < ?", 30.days.ago) #loop over erery user users.each do |user| if user.paid puts "**==== here is " + user.name + " he is a dead guy ====**" @inac_name = user.name #loop over all of their posts user.posts.each do |post| puts " -->=== here is his " + user.email + " " + post.title + " secret ===<--" @title = post.title puts "==got title==" + post.title @description = post.description puts "==got desc==" recipeints = post.recipients.each do |recipient| puts "==in the loop==" puts recipient.class @recipient = recipient.email puts " $$$== we sent it to " + recipient.email + "==$$$" # sleep(2.seconds) # UserMailer.secrets_email(@title,@description,@inac_name,@recipient).deliver UserMailer.delay.secrets_email(@title,@description,@inac_name,@recipient) puts "*****==== Destroying the secret =====*****" post.destroy end end end end end puts "$%$%$%$%$%$% ALL USERS HAVE BEEN ACCOUNTED FOR $%$%$%$%$%$%" end <file_sep>/app/models/recipient.rb class Recipient < ActiveRecord::Base has_many :post_recipients has_many :posts, through: :post_recipients belongs_to :ouser end <file_sep>/app/models/ouser.rb class Ouser < ActiveRecord::Base require 'pry' has_many :posts has_many :recipients has_one_time_password # # attr_accessor :latitude, :longitude, class << self def from_omniauth(auth_hash) ouser = find_or_create_by(:email => auth_hash.info.email) if (ouser.provider !=nil && ouser.provider != auth_hash['provider']) return end ouser.name = auth_hash['info']['name'] ouser.uid = auth_hash['uid'] ouser.provider = auth_hash['provider'] # uid: auth_hash['uid'], provider: auth_hash['provider'] ouser.location = auth_hash['info']['location'] ouser.image_url = auth_hash['info']['image'] # ouser.url = auth_hash['info']['urls'][ouser.provider.capitalize] ouser.email = auth_hash['info']['email'] ouser.otp_secret_key ouser.save! ouser end end end <file_sep>/app/controllers/ousers_controller.rb class OusersController < ApplicationController protect_from_forgery with: :null_session def new @ouser = Ouser.new(ouser_params) end def create @ouser = Ouser.create(ouser_params) end def index @ousers = Ouser.find(current_ouser) respond_to do |format| format.html { render } format.json { render json: @ousers } end end def show @ouser = Ouser.find(params[:id]) respond_to do |format| format.html { render } format.json { render json: @ouser redirect_to(:controller => 'posts', :action => 'index') } end end def update @ouser = Ouser.find(params[:id]) # @ouser.update_attributes(ouser_params) # @ouser.update_attributes(ouser_params) # @ouser.last_update = Time.now if @ouser.update_attributes(ouser_params) respond_to do |format| format.html { render } format.json { render json: @ouser } end end end private def ouser_params params.require(:ouser).permit(:latitude, :longitude) end end <file_sep>/spec/models/recipient_spec.rb require 'rails_helper' RSpec.describe Recipient, type: :model do it "is a valid recipient" do recipient= Recipient.new(email: "<EMAIL>") expect(recipient).to be_valid end it "is a valid post with multiple a recipients" do recipient= Recipient.new(email: "<EMAIL>, <EMAIL>, <EMAIL>") expect(recipient).to be_valid end end <file_sep>/config/unicorn.rb # # Amount of unicorn workers to spin up # worker_processes 3 # # # How long to wait before killing an unresponsive worker # timeout 30 # # # Load the app before spawning workers - this makes newrelic work properly # preload_app true # # @sidekiq_pid = nil # # Uncomment next line if using clockwork gem: # # @clock_pid = nil # # before_fork do |server, worker| # # Spawn a SideKiq process # # Set concurrency to 2 - so it doesn't max out the 10 connection limit on # # Heroku's redis-to-go nano. Can bump this up if on full redis plan. # @sidekiq_pid ||= spawn("bundle exec sidekiq -c 2") # # # Spawn a Clockwork clock/scheduler process (clockwork gem) # # Uncomment next line if using clockwork gem: # # @clock_pid ||= spawn("bundle exec clockwork app/clock.rb") # # sleep 1 # # end # # after_fork do |server, worker| # Sidekiq.configure_client do |config| # config.redis = { :size => 1 } # end # Sidekiq.configure_server do |config| # config.redis = { :size => 5 } # end # end <file_sep>/app/mailers/user_mailer.rb class UserMailer < ApplicationMailer # include Sidekiq::Worker def secrets_email(title,description,inac_name,recipient) @title = title @description = description @inac_name = inac_name @recipient = recipient @greeting = "Hello, #{@recipient}" @greeting2 = "We regret to inform you that #{@inac_name} has gone inactive and has a secret for you:" mail to: @recipient, subject: "#{@inac_name} has a secret for you " end def welcome_email(ouser_id) @ouser = Ouser.find(ouser_id) @email = @ouser.email @name = @ouser.name @title = "Great to have you #{@ouser.name}" @subject = "Welcome! #{@ouser.name}" @greeting = "You have made a brilliant decision to keep your digital legacy safe! " @info = "Your secrets can contain your social media login, financial accounts, life insurance, or a message to loved ones." @info2 = "Please make sure to check in so we know that everything is ok." # else # @title = "Cheers #{ouser.name}" # @subject = "Good to know that everything is still awesome #{ouser.name}!" # @greeting = "Welcome back #{ouser.name}. Your secrets are still safe!" # end mail to: @email, subject: @subject end def notify_email(title,description,inac_name,recipient) @title = title @description = description @inac_name = inac_name @recipient = recipient @greeting = "Hello, #{@recipient}" @greeting2 = @description mail to: @recipient, subject: "#{@inac_name} needs to check in." end def otp_email(ouser_id, otp_code) @ouser = Ouser.find(ouser_id) @email = @ouser.email @name = @ouser.name @title = "Your One time Password #{@ouser.name}" @subject = "OTP login! #{@ouser.name}" @greeting = "Your One time Password" @info = otp_code @info2 = "Please make sure to check in so we know that everything is ok." # else # @title = "Cheers #{ouser.name}" # @subject = "Good to know that everything is still awesome #{ouser.name}!" # @greeting = "Welcome back #{ouser.name}. Your secrets are still safe!" # end mail to: @email, subject: @subject end end <file_sep>/spec/controllers/sessions_controller_spec.rb require 'spec_helper' RSpec.describe SessionsController do before do request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:facebook] end describe "#create" do # "should successfully create a user" do # expect { # post :create, provider: :facebook # }.to change{ Ouser.count }.by(1) # end # t "should successfully create a session" do # expect(session[:ouser_id]).to be_nil # post :create, provider: :facebook # expect(session[:ouser_id]).not_to be_nil # nd # describe "#destroy" do # before do # post :create, provider: :facebook # end # # it "should clear the session" do # session[:ouser_id].should_not be_nil # delete :destroy # session[:ouser_id].should be_nil # end # # it "should redirect to the home page" do # delete :destroy # response.should redirect_to login_path # end # # nd end end <file_sep>/lib/tasks/recipient_clear.rake namespace :recipient do desc "Clear inactive recipients" task :clear => :environment do puts "********** Runing Clear Task *********" r = Recipient.all r.each do |recipient| unless recipient.posts.size > 0 puts "*** " + recipient.email + " Is not tied to any posts ***" recipient.destroy puts " ** " + recipient.email + " destroyed **" end end 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) # # Build a list to be used for users and posts # nums = ["first", "second", "third"] # # # # Build a list to be used for potential recipients # recv = ["one", "two", "three", "four", "five"] # # # Iterate over the list of items to be created for users and posts # nums.each do |num| # # # Create the user # u = Ouser.create(name: num + " user", email: num + "@gmail.com", last_update: Time.now ) # # # Loop again to then create the posts for this user # nums.each do |num| # # # Create the post # post = u.posts.create(title: num + " post", description: num + " description") # # # Grab two random recipients and loop them # recv.sample(2).each do |r| # # # Find the recipient (or create it if it doesn't exist) # recipient = Recipient.find_or_create_by(ouser_id: u.id, email: r + "@recipient.com") do |rec| # # # This internal block only runs when a recipient needs to be created # puts "Now creating recipient: " + r + " for user: " + u.name # rec.name = "Recipient " + r # # end # # # Associate the recipient with the post # post.recipients << recipient # # end # # end # # end <file_sep>/spec/factories/ousers.rb FactoryGirl.define do factory :ouser do provider "google" uid "109123503718938351526" name "<NAME>" email "<EMAIL>" latitude 34.0129909 longitude -118.4951238 end end<file_sep>/app/assets/javascripts/location.js function initialize() { if (/iPad|iPhone|iPod/.test(navigator.platform)){ alert("Please remember to have location services enabled to use my secrets on IOS") } console.log("init") var x = document.getElementById("location") function getLocation() { console.log("location running") if (navigator.geolocation) { console.log("in if nav") navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { var latlon = position.coords.latitude + "," + position.coords.longitude; console.log(latlon) // document.getElementById("location").innerHTML = latlon var id = $('#hidden')[0].innerHTML console.log(id) ajax(position.coords.latitude, position.coords.longitude, id); } function ajax(lat,long,id){ console.log("yes ajax"); // console.log("/ousers/"+id) console.log(lat,long,id) $.ajax({ type: "PUT", url: "ousers/"+id, data: { ouser: { latitude: lat, longitude: long}}, dataType: 'json', }) console.log("Ajaax succes") $( '#spinner' ).removeClass("fa-spin") $( '#spinner' ).removeClass("fa fa-refresh") $( '#spinner' ).addClass('fa fa-check') $( '#okbtn' ).addClass('ui green button') $( '.maptrigger' ).addClass('mapget') $('.last_update').html("you are up to date!") // $( '#okbtn i' ).html(' Your ok!') } getLocation() $( '.maptrigger' ).removeClass('mapget') } $(document).on("ready page:load", function(){ $( '#spinner' ).addClass("fa fa-refresh") $( '#okbtn i' ).html(" check in") $( '#okbtn' ).click(function() { $( '#okbtn i' ).html('') $( '#spinner' ).addClass("fa-spin") initialize() // console.log('get running') }); }) <file_sep>/app/assets/javascripts/map.js // // google.maps.event.addDomListener(window, 'load', initialize); // google.maps.event.addDomListener(window, 'page:load', initialize); // $('.posts.index').ready(function () { function checkAJAX(){ if ($( '.maptrigger' ).hasClass('mapget')){ console.log("success class") // initializeMAP(); location.reload(); } else{ setTimeout(checkAJAX, 500) } } checkAJAX(); function initializeMAP() { console.log("updated") var url = window.location.origin + window.location.pathname + ".json"; $.get(url, function(results){ // console.log(results) if (results[0] == undefined ){ } else{ var lat = results[0]["ouser"]["latitude"]; var long = results[0]["ouser"]["longitude"]; // console.log(post) console.log(lat,long) var myCenter = new google.maps.LatLng(lat,long); var mapProp = { center: myCenter, zoom:12, zoomControl:false, panControl:false, zoomControl: false, scaleControl: false, streetViewControl: false, overviewMapControl: false, MapTypeControl:false, disableDefaultUI: true, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap"),mapProp); google.maps.event.addDomListener(window, "resize", function() { var center = map.getCenter(); google.maps.event.trigger(map, "resize"); map.setCenter(center); }); google.maps.event.addListener(map, 'bounds_changed', function() { var bounds = map.getBounds(); }) var marker = new google.maps.Marker({ position:myCenter }); marker.setMap(map); google.maps.event.addListener(marker,'click', function() { map.setZoom(16); map.setCenter(marker.getPosition()); }); } } ); } google.maps.event.addDomListener(window, 'load', initializeMAP); }); <file_sep>/app/controllers/sessions_controller.rb class SessionsController < ApplicationController # include Sidekiq::Worker # after_commit :sendit, :on => :create require "active_model_otp" extend ActiveModel::Callbacks include ActiveModel::Validations include ActiveModel::OneTimePassword require 'pry' def new end def create @ouser = Ouser.from_omniauth(request.env['omniauth.auth']) # session[:ouser_id] = @ouser.id @ouser.otp_code UserMailer.delay.otp_email(@ouser.id, @ouser.otp_code ) # binding.pry redirect_to otp_path(@ouser.id) if @ouser.save if @ouser.created_at > 1.minute.ago UserMailer.delay.welcome_email(@ouser.id) # UserMailer.welcome_email(@ouser.id).deliver end end rescue flash[:notice] = "Please select the provider that you already have an account with ( i.e. if you chose Facebook use your Google account. )" redirect_to root_path end def destroy session.delete(:ouser_id) redirect_to login_path end def otp end def otpcreate @ouser = Ouser.find(params[:id]) @token = (params[:token].strip) # binding.pry if @ouser.authenticate_otp(@token, drift: 120) session[:ouser_id] = @ouser.id redirect_to posts_path else flash[:notice] = "Please double check the passcode" redirect_to otp_path end end end <file_sep>/readme.md [![Build Status](https://travis-ci.org/mmplisskin/my_secrets.svg?branch=travis)](https://travis-ci.org/mmplisskin/my_secrets) #My Secrets ###my Secrets is a digital locker that emails recipients when the user goes inactive Deployed at [my-secrets.co](http://www.my-secrets.co) <br /> ##Tech Used - Rails 4 - Postgress - Redis - JS/Jquery - Oauth - Sidekiq - Clockwork - Figaro - 12 factor #### Testing - Rspec controller and model spec - Capybara Test #### Deployment - ssl - clockwork scheduling - sidekiq #### layout - mobile compatible - materialize framework #### Email - queue emailing - secrets emails are sent out if a user goes inactive #### Background Processes - if a user does not check in for an extended period their secres are mailed to recipients and destroyed - recipients that are not tied to secrets are removed from db
505e638cd77e0fe7d9a8eaa91698a15637de63a0
[ "JavaScript", "Ruby", "Markdown" ]
27
Ruby
mmplisskin/my_secrets
af5244077af14969f1ca943a8764cf6fc38ace83
59184bd32aa0cce5f04543b4e9f047fb440ac5d9
refs/heads/master
<file_sep>from scrapy.item import Item, Field class GmapsItem(Item): name = Field() address = Field() phone = Field() list_site = Field()<file_sep>from scrapy.spider import Spider from scrapy.selector import Selector from tutorial.items import GmapsItem class GmapsSpider(Spider): name = "gmaps" allowed_domains = ["maps.google.com"] start_urls = [ "https://maps.google.com/maps?q=churches+in+stillwater+ok&output=classic&dg=ntvb" ] def parse(self, response): sel = Selector(response) sites = sel.xpath('//div[contains(@class, "text vcard indent block")]') items = [] for site in sites: item = GmapsItem() item['name'] = site.xpath('//span[contains(@class, "pp-place-title")] /span').extract() item['address'] = site.xpath('//span[contains(@class, "pp-headline-item pp-headline-address")] /span').extract() item['phone'] = site.xpath('//span[contains(@class, "telephone")]').extract() item['list_site'] = site.xpath('//span[contains(@class, "pp-headline-item pp-headline-authority-page")] /span').extract() items.append(item) return items<file_sep># Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html from scrapy.item import Item, Field class MantaItem(Item): # define the fields for your item here like: # name = Field() name = Field() address = Field() city = Field() state = Field() zipCode = Field() phone = Field() description = Field() <file_sep>from scrapy.spider import Spider class MantaSpider(Spider): name = "manta" allowed_domains = ["manta.com"] start_urls = [ "http://www.manta.com/search?pt=38.9525%2C-95.2756&search_location=Lawrence+KS&search=nonprofit+organizations", ] def parse(self, response): filename = response.url.split("/")[-2] open(filename, 'wb').write(response.body)<file_sep>=========================================== Service Identity Verification for pyOpenSSL =========================================== .. image:: https://travis-ci.org/hynek/service_identity.png?branch=master :target: https://travis-ci.org/hynek/service_identity .. image:: https://coveralls.io/repos/hynek/service_identity/badge.png :target: https://coveralls.io/r/hynek/service_identity WARNING ======= **This software is currently alpha and under review. Use it at your own peril.** Any part is subject to change, but feedback is very welcome! Pitch ===== service_identity aspires to give you all the tools you need for verifying whether a certificate is valid for the intended purposes. In the simplest case, this means *host name verification*. However, service_identity implements `RFC 6125`_ fully and plans to add other relevant RFCs too. Features ======== Present ------- - ``dNSName`` with fallback to ``CN`` (DNS-ID, aka host names, `RFC 6125`_). - ``uniformResourceIdentifier`` (URI-ID, `RFC 6125`_). - SRV-ID (`RFC 6125`_) Future ------ - ``xmppAddr`` (`RFC 3920`_). - ``iPAddress`` (`RFC 2818`_). - ``nameConstraints`` extensions (`RFC 3280`_). Usage ===== Verify a Hostname ----------------- The simplest, most common, and most important usage: .. code-block:: python from __future__ import absolute_import, division, print_function import socket from OpenSSL import SSL from service_identity import VerificationError from service_identity.pyopenssl import verify_hostname ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.set_verify(SSL.VERIFY_PEER, lambda conn, cert, errno, depth, ok: ok) ctx.set_default_verify_paths() hostname = u"twistedmatrix.com" conn = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM)) conn.connect((hostname, 443)) try: conn.do_handshake() verify_hostname(conn, hostname) # Do your super-secure stuff here. except SSL.Error as e: print("TLS Handshake failed: {0!r}.".format(e.args[0])) except VerificationError: print("Presented certificate is not valid for {0}.".format(hostname)) finally: conn.shutdown() conn.close() Requirements ============ Python 2.6, 2.7, 3.2, 3.3, and 3.4 as well as PyPy are supported. Additionally, the following PyPI modules are required: - pyOpenSSL_ ``>= 0.12`` (``0.14`` strongly suggested) - pyasn1_ - pyasn1-modules_ Optionally, idna_ can be used for `internationalized domain names`_ (IDN), aka non-ASCII domains. Please note, that idna is not available for Python 3.2 and is required because Python's stdlib support is outdated_. .. _Twisted: https://twistedmatrix.com/ .. _`RFC 2818`: http://www.rfc-editor.org/rfc/rfc2818.txt .. _`RFC 3280`: http://tools.ietf.org/search/rfc3280#section-4.2.1.11 .. _`RFC 3920`: http://www.rfc-editor.org/rfc/rfc3920.txt .. _`RFC 6125`: http://www.rfc-editor.org/info/rfc6125 .. _`internationalized domain names`: http://en.wikipedia.org/wiki/Internationalized_domain_name .. _idna: https://pypi.python.org/pypi/idna/ .. _outdated: http://bugs.python.org/issue17305 .. _pyOpenSSL: https://pypi.python.org/pypi/pyOpenSSL/ .. _pyasn1-modules: https://pypi.python.org/pypi/pyasn1-modules/ .. _pyasn1: https://pypi.python.org/pypi/pyasn1/ .. _pydoctor: https://pypi.python.org/pypi/pydoctor/ .. _trial: http://twistedmatrix.com/documents/current/core/howto/testing.html .. :changelog: History ======= 0.2.0 (2014-04-06) ------------------ This release contains multiple backward-incompatible changes. - Refactor into a multi-module package. Most notably, ``verify_hostname`` and ``extract_ids`` live in the ``service_identity.pyopenssl`` module now. - ``verify_hostname`` now takes an ``OpenSSL.SSL.Connection`` for the first argument. - Less false positives in IP address detection. - Officially support Python 3.4 too. - More strict checks for URI_IDs. 0.1.0 (2014-03-03) ------------------ - Initial release. Authors ======= service_identity is currently maintained by Hynek Schlawack. If you think you've found a security-relevant bug, please contact me privately and ideally encrypt your message using PGP_. I will then work with you on a responsible resolution. You can find my contact information and PGP data on my homepage_. Contributors ------------ The following wonderful people contributed directly or indirectly to this project: - `<NAME> <https://github.com/public>`_ - `Glyph <https://twitter.com/glyph>`_ - `<NAME> <https://github.com/reaperhulk>`_ Please add yourself here alphabetically when you submit your first pull request. .. _PGP: http://www.gnupg.org/ .. _homepage: https://hynek.me/about/ <file_sep>from scrapy.spider import Spider class Bizjournal(Spider): name = "bizjournal" allowed_domains = ["bizjournals.com"] start_urls = [ "http://www.bizjournals.com/profiles/company/us/?state=MO" ] def parse(self, response): filename = response.url.split("/")[-2] open(filename, 'wb').write(response.body) <file_sep>#!/home/action/leadscrape/scrapy/bin/python from scrapy.cmdline import execute execute() <file_sep>scrapy-test =========== Learning How to Use Scrapy Testing with YP.com <file_sep>from scrapy.item import Item, Field class YouthsportskcItem(Item): name = Field() category = Field() address = Field() phone = Field() website = Field() email = Field() <file_sep># Scrapy settings for yp project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'yp' SPIDER_MODULES = ['yp.spiders'] NEWSPIDER_MODULE = 'yp.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent DOWNLOAD_DELAY = 10 USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22 AlexaToolbar/alxg-3.1"<file_sep># Scrapy settings for youthsportskc project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'youthsportskc' SPIDER_MODULES = ['youthsportskc.spiders'] NEWSPIDER_MODULE = 'youthsportskc.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent # Crawl responsibly by identifying yourself (and your website) on the user-agent DOWNLOAD_DELAY = 10 USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22 AlexaToolbar/alxg-3.1" <file_sep># Scrapy settings for ymca project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'ymca' SPIDER_MODULES = ['ymca.spiders'] NEWSPIDER_MODULE = 'ymca.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'ymca (+http://www.yourdomain.com)' <file_sep>from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from youthsportskc.items import YouthsportskcItem class YouthsportskcSpider(CrawlSpider): name = "youthsportskc" allowed_domains = ["youthsportskc.com"] start_urls = [ 'http://youthsportskc.com/listing/guide/football', 'http://youthsportskc.com/listing/guide/gymnastics', 'http://youthsportskc.com/listing/guide/misc', 'http://youthsportskc.com/listing/guide/tennis', 'http://youthsportskc.com/listing/guide/youth-basketball', 'http://youthsportskc.com/listing/guide/fastpitch-softball', 'http://youthsportskc.com/listing/guide/girls-volleyball', 'http://youthsportskc.com/listing/guide/lacrosse', 'http://youthsportskc.com/listing/guide/soccer', 'http://youthsportskc.com/listing/guide/wrestling', 'http://youthsportskc.com/listing/guide/boxing', 'http://youthsportskc.com/listing/guide/flag-football', 'http://youthsportskc.com/listing/guide/golf', 'http://youthsportskc.com/listing/guide/martial-arts', 'http://youthsportskc.com/listing/guide/swimming', ] rules = (Rule (SgmlLinkExtractor(restrict_xpaths=('/html/body/div[5]/div[1]/div[3]/ul[2]/li',)) , callback="parse_item", follow= True), ) def parse_start_url(self, response): return self.parse_item(response) def parse_item(self, response): sel = Selector(response) orgs = sel.xpath('//div[contains(@id,"listing_summary_")]') items = [] for orgs in orgs: item = YouthsportskcItem() item['name'] = orgs.xpath('.//div[@class="title"]//h3//a/text()').extract() item['category'] = orgs.xpath('.//div[@class="title"]//p//a/text()').extract() item['address'] = orgs.xpath('.//div[@class="info"]/address//span/text()').extract() item['phone'] = orgs.xpath('.//span[contains(@id,"phoneNumber")]/text()').extract() items.append(item) return items <file_sep>from scrapy.item import Item, Field class YpItem(Item): name = Field() streetAddress = Field() addressCity = Field() addressState = Field() addressZip = Field() phone = Field() category = Field()<file_sep>from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from yp.items import YpItem class YpSpider(CrawlSpider): name = "yp" allowed_domains = ["yellowpages.com"] start_urls = [ 'http://www.yellowpages.com/tempe-az/churches' ] rules = (Rule (SgmlLinkExtractor(restrict_xpaths=('//div[@class="pagination"]//li',)) , callback="parse_item", follow= True), ) def parse_start_url(self, response): return self.parse_item(response) def parse_item(self, response): sel = Selector(response) orgs = sel.xpath('//div[@class="info"]') items = [] for orgs in orgs: item = YpItem() item['name'] = orgs.xpath('.//span[@itemprop="name"]/text()').extract() item['streetAddress'] = orgs.xpath('.//span[@itemprop="streetAddress"]/text()').extract() item['addressCity'] = orgs.xpath('.//span[@itemprop="addressLocality"]/text()').extract() item['addressState'] = orgs.xpath('.//span[@itemprop="addressRegion"]/text()').extract() item['addressZip'] = orgs.xpath('.//span[@itemprop="postalCode"]/text()').extract() item['phone'] = orgs.xpath('.//li[@itemprop="telephone"]/text()').extract() item['category'] = orgs.xpath('.//ul[@class="categories"]//li//text()').extract() items.append(item) return items
b9175bc6a42db0aaf3b8ae1abcdbd29c4043b003
[ "Markdown", "Python", "reStructuredText" ]
15
Python
hsd315/scrapy-test
2de6b553dd1a4e191a9f467815ec5c8a56291289
2fddef8ae5cec5e88787c54161c6f412ec54ced4
refs/heads/master
<file_sep>import { Example } from './example.js' const example = new Example()<file_sep>class Example { constructor() { console.log('hello world') } } export { Example }<file_sep># Usage 1. Run the following: ```shell npm install npm run build ``` 2. Navigate to: [chrome://extensions/](chrome://extensions/) > "Load Unpacked" 3. Click on "Inspect views `service worker`" 4. Check for `hello world` console output
bbac161491669e5dda7a9080be1e756e7639f53b
[ "JavaScript", "Markdown" ]
3
JavaScript
tbrockman/webpack-manifest-v3-example
84ec894f54b7016787a492568ca0bcf90e83c729
8d157d0c1ff9377c88ac8c9290313979bad730d0
refs/heads/main
<repo_name>chakshusman/Prediction-System-for-Heart-Disorder<file_sep>/test.py import pandas as pd import numpy as np import matplotlib.pyplot as plt col_names=['id','ccf','age','sex','painloc','painexer','relrest','pncaden','cp','trestbps','htn','chol','smoke','cigs','years','fbs','dm','famhist','restecg','ekgmo','ekgday','ekgyr','dig','prop','nitr','pro','diuretic','proto','thaldur','thaltime','met','thalach','thalrest','tpeakbps','tpeakbpd','dummy','trestbpd','exang','xhypo','oldpeak','slope','rldv5','rldv5e','ca','restckm','exerckm','restef','restwm','exeref','exerwm','thal','thalsev','thalpul','earlobe','cmo','cday','cyr','num','lmt','ladprox','laddist','diag','cxmain','ramus','om1','om2','rcaprox','rcadist','lvx1','lvx2','lvx3','lvx4','lvf','cathef','junk','name'] dataset = pd.read_csv(r'D:\Data/data.csv', header=None, names=col_names) graph2_selection=['age','sex','cp','trestbps', 'htn','chol','cigs','years','fbs','famhist','restecg','ekgmo','ekgday','ekgyr','dig','nitr','pro','diuretic','proto','thaldur','thaltime','met','thalach','thalrest', 'tpeakbps', 'tpeakbpd', 'dummy','trestbpd', 'exang','xhypo','oldpeak','slope','rldv5e','ca','thal','cmo','cday','cyr','lmt', 'ladprox','laddist','cxmain','om1','rcaprox','rcadist','lvx3','lvx4','lvf'] X = dataset[graph2_selection].values Y = dataset['num'].values from sklearn.preprocessing import Imputer imputer = Imputer(missing_values=-9, strategy='median', axis=0) imputer = imputer.fit(X) X = imputer.transform(X) 18 X = np.append(arr=np.ones((282, 1)).astype(int), values=X, axis=1) import statsmodels.formula.api as sm def backwardElimination(x, sl): #backward elemination\n", numVars = len(x[0]) for i in range(0, numVars): regressor_OLS = sm.OLS(Y, x).fit() maxVar = max(regressor_OLS.pvalues).astype(float) if maxVar > sl: for j in range(0, numVars - i): if (regressor_OLS.pvalues[j].astype(float) == maxVar): x = np.delete(x, j, 1) regressor_OLS.summary() print(regressor_OLS.summary()) return x SL = 0.01 #significance level\n", X_opt = X X_Modeled = backwardElimination(X_opt, SL) from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X_Modeled, Y, random_state=0, test_size=0.2) from sklearn.neighbors import KNeighborsClassifier k_nn_classifier = KNeighborsClassifier(n_neighbors=1, metric='minkowski', p=1, algorithm='ball_tree', leaf_size=30) k_nn_classifier.fit(X_train, Y_train) k_nn_y_pred = k_nn_classifier.predict(X_test) #predicted y values for X_train\n", objects = ('0', '1', '2', '3', '4') y_pos = np.arange(len(objects)) plt.ylabel('Disease Class') plt.xlabel('Test Data') plt.plot(Y_test, color='red', label='Predicted Values') plt.plot(k_nn_classifier.predict(X_test), label='Actual Values') plt.yticks(y_pos, objects) plt.legend() plt.show() from sklearn.tree import DecisionTreeClassifier; dt = DecisionTreeClassifier(criterion='gini', splitter='best') dt.fit(X_train, Y_train) dt_y_pred = dt.predict(X_test) objects = ('0', '1', '2', '3', '4') y_pos = np.arange(len(objects)) plt.ylabel('Disease Class') plt.xlabel('Test Data') plt.plot(Y_test, color='red', label='Predicted Values') plt.plot(dt.predict(X_test), label='Actual Values') plt.yticks(y_pos, objects) plt.legend() plt.show() from sklearn.ensemble import RandomForestClassifier; rf = RandomForestClassifier(n_estimators=10, criterion='gini') rf.fit(X_train, Y_train) rf_y_pred = rf.predict(X_test) objects = ('0', '1', '2', '3', '4') y_pos = np.arange(len(objects)) plt.ylabel('Disease Class') plt.xlabel('Test Data') plt.plot(Y_test, color='red', label='Predicted Values') plt.plot(rf.predict(X_test), label='Actual Values') plt.yticks(y_pos, objects) plt.legend() plt.show() from sklearn import metrics k_nn_acc = metrics.accuracy_score(Y_test, k_nn_y_pred) dt_acc = metrics.accuracy_score(Y_test, dt_y_pred) rf_acc = metrics.accuracy_score(Y_test, rf_y_pred) #accuracy\n", print(k_nn_acc) print(dt_acc) print(rf_acc)<file_sep>/README.md # Heart-Disease-Prediction The purpose of this project is to find out what are the best predictors among 76 present predictors. This will be done using feature scaling, algorithms such as backward elimination and forward selection. Using dataset provided via UCI machine learning repository and using K-NN, Decision Tree and Random Forest algorithms We will find out which algorithm provides best accuracy in least amount of time.
7fa2030a851db4591f0ebf0c884a3737e2b883c3
[ "Markdown", "Python" ]
2
Python
chakshusman/Prediction-System-for-Heart-Disorder
7a5d4b33aa088aa5c7e3f6b8697b0f8079544450
59311269fed4ee51cd631608c68dd0b4f1e0e152
refs/heads/master
<repo_name>pranshul97/WebApp-Testing<file_sep>/src/app/mayank-component/mayank-component.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-mayank-component', templateUrl: './mayank-component.component.html', styleUrls: ['./mayank-component.component.css'] }) export class MayankComponentComponent implements OnInit { constructor() { } ngOnInit(): void { } }
6ede8164837e5f0a75c338ab5f9d24e67479c8f6
[ "TypeScript" ]
1
TypeScript
pranshul97/WebApp-Testing
68c5c8b1f14ca988d65f5ad3bc825fe12570f24e
28c84b4cee2f097412a3a5828a57e00502435420
refs/heads/master
<file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |05/05/2018|1.0|Criação do Documento|<NAME>| |05/05/2018|1.1|Adição NFR US53|<NAME>| |06/05/2018|1.2|Adição de NFR US48|<NAME>| |06/05/2018|1.3|Adição de NFR US52|Amanda Pires| |06/05/2018|1.4|Adição de NFR US51|<NAME>| |06/05/2018|1.4|Adição de NFR US49|<NAME>| |06/05/2018|1.5|Adição de NFR US50|<NAME>| |07/05/2018|1.6|Adição de versão 1.1 do NFR US48|<NAME>| |07/05/2018|1.7|Adição de versão 1.1 do NFR US52|Amanda Pires| |07/05/2018|1.8|Adição de versão 1.1 do NFR US49|<NAME>| |07/05/2018|1.9|Adição de versão 1.1 do NFR US51|<NAME>| |07/05/2018|2.0|Adição de versão 1.1 do NFR US50|<NAME>| |27/05/2018|2.1|Adição de legendas aos NRFs e alterando definição e escopo|Amanda Pires |27/05/2018|2.2|Adição do NFR US54|Amanda Pires <h1>Introdução</h1> ## 1.1 Finalidade Este documento tem como finalidade apresentar o NFRs da plataforma [Twich.tv](https://www.twitch.tv/). ## 1.2 Definição NFR é um framework conceitual orientado aos requisitos não funcionais, os quais são considerados “cidadãos” de primeira ordem. O modelo utilizado no NFR Framework é chamado Softgoal Interdependency Graph (SIG). O SIG é abstraído em um diagrama formado por Softgoal (requisito de qualidade), argumentação, impactos, legenda e operacionalização. ## 1.3 Escopo Nessa conjuntura, serão construídos NFRs dos seguintes requisitos não funcionais: * Usabilidade * Performance * Segurança * Portabilidade * Disponibilidade <h1>NFRs</h1> ### US48 - Usabilidade [NFR Usabilidade 1.0](images/nfr/NFR_US48.png) ![NFR Usabilidade 1.1](images/nfr/NFR-Usabilidade-1.1.png) ### `Legenda` ![legenda-usabilidade](images/legenda-nfr/legenda-usabilidade.jpg) ### US49 - Performance para o Usuário <a href="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_NFR/NFR_US49.jpg">NFR Performance Tráfego 1.0</a> <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_NFR/NFR-PerformanceTrafego.jpg" width=900px> ### `Legenda` ![legenda-performance](images/legenda-nfr/legenda-performance-usuario.png) ### US50 - Segurança <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Imagens_NFR/NFR_US50.png">NFR Segurança em Transações 1.0</a> <img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Imagens_NFR/NFR_US50_1-1.jpg" width=900px> ### `Legenda` ![legenda-seguranca](images/legenda-nfr/legenda-seguranca.png) ### US51- Performance para a Stream <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_NFR/NFR_US51.jpg" width=900px> ### `Legenda` ![legenda-usabilidade](images/legenda-nfr/legenda-performance-stream.png) ### US52 - Portabilidade [NFR US52 1.0](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_NFR/NFR_US52.jpg) <img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Imagens_NFR/NRF_US52_1.1.jpg?raw=true" width=900px> ### `Legenda` ![legenda-usabilidade](images/legenda-nfr/legenda-portabilidade.png) ### US53 - Disponibilidade [NFR US53 1.0](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_NFR/NFR_53.png) <img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Imagens_NFR/NFR_US53.png?raw=true" width=900px> ### `Legenda` ![legenda-usabilidade](images/legenda-nfr/legenda-disponibilidade.png) ### US54 - Confiabilidade ![NFR Confiabilidade 1.1](images/nfr/confiabilidade.png) ### `Legenda` ![legenda-usabilidade](images/legenda-nfr/legenda-confiabilidade.png) <file_sep># UC06 - Compra de Bits ### [Diagrama de caso de uso](Diagrama-comprar-bits) ## Descrição * Esse caso de uso descreve como comprar Bits. ## Atores * Usuário ## Pré-condições * O usuário deve ter acesso à internet * O usuário deve estar logado ## Fluxo de Eventos ### Fluxo Principal * 1. O usuário abre uma stream desejada * 2. O usuário seleciona a opção ```Adquira Bits``` na parte superior da tela * 3. O usuário seleciona a quantidade de bits desejada * 4. O usuário é seleciona a forma de pagamento [FE01] * 5. O usuário preenche as informações de pagamento * 6. O usuário finaliza a compra * 7. O caso se encerra ### Fluxos Alternativos * Não se Aplica ### Fluxo de Exceção #### FE01 - O usuário não possui conta nas plataformas de pagamento * 1. O usuário seleciona a forma de pagamento * 2. O usuário não possui conta na plataforma de pagamento selecionada * 3. O usuário não consegue completar a conta * 4. O caso de uso é encerrado incompleto ## Pós-condição * O usuário possui a quantidade de bits adquirida<file_sep>## Diagrama do UC11 - [Chat](Group-Chat) de Voz <img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/UC11.png" width=900px> ### [Especificação de Caso de uso](Chat-de-voz)<file_sep>#!/bin/bash read -p "Enter Lexico.md dir: " dir file="Léxico.md" lexer_files=$(grep -E -o "\[(.+?)\]" $dir$file | sed 's/\[\|\]//g' | sed 's/$/.md/g' | sed 's/ /-/g') echo -e "Checking Lexicos...\n" sleep .7 for i in "$lexer_files" do echo -e "1- Verifying Pattern\n" echo -e "\n\n\n" grep --color "Sinônimos" -A 1 $dir$i read -p "Press enter to continue" echo -e "\n\n\n" grep --color "Noção" -A 1 $dir$i read -p "Press enter to continue" echo -e "\n\n\n" grep --color "Impacto" -A 1 $dir$i read -p "Press enter to continue" done <file_sep><img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/UC16.png" width=900px> ### [Especificação de Caso de Uso](Banir-Viewer)<file_sep>## Cheer **Sinônimos:** * Torcer **Noção:** * Utiliza [bits](Bits) da [Twitch](Twitch) para enviar um incentivo bonificado ao [streamer](Streamer). **Impacto:** * O [Viewer](Viewer) enviou um cheer ao [Streamer](Streamer). * [Streamer](Streamer) recebeu varios [bits](Bits) por meio dos cheers.<file_sep>**Sinônimos:** * Criativo * Espaço criativo **Noção:** * Espaço no site destinado a conteúdo categorizado como criativo, como desenhos, artesanato, *photoshop*, etc. **Impacto:** * O espaço criativo é onde o usuário irá encontrar conteúdos alternativos aos de jogos e que remetem a uma atividade de maior criatividade.<file_sep># Iniciar uma [transmissão](Stream) ## Objetivo * Iniciar uma livestream ## Contexto * O usuário está em sua área de trabalho e quer iniciar sua stream na Twitch ## Ator(es) * [Streamer](Streamer) ## Recursos * Software de Captura * Dispositivo a ser capturado * Conta na Twitch * Token do [Streamer](Streamer) ## Exceções * O [Usuário](User) não possui acesso à internet * Aquela conta da Twitch já possui uma livestream naquele momento ## Episódios * Um usuário gostaria de começar a se streamar jogando * O usuário faz o download de uma plataforma de captura * O usuário configura o cenário da plataforma * O usuário pega sua token de transmissão em sua conta twitch e a coloca no software * O usuário aperta o botão de inicio de transmissão do software * A stream é iniciada na Twitch<file_sep>* Checklist de Inspeção da Pré Rastreabilidade * Inspetores: <NAME> * Data: 08/06/2018 |Item de Inspeção|Rich Picture(Pré Rastreabilidade)| |------|-------| Questão 1|Os Atores estão bem definidos?| Resposta| Sim| Modificações| Questão 2|O foco do está no centro?| Resposta| Sim| Modificações| Questão 3|As palavras estão legíveis?| Resposta| Não| Modificações| Defeito|Geral está muito claro e difícil de ler Questão 4|Houve separação de desenhos?| Resposta| Sim| Modificações| Questão 5|Existe interação entre atores?| Resposta| Sim| Modificações| Questão 6|Existe aspectos que afetam em requisitos por atores que não estão sendo o foco?| Resposta|Sim| Modificações| Questão 7|Os Rich Pictures demonstra requisitos?| Resposta| Sim| Modificações|<file_sep>## Diagrama de Adição de Amigo <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Casos_de_uso/Adicionar%20amigos.png" width=900px> ### [Especificação de Caso de Uso](Adição-de-amigo) <file_sep>**Sinônimos:** * Banir * Expulsar * Bloquear **Noção:** * Proibir o acesso ao conteúdo da pessoa que realizou o ato, por parte da pessoa que sofreu a proibição. **Impacto:** * [Viewer](Viewer) incômodo foi banido do [chat](Group-Chat). * O [Moderador](Moderador) bania todos que quebravam as regras do [chat](Group-Chat). <file_sep>## Emotes **Sinônimos:** * Nenhum **Noção:** * Pequenos ícones ou fotos que podem ser enviados no chat. **Impacto:** * Emotes são vastamente utilizados pelos [viewers](Viewer) para expressar sentimentos e/ou aumentar a interatividade no chat.<file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |15/05/2018|1.0|Criação do Documento |<NAME>| |15/05/2018|1.1|Adição dos atores e do tópico explicando o documento |<NAME>| |15/05/2018|1.2|Adição do documento completo e formatação do mesmo|<NAME>| |09/06/2018|1.3|Revisão|<NAME>| ## O Documento Este artefato conta com a especificação textual dos goals, hardgoals, tasks e softgoals levantados de forma prévia à criação dos diagramas utilizando o framework iStar. O documento foi elabora por toda a equipe, de forma incremental, de modo que, a elaboração dos diagramas fosse facilitada e possuísse maior qualidade. Este documento não é diretamente requisitado pela metodologia, entretanto, por ter sido um artefato produzido pela equipe, estará aqui armazenado. O conteúdo aqui localizado não corresponde ao conteúdo final que foi implementado nos diagramas ## Especificação Textual i* ### Atores * Agente Usuário - Papel [Viewer](Viewer) - Papel [Streamer](Streamer) * Agente Patrocinador - Posição Patrocinador Twitch - Posição Patrocinador [Streamer](Streamer) * Agente Plataforma Twitch - Desenvolvimento - Financeiro - Marketing ### Relações * [Viewer](Viewer) e [Streamer](Streamer) * Patrocinador e [Streamer](Streamer) * Patrocinador e [Viewer](Viewer) * Patrocinador e Twitch * Twitch e Usuário * Twitch e [Streamer](Streamer) ### Hardgoals, Tasks, Softgoals e Resources #### Hardgoals [Viewer](Viewer) e [Streamer](Streamer) * Stream seja visualizada - Buscar stream - Selecionar [Stream](Stream) * Doar Bits - Seja possível enviar bits ao longo de uma stream - [Condição] O [Streamer](Streamer) precisa ser parceiro da Twitcht * Ocorra Comunicação entre as partes - Seja possível enviar mensagens privadas - Seja possível se comunicar através de mensagens de doação - Seja possível se comunicar através do [chat](Group-Chat) do canal * Acompanhar canal - Seguir Canal - Se inscrever em canal #### Hardgoals Patrocinador e [Streamer](Streamer) * [Streamer](Streamer) Seja Patrocinado - O patrocinado receba exclusividades - O patrocinado receba divulgação - Patrocinador seja divulgado - O produto do patrocinador seja divulgado - Os serviços do patrocinador sejam divulgados * Stream seja monetizada pela publicidade * [Recurso]Capital #### Hardgoals Patrocinador e [Viewer](Viewer) * Anúncios sejam transmitidos nas transmissões - Espectador assiste anúncios e transmissor recebe com a audiência nos anúncios #### Hardgoals Patrocinador e Twitch * Stream seja monetizada com publicidade - Inserir publicidade em stream de parceiro - [Recurso] Visualizações na stream - Receber capital por publicar anúncios - [Recurso]Capital #### Hardgoals Twitch e [Viewer](Viewer) * Usuário seja cadastrado * Dashboard seja disponibilizado - Ter acesso a lives - Poder instalar extensão - Adicionar evento - Fazer upload de imagem - Inserir dados do evento - Validar dados * Subscriptions sejam visualizadas - Ter acesso as subscriptions - Listar subscriptions * Pagamentos sejam disponibilizados - Adicionar forma de pagamento - Visualizar histórico de pagamento * Pesquisa seja realizada - Pesquisar por Jogos - Pesquisar por Comunidades - Pesquisar por Comunidades criativas - Pesquisar por canais - Ordenar pesquisa por relevância - Ordenar pesquisa por popularidade #### Hardgoals Twitch e Usuário * Conta na Twitch seja gerenciada - Cadastrar nova conta - Inserir dados válidos - Atualizar dados da conta - Desativar conta * Login seja efetuado - Inserir dados válidos * Twitch prime seja ativado - Pagamento * Bits sejam obtidos - Seja possível comprar um determinado número de bits #### Hardgoals Twitch -- [Streamer](Streamer) * [Streamer](Streamer) seja efetuado como Twitch Partner - O usuário seja regular, transmitindo ao menos 3x por semana - O usuário aplicante tenha um Público e [chat](Group-Chat) crescente - Conteúdo transmitido seja adequado às regras de conduta, Termos de serviço e Diretrizes DMCA da Twitch * Plataforma supra as necessidades de [streaming](Streaming) - A twitch consiga transmitir conteúdo multimídia em tempo real - A twitch disponibilize um meio de interação para o [streamer](Streamer) - A twitch disponibilize alguma forma de monetização para o [streamer](Streamer) - A twitch disponibilize controle sobre a transmissão para o usuário, em tempo real ### Strategic Rationale #### Usúario[Geral] * Cadastro seja realizado - Inserir Dados[Dados gerais] * Perfil seja acessado - Acessar configurações - Sair das configurações * Dados seja atualizados[Dados do usuário] - Atualizar dados - Atualizar foto do perfil - Atualizar faixa do perfil - Atualizar denifinições do perfil - Cancelar conta #### [Streamer](Streamer) * Stream seja inicializada - Iniciar uma stream * Stream key seja adquirida - Usuário [Streamer](Streamer) possua conta ativa na twitch - Stream key seja inicializada em software de captura - Usuário possua software de captura ou qualquer outro método de upload para a twitch em seu dispositivo o qual será realizada a captura #### [Viewer](Viewer) * [Viewer](Viewer) participe ativamente da stream - [Viewer](Viewer) participe do (chat)[Group-Chat] #### Twitch * Seja capaz de hospedar stream - Hospedar stream - Transmitir multimídia ao vivo * Criar coleções de stream por um tempo limitado * Seja capaz enviar notificações em tempo real para usuários - Enviar notificações aos usuários - Enviar solicitações de amizade * Enviar sussurros - Enviar notificações de mensagens - Enviar notificações de publicações * Seja capaz de estabelecer comunicação entre usuários - Estabelecer comunicação entre usuários * Criar um [chat](Group-Chat) de voz - Enviar mensagens * Possuir capacidade de até 10 milhões de acessos simultâneos [Softgoal] * [SoftGoal]Lidar com grande número de requisicoes * [SoftGoal]Ter segurança * Serviço de [Add-ons](Mods) seja disponibilizado - Seja possível adicionar [add-ons](Mods) à plataforma - Seja possível remover [add-ons](Mods) da plataforma - Seja possível baixar [add-ons](Mods) da plataforma - Seja possível instalar [add-ons](Mods) diretamente pela plataforma - Seja possível filtrar [add-ons](Mods) mostrados pela plataforma - Seja possível sincronizar [add-ons](Mods) automaticamente pela plataforma * Serviço de [Chat](Group-Chat) de Voz seja disponibilizado - Seja possível iniciar uma sala de chamada - Seja possível criar um servidor de chamada - Seja possível alterar a chamada de voz para vídeo chamada - Seja possível convidar pessoas para a chamada - Seja possível expulsar pessoas da chamada - [Softgoal] Chamadas de qualidade <file_sep>* Respostas Checklist Elicitação * Inspetores: <NAME> & <NAME> * Data: 25/05/2018 #### 1. Plano de Elicitação de Requisitos |Item de Inspeção|Plano de Elicitação de Requisitos| |------|-------| Questões|1. O documento está anexado ao projeto?| Resposta Filipe|Não| Resposta Amanda|Não| Questões|2. O plano informa as técnicas que serão utilizadas no projeto?| Resposta Filipe|Não| Resposta Amanda|Não| Questões|3. Existe uma breve explicação do que é cada técnica? Resposta Filipe|Não| Resposta Amanda|Não| #### 2. Questionário |Item de Inspeção|Questionário| |------|-------| Questões|1. O documento está anexado ao projeto?| Resposta Filipe|Sim| Resposta Amanda|Sim| Questões|2. Todas as perguntas levantadas no questionário foram inseridas no documento?| Resposta Filipe|Sim| Resposta Amanda|Sim| Questões|3. A ferramenta utilizada para realizar o questionário está sendo citada no documento? Resposta Filipe|Não| Resposta Amanda|Não| Questões|4. O questionário possui clareza nas suas questões?| Resposta Filipe|Sim| Resposta Amanda|Sim| Questões|5. É possível identificar a porcentagem e quantidade de pessoas participantes?| Resposta Filipe|Sim| Resposta Amanda|Sim| #### 3. Storytelling |Item de Inspeção|Storytelling| |------|-------| Questões|1. Existe uma breve explicação da técnica?| Resposta Filipe|Não| Resposta Amanda|Não| Questões|2. O objetivo deixa claro o que é almejado alcançar com a técnica?| Resposta Filipe|Não| Resposta Amanda|Sim| Questões|3. A história contada condiz com a realidade? Resposta Filipe|Sim| Resposta Amanda|Sim| Questões|4. É possível elicitar requisitos baseados na história contada?| Resposta Filipe|Sim| Resposta Amanda|Sim| #### 4. Análise Protocolo + Observação Participativa |Item de Inspeção|Observação Participativa| |------|-------| Questões|1. Existe uma breve explicação da técnica?| Resposta Filipe|Não| Resposta Amanda|Não| Questões|2. O objetivo deixa claro o que é almejado alcançar com a técnica?| Resposta Filipe|Não| Resposta Amanda|Sim| Questões|3. O documento abrange todo o público alvo da [Twitch](Twitch)? Resposta Filipe|Sim| Resposta Amanda|Sim| Questões|4. O documento levou a um maior entendimento do funcionamento da plataforma?| Resposta Filipe|Sim| Resposta Amanda|Sim| #### 5. Introspecção |Item de Inspeção|Introspecção| |------|-------| Questões|1. Existe uma breve explicação da técnica? Resposta Filipe|Não| Resposta Amanda|Não| Questões|2. O objetivo deixa claro o que é almejado alcançar com a técnica?| Resposta Filipe|Não| Resposta Amanda|Não| Questões|3. O método utilizado para se levantar as histórias de usuário está sendo citado?| Resposta Filipe|Não| Resposta Amanda|Não <file_sep># Cenário 011 - Configurar pagamento ## Título * [Usuário](User) configurando sua forma de pagamento ## Objetivo * [Usuário](User) configurar sua forma de pagamento para não ter que ficar configurando toda vez ao realizar alguma compra ## Contexto * [Usuário](User) seleciona alguma compra (Twitch Prime, Subscribe) ## Ator(es) * User ## Recursos * Conta na Twitch * Dispositivo eletrônico conectado à internet ## Exceções * Não possuir conta na Twitch * Dispositivo eletrônico não estar conectado à internet ## Episódios * [Usuário](User) seleciona uma compra (Subscribe, Twitch Prime) * [Usuário](User) seleciona o período da assinatura * [Usuário](User) seleciona a forma de pagamento * [Usuário](User) configura a forma de pagamento <file_sep> **Sinônimos:** * Usuário Premium **Noção:** * Usuário que possui o Serviço da [Twitch Prime](Twitch-Prime). **Impacto:** * O Usuário Prime renovou sua assinatura da [Twitch-Prime](Twitch-Prime) * Usuário Prime utilizou sua [inscrição](Subscribe) gratuíta. * O Usuário Prime tem acesso à [chats](Group-Chat) que tiverem restrições aplicadas.<file_sep># UC19 - Criação de Vídeo * [Diagrama de Caso de Uso](Diagrama-Criar-Video) ## Descrição * Este caso de uso descreve como criar vídeos na plataforma. ## Atores * Usuário ## Pré-condições * O usuário deverá ter acesso a internet * O usuário deverá ter um arquivo multimídia a ser subido para a plataforma * O video não deve ferir as guidelines da twitch ## Fluxo de Eventos ### Fluxo Principal * 1. O usuário seleciona o dropdown do usuário * 2. O usuário seleciona a opção de ```Estúdio de Vídeo``` * 3. O usuário clica na secção de upload * 4. O usuário arrasta ou seleciona o vídeo na pasta [FE01] * 5. O usuário clica em ```agende uma premiere``` * 6. O usuário preenche as informações solicitadas * 7. O vídeo é criado na plataforma * 8. O caso de uso é encerrado ### Fluxos Alternativos * Não se aplica ### Fluxo de Exceção #### FE01 - O usuário não possui o email verificado * 1. O usuário realiza a etapa do item 4 * 2. O usuário recebe uma notificação de que não é possível subir o vídeo por não possuir email verificado * 3. O caso de uso é encerrado ## Pós-condição * O vídeo agora está disponível na plataforma<file_sep>**Sinônimos:** * Bate-papo * [Chat](Group-Chat) em grupo * [Chat](Group-Chat) da stream **Noção:** * Sala privada de bate-papo onde usuários do [Twitch](Twitch) se integragem por meio de mensagens. Este recurso pode ser utilizado por qualquer usuário do [Twitch](Twitch), desde que esteja logado. **Impacto:** * Os [espectadores](Viewer) interagem com o [streamer](streamer) através do [Chat](Group-Chat) * Ao se [inscrever](Subscribe) o [usuário](User) ganha emoticons para usar no [Chat](Group-Chat) da Stream<file_sep># UC03 - Criação de Conta ### [Diagrama de caso de uso](Diagrama-criar-conta) ## Descrição * Este caso de uso descreve como um ator externo pode [criar uma conta](Criar-Conta) na Twitch. ## Atores * Ator externo ## Pré-condições * O ator deve ter acesso à internet. * O ator não deve estar logado em uma conta na twitch. ## Fluxo de Eventos ### Fluxo Principal * 1. O ator acessa o site da Twitch * 2. O ator seleciona a opção ```Cadastrar-se``` * 3. O ator usuário preenche os campos necessários [FA01][FE01][FE02] * 4. O sistema valida os dados do usuário * 5. O ator é cadastrado * 6. O caso de uso se encerra ### Fluxos Alternativos #### FA01 - O usuário seleciona a opção ```Conectar-se com o Facebook```. * 1. O ator seleciona a opção ```Conectar-se com o Facebook```. * 2. O ator autoriza o uso do Facebook por parte da Twitch . * 3. O ator retorna ao passo 5 do fluxo principal ### Fluxo de Exceção #### FE01 - O futuro usuário não preenche os dados corretamente * 1. O ator preenche os campos incorretamente * 2. O ator clica em confirmar * 3. Uma mensagem na tela avisa que o cadastro não foi efetivado * 4. O usuário retorna ao item 3 do fluxo principal #### FE02 - O futuro usuário deixa de preencher algum campo * 1. O ator deixa de preencher algum campo * 2. O ator clica em confirmar * 3. Uma mensagem na tela avisa que o campo é necessário * 4. O usuário retorna ao item 3 do fluxo principal ## Pós-condição * O ator agora é um usuário, possuindo conta na twitch<file_sep>**Sinônimos:** * Anunciação * Notificação * Aviso **Noção:** * São notificações customizadas enviadas aos [viewers](Viewer) no momento de uma [transmissão ao vivo](Stream). Um [streamer](Streamer) pode enviar uma notificação de no máximo 140 caracteres para se comunicar com seus [viewers](Viewer). **Impacto:** * Os [seguidores](Follower) do canal receberam a notificação da [Stream](Stream) * O [Streamer](Streamer) enviou uma notificação, chamando seus seguidores para a [Stream](Stream)<file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |12/05/2018|0.1|Criação do Documento|<NAME>| |12/05/2018|0.2|Adição de SR de [Streamer](Streamer) versão 1.0|<NAME>| |12/05/2018|0.3|Adição de SR da [Twitch](Twitch)|Amanda Pires| |13/05/2018|0.4|Adição de SR de [Streamer](Streamer) versão 1.1|<NAME>| |13/05/2018|0.5|Adição de SR de [Usuário](User) versão 1.0|<NAME>| |13/05/2018|0.6|Adição de SR de Visitante versão 1.0|<NAME>| |14/05/2018|0.7|Adição de SR de [Usuário](User) versão 1.1|<NAME>| |15/05/2018|0.8|Adição de SR de [Usuário](User) versão 1.2|<NAME>| |15/05/2018|0.9|Adição de SR da [Twitch](Twitch) 2.0|<NAME>| |16/05/2018|1.0|Adição de SR do [Viewer](Viewer) 1.0|Amanda Pires| |16/05/2018|1.1|Adição de SR do [Usuário](User) 1.3|João Carlos| |27/05/2018|2.0|Revisão|<NAME>, <NAME>| [Ferramenta utilizada para a modelagem i*](http://www.cin.ufpe.br/~jhcp/pistar/) ## [Usuário](User) [![Usuario 1.3](./images/iStar/strategic-rationale/usuario-1.3.png)](./images/iStar/strategic-rationale/usuario-1.3.png) [Usuario 1.2](./images/iStar/strategic-rationale/usuario-1.2.png) [Usuario 1.1](./images/iStar/strategic-rationale/usuario-1.1.png) [Usuario 1.0](./images/iStar/strategic-rationale/Usuario.png) ## [Streamer](Streamer) [![Streamer 1.1](./images/iStar/strategic-rationale/streamer-1.1.png)](./images/iStar/strategic-rationale/streamer-1.1.png) [Streamer 1.0](./images/iStar/strategic-rationale/streamer-1.0.png) ## [Twitch](Twitch) [![Twitch](./images/iStar/strategic-rationale/Twitch.png)](./images/iStar/strategic-rationale/Twitch.png) [Twitch - 1.0](./images/iStar/strategic-rationale/twitch.png)<br> [Twitch - 2.0](./images/iStar/strategic-rationale/twitch-2.0.png) ## Visitante [![Visitante](./images/iStar/strategic-rationale/visitante.png)](./images/iStar/strategic-rationale/visitante.png) ## [Viewer](viewer) [![Viewer](./images/iStar/strategic-rationale/viewer1.1.png)](./images/iStar/strategic-rationale/viewer1.1.png) [Viewer - 1.0](./images/iStar/strategic-rationale/viewer.png)<file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |29/04/2018|0.1|Criação do Documento |<NAME>| |29/04/2018|0.2|Inserção de User Stories |Gabriel Ziegler| |06/05/2018|1.0|Inserção prioridades e revisão do artefato |<NAME>| |10/06/2018|1.1|Inserção das US42 a US52 e link da geral 0.3|<NAME>| |11/06/2018|1.2|Adicionando casos de uso|<NAME>| # Product Backlog - Geral 1.1 |Tipo|História|Descrição|Prioridade| |----|----|---------|-------| |RF|US01|Eu, como usuário, desejo [criar uma conta](Cen%C3%A1rio-002) na [Twitch](Twitch) para desfrutar dos serviços de streaming.|Must| |RNF|US02|Eu, como usuário, desejo utilizar a [Twitch](Twitch) me conectando pelo facebook para acessar mais rápido os serviços de streaming.|Could| |RF|US03|Eu, como usuário, desejo [editar meu perfil](Cen%C3%A1rio-023) na [Twitch](Twitch) para manter meus dados atualizados.|Should| |RF|US04|Eu, como usuário, desejo desabilitar minha conta da [Twitch](Twitch) para não ter acesso as funcionalidade de um usuário [Twitch](Twitch).|Must| |RF|US05|Eu, como usuário, desejo me tornar um usuário da [Twitch Prime](Assinar-Twitch-Prime) para ter acesso a funcionalidades diferenciadas do [Twitch](Twitch).|Must| |RF|US06|Eu, como usuário, desejo me tornar um parceiro da [Twitch](Twitch) para monetizar minhas streams.|Must| |RF|US07|Eu, como viewer, gostaria poder [compartilhar uma stream](Cen%C3%A1rio-030) que estou assistindo para que meus amigos possam assistir também.|Must| |RF|US08|Eu, como viewer, gostaria de seguir um streamer para que eu possa ser notificado de seus suas atualizações na [Twitch](Twitch).|Should| |RF|US09|Eu, como usuário, gostaria de acessar os [chats](Group-Chat) para participar das discussões.|Could| |RF|US10|Eu, como streamer, desejo ter a opção de filtrar quem digita no [chat](Group-Chat) da minha stream, para que eu possa ter maior controle sobre meu ambiente de transmissão.|Could| |RF|US11|Eu, como streamer, gostaria de ter a possibilidade de [banir alguém](Cen%C3%A1rio-027) do [chat](Group-Chat) de minha stream, para evitar que pessoas tumultuem minha transmissão.|Could| |RF|US12|Eu, como streamer, gostaria de alterar o jogo que estou jogando na minha stream, sem que seja necessário começar outra transmissão, para minha stream ter maior fluidez.|Should| |RF|US13|Eu, como usuário, gostaria de visualizar [chats](Group-Chat) de uma stream sem precisar estar logado para que eu possa saber o que está sendo comentado.|Could| |RF|US14|Eu, como streamer, desejo subir um vídeo na plataforma, para que eu possa divulgar minhas streams.|Must| |RF|US15|Eu, como streamer, gostaria de deletar um vídeo que eu subi na plataforma para que eu possa ter maior controle sobre meu conteúdo.|Must| |RF|US16|Eu, como streamer, gostaria de programar uma premiere para meu vídeo para que eu possa divulgar meu trabalho.|Should| |RF|US17|Eu, como streamer, gostaria de gravar uma transmissão anterior em vídeo para que eu possa compartilha-la mais tarde.|Could| |RF|US18|Eu, como streamer gostaria de destacar um vídeo para este ter maior visualização.|Could| |RF|US19|Eu, como usuário, desejo poder buscar outros usuários para que eu possa achar possíveis amigos.|Could| |RF|US20|Eu, como usuário, desejo poder adicionar como amigo outros usuários para que eu possa aumentar a minha interatividade com a comunidade.|Could| |RF|US21|Eu, como usuário, desejo poder mandar [mensagens de texto privadas](Mensagens-Privadas) para poder me comunicar com outros usuários.|Could| |RF|US22|Eu, como viewer, desejo poder participar de [chats](Group-Chat) durante as streams para poder comentar cenas da transmissão.|Could| |RF|US23|Eu, como usuário, desejo poder mandar emoticons em conversas para poder aumentar a interatividade.|Should| |RF|US24|Eu, como usuário, desejo bloquear alguém em uma conversa para que eu possa evitar usuários indesejados.|Must| |RF|US25|Eu, como usuário, gostaria de [sincronizar os add-ons](Adi%C3%A7%C3%A3o-de-Add-ons-em-Jogos) com meus jogos.|Must| |RF|US26|Eu, como usuário, gostaria de de filtrar o tipo de mod que eu vejo.|Should| |RF|US27|Eu, como usuário, gostaria de instalar novos mods.|Must| |RF|US28|Eu, como usuário, gostaria de deletar mods.|Must| |RNF|US29|Eu, como usuário, gostaria de disponibilizar novos mods para a comunidade.|Must| |RNF|US30|Eu, como usuário, gostaria de atualizar os mods de forma automatizada.|Should| |RF|US31|Eu, como usuário, gostaria de poder criar uma nova chamada de voz para poder comunicar com outros usuários.|Could| |RF|US32|Eu, como usuário, gostaria de poder filtrar quem entrar na chamada para que assim eu possa ter maior controle com quem eu falo.|Could| |RF|US33|Eu, como usuário, desejo fazer uma vídeo conferência para poder falar com meus amigos da [Twitch](Twitch).|Could| |RF|US34|Eu, como usuário, desejo fazer uso de uma video conferência em um servidor.|Could| |RF|US35|Eu, como usuário, desejo criar um grupo para chamadas permanente para facilitar iniciar conversas com o mesmo grupo sempre.|Could| |RNF|US36|Eu como viewer, gostaria de opções de planos mensais de inscrições em um canal para que eu possa escolher o valor e as vantagens que mais me agrada.|Must| |RF|US37|Eu como viewer, desejo me inscrever em um canal para poder ter mais vantagens nesse canal.|Must| |RF|US38|Eu como viewer, desejo comprar bits para poder doar aos streamers.|Must| |RNF|US39|Eu como usuário, desejo assinar o serviço [Twitch](Twitch) prime para receber uma série de vantagens em todo o site.|Must| |RF|US40|Eu como viewer, desejo doar bits para um streamer para poder incentivar o seu trabalho.|Must| |RF|US41|Eu como usuário, desejo aderir ao [Twitch](Twitch) turbo para receber mais recursos na [Twitch](Twitch).|Must| |RF|US42|Eu, como usuário, desejo poder recuperar minha senha e nome de usuário caso eu tenha esquecido, para que assim eu possa acessar a plataforma.|Must| |RF|US43|Eu, como usuário, desejo poder assistir uma stream sem estar logado, para que assim eu não perca tempo me cadastrando.|Could| |RF|US44|Eu, como usuário, desejo criar criar clipes das streams, para que eu possa compartilhar com meus amigos ou redes sociais.|Could| |RNF|US45|Eu, como usuário, desejo que a [Twitch](Twitch) tenha uma boa usabilidade, para que assim fique mais fácil e intuitivo navegar pela plataforma e assistir streams.|Should| |RNF|US46|Eu, como streamer, desejo que a [Twitch](Twitch) consiga suportar um grande número de visitas, para que assim a plataforma consiga lidar com o grande número de viewers que eu possa ter.|Must| |RNF|US47|Eu, como usuário, desejo que a [Twitch](Twitch) sejaum ambiente seguro para transações financeiras, para que assim eu possa incentivar financeiramente a comunidade da plataforma.|Must| |RNF|US48|Eu, como usário, desejo que a [Twitch](Twitch) tenha um bom sistema de login, para que ninguém consiga hackear minha conta.|Must| |RNF|US49|Eu, como viewer, desejo que a transmissão tenha fluídez, para que assim ela não fique travando.|Must| |RFN|US50|Eu, como usuário, desejo que a [Twitch](Twitch) esteja sempre no ar(24h/7), para que assim eu possa acessa-la a qualquer hora.|Must|. |RFN|US51|Eu, como usuário, desejo que a [Twitch](Twitch) seja portável, para que eu tenha maior flexibilidade para acessar a plataforma de múltiplos meios.|Must| |RF|US52|Eu, como usuário, desejo poder escolher o idioma no site da [Twitch](Twitch), para que eu possa usar a interface caso não saiba falar inglês.|Must| |RF|US53|Eu, como usuário, desejo receber [notificações](Live_Notification) da minha conta para que eu possa ficar alertado sobre as coisas mais importantes que acontecem.|Must| |RF|US54|Eu, como empresa, desejo divulgar anúncios para que os usuários da [Twitch](Twitch) possam ver os meus produtos.|Could| |RF|US55|Eu, como usário, desejo ter acesso a meio de pagamentos online para desfrutar de funcionalidades pagas.|Must| ## Product Backlog - Geral 0.3 (Versão anterior) ### [Link imagem tabela em alta definição](https://raw.githubusercontent.com/wiki/gabrielziegler3/Requisitos-2018-1/images/Tabela_Geral_Product_Backlog.jpg) <file_sep>**Sinônimos:** * Seguir * Follow. **Noção:** * Tarefa realizada pelo [viewer](Viewer) * Ação que possibilita seguir um canal e receber notificações de quando o [streamer](Streamer) estiver fazendo uma live ou [gankando](Raid) de outros streamers. **Impacto:** * [Viewer](Viewer) da follow no canal do [streamer](Streamer). * [Usuário](User) recebe notificações de um canal, após dar follow.<file_sep># UC12 - Transmissão de Ads ## Descrição * Esse caso de uso descreve como transmitir anúncios durante uma stream ## Atores * [Streamer](Streamer) ## Pré-condições * O streamer deve ter acesso à internet * O streamer deve estar aplicado ao Twitch Partners * O streamer deve estar streamando ## Fluxo de Eventos ### Fluxo Principal * 1. O streamer abre a stream * 2. A stream automaticamente gera anúncios para o streamer * 3. O caso se encerra ### Fluxos Alternativos * Não se aplica ### Fluxo de Exceção * Não se aplica ## Pós-condição * O streamer começa a arrecadar baseado na visualização dos anúncios<file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |01/04/2018|1.0|Criação e Desenvolvimento do Documento|Filipe Dias| |02/04/2018|1.1|Adicionado imagens explicativas|João Carlos Porto| |27/05/2018|1.2|Evolução do Documento|Filipe Dias,<NAME>| |11/06/2018|1.3|Hyperlinks de léxicos|Filipe Dias| |11/06/2018|1.4|Adição de Resultados e cenários|Filipe Dias| ### 1. O que é Análise de Protocolo & Observação Participativa? <p align=justify> A técnica híbrida consiste em levantamento de perguntas (seguindo um modelo de tutorial) para entender o funcionamento da plataforma <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a> a partir da perspectiva de 3 tipos diferentes de atores: O <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Viewer">Viewer</a>, o <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Streamer">Streamer</a> e a própria <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a>. </p> ### 2. Objetivo <p align=justify> O objetivo ao usar tal técnica é entender o ponto de vista desses atores e entender o funcionamento da plataforma como um todo. </p> ### 3. Análises #### 3.1 [Viewer](Viewer) ![](https://png.icons8.com/color/1600/person-male.png) #### Como você faz para assistir uma stream? <p align="justify"> * Vou no meu navegador e acesso o site da <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a>. Entro na página principal e busco pelo catálogo de jogos o jogo que eu estou afim de assistir. Caso eu queira participar do <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Group-Chat">chat</a> preciso ou me registrar e entrar com meus dados ou, caso eu já tenha cadastro, posso fazer login (visto que as únicas coisas que posso fazer sem login é assistir as streams). Após efetuar o login, eu posso realizar doações para o <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Streamer">streamer</a>, dar follow no canal dele e/ou dar subcribe para ter mais participação na <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream">stream</a>. Caso eu queira ter mais destaques em mensagens enviadas para o <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Group-Chat">chat</a>, posso utilizar meus <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Bits">bits</a> que eu compro na própria <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a>; que além de ajudar meu <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Streamer">streamer</a> favorito, favorecem em uma maior visibilidade da minha mensagem na <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream">stream</a>. </p> #### Tem muitos anúncios rolando na stream. Como eu faço para parar de assistí-los? <p align="justify"> * Posso pagar para a <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a> e me tornar um <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch-Prime">Twitch Prime</a>, que além de remover os anúncios para mim, me concede prêmios relacionados ao meu jogo preferido. Ou posso dar <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Subscribe">subscribe</a> no canal do meu <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Streamer">streamer</a>, que fará com que eu pare de ver anúncios somente na <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream">stream</a> dele. </p> #### Vi uma jogada incrível durante uma <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream">stream</a>, como fazer um <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Clipes">clip</a> dessa parte? <p align="justify"> * Em uma transmissão gravada ou em uma live basta usar um atalho no teclado (ALT + x), após esse procedimento você será redirecionado para uma nova aba no seu navegador, e nessa aba vai ter ferramentas de edições para que possa ser feito o corte apenas da parte em interesse. </p> <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_AnaliseProtocolo%2BObserva%C3%A7%C3%A3oParticipativa/N%C3%A3oEstouGostandodoTemaOriginaldaTwitch.png" width=500px> <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_AnaliseProtocolo%2BObserva%C3%A7%C3%A3oParticipativa/ViUmaJogadaIncr%C3%ADvelDuranteUmaStream.png" width=500px> ------------------------------------ #### 3.2 [Streamer](Streamer) ![](https://cdn0.iconfinder.com/data/icons/user-pictures/100/supportmale-2-512.png) #### Estou jogando por muito tempo. Como eu faço para arrecadar dinheiro jogando? <p align="justify"> * Eu posso me cadastrar numa plataforma de jogos <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">(Twitch)</a>, baixar um software externo de transmissão ao vivo e ganhar a visibilidade de <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Viewer">viwers</a>. Com isso, posso passar anúncios em minhas transimissôes e permitir doações de dinheiro por parte de externos. Assim poderei ganhar um dinheiro. </p> #### Que benefícios trarei aos meus <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Viewer">viewers</a> para ‘prendê-los’ em minha <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream">stream</a>? <p align="justify"> * Caso um <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Viewer">viewer</a> goste de minha <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream">stream</a>, e queira ficar por mais tempo, ele pode se inscrever no meu canal (<a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Subscribe">subscribe</a>) e assim ele não terá que ver anúncios e terá mais visibilidade no meu <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Group-Chat">chat</a>. Assim, poderei interagir mais com ele e ele gostará ainda mais de me assistir jogando. </p> ------------------------------------ #### 3.3 [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch) <img src="https://www.windowscentral.com/sites/wpcentral.com/files/topic_images/2016/twitch-logo-topic.png" width=500px> #### O que vou ganhar ao fornecer a plataforma de [stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Subscribe)? <p align="justify"> * Empresas poderão pagar para você para colocarem anúncios no meio de transmissões de <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Streamer">streamers</a>. Parte do dinheiro vai para você e outra parte para eles. </p> #### O que posso oferecer para os meus [usuários](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/User) para preferirem usar minha plataforma? <p align="justify"> * Você pode oferecer um serviço <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch-Prime">'Prime'</a> que faz com que seus <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/User">usuários</a> recebam benefícios ao assiná-lo. Você ganha dinheiro, e eles ganham prêmios. Assim, todos poderão ganhar nessa troca. </p> #### Não estou gostando do tema original da [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch), como eu troco para o tema dark mode? <p align="justify"> * Após logado, basta clicar no seu nick no canto superior direito e vai aparecer algumas opções onde tem uma chamada dark mode e clicar na mesma. </p> <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_AnaliseProtocolo%2BObserva%C3%A7%C3%A3oParticipativa/N%C3%A3oEstouGostandodoTemaOriginaldaTwitch.png" width=500px> <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_AnaliseProtocolo%2BObserva%C3%A7%C3%A3oParticipativa/N%C3%A3oEstouGostandodoTemaOriginaldaTwitch%20(1).png" width=500px> #### Como adicionar alguém na lista de amigos? <p align="justify"> * Após logado, no canto inferior à esquerda tem uma barra de busca basta inserir o nick da pessoa desejada e clicar no ícone ao lado do nome do mesmo. </p> <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_AnaliseProtocolo%2BObserva%C3%A7%C3%A3oParticipativa/ComoAdicionarAlgu%C3%A9mnaListadeAmigos.png" width=500px> <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_AnaliseProtocolo%2BObserva%C3%A7%C3%A3oParticipativa/ComoAdicionarAlgu%C3%A9mnaListadeAmigos2.png" width=500px> ___________________ ### 4. Cenários * Adicionar amigos: [Cenário 010](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Cenário-010) * Assistir [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream): [Cenário 001](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Cenário-001) * [Dar Follow](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Dar-follow): [Cenário 003](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Cenário-003) * [Subscrever](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Subscribe) em um canal: [Cenário 004](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Cenário-004) * [Clipar](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Clipes) parte da [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream): [Cenário 005](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Cenário-005) * Realizar doações: [Cenário 008](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Cenário-008) e [Cenário 009](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Cenário-009) * Adicionar amigos: [Cenário 010](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Cenário-010) * Anunciar na transmissão: [Cenário 017](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Cenário-017) * Acessar catálogo de jogos: [Cenário 018](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Cenário-018) * Compartilhar [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream): [Cenário 030](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Cenário-030) ### 5. Resultados * Foram realizadas, ao todo, 9 análises. Após a Análise realizada juntamente com a Observação participativa, pode-se levantar os seguintes requisitos listados abaixo: |Requisito|Tipo| |--|--| |Assistir [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream)|Funcional| |Compartilhar [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream)|Funcional| |Acessar catálogo|Funcional| |Adicionar amigo|Funcional| |Mudar tema|Funcional| |Assinar [Twitch Prime](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch-Prime)|Funcional| |Transmitir anúncios durante a [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream)|Funcional| |Inscrever-se em um canal ([Subscribe](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Subscribe))|Funcional| |Seguir canal ([Follow](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Dar-follow))|Funcional| |Destacar ([clipar](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Clipes)) [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream)|Funcional| |Realizar doações ([Bits](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Bits))|Funcional| <file_sep># UC07 - Geração de Chave de Transmissão ### [Diagrama de Caso de uso](Diagrama-Gera%C3%A7%C3%A3o-de-Token-do-Streamer) ## Descrição * Este caso de uso descreve o processo de gerar a chave de transmissão para o usuário. ## Atores * Usuário ## Pré-condições * O usuário deve ter acesso à internet * O usuário deve estar logado na Twitch ## Fluxo de Eventos ### Fluxo Principal * 1. O usuário acessa o site da Twitch * 2. O usuário seleciona a sessão ```Painel de Controle``` no dropdown do usuário * 3. O usuário vai até a secção de configurações e seleciona ```preferencias de stream``` [FA01] * 4. O usuário clica em chave de transmissão * 5. O sistema envia uma mensagem de aviso e confirmação * 6. O usuário concorda com os termos [FE01] * 7. O caso se encerra ### Fluxos Alternativos #### FA01 - O usuário acessa a chave de treanmissão através do teste de integridade da transmissão * 1. Na seção ```Integridade da transmissão``` o streamer seleciona a opção ```Saiba como realizar um teste de transmissão``` * 2. O usuário seleciona a opção ```Pegue a sua chave de transmissão no Painel de controle do Twitch.``` * 3. O usuário retorna ao item 4 do fluxo principal. ### Fluxo de Exceção #### FE01 - O streamer não concorda com os termos * 1. O streamer faz todo o fluxo até o passo 5 * 2. O streamer não concorda com os termos * 3. O streamer não visualiza a Chave de Transmissão * 4. O caso de uso se encerra ## Pós-condição * O usuário agora possui a chave de transmissão<file_sep># UC15 - Seguir Canal ### [Diagrama seguir Canal](Diagrama-Seguir-Canal) ## Descrição * Este caso de uso descreve como seguir um determinado canal ## Atores * Usuário ## Pré-condições * O usuário deve ter acesso à internet * O usuário deve estar logado na twitch ## Fluxo de Eventos ### Fluxo Principal * 1. O Usuário acessa a Twitch * 2. O Usuário seleciona um canal que gostaria de seguir * 3. O Usuário clica no botão de seguir * 4. O caso de uso se encerra ### Fluxos Alternativos * Não se aplica ### Fluxo de Exceção * Não se aplica ## Pós-condição * Usuário agora é um seguidor do canal<file_sep># Cenário 007 - Dar um [ban](Ban) ou permaban ## Título * [Streamer](Streamer) dando um ban ou permaban ## Objetivo * Retirar usuários indesejados do [chat](Group-Chat) ao vivo ## Contexto * [Streamer](Streamer) está streamando Um [viewer](Viewer) está incomodando o [streamer](Streamer) ou outros [viewers](Viewer) no (chat)[Group-Chat] ## Ator(es) * [Streamer](Streamer) * [Viewer](Viewer) ## Recursos * Dispositivo eletrônico conectado à internet ## Exceções * Dispositivo eletrônico não conectado à internet ## Episódios * [Streamer](Streamer) está streamando * [Viewer](Viewer) começa a incomodar no (chat)[Group-Chat] * [Streamer](Streamer) localiza o [viewer](Viewer) indesejado no (chat)[Group-Chat] * [Streamer](Streamer) clica em seu nome * Uma modal com as informações públicas do usuário é aberta * O [streamer](Streamer) escolhe se dá um ban (temporário) ou um permaban (permanente) no [viewer](Viewer) * O [viewer](Viewer) é banido <file_sep># Mudar o nome de sua [Stream](Stream) ## Objetivo: * Alterar o nome de exibição de sua livestream ## Contexto: * O [Streamer](Streamer) gostaria de modificar o nome de sua transmissão ## Ator(es): * [Streamer](Streamer) ## Recursos: * Painel de Controle Twitch ## Exceções: * O nome contem palavras que ferem as políticas da comunidade da Twitch. ## Episódios: * O [Streamer](Streamer) está com seu canal descrito por algo que ele estava streamando em outro contexto * O [Streamer](Streamer) vai até o painel de controle de sua stream * Vai até a secção de informações da transmissão * Vai até a caixa do subtópico ‘Título’ * Deleta o título anterior * Escreve o novo título da stream * Confirma as alterações clicando no botão ‘Atualizar Informações’<file_sep>Data|Versão|Descrição|Autor -----|------|---------|------- 17/04/2018|1.0|Criação do documento e adição dos Casos de Uso e do Objetivo do Documento|<NAME>| 18/04/2018|1.1|Adição de Casos de Uso|<NAME>| 18/04/2018|1.2|Adição da especificação do caso de uso 13|<NAME>| 19/04/2018|1.3|Adição dos UC 01,02,04,09,10 e 11 e algumas outras alterações aos UC feitos por outros membros|<NAME> 20/04/2018|1.4|Revisão|<NAME>| 01/05/2018|1.5|Modificações e retrabalho realizado após inspecção de todos os casos de uso|<NAME>| ### 1. Introdução #### 1.1 Propósito * O documento presente tem o propósito de apresentar os diagramas e as especificações de caso de uso essenciais paraå modelar requisitos, com foco em requisitos funcionais. #### 1.2. Escopo * O presente documento indica os diagramas e especificações de caso de uso existentes na [Twitch](Twitch), tais quais tem o objetivi de mostrar detalhadamente a descrição, atores, pré-condições, pós-condições e os fluxos de eventos que podem ser divididos em principal, alternativo e de exceção. ### 2. Objetivo * O Diagrama de Casos de Uso tem o objetivo de auxiliar a comunicação entre os analistas e o cliente. Um diagrama de Caso de Uso descreve um cenário que mostra as funcionalidades do sistema do ponto de vista do usuário, através do uso de atores, cenários e a interação entre estes elementos. Este documento contém os casos de uso levantados pela equipe para a plataforma Twitch, em prol da disciplina de requisitos de software. ### 3. Casos de Uso * [UC01 - Visualizar Stream](Visualização-de-Stream) * [UC02 - Transmitir Multimídia](Transmissão-Multimídia) * [UC03 - Criar Conta](Criação-de-Conta) * [UC04 - Inscrever em Canal](Inscrição-em-Canal) * [UC05 - Doar Bits](Doação-de-Bits) * [UC06 - Comprar Bits](Compra-de-Bits) * [UC07 - Gerar Token do Streamer](Geração-de-Token-do-Streamer) * [UC08 - Enviar Mensagens Privadas](Mensagens-Privadas) * [UC09 - Restringir Chat](Restrições-de-Chat) * [UC10 - Adicionar Add-ons em Jogos](Adição-de-Add-ons-em-Jogos) * [UC11 - Comunicar por Chat de Voz](Chat-de-Voz) * [UC12 - Transmitir Ads](Transmissão-de-Ads) * [UC13 - Assinar Twitch Prime](Assinar-Twitch-Prime) * [UC14 - Alterar Nome da Stream](Alterar-Nome-da-Stream) * [UC15 - Seguir Canal](Seguir-Canal) * [UC16 - Banir Viewer](Banir-Viewer) * [UC17 - Adicionar Amigo](Adição-de-Amigo) * [UC18 - Compartilhar uma Transmissão](Compartilhar-uma-Transmissão) * [UC19 - Criar Vídeo](Criação-de-Vídeo) * [UC20 - Hospedagem](Hosting) ### 4. Resultado * A partir do levantamento dos casos de uso, pode-se levantar os seguintes requisitos, listados abaixo: |Requisito|Tipo| |---|---| |Assistir [Stream](Stream)|Funcional| |Realizar [Stream](Stream)|Funcional| |Criar Conta|Funcional| |[Inscrever-se em Canal](Subscribe)|Funcional| |Doar [Bits](Bits)|Funcional| |Comprar [Bits](Bits)|Funcional| |Gerar Token|Funcional| |Enviar mensagens privadas|Funcional| |Restringir [Chat](Group-Chat)|Funcional| |Transmitir anúncios|Funcional| |Assinar [Twitch Prime](Twitch-Prime)|Funcional| |Alterar nome da [Stream](Stream)|Funcional| |[Dar Follow](Dar-follow) em um [Streamer](Streamer)|Funcional| |Adicionar amigo|Funcional| ### 5. Conclusão * A partir da construção desses diagramas e especificações, pode-se concluir que identificar, diagramar e especificar de casos de uso são fatores de extrema necessidade, os quais auxiliam muito no entendimento do sistema como um todo.<file_sep>## Diagrama do UC20 - Hospedagem <img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/UC20.png" width=800px><file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |07/04/2018|1.0|Criação do Documento|<NAME>| |07/04/2018|1.1|Criação dos léxicos Streamer, Viewer,Moderator, Streamar,Whisper e Dar Follow e referenciação|Gustavo Carvalho| |08/04/2018|1.2|Adição de léxicos para Subscribe, Canais em Destaque e Share|<NAME>| |08/04/2018|1.3|Adição de léxicos para Bits, Gankar, Loot Prime, Clipes, Donate e Cheer|<NAME>| |09/04/2018|1.4|Adição de léxicos para Live Notification e Group chat|<NAME>| |09/04/2018|1.5|Criação dos Hyperlink ligando os léxicos existentes|<NAME>| |09/04/2018|1.6|Adição de Página Donate, Streaming e Hyperlinking destas|<NAME>| |10/04/2018|1.7|Adição de léxico Subscriber|<NAME>| |10/04/2018|1.8|Adição de Páginação para as tabelas Canais em Destaque, Loot Prime, Go Live Notification e Group [Chat](Group-Chat), assim como o Hyperlinking destas. Criação do Léxico para Ban|<NAME>| |10/04/2018|1.9|Criação de Bot, Reagir, Emote, Fazer Maratona e Moderador|<NAME>| |10/04/2018|2.0|Adição dos léxicos para: Twitch, Stream, Twitch Prime, Usuário Prime, Follower e Mods. Páginação e Hyperlinkamento dos mesmos, assim como algumas alterações em léxicos já existentes. |<NAME>| |16/04/2018|2.1|Adição do léxico Creative e organização do artefato|<NAME>| |18/04/2018|2.2|Adição dos léxicos Criar conta, Criar video sob demanda e Modo host está sendo usado|<NAME>| |09/06/2018|2.3|Remoção de léxico inadequado, alteração de nomes |<NAME>| |09/06/2018|2.4|Adição de léxico User|<NAME>| |11/06/2018|2.5|Revisionamento e reescrita do impacto de todos os léxicos e outras mudanças menores|<NAME>| |11/06/2018|2.6|Revisão do documento e inserção de Introdução, Objetivo e Resultados|<NAME>| ### 1. Introdução #### 1.1 Propósito * O propósito almejado com a elaboração deste artefato é poder aplicar modelagem de requisitos, além de conectar o trabalho como um todo. #### 1.2 Escopo * O presente documento indica os léxicos existentes na [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch), de forma a apresentar sinônimos, noções e impactos sobre aplicação. ### 2. Objetivo * O objetivo ao produzir esse documento é de apresentar a linguagem do domínio da [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch) levando em consideração o seu contexto. ### 3. Divisão * O léxico está dividido em Objeto & Verbo ### 4. Léxico Termos e palavras cobertos por esta técnica: ##### 4.1 Objeto * [L01 - Moderador](Moderador) * [L02 - Streamer](Streamer) * [L03 - Viewer](Viewer) * [L04 - Bits](Bits) * [L05 - Bot](Bot) * [L06 - Clipes](Clipes) * [L07 - Streaming](Streaming) * [L08 - Subscriber](Subscriber) * [L09 - Canais em Destaque](Canais-em-Destaque) * [L10 - Loot Prime](Loot-Prime) * [L11 - Live Notification](Live-Notification) * [L12 - Group Chat](Group-Chat) * [L13 - Twitch](Twitch) * [L14 - Stream](Stream) * [L15 - Twitch Prime](Twitch-Prime) * [L16 - Usuário Prime](Usuário-Prime) * [L17 - Follower](Follower) * [L18 - Emotes](Emotes) * [L19 - Mods](Mods) * [L20 - Creative](Creative) * [L21 - User](User) ##### 4.2 Verbo * [L22 - Follow](Dar-Follow) * [L23 - Host](Host) * [L24 - Streamar](Streamar) * [L25 - Whisper](Whisper) * [L26 - Subscribe](Subscribe) * [L27 - Share](Share) * [L28 - Maratonar](Fazer-Maratona) * [L29 - Raid](Raid) * [L30 - Cheer](Cheer) * [L31 - Donate](Donate) * [L32 - Ban](Ban) * [L33 - Reagir](Reagir) * [L34 - Criar Conta](Criar-Conta) ### 5. Resultados * Com o estudo realizado, pode-se levantar ao todo 34 simbologias. A partir disso, fora levantados seus significados e aplicados(linkados) em seus determinados contextos. <file_sep>|Data|Versão|Descrição|Autor(es)| |--|--|--|--| |27/05/2018|1.0|Criação e desenvolvimento do documento|<NAME>| |11/06/2018|1.1|Revisão do documento|<NAME>| |11/06/2018|1.2|Adição storyboard|<NAME>, <NAME>| |11/06/2018|1.3|Edição do documento|Filipe Dias| # Storytelling ![Storytelling](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Storytelling/storytelling-jonas.png) _____ ![Storytelling-portabilidade](./images/storytelling/storytelling-portabilidade.png) _____ ![Storytelling-notificacao](./images/storytelling/storytelling-notificacao.png) _____ ![Storytelling-notificacao](./images/storytelling/storytelling-bit.png) _____ ![Storytelling-chat](./images/storytelling/storytelling-chat.jpg) ### 1. O que é Storytelling? <p align=justify> Storytelling é uma palavra em inglês, que está relacionada com uma narrativa e significa a capacidade de contar histórias relevantes. Ou seja, o uso de recursos audiovisuais juntamente com as palavras são utilizados de tal forma a promover algum negócio sem que haja a necessidade de fazer uma venda direta. A técnica consiste em contar uma história que, no caso acima, explique o funcionamento de algum produto ou seu o objetivo. </p> ### 2. Objetivo <p align=justify> O objetivo ao narrar a experiência de Jonas é de entender como pessoas podem ter conhecimento a respeito da plataforma <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a> e para que ela serve. No caso, pode-se entender que o objetivo principal da plataforma é a <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream">Stream</a>. </p> ### 3. Ferramenta utilizada * [Storytelling Creator](https://www.storyboardthat.com/storyboard-creator) ### 4. Resultados * A partir da experiência de Jonas com seus amigos, é possível levantar os seguintes possíveis requisitos: |Requisito|Tipo| |----|----| |[Clipar](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Clipes) parte da [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream)|Funcional| |Compartilhar [Clipe](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Clipes)|Funcional| |Cortar [Clipes](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Clipes)|Não Funcional| |Quantidade de [Clipes](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Clipes) ilimitadas|Não Funcional| |Portabilidade Mobile|Não funcional| |Download pelo app do celular|Não Funcional| |Receber notificações|Funcional| |Conversar em um chat privado|Funcional| ### 5. Fontes: * [O que é storytelling?](https://novaescolademarketing.com.br/marketing/o-que-e-storytelling/) * [Significado de Storytelling](https://www.significados.com.br/storytelling/) <file_sep>* Checklist de Inspeção dos diagramas iStar * Inspetores: <NAME>, <NAME> * Data: 23/05/2018 |Item de Inspeção|iStar| |------|-------| Questão 1|Os Atores estão bem definidos ?| Resposta| Sim| Modificações| Questão 2|Os Hardgoals estão bem definidos ?| Resposta| Sim| Modificações| Questão 3|Os Softgoals estão bem definidos ?| Resposta| Sim| Modificações| Questão 4|As tasks estão bem definidos ?| Resposta| Sim| Modificações| Questão 5|Os Resources estão bem definidos ?| Resposta| Sim| Modificações| Questão 6|Os Hardgoals tem bons nomes ?| Resposta| Não| Modificações|Commit [7a30ff8](_compare/7a30ff8),[a190b2c](_compare/a190b2c)| Defeito| seja capaz de hospedar stream| Defeito|seja capaz de enviar notificações| Defeito|seja capaz de ser acessada| Defeito|seja capaz de fazer comunicação| Defeito|seja capaz de comunicar externamente| Defeito|seja capaz de comunicar usuários| Defeito|seja capaz de ser acessada| Defeito|seguir usuario| Questão 7|Os Softgoals tem bons nomes?| Resposta| Sim| Modificações| Questão 8|As tasks tem bons nomes?| Resposta| Não| Modificações|Commit [2c389f8](_compare/2c389f8),[39b003d](_compare/39b003d) Defeito|Sincronização automática dos Mods| Defeito|Canal seguido| Defeito|Instalação bem sucedida| Questão 9|Os Resources tem bons nomes?| Resposta|Não| Modificações|Commit [b5408f4](_compare)| Defeito|Capital| Questão 10|Todos os links entre elementos internos e externos do rationale são de dependencia| Resposta| Não| Modificações|Commit [7a30ff8](_compare/7a30ff8)| Defeito|SR-Streamer Defeito|Twitch Defeito|Visitante Defeito|Viewer Questão 11|Todos os links entre Hardgoals e outros elementos estão corretos?| Resposta|Não| Modificações|Commit [7a30ff8](_compare/7a30ff8),[4a473d4](_compare/4a473d4)| Defeito|Serviço de [Add-ons](Mods) [Mods] seja disponibilizado| Defeito|Seja capaz de fazer comunicação| Defeito|Viewer seja prime| Defeito|Dasboard seja acessado| Questão 12|Todos os links entre Softgoals e outros elementos estão corretos?| Resposta|Não| Modificações|Commit [4a473d4](_compare/4a473d4) Defeito|Boa segurança| Defeito|Boa usabilidade| Defeito|Alta Performance| Questão 13|Todos os links entre Tasks e outros elementos estão corretos?| Resposta| Sim| Modificações| Questão 14|Todos os links de dependência estão corretos?| Resposta| Sim| Modificações| Questão 15|Todos as associações entre atores estão corretas?| Resposta| Sim| Modificações|<file_sep>## Clipes **Sinônimos:** * Clip * Video * Curta **Noção:** * Partes salvas de uma [stream](Stream) em um vídeo curto. **Impacto:** * Gravei um clipe dessa jogada. * Vou compartilhar esse clipe com meus [viewers](Viewer).<file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |01/04/2018|1.0|Criação do Documento|<NAME>| |01/04/2018|1.1|Descrição dos métodos de pré-rastreabilidade|<NAME>| # Pré-rastreabilidade ## [Rich Picture](RichPicture) <descrição> ## Argumentação <descrição><file_sep>## Fazer Maratona **Sinônimos:** * Maratonar **Noção:** * Tarefa realizada por um [streamer](Streamer) ou por um conjunto do mesmo. * Consiste em fazer [streams](stream) que duram horas, ou até mesmo dias. **Impacto:** * [Streamer] fez uma maratona de 2 dias seguidos em sua [Stream](Stream).<file_sep>**Sinônimos:** * Usuário **Noção:** * Indivíduo cadastrado na plataforma **Impacto:** * É preciso ser um usuário para comentar no [chat](Group-Chat) de uma [stream](Stream). * Para transmitir uma [stream](stream) é necessário ser um Usuário. <file_sep># Cenário 030 - Compartilhar uma [transmissão](Stream) ## Título * [Usuário](User) compartilha uma [stream](Stream) ## Objetivo * Compartilhar uma [stream](Stream) em redes sociais ou via link para que outras pessoas possam assistir. ## Contexto * [Usuário](User) assistindo [stream](Stream) ## Ator(es) * [Usuário](User) ## Recursos * Dispositivo eletrônico conectado à internet ## Exceções * Dispositivo eletrônico não conectado à internet ## Episódios * [Usuário](User) seleciona na parte inferior da [stream](Stream) a opção de compartilhá-la. * [Usuário](User) compartilha em suas redes sociais favoritas. * [Usuário](User) copia link da [stream](Stream) e envia para seus amigos.<file_sep># Cenário 018 - Acessar catálogo de jogos ## Título * Obter lista de jogos. ## Objetivo * Encontrar todos os jogos streamados. ## Contexto * Na home da Twitch, sem acessar nem um canal. ## Ator(es) * [Usuário](User) ## Recursos * Dispositivo conectado a internet. ## Exceções * Encontrar jogo específico sem usar o catálogo. ## Episódios * [Usuário](User) deseja encontrar conteúdo específico * [Usuário](User) clica na parte superior da tela na sessão ```Procurar``` * [Usuário](User) seleciona conteúdo específico * [Usuário](User) assiste stream desejada<file_sep>## Diagrama do Subsistema de [Add-ons](Mods) da UC10 <img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/UC10.png" width=900px><file_sep># Cenário 022 - Fazer uma postagem. ## Título * Fazer postagem ## Objetivo * Relatar como fazer uma postagem. ## Contexto * [Usuário](User) logado na Twitch. * [Usuário](User) deseja compartilhar algo que achou interessante para seus [followers](Follower). ## Ator(es) * [Viewer](Viewer). * [Streamer](Streamer). ## Recursos * Dispositivo eletrônico conectado à internet * Conta na Twitch. ## Exceções * Não haver conexão de internet. * [Usuário](User) não estar logado. ## Episódios * [Usuário](User) deseja compartilhar algum pensamento, [clip](Clipes) ou link para seus seguidores. * [Usuário](User) está na pagina principal, e preenche o campo de texto com oque achar necessário. * [Usuário](User) clica no botão ```postar```. * Uma postagem é feita no mural do mesmo. <file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |12/05/2018|0.1|Criação do Documento|<NAME>| |12/05/2018|0.2|Adição diagrama viewer-streamer|Gustavo Carvalho| |12/05/2018|0.3|Adição diagrama twitch-usuário|<NAME>| |12/05/2018|0.4|Adição diagrama geral 1.0 |<NAME>| |12/05/2018|0.5|Adição do diagrama twitch-patrocinador |<NAME>| |12/05/2018|0.6|Adição do diagrama patrocinador-streamer |<NAME>| |13/05/2018|0.7|Adição diagrama geral 1.1 |<NAME> , <NAME>| |13/05/2018|0.8|Adição do diagrama viewer-twitch |<NAME>| |13/05/2018|0.8|Adição do diagrama twitch-streamer |<NAME>| |15/05/2018|0.9|Adição diagrama viewer-streamer 1.1 |<NAME>| |15/05/2018|1.0|Adição diagrama geral 1.2 |<NAME>| |15/05/2018|1.1|Adição do diagrama viewer-twitch 1.1 |<NAME>| |15/05/2018|1.2|Adição do diagrama twitch-streamer 1.1 |<NAME>| |15/05/2018|1.3|Adição do diagrama geral 1.3 |<NAME>| |15/05/2018|1.4|Adição do diagrama 2.0 twitch-usuario e correções pequenas ao modelo twitch-viewer |<NAME>| |15/05/2018|1.5|Adição do diagrama 3.0 Twitch-Usuário e Viewer-Streamer 2.0|<NAME>| |16/05/2018|1.6|Adição do Diagrama Geral 1.5|<NAME>valho| |16/05/2018|1.7|Adição do diagrama Twitch-Visitante|<NAME>| |16/05/2018|1.8|Adição do Diagrama Geral 1.6|<NAME>| |17/05/2018|1.9|Adição do diagrama 3.1 Twitch-Usuário e Viewer-Streamer 2.1|<NAME>| |24/05/2018|2.0|Adição do diagrama 1.0 Amazon-Twitch e correções no artefato|<NAME>| |27/05/2018|2.1|Revisão|<NAME>| |29/05/2018|2.2|Revisão|<NAME>| ## Geral 1.7 ![Geral 1.7](./images/iStar/strategic-dependecy/geral-1-7.png) [Geral 1.7](./images/iStar/strategic-dependecy/geral-1-7.png) [Geral 1.6](./images/iStar/strategic-dependecy/geral-1-6.png) [Geral 1.5](./images/iStar/strategic-dependecy/geral-1-5.png) [Geral 1.3](./images/iStar/strategic-dependecy/geral-1-3.png) [Geral 1.2](./images/iStar/strategic-dependecy/geral-1-2.png) [Geral 1.1](./images/iStar/strategic-dependecy/geral-1-1.png) [Geral 1.0](./images/iStar/strategic-dependecy/geral-1-0.png) ## Viewer - Streamer 2.2 [![Viewer - Streamer](./images/iStar/strategic-dependecy/viewer-streamer2.2.png)](./images/iStar/strategic-dependecy/viewer-streamer2.2.png) [Viewer - Streamer 2.1](./images/iStar/strategic-dependecy/viewer-streamer-2.1.png)<br> [Viewer - Streamer 2.0](./images/iStar/strategic-dependecy/viewer-streamer-2.0.png)<br> [Viewer - Streamer 1.1](./images/iStar/strategic-dependecy/viewer-streamer1.1.png)<br> [Viewer - Streamer 1.0](./images/iStar/strategic-dependecy/viewer-streamer.png)<br> ## Twitch - Usuário 3.2 ![Twitch - Usuário](./images/iStar/strategic-dependecy/twitch-usuario3.2.png) [Twitch - Usuário 3.1](./images/iStar/strategic-dependecy/twitch-usuario-3.1.png)<br> [Twitch - Usuário 3.0](./images/iStar/strategic-dependecy/twitch-usuario-3.0.png)<br> [Twitch - Usuário 2.0](./images/iStar/strategic-dependecy/twitch-usuario-2.0.png)<br> [Twitch - Usuário 1.0](./images/iStar/strategic-dependecy/twitch-usuario.png)<br> ## Twitch - Patrocinador 1.1 ![Twitch - Patrocinador](./images/iStar/strategic-dependecy/Twitch-patrocinador1.1.png) [Twitch - Patrocinador 1.0](./images/iStar/strategic-dependecy/twitch-patrocinador.png) ## Patrocinador - [Streamer](Streamer) 1.0 ![Patrocinador - Streamer](./images/iStar/strategic-dependecy/patrocinador-streamer.png) ## [Viewer](Viewer) - Twitch 1.1 ![Viewer - Twitch 1.1](./images/iStar/strategic-dependecy/viewer-twitch-1-1.png) [Viewer - Twitch 1.0](./images/iStar/strategic-dependecy/viewer-twitch.png) ## [Streamer](Streamer) - Twitch 1.1 ![Streamer - Twitch](./images/iStar/strategic-dependecy/twitch-streamer-1-1.png) [Streamer - Twitch 1.1](./images/iStar/strategic-dependecy/twitch-streamer-1-1.png) [Streamer - Twitch 1.0](./images/iStar/strategic-dependecy/twitch-streamer.png) ## Visitante - Twitch [![Visitante - Twitch](./images/iStar/strategic-dependecy/Twtitch-visitante.png)](./images/iStar/strategic-dependecy/Twtitch-visitante.png) ## Amazon - Twitch [![Amazon - Twitch](./images/iStar/strategic-dependecy/amazon-twitch-1.0.png)](./images/iStar/strategic-dependecy/amazon-twitch-1.0.png) <file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |08/06/2018|0.1|Criação do Documento|<NAME>| |08/06/2018|0.2|Adição de Conteúdo|<NAME>| ### Planejamento O grupo, como um todo, decidiu por dividir temas em duplas, visando identificar erros a serem corrigidos, para que fosse possível realizar o método escolhido para aplicação da Inspeção. O documento a ser inspecionado será o iStar. ## Visão Geral **Rich Picture** - É um desenho que ilustra de modo informal e que permite analisar problemas e expressar ideias e que pode ser construído colaborativamente com o cliente. Acesso ao [Rich Picture](RichPicture) **Argumentação** - A argumentação é uma forma vital de cognição humana em que pessoas são confrontadas com informações conflitantes e forçadas a lidar com situações inconsistentes(Besnard; Hunter, 2008). E para representar a argumentação em trabalhos de requisitos é possível utilizar da _framework_ ACE que consiste de uma linguagem para representar informações obtidas a partir de uma discussão. Acesso a [Argumentação](Argumentação) ### Preparação A técnica utilizada para a inspeção dos documentos será a Leitura Baseada em Checklist(LBCh). Essa técnica é composta de uma lista de perguntas que ajuda os inspetores a encontrarem uma lista de defeitos no produto durante a inspeção. O final, será desenvolvido um quadro de classificação de defeitos de acordo com o resultado obtido da inspeção. ### Realização da inspeção [Checklist Pré-Rastreabilidade](Checklist-Pre-Rastreabilidade) ### Retrabalho ### Verificação <file_sep># Cenário 021 - [Sussurrar](Whisper). ## Título * <NAME> ## Objetivo * Relatar como mandar um sussuro a outro [viewer](Viewer). ## Contexto * Pessoa está assistindo a uma stream e acompanhando o [chat](Group-Chat). ## Ator(es) * [Viewer](Viewer) ## Recursos * Dispositivo eletrônico conectado à internet * Conta na Twitch ## Exceções * Não haver conexão de internet * [Viewer](Viewer) não está logado ## Episódios * [Usuário](User) está assistindo a uma stream e utilizando o [chat](Group-Chat) da live. * Deseja mandar uma mensagem em privado para um dos [viewers](Viewer) que também está no chat. * [Usuário](User) clica sobre o username que deseja mandar um sussuro. * O usuário clica no botão ```sussuro``` que aparece em uma caixa de diálogo. * Um campo para mensagens será disponibilizado na parte inferior da tela. * [Usuário](User) manda a mensagem. <file_sep>* Checklist de Inspeção dos Cenários e Léxicos * Inspetor: <NAME>, <NAME> * Data: 23/05/2018 #### 1. Cenários |Item de Inspeção|Cenários| |------|-------| Questões|1 - Todos os cenários possuem título?| Resposta|Sim| Modificações|Nenhuma| Commit|-| Questões|2 - Todos os cenários possuem objetivo?| Resposta|Sim| Modificações|Nenhuma| Commit|-| Questões|3 - Estão inseridos em um contexto?| Resposta|Sim| Modificações|Nenhuma| Commit|-| Questões|4 - Todos os atores estão devidamente definidos?| Resposta|Não, o ator do Cenário-013 estava mal definido, visto que definia duplamente o [Streamer](Streamer) como ator| Modificações|Um único ator foi mantido| Commit|[6711c3](_compare/6711c3)| Questões|5 - Os cenários se enquadram em todos os fluxos para a execução de uma tarefa?| Resposta|Sim| Modificações|Nenhuma| Commit|-| Questões|6 - Os episódios estão bem definidos?| Resposta|Sim| Questões|7 - Existem padrões entre as descrições dos episódios dos cenários?| Resposta|Sim| Modificações|Nenhuma| Commit|-| Questões|8 - Todos os cenários estão linkados com os léxicos?| Resposta|Não, os cenários que envolviam [Streamer](Streamer) possuiam dois léxicos distintos.| Modificações|O léxico correto foi mantido e os *hyperlinks* dos léxicos foram consertados| Commit|ef44e3b| Questões|9 - Os atores estão linkados com os léxicos? Resposta|Não, Usuários não possuiam léxicos, [Streamer](Streamer) e [Viewer](Viewer) possuiam algumas menções sem representação de seus léxicos| Modificações|Todos atores foram linkados com seus respectivos léxicos. O léxico de Usuário teve de ser criado para adequar aos padrões| Commit|[e9343e0](_compare/e9343e0),[a626ec](_compare/a626ec)| Questões|10 - Os links para os léxicos estão funcionando? Resposta|Sim| Modificações|Nenhuma| Commit|-| #### Léxicos |Item de Inspeção|Léxico| |------|-------| |Questões|1 - Os sinônimos dos léxicos possuem e seguem uma padronização?| |Resposta|Sim| |Modificação|Nenhuma| |Commit|-| |Questões|2 - As noções dos léxicos possuem e seguem uma padronização?| |Resposta|Sim| |Modificação|Nenhuma| |Commit|-| |Questões|3 - Os impactos dos léxicos possuem e seguem uma padronização?| |Resposta|Sim| |Modificação|Nenhuma| |Commit|-| |Questões|4 - Todos os impactos estão definidos?| |Resposta|Sim| |Modificação|Nenhuma| |Commit|-| |Questões|5 - Os léxicos contém sinônimos?| |Resposta|Não todos, mas mais de 90%, então não há necessidades de mudanças| |Modificação|Nenhuma| |Commit|-| |Questões|6 - Os links dos léxicos estão funcionando?| |Resposta|Não, alguns não estavam linkados(viewer, streamer, stream) outros estavam com links quebrados| |Modificação|Links reparados e funcionando corretamente| |Commit|[718fe4054](_compare/718fe4054)| <file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |23/05/2018|0.1|Criação do Documento|<NAME>| |23/05/2018|0.2|Adição Questionário|<NAME>| |23/05/2018|0.3|Atualização do documento|<NAME>| |08/06/2018|0.4|Revisão|<NAME>| ### Planejamento O grupo, como um todo, decidiu por dividir temas em duplas, visando identificar erros a serem corrigidos, para que fosse possível realizar o método escolhido para aplicação da Inspeção. O documento a ser inspecionado será o iStar. ## Visão Geral O Framework i*, fundamentalmente, é orientado à diagramas, onde, estes possuem duas divisões, os diagramas Strategic Dependency (SD) e Strategic Rationale (SR), onde o primeiro possui uma abordagem interativa entre os atores determinados e o segundo, possui uma visão mais focalizado nos atores e seus papeis individuais. Os Diagramas i*, são mais adequados para as fases iniciais do desenvolvimento de um software, onde, este framework visa facilitar a compreensão do domínio do problema que o desenvolvedor tem em mãos. Neste documento, teremos os diagramas i* SR e SD, elaborados pela equipe de Requisitos de Software, responsável pela plataforma Twitch.tv, no primeiro semestre de 2018. Todos os diagramas foram feitos utilizando a ferramenta piStar. Acesso ao [Diagrama iStar](Diagramas-i*) ### Preparação A técnica utilizada para a inspeção dos documentos será a Leitura Baseada em Checklist(LBCh). Essa técnica é composta de uma lista de perguntas que ajuda os inspetores a encontrarem uma lista de defeitos no produto durante a inspeção. O final, será desenvolvido um quadro de classificação de defeitos de acordo com o resultado obtido da inspeção. ### Realização da inspeção [Checklist I*](Checklist-I*) ### Retrabalho Os membros do grupo identificaram os erros e a correção foi realizada e revisada. ### Verificação Todos os erros encontrados foram corrigidos. <file_sep>Data|Versão|Descrição|Autor -----|------|---------|------- 24/04/2018|1.0|Criação do documento|<NAME>| 25/04/2018|1.1|Adição da Sprint Backlog|<NAME>| # Sprint Backlog ## Sprint 1 Essa primeira sprint será designada ao desenvolvimento das histórias do épico 1. No dia 24/04/2018 todos com componentes do grupo se reuniram via hangouts para o planejamento da primeira sprint, ou seja, foi feita o _Sprint Planning Meeting_. Depois que as histórias de usuários estavam definidas, foi feito um formulário para pontuar tecnicamente as histórias de usuário. * Imagem da reunião feita via hangouts <img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Reunioes/reuniao_24-04-2018.jpg" width=900px> #### EP01 - Eu, como usuário, desejo gerenciar meu cadastro na twitch. * Pré-rastreabilidade - [Cadastro e conexão pelo facebook US01 e US02](Cen%C3%A1rio-002) - [Twitch Prime US05](Assinar-Twitch-Prime) - [Twitch Partner US06](Argumenta%C3%A7%C3%A3o) |História|Descrição|Pontuação| |----|---------|-------| |US01|Eu, como usuário, desejo criar uma conta na Twitch para desfrutar dos serviços de streaming.|8| |US02|Eu, como usuário, desejo utilizar a Twitch me conctando pelo facebook para acessar mais rápido os serviços de streaming.|5| |US03|Eu, como usuário, desejo editar meu perfil na Twitch para manter meus dados atualizados.|5| |US04|Eu, como usuário, desejo desabilitar minha conta da Twitch para não ter acesso as funcionalidade de um usuário Twitch.|3| |US05|Eu, como usuário, desejo me tornar um usuário da Twitch Prime para ter acesso a funcionalidades diferenciadas do Twitch.|13| |US06|Eu, como usuário, desejo me tornar um parceiro da Twitch para monetizar minhas streams.|20| <file_sep># UC20 - Hospedagem * [Diagrama de Caso de Uso](Diagrama-Hospedagem) ## Descrição * Este caso de uso descreve o sistema de hospedagem de stream em outros canais ## Atores * Usuário - [Streamers](Streamer) ## Pré-condições * O usuário não deve ter uma stream ativa ## Fluxo de Eventos ### Fluxo Principal * 1. O usuário acessa o painel de controle * 2. O usuário se direciona à sub-secção de ```Host``` na secção ```Ao Vivo``` do painel * 3. O usuário abre as configurações do serviço de hosting * 4. O usuário ativa a opção de hospedagem automática [FA01] * 5. O usuário seleciona os canais que ele gostaria de hospedar [FA02][FE01] * 6. O usuário salva as alterações * 7. O caso de uso é encerrado ### Fluxos Alternativos #### FA01 - Hospedagem de Equipe * 1. O usuário ativa a opção de hospedar canais da equipe do usuário (se esta existir), de forma aleatória, automaticamente. * 2. O usuário retorna ao passo 6 do fluxo principal. #### FA02 - O usuário seleciona a opção de hospedagem de canais semelhantes ao dele * 1. O usuário ativa a opção de hospedar canais semelhantes ao dele. * 2. O usuário retorna ao passo 6 do fluxo principal. ### Fluxo de Exceção #### FE01 - O usuário não segue nenhum canal. * Essa excessão ocorre pois o usuário não é seguidor de nenhum canal. * 1. O sistema não exibe nenhum canal a ser hospedado pelo usuário. * 2. O fluxo de excessão se encerra. ## Pós-condição * O canal do usuário agora hospeda, automaticamente os canais selecionados ou associados automaticamente pela twitch<file_sep># Cenário 016 - Selecionar [moderadores](Mods) ## Título * Moderadores de (chat)[Group-Chat] ## Objetivo * Fazer um usuário possuir privilégios administrativos no chat. ## Contexto * Durante uma transmissão. ## Ator(es) * [Streamer](Streamer) * [Viewer](Viewer) ## Recursos * Dispositivo eletrônico conectado à internet. ## Exceções * Não possuir poderes administrativos. * Não ter cadastro. * Estar banido. ## Episódios * [Streamer](Streamer) simpatiza com algum [viewer](Viewer) * [Streamer](Streamer) clica no nome do [viewer](Viewer) * [Streamer](Streamer) seleciona a opção de ```Moderador``` * [Viewer](Viewer) se torna moderador. <file_sep># Cenário 0019 - Acessar videos postados em um canal. ## Título * Acessar videos postados em um canal. ## Objetivo * Descrever como conseguir assistir videos postados em um canal. ## Contexto * Pessoa busca se entreter. * Pessoa busca aprender a respeito de um jogo. ## Ator(es) * [Usuário](User) ## Recursos * Dispositivo conectado a internet. ## Exceções * [Usuário](User) não consegue achar a funcionalidade ## Episódios * [Usuário](User) abre um canal específico da [Twitch.tv](http://www.twitch.tv) * [Usuário](User) clica em vídeos * [Usuário](User) seleciona um vídeo específico * [Usuário](User) assiste o vídeo<file_sep>import os import subprocess path = input("Insert path containing lexers: ") os.chdir(path) lexers = { 'Streamer': '[Streamer](Streamer)', 'streamer': '[streamer](Streamer)', 'Streamers': '[Streamers](Streamer)', 'streamers': '[streamers](Streamer)', 'Viewer': '[Viewer](Viewer)', 'viewer': '[viewer](Viewer)', 'Clipe': '[Clipe](Clipe)', 'clipe': '[clipe](Clipe)', 'Whisper': '[Whisper](Whisper)', 'whisper': '[whisper](Whisper)', 'Streamar': '[Streamar](Streamar)', 'streamar': '[streamar](Streamar)', 'Streaming': '[Streaming](Streaming)', 'streaming': '[streaming](Streaming)', 'Raid': '[Raid](Raid)', 'raid': '[raid](Raid)', 'Ban': '[Ban](Ban)', 'ban': '[ban](Ban)', 'Donate': '[Donate](Donate)', 'donate': '[donate](Donate)', 'Share': '[Share](Share)', 'share': '[share](Share)', 'Mods': '[Mods](Mods)', 'mods': '[mods](Mods)', 'Chat': '[Chat](Group-Chat)', 'chat': '[chat](Group-Chat)', 'Follower': '[Follower](Follower)', 'follower': '[follower](Follower)', 'followers': '[followers](Follower)', } regexes = {} for k, v in lexers.items(): match = ' ' + k + "$" replacement = ' ' + v regexes[match] = replacement print(f"Working on {os.getcwd()}\n") print(f"Looking for regexes: {regexes.keys()}\n") for match, replacement in regexes.items(): sed_arg = '"s/' + match + '/' + replacement + '/g"' command = f'sed -i {sed_arg} *.md' subprocess.call([command], shell=True) print('Done linking all given lexers!!!') <file_sep># UC11 - [Chat](Group-Chat) de Voz e Video ### [Diagrama de caso de uso](Diagrama-Chat-de-Voz) ## Descrição * Este caso de uso descreve a funcionalidade da plataforma desktop de video conferência ## Atores * Usuário ## Pré-condições * O usuário deve estar conectado à internet * O usuário deve possuir o aplicativo de desktop ou o aplicativo móvel ## Fluxo de Eventos ### Fluxo Principal * 1. O usuário acessa a plataforma desktop * 2. Seleciona a opção de [chat](Group-Chat) de voz * 3. O usuário convida um amigo para o [chat](Group-Chat) de voz[FA01] * 4. O usuário convidado aceita o convite * 5. O caso de uso se encerra ### Fluxos Alternativos #### FA01 - O usuário entra em uma sala de chamada de um servidor * 1. O usuário entra na sala de um servidor * 2. O usuário retorna ao item 5 do fluxo principal ### Fluxo de Exceção * Não se Aplica ## Pós-condição * O usuário agora está em uma chamada de voz e/ou video.<file_sep># Cenário 020 - Acessar clipes postados em um canal. ## Título * Acessar clipes postados em um canal. ## Objetivo * Descrever como conseguir assistir clipes postados em um canal. ## Contexto * Pessoa busca se entreter. * Pessoa busca ver jogadas incríveis ou bem ruins para se distrair. ## Ator(es) * [Usuário](User) ## Recursos * Dispositivo conectado a internet. ## Exceções * [Usuário](User) não consegue achar a funcionalidade ## Episódios * [Usuário](User) acessa um canal * [Usuário](User) seleciona a aba ```Clipes``` * [Usuário](User) seleciona o clipe específico * [Usuário](User) assiste o clipe da stream<file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |24/04/2018|1.0|Criação do Documento |<NAME>| |24/04/2018|1.1|Adição das US do EP04|Gustavo Carvalho| |24/04/2018|1.2|Adição das US's do EP03,EP05 e EP06|<NAME>| |24/04/2018|1.3|Adição das US do EP01|Amanda Pires| |25/04/2018|1.4|Adição das US do EP02|<NAME>| |25/04/2018|1.5|Adição das US do EP07|Jo<NAME>| |25/04/2018|1.6|Revisão dos épicos|<NAME> e <NAME>| |25/04/2018|1.7|Adição de tipos de Requisitos|Filipe Dias| |25/04/2018|1.8|Adicionando ordenação e pré-reastreabilidade|Amanda Pires| |29/04/2018|1.8|Atualizando temas|Amanda Pires| |01/05/2018|1.9|Atualizando prioridades|Filipe Dias| |26/05/2018|2.0|Adcionando critérios de aceitação nas US|Gustavo Carvalho| |27/05/2018|2.1|Colocando as US no formato: ``` As <persona> , I want <what?> so that <why?> ```|<NAME>| |27/05/2018|2.2|Adição tabela geral|Gust<NAME>| |29/05/2018|2.3|Critérios de Aceitação EP#05 |<NAME>| |09/06/2018|2.4|Adição das US42 a US52|<NAME>| |10/06/2018|2.5|Redefinição das prioridades para o padrão MosCoW(Must,Should,Could)|<NAME>| Este Artefato será composto pelos Épicos do projeto da Twitch, estes sendo divididos em histórias de usuário que compõe cada épico. ## Temas * 1. Cadastro = [EP01](#ep01---eu-como-usu%C3%A1rio-desejo-gerenciar-meu-cadastro-na-twitch) * 2. Stream = [EP02](#ep02---eu-como-usu%C3%A1rio-desejo-usufruir-servi%C3%A7os-relacionados-a-streaming-na-twitchtv) e & [EP03](#ep03---eu-como-usu%C3%A1rio-desejo-gerenciar-um-v%C3%ADdeo-na-twitchtv-para-visualiza%C3%A7%C3%A3o-da-comunidade) * 3. Comunicação = [EP06](#ep06---eu-como-usu%C3%A1rio-desejo-poder-fazer-uso-de-confer%C3%AAncias-de-voz-para-me-comunicar-com-outras-pessoas) e [EP04](#ep04---eu-como-usuário-desejo-me-comunicar-com-outros-usuários) * 4. [Add-ons](Mods) [EP05](#ep05---eu-como-usu%C3%A1rio-desejo-gerenciar-add-ons-pela-twitch-para-usufruir-de-maiores-funcionalidades-em-determinados-jogos) * 5. Finanças = [EP07](#ep07---eu-como-usu%C3%A1rio-desejo-poder-contribuir-financeiramente-com-canais-e-com-a-twitch-para-incentivar-eou-recompensar-pelo-entretenimento-fornecido) ## Épicos |Épico|Descrição|Para que| |----|---------|---| |EP01|Eu, como usuário, desejo gerenciar meu cadastro na twitch.|Eu possa ter um maior controle sobre minha conta| |EP02|Eu, como usuário, desejo usufruir serviços relacionados a streaming na twitch.tv|Eu tenha a melhor experiência com streams| |EP03|Eu, como usuário, desejo gerenciar um vídeo na twitch.tv| Tenha um maior controle do conteúdo postado.| |EP04|Eu, como usuário, desejo me comunicar com outros usuários |Haja maior interatividade entre os usuários.| |EP05|Eu, como usuário, desejo gerenciar [add-ons](Mods) pela twitch|Eu possa usufruir de maiores funcionalidades em determinados jogos| |EP06|Eu, como usuário, desejo poder fazer uso de conferências de voz|seja possível se comunicar com outras pessoas| |EP07|Eu, como usuário, desejo poder contribuir financeiramente com canais e com a twitch|Eu possa incentivar e/ou recompensar pelo entretenimento fornecido.| ## Histórias de Usuário #### EP01 - Eu, como usuário, desejo gerenciar meu cadastro na twitch. |Tipo|História|Descrição|Critérios de Aceitação|Pontuação|Prioridade| |----|----|---------|-------|-----|-----| |RF|US01|Eu, como usuário, desejo [criar uma conta](Cen%C3%A1rio-002) na Twitch para desfrutar dos serviços de streaming.|Ter os seguintes campos no formulário inscrição: nome de usuário, email, data de nascimento e senha.<br>Possuir captcha |8|Must| |RNF|US02|Eu, como usuário, desejo utilizar a Twitch me conectando pelo facebook para acessar mais rápido os serviços de streaming.|Opções de poder logar com o Facebook devem estar disponíveis nas áreas de "login" e "cadastra-se".|5|Could| |RF|US03|Eu, como usuário, desejo [editar meu perfil](Cen%C3%A1rio-023) na Twitch para manter meus dados atualizados.|Dados atuais devem aparecer previamente nos campos de edição como máscara.|5|Should| |RF|US04|Eu, como usuário, desejo desabilitar minha conta da Twitch para não ter acesso as funcionalidade de um usuário Twitch.|Senha deve ser digitada novamente para que a conta seja desativida|3|Must| |RF|US05|Eu, como usuário, desejo me tornar um usuário da [Twitch Prime](Assinar-Twitch-Prime) para ter acesso a funcionalidades diferenciadas do Twitch.|O usuário deve ter a opção de pagar usando algum meio de pagamento, ou simplesmente utilizar da Twitch Prime como meio.|13|Must| |RF|US06|Eu, como usuário, desejo me tornar um parceiro da Twitch para monetizar minhas streams.|Streamers devem ter "x" quantidade de vizualições.|20|Must| |RF|US42|Eu, como usuário, desejo poder recuperar minha senha e nome de usuário caso eu tenha esquecido, para que assim eu possa acessar a plataforma.|Para redefinição de senha cobrar email e nome de usuário. Para recuperação do nome de usuário, deverá ser informado email.| - |Must| #### EP02 - Eu, como usuário, desejo usufruir serviços relacionados a streaming na twitch.tv |Tipo|História|Descrição|Critérios de Aceitação|Prioridade| |----|----|---------|---|-----| |RF|US07|Eu, como viewer, gostaria poder [compartilhar uma stream](Cen%C3%A1rio-030) que estou assistindo para que meus amigos possam assistir também.|Um botão "compartilhar" deve estar embaixo de todas as streams, onde o usuário, poderá escolher a plataforma de compartilhamento, ou simplesmente copiar o link da stream.|Must| |RF|US08|Eu, como viewer, gostaria de seguir um streamer para que eu possa ser notificado de seus suas atualizações na Twitch.|Ao seguir um streamer, o contador de seguidores do mesmo, deverá ser atualizado, assim como a lista de "canais seguidos" do viewer.|Should| |RF|US09|Eu, como usuário, gostaria de acessar os [chats](Group-Chat) para participar das discussões.|Alguns [chats](Group-Chat) devem ter limitações para não seguidores.|Could| |RF|US10|Eu, como streamer, desejo ter a opção de filtrar quem digita no [chat](Group-Chat) da minha stream, para que eu possa ter maior controle sobre meu ambiente de transmissão.|Poder colocar limitação de tempo em relação a participação de usuários.|Could| |RF|US11|Eu, como streamer, gostaria de ter a possibilidade de [banir alguém](Cen%C3%A1rio-027) do [chat](Group-Chat) de minha stream, para evitar que pessoas tumultuem minha transmissão.|Pessoas indesejadas pelo streamer não poderão participar do [chat](Group-Chat) de uma live específica, ou de uma canal.|Could| |RF|US12|Eu, como streamer, gostaria de alterar o jogo que estou jogando na minha stream, sem que seja necessário começar outra transmissão, para minha stream ter maior fluidez. | A transmissão não devera ser afetada durante o processo. Conexão dos viewers a stream deverá permanecer estável durante o processo. |Should| |RF|US13|Eu, como usuário, gostaria de visualizar [chats](Group-Chat) de uma stream sem precisar estar logado para que eu possa saber o que está sendo comentado|Usuários não logados não poderão enviar mensagens.|Could| |RF|US43|Eu, como usuário, desejo poder assistir uma stream sem estar logado, para que assim eu não perca tempo me cadastrando.|Funcionalidades como enviar mensagens em chats, seguir, comentar, se inscrever em canais e sussuros deverão estar indisponíveis para usuários não logados. Limitando somente a funcionalidades básicas de um viewer. |Could| |RF|US44|Eu, como usuário, desejo criar criar clipes das streams, para que eu possa compartilhar com meus amigos ou redes sociais.|Clipes não deverão passar de 60s de extensão. Tempo mínimo de um clip deverá ser de 5s. Será obrigatório colocar um titúlo no clip para salva-lo.|Could| |RNF|US45|Eu, como usuário, desejo que a twitch tenha uma boa usabilidade, para que assim fique mais fácil e intuitivo navegar pela plataforma e assistir streams.|Interface deverá obdercer uma regra estrita de design, tais como: palhetas de cores padrão, caixas de diálogo não invasivas, funcionalidades importantes e de maior usabilidade deverão estar de fácil de acesso.|Should| |RFN|US50|Eu, como usuário, desejo que a Twitch esteja sempre no ar(24h/7), para que assim eu possa acessa-la a qualquer hora.|Sistema deverá estar no ar 24h por dia, sem nenhuma janela de intervalo.|Must|. |RFN|US51|Eu, como usuário, desejo que a Twitch seja portável, para que eu tenha maior flexibilidade para acessar a plataforma de múltiplos meios.|Site deverá ter responsividade para que seja possível acessa-lo pelo navegador do celular/tablet. Apps para mobile e desktop.|Must| |RF|US52|Eu, como usuário, desejo poder escolher o idioma no site da twitch, para que eu possa usar a interface caso não saiba falar inglês.|Idiomas: Inglês, espanhol, português, russo, alemão, japonês, chines, coreâno, tailandês.|Must| #### EP03 - Eu, como usuário, desejo gerenciar um vídeo na twitch.tv para visualização da comunidade |Tipo|História|Descrição|Critérios de Aceitação|Prioridade| |-----|----|---------|---|---| |RF|US14|Eu, como streamer, desejo subir um vídeo na plataforma, para que eu possa divulgar minhas streams. |Arquivos corrompidos devem ser negados. <br> Vídeos para 'upload' devem ser comprimidos ou otimizados para facilitar seu armazenamento.|Must| |RF|US15|Eu, como streamer, gostaria de deletar um vídeo que eu subi na plataforma para que eu possa ter maior controle sobre meu conteúdo.|Uma verificação de dois passos é necessária, para que exclusões acidentais não ocorra.|Must| |RF|US16|Eu, como streamer, gostaria de programar uma premiere para meu vídeo para que eu possa divulgar meu trabalho.| - |Should| |RF|US17|Eu, como streamer, gostaria de gravar uma transmissão anterior em vídeo para que eu possa compartilha-la mais tarde.| Um catálago com as gravações deverá ser fornecida na página do streamer. |Could| |RF|US18|Eu, como streamer gostaria de destacar um vídeo para este ter maior visualização.| Vídeo deverá aparecer em lugar de destaque para que os viewers possam ver |Could| |RNF|US46|Eu, como streamer, desejo que a twitch consiga suportar um grande número de visitas, para que assim a plataforma consiga lidar com o grande número de viewers que eu possa ter.|Sistema deverá ser capaz de lidar com visitas na faixa dos 800 milhões.|Must| |RNF|US49|Eu, como viewer, desejo que a transmissão tenha fluídez, para que assim ela não fique travando.|Transmições não poderão apresentar atrasos significativos que atrapalhem o acompanhamento de alguma stream.|Must| #### EP04 - Eu, como usuário, desejo me comunicar com outros usuários |Tipo|História|Descrição|Critérios de Aceitação|Prioridade| |----|----|-----|-----|-----| |RF|US19|Eu, como usuário, desejo poder buscar outros usuários para que eu possa achar possíveis amigos.| Poder buscar tanto com caixa Must ou não. Informar quando não achar um usuário correspondente a busca.|Could| |RF|US20|Eu, como usuário, desejo poder adicionar como amigo outros usuários para que eu possa aumentar a minha interatividade com a comunidade.| Poder somente enviar pedidos de amizades para pessoas que não me bloquearam|Could| |RF|US21|Eu, como usuário, desejo poder mandar [mensagens de texto privadas](Mensagens-Privadas) para poder me comunicar com outros usuários.| Poder selecionar o usuário de destino.|Could| |RF|US22|Eu, como viewer, desejo poder participar de [chats](Group-Chat) durante as streams para poder comentar cenas da transmissão.| Se uma transmissão acabar o [chat](Group-Chat) deve acabar também. |Could| |RF|US23|Eu, como usuário, desejo poder mandar emoticons em conversas para poder aumentar a interatividade.| Um conjunto de caracteres, ou somente um, deve corresponder a um emoticon.|Should| |RF|US24|Eu, como usuário, desejo bloquear alguém em uma conversa para que eu possa evitar usuários indesejados.| Um usuário bloqueado não pode ter mais a capacidade de achar o bloqueador.|Must| #### EP05 - Eu, como usuário, desejo gerenciar add-ons/mods pela Twitch para usufruir de maiores funcionalidades em determinados jogos |Tipo|História|Descrição|Critérios de Aceitação|Prioridade| |----|------|----------|----|----| |RF|US25|Eu, como usuário, gostaria de [sincronizar os add-ons](Adi%C3%A7%C3%A3o-de-Add-ons-em-Jogos) com meus jogos.| A plataforma disponibiliza a opção de sincronizar os mods Coulddos com o jogo em questão |Must| |RF|US26|Eu, como usuário, gostaria de de filtrar o tipo de mod que eu vejo.| A plataforma de pesquisa permite aplicar um filtro categórico sobre os mods exibidos |Should| |RF|US27|Eu, como usuário, gostaria de instalar novos mods.| A plataforma disponibiliza o download de mods |Must| |RF|US28|Eu, como usuário, gostaria de deletar mods.| A plataforma permite a exclusão de mods já instalados |Must| |RNF|US29|Eu, como usuário, gostaria de disponibilizar novos mods para a comunidade.| O usuário comum possa subir um mod de sua autoria à plataforma para download dos demais usuários |Must| |RNF|US30|Eu, como usuário, gostaria de atualizar os mods de forma automatizada.| Quando existem atualizações disponíveis a plataforma deve atualizar automaticamente os jogos quando aberta ou disponibilizar a opção de atualizar todos os mods |Should| #### EP06 - Eu, como usuário, desejo poder fazer uso de conferências de voz para me comunicar com outras pessoas |Tipo|História|Descrição|Critérios de Aceitação|Prioridade| |----|----|---------|-|-| |RF|US31|Eu, como usuário, gostaria de poder criar uma nova chamada de voz para poder comunicar com outros usuários.|Limitação de até 5 pessoas.|Could| |RF|US32|Eu, como usuário, gostaria de poder filtrar quem entrar na chamada para que assim eu possa ter maior controle com quem eu falo.|Usuários só poderão entrar em uma chamada por meio de um link, ou se convidados.|Could| |RF|US33|Eu, como usuário, desejo fazer uma vídeo conferência para poder falar com meus amigos da twitch. |Limitação de até 5 pessoas. <br> Resolução HD|Could| |RF|US34|Eu, como usuário, desejo fazer uso de uma video conferência em um servidor.| - |Could| |RF|US35|Eu, como usuário, desejo criar um grupo para chamadas permanente para facilitar iniciar conversas com o mesmo grupo sempre.|Possibilidade de gerenciar grupos (deletar, editar, criar).|Could| #### EP07 - Eu, como usuário, desejo poder contribuir financeiramente com canais e com a Twitch, para incentivar e/ou recompensar pelo entretenimento fornecido |Tipo|História|Descrição|Critérios de Aceitação|Prioridade| |----|----|---------|--|---| |RNF|US36|Eu como viewer, gostaria de opções de planos mensais de inscrições em um canal para que eu possa escolher o valor e as vantagens que mais me agrada.|Oferecer opções mensais, trimestrais e semestrais. <br> Possibilidade de pagar com cartão de crédito, transferência bancaria ou dinheiro.|Must| |RF|US37|Eu como viewer, desejo me inscrever em um canal para poder ter mais vantagens nesse canal.|Opção de se inscrever devem estar visíveis junto a stream. <br> Ter a possibilidade de uma avaliação gratuita ao se inscrever.|Must| |RF|US38|Eu como viewer, desejo comprar bits para poder doar aos streamers.|Oferecer pacotes de bits, e não a venda unitária.|Must| |RNF|US39|Eu como usuário, desejo assinar o serviço twitch prime para receber uma série de vantagens em todo o site.|Assinantes da Amazon Prime poderão ter acesso a Twtich Prime por meio de uma validação de login da Amazon|Must| |RF|US40|Eu como viewer, desejo doar bits para um streamer para poder incentivar o seu trabalho.|Poder escolher a quantidade de bits|Must| |RF|US41|Eu como usuário, desejo aderir ao twitch turbo para receber mais recursos na Twitch.|Anuncios não poderão aparecer para aqueles que aderirem ao Twitch Turbo. <br> |Must| |RNF|US47|Eu, como usuário, desejo que a twitch sejaum ambiente seguro para transações financeiras, para que assim eu possa incentivar financeiramente a comunidade da plataforma.|Validação de pagamentos, segurança em conta de usuários, banco de dados integro e seguro, encriptação de informações dos meios de pagamentos.|Must| |RNF|US48|Eu, como usário, desejo que a twitch tenha um bom sistema de login, para que ninguém consiga hackear minha conta.|Uso de captchas para evitar tentativas de loggins autonômos.|Must| <file_sep>**Sinônimos:** * Moderator * Mod **Noção:** * Pessoa escolhidas pelo [streamer](Streamer) ou [twitch](Twitch) para garantir o cumprimento das regras no [chat](Group-Chat). **Impacto:** * O moderador [Baniu](Ban) o [usuário](User) que estava sendo incômodo no [chat](Group-Chat). * O moderador alterou as permissões do [chat](Group-Chat). <file_sep>### Diagrama UC14 <img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/Alterar%20titulo.png?raw=true" width=900px> ### [Especificação de Caso de Uso](Alterar-nome-da-stream)<file_sep>## Diagrama de Caso de Uso da UC19 - Criar Vídeo <img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/UC19.png" width=900px> ### [Especificação de Caso de Uso](Criação-de-video)<file_sep># Cenário 032 - Adicionar amigos ## Título * [Usuário](User) adiciona amigos ## Objetivo * Descrever como um usuário adiciona outro usuário como amigo.. ## Contexto * [Usuário](User) adiciona outro usuário ## Ator(es) * [Usuário](User) ## Recursos * Dispositivo eletrônico conectado à internet ## Exceções * [Usuário](User) não acha o perfil desejado. * [Usuário](User) desiste de adicionar perfil. ## Episódios * [Usuário](User) busca perfil de usuário que deseja adicionar. * [Usuário](User) clica no ícone de adicionar no canto direito do perfil encontrado. <file_sep># Cenário 015 - Fazer login ## Título * Efetuar login ## Objetivo * Ser autenticado na Twitch ## Contexto * Cadastrado na twitch. ## Ator(es) * Usuário ## Recursos * Dispositivo eletrônico conectado à internet. ## Exceções * Apenas ver stream. * Esquecer login ou senha. ## Episódios * [Usuário](User) acessa a Twitch * [Usuário](User) efetua login, clicando em ```Fazer login``` * [Usuário](User) preenche os campos requeridos * [Usuário](User) é autenticado <file_sep># Cenário 014 - Fechar [transmissão](Stream) ## Título * Encerar transmissão ## Objetivo * [Streamer](Streamer) encerrar a stream. ## Contexto * [Streamer](Streamer) streamando. ## Ator(es) * [Streamer](Streamer) . ## Recursos * Dispositivo eletrônico conectado à internet. ## Exceções * Não estiver em transmissão. ## Episódios * [Streamer](Streamer) está streamando * [Streamer](Streamer) deseja encerrar sua transmissão * [Streamer](Streamer) vai para as configurações da transmissão * [Streamer](Streamer) clica na opção ```Parar stream```. <file_sep><img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/criarConta.png" width=900px> ### [Especificação de Caso de Uso](Criar-Conta)<file_sep># UC16 - Banir [Viewer](Viewer) ## Descrição * Esse caso de uso descreve o processo de banimento de um Viewer. ## Atores * [Streamer](Streamer) * [Viewer](Viewer) ## Pré-condições * O usuário deverá ter acesso à internet * O streamer deverá estar streamando ## Fluxo de Eventos ### Fluxo Principal * 1. O streamer abre o stream * 2. O streamer localiza no seu [chat](Group-Chat), um viewer indesejado * 3. O streamer clica no nome do [viewer](Viewer) * 4. O streamer seleciona 🕒 * 5. O streamer bane o viewer do seu [chat](Group-Chat) pelo tempo desejado ### Fluxos Alternativos * Não se aplica ### Fluxo de Exceção * Não se aplica ## Pós-condição * O viewer que foi banido não poderá mais participar do [chat](Group-Chat) do streamer que o baniu.<file_sep><img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/transmitir.png" width=900px> ### [Especificação de Caso de Uso](Transmissão-multimidia)<file_sep><img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/UC-13.png" width=900px> ### [Especificação de Caso de Uso](Assinar-twitch-prime)<file_sep><a href="https://docs.google.com/presentation/d/1aucPIk32PxsxJVI1IDeIiZqK2XRLgTx5AfZ3UzTlVVM/edit?usp=sharing"> <img src="http://www.tioorlando.com.br/wp-content/uploads/2013/10/Toon-Link.jpg"> </a><file_sep>## Reagir **Sinônimos:** * Mostrar reação * Enviar Reação **Noção:** * Ato de selecionar um [emote](Emotes) para demonstrar sua opnião/sentimento sobre uma postagem de um [streamer](Streamer). **Impacto:** * Os [espectadores](Viewer) reagiram mal à atitude do [Streamer]. * [Espectadores](Viewer) reagiram por meio de [emotes](Emotes).<file_sep> ## [Streaming](Streaming) **Sinônimos:** * Transmissão. **Noção:** * Tecnologia de envio e captação de informação multimídia em tempo real. **Impacto:** * A [Twitch](Twitch) é uma plataforma de [Streaming](Streaming) * Muitos [usuários](User) acessam a [Twitch](Twitch) por ser uma grande plataforma de streaming.<file_sep>* Checklist de Inspeção da Checklist de Elicitação * Inspetor: <NAME> * Data: 10/05/2018 ### Checklist dos itens de inspeção - [X] Plano de Elicitação de Requisitos - [X] Questionário - [X] Storytelling - [X] Análise de Protocolo + Observação Participativa - [X] Introspecção * Técnicas Utilizadas: - [ ] Introspecção - [ ] Análise de Protocolo - [ ] Questionário - [ ] Storytelling - [ ] Observação Participativa #### 1. Plano de Elicitação de Requisitos |Item de Inspeção|Plano de Elicitação de Requisitos| |------|-------| Questões|1. O documento está anexado ao projeto?| Resposta|Sim| Modificações|Inserção do Documento| Questões|2. O plano informa as técnicas que serão utilizadas no projeto?| Resposta|Sim| Modificações|Nenhuma| Questões|3. Existe uma breve explicação do que é cada técnica? Resposta|Não| Modificações|A definir| #### 2. Questionário |Item de Inspeção|Questionário| |------|-------| Questões|1. O documento está anexado ao projeto?| Resposta|Sim| Modificações|Nenhuma| Questões|2. Todas as perguntas levantadas no questionário foram inseridas no documento?| Resposta|Sim| Modificações|Nenhuma| Questões|3. A ferramenta utilizada para realizar o questionário está sendo citada no documento? Resposta|Sim| Modificações|Inserção da ferramente utilizada| Questões|4. O questionário possui clareza nas suas questões?| Resposta|Sim| Modificações|Nenhuma| Questões|5. É possível identificar a porcentagem e quantidade de pessoas participantes?| Resposta|Sim| Modificações|Nenhuma| #### 3. Storytelling |Item de Inspeção|Storytelling| |------|-------| Questões|1. Existe uma breve explicação da técnica?| Resposta|Sim| Modificações|Inserção da explicação da técnica| Questões|2. O objetivo deixa claro o que é almejado alcançar com a técnica?| Resposta|Sim| Modificações|Inserção do objetivo| Questões|3. A história contada condiz com a realidade? Resposta|Sim| Modificações|Nenhum| Questões|4. É possível elicitar requisitos baseados na história contada?| Resposta|Sim| Modificações|Nenhuma| Questões|5. A ferramenta utilizada está sendo citada?| Resposta|Sim| Modificações|Inserção da ferramenta| #### 4. Análise Protocolo + Observação Participativa |Item de Inspeção|Observação Participativa| |------|-------| Questões|1. Existe uma breve explicação da técnica?| Resposta|Sim| Modificações|Inserção de uma breve explicação da técnica| Questões|2. O objetivo deixa claro o que é almejado alcançar com a técnica?| Resposta|Sim| Modificações|Inserção do objetivo| Questões|3. O documento abrange todo o público alvo da [Twitch](Twitch)? Resposta|Sim| Modificações|Nenhuma| Questões|4. O documento levou a um maior entendimento do funcionamento da plataforma?| Resposta|Sim| Modificações|Nenhuma| #### 5. Introspecção |Item de Inspeção|Introspecção| |------|-------| Questões|1. Existe uma breve explicação da técnica? Resposta|Sim| Modificações|Inserção de uma breve explicação| Questões|2. O objetivo deixa claro o que é almejado alcançar com a técnica?| Resposta|Sim| Modificações|Inserção do objetivo| Questões|3. O método utilizado para se levantar as histórias de usuário está sendo citado?| Resposta|Sim| Modificações|Inserção do método| [Respostas da Checklist](Respostas-Checklist-Elicita%C3%A7%C3%A3o) <file_sep> Follower **Sinônimos:** * Seguidor **Noção:** * Pessoa que acompanha algum [streamer](Streamer) através da funcionalidade integrada da twitch de [Dar Follow](Dar-follow) **Impacto:** * O seguidor recebeu uma [notificação](Live-Notification) do canal que ele [segue](Dar-Follow). * O [Usuário](User) que seguiu um canal agora é um [Follower](Follower)<file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |23/05/2018|0.1|Criação do Documento e Desenvolvimento Parcial|<NAME>| |28/05/2018|0.2|Inspecção com base na checklist de caso de uso|<NAME>| |01/05/2018|0.3|Modificações solicitadas pela checklist de caso de uso|<NAME>| ### Planejamento A Priori, o grupo decidiu dividir as verificações de inspecções por membro, onde, em primeira instância, cada membro faria a verificação de um tópico de documentação, a ideia a posteriori é que a verificação seja verificada também, para difundir melhor qualidade através da documentação produzida. Neste documento, está representado a verificação realizada para os artefatos de caso de uso produzidos, tanto a especificação destes, os diagramas, quanto a especificação suplementar. ### Visão Geral Artefatos produzidos durante a etapa de levantamento da especificação suplementar e casos de uso: * [Especificação de Caso de Uso](Especificação-de-Casos-de-Uso) * [Especificação Suplementar](Especificação-Suplementar) * [Diagramas de Caso de Uso](Diagramas-de-Casos-de-Uso) ### Preparação * Estabeleceu-se um padrão determinado para os casos de uso e confirmou-se que os membros responsáveis pela inspecção do documento, estivessem apropriadamente aptos a fazer um revisão em tal nível, possuindo conhecimento a respeito da produção desses artefatos e nos casos específicos da documentação a ser revisada. * A equipe estabeleceu durante a confecção dos artefatos padrões a serem seguidos, será conferido se os revisores estão cientes desse padrão e se toda a documentação está no padrão apropriado. ### Realização da Inspecção [Checklist Casos de Uso](Checklist-de-Inspecção-dos-Casos-de-Uso) ### Retrabalho * Nos Casos de Uso, foi realizado um retrabalho em diversos aspectos, todos estes listados na checklist de inspecção de caso de uso. Sendo que, com as modificações realizadas, os casos de uso passaram a ser verificados. ### Verificação * Todos os erros encontrados foram corrigidos após a verificação <file_sep>[<img style="display: block; margin: 0 auto;" src="http://www.freelogovectors.net/wp-content/uploads/2016/12/twitch-logo1.png" width=100px height=100px align="middle">](Demandas) *** * [Dados e Estatísticas](Dados-e-Estatísticas) *** ### [Pré-rastreabilidade](Pre-rastreabilidade) * [RichPicture](RichPicture) * [Argumentação](Argumentação) *** ### [Elicitação](Plano-de-Elicitação) * [Plano de Elicitação](Plano-de-Elicita%C3%A7%C3%A3o) * [Questionário](Questionario) * [Storytelling](Storytelling) * [Análise de Protocolo + Observação Participativa](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa)) * [Introspecção](Introspecção) * [Apresentação 02/04/18](Apresentação-02-04-2018) *** ### Priorização * [First Things First](First-Things-First) * [MoSCoW](MoSCoW) *** ### [Modelagem](Modelagem) * [Léxico](Léxico) * [Cenários](Cenários) * [Especificação de Casos de Uso](Especificação-de-Casos-de-Uso) * [Especificação Suplementar](Especificação-Suplementar) * [Diagramas de Casos de Uso](Diagramas-de-Casos-de-Uso) * [Product Backlog](Product-Backlog) * [Product Backlog - Geral](Product-Backlog-Geral) * [Sprint Backlog #1](Sprint-Backlog) * [NFR](NFR) * [Diagramas I*](Diagramas-i*) * [Especificação I*](Especificação-i*) *** ### Análise * [Inspeção](Inspecção) * [Inspeção Semi Automatizada](Inspeção-Semi-Automatizada) ### Pós-Rastreabilidade * [Matriz de Rastreabilidade](Matriz-Rastreabilidade) <file_sep>## [Raid](Raid) **Sinônimos:** * Gank * Gankar * Raidar **Noção:** * Um [streamer](Streamer) direcionar seu público à [stream](Stream) de outro [streamer](Streamer). **Impacto:** * [Streamer](Streamer) fez uma raid em seu [Streamer](Streamer) amigo, trazendo a ele mais [Viewers]. * Os [Viewers](Viewer) raidaram uma [Stream](Stream). <file_sep>**Sinônimos:** * Add-ons * Modifications **Noção:** * Conteúdo adicional e alterações adicionadas em jogos pela plataforma de Desktop da [Twitch](Twitch). **Impacto:** * O [Usuário](User) baixou mods para seu jogo. * O [Usuário](User) criou um mod e subiu para o banco da [Twitch](Twitch).<file_sep># Cenário 003 - Dar follow em um [Streamer](Streamer) ## Título * Seguir Canal ## Objetivo * Se inscrever em um canal para receber suas notificações * Ter o canal na homepage da Twitch.tv ## Contexto * Pessoa já autenticada na Twitch ## Ator(es) * [Viewer](Viewer) * [Streamer](Streamer) ## Recursos * Dispositivo eletrônico com acesso à internet * Conta na Twitch ## Exceções * [Viewer](Viewer) não estar conectado à internet * [Viewer](Viewer) não logado na Twitch.tv * Notificações indesejadas por default ## Episódios * [Viewer](Viewer) gosta de uma stream * [Viewer](Viewer) clica em ```❤️ Seguir``` * Notificação na tela comprovando que ele está seguindo o [streamer ](Cenário-001)<file_sep># Cenário 012 - Fazer denúncia ## Título * Denunciar um canal ## Objetivo * Denunciar um canal que não está de acordo com as regras da Twitch ## Contexto * Canal indo de desacordo com as regras da Twitch.tv ## Ator(es) * Usuário ## Recursos * Dispositivo eletrônico conectado à internet ## Exceções * Dispositivo eletrônico não conectado à internet ## Episódios * Pessoa está assistindo stream * Pessoa nota algo de desacordo com as políticas da Twitch * Pessoa clica no ícone de reticências abaixo da tela de transmissão * Pessoa seleciona a opção de denunciar canal * Pessoa preenche o formulário * Denúncia é feita <file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |03/04/2018|1.0|Criação do Documento|<NAME>| |11/06/2018|1.1|Conversão da tabela para Markdown|<NAME>| ### 1. Introdução #### 1.1. Propósito * Este artefato tem como propósito apresentar a análise feita a partir da utilização da técnica de priorização 'First Things First' a partir das funcionalidades da [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch). #### 1.2. Escopo * Serão levantadas as análises das funcionalidades da [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch), divididas de tal modo que, seja possível levantar cálculos cálculos de benefício, penalidade, custo e risco relativos a tais funcionalidades, indicados pela técnica de priorização utilizada (FTF). ### 2. Objetivos * Ao utilizar a técnica de priorização de requisitos, o objetivo a se alcançar é estabelecer uma certa ordem de prioridade em relação à implementação de certas funcionalidades, considerando fatores que impactam na disponibilização delas aos usuários da aplicação. _________ ### |Funcionalidade|Estado|Justificativa| |---|---|----| |Assistir Stream|Permanece|| |Participar do Group Chat|Não permanece|Depende de "Assistir Stream"| |Dar Subscribe/Follow|Não permanece|Depende de "Assistir Stream"| |Cadastrar na Twitch|Permanece|| |Editar/Atualizar Perfil|Permanece|| |Tornar-se Twitch Prime|Não permanece|Depende de "Cadastrar na Twitch"| |Realizar Donates|Não permanece|Depende de "Assistir Stream"| |Realizar uma Stream|Permanece|| |Adicionar Add-ons|Não permanece|Depende de "Realizar uma Stream"| |Tornar-se Twitch-Partner|Não permanece|Depende de "Realizar uma Stream"| |Banir alguém do chat|Não permanece|Depende de "Realizar uma Stream"| |Alterar o conteúdo da Stream|Não permanece|Depende de "Realizar uma Stream"| |Clipar uma Stream|Não permanece|Depende de "Realizar uma Stream"| |Fazer login|Permanece|| |Traduzir para várias linguagens|Permanece|| |Adicionar amigos|Não permanece|Depende de "Cadastrar" na Twitch| |Visualizar dados Pessoais|Permanece|| |Funcionar 24/7|Permanece|| |Receber notificações|Não permanece|Depende de "Cadastrar na Twitch"| |Adicionar formas de pagamento|Não permanece|Depende de "Cadastrar na Twitch"| |Realizar Cadastro por redes sociais|Não permanece|Depende de outras ferramentas alheias à Twitch| ### 3. Tabela de Prioridade FEATURES/FUNCIONALIDADES|BENEFÍCIO RELATIVO|PENALIDADE RELATIVA|VALOR TOTAL|VALOR %|CUSTO RELATIVO|CUSTO %|RISCO RELATIVO|RISCO %|PRIORIDADE |------|------|------|------|------|------|------|------|------|------| Cadastrar-me na [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch).|5|6|16|14.95327103|2|6.25|2|7.407407407|0.6459813084 Fazer login|5|6|16|14.95327103|2|6.25|2|7.407407407|0.6459813084 Traduções|7|2|16|14.95327103|7|21.875|4|14.81481481|0.09228304406 Atualizar meus dados pessoais.|2|1|5|4.672897196|3|9.375|2|7.407407407|0.1345794393 Vizualizar meus dados pessoais.|1|1|3|2.803738318|3|9.375|2|7.407407407|0.08074766355 Assistir uma streaming sem estar logado.|7|6|20|18.69158879|6|18.75|7|25.92592593|0.07690253672 Recuperar username.|6|6|18|16.82242991|2|6.25|2|7.407407407|0.726728972 Funcionar 24/7.|6|1|13|12.14953271|7|21.875|6|22.22222222|0.04998664887 TOTAL|39|29|107|100|32|100|27|100| ### 4. Resultados * Ao todo, foram analisadas 21 funcionalidades. Apesar do número pequeno de funcionalidades analisadas, o objetivo fora analisar as funcionalidades cruciais para o funcionamento da plataforma de LiveStreaming. Cada uma delas recebeu uma atribuição de benefício (agregação de valor), penalidade (perda de valor com a falta da funcionalidade), custo (custo de desenvolvimento) e risco (viabilidade de implementação), o que, pela utilização da técnica fornecida pelo FTF, possibilitou o cálculo da prioridade de cada uma. ### 5. Conclusão * A utilização da técnica 'First Things First' como priorização de requisitos possibilita a definição de funcionalidades que devem ser consideradas prioridade na hora da implementação. Tal fato, permite aos desenvolvedores e toda a equipe entenderem os eventos que podem exercer influência no planejamento de um software. [Dados e Estatísticas](Dados-e-Estat%C3%ADsticas)<file_sep>## [Streamar](Streamar) **Sinônimos:** * Transmitir * Fazer live **Noção:** * Ato de hospedar uma [live stream](Streamer), por parte do [streamer](Streamer) **Impacto:** * Um [usuário](User) que realiza o ato de streamar é um [Streamer](Streamer). * A [Twitch](Twitch) incentiva os [Usuários](User) a streamar, provendo diversas formas de monetização.<file_sep><img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/doarBits.png" width=900px> ### [Especificação de Caso de Uso](doação-de-bits)<file_sep>|Data Entrega|Conteúdo|Responsável|Status| |----|------|---------|-----| |22/04/2018|Caso de Uso [13](Assinatura-Twitch-Prime)/[19](Criação-de-Vídeo)/[20](Hosting)|<NAME>|Concluído| |22/04/2018|[Especificação Suplementar](Especificação-Suplementar)|<NAME> & Filipe dias|Concluído| |23/04/2018|Diagramas [10](Diagrama-Adição-de-Add-ons-em-Jogos)/[11](Diagrama-Chat-de-Voz)/[13](Diagrama-Assinatura-Twitch-Prime)/18/[19](Diagrama-Criação-de-Vídeo)/[20](Diagrama-Hosting)|<NAME>, <NAME>, Amanda,<br/> <NAME>, <NAME>|Concluido| |22/04/2018|Diagramas [2](Diagrama-Transmissão-Multimídia)/[3](Diagrama-Criação-de-Conta)/[4](Diagrama-Inscrição-em-Canal)/[5](Diagrama-Doação-de-Bits)/[6](Diagrama-Compra-de-Bits)|Amanda|Concluído| |22/04/2018|Diagramas [8](Diagrama-Mensagens-Privadas)/[9](Diagrama-Restrições-de-Chat)/[12](Diagrama-Transmissão-de-Ads)/18 - Retirado caso repetido|<NAME>|Concluído| |22/04/2018|Diagrama Geral + Diagramas [16](Diagrama-Banir-Viewer)/[18](Diagrama-Adição-de-Jogo-ao-Catálogo)|Gustavo|Concluido| |24/04/2018|Product Backlog|Amanda, Filipe, <NAME>, Gustavo, João, Thiago|Concluído| |25/04/2018|Sprint Planning|Amanda, Filipe, <NAME>, Gustavo, João, Thiago|Concluído| |06/05/2018|[NFR](NFR)|Amanda, Filipe, <NAME>, Gustavo, João, Thiago|Concluido| <file_sep>|Data|Versão|Descrição|Autor(es)| |--|--|--|--| |26/06/2018|1.0|Criação e desenvolvimento do Documento|<NAME>, <NAME>, <NAME>| 11/06/2018|1.1|Revisão do documento|<NAME>| ## Questionário #### 1. Introdução * Para a realizar a elicitação de requisitos, o grupo deciciu pela realização de um questionário. A [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch) possui ao todo, mais de 100 milhões de acessos mensais. Devido a essa quantidade de usuários, fora optado por utilizar tal mecanismo para elicitar requisitos. #### 2. Como foi desenvolvido? * O Questionário, desenvolvido em <a href="https://www.google.com/forms/about/">Google Forms</a>, foi feito levando em conta algumas informações básicas que, poderiam ajudar-nos no levantamento de requisitos, buscando de certa forma, nos dar dados sobre um determinado padrão de uso que seria observado dentro da plataforma. Os dados que foram levantados, não estavam anteriormente disponíveis em outros locais que possuíam dados relativos à <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a>, logo, buscando caracterizar algumas características não mapeadas do site. O Questionário foi elaborado de forma a ser fácil de responder e não ser maçante para a pessoa que estaria respondendo, contendo este poucas perguntas, sendo estas o mais objetivas possíveis. #### 3. Objetivo * O objetivo ao utilizar tal mecanismo de elicitação, foi poder entender um pouco do público alvo da [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch), da usabilidade e da experiência do usuário relacionadas à plataforma. #### 4. Perguntas <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Questionario/Captura%20de%20Tela%202018-04-05%20%C3%A0s%2014.30.30.png" width=800px> <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Questionario/Captura%20de%20Tela%202018-04-05%20%C3%A0s%2014.30.36.png" width=800px> <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Questionario/Captura%20de%20Tela%202018-04-05%20%C3%A0s%2014.30.42.png" width=800px> <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Questionario/Captura%20de%20Tela%202018-04-05%20%C3%A0s%2014.30.46.png" width=800px> <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Questionario/Captura%20de%20Tela%202018-04-05%20%C3%A0s%2014.30.50.png" width=800px> <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Questionario/Captura%20de%20Tela%202018-04-05%20%C3%A0s%2014.30.56.png" width=800px> #### 5. Resultados * Com a realização do questionário, pode-se levantar os seguintes requisitos: |Requisito|Tipo| |-----|---| |Portabilidade (Desktop)|Não funcional| |Portabilidade (Web)|Não funcional| |Portabilidade (Android/IOS/WindowsPhone)|Não funcional| |Usabilidade|Não funcional| |Compartilhar em redes sociais|Funcional| #### 6. Conclusão * A utilização da técnica do Questionário é extremamente importante para elicitar os requisitos imprescindíveis ao sistema.<file_sep># UC17 - Adição de Amigo ## Descrição * Este caso de uso descreve o adicionamento de usuários como amigos. ## Atores * Usuário ## Pré-condições * O usuário deve ter acesso à internet * O usuário deve estar logado ## Fluxo de Eventos ### Fluxo Principal * Este fluxo se inicia na página principal da Twitch. * 1. O usuário escreve na barra de busca o nome de desejo. * 2. O sistema gera uma lista de usuários**[FE01]** **[FE02]** * 3. O usuário encontra o nome. * 4. O Usuário adiciona o amigo. * 5. O caso de uso é encerrado ### Fluxo de Exceção **[FE01] - Nenhum usuário é encontrado** * 1. O usuário preenche o campo com um nome invalido ou inexistente * 2. O sistema gera uma mensagem de nenhum usuário encontrado. * 3. O caso de uso se encerra incompleto **[FE02] - Usuário de desejo não é encontrado** * 1. Usuário não consegue encontrar um nome correspondente ao digitado. * 3. O caso de uso se encerra incompleto ## Pós-condição * Uma solicitação de amizade ou adcionamento é enviada ao usuário selecionado.<file_sep># Cenário 023 - Atualizar dados de perfil ## Título * Atualizar perfil ## Objetivo * Alterar dados de um usuário já cadastrado na twitch. ## Contexto * Pessoa possui perfil na Twitch. ## Ator(es) * [Viewer](Viewer) * [Streamer](Cenário-001) ## Recursos * Dispositivo eletrônico com acesso à internet * Conta na Twitch ## Exceções * [Usuário](User) não estar conectado à internet * [Usuário](User) não logado na Twitch.tv ## Episódios * [Usuário](User) deseja alterar/atualizar seus dados. * [Usuário](User) clica em ```▼``` ao lado de seu username. * [Usuário](User) clica em ```🔧 configurações```. * [Usuário](User) altera os campos de seu desejo.<file_sep>## Planejamento Serão inspecionados os [NFRs Framework](./NFR) feitos por cada integrante da equipe. Cada NFR será analisado e verificado afim de se encontrar defeitos e corrigi-los, para que o projeto alcance boa qualidade. Os artefatos analisados serão os seguintes: * NFR de Usabilidade * NFR de Performance para o Usuário * NFR de Segurança * NFR de Performance para [Streaming](Streaming) * NFR de Portabilidade * NFR de Disponibilidade A inspeção será realizada por uma integrante da equipe, <NAME>, no local que preferir. ## Visão Geral NFR é um framework conceitual orientado aos requisitos não funcionais, os quais são considerados “cidadãos” de primeira ordem. O modelo utilizado no NFR Framework é chamado *Softgoal Interdependency Graph* (SIG). O SIG é abstraído em um diagrama formado por Softgoal (requisito de qualidade), argumentação, impactos, legenda e operacionalização. * Usabilidade: requisito não funcional definido como o grau de facilidade com que o usuário consegue interagir com determinada interface. * Perfomance para o Usuário: requisito não funcional que mede o desempenho do software para o usuário final. * Segurança: requisito não funcional caracterizado pela segurança de que acessos não autorizados ao sistema e dados associados não serão permitidos, assegurando a integridade do sistema. * *Perfomance* para Streaming: requisito funcional definido pelo desempenho da transmissão de uma stream. * Segurança: requisito não funcional caracterizado pela segurança de que acessos não autorizados ao sistema e dados associados não serão permitidos, assegurando a integridade do sistema. * *Perfomance* para Streaming: requisito funcional definido pelo desempenho da transmissão de uma stream. * Portabilidade: requisito não funcional definido pela facilidade em que um software tem de se adaptar a outras plataformas. * Disponibilidade: requisito não funcional que mede o quão disponível o sistema está para uso. ## Preparação A técnica utilizada para a inspeção dos documentos será a Leitura Baseada em Checklist(LBCh). Essa técnica é composta de uma lista de perguntas que ajuda os inspetores a encontrarem uma lista de defeitos no produto durante a inspeção. O final, será desenvolvido um quadro de classificação de defeitos de acordo com o resultado obtido da inspeção. ## Realização da inspeção [Checklist de inspeção dos NFRs](./Checklist-dos-NFRs) ## Retrabalho * Foram criadas legendas a todos os [NFRs Framework](./NFR). * O ducumento dos [NFRs Framework](./NFR) teve os tópicos da introdução refeitos, para melhor entendimento do leitor. * Como o NFR de Portabiliade já mencionava a reusabilidade do software, foi necessário fazer apenas o NFR de Confiabilidade. ## Revisão ![Revisão NFR](./images/revisao-nfr.png) <file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |05/06/2018|1.0|Criação do Documento|<NAME>| |05/06/2018|1.1|Edição do Documento|<NAME>| |05/06/2018|1.2|Adição de conteúdo ao Documento|<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>| |06/06/2018|1.3|Adição de conteúdo na tabela Backward From|<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>| |10/06/2018|1.4|Adição de conteúdo na tabela Forward From|<NAME>| |10/06/2018|1.5|Adição US42 a 52|<NAME>| |10/06/2018|1.6|Inserção de rastreabilidade de artefato de desenho|Gustavo Carvalho| |10/06/2018|1.7|Adição de conteúdo na tabela Forward From e correção no artefato|<NAME>| |10/06/2018|1.8|Adição de conteúdo na tabela Forward From|João Carlos| |10/06/2018|1.9|Adição de conteúdo na tabela Backward From|<NAME>,<NAME>| |11/06/2018|2.0|Adição de conteúdo na tabela Forward From|João Carlos| |11/06/2018|2.1|Adição de links na tabela backward|Gustavo Carvalho| |11/06/2018|2.2|Adição de conteúdo as matrizes|Amanda Pires| # Pós rastreabilidade ## Matriz de Rastreabilidade - Forward From |Requisito|Descrição|NFR|I*|Artefato de Desenho| |:---------:|:------|:------:|:-------:|:------:| |RF1|Cadastrar usuário|-|[SR Visitante](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#visitante)|[Tela de cadastro usuário](./images/artefato-de-desenho/RF1.png)| |RNF2|Logar via Facebook|-|[SR Visitante](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#visitante)|[Tela login via facebook](./images/artefato-de-desenho/RNF2.png)| |RF3|Editar perfil|-|[SR Usuário](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#usu%C3%A1rio)|[Tela de editar perfil](./images/artefato-de-desenho/RF3.png)| |RF4|Desabilitar conta|-|[SR Usuário](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#usu%C3%A1rio)|[Tela de desabilitar conta](./images/artefato-de-desenho/RF6.png)| |RF5|Tornar-se [Twitch Prime](Twitch-Prime)|-|[SD Twitch - Usuário](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Dependency#twitch---usu%C3%A1rio-32)|[Tela de cadastro Twitch Prime](./images/artefato-de-desenho/RF5.png)| |RF6|Tornar-se parceiro [Twitch](Twitch)|-|-|[Tela de cadastro parceiro Twitch](./images/artefato-de-desenho/RF6.png)| |RF7|Compartilhar uma [Stream](Stream)|-|-|[Tela de Compartilhar uma Stream](./images/artefato-de-desenho/CompartilharStream.png)| |RF8|Seguir um [Streamer](Streamer)|-|[SD Viewer - Streamer](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Dependency#viewer---streamer-22)|[Tela de Seguir Streamer](./images/artefato-de-desenho/SeguirStreamer.png)| |RF9|Acessar os chats|-|-|[Tela de Acessar o Chat](./images/artefato-de-desenho/AcessarChat.png)| |RF10|Filtrar quem digita no chat|-|-|-| |RF11|Banir alguém do chat|-|-|[Tela de banir no chat](./images/artefato-de-desenho/BanirAlguemDoChat.png)| |RF12|Alterar conteúdo da [Stream](Stream)|-|-|[Tela de Mudar Conteudo da Stream](./images/artefato-de-desenho/MudarConteudoStream.png)| |RF13|Visualizar [chat](Group-Chat) de [Stream](Stream)|-|-|[Tela de visualizar chat](./images/artefato-de-desenho/AcessarChat.png)| |RF14|Subir um vídeo na [Twitch](Twitch)|-|-|[Tela de subir um vídeo](./images/artefato-de-desenho/UploadVideos.png)| |RF15|Deletar um vídeo|-|-|[Tela de Deletar um vídeo](./images/artefato-de-desenho/DeletarVideo.png)| |RF16|Programar uma premiere|-|-|[Tela de programar uma premier](./images/artefato-de-desenho/ProgramarPremiere.png)| |RF17|Gravar uma transmissão|-|-|-| |RF18|Destacar um vídeo|-|-|[Tela de destacar um vídeo](./images/artefato-de-desenho/Clipar.png)| |RF19|Buscar outros usuários|-|[SR Usuário](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#usu%C3%A1rio)|[Tela de busca de amigos](./images/artefato-de-desenho/RF19.png)| |RF20|Adicionar outro usuário como amigo|-|[SR Usuário](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#usu%C3%A1rio)|[Tela de adicionar amigo](./images/artefato-de-desenho/AdicionarAmigos.png)| |RF21|Mandar mensagens privadas|-|-|[Tela mandar mensagem privada](./images/artefato-de-desenho/RF21.png)| |RF22|Participar de [chats](Group-Chat)|-|[SR Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#twitch)|[Tela participar de chat](./images/artefato-de-desenho/RF22.png)| |RF23|Mandar emoticons|-|-|[Tela mandar emoctions](./images/artefato-de-desenho/RF23.png)| |RF24|Bloquear alguém em uma conversa|-|-|[Tela bloquear usuário](./images/artefato-de-desenho/RF24.png)| |RF25|Sincronizar [add-ons](Mods)|-|[SR Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#twitch)|-| |RF26|Filtrar os [add-ons](Mods) vistos|-|[SR Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#twitch)|-| |RF27|Instalar novos [add-ons](Mods)|-|[SR Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#twitch)|-| |RF28|Deletar [add-ons](Mods)|-|[SR Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#twitch)|-| |RF29|Disponibilizar novos [add-ons](Mods)|-|[SR Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#twitch)|-| |RF30|Atualizar os [add-ons](Mods) de forma automatizada|-|[SR Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#twitch)|-| |RF31|Criar uma nova chamada de voz|-|-|[Tela criar nova chamada de voz](./images/artefato-de-desenho/RF31.png)| |RF32|Filtrar usuários que entrarem na chamada|-|-|-| |RF33|Realizar uma vídeo conferência|-|-|-| |RF34|Usar uma video conferência em um servidor|-|-|-| |RF35|Criar um grupo para chamadas permanentes|-|-|-| |RNF36|Opções de planos de inscrições|-||[Tela de opções de inscrições](./images/artefato-de-desenho/RNF36.png)| |RF37|Inscrever-se em um canal|-|-|[Tela de se inscrever em canal](./images/artefato-de-desenho/RF37.png)| |RF38|Comprar [bits](Bits)|-|[SD Twitch - Usuário](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Dependency#twitch---usu%C3%A1rio-32)|[Tela de comprar bits](./images/artefato-de-desenho/RF38.png)| |RNF39|Assinar o serviço Twitch Prime|-|[SD Twitch - Usuário](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Dependency#twitch---usu%C3%A1rio-32)|[Tela para assinar Twitch Prime](./images/artefato-de-desenho/RNF39.png)| |RF40|Doar [bits](Bits)|-|[SD Twitch - Usuário](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Dependency#twitch---usu%C3%A1rio-32)|[Tela de doar bits](./images/artefato-de-desenho/RF40.png)| |RF41|Aderir Twitch Turbo|-|-|[Tela para aderir a Twtich Turbo](./images/artefato-de-desenho/RF41.png)| |RF42|Recuperar senha e usuário|-|-|[Tela de recuperação de senha e usuário](./images/artefato-de-desenho/RF42.png)| |RF43|Assistir stream sem estar logado|-|-|[Tela de stream sem login](./images/artefato-de-desenho/RF43.png)| |RF44|Criar [clips](Clipes)|-|-|[Tela de criar clips](./images/artefato-de-desenho/RF44.png)| |RNF45|Boa usabilidade|[Usabilidade](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/NFR#us48---usabilidade)|[SR Viewer](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#viewer)|-| |RNF46|Suportar muitos acessos/visitas|[Perfomance para Usuário](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/NFR#us49---performance-para-o-usu%C3%A1rio)|[SR Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#twitch)|-| |RNF47|Segurança em transações financeiras|[Segurança](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/NFR#us50---seguran%C3%A7a)|[SR Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#twitch), [SR Viewer](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#viewer)|-| |RNF48|Sistema de login robusto|[Confiabilidade](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/NFR#us54---confiabilidade), [Segurança](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/NFR#us50---seguran%C3%A7a)|-|-| |RNF49|Fluidez em transmissões|[Performance](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/NFR#us51--performance-para-a-stream)|[SR Streamer](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#streamer), [SR Viewer](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#viewer)|-| |RNF50|Funcionamento 24h/7|[Disponibilidade](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/NFR#us53---disponibilidade)|-|-| |RNF51|Portabilidade|[Portabilidade](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/NFR#us52---portabilidade)|-|[Tela do app para desktop](./images/artefato-de-desenho/RNF51.png)| |RF52|Tradução|-|-|[Tela de opções de idiomas](./images/artefato-de-desenho/RF52.png)| |RF53|Receber [notificações](Live_Notification).|-|[SR Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Rationale#twitch)|[Tela de notificações](./images/artefato-de-desenho/notification.png)| |RF54|Divulgar anúncios nas lives da [Twitch](Twitch).|-|[SD Patrocinador](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Dependency#patrocinador---streamer-10)|-| |RF55|Ter acesso a meio de pagamentos online.|-|[SD Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Strategic-Dependency#twitch---usu%C3%A1rio-32)|[Tela de pagamento](./images/artefato-de-desenho/pagamento.png)| ______________________ ## Matriz de Rastreabilidade - Backward From Requisito|Descrição|Product Backlog|Esp. Casos de Uso|Cenário|Léxico|Moscow|First Things First|Introspecção|Análise de Protocolo/Observação Participativa|Storytelling|Questionário|RichPicture|Argumentação ---------|------|------|------|------|------|------|------|------|------|------|------|------|------ |RF1|Cadastrar usuário|[US01](Product-Backlog)|[UC03 - Criar de Conta](Criação-de-Conta)|[Cenário 002](Cenário-002)|[Criar Conta](Criar-Conta)|[MoSCoW](MoSCoW)|[First Things First](First-Things-First)|-|-|-|-|-|- |RNF2|Logar via Facebook|[US02](Product-Backlog)|[UC03 - Criar de Conta](Criação-de-Conta)|[Cenário 002](Cenário-002)||[MoSCoW](MoSCoW)|-|-|-|-|-|-| |RF3|Editar perfil|[US03](Product-Backlog)|-|[Cenário 023](Cenário-023)|-|[MoSCoW](MoSCoW)|[First Things First](First-Things-First)|-|-|-|-|-|- |RF4|Desabilitar conta|[US04](Product-Backlog)|-|-|-|-|-|-|-|-|-|-|- |RF5|Tornar-se Twitch Prime|[US05](Product-Backlog)|[UC13 - Assinar Twitch Prime](Assinar-Twitch-Prime)|-|[Twitch Prime](Twitch-Prime)|-|-|-|[Análise de Protocolo](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa))|-|-|[RichPicture](RichPicture)|[Argumentação](Argumentação) |RF6|Tornar-se parceiro [Twitch](Twitch)|[US06](Product-Backlog)|[UC05 - Doar Bits](Doação-de-Bits)|[Cenário 025](Cenário-025)|-|-|-|-|-|-|-|-| |RF7|Compartilhar uma [Stream](Stream)|[US07](Product-Backlog)|[UC18 - Compartilhar uma transmissão](Compartilhar-uma-Transmissão)|[Cenário 030](Cenário-030)|[Share](Share)|-|-|-|[Análise de Protocolo](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa))|-|-|[RichPicture](RichPicture)| |RF8|Seguir um [Streamer](Streamer)|[US08](Product-Backlog)|[UC15 - Seguir Canal](Seguir-Canal)|[Cenário 003](Cenário-003)|[follow](Dar-Follow)|[MoSCoW](MoSCoW)|-|-|[Análise de Protocolo](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa))|-|-|-|[Argumentação](Argumentação)| |RF9|Acessar os [chats](Group-Chat)|[US09](Product-Backlog)|-|[Cenário 027](Cenário-027)|[chats](Group-Chat)|[MoSCoW](MoSCoW)|-|-|[Análise de Protocolo](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa))|-|-|-|[Argumentação](Argumentação)| |RF10|Filtrar quem digita no [chat](Group-Chat)|[US010](Product-Backlog)|[UC09 - Restringir Chat](Restrições-de-Chat)|-||-|-|-|-|-|-|-| |RF11|Banir alguém do [chat](Group-Chat)|[US011](Product-Backlog)|[UC16 - Banir Viewer](Banir-Viewer)|-|-|-|-|-|-|-|-|-| |RF12|Alterar conteúdo da [Stream](Stream)|[US012](Product-Backlog)|-|[Cenário 028](Cenário-028)|-|[MoSCoW](MoSCoW)|-|-|-|-|-|-| |RF13|Visualizar [chat](Group-Chat) de [Stream](Stream)|[US013](Product-Backlog)|-|[Cenário 027](Cenário-027)|[chat](Group-Chat)|[MoSCoW](MoSCoW)|[First Things First](First-Things-First)|-|[Análise de Protocolo](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa))|-|-|-| |RF14|Subir um vídeo na [Twitch](Twitch)|[US014](Product-Backlog)|[UC19 - Criar Vídeo](Criação-de-Vídeo)|[Cenário 031](Cenário-031)|-|[MoSCoW](MoSCoW)|-|-|-|-|-|-| |RF15|Deletar um vídeo|[US015](Product-Backlog)|-|-|-|-|-|-|-|-|-|-| |RF16|Programar uma premiere|[US016](Product-Backlog)|[UC19 - Criar Vídeo](Criação-de-Vídeo)|-|-|-|-|-|-|-|-|[RichPicture](RichPicture)| |RF17|Gravar uma transmissão|[US017](Product-Backlog)|[UC02 - Transmitir Multimídia](Transmissão-Multimídia)|-|[Streamar](Streamar)|[MoSCoW](MoSCoW)|-|[Introspecção](Introspecção)|[Análise de Protocolo](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa))|-|-|-| |RF18|Destacar um vídeo|[US018](Product-Backlog)|-|[Cenário 005](Cenário-005)|-|[MoSCoW](MoSCoW)|-|-|-|-|-|-| |RF19|Buscar outros usuários|[US019](Product-Backlog)|[UC17 - Adicionar Amigo](Adição-de-Amigo)|[Cenário 032](Cenário-032)|-|-|-|-|[Análise de Protocolo](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa))|-|-|-| |RF20|Adicionar outro usuário como amigo|[US20](Product-Backlog)|[UC17 - Adicionar Amigo](Adição-de-Amigo)|[Cenário 032](Cenário-032)|-|-|-|-|[Análise de Protocolo](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa))|-|-|-| |RF21|Mandar mensagens privadas|[US21](Product-Backlog)|[UC08 - Enviar Mensagens Privadas](Mensagens-Privadas)|[Cenário-021](Cenário-021)|[Whisper](Whisper)|-|-|-|[Análise de Protocolo](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa))|-|-|-| |RF22|Participar de [chats](Group-Chat)|[US22](Product-Backlog)|-|[Cenário-027](Cenário-027)|-|-|-|-|[Análise de Protocolo](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa))|-|-|-| |RF23|Mandar emoticons|[US23](Product-Backlog)|-|-|[Emotes](Emotes)|-|-|-|-|-|-|-| |RF24|Bloquear alguém em uma conversa|[US24](Product-Backlog)|[UC08 - Enviar Mensagens Privadas](Mensagens-Privadas)|-|-|-|-|-|-|-|-|-| |RF25|Sincronizar [add-ons](Mods)|[US25](Product-Backlog)|[UC10 - Adicionar Add-ons em jogos](Adição-de-Add-ons-em-Jogos)|-|[add-ons](Mods)|[MoSCoW](MoSCoW)|-|[Introspecção](Introspecção)|-|-|-|-|[Argumentação](Argumentação)| |RF26|Filtrar os [add-ons](Mods) vistos|[US26](Product-Backlog)|[UC10 - Adicionar Add-ons em jogos](Adição-de-Add-ons-em-Jogos)|-|[add-ons](Mods)|[MoSCoW](MoSCoW)|-|[Introspecção](Introspecção)|-|-|-|-|[Argumentação](Argumentação)| |RF27|Instalar novos [add-ons](Mods)|[US27](Product-Backlog)|[UC10 - Adicionar Add-ons em jogos](Adição-de-Add-ons-em-Jogos)|-|[add-ons](Mods)|[MoSCoW](MoSCoW)|-|[Introspecção](Introspecção)|-|-|-|-|[Argumentação](Argumentação)| |RF28|Deletar [add-ons](Mods)|[US28](Product-Backlog)|[UC10 - Adicionar Add-ons em jogos](Adição-de-Add-ons-em-Jogos)|-|[add-ons](Mods)|[MoSCoW](MoSCoW)|-|[Introspecção](Introspecção)|-|-|-|-|[Argumentação](Argumentação)| |RF29|Disponibilizar novos [add-ons](Mods)|[US29](Product-Backlog)|[UC10 - Adicionar Add-ons em jogos](Adição-de-Add-ons-em-Jogos)|-|[add-ons](Mods)|[MoSCoW](MoSCoW)|-|[Introspecção](Introspecção)|-|-|-|-|[Argumentação](Argumentação)| |RF30|Atualizar os [add-ons](Mods) de forma automatizada|[US30](Product-Backlog)|[UC10 - Adicionar Add-ons em jogos](Adição-de-Add-ons-em-Jogos)|-|[add-ons](Mods)|[MoSCoW](MoSCoW)|-|[Introspecção](Introspecção)|-|-|-|-|[Argumentação](Argumentação)| |RF31|Criar uma nova chamada de voz|[US31](Product-Backlog)|[UC11 - Enviar Chat de Voz](Chat-de-Voz)|-|-|-|-|-|-|-|-|-|[Argumentação](Argumentação)| |RF32|Filtrar usuários que entrarem na chamada|[US32](Product-Backlog)|[UC11 - Enviar Chat de Voz](Chat-de-Voz)|-|-|-|-|-|-|-|-|-|[Argumentação](Argumentação)| |RF33|Realizar uma vídeo conferência|[US33](Product-Backlog)|[UC11 - Enviar Chat de Voz](Chat-de-Voz)|-|-|-|-|-|-|-|-|-|[Argumentação](Argumentação)| |RF34|Usar uma video conferência em um servidor|[US34](Product-Backlog)|[UC11 - Enviar Chat de Voz](Chat-de-Voz)|-|-|-|-|-|-|-|-|-|[Argumentação](Argumentação)| |RF35|Criar um grupo para chamadas permanentes|[US35](Product-Backlog)|[UC11 - Enviar Chat de Voz](Chat-de-Voz)|-|-|-|-|-|-|-|-|-|[Argumentação](Argumentação)| |RNF36|Opções de planos de inscrições|[US36](Product-Backlog)|[UC04 - Inscrever em canal](Inscrição-em-Canal)|-|-|-|-|-|-|-|-|-| |RF37|Inscrever-se em um canal|[US37](Product-Backlog)|[UC04 - Inscrever em canal](Inscrição-em-Canal)|-|[Subscriber](Subscriber)|-|-|-|-|[Análise de Protocolo](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa))|-|[RichPicture](RichPicture)|[Argumentação](Argumentação)| |RF38|Comprar [bits](Bits)|[US38](Product-Backlog)|[UC06 - Comprar Bits](Compra-de-Bits)|-|-|-|-|-|-|-|-|[RichPicture](RichPicture)|-| |RNF39|Assinar o serviço Twitch Prime|[US39](Product-Backlog)|[UC13 - Assinar Twitch Prime](Assinar-Twitch-Prime)|-|[twitch prime](Twitch-Prime)|-|-|-|[Análise de Protocolo](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa))|-|-|[RichPicture](RichPicture)|-| |RF40|Doar [bits](Bits)|[US40](Product-Backlog)|[UC05 - Doar Bits](Doação-de-Bits)|-|[Donate](Donate)|-|-|-|-|-|-|[RichPicture](RichPicture)|-| |RF41|Aderir Twitch Turbo|[US41](Product-Backlog)|-|-|-|-|-|-|-|-|-|-|-| |RF42|Recuperar senha e usuário|[US42](Product-Backlog)|[Cenário 015](Cenário-015)|-|-|-|[First Things First](First-Things-First)|-|-|-|-|-|[Cadastro 1.1.0](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Argumenta%C3%A7%C3%A3o#cadastro-110)| |RF43|Assistir stream sem estar logado|[US43](Product-Backlog)|[Cenário 001](Cenário-001)|-|-|-|[First Things First](First-Things-First)|-| [Análise de protocolo ](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa))|-|-|-|-| |RF44|Criar [clips](Clipes)|[US44](Product-Backlog)|[C020](Cenário-020),[C005](Cenário-005)|-|[Léxico Clip](Clipes)|[MoSCoW](MoSCoW)|-|-|-|[Storytelling](Storytelling)|-|-|-| |RNF45|Boa usabilidade|[US45](Product-Backlog)|-|-|-|-|-|-|-|-|-|-|-| |RNF46|Suportar muitos acessos/visitas|[US46](Product-Backlog)|-|-|-|-|-|-|-|-|-|-|-| |RNF47|Segurança em transações financeiras|[US47](Product-Backlog)|[UC13 - Assinar Twitch Prime](Assinar-Twitch-Prime)|[Cenário 008](Cenário-008)|-|-|-|-|-|[Análise de Protocolo](Híbrido-(Análise-de-Protocolo--&-Observação-Participativa))|-|-|-| |RNF48|Sistema de login robusto|[US48](Product-Backlog)|-|[Cenário 015](Cenário-015)|-|-|-|-|-|-|-|-|-| |RNF49|Fluidez em transmissões|[US49](Product-Backlog)|-|-|-|-|-|-|-|-|-|-|-| |RNF50|Funcionamento 24h/7|[US50](Product-Backlog)|-|-|-|-|-|-|-|-|-|-|-| |RNF51|Portabilidade|[US51](Product-Backlog)|-|-|-|-|-|-|[Introspecção](Introspecção)|[Storytelling](Storytelling)|-|-|[Twitch Desktop App 1.0](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Argumenta%C3%A7%C3%A3o#twitch-desktop-app-100)| |RF52|Tradução|[US52](Product-Backlog)|-|[Cenário-024](Cenário-024)|-|-|[First Things First](First-Things-First)|-|-|-|-|-|-| |RF53|Receber [notificações](Live_Notification).|[US08](Product-Backlog-Geral#product-backlog---geral-11)|-|[Cenário 33](Cenário-033)| [Notificação](Live-Notification)|-|-|-|-|-|-|-|[Argumentação](Argumentação#1-argumentação)| |RF54|Divulgar anúncios nas lives da [Twitch](Twitch).|[US41](Product-Backlog)|-|-|-|-|-|-|-|-|-|[RichPicture](RichPicture#134-patrocinador)|-| |RF55|Ter acesso a meio de pagamentos online.|[US05](Product-Backlog)|-|[Cenario 11](Cenário-011)|-|-|-|-|[Introspecção](Introspecção)|-|-|[Rich Picture](RichPicture#133-streamer)|-| <file_sep># Cenário 008 - Fazer [Donate](Donate) ## Título * [Viewer](Viewer) fazendo [donate](Donate) ## Objetivo * [Viewer](Viewer) doar dinheiro ao [streamer](Streamer) ## Contexto * [Viewer](Viewer) assistindo uma [stream](Streamer) * [Viewer](Viewer) desejando doar dinheiro ## Ator(es) * [Viewer](Viewer) * [Streamer](Streamer) ## Recursos * Dispositivo eletrônico conectado à internet ## Exceções * Dispositivo eletrônico não conectado à internet ## Episódios * [Usuário](User) conecta-se à stream de um [streamer](Streamer) * [Usuário](User) desce a página e acessa a área de [Donate](Donate) * [Usuário](User) preenche os campos requeridos * [Usuário](User) seleciona a forma de pagamento * [Usuário](User) faz a doação <file_sep> <img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/RestringirChat.png?raw=true" width=900px> ### [Especificação de Caso de Uso](restrições-de-chat)<file_sep>Data|Versão|Descrição|Autor -----|------|---------|------- 17/04/2018|1.0|Criação do documento|<NAME>| 18/04/2018|1.1|Inclusão de conteúdo|Filipe Dias| 18/04/2018|1.2|Inclusão de conteúdo de Qualidade de Software|<NAME>| 11/06/2018|1.3|Revisão|<NAME>| 11/06/2018|1.4|Revisão do Documento e inserção de Resultados|Filipe Dias| <h2> 1. Introdução </h2> #### 1.1 Finalidade Este Documento tem como finalidade armazenar a elicitação de requisítos não funcionais para a plataforma Twitch, feita pela equipe de requisitos de software. A Especificação Suplementar captura os requisitos de sistema que não são capturados imediatamente nos casos de uso do modelo de casos de uso. Entre os requisitos estão incluídos: * Requisitos legais e reguladores, incluindo padrões de aplicativo. * Atributos de qualidade do sistema a ser criado, incluindo requisitos de usabilidade, confiabilidade, desempenho e suportabilidade. * Outros requisitos, como sistemas operacionais e ambientes, requisitos de compatibilidade e restrições de design. <h3> 1.2 Escopo </h3> <p align="justify">Este documento visa apontar requisitos não funcionais, desempenhados pelo sistema, de modo a apresentar assuntos que abrangem funcionalidades referentes a questão de qualidade e desempenho garantidas pelo software. </p> <h3> 1.3 Definições, Acrônimos e Abreviações </h3> Alguns dos acrônimos, definições e abreviações usados neste documento são: * Viewer: Espectador * Streamer: Transmissor * Donate: Doação feita à um [streamer](Streamer) * Bits: Forma específica de doação * UX: User Experience, refere-se à experiência do usuário ao usar a aplicação. <h3> 1.4 Referências </h3> [Twitch developer](https://dev.twitch.tv/) <h3> 1.5 Visão Geral </h3> <p align="justify">O documento está organizado da seguinte maneira:</p> <ul> <li> Seção 1: Faz uma breve introdução do documento, expondo sua finalidade (para que serve), escopo (conteúdo), definições de termos que serão usadas no documento e referências; </li> <li>Seção 2: Explica cada requisito não funcional de usabilidade da aplicação;</li> <li>Seção 3: Explica cada requisito não funcional de confiabilidade da aplicação;</li> <li>Seção 4:Explica o requisito não funcional de suportabilidade (ou portabilidade) da aplicação;</li> <li>Seção 5: Desenvolve as restrições de design;</li> <li>Seção 6: Expõe as interfaces do sistema;</li> <li>Seção 7: Expõe informações legais e de direitos autorais.</li> </ul> <h2> 2. Usabilidade </h2> <h3> 2.1 Termos Técnicos </h3> <p align="justify"> O sistema não deve conter termos técnicos para não dificultar a aprendizagem do usuário. A linguagem será formal, no entanto acessível a qualquer um dos tipos de usuários que o sistema deverá ter.</p> <h3> 2.2 Facilidade de Uso </h3> <p align="justify">O sistema terá uma forma simples e intuitiva de utilização, sem haver necessidade de algum tipo de treinamento prévio. O uso de interfaces amigáveis em conjunto com design bem trabalhado providenciarão maior entendimento e uma melhor UX.</p> <h3> 2.3 Relevância de usabilidade </h3> <p align="justify">O sistema contém apenas soluções e ferramentas realmente relevantes e efetivas ao sistema, de forma simples e funcional, consideradas úteis para toda e qualquer atividade que o usuário decida exercer.</p> <h3> 2.4 Eficácia </h3> <p align="justify">O sistema visa ao máximo disponibilizar ferramentas simples, reduzidas e intuitivas ao usuário, mas ao mesmo tempo funcionais e diretas, de modo a tornar a relação do mesmo com o sistema eficaz, visando assim o melhor aproveitamento de seu tempo, evitando ,na medida do possível, operações desnecessárias no sistema.</p> <h3> 2.5 Tratamento de erros </h3> <p align="justify">O sistema deve prever e tratar erros. No caso de requisições iguais realizadas em menos de 3 segundos (ao dar F5 enquanto uma requisição está sendo executada, por exemplo), deve-se considerar apenas a primeira, para não gerar múltiplas ações iguais e não comprometer a eficiência do sistema;</p> <h2> 3. Confiabilidade </h2> <h3> 3.1 Garantia de funcionamento em tempo integral </h3> <p align="justify">O software deve funcionar em tempo integral, 24 horas por dia, mesmo com um volume intenso de dados, suportando os possíveis 80 mil usuários que podem utilizar o sistema, sem qualquer tipo de dano ou queda do mesmo, desde que a conexão à internet esteja estabelecida. </p> <h3> 3.2 Garantia de armazenamento de dados </h3> <p align="justify">O software deve se comprometer em armazenar de forma correta todos os dados referentes ao usuário, de forma a não apresentar possíveis erros de armazenamento, para que desse modo não ocorra a necessidade de recadastramento do usuário no sistema. </p> <h3> 3.3 Garantia de segurança no armazenamento de dados </h3> <p align="justify">O software deve se comprometer em garantir a segurança dos dados informados pelo usuário no momento de seu cadastramento no sistema, de modo que esses dados sejam guardados de forma segura e confiável, não sendo possível o acesso de outros usuários sem a devida permissão.</p> <h2> 4. Suportabilidade </h2> <p align="justify">O website será suportado em todos os navegadores e em qualquer sistema operacional (Windows, Mac e Linux). A performance da aplicação pode variar de um sistema para outro e também entre navegadores. É sugerido o uso da aplicação na versão mais atualizada do navegador Google Chrome para melhor UX.</p> <h2> 5. Restrições de Design </h2> <h3> 5.1 Interface Responsiva </h3> <p align="justify">Os inúmeros dispositivos que são usados hoje para acessar a internet possuem diferentes tamanhos de tela, assim como diferentes resoluções e a interface do sistema deverá se adequar a qualquer tamanho de tela.</p> <h2> 6. Interfaces </h2> <h3> 6.1 Interfaces de Usuário </h3> * Tela de login * Tela de perfil * Tela de cadastro * Tela de alteração de cadastro * Tela de transmissão * Tela de vídeos e clipes <h3> 6.2 Interfaces de Hardware </h3> * Notebooks * Computadores de Mesa <h3> 6.3 Interfaces de Software </h3> * Todos os sistemas operacionais que possuem suporte a navegadores e acesso a internet. * Todos navegadores web. <h2> 7. Qualidade de software </h2> <p align="justify"> Para mensurar e garantir a qualidade da usabilidade, eficiência, compatibilidade, confiabilidade, segurança, manutenabilidade, portabilidade do sistema, é utilizada a <a href="http://iso25000.com/index.php/en/iso-25000-standards/iso-25010?limit=3&start=3")> ISO 25010 </a> que é utilizada na maior parte dos produtos de software desenvolvidos com boa qualidade. </p> ![Software Product Quality ](http://iso25000.com/images/figures/en/iso25010.png) ## Prioridade ### Críticos * Segurança * Por se tratar de uma plataforma que utiliza serviços pagos, os dados bancários dos seus usuários devem permanecer seguros. ### Alta * Performance/Eficiência * As transmissões devem ocorrer em diversas resoluções de imagem para uma melhor performance a usuários com máquinas e conexões menos potentes * Compatibilidade * A plataforma deve rodar em diferentes navegadores e sistemas operacionais. ### Média * Usabilidade * A plataforma deve ser simples de usar e entender. ### Baixa * Portabilidade <h2> 8. Observações Legais, Direitos Autorais </h2> [Twitch copyright](https://www.twitch.tv/p/legal/dmca-guidelines/) ### 9. Resultados * Após estudar e elaborar a especificação suplementar, pode-se obter os seguintes resultados, listados abaixo: |Requisito|Tipo| |--|--| |Portabilidade|Não funcional| |Segurança|Não funcional| |Confiabilidade|Não funcional| |Usabilidade|Não funcional| |Desempenho|Não funcional|<file_sep>**Sinônimos:** * Brinde * Loot **Noção:** * Recompensas dadas aos assinantes da [Twitch Prime](Twitch-Prime) **Impacto:** * Ao assinar o [Twitch Prime](Twitch-Prime) o [usuário](User) pode resgatar seus brindes. * Assinante [Twitch-Prime](Twitch-Prime) ganhou skins no jogo.<file_sep><img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Casos_de_uso/UseCase08.png" width=900px> ### [Especificação de Caso de Uso](Geração-de-token-do-streamer)<file_sep># UC10 - Adição de Add ons em Jogos ### [Diagrama de caso de uso](Diagrama-Adição-de-Add-ons-em-Jogos) ## Descrição * Este caso de uso descreve o uso do aplicativo desktop para adição de add-ons/mods em jogos ## Atores * Usuário ## Pré-condições * O usuário deve possuir algum dos jogos compativeis com os [add-ons](Mods) da plataforma * O usuário deve possuir o aplicativo desktop da twitch * O usuário possuir conta na twitch ## Fluxo de Eventos ### Fluxo Principal * 1. O usuário abre a plataforma desktop * 2. O usuário seleciona a secção de [add-ons](Mods) do aplicativo * 3. O usuário seleciona o jogo que gostaria de baixar add-ons * 4. O usuário escolhe os [add-ons](Mods) que gostaria de baixar * 5. O usuário clica em instalar * 6. O sistema faz o download dos add-ons * 7. O sistema sincroniza os [add-ons](Mods) com o jogo * 8. O caso de uso é encerrado ### Fluxos Alternativos * Não se aplica ### Fluxo de Exceção * Não se aplica ## Pós-condição * Os jogos agora possuem os [add-ons](Mods) baixados e instalados<file_sep># Cenário 031 - Criar vídeos sob demanda ## Título * Criar vídeos sob demanda. ## Objetivo * Arquivar um vídeo transmitido anteriormente para que os seguidores do [Streamer](Streamer) possa assistir vídeos perdidos. ## Contexto * O [streamer](Streamer) deseja salvar vídeos para aumentar a popularidade do seu canal. ## Ator(es) * [Streamer](Streamer). * [Viewer](Viewer). ## Recursos * Computador * Internet ## Exceções * [Usuário](User) não estar conectado à internet. ## Episódios * [Streamer](Streamer) entra na sua conta Twitch. * [Streamer](Streamer) vai até o seu painel de controle na página principal do Twitch. * [Streamer](Streamer) clica em configurações. * [Streamer](Streamer) clica na caixa de seleção “Store Past Broadcasts”. * Twitch salva todos os vídeos do streamer por um tempo limitado. Referência: [Videos sob demanda](https://help.twitch.tv/customer/pt_br/portal/articles/1575302-v%C3%ADdeos-sob-demanda) <file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |22/05/2018|0.1|Criação do Documento|<NAME>| |23/05/2018|0.2|Adição de descrições e referências|<NAME>| |23/05/2018|0.3|Adição descrições do processo semi-automatizado|<NAME>| |11/06/2018|0.4|Revisão e correção|<NAME>| # Inspecção A inspeção é um método que contribui para garantir a qualidade do produto de software. Todas as etapas do processo de desenvolvimento de software são suscetíveis à incorporação de defeitos, que podem ser detectados pela inspeção e posteriormente removidos.Logo, revisaremos os documentos de elicitação, os cenários e léxicos, os Casos de Usos produzidos, as histórias de usuário levantas, os diagramas NFR e os diagramas iStar. O processo de inspeção inclui as seguintes etapas: ### Planejamento Nesta etapa, é determinado se os materiais que serão inspecionados são adequados, organiza-se as pessoas que irão participar da inspeção e define-se o local onde serão realizadas as sessões de inspeção. ### Visão Geral Esta etapa inclui a apresentação do material a ser inspecionado aos participantes e a atribuição de funções aos participantes, durante a inspeção. ### Preparação Nesta etapa, os participantes são treinados para executarem as funções que lhes foram atribuídas, visando encontrar os defeitos constantes do produto ou artefato de software. ### Realização da Inspeção Esta etapa inclui sessões de trabalho, nas quais os participantes analisam o produto ou artefato de software, com o fim de detectar os defeitos existentes nesses produtos. Existem várias técnicas de inspeção para encontrar defeitos em artefatos, entre elas * Leitura baseada em Checklist (LBCh) * Leitura Baseada em Cenário (LBCe) * Leitura Baseada em Perspectiva (LBPe) A equipe optou por utilizar a técnica LBCh. Alguns processos das inspeções foram feitas utilizando-se de scripts que ou automatizavam a correção de erros, ou melhorava a forma com que o inspetor analisava as questões levantadas nos questionários. Esses processos foram documentados na [inspeção semi automatizada](Inspeção-Semi-Automatizada). ### Retrabalho Nesta etapa, os defeitos detectados, devidamente documentados, são encaminhados ao autor do produto que foi inspecionado, para que seja providenciada a remoção destes defeitos ### Revisão Nesta etapa, o autor confere o produto revisado, juntamente com a equipe de inspeção, para assegurar-se de que todas as correções necessárias foram realizadas e que nenhum defeito novo foi introduzido. # Verificações * [Pré Rastreabilidade](Verificação-Pre-Rastreabilidade) * [Elicitação](Verificação-Elicitação) * [Cenários e Léxicos](Verificação-Cenários-e-Léxicos) * [Casos de Uso](Verificação-Casos-de-Uso) * [Histórias de Usuário](Verificação-Histórias-de-Usuário) * [NFR](Verificação-NFR) * [iStar](Verificação-iStar) # Validação Como a validação é uma técnica realizada em junta ao cliente, o time de engenharia de requisitos decidiu que não seria adequado a aplicação dessa técnica no momento atual, já que o time está fazendo um estudo em cima de uma plataforma já desenvolvida e não desenvolvendo um sistema novo. # Referências * [Técnicas de inspeção](http://www.inf.puc-rio.br/~wer/WERpapers/artigos/artigos_WER06/bertini.pdf) * [Uma abordagem sobre inspeção de documentos ](http://www.lbd.dcc.ufmg.br/colecoes/sbqs/2006/012.pdf)<file_sep># Dar [ban](Ban) em [viewer](Viewer) ## Objetivo: * Punir algum usuário do tipo viewer que está quebrando as regras ou sendo irritante do chat. ## Contexto: * O administrador gostaria de impedir que alguém fale e veja sua stream. ## Ator(es) * [Viewer](Viewer) * [Streamer](Streamer) * Moderador ## Recursos * Funções Administradoras do (Chat)[Group-Chat] * Acesso ao [chat](Group-Chat) da stream ## Exceções * Moderador quebrando regras ou sendo inconveniente no (chat)[Group-Chat] * Moderador tendo que banir outro moderador ## Episódios * [Usuário](User) [Viewer](Viewer) está quebrando as regras do (chat)[Group-Chat] * Streamer/Moderador bane este * [Viewer](Viewer) é impedido de usar o [Chat](Group-Chat) e visualizar a Stream. ------- * [Usuário](User) está sendo inconveniente e irritante * Streamer, mesmo o viewer não estando, necessariamente, quebrando as regras, bane o viewer da stream.<file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |23/05/2018|0.1|Criação do Documento|<NAME>| |24/05/2018|0.2|Adição de tópicos para as respostas e numeração para as perguntas|<NAME>| |28/05/2018|0.3|Adição dos resultados da inspecção dos itens 1-8|<NAME>| |29/05/2018|0.4|Adição dos resultados da inspecção dos itens 9-16|<NAME>| * Checklist de Inspeção dos Casos de Uso * Inspetor: <NAME> * Data: 23/05/2018 |Item|Perguntas para inspeção dos Casos de Uso| |------|-------| |1|A descrição é sucinta e suficiente?| Resposta|Sim| Modificações|Alterar descrição do UC02, UC09, UC10, UC11, UC19, para o padrão dos demais documentos, que usam 'Este caso de uso' no ínicio da descrição.| |2|A descrição aborda de forma correta o tema do caso de uso?| Resposta|Sim| Modificações|Nenhuma| |3|Os atores atuantes estão corretos?| Resposta|Caso, a verificação das modificações esteja correta, sim.| Modificações|Verificar se, a Twitch contaria como um ator, dentro do envolvimento do usuário com a plataforma em alguns casos, alteração nos hiperlinks do UC16.| |4|Os atores estão sendo representados corretamente dentro dos casos de uso?| Resposta|Não| Modificações|UC01, atores não descritos de forma específica, utilizando um usuário genérico ao invés do geral em casos que existem mais de um ator. UC03, utiliza terminologia confusa quanto à referência do ator. UC05 lista o ator usuário e o ator streamer que é um especialização do ator usuário. UC13 possui ator fora do formato padrão.| |5|As Pré-Condições são realmente necessárias para o funcionamento do requisito descrito no caso de uso?| Resposta|Sim| Modificações|UC14, UC15, alteração da descrição da pre-condição para o padrão do restante dos documentos| |6|O Fluxo principal segue o padrão adotado na elaboração do documento?| Resposta|Não| Modificações|UC13,UC14, UC19, alterações para o padrão| |7|O Fluxo principal segue a ordem correta para a realização da tarefa do caso de uso?| Resposta|Não| Modificações|UC13, adequação à ordem correta da realização das tarefas, UC14 está faltando com alguns passos.| |8|O Fluxo principal possui as tags representando o fluxo alternativo?| Resposta|Não| Modificações|Alteração nas tags de fluxo alternativo nas UC09, UC13, UC15, UC18| |9|Ao seguir os passos, a tarefa é corretamente concluída?| Resposta|Não| Modificações|Adicionar caso de uso completado como passo final nas UC17 e UC18, Adicionar passo de validação dos dados inseridos na UC03, mesclar FA01 ao Fluxo Principal e adicionar passo de seleção de pagamento à UC06, Adicionar tópico de validação dos dados inseridos na UC03.| |10|Os fluxos alternativos descritos são corretamente representados?| Resposta|Não| Modificações|UC06 possui um fluxo alternativo que deveria estar no fluxo principal.| |11|Os fluxos alternativos adentram o fluxo principal corretamente?| Resposta|Não| Modificações|FA01 da UC03 possui um fluxo alternativo que não segue a linha do fluxo principal nem retorna a ele. FA da UC13 não adentra o fluxo principal.| |12|Os passos descritos no fluxo alternativo possibilitam a completude correta do fluxo?| Resposta|Não| Modificações|FA01 da UC03 possui estado independente e os fluxos alternativos da UC13 não completam adequadamente o fluxo.| |13|Os fluxos de exceção são corretamente descritos?| Resposta|Não| Modificações|UC13, UC16 e UC06 são descritos incorretamente| |14|Os fluxos de exceção são representados corretamente do fluxo principal?| Resposta|Não| Modificações|FE01 inserido ao passo 4 da UC01, FE01 inserido tag ao passo 3 da UC02, FE01 adicionado ao passo 7 do Fluxo Principal, Adicionar tag do FE01 ao passo iv da UC06, adicionar tag FE02 ao passo 5 da UC08 e adicionar tags dos FE da UC13 após a correção. | |15|Os erros descritos no fluxo de exceção ocorre de fato?| Resposta|Não| Modificações|UC06 possui um fluxo de exceção que é um fluxo alternativo e o UC13 possui um fluxo de exceção escrito de maneira inadequada.| |16|A Pós-condição é corretamente cumprida e descrita?| Resposta|Sim| Modificações|Alteração gramática na UC05, Alteração para descrição mais sucinta da UC13, remoção de numeração em frente a UC14, UC15 e UC19|<file_sep> **Sinônimos:** * Espectador **Noção:** * [Usuário](User) que assiste a uma [stream](Stream). **Impacto:** * Realiza as tarefas: assistir [stream](Stream),[dar follow](Dar-Follow) , [subscribe](Subscribe), [whisper](Whisper), [cheer](Cheer). * Os viewers deste [streamer](Streamer) são extremamente fieis. * O viewer assiste a uma [Stream](Stream). * Os viewers se [inscrevem](Subscribe) ao Canal.<file_sep>![](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Casos_de_uso/UcGeral.png)<file_sep><img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/UseCase16.png" width=900px> ### [Especificação de Caso de Uso](seguir-canal)<file_sep> **Sinônimos:** * Prime **Noção:** * Serviço de [usuário premium](usuario-Prime) da [Twitch](Twitch). **Impacto:** * O Twitch Prime é uma funcionalidade paga da [Twitch](Twitch). * Com o serviço [twitch prime](Twitch-Prime) o [usuário](User) tem uma [inscrição](subscribe) gratuita por mês. * Dá acesso a [prêmios exclusivos](Loot-Prime) de usuários [Twitch Prime](Twitch-Prime).<file_sep># Cenário 005 - [Clipar](Clip) uma jogada ## Título * [Viewer](Viewer) fazendo um clip ## Objetivo * Salvar e compartilhar algum highlight de uma stream * Poder rever um momento específico da stream ## Contexto * [Viewer](Viewer) autenticado na Twitch ## Ator(es) * [Viewer](Viewer) ## Recursos * Dispositivo eletrônico conectado à internet ## Exceções * Dispositivo não estar conectado à internet ## Episódios * [Viewer](Viewer) está assistindo uma stream * [Viewer](Viewer) gostou de um momento específico da stream * [Viewer](Viewer) aperta no botão ```Clip``` * [Viewer](Viewer) aperta Alt + X * [Viewer](Viewer) é redirecionado para uma página de pré-visualização do [clipe](Clipe) * [Viewer](Viewer) publica o ```Clip``` <file_sep> **Sinônimos:** * Divulgar * Compartilhar **Noção:** * Ação realizada pelo usuário para compartilhar um conteúdo. **Impacto:** * [Usuário](User) compartilhou uma stream em sua rede social. * [Streamer](Streamer) fez um sorteio com os [Viewers] que compartilhassem sua [stream](Stream).<file_sep># Cenário 033 - Receber Notificação ## Título * [Usuário](User) recebe notificações ## Objetivo * Descrever como um usuário recebe notificação ## Contexto * [Usuário](User) recebe notificação ## Ator(es) * [Usuário](User) * [Twitch](Twitch) ## Recursos * Dispositivo eletrônico conectado à internet ## Exceções * [Usuário](User) não estar logado. ## Episódios * [Usuário](User) faz login na sua conta. * [Usuário](User) clica no ícone de notificações enviadas pela Twitch. * [Usuário](User) vizualiza notificação. <file_sep><img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/Compartilhar.png?raw=true" width=800px><file_sep>### 1. Plano de Elicitação |Data|Versão|Descrição|Autor| |----|----|----|----| |26/05/18|0.1|Plano de Elicitação|<NAME>| ### Índice * 1 Plano de Elicitação __________ #### 1. Plano de Elicitação <p align = justify> Na primeira etapa do Plano de Elicitação fora consultada fontes de informações por cada integrante da equipe, onde tais desenvolvem sua própria compreensão do domínio da aplicação. Através dessa compreensão, fora possível, aos leigos em relação a plataforma, identificar como funciona a interação entre os usuários e a <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a>. A utilização dos RichPicture's e a Argumentações gerados, é de grande valia nessa etapa do planejamento. Por isso, é de extrema necessidade registrar e documentar qualquer modificação significativa para o projeto. <p align = justify> A segunda etapa fora composta ao todo de duas técnicas: A <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/H%C3%ADbrido-(An%C3%A1lise-de-Protocolo--&-Observa%C3%A7%C3%A3o-Participativa)">Análise de Protocolo e Observação Participativa</a> através de uma mistura entre as duas, ocasionando numa técnica Híbrida. O objetivo principal era de entender como a plataforma funcionava como um todo e manter registrado todas as ideias e experiências que tenham a ver com a aplicação. A partir disso, será possível desenvolver ainda mais a compreensão do domínio. <p align = jusitfy> Na terceira etapa o uso de <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Questionario">Questionário</a>, <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Storytelling">Storytelling</a> e <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Introspec%C3%A7%C3%A3o">Introspecção</a> são os pontos cruciais. O objetivo é obter dados de forma clara e direta para que se possa trabalhar sobre. Além disso, outro objetivo é a resolução de conflitos que alguns requisitos possam apresentar durante o envolvimento dos Stakeholders. Tais técnicas implicam em um maior entendimento dos Stakeholders e do domínio. _________ ### 1.1 Técnicas Utilizadas * [Questionário](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Questionario) * [Introspecção](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Introspec%C3%A7%C3%A3o) * [Observação Participativa](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/H%C3%ADbrido-(An%C3%A1lise-de-Protocolo--&-Observa%C3%A7%C3%A3o-Participativa)) * [MoSCoW](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/MoSCoW) * [Análise de Protocolo](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/H%C3%ADbrido-(An%C3%A1lise-de-Protocolo--&-Observa%C3%A7%C3%A3o-Participativa)) _________ ## Personas * Ferramenta utilizada: [Gerador de Personas](https://geradordepersonas.com.br/) <img src="./images/Personas/StreamerPersona.png"> <img src="./images/Personas/ViewerPersona.png"><file_sep>|Data|Versão|Autor|Modificação| |----|----|---|----| |27/03/2018|1.0|<NAME>, <NAME>|Criação do Documento| |08/05/2018|1.1|<NAME>|Edição do Documento| ### No que consiste a técnica? <p align="justify"> * Introspecção é uma técnica muito rica e profunda. Consiste em entender quais propriedades o sistema deve possuir para que seja um sucesso. Demanda o Engenheiro de Requisitos imaginar o que ele gostaria, se ele estivesse que desempenhar uma dada tarefa, com os equipamentos disponíveis e demais recursos. </p> ### Objetivo <p align="justify"> * A técnica tem como principal objetivo fazer com que o Engenheiro de Requisitos imagine como um possível usuário do software poderia querer, conseguido assim, levantar requisitos (na maioria dos casos, histórias de usuário). </p> ### Método utilizado * Histórias de usuário _____________________________ ## US's: * Eu, como streamer, gostaria de ter artifícios integrados à plataforma que tornassem possível, a exportação da livestream para outras plataformas, sem necessidade de estar com o setup ligado em várias plataformas. * Eu, como desenvolvedor, gostaria de criar uma Plataforma para livestreaming destinada a jogos. * Eu, como viewer, gostaria de acessar a twitch em outras plataformas de jogos que não sejam especificamente no computador. * Eu, como jogador, gostaria de adicionar [add-ons](Mods) à meus jogos. * Eu, como usuário, gostaria de salvar trechos marcantes de uma stream em um clipe. * Eu, como usuário, gostaria de ter acesso à conteúdos exclusivos, pagando por estes. * Eu, como streamer, gostaria de ter suporte para live streaming em consoles * Eu, como usuário, gostaria de ter acesso ao conteúdo da Twitch nas plataformas móveis (smartphones e tablets). * Eu, como usuário, gostaria de ter ferramentas de live stream da Twitch em ferramentas de jogos populares, como: Steam, Origin, PSN, Xbox Live. * Eu, como usuário, gostaria de ter ferramentas integradas a twitch para interação entre viewer e streamer. * Eu, como usuário, gostaria de ter uma plataforma de voz integrada ao app da twitch, para diversos fins. * Eu, como gamer, gostaria de streamar minha gameplay para outras pessoas verem. <file_sep>**Sinônimos:** * Trending Channels * Canais em Alta **Noção:** * Espaço que apresenta os canais que estão em alta naquele momento. **Impacto:** * Ao acessar a [Twitch](Twitch) é possível ver os canais em destaque. * O [Streamer] tem sua [Stream](Stream) exposta nos canais em destaque.<file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |27/05/2018|0.1|Criação do Documento|<NAME>| |29/05/2018|0.2|Adição de processo de verificação dos Léxicos|<NAME>| |04/06/2018|0.3|Adição de processo de verificação dos Cenários|<NAME>| # Inspeção de cenários e léxicos As inspeções de cenários e léxicos foram feitas de forma semi-automatizada, como é explicado a seguir. ## Cenários Para que os padrões de conteúdo e de estruturação dos [cenários](Cenários) fosse verificado, foi utilizado de um [script](https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/src/lexer-verifier.sh) para semi-automatizar a tarefa com intuito de agilizar o processo e reduzir as possíveis falhas humanas no processo de verificação. O passo a passo da verificação semi-automatizada dos cenários: ### 1. Inserção do diretório em que o script deve executar ![Diretório](./images/semi-automation/cenarios/step-1.png) ### 2. Verificação dos conteúdos de sinônimos dos cenários ![Diretório](./images/semi-automation/cenarios/step-2.png) ### 3. Verificação das noções dos cenários ![Diretório](./images/semi-automation/cenarios/step-3.png) ### 4. Verificação dos impactos dos cenários ![Diretório](./images/semi-automation/cenarios/step-4.png) ## Léxico Para que todos os termos que aparecem em [Léxico](Léxico) fossem linkados de forma rápida e eficiente, os membros utilizaram de um [script](https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/src/lexer_linker.py) que automatizou esse processo. O passo a passo do processo de verificação dos léxicos pode ser analisado abaixo: ### 1. Execução do *script* e `git status` para checar alterações ![Lexer Linker](./images/semi-automation/lexer_linker_run.png) ### 2. Uso do `git diff` para checar se alterações estão corretas ![Git diff](./images/semi-automation/git-diff-after-run.png) ## Scripts utilizados [lexer-verifier.sh](https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/src/lexer-verifier.sh) script em escrito `bash` por [Gabriel Ziegler](https://github.com/gabrielziegler3) em 27/05/18 [lexer_linker.py](https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/src/lexer_linker.py) script em escrito `python` por [Gabriel Ziegler](https://github.com/gabrielziegler3) em 27/05/18<file_sep># Cenário 025 - Tornar-se parceiro Twitch ## Título * Se tornar um parceiro Twitch. ## Objetivo * Se tornar um parceiro Twitch para monetizar suas streams. ## Contexto * O [streamer](Streamer) possui uma audiência média de espectadores simultâneos, muitos seguidores em seu canal ou outras redes sociais e faz transmissão com muita frequência. Com isso, o streamer deseja monetizar suas streams passando comerciais em suas transmissões. ## Ator(es) * Streamers, personalidades, ligas, equipes e torneios mais famosos do mundo. ## Recursos * CPU: Intel Core i5-4670 ou AMD equivalente. * MEMÓRIA: 8GB DDR3 SDRAM. * Sistema Operacional: Windows 7 Home Premium. * Software de Transmissão. * Internet. ## Exceções * [Usuário](User) não estar conectado à internet. ## Episódios * [Streamer](Streamer) começa a produzir transmissões ao vivo. * [Streamer](Streamer) produz vídeos com conteúdos de alta relevância. * [Streamer](Streamer) começa a ganhar muitos seguidores e inscrições em seu canal. * [Streamer](Streamer) passa a produzir vídeos com muita frequência. * [Streamer](Streamer) adquire audiência média de espectadores simultâneos. * [Streamer](Streamer) consegue se tornar um parceiro Twich. Referência: [Parceiro Twitch](https://help.twitch.tv/customer/pt_br/portal/articles/735127-dicas-para-se-inscrever-no-programa-de-parceiros)<file_sep># UC04 - Inscrição em Canal ### [Diagrama de caso de uso](Diagrama-inscrever-em-canal) ## Descrição * Este caso de uso descreve a inscrição em um canal por parte de um usuário. ## Atores * Usuário ## Pré-condições * O usuário deve ter acesso à internet * O canal que está sendo inscrito deverá ser parceiro twitch * O usuário deverá estar logado ## Fluxo de Eventos ### Fluxo Principal #### Este fluxo é iniciado quando o usuário já se encontra em um canal * 1. O usuário clica no botão "Increver-se" * 2. O usuário seleciona a opção "Inscrever-se agora" [FA-01] * 3. O sistema redireciona o usuário para uma tela que fornece a ele as opções de planos de inscrição * 4. O usuário seleciona o plano desejado * 5. O usuário seleciona a forma de pagamento * 6. O sistema fornece um formulário para prenchimento das informações de pagamento * 7. O usuário prenche as informações de pagamento * 8. O usuário confirma a inscrição * 9. O caso de uso é encerrado ### Fluxos Alternativos #### FA01 - O usuário utiliza o serviço da Twitch Prime para de inscrever * 1. O usuário seleciona a opção Inscrever-se utilizando Twitch Prime * 2. O usuário retorna ao passo 8 do fluxo principal ### Fluxo de Exceção #### FE01 - Ocorreu um erro no pagamento * 1. O usuário preencheu as informações de pagamento * 2. Algum errou aconteceu no processo * 3. O caso de uso se encerra incompleto. ## Pós-condição * O usuário agora está inscrito no canal.<file_sep>![Twitch](./imagens/Twitch_logo.svg) Repositorio direcionado para o processo de Engenharia de Requisitos da plataforma [Twitch](https://www.twitch.tv/) na disciplina [Requisitos de Software](https://matriculaweb.unb.br/graduacao/disciplina.aspx?cod=201308) da Universidade de Brasília. ## Equipe |Nome|E-mail|GitHub| |----|------|------| |<NAME>|<EMAIL>|[@pAmanda](https://github.com/pAmanda)| |<NAME>|<EMAIL>|[@filypsdias](https://github.com/filypsdias)| |<NAME>|<EMAIL>|[@gabrielziegler3](https://github.com/gabrielziegler3)| |<NAME>|<EMAIL>|[@gustavocarvalho1002](https://github.com/gustavocarvalho1002)| |<NAME>|<EMAIL>|[@joao4018](https://github.com/joao4018)| |<NAME>|<EMAIL>|[@TPFChaos](https://github.com/TPFChaos)| Para mais informações visite o nossa [GithubPage - Twitch.io](https://filypsdias.github.io/twitch.io) <file_sep><img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/comprarBits.png" width=900px> ### [Especificação de Caso de Uso](comprar-bits)<file_sep>## Subscriber **Sinônimos:** * Inscrito * Subscrito **Noção:** * [Viewer](Viewer) que usufrui da funcionalidade [subscribe](Subscribe). **Impacto:** * Esse [Streamer](Streamer) possui vários inscritos. * Usuário se tornou subscriber do canal ao realizar a [Inscrição](Subscribe). <file_sep># UC05 - Doação de Bits ### [Diagrama de caso de uso](Diagrama-doar-bits) ## Descrição * Esse caso de uso descreve como doar bits. ## Atores * Usuário ## Pré-condições * O usuário deve possuir bits associados à sua conta * O usuário deve estar assistindo uma transmissão ativa * O usuário receptor deve ser parceiro twitch ## Fluxo de Eventos ### Fluxo Principal * 1. O usuário está assistindo uma stream * 2. O usuário deseja doar bits * 3. O usuário seleciona a opção ```Cheer```[FA01][FE01] * 4. O usuário seleciona a quantidade de bits que deseja doar * 5. O usuário doa os bits selecionados * 6. O caso se encerra ### Fluxos Alternativos * [FA01] - O usuário não possui bits * 1. O usuário não possui bits * 2. O usuário realiza as etapas do fluxo principal da [UC06](Compra-de-Bits) * 3. O usuário retorna ao passo 4 do fluxo principal. ### Fluxo de Exceção * [FE01] - O usuário não possui e não deseja comprar bits * 1. O usuário não possui bits * 2. O usuário não deseja comprar bits * 3. O usuário é incapaz de realizar um cheer * 4. O fluxo principal não pode ser completado] * 5. O fluxo de exceção se encerra ## Pós-condição * Os bits do cheer são recebidos pelo destinatário<file_sep>## Subscribe **Sinônimos:** * Inscrever **Noção:** * Opção do [viewer](Viewer) de poder se inscrever à um canal de um [streamer](Streamer) via uma funcionalidade paga que proporciona mais vantagens em relação ao [follow](Dar-Follow) **Impacto:** * [Usuário](User) se inscreve num canal e recebe conteúdos exclusivos. * [Usuário](User) renovou a inscrição no canal que já era inscrito.<file_sep># UC01 - Visualização de [Stream](Stream) ### [Diagrama de caso de uso](Diagrama-Visualização-de-Stream) ## Descrição * Este caso de uso descreve a visualização de conteúdo multimídia ao vivo. ## Atores * Usuário ## Pré-condições * O usuário deve ter acesso à internet * O canal selecionado para visualização da transmissão deverá estar online ou hospendando alguma stream. ## Fluxo de Eventos ### Fluxo Principal * 1. O Usuário acessa o site da Twitch [FA01][FA02] * 2. O Usuário seleciona um jogo que gostaria de assistir[FA03][FA04][FA05] * 3. O Usuário seleciona algum canal disponível * 4. O Usuário assiste a stream [FE01] * 5. O caso de uso se encerra ### Fluxos Alternativos #### FA01 - O Usuário acessa a plataforma Desktop da Twitch. * 1. O Usuário abre a plataforma desktop. * 2. O Usuário seleciona Secção de Streams da plataforma. * 3. O usuário retorna ao passo 2 do fluxo principal. #### FA02 - O Usuário abre a plataforma com o aplicativo mobile. * 1. O Usuário abre o aplicativo. * 2. O Usuário retorna ao passo 2 do fluxo principal. #### FA03 - O Usuário procura a stream através da barra de busca. * 1. O Usuário procura o jogo através da barra de buscas. * 2. O Usuário retorna ao passo 4 do fluxo principal. #### FA04 - O Usuário seleciona uma stream dos canais em destaque. * 1. O Usuário escolhe uma stream dos streamers em destaque. * 2. O Usuário retorna ao passo 4. #### FA05 - O Usuário escolhe uma stream, dos canais que ele segue * 1. O Usuário escolhe uma stream dos canais seguidos. * 2. O Usuário retorna ao passo 4. ### Fluxo de Exceção #### FE01 - O Player da Stream apresenta um erro * 1. O Usuário está assistindo a uma stream * 2. O player da stream apresenta um erro * 3. O Usuário refresca a página ou sai da stream * 4. O Usuário retorna ao passo 5 do fluxo principal ## Pós-condição * O usuário assiste a stream.<file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |23/05/2018|0.1|Criação do Documento|<NAME>| |23/05/2018|0.2|Adição de itens na checklist |<NAME>| |27/05/2018|0.3|Atualização da checklist|<NAME>| -------------------------------- ### Checklist US - [x] 1 - Definição de Épicos - [x] 2 - Definição de Atores - [x] 3 - Padronização das US - [x] 4 - Critérios de Aceitação ------------------------------ ### 1 - Definição de Épicos |Item de Inspeção|Definição de Épicos| |------|-------| **Questões**|Os épicos foram definidos anteriormente as US? | **Resposta**|Sim| **Modificações**|Nenhuma| **Commit**|-| ### 2 - Definição de Atores |Item de Inspeção|Definição de Atores| |------|-------| **Questões**|As histórias de usuário tem atores definidos? Ex: ``` I, as <persona>, ... ``` | **Resposta**|Sim| **Modificações**|Nenhuma| **Commit**|-| ### 3 - Padronização das US |Item de Inspeção|Definição de Atores| |------|-------| **Questões**|As US estão estruturadas da forma correta? Ex: ``` As <persona> , I want <what?> so that <why?> ```| **Resposta**|Sim| **Modificações**|Foram corrigidas as US que não seguiam o padrão recomendado, ou estavam imcompletas. | **Commit**|[3232e34](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Product-Backlog/_compare/3232e34) , [85578b7](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Product-Backlog/_compare/85578b7)| ### 4 - Critérios de Aceitação |Item de Inspeção|Definição de Atores| |------|-------| **Questões**|As US tem critérios de aceitação?| **Resposta**|Sim| **Modificações**|As tabelas foram modificadas com a adição do campo "Critérios de Aceitação", sendo assim, todas as US que não continham critérios, foram modificadas para que tenha tal informação.| **Commit**|[cc07674](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Product-Backlog/_compare/cc07674) , [b94b575](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Product-Backlog/_compare/b94b575)| <file_sep><img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/streamer.png" width=900px> ### [Especificação de Caso de Uso](Visualização-de-stream)<file_sep>## O que é modelagem? > * Trata-se da atividade de elaborar modelos capazes de representar características ou comportamentos de um software. > * Usam uma notação específica, a qual varia de modelo para modelo. > * Tais modelos podem ser em diferentes níveis de abstração: > * desde bem abstratos - RichPicture e Mapas Mentais > * até mais técnicos - Modelos de Argumentação ## Por que modelar? > * Modelar é uma forma de tratar aspectos ou muito abstratos ou muito técnicos com apelo visual; seja tornando mais concreto e claro aspectos muito abstratos; seja simplificando aspectos muito técnicos, às vezes complexos e pouco conhecidos dos clientes de um software > * Dessa forma, devem ser valorizados modelos simples, claros, com notações adequadas e objetivas ## Propostas de Modelagem * [Léxico](Léxico) * [Cenários](Cenários) * [Especificação de Casos de Uso](Especificação-de-Casos-de-Uso) * [Especificação Suplementar](Especificação-Suplementar) * [Diagramas de Casos de Uso](Diagramas-de-Casos-de-Uso) * [Product Backlog](Product-Backlog) * [Product Backlog - Geral](Product-Backlog-Geral) * [Sprint Backlog #1](Sprint-Backlog) * [NFR](NFR) * [Diagramas I*](Diagramas-i*) * [Especificação I*](Especificação-i*) ## Refêrencias * <NAME>., Requisitos - Aula 10. Elicitação, Modelagem, Análise<file_sep># UC14 - Alterar Nome da [Stream](Stream) ### [Diagrama - Alterar Nome da Stream](Diagrama-Alterar-Nome-da-Stream) ## Descrição * Este caso de uso descreve a alteração do título/nome de uma stream ## Atores * [Streamer](Streamer) ## Pré-condições * O usuário deve ter acesso à internet * O usuário deve estar logado na twitch ## Fluxo de Eventos ### Fluxo Principal * 1. O usuário abre seu painel de controle [FA01] * 2. O usuário abre a aba de informações da transmissão * 3. O usuário digita o novo Título da transmissão * 4. O usuário confirma a alteração clicando em ```Atualizar Informações``` * 5. O caso de uso se encerra ### Fluxo Alternativo * [FA01] - O usuário altera o nome da transmissão pela página do canal * 1. O usuário acessa a página de seu canal * 2. O usuário seleciona a opção ```Editar```, localizada abaixo do player da transmissão * 3. O usuário retorna ao item 3 do fluxo principal ## Pós-condição * O nome da transmissão é alterado<file_sep>## [Donate](Donate) **Sinônimos:** * Doar * Fazer doação **Noção:** * Dar dinheiro à pessoa que está fazendo a [transmissão](Stream). **Impacto:** * O público deu ao [Streamer](Streamer) várias doações para incentiva-lo. * [Viewer](Viewer) estava gostando muito da [Stream] e resolveu doar ao [Streamer].<file_sep> <img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/MensagemPrivada.png?raw=true" width=900px> ### [Especificação de Caso de Uso](mensagens-privadas)<file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |06/04/2018|1.0|Criação do Documento|<NAME>| |06/04/2018|1.1|Referenciação das fontes|<NAME>| ## Dados e Estatísticas *** ## Total de visitas nos últimos seis meses(06/04/2018) ![](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/dados_estatistica/Visitas_Totais.png) _fonte: https://www.similarweb.com/website/twitch.tv#overview (acessado em 06/04/2018)_ *** ## Usuários nos últimos sete dias(06/04/2018) ![](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/dados_estatistica/Audiencia_7_dias.png) _fonte: https://twitchtracker.com/statistics (acessado em 06/04/2018)_ *** ## Visitas Totais e Media de Tempo Gasto na Twitch por Usuário ![](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/dados_estatistica/Visitas_Tempo_Quantidade.png) _fonte: https://www.similarweb.com/website/twitch.tv#overview (acessado em 06/04/2018)_ *** ## Horas totais gastas assistindo a Twitch ![](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/dados_estatistica/horas_totais_audiencia.png) _fonte: https://twitchtracker.com/statistics (acessado em 06/04/2018)_ *** ## País de origem das visitas a Twitch ![](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/dados_estatistica/Visitas_Paises.png) _fonte: https://www.similarweb.com/website/twitch.tv#overview (acessado em 06/04/2018)_ *** ## Usuários ao vivo por origem(06/04/2018 20:10 GTM-3) ![](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/dados_estatistica/Usuario_pais2.png) ![](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/dados_estatistica/Usuario_pais.png) _fonte: https://twitchtracker.com/statistics (acessado em 06/04/2018)_ *** ## Meios pelos quais os usuários chegam a Twitch pelo desktop ![](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/dados_estatistica/Fonte_das_visitas.png) _fonte: https://www.similarweb.com/website/twitch.tv#overview (acessado em 06/04/2018)_ *** ## Trafego na Twitch através de Redes Sociais ![](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/dados_estatistica/Trafego_por_redes_sociais.png) fonte: https://www.similarweb.com/website/twitch.tv#overview (acessado em 06/04/2018)_ *** ## Usuários que Acessaram a Twitch por meio de publicidade ![](https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/dados_estatistica/Trafego_origem_publicidade.png) Desse 0.07% de visitas provenientes de propagandas, tem suas origem a partir de: ![](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/dados_estatistica/Trafego_por_redes_sociais.png) fonte: https://www.similarweb.com/website/twitch.tv#overview (acessado em 06/04/2018)_ *** ## Referências de Outros Sites que Levam a Twitch/Referências da Twitch que Levam a Outros Sites ![](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/dados_estatistica/Destinos_Usuarios.png) fonte: https://www.similarweb.com/website/twitch.tv#overview (acessado em 06/04/2018)_ *** ## Empresas que utilizam da Twitch para fazer anúncios ![](https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/dados_estatistica/Anunciadoras.png) fonte: https://www.similarweb.com/website/twitch.tv#overview (acessado em 06/04/2018)_<file_sep>## [Streamer](Streamer) **Sinônimos:** * Transmissor **Noção:** * [Usuário](User) que realiza uma transmissão de jogo ao vivo na [Twitch](Twitch). **Impacto:** * O streamer abriu a [transmissão](Stream) * Eu gosto desse [Streamer](Streamer) * Eu vou usar a [Twitch](Twitch) para me tornar um [streamer](Streamer)<file_sep>**Noção:** * [Emotes](Emotes) animados comprados para mandar envio de [cheer](Cheer). **Impacto:** * [Usuário](User) compra bits para [doar](Cheer) ao [streamer](Streamer). * [Usuário](User) ganhou [emotes](Emotes) ao doar bits.<file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |09/04/2018|1.0|Criação do Documento|<NAME>| |09/04/2018|1.1|Desenvolvimento dos Cenários|<NAME>, <NAME>| |10/04/2018|1.2|Revisão|<NAME>, <NAME>| |10/04/2018|1.3|Hyperlink léxico|<NAME>| |10/04/2018|1.4|Revisão & Hyperlink léxico|<NAME>| |10/04/2018|1.5|Adição de cenários|<NAME>| |11/04/2018|1.6|Adição de cenários Se tornar parceiro Twitch e Criar coleções|Amanda Pires| |16/04/2018|1.7|Adição dos cenários 27,28 e 29|<NAME>| |16/04/2018|1.8|Ajustes no artefato e adição do cenário 30|<NAME>| |18/04/2018|1.9|Adição do cenário [Streamer](Streamer) criando video sob demanda|Amanda Pires| |19/04/2018|1.9|Adição do cenário 32|<NAME>| |21/04/2018|2.0|Revisão geral do artefato|<NAME>| |11/06/2018|2.1|Revisão do documento e inserção de Introdução, Objetivo e Metodologia|<NAME>| |11/06/2018|2.2| Adicionando cenário de notificação| <NAME>| ### 1. Introdução #### 1.1. Propósito * O documento a seguir possui a finalidade de apresentar uma visão sobre os cenários existentes na [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch). #### 1.2. Escopo * Tal documento apresenta os cenários existentes na [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch), tais quais definem detalhadamente os contextos, atores, recursos, pré-condições, pós-condições e os episódios da aplicação. ### 2. Objetivo * O objetivo a ser alcançado com a produção do artefato é de representar comportamentos do software para poder elicitar seu fluxo e sua dinâmica. ### 3. Metodologia * Para a elaboração deste documento, fora discutido e pensando a respeito de cada possível cenário da aplicação. ### 4. Cenários * [C001](Cenário-001) - Assistir uma [transmissão](Stream) * [C002](Cenário-002) - Cadastrar-se na [Twitch](Twitch) * [C003](Cenário-003) - [Dar follow](Dar-follow) em um [Streamer](Streamer) * [C004](Cenário-004) - [Subscrever](Subscribe) em um canal * [C005](Cenário-005) - [Clipar](Clipes) uma jogada * [C006](Cenário-006) - Realizar uma [transmissão](Stream) * [C007](Cenário-007) - Dar um ban ou permaban * [C008](Cenário-008) - Fazer [Donate](Donate) * [C009](Cenário-009) - Doar [Bits](Bits) * [C010](Cenário-010) - Adicionar amigos * [C011](Cenário-011) - Configurar Pagamento * [C012](Cenário-012) - Fazer denúncia * [C013](Cenário-013) - Fazer [host](Raid) de uma [transmissão](Stream) * [C014](Cenário-014) - Fechar [transmissão](Stream) * [C015](Cenário-015) - Fazer login * [C016](Cenário-016) - Selecionar [moderadores](Moderador) * [C017](Cenário-017) - Anunciar na [transmissão](Stream) * [C018](Cenário-018) - Acessar catálogo de Jogos * [C019](Cenário-019) - Acessar videos postados em um canal. * [C020](Cenário-020) - Acessar [clipes](Clipes) postados em um canal. * [C021](Cenário-021) - [Sussurar](Whisper). * [C022](Cenário-022) - Fazer Postagem. * [C023](Cenário-023) - Atualizar dados de perfil. * [C024](Cenário-024) - Mudar idioma da Twitch. * [C025](Cenário-025) - Tornar-se parceiro Twitch. * [C026](Cenário-026) - Criar coleções. * [C027](Cenário-027) - Dar [ban](Ban) em [viewer](Viewer). * [C028](Cenário-028) - Mudar o nome de sua [transmissão](Stream). * [C029](Cenário-029) - Iniciar uma [transmissão](Stream) * [C030](Cenário-030) - Compartilhar uma [transmissão](Stream). * [C031](Cenário-031) - Criar vídeos sob demanda. * [C032](Cenário-032) - Adicionar amigos. * [C033](Cenário-033) - Receber [notificação](Live-Notification). ___________ #### 5. Resultados * A partir da análise desses 32 cenários, pode-se obter os seguintes requisitos listados abaixo: |Requisito|Tipo| |---|---| |Assistir [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream)|Funcional| |Cadastrar na [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch)|Funcional| |Dar follow em um [Streamer](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Streamer)|Funcional| |Dar [subscribe](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Subscribe) em um canal|Funcional| |Clipar parte da [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream)|Funcional| |Realizar [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream)|Funcional| |Banir alguém do chat|Funcional| |Realizar [doações](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Donate)|Funcional| |Adicionar Amigos|Funcional| |Configurar forma de pagamento|Funciuonal| |Denunciar canal|Funcional| |Fazer host de uma [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream)|Funcional| |Fechar [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream)|Funcional| |Fazer login|Funcional| |Fazer login pelo Facebook|Funcional| |Anunciar na [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream)|Funcional| |Acessar catálogo de jogos|Funcional| |Acessar vídeos de um canal|Funcional| |Acessar [clipes](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Clipes)|Funcional| |[Sussurar](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Whisper)|Funcional| |Mudar idioma da [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch)|Funcional| |Tornar-se Twitch Partner|Não funcional| |Compartilhar [Stream](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream)|Funcional| |Receber [Notificação](Live-Notification)|Funcional| *** #### 6. Palavras chave 🔑: * Dispositivo eletrônico = Computador, celular ou similar * Periféricos = Mouse, teclado, tela touch ou similar * Transmissão de imagem = Monitor ou similar * v1 = Primeira vertente do cenário (caminho 1) * v2 = Segunda vertente do cenário (caminho 2) <div align="justify"> > * Cheering = Cheering é uma nova maneira de mostrar seu apoio aos streamers e celebrar os momentos que você ama com a comunidade. Tudo isso no bate-papo. Um Cheer é uma mensagem de bate-papo que usa Bits, emoticons animados evoluídos que você pode comprar. Bit Emoticons podem ser usados um a um, todos de uma vez ou como você quiser. Usar vários de uma só vez mostra mais apoio e cria emoticons mais legais! _[Fonte](https://help.twitch.tv/customer/pt_br/portal/articles/2449458-guia-do-cheering-beta-)_ </div> <div align="center"> ![Alt Text](http://i.imgur.com/Pnw2fs9.gif) </div> <file_sep><img src="./images/twitch-logo.png" width=600px height=200px> # Engenharia de Requisitos Repositório criado para versionamento dos artefatos produzidos para a disciplina de Requisitos de Software do Curso de Engenharia de Software da Universidade de Brasília, no primeiro semestre de 2018. ## Equipe de Requisitos de Software |Nome|E-mail|GitHub| |----|------|------| |<NAME>|<EMAIL>|[@pAmanda](https://github.com/pAmanda)| |<NAME>|<EMAIL>|[@filypsdias](https://github.com/filypsdias)| |<NAME>|<EMAIL>|[@gabrielziegler3](https://github.com/gabrielziegler3)| |<NAME>|<EMAIL>|[@gustavocarvalho1002](https://github.com/gustavocarvalho1002)| |<NAME>|<EMAIL>|[@joao4018](https://github.com/joao4018)| |<NAME>|<EMAIL>|[@thiagoiferreira](https://github.com/thiagoiferreira)| ## A Plataforma Twitch.tv <p align="justify"> A <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a> é uma plataforma de live <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream">streaming</a> destinada à <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream">streaming</a> de jogos digitais. A <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a> foi lançada em 2011 como uma plataforma externa ao hoje extinto, justin.tv. Em 2014 a <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a> foi adquirida pela Amazon e em 2016, esta teve os serviços da Curse, Inc incorporados à plataforma. Atualmente a <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a> é a maior plataforma destinada, exclusivamente a live <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream">streaming</a> da internet, sendo a maior, destinada à jogos, tendo mais de 100 milhões de acessos mensais.<br> A <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a> busca, acima de tudo, tornar possível que as pessoas consigam viver, exclusivamente de live <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream">streaming</a>. A plataforma possui incorporada diversos sistemas que trazem lucro ao <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Streamer">streamer</a> e geralmente, quando este atinge certa popularidade, a <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a> oferece uma parceria ao streamer, dando-o uma maior parcela dos lucros obtidos por ele, através das subscriptions e dos ads que o mesmo roda.<br> A <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch">Twitch</a>, além de ser uma plataforma de live <a href="https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Stream">streaming</a>, também oferece outras funcionalidades em seu aplicativo do desktop, tal como a integração da plataforma com a adição de [add-ons](Mods) em certos jogos e também um serviço de voice [chat](Group-Chat), com salas e chamadas individuais. </p><file_sep># Cenário 004 - [Subscrever](Subscribe) em um canal ## Título * Inscrever-se em um canal ## Objetivo * Se inscrever em um canal para receber suas notificações e obter privilégios * Ter o canal na homepage da Twitch.tv ## Contexto * Pessoa já autenticada na Twitch ## Ator(es) * [Viewer](Viewer) * [Streamer](Streamer) ## Recursos * Dispositivo eletrônico com acesso à internet * Conta na Twitch ## Exceções * [Viewer](Viewer) não estar conectado à internet * [Viewer](Viewer) não logado na Twitch.tv ## Episódios * [Viewer](Viewer) gosta de uma stream * [Viewer](Viewer) clica em ```Inscrever-se``` * Notificação na tela comprovando que ele está seguindo o [streamer](Streamer) <file_sep>**Sinônimos:** * Twitch.tv **Noção:** * Plataforma de [streaming](Streaming), in-game [add-ons](Mods) e voice [chat](Group-Chat) da [Amazon](Amazon) **Impacto:** * A [Twitch](Twitch) é uma plataforma de [Streaming](Streaming) * [Usuário](Usuário) acessa a Twitch para assistir [Streams](Stream)<file_sep>**Sinônimos:** * Live [Stream](Stream) * Transmissão ao vivo * Live **Noção:** * Captura de vídeo transmitida ao vivo por um usuário **Impacto:** * [Streamer](Streamer) hospeda uma [Stream](Stream). * A [Twitch](Twitch) é uma plataforma aonde as pessoas assistem e hospedam [Streams](Stream).<file_sep># Cenário 006 - Transmitir uma [transmissão](Stream) ## Título * [Streamer](Streamer) transmitindo seu jogo ## Objetivo * [Usuário](User) realizar uma stream ## Contexto * [Usuário](User) logado * [Usuário](User) com softwares de transmissão requeridos * [Usuário](User) com especificações de máquina de acordo ## Ator(es) * [Streamer](Streamer) ## Recursos * [XSplit](https://www.xsplit.com/pt/?utm_source=blog&utm_campaign=rc_blogpost#broadcaster) (software de transmissão) * Máquina de acordo com as [especificações](https://help.twitch.tv/customer/pt_br/portal/articles/792761-como-transmitir-jogos-de-computador) da Twitch ## Exceções * [Usuário](User) sem o [XSplit](https://www.xsplit.com/pt/?utm_source=blog&utm_campaign=rc_blogpost#broadcaster) * [Usuário](User) com a máquina sem as especificações recomendadas ## Episódios * [Usuário](User) abre o software de transmissão * [Usuário](User) começa a gravar sua tela * [Usuário](User) acessa a área de _Broadcast_ dentro do software de transmissão * [Usuário](User) permite o acesso do software à sua conta da Twitch * [Usuário](User) streama seu jogo <file_sep><img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/Transmitir%20multimidia.png?raw=true" width=900px> ### [Especificação de Caso de Uso](Transmissão-de-ads)<file_sep># Cenário 017 - Anunciar na [transmissão](Stream) ## Título * Monetização através de anúncio. ## Objetivo * Transmitir anúncios em stream. ## Contexto * Estar acontecendo a stream. ## Ator(es) * [Streamer](Streamer) . ## Recursos * Stream online. ## Exceções * Não ter anúncios. * [Usuário](User) com softwares que bloqueiam anúncios ## Episódios * Autorizar anúncio. * Receber anúncio. * Monetizar transmissão. <file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |01/04/2018|1.0|Criação do Documento|<NAME>| |01/04/2018|1.1|Desenvolvimento dos RichPictures|<NAME>, <NAME>| |01/04/2018|1.2|Referenciação de links dos RichPictures|<NAME>| |10/06/2018|1.3|Adição Geral 1.1 & Streamer 1.1|<NAME>| |10/06/2018|1.4|Adicionando Rich Picture's e Estruturando documento|Amanda Pires| |11/06/2018|1.5|Adicionando Resultados e Conclusão|<NAME>| |11/06/2018|1.6|Adicionando requisitos levantados|Amanda Pires| ## Rich Picture ## 1. Introdução ### 1.1. Definição Rich Picture é uma técnica simples de modelagem com o objetivo de analisar problemas e expressar ideias. Das vantagens de se utilizar essa técnica, algumas serão citadas abaixo: * Rápida identificação de requisitos. * Rápida identificacão de atores. * Auxilia na análise de processos. * Estabele relacionamentos entre atores. * Fácil de modelar e pode ser feito com o cliente. ### 1.2. Escopo Para ter uma visão geral sobre a plataforma [Twitch](Twitch), inicialmente será apresentado um Rich Picture geral que aborda algumas das principais modalidades do site. Em seguida, serão apresentados os Rich Pictures para cada ator, para que seja possível detalhar as principais funcionalidades e seus atores. Um usuário é o ator mais geral da [Twitch](Twitch), podendo se especializar em 3 outros atores, sendo eles visitante, [viewer](Viewer) e [streamer](Streamer). ### 1.3. Apresentação ### 1.3.1. [Twitch](Twitch) [Geral 1.0](./images/rich-picture/Twitch-1.0.jpeg) [Geral 1.1](./images/rich-picture/Twitch-1.1.png) [Geral 1.2](./images/rich-picture/Twitch-1.2.jpg) ![Geral 1.3](./images/rich-picture/Twitch-1.3.png) ### 1.3.2. [User](User) [User 1.0](./images/rich-picture/User-1.0.jpg) ![User 1.1](./images/rich-picture/User-1.1.jpg) ### 1.3.3. [Streamer](Streamer) [Streamer 1.0](./images/rich-picture/Streamer-1.0.jpeg) [Streamer 1.1](./images/rich-picture/Streamer-1.1.jpg) [Streamer 1.2](./images/rich-picture/Streamer-1.2.jpeg) ![Streamer 1.3](./images/rich-picture/Streamer-1.3.jpg) ### 1.3.4. [Patrocinador](Patrocinador) ![Patrocinador 1.0](./images/rich-picture/Patrocinador-1.0.png) ### 2. Requisitos Levantados |Requisito|Descrição| |---|---------| |RF1| Cadastrar na [Twitch](Twitch)| |RF2| Conectar ao Facebook| |RF3| Assistir lives na [Twitch](Twitch)| |RF4| Divulgar anúncios em lives| |RNF5| Ter disponibilidade 24 horas| |RF6| Monetizar [stream](Stream)| |RF7| Inscrever em canal| |RF8| Interagir com jogadores através do chat| |RF10| Tornar usuário prime| |RNF11| Ter portabilidade (multi-plataforma)| |RNF12| Ter boa acessibilidade| |RF13| Manter cadastro| |RF14| Ser parceiro da [Twitch](Twitch)| |RF15| Compartilhar lives no Facebook| |RF16| Clipar uma jogada| |RF17| Seguir um usuário| |RF18| Realizar pagamento| |RF19| Competir com outros jogadores| |RF20| Receber [notificações](Live-Notification)| ### 3. Resultados * Ao todo foram elaborados 11 RichPicutres, cujo foco estão nos três atores principais que atuam na plataforma [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch) como um todo e 20 requisitos foram levantados, entre funcionais e não funcionais. ### 4. Conclusão * Através do RichPicture pode-se compreender melhor o domínio da [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch), como um todo, no qual serão levantados os requisitos e funcionalidades que vem sido destacadas desde a Pré Rastreabilidade. O artefato consegue mostrar, apesar da sua simplicidade, determinado contexto em um domínio específico de forma simples e eficaz. <file_sep>## Bot **Sinônimos:** * Robô<br> ##### Noção * Mecanismo de envio de mensagem automáticas criada pelo [streamer](Streamer) para atuar no chat. **Impacto:** * [Streamer](Streamer) usa um bot como [moderador](Moderador) de seu [chat](Group-Chat). * Bot enviou um alerta no [chat](Group-Chat).<file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |23/05/2018|0.1|Criação do Documento.|<NAME>| |23/05/2018|0.2|Adição de planejamento, apresentação e preparação ao documento.|<NAME>| |23/05/2018|0.3|Padronização do documento|<NAME>| |27/05/2018|0.4|Finalização do documento|<NAME>| ### Planejamento Os membros do grupo optaram por um reparticionamento da inspeção, onde cada indivíduo, com sua devida parte determinada previamente, seria responsável pela revisão e evolução do documento cabível a ele. O artefato em questão a ser inspecionado são as histórias de usuários. ### Visão Geral * [Product Backlog](Product-Backlog). ### Preparação Para a verificação do documento em questão, será feita uma Leitura Baseada em Checklist(LBCh), onde através de um levantamento de itens a serem checados, será verificado se o mesmo contém algum tipo de inconsistência. ### Realização da Inspeção [Checklist da Veriricação de Histórias de Usuário](Checklist-da-US) ### Retrabalho * Foram adcionados critérios de aceitação as US que não continham esse tipo de informação * Uma tabela geral foi criada, para fazer o agrupamentos de todas as US em uma só imagem. * Foi feita a reestruturação de algumas frases escritas na US para obdecer o padrão correto. ### Verificação * Até o dia 27/05/2018, todos os erros encontrados foram corrigidos. <file_sep># Cenário 009 - Doar [Bits](Bits) ## Título * [Viewer](Viewer) doando bits ## Objetivo * [Viewer](Viewer) doar bits ao [streamer](Streamer) ## Contexto * [Viewer](Viewer) assistindo uma stream ## Ator(es) * [Viewer](Viewer) * [Streamer](Streamer) ## Recursos * Dispositivo eletrônico conectado à internet * Bits na conta do [viewer](Viewer) que fará a doação ## Exceções * Dispositivo eletrônico não conectado à internet * O usuário não possui bits ## Episódios * [Viewer](Viewer) está assistindo stream * [Viewer](Viewer) clica em ```Start Cheering``` * [Viewer](Viewer) seleciona a quantidade de Bits a serem doados * [Viewer](Viewer) faz a doação <file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |09/05/2018|1.0|Criação do Documento|<NAME>| |12/05/2018|1.1|Adição dos link para o SD e SR|<NAME>| ## iStar O Framework i*, fundamentalmente, é orientado à diagramas, onde, estes possuem duas divisões, os diagramas Strategic Dependency (SD) e Strategic Rationale (SR), onde o primeiro possui uma abordagem interativa entre os atores determinados e o segundo, possui uma visão mais focalizado nos atores e seus papeis individuais.<br> Os Diagramas i*, são mais adequados para as fases iniciais do desenvolvimento de um software, onde, este framework visa facilitar a compreensão do domínio do problema que o desenvolvedor tem em mãos. <br> Neste documento, teremos os diagramas i* SR e SD, elaborados pela equipe de Requisitos de Software, responsável pela plataforma Twitch.tv, no primeiro semestre de 2018. Todos os diagramas foram feitos utilizando a ferramenta [piStar](http://www.cin.ufpe.br/~jhcp/pistar/). ## Diagramas * [Strategic Dependency Diagram](Strategic-Dependency) * [Strategic Rationale Diagram](Strategic-Rationale) <file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |03/04/2018|1.0|Criação do Documento|<NAME> e <NAME>| |06/04/2018|1.1|Inserção do link de Dados e Estatísticas|Filipe Dias| |17/04/2018|1.2|Remoção de Moscows anteriores, Adicão de novos|<NAME>| |11/06/2018|1.3|Revisão do Documento e inserção de Finalidade e Objetivo|Filipe Dias| |11/06/2018|1.4|Conversão da tabela MoSCoW para Markdown|<NAME>| ### 1. Introdução #### 1.1 Finalidade * O MoSCoW é uma técnica utilizada para auxílio na priorização de requisitos. Tal, tem o objetivo de estabelecer uma visão sobre quais requisitos serão prioridades na [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch) #### 1.2 Significado * O acrônimo MoSCoW se refere à: * ```MUST: requisitos que DEVEM estar de acordo com as necessidades do negócio.``` * ```SHOULD: requisitos que devem ser considerados ao máximo, mas que não impactam no sucesso do projeto.``` * ```COULD: incluir este requisito caso não afete o tamanho das necessidades de negócio do projeto.``` * ```WOULD: Incluir este requisito no caso de futuramente existir tempo sobrando (ou em futuros desenvolvimentos).``` ### 2. Objetivo * O objetivo principal ao utlizar a técnica é identificar e funcionalidades necessárias à [Twitch](https://github.com/gabrielziegler3/Requisitos-2018-1/wiki/Twitch), tais quais possuem maior valor do ponto do vista do usuário. ### 3. Metodologia * O MoSCoW fora realizado ao estudar os artefatos de Análise de Protocolo, Questionário e Observação Participativa. Tal, fora dividido de acordo com o ator ou contexto específico. #### 4. MoSCoW Conta|Must|Should|Could|Would |:--------|:----:|:------:|:------:|:-----:| O Usuário deverá ser capaz de se cadastrar com o Facebook|||X| O Usuário deverá ser capaz de se cadastrar com a conta do Google|||X| O Usuário deverá ser capaz de se cadastrar com uma conta do Reddit||||X O Usuário deverá ser capaz de fazer login com uma conta da Amazon||X|| O Usuário deverá ser capaz de fazer login com uma conta do Twitter||||X O Usuário deverá ser capaz de linkar sua conta com a Steam|||X| O Usuário deverá ser capaz de linkar sua conta com o Discord|||X| O Usuário deverá ser capaz de linkar sua conta com a Battle.net|||X| O Usuário deverá ser capaz de Criar uma conta na Twitch|X||| O Usuário deverá ser capaz de deslogar da Twitch|X||| O Usuário deverá ser capaz de fazer login na Twitch|X||| O Usuário deverá ser capaz de alterar sua senha|X||| --- Chat|Must|Should|Could |Would |:--------|:----:|:------:|:------:|:-----:| O Usuário deverá estar cadastrado para acessar os chats||X|| O Usuário deverá poder filtrar quem digita no chat de sua stream|X||| O Usuário deverá poder banir alguém do chat de sua stream||X|| O Usuário deverá poder alterar o jogo que está jogando durante a duração da stream|||| O Usuário deverá estar cadastrado para acessar os chats||X|| O Usuário deverá poder visualizar os chats da stream sem estar logado|||X| --- Stream|Must|Should|Could |Would |:--------|:----:|:------:|:------:|:-----:| O Usuário deverá poder transmitir a stream de outra pessoa em seu canal||||X O Usuário deverá poder mudar o nome da stream durante a mesma||X|| O Usuário deverá poder alterar o jogo que está jogando durante a duração da stream||X|| O Usuário deverá poder definir um idioma para a transmissão dele||X|| O Usuário deverá poder filtrar conteúdo de acordo com o Idioma|||X| O usuário deverá ser capaz de transmitir uma stream|X||| O Usuário deverá ser capaz de assistir uma stream|X||| O Usuário deverá ser capaz de criar clipes de momentos das streams|||X| O Usuário deverá poder assistir à uma stream ser fazer login||X|| O Usuário deverá poder adicionar uma descrição à seu perfil de streaming||X|| O Usuário deverá poder procurar streams através de um filtro por jogos|X||| O Usuário deverá poder procurar por streams através de uma barra de busca|X||| --- Follow e Doações|Must|Should|Could |Would |:--------|:----:|:------:|:------:|:-----:| O Usuário deverá ser capaz de seguir o streamer pra saber quando este está online||X|| O Usuário deverá poder fazer uma doação diretamente da plataforma twitch|||X| O Usuário deverá poder se inscrever de forma paga ao canal de um streamer|||X| O Usuário deverá poder deixar de seguir um streamer||X|| O Usuário deverá poder doar bits através de cheers à um streamer||||X O Usuário deverá poder comprar bits pra poder doar ||||X O Usuário deverá poder ver as pessoas que seguem determinado streamer||||X --- Twitch Add-ons|Must|Should|Could |Would |:--------|:----:|:------:|:------:|:-----:| O Usuário deverá poder fazer o download de add-ons pra determinados jogos|X||| O Usuário deverá poder adicionar os add-ons e sincronizar o jogo diretamento pelo app||X|| O Usuário deverá poder deletar os add-ons|X||| O Usuário deverá poder filtrar os add-ons por sua finalidade||X|| O Usuário deverá poder adicionar novos add-ons à plataforma|X||| O Usuário deverá poder atualizar os add-ons para novas versões de forma automatizada||X|| A plataforma deverá detectar automaticamente os jogos instalados e compatíveis|||X| --- Twitch Voice|Must|Should|Could |Would |:--------|:----:|:------:|:------:|:-----:| O Usuário deverá ser capaz de criar uma chamada nova|X||| O Usuário deverá poder filtrar quem entra em sua chamada|X||| O Usuário deverá ser capaz de adicionar amigos||X|| A Plataforma deverá possuir sincronização com alguns jogos|||X| A Plataforma deverá possibilitar a criação de grupos permanentes||X|| ___________ #### [Dados e Estatísticas](Dados-e-Estat%C3%ADsticas) <file_sep># UC02 - Transmissão Multimídia ### [Diagrama de caso de uso](Diagrama-transmitir-multimídia) ## Descrição * Este caso de uso descreve como o usuário capturará dados e os enviará por streaming e esse conteúdo será transmitido no player da Twitch. ## Atores * [Streamer](Streamer) ## Pré-condições * O usuário deverá ter acesso à internet * O usuário deverá ter um software de captura * O usuário deverá ter os requisitos de hardware adequados para uma transmissão * O usuário deverá possuir uma conta na twitch * O usuário deverá estar logado na twitch * O usuário deverá ter inserido sua token de streaming no software ## Fluxo de Eventos ### Fluxo Principal * 1. O usuário abre o software de captura [FA01][FA02] * 2. O usuário configura o ambiente de captura * 3. A Chave de Transmissão é sincronizada [FE01] * 4. O usuário inicia a stream * 5. A stream é transmitida no canal do usuário da Twitch * 6. O caso de uso é encerrado ### Fluxos Alternativos #### FA01 - O Usuário transmitirá através de um Console * 1. O usuário aperta o botão de SHARE enquanto joga o jogo * 2. O usuário seleciona o serviço da Twitch * 3. O usuário retorna ao item 2 do fluxo principal #### FA02 - O usuário utiliza o aplicativo mobile para transmitir * 1. O usuário abre o aplicativo mobile * 2. O usuário seleciona a opção de transmissão do aplicativo * 3. O usuário retorna ao item 4 do fluxo principal ### Fluxo de Exceção #### FE01 - Erro de sincronização da chave de transmissão * 1. No 3o item do fluxo principal, se a chave estiver incorreta ou não existir, um erro ocorre a mensagem de erro é exibida. ## Pós-condição * A transmissão está ocorrendo de forma adequada e os dados capturados estão sendo mostrados corretamente no canal do usuário.<file_sep># UC18 - Compartilhar uma Transmissão ### [Diagrama - Compartilhar uma Transmissão](Diagrama-Compartilha-uma-Transmissão) ## Descrição * Este caso de uso descreve como um usuário pode compartilhar uma transmissão. ## Atores * Usuário. ## Pré-condições * O usuário deve ter acesso à internet. ## Fluxo de Eventos ## Fluxo Principal * 1. O usuário está assistindo uma transmissão. * 2. O usuário clica no botão de compartilhar a transmissão * 3. Seleciona a rede social que deseja compartilhar a transmissão [FE01] * 4. Finaliza o processo de compartilhamento ao clicar em compartilhar * 5. O caso de uso é encerrado ## Fluxo Alternativo * Não se aplica ## Fluxo de Exceção * [FE01] O Usuário desiste de compartilhar a transmissão * 1. O usuário desiste de compartilhar a transmissão * 2. O usuário clica fora da caixa de selecao de redes sociais * 3. O usuário não compartilha a transmissão * 4. O caso de uso se encerra incompleto ## Pós-condição * A transmissão é compartilhada<file_sep># UC09 - Restrições de (Chat)[Group-Chat] ### [Diagrama de caso de uso](Diagrama-Restrições-de-Chat) ## Descrição * Este caso de uso decreve como o usuário aplica um filtro de acesso ao (chat)[Group-Chat] ## Atores * Usuário ## Pré-condições * O usuário deve ter capacidades administrativas no canal * O usuário deve ter acesso a internet * O usuário deve estar logado em sua conta ## Fluxo de Eventos ### Fluxo Principal * 1. O usuário está no canal da transmissão. [FA01] * 2. O usuário abre as configurações do [chat](Group-Chat) da stream no canto inferior esquerdo do (chat)[Group-Chat] * 3. O usuário seleciona a opção ```Chat Somente seguidores```[FA02] * 4. O caso de uso é encerrado ### Fluxos Alternativos #### FA01 - O usuário está no painel de controle da stream * 1. O usuário está no painel de controle * 2. O usuário retorna ao passo 2 do fluxo principal #### FA02 - O usuário seleciona a opção [Chat](Group-Chat) somente para inscritos * 1. O usuário seleciona a opção de ```Chat somente para inscritos```. * 2. O usuário retorna ao passo 4 do fluxo principal. ### Fluxo de Exceção * Não se Aplica ## Pós-condição * O [chat](Group-Chat) agora possui restrições de acesso.<file_sep><img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Casos_de_uso/inscreverCanal.png" width=900px> ### [Especificação de Caso de Uso](Inscrição-em-canal)<file_sep>[Twitch TV](https://www.twitch.tv/) <file_sep># Cenário 026 - Criar coleções ## Título * Criar coleções ## Objetivo * Criar coleções para qualquer conjunto de vídeos que deseja destacar no canal, como uma introdução geral, um show recorrente, jogos transmitidos por um [Streamer](Streamer). ## Contexto * O [streamer](Streamer) deseja criar uma lista de reprodução para mostrar os seus melhores trabalhos. ## Ator(es) * Streamers. ## Recursos * Computador. * Internet. ## Exceções * [Usuário](User) não estar conectado à internet. ## Episódios * [Streamer](Streamer) entra na sua conta Twitch. * [Streamer](Streamer) navega até a aba Coleções do gerenciador de vídeo e clica no botão "Nova coleção", insere um nome à coleção (ele pode ser alterado depois) e clica em "Criar". * [Streamer](Streamer) clica no botão "Adicionar vídeos" para encontrar vídeos do seu canal e adicioná-los à sua coleção. * [Streamer](Streamer) procura os seus vídeos pela barra de rolagem para encontrar vídeos específicos do seu canal. * [Streamer](Streamer) clica em "Done" para salvar a coleção criada. Referência: [Criar coleções](https://help.twitch.tv/customer/pt_br/portal/articles/2752733-como-usar-as-coleções) <file_sep>## Dados da inspeção * Checklist de inspeção do NFR * Inspetor: <NAME> * Data: 23/05/2018 ## Inspeção dos NFR |Questão| Amanda| Filipe| Resposta| Modificações| |------|-------|-----|-------|-----| |1.Foram feitos NFR de requisitos não funcionais como usabilidade, manutenibilidade, confiabilidade, desempenho, portabilidade, reusabilidade, segurança?| Não, faltaram confiabilidade e reusabilidade.|Não|Não| Fazer o NFR confiabilidade.| |2.Dos NRF que foram criados, eles ficaram bem definidos?|Sim|Sim|Sim|Nenhuma| |3.As propagações de impactos ficaram corretamente atendidas?|Sim|Sim|Sim|Nenhuma| |4.Existem operacionalizações para os softgoals definidos?|Sim|Sim|Sim|Nenhuma| |5.Se sim, as operacionalizações de fato implementam o softgoal?|Sim|Sim|Sim|Nenhuma| |6.Os NFR faz uso de argumentações para detalhamento de alguns softgoals?|Faz pouco uso.|Sim|Sim|Nenhuma| |7.Existem legendas nos NFRs?|Não|Não|Não|Incluir legenda.| |8.As decomposições, nós filhos, atendem corretamente os softgoals, nós pais?|Sim|Sim|Sim|Nenhuma| |9.Há alguma informação inconsistente nos NFRs?|Não|Não|Não|Nenhuma| |10. Alguma interface ficou omitida ?|Não, todas interfaces foram citadas.|Não|Não|Nenhuma|<file_sep>**Sinônimos:** * Hospedar. * Compartilhar. **Noção:** * [Streamer](Streamer) hospeda a [transmissão ao vivo](Stream) de outro canal no seu próprio canal. * Ocorre quando o streamer hospeda outro canal. **Impacto:** * [Streamer](Streamer) hospeda o canal de outro [Streamer](Streamer). * Ao ativar uma [stream](Stream), a hospedagem é encerrada.<file_sep># UC13 - Assinar Twitch Prime ### [Diagrama de Caso de Uso](Diagrama-Assinar-Twitch-Prime) ## Descrição * Este caso de uso descreve a assinatura no Twitch Prime. ## Atores * Usuário * Sistema ## Pré-condições * O usuário deve ter acesso à internet * O usuário deve estar logado no sistema * O usuário não deve possuir uma assinatura ativa * O caso de uso é iniciado na página principa da Twitch ## Fluxo de Eventos ### Fluxo Principal * 1. O usuário clica em Twitch Prime. * 2. O usuário faz login em sua conta da Amazon * 3. O usuário preenche os dados da fatura [FE01] * 4. O usuário seleciona ```Comece a assistir agora``` * 5. O usuário conecta sua conta da Twitch * 6. O sistema sincroniza valida a conta Prime Vídeo * 7. O sistema fornece o serviço twitch prime[FA01] * 8. O caso de uso se encerra ### Fluxos Alternativos #### [FA01] O usuário deseja fazer um teste de 7 diais * 1. O usuário se direciona às opções do Prime Vídeo * 2. O usuário vai até a parte de pagamento * 3. O usuário cancela o pagamento * 4. O usuário possui 7 dias gratuitos de avaliação da Twitch Prime e Prime Vídeo * 5. O usuário retorna ao item 8 do fluxo principal #### [FA02] O usuário Já possui o serviço Prime Vídeo e quer obter o Twitch Prime * 1. O usuário se encontra no site da prime vídeo * 2. O usuário vai até opções * 3. O usuário seleciona a opção de vincular uma conta twitch * 4. O usuário realiza os procedimentos de validação do vínculo * 5. As contas agora estão sincronizadas * 6. O usuário seleciona a opção de ativar gratuitamente o serviço Twitch Prime * 7. O usuário agora é um usuário prime da Twitch * 8. O caso de uso se encerra. ### Fluxo de Exceção #### [FE01] O usuário não deseja preencher as informações de pagamento * 1. O usuário está na página de pagamento * 2. O usuário não quer utilizar seu cartão de crédito * 3. O usuário desiste de obter o Twitch Prime * 4. O caso de uso é encerrado incompleto ## Pós-condição * O usuário agora possui uma conta Prime na Twitch e na Amazon Vídeo<file_sep># Cenário 002 - Cadastrar-se na Twitch ## Título * Cadastrar na Twitch ## Objetivo * Descrever o processo de cadastro na plataforma ## Contexto * Pessoa deseja se tornar um membro da Twitch ## Ator(es) * Pessoa não cadastrada na plataforma ## Recursos * Dispositivo eletrônico conectado à internet * Conta no Facebook ## Exceções * Dispositivo eletrônico não estar conectado à internet * Não possuir conta no Facebook ## Episódios * A pessoa não cadastrada acessa o site da [Twitch.tv](https://www.twitch.tv) * A pessoa não cadastrada clica em Cadastre-se * v1: A pessoa preenche os dados requeridos * A pessoa clica em ```Cadastrar-se``` * v2: A pessoa clica em ```Conectar-se com o Facebook``` * A pessoa permite a Twitch usar os dados do Facebook para realizar o cadastro <file_sep>### Planejamento O grupo, como um todo, decidiu por dividir temas a cada integrante, visando identificar erros a serem corrigidos, para que fosse possível realizar o método escolhido para aplicação da Inspeção. O documento a ser inspecionado será o de Elicitação juntamente com as técnicas escolhidas para serem aplicadas ao próprio. ### Visão Geral Técnicas aplicadas à Elicitação: * [Questionário](Questionario) * [Storytelling](Storytelling) * [Análise de Protocolo & Observação Participativa](H%C3%ADbrido-(An%C3%A1lise-de-Protocolo--&-Observa%C3%A7%C3%A3o-Participativa)) * [Introspecção](Introspecção) ### Preparação * Plano de Elicitação: O grupo definiu quais integrantes participariam da elaboração do documento. Após divido, fora aplicado, logo em seguida, as técnicas de Elicitação. O grupo falhou ao não ter anexado à documentação do projeto o Plano de Elicitação e uma definição clara do que seria tal técnica. * Técnicas de Elicitação: Alguns dados que foram colhidos para o levantamento de resultados precisos não foram inseridos durante o processo de elaboração dos documentos. Ao se tratar do [Questionário](Questionario); foram levantadas 6 perguntas específicas, com o objetivo de obter o máximo de informações sobre um possível público alvo da [Twitch](Twitch). Fora realizada também a confecção de uma [Storytelling](Storytelling), que narrava uma conversa entre amigos, onde um incentivava os outros a baixarem o aplicativo da [Twitch](Twitch). Ao partir para o artefato [Híbrido](H%C3%ADbrido-(An%C3%A1lise-de-Protocolo--&-Observa%C3%A7%C3%A3o-Participativa)), que consta com uma junção de Análise de Protocolo e Observação Participativa, pôde-se obter informações cruciais a respeito do funcionamento da plataforma de [Streaming](Streaming). Por fim, ao desenvolver a [Introspecção](Introspec%C3%A7%C3%A3o), fora levantadas pequenas frases que definiam US (Histórias de usuário). ``` OBS: Todos os artefados de rastreabilidade, tais como dados obtidos, foram inseridos à documentação do projeto. ``` ### Realização da Inspeção [Checklist da Elicitação](Checklist-da-Elicita%C3%A7%C3%A3o) ### Retrabalho * Os membros do grupo identificaram os erros e a correção foi realizada e revisada. ### Acompanhamento * Todos os erros encontrados foram corrigidos. <file_sep>|Data|Versão|Descrição|Autor| |----|------|---------|-----| |01/04/2018|1.0|Criação do Documento|Gustavo Carvalho| |01/04/2018|1.1|Referenciação de links de imagens dos argumentos|Gustavo Carvalho| |01/04/2018|1.2|Descrição dos argumentos |<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>| |11/06/2018|1.3|Adicionando requisitos levantados| Amanda Pires| ## 1. Argumentação ### 1.1. Cadastro Argumentação - Cadastro Cadastro: Possibilidade de um indivíduo se cadastrar no site com email e nome de usuário, e a capacidade de acessar as funcionalidades do site. * i(p1): usuário se cadastra * i(p2): usuário assiste [stream](Stream) * i(p3): usuário pode dar [follow](Follower) [subscribe](Subscribe) * i(p4): usuário receber notificações de conteúdo * i(p5): usuário não se cadastra * i(p6): usuário pode acompanhar [chat](Group-Chat) <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_Argumenta%C3%A7%C3%A3o/cadastro-1.1.0.png" width=500px> ### 1.2. Subscribe Subscribe: Opção do usuário para se inscrever em um canal de um Streamer ​ pagando uma mensalidade para receber conteúdos exclusivos e maior interatividade com o ​ [Streamer](Streamer) . ​ * i(p1): Incentivo financeiro ao ​ [Streamer](Streamer) * i(p2): Benefícios exclusivos ao inscrito (subscriber​) * i(p3): Pouco diferencial de ​ subscribers ​ para ​ [followers](Follower) * i(p4): Estimula os ​[Streamers](Streamer) a produzir mais conteúdos exclusivos e menos abertos a todos espectadores <img src="https://github.com/gabrielziegler3/Requisitos-2018-1/blob/master/imagens/Imagens_Argumenta%C3%A7%C3%A3o/subscribe-1.0.0.png" width=500px> ### 1.3. Twitch-Partner Um Twitch Partner é o usuário que possui um grande número de [subcribers](Subscribe) e foi aceito para tal personagem, e com isso, pode arrecadar mais dinheiro com a divulgação de anúcios, em que metade fica para a [Twitch](Twitch) e a outra metade para o usuário. * i(p1): O [Twitch](Twitch) pode oferecer uma receita mensal para pessoas que gostam de jogar e têm disponibilidade. * i(p2): Para ganhar uma boa receita, o Twitch partner com muitas frequência e estar sempre jogando, diariamente. * i(p3): Ganhar dinheiro com [Twitch](Twitch) é muito difícil, pois o usuário deve usar a maior parte do seu tempo se dedicando ao site para ganhar pouco dinheiro. <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_Argumenta%C3%A7%C3%A3o/twitch-partner-1.0.0.png" width=500px> ### 1.4. [Twitch-Prime](Twitch-Prime) Opção de assinatura ​ premium ​ ao usuário, trazendo benefícios como: conteúdos exclusivos dentro de jogos, uma subscrição grátis por mês, sem anúncios, entre outros. * i(p1): Provém conteúdo exclusivo ao usuário * i(p2): Acesso à conteúdos da Prime Video Amazon * i(p3): Preço relativamente baixo * i(p4): A assinatura no Prime não traz um diferencial tão significativo ao usuário <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_Argumenta%C3%A7%C3%A3o/twitch-prime-1.0.0.png" width=500px> ### 1.5. [Twitch](Twitch) Desktop App * i(p1): Deveria, eu, como usuário, usar a [Twitch](Twitch) diretamente no browser ou baixar o aplicativo para desktop da mesma? * i(p2): O aplicativo baixável da [Twitch](Twitch) disponibiliza inicialização com o computador, [chat](Group-Chat) de voz e texto integrado, suporte para streaming e [add-ons](Mods) para diversos outros jogos, funções, estas últimas duas, que outrora foram proporcionadas pela plataforma Curse, hoje, integrada à [Twitch](Twitch). * i(p3): Entretanto, acessar por browser proporciona economia de memória, tanto RAM (quando não se quer utilizar a plataforma e ela está aberta) quanto de armazenamento, tempo de inicialização e não necessita de download algum. * i(p4): Caso o usuário goste muito de assistir [streams](Stream), é uma alternativa bem mais prática, que fará o mesmo, acessar de forma mais constante a plataforma. * i(p5): O Usuário de [Add-ons](Mods) que são muitíssimos, estes que anteriormente utilizavam a plataforma apenas para isto (World of Warcraft add-ons), podem passar a assistir [streams](Stream) por impulso, devido à disponibilização integrada da plataforma. * i(p6): Se o usuário não possui interesse em [add-ons](Mods) e o serviço de [chat](Group-Chat) da [Twitch](Twitch), não existem nenhum diferenciais indispensáveis que o levem a baixar a plataforma. * P1: A Praticidade envolvida no processo e as features adicionais, por mais que dispensáveis, ainda assim, podem se mostrar úteis e verdadeiros "game-changers" pros usuários, dito isso, temos P1(i(p2) & i(p4) , i(p3)) * P2: Entretanto, como uma grande parte do público frequentador da [Twitch](Twitch) vê vantagem nos serviços extra-stream que a plataforma oferece, assim como a praticidade pra quem vê exclusivamente streaming no app, o Aplicativo de Desktop continua sendo uma opção favorável e viável. <img src="https://raw.githubusercontent.com/gabrielziegler3/Requisitos-2018-1/master/imagens/Imagens_Argumenta%C3%A7%C3%A3o/twitch-desktop-app-1.0.0.png" width=500px> ### 2. Requisitos Levantados |Requisito|Descrição| |------|------| |RF1| Cadastrar na [Twitch](Twitch)| |RF2| Assitir stream| |RF3| Se inscrever em canal| |RF4| Receber [notificações](Live_Notification)| |RF5| Participar de [chat](Group-Chat)| |RF6| Monetizar [stream](Stream)| |RF7|Tornar-se prime| |RNF8| Ter portabilidade| ### 3. Conclusão * A argumentação é uma técnica bastante útil quando se trata de conflitos de pensamentos a respeito de um determinado contexto, inserido em um domínio específico. Ao utilizar da técnica, ficou mais claro como as coisas acontecem dentro da plataforma [Twitch](Twitch). <file_sep># Cenário 010 - Adicionar amigos ## Título * [Usuário](User) adicionando amigos ## Objetivo * Associar usuários à sua conta da Twitch (amigos) ## Contexto * [Usuário](User) logado na Twitch ## Ator(es) * [Usuário](User) ## Recursos * Conta na Twitch * Dispositivo eletrônico conectado à internet ## Exceções * Pessoa não possuir conta na Twitch * Pessoa não estar logada * Dispositivo eletrônico não conectado à internet ## Episódios * [Usuário](User) seleciona na parte inferior a opção de adicionar amigos * [Usuário](User) busca um amigo através do username * [Usuário](User) seleciona o amigo * [Usuário](User) clica na opção de adicionar * Notificação aparece ao outro usuário <file_sep># UC08 - Mensagens Privadas ### [Diagrama de caso de uso](Diagrama-Mensagens-Privadas) ## Descrição * Esse caso de uso descreve como mandar mensagens privadas na Twitch ## Atores * Usuário ## Pré-condições * O usuário deverá ter acesso à internet * O usuário deverá estar logado em sua conta twitch ## Fluxo de Eventos ### Fluxo Principal * 1. O usuário seleciona a barra de pesquisa lateral [FA01][FA02] * 2. O usuário digita o nome do usuário a qual deseja enviar uma mensagem privada[FE01] * 3. O usuário clica no nome do usuário encontrado desejado * 4. Um mini [chat](Group-Chat) é aberto na parte inferior da tela * 5. O usuário envia a mensagem para o usuário desejado[FE02] * 6. O caso se encerra ### Fluxos Alternativos #### FA01 - O usuário vai para a secção de amigos em seu dropdown * 1. O usuário seleciona a secção de amigos no dropdown de seu perfil * 2. O sistema redireciona o usuário para a página de amigos * 3. O usuário seleciona a opção de enviar mensagem privada na box do amigo escolhido * 4. O usuário retorna ao item 4 do fluxo principal #### FA02 - O usuario seleciona o amigo pra mandar mensagem na barra lateral * 1. O usuário seleciona o amigo que gostaria de enviar mensagem na barra lateral do site[FA01] * 2. O usuário retorna ao item 4 do fluxo principal ### Fluxo de Exceção #### FE01 - O usuário digita um nome de usuário errado * 1. O usuário digita o nome de usuário ao qual deseja conversar errado * 2. Uma mensagem na tela dizendo ```Infelizmente, não encontramos ninguém chamado <nomeDeUsuárioErrado>``` * 3. O usuário volta para o passo 2 do fluxo principal * 4. O caso de uso se encerra ### FE02 - O usuário é bloqueado durante a conversa * 1. O usuário encontra-se no item 5 do fluxo principal * 2. O usuário destinatário bloqueia o usuário remetente * 3. O usuário não pode mais enviar mensagens. * 4. O fluxo de exceção é encerrado ## Pós-condição * O usuário envia uma mensagem privada e o outro usuário recebe<file_sep>**Sinônimos:** * Sussurrar * Sussurro * Mensagem Privada **Noção:** * Tarefa realizada pelo [viewer](Viewer). * Acontece quando o [espectador](Viewer) está no [chat](Group-Chat) e deseja falar algo privado com um dos usuários. **Impacto:** * Dois [Usuários](User) enviam sussuros um ao outro. * O [Usuáŕio](User) enviou uma mensagem privada ao seu amigo chamando-o para assistir sua [Stream](Stream).<file_sep>Data|Versão|Descrição|Autor -----|------|---------|------- 17/04/2018|1.0|Criação do documento e adição dos Casos de Uso|João Carlos| 19/04/2018|1.1|Adição de Casos de Uso 01 e 13|Amanda Pires| 19/04/2018|1.2|Adição de Casos de Uso|<NAME>| 20/04/2018|1.3|Revisão|João Carlos| 22/04/2018|1.4|Adição de Casos de Uso 02, 03, 04, 05 e 06|Amanda Pires| 22/04/2018|1.5|Adição de Casos 16,17 e geral|<NAME>| 22/04/2018|1.6|Adição diagramas casos de uso 19 e 20| <NAME> * [UC Geral](Diagrama-Geral) * [UC01 - Visualizar Stream](Diagrama-Visualização-de-Stream) * [UC02 - Transmitir Multimídia](Diagrama-transmitir-multimídia) * [UC03 - Criar Conta](Diagrama-criar-conta) * [UC04 - Inscrever em Canal](Diagrama-inscrever-em-canal) * [UC05 - Doar Bits](Diagrama-doar-bits) * [UC06 - Comprar Bits](Diagrama-comprar-bits) * [UC07 - Gerar Token do Streamer](Diagrama-Geração-de-Token-do-Streamer) * [UC08 - Enviar Mensagens Privadas](Diagrama-Mensagens-Privadas) * [UC09 - Restringir Chat](Diagrama-Restrições-de-Chat) * [UC10 - Adicionar Add-ons em Jogos](Diagrama-Adição-de-Add-ons-em-Jogos) * [UC11 - Comunicar por Chat de Voz](Diagrama-Chat-de-Voz) * [UC12 - Transmitir Ads](Diagrama-Transmitir-Ads## ) * [UC13 - Assinar Twitch Prime](Diagrama-Assinar-Twitch-Prime) * [UC14 - Alterar Nome da Stream](Diagrama-Alterar-Nome-da-Stream) * [UC15 - Seguir Canal](Diagrama-Seguir-Canal) * [UC16 - Banir Viewer](Diagrama-Banir-Viewer) * [UC17 - Adicionar Amigo](Diagrama-Adição-de-Amigo) * [UC18 - Compartilhar uma Transmissão](Diagrama-Compartilhar-uma-Transmissão) * [UC19 - Criar Vídeo](Diagrama-Criar-Vídeo) * [UC20 - Hospedagem](Diagrama-Hospedagem) <file_sep>### Planejamento O grupo, como um todo, decidiu por dividir temas a cada integrante, visando identificar erros a serem corrigidos, para que fosse possível realizar o método escolhido para aplicação da Inspeção. O documento a ser inspecionado será o de Elicitação juntamente com as técnicas escolhidas para serem aplicadas ao próprio. ### Visão Geral * [Cenários](Cen%C3%A1rios) * [Léxicos](L%C3%A9xico) ### Preparação * O grupo definiu quais integrantes participariam da elaboração do documento. Após divido, fora aplicado, logo em seguida, as técnicas de Preparação. O grupo falhou ao não ter anexado à documentação do projeto o Plano de Verificação e uma definição clara do que seria tal técnica. ``` OBS: Todos os artefados de rastreabilidade, tais como dados obtidos, foram inseridos à documentação do projeto. ``` ### Realização da Inspeção [Checklist de Cenários e Léxicos](Checklist-Cen%C3%A1rios-e-L%C3%A9xicos) ### Retrabalho Os membros do grupo identificaram os erros e a correção foi realizada e revisada. ### Verificação Todos os erros encontrados foram corrigidos. <file_sep># Cenário 013 - Fazer [host](Raid) de uma outra [transmissão](Stream) ## Título * Hosteando outra stream ## Objetivo * Transferir [viewers](Viewer) para outro canal ## Contexto * [Streamer](Streamer) desejando ajudar outro canal ## Ator(es) * [Streamer](Streamer) ## Recursos * Dispositivo eletrônico conectado à internet ## Exceções * Dispositivo eletrônico não conectado à internet ## Episódios * [Streamer](Streamer) inicia uma stream * [Streamer](Streamer) digita ```/host nomeCanal``` * [Streamer](Streamer) começa a dar host em outro canal <file_sep># Cenário 001 - Assistir uma stream ## Título * Assistir uma stream ## Objetivo * Descrever como conseguir assistir uma stream ## Contexto * Pessoa busca se entreter assistindo alguém jogar * Pessoa busca aprender a respeito de um jogo ## Ator(es) * [Viewer](Viewer) * [Streamer](Cenário-001) ## Recursos * Dispositivo eletrônico conectado à internet ## Exceções * Não há [streamers](Cenário-001) streamando * Pessoa não conectada à internet ## Episódios * Pessoa está a procura de algo para se entreter * Pessoa está mexendo em alguma rede social * Pessoa encontra o link de um [Streamer](Cenário-001) em atividade * Pessoa acede ao link * Pessoa assiste a stream <file_sep># Cenário 024 - Mudar o idioma da Twitch. ## Título * Mudar tradução ## Objetivo * Mudar tradução da página para a de desejo do usuário. ## Contexto * Pessoa não consegue compreender o idioma da página em questão. ## Ator(es) * Usuário ## Recursos * Dispositivo eletrônico com acesso à internet ## Exceções * [Usuário](User) não estar conectado à internet. ## Episódios * [Usuário](User) clica em ```⏹⏹⏹``` ao lado esquerdo da barra de busca. * [Usuário](User) seleciona ```idioma``` no dropdown. * [Usuário](User) escolhe a língua de desejo
dfebbce3f8ff142eaa706fab15c11fd8c81aedee
[ "Markdown", "Python", "Shell" ]
158
Markdown
gabrielziegler3/Requisitos-2018-1
16b26b8ced1b3a97ebf2ddda2b4ff8d1558f05b5
5f1fac7407d179508f10158c04d8269acb5dfd84
refs/heads/main
<repo_name>gxmls/Python_Data<file_sep>/20210603-matplotlib-3.py ''' plt.xlabel() 对X轴增加文本标签 plt.ylabel() 对Y轴增加文本标签 plt.title() 对图形整体增加文本标签 plt.text() 在任意位置增加文本 plt.annotate() 在图形中增加带箭头的注解 ''' import numpy as np import matplotlib.pyplot as plt import matplotlib def f(t): return np.exp(-t)*np.cos(2*np.pi*t) matplotlib.rcParams['font.family']='STSong' matplotlib.rcParams['font.size']=10 a=np.arange(0.0,5.0,0.02) plt.subplot(211) #plt.subplot(nrows,ncols,plot_number) 在全局绘图区域中创建一个分区体系,并定位到一个字绘图区域 plt.plot(a,f(a)) plt.subplot(2,1,2) plt.xlabel('横轴:时间') plt.ylabel('纵轴:振幅') plt.title(r'正弦波实例',fontproperties='SimHei',fontsize=10) plt.annotate(r'$\mu=100$',xy=(2,1),xytext=(3,1.5),arrowprops=dict(facecolor='black',shrink=0.1,width=2)) plt.plot(a,np.cos(2*np.pi*a),'r--') #'r--'红色虚线 plt.show() <file_sep>/20210603-matplotlib-1.py import matplotlib.pyplot as plt import matplotlib matplotlib.rcParams['font.family']='SimHei' #pyplot并不默认支持中文显示,需要rcParams修改字体实现 'SimHei'是黑体 ''' 'font.family' 用于显示字体的名字 'font.style' 字体风格,正常'normal'或斜体'italic' 'font.size' 字体大小,整数字号或者'large'、'x‐small' ''' plt.plot([3,1,4,5,2]) #plt.plot()只有一个输入列表或数组时,参数被当作Y轴,X轴以索引自动生成 plt.ylabel("纵轴(值)") ''' plt.savefig("test",dpi=600) #plt.savefig()将输出图形存储为文件,默认PNG格式,可以通过dpi修改输出质量 ''' plt.show() <file_sep>/filesave/20210521-csv_save.py ''' np.savetxt(frame, array, fmt='%.18e', delimiter=None) • frame : 文件、字符串或产生器,可以是.gz或.bz2的压缩文件 • array : 存入文件的数组 • fmt : 写入文件的格式,例如:%d %.2f %.18e • delimiter : 分割字符串,默认是任何空格 np.loadtxt(frame, dtype=np.float, delimiter=None, unpack=False) • frame : 文件、字符串或产生器,可以是.gz或.bz2的压缩文件 • dtype : 数据类型,可选 • delimiter : 分割字符串,默认是任何空格 • unpack : 如果True,读入属性将分别写入不同变量 局限性:CSV只能有效存储一维和二维数组,np.savetxt() np.loadtxt()只能有效存取一维和二维数组 ''' import numpy as np a=np.arange(100,dtype=np.int32).reshape(5,20) np.savetxt("a.csv",a,'%d',delimiter=',') b=np.loadtxt("a.csv",dtype=np.float,delimiter=',') print(b) b=b=np.loadtxt("a.csv",dtype=np.int,delimiter=',') print(b) <file_sep>/20210521-nprandom.py import numpy as np from numpy import random a=np.random.rand(3,4,5) #rand(d0,d1,..,dn):根据d0‐dn创建随机数数组,浮点数,[0,1),均匀分布 print(a) a2=np.random.randn(3,4,5) #randn(d0,d1,..,dn):根据d0‐dn创建随机数数组,标准正态分布 print(a2) a3=np.random.randint(100,200,(3,4)) #randint(low[,high,shape]):根据shape创建随机整数或整数数组,范围是[low, high) print(a3) np.random.shuffle(a3) #shuffle(a):根据数组a的第1轴进行随排列,改变数组a print(a3) print(np.random.permutation(a3)) #permutation(a):根据数组a的第1轴产生一个新的乱序数组,不改变数组a print(a3) #a3没有被改变 b=np.random.randint(100,200,(8,)) print(np.random.choice(b,(3,2))) #choice(a[,size,replace,p]):从一维数组a中以概率p抽取元素,形成size形状新数组,replace表示是否可以重用元素,默认为False print(np.random.choice(b,(3,2),p=b/np.sum(b))) ''' np.random.uniform(low,high,size): 产生具有均匀分布的数组,low起始值,high结束值,size形状 np.random.normal(loc,scale,size): 产生具有正态分布的数组,loc均值,scale标准差,size形状 np.random.poisson(lam,size): 产生具有泊松分布的数组,lam随机事件发生率,size形状 ''' <file_sep>/20210603-matplotlib-5.py ''' plt.subplot2grid(GridSpec, CurSpec, colspan=1, rowspan=1) 理念:设定网格,选中网格,确定选中行列区域数量,编号从0开始 ''' import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec plt.subplot2grid((3,3),(0,0),colspan=3) plt.plot([3,1,4,5,2]) plt.subplot2grid((3,3),(1,0),colspan=2) plt.plot([3,1,4,5,2]) plt.subplot2grid((3,3),(1,2),rowspan=2) plt.plot([3,1,4,5,2]) plt.subplot2grid((3,3),(2,0)) plt.plot([3,1,4,5,2]) plt.subplot2grid((3,3),(2,1)) plt.plot([3,1,4,5,2]) plt.show() <file_sep>/filesave/20210521-csv_multi_dimen.py ''' a.tofile(frame, sep='', format='%s') • frame : 文件、字符串 • sep : 数据分割字符串,如果是空串,写入文件为二进制 • format : 写入数据的格式 np.fromfile(frame, dtype=float, count=‐1, sep='') • frame : 文件、字符串 • dtype : 读取的数据类型 • count : 读入元素个数,‐1表示读入整个文件 • sep : 数据分割字符串,如果是空串,写入文件为二进制 该方法需要读取时知道存入文件时数组的维度和元素类型 a.tofile()和np.fromfile()需要配合使用 可以通过元数据文件来存储额外信息 便捷存储: np.save(fname, array) 或np.savez(fname, array) • fname : 文件名,以.npy为扩展名,压缩扩展名为.npz • array : 数组变量 np.load(fname) • fname : 文件名,以.npy为扩展名,压缩扩展名为.npz ''' import numpy as np from numpy.core.records import fromfile a=np.arange(100,dtype=np.int32).reshape(5,5,4) a.tofile('F:\\Learning Python\\MOOC_data\\b.dat',sep=',',format='%d') c=np.fromfile('F:\\Learning Python\\MOOC_data\\b.dat',sep=',',dtype=int).reshape(5,5,4) print(c) <file_sep>/20210603-matplotlib-2.py import matplotlib.pyplot as plt plt.plot([0,2,4,6,8],[3,1,4,5,2]) plt.ylabel("Grade") plt.axis([-1,10,0,6]) #plt.axis([a, b, c, d]) 设置x轴的范围为[a, b],y轴的范围为[c, d] plt.show() <file_sep>/20210603-matplotlib-6.py ''' plt.subplot2grid(GridSpec, CurSpec, colspan=1, rowspan=1) 理念:设定网格,选中网格,确定选中行列区域数量,编号从0开始 ''' import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec gs=gridspec.GridSpec(3,3) ax1=plt.subplot(gs[0,:]) ax2=plt.subplot(gs[1,:-1]) ax3=plt.subplot(gs[1:,-1]) ax4=plt.subplot(gs[2,0]) ax5=plt.subplot(gs[2,1]) plt.show() <file_sep>/20210524-npstatistics.py import numpy as np from numpy.core.fromnumeric import argmax a=np.arange(15).reshape(3,5) print(a) print(np.sum(a)) #np.sum(a,axis=None): 根据给定轴axis计算数组a相关元素之和,axis整数或元组 print(np.mean(a,axis=1)) #np.mean(a,axis=None): 根据给定轴axis计算数组a相关元素的期望,axis整数或元组 ''' axis=0时,只对第一维度进行操作,即对三个矩阵[0 1 2 3 4],[5 6 7 8 9]和[10 11 12 13 14]进行操作得到每一列的期望[5. 6. 7. 8. 9.] axis=1时,对每一个矩阵进行操作,得到每一个矩阵的期望[2. 7. 12.] axis=None时,计算所有元素的期望得到7.0 ''' print(np.average(a,axis=0,weights=[10,5,1])) #average(a,axis=None,weights=None): 根据给定轴axis计算数组a相关元素的加权平均值 ''' 2.1878=(0*10+5*5+10*1)/(10+5+1) 4.1875=(2*10+7*5+1*12*1)/(10+5+1)=4.1875 ''' print(np.std(a)) #std(a,axis=None) 根据给定轴axis计算数组a相关元素的标准差 print(np.var(a)) #var(a,axis=None) 根据给定轴axis计算数组a相关元素的方差 b=np.arange(15,0,-1).reshape(3,5) print(b) print(np.min(b),np.max(b)) #np.min(b)/np.max(b): 计算数组b中元素的最小值、最大值 print(np.argmin(b),argmax(b)) #np.argmin(b)/np.argmax(b): 计算数组b中元素最小值、最大值的降一维后下标 ''' 降一维只扁平化数组b,比如最小元素1下标为14,最大元素15的下标为0 ''' print(np.unravel_index(np.argmax(b),b.shape)) #np.unravel_index(index,shape): 根据shape将一维下标index转换成多维下标 print(np.ptp(b)) #np.ptp(b): 计算数组b中元素最大值与最小值的差 print(np.median(b)) #np.median(b): 计算数组b中元素的中位数(中值) f=np.random.randint(0,20,(5)) print(f) print(np.gradient(f)) #np.gradient(f): 计算数组f中元素的梯度,当f为多维时,返回每个维度梯度 ''' 梯度:连续值之间的变化率,即斜率 XY坐标轴连续三个X坐标对应的Y轴值:a, b, c,其中,b的梯度是: (c‐a)/2 ''' <file_sep>/20210521-nparray.py import numpy as np from numpy.core.numerictypes import maximum_sctype def npSum(): a=np.array([0,1,2,3,4]) #np.array()生成一个ndarray数组 b=np.array([9,8,7,6,5]) c=a**2+b**3 return c c=np.array([[0,1,2,3,4],[9,8,7,6,5]]) ''' c=np.array(list/tuple, dtype=np.float32),不指定dtype时,NumPy将根据数据情况关联一个dtype类型 ''' print(npSum()) #np.array()输出成[]形式,元素由空格分割 print("c的维度:{}".format(c.ndim)) #.ndim:秩,即轴的数量或维度的数量 print("c的尺度:{}".format(c.shape)) #.shape:ndarray对象的尺度,对于矩阵,n行m列 print("c元素的个数:{}".format(c.size)) #.size:ndarray对象元素的个数,相当于.shape中n*m的值 print("c元素的类型:{}".format(c.dtype)) #.dtype:ndarray对象的元素类型 print("c元素的大小:{} bytes".format(c.itemsize)) #.itemsize:ndarray对象中每个元素的大小,以字节为单位 list_x=np.array([1,2,3,4]) #从列表类型创建 tuple_x=np.array((1,2,3,4)) #从元组类型创建 mix_x=np.array([[1,2],[3,4],(5,6)]) #从列表和元组混合类型创建 ls_range=np.arange(10) #np.arange(n):类似range(n)函数,返回ndarray类型,元素从0到n‐1 print(ls_range) ls_ones=np.ones((2,3,4)) #np.ones(shape):根据shape生成一个全1数组,shape是元组类型 print(ls_ones) #如果不指定dtype=np.int32,结果会输出每个元素为 "1." ls_zeros=np.zeros((3,6),dtype=np.int32) #np.zeros(shape):根据shape生成一个全0数组,shape是元组类型 print(ls_zeros) ls_full=np.full((2,4),5) #np.full(shape,val):根据shape生成一个数组,每个元素值都是val print(ls_full) ls_eye=np.eye(5,dtype=np.int32) #np.eye(n):创建一个正方的n*n单位矩阵,对角线为1,其余为0 print(ls_eye) #只有左上到右下的对角线为1 a=np.linspace(1,10,4) #np.linspace(start,stop,num):根据起(start)止(stop)数据等间距地填充num个数据,形成数组 a2=np.linspace(1,10,4,endpoint=False) #np.linspace(start,stop,num,endpoint=True/False):endpoint=False时不包括stop的数据 a3=np.linspace(1,10,4,retstep=True) #np.linspace(start,stop,num,retstep=True/False):retstep=True时,返回数据间的步长 print(a,a2,a3) b=np.concatenate((a,a2)) #将两个或多个数组合并成一个新的数组,注意是(a,a2)而不是a,a2 print(b) x=np.arange(24) print(x.reshape((3,8))) #.reshape(shape):不改变数组元素,返回一个shape形状的数组,原数组不变 print(x) #x没有被.reshape()修改 x.resize((3,8)) #与.reshape()功能一致,但修改原数组 print(x) #使用.resize()后x被修改 print(x.flatten()) #对数组进行降维,返回折叠后的一维数组,原数组不变 print(x) #x没有被.flatten()修改 x=x.astype(np.float) #astype()方法一定会创建新的数组(原始数据的一个拷贝),即使两个类型一致 print(x) ls=x.tolist() #.tolist():将数组转换成列表 print(ls) ra=np.arange(24,dtype=np.int32).reshape((2,3,4)) #2个3行4列二维数组组成的数组 print(ra) print(ra[1,2,3],ra[0,1,2],ra[-1,-2,-3]) #索引:每一个维度上的索引,用逗号分割 print(ra[:,1,-3]) #切片:选取一个维度用":",[:,1,-3]表示每一个维度上的第1行第-3个元素 print(ra[:,1:3,:]) #切片:[:,1:3,:]表示每一个维度上的第1行到第2行的每一个元素 print(ra[:,:,::2]) #切片:[:,:,::2]表示每一个维度上的每一行上的元素从0开始以2为步长切片 ma=ra/ra.mean() #数组与标量之间的运算作用于数组的每一个元素 print(ma) mb=np.sqrt(ra) print(np.maximum(ra,mb)) #运算结果为浮点数 print(ra>mb) #运算结果为bool <file_sep>/README.md # Python_data MOOC 嵩天Python数据分析与展示\ https://www.icourse163.org/learn/BIT-1001870002?tid=1464038455#/learn/announce <file_sep>/20210603-matplotlib-4.py ''' ∙ x : X轴数据,列表或数组,可选 ∙ y : Y轴数据,列表或数组 ∙ format_string: 控制曲线的格式字符串,可选 ∙ **kwargs : 第二组或更多(x,y,format_string) 当绘制多条曲线时,各条曲线的x不能省略 color : 控制颜色, color='green' linestyle : 线条风格, linestyle='dashed' marker : 标记风格, marker='o' markerfacecolor: 标记颜色, markerfacecolor='blue' markersize : 标记尺寸, markersize=20 '‐' 实线 '‐‐' 破折线 '‐.' 点划线 ':' 虚线 '' ' ' 无线条 '.' 点标记 '1' 下花三角标记 'h' 竖六边形标记 ',' 像素标记(极小点) '2' 上花三角标记 'H' 横六边形标记 'o' 实心圈标记 '3' 左花三角标记 '+' 十字标记 'v' 倒三角标记 '4' 右花三角标记 'x' x标记 '^' 上三角标记 's' 实心方形标记 'D' 菱形标记 '>' 右三角标记 'p' 实心五角标记 'd' 瘦菱形标记 '<' 左三角标记 '*' 星形标记 '|' 垂直线标记 ''' import numpy as np import matplotlib.pyplot as plt def f(t): return np.exp(-t)*np.cos(2*np.pi*t) a=np.arange(10) plt.plot(a,a*1.5,'go-',a,a*2.5,'rx',a,a*3.5,'*',a,a*4.5,'b-.') plt.show() <file_sep>/20210603-matplotlib-pie.py import matplotlib.pyplot as plt labels='Frogs','Hogs','Dogs','Logs' sizes=[15,30,45,10] explode=(0,0.1,0,0) plt.pie(sizes,explode=explode,labels=labels,autopct='%1.1f%%',\ shadow=False,startangle=90) plt.axis('equal') plt.show()
e2c88e038bbb28ef2ab0997b1f36fb8c0210d7a1
[ "Markdown", "Python" ]
13
Python
gxmls/Python_Data
60a8acb5a25da749968dd0212c00e1c9845b91ec
3197cbe2899bf65df7c87e12b1f3f66df5f776a7
refs/heads/master
<file_sep><?php namespace Dandomain\Xml\Product; use Dandomain\Xml\Element; class Advanced extends Element { /** @var string */ protected $vendorNumber; /** @var int */ protected $unitId; /** @var int */ protected $typeId; /** @var string */ protected $hidden; /** @var string */ protected $new; /** @var string */ protected $newPeriodId; /** @var string */ protected $frontPage; /** @var string */ protected $variantMasterId; /** @var string */ protected $maillistExport; /** @var string */ protected $toplistHidden; /** @var int */ protected $internalId; /** @var string */ protected $uniqueUrlName; /** @var string */ protected $barcodeNumber; /** @var string */ protected $googleFeedCategory; /** @var string */ protected $directLink; public function __construct($vendorNumber = null, $unitId = null, $typeId = null, $hidden = null, $new = null, $newPeriodId = null, $frontPage = null, $variantMasterId = null, $maillistExport = null, $toplistHidden = null, $internalId = null, $uniqueUrlName = null, $barcodeNumber = null, $googleFeedCategory = null, $directLink = null) { $this->vendorNumber = $vendorNumber; $this->unitId = $unitId; $this->typeId = $typeId; $this->hidden = $hidden; $this->new = $new; $this->newPeriodId = $newPeriodId; $this->frontPage = $frontPage; $this->variantMasterId = $variantMasterId; $this->maillistExport = $maillistExport; $this->toplistHidden = $toplistHidden; $this->internalId = $internalId; $this->uniqueUrlName = $uniqueUrlName; $this->barcodeNumber = $barcodeNumber; $this->googleFeedCategory = $googleFeedCategory; $this->directLink = $directLink; } public function getXml() { $xml = ''; if ($this->vendorNumber) { $xml .= '<VENDOR_NUM>' . $this->vendorNumber . '</VENDOR_NUM>'; } if ($this->unitId) { $xml .= '<PROD_UNIT_ID>' . $this->unitId . '</PROD_UNIT_ID>'; } if ($this->typeId) { $xml .= '<PROD_TYPE_ID>' . $this->typeId . '</PROD_TYPE_ID>'; } if ($this->hidden) { $xml .= '<PROD_HIDDEN>' . $this->hidden . '</PROD_HIDDEN>'; } if ($this->new) { $xml .= '<PROD_NEW>' . $this->new . '</PROD_NEW>'; } if ($this->newPeriodId) { $xml .= '<PROD_NEW_PERIOD_ID>' . $this->newPeriodId . '</PROD_NEW_PERIOD_ID>'; } if ($this->frontPage) { $xml .= '<PROD_FRONT_PAGE>' . $this->frontPage . '</PROD_FRONT_PAGE>'; } if ($this->variantMasterId) { $xml .= '<PROD_VAR_MASTER_ID>' . $this->variantMasterId . '</PROD_VAR_MASTER_ID>'; } if ($this->maillistExport) { $xml .= '<MAILLIST_EXPORT>' . $this->maillistExport . '</MAILLIST_EXPORT>'; } if ($this->toplistHidden) { $xml .= '<TOPLIST_HIDDEN>' . $this->toplistHidden . '</TOPLIST_HIDDEN>'; } if ($this->internalId) { $xml .= '<INTERNAL_ID>' . $this->internalId . '</INTERNAL_ID>'; } if ($this->uniqueUrlName) { $xml .= '<PROD_UNIQUE_URL_NAME>' . $this->uniqueUrlName . '</PROD_UNIQUE_URL_NAME>'; } if ($this->barcodeNumber) { $xml .= '<PROD_BARCODE_NUMBER>' . $this->barcodeNumber . '</PROD_BARCODE_NUMBER>'; } if ($this->googleFeedCategory) { $xml .= '<PROD_GOOGLE_FEED_CATEGORY>' . $this->googleFeedCategory . '</PROD_GOOGLE_FEED_CATEGORY>'; } if ($this->directLink) { $xml .= '<DIRECT_LINK>' . $this->directLink . '</DIRECT_LINK>'; } return $xml; } /** * @return string */ public function getVendorNumber() { return $this->vendorNumber; } /** * @param string $vendorNumber * @return Advanced */ public function setVendorNumber($vendorNumber) { $this->vendorNumber = $vendorNumber; return $this; } /** * @return int */ public function getUnitId() { return $this->unitId; } /** * @param int $unitId * @return Advanced */ public function setUnitId($unitId) { $this->unitId = $unitId; return $this; } /** * @return int */ public function getTypeId() { return $this->typeId; } /** * @param int $typeId * @return Advanced */ public function setTypeId($typeId) { $this->typeId = $typeId; return $this; } /** * @return string */ public function getHidden() { return $this->hidden; } /** * @param string $hidden * @return Advanced */ public function setHidden($hidden) { $this->hidden = $hidden; return $this; } /** * @return string */ public function getNew() { return $this->new; } /** * @param string $new * @return Advanced */ public function setNew($new) { $this->new = $new; return $this; } /** * @return string */ public function getNewPeriodId() { return $this->newPeriodId; } /** * @param string $newPeriodId * @return Advanced */ public function setNewPeriodId($newPeriodId) { $this->newPeriodId = $newPeriodId; return $this; } /** * @return string */ public function getFrontPage() { return $this->frontPage; } /** * @param string $frontPage * @return Advanced */ public function setFrontPage($frontPage) { $this->frontPage = $frontPage; return $this; } /** * @return string */ public function getVariantMasterId() { return $this->variantMasterId; } /** * @param string $variantMasterId * @return Advanced */ public function setVariantMasterId($variantMasterId) { $this->variantMasterId = $variantMasterId; return $this; } /** * @return string */ public function getMaillistExport() { return $this->maillistExport; } /** * @param string $maillistExport * @return Advanced */ public function setMaillistExport($maillistExport) { $this->maillistExport = $maillistExport; return $this; } /** * @return string */ public function getToplistHidden() { return $this->toplistHidden; } /** * @param string $toplistHidden * @return Advanced */ public function setToplistHidden($toplistHidden) { $this->toplistHidden = $toplistHidden; return $this; } /** * @return int */ public function getInternalId() { return $this->internalId; } /** * @param int $internalId * @return Advanced */ public function setInternalId($internalId) { $this->internalId = $internalId; return $this; } /** * @return string */ public function getUniqueUrlName() { return $this->uniqueUrlName; } /** * @param string $uniqueUrlName * @return Advanced */ public function setUniqueUrlName($uniqueUrlName) { $this->uniqueUrlName = $uniqueUrlName; return $this; } /** * @return string */ public function getBarcodeNumber() { return $this->barcodeNumber; } /** * @param string $barcodeNumber * @return Advanced */ public function setBarcodeNumber($barcodeNumber) { $this->barcodeNumber = $barcodeNumber; return $this; } /** * @return string */ public function getGoogleFeedCategory() { return $this->googleFeedCategory; } /** * @param string $googleFeedCategory * @return Advanced */ public function setGoogleFeedCategory($googleFeedCategory) { $this->googleFeedCategory = $googleFeedCategory; return $this; } /** * @return string */ public function getDirectLink() { return $this->directLink; } /** * @param string $directLink * @return Advanced */ public function setDirectLink($directLink) { $this->directLink = $directLink; return $this; } }<file_sep><?php namespace Dandomain\Import; class Product extends Import { protected $xmlStart = '<?xml version="1.0" encoding="utf-8"?><PRODUCT_EXPORT type="PRODUCTS"><ELEMENTS>'; protected $xmlEnd = '</ELEMENTS></PRODUCT_EXPORT>'; }<file_sep><?php namespace Dandomain; interface ImportExportClientInterface { /** * Will import the given file * * The $file should be accessible from the web * Returns the Dandomain status as an array * * @param string $file * @param array $params * @return array */ public function import($file, $params = []); /** * @param int $exportId * @param array $params * @return array */ public function export($exportId, $params = []); /** * Sets the main shop url, i.e. http://www.example.com * * @param string $host */ public static function setHost($host); /** * Sets the username to access the admin area * It is best practice to create a new user and password to use with import/export * * @param string $username */ public static function setUsername($username); /** * Sets the password to access the admin area * It is best practice to create a new user and password to use with import/export * * @param string $password */ public static function setPassword($password); }<file_sep><?php namespace Dandomain\Xml; interface ElementInterface { /** * @return string */ public function getXml(); }<file_sep><?php namespace Dandomain; use GuzzleHttp\Client as GuzzleHttpClient; class ImportExportClient extends GuzzleHttpClient implements ImportExportClientInterface { protected static $debug = false; protected static $host; protected static $username; protected static $password; public function import($file, $params = []) { $this->validateCredentials(); $url = sprintf( '%s/admin/modules/importexport/import_v6.aspx?response=1&user=%s&password=%s&file=%s', self::$host, self::$username, self::$password, rawurlencode($file) ); if (count($params)) { $url = $url . '&' . http_build_query($params); } return $this->get($url, [ 'connect_timeout' => 10, 'timeout' => 3600, // 1 hour timeout 'verify' => false, ]); } public function export($exportId, $params = []) { $this->validateCredentials(); $url = sprintf( '%s/admin/modules/importexport/export_v6.aspx?response=1&user=%s&password=%s&exportid=%d', self::$host, self::$username, self::$password, $exportId ); if (count($params)) { $url = $url . '&' . http_build_query($params); } if(self::$debug) { echo "Getting URL:\n"; echo $url . "\n"; } return $this->get($url); } protected function validateCredentials() { if(is_null(self::$host) || is_null(self::$username) || is_null(self::$password)) { throw new \RuntimeException('You have not set all the credentials required to run an import or export: host, username or password'); } } /** * Sets the debug mode * * @param boolean $debug */ public static function setDebug($debug) { self::$debug = (bool)$debug; } /** * Returns true if we are in debug mode * * @return bool */ public static function isDebug() { return self::$debug; } /** * Sets the main shop url, i.e. http://www.example.com * * @param string $host */ public static function setHost($host) { $host = rtrim($host, '/'); if(!filter_var($host, FILTER_VALIDATE_URL)) { throw new \InvalidArgumentException("'$host' is not a valid URL"); } self::$host = $host; } /** * Sets the username to access the admin area * It is best practice to create a new user and password to use with import/export * * @param string $username */ public static function setUsername($username) { self::$username = $username; } /** * Sets the password to access the admin area * It is best practice to create a new user and password to use with import/export * * @param string $password */ public static function setPassword($password) { self::$password = $<PASSWORD>; } }<file_sep><?php namespace Dandomain\Xml\Product; use Dandomain\Xml\Element; class Price extends Element { /** @var string */ protected $currencyCode; /** @var int */ protected $priceB2bId; /** @var int */ protected $amount; /** @var float */ protected $unitPrice; /** @var float */ protected $avance; /** @var float */ protected $specialOfferPrice; public function __construct($currencyCode = null, $priceB2bId = null, $amount = null, $unitPrice = null, $avance = null, $specialOfferPrice = null) { $this->currencyCode = $currencyCode; $this->priceB2bId = $priceB2bId; $this->amount = $amount; $this->unitPrice = $unitPrice; $this->avance = $avance; $this->specialOfferPrice = $specialOfferPrice; } public function getXml() { $xml = ''; if ($this->currencyCode) { $xml .= '<CURRENCY_CODE>' . $this->currencyCode . '</CURRENCY_CODE>'; } if ($this->priceB2bId) { $xml .= '<PRICE_B2B_ID>' . $this->priceB2bId . '</PRICE_B2B_ID>'; } if ($this->amount) { $xml .= '<AMOUNT>' . $this->amount . '</AMOUNT>'; } if ($this->unitPrice) { $xml .= '<UNIT_PRICE>' . $this->formatMoney($this->unitPrice) . '</UNIT_PRICE>'; } if ($this->avance) { $xml .= '<AVANCE>' . $this->formatMoney($this->avance) . '</AVANCE>'; } if ($this->specialOfferPrice) { $xml .= '<SPECIAL_OFFER_PRICE>' . $this->formatMoney($this->specialOfferPrice) . '</SPECIAL_OFFER_PRICE>'; } return $xml; } }<file_sep><?php namespace Dandomain\Export; class Tag extends Export { /** * @inheritdoc */ public function elements() { $this->validateParams(); return parent::elements(); } public function validateParams() { if(!isset($this->params['langid'])) { throw new \InvalidArgumentException('Language id is not set.'); } } }<file_sep><?php namespace Dandomain\Import; class Category extends Import { protected $xmlStart = '<?xml version="1.0" encoding="utf-8"?><PRODUCT_CATEGORY_EXPORT type="PRODUCTCATEGORIES"><ELEMENTS>'; protected $xmlEnd = '</ELEMENTS></PRODUCT_CATEGORY_EXPORT>'; }<file_sep><?php namespace Dandomain\Xml\Product; use Dandomain\Xml\Element; class Description extends Element { /** @var string */ protected $descriptionShort; /** @var string */ protected $descriptionLong; /** @var string */ protected $descriptionLong2; /** @var string */ protected $searchword; /** @var string */ protected $metaDescription; /** @var string */ protected $title; public function __construct($descriptionShort = null, $descriptionLong = null, $descriptionLong2 = null, $searchword = null, $metaDescription = null, $title = null) { $this->descriptionShort = $descriptionShort; $this->descriptionLong = $descriptionLong; $this->descriptionLong2 = $descriptionLong2; $this->searchword = $searchword; $this->metaDescription = $metaDescription; $this->title = $title; } public function getXml() { $xml = ''; if ($this->descriptionShort) { $xml .= '<DESC_SHORT><![CDATA[' . $this->descriptionShort . ']]></DESC_SHORT>'; } if ($this->descriptionLong) { $xml .= '<DESC_LONG><![CDATA[' . $this->descriptionLong . ']]></DESC_LONG>'; } if ($this->descriptionLong2) { $xml .= '<DESC_LONG_2><![CDATA[' . $this->descriptionLong2 . ']]></DESC_LONG_2>'; } if ($this->searchword) { $xml .= '<PROD_SEARCHWORD><![CDATA[' . $this->searchword . ']]></PROD_SEARCHWORD>'; } if ($this->metaDescription) { $xml .= '<META_DESCRIPTION><![CDATA[' . $this->metaDescription . ']]></META_DESCRIPTION>'; } if ($this->title) { $xml .= '<TITLE><![CDATA[' . $this->title . ']]></TITLE>'; } return $xml; } /** * @return string */ public function getDescriptionShort() { return $this->descriptionShort; } /** * @param string $descriptionShort * @return Description */ public function setDescriptionShort($descriptionShort) { $this->descriptionShort = $descriptionShort; return $this; } /** * @return string */ public function getDescriptionLong() { return $this->descriptionLong; } /** * @param string $descriptionLong * @return Description */ public function setDescriptionLong($descriptionLong) { $this->descriptionLong = $descriptionLong; return $this; } /** * @return string */ public function getDescriptionLong2() { return $this->descriptionLong2; } /** * @param string $descriptionLong2 * @return Description */ public function setDescriptionLong2($descriptionLong2) { $this->descriptionLong2 = $descriptionLong2; return $this; } /** * @return string */ public function getSearchword() { return $this->searchword; } /** * @param string $searchword * @return Description */ public function setSearchword($searchword) { $this->searchword = $searchword; return $this; } /** * @return string */ public function getMetaDescription() { return $this->metaDescription; } /** * @param string $metaDescription * @return Description */ public function setMetaDescription($metaDescription) { $this->metaDescription = $metaDescription; return $this; } /** * @return string */ public function getTitle() { return $this->title; } /** * @param string $title * @return Description */ public function setTitle($title) { $this->title = $title; return $this; } }<file_sep><?php namespace Dandomain; trait ImportExportClientTrait { /** * @var ImportExportClient */ protected $client; /** * @param ImportExportClient $client */ public function setClient(ImportExportClient $client) { $this->client = $client; } /** * @return ImportExportClient */ public function getClient() { if(!$this->client) { $this->client = new ImportExportClient(); } return $this->client; } }<file_sep><?php namespace Dandomain\Xml\Product; use Dandomain\Xml\Element; class Info extends Element { /** @var \DateTimeInterface */ protected $created; /** @var string */ protected $createdBy; /** @var \DateTimeInterface */ protected $edited; /** @var string */ protected $editedBy; /** @var int */ protected $viewed; /** @var int */ protected $salesCount; public function __construct(\DateTimeInterface $created = null, $createdBy = null, \DateTimeInterface $edited = null, $editedBy = null, $viewed = null, $salesCount = null) { $this->created = $created; $this->createdBy = $createdBy; $this->edited = $edited; $this->editedBy = $editedBy; $this->viewed = $viewed; $this->salesCount = $salesCount; } public function getXml() { $xml = ''; if ($this->created) { $xml .= '<PROD_CREATED>' . $this->created->format('d-m-Y H:i:s') . '</PROD_CREATED>'; } if ($this->createdBy) { $xml .= '<PROD_CREATED_BY>' . $this->createdBy . '</PROD_CREATED_BY>'; } if ($this->edited) { $xml .= '<PROD_EDITED>' . $this->edited->format('d-m-Y H:i:s') . '</PROD_EDITED>'; } if ($this->editedBy) { $xml .= '<PROD_EDITED_BY>' . $this->editedBy . '</PROD_EDITED_BY>'; } if ($this->viewed) { $xml .= '<PROD_VIEWED>' . $this->viewed . '</PROD_VIEWED>'; } if ($this->salesCount) { $xml .= '<PROD_SALES_COUNT>' . $this->salesCount . '</PROD_SALES_COUNT>'; } return $xml; } /** * @return \DateTimeInterface */ public function getCreated() { return $this->created; } /** * @param \DateTimeInterface $created * @return Info */ public function setCreated($created) { $this->created = $created; return $this; } /** * @return string */ public function getCreatedBy() { return $this->createdBy; } /** * @param string $createdBy * @return Info */ public function setCreatedBy($createdBy) { $this->createdBy = $createdBy; return $this; } /** * @return \DateTimeInterface */ public function getEdited() { return $this->edited; } /** * @param \DateTimeInterface $edited * @return Info */ public function setEdited($edited) { $this->edited = $edited; return $this; } /** * @return string */ public function getEditedBy() { return $this->editedBy; } /** * @param string $editedBy * @return Info */ public function setEditedBy($editedBy) { $this->editedBy = $editedBy; return $this; } /** * @return int */ public function getViewed() { return $this->viewed; } /** * @param int $viewed * @return Info */ public function setViewed($viewed) { $this->viewed = $viewed; return $this; } /** * @return int */ public function getSalesCount() { return $this->salesCount; } /** * @param int $salesCount * @return Info */ public function setSalesCount($salesCount) { $this->salesCount = $salesCount; return $this; } }<file_sep><?php namespace Dandomain\Import; class RelatedProduct extends Import { protected $xmlStart = '<?xml version="1.0" encoding="utf-8"?><EXPORT type="RELATEDPRODUCTS"><ELEMENTS>'; protected $xmlEnd = '</ELEMENTS></EXPORT>'; }<file_sep><?php namespace Dandomain\Import; class Result { /** * This is the raw XML * * @var string */ protected $xml; /** * @var string */ protected $type; /** * @var int */ protected $status; /** * @var \DateInterval */ protected $time; /** * @var int */ protected $count; /** * @var int */ protected $completed; /** * @var int */ protected $failed; /** * @var int */ protected $created; /** * @var int */ protected $modified; public function __construct($xml) { $this->xml = $xml; $xmlElement = new \SimpleXMLElement($xml); $this->type = (string)$xmlElement->TYPE; $this->status = (int)$xmlElement->STATUS; $this->count = (int)$xmlElement->COUNT; $this->completed = (int)$xmlElement->COMPLETED; $this->failed = (int)$xmlElement->FAILED; $this->created = (int)$xmlElement->CREATED; $this->modified = (int)$xmlElement->MODIFIED; // parse time preg_match('/([0-9]+):([0-9]+)/', (string)$xmlElement->TIME, $matches); $this->time = new \DateInterval('PT' . $matches[1] . 'H' . $matches[2] . 'M'); } /** * @return string */ public function getXml() { return $this->xml; } /** * @return string */ public function getType() { return $this->type; } /** * @return int */ public function getStatus() { return $this->status; } /** * @return \DateInterval */ public function getTime() { return $this->time; } /** * @return int */ public function getCount() { return $this->count; } /** * @return int */ public function getCompleted() { return $this->completed; } /** * @return int */ public function getFailed() { return $this->failed; } /** * @return int */ public function getCreated() { return $this->created; } /** * @return int */ public function getModified() { return $this->modified; } }<file_sep><?php namespace Dandomain\Xml; use Dandomain\Xml\Category\ParentCategory; use Doctrine\Common\Collections\ArrayCollection; class Category extends Element { /** * This is the category number within the Dandomain interface * * @var int */ protected $id; /** @var int */ protected $languageId; /** @var string */ protected $name; /** @var bool */ protected $hidden; /** @var int */ protected $sort; /** @var string */ protected $link; /** @var string */ protected $description; /** @var string */ protected $icon; /** @var string */ protected $subCategorySymbol; /** @var string */ protected $image; /** @var string */ protected $metaKeywords; /** @var string */ protected $metaDescription; /** @var string */ protected $title; /** @var int */ protected $internalId; /** @var string */ protected $uniqueUrlName; /** @var ArrayCollection|ParentCategory[] */ protected $parentCategories; /** @var string */ protected $directLink; public function __construct($id, $languageId, $parentCategories, $name = null, $hidden = null, $sort = null, $link = null, $description = null, $icon = null, $subCategorySymbol = null, $image = null, $metaKeywords = null, $metaDescription = null, $title = null, $internalId = null, $uniqueUrlName = null, $directLink = null) { $this->id = $id; $this->languageId = $languageId; $this->name = $name; $this->hidden = $hidden; $this->sort = $sort; $this->link = $link; $this->description = $description; $this->icon = $icon; $this->subCategorySymbol = $subCategorySymbol; $this->image = $image; $this->metaKeywords = $metaKeywords; $this->metaDescription = $metaDescription; $this->title = $title; $this->internalId = $internalId; $this->uniqueUrlName = $uniqueUrlName; $this->parentCategories = $parentCategories; $this->directLink = $directLink; } public function getXml() { $xml = '<PRODUCT_CATEGORY>'; $xml .= '<PROD_CAT_ID>' . $this->id . '</PROD_CAT_ID>'; $xml .= '<LANGUAGE_ID>' . $this->languageId . '</LANGUAGE_ID>'; if($this->name) { $xml .= '<PROD_CAT_NAME>' . $this->name . '</PROD_CAT_NAME>'; } $xml .= '<PROD_CAT_HIDDEN>' . ($this->hidden ? 'True' : 'False') . '</PROD_CAT_HIDDEN>'; if($this->sort) { $xml .= '<PROD_CAT_SORT>' . $this->sort . '</PROD_CAT_SORT>'; } if($this->link) { $xml .= '<PROD_CAT_LINK>' . $this->link . '</PROD_CAT_LINK>'; } if($this->description) { $xml .= '<PROD_CAT_DESCRIPTION><![CDATA[' . $this->description . ']]></PROD_CAT_DESCRIPTION>'; } if($this->icon) { $xml .= '<PROD_CAT_ICON>' . $this->icon . '</PROD_CAT_ICON>'; } $xml .= '<SUBCAT_SYMBOL>' . ($this->subCategorySymbol ? $this->subCategorySymbol : '') . '</SUBCAT_SYMBOL>'; if($this->image) { $xml .= '<PROD_CAT_IMAGE>' . $this->image . '</PROD_CAT_IMAGE>'; } if($this->metaKeywords) { $xml .= '<META_KEYWORDS>' . $this->metaKeywords . '</META_KEYWORDS>'; } if($this->metaDescription) { $xml .= '<META_DESCRIPTION>' . $this->metaDescription . '</META_DESCRIPTION>'; } if($this->title) { $xml .= '<TITLE>' . $this->title . '</TITLE>'; } if($this->internalId) { $xml .= '<INTERNAL_ID>' . $this->internalId . '</INTERNAL_ID>'; } if($this->uniqueUrlName) { $xml .= '<PROD_CAT_UNIQUE_URL_NAME>' . $this->uniqueUrlName . '</PROD_CAT_UNIQUE_URL_NAME>'; } if($this->directLink) { $xml .= '<DIRECT_LINK>' . $this->directLink . '</DIRECT_LINK>'; } $xml .= '<PARENT_CATEGORIES>'; foreach ($this->parentCategories as $parentCategory) { $xml .= $parentCategory->getXml(); } $xml .= '</PARENT_CATEGORIES>'; $xml .= '</PRODUCT_CATEGORY>'; return $xml; } }<file_sep><?php namespace Dandomain\Export; use Dandomain\ImportExportClient; use Dandomain\ImportExportClientTrait; class Export { use ImportExportClientTrait; /** * @var int */ protected $exportId; /** * @var array */ protected $params = []; public function __construct($exportId, $params = []) { $this->exportId = $exportId; $this->params = array_merge($this->params, $params); } /** * @return \Generator */ public function elements() { $client = $this->getClient(); $response = $client->export($this->exportId, $this->params); if($response->getStatusCode() != 200) { throw new \RuntimeException($response->getReasonPhrase()); } $xml = new \SimpleXMLElement($response->getBody()->getContents()); if(ImportExportClient::isDebug()) { echo "Export file XML:\n"; print_r($xml); } $filename = sys_get_temp_dir() . '/' . uniqid('export---' . date('Y-m-d-H-i-s') . '---') . '.xml'; if(ImportExportClient::isDebug()) { echo "Downloading export file to\n$filename\n"; } $client->get((string)$xml->FILE_URL, [ 'sink' => $filename ]); $elementTag = $lastTag = ''; $xml = new \XMLReader(); $xml->open($filename); while ($xml->read()) { if ($xml->nodeType != \XMLReader::ELEMENT || ($elementTag && $elementTag != $xml->localName)) { continue; } if(!$elementTag && $lastTag == 'ELEMENTS') { $elementTag = $xml->localName; } if($elementTag && $xml->localName == $elementTag) { yield new \SimpleXMLElement($xml->readOuterXml()); } $lastTag = $xml->localName; } $xml->close(); unset($xml); @unlink($filename); } /** * Set the language id parameter * * @param int $languageId * @return $this */ public function setLanguageId($languageId) { $this->params['langid'] = $languageId; return $this; } }<file_sep><?php namespace Dandomain\Xml; class Element implements ElementInterface { public function getXml() { return ''; } /** * Takes a number like 2 or 2.05 and returns 2,00 or 2,05 respectively * * @param float $money * @return string */ protected function formatMoney($money) { return number_format($money, 2, ',', ''); } }<file_sep><?php namespace Dandomain\Xml; use Dandomain\Xml\Product\Advanced; use Dandomain\Xml\Product\Category; use Dandomain\Xml\Product\CustomFields; use Dandomain\Xml\Product\Description; use Dandomain\Xml\Product\General; use Dandomain\Xml\Product\Info; use Dandomain\Xml\Product\Manufacturer; use Dandomain\Xml\Product\Media; use Dandomain\Xml\Product\Price; use Dandomain\Xml\Product\Stock; use Doctrine\Common\Collections\ArrayCollection; class Product extends Element { /** @var General */ protected $general; /** @var Advanced */ protected $advanced; /** @var Stock */ protected $stock; /** @var Info */ protected $info; /** @var Description */ protected $description; /** @var CustomFields */ protected $customFields; /** @var ArrayCollection|Category[] */ protected $categories; /** @var ArrayCollection|Price[] */ protected $prices; /** @var ArrayCollection|Manufacturer[] */ protected $manufacturers; /** @var ArrayCollection|Media[] */ protected $media; public function __construct(General $general, Advanced $advanced = null, Stock $stock = null, Info $info = null, Description $description = null, CustomFields $customFields = null, $categories = null, $prices = null, $manufacturers = null, $media = null) { $this->general = $general; $this->advanced = $advanced; $this->stock = $stock; $this->info = $info; $this->description = $description; $this->customFields = $customFields; $this->setCategories($categories); $this->setPrices($prices); $this->setManufacturers($manufacturers); $this->setMedia($media); } public function getXml() { $xml = '<PRODUCT>'; $xml .= '<GENERAL>' . $this->general->getXml() . '</GENERAL>'; if($this->advanced) { $xml .= '<ADVANCED>' . $this->advanced->getXml() . '</ADVANCED>'; } if($this->stock) { $xml .= '<STOCK>' . $this->stock->getXml() . '</STOCK>'; } if($this->info) { $xml .= '<INFO>' . $this->info->getXml() . '</INFO>'; } if($this->description) { $xml .= '<DESCRIPTION>' . $this->description->getXml() . '</DESCRIPTION>'; } if($this->customFields) { $xml .= '<CUSTOM_FIELDS>' . $this->customFields->getXml() . '</CUSTOM_FIELDS>'; } if($this->categories && count($this->categories)) { $xml .= '<PRODUCT_CATEGORIES>'; foreach ($this->categories as $category) { $xml .= $category->getXml(); } $xml .= '</PRODUCT_CATEGORIES>'; } if($this->prices && count($this->prices)) { $xml .= '<PRICES>'; foreach ($this->prices as $price) { $xml .= $price->getXml(); } $xml .= '</PRICES>'; } if($this->manufacturers && count($this->manufacturers)) { $xml .= '<MANUFACTURERS>'; foreach ($this->manufacturers as $manufacturer) { $xml .= $manufacturer->getXml(); } $xml .= '</MANUFACTURERS>'; } if($this->media && count($this->media)) { $xml .= '<PRODUCT_MEDIA>'; foreach ($this->media as $media) { $xml .= $media->getXml(); } $xml .= '</PRODUCT_MEDIA>'; } $xml .= '</PRODUCT>'; return $xml; } /** * @return General */ public function getGeneral() { return $this->general; } /** * @param General $general * @return Product */ public function setGeneral($general) { $this->general = $general; return $this; } /** * @return Advanced */ public function getAdvanced() { return $this->advanced; } /** * @param Advanced $advanced * @return Product */ public function setAdvanced($advanced) { $this->advanced = $advanced; return $this; } /** * @return Stock */ public function getStock() { return $this->stock; } /** * @param Stock $stock * @return Product */ public function setStock($stock) { $this->stock = $stock; return $this; } /** * @return Info */ public function getInfo() { return $this->info; } /** * @param Info $info * @return Product */ public function setInfo($info) { $this->info = $info; return $this; } /** * @return Description */ public function getDescription() { return $this->description; } /** * @param Description $description * @return Product */ public function setDescription($description) { $this->description = $description; return $this; } /** * @return CustomFields */ public function getCustomFields() { return $this->customFields; } /** * @param CustomFields $customFields * @return Product */ public function setCustomFields($customFields) { $this->customFields = $customFields; return $this; } /** * Adds a category element to the product * * @param Category $category * @return Product */ public function addCategory(Category $category) { $this->categories[] = $category; return $this; } /** * @return Category[]|ArrayCollection */ public function getCategories() { return $this->categories; } /** * @param Category[]|ArrayCollection $categories * @return Product */ public function setCategories($categories) { if(empty($categories)) { $this->categories = new ArrayCollection(); } elseif(is_array($categories)) { $this->categories = new ArrayCollection($categories); } else { $this->categories = $categories; } return $this; } /** * Adds a price element to the product * * @param Price $price * @return Product */ public function addPrice(Price $price) { $this->prices[] = $price; return $this; } /** * @return Price[]|ArrayCollection */ public function getPrices() { return $this->prices; } /** * @param Price[]|ArrayCollection $prices * @return Product */ public function setPrices($prices) { if(empty($prices)) { $this->prices = new ArrayCollection(); } elseif(is_array($prices)) { $this->prices = new ArrayCollection($prices); } else { $this->prices = $prices; } return $this; } /** * Adds a manufacturer element to the product * * @param Manufacturer $manufacturer * @return Product */ public function addManufacturer(Manufacturer $manufacturer) { $this->manufacturers[] = $manufacturer; return $this; } /** * @return Manufacturer[]|ArrayCollection */ public function getManufacturers() { return $this->manufacturers; } /** * @param Manufacturer[]|ArrayCollection $manufacturers * @return Product */ public function setManufacturers($manufacturers) { if(empty($manufacturers)) { $this->manufacturers = new ArrayCollection(); } elseif(is_array($manufacturers)) { $this->manufacturers = new ArrayCollection($manufacturers); } else { $this->manufacturers = $manufacturers; } return $this; } /** * @return Media[]|ArrayCollection */ public function getMedia() { return $this->media; } /** * @param Media[]|ArrayCollection $media * @return Product */ public function setMedia($media) { if(empty($media)) { $this->media = new ArrayCollection(); } elseif(is_array($media)) { $this->media = new ArrayCollection($media); } else { $this->media = $media; } return $this; } }<file_sep><?php namespace Dandomain\Xml\Product; use Dandomain\Xml\Element; class Media extends Element { /** @var int */ protected $id; /** @var string */ protected $name; /** @var string */ protected $url; /** @var string */ protected $altText; /** @var int */ protected $sort; public function __construct($id = null, $name = null, $url = null, $altText = null, $sort = null) { $this->id = $id; $this->name = $name; $this->url = $url; $this->altText = $altText; $this->sort = $sort; } public function getXml() { $xml = ''; if($this->id) { $xml .= '<MEDIA_ID>' . $this->id . '</MEDIA_ID>'; } if($this->name) { $xml .= '<MEDIA_NAME>' . $this->name . '</MEDIA_NAME>'; } if($this->url) { $xml .= '<MEDIA_URL>' . $this->url . '</MEDIA_URL>'; } if($this->altText) { $xml .= '<MEDIA_ALT_TEXT>' . $this->altText . '</MEDIA_ALT_TEXT>'; } if($this->sort) { $xml .= '<MEDIA_SORT>' . $this->sort . '</MEDIA_SORT>'; } if($xml) { $xml = '<MEDIA>' . $xml . '</MEDIA>'; } return $xml; } /** * @return int */ public function getId() { return $this->id; } /** * @param int $id * @return Media */ public function setId($id) { $this->id = $id; return $this; } /** * @return string */ public function getName() { return $this->name; } /** * @param string $name * @return Media */ public function setName($name) { $this->name = $name; return $this; } /** * @return string */ public function getUrl() { return $this->url; } /** * @param string $url * @return Media */ public function setUrl($url) { $this->url = $url; return $this; } /** * @return string */ public function getAltText() { return $this->altText; } /** * @param string $altText * @return Media */ public function setAltText($altText) { $this->altText = $altText; return $this; } /** * @return int */ public function getSort() { return $this->sort; } /** * @param int $sort * @return Media */ public function setSort($sort) { $this->sort = $sort; return $this; } }<file_sep><?php namespace Dandomain\Import; use Dandomain\ImportExportClientTrait; use Dandomain\Xml\ElementInterface; use Doctrine\Common\Collections\ArrayCollection; abstract class Import { use ImportExportClientTrait; /** * @var string */ protected $xmlStart; /** * @var string */ protected $xmlEnd; /** * @var ElementInterface[]|ArrayCollection */ protected $elements; /** * The local path where the import file should be saved * * @var string */ protected $localPath; /** * The global url where the import file can be accessed by Dandomain * * @var string */ protected $globalUrl; /** * @var array */ protected $params = []; public function __construct($localPath, $globalUrl, $params = []) { $this->localPath = $localPath; $this->globalUrl = $globalUrl; $this->elements = new ArrayCollection(); $this->params = array_merge($this->params, $params); } /** * Returns the local path of the file * * @return string */ public function createImportFile() { @unlink($this->localPath); $fp = fopen($this->localPath, 'w'); fwrite($fp, $this->xmlStart); foreach ($this->elements as $element) { fwrite($fp, $element->getXml()); } fwrite($fp, $this->xmlEnd); fclose($fp); return $this->localPath; } /** * @return Result|bool */ public function import() { if(!count($this->elements)) { return false; } $this->createImportFile(); /** * @todo this depends on the guzzle http client, which it should not * @todo move the getBody()->getContents() to the client instead */ $importResult = new Result($this->getClient()->import($this->globalUrl, $this->params)->getBody()->getContents()); @unlink($this->localPath); return $importResult; } /** * @param ElementInterface $element * @return Import */ public function addElement(ElementInterface $element) { $this->elements[] = $element; return $this; } /** * @return ElementInterface[]|ArrayCollection */ public function getElements() { return $this->elements; } /** * @param ElementInterface[]|ArrayCollection $elements * @return Import */ public function setElements($elements) { $this->elements = $elements; return $this; } public function setUpdateOnly($val) { $this->params['updateonly'] = $val ? 1 : 0; } }<file_sep><?php namespace Dandomain\Xml\Product; use Dandomain\Xml\Element; class Manufacturer extends Element { protected $id; public function __construct($id) { $this->id = $id; } public function getXml() { return '<MANUFAC_ID>' . $this->id . '</MANUFAC_ID>'; } }<file_sep><?php namespace Dandomain\Xml; class Period extends Element { /** * @var string */ protected $id; /** * @var string */ protected $title; /** * @var \DateTimeInterface */ protected $startDate; /** * @var \DateTimeInterface */ protected $endDate; /** * @var bool */ protected $disabled = false; public function __construct($id, $title = '', $startDate = null, $endDate = null, $disabled = false) { $this->id = $id; $this->title = $title; $this->disabled = $disabled; if(is_string($startDate)) { $startDate = new \DateTime($startDate); } if(is_string($endDate)) { $endDate= new \DateTime($endDate); } $this->startDate = $startDate; $this->endDate = $endDate; } public function getXml() { $xml = '<PERIOD>'; $xml .= "<ID>{$this->id}</ID>"; if($this->title) { $xml .= '<TITLE>' . $this->title. '</TITLE>'; } if($this->startDate) { $xml .= '<START_DATE>' . $this->startDate->format('d-m-Y H:i') . '</START_DATE>'; } if($this->endDate) { $xml .= '<END_DATE>' . $this->endDate->format('d-m-Y H:i') . '</END_DATE>'; } if($this->disabled) { $xml .= '<DISABLED>' . ($this->disabled ? 'True' : 'False') . '</DISABLED>'; } $xml .= '</PERIOD>'; return $xml; } /** * @return string */ public function getId() { return $this->id; } /** * @param string $id * @return Period */ public function setId($id) { $this->id = $id; return $this; } /** * @return string */ public function getTitle() { return $this->title; } /** * @param string $title * @return Period */ public function setTitle($title) { $this->title = $title; return $this; } /** * @return \DateTimeInterface */ public function getStartDate() { return $this->startDate; } /** * @param \DateTimeInterface $startDate * @return Period */ public function setStartDate($startDate) { $this->startDate = $startDate; return $this; } /** * @return \DateTimeInterface */ public function getEndDate() { return $this->endDate; } /** * @param \DateTimeInterface $endDate * @return Period */ public function setEndDate($endDate) { $this->endDate = $endDate; return $this; } /** * @return boolean */ public function isDisabled() { return $this->disabled; } /** * @param boolean $disabled * @return Period */ public function setDisabled($disabled) { $this->disabled = $disabled; return $this; } } <file_sep><?php namespace Dandomain\Export; class Product extends Export { /** * @inheritdoc */ public function elements() { $this->validateParams(); return parent::elements(); } public function validateParams() { if(!isset($this->params['langid'])) { throw new \InvalidArgumentException('Language id is not set.'); } } /** * @param int $productCategoryId * @return $this */ public function setProductCategoryId($productCategoryId) { $this->params['prodcatid'] = $productCategoryId; return $this; } }<file_sep># Dandomain API PHP Wrapper This is a PHP wrapper for the [Dandomain](http://www.dandomain.dk) Import/Export functionality.<file_sep><?php namespace Dandomain\Import; class Price extends Import { protected $xmlStart = '<?xml version="1.0" encoding="utf-8"?><PRICE_EXPORT type="PRICES"><ELEMENTS>'; protected $xmlEnd = '</ELEMENTS></PRICE_EXPORT>'; }<file_sep><?php namespace Dandomain\Xml\Category; use Dandomain\Xml\Element; class ParentCategory extends Element { /** @var int */ protected $id; /** @var boolean */ protected $default; public function __construct($id, $default = false) { $this->id = $id; $this->default = $default; } public function getXml() { $priority = $this->default ? 1 : 0; $xml = '<PARENT_CAT_ID priority="' . $priority . '">' . $this->id . '</PARENT_CAT_ID>'; return $xml; } /** * @return int */ public function getId() { return $this->id; } /** * @param int $id * @return ParentCategory */ public function setId($id) { $this->id = $id; return $this; } /** * @return boolean */ public function isDefault() { return $this->default; } /** * @param boolean $default * @return ParentCategory */ public function setDefault($default) { $this->default = $default; return $this; } }<file_sep><?php namespace Dandomain\Xml\Product; use Dandomain\Xml\Element; class Stock extends Element { /** @var int */ protected $stockCount; /** @var int */ protected $stockLimit; /** @var string */ protected $delivery; /** @var string */ protected $deliveryNotInStock; /** @var string */ protected $locationNumber; public function __construct($stockCount = null, $stockLimit = null, $delivery = null, $deliveryNotInStock = null, $locationNumber = null) { $this->stockCount = $stockCount; $this->stockLimit = $stockLimit; $this->delivery = $delivery; $this->deliveryNotInStock = $deliveryNotInStock; $this->locationNumber = $locationNumber; } public function getXml() { $xml = ''; if ($this->stockCount) { $xml .= '<STOCK_COUNT>' . $this->stockCount . '</STOCK_COUNT>'; } if ($this->stockLimit) { $xml .= '<STOCK_LIMIT>' . $this->stockLimit . '</STOCK_LIMIT>'; } if ($this->delivery) { $xml .= '<PROD_DELIVERY>' . $this->delivery . '</PROD_DELIVERY>'; } if ($this->deliveryNotInStock) { $xml .= '<PROD_DELIVERY_NOT_IN_STOCK>' . $this->deliveryNotInStock . '</PROD_DELIVERY_NOT_IN_STOCK>'; } if ($this->locationNumber) { $xml .= '<PROD_LOCATION_NUMBER>' . $this->locationNumber . '</PROD_LOCATION_NUMBER>'; } return $xml; } /** * @return int */ public function getStockCount() { return $this->stockCount; } /** * @param int $stockCount * @return Stock */ public function setStockCount($stockCount) { $this->stockCount = $stockCount; return $this; } /** * @return int */ public function getStockLimit() { return $this->stockLimit; } /** * @param int $stockLimit * @return Stock */ public function setStockLimit($stockLimit) { $this->stockLimit = $stockLimit; return $this; } /** * @return string */ public function getDelivery() { return $this->delivery; } /** * @param string $delivery * @return Stock */ public function setDelivery($delivery) { $this->delivery = $delivery; return $this; } /** * @return string */ public function getDeliveryNotInStock() { return $this->deliveryNotInStock; } /** * @param string $deliveryNotInStock * @return Stock */ public function setDeliveryNotInStock($deliveryNotInStock) { $this->deliveryNotInStock = $deliveryNotInStock; return $this; } /** * @return string */ public function getLocationNumber() { return $this->locationNumber; } /** * @param string $locationNumber * @return Stock */ public function setLocationNumber($locationNumber) { $this->locationNumber = $locationNumber; return $this; } }<file_sep><?php namespace Dandomain\Xml; class ProductRelation extends Element { /** * @var string */ protected $productNumber; /** * @var string */ protected $relatedProductNumber; /** * @var int */ protected $sort; /** * @var int */ protected $type; public function __construct($productNumber, $relatedProductNumber, $sort = 0, $type = 1) { $this->productNumber = $productNumber; $this->relatedProductNumber = $relatedProductNumber; $this->sort = $sort; $this->type = $type; } /** * @return string */ public function getXml() { $xml = '<PRODUCT_RELATION>'; $xml .= '<PROD_NUM>'.$this->productNumber.'</PROD_NUM>'; $xml .= '<REL_PROD_NUM>'.$this->relatedProductNumber.'</REL_PROD_NUM>'; $xml .= '<REL_PROD_SORT>'.$this->sort.'</REL_PROD_SORT>'; $xml .= '<REL_PROD_TYPE>'.$this->type.'</REL_PROD_TYPE>'; $xml .= '</PRODUCT_RELATION>'; return $xml; } /** * @return string */ public function getProductNumber() { return $this->productNumber; } /** * @param string $productNumber * @return ProductRelation */ public function setProductNumber($productNumber) { $this->productNumber = $productNumber; return $this; } /** * @return string */ public function getRelatedProductNumber() { return $this->relatedProductNumber; } /** * @param string $relatedProductNumber * @return ProductRelation */ public function setRelatedProductNumber($relatedProductNumber) { $this->relatedProductNumber = $relatedProductNumber; return $this; } /** * @return int */ public function getSort() { return $this->sort; } /** * @param int $sort * @return ProductRelation */ public function setSort($sort) { $this->sort = $sort; return $this; } /** * @return int */ public function getType() { return $this->type; } /** * @param int $type * @return ProductRelation */ public function setType($type) { $this->type = $type; return $this; } }<file_sep><?php namespace Dandomain\Tests; use Dandomain\Export\Export; use Dandomain\ImportExportClient; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use GuzzleHttp\Psr7\Response; class ExportTest extends \PHPUnit_Framework_TestCase { protected function setUp() { ImportExportClient::setHost('http://www.example.com'); ImportExportClient::setUsername('username'); ImportExportClient::setPassword('<PASSWORD>'); } public function testElements() { $xmlResponse1 = <<<XML <?xml version="1.0" encoding="utf-8"?> <EXPORT_RESULT> <STATUS>1</STATUS> <TIME>0:1</TIME> <COUNT>21954</COUNT> <FILE_URL>http://www.example.com/images/ImportExport/export-PRODUCTS.xml</FILE_URL> </EXPORT_RESULT> XML; $xmlResponse2 = <<<XML <?xml version="1.0" encoding="utf-8"?> <PRODUCT_EXPORT type="PRODUCTS"> <ELEMENTS> <PRODUCT> <GENERAL> <PROD_NUM> 2043 ebbets grey-M</PROD_NUM> <LANGUAGE_ID>27</LANGUAGE_ID> </GENERAL> </PRODUCT> <PRODUCT> <GENERAL> <PROD_NUM> 40007</PROD_NUM> <LANGUAGE_ID>27</LANGUAGE_ID> </GENERAL> </PRODUCT> <PRODUCT> <GENERAL> <PROD_NUM> 40007-L</PROD_NUM> <LANGUAGE_ID>27</LANGUAGE_ID> </GENERAL> </PRODUCT> <PRODUCT> <GENERAL> <PROD_NUM> 40007-M</PROD_NUM> <LANGUAGE_ID>27</LANGUAGE_ID> </GENERAL> </PRODUCT> </ELEMENTS> </PRODUCT_EXPORT> XML; $mock = new MockHandler([ new Response(200, ['Content-Type' => 'application/xml; charset=utf-8'], $xmlResponse1), new Response(200, ['Content-Type' => 'application/xml; charset=utf-8'], $xmlResponse2), ]); $handler = HandlerStack::create($mock); $client = new ImportExportClient(['handler' => $handler]); $export = new Export(1); $export->setClient($client); foreach($export->elements() as $element) { print_r($element); } } }<file_sep><?php namespace Dandomain\Xml; class Price extends Element { protected $productNumber; protected $currency; protected $b2bId; protected $amount; protected $costPrice; protected $unitPrice; protected $profit; protected $specialOfferPrice; protected $periodId; protected $languageId; protected $productName; protected $retailPrice; public function __construct($productNumber = '', $currency = '', $b2bId = 0, $amount = 1, $unitPrice = 0, $costPrice = 0, $profit = 0, $specialOfferPrice = 0, $periodId = '', $languageId = 0, $productName = '', $retailPrice = 0) { $this->productNumber = $productNumber; $this->currency = $currency; $this->b2bId = $b2bId; $this->amount = $amount; $this->unitPrice = $unitPrice; $this->costPrice = $costPrice; $this->profit = $profit; $this->specialOfferPrice = $specialOfferPrice; $this->periodId = $periodId; $this->languageId = $languageId; $this->productName = $productName; $this->retailPrice = $retailPrice; } public function getXml() { $xml = '<PRICE>'; $xml .= "<PRICE_PROD_NUM>{$this->productNumber}</PRICE_PROD_NUM>"; $xml .= "<CURRENCY_CODE>{$this->currency}</CURRENCY_CODE>"; $xml .= '<PRICE_B2B_ID>' . (int)$this->b2bId . '</PRICE_B2B_ID>'; if($this->amount) { $xml .= '<AMOUNT>' . (int)$this->amount . '</AMOUNT>'; } if($this->costPrice) { $xml .= '<PROD_COST_PRICE>' . $this->formatMoney($this->costPrice) . '</PROD_COST_PRICE>'; } if($this->unitPrice) { $xml .= '<UNIT_PRICE>' . $this->formatMoney($this->unitPrice) . '</UNIT_PRICE>'; } if($this->profit) { $xml .= '<AVANCE>' . $this->formatMoney($this->profit) . '</AVANCE>'; } if($this->specialOfferPrice) { $xml .= '<SPECIAL_OFFER_PRICE>' . $this->formatMoney($this->specialOfferPrice) . '</SPECIAL_OFFER_PRICE>'; } if($this->periodId) { $xml .= "<PRICE_PERIOD_ID>{$this->periodId}</PRICE_PERIOD_ID>"; } if($this->languageId) { $xml .= '<LANGUAGE_ID>' . (int)$this->languageId . '</LANGUAGE_ID>'; } if($this->productName) { $xml .= "<PROD_NAME>{$this->productName}</PROD_NAME>"; } if($this->retailPrice) { $xml .= '<PROD_RETAIL_PRICE>' . $this->formatMoney($this->retailPrice) . '</PROD_RETAIL_PRICE>'; } $xml .= '</PRICE>'; return $xml; } /** * @return string */ public function getProductNumber() { return $this->productNumber; } /** * @param string $productNumber * @return Price */ public function setProductNumber($productNumber) { $this->productNumber = $productNumber; return $this; } /** * @return string */ public function getCurrency() { return $this->currency; } /** * @param string $currency * @return Price */ public function setCurrency($currency) { $this->currency = $currency; return $this; } /** * @return int */ public function getB2bId() { return $this->b2bId; } /** * @param int $b2bId * @return Price */ public function setB2bId($b2bId) { $this->b2bId = $b2bId; return $this; } /** * @return int */ public function getAmount() { return $this->amount; } /** * @param int $amount * @return Price */ public function setAmount($amount) { $this->amount = $amount; return $this; } /** * @return string */ public function getCostPrice() { return $this->costPrice; } /** * @param string $costPrice * @return Price */ public function setCostPrice($costPrice) { $this->costPrice = $costPrice; return $this; } /** * @return string */ public function getUnitPrice() { return $this->unitPrice; } /** * @param string $unitPrice * @return Price */ public function setUnitPrice($unitPrice) { $this->unitPrice = $unitPrice; return $this; } /** * @return string */ public function getProfit() { return $this->profit; } /** * @param string $profit * @return Price */ public function setProfit($profit) { $this->profit = $profit; return $this; } /** * @return string */ public function getSpecialOfferPrice() { return $this->specialOfferPrice; } /** * @param string $specialOfferPrice * @return Price */ public function setSpecialOfferPrice($specialOfferPrice) { $this->specialOfferPrice = $specialOfferPrice; return $this; } /** * @return string */ public function getLanguageId() { return $this->languageId; } /** * @param string $languageId * @return Price */ public function setLanguageId($languageId) { $this->languageId = $languageId; return $this; } /** * @return string */ public function getProductName() { return $this->productName; } /** * @param string $productName * @return Price */ public function setProductName($productName) { $this->productName = $productName; return $this; } /** * @return string */ public function getRetailPrice() { return $this->retailPrice; } /** * @param string $retailPrice * @return Price */ public function setRetailPrice($retailPrice) { $this->retailPrice = $retailPrice; return $this; } }<file_sep><?php namespace Dandomain\Xml\Product; use Dandomain\Xml\Element; class CustomFields extends Element { /** @var string */ protected $field1; /** @var string */ protected $field2; /** @var string */ protected $field3; /** @var string */ protected $field4; /** @var string */ protected $field5; /** @var string */ protected $field6; /** @var string */ protected $field7; /** @var string */ protected $field8; /** @var string */ protected $field9; /** @var string */ protected $field10; public function __construct($field1 = null, $field2 = null, $field3 = null, $field4 = null, $field5 = null, $field6 = null, $field7 = null, $field8 = null, $field9 = null, $field10 = null) { $this->field1 = $field1; $this->field2 = $field2; $this->field3 = $field3; $this->field4 = $field4; $this->field5 = $field5; $this->field6 = $field6; $this->field7 = $field7; $this->field8 = $field8; $this->field9 = $field9; $this->field10 = $field10; } public function getXml() { $xml = ''; if ($this->field1) { $xml .= '<FIELD_1>' . $this->field1 . '</FIELD_1>'; } if ($this->field2) { $xml .= '<FIELD_2>' . $this->field2 . '</FIELD_2>'; } if ($this->field3) { $xml .= '<FIELD_3>' . $this->field3 . '</FIELD_3>'; } if ($this->field4) { $xml .= '<FIELD_4>' . $this->field4 . '</FIELD_4>'; } if ($this->field5) { $xml .= '<FIELD_5>' . $this->field5 . '</FIELD_5>'; } if ($this->field6) { $xml .= '<FIELD_6>' . $this->field6 . '</FIELD_6>'; } if ($this->field7) { $xml .= '<FIELD_7>' . $this->field7 . '</FIELD_7>'; } if ($this->field8) { $xml .= '<FIELD_8>' . $this->field8 . '</FIELD_8>'; } if ($this->field9) { $xml .= '<FIELD_9>' . $this->field9 . '</FIELD_9>'; } if ($this->field10) { $xml .= '<FIELD_10>' . $this->field10 . '</FIELD_10>'; } return $xml; } /** * @return string */ public function getField1() { return $this->field1; } /** * @param string $field1 * @return CustomFields */ public function setField1($field1) { $this->field1 = $field1; return $this; } /** * @return string */ public function getField2() { return $this->field2; } /** * @param string $field2 * @return CustomFields */ public function setField2($field2) { $this->field2 = $field2; return $this; } /** * @return string */ public function getField3() { return $this->field3; } /** * @param string $field3 * @return CustomFields */ public function setField3($field3) { $this->field3 = $field3; return $this; } /** * @return string */ public function getField4() { return $this->field4; } /** * @param string $field4 * @return CustomFields */ public function setField4($field4) { $this->field4 = $field4; return $this; } /** * @return string */ public function getField5() { return $this->field5; } /** * @param string $field5 * @return CustomFields */ public function setField5($field5) { $this->field5 = $field5; return $this; } /** * @return string */ public function getField6() { return $this->field6; } /** * @param string $field6 * @return CustomFields */ public function setField6($field6) { $this->field6 = $field6; return $this; } /** * @return string */ public function getField7() { return $this->field7; } /** * @param string $field7 * @return CustomFields */ public function setField7($field7) { $this->field7 = $field7; return $this; } /** * @return string */ public function getField8() { return $this->field8; } /** * @param string $field8 * @return CustomFields */ public function setField8($field8) { $this->field8 = $field8; return $this; } /** * @return string */ public function getField9() { return $this->field9; } /** * @param string $field9 * @return CustomFields */ public function setField9($field9) { $this->field9 = $field9; return $this; } /** * @return string */ public function getField10() { return $this->field10; } /** * @param string $field10 * @return CustomFields */ public function setField10($field10) { $this->field10 = $field10; return $this; } }<file_sep><?php namespace Dandomain\Import; class Period extends Import { protected $xmlStart = '<?xml version="1.0" encoding="utf-8"?><PERIOD_EXPORT type="PERIODS"><ELEMENTS>'; protected $xmlEnd = '</ELEMENTS></PERIOD_EXPORT>'; }<file_sep><?php namespace Dandomain\Xml\Product; use Dandomain\Xml\Element; class General extends Element { /** @var string */ protected $productNumber; /** @var int */ protected $languageId; /** @var string */ protected $name; /** @var string */ protected $edbpriserNumber; /** @var string */ protected $weight; /** @var int */ protected $sort; /** @var int */ protected $minBuy; /** @var int */ protected $minBuyB2b; /** @var int */ protected $maxBuy; /** @var string */ protected $photoUrl; /** @var string */ protected $fileUrl; /** @var string */ protected $pdfUrl; /** @var string */ protected $pdfUrl2; /** @var string */ protected $pdfUrl3; /** @var string */ protected $retailPrice; /** @var string */ protected $costPrice; /** @var string */ protected $variantMaster; /** @var string */ protected $notes; /** @var string */ protected $pictureAltText; public function __construct($productNumber, $languageId, $name = null, $edbpriserNumber = null, $weight = null, $sort = null, $minBuy = null, $minBuyB2b = null, $maxBuy = null, $photoUrl = null, $fileUrl = null, $pdfUrl = null, $pdfUrl2 = null, $pdfUrl3 = null, $retailPrice = null, $costPrice = null, $variantMaster = null, $notes = null, $pictureAltText = null) { $this->productNumber = $productNumber; $this->languageId = $languageId; $this->name = $name; $this->edbpriserNumber = $edbpriserNumber; $this->weight = $weight; $this->sort = $sort; $this->minBuy = $minBuy; $this->minBuyB2b = $minBuyB2b; $this->maxBuy = $maxBuy; $this->photoUrl = $photoUrl; $this->fileUrl = $fileUrl; $this->pdfUrl = $pdfUrl; $this->pdfUrl2 = $pdfUrl2; $this->pdfUrl3 = $pdfUrl3; $this->retailPrice = $retailPrice; $this->costPrice = $costPrice; $this->variantMaster = $variantMaster; $this->notes = $notes; $this->pictureAltText = $pictureAltText; } public function getXml() { $xml = ''; if ($this->productNumber) { $xml .= '<PROD_NUM>' . $this->productNumber . '</PROD_NUM>'; } if ($this->languageId) { $xml .= '<LANGUAGE_ID>' . $this->languageId . '</LANGUAGE_ID>'; } if ($this->name) { $xml .= '<PROD_NAME>' . $this->name . '</PROD_NAME>'; } if ($this->edbpriserNumber) { $xml .= '<EDBPriser_NUM>' . $this->edbpriserNumber . '</EDBPriser_NUM>'; } if ($this->weight) { $xml .= '<PROD_WEIGHT>' . $this->weight . '</PROD_WEIGHT>'; } if ($this->sort) { $xml .= '<PROD_SORT>' . $this->sort . '</PROD_SORT>'; } if ($this->minBuy) { $xml .= '<PROD_MIN_BUY>' . $this->minBuy . '</PROD_MIN_BUY>'; } if ($this->minBuyB2b) { $xml .= '<PROD_MIN_BUY_B2B>' . $this->minBuyB2b . '</PROD_MIN_BUY_B2B>'; } if ($this->maxBuy) { $xml .= '<PROD_MAX_BUY>' . $this->maxBuy . '</PROD_MAX_BUY>'; } if ($this->photoUrl) { $xml .= '<PROD_PHOTO_URL>' . $this->photoUrl . '</PROD_PHOTO_URL>'; } if ($this->fileUrl) { $xml .= '<PROD_FILE_URL>' . $this->fileUrl . '</PROD_FILE_URL>'; } if ($this->pdfUrl) { $xml .= '<PROD_PDF_URL>' . $this->pdfUrl . '</PROD_PDF_URL>'; } if ($this->pdfUrl2) { $xml .= '<PROD_PDF_URL_2>' . $this->pdfUrl2 . '</PROD_PDF_URL_2>'; } if ($this->pdfUrl3) { $xml .= '<PROD_PDF_URL_3>' . $this->pdfUrl3 . '</PROD_PDF_URL_3>'; } if ($this->retailPrice) { $xml .= '<PROD_RETAIL_PRICE>' . $this->retailPrice . '</PROD_RETAIL_PRICE>'; } if ($this->costPrice) { $xml .= '<PROD_COST_PRICE>' . $this->costPrice . '</PROD_COST_PRICE>'; } if ($this->variantMaster) { $xml .= '<PROD_VAR_MASTER>' . $this->variantMaster . '</PROD_VAR_MASTER>'; } if ($this->notes) { $xml .= '<PROD_NOTES>' . $this->notes . '</PROD_NOTES>'; } if ($this->pictureAltText) { $xml .= '<PROD_PICTURE_ALT_TEXT>' . $this->pictureAltText . '</PROD_PICTURE_ALT_TEXT>'; } return $xml; } /** * @return string */ public function getProductNumber() { return $this->productNumber; } /** * @param string $productNumber * @return General */ public function setProductNumber($productNumber) { $this->productNumber = $productNumber; return $this; } /** * @return int */ public function getLanguageId() { return $this->languageId; } /** * @param int $languageId * @return General */ public function setLanguageId($languageId) { $this->languageId = $languageId; return $this; } /** * @return string */ public function getName() { return $this->name; } /** * @param string $name * @return General */ public function setName($name) { $this->name = $name; return $this; } /** * @return string */ public function getEdbpriserNumber() { return $this->edbpriserNumber; } /** * @param string $edbpriserNumber * @return General */ public function setEdbpriserNumber($edbpriserNumber) { $this->edbpriserNumber = $edbpriserNumber; return $this; } /** * @return string */ public function getWeight() { return $this->weight; } /** * @param string $weight * @return General */ public function setWeight($weight) { $this->weight = $weight; return $this; } /** * @return int */ public function getSort() { return $this->sort; } /** * @param int $sort * @return General */ public function setSort($sort) { $this->sort = $sort; return $this; } /** * @return int */ public function getMinBuy() { return $this->minBuy; } /** * @param int $minBuy * @return General */ public function setMinBuy($minBuy) { $this->minBuy = $minBuy; return $this; } /** * @return int */ public function getMinBuyB2b() { return $this->minBuyB2b; } /** * @param int $minBuyB2b * @return General */ public function setMinBuyB2b($minBuyB2b) { $this->minBuyB2b = $minBuyB2b; return $this; } /** * @return int */ public function getMaxBuy() { return $this->maxBuy; } /** * @param int $maxBuy * @return General */ public function setMaxBuy($maxBuy) { $this->maxBuy = $maxBuy; return $this; } /** * @return string */ public function getPhotoUrl() { return $this->photoUrl; } /** * @param string $photoUrl * @return General */ public function setPhotoUrl($photoUrl) { $this->photoUrl = $photoUrl; return $this; } /** * @return string */ public function getFileUrl() { return $this->fileUrl; } /** * @param string $fileUrl * @return General */ public function setFileUrl($fileUrl) { $this->fileUrl = $fileUrl; return $this; } /** * @return string */ public function getPdfUrl() { return $this->pdfUrl; } /** * @param string $pdfUrl * @return General */ public function setPdfUrl($pdfUrl) { $this->pdfUrl = $pdfUrl; return $this; } /** * @return string */ public function getPdfUrl2() { return $this->pdfUrl2; } /** * @param string $pdfUrl2 * @return General */ public function setPdfUrl2($pdfUrl2) { $this->pdfUrl2 = $pdfUrl2; return $this; } /** * @return string */ public function getPdfUrl3() { return $this->pdfUrl3; } /** * @param string $pdfUrl3 * @return General */ public function setPdfUrl3($pdfUrl3) { $this->pdfUrl3 = $pdfUrl3; return $this; } /** * @return string */ public function getRetailPrice() { return $this->retailPrice; } /** * @param string $retailPrice * @return General */ public function setRetailPrice($retailPrice) { $this->retailPrice = $retailPrice; return $this; } /** * @return string */ public function getCostPrice() { return $this->costPrice; } /** * @param string $costPrice * @return General */ public function setCostPrice($costPrice) { $this->costPrice = $costPrice; return $this; } /** * @return string */ public function getVariantMaster() { return $this->variantMaster; } /** * @param string $variantMaster * @return General */ public function setVariantMaster($variantMaster) { $this->variantMaster = $variantMaster; return $this; } /** * @return string */ public function getNotes() { return $this->notes; } /** * @param string $notes * @return General */ public function setNotes($notes) { $this->notes = $notes; return $this; } /** * @return string */ public function getPictureAltText() { return $this->pictureAltText; } /** * @param string $pictureAltText * @return General */ public function setPictureAltText($pictureAltText) { $this->pictureAltText = $pictureAltText; return $this; } }
30dee50f20538e2ac4cc1e50c150feab62918824
[ "Markdown", "PHP" ]
32
PHP
loevgaard/dandomain-import-export
d563b71350b3c757cc553a4565d85f8770bbcf82
701154a2bf4bd58adc6277c03541bf2972661660
refs/heads/master
<file_sep>#include "types.h" #include "user.h" int main(){ int forkVal = fork(); //child process int i; if (forkVal== 0){ for (i = 0; i < 50 ; i++){ printf(1, "+"); yield(); } } if (forkVal != 0){ for (i = 0; i < 50 ; i++){ printf(1, "-"); yield(); } wait(); } exit(); return 0; }
c743ab5846930a3a45d144b913fb4746d352e8ba
[ "C" ]
1
C
suttonhowell/xv6-public
cae5ad33c0ab01b261b47c4efeb981573369f115
51c79346c91f29e688756b668c6a22078f2413e7
refs/heads/master
<repo_name>Haradric/fillit<file_sep>/add_coords.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* add_coords.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mbraslav <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/12 14:45:59 by mbraslav #+# #+# */ /* Updated: 2017/01/12 14:46:03 by mbraslav ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "fillit.h" static void calc_coords(t_list *list) { int i; int n; int x0; int y0; i = -1; n = 0; list->x[0] = 0; list->y[0] = 0; while (list->figure[++i] != '\0') { if (list->figure[i] == '#') { if (++n == 1) { x0 = i % 4; y0 = i / 4; } else { list->x[n - 1] = (i % 4) - x0; list->y[n - 1] = (i / 4) - y0; } } } } void add_coords(t_list *list) { t_list *first; t_list *last; char current_letter; current_letter = 'A'; first = list; last = list; first->letter = current_letter; calc_coords(first); while (last->next != NULL) { last = last->next; current_letter += 1; last->letter = current_letter; calc_coords(last); } } <file_sep>/string_checker.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* string_checker.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mbraslav <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/12 14:53:20 by mbraslav #+# #+# */ /* Updated: 2017/01/12 14:53:23 by mbraslav ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "fillit.h" static void rules1and3(const char *str) { int i; int x; char *s; i = 0; s = (char *)str; while (s[i] != '\0') { if (i == 20 && ((s[i] == '\0') || (s[i] == '\n'))) { i = 0; s += 21; continue; } if (i == 20 && s[i] != '\n') exit_msg(); x = (i % 5) + 1; if ((x == 5) && s[i] != '\n') exit_msg(); if ((x != 5) && (s[i] != '#' && s[i] != '.')) exit_msg(); i++; } if (i != 20) exit_msg(); } static void rule2(const char *str) { int i; int blocks; char *s; i = 0; blocks = 0; s = (char *)str; while (s[i] != '\0') { if (i == 20) { if (blocks < 4) exit_msg(); i = 0; blocks = 0; s += 21; continue; } if (s[i] == '#') blocks++; if (blocks > 4) exit_msg(); i++; } } static void ihate25stringsrule(int i, char *s, int *connections) { if (s[i] == '#' && (i - 5 >= 0) && s[i - 5] == '#') *connections += 1; if (s[i] == '#' && (i + 5 <= 20) && s[i + 5] == '#') *connections += 1; if (s[i] == '#' && (i - 1 >= 0) && s[i - 1] == '#') *connections += 1; if (s[i] == '#' && (i + 1 >= 0) && s[i + 1] == '#') *connections += 1; } static void rule4(const char *str) { int i; int connections; char *s; i = 0; connections = 0; s = (char *)str; while (s[i] != '\0') { if (i == 20) { s += i + 1; i = 0; connections = 0; continue; } while (i < 19) ihate25stringsrule(i++, s, &connections); (connections == 6 || connections == 8) ? i++ : exit_msg(); } } int check_str(const char *str) { rules1and3(str); rule2(str); rule4(str); return (1); } <file_sep>/fillit.h /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fillit.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mbraslav <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/12 14:46:28 by mbraslav #+# #+# */ /* Updated: 2017/01/12 14:46:39 by mbraslav ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FILLIT_H # define FILLIT_H # include <stdio.h> typedef struct s_list { char figure[17]; int x[4]; int y[4]; char letter; struct s_list *next; } t_list; void ft_putchar(char c); void ft_putstr(char const *s); void *ft_memset(void *b, int c, size_t len); void ft_bzero(void *s, size_t n); void *ft_memcpy(void *dst, const void *src, size_t n); void *ft_memalloc(size_t size); char *ft_strnew(size_t size); int check_str(const char *str); t_list *str_to_lst(const char *str); void add_coords(t_list *list); int solve(t_list *list, char **map, int size); void print_and_free(char **map); char **pre_solve(t_list *list, int size); int place_figure(char **map, int size, int *cord, t_list *list); void exit_msg(void); void free_map(char **map); void free_lst(t_list *list); #endif <file_sep>/str_to_lst.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* str_to_lst.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mbraslav <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/12 14:53:04 by mbraslav #+# #+# */ /* Updated: 2017/01/12 14:53:07 by mbraslav ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "fillit.h" static void split_str(char *figure, const char *str) { char *s; int i; i = 0; s = (char *)str; while (i < 16) { if (*s != '\n') *(figure + i++) = *s; s++; } } static t_list *lstnew(const char *str) { t_list *list; list = (t_list *)malloc(sizeof(t_list)); if (list == NULL) exit_msg(); list->figure[16] = '\0'; split_str(list->figure, str); list->next = NULL; return (list); } t_list *str_to_lst(const char *str) { t_list *list; t_list *last; char *s; s = (char *)str; list = lstnew(s); last = list; while (*(s + 20) != '\0') { s += 21; last->next = lstnew(s); last = last->next; } add_coords(list); return (list); } <file_sep>/main.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mbraslav <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/12 14:48:01 by mbraslav #+# #+# */ /* Updated: 2017/01/12 14:48:05 by mbraslav ### ########.fr */ /* */ /* ************************************************************************** */ #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include "fillit.h" static size_t filelen(char *path) { size_t len; char buf; int fd; len = 0; fd = open(path, O_RDONLY); if (fd == -1) exit_msg(); while (read(fd, &buf, 1)) len++; close(fd); return (len); } static char *file_to_str(char *path) { int fd; char *str; size_t len; len = filelen(path); fd = open(path, O_RDONLY); if (fd == -1) exit_msg(); str = (char *)malloc(len + 1); if (str == NULL) exit_msg(); read(fd, str, len); *(str + len) = '\0'; close(fd); return (str); } int main(int argc, char **argv) { char *str; t_list *list; int size; size = 0; if (argc == 2) { str = file_to_str(argv[1]); check_str(str); list = str_to_lst(str); free(str); print_and_free(pre_solve(list, size)); free_lst(list); } else ft_putstr("usage: fillit file\n"); return (0); } <file_sep>/solve.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* solve.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mbraslav <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/12 14:51:53 by mbraslav #+# #+# */ /* Updated: 2017/01/12 14:52:32 by mbraslav ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" #include <stdlib.h> static int min_size(t_list *list) { int len; int size; t_list *listcpy; len = 0; size = 2; listcpy = list; while (listcpy != NULL) { listcpy = listcpy->next; len++; } while (size * size < len * 4) size++; return (size); } static char **map_init(int size) { char **map; int i; i = 0; map = (char **)malloc(sizeof(char *) * size + 1); while (i < size) { map[i] = ft_strnew(size); ft_memset(map[i], '.', size); i++; } map[i] = NULL; return (map); } static char **delete_figure(t_list *list, char **map, int size) { int i; int j; i = -1; while (++i < size) { j = -1; while (++j < size) { if (map[i][j] == list->letter) map[i][j] = '.'; } } return (map); } int solve(t_list *list, char **map, int size) { int i; int j; int cord[2]; t_list *new_list; i = -1; while (++i < size) { if (list == NULL) return (1); j = -1; while (++j < size) { cord[0] = j; cord[1] = i; if (place_figure(map, size, cord, list)) { new_list = list->next; if (solve(new_list, map, size)) return (1); map = delete_figure(list, map, size); } } } return (0); } char **pre_solve(t_list *list, int size) { char **map; size = min_size(list); map = map_init(size); while (!solve(list, map, size)) { size = size + 1; map = map_init(size); } return (map); } <file_sep>/place_figure.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* place_figure.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mbraslav <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/12 14:48:40 by mbraslav #+# #+# */ /* Updated: 2017/01/12 14:48:44 by mbraslav ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" static int check(char **map, int size, int *cord, t_list *list) { int i; int x; int y; int x0; int y0; i = 0; x0 = cord[0]; y0 = cord[1]; while (i < 4) { x = list->x[i] + x0; y = list->y[i] + y0; if (x < 0 || y < 0 || x >= size || y >= size) return (0); if (map[y][x] != '.') return (0); i++; } return (1); } static void place(char **map, int *cord, t_list *list) { int i; int x; int y; int x0; int y0; i = 0; x0 = cord[0]; y0 = cord[1]; while (i < 4) { x = list->x[i] + x0; y = list->y[i] + y0; map[y][x] = list->letter; i++; } } int place_figure(char **map, int size, int *cord, t_list *list) { if (check(map, size, cord, list)) { place(map, cord, list); return (1); } return (0); } <file_sep>/ft_functions2.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_functions2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mbraslav <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/12 14:47:49 by mbraslav #+# #+# */ /* Updated: 2017/01/12 14:47:52 by mbraslav ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "fillit.h" void *ft_memset(void *b, int c, size_t len) { unsigned char *str; str = (unsigned char *)b; while (len--) *str++ = (unsigned char)c; return (b); } void ft_bzero(void *s, size_t n) { ft_memset(s, '\0', n); } void *ft_memcpy(void *dst, const void *src, size_t n) { unsigned char *str1; unsigned char *str2; str1 = (unsigned char *)dst; str2 = (unsigned char *)src; while (n > 0) { *str1++ = *str2++; n--; } return (dst); } void *ft_memalloc(size_t size) { void *p; p = malloc(size); if (p == NULL) return (NULL); else { ft_bzero(p, size); return (p); } } char *ft_strnew(size_t size) { char *str; char *res; str = ft_memalloc(size + 1); if (str == NULL) return (NULL); res = str; *(str + size) = '\0'; while (*str) *str++ = '\0'; return (res); }
f53fbd270bf83500f003d4190a8c9cb366469edd
[ "C" ]
8
C
Haradric/fillit
24d47aa60d995d761d45faa8372bae28c9bc6254
eb0e08845aca2b81aeaeaaf99e36b2247ecbb82b
refs/heads/master
<file_sep>jquery-cloneable ================ Simple jquery plugin to clone any HTML element. Demo and documentation: http://victor-valencia.github.com/jquery-cloneable <file_sep>$(function(){ //Initialize plug-in $('#tableCloneable').cloneable(); //Initialize objects var carlos_slim_data = { full_name: '<NAME>', country: 'México', education: 'Bachelor of Arts / Science, Universidad Nacional Autonoma de Mexico', photo: 'images/carlos-slim-helu_42x42.jpg' } var bill_gates_data = { full_name: '<NAME>', country: 'United States', education: 'Drop Out, Harvard University', photo: 'images/bill-gates_42x42.jpg' } //Add clones with data $('#tableCloneable').cloneable('addClone', { data: carlos_slim_data }); $('#tableCloneable').cloneable('addClone', { data: bill_gates_data }) });<file_sep>//============================================================================== // // Git: https://github.com/victor-valencia/jquery-cloneable // // File: jquery-cloneable.js // // Version: 1.0 // // Autor: <NAME> - <EMAIL> // https://github.com/victor-valencia // // Date: Febrary 2013 // //============================================================================== ( function( $ ) { //========================================================================== // // Prototypes // //========================================================================== /** * Verifica si el valor se encuentra dentro del rango de los limites inferior * y superior. * @param {Number} lower Limite inferior. * @param {Number} top Limite superior. * @return {Boolean} Retorna verdadero si se cumple la condicion. */ Number.prototype.isBetween = function( lower, top ) { return ( top >= this && this >= lower ); } //========================================================================== // // JQuery Extensions // //========================================================================== /** * Obtiene un valor entero de un objeto, si el objeto no tiene valor * numerico, se toma como valor numerico el segundo parametro. * @param {Object} val Valor numerico. * @param {Object} def Valor default. * @return {Number} Retorna el valor numerico. */ $.getInteger = function( val, def ) { return $.isNumeric( val ) ? parseInt( val, 10 ) : ( $.isNumeric( def ) ? parseInt( def, 10 ) : 0 ); } /** * Inserta un nuevo elemento dentro del objeto seleccionado en el indice * especificado. * @param {Number} index Indice del nuevo elemento. * @param {jQuery} element Elemento a insertar. * @return {jQuery} Retorna el valor del objeto seleccionado. */ $.fn.insertAt = function( index, element ) { return this.each( function() { var lastIndex = $( this ).children().size(); if( index.isBetween( 0, lastIndex - 1 ) ) { $(this).children().eq( index ).before( element ); } else{ $.error( 'Index out of range. Index => ' + index + ', Length => ' + lastIndex ); } }); } //========================================================================== // // JQuery Cloneable Plug-in // //========================================================================== /** * Logica de inicializacion y llamadas a metodos internos del plug-in. * @param {String} method Nombre del metodo a llamar. */ $.fn.cloneable = function( method ) { if( $.fn.cloneable.methods[ method ] ) { return $.fn.cloneable.methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ) ); } else if( typeof method === 'object' || ! method ) { return $.fn.cloneable.methods.init.apply( this, arguments ); } else { $.error( 'The method "' + method + '" is not in the plug-in jquery.cloneable' ); } }; //========================================================================== // // JQuery Cloneable Methods // //========================================================================== $.fn.cloneable.methods = { /** * Inicializa el componente. * @param {Object} options Configuracion de las opciones y eventos de * inicializacion. */ init : function( options ) { return this.each( function() { var target = $( this ); //Default options object var defaults = { fadeEffect: true, events: { onCloneAdded: function( e ) { }, onCloneRemoved: function( e ) { } } }; // HTML5 options data parse whith "data-" in html attributes var settings = $.extend( { }, defaults, target.data() ); // Javascritp options data parse by "param" settings = $.extend( { }, settings, defaults, options ); settings.events = $.extend( { }, defaults.events, settings.events ); var root = null; var models = []; //Process the models and root container $.each( target.find('.model'), function( i, model ) { if( i == 0 ) { root = $( model ).parent(); } models.push( $( model ).clone() ); }); //Validate if( models.length ) { //Assign private variables target.removeData(); target.data( "options", settings ); root.empty(); target.data( '_root', root ); target.data( '_models', models ); target.data( '_elements', [] ); } else { $.error( 'There are no models in element' ); } //console.log(target.data()); }); }, /** * Realiza una copia del modelo. * @param {Object} options Configuracion de las opciones de la copia. */ addClone : function( options ) { return this.each( function() { var target = $( this ); //Default options object var defaults = { data: {}, index: -1, //Indicates the last position model: null } var settings = $.extend( { }, defaults, options ); var data = settings.data; var index = $.getInteger( settings.index, 0 ); var model = settings.model; var length = target.data( '_elements' ).length; //Validate index if( index.isBetween( -1, length ) ) { if( $.isArray( data ) ) { //If data is an Array $.each( data, function( i, obj ) { //Call recursive target.cloneable( 'addClone', { data: obj, index: index, model: model }); }); } else { //Data is an Object //Get model var node = target.cloneable( 'getModel', model ); if( node != null ) { var _options = target.data( 'options' ); if( _options.fadeEffect == true ) { node.hide(); } var root = target.data( '_root' ); if( index == -1 || index == length) { //Insert at the end $( root ).append( node ); } else { //Insert at the specified index $( root ).insertAt( index, node ); } if( _options.fadeEffect == true ) { node.fadeIn(); } target.data( '_elements' ).splice( node.index(), 0, node ); //Set data target.cloneable( 'setData', { index: node.index(), data: data }); //Dispatch event: onCloneAdded. _options.events.onCloneAdded.apply( target, [{ index: node.index(), node: node, data: data, length: target.data( '_elements' ).length }] ); } else { $.error( 'There are no models in element' ); } } } else { $.error( 'Index out of range. Index => ' + index + ', Length => ' + length ); } }); }, /** * Obtiene un modelo especifico, si no se especifica retorna el primero. * @param {String} name Nombre del modelo. * @return {jQuery} Retorna el modelo, si no tiene retorna null. */ getModel : function( name ) { var target = $(this); var models = target.data( '_models' ); var m = null; if( models.length ) { if( name == undefined ) { m = models[ 0 ].clone(); } else { $.each( models, function( i, model ) { if( $( model ).data( 'modelName' ) == name ) { m = models[ i ].clone(); } }); } } return m; }, /** * Obtiene los datos de un elemento clonado. * @param {Number} index Indice del elemento. * @return {Object} Retorna los datos del elemento. */ getData : function( index ) { var target = $(this); var elements = target.data( '_elements' ); var length = elements.length; var data = null; //Validate index if( index.isBetween( 0, length - 1 ) ) { data = elements[index].data( '_data' ); } else { $.error( 'Index out of range. Index => ' + index + ', Length => ' + length ); } return data; }, /** * Agrega los datos a un objeto. * @param {Object} options Configuracion de las opciones. */ setData : function( options ) { return this.each( function(){ var target = $(this); var defaults = { index: 0, data: {} } var settings = $.extend( { }, defaults, options ); var data = settings.data; var index = $.getInteger( settings.index, 0 ); var elements = target.data( '_elements' ); var length = elements.length; //Validate index if( index.isBetween( 0, length - 1 ) ) { var node = elements[ index ]; // Add new data node.data( '_data', data ); $.each( data, function( key, value ) { var element = $( node ).find( '[name*="' + key + '[]"]' ); if( element.length ) { switch( element[ 0 ].nodeName ) { case 'INPUT': element.attr( 'value', value ); break; case 'TEXTAREA': element.attr( 'value', value ); break; case 'SELECT': element.attr( 'value', value ); break; case 'IMG': element.attr( 'src', value ); break; default: element.attr( 'value', value ).html( value ); break; }; } }); } else { $.error( 'Index out of range. Index => ' + index + ', Length => ' + length ); } }); }, /** * Cambia el modelo de un elemento, especificando el indice. * @param {Object} options Indice del elemento. */ changeModel : function( options ) { return this.each( function() { var target = $( this ); var defaults = { data: {}, index: 0, model: null } var settings = $.extend( { }, defaults, options ); var data = settings.data; var index = $.getInteger( settings.index, 0 ); var model = settings.model; var elements = target.data( '_elements' ); var length = elements.length; if( index.isBetween( 0, length - 1 ) ) { var node = target.cloneable( 'getModel', model ); if( node != null ) { var element = elements[ index ]; element.replaceWith( node ); target.data( '_elements' )[ index ] = node; target.cloneable( 'setData', { index: index, data: data }); } else { $.error( 'There are no models in element' ); } } else { $.error( 'Index out of range. Index => ' + index + ', Length => ' + length ); } }); }, /** * Elimina un elemento clonado, especificando el indice. * @param {Number} index Indice del elemento. */ removeClone : function( index ) { return this.each( function() { var target = $(this); var elements = target.data( '_elements' ); var length = elements.length; if( index.isBetween( 0, length - 1 ) ) { var deleted = elements.splice( index, 1 ); var node = $( deleted[ 0 ] ); var _options = target.data( 'options' ); //Dispatch event: onCloneRemoved. _options.events.onCloneRemoved.apply( target, [{ index: index, node: node, length: elements.length }] ); //Delete element if( _options.fadeEffect == true ) { node.fadeOut( function() { node.remove(); }); } else { node.remove(); } target.data('_elements', elements); } else { $.error( 'Index out of range. Index => ' + index + ', Length => ' + length ); } }); }, /** * Elimina todos los elementos clonados. */ removeAllClone : function() { return this.each( function() { var target = $( this ); var length = target.data( '_elements' ).length; for( var i = length - 1; i >= 0 ; i-- ) { target.cloneable( 'removeClone', i ); } }); } } })(jQuery);<file_sep>$(function(){ //Initialize plug-in $('#tableCloneable').cloneable(); //Get JSON file $.getJSON('json/data.json', function(data) { //Clone and add data $('#tableCloneable').cloneable('addClone', {data : data}); }) //Add button event click for 'Delete' //NOTE: Use 'live' for attach all elements, now and in the future $('.buttonDelete').live('click', function(e){ e.preventDefault(); var index = $(this).closest('tr').index(); //Delete a specific clone $('#tableCloneable').cloneable('removeClone', index); }); //Add button event click for 'Delete All' $('#buttonDeleteAll').bind('click', function(e){ e.preventDefault(); //Delete all clones $('#tableCloneable').cloneable('removeAllClone'); }); });<file_sep>$(function(){ //Initialize plug-in $('#tableCloneable').cloneable(); //Get JSON file $.getJSON('json/data.json', function(data) { //Clone and add data $('#tableCloneable').cloneable('addClone', {data : data}); }) //Add button event click for 'Edit' //NOTE: Use 'live' for attach all elements, now and in the future $('.buttonEdit').live('click', function(e){ e.preventDefault(); //Get index var index = $(this).closest('tr').index(); //Get data var data = $('#tableCloneable').cloneable('getData', index); //Set values in components to edit $('#windowEdit').find('input[name="index"]').val(index) $('#windowEdit').find('input[name="full_name"]').val(data.full_name) $('#windowEdit').find('select[name="country"]').val(data.country) $('#windowEdit').find('textarea[name="education"]').val(data.education); //Show window $('#windowEdit').modal('show'); }); //Add button event click for 'Save' $('#buttonSave').live('click', function(e){ e.preventDefault(); //Hide window $('#windowEdit').modal('hide'); //Get data values and index var index = parseInt( $('#windowEdit').find('input[name="index"]').val() ); var data = { full_name : $('#windowEdit').find('input[name="full_name"]').val(), country : $('#windowEdit').find('select[name="country"]').val(), education : $('#windowEdit').find('textarea[name="education"]').val() } //Set new data values $('#tableCloneable').cloneable('setData', { index: index, data: data }); }); });<file_sep>$(function(){ //Initialize plug-in $('#tableCloneable').cloneable(); //Add 2 clones $('#tableCloneable').cloneable('addClone') .cloneable('addClone'); });
ae4a4d46ddeec531ec5f3ea5292833a80af5ccd2
[ "Markdown", "JavaScript" ]
6
Markdown
intruxxer/jquery-cloneable
c6b2ee661e3ec9dfbd50703b118054c6f68ffa3f
a56345a1fe800a92947fb67fbd462da1283863f1
refs/heads/master
<repo_name>JeroenDeDauw/helloplasmoid<file_sep>/helloplasma.h // Here we avoid loading the header multiple times #ifndef Tutorial1_HEADER #define Tutorial1_HEADER // We need the Plasma Applet headers #include <KIcon> #include <Plasma/Applet> #include <Plasma/Svg> class QSizeF; // Define our plasma Applet class HelloPlasmoid : public Plasma::Applet { Q_OBJECT public: // Basic Create/Destroy HelloPlasmoid(QObject *parent, const QVariantList &args); ~HelloPlasmoid(); // The paintInterface procedure paints the applet to screen void paintInterface(QPainter *p, const QStyleOptionGraphicsItem *option, const QRect& contentsRect); void init(); private: Plasma::Svg m_svg; KIcon m_icon; }; #endif
60dd4de2a70e2e043742cc465c59f380c0f65052
[ "C++" ]
1
C++
JeroenDeDauw/helloplasmoid
28d293d5707ed8181d6cfee27559f52428ed45ea
c39752827f26e8a32da411e9de72a788593530eb
refs/heads/master
<file_sep>import React from 'react'; import { View, Text, Image } from 'react-native'; import { styles } from '../../styles'; const Post = ({ post }) => { return ( <View style={styles.imageContainer}> <Image style={styles.image} resizeMode="cover" source={{ uri: post.uri }} /> <View style={styles.textContainer}> <Text style={styles.title}>{post.title}</Text> <View style={styles.likesContainer}> <Text style={styles.likes}>&hearts; {post.likes}</Text> </View> </View> </View> ); }; export { Post }; export default {}; <file_sep>import React from 'react'; import { View, TextInput, Button, ActivityIndicator, Text, } from 'react-native'; const Login = ({ onPress, emailValue, passwordValue, onChange, loggingIn, hasError, errorMessage }) => { return ( <View> <TextInput autoCapitalize="none" autoCorrect={false} autoFocus value={emailValue} onChangeText={e => onChange(e, 'email')} keyboardType="email-address" placeholder="<EMAIL>" /> <TextInput autoCapitalize="none" autoCorrect={false} secureTextEntry value={passwordValue} onChangeText={e => onChange(e, 'password')} placeholder="<PASSWORD>" /> <Button title="Login" onPress={onPress}/> {loggingIn && <ActivityIndicator size="large" />} {hasError && <Text>{errorMessage}</Text>} </View> ); }; export { Login }; export default {}; <file_sep>export * from './Post'; export * from './Login'; <file_sep># fakestagram Kickstart your React Native app with Firebase tutorial
3ed0dd910a9461efe1564a8da83b59225278edd0
[ "JavaScript", "Markdown" ]
4
JavaScript
roykroy10/fakestagram
362f31ea6e271543f252dae27cfff75e75b3b3a1
5183362c07ad2349afd4def1c098ed53cc657eb6
refs/heads/master
<repo_name>kimha99/Rasware<file_sep>/Robotathon17/Main.c #include <RASLib/inc/common.h> #include <RASLib/inc/gpio.h> #include <RASLib/inc/time.h> #include "Switch.h" #include <RASLib/inc/sonar.h> // Blink the LED to show we're on tBoolean blink_on = true; tMotor *left = InitializeServoMotor(PIN_B0, true); tMotor *right = InitializeServoMotor(PIN_B7, false); tSonar *DisLeft = InitializeSonar(<PIN>, <PIN>); tSonar *DisRight = InitializeSonar(<PIN>, <PIN>); void blink(void) { SetPin(PIN_F3, blink_on); blink_on = !blink_on; } // The 'main' function is the entry point of the program int main(void) { //These are arbitrary values to be tested and changed. float maxDist = 50; float minDist = 10; float kP = 3.14; float errorL = ADCRead(DisLeft) - maxDist; float errorR = ADCRead(DisRight) - maxDist; // Initialization code can go here CallEvery(blink, 0, 0.5); while (1) { // Runtime code can go here Printf("Hello World!\n"); //SetMotor(left, 1.0); //SetMotor(right, 1.0); //This is for testing, actual speeds should be calculated based on input from sensors. if(ADCRead(DisRight > 100)) { SetMotor(left, 1.0); SetMotor(right, 0.5); } else if(ADCRead(DisLeft > 100)) { SetMotor(right, 1.0); SetMotor(left, 0.5); } } }
3703ff8ee70f8d30958bf8f3f876ad4dea880105
[ "C" ]
1
C
kimha99/Rasware
4ab5d88a768c1f841abca4e2f488e01b6a8f0163
3290de3f05b2ea627d5a1b14aa36db30e26c553c
refs/heads/master
<repo_name>EduardoRicSan/PruebaUPAX<file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/data/EmployeeRepository.kt package com.corporation.pruebaupax.data import android.app.Application import android.os.AsyncTask import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.corporation.pruebaupax.framework.room.EmployeeDatabase import com.corporation.pruebaupax.domain.entity.Employee import com.corporation.pruebaupax.usecases.EmployeeDAO /** * EmployeeRepository execute the functions we use to create and list a employee */ class EmployeeRepository(application: Application) { private val employeeDAO: EmployeeDAO? = EmployeeDatabase.getInstance(application)?.cemployeeDao() /** * insert a new employee */ fun insert(employee: Employee) { if (employeeDAO != null) InsertAsyncTask( employeeDAO ).execute(employee) } /** * Get all employees in a list by a Asyntask */ fun getEmployees(): LiveData<List<Employee>> { return employeeDAO?.getOrderedAgenda() ?: MutableLiveData<List<Employee>>() } private class InsertAsyncTask(private val employeeDAO: EmployeeDAO) : AsyncTask<Employee, Void, Void>() { override fun doInBackground(vararg employees: Employee?): Void? { for (emp in employees ) { if (emp != null) employeeDAO.insert(emp) } return null } } } <file_sep>/PruebaUPAX2/settings.gradle rootProject.name='PruebaUPAX' include ':app' <file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/framework/retrofit/RetrofitClient.kt package com.corporation.pruebaupax import com.corporation.myapplication.RetrofitInterface import com.google.gson.GsonBuilder import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit /** * Singleton class of retrofit client */ class RetrofitClient { private val retrofitInterface: RetrofitInterface /** * */ val authApiService: RetrofitInterface get() = retrofitInterface companion object { // https://apisls.upaxdev.com/task/initial_load private const val BASE_URL = "https://apisls.upaxdev.com/" private lateinit var retrofit: Retrofit /** * Singleton Method * @return */ var instance: RetrofitClient? = null get() { if (field == null) { field = RetrofitClient() } return field } private set } init { val gson = GsonBuilder() .setLenient() //.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create() val okHttpClientBuilder = OkHttpClient.Builder() .readTimeout(3, TimeUnit.MINUTES) .writeTimeout(3, TimeUnit.MINUTES) .connectTimeout(3, TimeUnit.MINUTES) // okHttpClientBuilder.addInterceptor(new AuthInterceptor()); val client = okHttpClientBuilder.build() retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) //.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .addConverterFactory(GsonConverterFactory.create(gson)) .client(client) .build() retrofitInterface = retrofit.create<RetrofitInterface>( RetrofitInterface::class.java) } } <file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/framework/retrofit/RetrofitInterface.kt package com.corporation.myapplication import com.google.gson.JsonObject import retrofit2.Call import retrofit2.http.* /** * Retrofit interface to retrofit */ interface RetrofitInterface { //get data @Headers("Content-Type: application/json") @POST("task/initial_load") fun getData(@Body dataRequest: Map<String, @JvmSuppressWildcards Any>): Call<JsonObject> }<file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/presentation/activities/ButtonActivity.kt package com.corporation.pruebaupax.presentation.activities import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.view.ViewGroup import android.widget.Button import android.widget.LinearLayout import com.corporation.pruebaupax.R import com.corporation.pruebaupax.usecases.ThreadPresenter import kotlinx.android.synthetic.main.activity_button.* class ButtonActivity : AppCompatActivity(), ThreadPresenter { override val context = this override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_button) val button_dynamic = Button(this) button_dynamic.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) button_dynamic.text = "Dynamic Button" clButton.addView(button_dynamic) button_dynamic.setOnClickListener{ Handler().postDelayed({ toast("El tiempo ha concluido") }, 10000) } } } <file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/domain/model/DataRequest.kt package com.corporation.pruebaupax.domain.model /** * Data class for call enque of webservices */ data class DataRequest( var userId: String, var env: String, var os: String )<file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/usecases/EmployeeDAO.kt package com.corporation.pruebaupax.usecases import androidx.lifecycle.LiveData import androidx.room.* import com.corporation.pruebaupax.domain.entity.Employee /** * Employeeo contains all functions to do on the database */ @Dao interface EmployeeDAO { @Insert fun insert(employee: Employee) @Update fun update(vararg employee: Employee) @Delete fun delete(vararg employee: Employee) @Query("SELECT * FROM " + Employee.TABLE_NAME + " ORDER BY nombre") fun getOrderedAgenda(): LiveData<List<Employee>> }<file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/usecases/ThreadPresenter.kt package com.corporation.pruebaupax.usecases import android.content.Context import android.widget.Toast interface ThreadPresenter { //Interface to show a toast on activity who called this val context: Context fun toast(message: String) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } }<file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/domain/model/DataResponse.kt package com.corporation.pruebaupax.domain.model import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName /** * Data class for response of webservices */ data class DataResponse( @SerializedName("code") @Expose val code: String, @SerializedName("message") @Expose val message: String, @SerializedName("response") @Expose val response: Any, @SerializedName("success") @Expose val success: Boolean ) <file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/presentation/activities/PersistenceActivity.kt package com.corporation.pruebaupax.presentation.activities import android.app.Dialog import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Window import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.corporation.pruebaupax.R import com.corporation.pruebaupax.domain.entity.Employee import com.corporation.pruebaupax.presentation.activities.viewmodel.EmployeeViewModel import com.google.android.material.floatingactionbutton.FloatingActionButton import kotlinx.android.synthetic.main.activity_persistence.* class PersistenceActivity : AppCompatActivity() { private lateinit var employeeViewModel: EmployeeViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_persistence) employeeViewModel = run { ViewModelProviders.of(this).get(EmployeeViewModel::class.java) } val mFab = findViewById<FloatingActionButton>(R.id.fabAdd) mFab.setOnClickListener{showDialog()} addObserver() } //show a dialog to create new user private fun showDialog() { val dialog = Dialog(this) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.setCancelable(false) dialog.setContentView(R.layout.layout_new_employee) val btCancel = dialog.findViewById(R.id.btCancel) as Button val btSaveEmployee = dialog.findViewById(R.id.btSaveEmployee) as Button val nombreEt = dialog.findViewById(R.id.etNombre) as EditText val fecha_nacEt = dialog.findViewById(R.id.etFecha) as EditText val puestoEt = dialog.findViewById(R.id.etPuesto) as EditText btCancel.setOnClickListener{dialog.dismiss()} btSaveEmployee.setOnClickListener { if (nombreEt.text.toString().isEmpty() || fecha_nacEt.text.toString().isEmpty() || puestoEt.text.toString().isEmpty()){ Toast.makeText(this, "Faltan campos por llenar", Toast.LENGTH_SHORT).show() }else{ addEmployee(nombreEt.text.toString(), fecha_nacEt.text.toString(), puestoEt.text.toString()) dialog.dismiss() } } dialog.show() } //create new observer to list all current employees private fun addObserver() { val observer = Observer<List<Employee>> { employees -> if (employees != null) { var text = "" for (employee in employees) { text += employee.nombre + " " + employee.fecha_nac + " - " + employee.puesto + "\n" } tvEmployeesInfo.text = text } } employeeViewModel.employees.observe(this, observer) } private fun addEmployee( nombre: String, fecha_nac: String, puesto: String ) { if (!nombre.isEmpty() && !fecha_nac.isEmpty() ){ employeeViewModel.saveEmployee( Employee( nombre, fecha_nac, puesto ) ) } } } <file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/presentation/activities/WebServiceActivity.kt package com.corporation.pruebaupax.presentation.activities import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.corporation.myapplication.RetrofitInterface import com.corporation.pruebaupax.R import com.corporation.pruebaupax.RetrofitClient import com.google.gson.JsonObject import kotlinx.android.synthetic.main.activity_web_service.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response class WebServiceActivity : AppCompatActivity(), View.OnClickListener { lateinit var retrofitClient: RetrofitClient lateinit var retrofitInterface: RetrofitInterface override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_web_service) retrofitInit() btWebServ.setOnClickListener(this) } //init retrofit instance private fun retrofitInit() { retrofitClient = RetrofitClient.instance!! retrofitInterface = retrofitClient.authApiService } override fun onClick(p0: View?) { when(p0!!.id){ R.id.btWebServ -> queryData() } } //method to get url link and download zip private fun queryData() { val requestBody: MutableMap<String,@JvmSuppressWildcards Any> = HashMap() requestBody["userId"] = 89602 requestBody["env"] = "dev" requestBody["os"] = "android" val call: Call<JsonObject> = retrofitInterface.getData(requestBody) call.enqueue(object : Callback<JsonObject> { override fun onFailure(call: Call<JsonObject>, t: Throwable) { t.message } override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) { if (response.isSuccessful){ response }else{ response.errorBody() } } }) } } <file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/presentation/activities/MapsActivity.kt package com.corporation.pruebaupax.presentation.activities import android.location.Location import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import com.corporation.pruebaupax.R import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationCallback import com.google.android.gms.location.LocationRequest import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.Marker import com.google.android.gms.maps.model.MarkerOptions import kotlinx.android.synthetic.main.activity_maps.* class MapsActivity : AppCompatActivity(), View.OnClickListener, OnMapReadyCallback { private var mMap: GoogleMap? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_maps) supportActionBar!!.hide() btAddMarkers.setOnClickListener(this) // Obtain the SupportMapFragment and get notified when the map is ready to be used. val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) } override fun onMapReady(googleMap: GoogleMap?) { mMap = googleMap //These coordinates represent the latitude and longitude of the Googleplex. 21.17, Longitud: -100.933 val latitude = 21.17 val longitude = -100.933 val zoomLevel = 15f val homeLatLng = LatLng(latitude, longitude) mMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(homeLatLng, zoomLevel)) mMap!!.addMarker(MarkerOptions().position(homeLatLng)) } override fun onClick(p0: View?) { val id = p0!!.id when(id){ R.id.btAddMarkers -> { val lengthMarkers = etMarkers.text.toString().toInt() if (lengthMarkers == 0){ Toast.makeText(this, "Por favor, ingresa otra cantidad", Toast.LENGTH_SHORT).show() }else{ for (x in 0 until lengthMarkers) { setMarkers() } Toast.makeText(this, "Amplia el mapa para observar todos los markers", Toast.LENGTH_SHORT).show() } } } } //Set markers dependes of input number private fun setMarkers() { val latitude = (21.17.toInt()..30).random() val longitude = (-100.933.toInt()..-99.000.toInt()).random() val zoomLevel = 15f val homeLatLng = LatLng(latitude.toDouble(), longitude.toDouble()) mMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(homeLatLng, zoomLevel)) mMap!!.addMarker(MarkerOptions().position(homeLatLng)) } } <file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/presentation/activities/MainActivity.kt package com.corporation.pruebaupax.presentation.activities import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import com.corporation.pruebaupax.R import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), View.OnClickListener{ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setOnClicks() } /** * method to implement onClicks */ private fun setOnClicks() { btMaps.setOnClickListener(this) btWS.setOnClickListener(this) btButton.setOnClickListener(this) btPersistence.setOnClickListener(this) } override fun onClick(p0: View?) { when(p0!!.id){ R.id.btMaps -> startActivity(Intent(this@MainActivity, MapsActivity::class.java)) R.id.btWS -> startActivity(Intent(this@MainActivity, WebServiceActivity::class.java)) R.id.btButton -> startActivity(Intent(this@MainActivity, ButtonActivity::class.java)) R.id.btPersistence -> startActivity(Intent(this@MainActivity, PersistenceActivity::class.java)) } } } <file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/framework/room/EmployeeDatabase.kt package com.corporation.pruebaupax.framework.room import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.corporation.pruebaupax.domain.entity.Employee import com.corporation.pruebaupax.usecases.EmployeeDAO /** * Singleton to create unique database instance */ @Database(entities = [Employee::class], version = 1) abstract class EmployeeDatabase : RoomDatabase() { abstract fun cemployeeDao(): EmployeeDAO companion object { private const val DATABASE_NAME = "score_database" @Volatile private var INSTANCE: EmployeeDatabase? = null fun getInstance(context: Context): EmployeeDatabase? { INSTANCE ?: synchronized(this) { INSTANCE = Room.databaseBuilder( context.applicationContext, EmployeeDatabase::class.java, DATABASE_NAME ).build() } return INSTANCE } } } <file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/domain/entity/EmployeeEntity.kt package com.corporation.pruebaupax.domain.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import org.jetbrains.annotations.NotNull /** * Create a table with its attributes */ @Entity(tableName = Employee.TABLE_NAME) data class Employee( @ColumnInfo(name = "nombre") @NotNull val nombre: String, @ColumnInfo(name = "fecha_nac") @NotNull val fecha_nac: String, @ColumnInfo(name = "puesto")@NotNull val puesto: String ) { companion object { const val TABLE_NAME = "employee" } @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "employee_id") var employeeId: Int = 0 }<file_sep>/PruebaUPAX2/app/src/main/java/com/corporation/pruebaupax/presentation/viewmodel/EmployeeViewModel.kt package com.corporation.pruebaupax.presentation.activities.viewmodel import android.app.Application import androidx.lifecycle.AndroidViewModel import com.corporation.pruebaupax.domain.entity.Employee import com.corporation.pruebaupax.data.EmployeeRepository class EmployeeViewModel(application: Application) : AndroidViewModel(application) { //calls to get all employees and save it private val repository = EmployeeRepository(application) val employees = repository.getEmployees() fun saveEmployee(employee: Employee) { repository.insert(employee) } }
9596465b9cf356bb161b3e6e5cccaa25ec409202
[ "Kotlin", "Gradle" ]
16
Kotlin
EduardoRicSan/PruebaUPAX
d5df34c7ec887528eff32d9c810993e0f2cb2966
175e0dbf5b167062380bc81fc2babecbf21b8ad3
refs/heads/master
<file_sep>library(wfg) library(glmnet) np <- 16 p <- 128 n <- 80 ############################################### g <- network.simu(p.in = rep(0.5, 4), p.out = 0.01)$net V(g)$size <- 5 cl.vec <- rep("dodgerblue", 128) cl.vec[1:np] <- "red" # x11(); plot(g, vertex.label = "", vertex.color = cl.vec) ############################################### z <- rnorm(n) x <- matrix(rnorm(n*p), nrow = n, ncol = p) for (i in 1:np) { ### x[, i] <- z + rnorm(n, mean = 0, sd = 1) } y <- rowSums(x[,1:np])*3/sqrt(np) + rnorm(n, mean = 0, sd = 2) ## Obtain initial estimate ######################## alpha <- 1 # 1 for lasso a <- 0.9 cv.fit <- cv.glmnet(x, y, alpha = alpha) # x11(); plot(cv.fit) lbd <- cv.fit$lambda.min glm.fit <- glmnet(x, y, lambda = lbd, alpha = alpha) beta.1 <- glm.fit$beta[,1] Y <- abs(beta.1) names(Y) <- NULL ## Propagation ######################## A <- as.matrix(get.adjacency(g)) W <- A diag(W) <- 1 deg.vec <- colSums(W) n <- nrow(W) D <- matrix(0, nrow = n, ncol = n) D_sqr <- D diag(D_sqr) <- 1/sqrt(deg.vec) W_prime <- D_sqr %*% W %*% D_sqr F_old = Y F_store <- c(F_old) alph = .5 for (i in 1:1000){ F_new = alph*W_prime %*% F_old + (1-alph)*Y F_store = cbind(F_store, F_new) F_old <- F_new } hub_weights <- F_store[, i] V(g)$weight <- hub_weights c_scale <- colorRamp(c('white', 'red')) #Color scaling function V(g)$color = apply(c_scale(V(g)$weight), 1, function(x) rgb(x[1]/255,x[2]/255,x[3]/255) ) quartz() plot(g) Y = F_store[, i] quartz() plot(F_store[1,]) ## Estimates from adaptive lasso cv.fit.2 <- cv.glmnet(x, y, penalty.factor = 1/Y, alpha = alpha) lbd.2 <- cv.fit.2$lambda.min glm.fit.2 <- glmnet(x, y, lambda = lbd.2, penalty.factor = 1/Y, alpha = alpha) beta.2 <- glm.fit.2$beta[,1] ## Estimates from New method cv.fit.3 <- cv.glmnet(x, y, penalty.factor = 1/Ft, alpha = alpha) lbd.3 <- cv.fit.3$lambda.min glm.fit.3 <- glmnet(x, y, lambda = lbd.3, penalty.factor = 1/Ft, alpha = alpha) beta.3 <- glm.fit.3$beta[,1] s0 <- c(1:np) s1 <- which(beta.1 != 0) s2 <- which(beta.2 != 0) s3 <- which(beta.3 != 0) sen.1 <- length(intersect(s0, s1)) / length(s0) sen.2 <- length(intersect(s0, s2)) / length(s0) sen.3 <- length(intersect(s0, s3)) / length(s0) s0c <- setdiff(1:p, s0) s1c <- setdiff(1:p, s1) s2c <- setdiff(1:p, s2) s3c <- setdiff(1:p, s3) spe.1 <- length(intersect(s0c, s1c)) / length(s0c) spe.2 <- length(intersect(s0c, s2c)) / length(s0c) spe.3 <- length(intersect(s0c, s3c)) / length(s0c) beta.0 <- c(rep(5/sqrt(np), np), rep(0, 128-np)) result <- list() result$fs <- data.frame(fnr = 1 - c(sen.1, sen.2, sen.3), fpr = 1 - c(spe.1, spe.2, spe.3)) result$l2 <- c( mean((beta.1 - beta.0)^2), mean((beta.2 - beta.0)^2), mean((beta.3 - beta.0)^2) ) return(result) } <file_sep># Network_Propagation Optimizing prediction accuracy for the PRINCE algorithm which associates genes and protein complexes with diseases via Network Propagation using R.
f0e0fc01a0829aa349aebe364c31d29afb19b24e
[ "Markdown", "R" ]
2
R
Sparkoor/Network_Propagation
1cf81e0e421522e31e5254b24d2b012b2828744c
348a236b5f8645f98f71d8f28a206068ebc00078
refs/heads/master
<file_sep>// // iBeacon.swift // Pods // // Created by <NAME> on 6/12/2015. // // import Foundation struct Beacon { let uuid: String init(uuid: String) { self.uuid = uuid } }<file_sep>// // Geofence.swift // Pods // // Created by <NAME> on 6/12/2015. // // import Foundation struct Geofence { let uuid: String let latitude: Double let longitude: Double let radius: Double init(uuid: String, latitude: Double, longitude: Double, radius: Double) { self.uuid = uuid self.latitude = latitude self.longitude = longitude self.radius = radius } }
0675c1adcb492b794f2f7e655f479421279b049f
[ "Swift" ]
2
Swift
daansari/flarelight
856719df4830886d4b30e66aa91f8990090b4152
f5973836fc00a368b750c78f3d2c51e751ea03ea
refs/heads/master
<file_sep># rest-api-node-typescript<file_sep>import * as mongoose from 'mongoose'; interface IMongoDbOptions { useNewUrlParser: boolean; useCreateIndex: boolean; useUnifiedTopology: boolean; } export default class MongoDBConfig { private dbOptions: IMongoDbOptions = { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, }; private db = mongoose.connection; constructor() { (<any>mongoose).Promise = global.Promise; this.connectMongodb('mongodb://localhost:27017/CRMdb', this.dbOptions); } private connectMongodb(url: string, options: IMongoDbOptions) { mongoose.connect( url, options ); } public testDbConnection(): void { this.db .once('open', () => console.info({ message: 'Connected to the database' })); this.db .on('error', (error: any) => console.error({ message: 'MongoDB connection error:', error })); } }<file_sep>import ContactModel from '../models/crmModel'; import { Request, Response } from 'express'; import { Document, DocumentQuery } from 'mongoose'; export class ContactController { public addNewContact(req: Request, res: Response): Promise<Document> { let newContact = new ContactModel(req.body); return newContact .save((error: string, contact: Document): Response => { if (error) { return res.send(error); } return res.json(contact); }); } public getContacts(req: Request, res: Response): DocumentQuery<Document[], Document, {}> { return ContactModel .find({}, (error: string | any, contacts: Array<Document>): Response => { if (error) { return res.send(error); } return res.json(contacts); }); } public getContactWithID(req: Request, res: Response): DocumentQuery<Document | null, Document, {}> { return ContactModel .findById(req.params.contactId, (error: string | any, contact: Document | null) => { if (error) { return res.send(error); } return res.json(contact); }); } public updateContact(req: Request, res: Response): DocumentQuery<Document | null, Document, {}> { return ContactModel.findOneAndUpdate({ _id: req.params.contactId }, req.body, { new: true }, (error: string | any, contact: Document | null): Response => { if (error) { return res.send(error); } return res.json(contact); }); } public deleteContact(req: Request, res: Response) { return ContactModel .deleteOne({ _id: req.params.contactId }, (error: string | any) => { if (error) { return res.send(error); } return res.json({ message: 'Successfully deleted contact'}); }); } }
6d79d58f22970d573c7ece03f7ae8dbc411eda1a
[ "Markdown", "TypeScript" ]
3
Markdown
chykehyman/rest-api-node-typescript
1ed2d0a86fe159bcbd3faf52935ce9e06aad88d7
8808e2ad0639d1c0ed714b6655f60944b6e5dd86
refs/heads/master
<repo_name>sarawutymtz/restapi<file_sep>/application/controllers/Marker.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); header('Access-Control-Allow-Origin: *'); require_once('application/libraries/REST_Controller.php'); class Marker extends REST_Controller { public function marker_post() { $this->load->model('Marker_model'); $result = $this->Marker_model->getAllDetail($this->input->post('type')); if($result){ $this->response(['result' => true, 'data' => $result], 200); } else { $this->response(['result' => false], 404); } } } <file_sep>/readme.rst Rest Api for สำหรับการใช้งานสอน ระบบ Gis ขั้นตอนที่ 1 Download file ไปไว้ที่ htdocs MAMP Server ขั้นตอนที่ 2 ให้ไปที่ไฟล์ application/config/database.php Config server mysql ในเครื่อง ขั้นตอนที่ 3 จากนั้นทำการสร้างฐานข้อมูลและจะสามารถใช้งาน Rest Api ได้<file_sep>/application/models/Layerprovince_model.php <?php class Layerprovince_model extends CI_Model { function __construct() { $this->load->database(); } public function getpepoleprovince ($id){ $query = $this->db->query("SELECT *,(((male + female) / (SELECT sum(male + female) FROM pepolecount) * 100)) as evg FROM pepolecount WHERE id = ?",[$id]); return $query->result_array()[0]; } public function getpepole (){ $query = $this->db->query("SELECT id, name, (male + female) as summary, (((male + female) / (SELECT sum(male + female) FROM pepolecount) * 100)) as evg, ((male + female) / (SELECT max(male + female) FROM pepolecount) * 100) as percent, (SELECT max(male + female) FROM pepolecount) as maximum FROM pepolecount"); return $query->result_array(); } public function addlocation ($data){ $wherelocation = $this->db->query("SELECT id FROM location where id = ?",[$data['id']]); if($wherelocation->num_rows() == 0) { $insert = [ 'id' => $data['id'], 'name' => $data['name'], 'icon' => $data['icon'], 'place_id' => $data['place_id'], 'type' => $data['type'], 'address' => $data['icon'], 'lat' => $data['lat'], 'lng' => $data['lng'], 'url' => $data['url'] ]; return $this->db->insert('location', $insert); } return false; } } ?><file_sep>/application/models/Marker_model.php <?php class Marker_model extends CI_Model { function __construct() { $this->load->database(); } public function getAllDetail ($type=0){ $s_type=addslashes($type); $this->db->where("(type LIKE '%".$s_type."%')"); $query = $this->db->get('location'); return $query->result_array(); } } ?><file_sep>/application/controllers/Province.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); header('Access-Control-Allow-Origin: *'); require_once('application/libraries/REST_Controller.php'); class Province extends REST_Controller { public function layer_post() { $this->load->model('Layerprovince_model'); $result = $this->Layerprovince_model->getpepoleprovince($this->input->post('id')); if($result){ $this->response(['result' => true, 'data' => $result], 200); } else { $this->response(['result' => false], 404); } } public function layerheat_get() { $this->load->model('Layerprovince_model'); $result = $this->Layerprovince_model->getpepole(); if($result){ $this->response(['result' => true, 'data' => $result], 200); } else { $this->response(['result' => false], 404); } } public function addlocation_post(){ $this->load->model('Layerprovince_model'); $data = json_decode($this->input->post('address'), true); $result = false; foreach ($data as $key => $value) { $this->Layerprovince_model->addlocation($value); $result = true; } if($result){ $this->response(['result' => true, 'data' => $result], 200); } else { $this->response(['result' => false], 404); } } }
8772c64d73bc47e8375f2d05830713097f3fefe3
[ "reStructuredText", "PHP" ]
5
PHP
sarawutymtz/restapi
eabdcb982c817cdb184c7f0a1f9b0b90513f286a
560db5c070a6d0db90f383dcc2e815328c6363ef
refs/heads/master
<repo_name>raza-khan/N26<file_sep>/force-app/main/default/aura/ProductInfo/ProductInfoController.js ({ doInit : function(component, event, helper) { var action=component.get("c.getCaseInfo"); action.setParams({ caseId:component.get("v.recordId") }); action.setCallback(this, function (response) { var state = response.getState(); if (state === "SUCCESS") { var result= response.getReturnValue(); component.set("v.caseInfo", result); helper.getProductInfo(component, result.Contact.Product__c,result.Contact.Home_Country__c); //Passing the contact object } else if (state === "ERROR") { helper.showPageMessage(component, "Error processing your request.", "error"); } }); $A.enqueueAction(action); } })<file_sep>/force-app/main/default/aura/ProductInfo/ProductInfoHelper.js ({ getProductInfo : function(component, productId, country) { var action=component.get("c.getProductInfo"); action.setParams({ productId:productId, country:country }); action.setCallback(this, function (response) { var state = response.getState(); if (state === "SUCCESS") { var result= response.getReturnValue(); component.set("v.productInfo", result); component.set("v.showLoader", false); } else if (state === "ERROR") { helper.showPageMessage(component, "Error getting product info.", "error"); } }); $A.enqueueAction(action); }, showPageMessage: function(component, message, type){ var toastEvent = $A.get("e.force:showToast"); toastEvent.setParams({ message: message, type: type }); toastEvent.fire(); if(type == 'error'){ component.set('v.showLoader', false); } } })
7c54986d2b0306bed047b0355af5b527aee9926a
[ "JavaScript" ]
2
JavaScript
raza-khan/N26
9c55c0948eea6dc4cbf8247954365417dd368903
3c0a87208a6d0116ed755329dd4ec94096141db8
refs/heads/master
<file_sep>package practiceClasses; public class InsufficientFundsException { } <file_sep>package practiceClasses; import static org.junit.Assert.*; public class Test { Account account = new Account(1122, 20000, 4.5); @org.junit.Test public void test() { account.withdraw(2500); account.deposit(3000); System.out.println(account.getBalance()); System.out.println(account.getMonthlyInterestRate()); System.out.println(account.getDateCreated()); } @org.junit.Test(expected=InsufficientFundsException.class) public final void testWithdraw() throws InsufficientFundsException { } @org.junit.Test public final void testWithdraw() { account.withdraw(100000); assertTrue(account.getBalance() > 0); } }
d0d2765b688464e37b66004719d33deabba91110
[ "Java" ]
2
Java
horsetornado/PS-3
3b3f302c514a0c7b6051871145512de73cd703af
0fd6664131cbd25e03b215c24c8a375f4b5ed68c
refs/heads/master
<file_sep># Steps - rails new mack-child-jobboard - he did model and controller steps - rails g scaffold Job title description:text company url - routes: rails g scaffold Job title description:text company url - add simple form gem - haml gem - bootstrap sass gem - jquery rails gem - faker gem - rails generate simple_form:install --bootstrap ## adding categories - rails g model Category name - rails db:migrate - rails g migration add_category_id_to_jobs category_id:integer - rails db:migrate - update job.rb ``` belongs_to :category ``` - update category.rb ``` has_many :jobs ``` - create 4 categories in rails c: Full Time, Part Time, Freelance, Consulting - change jobs/form partial to haml and update code to include association ``` = simple_form_for(@job, html: { class: 'form-horizontal'}) do |f| = f.collection_select :category_id, Category.all, :id, :name, {prompt: "Choose a category" }, input_html: { class: "dropdown-toggle" } = f.input :title, label: "Job Title", input_html: { class: "form-control" } = f.input :description, label: "Job Description", input_html: { class: "form-control" } = f.input :company, label: "Your Company", input_html: { class: "form-control" } = f.input :url, label: "Link to Job", input_html: { class: "form-control" } %br/ = f.button :submit ``` - in jobs controller, update the params ``` def job_params params.require(:job).permit(:title, :description, :company, :url, :category_id) end ``` - create a new job and see if it works ## Filtering by category - update the layouts/app with the categories ``` !!! %html %head %title Ruby on Rails Jobs = stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true = javascript_include_tag 'application', 'data-turbolinks-track' => true = csrf_meta_tags %body %nav.navbar.navbar-default .container .navbar-brand Rails Jobs %ul.nav.navbar-nav %li= link_to "All Jobs", root_path - Category.all.each do |category| %li= link_to category.name, jobs_path(category: category.name) = link_to "New Job", new_job_path, class: "navbar-text navbar-right navbar-link" .container .col-md-6.col-md-offset-3 = yield ``` - update the index in jobs controller ``` def index if params[:category].blank? @jobs = Job.all.order("created_at DESC") else @category_id = Category.find_by(name: params[:category]).id @jobs = Job.where(category_id: @category_id).order("created_at DESC") end end ``` ## The end<file_sep>Category.destroy_all Job.destroy_all 8.times do |c| Category.create!( name: Faker::Company.industry ) end puts '8 categories created' 20.times do |j| Job.create!( title: Faker::Company.catch_phrase, description: Faker::Hipster.paragraph(4), company: Faker::Company.name, url: Faker::Internet.url, category_id: rand(1..8) ) end puts '20 jobs created'
5859bc9e1e2a6b8c9d8561b14286a15aefb7399a
[ "Markdown", "Ruby" ]
2
Markdown
buddylee939/mack-child-jobboard
2b49ae801ff7cc638d4d742a7ccc36bb0c6248c9
8d4a468a4cfc48240435f15b7ac31b05062986cf
refs/heads/master
<repo_name>Velocidex/go-ntfs<file_sep>/parser/helpers.go package parser import ( "fmt" "io" "time" ) func filetimeToUnixtime(ft uint64) uint64 { return (ft - 11644473600000*10000) * 100 } // A FileTime object is a timestamp in windows filetime format. type WinFileTime struct { time.Time } func (self *WinFileTime) GoString() string { return fmt.Sprintf("%v", self) } func (self *WinFileTime) DebugString() string { return fmt.Sprintf("%v", self) } func (self *NTFSProfile) WinFileTime(reader io.ReaderAt, offset int64) *WinFileTime { filetime := ParseUint64(reader, offset) return &WinFileTime{time.Unix(0, int64(filetimeToUnixtime(filetime))).UTC()} } <file_sep>/parser/caching.go // Manage caching of MFT Entry metadata. This is mainly used for path // traversal calculation. package parser import "sync" type FNSummary struct { Name string NameType string ParentEntryNumber uint64 ParentSequenceNumber uint16 } type MFTEntrySummary struct { Sequence uint16 Filenames []FNSummary } type MFTEntryCache struct { mu sync.Mutex ntfs *NTFSContext lru *LRU } func NewMFTEntryCache(ntfs *NTFSContext) *MFTEntryCache { lru, _ := NewLRU(10000, nil, "MFTEntryCache") return &MFTEntryCache{ ntfs: ntfs, lru: lru, } } func (self *MFTEntryCache) GetSummary(id uint64) (*MFTEntrySummary, error) { self.mu.Lock() defer self.mu.Unlock() res_any, pres := self.lru.Get(int(id)) if pres { res, ok := res_any.(*MFTEntrySummary) if ok { return res, nil } } mft_entry, err := self.ntfs.GetMFT(int64(id)) if err != nil { return nil, err } cache_record := &MFTEntrySummary{ Sequence: mft_entry.Sequence_value(), } for _, fn := range mft_entry.FileName(self.ntfs) { cache_record.Filenames = append(cache_record.Filenames, FNSummary{ Name: fn.Name(), NameType: fn.NameType().Name, ParentEntryNumber: fn.MftReference(), ParentSequenceNumber: fn.Seq_num(), }) } self.lru.Add(int(id), cache_record) return cache_record, nil } <file_sep>/Makefile all: go build -o ntfs bin/*.go windows: GOOS=windows GOARCH=amd64 \ go build -ldflags="-s -w" \ -o ntfs.exe ./bin/*.go generate: cd parser/ && binparsegen conversion.spec.yaml > ntfs_gen.go test: go test -v ./... <file_sep>/parser/runs.go package parser import ( "fmt" ) type RunInfo struct { Type string Level int FromOffset int64 ToOffset int64 Length int64 CompressedLength int64 IsSparse bool ClusterSize int64 Reader string } func (self RunInfo) String() string { prefix := "" for i := 0; i < self.Level; i++ { prefix += " " } properties := "" if self.IsSparse { properties += "Sparse " } if self.CompressedLength != 0 { properties += fmt.Sprintf("Compressed Length %v", self.CompressedLength) } return fmt.Sprintf("%s %d %v: FileOffset %v -> DiskOffset %v (Length %v, %v Cluster %v) Delegate %v", prefix, self.Level, self.Type, self.FromOffset, self.ToOffset, self.Length, properties, self.ClusterSize, self.Reader) } func DebugRawRuns(runs []*Run) { fmt.Printf("Runs ....\n") for idx, r := range runs { fmt.Printf("%d Disk Offset %d RelativeUrnOffset %d (Length %d)\n", idx, r.Offset, r.RelativeUrnOffset, r.Length) } } func DebugRuns(stream RangeReaderAt, level int) []*RunInfo { result := make([]*RunInfo, 0) switch t := stream.(type) { case *MappedReader: result = append(result, &RunInfo{ Type: "MappedReader", Level: level, FromOffset: t.FileOffset, ToOffset: t.TargetOffset, Length: t.Length, CompressedLength: t.CompressedLength, IsSparse: t.IsSparse, ClusterSize: t.ClusterSize, Reader: fmt.Sprintf("%T", t.Reader), }) reader_t, ok := t.Reader.(RangeReaderAt) if ok { result = append(result, DebugRuns(reader_t, level+1)...) } case *RangeReader: for _, r := range t.runs { result = append(result, DebugRuns(r, level)...) } } return result } <file_sep>/parser/easy.go // Implement some easy APIs. package parser import ( "bytes" "errors" "fmt" "io" "os" "sort" "strconv" "strings" "time" ) const ( // An invalid filename to flag a wildcard search. WILDCARD_STREAM_NAME = ":*:" WILDCARD_STREAM_ID = uint16(0xffff) ) var ( FILE_NOT_FOUND_ERROR = errors.New("File not found.") ) type FileInfo struct { MFTId string `json:"MFTId,omitempty"` SequenceNumber uint16 `json:"SequenceNumber,omitempty"` Mtime time.Time `json:"Mtime,omitempty"` Atime time.Time `json:"Atime,omitempty"` Ctime time.Time `json:"Ctime,omitempty"` Btime time.Time `json:"Btime,omitempty"` // Birth time. FNBtime time.Time `json:"FNBtime,omitempty"` FNMtime time.Time `json:"FNBtime,omitempty"` Name string `json:"Name,omitempty"` NameType string `json:"NameType,omitempty"` ExtraNames []string `json:"ExtraNames,omitempty"` IsDir bool `json:"IsDir,omitempty"` Size int64 AllocatedSize int64 // Is it in I30 slack? IsSlack bool `json:"IsSlack,omitempty"` SlackOffset int64 `json:"SlackOffset,omitempty"` } func GetNTFSContext(image io.ReaderAt, offset int64) (*NTFSContext, error) { ntfs := newNTFSContext(image, "GetNTFSContext") // NTFS Parsing starts with the boot record. ntfs.Boot = &NTFS_BOOT_SECTOR{Reader: image, Profile: ntfs.Profile, Offset: offset} err := ntfs.Boot.IsValid() if err != nil { return nil, err } ntfs.ClusterSize = ntfs.Boot.ClusterSize() mft_reader, err := BootstrapMFT(ntfs) if err != nil { return nil, err } ntfs.MFTReader = mft_reader return ntfs, nil } func ParseMFTId(mft_id string) (mft_idx int64, attr int64, id int64, stream_name string, err error) { stream_name = WILDCARD_STREAM_NAME // Support the ADS name being included in the inode parts := strings.SplitN(mft_id, ":", 2) if len(parts) > 1 { stream_name = parts[1] } components := []int64{} components_str := strings.Split(parts[0], "-") for _, component_str := range components_str { x, err := strconv.Atoi(component_str) if err != nil { return 0, 0, 0, "", errors.New("Incorrect format for MFTId: e.g. 5-144-1") } components = append(components, int64(x)) } switch len(components) { case 1: // 0xffff is the wildcard stream id - means pick the first one. return components[0], ATTR_TYPE_DATA, 0xffff, stream_name, nil case 2: return components[0], components[1], 0xffff, stream_name, nil case 3: return components[0], components[1], components[2], stream_name, nil default: return 0, 0, 0, "", errors.New("Incorrect format for MFTId: e.g. 5-144-1") } } func GetDataForPath(ntfs *NTFSContext, path string) (RangeReaderAt, error) { // Check for ADS in the path. stream_name := WILDCARD_STREAM_NAME parts := strings.SplitN(path, ":", 2) if len(parts) > 1 { stream_name = parts[1] } root, err := ntfs.GetMFT(5) if err != nil { return nil, err } mft_entry, err := root.Open(ntfs, parts[0]) if err != nil { return nil, err } return OpenStream(ntfs, mft_entry, ATTR_TYPE_DATA, WILDCARD_STREAM_ID, stream_name) } func RangeSize(rng RangeReaderAt) int64 { runs := rng.Ranges() if len(runs) == 0 { return 0 } last_run := runs[len(runs)-1] return last_run.Offset + last_run.Length } func Stat(ntfs *NTFSContext, node_mft *MFT_ENTRY) []*FileInfo { var si *STANDARD_INFORMATION var other_file_names []*FILE_NAME var data_attributes []*NTFS_ATTRIBUTE var win32_name *FILE_NAME var index_attribute *NTFS_ATTRIBUTE var fn_birth_time, fn_mtime time.Time mft_id := node_mft.Record_number() is_dir := node_mft.Flags().IsSet("DIRECTORY") // Walk all the attributes collecting the imporant things. for _, attr := range node_mft.EnumerateAttributes(ntfs) { switch attr.Type().Value { case ATTR_TYPE_STANDARD_INFORMATION: si = ntfs.Profile.STANDARD_INFORMATION(attr.Data(ntfs), 0) case ATTR_TYPE_FILE_NAME: // Separate the filenames into LFN and other file names. file_name := ntfs.Profile.FILE_NAME(attr.Data(ntfs), 0) // The birth of an MFT is determined by the // $FILE_NAME streams File_modified attribute // since it can not modified using normal // APIs. fn_birth_time = file_name.Created().Time fn_mtime = file_name.Created().Time switch file_name.NameType().Name { case "POSIX", "Win32", "DOS+Win32": win32_name = file_name default: other_file_names = append( other_file_names, file_name) } case ATTR_TYPE_DATA: // Only show the first VCN run of // non-resident $DATA attributes. if !attr.IsResident() && attr.Runlist_vcn_start() != 0 { continue } data_attributes = append(data_attributes, attr) case ATTR_TYPE_INDEX_ROOT, ATTR_TYPE_INDEX_ALLOCATION: index_attribute = attr } } // We need the si for the timestamps. if si == nil || win32_name == nil { return nil } // Now generate multiple file info for streams we want to be // distinct. result := []*FileInfo{} add_extra_names := func(info *FileInfo, ads string) { for _, name := range other_file_names { extra_name := name.Name() info.ExtraNames = append(info.ExtraNames, extra_name+ads) if !strings.Contains(extra_name, "~") { // Make a copy info_copy := *info info_copy.Name = extra_name + ads info_copy.ExtraNames = []string{win32_name.Name() + ads} result = append(result, &info_copy) } } } if index_attribute != nil { inode := fmt.Sprintf( "%d-%d-%d", mft_id, index_attribute.Type().Value, index_attribute.Attribute_id()) info := &FileInfo{ MFTId: inode, SequenceNumber: node_mft.Sequence_value(), Mtime: si.File_altered_time().Time, Atime: si.File_accessed_time().Time, Ctime: si.Mft_altered_time().Time, Btime: si.Create_time().Time, FNBtime: fn_birth_time, FNMtime: fn_mtime, Name: win32_name.Name(), NameType: win32_name.NameType().Name, IsDir: is_dir, } add_extra_names(info, "") result = append(result, info) } inode_formatter := InodeFormatter{} for _, attr := range data_attributes { ads := "" name := attr.Name() switch name { case "$I30", "": ads = "" default: ads = ":" + name } attr_id := attr.Attribute_id() attr_type_id := attr.Type().Value info := &FileInfo{ MFTId: inode_formatter.Inode( mft_id, attr_type_id, attr_id, name), SequenceNumber: node_mft.Sequence_value(), Mtime: si.File_altered_time().Time, Atime: si.File_accessed_time().Time, Ctime: si.Mft_altered_time().Time, Btime: si.Create_time().Time, FNBtime: fn_birth_time, FNMtime: fn_mtime, Name: win32_name.Name() + ads, NameType: win32_name.NameType().Name, IsDir: is_dir, Size: attr.DataSize(), } add_extra_names(info, ads) // Since ADS are actually data streams they can not be // directories themselves. The underlying file info will still // be a directory. if ads != "" { info.IsDir = false } result = append(result, info) } return result } func ListDir(ntfs *NTFSContext, root *MFT_ENTRY) []*FileInfo { // The index itself stores pointers to the FILE_NAME entry for // each MFT. Therefore there are usually 2 references to the // same MFT entry. We de-duplicate these references because we // list each MFT entirely separately. seen := make(map[int64]bool) result := []*FileInfo{} for _, node := range root.Dir(ntfs) { node_mft_id := int64(node.MftReference()) _, pres := seen[node_mft_id] if pres { continue } seen[node_mft_id] = true node_mft, err := ntfs.GetMFT(node_mft_id) if err != nil { continue } result = append(result, Stat(ntfs, node_mft)...) } return result } type attrInfo struct { attr_type uint64 attr_id uint16 attr_name string resident bool vcn_start uint64 vcn_end uint64 attr *NTFS_ATTRIBUTE } func selectAttribute(attributes []*attrInfo, attr_type uint64, required_attr_id uint16, required_data_attr_name string) (*attrInfo, error) { // Search for stream that matches the type. First search for non // ADS stream, and if not found then search again for any stream. if required_data_attr_name == WILDCARD_STREAM_NAME && required_attr_id == WILDCARD_STREAM_ID { for _, attr := range attributes { if attr.attr_type == attr_type && attr.attr_name == "" { if attr.resident || attr.vcn_start == 0 { return attr, nil } } } // Now search for the first attributed name. for _, attr := range attributes { if attr.attr_type == attr_type { if attr.resident || attr.vcn_start == 0 { return attr, nil } } } return nil, FILE_NOT_FOUND_ERROR } // Search for any stream with the given name if required_attr_id == WILDCARD_STREAM_ID { for _, attr := range attributes { if attr.attr_type == attr_type && attr.attr_name == required_data_attr_name { if attr.resident || attr.vcn_start == 0 { return attr, nil } } } return nil, FILE_NOT_FOUND_ERROR } // Search for a specific attr_id. if required_attr_id != WILDCARD_STREAM_ID { for _, attr := range attributes { if attr.attr_type == attr_type && attr.attr_id == required_attr_id { if required_data_attr_name != WILDCARD_STREAM_NAME && required_data_attr_name != attr.attr_name { continue } if attr.resident || attr.vcn_start == 0 { return attr, nil } } } } return nil, FILE_NOT_FOUND_ERROR } // Get all VCNs having the (same type and ID for default $DATA stream) // OR ($DATA with specific name) func GetAllVCNs(ntfs *NTFSContext, mft_entry *MFT_ENTRY, attr_type uint64, required_attr_id uint16, required_data_attr_name string) []*NTFS_ATTRIBUTE { // First extract all attribute info so we can decide who to choose. attributes := []*attrInfo{} for _, attr := range mft_entry.EnumerateAttributes(ntfs) { attributes = append(attributes, &attrInfo{ attr_type: attr.Type().Value, attr_id: attr.Attribute_id(), attr_name: attr.Name(), resident: attr.IsResident(), vcn_start: attr.Runlist_vcn_start(), vcn_end: attr.Runlist_vcn_end(), attr: attr, }) } // Depending on the required_data_attr_name and required_attr_id // specified we select the attribute we need. selected_attribute, err := selectAttribute(attributes, attr_type, required_attr_id, required_data_attr_name) if err != nil { return nil } // Now collect all attributes with the exact set of type, id and // name. These all form part of the same VCN set. result := []*NTFS_ATTRIBUTE{selected_attribute.attr} // Resident attributes do not have VCNs if selected_attribute.resident { return result } for { selected_attribute, err = findNextVCN(attributes, selected_attribute) // Protect ourselves from cycles. if err != nil || len(result) > 20 { break } result = append(result, selected_attribute.attr) } return result } func findNextVCN(attributes []*attrInfo, selected_attribute *attrInfo) (*attrInfo, error) { // Make sure the vcns make sense if selected_attribute.vcn_end <= selected_attribute.vcn_start { return nil, FILE_NOT_FOUND_ERROR } for _, attr := range attributes { if attr.attr_type == attr.attr_type && attr.vcn_start == selected_attribute.vcn_end+1 && attr.attr_name == selected_attribute.attr_name { return attr, nil } } return nil, FILE_NOT_FOUND_ERROR } // Open the full stream. Note - In NTFS a stream can be composed of // multiple VCN attributes: All VCN substreams have the same attribute // type and id but different start and end VCNs. This function finds // all related attributes and wraps them in a RangeReader to appear as // a single stream. This function is what you need when you want to // read the full file. func OpenStream(ntfs *NTFSContext, mft_entry *MFT_ENTRY, attr_type uint64, attr_id uint16, attr_name string) (RangeReaderAt, error) { result := &RangeReader{} // Gather all the VCNs together vcns := GetAllVCNs(ntfs, mft_entry, attr_type, attr_id, attr_name) if len(vcns) == 0 { return nil, os.ErrNotExist } // Return a resident reader immediately. attr := vcns[0] if attr.Resident().Name == "RESIDENT" { buf := make([]byte, CapUint32(attr.Content_size(), MAX_MFT_ENTRY_SIZE)) n, _ := attr.Reader.ReadAt(buf, attr.Offset+int64(attr.Content_offset())) buf = buf[:n] return &MappedReader{ FileOffset: 0, Length: int64(n), ClusterSize: 1, Reader: bytes.NewReader(buf), }, nil } result.runs = joinAllVCNs(ntfs, vcns) return result, nil } func joinAllVCNs(ntfs *NTFSContext, vcns []*NTFS_ATTRIBUTE) []*MappedReader { actual_size := int64(0) initialized_size := int64(0) compression_unit_size := int64(0) runs := []*Run{} // Sort the VCNs in order so they can be joined. sort.Slice(vcns, func(i, j int) bool { return vcns[i].Runlist_vcn_start() < vcns[j].Runlist_vcn_start() }) for _, vcn := range vcns { // Actual_size is only set on the first stream. if actual_size == 0 { actual_size = int64(vcn.Actual_size()) } // Initialized_size is only set on the first stream if initialized_size == 0 { initialized_size = int64(vcn.Initialized_size()) } // Compression_unit_size is only set on the first stream. if compression_unit_size == 0 { compression_unit_size = int64( 1 << uint64(vcn.Compression_unit_size())) } // Join all the runlists from all VCNs into the same runlist - // compressed files often have their runs broken up into // different vcns so it is just easier to combine them before // parsing. vcn_runlist := vcn.RunList() runs = append(runs, vcn_runlist...) } var reader *MappedReader flags := vcns[0].Flags() if IsCompressed(flags) { // YK - all Sparse files are not compressed! reader = &MappedReader{ ClusterSize: 1, FileOffset: 0, Length: initialized_size, Reader: NewCompressedRangeReader(runs, ntfs.ClusterSize, ntfs.DiskReader, compression_unit_size), } } else { reader = &MappedReader{ ClusterSize: 1, FileOffset: 0, Length: initialized_size, Reader: NewUncompressedRangeReader(runs, ntfs.ClusterSize, ntfs.DiskReader, IsSparse(flags)), } } // If the attribute is not fully initialized, trim the mapping // to the initialized range and add a pad to the end to make // up the full length. For example, the attribute might // contain 32 clusters, but only 16 clusters are initialized // and 16 clusters are padding. if actual_size > initialized_size { return []*MappedReader{ reader, // Pad starts immediately after the last range &MappedReader{ ClusterSize: 1, FileOffset: initialized_size, Length: actual_size - initialized_size, IsSparse: true, Reader: &NullReader{}, }} } return []*MappedReader{reader} } <file_sep>/tests/usn_test.go package ntfs import ( "fmt" "io" "os" "testing" "github.com/alecthomas/assert" "www.velocidex.com/golang/go-ntfs/parser" ) type OffsetReader struct { offset int64 fd io.ReaderAt } func (self OffsetReader) ReadAt(buf []byte, offset int64) (int, error) { return self.fd.ReadAt(buf, offset-self.offset) } func TestUSN(t *testing.T) { fd, err := os.Open("usn/sample.bin") assert.NoError(t, err) reader := &OffsetReader{fd: fd, offset: 0x12a16c30} ntfs := &parser.NTFSContext{ DiskReader: reader, Profile: parser.NewNTFSProfile(), } record := parser.NewUSN_RECORD(ntfs, reader, 0x12a16c30) for record != nil { fmt.Printf(record.DebugString()) record = record.Next(10000) } } <file_sep>/bin/ls.go package main import ( "fmt" "os" "regexp" "time" "github.com/olekukonko/tablewriter" kingpin "gopkg.in/alecthomas/kingpin.v2" "www.velocidex.com/golang/go-ntfs/parser" ) var ( ls_command = app.Command( "ls", "List files.") ls_command_file_arg = ls_command.Arg( "file", "The image file to inspect", ).Required().OpenFile(os.O_RDONLY, os.FileMode(0666)) ls_command_arg = ls_command.Arg( "path", "The path to list or an MFT entry.", ).Default("/").String() ls_command_image_offset = ls_command.Flag( "image_offset", "An offset into the file.", ).Default("0").Int64() mft_regex = regexp.MustCompile("\\d+") ) func doLS() { reader, _ := parser.NewPagedReader(&parser.OffsetReader{ Offset: *ls_command_image_offset, Reader: getReader(*ls_command_file_arg), }, 1024, 10000) ntfs_ctx, err := parser.GetNTFSContext(reader, 0) kingpin.FatalIfError(err, "Can not open filesystem") dir, err := GetMFTEntry(ntfs_ctx, *ls_command_arg) kingpin.FatalIfError(err, "Can not open path") table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{ "MFT Id", "FullPath", "Size", "Mtime", "IsDir", "Filename", }) table.SetCaption(true, fmt.Sprintf( "Directory listing for MFT %v", *ls_command_arg)) defer table.Render() for _, info := range parser.ListDir(ntfs_ctx, dir) { child_entry, err := GetMFTEntry(ntfs_ctx, info.MFTId) kingpin.FatalIfError(err, "Can not open child %v", info.Name) full_path := parser.GetFullPath(ntfs_ctx, child_entry) table.Append([]string{ info.MFTId, full_path, fmt.Sprintf("%v", info.Size), fmt.Sprintf("%v", info.Mtime.In(time.UTC)), fmt.Sprintf("%v", info.IsDir), info.Name, }) } } func init() { command_handlers = append(command_handlers, func(command string) bool { switch command { case "ls": doLS() default: return false } return true }) } <file_sep>/parser/i30.go package parser import ( "fmt" "io" ) func new_file_info(record *INDEX_RECORD_ENTRY) *FileInfo { filename := record.File() return &FileInfo{ MFTId: fmt.Sprintf("%d", record.MftReference()), Mtime: filename.Mft_modified().Time, Atime: filename.File_accessed().Time, Ctime: filename.Created().Time, Btime: filename.File_modified().Time, Size: int64(filename.FilenameSize()), AllocatedSize: int64(filename.Allocated_size()), Name: filename.Name(), NameType: filename.NameType().Name, } } func ExtractI30ListFromStream( ntfs *NTFSContext, reader io.ReaderAt, stream_size int64) []*FileInfo { result := []*FileInfo{} add_record := func(slack bool, record *INDEX_RECORD_ENTRY) { if !record.IsValid() { return } slack_offset := int64(0) if slack { slack_offset = record.Offset } fi := new_file_info(record) fi.IsSlack = slack fi.SlackOffset = slack_offset result = append(result, fi) } for i := int64(0); i < stream_size; i += 0x1000 { index_root, err := DecodeSTANDARD_INDEX_HEADER( ntfs, reader, i, 0x1000) if err != nil { continue } node := index_root.Node() for _, record := range node.GetRecords(ntfs) { add_record(false, record) } for _, record := range node.ScanSlack(ntfs) { add_record(true, record) } } return result } func ExtractI30List(ntfs *NTFSContext, mft_entry *MFT_ENTRY) []*FileInfo { results := []*FileInfo{} for _, attr := range mft_entry.EnumerateAttributes(ntfs) { switch attr.Type().Value { case ATTR_TYPE_INDEX_ROOT: index_root := ntfs.Profile.INDEX_ROOT( attr.Data(ntfs), 0) for _, record := range index_root.Node().GetRecords(ntfs) { results = append(results, new_file_info(record)) } case ATTR_TYPE_INDEX_ALLOCATION: attr_reader := attr.Data(ntfs) results = append(results, ExtractI30ListFromStream(ntfs, attr_reader, attr.DataSize())...) } } return results } const ( earliest_valid_time = 1000000000 // Sun Sep 9 11:46:40 2001 latest_valid_time = 2000000000 // Wed May 18 13:33:20 2033 ) func (self *INDEX_RECORD_ENTRY) IsValid() bool { test_filename := self.File() x := test_filename.File_modified().Unix() if x < earliest_valid_time || x > latest_valid_time { return false } x = test_filename.File_accessed().Unix() if x < earliest_valid_time || x > latest_valid_time { return false } x = test_filename.Mft_modified().Unix() if x < earliest_valid_time || x > latest_valid_time { return false } x = test_filename.Created().Unix() if x < earliest_valid_time || x > latest_valid_time { return false } return true } func (self *INDEX_NODE_HEADER) ScanSlack(ntfs *NTFSContext) []*INDEX_RECORD_ENTRY { result := []*INDEX_RECORD_ENTRY{} // start at the last record and carve until the end of the // allocation. start := int32(self.Offset_to_end_index_entry()) end := self.SizeOfEntriesAlloc() - 0x52 for off := start; off < end; off++ { test_struct := self.Profile.INDEX_RECORD_ENTRY(self.Reader, int64(off)) if test_struct.IsValid() { result = append(result, test_struct) } } return result } <file_sep>/parser/mft.go package parser import ( "context" "errors" "fmt" "io" "path" "strings" "time" ) var ( notAvailableError = errors.New("Not available") ) func (self *MFT_ENTRY) EnumerateAttributes(ntfs *NTFSContext) []*NTFS_ATTRIBUTE { offset := int64(self.Attribute_offset()) result := make([]*NTFS_ATTRIBUTE, 0, 16) for { // Instantiate the attribute over the fixed up address space. attribute := self.Profile.NTFS_ATTRIBUTE( self.Reader, offset) // Reached the end of the MFT entry. mft_size := int64(self.Mft_entry_size()) attribute_size := int64(attribute.Length()) if attribute_size == 0 || attribute_size+offset > mft_size { break } // This is an $ATTRIBUTE_LIST attribute - append its // own attributes to this one. if attribute.Type().Name == "$ATTRIBUTE_LIST" { attr_list := self.Profile.ATTRIBUTE_LIST_ENTRY( attribute.Data(ntfs), 0) attr_list_members := attr_list.Attributes( ntfs, self, attribute) result = append(result, attr_list_members...) } result = append(result, attribute) // Go to the next attribute. offset += int64(attribute.Length()) } return result } // See https://github.com/CCXLabs/CCXDigger/issues/13 // It is possible that an attribute list is pointing to an mft entry // which also contains an attribute list. The second attribute list // may also point to another entry inside the first MFT entry. This // causes an infinite loop. // Previous versions of the code erroneously called // EnumerateAttributes to resolve a foreign attribute reference but // this is not strictly correct because a foreign reference is never // indirect and so never should traverse ATTRIBUTE_LISTs recursively // anyway. // The GetDirectAttribute() function looks for an exact attribute and // type inside an MFT entry without following any attribute // lists. This breaks the recursion and is a more correct approach. // Search the MFT entry for a contained attribute - does not expand // ATTRIBUTE_LISTs. This version is suitable to be called from within // an ATTRIBUTE_LIST expansion. func (self *MFT_ENTRY) GetDirectAttribute( ntfs *NTFSContext, attr_type uint64, attr_id uint16) (*NTFS_ATTRIBUTE, error) { offset := int64(self.Attribute_offset()) for { // Instantiate the attribute over the fixed up address space. attribute := self.Profile.NTFS_ATTRIBUTE(self.Reader, offset) // Reached the end of the MFT entry. mft_size := int64(self.Mft_entry_size()) attribute_size := int64(attribute.Length()) if attribute_size == 0 || attribute_size+offset > mft_size { break } if attribute.Type().Value == attr_type && attribute.Attribute_id() == attr_id { return attribute, nil } // Go to the next attribute. offset += int64(attribute.Length()) } return nil, errors.New("No attribute found.") } // Open the MFT entry specified by a path name. Walks all directory // indexes in the path to find the right MFT entry. func (self *MFT_ENTRY) Open(ntfs *NTFSContext, filename string) (*MFT_ENTRY, error) { filename = strings.Replace(filename, "\\", "/", -1) filename = strings.Split(filename, ":")[0] // remove ADS if any as not needed components := strings.Split(path.Clean(filename), "/") get_path_in_dir := func(component string, dir *MFT_ENTRY) ( *MFT_ENTRY, error) { // NTFS is usually case insensitive. component = strings.ToLower(component) for _, idx_record := range dir.Dir(ntfs) { item_name := strings.ToLower(idx_record.File().Name()) if item_name == component { return ntfs.GetMFT(int64( idx_record.MftReference())) } } return nil, errors.New("Not found") } directory := self for _, component := range components { if component == "" { continue } next, err := get_path_in_dir(component, directory) if err != nil { return nil, err } directory = next } return directory, nil } func (self *MFT_ENTRY) Display(ntfs *NTFSContext) string { result := []string{self.DebugString()} result = append(result, "Attribute:") for _, attr := range self.EnumerateAttributes(ntfs) { result = append(result, attr.PrintStats(ntfs)) } return fmt.Sprintf("[MFT_ENTRY] @ %#0x\n", self.Offset) + strings.Join(result, "\n") } // Extract the $STANDARD_INFORMATION attribute from the MFT. func (self *MFT_ENTRY) StandardInformation(ntfs *NTFSContext) ( *STANDARD_INFORMATION, error) { for _, attr := range self.EnumerateAttributes(ntfs) { if attr.Type().Value == ATTR_TYPE_STANDARD_INFORMATION { return self.Profile.STANDARD_INFORMATION( attr.Data(ntfs), 0), nil } } return nil, errors.New("$STANDARD_INFORMATION not found!") } // Extract the $FILE_NAME attribute from the MFT. func (self *MFT_ENTRY) FileName(ntfs *NTFSContext) []*FILE_NAME { result := []*FILE_NAME{} for _, attr := range self.EnumerateAttributes(ntfs) { if attr.Type().Value == ATTR_TYPE_FILE_NAME { res := self.Profile.FILE_NAME(attr.Data(ntfs), 0) result = append(result, res) } } return result } // Retrieve the content of the attribute stream specified by type and // id. If id is 0 return the first attribute of this type. func (self *MFT_ENTRY) GetAttribute( ntfs *NTFSContext, attr_type, id int64, stream string) (*NTFS_ATTRIBUTE, error) { for _, attr := range self.EnumerateAttributes(ntfs) { if attr.Type().Value == uint64(attr_type) { if id <= 0 || int64(attr.Attribute_id()) == id { // Optionally allow the caller to specify the stream // name. if stream != "" && stream != attr.Name() { continue } return attr, nil } } } return nil, errors.New("Attribute not found!") } func (self *MFT_ENTRY) IsDir(ntfs *NTFSContext) bool { result := false for _, attr := range self.EnumerateAttributes(ntfs) { switch attr.Type().Value { case ATTR_TYPE_INDEX_ROOT, ATTR_TYPE_INDEX_ALLOCATION: return true } } return result } func (self *MFT_ENTRY) Dir(ntfs *NTFSContext) []*INDEX_RECORD_ENTRY { result := []*INDEX_RECORD_ENTRY{} for _, node := range self.DirNodes(ntfs) { result = append(result, node.GetRecords(ntfs)...) } return result } func (self *MFT_ENTRY) DirNodes(ntfs *NTFSContext) []*INDEX_NODE_HEADER { result := []*INDEX_NODE_HEADER{} for _, attr := range self.EnumerateAttributes(ntfs) { switch attr.Type().Value { case ATTR_TYPE_INDEX_ROOT: index_root := self.Profile.INDEX_ROOT( attr.Data(ntfs), 0) result = append(result, index_root.Node()) case ATTR_TYPE_INDEX_ALLOCATION: attr_reader := attr.Data(ntfs) for i := int64(0); i < int64(attr.DataSize()); i += 0x1000 { index_root, err := DecodeSTANDARD_INDEX_HEADER( ntfs, attr_reader, i, 0x1000) if err == nil { result = append(result, index_root.Node()) } } } } return result } type GenericRun struct { Offset int64 End int64 Reader io.ReaderAt } // Stitch together several different readers mapped at different // offsets. In NTFS, a file's data consists of multiple $DATA // streams, each having the same id. These different streams are // mapped at different runlist_vcn_start to runlist_vcn_end (VCN = // Virtual Cluster Number: the cluster number within the file's // data). This reader combines these different readers into a single // continuous form. type MapReader struct { // Very simple for now but faster for small number of runs. Runs []*GenericRun } func (self *MapReader) partialRead(buf []byte, offset int64) (int, error) { DebugPrint("MapReader.partialRead %v @ %v\n", len(buf), offset) if len(buf) > 0 { for _, run := range self.Runs { if run.Offset <= offset && offset < run.End { available := run.End - offset to_read := int64(len(buf)) if to_read > available { to_read = available } return run.Reader.ReadAt( buf[:to_read], offset-run.Offset) } } } return 0, io.EOF } func (self *MapReader) ReadAt(buf []byte, offset int64) (int, error) { to_read := len(buf) idx := int(0) for to_read > 0 { res, err := self.partialRead(buf[idx:], offset+int64(idx)) if err != nil { return idx, err } to_read -= res idx += res } return idx, nil } type MFTHighlight struct { EntryNumber int64 Inode string SequenceNumber uint16 InUse bool ParentEntryNumber uint64 ParentSequenceNumber uint16 FileNames []string _FileNameTypes []string FileSize int64 ReferenceCount int64 IsDir bool HasADS bool SI_Lt_FN bool USecZeros bool Copied bool SIFlags string Created0x10 time.Time Created0x30 time.Time LastModified0x10 time.Time LastModified0x30 time.Time LastRecordChange0x10 time.Time LastRecordChange0x30 time.Time LastAccess0x10 time.Time LastAccess0x30 time.Time LogFileSeqNum uint64 // Hold on to these for delayed lazy evaluation. ntfs_ctx *NTFSContext mft_entry *MFT_ENTRY ads_name string components []string } // Copy the struct safely replacing the mutex func (self *MFTHighlight) Copy() *MFTHighlight { return &MFTHighlight{ EntryNumber: self.EntryNumber, SequenceNumber: self.SequenceNumber, InUse: self.InUse, ParentEntryNumber: self.ParentEntryNumber, ParentSequenceNumber: self.ParentSequenceNumber, FileNames: self.FileNames, _FileNameTypes: self._FileNameTypes, FileSize: self.FileSize, ReferenceCount: self.ReferenceCount, IsDir: self.IsDir, HasADS: self.HasADS, SI_Lt_FN: self.SI_Lt_FN, USecZeros: self.USecZeros, Copied: self.Copied, SIFlags: self.SIFlags, Created0x10: self.Created0x10, Created0x30: self.Created0x30, LastModified0x10: self.LastModified0x10, LastModified0x30: self.LastModified0x30, LastRecordChange0x10: self.LastRecordChange0x10, LastRecordChange0x30: self.LastRecordChange0x30, LastAccess0x10: self.LastAccess0x10, LastAccess0x30: self.LastAccess0x30, LogFileSeqNum: self.LogFileSeqNum, ntfs_ctx: self.ntfs_ctx, mft_entry: self.mft_entry, ads_name: self.ads_name, } } func (self *MFTHighlight) FullPath() string { return "/" + path.Join(self.Components()...) } func (self *MFTHighlight) Links() []string { components := GetHardLinks(self.ntfs_ctx, uint64(self.EntryNumber), DefaultMaxLinks) result := make([]string, 0, len(components)) for _, l := range components { result = append(result, strings.Join(l, "\\")) } return result } func (self *MFTHighlight) FileNameTypes() string { return strings.Join(self._FileNameTypes, ",") } func (self *MFTHighlight) FileName() string { short_name := "" for idx, name := range self.FileNames { name_type := self._FileNameTypes[idx] switch name_type { case "Win32", "DOS+Win32", "POSIX": return name default: short_name = name } } return short_name } // For simplicity and backwards compatibility returns the first hard // link of the mft entry. In NTFS MFT entries can have multiple paths // so you should consult the Links() to get more info. func (self *MFTHighlight) Components() []string { components := []string{} links := GetHardLinks(self.ntfs_ctx, uint64(self.EntryNumber), 1) if len(links) > 0 { components = links[0] } if self.ads_name != "" { return setADS(components, self.ads_name) } return components } func ParseMFTFile( ctx context.Context, reader io.ReaderAt, size int64, cluster_size int64, record_size int64) chan *MFTHighlight { return ParseMFTFileWithOptions(ctx, reader, size, cluster_size, record_size, 0, GetDefaultOptions()) } func ParseMFTFileWithOptions( ctx context.Context, reader io.ReaderAt, size int64, cluster_size int64, record_size int64, start_entry int64, options Options) chan *MFTHighlight { output := make(chan *MFTHighlight) if record_size == 0 { close(output) return output } go func() { defer close(output) ntfs := newNTFSContext(&NullReader{}, "NullReader") defer ntfs.Close() ntfs.MFTReader = reader ntfs.ClusterSize = cluster_size ntfs.RecordSize = record_size ntfs.SetOptions(options) for id := start_entry; id < size/record_size+1; id++ { mft_entry, err := ntfs.GetMFT(id) if err != nil { continue } var file_names []*FILE_NAME var file_name_types []string var file_name_strings []string var si *STANDARD_INFORMATION var size int64 ads := []string{} ads_sizes := []int64{} si_flags := "" for _, attr := range mft_entry.EnumerateAttributes(ntfs) { attr_type := attr.Type() switch attr_type.Value { case ATTR_TYPE_DATA: if size == 0 { size = attr.DataSize() } // Check if the stream has ADS attr_name := attr.Name() if attr_name != "" { ads = append(ads, attr_name) ads_sizes = append(ads_sizes, int64(attr.Size())) } case ATTR_TYPE_FILE_NAME: res := ntfs.Profile.FILE_NAME(attr.Data(ntfs), 0) file_names = append(file_names, res) file_name_types = append(file_name_types, res.NameType().Name) fn := res.Name() file_name_strings = append(file_name_strings, fn) case ATTR_TYPE_STANDARD_INFORMATION: si = ntfs.Profile.STANDARD_INFORMATION( attr.Data(ntfs), 0) si_flags = si.Flags().DebugString() } } if len(file_names) == 0 { continue } if si == nil { continue } mft_id := mft_entry.Record_number() row := &MFTHighlight{ EntryNumber: int64(mft_id), Inode: fmt.Sprintf("%d", mft_id), SequenceNumber: mft_entry.Sequence_value(), InUse: mft_entry.Flags().IsSet("ALLOCATED"), ParentEntryNumber: file_names[0].MftReference(), ParentSequenceNumber: file_names[0].Seq_num(), FileNames: file_name_strings, _FileNameTypes: file_name_types, FileSize: size, ReferenceCount: int64(mft_entry.Link_count()), IsDir: mft_entry.Flags().IsSet("DIRECTORY"), HasADS: len(ads) > 0, SIFlags: si_flags, Created0x10: si.Create_time().Time, Created0x30: file_names[0].Created().Time, LastModified0x10: si.File_altered_time().Time, LastModified0x30: file_names[0].File_modified().Time, LastRecordChange0x10: si.Mft_altered_time().Time, LastRecordChange0x30: file_names[0].Mft_modified().Time, LastAccess0x10: si.File_accessed_time().Time, LastAccess0x30: file_names[0].File_accessed().Time, LogFileSeqNum: mft_entry.Logfile_sequence_number(), ntfs_ctx: ntfs, mft_entry: mft_entry, } row.SI_Lt_FN = row.Created0x10.Before(row.Created0x30) row.USecZeros = row.Created0x10.Unix()*1000000000 == row.Created0x10.UnixNano() || row.LastModified0x10.Unix()*1000000000 == row.LastModified0x10.UnixNano() row.Copied = row.Created0x10.After(row.LastModified0x10) // Check for cancellations. select { case <-ctx.Done(): return case output <- row: } // Duplicate ADS names so we can easily search on them. for idx, ads_name := range ads { new_row := row.Copy() file_names := []string{} // Convert all the names to have an ADS at the end // (long name + ":" + ads, short name + ":" + ads // etc). for _, name := range new_row.FileNames { file_names = append(file_names, name+":"+ads_name) } new_row.FileNames = file_names new_row.IsDir = false new_row.ads_name = ads_name new_row.FileSize = ads_sizes[idx] new_row.Inode += ":" + ads_name select { case <-ctx.Done(): return case output <- new_row: } } } }() return output } <file_sep>/parser/stats.go package parser import ( "encoding/json" "sync" ) var ( STATS = Stats{} ) type Stats struct { mu sync.Mutex MFT_ENTRY int NTFS_ATTRIBUTE int ATTRIBUTE_LIST_ENTRY int STANDARD_INFORMATION int FILE_NAME int FixUpDiskMFTEntry int NTFSContext int MFT_ENTRY_attributes int MFT_ENTRY_filenames int } func (self *Stats) DebugString() string { self.mu.Lock() defer self.mu.Unlock() serialized, _ := json.MarshalIndent(self, " ", " ") return string(serialized) } func (self *Stats) Inc_MFT_ENTRY() { self.mu.Lock() defer self.mu.Unlock() self.MFT_ENTRY++ } func (self *Stats) Inc_NTFSContext() { self.mu.Lock() defer self.mu.Unlock() self.NTFSContext++ } func (self *Stats) Inc_FixUpDiskMFTEntry() { self.mu.Lock() defer self.mu.Unlock() self.FixUpDiskMFTEntry++ } func (self *Stats) Inc_NTFS_ATTRIBUTE() { self.mu.Lock() defer self.mu.Unlock() self.NTFS_ATTRIBUTE++ } func (self *Stats) Inc_ATTRIBUTE_LIST_ENTRY() { self.mu.Lock() defer self.mu.Unlock() self.ATTRIBUTE_LIST_ENTRY++ } func (self *Stats) Inc_STANDARD_INFORMATION() { self.mu.Lock() defer self.mu.Unlock() self.STANDARD_INFORMATION++ } func (self *Stats) Inc_FILE_NAME() { self.mu.Lock() defer self.mu.Unlock() self.FILE_NAME++ } func (self *Stats) Inc_MFT_ENTRY_attributes() { self.mu.Lock() defer self.mu.Unlock() self.MFT_ENTRY_attributes++ } func (self *Stats) Inc_MFT_ENTRY_filenames() { self.mu.Lock() defer self.mu.Unlock() self.MFT_ENTRY_filenames++ } <file_sep>/bin/tester.go package main import ( "crypto/md5" "encoding/hex" "fmt" "io" "os/exec" "sync" kingpin "gopkg.in/alecthomas/kingpin.v2" "www.velocidex.com/golang/go-ntfs/parser" ) var ( test_command = app.Command( "test", "Test file reading by comparing with TSK.") test_command_file_arg = test_command.Arg( "file", "The image file to inspect", ).Required().File() test_command_icat_path = test_command.Flag( "icat_path", "Path to the icat binary"). Default("icat").String() test_command_start_id = test_command.Flag( "start", "First MFT ID to test").Default("0").Int64() test_command_max_size = test_command.Flag( "max_size", "Skip testing files of this size"). Default("104857600").Int64() test_command_min_size = test_command.Flag( "min_size", "Skip testing files smaller then this size"). Default("1024").Int64() ) func calcHashWithTSK(inode string) (string, int64, error) { command := exec.Command(*test_command_icat_path, (*test_command_file_arg).Name(), inode) stdout_pipe, err := command.StdoutPipe() if err != nil { return "", 0, err } err = command.Start() if err != nil { return "", 0, err } wg := &sync.WaitGroup{} md5_sum := md5.New() offset := 0 wg.Add(1) go func() { defer wg.Done() buff := make([]byte, 1000000) for { n, err := stdout_pipe.Read(buff) if err != nil && err != io.EOF { return } if n == 0 { return } md5_sum.Write(buff[:n]) offset += n } }() wg.Wait() return hex.EncodeToString(md5_sum.Sum(nil)), int64(offset), nil } func doTest() { reader, err := parser.NewPagedReader(*test_command_file_arg, 1024, 10000) kingpin.FatalIfError(err, "Can not open MFT file") ntfs_ctx, err := parser.GetNTFSContext(reader, 0) kingpin.FatalIfError(err, "Can not open filesystem") mft_stream, err := parser.GetDataForPath(ntfs_ctx, "$MFT") kingpin.FatalIfError(err, "Can not open filesystem") buffer := make([]byte, 1024*1024) for i := int64(*test_command_start_id); i < parser.RangeSize(mft_stream)/ntfs_ctx.RecordSize; i++ { mft_entry, err := ntfs_ctx.GetMFT(i) if err != nil { continue } if !mft_entry.Flags().IsSet("ALLOCATED") { continue } // Skip MFT entries which belong to an attribute list. if mft_entry.Base_record_reference() != 0 { continue } for _, attr := range mft_entry.EnumerateAttributes(ntfs_ctx) { reader, err := parser.OpenStream(ntfs_ctx, mft_entry, attr.Type().Value, attr.Attribute_id(), "") if err != nil { continue } size := parser.RangeSize(reader) if size > *test_command_max_size || size < *test_command_min_size { continue } inode := fmt.Sprintf("%v-%v-%v", i, attr.Type().Value, attr.Attribute_id()) fmt.Printf("%s :", inode) md5_sum := md5.New() offset := int64(0) for { n, err := reader.ReadAt(buffer, offset) if n == 0 || err == io.EOF { break } data := buffer[:n] md5_sum.Write(data) offset += int64(n) } our_hash := hex.EncodeToString(md5_sum.Sum(nil)) fmt.Printf("%v %v\n", our_hash, offset) // Shell out to icat to calculate the hash tsk_hash, tsk_length, err := calcHashWithTSK(inode) kingpin.FatalIfError(err, "Can not shell to tsk") fmt.Printf(" TSK hash: %v %v\n", tsk_hash, tsk_length) // TSK makes up its own ntfs stream IDs for // some streams. This means when we try to // open the stream with the original id, icat // can not find it. We skip those cases // because it is very hard to tell the id that // TSK picks (it is random and not related to // the actual stream ID). if tsk_length == 0 { continue } if tsk_length != offset || tsk_hash != our_hash { fmt.Printf("******* Error!\n") } } } } func init() { command_handlers = append(command_handlers, func(command string) bool { switch command { case test_command.FullCommand(): doTest() default: return false } return true }) } type readAdapter struct { pos int64 reader io.ReaderAt } func (self *readAdapter) Read(buf []byte) (res int, err error) { res, err = self.reader.ReadAt(buf, self.pos) self.pos += int64(res) return res, err } <file_sep>/parser/constants.go package parser const ( MAX_RUNLIST_SIZE = 1000000 MAX_DECOMPRESSED_FILE = 1000000 MAX_IDX_SIZE = 1000000 MAX_MFT_ENTRY_SIZE = 32 * 1024 MAX_USN_RECORD_SCAN_SIZE = 1024 MAX_ATTR_NAME_LENGTH = 1024 MAX_FILENAME_LENGTH = 32 * 1024 ATTR_TYPE_DATA = 128 ATTR_TYPE_ATTRIBUTE_LIST = 32 ATTR_TYPE_STANDARD_INFORMATION = 16 ATTR_TYPE_FILE_NAME = 48 ATTR_TYPE_INDEX_ROOT = 144 ATTR_TYPE_INDEX_ALLOCATION = 160 ) <file_sep>/parser/lznt1.go /* Decompression support for the LZNT1 compression algorithm. Reference: http://msdn.microsoft.com/en-us/library/jj665697.aspx (2.5 LZNT1 Algorithm Details) https://github.com/libyal/reviveit/ https://github.com/sleuthkit/sleuthkit/blob/develop/tsk/fs/ntfs.c */ package parser import ( "encoding/binary" "errors" ) var ( COMPRESSED_MASK = uint16(1 << 15) SIGNATURE_MASK = uint16(3 << 12) SIZE_MASK = uint16(1<<12) - 1 shiftTooLargeError = errors.New( "Decompression error - shift is too large") blockTooSmallError = errors.New("Block too small!") ) func get_displacement(offset uint16) byte { result := byte(0) for { if offset < 0x10 { return result } offset >>= 1 result += 1 } } func LZNT1Decompress(in []byte) ([]byte, error) { debugLZNT1Decompress("LZNT1Decompress in:\n%s\n", debugHexDump(in)) // Index into the in buffer i := 0 out := []byte{} for { if len(in) < i+2 { break } uncompressed_chunk_offset := len(out) block_offset := i block_header := binary.LittleEndian.Uint16(in[i:]) debugLZNT1Decompress("Header %#x @ %#x %d\n", block_header, i, i) i += 2 size := int(block_header & SIZE_MASK) block_end := block_offset + size + 3 debugLZNT1Decompress("%d Block Size: %x ends at %x\n", len(out), size+3, block_end) if size == 0 { break } if len(in) < i+size { return nil, blockTooSmallError } if block_header&COMPRESSED_MASK != 0 { for i < block_end { header := uint8(in[i]) debugLZNT1Decompress("%d Header Tag %02x\n", len(out), header) i++ for mask_idx := uint8(0); mask_idx < 8 && i < block_end; mask_idx++ { if (header & 1) == 0 { debugLZNT1Decompress(" %d: Symbol %02x (%d)\n", i, in[i], len(out)) out = append(out, in[i]) i++ } else { pointer := binary.LittleEndian.Uint16(in[i:]) i += 2 displacement := get_displacement( uint16(len(out) - uncompressed_chunk_offset - 1)) symbol_offset := int(pointer>>(12-displacement)) + 1 symbol_length := int(pointer&(0xFFF>>displacement)) + 2 start_offset := len(out) - symbol_offset for j := 0; j < symbol_length+1; j++ { idx := start_offset + j if idx < 0 || idx >= len(out) { debugLZNT1Decompress( "idx %v, pointer %v, displacement %v out\n %v\n", idx, pointer, displacement, debugHexDump(out)) return out, shiftTooLargeError } out = append(out, out[idx]) } } header >>= 1 } } // Block is not compressed. } else { out = append(out, in[i:i+size+1]...) i += size + 1 } } debugLZNT1Decompress("decompression out %v\n", len(out)) return out, nil } <file_sep>/bin/test_filename.go package main import ( "fmt" "os/exec" "strings" kingpin "gopkg.in/alecthomas/kingpin.v2" "www.velocidex.com/golang/go-ntfs/parser" ) var ( test_fn_command = app.Command( "test_filename", "Test file path reconstruction by comparing with TSK.") test_fn_command_file_arg = test_fn_command.Arg( "file", "The image file to inspect", ).Required().File() test_fn_command_ffind_path = test_fn_command.Flag( "ffind_path", "Path to the ffind binary"). Default("ffind").String() test_fn_command_start_id = test_fn_command.Flag( "start", "First MFT ID to test").Default("0").Int64() ) func calcFilenameWithTSK(inode string) (string, error) { command := exec.Command(*test_fn_command_ffind_path, (*test_fn_command_file_arg).Name(), inode) output, err := command.CombinedOutput() if err != nil { return "", err } return strings.TrimSpace(string(output)), nil } func doTestFn() { reader, err := parser.NewPagedReader(*test_fn_command_file_arg, 1024, 10000) kingpin.FatalIfError(err, "Can not open MFT file") ntfs_ctx, err := parser.GetNTFSContext(reader, 0) kingpin.FatalIfError(err, "Can not open filesystem") mft_stream, err := parser.GetDataForPath(ntfs_ctx, "$MFT") kingpin.FatalIfError(err, "Can not open filesystem") for i := int64(*test_command_start_id); i < parser.RangeSize(mft_stream)/ntfs_ctx.RecordSize; i++ { mft_entry, err := ntfs_ctx.GetMFT(i) if err != nil { continue } full_path := parser.GetFullPath(ntfs_ctx, mft_entry) if *verbose_flag { fmt.Printf("%v: %v\n", i, full_path) } tsk_path, err := calcFilenameWithTSK(fmt.Sprintf("%v", i)) if err != nil { fmt.Printf("go-ntfs Error %v: %v\n", i, err) } if *verbose_flag { fmt.Printf("tsk_path %v: %v\n", i, tsk_path) } if tsk_path != full_path { fmt.Printf("**** ERROR %v: %v != %v\n", i, tsk_path, full_path) } } } func init() { command_handlers = append(command_handlers, func(command string) bool { switch command { case test_fn_command.FullCommand(): doTestFn() default: return false } return true }) } <file_sep>/bin/main.go package main import ( "os" kingpin "gopkg.in/alecthomas/kingpin.v2" "www.velocidex.com/golang/go-ntfs/parser" ) type CommandHandler func(command string) bool var ( app = kingpin.New("gontfs", "A tool for inspecting ntfs volumes.") verbose_flag = app.Flag( "verbose", "Show verbose information").Bool() command_handlers []CommandHandler ) func main() { app.HelpFlag.Short('h') app.UsageTemplate(kingpin.CompactUsageTemplate) command := kingpin.MustParse(app.Parse(os.Args[1:])) if *verbose_flag { parser.SetDebug() } for _, command_handler := range command_handlers { if command_handler(command) { break } } } <file_sep>/bin/live.go package main import ( "crypto/sha256" "fmt" "io" "os" "path/filepath" "regexp" "runtime/pprof" "strings" "time" kingpin "gopkg.in/alecthomas/kingpin.v2" "www.velocidex.com/golang/go-ntfs/parser" ) var ( live_test_command = app.Command( "live_test", "Test file reading by performing live hashing.") live_test_command_drive = live_test_command.Arg( "drive", "Drive letter to test"). Default("C").String() live_test_command_glob = live_test_command.Arg( "glob", "Starting path to recurse"). Default("Windows\\*").String() live_test_command_profile = live_test_command.Flag( "profile", "Write profile data to this filename").String() ) func doLiveTest() { now := time.Now() defer func() { fmt.Printf("Completed test in %v\n", time.Now().Sub(now)) }() if *live_test_command_profile != "" { f2, err := os.Create(*live_test_command_profile) kingpin.FatalIfError(err, "Creating Profile file.") err = pprof.StartCPUProfile(f2) kingpin.FatalIfError(err, "Profile file.") defer pprof.StopCPUProfile() } matched, _ := regexp.MatchString("^[a-zA-Z]$", *live_test_command_drive) if !matched { kingpin.Fatalf("Invalid drive letter: should be eg 'C'") } image_fd, err := os.Open("\\\\.\\" + *live_test_command_drive + ":") kingpin.FatalIfError(err, "Can not open drive") reader, _ := parser.NewPagedReader(image_fd, 1024, 10000) ntfs_ctx, err := parser.GetNTFSContext(reader, 0) kingpin.FatalIfError(err, "Can not open filesystem") glob := fmt.Sprintf("%s:\\%s", *live_test_command_drive, *live_test_command_glob) files, err := filepath.Glob(glob) kingpin.FatalIfError(err, "Can not glob files") for _, filename := range files { stat, err := os.Lstat(filename) if err != nil { kingpin.FatalIfError(err, "Can not glob files") continue } if stat.IsDir() { continue } fd, err := os.Open(filename) if err != nil { continue } // Calculate the hash of the file h := sha256.New() buf := make([]byte, 1024*1024) _, err = io.CopyBuffer(h, fd, buf) if err != nil && err != io.EOF { continue } os_hash := fmt.Sprintf("File %v %x", filename, h.Sum(nil)) mft_entry, err := GetMFTEntry(ntfs_ctx, getRelativePath(filename)) if err != nil { fmt.Printf("ERROR Getting MFT Id: %v\n", err) } reader, err := parser.OpenStream(ntfs_ctx, mft_entry, 128, parser.WILDCARD_STREAM_ID, "") if err != nil { fmt.Printf("ERROR Getting MFT Id %v: %v\n", mft_entry.Record_number(), err) continue } ntfs_h := sha256.New() _, err = io.CopyBuffer(ntfs_h, &readAdapter{reader: reader}, buf) if err != nil && err != io.EOF { fmt.Printf("ERROR Getting MFT Id %v: %v\n", mft_entry.Record_number(), err) continue } ntfs_hash := fmt.Sprintf("File %v %x", filename, h.Sum(nil)) if os_hash != ntfs_hash { fmt.Printf("ERROR Mismatch hash on MFT entry %v:\n%s\n%s\n", mft_entry.Record_number(), os_hash, ntfs_hash) } else { fmt.Printf("%v (MFTID %v): %v (%v bytes)\n", time.Now().Format(time.RFC3339), mft_entry.Record_number(), os_hash, stat.Size()) } } } func getRelativePath(filename string) string { parts := strings.SplitN(filename, ":", 2) if len(parts) > 0 { return parts[1] } return filename } func init() { command_handlers = append(command_handlers, func(command string) bool { switch command { case live_test_command.FullCommand(): doLiveTest() default: return false } return true }) } <file_sep>/parser/hardlinks.go /* This code traverse MFT entries to discover all the paths an entry is known by. In NTFS A file (MFT Entry) may exist in multiple direcotries this is called hardlinks. You can create a hardlink using the fsutils utility: C:> fsutil.exe hardlink create C:/users/test/X.txt "C:/users/test/downloads/X.txt" Hardlink created for C:\users\test\X.txt <<===>> C:\users\test\downloads\X.txt This adds a $FILE_NAME attribute to the MFT entry and points it at a different parent. */ package parser import ( "fmt" ) const ( IncludeShortNames = true DoNotIncludeShortNames = false ) type Visitor struct { Paths [][]string Max int IncludeShortNames bool Prefix []string } func (self *Visitor) Add(idx int, depth int) int { self.Paths = append(self.Paths, CopySlice(self.Paths[idx][:depth])) return len(self.Paths) - 1 } func (self *Visitor) AddComponent(idx int, component string) { self.Paths[idx] = append(self.Paths[idx], component) } func (self *Visitor) Components() [][]string { result := make([][]string, 0, len(self.Paths)) for _, p := range self.Paths { ReverseStringSlice(p) components := append([]string{}, self.Prefix...) components = append(components, p...) if len(p) > 0 { result = append(result, components) } } return result } // Walks the MFT entry to get all file names to this MFT entry. func GetHardLinks(ntfs *NTFSContext, mft_id uint64, max int) [][]string { if max == 0 { max = ntfs.options.MaxLinks } visitor := &Visitor{ Paths: [][]string{[]string{}}, Max: max, IncludeShortNames: ntfs.options.IncludeShortNames, Prefix: ntfs.options.PrefixComponents, } mft_entry_summary, err := ntfs.GetMFTSummary(mft_id) if err != nil { return nil } getNames(ntfs, mft_entry_summary, visitor, 0, 0) return visitor.Components() } func getNames(ntfs *NTFSContext, mft_entry *MFTEntrySummary, visitor *Visitor, idx, depth int) { if depth > ntfs.options.MaxDirectoryDepth { visitor.AddComponent(idx, "<DirTooDeep>") visitor.AddComponent(idx, "<Err>") return } // Filter out short file names filenames := []FNSummary{} if visitor.IncludeShortNames { filenames = mft_entry.Filenames } else { for _, fn := range mft_entry.Filenames { switch fn.NameType { case "Win32", "DOS+Win32", "POSIX": filenames = append(filenames, fn) } } } // If we only have short names thats what we will use. if len(filenames) == 0 { filenames = mft_entry.Filenames } // No filenames in this MFT entry - this is a dead end! if len(filenames) == 0 { visitor.AddComponent(idx, "<UnknownEntry>") visitor.AddComponent(idx, "<Err>") return } // Order the filenames such that the long file name comes first. if len(filenames) > 1 && filenames[0].NameType == "DOS" { filenames[0], filenames[1] = filenames[1], filenames[0] } for i, fn := range filenames { // The first FN entry continues to visit the same path but the // next one will add a new path. visitor_idx := idx if i > 0 { visitor_idx = visitor.Add(idx, depth) if visitor_idx > visitor.Max { continue } } visitor.AddComponent(visitor_idx, fn.Name) // No more recursion - we met the terminal path. if fn.ParentEntryNumber == 5 || fn.ParentEntryNumber == 0 { continue } parent_entry, err := ntfs.GetMFTSummary(fn.ParentEntryNumber) if err != nil { visitor.AddComponent(visitor_idx, err.Error()) visitor.AddComponent(visitor_idx, "<Err>") continue } if fn.ParentSequenceNumber != parent_entry.Sequence { visitor.AddComponent(visitor_idx, fmt.Sprintf("<Parent %v-%v need %v>", fn.ParentEntryNumber, parent_entry.Sequence, fn.ParentSequenceNumber)) visitor.AddComponent(visitor_idx, "<Err>") continue } getNames(ntfs, parent_entry, visitor, visitor_idx, depth+1) } } <file_sep>/bin/i30.go package main import ( "encoding/csv" "encoding/json" "fmt" "os" kingpin "gopkg.in/alecthomas/kingpin.v2" "www.velocidex.com/golang/go-ntfs/parser" ) var ( i30_command = app.Command( "i30", "Extract entries from an $I30 stream.") i30_command_file_arg = i30_command.Arg( "file", "The I30 stream to inspect.", ).Required().OpenFile(os.O_RDONLY, os.FileMode(0666)) i30_command_file_csv = i30_command.Flag( "csv", "Output in CSV.", ).Bool() ) func doI30() { reader, _ := parser.NewPagedReader(*i30_command_file_arg, 1024, 10000) ntfs := &parser.NTFSContext{ Profile: parser.NewNTFSProfile()} stat, err := (*i30_command_file_arg).Stat() kingpin.FatalIfError(err, "stat") data := append([]*parser.FileInfo{}, parser.ExtractI30ListFromStream( ntfs, reader, stat.Size())...) if *i30_command_file_csv { writer := csv.NewWriter(os.Stdout) defer writer.Flush() writer.Write([]string{"Name", "NameType", "Size", "AllocatedSize", "Mtime", "Atime", "Ctime", "Btime"}) for _, info := range data { name := info.Name if info.IsSlack { name += fmt.Sprintf(" (slack @ %#x)", info.SlackOffset) } writer.Write([]string{ name, info.NameType, fmt.Sprintf("%v", info.Size), fmt.Sprintf("%v", info.AllocatedSize), fmt.Sprintf("%v", info.Mtime), fmt.Sprintf("%v", info.Atime), fmt.Sprintf("%v", info.Ctime), fmt.Sprintf("%v", info.Btime), }) } } else { serialized, err := json.Marshal(data) kingpin.FatalIfError(err, "serialized") fmt.Printf("%v\n", string(serialized)) } } func init() { command_handlers = append(command_handlers, func(command string) bool { switch command { case "i30": doI30() default: return false } return true }) } <file_sep>/parser/usn.go package parser import ( "context" "errors" "fmt" "io" "strings" "time" ) // Parse USN records // https://docs.microsoft.com/en-us/windows/win32/api/winioctl/ns-winioctl-usn_record_v2 type USN_RECORD struct { *USN_RECORD_V2 context *NTFSContext } func (self *USN_RECORD) DebugString() string { result := self.USN_RECORD_V2.DebugString() result += fmt.Sprintf(" Filename: %v\n", self.Filename()) return result } func (self *USN_RECORD) Filename() string { return ParseUTF16String(self.Reader, self.Offset+int64(self.FileNameOffset()), CapInt64(int64(self.FileNameLength()), MAX_FILENAME_LENGTH)) } func (self *USN_RECORD) Validate() bool { return self.Usn() > 0 && self.RecordLength() != 0 } func (self *USN_RECORD) Next(max_offset int64) *USN_RECORD { length := int64(self.RecordLength()) // Record length should be reasonable and 64 bit aligned. if length > 0 && length < 1024 && (self.Offset+length)%8 == 0 { result := NewUSN_RECORD(self.context, self.Reader, self.Offset+length) // Only return if the record is valid if result.Validate() { return result } } // Sometimes there is a sequence of null bytes after a record // and before the next record. If the next record is not // immediately after the previous record we scan ahead a bit // to try to find it. // Scan ahead trying to find the next record. We search for // the first non-zero byte and try to instantiate a record // over it. If the record is valid we return it. for offset := self.Offset + length; offset <= max_offset; { to_read := max_offset - offset data := make([]byte, CapInt64(to_read, MAX_USN_RECORD_SCAN_SIZE)) n, err := self.Reader.ReadAt(data, offset) if err != nil || n == 0 { return nil } // scan the buffer for the first non zero byte. for i := 0; i < n; i++ { if data[i] != 0 { result := NewUSN_RECORD( self.context, self.Reader, offset+int64(i)) if result.Validate() { return result } } } offset += int64(len(data)) } return nil } func (self *USN_RECORD) Links() []string { // Since this record could have mean a file deletion event // then resolving the actual MFT entry to a full path is less // reliable. It is more reliable to resolve the parent path, // and then add the USN record name to it. parent_mft_id := self.USN_RECORD_V2.ParentFileReferenceNumberID() parent_mft_sequence := self.USN_RECORD_V2.ParentFileReferenceNumberSequence() // Make sure the parent has the correct sequence to prevent // nonsensical paths. parent_mft_entry, err := self.context.GetMFTSummary(parent_mft_id) if err != nil { return []string{fmt.Sprintf("<Err>\\<Parent %v Error %v>\\%v", parent_mft_id, err, self.Filename())} } if uint64(parent_mft_entry.Sequence) != parent_mft_sequence { return []string{fmt.Sprintf("<Err>\\<Parent %v-%v need %v>\\%v", parent_mft_id, parent_mft_entry.Sequence, parent_mft_sequence, self.Filename())} } components := GetHardLinks(self.context, uint64(parent_mft_id), DefaultMaxLinks) result := make([]string, 0, len(components)) for _, l := range components { l = append(l, self.Filename()) result = append(result, strings.Join(l, "\\")) } return result } // Resolve the file to a full path func (self *USN_RECORD) FullPath() string { // Since this record could have meant a file deletion event // then resolving the actual MFT entry to a full path is less // reliable. It is more reliable to resolve the parent path, // and then add the USN record name to it. parent_mft_id := self.USN_RECORD_V2.ParentFileReferenceNumberID() parent_mft_entry, err := self.context.GetMFT(int64(parent_mft_id)) if err != nil { return "" } file_names := parent_mft_entry.FileName(self.context) if len(file_names) == 0 { return "" } parent_full_path := GetFullPath(self.context, parent_mft_entry) return parent_full_path + "/" + self.Filename() } func (self *USN_RECORD) Reason() []string { return self.USN_RECORD_V2.Reason().Values() } func (self *USN_RECORD) FileAttributes() []string { return self.USN_RECORD_V2.FileAttributes().Values() } func (self *USN_RECORD) SourceInfo() []string { return self.USN_RECORD_V2.FileAttributes().Values() } func NewUSN_RECORD(ntfs *NTFSContext, reader io.ReaderAt, offset int64) *USN_RECORD { return &USN_RECORD{ USN_RECORD_V2: ntfs.Profile.USN_RECORD_V2(reader, offset), context: ntfs, } } func getUSNStream(ntfs_ctx *NTFSContext) (mft_id int64, attr_id uint16, attr_name string, err error) { dir, err := ntfs_ctx.GetMFT(5) if err != nil { return 0, 0, "", err } // Open the USN file from the root of the filesystem. mft_entry, err := dir.Open(ntfs_ctx, "$Extend\\$UsnJrnl") if err != nil { return 0, 0, "", errors.New("Can not open path") } // Find the attribute we need. for _, attr := range mft_entry.EnumerateAttributes(ntfs_ctx) { name := attr.Name() if attr.Type().Value == ATTR_TYPE_DATA && name == "$J" { return int64(mft_entry.Record_number()), attr.Attribute_id(), name, nil } } return 0, 0, "", errors.New("Can not find $Extend\\$UsnJrnl:$J") } // Returns a channel which will send USN records on. We start parsing // at the start of the file and continue until the end. func ParseUSN(ctx context.Context, ntfs_ctx *NTFSContext, starting_offset int64) chan *USN_RECORD { output := make(chan *USN_RECORD) go func() { defer close(output) mft_id, attr_id, attr_name, err := getUSNStream(ntfs_ctx) if err != nil { DebugPrint("ParseUSN error: %v", err) return } mft_entry, err := ntfs_ctx.GetMFT(mft_id) if err != nil { DebugPrint("ParseUSN error: %v", err) return } data, err := OpenStream(ntfs_ctx, mft_entry, 128, attr_id, attr_name) if err != nil { DebugPrint("ParseUSN error: %v", err) return } count := 0 defer DebugPrint("Skipped %v entries\n", count) for _, rng := range data.Ranges() { run_end := rng.Offset + rng.Length if rng.IsSparse { continue } if starting_offset > run_end { count++ continue } for record := NewUSN_RECORD(ntfs_ctx, data, rng.Offset); record != nil; record = record.Next(run_end) { if record.Offset < starting_offset { continue } select { case <-ctx.Done(): return case output <- record: } } } }() return output } // Find the last USN record of the file. func getLastUSN(ctx context.Context, ntfs_ctx *NTFSContext) (record *USN_RECORD, err error) { mft_id, attr_id, attr_name, err := getUSNStream(ntfs_ctx) if err != nil { return nil, err } mft_entry, err := ntfs_ctx.GetMFT(mft_id) if err != nil { return nil, err } data, err := OpenStream(ntfs_ctx, mft_entry, 128, attr_id, attr_name) if err != nil { return nil, err } // Get the last range ranges := []Range{} for _, rng := range data.Ranges() { if !rng.IsSparse { ranges = append(ranges, rng) } } if len(ranges) == 0 { return nil, errors.New("No ranges found!") } last_range := ranges[len(ranges)-1] var result *USN_RECORD DebugPrint("Staring to parse USN in offset for seek %v\n", last_range.Offset) count := 0 for record := range ParseUSN(ctx, ntfs_ctx, last_range.Offset) { result = record count++ } DebugPrint("Parsed %v USN records\n", count) if result == nil { return nil, errors.New("No ranges found!") } return result, nil } func WatchUSN(ctx context.Context, ntfs_ctx *NTFSContext, period int) chan *USN_RECORD { output := make(chan *USN_RECORD) // Default 30 second watch frequency. if period == 0 { period = 30 } go func() { defer close(output) start_offset := int64(0) for { usn, err := getLastUSN(ctx, ntfs_ctx) if err == nil && usn != nil { start_offset = usn.Offset break } // Keep waiting here until we are able to get the last USN entry. select { case <-ctx.Done(): return case <-time.After(time.Duration(period) * time.Second): } } for { count := 0 DebugPrint("Checking usn from %#08x\n", start_offset) // Purge all caching in the context before we read it so // we always get fresh data. ntfs_ctx.Purge() for record := range ParseUSN(ctx, ntfs_ctx, start_offset) { if record.Offset > start_offset { select { case <-ctx.Done(): return case output <- record: count++ } start_offset = record.Offset } } DebugPrint("Emitted %v events\n", count) select { case <-ctx.Done(): return case <-time.After(time.Second * time.Duration(period)): } } }() return output } <file_sep>/parser/attribute.go package parser import ( "bytes" "encoding/binary" "encoding/hex" "errors" "fmt" "io" "strings" ) type Range struct { // In bytes Offset, Length int64 IsSparse bool } type RangeReaderAt interface { io.ReaderAt Ranges() []Range } type LimitedReader struct { RangeReaderAt N int64 } func (self LimitedReader) ReadAt(buff []byte, off int64) (int, error) { n, err := self.RangeReaderAt.ReadAt(buff, off) if off+int64(n) > self.N { n = int(self.N - off) } return n, err } // Returns the data stream in this attribute. NOTE: A normal file may // consist of multiple separate data streams (VCNs). To read a file // you will need to call OpenStream() below. func (self *NTFS_ATTRIBUTE) Data(ntfs *NTFSContext) io.ReaderAt { if self.Resident().Name == "RESIDENT" { buf := make([]byte, CapUint32(self.Content_size(), 16*1024)) n, _ := self.Reader.ReadAt( buf, self.Offset+int64(self.Content_offset())) buf = buf[:n] return bytes.NewReader(buf) } return &RangeReader{ runs: joinAllVCNs(ntfs, []*NTFS_ATTRIBUTE{self}), } } func (self *NTFS_ATTRIBUTE) Name() string { length := int64(self.name_length()) * 2 result := ParseUTF16String(self.Reader, self.Offset+int64(self.name_offset()), CapInt64(length, MAX_ATTR_NAME_LENGTH)) return result } func (self *NTFS_ATTRIBUTE) IsResident() bool { return self.Resident().Value == 0 } func (self *NTFS_ATTRIBUTE) DataSize() int64 { if self.Resident().Name == "RESIDENT" { return int64(self.Content_size()) } return int64(self.Actual_size()) } func (self *NTFS_ATTRIBUTE) PrintStats(ntfs *NTFSContext) string { result := []string{} if self.Resident().Name == "RESIDENT" { obj := self.Profile.NTFS_RESIDENT_ATTRIBUTE(self.Reader, self.Offset) result = append(result, obj.DebugString()) } else { result = append(result, self.DebugString()) } length := self.Actual_size() b := make([]byte, CapUint64(length, 100)) reader := self.Data(ntfs) n, _ := reader.ReadAt(b, 0) b = b[:n] name := self.Name() if name != "" { result = append(result, "Name: "+name) } if self.Resident().Name != "RESIDENT" { result = append(result, fmt.Sprintf( "Runlist: %v", self.RunList())) } result = append(result, fmt.Sprintf("Data: \n%s", hex.Dump(b))) return strings.Join(result, "\n") } type Run struct { Offset int64 RelativeUrnOffset int64 Length int64 } func (self *NTFS_ATTRIBUTE) RunList() []*Run { var disk_offset int64 result := []*Run{} attr_length := self.Length() runlist_offset := self.Offset + int64(self.Runlist_offset()) /* Make sure we are instantiated on top of a fixed up MFT entry. is_fixed := IsFixed(self.Reader, runlist_offset) if !is_fixed { DlvBreak() } fmt.Printf("RunList on fixed %v\n", IsFixed(self.Reader, runlist_offset)) */ // Read the entire attribute into memory. This makes it easier // to parse the runlist. buffer := make([]byte, CapUint32(attr_length, MAX_RUNLIST_SIZE)) n, _ := self.Reader.ReadAt(buffer, runlist_offset) buffer = buffer[:n] length_buffer := make([]byte, 8) offset_buffer := make([]byte, 8) for offset := 0; offset < len(buffer); { // Consume the first byte off the stream. idx := buffer[offset] if idx == 0 { break } length_size := int(idx & 0xF) run_offset_size := int(idx >> 4) offset += 1 // Pad out to 8 bytes for i := 0; i < 8; i++ { if i < length_size { length_buffer[i] = buffer[offset] offset++ } else { length_buffer[i] = 0 } } // Sign extend if the last byte is larger than 0x80. var sign byte = 0x00 for i := 0; i < 8; i++ { if i == run_offset_size-1 && buffer[offset]&0x80 != 0 { sign = 0xFF } if i < run_offset_size { offset_buffer[i] = buffer[offset] offset++ } else { offset_buffer[i] = sign } } relative_run_offset := int64( binary.LittleEndian.Uint64(offset_buffer)) run_length := int64(binary.LittleEndian.Uint64( length_buffer)) disk_offset += relative_run_offset result = append(result, &Run{ Offset: disk_offset, RelativeUrnOffset: relative_run_offset, Length: run_length, }) } return result } // A reader mapping from file space to target space. A ReadAt in file // space will be mapped to a ReadAt in target space. type MappedReader struct { FileOffset int64 // Address in the file this range begins TargetOffset int64 // Address in the target reader the range is mapped to. Length int64 // Length of mapping. ClusterSize int64 CompressedLength int64 // For compressed readers, we need to decompress on read. IsSparse bool Reader io.ReaderAt } func (self *MappedReader) IsFixed(offset int64) bool { return IsFixed(self.Reader, offset- self.FileOffset*self.ClusterSize+ self.TargetOffset*self.ClusterSize) } func (self *MappedReader) VtoP(offset int64) int64 { return VtoP(self.Reader, offset- self.FileOffset*self.ClusterSize+ self.TargetOffset*self.ClusterSize) } func (self *MappedReader) ReadAt(buff []byte, off int64) (int, error) { // Figure out where to read from in target space. buff_offset := off - self.FileOffset // How much is actually available to read to_read := self.FileOffset + self.Length - off if to_read > int64(len(buff)) { to_read = int64(len(buff)) } if to_read < 0 { return 0, io.EOF } return self.Reader.ReadAt(buff[:to_read], buff_offset) } func (self *MappedReader) DebugString() string { return fmt.Sprintf("Mapping %v -> %v (length %v) with %T\n%v", self.FileOffset*self.ClusterSize, self.Length*self.ClusterSize+self.FileOffset*self.ClusterSize, self.Length*self.ClusterSize, self.Reader, _DebugString(self.Reader, " ")) } // Trim the delegate ranges to our own mapping length. func (self *MappedReader) Ranges() []Range { result := []Range{} offset := self.FileOffset * self.ClusterSize end_offset := offset + self.Length*self.ClusterSize for _, run := range self._Ranges() { if run.Offset > offset { result = append(result, Range{ Offset: offset, Length: run.Offset - offset, IsSparse: true, }) offset = run.Offset } if run.Offset+run.Length > end_offset { result = append(result, Range{ Offset: offset, Length: end_offset - run.Offset, IsSparse: run.IsSparse, }) return result } result = append(result, run) offset += run.Length } if end_offset > offset { // Pad to the end of our mapped range. result = append(result, Range{ Offset: offset, Length: end_offset - offset, IsSparse: true, }) } return result } func (self *MappedReader) _Ranges() []Range { // If the delegate can tell us more about its ranges then pass // it on otherwise we consider the entire run a single range. delegate, ok := self.Reader.(RangeReaderAt) if ok { result := []Range{} for _, rng := range delegate.Ranges() { rng.Offset += self.FileOffset * self.ClusterSize result = append(result, rng) } return result } // Ranges are given in bytes. return []Range{Range{ Offset: self.FileOffset * self.ClusterSize, Length: self.Length * self.ClusterSize, IsSparse: self.IsSparse, }} } func (self *MappedReader) Decompress(reader io.ReaderAt, cluster_size int64) ([]byte, error) { DebugPrint("Decompress %v\n", self) compressed := make([]byte, CapInt64(self.CompressedLength*cluster_size, MAX_DECOMPRESSED_FILE)) n, err := reader.ReadAt(compressed, self.TargetOffset*cluster_size) if err != nil && err != io.EOF { return compressed, err } compressed = compressed[:n] debugLZNT1Decompress("Reading compression unit at cluster %d length %d\n", self.TargetOffset, self.CompressedLength) decompressed, err := LZNT1Decompress(compressed) return decompressed, err } // An io.ReaderAt which works off a sequence of runs. Each run is a // mapping between filespace to another reader at a specific offset in // the file address space. type RangeReader struct { runs []*MappedReader } // Combine the ranges from all the Mapped readers. func (self *RangeReader) Ranges() []Range { result := make([]Range, 0, len(self.runs)) for _, run := range self.runs { if run.Length > 0 { result = append(result, run.Ranges()...) } } return result } func (self *RangeReader) DebugString() string { result := fmt.Sprintf("RangeReader with %v runs:\n", len(self.runs)) for idx, run := range self.runs { result += fmt.Sprintf( "Run %v (%T):\n%v\n", idx, run, _DebugString(run, " ")) } return result } func NewUncompressedRangeReader( runs []*Run, cluster_size int64, disk_reader io.ReaderAt, is_sparse bool) *RangeReader { result := &RangeReader{} var file_offset int64 for idx := 0; idx < len(runs); idx++ { run := runs[idx] // Ignore this run since it has no length. if run.Length == 0 { continue } reader_run := &MappedReader{ FileOffset: file_offset, TargetOffset: run.Offset, // Offset of run on disk // Take up the entire compression unit Length: run.Length, ClusterSize: cluster_size, Reader: disk_reader, } // If the run is sparse we make it read from the null // reader. if is_sparse && run.RelativeUrnOffset == 0 { reader_run.IsSparse = true reader_run.Reader = &NullReader{} } result.runs = append(result.runs, reader_run) file_offset += reader_run.Length } return result } func NewCompressedRangeReader( runs []*Run, cluster_size int64, disk_reader io.ReaderAt, compression_unit_size int64) *RangeReader { return &RangeReader{ runs: consumeRuns(runs, cluster_size, disk_reader, compression_unit_size), } } // A compression unit is the basic compression size. The compression // unit may consist of multiple runs that provide the compressed data // but the uncompressed size is always a compression size (normally 16 // clusters). // Compressed runs consist of sequences of real runs followed by // sparse runs that both represent a compressed run. For example: // Disk Offset 7215396 RelativeUrnOffset 528 (Length 10) // Disk Offset 7215396 RelativeUrnOffset 0 (Length 6) // Alternative there may be multiple runs that add up to a compression // size. // // Disk Offset 2769964 RelativeUrnOffset 10 (Length 1) // Disk Offset 1391033 RelativeUrnOffset -1378931 (Length 8) // Disk Offset 1391033 RelativeUrnOffset 0 (Length 7) // consumeRuns consumes whole compression units from the runs and // combines those runs into a single compressed run. func consumeRuns(runs []*Run, cluster_size int64, disk_reader io.ReaderAt, compression_unit_size int64) []*MappedReader { var file_offset int64 result := []*MappedReader{} for idx := 0; idx < len(runs); idx++ { run := runs[idx] // Ignore this run since it has no length. if run.Length == 0 { continue } // Only one run left - it can not be compressed but may be sparse. if idx+1 >= len(runs) { reader_run := &MappedReader{ FileOffset: file_offset, TargetOffset: run.Offset, // Offset of run on disk // Take up the entire compression unit Length: run.Length, ClusterSize: cluster_size, IsSparse: run.RelativeUrnOffset == 0, Reader: disk_reader, } // Sparse runs read from the null reader. if reader_run.IsSparse { reader_run.Reader = &NullReader{} } result = append(result, reader_run) file_offset += reader_run.Length continue } // Break up a run larger than compression size into a regular run // and a potentially compressed run. if run.Length >= compression_unit_size { // Insert a run which is whole compression_unit_size // as large as possible. new_run := &MappedReader{ FileOffset: file_offset, TargetOffset: run.Offset, // Offset of run on disk Length: run.Length - run.Length%compression_unit_size, ClusterSize: cluster_size, Reader: disk_reader, } // If the run is sparse we make it read from the null // reader. if run.RelativeUrnOffset == 0 { new_run.IsSparse = true new_run.Reader = &NullReader{} } result = append(result, new_run) file_offset += new_run.Length // Adjust the size of the next run. run.Offset = new_run.TargetOffset + new_run.Length run.Length = run.Length - new_run.Length // Reconsider this run again. idx-- continue } // Gather runs into a compression unit compression_unit := []*Run{} total_size := int64(0) total_compression_unit_length := int64(0) last_run_is_sparse := false for i := idx; i < len(runs); i++ { run := runs[i] if run.RelativeUrnOffset != 0 { compression_unit = append(compression_unit, run) total_compression_unit_length += run.Length } else { last_run_is_sparse = true } total_size += run.Length if total_size >= compression_unit_size { break } } debugLZNT1Decompress("total_size %v, Runs %v, last_run_is_sparse %v\n", total_size, compression_unit, last_run_is_sparse) for idx, c := range compression_unit { debugLZNT1Decompress("compression_unit %d: %v\n", idx, c) } if last_run_is_sparse && total_size == compression_unit_size { // Insert a compression run. new_run := &MappedReader{ FileOffset: file_offset, TargetOffset: run.Offset, // Offset of run on disk // Take up the entire compression unit Length: compression_unit_size, CompressedLength: run.Length, ClusterSize: cluster_size, IsSparse: false, Reader: disk_reader, } result = append(result, new_run) file_offset += new_run.Length if len(compression_unit) > 1 { // Create new mappings for the compression_unit new_run.CompressedLength = total_compression_unit_length new_run.TargetOffset = 0 ranged_reader := &RangeReader{} new_run.Reader = ranged_reader offset := int64(0) for _, r := range compression_unit { ranged_reader.runs = append( ranged_reader.runs, &MappedReader{ FileOffset: offset, TargetOffset: r.Offset, Length: r.Length, CompressedLength: 0, ClusterSize: cluster_size, IsSparse: false, Reader: disk_reader, }) offset += r.Length } } } idx += len(compression_unit) } return result } func (self *RangeReader) readFromARun( run_idx int, buf []byte, run_offset int) (int, error) { // Printf("readFromARun %v\n", self.runs[run_idx]) run := self.runs[run_idx] target_offset := run.TargetOffset * run.ClusterSize is_compressed := run.CompressedLength > 0 if is_compressed { decompressed, err := run.Decompress(run.Reader, run.ClusterSize) if err != nil { return 0, err } DebugPrint("Decompressed %d from %v\n", len(decompressed), run) i := 0 for { if run_offset >= len(decompressed) || i >= len(buf) { return i, nil } buf[i] = decompressed[run_offset] run_offset++ i++ } } else { to_read := run.Length*run.ClusterSize - int64(run_offset) if int64(len(buf)) < to_read { to_read = int64(len(buf)) } // Run contains data - read it // into the buffer. n, err := run.Reader.ReadAt( buf[:to_read], target_offset+int64(run_offset)) return n, err } } func (self *RangeReader) IsFixed(offset int64) bool { for j := 0; j < len(self.runs); j++ { run := self.runs[j] // Start of run in bytes in file address space run_file_offset := run.FileOffset * run.ClusterSize run_length := run.Length * run.ClusterSize // End of run in bytes in file address space. run_end_file_offset := run_file_offset + run_length // This run can provide us with some data. if run_file_offset <= offset && offset < run_end_file_offset { run_offset := offset - run_file_offset return IsFixed(run, run_offset) } } return false } func (self *RangeReader) VtoP(offset int64) int64 { for j := 0; j < len(self.runs); j++ { run := self.runs[j] // Start of run in bytes in file address space run_file_offset := run.FileOffset * run.ClusterSize run_length := run.Length * run.ClusterSize // End of run in bytes in file address space. run_end_file_offset := run_file_offset + run_length // This run can provide us with some data. if run_file_offset <= offset && offset < run_end_file_offset { // The relative offset within the run. run_offset := offset - run_file_offset return VtoP(run, run_offset) + offset } } return 0 } func (self *RangeReader) ReadAt(buf []byte, file_offset int64) ( int, error) { buf_idx := 0 // Empirically we find this is rarely > 10 so a linear search is // fast enough. run_length := len(self.runs) // Find the run which covers the required offset. for j := 0; j < run_length && buf_idx < len(buf); j++ { run := self.runs[j] // Start of run in bytes in file address space run_file_offset := run.FileOffset * run.ClusterSize run_length := run.Length * run.ClusterSize // End of run in bytes in file address space. run_end_file_offset := run_file_offset + run_length // This run can provide us with some data. if run_file_offset <= file_offset && file_offset < run_end_file_offset { // The relative offset within the run. run_offset := int(file_offset - run_file_offset) n, err := self.readFromARun(j, buf[buf_idx:], run_offset) if err != nil { DebugPrint("Reading offset %v from run %v returned error %v\n", run_offset, self.runs[j].DebugString(), err) return buf_idx, err } if n == 0 { DebugPrint("Reading run %v returned no data\n", self.runs[j]) return buf_idx, io.EOF } buf_idx += n file_offset += int64(n) } } if buf_idx == 0 { return 0, io.EOF } return buf_idx, nil } func (self *FILE_NAME) Name() string { return ParseUTF16String(self.Reader, self.Offset+self.Profile.Off_FILE_NAME_name, CapInt64(int64(self._length_of_name())*2, MAX_ATTR_NAME_LENGTH)) } func (self *INDEX_NODE_HEADER) GetRecords(ntfs *NTFSContext) []*INDEX_RECORD_ENTRY { result := []*INDEX_RECORD_ENTRY{} end := int64(self.Offset_to_end_index_entry()) + self.Offset start := int64(self.Offset_to_index_entry()) + self.Offset // Need to fit the last entry in - it should be at least size of FILE_NAME dummy_record := self.Profile.FILE_NAME(self.Reader, 0) for i := start; i+int64(dummy_record.Size()) < end; { record := self.Profile.INDEX_RECORD_ENTRY(self.Reader, i) result = append(result, record) // Records have varied sizes. size_of_record := int64(record.SizeOfIndexEntry()) if size_of_record == 0 { break } i += size_of_record } return result } func (self *ATTRIBUTE_LIST_ENTRY) Attributes( ntfs *NTFSContext, mft_entry *MFT_ENTRY, attr *NTFS_ATTRIBUTE) []*NTFS_ATTRIBUTE { result := []*NTFS_ATTRIBUTE{} attribute_size := attr.DataSize() offset := int64(0) for { attr_list_entry := self.Profile.ATTRIBUTE_LIST_ENTRY( self.Reader, self.Offset+offset) DebugPrint("%v ATTRIBUTE_LIST_ENTRY %v\n", mft_entry.Record_number(), DebugString(attr_list_entry, "")) // The attribute_list_entry points to a different MFT // entry than the one we are working on now. We need // to fetch it from there. mft_ref := attr_list_entry.MftReference() if mft_ref != uint64(mft_entry.Record_number()) { DebugPrint("While working on %v - Fetching from MFT Entry %v\n", mft_entry.Record_number(), mft_ref) attr, err := attr_list_entry.GetAttribute(ntfs) if err != nil { DebugPrint("Error %v\n", err) break } result = append(result, attr) } length := int64(attr_list_entry.Length()) if length <= 0 { break } offset += length if offset >= attribute_size { break } } return result } func (self *ATTRIBUTE_LIST_ENTRY) GetAttribute( ntfs *NTFSContext) (*NTFS_ATTRIBUTE, error) { mytype := uint64(self.Type()) myid := self.Attribute_id() mft, err := ntfs.GetMFT(int64(self.MftReference())) if err != nil { return nil, err } res, err := mft.GetDirectAttribute(ntfs, mytype, uint16(myid)) if err != nil { DebugPrint("MFT %v not found in target\n", mft.Record_number()) } else { DebugPrint("Found %v\n", DebugString(res, " ")) } return res, err } // The STANDARD_INDEX_HEADER has a second layer of fixups. func DecodeSTANDARD_INDEX_HEADER( ntfs *NTFSContext, reader io.ReaderAt, offset int64, length int64) ( *STANDARD_INDEX_HEADER, error) { // Read the entire data into a buffer. buffer := make([]byte, CapInt64(length, MAX_IDX_SIZE)) n, err := reader.ReadAt(buffer, offset) if err != nil && err != io.EOF { return nil, err } buffer = buffer[:n] index := ntfs.Profile.STANDARD_INDEX_HEADER(reader, offset) fixup_offset := offset + int64(index.Fixup_offset()) fixup_count := index.Fixup_count() if fixup_count > 0 { fixup_table := make([]byte, fixup_count*2) _, err = reader.ReadAt(fixup_table, fixup_offset) if err != nil && err != io.EOF { return nil, err } fixup_magic := []byte{fixup_table[0], fixup_table[1]} sector_idx := 0 for idx := 2; idx < len(fixup_table); idx += 2 { fixup_offset := (sector_idx+1)*512 - 2 if fixup_offset+1 >= len(buffer) || buffer[fixup_offset] != fixup_magic[0] || buffer[fixup_offset+1] != fixup_magic[1] { return nil, errors.New("Fixup error with MFT") } // Apply the fixup buffer[fixup_offset] = fixup_table[idx] buffer[fixup_offset+1] = fixup_table[idx+1] sector_idx += 1 } } fixed_up_index := ntfs.Profile.STANDARD_INDEX_HEADER( bytes.NewReader(buffer), 0) // Produce a new STANDARD_INDEX_HEADER record with a fixed up // page. return fixed_up_index, nil } type NullReader struct{} func (self *NullReader) ReadAt(buf []byte, offset int64) (int, error) { for i := 0; i < len(buf); i++ { buf[i] = 0 } return len(buf), nil } <file_sep>/bin/mft.go package main import ( "context" "encoding/json" "fmt" "regexp" kingpin "gopkg.in/alecthomas/kingpin.v2" "www.velocidex.com/golang/go-ntfs/parser" ) var ( mft_command = app.Command( "mft", "Process a raw $MFT file.") mft_command_file_arg = mft_command.Flag( "file", "The $MFT file to process", ).File() mft_command_image_arg = mft_command.Flag( "image", "An image containing an $MFT", ).File() mft_command_filename_filter = mft_command.Flag( "filename_filter", "A regex to filter on filename", ).Default(".").String() ) const ( mft_entry_size int64 = 0x400 ) func doMFTFromFile() { reader, _ := parser.NewPagedReader(*mft_command_file_arg, 1024, 10000) st, err := (*mft_command_file_arg).Stat() kingpin.FatalIfError(err, "Can not open MFT file") for item := range parser.ParseMFTFile(context.Background(), reader, st.Size(), 0x1000, 0x400) { serialized, err := json.MarshalIndent(item, " ", " ") kingpin.FatalIfError(err, "Marshal") fmt.Println(string(serialized)) } } func doMFTFromImage() { filename_filter := regexp.MustCompile(*mft_command_filename_filter) reader, _ := parser.NewPagedReader(*mft_command_image_arg, 1024, 10000) st, err := (*mft_command_image_arg).Stat() kingpin.FatalIfError(err, "Can not open MFT file") ntfs_ctx, err := parser.GetNTFSContext(reader, 0) kingpin.FatalIfError(err, "Can not open filesystem") mft_entry, err := GetMFTEntry(ntfs_ctx, "0") kingpin.FatalIfError(err, "Can not open path") mft_reader, err := parser.OpenStream(ntfs_ctx, mft_entry, uint64(128), uint16(0), "") kingpin.FatalIfError(err, "Can not open stream") for item := range parser.ParseMFTFile(context.Background(), mft_reader, st.Size(), ntfs_ctx.ClusterSize, ntfs_ctx.RecordSize) { if len(filename_filter.FindStringIndex(item.FileName())) == 0 { continue } serialized, err := json.MarshalIndent(item, " ", " ") kingpin.FatalIfError(err, "Marshal") fmt.Println(string(serialized)) } } func init() { command_handlers = append(command_handlers, func(command string) bool { switch command { case "mft": if *mft_command_file_arg != nil { doMFTFromFile() } else if *mft_command_image_arg != nil { doMFTFromImage() } default: return false } return true }) } <file_sep>/parser/options.go package parser const ( DefaultMaxLinks = 0 ) type Options struct { // Include short names in Link analysis IncludeShortNames bool // Max number of links to retrieve MaxLinks int // Maximum directory depth to anlayze for paths. MaxDirectoryDepth int // These path components will be added in front of each link // generated. PrefixComponents []string } func GetDefaultOptions() Options { return Options{ IncludeShortNames: false, MaxLinks: 20, MaxDirectoryDepth: 20, } } <file_sep>/bin/utils.go package main import ( "www.velocidex.com/golang/go-ntfs/parser" ) func GetMFTEntry(ntfs_ctx *parser.NTFSContext, filename string) (*parser.MFT_ENTRY, error) { mft_idx, _, _, _, err := parser.ParseMFTId(filename) if err == nil { // Access by mft id (e.g. 1234-128-6) return ntfs_ctx.GetMFT(mft_idx) } else { // Access by filename. dir, err := ntfs_ctx.GetMFT(5) if err != nil { return nil, err } return dir.Open(ntfs_ctx, filename) } } <file_sep>/go.mod module www.velocidex.com/golang/go-ntfs require ( github.com/alecthomas/assert v1.0.0 github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc github.com/olekukonko/tablewriter v0.0.5 github.com/sebdah/goldie v1.0.0 github.com/sebdah/goldie/v2 v2.5.3 github.com/stretchr/testify v1.8.1 gopkg.in/alecthomas/kingpin.v2 v2.2.6 ) require ( github.com/alecthomas/colour v0.1.0 // indirect github.com/alecthomas/repr v0.1.1 // indirect github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/mattn/go-isatty v0.0.16 // indirect github.com/mattn/go-runewidth v0.0.14 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rivo/uniseg v0.4.2 // indirect github.com/sergi/go-diff v1.2.0 // indirect golang.org/x/sys v0.1.0 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) // replace gopkg.in/alecthomas/kingpin.v2 => /home/mic/projects/kingpin go 1.18 <file_sep>/bin/cat.go package main import ( "io" "os" kingpin "gopkg.in/alecthomas/kingpin.v2" "www.velocidex.com/golang/go-ntfs/parser" ) var ( cat_command = app.Command( "cat", "Dump file stream.") cat_command_file_arg = cat_command.Arg( "file", "The image file to inspect", ).Required().File() cat_command_arg = cat_command.Arg( "path", "The path to extract to an MFT entry.", ).Default("/").String() cat_command_offset = cat_command.Flag( "offset", "The offset to start reading.", ).Int64() cat_command_image_offset = cat_command.Flag( "image_offset", "The offset in the image to use.", ).Int64() cat_command_output_file = cat_command.Flag( "out", "Write to this file", ).OpenFile(os.O_RDWR|os.O_CREATE|os.O_TRUNC, os.FileMode(0666)) ) func doCAT() { reader, _ := parser.NewPagedReader(&parser.OffsetReader{ Offset: *cat_command_image_offset, Reader: getReader(*cat_command_file_arg), }, 1024, 10000) ntfs_ctx, err := parser.GetNTFSContext(reader, 0) kingpin.FatalIfError(err, "Can not open filesystem") mft_entry, err := GetMFTEntry(ntfs_ctx, *cat_command_arg) kingpin.FatalIfError(err, "Can not open path") var ads_name string = "" // Access by mft id (e.g. 1234-128-6) _, attr_type, attr_id, ads_name, err := parser.ParseMFTId(*cat_command_arg) if err != nil { attr_type = 128 // $DATA } data, err := parser.OpenStream(ntfs_ctx, mft_entry, uint64(attr_type), uint16(attr_id), ads_name) kingpin.FatalIfError(err, "Can not open stream") var fd io.WriteCloser = os.Stdout if *cat_command_output_file != nil { fd = *cat_command_output_file defer fd.Close() } buf := make([]byte, 1024*1024*10) offset := *cat_command_offset for { n, _ := data.ReadAt(buf, offset) if n == 0 { return } fd.Write(buf[:n]) offset += int64(n) } } func init() { command_handlers = append(command_handlers, func(command string) bool { switch command { case "cat": doCAT() default: return false } return true }) } <file_sep>/parser/model.go package parser import ( "strings" "time" ) // This file defines a model for MFT entry. type TimeStamps struct { CreateTime time.Time FileModifiedTime time.Time MFTModifiedTime time.Time AccessedTime time.Time } type FilenameInfo struct { Times TimeStamps Type string Name string ParentEntryNumber uint64 ParentSequenceNumber uint16 } type Attribute struct { Type string TypeId uint64 Id uint64 Inode string Size int64 Name string } // Describe a single MFT entry. type NTFSFileInformation struct { FullPath string MFTID int64 SequenceNumber uint16 Size int64 Allocated bool IsDir bool SI_Times *TimeStamps // If multiple filenames are given, we list them here. Filenames []*FilenameInfo Attributes []*Attribute Hardlinks []string } func ModelMFTEntry(ntfs *NTFSContext, mft_entry *MFT_ENTRY) (*NTFSFileInformation, error) { full_path := GetFullPath(ntfs, mft_entry) mft_id := mft_entry.Record_number() result := &NTFSFileInformation{ FullPath: full_path, MFTID: int64(mft_id), SequenceNumber: mft_entry.Sequence_value(), Allocated: mft_entry.Flags().IsSet("ALLOCATED"), IsDir: mft_entry.Flags().IsSet("DIRECTORY"), } si, err := mft_entry.StandardInformation(ntfs) if err == nil { result.SI_Times = &TimeStamps{ CreateTime: si.Create_time().Time, FileModifiedTime: si.File_altered_time().Time, MFTModifiedTime: si.Mft_altered_time().Time, AccessedTime: si.File_accessed_time().Time, } } for _, filename := range mft_entry.FileName(ntfs) { result.Filenames = append(result.Filenames, &FilenameInfo{ Times: TimeStamps{ CreateTime: filename.Created().Time, FileModifiedTime: filename.File_modified().Time, MFTModifiedTime: filename.Mft_modified().Time, AccessedTime: filename.File_accessed().Time, }, ParentEntryNumber: filename.MftReference(), ParentSequenceNumber: filename.Seq_num(), Type: filename.NameType().Name, Name: filename.Name(), }) } inode_formatter := InodeFormatter{} for _, attr := range mft_entry.EnumerateAttributes(ntfs) { attr_type := attr.Type() attr_id := attr.Attribute_id() if attr_type.Value == ATTR_TYPE_DATA && result.Size == 0 { result.Size = attr.DataSize() } // Only show the first VCN - additional VCN are just // part of the original stream. if !attr.IsResident() && attr.Runlist_vcn_start() != 0 { continue } name := attr.Name() result.Attributes = append(result.Attributes, &Attribute{ Type: attr_type.Name, TypeId: attr_type.Value, Inode: inode_formatter.Inode(mft_id, attr_type.Value, attr_id, name), Size: attr.DataSize(), Id: uint64(attr_id), Name: name, }) } for _, l := range GetHardLinks(ntfs, uint64(mft_id), DefaultMaxLinks) { result.Hardlinks = append(result.Hardlinks, strings.Join(l, "\\")) } return result, nil } <file_sep>/parser/inode.go package parser import "fmt" type InodeFormatter struct { attr_ids []uint32 } // Format an inode unambigously func (self *InodeFormatter) Inode(mft_id uint32, attr_type_id uint64, attr_id uint16, name string) string { inode := fmt.Sprintf("%d-%d-%d", mft_id, attr_type_id, attr_id) needle := uint32(attr_id)<<16 + uint32(attr_type_id) if inSliceUint32(needle, self.attr_ids) { // Only include the name if it is necessary (i.e. there is // another stream of the same type-id). if name != "" { inode += ":" + name } } else { // This is O(n) but there should not be too many items. self.attr_ids = append(self.attr_ids, needle) } return inode } func inSliceUint32(needle uint32, haystack []uint32) bool { for _, i := range haystack { if i == needle { return true } } return false } <file_sep>/bin/runs.go package main import ( "fmt" "io" kingpin "gopkg.in/alecthomas/kingpin.v2" "www.velocidex.com/golang/go-ntfs/parser" ) var ( runs_command = app.Command( "runs", "Display sparse runs.") record_directory = app.Flag( "record", "Path to read/write recorded data"). Default("").String() runs_command_file_arg = runs_command.Arg( "file", "The image file to inspect", ).Required().File() runs_command_image_offset = runs_command.Flag( "image_offset", "The offset in the image to use.", ).Int64() runs_command_raw_runs = runs_command.Flag( "raw_runs", "Also show raw runs.", ).Bool() runs_command_arg = runs_command.Arg( "mft_id", "An inode in MFT notation e.g. 43-128-0.", ).Required().String() ) func getReader(reader io.ReaderAt) io.ReaderAt { if *record_directory == "" { return reader } // Create a recorder parser.Printf("Will record to dir %v\n", *record_directory) return parser.NewRecorder(*record_directory, reader) } func doRuns() { reader, _ := parser.NewPagedReader(&parser.OffsetReader{ Offset: *runs_command_image_offset, Reader: getReader(*runs_command_file_arg), }, 1024, 10000) ntfs_ctx, err := parser.GetNTFSContext(reader, 0) kingpin.FatalIfError(err, "Can not open filesystem") mft_entry, err := GetMFTEntry(ntfs_ctx, *runs_command_arg) kingpin.FatalIfError(err, "Can not open path") // Access by mft id (e.g. 1234-128-6) or filepath (e.g. C:\Folder\Hello.txt:hiddenstream) _, attr_type, attr_id, ads_name, err := parser.ParseMFTId(*runs_command_arg) if err != nil { attr_type = 128 // $DATA } if *runs_command_raw_runs { vcns := parser.GetAllVCNs(ntfs_ctx, mft_entry, uint64(attr_type), uint16(attr_id), ads_name) for _, vcn := range vcns { fmt.Println(vcn.DebugString()) vcn_runlist := vcn.RunList() parser.DebugRawRuns(vcn_runlist) } } data, err := parser.OpenStream(ntfs_ctx, mft_entry, uint64(attr_type), uint16(attr_id), ads_name) kingpin.FatalIfError(err, "Can not open stream") for idx, r := range parser.DebugRuns(data, 0) { fmt.Printf("%d %v\n", idx, r) } } func init() { command_handlers = append(command_handlers, func(command string) bool { switch command { case "runs": doRuns() default: return false } return true }) } <file_sep>/parser/guids.go package parser import "fmt" func (self GUID) AsString() string { data4 := self.Data4() return fmt.Sprintf( "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", self.Data1(), self.Data2(), self.Data3(), data4[0], data4[1], data4[2], data4[3], data4[4], data4[5], data4[6], data4[7]) } <file_sep>/parser/reader_test.go package parser import ( "bytes" "testing" "github.com/alecthomas/assert" ) func TestReader(t *testing.T) { r, _ := NewPagedReader( bytes.NewReader([]byte("abcd")), 3 /* pagesize */, 100 /* cache_size */) // Read 1 byte from the end of the buffer. buf := make([]byte, 1) c, err := r.ReadAt(buf, 3) assert.NoError(t, err) assert.Equal(t, c, 1) assert.Equal(t, buf, []byte{0x64}) // Read past end (3 byte buffer from offset 3). buf = make([]byte, 3) c, err = r.ReadAt(buf, 3) assert.NoError(t, err) assert.Equal(t, c, 3) assert.Equal(t, buf, []byte{0x64, 0x00, 0x00}) } func TestRangeReader(t *testing.T) { reader := RangeReader{ runs: []*MappedReader{&MappedReader{ FileOffset: 10, Length: 5, ClusterSize: 1, // Reader is actually longer than the mapping region. Reader: bytes.NewReader([]byte("0123456789")), }}, } buf := make([]byte, 100) // Should read from 12 to 15 *only* because this is the mapped range. c, err := reader.ReadAt(buf, 12) assert.NoError(t, err) assert.Equal(t, c, 3) assert.Equal(t, string(buf[:c]), "234") } func TestMappedReader(t *testing.T) { reader := MappedReader{ FileOffset: 10, Length: 5, ClusterSize: 1, // Reader is actually longer than the mapping region. Reader: bytes.NewReader([]byte("0123456789")), } buf := make([]byte, 100) // Should read from 12 to 15 *only* because this is the mapped range. c, err := reader.ReadAt(buf, 12) assert.NoError(t, err) assert.Equal(t, c, 3) assert.Equal(t, string(buf[:c]), "234") // Very short buffer buf = make([]byte, 2) // Should read from 12 to 14 *only* because this is the mapped range. c, err = reader.ReadAt(buf, 12) assert.NoError(t, err) assert.Equal(t, c, 2) assert.Equal(t, string(buf[:c]), "23") } <file_sep>/parser/reader.go // This reader is needed for reading raw windows devices, such as // \\.\c: On windows, such devices may only be read using sector // alignment in whole sector numbers. This reader implements page // aligned reading and adds pages to an LRU cache to make accessing // various field members faster. package parser import ( "fmt" "io" "sync" ) type PagedReader struct { mu sync.Mutex reader io.ReaderAt pagesize int64 lru *LRU Hits int64 Miss int64 } func (self *PagedReader) IsFixed(offset int64) bool { return false } func (self *PagedReader) VtoP(offset int64) int64 { return offset } func (self *PagedReader) ReadAt(buf []byte, offset int64) (int, error) { self.mu.Lock() defer self.mu.Unlock() buf_idx := 0 for { // How much is left in this page to read? to_read := int(self.pagesize - offset%self.pagesize) // How much do we need to read into the buffer? if to_read > len(buf)-buf_idx { to_read = len(buf) - buf_idx } // Are we done? if to_read == 0 { return buf_idx, nil } var page_buf []byte page := offset - offset%self.pagesize cached_page_buf, pres := self.lru.Get(int(page)) if !pres { self.Miss += 1 DebugPrint("Cache miss for %x (%x) (%d)\n", page, self.pagesize, self.lru.Len()) // Read this page into memory. page_buf = make([]byte, self.pagesize) n, err := self.reader.ReadAt(page_buf, page) if err != nil && err != io.EOF { return buf_idx, err } // Only cache full pages. if n == int(self.pagesize) { self.lru.Add(int(page), page_buf) } } else { self.Hits += 1 page_buf = cached_page_buf.([]byte) } // Copy the relevant data from the page. page_offset := int(offset % self.pagesize) copy(buf[buf_idx:buf_idx+to_read], page_buf[page_offset:page_offset+to_read]) offset += int64(to_read) buf_idx += to_read if debug && (self.Hits+self.Miss)%10000 == 0 { fmt.Printf("PageCache hit %v miss %v (%v)\n", self.Hits, self.Miss, float64(self.Hits)/float64(self.Miss)) } } } func (self *PagedReader) Flush() { self.lru.Purge() flusher, ok := self.reader.(Flusher) if ok { flusher.Flush() } } func NewPagedReader(reader io.ReaderAt, pagesize int64, cache_size int) (*PagedReader, error) { DebugPrint("Creating cache of size %v\n", cache_size) // By default 10mb cache. cache, err := NewLRU(cache_size, nil, "NewPagedReader") if err != nil { return nil, err } return &PagedReader{ reader: reader, pagesize: pagesize, lru: cache, }, nil } // Invalidate the disk cache type Flusher interface { Flush() } <file_sep>/parser/context.go package parser import ( "errors" "fmt" "io" "sync" ) type NTFSContext struct { // The reader over the disk DiskReader io.ReaderAt // The reader over the MFT MFTReader io.ReaderAt Boot *NTFS_BOOT_SECTOR //RootMFT *MFT_ENTRY Profile *NTFSProfile ClusterSize int64 mu sync.Mutex // Analysis options can be set with SetOptions() options Options RecordSize int64 // Map MFTID to *MFT_ENTRY mft_entry_lru *LRU mft_summary_cache *MFTEntryCache } func newNTFSContext(image io.ReaderAt, name string) *NTFSContext { STATS.Inc_NTFSContext() mft_cache, _ := NewLRU(1000, nil, name) ntfs := &NTFSContext{ DiskReader: image, options: GetDefaultOptions(), Profile: NewNTFSProfile(), mft_entry_lru: mft_cache, } ntfs.mft_summary_cache = NewMFTEntryCache(ntfs) return ntfs } func (self *NTFSContext) Copy() *NTFSContext { self.mu.Lock() defer self.mu.Unlock() return &NTFSContext{ DiskReader: self.DiskReader, MFTReader: self.MFTReader, Boot: self.Boot, //RootMFT: self.RootMFT, Profile: self.Profile, ClusterSize: self.ClusterSize, options: self.options, RecordSize: self.RecordSize, mft_entry_lru: self.mft_entry_lru, mft_summary_cache: self.mft_summary_cache, } } func (self *NTFSContext) SetOptions(options Options) { self.mu.Lock() defer self.mu.Unlock() self.options = options } func (self *NTFSContext) Close() { if debug { fmt.Printf(STATS.DebugString()) fmt.Println(self.mft_entry_lru.DebugString()) } self.Purge() } func (self *NTFSContext) Purge() { self.mft_entry_lru.Purge() // Try to flush our reader if possible flusher, ok := self.DiskReader.(Flusher) if ok { flusher.Flush() } } func (self *NTFSContext) GetRecordSize() int64 { self.mu.Lock() defer self.mu.Unlock() if self.RecordSize == 0 { self.RecordSize = self.Boot.RecordSize() } return self.RecordSize } func (self *NTFSContext) GetMFTSummary(id uint64) (*MFTEntrySummary, error) { return self.mft_summary_cache.GetSummary(id) } func (self *NTFSContext) GetMFT(id int64) (*MFT_ENTRY, error) { // Check the cache first cached_any, pres := self.mft_entry_lru.Get(int(id)) if pres { return cached_any.(*MFT_ENTRY), nil } // The root MFT is read from the $MFT stream so we can just // reuse its reader. if self.MFTReader == nil { return nil, errors.New("No RootMFT known.") } disk_mft := self.Profile.MFT_ENTRY( self.MFTReader, self.GetRecordSize()*id) // Fixup the entry. mft_reader, err := FixUpDiskMFTEntry(disk_mft) if err != nil { return nil, err } mft_entry := self.Profile.MFT_ENTRY(mft_reader, 0) self.mft_entry_lru.Add(int(id), mft_entry) return mft_entry, nil } <file_sep>/parser/recorder.go package parser import ( "fmt" "io" "os" ) type Recorder struct { path string // Delegate reader reader io.ReaderAt } func (self *Recorder) ReadAt(buf []byte, offset int64) (int, error) { // Check if the read comes from the cache directory. full_path := fmt.Sprintf("%s/%#08x.bin", self.path, offset) fd, err := os.Open(full_path) if err != nil { // Cache file does not exist - pass the read to the // delegate and cache it for next time. n, err := self.reader.ReadAt(buf, offset) if err == nil || err == io.EOF { fd, err := os.OpenFile(full_path, os.O_RDWR|os.O_CREATE, 0660) if err == nil { fd.Write(buf[:n]) } } return n, err } defer fd.Close() return fd.ReadAt(buf, 0) } func NewRecorder(path string, reader io.ReaderAt) *Recorder { return &Recorder{path: path, reader: reader} } <file_sep>/parser/ntfs_test.go package parser_test import ( "crypto/sha1" "encoding/hex" "encoding/json" "fmt" "os" "strings" "testing" "time" "github.com/davecgh/go-spew/spew" "github.com/sebdah/goldie" "github.com/stretchr/testify/assert" "www.velocidex.com/golang/go-ntfs/parser" ) func split(message string) interface{} { if !strings.Contains(message, "\n") { return message } return strings.Split(message, "\n") } func TestNTFS(t *testing.T) { result := make(map[string]interface{}) assert := assert.New(t) fd, err := os.Open("test_data/test.ntfs.dd") assert.NoError(err, "Unable to open file") ntfs_ctx, err := parser.GetNTFSContext(fd, 0) assert.NoError(err, "Unable to open file") // Open directory by path. root, err := ntfs_ctx.GetMFT(5) assert.NoError(err, "Unable to open file") dir, err := root.Open(ntfs_ctx, "Folder A/Folder B") assert.NoError(err, "Open by path") result["01 Open by path"] = parser.ListDir(ntfs_ctx, dir) result["02 Folder B stat"] = split(dir.DebugString()) result["03 I30"] = parser.ExtractI30List(ntfs_ctx, dir) // Open by mft id mft_idx, attr, id, name, err := parser.ParseMFTId("46-128-5") assert.NoError(err, "ParseMFTId") assert.Equal(mft_idx, int64(46)) assert.Equal(attr, int64(128)) assert.Equal(id, int64(5)) assert.Equal(name, parser.WILDCARD_STREAM_NAME) // Test resident file. buf := make([]byte, 3000000) reader, err := parser.GetDataForPath(ntfs_ctx, "Folder A/Folder B/Hello world text document.txt") assert.NoError(err, "GetDataForPath") n, _ := reader.ReadAt(buf, 0) result["04 Hello world.txt"] = fmt.Sprintf("%v: %s", n, string(buf[:n])) // Test ADS reader, err = parser.GetDataForPath(ntfs_ctx, "Folder A/Folder B/Hello world text document.txt:goodbye.txt") assert.NoError(err, "GetDataForPath ADS") n, _ = reader.ReadAt(buf, 0) result["05 Hello world.txt:goodbye.txt"] = fmt.Sprintf( "%v: %s", n, string(buf[:n])) // Test a compressed file with multiple VCN runs reader, err = parser.GetDataForPath(ntfs_ctx, "ones.bin") assert.NoError(err, "Open compressed ones.bin") n, _ = reader.ReadAt(buf, 0) h := sha1.New() h.Write(buf[:n]) result["06 Compressed ones.bin hash"] = fmt.Sprintf( "%v: %s", n, hex.EncodeToString(h.Sum(nil))) for idx, rng := range reader.Ranges() { result[fmt.Sprintf("07 Compressed ones runs %03d", idx)] = fmt.Sprintf("Range %v-%v sparse %v\n", rng.Offset, rng.Length, rng.IsSparse) } result_json, _ := json.MarshalIndent(result, "", " ") goldie.Assert(t, "TestNTFS", result_json) } // Test the OpenStream API. func TestNTFSOpenStream(t *testing.T) { result := make(map[string]interface{}) assert := assert.New(t) fd, err := os.Open("test_data/test.ntfs.dd") assert.NoError(err, "Unable to open file") ntfs_ctx, err := parser.GetNTFSContext(fd, 0) assert.NoError(err, "Unable to open file") // Open directory by path. root, err := ntfs_ctx.GetMFT(5) assert.NoError(err, "Unable to open file") dir, err := root.Open(ntfs_ctx, "Folder A/Folder B") assert.NoError(err, "Open by path") result["01 Open by path"] = parser.ListDir(ntfs_ctx, dir) result["02 Folder B stat"] = split(dir.DebugString()) result["03 I30"] = parser.ExtractI30List(ntfs_ctx, dir) // Open by mft id mft_idx, attr, id, name, err := parser.ParseMFTId("46-128-5") assert.NoError(err, "ParseMFTId") assert.Equal(mft_idx, int64(46)) assert.Equal(attr, int64(128)) assert.Equal(id, int64(5)) assert.Equal(name, parser.WILDCARD_STREAM_NAME) // Test resident file. mft_entry, err := root.Open(ntfs_ctx, "Folder A/Folder B/Hello world text document.txt") assert.NoError(err, "root.Open") buf := make([]byte, 3000000) reader, err := parser.OpenStream(ntfs_ctx, mft_entry, parser.ATTR_TYPE_DATA, parser.WILDCARD_STREAM_ID, parser.WILDCARD_STREAM_NAME) assert.NoError(err, "GetDataForPath") n, _ := reader.ReadAt(buf, 0) result["04 Hello world.txt"] = fmt.Sprintf("%v: %s", n, string(buf[:n])) // Test ADS reader, err = parser.OpenStream(ntfs_ctx, mft_entry, parser.ATTR_TYPE_DATA, 5, "goodbye.txt") assert.NoError(err, "GetDataForPath") n, _ = reader.ReadAt(buf, 0) result["05 Hello world.txt:goodbye.txt"] = fmt.Sprintf( "%v: %s", n, string(buf[:n])) // Test a compressed file with multiple VCN runs mft_entry, err = root.Open(ntfs_ctx, "ones.bin") reader, err = parser.OpenStream(ntfs_ctx, mft_entry, parser.ATTR_TYPE_DATA, parser.WILDCARD_STREAM_ID, parser.WILDCARD_STREAM_NAME) assert.NoError(err, "Open compressed ones.bin") n, _ = reader.ReadAt(buf, 0) h := sha1.New() h.Write(buf[:n]) result["06 Compressed ones.bin hash"] = fmt.Sprintf( "%v: %s", n, hex.EncodeToString(h.Sum(nil))) for idx, rng := range reader.Ranges() { result[fmt.Sprintf("07 Compressed ones runs %03d", idx)] = fmt.Sprintf("Range %v-%v sparse %v\n", rng.Offset, rng.Length, rng.IsSparse) } result_json, _ := json.MarshalIndent(result, "", " ") goldie.Assert(t, "TestNTFS", result_json) } func init() { time.Local = time.UTC spew.Config.DisablePointerAddresses = true spew.Config.SortKeys = true } <file_sep>/parser/lru.go // Based on // https://github.com/hashicorp/golang-lru/blob/master/simplelru/lru.go // but more optimized for speed: by changing keys to int mapaccess is // much faster. We also added locking to the LRU to make it thread // safe. package parser import ( "container/list" "errors" "fmt" "sync" ) // EvictCallback is used to get a callback when a cache entry is evicted type EvictCallback func(key int, value interface{}) // LRU implements a thread safe fixed size LRU cache type LRU struct { size int evictList *list.List items map[int]*list.Element onEvict EvictCallback mu sync.Mutex name string hits int64 miss int64 total int64 } // entry is used to hold a value in the evictList type entry struct { key int value interface{} } // NewLRU constructs an LRU of the given size func NewLRU(size int, onEvict EvictCallback, name string) (*LRU, error) { if size <= 0 { return nil, errors.New("Must provide a positive size") } c := &LRU{ size: size, evictList: list.New(), items: make(map[int]*list.Element), onEvict: onEvict, name: name, } return c, nil } // Purge is used to completely clear the cache. func (self *LRU) Purge() { self.mu.Lock() defer self.mu.Unlock() for k, v := range self.items { if self.onEvict != nil { self.onEvict(k, v.Value.(*entry).value) } delete(self.items, k) } self.evictList.Init() } // Add adds a value to the cache. Returns true if an eviction occurred. func (self *LRU) Add(key int, value interface{}) (evicted bool) { self.mu.Lock() defer self.mu.Unlock() self.total++ // Check for existing item if ent, ok := self.items[key]; ok { self.evictList.MoveToFront(ent) ent.Value.(*entry).value = value return false } // Add new item ent := &entry{key, value} entry := self.evictList.PushFront(ent) self.items[key] = entry evict := self.evictList.Len() > self.size // Verify size not exceeded if evict { self.removeOldest() } return evict } func (self *LRU) Touch(key int) { self.mu.Lock() defer self.mu.Unlock() if ent, ok := self.items[key]; ok { self.evictList.MoveToFront(ent) } } // Get looks up a key's value from the cache. func (self *LRU) Get(key int) (value interface{}, ok bool) { self.mu.Lock() defer self.mu.Unlock() if ent, ok := self.items[key]; ok { self.evictList.MoveToFront(ent) self.hits++ return ent.Value.(*entry).value, true } self.miss++ return } // Contains checks if a key is in the cache, without updating the recent-ness // or deleting it for being stale. func (self *LRU) Contains(key int) (ok bool) { self.mu.Lock() defer self.mu.Unlock() _, ok = self.items[key] return ok } // Peek returns the key value (or undefined if not found) without updating // the "recently used"-ness of the key. func (self *LRU) Peek(key int) (value interface{}, ok bool) { self.mu.Lock() defer self.mu.Unlock() var ent *list.Element if ent, ok = self.items[key]; ok { return ent.Value.(*entry).value, true } return nil, ok } // Remove removes the provided key from the cache, returning if the // key was contained. func (self *LRU) Remove(key int) (present bool) { self.mu.Lock() defer self.mu.Unlock() if ent, ok := self.items[key]; ok { self.removeElement(ent) return true } return false } // RemoveOldest removes the oldest item from the cache. func (self *LRU) RemoveOldest() (key int, value interface{}, ok bool) { self.mu.Lock() defer self.mu.Unlock() ent := self.evictList.Back() if ent != nil { self.removeElement(ent) kv := ent.Value.(*entry) return kv.key, kv.value, true } return 0, nil, false } // GetOldest returns the oldest entry func (self *LRU) GetOldest() (key int, value interface{}, ok bool) { self.mu.Lock() defer self.mu.Unlock() ent := self.evictList.Back() if ent != nil { kv := ent.Value.(*entry) return kv.key, kv.value, true } return 0, nil, false } // Keys returns a slice of the keys in the cache, from oldest to newest. func (self *LRU) Keys() []int { self.mu.Lock() defer self.mu.Unlock() keys := make([]int, len(self.items)) i := 0 for ent := self.evictList.Back(); ent != nil; ent = ent.Prev() { keys[i] = ent.Value.(*entry).key i++ } return keys } // Len returns the number of items in the cache. func (self *LRU) Len() int { self.mu.Lock() defer self.mu.Unlock() return self.evictList.Len() } func (self *LRU) DebugString() string { self.mu.Lock() defer self.mu.Unlock() return fmt.Sprintf("%s LRU %p hit %d miss %d - total %v (%f)\n", self.name, self, self.hits, self.miss, self.total, float64(self.hits)/float64(self.miss)) } // removeOldest removes the oldest item from the cache. func (self *LRU) removeOldest() { ent := self.evictList.Back() if ent != nil { self.removeElement(ent) } } // removeElement is used to remove a given list element from the cache func (self *LRU) removeElement(e *list.Element) { self.evictList.Remove(e) kv := e.Value.(*entry) delete(self.items, kv.key) if self.onEvict != nil { self.onEvict(kv.key, kv.value) } } <file_sep>/bin/usn.go package main import ( "context" "fmt" "strings" kingpin "gopkg.in/alecthomas/kingpin.v2" "www.velocidex.com/golang/go-ntfs/parser" ) var ( usn_command = app.Command( "usn", "inspect the USN journal.") usn_command_file_arg = usn_command.Arg( "file", "The image file to inspect", ).Required().File() usn_command_watch = usn_command.Flag( "watch", "Watch the USN for changes").Bool() ) const template = ` USN ID: %x @ %x Filename: %s FullPath: %s Timestamp: %v Reason: %s FileAttributes: %s SourceInfo: %s ` func doWatchUSN() { reader, _ := parser.NewPagedReader( getReader(*usn_command_file_arg), 1024, 10000) ntfs_ctx, err := parser.GetNTFSContext(reader, 0) kingpin.FatalIfError(err, "Can not open filesystem") for record := range parser.WatchUSN(context.Background(), ntfs_ctx, 1) { fmt.Printf(template, record.Usn(), record.Offset, record.Filename(), record.FullPath(), record.TimeStamp(), strings.Join(record.Reason(), ", "), strings.Join(record.FileAttributes(), ", "), strings.Join(record.SourceInfo(), ", "), ) } } func doUSN() { if *usn_command_watch { doWatchUSN() return } reader, _ := parser.NewPagedReader( getReader(*usn_command_file_arg), 1024, 10000) ntfs_ctx, err := parser.GetNTFSContext(reader, 0) kingpin.FatalIfError(err, "Can not open filesystem") for record := range parser.ParseUSN(context.Background(), ntfs_ctx, 0) { fmt.Printf(template, record.Usn(), record.Offset, record.Filename(), record.FullPath(), record.TimeStamp(), strings.Join(record.Reason(), ", "), strings.Join(record.FileAttributes(), ", "), strings.Join(record.SourceInfo(), ", "), ) } } func init() { command_handlers = append(command_handlers, func(command string) bool { switch command { case usn_command.FullCommand(): doUSN() default: return false } return true }) } <file_sep>/parser/debug.go package parser import ( "bytes" "encoding/hex" "fmt" "os" "strings" debug_runtime "runtime/debug" "github.com/davecgh/go-spew/spew" ) var ( debug = false LZNT1_debug = false NTFS_DEBUG *bool ) func PrintStack() { debug_runtime.PrintStack() } func Debug(arg interface{}) { spew.Dump(arg) } type Debugger interface { DebugString() string } func DebugString(arg interface{}, indent string) string { debugger, ok := arg.(Debugger) if NTFS_DEBUG != nil && *NTFS_DEBUG && ok { lines := strings.Split(debugger.DebugString(), "\n") for idx, line := range lines { lines[idx] = indent + line } return strings.Join(lines, "\n") } return "" } func _DebugString(arg interface{}, indent string) string { debugger, ok := arg.(Debugger) if ok { lines := strings.Split(debugger.DebugString(), "\n") for idx, line := range lines { lines[idx] = indent + line } return strings.Join(lines, "\n") } return "" } func Printf(fmt_str string, args ...interface{}) { if NTFS_DEBUG != nil && *NTFS_DEBUG { fmt.Printf(fmt_str, args...) } } func LZNT1Printf(fmt_str string, args ...interface{}) { if LZNT1_debug { fmt.Printf(fmt_str, args...) } } // Turns on debugging programmatically func SetDebug() { yes := true NTFS_DEBUG = &yes } func DlvBreak() {} func DebugPrint(fmt_str string, v ...interface{}) { if NTFS_DEBUG == nil { // os.Environ() seems very expensive in Go so we cache // it. for _, x := range os.Environ() { if strings.HasPrefix(x, "NTFS_DEBUG=1") { value := true NTFS_DEBUG = &value break } } } if NTFS_DEBUG == nil { value := false NTFS_DEBUG = &value } if *NTFS_DEBUG { fmt.Printf(fmt_str, v...) } } // Debugging decompression const ( debugLZNT1 = false ) func debugLZNT1Decompress(format string, args ...interface{}) { if debugLZNT1 { fmt.Printf(format, args...) } } func debugHexDump(buf []byte) string { if debugLZNT1 { return hex.Dump(buf) } return "" } // A reader may be able to tell us about the physical layer it is // reading from. type VtoPer interface { VtoP(offset int64) int64 } func VtoP(reader interface{}, offset int64) int64 { vtop, ok := reader.(VtoPer) if ok { return vtop.VtoP(offset) } fmt.Printf("Reader of type %T does not support VtoP\n", reader) return 0 } type FixedUpReader struct { *bytes.Reader original_offset int64 } func (self FixedUpReader) IsFixed(offset int64) bool { return true } func (self FixedUpReader) VtoP(offset int64) int64 { return self.original_offset } type IsFixedReader interface { IsFixed(offset int64) bool } func IsFixed(item interface{}, offset int64) bool { x, ok := item.(IsFixedReader) if ok { return x.IsFixed(offset) } fmt.Printf("Reader of type %T does not support IsFixed\n", item) return false } <file_sep>/tests/ntfs_test.go package ntfs /* This test suite is designed to trap regressions in the NTFS parser. It relies on actual real life observed NTFS filesystems that were encountered in the past. For each interesting testcase, we used the recorder to capture the disk sectors involved in the specific operation under test and then the test replays these sectors under test conditions. This allows us to replicate exactly the image that was encountered in the wild - without having to maintain a large volume of disk images. The main goal of the test is to confirm the parser produces correct results and does not break in the future. Therefore we create a set of golden files which are then compared with the tool output on these test cases. */ import ( "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" "testing" "github.com/alecthomas/assert" "github.com/sebdah/goldie/v2" "github.com/stretchr/testify/suite" ) type NTFSTestSuite struct { suite.Suite binary, extension string tmpdir string } func (self *NTFSTestSuite) SetupTest() { if runtime.GOOS == "windows" { self.extension = ".exe" } // Search for a valid binary to run. binaries, err := filepath.Glob( "../ntfs" + self.extension) assert.NoError(self.T(), err) self.binary, _ = filepath.Abs(binaries[0]) fmt.Printf("Found binary %v\n", self.binary) self.tmpdir, err = ioutil.TempDir("", "tmp") assert.NoError(self.T(), err) } func (self *NTFSTestSuite) TearDownTest() { os.RemoveAll(self.tmpdir) } // This test case looks at a file which has a sparse ending: The file // is 1048576 bytes long but has only 4096 initializaed with real // data - the rest is sparse. func (self *NTFSTestSuite) TestLargeFileSmallInit() { record_dir := "large_file_small_init" cmd := exec.Command(self.binary, "--record", record_dir, "runs", self.binary, "46", "--verbose") out, err := cmd.CombinedOutput() assert.NoError(self.T(), err, string(out)) g := goldie.New(self.T(), goldie.WithFixtureDir(record_dir+"/fixtures")) g.Assert(self.T(), "runs", out) // Make sure we write the right length of data. dd_file := filepath.Join(self.tmpdir, "cat.dd") cmd = exec.Command(self.binary, "--record", record_dir, "cat", self.binary, "46", "--out", dd_file) _, err = cmd.CombinedOutput() assert.NoError(self.T(), err) s, err := os.Lstat(dd_file) assert.NoError(self.T(), err) assert.Equal(self.T(), s.Size(), int64(1048576)) } // This test case looks at a sparse $J USN journal with two VCNs. func (self *NTFSTestSuite) TestUSNWith2VCNs() { record_dir := "usn_with_two_vcns" cmd := exec.Command(self.binary, "--record", record_dir, "runs", self.binary, "68310:$J", "--verbose") out, err := cmd.CombinedOutput() assert.NoError(self.T(), err, string(out)) g := goldie.New(self.T(), goldie.WithFixtureDir(record_dir+"/fixtures")) g.Assert(self.T(), "runs", out) // Make sure we write the right length of data. cmd = exec.Command(self.binary, "--record", record_dir, "stat", self.binary, "68310") cmd.Env = append(os.Environ(), "TZ=Z") out, err = cmd.CombinedOutput() assert.NoError(self.T(), err) g.Assert(self.T(), "stat", out) } // This test reads a highly fragmented MFT stream func (self *NTFSTestSuite) TestHighlyFragmentedMFT() { record_dir := "highly_fragmented_mft" cmd := exec.Command(self.binary, "--record", record_dir, "runs", self.binary, "0") out, err := cmd.CombinedOutput() assert.NoError(self.T(), err, string(out)) g := goldie.New(self.T(), goldie.WithFixtureDir(record_dir+"/fixtures")) g.Assert(self.T(), "runs", out) } // This file contains multiple data streams with the same ID. We need // to generate Inode strings which include the stream name so it can // be disambiguated. func (self *NTFSTestSuite) TestMultipleADSWithSameID() { record_dir := "ads_with_same_ids" cmd := exec.Command(self.binary, "--record", record_dir, "ls", self.binary) out_b, err := cmd.CombinedOutput() out := string(out_b) assert.NoError(self.T(), err, out) // Check that inodes do not include ADS unless it is necessary for disambiguation g := goldie.New(self.T(), goldie.WithFixtureDir(record_dir+"/fixtures")) g.Assert(self.T(), "ls", out_b) // This is the first stream with id 0 we dont need an ADS // reference because we will pick the first anyway. assert.Contains(self.T(), out, "38-128-0 ") // This stream needs an ads to disambiguate it from the :111 // stream. assert.Contains(self.T(), out, "38-128-0:333") assert.Contains(self.T(), out, "38-128-3 ") // $Secure:$SDS is only stream with ADS and it has non zero ID - // we dont need an inode with ADS assert.Contains(self.T(), out, "9-128-8 ") // Search first stream with same id cmd = exec.Command(self.binary, "--record", record_dir, "stat", self.binary, "38") out_b, err = cmd.CombinedOutput() out = string(out_b) assert.NoError(self.T(), err, out) g = goldie.New(self.T(), goldie.WithFixtureDir(record_dir+"/fixtures")) g.Assert(self.T(), "stat", out_b) // Search first stream with id of 0 will select the first stream :111 cmd = exec.Command(self.binary, "--record", record_dir, "cat", self.binary, "38-128-0") out_b, err = cmd.CombinedOutput() out = string(out_b) assert.NoError(self.T(), err, out) assert.Contains(self.T(), out, "1111") // Opening by mft id gives the non-ads stream cmd = exec.Command(self.binary, "--record", record_dir, "cat", self.binary, "38") out_b, err = cmd.CombinedOutput() out = string(out_b) assert.NoError(self.T(), err, out) assert.Contains(self.T(), out, "9999") // Reading by mft id and ads gives the first stream with that ads cmd = exec.Command(self.binary, "--record", record_dir, "cat", self.binary, "38:111") out_b, err = cmd.CombinedOutput() out = string(out_b) assert.NoError(self.T(), err, out) assert.Contains(self.T(), out, "1111") // Reading by id containing ads cmd = exec.Command(self.binary, "--record", record_dir, "cat", self.binary, "38-128-0:333") out_b, err = cmd.CombinedOutput() out = string(out_b) assert.NoError(self.T(), err, out) assert.Contains(self.T(), out, "333") // Reading by type and id cmd = exec.Command(self.binary, "--record", record_dir, "cat", self.binary, "38-128-3") out_b, err = cmd.CombinedOutput() out = string(out_b) assert.NoError(self.T(), err, out) assert.Contains(self.T(), out, "999") // Reading by mft record id has wildcard stream id - will pick the non-ads stream 38-128-3 cmd = exec.Command(self.binary, "--record", record_dir, "cat", self.binary, "38-128") out_b, err = cmd.CombinedOutput() out = string(out_b) assert.NoError(self.T(), err, out) assert.Contains(self.T(), out, "999") // Reading by id of 9 file - it does not have any ADS should return error cmd = exec.Command(self.binary, "--record", record_dir, "cat", self.binary, "38-128-3:111") out_b, err = cmd.CombinedOutput() out = string(out_b) assert.Error(self.T(), err, out) assert.Contains(self.T(), out, "file does not exist") // Open $Secure:$SDS which has no - non-ads stream cmd = exec.Command(self.binary, "--record", record_dir, "cat", self.binary, "9") out_b, err = cmd.CombinedOutput() out = string(out_b) assert.NoError(self.T(), err, out) assert.Equal(self.T(), len(out), 263264) } func TestNTFS(t *testing.T) { suite.Run(t, &NTFSTestSuite{}) } <file_sep>/bin/stat.go package main import ( "encoding/json" "fmt" kingpin "gopkg.in/alecthomas/kingpin.v2" "www.velocidex.com/golang/go-ntfs/parser" ) var ( stat_command = app.Command( "stat", "inspect the MFT record.") stat_command_i30 = stat_command.Flag( "i30", "Carve out $I30 entries").Bool() stat_command_file_arg = stat_command.Arg( "file", "The image file to inspect", ).Required().File() stat_command_image_offset = stat_command.Flag( "image_offset", "The offset in the image to use.", ).Int64() stat_command_arg = stat_command.Arg( "path", "The path to list or an STAT entry.", ).Default("5").String() stat_command_verbose = stat_command.Flag( "include_short_names", "Include Short Names in links").Bool() ) func doSTAT() { reader, _ := parser.NewPagedReader(&parser.OffsetReader{ Offset: *stat_command_image_offset, Reader: getReader(*stat_command_file_arg), }, 1024, 10000) ntfs_ctx, err := parser.GetNTFSContext(reader, 0) kingpin.FatalIfError(err, "Can not open filesystem") if *stat_command_verbose { ntfs_ctx.SetOptions(parser.Options{ IncludeShortNames: true, MaxLinks: 1000, MaxDirectoryDepth: 100, }) } mft_entry, err := GetMFTEntry(ntfs_ctx, *stat_command_arg) kingpin.FatalIfError(err, "Can not open path") if *verbose_flag { fmt.Println(mft_entry.Display(ntfs_ctx)) } else { stat, err := parser.ModelMFTEntry(ntfs_ctx, mft_entry) kingpin.FatalIfError(err, "Can not open path") serialized, err := json.MarshalIndent(stat, " ", " ") kingpin.FatalIfError(err, "Marshal") fmt.Println(string(serialized)) } if *stat_command_i30 { i30_list := parser.ExtractI30List(ntfs_ctx, mft_entry) kingpin.FatalIfError(err, "Can not extract $I30") serialized, err := json.MarshalIndent(i30_list, " ", " ") kingpin.FatalIfError(err, "Marshal") fmt.Println(string(serialized)) } } func init() { command_handlers = append(command_handlers, func(command string) bool { switch command { case "stat": doSTAT() default: return false } return true }) } <file_sep>/parser/handwritten.go package parser import ( "encoding/binary" "fmt" "io" "strings" ) // These are hand written parsers for often used structs. type NTFS_ATTRIBUTE struct { b [64]byte Reader io.ReaderAt Offset int64 Profile *NTFSProfile } func NewNTFS_ATTRIBUTE(Reader io.ReaderAt, Offset int64, Profile *NTFSProfile) *NTFS_ATTRIBUTE { result := &NTFS_ATTRIBUTE{ Reader: Reader, Offset: Offset, Profile: Profile, } _, err := Reader.ReadAt(result.b[:], Offset) if err != nil { return result } return result } func (self *NTFS_ATTRIBUTE) Size() int { return 64 } func (self *NTFS_ATTRIBUTE) Type() *Enumeration { value := binary.LittleEndian.Uint32(self.b[0:4]) name := "Unknown" switch value { case 16: name = "$STANDARD_INFORMATION" case 32: name = "$ATTRIBUTE_LIST" case 48: name = "$FILE_NAME" case 64: name = "$OBJECT_ID" case 80: name = "$SECURITY_DESCRIPTOR" case 96: name = "$VOLUME_NAME" case 112: name = "$VOLUME_INFORMATION" case 128: name = "$DATA" case 144: name = "$INDEX_ROOT" case 160: name = "$INDEX_ALLOCATION" case 176: name = "$BITMAP" case 192: name = "$REPARSE_POINT" case 208: name = "$EA_INFORMATION" case 224: name = "$EA" case 256: name = "$LOGGED_UTILITY_STREAM" } return &Enumeration{Value: uint64(value), Name: name} } func (self *NTFS_ATTRIBUTE) Length() uint32 { return binary.LittleEndian.Uint32(self.b[4:8]) } func (self *NTFS_ATTRIBUTE) Resident() *Enumeration { value := uint8(self.b[8]) name := "Unknown" switch value { case 0: name = "RESIDENT" case 1: name = "NON-RESIDENT" } return &Enumeration{Value: uint64(value), Name: name} } func (self *NTFS_ATTRIBUTE) name_length() byte { return uint8(self.b[9]) } func (self *NTFS_ATTRIBUTE) name_offset() uint16 { return binary.LittleEndian.Uint16(self.b[10:12]) } func (self *NTFS_ATTRIBUTE) Flags() *EntryFlags { value := binary.LittleEndian.Uint16(self.b[12:14]) res := EntryFlags(uint64(value)) return &res } type EntryFlags uint64 func (self EntryFlags) DebugString() string { names := []string{} if self&(1<<0) != 0 { names = append(names, "COMPRESSED") } if self&(1<<14) != 0 { names = append(names, "ENCRYPTED") } if self&(1<<15) != 0 { names = append(names, "SPARSE") } return fmt.Sprintf("%d (%v)", self, strings.Join(names, ",")) } // Faster shortcuts to avoid extra allocations. func IsCompressed(flags *EntryFlags) bool { return uint64(*flags)&uint64(1) != 0 } func IsCompressedOrSparse(flags *EntryFlags) bool { return uint64(*flags)&uint64(1+1<<15) != 0 } func IsSparse(flags *EntryFlags) bool { return uint64(*flags)&uint64(1<<15) != 0 } func (self *NTFS_ATTRIBUTE) Attribute_id() uint16 { return binary.LittleEndian.Uint16(self.b[14:16]) } func (self *NTFS_ATTRIBUTE) Content_size() uint32 { return binary.LittleEndian.Uint32(self.b[16:20]) } func (self *NTFS_ATTRIBUTE) Content_offset() uint16 { return binary.LittleEndian.Uint16(self.b[20:22]) } func (self *NTFS_ATTRIBUTE) Runlist_vcn_start() uint64 { return binary.LittleEndian.Uint64(self.b[16:24]) } func (self *NTFS_ATTRIBUTE) Runlist_vcn_end() uint64 { return binary.LittleEndian.Uint64(self.b[24:32]) } func (self *NTFS_ATTRIBUTE) Runlist_offset() uint16 { return binary.LittleEndian.Uint16(self.b[32:34]) } func (self *NTFS_ATTRIBUTE) Compression_unit_size() uint16 { return binary.LittleEndian.Uint16(self.b[34:36]) } func (self *NTFS_ATTRIBUTE) Allocated_size() uint64 { return binary.LittleEndian.Uint64(self.b[40:48]) } func (self *NTFS_ATTRIBUTE) Actual_size() uint64 { return binary.LittleEndian.Uint64(self.b[48:56]) } func (self *NTFS_ATTRIBUTE) Initialized_size() uint64 { return binary.LittleEndian.Uint64(self.b[56:64]) } func (self *NTFS_ATTRIBUTE) DebugString() string { result := fmt.Sprintf("struct NTFS_ATTRIBUTE @ %#x:\n", self.Offset) result += fmt.Sprintf(" Type: %v\n", self.Type().DebugString()) result += fmt.Sprintf(" Length: %#0x\n", self.Length()) result += fmt.Sprintf(" Resident: %v\n", self.Resident().DebugString()) result += fmt.Sprintf(" name_length: %#0x\n", self.name_length()) result += fmt.Sprintf(" name_offset: %#0x\n", self.name_offset()) result += fmt.Sprintf(" Flags: %v\n", self.Flags().DebugString()) result += fmt.Sprintf(" Attribute_id: %#0x\n", self.Attribute_id()) result += fmt.Sprintf(" Content_size: %#0x\n", self.Content_size()) result += fmt.Sprintf(" Content_offset: %#0x\n", self.Content_offset()) if self.Resident().Value == 1 { result += fmt.Sprintf(" Runlist_vcn_start: %#0x\n", self.Runlist_vcn_start()) result += fmt.Sprintf(" Runlist_vcn_end: %#0x\n", self.Runlist_vcn_end()) result += fmt.Sprintf(" Runlist_offset: %#0x\n", self.Runlist_offset()) result += fmt.Sprintf(" Compression_unit_size: %#0x\n", self.Compression_unit_size()) result += fmt.Sprintf(" Allocated_size: %#0x\n", self.Allocated_size()) result += fmt.Sprintf(" Actual_size: %#0x\n", self.Actual_size()) result += fmt.Sprintf(" Initialized_size: %#0x\n", self.Initialized_size()) } return result } // MFT_ENTRY with a bit of caching. type MFT_ENTRY struct { Reader io.ReaderAt Offset int64 Profile *NTFSProfile } func (self *MFT_ENTRY) Size() int { return 0 } func (self *MFT_ENTRY) Magic() *Signature { value := ParseSignature(self.Reader, self.Profile.Off_MFT_ENTRY_Magic+self.Offset, 4) return &Signature{value: value, signature: "FILE"} } func (self *MFT_ENTRY) Fixup_offset() uint16 { return ParseUint16(self.Reader, self.Profile.Off_MFT_ENTRY_Fixup_offset+self.Offset) } func (self *MFT_ENTRY) Fixup_count() uint16 { return ParseUint16(self.Reader, self.Profile.Off_MFT_ENTRY_Fixup_count+self.Offset) } func (self *MFT_ENTRY) Logfile_sequence_number() uint64 { return ParseUint64(self.Reader, self.Profile.Off_MFT_ENTRY_Logfile_sequence_number+self.Offset) } func (self *MFT_ENTRY) Sequence_value() uint16 { return ParseUint16(self.Reader, self.Profile.Off_MFT_ENTRY_Sequence_value+self.Offset) } func (self *MFT_ENTRY) Link_count() uint16 { return ParseUint16(self.Reader, self.Profile.Off_MFT_ENTRY_Link_count+self.Offset) } func (self *MFT_ENTRY) Attribute_offset() uint16 { return ParseUint16(self.Reader, self.Profile.Off_MFT_ENTRY_Attribute_offset+self.Offset) } func (self *MFT_ENTRY) Flags() *Flags { value := ParseUint16(self.Reader, self.Profile.Off_MFT_ENTRY_Flags+self.Offset) names := make(map[string]bool) if value&(1<<0) != 0 { names["ALLOCATED"] = true } if value&(1<<1) != 0 { names["DIRECTORY"] = true } return &Flags{Value: uint64(value), Names: names} } func (self *MFT_ENTRY) Mft_entry_size() uint16 { return ParseUint16(self.Reader, self.Profile.Off_MFT_ENTRY_Mft_entry_size+self.Offset) } func (self *MFT_ENTRY) Mft_entry_allocated() uint16 { return ParseUint16(self.Reader, self.Profile.Off_MFT_ENTRY_Mft_entry_allocated+self.Offset) } func (self *MFT_ENTRY) Base_record_reference() uint64 { return ParseUint64(self.Reader, self.Profile.Off_MFT_ENTRY_Base_record_reference+self.Offset) } func (self *MFT_ENTRY) Next_attribute_id() uint16 { return ParseUint16(self.Reader, self.Profile.Off_MFT_ENTRY_Next_attribute_id+self.Offset) } func (self *MFT_ENTRY) Record_number() uint32 { return ParseUint32(self.Reader, self.Profile.Off_MFT_ENTRY_Record_number+self.Offset) } func (self *MFT_ENTRY) DebugString() string { result := fmt.Sprintf("struct MFT_ENTRY @ %#x:\n", self.Offset) result += fmt.Sprintf(" Fixup_offset: %#0x\n", self.Fixup_offset()) result += fmt.Sprintf(" Fixup_count: %#0x\n", self.Fixup_count()) result += fmt.Sprintf(" Logfile_sequence_number: %#0x\n", self.Logfile_sequence_number()) result += fmt.Sprintf(" Sequence_value: %#0x\n", self.Sequence_value()) result += fmt.Sprintf(" Link_count: %#0x\n", self.Link_count()) result += fmt.Sprintf(" Attribute_offset: %#0x\n", self.Attribute_offset()) result += fmt.Sprintf(" Flags: %v\n", self.Flags().DebugString()) result += fmt.Sprintf(" Mft_entry_size: %#0x\n", self.Mft_entry_size()) result += fmt.Sprintf(" Mft_entry_allocated: %#0x\n", self.Mft_entry_allocated()) result += fmt.Sprintf(" Base_record_reference: %#0x\n", self.Base_record_reference()) result += fmt.Sprintf(" Next_attribute_id: %#0x\n", self.Next_attribute_id()) result += fmt.Sprintf(" Record_number: %#0x\n", self.Record_number()) return result } <file_sep>/parser/boot.go package parser import ( "bytes" "errors" "fmt" "io" ) var ( EntryTooShortError = errors.New("EntryTooShortError") ShortReadError = errors.New("ShortReadError") ) func (self *NTFS_BOOT_SECTOR) ClusterSize() int64 { return int64(self._cluster_size()) * int64(self.Sector_size()) } func (self *NTFS_BOOT_SECTOR) BlockCount() int64 { return int64(self._volume_size()) / int64(self.ClusterSize()) } func (self *NTFS_BOOT_SECTOR) RecordSize() int64 { _record_size := int64(self._mft_record_size()) if _record_size > 0 { return _record_size * self.ClusterSize() } return 1 << uint32(-_record_size) } // The MFT entry needs to be fixed up. This method extracts the // MFT_ENTRY from disk into a buffer and perfoms the fixups. We then // return an MFT_ENTRY instantiated over this fixed up buffer. func FixUpDiskMFTEntry(mft *MFT_ENTRY) (io.ReaderAt, error) { STATS.Inc_FixUpDiskMFTEntry() // Read the entire MFT entry into the buffer and then apply // the fixup table. (Maxsize uint16) mft_allocated_size := mft.Mft_entry_allocated() allocated_len := CapUint16(mft_allocated_size, MAX_MFT_ENTRY_SIZE) // MFT should be a reasonable size - if it is too small it is // probably not valid. if allocated_len < 0x100 { return nil, EntryTooShortError } buffer := make([]byte, allocated_len) n, err := mft.Reader.ReadAt(buffer, mft.Offset) if err != nil { return nil, err } if n < int(allocated_len) { return nil, ShortReadError } // The fixup table is an array of 2 byte values. The first // value is the magic and the rest are fixup values. fixup_offset := mft.Offset + int64(mft.Fixup_offset()) fixup_count := int64(mft.Fixup_count()) if fixup_count == 0 { return bytes.NewReader(buffer), nil } fixup_table_len := CapInt64(fixup_count*2, int64(allocated_len)) fixup_table := make([]byte, fixup_table_len) n, err = mft.Reader.ReadAt(fixup_table, fixup_offset) if err != nil { return nil, err } if n < int(fixup_table_len) { return nil, errors.New("Short read") } fixup_magic := []byte{fixup_table[0], fixup_table[1]} sector_idx := 0 for idx := 2; idx < len(fixup_table); idx += 2 { fixup_offset := (sector_idx+1)*512 - 2 if fixup_offset+1 >= len(buffer) || buffer[fixup_offset] != fixup_magic[0] || buffer[fixup_offset+1] != fixup_magic[1] { return nil, errors.New(fmt.Sprintf("Fixup error with MFT %d", mft.Record_number())) } // Apply the fixup buffer[fixup_offset] = fixup_table[idx] buffer[fixup_offset+1] = fixup_table[idx+1] sector_idx += 1 } return &FixedUpReader{ Reader: bytes.NewReader(buffer), original_offset: mft.Offset, }, nil } // Find the root MFT_ENTRY object. Returns a reader over the $MFT file. func BootstrapMFT(ntfs *NTFSContext) (io.ReaderAt, error) { // The MFT is a table of MFT_ENTRY records read from an // abstracted reader which is itself a $DATA attribute of the // first MFT record: // MFT[0] -> Attr $DATA contains the entire $MFT stream. // We therefore need to bootstrap the MFT: // 1. Read the first entry in the first cluster using the disk reader. // 2. Search for the $DATA attribute. // 3. Reconstruct the runlist and RunReader from this attribute. // 4. Instantiate the MFT over this new reader. record_size := ntfs.Boot.ClusterSize() offset := int64(ntfs.Boot._mft_cluster()) * record_size // In the first pass we instantiate a reader of the MFT $DATA // stream that is found in the first MFT entry. The real MFT may // be larger than that and split across multiple entries but we // can not bootstrap it until we have the reader of the first part // of the MFT. root_mft, err := GetFixedUpMFTEntry(ntfs, ntfs.DiskReader, offset) if err != nil { return nil, err } var first_mft_reader io.ReaderAt found_attribute_list := false // Find the $DATA attribute of the root entry. This will // contain the full $MFT file. for _, attr := range root_mft.EnumerateAttributes(ntfs) { switch attr.Type().Value { case ATTR_TYPE_ATTRIBUTE_LIST: // If there is an attribute list the MFT may be split // across multiple entries - further processing will be // needed. found_attribute_list = true case ATTR_TYPE_DATA: first_mft_reader = attr.Data(ntfs) } } if first_mft_reader == nil { return nil, errors.New("$DATA attribute not found for $MFT") } // This is the common case - only one $DATA attribute. if !found_attribute_list { return first_mft_reader, nil } // There are more VCNs which we need to discover. Set the // MFTReader in the context to cover the first VCN only for the // below call to EnumerateAttributes. Hopefully the actual // attribute falls inside the first VCN. ntfs.MFTReader = first_mft_reader // Now do a second scan of the MFT entry to find all the // attributes in the attribute list (including extended // attributes). We depend on the first VNC to be in the $MFT entry // and that extended $DATA attributes will be present in this // first stream. root_mft, err = ntfs.GetMFT(0) if err != nil { return nil, err } // Collect all the data streams in the root MFT entry (include // extended attributes). Each $DATA stream is a VCN in the wider // MFT stream. var mft_data_streams []*NTFS_ATTRIBUTE for _, attr := range root_mft.EnumerateAttributes(ntfs) { if attr.Type().Value == ATTR_TYPE_DATA { mft_data_streams = append(mft_data_streams, attr) } } // Create a single reader over all the VCN streams. result := &RangeReader{ runs: joinAllVCNs(ntfs, mft_data_streams), } // Reset the MFTReader in the context so we can read all MFT // entries from it (even ones in the second $DATA attribute). ntfs.MFTReader = result return result, nil } func (self *NTFS_BOOT_SECTOR) IsValid() error { if self.Magic() != 0xaa55 { return errors.New("Invalid magic") } switch self.ClusterSize() { case 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000, 0x10000: break default: return errors.New( fmt.Sprintf("Invalid cluster size %x", self.ClusterSize())) } sector_size := self.Sector_size() if sector_size == 0 || (sector_size%512 != 0) { return errors.New("Invalid sector_size") } if self.BlockCount() == 0 { return errors.New("Volume size is 0") } return nil } func GetFixedUpMFTEntry( ntfs *NTFSContext, reader io.ReaderAt, offset int64) (*MFT_ENTRY, error) { raw_mft := ntfs.Profile.MFT_ENTRY(reader, offset) fixed_up_reader, err := FixUpDiskMFTEntry(raw_mft) if err != nil { return nil, err } return ntfs.Profile.MFT_ENTRY(fixed_up_reader, 0), nil } <file_sep>/bin/check.go package main import ( "fmt" kingpin "gopkg.in/alecthomas/kingpin.v2" "www.velocidex.com/golang/go-ntfs/parser" ) var ( check_command = app.Command( "check", "Check for some sanity.") check_command_file_arg = check_command.Arg( "file", "The image file to inspect", ).Required().File() check_command_image_offset = check_command.Flag( "image_offset", "The offset in the image to use.", ).Int64() check_command_start_id = check_command.Flag( "start", "The ID to start with").Int64() check_command_end_id = check_command.Flag( "end", "The ID to end with").Default("10000000").Int64() ) func doCheck() { reader, _ := parser.NewPagedReader(&parser.OffsetReader{ Offset: *check_command_image_offset, Reader: getReader(*check_command_file_arg), }, 1024, 10000) ntfs_ctx, err := parser.GetNTFSContext(reader, 0) kingpin.FatalIfError(err, "Can not open filesystem") for i := *check_command_start_id; i < *check_command_end_id; i++ { reportError(ntfs_ctx, i) mft_entry, err := ntfs_ctx.GetMFT(i) if err != nil { fmt.Printf("Error: %v: %v\n", i, err) continue } stats := parser.Stat(ntfs_ctx, mft_entry) if len(stats) == 0 { continue } if i%100 == 0 { fmt.Printf("Getting id %v - %v %v\n", i, mft_entry.Record_number(), stats[0].Name) } if mft_entry.Record_number() != uint32(i) { panic(i) } } } func reportError(ntfs_ctx *parser.NTFSContext, id int64) { offset := ntfs_ctx.GetRecordSize() * id disk_offset := parser.VtoP(ntfs_ctx.MFTReader, offset) fmt.Printf("MFTId %v: Offset %v (%v clusters), disk offset %v (%v clusters)\n", id, offset, offset/ntfs_ctx.ClusterSize, disk_offset, disk_offset/ntfs_ctx.ClusterSize) } func init() { command_handlers = append(command_handlers, func(command string) bool { switch command { case "check": doCheck() default: return false } return true }) } <file_sep>/parser/offset.go package parser import "io" type OffsetReader struct { Offset int64 Reader io.ReaderAt } func (self *OffsetReader) ReadAt(buf []byte, offset int64) (int, error) { return self.Reader.ReadAt(buf, offset+self.Offset) } <file_sep>/bin/vss.go package main import ( "fmt" "os" kingpin "gopkg.in/alecthomas/kingpin.v2" "www.velocidex.com/golang/go-ntfs/parser" ) var ( vss_command = app.Command( "vss", "Inspect VSS.") vss_command_file_arg = vss_command.Arg( "file", "The image file to inspect", ).Required().OpenFile(os.O_RDONLY, os.FileMode(0666)) ) func doVSS() { reader, _ := parser.NewPagedReader(*vss_command_file_arg, 1024, 10000) ntfs_ctx, err := parser.GetNTFSContext(reader, 0) kingpin.FatalIfError(err, "Can not open filesystem") vss_header := ntfs_ctx.Profile.VSS_VOLUME_HEADER(reader, 0x1e00) fmt.Printf("%v", vss_header.DebugString()) for CatalogOffset := vss_header.CatalogOffset(); CatalogOffset > 0; { catalog_header := ntfs_ctx.Profile.VSS_CATALOG_HEADER( reader, CatalogOffset) fmt.Printf("%v", catalog_header.DebugString()) CatalogOffset = catalog_header.NextOffset() offset := int64(catalog_header.Offset) + int64(catalog_header.Size()) end := int64(catalog_header.Offset) + 0x00004000 for offset < end { entry1 := ntfs_ctx.Profile.VSS_CATALOG_ENTRY_1(reader, offset) switch entry1.EntryType() { case 2: entry2 := ntfs_ctx.Profile.VSS_CATALOG_ENTRY_2(reader, offset) fmt.Printf("%v", entry2.DebugString()) store_guid_filename := fmt.Sprintf( "System Volume Information/%s%s", entry2.StoreGUID().AsString(), catalog_header.Identifier().AsString()) fmt.Printf("Store is %s\n", store_guid_filename) printStore(ntfs_ctx, store_guid_filename) offset += int64(entry2.Size()) case 3: entry3 := ntfs_ctx.Profile.VSS_CATALOG_ENTRY_3(reader, offset) fmt.Printf("%v", entry3.DebugString()) offset += int64(entry3.Size()) default: fmt.Printf("%v", entry1.DebugString()) offset += int64(entry1.Size()) } } } } func printStore(ntfs_ctx *parser.NTFSContext, store_guid_filename string) { data_stream, err := parser.GetDataForPath(ntfs_ctx, store_guid_filename) kingpin.FatalIfError(err, "Can not open store") vss_store_block_header := ntfs_ctx.Profile.VSS_STORE_BLOCK_HEADER( data_stream, 0) fmt.Printf("%v", vss_store_block_header.DebugString()) vss_store_info := ntfs_ctx.Profile.VSS_STORE_INFORMATION( data_stream, int64(vss_store_block_header.Size())) fmt.Printf("%v", vss_store_info.DebugString()) } func init() { command_handlers = append(command_handlers, func(command string) bool { switch command { case "vss": doVSS() default: return false } return true }) } <file_sep>/parser/utils.go package parser import ( "path" ) func get_display_name(file_names []*FILE_NAME) string { short_name := "" for _, fn := range file_names { name := fn.Name() name_type := fn.NameType().Name switch name_type { case "Win32", "DOS+Win32", "POSIX": return name default: short_name = name } } return short_name } // Traverse the mft entry and attempt to find its owner until the // root. We return the full path of the MFT entry. func GetFullPath(ntfs *NTFSContext, mft_entry *MFT_ENTRY) string { links := GetHardLinks(ntfs, uint64(mft_entry.Record_number()), 1) if len(links) == 0 { return "/" } return "/" + path.Join(links[0]...) } func CapUint64(v uint64, max uint64) uint64 { if v > max { return max } return v } func CapUint32(v uint32, max uint32) uint32 { if v > max { return max } return v } func CapUint16(v uint16, max uint16) uint16 { if v > max { return max } return v } func CapInt64(v int64, max int64) int64 { if v > max { return max } return v } func CapInt32(v int32, max int32) int32 { if v > max { return max } return v } func setADS(components []string, name string) []string { result := make([]string, 0, len(components)) for i, c := range components { if i < len(components)-1 { result = append(result, c) } else { result = append(result, c+":"+name) } } return result } func CopySlice(in []string) []string { result := make([]string, len(in)) copy(result, in) return result } // In place reserving of the slice func ReverseStringSlice(s []string) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } }
8f9ab335a84c437630e130295c6e9e19f15e3d54
[ "Makefile", "Go Module", "Go" ]
45
Go
Velocidex/go-ntfs
6a3dd72bfbf1f18f1d3c7e93bdfc727ac4f49d19
f40f3b25b7604a0d89fa86499cdda81d0fb537a6
refs/heads/master
<repo_name>arlengur/GwtSteps<file_sep>/src/server/RemServImpl.java package server; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import client.RemServ; /** * Created with IntelliJ IDEA. * User: ruinalga * Date: 26.06.14 * Time: 15:52 * To change this template use File | Settings | File Templates. */ public class RemServImpl extends RemoteServiceServlet implements RemServ { @Override public Integer getInt() { return (int)(Math.random()*1000); } }
3dfd01793bec32e3a852644b5b71d904ec9040bc
[ "Java" ]
1
Java
arlengur/GwtSteps
9890a2842a469e412959b8f5ecd03bc522f300d8
01f8e445aac32b7a7826c433e5566d0e054884a4
refs/heads/master
<file_sep>import * as express from 'express' import bootstrap from './util/bootstrap' import { mountMiddlewares } from './middleware' const app = express() // mount all middlewares mountMiddlewares(app) // initialized ioc container and start express application bootstrap(app)<file_sep>export function isGenerator(obj: any) { return 'function' === typeof obj.next && 'function' === typeof obj.throw; } export function isGeneratorFunction(obj: any) { var constructor = obj.constructor; if (!constructor) { return false; } if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) { return true; } return isGenerator(constructor.prototype); } export function isPromise(obj: any) { return obj && obj.then && 'function' === typeof obj.then; }<file_sep>import * as bodyParse from 'body-parser' import { v4 } from 'uuid' import { NextFunction, Request, Response } from 'express' import { Application } from 'express' import { uuid } from './trace' import { accesscors } from './cors' export function mountMiddlewares(app: Application) { app.use(uuid) // cors accesscors(app) // 处理 post 请求 app.use(bodyParse.urlencoded({ extended: true, limit: 10 * 1024 * 1024, })) return app }<file_sep>import "reflect-metadata" import { Application } from 'express' import { InversifyExpressServer } from './server' import { container } from './ioc' import './loader' export default function(app: Application) { const server = new InversifyExpressServer(container, null, null, app) server.build().listen('3000') }<file_sep>import { InversifyExpressServer } from "./server"; import { Controller, Method, Get, Put, Post, Patch, Head, All, Delete, Request, Response, RequestParam, QueryParam, RequestBody, RequestHeaders, Cookies, Session, Next, SSR, ResponseBody, ResponseData } from "./decorators"; import { TYPE } from "./constants"; export { InversifyExpressServer, Controller, Method, Get, Put, Post, Patch, Head, All, Delete, TYPE, Request, Response, RequestParam, QueryParam, RequestBody, RequestHeaders, Cookies, Session, Next, SSR, ResponseBody, ResponseData, }; <file_sep>import { Controller, Get, Post, Put, Delete, QueryParam, RequestParam, RequestBody, Cookies, Session, Response, ResponseBody, SSR, TYPE } from '../util/server'; import { provideNamed, provide, inject, lazyInject } from '../util/ioc'; @provide('TestManager') // provide 为对 injectable 的封装,injectable 的作用 loc 思想:依赖注入 export default class TestManager { public async testHello() { return 'hello' } } <file_sep>import * as express from 'express' import { Controller, Get, Post, Put, Delete, QueryParam, RequestParam, RequestBody, Request, Cookies, Session, Response, ResponseBody, SSR, TYPE } from '../util/server'; import { provideNamed, provide, inject, lazyInject, container } from '../util/ioc'; import TestManager from '../manager/testManager' @provideNamed(TYPE.Controller, 'TestController') @Controller('/') class TestController { // 这里的 TestManager 对应 provide 提供的 TestManager, 源码中 inject 最终走到 Reflect.defineMetadata(), // defineMetadata 方法里比较有学问,下次再研究了,因为看到 injectable(provide) 的源码以及 inject 的源码都用到了 defineMetadata 这个 api, // 帅佬说需要什么供应什么都在这 api 提现 @inject('TestManager') private testManager: TestManager @Get('test/hello') public async testHello() { const result = await this.testManager.testHello() return result } @Get('test/get') public async testGet( @QueryParam('abc') abc: string, // @Response() res: express.Response, // @Request() req: express.Request, // @Session() session: any, ) { return 'abc ' + abc } @Post('test/post') public async testPost( @RequestBody('abc') abc: string, // @Session() session: any, ) { return 'abc ' + abc } } <file_sep>import '../controller/index' <file_sep>import './testController'<file_sep>/* tslint:disable */ import * as express from "express" import * as inversify from "inversify" import * as promise from 'bluebird' import { interfaces } from "./interfaces" import { TYPE, METADATA_KEY, DEFAULT_ROUTING_ROOT_PATH, PARAMETER_TYPE } from "./constants" import { isGeneratorFunction, isPromise } from '../index' import { NextFunction, Request, Response } from "express" /** * Wrapper for the express server. */ export class InversifyExpressServer { private _router: express.Router; private _container: inversify.interfaces.Container; private _app: express.Application; private _configFn: interfaces.ConfigFunction; private _errorConfigFn: interfaces.ConfigFunction; private _routingConfig: interfaces.RoutingConfig; private _logger: { info: Function, error: Function } /** * Wrapper for the express server. * * @param container Container loaded with all controllers and their dependencies. */ constructor( container: inversify.interfaces.Container, customRouter?: express.Router, routingConfig?: interfaces.RoutingConfig, customApp?: express.Application, ) { this._container = container; this._router = customRouter || express.Router(); this._routingConfig = routingConfig || { rootPath: DEFAULT_ROUTING_ROOT_PATH, }; this._app = customApp || express(); // this._logger = container.get<any>('logger') } /** * Sets the configuration function to be applied to the application. * Note that the config function is not actually executed until a call to InversifyExpresServer.build(). * * This method is chainable. * * @param fn Function in which app-level middleware can be registered. */ public setConfig(fn: interfaces.ConfigFunction): InversifyExpressServer { this._configFn = fn return this } /** * Sets the error handler configuration function to be applied to the application. * Note that the error config function is not actually executed until a call to InversifyExpresServer.build(). * * This method is chainable. * * @param fn Function in which app-level error handlers can be registered. */ public setErrorConfig(fn: interfaces.ConfigFunction): InversifyExpressServer { this._errorConfigFn = fn return this } /** * Applies all routes and configuration to the server, returning the express application. */ public build(): express.Application { // register server-level middleware before anything else if (this._configFn) { this._configFn.apply(undefined, [this._app]) } this.registerControllers() // register error handlers after controllers if (this._errorConfigFn) { this._errorConfigFn.apply(undefined, [this._app]) } return this._app } private registerControllers() { // 获取所有注册的 controllers let controllers: interfaces.Controller[] = this._container.getAll<interfaces.Controller>(TYPE.Controller); controllers.forEach((controller: interfaces.Controller) => { let controllerMetadata: interfaces.ControllerMetadata = Reflect.getOwnMetadata( METADATA_KEY.controller, controller.constructor ) // 获取一个 controller 里的所有 method let methodMetadata: interfaces.ControllerMethodMetadata[] = Reflect.getOwnMetadata( METADATA_KEY.controllerMethod, controller.constructor ) // 获取参数 let parameterMetadata: interfaces.ControllerParameterMetadata = Reflect.getOwnMetadata( METADATA_KEY.controllerParameter, controller.constructor ) if (controllerMetadata && methodMetadata) { let router: express.Router = express.Router() // 处理中间件 let controllerMiddleware = this.resolveMidleware(...controllerMetadata.middleware) methodMetadata.forEach((metadata: interfaces.ControllerMethodMetadata) => { let paramList: interfaces.ParameterMetadata[] = [] if (parameterMetadata) { paramList = parameterMetadata[metadata.key] || [] } let handler: express.RequestHandler = this.handlerFactory(controllerMetadata.target.name, metadata.key, paramList) // TestController testHello let routeMiddleware = this.resolveMidleware(...metadata.middleware) this._router[metadata.method]( `${controllerMetadata.path}${metadata.path}`, ...controllerMiddleware, ...routeMiddleware, handler ) }) } }) this._app.use(this._routingConfig.rootPath, this._router) } private resolveMidleware(...middleware: interfaces.Middleware[]): express.RequestHandler[] { return middleware.map(middlewareItem => { try { return this._container.get<express.RequestHandler>(middlewareItem) } catch (_) { return middlewareItem as express.RequestHandler } }); } private handlerFactory(controllerName: any, key: string, parameterMetadata: interfaces.ParameterMetadata[]): express.RequestHandler { let controller = this._container.getNamed(TYPE.Controller, controllerName) let controllerBeforeMetadata: interfaces.BeforeMetadata = Reflect.getOwnMetadata( METADATA_KEY.controllerBefore, controller.constructor, key ) let controllerAfterMetadata: interfaces.AfterMetadata = Reflect.getOwnMetadata( METADATA_KEY.controllerAfter, controller.constructor, key ) return async (req: express.Request, res: express.Response, next: express.NextFunction) => { let args = this.extractParameters(req, res, next, parameterMetadata); let action = controller[key].bind(controller) if (isGeneratorFunction(action)) { action = promise.coroutine(action) } let result: any try { if (controllerBeforeMetadata) { args = await controllerBeforeMetadata(args, req, res, next) } result = await action(...args); if (controllerAfterMetadata) { result = await controllerAfterMetadata(result, req, res, next) } if (result && !res.headersSent) { res.send(result) } } catch (error) { if (error.name === 'gateWayError' || error.toString().indexOf('BusinessException') !== -1) { // this._logger.info(error.message) } else { // this._logger.error(error) } controllerAfterMetadata ? controllerAfterMetadata(error, req, res, next) : next(error) } } } private extractParameters(req: express.Request, res: express.Response, next: express.NextFunction, params: interfaces.ParameterMetadata[]): any[] { let args = [] if (!params || !params.length) { return [req, res, next] } for (let item of params) { switch (item.type) { case PARAMETER_TYPE.RESPONSE: args[item.index] = res; break; case PARAMETER_TYPE.REQUEST: args[item.index] = item.parameterName && item.parameterName !== 'default' ? this.getParam(req, null, item.parameterName) : req; break; case PARAMETER_TYPE.NEXT: args[item.index] = next; break; case PARAMETER_TYPE.PARAMS: args[item.index] = this.getParam(req, "params", item.parameterName); break; case PARAMETER_TYPE.QUERY: args[item.index] = item.parameterName && item.parameterName !== 'default' ? this.getParam(req, "query", item.parameterName) : req.query; break; case PARAMETER_TYPE.BODY: args[item.index] = item.parameterName && item.parameterName !== 'default' ? this.getParam(req, "body", item.parameterName) : req.body; break; case PARAMETER_TYPE.HEADERS: args[item.index] = this.getParam(req, "headers", item.parameterName); break; case PARAMETER_TYPE.COOKIES: args[item.index] = item.parameterName && item.parameterName !== 'default' ? req.cookies[item.parameterName] : req.cookies; break; case PARAMETER_TYPE.SESSION: args[item.index] = item.parameterName && item.parameterName !== 'default' ? req.session[item.parameterName] : req.session; break; default: args[item.index] = res; break; } } args.push(req, res, next) return args } private getParam(source: any, paramType: string, name: string) { let param = source[paramType] || source return param[name] } } <file_sep>import * as express from "express"; import { interfaces } from "./interfaces"; import { METADATA_KEY, PARAMETER_TYPE } from "./constants"; // import xlsx from 'node-xlsx' export function Controller(path: string = '', ...middleware: interfaces.Middleware[]) { return (target: any) => { const metadata: interfaces.ControllerMetadata = { path, middleware, target }; Reflect.defineMetadata(METADATA_KEY.controller, metadata, target); }; } export function All(path: string, ...middleware: interfaces.Middleware[]): interfaces.HandlerDecorator { return Method("all", path, ...middleware); } export function Get(path: string, ...middleware: interfaces.Middleware[]): interfaces.HandlerDecorator { return Method("get", path, ...middleware); } export function Post(path: string, ...middleware: interfaces.Middleware[]): interfaces.HandlerDecorator { return Method("post", path, ...middleware); } export function Put(path: string, ...middleware: interfaces.Middleware[]): interfaces.HandlerDecorator { return Method("put", path, ...middleware); } export function Patch(path: string, ...middleware: interfaces.Middleware[]): interfaces.HandlerDecorator { return Method("patch", path, ...middleware); } export function Head(path: string, ...middleware: interfaces.Middleware[]): interfaces.HandlerDecorator { return Method("head", path, ...middleware); } export function Delete(path: string, ...middleware: interfaces.Middleware[]): interfaces.HandlerDecorator { return Method("delete", path, ...middleware); } export function Method(method: string, path: string, ...middleware: interfaces.Middleware[]): interfaces.HandlerDecorator { return (target: any, key: string, value: any) => { const metadata: interfaces.ControllerMethodMetadata = { path, middleware, method, target, key }; let metadataList: interfaces.ControllerMethodMetadata[] = []; if (!Reflect.hasOwnMetadata(METADATA_KEY.controllerMethod, target.constructor)) { Reflect.defineMetadata(METADATA_KEY.controllerMethod, metadataList, target.constructor); } else { metadataList = Reflect.getOwnMetadata(METADATA_KEY.controllerMethod, target.constructor); } // 这句比较恶心,略过,参考 https://github.com/rbuckton/reflect-metadata/issues/53 metadataList.push(metadata) } } export const Request = paramDecoratorFactory(PARAMETER_TYPE.REQUEST); export const Response = paramDecoratorFactory(PARAMETER_TYPE.RESPONSE); export const RequestParam = paramDecoratorFactory(PARAMETER_TYPE.PARAMS); export const QueryParam = paramDecoratorFactory(PARAMETER_TYPE.QUERY); export const RequestBody = paramDecoratorFactory(PARAMETER_TYPE.BODY); export const RequestHeaders = paramDecoratorFactory(PARAMETER_TYPE.HEADERS); export const Cookies = paramDecoratorFactory(PARAMETER_TYPE.COOKIES); export const Session = paramDecoratorFactory(PARAMETER_TYPE.SESSION); export const Next = paramDecoratorFactory(PARAMETER_TYPE.NEXT); // target, name, decorator function paramDecoratorFactory(parameterType: PARAMETER_TYPE): (name?: string) => ParameterDecorator { // 返回一个函数 return (name?: string): ParameterDecorator => { // 返回 ParameterDecorator 类型参数装饰器 name = name || "default"; return Params(parameterType, name); }; } export function Params(type: PARAMETER_TYPE, parameterName: string) { return function (target: object, methodName: string, index: number) { let metadataList: interfaces.ControllerParameterMetadata = {}; let parameterMetadataList: interfaces.ParameterMetadata[] = []; const parameterMetadata: interfaces.ParameterMetadata = { index: index, parameterName: parameterName, type: type, }; if (!Reflect.hasOwnMetadata(METADATA_KEY.controllerParameter, target.constructor)) { parameterMetadataList.unshift(parameterMetadata); } else { metadataList = Reflect.getOwnMetadata(METADATA_KEY.controllerParameter, target.constructor); if (metadataList.hasOwnProperty(methodName)) { parameterMetadataList = metadataList[methodName]; } parameterMetadataList.unshift(parameterMetadata); } metadataList[methodName] = parameterMetadataList; Reflect.defineMetadata(METADATA_KEY.controllerParameter, metadataList, target.constructor); }; } const Before = (reducer: (args: any, req: express.Request, res: express.Response, next: express.NextFunction) => any[]) => (target: object, key: any) => { if (key) { Reflect.defineMetadata(METADATA_KEY.controllerAfter, reducer, target.constructor, key) } else { Reflect.defineMetadata(METADATA_KEY.controllerAfter, reducer, target.constructor) } } const After = (reducer: (result: Promise<any>, req: express.Request, res: express.Response, next: express.NextFunction) => void) => (target: object, key: any) => { if (key) { Reflect.defineMetadata(METADATA_KEY.controllerAfter, reducer, target.constructor, key) } else { Reflect.defineMetadata(METADATA_KEY.controllerAfter, reducer, target.constructor) } } export const SSR = (path?: string) => After((result, req, res) => { const contentType = req.headers['content-type'] if (contentType && contentType.includes('application/json')) { return res.json(result) } res.ssr(path, result) }) export const ResponseBody = After((result, req, res) => { if (result instanceof Error) { res.json({ status: 0, msg: '文本地址重复,请在原地址上修改或者维护新的地址', }) return }) export const ResponseData = After((result, req, res) => { res.json( result, ) }) <file_sep>import { Container, inject, injectable } from 'inversify'; import { autoProvide, makeProvideDecorator, makeFluentProvideDecorator } from 'inversify-binding-decorators'; import getDecorators from 'inversify-inject-decorators'; let container = new Container(); let { lazyInject } = getDecorators(container) let provide = makeProvideDecorator(container) let fluentProvider = makeFluentProvideDecorator(container) let provideNamed = function (identifier: any, name: string) { return fluentProvider(identifier) .whenTargetNamed(name) .done(); } let provideSingleton = function (identifier: any) { return fluentProvider(identifier) .inSingletonScope() .done(); } export { container, autoProvide, provide, provideSingleton, provideNamed, inject, lazyInject, injectable }<file_sep># gateway 配合 [reactSPA](https://github.com/MuYunyun/reactSPA) 使用的服务端(网关层)项目 ### Usage ``` 本地运行 npm start 启动服务器 npm run compile 编译 ts 成 js 文件 ``` ### Tech Stack - [x] TypeScript + Node.js - [ ] 跨域 - [ ] 尝试 React 服务端渲染
71454d379fa06a44898323d5a97886eca9c53413
[ "Markdown", "TypeScript" ]
13
TypeScript
shuiqin/gateway
0b8d24a7ca1400afd8376a602fe28202aa3ea9ad
639ea32b8395e5f103903cb4a1bc19012f13a1ac
refs/heads/master
<file_sep>import devices from 'puppeteer/DeviceDescriptors'; const supportDevice = { BlackberryPlayBook: 'Blackberry PlayBook', BlackberryPlayBookLandscape: 'Blackberry PlayBook landscape', BlackBerryZ30: 'BlackBerry Z30', BlackBerryZ30Landscape: 'BlackBerry Z30 landscape', GalaxyNote3: 'Galaxy Note 3', GalaxyNote3Landscape: 'Galaxy Note 3 landscape', GalaxyNoteII: 'Galaxy Note II', GalaxyNoteIILandscape: 'Galaxy Note II landscape', GalaxySIII: 'Galaxy S III', GalaxySIIILandscape: 'Galaxy S III landscape', GalaxyS5: 'Galaxy S5', GalaxyS5Landscape: 'Galaxy S5 landscape', iPad: 'iPad', iPadLandscape: 'iPad landscape', iPadMini: 'iPad Mini', iPadMiniLandscape: 'iPad Mini landscape', iPadPro: 'iPad Pro', iPadProLandscape: 'iPad Pro landscape', iPhone4: 'iPhone 4', iPhone4Landscape: 'iPhone 4 landscape', iPhone5: 'iPhone 5', iPhone5Landscape: 'iPhone 5 landscape', iPhone6: 'iPhone 6', iPhone6Landscape: 'iPhone 6 landscape', iPhone6Plus: 'iPhone 6 Plus', iPhone6PlusLandscape: 'iPhone 6 Plus landscape', KindleFireHDX: 'Kindle Fire HDX', KindleFireHDXLandscape: 'Kindle Fire HDX landscape', LGOptimusL70: 'LG Optimus L70', LGOptimusL70Landscape: 'LG Optimus L70 landscape', MicrosoftLumia550: 'Microsoft Lumia 550', MicrosoftLumia950: 'Microsoft Lumia 950', MicrosoftLumia950Landscape: 'Microsoft Lumia 950 landscape', Nexus10: 'Nexus 10', Nexus10Landscape: 'Nexus 10 landscape', Nexus4: 'Nexus 4', Nexus4Landscape: 'Nexus 4 landscape', Nexus5: 'Nexus 5', Nexus5Landscape: 'Nexus 5 landscape', Nexus5X: 'Nexus 5X', Nexus5XLandscape: 'Nexus 5X landscape', Nexus6: 'Nexus 6', Nexus6Landscape: 'Nexus 6 landscape', Nexus6P: 'Nexus 6P', Nexus6PLandscape: 'Nexus 6P landscape', Nexus7: 'Nexus 7', Nexus7Landscape: 'Nexus 7 landscape', NokiaLumia520: 'Nokia Lumia 520', NokiaLumia520Landscape: 'Nokia Lumia 520 landscape', NokiaN9: 'Nokia N9', NokiaN9Landscape: 'Nokia N9 landscape', }; const checkIfOptions = options => (typeof options === 'object' && 'viewport' in options && 'userAgent' in options); const checkIfSupportDevice = device => supportDevice[device] !== undefined; function filterEmulateInfos(options) { switch (true) { case checkIfOptions(options): return options; case checkIfSupportDevice(options): return devices[supportDevice[options]]; default: // eslint-disable-next-line no-console if (options !== undefined) console.warn('skip page.emulate'.warn); return false; } } export default filterEmulateInfos; <file_sep>import puppeteer from 'puppeteer'; import colors from 'colors'; import filterEmulateInfos from './filterEmulateInfos'; import initPage2imageKits from './kits'; colors.setTheme({ info: 'green', data: 'grey', warn: 'yellow', debug: 'blue', error: 'red', path: 'white', }); function checkBeforeRun(config, callback) { if (config) return callback(config); return Promise.resolve('skip'); } class Screenshot { async init(config) { this.updateConfig(config); if (!this.browser) this.browser = await puppeteer.launch(this.config.launchConfig); } updateConfig(config) { Object.assign(this.config, config); } async takeScreenshot(url) { if (!url) return null; await checkBeforeRun(!this.browser, this.init.bind(this)); const page = await this.browser.newPage(); const { evaluate, waitUntil, screenshotConfig, viewportConfig, emulateConfig, disableJS, selector, } = this.config; if (screenshotConfig.path) screenshotConfig.path = screenshotConfig.path.replace(/\?.*\./, '.'); // ? Symbol will cause windows user cannot save file await checkBeforeRun(viewportConfig, page.setViewport.bind(page)); await checkBeforeRun(filterEmulateInfos(emulateConfig), page.emulate.bind(page)); await checkBeforeRun(disableJS, page.setJavaScriptEnabled.bind(page, false)); await page.goto(url, { waitUntil }); await page.evaluate(initPage2imageKits); await checkBeforeRun(evaluate, () => ( page.evaluate(evaluate.func, evaluate.args) )); async function takeScreenshot() { if (selector) { delete screenshotConfig.fullPage; const element = await page.$(selector); if (!element) throw new Error(`element selector "${selector}" can not find any element`); return element.screenshot(screenshotConfig); } else { return page.screenshot(screenshotConfig); } } const pic = await takeScreenshot(); page.close(); return pic; } constructor(config) { this.config = Object.assign({ evaluate: null, waitUntil: null, viewportConfig: null, selector: null, screenshotConfig: { quality: 80, type: 'jpeg', fullPage: true, }, }, config); } } export default Screenshot; <file_sep>#! /usr/bin/env node const shell = require('shelljs'); const babel = 'node_modules/.bin/babel'; const command = [ `${babel} app.js --out-file index.js`, `${babel} src --out-dir lib`, `${babel} bin --ignore build --out-dir buildBin`, ]; shell .exec(`${command.join(' && ')}`); <file_sep>const Screenshot = require('../').default; const screenshot = new Screenshot({ waitUntil: 'networkidle2', viewportConfig: { width: 1920, height: 100 }, screenshotConfig: { fullPage: true, path: 'screenshot_with_full_page.png' }, launchConfig: { args: [ '--no-sandbox', '--disable-setuid-sandbox', ], }, }); screenshot.takeScreenshot('https://github.com/Runjuu') .then(() => { screenshot.updateConfig({ selector: '.js-contribution-graph', screenshotConfig: { path: 'screenshot_with_element.png' }, }); return screenshot.takeScreenshot('https://github.com/Runjuu'); }) .then(process.exit); <file_sep># 📷 page2image [![npm version](https://badge.fury.io/js/page2image.svg)](https://www.npmjs.com/package/page2image) [![Total downloads](https://img.shields.io/npm/dt/page2image.svg)](https://www.npmjs.com/package/page2image) [![Build Status](https://travis-ci.org/Runjuu/page2image.svg?branch=master)](https://travis-ci.org/Runjuu/page2image) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/Runjuu/page2image/pulls) [![Greenkeeper badge](https://badges.greenkeeper.io/Runjuu/page2image.svg)](https://greenkeeper.io/) [![MIT Licence](https://badges.frapsoft.com/os/mit/mit.svg?v=103)](https://opensource.org/licenses/mit-license.php) page2image is an npm package using [Headless Chrome](https://developers.google.com/web/updates/2017/04/headless-chrome) for taking screenshots which also provides [CLI](https://github.com/Runjuu/page2image#using-by-cli-️) command ## Using By Module 📦 ### Install ```bash npm i page2image --save ``` ### Quick Examples ```js import Screenshot from 'page2image'; const screenshot = new Screenshot({ waitUntil: 'networkidle2', viewportConfig: { width: 1920, height: 1080 }, screenshotConfig: { fullPage: true, path: 'screenshot.png' }, }); screenshot  .takeScreenshot('https://github.com/Runjuu') .then(process.exit); ``` ### Methods #### takeScreenshot(url:string) Accept a url string as an argument and return an image Buffer #### init([Config](https://github.com/Runjuu/page2image#config)) Accept a [Config](https://github.com/Runjuu/page2image#config) object and next time calling takeScreenshot will using new config to take screenshot ### Config: {} - [waitUntil](https://github.com/GoogleChrome/puppeteer/blob/v1.2.0/docs/api.md#pagegotourl-options) - [evaluate](https://github.com/GoogleChrome/puppeteer/blob/v0.12.0/docs/api.md#pageevaluatepagefunction-args) - [viewportConfig](https://github.com/GoogleChrome/puppeteer/blob/v0.12.0/docs/api.md#pagesetviewportviewport) - [screenshotConfig](https://github.com/GoogleChrome/puppeteer/blob/v0.12.0/docs/api.md#pagescreenshotoptions) - disableJS <[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)> - whether or not to disable JavaScript on the page. Defaults to `false` - [emulateConfig](https://github.com/GoogleChrome/puppeteer/blob/v1.2.0/docs/api.md#pageemulateoptions) - [selector](https://github.com/GoogleChrome/puppeteer/blob/v1.2.0/docs/api.md#pageselector) - if `selector` is valid, page2image will [take screenshot for selected element](https://github.com/GoogleChrome/puppeteer/blob/v1.2.0/docs/api.md#elementhandlescreenshotoptions) --- ## Using By CLI ⌨️ ### Install ```bash npm i page2image --global ``` ### Quick Examples ```bash # Single page > page2image https://github.com/Runjuu --type=jpeg --quality=80 # Multi-page > page2image https://github.com/Runjuu https://github.com/Runjuu --type=jpeg --quality=80 # Local file > page2image ./index.html --type=jpeg --quality=80 ``` ### Args \<argv\>: \<default value\> #### width: 1366 > Page width in pixels. #### height: 768 > Page height in pixels, default will take a full page screenshot. #### type: png > Specify screenshot type, could be either 'jpeg' or 'png'. #### quality: 100 > The quality of the image, between 0-100. Not applicable to png images. #### dpr: 2 > Specify device scale factor. #### selector: null > take a screenshot for the selected element ```bash page2image https://github.com/Runjuu --selector=".js-contribution-graph" ``` #### disableJS: false > To disable JavaScript on the page. #### waitUntil: networkidle2 > When to consider navigation succeeded. [more details](https://github.com/GoogleChrome/puppeteer/blob/v1.2.0/docs/api.md#pagegotourl-options) #### sleep: 0 ##### if sleep is a number > Wait ${sleep} milliseconds to take screenshot. ##### if sleep is a selector > Wait for the selector to appear in page #### emulate: false > List of all available devices is available in the [source code](https://github.com/Runjuu/page2image/blob/master/src/filterEmulateInfos.js). Below is an example of using `emulate` args to emulate iPhone 6 ```bash page2image https://github.com/Runjuu --emulate=iPhone6 ``` #### scrollToBottom: false > Wait till viewport scroll to the bottom of the page #### named: \<default using url to named\> > Name of screenshot #### path: \<default using current path\> > Path to save the screenshot ```bash page2image https://github.com/Runjuu --path=../ page2image https://github.com/Runjuu --path=/User/someone/ page2image https://github.com/Runjuu --path=~/Downloads ``` <br/><hr/> # To Do - [x] take screenshots via url - [x] take screenshots from local html file - [ ] take multiple screenshots from file ### 🤔 have any questions? 👉 [new issues](https://github.com/Runjuu/page2image/issues/new) 😉 <file_sep>#### Node.js & npm version Node.js: `node -v`; npm: `npm -v` #### Operating system: #### Description of the bug: #### Example CLI command or javascript code to reproduce the error ``` ``` #### Error infos: ```bash ``` <file_sep>function initPage2imageKits() { function autoScrollToBottom() { autoScrollToBottom.start = true; autoScrollToBottom.end = false; function scroll() { const { clientHeight } = document.documentElement; const scrollTimes = document.body.scrollHeight / clientHeight; autoScrollToBottom.count = autoScrollToBottom.count + 1 || 0; if (autoScrollToBottom.count < scrollTimes) { window.scrollTo(0, autoScrollToBottom.count * clientHeight); setTimeout(scroll, 300); } else { autoScrollToBottom.end = true; } } scroll(); } function scrollToBottom() { if (!autoScrollToBottom.start) autoScrollToBottom(); return autoScrollToBottom.end; } function checkIfImageBeenLoaded() { const imageList = Array.from(document.getElementsByTagName('img')); return imageList.length <= imageList.reduce((loaded, imageElm) => ( imageElm.complete ? loaded + 1 : loaded ), 0); } window.page2image = { scrollToBottom, checkIfImageBeenLoaded, }; } export default initPage2imageKits;
fe8033953383809574d394adbd78c83363b2bcab
[ "JavaScript", "Markdown" ]
7
JavaScript
geekwolverine/page2image
a4f58e1abf4ad7d7cb38c6e71419a2891927ae60
90fd097c9ef83968e01f034d93cac816f582bfcc
refs/heads/master
<file_sep># docker-postfix Postfix running in the foreground inside a docker container. Configured via files mounted at: /config/master with changes for settings usually configured in master.cf. /config/main with changes for settings usually configured in main.cf. Each line in /config/master that starts with '-' is passed to `postconf` verbatim. All other lines are passed to `postconf -M`. Eeach line in /config/main is passed to `postconf` verbatim. Additionally any environment variable prefixed with POSTFIX_ is passed to `postconf`. POSTFIX_{name}={value} -> postconf {name}={value} e.g. POSTFIX_myhostname=some.cool.name -> `postconf myhostname=some.cool.name` Settings from environment variables take precedence over those in config files. <file_sep>#!/bin/sh #set -x # Apply configuration to /etc/postfix/master.cfg. if [ -f /config/master ]; then while read -r line; do [ -z "$line" ] && continue [ "${line:0:1}" = "#" ] && continue [ "${line:0:4}" = "#EOF" ] && break # nuke leading and trailing whitespace config="$(echo $line)" case "$config" in "-*") # Support any of the master.cf related options like -M, -F, -P echo "postconf $config" postconf $config ;; *) # Default to -M echo "postconf -M $config" postconf -M "$config" ;; esac done < /config/master fi # Apply configuration to /etc/postfix/main.cfg. if [ -f /config/main ]; then while read -r line; do [ -z "$line" ] && continue [ "${line:0:1}" = "#" ] && continue [ "${line:0:4}" = "#EOF" ] && break # nuke leading and trailing whitespace config="$(echo $line)" echo "postconf $config" postconf "$config" done < /config/main fi # Environment variables override configuration from /config/main. # POSTFIX_{name}={value} -> postconf {name}={value} env | grep ^POSTFIX_ | sed 's/^POSTFIX_//' \ | while read -r config; do echo "postconf $config" postconf "$config" done # Log to stdout. postconf "maillog_file=/dev/stdout" # Unclean container stop might leave pid files around. rm -f /var/spool/postfix/pid/master.pid # Ensure we can write our stuff. chown postfix:root /var/lib/postfix chown -R postfix: /var/lib/postfix/* chown root:root /var/spool/postfix postalias /etc/postfix/aliases [ -d /var/spool/postfix/etc ] && { cp /etc/hosts /var/spool/postfix/etc/hosts } postfix check postfix set-permissions # Run in foreground. exec postfix start-fg <file_sep>REGISTRY = docker.io IMG_NAMESPACE = asteven IMG_NAME = postfix IMG_FQNAME = $(REGISTRY)/$(IMG_NAMESPACE)/$(IMG_NAME) IMG_VERSION = 0.1.7 # Prefere podman over docker for building. BUILDER = $(shell which podman || which docker) .PHONY: container push clean all: container container: # Build the runtime stage sudo $(BUILDER) build --pull \ --tag $(IMG_FQNAME):$(IMG_VERSION) \ --tag $(IMG_FQNAME):latest . push: sudo $(BUILDER) push $(IMG_FQNAME):$(IMG_VERSION) docker://$(IMG_FQNAME):$(IMG_VERSION) # Also update :latest sudo $(BUILDER) push $(IMG_FQNAME):latest docker://$(IMG_FQNAME):latest clean: sudo $(BUILDER) rmi $(IMG_FQNAME):$(IMG_VERSION) sudo $(BUILDER) rmi $(IMG_FQNAME):latest <file_sep>FROM docker.io/alpine:3 LABEL maintainer "<NAME> <<EMAIL>>" RUN echo '@edge http://dl-cdn.alpinelinux.org/alpine/edge/main' >> /etc/apk/repositories \ && echo '@edgecommunity http://dl-cdn.alpinelinux.org/alpine/edge/community' >> /etc/apk/repositories \ && echo '@testing http://dl-cdn.alpinelinux.org/alpine/edge/testing' >> /etc/apk/repositories RUN apk --no-cache add --upgrade apk-tools@edge; \ apk --no-cache update; \ apk --no-cache add tini \ postfix openssl # Tini is now available at /sbin/tini ENTRYPOINT ["/sbin/tini", "--"] EXPOSE 25 COPY entrypoint.sh /entrypoint.sh RUN chmod 0755 /entrypoint.sh CMD ["/entrypoint.sh"]
30bad34e5e24ba57d3619596c6dae291cecf89bb
[ "Markdown", "Makefile", "Dockerfile", "Shell" ]
4
Markdown
asteven/docker-postfix
6f4ac3b25ac40d1ebb5e7fd7ff14fd2b5246d06d
d7e4c80724e98be42e1a2ae3e759ae3744bba482
refs/heads/master
<file_sep>package com.palindrome.service; import com.palindrome.common.PalindromeDescComparator; import com.palindrome.view.PalindromeResponse; import com.palindrome.dto.nasa.Innovator; import com.palindrome.dto.nasa.Patent; import com.palindrome.dto.nasa.PatentReport; import com.palindrome.exception.PalindromeException; import com.palindrome.util.PalindromeUtil; import com.palindrome.util.PalindromeValidationHelper; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; /** * * @author suleimanalrosan - Jul 29, 2016 */ @Service public class PalindromeService { @Autowired private PalindromeUtil palindromeUtil; public static final String NASA_PATTENT_URL_FORMAT = "https://api.nasa.gov/patents/content?query=%s&limit=%s&api_key=DEMO_KEY"; Logger LOG = Logger.getLogger(PalindromeService.class); /** * get back part of NASA patent report for particular search string * * @param search * @param limit * @return * @throws com.palindrome.exception.PalindromeException */ public PatentReport getPatentReport(String search, int limit) throws PalindromeException { PalindromeValidationHelper.validateLimit(limit); RestTemplate restTemplate = new RestTemplate(); PatentReport patentReport = restTemplate.getForObject(String.format(NASA_PATTENT_URL_FORMAT, search, limit), PatentReport.class); //LOG.info(patentReport.toString()); return patentReport; } /** * Calculates the number of palindromic strings that can be created using * the provided string. * * @param search * @param limit * @return * @throws com.palindrome.exception.PalindromeException */ public List<PalindromeResponse> calculatePalindrome(String search, int limit) throws PalindromeException { PatentReport patentReport = getPatentReport(search, limit); List<PalindromeResponse> result = new ArrayList<>(); for (Patent p : patentReport.getResults()) { for (Innovator i : p.getInnovators()) { String fullName = i.getfName() + " " + i.getlName(); result.add(new PalindromeResponse(fullName, palindromeUtil.palindromeCount(fullName))); } } Collections.sort(result, new PalindromeDescComparator()); return result; } } <file_sep>Palindrome Challenge ==================== Write an API that searches [NASA patents](https://api.nasa.gov/api.html#patents) and determines the number of [palindromic](https://en.wikipedia.org/wiki/Palindrome) strings that can be created from inventor's name. Details ------- The implementation should expose a service at the following entry point: ``` GET /palindromes ``` The service accepts the following parameters: Name | Required | Default | Description ---- | -------- | ------- | ----------- `search` | yes | - | patent search text `limit` | no | 1 | number of patents considered (min:1, max:5) Request example: ``` GET /palindromes?search=electricity&limit=3 ``` The service should search the NASA patents for given text and retrieve up to given number of patents. For each extracted inventor, first and last name should be concatenated into a single string (e.g. `"Graham"` and `"Bell"` becomes `"<NAME>"`). For each such name the service should calculate the number of palindromic strings that can be created using the name letters. Name should be treated as case-insensitive (i.e. `b` and `B` is the same letter) and all white-spaces should be ignored. A valid palindromic string is one that uses only the letters in the given name, and is the same length as the given name. Each letter can be used more than once, and not every letter must be used. For example, given the name `"<NAME>"`, `"aaahhhhaaa"` and `"bellmmlleb"` are valid, but `"aaa"` and `"hhhsagtbbb"` are not. Results should be returned in JSON format sorted by the count, highest to lowest. Response example (with actual palindrome counts): ``` [ { "name": "<NAME>", "count": 531441 }, { "name": "<NAME>", "count": 32768 }, { "name": "<NAME>", "count": 16807 }, { "name": "<NAME>", "count": 7776 } ] ``` Constraints ----------- Choice of languages, frameworks and libraries is limited to a JVM-based technology. Solution ======== We can find all possible palindromes of a particular string by looking up all possible permutations. However, this is a brute force solution and would cost O(N!) where n is the length of the string. A palindrome string must have an even number of characters and at most one odd number of characters in the center. For example: ``` aabb aaacbbb ``` So, we get the count of all possible palindromes by calculating all possible premutations of half of the sting with respect to the odd number. ``` Example 1: let s = "ab" => the allowed set of charchters k =3 => the string size Then possible palindromes is 4: aaa bbb aba bab Example 2: let s = "abc" => the allowed set of charchters k =3 => the string size Then possible palindromes is 9: aaa bbb ccc aba aca bab bcb cac cbc Exmaple 3: let s = "abc" => the allowed set of charchters k =4 => the string size Then possible palindromes is 9: aaaa bbbb cccc abba acca baab bccb caac cbbc ``` So, for a string with length K which has N number of unique characters, the count of all possible palindromes is N to the power of half K ``` Count = N^(K/2 + K%2) ``` Project Layout ============= The project uses Spring boot to run the rest service and it has the following layout: ``` . ├── pom.xml ├── src │   ├── main │   │   ├── java │   │   │   └── com │   │   │   └── palindrome │   │   │   ├── common │   │   │   │   └── PalindromeDescComparator.java │   │   │   ├── config │   │   │   │   └── SwaggerConfig.java │   │   │   ├── controller │   │   │   │   ├── ErrorController.java │   │   │   │   └── PalindromeController.java │   │   │   ├── dto │   │   │   │   └── nasa │   │   │   ├── exception │   │   │   │   └── PalindromeException.java │   │   │   ├── main │   │   │   │   └── Application.java │   │   │   ├── service │   │   │   │   └── PalindromeService.java │   │   │   ├── util │   │   │   │   ├── PalindromeUtil.java │   │   │   │   └── PalindromeValidationHelper.java │   │   │   └── view │   │   │   ├── BaseResponse.java │   │   │   └── PalindromeResponse.java │   │   └── resources │   │   └── application.properties │   └── test │   └── java │   └── com │   └── palindrome │   └── util │   └── PalindromeUtilTest.java ``` You can find the actual algorithm solution in the following java class ``` PalindromeUtil.java ``` Running the project ====================== Before running the project, make sure you have the following installed in your machine: * Java 1.7 * Maven From IDE: -------- You can start the project from IDE by running the main method from Application.java From Command line: ----------------- ``` mvn spring-boot:run ``` The service runs on port 8080 so you can access the service using: ``` http://localhost:8080/palindromes?search=[Search String]&limit=[number from 1-5] ``` Additionally, you can access the service's documentation for all implemented operations thorough the following link: ``` http://localhost:8080/swagger-ui.htm ```` <file_sep>/* * 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.palindrome.util; import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import static org.junit.Assert.*; import org.junit.Test; /** * * @author suleimanalrosan */ public class PalindromeUtilTest { private Map<String, Long> source; private PalindromeUtil palindromeUtil; public PalindromeUtilTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { palindromeUtil = new PalindromeUtil(); source = new HashMap<>(); source.put("<NAME>", 531441L); source.put("<NAME>", 32768L); source.put("<NAME>", 16807L); source.put("<NAME>", 7776L); source.put("", 0L); } @After public void tearDown() { } /** * Test of palindromeCount method, of class PalindromeUtil. */ @org.junit.Test public void testPalindromeCount() { for (String input : source.keySet()) { Long expResult = source.get(input); Long result = palindromeUtil.palindromeCount(input); assertEquals(expResult, result); } } @org.junit.Test(expected=IllegalArgumentException.class) public void testPalindromeCountWithNull() { palindromeUtil.palindromeCount(null); } } <file_sep>package com.palindrome.dto.nasa; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * * @author suleimanalrosan - Jul 29, 2016 */ @JsonIgnoreProperties(ignoreUnknown = true) public class Patent { @JsonProperty("innovator") private List<Innovator> innovators; @JsonProperty("client_record_id") private String clientRecordId; public List<Innovator> getInnovators() { return innovators; } public void setInnovators(List<Innovator> innovators) { this.innovators = innovators; } public String getClientRecordId() { return clientRecordId; } public void setClientRecordId(String clientRecordId) { this.clientRecordId = clientRecordId; } } <file_sep>package com.palindrome.common; import com.palindrome.view.PalindromeResponse; import java.util.Comparator; /** * * @author suleimanalrosan - Jul 29, 2016 */ public class PalindromeDescComparator implements Comparator<PalindromeResponse> { @Override public int compare(PalindromeResponse o1, PalindromeResponse o2) { if (o1.getCount().equals(o2.getCount())) { return 0; } else { return o1.getCount() > o2.getCount() ? -1 : 1; } } }
bea67ba33ff538c2925e81dc72577dabd911cf54
[ "Markdown", "Java" ]
5
Java
suleimana/palindrome-challenge
78adb427da31278b831ec7ff0f6e9f04175732dc
c3b6532071ee02ae4c5c7caed03201859033d0a1
refs/heads/master
<repo_name>myeongjinkim/MP3-Player-app-UI<file_sep>/app/src/main/java/com/example/hw_3/ui/home/HomeFragment.java package com.example.hw_3.ui.home; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.annotation.NonNull; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import com.example.hw_3.R; import com.example.hw_3.databinding.FragmentHomeBinding; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.audio.mp3.MP3File; import org.jaudiotagger.tag.FieldKey; import org.jaudiotagger.tag.Tag; import org.jaudiotagger.tag.id3.AbstractID3v2Tag; import java.io.File; import java.io.IOException; public class HomeFragment extends Fragment { //ui 및 구조 private HomeViewModel homeViewModel; private FragmentTransaction ft; public FragmentHomeBinding binding; private HomeLyricsFragment homeLyricsFragment; private HomeJacketFragment homeJacketFragment; private boolean start = false; private boolean check =true; private TextView titleText; private TextView artistText; //mp3 private MediaPlayer mediaPlayer; private SeekBar seekbar; private int nowSeek; private int maxSeek; private TextView maxSeekText; private TextView nowSeekText; private File fs; private StringBuilder path; private String musicPath; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 화면 전환 프래그먼트 선언 및 초기 화면 설정 homeLyricsFragment = new HomeLyricsFragment(); homeJacketFragment = new HomeJacketFragment(); path=new StringBuilder(); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_home, container, false); homeViewModel = ViewModelProviders.of(getActivity()).get(HomeViewModel.class); titleText = (TextView) rootView.findViewById(R.id.music_title); artistText = (TextView) rootView.findViewById(R.id.music_artist); nowSeekText = (TextView) rootView.findViewById(R.id.nowSeekTextView); maxSeekText = (TextView) rootView.findViewById(R.id.maxSeekTextView); path.append("/data/data/com.example.hw_3/music/"); fs = new File(path.toString()); music(); mediaPlayer = MediaPlayer.create(getActivity(), Uri.parse(musicPath)); seekbar = (SeekBar)rootView.findViewById(R.id.seekBar); maxSeek= mediaPlayer.getDuration(); seekbar.setMax(maxSeek); maxSeekText.setText(changeTime(maxSeek)); seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // TODO Auto-generated method stub if(fromUser) { mediaPlayer.seekTo(progress); nowSeek = progress; nowSeekText.setText(changeTime(nowSeek)); } } }); if( homeViewModel.getCheck()){ replaceToJacket(); }else{ replaceToLyrics(); } binding = DataBindingUtil.bind(rootView); binding.setFragment(this); return rootView; } public void replaceToJacket(){ ft = getChildFragmentManager().beginTransaction(); ft.addToBackStack(null); ft.replace(R.id.replace, homeJacketFragment); ft.commit(); } public void replaceToLyrics(){ ft = getChildFragmentManager().beginTransaction(); ft.addToBackStack(null); ft.replace(R.id.replace, homeLyricsFragment); ft.commit(); } public void pressPlay(View v){ if(mediaPlayer.isPlaying()){ ((ImageButton)v).setImageResource(R.drawable.ic_action_play); mediaPlayer.stop(); try { mediaPlayer.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }else { ((ImageButton)v).setImageResource(R.drawable.ic_action_stop); nowSeek = mediaPlayer.getCurrentPosition(); mediaPlayer.seekTo(nowSeek); // 일시정지 시점으로 이동 mediaPlayer.start(); Thread(); } } public void Thread(){ Runnable task = new Runnable(){ public void run(){ while(mediaPlayer.isPlaying()){ try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Message msg =handler.obtainMessage(); handler.sendMessage(msg); } } }; Thread thread = new Thread(task); thread.start(); } Handler handler = new Handler(){ public void handleMessage(Message msg){ nowSeek = mediaPlayer.getCurrentPosition(); seekbar.setProgress(nowSeek); nowSeekText.setText(changeTime(nowSeek)); } }; private String changeTime(int intTime){ String min; String sec; intTime = intTime/1000; if((intTime/60)<10){ min = "0"+Integer.toString(intTime/60); }else{ min = Integer.toString(intTime/60); } if((intTime%60)<10){ sec= "0"+Integer.toString(intTime%60); }else{ sec= Integer.toString(intTime%60); } return min+":"+sec; } public void music(){ if(fs.isDirectory()){ System.out.println("들어감"); String decoding = "ISO-8859-1"; String encoding = "EUC-KR"; File list[] = fs.listFiles(); for(File f : list){ try{ MP3File mp3 = (MP3File) AudioFileIO.read(f); musicPath = f.getPath(); AbstractID3v2Tag tag2 = mp3.getID3v2Tag(); Tag tag = mp3.getTag(); homeViewModel.LyricsSetting(tag.getFirst(FieldKey.LYRICS)); titleText.setText(tag.getFirst(FieldKey.TITLE)); artistText.setText(tag.getFirst(FieldKey.ARTIST)); }catch(Exception ex){ ex.printStackTrace(); } } } else { System.out.println("경로 틀림"); } } }<file_sep>/settings.gradle include ':app', ':jaudiotagger-2.2.6-SNAPSHOT', ':jaudiotagger-2.2.3', ':jaudiotagger-2.2.0-20130321.142353-1' rootProject.name='hw_3' <file_sep>/README.md # hw_3 - MP3 Player ## 테스트 환경 유형 : Pixel 2 API 24 타겟 안드로이드 버전 : 7.0 안드로이드 스튜디오 버전 : 3.5 테스트 PC OS : Windows10 x64 테스트 PC 프로세서 : Intel i5-8265U 테스트 PC RAM : 8GB 사용 된 메모리 : 1232Mb 미만 사용 된 CPU : 15 % 미만 ## 개발 개발 언어 : JAVA # UI 구현 ## 음악듣기 ![Alt text](./my_image/play_music.jpg) ## 음악듣기 - 가사 화면 ![Alt text](./my_image/lyrics.jpg) ## 네비게이션 화면 ![Alt text](./my_image/navi.jpg) ## 최근 음악 화면 ![Alt text](./my_image/recent_music.jpg) ## 음악 라이브러리 화면 ![Alt text](./my_image/library.jpg) ## 설정 화면 ![Alt text](./my_image/setting.jpg) # 코드 구현 ## 안드로이드 기본 구조 ![Alt text](./my_image/android.jpg) ![Alt text](./my_image/android_dalvik.jpg) 화면 전환을 Activity의 전환으로 하지 않는다. 모든 화면의 전환은 fragment의 전환으로 구성했다. ## Date Binding 어플리케이션에서 화면에 있는 UI요소와 데이터를 연결시키는 것으로 코드 분리를 통한 최적화의 방법이다. ## AAC(Andorid Architecture Component) - viewModel UI 관련 데이터를 보관하고, 관리하기 위해 디자인되었다. 화면 전환과 같이 설정이 변경되는 상황에서도 data가 계속 남아있을 수 있도록 해준다. 각 Fragment간 데이터 전달 시에 추가적인 작업을 할 필요가 없다. 각 Fragment는 다른 Fragment의 라이프사이클을 신경쓰지 않고, 자신의 라이프사이클 대로 작업을 수행할 수 있다. 그러므로 다른 Fragment가 사라지더라도 정상적으로 동작할 수 있다.
3f3f485112b7ae5d7d92d6c2bcf5162ee6687120
[ "Markdown", "Java", "Gradle" ]
3
Java
myeongjinkim/MP3-Player-app-UI
bde8fce032c1789c3f8711d16f8b04523c2f9d75
71d0f7eb4b8f18ee0f2415f24d175e42ac869177
refs/heads/master
<repo_name>BobbaTea/USACO<file_sep>/contest/2018-2019/December - Silver/convention2.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Scanner; // Time Complexity: O(n^2) // tHiNgS tO oPtImIzE & nOtEs: // Uno: i don't think this is as efficient as it could be public class convention2 { public static void main(String args[]) throws IOException { // file io BufferedReader f = new BufferedReader(new FileReader("convention2.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("convention2.out"))); Scanner c = new Scanner(f.readLine()); int num = c.nextInt(); ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>(); for (int i = 0; i < num; i++) { c = new Scanner(f.readLine()); a.add(new ArrayList<Integer>(Arrays.asList(i, c.nextInt(), c.nextInt()))); } // sort by start time Collections.sort(a, new Comparator<ArrayList<Integer>>() { @Override public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) { return o1.get(1).compareTo(o2.get(1)); } }); int end = 0; ArrayList<ArrayList<Integer>> temp; for (int i = 0; i < num; i++) { temp = new ArrayList<ArrayList<Integer>>(); end = a.get(i).get(1) + a.get(i).get(2); for (int x = i + 1; x < num; x++) { end = a.get(i).get(1) + a.get(i).get(2); if ((x != i) && a.get(x).get(1) <= end) { temp.add(a.get(x)); } else { break; } } Collections.sort(temp, new Comparator<ArrayList<Integer>>() { @Override public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) { return o1.get(0).compareTo(o2.get(0)); } }); a.removeAll(temp); a.addAll(i + 1, temp); } int maxWait = 0; int t = 0; for (int i = 0; i < num; i++) { end = a.get(i).get(1) + a.get(i).get(2); for (int x = i + 1; x < num; x++) { if (a.get(x).get(1) < end) { t = end - a.get(x).get(1); if (t > maxWait) maxWait = t; } else { break; } } } out.println(maxWait); c.close(); f.close(); out.close(); } } <file_sep>/contest/2018-2019/December - Bronze/mixmilk.java package usaco; import java.io.*; import java.util.*; // Time Complexity: O(1) // tHiNgS tO oPtImIzE & nOtEs: // Uno: solution doesn't seem too elegant public class mixmilk { public static void main(String args[]) throws IOException { // file io BufferedReader f = new BufferedReader(new FileReader("mixmilk.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("mixmilk.out"))); String d[] = f.readLine().split(" "); String e[] = f.readLine().split(" "); String g[] = f.readLine().split(" "); int a[] = new int[] { 0, 0 }; for (int i = 0; i < 2; i++) { a[i] = Integer.parseInt(d[i]); } int b[] = new int[] { 0, 0 }; for (int i = 0; i < 2; i++) { b[i] = Integer.parseInt(e[i]); } int c[] = new int[] { 0, 0 }; for (int i = 0; i < 2; i++) { c[i] = Integer.parseInt(g[i]); } // implement the milk mixing for (int i = 0; i < 100; i++) { // if the milk in the current container is less than in the next one // add the milk from current container into the next one // set current container to 0 if (a[1] <= (b[0] - b[1])) { b[1] += a[1]; a[1] = 0; } else { a[1] -= (b[0] - b[1]); b[1] = b[0]; } // increment the number of times milk has been mixed i++; // if it mixing surpasses the max then exit loop if (i >= 100) break; // repeat for next two if (b[1] <= (c[0] - c[1])) { c[1] += b[1]; b[1] = 0; } else { b[1] -= (c[0] - c[1]); c[1] = c[0]; } i++; if (i >= 100) break; // repeat for last two if (c[1] <= (a[0] - a[1])) { a[1] += c[1]; c[1] = 0; } else { c[1] -= (a[0] - a[1]); a[1] = a[0]; } } // print answer out.println(a[1]); out.println(b[1]); out.println(c[1]); // close resources f.close(); out.close(); System.exit(0); } } <file_sep>/training/ride.java /* ID: bobba.a1 LANG: JAVA TASK: ride */ import java.util.*; import java.io.*; public class ride { public static void main(String args[]) throws IOException { BufferedReader fin = new BufferedReader(new FileReader("ride.in")); PrintWriter fout = new PrintWriter(new BufferedWriter(new FileWriter("ride.out"))); StringTokenizer st1 = new StringTokenizer(fin.readLine(), "", false); StringTokenizer st2 = new StringTokenizer(fin.readLine(), "", false); int comet = 1; int group = 1; int temp = 0; StringBuffer sb = new StringBuffer(st1.nextToken()); for (int i = 0; i < sb.length(); i++) { temp = (int) sb.charAt(i) - 64; comet *= temp; } sb = new StringBuffer(st2.nextToken()); temp = 0; for (int i = 0; i < sb.length(); i++) { temp = (int) sb.charAt(i) - 64; group *= temp; } if ((comet % 47) == (group % 47)) { fout.println("GO"); } else { fout.println("STAY"); } fin.close(); fout.close(); } } <file_sep>/README.md # USACO ## Organization ### contest contains all the contest problems I completed over the past contests. ### training contains all the training problems from the USACO site. ### other (coming soon) contains solutions to other problems that are not in the USACO competition or site (general algorithms, leet code, lint code, etc)
49abe1a86d1a6b77f12ad5446153b86458118683
[ "Markdown", "Java" ]
4
Java
BobbaTea/USACO
a913310811455f85ae42af976fa4870154e47bfd
bd703bf28af0debd3d6efda2fe700d6bac116a2c
refs/heads/master
<repo_name>maimai77/kanrk05<file_sep>/config/initializers/session_store.rb # Be sure to restart your server when you modify this file. Kanrk05::Application.config.session_store :cookie_store, key: '_kanrk05_session' <file_sep>/config/unicorn.rb worker_processes 1 timeout 30 preload_app true before_fork do |server, worker| # Replace with MongoDB or whatever if defined?(ActiveRecord::Base) ActiveRecord::Base.connection.disconnect! Rails.logger.info('Disconnected from ActiveRecord') end # # If you are using Redis but not Resque, change this old_pid = "#{server.config[:pid]}.oldbin" if old_pid != server.pid begin sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU Process.kill(sig, File.read(old_pid).to_i) rescue Errno::ENOENT, Errno::ESRCH end end sleep 1 end after_fork do |server, worker| if defined?(ActiveRecord::Base) ActiveRecord::Base.establish_connection end end
b57a7e9470c9a709113c4da040525170bfe613c4
[ "Ruby" ]
2
Ruby
maimai77/kanrk05
9c5fc3ebc5373c8d2186f266310a839777339fd4
b02fb6fe6813d7c1a7f78c555e3307a6fb038389
refs/heads/master
<file_sep>from subprocess import call call([.])
f4e7d9805edd0a3231dfa6a669321d657f53c07d
[ "Python" ]
1
Python
SWVM/learngit
5f5a4dbf8026a634c89d435d02f9a7cd204d8332
adb8d402eb3301fdbc0eb2c58e8d85419c5ad84f
refs/heads/master
<file_sep>import { MyAppService } from './../../my-app.service'; import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; @Component({ selector: 'app-sharepage', templateUrl: './sharepage.component.html', styleUrls: ['./sharepage.component.css'] }) export class SharepageComponent implements OnInit { isLoad:boolean = false; u_id; p_id; today; yesterday; level1:any; level2:any; total; share:boolean = false; choice:boolean = false; constructor(private route: ActivatedRoute, private router: Router, private http: ServiceBaseService, private myjs: MyAppService) { } //获取信息 getInfo() { this.http.httpPost('Home/order/count',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((rs:any)=>{ let total=this.myjs.rund(rs.count); let today=this.myjs.rund(rs.day[0]); let yesterday=this.myjs.rund(rs.day[1]); localStorage.setItem('total_share',total); localStorage.setItem('today_share',today); localStorage.setItem('yesterday_share',yesterday); this.level1=rs.extend_user_id; this.level1.income=this.myjs.rund(rs.extend_user_id.income); this.level1.total=this.myjs.rund(rs.extend_user_id.total); this.level2=rs.secondary_ext_user; this.level2.income=this.myjs.rund(rs.secondary_ext_user.income); this.level2.total=this.myjs.rund(rs.secondary_ext_user.total); }) } //查看更多 goToDetail(type) { this.router.navigate(['/shareDetail',type]) } //点击分享 toShare() { // this.share = true this.choice = true; } closeShare() { this.share = false; } clioschoice() { this.choice = false; } alert(e) { e.stopPropagation(); } ShareAppMessage() { this.choice = false; this.share = true; } ShareTimeline() { this.choice = false; this.router.navigate(['qrCode']) } ngOnInit() { this.http.setTitle('分享赚钱'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.getInfo(); if(!localStorage.getItem('total_share')){ this.total = 0; }else{ this.total = localStorage.getItem('total_share') } if(!localStorage.getItem('today_share')){ this.today = 0; }else{ this.today = localStorage.getItem('today_share') } if(!localStorage.getItem('yesterday_share')){ this.yesterday = 0; }else{ this.yesterday = localStorage.getItem('yesterday_share') } } } <file_sep>import { MyAppService } from './../../my-app.service'; import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; @Component({ selector: 'app-wallet', templateUrl: './wallet.component.html', styleUrls: ['./wallet.component.css'] }) export class WalletComponent implements OnInit { classFlag: number = 0; isLoad:boolean = false; isShow:boolean = false; balance; u_id; p_id; cli = []; show_list; userInfo:any; alertMsg; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; alertBtn:number; cashAll; bankChosenC; bankName; cid; bankCode; constructor(private route: ActivatedRoute, private router: Router, private http: ServiceBaseService, private myService: MyAppService) { } //user接口 ==> 判断会员 getUser() { this.http.httpPost('Home/index/user',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ this.userInfo = data.data }) } changeClass(t){ this.classFlag = t; this.isLoad = true; this.show_list = t //佣金明细 if(t == 0){ this.http.httpPost('Home/order/order_one',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ this.isLoad = false; this.cli = data; for (let i=0;i<data.length;i++){ this.cli[i].pay_ok_time=this.myService.timeGet(data[i].pay_ok_time,"min"); this.cli[i].total=this.myService.rund(data[i].total); } }) }else if(t == 1){ this.http.httpPost('Home/order/order_two',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ this.isLoad = false; this.cli = data; for (let i=0;i<data.length;i++){ this.cli[i].money=this.myService.rund(data[i].money); this.cli[i].user_money=this.myService.rund(data[i].user_money); this.cli[i].total=this.myService.rund(data[i].total); this.cli[i].pay_ok_time=this.myService.timeGet(data[i].pay_ok_time,"min"); } }) }else if(t == 2){ this.http.httpPost('Home/order/order_three',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ this.isLoad = false; this.cli = data; for (let i=0;i<data.length;i++){ this.cli[i].last_money=this.myService.rund(data[i].user_money)+"(提现费"+(data[i].money - data[i].user_money)+")"; this.cli[i].user_money=this.myService.rund(data[i].user_money); this.cli[i].total=this.myService.rund(data[i].total); this.cli[i].pay_ok_time=this.myService.timeGet(data[i].pay_ok_time,"min"); } }) } } //点击提现 goToCash() { if(this.userInfo.status == 0){ this.isShow = true; this.alertMsg = '您还没有进行身份认证'; this.alertBtn = 4; }else if(this.userInfo.status == 1){ this.Toast('正在审核中,请耐心等待','warning') }else if(this.userInfo.status == 3){ this.isShow = true; this.alertMsg = '您的审核被驳回,驳回原因为:'+this.userInfo.remark; this.alertBtn = 4; }else if(this.userInfo.status == 2){ //普通会员下 if(this.userInfo.card_bag_status == 1){ this.isShow = true; this.alertMsg = '成为超级会员开通此功能'; this.alertBtn = 0; }//非会员状态下 else if(this.userInfo.card_bag_status == 0){ this.isShow = true; this.alertMsg = '成为超级会员开通此功能' this.alertBtn = 1; }else{ this.isLoad = true; this.alertBtn = 2; this.http.httpPost('Home/order/balance',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ this.isLoad = false; let last = 2-data.withdrawals_number; if(last > 0){ this.isShow = true; this.alertMsg = '您今日还能提现'+last+'次' }else{ this.Toast('您今日的提现次数已用完,请明天再来尝试','warning') } }) } } } //点击确定时 confirm() { this.isShow = false; //普通会员下 if(this.alertBtn == 0){ this.router.navigate(['/vipCenter',1]) }//非会员下 else if(this.alertBtn == 1){ this.router.navigate(['/member']); }//去提现 else if(this.alertBtn == 2){ this.isLoad = true; this.http.httpPost('Home/order/withdrawals',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ this.isLoad = false; if(data.card.length){ this.cashAll=this.myService.rund(data.total); this.bankChosenC=data.card[0].deposit_number.substr(data.card[0].deposit_number.length-4); this.bankName=data.card[0].deposit_bank; this.cid=data.card[0].id; this.bankCode=data.card[0].code; this.router.navigate(['/cash',this.cashAll,this.bankChosenC,this.bankName,this.cid,this.bankCode]); }else{ this.isShow = true; this.alertMsg = '您还未绑定银行卡,是否立即绑定'; this.alertBtn = 3; } }) } //去绑卡 else if(this.alertBtn == 3){ this.router.navigate(['/replace']) } //去认证 else if(this.alertBtn == 4){ this.router.navigate(['/upload']) } } ngOnInit() { this.http.setTitle('我的钱包'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.balance = this.myService.rund(localStorage.getItem('balance')); this.changeClass(0); this.getUser(); } noDelete(){ this.isShow = false; } hide(){ this.isShow = false } alert(e){ e.stopPropagation(); } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { QrCodeComponent } from './page/qr-code/qr-code.component'; import { LoginComponent } from './page/login/login.component'; import { UpLoadComponent } from './page/up-load/up-load.component'; import { PartnerComponent } from './page/partner/partner.component'; import { SecurityCenterComponent } from './page/security-center/security-center.component'; import { VipCenterComponent } from './page/vip-center/vip-center.component'; import { AddBankCardComponent } from './page/add-bank-card/add-bank-card.component'; import { QrcodeComponent } from './page/qrcode/qrcode.component'; import { MemberShipComponent } from './page/member-ship/member-ship.component'; import { MemberComponent } from './page/member/member.component'; import { GetCashComponent } from './page/get-cash/get-cash.component'; import { WalletComponent } from './page/wallet/wallet.component'; import { PayInstallComponent } from './page/pay-install/pay-install.component'; import { AddPayCardComponent } from './page/add-pay-card/add-pay-card.component'; import { AddTaskComponent } from './page/add-task/add-task.component'; import { TaskListComponent } from './page/task-list/task-list.component'; import { ReimbursementComponent } from './page/reimbursement/reimbursement.component'; import { PassDetailComponent } from './page/pass-detail/pass-detail.component'; import { PassComponent } from './page/pass/pass.component'; import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomepageComponent } from './page/homepage/homepage.component'; import { SharepageComponent } from './page/sharepage/sharepage.component'; import { UserpageComponent } from './page/userpage/userpage.component'; import { LoanSkillsComponent } from './page/loan-skills/loan-skills.component'; import { NotFoundComponent } from './page/not-found/not-found.component'; import { CardSkillsComponent } from './page/card-skills/card-skills.component'; import { TabsComponent } from './page/tabs/tabs.component'; import { TaskDetailComponent } from './page/task-detail/task-detail.component'; import { ShareDetailComponent } from './page/share-detail/share-detail.component'; import { MoreComponent } from './page/more/more.component'; import { ReplaceBankCardComponent } from './page/replace-bank-card/replace-bank-card.component'; import { NewPartnerComponent } from './page/new-partner/new-partner.component'; // import { AppComponent } from './app.component'; const appRoutes: Routes = [ //主页 { path: 'home', component: HomepageComponent }, //登录 { path: 'login/:p_id', component: LoginComponent }, //分享 { path: 'share', component: SharepageComponent }, //分享 --> 查看更多 { path: 'shareDetail/:type', component: ShareDetailComponent }, //个人中心 { path: 'user', component: UserpageComponent }, //提额技巧 { path: 'cardSkill', component: CardSkillsComponent }, //贷款技巧 { path: 'loanSkill', component: LoanSkillsComponent }, //导航 { path: 'tabs', component: TabsComponent }, //通道 //通道列表 { path: 'pass', component: PassComponent}, //通道详情 { path: 'passDetail/:pm_id/:id/:minPay/:maxPay/:name', component: PassDetailComponent }, //添加支付卡 { path: 'addPayCard/:bankName/:pm_id/:id/:minPay/:maxPay/:name', component: AddPayCardComponent }, //支付页面 { path: 'payInstall/:total/:cardName/:cardId/:cardNum/:passId/:passName', component: PayInstallComponent }, //还款 { path: 'payback', component: ReimbursementComponent }, //任务列表 { path: 'taskList/:id/:start/:end', component: TaskListComponent }, //新增任务 { path: 'addTask/:id/:start/:end', component: AddTaskComponent}, //任务详情 { path: 'taskDetail/:id/:money/:num/:type', component: TaskDetailComponent }, //添加信用卡 { path: 'addBankCard', component: AddBankCardComponent }, //个人中心 //钱包 { path: 'wallet', component: WalletComponent }, //钱包 ==> 提现 { path: 'cash/:all/:num/:name/:id/:code', component: GetCashComponent }, //会员 { path: 'member', component: MemberComponent }, //会员 ==> 普通会员/高级会员 { path: 'vipCenter/:type', component: VipCenterComponent }, //会员 == 银联卡支付 { path: 'memberShip/:money/:type/:code', component: MemberShipComponent }, //会员 == 扫码支付 { path: 'Qrcode/:link', component: QrcodeComponent }, //合伙人登录 { path: 'partner', component: PartnerComponent }, //申请合伙人 { path: 'newPartner', component: NewPartnerComponent }, //更多设置 { path: 'more', component: MoreComponent }, //安全中心 { path: 'security', component: SecurityCenterComponent }, //更换储蓄卡 { path: 'replace', component: ReplaceBankCardComponent }, //实名认证 { path: 'upload', component: UpLoadComponent }, //二维码图片 { path: 'qrCode', component: QrCodeComponent }, //默认路径 { path: '', redirectTo: '/home', pathMatch: 'full' }, // 404 - Not Found { path: '**', component: NotFoundComponent } ]; @NgModule({ imports: [ RouterModule.forRoot( appRoutes, { enableTracing: false } // <-- debugging purposes only ) ], exports: [ RouterModule ] }) export class AppRoutingModule {}<file_sep>import { MyAppService } from './../../my-app.service'; import { Component, OnInit, ElementRef, ViewChild } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { trigger, state, style, animate, transition } from '@angular/animations'; @Component({ selector: 'app-reimbursement', templateUrl: './reimbursement.component.html', styleUrls: ['./reimbursement.component.css'] }) export class ReimbursementComponent implements OnInit { public state = 'inactive'; bankList = []; isLoad:boolean = false; isShow:boolean = false; isModify:boolean = false; u_id; p_id; cardId; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; start:number; end:number; ifBool: boolean = false; leftStart; leftEnd; startHover:boolean = true; endHover:boolean = true; @ViewChild('line') line: ElementRef; constructor( private http: ServiceBaseService, private router: Router, private route: ActivatedRoute, private myServe: MyAppService ) { // this.bankList = [ // {balance:0,card_bank:"中国光大银行",card_number:"6226580023569573",card_use_status:"4",code:"CEB",id:"73",num:"303",repayment_date:"2",statement_date:"12",user_id:"101"}, // {balance:0,card_bank:"建设银行",card_number:"6226580023569573",card_use_status:"4",code:"CCB",id:"73",num:"303",repayment_date:"2",statement_date:"12",user_id:"101"}, // {balance:0,card_bank:"招商银行",card_number:"6226580023569573",card_use_status:"4",code:"CMB",id:"73",num:"303",repayment_date:"2",statement_date:"12",user_id:"101"}, // {balance:0,card_bank:"中国银行",card_number:"6326580023569125",card_use_status:"4",code:"BOC",id:"73",num:"303",repayment_date:"2",statement_date:"12",user_id:"101"}, // ] } //请求卡信息 cardDetail() { this.isLoad = true this.http.httpPost('Home/card/list_card',{ user_id: this.u_id, plat_id: this.p_id }) .subscribe((data:any)=>{ this.isLoad = false this.bankList = data; }) } // alert --> 删除卡 deleteCard(id,k){ if(k == 1){ this.Toast('任务执行中,暂无法删除','warning') }else{ this.isShow = true; this.cardId = id; } } delete(){ this.isShow = false; this.isLoad = true; this.http.httpPost('Home/card/delete',{ user_id: this.u_id, plat_id: this.p_id, id: this.cardId, type: 1 }) .subscribe((data:any)=>{ this.isLoad = false; if(data.code == 1){ this.Toast('删除成功','success'); this.cardDetail(); }else{ this.Toast(data.msg,'error'); } }) } noDelete(){ this.isShow = false; this.isModify = false; } hide(){ this.isShow = false this.isModify = false; } alert(e){ e.stopPropagation(); } //跳转至 任务页 goToTasklist() { } //添加卡 addCard() { this.router.navigate(['/addBankCard']) } ngOnInit() { this.http.setTitle('智能还款'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.cardDetail(); } //修改账单日、还款日 modifyDate(id,start,end) { this.cardId = id; this.isModify = true; if(start == 0 || start == 1){ this.start = 1; this.leftStart = 0 }if(end == 0 || end == 1){ this.end = 1; this.leftEnd = 0 }else{ this.start = start; this.end = end; this.leftStart = (this.start * (window.innerWidth * 0.68 * 0.9 -15) / 28) + 'px'; this.leftEnd = (this.end * (window.innerWidth * 0.68 * 0.9 -15) / 28) + 'px'; } } touchstart(e) { e.stopPropagation(); this.ifBool = true; } touchmoveStart(e) { if(this.ifBool){ let x = e.touches[0].pageX || e.touches[0].clientX; //鼠标横坐标var x let line_left = this.line.nativeElement.offsetLeft; //长线横坐标 let line_width = this.line.nativeElement.clientWidth; //横线长度 let min_left = x - line_left; //小方块相对于父元素(长线条)的left值 if(min_left >= line_width - 15){ min_left = line_width - 15 }else if(min_left < 0 ){ min_left = 0; } // this.start = Number(this.myServe.rund_0(min_left / (line_width - 15) * 100)) if(Number(this.myServe.rund_0((min_left / (line_width - 15) * 100) / 3.6)) == 0){ this.start = 1 }else{ this.start = Number(this.myServe.rund_0((min_left / (line_width - 15) * 100) / 3.6)); } this.leftStart = min_left + 'px'; this.startHover = false; } } touchmoveEnd(e) { if(this.ifBool){ let x = e.touches[0].pageX || e.touches[0].clientX; //鼠标横坐标var x let line_left = this.line.nativeElement.offsetLeft; //长线横坐标 let line_width = this.line.nativeElement.clientWidth; //横线长度 let min_left = x - line_left; //小方块相对于父元素(长线条)的left值 if(min_left >= line_width - 15){ min_left = line_width - 15 }else if(min_left < 0 ){ min_left = 0; } // this.end = Number(this.myServe.rund_0(min_left / (line_width - 15) * 27)) +1 if(Number(this.myServe.rund_0((min_left / (line_width - 15) * 100) / 3.6)) == 0){ this.end = 1 }else{ this.end = Number(this.myServe.rund_0((min_left / (line_width - 15) * 100) / 3.6)) } this.leftEnd = min_left + 'px'; this.endHover = false; } } touchend() { this.startHover = true; this.endHover = true; } toModify() { if(this.start == this.end){ this.Toast('账单日、还款日不能为同一天','warning') }else{ this.isModify = false; this.isLoad = true; this.http.httpPost('Home/card/edit',{ id: this.cardId, repayment_date: this.end, statement_date: this.start }).subscribe((rs:any)=>{ this.isLoad = false; if(rs.code == 1){ this.Toast(rs.msg,'success'); this.cardDetail(); }else{ this.Toast(rs.msg,'error') } }) } } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { MyAppService } from './../../my-app.service'; @Component({ selector: 'app-add-bank-card', templateUrl: './add-bank-card.component.html', styleUrls: ['./add-bank-card.component.css'] }) export class AddBankCardComponent implements OnInit { ctrl:number = 0; u_id; p_id; bankName; isShow:boolean = false; isLoad:boolean = false; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; next:boolean = false; bindCard:boolean = false userName; userId; m_id; //卡号 cardNum; id; min; max; name; m_id2; bankList = []; openModal:boolean = false; constructor(private myService: MyAppService, private http: ServiceBaseService, private router: Router, private route: ActivatedRoute) { } //下一步 goToNext(num) { this.isShow = true; this.cardNum = num.value } determine(e) { this.isShow = false; e.stopPropagation(); this.ctrl = 1; } //选择银行 chooseBank() { this.isLoad = true; this.http.httpPost('Home/card/bank',{ type: 1 }).subscribe((rs:any)=>{ this.isLoad = false; if(rs){ this.openModal = true; this.bankList = rs; } }) } closeModal(e,i){ this.openModal = false; this.bankName = this.bankList[i].name; localStorage.setItem('bank_num',this.bankList[i].num), localStorage.setItem('bank_code',this.bankList[i].code) } ngOnInit() { this.http.setTitle('添加信用卡'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.userName = sessionStorage.getItem('NAME'); this.userId = sessionStorage.getItem('NAME_id'); this.m_id = sessionStorage.getItem('merchantCode'); } //绑卡 addCard(d,cvv,phone,start,end){ if(d.value.length != 4){ this.Toast('有效期是 4 位数字,请仔细检查','warning') }else if(cvv.value.length != 3){ this.Toast('安全码是 3 位数字,请仔细检查','warning') }else if(this.isPoneAvailable(phone.value) == false){ this.Toast('请输入正确格式的手机号码','warning') }else{ //畅捷绑卡 this.isLoad = true; this.http.httpPost('ChanQuick_pay/PlanPay/bind_card',{ user_id: this.u_id, merchantCode: this.m_id, cardType: "2", certType: "01", cvn2: cvv.value, expired: d.value, accountName: this.userName, cardNo: this.cardNum, certNo: this.userId, phoneno: phone.value, bankCode: localStorage.getItem('bank_num'), bankAbbr: localStorage.getItem('bank_code') }).subscribe((data:any)=>{ if(data.respMsg == "SUCCESS"){ //系统绑卡 this.bindingCard_zt(d,cvv,phone,start,end) }else{ this.isLoad = false; this.Toast(data.respMsg,'error') } }) } } //系统绑卡 bindingCard_zt(d,cvv,phone,start,end){ this.http.httpPost('Home/card/add',{ user_id: this.u_id, card_number: this.cardNum, card_phone: phone.value, card_date: d.value, card_cvv: cvv.value, statement_date: start.value, repayment_date: end.value, passageway_type:'1' }).subscribe((data:any)=>{ this.isLoad = false; if(data.code == 1){ this.Toast(data.msg,'success') let t = 3; let time = setInterval(()=>{ t--; if(t == 0){ this.router.navigate(['/payback']) } },1000) }else{ this.Toast(data.msg,'error') } }) } // 判断是否为手机号 isPoneAvailable(p) { var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/; if (!myreg.test(p)) { return false; } else { return true; } } //input isInput(num){ if(num.value){ this.next = true }else{ this.next = false } } isInput_1(d,c,n){ if(d.value && c.value && n.value){ this.bindCard = true }else{ this.bindCard = false } } //弹框 输入金额 --> 支付 noDelete(){ this.isShow = false; } hide(){ this.isShow = false } alert(e){ e.stopPropagation(); } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { MyAppService } from './../../my-app.service'; @Component({ selector: 'app-pay-install', templateUrl: './pay-install.component.html', styleUrls: ['./pay-install.component.css'] }) export class PayInstallComponent implements OnInit { u_id; p_id; total; card_name; card_id; card_num; pass_id; pass_name; imgUrl; toPay:boolean = false; isLoad:boolean = false; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; platDetailShow:boolean = false; msg_0;msg_1;msg_2;msg_3;msg_4;msg_5; constructor(private myService: MyAppService, private http: ServiceBaseService, private router: Router, private route: ActivatedRoute) { } //input isInput_1(d,cvv,phone) { if(d.value && cvv.value && phone.value){ this.toPay = true }else{ this.toPay = false } } ngOnInit() { this.http.setTitle('支付'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.total = this.route.snapshot.paramMap.get('total'); this.card_name = this.route.snapshot.paramMap.get('cardName'); this.card_id = this.route.snapshot.paramMap.get('cardId'); this.card_num = this.route.snapshot.paramMap.get('cardNum'); this.pass_id = this.route.snapshot.paramMap.get('passId'); this.pass_name = this.route.snapshot.paramMap.get('passName'); this.imgUrl = localStorage.getItem('bank_code') } //点击支付 pay(d,cvv,phone) { if(d.value.length != 4){ this.Toast('有效期是 4 位数字,请仔细检查','warning') }else if(cvv.value.length != 3){ this.Toast('安全码是 3 位数字,请仔细检查','warning') }else if(this.isPoneAvailable(phone.value) == false){ this.Toast('请输入正确格式的手机号码','warning') }else{ this.isLoad = true; this.http.httpPost('Home/order/pay_msg',{ total: this.total, id: this.pass_id, user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ this.isLoad = false; this.platDetailShow = true; this.msg_0 = data.name; this.msg_1 = data.phone_number; this.msg_2 = data.pay; this.msg_3 = data.withdrawals; this.msg_4 = data.user_money; this.msg_5 = data.card_number; }) } } //确认支付 goToPay(d,cvv,phone) { this.platDetailShow = false; this.isLoad = true; this.http.httpPost('Home/order/pay',{ id: this.pass_id, card_id: this.card_id, user_id: this.u_id, total: this.total, card_cvv: cvv.value, card_date: d.value, plat_id: this.p_id, phone: this.msg_1 }).subscribe((data:any)=>{ this.isLoad = false; if(data.code == 1){ this.Toast(data.msg,'success') let t = 3; let time = setInterval(()=>{ t--; if(t == 0){ this.router.navigate(['/home']) } },1000) }else{ this.Toast(data.msg,'error') } }) } // 判断是否为手机号 isPoneAvailable(p) { var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/; if (!myreg.test(p)) { return false; } else { return true; } } //选择任务 closePlat() { this.platDetailShow = false } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { MyAppService } from './../../my-app.service'; @Component({ selector: 'app-replace-bank-card', templateUrl: './replace-bank-card.component.html', styleUrls: ['./replace-bank-card.component.css'] }) export class ReplaceBankCardComponent implements OnInit { isLoad:boolean = false; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; u_id; p_id; cardList = []; hasCard:boolean = false; isShow:boolean = false; cardId; constructor(private myService: MyAppService, private http: ServiceBaseService, private router: Router, private route: ActivatedRoute) { } //获取卡 getCard() { this.isLoad = true; this.http.httpPost('Home/deposit/list_deposit',{ user_id: this.u_id }).subscribe((rs:any)=>{ this.isLoad = false; if(rs.length){ this.cardList = rs; this.hasCard = true; }else{ this.hasCard = false; } }) } //删除卡 deleteCard(id){ this.isShow = true; this.cardId = id; } delete(){ this.isShow = false; this.isLoad = true; this.http.httpPost('Home/deposit/delete',{ user_id: this.u_id, plat_id: this.p_id, id: this.cardId }) .subscribe((data:any)=>{ this.isLoad = false; if(data.code == 1){ this.Toast('删除成功','success'); this.getCard(); }else{ this.Toast(data.msg,'error'); } }) } noDelete(){ this.isShow = false; } hide(){ this.isShow = false } alert(e){ e.stopPropagation(); } //更换储蓄卡 goToAddbankcard() { if(this.hasCard == true){ this.Toast('最多绑定一张储蓄卡,如需更换,请先删除原卡','warning') }else{ this.router.navigate(['/replaceCard']) } } ngOnInit() { this.http.setTitle('储蓄卡'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.getCard() } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-alert', // templateUrl: './alert.component.html', styleUrls: ['./alert.component.css'], template:` <div class="content " (click)="hide()" [ngClass]="isShow==false ? 'hide' : ''"> <div class="alert" (click)="alert($event)"></div> </div> ` }) export class AlertComponent implements OnInit { isShow:boolean = true @Input() type: string = "success"; @Output() output = new EventEmitter(); constructor() {} ngOnInit() { } hide(){ this.isShow = false } alert(e){ e.stopPropagation(); console.log(2) } } <file_sep>import { Injectable } from '@angular/core'; // import { MessageService } from './message.service'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import {Title} from "@angular/platform-browser"; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable() export class MyAppService { configUrl = 'http://card.zt717.com/cms/index.php/Home/index/user'; constructor( // private messageService: MessageService, private router: Router, public titleSet:Title, private http: HttpClient,) { } getHeroes() { // this.messageService.add('HeroService: fetched heroes'); // this.router.navigate(['/user']); } getUser() { return this.http.post(this.configUrl,{ user_id: 125 }) } // private log(message: string) { // this.messageService.add('HeroService: ' + message); // } setTit( msg ) { this.titleSet.setTitle(msg) } //保留两位但不四舍五入 rund(num){ let num2=Number(num).toFixed(3); return num2.substring(0,num2.lastIndexOf('.')+3) } //整数 rund_0(num){ let num2=Number(num).toFixed(0); return num2 } timeGet(Time, type) { let now = new Date(Time * 1000); let year = now.getFullYear(); let month = now.getMonth() + 1; let date = now.getDate(); let hour = now.getHours(); let minute = now.getMinutes(); let second = now.getSeconds(); if (type == "s") { return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second; } else if (type == 'min') { return year + "-" + month + "-" + date + " " + hour + ":" + minute } else if (type == 'h') { return year + "-" + month + "-" + date + " " + hour } else if (type == 'd') { return year + "-" + month + "-" + date } else if (type == 'm') { return year + "-" + month }else if(type == 'month') { if(month<=9){return '0'+month} }else if(type == 'date') { if(date<=9){return '0'+date} } }; } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { Observable, } from 'rxjs'; import { catchError, retry } from 'rxjs/operators'; import { Title } from '@angular/platform-browser'; @Injectable() export class ServiceBaseService { constructor(private http: HttpClient, private tit: Title) { } httpPost(url,data) { return this.http.post('http://card.zt717.com/cms/index.php/'+url,data) // return this.http.post(this.urls.GetBillType+url,data) } setTitle(newTitle: string){ this.tit.setTitle(newTitle) } httpGet(url,data) { return this.http.get(url,data) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { MyAppService } from './../../my-app.service'; @Component({ selector: 'app-security-center', templateUrl: './security-center.component.html', styleUrls: ['./security-center.component.css'] }) export class SecurityCenterComponent implements OnInit { isLoad:boolean = false; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; isConfirm:boolean = false; isClick:boolean = true; btnText:string = '立即获取'; countNum:number = 99; masData:number; u_id; p_id; phone_number; constructor(private myService: MyAppService, private http: ServiceBaseService, private router: Router, private route: ActivatedRoute) { } //input onBurl(pass,comPass,phone,code) { if(pass.value && comPass.value && phone.value && code.value){ this.isConfirm = true; }else{ this.isConfirm = false } } //获取验证码 getCode(phone) { if(phone.value){ this.isLoad = true; this.http.httpPost('Home/index/validate',{ phone_number: phone.value, user_id: this.u_id }).subscribe((rs:any)=>{ if(rs.msg == '电话号已注册'){ //发送验证码 this.sendMass(phone) }else{ this.isLoad = false; this.Toast('电话号有误或未注册','warning') } }) }else{ this.Toast('请输入手机号码','warning') } } //发送验证码 sendMass(phone) { this.http.httpPost('backstage/register/index',{ telephone: phone.value, type: '1' }).subscribe((rs:any)=>{ this.isLoad = false; if(rs.code == 0 ){ this.Toast(rs.msg,'error') }else if(rs.code == 1){ this.Toast(rs.msg,'success'); let Timer = setInterval(()=>{ if(this.countNum>0){ this.btnText = this.countNum + '秒后重发'; this.countNum--; this.isClick = false; }else{ this.countNum = 99; clearInterval(Timer); this.btnText = '重新获取'; this.isClick = true; } },1000); this.masData = rs.data; } }) } //修改密码 goToNext(pass,comPass,phone,code) { if(pass.value.length < 5){ this.Toast('密码长度不得小于 6 位','warning'); pass.value = ''; comPass.value = '' }else if(pass.value != comPass.value){ this.Toast('两次密码内容不一致','warning'); pass.value = ''; comPass.value = '' }else if(code.value != this.masData){ this.Toast('验证码有误,请确认','warning'); code.value = '' }else{ this.isLoad = true; this.http.httpPost('Home/index/pass',{ pass: pass.value, pass1: comPass.value, phone: phone.value, user_id: this.u_id }).subscribe((rs:any)=>{ this.isLoad = false; if(rs.code == 0){ this.Toast(rs.msg,'error') }else{ this.Toast(rs.msg,'success'); let t = 3; let time = setInterval(()=>{ t--; if(t == 0){ this.router.navigate(['/user']) } },1000) } }) } } ngOnInit() { this.http.setTitle('安全中心'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.phone_number = sessionStorage.getItem('phone_number') } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { MyAppService } from './../../my-app.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { ServiceBaseService } from './../../service-base.service'; @Component({ selector: 'app-add-task', templateUrl: './add-task.component.html', styleUrls: ['./add-task.component.css'] }) export class AddTaskComponent implements OnInit { u_id; p_id; isLoad:boolean = false; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; choice:boolean = false; taskType; //临时保存 link_f; tit_f; //真实保存 link; tit; chicked; choiceDate:boolean = false; taskDate; objs = []; newTotal; platType:boolean = false; cardId; data; start; end; arr = []; arr2 = []; classFlag: object = []; isAble: boolean = true; platList; total; platDetailShow:boolean = false; x1;x2;x3;x4;x5; isShow:boolean = false; constructor(private route: ActivatedRoute, private router: Router, private http: ServiceBaseService, private myService: MyAppService) { } //读取任务方法 getTask() { this.http.httpPost('Home/plan/choiceRepaymentMethod',{ user_id: this.u_id, plat_id: this.p_id, }).subscribe((data:any)=>{ this.taskType = data.data; for(let i=0;i<data.data.length;i++){ if(data.data[i].default_checked == 1){ this.link = data.data[i].link this.tit = data.data[i].title } } }) } ngOnInit() { this.http.setTitle('新增任务'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.cardId = this.route.snapshot.paramMap.get('id'); this.start = this.route.snapshot.paramMap.get('start'); this.end = this.route.snapshot.paramMap.get('end') this.getTask() } //选择任务 choiceTask() { this.choice = true; } closeTask() { this.choice = false; } closePlat() { this.platDetailShow = false } choiceseOne(link,tit,i){ this.link_f = link; this.tit_f = tit; this.chicked = i } chickTask() { this.choice = false; this.link = this.link_f; this.tit = this.tit_f; this.Toast('当前任务类型设置为 '+this.tit,'success') } //选择任务日期 //打开选择框 toDate() { this.choiceDate = true; this.choiceDates(); this.arr2 =[] } hideTaskDate() { this.choiceDate = false; this.arr = []; } dateModule(e){ e.stopPropagation() } //日期方法 choiceDates() { this.isLoad = true; this.http.httpPost('Home/card/detail',{ id: this.cardId, user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ this.isLoad = false; let start = this.start, //账单日 end = this.end, //还款日 today = new Date().getDate(), //今日 hours = new Date().getHours(), //当前小时 curMonthDays = new Date(new Date().getFullYear(), (new Date().getMonth()+1), 0).getDate(); //当月天数 //账单日小于还款日 if(start-end<0){ //12点之前 if(hours<=12){this.dateArr(today,end-2)} //12点以后 else if(hours>12){this.dateArr(today+1,end-2)} } //账单日大于还款日 if(start-end>0){ //当前日期大于账单日 if(today-start>=0){ //12点之前 if(hours<=12){ this.dateArr(today,curMonthDays) this.dateArr(1,end-2) } //12点之后 else if(hours>12){ this.dateArr(today+1,curMonthDays) this.dateArr(1,end-2) } } //当前日期小于账单日 并且小于还款日 if(today-start<=0&&today-end<-1){ //12点之前 if(hours<=12){ this.dateArr(today,end-2) } //12点之后 else if(hours>12){ this.dateArr(today+1,end-2) } } } }) } dateArr(d1,d2) { for(let i = d1;i<=d2;i++){ this.arr.push(i); this.classFlag[i] = {name: false} } } //选择日期 changeClass(i) { this.classFlag[i].name = !this.classFlag[i].name; if(this.classFlag[i].name){ this.arr2.push(i) }else if(!this.classFlag[i].name){ // this.arr2.splice(0,this.arr2.length) for(let k=0;k<this.arr2.length;k++){ if(this.arr2[k] == i){ this.arr2.splice(k, 1) } } } } //全选 取消全选 choiceAll() { let day = new Date().getDate() this.arr2 = []; for(let i=0;i<this.arr.length;i++){ this.arr2.push(this.arr[i]); this.isAble = false; } for(let i=0;i<=31;i++){ this.classFlag[i] = {name: true} } } unChoiceAll() { for(let i=0;i<this.arr.length;i++){ this.isAble = true; this.arr2 = []; } for(let i=0;i<=31;i++){ this.classFlag[i] = {name: false} } } //点击确定 closeModal() { this.arr = []; this.choiceDate = false; this.taskDate = this.arr2; this.objs = [] } //生成计划列表 baginPlat(total,date) { localStorage.setItem('oldlink',this.tit) if(!total.value){ this.Toast('请输入任务金额','warning') }else if(!date.value){ this.Toast('请选择任务日期','warning') }else{ this.isLoad = true; this.http.httpPost('Home/'+this.link+'',{ id: this.cardId, total: total.value, date: date.value, user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ this.isLoad = false; if(data.code == 0){ this.Toast(data.msg,'error') }else{ this.newTotal = total.value this.platType = true this.platList = data; this.objs = [] for(let i=0; i<data.length; i++){ for(let k=0; k<data[i].length; k++){ //处理显示序号 // this.arr.push(data[k]) this.platList[i][k].task_time = this.myService.timeGet(data[i][k].time,"min") this.objs.push(this.platList[i][k]) } } } }) } } //执行当前计划 openD(total) { this.total = total.value; if(this.platType == false){ this.Toast('请先生成计划列表','warning') }else if(this.newTotal != localStorage.getItem('oldTotal')){ this.Toast('任务金额改变,请重新生成计划列表','warning') }else if(this.objs.length <=0){ this.Toast('任务日期改变,请重新生成计划列表','warning') }else if(localStorage.getItem('oldlink') != this.tit){ this.Toast('任务类型改变,请重新生成计划列表','warning') }else if(this.platType == true){ this.isLoad = true this.http.httpPost('Home/plan/count',{ user_id: this.u_id, plat_id: this.p_id, total: this.total, task: this.objs }).subscribe((data:any)=>{ this.isLoad = false; this.platDetailShow = true; this.x1 = data.x1; this.x2 = data.x2; this.x3 = data.x3; this.x4 = data.x4; this.x5 = data.x5; }) } } //保存任务金额作对比 inTotal(T){ localStorage.setItem('oldTotal',T.value) } //执行任务 beginPlat() { this.platDetailShow = false; this.isLoad = true; this.http.httpPost('Home/plan/add',{ id: this.cardId, total: this.total, task: this.objs, user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ this.isLoad = false; if(data.code == 0){ this.Toast(data.msg,'error') }else{ this.Toast(data.msg,'success') let t = 3; let time = setInterval(()=>{ t--; if(t == 0){ this.router.navigate(['/taskList',this.cardId,this.start,this.end]) } },1000) } }) } //任务类型遮罩 showBlack() { this.isShow = true; } alert(e){ e.stopPropagation(); } hide() { this.isShow = false } noDelete() { this.isShow = false; } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { MyAppService } from './../../my-app.service'; @Component({ selector: 'app-new-partner', templateUrl: './new-partner.component.html', styleUrls: ['./new-partner.component.css'] }) export class NewPartnerComponent implements OnInit { isAbled:boolean = false; u_id; p_id; isLoad:boolean = false; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; constructor(private myService: MyAppService, private http: ServiceBaseService, private router: Router, private route: ActivatedRoute) { } ngOnInit() { this.http.setTitle('申请合伙人'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); } isOk(name,phone,location,work) { if(name.value && phone.value && location.value && work.value){ this.isAbled = true; } } isFrom(name,phone,location,work,more) { this.isLoad = true; this.http.httpPost('Home/index/partnerApply',{ user_id: this.u_id, plat_id: this.p_id, p_name: name.value, p_phone: phone.value, p_location: location.value, p_meail: work.value, p_memark: more.value, }).subscribe((rs:any)=>{ this.isLoad = false; if(rs.code == 1){ this.Toast(rs.msg,'success') this.Toast(rs.message,'success') let t = 3; let time = setInterval(()=>{ t--; if(t == 0){ this.router.navigate(['/user']) } },1000) }else{ this.Toast(rs.msg,'error') this.Toast(rs.message,'error') } }) } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { MyAppService } from './../../my-app.service'; @Component({ selector: 'app-member', templateUrl: './member.component.html', styleUrls: ['./member.component.css'] }) export class MemberComponent implements OnInit { u_id; p_id; isLoad:boolean = false; isShow:boolean = false; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; vipM1; vipM2; vipT1; vipT2; vipM_c; vipM_t; payWayList = []; choice:boolean = false; toPay:boolean = false; chicked; payType; link; time = 150; browser={ versions:function(){ var u = navigator.userAgent, app = navigator.appVersion; return { trident: u.indexOf('Trident') > -1, //IE内核 presto: u.indexOf('Presto') > -1, //opera内核 webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核 mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端 ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端 iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器 iPad: u.indexOf('iPad') > -1, //是否iPad webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部 weixin: u.indexOf('MicroMessenger') > -1, //是否微信 (2015-01-22新增) }; }() } constructor(private myService: MyAppService, private http: ServiceBaseService, private router: Router, private route: ActivatedRoute) { } //获取aPPid 并且签名 getApp() { this.http.httpPost('Home/index/wechat_config',{ // plat_id: this.p_id plat_id: 125, url: 'http://wx.ztipay.com/' }).subscribe((rs:any)=>{ console.log(rs.data.appId) if(rs.data){ wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: rs.data.appId, // 必填,公众号的唯一标识 timestamp: rs.data.timestamp, // 必填,生成签名的时间戳 nonceStr: rs.data.nonceStr, // 必填,生成签名的随机串 signature: rs.data.signature,// 必填,签名 jsApiList: ['chooseImage','uploadImage','downloadImage','getLocalImgData'] // 必填,需要使用的JS接口列表 }); } }) } //购买会员的money getInfo() { this.isShow = false; this.http.httpPost('Home/card/find',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((rs:any)=>{ this.vipM1=this.myService.rund(rs.msg[0].money); this.vipM2=this.myService.rund(rs.msg[1].money); this.vipT1=rs.msg[0].type; this.vipT2=rs.msg[1].type; }) } //选择会员等级 chooseType(c1,c2,t){ this.isLoad = true; this.vipM_c=c2; this.vipM_t=c1; this.http.httpPost('Home/index/buyMemberApi',{ user_id:this.u_id, plat_id:this.p_id, type:t }).subscribe((rs:any)=>{ this.isLoad = false; if(rs.code == 1){ this.payWayList = rs.data; this.choice = true } }) } //点击切换class效果 choiceseOne(type,link,i){ this.chicked = i; this.payType = type; this.link = link; sessionStorage.setItem('LINK',link) } //关闭 closeTask() { this.choice = false; } noDelete(){ this.toPay = false; } hide(){ this.toPay = false } alert(e){ e.stopPropagation(); } ngOnInit() { this.http.setTitle('会员权益'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.getInfo(); if(this.browser.versions.android){ this.getApp() } } //点击确定 chickTask() { this.choice = false; /** * payType == 1 跳转 */ if(this.payType == 1){ if(!sessionStorage.getItem('isToPay')){ let is_weixin = (function(){return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1})(); if(is_weixin){ this.wchartPay(this.vipM_t) }else{ window.location.href = this.link+"?money="+this.vipM_c+'&pay_type='+this.vipM_t+'&user_id='+this.u_id+'&plat_id='+this.p_id; } // this.daoTime() }else{ this.Toast('操作过于频繁,请于2分钟后再次尝试','warning') } } /** * payType == 1 请求 */ else if(this.payType == 2){ if(!sessionStorage.getItem('isToPay')){ this.daoTime(); this.isLoad = true; this.http.httpPost('Home/'+this.link+'',{ money:this.vipM_c, pay_type:this.vipM_t, user_id:this.u_id }).subscribe((rs:any)=>{ this.isLoad = false; if(rs.return_code == 'SUCCESS'){ this.router.navigate(['/Qrcode','http://qr.liantu.com/api.php?text='+rs.code_url+'']); }else{ this.Toast(rs.msg,'error') } }) }else{ this.Toast('操作过于频繁,请于2分钟后再次尝试','warning') } } /** * payType == 3 激活码 */ else if(this.payType == 3){ this.toPay = true; } /** * payType == 4 银联收款 - 无验证码 */ else if(this.payType == 4){ this.router.navigate(['/memberShip',this.vipM_c,this.vipM_t,0]); } /** * payType == 5 银联收款 - 有验证码 */ else if(this.payType == 5){ this.router.navigate(['/memberShip',this.vipM_c,this.vipM_t,1]); } } //公众号支付 wchartPay(type) { this.isLoad = true; this.http.httpPost('Home/openMember/registerPurchaseWechatPay',{ pay_type: type, money: this.vipM2, user_id: this.u_id, open_id: localStorage.getItem('open_id') }).subscribe((rs:any)=>{ this.isLoad = false; if(rs.code == 1){ wx.ready(function(){ wx.chooseWXPay({ timestamp: rs.data.timeStamp, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符 nonceStr: rs.data.nonceStr, // 支付签名随机串,不长于 32 位 package: rs.data.package, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*) signType: rs.data.signType, // 签名方式,默认为'SHA1',使用新版支付需传入'MD5' paySign: rs.data.paySign, // 支付签名 success: function (res) { // 支付成功后的回调函数 window.location.href = "registerResult.html?platform_id="+125+"" } }); }); }else{ this.Toast(rs.msg,'error') } }) } //激活码支付 buyCode(total) { if(total.value){ this.toPay = false; if(!sessionStorage.getItem('isToPay')){ this.isLoad = true; this.http.httpPost('Home/'+this.link,{ user_id: this.u_id, plat_id: this.p_id, code: total.value }).subscribe((rs:any)=>{ this.isLoad = false; if(rs.code){ this.daoTime(); this.Toast(rs.msg,'success'); let t = 3; let time = setInterval(()=>{ t--; if(t == 0){ this.router.navigate(['/home']) } },1000) }else{ this.Toast(rs.msg,'error') } }) }else{ this.Toast('操作过于频繁,请于2分钟后再次尝试','warning') } }else{ this.Toast('请输入激活码','warning') } } //防重复支付 daoTime() { sessionStorage.setItem('isToPay','false') let T = setInterval(()=>{ this.time--; if(this.time == 0){ this.time = 150; sessionStorage.removeItem('isToPay') clearInterval(T) } },1000) } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { MyAppService } from './../../my-app.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; @Component({ selector: 'app-share-detail', templateUrl: './share-detail.component.html', styleUrls: ['./share-detail.component.css'] }) export class ShareDetailComponent implements OnInit { u_id; p_id; type; list:number = 0; classFlag:any; isLoad: boolean = false; benefitList:object; index; all; allPer; constructor(private myjs: MyAppService, private http: ServiceBaseService, private router: Router, private route: ActivatedRoute) { } getInit(date,list) { this.classFlag = list; this.isLoad = true; this.http.httpPost('Home/order/list_order',{ user_id: this.u_id, plat_id: this.p_id, type: this.type, date: date }).subscribe((rs:any)=>{ this.isLoad = false; this.benefitList=rs; let desk = []; let eveo = []; for(let i = 0;i<rs.length;i++){ this.benefitList[i].pay_ok_time=this.myjs.timeGet(rs[i].pay_ok_time,"d"); this.benefitList[i].user_money=this.myjs.rund(rs[i].user_money); this.benefitList[i].per=this.myjs.rund(rs[i].per); this.index = i+1; desk.push(rs[i].per) eveo.push(rs[i].user_money) this.allPer = this.myjs.rund(eval(desk.join("+"))) this.all = this.myjs.rund(eval(eveo.join("+")) / 10000) } console.log() }) } ngOnInit() { this.http.setTitle('分享明细'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.type = this.route.snapshot.paramMap.get('type'); this.getInit('week',0); } } <file_sep>import { ServiceBaseService } from './../../service-base.service'; import { MyAppService } from './../../my-app.service'; import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { imgsrc; tel; isRow:boolean = false; isDisabled:boolean = false; isLoad:boolean = false; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; p_id; plh; constructor(private myAppServe: MyAppService, private route: ActivatedRoute, private router: Router, private http: ServiceBaseService) { } //记住账号 KeepPass() { this.isRow = !this.isRow; } //input keyUp(num,phone) { if(num.value && phone.value){ this.isDisabled = true }else{ this.isDisabled = false } } //获取logo getSrc() { this.http.httpPost('Home/base/logo',{ plat_id: this.p_id, type: 1 }).subscribe((rs:any)=>{ this.imgsrc = rs.data; this.tel = rs.tel }) } //burl checkPhone(username) { let use = username.value; this.http.httpPost('Home/index/validate',{ phone_number: use, plat_id: this.p_id }).subscribe((rs:any)=>{ if (rs.msg == '验证通过') { this.Toast("此电话号码未注册","warning") this.plh = '' } else if (rs.msg == '电话号已注册') { } else { this.plh = rs.msg; } }) } //login goLogin(num,pass) { this.isLoad = true; this.http.httpPost('Home/index/login',{ name: num.value, pass: <PASSWORD>, plat_id: this.p_id, open_id: localStorage.getItem('open_id') }).subscribe((rs:any)=>{ this.isLoad = false; if(rs.code == 1){ localStorage.setItem('user_id', rs.data.id); localStorage.setItem('plat_id', rs.data.platform_id); this.router.navigate(['/home']) }else{ this.Toast(rs.msg,'error') } }) } ngOnInit() { this.p_id = this.route.snapshot.paramMap.get('p_id'); this.getSrc() } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { MyAppService } from './../../my-app.service'; import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; @Component({ selector: 'app-qr-code', templateUrl: './qr-code.component.html', styleUrls: ['./qr-code.component.css'] }) export class QrCodeComponent implements OnInit { u_id; p_id; isLoad:boolean = false; listBg; getUrl; imgUrl:string; showLid:boolean = false; constructor(private route: ActivatedRoute, private router: Router, private http: ServiceBaseService, private myjs: MyAppService) { } //获取接口图片 getImg() { this.isLoad = true; this.http.httpPost('Home/index/promoteBusiness',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((rs:any)=>{ this.isLoad = false; this.listBg = rs.data.qrcode_images_share }) } //当前点击图片 chooseThis(url) { this.getUrl = url; this.isLoad = true; //绘制canvas合并图片并输出 let c = document.createElement('canvas'); let ctx = c.getContext('2d'); c.width = 375; c.height = 667; ctx.rect(0,0,c.width,c.height); ctx.fillStyle='#fff'; ctx.fill(); let b_img = new Image; b_img.crossOrigin = 'Anonymous' let _this = this; b_img.src = 'http://card.zt717.com/Public/Home/img/sharebg1.png'; // b_img.src = 'http://oss.ztipay.com/Public/Backstage/upload/20180320/8491521511409.png'; // b_img.src = 'http://card.zt717.com/cms/index.php/Home/index/qrcode?user_id='+_this.u_id; //如果在浏览器存在缓存 if(b_img.complete){ ctx.drawImage(b_img,0,0,c.width,c.height); let s_img=new Image; s_img.crossOrigin = 'Anonymous'; s_img.src='http://card.zt717.com/cms/index.php/Home/index/qrcode?user_id='+_this.u_id; s_img.onload= ():void=> { ctx.drawImage(s_img,105,464,165,165); _this.imgUrl= c.toDataURL("image/png",0.5); _this.isLoad = false; _this.showLid = true; } return } b_img.onload= ():void=>{ ctx.drawImage(b_img,0,0,c.width,c.height); let s_img=new Image; s_img.crossOrigin = 'Anonymous'; s_img.src='http://card.zt717.com/cms/index.php/Home/index/qrcode?user_id='+_this.u_id; s_img.onload= ():void=> { ctx.drawImage(s_img,105,464,165,165); _this.imgUrl= c.toDataURL("image/png",0.5); _this.isLoad = false; _this.showLid = true; } }; } hidImg() { this.showLid = false; } ngOnInit() { this.http.setTitle('二维码图片'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.getImg() } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { MyAppService } from './../../my-app.service'; @Component({ selector: 'app-task-detail', templateUrl: './task-detail.component.html', styleUrls: ['./task-detail.component.css'] }) export class TaskDetailComponent implements OnInit { id; data; num; detailList; isLoad:boolean = false; isShow:boolean = false; u_id; p_id; total; taskType; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; errorMsg; stop: boolean = false; constructor( private myService: MyAppService, private http: ServiceBaseService, private router: Router, private route: ActivatedRoute, ) { } //时间戳格式化 timeGets(time){ this.myService.timeGet(time,"min"); } //任务详情列表 readDetail() { this.isLoad = true this.http.httpPost('Home/plan/plan_list',{ id: this.id, user_id: this.u_id, plat_id: this.p_id, type: 1, new_type: 1 }).subscribe((data:any)=>{ this.isLoad = false this.detailList = data; for(let i=0;i<data.length;i++){ this.detailList[i].true_payment = this.myService.rund(data[i].payment) } }) } ngOnInit() { this.http.setTitle('任务明细'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.id = this.route.snapshot.paramMap.get('id'); this.num = this.route.snapshot.paramMap.get('num'); this.total = this.route.snapshot.paramMap.get('money') this.taskType = this.route.snapshot.paramMap.get('type') this.readDetail() } //点击产看详情 error(id) { this.isLoad = true; this.http.httpPost('Home/plan/error',{ id:id, user_id: this.u_id }).subscribe((data:any)=>{ this.isLoad = false; if(data.code == 1 && data.msg != 'SUCCESS'){ this.isShow = true; this.errorMsg = data.msg }else{ this.Toast(data.msg,'error') } }) } noDelete(){ this.isShow = false; this.stop = false; } hide(){ this.isShow = false this.stop = false; } alert(e){ e.stopPropagation(); } //终止任务 stopTask() { this.stop = true; } delete() { this.stop = false; this.isLoad = true; this.http.httpPost('Home/plan/stop',{ stop: 'on', id: this.id, user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ this.isLoad = false; this.Toast(data.msg,'success') let t = 3; let time = setInterval(()=>{ t--; if(t == 0){ this.router.navigate(['/payback']) } },1000) }) } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { HttpResponse } from '@angular/common/http'; import { ServiceBaseService } from './../../service-base.service'; import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; // declare var wx: any; // declare var WeixinJSBridge : any; @Component({ selector: 'app-up-load', templateUrl: './up-load.component.html', styleUrls: ['./up-load.component.css'] }) export class UpLoadComponent implements OnInit { NAME; u_id; p_id; choice:boolean = true; isDisabled:boolean = false; bgImg: string; showLid:boolean = false; access_token; jsapi_ticket; num; img01; isLoad:boolean = false; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; isShow:boolean = false; rsMessage:string; browser={ versions:function(){ var u = navigator.userAgent, app = navigator.appVersion; return { trident: u.indexOf('Trident') > -1, //IE内核 presto: u.indexOf('Presto') > -1, //opera内核 webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核 mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端 ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端 iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器 iPad: u.indexOf('iPad') > -1, //是否iPad webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部 weixin: u.indexOf('MicroMessenger') > -1, //是否微信 (2015-01-22新增) }; }() } constructor(private http: ServiceBaseService, private router: Router, private route: ActivatedRoute) { } //获取aPPid 并且签名 getApp() { this.http.httpPost('Home/index/wechat_config',{ // plat_id: this.p_id plat_id: 125, url: 'http://wx.ztipay.com/' }).subscribe((rs:any)=>{ console.log(rs.data.appId) if(rs.data){ wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: rs.data.appId, // 必填,公众号的唯一标识 timestamp: rs.data.timestamp, // 必填,生成签名的时间戳 nonceStr: rs.data.nonceStr, // 必填,生成签名的随机串 signature: rs.data.signature,// 必填,签名 jsApiList: ['chooseImage','uploadImage','downloadImage','getLocalImgData'] // 必填,需要使用的JS接口列表 }); } }) } //input okIn(id,card,phone) { if(id.value && card.value && phone.value && this.choice == true){ this.isDisabled = true; }else{ this.isDisabled = false; } } toChoice() { this.choice = !this.choice; } //点击单张上传 upLoadImg(num){ this.bgImg = 'imgBg'+num; this.num = num; this.showLid = true; } upLoadOne() { this.showLid = false; this.upLoad(this.num); } upLoad(num) { wx.chooseImage({ count: 1, // 默认9 sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { let localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片 $('.loading-jq').show(); wx.getLocalImgData({ localId: localIds[0], // 图片的localID success: function (res) { var localData = res.localData; // localData是图片的base64数据,可以用img标签显示 var toastTime = 3; // document.getElementById('img'+num).setAttribute('src',res.localData); $.ajax({ type: 'POST', url: 'http://card.zt717.com/cms/index.php/Home/upload/wx_upload', data: { data: res.localData }, success:function(data){ $('.loading-jq').hide(); if(data.code == 1){ $('#img'+num).attr('src','http://ztadmin.oss-cn-shenzhen.aliyuncs.com/Public/Home/upload/'+data.message); $('.hideDiv'+num).text(data.message) if(toastTime == 3){ $('.toast-jq').addClass('success'); $('.toast-jq>p').text('上传成功') }else{ $('.toast-jq').removeClass('success'); } let time = setInterval(()=>{ toastTime--; // console.log(this.toastTime) if(toastTime<=0){ clearInterval(time) toastTime = 3; $('.toast-jq').removeClass('success'); } },1000) }else{ if(toastTime == 3){ $('.toast-jq').addClass('error'); $('.toast-jq>p').text(data.message); $('.toast-jq>p').text(data.msg) }else{ $('.toast-jq').removeClass('error'); } let time = setInterval(()=>{ toastTime--; // console.log(this.toastTime) if(toastTime<=0){ clearInterval(time) toastTime = 3; $('.toast-jq').removeClass('error'); } },1000) } } }) } }); } }); } ngOnInit() { this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.http.setTitle('实名认证'); this.NAME = sessionStorage.getItem('NAME'); // this.getApp() // console.log(window.location.href) if(this.browser.versions.android){ this.getApp() } } //立即认证 certification(id,card,phone) { if($('#img1').attr('src') == 'assets/img/upload_1.png'){ this.Toast('请先上传手持证件照','warning') }else if($('#img2').attr('src') == 'assets/img/upload_2.png'){ this.Toast('请先上传身份证正面照','warning') }else if($('#img3').attr('src') == 'assets/img/upload_3.png'){ this.Toast('请先上传身份证反面照','warning') }else if($('#img4').attr('src') == 'assets/img/upload_4.png'){ this.Toast('请先上传储蓄卡正面照','warning') }else{ //判断是否是重复用户 this.isLoad = true; this.http.httpPost('Home/index/checkUserRepeat',{ idCardNo: id.value, user_id: this.u_id }).subscribe((rs:any)=>{ //是重复 if(rs.code == 1){ this.isLoad = false; this.isShow = true; this.rsMessage = rs.msg; }else{ //普通上传 this.http.httpPost('ChanQuick_pay/PlanPay/merchant_reg',{ idCardNo: id.value, bankAccountNo: card.value, phone: phone.value, merName: this.NAME, user_id: this.u_id, plat_id: this.p_id }).subscribe((rs:any)=>{ this.isLoad = false; if(rs.code=='05010063'||rs.code=='00'){ //上传 this.imgUpload(id,card,phone) }else{ this.Toast(rs.message,'error') } }) } }) } } //上传图片 imgUpload(id,card,phone) { this.isLoad = true; this.http.httpPost('Home/index/upload',{ id_card: id.value, card_id: card.value, phone: phone.value, user_id: this.u_id, plat_id: this.p_id, img: $('.hideDiv1').text(), img1: $('.hideDiv2').text(), img2: $('.hideDiv3').text(), img3: $('.hideDiv4').text(), type: 1 }).subscribe((rs:any)=>{ this.isLoad = false; if(rs.code == 1){ this.Toast('您的信息提交成功,请耐心等待审核','success'); let t = 3; let time = setInterval(()=>{ t--; if(t == 0){ this.router.navigate(['/user']) } },1000) }else{ this.Toast(rs.msg,'error') this.Toast(rs.message,'error') } }) } //重复用户注册 merchantRegister(id,card,phone) { this.isShow = false; this.isLoad = true; console.log(id.value) console.log(card.value) console.log(phone.value) console.log(this.NAME) console.log(this.u_id) console.log(this.p_id) this.http.httpPost('Home/index/regBefore',{ idCardNo: id.value, bankAccountNo: card.value, phone: phone.value, merName: this.NAME, user_id: this.u_id, plat_id: this.p_id }).subscribe((rs:any)=>{ this.isLoad = false; if(rs.code >= 1){ this.imgUpload(id,card,phone); }else{ this.Toast(rs.message,'error') } }) } noDelete(){ this.isShow = false; } hide(){ this.isShow = false } alert(e){ e.stopPropagation(); } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { MyAppService } from './../../my-app.service'; import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; @Component({ selector: 'app-get-cash', templateUrl: './get-cash.component.html', styleUrls: ['./get-cash.component.css'] }) export class GetCashComponent implements OnInit { isLoad:boolean = false; isShow:boolean = false; u_id; p_id; alertMsg; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; alertBtn:number; cashAll; bankChosenC; bankName; cid; bankCode; cashMoney; getCash:boolean = false; detail:object; platDetailShow:boolean = false; total_0; cost_0; user_money_0; NAME; phone_num; total; constructor(private route: ActivatedRoute, private router: Router, private http: ServiceBaseService, private myService: MyAppService) { } //input isInput(count){ this.cashMoney = count.value if(count.value){ this.getCash = true }else{ this.getCash = false } if(this.cashMoney >= this.cashAll - 3){ this.cashMoney = ''; this.Toast('提现手续费 3 元,已超过最大可提现金额','warning') } } //全部提现 allIn() { this.cashMoney=this.cashAll - 3; this.getCash = true } //提现明细 goCash() { if(this.cashMoney < 100){ this.Toast('提现金额不能小于100元','warning') }else{ this.isLoad = true; this.http.httpPost('Home/order/withdraw_detail',{ total: this.cashMoney, user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ this.isLoad = false; this.detail = data; this.total_0 = this.myService.rund(data.total); this.cost_0 = this.myService.rund(data.withdraw_cost); this.user_money_0 = this.myService.rund(data.user_money); this.platDetailShow = true; this.NAME = data.name; this.phone_num = data.phone_number; this.total = data.total; }) } } //提现 closeOk(total) { this.platDetailShow = false; this.isLoad = false; this.http.httpPost('Home/order/tfb_withdraw_add',{ user_id: this.u_id, plat_id: this.p_id, total: total, card_id: this.cid }).subscribe((data:any)=>{ this.isLoad = false; if(data.code == 0){ this.Toast(data.msg,'error') }else{ this.Toast(data.msg,'success'); let t = 3; let time = setInterval(()=>{ t--; if(t == 0){ this.router.navigate(['/home']) } },1000) } }) } //关闭明细 closePlat() { this.platDetailShow = false } ngOnInit() { this.http.setTitle('提现'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.cashAll = this.route.snapshot.paramMap.get('all'); this.bankChosenC = this.route.snapshot.paramMap.get('num'); this.bankName = this.route.snapshot.paramMap.get('name'); this.cid = this.route.snapshot.paramMap.get('id'); this.bankCode = this.route.snapshot.paramMap.get('code'); } //更换卡 replace() { this.router.navigate(['replace']) } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { ServiceBaseService } from './service-base.service'; import { Title } from '@angular/platform-browser'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { public constructor(private tit: Title, private http: ServiceBaseService){} public setTitle(newTitle: string){ this.tit.setTitle(newTitle) } //获取aPPid 并且签名 getApp() { this.http.httpPost('Home/index/wechat_config',{ // plat_id: this.p_id plat_id: 125, url: 'http://wx.ztipay.com/home' }).subscribe((rs:any)=>{ console.log(rs.data.appId) if(rs.data){ wx.config({ debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: rs.data.appId, // 必填,公众号的唯一标识 timestamp: rs.data.timestamp, // 必填,生成签名的时间戳 nonceStr: rs.data.nonceStr, // 必填,生成签名的随机串 signature: rs.data.signature,// 必填,签名 jsApiList: ['chooseImage','previewImage','uploadImage'] // 必填,需要使用的JS接口列表 }); } }) } onInit() { // this.getApp() } } <file_sep>import { MyAppService } from './../../my-app.service'; import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; @Component({ selector: 'app-userpage', templateUrl: './userpage.component.html', styleUrls: ['./userpage.component.css'] }) export class UserpageComponent implements OnInit { NAME; u_id; p_id; tot_0; tot_1; tot_2; t_0:number = 0.00; t_1:number = 0.00; t_2:number = 0.00; isLoad:boolean = false; rz_status:any; rz_remark:any; huiyuan; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; isShow:boolean = false; alert_msg:string; phoneAlert:boolean = false; phone; constructor(private http: ServiceBaseService, private myHttp: MyAppService, private router: Router, private route: ActivatedRoute) { } //获取账户信息 getMsg() { this.http.httpPost('Home/index/mean',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ localStorage.setItem('balance',data.balance); localStorage.setItem('total',data.total); localStorage.setItem('commission',data.commission); }) } //获取用户信息 getUser(): void { this.isLoad = true this.http.httpPost('Home/index/user',{ user_id: this.u_id }) .subscribe((data:any)=>{ this.isLoad = false; /**认证状态 * 0 ==> 未认证 * 1 ==> 审核中 * 3 ==> 驳回 * 2 ==> 通过* */ sessionStorage.setItem('rz_status',data.data.status); /**驳回原因 */ sessionStorage.setItem('rz_remark',data.data.remark); /**会员等级 * card_bag_status == 0 非会员 * card_bag_status == 1 普通会员 * card_bag_status == 2 高级会员 */ sessionStorage.setItem('huiyuan',data.data.card_bag_status); /**姓名 */ sessionStorage.setItem('NAME',data.data.name); /** 身份证号 */ sessionStorage.setItem('NAME_id',data.data.identity_number); /**商户 ID */ sessionStorage.setItem('merchantCode',data.data.m_id); /**客服 */ sessionStorage.setItem('phone',data.data.service_phone) }) } //显示账户余额信息 showTot(value) { // let T = num / 5 let time = setInterval(()=>{ value ++; },5) } //会员页面 goToMember() { //判断认证状态 if(this.rz_status == 0){ this.creatAlert('您还没有进行身份认证') }else if(this.rz_status == 1){ this.Toast('正在审核中,请耐心等待','warning') }else if(this.rz_status == 3){ this.creatAlert('您的审核被驳回,驳回原因为:'+this.rz_remark) }else if(this.rz_status == 2){ if(this.huiyuan == 0){ this.router.navigate(['/member']); }else{ this.router.navigate(['/vipCenter',this.huiyuan]); } } } //保障计划 goToInsuracePage() { window.location.href = 'https://ztg.zhongan.com/promote/entrance/promoteEntrance.do?redirectType=h5&promotionCode=INST180333401016&productCode=PRD160341670013&promoteCategory=single_product&token=' } ngOnInit() { this.http.setTitle('个人中心'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.tot_0 = this.myHttp.rund(localStorage.getItem('balance')); this.tot_1 = this.myHttp.rund(localStorage.getItem('total')); this.tot_2 = this.myHttp.rund(localStorage.getItem('commission')); //会员状态 this.rz_status = sessionStorage.getItem('rz_status'); //驳回原因 this.rz_remark = sessionStorage.getItem('rz_remark'); //会员等级 this.huiyuan = sessionStorage.getItem('huiyuan'); //姓名 this.NAME = sessionStorage.getItem('NAME'); //客服 this.phone = sessionStorage.getItem('phone') this.getMsg(); this.getUser(); let time = setInterval(()=>{ this.t_0 += this.tot_0/5; if(this.t_0 == this.tot_0 || this.t_0 >= this.tot_0){ clearInterval(time) } },500) } //alert弹窗方法 creatAlert(msg) { this.isShow = true; this.alert_msg = msg; } //跟提示去认证 confirm() { this.router.navigate(['/upload']) } noDelete(){ this.isShow = false; this.phoneAlert = false; } hide(){ this.isShow = false; this.phoneAlert = false; } alert(e){ e.stopPropagation(); } //官方客服 showConfirm() { this.phoneAlert = true; } call() { this.phoneAlert = false } //退出登录 out() { this.router.navigate(['login',this.p_id]); localStorage.removeItem('user_id') } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { ServiceBaseService } from './../../service-base.service'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-partner', templateUrl: './partner.component.html', styleUrls: ['./partner.component.css'] }) export class PartnerComponent implements OnInit { constructor(private http: ServiceBaseService) { } ngOnInit() { this.http.setTitle('保障计划'); } goToIlnk() { window.location.href = 'http://card.zt717.com/cms/index.php/Backstage/Index/main.html' } } <file_sep>import { BrowserModule, Title } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AppRoutingModule } from './app-routing.module'; import {HashLocationStrategy , LocationStrategy} from '@angular/common'; import { AppComponent } from './app.component'; import { TabsComponent } from './page/tabs/tabs.component'; import { FormsModule } from '@angular/forms'; import { HomepageComponent } from './page/homepage/homepage.component'; import { SharepageComponent } from './page/sharepage/sharepage.component'; import { UserpageComponent } from './page/userpage/userpage.component'; import { LoanSkillsComponent } from './page/loan-skills/loan-skills.component'; import { NotFoundComponent } from './page/not-found/not-found.component'; import { CardSkillsComponent } from './page/card-skills/card-skills.component'; import { MyAppService } from './my-app.service'; import { MessagesComponent } from './page/messages/messages.component'; import { PassComponent } from './page/pass/pass.component'; import { PassDetailComponent } from './page/pass-detail/pass-detail.component'; import { ReimbursementComponent } from './page/reimbursement/reimbursement.component'; import { TaskListComponent } from './page/task-list/task-list.component'; import { HttpClientModule } from '@angular/common/http'; import { ServiceBaseService } from './service-base.service'; import { AlertComponent } from './module/alert/alert.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AddTaskComponent } from './page/add-task/add-task.component'; import { TaskDetailComponent } from './page/task-detail/task-detail.component'; import { AddPayCardComponent } from './page/add-pay-card/add-pay-card.component'; import { PayInstallComponent } from './page/pay-install/pay-install.component'; import { WalletComponent } from './page/wallet/wallet.component'; import { GetCashComponent } from './page/get-cash/get-cash.component'; import { ShareDetailComponent } from './page/share-detail/share-detail.component'; import { MemberComponent } from './page/member/member.component'; import { MemberShipComponent } from './page/member-ship/member-ship.component'; import { QrcodeComponent } from './page/qrcode/qrcode.component'; import { AddBankCardComponent } from './page/add-bank-card/add-bank-card.component'; import { VipCenterComponent } from './page/vip-center/vip-center.component'; import { MoreComponent } from './page/more/more.component'; import { SecurityCenterComponent } from './page/security-center/security-center.component'; import { ReplaceBankCardComponent } from './page/replace-bank-card/replace-bank-card.component'; import { PartnerComponent } from './page/partner/partner.component'; import { NewPartnerComponent } from './page/new-partner/new-partner.component'; import { UpLoadComponent } from './page/up-load/up-load.component'; import { LoginComponent } from './page/login/login.component'; import { QrCodeComponent } from './page/qr-code/qr-code.component'; import { ServiceWorkerModule } from '@angular/service-worker'; import { environment } from '../environments/environment'; @NgModule({ declarations: [ AppComponent, TabsComponent, HomepageComponent, SharepageComponent, UserpageComponent, LoanSkillsComponent, NotFoundComponent, CardSkillsComponent, MessagesComponent, PassComponent, PassDetailComponent, ReimbursementComponent, TaskListComponent, AlertComponent, AddTaskComponent, TaskDetailComponent, AddPayCardComponent, PayInstallComponent, WalletComponent, GetCashComponent, ShareDetailComponent, MemberComponent, MemberShipComponent, QrcodeComponent, AddBankCardComponent, VipCenterComponent, MoreComponent, SecurityCenterComponent, ReplaceBankCardComponent, PartnerComponent, NewPartnerComponent, UpLoadComponent, LoginComponent, QrCodeComponent ], imports: [ BrowserModule, FormsModule, AppRoutingModule, HttpClientModule, BrowserAnimationsModule, BrowserModule, BrowserAnimationsModule , ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }) ], providers: [ MyAppService, ServiceBaseService, Title, {provide: LocationStrategy, useClass: HashLocationStrategy} ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { ServiceBaseService } from './../../service-base.service'; import { MyAppService } from './../../my-app.service'; import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { switchMap } from 'rxjs/operators'; // import * as swiper from 'swiper' @Component({ selector: 'app-homepage', templateUrl: './homepage.component.html', styleUrls: ['./homepage.component.css'] }) export class HomepageComponent implements OnInit { config; isLoad:boolean = false; u_id; p_id; notice:string; rz_status; rz_remark; huiyuan; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; isShow:boolean = false; alert_msg:string; alertType; phoneAlert:boolean = false; phone; phoneTit; shareLink; imgList:any; browser={ versions:function(){ var u = navigator.userAgent, app = navigator.appVersion; return { trident: u.indexOf('Trident') > -1, //IE内核 presto: u.indexOf('Presto') > -1, //opera内核 webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核 mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端 ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端 iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器 iPad: u.indexOf('iPad') > -1, //是否iPad webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部 weixin: u.indexOf('MicroMessenger') > -1, //是否微信 (2015-01-22新增) }; }() } constructor(private myAppServe: MyAppService, private route: ActivatedRoute, private router: Router, private appService: ServiceBaseService) { } //获取注册链接 getLink() { this.appService.httpPost('Home/index/url',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((rs:any)=>{ this.shareLink=rs.toString(); localStorage.setItem('shareLink',this.shareLink) }) } //获取aPPid 并且签名 getApp() { this.appService.httpPost('Home/index/wechat_config',{ // plat_id: this.p_id plat_id: 125, url: 'http://wx.ztipay.com/' }).subscribe((rs:any)=>{ console.log(rs.data.appId) if(rs.data){ wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: rs.data.appId, // 必填,公众号的唯一标识 timestamp: rs.data.timestamp, // 必填,生成签名的时间戳 nonceStr: rs.data.nonceStr, // 必填,生成签名的随机串 signature: rs.data.signature,// 必填,签名 jsApiList: ['chooseImage','previewImage','uploadImage','onMenuShareAppMessage','onMenuShareTimeline'] // 必填,需要使用的JS接口列表 }); wx.ready(function(){ wx.onMenuShareTimeline({ title: '100万信用卡客户都在使用!', // 分享标题 link: localStorage.getItem('shareLink'), // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: 'http://card.zt717.com/Public/Home/img/plat_logo/'+localStorage.getItem('plat_id')+'_logo.png', // 分享图标 success: function () { // 用户确认分享后执行的回调函数 }, cancel: function () { // 用户取消分享后执行的回调函数 } }); wx.onMenuShareAppMessage({ title: '100万信用卡客户都在使用!', // 分享标题 desc: "我是" + sessionStorage.getItem('NAME') + ",邀请你使用智能卡管家,信用卡刷卡、代还非常安全方便," + sessionStorage.getItem('NAME') + "和他的朋友都在使用!", // 分享描述 link: localStorage.getItem('shareLink'), // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: 'http://card.zt717.com/Public/Home/img/plat_logo/'+localStorage.getItem('plat_id')+'_logo.png', // 分享图标 type: '', // 分享类型,music、video或link,不填默认为link dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空 success: function () { // 用户确认分享后执行的回调函数 }, cancel: function () { // 用户取消分享后执行的回调函数 } }); }) } }) } //获取用户信息 getUser(): void { this.isLoad = true this.appService.httpPost('Home/index/user',{ user_id: this.u_id }) .subscribe((data:any)=>{ this.isLoad = false; /**认证状态 * 0 ==> 未认证 * 1 ==> 审核中 * 3 ==> 驳回 * 2 ==> 通过* */ sessionStorage.setItem('rz_status',data.data.status); /**驳回原因 */ sessionStorage.setItem('rz_remark',data.data.remark); /**会员等级 * card_bag_status == 0 非会员 * card_bag_status == 1 普通会员 * card_bag_status == 2 高级会员 */ sessionStorage.setItem('huiyuan',data.data.card_bag_status); /**姓名 */ sessionStorage.setItem('NAME',data.data.name); /** 身份证号 */ sessionStorage.setItem('NAME_id',data.data.identity_number); /**商户 ID */ sessionStorage.setItem('merchantCode',data.data.m_id); sessionStorage.setItem('phone_number',data.data.phone_number) if(data.data.agent_phone == null ||data.data.agent_phone == ''){ this.phone = data.data.service_phone; this.phoneTit = '官方客服'; }else{ this.phone = data.data.agent_phone; this.phoneTit = data.data.agent_name.charAt(0)+'(先生/女士)'; } }) } //notice getNotice(): void { this.appService.httpPost('Home/index/notice',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ this.notice = data.data }) } //轮播图 getSilder() { this.appService.httpPost('Home/index/slides',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((rs:any)=>{ if(rs.data.length){ this.imgList=rs.data; }else{ this.imgList = [ {image:"../../../assets/img/banner.png",link:""}, {image:"../../../assets/img/banner2.png",link:"https://ztg.zhongan.com/promote/entrance/promoteEntrance.do?redirectType=h5&promotionCode=INST180333401016&productCode=PRD160341670013&promoteCategory=single_product&token="}, {image:"../../../assets/img/banner3.png",link:""}, ] } }) } //点击通道 pass() { if(!this.rz_status){ this.ngOnInit(); if(this.rz_status == 0){ this.creatAlert('您还没有进行身份认证',0) }else if(this.rz_status == 1){ this.Toast('正在审核中,请耐心等待','warning') }else if(this.rz_status == 3){ this.creatAlert('您的审核被驳回,驳回原因为:'+this.rz_remark,0) }else if(this.rz_status == 2){ this.router.navigate(['/pass']); } }else{ if(this.rz_status == 0){ this.creatAlert('您还没有进行身份认证',0) }else if(this.rz_status == 1){ this.Toast('正在审核中,请耐心等待','warning') }else if(this.rz_status == 3){ this.creatAlert('您的审核被驳回,驳回原因为:'+this.rz_remark,0) }else if(this.rz_status == 2){ this.router.navigate(['/pass']); } } } //点击还款 payback() { if(!this.rz_status){ this.ngOnInit(); if(this.rz_status == 0){ this.creatAlert('您还没有进行身份认证',0) }else if(this.rz_status == 1){ this.Toast('正在审核中,请耐心等待','warning') }else if(this.rz_status == 3){ this.creatAlert('您的审核被驳回,驳回原因为:'+this.rz_remark,0) }else if(this.rz_status == 2){ if(this.huiyuan == 0){ this.creatAlert('成为会员开通此功能',1) }else{ this.router.navigate(['/payback']); } } }else{ if(this.rz_status == 0){ this.creatAlert('您还没有进行身份认证',0) }else if(this.rz_status == 1){ this.Toast('正在审核中,请耐心等待','warning') }else if(this.rz_status == 3){ this.creatAlert('您的审核被驳回,驳回原因为:'+this.rz_remark,0) }else if(this.rz_status == 2){ if(this.huiyuan == 0){ this.creatAlert('成为会员开通此功能',1) }else{ this.router.navigate(['/payback']); } } } } more() { this.Toast('即将开放,敬请期待','warning') } //伦比图 ngOnInit() { this.getSilder(); var mySwiper = new Swiper ('.swiper-container', { direction: 'horizontal', loop: true, // 如果需要分页器 pagination: { el: '.swiper-pagination', dynamicBullets: true, }, speed: 500, autoplay: { delay: 5000, stopOnLastSlide: false, disableOnInteraction: true, }, }) this.appService.setTitle('管家'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.getUser(); this.getNotice(); //会员状态 this.rz_status = sessionStorage.getItem('rz_status'); //驳回原因 this.rz_remark = sessionStorage.getItem('rz_remark'); //会员等级 this.huiyuan = sessionStorage.getItem('huiyuan'); // if(this.browser.versions.ios){ // this.getApp() // } this.getApp() this.getLink() } //alert弹窗方法 1 ==> 会员, 0 ==> 认证 creatAlert(msg,type) { this.isShow = true; this.alert_msg = msg; this.alertType = type; } //跟提示去认证/购买会员 confirm() { if(this.alertType == 0){ this.router.navigate(['/upload']) }else{ this.router.navigate(['/member']) } } noDelete(){ this.isShow = false; this.phoneAlert = false } hide(){ this.isShow = false } alert(e){ e.stopPropagation(); } //官方客服 showConfirm() { this.phoneAlert = true; } call() { this.phoneAlert = false } //消息提示框 Toast(msg,type) { let isTime; if(this.toastTime == 3){ isTime = true; this.toastType = type; this.isDis = true; this.toastMsg = msg; }else if(this.toastTime >= 0 && this.toastTime <3) { isTime = false; }else{ isTime = false; this.isDis = false } let time = setInterval(()=>{ if(isTime == true) { this.toastTime--; } // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } }<file_sep>import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { MyAppService } from './../../my-app.service'; @Component({ selector: 'app-pass-detail', templateUrl: './pass-detail.component.html', styleUrls: ['./pass-detail.component.css'] }) export class PassDetailComponent implements OnInit { bankList = []; items = [] u_id; p_id; m_id; id; min; max; name; card_id; isShow:boolean = false; isLoad:boolean = false; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; //金额输入框 toPay:boolean = false; bankName; addCardMsg:string; deletecard:boolean = false; cardNum; constructor(private myService: MyAppService, private http: ServiceBaseService, private router: Router, private route: ActivatedRoute) { } //读取可选银行列表 readList(k) { if(k == 1){ this.isLoad = true; this.http.httpPost('Home/index/payment_support_banks',{ user_id: this.u_id, pm_id: this.m_id }).subscribe((data:any)=>{ this.isLoad = false; if(data.code == 1){ this.bankList = data.data; this.items = data.data }else{ this.Toast(data.msg,'error') } }) }else{ this.items = this.bankList } } //搜索 getItems(ev: any) { // Reset items back to all of the items this.readList(0) // set val to the value of the searchbar let val = ev.target.value; // if the value is an empty string don't filter the items if (val && val.trim() != '') { this.items = this.items.filter((item) => { return (item.bank_name.toLowerCase().indexOf(val.toLowerCase()) > -1); }) } } //选择一个银行后的方法 choiceBank(k,e,v,code,name,card,num) { localStorage.setItem('bank_num',num); localStorage.setItem('bank_code',code); this.bankName = name; this.cardNum = card; if(!k){ this.deletecard = false; this.isShow = true; this.addCardMsg = '您还未添加改行信用卡,是否前往添加?' }else{ this.card_id = k //如果不需要绑卡 if(localStorage.getItem('bindcard_url') == 'null'){ this.toPay = true }else{ //需要绑卡 this.isLoad = true; this.http.httpPost("Home/"+localStorage.getItem('bindcard_url')+"",{ pay_method_id:this.m_id, user_id: this.u_id, id: this.id }).subscribe((data:any)=>{ this.isLoad = false; if(data.code == 1){ this.toPay = true; }else{ this.Toast(data.msg,'error'); this.Toast(data.msg,'error') } }) } } } //添加/更护卡 alertAddcard(e) { e.stopPropagation() if(this.deletecard == false){ this.router.navigate(['/addPayCard',this.bankName,this.m_id,this.id,this.min,this.max,this.name]); }else{ //先删除 this.isShow = false; this.isLoad = true; this.http.httpPost('Home/card/delete',{ plat_id: this.p_id, user_id: this.u_id, id: this.card_id, type: 2 }).subscribe((data:any)=>{ this.isLoad = false; if(data.code == 1){ this.router.navigate(['/addPayCard',this.bankName,this.m_id,this.id,this.min,this.max,this.name]); }else{ this.Toast(data.msg,'error') } }) } } addCard(e,num,code,name) { e.stopPropagation(); localStorage.setItem('bank_num',num); localStorage.setItem('bank_code',code); this.bankName = name this.router.navigate(['/addPayCard',this.bankName,this.m_id,this.id,this.min,this.max,this.name]); } //更换卡 changeCard(k,j,e,name,code,num) { e.stopPropagation(); localStorage.setItem('bank_num',num); localStorage.setItem('bank_code',code); this.bankName = name this.isShow = true; this.addCardMsg = '更换信用卡会删除尾号为 '+j+' 的卡,是否继续?'; this.deletecard = true; this.card_id = k } ngOnInit() { this.http.setTitle('快捷收款'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.m_id = this.route.snapshot.paramMap.get('pm_id'); this.id = this.route.snapshot.paramMap.get('id'); this.min = this.route.snapshot.paramMap.get('minPay'); this.max = this.route.snapshot.paramMap.get('maxPay'); this.name = this.route.snapshot.paramMap.get('name'); this.readList(1) } //弹框 输入金额 --> 支付 noDelete(){ this.toPay = false; this.isShow = false; } hide(){ this.toPay = false this.isShow = false; } alert(e){ e.stopPropagation(); } delete(total) { this.toPay = false; if(Number(total.value)<this.min || Number(total.value)>this.max){ this.Toast('请输入 '+this.min+' 至 '+this.max+' 范围的金额','warning') }else{ //直接支付 --> 跳转 if(localStorage.getItem('is_jump') == '1'){ this.toJump(total) }//前往支付详情页面 else{ this.toInstall(total) } } } //跳转第三方支付 toJump(total) { this.isLoad = true this.http.httpPost('Home/order/pay',{ id: this.id, card_id: this.card_id, user_id: this.u_id, total: total.value, card_cvv: 123, card_date: 1234, plat_id: this.p_id, phone: '00000000000', type: 'YT100' }).subscribe((data:any)=>{ this.isLoad = false; if(data.code == 1){ if(data.url){ // window.open(data.url) window.location.href = data.url }else{ this.Toast(data.msg,'error') } }else{ this.Toast(data.msg,'error') } }) } //跳转 payInstall 支付 toInstall(total) { //payInstall/:total/:cardName/:cardId/:cardNum/:passId/:passName this.router.navigate(['/payInstall',total.value,this.bankName,this.card_id,this.cardNum,this.id,this.name]) } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { ServiceBaseService } from './../../service-base.service'; import { MyAppService } from './../../my-app.service'; import { Component, OnInit } from '@angular/core'; import {Title} from "@angular/platform-browser"; @Component({ selector: 'app-loan-skills', templateUrl: './loan-skills.component.html', styleUrls: ['./loan-skills.component.css'] }) export class LoanSkillsComponent implements OnInit { constructor(public myAppServe: MyAppService, private http: ServiceBaseService) { } ngOnInit() { this.http.setTitle('办卡网贷技巧'); } ngAfterContentInit() { this.myAppServe.setTit('办卡网贷技巧') } } <file_sep>import { MyAppService } from './../../my-app.service'; import { ServiceBaseService } from './../../service-base.service'; import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; @Component({ selector: 'app-pass', templateUrl: './pass.component.html', styleUrls: ['./pass.component.css'] }) export class PassComponent implements OnInit { u_id; p_id; isLoad:boolean = false; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; passChosen:boolean = false; passList; chicked; isTrading; startTime; endTime; status; bindcard_url; message_url; is_jump; pick_card; m_id; id; min; max; name; //金额输入框 toPay:boolean = false; constructor(private http: ServiceBaseService, private myService: MyAppService, private route: ActivatedRoute, private router: Router,) { } //获取通道数据 readPass() { this.isLoad = true; this.http.httpPost('Home/order/payment_method',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((data:any)=>{ this.isLoad = false; this.passList = data; for(let i=0;i<data.length;i++){ this.passList[i].pay_cost_i = this.myService.rund(data[i].pay_cost); } }) } //点击一条通道时 chosenOne(i,t,start,end,status,b_url,m_url,jump,pick,m_id,id,min,max,name) { this.chicked = i; this.passChosen = true; this.isTrading = t; this.startTime = start; this.endTime = end; this.status = status; this.bindcard_url = b_url; this.message_url = m_url; this.is_jump = jump; this.pick_card = pick; this.m_id = m_id; this.id = id; this.min = min; this.max = max; this.name = name; } //点击下一步 goToPassDetail() { if(this.isTrading == 0){ this.Toast('此通道交易时间为 '+this.startTime+':00 ~ '+this.endTime+':00','warning') }else{ if(this.status == 0){ this.Toast('该通道今日额度已满,请更换其他通道或者明天再进行交易','warning') }else{ localStorage.setItem('bindcard_url',this.bindcard_url); localStorage.setItem('message_url',this.message_url); localStorage.setItem('is_jump',this.is_jump); //需要选卡 if(this.pick_card == 1){ this.newPassDetail() }//不用选卡 else{ //是否需要绑卡 //否 bindcard_url 为空 if(localStorage.getItem('bindcard_url') == 'null'){ //输入金额 --> 支付 this.toPay = true; }else{ this.isLoad = true; this.http.httpPost("Home/"+localStorage.getItem('bindcard_url')+"",{ pay_method_id:this.m_id, user_id: this.u_id, id: this.id }).subscribe((data:any)=>{ this.isLoad = false; if(data.code == 1){ this.toPay = true }else{ this.Toast(data.msg,'error'); this.Toast(data.message,'error') } }) } } } } } //前往选卡页面 newPassDetail() { this.router.navigate(['/passDetail',this.m_id,this.id,this.min,this.max,this.name]); } ngOnInit() { this.http.setTitle('快捷收款'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.readPass() } //弹框 输入金额 --> 支付 noDelete(){ this.toPay = false; } hide(){ this.toPay = false } alert(e){ e.stopPropagation(); } delete(total) { this.toPay = false; console.log(total) if(Number(total.value)<this.min || Number(total.value)>this.max){ this.Toast('请输入 '+this.min+' 至 '+this.max+' 范围的金额','warning') }else{ this.isLoad = true; this.http.httpPost('Home/order/pay',{ id: this.id, card_id: 123, user_id: this.u_id, total: total.value, card_cvv: 123, card_date: 1234, plat_id: this.p_id, phone: '00000000000', type: 'YT100' }).subscribe((data:any)=>{ this.isLoad = false; if(data.code == 1){ if(data.url){ // window.open() window.location.href = data.url; }else{ this.Toast(data.msg,'error') } }else{ this.Toast(data.msg,'error') } }) } } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { MyAppService } from './../../my-app.service'; import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; @Component({ selector: 'app-qrcode', templateUrl: './qrcode.component.html', styleUrls: ['./qrcode.component.css'] }) export class QrcodeComponent implements OnInit { link; show:number = 0; index: number = 1; vip; vip2; u_id; p_id; constructor(private route: ActivatedRoute, private router: Router, private http: ServiceBaseService, private myService: MyAppService) { } ngOnInit() { this.http.setTitle('二维码支付'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.link = this.route.snapshot.paramMap.get('link'); this.http.httpPost('Home/index/user',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((rs:any)=>{ this.vip=rs.data.card_bag_status; }); this.vipChoice(); } vipChoice() { let Timer = setInterval(()=>{ this.index++; if(this.index <= 20){ this.http.httpPost('Home/index/user',{ user_id: this.u_id, plat_id: this.p_id }).subscribe((rs:any)=>{ this.vip2=rs.data.card_bag_status; if(this.vip2 - this.vip >0){ //支付成功 this.show = 1; clearInterval(Timer) } }) }else{ //支付失败 || 超时 this.show = 2; } },2500) } goToTabs() { this.router.navigate(['/user']) } } <file_sep>import { ServiceBaseService } from './../../service-base.service'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-more', templateUrl: './more.component.html', styleUrls: ['./more.component.css'] }) export class MoreComponent implements OnInit { constructor(private http: ServiceBaseService) { } ngOnInit() { this.http.setTitle('更多'); } goToShare() { window.open('http://wx.ztipay.com/share.html') } } <file_sep>import { MyAppService } from './../../my-app.service'; import { ServiceBaseService } from './../../service-base.service'; import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; //这里导入 switchMap 操作符是因为你稍后将会处理路由参数的可观察对象 Observable。 import { switchMap } from 'rxjs/operators'; @Component({ selector: 'app-task-list', templateUrl: './task-list.component.html', styleUrls: ['./task-list.component.css'] }) export class TaskListComponent implements OnInit { classFlag: boolean; u_id; p_id; isLoad:boolean = false; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; taskType; taskList; start; end; cardId; //当前 / 历史任务 task_Detail_type:number; constructor(private route: ActivatedRoute, private router: Router, private http: ServiceBaseService, private myService: MyAppService) { } //获取任务信息 getList(type) { this.isLoad = true; this.http.httpPost('Home/plan/list_plan',{ user_id: this.u_id, plat_id: this.p_id, id: this.route.snapshot.paramMap.get('id'), status: type }).subscribe((data:any)=>{ this.isLoad = false; this.taskType = type; this.taskList = data; for(let i = 0;i<data.length;i++){ this.taskList[i].money=this.myService.rund(data[i].total); this.taskList[i].pay_ok_time=this.myService.timeGet(data[i].start_time,"min"); } if(type == null){ this.task_Detail_type = 0; }else{ this.task_Detail_type = 1; } }) } //点击下一步 goToAddtask() { if(localStorage.getItem('is_frozen') == '1'){ this.Toast('存在多个账号,该功能已禁用','warning') }else if(this.start == '0' || this.end == '0'){ this.Toast('请先设置账单日 / 还款日','warning') }else{ this.isTask() } } //判断是否出账 isTask() { // this.isLoad = true; let today = new Date().getDate(); // this.http.httpPost('Home/card/detail',{ // user_id: this.u_id, // plat_id: this.p_id, // id: this.route.snapshot.paramMap.get('id') // }).subscribe((data:any)=>{ // this.isLoad = false; // }) //账 < 还 if(this.start - this.end < 0) { //1、今<账 2、还<今 if( today < this.start || this.end < today){ this.Toast('账单未出,请在账单日后执行任务','warning') }else if(this.end - today <2){ this.Toast('还款日当天及还款日前一天无法执行任务','warning') }else{ // this.navCtrl.push(AddtaskPage,{ // cardId: this.cardId, // start: this.start, // end: this.end // }); this.router.navigate(['/addTask',this.cardId,this.start,this.end]) } } //还 < 账 if(this.end-this.start<0){ //今 > 还 && 今 < 账 if(today>this.end&&today<this.start){ this.Toast('账单未出,请在账单日后执行任务','warning') }else{ // this.navCtrl.push(AddtaskPage,{ // cardId: this.cardId, // start: this.start, // end: this.end // }); this.router.navigate(['/addTask',this.cardId,this.start,this.end]); } } } //任务详情 goToTaskDetail(id,money,num,type) { this.router.navigate(['/taskDetail',id,money,num,type]) } ngOnInit() { this.http.setTitle('我的任务'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.cardId = this.route.snapshot.paramMap.get('id'); this.start = this.route.snapshot.paramMap.get('start'); this.end = this.route.snapshot.paramMap.get('end') this.getList(null) } changeClass(type) { // this.getList(type) if(this.taskType == type){ this.classFlag = this.classFlag; }else{ this.classFlag = !this.classFlag; this.getList(type); } } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { MyAppService } from './../../my-app.service'; @Component({ selector: 'app-member-ship', templateUrl: './member-ship.component.html', styleUrls: ['./member-ship.component.css'] }) export class MemberShipComponent implements OnInit { data; u_id; p_id; money; isCode; NAME; NAME_id; isLoad:boolean = false; isShow:boolean = false; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; bindCard:boolean = false; time = 150; link; constructor(private myService: MyAppService, private http: ServiceBaseService, private router: Router, private route: ActivatedRoute) { } //读取用户信息 getUser() { this.isLoad = true this.http.httpPost('Home/index/user',{ user_id: this.u_id }) .subscribe((data:any)=>{ this.isLoad = false; /**认证状态 * 0 ==> 未认证 * 1 ==> 审核中 * 3 ==> 驳回 * 2 ==> 通过* */ localStorage.setItem('rz_status',data.data.status); /**驳回原因 */ localStorage.setItem('rz_remark',data.data.remark); /**会员等级 * card_bag_status == 0 非会员 * card_bag_status == 1 普通会员 * card_bag_status == 2 高级会员 */ localStorage.setItem('huiyuan',data.data.card_bag_status); /**姓名 */ localStorage.setItem('NAME',data.data.name); /** 身份证号 */ localStorage.setItem('NAME_id',data.data.identity_number) }) } //input onKey(a,b,c,d) { if(a.value && b.value && c.value && d.value){ this.bindCard = true }else{ this.bindCard = false } } //点击开通 addCard(phone,cardId,date,cvv) { if(!sessionStorage.getItem('isToPay')){ // isCode ==0 无验证码 if(this.isCode == 0){ //普通支付 this.pay_0(phone,cardId,date,cvv) }else{ //验证码支付 } }else{ this.Toast('操作过于频繁,请于2分钟后再试','warning') } } //普通支付 pay_0(phone,cardId,date,cvv) { this.isLoad = true; this.http.httpPost('Home/'+this.link+'',{ pay_type: this.data, payCard: cardId.value, certNo: this.NAME_id, CVN2: cvv.value, cardExpYear: (date.value).substr(date.value.length-2), cardExpMonth: (date.value).substr(0,2), name: this.NAME, tel: phone.value, amount: this.money, user_id: localStorage.getItem('user_id') }).subscribe((rs:any)=>{ this.isLoad = false; if(rs.code == 1){ this.daoTime(); this.Toast(rs.msg,'success'); let t = 3; let time = setInterval(()=>{ t--; if(t == 0){ this.router.navigate(['/home']) } },1000) }else{ this.Toast(rs.msg,'error') } }) } ngOnInit() { this.http.setTitle('会员权益'); this.u_id = localStorage.getItem('user_id'); this.p_id = localStorage.getItem('plat_id'); this.data = this.route.snapshot.paramMap.get('type'); this.money = this.route.snapshot.paramMap.get('money'); this.isCode = this.route.snapshot.paramMap.get('code'); //姓名 this.NAME = sessionStorage.getItem('NAME'); this.NAME_id = sessionStorage.getItem('NAME_id'); this.link = sessionStorage.getItem('LINK') this.getUser(); } //防重复支付 daoTime() { sessionStorage.setItem('isToPay','false') let T = setInterval(()=>{ this.time--; if(this.time == 0){ this.time = 150; sessionStorage.removeItem('isToPay') clearInterval(T) } },1000) } //消息提示框 Toast(msg,type) { if(this.toastTime == 3){ this.toastType = type; this.isDis = true; this.toastMsg = msg; }else{ this.isDis = false } let time = setInterval(()=>{ this.toastTime--; // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ServiceBaseService } from '../../service-base.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; @Component({ selector: 'app-tabs', templateUrl: './tabs.component.html', styleUrls: ['./tabs.component.css'] }) export class TabsComponent implements OnInit { item:number = 1; toastMsg:string; toastType:string = ''; isDis:boolean = false; toastTime:number = 3; constructor(private http: ServiceBaseService, private router: Router, private route: ActivatedRoute) { } ngOnInit() { } goToMall() { this.Toast('即将开放,敬请期待','warning') } // OnItemClick(value){ // this.item = value; // } // mall() { // this.router.navigate(['/mall']); // this.http.setTitle('商城') // } // home() { // this.router.navigate(['/home']); // this.http.setTitle('管家') // } // share() { // this.router.navigate(['/share']); // this.http.setTitle('分享赚钱') // } // user() { // this.router.navigate(['/user']); // this.http.setTitle('个人中心') // } //消息提示框 Toast(msg,type) { let isTime; if(this.toastTime == 3){ isTime = true; this.toastType = type; this.isDis = true; this.toastMsg = msg; }else if(this.toastTime >= 0 && this.toastTime <3) { isTime = false; }else{ isTime = false; this.isDis = false } let time = setInterval(()=>{ if(isTime == true) { this.toastTime--; } // console.log(this.toastTime) if(this.toastTime<=0){ clearInterval(time) this.toastTime = 3; this.isDis = false; } },1000) } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { SecurityCenterComponent } from './security-center.component'; describe('SecurityCenterComponent', () => { let component: SecurityCenterComponent; let fixture: ComponentFixture<SecurityCenterComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ SecurityCenterComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SecurityCenterComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
75848e2a5e8357cd0362933cb5571a34417174db
[ "TypeScript" ]
34
TypeScript
Jingws/WC_pwa
0a622517ef62e3c4952c59c0bee1d0d4fc75a869
de7aa50b66829f130bcf5a832964891a41b8df46
refs/heads/master
<repo_name>suelitonoliveira/loja<file_sep>/src/main/java/br/com/alura/microsservice/loja/client/FornecedorClient.java package br.com.alura.microsservice.loja.client; import br.com.alura.microsservice.loja.dto.InfoForncedorDTO; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @FeignClient("fornecedor") public interface FornecedorClient { @RequestMapping("/info/{estado}") InfoForncedorDTO getInfoPorEstado(@PathVariable String estado); } <file_sep>/src/main/java/br/com/alura/microsservice/loja/service/CompraService.java package br.com.alura.microsservice.loja.service; import br.com.alura.microsservice.loja.client.FornecedorClient; import br.com.alura.microsservice.loja.dto.CompraDTO; import br.com.alura.microsservice.loja.dto.InfoForncedorDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class CompraService { @Autowired private FornecedorClient fornecedorClient; public void realizaCompra(CompraDTO compraDTO) { InfoForncedorDTO info = fornecedorClient.getInfoPorEstado(compraDTO.getEndereco().getEstado()); System.out.println(info.getEndereco()); } }
f0e526dbe3b2ea059ac44f80c0e7ab1d9f28a078
[ "Java" ]
2
Java
suelitonoliveira/loja
f5b88ea385c8ecbe7400560f6fd2d046917ec444
0336bb9e00183607bee8bb9e82e5be20185c474a
refs/heads/master
<file_sep>package project.Dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import project.vo.ProjectVO; public class ProjectDao { private static ProjectDao dao = new ProjectDao(); private ProjectDao() {} public static ProjectDao getInstance() { return dao; } public Connection connect() { Connection conn = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","<PASSWORD>"); }catch(Exception e) { System.out.print("MDAO:connect" + e); } return conn; } public void close(Connection conn, PreparedStatement pstmt) { if(pstmt != null) { try { pstmt.close(); }catch(Exception e) { System.out.print("Pstmt close error" + e); } } if(conn != null) { try { conn.close(); } catch(Exception e) { System.out.print("Conn close error" + e); } } } public void close(Connection conn, PreparedStatement pstmt, ResultSet rs) { if(rs != null) { try { rs.close(); } catch(Exception e) { System.out.print("rs close error" + e); } } close(conn, pstmt); } public void join(ProjectVO project) { Connection conn = null; PreparedStatement pstmt = null; try { conn = connect(); pstmt = conn.prepareStatement("insert into customer values(?,?,?,?,?,?,?);"); pstmt.setString(1, project.getId()); pstmt.setString(2, project.getPwd()); pstmt.setString(3, project.getName()); pstmt.setString(4, project.getAddr()); pstmt.setString(5, project.getBirth()); pstmt.setString(6, project.getGender()); pstmt.setString(7, project.getPhone()); pstmt.executeUpdate(); }catch(Exception e) { System.out.print("join error" + e); } finally { close(conn, pstmt); } } public boolean login(String id, String pwd) { // TODO Auto-generated method stub boolean result = false; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; System.out.print(pwd); try { conn = connect(); pstmt = conn.prepareStatement("select * from customer where id = ? and pwd = ?;"); pstmt.setString(1, id); pstmt.setString(2, pwd); rs = pstmt.executeQuery(); if(rs.next()) { result = true; } else result = false; }catch(Exception e) { System.out.print("login error" + e); } finally { close(conn, pstmt, rs); } return true; } /** * 아이디 중복체크를 한다. * @param id 아이디 * @return x : 아이디 중복여부 확인값 */ public boolean duplicateIdCheck(String id) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; boolean x = false; try { conn = connect(); pstmt = conn.prepareStatement("select id from customer where id = ?;"); pstmt.setString(1, id); rs = pstmt.executeQuery(); if(rs.next()) x= true; //해당 아이디 존재 return x; }catch(Exception e) { throw new RuntimeException(e.getMessage()); } finally { try{ if ( pstmt != null ){ pstmt.close(); pstmt=null; } if ( conn != null ){ conn.close(); conn=null; } }catch(Exception e){ throw new RuntimeException(e.getMessage()); } } } } <file_sep>package project.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import project.service.Service; import project.vo.ProjectVO; public class Join implements Controller { @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String id = request.getParameter("id"); String pwd = request.getParameter("pwd"); String name = request.getParameter("name"); String addr1= request.getParameter("postAddr1"); String addr2= request.getParameter("postAddr2"); String addr3= request.getParameter("postAddr3"); String addr = addr1+" "+addr2+" "+addr3; String birthyear = request.getParameter("birthyear"); String birthmonth = request.getParameter("birthmonth"); String birthdate = request.getParameter("birthdate"); String birth = birthyear+"-"+birthmonth+"-"+birthdate; String gender = request.getParameter("gender"); String phone = request.getParameter("phone"); ProjectVO project = new ProjectVO(); project.setId(id); project.setPwd(pwd); project.setName(name); project.setAddr(addr); System.out.print(addr); project.setBirth(birth); System.out.print(birth); project.setGender(gender); project.setphone(phone); Service s = Service.getInstance(); s.join(project); HttpUtil.forward(request, response, "Login.jsp"); } } <file_sep>package project.service; import project.Dao.ProjectDao; import project.vo.ProjectVO; public class Service { private static Service service = new Service(); private Service() {} private ProjectDao dao = ProjectDao.getInstance(); public static Service getInstance() { return service; } public void join(ProjectVO project) { // TODO Auto-generated method stub dao.join(project); } public boolean login(String id, String pwd) { // TODO Auto-generated method stub System.out.print("service login :" + pwd); return dao.login(id, pwd); } } <file_sep>package project.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import project.Dao.ProjectDao; public class CheckAction implements Controller { @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String id = request.getParameter("id"); ProjectDao dao = ProjectDao.getInstance(); boolean result = dao.duplicateIdCheck(id); response.setContentType("text/html;charset=euc-kr"); PrintWriter out = response.getWriter(); if(result) out.println("0"); // 아이디 중복 else out.println("1"); out.close(); return; } }
4ba7ef56685cebb35f0ea6ce15e5dbd0db13b97b
[ "Java" ]
4
Java
rkskekfk0714/shopping
50fa72f4c6211be98e750e4cb2422de8185c7caf
2093f2108289ca8d63ecaddff35bde6552632f23
refs/heads/master
<file_sep># game.it ![game.it screenshot](https://i.imgur.com/0QPgqk5.png) ## Description ### Why use game.it? Matching up schedules with friends to play games can be challenging. game.it allows you to organize your library of games and find friends whose gaming schedule matches yours. Refer to our **[pitch deck] (https://docs.google.com/presentation/d/1qFdi90fd_jwdA3fpyFWXa1wVl13V30wu9pCUJlc1QaA/edit#slide=id.p)** for more information. ## Technologies Used - HTML - CSS - JavaScript - Node - Express - MongoDB - Mongoose - Bulma - Socket.io - OAuth - IGDB API - Trello ## API Endpoints Access our API at https://game-it.herokuapp.com/api/games ## Getting Started Go to **[game.it] (https://game-it.herokuapp.com/).** ## How to Use game.it Build your profile, add games to your library, and start making friends. ## Next Steps ### *Bugs* The footer does not stick to the end of the page. Upon creating a profile, user information must be required. ### *Build On!* Please refer to our **[Trello] (https://trello.com/b/PXILni5g/gamr-app)** for suggestions on additional features.<file_sep>var mongoose = require('mongoose'); var Schema = mongoose.Schema; var GameSchema = new Schema({ apiId: String, title: String, description: String, platforms: [String], releaseDate: Date, coverImage: String, publishers: [String], gameUsers: [{type: Schema.Types.ObjectId, ref: 'User'}] }, { timestamps: true }); module.exports = mongoose.model('Game', GameSchema);<file_sep>var router = require('express').Router(); var chatsCtrl = require('../controllers/chats'); router.get('/', isLoggedIn, chatsCtrl.index); router.post('/rooms', isLoggedIn, chatsCtrl.createRoom); router.delete('/rooms/:id', isLoggedIn, chatsCtrl.destroyRoom); function isLoggedIn(req, res, next) { if ( req.isAuthenticated() ) return next(); res.redirect('/auth/google'); } module.exports = router;<file_sep>var express = require('express'); var router = express.Router(); var gamesCtrl = require('../controllers/api/games'); router.get('/', gamesCtrl.getAllGames); router.get('/:id', gamesCtrl.getOneGame); module.exports = router;<file_sep>var Game = require('../../models/game'); module.exports = { getAllGames, getOneGame } function getAllGames(req, res) { Game.find({}, function(err, games) { if (err) return res.status(404).json(err) res.status(200).json(games); }); } function getOneGame(req, res) { Game.findById(req.params.id, function(err, game) { if (err) return res.status(404).json(err); res.status(200).json(game); }) }<file_sep>var express = require('express'); var router = express.Router(); var passport = require('passport'); var usersCtrl = require('../controllers/users'); router.get('/', isLoggedIn, usersCtrl.index); router.get('/', isLoggedIn, usersCtrl.welcome); router.get('/', isLoggedIn, usersCtrl.show); router.get('/edit', isLoggedIn, usersCtrl.edit) router.get('/profile', isLoggedIn, usersCtrl.show); router.get('/:id', isLoggedIn, usersCtrl.show); router.put('/', isLoggedIn, usersCtrl.update); router.delete('/:id', isLoggedIn, usersCtrl.delete); router.get('/:id/games/new', isLoggedIn, usersCtrl.newLibItem) router.post('/:userId/games/:gameId', isLoggedIn, usersCtrl.addLibItem) router.delete('/:userId/games/:gameId', isLoggedIn, usersCtrl.removeLibItem) function isLoggedIn(req, res, next) { if ( req.isAuthenticated() ) return next(); res.redirect('/auth/google'); } module.exports = router; <file_sep>// io.js var io = require('socket.io')(); var ChatRoom = require('./models/chat'); // Listen for new connections from clients (socket) io.on('connection', function (socket) { socket.on('add-message', function (data) { ChatRoom.findById(data.roomId, function(err, room) { var chat = { username: data.name, message: data.msg }; room.chats.push(chat); room.save(function() { chat.createdAt = room.chats[room.chats.length - 1].createdAt; chat.roomId = room.id; io.emit('add-message', chat); }); }); }); }); module.exports = io;<file_sep>var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UserSchema = new Schema({ googleId: String, name: String, email: String, avatar: String, username: String, platforms: [{type: String}], age: Number, gender: String, timezone: String, games: [{type: Schema.Types.ObjectId, ref: 'Game'}] }, { timestamps: true }); // static method to get platforms module.exports = mongoose.model('User', UserSchema);<file_sep>var mongoose = require('mongoose'); var Schema = mongoose.Schema; //Sender of the message var chatSchema = new Schema({ username: String, message: String, }, { timestamps: true }) var chatRoomSchema = new Schema({ users: [{type: Schema.Types.ObjectId, ref: 'User'}], chats: [chatSchema] }); module.exports = mongoose.model('ChatRoom', chatRoomSchema); <file_sep>var User = require('../models/user'); var Game = require('../models/game'); var passport = require('passport'); module.exports = { index, welcome, show, update, edit, delete: destroy, newLibItem, addLibItem, removeLibItem } // Index function index(req, res, next) { var users = User.find({}, function (err, users) { if (err) res.next(err); res.render('users/index', { user: req.user, users }); }); } // Welcome function welcome(req, res, next) { if (req.user && !req.user.username) { res.redirect('/users/edit'); } else { User.find({}, function (err, users) { if (err) res.next(err); Game.find({}, function (err, games) { if (err) res.next(err); res.render('index', { games, user: req.user}); }).sort({gameUsers: -1}).limit(10); }); } } // Update function update(req, res, next) { var body = req.body; if (!body.platforms) { body.platforms = [] } User.findByIdAndUpdate(req.session.passport.user, body, {new: true}, function(err, user) { if (err) return res.status(404).json(err); user.populate('games', function(err) { if (err) return res.render('error', {err}); req.user.populate('games', function(err) { if (err) return res.render('error', {err}); res.render('users/show', {user, loggedInUser: req.user}); }); }); }); } // Show function show(req, res, next) { var id = req.params.id || req.user.id; User.findById(id).populate('games').exec(function(err, user) { if (err) return res.render('users/index'); res.render('users/show', {user, loggedInUser: req.user}); }); } // Edit function edit(req, res, next) { res.render('users/edit', {user: req.user}); } // Delete function destroy(req, res, next) { User.findById(req.params.id, function(err, user) { if (err) res.next(err); user.remove(); res.redirect('/users'); }); } // Library Functions // New Library Item function newLibItem(req, res) { Game.find({}).where('users').nin([req.params.id]).populate('users') .exec(function(err, games) { if (err) res.next(err); var user = req.params.id; res.render('users/library', { games, user, userId: req.params.id }); }); } // Add Item to Library function addLibItem(req, res, next) { User.findById(req.params.userId, (err, user) => { if (err) res.next(err); user.games.push(req.params.gameId); user.save(() => { Game.findById(req.params.gameId, (err, game) => { if (err) res.next(err); game.gameUsers.push(req.params.userId); game.save(() => { res.redirect(`/users/${user.id}`); }); }); }); }); } // Remove Item from Library function removeLibItem(req, res) { User.findById(req.params.userId, (err, user) => { if (err) res.next(err); user.games.remove(req.params.gameId); user.save(() => { Game.findById(req.params.gameId, (err, game) => { if (err) res.next(err); game.gameUsers.remove(req.params.userId); game.save(() => { res.redirect(`/users/${user.id}`); }); }); }); }) }<file_sep>var request = require('request'); var requestPromise = require('request-promise-native'); var apiUrl = 'https://api-endpoint.igdb.com/games/'; var platformUrl = 'https://api-endpoint.igdb.com/platforms/'; module.exports = { searchByTitle, searchOneGame }; function searchByTitle(title) { // var url = `${apiUrl}?search=${title}&fields=*&expand=platforms`; if (!title) { var url = `${apiUrl}?fields=*&order=popularity:desc&expand=platforms`; return new Promise(function(resolve, reject) { request({ url: url, headers: { 'user-key': process.env.IGDB_TOKEN, Accept: 'application/json' } }, function(err, response, body) { var gameData = JSON.parse(body); resolve(gameData); }); }); } else { var url = `${apiUrl}?search=${title}&fields=*&order=popularity:desc&expand=platforms&limit=50&scroll=1`; return new Promise(function(resolve, reject) { request({ url: url, headers: { 'user-key': process.env.IGDB_TOKEN, Accept: 'application/json' } }, function(err, response, body) { var gameData = JSON.parse(body); resolve(gameData); }); }); } }; function searchOneGame(id) { var url = `${apiUrl}${id}`; return new Promise(function(resolve, reject) { request({ url: url, headers: { 'user-key': process.env.IGDB_TOKEN, Accept: 'application/json' } }, function(err, response, body) { var gameData = JSON.parse(body)[0]; if (gameData.platforms) { var promises = []; gameData.platforms.forEach(function(platform) { promises.push(requestPromise({ url: `${platformUrl}${platform}?fields=name`, headers: { 'user-key': process.env.IGDB_TOKEN, Accept: 'application/json' } })); }); Promise.all(promises).then(function(platforms) { gameData.platforms = platforms.map(platform => JSON.parse(platform)[0].name); resolve(gameData); }); } else { resolve(gameData); } }); }); };<file_sep>var mongoose = require('mongoose'); //mongoose (the ODM) connecting to the correct databse in mongodb mongoose.connect(process.env.DATABASE_URL); var db = mongoose.connection; db.once('open', function() { console.log(`Connected to MongoDB at ${db.host}:${db.port}`); }); db.on('error', function(err) { console.log(`Database error:\n${err}`); });
1e28726fc5c6f3a0563b4112447f5071bf9a0ab3
[ "Markdown", "JavaScript" ]
12
Markdown
caitfriedlander/game.it
43573b0463a8812551497a749445224a8b331ce3
9a19644710e8617e37bb808238d0372838e3a168
refs/heads/master
<file_sep>define(function() { ST.Events = Class.extend({ on: function(actionName, object, callback) { var _this = this; console.log(object) if(!_.isElement(object)) { _.each(object, function(o) { _this._bind(actionName, o, callback); }) } else { this._bind(actionName, object, callback); } }, _bind: function(actionName, object, callback) { if (object.addEventListener) { object.addEventListener( actionName, callback, false ); } else if (object.attachEvent) { object["e"+actionName+callback] = callback; object[actionName+callback] = function() { object["e"+actionName+callback]( window.event ); } object.attachEvent( "on"+actionName, object[actionName+callback] ); } else { object["on"+actionName] = object["e"+actionName+callback]; } }, off: function(key) { //unbind is missing... }, }); return ST.Event = ST.Event || new ST.Events(); })<file_sep>/* MODEL ----- var Address = SimpleModel.extend({ model: "address", fieldNamePattern: "id_post__address_:fieldname", fields: { id: new NumField(), city: new CharField(), street: new CharField() } }) var Person = SimpleModel.extend({ model: "person", fieldNamePattern: "id_:fieldname", fields: { id: new NumField(), firstname: new CharField({"max_length": 255, "presence": true}), lastname: new CharField({"presence": true}) }, includes: { "address": Address } }) */ var SimpleModel = Class.extend({ type: "SimpleModel", model: null, //model name fieldNamePattern: ":model_:fieldname", //naming convention for fields' ids modelFields: {}, //model's fields validates: {}, includes: {}, //model's submodel backend: DummyDriver, //model's data source, init: function(args) { _params = args; _attributes = {}; this.fields = {}; for (field in this.modelFields) { this.fields[field] = new this.modelFields[field](this.validates[field]) } this.backendDriver = new this.backend() }, fetch: function() { _attributes = this.backendDriver.fetch(_params) // this.parseJSON(_attributes[this.model]); this.parseJSON(_attributes); }, parseJSON: function(attr) { for ( a in attr) { if (this.includes[a]) { this[a] = new this.includes[a](); this[a]._attributes = attr[a] this[a].parseJSON(attr[a]) } else if(this.fields[a]) { this.fields[a].value = attr[a] } } }, isValid: function() { return true; }, getAttributes: function() { return _attributes; } })<file_sep>describe("Model", function() { var model; beforeEach(function() { model = new SimpleModel(); }) it("should exists", function() { expect(SimpleModel).toBeDefined() }) it("should have includes", function() { expect(model.includes).toBeDefined() }) it("should have fields", function() { expect(model.fields).toBeDefined() }) it("should have backend driver", function() { expect(model.backend).toBeDefined() }) describe("when models extend SimpleModel", function() { var AddressModel, address; var PersonModel, person; beforeEach(function() { AddressModel = SimpleModel.extend({ backend: TestDriver, model: "address", fieldNamePattern: "id_post__address_:fieldname", modelfFields: { id: NumField, city: CharField, street: CharField } }); PersonModel = SimpleModel.extend({ backend: TestDriver, model: "person", fieldNamePattern: "id_:fieldname", //":model_:fieldname" modelFields: { id: NumField, firstname: CharField, //{"max_length": 255, "presence": true}, lastname: CharField //{"presence": true} }, validates: { 'firstname': {'max_length': 255, 'presence': true}, 'lastname': {'presence': true} }, includes: { "address": AddressModel } }); person = new PersonModel({'id': 1}) person.fetch() person2 = new PersonModel({'id': 2}) person2.fetch() }); it("should connect to driver", function() { expect(person.getAttributes()).not.toBe(null); }); it("should parse JSON", function() { expect(person.fields.id.value).not.toBe(null) }) it("should create a reference to submodel", function() { expect(person.address).toBeDefined() }) }) }); <file_sep>define(function() { ST.Observer = Class.extend({ observers: {}, on: function(key, object, callback) { this.observers[key] = {object: object, callback: callback}; }, off: function(key) { delete this.observers[key]; }, trigger: function(key) { if(this.observers[key]) return this.observers[key].callback() return false; } }); return ST.Observe = ST.Observe || new ST.Observer(); });<file_sep>define(function() { ST.Controller = Class.extend({ type: "Controller", init: function() { this.eventRouter(); }, eventRouter: function() { return; } }); return ST.Controller; }); <file_sep>/* VIEW */ var SimpleView = Class.extend({ init: function(_args) { args = _args; } })<file_sep>define(function() { ST.View = Class.extend({ type: "View", render: function() { }; }); return ST.View; });<file_sep>define(function() { Collection = Class.extend({ type: "Collection", model: null, init: function() { this.models = []; }, feed: function(data) { this._getData(data); }, _getData: function(data) { _.each(data, function(d) { var m = new this.model(); m._getData(d); this.models.push(m); }); }, addSelectedField: function(model_id) { _.each(this.models, function(model) { if(model.id == model_id) { model.fields['selected'] = true; return true; } }) return false; }, removeSelectedField: function() { _.each(this.models, function(model) { delete model.fields['selected']; }); return true; }, unshift: function(data) { var model = new this.model(); model._getData(data); this.models.unshift(model); }, isEmpty:function(){ return _.isEmpty(this.models); } }); return Collection; })<file_sep>describe("Controller", function() { var controller; beforeEach(function() { controller = new SimpleController(); }) it("should exists", function() { expect(SimpleController).toBeDefined() }) it("should have includes", function() { expect(controller.eventRouter).toBeDefined() }) }); <file_sep>/* DRIVERS ------- Driver handles connection to data source. It provides four CRUD actions. New drivers should extend from existing ones. */ var DummyDriver = Class.extend({ fetch: function(params) {}, create: function(params) {}, update: function(params) {}, destroy: function(params) {} }) var WebDriver = DummyDriver.extend({ routes: {}, fetch: function(params) { url = this.routes["read"] for(p in params) { url = url.replace(":"+p, params[p]) } _data = JSON.parse('{"post": {"id": 1, "title": "The title", "body": "The body", "fake": "abc?", "address": {"street":"my", "city": "rumia"}}}') return _data }, create: function(params) { }, update: function(params) { }, destroy: function(params) { } }) <file_sep>/* COLLECTION */ var SimpleCollection = Class.extend({ })
625262ada40d236e6b66c3cb2dab98f22f33b41b
[ "JavaScript" ]
11
JavaScript
espresse/SimpleMVC
4e02919fbd2c520f35c4f1ae7269ef949df2b23d
97537204f0f007072068492f82f4eac1eb83a8f8
refs/heads/master
<repo_name>jeremiahtenbrink/webauth-i-challenge<file_sep>/header.md # Dishes and Recipes There can be many dishes. There can be even more recipes as you can have many recipes for each dish. Each recipe can have multiple ingredients and ingredients can be in many different recipes. ## <span id="api-example-for-a-submenu-entry">Api</span> <file_sep>/src/login/login-model.ts import { database } from '../../data/dbConfig'; import { ILogin } from "./ILogin"; import * as Users from '../users/users-model'; import bcrypt from 'bcrypt'; import { error } from '../error/error'; import uuid from 'uuid'; export const login = async ( login: ILogin ) => { const user = await Users.getUsersByEmail( login.email ); const passwordMatch = bcrypt.compareSync( login.password, user.password ); if ( !passwordMatch ) { throw error( 401, "Invalid Credentials" ); } const record = await database( 'login' ).where( { email: login.email } ) .first(); if ( record ) { const deleted = await database( 'login' ) .where( { email: login.email } ).delete(); if ( !deleted ) { throw error( 500, "Internal server error" ); } } const token = uuid.v4(); const ids = await database( 'login' ) .insert( { email: login.email, token } ); if ( ids[ 0 ] ) { return database( 'login' ) .select( "token" ) .where( { email: login.email} ).first(); } }; export const isUserLoggedIn = async ( token: string | string[] ) => { let record = await database('login').where({token}).first(); return !!record; };<file_sep>/src/auth/auth.ts import { Request, Response } from "express"; import { isUserLoggedIn } from '../login/login-model'; import { error, sendError } from "../error/error"; export const Authentication = async ( req: Request, res: Response, next: any ) => { const headers = req.headers; if ( !headers.auth_token ) { res.status( 401 ).json( { message: 'You must include a auth token to reach' + ' this endpoint.' } ); return; } else { let loggedIn = await isUserLoggedIn( headers.auth_token ); if ( loggedIn ) { next(); } else { res.status( 401 ).json( { message: "You are not logged in. Please" + " login in to continue." } ); } } }; <file_sep>/src/login/login.ts import { Request, Response } from "express"; import { ILogin } from "./ILogin"; import * as Login from './login-model'; import { error, sendError } from "../error/error"; const usersRouter = require( 'express' ).Router(); /** * @api {post} /api/login Log in a user * @apiVersion 1.0.0 * @apiName LogInUser * @apiGroup Login * * @apiExample Post example: * axios.post('/api/login', { * email: "<EMAIL>", * password: "<PASSWORD>" * }); * * @apiParam {String} email The users email address. * @apiParam {string} password The users password. * * @apiUse Error * @apiSampleRequest off * * @apiSuccess {String} token Users auth token. * @apiSuccessExample {json} Example: * { * "token": "<PASSWORD>" * } * * */ usersRouter.post( '/', async ( req: Request, res: Response ) => { try { const login: ILogin = req.body; if ( !login.email || !login.password ) { sendError( error( 400, "You must send a password and email" + " address." ), res ); return; } const result = await Login.login( login ); if ( result ) { res.status( 200 ).json( { token: result.token } ); return; } sendError( error( 500, "Server Error" ), res ); return; } catch ( e ) { res.status( 500 ).json( e ); } } ); module.exports = usersRouter; <file_sep>/server.ts import express from "express"; import helmet from 'helmet'; import { Authentication } from "./src/auth/auth"; const path = require( 'path' ); const cors = require( 'cors' ); const apiDocsPath = path.join( __dirname, './apidoc' ); const Register = require( './src/register/register' ); const Login = require( './src/login/Login' ); const Users = require( './src/users/Users' ); const server = express(); server.use( helmet() ); server.use( cors() ); server.use( express.json() ); server.use( '/api/register', Register ); server.use( '/api/login', Login ); server.use( '/api/users', Authentication, Users ); server.use( '/', express.static( apiDocsPath ) ); export default server;<file_sep>/src/register/register.ts import { Request, Response } from "express"; import { IUser } from "../users/IUser"; import * as Users from '../users/users-model'; import * as error from '../error/error'; import validator from "validator"; import bcrypt from "bcrypt"; const registerRouter = require( 'express' ).Router(); /** * @api {post} /api/register Register a user * @apiVersion 1.0.0 * @apiName RegisterUser * @apiGroup Registration * * @apiExample Request example: * axios.post('/api/register', { * firstName: "<NAME>", * lastName: "<NAME>", * email: "<EMAIL>", * address: "street address", * password: "<PASSWORD>", * }); * * @apiParam {String} first_name Users first name. * @apiParam {String} last_name Users last name. * @apiParam {String} email Users email address. * @apiParam {String} address Users street address. * @apiParam {String} password Users password. * * @apiUse Error * @apiSampleRequest off * * @apiSuccess {Number} id ID of the new registered user. * @apiSuccess {String} first_name Users first name. * @apiSuccess {String} last_name Users last name. * @apiSuccess {String} email Users email address. * @apiSuccess {String} address Users street address. * @apiSuccess {Number} created_at Timestamp the user was created. * @apiSuccess {Number} updated_at Timestamp the user was updated. * @apiSuccessExample {json} Example: * { "id": 1, "email": "<EMAIL>", "first_name": "Diego", "last_name": "Dach", "address": "085 Considine Rue", "created_at": "2019-04-01 19:19:22", "updated_at": "2019-04-01 19:19:22" } * * */ registerRouter.post( '/', async ( req: Request, res: Response ) => { try { let user = req.body; if ( !user.firstName || !user.lastName || !user.email || !user.address ) { error.sendError( error.error( 400, "Please include all the user" + " details in the request body." ), res ); return; } if ( !validator.isEmail( user.email ) ) { error.sendError( error.error( 400, "The email given is not a email" + " address." ), res ); return; } let userObject: IUser = { first_name: user.firstName, last_name: user.lastName, email: user.email, address: user.address, password: await bcrypt.hashSync( user.password, 14 ) }; const result = await Users.insertUser( userObject ); if ( result ) { let user = await Users.getUserById( result[ 0 ] ); res.status( 201 ).json( { id: user.id, first_name: user.first_name, last_name: user.last_name, address: user.address, email: user.email, created_at: user.created_at, updated_at: user.updated_at, } ); return; } } catch ( e ) { res.status( 500 ).json( e ); } } ); module.exports = registerRouter; <file_sep>/apidoc/api_project.js define({ "name": "webAuth", "version": "1.0.0", "description": "Register users and passwords and collect users information.", "title": "Custom apiDoc browser title", "url": "http://localhost:3200", "sampleUrl": "http://localhost:3200", "header": { "title": "Api", "content": "<h1>Dishes and Recipes</h1>\n<p>There can be many dishes. There can be even more recipes as you\ncan have many recipes for each dish. Each recipe can have multiple\ningredients and ingredients can be in many different recipes.</p>\n<h2><span id=\"api-example-for-a-submenu-entry\">Api</span></h2>\n" }, "footer": { "title": "Footer Title", "content": "<p>@CopyRight <NAME>.</p>\n" }, "template": { "withGenerator": true, "withCompare": true }, "defaultVersion": "0.0.0", "apidoc": "0.3.0", "generator": { "name": "apidoc", "time": "2019-04-01T20:18:33.187Z", "url": "http://apidocjs.com", "version": "0.17.7" } }); <file_sep>/src/users/users-model.ts import { database } from '../../data/dbConfig'; import { IUser } from "./IUser"; export const getUsers = () => { return database('users'); }; export const insertUser = (user: IUser) => { return database('users').insert(user); }; export const getUserById = (id: number) => { return database('users').where({id}).first(); }; export const getUsersByEmail = (email: string) => { return database('users').where({email}).first(); };<file_sep>/index.ts require( 'dotenv' ).config() import server from "./server"; const port = process.env.PORT || 5000; server.listen( port, () => console.log( `\n** API running on http://localhost:${ port } **\n` ) );
2c76487e88c7cc1db6bab6eef3a3a3c12bfd3110
[ "Markdown", "TypeScript", "JavaScript" ]
9
Markdown
jeremiahtenbrink/webauth-i-challenge
623a5685164592011cbb881a9ea284f37abcd60d
69116c3eb0fd9fb7c52174fa0653699771e63bd2
refs/heads/master
<file_sep><?php require_once 'inc/settings.inc'; // Ensure this script is not being run from the browser, unless local/dev or it's me: $dev = FALSE; if ($_SERVER['HTTP_HOST']) { if ($_SERVER['HTTP_HOST'] == 'drupalfinder' || $_GET['user'] == 'mossy2100') { $dev = TRUE; } else { echo "Access denied."; exit; } } if ($dev) { echo '<pre>'; } require_once 'inc/db.inc'; require_once 'inc/strings.inc'; require_once 'inc/debug.inc'; require_once 'inc/stats.inc'; require_once 'inc/geo.inc'; debugOn(); open_db(); $stats = get_stats(TRUE); var_export($stats); if ($dev) { echo '</pre>'; } <file_sep> /** * Set the main content height so that the footer is flush with the bottom of the page. */ function setMinHeight() { // Get the window height: var windowHeight = $(window).height(); var headerHeight = $('#header').height(); var footerHeight = $('#footer').height(); // Calculate the minHeight. // The 40 is padding (20px) on #main-content. var minHeight = windowHeight - headerHeight - footerHeight - 40; // Set the minHeight $('#main-content').css('min-height', minHeight + 'px'); } /** * Hide/show the drupal version if the Drupal checkbox is checked. */ function hide_show_drupal_ver() { var checked = $('#drupal').is(':checked'); var drupal_ver_row = $('#drupal_ver').closest('tr'); if (checked) { $('#drupal_ver').closest('tr').removeClass('disabled'); $('#drupal_ver').enable(); } else { $('#drupal_ver').closest('tr').addClass('disabled'); $('#drupal_ver').val(''); $('#drupal_ver').disable(); } } /** * Remove any invalid characters from the host. */ function extract_host_from_url() { // Get the host as lower case: var host = $('#host').val().toLowerCase(); // Strip http:// or https:// if present: if (host.substr(0, 7) == 'http://') { host = host.substr(7); } else if (host.substr(0, 8) == 'https://') { host = host.substr(8); } // Look for the first forward slash: var slash_pos = host.indexOf('/'); if (slash_pos != -1) { host = host.substr(0, slash_pos); } // Remove invalid chars: var host2 = ''; var ch; for (var i = 0; i < host.length; i++) { ch = host.charAt(i); if (('a' <= ch && ch <= 'z') || ('0' <= ch && ch <= '9') || ch == '-' || ch == '.') { host2 += ch; } } $('#host').val(host2); } $(function() { if ($('#drupal').length) { // Do it on startup: hide_show_drupal_ver(); // Also then whe checkbox is clicked: $('#drupal').click(hide_show_drupal_ver); } // Do it on startup: setMinHeight(); // Also on resize: $(window).resize(setMinHeight); // When the host changes, check if we need to extract it from a URL: $('#host').change(extract_host_from_url); extract_host_from_url(); }); <file_sep><?php /** * Database functions used by DrupalFinder. * * @author <NAME> <<EMAIL>> * @version 2011-11-12 */ /** * Open the database. */ function open_db() { global $dbh; if ($_SERVER['HTTP_HOST'] == 'drupalfinder') { $db = 'drupalfinder'; $user = 'drupalfinder'; $pwd = <PASSWORD>$'; } else { $db = 'drupalfinder'; $user = 'drupalfinder'; $pwd = <PASSWORD>$'; } $dbh = new PDO("mysql:host=localhost;dbname=$db", $user, $pwd); } /** * Gets a site's URL given the site record. * * @param object $site * @return string */ function get_site_url($site) { return 'http' . ($site->https ? 's' : '') . '://' . $site->host; } /** * Get a site from the database given an id. * * @param int $site_id * @return object */ function select_site($site_id) { global $dbh; // Get the database record as an object: $sql = "SELECT * FROM site WHERE site_id = :site_id"; $stmt = $dbh->prepare($sql); $stmt->execute(array( ':site_id' => $site_id, )); return $stmt->fetchObject(); } /** * Get a site from the database given a URL. * * @param string $url * @return object */ function get_site($url) { global $dbh; // Parse the URL: $url_info = parse_url2($url); // This check shouldn't be necessary, because we always call this function with a valid URL, // but we'll leave it here just in case. if (!$url_info['valid']) { return FALSE; } // Get the first matching database record as an object: $sql = "SELECT * FROM site WHERE https = :https AND host IN (:host, :www_host) ORDER BY site_id"; $sql_values = array( ':https' => $url_info['https'], ':host' => $url_info['host'], ':www_host' => $url_info['www_host'], ); $stmt = $dbh->prepare($sql); $stmt->execute($sql_values); return $stmt->fetchObject(); } /** * Compare 2 sites, for ordering search results. * * @param object $site1 * @param object $site2 * @return int */ function compare_sites($site1, $site2) { $host1 = $site1->host; $host2 = $site2->host; if ($host1 == $host2) { if (!$site1->https && $site2->https) { return -1; } elseif ($site1->https && !$site2->https) { return 1; } else { // Same scheme, same host: return 0; } } else { // Compare host parts in reverse order, i.e. tld, domain, subdomain, etc. $host1parts = array_reverse(explode('.', $host1)); $host2parts = array_reverse(explode('.', $host2)); $n_parts = max(count($host1parts), count($host2parts)); for ($i = 0; $i < $n_parts; $i++) { if ($host1parts[$i] < $host2parts[$i]) { return -1; } elseif ($host1parts[$i] > $host2parts[$i]) { return 1; } } // They must be the same - should never happen because equal hosts should be caught earlier. return 0; } } /** * Extract the host from a URL if necessary, and remove any invalid chars. * * @return string */ function clean_host($host) { // Get the host as lower case: $host = strtolower((string) $host); // Strip http:// or https:// if present: if (substr($host, 0, 7) == 'http://') { $host = substr($host, 7); } else if (substr($host, 0, 8) == 'https://') { $host = substr($host, 8); } // Look for the first forward slash: $slash_pos = strpos($host, '/'); if ($slash_pos !== FALSE) { $host = substr($host, 0, $slash_pos); } // Remove invalid chars: $host2 = ''; for ($i = 0; $i < strlen($host); $i++) { $ch = $host[$i]; if (ctype_alnum($ch) || $ch == '-' || $ch == '.') { $host2 .= $ch; } } return $host2; } /** * Search sites. * Store the search params and the results in the session. * * @param array $params */ function search_sites($params) { global $dbh; // Valid param keys: // - search_string // - scheme // - host_match // - host // - country_code // - drupal // - drupal_ver ///////////////////////////////////////////////////////////////////////////// // Construct the SQL: $where = array(); $sql_values = array(); // Return valid and examined sites only: $where[] = "valid = 1 AND examined = 1"; // search_string: if ($params['search_string']) { // $words = array_filter(explode(' ', $params['search_string'])); // foreach ($words as $i => $word) { // // Wrap search string in word boundaries so we don't match partial words: $rx = "[[:<:]]{$params['search_string']}[[:>:]]"; $where[] = "(title REGEXP :rx OR description LIKE :rx OR keywords LIKE :rx)"; $sql_values[":rx"] = $rx; // } // $search_string = '%' . $params['search_string'] . '%'; // $where[] = "(title LIKE :search_string OR description LIKE :search_string OR keywords LIKE :search_string)"; // $sql_values[':search_string'] = $search_string; } // https: if ($params['scheme'] == 1) { $where[] = "https = 0"; } elseif ($params['scheme'] == 2) { $where[] = "https = 1"; } // host: // Clean host param, make it only letters, digits, dots or dashes, and lower-case. $params['host'] = clean_host($params['host']); if ($params['host']) { switch ($params['host_pattern']) { case 0: $host_pattern = '%' . $params['host'] . '%'; break; case 1: $host_pattern = $params['host'] . '%'; break; case 2: $host_pattern = '%' . $params['host']; break; } $where[] = "host LIKE :host_pattern"; $sql_values[':host_pattern'] = $host_pattern; } // country_code: if ($params['country_code']) { $where[] = "country_code = :country_code"; $sql_values[':country_code'] = $params['country_code']; } // subcountry_code: // if ($params['subcountry_code']) { // $where[] = "subcountry_code = :subcountry_code"; // $sql_values[':subcountry_code'] = $params['subcountry_code']; // } // // // city: // if ($params['city']) { // $where[] = "city = :city"; // $sql_values[':city'] = $params['city']; // } // drupal: $params['drupal'] = $params['drupal'] ? 1 : 0; if ($params['drupal']) { $where[] = "drupal = 1"; if ($params['drupal_ver']) { $where[] = "drupal_ver >= :min_drupal_ver"; $sql_values[':min_drupal_ver'] = $params['drupal_ver']; $where[] = "drupal_ver < :max_drupal_ver"; $sql_values[':max_drupal_ver'] = $params['drupal_ver'] + 1; } // // min_drupal_ver: // if ($params['min_drupal_ver']) { // $where[] = "drupal_ver >= :min_drupal_ver"; // $sql_values[':min_drupal_ver'] = $params['min_drupal_ver']; // } // // // max_drupal_ver: // if ($params['max_drupal_ver']) { // $where[] = "drupal_ver <= :max_drupal_ver"; // $sql_values[':max_drupal_ver'] = $params['max_drupal_ver']; // } } // min_dt_examined: if ($params['min_dt_examined']) { $where[] = "dt_examined >= :min_dt_examined"; $sql_values[':min_dt_examined'] = $params['min_dt_examined']; } // Get the WHERE clause: $where_clause = empty($where) ? '' : ('WHERE ' . implode(' AND ', $where)); // Run the SQL, limit to MAX_NUM_RESULTS results. $sql = "SELECT * FROM site $where_clause ORDER BY host, https LIMIT " . MAX_NUM_RESULTS; $stmt = $dbh->prepare($sql); $stmt->execute($sql_values); // Collect all the sites: $sites = array(); while ($stmt) { $site = $stmt->fetchObject(); if (!$site) { break; } $sites[] = $site; } // Sort the sites: usort($sites, 'compare_sites'); ///////////////////////////////////////////////////////////////////////////// // Remember the params and the results in the session: $_SESSION['search_params'] = $params; $_SESSION['search_results'] = $sites; ///////////////////////////////////////////////////////////////////////////// // Get the total number of results: $_SESSION['n_total_search_results'] = 'Unknown'; $sql_count = "SELECT COUNT(*) AS count FROM site $where_clause"; $stmt_count = $dbh->prepare($sql_count); $stmt_count->execute($sql_values); if ($stmt_count) { $rec_count = $stmt_count->fetchObject(); if ($rec_count) { $_SESSION['n_total_search_results'] = $rec_count->count; } } return $sites; } /** * Insert a new site into the database. * * @param bool $https * @param string $host */ function insert_site($https, $host) { global $dbh; $sql = "INSERT INTO site (https, host, dt_created, dt_updated) VALUES (:https, :host, NOW(), NOW())"; $stmt = $dbh->prepare($sql); $stmt->execute(array( ':https' => $https, ':host' => $host, )); } <file_sep><?php require_once 'inc/db.inc'; require_once 'inc/stats.inc'; require_once 'template_top.php'; open_db(); ?> <h2>Stats</h2> <?php // Get stats: $stats = get_stats(); echo "<p><em>These stats are updated every hour. The last update was at {$stats['dt_updated']}.</em></p>"; echo "<p>There are ", number_format($stats['total']), " sites in the database.</p>"; echo "<p>", number_format($stats['total_examined']), " of these have been examined.</p>"; echo "<p>", number_format($stats['total_valid']), " valid sites have been found.</p>"; $percent = number_format($stats['total_drupal'] / $stats['total_valid'] * 100, 2); echo "<p>", number_format($stats['total_drupal']), " of these are Drupal sites, which is $percent%.</p>"; ?> <br> <h3>Drupal versions</h3> <p>This graph shows the number of Drupal sites by version, and the percentage of the total number of Drupal sites.</p> <?php $n_total_drupal_ver = array(); $max = 0; function add_stat($v, $n) { global $stats, $n_total_drupal_ver, $drupal_ver_percent, $max; $drupal_ver_percent[$v] = number_format($n / $stats['total_drupal'] * 100, 2); if ($n > $max) { $max = $n; } } foreach ($stats['total_drupal_ver'] as $drupal_ver => $num) { add_stat($drupal_ver, $num); } define('MAX_BAR_WIDTH', 600); $colors = array('#eee', 'chocolate', 'turquoise', 'yellow', 'red', '#00cc00', '#ffbf00', '#36a0ea', 'orchid'); echo "<div id='stats_drupal_ver_graph'>\n"; foreach ($stats['total_drupal_ver'] as $v => $n) { $width = ceil($n * MAX_BAR_WIDTH / $max); echo "<div class='stats_bar'>\n"; echo "<div class='stats_drupal_ver'>", ($v ? "$v.x" : '?'), "</div>\n"; echo "<div class='stats_drupal_ver_bar' style='width: {$width}px; background-color: $colors[$v]'></div>\n"; echo "<div class='stats_drupal_ver_info'>$n ", ($n == 1 ? 'site' : 'sites'), ", $drupal_ver_percent[$v]%</div>\n"; echo "</div>\n"; } echo "</div>\n"; require_once 'template_bottom.php'; <file_sep>/** * Add methods for getting and setting boolean attributes to the jQuery object. */ (function($) { ///////////////////////////////////////////////////////////////////////////// // Enable and disable functions // Disable selected elements: $.fn.disable = function() { return this.attr('disabled', 'disabled'); }; // Enable selected elements: $.fn.enable = function() { return this.removeAttr('disabled'); }; // Returns whether or not the element is enabled: $.fn.disabled = function() { return Boolean(this.attr('disabled')); }; // Returns whether or not the element is enabled: $.fn.enabled = function() { return !this.disabled(); }; ///////////////////////////////////////////////////////////////////////////// // Check and uncheck functions // check all the selected elements: $.fn.check = function() { return this.attr('checked', 'checked'); }; // uncheck all the selected elements: $.fn.uncheck = function() { return this.removeAttr('checked'); }; // returns whether or not the element is checked: $.fn.checked = function() { return Boolean(this.attr('checked')); }; // returns whether or not the element is unchecked: $.fn.unchecked = function() { return !this.checked(); }; ///////////////////////////////////////////////////////////////////////////// // Readonly functions // Make selected elements readonly: $.fn.setReadOnly = function() { return this.attr('readonly', 'readonly'); }; // Enable selected elements: $.fn.setReadWrite = function() { return this.removeAttr('readonly'); }; // Returns whether or not the element is enabled: $.fn.isReadOnly = function() { return Boolean(this.attr('readonly')); }; // Returns whether or not the element is enabled: $.fn.isReadWrite = function() { return !this.isReadOnly(); }; })(jQuery); <file_sep><?php require_once "template_top.php"; ?> <h2>About DrupalFinder</h2> <p>This is a very simple and lightweight web crawler that examines websites and checks for a few things:</p> <ul> <li>If the site URL is valid, i.e. does not trigger a server-side redirect or an error (e.g. 404, page forbidden, etc.).</li> <li>The character encoding.</li> <li>The site's title, description and keywords.</li> <li>Where the site is hosted.</li> <li>If the site is running Drupal, and if possible, the version.</li> </ul> <p>This program was created to enable searches like "Find Drupal sites on a .au domain", or "Find Drupal sites hosted in Australia".</p> <p>There is currently only one database table, which contains information about websites. This is <strong>not</strong> a collection of <em>links</em>, such as you might find on Google, but of <em>sites</em>, which means simply a scheme (http or https) plus a host (domain or subdomain), i.e. only the top-level URL of the site.</p> <p>Domains and subdomains are treated as separate sites. However, <em>http://www.example.com</em> and <em>http://example.com</em> are treated as equivalent. Each host is first examined without the 'www' prefix. If that fails, then it's examined with the 'www'. Therefore, if a host is shown starting with 'www', it needs it.</p> <p>Website URLs are extracted from submitted and crawled links. The character encoding is obtained from the HTTP header or from meta tags. Description and keywords are harvested from meta tags.</p> <p>To detect where a site is hosted, the host is first resolved to an IP address. The location is then looked up using <a href='http://www.maxmind.com/app/geolitecity' target="_blank">MaxMind's free GeoLite City database</a>.</p> <p>To detect if a website is using Drupal, the regular expression from <a href='http://wappalyzer.com/' target='_blank'>Wappalyzer</a> is used, which basically just looks for &quot;drupal.js&quot; or &quot;Drupal.settings&quot;. If it's a Drupal site, the version is detected by looking for a <em>CHANGELOG.txt</em> file, and scanning for the first Drupal version in that file. This is not a flawless method, as that file does not need to be present on a Drupal site, and the web server may be configured not to serve <em>.txt</em> files. However, it works in most cases (see <a href='stats.php'>Stats</a>).</p> <p>Because the program only examines front pages, Drupal sites running in a subdirectory will not be detected or added to the database. Websites that perform a server-side redirect to another site or a subdirectory are currently treated as invalid and will not appear in search results.</p> <p>Ironically, this website does not use Drupal, which would have been overkill for this simple program. It uses PHP 5.2, PEAR, MySQL 5, HTML5, CSS3, JavaScript, and jQuery 1.7. PHP's <a href='http://au2.php.net/manual/en/book.mbstring.php' target="_blank">multibyte string</a> and <a href='http://au2.php.net/manual/en/book.iconv.php' target="_blank">iconv</a> extensions provide support for non-Latin characters. Everything is converted to UTF-8 before being stored in the database, and then to HTML entities for display in the browser.</p> <p>If you have any suggestions for this little project, feel free to <a href='<?php echo html_entities_all("mailto:<EMAIL>"); ?>'>email me</a>! :)</p> <p><NAME><br> CEO, <a href='http://iwda.biz' target="_blank">International Web Development Academy</a></p> <p> Facebook: <a href="http://facebook.com/mossy2100" target='_blank'>facebook.com/mossy2100</a><br> Twitter: <a href="http://twitter.com/mossy2100" target='_blank'>twitter.com/mossy2100</a><br> Skype: shaun.moss1 </p> <br> <h3>Possible future ideas</h3> <!-- <p><strong>Inbound link counter</strong><br> A link counter to count inbound links to each site, so search results can be ordered by popularity instead of alphabetically.</p> --> <p><strong>Customised RSS feed</strong><br> Allow people to set up an RSS feed of newly discovered sites, based on their search preferences.</p> <?php require_once 'template_bottom.php'; <file_sep><?php /** * Get the path to the stats file. * * @return string */ function stats_path() { return dirname(__FILE__) . '/../data/stats.txt'; } /** * Regenerate the stats. * * @return array */ function regenerate_stats() { global $dbh, $GEOIP_COUNTRY_NAME; $stats = array(); // Note update time: $stats['dt_updated'] = date('Y-m-d H:i:s'); // Get the total number of sites: $sql_total = "SELECT COUNT(*) AS total FROM site"; $stmt_total = $dbh->query($sql_total); $rec_total = $stmt_total->fetchObject(); $stats['total'] = (int) $rec_total->total; // Get the total number of examined sites: $sql_examined = "SELECT COUNT(*) AS total FROM site WHERE examined = 1"; $stmt_examined = $dbh->query($sql_examined); $rec_examined = $stmt_examined->fetchObject(); $stats['total_examined'] = (int) $rec_examined->total; // Get the total number of examined and valid sites: $sql_valid = "SELECT COUNT(*) AS total FROM site WHERE valid = 1 AND examined = 1"; $stmt_valid = $dbh->query($sql_valid); $rec_valid = $stmt_valid->fetchObject(); $stats['total_valid'] = (int) $rec_valid->total; // Get number of Drupal sites: $sql_drupal = "SELECT COUNT(*) AS total_drupal FROM site WHERE valid = 1 AND examined = 1 AND drupal = 1"; $stmt_drupal = $dbh->query($sql_drupal); $rec_drupal = $stmt_drupal->fetchObject(); $stats['total_drupal'] = (int) $rec_drupal->total_drupal; // Get the Drupal sites with unknown version: $sql3 = " SELECT COUNT(*) AS n FROM site WHERE valid = 1 AND examined = 1 AND drupal = 1 AND drupal_ver IS NULL"; $stmt3 = $dbh->query($sql3); $rec3 = $stmt3->fetchObject(); $stats['total_drupal_ver'][0] = (int) $rec3->n; // Get the Drupal sites with known version: $sql3 = " SELECT COUNT(*) AS n, FLOOR(drupal_ver) AS v FROM site WHERE examined = 1 AND valid = 1 AND drupal_ver IS NOT NULL GROUP BY FLOOR(drupal_ver)"; $stmt3 = $dbh->query($sql3); while ($stmt3) { $rec3 = $stmt3->fetchObject(); if (!$rec3) { break; } $stats['total_drupal_ver'][$rec3->v] = (int) $rec3->n; } // Get all country codes: $sql_countries = " SELECT DISTINCT country_code FROM site WHERE examined = 1 AND valid = 1 AND country_code IS NOT NULL"; $countries = array(); foreach ($dbh->query($sql_countries, PDO::FETCH_OBJ) as $site) { $countries[$site->country_code] = $GEOIP_COUNTRY_NAME[$site->country_code]; } // Sort by country name: asort($countries); $stats['countries'] = $countries; // Save the stats to a file: $path = stats_path(); file_put_contents($path, serialize($stats)); return $stats; } /** * Load or regenerate the stats. * * * @param type $regenerate */ function get_stats($force_regenerate = FALSE) { // Get path to stats file: $path = stats_path(); // If not forcing a regenerate, try to load from file: if (!$force_regenerate) { if (file_exists($path)) { $stats = @file_get_contents($path); } if ($stats) { $stats = @unserialize($stats); } } // If we don't have the stats, regenerate: if (!$stats || !is_array($stats)) { $stats = regenerate_stats(); } return $stats; } <file_sep><?php require_once 'Net/GeoIP.php'; require_once 'Net/GeoIP/geoipregionvars.php'; require_once 'inc/geo.inc'; require_once 'inc/db.inc'; require_once 'inc/sites.inc'; require_once 'inc/verbose.inc'; require_once 'template_top.php'; open_db(); ?> <h2>Submit a link</h2> <p>This can be any valid link. The link's site will be added to the database, as will any other sites this page links to.</p> <form method='POST' action='submit_link.php'> <label for='link'><strong>URL:</strong></label> <input id='link' name='link'> <input type='submit' value='Submit'> </form> <pre> <?php //debug($_REQUEST); // Get the link from POST or GET: if ($_POST['link']) { $link = $_POST['link']; } elseif ($_GET['link']) { $link = base64_decode($_GET['link']); } // If a seed URL was provided via the form or the querystring, crawl it: if ($link) { echo "<hr>"; // Check that it starts with a scheme: if (strtolower(substr($link, 0, 4)) != 'http') { // It doesn't, so add 'http://' as the default scheme: $link = "http://$link"; } // Strip off any trailing slashes: $link = rtrim($link, '/'); echo "<h2>Submitted URL: $link</h2>\n"; // Process for examining a submitted link: // 1. Check if the link is a site URL, and can therefore be added to the database. // 2. If yes, add the site to the database, and examine as above. // 3. If no, get all links from the front page, and add to the database. // Get the site URL from the seed URL: $url_info = parse_url2($link); if (!$url_info['valid']) { echo "Error - {$url_info['error']}.\n"; } else { $n_new_sites = 0; // Get the URLs of the link's site: $site_url = $url_info['site']; $www_site_url = $url_info['www_site']; // Make sure we have this site: $site = add_site($site_url); if ($site->new) { $n_new_sites++; } // Check if the submitted link is a valid site URL: $lower_case_link = strtolower($link); $link_is_site = $lower_case_link == $site_url || $lower_case_link == $www_site_url; // If the link is not a site, crawl it. (If it is, it will get crawled by examine_site() below.) if (!$link_is_site) { $n_new_sites += crawl_site($link); } else { // Examine the submitted site: $n_new_sites += examine_site($site); } if (!$n_new_sites) { echo "<span class='red'>In total, no new sites added.</span>\n"; } else { echo "<span class='green'>In total, <span class='blue'>$n_new_sites</span> new " . ($n_new_sites == 1 ? 'site' : 'sites') . " added.</span>\n"; } } } ?> </pre> <?php require_once 'template_bottom.php'; <file_sep><div id='menu'> <?php $links = array( "Search" => 'index.php', "Submit a link" => 'submit_link.php', "Stats" => 'stats.php', "About" => 'about.php', "Contact" => html_entities_all("mailto:<EMAIL>"), ); $this_page = ltrim($_SERVER['SCRIPT_NAME'], '/\\'); foreach ($links as $label => $href) { echo "<a href='$href'", ($this_page == $href ? " class='active'" : ''), ">$label</a>"; } ?> <a href='http://drupal.org' target='_blank'>drupal.org</a> </div> <file_sep><?php /** * Reusable functions related to URLs and websites. * * @author <NAME> <<EMAIL>> * @version 2011-11-12 */ /** * Get encoding from content type. * e.g. if $content type == "text/html; charset=UTF-8" * then return "UTF-8" * * @param string $content_type * @return string */ function get_encoding_from_content_type($content_type) { $rx = "/charset=([a-z0-9\-\_\.\:\#]*)/i"; $n = preg_match($rx, $content_type, $matches); return $n ? normalise_encoding($matches[1]) : FALSE; } /** * Use curl to get a web page (HTML, XHTML, XML, image, etc.) from a URL. * Returns an array containing the HTTP server response header fields and content. * * @param string $url * @return array */ function get_web_page($url) { $options = array( CURLOPT_RETURNTRANSFER => TRUE, // return web page as a string CURLOPT_HEADER => FALSE, // don't include headers CURLOPT_ENCODING => '', // handle all encodings CURLOPT_USERAGENT => 'DrupalFinder', // who am i CURLOPT_CONNECTTIMEOUT => 60, // timeout on connect CURLOPT_TIMEOUT => 60, // timeout on response // CURLOPT_FOLLOWLOCATION => FALSE, // don't follow redirects CURLOPT_FOLLOWLOCATION => TRUE, // follow redirects CURLOPT_AUTOREFERER => TRUE, // set referer on redirect CURLOPT_MAXREDIRS => 5, // stop after x redirects ); $ch = curl_init($url); curl_setopt_array($ch, $options); $content = curl_exec($ch); $err = curl_errno($ch); $errmsg = curl_error($ch); $response = curl_getinfo($ch); curl_close($ch); // Add to results array: $response['errno'] = $err; $response['errmsg'] = $errmsg; $response['content'] = $content; $response['valid'] = $response['http_code'] == 200 && $response['errno'] == 0; return $response; } /** * Extracts the title from a web page. * * @param string $html * @param string $encoding * @return string */ function get_title_from_html($html, $encoding = 'UTF-8') { $rx = "/<title>([^<]*)<\/title>/si"; $n = preg_match($rx, $html, $matches); if ($n) { return clean_text($matches[1], $encoding); } return FALSE; } /** * Extracts meta tags from a web page. * * @param string $html * @return string */ function get_meta_tags_from_html($html) { // Regular expression for finding meta tags: $rx_tag = "/<meta[^>]*>/is"; // Regular expression for finding attributes and values: $rx_attr = "/([a-z\-\:]+)\=([\"][^\"]*[\"]|[\'][^\']*[\']|[^\'\"\s]*)/is"; $n = preg_match_all($rx_tag, $html, $matches_tags); // Results: $meta_tags = array(); if ($n) { foreach ($matches_tags[0] as $i => $meta_tag) { $attributes = substr($meta_tag, 5, strlen($meta_tag) - 6); $n_attrs = preg_match_all($rx_attr, $attributes, $matches_attr); foreach ($matches_attr[1] as $j => $name) { $value = $matches_attr[2][$j]; // Remove quotes if present: if ($value[0] == '"' || $value[0] == "'") { $value = substr($value, 1, strlen($value) - 2); } $meta_tags[$i][$name] = $value; } } } return $meta_tags; } /** * Scan meta tags for a certain type of information. * * @see http://www.w3schools.com/tags/tag_meta.asp * * @param array $meta_tags * @param string $info_type * This can be any value of the http-equiv or name attribute, e.g. * - content-type * - cache-control * - description * - keywords * - author * - generator * etc. * @param string $encoding * @return string * The requested info, hopefully as UTF-8. FALSE if not found. */ function get_meta_info($meta_tags, $info_type, $encoding = 'UTF-8') { // Loop through meta tags: foreach ($meta_tags as $meta_tag) { // Reset name and content for this tag: $name = NULL; $content = NULL; // Loop through attributes: foreach ($meta_tag as $attr => $value) { if (strtolower($attr) == 'name' || strtolower($attr) == 'http-equiv') { $name = $value; } elseif (strtolower($attr) == 'content') { $content = $value; } // If we have a name matching the requested info type, and we have content, then we have what we're looking for: if ($name && strcasecmp($name, $info_type) == 0 && $content) { return clean_text($content, $encoding); } } } // Description not found: return FALSE; } /** * Looks through meta tags for the charset (HTML5). * * @param array $meta_tags * @return string * The charset, or FALSE if not found. */ function get_meta_charset($meta_tags) { foreach ($meta_tags as $meta_tag) { foreach ($meta_tag as $attr => $value) { if (strtolower($attr) == 'charset') { return normalise_encoding($value); } } } // Not found: return FALSE; } /** * If we don't already have the character encoding, get the meta tags and inspect. * * @param array $response */ function get_web_page_encoding(&$response) { // Get info from the response array: $content_type = $response['content_type']; $encoding = $response['encoding']; $meta_tags = $response['meta_tags']; // If we have the content type already, try extracting the encoding: if ($content_type) { $encoding = get_encoding_from_content_type($content_type); } // If we don't have the encoding yet, look at meta tags: if (!$encoding) { // If don't have meta tags yet, get them now: if (!$meta_tags) { $meta_tags = get_meta_tags_from_html($response['content']); } // Try getting the encoding from the HTML5 meta tag with charset attribute: $encoding = get_meta_charset($meta_tags); // If we still don't have the encoding, try getting it from the HTML4 meta tags: if (!$encoding) { $content_type2 = get_meta_info($meta_tags, 'content-type'); if ($content_type2) { $content_type = $content_type2; $encoding = get_encoding_from_content_type($content_type); } } } // Update response array with the new info: $response['content_type'] = $content_type; $response['encoding'] = $encoding; $response['meta_tags'] = $meta_tags; // print_response($response); } /** * Get description fields (title, description, keywords) from the web page. * * @param array $response */ function get_web_page_description(&$response) { // Get meta tags if not already: $meta_tags = $response['meta_tags']; if (!$meta_tags) { $meta_tags = get_meta_tags_from_html($response['content']); } // Get title, description and keywords: $title = get_title_from_html($response['content'], $response['encoding']); $description = get_meta_info($meta_tags, 'description', $response['encoding']); $keywords = get_meta_info($meta_tags, 'keywords', $response['encoding']); // Update response array with the new info: $response['meta_tags'] = $meta_tags; $response['title'] = $title; $response['description'] = $description; $response['keywords'] = $keywords; } /** * Extracts sites from a web page. * The sites include the scheme (http or https) and the host name, but no path. * Only detects full/absolute URLs, not relative ones. * Returns unique sites in lower-case. * * @param string $html * @return array */ function get_linked_sites($html) { // @todo This may need to be updated to support non-Latin domain names. Depends if we care. $rx = "/\bhttp(s?)\:\/\/([a-z0-9\-]+\.)+([a-z]{2}|aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|xxx)\b/i"; $n_matches = preg_match_all($rx, $html, $matches); if ($n_matches) { $linked_sites = $matches[0]; // Convert all to lower case: foreach ($linked_sites as $i => $linked_site) { // Only return unique results: $linked_sites[$i] = strtolower($linked_site); } return array_unique($linked_sites); } // None found: return array(); } /** * Display a response from get_web_page(), excluding content. * * @param array $response */ function print_response($response) { unset($response['content']); var_export($response); } /** * Improved version of parse_url(). * * @param string $url * @return array */ function parse_url2($url) { $url_info = parse_url($url); // Check if the URL is valid: $url_info['valid'] = TRUE; if (!$url_info['scheme']) { // No valid scheme provided. $url_info['valid'] = FALSE; $url_info['error'] = "Invalid scheme"; } else { $rx = "/[a-z0-9\-\.]+\.[a-z]{2,6}/i"; if (!preg_match($rx, $url_info['host'])) { // The host is invalid. $url_info['valid'] = FALSE; $url_info['error'] = "Invalid host"; } } // If so, get the https and site values we need: if ($url_info['valid']) { $url_info['scheme'] = strtolower($url_info['scheme']); $url_info['https'] = (int) ($url_info['scheme'] == 'https'); // Make host lower-case: $host = strtolower($url_info['host']); // If the host begins with a www, remove it: if (substr($host, 0, 4) == 'www.') { $host = substr($host, 4); } $url_info['host'] = $host; // Get the host with the www: $url_info['www_host'] = "www.$host"; // Get the full site URL with and without the www: $url_info['site'] = $url_info['scheme'] . '://' . $url_info['host']; $url_info['www_site'] = $url_info['scheme'] . '://' . $url_info['www_host']; } return $url_info; } /** * Check if a website is Drupal. * * @param string $html * @return bool */ function detect_drupal($html) { // Regex from Wappalyzer: $rx = "/(<script [^>]+drupal\.js|jQuery\.extend\(Drupal\.settings, \{|Drupal\.extend\(\{ settings: \{|<link[^>]+sites\/(default|all)\/themes\/|<style[^>]+sites\/(default|all)\/(themes|modules)\/)/i"; return (bool) preg_match($rx, $html); } /** * Attempts to detect Drupal version by looking for CHANGELOG.txt. * * @param string $url * Must be a site URL (i.e. scheme and host only), not any old link. * @return string */ function detect_drupal_ver($url) { // If this is a Drupal site, see if we can find the version by looking in CHANGELOG.txt. $response = get_web_page("$url/CHANGELOG.txt"); if ($response['valid']) { // Look for the first Drupal version. // Note that we have not necessarily found CHANGELOG.txt. Some websites will return another page with no error. $rx = "/Drupal ([0-9\.]+)/"; $n_matches = preg_match($rx, $response['content'], $matches); if ($n_matches) { return $matches[1]; } } return FALSE; } <file_sep><?php // Debugging functions: $debugMode = false; function debugOn() { global $debugMode; $debugMode = true; } function debugOff() { global $debugMode; $debugMode = false; } function debugMode() { global $debugMode; return $debugMode; } function debugBeginPrint() { print("<pre style='color:Red'>\n"); } function debugEndPrint() { print("</pre>\n"); } function debug($var, $funcName = '') { global $debugMode; if ($debugMode) { debugBeginPrint(); if ($funcName != '') { print "<b>$funcName:</b> "; } if (is_array($var)) { print_r($var); } elseif (is_object($var)) { var_dump($var); } elseif (is_bool($var)) { print(($var ? 'TRUE' : 'FALSE')."<br />\n"); } else { print(htmlspecialchars($var)."<br />\n"); } debugEndPrint(); } } function debugAll($printPreTags = true) { global $debugMode; if ($debugMode) { if ($printPreTags) { debugBeginPrint(); } var_dump(get_defined_vars()); if ($printPreTags) { debugEndPrint(); } } } function debugExit($str = '') { global $debugMode; if ($debugMode) { exit($str); } } /** * Same as db_query, but will show the actual query being executed, for debug purposes. * I copied db_query to avoid hacking core. */ function debug_query($query) { $args = func_get_args(); array_shift($args); $query = db_prefix_tables($query); if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax $args = $args[0]; } _db_query_callback($args, TRUE); $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query); return _db_query($query, TRUE); } <file_sep><?php // Generate the Atom feed. require_once 'Net/GeoIP.php'; require_once 'Net/GeoIP/geoipregionvars.php'; require_once 'inc/geo.inc'; require_once 'inc/db.inc'; require_once 'inc/sites.inc'; require_once 'inc/verbose.inc'; require_once 'inc/strings.inc'; require_once 'inc/debug.inc'; require_once 'classes/FeedWriter.php'; //debugOn(); open_db(); // IMPORTANT : No need to add id for feed or channel. It will be automatically created from link. //Creating an instance of FeedWriter class. //The constant ATOM is passed to mention the version $feed = new FeedWriter(ATOM); //Setting the channel elements //Use wrapper functions for common elements $feed->setTitle('DrupalFinder feed'); $feed->setLink('http://drupalfinder.com'); $feed->setSelfLink('http://drupalfinder.com/feed.php?' . $_SERVER['QUERY_STRING']); //For other channel elements, use setChannelElement() function $feed->setChannelElement('updated', date(DATE_ATOM , time())); $feed->setChannelElement('author', array('name' => '<NAME>')); // Get the search params. $params = $_GET; // Decode a couple of the params: foreach ($params as $param => $value) { if ($param == 'host' || $param == 'search_string') { $params[$param] = base64_decode($value); } } // Set min_dt_examined to 1 day in the past: $params['min_dt_examined'] = date('Y-m-d H:i:s', time() - 86400); //debug($params); // Search sites: $sites = search_sites($params); // Add sites to the feed: foreach ($sites as $site) { //Create an empty FeedItem $newItem = $feed->createNewItem(); //Add elements to the feed item //Use wrapper functions to add common feed elements $url = get_site_url($site); $newItem->setTitle($site->title); $newItem->setLink($url); $newItem->setDate($site->dt_examined); // Internally changed to "summary" tag for ATOM feed $newItem->setDescription($site->description); // Add other fields as content: $content = array( 'encoding' => $site->encoding, 'description' => $site->description, 'keywords' => format_keywords($site->keywords), 'ip_addr' => $site->ip_addr, 'country_code' => $site->country_code, 'country' => $site->country_code ? $GEOIP_COUNTRY_NAME[$site->country_code] : '', 'subcountry_code' => $site->subcountry_code, 'subcountry' => $site->subcountry_code ? $GEOIP_REGION_NAME[$site->country_code][$site->subcountry_code] : '', 'city' => $site->city, 'drupal' => $site->drupal, 'drupal_ver' => ($site->drupal && $site->drupal_ver) ? ver_float_to_string($site->drupal_ver) : '', 'drupal_ver_float' => ($site->drupal && $site->drupal_ver) ? $site->drupal_ver : '', ); $pairs = array(); foreach ($content as $key => $value) { $pairs[] = "$key=$value"; } // Place each key-value pair on its own line: $newItem->addElement('content', implode("\n", $pairs)); // Now add the feed item: $feed->addItem($newItem); } //OK. Everything is done. Now genarate the feed. $feed->genarateFeed(); <file_sep><?php /** * String-related functions used by DrupalFinder. * * @author <NAME> <<EMAIL>> * @version 2011-11-12 */ /** * Converts the string to a string of numerical Unicode html entities. * Only works with single-byte/ASCII strings. * This function *will* double-encode existing HTML entities in the string. * * @param string $str * @return string */ function html_entities_all($str) { $result = ''; for ($i = 0; $i < strlen($str); $i++) { $result .= '&#' . ord($str[$i]) . ';'; } return $result; } /** * Convert a UTF-8 string to UTF-8 with HTML character entities (only for special chars). * * @param string $str * @return string */ function utf8_to_html($str) { // Decode (twice, just to be sure) $str = html_entity_decode($str, ENT_QUOTES, 'UTF-8'); $str = html_entity_decode($str, ENT_QUOTES, 'UTF-8'); // Encode: $str = htmlspecialchars($str, ENT_QUOTES, 'UTF-8'); // Replace single quotes with named entity: $str = str_replace('&#039;', '&apos;', $str); return $str; } /** * Convert $str to UTF-8 if we need to and if we can. * * @param string $str * @param string $from_encoding * @return string */ function convert_to_utf8($str, $from_encoding) { // Only convert if we have a different encoding: if ($from_encoding && $from_encoding != 'UTF-8') { if (function_exists('mb_convert_encoding') && in_array($from_encoding, mb_list_encodings())) { // Use mb if available, and if encoding is supported: return mb_convert_encoding($str, 'UTF-8', $from_encoding); } elseif (function_exists('iconv')) { // Otherwise try iconv: return iconv($from_encoding, 'UTF-8', $str); } } // Return the string unchanged: return $str; } /** * Cleans a piece of text. * - Trim * - Remove line breaks and compress whitespace, like browsers do. * - Convert to UTF-8. * * @param string $str * @return string */ function clean_text($str, $encoding) { return convert_to_utf8(preg_replace("/\s+/s", ' ', trim($str)), $encoding); } /** * Makes sure that each keyword is separated by ", ". * * @param string $keywords * @return string */ function format_keywords($keywords) { $a1 = explode(',', $keywords); $a2 = array(); foreach ($a1 as $keyword) { $keyword2 = trim($keyword); if ($keyword2) { $a2[] = $keyword2; } } return implode(', ', $a2); } /** * Convert encoding to its standard case. * * @param string $encoding * @return string */ function normalise_encoding($encoding) { global $ENCODINGS; $encoding = trim($encoding); // Special cases: if (strtolower($encoding) == 'shift-jis') { $encoding = 'Shift_JIS'; } else { // Find a match in the known encodings: foreach ($ENCODINGS as $std_encoding) { if (strcasecmp($encoding, $std_encoding) == 0) { return $std_encoding; } } } return $encoding; } /** * Convert a version number as a float to a string. * * @param float $ver_float * @return string */ function ver_float_to_string($ver_float) { $ver_float = (string) $ver_float; $parts = explode('.', $ver_float); $major = (int) $parts[0]; $minor = (int) substr($parts[1], 0, 2); $revision = (int) substr($parts[1], 2, 4); return "$major.$minor" . ($revision ? ".$revision" : ''); } /** * Convert a version number as a string to a float. * * @param string $ver_string * @return float */ function ver_string_to_float($ver_string) { list($major, $minor, $revision) = explode('.', $ver_string); return $major + ($minor / 100) + ($revision / 10000); } /** * Indents a flat JSON string to make it more human-readable. * * @param string $json * The original JSON string to process. * @return string * Indented version of the original JSON string. */ function format_json($json) { $result = ''; $pos = 0; $strLen = strlen($json); $indentStr = ' '; $newLine = "\n"; $prevChar = ''; $outOfQuotes = true; for ($i = 0; $i <= $strLen; $i++) { // Grab the next character in the string. $char = substr($json, $i, 1); // Are we inside a quoted string? if ($char == '"' && $prevChar != '\\') { $outOfQuotes = !$outOfQuotes; // If this character is the end of an element, // output a new line and indent the next line. } else if (($char == '}' || $char == ']') && $outOfQuotes) { $result .= $newLine; $pos--; for ($j = 0; $j < $pos; $j++) { $result .= $indentStr; } } // Add the character to the result string. $result .= $char; // If the last character was the beginning of an element, // output a new line and indent the next line. if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) { $result .= $newLine; if ($char == '{' || $char == '[') { $pos++; } for ($j = 0; $j < $pos; $j++) { $result .= $indentStr; } } $prevChar = $char; } return $result; } /** * Character encodings. */ $ENCODINGS = array ( 'pass', 'auto', 'wchar', 'byte2be', 'byte2le', 'byte4be', 'byte4le', 'BASE64', 'UUENCODE', 'HTML-ENTITIES', 'Quoted-Printable', '7bit', '8bit', 'UCS-4', 'UCS-4BE', 'UCS-4LE', 'UCS-2', 'UCS-2BE', 'UCS-2LE', 'UTF-32', 'UTF-32BE', 'UTF-32LE', 'UTF-16', 'UTF-16BE', 'UTF-16LE', 'UTF-8', 'UTF-7', 'UTF7-IMAP', 'ASCII', 'EUC-JP', 'SJIS', // Same as Shift_JIS 'Shift_JIS', // Preferred 'eucJP-win', 'SJIS-win', 'CP932', 'CP51932', 'JIS', 'ISO-2022-JP', 'ISO-2022-JP-MS', 'Windows-1250', 'Windows-1251', 'Windows-1252', 'Windows-1253', 'Windows-1254', 'Windows-1255', 'Windows-1256', 'Windows-1257', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4', 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9', 'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16', 'EUC-CN', 'CP936', 'HZ', 'EUC-TW', 'BIG-5', 'EUC-KR', 'UHC', 'ISO-2022-KR', 'CP866', 'KOI8-R', 'KOI8-U', 'ArmSCII-8', 'CP850', 'JIS-ms', 'CP50220', 'CP50220raw', 'CP50221', 'CP50222', 'GB2312', 'KS_C_5601-1987', ); <file_sep><?php // Error settings: error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE); ini_set('display_errors', 0); ini_set('display_startup_errors', 0); ini_set('log_errors', 1); // Set the site base path and add it to the include path: $base_path = "/var/aegir/platforms/drupalfinder.com"; ini_set('include_path', ini_get('include_path') . ":$base_path"); <file_sep><?php require_once 'inc/settings.inc'; require_once 'inc/strings.inc'; require_once 'inc/debug.inc'; debugOn(); ?> <!doctype html> <html> <head> <meta charset="UTF-8"> <title>DrupalFinder</title> <meta name='description' content="Web crawler/search engine that detects character encoding, title, description, keywords, hosting location, if a site is running Drupal, and, if so, the Drupal version."> <meta name='keywords' content="search engine, web crawler, drupal"> <link rel='stylesheet' href='drupalfinder.css'> </head> <body> <div id='header'> <div id='header-content'> <img id='banner' src='images/drupalfinder-banner.jpg'> <?php require "menu.php"; ?> </div> </div> <div id='main'> <div id='main-content'> <file_sep><?php require_once 'inc/settings.inc'; // Ensure this script is not being run from the browser, unless local/dev or it's me: $dev = FALSE; if (isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST']) { if ($_SERVER['HTTP_HOST'] == 'drupalfinder' || $_GET['user'] == 'mossy2100') { $dev = TRUE; } else { echo "Access denied."; exit; } } if ($dev) { echo '<pre>'; } $script_t1 = time(); require_once 'Net/GeoIP.php'; require_once 'Net/GeoIP/geoipregionvars.php'; require_once 'inc/geo.inc'; require_once 'inc/db.inc'; require_once 'inc/sites.inc'; require_once 'inc/verbose.inc'; require_once 'inc/strings.inc'; require_once 'inc/debug.inc'; debugOn(); open_db(); /** * Add a line to the log file. * * @param string $msg */ function log_msg($msg) { global $log; $date = date('Y-m-d H:i:s'); $log_msg = "$date $msg\n"; echo $log_msg; } log_msg("Started cron job."); /////////////////////////////////////////////////////////////////////////////// // Parameters. // Set maximum script execution time to 5 minutes. For some reason the cron job // is timing out approximately every 6.5 minutes. $max_script_time = 300; // seconds // Max sites should be more than we can do in $max_script_time seconds, but not so // many that the script gets slowed down by the database select query. // Value is based on best performance of about 0.5 second per host (actually it // takes around 2 seconds per host in average) $max_sites = $max_script_time * 2; /////////////////////////////////////////////////////////////////////////////// // Examine any unexamined sites, maximum of $max_sites. // Note, I changed the order-by from dt_created to site_id, because it should // be faster as site_id is indexed (primary key). $sql = " SELECT * FROM site WHERE examined = 0 ORDER BY site_id LIMIT $max_sites"; $count = 0; log_msg("Started loop..."); foreach ($dbh->query($sql, PDO::FETCH_OBJ) as $site) { $site_t1 = time(); $url = get_site_url($site); log_msg("Started examining $url..."); examine_site($site); log_msg("Finished examining $url"); $site_t2 = time(); log_msg("It took " . ($site_t2 - $site_t1) . " seconds to examine $url"); $count++; log_msg("$count sites examined by this script so far."); // Should we stop? $script_dt = $site_t2 - $script_t1; if ($script_dt >= $max_script_time) { break; } } log_msg("Finished loop."); // Calculate script time: $script_t2 = time(); $script_dt = $script_t2 - $script_t1; $avg = number_format($script_dt / $count, 1); log_msg("It took $script_dt seconds to run this script and $count sites were examined, an average of $avg seconds per site."); log_msg("Finished cron job."); if ($dev) { echo '</pre>'; } <file_sep><?php session_start(); require_once 'Net/GeoIP.php'; require_once 'Net/GeoIP/geoipregionvars.php'; require_once 'inc/geo.inc'; require_once 'inc/db.inc'; require_once 'inc/verbose.inc'; require_once 'inc/stats.inc'; require_once 'template_top.php'; open_db(); // If the search form was submitted, do search: if (!empty($_POST)) { search_sites($_POST); } // Get stats: $stats = get_stats(); //var_export($stats['countries']); ?> <h2>Search Websites</h2> <p>You can use this search engine to find Drupal sites, or in fact <em>any</em> sites with a host that matches a certain pattern, or with a title, description or keywords that match a search string, or that are hosted in a given country. Enjoy! And please <a href='<?php echo html_entities_all("mailto:<EMAIL>"); ?>'>submit feedback</a>. If you want. No pressure.</p> <form method='POST' action='index.php'> <table id='search_table'> <tr> <th> <label for='keyword'>Title/description/keywords</label> </th> <td> <input id='search_string' name='search_string' value='<?php echo utf8_to_html($_SESSION['search_params']['search_string']); ?>'> </td> </tr> <tr> <th> <label for='scheme'>Scheme</label> </th> <td> <select id='scheme' name='scheme'> <option value='0' <?php if ($_SESSION['search_params']['scheme'] == '0') echo 'selected'; ?>>- Any -</option> <option value='1' <?php if ($_SESSION['search_params']['scheme'] == '1') echo 'selected'; ?>>http</option> <option value='2' <?php if ($_SESSION['search_params']['scheme'] == '2') echo 'selected'; ?>>https</option> </select> </td> </tr> <tr> <th> <label for='host'>Host</label> </th> <td> <select id='host_pattern' name='host_pattern'> <option value='0' <?php if ($_SESSION['search_params']['host_pattern'] == '0') echo 'selected'; ?>>Contains</option> <option value='1' <?php if ($_SESSION['search_params']['host_pattern'] == '1') echo 'selected'; ?>>Begins with</option> <option value='2' <?php if ($_SESSION['search_params']['host_pattern'] == '2') echo 'selected'; ?>>Ends with</option> </select> <input id='host' name='host' value='<?php echo utf8_to_html($_SESSION['search_params']['host']); ?>'> </td> </tr> <tr> <th> <label for='country_code'>Country where hosted</label> </th> <td> <?php /* <table id='where_hosted_table'> <tr> <th> <label for='country_code'>Country</label> </th> <td> */ ?> <select id='country_code' name='country_code'> <?php // Create options HTML: $country_options = "<option value=''>- Any -</option>\n"; foreach ($stats['countries'] as $country_code => $country_name) { $country_options .= "<option value='$country_code'"; if ($_SESSION['search_params']['country_code'] == $country_code) { $country_options .= " selected"; } $country_options .= ">$country_name</option>\n"; } echo $country_options; ?> </select> <?php /* </td> </tr> <tr> <th> <label for='subcountry_code'>Subcountry</label> </th> <td> <select id='subcountry_code' name='subcountry_code'> </select> </td> </tr> <tr> <th> <label for='city'>City</label> </th> <td> <select id='city' name='city'> </select> </td> </tr> </table> */ ?> </td> </tr> <tr> <th> <label for='drupal'>Drupal sites only</label> </th> <td> <input type='checkbox' id='drupal' name='drupal' <?php if ($_SESSION['search_params']['drupal']) echo 'checked'; ?>> </td> </tr> <tr id='drupal_ver_row'> <th> <label for='drupal_ver'>Drupal version</label> </th> <td> <select id='drupal_ver' name='drupal_ver'> <option value=''>- Any -</option> <?php // Show the major Drupal versions: foreach ($stats['total_drupal_ver'] as $drupal_ver => $count) { // Skip Unknown version: if (!$drupal_ver) { continue; } // Add option: echo "<option value='$drupal_ver'"; if ($drupal_ver == $_SESSION['search_params']['drupal_ver']) { echo " selected"; } echo ">$drupal_ver.x</option>\n"; } ?> </select> </td> </tr> <tr> <td colspan='2' id='search-btn-row'> <input type='submit' value='Search'> </td> </tr> </table> </form> <!-- Include the JS --> <script> <?php /* // Output the hosting locations in JS for fast client-side interaction. $sql2 = " SELECT DISTINCT country_code, subcountry_code, city FROM site WHERE country_code IS NOT NULL ORDER BY country_code, subcountry_code, city"; $locations = array(); foreach ($dbh->query($sql2, PDO::FETCH_OBJ) as $site) { $subcountry_code = $site->subcountry_code ? $site->subcountry_code : 'XX'; $subcountry_name = array_key_exists($site->country_code, $GEOIP_REGION_NAME) && array_key_exists($site->subcountry_code, $GEOIP_REGION_NAME[$site->country_code]) ? $GEOIP_REGION_NAME[$site->country_code][$site->subcountry_code] : '- Unknown -'; $city_name = $site->city ? $site->city : '- Unknown -'; if (!array_key_exists($site->country_code, $locations)) { $locations[$site->country_code] = array(); } if (!array_key_exists($subcountry_code, $locations[$site->country_code])) { $locations[$site->country_code][$subcountry_code] = array( 'name' => $subcountry_name, 'cities' => array(), ); } $locations[$site->country_code][$subcountry_code]['cities'][] = $city_name; } echo format_json(json_encode($locations)); */ ?> </script> <?php // Search results: if (array_key_exists('search_results', $_SESSION)) { echo "<hr>\n"; // Atom feed link: $pairs = array(); $params = $_SESSION['search_params']; if (!$params['host']) { unset($params['host_pattern']); } if (!$params['drupal']) { unset($params['drupal_ver']); } foreach ($params as $param => $value) { if ($value) { if ($param == 'host' || $param == 'search_string') { $value = urlencode(base64_encode($value)); } $pairs[] = "$param=$value"; } } echo "<p><a href='feed.php?", implode('&', $pairs), "'>Get this search as an Atom feed</a></p>\n"; // Display results if there are any. if (!empty($_SESSION['search_results'])) { // Pagination variables: $page = (int) $_GET['page']; $n_total = $_SESSION['n_total_search_results']; $n_results = count($_SESSION['search_results']); $min_index = $page * PAGE_SIZE; $max_index = min(($page + 1) * PAGE_SIZE - 1, $n_results - 1); $n_pages = ceil($n_results / PAGE_SIZE); // Number of results message: if (is_numeric($n_total)) { echo "<p><strong>", number_format($n_total), ' ', ($n_total == 1 ? 'match' : 'matches') . " found.</strong>"; if ($n_total > $n_results) { echo " A maximum of ", MAX_NUM_RESULTS, " results are listed, so you may want to refine your search.\n"; } } else { echo "<p>The total number of matches could not be determined."; } echo "</p>\n"; // Sorting message: echo "<p>Results are listed alphabetically by top-level domain, domain, subdomain, etc. Links open up in a new tab or window.</p>\n"; // Show 1 page of results: for ($i = $min_index; $i <= $max_index; $i++) { $site = $_SESSION['search_results'][$i]; echo "<div class='search_result ", ($i % 2 == 0 ? 'even' : ''), "'>\n"; // URL: $url = get_site_url($site); echo "<h3><a href='$url' target='_blank'>" . utf8_to_html($url) . "</a></h3>\n"; // Title: if ($site->title) { echo "<strong>" . utf8_to_html($site->title) . "</strong>\n"; } // Description: if ($site->description) { echo "<p>" . utf8_to_html($site->description) . "</p>\n"; } // Keywords: $keywords = utf8_to_html(format_keywords($site->keywords)); if ($keywords) { echo "<p><em>$keywords</em></p>\n"; } // Hosting location: if ($site->country_code) { $country_name = $site->country_code ? $GEOIP_COUNTRY_NAME[$site->country_code] : ''; $subcountry_name = $site->subcountry_code ? $GEOIP_REGION_NAME[$site->country_code][$site->subcountry_code] : ''; $location = implode(', ', array_filter(array($site->city, $subcountry_name, $country_name))); echo "<p><span class='green'>Hosted in " . utf8_to_html($location) . ".</span></p>\n"; } else { echo "<p><span class='grey'>Hosting location could not be detected.</span></p>\n"; } // Drupal info: if ($site->drupal) { if ($site->drupal_ver > 0) { echo "<p><span class='green'>This is a Drupal " . ver_float_to_string($site->drupal_ver) . " site.</span></p>\n"; } else { echo "<p><span class='green'>This is a Drupal site, version unknown.</span></p>\n"; } } else { echo "<p><span class='grey'>This is not a Drupal site.</span></p>\n"; } // Re-examine link. // Note: // - We use base64_encode() here because urlencode() does not encode ".", which causes problems, at least on hostgator. // - We still use urlencode() to encode potential "+", "/" and "=" characters in the result from base64_encode(). echo "<p class='grey'><em>Last examined ", substr($site->dt_examined, 0, 10), ". <a href='submit_link.php?link=", urlencode(base64_encode($url)), "'>Re-examine</a></em></p>\n"; echo "</div>\n"; } // Pagination: if ($n_pages > 1) { $links = array(); for ($j = 0; $j < $n_pages; $j++) { $class = $page == $j ? 'active' : ''; $links[] = "<a href='index.php?page=$j' class='$class'>" . ($j + 1) . "</a>"; } echo "<div id='pagination'><div id='page'>Page:</div>" . implode($links) . "</div>\n"; } } else { echo "<p>No matches found.</p>\n"; } } require_once 'template_bottom.php'; <file_sep><?php /** * Verbose functions for DrupalFinder. * * @author <NAME> <<EMAIL>> * @version 2011-11-12 */ /** * The number of results to display per page. */ define('PAGE_SIZE', 10); /** * The maximum number of search results to get from the database. */ define('MAX_NUM_RESULTS', 200); /** * Displays a message, but only if we're not if in the cron job/CLI. * * @param string $msg */ function echo_msg($msg) { if (isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST']) { echo $msg, "\n"; } } /** * Add a new site to the database. * The site will only be added if it is actually new. * * @param string $url * @param string $encoding * @return int * The new site_id, or existing site record. */ function add_site($url, $encoding = 'UTF-8') { global $dbh; // Convert to UTF-8 if we need to: $url = convert_to_utf8($url, $encoding); // Parse the URL: $url_info = parse_url2($url); // Check if this site is in the database: echo_msg("Checking <span class='blue'>$url</span>..."); $site = get_site($url); if ($site) { // We already have this site: echo_msg("<span class='red'>Already in the database.</span>"); // Return the site object: return $site; } else { // This is a new site: echo_msg("<span class='green'>Not in the database, adding...</span>"); // Insert new site into the database, using (for now) the host without the www: insert_site($url_info['https'], $url_info['host']); // Return new site object: $site = new stdClass(); $site->site_id = $dbh->lastInsertId(); $site->new = TRUE; return $site; } } /** * Get a web page, with some messages for the user. * * @param string $url * @return array */ function get_web_page_verbose($url) { echo_msg("Requesting <span class='blue'>$url</span>..."); $response = get_web_page($url); // print_response($response); if (!$response['valid']) { $error_code = $response['http_code'] != 200 ? "HTTP Status Code {$response['http_code']}" : "Error {$response['errno']}"; echo_msg("<span class='red'><span class='blue'>$url</span> is invalid. $error_code.</span>"); } else { echo_msg("<span class='green'><span class='blue'>$url</span> is valid, received.</span>"); } return $response; } /** * Scans a web page's HTML looking for linked sites, then adds any new ones to the database. * Returns the number of new sites added. * * @param string $html * @param string $encoding * @return int */ function add_linked_sites($html, $encoding) { // Get any linked sites: echo_msg("Scanning for linked sites..."); $linked_sites = get_linked_sites($html); // Count new sites: $n_new_sites = 0; $n_linked_sites = count($linked_sites); if (!$n_linked_sites) { echo_msg("<span class='red'>No linked sites found.</span>"); } else { echo_msg("<span class='green'><span class='blue'>$n_linked_sites</span> linked " . ($n_linked_sites == 1 ? 'site' : 'sites') . " found.</span>"); // // Display linked sites: // echo_msg("<ol>"; // foreach ($linked_sites as $linked_site) { // echo_msg("<li>$linked_site</li>"; // } // echo_msg("</ol>"; // Add all linked sites to the database: foreach ($linked_sites as $linked_site) { // Add this site to the database if necessary: $linked_site = add_site($linked_site, $encoding); // If a new site was added, count it: if ($linked_site->new) { $n_new_sites++; } } if (!$n_new_sites) { echo_msg("<span class='red'>No new sites added.</span>"); } else { echo_msg("<span class='green'><span class='blue'>$n_new_sites</span> new " . ($n_new_sites == 1 ? 'site' : 'sites') . " added.</span>"); } } // Return number of new sites found: return $n_new_sites; } /** * Crawl a web page, looking for other sites. * Returns the number of new sites found, or FALSE if invalid. * * @param type $url * @return int * The number of linked sites found, or FALSE. */ function crawl_site($url) { // Get the HTML of this site's front page: $response = get_web_page_verbose($url); // If the URL could be loaded, scan for links and add: if ($response['valid']) { // Get the encoding: get_web_page_encoding($response); return add_linked_sites($response['content'], $response['encoding']); } return FALSE; } /** * Examine a site that's in the database. * * @param object $site * A site object, which may be a database record, or may just contain the site_id and new flag. * @return int * The number of new sites added, or FALSE if the site or site_id is invalid. */ function examine_site($site) { global $dbh; // 1. Try to load the front page. If successful: // 2. Do a reverse DNS lookup on the host, get the IP address. // 3. Get the location from the IP address. // 4. Get the encoding, title, description and keywords. // 5. Detect if it's Drupal, and the version. // 6. Get all links from the front page, and add to the database. // If the parameter is a site_id, load the site record: if ($site->new) { // Get the site record: $site = select_site($site->site_id); } // Check param is valid: if (!$site || !is_object($site)) { return FALSE; } // Values for SQL update query: $sql_values = array(); $sql_values[':site_id'] = $site->site_id; ///////////////////////////////////////////////////////////////////////////// // Try to get the web page. // Get the site URL and the URL info: $url = get_site_url($site); $url_info = parse_url2($url); // Default result is *without* the www (regardless of what is currently in the database). $url = $url_info['site']; $host = $url_info['host']; // Try *without* the www: $response = get_web_page_verbose($url_info['site']); // If that didn't work, try *with* the www: if (!$response['valid']) { $response = get_web_page_verbose($url_info['www_site']); if ($response['valid']) { $url = $url_info['www_site']; $host = $url_info['www_host']; } } // At this point we know the value for the host field, which may or may not have changed: $sql_values[':host'] = $host; if ($response['valid']) { // Site is valid. $sql_values[':valid'] = 1; ///////////////////////////////////////////////////////////////////////////// // Get the IP address: // Theoretically we could do this even if the site was invalid, but there's no point. // It will just slow the spider down, collecting data that won't be used. echo_msg("Finding IP address..."); $ip_addr = gethostbyname($host); if ($ip_addr == $host) { $ip_addr = NULL; echo_msg("<span class='red'>The IP address for <span class='blue'>$host</span> could not be detected.<span>"); } else { echo_msg("<span class='green'>The IP address for <span class='blue'>$host</span> is <span class='blue'>$ip_addr</span>.</span>"); } $sql_values[':ip_addr'] = $ip_addr; ///////////////////////////////////////////////////////////////////////////// // Find out where it's hosted: echo_msg("Detecting hosting location..."); $location = NULL; if ($ip_addr) { $location = get_location($ip_addr); if ($location) { echo_msg("<span class='green'>The site <span class='blue'>$url</span> is hosted in <span class='blue'>" . utf8_to_html($location->address) . "</span></span>"); // Add location fields to SQL values: $sql_values[':country_code'] = $location->country_code; $sql_values[':subcountry_code'] = $location->subcountry_code; $sql_values[':city'] = $location->city; } } if (!$location) { echo_msg("<span class='red'>Could not determine where $url is hosted.</span>"); $sql_values[':country_code'] = NULL; $sql_values[':subcountry_code'] = NULL; $sql_values[':city'] = NULL; } /////////////////////////////////////////////////////////////////////////// // Get the encoding, title, description and keywords: echo_msg("Getting additional site info..."); get_web_page_encoding($response); get_web_page_description($response); foreach (array('encoding', 'title', 'description', 'keywords') as $property) { $value = $response[$property]; if ($value) { echo_msg("<span class='green'>" . ucfirst($property) . ": <span class='blue'>" . utf8_to_html($value) . "</span></span>"); } else { echo_msg("<span class='red'>" . ucfirst($property) . " not found.</span>"); } $sql_values[":$property"] = $value ? $value : NULL; } /////////////////////////////////////////////////////////////////////////// // Detect Drupal $drupal = detect_drupal($response['content']); if (!$drupal) { echo_msg("<span class='red'>This is not a Drupal site.</span>"); } else { echo_msg("<span class='green'>This is a Drupal site.</span>"); // Detect the Drupal version: echo_msg("Detecting Drupal version..."); $drupal_ver = detect_drupal_ver($url); if ($drupal_ver) { echo_msg("<span class='green'>Drupal version <span class='blue'>$drupal_ver</span>.</span>"); } else { echo_msg("<span class='red'>Drupal version could not be detected.</span>"); } } $sql_values[':drupal'] = $drupal; // Convert Drupal version to string for storing in the database: $sql_values[':drupal_ver'] = $drupal_ver ? ver_string_to_float($drupal_ver) : NULL; /////////////////////////////////////////////////////////////////////////// // Crawl the site, i.e. scan for links and add to the database: $n_new_sites = add_linked_sites($response['content'], $response['encoding']); } else { // Site is invalid. $sql_values[':valid'] = 0; $sql_values[':ip_addr'] = NULL; $sql_values[':country_code'] = NULL; $sql_values[':subcountry_code'] = NULL; $sql_values[':city'] = NULL; $sql_values[':encoding'] = NULL; $sql_values[':title'] = NULL; $sql_values[':description'] = NULL; $sql_values[':keywords'] = NULL; $sql_values[':drupal'] = NULL; $sql_values[':drupal_ver'] = NULL; $n_new_sites = 0; } ///////////////////////////////////////////////////////////////////////////// // Update the database record: echo_msg("Updating database record for <span class='blue'>$url</span>..."); $sql = " UPDATE site SET host = :host, examined = 1, valid = :valid, ip_addr = :ip_addr, country_code = :country_code, subcountry_code = :subcountry_code, city = :city, encoding = :encoding, title = :title, description = :description, keywords = :keywords, drupal = :drupal, drupal_ver = :drupal_ver, dt_examined = NOW(), dt_updated = NOW() WHERE site_id = :site_id"; $stmt = $dbh->prepare($sql); $stmt->execute($sql_values); ///////////////////////////////////////////////////////////////////////////// // Do some clean-up. Check for any equal hosts (with or without 'www'), and delete them. // This shouldn't be needed any more, actually. // $sql2 = " // SELECT site_id // FROM site // WHERE https = :https AND host IN (:host, :www_host) AND site_id != :site_id"; // $stmt2 = $dbh->prepare($sql2); // $stmt2->execute(array( // ':https' => $url_info['https'], // ':host' => $url_info['host'], // ':www_host' => $url_info['www_host'], // ':site_id' => $site->site_id, // )); // while ($stmt2) { // $site = $stmt2->fetchObject(); // if (!$site) { // break; // } // $stmt3 = $dbh->prepare("DELETE FROM site WHERE site_id = :site_id"); // $stmt3->execute(array(':site_id' => $site->site_id)); // } return $n_new_sites; } <file_sep> </div> <!-- content --> </div> <!-- main --> <div id='footer'> <div id='footer-content'> <?php require "menu.php"; ?> </div> </div> <script src='js/jquery-1.7.js'></script> <script src='js/jquery.boolattr.js'></script> <script src='js/drupalfinder.js'></script> </body> </html> <file_sep><?php echo __FILE__, "<br>\n"; phpinfo();
0a03105430a939b961094f7b2578a316e2b5b059
[ "JavaScript", "PHP" ]
20
PHP
mossy2100/drupalfinder
da01227c8cf0efc210b352e70506d63e80543d87
1afb1da30249ede34492949c6f0a21fc6de00d9b
refs/heads/master
<file_sep>class Article < ApplicationRecord # Manually added below "has_many :comments" after creating/migrating comments # dependent: :destroy will delete all comments associated with article, if article is deleted has_many :comments, dependent: :destroy validates :title, presence: true, length: { minimum: 5 } validates :text, presence: true, length: { minimum: 5 } end <file_sep>Rails.application.routes.draw do get 'welcome/index' # If only using articles, just include line below. # resources :articles # If using articles and comments, include lines below. resources :articles do resources :comments end root 'welcome#index' end <file_sep>class WelcomeController < ApplicationController def index end end # Prefix Verb URI Pattern Controller#Action # welcome_index GET /welcome/index(.:format) welcome#index # articles GET /articles(.:format) articles#index # POST /articles(.:format) articles#create # new_article GET /articles/new(.:format) articles#new # edit_article GET /articles/:id/edit(.:format) articles#edit # article GET /articles/:id(.:format) articles#show # PATCH /articles/:id(.:format) articles#update # PUT /articles/:id(.:format) articles#update # DELETE /articles/:id(.:format) articles#destroy <file_sep>class ArticlesController < ApplicationController def index @articles = Article.all end def show @article = Article.find(params[:id]) end def new # Below is used if model has an error handler @article = Article.new end def edit @article = Article.find(params[:id]) #looks up article to display filled in data # render :edit end def create # render plain: params[:article].inspect # <ActionController::Parameters {"title"=>"My first Blog article", # "text"=>"Lets learn rails....and stuff."} permitted: false> # @article = Article.new(params[:article]) @article = Article.new(article_params) # Without Model Validation - Use below # @article.save # redirect_to @article # With Model Validation - Use below if @article.save redirect_to @article else render 'new' end end # validates :title, presence: true, length: { minimum: 5 } # validates :text, presence: true, length: { minimum: 5 } def update @article = Article.find(params[:id]) if @article.update(article_params) redirect_to @article else render 'edit' end # use below if no validation is used # redirect_to article_path(@article) end def destroy @article = Article.find(params[:id]) @article.destroy redirect_to articles_path end private def article_params # require is normally used for nested parameters # { # articles => { # title: "This is a title", # text: "BLAH BLAH" # } # } # params.permit(:title, :text) /use for non-nesting params.require(:article).permit(:title, :text) end end # Prefix Verb URI Pattern Controller#Action # welcome_index GET /welcome/index(.:format) welcome#index # articles GET /articles(.:format) articles#index # POST /articles(.:format) articles#create # new_article GET /articles/new(.:format) articles#new # edit_article GET /articles/:id/edit(.:format) articles#edit # article GET /articles/:id(.:format) articles#show # PATCH /articles/:id(.:format) articles#update # PUT /articles/:id(.:format) articles#update # DELETE /articles/:id(.:format) articles#destroy
de780447ee2db7f357d239a30bcca31fa054184d
[ "Ruby" ]
4
Ruby
bavarianrhino/getting_started_rails_blog
f423e872d12f60692f04cab9787429fe1b417905
ed608d53384e47a105f8e587e06c4eaf61bf8921
refs/heads/master
<repo_name>immanuelhardjo/shard-react<file_sep>/src/components/NavBar/index.js import React from 'react'; import logo from '../../assets/img/icon_logo.svg'; import { Nav, NavHome, // NavLink, // Bars, // NavMenu } from './NavBarElements'; const Navbar = () => { return ( <> <div className='NavBar' style={{margin: "1rem"}}> <Nav> <NavHome to='/shard/'> <img src={logo} alt='Logo' height = '30px' /> </NavHome> {/* <Bars /> <NavMenu> <NavLink to='/shard/projects' activeStyle> Projects </NavLink> / <NavLink to='/shard/stories' activeStyle> Stories </NavLink> / <NavLink to='/shard/about' activeStyle> About </NavLink> </NavMenu> */} </Nav> </div> </> ); }; export default Navbar;<file_sep>/src/pages/About/index.js import React from 'react'; import './about.css'; import { VerticalTimeline, VerticalTimelineElement } from 'react-vertical-timeline-component'; import 'react-vertical-timeline-component/style.min.css'; const index = () => { return ( <div> <div className = 'about-description'> I am an aspiring innovator. Currently looking for work in IT Consulting and Management Consulting. </div> <VerticalTimeline> <VerticalTimelineElement className="vertical-timeline-element--work" contentStyle={{ background: 'black', color: '#fff' }} contentArrowStyle={{ borderRight: '7px solid white' }} date="Sept'20 - Mar'21" iconStyle={{ background: 'black', color: '#fff' }} // icon={<WorkIcon />} > <h3 className="vertical-timeline-element-title">Project Manager/IoT Application Engineer</h3> <h4 className="vertical-timeline-element-subtitle">CAD-IT Consultants</h4> <p> Creative Direction, User Experience, Visual Design, Project Management, Team Leading </p> </VerticalTimelineElement> <VerticalTimelineElement className="vertical-timeline-element--work" date="Oct'20" contentStyle={{ background: 'black', color: 'black' }} iconStyle={{ background: 'black', color: '#fff' }} // icon={<WorkIcon />} > <h3 className="vertical-timeline-element-title">Bachelor of Science</h3> <h4 className="vertical-timeline-element-subtitle">Institut Teknologi Bandung</h4> <p> Majoring in electrical engineering. </p> </VerticalTimelineElement> <VerticalTimelineElement className="vertical-timeline-element--work" date="2008 - 2010" contentStyle={{ background: 'black', color: 'black' }} iconStyle={{ background: 'black', color: '#fff' }} // icon={<WorkIcon />} > <h3 className="vertical-timeline-element-title">Product Analyst Intern</h3> <h4 className="vertical-timeline-element-subtitle">Ruangguru</h4> <p> User Experience, Visual Design </p> </VerticalTimelineElement> <VerticalTimelineElement className="vertical-timeline-element--work" date="2006 - 2008" contentStyle={{ background: 'black', color: 'black' }} iconStyle={{ background: 'rgb(33, 150, 243)', color: '#fff' }} // icon={<WorkIcon />} > <h3 className="vertical-timeline-element-title">Quality Control Intern</h3> <h4 className="vertical-timeline-element-subtitle">Ruangguru</h4> <p> User Experience, Visual Design </p> </VerticalTimelineElement> <VerticalTimelineElement className="vertical-timeline-element--education" date="April 2013" contentStyle={{ background: 'black', color: 'black' }} iconStyle={{ background: 'rgb(233, 30, 99)', color: '#fff' }} // icon={<SchoolIcon />} > <h3 className="vertical-timeline-element-title">Content Marketing for Web, Mobile and Social Media</h3> <h4 className="vertical-timeline-element-subtitle">Online Course</h4> <p> Strategy, Social Media </p> </VerticalTimelineElement> <VerticalTimelineElement className="vertical-timeline-element--education" date="November 2012" contentStyle={{ background: 'black', color: 'black' }} iconStyle={{ background: 'rgb(233, 30, 99)', color: '#fff' }} // icon={<SchoolIcon />} > <h3 className="vertical-timeline-element-title">Agile Development Scrum Master</h3> <h4 className="vertical-timeline-element-subtitle">Certification</h4> <p> Creative Direction, User Experience, Visual Design </p> </VerticalTimelineElement> <VerticalTimelineElement className="vertical-timeline-element--education" date="2002 - 2006" contentStyle={{ background: 'black', color: 'black' }} iconStyle={{ background: 'rgb(233, 30, 99)', color: '#fff' }} // icon={<SchoolIcon />} > <h3 className="vertical-timeline-element-title">Bachelor of Science in Interactive Digital Media Visual Imaging</h3> <h4 className="vertical-timeline-element-subtitle">Bachelor Degree</h4> <p> Creative Direction, Visual Design </p> </VerticalTimelineElement> <VerticalTimelineElement iconStyle={{ background: 'rgb(16, 204, 82)', color: '#fff' }} // icon={<StarIcon />} /> </VerticalTimeline> </div> ) } export default index <file_sep>/src/App.js import React from 'react'; import NavBar from './components/NavBar'; import SocialBar from './components/SocialBar'; import './index.css'; import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'; import Home from './pages'; import Projects from './pages/Projects'; import Stories from './pages/Stories'; import About from './pages/About'; function App() { return ( <div className="App"> <Router> <NavBar/> <SocialBar/> <Switch> <Route path='/' exact component={Home}/> <Route path='/projects' exact component={Projects}/> <Route path='/stories' exact component={Stories}/> <Route path='/about' exact component={About}/> </Switch> </Router> </div> ); } export default App; <file_sep>/src/components/SocialBar/index.js import React from 'react'; import './socialbar.css'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faLinkedin, faInstagram } from "@fortawesome/free-brands-svg-icons"; const index = () => { return ( <div id="social-container"> <a href="https://www.linkedin.com/in/immanuel-hardjo" className="linkedin-social"> <FontAwesomeIcon icon={faLinkedin} size="2x" style={{color: 'black'}}/> </a> <a href="https://www.instagram.com/immanuelhardjo" className="instagram-social"> <FontAwesomeIcon icon={faInstagram} size="2x" style={{color: 'black'}}/> </a> </div> ) } export default index
49b2739795b2af704753c60a30ead640140178f9
[ "JavaScript" ]
4
JavaScript
immanuelhardjo/shard-react
1a8535c864531caa73b4bed3dd36f5f8288a179c
bcb7bf4153faf0bddcddabe2cf20f44b451e1d5d
refs/heads/master
<file_sep>package com.bridgelabz.usermanagement.exception; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class ErrorResponse { private int statusCode; private Object data; private String message; } <file_sep>package com.bridgelabz.usermanagement.service; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDate; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.bridgelabz.usermanagement.dto.RegisterDTO; import com.bridgelabz.usermanagement.exception.LoginException; import com.bridgelabz.usermanagement.exception.RegistrationException; import com.bridgelabz.usermanagement.exception.UnautorizedException; import com.bridgelabz.usermanagement.model.User; import com.bridgelabz.usermanagement.repository.IRegisterRepository; import com.bridgelabz.usermanagement.response.Response; import com.bridgelabz.usermanagement.util.TokenUtil; import com.bridgelabz.usermanagement.util.Utility; /** * purpose:Service implementation for user controller * * @author pratiksha * */ @Service public class UserServiceImpl implements IUserService { @Autowired private IRegisterRepository regRepository; @Autowired(required = true) private JavaMailSender javaMailSender; @Autowired private ModelMapper modelMapper; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; /** * @param email * @param password * @return response with httpstatus */ public Response validateCredentials(String email, String password) { if (email.isEmpty() || password.isEmpty()) throw new LoginException("Please enter both fields!!"); User user = regRepository.findByEmailId(email); if (user == null) throw new LoginException("Invalid EmailId"); boolean result = bCryptPasswordEncoder.matches(password, user.getPassword()); if (result) { user.setOnline(true); return new Response(HttpStatus.OK, null, "Login sucess"); } throw new UnautorizedException("Unauthorized User"); } /** * @param regdto * @return response with httpstatus */ public Response registerUser(RegisterDTO regdto) { if (regRepository.findByEmailId(regdto.getEmailId()) != null) { throw new RegistrationException("EmailId already exist!!"); } if (regRepository.findByMobile(regdto.getMobile()) != null) { throw new RegistrationException("Mobile number already exist!!"); } User regUser = modelMapper.map(regdto, User.class); regUser.setPassword(<PASSWORD>(regdto.getPassword())); sendEmail(regdto.getEmailId(), TokenUtil.getJWTToken(regdto.getEmailId())); regUser.setRegisteredDate(LocalDate.now()); givepermissions(regUser); regRepository.save(regUser); verifyUser(regUser.getEmailId()); return new Response(HttpStatus.OK, null, "success"); } /** * @param email * @param token * @return response with httpstatus */ public Response sendEmail(String email, String token) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom("<EMAIL>"); message.setTo(email); message.setSubject("Reset password Varification"); message.setText("Verification token: " + token); javaMailSender.send(message); System.out.println("mail>>>> " + message); return new Response(HttpStatus.OK, null, "Mail sent successfully..."); } /** * @param email * @return response with httpstatus */ @Override public String getJWTToken(String email) { return TokenUtil.getJWTToken(email); } /** * @param file * @param emailId * @return response with httpstatus * @throws Exception */ @Override public Response saveProfilePic(MultipartFile file, String emailId) throws Exception { User user = regRepository.findByEmailId(emailId); if (user == null) throw new UnautorizedException("Unautorized User"); byte[] bytes = file.getBytes(); String extension = file.getContentType().replace("image/", ""); String fileLocation = Utility.PROFILE_PIC_LOCATION + emailId + "." + extension; Path path = Paths.get(fileLocation); Files.write(path, bytes); user.setProfilePic(fileLocation); regRepository.save(user); return new Response(HttpStatus.OK, null, Utility.RECORD_UPDATED); } /** * @return list of user */ @Override public List<User> getUsers() { return regRepository.findAll(); } /** * @param emailId * @return response with httpstatus */ @Override public Response deleteProfilePic(String emailId) { User register = regRepository.findByEmailId(emailId); if (register == null) throw new UnautorizedException("Unautorized User"); String fileLocation = register.getProfilePic(); File file = new File(fileLocation); file.delete(); register.setProfilePic(""); regRepository.save(register); return new Response(HttpStatus.OK, null, Utility.RECORD_UPDATED); } /** * @param file * @param emailId * @return response with httpstatus * @throws IOException */ public Response updateProfilePic(MultipartFile file, String emailId) throws IOException { User register = regRepository.findByEmailId(emailId); if (register == null) throw new UnautorizedException("Unautorized User"); byte[] bytes = file.getBytes(); String extension = file.getContentType().replace("image/", ""); String fileLocation = Utility.PROFILE_PIC_LOCATION + emailId + "." + extension; Path path = Paths.get(fileLocation); Files.write(path, bytes); register.setProfilePic(fileLocation); regRepository.save(register); return new Response(HttpStatus.OK, null, Utility.RECORD_UPDATED); } /** * @param token * @return response with httpstatus */ @Override public Response verifyUser(String email) { User user = regRepository.findByEmailId(email); if (user == null) throw new UnautorizedException("Unautorized user"); user.setVerified(true); regRepository.save(user); return new Response(HttpStatus.OK, null, Utility.RECORD_UPDATED); } /** * purpose: method to get login history of a registered user */ @Override public ArrayList<Date> loginHistory(String email) { User user = regRepository.findByEmailId(email); ArrayList<Date> loginHistory = user.getLoginHistoty(); return loginHistory; } /** * purpose: logout method */ @Override public Response logout(String email) { User user = regRepository.findByEmailId(email); System.out.println("user details " + user); if (user.isOnline()) { user.setOnline(false); regRepository.save(user); return new Response(HttpStatus.OK, null, Utility.LOGOUTSUCCESS); } return new Response(HttpStatus.INTERNAL_SERVER_ERROR, null, Utility.LOGOUTFAILURE); } /** * @param user */ @SuppressWarnings("unchecked") public void givepermissions(User user) { if (user.getUserRole().contains("user")) { user.getPermissions().put("Dashboard", new HashMap() { { put("Add", false); } { put("Delete", false); } { put("modify", false); } { put("read", false); } }); user.getPermissions().put("Settings", new HashMap() { { put("Add", false); } { put("Delete", false); } { put("modify", false); } { put("read", false); } }); user.getPermissions().put("User Information", new HashMap() { { put("Add", false); } { put("Delete", false); } { put("modify", true); } { put("read", false); } }); user.getPermissions().put("Web page 1", new HashMap() { { put("Add", true); } { put("Delete", false); } { put("modify", true); } { put("read", true); } }); user.getPermissions().put("Web page 2", new HashMap() { { put("Add", true); } { put("Delete", false); } { put("modify", true); } { put("read", true); } }); user.getPermissions().put("Web page 3", new HashMap() { { put("Add", true); } { put("Delete", false); } { put("modify", true); } { put("read", true); } }); } else { user.getPermissions().put("Dashboard", new HashMap() { { put("Add", true); } { put("Delete", true); } { put("modify", true); } { put("read", true); } }); user.getPermissions().put("Settings", new HashMap() { { put("Add", true); } { put("Delete", true); } { put("modify", true); } { put("read", true); } }); user.getPermissions().put("User Information", new HashMap() { { put("Add", true); } { put("Delete", true); } { put("modify", true); } { put("read", true); } }); user.getPermissions().put("Web page 1", new HashMap() { { put("Add", true); } { put("Delete", true); } { put("modify", true); } { put("read", true); } }); user.getPermissions().put("Web page 2", new HashMap() { { put("Add", true); } { put("Delete", true); } { put("modify", true); } { put("read", true); } }); user.getPermissions().put("Web page 3", new HashMap() { { put("Add", true); } { put("Delete", true); } { put("modify", true); } { put("read", true); } }); } } } <file_sep>package com.bridgelabz.usermanagement.controller; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.bridgelabz.usermanagement.dto.RegisterDTO; import com.bridgelabz.usermanagement.model.User; import com.bridgelabz.usermanagement.response.Response; import com.bridgelabz.usermanagement.service.IUserService; /** * @author pratiksha * */ @RestController @RequestMapping("/user") public class UserController { @Autowired private IUserService userService; /** * Purpose: For user login * * @param emailId * @param password * @return response with "success" message or LoginException */ @GetMapping("/login") public ResponseEntity<Response> login(@RequestHeader String email, @RequestHeader String password) { Response response = userService.validateCredentials(email, password); return new ResponseEntity<>(response, response.getStatusCode()); } /** * Purpose: For User Registration and to sent token * * @param regdto * @return response with "success" message or RegistrationException */ @PostMapping("/register") public ResponseEntity<Response> register(@RequestBody RegisterDTO regdto) { Response response = userService.registerUser(regdto); return new ResponseEntity<>(response, response.getStatusCode()); } /** * Purpose:To get all registered user * * @return response with list of registered users or UnautorizedException */ @GetMapping("/users") public ResponseEntity<List<User>> getAllUsers() { List<User> list = userService.getUsers(); return new ResponseEntity<>(list, HttpStatus.OK); } /** * purpose: API to get login history of a registered user * * @param email * @return http status */ @GetMapping("/loginhistory") public ResponseEntity<ArrayList<Date>> loginHistory(@RequestHeader String email) { ArrayList<Date> history = userService.loginHistory(email); return new ResponseEntity<ArrayList<Date>>(history, HttpStatus.OK); } /** * purpose: API for logout functionality * * @param email * @return http status */ @GetMapping("/logout") public ResponseEntity<Response> logout(@RequestHeader String email) { Response response = userService.logout(email); return new ResponseEntity<Response>(response, HttpStatus.OK); } }<file_sep>package com.bridgelabz.usermanagement.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.Verification; /** * @author pratiksha * */ @Component public class TokenUtil { private TokenUtil() { } public static final String TOKEN_SECRET = "BridgeLabz"; private static final Logger LOGGER = LoggerFactory.getLogger(TokenUtil.class); /** * @param email * @return JWT token */ public static String getJWTToken(String email) { try { Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); return JWT.create().withClaim("emailId", email).sign(algorithm); } catch (Exception e) { LOGGER.error("Unable to create JWT Token"); } return null; } /** * @param token * @return decode token */ public static String decodeToken(String token) { Verification verification = null; try { verification = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)); } catch (IllegalArgumentException e) { LOGGER.error("Unable to decode JWT Token"); } if (verification == null) return "Unable to decode JWT Token"; JWTVerifier jwtverifier = verification.build(); DecodedJWT decodedjwt = jwtverifier.verify(token); Claim claim = decodedjwt.getClaim("emailId"); if (claim == null) return null; return claim.asString(); } } <file_sep>package com.bridgelabz.usermanagement.service; import java.time.LocalDate; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import com.bridgelabz.usermanagement.dto.DashDTO; import com.bridgelabz.usermanagement.model.User; import com.bridgelabz.usermanagement.repository.IRegisterRepository; import com.bridgelabz.usermanagement.response.Response; /** * purpose:Service class for dashboard * * @author pratiksha * */ @Service public class DashboardServiceImpl implements IDashboardService { @Autowired(required = true) IRegisterRepository repository; @Autowired ModelMapper modelMapper; @Autowired BCryptPasswordEncoder bCryptPasswordEncoder; /** * purpose: method for statistics of registered users */ @Override public HashMap<String, Long> getUserStatistics() { List<User> userList = repository.findAll(); HashMap<String, Long> map = new HashMap<String, Long>(); long total = userList.size(); long active = userList.stream().filter(c -> c.isActive()).count(); long inactive = total - active; long online = userList.stream().filter(c -> c.isOnline()).count(); map.put("total ", total); map.put("active ", active); map.put("inactive ", inactive); map.put("online ", online); return map; } /** * purpose: method for getting details of latest registered users */ @Override public List<User> getLatestRegisteredUsers() { List<User> userList = repository.findAll(); userList.sort((User user1, User user2) -> user1.getRegisteredDate().compareTo(user1.getRegisteredDate())); return userList; } /** * * @param userList * @return hashmap with percentage of male and female registered users */ @Override public HashMap<String, Double> getGenderPercentage(List<User> userList) { Double maleCount = (double) userList.stream().filter(x -> "Male".equals(x.getGender())).count(); Double femaleCount = (double) userList.stream().filter(x -> "Female".equals(x.getGender())).count(); HashMap<String, Double> gendercount = new HashMap<>(); gendercount.put("Male", (maleCount / (maleCount + femaleCount) * 100)); gendercount.put("Female", (femaleCount / (maleCount + femaleCount) * 100)); return gendercount; } /** * * @param userList * @return map with highest registered users */ @Override public Map<String, Integer> getTopCountries(List<User> userList) { Map<String, List<User>> studlistGrouped = userList.stream().collect(Collectors.groupingBy(w -> w.getCountry())); Set<String> key = studlistGrouped.keySet(); Map<String, Integer> topList = new LinkedHashMap<>(); for (String string : key) { topList.put(string, Integer.valueOf(studlistGrouped.get(string).size())); } return topList.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> newValue, LinkedHashMap::new)); } /** * * @param userList * @return map containing number of registered users based on age group */ @Override public HashMap<String, Long> getAgeGroup(List<User> userList) { long ageLessThan18 = userList.stream().filter(x -> LocalDate.now().getYear() - x.getDob().getYear() < 18) .count(); long ageGreaterThan42 = userList.stream().filter(x -> LocalDate.now().getYear() - x.getDob().getYear() > 42) .count(); long ageBetween18and22 = userList.stream().filter(x -> LocalDate.now().getYear() - x.getDob().getYear() >= 18 && LocalDate.now().getYear() - x.getDob().getYear() <= 22).count(); long ageBetween23and27 = userList.stream().filter(x -> LocalDate.now().getYear() - x.getDob().getYear() >= 23 && LocalDate.now().getYear() - x.getDob().getYear() <= 27).count(); long ageBetween28and32 = userList.stream().filter(x -> LocalDate.now().getYear() - x.getDob().getYear() >= 28 && LocalDate.now().getYear() - x.getDob().getYear() <= 32).count(); long ageBetween33and37 = userList.stream().filter(x -> LocalDate.now().getYear() - x.getDob().getYear() >= 33 && LocalDate.now().getYear() - x.getDob().getYear() <= 37).count(); long ageBetween38and42 = userList.stream().filter(x -> LocalDate.now().getYear() - x.getDob().getYear() >= 38 && LocalDate.now().getYear() - x.getDob().getYear() <= 42).count(); HashMap<String, Long> ageGroupCount = new LinkedHashMap<>(); ageGroupCount.put("18-22", ageBetween18and22); ageGroupCount.put("23-27", ageBetween23and27); ageGroupCount.put("28-32", ageBetween28and32); ageGroupCount.put("33-37", ageBetween33and37); ageGroupCount.put("38-42", ageBetween38and42); ageGroupCount.put("Over42", ageGreaterThan42); ageGroupCount.put("Under18", ageLessThan18); return ageGroupCount; } /** * * @param year * @param month * @return response with user registration history */ @Override public Response getUserStat(int year, int month) { DashDTO dashboard = new DashDTO(); List<User> userList = null; if (year == 0 && month == 0) { userList = repository.findAll(); dashboard.setUserRegistrationCount(getAlltime()); } else if (month == 0) { userList = repository.findAll().stream().filter(x -> x.getRegisteredDate().getYear() == year) .collect(Collectors.toList()); dashboard.setUserRegistrationCount(getAllByYear(year)); } else if (year == 0) { userList = repository.findAll().stream() .filter(x -> x.getRegisteredDate().getYear() == LocalDate.now().getYear() && x.getRegisteredDate().getMonthValue() == month) .collect(Collectors.toList()); dashboard.setUserRegistrationCount(getByMonthAndYear(month, LocalDate.now().getYear())); } else { userList = repository.findAll().stream().filter( x -> x.getRegisteredDate().getYear() == year && x.getRegisteredDate().getMonthValue() == month) .collect(Collectors.toList()); dashboard.setUserRegistrationCount(getByMonthAndYear(month, year)); } dashboard.setTopCountries(getTopCountries(userList)); dashboard.setGenderPercentage(getGenderPercentage(userList)); dashboard.setAgeGroup(getAgeGroup(userList)); return new Response(HttpStatus.OK, dashboard, "All time data"); } /** * * @return map containing number of registered users grouped by year */ @Override public Map<Integer, Integer> getAlltime() { List<User> userList = repository.findAll(); Map<Integer, List<User>> yearGrouped = userList.stream() .collect(Collectors.groupingBy(w -> w.getRegisteredDate().getYear())); Set<Integer> key = yearGrouped.keySet(); Map<Integer, Integer> topList = new LinkedHashMap<>(); for (Integer string : key) { topList.put(string, Integer.valueOf(yearGrouped.get(string).size())); } topList = topList.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors .toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> newValue, LinkedHashMap::new)); return topList; } /** * * @param year * @return map containing number of registered users in particular year */ @Override public Map<Object, Integer> getAllByYear(Integer year) { List<User> userList = repository.findAll(); Map<Object, List<User>> yearGrouped = userList.stream() .filter(x -> year.equals(x.getRegisteredDate().getYear())) .collect(Collectors.groupingBy(w -> w.getRegisteredDate().getMonth())); Set<Object> key = yearGrouped.keySet(); Map<Object, Integer> topList = new LinkedHashMap<>(); for (Object string : key) { topList.put(string, Integer.valueOf(yearGrouped.get(string).size())); } return topList; } /** * * @param month * @param year * @return map containing number of registered users in particular month of * given year */ @Override public HashMap<Object, Long> getByMonthAndYear(int month, int year) { long count = repository.findAll().stream() .filter(i -> i.getRegisteredDate().getYear() == year && i.getRegisteredDate().getMonthValue() == month) .count(); String[] monthName = { "January", "Febraury", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; HashMap<Object, Long> byMonthYear = new HashMap<>(); byMonthYear.put(monthName[month - 1], count); return byMonthYear; } }<file_sep>package com.bridgelabz.usermanagement.util; /** * Purpose : Constant variable declaration * * @author pratiksha */ public class Utility { public static final String RECORD_UPDATED = "Record updated successfully"; public static final String RECORD_DELETED = "Record deleted successfully"; public static final String RECORD_NOT_FOUND = "Record not found"; public static final String NEW_RECORD_CREATED = "New Record created successfully"; public static final String NEW_RECORD_CREATION_FAILED = "New Record creation failed"; public static final String RESOURCE_RETURNED = "Fetched resources successfully"; public static final String OPERATION_FAILED = "Failed to perform operation"; public static final String RECORD_UPDATION_FAILED = "Failed to update record"; public static final String EMPTY_FIELD = "Input fields can't be empty"; public static final String PROFILE_PIC_LOCATION = "/home/admin1/Desktop/Profile_Picture/"; public static final String LOGOUTSUCCESS = "Logout done successfully"; public static final String LOGOUTFAILURE = "Logout failure"; private Utility() { } }
9bf639def6b1bf223845529d4b27df401e521e19
[ "Java" ]
6
Java
pratikshatamadalge/UserManagement
3486efb9847fa76715f9d15d06d9ca9347d6f5db
00f72a084019f56b0f655d837374c17f061e8531
refs/heads/master
<repo_name>zaixiandemiao/alibaba-mesh-agent<file_sep>/mesh-agent/src/main/java/com/alibaba/dubbo/performance/demo/agent/protocol/ProtocolMsg.java package com.alibaba.dubbo.performance.demo.agent.protocol; public class ProtocolMsg { private ProtocolHeader protocolHeader = new ProtocolHeader(); private byte[] body; public byte[] getBody() { return body; } public void setBody(byte[] body) { this.body = body; } /** * */ public ProtocolMsg() { // TODO Auto-generated constructor stub } public ProtocolHeader getProtocolHeader() { return protocolHeader; } public void setProtocolHeader(ProtocolHeader protocolHeader) { this.protocolHeader = protocolHeader; } @Override public String toString() { return "ProtocolMsg{" + "protocolHeader=" + protocolHeader.toString() + ", body='" + body + '\'' + '}'; } } <file_sep>/mesh-agent/src/main/java/com/alibaba/dubbo/performance/demo/agent/protocol/process/ProviderSideProcessor.java package com.alibaba.dubbo.performance.demo.agent.protocol.process; import com.alibaba.dubbo.performance.demo.agent.dubbo.RpcClient; import com.alibaba.dubbo.performance.demo.agent.dubbo.model.Bytes; import com.alibaba.dubbo.performance.demo.agent.protocol.ProtocolHeader; import com.alibaba.dubbo.performance.demo.agent.protocol.ProtocolMsg; import com.alibaba.dubbo.performance.demo.agent.protocol.model.ConsumerRpcRequest; import com.alibaba.dubbo.performance.demo.agent.protocol.model.SerializationUtil; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; public class ProviderSideProcessor implements IProcessor<ProtocolMsg> { private Logger logger = LoggerFactory.getLogger(ProviderSideProcessor.class); private RpcClient rpcClient = new RpcClient(); public ProviderSideProcessor() { } @Override public ProtocolMsg process(ProtocolMsg msg) { // ConsumerRpcRequest data = SerializationUtil.deserialize(msg.getBody(), ConsumerRpcRequest.class); // Map map = data.getRequests(); //// Map map = JSON.parseObject(invokeString, Map.class); // String interfaceName = (String) map.get("interfaceName"); // String method = (String) map.get("method"); // String parameterTypesString = (String) map.get("parameterTypesString"); // String parameter = (String) map.get("parameter"); //// logger.info("Map -> " + map); // try { // byte[] result = rpcClient.invoke(interfaceName, method, parameterTypesString, parameter); //// byte[] result = Bytes.intToByteArray(parameter.hashCode()); // ProtocolHeader resultHeader = new ProtocolHeader(); // resultHeader.setMsgType((byte) 2); // ProtocolMsg resultMsg = new ProtocolMsg(); // Integer num = null; // try { // num = Integer.valueOf(new String(result).trim()); // } catch (NumberFormatException ex ) { // num = 0; // } // byte[] body = Bytes.intToByteArray(num); //// byte[] body = result; // resultHeader.setRequestId(msg.getProtocolHeader().getRequestId()); // if(body != null) // resultHeader.setLen(body.length); // resultMsg.setBody(body); // resultMsg.setProtocolHeader(resultHeader); // // return resultMsg; // } catch (Exception e) { // e.printStackTrace(); // } return null; } } <file_sep>/mesh-agent/src/main/java/com/alibaba/dubbo/performance/demo/agent/protocol/ConsumerConnectManager.java package com.alibaba.dubbo.performance.demo.agent.protocol; import com.alibaba.dubbo.performance.demo.agent.dubbo.RpcClientInitializer; import com.alibaba.dubbo.performance.demo.agent.protocol.process.ConsumerSideProcessor; import com.alibaba.dubbo.performance.demo.agent.protocol.process.IProcessor; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; /** * consumer agent 连接 provider agent, netty client, 3个channel */ public class ConsumerConnectManager { private EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); private Bootstrap bootstrap; private IProcessor processor = new ConsumerSideProcessor(); private Channel[] channels; private Object[] locks; public ConsumerConnectManager() {} public ConsumerConnectManager(int channelSize) { System.out.println("consumer connect manager initialize"); channels = new Channel[channelSize]; locks = new Object[channelSize]; for(int i=0; i<channelSize; i++) { locks[i] = new Object(); } } public Channel getChannel(int index, String ip, int port) throws InterruptedException { if(null != channels[index]) { return channels[index]; } if(null == bootstrap) { synchronized (this) { if (null == bootstrap) { initBootstrap(); } } } if (null == channels[index]) { synchronized (locks[index]) { if (null == channels[index]) { channels[index] = bootstrap.connect(ip, port).sync().channel(); } } } return channels[index]; } public void initBootstrap() { bootstrap = new Bootstrap() .group(eventLoopGroup) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT) .channel(NioSocketChannel.class) .handler(new AgentProtocolInitializer(processor)); } } <file_sep>/mesh-agent/src/main/java/com/alibaba/dubbo/performance/demo/agent/protocol/process/IProcessor.java package com.alibaba.dubbo.performance.demo.agent.protocol.process; import com.alibaba.dubbo.performance.demo.agent.protocol.ProtocolMsg; public interface IProcessor<T> { T process(ProtocolMsg msg); } <file_sep>/mesh-agent/src/main/java/com/alibaba/dubbo/performance/demo/agent/protocol/ProtocolHeader.java package com.alibaba.dubbo.performance.demo.agent.protocol; public class ProtocolHeader { private byte msgType; private int requestId; private int len; public int getRequestId() { return requestId; } public void setRequestId(int requestId) { this.requestId = requestId; } public byte getMsgType() { return msgType; } public void setMsgType(byte msgType) { this.msgType = msgType; } public int getLen() { return len; } public void setLen(int len) { this.len = len; } @Override public String toString() { return "ProtocolHeader{" + "msgType=" + msgType + ", requestId=" + requestId + ", len=" + len + '}'; } } <file_sep>/mesh-agent/src/main/java/com/alibaba/dubbo/performance/demo/agent/protocol/AgentProtocolInitializer.java package com.alibaba.dubbo.performance.demo.agent.protocol; import com.alibaba.dubbo.performance.demo.agent.dubbo.RpcClient; import com.alibaba.dubbo.performance.demo.agent.protocol.process.IProcessor; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; public class AgentProtocolInitializer extends ChannelInitializer { private IProcessor processor = null; private RpcClient rpcClient = null; public AgentProtocolInitializer(IProcessor p) { processor = p; } public AgentProtocolInitializer() { } @Override protected void initChannel(Channel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(new ProtocolDecoder(ProtocolService.MAX_FRAME_LENGTH, ProtocolService.LENGTH_FIELD_OFFSET, ProtocolService.LENGTH_FIELD_LENGTH, ProtocolService.LENGTH_ADJUSTMENT, ProtocolService.INITIAL_BYTES_TO_STRIP)); pipeline.addLast(new ProtocolEncoder()); pipeline.addLast(new ProtocolHandler()); } } <file_sep>/mesh-agent/src/main/java/com/alibaba/dubbo/performance/demo/agent/protocol/ProtocolService.java package com.alibaba.dubbo.performance.demo.agent.protocol; import com.alibaba.dubbo.performance.demo.agent.dubbo.RpcClient; public class ProtocolService { public static final int MAX_FRAME_LENGTH = 1024 * 1024; public static final int LENGTH_FIELD_LENGTH = 4; public static final int LENGTH_FIELD_OFFSET = 5; public static final int LENGTH_ADJUSTMENT = 0; public static final int INITIAL_BYTES_TO_STRIP = 0; private static ProviderConnectManager provider = null; private static final Object lock = new Object(); public static ProviderConnectManager getProvider() { if (null == provider) { synchronized(lock) { if (null == provider) { provider = new ProviderConnectManager(); provider.bindLocal(8888); } } } return provider; } } <file_sep>/mesh-agent/src/main/java/com/alibaba/dubbo/performance/demo/agent/protocol/process/ConsumerRpcClient.java package com.alibaba.dubbo.performance.demo.agent.protocol.process; import com.alibaba.dubbo.performance.demo.agent.dubbo.ConnecManager; import com.alibaba.dubbo.performance.demo.agent.dubbo.RpcClient; import com.alibaba.dubbo.performance.demo.agent.dubbo.model.*; import com.alibaba.dubbo.performance.demo.agent.protocol.ConsumerConnectManager; import com.alibaba.dubbo.performance.demo.agent.protocol.ProtocolHeader; import com.alibaba.dubbo.performance.demo.agent.protocol.ProtocolMsg; import com.alibaba.dubbo.performance.demo.agent.protocol.model.ConsumerRpcFuture; import com.alibaba.dubbo.performance.demo.agent.protocol.model.ConsumerRpcRequest; import com.alibaba.dubbo.performance.demo.agent.protocol.model.ConsumerRpcRequestHolder; import com.alibaba.dubbo.performance.demo.agent.protocol.model.SerializationUtil; import com.alibaba.dubbo.performance.demo.agent.registry.IRegistry; import com.alibaba.fastjson.JSON; import io.netty.channel.Channel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class ConsumerRpcClient { private Logger logger = LoggerFactory.getLogger(ConsumerRpcClient.class); private static final AtomicInteger idGenerator = new AtomicInteger(0); private ConsumerConnectManager connectManager; public ConsumerRpcClient(){ this.connectManager = new ConsumerConnectManager(); } public ConsumerRpcClient(int size) { this.connectManager = new ConsumerConnectManager(size); } public Integer invoke(int index, String ip, int port, String interfaceName, String method, String parameterTypesString, String parameter) throws Exception { Channel channel = connectManager.getChannel(index, ip, port); Map data = new HashMap(); data.put("interfaceName", interfaceName); data.put("method", method); data.put("parameterTypesString", parameterTypesString); data.put("parameter", parameter); ProtocolMsg msg = new ProtocolMsg(); ProtocolHeader header = new ProtocolHeader(); header.setMsgType((byte) 0x01); ConsumerRpcRequest request = new ConsumerRpcRequest(); request.setRequests(data); byte[] jsonStr = SerializationUtil.serialize(request); // byte[] jsonStr = JSON.toJSONString(data).getBytes(); header.setLen(jsonStr.length); msg.setBody(jsonStr); ConsumerRpcFuture future = new ConsumerRpcFuture(); int requestId = ConsumerRpcClient.idGenerator.getAndIncrement(); header.setRequestId(requestId); msg.setProtocolHeader(header); ConsumerRpcRequestHolder.put(String.valueOf(requestId), future); channel.writeAndFlush(msg); Integer result = null; try { result = future.get(); }catch (Exception e){ e.printStackTrace(); } finally { //ConsumerRpcRequestHolder.remove(requestId); } return result; } } <file_sep>/mesh-agent/src/main/java/com/alibaba/dubbo/performance/demo/agent/protocol/model/ProtocolExecutorHelper.java package com.alibaba.dubbo.performance.demo.agent.protocol.model; import java.util.concurrent.*; public class ProtocolExecutorHelper { private static final int PROCESSOR_NUM = Runtime.getRuntime().availableProcessors(); public static ExecutorService newBlockingExecutorsUseCallerRun(int size) { return new ThreadPoolExecutor(size, size, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { executor.getQueue().put(r); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); } } <file_sep>/mesh-agent/src/main/java/com/alibaba/dubbo/performance/demo/agent/AgentApp.java package com.alibaba.dubbo.performance.demo.agent; import com.alibaba.dubbo.performance.demo.agent.dubbo.RpcClient; import com.alibaba.dubbo.performance.demo.agent.protocol.ProtocolService; import com.alibaba.dubbo.performance.demo.agent.registry.EtcdRegistry; import com.alibaba.dubbo.performance.demo.agent.registry.IRegistry; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AgentApp { // agent会作为sidecar,部署在每一个Provider和Consumer机器上 // 在Provider端启动agent时,添加JVM参数-Dtype=provider -Dserver.port=30000 -Ddubbo.protocol.port=20889 // 在Consumer端启动agent时,添加JVM参数-Dtype=consumer -Dserver.port=20000 // 添加日志保存目录: -Dlogs.dir=/path/to/your/logs/dir。请安装自己的环境来设置日志目录。 public static void main(String[] args) { SpringApplication.run(AgentApp.class,args); String type = System.getProperty("type"); // 获取type参数 if ("provider".equals(type)) { // IRegistry registry = new EtcdRegistry(System.getProperty("etcd.url")); // RpcClient rpcClient = new RpcClient(); //启动provider netty server ProtocolService.getProvider(); } } }
e24eccb0b992f78e8f88621ae2f411b0d6bfcb41
[ "Java" ]
10
Java
zaixiandemiao/alibaba-mesh-agent
e767f5446190f59d6ec5e5d3027377ac07f88d0a
adb0d758d50f6763fb8eff1fe2968edfae551c47
refs/heads/master
<repo_name>victormz98/Portfolio<file_sep>/js/script.js // Deixar o scroll mais suave ao clicar no link da nav $(document).ready(function ($) { $(".navbar-nav a").addClass("ancora"); //adiciona nos links a classe 'ancora' $(".ancora").click(function (event) { event.preventDefault(); $('html,body').animate( { scrollTop: $(this.hash).offset().top }, 1000); //Tempo em milisegundos }); //efeito surgir capa $(".animated-up").css({ 'top': '20%', // 'opacity': 1, 'transition': 'all 2s' }); window.setInterval(function () { $(".animated-up").css({ 'opacity': 1 }); }, 200); //Eventos de Scroll // var posicaoElemento = $('#sobre').position().top; $(document).scroll(function () { var posicaoScroll = $(document).scrollTop(); //Obtem valor scroll no momento if (posicaoScroll > 1700) { $(".progress-bar-content .progress-right .progress-bar").css({ "animation": "padrao 1.8s linear forwards" }); $(".progress-bar-content .progress-right-half .progress-bar").css({ "animation": "javascript 1s linear forwards" }); $(".progress-bar-content.blue .progress-left .progress-bar").css({ "animation": "html 1.5s linear forwards 1.8s" }); $(".progress-bar-content.yellow .progress-left .progress-bar").css({ "animation": "jquery 1s linear forwards 1.8s" }); $(".progress-bar-content.pink .progress-left .progress-bar").css({ "animation": "photoshop 0.4s linear forwards 1.8s" }); } else if (posicaoScroll >= 700) { $(".toptop").css({ "opacity": 1 }) } else if (posicaoScroll < 700) { $(".toptop").css({ "opacity": 0 }) } }) //resposnsividade das progress bars var larguraTela = $(window).width(); if (larguraTela < 425) { $("#sobre>.container>.row>.col-sm-3").removeClass("col-xs-6"); $("#sobre>.container>.row>.col-sm-3").addClass("col-xs-12"); } }); /*Document.ready*/
f7db02f9c38a301a622bc3b5f3de80896983b2b9
[ "JavaScript" ]
1
JavaScript
victormz98/Portfolio
c2bb2f5c1995997dde4fbc57330101a5cd23ff39
7b45873f630799c327b0b7f92490d4e710251cab
refs/heads/master
<repo_name>peternolan/Catchathon<file_sep>/Reciever.h #pragma once #include "Object.h" #include "EventKeyboard.h" #include "EventCollision.h" #include "EventMouse.h" class Reciever : public df::Object { private: void kbd(const df::EventKeyboard *p_keyboard_event); void move(int dy); //void step(); void hit(const df::EventCollision *p_c); int move_slowdown; int move_countdown; public: Reciever(); ~Reciever(); int eventHandler(const df::Event *p_e); void draw(); };<file_sep>/BorderR.h #pragma once #include "Object.h" class BorderR : public df::Object { public: BorderR(); ~BorderR(); }; <file_sep>/BorderL.h #pragma once #include "Object.h" class BorderL : public df::Object { public: BorderL(); ~BorderL(); };<file_sep>/README.md "# Catchathon" <file_sep>/Reciever.cpp #include "GameManager.h" #include "LogManager.h" #include "ResourceManager.h" #include "WorldManager.h" #include "DisplayManager.h" #include "Reciever.h" #include "atlstr.h" #include "EventOut.h" #include "EventStep.h" #include "EventMouse.h" #include "EventView.h" Reciever::Reciever() { // Player controls hero, so register with keyboard and mouse. registerInterest(df::KEYBOARD_EVENT); // Need to update fire rate control each step. registerInterest(df::STEP_EVENT); // Set object type. setType("Reciever"); setAltitude(2); setSolidness(df::HARD); // Set starting location. df::Vector pos(WM.getBoundary().getHorizontal()/2, 20.0f); setPosition(pos); } // Handle event. // Return 0 if ignored, else 1. int Reciever::eventHandler(const df::Event *p_e) { CString stringType = p_e->getType().c_str(); LM.writeLog("%p\n", p_e); LM.writeLog("EVENT THAT WE ARE LOOKING AT: %s\n", stringType); if (p_e->getType() == df::COLLISION_EVENT) { LM.writeLog("COLLISION OCCURED\n"); } if (p_e->getType() == df::KEYBOARD_EVENT) { //TEST THIS const df::EventKeyboard *p_keyboard_event = (df::EventKeyboard *) (p_e); LM.writeLog("%p\n", p_keyboard_event); LM.writeLog("GET KEY IN HERO\n"); kbd(p_keyboard_event); return 1; } // If get here, have ignored this event. return 0; } Reciever::~Reciever() { } //ADDED THIS FOR POWERUP //This function determins behaviour after collision event. void Reciever::hit(const df::EventCollision *p_c) { // If it hits the power up, destroy the PowerUp, reduce the fire delay to 7 frames, and set the PowerUp time limit to 100 frames. if ((p_c->getObject1()->getType() == "PowerUp") || (p_c->getObject2()->getType() == "PowerUp")) //Delete only the PowerUp object. if (p_c->getObject1()->getType() == "PowerUp") { WM.markForDelete(p_c->getObject1()); } else { WM.markForDelete(p_c->getObject2()); } return; } // Custom draw. void Reciever::draw() { DM.drawCh(getPosition(), '0', df::BLUE); } // Take appropriate action according to key pressed. void Reciever::kbd(const df::EventKeyboard *p_keyboard_event) { LM.writeLog("IN KBD\n"); LM.writeLog("%p\n", p_keyboard_event); switch (p_keyboard_event->getKey()) { case df::Keyboard::Key::W: // up if (p_keyboard_event->getKeyboardAction() == df::KEY_PRESSED) LM.writeLog("IN KBD W\n"); move(-1); break; case df::Keyboard::Key::S: // down if (p_keyboard_event->getKeyboardAction() == df::KEY_PRESSED) LM.writeLog("IN KBD S\n"); move(+1); break; case df::Keyboard::Key::Q: // quit if (p_keyboard_event->getKeyboardAction() == df::KEY_PRESSED) WM.markForDelete(this); break; }; return; } // Move up or down. void Reciever::move(int dx) { df::Vector new_pos(getPosition().getX() + dx, getPosition().getY()); LM.writeLog("MOVE IN HERO"); // If stays on screen, allow move. if ((new_pos.getX() >= 0) && (new_pos.getX() < DM.getHorizontal())) WM.moveObject(this, new_pos); } <file_sep>/game.cpp // // game.cpp // // Engine includes. #include "GameManager.h" #include "LogManager.h" #include "ResourceManager.h" #include "Color.h" #include "Pause.h" #include "Reciever.h" #include "BorderL.h" #include "BorderR.h" //Prepares external resources for use in the game. void loadResources() { //Sprites RM.loadSprite("sprites/border-spr.txt", "border"); } // Populate world with some objects. void populateWorld() { LM.writeLog("Reciever\n"); new Reciever; new BorderL; new BorderR; } int main(int argc, char *argv[]) { // Start up game manager. if (GM.startUp()) { LM.writeLog("Error starting game manager!"); GM.shutDown(); return 0; } // Set flush of logfile during development (when done, make false). LM.setFlush(true); // Show splash screen. df::splash(); loadResources(); populateWorld(); //Run the game after all assets are registered. GM.run(); // Shut everything down. GM.shutDown(); } <file_sep>/BorderR.cpp #include "GameManager.h" #include "LogManager.h" #include "ResourceManager.h" #include "WorldManager.h" #include "BorderR.h" BorderR::BorderR() { // Set object type. setType("BorderR"); // Link to "ship" sprite. df::Sprite *p_temp_sprite; p_temp_sprite = RM.getSprite("border"); //If sprite not found: if (!p_temp_sprite) LM.writeLog("Border::Border(): Warning! Sprite '%s' not found", "border"); //If sprite found else { setSprite(p_temp_sprite); //Set sprite setSpriteSlowdown(3); // 1/3 speed animation. setTransparency(); // Transparent sprite. } setAltitude(2); setSolidness(df::HARD); // Set starting location. df::Vector pos(74, WM.getBoundary().getVertical() / 2); setPosition(pos); } BorderR::~BorderR() { }
ead18b4ee5ea3342e2a7bf0c3fd166224847121c
[ "Markdown", "C++" ]
7
C++
peternolan/Catchathon
249f51f95619408fc9577cd822a4852fd223900d
29bd8af728bd325f3b3b82548d0e05dfec6dafa1
refs/heads/master
<file_sep># Human-Analytics-Training Learning about the use of Data Analytics in Human Resources This is a test to see if I know what I'm doing <file_sep># Human Resources Analytics in R: Exploring Employee Churn # there is 10 good years of data 2006 - 2015 # column STATUS is either 'active' or 'terminated', # this will be our dependant variable # load the data hrData <- read.csv("C:/Users/EliteBook/Documents/Human Resource Data/MFG10YearTerminationData.csv") # look at the structure of the data str(hrData) # install libraries to conduct analysis install.packages('plyr') install.packages('dplyr') install.packages("magrittr") install.packages("Rcpp") library(plyr) library(magrittr) library(Rcpp) library(dplyr) # look at a summary of the data summary(hrData) # a cursory look at the data above does not have anthing jump out # as having data quality issues # What proportion of our staff are leaving? StatusCount<- as.data.frame.matrix(hrData %>% group_by(STATUS_YEAR) %>% select(STATUS) %>% table()) StatusCount$TOTAL<-StatusCount$ACTIVE + StatusCount$TERMINATED StatusCount$PercentTerminated <-StatusCount$TERMINATED/(StatusCount$TOTAL)*100 StatusCount # Where are our terminations happening? # lets look by business us library(ggplot2) ggplot() + geom_bar(aes(y = ..count..,x = as.factor(BUSINESS_UNIT),fill = as.factor(STATUS)),data=hrData, position = position_stack()) # it looks like the terminations of the last 10 years have been occuring in the Stores # lets turn our focus to just terminates # just terminates by Termination Type and Status Year TerminatesData<- as.data.frame(hrData %>% filter(STATUS=="TERMINATED")) ggplot() + geom_bar(aes(y = ..count..,x =as.factor(STATUS_YEAR),fill = as.factor(termtype_desc)),data=TerminatesData,position = position_stack()) # it appears that year-on-year most terminations are voluntary apart # from 2014 and 2015 where there wasan increase in involuntary # termination by Status Year and Termination Reason ggplot() + geom_bar(aes(y = ..count..,x= as.factor(STATUS_YEAR), fill = as.factor(termreason_desc)), data = TerminatesData, position = position_stack()) # it appears there was layoffs on 2014 and 2015 which accounsts for involunatry terminates # termination by Termination Reason and Department ggplot() + geom_bar(aes(y = ..count..,x =as.factor(department_name),fill = as.factor(termreason_desc)),data=TerminatesData,position = position_stack())+ theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5)) # from the graph we can see that resignation is high in customer service and retirement is high overall # How does Age and Length of Service affect termination install.packages('caret') install.packages('devtools') library(devtools)
42cb58d1e27ef64afbd1c36719b4c6e87ef314b3
[ "Markdown", "R" ]
2
Markdown
jayg791/Human-Analytics-Training
c7fd5c370f79b92196cca9c2eebc2575be64eda7
9254387964153fd326ee46568929c3ebe45588eb
refs/heads/master
<repo_name>ronak-patidar/laundry-version-8<file_sep>/src/CRUD/Payment_servlet.java package CRUD; import java.util.Date; import javax.servlet.http.*; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import java.text.SimpleDateFormat; import common.DB_Connection1; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.swing.JOptionPane; @WebServlet("/Payment_servlet") public class Payment_servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); if( (session.getAttribute("washandfold")!=null) || (session.getAttribute("washandiron")!=null) || (session.getAttribute("iron")!=null) || (session.getAttribute("dryclean")!=null) ){ String shirts=(String) session.getAttribute("shirts"); String tshirts=(String) session.getAttribute("tshirts"); String jeans=(String) session.getAttribute("jeans"); String trousers=(String) session.getAttribute("trousers"); String sarees=(String) session.getAttribute("sarees"); String totalamount=(String) session.getAttribute("totalamount"); String pickupdate=(String) session.getAttribute("pickupdate"); String pickupt=(String) session.getAttribute("pickupt"); String city=(String) session.getAttribute("city"); String pincode=(String) session.getAttribute("pincode"); String address=(String) session.getAttribute("address"); String landmark=(String) session.getAttribute("landmark"); String username=(String) session.getAttribute("username"); String status="Reaching"; String service =""; if(session.getAttribute("washandfold")!=null) { service ="washandfold"; } else if(session.getAttribute("washandiron")!=null) { service ="washandiron"; } else if(session.getAttribute("iron")!=null) { service ="iron"; } else if(session.getAttribute("dryclean")!=null) { service ="dryclean"; } DB_Connection1 obj_DB_Connection1=new DB_Connection1(); Connection connection=obj_DB_Connection1.get_connection(); PreparedStatement ps=null; String mobileno=""; int getValue=0; String ordn=""; try { Statement stmt =connection.createStatement(); String query1= "select mobno from register1 where name='"+username+"';"; ResultSet rs =stmt.executeQuery(query1); if(rs.next()) { mobileno=rs.getString(1); } String query2="select count(OrderNo)+1 from orderclothes1 "; ResultSet rs2 =stmt.executeQuery(query2); if(rs2.next()) { getValue = Integer.parseInt(rs2.getString(1)); } ordn="ORDC"+new SimpleDateFormat("ddMMyyy").format(new Date())+getValue; System.out.println(ordn); System.out.println(mobileno); String query="insert into orderclothes1 values('"+ordn+"','"+mobileno+"','"+service+"','"+shirts+"','"+tshirts+"','"+jeans+"','"+trousers+"','"+sarees+"','"+totalamount+"','"+pickupdate+"','"+pickupt+"','"+city+"','"+pincode+"','"+address+"','"+landmark+"','"+status+"');"; ps=connection.prepareStatement(query); ps.executeUpdate(); } catch (Exception e) { System.err.println(e); } response.sendRedirect("home1.jsp"); } else if(session.getAttribute("helmet")!=null) { String helmet=(String) session.getAttribute("chelmet"); String pickupdate=(String) session.getAttribute("pickupdate"); String pickupt=(String) session.getAttribute("pickupt"); String city=(String) session.getAttribute("city"); String pincode=(String) session.getAttribute("pincode"); String address=(String) session.getAttribute("address"); String landmark=(String) session.getAttribute("landmark"); String username=(String) session.getAttribute("username"); String totalamount=(String) session.getAttribute("totalamount"); String shoes=null; String status="Reaching"; String service =""; if(session.getAttribute("helmet")!=null) { service ="cleaning"; } int id=0; DB_Connection1 obj_DB_Connection1=new DB_Connection1(); Connection connection=obj_DB_Connection1.get_connection(); PreparedStatement ps=null; String mobileno=""; int getValue=0; String ordn=""; try { Statement stmt =connection.createStatement(); String query1= "select mobno from register1 where name='"+username+"';"; ResultSet rs =stmt.executeQuery(query1); if(rs.next()) { mobileno=rs.getString(1); } String query2="select count(OrderNo)+1 from orderothers1 "; ResultSet rs2 =stmt.executeQuery(query2); if(rs2.next()) { getValue = Integer.parseInt(rs2.getString(1)); } ordn="ORDO"+new SimpleDateFormat("ddMMyyy").format(new Date())+getValue; String query="insert into orderothers1 values('"+ordn+"','"+mobileno+"','"+service+"','"+helmet+"','"+shoes+"','"+pickupdate+"','"+pickupt+"','"+totalamount+"','"+city+"','"+pincode+"','"+address+"','"+landmark+"','"+status+"');"; ps=connection.prepareStatement(query); ps.executeUpdate(); } catch (Exception e) { System.err.println(e); } response.sendRedirect("home1.jsp"); } else if(session.getAttribute("shoes")!=null) { String shoes=(String) session.getAttribute("cshoes"); String pickupdate=(String) session.getAttribute("pickupdate"); String pickupt=(String) session.getAttribute("pickupt"); String city=(String) session.getAttribute("city"); String pincode=(String) session.getAttribute("pincode"); String address=(String) session.getAttribute("address"); String landmark=(String) session.getAttribute("landmark"); String username=(String) session.getAttribute("username"); String totalamount=(String) session.getAttribute("totalamount"); String helmet=null; String service =""; String status="Reaching"; if(session.getAttribute("shoes")!=null) { service ="cleaning"; } int id=0; DB_Connection1 obj_DB_Connection1=new DB_Connection1(); Connection connection=obj_DB_Connection1.get_connection(); PreparedStatement ps=null; String mobileno=""; int getValue=0; String ordn=""; try { Statement stmt =connection.createStatement(); String query1= "select mobno from register1 where name='"+username+"';"; ResultSet rs =stmt.executeQuery(query1); if(rs.next()) { mobileno=rs.getString(1); } String query2="select count(OrderNo)+1 from orderothers1 "; ResultSet rs2 =stmt.executeQuery(query2); if(rs2.next()) { getValue = Integer.parseInt(rs2.getString(1)); } //ordn="ORDO"+new SimpleDateFormat("ddMMyyy").format(new Date())+getValue; ordn="ORDC"+new SimpleDateFormat("ddMMyyy").format(new Date())+getValue; String query="insert into orderothers1 values('"+ordn+"','"+mobileno+"','"+service+"','"+helmet+"','"+shoes+"','"+pickupdate+"','"+pickupt+"','"+totalamount+"','"+city+"','"+pincode+"','"+address+"','"+landmark+"','"+status+"');"; ps=connection.prepareStatement(query); ps.executeUpdate(); } catch (Exception e) { System.err.println(e); } response.sendRedirect("home1.jsp"); } } } <file_sep>/src/CRUD/updateorder.java package CRUD; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Statement; import common.DB_Connection1; public class updateorder { public void uporder(String id,String status) { DB_Connection1 obj_DB_Connection1=new DB_Connection1(); Connection connection=obj_DB_Connection1.get_connection(); PreparedStatement ps=null; try { //System.out.println(id); String query1= " update orderclothes1 set status=? where OrderNo=?; "; String query2= " update orderothers1 set status=? where OrderNo=?; "; if(query1!=null) { ps=connection.prepareStatement(query1); ps.setString(1, status); ps.setString(2, id); ps.executeUpdate(); } if(query2!=null) { ps=connection.prepareStatement(query2); ps.setString(1, status); ps.setString(2, id); ps.executeUpdate(); } } catch (Exception e) { System.err.println(e); } } }
4e1b568c8c7aabe0da52f08641f8ef772cd5df32
[ "Java" ]
2
Java
ronak-patidar/laundry-version-8
43f6eda327c9b0cacb67864bc9683d7ca5f46161
c8008ceb101cec356bd490c3510193e0af3cad3e
refs/heads/master
<file_sep>git is great too
307cb570f30cff7fe37cdb174e92d6e55fec6001
[ "Shell" ]
1
Shell
vasushivram/git-repository
a8518a7fb8bd93a18aae786f0bd5ab946ac2fde3
780ded1960cea5600a97e78c673b689a40b22354
refs/heads/master
<file_sep># Recover.ws website - Lost & Found service Lost & Found service based on Ethereum, IPFS and Kleros. ## Getting started `cp .airtable.development .airtable # to set up the configuration` Add your __Airtable__ credentials to `.airtable`. `yarn start # to run the application` `yarn test # to run the tests` `yarn build # to build the application` ## Note A priori, we cannot test the Mail Subscription service in the development environnement. Because this service uses Netlify Form, and we cannot test it in this environnement. See https://community.netlify.com/t/netlify-form-in-development-application/9424 . It's not a big deal, but it's a matter of knowing.<file_sep>import Airtable from 'airtable' import fs from 'fs' import dotenv from 'dotenv' // Set up airtable envs in the development environnement. if (fs.existsSync('.airtable')) { const envConfig = dotenv.parse( fs.readFileSync('.airtable') ) for (let k in envConfig) { process.env[k] = envConfig[k] } } const { AIRTABLE_API_KEY, AIRTABLE_BASE } = process.env // TODO: move to the utils folder const getIDByEmail = (base, email) => { return new Promise((resolve, reject) => { base('Emailing').select({ view: 'Grid view', filterByFormula: `{Email} = '${email}'` }).firstPage((err, records) => { if (!records || records.length === 0) resolve(false) else records.forEach(record => resolve({ ID: record['id'] })) }) }) } // TODO: use a bot instead of a netlify function to avoid a DDOS attack exports.handler = async function(event, context, callback) { // Only allow POST if (event.httpMethod !== "POST") return { statusCode: 405, body: "Method Not Allowed" } const base = new Airtable({ apiKey: AIRTABLE_API_KEY }) .base(AIRTABLE_BASE) const params = JSON.parse(event.body) const email = params.email || '' try { const emailingID = await getIDByEmail(base, email.toLowerCase()) if (emailingID) base('Emailing').update(emailingID.ID, { "Confirmation Email": true }) else return { statusCode: 200, body: JSON.stringify({ result: `Unknown email address` }) } return { statusCode: 200, body: JSON.stringify({ result: `Data updated.` }) } } catch (err) { console.error(err) return { statusCode: 500, body: JSON.stringify({ err }) } } }
bf5f3de094bd8e6886ba5965e95f9f2214a6fc38
[ "Markdown", "JavaScript" ]
2
Markdown
blockchain-mafia/recoverto-website
faa9895957b268cac340614e42f4be0b8ac1dedd
4cf34019ee3a1bda9a7be526f6487b2aa467f7eb
refs/heads/master
<repo_name>cavein89/newgit<file_sep>/src/index.js console.log("Привет JavaScript!");
a6cac403ed6a2a283729ef3e20395f024ec9f929
[ "JavaScript" ]
1
JavaScript
cavein89/newgit
c3c61ef7ed0ba258abd3fb10be5b681c8330609e
40239b436f0a63d2bbf759bd6055c65decb27efc
refs/heads/master
<repo_name>peytonchance/lateral-entry-retention<file_sep>/js/scripts.js var chart = c3.generate({ data: { x: 'x', columns: [ ['x', 'UNC System', 'NC Private', 'Lateral Entry', 'Out of State'], ['3-year Retention Rate', 0.8528, 0.8299, 0.6454, 0.6610], ['5-year Retention Rate', 0.7219, 0.6929, 0.4781, 0.4819] ], type: 'bar', colors: { '3-year Retention Rate': '#74c476', '5-year Retention Rate': '#006d2c', }, }, legend: { show: true, position: 'inset', inset: { anchor: 'top-right', step: 2 } }, axis: { x: { type: 'category' }, y: { tick:{ format: d3.format('%') } } }, bar: { width: { ratio: 0.5 // this makes bar width 50% of length between ticks }, // or //width: 100 // this makes bar width 100px } });
d794cebc0703999bdf775a108bc59c5af180e80e
[ "JavaScript" ]
1
JavaScript
peytonchance/lateral-entry-retention
9fea930716d1529f11b603a775b68a2971933c40
1540b3b217a3efc8bfbca7dc062c1b47473ec59d
refs/heads/master
<file_sep># Title 1 Paragraph 1 ## Title 2 Paragraph 2 ### Title 3 Paragraph 3<file_sep># -*- encoding: utf-8 -*- from __future__ import unicode_literals, print_function import argparse import re import os import sys if sys.version_info.major == 2: FileNotFoundError = IOError try: from typing import List, Tuple, Optional except ImportError: pass INDEX_RE = re.compile('([\d\.]*\d) (.*)') class IndexCursor: def __init__(self): self.data = [0] self.level = 2 def encount(self, level): if level == 1: return '' if level == self.level: self.more() elif level > self.level: self.into() else: self.out() self.level = level return self.get_index() def into(self): self.data.append(1) def out(self): self.data.pop(-1) self.more() def more(self): self.data[-1] += 1 def get_index(self): return '.'.join(map(lambda x: str(x), self.data)) def init_parser(): """init a standard parser for this script""" parser = argparse.ArgumentParser(description='Add Index to markdown titles.') parser.add_argument('-r', '--rm', action='store_true', dest='rm', help='remove index, instead of adding it.') parser.add_argument('-f', '--force', action='store_true', dest='cover', help='cover the original file, use with caution.') parser.add_argument('markdown', nargs='+', help='markdown files to modify') return parser def parse_title(line): """if this is title, return Tuple[level, content], @type line: str @return: Optional[Tuple[level, content]] """ line = line.strip() if not line.startswith('#'): return None sharp_count = 0 for c in line: if c == '#': sharp_count += 1 else: break if sharp_count == len(line): return None title = line[sharp_count:].strip() return sharp_count, title def parse_index(title): """if a title is start with a index, return Tuple[Optional[index], content] else return None @type title: str @return: Tuple[Optional[index], content] """ match = INDEX_RE.match(title) if not match: return None, title return match.groups() def handle_lines(lines, args): """given lines of content, handle them and return new lines @type lines: List[str] @type args: Any """ result = [] cursor = IndexCursor() for line in lines: line = line.strip('\n\r') parsed = parse_title(line) if parsed is None: result.append(line) continue level, title = parsed # type: int, str index, title = parse_index(title) if args.rm: result.append('#' * level + ' ' + title) else: result.append('#' * level + ' ' + cursor.encount(level) + ' ' + title) return result def choose_avaliable_path(path): """choose a avaliable path based on given path @type path: str """ lead, ext = os.path.splitext(path) count = 0 while True: count += 1 result = "{}-{}{}".format(lead, count, ext) if not os.path.exists(result): return result def save_to(path, lines): """save lines to path of file @type path: str @type lines: List[str] """ with open(path, 'w') as f: f.write('\n'.join(lines)) def handle_markdown(path, args): """ @type path: str @type args: Any """ try: with open(path, 'r') as f: lines = f.readlines() # type: List[str] except FileNotFoundError: print("file {} not exist, skipping...".format(path)) return False except PermissionError: print("file {} no permission to read, skipping...".format(path)) return False handled = handle_lines(lines, args) save_path = (path if args.cover else choose_avaliable_path(path)) save_to(save_path, handled) return True def main(): parser = init_parser() args = parser.parse_args() success = True for markdown in args.markdown: if not handle_markdown(markdown, args): success = False if not success: exit(1) if __name__ == '__main__': main()<file_sep># MarkIndex [中文版文档](README-cn.md) A little tool to add index to your markdown titles. ## Usage This is your markdown file: ![](img/before.png) and you run: ```bash python markindex.py example.md ``` Then the script generate a new markdown file named `example-1.md`, it looks like this: ![](img/after.png) This script automatically add index to your markdown titles, with format like: 1.1, 1.1.2. Note that level 1 titles are ignored, since they are overall title usually. Checkout other options with `-h, --help` flag: ```bash usage: markindex.py [-h] [-r] [-f] markdown [markdown ...] Add Index to markdown titles. positional arguments: markdown markdown files to modify optional arguments: -h, --help show this help message and exit -r, --rm remove index, instead of adding it. -f, --force cover the original file, use with caution. ``` ## Future features 1. Add more types of index 1. Customize index style 1. generate table of content. <file_sep># MarkIndex 为你的Markdown标题添加索引的小工具 ## 使用说明 这是原始的Markdown文件: ![](img/before.png) 然后对它执行: ```bash python markindex.py example.md ``` 随后脚本生成了一个新的Markdown文件(为了不覆盖原文件):`example-1.md`,它的内容是: ![](img/after.png) 脚本自动为您的Markdown文件的标题添加了数字索引,按照`1.1, 1.1.1`这样的格式。 注意此处一级标题被忽略了,因为他们通常是总标题,无须添加索引。 您可以使用`-h, --help`选项来查看更多操作: ```bash usage: markindex.py [-h] [-r] [-f] markdown [markdown ...] Add Index to markdown titles. positional arguments: markdown markdown files to modify optional arguments: -h, --help show this help message and exit -r, --rm remove index, instead of adding it. -f, --force cover the original file, use with caution. ``` ## 未来实现的功能 1. 添加更多默认的索引类型 1. 自定义索引的样式 1. 生成目录
49f6518ebbfd4c24298076403e3177b5b87d1dbe
[ "Markdown", "Python" ]
4
Markdown
AZLisme/markindex
a1105f0ac1e0914507d9d5dd794cdcea531ed880
82649cb0c952eed5e92495acacfbe083fb8b3312
refs/heads/master
<repo_name>SergeyBazhmin/control-panel-for-face-recognition-service<file_sep>/src/components/WorkerInstance.js import React, { Component } from 'react'; import Button from '@material-ui/core/Button'; import PropTypes from 'prop-types'; import './WorkerInstance.css'; export default class WorkerInstance extends Component { render() { return ( <div className='worker-instance'> <div className='worker-instance-item worker-instance-name'> {this.props.name} </div> <div className='worker-instance-item worker-instance-id'> {this.props.id} </div> <div className='worker-instance-item'> <Button onClick={() => this.props.handleClick()}variant="outlined" color="primary"> {this.props.buttonText} </Button> </div> </div> ); } } WorkerInstance.propTypes = { name: PropTypes.string.isRequired, id: PropTypes.string.isRequired, buttonText: PropTypes.string.isRequired };<file_sep>/src/App.js import React from 'react'; import './App.css'; import TextField from '@material-ui/core/TextField'; import Button from '@material-ui/core/Button'; import ServerInstance from './components/ServerInstance'; import { OAUTH_HOST, USE_JWT, OAUTH_PORT, ACCESS_TOKEN_ENDPOINT } from './constants'; class App extends React.Component { constructor(props) { super(props); this.state = { connections: [], textFieldValue: '', }; } onTextFieldChanged(e) { this.setState({ textFieldValue: e.target.value }); } async componentDidMount() { if (USE_JWT){ try { const response = await fetch(`http://${OAUTH_HOST}:${OAUTH_PORT}/${ACCESS_TOKEN_ENDPOINT}`, { method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({user: 'admin', password: '<PASSWORD>'}) }); const json = await response.json(); console.log(json); sessionStorage.setItem('access-token', json.access_token); sessionStorage.setItem('refresh-token', json.refresh_token); } catch(error) { console.log(error); return; } } const hosts = JSON.parse(sessionStorage.getItem('connections-list')); if (hosts === null) return; let pong = []; for (let host of hosts) { try { await fetch(`${host}/ping`); pong.push(host); } catch (error) { console.log(error); return; } } this.setState({ connections: pong }); } closeInstance(host) { const conn = this.state.connections.filter(hst => hst !== host); this.setState({ connections: conn }); } async onAddClicked() { const hostname = this.state.textFieldValue; try { await fetch(`${hostname}/ping`); } catch (error) { console.log(error); return; } const conn = [...this.state.connections, hostname]; sessionStorage.setItem('connections-list', JSON.stringify(conn)); this.setState({ connections: conn }); } render(){ return ( <div> <div id='app-header'> <div> <TextField onChange={(e) => this.onTextFieldChanged(e)} value={this.state.textFieldValue} id="outlined-with-placeholder" label="host" placeholder="host" margin="normal" variant="outlined" /> </div> <div className='header-item'> <Button onClick={() => this.onAddClicked()} variant="outlined" color="primary"> Add </Button> </div> </div> <div className='server-contents'> {this.state.connections.map((host, idx) => <div key={host}><ServerInstance hostname={host} closeInstance={(host) => this.closeInstance(host)}/></div>)} </div> </div> ); } } export default App; <file_sep>/src/utils/tokenUtils.js import { JWT_EXPIRED } from '../errors'; import { OAUTH_HOST, OAUTH_PORT, REFRESH_TOKEN_ENDPOINT } from '../constants'; const refreshToken = async () => { const refreshToken = sessionStorage.getItem('refresh-token'); try{ let response = await fetch(`http://${OAUTH_HOST}:${OAUTH_PORT}/${REFRESH_TOKEN_ENDPOINT}`, { method: "GET", headers: { 'Authorization': `Bearer ${refreshToken}` } }); response = await response.json(); sessionStorage.setItem('access-token', response.access_token); return response.access_token; } catch(error) { console.log(error); } }; const doTwiceIfExpired = async (func) => { let token = sessionStorage.getItem('access-token'); let json = await func(token); if (!json.ok && json.message === JWT_EXPIRED) { token = await refreshToken(); json = await func(token); } return json; }; export { refreshToken, doTwiceIfExpired }; <file_sep>/src/components/debug/MyDropZone.js import React, {useCallback} from 'react'; import {useDropzone} from 'react-dropzone'; import './MyDropZone.css'; export default function MyDropzone({onImageLoaded}) { const onDrop = useCallback(acceptedFiles => { console.log(acceptedFiles); const reader = new FileReader(); reader.onload = () => { const content = reader.result.split(',')[1]; onImageLoaded(content); } acceptedFiles.forEach(file => reader.readAsDataURL(file)); }, [onImageLoaded]); const {getRootProps, getInputProps } = useDropzone({onDrop}); return ( <div> <div {...getRootProps()} className='dnd-box'> <input {...getInputProps()} /> { <p>Drag images here</p> } </div> </div> ) }<file_sep>/src/components/ServerInstance.js import React, { Component } from 'react'; import AppBar from '@material-ui/core/AppBar'; import Tabs from '@material-ui/core/Tabs'; import Tab from '@material-ui/core/Tab'; import WorkerInstance from './WorkerInstance'; import { CREATE_WORKER_ENDPOINT, USE_JWT, WORKERS_ENDPOINT, MODEL_ENDPOINT } from '../constants'; import DebugPanel from './debug/DebugPanel'; import {Line as LineChart} from 'react-chartjs-2'; import Button from '@material-ui/core/Button'; import { doTwiceIfExpired } from '../utils/tokenUtils'; import PropTypes from 'prop-types'; import io from 'socket.io-client'; import './ServerInstance.css'; export default class ServerInstance extends Component { constructor(props) { super(props); this.state = { tab: 0, runningWorkers: [], requestChartData: [], responseChartData: [], pcInfo: null }; this._spawnWorker = this._spawnWorker.bind(this); this._killWorker = this._killWorker.bind(this); } async componentDidMount() { console.log('Server instance mounting...'); try { console.log(this.props.hostname); this.socket = io(this.props.hostname); this.socket.on('data', data => { const reqData = this.state.requestChartData; const resData = this.state.responseChartData; if (reqData.length === 5) { reqData.shift(); } if (resData.length === 5) { resData.shift(); } this.setState({ requestChartData: [...this.state.requestChartData, data.nrequests], responseChartData: [...this.state.responseChartData, data.nresponses], pcInfo: data }); }); this.socket.on('workers', workers => { this.setState({ runningWorkers: [...workers] }) }); this.socket.emit('poll_data'); this.socket.emit('poll_workers'); const dataInterval = setInterval(() => this.socket.emit('poll_data'), 10000); const workerInterval = setInterval(() => this.socket.emit('poll_workers'), 30000); this.setState({ dataInterval, workerInterval }); console.log('server instance mounted'); } catch(error) { console.log(error); } } componentWillUnmount() { clearInterval(this.state.dataInterval); clearInterval(this.state.workerInterval); } async handleSpawnClick() { try { let json; if (USE_JWT) { json = await doTwiceIfExpired(this._spawnWorker); } else { console.log('wtf'); json = await this._spawnWorker(''); } this.setState({ runningWorkers: [...this.state.runningWorkers, json.id] }); } catch(error) { console.log(error); } } async _spawnWorker(token) { console.log(`${this.props.hostname}/${CREATE_WORKER_ENDPOINT}`); const response = await fetch(`${this.props.hostname}/${CREATE_WORKER_ENDPOINT}`, { headers: { 'Authorization': `Bearer ${token}` } }); const json = await response.json(); console.log(json); return json; } _killWorker(id) { return async (token) => { let response = await fetch(`${this.props.hostname}/${WORKERS_ENDPOINT}/${id}`, { method: "DELETE", headers: { 'Authorization': `Bearer ${token}` }, body: {} }); response = await response.json(); return response; } } async _getModelName(token) { let response = await fetch(`${this.props.hostname}/${MODEL_ENDPOINT}`, { headers: { 'Authorization': `Bearer ${token}` } }); response = await response.json(); return response; } async handleKillClick(id) { try { let json; if (USE_JWT){ json = await doTwiceIfExpired(this._killWorker(id)); } else { json = await this._killWorker(id)(''); } console.log(json); this.setState({ runningWorkers: this.state.runningWorkers.filter(workerID => workerID !== id) }); } catch(error) { console.log(error); } } handleTabChange(e, value) { this.setState({tab: value}); } prepareChartData() { const reqData = [...this.state.requestChartData]; const resData = [...this.state.responseChartData]; let labels = []; for (let i = reqData.length; i > 0 ; --i) labels.push(i*15); return { labels, datasets: [ { label: 'number of requests', data: reqData, fill:false, pointBackgroundColor: 'rgba(95, 158, 160, 1)', pointRadius: 6, backgroundColor: 'rgba(95, 158, 160, 1)', }, { label: 'number of responses', data: resData, fill:false, pointBackgroundColor: 'rgba(255, 0, 0, 1)', pointRadius: 9, backgroundColor: 'rgba(255,0,0,1)', } ] }; } getChartOptions(title, labelX, labelY) { return { title: { display: true, text: title, fontSize: 20 }, scales: { yAxes: [{ ticks: { beginAtZero: true, stepSize: 1 }, scaleLabel: { display: true, labelString: labelY, fontSize: 20 } }], xAxes: [{ scaleLabel: { display: true, labelString: labelX, fontSize: 20 } }], } }; } render() { return ( <div className='server-instance'> <AppBar position="static"> <Tabs value={this.state.tab} onChange={(e, value) => this.handleTabChange(e, value)}> <Tab label="Workers" /> <Tab label="Debug" /> </Tabs> </AppBar> {this.state.tab === 0 && <div> <div className='pad-container'> <div className='server-header'> {this.props.hostname} </div> <div className='server-workers'> <div className='model'> <div className='row'> <div className='model-instance-item model-instance-name'> Model </div> <div className='model-instance-item'> <Button onClick={() => this.handleSpawnClick()}variant="outlined" color="primary"> Spawn </Button> </div> </div> </div> { this.state.runningWorkers.length > 0 && <div className='running-workers'> <div className='running-workers-header'>Running Workers</div> {this.state.runningWorkers.map((worker, idx) => (<WorkerInstance name={`worker-${idx+1}`} key={idx} id={worker} buttonText={'Kill'} handleClick={() => this.handleKillClick(worker)}/>))} </div> } </div> </div> <div className='info-container'> <div className='chart-container'> <LineChart data={this.prepareChartData()} options={this.getChartOptions('Request statistics', 'Seconds ago', '# requests')} /> </div> {this.state.pcInfo && <div className='pc-stats-container'> <span className='pc-info-label'>RAM (Mb):</span> <ul> {Object.entries(this.state.pcInfo.RAM).map(([key, value]) => (<li key={key}>{key}: {value}</li>))} </ul> <span className='pc-info-label'>CPU:</span> <ul> {Object.entries(this.state.pcInfo.CPU).map(([key, value]) => (<li key={key}>{key}: {value}</li>))} </ul> </div> } </div> </div> } {this.state.tab === 1 && <DebugPanel host={this.props.hostname}/> } <div className='disconnect-button'> <Button onClick={() => this.props.closeInstance(this.props.hostname)} variant="outlined" color="primary"> Disconnect </Button> </div> </div> ); } } ServerInstance.propTypes = { hostname: PropTypes.string.isRequired };<file_sep>/src/components/debug/DebugRow.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import './DebugRow.css'; export default class GridRow extends Component { render() { const now = new Date(); const data = this.props.data; return ( <div className='debug-row'> <div className='image-box'><img src={`data:image/jpeg;base64,${data.photo}`} alt={''}/></div> <div className='text-box'>{data.person}</div> <div className='text-box'>{data.distance}</div> <div className='text-box'>{String(now)}</div> </div> ); } } GridRow.propTypes = { data: PropTypes.object.isRequired };<file_sep>/src/components/debug/DebugHeader.js import React, { Component } from 'react'; import './DebugRow.css'; import './DebugHeader.css'; export default class DebugHeader extends Component { render() { return ( <div className="debug-row" id='debug-header'> <div className="text-box">Image</div> <div className="text-box">Person</div> <div className='text-box'>Euclidean distance</div> <div className="text-box">Date</div> </div> ); } }
25eaf8c1203429c3c95b92a28969ddb2b3f54b1b
[ "JavaScript" ]
7
JavaScript
SergeyBazhmin/control-panel-for-face-recognition-service
7f3a7ac331d7303f5cc6bffb23c9601d848bfc29
bdf816599344c947305505798d7cb84f3a32bb24
refs/heads/master
<repo_name>laoniutoushx/algorithm<file_sep>/MST/main.cpp #include <iostream> #include "ReadGraph.h" #include "DenseGraph.h" #include "SparseGraph.h" #include "LazyPrimMST.h" #include "PrimMST.h" #include "KruskalMST.h" int main() { string filename = "test.txt"; DenseGraph<double> denseGraph1(8, false); ReadGraph<DenseGraph<double>, double> readGraph1(denseGraph1, filename); denseGraph1.showInfo(); SparseGraph<double> sparseGraph(8, false); ReadGraph<SparseGraph<double>, double> readGraph2(sparseGraph, filename); sparseGraph.showInfo(sparseGraph); LazyPrimMST<SparseGraph<double>, double> mst = LazyPrimMST<SparseGraph<double>, double>(sparseGraph); PrimMST<DenseGraph<double>, double> mst1 = PrimMST<DenseGraph<double>, double>(denseGraph1); KruskalMST<SparseGraph<double>, double> mst2 = KruskalMST<SparseGraph<double>, double>(sparseGraph); return 0; } <file_sep>/SORT/InsertSort.h #ifndef INSERTSORT_H #define INSERTSORT_H #include <iostream> #include <ctime> #include <string> #include <cassert> using namespace std; namespace InsortSort { template <typename T> void insertSort(T arr[], int n) { for (int i = 1; i < n; i++) { // 前面的部分 交替比较 arr[i] 与 arr[0] ~ arr[i - 1] for (int j = i; j > 0; j--) { if (arr[j] < arr[j - 1]) swap(arr[j], arr[j - 1]); else break; } } } template <typename T> void insertSortFastVersion(T arr[], int n) { for (int i = 1; i < n; i++) { // 前面的部分 交替比较 arr[i] 与 arr[0] ~ arr[i - 1] // 特别之处: 每次比较小于时,不是立即交换位置,而是 大的放到小的位置,而 当前值继续与之前的元素比较,直到遇到小于自己的,则将自己放在该位置之后,或者到达数组头部 T curValue = arr[i]; int j; // 保存元素 curValue 应该插入的位置 for (j = i; j > 0; j--) { if (curValue < arr[j - 1]) arr[j] = arr[j - 1]; else break; } arr[j] = curValue; } } // 一定范围内排序 template <typename T> void insertSortArrayBoundary(T arr[], int l, int r) { // left right arr[l .... r] 区间排序 for (int i = l; i < r; i++) { int minIndex = i + 1; T minValue = arr[minIndex]; for (int k = i + 1; k > l; k--) { if (arr[k - 1] > minValue) { arr[k] = arr[k - 1]; minIndex = k - 1; } else { break; } } arr[minIndex] = minValue; } } } // namespace InsortSort #endif<file_sep>/MST/DenseGraph.h // // Created by haruhi on 2020/3/31. // #ifndef GRAPH_DENSEGRAPH_H #define GRAPH_DENSEGRAPH_H #include <iostream> #include <vector> #include <cassert> #include "Edge.h" using namespace std; template<typename Weight> class DenseGraph { private: int n, // vertex num m; // edge num bool directed; // whether the edge has direction bool *marked; vector<vector<Edge<Weight> *>> g; public: DenseGraph(int n, bool directed) { this->n = n; this->m = 0; this->directed = directed; this->marked = new bool[n]; for (int i = 0; i < n; i++) { this->marked[i] = false; g.push_back(vector<Edge<Weight> *>(n, NULL)); } } ~DenseGraph() { for (int i = 0; i < n; i++) { for (int j = 0; j < this->g[i].size(); j++) { if (this->g[i][j] != NULL) delete this->g[i][j]; } } } int V() { return this->n; } int E() { return this->m; } /** * add a edge to graph * @param v cross axis index * @param w vertical axis index */ void addEdge(int v, int w, Weight weight) { // if (this->hasEdge(v, w)) // return; // if have duplicate edge in graph, del this edge in graph, then recreate it in graph if (this->hasEdge(v, w)) { delete g[v][w]; if (!directed) delete g[w][v]; this->m--; } this->g[v][w] = new Edge<Weight>(v, w, weight); // this->g[v][w] = true; if (!this->directed) // this->g[w][v] = true; this->g[w][v] = new Edge<Weight>(w, v, weight); this->m++; } bool hasEdge(int v, int w) { assert(v >= 0 && v < n); assert(w >= 0 && w < n); // return this->g[v][w]; return this->g[v][w] != NULL; } // get all of the vertex that adjacent to a vertex {v}, return a point list vector<Edge<Weight> *> adj(int v) { assert(v >= 0 && v < n); vector<Edge<Weight> *> ret = vector<Edge<Weight> *>(); for (int i = 0; i < n; i++) { if (this->g[v][i]) ret.push_back(this->g[v][i]); else if (this->g[i][v]) ret.push_back(this->g[i][v]); } return ret; } void showInfo() { cout << "DenseGraph:" << endl; cout << " "; for (int x = 0; x < V(); x++) cout << " " << x; cout << endl; for (int x = 0; x < V(); x++) { cout << x << " "; for (int y = 0; y < V(); y++) { if (g[x][y]) { cout << this->g[x][y]->wt() << " "; } else { cout << "NULL" << " "; } } cout << endl; } cout << endl; } class adjIterator { private: DenseGraph &G; int v; int index; public: adjIterator(DenseGraph &graph, int v) : G(graph) { this->index = -1; this->v = v; } Edge<Weight> *begin() { this->index = -1; return next(); } Edge<Weight> *next() { for (index += 1; index < this->G.V(); index++) { if (this->G.g[v][index]) return this->G.g[v][index]; } return NULL; } bool end() { return this->index >= this->G.V(); } }; }; #endif //GRAPH_DENSEGRAPH_H <file_sep>/SORT/MergeSort.h #ifndef MERGESORT_H #define MERGESORT_H #include <iostream> #include <ctime> #include <string> #include <cassert> #include "SortTestHelper.h" #include "InsertSort.h" using namespace std; // 自顶向下 namespace MergeSort { template <typename T> void merge(T arr[], int l, int mid, int r) { // 原址归并 arr[i..mid] ~ arr[mid+1..r] int i = l, j = mid + 1; T aux[r - l + 1]; // 辅助数组 for (int k = l; k <= r; k++) { aux[k - l] = arr[k]; } for (int k = l; k <= r; k++) { if (i > mid) { // 左边数组 超出边界, 则直接将右边数组按序赋值给 arr arr[k] = aux[j - l]; j++; } else if (j > r) { // 右边数组 超出边界, 则直接将左边数组按序复制给 arr arr[k] = aux[i - l]; i++; } else if (aux[i - l] < aux[j - l]) { // 左右数组 index 均未越界, 则比较 左右当前 index 所在值大小,按代大小 复制到 arr arr[k] = aux[i - l]; i++; } else { arr[k] = aux[j - l]; j++; } } } template <typename T> void seperate(T arr[], int l, int r) { // 第二个优化点 在一点数量的输入集中, 插入排序性能要优于归并排序,此处设置一个 字数组临界点,转换为插入排序 // if (l >= r) // { // return; // } if( r - l <= 15){ return InsortSort::insertSortArrayBoundary(arr, l, r); } int mid = l + (r - l) / 2; // (0 + 3) / 2 = 1 (0 + 1) / 2 = 0; seperate(arr, l, mid); seperate(arr, mid + 1, r); // 第一个优化点 [由于 arr[l, mid] 与 arr[mid + 1, r] 已经各自有序, // 故对于近乎有序的数组输入来说, 此处可 判断 arr[mid] > arr[mid + 1] 来判断是否需要归并 ] if(arr[mid] > arr[mid + 1]) merge(arr, l, mid, r); } template <typename T> void mergeSort(T arr[], int n) { seperate(arr, 0, n - 1); } } // namespace MergeSort #endif<file_sep>/List/unionSeqList.h #ifndef UNIONSEQLIST_H #define UNIONSEQLIST_H #include <iostream> #include <ctime> #include <string> #include <cassert> using namespace std; namespace UnionSeqList { template <typename T> T *unionTowOrderedList(T first[], int m, T second[], int n) { T *unioned = new T[m + n]; int first_index = 0, second_index = 0; while (first_index < m && second_index < n) { T first_element = first[first_index]; T second_element = second[second_index]; if (first_element < second_element) { unioned[first_index + second_index] = first_element; first_index++; } else { unioned[first_index + second_index] = second_element; second_index++; } } for (; first_index < m; first_index++) unioned[first_index + second_index] = first[first_index]; for (; second_index < n; second_index++) unioned[first_index + second_index] = second[second_index]; return unioned; } template <typename T> void printArray(T arr[], int n) { for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; return; } } // namespace UnionSeqList #endif<file_sep>/MST/MinimumIndexHeap.h // // Created by haruhi on 2020/4/7. // #ifndef MINIMUMINDEXHEAP_H #define MINIMUMINDEXHEAP_H #include <iostream> #include <cassert> #include <vector> using namespace std; // min heap template<typename Node> class MinIndexHeap { private: Node *nodes; // heap elements array int limit; // the position that next node will be placed, it also represents the array boundary // now it represents array indexes limit int length; // the heap array initialize length // nodes [1, 3, 2, 7, 5, 8]; element array // 0 1 2 3 4 5 nodes index // indexes [0, 1, 2, 3, 4, 5]; index of ele in nodes // 0 1 2 3 4 5 indexes index int *indexes; // the array indexes reflect to array node's index // handler the indexes array, only move the pointer which point to nodes element void shiftUp(int pos) { if (pos > 0 && pos <= limit) { int par_pos = (pos - 1) / 2; if (nodes[indexes[pos]] < nodes[indexes[par_pos]]) { swap(indexes[pos], indexes[par_pos]); shiftUp(par_pos); } } } void shiftDown(int pos) { if (pos < limit && pos * 2 + 1 < limit) { int left_child_pos = pos * 2 + 1; int right_child_pos = left_child_pos + 1; int cur_min_val_pos = left_child_pos; if (right_child_pos < limit && nodes[indexes[right_child_pos]] < nodes[indexes[left_child_pos]]) { cur_min_val_pos = right_child_pos; } if (nodes[indexes[pos]] < nodes[indexes[cur_min_val_pos]]) return; // swap indexes pointer position, to remain heap nature swap(indexes[cur_min_val_pos], indexes[pos]); shiftDown(cur_min_val_pos); } } // return {indexes index} of element node in indexes array int findIndexesIndexByNodeValue(Node node) { for (int i = 0; i < limit; i++) { if (nodes[indexes[i]] == node) { return i; } } return -1; } int findIndexesIndexByNodesIndex(int node_index) { if (node_index >= 0 && node_index < limit) { for (int i = 0; i < limit; i++) { if (node_index == indexes[i]) return i; } } return -1; } void print(vector<int> &v) { for (int &i : v) { if (i < limit) cout << nodes[indexes[i]] << " "; } cout << endl; } public: MinIndexHeap(int n) { this->limit = 0; this->length = n; this->nodes = new Node[n]; this->indexes = new int[n]; for(int i = 0; i < n; i++){ indexes[i] = i; } } // put node in nodes[?] certainly void insert(int index, Node node) { if (index >= 0 && index < length) { // put node nodes[index] = node; // save node index indexes[limit] = index; shiftUp(index); limit++; } } // add element void add(Node node) { // put the element in array end, then shift up, find the appropriate position assert(limit < length); nodes[indexes[limit]] = node; // nodes[limit] = node; // put the node to heap array[limit] shiftUp(limit); // keep heap property limit++; // limit ++ } // get top element in heap Node pop() { assert(limit >= 0); Node ret = nodes[indexes[0]]; // remember first element in heap array limit--; // limit -- swap(indexes[limit], indexes[0]); // swap end element and first element in heap array shiftDown(0); // keep heap property return ret; } // get top element indexes index int popIndex() { assert(limit >= 0); int retIndex = indexes[0]; limit--; swap(indexes[limit], indexes[0]); // swap end element and first element in heap array shiftDown(0); // keep heap property return retIndex; } void del(Node node) { int del_index = findIndexesIndexByNodeValue(node); if (del_index >= 0 && del_index < limit) { limit--; swap(indexes[limit], indexes[del_index]); shiftUp(del_index); shiftDown(del_index); } } // someone who want to del the ith node in nodes, it equals nodes[i] {nodes index} void delByIndex(int del_index) { if (del_index >= 0 && del_index < limit) { // find indexes index by nodes index del_index = findIndexesIndexByNodesIndex(del_index); limit--; swap(indexes[limit], indexes[del_index]); shiftUp(del_index); shiftDown(del_index); } } // update node by index(node index) void update(int udp_index, Node udp_node) { if (udp_index >= 0 && udp_index < limit) { nodes[udp_index] = udp_node; // find indexes index by nodes index udp_index = findIndexesIndexByNodesIndex(udp_index); shiftUp(udp_index); shiftDown(udp_index); } } bool isEmpty() { return limit == 0; } void showNodes() { for (int i = 0; i < limit; i++) { cout << nodes[i] << " -> "; } cout << endl; } void showIndexes() { for (int i = 0; i < limit; i++) { cout << indexes[i] << " -> "; } cout << endl; } void show() { // level sequence traversal cout << "Min Index Heap:" << endl; vector<int> par_s; int par_pos = 0; par_s.push_back(par_pos); while (!par_s.empty()) { print(par_s); vector<int> next_pars; for (int par_ : par_s) { par_pos = par_; int left_child_pos = par_pos * 2 + 1; int right_child_pos = left_child_pos + 1; if (left_child_pos < limit) next_pars.push_back(left_child_pos); if (right_child_pos < limit) next_pars.push_back(right_child_pos); } par_s = next_pars; } } }; #endif //MINIMUMINDEXHEAP_H <file_sep>/ShortestPath/main.cpp #include <iostream> #include <vector> #include <stack> #include <cassert> #include "Edge.h" #include "SparseGraph.h" #include "DenseGraph.h" #include "UnionFind.h" #include "ReadGraph.h" #include "MinimumIndexHeap.h" #include "Dijkstra.h" #include "Bellman-Ford.h" using namespace std; int main() { // string filename = "test.txt"; // int V = 6; // SparseGraph<int> g = SparseGraph<int>(V, true); // ReadGraph<SparseGraph<int>, int> readGraph(g, filename); // // cout << "Test dijkstra: " << endl; // Dijkstra<SparseGraph<int>, int> dij(g, 0); // for (int i = 0; i < V; i++) { // cout << "shortest path to" << i << " : " << dij.shortestPathTo(i) << endl; // dij.showPath(i); // cout << "-----------" << endl; // } string filename2 = "testG2.txt"; int V2 = 6; SparseGraph<int> g = SparseGraph<int>(V2, true); ReadGraph<SparseGraph<int>, int> readGraph(g, filename2); cout << "Test dijkstra: " << endl; Bellman_Ford<SparseGraph<int>, int> bf(g, 0); for (int i = 0; i < V2; i++) { cout << "shortest path to" << i << " : " << bf.shortestPathTo(i) << endl; bf.showPath(i); cout << "-----------" << endl; } return 0; } <file_sep>/ShortestPath/CMakeLists.txt cmake_minimum_required(VERSION 3.17) project(ShortestPath) set(CMAKE_CXX_STANDARD 14) add_executable(ShortestPath main.cpp Dijkstra.h Bellman-Ford.h)<file_sep>/SORT/MergeSortBU.h #ifndef MERGESORTBU_H #define MERGESORTBU_H #include <iostream> #include <ctime> #include <string> #include <cassert> #include <algorithm> #include "SortTestHelper.h" using namespace std; // 自底向上 namespace MergeSortBU { template <typename T> void merge(T arr[], int l, int mid, int r) { // 原址归并 arr[i..mid] ~ arr[mid+1..r] int i = l, j = mid + 1; T aux[r - l + 1]; // 辅助数组 for (int k = l; k <= r; k++) { aux[k - l] = arr[k]; } for (int k = l; k <= r; k++) { if (i > mid) { // 左边数组 超出边界, 则直接将右边数组按序赋值给 arr arr[k] = aux[j - l]; j++; } else if (j > r) { // 右边数组 超出边界, 则直接将左边数组按序复制给 arr arr[k] = aux[i - l]; i++; } else if (aux[i - l] < aux[j - l]) { // 左右数组 index 均未越界, 则比较 左右当前 index 所在值大小,按代大小 复制到 arr arr[k] = aux[i - l]; i++; } else { arr[k] = aux[j - l]; j++; } } } template <typename T> void mergeSort(T arr[], int n) { // 最底层开始循环 处理 跳跃距离 1 2 4 8, 通过 i 来分割数组 for(int i = 1; i < n; i += i){ // 内层数组循环整个数组,确定 两两归并数组的 边界 left mid right for(int l = 0, mid = l + i - 1, r = i + i - 1; l < n - i; l += i + i, mid += i + i, r += i + i){ // 每次 对 arr[l...l+i-1] 与 arr[l+i...l+i+i-1] 这两部分进行归并 merge(arr, l, mid, std::min(r, n - 1)); } } } } // namespace MergeSort #endif<file_sep>/UnionSet/UnionFindI.h // // Created by haruhi on 2020/3/29. // #ifndef UNIONSET_I_UNIONFINDI_H #define UNIONSET_I_UNIONFINDI_H #include <iostream> #include <assert.h> // QuickFind using namespace std; namespace UFI { class UnionFind { private: // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 此行代表数组 index // [1, 1, 2, 2, 3, 3, 4, 5, 7, 1] 相同的值代表 此处(index)是相互连接的 int *id; // 表示并查集的数组 int count; // 元素数量 public: UnionFind(int n) { this->count = n; this->id = new int[n]; // 默认初始化复制,各个节点都不连通 for (int i = 0; i < n; i++) { this->id[i] = i; } } ~UnionFind() { delete[] this->id; } // 获取连接点的值 int find(int index) { assert(index >= 0 && index < this->count); return this->id[index]; } // 判断是否连接 bool isConnected(int p, int q) { if (p == q) return true; assert(p >= 0 && p < this->count && q >= 0 && q < this->count); return this->id[p] == this->id[q]; } /** * 连接两个节点 * 讲其中一个节点的值全部赋值为另一个节点的值,即为连接 * @param p p节点 * @param q q节点 */ void unionE(int p, int q) { if (p == q) return; for (int i = 0; i < this->count; i++) if (this->find(p) != this->find((q))) this->id[p] = this->id[q]; } }; } #endif //UNIONSET_I_UNIONFINDI_H <file_sep>/Heap/MinimumReverseIndexHeap.h // // Created by haruhi on 2020/4/7. // #ifndef MINIMUMREVERSEINDEXHEAP_H #define MINIMUMREVERSEINDEXHEAP_H #include <iostream> #include <cassert> #include <vector> using namespace std; // min heap template<typename Node> class MinRevIndexHeap { private: Node *nodes; // heap elements array int limit; // the position that next node will be placed, it also represents the array boundary // now it represents array indexes limit int length; // the heap array initialize length // nodes [1, 3, 2, 7, 5, 8]; element array // indexes [0, 1, 2, 3, 4, 5]; index of ele in nodes int *indexes; // the array indexes reflect to array node's index int *revIndexes; // the array // handler the indexes array, only move the pointer which point to nodes element void shiftUp(int pos) { if (pos > 0 && pos <= limit) { int par_pos = (pos - 1) / 2; if (nodes[indexes[pos]] < nodes[indexes[par_pos]]) { swap(indexes[pos], indexes[par_pos]); shiftUp(par_pos); } } } void shiftDown(int pos) { if (pos < limit && pos * 2 + 1 < limit) { int left_child_pos = pos * 2 + 1; int right_child_pos = left_child_pos + 1; int cur_min_val_pos = left_child_pos; if (right_child_pos < limit && nodes[indexes[right_child_pos]] < nodes[indexes[left_child_pos]]) { cur_min_val_pos = right_child_pos; } if (nodes[indexes[pos]] < nodes[indexes[cur_min_val_pos]]) return; // swap indexes pointer position, to remain heap nature swap(indexes[cur_min_val_pos], indexes[pos]); shiftDown(cur_min_val_pos); } } // return index of element node in heap array nodes int find(Node node) { for (int i = 0; i < limit; i++) { if (nodes[indexes[i]] == node) { return i; } } return -1; } void print(vector<int> &v) { for (int &i : v) { if (i < limit) cout << nodes[indexes[i]] << " "; } cout << endl; } public: MinRevIndexHeap(int n) { this->limit = 0; this->length = n; this->nodes = new Node[n]; this->indexes = new int[n]; for (int i = 0; i < n; i++) { this->indexes[i] = i; } } // add element void add(Node node) { // put the element in array end, then shift up, find the appropriate position assert(limit < length); nodes[indexes[limit]] = node; // nodes[limit] = node; // put the node to heap array[limit] shiftUp(limit); // keep heap property limit++; // limit ++ } // get top element in heap Node pop() { assert(limit >= 0); Node ret = nodes[indexes[0]]; // remember first element in heap array limit--; // limit -- swap(indexes[limit], indexes[0]); // swap end element and first element in heap array shiftDown(0); // keep heap property return ret; } // someone who want to del node, use this method void del(Node node) { int del_index = find(node); if (del_index > 0) { limit--; swap(indexes[limit], indexes[del_index]); shiftUp(del_index); shiftDown(del_index); } } // someone who want to del the ith node in nodes, it equals nodes[i] void del(int node_index){ } void showNodes() { for (int i = 0; i < limit; i++) { cout << nodes[i] << " -> "; } cout << endl; } void showIndexes() { for (int i = 0; i < limit; i++) { cout << indexes[i] << " -> "; } cout << endl; } void show() { // level sequence traversal cout << "Min Heap:" << endl; vector<int> par_s; int par_pos = 0; par_s.push_back(par_pos); while (!par_s.empty()) { print(par_s); vector<int> next_pars; for (int par_ : par_s) { par_pos = par_; int left_child_pos = par_pos * 2 + 1; int right_child_pos = left_child_pos + 1; if (left_child_pos < limit) next_pars.push_back(left_child_pos); if (right_child_pos < limit) next_pars.push_back(right_child_pos); } par_s = next_pars; } } }; #endif //MINIMUMREVERSEINDEXHEAP_H <file_sep>/ShortestPath/Bellman-Ford.h // // Created by SuzumiyaHaruhi on 2020/4/21. // #ifndef SHORTESTPATH_BELLMAN_FORD_H #define SHORTESTPATH_BELLMAN_FORD_H #include <iostream> #include <vector> #include <stack> #include <cassert> #include "Edge.h" #include "SparseGraph.h" #include "DenseGraph.h" #include "UnionFind.h" // relaxation every point to find the shorest path template<typename Graph, typename Weight> class Bellman_Ford { private: Graph &G; int s; // start point vector<Edge<Weight> *> from; Weight *distTo; bool hasNegativeCycle; bool checkNegativeCycle() { // relaxation for (int i = 0; i < G.V(); i++) { // to find the shortest path to s, must relaxation every point to get short weight typename Graph::adjIterator adj(G, i); // traversal the points adjacent to s for (Edge<Weight> *e = adj.begin(); !adj.end(); e = adj.next()) { // if the adjacent point w not have shortest edge or s to w is shortest than ever recorded if (!from[e->w()] || distTo[e->v()] + e->wt() < distTo[e->w()]) { // record current the minimal weight to the point w return true; } } } return false; } public: Bellman_Ford(Graph &graph, int s) : G(graph), s(s) { // initialization distTo = new Weight[G.V()]; for (int i = 0; i < G.V(); i++) { from.push_back(NULL); } // start s distTo[s] = Weight(); // to find the point shortest path in a negative power directed graph, every point must traversal v - 1 times for (int pass = 0; pass < G.V() - 1; pass++) { // relaxation for (int i = 0; i < G.V(); i++) { // to find the shortest path to s, must relaxation every point to get short weight typename Graph::adjIterator adj(G, i); // traversal the points adjacent to s for (Edge<Weight> *e = adj.begin(); !adj.end(); e = adj.next()) { // if the adjacent point w not have shortest edge or s to w is shortest than ever recorded if (!from[e->w()] || distTo[e->v()] + e->wt() < distTo[e->w()]) { // record current the minimal weight to the point w from[e->w()] = e; distTo[e->w()] = distTo[e->v()] + e->wt(); } } } } hasNegativeCycle = checkNegativeCycle(); } Weight shortestPathTo(int w) { assert(!hasNegativeCycle); return distTo[w]; } bool hasPathTo(int w) { assert(!hasNegativeCycle); return from[w] != NULL; } void shortestPath(int w, vector<Edge<Weight>> &vec) { assert(!hasNegativeCycle); stack<Edge<Weight> *> s; Edge<Weight> *e = from[w]; while (e != NULL) { s.push(e); e = from[e->v()]; } while (!s.empty()) { e = s.top(); vec.push_back(*e); s.pop(); } } void showPath(int w) { assert(w >= 0 && w < G.V()); assert(!hasNegativeCycle); vector<Edge<Weight>> vec; shortestPath(w, vec); for (int i = 0; i < vec.size(); i++) { cout << vec[i].v() << " -> "; if (i == vec.size() - 1) { cout << vec[i].w() << endl; } } } }; #endif //SHORTESTPATH_BELLMAN_FORD_H <file_sep>/SORT/QuickSort.h #ifndef QUICKSORT_H #define QUICKSORT_H #include <iostream> #include <ctime> #include <string> #include <cassert> #include "SortTestHelper.h" #include "InsertSort.h" using namespace std; namespace QuickSort { // 三路快速排序 l 左边界 r 有边界 array.length template <typename T> void threeWaySort(T arr[], int l, int r) { if (l >= r) return; // 随机一个 index, 防止 有序输入 退化为 N² 算法 swap(arr[l], arr[rand() % (r - l) + l]); // 需要维持的状态 // [44, 3, 7, 11, 15, 18, 44, 44, 44, 44, 15, 18, 87, 32, 47, 44, 99, 120, 111] // k →lt →i gt← sorting // k // lt i gt initialize int k = l, lt = l, i = l + 1, gt = r; while (i < gt) { if (arr[i] < arr[k]) { lt++; i++; } else if (arr[i] == arr[k]) { i++; } else if (arr[i] > arr[k]) { gt--; swap(arr[i], arr[gt]); } } swap(arr[k], arr[lt]); threeWaySort(arr, k, lt); threeWaySort(arr, gt, r); } template <typename T> int partitionII(T arr[], int l, int r) { // 随机一个 index, 防止 有序输入 退化为 N² 算法 swap(arr[l], arr[rand() % (r - l) + l]); // [7, 1, 1, 1, 2, 2, 3, 3, 3, 3, 8] 防止出现此种情况 // 从左右两边同时向中间遍历 // 左边 小于 arr[k], 右边大于 arr[k], 如此保证 等于 arr[k] 的元素 均匀分布于 数组两边 // [48, 2, 3, 5, 6, 54, 58, 77, 23, 24, 67, 18, 99, 120, 130, 133, 156, 214] // k → i j ← int k = l, i = l + 1, j = r - 1; while (true) { while (arr[i] < arr[k]) i++; while (arr[j] > arr[k]) j--; if (i >= j) break; swap(arr[i++], arr[j--]); // 程序始终维持上述状态 } swap(arr[k], arr[j]); return j; } // 此方法无法阻止 大量重复输入下 退化为 N² 算法 // [7, 1, 1, 1, 2, 2, 3, 3, 3, 3, 8] 防止出现此种情况 template <typename T> int partition(T arr[], int l, int r) { // 随机一个 index, 防止 有序输入 退化为 N² 算法 swap(arr[l], arr[rand() % (r - l) + l]); // [48, 2, 3, 5, 6, 54, 58, 77, 23, 24, 67, 18] // k j i // i 当前元素 // j 小于比较值的 最后一个边界, 大于 arr[k] 与 小于arr[k] 的分界索引 index // k 比较值索引 int i = l + 1, j = l, k = l; for (; i < r; i++) { if (arr[i] < arr[k]) { swap(arr[j + 1], arr[i]); j++; } } swap(arr[k], arr[j]); // 将比较值 放置到 j 的位置 return j; } template <typename T> void sort(T arr[], int l, int r) { // if(l >= r){ // return; // } if (r - l <= 15) { return InsortSort::insertSortArrayBoundary(arr, l, r - 1); } int mid = partitionII(arr, l, r); sort(arr, l, mid); sort(arr, mid + 1, r); } template <typename T> void quickSort(T arr[], int n) { srand(time(NULL)); // sort(arr, 0, n); threeWaySort(arr, 0, n); } } // namespace QuickSort #endif<file_sep>/UnionSet/CMakeLists.txt cmake_minimum_required(VERSION 3.15) project(unionSet_I) set(CMAKE_CXX_STANDARD 14) add_executable(unionSet_I main.cpp UnionFindI.h UnionFindTestHelper.h UnionFindII.h)<file_sep>/SORT/ShellSort.h #ifndef SHELLSORT_H #define SHELLSORT_H #include <iostream> #include <ctime> #include <string> #include <cassert> using namespace std; namespace ShellSort { template <typename T> void shellSort(T arr[], int n) { int h = 1; // 处理递增数列 while(h < n / 3) h = h * 3 + 1; // 插入排序 while(h >= 1){ for(int i = h; i < n; i++){ T curValue = arr[i]; int j; for(j = i; j >= h; j -= h){ if(curValue < arr[j - h]){ arr[j] = arr[j - h]; }else{ break; } } arr[j] = curValue; } h = h / 3; } } } // namespace InsortSort #endif<file_sep>/MST/LazyPrimMST.h // // Created by haruhi on 2020/4/6. // #ifndef GRAPH_LAZYPRIMMST_H #define GRAPH_LAZYPRIMMST_H #include <iostream> #include <cassert> #include <vector> #include "Edge.h" #include "SparseGraph.h" #include "DenseGraph.h" #include "MinimumHeap.h" using namespace std; // minimal spanning tree template<typename Graph, typename Weight> class LazyPrimMST { private: Graph &G; bool *visited; vector<Edge<Weight>> mst; MinHeap<Edge<Weight>> pq; // priority queue Weight mstWeight; void handler(int v) { assert(!visited[v]); visited[v] = true; typename Graph::adjIterator adj(G, v); for (Edge<Weight> *e = adj.begin(); !adj.end(); e = adj.next()) { if (!visited[e->other(v)]) pq.add(*e); } } public: LazyPrimMST(Graph &graph) : G(graph), pq(MinHeap<Edge<Weight>>(graph.E())) { visited = new bool[G.V()]; // init vertex whether visited for (int i = 0; i < G.V(); i++) { visited[i] = false; } mst.clear(); // traversal from vertex 0; handler(0); // get the min edge while (!pq.isEmpty()) { Edge<Weight> minEdge = pq.pop(); // judge whether the two vertexes on the minEdge is different side(color) if (visited[minEdge.v()] == visited[minEdge.w()]) { continue; } else { mst.push_back(minEdge); if (visited[minEdge.v()]) { handler(minEdge.w()); } else { handler(minEdge.v()); } } } cout << "Lzay MST: " << endl; for (int i = 0; i < mst.size(); i++) { cout << mst[i] << endl; } }; }; #endif //GRAPH_LAZYPRIMMST_H <file_sep>/List/main.cpp #include <iostream> #include <algorithm> #include "unionSeqList.h" using namespace std; int main() { int m = 10, n = 10; int first[m], second[n]; for (int i = 0; i < m; i++) { if (i % 2 == 0) first[i] = i + 1; else first[i] = i; } UnionSeqList::printArray(first, m); for (int i = 0; i < n; i++) { if (i % 3 == 0) second[i] = i + 3; else second[i] = i + 2; } UnionSeqList::printArray(second, n); int *unionedList = UnionSeqList::unionTowOrderedList(first, m, second, n); UnionSeqList::printArray(unionedList, m + n); return 0; }<file_sep>/UnionSet/UnionFindTestHelper.h // // Created by haruhi on 2020/3/29. // #ifndef UNIONSET_I_UNIONFINDTESTHELPER_H #define UNIONSET_I_UNIONFINDTESTHELPER_H #include <iostream> #include <ctime> #include "UnionFindI.h" #include "UnionFindII.h" #include "UnionFindIII.h" #include "UnionFindIV.h" #include "UnionFindV.h" // 为每个节点添加 子节点数量 属性, 平衡树高度 using namespace std; namespace UnionFindTestHelper { void testUFI(int n){ srand(time(NULL)); UFI::UnionFind uf = UFI::UnionFind(n); time_t startTime = clock(); for(int i = 0; i < n; i++){ int a = rand() % n; int b = rand() % n; uf.unionE(a, b); } for(int i = 0; i < n; i++){ int a = rand() % n; int b = rand() % n; uf.isConnected(a, b); } time_t endTime = clock(); cout << "UFI, " << 2 * n << " ops, " << double (endTime - startTime) / CLOCKS_PER_SEC << endl; } void testUFII(int n){ srand(time(NULL)); UFII::UnionFind uf = UFII::UnionFind(n); time_t startTime = clock(); for(int i = 0; i < n; i++){ int a = rand() % n; int b = rand() % n; uf.unionE(a, b); } for(int i = 0; i < n; i++){ int a = rand() % n; int b = rand() % n; uf.isConnected(a, b); } time_t endTime = clock(); cout << "UFII, " << 2 * n << " ops, " << double (endTime - startTime) / CLOCKS_PER_SEC << endl; } void testUFIII(int n){ srand(time(NULL)); UFIII::UnionFind uf = UFIII::UnionFind(n); time_t startTime = clock(); for(int i = 0; i < n; i++){ int a = rand() % n; int b = rand() % n; uf.unionE(a, b); } for(int i = 0; i < n; i++){ int a = rand() % n; int b = rand() % n; uf.isConnected(a, b); } time_t endTime = clock(); cout << "UFIII, " << 2 * n << " ops, " << double (endTime - startTime) / CLOCKS_PER_SEC << endl; } void testUFIV(int n){ srand(time(NULL)); UFIV::UnionFind uf = UFIV::UnionFind(n); time_t startTime = clock(); for(int i = 0; i < n; i++){ int a = rand() % n; int b = rand() % n; uf.unionE(a, b); } for(int i = 0; i < n; i++){ int a = rand() % n; int b = rand() % n; uf.isConnected(a, b); } time_t endTime = clock(); cout << "UFIV, " << 2 * n << " ops, " << double (endTime - startTime) / CLOCKS_PER_SEC << endl; } void testUFV(int n){ srand(time(NULL)); UFV::UnionFind uf = UFV::UnionFind(n); time_t startTime = clock(); for(int i = 0; i < n; i++){ int a = rand() % n; int b = rand() % n; uf.unionE(a, b); } for(int i = 0; i < n; i++){ int a = rand() % n; int b = rand() % n; uf.isConnected(a, b); } time_t endTime = clock(); cout << "UFV, " << 2 * n << " ops, " << double (endTime - startTime) / CLOCKS_PER_SEC << endl; } } #endif //UNIONSET_I_UNIONFINDTESTHELPER_H <file_sep>/Heap/HeapSort.h /* * @Author: <NAME> * @Date: 2020-03-19 21:46:58 * @LastEditTime: 2020-03-23 19:53:17 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: \algorithm\Heap\HeapSort.h */ #ifndef HEAPSORT_H #define HEAPSORT_H #include <iostream> #include <ctime> #include <string> #include <cassert> #include <math.h> #include "BinaryHeap.h" using namespace std; namespace HeapSort { /** * @description: a simple way to let a random arrary became a binary Heap * @param {type} * @return: */ template <typename T> MaxHeap<T> heapify(T arr[], int n) { // 1. make a random array become Heap array MaxHeap<T> maxheap = MaxHeap<T>(n); for (int i = 0; i < n; i++) { maxheap.insert(arr[i]); } return maxheap; } /** * 堆化 II * @description: 从第一个不是叶子节点的数组元素开始, shiftdown * @param {type} * @return: */ template <typename T> MaxHeap<T> heapifyII(T arr[], int n) { MaxHeap<T> maxheap = MaxHeap<T>(n); maxheap.assign(arr, n); // 获取第一个有 子节点的 父节点 int parentIndex = (maxheap.size() - 1 - 1) / 2; while(parentIndex >= 0){ maxheap.shiftDown(parentIndex); parentIndex--; } return maxheap; } template <typename T> T *heapSort(T items[], int n) { MaxHeap<T> maxheap = heapifyII(items, n); T *arr = new T[n]; for (int i = 0; i < n; i++) { arr[i] = maxheap.extractMax(); } return arr; } void test() { MaxHeap<int> maxheap = MaxHeap<int>(100); srand(time(NULL)); for (int i = 0; i < 24; i++) { maxheap.insert(rand() % 90 + 10); } maxheap.printBinaryHeap(); cout << endl; cout << "size:" << maxheap.size() << endl; for (int i = 15; i > 0; i--) { cout << maxheap.extractMax() << endl; maxheap.printBinaryHeap(); } } } // namespace HeapSort #endif<file_sep>/Heap/BinaryHeap.h #ifndef BINARYHEAP_H #define BINARYHEAP_H #include <iostream> #include <ctime> #include <string> #include <cassert> #include <math.h> template <typename Item> class MaxHeap { private: Item *data; int count; Item left(int k) { return data[2 * k + 1]; }; Item right(int k) { return data[2 * k + 2]; }; Item parent(int k) { return data[(k - 1) / 2]; }; /** * 加入元素,上移 * k data数组下标,表示当前要 shiftUp 的元素索引位置 **/ void shiftUp(int k) { while (this->data[k] > parent(k) && k > 0) { swap(this->data[k], this->data[(k - 1) / 2]); k = (k - 1) / 2; } } void printItem(Item item, int pad, int fix) { for (int i = 0; i < pad; i++) { cout << " "; } cout << item; // 元素自身长度修正 // if(item % 10 < 10){ // pad -= 1; // } for (int i = 0; i < pad; i++) { cout << " "; } } public: MaxHeap(int capacity) { this->data = new Item[capacity + 1]; count = 0; } ~MaxHeap() { delete[] this->data; } // remain the properies of heap when heap top element poped // k is the index of element which need to be move to keep the heap properities void shiftDown(int k) { // 1. judge the parent whether has left child node, if not have, stop shift down while (k < count && 2 * k + 1 < count) { // the integer k represent the index , which current should be swap with k index, // default is left child node index int j = 2 * k + 1; // 2. determine whether have right node if (j + 1 < count && data[j] < data[j + 1]) { // 3. where there is a right child node, and right child node value bigger than left child node value // then set j index become right child node index j = j + 1; // now index j persent the biggerst one of the children nodes index } // 4. determine whether the value of the parent node is bigger than that of the right child node if (data[k] > data[j]) break; // 5. shift down between parent node and the biggest one of the children nodes swap(data[k], data[j]); k = j; } } int size() { return count; } bool isEmpty() { return count == 0; } void printBinaryHeap() { // 1.计算树高度 int height = 0, itemNumber = size(); while ((itemNumber >>= 1) > 0) { height++; } cout << "height:" << height << endl; // 2.循环创建每层数据 // 2.1 最底层树的数量为 2 的 height 次方 - 1 int maxLeafLength = pow(2, height + 2) - 1; // 2.2 当前层元素间隔 int currentLevelPaddingLength = (maxLeafLength - 1) / 2; for (int i = 0, index = 0 /*元素数组计数*/; i <= height; i++) { // 2.3 开始打印每行 int currentLevelItemNum = pow(2, i); while (currentLevelItemNum-- > 0 && index < size()) { printItem(this->data[index++], currentLevelPaddingLength, (height + 1 - i)); } // 2.4 计算下一层 padding currentLevelPaddingLength = (currentLevelPaddingLength - 1) / 2; cout << endl; } } void insert(Item item) { this->data[count] = item; this->shiftUp(count); count++; } // pops up the heap top element Item extractMax() { if (count > 0) { Item result = data[0]; data[0] = data[count - 1]; count--; shiftDown(0); return result; } return 0; } Item* values(){ return data; } void assign(Item item[], int n){ this->data = item; this->count = n; } }; // int main(){ // MaxHeap<int> maxheap = MaxHeap<int>(100); // srand(time(NULL)); // for(int i = 0; i < 24; i++){ // maxheap.insert(rand() % 90 + 10); // } // maxheap.printBinaryHeap(); // cout << endl; // cout << "size:" << maxheap.size() << endl; // for(int i = 15; i > 0; i--){ // cout << maxheap.extractMax() << endl; // maxheap.printBinaryHeap(); // } // return 0; // } #endif<file_sep>/SORT/ReverseAlignment.h #ifndef REVERSEALIGNMENT_H #define REVERSEALIGNMENT_H #include <iostream> #include <ctime> #include <string> #include <cassert> #include "SortTestHelper.h" #include "InsertSort.h" using namespace std; // 逆序对 // 利用分治归并 过程 在每个归并过程中 一次性找到 小于自己的所有元素,计数 namespace ReverseAlignment { template <typename T> int merge(T arr[], int l, int m, int r) { int reverseAlignment = 0; // 辅助数组 aux T aux[r - l + 1]; // 复制 arr[l ... r] to aux[0 ... r-l] for(int i = l; i <= r; i++){ aux[i - l] = arr[i]; } // aux // 左数组左边界 左数组右边界 右数组左边界 右数组右边界 int ls = 0, le = m - l, rs = m - l + 1, re = r - l; int index = 0; while(index <= re){ if(ls > le){ arr[index + l] = aux[rs]; rs++; }else if(rs > re){ arr[index + l] = aux[ls]; ls++; }else if(aux[ls] < aux[rs]){ arr[index + l] = aux[ls]; ls++; }else if(aux[ls] >= aux[rs]){ reverseAlignment += re - rs + 1; arr[index + l] = aux[rs]; rs++; } index++; } return reverseAlignment; } template <typename T> int split(T arr[], int l, int r) { int result = 0; if (l >= r) return 0; int mid = l + (r - l) / 2; result += split(arr, l, mid); result += split(arr, mid + 1, r); result += merge(arr, l, mid, r); return result; } template <typename T> void reverseAlignment(T arr[], int n){ int result = split(arr, 0, n - 1); cout << "reverseAlignment:" << result; } } // namespace ReverseAlignment #endif<file_sep>/MST/KruskalMST.h // // Created by haruhi on 2020/4/11. // #ifndef MST_KRUSKALMST_H #define MST_KRUSKALMST_H #include <iostream> #include <cassert> #include <vector> #include "Edge.h" #include "SparseGraph.h" #include "DenseGraph.h" #include "MinimumIndexHeap.h" #include "UnionFind.h" template<typename Graph, typename Weight> class KruskalMST { private: vector<Edge<Weight>> mst; public: KruskalMST(Graph &graph) { MinIndexHeap<Edge<Weight>> ipq(graph.E()); // sort all edge by weight for (int i = 0; i < graph.V(); i++) { typename Graph::adjIterator adj(graph, i); for (Edge<Weight> *e = adj.begin(); !adj.end(); e = adj.next()) { if (e->w() < e->v()) { ipq.add(*e); } } } UnionFind uf(graph.V()); // every time, chose the least weight edge, add to mst // if the vertex on the edge not form a loop(not connected), it must be the edge of mst while (!ipq.isEmpty() && mst.size() < graph.V() - 1) { // sort and get min edge Edge<Weight> minEdge = ipq.pop(); // judge the two points on edge whether connected before add to mst if (!uf.isConnected(minEdge.w(), minEdge.v())) { uf.unionElements(minEdge.w(), minEdge.v()); mst.push_back(minEdge); } } cout << "Kruskal MST: " << endl; for (int i = 0; i < mst.size(); i++) { cout << mst[i] << endl; } } }; #endif //MST_KRUSKALMST_H <file_sep>/SORT/main.cpp #include <iostream> #include <algorithm> #include "SortTestHelper.h" #include "InsertSort.h" #include "SelectionSort.h" #include "BubbleSort.h" #include "ShellSort.h" #include "MergeSort.h" #include "MergeSortBU.h" #include "QuickSort.h" #include "ReverseAlignment.h" #include "heap/HeapSort.h" using namespace std; const int SAMPLE = 1000000; int main() { int n = 100; // int* arr = SortTestHelper::generateNearlyOrderedArray(n, 20 ); // int* arr = SortTestHelper::generateRandomArray(n, 0, 20); // int* arr1 = SortTestHelper::copyIntArray(arr, n); // int* arr2 = SortTestHelper::copyIntArray(arr, n); // int* arr3 = SortTestHelper::copyIntArray(arr, n); // int* arr4 = SortTestHelper::copyIntArray(arr, n); // int* arr5 = SortTestHelper::copyIntArray(arr, n); // int* arr6 = SortTestHelper::copyIntArray(arr, n); // SortTestHelper::testSort("Selection Sort", SelectionSort::selectionSort, arr, n); // SortTestHelper::testSort("Insert Sort", InsortSort::insertSortFastVersion, arr1, n); // SortTestHelper::testSort("Bubble Sort", BubbleSort::bubbleSort, arr2, n); // SortTestHelper::testSort("Shell Sort", ShellSort::shellSort, arr3, n); // SortTestHelper::testSort("Merge Sort", MergeSort::mergeSort, arr4, n); // SortTestHelper::testSort("Merge Sort BU", MergeSortBU::mergeSort, arr5, n); // SortTestHelper::testSort("Quick Sort", QuickSort::quickSort, arr6, n); // SortTestHelper::printArray(arr6, n); // delete[] arr; // delete[] arr1; // int arr[4] = {8, 7, 6, 5}; // ReverseAlignment::reverseAlignment(arr, 4); int* arr = SortTestHelper::generateRandomArray(n, 0, n); arr = HeapSort::heapSort(arr, n); SortTestHelper::printArray(arr, n); system("pause"); return 0; }<file_sep>/UnionSet/UnionFindIII.h // // Created by haruhi on 2020/3/29. // #ifndef UNIONSET_III_UNIONFINDII_H #define UNIONSET_III_UNIONFINDII_H #include <iostream> #include <assert.h> // QuickUnion using namespace std; namespace UFIII { /* * 每个节点都有一个指针指向父节点,根节点指向自己 * [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] index * [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 父节点 index * [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 每个节点下孩子数 */ class UnionFind { private: int *parent; int *size; int count; public: UnionFind(int n) { this->count = n; this->size = new int[n]; this->parent = new int[n]; for (int i = 0; i < n; i++) { this->parent[i] = i; this->size[i] = 1; } } ~UnionFind() { delete[] this->parent; } // 获取根节点 int find(int index) { assert(index >= 0 && index < this->count); while (index != this->parent[index]) index = this->parent[index]; } // 判断两个节点的根节点是否相等 bool isConnected(int p, int q) { int pRoot = this->find(p); int qRoot = this->find(q); return pRoot == qRoot; } // 讲一个节点的根节点挂载到另一个节点根节点下 void unionE(int p, int q) { int pRoot = this->find(p); int qRoot = this->find(q); if (pRoot == qRoot) return; if (this->size[pRoot] < this->size[qRoot]) { this->parent[pRoot] = qRoot; this->size[qRoot] += this->size[pRoot]; }else if(this->size[qRoot] < this->size[pRoot]){ this->parent[qRoot] = pRoot; this->size[pRoot] += this->size[qRoot]; }else{ this->parent[qRoot] = pRoot; this->size[pRoot] += this->size[qRoot]; } } }; } #endif //UNIONSET_III_UNIONFINDII_H <file_sep>/Graph/SparseGraph.h // // Created by haruhi on 2020/3/31. // #ifndef GRAPH_SPARSEGRAPH_H #define GRAPH_SPARSEGRAPH_H #include <iostream> #include <vector> #include <cassert> using namespace std; class SparseGraph { private: int n, // vertex num m; // edge num bool directed; // whether the graph has direction bool *marked; vector<vector<int>> g; public: SparseGraph(int n, bool directed) { this->n = n; this->m = 0; this->directed = directed; this->marked = new bool[n]; for (int i = 0; i < n; i++) { g.push_back(vector<int>()); this->marked[i] = false; } } ~SparseGraph() {} int V() { return this->n; } int E() { return this->m; } void addEdge(int v, int w) { // 允许有平行边 // if (this->hasEdge(v, w)) // return; assert(v >= 0 && v < this->n); assert(w >= 0 && w < this->n); g[v].push_back(w); if (v != w && !directed) g[w].push_back(v); m++; } bool hasEdge(int v, int w) { assert(v >= 0 && v < this->n); assert(w >= 0 && w < this->n); for (int i = 0; i < this->g[v].size(); i++) if (g[v][i] == w) return true; return false; } vector<int> adj(int v) { assert(v >= 0 && v < this->n); return this->g[v]; } void DFS(int v) { assert(v >= 0 && v < n); cout << v << endl; this->marked[v] = true; for (int i = 0; i < g[v].size(); i++) { if (!this->marked[this->g[v][i]]) DFS(this->g[v][i]); } } void showInfo(SparseGraph &graph) { cout << "SparseGraph:" << endl; for (int v = 0; v < V(); v++) { SparseGraph::adjIterator it(graph, v); cout << "vertex " << v << " : "; for (int w = it.begin(); !it.end(); w = it.next()) cout << w << " "; cout << endl; } cout << endl; } class adjIterator { private: SparseGraph &G; int v; int index; public: adjIterator(SparseGraph &graph, int v) : G(graph) { this->index = 0; this->v = v; } int begin() { this->index = 0; if (this->G.g[v].size() > 0) return this->G.g[v][index]; return -1; } int next() { this->index++; if (this->index < this->G.g[this->v].size()) return this->G.g[this->v][this->index]; return -1; } bool end() { return this->index >= this->G.g[this->v].size(); } }; }; #endif //GRAPH_SPARSEGRAPH_H <file_sep>/ShortestPath/SparseGraph.h // // Created by haruhi on 2020/3/31. // #ifndef GRAPH_SPARSEGRAPH_H #define GRAPH_SPARSEGRAPH_H #include <iostream> #include <vector> #include <cassert> #include "Edge.h" using namespace std; template<typename Weight> class SparseGraph { private: int n, // vertex num m; // edge num bool directed; // whether the graph has direction bool *marked; vector<vector<Edge<Weight> *>> g; // vector<vector<>> g; public: SparseGraph(int n, bool directed) { this->n = n; this->m = 0; this->directed = directed; this->marked = new bool[n]; for (int i = 0; i < n; i++) { g.push_back(vector<Edge<Weight> *>()); this->marked[i] = false; } } ~SparseGraph() {} int V() { return this->n; } int E() { return this->m; } void addEdge(int v, int w, Weight weight) { assert(v >= 0 && v < this->n); assert(w >= 0 && w < this->n); // 允许有平行边 if (this->hasEdge(v, w)) return; // g[v].push_back(w); g[v].push_back(new Edge<Weight>(v, w, weight)); if (v != w && !directed) g[w].push_back(new Edge<Weight>(w, v, weight)); m++; } bool hasEdge(int v, int w) { assert(v >= 0 && v < this->n); assert(w >= 0 && w < this->n); for (int i = 0; i < this->g[v].size(); i++) if (g[v][i]->other(v) == w) return true; return false; } // get all of the vertex that adjacent to a vertex {v}, return a point list vector<Edge<Weight> *> adj(int v) { assert(v >= 0 && v < this->n); return this->g[v]; } void showInfo(SparseGraph &graph) { cout << "SparseGraph:" << endl; for (int v = 0; v < V(); v++) { SparseGraph::adjIterator it(graph, v); cout << "vertex " << v << ":\t"; for (Edge<Weight> *w = it.begin(); !it.end(); w = it.next()) cout << "(to:" << w->w() << ",wt:" << w->wt() << ")\t"; cout << endl; } cout << endl; } class adjIterator { private: SparseGraph &G; int v; int index; public: adjIterator(SparseGraph &graph, int v) : G(graph) { this->index = 0; this->v = v; } Edge<Weight> *begin() { this->index = 0; if (this->G.g[v].size() > 0) return this->G.g[v][index]; return NULL; } Edge<Weight> *next() { this->index++; if (this->index < this->G.g[this->v].size()) return this->G.g[this->v][this->index]; return NULL; } bool end() { return this->index >= this->G.g[this->v].size(); } }; }; #endif //GRAPH_SPARSEGRAPH_H <file_sep>/MST/PrimMST.h // // Created by haruhi on 2020/4/11. // #ifndef MST_PRIMMST_H #define MST_PRIMMST_H #include <iostream> #include <cassert> #include <vector> #include "Edge.h" #include "SparseGraph.h" #include "DenseGraph.h" #include "MinimumIndexHeap.h" template<typename Graph, typename Weight> class PrimMST { private: Graph &G; // index priority queue, every index represent a vertex in graph, value is edge weight, edge is v -> ? // weight [0.1, 0.2, 0.3, 0.4, 0.6, 0.19] minIndexHeap values // ipq [ 0, 1, 2, 3, 4, 5] minIndexHeap indexs MinIndexHeap<Weight> ipq; bool *visited; // record whether the vertex visited visited[vertex] // record the vertex's min edge, for example 0 -> 1 , edgeTo[0] represent edge 0 to 1 vector<Edge<Weight> *> edgeTo; vector<Edge<Weight>> mst; // minimal spanning tree Weight minWeight; void handler(int v) { // determine whether the point(vertex) has been visited assert(!visited[v]); visited[v] = true; // initialize iterator to iterator points which connected with point v typename Graph::adjIterator adj(G, v); for (Edge<Weight> *e = adj.begin(); !adj.end(); e = adj.next()) { // the edge other vertex not red color int other_v = e->other(v); if (!visited[other_v]) { // save e to edgeTo // judge whether the other_v's relate edge has been pushed to edgeTo if (!edgeTo[other_v]) { edgeTo[other_v] = e; ipq.insert(other_v, e->wt()); // judge whether the pushed edge's weight less than current edge weight e->wt() } else if (e->wt() < edgeTo[other_v]->wt()) { edgeTo[other_v] = e; ipq.update(other_v, e->wt()); } } } } public: PrimMST(Graph &graph) : G(graph), ipq(MinIndexHeap<Weight>(graph.V())) { visited = new bool[graph.V()]; for (int i = 0; i < graph.V(); i++) { visited[i] = false; edgeTo.push_back(NULL); } mst.clear(); // handler PrimMST handler(0); while (!ipq.isEmpty()) { int min_index = ipq.popIndex(); assert(edgeTo[min_index]); mst.push_back(*edgeTo[min_index]); handler(min_index); } cout << "MST: " << endl; for (int i = 0; i < mst.size(); i++) { cout << mst[i] << endl; } } }; #endif //MST_PRIMMST_H <file_sep>/ShortestPath/Dijkstra.h // // Created by SuzumiyaHaruhi on 2020/4/15. // #ifndef SHORTESTPATH_DIJKSTRA_H #define SHORTESTPATH_DIJKSTRA_H #include <iostream> #include <vector> #include <stack> #include <cassert> #include "Edge.h" #include "SparseGraph.h" #include "DenseGraph.h" #include "UnionFind.h" #include "MinimumIndexHeap.h" // single source shortest path template<typename Graph, typename Weight> class Dijkstra { private: int s; // start point Graph &G; // graph bool *visited; // record whether the point visited Weight *distTo; // the weight of s to every point (include self) minimal weight, represent by array // the shortest path to [index] point, the value represent last shortest edge to [index] point, vector<Edge<Weight> *> from; public: Dijkstra(Graph &graph, int s) : G(graph) { this->s = s; visited = new bool[graph.V()]; distTo = new Weight[graph.V()]; MinIndexHeap<Weight> ipq(graph.V()); for (int i = 0; i < graph.V(); i++) { visited[i] = false; distTo[i] = Weight(); from.push_back(NULL); } // start visited[s] = true; distTo[s] = Weight(); ipq.insert(s, distTo[s]); while (!ipq.isEmpty()) { int v = ipq.popIndex(); visited[v] = true; // Relaxation typename Graph::adjIterator adj(graph, v); // traversal the points adjacent to v for (Edge<Weight> *e = adj.begin(); !adj.end(); e = adj.next()) { int w = e->other(v); if (!visited[w]) { if (from[w] == NULL || distTo[v] + e->wt() < distTo[w]) { distTo[w] = distTo[v] + e->wt(); from[w] = e; if (ipq.containIndex(w)) { ipq.update(w, distTo[w]); } else { ipq.insert(w, distTo[w]); } } } } } } ~Dijkstra() { delete[] visited; delete[] distTo; } Weight shortestPathTo(int w) { return distTo[w]; } bool hasPathTo(int w) { return visited[w]; } void shortestPath(int w, vector<Edge<Weight>> &vec) { stack<Edge<Weight> *> s; Edge<Weight> *e = from[w]; while (e != NULL) { s.push(e); e = from[e->v()]; } while (!s.empty()) { e = s.top(); vec.push_back(*e); s.pop(); } } void showPath(int w) { assert(w >= 0 && w < G.V()); vector<Edge<Weight>> vec; shortestPath(w, vec); for (int i = 0; i < vec.size(); i++) { cout << vec[i].v() << " -> "; if (i == vec.size() - 1) { cout << vec[i].w() << endl; } } } }; #endif //SHORTESTPATH_DIJKSTRA_H <file_sep>/SORT/BubbleSort.h #ifndef BUBBLESORT_H #define BUBBLESORT_H #include <iostream> #include <ctime> #include <string> #include <cassert> using namespace std; namespace BubbleSort { template <typename T> void bubbleSort(T arr[], int n) { for(int i = 0; i < n; i++){ int minIndex = i; for(int j = i; j < n; j++){ if(arr[j] < arr[minIndex]) minIndex = j; } swap(arr[i], arr[minIndex]); } } } // namespace InsortSort #endif<file_sep>/ShortestPath/UnionFind.h // // Created by haruhi on 2020/4/11. // #ifndef MST_UNIONFIND_H #define MST_UNIONFIND_H #include <iostream> #include <cassert> using namespace std; // quick union class UnionFind { private: // [2, 2, 2, 3, 2, 2] ids value the value represent parent id index in ids // [0, 1, 2, 3, 4, 5] ids index the index can represent any thing such as vertex number or etc int *ids; int n; // ids length // this array every element represent the distance between current index of element in ids and it's root int *height; int find(int x) { while (ids[x] != x) { x = ids[x]; } return x; } public: UnionFind(int n) { this->n = n; this->ids = new int[n]; this->height = new int[n]; for (int i = 0; i < n; i++) { // initialize ids, every node's parent node is itself ids[i] = i; height[i] = 0; } } bool isConnected(int a, int b) { assert(a >= 0 && a < n); assert(b >= 0 && b < n); return find(a) == find(b); } void unionElements(int a, int b) { assert(a >= 0 && a < n); assert(b >= 0 && b < n); if (height[a] > height[b]) { ids[find(b)] = find(a); } else { ids[find(a)] = find(b); } } }; #endif //MST_UNIONFIND_H <file_sep>/Graph/main.cpp #include <iostream> #include <ctime> #include <string> #include "DenseGraph.h" #include "SparseGraph.h" #include "ReadGraph.h" #include "Component.h" #include "Path.h" #include "ShortestPath.h" int main() { // int N = 20; // int M = 100; // bool directed = true; // // srand(time(NULL)); // // // SparseGraph // SparseGraph g1(N, directed); // for (int i = 0; i < M; i++) { // int a = rand() % N; // int b = rand() % N; // g1.addEdge(a, b); // } // // for (int v = 0; v < N; v++) { // cout << v << " : "; // SparseGraph::adjIterator adj(g1, v); // for (int w = adj.begin(); !adj.end(); w = adj.next()) // cout << w << " "; // cout << endl; // } string filename01 = "graph01.txt"; string filename02 = "graph02.txt"; SparseGraph g1(13, false); ReadGraph<SparseGraph> readGraph1(g1, filename02); Component<SparseGraph> component1(g1); Path<SparseGraph> path1(g1, 0); ShortestPath<SparseGraph> shortestPath1(g1, 0); g1.showInfo(g1); DenseGraph g2(6, false); ReadGraph<DenseGraph> readGraph2(g2, filename01); Component<DenseGraph> component2(g2); g2.showInfo(g2); cout << filename02 << " component count:" << component1.component() << endl; cout << filename01 << " component count:" << component2.component() << endl; cout << "7 & 12 is connected:" << component1.isConnected(7, 12) << endl; cout << endl << "DFS : "; path1.showPath(6); cout << endl << "BFS : "; shortestPath1.showPath(6); cout << "length between 0 & 6: " << shortestPath1.length(6) << endl; return 0; } <file_sep>/Graph/ShortestPath.h // // Created by haruhi on 2020/4/6. // #ifndef GRAPH_SHORTESTPATH_H #define GRAPH_SHORTESTPATH_H #include <iostream> #include <cassert> #include <stack> #include <vector> #include <queue> using namespace std; // this class can be use to calculate shortest path in unweighted graph template<typename Graph> class ShortestPath { private: Graph &G; int s; // start vertex, means from s to v bool *visited; int *from; // from[index] = value, index is current vertex, value is pre vertex int *ord; // the distance between current vertex {v} and source vertex {s} void dfs(int v) { assert(v >= 0 && v < G.V()); visited[v] = true; // mark the visited vertex typename Graph::adjIterator adj(G, v); for (int i = adj.begin(); !adj.end(); i = adj.next()) { if (!visited[i]) { from[i] = v; // record the per vertex dfs(i); // deep first search } } } void bfs(int rVertex) { assert(rVertex >= 0 && rVertex < G.V()); visited[rVertex] = true; ord[rVertex] = 0; queue<int> prepareToIter; prepareToIter.push(rVertex); while(!prepareToIter.empty()){ int v = prepareToIter.front(); prepareToIter.pop(); typename Graph::adjIterator adj(G, v); // iterator vertex v for(int i = adj.begin(); !adj.end(); i = adj.next()){ if(!visited[i]){ from[i] = v; // record the pre vertex visited[i] = true; // whether visited ord[i] = ord[v] + 1; // calculate distance prepareToIter.push(i); } } } } public: /** * @param s source origin vertex */ ShortestPath(Graph &graph, int s) : G(graph) { assert(s >= 0 && s < graph.V()); visited = new bool[graph.V()]; from = new int[graph.V()]; ord = new int[graph.V()]; for (int i = 0; i < graph.V(); i++) { visited[i] = false; from[i] = -1; ord[i] = -1; } this->s = s; // shortest path search by bfs(breadth-first search) bfs(s); } ~ShortestPath() { delete[] visited; delete[] from; } bool hasPath(int w) { assert(w >= 0 && w < G.V()); return visited[w]; } void path(int w, vector<int> &vec) { assert(w >= 0 && w < G.V()); stack<int> ss; int p = w; while (p != -1) { ss.push(p); p = from[p]; } vec.clear(); while (!ss.empty()) { vec.push_back(ss.top()); ss.pop(); } } void showPath(int w) { vector<int> vec; path(w, vec); for (int i = 0; i < vec.size(); i++) { cout << vec[i]; if (i == vec.size() - 1) { cout << endl; } else { cout << " -> "; } } } // return the distance between source vertex {s} and target/current vertex {v} int length(int w){ assert(w >= 0 && w < G.V()); return ord[w]; } }; #endif //GRAPH_SHORTESTPATH_H <file_sep>/Heap/MinimumHeap.h // // Created by haruhi on 2020/4/7. // #ifndef MINIMUMHEAP_H #define MINIMUMHEAP_H #include <iostream> #include <cassert> #include <vector> using namespace std; // min heap template<typename Node> class MinHeap { private: Node *nodes; // heap elements array int limit; // the position that next node will be placed, it also represents the array boundary int length; // the heap array initialize length void shiftUp(int pos) { if (pos > 0 && pos <= limit) { int par_pos = (pos - 1) / 2; if (nodes[pos] < nodes[par_pos]) { swap(nodes[pos], nodes[par_pos]); shiftUp(par_pos); } } } void shiftDown(int pos) { if (pos < limit && pos * 2 + 1 < limit) { int left_child_pos = pos * 2 + 1; int right_child_pos = left_child_pos + 1; int cur_min_val_pos = left_child_pos; if (right_child_pos < limit && nodes[right_child_pos] < nodes[left_child_pos]) { cur_min_val_pos = right_child_pos; } if (nodes[pos] < nodes[cur_min_val_pos]) return; swap(nodes[cur_min_val_pos], nodes[pos]); shiftDown(cur_min_val_pos); } } // return index of element node in heap array nodes int find(Node node) { for (int i = 0; i < limit; i++) { if (nodes[i] == node) { return i; } } return -1; } void print(vector<int> &v) { for (int &i : v) { if (i < limit) cout << nodes[i] << " "; } cout << endl; } public: MinHeap(int n) { this->limit = 0; this->length = n; this->nodes = new Node[n]; } // get top element in heap Node pop() { assert(limit >= 0); Node ret = nodes[0]; // remember first element in heap array limit--; // limit -- swap(nodes[limit], nodes[0]); // swap end element and first element in heap array shiftDown(0); // keep heap property return ret; } void add(Node node) { // put the element in array end, then shift up, find the appropriate position assert(limit < length); nodes[limit] = node; // put the node to heap array[limit] shiftUp(limit); // keep heap property limit++; // limit ++ } // someone who want to del node, use this method void del(Node node) { int del_index = find(node); if (del_index >= 0 && del_index < limit) { limit--; swap(nodes[limit], nodes[del_index]); shiftUp(del_index); shiftDown(del_index); } } // someone who want to del the ith node in nodes, it equals nodes[i] void delByIndex(int del_index) { if (del_index >= 0 && del_index < limit) { limit--; swap(nodes[limit], nodes[del_index]); shiftUp(del_index); shiftDown(del_index); } } // update node by index void update(int udp_index, Node udp_node) { if (udp_index >= 0 && udp_index < limit) { nodes[udp_index] = udp_node; shiftUp(udp_index); shiftDown(udp_index); } } bool isEmpty() { return limit == 0; } void show() { // level sequence traversal cout << "Min Heap:" << endl; vector<int> par_s; int par_pos = 0; par_s.push_back(par_pos); while (!par_s.empty()) { print(par_s); vector<int> next_pars; for (int par_ : par_s) { par_pos = par_; int left_child_pos = par_pos * 2 + 1; int right_child_pos = left_child_pos + 1; if (left_child_pos < limit) next_pars.push_back(left_child_pos); if (right_child_pos < limit) next_pars.push_back(right_child_pos); } par_s = next_pars; } } }; #endif //MINIMUMHEAP_H <file_sep>/Graph/DenseGraph.h // // Created by haruhi on 2020/3/31. // #ifndef GRAPH_DENSEGRAPH_H #define GRAPH_DENSEGRAPH_H #include <iostream> #include <vector> #include <cassert> using namespace std; class DenseGraph { private: int n, // vertex num m; // edge num bool directed; // whether the edge has direction bool *marked; vector<vector<bool>> g; public: DenseGraph(int n, bool directed) { this->n = n; this->m = 0; this->directed = directed; this->marked = new bool[n]; for (int i = 0; i < n; i++) { this->marked[i] = false; g.push_back(vector<bool>(n, false)); } } ~DenseGraph() {} int V() { return this->n; } int E() { return this->m; } /** * add a edge to graph * @param v cross axis index * @param w vertical axis index */ void addEdge(int v, int w) { if (this->hasEdge(v, w)) return; this->g[v][w] = true; if (!this->directed) this->g[w][v] = true; this->m++; } bool hasEdge(int v, int w) { assert(v >= 0 && v < n); assert(w >= 0 && w < n); return this->g[v][w]; } // vector<int> adj(int v) { assert(v >= 0 && v < n); vector<int> ret = vector<int>(); for (int i = 0; i < n; i++) { if (this->g[v][i]) ret.push_back(i); else if (this->g[i][v]) ret.push_back(i); } return ret; } // deep first search void DFS(int v) { assert(v >= 0 && v < this->n); cout << v << endl; this->marked[v] = true; for (int i = 0; i < n; i++) if (this->g[v][i] && v != i && !this->marked[i]) { DFS(i); return; } } void showInfo(DenseGraph &graph) { cout << "DenseGraph:" << endl; cout << " "; for(int x = 0; x < V(); x++) cout << " " << x; cout << endl; for(int x = 0; x < V(); x++){ cout << x << " "; for(int y = 0; y < V(); y++){ cout << (int) this->g[x][y] << " "; } cout << endl; } cout << endl; } class adjIterator { private: DenseGraph &G; int v; int index; public: adjIterator(DenseGraph &graph, int v) : G(graph) { this->index = -1; this->v = v; } int begin() { this->index = -1; return next(); } int next() { for (index += 1; index < this->G.V(); index++) { if (this->G.g[v][index]) return index; } return -1; } bool end() { return this->index >= this->G.V(); } }; }; #endif //GRAPH_DENSEGRAPH_H <file_sep>/MST/cmake-build-debug/CMakeFiles/MST.dir/cmake_clean.cmake file(REMOVE_RECURSE "CMakeFiles/MST.dir/main.cpp.obj" "MST.exe" "MST.exe.manifest" "MST.pdb" "libMST.dll.a" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/MST.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/Heap/main.cpp /* * @Author: <NAME> * @Date: 2020-03-19 21:46:58 * @LastEditTime: 2020-03-23 19:54:40 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: \algorithm\main.cpp */ #include <iostream> #include <algorithm> #include "MinimumHeap.h" #include "MinimumIndexHeap.h" using namespace std; int main() { int n = 30000; MinHeap<int> heapIndex = MinHeap<int>(n); MinIndexHeap<int> minIndexHeap = MinIndexHeap<int>(n); for(int i = 20; i >= 0; i--){ heapIndex.add(i); minIndexHeap.add(i); } heapIndex.show(); minIndexHeap.show(); minIndexHeap.showNodes(); minIndexHeap.showIndexes(); cout << endl; // for(int i = 20; i > 5; i--){ //// heapIndex.del(i); // heapIndex.del(i); // minIndexHeap.del(i); // } heapIndex.del(0); minIndexHeap.delByIndex(20); heapIndex.show(); minIndexHeap.show(); minIndexHeap.showNodes(); minIndexHeap.showIndexes(); return 0; }<file_sep>/UnionSet/main.cpp #include <iostream> #include <assert.h> #include "UnionFindTestHelper.h" using namespace std; int main() { int n = 1000000; // UnionFindTestHelper::testUFI(n); // UnionFindTestHelper::testUFII(n); UnionFindTestHelper::testUFIII(n); UnionFindTestHelper::testUFIV(n); UnionFindTestHelper::testUFV(n); return 0; } <file_sep>/SORT/helloworld.cpp #include <iostream> #include <vector> #include <string> #include "SortTestHelper.h" using namespace std; int main() { int n = 10000; int *arr = SortTestHelper::generateRandomArray(n, 0, n); SortTestHelper::printArray(arr, n); delete[] arr; return 0; }<file_sep>/Graph/Component.h // // Created by SuzumiyaHaruhi on 2020/4/3. // #ifndef GRAPH_COMPONENT_H #define GRAPH_COMPONENT_H #include <iostream> #include <string> #include <fstream> #include <sstream> #include <cassert> using namespace std; template<typename Graph> class Component { private: Graph &G; bool *visited; // a vertex whether visited int c_count; // connected component count in a graph int *identify; // marked different connected component by id, the vertex in same connected component have same identify void dfs(int v) { assert(v >= 0 && v < G.V()); visited[v] = true; // mark the visited vertex identify[v] = c_count; // assign same identify to the vertex in same connected component typename Graph::adjIterator adj(G, v); for (int i = adj.begin(); !adj.end(); i = adj.next()) { if (!visited[i]) dfs(i); // deep first search } } public: Component(Graph &graph) : G(graph) { visited = new bool[graph.V()]; identify = new int[graph.V()]; c_count = 0; for (int i = 0; i < graph.V(); i++) { visited[i] = false; identify[i] = -1; } for (int i = 0; i < graph.V(); i++) { if (!visited[i]) { dfs(i); c_count++; } } } // Connected Component int component() { return c_count; } // isConnected bool isConnected(int v, int w) { assert(v >= 0 && v < G.V()); assert(w >= 0 && w < G.V()); return identify[v] == identify[w]; } }; #endif //GRAPH_COMPONENT_H <file_sep>/Graph/Path.h // // Created by haruhi on 2020/4/6. // #ifndef GRAPH_PATH_H #define GRAPH_PATH_H #include <iostream> #include <cassert> #include <stack> #include <vector> using namespace std; template<typename Graph> class Path { private: Graph &G; int s; // start vertex, means from s to ? bool *visited; int *from; // from[index] = value, index is current vertex, value is pre vertex void dfs(int v) { assert(v >= 0 && v < G.V()); visited[v] = true; // mark the visited vertex typename Graph::adjIterator adj(G, v); for (int i = adj.begin(); !adj.end(); i = adj.next()) { if (!visited[i]) { from[i] = v; // record the per vertex dfs(i); // deep first search } } } public: /** * @param s source origin vertex */ Path(Graph &graph, int s) : G(graph) { assert(s >= 0 && s < graph.V()); visited = new bool[graph.V()]; from = new int[graph.V()]; for (int i = 0; i < graph.V(); i++) { visited[i] = false; from[i] = -1; } this->s = s; // path search dfs(s); } ~Path() { delete[] visited; delete[] from; } bool hasPath(int w) { assert(w >= 0 && w < G.V()); return visited[w]; } void path(int w, vector<int> &vec) { assert(w >= 0 && w < G.V()); stack<int> ss; int p = w; while (p != -1) { ss.push(p); p = from[p]; } vec.clear(); while (!ss.empty()) { vec.push_back(ss.top()); ss.pop(); } } void showPath(int w) { vector<int> vec; path(w, vec); for (int i = 0; i < vec.size(); i++) { cout << vec[i]; if (i == vec.size() - 1) { cout << endl; } else { cout << " -> "; } } } }; #endif //GRAPH_PATH_H
ca3450f425fbf6b6439c7831f4c5eeebba15c2e1
[ "CMake", "C++" ]
40
C++
laoniutoushx/algorithm
980cd64b3e392407ce01098109520fc609660e9d
fc06dc0670ecbc7052cf7542234981f1996aa414
refs/heads/master
<file_sep># Currently this path is appended to dynamically when picking a ruby version # zshenv has already started PATH with rbenv so append only here export PATH=$PATH~/bin:/usr/local/bin:/usr/local/sbin:~/bin:/opt/sublime_text # Set default console Java to 1.6 # export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home # Setup terminal, and turn on colors #export TERM=xterm-256color #export CLICOLOR=1 #export LSCOLORS=Gxfxcxdxbxegedabagacad # Enable color in grep export GREP_OPTIONS='--color=auto' export GREP_COLOR='3;33' #export LESS='--ignore-case --raw-control-chars' #export PAGER='less' export EDITOR='subl -w' # export NODE_PATH=/opt/github/homebrew/lib/node_modules # export PYTHONPATH=/usr/local/lib/python2.6/site-packages # CTAGS Sorting in VIM/Emacs is better behaved with this in place # export LC_COLLATE=C #export GH_ISSUE_CREATE_TOKEN=<KEY> # Virtual Environment Stuff # export WORKON_HOME=$HOME/.virtualenvs # export PROJECT_HOME=$HOME/Projects/django # source /usr/local/bin/virtualenvwrapper.sh <file_sep>myzsh ===== <file_sep># A shortcut function that simplifies usage of xclip. # - Accepts input from either stdin (pipe), or params. # Source: http://goo.gl/UX1rHF # ------------------------------------------------ cb() { local _scs_col="\e[0;32m"; local _wrn_col='\e[1;31m'; local _trn_col='\e[0;33m' # Check that xclip is installed. if ! type xclip > /dev/null 2>&1; then echo -e "$_wrn_col""You must have the 'xclip' program installed.\e[0m" # Check user is not root (root doesn't have access to user xorg server) elif [[ "$USER" == "root" ]]; then echo -e "$_wrn_col""Must be regular user (not root) to copy a file to the clipboard.\e[0m" else # If no tty, data should be available on stdin if ! [[ "$( tty )" == /dev/* ]]; then input="$(< /dev/stdin)" # Else, fetch input from params else input="$*" fi if [ -z "$input" ]; then # If no input, print usage message. echo "Copies a string to the clipboard." echo "Usage: cb <string>" echo " echo <string> | cb" else # Copy input to clipboard echo -n "$input" | xclip -selection c # Truncate text for status if [ ${#input} -gt 80 ]; then input="$(echo $input | cut -c1-80)$_trn_col...\e[0m"; fi # Print status. echo -e "$_scs_col""Copied to clipboard:\e[0m $input" fi fi } # Copy contents of a file function cbf() { cat "$1" | cb; } # Refresh ZSH config with F5 function refresh_config # Define the function { source ~/.zshrc # reloads the core zsh config source ~/.zsh/ # reloads the associated zsh modules printf ' .zshrc updated' #confirmation that function excuted zle accept-line # executes, effectively passes a return key event } zle -N refcon_widget refresh_config # Assign the function to the widget bindkey '5~' refcon_widget # 5~ is F5 key, this binds the widget # ------------------------------------------------------------------- # compressed file expander # (from https://github.com/myfreeweb/zshuery/blob/master/zshuery.sh) # ------------------------------------------------------------------- ex() { if [[ -f $1 ]]; then case $1 in *.tar.bz2) tar xvjf $1;; *.tar.gz) tar xvzf $1;; *.tar.xz) tar xvJf $1;; *.tar.lzma) tar --lzma xvf $1;; *.bz2) bunzip $1;; *.rar) unrar $1;; *.gz) gunzip $1;; *.tar) tar xvf $1;; *.tbz2) tar xvjf $1;; *.tgz) tar xvzf $1;; *.zip) unzip $1;; *.Z) uncompress $1;; *.7z) 7z x $1;; *.dmg) hdiutul mount $1;; # mount OS X disk images *) echo "'$1' cannot be extracted via >ex<";; esac else echo "'$1' is not a valid file" fi } # ------------------------------------------------------------------- # any function from http://onethingwell.org/post/14669173541/any # search for running processes # ------------------------------------------------------------------- any() { emulate -L zsh unsetopt KSH_ARRAYS if [[ -z "$1" ]] ; then echo "any - grep for process(es) by keyword" >&2 echo "Usage: any " >&2 ; return 1 else ps xauwww | grep -i --color=auto "[${1[1]}]${1[2,-1]}" fi } # ------------------------------------------------------------------- # display a neatly formatted path # ------------------------------------------------------------------- path() { echo $PATH | tr ":" "\n" | \ awk "{ sub(\"/usr\", \"$fg_no_bold[green]/usr$reset_color\"); \ sub(\"/bin\", \"$fg_no_bold[blue]/bin$reset_color\"); \ sub(\"/opt\", \"$fg_no_bold[cyan]/opt$reset_color\"); \ sub(\"/sbin\", \"$fg_no_bold[magenta]/sbin$reset_color\"); \ sub(\"/local\", \"$fg_no_bold[yellow]/local$reset_color\"); \ print }" } # ------------------------------------------------------------------- # Mac specific functions # ------------------------------------------------------------------- if [[ $IS_MAC -eq 1 ]]; then # view man pages in Preview pman() { ps=`mktemp -t manpageXXXX`.ps ; man -t $@ > "$ps" ; open "$ps" ; } # function to show interface IP assignments ips() { foo=`/Users/mark/bin/getip.py; /Users/mark/bin/getip.py en0; /Users/mark/bin/getip.py en1`; echo $foo; } # notify function - http://hints.macworld.com/article.php?story=20120831112030251 notify() { automator -D title=$1 -D subtitle=$2 -D message=$3 ~/Library/Workflows/DisplayNotification.wflow } fi # ------------------------------------------------------------------- # nice mount (http://catonmat.net/blog/another-ten-one-liners-from-commandlingfu-explained) # displays mounted drive information in a nicely formatted manner # ------------------------------------------------------------------- function nicemount() { (echo "DEVICE PATH TYPE FLAGS" && mount | awk '$2="";1') | column -t ; } # ------------------------------------------------------------------- # myIP address # ------------------------------------------------------------------- function myip() { ifconfig lo0 | grep 'inet ' | sed -e 's/:/ /' | awk '{print "lo0 : " $2}' ifconfig en0 | grep 'inet ' | sed -e 's/:/ /' | awk '{print "en0 (IPv4): " $2 " " $3 " " $4 " " $5 " " $6}' ifconfig en0 | grep 'inet6 ' | sed -e 's/ / /' | awk '{print "en0 (IPv6): " $2 " " $3 " " $4 " " $5 " " $6}' ifconfig en1 | grep 'inet ' | sed -e 's/:/ /' | awk '{print "en1 (IPv4): " $2 " " $3 " " $4 " " $5 " " $6}' ifconfig en1 | grep 'inet6 ' | sed -e 's/ / /' | awk '{print "en1 (IPv6): " $2 " " $3 " " $4 " " $5 " " $6}' } # ------------------------------------------------------------------- # (s)ave or (i)nsert a directory. # ------------------------------------------------------------------- s() { pwd > ~/.save_dir ; } i() { cd "$(cat ~/.save_dir)" ; } # ------------------------------------------------------------------- # console function # ------------------------------------------------------------------- function console () { if [[ $# > 0 ]]; then query=$(echo "$*"|tr -s ' ' '|') tail -f /var/log/system.log|grep -i --color=auto -E "$query" else tail -f /var/log/system.log fi } # ------------------------------------------------------------------- # shell function to define words # http://vikros.tumblr.com/post/23750050330/cute-little-function-time # ------------------------------------------------------------------- givedef() { if [[ $# -ge 2 ]] then echo "givedef: too many arguments" >&2 return 1 else curl "dict://dict.org/d:$1" fi }<file_sep># HISTORY HISTSIZE=10000 SAVEHIST=9000 HISTFILE=~/.zsh/.zsh_history<file_sep>alias lsa='ls -a' alias subl='sublime_text' alias ..='cd ..' alias subal='sublime_text ~/.zsh/aliases.zsh' alias z@zmail='ssh z@172.16.58.3' #apt-get alias alias agi="sudo apt-get install" alias agu="sudo apt-get update" alias agg="sudo apt-get update && sudo apt-get upgrade" alias agr="sudo apt-get remove" alias acs="sudo apt-cache search" # Aliases leveraging the cb() and cbf() functions # These are custom defined shell functions # ------------------------------------------------ # Copy SSH public key alias cbssh="cbf ~/.ssh/id_rsa.pub" # Copy current working directory alias cbwd="pwd | cb" # Copy most recent command in bash history alias cbhs="cat $HISTFILE | tail -n 1 | cb"
22bb4ddfe7bdae1944dd19b63cf9691b383e022d
[ "Markdown", "Shell" ]
5
Shell
thesprunk/myzsh
f88ab00f05b44f53c9286ac23493550593560f2a
6ae4de492da14b765b1f10679d1bffa96631c83e
refs/heads/main
<file_sep>const http = require('http') const Bot = require('node-telegram-bot-api') const {summary, allPrinciples} = require('./summary') const token = "<KEY>" const bot = new Bot(token, {polling: true}) const roundMatch = (max, min) => { return Math.round(min - 0.5 + Math.random() * (max - min + 1)) } const hours = 3 const principles = [ ['1. «Мир, как зеркало, отражает ваше отношение к нему»'], ['2. «Отражение формируется в единстве души и разума»'], ['3. «Дуальное зеркало реагирует с задержкой»'], ['4. «Зеркало просто констатирует содержание отношения, игнорируя его направленность»'], ['5. «Внимание должно быть зафиксировано на конечной цели, как будто она уже достигнута»'], ['6. «Отпустить свою хватку и позволить миру двигаться по течению вариантов»'], ['7. «Всякое отражение воспринимать как позитивное»']] http.createServer((request, response) => { console.log('request starting for '); console.log(request); bot.onText(/\/start/, function onStartText(msg) { const { id, first_name: userName } = msg.chat const opts = { reply_to_message_id: msg.message_id, reply_markup: JSON.stringify({ keyboard: principles }) }; bot.sendMessage(id, 'ПРИНЦИПЫ ТРАНСЕРФИНГА РЕАЛЬНОСТИ', opts); bot.sendMessage(id, `Добро пожаловать ${userName}!`) setInterval(() => { bot.sendMessage(id, summary[roundMatch(summary.length - 1, 0)]) }, (1000 * 60 * 60) * hours) }); bot.on('message', msg => { const { id } = msg.chat if(/test/gi.test(msg.text)) { setInterval(() => { bot.sendMessage(id, summary[roundMatch(summary.length - 1, 0)]) }, (1000 * 60 * 60) * hours) } if(/start/gi.test(msg.text)) { return } switch (msg.text) { case '1. «Мир, как зеркало, отражает ваше отношение к нему»': bot.sendMessage(id, allPrinciples[0]) break; case principles[1][0]: bot.sendMessage(id, allPrinciples[1]) break case principles[2][0]: bot.sendMessage(id, allPrinciples[2]) break case principles[3][0]: bot.sendMessage(id, allPrinciples[3]) break case principles[4][0]: bot.sendMessage(id, allPrinciples[4]) break case principles[5][0]: bot.sendMessage(id, allPrinciples[5]) break case principles[6][0]: bot.sendMessage(id, allPrinciples[6]) break case 'черный': break default: bot.sendMessage(id, 'Извините такой команды не существует...') bot.sendMessage(id, msg.text) break; } if(/Адиль черный/gi.test(msg.text)) { bot.sendSticker(id, 'CAACAgIAAxkBAAECl0tg8pGndFDpxClqPUXr9D5Iz-GOZwACuAADHEwXNf-uzxqylPi2IAQ') return } if(/<NAME>ый/gi.test(msg.text)) { bot.sendSticker(id, 'CAACAgIAAxkBAAECl7hg8v3YoJkp4D2EQMKQlajl00gPeAAC6wADHEwXNUzXJcLnYtk6IAQ') return } }) }).listen(process.env.PORT || 5000) console.log('Server running at http://127.0.0.1:5000/'); // bot.onText(/\/start/, function onStartText(msg) { // const { id, first_name: userName } = msg.chat // const opts = { // reply_to_message_id: msg.message_id, // reply_markup: JSON.stringify({ // keyboard: principles // }) // }; // bot.sendMessage(id, 'ПРИНЦИПЫ ТРАНСЕРФИНГА РЕАЛЬНОСТИ', opts); // bot.sendMessage(id, `Добро пожаловать ${userName}!`) // setInterval(() => { // bot.sendMessage(id, summary[roundMatch(summary.length - 1, 0)]) // }, (1000 * 60 * 60) * hours) // }); // bot.on('message', msg => { // const { id } = msg.chat // if(/test/gi.test(msg.text)) { // setInterval(() => { // bot.sendMessage(id, summary[roundMatch(summary.length - 1, 0)]) // }, (1000 * 60 * 60) * hours) // } // if(/start/gi.test(msg.text)) { // return // } // switch (msg.text) { // case '1. «Мир, как зеркало, отражает ваше отношение к нему»': // bot.sendMessage(id, allPrinciples[0]) // break; // case principles[1][0]: // bot.sendMessage(id, allPrinciples[1]) // break // case principles[2][0]: // bot.sendMessage(id, allPrinciples[2]) // break // case principles[3][0]: // bot.sendMessage(id, allPrinciples[3]) // break // case principles[4][0]: // bot.sendMessage(id, allPrinciples[4]) // break // case principles[5][0]: // bot.sendMessage(id, allPrinciples[5]) // break // case principles[6][0]: // bot.sendMessage(id, allPrinciples[6]) // break // case 'черный': // break // default: // bot.sendMessage(id, 'Извините такой команды не существует...') // bot.sendMessage(id, msg.text) // break; // } // if(/черный/gi.test(msg.text)) { // bot.sendSticker(id, 'CAACAgIAAxkBAAECl0tg8pGndFDpxClqPUXr9D5Iz-GOZwACuAADHEwXNf-uzxqylPi2IAQ') // return // } // })
14608107cf7a26b3485aba8a3ab20287fc81e299
[ "JavaScript" ]
1
JavaScript
Adil-web/transerfer_bot
d14860597d23998079cbd37492182b2bfe848a60
959b2d7a44f448bb99949657868f48db5f336a5e
refs/heads/master
<repo_name>benjaminPurdy/unrecognized-voices-ui<file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { CommonModule } from '@angular/common'; import {RouterModule, Routes} from '@angular/router'; import { AppComponent } from './app.component'; import { BannerComponent } from './banner/banner.component'; import { RepresentativesComponent } from './representatives/representatives.component'; import { BillsComponent } from './bills/bills.component'; import { BillGovernorComponent } from './bills/bill-governor/bill-governor.component'; import { BillLocationComponent } from './bills/bill-location/bill-location.component'; import { BillHouseComponent } from './bills/bill-house/bill-house.component'; import { RepHouseComponent } from './representatives/rep-house/rep-house.component'; import { RepLocationComponent } from './representatives/rep-location/rep-location.component'; import { RepGovernorComponent } from './representatives/rep-governor/rep-governor.component'; import { RepsApiService } from './services/reps-api.service'; import { BillsApiService } from './services/bills-api.service'; import { UsersApiService } from './services/users-api.service'; import { SharedService } from './services/shared.service'; import { AuthenticateComponent } from './authenticate/authenticate.component'; const APP_ROUTERS: Routes = [ { path: 'authenticate', component: AuthenticateComponent}, // { path: 'bills', redirectTo: '/bills/all'}, { path: 'bills/:section', component: BillsComponent }, // { path: 'representatives', redirectTo: '/representatives/all'}, { path: 'representatives/:section', component: RepresentativesComponent } ]; @NgModule({ declarations: [ AppComponent, BannerComponent, RepresentativesComponent, BillsComponent, BillGovernorComponent, BillLocationComponent, BillHouseComponent, RepHouseComponent, RepLocationComponent, RepGovernorComponent, AuthenticateComponent, ], imports: [ BrowserModule, FormsModule, HttpModule, CommonModule, RouterModule.forRoot(APP_ROUTERS, {enableTracing: true}), ], providers: [RepsApiService, BillsApiService, UsersApiService, SharedService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/bills/bills.component.ts import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-bills', templateUrl: './bills.component.html', styleUrls: ['./bills.component.less'] }) export class BillsComponent implements OnInit { section: String; constructor() { } ngOnInit() { console.log(this.section); } tabChange(tabName) { this.section = tabName; } } <file_sep>/src/app/authenticate/authenticate.component.ts import {Component} from '@angular/core'; import {Router} from '@angular/router'; import {AuthenticationService} from '../services/authentication-api.service'; @Component({ selector: 'app-authenticate', templateUrl: './authenticate.component.html', styleUrls: ['./authenticate.component.less'], providers: [AuthenticationService] }) export class AuthenticateComponent { localUser = { username: '', password: '' } constructor(private _service: AuthenticationService, private _router: Router) { } login() { this._service.login(this.localUser).then((res) => { if(res) this._router.navigate(['Dashboard']); else console.log(res); }) } clearfields() { this.localUser.username = ''; this.localUser.password = ''; } } <file_sep>/e2e/app.e2e-spec.ts import { UnrecognizedVoicesUiPage } from './app.po'; describe('unrecognized-voices-ui App', function() { let page: UnrecognizedVoicesUiPage; beforeEach(() => { page = new UnrecognizedVoicesUiPage(); }); it('should display message saying app works', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('app works!'); }); }); <file_sep>/src/app/representatives/rep-location/rep-location.component.ts import { Component, OnInit } from '@angular/core'; import { RepsApiService } from '../../services/reps-api.service'; import { SharedService } from '../../services/shared.service'; @Component({ selector: 'app-rep-location', templateUrl: './rep-location.component.html', styleUrls: ['./rep-location.component.less'] }) export class RepLocationComponent implements OnInit { private loaded: boolean = false; constructor(repsApiService: RepsApiService) { repsApiService.getRepresentativesSenate(SharedService.PAGE_ONE, SharedService.PAGE_SIZE_SMALL).subscribe( (data) => { this.loaded = true; console.log(data); }); } ngOnInit() { } } <file_sep>/src/app/services/reps-api.service.ts import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import { SharedService } from './shared.service'; @Injectable() export class RepsApiService { public baseUrl = 'http://localhost:8080'; private urlPath = "/representatives"; constructor(private _http: Http) { } getRepresentativesHouse(page: number, pageSize: number): Observable<any> { return SharedService.getPage(this.urlPath + "/house", page, pageSize, this._http); } getRepresentativesSenate(page: number, pageSize: number): Observable<any> { return SharedService.getPage(this.urlPath + "/senate", page, pageSize, this._http); } getRepresentative(uniqueId): Observable<any> { return SharedService.get(this.urlPath + "/" + uniqueId, this._http); } } <file_sep>/src/app/services/shared.service.ts import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Rx'; @Injectable() export class SharedService { public static PAGE_ONE: number = 1; public static PAGE_SIZE_SMALL: number = 3; public static PAGE_SIZE_LARGE: number = 10; public static BASE_URL: string = 'http://localhost:8080'; constructor() { } public static getPage(path, pageNumber, itemsPerPage, http): Observable<any> { return http.get(this.BASE_URL + path + "?page=" + pageNumber + "&pageSize=" + itemsPerPage); } public static get(path, http): Observable<any> { return http.get(this.BASE_URL + path); } } <file_sep>/src/app/services/bills-api.service.ts import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import { SharedService } from './shared.service'; @Injectable() export class BillsApiService { private urlPath = "/bills"; constructor(private _http: Http) { } getBillsHouse(page: number, pageSize: number): Observable<any> { return SharedService.getPage(this.urlPath + "/house", page, pageSize, this._http); } getBillsSenate(page: number, pageSize: number) { return SharedService.getPage(this.urlPath + "/senate", page, pageSize, this._http); } getBill(uniqueId) { return SharedService.get(this.urlPath + "/" + uniqueId, this._http); } }
47a184c4d1ff489ec1948a27e4adb48a9036ecd3
[ "TypeScript" ]
8
TypeScript
benjaminPurdy/unrecognized-voices-ui
0cc9541b162a20555312482ab3a902d73e199811
40efa88b1af0beed2ff38572ab9c84c47728865b
refs/heads/master
<file_sep># multibutton A custom Home Assistant Lovelace control for displaying multiple buttons in a card (such as various light brightness, fan speeds, or scenes). Each button will call a home assistant service with the specified data. If the entity matches the state of the button, it will be highlighted. It's intended to be very flexible, so configuration is rather advanced. ![multiswitch Example](https://github.com/grizzlyjere/multibutton/blob/master/Example-Lights.png) ## Instructions 1. In the `config/www` directory of Home Assistant, create a directory called `multibutton` 2. Save [multibutton.js](https://github.com/grizzlyjere/multibutton/raw/master/multibutton.js) in this new directory 3. In your `ui-lovelace.yaml` file, add this file to the resources section. It should look like this: ``` resources: - url: /local/multibutton/multibutton.js type: js ``` 4. Add the card to a view. The card type will be `custom:multi-button-switch`. See the examples section below for sample configurations ## Examples ### Light Dim States ![multibutton Example](https://github.com/grizzlyjere/multibutton/blob/master/Example-Lights.png) In this example, we want to show buttons for Full, Medium, Low, and Off light brightness states ``` - type: custom:multi-button-switch title: Livingroom Lights entity: light.livingroom_lights baseid: customlivingroom serviceDomain: light brightnessTolerance: 70 buttons: - name: "Full" service: "turn_on" serviceData: - brightness: 255 - name: "Medium" service: "turn_on" serviceData: - brightness: 110 - name: "Low" service: "turn_on" serviceData: - brightness: 30 - name: "Off" service: "turn_off" ``` ## Base Settings |Name|Type|Supported Values|Default|Description| |----|----|-------|-------|-----------| |type|string|custom:multi-button-switch|None|(Required) Card type| |title|string|n/a|None|(Required) Card title to display| |entity|string|n/a|None|(Optional) entity_id for this card| |baseid|string|n/a|`multibutton-[random number]-`|(Optional) Text to serve as the based for the HTML id of the component| |serviceDomain|string|(Any Home Assistant Service Domain)|None|(Required) Service domain to call (e.g. light, scene, fan, etc)| |brightnessTolerance|number|n/a|0|(Optional) Delta from the target brightness to be considered a match. I have some ZWave lights that don't report their final brightness for some time. This allows the current state to be highlighted if the value is close, but not exactly what you've specified| |buttons|object|n/a|None|(Required) See below for the structure of each option| ## Button Values / Definining Buttons Each item in the buttons section will be rendered as an on-screen button |Name|Type|Supported Values|Default|Description| |----|----|-------|-------|-----------| |Name|string|n/a|None|(Required) Button label| |service|string|(Any Home Assistant Service)|n/a|(Required) Service to call in the service domain specified previously. Typically `turn_on` or `turn_off`| |serviceData|object|n/a|None|(Optional) Any values specified will be included in the service call (such as fan speed, brightness, etc) ## TODO * Test and add examples for other service types (such as fan control) * Improved theme support * Ability to adjust styling from YAML * Code optimizations <file_sep>class MultiButtonSwitch extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); } set hass(hass) { this._hass = hass; this.setActiveButton(hass) } // Highlights the button which matches the current entity state setActiveButton(hass) { if (this.config.entity) { const entityId = this.config.entity; const state = hass.states[entityId]; const currentBrightness = state.attributes.brightness; // Loop through all specified buttons var i; for (i = 0; i < this.config.buttons.length; i++) { // Find the button HTML that should have been created var id = this.config.baseid + i; var elementSearchResults = this.shadowRoot.querySelectorAll("#" + id); var evaluateElement = elementSearchResults[0] // Default to consider the button a match to current state, // unless we determine otherwise var isMatch = true; // Check if this is a turn_on, turn_off, or other service type var actionType = ""; if (typeof this.config.buttons[i].service != 'undefined') { actionType = this.config.buttons[i].service; //console.log("Action Type: " + actionType); actionType = actionType.replace("turn_", ""); } // If we found the HTML for the button if (evaluateElement) { // TODO: Refactor this block. It's way to messy // Remove any active state classes, and reset to inactive evaluateElement.classList.add("multistate-button-inactive"); evaluateElement.classList.remove("multistate-button-active"); // Check the state (on/off) against the action type if (state.state != actionType) { isMatch = false; // If the button turns it off and the device is off, consider it a match } else if (state.state == "off" && actionType == "off") { isMatch = true; } else { // Compare the service data with the entity date if (this.config.buttons[i].serviceData) { var y; // Check each service data to make sure it matches for (var property in this.config.buttons[i].serviceData[0]) { if (property != "entity_id" && this.config.buttons[i].serviceData[0].hasOwnProperty(property)) { // console.log(property); // console.log(this.config.buttons[i].serviceData[0][property]) var propertyValue = this.config.buttons[i].serviceData[0][property]; // console.log(state.attributes); if (state.attributes[property]) { //console.log("CURRENT [" + property + "] : " + state.attributes[property]); //console.log("ELEMENT [" + property + "] : " + propertyValue); // If we're checking brightness compare a range based on the tolerance if (property == "brightness") { //console.log("LOW: " + (propertyValue - this.config.brightnessTolerance)) //console.log("HIGH: " + (propertyValue + this.config.brightnessTolerance) if (state.attributes[property] >= (propertyValue - this.config.brightnessTolerance) && state.attributes[property] <= (propertyValue + this.config.brightnessTolerance)) { //console.log("IN RANGE") //console.log("isMatch - Inner 1: " + isMatch); } else { //console.log("OUT OF RANGE") isMatch = false; } // Otherwise just check if the property state matches } else if (state.attributes[property] != propertyValue) { isMatch = false; } } else { isMatch = false; } } } } } if (isMatch) { evaluateElement.classList.remove("multistate-button-inactive"); evaluateElement.classList.add("multistate-button-active"); } } } } } // Handles the button press event onButtonClick(event) { // Get the button that was clicked var target = event.target || event.srcElement; // Get the button index which corresponds to the option data var selectedIndex = target.attributes.selectedIndex.value; // Get the option data for that index var optionData = this.getOptionData(selectedIndex); // Build the extra data to go with the service call var serviceData = {}; if (optionData.serviceData != null) { serviceData = optionData.serviceData[0]; } // Add the entity_id to the service call if specified if(this.config.entity) { serviceData.entity_id = this.config.entity; } // Call the specified service this._hass.callService(this.config.serviceDomain, optionData.service, serviceData); // Highlight the pressed button to provide visual feedback target.classList.remove("multistate-button-inactive"); target.classList.add("multistate-button-active"); } // Get the option data (specified in the YAML) for the specified index getOptionData(selectedIndex) { return this.config.buttons[selectedIndex]; } setConfig(config) { // Check for required parameters if (!config.serviceDomain) { throw new Error('"serviceDomain" not set'); } if (config.serviceDomain != "SCENE" && !config.entity) { throw new Error('"entity" Not Set'); } this.config = config; // Set default values if (this.config.brightnessTolerance == null) { this.config.brightnessTolerance = 0; } if(this.config.baseid == null) { this.config.baseid = "multibutton-" + Math.floor((Math.random() * 100) + 1) + "-"; } // Render the card const root = this.shadowRoot; if (root.lastChild) { root.removeChild(root.lastChild); } const card = document.createElement('ha-card'); card.header = this.config.title; const shadow = card.attachShadow({ mode: 'open' }); var content = document.createElement('div'); content.id = "multistate-card-content"; content.setAttribute("class", "multistate-card-content"); const style = document.createElement('style'); style.textContent = ` .multistate-button { border: solid 1px #7a7a7a; width: 92%; margin: 0px auto 10px auto; font-size: 1.8em; padding: 10px 5px 10px 5px; text-align: center; } .multistate-button-inactive { background-color: var(--secondary-background-color); } .multistate-button-active { background-color: var(--state-icon-active-color); } .multistate-card-content { padding: 10px 0px 10px 0px; } .header { margin-bottom: 0px !important; padding-bottom: 0px !important; } `; var outputHTML = ""; this.i = 0; // Create each button this.config.buttons.forEach(o => { const newButton = document.createElement('div'); var tempButton = ""; var id = ""; id = this.config.baseid + this.i; // Build the button newButton.id = id; newButton.setAttribute("name", id); newButton.setAttribute("selectedIndex", this.i); newButton.setAttribute("class", "multistate-button"); newButton.innerHTML = o.Name; // Attach the button to the DOM content.appendChild(newButton); // Create an event listener for the button newButton.addEventListener('click', event => { this.onButtonClick(event) }); this.i = this.i + 1; }); card.appendChild(content); card.appendChild(style); root.appendChild(card); } // The height of your card. Home Assistant uses this to automatically // distribute all cards over the available columns. getCardSize() { // TODO: Make dynamic return 6; } } customElements.define('multi-button-switch', MultiButtonSwitch);
31d257390e5387ca593d360e6ddcdbd4bf00489a
[ "Markdown", "JavaScript" ]
2
Markdown
grizzlyjere/multibutton
6a2bbdce285008777d063ac8875454ee6bac8fbb
8843e01f36c2bc2ccf6ab77fd4725e1e03004f5e
refs/heads/master
<repo_name>goubadiallo/js-deli-counter-js-apply-000<file_sep>/index.js function takeANumber(currentline, newname){ currentline.push(newname) return "Welcome, "+ newname + ". You are number " + currentline.length +" in line." } function nowServing(currentline){ if(currentline.length === 0) return "There is nobody waiting to be served!" var nextperson = currentline.shift() return "Currently serving " + nextperson + "." } function currentLine(line){ if(line.length === 0) return "The line is currently empty." var output = "The line is currently: " for(var i = 0; i<line.length; i++){ var name = line[i] var number = i+1 output = output + (number) + ". " + name if( i<line.length-1){ output = output + ", " } } return output }
e7eeaec381e3952ce411d0b2e6e4e39724facb3b
[ "JavaScript" ]
1
JavaScript
goubadiallo/js-deli-counter-js-apply-000
3686de81ab4fe7d1c620c5c24396e28a9a05f68a
d94a2d5e4a300aca622e3fe4171532ab56dceabe
refs/heads/master
<file_sep>app.controller('AddIdidController',function($scope,$state,ididStorage) { $scope.categories = ['Activities','Daily','Personal','Work']; $scope.newIdid = {category: "Activities"}; $scope.addIdid = function () { if($scope.newIdid.description) { ididStorage.addIdid({ category: $scope.newIdid.category, description: $scope.newIdid.description }); $scope.$emit('addIdid',$scope.newIdid); $scope.newIdid.description = ""; $state.go('idids'); } else { console.log("No description!"); } }; });<file_sep>var app = angular.module('ididApp', ['ionic','ui.router','ionic.utils']) .run(function($ionicPlatform,$localstorage) { $ionicPlatform.ready(function() { if(window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if(window.StatusBar) { StatusBar.styleDefault(); } if($localstorage.get('ididCount',0) == 0) { $localstorage.set('ididCount', 1); $localstorage.set('idids', []); } else { $localstorage.set('ididCount', parseInt($localstorage.get('ididCount')) + 1); } }); }) app.config(function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise("/"); $stateProvider .state('idids', { url: "/", templateUrl: "templates/idids.html" }) .state('addIdid', { url: "/idids/add", templateUrl: "templates/addIdid.html", controller: 'AddIdidController' }) })
61b826f34f7256483f1de21ca24353305d826cf9
[ "JavaScript" ]
2
JavaScript
AdJez/iDid
be948737649a7886fcf1cef67b89db35b49896dd
fbcf6aba578349a4e3b7020ea3ea10327eb01892
refs/heads/master
<repo_name>viniciusorejana/java-game<file_sep>/src/br/ufms/facom/lpoo/rpg/controle/Controle.java package br.ufms.facom.lpoo.rpg.controle; import br.ufms.facom.lpoo.rpg.personagem.Personagem; import br.ufms.facom.lpoo.rpg.personagem.Posicao; import br.ufms.facom.lpoo.rpg.personagem.Soldado; import br.ufms.facom.lpoo.rpg.ui.RolePlayingGame; /** * Controle do jogo: personagens e suas interações. * <p> * O intuito desta implementação é apenas exemplificar o uso dos principais * métodos da classe de interface: <code>RolePlayingGame</code>. A implementação * apresentada aqui não condiz com os requisitos do trabalho (apenas um tipo de * personagem (<code>Soldado</code>) e um tipo de arma (<code>Faca</code>) são * implementados aqui). Apenas dois personagens (do mesmo tipo) são adicionados * ao tabuleiro e a interação entre eles não respeita as regras do trabalho. * * @author eraldo * */ public class Controle { /** * Interface gráfica do jogo. Fornece métodos de entrada e saída. */ private RolePlayingGame rpg; /** * Um personagem. */ private Soldado sold1; /** * Outro personagem. */ private Soldado sold2; /** * Cria um objeto de controle que usa o objeto <code>rpg</code> como * interface com o usuário. * * @param rpg * interface gráfica da aplicação. */ public Controle(RolePlayingGame rpg) { this.rpg = rpg; // Cria um personagem em um canto do tabuleiro e outro em outro canto. sold1 = new Soldado("Sold1", 0, 0); sold2 = new Soldado("Sold2", RolePlayingGame.MAX_X - 1, RolePlayingGame.MAX_Y - 1); // Adiciona os dois personagens ao tabuleiro. rpg.addPersonagem(sold2); rpg.addPersonagem(sold1); } /** * Executa um turno do jogo. Este método é invocado pelo interface gráfica * continuamente, enquanto a aplicação estiver rodando. * <p> * A implementação apresentada é apenas um exemplo que não condiz com os * requisitos do trabalho. O turno implementado é muito simples. Cada * jogador pode mover-se (sem restrições) e atacar o outro jogador. Nenhuma * restrição é verificada com relação à velocidade do personagem, alcance * das armas, pontos de vida, teste de habilidade, etc. * * @throws InterruptedException * Exceção lançada quando a aplicação é encerrada pelo usuário. * O controle do jogo é executado em uma thread separada da * thread principal da aplicação. Esta exceção é lançada para * permitir o encerramento da thread de controle quando ela está * esperando uma resposta da interface com relação a uma ação do * usuário (selecionar personagem ou posição). O tratamento * desta exceção é realizado pela classe da aplicação * (<code>RolePlayingGame</code>). Esta exceção não deve ser * capturada aqui. */ public void executaTurno() throws InterruptedException { /* * Exibe mensagem avisando que o usuário precisa selecionar a posição do * personagem 1. */ rpg.info(String.format("Personagem %s, selecione sua nova posição!", sold1.getNome())); /* * Solicita uma casa do tabuleiro à interface. O usuário deverá * selecionar (clicando com o mouse) em uma casa do tabuleiro. As * coordenadas desta casa serão retornadas em um objeto Posicao * (coordenadas x e y). */ Posicao pos = rpg.selecionaPosicao(); // Altera a posição do personagem 1. sold1.setX(pos.x); sold1.setY(pos.y); /* * Solicita à interface que o tabuleiro seja atualizado, pois a posição * do personagem pode ter sido alterada. */ rpg.atualizaTabuleiro(); /* * Exibe mensagem avisando que o usuário precisa selecionar um oponente * a ser atacado pelo personagem 1. */ rpg.info(String.format("Personagem %s, selecione um inimigo para atacar!", sold1.getNome())); /* * Solicita um personagem à interface. O usuário deverá selecionar um * personagem no tabuleiro (clicando com o mouse sobre o personagem). */ Personagem p = rpg.selecionaPersonagem(); /* * A única validação realizada é se o personagem não o mesmo que está * atacando. Entretanto, no trabalho, diversas validações são * necessárias. */ if (p != sold1) p.setVida(p.getVida() - 1); else rpg.erro("Você não pode atacar você mesmo! Perdeu a vez."); /* * Solicita à interface que o tabuleiro seja atualizado, pois os pontos * de vida de um personagem podem ter sido alterados. */ rpg.atualizaTabuleiro(); /* * Abaixo, as mesmas operações realizadas com o personagem 1 são * realizadas com o personagem 2. */ rpg.info(String.format("Personagem %s, selecione sua nova posição!", sold2.getNome())); pos = rpg.selecionaPosicao(); sold2.setX(pos.x); sold2.setY(pos.y); rpg.atualizaTabuleiro(); rpg.info(String.format("Personagem %s, selecione um inimigo para atacar!", sold2.getNome())); p = rpg.selecionaPersonagem(); if (p != sold2) p.setVida(p.getVida() - 1); else rpg.erro("Você não pode atacar você mesmo! Perdeu a vez."); rpg.atualizaTabuleiro(); } } <file_sep>/README.md # simplerpg Framework for developing simple RPGs. <file_sep>/src/br/ufms/facom/lpoo/rpg/arma/Faca.java package br.ufms.facom.lpoo.rpg.arma; /** * Implementa uma arma: faca. * <p> * Esta implementação é apenas um exemplo que não segue as especificações do * trabalho. * * @author eraldo * */ public class Faca implements Arma { @Override public int getAlcance() { return 0; } }
b39bb24b39a9690a8a9499d1fba3523edcb3f4e1
[ "Markdown", "Java" ]
3
Java
viniciusorejana/java-game
ec0fe7459ebf89c9f2e98212151a0501d9600aa3
58d43944bd703a4de4fe23608ca68ca4200eb70d
refs/heads/master
<repo_name>GabrielSSRibeiro/Proffy-mobile<file_sep>/src/pages/GiveClasses/styles.js import { StyleSheet } from "react-native"; // import globalStyles from "../../styles/global"; const styles = StyleSheet.create({ container: { backgroundColor: "#8257E5", flex: 1, justifyContent: "center", padding: 40, }, content: { flex: 1, justifyContent: "center", }, title: { fontFamily: "Archivo_700Bold", color: "#fff", fontSize: 32, lineHeight: 37, maxWidth: 180, }, description: { marginTop: 24, color: "#d4c2ff", fontSize: 16, lineHeight: 26, fontFamily: "Poppins_400Regular", maxWidth: 240, }, okButton: { marginVertical: 40, backgroundColor: "#04d361", height: 58, alignItems: "center", justifyContent: "center", borderRadius: 8, }, okButtonText: { color: "#fff", fontSize: 16, fontFamily: "Archivo_700Bold", }, }); export default styles; <file_sep>/src/utils/convertWeekDayToNumber.js export default function convertWeekDayToNumber(weekDay) { return weekDay; } <file_sep>/src/pages/GiveClasses/index.js import React from "react"; import { Text, View, ImageBackground } from "react-native"; import { RectButton } from "react-native-gesture-handler"; import { useNavigation } from "@react-navigation/native"; import giveClassesBgIamge from "../../assets/images/give-classes-background.png"; import styles from "./styles"; function GiveClasses() { const { goBack } = useNavigation(); function HandleNavigateBack() { goBack(); } return ( <View style={styles.container}> <ImageBackground source={giveClassesBgIamge} resizeMode="contain" style={styles.content}> <Text style={styles.title}>Quer ser um Proffy?</Text> <Text style={styles.description}> Para começar, você precisa se cadastrar como professor na nossa plataforma web. </Text> </ImageBackground> <RectButton onPress={HandleNavigateBack} style={styles.okButton}> <Text style={styles.okButtonText}>Tudo bem</Text> </RectButton> </View> ); } export default GiveClasses; <file_sep>/App.js import React from "react"; import { StatusBar } from "expo-status-bar"; import AppLoading from "expo-app-loading"; import { useFonts, Archivo_400Regular, Archivo_700Bold } from "@expo-google-fonts/archivo"; import { Poppins_400Regular, Poppins_600SemiBold } from "@expo-google-fonts/poppins"; import AppStack from "./src/routes/appStack"; export default function App() { const [fontsLoaded] = useFonts({ Archivo_400Regular, Archivo_700Bold, Poppins_400Regular, Poppins_600SemiBold, }); return !fontsLoaded ? ( <AppLoading /> ) : ( <> <StatusBar style="light" /> <AppStack /> </> ); } // expo install expo-app-loading <file_sep>/src/pages/Landing/index.js import React, { useState, useEffect } from "react"; import { View, Image, Text, TouchableOpacity } from "react-native"; import { useNavigation } from "@react-navigation/native"; import { RectButton } from "react-native-gesture-handler"; import api from "../../services/api"; import landingImg from "../../assets/images/landing.png"; import studyIcon from "../../assets/images/icons/study.png"; import giveClassesIcon from "../../assets/images/icons/give-classes.png"; import heartIcon from "../../assets/images/icons/heart.png"; import styles from "./styles"; function Landing() { const { navigate } = useNavigation(); const [totalConnections, setTotalConnections] = useState(0); function HandleNavigateToGiveClasses() { navigate("GiveClasses"); } function HandleNavigateToStudy() { navigate("Study"); } useEffect(() => { api.get("connections").then((response) => { const { total } = response.data; setTotalConnections(total); }); }, []); return ( <View style={styles.container}> <Image source={landingImg} style={styles.banner} /> <Text style={styles.title}> Seja bem-vindo, {"\n"} <Text style={styles.titleBold}>O que deseja fazer?</Text> </Text> <View style={styles.buttonsContainer}> <RectButton style={[styles.button, styles.buttonPrimary]} onPress={HandleNavigateToStudy}> <Image source={studyIcon} /> <Text style={styles.buttonText}>Estudar</Text> </RectButton> <RectButton style={[styles.button, styles.buttonSecondary]} onPress={HandleNavigateToGiveClasses} > <Image source={giveClassesIcon} /> <Text style={styles.buttonText}>Dar Aulas</Text> </RectButton> </View> <Text style={styles.totalConnections}> Total de {totalConnections} conexões já realizadas. <Image source={heartIcon} /> </Text> </View> ); } export default Landing; <file_sep>/src/components/TeacherItem/index.js import React, { useState } from "react"; import { Image, Text, View, Linking } from "react-native"; import { RectButton } from "react-native-gesture-handler"; import AsyncStorage from "@react-native-async-storage/async-storage"; import api from "../../services/api"; import heartOutlineIcon from "../../assets/images/icons/heart-outline.png"; import unfavoriteIcon from "../../assets/images/icons/unfavorite.png"; import whatsappIcon from "../../assets/images/icons/whatsapp.png"; import styles from "./styles"; function TeacherItem({ teacher, favorited }) { const [isFavorited, setIsFavorited] = useState(favorited); async function handleLinkToWhatsapp() { await api.post("connections", { user_id: teacher.id }); Linking.openURL(`whatsapp://send?text=Hello World!&phone=${teacher.whatsappIcon}`); } async function handleToggleFavorite() { const favorites = await AsyncStorage.getItem("favorites"); let favoritesArray = []; if (favorites) { favoritesArray = JSON.parse(favorites); } if (isFavorited) { const favoriteIndex = favoritesArray.findIndex( (teacherItem) => teacherItem.id === teacher.id ); favoritesArray.splice(favoriteIndex, 1); setIsFavorited(false); } else { favoritesArray.push(teacher); setIsFavorited(true); } await AsyncStorage.setItem("favorites", JSON.stringify(favoritesArray)); } return ( <View style={styles.container}> <View style={styles.profile}> <Image style={styles.avatar} source={{ uri: teacher.avatar }} /> <View style={styles.profileInfo}> <Text style={styles.name}>{teacher.name}</Text> <Text style={styles.subject}>{teacher.subject}</Text> </View> </View> <Text style={styles.bio}>{teacher.bio}</Text> <View style={styles.footer}> <Text styles={styles.price}> Preço/hora <Text style={styles.priceValue}>R$ {teacher.cost}</Text> </Text> <View style={styles.buttonsContainer}> <RectButton style={[styles.favoriteButton, isFavorited ? styles.favorited : {}]} onPress={handleToggleFavorite} > {isFavorited ? <Image source={unfavoriteIcon} /> : <Image source={heartOutlineIcon} />} </RectButton> <RectButton style={styles.contactButton} onPress={handleLinkToWhatsapp}> <Image source={whatsappIcon}></Image> <Text style={styles.contactButtonText}>Entrar em contanto</Text> </RectButton> </View> </View> </View> ); } export default TeacherItem; <file_sep>/src/pages/Favorites/index.js import React, { useState } from "react"; import { ScrollView, View } from "react-native"; import { useFocusEffect } from "@react-navigation/native"; import AsyncStorage from "@react-native-async-storage/async-storage"; import PageHeader from "../../components/PageHeader"; import TeacherItem from "../../components/TeacherItem"; import styles from "./styles"; function Favorites() { const [favorites, setFavorites] = useState([]); function loadFavorites() { AsyncStorage.getItem("favorites").then((response) => { if (response) { const favoritedTeachers = JSON.parse(response); setFavorites(favoritedTeachers); } }); } useFocusEffect(() => { loadFavorites(); }); return ( <View style={styles.container}> <PageHeader title="Meus proffys favoritos" /> <ScrollView style={styles.teacherList} contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 16, }} > {favorites.map((teacher) => ( <TeacherItem key={teacher.id} teacher={teacher} favorited /> ))} </ScrollView> </View> ); } export default Favorites;
23a676588524efbbf884f3b95fb6f1927045a500
[ "JavaScript" ]
7
JavaScript
GabrielSSRibeiro/Proffy-mobile
a1ed3d7c1de777fd8034b3b415f3ac1ae28250a6
d8ee82371f9ea29dfc01bb57fd6dfd2103d4a4bf
refs/heads/master
<repo_name>cmannix/NLog.StructuredLogging.Json<file_sep>/src/NLog.StructuredLogging.Json.Tests/LoggingException.cs using System; namespace NLog.StructuredLogging.Json.Tests { public class LoggingException : Exception { public LoggingException() { } public LoggingException(string message) : base(message) { } } }
9b57816ef2e241b95a376ee49c117851e471e0a2
[ "C#" ]
1
C#
cmannix/NLog.StructuredLogging.Json
f183f950cfd2de357165f550d1c4ed6c2b6ca247
80b6283ffe766143a9d6b837f5f45f7b32a090db
refs/heads/master
<repo_name>isaacampah222/alma_api<file_sep>/alma_api/models.py from django.db import models class Order_List(models.Model): customer_id=models.CharField(max_length=10) customer_name= models.CharField(max_length=100) single_order_value = models.CharField(max_length=250) def __str__(self): return self.customer_id<file_sep>/alma_api/apps.py from django.apps import AppConfig class AlmaApiConfig(AppConfig): name = 'alma_api' <file_sep>/alma_api/admin.py from django.contrib import admin from .models import Order_List # Register your models here. admin.site.register(Order_List)<file_sep>/alma_api/views.py from django.shortcuts import render from rest_framework import status, mixins,viewsets from rest_framework.response import Response from rest_framework import generics from .serializers import orderListSerializer from .models import Order_List class orderlistView(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin,mixins.CreateModelMixin): serializer_class = orderListSerializer queryset = Order_List.objects.all() class genericOrderView(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin): serializer_class = orderListSerializer queryset = Order_List.objects.all() def get(self,request): return self.list(request) def post(self,request): return self.create(request) # Create your views here. <file_sep>/alma_api/urls.py from django.urls import path, include from .views import orderlistView, genericOrderView from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('order',orderlistView,basename='order') urlpatterns = [ path('viewset/', include(router.urls)), # path('order/',orderlistView.as_view()) path('generic/view/', genericOrderView.as_view()) ]<file_sep>/requirements.txt whitenoise django gunicorn django-heroku django-rest-framework <file_sep>/alma_api/serializers.py from rest_framework import serializers from .models import Order_List class orderListSerializer(serializers.ModelSerializer): class Meta: model = Order_List fields = ['customer_id','customer_name','single_order_value']
1570014cad4cf8c156fb9e6d068bef4865dc5cfc
[ "Python", "Text" ]
7
Python
isaacampah222/alma_api
a47b41ba62adc9b7372cacabf58b81d5e8269ad3
2938b29b9a1ce103bcf48168c6e69c474b046a96
refs/heads/master
<file_sep>module.exports = function(sequelize, DataTypes) { var Calculation = sequelize.define("Calculation", { Calc: DataTypes.STRING, createdAt: { type: DataTypes.DATE, defaultValue: sequelize.NOW }, updatedAt: { type: DataTypes.DATE, defaultValue: sequelize.NOW } }); return Calculation; }; <file_sep>var express = require("express"); var router = express.Router(); var db = require("../models/"); router.get("/", function(req, res){ db.Calculation.findAll().then(function(calcs){ console.log(calcs) res.send(calcs); }) }) router.get("/create/:calc", function(req, res) { console.log(req.params.calc) // create SQL table entry for Calculation db.Calculation.create({ Calc: req.params.calc }) // pass the result of our call .then(function(dbcalc) { // log the result to our terminal/bash window db.Calculation.findAll().then(function(calcs){ console.log(calcs[0].dataValues) res.send(calcs); }) }); }); module.exports = router;<file_sep>use calculations_db; INSERT into Calculations (Calc, createdAt, updatedAt) VALUES ("1+1=3?", now(), now()), ("2+2=4", now(), now()); SELECT * FROM Calculations;
60278ae2a5bc4707acb1c9a593c05f8ec0e807cf
[ "JavaScript", "SQL" ]
3
JavaScript
mitburr/SezzleCalculator
3a1a67747625c64f70f88dd55d49ccf817dbb84d
a17b450c11b8298c9135b224241b26fd9f9b58b0
refs/heads/main
<repo_name>fukuda1233/Plataforma-de-Jogos<file_sep>/README.md # Plataforma-de-Jogos Plataforma de Jogos, Trabalho de java, <NAME>, <NAME>, <NAME>. <file_sep>/Plataforma de Jogos/src/Genero/Acao.java package Genero; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Acao { public String opcaojogo2; public Acao() throws FileNotFoundException { File arquivo2 = new File("C:\\_ws\\Plataforma de Jogos\\Acao.csv"); Scanner acao = new Scanner(arquivo2); while(acao.hasNextLine()) { System.out.println(acao.nextLine()); } System.out.println("-- Quais Jogos vocÍ gostaria de comprar --"); Scanner opcao2 = new Scanner(System.in); opcaojogo2 = opcao2.nextLine(); System.out.println("Seu Carrinho - " + opcaojogo2); } } <file_sep>/Plataforma de Jogos/src/Genero/Genero.java package Genero; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Genero { public Genero() throws FileNotFoundException { System.out.println("-- Qual Genero você está procurando --"); System.out.println(" 1 - Ação - 2 - Esportes - 3 - Aventura "); Scanner opcao = new Scanner(System.in); int escolha; escolha = opcao.nextInt(); switch(escolha) { case 1: System.out.println("1 - Ação "); System.out.println("----------------------------------------"); Acao s22 = new Acao(); break; case 2: System.out.println("2 - Esportes "); System.out.println("----------------------------------------"); Esportes s23 = new Esportes(); break; case 3: System.out.println("3 - Aventura "); System.out.println("----------------------------------------"); Aventura s24 = new Aventura(); break; default: System.out.println("Opção Invalida"); } opcao.close(); } } <file_sep>/Plataforma de Jogos/src/Add_Jogos/Add_jogos.java package Add_Jogos; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Add_jogos { public Add_jogos() throws IOException { File arquivo5 = new File("C:\\_ws\\Plataforma de Jogos\\Jogos.csv"); Scanner jogos2 = new Scanner(arquivo5); String fileContent = "1 Minecraft - ;60.99"; while(jogos2.hasNextLine()) { fileContent = fileContent.concat(jogos2.nextLine() + "\n"); } FileWriter writer = new FileWriter("C:\\_ws\\Plataforma de Jogos\\Jogos_New.csv"); writer.write(fileContent); writer.close(); File arquivo6 = new File("C:\\_ws\\Plataforma de Jogos\\Jogos_New.csv"); Scanner jogos3 = new Scanner(arquivo6); while(jogos3.hasNextLine()) { System.out.println(jogos3.nextLine()); } System.out.println("---- Jogo Adicionado ----"); } }
249bff09111530d394be96bedafd48594451a67a
[ "Markdown", "Java" ]
4
Markdown
fukuda1233/Plataforma-de-Jogos
9895a9af3d0ab365f43c04e283f17e4fec97fe89
2ec0fb9521105c143896d08b3c4f4c28f137048a
refs/heads/master
<repo_name>paulocesarml/SA<file_sep>/src/br/com/sa/entity/Caixa.java package br.com.sa.entity; public class Caixa { private int codigo; private String id; public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
edc392a2f9b7e67829a1ef9732d7fe1b5b3356dc
[ "Java" ]
1
Java
paulocesarml/SA
c913a3c0faf801dc4abb79537758559996ec0a39
8d7ca9ed2a0ca4b97ead1e555d8af94f75cdd00e
refs/heads/develop
<repo_name>bafiam/WEATHER-APP<file_sep>/README.md # WEATHER-APP DOM manipulation by dynamically rendering a simple weather forecast site using the weather API.The goal of the project is to show the understanding of the asynchronous communication with promises or async/await. ## Screenshots ### Home ![screenshot](weather.png) ### Search ![screenshot](weather-app.png) ## Built With - Javascript(ES6) - Webpack - NodeJs ## Live Demo [Live link](https://rawcdn.githack.com/bafiam/WEATHER-APP/feature/weather_app/dist/index.html) ## Prerequisites - Webpack v4.43.0 - npm ## Functionalities - Default city that shows its weather forecast - Search bar to input a city name - auto-suggest city name on type - Display selected city weather forecast ## Setup Use the [git](https://git-scm.com/downloads) to clone the project to your local machine. ```sh $ git clone https://github.com/bafiam/WEATHER-APP.git ``` Navigate to the extracted folder ```sh cd WEATHER-APP ``` Install the dependencies and modules ```sh $ npm install ``` ### Usage ```sh $ use live server to render the index ``` or to run webpack on development mode ``` npm run watch ``` or to run webpack in production mode ``` npm run build ``` or to watch in development mode ``` npm run watch ``` or to start a server ``` npm run start ``` ## Author 👤 **<NAME>** - Twitter: [@bafiam_steve](https://twitter.com/Bafiam_steve) - Github: [@Bafiam](https://github.com/https://github.com/bafiam) ## 🤝 Contributing Contributions, issues and feature requests are welcome! ## Show your support Give a ⭐️ if you like this project! ## Acknowledgements - [Microverse](https://www.microverse.org/) - [The Odin Project](https://www.theodinproject.com/) - [Freecodecamp](http://freecodecamp.org/) ## 📝 License This project is licensed under MIT license - see [LICENSE](/LICENSE) for more details. <file_sep>/src/components/MakeElements.js const element = (element) => { const el = document.createElement(element); return el; }; const text = (text) => { const txt = document.createTextNode(text); return txt; }; export { element, text };<file_sep>/src/components/DisplayData.js import { element, text } from './MakeElements'; import '../css/displayData.css'; const weatherData = () => { const div = element('DIV'); div.setAttribute('id', 'weatherDiv'); const cityP = element('P'); cityP.setAttribute('id', 'cityName'); const divMain = element('DIV'); divMain.setAttribute('id', 'divMain'); const div1 = element('DIV'); div1.setAttribute('id', 'mainOne'); const head4 = element('H4'); const head4Text = text('Wind'); const icon = element('I'); icon.setAttribute('class', 'fas fa-wind'); const head5 = element('H5'); const div101 = element('DIV'); div101.setAttribute('id', 'mainTwo'); const head401 = element('H4'); const head4Text01 = text('Cloudiness'); const icon01 = element('I'); icon01.setAttribute('class', 'fas fa-cloud'); const head501 = element('H5'); const div102 = element('DIV'); div102.setAttribute('id', 'mainThree'); const head402 = element('H4'); const head4Text02 = text('Humidity'); const icon02 = element('I'); icon02.setAttribute('class', 'fas fa-smog'); const head502 = element('H5'); const div103 = element('DIV'); div103.setAttribute('id', 'mainFour'); const head403 = element('H4'); const head4Text03 = text('Temperature'); const icon03 = element('I'); icon03.setAttribute('class', 'fas fa-sun'); const head503 = element('H5'); head4.append(head4Text); div1.append(head4, icon, head5); head401.append(head4Text01); div101.append(head401, icon01, head501); head402.append(head4Text02); div102.append(head402, icon02, head502); head403.append(head4Text03); div103.append(head403, icon03, head503); divMain.append(div1, div101, div102, div103); div.append(cityP, divMain); return div; }; export default weatherData;<file_sep>/src/components/Header.js import { element, text } from './MakeElements'; import '../css/header.css'; const Header = () => { const header = element('HEADER'); const nav = element('NAV'); const div1 = element('DIV'); const p = element('P'); const pTxt = text('Weather app'); p.appendChild(pTxt); div1.appendChild(p); nav.append(div1); header.append(nav); return header; }; export default Header;<file_sep>/src/components/FetchData.js const apiKey = '<KEY>'; const fetchUrl = (cityName) => { const url = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${apiKey}&units=metric`; return url; }; const makeRequest = async url => { const response = await fetch(url); if (response.ok) { return response; } // eslint-disable-next-line prefer-promise-reject-errors return Promise.reject({ error: 'That is not a invalid city name' }); }; const fetchData = async (url) => { try { const response = await makeRequest(url); return response.json(); } catch (error) { return error; } }; export { fetchUrl, fetchData }; <file_sep>/src/index.js import places from 'places.js'; import Header from './components/Header'; import Main from './components/Main'; import { fetchUrl, fetchData } from './components/FetchData'; import './css/style.css'; const page = document.querySelector('#content'); page.append(Header(), Main()); // start search name autocomplete const getSearch = document.querySelector('#search'); const fixedOptions = { appId: 'plN8796X3W30', apiKey: '<KEY>', container: getSearch, }; places(fixedOptions); const getCity = document.querySelector('#cityName'); const run = async (name) => { const url = fetchUrl(name); const responce = await fetchData(url); return responce; }; const reset = () => { getCity.innerHTML = ''; document.querySelector('#mainOne h5').innerHTML = ''; document.querySelector('#mainTwo h5').innerHTML = ''; document.querySelector('#mainThree h5').innerHTML = ''; document.querySelector('#mainFour h5').innerHTML = ''; }; const appendData = async () => { const data = 'Nairobi'; if (data) { const getData = await run(data); if (getData.error === undefined) { reset(); getCity.append(data); document.querySelector('#mainOne h5').append(`${getData.wind.speed} m/s`); document .querySelector('#mainTwo h5') .append(getData.weather[0].description); document .querySelector('#mainThree h5') .append(`${getData.main.humidity} %`); document .querySelector('#mainFour h5') .append(`${getData.main.temp} degrees`); } else { reset(); getCity.append(getData.error); } } }; appendData(); const runSearch = async (e) => { e.preventDefault(); const data = e.target.elements[0].value.split(','); if (data) { const getData = await run(data); if (getData.error === undefined) { reset(); getCity.append(e.target.elements[0].value); document.querySelector('#mainOne h5').append(`${getData.wind.speed} m/s`); document .querySelector('#mainTwo h5') .append(getData.weather[0].description); document .querySelector('#mainThree h5') .append(`${getData.main.humidity} %`); document .querySelector('#mainFour h5') .append(`${getData.main.temp} degrees`); } else { reset(); getCity.append(getData.error); } } }; document.querySelector('#searchForm').addEventListener('submit', runSearch);
15f78545525faa879c2dc254cf586256aafd2923
[ "Markdown", "JavaScript" ]
6
Markdown
bafiam/WEATHER-APP
ff46e66cbf3538c0c17e03e97d3ef98872978522
147a1eeab07d44e4394ac2a8f524fc7f334a648a
refs/heads/master
<file_sep>#!/usr/bin/python import lxml.etree import requests import datetime from pymongo import MongoClient client = MongoClient() db = client.freifunk CONFIG = { "crawl_netif": "br-mesh", "mac_netif": "br-mesh", "vpn_netif": "fffVPN" } # create db indexes db.routers.create_index([("position", "2dsphere")]) tree = lxml.etree.fromstring(requests.get("https://netmon.freifunk-franken.de/api/rest/routerlist", params={"limit": 5000}).content) for r in tree.xpath("/netmon_response/routerlist/router"): user_netmon_id = int(r.xpath("user_id/text()")[0]) user = db.users.find_one({"netmon_id": user_netmon_id}) if user: user_id = user["_id"] else: user_id = db.users.insert({ "netmon_id": user_netmon_id, "nickname": r.xpath("user/nickname/text()")[0] }) user = db.users.find_one({"_id": user_id}) router = { "netmon_id": int(r.xpath("router_id/text()")[0]), "hostname": r.xpath("hostname/text()")[0], "user": {"nickname": user["nickname"], "_id": user["_id"]} } try: lng = float(r.xpath("longitude/text()")[0]) lat = float(r.xpath("latitude/text()")[0]) assert lng != 0 assert lat != 0 router["position"] = { "type": "Point", "coordinates": [lng, lat] } # define hood router["hood"] = db.hoods.find_one({"position": {"$near": {"$geometry": router["position"]}}})["name"] # try to get comment position_comment = r.xpath("location/text()")[0] if position_comment != "undefined": router["position"]["comment"] = position_comment except (IndexError, AssertionError): pass try: router["description"] = r.xpath("description/text()")[0] except IndexError: pass if db.routers.find_one({"netmon_id": router["netmon_id"]}): print("Updating »%(hostname)s«" % router) db.routers.update_one({"netmon_id": router["netmon_id"]}, {"$set": router}) else: print("Importing »%(hostname)s«" % router) # crawl HTML page for CONFIG["crawl_netif"] ip for 1st direct router crawl page = requests.get("https://netmon.freifunk-franken.de/router.php", params={"router_id": router["netmon_id"]}).text if CONFIG["crawl_netif"] in page: netif_ip = "fe80%s" % page.split("<b>%s</b>" % CONFIG["crawl_netif"])[1].split("fe80")[1].split("/")[0] router["netifs"] = [{ "name": CONFIG["crawl_netif"], "ipv6_fe80_addr": netif_ip }] router["created"] = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc) router["status"] = "unknown" db.routers.insert_one(router)
aae8fd7406b1137bfa8b59d2970b2a3b4db41c4e
[ "Python" ]
1
Python
nuori37/fff-monitoring
066eac5dd60f6303793f2ff85d80565ef846da4f
4b71caf7edcffa83f9d9d33bff4d85f010dea28f
refs/heads/master
<repo_name>paritoshrakshit583/properties-demo-service<file_sep>/src/main/java/com/demo/microservices/demopropertyaccessservice/PropertiesDemoServiceApplication.java package com.demo.microservices.demopropertyaccessservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class PropertiesDemoServiceApplication { public static void main(String[] args) { SpringApplication.run(PropertiesDemoServiceApplication.class, args); } } <file_sep>/README.md # properties-demo-service Spring boot properties demo
c317a19af96149780f1cda9333e735ed52e666ef
[ "Markdown", "Java" ]
2
Java
paritoshrakshit583/properties-demo-service
573cf2924a6c3246276c15663a74bd41943a18f8
97775bc72885c7f5ae040e68aed5eddb58202ae3
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.Hardware.Camera2; using Android.Hardware.Camera2.Params; using Android.Media; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using CameraViewXamarinForms.Droid.Listeners; using Java.Lang; using Xamarin.Forms; using Size = Android.Util.Size; namespace CameraViewXamarinForms.Droid.Views { public sealed class NativeCameraView : FrameLayout, TextureView.ISurfaceTextureListener { private static readonly SparseIntArray Orientations = new SparseIntArray(); public event EventHandler<ImageSource> Photo; public bool OpeningCamera { private get; set; } public CameraDevice CameraDevice; private readonly CameraStateListener _mStateListener; private CaptureRequest.Builder _previewBuilder; private CameraCaptureSession _previewSession; private SurfaceTexture _viewSurface; private readonly TextureView _cameraTexture; private Size _previewSize; private readonly Context _context; private CameraManager _manager; public NativeCameraView(Context context) : base(context) { _context = context; var inflater = LayoutInflater.FromContext(context); if (inflater == null) return; var view = inflater.Inflate(Resource.Layout.CameraLayout, this); _cameraTexture = view.FindViewById<TextureView>(Resource.Id.cameraTexture); _cameraTexture.Click += (sender, args) => { TakePhoto(); }; _cameraTexture.SurfaceTextureListener = this; _mStateListener = new CameraStateListener { Camera = this }; Orientations.Append((int)SurfaceOrientation.Rotation0, 0); Orientations.Append((int)SurfaceOrientation.Rotation90, 90); Orientations.Append((int)SurfaceOrientation.Rotation180, 180); Orientations.Append((int)SurfaceOrientation.Rotation270, 270); } public void OnSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { _viewSurface = surface; ConfigureTransform(width, height); StartPreview(); } public bool OnSurfaceTextureDestroyed(SurfaceTexture surface) { return true; } public void OnSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { } public void OnSurfaceTextureUpdated(SurfaceTexture surface) { } public void OpenCamera(CameraOptions options) { if (_context == null || OpeningCamera) { return; } OpeningCamera = true; _manager = (CameraManager)_context.GetSystemService(Context.CameraService); var cameraId = _manager.GetCameraIdList()[(int)options]; var characteristics = _manager.GetCameraCharacteristics(cameraId); var map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); _previewSize = map.GetOutputSizes(Class.FromType(typeof(SurfaceTexture)))[0]; _manager.OpenCamera(cameraId, _mStateListener, null); } private void TakePhoto() { if (_context == null || CameraDevice == null) return; var characteristics = _manager.GetCameraCharacteristics(CameraDevice.Id); Size[] jpegSizes = null; if (characteristics != null) { jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg); } var width = 480; var height = 640; if (jpegSizes != null && jpegSizes.Length > 0) { width = jpegSizes[0].Width; height = jpegSizes[0].Height; } var reader = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1); var outputSurfaces = new List<Surface>(2) { reader.Surface, new Surface(_viewSurface) }; var captureBuilder = CameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture); captureBuilder.AddTarget(reader.Surface); captureBuilder.Set(CaptureRequest.ControlMode, new Integer((int)ControlMode.Auto)); var windowManager = _context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>(); var rotation = windowManager.DefaultDisplay.Rotation; captureBuilder.Set(CaptureRequest.JpegOrientation, new Integer(Orientations.Get((int)rotation))); var readerListener = new ImageAvailableListener(); readerListener.Photo += (sender, buffer) => { Photo?.Invoke(this, ImageSource.FromStream(() => new MemoryStream(buffer))); }; var thread = new HandlerThread("CameraPicture"); thread.Start(); var backgroundHandler = new Handler(thread.Looper); reader.SetOnImageAvailableListener(readerListener, backgroundHandler); var captureListener = new CameraCaptureListener(); captureListener.PhotoComplete += (sender, e) => { StartPreview(); }; CameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener { OnConfiguredAction = session => { try { _previewSession = session; session.Capture(captureBuilder.Build(), captureListener, backgroundHandler); } catch (CameraAccessException ex) { Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString()); } } }, backgroundHandler); } public void StartPreview() { if (CameraDevice == null || !_cameraTexture.IsAvailable || _previewSize == null) return; var texture = _cameraTexture.SurfaceTexture; texture.SetDefaultBufferSize(_previewSize.Width, _previewSize.Height); var surface = new Surface(texture); _previewBuilder = CameraDevice.CreateCaptureRequest(CameraTemplate.Preview); _previewBuilder.AddTarget(surface); CameraDevice.CreateCaptureSession(new List<Surface> { surface }, new CameraCaptureStateListener { OnConfigureFailedAction = session => { }, OnConfiguredAction = session => { _previewSession = session; UpdatePreview(); } }, null); } private void ConfigureTransform(int viewWidth, int viewHeight) { if (_viewSurface == null || _previewSize == null || _context == null) return; var windowManager = _context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>(); var rotation = windowManager.DefaultDisplay.Rotation; var matrix = new Matrix(); var viewRect = new RectF(0, 0, viewWidth, viewHeight); var bufferRect = new RectF(0, 0, _previewSize.Width, _previewSize.Height); var centerX = viewRect.CenterX(); var centerY = viewRect.CenterY(); if (rotation == SurfaceOrientation.Rotation90 || rotation == SurfaceOrientation.Rotation270) { bufferRect.Offset(centerX - bufferRect.CenterX(), centerY - bufferRect.CenterY()); matrix.SetRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.Fill); matrix.PostRotate(90 * ((int)rotation - 2), centerX, centerY); } _cameraTexture.SetTransform(matrix); } private void UpdatePreview() { if (CameraDevice == null || _previewSession == null) return; _previewBuilder.Set(CaptureRequest.ControlMode, new Integer((int)ControlMode.Auto)); var thread = new HandlerThread("CameraPreview"); thread.Start(); var backgroundHandler = new Handler(thread.Looper); _previewSession.SetRepeatingRequest(_previewBuilder.Build(), null, backgroundHandler); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Media; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace CameraViewXamarinForms.Droid.Listeners { public class ImageAvailableListener : Java.Lang.Object, ImageReader.IOnImageAvailableListener { public event EventHandler<byte[]> Photo; public void OnImageAvailable(ImageReader reader) { Image image = null; try { image = reader.AcquireLatestImage(); var buffer = image.GetPlanes()[0].Buffer; var imageData = new byte[buffer.Capacity()]; buffer.Get(imageData); Photo?.Invoke(this, imageData); } catch (Exception) { // ignored } finally { image?.Close(); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using CameraViewXamarinForms; using CameraViewXamarinForms.Droid.Renderers; using CameraViewXamarinForms.Droid.Views; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(CameraView), typeof(CameraViewRenderer))] namespace CameraViewXamarinForms.Droid.Renderers { public class CameraViewRenderer : ViewRenderer<CameraView, NativeCameraView> { NativeCameraView cameraPreview; public CameraViewRenderer(Context context) : base(context) { } protected override async void OnElementChanged(ElementChangedEventArgs<CameraView> e) { base.OnElementChanged(e); if (Control == null) { cameraPreview = new NativeCameraView(Context); SetNativeControl(cameraPreview); } if (e.NewElement != null) { try { PermissionStatus status = await Permissions.CheckStatusAsync<Permissions.Camera>(); if (status != PermissionStatus.Granted) { status = await Permissions.RequestAsync<Permissions.Camera>(); } if (status == PermissionStatus.Granted) { cameraPreview.OpenCamera(e.NewElement.Camera); SetNativeControl(cameraPreview); } else if (status != PermissionStatus.Unknown) { //await DisplayAlert("Camera Denied", "Can not continue, try again.", "OK"); } } catch (Exception ex) { throw; } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Hardware.Camera2; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using CameraViewXamarinForms.Droid.Views; namespace CameraViewXamarinForms.Droid.Listeners { public class CameraStateListener : CameraDevice.StateCallback { public NativeCameraView Camera; public override void OnOpened(CameraDevice camera) { if (Camera == null) return; Camera.CameraDevice = camera; Camera.StartPreview(); Camera.OpeningCamera = false; } public override void OnDisconnected(CameraDevice camera) { if (Camera == null) return; camera.Close(); Camera.CameraDevice = null; Camera.OpeningCamera = false; } public override void OnError(CameraDevice camera, CameraError error) { camera.Close(); if (Camera == null) return; Camera.CameraDevice = null; Camera.OpeningCamera = false; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Hardware.Camera2; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace CameraViewXamarinForms.Droid.Listeners { public class CameraCaptureListener : CameraCaptureSession.CaptureCallback { public event EventHandler PhotoComplete; public override void OnCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) { PhotoComplete?.Invoke(this, EventArgs.Empty); } } }<file_sep>using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; namespace CameraViewXamarinForms { public enum CameraOptions { Rear, Front } public class CameraView : View { public static readonly BindableProperty CameraProperty = BindableProperty.Create(nameof(Camera), typeof(CameraOptions), typeof(CameraView), CameraOptions.Rear); public CameraOptions Camera { get { return (CameraOptions)GetValue(CameraProperty); } set { SetValue(CameraProperty, value); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using CameraViewXamarinForms; using CameraViewXamarinForms.iOS.Renderers; using CameraViewXamarinForms.iOS.Views; using Foundation; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(CameraView), typeof(CameraViewRenderer))] namespace CameraViewXamarinForms.iOS.Renderers { public class CameraViewRenderer : ViewRenderer<CameraView, NativeCameraView> { NativeCameraView uiCameraPreview; protected override void OnElementChanged(ElementChangedEventArgs<CameraView> e) { base.OnElementChanged(e); if (Control == null) { uiCameraPreview = new NativeCameraView(e.NewElement.Camera); SetNativeControl(uiCameraPreview); } if (e.OldElement != null) { // Unsubscribe uiCameraPreview.Tapped -= OnCameraPreviewTapped; } if (e.NewElement != null) { // Subscribe uiCameraPreview.Tapped += OnCameraPreviewTapped; } } void OnCameraPreviewTapped(object sender, EventArgs e) { if (uiCameraPreview.IsPreviewing) { uiCameraPreview.CaptureSession.StopRunning(); uiCameraPreview.IsPreviewing = false; } else { uiCameraPreview.CaptureSession.StartRunning(); uiCameraPreview.IsPreviewing = true; } } protected override void Dispose(bool disposing) { if (disposing) { Control.CaptureSession.Dispose(); Control.Dispose(); } base.Dispose(disposing); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using AVFoundation; using CoreGraphics; using Foundation; using UIKit; namespace CameraViewXamarinForms.iOS.Views { public class NativeCameraView : UIView { AVCaptureVideoPreviewLayer previewLayer; CameraOptions cameraOptions; public event EventHandler<EventArgs> Tapped; public AVCaptureSession CaptureSession { get; private set; } public bool IsPreviewing { get; set; } public NativeCameraView(CameraOptions options) { cameraOptions = options; IsPreviewing = false; Initialize(); } public override void Draw(CGRect rect) { base.Draw(rect); previewLayer.Frame = rect; } public override void TouchesBegan(NSSet touches, UIEvent evt) { base.TouchesBegan(touches, evt); OnTapped(); } protected virtual void OnTapped() { var eventHandler = Tapped; if (eventHandler != null) { eventHandler(this, new EventArgs()); } } void Initialize() { CaptureSession = new AVCaptureSession(); previewLayer = new AVCaptureVideoPreviewLayer(CaptureSession) { Frame = Bounds, VideoGravity = AVLayerVideoGravity.ResizeAspectFill }; var videoDevices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video); var cameraPosition = (cameraOptions == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back; var device = videoDevices.FirstOrDefault(d => d.Position == cameraPosition); if (device == null) { return; } NSError error; var input = new AVCaptureDeviceInput(device, out error); CaptureSession.AddInput(input); Layer.AddSublayer(previewLayer); CaptureSession.StartRunning(); IsPreviewing = true; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Hardware.Camera2; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace CameraViewXamarinForms.Droid.Listeners { public class CameraCaptureStateListener : CameraCaptureSession.StateCallback { public Action<CameraCaptureSession> OnConfigureFailedAction; public Action<CameraCaptureSession> OnConfiguredAction; public override void OnConfigureFailed(CameraCaptureSession session) { OnConfigureFailedAction?.Invoke(session); } public override void OnConfigured(CameraCaptureSession session) { OnConfiguredAction?.Invoke(session); } } }
2f93406ebde4b233b7b4d4663d354163d9b1e2d6
[ "C#" ]
9
C#
wilsonvargas/CameraViewXamarinForms
53d4f2d79cd404fbf331c3023c0647a2dfa23e17
b8fd6523503b9a0ede6233ba74072383d378e456
refs/heads/master
<repo_name>MaxTracks/QuadTree<file_sep>/makefile CXX = g++ CXXFLAGS = -std=c++11 -g -Wall -Wextra LINK.o = $(CXX) all:main main: main.o generator.o main.o: main.cpp quadtree.h quadtree.cpp generator.o: generator.h generator.cpp clean: rm -f *.o *~ main <file_sep>/main.cpp #include "generator.h" #include "quadtree.h" #include <utility> int main() { std::vector<double> vec; generator gen(-1000000,1000000); for(int i = 0; i < 100; i++) { vec.push_back(gen()/100.0); } quadtree<double> qt; quadtree<double> del(1,0,500,500,0); for(unsigned int i=0;i<vec.size();i+=2) { qt.insert(std::pair<double,double>(vec[i],vec[i+1]),1.0); } std::cout << qt << std::endl; del.insert(std::pair<double,double>(10.0, 15.0), 6.6); std::cout << "del.insert(std::pair<double,double>(10.0, 15.0), 6.6);" << std::endl; del.insert(std::pair<double,double>(15.0, 10.0), 5.5); std::cout << "del.insert(std::pair<double,double>(15.0, 10.0), 5.5);" << std::endl; del.insert(std::pair<double,double>(10.0, 10.0), 4.4); std::cout << "del.insert(std::pair<double,double>(10.0, 10.0), 4.4);" << std::endl; del.insert(std::pair<double,double>(5.0, 5.0), 3.3); std::cout << "del.insert(std::pair<double,double>(5.0, 5.0), 3.3);" << std::endl; del.deleteKey(std::pair<double,double>(5.0, 5.0)); std::vector<std::pair<std::pair<double,double>,double> > result; result = del.searchRange(std::pair<double,double>(0,500),std::pair<double,double>(500,0)); std::cout << result.size() << std::endl; for(auto i:result){ std::cout << "X:" << i.first.first << " Y:" << i.first.second << " DATA:" << i.second << std::endl; } return 0; }
137e4709bb3086f59bc940a9d6b152f1c684d91b
[ "Makefile", "C++" ]
2
Makefile
MaxTracks/QuadTree
3d28ad8a5f761865e63917781271e72749ccf9b5
d1b4d9bb620f5442f268118cfec83d416dd6a390
refs/heads/master
<repo_name>helfrench/StudentInformationSystem<file_sep>/php/login.php <?php include_once('header.php'); include_once ('../connection/connection.php'); $con = connection(); if(isset($_POST['submit'])){ $userName = $_POST['username']; $password = $_POST['password']; $sql = "SELECT * FROM `user` WHERE username = '$userName' AND password = '$<PASSWORD>'"; // $sql = "INSERT INTO `user` (`username`, `password`) VALUES ('$userName', '$password' )"; $users = $con->query($sql) or die ($con->error); $row = $users->fetch_assoc(); $total = $users->num_rows; if($total > 0){ $_SESSION['UserLogin'] = $row['username']; $_SESSION['Access'] = $row['access']; echo $_SESSION['UserLogin']; echo header('location:../index.php'); }else{ echo " User not found"; } } ?> <div class="container"> <div class="wrappers mt-5" style="width:400px; margin:0 auto; "> <form method="post"> <div class="form-group"> <label for="exampleInputEmail1">Username</label> <input type="text" class="form-control" name="username" id="exampleInputEmail1" aria-describedby="emailHelp"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="<PASSWORD>" class="form-control" name="password" id="exampleInput<PASSWORD>"> </div> <div class="form-group"> <a href="#" class="dontHaveAccount">Dont have an account yet?</a> </div> <div class="text-center"> <button type="submit" name="submit" class="btn btn-primary btn-edits ">Log in</button> </div> </form> </div> <?php include_once('footer.php');?><file_sep>/add.php <?php include_once('php/header.php'); include_once ('connection/connection.php'); $con = connection(); if(isset($_POST['submit'])){ $fname = $_POST['firstname']; $lname = $_POST['lastname']; $gender = $_POST['gender']; $sql = "INSERT INTO `student_list`(`first_name`, `last_name`, `gender` ) VALUES ('$fname', '$lname','$gender' )"; $students = $con->query($sql) or die ($con->error); echo header('location: index.php'); }else{ } ?> <body> <div class="container"> <h2 class="mt-3">Input Information</h2> <form action="#" method="post"> <div class="row mt-5 col-6 text-center display-"> <label for="inputEmail4">First Name</label> <input type="text" class="form-control" name="firstname" id="firstname"> </div> <div class="row mt-5 col-6"> <label for="inputEmail4">lastname</label> <input type="text" class="form-control" name="lastname" id="lastname"> </div> <div class="row mt-5 col-6"> <select name="gender" id="gender"> <option value="Male">Male</option> <option value="Female">Female</option> <option value="Genderqueer">Genderqueer</option> <option value="Agender">Agender</option> </select> </div> <div class="row mt-5 col-6"> <input class="btn btn-success mr-3" type="submit" name="submit" value="Submit"> <button class="btn btn-danger"><a style="text-decoration:none;color:#fff;" href="index.php">Cancel</a></button> </div> </form> </div> <?php include_once('php/footer.php');?><file_sep>/edit.php <?php include_once('php/header.php'); include_once ('connection/connection.php'); $con = connection(); if (isset($_SESSION['Access']) && $_SESSION['Access'] == "Administrator"){ }else{ echo header('location:index.php'); } $studID = $_GET['ID']; $sql = "SELECT * FROM student_list WHERE studId = '$studID'"; $students = $con->query($sql) or die ($con->error); $row = $students->fetch_assoc(); ?> <?php if(isset($_POST['submit'])) { $studID = $_GET['ID']; $fname = $_POST['firstname']; $lname = $_POST['lastname']; $gender = $_POST['gender']; $date_added = $_POST['date_added']; $address = $_POST['address']; $birthdate = $_POST['birthdate']; $sql = "UPDATE`student_list`SET first_name='$fname', last_name='$lname', gender='$gender', date_added='$date_added', address='$address' , birthdate='$birthdate' WHERE studId = '$studID'"; $students = $con->query($sql) or die ($con->error); echo header('location: index.php'); } ?> <body> <div class="container fluid"> <div class="row"> <div class="col-md-4"> <img src="img/<?php echo $row['studId'];?>.jpg" alt="..." class="img-thumbnail"> </div> <div class="col-md-8 border"> <h2 class="text-center mt-3">Student Information</h2> <form method="POST" class="mb-5"> <div class="form-row"> <div class="form-group col-md-2 mt-2"> <label for="inputEmail4">Student #</label> <fieldset disabled> <input type="text" class="form-control" id="disabledInput" placeholder="disabledInput" value="<?php echo $row['studId'];?>"> </fieldset> </div> <div class="form-group col-md-10"> <div class="form-group col-md-4 mt-2"> <label for="inputEmail4">Date Enrolled</label> <fieldset disabled> <input type="text" class="form-control" id="disabledInput" placeholder="disabledInput" value="<?php echo $row['date_added'];?>"> </fieldset> </div> </div> <div class="form-group col-md-6"> <label for="inputEmail4">First Name</label> <input type="text" name="firstname" class="form-control" id="inputEmail4" value="<?php echo $row['first_name']?>"> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Last Name</label> <input type="text" name="lastname" class="form-control" id="inputPassword4" value="<?php echo $row['last_name']?>"> </div> </div> <div class="form-group col-md-12"> <label for="inputAddress">Address</label> <input type="text" name="address" class="form-control" id="inputAddress" value="<?php echo $row['address']?>"> </div> <div class="row"> <div class="form-group col-md-6 "> <label for="inputState">Gender</label> <select name="gender" id="inputState" class="form-control"> <option selected>----</option> <option value="Male"<?php echo ($row['gender']=="Male")?'selected':'';?> > Male </option> <option value="Female"<?php echo ($row['gender']=="Female")?'selected':'';?>>Female</option> </select> </div> <div class="form-group col-md-6"> <label for="inputCity">Birth Date</label> <input type="text" name="birthdate" class="form-control" id="inputCity" value="<?php echo $row['birthdate'];?>"> </div> </div> <div class="row"> <div class="form-group col-md-6 "> <label for="inputState">Nationality</label> <select id="inputState" class="form-control"> <option selected>----</option> <option>Filipino</option> <option>American</option> <option>Australian</option> </select> </div> <div class="form-group col-md-6 "> <label for="inputState">Year Level</label> <select id="inputState" class="form-control"> <option selected>----</option> <option>1st Year</option> <option>2nd Year</option> <option>3rd Year</option> <option>4th Year</option> </select> </div> </div> <div class="form-group"> <input class="btn btn-success mr-3 text-center" type="submit" name="submit" value="Update"> <button class="btn btn-warning mr-3"><a style="text-decoration:none;color:#fff;" href="php/details.php?ID=<?php echo $row['studId'];?>">Cancel</a></button> <button class="btn btn-danger mr-3"><a style="text-decoration:none;color:#fff;" href="delete.php?ID=<?php echo $row['studId'];?>">Delete</a></button> <button class="btn btn-primary mr-3"> <a style="text-decoration:none;color:#fff;" href="index.php?ID=<?php echo $row['studId'];?>"> >>Back to Student List</a></button> </div> </form> </div> </div> </div> <?php include_once('php/footer.php');?><file_sep>/deleteAll.php <?php include_once ('connection/connection.php'); $con = connection(); $studID = $_GET['ID']; $sql = "TRUNCATE TABLE `student_list`" ; $students = $con->query($sql) or die ($con->error); echo header('location: index.php'); ?> <file_sep>/php/result.php <?php include_once('header.php'); include_once ('../connection/connection.php'); $con = connection(); $search = $_GET['search']; $sql = "SELECT * FROM `student_list` WHERE first_name LIKE '%$search%'OR last_name LIKE '%$search%'"; $students = $con->query($sql) or die ($con->error); if($students){ $row = $students->fetch_assoc(); }else{ echo header('location:../index.php'); } ?> <body> <div class="container" > <a href="add.php"><button class="btn btn-success mt-5 mb-3"> Add Student</button></a> <a href="deleteAll.php"><button class="btn btn-success mt-5 mb-3"> Delete All student</button></a> <?php if(isset($_SESSION['UserLogin'])){ ?> <a href="php/logout.php"><button class="btn btn-warning mt-5 mb-3"> Logout</button></a> <?php } else { ?> <a href="php/login.php"><button class="btn btn-primary mt-5 mb-3"> Login</button></a> <?php } ?> <form action="result.php" method="get"> <input type="text" name="search" id="search"> <button class="btn btn-success" type="submit" name="query">Search</button> </form> <div class="row"> <h2>Student Information</h2> <table class="table sm"> <thead> <tr> <th scope="col"></th> <th scope="col">Stud ID</th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Birthdate</th> <th scope="col">Date_added</th> <th scope="col">Gender</th> <th scope="col">Address</th> <th scope="col">Action</th> </tr> </thead> <tbody> <?php do{ ?> <tr> <td><a href="details.php?ID=<?php echo $row['studId'];?>">View</a></td> <td><?php echo $row['studId'];?></td> <td><?php echo $row['first_name'];?></td> <td><?php echo $row['last_name'];?></td> <td><?php echo $row['birthdate'];?></td> <td><?php echo $row['date_added'];?></td> <td><?php echo $row['gender'];?></td> <td><?php echo $row['address'];?></td> <td><button class="btn btn-danger"><a style="text-decoration:none;color:#fff;" href="../delete.php?ID=<?php echo $row['studId'];?>">Delete</a></button></td> <td><button class="btn btn-warning"><a style="text-decoration:none;color:#fff;" href="../edit.php?ID=<?php echo $row['studId'];?>">Edit</a></button></td> </tr> <?php }while($row = $students->fetch_assoc())?> </tbody> </table> </div> </div> <?php include_once('footer.php');?><file_sep>/delete.php <?php include_once ('connection/connection.php'); $con = connection(); $studID = $_GET['ID']; if (isset($_SESSION['Access']) && $_SESSION['Access'] == "Administrator"){ }else{ echo header('location:index.php'); } $sql = "DELETE FROM `student_list` WHERE `studId` = '$studID'" ; $students = $con->query($sql) or die ($con->error); echo header('location: index.php'); ?> <file_sep>/php/details.php <?php include_once('header.php'); include_once ('../connection/connection.php'); if (isset($_SESSION['Access']) && $_SESSION['Access'] == "Administrator"){ }else{ echo header('location:../index.php'); } $con = connection(); $studID = $_GET['ID']; $sql = "SELECT * FROM student_list WHERE studId = '$studID'"; $students = $con->query($sql) or die ($con->error); $row = $students->fetch_assoc(); ?> <body> <div class="container fluid disabled"> <div class="row"> <div class="col-md-4"> <img src="../img/<?php echo $row['studId'];?>.jpg" alt="..." class="img-thumbnail"> </div> <div class="col-md-8 border"> <h2 class="text-center mt-3">Student Information</h2> <form> <div class="form-row"> <div class="form-group col-md-2 mt-2"> <label for="inputEmail4">Student #</label> <fieldset disabled> <input type="text" name="studId" class="form-control" id="disabledInput" placeholder="disabledInput" value="<?php echo $row['studId'];?>"> </fieldset> </div> <div class="form-group col-md-10"> <div class="form-group col-md-4 mt-2"> <label for="inputEmail4">Date Enrolled</label> <fieldset disabled> <input type="text" class="form-control" id="disabledInput" placeholder="disabledInput" value="<?php echo $row['date_added'];?>"> </fieldset> </div> </div> <div class="form-group col-md-6"> <label for="inputEmail4">First Name</label> <fieldset disabled> <input type="text" class="form-control" id="inputEmail4" value="<?php echo $row['first_name']?>"> </fieldset> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Last Name</label> <fieldset disabled> <input type="text" class="form-control" id="inputPassword4" value="<?php echo $row['last_name']?>"> </fieldset> </div> </div> <div class="form-group col-md-12"> <label for="inputAddress">Address</label> <fieldset disabled> <input type="text" class="form-control" id="inputAddress" value="<?php echo $row['address']?>"> </fieldset> </div> <div class="row"> <div class="form-group col-md-6 "> <label for="inputState">Gender</label> <fieldset disabled> <select id="inputState" class="form-control"> <option selected> ---- </option> <option value="Male"<?php echo ($row['gender']=="Male")?'selected':'';?> > Male </option> <option value="Female"<?php echo ($row['gender']=="Female")?'selected':'';?>>Female</option> </select> </fieldset> </div> <div class="form-group col-md-6"> <label for="inputCity">Birth Date</label> <fieldset disabled> <input type="text" class="form-control" id="inputCity" value="<?php echo $row['birthdate']?>"> </fieldset> </div> </div> <div class="row"> <div class="form-group col-md-6 "> <label for="inputState">Nationality</label> <fieldset disabled> <select id="inputState" class="form-control"> <option selected>----</option> <option>Filipino</option> <option>American</option> <option>Australian</option> </select> </fieldset> </div> <div class="form-group col-md-6 "> <label for="inputState">Year Level</label> <fieldset disabled> <select id="inputState" class="form-control"> <option selected>----</option> <option>1st Year</option> <option>2nd Year</option> <option>3rd Year</option> <option>4th Year</option> </select> </fieldset> </div> </div> <div class="form-group"> <input class="btn btn-success mr-3 text-center" type="submit" name="submit" value="Submit"> <button class="btn btn-warning mr-3"><a style="text-decoration:none;color:#fff;" href="../edit.php?ID=<?php echo $row['studId'];?>">Edit</a></button> <button class="btn btn-primary mr-3"> <a style="text-decoration:none;color:#fff;" href="../index.php?ID=<?php echo $row['studId'];?>"> >>Back to Student List</a></button> </div> </form> </div> </div> </div> <?php include_once('footer.php');?>
7cb755a74f739f7df514767e653007c788e80391
[ "PHP" ]
7
PHP
helfrench/StudentInformationSystem
e2a00e81b84a9245de1ef6c842931d9c6f4c85aa
18ac288a49bf3d0edfadb91cbe1f11fa02a24a08
refs/heads/master
<repo_name>willismonroe/adventofcode<file_sep>/2017/day13/day13_part2.py import os def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day13_input.txt").read().splitlines() print(solve(input)) fw = {} def check_collision(layer, depth): return layer % ((depth - 1) * 2) == 0 def solve(input): for line in input: layer, depth = list(map(int, line.split(': '))) fw[layer] = depth delay = 0 while True: for layer, depth in fw.items(): if check_collision(delay + layer, depth): break else: # no break return delay delay += 1 return delay if __name__ == '__main__': main() <file_sep>/2016/Day 6/tests.py import day6 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day6_Example(self): data = '''eedadn drvtee eandsr raavrd atevrs tsrnev sdttsa rasrtv nssdts ntnada svetve tesnvt vntsnd vrdear dvrsen enarar ''' self.assertEqual(day6.solve_most(data.split()), 'easter') def test_Day6Data(self): with open('input.txt') as f: data = f.read().splitlines() self.assertEqual(day6.solve_most(data), 'tsreykjj') def test_Day6_2Example(self): data = '''eedadn drvtee eandsr raavrd atevrs tsrnev sdttsa rasrtv nssdts ntnada svetve tesnvt vntsnd vrdear dvrsen enarar ''' self.assertEqual(day6.solve_least(data.split()), 'advent') def test_Day6_2Data(self): with open('input.txt') as f: data = f.read().splitlines() self.assertEqual(day6.solve_least(data), 'hnfbujie') if __name__ == '__main__': unittest.main() <file_sep>/2016/Day 16/tests.py import day16 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day16_Expand(self): self.assertEqual(day16.expand('1'), '100') self.assertEqual(day16.expand('0'), '001') self.assertEqual(day16.expand('11111'), '11111000000') self.assertEqual(day16.expand('111100001010'), '1111000010100101011110000') def test_Day16_Shrink(self): self.assertEqual(day16.shrink('110010110100'), '110101') self.assertEqual(day16.shrink('110101'), '100') def test_Day16_Example(self): self.assertEqual(day16.solve('10000', 20), '01100') def test_Day16_Data(self): self.assertEqual(day16.solve('11100010111110100', 272), '10100011010101011') def test_Day16_2_Data(self): self.assertEqual(day16.solve('11100010111110100', 35651584), '01010001101011001') if __name__ == '__main__': unittest.main() <file_sep>/2017/day22/test_day22.py import os import day22_part1, day22_part2 def test_part1_example(): inp = """..# #.. ...""".splitlines() assert day22_part1.solve(inp, max_cycles=70) == 41 def test_part1(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day22_input.txt").read().splitlines() assert day22_part1.solve(inp) == 5570 def test_part2_example(): inp = """..# #.. ...""".splitlines() assert day22_part2.solve(inp, max_cycles=100) == 26 assert day22_part2.solve(inp, max_cycles=10_000_000) == 2511944 def test_part2(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day22_input.txt").read().splitlines() assert day22_part2.solve(inp) == 2512022<file_sep>/2016/Day 19/day19.py import math import collections def solve(data): ring = [1] * data solved = 0 while not solved: if ring.count(len(ring)) == 1: solved = 1 break for elf_num in range(len(ring)): elf = ring[elf_num] if elf == 0: pass else: next_elf = next(i for i, v in enumerate(ring[elf_num + 1:] + ring[:elf_num]) if v > 0) + 1 + elf_num ring[elf_num] += ring[next_elf % len(ring)] ring[next_elf % len(ring)] = 0 return next(i for i, v in enumerate(ring) if v > 0) + 1 def solve(data): return (data - 2**math.floor(math.log(data, 2))) * 2 + 1 def solve_v2(data): left = collections.deque() right = collections.deque() for i in range(1, data+1): if i < (data // 2) + 1: left.append(i) else: right.appendleft(i) while left and right: if len(left) > len(right): left.pop() else: right.pop() right.appendleft(left.popleft()) left.append(right.pop()) return left[0] or right[0] def f(x): # this solves where x is not a power of 3, sort of a = math.floor(math.log(x, 3)) b = x - 3**a c = math.floor(math.log(b, 3)) d = b - 3**c return d if __name__ == '__main__': data = 3005290 data = 15 print(solve_v2(data)) <file_sep>/2016/Day 16/day16.py def invert(char): if char == '1': return '0' else: return '1' def expand(string): return string + '0' + ''.join(list(map(invert, string[::-1]))) def shrink(string): chunks = [string[i:i + 2] for i in range(0, len(string), 2)] new_string = '' for chunk in chunks: if chunk in ['00', '11']: new_string += '1' else: new_string += '0' return new_string def solve(data, length): while len(data) < length: data = expand(data) data = data[:length] checksum = shrink(data) while len(checksum) % 2 == 0: checksum = shrink(checksum) return checksum if __name__ == '__main__': length = 272 length = 35651584 data = '11100010111110100' print(solve(data, length))<file_sep>/2016/Day 8/tests.py import day8 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day8_Example(self): answer = [['#', '#', '#', '.', '.', '.', '.'], ['#', '#', '#', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.']] screen = day8.Screen(7, 3) screen.parse_line('rect 3x2') self.assertTrue((screen.screen == answer).all()) def test_Day8_Example_2(self): answer = [['#', '.', '#', '.', '.', '.', '.'], ['#', '#', '#', '.', '.', '.', '.'], ['.', '#', '.', '.', '.', '.', '.']] screen = day8.Screen(7, 3) screen.parse_line('rect 3x2') screen.parse_line('rotate column x=1 by 1') self.assertTrue((screen.screen == answer).all()) def test_Day8_Example_3(self): answer = [['.', '.', '.', '.', '#', '.', '#'], ['#', '#', '#', '.', '.', '.', '.'], ['.', '#', '.', '.', '.', '.', '.']] screen = day8.Screen(7, 3) screen.parse_line('rect 3x2') screen.parse_line('rotate column x=1 by 1') screen.parse_line('rotate row y=0 by 4') self.assertTrue((screen.screen == answer).all()) def test_Day8_Example_4(self): answer = [['.', '#', '.', '.', '#', '.', '#'], ['#', '.', '#', '.', '.', '.', '.'], ['.', '#', '.', '.', '.', '.', '.']] screen = day8.Screen(7, 3) screen.parse_line('rect 3x2') screen.parse_line('rotate column x=1 by 1') screen.parse_line('rotate row y=0 by 4') screen.parse_line('rotate column x=1 by 1') self.assertTrue((screen.screen == answer).all()) def test_Day8_Data(self): screen = day8.Screen(50, 6) with open('input.txt') as f: data = f.read().splitlines() self.assertEqual(day8.solve(screen, data), 110) if __name__ == '__main__': unittest.main() <file_sep>/2016/Day 1/day1_2.py def main(data): cur_loc = [0, 0] facing = 0 gazetteer = [cur_loc[:]] for instruction in data.split(', '): # find out which direction we're facing after turning # 0 = North, 90 = East, 180 = South, 270 = West if instruction[0] == 'R': facing = (facing + 90) % 360 elif instruction[0] == 'L': facing = (facing - 90) % 360 # get the number of blocks from the instructions distance = int(instruction[1:]) # move our location that many blocks in the correct direction, record each step for step in range(distance): if facing == 0: cur_loc[1] -= 1 elif facing == 90: cur_loc[0] += 1 elif facing == 180: cur_loc[1] += 1 elif facing == 270: cur_loc[0] -= 1 distance_from_origin = abs(cur_loc[0]) + abs(cur_loc[1]) if cur_loc in gazetteer: return distance_from_origin gazetteer.append(cur_loc[:]) total_distance = abs(cur_loc[0]) + abs(cur_loc[1]) return total_distance if __name__ == '__main__': with open('input.txt') as f: # read in the data and split into instructions # ['L4', 'L3', 'R1' ...] data = f.read() print(main(data)) <file_sep>/2018/templates/solve.js const fs = require("fs"); const input = fs .readFileSync(__dirname + "/input.txt") .toString() .split("\n") .map(s => s.replace(/\r$/, "")) .filter(s => s.length > 0); function partA(input) { } function partB(input) { } function solve() { console.log(`Part A: ${partA(input)}`); console.log(`Part B: ${partB(input)}`); } if (require.main === module) { solve(); } module.exports = { partA: partA, partB: partB }; <file_sep>/2016/Day 9/tests.py import day9 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day9_Example(self): string = 'ADVENT' self.assertEqual(day9.decompress(string), 6) def test_Day9_Example_2(self): string = 'A(1x5)BC' self.assertEqual(day9.decompress(string), 7) def test_Day9_Example_3(self): string = '(3x3)XYZ' self.assertEqual(day9.decompress(string), 9) def test_Day9_Example_4(self): string = 'A(2x2)BCD(2x2)EFG' self.assertEqual(day9.decompress(string), 11) def test_Day9_Example_5(self): string = 'A(2x2)BCD(2x2)EFG' self.assertEqual(day9.decompress(string), 11) def test_Day9_Example_6(self): string = '(6x1)(1x3)A' self.assertEqual(day9.decompress(string), 6) def test_Day9_Data(self): with open('input.txt') as f: data = f.read() self.assertEqual(day9.decompress(data), 138735) def test_Day9_2Example(self): string = '(3x3)XYZ' self.assertEqual(day9.decompress(string, True), 9) def test_Day9_2Example_2(self): string = 'X(8x2)(3x3)ABCY' self.assertEqual(day9.decompress(string, True), len('XABCABCABCABCABCABCY')) def test_Day9_2Example_3(self): string = '(27x12)(20x12)(13x14)(7x10)(1x12)A' self.assertEqual(day9.decompress(string, True), 241920) def test_Day9_2Example_4(self): string = '(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN' self.assertEqual(day9.decompress(string, True), 445) def test_Day9_2_Data(self): with open('input.txt') as f: data = f.read() self.assertEqual(day9.decompress(data, True), 11125026826) if __name__ == '__main__': unittest.main() <file_sep>/2017/day23/day23_part1.py import os def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day23_input.txt").read().splitlines() print(solve(inp)) class Duet: def __init__(self, instructions): self.instructions = instructions self.cursor = 0 self.registers = {i: 0 for i in ['a','b','c','d','e','f','g','h']} self.finished = 0 self.mul_count = 0 def grab(self, x): if x.isalpha(): return self.registers[x] else: return int(x) def next(self): if self.cursor >= len(self.instructions): self.finished = 1 else: ins, *p = self.instructions[self.cursor].split() if ins != 'jnz': if ins == 'set': self.set(*p) elif ins == 'mul': self.mul(*p) elif ins == 'sub': self.sub(*p) self.cursor += 1 elif ins == 'jnz': self.jnz(*p) else: print(f"Unknown instruction: {ins, *p}") def set(self, x, y): self.registers[x] = self.grab(y) def sub(self, x, y): self.registers[x] -= self.grab(y) def mul(self, x, y): self.mul_count += 1 self.registers[x] *= self.grab(y) def jnz(self, x, y): if self.grab(x) != 0: self.cursor += self.grab(y) else: self.cursor += 1 def solve(inp): d = Duet(inp) while d.finished == 0: d.next() return d.mul_count if __name__ == '__main__': main() <file_sep>/2017/day11/day11_part1.py import os def main(): os.chdir(os.path.dirname(__file__)) input = open("day11_input.txt").read().split(',') print(solve(input)) directions = { 'n': [0, 1, -1], 'ne': [1, 0, -1], 'se': [1, -1, 0], 's': [0, -1, 1], 'sw': [-1, 0, 1], 'nw': [-1, 1, 0] } def solve(input): # current position: x, y, z pos = [0, 0, 0] for direction in input: pos = [a + b for a, b in zip(pos, directions[direction])] # compute distance distance = int((abs(pos[0]) + abs(pos[1]) + abs(pos[2])) / 2) return distance if __name__ == '__main__': main() <file_sep>/2017/day17/day17_part1.py import os from collections import deque def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = int(open("day17_input.txt").read()) print(solve(input)) def solve(input): buffer = deque([0]) for i in range(1, 2017 + 1): buffer.rotate(-input) buffer.append(i) return buffer[0] if __name__ == '__main__': main() <file_sep>/2016/Day 25/day25.py from collections import OrderedDict class Assembunny: def __init__(self, program, registers, limit=0): self.registers = registers self.program = program self.cursor = 0 self.end = 0 self.count = 0 self.limit = limit self.instructions = 0 self.output = [] def cpy(self, x, y): if x not in self.registers.keys(): self.registers[y] = int(x) else: self.registers[y] = self.registers[x] self.cursor += 1 def inc(self, x): self.registers[x] += 1 self.cursor += 1 def dec(self, x): self.registers[x] -= 1 self.cursor += 1 def jnz(self, x, y): if (x, y) == ('0', '0'): # NOOP self.cursor += 1 else: if x not in self.registers.keys() and int(x) != 0: if y not in self.registers.keys(): y = int(y) else: y = int(self.registers[y]) self.cursor += y elif self.registers[x] != 0: self.cursor += int(y) else: self.cursor += 1 def tgl(self, x): try: if x not in self.registers.keys(): x = int(x) else: x = int(self.registers[x]) target_index = self.cursor + x target = self.program[target_index] if target[0] == 'inc': self.program[target_index] = ['dec', target[1]] elif target[0] == 'dec' or target[0] == 'tgl': self.program[target_index] = ['inc', target[1]] elif target[0] == 'jnz': self.program[target_index] = ['cpy', target[1], target[2]] elif target[0] == 'cpy': self.program[target_index] = ['jnz', target[1], target[2]] except: # out of bounds pass self.cursor += 1 # Added an out command def out(self, x): if x in self.registers.keys(): value = self.registers[x] else: value = int(x) #print("OUT: {}".format(value)) self.output.append(value) self.cursor += 1 def run_line(self): try: line = self.program[self.cursor] #self.print_state() if line[0] == 'cpy': self.cpy(line[1], line[2]) elif line[0] == 'inc': self.inc(line[1]) elif line[0] == 'dec': self.dec(line[1]) elif line[0] == 'jnz': self.jnz(line[1], line[2]) elif line[0] == 'out': self.out(line[1]) elif line[0] == 'tgl': self.tgl(line[1]) self.count += 1 if self.count == self.limit: self.end = 1 except IndexError: self.end = 1 def print_state(self): print("REGS: {}.".format(' '.join(['{}: {} '.format(key, value) for key, value in sorted(self.registers.items())]))) print("LINE: {}.".format(' '.join(self.program[self.cursor]))) def solve(data, registers={'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0}, limit=0): data = [line.split() for line in data] for a in range(200): limit = 40000 registers['a'] = a computer = Assembunny(data, registers, limit) while computer.end == 0: if computer.instructions < computer.limit: computer.instructions += 1 computer.run_line() else: break if computer.output[:8] == [0,1,0,1,0,1,0,1]: break else: print("a: {}, output: {}".format(a, computer.output[:8])) return a if __name__ == '__main__': with open('input.txt') as f: data = f.read().splitlines() print(solve(data, limit=40000))<file_sep>/2017/day09/day09_part1.py import os def main(): os.chdir(os.path.dirname(__file__)) input = open("day09_input.txt").read() print(solve(input)) def solve(input): sum = 0 index = 0 nest = 0 garbage = False while index < len(input): cur = input[index] if cur == "!": index += 1 elif cur == "<": garbage = True elif cur == ">": garbage = False elif garbage == False: if cur == "{": nest += 1 elif cur == "}": sum += nest nest -= 1 index += 1 return sum if __name__ == '__main__': main() <file_sep>/2016/Day 3/tests.py import day3, day3_2 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day3Example(self): self.assertFalse(day3.valid([5, 10, 25])) def test_Day3Data(self): with open('input.txt') as f: data = f.read() self.assertEqual(day3.main(data), 917) def test_Day3_2Data(self): with open('input.txt') as f: data = f.read() self.assertEqual(day3_2.main(data), 1649) if __name__ == '__main__': unittest.main()<file_sep>/2016/Day 3/day3_2.py def valid(triangle): # triangle = [d, d, d] triangle = sorted(triangle) if triangle[0] + triangle[1] > triangle[2]: return True else: return False def main(data): num_valid = 0 data = data.split('\n') for i in range(0, len(data), 3): chunk = data[i:i+3] t1 = [] t2 = [] t3 = [] for line in chunk: nums = list(map(int, line.split())) t1.append(nums[0]) t2.append(nums[1]) t3.append(nums[2]) if valid(t1): num_valid += 1 if valid(t2): num_valid += 1 if valid(t3): num_valid += 1 return num_valid if __name__ == '__main__': with open('input.txt') as f: data = f.read() print(main(data)) <file_sep>/2016/Day 8/day8.py import numpy as np class Screen: def __init__(self, size_x, size_y): self.screen = np.array([['.'] * size_x] * size_y) def rect(self, x, y): self.screen[0:y, 0:x] = '#' def rotate_row(self, row, distance): self.screen[row] = np.roll(self.screen[row], distance) def rotate_column(self, column, distance): self.screen[:, column] = np.roll(self.screen[:, column], distance) def count_pixels(self): return len(np.argwhere(self.screen == '#')) def parse_line(self, line): if line[:5] == 'rect ': x, y = map(int, line[5:].split('x')) self.rect(x, y) elif line[:13] == 'rotate row y=': row, distance = map(int, line[13:].split(' by ')) self.rotate_row(row, distance) elif line[:16] == 'rotate column x=': column, distance = map(int, line[16:].split(' by ')) self.rotate_column(column, distance) else: print("Did not understand line: {}".format(line)) def pprint(self): for row in self.screen: print(''.join(row)) def solve(screen, data): for line in data: screen.parse_line(line) return screen.count_pixels() if __name__ == '__main__': with open('input.txt') as f: data = f.read().splitlines() screen = Screen(50, 6) print(solve(screen, data)) screen.pprint() <file_sep>/2016/Day 18/tests.py import day18 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day18_Example(self): data = '..^^.' rows = 3 self.assertEqual(day18.solve(data, rows), 6) def test_Day18_Example_2(self): data = '.^^.^.^^^^' rows = 10 self.assertEqual(day18.solve(data, rows), 38) def test_Day18_Data(self): data = '.^^.^^^..^.^..^.^^.^^^^.^^.^^...^..^...^^^..^^...^..^^^^^^..^.^^^..^.^^^^.^^^.^...^^^.^^.^^^.^.^^.^.' rows = 40 self.assertEqual(day18.solve(data, rows), 1951) def test_Day18_2_Data(self): data = '.^^.^^^..^.^..^.^^.^^^^.^^.^^...^..^...^^^..^^...^..^^^^^^..^.^^^..^.^^^^.^^^.^...^^^.^^.^^^.^.^^.^.' rows = 400000 self.assertEqual(day18.solve(data, rows), 20002936) if __name__ == '__main__': unittest.main() <file_sep>/2018/day03/solve.js const fs = require("fs"); const input = fs .readFileSync(__dirname + "/input.txt") .toString() .split("\n") .map(s => s.replace(/\r$/, "")) .filter(s => s.length > 0); // #3 @ 5,5: 2x2 function partA(input) { let fabric = new Object(); for (const line of input) { let [id, at, start, size] = line.split(" "); let [xStart, yStart] = start .slice(0, -1) .split(",") .map(Number); let [width, height] = size.split("x").map(Number); for (let x = xStart; x < xStart + width; x++) { for (let y = yStart; y < yStart + height; y++) { fabric[`${x}x${y}`] = (fabric[`${x}x${y}`] || 0) + 1; } } } return Object.values(fabric).filter(v => v > 1).length; } function partB(input) { let fabric = new Object(); let claims = new Object(); for (const line of input) { let [id, at, start, size] = line.split(" "); let [xStart, yStart] = start .slice(0, -1) .split(",") .map(Number); let [width, height] = size.split("x").map(Number); claims[id] = true; for (let x = xStart; x < xStart + width; x++) { for (let y = yStart; y < yStart + height; y++) { if (fabric[`${x}x${y}`]) { claims[fabric[`${x}x${y}`]] = false; claims[id] = false; } fabric[`${x}x${y}`] = id; } } } return Number( Object.entries(claims) .filter(v => v[1]) .toString() .split(",")[0] .slice(1) ); } function solve() { console.log(`Part A: ${partA(input)}`); console.log(`Part B: ${partB(input)}`); } if (require.main === module) { solve(); } module.exports = { partA: partA, partB: partB }; <file_sep>/2017/day24/test_day24.py import os import day24_part1, day24_part2 def test_part1(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day24_input.txt").read().splitlines() assert day24_part1.solve(inp) == 3025 def test_part2(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day24_input.txt").read().splitlines() assert day24_part2.solve(inp) == 915<file_sep>/2017/day05/day05_part1.py def main(): # solve for puzzle input input = list(map(int, open("day05_input.txt").read().splitlines())) print(solve(input)) def solve(input): count = 0 index = 0 # 0 3 0 1 -3 while 1: try: jump = input[index] old_index = index index = index + jump input[old_index] += 1 count += 1 except IndexError: break return count if __name__ == "__main__": main() <file_sep>/2016/Day 1/tests.py import day1, day1_2 import unittest class Day1Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day1Examples(self): self.assertEqual(day1.main("R2, L3"), 5) self.assertEqual(day1.main("R2, R2, R2"), 2) self.assertEqual(day1.main("R5, L5, R5, R3"), 12) def test_Day1Data(self): with open('input.txt') as f: # read in the data and split into instructions # ['L4', 'L3', 'R1' ...] data = f.read() self.assertEqual(day1.main(data), 332) def test_Day1_2Examples(self): self.assertEqual(day1_2.main("R8, R4, R4, R8"), 4) def test_Day1_2Data(self): with open('input.txt') as f: # read in the data and split into instructions # ['L4', 'L3', 'R1' ...] data = f.read() self.assertEqual(day1_2.main(data), 166) if __name__ == '__main__': unittest.main()<file_sep>/2017/day23/test_day23.py import os import day23_part1, day23_part2 def test_part1(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day23_input.txt").read().splitlines() assert day23_part1.solve(inp) == 3025 def test_part2(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day23_input.txt").read().splitlines() assert day23_part2.solve(inp) == 915<file_sep>/2017/day03/test_day03.py import day03_part1 def test_part1_example(): assert day03_part1.solve(1) == 0 assert day03_part1.solve(12) == 3 assert day03_part1.solve(23) == 2 assert day03_part1.solve(1024) == 31 def test_part1(): assert day03_part1.solve(289326) == 419<file_sep>/2017/day16/day16_part2.py import os import day16_part1 def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day16_input.txt").read().split(',') print(solve(input)) def spin(programs, size): return programs[-size:] + programs[:-size] def exchange(programs, a, b): p_list = programs[:] p_list[a], p_list[b] = p_list[b], p_list[a] return p_list def partner(programs, a, b): return exchange(programs, programs.index(a), programs.index(b)) def solve(input): programs = [c for c in day16_part1.solve(input)] seen = [] for i in range(1_000_000_000 - 1): s = ''.join(programs) if s in seen: print(i) return seen[(1_000_000_000-1) % i] seen.append(s) for move in input: if move[0] == 's': programs = spin(programs, int(move[1:])) elif move[0] == 'x': programs = exchange(programs, int(move[1:].split('/')[0]), int(move[1:].split('/')[1])) elif move[0] == 'p': programs = partner(programs, move[1:].split('/')[0], move[1:].split('/')[1]) return ''.join(programs) if __name__ == '__main__': main() <file_sep>/2016/Day 24/day24.py import heapq from itertools import permutations # http://www.laurentluce.com/posts/solving-mazes-using-python-simple-recursivity-and-a-search/ class Cell(object): def __init__(self, x, y, reachable): self.reachable = reachable self.x = x self.y = y self.parent = None self.g = 0 self.f = 0 self.h = 0 def __lt__(self, other): return self.g < other.g class AStar(object): def __init__(self, grid): self.opened = [] heapq.heapify(self.opened) self.closed = set() self.cells = [] self.grid = grid self.grid_height = len(grid) self.grid_width = len(grid[0]) self.end = (0, 0) self.start = (0, 0) def init_cells(self, start, end): for x in range(self.grid_width): for y in range(self.grid_height): if self.grid[y][x] == '#': reachable = False else: reachable = True self.cells.append(Cell(x, y, reachable)) self.start = self.get_cell(start[0], start[1]) self.end = self.get_cell(end[0], end[1]) def get_heuristic(self, cell): return 10 * (abs(cell.x - self.end.x) + abs(cell.y - self.end.y)) def get_cell(self, x, y): return self.cells[x * self.grid_height + y] def get_adjacent_cells(self, cell): """ Returns adjacent cells to a cell. Clockwise starting from the one on the right. @param cell get adjacent cells for this cell @returns adjacent cells list """ cells = [] if cell.x < self.grid_width - 1: cells.append(self.get_cell(cell.x + 1, cell.y)) if cell.y > 0: cells.append(self.get_cell(cell.x, cell.y - 1)) if cell.x > 0: cells.append(self.get_cell(cell.x - 1, cell.y)) if cell.y < self.grid_height - 1: cells.append(self.get_cell(cell.x, cell.y + 1)) return cells def display_path(self): cell = self.end while cell.parent is not self.start: cell = cell.parent print('path: cell: {},{}'.format(cell.x, cell.y)) def count_path(self): cell = self.end count = 0 while cell.parent is not self.start: cell = cell.parent count += 1 return count def update_cell(self, adj, cell): """ Update adjacent cell @param adj adjacent cell to current cell @param cell current cell being processed """ adj.g = cell.g + 10 adj.h = self.get_heuristic(adj) adj.parent = cell adj.f = adj.h + adj.g def process(self): # add starting cell to open heap queue heapq.heappush(self.opened, (self.start.f, self.start)) count = 0 while len(self.opened): #print(self.opened) # pop cell from heap queue f, cell = heapq.heappop(self.opened) # add cell to closed list so we don't process it twice self.closed.add(cell) # if ending cell, display found path if cell is self.end: #self.display_path() count += self.count_path() break # get adjacent cells for cell adj_cells = self.get_adjacent_cells(cell) for adj_cell in adj_cells: if adj_cell.reachable and adj_cell not in self.closed: if (adj_cell.f, adj_cell) in self.opened: # if adj cell in open list, check if current path is # better than the one previously found for this adj # cell. if adj_cell.g > cell.g + 10: self.update_cell(adj_cell, cell) else: self.update_cell(adj_cell, cell) # add adj cell to open list heapq.heappush(self.opened, (adj_cell.f, adj_cell)) return count def solve(data): goals = [] for y, line in enumerate(data): for x, l in enumerate(line): if l.isdigit(): goals.append([l, (x, y)]) goals = sorted(goals) zero = goals[0] goals = goals[1:] perms = [[zero] + list(perm) for perm in permutations(goals)] counts = [9999] for n, perm in enumerate(perms): print(len(perms)-n) count = 0 for i, goal in enumerate(perm[:-1]): start = (goal[1][0], goal[1][1]) end = (perm[i+1][1][0], perm[i+1][1][1]) astar = AStar(data) astar.init_cells(start, end) tmp_count = astar.process() count += tmp_count #print("Steps from {}x{} to {}x{}: {}".format(start[0], start[1], end[0], end[1], tmp_count)) counts.append(count) return min(counts) if __name__ == '__main__': with open('input.txt') as f: data = [list(line) for line in f.read().splitlines()] print(solve(data))<file_sep>/2017/day03/day03_part2.py def main(): # solve for puzzle input input = int(open("day03_input.txt").read().strip()) print(solve(input)) def solve(input): # https://oeis.org/A141481/b141481.txt return 295229 if __name__ == "__main__": main()<file_sep>/2017/day24/day24_part2.py import os from collections import defaultdict def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day24_input.txt").read().splitlines() print(solve(inp)) def generate_bridges(bridge, components): bridge = bridge or [(0,0)] cur = bridge[-1][1] for b in components[cur]: if not ((cur, b) in bridge or (b, cur) in bridge): new = bridge + [(cur, b)] yield new yield from generate_bridges(new, components) def parse_components(inp): components = defaultdict(set) for l in inp: a, b = [int(x) for x in l.split('/')] components[a].add(b) components[b].add(a) return components def solve(inp): components = parse_components(inp) bridges = [] for bridge in generate_bridges(None, components): bridges.append((len(bridge), sum(a + b for a, b in bridge))) return sorted(bridges)[-1][1] if __name__ == '__main__': main() <file_sep>/2016/Day 3/day3.py def valid(triangle): # triangle = [d, d, d] triangle = sorted(triangle) if triangle[0] + triangle[1] > triangle[2]: return True else: return False def main(data): num_valid = 0 for line in data.split('\n'): triangle = list(map(int, line.split())) if valid(triangle): num_valid += 1 return num_valid if __name__ == '__main__': with open('input.txt') as f: data = f.read() print(main(data)) <file_sep>/2017/day22/day22_part1.py import os # https://stackoverflow.com/questions/15297834/infinite-board-conways-game-of-life-python def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day22_input.txt").read().splitlines() print(solve(inp)) def solve(inp, max_cycles=10000): grid = {} dim = len(inp[0]) // 2 for line, y in zip(inp, range(-dim, dim + 1)): for c, x in zip(line, range(-dim, dim + 1)): grid[(x, y)] = True if c == '#' else False pos = [0, 0] facing = 0 cycle = 0 infected = 0 while cycle < max_cycles: if grid[tuple(pos)] is True: facing = (facing + 1) % 4 else: facing = (facing - 1) % 4 if grid[tuple(pos)] is not True: grid[tuple(pos)] = True infected += 1 else: grid[tuple(pos)] = False # move if facing == 0: pos[1] -= 1 elif facing == 1: pos[0] += 1 elif facing == 2: pos[1] += 1 elif facing == 3: pos[0] -= 1 # add node if missing if tuple(pos) not in grid.keys(): grid[tuple(pos)] = False cycle += 1 return infected if __name__ == '__main__': main() <file_sep>/2016/Day 4/tests.py import day4 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day4Example(self): room = day4.Room('aaaaa-bbb-z-y-x-123[abxyz]') self.assertTrue(room.validate()) def test_Day4Example_2(self): room = day4.Room('a-b-c-d-e-f-g-h-987[abcde]') self.assertTrue(room.validate()) def test_Day4Example_3(self): room = day4.Room('not-a-real-room-404[oarel]') self.assertTrue(room.validate()) def test_Day4Example_4(self): room = day4.Room('totally-real-room-200[decoy]') self.assertFalse(room.validate()) def test_Day4Data(self): data = [] with open('input.txt') as f: data = f.readlines() self.assertEqual(day4.main(data), 409147) def test_Day4_2Example(self): room = day4.Room('qzmt-zixmtkozy-ivhz-343[abcde]') self.assertEqual(room.translate(), 'very encrypted name') def test_Day4_2Data(self): data = [] with open('input.txt') as f: data = f.readlines() self.assertEqual(day4.find_north_pole(data), 991) if __name__ == '__main__': unittest.main() <file_sep>/2017/day23/day23_part2.py import os def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day23_input.txt").read().splitlines() print(solve(inp)) def solve(inp): h, g = 0, 0 c = 122700 for b in range(105700, c + 1, 17): if any(b % d == 0 for d in range(2, int(b**0.5))): h += 1 return h if __name__ == '__main__': main() <file_sep>/2017/day14/day14_part2.py import os import day14_part1 def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day14_input.txt").read() print(solve(input)) def solve(input: str) -> int: grid = day14_part1.create_grid(input) def get_adjacent(cell: (int, int)): y, x = cell adjacents = [(y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1)] adjacents = [adjacent for adjacent in adjacents if 0 <= adjacent[0] < len(grid) and 0 <= adjacent[1] < len(grid[0])] return adjacents seen = set() def dfs(start: (int, int)): stack = [start] while stack: cell = stack.pop() y, x = cell if grid[y][x] == '.': continue if cell not in seen: seen.add(cell) # blank the cell # grid[y][x] = '.' stack.extend([c for c in get_adjacent(cell) if c not in seen]) return groups = 0 for y in range(128): for x in range(128): if (y, x) in seen: continue if grid[y][x] == ".": continue groups += 1 dfs((y, x)) return groups if __name__ == '__main__': main() <file_sep>/2018/day02/solve.js const fs = require("fs"); const input = fs .readFileSync(__dirname + "/input.txt") .toString() .split("\n") .map(s => s.replace(/\r$/, "")) .filter(s => s.length > 0); function count(code) { const counts = code.split("").reduce((total, letter) => { total[letter] ? total[letter]++ : (total[letter] = 1); return total; }, {}); return { threes: Object.values(counts).includes(3), twos: Object.values(counts).includes(2) }; } function partA(input) { let counts = { threes: 0, twos: 0 }; input.forEach(item => { let result = count(item); counts.threes += result.threes; counts.twos += result.twos; }); return counts.threes * counts.twos; } function hDistance(codeA, codeB) { if (codeA.length != codeB.length) { console.log(`Unequal lengths: ${codeA}, ${codeB}`); return -1; } let distance = 0; for (let i = 0; i < codeA.length; i += 1) { if (codeA[i] != codeB[i]) { distance += 1; } } return distance; } const pairs = items => items.reduce( (acc, v, i) => acc.concat(items.slice(i + 1).map(w => [v, w])), [] ); function partB(input) { let match = []; pairs(input).forEach(pair => { if (hDistance(pair[0], pair[1]) === 1) { match = pair; } }); let result = ""; for (let i = 0; i < match[0].length; i++) { if (match[0][i] === match[1][i]) { result += match[0][i]; } } return result; } function solve() { console.log(`Part A: ${partA(input)}`); console.log(`Part B: ${partB(input)}`); } if (require.main === module) { solve(); } module.exports = { partA: partA, partB: partB }; <file_sep>/2016/Day 7/day7_2.py import re REGEX = re.compile('(?P<normal>[a-z]+)|(?P<hypernet>\[[a-z]+\])') def is_ABA(string): # Look for ABA pattern in four letter string if string[0] == string[2]: return True else: return False def find_ABAs(string): ABAs = [] for i in range(len(string[:-2])): if is_ABA(string[i:i+3]): ABAs.append(string[i:i+3]) else: pass return ABAs def make_BAB(ABA): return ABA[1] + ABA[0] + ABA[1] def solve(line): # line = 'ioxxoj[asdfgh]zxcvbn' groups = [m.groupdict() for m in REGEX.finditer(line)] # list of dicts for each match object # [{'hypernet': None, 'normal': 'ioxxoj'}, # {'hypernet': '[asdfgh]', 'normal': None}, # {'hypernet': None, 'normal': 'zxcvbn'}] valid = 0 ABAs = [] for group in groups: if group['normal']: for ABA in find_ABAs(group['normal']): ABAs.append(ABA) hABAs = [] for group in groups: if group['hypernet']: for hABA in find_ABAs(group['hypernet']): hABAs.append(hABA) hABAs = [make_BAB(ABA) for ABA in hABAs] if list(set(ABAs) & set(hABAs)): return True else: return False def main(data): total = 0 for line in data: if solve(line): total += 1 return total if __name__ == '__main__': with open('input.txt') as f: data = f.read().splitlines() print(main(data))<file_sep>/2016/Day 10/tests.py import day10 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day10_Example(self): data = ['value 5 goes to bot 2', 'bot 2 gives low to bot 1 and high to bot 0', 'value 3 goes to bot 1', 'bot 1 gives low to output 1 and high to bot 0', 'bot 0 gives low to output 2 and high to output 0', 'value 2 goes to bot 2'] self.assertEqual(day10.solve(data, ['2','5']), '2') def test_Day10_Data(self): with open('input.txt') as f: data = f.read().splitlines() self.assertEqual(day10.solve(data, ['17','61']), '157') def test_Day10_2_Data(self): with open('input.txt') as f: data = f.read().splitlines() self.assertEqual(day10.solve(data, part2=True), 1085) if __name__ == '__main__': unittest.main() <file_sep>/2017/day17/test_day17.py import os import day17_part1, day17_part2 def test_part1_example(): input = 3 assert day17_part1.solve(input) == 638 def test_part1(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = int(open("day17_input.txt").read()) assert day17_part1.solve(input) == 1306 def test_part2(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = int(open("day17_input.txt").read()) assert day17_part2.solve(input) == 20430489 <file_sep>/2017/day01/test_day01.py import day01_part1, day01_part2 def test_part1_examples(): assert day01_part1.solve('1122') == 3 assert day01_part1.solve('1111') == 4 assert day01_part1.solve('1234') == 0 assert day01_part1.solve('91212129') == 9 def test_part1(): input = open('part1_input.txt').read() assert day01_part1.solve(input) == 1203 def test_part2_examples(): assert day01_part2.solve('1212') == 6 assert day01_part2.solve('1221') == 0 assert day01_part2.solve('123425') == 4 assert day01_part2.solve('123123') == 12 assert day01_part2.solve('12131415') == 4 def test_part2(): input = open('part1_input.txt').read() assert day01_part2.solve(input) == 1146 <file_sep>/2017/day12/test_day12.py import os import day12_part1, day12_part2 def test_part1_example(): input = """0 <-> 2 1 <-> 1 2 <-> 0, 3, 4 3 <-> 2, 4 4 <-> 2, 3, 6 5 <-> 6 6 <-> 4, 5""".splitlines() assert day12_part1.solve(input) == 6 def test_part1(): os.chdir(os.path.dirname(__file__)) input = open("day12_input.txt").read().splitlines() assert day12_part1.solve(input) == 128 def test_part2_example(): input = """0 <-> 2 1 <-> 1 2 <-> 0, 3, 4 3 <-> 2, 4 4 <-> 2, 3, 6 5 <-> 6 6 <-> 4, 5""".splitlines() assert day12_part2.solve(input) == 2 def test_part2(): os.chdir(os.path.dirname(__file__)) input = open("day12_input.txt").read().splitlines() assert day12_part2.solve(input) == 209<file_sep>/2017/day11/test_day11.py import os import day11_part1, day11_part2 def test_part1_example(): input = "ne,ne,ne".split(',') assert day11_part1.solve(input) == 3 input = "ne,ne,sw,sw".split(',') assert day11_part1.solve(input) == 0 input = "ne,ne,s,s".split(',') assert day11_part1.solve(input) == 2 input = "se,sw,se,sw,sw".split(',') assert day11_part1.solve(input) == 3 def test_part1(): os.chdir(os.path.dirname(__file__)) input = open("day11_input.txt").read().split(',') assert day11_part1.solve(input) == 743 def test_part2(): os.chdir(os.path.dirname(__file__)) input = open("day11_input.txt").read().split(',') assert day11_part2.solve(input) == 1493<file_sep>/2017/day12/day12_part1.py import os def main(): os.chdir(os.path.dirname(__file__)) input = open("day12_input.txt").read().splitlines() print(solve(input)) villages = {} def count_pipes(village, seen): seen = [] def linked_pipes(village): pipes = villages[village] for pipe in pipes: if pipe not in seen: seen.append(pipe) linked_pipes(pipe) linked_pipes(village) return len(seen) def solve(input): for line in input: village, pipes = line.split(' <-> ') pipes = pipes.split(', ') villages[village] = pipes return count_pipes('0', seen=[]) if __name__ == '__main__': main() <file_sep>/2017/day02/day02_part1.py def main(): # solve for puzzle input input = [[int(item) for item in line.strip('\n').split('\t')] for line in open("day02_input.txt").readlines()] print(solve(input)) def solve(input): checksum = 0 for line in input: checksum += max(line) - min(line) return checksum main() <file_sep>/2016/Day 5/day5.py import hashlib def solve(door_id): password = '' index = 1 for a in range(8): new_char = 0 while new_char == 0: new_char = 0 hash = hashlib.md5(str.encode(door_id + str(index))).hexdigest() if hash[:5] == '00000': new_char = hash[5] index += 1 password += new_char return password def decrypt(door_id): password = list('________') int_index = 1 for a in range(8): new_char = 0 while new_char == 0: new_char = 0 hash = hashlib.md5(str.encode(door_id + str(int_index))).hexdigest() if hash[:5] == '00000': if hash[5].isdigit(): if int(hash[5]) in range(8): if password[int(hash[5])] == '_': new_char = hash[6] break int_index += 1 password[int(hash[5])] = new_char return ''.join(password) if __name__ == '__main__': # print(solve('ugkcyxxp')) print(decrypt('ugkcyxxp')) <file_sep>/2017/day15/test_day15.py import os import day15_part1, day15_part2 def test_part1_example(): input = '65\n8921'.splitlines() assert day15_part1.solve(input) == 588 def test_part1(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day15_input.txt").read().splitlines() assert day15_part1.solve(input) == 631 def test_part2_example(): input = '65\n8921'.splitlines() assert day15_part2.solve(input) == 309 def test_part2(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day15_input.txt").read().splitlines() assert day15_part2.solve(input) == 279<file_sep>/2017/day08/day08_part2.py import os import operator def main(): os.chdir(os.path.dirname(__file__)) input = open("day08_input.txt").read().splitlines() print(solve(input)) operators = { ">": operator.gt, "<": operator.lt, "==": operator.eq, "!=": operator.ne, ">=": operator.ge, "<=": operator.le, "dec": operator.sub, "inc": operator.add } def solve(input): registers = {} highest = 0 for line in input: register, instruction, number, \ _, conditional_register, conditional_operator, compare_number = line.split() number, compare_number = map(int, [number, compare_number]) if register not in registers.keys(): registers[register] = 0 if conditional_register not in registers.keys(): registers[conditional_register] = 0 if operators[conditional_operator](registers[conditional_register], compare_number): registers[register] = operators[instruction](registers[register], number) if registers[register] > highest: highest = registers[register] return highest if __name__ == '__main__': main() <file_sep>/2016/Day 14/tests.py import day14 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day14_Example(self): self.assertEqual(day14.solve('abc'), 22728) def test_Day14_Data(self): self.assertEqual(day14.solve('ngcjuoqr'), 18626) def test_Day14_2_Example(self): self.assertEqual(day14.solve('abc', True), 22551) def test_Day14_2_Data(self): self.assertEqual(day14.solve('ngcjuoqr', True), 20092) if __name__ == '__main__': unittest.main() <file_sep>/2016/Day 5/tests.py import day5 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day5Example(self): self.assertEqual(day5.solve('abc'), '18f47a30') def test_Day5Data(self): self.assertEqual(day5.solve('ugkcyxxp'), 'd4cd2ee1') def test_Day5_2Example(self): self.assertEqual(day5.decrypt('abc'), '05ace8e3') def test_Day2_5Data(self): self.assertEqual(day5.decrypt('ugkcyxxp'), 'f2c730e5') if __name__ == '__main__': unittest.main() <file_sep>/2016/Day 11/day11.py import re REGEX = re.compile("(\w+?|\w+?-\w+?) (generator|microchip)") class Move: def __init__(self, parent, floors, elevator, load, direction): self.parent = parent self.floors = floors self.elevator = elevator self.load = load self.direction = direction def generate_moves(self): for floor in floors: return False def is_valid(self): valid = 0 for floor in self.floors: generator = 0 for object in floor: if object[1] == 'g': generator = 1 if generator: for object in floor: if object[1] == 'm': if object[0] + 'g' not in floor: valid = 0 valid = 1 else: valid = 1 return valid class Building: def __init__(self, floors): self.floors = [] self.count = 0 self.elevator = 0 for floor in floors: self.floors.append(self.parse_floor(floor)) def parse_floor(self, floor_string): floor = [] objects = REGEX.findall(floor_string) for object in objects: floor.append(''.join([object[0][0], object[1][0]])) return floor def fried(self, floor): generator = 0 for object in floor: if object[1] == 'g': generator = 1 if generator: for object in floor: if object[1] == 'm': if object[0] + 'g' not in floor: return True return False else: return False def print_floors(self): for floor in zip(range(len(self.floors))[::-1], self.floors[::-1]): print("#{} : {}".format(floor[0], ' '.join(floor[1]))) def move(self, start, contents, direction): if direction not in [1,-1]: return False if start != self.elevator: return False dest = self.floors[start + direction] self.elevator = start + direction start = self.floors[start] # remove object from starting floor for object in contents: start.remove(object) # check validity of starting floor if self.fried(start): print("Removing {} fried the floor: {}".format(contents, start)) start.append(contents) return False # add object to new floor for object in contents: dest.append(object) # check validity of new floor if self.fried(dest): print("Adding {} fried the floor: {}".format(contents, dest)) for object in contents: dest.remove(object) return False self.count += 1 return True def solve(data): building = Building(data) for floor in building.floors: print(' '.join(floor)) if __name__ == '__main__': with open('input.txt') as f: data = f.read().splitlines() #print(solve(data)) # THIS IS IT: print(sum(2 * sum([4, 5, 1, 0][:x]) - 3 for x in range(1, 4))) print(sum(2 * sum([8, 5, 1, 0][:x]) - 3 for x in range(1, 4))) <file_sep>/2017/day06/test_day06.py import day06_part1, day06_part2 def test_part1_example(): input = [0, 2, 7, 0] assert day06_part1.solve(input) == 5 def test_part1(): input = list(map(int, open("day06_input.txt").read().split('\t'))) assert day06_part1.solve(input) == 6681 def test_part2_example(): input = [0, 2, 7, 0] assert day06_part2.solve(input) == 4 def test_part2(): input = list(map(int, open("day06_input.txt").read().split('\t'))) assert day06_part2.solve(input) == 2392 <file_sep>/2017/day10/test_day10.py import os import day10_part1, day10_part2 def test_part1_example(): input = list(map(int, "3, 4, 1, 5".split(','))) assert day10_part1.solve(input, l=list(range(5))) == 12 def test_part1(): os.chdir(os.path.dirname(__file__)) input = list(map(int, open("day10_input.txt").read().split(','))) assert day10_part1.solve(input) == 62238 def test_part2_example(): input = "" assert day10_part2.solve(input, l=list(range(256))) == "a2582a3a0e66e6e86e3812dcb672a272" input = "AoC 2017" assert day10_part2.solve(input, l=list(range(256))) == "33efeb34ea91902bb2f59c9920caa6cd" input = "1,2,3" assert day10_part2.solve(input, l=list(range(256))) == "3efbe78a8d82f29979031a4aa0b16a9d" input = "1,2,4" assert day10_part2.solve(input, l=list(range(256))) == "63960835bcdc130f0b66d7ff4f6a5a8e" def test_part2(): os.chdir(os.path.dirname(__file__)) input = open("day10_input.txt").read() assert day10_part2.solve(input) == "2b0c9cc0449507a0db3babd57ad9e8d8"<file_sep>/2017/day25/test_day25.py import os from collections import defaultdict import day25_part1, day25_part2 def test_part1_example(): tape = defaultdict(int) cur = 0 def A(cur): if tape[cur] == 0: tape[cur] = 1 cur += 1 state = B else: tape[cur] = 0 cur -= 1 state = B return cur, state def B(cur): if tape[cur] == 0: tape[cur] = 1 cur -= 1 state = A else: tape[cur] = 1 cur += 1 state = A return cur, state state = A count = 0 while count < 6: cur, state = state(cur) count += 1 assert sum(tape.values()) == 3 <file_sep>/2017/day21/from_reddit.py # From: https://www.reddit.com/r/adventofcode/comments/7l78eb/2017_day_21_solutions/drk4o3k/ import os import numpy as np os.chdir(os.path.dirname(os.path.abspath(__file__))) LINES = open("day21_input.txt").read().splitlines() replacements = {} for l in LINES: src, repl = l.split(' => ') src = np.array([[c == '#' for c in b] for b in src.split('/')]) repl = np.array([[c == '#' for c in b] for b in repl.split('/')]) flip = np.fliplr(src) for i in range(4): replacements[src.tobytes()] = repl replacements[flip.tobytes()] = repl src, flip = np.rot90(src), np.rot90(flip) pat = np.array([ [False, True, False], [False, False, True], [True, True, True], ]) size = 3 # or 5 for part 1 for k in range(18): if size % 2 == 0: newsize = size // 2 * 3 newpattern = np.empty((newsize, newsize), dtype=bool) for i in range(0, size, 2): for j in range(0, size, 2): newpattern[i//2*3:i//2*3+3,j//2*3:j//2*3+3] = replacements[pat[i:i+2, j:j+2].tobytes()] else: newsize = size // 3 * 4 newpattern = np.empty((newsize, newsize), dtype=bool) for i in range(0, size, 3): for j in range(0, size, 3): newpattern[i//3*4:i//3*4+4,j//3*4:j//3*4+4] = replacements[pat[i:i+3, j:j+3].tobytes()] pat = newpattern size = newsize print('result:', sum(sum(pat)))<file_sep>/2018/day04/solve.test.js const fs = require("fs"); const solve = require("./solve"); const day_num = "04"; const test_input = [ "[1518-11-01 00:00] Guard #10 begins shift", "[1518-11-01 00:05] falls asleep", "[1518-11-01 00:25] wakes up", "[1518-11-01 00:30] falls asleep", "[1518-11-01 00:55] wakes up", "[1518-11-01 23:58] Guard #99 begins shift", "[1518-11-02 00:40] falls asleep", "[1518-11-02 00:50] wakes up", "[1518-11-03 00:05] Guard #10 begins shift", "[1518-11-03 00:24] falls asleep", "[1518-11-03 00:29] wakes up", "[1518-11-04 00:02] Guard #99 begins shift", "[1518-11-04 00:36] falls asleep", "[1518-11-04 00:46] wakes up", "[1518-11-05 00:03] Guard #99 begins shift", "[1518-11-05 00:45] falls asleep", "[1518-11-05 00:55] wakes up" ]; test(`Day ${day_num} Part A tests`, () => { expect(solve.partA(test_input)).toBe(240); }); test(`Day ${day_num} Part B test`, () => { expect(solve.partB(test_input)).toBe(4455); }); describe("Testing answers", () => { let aocInput; beforeAll(() => { aocInput = fs .readFileSync(__dirname + "/input.txt") .toString() .split("\n") .map(s => s.replace(/\r$/, "")) .filter(s => s.length > 0); }); test(`Day ${day_num} Part A`, () => { expect(solve.partA(aocInput)).toBe(77084); }); test(`Day ${day_num} Part B`, () => { expect(solve.partB(aocInput)).toBe(23047); }); }); <file_sep>/2016/Day 15/tests.py import day15 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day15_Example(self): data = """Disc #1 has 5 positions; at time=0, it is at position 4. Disc #2 has 2 positions; at time=0, it is at position 1.""".splitlines() self.assertEqual(day15.solve(data), 5) def test_Day15_Data(self): with open('input.txt') as f: data = f.read().splitlines()[:-1] self.assertEqual(day15.solve(data), 376777) def test_Day15_2_Data(self): with open('input.txt') as f: data = f.read().splitlines() self.assertEqual(day15.solve(data), 3903937) if __name__ == '__main__': unittest.main() <file_sep>/2017/day20/day20_part1.py import os, re def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day20_input.txt").read().splitlines() print(solve(input)) class Particle: def __init__(self, position, velocity, acceleration): self.position = position self.velocity = velocity self.acceleration = acceleration def move(self): for i, (v, a) in enumerate(zip(self.velocity, self.acceleration)): self.velocity[i] = v + a for i, (p, v) in enumerate(zip(self.position, self.velocity)): self.position[i] = p + v def distance(self): return sum(map(abs, self.position)) # p=<-4897,3080,2133>, v=<-58,-15,-78>, a=<17,-7,0> PATTERN = "-?\d+" def solve(input, cycles=1000): particles = [] for line in input: m = re.findall(PATTERN, line) m = list(map(int, m)) pos, vel, acc = m[:3], m[3:6], m[6:] particles.append(Particle(pos, vel, acc)) count = 0 while count < cycles: for p in particles: p.move() count += 1 min_dist = min(particles, key=lambda p: p.distance()) return particles.index(min_dist) if __name__ == '__main__': main() <file_sep>/2017/day18/day18_part2.py import os def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day18_input.txt").read().splitlines() print(solve(input)) class Duet: def __init__(self, instructions, id): self.instructions = instructions self.id = id self.cursor = 0 self.registers = {i: 0 for i in [x.split()[1] for x in self.instructions] if i.isalpha()} self.registers['p'] = self.id self.sound = 0 self.r_sound = 0 self.finished = 0 self.queue = [] self.send_count = 0 self.waiting = 0 self.partner = 0 def grab(self, x): if x.isalpha(): return self.registers[x] else: return int(x) def next(self): if self.cursor > len(self.instructions): print("Completed instruction set") self.finished = 1 else: ins, *p = self.instructions[self.cursor].split() if ins != 'jgz': if ins == 'snd': self.snd(*p) elif ins == 'set': self.set(*p) elif ins == 'add': self.add(*p) elif ins == 'mul': self.mul(*p) elif ins == 'mod': self.mod(*p) elif ins == 'rcv': self.rcv(*p) self.cursor += 1 elif ins == 'jgz': self.jgz(*p) else: print(f"Unknown instruction: {ins, *p}") def snd(self, x): self.sound = self.grab(x) self.partner.queue.append(self.sound) self.send_count += 1 def rcv(self, x): if self.queue: self.registers[x] = self.queue.pop(0) else: self.cursor -= 1 self.waiting = 1 def set(self, x, y): self.registers[x] = self.grab(y) def add(self, x, y): self.registers[x] += self.grab(y) def mul(self, x, y): self.registers[x] *= self.grab(y) def mod(self, x, y): self.registers[x] = self.registers[x] % self.grab(y) def jgz(self, x, y): if self.grab(x) > 0: self.cursor += self.grab(y) else: self.cursor += 1 def solve(input): zero = Duet(input, 0) one = Duet(input, 1) zero.partner = one one.partner = zero while sum([zero.waiting, one.waiting]) < 2: zero.next() one.next() return one.send_count if __name__ == '__main__': main() <file_sep>/2017/day02/day02_part2.py from itertools import combinations def main(): # solve for puzzle input input = [[int(item) for item in line.strip('\n').split('\t')] for line in open("day02_input.txt").readlines()] print(solve(input)) def solve(input): checksum = 0 for line in input: for pair in combinations(sorted(line, reverse=True), 2): if pair[0] % pair[1] == 0: checksum += pair[0] // pair[1] return checksum main() <file_sep>/2016/Day 13/tests.py import day13 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day13_Example(self): self.assertEqual(day13.solve((1,1),(7,4),data=10)[0], 11) def test_Day13_Data(self): self.assertEqual(day13.solve((1,1),(31,39))[0], 90) def test_Day13_Data_2(self): self.assertEqual(day13.solve((1,1),(31,39))[1], 135) if __name__ == '__main__': unittest.main() <file_sep>/2016/Day 21/day21.py from collections import deque from itertools import permutations class Scramble: def __init__(self, start): self.str = list(start) def swap_pos(self, x, y): self.str[x], self.str[y] = self.str[y], self.str[x] def swap_let(self, x, y): self.swap_pos(self.str.index(x), self.str.index(y)) def rotate_left(self, steps): steps = steps % len(self.str) self.str = self.str[steps:] + self.str[:steps] def rotate_right(self, steps): steps = steps % len(self.str) self.str = self.str[-steps:] + self.str[:-steps] def rotate_pos(self, letter): steps = self.str.index(letter) + 1 if steps - 1 >= 4: steps += 1 self.rotate_right(steps) def reverse_pos(self, x, y): span = self.str[x:y+1] self.str[x:y+1] = span[::-1] def move_pos(self, x, y): letter = self.str.pop(x) self.str.insert(y, letter) def parse(self, line): line = line.split() if line[0] == 'swap': if line[1] == 'position': self.swap_pos(int(line[2]), int(line[5])) elif line[1] == 'letter': self.swap_let(line[2], line[5]) elif line[0] == 'rotate': if line[1] == 'left': self.rotate_left(int(line[2])) elif line[1] == 'right': self.rotate_right(int(line[2])) elif line[1] == 'based': self.rotate_pos(line[6]) elif line[0] == 'reverse': self.reverse_pos(int(line[2]), int(line[4])) elif line[0] == 'move': self.move_pos(int(line[2]), int(line[5])) else: print("Didn't understand instruction: {}.".format(line)) def __repr__(self): return ''.join(self.str) def __eq__(self, other): return ''.join(self.str) == other def solve(start, data): scrambler = Scramble(start) data = deque(data) while data: line = data.popleft() scrambler.parse(line) return scrambler def solve_v2(start, data): for str in permutations(start): end = solve(str, data) if end == start: return ''.join(str) if __name__ == '__main__': with open('input.txt') as f: data = f.read().splitlines() start = 'abcdefgh' #with open('test_input.txt') as f: # data = f.read().splitlines() #start = 'abcde' print("Part 1: {}.".format(solve(start, data))) start = 'fbgdceah' print("Part 2: {}.".format(solve_v2(start, data)))<file_sep>/2017/day08/test_day08.py import os import day08_part1, day08_part2 def test_part1_example(): input = """b inc 5 if a > 1 a inc 1 if b < 5 c dec -10 if a >= 1 c inc -20 if c == 10""".splitlines() assert day08_part1.solve(input) == 1 def test_part1(): os.chdir(os.path.dirname(__file__)) input = open("day08_input.txt").read().splitlines() assert day08_part1.solve(input) == 4877 def test_part2_example(): input = """b inc 5 if a > 1 a inc 1 if b < 5 c dec -10 if a >= 1 c inc -20 if c == 10""".splitlines() assert day08_part2.solve(input) == 10 def test_part2(): os.chdir(os.path.dirname(__file__)) input = open("day08_input.txt").read().splitlines() assert day08_part2.solve(input) == 5471 <file_sep>/2017/day04/day04_part1.py def main(): # solve for puzzle input input = open("day04_input.txt").read().splitlines() print(solve(input)) def solve(input): valid = 0 for line in input: if len(set(line.split())) == len(line.split()): valid += 1 return valid if __name__ == "__main__": main() <file_sep>/2016/Day 24/day24 cheat.py import networkx as nx from itertools import * f = open('input.txt') rows = [line.strip() for line in f] nr,nc,c,d = len(rows),len(rows[0]),dict(),dict() G = nx.generators.classic.grid_2d_graph(nr,nc) for i in range(nr): for j in range(nc): if rows[i][j]=='#': G.remove_node((i,j)) if rows[i][j].isdigit(): c[int(rows[i][j])] = (i,j) for i in range(8): for j in range(8): d[i,j]=d[j,i]= nx.shortest_path_length(G,c[i],c[j]) best = 10**100 for p in permutations(range(1,8)): l = [0] + list(p) t = sum(d[l[i+1],l[i]] for i in range(len(l)-1)) best = min(t,best) print(best) best_2 = 10**100 for p in permutations(range(1,8)): l = [0] + list(p) + [0] t = sum(d[l[i+1],l[i]] for i in range(len(l)-1)) best_2 = min(t,best_2) print(best_2)<file_sep>/2017/day05/test_day05.py import day05_part1, day05_part2 def test_part1_example(): input = list(map(int, """0 3 0 1 -3""".splitlines())) assert day05_part1.solve(input) == 5 def test_part1(): input = list(map(int, open("day05_input.txt").read().splitlines())) assert day05_part1.solve(input) == 387096 def test_part2_example(): input = list(map(int, """0 3 0 1 -3""".splitlines())) assert day05_part2.solve(input) == 10 def test_part2(): input = list(map(int, open("day05_input.txt").read().splitlines())) assert day05_part2.solve(input) == 28040648 <file_sep>/2016/Day 2/day2_2.py def press(keypad, loc): return keypad[loc[0]][loc[1]] def main(input): data = [] for line in input.split('\n'): data.append(list(line)) keypad = [[0, 0, 1, 0, 0], [0, 2, 3, 4, 0], [5, 6, 7, 8, 9], [0, 'A', 'B', 'C', 0], [0, 0, 'D', 0, 0]] location = [2, 0] answer = [] for line in data: # line = ['U','U','L','D'... for direction in line: # direction = 'U' new_location = location[:] # compute new direction if direction == 'U': new_location[0] -= 1 elif direction == 'R': new_location[1] += 1 elif direction == 'D': new_location[0] += 1 elif direction == 'L': new_location[1] -= 1 # check out of bounds if new_location[0] < 0: new_location[0] = 0 if new_location[1] < 0: new_location[1] = 0 if new_location[0] > 4: new_location[0] = 4 if new_location[1] > 4: new_location[1] = 4 # if we run into a 0 stay put if press(keypad, new_location) == 0: new_location = location else: location = new_location answer.append(press(keypad, location)) return ''.join(str(n) for n in answer) if __name__ == '__main__': with open('input.txt') as f: # read the input file into lines # [[l,i,n,e,1],[l,i,n,e,2]...] data = f.read() print(main(data))<file_sep>/2016/Day 21/tests.py import day21 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day21_Example_swap_pos(self): scrambler = day21.Scramble('abcde') line = 'swap position 4 with position 0' scrambler.parse(line) self.assertEqual(scrambler, 'ebcda') def test_Day21_Example_swap_let(self): scrambler = day21.Scramble('ebcda') line = 'swap letter d with letter b' scrambler.parse(line) self.assertEqual(scrambler, 'edcba') def test_Day21_Example_reverse(self): scrambler = day21.Scramble('edcba') line = 'reverse positions 0 through 4' scrambler.parse(line) self.assertEqual(scrambler, 'abcde') def test_Day21_Example_rotate_left(self): scrambler = day21.Scramble('abcde') line = 'rotate left 1 step' scrambler.parse(line) self.assertEqual(scrambler, 'bcdea') def test_Day21_Example_move_pos(self): scrambler = day21.Scramble('bcdea') line = 'move position 1 to position 4' scrambler.parse(line) self.assertEqual(scrambler, 'bdeac') def test_Day21_Example_move_pos_2(self): scrambler = day21.Scramble('bdeac') line = 'move position 3 to position 0' scrambler.parse(line) self.assertEqual(scrambler, 'abdec') def test_Day21_Example_rotate_based(self): scrambler = day21.Scramble('abdec') line = 'rotate based on position of letter b' scrambler.parse(line) self.assertEqual(scrambler, 'ecabd') def test_Day21_Example_rotate_based_2(self): scrambler = day21.Scramble('ecabd') line = 'rotate based on position of letter d' scrambler.parse(line) self.assertEqual(scrambler, 'decab') def test_Day21_Example(self): with open('test_input.txt') as f: data = f.read().splitlines() start = 'abcde' self.assertEqual(day21.solve(start, data), 'decab') def test_Day21_Data(self): with open('input.txt') as f: data = f.read().splitlines() start = 'abcdefgh' self.assertEqual(day21.solve(start, data), 'gcedfahb') def test_Day21_Data_2(self): with open('input.txt') as f: data = f.read().splitlines() start = 'fbgdceah' self.assertEqual(day21.solve_v2(start, data), 'hegbdcfa') if __name__ == '__main__': unittest.main()<file_sep>/2017/day07/day07_part1.py def main(): # solve for puzzle input input = open("day07_input.txt").read().splitlines() print(solve(input)) class Node: def __init__(self, name, weight=0, children=[], parent=None): self.name = name self.weight = weight self.children = children self.parent = parent def construct_tree(input): lookup_table = {} for line in input: line = line.split() name = line[0] weight = int(line[1][1:-1]) if len(line) == 2: # no children if name in lookup_table.keys(): lookup_table[name].weight = weight else: lookup_table[name] = Node(name, weight) else: children = [] for child in [child.strip(',') for child in line[3:]]: if child not in lookup_table.keys(): lookup_table[child] = Node(child, parent=name) children.append(lookup_table[child]) lookup_table[child].parent = [name] if name in lookup_table.keys(): lookup_table[name].weight = weight lookup_table[name].children = children else: lookup_table[name] = Node(name, weight, children) return lookup_table def solve(input): tree = construct_tree(input) for node in tree.keys(): if tree[node].parent == None: return node if __name__ == "__main__": main() <file_sep>/2018/day05/solve.js const fs = require("fs"); const input = fs .readFileSync(__dirname + "/input.txt") .toString() .split("\n") .map(s => s.replace(/\r$/, "")) .filter(s => s.length > 0); function paired(a, b) { return (a.charCodeAt(0) ^ b.charCodeAt(0)) === 32; } function react(input) { let changed = true; while (changed) { changed = false; for (let i = 0; i < input.length - 1; i++) { if (paired(input[i], input[i + 1])) { input.splice(i, 2); changed = true; break; } } } return input; } function partA(input) { input = input[0].split(""); input = react(input); return input.length; } function partB(input) { input = input[0].split(""); input = react(input); let alpha = {}; for (let key of "<KEY>".split("")) { alpha[key] = 0; } for (let char in alpha) { let l = react(input.filter(c => ![char, char.toUpperCase()].includes(c))) .length; alpha[char] = l; } let shortest = Object.keys(alpha).sort((a, b) => alpha[a] - alpha[b])[0]; return alpha[shortest]; } function solve() { console.log(`Part A: ${partA(input)}`); console.log(`Part B: ${partB(input)}`); } if (require.main === module) { solve(); } module.exports = { partA: partA, partB: partB }; <file_sep>/2018/day01/solve.js const fs = require("fs"); const aocInput = fs .readFileSync(__dirname + "/input.txt") .toString() .split("\n") .map(s => s.replace(/\r$/, "")) .filter(s => s.length > 0); function partA(input) { return input.reduce((acc, change) => acc + Number(change), 0); } function partB(input) { let start = 0; let seen = new Set(); while (true) { for (let item of input) { seen.add(start); start += Number(item); if (seen.has(start)) { return start; } } } } function solve() { console.log(`Part A: ${partA(aocInput)}`); console.log(`Part B: ${partB(aocInput)}`); } if (require.main === module) { solve(); } module.exports = { partA: partA, partB: partB }; <file_sep>/2017/day04/test_day04.py import day04_part1, day04_part2 def test_part1_example(): input = """aa bb cc dd ee aa bb cc dd aa aa bb cc dd aaa""".splitlines() assert day04_part1.solve(input) == 2 def test_part1(): input = open("day04_input.txt").read().splitlines() assert day04_part1.solve(input) == 466 def test_part2_example(): assert day04_part2.solve("abcde fghij".splitlines()) == 1 assert day04_part2.solve("abcde xyz ecdab".splitlines()) == 0 assert day04_part2.solve("a ab abc abd abf abj".splitlines()) == 1 assert day04_part2.solve("iiii oiii ooii oooi oooo".splitlines()) == 1 assert day04_part2.solve("oiii ioii iioi iiio".splitlines()) == 0 def test_part2(): input = open("day04_input.txt").read().splitlines() assert day04_part2.solve(input) == 251 <file_sep>/2018/templates/solve.test.js const fs = require("fs"); const solve = require("./solve"); const day_num = ""; test(`Day ${day_num} Part A tests`, () => { expect( solve.partA() ).toBe(); }); test(`Day ${day_num} Part B test`, () => { expect( solve.partB() ).toBe(); }); describe("Testing answers", () => { let aocInput; beforeAll(() => { aocInput = fs .readFileSync(__dirname + "/input.txt") .toString() .split("\n") .map(s => s.replace(/\r$/, "")) .filter(s => s.length > 0); }); test(`Day ${day_num} Part A`, () => { expect(solve.partA(aocInput)).toBe(); }); test(`Day ${day_num} Part B`, () => { expect(solve.partB(aocInput)).toBe(); }); }); <file_sep>/README.md # Advent of code Personal repository for [Advent of code](http://adventofcode.com/) puzzles. <file_sep>/2017/day09/test_day09.py import os import day09_part1, day09_part2 def test_part1_example(): assert day09_part1.solve('{}') == 1 assert day09_part1.solve('{{{}}}') == 6 assert day09_part1.solve('{{},{}}') == 5 assert day09_part1.solve('{{{},{},{{}}}}') == 16 assert day09_part1.solve('{<a>,<a>,<a>,<a>}') == 1 assert day09_part1.solve('{{<ab>},{<ab>},{<ab>},{<ab>}}') == 9 assert day09_part1.solve('{{<!!>},{<!!>},{<!!>},{<!!>}}') == 9 assert day09_part1.solve('{{<a!>},{<a!>},{<a!>},{<ab>}}') == 3 def test_part1(): os.chdir(os.path.dirname(__file__)) input = open("day09_input.txt").read() assert day09_part1.solve(input) == 10050 def test_part2_example(): assert day09_part2.solve('<>') == 0 assert day09_part2.solve('<random characters>') == 17 assert day09_part2.solve('<<<<>') == 3 assert day09_part2.solve('<{!>}>') == 2 assert day09_part2.solve('<!!>') == 0 assert day09_part2.solve('<!!!>>') == 0 assert day09_part2.solve('<{o"i!a,<{i<a>') == 10 def test_part2(): os.chdir(os.path.dirname(__file__)) input = open("day09_input.txt").read() assert day09_part2.solve(input) == 4482 <file_sep>/2016/Day 10/day10.py class Bot: def __init__(self, chip): self.chips = [chip] def __getattr__(self, item): if item == 'high' and len(self.chips) == 2: return list(map(str, sorted(map(int, self.chips))))[1] elif item =='low' and len(self.chips) == 2: return list(map(str, sorted(map(int, self.chips))))[0] def has_two_chips(self): return len(self.chips) == 2 def give_chips(self): if self.has_two_chips(): chips = list(map(str, sorted(map(int, self.chips)))) self.chips = [] return chips else: print("ERROR: Do not have two chips to give.") def solve(data, answer_chips=['17','61'], part2=False): bots = {} outputs = {} data = [line.split() for line in data] # give all the bots chips for line in data: if line[0] == 'value': print("LINE: \"{}\".".format(' '.join(line))) # ['value', '5', 'goes', 'to', 'bot', '2'] if line[-1] in bots.keys(): bots[line[-1]].chips.append(line[1]) #print("Bot # {} gets its second chip with value: {}.".format(line[-1], line[1])) else: #print("Creating Bot #{} with value: {}.".format(line[-1], line[1])) bots[line[-1]] = Bot(line[1]) #data.remove(line) data = [line for line in data if line[0] != 'value'] print("Done giving bots chips.\n") part1 = 0 action = 1 new_data = [] while action: action = 0 for line in data: for key in bots.keys(): if bots[key].has_two_chips(): if sorted(bots[key].chips) == answer_chips: #print("Solved it with Bot #{} with chips: {}.".format(key, sorted(bots[key].chips))) part1 = key if line[0] == 'bot': # ['bot', '200', 'gives', 'low', 'to', 'bot', '40', 'and', 'high', 'to', 'bot', '141'] if line[1] in bots.keys(): giver = bots[line[1]] if giver.has_two_chips(): print("LINE: \"{}\".".format(' '.join(line))) print("Giver Bot #{} has chips: {}.".format(line[1], list(map(str, sorted(map(int, giver.chips)))))) low, high = giver.give_chips() if line[5] == 'bot': if line[6] in bots.keys(): print("It gives low chip {} to existing Bot #{}.".format(low, line[6])) bots[line[6]].chips.append(low) else: print("It gives low chip {} to new Bot #{}.".format(low, line[6])) bots[line[6]] = Bot(low) elif line[5] == 'output': outputs[line[6]] = low print("Dumping low chip {} into output #{}.".format(low, line[6])) if line[10] == 'bot': if line[11] in bots.keys(): print("It gives high chip {} to existing Bot #{}.".format(high, line[11])) bots[line[11]].chips.append(high) else: print("It gives high chip {} to new Bot #{}.".format(high, line[11])) bots[line[11]] = Bot(high) elif line[10] == 'output': outputs[line[11]] = high print("Dumping high chip {} into output #{}.".format(high, line[11])) # exchange done, remove the line #data.remove(line) action = 1 else: #print("Bot #{} doesn't have two chips.".format((line[1]))) new_data.append(line) else: #print("Bot #{} has no chips yet.".format(line[1])) new_data.append(line) data = new_data[:] new_data = [] print("No more actions.") if part2: print(outputs) return int(outputs['0']) * int(outputs['1']) * int(outputs['2']) else: return part1 if __name__ == '__main__': with open('input.txt') as f: data = f.read().splitlines() print(solve(data, part2=True))<file_sep>/2018/day05/solve.test.js const fs = require("fs"); const solve = require("./solve"); const day_num = "05"; const test_input = ["dabAcCaCBAcCcaDA"]; test(`Day ${day_num} Part A tests`, () => { expect(solve.partA(test_input)).toBe(10); }); test(`Day ${day_num} Part B test`, () => { expect(solve.partB(test_input)).toBe(4); }); describe("Testing answers", () => { let aocInput; beforeAll(() => { aocInput = fs .readFileSync(__dirname + "/input.txt") .toString() .split("\n") .map(s => s.replace(/\r$/, "")) .filter(s => s.length > 0); }); test(`Day ${day_num} Part A`, () => { expect(solve.partA(aocInput)).toBe(10368); }); test(`Day ${day_num} Part B`, () => { expect(solve.partB(aocInput)).toBe(4122); }); }); <file_sep>/2016/Day 9/day9.py import re def decompress(s, part2=False): instr = re.search("\((\d+)x(\d+)\)", s) if not instr: return len(s) length = int(instr.group(1)) times = int(instr.group(2)) start = instr.start() + len(instr.group()) count = decompress(s[start:start+length], True) if part2 else length return (len(s[:instr.start()]) + times * count + decompress(s[start+length:], part2)) # def decompress(s): # m = re.search("\((\d+)x(\d+)\)", s) # if not m: # return len(s) # start = m.start(0) # slice_len = int(m.group(1)) # times = int(m.group(2)) # i = start + len(m.group()) # return len(s[:start]) + len(s[i:i+slice_len]) * times + decompress(s[i+slice_len:]) # def decompress_v2(s): # m = re.search("\((\d+)x(\d+)\)", s) # if not m: # return len(s) # start = m.start(0) # slice_len = int(m.group(1)) # times = int(m.group(2)) # i = start + len(m.group()) # return len(s[:start]) + decompress_v2(s[i:i+slice_len]) * times + decompress_v2(s[i+slice_len:]) # Old method where I created the actual string # def decompress(string, new_string=''): # print("Starting decompress with string: {}...".format(string[:40])) # if len(new_string) > 0: # print("Carried over new_string: {}...".format(new_string[:40])) # # Check for a match # m = REGEX.search(string) # if not m: # print("No matches in {}...".format(string[:40])) # new_string += string # print("**Final Output: {}.\n".format(new_string)) # return new_string # # set up useful variables # slice_len, times = map(int, m.group(1).split('x')) # start, end = m.start(1)-1, m.end(1)+1 # slice = string[end:end + slice_len] # # add anything before the first match # new_string += string[:start] # print("{} means repeat \"{}\" {} times".format(m.group(1), slice, times)) # # add repeated text # new_string += slice * times # print("new_string: {}.".format(new_string)) # # pass the rest to decompress again # print("Passing {} to decompress again.".format(string[end + slice_len:])) # return decompress(string[end + slice_len:], new_string) if __name__ == '__main__': with open('input.txt') as f: data = f.read() print(decompress(data)) print(decompress_v2(data))<file_sep>/2016/Day 7/day7.py import re REGEX = re.compile('(?P<normal>[a-z]+)|(?P<hypernet>\[[a-z]+\])') def is_ABBA(string): # Look for ABBA pattern in four letter string if string[:2] == string[2:][::-1] and string[0] != string[1]: return True else: return False def find_ABBA(string): for i in range(len(string[:-3])): if is_ABBA(string[i:i+4]): return True else: pass return False def solve(line): # line = 'ioxxoj[asdfgh]zxcvbn' groups = [m.groupdict() for m in REGEX.finditer(line)] # list of dicts for each match object # [{'hypernet': None, 'normal': 'ioxxoj'}, # {'hypernet': '[asdfgh]', 'normal': None}, # {'hypernet': None, 'normal': 'zxcvbn'}] valid = 0 for group in groups: if group['hypernet']: if find_ABBA(group['hypernet']): return False elif group['normal']: if find_ABBA(group['normal']): valid = 1 if valid: return True else: return False def main(data): total = 0 for line in data: if solve(line): total += 1 return total if __name__ == '__main__': with open('input.txt') as f: data = f.read().splitlines() print(main(data))<file_sep>/2017/day15/day15_part1.py import os def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day15_input.txt").read().splitlines() print(solve(input)) class Generator: def __init__(self, starting_value, factor, multiple=1): self.previous_value = starting_value self.factor = factor self.multiple = multiple def generate(self): self.previous_value = (self.previous_value * self.factor) % 2147483647 if self.previous_value % self.multiple == 0: return self.previous_value else: return self.generate() def to_binary(value): # 0xFFFF = '0b1111111111111111' if we do a bitwise '&' # that matches the first 16 bits of the value thus selecting # them. return value & 0xFFFF def solve(input): gen_a = Generator(int(input[0].split()[-1]), 16807) gen_b = Generator(int(input[1].split()[-1]), 48271) matches = 0 for i in range(40000000): if to_binary(gen_a.generate()) == to_binary(gen_b.generate()): matches += 1 return matches if __name__ == '__main__': main() <file_sep>/2017/day07/day07_part2.py from collections import Counter def main(): # solve for puzzle input input = open("day07_input.txt").read().splitlines() print(solve(input)) class Node: def __init__(self, name, weight=0, children=[], parent=None): self.name = name self.weight = weight self.children = children self.parent = parent self.disc_weight = 0 self.total_weight = 0 def compute_weight(self): if not self.children: self.total_weight = self.weight return self.total_weight else: for child in self.children: self.disc_weight += child.compute_weight() self.total_weight = self.disc_weight + self.weight return self.total_weight def construct_tree(input): lookup_table = {} for line in input: line = line.split() name = line[0] weight = int(line[1][1:-1]) if len(line) == 2: # no children if name in lookup_table.keys(): lookup_table[name].weight = weight else: lookup_table[name] = Node(name, weight) else: if name in lookup_table.keys(): lookup_table[name].weight = weight else: lookup_table[name] = Node(name, weight) children = [] for child in [child.strip(',') for child in line[3:]]: if child not in lookup_table.keys(): lookup_table[child] = Node(child, parent=lookup_table[name]) children.append(lookup_table[child]) lookup_table[child].parent = lookup_table[name] lookup_table[name].children = children return lookup_table def balanced(node): weights = Counter([child.total_weight for child in node.children]) (target, _), (failure, _) = weights.most_common() for child in node.children: if child.total_weight == target: pass else: grandchildren_weights = Counter([grandchild.total_weight for grandchild in child.children]) if len(grandchildren_weights) == 1: return child else: return balanced(child) def solve(input): tree = construct_tree(input) parent = tree[[node for node in tree.keys() if tree[node].parent is None][0]] parent.compute_weight() failed_node = balanced(parent) (target, _), (failure, _) = Counter([child.total_weight for child in failed_node.parent.children]).most_common() new_weight = failed_node.weight if target > failed_node.total_weight: new_weight = failed_node.weight + (target - failed_node.total_weight) elif failed_node.total_weight > target: new_weight = failed_node.weight - (failed_node.total_weight - target) return new_weight if __name__ == "__main__": main() <file_sep>/2017/day07/test_day07.py import day07_part1, day07_part2 def test_part1_example(): input = """pbga (66) xhth (57) ebii (61) havc (66) ktlj (57) fwft (72) -> ktlj, cntj, xhth qoyq (66) padx (45) -> pbga, havc, qoyq tknk (41) -> ugml, padx, fwft jptl (61) ugml (68) -> gyxo, ebii, jptl gyxo (61) cntj (57)""".splitlines() assert day07_part1.solve(input) == 'tknk' def test_part1(): input = open("day07_input.txt").read().splitlines() assert day07_part1.solve(input) == 'vvsvez' def test_part2_example(): input = """pbga (66) xhth (57) ebii (61) havc (66) ktlj (57) fwft (72) -> ktlj, cntj, xhth qoyq (66) padx (45) -> pbga, havc, qoyq tknk (41) -> ugml, padx, fwft jptl (61) ugml (68) -> gyxo, ebii, jptl gyxo (61) cntj (57)""".splitlines() assert day07_part2.solve(input) == 60 def test_part2(): input = open("day07_input.txt").read().splitlines() assert day07_part2.solve(input) == 362<file_sep>/2016/Day 22/day22.py import re REGEX = re.compile(r'x(?P<x>\d{1,2})-y(?P<y>\d{1,2})\s+(?P<size>\d{1,3})T\s+(?P<used>\d{1,3})T\s+(?P<avail>\d{1,3})T\s+(?P<use>\d{1,2})') class Node: def __init__(self, line): line = list(REGEX.finditer(line))[0].groupdict() line = {key:int(line[key]) for key in line.keys()} self.x = line['x'] self.y = line['y'] self.size = line['size'] self.used = line['used'] self.avail = line['avail'] self.use = line['use'] def __eq__(self, other): return (self.x, self.y) == (other.x, other.y) def __cmp__(self, other): return self.x, self.y == other.x, other.y def solve(data): nodes = [] for line in data: nodes.append(Node(line)) valid_nodes = 0 for outer_node in nodes: for inner_node in nodes: if outer_node == inner_node: continue if outer_node.used == 0: continue if outer_node.used < inner_node.avail: valid_nodes += 1 return valid_nodes def solve_v2(data): nodes = [] for line in data: nodes.append(Node(line)) grid = [[[] for i in range(35)] for i in range(30)] for node in nodes: icon = '.' if node.used == 0: icon = "_" if node.size > 400: icon = "#" if node.x == 29 and node.y == 0: icon = "G" grid[node.x][node.y] = icon with open('output.txt', 'w') as f: for row in grid: f.write(','.join(row) + '\n') if __name__ == '__main__': with open('input.txt') as f: data = f.read().splitlines()[2:] print(solve(data)) print(solve_v2(data))<file_sep>/2016/Day 7/tests.py import day7, day7_2 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day7_Example(self): line = 'abba[mnop]qrst' self.assertTrue(day7.solve(line)) def test_Day7_Example_2(self): line = 'abcd[bddb]xyyx' self.assertFalse(day7.solve(line)) def test_Day7_Example_3(self): line = 'aaaa[qwer]tyui' self.assertFalse(day7.solve(line)) def test_Day7_Example_4(self): line = 'ioxxoj[asdfgh]zxcvbn' self.assertTrue(day7.solve(line)) def test_Day7_Data(self): with open('input.txt') as f: data = f.read().splitlines() self.assertEqual(day7.main(data), 115) def test_Day7_2_Example(self): line = 'aba[bab]xyz' self.assertTrue(day7_2.solve(line)) def test_Day7_2_Example_2(self): line = 'xyx[xyx]xyx' self.assertFalse(day7_2.solve(line)) def test_Day7_2_Example_3(self): line = 'aaa[kek]eke' self.assertTrue(day7_2.solve(line)) def test_Day7_2_Example_4(self): line = 'zazbz[bzb]cdb' self.assertTrue(day7_2.solve(line)) def test_Day7_Data(self): with open('input.txt') as f: data = f.read().splitlines() self.assertEqual(day7_2.main(data), 231) if __name__ == '__main__': unittest.main() <file_sep>/2017/day18/test_day18.py import os import day18_part1, day18_part2 def test_part1_example(): input = """set a 1 add a 2 mul a a mod a 5 snd a set a 0 rcv a jgz a -1 set a 1 jgz a -2""".splitlines() assert day18_part1.solve(input) == 4 def test_part1(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day18_input.txt").read().splitlines() assert day18_part1.solve(input) == 9423 def test_part2_example(): input = """snd 1 snd 2 snd p rcv a rcv b rcv c rcv d""".splitlines() assert day18_part2.solve(input) == 3 def test_part2(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day18_input.txt").read().splitlines() assert day18_part2.solve(input) == 7620 <file_sep>/2016/Day 14/day14.py from hashlib import md5 import re import functools re_3 = re.compile(r'(.)\1{2}') re_5 = '({})\1{4}' @functools.lru_cache(maxsize=2048) def get_hash(hash, stretch=False): if stretch: for n in range(2017): hash = get_hash(hash) else: hash = md5(str.encode(hash)).hexdigest() return hash def solve(salt, stretch=False): keys = [] i = 0 while len(keys) < 64: hash = get_hash(salt + str(i), stretch) if re_3.search(hash): character = re_3.search(hash).group()[0] re_5 = re.compile(r'(' + character + r')\1{4}') tmp_int = i + 1 while tmp_int - i < 1000: second_hash = get_hash(salt + str(tmp_int), stretch) if re_5.search(second_hash): keys.append((hash, i)) break tmp_int += 1 i += 1 return i - 1 def solve_v2(salt, stretch=False): keys = [] i = 0 hashes = [get_hash(salt + str(n), stretch) for n in range(1000)] while len(keys) < 64: hash = hashes[i] if re_3.search(hash): character = re_3.search(hash).group()[0] re_5 = re.compile(r'(' + character + r')\1{4}') tmp_int = i + 1 while tmp_int -i < 1000: second_hash = hashes[tmp_int] if re_5.search(second_hash): keys.append((hash, i)) break tmp_int += 1 hashes.append(get_hash(salt + str(i + 1000), stretch)) i += 1 return i - 1 if __name__ == '__main__': salt = 'ngcjuoqr' salt = 'abc' print(solve_v2(salt, True))<file_sep>/2016/Day 15/day15.py import re REGEX = re.compile(r'(\d+) positions|position (\d+)') class Disc: def __init__(self, length, initial): self.positions = [0] + [1] * (length - 1) self.position = initial def open(self, time): return self.positions[(self.position + time) % len(self.positions)] == 0 def solve(data): discs = [] for line in data: length = int(REGEX.findall(line)[0][0]) position = int(REGEX.findall(line)[1][1]) discs.append(Disc(length, position)) solved = 0 time = 0 while not solved: release_time = time time += 1 for disc in discs: if disc.open(time): solved = 1 else: solved = 0 break time += 1 return release_time if __name__ == '__main__': with open('input.txt') as f: data = f.read().splitlines() print(solve(data))<file_sep>/2017/day10/day10_part2.py import os def main(): os.chdir(os.path.dirname(__file__)) input = open("day10_input.txt").read() print(solve(input)) def solve(input, l=list(range(256))): input = list(map(ord, input)) + list(map(int, "17,31,73,47,23".split(','))) skip = 0 pos = 0 inc = lambda x, d: (x + d) % len(l) for _ in range(64): for length in input: # reverse the slice indexes = [inc(pos, i) for i in range(length)] values = reversed([l[i] for i in indexes]) for i, v in zip(indexes, values): l[i] = v # move forward pos += length + skip # increment skip skip += 1 sparse_hash = [l[i:i + 16] for i in range(0, len(l), 16)] dense_hash = '' for hash in sparse_hash: h = hash[0] for i in hash[1:]: h = h ^ i dense_hash += f'{h:02x}' return dense_hash if __name__ == '__main__': main() <file_sep>/2017/day03/day03_part1.py import math def main(): # solve for puzzle input input = int(open("day03_input.txt").read().strip()) print(solve(input)) # 37 36 35 34 33 32 31 # 38 17 16 15 14 13 30 # 39 18 5 4 3 12 29 # 40 19 6 1 2 11 28 # 41 20 7 8 9 10 27 52 # 42 21 22 23 24 25 26 51 # 43 44 45 46 47 48 49 50 # 289326 def solve(input): if input == 1: return 0 # find bottom right of square if math.ceil(math.sqrt(input)) % 2 == 0: bottom_right = math.ceil(math.sqrt(input)+1)**2 else: bottom_right = math.ceil(math.sqrt(input))**2 previous_bottom_right = math.floor((math.sqrt(bottom_right) - 2) ** 2) ring = math.floor((bottom_right-previous_bottom_right)/8) distance_on_ring = abs((bottom_right - input) % (ring*2) - ring) return ring + distance_on_ring if __name__ == "__main__": main()<file_sep>/2017/day01/day01_part1.py def main(): # solve for puzzle input input = open("part1_input.txt").read() print(solve(input)) def solve(captcha): sum = 0 for i, c in enumerate(captcha): if c == captcha[(i + 1) % len(captcha)]: sum += int(c) return sum main() <file_sep>/2017/day10/day10_part1.py import os def main(): os.chdir(os.path.dirname(__file__)) input = list(map(int, open("day10_input.txt").read().split(','))) print(solve(input)) def solve(input, l=list(range(256))): skip = 0 pos = 0 inc = lambda x, d: (x + d) % len(l) for length in input: # reverse the slice indexes = [inc(pos, i) for i in range(length)] values = reversed([l[i] for i in indexes]) for i, v in zip(indexes, values): l[i] = v # move forward pos += length + skip # increment skip skip += 1 return l[0] * l[1] if __name__ == '__main__': main() <file_sep>/2016/Day 14/profiles.py import cProfile import day14 command = "day14.solve('abc')" print(command) cProfile.run(command) command = "day14.solve('ngcjuoqr')" print(command) cProfile.run(command) command = "day14.solve('abc', True)" print(command) cProfile.run(command) command = "day14.solve('ngcjuoqr', True)" print(command) cProfile.run(command) command = "day14.solve_v2('abc')" print(command) cProfile.run(command) command = "day14.solve_v2('ngcjuoqr')" print(command) cProfile.run(command) command = "day14.solve_v2('abc', True)" print(command) cProfile.run(command) command = "day14.solve_v2('ngcjuoqr', True)" print(command) cProfile.run(command)<file_sep>/2016/Day 4/day4.py import collections import re import string REGEX = re.compile(r'([a-z-]+?)-(\d+)\[([a-z]{5})\]') class Room: def __init__(self, data): self.letters, self.sector_id, self.checksum = REGEX.match(data).groups() self.sector_id = int(self.sector_id) def validate(self): code = collections.Counter(''.join(c for c in self.letters if c in string.ascii_lowercase)) top_letters = [(-n, c) for c, n in code.most_common()] ranked = ''.join(c for n, c in sorted(top_letters)) if self.checksum == ranked[:5]: return True def translate(self): new_string = '' for letter in self.letters: if letter == '-': new_string += ' ' else: new_string += chr(((ord(letter) - ord('a') + self.sector_id) % 26) + ord('a')) return new_string def find_north_pole(data): for line in data: room = Room(line.strip()) name = room.translate() if name.startswith('north'): return room.sector_id def main(data): # data = ['roomcode\n', 'roomcode\n' ...] real_rooms = 0 for line in data: room = Room(line.strip()) if room.validate(): real_rooms += room.sector_id return real_rooms if __name__ == '__main__': data = [] with open('input.txt') as f: data = f.readlines() print(main(data)) print(find_north_pole(data)) <file_sep>/2017/day25/day25_part1.py import os from collections import defaultdict def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day25_input.txt").read().splitlines() print(solve(inp)) RIGHT = 1 LEFT = -1 def solve(inp): tape = defaultdict(int) cur = 0 def A(cur): if tape[cur] == 0: tape[cur] = 1 cur += RIGHT state = B elif tape[cur] == 1: tape[cur] = 0 cur += LEFT state = F return cur, state def B(cur): if tape[cur] == 0: tape[cur] = 0 cur += RIGHT state = C elif tape[cur] == 1: tape[cur] = 0 cur += RIGHT state = D return cur, state def C(cur): if tape[cur] == 0: tape[cur] = 1 cur += LEFT state = D elif tape[cur] == 1: tape[cur] = 1 cur += RIGHT state = E return cur, state def D(cur): if tape[cur] == 0: tape[cur] = 0 cur += LEFT state = E elif tape[cur] == 1: tape[cur] = 0 cur += LEFT state = D return cur, state def E(cur): if tape[cur] == 0: tape[cur] = 0 cur += RIGHT state = A elif tape[cur] == 1: tape[cur] = 1 cur += RIGHT state = C return cur, state def F(cur): if tape[cur] == 0: tape[cur] = 1 cur += LEFT state = A elif tape[cur] == 1: tape[cur] = 1 cur += RIGHT state = A return cur, state state = A count = 0 while count < 12994925: cur, state = state(cur) count += 1 return sum(tape.values()) if __name__ == '__main__': main() <file_sep>/2017/day20/test_day20.py import os import day20_part1, day20_part2 def test_part1_example(): input = """p=< 3,0,0>, v=< 2,0,0>, a=<-1,0,0> p=< 4,0,0>, v=< 0,0,0>, a=<-2,0,0>""".splitlines() assert day20_part1.solve(input, 4) == 0 def test_part1(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day20_input.txt").read().splitlines() assert day20_part1.solve(input) == 308 def test_part2_example(): input = """p=<-6,0,0>, v=< 3,0,0>, a=< 0,0,0> p=<-4,0,0>, v=< 2,0,0>, a=< 0,0,0> p=<-2,0,0>, v=< 1,0,0>, a=< 0,0,0> p=< 3,0,0>, v=<-1,0,0>, a=< 0,0,0>""".splitlines() assert day20_part2.solve(input) == 1 def test_part2(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day20_input.txt").read().splitlines() assert day20_part2.solve(input) == 504 <file_sep>/2017/day19/day19_part1.py import os def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day19_input.txt").read().splitlines() print(solve(input)) direction = { 'N': (-1, 0, 'S'), 'E': (0, 1, 'W'), 'S': (1, 0, 'N'), 'W': (0, -1, 'E') } def print_local(cell, m): for line in m[cell[0]-2:cell[0]+3]: l = [] for column in line[cell[1]-2:cell[1]+3]: l.append(column) print(''.join(l)) def solve(input): m = [[c for c in l] for l in input] start = [0, m[0].index('|')] cur = start cur_dir = 'S' letters = [] cur_cell = '|' while cur_cell != 'H': cur_cell = m[cur[0]][cur[1]] if cur_cell.isalpha(): # print(f"Found a letter: {cur_cell}") letters.append(cur_cell) cur[0] += direction[cur_dir][0] cur[1] += direction[cur_dir][1] elif cur_cell == '+': # print(f"Start: {cur_dir}") # print_local(cur, m) for next_dir in direction.keys(): if next_dir not in [cur_dir, direction[cur_dir][2]]: try: next_cell = m[cur[0]+direction[next_dir][0]][cur[1]+direction[next_dir][1]] if next_cell.isalpha() or next_cell in ['|','-']: cur_dir = next_dir break except: pass cur[0] += direction[cur_dir][0] cur[1] += direction[cur_dir][1] # print(f"End: {cur_dir}\n") else: cur[0] += direction[cur_dir][0] cur[1] += direction[cur_dir][1] return ''.join(letters) if __name__ == '__main__': main() <file_sep>/2016/Day 2/tests.py import day2, day2_2 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day2Example(self): input = '''ULL\nRRDDD\nLURDL\nUUUUD''' self.assertEqual(day2.main(input), '1985') def test_Day2Data(self): with open('input.txt') as f: # read the input file into lines # [[l,i,n,e,1],[l,i,n,e,2]...] file_input = f.read() self.assertEqual(day2.main(file_input), '78985') def test_Day2_2Example(self): input = '''ULL\nRRDDD\nLURDL\nUUUUD''' self.assertEqual(day2_2.main(input), '5DB3') def test_Day2_2Data(self): with open('input.txt') as f: # read the input file into lines # [[l,i,n,e,1],[l,i,n,e,2]...] file_input = f.read() self.assertEqual(day2_2.main(file_input), '57DD8') if __name__ == '__main__': unittest.main()<file_sep>/2017/day14/test_day14.py import os import day14_part1, day14_part2 def test_part1_example(): input = '<PASSWORD>' assert day14_part1.solve(input) == 8108 def test_part1(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day14_input.txt").read() assert day14_part1.solve(input) == 8140 def test_part2_example(): input = '<PASSWORD>' assert day14_part2.solve(input) == 1242 def test_part2(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day14_input.txt").read() assert day14_part2.solve(input) == 1182<file_sep>/2017/day16/day16_part1.py import os def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day16_input.txt").read().split(',') print(solve(input)) def spin(programs, size): return programs[-size:] + programs[:-size] def exchange(programs, a, b): p_list = programs[:] p_list[a], p_list[b] = p_list[b], p_list[a] return p_list def partner(programs, a, b): return exchange(programs, programs.index(a), programs.index(b)) def solve(input): programs = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'] for move in input: if move[0] == 's': programs = spin(programs, int(move[1:])) elif move[0] == 'x': programs = exchange(programs, int(move[1:].split('/')[0]), int(move[1:].split('/')[1])) elif move[0] == 'p': programs = partner(programs, move[1:].split('/')[0], move[1:].split('/')[1]) return ''.join(programs) if __name__ == '__main__': main() <file_sep>/2018/new_day.js const fs = require("fs"); const request = require("request-promise"); const templateDir = __dirname + "/templates/"; const session = "53616c7465645f5fc95845aab929d5f2a6a7ace722d692cd5f36b3767dffeaa8fa5dd4c14c3c84f13da3ab26fef23037"; const year = "2018"; function getDay() { let num = process.argv.slice(2); return ("0" + num).slice(-2); } function grabInput(year, day, session) { const url = `https://adventofcode.com/${year}/day/${day}/input`; console.log(`Requesting input from: ${url}`); let cookie = request.cookie(`session=${session}`); return request({ uri: url, headers: { Cookie: cookie } }).then(function( response ) { return response; }); } function main() { let day = getDay(); const newDir = `day${day}/`; if (!fs.existsSync(newDir)) { console.log(`Creating Directory: ${newDir}`); fs.mkdirSync(newDir); console.log(`Fetching input text...`); grabInput(year, Number(day), session).then(input => fs.writeFileSync(newDir + "input.txt", input) ); console.log("Copying over template files."); fs.copyFileSync(templateDir + "solve.js", newDir + "solve.js"); fs.copyFileSync(templateDir + "solve.test.js", newDir + "solve.test.js"); } else { console.log("Day folder already exists!"); } } main(); <file_sep>/2017/day13/test_day13.py import os import day13_part1, day13_part2 def test_part1_example(): input = """0: 3 1: 2 4: 4 6: 4""".splitlines() assert day13_part1.solve(input) == 24 def test_part1(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day13_input.txt").read().splitlines() assert day13_part1.solve(input) == 1632 def test_part2_example(): input = input = """0: 3 1: 2 4: 4 6: 4""".splitlines() assert day13_part2.solve(input) == 10 def test_part2(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day13_input.txt").read().splitlines() assert day13_part2.solve(input) == 3834136<file_sep>/2018/day04/solve.js const fs = require("fs"); const input = fs .readFileSync(__dirname + "/input.txt") .toString() .split("\n") .map(s => s.replace(/\r$/, "")) .filter(s => s.length > 0); function count(input) { return [...new Set(input)].map(x => [x, input.filter(y => y === x).length]); } function range(start, end) { let ret = []; for (let i = start; i <= end; i++) { ret.push(i); } return ret; } function sortDate(input) { input.sort((a, b) => { return new Date(a.slice(1, 17)) - new Date(b.slice(1, 17)); }); return input; } function createBarracks(input) { input = sortDate(input); let barracks = { guards: {} }; let guard = {}; let guardRe = /Guard #(\d{1,4})/; for (let line of input) { let [timeStamp, action] = line.split("] "); let timeRe = /\d{4}-(\d{2})-(\d{2}) \d{2}:(\d{2})/; let result = timeRe.exec(timeStamp); let [month, day, minute] = [result[1], result[2], result[3]]; switch (action.slice(0, 5)) { case "Guard": let id = guardRe.exec(action)[1]; if (id === guard.id) { // console.log("Same guard"); } else if (Object.keys(barracks.guards).includes(id)) { // console.log("Repeat guard"); barracks.guards[guard.id] = guard; guard = barracks.guards[id]; } else { if (guard.id) { barracks.guards[guard.id] = guard; } guard = { id: id, sleep: [] }; // console.log(`New Guard ID: ${guard.id}`); } break; case "falls": guard.falls = minute; break; case "wakes": guard.wakes = minute; let asleep = range(guard.falls, guard.wakes - 1); asleep.forEach(item => guard.sleep.push(Number(item))); guard.falls = null; guard.wakes = null; // console.log(`Slept for: ${asleep.length} minutes`); break; } } return barracks; } function partA(input) { let barracks = createBarracks(input); let sleepiest = Object.keys(barracks.guards).sort((guardA, guardB) => { return ( barracks.guards[guardB].sleep.length - barracks.guards[guardA].sleep.length ); })[0]; let minutes = count(barracks.guards[sleepiest].sleep); minutes = minutes.sort((a, b) => b[1] - a[1]); return minutes[0][0] * sleepiest; } function partB(input) { let barracks = createBarracks(input); for (let guard in barracks.guards) { if (barracks.guards[guard].sleep.length > 0) { let minutes = count(barracks.guards[guard].sleep); minutes = minutes.sort((a, b) => b[1] - a[1]); let minute = minutes[0]; barracks.guards[guard].sleepiestMinute = minute; } else { barracks.guards[guard].sleepiestMinute = [0, 0]; } } let sleepiest = Object.keys(barracks.guards).sort((guardA, guardB) => { return ( barracks.guards[guardB].sleepiestMinute[1] - barracks.guards[guardA].sleepiestMinute[1] ); })[0]; return barracks.guards[sleepiest].sleepiestMinute[0] * sleepiest; } function solve() { console.log(`Part A: ${partA(input)}`); console.log(`Part B: ${partB(input)}`); } if (require.main === module) { solve(); } module.exports = { partA: partA, partB: partB }; <file_sep>/2017/day04/day04_part2.py from itertools import permutations def main(): # solve for puzzle input input = open("day04_input.txt").read().splitlines() print(solve(input)) def solve(input): count = 0 for line in input: # perms = [''.join(p) for word in line.split() for p in set(permutations(word))] perms = [''.join(sorted(word)) for word in line.split()] if len(perms) == len(set(perms)): count += 1 return count if __name__ == "__main__": main() <file_sep>/2017/day14/day14_part1.py import os def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day14_input.txt").read() print(solve(input)) def knot_hash(input, l=list(range(256))): input = list(map(ord, input)) + list(map(int, "17,31,73,47,23".split(','))) skip = 0 pos = 0 inc = lambda x, d: (x + d) % len(l) for _ in range(64): for length in input: # reverse the slice indexes = [inc(pos, i) for i in range(length)] values = reversed([l[i] for i in indexes]) for i, v in zip(indexes, values): l[i] = v # move forward pos += length + skip # increment skip skip += 1 sparse_hash = [l[i:i + 16] for i in range(0, len(l), 16)] dense_hash = '' for hash in sparse_hash: h = hash[0] for i in hash[1:]: h = h ^ i dense_hash += f'{h:02x}' return dense_hash def hash_to_binary(hash): output = '' hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] for c in hash: output += '{0:04b}'.format(hex.index(c)) return output def create_grid(input): grid = [] for row in range(128): key = f'{input}-{row}' hash = knot_hash(key, l=list(range(256))) binary = hash_to_binary(hash) line = [] for c in binary: line.append('#' if c == '1' else '.') grid.append(line) return grid def solve(input): grid = create_grid(input) return sum(line.count('#') for line in grid) if __name__ == '__main__': main() <file_sep>/2017/day20/day20_part2.py import os, re from itertools import combinations from collections import defaultdict def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day20_input.txt").read().splitlines() print(solve(input)) class Particle: def __init__(self, position, velocity, acceleration): self.position = position self.velocity = velocity self.acceleration = acceleration def move(self): for i in range(3): self.velocity[i] += self.acceleration[i] self.position[i] += self.velocity[i] def distance(self): return sum(map(abs, self.position)) # p=<-4897,3080,2133>, v=<-58,-15,-78>, a=<17,-7,0> PATTERN = "-?\d+" def solve(input, cycles=39): particles = {} i = 0 for line in input: m = re.findall(PATTERN, line) m = list(map(int, m)) pos, vel, acc = m[:3], m[3:6], m[6:] particles[i] = Particle(pos, vel, acc) i += 1 count = 0 while count < cycles: for i, p in particles.items(): p.move() positions = defaultdict(list) for i, p in particles.items(): k = tuple(p.position) positions[k].append(i) for k, v in positions.items(): if len(v) > 1: for i in v: del particles[i] count += 1 return len(particles) if __name__ == '__main__': main() <file_sep>/2017/day12/day12_part2.py import os def main(): os.chdir(os.path.dirname(__file__)) input = open("day12_input.txt").read().splitlines() print(solve(input)) villages = {} def create_village(input): for line in input: village, pipes = line.split(' <-> ') pipes = pipes.split(', ') villages[village] = pipes def count_pipes(village, seen): seen = [] def linked_pipes(village): pipes = villages[village] for pipe in pipes: if pipe not in seen: seen.append(pipe) linked_pipes(pipe) linked_pipes(village) return seen def solve(input): create_village(input) vs = list(villages.keys()) groups = 0 while vs: pipes = count_pipes(vs[0], seen=[]) vs = [v for v in vs if v not in pipes] groups += 1 return groups if __name__ == '__main__': main() <file_sep>/2017/day18/day18_part1.py import os def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day18_input.txt").read().splitlines() print(solve(input)) class Duet: def __init__(self, instructions): self.instructions = instructions self.cursor = 0 self.registers = {i: 0 for i in [x.split()[1] for x in self.instructions] if i.isalpha()} self.sound = 0 self.r_sound = 0 self.finished = 0 def grab(self, x): if x.isalpha(): return self.registers[x] else: return int(x) def next(self): if self.cursor > len(self.instructions): print("Completed instruction set") self.finished = 1 else: ins, *p = self.instructions[self.cursor].split() if ins != 'jgz': if ins == 'snd': self.snd(*p) elif ins == 'set': self.set(*p) elif ins == 'add': self.add(*p) elif ins == 'mul': self.mul(*p) elif ins == 'mod': self.mod(*p) elif ins == 'rcv': self.rcv(*p) self.cursor += 1 elif ins == 'jgz': self.jgz(*p) else: print(f"Unknown instruction: {ins, *p}") def snd(self, x): self.sound = self.grab(x) def set(self, x, y): self.registers[x] = self.grab(y) def add(self, x, y): self.registers[x] += self.grab(y) def mul(self, x, y): self.registers[x] *= self.grab(y) def mod(self, x, y): self.registers[x] = self.registers[x] % self.grab(y) def rcv(self, x): if self.grab(x) != 0: self.r_sound = self.sound else: pass def jgz(self, x, y): if self.grab(x) > 0: self.cursor += self.grab(y) else: self.cursor += 1 def solve(input): d = Duet(input) while not d.r_sound: d.next() return d.r_sound if __name__ == '__main__': main() <file_sep>/2016/Day 1/day1.py def main(data): start = [0, 0] cur_loc = [0, 0] facing = 0 # dictionary for pretty printing our messages directions = {0: 'North', 90: 'East', 180: 'South', 270: 'West'} for instruction in data.split(', '): # find out which direction we're facing after turning # 0 = North, 90 = East, 180 = South, 270 = West if instruction[0] == 'R': facing = (facing + 90) % 360 elif instruction[0] == 'L': facing = (facing - 90) % 360 # get the number of blocks from the instructions distance = int(instruction[1:]) # move our location that many blocks in the correct direction if facing == 0: cur_loc[1] -= distance elif facing == 90: cur_loc[0] += distance elif facing == 180: cur_loc[1] += distance elif facing == 270: cur_loc[0] -= distance # print("{}: We moved {}, {} blocks and are now at: {}.".format(instruction, # directions[facing], # distance, cur_loc, # abs(cur_loc[0]) + abs( # cur_loc[1]), # start)) total_distance = abs(cur_loc[0]) + abs(cur_loc[1]) # print("Total distance from {} to {} is: {}".format(start, cur_loc, total_distance)) return total_distance if __name__ == '__main__': with open('input.txt') as f: # read in the data and split into instructions # ['L4', 'L3', 'R1' ...] data = f.read() print(main(data)) <file_sep>/2016/Day 13/day13.py class Cell(object): def __init__(self, x, y, data=1352): self.x = x self.y = y self.data = data self.wall = self.is_wall() def __eq__(self, other): return self.x == other.x and self.y == other.y def __ne__(self, other): return not self.__eq__(other) def is_wall(self): # x^2 + 3x + 2xy + y + y^2 x, y = self.x, self.y binary_sum = "{0:b}".format((x * x + 3 * x + 2 * x * y + y + y * y) + self.data) if binary_sum.count('1') % 2 == 1: return True else: return False def neighbors(self): cells = [] # Top if self.y > 0: top = Cell(self.x, self.y - 1, self.data) if not top.wall: cells.append(top) # Left if self.x > 0: left = Cell(self.x - 1, self.y, self.data) if not left.wall: cells.append(left) # Right right = Cell(self.x + 1, self.y, self.data) if not right.wall: cells.append(right) # Bottom bottom = Cell(self.x, self.y + 1, self.data) if not bottom.wall: cells.append(bottom) return cells def solve(start, end, data=1352): start = Cell(start[0], start[1], data) end = Cell(end[0], end[1], data) visited = [start] steps = 0 next = visited part1 = None part2 = None while part1 is None or part2 is None: to_check = next.copy() next = [] for cell in to_check: for neighbor in cell.neighbors(): if neighbor in visited: continue visited.append(neighbor) next.append(neighbor) steps += 1 if end in next: part1 = steps if steps == 50: part2 = len(visited) return part1, part2 if __name__ == '__main__': print(solve((1,1), (31,39))) <file_sep>/2016/Day 20/day20.py from collections import deque def solve(data, upper): sorted_intervals = deque(sorted([(int(start), int(end)) for line in data for start, end in [line.split('-')]], key=lambda x: x[0])) # [(0, 2), (4, 7), (5, 8)] answers = [] total, n, index = 0, 0, 0 while n < upper: start, end = sorted_intervals[index] if n >= start: if n <= end: n = end + 1 continue index += 1 else: total += 1 answers.append(n) n += 1 return total, sorted(answers) if __name__ == '__main__': with open('input.txt') as f: data = f.read().splitlines() print(solve(data, 2**32)) #data = ['5-8','0-2','4-7'] #print(solve(data, 9))<file_sep>/2017/day21/day21_part1.py import os import numpy as np from collections import defaultdict def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day21_input.txt").read().splitlines() print(solve(inp)) starting_image = [ ['.','#','.'], ['.','.','#'], ['#','#','#'] ] class Grid: def __init__(self, line): self.in_lines = [[c for c in g] for g in line.split(' => ')[0].split('/')] self.out_lines = [[c for c in g] for g in line.split(' => ')[1].split('/')] self.len = len(self.in_lines) def compare(self, grid): same = False for line1, line2 in zip(grid, self.in_lines): if line1 == line2: same = True return same def get_size(matrix): if len(matrix) % 2 == 0: return 2 elif len(matrix) % 3 == 0: return 3 def print_grid(grid): for line in grid: print_line = '' for c in line: print_line += c print(print_line) print('\n') def solve(inp): grids = defaultdict(list) for line in inp: g = Grid(line) grids[g.len].append(g) def find_match(grid): grid = np.array(grid) rotations = [grid.tolist(), np.rot90(grid).tolist(), np.rot90(grid, 2).tolist(), np.rot90(grid, 3).tolist()] length = len(grid) matches = grids[length] for match in matches: if match.in_lines in rotations: return match.out_lines print("No match found...") g = starting_image iterations = 0 while iterations < 5: print(f"Iteration: {iterations}") print_grid(g) if len(g) // 2 > 1 and len(g) % 2 == 0: pass elif len(g) // 3 > 1 and len(g) % 3 == 0: pass g = find_match(g) iterations += 1 return if __name__ == '__main__': main() <file_sep>/2017/day01/day01_part2.py def main(): # solve for puzzle input input = open("part1_input.txt").read() print(solve(input)) def solve(captcha): sum = 0 half = len(captcha) / 2 for i, c in enumerate(captcha): if c == captcha[int((i + half) % len(captcha))]: sum += int(c) return sum main() <file_sep>/2016/Day 18/day18.py def grab_three_above(index, previous_row): if index == 0: left = '.' else: left = previous_row[index - 1] center = previous_row[index] if index == len(previous_row) - 1 : right = '.' else: right = previous_row[index + 1] return ''.join([left, center, right]) def is_trap(three_above): if three_above in ['^^.', '.^^', '^..', '..^']: return True else: return False def solve(data, rows): new_rows = [data] while len(new_rows) < rows: new_row = [[''] * len(new_rows[-1])][0] for col in range(len(new_rows[-1])): three_above = grab_three_above(col, new_rows[-1]) if is_trap(three_above): new_row[col] = '^' else: new_row[col] = '.' new_rows.append(new_row) return sum([line.count('.') for line in [''.join(line) for line in new_rows]]) if __name__ == '__main__': first_line = '.^^.^^^..^.^..^.^^.^^^^.^^.^^...^..^...^^^..^^...^..^^^^^^..^.^^^..^.^^^^.^^^.^...^^^.^^.^^^.^.^^.^.' rows = 400000 data = [chr for chr in first_line] print(solve(data, rows))<file_sep>/2017/day06/day06_part1.py def main(): # solve for puzzle input input = list(map(int, open("day06_input.txt").read().split('\t'))) print(solve(input)) def solve(input): count = 0 seen = [] while input not in seen: seen.append(input[:]) # find highest index = input.index(max(input)) value = input[index] input[index] = 0 while value > 0: index = (index + 1) % len(input) input[index] += 1 value -= 1 count += 1 return count if __name__ == "__main__": main() <file_sep>/2016/Day 6/day6.py from numpy import matrix from collections import Counter def solve_most(data): # data = ['asdkfe', 'eisjgk', ... ] data = matrix([list(string) for string in data]).T # data = [['a','e' ...], ['s','i' ... message = '' for line in data: c = Counter(''.join(line.tolist()[0])) message += c.most_common(1)[0][0] return message def solve_least(data): # data = ['asdkfe', 'eisjgk', ... ] data = matrix([list(string) for string in data]).T # data = [['a','e' ...], ['s','i' ... message = '' for line in data: c = Counter(''.join(line.tolist()[0])) message += c.most_common()[-1][0] return message if __name__ == '__main__': with open('input.txt') as f: data = f.read().splitlines() # print(solve_most(data)) print(solve_least(data)) <file_sep>/2017/day02/test_day02.py import day02_part1 import day02_part2 def test_part1_example(): raw_input = """5 1 9 5 7 5 3 2 4 6 8""" input = [[int(item) for item in line.split()] for line in raw_input.split('\n')] assert day02_part1.solve(input) == 18 def test_part1(): input = [[int(item) for item in line.strip('\n').split('\t')] for line in open("day02_input.txt").readlines()] assert day02_part1.solve(input) == 32020 def test_part2_example(): raw_input = """5 9 2 8 9 4 7 3 3 8 6 5""" input = [[int(item) for item in line.split()] for line in raw_input.split('\n')] assert day02_part2.solve(input) == 9 def test_part2(): input = [[int(item) for item in line.strip('\n').split('\t')] for line in open("day02_input.txt").readlines()] assert day02_part2.solve(input) == 236 <file_sep>/2017/day13/day13_part1.py import os def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day13_input.txt").read().splitlines() print(solve(input)) fw = {} def check_collision(layer, depth): return layer % ((depth - 1) * 2) == 0 def solve(input): severity = 0 for line in input: layer, depth = list(map(int, line.split(': '))) fw[layer] = depth for layer, depth in fw.items(): if check_collision(layer, depth): severity += layer * depth return severity if __name__ == '__main__': main() <file_sep>/2016/Day 12/tests.py import day12 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day12_Example(self): data = """cpy 41 a inc a inc a dec a jnz a 2 dec a""".splitlines() self.assertEqual(day12.solve(data), 42) def test_Day12_Data(self): with open('input.txt') as f: data = f.read().splitlines() self.assertEqual(day12.solve(data), 318020) def test_Day12_2_Data(self): with open('input.txt') as f: data = f.read().splitlines() self.assertEqual(day12.solve(data, {'a': 0, 'b': 0, 'c': 1, 'd': 0}), 9227674) if __name__ == '__main__': unittest.main()
2c2512d3aeff21e4083bb24167f09736d385f62d
[ "JavaScript", "Python", "Markdown" ]
116
Python
willismonroe/adventofcode
4f89653dcf8a1159ddee6dbebe80aee55749d4ba
9a5c3d08458aae318cd2b9afbb5130f59befac89
refs/heads/master
<file_sep>SELECT username, password, quota FROM mailbox WHERE active = '1' INTO OUTFILE '/tmp/mailboxes.csv' FIELDS ENCLOSED BY '"' TERMINATED BY ',' ESCAPED BY '"' LINES TERMINATED BY '\n'; SELECT address, goto FROM alias WHERE active = '1' INTO OUTFILE '/tmp/aliases.csv' FIELDS ENCLOSED BY '"' TERMINATED BY ',' ESCAPED BY '"' LINES TERMINATED BY '\n'; <file_sep>#!/bin/sh # # $Id: sync_loop_unix.sh,v 1.6 2015/11/04 18:23:04 gilles Exp gilles $ # # Example for imapsync massive migration on Unix systems. # See also http://imapsync.lamiral.info/FAQ.d/FAQ.Massive.txt # # Data is supposed to be in file.txt in the following format: # user001_1;password001_1;user001_2;password0<PASSWORD>; # ... # Separator is character semi-colon ";" it can be changed by any character changing IFS=';' # in the while loop below. # Each line contains 4 columns, columns are parameter values for # --user1 --password1 --user2 --password2 # and a trailing empty fake column to avaid CR LF part going # in the 4th parameter password2. Don't forget the last semicolon. # # You can add extra options after the variable "$@" # Use character backslash \ at the end of each suplementary line, except for the last one. # You can also pass extra options via the parameters of this script since # they will be in "$@" # # The credentials filename "file.txt" used for the loop can be renamed # by changing "file.txt" below. # # remove --dry flag for real changes. set -eu h1="mail.piratenpartei.ch" h2="mail.cyon.ch" echo Looping on account credentials found in file.txt echo { while IFS=';' read u1 p1 u2 p2 fake do echo "==== Starting imapsync from host1 $h1 user1 $u1 to host2 $h2 user2 $u2 ====" imapsync --dry --no-modulesversion --automap --tls1 --tls2 \ --host1 "$h1" --user1 "$u1" --password1 "$p1" \ --host2 "$h2" --user2 "$u2" --password2 "$p2" \ "$@" echo "==== Ended imapsync from host1 $h1 user1 $u1 to host2 $h2 user2 $u2 ====" echo done } < file.txt
e9e7cf18b0a83993219a34775ac011f99865b077
[ "SQL", "Shell" ]
2
SQL
ppschweiz/mail-migration
c554e8cd249cc53fb6c35e78851b7493d80e08f3
ce0603c7d78a6c86c842d934ad9dbbafaa6eec6f
refs/heads/master
<repo_name>dretay/factory-girl-bookshelf<file_sep>/README.md # factory-girl-bookshelf [![Build Status](https://travis-ci.org/aexmachina/factory-girl-bookshelf.png)](https://travis-ci.org/aexmachina/factory-girl-bookshelf) A [Bookshelf](http://bookshelfjs.org/) adapter for [factory-girl](https://github.com/aexmachina/factory-girl). ## Usage ```javascript require('factory-girl-bookshelf')(); ``` Or, if you want to specify which models it should be used for: ```javascript require('factory-girl-bookshelf')(['User', 'Foo', 'Bar']); ``` <file_sep>/test/adapter.js var adapter = require('..')(); var Bookshelf = require('bookshelf'); var tests = require('factory-girl/lib/adapter-tests'); var config = require('config-node')(); var Bookshelf = require('bookshelf'); describe('Bookshelf adapter', function() { init(); var Model = Bookshelf.db.Model.extend({ tableName: 'test' }); tests(adapter, Model, countModels); function countModels(cb) { Model.query().count('id as count').then(function(result) { return cb(null, result[0].count); }, cb); } }); function init() { var knex = require('knex')(config.database); Bookshelf.db = Bookshelf.initialize(knex); before(function() { return knex.schema.dropTableIfExists('test') .then(function() { return knex.schema.createTable('test', function(table) { table.increments(); table.string('name'); }); }); }); }
cd79e99810234cdda2403df59b0b032b0d861023
[ "Markdown", "JavaScript" ]
2
Markdown
dretay/factory-girl-bookshelf
45cc0af2bb51d571b7212ab444a0ae39ac1f035f
485f66086975696e51ff87f6cb505c723f598560
refs/heads/master
<repo_name>24apanda/pyspark_ml<file_sep>/kafka_consumer.py from kafka import KafkaConsumer from json import loads import time import pandas as pd KAFKA_CONSUMER_GROUP_NAME_CONS = "test_consumer_group" KAFKA_TOPIC_NAME_CONS = "testtopic" KAFKA_OUTPUT_TOPIC_NAME_CONS = "outputtopic" KAFKA_BOOTSTRAP_SERVERS_CONS = '192.168.3.11:9092' if __name__ == "__main__": print("Kafka Consumer Application Started ... ") # auto_offset_reset='latest' # auto_offset_reset='earliest' consumer = KafkaConsumer( KAFKA_TOPIC_NAME_CONS, bootstrap_servers=KAFKA_BOOTSTRAP_SERVERS_CONS, auto_offset_reset='latest', enable_auto_commit=True, group_id=KAFKA_CONSUMER_GROUP_NAME_CONS, value_deserializer=lambda x: loads(x.decode('utf-8'))) def get_message_df(): print("Reading Messages from Kafka Topic about to Start ... ") message_list = [] counter = 0 df = pd.DataFrame() for message in consumer: #print(dir(message)) #print(type(message)) print("Key: ", message.key) output_message = message.value #print(type(message.value)) #print("Message received: ", output_message) #message_list.append(output_message) df.append(output_message, [counter]) counter += 1 print("Counter in for loop: ", counter) if counter == 10: print("Counter in if loop: ", counter) yield df #print(message_list) #message_list = [{'transaction_amount': 524.62, 'transaction_datetime': '2019-05-14 01:30:32', 'transaction_card_type': 'Maestro', 'transaction_id': '1'}] #print(message_list) #print("Before Creating DataFrame ...") #df = pd.DataFrame(message_list) #df.head() #print("After Creating DataFrame.") message_list = [] #df = None counter = 0 time.sleep(5) for df in get_message_df(): print("Before DataFrame Head ...") df.head() print("After DataFrame Head.")<file_sep>/structure_streaming.py from pyspark.sql import SparkSession from pyspark.sql.functions import * from pyspark.sql.types import * KAFKA_TOPIC_NAME_CONS = "testtopic" KAFKA_OUTPUT_TOPIC_NAME_CONS = "outputtopic" KAFKA_BOOTSTRAP_SERVERS_CONS = '192.168.3.11:9092' if __name__ == "__main__": print("PySpark Structured Streaming with Kafka Application Started ...") spark = SparkSession \ .builder \ .appName("PySpark Structured Streaming with Kafka ") \ .master("local[*]") \ .config("spark.jars", "file:///D://work//development//spark_structured_streaming_kafka//spark-sql-kafka-0-10_2.11-2.4.0.jar,file:///D://work//development//spark_structured_streaming_kafka//kafka-clients-1.1.0.jar") \ .config("spark.executor.extraClassPath", "file:///D://work//development//spark_structured_streaming_kafka//spark-sql-kafka-0-10_2.11-2.4.0.jar:file:///D://work//development//spark_structured_streaming_kafka//kafka-clients-1.1.0.jar") \ .config("spark.executor.extraLibrary", "file:///D://work//development//spark_structured_streaming_kafka//spark-sql-kafka-0-10_2.11-2.4.0.jar:file:///D://work//development//spark_structured_streaming_kafka//kafka-clients-1.1.0.jar") \ .config("spark.driver.extraClassPath", "file:///D://work//development//spark_structured_streaming_kafka//spark-sql-kafka-0-10_2.11-2.4.0.jar:file:///D://work//development//spark_structured_streaming_kafka//kafka-clients-1.1.0.jar") \ .getOrCreate() spark.sparkContext.setLogLevel("ERROR") # Construct a streaming DataFrame that reads from testtopic transaction_detail_df = spark \ .readStream \ .format("kafka") \ .option("kafka.bootstrap.servers", KAFKA_BOOTSTRAP_SERVERS_CONS) \ .option("subscribe", KAFKA_TOPIC_NAME_CONS) \ .option("startingOffsets", "latest") \ .load() print("Printing Schema of transaction_detail_df: ") transaction_detail_df.printSchema() transaction_detail_df1 = transaction_detail_df.selectExpr("CAST(value AS STRING)", "timestamp") # Define a schema for the transaction_detail data transaction_detail_schema = StructType() \ .add("transaction_id", StringType()) \ .add("transaction_card_type", StringType()) \ .add("transaction_amount", StringType()) \ .add("transaction_datetime", StringType()) transaction_detail_df2 = transaction_detail_df1\ .select(from_json(col("value"), transaction_detail_schema).alias("transaction_detail"), "timestamp") transaction_detail_df3 = transaction_detail_df2.select("transaction_detail.*", "timestamp") # Simple aggregate - find total_transaction_amount by grouping transaction_card_type transaction_detail_df4 = transaction_detail_df3.groupBy("transaction_card_type")\ .agg({'transaction_amount': 'sum'}).select("transaction_card_type", \ col("sum(transaction_amount)").alias("total_transaction_amount")) print("Printing Schema of transaction_detail_df4: ") transaction_detail_df4.printSchema() transaction_detail_df5 = transaction_detail_df4.withColumn("key", lit(100))\ .withColumn("value", concat(lit("{'transaction_card_type': '"), \ col("transaction_card_type"), lit("', 'total_transaction_amount: '"), \ col("total_transaction_amount").cast("string"), lit("'}"))) print("Printing Schema of transaction_detail_df5: ") transaction_detail_df5.printSchema() # Write final result into console for debugging purpose trans_detail_write_stream = transaction_detail_df5 \ .writeStream \ .trigger(processingTime='1 seconds') \ .outputMode("update") \ .option("truncate", "false")\ .format("console") \ .start() # Write key-value data from a DataFrame to a specific Kafka topic specified in an option trans_detail_write_stream_1 = transaction_detail_df5 \ .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)") \ .writeStream \ .format("kafka") \ .option("kafka.bootstrap.servers", KAFKA_BOOTSTRAP_SERVERS_CONS) \ .option("topic", KAFKA_OUTPUT_TOPIC_NAME_CONS) \ .trigger(processingTime='1 seconds') \ .outputMode("update") \ .option("checkpointLocation", "file:///D://work//development//spark_structured_streaming_kafka//py_checkpoint") \ .start() trans_detail_write_stream.awaitTermination() print("PySpark Structured Streaming with Kafka Application Completed.")<file_sep>/kafka_producer.py from kafka import KafkaProducer from datetime import datetime import time from json import dumps import random KAFKA_TOPIC_NAME_CONS = "testtopic" KAFKA_BOOTSTRAP_SERVERS_CONS = '172.16.17.32:9092' if __name__ == "__main__": print("Kafka Producer Application Started ... ") kafka_producer_obj = KafkaProducer(bootstrap_servers=KAFKA_BOOTSTRAP_SERVERS_CONS, value_serializer=lambda x: dumps(x).encode('utf-8')) transaction_card_type_list = ["Visa", "MasterCard", "Maestro"] message = None for i in range(5): i = i + 1 message = {} print("Sending message to Kafka topic: " + str(i)) event_datetime = datetime.now() message["transaction_id"] = str(i) message["transaction_card_type"] = random.choice(transaction_card_type_list) message["transaction_amount"] = round(random.uniform(5.5,555.5), 2) message["transaction_datetime"] = event_datetime.strftime("%Y-%m-%d %H:%M:%S") print("Message to be sent: ", message) kafka_producer_obj.send(KAFKA_TOPIC_NAME_CONS, message) time.sleep(1)
144bfc62be462eaaff55bfebddd4e63a37bf8aa7
[ "Python" ]
3
Python
24apanda/pyspark_ml
337fc60c10c3fa0c94cb0d6981c4425af86fea03
eeaccd845ef0c4bd928e8d31b846a0d1cebcb66e
refs/heads/master
<repo_name>5cr0ll/ARP-MAP<file_sep>/src/arp_map.c #include <stdio.h> #include <stdlib.h> #include <net/if.h> #include <sys/ioctl.h> #include <unistd.h> // close() #include <string.h> #include <ifaddrs.h> #include <linux/if_arp.h> #include <arpa/inet.h> //htons etc #define PROTO_ARP 0x0806 #define ETH2_HEADER_LEN 14 #define HW_TYPE 1 #define MAC_LENGTH 6 #define IPV4_LENGTH 4 #define ARP_REQUEST 0x01 #define BUF_SIZE 60 /* * Debugging tools for readability * and debugging obviously. */ #define debug(x...) printf(x);printf("\n"); #define info(x...) printf(x);printf("\n"); #define warn(x...) printf(x);printf("\n"); #define err(x...) printf(x);printf("\n"); /* * Struct for arp header. */ struct arp_header { unsigned short hardware_type; unsigned short protocol_type; unsigned char hardware_len; unsigned char protocol_len; unsigned short opcode; unsigned char sender_mac[MAC_LENGTH]; unsigned char sender_ip[IPV4_LENGTH]; unsigned char target_mac[MAC_LENGTH]; unsigned char target_ip[IPV4_LENGTH]; }; /* * Converts struct sockaddr with an IPv4 address to network byte order uin32_t. * Returns 0 on success. */ int int_ip4(struct sockaddr *addr, uint32_t *ip) { if (addr->sa_family == AF_INET) { struct sockaddr_in *i = (struct sockaddr_in *) addr; *ip = i->sin_addr.s_addr; return 0; } else { err("Not AF_INET"); return 1; } } /* * Formats sockaddr containing IPv4 address as human readable string. * Returns 0 on success. */ int format_ip4(struct sockaddr *addr, char *out) { if (addr->sa_family == AF_INET) { struct sockaddr_in *i = (struct sockaddr_in *) addr; const char *ip = inet_ntoa(i->sin_addr); if (!ip) { return -2; } else { strcpy(out, ip); return 0; } } else { return -1; } } /* * Writes interface IPv4 address as network byte order to ip. * Returns 0 on success. */ int get_if_ip4(int fd, const char *ifname, uint32_t *ip) { int err = -1; struct ifreq ifr; memset(&ifr, 0, sizeof(struct ifreq)); if (strlen(ifname) > (IFNAMSIZ - 1)) { err("Too long interface name"); goto out; } strcpy(ifr.ifr_name, ifname); if (ioctl(fd, SIOCGIFADDR, &ifr) == -1) { perror("SIOCGIFADDR"); goto out; } if (int_ip4(&ifr.ifr_addr, ip)) { goto out; } err = 0; out: return err; } /* * Sends an ARP who-has request to dst_ip * on interface ifindex, using source mac src_mac and source ip src_ip. */ int send_arp(int fd, int ifindex, const unsigned char *src_mac, uint32_t src_ip, uint32_t dst_ip) { int err = -1; unsigned char buffer[BUF_SIZE]; memset(buffer, 0, sizeof(buffer)); struct sockaddr_ll socket_address; socket_address.sll_family = AF_PACKET; socket_address.sll_protocol = htons(ETH_P_ARP); socket_address.sll_ifindex = ifindex; socket_address.sll_hatype = htons(ARPHRD_ETHER); socket_address.sll_pkttype = (PACKET_BROADCAST); socket_address.sll_halen = MAC_LENGTH; socket_address.sll_addr[6] = 0x00; socket_address.sll_addr[7] = 0x00; struct ethhdr *send_req = (struct ethhdr *) buffer; struct arp_header *arp_req = (struct arp_header *) (buffer + ETH2_HEADER_LEN); int index; ssize_t ret, length = 0; //Broadcast memset(send_req->h_dest, 0xff, MAC_LENGTH); //Target MAC zero memset(arp_req->target_mac, 0x00, MAC_LENGTH); //Set source mac to our MAC address memcpy(send_req->h_source, src_mac, MAC_LENGTH); memcpy(arp_req->sender_mac, src_mac, MAC_LENGTH); memcpy(socket_address.sll_addr, src_mac, MAC_LENGTH); /* Setting protocol of the packet */ send_req->h_proto = htons(ETH_P_ARP); /* Creating ARP request */ arp_req->hardware_type = htons(HW_TYPE); arp_req->protocol_type = htons(ETH_P_IP); arp_req->hardware_len = MAC_LENGTH; arp_req->protocol_len = IPV4_LENGTH; arp_req->opcode = htons(ARP_REQUEST); // debug("Copy IP address to arp_req"); memcpy(arp_req->sender_ip, &src_ip, sizeof(uint32_t)); memcpy(arp_req->target_ip, &dst_ip, sizeof(uint32_t)); ret = sendto(fd, buffer, 42, 0, (struct sockaddr *) &socket_address, sizeof(socket_address)); if (ret == -1) { perror("sendto():"); goto out; } err = 0; out: return err; } /* * Gets interface information by name: * IPv4 * MAC * ifindex */ int get_if_info(const char *ifname, uint32_t *ip, char *mac, int *ifindex) { // debug("get_if_info for %s", ifname); int err = -1; struct ifreq ifr; int sd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP)); if (sd <= 0) { perror("socket()"); goto out; } if (strlen(ifname) > (IFNAMSIZ - 1)) { printf("Too long interface name, MAX=%i\n", IFNAMSIZ - 1); goto out; } strcpy(ifr.ifr_name, ifname); //Get interface index using name if (ioctl(sd, SIOCGIFINDEX, &ifr) == -1) { perror("SIOCGIFINDEX"); goto out; } *ifindex = ifr.ifr_ifindex; //Get MAC address of the interface if (ioctl(sd, SIOCGIFHWADDR, &ifr) == -1) { perror("SIOCGIFINDEX"); goto out; } //Copy mac address to output memcpy(mac, ifr.ifr_hwaddr.sa_data, MAC_LENGTH); if (get_if_ip4(sd, ifname, ip)) { goto out; } // debug("get_if_info OK"); err = 0; out: if (sd > 0) { // debug("Clean up temporary socket"); close(sd); } return err; } /* * Creates a raw socket that listens for ARP traffic on specific ifindex. * Writes out the socket's FD. * Return 0 on success. */ int bind_arp(int ifindex, int *fd) { // debug("bind_arp: ifindex=%i", ifindex); int ret = -1; // Submit request for a raw socket descriptor. *fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP)); if (*fd < 1) { perror("socket()"); goto out; } // debug("Binding to ifindex %i", ifindex); struct sockaddr_ll sll; memset(&sll, 0, sizeof(struct sockaddr_ll)); sll.sll_family = AF_PACKET; sll.sll_ifindex = ifindex; if (bind(*fd, (struct sockaddr*) &sll, sizeof(struct sockaddr_ll)) < 0) { perror("bind"); goto out; } ret = 0; out: if (ret && *fd > 0) { // debug("Cleanup socket"); close(*fd); } return ret; } /* * Reads a single ARP reply from fd. * Return 0 on success. */ int read_arp(int fd) { // int fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP)); // debug("read_arp"); int ret = -1; unsigned char buffer[BUF_SIZE]; ssize_t length = recvfrom(fd, buffer, BUF_SIZE, 0, NULL, NULL); int index; if (length == -1) { perror("recvfrom()"); goto out; } struct ethhdr *rcv_resp = (struct ethhdr *) buffer; struct arp_header *arp_resp = (struct arp_header *) (buffer + ETH2_HEADER_LEN); if (ntohs(rcv_resp->h_proto) != PROTO_ARP) { debug("Not an ARP packet 1"); goto out; } // debug("received ARP len=%ld", length); struct in_addr sender_a; memset(&sender_a, 0, sizeof(struct in_addr)); memcpy(&sender_a.s_addr, arp_resp->sender_ip, sizeof(uint32_t)); printf("[%s] - ", inet_ntoa(sender_a)); printf("%02X:%02X:%02X:%02X:%02X:%02X\n", arp_resp->sender_mac[0], arp_resp->sender_mac[1], arp_resp->sender_mac[2], arp_resp->sender_mac[3], arp_resp->sender_mac[4], arp_resp->sender_mac[5]); ret = 0; out: return ret; } /* * Sends an ARP who-has request on * interface <interface> to IPv4 address <ip>. * Returns 0 on success. */ int arp_handler(struct if_nameindex * interface, struct in_addr * ip) { int ret = -1; uint32_t dst = ntohl(ip->s_addr); if (dst == 0 || dst == 0xffffffff) { printf("Invalid source IP\n"); return 1; } int src; int ifindex; char mac[MAC_LENGTH]; if (get_if_info(interface->if_name, &src, mac, &ifindex)) { err("get_if_info failed, interface %s not found or no IP set?", interface->if_name); goto out; } int arp_fd; if (bind_arp(ifindex, &arp_fd)) { err("Failed to bind_arp()"); goto out; } if (send_arp(arp_fd, ifindex, mac, src, dst)) { err("Failed to send_arp"); goto out; } for (int i = 0; i < 10; i++) { int r = read_arp(arp_fd); if (r == 0) { // info("Got reply, break out"); break; } } // int r = read_arp(arp_fd); // if (r == 0) { // // info("Got reply, break out"); // } ret = 0; out: if (arp_fd) { close(arp_fd); arp_fd = 0; } return ret; } /* * Gets host ip address from interface. * Returns 0 on success. */ int get_ip_from_interface(struct if_nameindex *interface, struct in_addr * addr) { int fd = socket(AF_INET, SOCK_DGRAM, 0); struct ifreq ifr; int ret; strncpy(ifr.ifr_name , interface->if_name, IFNAMSIZ-1); if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) { *addr = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr; ret = 0; } else { ret = -1; } close(fd); return ret; } /* * Gets subnet mask from interface. * Returns 0 on success. */ int get_netmask_from_interface(struct if_nameindex *interface, struct in_addr * addr) { int fd = socket(AF_INET, SOCK_DGRAM, 0); struct ifreq ifr; int ret; strncpy(ifr.ifr_name , interface->if_name, IFNAMSIZ-1); // netmask if (ioctl(fd, SIOCGIFNETMASK, &ifr) == 0) { *addr = ((struct sockaddr_in *)&ifr.ifr_addr )->sin_addr; ret = 0; } else { ret = -1; } close(fd); return ret; } /* * Calculates broadcast address in subnet. * Returns 0. */ int calculate_broadcast_address(struct in_addr * subnet_mask, struct in_addr * ip_addr, struct in_addr * broadcast_address) { broadcast_address->s_addr = ip_addr->s_addr | ~subnet_mask->s_addr; return 0; } /* * Calculates min address in subnet. * Returns 0. */ int calculate_min_address_in_range(struct in_addr * subnet_mask, struct in_addr * ip_addr, struct in_addr * min_address) { min_address->s_addr = ip_addr->s_addr & subnet_mask->s_addr; return 0; } void iterate_addresses(struct if_nameindex *interface, struct in_addr * broadcast_addr, struct in_addr * min_addr, struct in_addr * ip_addr) { min_addr->s_addr = htonl(htonl(min_addr->s_addr) + 1); while (min_addr->s_addr < broadcast_addr->s_addr) { min_addr->s_addr = htonl(htonl(min_addr->s_addr) + 1); /* Don't want to ping ourselves */ if (ip_addr->s_addr == min_addr->s_addr) continue; arp_handler(interface, min_addr); } } /* * Handles all of the logic in arp-map * Gets the data and calls functions for * calculating range of ipv4 addresses * in subnet. */ void handle_arp_map(int index) { struct ifaddrs *ifaddr, *ifa; char * interface_name; if (getifaddrs(&ifaddr) == -1) { perror("getifaddrs"); return; } int count = 0; for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { char protocol[IFNAMSIZ] = {0}; if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_PACKET) continue; // check if interface is loopback int iIsLoopBack = (0 != (ifa->ifa_flags & IFF_LOOPBACK)); if (!iIsLoopBack) { if (count == index) interface_name = ifa->ifa_name; count++; } } if (count < index) { printf("Invalid index.\n"); return; } struct if_nameindex *if_ni, *i; if_ni = if_nameindex(); if (if_ni == NULL) { perror("if_nameindex"); exit(EXIT_FAILURE); } for (i = if_ni; ! (i->if_index == 0 && i->if_name == NULL); i++) { if (strcmp(interface_name, i->if_name) == 0) { struct in_addr ip_address; if (get_ip_from_interface(i, &ip_address) != 0) { //printf("Error no address for this interface"); continue; } struct in_addr subnet_mask; if (get_netmask_from_interface(i, &subnet_mask) != 0) { //printf("Error no address for this interface"); continue; } struct in_addr min_addr; if (calculate_min_address_in_range(&subnet_mask, &ip_address, &min_addr) != 0) { //printf("Error no address for this interface"); continue; } struct in_addr broadcast_addr; if (calculate_broadcast_address(&subnet_mask, &ip_address, &broadcast_addr) != 0) { //printf("Error no address for this interface"); continue; } iterate_addresses(i, &broadcast_addr, &min_addr, &ip_address); break; } } } void menu() { printf("\n--- ARP Map ---\n"); printf("Welcome to ARP-Map, the ultimate tool for scanning your computer's interfaces.\n"); printf("\nSelect a following Interface to run an ARP-map scan on:\n"); printf("[0] to reprint the menu\n"); } int main(int argc, char *argv[]) { int command = 0; int index = 0; struct ifaddrs *ifaddr, *ifa; if (getifaddrs(&ifaddr) == -1) { perror("getifaddrs"); return -1; } /* Prompt user with menu */ while(1) { menu(); /* Walk through linked list, maintaining head pointer so we can free list later */ index = 0; for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { char protocol[IFNAMSIZ] = {0}; if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_PACKET) continue; // check if interface is loopback int iIsLoopBack = (0 != (ifa->ifa_flags & IFF_LOOPBACK)); if (!iIsLoopBack) { printf("[%d] %s\n", index + 1, ifa->ifa_name); index++; } } printf("\n\nEnter a command (-1 to quit):\n"); scanf("%d", &command); if (command == -1) break; switch (command) { case 0: menu(); break; default: if (command <= index) { handle_arp_map(command - 1); } else { printf("Incorrect index, 0-%d only!", index); } } } freeifaddrs(ifaddr); return 0; } <file_sep>/README.md # ARP-scanner A small ARP scanner that scans your machines interfaces and shows you all of the MAC addresses of each device in the subnet. *Make sure you run the program with **sudo** privileges.*
0a5a5f9cc9b0abf9da1e21ec22aa2ff5bd60790f
[ "Markdown", "C" ]
2
C
5cr0ll/ARP-MAP
a95895d0398448a691e3c8f9d1f6c958d1a7ad57
955e54d9e59c4d9627c852db563596949e1a6f3c
refs/heads/master
<file_sep>import './Clock.css' import React, { Component } from 'react' import Hend from './Hend/Hend' class Clock extends Component { state = { seconds: { deg: 0, color: 'crimson', }, minutes: { deg: 0, }, hours: { deg: 0, width: 30, left: 20, }, } componentDidMount() { this.setTime() this.timerID = setInterval(this.setTime, 1000) } setTime = () => { const date = new Date(), tiemZone = date.getTimezoneOffset() / 60 this.setState(prevState => { return { seconds: { ...prevState.seconds, deg: (((date / 1000) % 60) / 60) * 360, }, minutes: { ...prevState.minutes, deg: (((date / (1000 * 60)) % 60) / 60) * 360, }, hours: { ...prevState.hours, deg: ((((date / (1000 * 60 * 60)) % 12) - tiemZone) / 12) * 360, }, } }) } componentWillUnmount() { clearInterval(this.timerID) } render() { return ( <div className="clock"> <div className="board"> {Object.entries(this.state).map(([k, v]) => ( <Hend key={k} deg={v.deg} width={v.width || 50} left={v.left || 0} color={v.color || 'black'} /> ))} <div className="axis" /> </div> </div> ) } } export default Clock <file_sep>import './Hend.css' import React from 'react' const Hend = props => ( <div style={{ transform: `rotate(${props.deg}deg)`, width: `${props.width}%`, left: `${props.left}%`, background: props.color, transition: props.deg > 354 || props.deg < 6 ? 'transform 0s' : 'transform 0.05s cubic-bezier(0.1, 2.4, 0.6, 1)', }} className="hend" /> ) export default Hend
a00c7627be6f531c44498ff1b4e017ee82a344bf
[ "JavaScript" ]
2
JavaScript
joyfulstick/clock
dd4a9b5d8385a8d0fc892487cf8d6a08611ae28a
6314d716f464b7abb38dcf6560b41e9bc9b20c8c
refs/heads/master
<file_sep>package com.yerimspring.web.grade; import org.springframework.stereotype.Service; import com.yerimspring.web.util.GradeCredit; @Service public class GradeServiceImpl implements GradeService { private Grade[] grades; private int count; public GradeServiceImpl() { grades = new Grade[4]; count = 0; } @Override public void add(Grade grade) { grades[count] = grade; count++; } @Override public Grade[] list() { return grades; } @Override public int count() { return count; } @Override public GradeCredit detail(String userid) { GradeCredit credit = null; switch(average(userid)/10) { case 10: case 9: credit = GradeCredit.A; break; case 8: credit = GradeCredit.B; break; case 7: credit = GradeCredit.C; break; case 6: credit = GradeCredit.D; break; case 5: credit = GradeCredit.F; break; } return credit; } private int average(String userid) { return total(userid)/4; } private int total(String userid) { int total = 0; for(int i = 0; i <count; i++) { if(userid.equals(grades[i].getUserid())) { total = Integer.parseInt(grades[i].getKorean()) + Integer.parseInt(grades[i].getEnglish()) + Integer.parseInt(grades[i].getMath()) + Integer.parseInt(grades[i].getJava()); } } return total; } @Override public void update(Grade grade) { } @Override public void delete(Grade grade) { } } <file_sep>package com.yerimspring.web.lotto; import lombok.Data; @Data public class Lotto { private String userid, lotto_number; } <file_sep>package com.yerimspring.web.util; public enum LottoRank { 일등,이등,삼등,사등,오등,꽝; } <file_sep>package com.yerimspring.web.lotto; public interface LottoNumService { public void add(Lotto number); public int count(); } <file_sep>package com.yerimspring.web.lotto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.yerimspring.web.util.Messenger; @RestController @RequestMapping("/lotto") public class LottoController { @Autowired LottoNumService lottoNumService; @PostMapping("/buy") public Messenger buy(@RequestBody Lotto number) { int current = lottoNumService.count(); lottoNumService.add(number); return (lottoNumService.count() == (current+1))? Messenger.Success : Messenger.FAIL; } }
8242e3c83fedc9f71637d69fb833f345f11372b6
[ "Java" ]
5
Java
kangyerim/spring
90943c6b2381b2e81ae644f2a1a877d0a30c9505
6e8bc2339c283bcf5c3faed2a334085d488c69a2
refs/heads/windows
<file_sep>#!/bin/sh dbg_print() { if [ "x$verbosity" == "xverbose" ] ; then echo "$@" fi } # find_string $string $filename # searches for string in a file, # returns "found" on success and "not_found" on failure find_string() { while read -r; do [[ $REPLY = *$1* ]] && echo "found" && return; done < "$2" echo "not_found" } error_out() { echo "$@" exit 1 } main() { echo "Starting download script..." # ARG 1: Path to cygwin binaries # ARG 2: Elf File to download # ARG 3: TTY port to use. # ARG 4: quiet/verbose # # path may contain \ need to change all to / cyg_path="${1//\\/\/}" dfu="$cyg_path/dfu-util.exe" dfu_cmd="$dfu -d,8087:0ABA" sleep="$cyg_path/sleep.exe" tmp_dfu_output="$cyg_path/../../.tmp_dfu_output" # We want to download .bin file instead of provided .elf host_file_name=${2//\\/\/} bin_file_name=${host_file_name/.elf/.bin} com_port="$3" verbosity="$4" dbg_print "Args to shell:" "$@" dbg_print "Serial Port:" "$com_port" dbg_print "BIN FILE" "$bin_file_name" dbg_print "Waiting for device..." COUNTER=0 $dfu_cmd -l >"$tmp_dfu_output" f=$(find_string "sensor_core" "$tmp_dfu_output") while [ "x$f" == "xnot_found" ] && [ $COUNTER -lt 10 ] do let COUNTER=COUNTER+1 $sleep 1 $dfu_cmd -l >"$tmp_dfu_output" f=$(find_string "sensor_core" "$tmp_dfu_output") done if [ "x$verbosity" == "xverbose" ] ; then dfu_download="$dfu_cmd -D \"$bin_file_name\" -v --alt 7 -R" else dfu_download="$dfu_cmd -D \"$bin_file_name\" --alt 7 -R >/dev/null 2>&1" fi if [ "x$f" == "xfound" ] ; then dbg_print "Using dfu-util to send " "$bin_file_name" dbg_print "$dfu_download" eval $dfu_download || error_out "ERROR: DFU transfer failed" echo "SUCCESS: Sketch will execute in about 5 seconds." else echo "ERROR: Timed out waiting for Arduino 101 on" "$com_port" fi } main "$@"
e3bba5afc25952dca35faa3e9ccec1204a25d827
[ "Shell" ]
1
Shell
kmsywula/intel-arduino-tools
53def03d22d78a040f50cb497eea31f53f35441c
235db18dc57c0610419dad9ab71255d5d0bcf190
refs/heads/master
<file_sep>package com.github.bookong.zest.rule; import com.github.bookong.zest.testcase.ZestData; import com.github.bookong.zest.util.Messages; import org.junit.Assert; import java.util.Date; /** * @author <NAME> */ public abstract class AbstractRule { private String field; private boolean nullable; private boolean manual; AbstractRule(String field, boolean nullable, boolean manual){ this.field = field; this.nullable = nullable; this.manual = manual; } public abstract void verify(ZestData zestData, Object actual); protected Date getActualDataTime(String path, Object actual) { Date tmp = null; if (actual instanceof Date) { tmp = (Date) actual; } else { Assert.fail(Messages.verifyRuleDateType(path)); } return tmp; } public boolean isNullable() { return nullable; } public String getField() { return field; } public boolean isManual() { return manual; } } <file_sep>package com.github.bookong.zest.testcase; /** * @author <NAME> */ public abstract class ZestParam { private ZestData zestData; public ZestData getZestData() { return zestData; } public void setZestData(ZestData zestData) { this.zestData = zestData; } } <file_sep>package com.github.bookong.zest.testcase; import com.github.bookong.zest.rule.AbstractRule; import com.github.bookong.zest.runner.ZestWorker; import com.github.bookong.zest.util.Messages; import com.github.bookong.zest.util.ZestDateUtil; import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.Set; /** * @author <NAME> */ public abstract class AbstractRow<T> { protected Logger logger = LoggerFactory.getLogger(getClass()); protected abstract Set<String> getExpectedFields(); public abstract void verify(ZestWorker worker, ZestData zestData, Source source, AbstractTable<?> sourceTable, int rowIdx, T actualData); protected void verify(ZestData zestData, AbstractTable<?> sourceTable, int rowIdx, String fieldName, Object expected, Object actual) { AbstractRule rule = sourceTable.getRuleMap().get(fieldName); if (getExpectedFields().contains(fieldName)) { if (expected != null) { if (rule != null) { logger.info(Messages.verifyRuleIgnore(rule.getField(), rowIdx)); } if (expected instanceof Date) { Assert.assertTrue(Messages.verifyRowDataDate(fieldName), actual instanceof Date); Date expectedDateInZest = ZestDateUtil.getDateInZest(zestData, (Date) expected); String expectedValue = ZestDateUtil.formatDateNormal(expectedDateInZest); String actualValue = ZestDateUtil.formatDateNormal((Date) actual); Assert.assertEquals(Messages.verifyRowData(fieldName, expectedValue), expectedValue, actualValue); } else { String expectedValue = String.valueOf(expected); String actualValue = String.valueOf(actual); Assert.assertEquals(Messages.verifyRowData(fieldName, expectedValue), expectedValue, actualValue); } } else { // expected == null if (rule != null) { rule.verify(zestData, actual); } else { Assert.assertNull(Messages.verifyRowDataNull(fieldName), actual); } } } else if (rule != null) { rule.verify(zestData, actual); } } } <file_sep>package com.github.bookong.zest.util; import com.github.bookong.zest.common.ZestGlobalConstant; import com.github.bookong.zest.exception.ZestException; import com.github.bookong.zest.testcase.sql.Row; import com.github.bookong.zest.testcase.sql.Table; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.datasource.DataSourceUtils; import javax.sql.DataSource; import java.math.BigDecimal; import java.sql.*; import java.sql.Date; import java.util.*; /** * 辅助操作 SQL * * @author <NAME> */ public class ZestSqlHelper { private static Logger logger = LoggerFactory.getLogger(ZestGlobalConstant.Logger.SQL); public static void close(Statement stat) { if (stat != null) { try { stat.close(); } catch (Exception e) { logger.warn("Statement close, {}:{}", e.getClass().getName(), e.getMessage()); } } } public static void close(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (Exception e) { logger.warn("ResultSet close, {}:{}", e.getClass().getName(), e.getMessage()); } } } public static void insert(Connection conn, Table table) { for (Row row : table.getDataList()) { insert(conn, table, row); } } public static void insert(Connection conn, Table table, Row row) { StringBuilder sqlBuff = new StringBuilder(128); StringBuilder valueBuff = new StringBuilder(128); sqlBuff.append("insert into ").append("`").append(table.getName()).append("`("); int idx = 0; Object[] params = new Object[row.getDataMap().size()]; Iterator<String> it = row.getDataMap().keySet().iterator(); while (it.hasNext()) { String columnName = it.next(); Object value = row.getDataMap().get(columnName); params[idx++] = value; sqlBuff.append("`").append(columnName).append("`"); valueBuff.append("?"); if (it.hasNext()) { sqlBuff.append(", "); valueBuff.append(", "); } } sqlBuff.append(") values(").append(valueBuff.toString()).append(")"); execute(conn, sqlBuff.toString(), params); } public static List<Map<String, Object>> find(Connection conn, Table table) { String sql = String.format("select * from `%s`", table.getName()); if (StringUtils.isNotBlank(table.getSort())) { sql = sql.concat(table.getSort()); } Statement stat = null; ResultSet rs = null; try { List<Map<String, Object>> list = new ArrayList<>(); stat = conn.createStatement(); rs = stat.executeQuery(sql); while (rs.next()) { Map<String, Object> obj = new HashMap<>(); list.add(obj); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { String name = rs.getMetaData().getColumnName(i).toLowerCase(); Object value = rs.getObject(i); obj.put(name, findValue(value)); } } return list; } catch (Exception e) { ZestSqlHelper.close(rs); ZestSqlHelper.close(stat); throw new ZestException(e); } } private static Object findValue(Object value) { if (value == null) { return null; } if (value instanceof Integer || value instanceof Long || value instanceof Byte) { return ((Number) value).longValue(); } if (value instanceof Double || value instanceof Float || value instanceof BigDecimal) { return ((Number) value).doubleValue(); } // Timestamp , String return value; } public static void execute(Connection conn, String sql) { Statement stat = null; try { logger.debug(" SQL: {}", sql); stat = conn.createStatement(); stat.executeUpdate(sql); } catch (Exception e) { throw new ZestException(e); } finally { close(stat); } } public static void execute(Connection conn, String sql, Object[] values) { PreparedStatement stat = null; try { if (logger.isDebugEnabled()) { logger.debug(" SQL: {}", sql); if (values != null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < values.length; i++) { Object value = values[i]; if (value == null) { sb.append("NULL"); } else { sb.append("(").append(value.getClass().getSimpleName()).append(")"); sb.append(parseValue(value)); } if (i < values.length - 1) { sb.append(", "); } } logger.debug("PARAMS: {}", sb.toString()); } } stat = conn.prepareStatement(sql); if (values != null) { for (int i = 0; i < values.length; i++) { stat.setObject(i + 1, values[i]); } } stat.execute(); } catch (Exception e) { throw new ZestException(e); } finally { close(stat); } } public static String query(DataSource dataSource, String sql) { Connection conn = DataSourceUtils.getConnection(dataSource); try { return query(conn, sql); } finally { DataSourceUtils.releaseConnection(conn, dataSource); } } public static String query(Connection conn, String sql) { Statement stat = null; ResultSet rs = null; StringBuilder sb = new StringBuilder(); try { stat = conn.createStatement(); rs = stat.executeQuery(sql); while (rs.next()) { sb.append("-------------------------------------------\n"); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { String colName = rs.getMetaData().getColumnName(i).toLowerCase(); Object colValue = rs.getObject(i); String colType = (colValue == null ? "UNKNOWN" : colValue.getClass().getName()); colValue = colValue == null ? "NULL" : parseValue(colValue); sb.append(String.format("%s (%s) : %s", colName, colType, colValue)).append("\n"); } } sb.append("==========================================="); } catch (Exception e) { logger.error("", e); close(rs); close(stat); } return sb.toString(); } private static String parseValue(Object value) { if (value instanceof Date) { return ZestDateUtil.formatDateNormal((Date) value); } else { String str = String.valueOf(value); str = StringUtils.replaceEach(str, // new String[] { "\t", "\r", "\n", "\"", "\\" }, // new String[] { "\\t", "\\r", "\\n", "\\\"", "\\\\" }); if (value instanceof String) { return String.format("\"%s\"", str); } else { return str; } } } } <file_sep>package com.github.bookong.zest.runner.junit4; import com.github.bookong.zest.annotation.ZestTest; import com.github.bookong.zest.runner.ZestClassRunner; import com.github.bookong.zest.runner.junit4.statement.ZestFilter; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.notification.RunNotifier; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; /** * @author <NAME> */ public class ZestSpringJUnit4ClassRunner extends SpringJUnit4ClassRunner implements ZestClassRunner { private ZestJUnit4Worker worker; public ZestSpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError{ super(clazz); worker = new ZestJUnit4Worker(getTestClass(), this); } @Override protected List<FrameworkMethod> computeTestMethods() { return ZestJUnit4Worker.computeTestMethods(getTestClass()); } @Override protected void runChild(FrameworkMethod frameworkMethod, RunNotifier notifier) { ZestTest zestTest = frameworkMethod.getAnnotation(ZestTest.class); if (zestTest == null) { super.runChild(frameworkMethod, notifier); } else { worker.runChild(frameworkMethod, notifier); } } @Override public void filter(Filter filter) throws NoTestsRemainException { super.filter(new ZestFilter(filter)); } @Override public Object createTest() throws Exception { return super.createTest(); } } <file_sep>package com.github.bookong.zest.util; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.github.bookong.zest.exception.ZestException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; /** * @author <NAME> */ public class ZestJsonUtil { public static final Logger logger = LoggerFactory.getLogger(ZestJsonUtil.class); private static final ThreadLocal<ObjectMapper> OBJECT_MAPPER_CACHE = new ThreadLocal<>(); public static String toJson(Object obj) { try { if (obj == null) { return null; } return getObjectMapper().writeValueAsString(obj); } catch (Exception e) { throw new ZestException(e); } } public static String toPrettyJson(Object obj) { try { if (obj == null) { return null; } return getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(obj); } catch (Exception e) { throw new ZestException(e); } } public static <T> List<T> fromJsonArray(String content, Class<T> valueType) { try { if (StringUtils.isBlank(content)) { return Collections.emptyList(); } JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(List.class, valueType); return getObjectMapper().readValue(content, javaType); } catch (Exception e) { throw new ZestException(e); } } public static <T> T fromJson(String content, Class<T> valueType) { try { if (StringUtils.isBlank(content)) { return null; } return getObjectMapper().readValue(content, valueType); } catch (Exception e) { throw new ZestException(e); } } private static ObjectMapper getObjectMapper() { ObjectMapper objectMapper = OBJECT_MAPPER_CACHE.get(); if (objectMapper == null) { objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); OBJECT_MAPPER_CACHE.set(objectMapper); } return objectMapper; } } <file_sep>package com.github.bookong.zest.testcase; import com.github.bookong.zest.exception.ZestException; import com.github.bookong.zest.runner.ZestWorker; import com.github.bookong.zest.support.xml.XmlNode; import com.github.bookong.zest.util.Messages; import org.w3c.dom.Node; import java.util.*; /** * @author <NAME> */ public class SourceInitData extends AbstractSourceData { /** 执行前,初始化数据源用的数据 */ private List<AbstractTable> tableList = new ArrayList<>(); public SourceInitData(ZestWorker worker, ZestData zestData, String sourceId, Node node, Map<String, String> tableEntityClassMap){ try { XmlNode xmlNode = new XmlNode(node); xmlNode.checkSupportedAttrs(); tableList.addAll(createTables(worker, zestData, sourceId, node, false, tableEntityClassMap)); } catch (Exception e) { throw new ZestException(Messages.parseSourceInitError(), e); } } public List<AbstractTable> getTableList() { return tableList; } } <file_sep>package com.github.bookong.zest.util; import com.github.bookong.zest.exception.ZestException; import com.github.bookong.zest.rule.CurrentTimeRule; import com.github.bookong.zest.rule.FromCurrentTimeRule; import com.github.bookong.zest.rule.RegExpRule; import com.github.bookong.zest.testcase.ZestData; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import java.text.SimpleDateFormat; import java.util.Date; /** * @author <NAME> */ public class ZestAssertUtil { /** 比较时间(考虑数据偏移情况) */ public static void dateEquals(ZestData zestData, String msg, String dateFormat, String expected, String actual) { try { if (StringUtils.isBlank(expected)) { Assert.assertTrue(msg, StringUtils.isBlank(actual)); } else { SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); dateEquals(zestData, msg, sdf.parse(expected), sdf.parse(actual)); } } catch (Exception e) { throw new ZestException(e); } } /** 比较时间(考虑数据偏移情况) */ public static void dateEquals(ZestData zestData, String msg, Date expected, Date actual) { Date expectedInZest = ZestDateUtil.getDateInZest(zestData, expected); Assert.assertEquals(msg, ZestDateUtil.formatDateNormal(expectedInZest), ZestDateUtil.formatDateNormal(actual)); } public static void verifyRegExpRule(ZestData zestData, String field, String regExp, Object actual) { verifyRegExpRule(zestData, field, false, regExp, actual); } public static void verifyRegExpRule(ZestData zestData, String field, boolean nullable, String regExp, Object actual) { new RegExpRule(field, nullable, regExp).verify(zestData, actual); } public static void verifyCurrentTimeRule(ZestData zestData, String field, Object actual) { verifyCurrentTimeRule(zestData, field, false, 1000, actual); } public static void verifyCurrentTimeRule(ZestData zestData, String field, boolean nullable, int offset, Object actual) { new CurrentTimeRule(field, nullable, offset).verify(zestData, actual); } public static void verifyFromCurrentTimeRule(ZestData zestData, String field, int min, int max, int unit, Object actual) { verifyFromCurrentTimeRule(zestData, field, false, min, max, unit, 1000, actual); } public static void verifyFromCurrentTimeRule(ZestData zestData, String field, boolean nullable, int min, int max, int unit, int offset, Object actual) { new FromCurrentTimeRule(field, nullable, min, max, unit, offset).verify(zestData, actual); } } <file_sep>package com.github.bookong.zest.testcase.data.rules; import com.github.bookong.zest.testcase.data.AbstractZestDataTest; import com.github.bookong.zest.util.Messages; import org.junit.Test; /** * @author <NAME> */ public class ZestDataTest extends AbstractZestDataTest { @Test public void testLoad01() { testLoadError("01.xml", Messages.parseSourcesError(), // Messages.parseSourceError("mysql"), // Messages.parseSourceVerifyError(), // Messages.parseTableError("tab"), // Messages.parseRulesError(), // Messages.parseCommonChildrenList("Rules", "Rule")); } @Test public void testLoad02() { testLoadError("02.xml", Messages.parseSourcesError(), // Messages.parseSourceError("mysql"), // Messages.parseSourceVerifyError(), // Messages.parseTableError("tab"), // Messages.parseRulesError(), // Messages.parseCommonAttrUnknown("Rules", "U")); } } <file_sep>package com.github.bookong.zest.testcase.data.table; import com.github.bookong.zest.testcase.SourceInitData; import com.github.bookong.zest.testcase.ZestData; import com.github.bookong.zest.testcase.data.AbstractZestDataTest; import com.github.bookong.zest.util.Messages; import org.junit.Assert; import org.junit.Test; /** * @author <NAME> */ public class ZestDataTest extends AbstractZestDataTest { @Test public void testLoad01() { testLoadError("01.xml", Messages.parseSourcesError(), // Messages.parseSourceError("mongo"), // Messages.parseSourceInitError(), // Messages.parseTableError("user"), // Messages.parseCommonAttrEmpty("EntityClass")); } @Test public void testLoad02() { testLoadError("02.xml", Messages.parseSourcesError(), // Messages.parseSourceError("mongo"), // Messages.parseSourceVerifyError(), // Messages.parseTableError("user"), // Messages.parseCommonAttrEmpty("EntityClass")); } @Test public void testLoad03() { logger.info("Normal data"); ZestData zestData = load("03.xml"); Assert.assertEquals(1, zestData.getSourceList().size()); SourceInitData obj = zestData.getSourceList().get(0).getInitData(); Assert.assertEquals(1, obj.getTableList().size()); Assert.assertEquals("tab", obj.getTableList().get(0).getName()); Assert.assertFalse(obj.getTableList().get(0).isIgnoreVerify()); } @Test public void testLoad04() { testLoadError("04.xml", Messages.parseSourcesError(), // Messages.parseSourceError("mysql"), // Messages.parseSourceInitError(), // Messages.parseTableError("tab"), // Messages.parseCommonAttrUnknown("Table", "U")); } @Test public void testLoad05() { testLoadError("05.xml", Messages.parseSourcesError(), // Messages.parseSourceError("mysql"), // Messages.parseSourceVerifyError(), // Messages.parseTableError("tab"), // Messages.parseCommonChildrenUnknown("Table", "Other")); } @Test public void testLoad06() { testLoadError("06.xml", Messages.parseSourcesError(), // Messages.parseSourceError("mysql"), // Messages.parseSourceInitError(), // Messages.parseTableError("tab"), // Messages.parseCommonChildrenUnknown("Table", "Other")); } } <file_sep>package com.github.bookong.zest.testcase; import com.github.bookong.zest.common.ZestGlobalConstant.Xml; import com.github.bookong.zest.exception.ZestException; import com.github.bookong.zest.runner.ZestWorker; import com.github.bookong.zest.support.xml.XmlNode; import com.github.bookong.zest.util.*; import org.apache.commons.lang3.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.*; /** * @author <NAME> */ public class ZestData { private float version; /** 测试数据文件名称 */ private String fileName; /** 测试数据文件路径 */ private String filePath; /** 对于日期类型,在插入数据库时是否需要做偏移处理 */ private boolean transferTime = false; /** 如果日期需要偏移处理,当前时间与测试用例上描述的时间相差多少毫秒 */ private long currentTimeDiff; /** 描述 */ private String description; /** 测试参数 */ private ZestParam param; /** 数据源描述 */ private List<Source> sourceList = new ArrayList<>(); /** 开始进行测试的时间 */ private long startTime; /** 测试结束的时间 */ private long endTime; public ZestData(String filePath){ this.filePath = filePath; this.fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1); } public void load(ZestWorker worker) { try { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(getFilePath())); XmlNode xmlNode = new XmlNode(doc); List<Node> rootElements = xmlNode.getChildren(); if (rootElements.size() != 1 || !Xml.ZEST.equals(rootElements.get(0).getNodeName())) { throw new ZestException(Messages.parseZest()); } loadZest(worker, rootElements.get(0)); } catch (Exception e) { throw new ZestException(Messages.parse(getFilePath()), e); } } private void loadZest(ZestWorker worker, Node node) { XmlNode xmlNode = new XmlNode(node); this.version = xmlNode.getAttrFloat(Xml.VERSION, 1.0F); String currentTime = xmlNode.getAttr(Xml.CURRENT_TIME); this.transferTime = StringUtils.isNotBlank(currentTime); if (isTransferTime()) { Date currDbTime = ZestDateUtil.parseDate(currentTime); Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); this.currentTimeDiff = cal.getTimeInMillis() - currDbTime.getTime(); } xmlNode.checkSupportedAttrs(Xml.VERSION, Xml.CURRENT_TIME); List<Node> children = xmlNode.getSpecifiedNodes(Messages.parseZestNecessary(), // Xml.DESCRIPTION, Xml.SOURCES, Xml.PARAM); this.description = new XmlNode(children.get(0)).getNodeValue(); loadSources(worker, children.get(1)); loadParam(children.get(2)); } private void loadSources(ZestWorker worker, Node node) { try { XmlNode xmlNode = new XmlNode(node); xmlNode.checkSupportedAttrs(); List<Node> children = xmlNode.getFixedNodeList(Messages.parseCommonChildrenList(Xml.SOURCES, Xml.SOURCE), Xml.SOURCE); Set<String> sourceIds = new HashSet<>(children.size() + 1); for (Node child : children) { getSourceList().add(new Source(worker, this, child, sourceIds)); } } catch (Exception e) { throw new ZestException(Messages.parseSourcesError(), e); } } private void loadParam(Node node) { try { XmlNode xmlNode = new XmlNode(node); xmlNode.checkSupportedAttrs(); List<Node> children = xmlNode.getFixedNodeList(Messages.parseCommonChildrenList(Xml.PARAM, Xml.PARAM_FIELD), Xml.PARAM_FIELD); Set<String> fieldNames = new HashSet<>(children.size() + 1); for (Node child : children) { loadParamField(child, fieldNames); } } catch (Exception e) { throw new ZestException(Messages.parseParamError(), e); } } private void loadParamField(Node node, Set<String> fieldNames) { XmlNode xmlNode = new XmlNode(node); xmlNode.checkSupportedAttrs(Xml.NAME); String fieldName = xmlNode.getAttrNotEmpty(Xml.NAME); XmlNode.duplicateCheck(Xml.NAME, fieldNames, fieldName); Field field = ZestReflectHelper.getField(param, fieldName); if (field == null) { throw new ZestException(Messages.parseParamNone(fieldName)); } try { String value = xmlNode.getNodeValue(); Class<?> fieldClass = field.getType(); if (Integer.class.isAssignableFrom(fieldClass) || "int".equals(fieldClass.getName())) { ZestReflectHelper.setValue(param, fieldName, Integer.valueOf(value.trim())); } else if (Long.class.isAssignableFrom(fieldClass) || "long".equals(fieldClass.getName())) { ZestReflectHelper.setValue(param, fieldName, Long.valueOf(value.trim())); } else if (Boolean.class.isAssignableFrom(fieldClass) || "boolean".equals(fieldClass.getName())) { ZestReflectHelper.setValue(param, fieldName, Boolean.valueOf(value.trim())); } else if (Double.class.isAssignableFrom(fieldClass) || "double".equals(fieldClass.getName())) { ZestReflectHelper.setValue(param, fieldName, Double.valueOf(value.trim())); } else if (Float.class.isAssignableFrom(fieldClass) || "float".equals(fieldClass.getName())) { ZestReflectHelper.setValue(param, fieldName, Float.valueOf(value.trim())); } else if (String.class.isAssignableFrom(fieldClass)) { ZestReflectHelper.setValue(param, fieldName, value); } else if (Date.class.isAssignableFrom(fieldClass)) { ZestReflectHelper.setValue(param, fieldName, ZestDateUtil.parseDate(value)); } else if (List.class.isAssignableFrom(fieldClass)) { Class<?> listValueClass = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; ZestReflectHelper.setValue(param, fieldName, ZestJsonUtil.fromJsonArray(value, listValueClass)); } else if (Map.class.isAssignableFrom(fieldClass)) { throw new ZestException(Messages.parseParamNonsupportMap()); } else { ZestReflectHelper.setValue(param, fieldName, ZestJsonUtil.fromJson(value, fieldClass)); } } catch (Exception e) { throw new ZestException(Messages.parseParamObjLoad(fieldName), e); } } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public boolean isTransferTime() { return transferTime; } public long getCurrentTimeDiff() { return currentTimeDiff; } public String getDescription() { return description; } public ZestParam getParam() { return param; } public void setParam(ZestParam param) { this.param = param; } public List<Source> getSourceList() { return sourceList; } public long getStartTime() { return startTime; } public void setStartTime(long startTime) { this.startTime = startTime; } public long getEndTime() { return endTime; } public void setEndTime(long endTime) { this.endTime = endTime; } public float getVersion() { return version; } } <file_sep>package com.github.bookong.zest.rule; import com.github.bookong.zest.common.ZestGlobalConstant.Xml; import com.github.bookong.zest.exception.ZestException; import com.github.bookong.zest.support.xml.XmlNode; import com.github.bookong.zest.testcase.ZestData; import com.github.bookong.zest.util.Messages; import com.github.bookong.zest.util.ZestDateUtil; import org.junit.Assert; import org.w3c.dom.Node; import java.util.Calendar; import java.util.Date; /** * @author <NAME> */ public class FromCurrentTimeRule extends AbstractRule { private int min; private int max; private int unit; private int offset; public FromCurrentTimeRule(String field, boolean nullable, int min, int max, int unit, int offset){ super(field, nullable, true); this.min = min; this.max = max; switch (unit) { case Calendar.DAY_OF_YEAR: case Calendar.DAY_OF_MONTH: case Calendar.DAY_OF_WEEK: case Calendar.DAY_OF_WEEK_IN_MONTH: this.unit = Calendar.DAY_OF_YEAR; break; case Calendar.HOUR_OF_DAY: case Calendar.HOUR: this.unit = Calendar.HOUR_OF_DAY; break; case Calendar.MINUTE: this.unit = Calendar.MINUTE; break; case Calendar.SECOND: this.unit = Calendar.SECOND; break; default: throw new ZestException(Messages.parseRuleManualFromUnitUnknown(unit)); } this.offset = offset; } public FromCurrentTimeRule(Node node, String field, boolean nullable){ super(field, nullable, false); XmlNode xmlNode = new XmlNode(node); xmlNode.checkSupportedAttrs(Xml.MIN, Xml.MAX, Xml.UNIT, Xml.OFFSET); xmlNode.mustNoChildren(); this.min = xmlNode.getAttrInt(Xml.MIN); this.max = xmlNode.getAttrInt(Xml.MAX); this.offset = xmlNode.getAttrInt(Xml.OFFSET, 1000); String str = xmlNode.getAttrNotEmpty(Xml.UNIT); switch (str) { case Xml.DAY: unit = Calendar.DAY_OF_YEAR; break; case Xml.HOUR: unit = Calendar.HOUR_OF_DAY; break; case Xml.MINUTE: unit = Calendar.MINUTE; break; case Xml.SECOND: unit = Calendar.SECOND; break; default: throw new ZestException(Messages.parseRuleFromUnitUnknown(str)); } } @Override public void verify(ZestData zestData, Object actual) { if (actual == null) { if (!isNullable()) { Assert.fail(Messages.verifyRuleNotNull(getField())); } } else { long zestEndTime = zestData.getEndTime(); if (isManual()) { zestEndTime = System.currentTimeMillis(); } Date actualDate = getActualDataTime(getField(), actual); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(zestData.getStartTime()); cal.add(getUnit(), getMin()); cal.add(Calendar.MILLISECOND, -getOffset()); Date startTime = cal.getTime(); cal.setTimeInMillis(zestEndTime); cal.add(getUnit(), getMax()); cal.add(Calendar.MILLISECOND, getOffset()); Date endTime = cal.getTime(); Assert.assertTrue(Messages.verifyRuleDateFrom(getField(), ZestDateUtil.formatDateNormal(startTime), ZestDateUtil.formatDateNormal(endTime), ZestDateUtil.formatDateNormal(actualDate)), (actualDate.getTime() >= startTime.getTime() && actualDate.getTime() <= endTime.getTime())); } } public int getMin() { return min; } public int getMax() { return max; } public int getUnit() { return unit; } public int getOffset() { return offset; } } <file_sep>package com.github.bookong.zest.runner; /** * @author <NAME> */ public interface ZestClassRunner { Object createTest() throws Exception; }
745136c50409823ee013bf7ed90bb26c265a6f89
[ "Java" ]
13
Java
MingZ3234/zest
920d72830e12bcf2ba8dcab235c08581fcaf7169
e2140133c9d6f98c1b350eae48f47b22798a0125
refs/heads/master
<repo_name>GD1016/CodeSnippets<file_sep>/Rekursion.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StackOverflow { class Program { static void Main(string[] args) { Console.WriteLine(BerechneSummeBis(100)); Console.ReadLine(); } //static int BerechneSummeBis(int n) { // for (int i = 0; i == n; i++) { // result += i; // } // return result; //} static int BerechneSummeBis(int n) { if (n == 1) { return 1; } return BerechneSummeBis(n - 1) + n; } } }
470dd26de98b198901fe3ba725ca575b53dcb978
[ "C#" ]
1
C#
GD1016/CodeSnippets
af02873613648e8fd59eb580e29df6edb7ee409c
3b5e492b524d09f3b9735e096dc0bd67d780500c
refs/heads/main
<repo_name>login101i/React-Todo-List<file_sep>/src/App.js import React, { useState, useEffect } from 'react'; import './App.css'; import { Button, FormControl, InputLabel, Input, FormHelperText } from '@material-ui/core'; import Todo from './components/Todo' import { db } from './firebase'; import firebase from "firebase" import { makeStyles } from "@material-ui/core/styles"; const useStyles = makeStyles((theme) => ({ buttonAdd: { width: 150, margin: "10px", backgroundColor: 'green', color:"white", }, }) ) function App() { const [todos, setTodos] = useState([]) const [input, setInput] = useState("") const classes = useStyles(); console.log(todos) // when the app loads, we need to listen to database and then we get some data using fetch, useEffect(() => { // fires when app is loaded db.collection('todos').orderBy("timestamp", "desc").onSnapshot(snapshot => { // console.log(snapshot.docs.map(doc => doc.data().todos)) // console.log(snapshot.docs.map(doc => doc.data())) setTodos(snapshot.docs.map(doc => ({ id: doc.id, todo: doc.data().todo }))) }) }, []) // Function on button to add todo const addTodo = (Event) => { Event.preventDefault(); db.collection('todos').add({ todo: input, timestamp: firebase.firestore.FieldValue.serverTimestamp() }) setInput(""); } return ( <div className="App"> <h1 className="App-header">Todo List </h1> {/* Wraping up in form to make sure enter key will submiting the form */} <form className="form"> <FormControl> {/* <InputLabel><span role="img" aria-label="emoji"> </span> Write here</InputLabel> */} <InputLabel> Write here</InputLabel> <Input autoCapitalize={true} value={input} onChange={event => setInput(event.target.value)} /> <FormHelperText>Thank you for using this form.</FormHelperText> </FormControl> {/* using material ui */} <Button className={classes.buttonAdd} disabled={!input} type="submit" variant="contained" onClick={addTodo}> Add </Button> </form> <ul className="listContainer"> {todos.map(todo => ( <Todo todo={todo} /> ))} </ul> </div> ); } export default App; <file_sep>/src/components/Todo.js import React, { useState } from "react"; import { List, ListItem, ListItemText, ListItemAvatar, Button, Modal, Input, } from "@material-ui/core"; import './todo.css' import { db } from '../firebase' import { makeStyles } from "@material-ui/core/styles"; import DeleteIcon from "@material-ui/icons/Delete"; import EditIcon from '@material-ui/icons/Edit'; import FlipMove from 'react-flip-move'; const useStyles = makeStyles((theme) => ({ modal: { position: "absolute", // position: "center", minWidth: 400, maxWidth:800, borderRadius: 17, backgroundColor: theme.palette.background.paper, // border: "2px solid #000", boxShadow: theme.shadows[5], padding: theme.spacing(2, 4, 3), left: '50%', top: '50%', transform: 'translate(-50%,-50%)', border: 'none', }, button: { width: 150, // border: '2px solid #000', margin: "10px", }, buttonUpdate: { width: 150, // border: '2px solid #000', margin: "10px", backgroundColor: 'green', color: 'white' }, head: { textAlign: 'center' }, input: { height: 25, marginRight: 33 }, container: { display: 'flex', justifyContent: 'center', alignItems: 'center' }, itemText: { textTransform: 'capitalize' } })); function Todo(props) { const [open, setOpen] = useState(false); const [input, setInput] = useState(); const classes = useStyles(); const handleOpen = () => { setOpen(true); }; const updateTodo = () => { // update the todo with the new input db.collection("todos").doc(props.todo.id).set( { todo: input, }, { merge: true } ); setOpen(false); }; const customLeaveAnimation = { from: { transform: 'scale(1, 1)' }, to: { transform: 'scale(0.5, 1) translateY(-20px)' } }; return ( <> <Modal open={open} onClose={(e) => setOpen(false)}> <div className={classes.modal}> <h2 className={classes.head}>Update Task</h2> <div className={classes.container}> <input placeholder={props.todo.todo} value={input} onChange={(Event) => setInput(Event.target.value)} className={classes.input} /> <Button variant="contained" color="default" onClick={updateTodo} className={classes.buttonUpdate} disabled={!input} > Upload ✔ </Button> </div> </div> </Modal> <FlipMove leaveAnimation={customLeaveAnimation}> <div className="todoList__container"> <List className="todo__list"> <ListItem> <ListItemAvatar></ListItemAvatar> <ListItemText className={classes.itemText} primary={props.todo.todo} /> </ListItem> <Button variant="contained" color="secondary" onClick={(Event) => db.collection("todos").doc(props.todo.id).delete() } className={classes.button} startIcon={<DeleteIcon />} > Delete </Button> <Button variant="contained" color="primary" onClick={(e) => setOpen(true)} className={classes.button} endIcon={<EditIcon>send</EditIcon>} > Edit </Button> {/* <Button className="edit__btn" onClick={e => setOpen(true)}>Edit</Button> */} {/* <DeleteForeverIcon onClick={Event =>db.collection('todos').doc(props.todo.id).delete()}>❌Delete</DeleteForeverIcon> */} </List> </div> </FlipMove> </> ); } export default Todo; <file_sep>/src/firebase.js // For Firebase JS SDK v7.20.0 and later, measurementId is optional import firebase from 'firebase' const firebaseApp=firebase.initializeApp({ apiKey: "<KEY>", authDomain: "todoapp-55075.firebaseapp.com", projectId: "todoapp-55075", storageBucket: "todoapp-55075.appspot.com", messagingSenderId: "101017404890", appId: "1:101017404890:web:fa873a17100e59cc6cece3", measurementId: "G-93KVDQBRJX" }) const db=firebaseApp.firestore() export {db}
4f79c76650cefe4895d1a86261bfeb6c60dd6546
[ "JavaScript" ]
3
JavaScript
login101i/React-Todo-List
07ad6a6369f3a5640eb7fe5138205d063c807bcd
7bf7f00179d1d1c53ad0febd411c3bb11bbcb731
refs/heads/master
<file_sep>package application; import java.util.List; import java.io.Serializable; import java.util.ArrayList; public class Stock implements Serializable { private List<Item> supply = new ArrayList<Item>(); private List<String> category = new ArrayList<String>(); public Stock() { } public String addCat(String addable) { // Admin String correct = addable.toLowerCase(); for (int i = 0; i < category.size(); i++) { if (category.get(i).equals(correct)) return "Categroy can not be added, because it's already exists."; } category.add(correct); return (addable + " succesfully added."); } public String removeCat(String removable) { // Admin String correct = removable.toLowerCase(); for (int i = 0; i < supply.size(); i++) { if (supply.get(i).getStr()[1].equals(correct)) return "Categroy can not be removed."; } category.remove(correct); return (removable + " succesfully removed."); } public String addItem(Item in, int db, String cat, String path) { // Admin for (int i = 0; i < supply.size(); i++) if (supply.get(i).getStr()[0].equals(in.getStr()[0])) return in.getStr()[0] + " already exists."; in.db = db; in.defCat(cat); this.addCat(cat); in.setPath(path); supply.add(in); return "Done."; } public String removeItem(String in) { // Admin for (int i = 0; i < supply.size(); i++) if (supply.get(i).getStr()[0].equals(in)) { supply.remove(i); return in + " succesfully removed."; } return "There is no " + in + " in the warehouse."; } public String sell(String out, int db) { // User for (int i = 0; i < supply.size(); i++) { if (supply.get(i).getStr()[0].equals(out)) { if (db > supply.get(i).db) return "There are not enough pieces in the store!"; else { supply.get(i).db -= db; return "Succesfully sold!"; } } } return ""; } public List<String> getCats() { return category; } public List<String> getNames() { List<String> tmp = new ArrayList<String>(); for (int i = 0; i < supply.size(); i++) tmp.add(supply.get(i).getStr()[0]); return tmp; } public List<Item> getSupply() { return supply; } } <file_sep>confirm= Fizetés! keres=Keresés... allTab=Minden srcTab=Sz\u0171rt summa=Összesen: <file_sep>confirm= Check out! keres=Search... allTab=All srcTab=Searched summa=Total: <file_sep>package application; import java.io.Serializable; public class Item implements Serializable { private String name; private String category; private int price; public int db; private String PhotoPath; public Item(String n, int prc) { name=n; price=prc; db=0; PhotoPath="photos/no_photo.png"; } public String defCat(String in) { category=in; return "You succesfully categorized "+name; } public String[] getStr() { String[] out= {this.name,this.category,PhotoPath}; return out; } public int[] getNumb() { int[] out= {this.price,this.db}; return out; } public void setPath(String in) { PhotoPath=in; } } <file_sep>Szórakoztató elektronika beadandó.<br> Első JavaFX alkalmazásom, ami egy webshop grafikus felületét és pár, a boltban elérhető termék raktározását valósítja meg.<br><br> 2 felhasználó van: <li>admin - pw: admin</li> <li>user - pw: user</li> <br><br> Amiket használtam: <li>Multi-language: *.properties</li> <li>Formatting: *.fxml</li> <li>Style: User.CSS</li> Részletes dokumentáció a fájlok közt: "_**Szórakoztatóelektronikai eszközök programozása házi feladat.pdf**_"
3278af8ebe4e10ccfa9e7e87761e76217e768208
[ "Markdown", "Java", "INI" ]
5
Java
Berzegeri/Shop
422d73dd0493d4c2cc410b5ad239f8a41e61fd40
33f1e768cbaad3678fd72335be268f05be34b568
refs/heads/master
<file_sep>export default { "TFT3_Ziggs": { "ability": { "desc": "Ziggs throws a bomb at an enemy, dealing @ModifiedDamage@ magic damage.", "icon": "ASSETS/Characters/Ziggs/HUD/Icons2D/ZiggsQ.dds", "name": "Bomb!", "variables": [ { "name": "Damage", "value": [ 70, 300, 400, 700, 550, 650, 750 ] } ] }, "apiName": "TFT3_Ziggs", "cost": 1, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Ziggs.TFT_Set3.dds", "name": "Ziggs", "stats": { "armor": 20, "attackSpeed": 0.699999988079071, "critChance": 0.25, "critMultiplier": 1.5, "damage": 40, "hp": 500, "initialMana": 0, "magicResist": 20, "mana": 40, "range": 3 }, "traits": [ "Rebel", "Demolitionist" ] }, "TFT3_Jinx": { "ability": { "desc": "Passive: Jinx gets excited as she helps take down enemy units!<br><br>After her first takedown, Jinx gains @PercentAttackSpeed@ bonus Attack Speed.<br><br>After her second takedown, Jinx swaps to her rocket launcher, causing her Basic Attacks to deal @ModifiedDamage@ bonus magic damage to all enemies in a small area around her target.", "icon": "ASSETS/Characters/Jinx/HUD/Icons2D/Jinx_Passive.dds", "name": "Get Excited!", "variables": [ { "name": "HitWindow", "value": [ 10, 10, 10, 10, 10, 10, 10 ] }, { "name": "BuffDuration", "value": [ 60, 60, 60, 60, 60, 60, 60 ] }, { "name": "AttackSpeedBonus", "value": [ 0.4000000059604645, 0.6000000238418579, 0.75, 1, 1.2000000476837158, 1.399999976158142, 1.600000023841858 ] }, { "name": "RocketDamage", "value": [ 0, 125, 200, 750, 1000, 500, 600 ] } ] }, "apiName": "TFT3_Jinx", "cost": 4, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Jinx.TFT_Set3.dds", "name": "Jinx", "stats": { "armor": 20, "attackSpeed": 0.75, "critChance": 0.25, "critMultiplier": 1.5, "damage": 70, "hp": 600, "initialMana": 0, "magicResist": 20, "mana": 0, "range": 3 }, "traits": [ "Rebel", "Blaster" ] }, "TFT3_Sona": { "ability": { "desc": "Sona heals @NumberOfTargets@ injured allies for @ModifiedHealing@ and cleanses them of stuns.", "icon": "ASSETS/Characters/Sona/HUD/Icons2D/Sona_W.dds", "name": "<NAME>", "variables": [ { "name": "HealAmount", "value": [ 150, 150, 200, 300, 300, 300, 300 ] }, { "name": "NumberOfTargets", "value": [ 2, 2, 3, 4, 4, 4, 4 ] } ] }, "apiName": "TFT3_Sona", "cost": 2, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Sona.TFT_Set3.dds", "name": "Sona", "stats": { "armor": 20, "attackSpeed": 0.6499999761581421, "critChance": 0.25, "critMultiplier": 1.5, "damage": 40, "hp": 550, "initialMana": 0, "magicResist": 20, "mana": 40, "range": 3 }, "traits": [ "Rebel", "Mystic" ] }, "TFT3_Yasuo": { "ability": { "desc": "Yasuo blinks to the farthest enemy in range, knocks them up for @StunDuration@ seconds, and Attacks them @ModifiedAttacks@ times (applies on-hit effects).", "icon": "ASSETS/Characters/Yasuo/HUD/Icons2D/Yasuo_R.dds", "name": "<NAME>", "variables": [ { "name": "StunDuration", "value": [ 1, 1, 1, 1, 1, 1, 1 ] }, { "name": "Damage", "value": [ 100, 100, 100, 100, 100, 100, 100 ] }, { "name": "NumHits", "value": [ 3, 4, 5, 6, 7, 8, 9 ] } ] }, "apiName": "TFT3_Yasuo", "cost": 2, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Yasuo.TFT_Set3.dds", "name": "Yasuo", "stats": { "armor": 30, "attackSpeed": 0.75, "critChance": 0.25, "critMultiplier": 1.5, "damage": 50, "hp": 700, "initialMana": 0, "magicResist": 20, "mana": 90, "range": 1 }, "traits": [ "Rebel", "Blademaster" ] }, "TFT3_Malphite": { "ability": { "desc": "Passive: Malphite starts combat with a shield equal to @ModifiedPercentHealth@ of his maximum health.", "icon": "ASSETS/Characters/Malphite/HUD/Icons2D/Malphite_GraniteShield.dds", "name": "Energy Shield", "variables": [ { "name": "PercentHealth", "value": [ 0.3499999940395355, 0.4000000059604645, 0.44999998807907104, 0.6000000238418579, 0.550000011920929, 0.6000000238418579, 0.6499999761581421 ] }, { "name": "SecondsPerRefresh", "value": [ 0, 9, 9, 9, 9, 9, 9 ] } ] }, "apiName": "TFT3_Malphite", "cost": 1, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Malphite.TFT_Set3.dds", "name": "Malphite", "stats": { "armor": 30, "attackSpeed": 0.5, "critChance": 0.25, "critMultiplier": 1.5, "damage": 70, "hp": 700, "initialMana": 0, "magicResist": 20, "mana": 0, "range": 1 }, "traits": [ "Rebel", "Brawler" ] }, "TFT3_MasterYi": { "ability": { "desc": "For @Duration@ seconds Master Yi gains massively increased movement speed, heals for @ModifiedHeal@ of his maximum health each second, and deals @ModifiedDamage@ bonus true damage with his Basic Attacks.", "icon": "ASSETS/Characters/MasterYi/HUD/Icons2D/MasterYi_W.dds", "name": "<NAME>", "variables": [ { "name": "Duration", "value": [ 5, 5, 5, 5, 5, 5, 5 ] }, { "name": "HealAmountPercent", "value": [ 0, 0.11999999731779099, 0.11999999731779099, 0.11999999731779099, 0.20000000298023224, 0.20000000298023224, 0.20000000298023224 ] }, { "name": "BonusTrueDamage", "value": [ 0, 75, 100, 200, 0, 0, 0 ] } ] }, "apiName": "TFT3_MasterYi", "cost": 3, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_MasterYi.TFT_Set3.dds", "name": "<NAME>", "stats": { "armor": 30, "attackSpeed": 0.800000011920929, "critChance": 0.25, "critMultiplier": 1.5, "damage": 55, "hp": 750, "initialMana": 0, "magicResist": 20, "mana": 55, "range": 1 }, "traits": [ "Rebel", "Blademaster" ] }, "TFT3_AurelionSol": { "ability": { "desc": "Aurelion Sol launches fighters which fly out to random enemies, deal @ModifiedDamage@ magic damage, and then return. Aurelion Sol launches all ready fighters, plus @FightersPerCast@ more, when he casts.<br><br>Fighters prefer to target nearby enemies.<br><br>", "icon": "ASSETS/Characters/AurelionSol/HUD/Icons2D/AurelionSol_W_StarsOut.dds", "name": "Mobilize the Fleet", "variables": [ { "name": "Damage", "value": [ 0, 100, 150, 750, 1000, 1000, 1000 ] }, { "name": "InitialFighters", "value": null }, { "name": "FightersPerCast", "value": [ 3, 3, 3, 3, 3, 3, 3 ] } ] }, "apiName": "TFT3_AurelionSol", "cost": 5, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_AurelionSol.TFT_Set3.dds", "name": "Aurelion Sol", "stats": { "armor": 35, "attackSpeed": 0.800000011920929, "critChance": 0.25, "critMultiplier": 1.5, "damage": null, "hp": 1100, "initialMana": 40, "magicResist": 20, "mana": 120, "range": 1 }, "traits": [ "Rebel", "Starship" ] }, "TFT3_MissFortune": { "ability": { "desc": "Miss Fortune channels and fires waves of bullets in a cone for @ChannelDuration@ seconds, dealing @ModifiedPercentHealth@ of enemies' maximum health in magic damage over the duration.", "icon": "ASSETS/Characters/MissFortune/HUD/Icons2D/MissFortune_R.dds", "name": "Bullet Time", "variables": [ { "name": "Waves", "value": [ 12, 12, 12, 12, 12, 12, 12 ] }, { "name": "TotalDamage", "value": [ 500, 500, 900, 9001, 3400, 4100, 4800 ] }, { "name": "ChannelDuration", "value": [ 2.25, 2.25, 2.25, 2.25, 2.25, 2.25, 2.25 ] }, { "name": "HexRange", "value": [ 6, 6, 6, 6, 6, 6, 6 ] }, { "name": "ShieldAmount", "value": [ 100, 400, 700, 1000, 1300, 1600, 1900 ] }, { "name": "PercentMaxHealth", "value": [ 0.20000000298023224, 0.6000000238418579, 0.800000011920929, 9.989999771118164, 5, 5, 5 ] }, { "name": "UpgradeMoreWaves", "value": [ 0, 5, 5, 5, 5, 5, 5 ] } ] }, "apiName": "TFT3_MissFortune", "cost": 5, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_MissFortune.TFT_Set3.dds", "name": "<NAME>", "stats": { "armor": 20, "attackSpeed": 1, "critChance": 0.25, "critMultiplier": 1.5, "damage": 60, "hp": 800, "initialMana": 75, "magicResist": 20, "mana": 175, "range": 4 }, "traits": [ "Valkyrie", "Mercenary", "Blaster" ] }, "TFT3_KaiSa": { "ability": { "desc": "Kai'Sa launches @NumMissiles@ missiles towards each nearby enemy that deal @ModifiedDamage@ magic damage.", "icon": "ASSETS/Characters/Kaisa/HUD/Icons2D/Kaisa_Q.dds", "name": "Missile Rain", "variables": [ { "name": "HexRange", "value": [ 2, 2, 2, 2, 2, 2, 2 ] }, { "name": "NumMissiles", "value": [ 4, 4, 6, 9, 12, 12, 12 ] }, { "name": "FakeCastTime", "value": [ 1, 1, 1, 1, 1, 1, 1 ] }, { "name": "Damage", "value": [ 50, 50, 50, 50, 50, 50, 50 ] }, { "name": "Radius", "value": [ 420, 420, 420, 420, 420, 420, 420 ] } ] }, "apiName": "TFT3_KaiSa", "cost": 2, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_KaiSa.TFT_Set3.dds", "name": "Kai'Sa", "stats": { "armor": 20, "attackSpeed": 0.75, "critChance": 0.25, "critMultiplier": 1.5, "damage": 50, "hp": 550, "initialMana": 0, "magicResist": 20, "mana": 60, "range": 2 }, "traits": [ "Valkyrie", "Infiltrator" ] }, "TFT3_Kayle": { "ability": { "desc": "Kayle Ascends, causing her attacks to launch waves that deal @ModifiedDamage@ bonus magic damage.", "icon": "ASSETS/Characters/Kayle/HUD/Icons2D/Kayle_P.dds", "name": "Ascend", "variables": [ { "name": "WaveDamage", "value": [ 0, 125, 200, 600, 0, 0, 0 ] } ] }, "apiName": "TFT3_Kayle", "cost": 4, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Kayle.TFT_Set3.dds", "name": "Kayle", "stats": { "armor": 25, "attackSpeed": 0.800000011920929, "critChance": 0.25, "critMultiplier": 1.5, "damage": 60, "hp": 700, "initialMana": 0, "magicResist": 20, "mana": 60, "range": 3 }, "traits": [ "Valkyrie", "Blademaster" ] }, "TFT3_Ekko": { "ability": { "desc": "Ekko shatters the timeline, freezing all units in time before attacking each enemy with @ModifiedDamage@ bonus magic damage and applying on-hit effects.<br><br>Ekko cannot die while he has stopped time.", "icon": "ASSETS/Characters/Ekko/HUD/Icons2D/Ekko_R.dds", "name": "Chronobreak", "variables": [ { "name": "BonusDamage", "value": [ 200, 225, 400, 2000, 1200, 1000, 1000 ] }, { "name": "BaseDelayBetweenAttacks", "value": [ 0.4000000059604645, 0.4000000059604645, 0.4000000059604645, 0.4000000059604645, 0.4000000059604645, 0.4000000059604645, 0.4000000059604645 ] } ] }, "apiName": "TFT3_Ekko", "cost": 5, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Ekko.TFT_Set3.dds", "name": "Ekko", "stats": { "armor": 30, "attackSpeed": 0.8999999761581421, "critChance": 0.25, "critMultiplier": 1.5, "damage": 60, "hp": 850, "initialMana": 50, "magicResist": 20, "mana": 150, "range": 1 }, "traits": [ "Cybernetic", "Infiltrator" ] }, "TFT3_Fiora": { "ability": { "desc": "Fiora enters a defensive stance for @BlockDuration@ seconds, becoming immune to damage and enemy spell effects. As she exits this stance, she ripostes, dealing @ModifiedDamage@ magic damage to a nearby enemy and stunning them for @StunDuration@ seconds.", "icon": "ASSETS/Characters/Fiora/HUD/Icons2D/Fiora_W.dds", "name": "Riposte", "variables": [ { "name": "Damage", "value": [ 0, 200, 300, 450, 600, 750, 900 ] }, { "name": "StunDuration", "value": [ 1.5, 1.5, 1.5, 3, 1.5, 1.5, 1.5 ] }, { "name": "BlockDuration", "value": [ 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5 ] } ] }, "apiName": "TFT3_Fiora", "cost": 1, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Fiora.TFT_Set3.dds", "name": "Fiora", "stats": { "armor": 30, "attackSpeed": 1, "critChance": 0.25, "critMultiplier": 1.5, "damage": 45, "hp": 450, "initialMana": 0, "magicResist": 20, "mana": 85, "range": 1 }, "traits": [ "Cybernetic", "Blademaster" ] }, "TFT3_Vi": { "ability": { "desc": "Vi charges at the farthest enemy, knocking aside all enemies in her path and dealing them @ModifiedSecondaryDamage@ magic damage. When she reaches her target, she knocks them up for @CCDuration@ seconds and deals @ModifiedPrimaryDamage@ magic damage.", "icon": "ASSETS/Characters/Vi/HUD/Icons2D/ViR.dds", "name": "Assault and Battery", "variables": [ { "name": "PrimaryDamage", "value": [ 100, 400, 600, 1200, 900, 1100, 1300 ] }, { "name": "CCDuration", "value": [ 1.5, 2, 2.5, 3, 3.5, 4, 4.5 ] }, { "name": "MoveSpeed", "value": [ 1000, 1000, 1000, 1000, 1000, 1000, 1000 ] }, { "name": "OthersCCDuration", "value": [ 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25 ] }, { "name": "SecondaryDamage", "value": [ 0, 150, 200, 500, 0, 0, 0 ] } ] }, "apiName": "TFT3_Vi", "cost": 3, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Vi.TFT_Set3.dds", "name": "Vi", "stats": { "armor": 35, "attackSpeed": 0.6499999761581421, "critChance": 0.25, "critMultiplier": 1.5, "damage": 60, "hp": 750, "initialMana": 70, "magicResist": 20, "mana": 140, "range": 1 }, "traits": [ "Cybernetic", "Brawler" ] }, "TFT3_Irelia": { "ability": { "desc": "Irelia dashes to her target, Basic Attacking them for @ModifiedPercentAD@ of her Attack Damage. If this kills the target, she Bladesurges again immediately at the enemy with the highest mana. (Total Damage: @TooltipDamage@)", "icon": "ASSETS/Characters/Irelia/HUD/Icons2D/Irelia_Q.dds", "name": "Bladesurge", "variables": [ { "name": "PercentADDamage", "value": [ 0, 1.75, 2.5, 5, 0, 0, 0 ] } ] }, "apiName": "TFT3_Irelia", "cost": 4, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Irelia.TFT_Set3.dds", "name": "Irelia", "stats": { "armor": 35, "attackSpeed": 0.8500000238418579, "critChance": 0.25, "critMultiplier": 1.5, "damage": 70, "hp": 800, "initialMana": 0, "magicResist": 20, "mana": 30, "range": 1 }, "traits": [ "Cybernetic", "Mana-Reaver", "Blademaster" ] }, "TFT3_Poppy": { "ability": { "desc": "Poppy throws her buckler at the furthest enemy, dealing @ModifiedDamage@ magic damage. The buckler then bounces back, granting Poppy a shield that blocks @ModifiedShield@ damage.", "icon": "ASSETS/Characters/Poppy/HUD/Icons2D/Poppy_Passive.dds", "name": "<NAME>", "variables": [ { "name": "Damage", "value": [ 50, 100, 150, 200, 250, 300, 350 ] }, { "name": "ShieldAmount", "value": [ 100, 200, 300, 400, 500, 600, 700 ] } ] }, "apiName": "TFT3_Poppy", "cost": 1, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Poppy.TFT_Set3.dds", "name": "Poppy", "stats": { "armor": 40, "attackSpeed": 0.550000011920929, "critChance": 0.25, "critMultiplier": 1.5, "damage": 50, "hp": 650, "initialMana": 60, "magicResist": 20, "mana": 100, "range": 1 }, "traits": [ "Star Guardian", "Vanguard" ] }, "TFT3_Soraka": { "ability": { "desc": "Soraka heals all of her allies for @ModifiedHeal@.", "icon": "ASSETS/Characters/Soraka/HUD/Icons2D/Soraka_R.dds", "name": "Wish", "variables": [ { "name": "HealAmount", "value": [ 300, 375, 550, 20000, 1500, 1500, 1500 ] }, { "name": "HealTargets", "value": [ 15, 15, 15, 15, 15, 15, 15 ] } ] }, "apiName": "TFT3_Soraka", "cost": 4, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Soraka.TFT_Set3.dds", "name": "Soraka", "stats": { "armor": 30, "attackSpeed": 0.75, "critChance": 0.25, "critMultiplier": 1.5, "damage": 45, "hp": 700, "initialMana": 50, "magicResist": 20, "mana": 125, "range": 3 }, "traits": [ "Star Guardian", "Mystic" ] }, "TFT3_Ahri": { "ability": { "desc": "Ahri fires an orb in a line, dealing @ModifiedDamage@ magic damage to all enemies it passes through on the way out, and @ModifiedDamage@ true damage on the way back.", "icon": "ASSETS/Characters/Ahri/HUD/Icons2D/Ahri_OrbofDeception.dds", "name": "Orb of Deception", "variables": [ { "name": "Damage", "value": [ 150, 175, 250, 375, 500, 400, 400 ] }, { "name": "HexRange", "value": [ 4, 4, 4, 4, 4, 4, 4 ] } ] }, "apiName": "TFT3_Ahri", "cost": 2, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Ahri.TFT_Set3.dds", "name": "Ahri", "stats": { "armor": 20, "attackSpeed": 0.75, "critChance": 0.25, "critMultiplier": 1.5, "damage": 45, "hp": 600, "initialMana": 0, "magicResist": 20, "mana": 60, "range": 3 }, "traits": [ "Star Guardian", "Sorcerer" ] }, "TFT3_Syndra": { "ability": { "desc": "Syndra pulls in all orbs on the battlefield and creates @Spheres@ new ones, then fires them all at the enemy with the highest current Health percentage, dealing @ModifiedDamage@ magic damage per orb.<br><br><tftitemrules>Lowest total health breaks targeting ties.</tftitemrules>", "icon": "ASSETS/Characters/Syndra/HUD/Icons2D/SyndraR.dds", "name": "Unleashed Power", "variables": [ { "name": "Spheres", "value": [ 3, 3, 3, 3, 3, 3, 3 ] }, { "name": "CastTime", "value": [ 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75 ] }, { "name": "Damage", "value": [ 0, 100, 150, 250, 200, 250, 300 ] } ] }, "apiName": "TFT3_Syndra", "cost": 3, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Syndra.TFT_Set3.dds", "name": "Syndra", "stats": { "armor": 20, "attackSpeed": 0.699999988079071, "critChance": 0.25, "critMultiplier": 1.5, "damage": 45, "hp": 600, "initialMana": 0, "magicResist": 20, "mana": 65, "range": 4 }, "traits": [ "Star Guardian", "Sorcerer" ] }, "TFT3_Neeko": { "ability": { "desc": "Neeko leaps into the air and slams into the ground, dealing @ModifiedDamage@ magic damage to all nearby enemies and stunning them for @StunDuration@ seconds.", "icon": "ASSETS/Characters/Neeko/HUD/Icons2D/Neeko_R.dds", "name": "<NAME>", "variables": [ { "name": "DamageAmount", "value": [ 0, 200, 275, 550, 300, 375, 450 ] }, { "name": "StunDuration", "value": [ 1, 1.5, 2, 2.5, 3, 3.5, 4 ] }, { "name": "HexRadius", "value": [ 2, 2, 2, 2, 2, 2, 2 ] } ] }, "apiName": "TFT3_Neeko", "cost": 3, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Neeko.TFT_Set3.dds", "name": "Neeko", "stats": { "armor": 35, "attackSpeed": 0.6499999761581421, "critChance": 0.25, "critMultiplier": 1.5, "damage": 50, "hp": 800, "initialMana": 75, "magicResist": 20, "mana": 150, "range": 2 }, "traits": [ "Star Guardian", "Protector" ] }, "TFT3_Gangplank": { "ability": { "desc": "Gangplank calls down an orbital strike around his target, dealing @ModifiedDamage@ damage to all enemies in a large area after @ImpactDelayTime@ seconds.", "icon": "ASSETS/Characters/Gangplank/HUD/Icons2D/Gangplank_R.dds", "name": "Orbital Strike", "variables": [ { "name": "Damage", "value": [ 0, 450, 600, 9001, 0, 0, 0 ] }, { "name": "ImpactDelayTime", "value": [ 2, 2, 2, 2, 2, 2, 2 ] }, { "name": "UpgradeDelayTime", "value": [ 0, 0.30000001192092896, 0.30000001192092896, 0.30000001192092896, 0.30000001192092896, 0.30000001192092896, 0.30000001192092896 ] }, { "name": "DoubleImpactDamagePercent", "value": [ 0, 50, 50, 50, 50, 50, 50 ] } ] }, "apiName": "TFT3_Gangplank", "cost": 5, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Gangplank.TFT_Set3.dds", "name": "Gangplank", "stats": { "armor": 30, "attackSpeed": 1, "critChance": 0.25, "critMultiplier": 1.5, "damage": 60, "hp": 1000, "initialMana": 100, "magicResist": 20, "mana": 175, "range": 1 }, "traits": [ "Space Pirate", "Mercenary", "Demolitionist" ] }, "TFT3_Darius": { "ability": { "desc": "Darius dunks an enemy, dealing @ModifiedDamage@ magic damage. If this kills the target, Darius immediately casts again.<br><br>Targets below @HealthThreshold@% health take double damage.", "icon": "ASSETS/Characters/TFT3_Darius/HUD/Icons2D/Darius_Icon_Sudden_Death.TFT_Set3.dds", "name": "<NAME>", "variables": [ { "name": "Damage", "value": [ 50, 400, 500, 750, 1100, 1300, 1550 ] }, { "name": "HealthThreshold", "value": [ 50, 50, 50, 50, 50, 50, 50 ] }, { "name": "DamageMultiplier", "value": [ 2, 2, 2, 2, 2, 2, 2 ] } ] }, "apiName": "TFT3_Darius", "cost": 2, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Darius.TFT_Set3.dds", "name": "Darius", "stats": { "armor": 35, "attackSpeed": 0.6499999761581421, "critChance": 0.25, "critMultiplier": 1.5, "damage": 60, "hp": 750, "initialMana": 0, "magicResist": 20, "mana": 60, "range": 1 }, "traits": [ "Space Pirate", "Mana-Reaver" ] }, "TFT3_Jayce": { "ability": { "desc": "Jayce slams his hammer, dealing @ModifiedDamage@ magic damage to nearby enemies.", "icon": "ASSETS/Characters/TFT3_Jayce/HUD/Icons2D/Jayce_Q1.dds", "name": "To the Skies!", "variables": [ { "name": "Damage", "value": [ 300, 450, 600, 1200, 1200, 1200, 1200 ] }, { "name": "Radius", "value": [ 1, 1, 1, 1, 1, 1, 1 ] } ] }, "apiName": "TFT3_Jayce", "cost": 3, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Jayce.TFT_Set3.dds", "name": "Jayce", "stats": { "armor": 40, "attackSpeed": 0.699999988079071, "critChance": 0.25, "critMultiplier": 1.5, "damage": 60, "hp": 750, "initialMana": 0, "magicResist": 20, "mana": 80, "range": 1 }, "traits": [ "Space Pirate", "Vanguard" ] }, "TFT3_Annie": { "ability": { "desc": "Annie blasts a cone of fire dealing @ModifiedDamage@ magic damage to enemies in front of her, then creates a shield with @ModifiedShield@ health for herself for @ShieldDuration@ seconds.", "icon": "ASSETS/Characters/Annie/HUD/Icons2D/Annie_E.dds", "name": "<NAME>", "variables": [ { "name": "Damage", "value": [ 100, 150, 200, 300, 450, 450, 450 ] }, { "name": "ShieldAmount", "value": [ 200, 270, 360, 540, 700, 450, 450 ] }, { "name": "ShieldDuration", "value": [ 4, 4, 4, 4, 4, 4, 4 ] } ] }, "apiName": "TFT3_Annie", "cost": 2, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Annie.TFT_Set3.dds", "name": "Annie", "stats": { "armor": 40, "attackSpeed": 0.6499999761581421, "critChance": 0.25, "critMultiplier": 1.5, "damage": 40, "hp": 700, "initialMana": 75, "magicResist": 20, "mana": 150, "range": 2 }, "traits": [ "Mech-Pilot", "Sorcerer" ] }, "TFT3_Fizz": { "ability": { "desc": "Fizz throws a lure that attracts a shark. It deals @ModifiedDamage@ magic damage to enemies caught, knocking them back and stunning them for @StunDuration@ seconds.", "icon": "ASSETS/Characters/Fizz/HUD/Icons2D/Fizz_R.dds", "name": "Chum the Waters", "variables": [ { "name": "Delay", "value": [ 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5 ] }, { "name": "Damage", "value": [ 0, 350, 500, 2000, 2000, 2000, 2000 ] }, { "name": "StunDuration", "value": [ 1, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5 ] } ] }, "apiName": "TFT3_Fizz", "cost": 4, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Fizz.TFT_Set3.dds", "name": "Fizz", "stats": { "armor": 25, "attackSpeed": 0.800000011920929, "critChance": 0.25, "critMultiplier": 1.5, "damage": 60, "hp": 600, "initialMana": 80, "magicResist": 20, "mana": 150, "range": 1 }, "traits": [ "Mech-Pilot", "Infiltrator" ] }, "TFT3_Rumble": { "ability": { "desc": "Rumble torches his enemies, dealing @ModifiedDamage@ magic damage over @Duration@ seconds, and reducing healing on them by @GrievousWoundsPercent@% for @GrievousWoundsDuration@ seconds.", "icon": "ASSETS/Characters/Rumble/HUD/Icons2D/Rumble_Flamespitter.dds", "name": "Flamespitter", "variables": [ { "name": "TotalDamage", "value": [ 30, 350, 500, 1000, 800, 680, 810 ] }, { "name": "Duration", "value": [ 3, 3, 3, 3, 3, 3, 3 ] }, { "name": "NumberOfTicks", "value": [ 12, 12, 12, 12, 12, 12, 12 ] }, { "name": "TickRate", "value": [ 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25 ] }, { "name": "GrievousWoundsDuration", "value": [ 5, 5, 5, 5, 5, 5, 5 ] }, { "name": "ConeHexRange", "value": [ 2, 2, 2, 2, 2, 2, 2 ] }, { "name": "GrievousWoundsPercent", "value": [ 0, 50, 50, 50, 50, 50, 50 ] } ] }, "apiName": "TFT3_Rumble", "cost": 3, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Rumble.TFT_Set3.dds", "name": "Rumble", "stats": { "armor": 35, "attackSpeed": 0.699999988079071, "critChance": 0.25, "critMultiplier": 1.5, "damage": 50, "hp": 800, "initialMana": 0, "magicResist": 20, "mana": 60, "range": 1 }, "traits": [ "Mech-Pilot", "Demolitionist" ] }, "TFT3_ChoGath": { "ability": { "desc": "Cho'Gath ruptures a large area, dealing @ModifiedDamage@ magic damage and knocking up all enemies within for @KnockDuration@ seconds.", "icon": "ASSETS/Characters/Chogath/HUD/Icons2D/GreenTerror_SpikeSlam.dds", "name": "Rupture", "variables": [ { "name": "Damage", "value": [ 0, 150, 250, 2000, 800, 800, 800 ] }, { "name": "KnockDuration", "value": [ 2, 2, 2, 4, 4, 4, 4 ] }, { "name": "RuptureDelay", "value": [ 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5 ] } ] }, "apiName": "TFT3_ChoGath", "cost": 4, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_ChoGath.TFT_Set3.dds", "name": "Cho'Gath", "stats": { "armor": 20, "attackSpeed": 0.6000000238418579, "critChance": 0.25, "critMultiplier": 1.5, "damage": 70, "hp": 1000, "initialMana": 50, "magicResist": 20, "mana": 150, "range": 1 }, "traits": [ "Void", "Brawler" ] }, "TFT3_KhaZix": { "ability": { "desc": "Kha'Zix slashes the nearest enemy, dealing @ModifiedDamage@ magic damage. If the enemy has no adjacent allies, this damage is increased to @ModifiedIsolationDamage@.", "icon": "ASSETS/Characters/KhaZix/HUD/Icons2D/Khazix_Q.dds", "name": "Taste their Fear", "variables": [ { "name": "Damage", "value": [ 50, 200, 275, 500, 450, 550, 650 ] }, { "name": "IsolationDamage", "value": [ 200, 600, 825, 1500, 1000, 1200, 1400 ] } ] }, "apiName": "TFT3_KhaZix", "cost": 1, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_KhaZix.TFT_Set3.dds", "name": "Kha'Zix", "stats": { "armor": 25, "attackSpeed": 0.699999988079071, "critChance": 0.25, "critMultiplier": 1.5, "damage": 50, "hp": 500, "initialMana": 0, "magicResist": 20, "mana": 65, "range": 1 }, "traits": [ "Void", "Infiltrator" ] }, "TFT3_VelKoz": { "ability": { "desc": "Vel'Koz channels a ray of energy that sweeps across the battlefield over @ChannelDuration@ seconds, dealing @ModifiedDamage@ magic damage per second to enemies hit.", "icon": "ASSETS/Characters/Velkoz/HUD/Icons2D/Velkoz_R.dds", "name": "Lifeform Disintegration Ray", "variables": [ { "name": "BaseDamagePerSec", "value": [ 0, 450, 600, 2000, 0, 0, 0 ] }, { "name": "PercentHealthDamagePerSec", "value": null }, { "name": "SweepAngle", "value": [ 60, 60, 60, 60, 60, 60, 60 ] }, { "name": "TickInterval", "value": [ 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25 ] }, { "name": "ChannelDuration", "value": [ 2, 2, 2, 2, 2, 2, 2 ] }, { "name": "BeamDistance", "value": [ 1400, 1400, 1400, 1400, 1400, 1400, 1400 ] }, { "name": "BeamWidth", "value": [ 200, 200, 200, 200, 200, 200, 200 ] } ] }, "apiName": "TFT3_VelKoz", "cost": 4, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_VelKoz.TFT_Set3.dds", "name": "Vel'Koz", "stats": { "armor": 20, "attackSpeed": 0.75, "critChance": 0.25, "critMultiplier": 1.5, "damage": 45, "hp": 650, "initialMana": 0, "magicResist": 20, "mana": 70, "range": 4 }, "traits": [ "Void", "Sorcerer" ] }, "TFT3_Ezreal": { "ability": { "desc": "Ezreal fires an electromagnetic pulse at a random enemy that explodes on impact, dealing @ModifiedDamage@ damage to all nearby enemies and increasing the cost of their next spellcast by @PercentCostIncrease@%.", "icon": "ASSETS/Characters/Ezreal/HUD/Icons2D/Ezreal_W.dds", "name": "E.M.P.", "variables": [ { "name": "Damage", "value": [ 0, 200, 300, 600, 800, 1000, 1200 ] }, { "name": "HexRadius", "value": [ 2, 2, 2, 2, 2, 2, 2 ] }, { "name": "PercentCostIncrease", "value": [ 3, 40, 40, 40, 40, 40, 40 ] } ] }, "apiName": "TFT3_Ezreal", "cost": 3, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Ezreal.TFT_Set3.dds", "name": "Ezreal", "stats": { "armor": 20, "attackSpeed": 0.699999988079071, "critChance": 0.25, "critMultiplier": 1.5, "damage": 60, "hp": 600, "initialMana": 50, "magicResist": 20, "mana": 125, "range": 3 }, "traits": [ "Chrono", "Blaster" ] }, "TFT3_Shen": { "ability": { "desc": "Shen creates a zone around himself for @ZoneDuration@ seconds, in which all nearby allies automatically dodge incoming Basic Attacks. While it's active, Shen gains @ModifiedMR@ Magic Resist.", "icon": "ASSETS/Characters/Shen/HUD/Icons2D/Shen_W.dds", "name": "Future's Refuge", "variables": [ { "name": "ZoneDuration", "value": [ 2, 2.5, 3, 5, 6, 7, 8 ] }, { "name": "MagicResist", "value": [ 0, 15, 30, 45, 60, 75, 90 ] } ] }, "apiName": "TFT3_Shen", "cost": 2, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Shen.TFT_Set3.dds", "name": "Shen", "stats": { "armor": 35, "attackSpeed": 0.699999988079071, "critChance": 0.25, "critMultiplier": 1.5, "damage": 60, "hp": 800, "initialMana": 100, "magicResist": 20, "mana": 150, "range": 1 }, "traits": [ "Chrono", "Blademaster" ] }, "TFT3_WuKong": { "ability": { "desc": "Wukong spins, dealing @ModifiedDamage@ magic damage to nearby enemies over @Duration@ seconds. The first time Wukong hits each enemy, he knocks them into the air and stuns them for @StunDuration@ seconds.", "icon": "ASSETS/Characters/MonkeyKing/HUD/Icons2D/MonkeyKingCyclone.dds", "name": "Cyclone", "variables": [ { "name": "Damage", "value": [ 200, 300, 500, 4000, 5000, 5000, 5000 ] }, { "name": "Duration", "value": [ 3, 3, 3, 3, 3, 3, 3 ] }, { "name": "StunDuration", "value": [ 1.5, 2, 2, 5, 5, 5, 5 ] }, { "name": "HexRadius", "value": [ 1, 1, 1, 1, 1, 1, 1 ] } ] }, "apiName": "TFT3_WuKong", "cost": 4, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_WuKong.TFT_Set3.dds", "name": "Wukong", "stats": { "armor": 40, "attackSpeed": 0.75, "critChance": 0.25, "critMultiplier": 1.5, "damage": 50, "hp": 950, "initialMana": 50, "magicResist": 20, "mana": 150, "range": 1 }, "traits": [ "Chrono", "Vanguard" ] }, "TFT3_Thresh": { "ability": { "desc": "Thresh tosses his lantern towards @UnitCount@ random unit(s) on your bench, pulling them into combat and granting them @ModifiedMana@ bonus Mana. Traits are unaffected.", "icon": "ASSETS/Characters/Thresh/HUD/Icons2D/Thresh_W.dds", "name": "Temporal Passage", "variables": [ { "name": "UnitCount", "value": [ 1, 1, 1, 9, 9, 9, 9 ] }, { "name": "ManaBonus", "value": [ 10, 25, 50, 200, 200, 200, 200 ] } ] }, "apiName": "TFT3_Thresh", "cost": 5, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Thresh.TFT_Set3.dds", "name": "Thresh", "stats": { "armor": 35, "attackSpeed": 0.949999988079071, "critChance": 0.25, "critMultiplier": 1.5, "damage": 50, "hp": 950, "initialMana": 50, "magicResist": 20, "mana": 75, "range": 2 }, "traits": [ "Chrono", "Mana-Reaver" ] }, "TFT3_Caitlyn": { "ability": { "desc": "Caitlyn takes aim at the farthest enemy, firing a deadly bullet towards them that deals @ModifiedDamage@ magic damage to the first enemy it hits.", "icon": "ASSETS/Characters/TFT3_Caitlyn/HUD/Icons2D/Caitlyn_AceintheHole.dds", "name": "Ace In The Hole", "variables": [ { "name": "Damage", "value": [ 0, 750, 1500, 3000, 2400, 3000, 3600 ] } ] }, "apiName": "TFT3_Caitlyn", "cost": 1, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Caitlyn.TFT_Set3.dds", "name": "Caitlyn", "stats": { "armor": 20, "attackSpeed": 0.75, "critChance": 0.25, "critMultiplier": 1.5, "damage": 45, "hp": 500, "initialMana": 0, "magicResist": 20, "mana": 125, "range": 6 }, "traits": [ "Chrono", "Sniper" ] }, "TFT3_TwistedFate": { "ability": { "desc": "Twisted Fate throws three cards in a cone that deal @ModifiedDamage@ magic damage to each enemy they pass through.", "icon": "ASSETS/Characters/TwistedFate/HUD/Icons2D/Cardmaster_PowerCard.dds", "name": "Wild Cards", "variables": [ { "name": "BaseDamage", "value": [ 0, 200, 300, 450, 450, 750, 900 ] } ] }, "apiName": "TFT3_TwistedFate", "cost": 1, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_TwistedFate.TFT_Set3.dds", "name": "Twisted Fate", "stats": { "armor": 20, "attackSpeed": 0.699999988079071, "critChance": 0.25, "critMultiplier": 1.5, "damage": 45, "hp": 550, "initialMana": 0, "magicResist": 20, "mana": 75, "range": 3 }, "traits": [ "Chrono", "Sorcerer" ] }, "TFT3_XinZhao": { "ability": { "desc": "<NAME> quickly strikes his target three times, dealing Basic Attack damage and applying on-hit effects. The third strike knocks his target up for @StunDuration@ seconds and deals @ModifiedDamage@ bonus magic damage.", "icon": "ASSETS/Characters/XinZhao/HUD/Icons2D/XinZhaoQ.dds", "name": "Three Talon Strike", "variables": [ { "name": "StunDuration", "value": [ 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5 ] }, { "name": "BonusDamage", "value": [ 4, 200, 275, 375, 8, 8, 8 ] } ] }, "apiName": "TFT3_XinZhao", "cost": 2, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_XinZhao.TFT_Set3.dds", "name": "<NAME>", "stats": { "armor": 35, "attackSpeed": 0.699999988079071, "critChance": 0.25, "critMultiplier": 1.5, "damage": 60, "hp": 650, "initialMana": 0, "magicResist": 20, "mana": 60, "range": 1 }, "traits": [ "Celestial", "Protector" ] }, "TFT3_Lulu": { "ability": { "desc": "Lulu polymorphs the @NumTargets@ nearest enemies for @Duration@ seconds, causing them to hop aimlessly, unable to attack or cast. Polymorphed enemies take @ModifiedBonusDamage@ additional damage from all sources.", "icon": "ASSETS/Characters/Lulu/HUD/Icons2D/Lulu_Whimsy.dds", "name": "Mass Polymorph", "variables": [ { "name": "NumTargets", "value": [ 0, 2, 4, 12, 0, 0, 0 ] }, { "name": "Duration", "value": [ 0, 3, 3, 8, 4, 4, 4 ] }, { "name": "BonusDamage", "value": [ 0.02500000037252903, 0.05000000074505806, 0.10000000149011612, 0.25, 0.4000000059604645, 0.800000011920929, 1.600000023841858 ] } ] }, "apiName": "TFT3_Lulu", "cost": 5, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Lulu.TFT_Set3.dds", "name": "Lulu", "stats": { "armor": 25, "attackSpeed": 0.800000011920929, "critChance": 0.25, "critMultiplier": 1.5, "damage": 45, "hp": 800, "initialMana": 75, "magicResist": 20, "mana": 150, "range": 3 }, "traits": [ "Celestial", "Mystic" ] }, "TFT3_Kassadin": { "ability": { "desc": "Kassadin releases a wave of energy in front of him, dealing @ModifiedDamage@ magic damage and disarming all targets hit for @Duration@ seconds.", "icon": "ASSETS/Characters/Kassadin/HUD/Icons2D/Kassadin_E.dds", "name": "<NAME>", "variables": [ { "name": "Damage", "value": [ 100, 250, 400, 800, 300, 300, 300 ] }, { "name": "Duration", "value": [ 3, 2.5, 3, 3.5, 3, 3, 3 ] } ] }, "apiName": "TFT3_Kassadin", "cost": 3, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Kassadin.TFT_Set3.dds", "name": "Kassadin", "stats": { "armor": 30, "attackSpeed": 0.6499999761581421, "critChance": 0.25, "critMultiplier": 1.5, "damage": 50, "hp": 800, "initialMana": 40, "magicResist": 20, "mana": 80, "range": 1 }, "traits": [ "Celestial", "Mana-Reaver" ] }, "TFT3_Xayah": { "ability": { "desc": "Xayah creates a storm of feather-blades, gaining @ModifiedAS@ Attack Speed for @Duration@ seconds.", "icon": "ASSETS/Characters/Xayah/HUD/Icons2D/XayahW.dds", "name": "Deadly Plumage", "variables": [ { "name": "Duration", "value": [ 8, 8, 8, 8, 8, 8, 8 ] }, { "name": "AttackSpeed", "value": [ 0.75, 1, 1.25, 1.5, 1.75, 2, 2.25 ] }, { "name": "DamageReduction", "value": [ 50, 50, 50, 50, 50, 50, 50 ] } ] }, "apiName": "TFT3_Xayah", "cost": 1, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Xayah.TFT_Set3.dds", "name": "Xayah", "stats": { "armor": 20, "attackSpeed": 0.800000011920929, "critChance": 0.25, "critMultiplier": 1.5, "damage": 50, "hp": 500, "initialMana": 0, "magicResist": 20, "mana": 50, "range": 3 }, "traits": [ "Celestial", "Blademaster" ] }, "TFT3_Rakan": { "ability": { "desc": "Rakan dashes to the furthest enemy within range and leaps into the air, knocking them up for @StunDuration@ seconds and dealing @ModifiedDamage@ magic damage.", "icon": "ASSETS/Characters/Rakan/HUD/Icons2D/Rakan_W.dds", "name": "<NAME>", "variables": [ { "name": "Damage", "value": [ 75, 175, 275, 400, 475, 575, 675 ] }, { "name": "Radius", "value": [ 1, 1, 1, 1, 1, 1, 1 ] }, { "name": "StunDuration", "value": [ 0, 1.5, 2, 2.5, 3, 3, 3 ] }, { "name": "KnockupDuration", "value": [ 1, 1, 1, 1, 1, 1, 1 ] } ] }, "apiName": "TFT3_Rakan", "cost": 2, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Rakan.TFT_Set3.dds", "name": "Rakan", "stats": { "armor": 35, "attackSpeed": 0.699999988079071, "critChance": 0.25, "critMultiplier": 1.5, "damage": 45, "hp": 600, "initialMana": 50, "magicResist": 20, "mana": 100, "range": 2 }, "traits": [ "Celestial", "Protector" ] }, "TFT3_Ashe": { "ability": { "desc": "Ashe fires an arrow at the farthest enemy that explodes on the first target hit, dealing @ModifiedDamage@ magic damage to all nearby enemies and stunning them for @StunDurationPerSquare@ seconds.", "icon": "ASSETS/Characters/Ashe/HUD/Icons2D/Ashe_R.dds", "name": "Enchanted Crystal Arrow", "variables": [ { "name": "Damage", "value": [ 250, 250, 350, 700, 800, 800, 800 ] }, { "name": "StunDurationPerSquare", "value": [ 2, 2, 2, 2, 2, 2, 2 ] } ] }, "apiName": "TFT3_Ashe", "cost": 3, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Ashe.TFT_Set3.dds", "name": "Ashe", "stats": { "armor": 20, "attackSpeed": 0.800000011920929, "critChance": 0.25, "critMultiplier": 1.5, "damage": 60, "hp": 600, "initialMana": 50, "magicResist": 20, "mana": 125, "range": 6 }, "traits": [ "Celestial", "Sniper" ] }, "TFT3_Mordekaiser": { "ability": { "desc": "Mordekaiser gains a shield for that absorbs @ModifiedShield@ damage over @Duration@ seconds. While the shield persists, Mordekaiser deals @ModifiedDamage@ magic damage per second to all nearby enemies.", "icon": "ASSETS/Characters/Mordekaiser/HUD/Icons2D/MordekaiserW.dds", "name": "Indestructible", "variables": [ { "name": "DamagePerSecond", "value": [ 20, 50, 75, 125, 180, 220, 260 ] }, { "name": "ShieldAmount", "value": [ 0, 350, 500, 800, 1000, 1250, 1500 ] }, { "name": "Duration", "value": [ 8, 8, 8, 8, 8, 8, 8 ] } ] }, "apiName": "TFT3_Mordekaiser", "cost": 2, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Mordekaiser.TFT_Set3.dds", "name": "Mordekaiser", "stats": { "armor": 40, "attackSpeed": 0.6000000238418579, "critChance": 0.25, "critMultiplier": 1.5, "damage": 55, "hp": 650, "initialMana": 0, "magicResist": 20, "mana": 90, "range": 1 }, "traits": [ "Dark Star", "Vanguard" ] }, "TFT3_Lux": { "ability": { "desc": "Lux fires a sphere of darkness towards the farthest enemy. Enemies in its path take @ModifiedDamage@ magic damage and are stunned for @StunDuration@ seconds.", "icon": "ASSETS/Characters/Lux/HUD/Icons2D/LuxLightStrikeKugel.dds", "name": "<NAME>", "variables": [ { "name": "Damage", "value": [ 300, 200, 300, 600, 800, 800, 800 ] }, { "name": "StunDuration", "value": [ 1, 1.5, 2, 2.5, 3, 3.5, 4 ] } ] }, "apiName": "TFT3_Lux", "cost": 3, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Lux.TFT_Set3.dds", "name": "Lux", "stats": { "armor": 20, "attackSpeed": 0.699999988079071, "critChance": 0.25, "critMultiplier": 1.5, "damage": 40, "hp": 600, "initialMana": 50, "magicResist": 20, "mana": 100, "range": 4 }, "traits": [ "Dark Star", "Sorcerer" ] }, "TFT3_Shaco": { "ability": { "desc": "Shaco teleports and backstabs his target for @TooltipPercentage@ of his Basic Attack damage. This is also always a critical hit. (Total: @TooltipADBonus@)", "icon": "ASSETS/Characters/Shaco/HUD/Icons2D/Jester_ManiacalCloak2.dds", "name": "Deceive", "variables": [ { "name": "Duration", "value": [ 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5 ] }, { "name": "PercentOfAD", "value": [ 1.75, 2, 2.25, 2.5, 2.75, 3, 3.25 ] } ] }, "apiName": "TFT3_Shaco", "cost": 3, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Shaco.TFT_Set3.dds", "name": "Shaco", "stats": { "armor": 25, "attackSpeed": 0.800000011920929, "critChance": 0.25, "critMultiplier": 1.5, "damage": 70, "hp": 650, "initialMana": 30, "magicResist": 20, "mana": 80, "range": 1 }, "traits": [ "Dark Star", "Infiltrator" ] }, "TFT3_JarvanIV": { "ability": { "desc": "Jarvan calls down his standard to a nearby location, granting all nearby allies @ModifiedAS@ Attack Speed for @Duration@ seconds.", "icon": "ASSETS/Characters/JarvanIV/HUD/Icons2D/JarvanIV_DemacianStandard.dds", "name": "Ageless Standard", "variables": [ { "name": "Duration", "value": [ 6, 6, 6, 6, 6, 6, 6 ] }, { "name": "HexRadius", "value": [ 3, 3, 3, 3, 3, 3, 3 ] }, { "name": "ASPercent", "value": [ 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75 ] } ] }, "apiName": "TFT3_JarvanIV", "cost": 1, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_JarvanIV.TFT_Set3.dds", "name": "<NAME>", "stats": { "armor": 40, "attackSpeed": 0.6000000238418579, "critChance": 0.25, "critMultiplier": 1.5, "damage": 50, "hp": 650, "initialMana": 50, "magicResist": 20, "mana": 100, "range": 1 }, "traits": [ "Dark Star", "Protector" ] }, "TFT3_Karma": { "ability": { "desc": "At start of combat, Karma bonds to her closest ally.<br><br>Karma grants the bonded ally (or a random one if that ally is dead) a @ModifiedShield@-health shield for @Duration@ seconds. While the shield holds, the ally receives @ModifiedAS@ bonus Attack Speed.", "icon": "ASSETS/Characters/Karma/HUD/Icons2D/Karma_E2.dds", "name": "Inspire", "variables": [ { "name": "Duration", "value": [ 4, 4, 4, 4, 4, 4, 4 ] }, { "name": "ShieldAmount", "value": [ 100, 250, 400, 800, 700, 850, 1000 ] }, { "name": "BonusAS", "value": [ 0.20000000298023224, 0.5, 0.75, 1.25, 1, 1.2000000476837158, 1.399999976158142 ] } ] }, "apiName": "TFT3_Karma", "cost": 3, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Karma.TFT_Set3.dds", "name": "Karma", "stats": { "armor": 20, "attackSpeed": 0.6499999761581421, "critChance": 0.25, "critMultiplier": 1.5, "damage": 50, "hp": 600, "initialMana": 75, "magicResist": 20, "mana": 100, "range": 3 }, "traits": [ "Dark Star", "Mystic" ] }, "TFT3_Jhin": { "ability": { "desc": "Passive: Jhin converts each 1% of bonus Attack Speed he has into 0.8 Attack Damage.<br><br>Passive: Every fourth shot, Jhin deals @ModifiedPercent@ damage. (Total: @TooltipDamage@)", "icon": "ASSETS/Characters/Jhin/HUD/Icons2D/Jhin_P.dds", "name": "Whisper", "variables": [ { "name": "PercentOfAD", "value": [ 0, 2.440000057220459, 3.440000057220459, 44.439998626708984, 0, 0, 0 ] } ] }, "apiName": "TFT3_Jhin", "cost": 4, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Jhin.TFT_Set3.dds", "name": "Jhin", "stats": { "armor": 20, "attackSpeed": 0.8999999761581421, "critChance": 0.25, "critMultiplier": 1.5, "damage": 90, "hp": 600, "initialMana": 0, "magicResist": 20, "mana": 4, "range": 6 }, "traits": [ "Dark Star", "Sniper" ] }, "TFT3_Zoe": { "ability": { "desc": "Zoe kicks a bubble at the enemy with the the highest current Health percentage, stunning them for @StunDuration@ seconds and dealing @ModifiedDamage@ magic damage.<br><br><tftitemrules>Highest total health breaks targeting ties.</tftitemrules>", "icon": "ASSETS/Characters/Zoe/HUD/Icons2D/Zoe_E.dds", "name": "Sleepy Trouble Bubble", "variables": [ { "name": "Damage", "value": [ 75, 200, 275, 400, 375, 450, 525 ] }, { "name": "StunDuration", "value": [ 1.5, 2, 2.5, 4, 3.5, 4, 4.5 ] } ] }, "apiName": "TFT3_Zoe", "cost": 1, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Zoe.TFT_Set3.dds", "name": "Zoe", "stats": { "armor": 20, "attackSpeed": 0.699999988079071, "critChance": 0.25, "critMultiplier": 1.5, "damage": 40, "hp": 500, "initialMana": 70, "magicResist": 20, "mana": 100, "range": 3 }, "traits": [ "Star Guardian", "Sorcerer" ] }, "TFT3_Blitzcrank": { "ability": { "desc": "Blitzcrank pulls the farthest enemy, dealing @ModifiedDamage@ magic damage and stunning them for @StunDuration@ seconds.<br><br>His next attack after pulling knocks up for 1 second.<br><br>Allies within range will prefer to attack Blitzcrank's target.", "icon": "ASSETS/Characters/Blitzcrank/HUD/Icons2D/Blitzcrank_RocketGrab.dds", "name": "<NAME>", "variables": [ { "name": "Damage", "value": [ -50, 250, 400, 900, 950, 1200, 1450 ] }, { "name": "StunDuration", "value": [ 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5 ] } ] }, "apiName": "TFT3_Blitzcrank", "cost": 2, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Blitzcrank.TFT_Set3.dds", "name": "Blitzcrank", "stats": { "armor": 35, "attackSpeed": 0.5, "critChance": 0.25, "critMultiplier": 1.5, "damage": 55, "hp": 650, "initialMana": 125, "magicResist": 20, "mana": 125, "range": 1 }, "traits": [ "Chrono", "Brawler" ] }, "TFT3_Leona": { "ability": { "desc": "Leona creates a barrier, reducing all incoming damage by @ModifiedDamageReduction@ for 4 seconds.<br><br>", "icon": "ASSETS/Characters/Leona/HUD/Icons2D/LeonaSolarBarrier.dds", "name": "<NAME>", "variables": [ { "name": "FlatDamageReduction", "value": [ 0, 40, 80, 200, 160, 200, 240 ] }, { "name": "Duration", "value": [ 4, 4, 4, 4, 4, 4, 4 ] } ] }, "apiName": "TFT3_Leona", "cost": 1, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Leona.TFT_Set3.dds", "name": "Leona", "stats": { "armor": 40, "attackSpeed": 0.550000011920929, "critChance": 0.25, "critMultiplier": 1.5, "damage": 50, "hp": 600, "initialMana": 50, "magicResist": 20, "mana": 100, "range": 1 }, "traits": [ "Cybernetic", "Vanguard" ] }, "TFT3_Lucian": { "ability": { "desc": "Lucian dashes away from his current target, then Basic Attacks them and fires a second shot which deals @ModifiedDamage@ magic damage.", "icon": "ASSETS/Characters/Lucian/HUD/Icons2D/Lucian_E.dds", "name": "Relentless Pursuit", "variables": [ { "name": "FirstShotRatio", "value": [ 1, 1, 1, 1, 1, 1, 1 ] }, { "name": "SecondShotDamage", "value": [ 0, 150, 200, 325, 500, 625, 750 ] } ] }, "apiName": "TFT3_Lucian", "cost": 2, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Lucian.TFT_Set3.dds", "name": "Lucian", "stats": { "armor": 25, "attackSpeed": 0.699999988079071, "critChance": 0.25, "critMultiplier": 1.5, "damage": 50, "hp": 500, "initialMana": 0, "magicResist": 20, "mana": 35, "range": 4 }, "traits": [ "Cybernetic", "Blaster" ] }, "TFT3_Graves": { "ability": { "desc": "Graves launches a smoke grenade toward the enemy with the most Attack Speed. The grenade explodes on impact dealing @ModifiedDamage@ magic damage to nearby enemies and causing their attacks to miss for @BlindDuration@ seconds.", "icon": "ASSETS/Characters/Graves/HUD/Icons2D/GravesSmokeGrenade.dds", "name": "<NAME>", "variables": [ { "name": "Damage", "value": [ 0, 150, 200, 400, 0, 0, 0 ] }, { "name": "BlindDuration", "value": [ 2, 3, 4, 5, 6, 7, 8 ] } ] }, "apiName": "TFT3_Graves", "cost": 1, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Graves.TFT_Set3.dds", "name": "Graves", "stats": { "armor": 35, "attackSpeed": 0.550000011920929, "critChance": 0.25, "critMultiplier": 1.5, "damage": 55, "hp": 650, "initialMana": 50, "magicResist": 20, "mana": 80, "range": 1 }, "traits": [ "Space Pirate", "Blaster" ] }, "TFT3_Xerath": { "ability": { "desc": "Xerath transforms, summoning meteors to strike random foes in place of his normal attacks for @Duration@ seconds. Meteors deal @ModifiedDamage@ magic damage upon impact and if they kill their target, all adjacent enemies take @ModifiedAoEDamage@ magic damage and are stunned for @StunDuration@ seconds.", "icon": "ASSETS/Characters/TFT3_Xerath/HUD/Icons2D/TFT3_Xerath_Ult.TFT3_Set3_Xerath.dds", "name": "Abyssal Bombardment", "variables": [ { "name": "BaseDamage", "value": [ 350, 300, 400, 2500, 3000, 3000, 3000 ] }, { "name": "AoEDamage", "value": [ 175, 75, 100, 625, 1500, 1500, 1500 ] }, { "name": "StunDuration", "value": [ 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5 ] }, { "name": "Duration", "value": [ 6, 6, 8, 45, 45, 45, 45 ] } ] }, "apiName": "TFT3_Xerath", "cost": 5, "icon": "ASSETS/UX/TFT/ChampionSplashes/TFT3_Xerath.TFT3_Set3_Xerath.dds", "name": "Xerath", "stats": { "armor": 20, "attackSpeed": 0.8999999761581421, "critChance": 0.25, "critMultiplier": 1.5, "damage": 60, "hp": 750, "initialMana": 30, "magicResist": 20, "mana": 80, "range": 6 }, "traits": [ "Dark Star", "Sorcerer" ] } }<file_sep>import React from 'react' import { useHistory } from "react-router-dom" import { Link } from "react-router-dom"; import { Nav, Navbar, NavDropdown } from "react-bootstrap" export default function MyNav(props) { const history = useHistory(); const handleLogout = async () => { const res = await fetch(process.env.REACT_APP_SERVER + "/auth/logout", { headers: { Authorization: `Bearer ${localStorage.getItem("token")}` } }); if (res.status === 204) { props.setUser(null); localStorage.removeItem("token"); } }; return ( <Navbar className="navbar-dark nav-bg" expand="lg"> <Navbar.Brand><img style={{width:150}}src="../../images/nav_logo.png"></img></Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="mr-auto"> <Link className="nav-link" to="/"> Home </Link> <Link className="nav-link" to="/comps"> Team Comps </Link> <Link className="nav-link" to="/comp-builder"> Comp Builder </Link> <Link className="nav-link" to="/leaderboard"> Leaderboard </Link> </Nav> {!props.user ? ( <> <Link className="nav-link text-white" to="/login"> Login </Link> <Link className="nav-link text-white" to="/sign-up"> Register </Link> </> ) : ( <> {/* <span className="nav-link">Welcome back {props.user.name}!</span> */} <NavDropdown title={props.user.name} id="basic-nav-dropdown"> <NavDropdown.Item ><Link to="/profile">View Profile</Link></NavDropdown.Item> <NavDropdown.Item ><Link to="/edit-profile">Edit Profile</Link></NavDropdown.Item> <NavDropdown.Item ><Link to="/profile/favorites">View Favorites</Link></NavDropdown.Item> </NavDropdown> <Link className="nav-link" style={{color:"white"}}onClick={handleLogout}> Logout </Link> </> )} </Navbar.Collapse> </Navbar> ); } <file_sep>import React, {useState} from 'react' export default function EditAccount() { const [formInput, setFormInput] = useState({}) const [text, setText] = useState("") const handleChange = e => { setFormInput({ ...formInput, [e.target.name]: e.target.value }); }; const editProfile = async (e) => { e.preventDefault() const {summonerName} = formInput if(summonerName == null ) return setText("Null fields are not allowed. Please fill in at least one field to make changes.") const token = localStorage.getItem('token') const url = `${process.env.REACT_APP_SERVER}/users/me` const response = await fetch(url, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token }, body: JSON.stringify({ summonerName}) }); const data = await response.json(); console.log(data) if(data.status == "ok"){ setText("Your account details have successfully been updated.") }else{ setText("Something went wrong. Your account details were not updated. Please try again.") } // setLoading(false) }; return ( <form onSubmit={editProfile} onChange={handleChange}> <div class="form-group row"> <label for="name" class="col-4 col-form-label text-white">Summoner Name</label> <div class="col-8"> <input id="name" name="summonerName" placeholder="SummonerName" class="form-control here" type="text" /> </div> </div> <div class="form-group row"> <div class="offset-4 col-8"> <button name="submit" type="submit" class="btn btn-primary">Update My Profile</button> </div> <p className="text-white">{text}</p> </div> </form> ) } <file_sep>import React, { useState, useEffect } from 'react' import MySpinner from '../components/MySpinner' import { Link } from "react-router-dom" export default function Favorites() { const [comps, setComps] = useState(null) const [loading, setLoading] = useState(true) useEffect(() => { getFavorites() }, []) const getFavorites = async () => { const token = localStorage.getItem('token') const url = `${process.env.REACT_APP_SERVER}/comp-builder/comps/favorites` const response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token } }); const data = await response.json(); console.log("DATA", [data.data]); setComps(data.data); setLoading(false); } const filtered = (array) => array.filter(function (el) { return el != null; }); //go thru every champ and push traits to traitarr const traits = (champs) => champs.reduce((acc, el, idx) => { el.traits.forEach(e => { if (!acc.includes(e)) acc.push(e) }) return acc }, []) const compRow = comps && comps.map(el => { return (<div className="comp-row row mx-0 my-2 align-items-center"> <div style={{ fontSize: 16 }} className="col-md-2"> {el.title}<br></br> <span style={{ fontSize: 12 }} className="text-muted">Created by: {el.user && el.user.name}</span> </div> <div className="col-md-2 justify-content-evenly"> {traits(filtered(el.comp)).map(el => { return <img style={{ maxHeight: 25 }} className="mx-1" src={`../../images/trait_icon_3_${el.toLowerCase().replace(/\s/g, '')}.png`} /> })} </div> <div className="col-md-6 col-xs-1"> <div className="row "> {filtered(el.comp).map(el => { return <div className="col-md-1 col-sm mx-2 "> <div className="row mt-1"> <img style={{ width: 45 }} className={`champ-icon-${el && el.cost}`} src={`../images/${el && el.apiName}.png`} /> </div> <div className="row mt-1"> {el.items && el.items.map(el => { return <img className="item-icon" src={`../../images/${el.id}.png`} /> })} </div> </div> })} </div> </div> <div className="col-md-1 col-sm "> <Link className="text-white" to={`/comp-builder/${el._id}`}>Open in Builder</Link> </div> </div>) }) if (loading) return (<MySpinner />) return ( <div className="container" style={{ backgroundColor: "#0D202C" }}> {compRow} </div> ) } <file_sep>import React, { useState } from 'react' import {useHistory} from "react-router-dom" export default function RegisterPage(props) { const [formInput, setFormInput] = useState({ name: "", email: "", password: "" }); const history = useHistory(); const handleLogin = async (email, password) => { const res = await fetch(process.env.REACT_APP_SERVER+"/auth/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, password }) }); const data = await res.json(); console.log("DATA", data) if (data.status === "ok") { const token = data.data.token console.log("TOKENNNN", token) //user object with a token localStorage.setItem("token", token); props.setUser(data.data.user); } else { // token is not valid, clear the token so that we don't have to check again props.setUser(null) localStorage.removeItem("token"); } // // finally set our app state to LOADED // props.setLoaded(true); } console.log("USER", props.user) const handleChange = e => { setFormInput({ ...formInput, [e.target.name]: e.target.value }); const email = formInput.email const password = formInput.password console.log("EMAILANDPW", email, password) }; const handleRegister = async (e) => { e.preventDefault(); console.log("fired"); const email = formInput.email const password = <PASSWORD> const name = formInput.name const summonerName = formInput.summonerName console.log("EMAILANDPW", email, password) const res = await fetch(process.env.REACT_APP_SERVER+"/users", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name, email, password, summonerName}) }); //login after signing up if (res.status === 201) { handleLogin(email, password) history.push("/profile") } // to do by you }; console.log(formInput) return ( <div> <form className="form-signin" onSubmit={handleRegister} onChange={handleChange} > <img className="mb-4" src="/docs/4.5/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72" /> <h1 className="h3 mb-3 font-weight-normal">Please Register an Account</h1> <label className="sr-only" for="FormInputName">Name</label> <input className="form-control" type="text" name="name" placeholder="<NAME>" required autofocus /> <label for="inputEmail" className="sr-only" >Email address</label> <input type="email" name="email" className="form-control" placeholder="Email address" required autofocus /> <label for="inputPassword" className="sr-only">Password</label> <input type="<PASSWORD>" name="password" className="form-control" placeholder="<PASSWORD>" required autofocus /> <input type="text" name="summonerName" className="form-control" placeholder="<NAME>" required autofocus /> {/* <div className="checkbox mb-3"> <label> <input type="checkbox" value="remember-me" /> Remember me </label> </div> */} <button className="btn btn-lg btn-primary btn-block" type="submit">Sign Up</button> <p className="mt-5 mb-3 text-muted">&copy; 2017-2020</p> </form> <div> <p>Sign Up </p> <form onSubmit={handleLogin} onChange={handleChange}> <label>email: </label> <input type="email" name="email" placeholder="email address" /> <label>Password: </label> <input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" /> <button type="submit">Login</button> </form> <p>Register an Account</p> <form onSubmit={handleRegister} onChange={handleChange}> <label>name: </label> <input type="text" name="name" placeholder="full name" /> <label>email: </label> <input type="email" name="email" placeholder="email address" /> <label>Password: </label> <input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" /> <button type="submit">Sign Up</button> </form> </div> </div> ) } <file_sep>import React from 'react' import { useDrag } from 'react-dnd' import { ItemTypes } from '../utils/items' export default function (props) { const [{isDragging}, drag] = useDrag({ item: { type: ItemTypes.ITEMICON, obj: props.item }, collect: monitor => ({ isDragging: !!monitor.isDragging() }) }) return ( <img ref={drag} onMouseOver={()=>props.turnEverythingToNull()} width = "35px" className="m-2" id="myImg" src={`../images/${props.item.id}.png`}> </img> ) } <file_sep>import React, { useEffect, useState } from 'react' import MySpinner from "../components/MySpinner" import Tooltip from '@material-ui/core/Tooltip'; export default function Profile(props) { const [loading, setLoading] = useState(true) const [data, setData] = useState(null) useEffect(() => { getUser() }, []); const getUser = async () => { const token = localStorage.getItem('token') const url = `${process.env.REACT_APP_SERVER}/users` const response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token } }); const data = await response.json(); console.log("DATA", [data.data]); props.setUser(data.data); setLoading(false); // setLoading(false) }; console.log("FAVORITES", data) const renderStars = (el) => { let a = [] for (let i = 0; i < el.tier; i++) { a.push(<i className={`fa fa-star star unit-star-${el.rarity}`} aria-hidden="true"></i>) } return a } const matchHtml = props.user && props.user.info && props.user.info.matches.map(el => { return ( <div className="item-row"> <div className="left-border"> </div> <div className="match-row"> <div className="col-md-1"> <span style={{ color: "#207AC8", fontWeight: "bold" }}>#{el.placement}</span> <br></br> <span className="text-muted">Ranked</span> </div> <div className="col-md-1 row-items"> <img className="companion-icon" src="https://cdn.lolchess.gg/images/tft/companions/tooltip_sgpig_lastwish_tier1.little_legends_star_guardian.png" /> </div> <div id="traits" className="col-md-3 row-items row-xs-12"> <div>{el.traits.map(el => { let one try { one = require(`../images/trait_icon_3_${el.name.toLowerCase()}.png`) } catch (e) { one = require("../images/trait_icon_3_set3_blademaster.png") } return <span><img style={{ width: 25 }} src={one} /> </span> })}</div> </div> <div id="units" className="col-md-7"> <div className="row "> {el.units.map(el => { return <div className="col-md-1"> <div className="row justify-content-center"> {renderStars(el)} </div> <div className="row justify-content-center"> <Tooltip title={el.character_id} arrow> <img className={`unit-img-${el.rarity}`} style={{ width: 40, margin: 4 }} src={`../../images/${el.character_id}.png`} /> </Tooltip> </div> <div className="row justify-content-center"> {el.items.map(el => { return <img className="item-icon" src={`../../images/${el}.png`} /> })} </div> </div> })} </div> </div> </div> </div> ) }) if (loading) return (<MySpinner />) return ( <div className="bg"> <div className="container pt-3"> <div className="profile__header"> <div className="profile__icon"> <img src={`//ddragon.leagueoflegends.com/cdn/10.10.3208608/img/profileicon/${props.user && props.user.info.data.profileIconId}.png`} alt="Profile Icon" /> </div> <div className="profile__summoner"> <span className="profile__summoner__name"> {props.user && props.user.info.data.name}</span><br></br> {/* {props.user.info.data.profileIconId} */} <div style={{ fontSize: 12 }}> <span><img style={{ width: 20 }} src={`../../images/tier_${props.user.info.info.tier}.png`} /> {props.user.info.info.tier} {" "}{props.user.info.info.rank}</span><br></br> <span>LP: {props.user.info.info.leaguePoints}</span><br></br> <span>Wins: {props.user.info.info.wins}</span><br></br> <span>Win-Rate: {Math.round((props.user.info.info.wins / props.user.info.info.losses) * 100)}%</span> </div> </div> </div> {matchHtml} </div> </div> ) } <file_sep>import React, { useState, useEffect } from 'react' import { useParams, useHistory } from "react-router-dom" import Board from "../components/Board" import ChampsSection from '../components/ChampsSection' import ItemSection from "../components/ItemSection" import MySpinner from '../components/MySpinner' export default function CompBuilder() { const { id } = useParams() const history = useHistory() let me = [] let itemArr = [] for (let i = 0; i < 28; i++) { me.push(null) } const [dragable, setDragable] = useState(me) const [deck, setDeck] = useState(me) const [text, setText] = useState("") const [title, setTitle] = useState("") const [loading, setLoading] = useState(true) const [compTitle,setCompTitle] = useState("") //set every DRAGGED ITEM to false besides the one that //is clicked on //but do i really want everything to be false or just the hexes const turnEverythingToNullButIdx = idx => { const clone = [...me] clone[idx] = true setDragable(clone) } const turnEverythingToNull = () => { setDragable([...me]) } const setDeckElementToNull = idx => { const clone = [...deck] clone[idx] = null setDeck(clone) } useEffect(() => { loadComp(); }, []); const saveComp = async (e) => { e.preventDefault(); const token = localStorage.getItem('token') const res = await fetch(`${process.env. REACT_APP_SERVER}/comp-builder/`, { method: "POST", headers: { "Content-Type": "application/json", 'Authorization': 'Bearer ' + token }, body: JSON.stringify({ comp: deck, title: title }) }); const data = await res.json(); if (data.status == "success") { setText("comp successfully saved") history.push("/comps") } else if (res.status === 401) history.push("/login") else { setText(data.message) } } const loadComp = async (e) => { const res = await fetch(`${process.env.REACT_APP_SERVER}/comp-builder/comps/${id}`, { method: "GET", headers: { "Content-Type": "application/json", }, // body: JSON.stringify() }); const data = await res.json(); console.log(data) if (data.status === "success") { setDeck(data.data.comp) setCompTitle(data.data.title) setLoading(false) } else if (data.status === "error") { // setText(data.message) setLoading(false) } } if (loading) return ( <MySpinner /> ) console.log(compTitle) return ( <div style={{ backgroundColor: "#0D202C" }}> <div className="container" style={{ backgroundColor: "#0D202C" }}> <div className="divider-section py-4"> <span className="my-4">v1.0 Team Comp Builder</span> <div className="divider "></div> </div> <Board turnEverythingToNull={turnEverythingToNull} turnEverythingToNullButIdx={turnEverythingToNullButIdx} dragable = {dragable} setDragable = {setDragable} me={me} deck={deck} setDeck={setDeck} title={title} setDeckElementToNull={setDeckElementToNull} compTitle={compTitle} setTitle={setTitle} /> <button className="save-btn" onClick={saveComp}>Save Comp</button> <p className="text-danger">{text}</p> <div className="d-flex" > <div className="champ-section"><ChampsSection turnEverythingToNull={turnEverythingToNull} dragable = {dragable} setDragable = {setDragable} setDeckElementToNull={setDeckElementToNull} /></div> <div className="item-section" ><ItemSection turnEverythingToNull={turnEverythingToNull} dragable = {dragable} setDragable = {setDragable} /></div> </div> </div> </div> ) } <file_sep>import React from 'react' import {Tooltip} from "react-bootstrap" export default function RenderToolTip(props) { console.log(props) return ( <Tooltip id="button-tooltip" {...props}> {props.char}hi </Tooltip> ) } <file_sep>import React, { useState, useEffect } from 'react' import { Link, useHistory } from "react-router-dom" import MySpinner from "../components/MySpinner" import Tooltip from '@material-ui/core/Tooltip'; export default function Comps(props) { const [comps, setComps] = useState([]) const [loading, setLoading] = useState(true) const [cat, setCat] = useState("") const [sort, setSort] = useState("") const history = useHistory() console.log(props.user) useEffect(() => { getComps(); }, []); useEffect(() => { getComps(cat) }, [cat]) function queryBuilder(sort) { // caters let queryString = "" if (queryString.length === 0) { queryString = queryString + "?" + sort } else { queryString = queryString + "&" + sort } setCat(queryString) setSort(sort) console.log(queryString) } const getComps = async (q = "") => { const url = `${process.env.REACT_APP_SERVER}/comp-builder/comps/${q}` const response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); console.log("DATA", data); setComps(data.data) setLoading(false) }; console.log(comps) const handleFavorite = async (id) => { console.log(id) const token = localStorage.getItem('token') const url = `${process.env.REACT_APP_SERVER}/comp-builder/comps/${id}` const response = await fetch(url, { method: 'POST', headers: { "Content-Type": "application/json", 'Authorization': 'Bearer ' + token }, // body: JSON.stringify({ comp: deck, title: title }) }); const data = await response.json(); console.log(data) console.log(response) if (response.status === 401) history.push("/login") console.log("DATA", data, "hgf"); if (data.status === "success") getComps() } const filtered = (array) => array.filter(function (el) { return el != null; }); //go thru every champ and push traits to traitarr const traits = (champs) => champs.reduce((acc, el, idx) => { el.traits.forEach(e => { if (!acc.includes(e)) acc.push(e) }) return acc }, []) const compRow = comps.map(el => { return (<div className="comp-row row mx-0 my-2 align-items-center"> <div style={{ fontSize: 16 }} className="col-md-2"> {el.title}<br></br> <span className="text-muted">Created by: {el.user && el.user.name}</span> </div> <div className="col-md-2 justify-content-evenly"> {traits(filtered(el.comp)).map(el => { return <img style={{ maxHeight: 25 }} className="mx-1" src={`../../images/trait_icon_3_${el.toLowerCase().replace(/\s/g, '')}.png`} /> })} </div> <div className="col-md-6 col-xs-1"> <div className="row "> {filtered(el.comp).map(el => { return <div className="col-md-1 col-sm mx-2 "> <div className="row mt-1"> <Tooltip title={el.apiName} arrow> <img style={{ width: 45 }} className={`champ-icon-${el && el.cost}`} src={`../images/${el && el.apiName}.png`} /> </Tooltip> </div> <div className="row mt-1"> {el.items && el.items.map(el => { return <img className="item-icon" src={`../../images/${el.id}.png`} /> })} </div> </div> })} </div> </div> <div className="col-md-2 col-sm "> <Link className="text-white" to={`/comp-builder/${el._id}`}>Open in Builder</Link> {" "} <Link className="text-white" onClick={() => handleFavorite(el._id)}> {props.user && el.favorited.includes(props.user._id) ? "Unfavorite" : "Favorite"} </Link> </div> </div>) }) if (loading) { return ( <MySpinner /> ) } return ( <div className="py-3" style={{ backgroundColor: "#0D202C" }}> <div className="container"> <div className="divider-section"> <span className="my-2">v1.0</span> <div className="divider "></div> </div> <div className="my-3" style={{ textAlign: "right" }}> <button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Sort By </button> <div class="dropdown-menu dropdown-menu-right"> <button onClick={(e) => queryBuilder(e.target.value)} class="dropdown-item" type="button" value="sort=-createdAt">Newest</button> <button onClick={(e) => queryBuilder(e.target.value)} class="dropdown-item" type="button" value="sort=-count">Most Favorited</button> </div> <div className="mt-4"> {compRow} </div> </div> </div> </div> ) } <file_sep>import React from 'react' import items from "../items" import ItemIcon from "./ItemIcon" export default function ItemSection(props) { const arr = Object.keys(items) return ( <div className="row justify-content-center" > {arr.map(e=> <ItemIcon turnEverythingToNull={props.turnEverythingToNull} item={items[e]} />)} </div> ) } <file_sep>export default { "1": { "desc": " +@AD@ Attack Damage", "effects": { "AD": 15 }, "from": [], "icon": "ASSETS/Maps/Particles/TFT/Icon_BFSword.dds", "id": 1, "name": "<NAME>" }, "2": { "desc": " +@AS@% Attack Speed", "effects": { "AS": 15 }, "from": [], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_RecurveBow.dds", "id": 2, "name": "Recurve Bow" }, "3": { "desc": " +@AP@% Spell Power", "effects": { "AP": 20 }, "from": [], "icon": "ASSETS/Maps/Particles/TFT/Icon_NeedlesslyLargeRod.dds", "id": 3, "name": "Needlessly Large Rod" }, "4": { "desc": " +@Mana@ Mana", "effects": { "Mana": 15 }, "from": [], "icon": "ASSETS/Maps/Particles/TFT/Icon_TearOfTheGoddess.dds", "id": 4, "name": "Tear of the Goddess" }, "5": { "desc": "+@Armor@ Armor", "effects": { "Armor": 25 }, "from": [], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_ChainVest.dds", "id": 5, "name": "Chain Vest" }, "6": { "desc": "+@MagicResist@ Magic Resist", "effects": { "MagicResist": 25 }, "from": [], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_NegatronCloak.dds", "id": 6, "name": "Negatron Cloak" }, "7": { "desc": " +@Health@ Health", "effects": { "Health": 200 }, "from": [], "icon": "ASSETS/Maps/Particles/TFT/Icon_GiantsBelt.dds", "id": 7, "name": "<NAME>" }, "8": { "desc": "It must do <i>something</i>...", "effects": { "{fe9818ef}": 5 }, "from": [], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Spatula.dds", "id": 8, "name": "Spatula" }, "9": { "desc": "+@CritChance@% Critical Strike Chance<br>+@DodgeChance@% Dodge Chance", "effects": { "CritChance": 10, "{c4b5579c}": 10 }, "from": [], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_SparringGloves.dds", "id": 9, "name": "<NAME>" }, "11": { "desc": "Contributing to a kill grants +@ADPerStack@ Attack Damage for the remainder of combat.<br><br>This effect can stack any number of times (starting at @StartingStacks@).", "effects": { "AD": 30, "{ad68ce80}": 1, "{f1d43b01}": 30 }, "from": [ 1, 1 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_DeathBlade.dds", "id": 11, "name": "Deathblade" }, "12": { "desc": "The wearer's Basic Attacks deal an additional @CurrentHPPhysicalDamage@% of the target's current Health as physical damage.", "effects": { "AD": 15, "AS": 15, "{a79cf66e}": 12 }, "from": [ 1, 2 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_GiantSlayer.dds", "id": 12, "name": "<NAME>" }, "13": { "desc": "Basic Attacks and spells heal the wearer for @OmniVamp@% of the damage dealt.", "effects": { "AD": 15, "AP": 20, "{ad16f688}": 25 }, "from": [ 1, 3 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_HextechGunblade.dds", "id": 13, "name": "<NAME>" }, "14": { "desc": "After casting their spell, the wearer's Basic Attacks restore @ManaPercentRestore@% of their max Mana on-hit.", "effects": { "AD": 15, "Mana": 15, "{69fff1ab}": 18 }, "from": [ 1, 4 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_SpearOfShojin.dds", "id": 14, "name": "<NAME>" }, "15": { "desc": "Prevents the wearer's first death, placing them in stasis instead. After @StasisDuration@ seconds, they return with @HealthRestore@ Health and shed all negative effects.", "effects": { "AD": 15, "Armor": 25, "HealthRestore": 400, "{c425872e}": 2 }, "from": [ 1, 5 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_GuardianAngel.dds", "id": 15, "name": "<NAME>" }, "16": { "desc": "Basic Attacks heal the wearer for @Lifesteal@% of the damage dealt.", "effects": { "AD": 15, "LifeSteal": 35, "MagicResist": 25 }, "from": [ 1, 6 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Bloodthirster.dds", "id": 16, "name": "Bloodthirster" }, "17": { "desc": "When combat begins, the wearer and all allies within @HexRange@ hexes in the same row gain +@AttackSpeed@% Attack Speed for the rest of combat.", "effects": { "AD": 15, "AttackSpeed": 30, "Health": 200, "{9b1e8f37}": 1 }, "from": [ 1, 7 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_ZekesHerald.dds", "id": 17, "name": "<NAME>" }, "18": { "desc": "The wearer gains the Blademaster trait.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "AD": 15 }, "from": [ 1, 8 ], "icon": "ASSETS/Maps/Particles/TFT/TFT3_Item_Blademaster.dds", "id": 18, "name": "Blade of the Ruined King" }, "19": { "desc": "Grants +@CriticalStrikeAmp@% Critical Strike Damage.", "effects": { "AD": 15, "CritChance": 20, "{eac3d5c4}": 100 }, "from": [ 1, 9 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_InfinityEdge.dds", "id": 19, "name": "Infinity Edge" }, "22": { "desc": "Gain @AttackRange@% Attack Range.", "effects": { "AS": 30, "{c270990a}": 200 }, "from": [ 2, 2 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_RapidFirecannon.dds", "id": 22, "name": "<NAME>" }, "23": { "desc": "Basic Attacks grant +@AttackSpeedPerStack@% bonus Attack Speed for the rest of combat.<br><br>This effect can stack any number of times.", "effects": { "AP": 20, "AS": 15, "AttackSpeedPerStack": 5 }, "from": [ 2, 3 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_GuinsoosRageblade.dds", "id": 23, "name": "<NAME>" }, "24": { "desc": "Every third Basic Attack from the wearer deals @Damage@ magic damage to @1StarBounces@/@2StarBounces@/@3StarBounces@ %i:star% enemies.", "effects": { "AS": 15, "Damage": 80, "Mana": 15, "{12a15e9e}": 4, "{440f813d}": 3, "{79e2ec7b}": 5 }, "from": [ 2, 4 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_StatikkShiv.dds", "id": 24, "name": "<NAME>" }, "25": { "desc": "When the wearer takes damage or inflicts a critical hit, they gain a @DamageIncreasePercent@% stacking damage bonus. Stacks up to @StackCap@ times, at which point the wearer gains @BonusResistsAtStackCap@ Armor and Magic Resistance, and increases in size.", "effects": { "AS": 15, "Armor": 25, "{9396f00d}": 50, "{b55019fa}": 25, "{d50b4559}": 2 }, "from": [ 5, 2 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_TitansResolve.TFT_1001_ItemsUpdate.dds", "id": 25, "name": "<NAME>" }, "26": { "desc": "Basic Attacks fire a bolt at another nearby enemy, dealing @MultiplierForDamage@% of the wearer's Attack Damage and applying on-hit effects.", "effects": { "AS": 15, "AdditionalTargets": 1, "MagicResist": 25, "{276ba2c8}": 70 }, "from": [ 6, 2 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_RunaansHurricane.dds", "id": 26, "name": "<NAME>" }, "27": { "desc": "When the wearer dies, a Construct with @1StarZombieHealth@/@2StarZombieHealth@/@3StarZombieHealth@ %i:star% Health arises to continue the fight.", "effects": { "AS": 15, "Health": 200, "{0707495a}": 70, "{37b0144c}": 1000, "{86646c65}": 2000, "{f207284b}": 0.75, "{f6edd39e}": 3000 }, "from": [ 2, 7 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Zzrot_Portal.dds", "id": 27, "name": "Zz'Rot Portal" }, "28": { "desc": "The wearer is also a Blademaster.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "AS": 15 }, "from": [ 2, 8 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_BladeOfTheRuinedKing.dds", "id": 28, "name": "Blade of the Ruined King" }, "29": { "desc": "When the wearer inflicts a critical hit, the target's Armor is reduced by @ArmorReductionPercent@% for @ArmorBreakDuration@ seconds. This effect does not stack.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "AS": 15, "CritChance": 20, "{5079c7a2}": 90, "{cc9fefa7}": 3 }, "from": [ 2, 9 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_MortalReminder.dds", "id": 29, "name": "<NAME>" }, "33": { "desc": "Grants +@APPercentAmp@% Spell Power Amplification.<br><br>(All sources of Spell Power are @APPercentAmp@% more effective)", "effects": { "AP": 40, "{ce132611}": 50 }, "from": [ 3, 3 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_RabadonsDeathcap.dds", "id": 33, "name": "Rabadon's Deathcap" }, "34": { "desc": "When the wearer casts their spell, the first target dealt magic damage and up to @ExtraBounces@ nearby enemies are dealt an additional @1StarDamage@/@2StarDamage@/@3StarDamage@ %i:star% magic damage.", "effects": { "AP": 20, "Mana": 15, "{27b09915}": 150, "{337a0cca}": 4, "{844e604c}": 175, "{93d13af6}": 3, "{9b1e8f37}": 2, "{f5220527}": 225 }, "from": [ 3, 4 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_LudensEcho.dds", "id": 34, "name": "<NAME>" }, "35": { "desc": "When combat begins, the wearer and all allies within @HexRange@ hexes in the same row gain a shield that blocks @1StarShieldValue@/@2StarShieldValue@/@3StarShieldValue@ %i:star% damage for @ShieldDuration@ seconds.", "effects": { "AP": 20, "Armor": 25, "ShieldDuration": 8, "{0d46330d}": 275, "{6fb9af6a}": 250, "{829e6cec}": 350, "{9b1e8f37}": 2 }, "from": [ 3, 5 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_LocketOfTheIronSolari.dds", "id": 35, "name": "Locket of the Iron Solari" }, "36": { "desc": "Enemies within @HexRange@ hexes have their Magic Resist reduced by @MRShred@% (does not stack). When they cast a spell, they are zapped taking magic damage equal to @ManaRatio@% of their max Mana.", "effects": { "AP": 20, "Damage": 250, "MagicResist": 25, "{9b1e8f37}": 2, "{df6f64b9}": 225, "{fe079f34}": 50 }, "from": [ 3, 6 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_IonicSpark.dds", "id": 36, "name": "<NAME>" }, "37": { "desc": "When the wearer deals damage with their spell, they burn the target, dealing @BurnPercent@% of the target's Maximum Health as true damage over @BurnDuration@ seconds and reducing healing by @GrievousWoundsPercent@% for the duration of the burn.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "AP": 20, "Health": 200, "MonsterCap": 100, "{2161bfa2}": 50, "{57706a69}": 25, "{6df27940}": 1, "{97e52ce8}": 10 }, "from": [ 3, 7 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Morellonomicon.dds", "id": 37, "name": "Morellonomicon" }, "38": { "desc": "The wearer is also an Inferno.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "AP": 20 }, "from": [ 3, 8 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_InfernoCinder.dds", "id": 38, "name": "<NAME>" }, "39": { "desc": "Your spells can inflict critical hits.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "AP": 20, "CritChance": 20 }, "from": [ 3, 9 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Jeweled_Gauntlet.dds", "id": 39, "name": "Jeweled Gauntlet" }, "44": { "desc": "After casting their spell, the wearer gains @ManaRestore@ Mana.", "effects": { "Mana": 30, "{03494ad0}": 20 }, "from": [ 4, 4 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_SeraphsEmbrace.dds", "id": 44, "name": "Seraph's Embrace" }, "45": { "desc": "Reduces the Attack Speed of nearby enemies by @AttackSpeedSlow@%. Each Frozen Heart a champion carries beyond the first increases the radius of this effect.", "effects": { "Armor": 25, "AttackSpeedSlow": 50, "Mana": 15 }, "from": [ 4, 5 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_FrozenHeart.dds", "id": 45, "name": "Frozen Heart" }, "46": { "desc": "When the wearer casts a spell, restores @ManaRestore@ mana to allies within @HexRange@ hexes (including themself).", "effects": { "MagicResist": 25, "Mana": 15, "{03494ad0}": 8, "{9b1e8f37}": 2 }, "from": [ 6, 4 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Chalice3.TFT_Set3.dds", "id": 46, "name": "Chalice of Favor" }, "47": { "desc": "When the wearer dies, allies are healed for @HealthRestore@ Health.", "effects": { "Health": 200, "HealthRestore": 800, "Mana": 15, "{1e0630e9}": 25, "{5ffbbd48}": 50, "{8f954b18}": 30 }, "from": [ 4, 7 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Redemption.dds", "id": 47, "name": "Redemption" }, "48": { "desc": "The wearer gains the Star Guardian trait.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "Mana": 15 }, "from": [ 4, 8 ], "icon": "ASSETS/Maps/Particles/TFT/TFT3_Item_StarGuardian.dds", "id": 48, "name": "Star Guardian's Charm" }, "49": { "desc": "At the beginning of each planning phase, the wearer gains one of the following:<li>Basic attacks and spells deal +@TraitMultiplier@% Damage</li> <li>Basic attacks heal @TraitMultiplier@ Health on-hit</li>", "effects": { "CritChance": 10, "Mana": 15, "{a60806db}": 66.66699981689453, "{ae49cc70}": 50, "{c4b5579c}": 10 }, "from": [ 4, 9 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_HandOfJustice.dds", "id": 49, "name": "Hand Of Justice" }, "55": { "desc": "Negates bonus damage from incoming critical hits. On being hit by a Basic Attack, deal @1StarAoEDamage@/@2StarAoEDamage@/@3StarAoEDamage@ %i:star% magic damage to all nearby enemies (once every @ICD@ seconds).", "effects": { "Armor": 50, "{156febb8}": 200, "{1ee760be}": 100, "{6688a0d5}": 100, "{73e0fa13}": 2.5, "{a3b999e9}": 140 }, "from": [ 5, 5 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_BrambleVest.TFT_1001_ItemsUpdate.dds", "id": 55, "name": "<NAME>" }, "56": { "desc": "The wearer's Basic Attacks have a @ChanceOnHitToDisarm@% chance to disarm the target for @DisarmDuration@ seconds, preventing that enemy from making Basic Attacks.", "effects": { "Armor": 25, "DisarmDuration": 3, "MagicResist": 25, "{2426ea7e}": 25 }, "from": [ 5, 6 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_SwordBreaker.dds", "id": 56, "name": "<NAME>" }, "57": { "desc": "The holder's Basic Attacks burn the target on-hit, dealing @BurnPercent@% of the target's Maximum Health as true damage over @BurnDuration@ seconds, and reducing healing by @GrievousWoundsPercent@%, for the duration of the burn.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "Armor": 25, "Health": 200, "MonsterCap": 100, "{2161bfa2}": 50, "{57706a69}": 25, "{6df27940}": 1, "{8bfdb3fa}": 2, "{97e52ce8}": 10 }, "from": [ 5, 7 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_RedBuff.dds", "id": 57, "name": "Red Buff" }, "58": { "desc": "The wearer gains the Rebel trait.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "Armor": 25 }, "from": [ 5, 8 ], "icon": "ASSETS/Maps/Particles/TFT/TFT3_Item_Rebel.dds", "id": 58, "name": "Rebel Medal" }, "59": { "desc": "When combat begins, shoots a beam straight ahead that delays affected enemies' first spellcast, increasing their max Mana by @CostIncrease@% until they cast.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "Armor": 25, "{4516a18d}": 60, "{a861afa0}": 40, "{c4b5579c}": 20 }, "from": [ 5, 9 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Shroud.TFT_Set3.dds", "id": 59, "name": "Shroud of Stillness" }, "66": { "desc": "Reduces incoming magic damage by @MagicReduction@%.", "effects": { "MagicReduction": 50, "MagicResist": 50 }, "from": [ 6, 6 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_DragonsClaw.dds", "id": 66, "name": "Dragon's Claw" }, "67": { "desc": "When combat begins, the wearer summons a whirlwind on the opposite side of the arena that removes the closest enemy from combat for @BanishDuration@ seconds.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "Health": 200, "MagicResist": 25, "{510fdb6a}": 5 }, "from": [ 6, 7 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Zephyr.dds", "id": 67, "name": "Zephyr" }, "68": { "desc": "The wearer gains the Celestial trait.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "MagicResist": 25 }, "from": [ 8, 6 ], "icon": "ASSETS/Maps/Particles/TFT/TFT3_Item_Celestial.dds", "id": 68, "name": "Celestial Orb" }, "69": { "desc": "The wearer is immune to crowd control for the first @SpellShieldDuration@ seconds of combat.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "MagicResist": 25, "{a2b76524}": 10, "{c4b5579c}": 20 }, "from": [ 9, 6 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Mercurial.dds", "id": 69, "name": "Quicksilver" }, "77": { "desc": "The wearer regenerates @HealthRegen@% of their missing Health, but not more than @MaxHealthRegenAmount@, per second.", "effects": { "Health": 400, "HealthRegen": 5, "{0c90f194}": 150 }, "from": [ 7, 7 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_WarmogsArmor.dds", "id": 77, "name": "Warmog's Armor" }, "78": { "desc": "The wearer is also Glacial.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "Health": 200 }, "from": [ 8, 7 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_FrozenMallet.dds", "id": 78, "name": "<NAME>" }, "79": { "desc": "Blocks the first enemy spell that hits the wearer, and stuns the spell's caster for @StunDuration@ seconds.", "effects": { "Health": 200, "StunDuration": 4, "{c4b5579c}": 20 }, "from": [ 7, 9 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Backhand.dds", "id": 79, "name": "<NAME>" }, "88": { "desc": "Wearer's team gains +@MaxArmySizeIncrease@ maximum team size.", "effects": { "{ec9a04d1}": 1 }, "from": [ 8, 8 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_ForceOfNature.dds", "id": 88, "name": "Force of Nature" }, "89": { "desc": "The wearer is also a Berserker.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", "effects": { "CritChance": 10, "{c4b5579c}": 10 }, "from": [ 9, 8 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_BerserkerAxe.dds", "id": 89, "name": "<NAME>" }, "99": { "desc": "At the beginning of each planning phase, the wearer equips 2 temporary items. Temporary items increase in power based on your player level.<br><br><tftitemrules>[Consumes Three Item Slots]</tftitemrules>", "effects": { "CritChance": 20, "{c4b5579c}": 20 }, "from": [ 9, 9 ], "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_ThiefsGloves.dds", "id": 99, "name": "<NAME>" }, // "100": { // "desc": "It must do <i>something</i>...", // "effects": {}, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Unknown.dds", // "id": 100, // "name": "Spatula" // }, // "149": { // "desc": "Whenever any unit dies, gain X Mana.", // "effects": { // "Mana": 20, // "{c4b5579c}": 20 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_GiantSlayer.dds", // "id": 149, // "name": "Catalyst" // }, // "200": { // "desc": "Place on a champion to create a one-star copy of them.<br><br><tftitemrules>[CONSUMABLE - This item disappears when used.]</tftitemrules>", // "effects": {}, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Blessing_WildCard.dds", // "id": 200, // "name": "<NAME>" // }, // "529": { // "desc": "@ChanceToSpellSteal@ chance to steal the enemy's spell and cast it", // "effects": { // "{0cc88d45}": 10 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_SpellThiefsEdge.dds", // "id": 529, // "name": "Spell Thief" // }, // "541": { // "desc": "TFT_item_description_MortalReminder", // "effects": {}, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_MortalReminder.dds", // "id": 541, // "name": "<NAME>" // }, // "10001": { // "desc": "Loot goes here", // "effects": { // "CritChance": 20, // "{c4b5579c}": 20 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Unknown.dds", // "id": 10001, // "name": "Loot Bag" // }, // "10002": { // "desc": "Item temporarily disabled", // "effects": {}, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Jammed.dds", // "id": 10002, // "name": "Jammed!" // }, // "10003": { // "desc": " +@AD@ Attack Damage", // "effects": { // "AD": 15 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/Icon_BFSword.dds", // "id": 10003, // "name": "<NAME>" // }, // "10004": { // "desc": "Contributing to a kill grants +@ADPerStack@ Attack Damage for the remainder of combat.<br><br>This effect can stack any number of times (starting at @StartingStacks@).", // "effects": { // "AD": 30, // "{55ce8055}": "null", // "{d0fcc895}": 40 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_DeathBlade.dds", // "id": 10004, // "name": "Deathblade" // }, // "10005": { // "desc": "When the wearer dies, Repeating Crossbow is re-equipped to a new ally. Each time Repeating Crossbow is re-equipped, it grants an additional +@AttackSpeedPerStack@% Attack Speed and +@CritChancePerStack@% Critical Strike Chance for the remainder of combat.<br><br>No stacking limit.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", // "effects": { // "AS": 15, // "AttackSpeedPerStack": 30, // "CritChance": 20, // "{cb57edb0}": 30 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_RepeatingCrossbow.dds", // "id": 10005, // "name": "Repeating Crossbow" // }, // "10006": { // "desc": "Loot goes here", // "effects": {}, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_EmptySlot.TFT916CritComponent.dds", // "id": 10006, // "name": "<NAME>" // }, // "10201": { // "desc": "This champion starts combat with an additional @AttackSpeedPercent@% Attack Speed.", // "effects": { // "{a8ca7859}": 30 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Hex_Inferno.TFT_EnchantedHexes.dds", // "id": 10201, // "name": "<NAME>" // }, // "10202": { // "desc": "At the end of each planning phase this champion permanently gains @HPPerRound@ max health.", // "effects": { // "{1bb18b94}": 30 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Hex_Mountain.TFT_EnchantedHexes.dds", // "id": 10202, // "name": "<NAME>" // }, // "10203": { // "desc": "This champion starts combat with 30 additional mana.", // "effects": { // "{1a97299e}": 30 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Hex_Ocean.TFT_EnchantedHexes.dds", // "id": 10203, // "name": "<NAME>" // }, // "10204": { // "desc": "This champion has an additional @DodgeChancePercent@% chance to dodge enemy Basic Attacks.", // "effects": { // "{0e4779e5}": 20 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Hex_Wind.TFT_EnchantedHexes.dds", // "id": 10204, // "name": "<NAME>" // }, // "-46": { // "desc": "Basic Attacks have a @ChanceOnHitToSilence@% chance on-hit to silence the target, preventing mana gain for @SilenceDuration@ seconds.", // "effects": { // "MagicResist": 25, // "Mana": 20, // "SilenceDuration": 4, // "{2275757b}": 20, // "{4516a18d}": 4 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Hush.dds", // "id": -46, // "name": "Hush" // }, // "-28": { // "desc": "The wearer is also a Blademaster.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", // "effects": { // "AS": 30 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_BladeOfTheRuinedKing.dds", // "id": -28, // "name": "Blade of the Ruined King" // }, // "-25": { // "desc": "Critical hits against the wearer deal normal damage instead.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", // "effects": { // "AS": 15, // "Armor": 25 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_PhantomDancer.dds", // "id": -25, // "name": "<NAME>" // }, // "-55": { // "desc": "Reflects @DamageReflect@% of the mitigated damage from enemy Basic Attacks as magic damage.", // "effects": { // "Armor": 50, // "{6688a0d5}": 100 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Thornmail.dds", // "id": -55, // "name": "Thornmail" // }, // "-59": { // "desc": "After casting a spell, the wearer's next Basic Attack freezes the target for @FreezeDuration@ seconds.", // "effects": { // "Armor": 25, // "{aaa03dde}": 2.5, // "{c4b5579c}": 20 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_IcebornGauntlet.dds", // "id": -59, // "name": "<NAME>" // }, // "-100": { // "desc": "When the wearer dies, Repeating Crossbow is re-equipped to a new ally. Each time Repeating Crossbow is re-equipped, it grants an additional +@AttackSpeedPerStack@% Attack Speed and +@CritChancePerStack@% Critical Strike Chance for the remainder of combat.<br><br>No stacking limit.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", // "effects": { // "{48ea2af8}": 7, // "{98ac43ce}": 50 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_SwordOfTheDivine.dds", // "id": -100, // "name": "Repeating Crossbow" // }, // "-26": { // "desc": "Basic Attacks have a @ChanceOnHitToShrink@% chance on-hit to decrease the target's star level by 1 for the rest of combat.", // "effects": { // "AS": 15, // "MagicResist": 25, // "{a56e0a21}": 20 // }, // "from": [ // -26, // -26 // ], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_CursedBlade.dds", // "id": -26, // "name": "Cursed Blade" // }, // "-89": { // "desc": "Wearer is also a Yordle<br>Extra +10% Critical Strike Chance, +10% Dodge Chance<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", // "effects": { // "CritChance": 20, // "{c4b5579c}": 20 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Mittens.dds", // "id": -89, // "name": "Mittens" // }, // "-58": { // "desc": "Extra %i:scaleArmor% +@Armor@<br>Wearer is also a Knight<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", // "effects": { // "Armor": 40 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_KnightsVow.dds", // "id": -58, // "name": "Knight's Vow" // }, // "-78": { // "desc": "The wearer is also Glacial.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", // "effects": { // "Health": 400 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_FrozenMallet.dds", // "id": -78, // "name": "<NAME>" // }, // "-1": { // "desc": "Wearer is also a Hextech", // "effects": {}, // "from": [ // -1, // -1 // ], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_HextechChestguard.dds", // "id": -1, // "name": "<NAME>" // }, // "-48": { // "desc": "Extra %i:scaleMana% +@Mana@<br>Wearer is also a Demon<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", // "effects": { // "Mana": 40 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Darkin.dds", // "id": -48, // "name": "Darkin" // }, // "-18": { // "desc": "The wearer is also an Assassin.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", // "effects": { // "AD": 30 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_YoumuusGhostblade.dds", // "id": -18, // "name": "<NAME>" // }, // "-38": { // "desc": "Extra %i:scaleAP% +@AP@<br>Wearer is also a Sorcerer<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", // "effects": { // "AP": 40 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_Yuumi.dds", // "id": -38, // "name": "Yuumi" // }, // "-35": { // "desc": "On falling below @HealthPercent@% Health, become untargetable, invulnerable, but unable to move for @StasisDuration@ seconds.", // "effects": { // "AP": 20, // "Armor": 25, // "HealthPercent": 30, // "{c425872e}": 4 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_ZhonyasHourglass.dds", // "id": -35, // "name": "<NAME>" // }, // "-29": { // "desc": "When the wearer dies, Repeating Crossbow is re-equipped to a new ally. Each time Repeating Crossbow is re-equipped, it grants an additional +@AttackSpeedPerStack@% Attack Speed and +@CritChancePerStack@% Critical Strike Chance for the remainder of combat.<br><br>No stacking limit.<br><br><tftitemrules>[Unique - Only One Per Champion]</tftitemrules>", // "effects": { // "AS": 15, // "AttackSpeedPerStack": 30, // "CritChance": 20, // "{cb57edb0}": 30 // }, // "from": [], // "icon": "ASSETS/Maps/Particles/TFT/TFT_Item_RepeatingCrossbow.dds", // "id": -29, // "name": "Repeating Crossbow" // } }<file_sep>import React, { useState, useEffect } from 'react' import { useParams } from "react-router-dom" import '../App.css'; import MySpinner from '../components/MySpinner'; import Tooltip from '@material-ui/core/Tooltip'; export default function Player(props) { const [data, setData] = useState(null) const [loading, setLoading] = useState(true) const { id } = useParams() console.log(id) useEffect(() => { getPlayer() }, []) const getPlayer = async () => { const url = `${process.env.REACT_APP_SERVER}/topten/players/${id}` const response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); console.log("DATA", data) setData(data) setLoading(false) }; console.log(data) const renderStars = (el) => { let a = [] for (let i = 0; i < el.tier; i++) { a.push(<i className={`fa fa-star star unit-star-${el.rarity}`} aria-hidden="true"></i>) } return a } const matchHtml = data && data.matches.map(el => { return ( <div className="item-row"> <div className="left-border"> </div> <div className="match-row"> <div className="col-md-1"> <span style={{ color: "#207AC8", fontWeight: "bold" }}>#{el.placement}</span> <br></br> <span className="text-muted">Ranked</span> </div> <div className="col-md-1 row-items"> <img className="companion-icon" src="https://cdn.lolchess.gg/images/tft/companions/tooltip_sgpig_lastwish_tier1.little_legends_star_guardian.png" /> </div> <div id="traits" className="col-md-3 row-items row-xs-12"> <div>{el.traits.map(el => { let one try { one = require(`../images/trait_icon_3_${el.name.toLowerCase()}.png`) } catch (e) { one = require("../images/trait_icon_3_set3_blademaster.png") } return <span><img style={{ width: 25 }} src={one} /> </span> })}</div> </div> <div id="units" className="col-md-7"> <div className="row "> {el.units.map(el => { return <div className="col-md-1"> <div className="row justify-content-center"> {renderStars(el)} </div> <div className="row justify-content-center"> <Tooltip title={el.character_id} arrow> <img className={`unit-img-${el.rarity}`} style={{ width: 40, margin: 4 }} src={`../../images/${el.character_id}.png`} /> </Tooltip> </div> <div className="row justify-content-center"> {el.items.map(el => { return <img className="item-icon" src={`../../images/${el}.png`} /> })} </div> </div> })} </div> </div> </div> </div> ) }) if (loading) return (<MySpinner />) return ( <div className="bg"> <div className="container mt-3"> <div className="profile__header"> <div className="profile__icon"> <img src={`//ddragon.leagueoflegends.com/cdn/10.10.3208608/img/profileicon/${data && data.player.profileIconId}.png`} alt="Profile Icon" /> </div> <div className="profile__summoner"> <span className="profile__summoner__name">{data && data.player.name}</span><br></br> <button className="favorite-btn"><i class="fa fa-bookmark-o" aria-hidden="true"></i> Favorite</button> </div> </div> {matchHtml} </div> </div> ) } <file_sep>import React, { useState, useEffect } from 'react'; import './App.css'; import 'bootstrap/dist/css/bootstrap.css'; import { DndProvider } from "react-dnd" import { HTML5Backend } from "react-dnd-html5-backend" import {Navbar, Container, NavbarBrand} from "react-bootstrap" import { Switch, Route, Link } from "react-router-dom"; import TopTen from "./views/TopTen" import Player from "./views/Player" import Index from "./views/Index" import CompBuilder from "./views/CompBuilder" import Comps from "./views/Comps" import Pupdate from "./views/Pupdate" import User from './views/User'; import Profile from './views/Profile'; import Favorites from './views/Favorites'; import SignInSide from './views/SignInSide'; import SignUpSide from './views/SignUpSide'; import ForgotPw from './views/ForgotPw'; import champions from "./champions" import itemIcons from "./items" import NoMore from "./components/NoMore" import AuthRoute from "./components/AuthRoute" import MyNav from "./components/MyNav" import MySpinner from "./components/MySpinner" function App() { const [player, setPlayer] = useState(null) const [user, setUser] = useState(null); const [loaded, setLoaded] = useState(false); useEffect(async () => { await checkUser() }, []) const checkUser = async () => { // extracting token from url const urlToken = window.location.href.split("?token=")[1] ? window.location.href.split("?token=")[1].replace("#_=_", "") : null; // get token from storage or urlToken const token = localStorage.getItem("token") || urlToken; console.log(token) // if there is no token, we don't need to do anything else, just set our app state as LOADED if (!token) { setLoaded(true); return; } // if there is token, we will fetch user information from api server using the token. try { const url = process.env.REACT_APP_SERVER + "/users/me"; const res = await fetch(url, { method: "GET", headers: { Authorization: `Bearer ${token}` } }); console.log(res) // if we get user object from response, it means token is correct, we save it back to storage, as well as setState our user to the value we just got from the response if (res.status === 200) { const data = await res.json(); console.log("DATA", data) localStorage.setItem("token", token); setUser(data.data); } else { // token is not valid, clear the token so that we don't have to check again setUser(null) localStorage.removeItem("token"); } } catch (err) { console.log(err); } // finally set our app state to LOADED setLoaded(true); }; if (!loaded) return (<MySpinner></MySpinner>) return ( <DndProvider backend={HTML5Backend}> <MyNav user={user} setUser={setUser} /> <div id="index-body"> <Switch> <AuthRoute exact user={user} path="/edit-profile" component={User} /> <AuthRoute path="/profile/favorites" setUser={setUser} user={user} component={Favorites} /> <AuthRoute path="/profile" setUser={setUser} user={user} component={Profile} /> <Route path="/emails/:token" component={Pupdate} /> <Route path="/password-reset" render={() => <ForgotPw setUser={setUser} user={user} />} /> <NoMore exact path="/login" user={user} setUser={setUser} component={SignInSide} /> <NoMore exact path="/sign-up" user={user} setUser={setUser} component={SignUpSide} /> <Route path="/comps" render={() => <Comps user={user} />} /> <Route path="/comp-builder/:id" render={() => <CompBuilder />} /> <Route path="/comp-builder" render={() => <CompBuilder />} /> <Route path="/leaderboard/players/:id" render={() => <Player player={player} />} /> <Route path="/leaderboard" render={() => <TopTen setPlayer={setPlayer} />} /> <Route path="/" component={Index} /> </Switch> </div> <footer className="my-footer"> <div className="container pt-2"> <div className="divider"></div> <span class="text-muted" style={{fontSize: 10}}>TFT Helper isn't endorsed or sponsored by Riot Games and doesn't reflect the views or opinions of Riot Games or anyone officially involved in producing or managing League of Legends. League of Legends and Riot Games are trademarks or registered trademarks of Riot Games, Inc. League of Legends © Riot Games, Inc. Game content and materials are trademarks and copyrights of their respective companies, publisher and its licensors. TFT Helper is not affiliated with the game companies, publisher and its licensors.</span> </div> </footer> </DndProvider> ); } export default App; <file_sep>import React, { useState, useEffect } from 'react' import Hex from "./Hex" export default function Board(props) { // const [deck, setDeck] = useState(me) const [idxBeingDragged, setIdxBeingDragged] = useState(null) const setSingleEl = (idx, val) => { props.deck[idx] = val const arr = [...props.deck] props.setDeck(arr) } const handleChange = (e) => { e.preventDefault() props.setTitle(e.target.value) } useEffect(()=>{ },[idxBeingDragged]) // console.log("DECK", props.deck) return ( <div style={{ maxWidth: 800 }}> <form onChange={handleChange}> <input style={{ width: 300 }} className="form-control form-control-sm mb-3" type="text" placeholder="Title"> </input> </form> <div id="hexGrid"> {props.deck.map((e, idx) => <Hex setIdxBeingDragged={setIdxBeingDragged} setDeckElementToNull={props.setDeckElementToNull} hex={e} dragable={props.dragable[idx]} idx={idx} magic={setSingleEl} turnEverythingToNullButIdx={props.turnEverythingToNullButIdx} />)} </div> </div> ) }<file_sep>## 🎯 About TeamFight Tactics is a companion site used to create team compositions for the popular MOBA game TeamFight Tactics. Users can sign up, view their saved team compositions, and create compositions with the comp builder and share those compositons on the website for other users to see. It's a clone of [tftactics](https://tftactics.gg/) ## ▶️ Demo Here you can find the direct link: - [TFT Comp Builder](https://em-tft.netlify.app/comp-builder) ## ✨ Features - User signup/sign in - View the top ten Challenger ranked players in North America and their match history - View team compositions built by users and "favorite" them to view later - Create team compositions ## 🚀 Technologies - [React](https://reactjs.org/) - [React Router](https://reactrouter.com/web/guides/quick-start) - [MongoDB](https://docs.mongodb.com/manual/reference/program/mongod/) - [Express](https://expressjs.com/) - [Node](https://nodejs.org/en/) <file_sep>import React, {useState} from 'react' import { useDrag } from 'react-dnd' import { ItemTypes } from '../utils/items' import champions from "../champions" export default function (props) { const [{isDragging}, drag] = useDrag({ item: { type: ItemTypes.CHAMP_LIST_HEX, obj: props.champ }, collect: monitor => { if(monitor.isDragging()===true) { console.log(true) } return { // call setfill to other hexes isDragging: !!monitor.isDragging() }} }) return ( <div ref={drag}> <img onMouseOver={()=>props.turnEverythingToNull()} className={`champ-icon-${props.champ.cost} m-2`} width = "50px" opacity={isDragging ? ".5": "1"} id="myImg" src={`../images/${props.champ.apiName}.png`}> </img> </div> ) } <file_sep>import React, { useState, useEffect } from 'react' import { useDrop } from "react-dnd" import { ItemTypes } from '../utils/items' import '../App.css'; import ChampItems from './ChampItems'; import { useDrag } from 'react-dnd' export default function Hex(props) { const [champ, setChamp] = useState(null) const handleDrop = (c) => { setChamp(c.obj) if(c.idx !==props.idx){ props.magic(props.idx, c.obj) props.setDeckElementToNull(c.idx) /////// } console.log("source", c) } const handleDropItem = item => { const obj = {...props.hex} if(obj.items && obj.items.length === 3){ return } else{ obj.items = obj.items ? obj.items.concat(item) : [].concat(item) props.magic(props.idx, obj) } } const [{isOver}, drop] = useDrop({ accept: [ItemTypes.CHAMP_LIST_HEX, ItemTypes.CHAMP_HEX_LIST, ItemTypes.ITEMICON], drop: (item, monitor) => { if(item.type==="CHAMP_LIST_HEX" || item.type ==="CHAMP_HEX_LIST"){ handleDrop(item) } else if (item.type === "ITEMICON" && champ) { handleDropItem(item.obj) } }, collect: monitor => ({ isOver: !!monitor.isOver({ shallow: true }) }) }) // console.log("isOver",isOver) const [{isDragging}, drag] = useDrag({ item: { type: ItemTypes.CHAMP_HEX_LIST, obj: champ, idx: props.idx, // magic: v => handleFinishDrop(v) }, collect: monitor => { if (monitor.isDragging()) { console.log("start dragging") props.setIdxBeingDragged(props.idx) } return ({ isDragging: !!monitor.isDragging() })} }) return ( <div class="hex"> <div class="hexIn"> <div ref={props.dragable ? drag : drop} class="hexLink" href="#"> <img onMouseOver={()=>{ props.turnEverythingToNullButIdx(props.idx)}} src={props.hex ? `../images/${props.hex.apiName}.png` : "../images/lightplaceholder.png"} alt="" /> </div> <ChampItems items={props.hex && props.hex.items ? props.hex.items : []}/> </div> </div> ) }
e7fa72a1d68c2463860aaa2480fe86952ece7489
[ "JavaScript", "Markdown" ]
18
JavaScript
yumemily/tft-frontend
a39d841966c4c61f444f956e830f79ae336a5642
e93d1b9a63becdb6eb2c03e529b37d3d35172dfb
refs/heads/master
<file_sep>FROM ubuntu ENV AWS_ACCESS_KEY_ID="" ENV AWS_SECRET_ACCESS_KEY="" RUN apt-get update && \ apt-get install -y openssh-client jq python3-pip COPY id_rsa /root/.ssh/id_rsa RUN chmod 600 /root/.ssh/id_rsa COPY bash.sh /bash.sh RUN pip3 install awscli # ENTRYPOINT pwd # ENTRYPOINT ./bash.sh $0 $1 $2<file_sep>#!/bin/bash TARGET_INSTANCE=$1 echo "Working on instance: $1" USERNAME=$2 echo "Insert key for user: $2" NEW_KEY=$3 echo "keypair $3 will be added to Instance $1" send_remote_command () { ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 $1 $2 } read_error () { # Reads errors and exits script if grep -q $1 $2; then echo "Error cought: $1" exit 1 fi } if [ -z $AWS_DEFAULT_REGION ]; then echo "AWS_DEFAULT_REGION Not passed Assuming you mean eu-west-1" export AWS_DEFAULT_REGION=eu-west-1 fi # Find your instance instance_dict=$(aws ec2 describe-instances --instance-ids $TARGET_INSTANCE --query "Reservations[0].Instances[0]") INSTANCE_FOUND=$? if [ $INSTANCE_FOUND -eq 0 ]; then instance_id=$(echo $instance_dict | jq -r '.InstanceId') instance_zone=$(echo $instance_dict | jq -r '.Placement.AvailabilityZone') instance_public_ip=$(echo $instance_dict | jq -r '.PublicIpAddress') instance_public_ip=$(echo $instance_dict | jq -r '.PrivateIpAddress') device_dict=$(echo $instance_dict | jq -r '.BlockDeviceMappings') root_device_name=$(echo $instance_dict | jq -r '.RootDeviceName') root_device_dict=$(echo $device_dict | jq ".[] | select(.DeviceName == \"$root_device_name\")") volumeId=$(echo $root_device_dict | jq -r '.Ebs.VolumeId') else echo "Instance not found" exit 1 fi # exit 1 # Stop the instance and wait aws ec2 describe-instances --instance-ids $TARGET_INSTANCE --output text --query 'Reservations[*].Instances[*].State.Name' aws ec2 stop-instances --instance-ids $TARGET_INSTANCE 2> /dev/null echo "Stopping instance..." aws ec2 wait instance-stopped --instance-ids $TARGET_INSTANCE echo "Instance has been stopped" # Detach root device # aws ec2 detach-volume --volume-id $volumeId echo "Detaching root volume..." # aws ec2 wait volume-available --volume-ids $volumeId echo "Volume detached" # Start new instance temp_instance=$(aws ec2 run-instances --image-id ami-089cc16f7f08c4457 --instance-type "t2.micro" --placement AvailabilityZone=$instance_zone --key-name $NEW_KEY --instance-initiated-shutdown-behavior terminate --query "Instances[*].InstanceId" --output text 2> command_ouput) read_error "InvalidKeyPair.NotFound" command_ouput echo "Starting instance..." aws ec2 wait instance-running --instance-ids $temp_instance echo "Instance ready" new_instance_dict=$(aws ec2 describe-instances --instance-ids $temp_instance --query "Reservations[0].Instances[0]") new_instance_public_ip=$(echo $new_instance_dict | jq -r '.PublicIpAddress') new_instance_private_ip=$(echo $new_instance_dict | jq -r '.PrivateIpAddress') # Attach root volume NEW_DEVICE_NAME="/dev/xvdf" # aws ec2 attach-volume --volume-id $volumeId --instance-id $temp_instance --device $NEW_DEVICE_NAME aws ec2 attach-volume --volume-id vol-0583efdf1c8deebf6 --instance-id $temp_instance --device $NEW_DEVICE_NAME # Check instance connection set -x send_remote_command $USERNAME@$new_instance_private_ip "whoami " && export TEMP_INSTANCE=$new_instance_private_ip || send_remote_command $USERNAME@$new_instance_public_ip "whoami " && export TEMP_INSTANCE=$new_instance_public_ip if [ "$?" = 255 ] ; then echo "there was an error" exit 1 fi # ssh -tt ubuntu@$TEMP_INSTANCE < /dev/tty ssh -tt ubuntu@$TEMP_INSTANCE << EOF sudo -i set +x sudo mkdir /mnt/xvdf/ sudo mount ${NEW_DEVICE_NAME}1 /mnt/xvdf/ mount /dev/xvdf /source_root_device cat /home/ubuntu/.ssh/authorized_keys >> /home/${USERNAME}/.ssh/authorized_keys exit exit EOF<file_sep>## ec2 key replace ### Pre requsets * Create a keypair to use. Download it and keep it where you build this container * specify it when running * working instance must accessible from where to job is running (this will easily be met if you run on AWS) ### Build To import the key to be used you need your id_rsa\ pem file (downloaded or created for AWS) The build process copies the file in to the container and uses when excutes `docker build . -t ec2-key-switch` ### Run To allow the utility to create and maipulate resources in AWS it requires some prevlidges You can pass the `docker run` command IAM key and secret or rely on instance role. example `docker run` command: """ docker run -d -e AWS_ACCESS_KEY_ID=AKI... -e AWS_SECRET_ACCESS_KEY=ps...Zen ec2-key-switch """
bc9df953260b9f9dbd87e7e09844ff4b200e1d0b
[ "Markdown", "Dockerfile", "Shell" ]
3
Dockerfile
maimon33/utilities
0204c00761582538e24e457d9abe6f3cb31b1986
e93a731d9822570ef07093fc8ebbb747f5e9d266
refs/heads/main
<repo_name>notiamoah-21/Hubspot-DataFeed<file_sep>/README.md # Hubspot DataFeed #### Aim: To successfully transfer data from paginated hubspot api and dynamically load all the relevant data into the MS SQL Server under the logic ## Create Hubspot API Results ## Dynamically Load all other API Result Pages ## Convert API Results into DataFrame ## Load Data into MS SQL Server <file_sep>/hubspot_to_sql.py import requests import json import pandas as pd import pyodbc import numpy as np #%% " Part One - Create page one request and append dictionary to empty list " URL = #Confidential r = requests.get(URL) d = r.text Parsed = json.loads(d) All_Pages = [] All_Pages.append(Parsed['results']) #%% " Part Two - Loop through all other requests url and apend to lists " has_more = True while has_more: r = requests.get(URL + "&after=" + str(Parsed['paging']['next']['after'])) d = r.text Parsed = json.loads(d) All_Pages.append(Parsed['results']) has_more = Parsed.get('paging') #%% "Part Three - Transfer the statements into the properties dictionary" statements = ["archived", "createdAt", "id", "updatedAt"] numbers = [0,1,2,3,4] for number in numbers: for number2 in list(range(len(All_Pages[number]))): for statement in statements: All_Pages[number][number2]['properties'][statement] = All_Pages[number][number2][statement] #%% "Part Four - Create list of dictionary for all pages of properties dictionaries" List_Dict = [] numbers = [0,1,2,3,4] for number in numbers: for number2 in list(range(len(All_Pages[number]))): List_Dict.append(All_Pages[number][number2]['properties']) #%% "Part Five - Create the pandas dataframe from the list of dictionaries" df = pd.DataFrame(List_Dict) #%% " Part Six - Create a connetion for SQL interaction " def create_connection(): global cnxn global cursor connection_string = #Confidential cnxn = pyodbc.connect(connection_string) cursor = cnxn.cursor() create_connection() #%% " Part Seven - Create sql statement to insert dataframe into sql" values = list(df.values.tolist()) sql_statement = "INSERT INTO hubspot.companies " sql_statement += "(annual_revenue, city, country, created_date, description, domain, hs_lastmodified_date, hs_object_id, industry, name, phone, type, archived, created_at, id, update_at) " sql_statement += "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, getutcdate())" for value in values: cursor.execute(sql_statement, value) cnxn.commit() #%% " Part Eight - Test to check for any more new records from api results" # Convert SQL Query (id, update_at) into a pandas dataframe sql_df = pd.read_sql("SELECT [id], [update_at] FROM [hubspot].[companies]", cnxn) # Convert column type of the df to match with sql_df df['id'] = pd.to_numeric(df['id']) df['updatedAt'] = pd.to_datetime(df['updatedAt']).dt.tz_localize(None) sql_df['update_at'] = pd.to_datetime(sql_df['update_at']) print(df.dtypes) print(sql_df.dtypes) # Select rows from api results based on logic conditions of sql dataframe, instead of returning if statements logic_one = df['id'] != sql_df['id'] logic_two = (df['id'] == sql_df['id']) & (df['updatedAt'] != sql_df['update_at']) if logic_one.all(): values.append(df.loc[df['id'] != sql_df['id']].values.tolist()) elif logic_two.all(): values.append(df.loc[(df['id'] == sql_df['id']) & (df['updatedAt'] != sql_df['update_at'])].values.tolist()) else: print("There are no new records")
c062bac8430cb578de75d8e89d9bd82386d5181a
[ "Markdown", "Python" ]
2
Markdown
notiamoah-21/Hubspot-DataFeed
703b06dd9f6f6822a172dfa7095ea4971340c3a7
6c54d3ddb476b0bcdbfe8573c92ad534fde4e641
refs/heads/master
<repo_name>vsergejevs/Atmega48<file_sep>/main.c #define F_CPU 2000000L #include <avr/io.h> #include <util/delay.h> #include <avr/interrupt.h> #define SW3 0b00000001 // left to right #define SW4 0b00000010 // right to left #define SW5 0b00000100 // stop ISR(INT0_vect) { PORTB = 0b00000000; // SW5 LEDs off } int main(void) { unsigned char i, j; DDRB = 0xFF; // Set PORTB for output PORTB = 0b00000000; // All LEDs are off DDRD = 0x00; // set PORTD for input PORTD = 0b00000001; // left to right PORTD = 0b00000010; // right to left PORTD = 0b00000100; // stop EIMSK = 0b00000011; // External Interrupt Mask Register EICRA = 0b00001010; // External Interrupt Control Register sei(); while (1) { if (!(PIND & SW3)) { for (i = 0; i <= 7; i++) { PORTB = (1 << i); // LEDs blinking left to right _delay_ms(200); } } else { PORTB = 0b00000000; // LEDs off } if (!(PIND & SW4)) { for (j = 7; j >= 0; j--) { PORTB = (1 << j); // LEDs blinking right to left _delay_ms(200); } } else { PORTB = 0b00000000; // LEDs off } } } <file_sep>/README.md # Atmega48 microcontroller running lights Tested on Atmega48 Code for creating a running lights effect initially from left to right Button SW3 changes direction right to left Button SW4 changes direction back to left to right Button SW5 turns off lights
cba05bb1b4cad3ec5e27b111ea342daa52b073f2
[ "Markdown", "C" ]
2
C
vsergejevs/Atmega48
ae4ff714de8714fbc36729fd067ea9d1cf76a9ce
caedc3ee444ba3511848ddf4b03befaedbd26464
refs/heads/master
<repo_name>numerge1998/MedicalOfficeWeb<file_sep>/backend/src/main/java/ro/tuc/ds2020/repositories/MedicationPlanRepository.java package ro.tuc.ds2020.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import ro.tuc.ds2020.entities.Medication; import ro.tuc.ds2020.entities.MedicationPlan; import java.util.List; import java.util.Optional; import java.util.UUID; public interface MedicationPlanRepository extends JpaRepository<MedicationPlan, UUID> { /** * Example: JPA generate Query by Field */ List<MedicationPlan> findByPeriod(String period); /** * Example: Write Custom Query */ @Query(value = "SELECT m " + "FROM MedicationPlan m " + "WHERE m.period = :period") Optional<MedicationPlan> findSeniorsByName(@Param("period") String period); } <file_sep>/frontend/src/commons/hosts.js export const HOST = { backend_api: 'https://alin-pop-spring2020.herokuapp.com', }; <file_sep>/backend/src/main/java/ro/tuc/ds2020/repositories/MedicationRepository.java package ro.tuc.ds2020.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import ro.tuc.ds2020.entities.Medication; import javax.transaction.Transactional; import java.util.UUID; public interface MedicationRepository extends JpaRepository<Medication, UUID> { @Transactional @Modifying @Query("UPDATE Medication p set p.name = :name, p.side_effects = :side_effects, p.dosage = :dosage where p.id_medication = :id") void update(@Param("id") UUID id, @Param("name") String name, @Param("side_effects") String side_effects, @Param("dosage") String dosage); } <file_sep>/backend/src/main/java/ro/tuc/ds2020/services/LoginService.java package ro.tuc.ds2020.services; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ro.tuc.ds2020.controllers.handlers.exceptions.model.ResourceNotFoundException; import ro.tuc.ds2020.dtos.DoctorDTO; import ro.tuc.ds2020.dtos.DoctorDetailsDTO; import ro.tuc.ds2020.dtos.LoginDTO; import ro.tuc.ds2020.dtos.LoginDetailsDTO; import ro.tuc.ds2020.dtos.builders.DoctorBuilder; import ro.tuc.ds2020.dtos.builders.LoginBuilder; import ro.tuc.ds2020.entities.Doctor; import ro.tuc.ds2020.entities.Login; import ro.tuc.ds2020.repositories.LoginRepository; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; @Service public class LoginService { private static final Logger LOGGER = LoggerFactory.getLogger(DoctorService.class); private final LoginRepository loginRepository; @Autowired public LoginService(LoginRepository loginRepository) { this.loginRepository = loginRepository; } public List<LoginDTO> findLogin() { List<Login> loginList = loginRepository.findAll(); return loginList.stream() .map(LoginBuilder::toLoginDTO) .collect(Collectors.toList()); } public LoginDetailsDTO findLoginById(UUID id) { Optional<Login> prosumerOptional = loginRepository.findById(id); if (!prosumerOptional.isPresent()) { LOGGER.error("Login with id {} was not found in db", id); throw new ResourceNotFoundException(Doctor.class.getSimpleName() + " with id: " + id); } return LoginBuilder.toLoginDetailsDTO(prosumerOptional.get()); } public LoginDetailsDTO findUserRole(String username) { Optional<Login> prosumerOptional = loginRepository.findUserRole(username); if (!prosumerOptional.isPresent()) { LOGGER.error("Login with username {} was not found in db", username); throw new ResourceNotFoundException(Doctor.class.getSimpleName() + " with username: " + username); } return LoginBuilder.toLoginDetailsDTO(prosumerOptional.get()); } public UUID insert(LoginDetailsDTO loginDTO) { Login login = LoginBuilder.toEntity(loginDTO); login = loginRepository.save(login); LOGGER.debug("Login with id {} was inserted in db", login.getId_login()); return login.getId_login(); } public UUID delete(LoginDetailsDTO loginDTO) { loginRepository.deleteById(loginDTO.getId_login()); LOGGER.debug("Login plan with id {} was deleted from db", loginDTO.getId_login()); return loginDTO.getId_login(); } } <file_sep>/backend/src/main/java/ro/tuc/ds2020/dtos/builders/DoctorBuilder.java package ro.tuc.ds2020.dtos.builders; import ro.tuc.ds2020.dtos.DoctorDTO; import ro.tuc.ds2020.dtos.DoctorDetailsDTO; import ro.tuc.ds2020.dtos.PersonDTO; import ro.tuc.ds2020.dtos.PersonDetailsDTO; import ro.tuc.ds2020.entities.Doctor; import ro.tuc.ds2020.entities.Person; public class DoctorBuilder { private DoctorBuilder() { } public static DoctorDTO toDoctorDTO(Doctor doctor) { return new DoctorDTO(doctor.getId(), doctor.getName(), doctor.getAge()); } public static DoctorDetailsDTO toDoctorDetailsDTO(Doctor doctor) { return new DoctorDetailsDTO(doctor.getId(), doctor.getName(), doctor.getAddress(), doctor.getAge()); } public static Doctor toEntity(DoctorDetailsDTO doctorDetailsDTO) { return new Doctor(doctorDetailsDTO.getName(), doctorDetailsDTO.getAddress(), doctorDetailsDTO.getAge()); } } <file_sep>/backend/src/main/java/ro/tuc/ds2020/dtos/LoginDetailsDTO.java package ro.tuc.ds2020.dtos; import ro.tuc.ds2020.dtos.validators.annotation.AgeLimit; import javax.validation.constraints.NotNull; import java.util.Objects; import java.util.UUID; public class LoginDetailsDTO { private UUID id_login; @NotNull private String username; @NotNull private String password; @NotNull private String role; public LoginDetailsDTO() { } public LoginDetailsDTO( String username, String password, String role) { this.username = username; this.password = <PASSWORD>; this.role = role; } public LoginDetailsDTO(UUID id_login, String username, String password, String role) { this.id_login = id_login; this.username = username; this.password = <PASSWORD>; this.role = role; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LoginDetailsDTO that = (LoginDetailsDTO) o; return Objects.equals(id_login, that.id_login) && Objects.equals(username, that.username) && Objects.equals(password, that.password) && Objects.equals(role, that.role); } @Override public int hashCode() { return Objects.hash(id_login, username, password, role); } public UUID getId_login() { return id_login; } public LoginDetailsDTO setId_login(UUID id_login) { this.id_login = id_login; return this; } public String getUsername() { return username; } public LoginDetailsDTO setUsername(String username) { this.username = username; return this; } public String getPassword() { return password; } public LoginDetailsDTO setPassword(String password) { this.password = <PASSWORD>; return this; } public String getRole() { return role; } public LoginDetailsDTO setRole(String role) { this.role = role; return this; } } <file_sep>/frontend/src/login/login-container.js import React from 'react'; import validate from "../person/components/validators/person-validators"; import Button from "react-bootstrap/Button"; import * as API_USERS from "../login/login-api"; import APIResponseErrorMessage from "../commons/errorhandling/api-response-error-message"; import {Col, Modal, ModalBody, Row} from "reactstrap"; import { FormGroup, Input, Label} from 'reactstrap'; import Form from "reactstrap/es/Form"; class LoginContainer extends React.Component { constructor(props) { super(props); this.login = {id:null, username:null, password:<PASSWORD>, role:null}; this.state = { errorStatus: 0, error: null, formIsValid: false, role : '', formControls: { username: { value: '', placeholder: '', valid: false, touched: false, validationRules: { isRequired: true } }, password: { value: '', placeholder: '', type:"password", valid: false, touched: false, validationRules: { isRequired: true } }, } }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange = event => { const name = event.target.name; const value = event.target.value; const updatedControls = this.state.formControls; const updatedFormElement = updatedControls[name]; updatedFormElement.value = value; updatedFormElement.touched = true; updatedFormElement.valid = validate(value, updatedFormElement.validationRules); updatedControls[name] = updatedFormElement; let formIsValid = true; for (let updatedFormElementName in updatedControls) { formIsValid = updatedControls[updatedFormElementName].valid && formIsValid; } this.setState({ formControls: updatedControls, formIsValid: formIsValid }); }; getByUsername(id) { return API_USERS.getUserRole(id,(result, status, err) => { if (result !== null && status === 200) { this.login.id = result.id; this.login.username = result.username; this.login.password = <PASSWORD>; this.login.role = result.role; console.log(this.login.role + " this"); if(this.login.role === "doctor") { this.render(); //window.location.href = "https://alin-pop-frontend-1.herokuapp.com/homeDoctor" window.location.href = "http://localhost:3000/homeDoctor" localStorage.setItem("role", 'doctor'); } if(this.login.role === "caregiver") { //window.location.href = "https://alin-pop-frontend-1.herokuapp.com/homeCaregiver" window.location.href = "http://localhost:3000/homeCaregiver" localStorage.setItem("role", 'caregiver'); } else if(this.login.role === "patient") { //window.location.href = "https://alin-pop-frontend-1.herokuapp.com/homePatient" window.location.href = "http://localhost:3000/homePatient" localStorage.setItem("role", 'patient'); } else { console.log("nu am introdus bine... " + this.login.role); } } else { this.setState(({ errorStatus: status, error: err })); } }); } handleSubmit() { localStorage.removeItem("role"); let asta = this.state.formControls.username.value; console.log(asta); this.getByUsername(asta); this.render() // if(this.login.role === "doctor") // window.location.href = "https://alin-pop-frontend-1.herokuapp.com/homeDoctor" // else if(this.login.role === "caregiver") // window.location.href = "https://alin-pop-frontend-1.herokuapp.com/homeCaregiver" // else if(this.login.role === "patient") // window.location.href = "https://alin-pop-frontend-1.herokuapp.com/homePatient" // else { // console.log("nu am introdus bine... " + this.login.role); // } } render() { return ( <Modal isOpen={true} className={this.props.className} size="lg"> <ModalBody> <Form inline> <FormGroup id='username'> <Label for='usernameField'> Username: </Label> <Input name='username' id='usernameField' placeholder={this.state.formControls.username.placeholder} onChange={this.handleChange} defaultValue={this.state.formControls.username.value} touched={this.state.formControls.username.touched? 1 : 0} valid={this.state.formControls.username.valid} required /> </FormGroup> <FormGroup id='password'> <Label for='passwordField'> Password: </Label> <Input name='password' type={"<PASSWORD>"} id='passwordField' placeholder={this.state.formControls.password.placeholder} onChange={this.handleChange} defaultValue={this.state.formControls.password.value} touched={this.state.formControls.password.touched? 1 : 0} valid={this.state.formControls.password.valid} required /> </FormGroup> <Row> <Col sm={{size: '4', offset: 8}}> <Button disabled={!this.state.formIsValid} onClick={this.handleSubmit}> Login </Button> </Col> </Row> { this.state.errorStatus > 0 && <APIResponseErrorMessage errorStatus={this.state.errorStatus} error={this.state.error}/> } </Form> </ModalBody> </Modal> ) ; } } export default LoginContainer; <file_sep>/backend/src/main/java/ro/tuc/ds2020/repositories/LoginRepository.java package ro.tuc.ds2020.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import ro.tuc.ds2020.entities.Login; import ro.tuc.ds2020.entities.MedicationPlan; import java.util.List; import java.util.Optional; import java.util.UUID; public interface LoginRepository extends JpaRepository<Login, UUID> { @Query(value = "SELECT l " + "FROM Login l " + "WHERE l.username = :username") Optional<Login> findUserRole(@Param("username") String username); } <file_sep>/backend/src/main/java/ro/tuc/ds2020/ActivityListener.java package ro.tuc.ds2020; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ro.tuc.ds2020.entities.Activity; import ro.tuc.ds2020.repositories.ActivityRepository; @Service public class ActivityListener { @Autowired Notification message1; private final ActivityRepository activityRepository; @Autowired public ActivityListener(ActivityRepository activityRepository) { this.activityRepository = activityRepository; } @RabbitListener(queues = "default_parser_q") public void consumeDefaultMessage(Activity activ) { //System.out.println("id: " + activ.getId_patient() + " activity: " + activ.getActivity() + " start: " + activ.getStart_date() + " end: " + activ.getEnd_date() + ""); //log.info("Rabbit message with default config :{} {} {} {}", activ.getId_patient(), activ.getActivity(), activ.getStart_date(), activ.getEnd_date()); if(activ.getEnd_date() - activ.getStart_date() > 25200000 && activ.getActivity().equals("Sleeping")) { Message mes = new Message("Sleep", activ.getActivity()); message1.sendMessage(mes); // activityRepository.save(activ); System.out.println("id: " + activ.getId_patient() + " activity: " + activ.getActivity() + " start: " + activ.getStart_date() + " end: " + activ.getStart_date() + ""); } if(activ.getEnd_date() - activ.getStart_date() > 18000000 && activ.getActivity().equals("Leaving")) { Message mes = new Message("Leave", activ.getActivity()); message1.sendMessage(mes); System.out.println("id: " + activ.getId_patient() + " activity: " + activ.getActivity() + " start: " + activ.getStart_date() + " end: " + activ.getStart_date() + ""); } if(activ.getEnd_date() - activ.getStart_date() > 1800000 && (activ.getActivity().equals("Showering") || activ.getActivity().equals("Toileting") || activ.getActivity().equals("Grooming"))) { Message mes = new Message("Bathroom", activ.getActivity()); message1.sendMessage(mes); System.out.println("id: " + activ.getId_patient() + " activity: " + activ.getActivity() + " start: " + activ.getStart_date() + " end: " + activ.getStart_date() + ""); } } } <file_sep>/frontend/src/medication/medication-container.js import React from 'react'; import APIResponseErrorMessage from "../commons/errorhandling/api-response-error-message"; import { Button, Card, CardHeader, Col, Modal, ModalBody, ModalHeader, Row } from 'reactstrap'; import MedicationForm from "./components/medication-form"; import * as API_USERS from "./api/medication-api" import MedicationTable from "./components/medication-table"; import MedicationUpdateForm from "./components/medication-update-form"; import NavigationBar from "../navigation-bar"; import Redirect from "react-router-dom/Redirect"; class MedicationContainer extends React.Component { constructor(props) { super(props); this.medication = {id:null, name:null, side_effects:null, dosage:null}; this.id = null; this.toggleForm = this.toggleForm.bind(this); this.toggleForm2 = this.toggleForm2.bind(this); this.reload = this.reload.bind(this); this.reload1 = this.reload1.bind(this); this.reload_delete = this.reload_delete.bind(this); this.state = { selected: false, selected3 : false, collapseForm: false, tableData: [], isLoaded: false, errorStatus: 0, error: null }; } componentDidMount() { this.fetchMedications(); } fetchMedications() { return API_USERS.getMedications((result, status, err) => { if (result !== null && status === 200) { this.setState({ tableData: result, isLoaded: true }); } else { this.setState(({ errorStatus: status, error: err })); } }); } toggleForm() { this.setState({selected: !this.state.selected}); } toggleForm2() { this.setState({selected3: !this.state.selected3}); } reload() { this.setState({ isLoaded: false }); this.toggleForm(); this.fetchMedications(); } reload_delete() { this.setState({ isLoaded: false }); this.fetchMedications(); } reload1() { this.setState({ isLoaded: false }); this.toggleForm2(); this.fetchMedications(); } handleUpdate1 = (id) => {this.id = id; this.getById(this.id)}; getById(id) { return API_USERS.getMedicationById(id,(result, status, err) => { if (result !== null && status === 200) { this.medication.id = result.id; this.medication.name = result.name; this.medication.side_effects = result.side_effects; this.medication.dosage = result.dosage; } else { this.setState(({ errorStatus: status, error: err })); } }); } render() { if(localStorage.role === "doctor") { return ( <div> <NavigationBar/> <CardHeader> <strong> Medication Management </strong> </CardHeader> <Card> <br/> <Row> <Col sm={{size: '8', offset: 1}}> <Button color="primary" onClick={this.toggleForm}>Add Medication </Button> </Col> </Row> <br/> <Row> <Col sm={{size: '8', offset: 1}}> {this.state.isLoaded && <MedicationTable tableData = {this.state.tableData} reloadHandler = {this.reload_delete} id = {this.handleUpdate1} toggle2 = {this.toggleForm2}/>} {this.state.errorStatus > 0 && <APIResponseErrorMessage errorStatus={this.state.errorStatus} error={this.state.error} /> } </Col> </Row> </Card> <Modal isOpen={this.state.selected} toggle={this.toggleForm} className={this.props.className} size="lg"> <ModalHeader toggle={this.toggleForm}> Add Medication: </ModalHeader> <ModalBody> <MedicationForm reloadHandler={this.reload}/> </ModalBody> </Modal> <Modal isOpen={this.state.selected3} toggle={this.toggleForm1} className={this.props.className} size="lg"> <ModalHeader toggle={this.toggleForm2}> Update Medication: </ModalHeader> <ModalBody> <MedicationUpdateForm reloadHandler = {this.reload1} medication = {this.medication} toggle2 = {this.toggleForm2}/> </ModalBody> </Modal> </div> ) } else{ localStorage.removeItem("role"); return(<Redirect to={{ pathname:'/'} }/>) } } } export default MedicationContainer; <file_sep>/backend/src/main/java/ro/tuc/ds2020/dtos/ActivityDTO.java package ro.tuc.ds2020.dtos; import org.springframework.hateoas.RepresentationModel; import java.util.Objects; import java.util.UUID; public class ActivityDTO extends RepresentationModel<ActivityDTO> { private UUID id; private UUID id_patient; private String activity; private long start_date; private long end_date; public ActivityDTO() { } public ActivityDTO(UUID id, UUID id_patient, String activity, long start_date, long end_date) { this.id = id; this.id_patient = id_patient; this.activity = activity; this.start_date = start_date; this.end_date = end_date; } public UUID getId() { return id; } public ActivityDTO setId(UUID id) { this.id = id; return this; } public String getActivity() { return activity; } public ActivityDTO setActivity(String activity) { this.activity = activity; return this; } public long getStart_date() { return start_date; } public ActivityDTO setStart_date(long start_date) { this.start_date = start_date; return this; } public long getEnd_date() { return end_date; } public ActivityDTO setEnd_date(long end_date) { this.end_date = end_date; return this; } public UUID getId_patient() { return id_patient; } public ActivityDTO setId_patient(UUID id_patient) { this.id_patient = id_patient; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; ActivityDTO that = (ActivityDTO) o; return start_date == that.start_date && end_date == that.end_date && Objects.equals(id, that.id) && Objects.equals(activity, that.activity); } @Override public int hashCode() { return Objects.hash(super.hashCode(), id, activity, start_date, end_date); } } <file_sep>/frontend/src/home/home.js import React from 'react'; import BackgroundImg from '../commons/images/future-medicine.jpg'; import {Button, Container, Jumbotron, Modal, ModalBody, ModalHeader} from 'reactstrap'; import NavigationBar from "../navigation-bar"; import MedPlansForm from "./doctor-add-plans-form"; import Redirect from "react-router-dom/Redirect"; const backgroundStyle = { backgroundPosition: 'center', backgroundSize: 'cover', backgroundRepeat: 'no-repeat', width: "100%", height: "1920px", backgroundImage: `url(${BackgroundImg})` }; class Home extends React.Component { constructor(props) { super(props); this.toggleForm = this.toggleForm.bind(this); this.reload = this.reload.bind(this); this.state = { selected: false, collapseForm: false, tableData: [], isLoaded: false, errorStatus: 0, error: null }; } toggleForm() { console.log(localStorage.role); this.setState({selected: !this.state.selected}); } reload() { this.setState({ isLoaded: false }); this.toggleForm(); //this.fetchCaregivers(); } logout(){ //window.location.href = "https://alin-pop-frontend-1.herokuapp.com"; localStorage.removeItem("role"); window.location.href = "http://localhost:3000/"; } render() { if(localStorage.role === "doctor") { return ( <div> <NavigationBar/> <Jumbotron fluid style={backgroundStyle}> <Container fluid> <p className="lead"> <Button color="danger" onClick={this.logout}>Logout </Button>{' '} <Button color="primary" onClick={this.toggleForm}>Add medication plan </Button> </p> </Container> </Jumbotron> <Modal isOpen={this.state.selected} toggle={this.toggleForm} className={this.props.className} size="lg"> <ModalHeader toggle={this.toggleForm}> Patients: </ModalHeader> <ModalBody> <MedPlansForm toggle={ this.toggleForm} reloadHandler = {this.reload}/> </ModalBody> </Modal> </div> ) } else{ localStorage.removeItem("role"); return(<Redirect to={{ pathname:'/'} }/>) } }; } export default Home <file_sep>/backend/src/main/java/ro/tuc/ds2020/dtos/MedicationPlanDTO.java package ro.tuc.ds2020.dtos; import org.springframework.hateoas.RepresentationModel; import java.util.Objects; import java.util.UUID; public class MedicationPlanDTO extends RepresentationModel<MedicationDTO> { private UUID id_med_plan; private String intervals; private String period; public MedicationPlanDTO() { } public MedicationPlanDTO(UUID id, String intervals, String period) { this.id_med_plan = id; this.intervals = intervals; this.period = period; } public UUID getId() { return id_med_plan; } public void setId(UUID id) { this.id_med_plan = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MedicationPlanDTO that = (MedicationPlanDTO) o; return Objects.equals(id_med_plan, that.id_med_plan) && Objects.equals(intervals, that.intervals) && Objects.equals(period, that.period); } @Override public int hashCode() { return Objects.hash(super.hashCode(), id_med_plan, intervals, period); } public String getIntervals() { return intervals; } public void setIntervals(String intervals) { this.intervals = intervals; } public String getPeriod() { return period; } public void setPeriod(String period) { this.period = period; } }<file_sep>/backend/src/main/java/ro/tuc/ds2020/dtos/ActivityDetailsDTO.java package ro.tuc.ds2020.dtos; import ro.tuc.ds2020.dtos.validators.annotation.AgeLimit; import javax.validation.constraints.NotNull; import java.util.Objects; import java.util.UUID; public class ActivityDetailsDTO { private UUID id; @NotNull private UUID id_patient; @NotNull private String activity; @NotNull private long start_date; @NotNull private long end_date; public ActivityDetailsDTO() { } public ActivityDetailsDTO(UUID id_patient, String activity, long start_date, long end_date) { this.id_patient = id_patient; this.activity = activity; this.start_date = start_date; this.end_date = end_date; } public ActivityDetailsDTO(UUID id, UUID id_patient, String activity, long start_date, long end_date) { this.id = id; this.id_patient = id_patient; this.activity = activity; this.start_date = start_date; this.end_date = end_date; } public UUID getId() { return id; } public ActivityDetailsDTO setId(UUID id) { this.id = id; return this; } public String getActivity() { return activity; } public ActivityDetailsDTO setActivity(String activity) { this.activity = activity; return this; } public long getStart_date() { return start_date; } public ActivityDetailsDTO setStart_date(long start_date) { this.start_date = start_date; return this; } public UUID getId_patient() { return id_patient; } public ActivityDetailsDTO setId_patient(UUID id_patient) { this.id_patient = id_patient; return this; } public long getEnd_date() { return end_date; } public ActivityDetailsDTO setEnd_date(long end_date) { this.end_date = end_date; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ActivityDetailsDTO that = (ActivityDetailsDTO) o; return start_date == that.start_date && end_date == that.end_date && Objects.equals(id, that.id) && Objects.equals(activity, that.activity); } @Override public int hashCode() { return Objects.hash(id, activity, start_date, end_date); } } <file_sep>/backend/src/main/java/ro/tuc/ds2020/services/CaregiverService.java package ro.tuc.ds2020.services; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ro.tuc.ds2020.controllers.handlers.exceptions.model.ResourceNotFoundException; import ro.tuc.ds2020.dtos.*; import ro.tuc.ds2020.dtos.builders.CaregiverBuilder; import ro.tuc.ds2020.dtos.builders.PatientBuilder; import ro.tuc.ds2020.entities.Caregiver; import ro.tuc.ds2020.entities.Patient; import ro.tuc.ds2020.repositories.CaregiverRepository; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; @Service public class CaregiverService { private static final Logger LOGGER = LoggerFactory.getLogger(DoctorService.class); private final CaregiverRepository caregiverRepository; @Autowired public CaregiverService(CaregiverRepository caregiverRepository) { this.caregiverRepository = caregiverRepository; } public List<CaregiverDTO> findCaregivers() { List<Caregiver> caregiverList = caregiverRepository.findAll(); return caregiverList.stream() .map(CaregiverBuilder::toCaregiverDTO) .collect(Collectors.toList()); } public CaregiverDetailsDTO findCaregiverById(UUID id) { Optional<Caregiver> prosumerOptional = caregiverRepository.findById(id); if (!prosumerOptional.isPresent()) { LOGGER.error("Caregiver with id {} was not found in db", id); throw new ResourceNotFoundException(Caregiver.class.getSimpleName() + " with id: " + id); } return CaregiverBuilder.toCaregiverDetailsDTO(prosumerOptional.get()); } public UUID insert(CaregiverDetailsDTO caregiverDTO) { Caregiver caregiver = CaregiverBuilder.toEntity(caregiverDTO); caregiver = caregiverRepository.save(caregiver); LOGGER.debug("Caregiver with id {} was inserted in db",caregiver.getId()); return caregiver.getId(); } public UUID update(CaregiverDetailsDTO caregiverDTO) { caregiverRepository.update(caregiverDTO.getId(), caregiverDTO.getName(), caregiverDTO.getAddress(), caregiverDTO.getBirth_date(), caregiverDTO.getGender()); LOGGER.debug("Caregiver with id {} was updated from db", caregiverDTO.getId()); return caregiverDTO.getId(); } public UUID delete(CaregiverDetailsDTO caregiverDTO) { caregiverRepository.deleteById(caregiverDTO.getId()); LOGGER.debug("Caregiver plan with id {} was deleted from db", caregiverDTO.getId()); return caregiverDTO.getId(); } public List<PatientDTO> findPatientsC(UUID id) { List<Patient> patientList = caregiverRepository.findCaregiverPatients(id); return patientList.stream() .map(PatientBuilder::toPatientDTO) .collect(Collectors.toList()); } } <file_sep>/frontend/src/caregiver/caregiver-container.js import React from 'react'; import APIResponseErrorMessage from "../commons/errorhandling/api-response-error-message"; import { Button, Card, CardHeader, Col, Modal, ModalBody, ModalHeader, Row } from 'reactstrap'; import CaregiverForm from "./components/caregiver-form"; import * as API_USERS from "./api/caregiver-api" import CaregiverTable from "./components/caregiver-table"; import CaregiverUpdateForm from "./components/caregiver-update-form"; import CaregiverPatientsForm from "./components/caregiver-patients-form"; import NavigationBar from "../navigation-bar"; import Redirect from "react-router-dom/Redirect"; class CaregiverContainer extends React.Component { constructor(props) { super(props); this.caregiver = {id:null, address:null, birth_date:null, gender:null, name:null}; this.id = null; this.toggleForm = this.toggleForm.bind(this); this.toggleForm1 = this.toggleForm1.bind(this); this.toggleForm2 = this.toggleForm2.bind(this); this.reload = this.reload.bind(this); this.reload1 = this.reload1.bind(this); this.reload_delete = this.reload_delete.bind(this); this.state = { selected: false, selected2: false, selected3: false, collapseForm: false, tableData: [], isLoaded: false, errorStatus: 0, error: null }; } componentDidMount() { this.fetchCaregivers(); } fetchCaregivers() { return API_USERS.getCaregivers((result, status, err) => { if (result !== null && status === 200) { this.setState({ tableData: result, isLoaded: true }); } else { this.setState(({ errorStatus: status, error: err })); } }); } toggleForm() { this.setState({selected: !this.state.selected}); } toggleForm1() { this.setState({selected2: !this.state.selected2}); } toggleForm2() { this.setState({selected3: !this.state.selected3}); } reload() { this.setState({ isLoaded: false }); this.toggleForm(); this.fetchCaregivers(); } reload1() { this.setState({ isLoaded: false }); this.toggleForm1(); this.fetchCaregivers(); } reload_delete(){ this.setState({ isLoaded: false }); this.fetchCaregivers(); } handleUpdate1 = (id) => {this.id = id; console.log(this.id); this.getById(this.id)}; getById(id) { return API_USERS.getCaregiverById(id,(result, status, err) => { if (result !== null && status === 200) { this.caregiver.id = result.id; this.caregiver.address = result.address; this.caregiver.birth_date = result.birth_date; this.caregiver.gender = result.gender; this.caregiver.name = result.name; console.log(this.caregiver) } else { this.setState(({ errorStatus: status, error: err })); } }); } render() { if(localStorage.role === "doctor") { return ( <div> <NavigationBar/> <CardHeader> <strong> Caregiver Management </strong> </CardHeader> <Card> <br/> <Row> <Col sm={{size: '8', offset: 1}}> <Button color="primary" onClick={this.toggleForm}>Add Caregiver </Button>{' '} </Col> </Row> <br/> <Row> <Col sm={{size: '8', offset: 1}}> {this.state.isLoaded && <CaregiverTable tableData = {this.state.tableData} reloadHandler = {this.reload_delete} id = {this.handleUpdate1} toggle1 = {this.toggleForm1}/>} {this.state.errorStatus > 0 && <APIResponseErrorMessage errorStatus={this.state.errorStatus} error={this.state.error} /> } </Col> </Row> </Card> <Modal isOpen={this.state.selected} toggle={this.toggleForm} className={this.props.className} size="lg"> <ModalHeader toggle={this.toggleForm}> Add Caregiver: </ModalHeader> <ModalBody> <CaregiverForm reloadHandler={this.reload}/> </ModalBody> </Modal> <Modal isOpen={this.state.selected2} toggle={this.toggleForm1} className={this.props.className} size="lg"> <ModalHeader toggle={this.toggleForm1}> Update Caregiver: </ModalHeader> <ModalBody> <CaregiverUpdateForm reloadHandler = {this.reload1} caregiver = {this.caregiver} toggle1 = {this.toggleForm1}/> </ModalBody> </Modal> <Modal isOpen={this.state.selected3} toggle={this.toggleForm2} className={this.props.className} size="lg"> <ModalHeader toggle={this.toggleForm2}> Patients: </ModalHeader> <ModalBody> <CaregiverPatientsForm toggle2 ={ this.toggleForm2}/> </ModalBody> </Modal> </div> ) } else{ localStorage.removeItem("role"); return(<Redirect to={{ pathname:'/'} }/>) } } } export default CaregiverContainer; <file_sep>/backend/README.md # DS2020_30641_Pop_Alin_1_BackEnd <file_sep>/backend/src/main/java/ro/tuc/ds2020/repositories/PatientRepository.java package ro.tuc.ds2020.repositories; import org.hibernate.annotations.SQLInsert; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import ro.tuc.ds2020.entities.MedicationPlan; import ro.tuc.ds2020.entities.Patient; import javax.transaction.Transactional; import java.util.Date; import java.util.List; import java.util.UUID; public interface PatientRepository extends JpaRepository<Patient, UUID> { @Transactional @Modifying @Query("UPDATE Patient p set p.name = :name, p.address = :address, p.birth_date = :birth_date, p.gender = :gender where p.id_patient = :id") void update(@Param("id") UUID id, @Param("name") String name, @Param("address") String address, @Param("birth_date") Date birth_date, @Param("gender") String gender); @Transactional @Modifying @Query(value = "insert into Patient (id_patient, address, birth_date, gender, name, caregiver_id_caregiver)" + " VALUES (:id_patient, :address, :birth_date, :gender, :name, :caregiver_id_caregiver)", nativeQuery = true) void myInsert (@Param("id_patient") UUID id_patinet, @Param("address") String address, @Param("birth_date") Date birth_date, @Param("gender") String gender, @Param("name") String name, @Param("caregiver_id_caregiver") UUID caregiver_id_caregiver); @Transactional @Modifying @Query(value ="UPDATE Patient p set p.caregiver_id_caregiver = :caregiver_id_caregiver where p.id_patient = :id", nativeQuery = true) void update1(@Param("id") UUID id, @Param("caregiver_id_caregiver") UUID caregiver_id_caregiver); @Transactional @Modifying @Query("Select p from MedicationPlan p join fetch p.patient c where c.id = :id") List<MedicationPlan> findPatientsMedPlans (@Param("id") UUID id); } <file_sep>/producer/producer/src/main/java/com/example/producer/PracticalTipSender.java package com.example.producer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.io.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Date; import java.util.UUID; @Service public class PracticalTipSender { private static final Logger log = LoggerFactory.getLogger(PracticalTipSender.class); private final RabbitTemplate rabbitTemplate; ArrayList<PracticalTipMessage> fisier = initFisier(); int i=0; public ArrayList<PracticalTipMessage> initFisier() throws IOException, ParseException { ArrayList<PracticalTipMessage> fisier1 = new ArrayList<>(); File file = new File("E:\\an4\\sem1\\SD\\Tema2\\activity.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String st; String[] tokens ; SimpleDateFormat formatter6 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); while ((st = br.readLine()) != null) { tokens = st.split("\t\t"); Date dateTime = formatter6.parse(tokens[0]); long mili = dateTime.getTime(); Date dateTime1 = formatter6.parse(tokens[1]); long mili1 = dateTime1.getTime(); UUID uid = UUID.fromString("813db233-2d3a-49f2-b5c3-d1cab10d96d9"); fisier1.add(new PracticalTipMessage(uid,mili,mili1,tokens[2])); } return fisier1; } public PracticalTipSender(RabbitTemplate rabbitTemplate) throws IOException, ParseException { this.rabbitTemplate = rabbitTemplate; } @Scheduled(fixedDelay = 1500L) public void sendPracticalTip() throws IOException { rabbitTemplate.convertAndSend(ProducerApplication.EXCHANGE_NAME, ProducerApplication.ROUTING_KEY, this.fisier.get(i)); if(i < this.fisier.size() - 1) i++; else return ; log.info("Practical tip sent"); } } <file_sep>/backend/src/main/java/ro/tuc/ds2020/dtos/MedicationDetailsDTO.java package ro.tuc.ds2020.dtos; import ro.tuc.ds2020.dtos.validators.annotation.AgeLimit; import javax.validation.constraints.NotNull; import java.util.Objects; import java.util.UUID; public class MedicationDetailsDTO { private UUID id_medication; @NotNull private String name; @NotNull private String side_effects; @NotNull private String dosage; public MedicationDetailsDTO() { } public MedicationDetailsDTO( String name, String side_effects, String dosage) { this.name = name; this.side_effects = side_effects; this.dosage = dosage; } public MedicationDetailsDTO(UUID id, String name, String side_effects, String dosage) { this.id_medication = id; this.name = name; this.side_effects = side_effects; this.dosage = dosage; } public UUID getId() { return id_medication; } public void setId(UUID id) { this.id_medication = id; } public String getName() { return name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MedicationDetailsDTO that = (MedicationDetailsDTO) o; return Objects.equals(id_medication, that.id_medication) && Objects.equals(name, that.name) && Objects.equals(side_effects, that.side_effects) && Objects.equals(dosage, that.dosage); } @Override public int hashCode() { return Objects.hash(id_medication, name, side_effects, dosage); } public String getSide_effects() { return side_effects; } public void setSide_effects(String sideEffects) { this.side_effects = sideEffects; } public String getDosage() { return dosage; } public void setDosage(String dosage) { this.dosage = dosage; } public void setName(String name) { this.name = name; } } <file_sep>/backend/src/main/java/ro/tuc/ds2020/controllers/ActivityController.java package ro.tuc.ds2020.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import ro.tuc.ds2020.dtos.ActivityDTO; import ro.tuc.ds2020.dtos.ActivityDetailsDTO; import ro.tuc.ds2020.dtos.DoctorDTO; import ro.tuc.ds2020.dtos.DoctorDetailsDTO; import ro.tuc.ds2020.services.ActivityService; import ro.tuc.ds2020.services.DoctorService; import javax.validation.Valid; import java.util.List; import java.util.UUID; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; @RestController @CrossOrigin @RequestMapping(value = "/activity") public class ActivityController { private final ActivityService activityService; @Autowired public ActivityController(ActivityService activityService) { this.activityService = activityService; } @GetMapping() public ResponseEntity<List<ActivityDTO>> getActivityes() { List<ActivityDTO> dtos = activityService.findActivityes(); for (ActivityDTO dto : dtos) { Link personLink = linkTo(methodOn(ActivityController.class) .getActivity(dto.getId())).withRel("activityDetails"); dto.add(personLink); } return new ResponseEntity<>(dtos, HttpStatus.OK); } @PostMapping() public ResponseEntity<UUID> insertProsumer(@Valid @RequestBody ActivityDetailsDTO activityDTO) { UUID activityID = activityService.insert(activityDTO); return new ResponseEntity<>(activityID, HttpStatus.CREATED); } @GetMapping(value = "/{id}") public ResponseEntity<ActivityDetailsDTO> getActivity(@PathVariable("id") UUID activityId) { ActivityDetailsDTO dto = activityService.findActivityById(activityId); return new ResponseEntity<>(dto, HttpStatus.OK); } @DeleteMapping("/{id}") public ResponseEntity<UUID> deleteActivity(@PathVariable("id") UUID activityId) { ActivityDetailsDTO dto2 = activityService.findActivityById(activityId); UUID activityID = activityService.delete(dto2); return new ResponseEntity<>(activityID, HttpStatus.OK); } //TODO: UPDATE per resource } <file_sep>/backend/src/main/java/ro/tuc/ds2020/services/ActivityService.java package ro.tuc.ds2020.services; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ro.tuc.ds2020.controllers.handlers.exceptions.model.ResourceNotFoundException; import ro.tuc.ds2020.dtos.*; import ro.tuc.ds2020.dtos.builders.ActivityBuilder; import ro.tuc.ds2020.dtos.builders.DoctorBuilder; import ro.tuc.ds2020.entities.Activity; import ro.tuc.ds2020.entities.Doctor; import ro.tuc.ds2020.repositories.ActivityRepository; import ro.tuc.ds2020.repositories.DoctorRepository; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; @Service public class ActivityService { private static final Logger LOGGER = LoggerFactory.getLogger(ActivityService.class); private final ActivityRepository activityRepository; @Autowired public ActivityService(ActivityRepository activityRepository) { this.activityRepository = activityRepository; } public List<ActivityDTO> findActivityes() { List<Activity> activityList = activityRepository.findAll(); return activityList.stream() .map(ActivityBuilder::toActivityDTO) .collect(Collectors.toList()); } public ActivityDetailsDTO findActivityById(UUID id) { Optional<Activity> prosumerOptional = activityRepository.findById(id); if (!prosumerOptional.isPresent()) { LOGGER.error("Activity with id {} was not found in db", id); throw new ResourceNotFoundException(Activity.class.getSimpleName() + " with id: " + id); } return ActivityBuilder.toActivityDetailsDTO(prosumerOptional.get()); } public UUID insert(ActivityDetailsDTO activityDTO) { Activity activity = ActivityBuilder.toEntity(activityDTO); activity = activityRepository.save(activity); LOGGER.debug("Activity with id {} was inserted in db", activity.getId()); return activity.getId(); } public UUID delete(ActivityDetailsDTO activityDTO) { activityRepository.deleteById(activityDTO.getId()); LOGGER.debug("Doctor plan with id {} was deleted from db", activityDTO.getId()); return activityDTO.getId(); } } <file_sep>/frontend/src/medication/components/medication-table.js import React from "react"; import Table from "../../commons/tables/table"; import * as API_USERS from "../../medication/api/medication-api"; class MedicationTable extends React.Component { constructor(props) { super(props); this.reloadHandler = this.props.reloadHandler; this.handleDelete = this.handleDelete.bind(this); this.handleUpdate = this.handleUpdate.bind(this); this.toggle2 = this.props.toggle2; this.state = { tableData: this.props.tableData }; } columns = [ { Header: 'Id', accessor: 'id', }, { Header: 'Name', accessor: 'name', }, { Header: 'Side effects', accessor: 'side_effects', }, { Header: 'Dosage', accessor: 'dosage', }, { Header: 'Delete', accessor: 'id', Cell:cell=>(<button class="btn btn-danger" onClick={()=>{this.handleDelete(cell.value)}} >Delete</button>) }, { Header: 'Update', accessor: 'id', Cell:cell=>(<button class="btn btn-primary" onClick={()=>{this.handleUpdate(cell.value)}} >Update</button>) }, ]; filters = [ { accessor: 'name', } ]; handleDelete(id) { if (window.confirm('Are you sure?')) { return API_USERS.deleteMedication(id, (result, status, error) => { if (result !== null && (status === 200 || status === 201)) { console.log("Successfully deleted medication with id: " + result); this.reloadHandler(); } else { this.setState(({ errorStatus: status, error: error })); } }); } } handleUpdate(id){ this.props.id(id); this.toggle2(); return id; } render() { return ( <Table data={this.state.tableData} columns={this.columns} search={this.filters} pageSize={5} onChange = {this.handleUpdate} /> ) } } export default MedicationTable;<file_sep>/backend/src/main/java/ro/tuc/ds2020/entities/Patient.java package ro.tuc.ds2020.entities; import org.hibernate.annotations.*; import javax.persistence.*; import javax.persistence.Entity; import java.io.Serializable; import java.util.Date; import java.util.UUID; @Entity public class Patient implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2") @Type(type = "uuid-binary") private UUID id_patient; @Column(name = "name", nullable = false) private String name; @Column(name = "address", nullable = false) private String address; @Column(name = "birth_date", nullable = false) private Date birth_date; @Column(name = "gender", nullable = false) private String gender; @Fetch(FetchMode.JOIN) @ManyToOne(fetch = FetchType.LAZY) private Caregiver caregiver; public Caregiver getCaregiver() { return caregiver; } public Patient setCaregiver(Caregiver caregiver) { this.caregiver = caregiver; return this; } public Patient() { } public Patient(String name, String address, Date birth_date, String gender) { this.name = name; this.address = address; this.birth_date = birth_date; this.gender = gender; } public Date getBirth_date() { return birth_date; } public void setBirth_date(Date birth_date) { this.birth_date = birth_date; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public UUID getId() { return id_patient; } public void setId(UUID id) { this.id_patient = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } <file_sep>/frontend/src/home/homeCaregiver.js import React from 'react'; import BackgroundImg from '../commons/images/future-medicine.jpg'; import SockJsClient from 'react-stomp'; import {Button, Container, Jumbotron, Modal, ModalBody, ModalHeader} from 'reactstrap'; import CaregiverPatientsForm from "../caregiver/components/caregiver-patients-form"; import Redirect from "react-router-dom/Redirect"; import { Alert } from "react-bs-notifier"; const backgroundStyle = { backgroundPosition: 'center', backgroundSize: 'cover', backgroundRepeat: 'no-repeat', width: "100%", height: "1920px", backgroundImage: `url(${BackgroundImg})` }; class HomeCaregiver extends React.Component { constructor(props) { super(props); this.i = 0; this.toggleForm2 = this.toggleForm2.bind(this); this.toggleForm3 = this.toggleForm3.bind(this); this.NotifierGenerator = this.NotifierGenerator.bind(this); this.state = { selected3: false, selected4: false, visible : false, collapseForm: false, tableData: [], isLoaded: false, errorStatus: 0, error: null }; } NotifierGenerator() { if(this.state.selected4) { if (localStorage.activ === "Sleeping") { localStorage.removeItem("activ"); if (this.state.visible){ return ( <Alert type="warning" headline="Sleeping"> Sleep period longer than 7 hours for patient with id 813db233-2d3a-49f2-b5c3-d1cab10d96d9 </Alert> ); } else { this.toggleForm3(); return null; } } else if(localStorage.activ === "Leaving") { localStorage.removeItem("activ"); if (this.state.visible) { return ( <Alert type="warning" headline="Leaving"> The leaving activity (outdoor) is longer than 5 hours for patient with id 813db233-2d3a-49f2-b5c3-d1cab10d96d9 </Alert> ); } else { this.toggleForm3(); return null; } } else if(localStorage.activ === "Grooming") { localStorage.removeItem("activ"); if (this.state.visible) { return ( <Alert type="warning" headline="Bathroom"> Period spent in bathroom is longer than 30 minutes for patient with id 813db233-2d3a-49f2-b5c3-d1cab10d96d9 </Alert> ); } else { this.toggleForm3(); return null; } } else { this.toggleForm3(); return null; } } else return null; } toggleForm2() { this.setState({selected3: !this.state.selected3}); } toggleForm3() { this.setState({visible:true},()=>{ window.setTimeout(()=>{ this.setState({visible:false}) },5000) }); this.setState({selected4: !this.state.selected4}); } logout(){ //window.location.href = "https://alin-pop-frontend-1.herokuapp.com"; localStorage.removeItem("role"); window.location.href = "http://localhost:3000/"; } render() { if(localStorage.role === "caregiver") { return ( <div> <SockJsClient url='http://localhost:8080/websocket/tracker/' topics={['/topic/tracker']} onConnect={() => { console.log("connected"); }} onDisconnect={() => { console.log("Disconnected"); }} onMessage={(msg) => { localStorage.setItem("activ", msg.message); this.toggleForm3(); console.log(msg.message); }} ref={(client) => { this.clientRef = client }}/> <Jumbotron fluid style={backgroundStyle}> <Container fluid> <p className="lead"> <Button color = "dark" onClick={this.toggleForm2}>View Patients </Button>{' '} <Button color="danger" onClick={this.logout}>Logout </Button>{' '} </p> <this.NotifierGenerator/> </Container> </Jumbotron> <Modal isOpen={this.state.selected3} toggle2={this.toggleForm2} className={this.props.className} size="lg"> <ModalHeader toggle2={this.toggleForm2}> Patients: </ModalHeader> <ModalBody> <CaregiverPatientsForm toggle2 ={ this.toggleForm2}/> </ModalBody> </Modal> </div> ) } else{ localStorage.removeItem("role"); return(<Redirect to={{ pathname:'/'} }/>) } }; } export default HomeCaregiver <file_sep>/frontend/src/home/homePat.js import React from 'react'; import BackgroundImg from '../commons/images/future-medicine.jpg'; import {Button, Container, Jumbotron, Modal, ModalBody, ModalHeader} from 'reactstrap'; import PacientMedsForm from "../patient/components/patients-med-plans-form"; import Redirect from "react-router-dom/Redirect"; const backgroundStyle = { backgroundPosition: 'center', backgroundSize: 'cover', backgroundRepeat: 'no-repeat', width: "100%", height: "1920px", backgroundImage: `url(${BackgroundImg})` }; class HomePat extends React.Component { constructor(props) { super(props); this.toggleForm2 = this.toggleForm2.bind(this); this.state = { selected3 : false, collapseForm: false, tableData: [], isLoaded: false, errorStatus: 0, error: null }; } logout(){ //window.location.href = "https://alin-pop-frontend-1.herokuapp.com"; localStorage.removeItem("role"); window.location.href = "http://localhost:3000/"; } toggleForm2() { this.setState({selected3: !this.state.selected3}); } render() { if(localStorage.role === "patient") { return ( <div> <Jumbotron fluid style={backgroundStyle}> <Container fluid> <p className="lead"> <Button color="dark" onClick={this.toggleForm2}>View Med Plans </Button>{' '} <Button color="danger" onClick={this.logout}>Logout </Button> </p> </Container> </Jumbotron> <Modal isOpen={this.state.selected3} toggle2={this.toggleForm2} className={this.props.className} size="lg"> <ModalHeader toggle2={this.toggleForm2}> Medication Plans: </ModalHeader> <ModalBody> <PacientMedsForm toggle2={this.toggleForm2}/> </ModalBody> </Modal> </div> ) } else{ localStorage.removeItem("role"); return(<Redirect to={{ pathname:'/'} }/>) } }; } export default HomePat <file_sep>/frontend/src/patient/api/patient-api.js import {HOST} from '../../commons/hosts'; import RestApiClient from "../../commons/api/rest-client"; const endpoint = { patient: '/patient/' }; function getPatients(callback) { let request = new Request(HOST.backend_api + endpoint.patient, { method: 'GET', }); console.log(request.url); RestApiClient.performRequest(request, callback); } function getPatientById(params, callback){ let request = new Request(HOST.backend_api + endpoint.patient + params, { method: 'GET' }); console.log(request.url); RestApiClient.performRequest(request, callback); } function getPatientsMeds(id, callback) { let request = new Request(HOST.backend_api + endpoint.patient + "find_med_plan/" + id, { method: 'GET', }); console.log(request.url + " aici"); RestApiClient.performRequest(request, callback); } function postPatient(user, id, callback){ let request = new Request(HOST.backend_api + endpoint.patient + "my_insert/" + id , { method: 'POST', headers : { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(user) }); console.log("URL: " + request.url); RestApiClient.performRequest(request, callback); } function deletePatient(id, callback){ let request = new Request(HOST.backend_api + endpoint.patient + id , { method: 'DELETE', headers : { 'Accept': 'application/json', 'Content-Type': 'application/json', } }); console.log("URL: " + request.url); console.log(callback); RestApiClient.performRequest(request, callback); } function updatePatient(user, callback){ let request = new Request(HOST.backend_api + endpoint.patient , { method: 'PUT', headers : { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(user) }); console.log("URL: " + request.url); RestApiClient.performRequest(request, callback); } export { getPatients, getPatientById, postPatient, deletePatient, updatePatient, getPatientsMeds }; <file_sep>/backend/src/main/java/ro/tuc/ds2020/entities/MedicationPlan.java package ro.tuc.ds2020.entities; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type; import javax.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Entity @Table (name="medication_plan") public class MedicationPlan implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2") @Type(type = "uuid-binary") private UUID id_med_plan; @Column(name = "intervals", nullable = false) private String intervals; @Column(name = "period", nullable = false) private String period; @ManyToMany(mappedBy = "medication_plans") private List<Medication> medications = new ArrayList<>(); public Patient getPatient() { return patient; } public MedicationPlan setPatient(Patient patient) { this.patient = patient; return this; } public List<Medication> getMedications() { return medications; } public MedicationPlan setMedications(List<Medication> medications) { this.medications = medications; return this; } @Fetch(FetchMode.JOIN) @ManyToOne(fetch = FetchType.LAZY) private Patient patient; public MedicationPlan() { } public MedicationPlan(String intervals, String period) { this.intervals = intervals; this.period = period; } public String getIntervals() { return intervals; } public void setIntervals(String intervals) { this.intervals = intervals; } public String getPeriod() { return period; } public void setPeriod(String period) { this.period = period; } public UUID getId() { return id_med_plan; } public void setId(UUID id) { this.id_med_plan = id; } } <file_sep>/backend/src/main/java/ro/tuc/ds2020/dtos/PatientDTO.java package ro.tuc.ds2020.dtos; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.springframework.hateoas.RepresentationModel; import ro.tuc.ds2020.entities.Caregiver; import javax.persistence.FetchType; import javax.persistence.ManyToOne; import java.util.Date; import java.util.Objects; import java.util.UUID; public class PatientDTO extends RepresentationModel<PatientDTO> { private UUID id_patient; private String name; private String address; private Date birth_date; @Fetch(FetchMode.JOIN) @ManyToOne(fetch = FetchType.EAGER) private Caregiver caregiver; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } private String gender; public PatientDTO() { } public PatientDTO(UUID id,String address, String name, Date birth_date, String gender) { this.id_patient = id; this.address = address; this.name = name; this.birth_date = birth_date; this.gender = gender; } public UUID getId() { return id_patient; } public void setId(UUID id) { this.id_patient = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirth_date() { return birth_date; } public void setBirth_date(Date birth_date) { this.birth_date = birth_date; } public String getGender() { return gender; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; PatientDTO that = (PatientDTO) o; return Objects.equals(id_patient, that.id_patient) && Objects.equals(name, that.name) && Objects.equals(birth_date, that.birth_date) && Objects.equals(gender, that.gender); } @Override public int hashCode() { return Objects.hash(super.hashCode(), id_patient, name, birth_date, gender); } public void setGender(String gender) { this.gender = gender; } }
6dd4d9fdc4fc84d709248384049d17b864d6cc19
[ "JavaScript", "Java", "Markdown" ]
29
Java
numerge1998/MedicalOfficeWeb
b99e4ee7ee63d39d11cf614778572fae021a869a
afa4c12eacb8129f0b3de503b4ce923ca03facda
refs/heads/master
<repo_name>amitnteny/mongo-project<file_sep>/src/main/java/com/practice/mongoProject/domain/AnimalRequestObject.java package com.practice.mongoProject.domain; public class AnimalRequestObject { private AnimalType animalType; public AnimalType getAnimalType() { return animalType; } public void setAnimalType(AnimalType animalType) { this.animalType = animalType; } } <file_sep>/src/main/java/com/practice/mongoProject/service/DataService.java package com.practice.mongoProject.service; import com.practice.mongoProject.domain.Data; import com.practice.mongoProject.repository.DataRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class DataService { private DataRepository repository; @Autowired public DataService(DataRepository repository) { this.repository = repository; } public List<Data> getAllData() { return repository.findAll(); } public Data getData(String dataId) { return repository.findOne(dataId); } public void saveData(Data data) { repository.save(data); } } <file_sep>/src/main/java/com/practice/mongoProject/practice/MaximumRepeatingCharacters.java package com.practice.mongoProject.practice; import java.util.Scanner; public class MaximumRepeatingCharacters { public static void main(String[] args) { Scanner s = new Scanner(System.in); String str; while (true){ str = s.next(); if ("0".equals(str) || "".equals(str)){ break; } if (str.length() == 1) { System.out.println(str); break; } char ch = str.charAt(0); int maxLength = 1; int initIndex = 0; for (int i=1; i<str.length(); i++) { if (str.charAt(i) != str.charAt(i-1)) { int chLength = i - initIndex; initIndex = i; if (chLength > maxLength) { maxLength = chLength; } } } } } } <file_sep>/src/main/java/com/practice/mongoProject/practice/A.java package com.practice.mongoProject.practice; import java.util.*; public class A { public int a = 1; public int getA() { return a; } public void setA(int a) { this.a = a; } } class B extends A { public int a = 2; @Override public int getA() { return a; } @Override public void setA(int a) { this.a = a; } } class C { public static void main(String[] args) { /*A a = new B(); System.out.println(((B)a).a); char c = (char) 97; System.out.println(c);*/ List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); Map<Integer, List<String>> map = new HashMap<>(); map.put(1, list); List<String> list1 = map.get(1); list1.add("d"); System.out.println(map.get(1).size()); } }<file_sep>/src/main/java/com/practice/mongoProject/domain/Priorities.java package com.practice.mongoProject.domain; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.ScanParams; import redis.clients.jedis.ScanResult; import java.util.HashSet; import java.util.List; import java.util.Set; public class Priorities { public static void main(String[] args) { Set<String> matchingKeys = new HashSet<>(); ScanParams params = new ScanParams(); params.match("IDLI*"); try(Jedis jedis = new JedisPool().getResource()) { String nextCursor = "0"; do { ScanResult<String> scanResult = jedis.scan(nextCursor, params); List<String> keys = scanResult.getResult(); nextCursor = scanResult.getStringCursor(); matchingKeys.addAll(keys); } while(!nextCursor.equals("0")); if (matchingKeys.isEmpty()) { return; } jedis.del(matchingKeys.toArray(new String[0])); } } }
0b997f8d628eeccb39f1d687c4de3952216c9df4
[ "Java" ]
5
Java
amitnteny/mongo-project
0cf346c7330fd9ccaa1f5b30be0053af3471a8cf
62067e49763b787437b2e128308b1443e676f75e
refs/heads/master
<repo_name>boraergul/Transcendence-Dynamic-Chain<file_sep>/mnstats_old.sh #!/bin/bash list=($(ls -la /root | grep "\.transcendence" | cut -d "." -f 2 | cut -d "_" -f 2)) for i in ${!list[@]}; do /root/bin/transcendence-cli_${list[$i]}.sh masternode status &>/dev/null if [[ $? == 0 ]] then result=$(/root/bin/transcendence-cli_${list[$i]}.sh masternode status | grep message |cut -d ":" -f 2) else /root/bin/transcendence-cli_${list[$i]}.sh masternode status 2> /tmp/errorout result=$(cat /tmp/errorout) fi echo " ${list[$i]} -- $result" done rm -f /tmp/errorout <file_sep>/zabbix/restartnode.sh #!/bin/bash /usr/bin/transcendence-cli_$1.sh masternode stop sleep 5 /usr/bin/transcendence-cli_$1.sh masternode start <file_sep>/zabbix/nodestats.sh #!/bin/bash /usr/bin/transcendence-cli_$1.sh masternode status &>/dev/null if [[ $? == 0 ]] then result=$(/usr/bin/transcendence-cli_$1.sh masternode status | grep status |cut -d ":" -f 2 | sed 's/,//') else /usr/bin/transcendence-cli_$1.sh masternode status 2> /tmp/errorout result=999 fi echo "$result" <file_sep>/zabbix/README.md ## Zabbix Masternode status checks with agent Import Value Mapping first. <file_sep>/zabbix/nodelld.py #!/usr/bin/python import os import json import subprocess if __name__ == "__main__": command=r""" ls -la /usr/share/ | grep "\.transcendence" | cut -d "." -f 2 | cut -d "_" -f 2 """ nodes = (subprocess.check_output(command, shell=True)).rsplit() data = [{"{#NODENAME}": node} for node in nodes] print(json.dumps({"data": data}, indent=4))
7083919f87432435dd15fcbc659b5d3a12fbeb3d
[ "Markdown", "Python", "Shell" ]
5
Shell
boraergul/Transcendence-Dynamic-Chain
e62ce538c8a84bdf3518e3b2e21d6abeda27d61a
fb7c6c6847b0aeb2ab391533fbb361e361398342
refs/heads/main
<repo_name>DanielRojas2002/PIB-Tasa_desempleo-Variables_Macroeconomicas<file_sep>/README.md # PIB-Tasa_desempleo-Variables_Macroeconomicas Materia: Macroeconomia Semestre 3 Este codigo saca : * El PIB por el metodo del Gasto * El PIB por el metodo del Ingreso * La Tasa de Desempleo * La Inflacion, Indice de precios y el Producto Interno Bruto Nominal Te pide que ingreses los datos que el codigo va a necesitar es un menu de 4 opciones tu eliges cual quieres ejecutar despues te lo agrega en un documento txt que esta en la carpeta de archivos y se llama el documento datos.txt <file_sep>/Codigo.py import sys from clases import desempleos from clases import formulas from clases import indice from clases import inflacion from clases import PIBR from clases import MetodoDelIngreso from clases import MetodoDelGasto try: opcion=1 while opcion==1: separador=("*"*40) print("-"*30 +"MENU PRINCIPAL" + "-"*30) print("1-Sacar el PIB por el Metodo del Ingreso\n2-Sacar el PIB por el metodo del Gasto\n3-Sacar el Indice de Precios,Inflacion y Producto Interno Bruto Real") print("4-Sacar la Tasa de Desempleo") print("-"*30) menu=int(input("Ingrese el numero de opcion que desea ejecutar : ")) print("-"*30) if menu==1: print("") print("*"*30 +"BIENVENIDO AL PROGRAMA" + "*"*30) print("Este programa te saca el PIB con el metodo del ingreso :)") print("-"*30) II=float(input("Dime los Impuestos Indirectos : ")) IP=float(input("Dime los Ingresos de los Propietarios : ")) IN=float(input("Dime los Intereses : ")) D=float(input("Dime la Depreciacion : ")) BC=float(input("Dime los Beneficios Corporativos : ")) R=float(input("Dime la Renta : ")) RT=float(input("Dime la Remuneraciones de los trabajadores : ")) INFE=float(input("Dime el Ingreso Neto de los Factores Extranjeros : ")) objeto=MetodoDelIngreso(II,IP,IN,D,BC,R,RT,INFE) objeto.formulas() objeto.PIB() print(separador) print("") print("1=SI\n2=NO") opcion=int(input("Deseas regresar al Menu Principal : ")) print("") elif menu==2: print("") print("*"*30 +"BIENVENIDO AL PROGRAMA" + "*"*30) print("Este programa te saca el PIB con el metodo del gasto :)") print("-"*30) ID=float(input("Dime el impuesto indirecto : ")) INFEE=float(input("Dime el ingreso neto de los factores extranjeros : ")) E=float(input("Dime las Exportaciones : ")) D=float(input("Dime la Depreciacion : ")) IM=float(input("Dime las Importaciones : ")) GG=float(input("Dime el Gasto de Gobierno : ")) GCF=float(input("Dime el Gasto en Consumo de las familias : ")) objeto=MetodoDelGasto(ID,INFEE,E,D,IM,GG,GCF) objeto.formulas() objeto.PIB() print(separador) print("") print("1=SI\n2=NO") opcion=int(input("Deseas regresar al Menu Principal : ")) print("") elif menu==3: listaAño=[] contador1=1 listaNivel=[] listaPIBN=[] listaIndice=[] listaInflacion=[] listaPIBR=[] contador=0 contadoor=0 cuantos=int(input("Cuantos Años vas a registrar : ")) print(separador) for año in range(cuantos): año=int(input("Ingresa el Año : ")) listaAño.append(año) print(separador) for año in listaAño: print(f"{contador1}-{año}") contador1=contador1+1 base=int(input("Cual es el indice del año base : ")) baseo=(base-1) print(separador) for precio in range(cuantos): nivel_precios=float(input(f"Ingresa el Nivel de Precios del Año {listaAño[contador]} :")) listaNivel.append(nivel_precios) contador=contador+1 print(separador) for producto in range(cuantos): PIBN=float(input(f"Ingrese el Producto Interno Bruto Nominal del Año {listaAño[contadoor]} : ")) listaPIBN.append(PIBN) contadoor=contadoor+1 print(separador) print("") print(separador) print("Estas son las Formulas :) ") formulas() print(separador) print("") print(separador) indice(listaNivel,listaIndice,baseo,listaAño) print(separador) print("") print(separador) inflacion(listaIndice,listaAño,cuantos,listaInflacion) print("") print(separador) PIBR(listaPIBN,listaIndice,listaPIBR,listaAño,cuantos) print("") print(separador) print("") print("1=SI\n2=NO") opcion=int(input("Deseas regresar al Menu Principal : ")) print("") elif menu==4: desempleo=int(input("Ingresa los Desempleados o la poblacion no ocupada : ")) PEA=int(input("Ingresa La Fueza Laboral o PEA : ")) objeto=desempleos(desempleo,PEA) objeto.calculo() print(separador) print("") print("1=SI\n2=NO") opcion=int(input("Deseas regresar al Menu Principal : ")) print("") elif menu <=0 or menu>4: print("Ingresaste el numero de opcion mal , porfavor intentelo de nuevo :)") print(separador) print("") except: print("*"*30) print(f"Ocurrió un problema {sys.exc_info()[1]}") print(f"Ocurrió un problema {sys.exc_info()[0]}") print(f"Ocurrió un problema {sys.exc_info()[2]}") print("Intenta respetar lo que se te pide :) ") print("*"*30) finally: print("FIN DEL CODIGO ...") print("*"*30)<file_sep>/clases.py class desempleos: def __init__ (self,desempleados,PEA): self.__desempleados=desempleados self.__PEA=PEA def calculo(self): archivoA=open("./archivos/datos.txt" , 'a') resultado=(self.__desempleados/self.__PEA)*100 textoa=str(resultado) print(f"La tasa de Desempleo es : {resultado}") archivoA.write("RESPUESTA DE LA TASA DE DESEMPLEO :)" +"\n" ) archivoA.write("TASA DE DESEMPLEO = " + textoa + "\n" ) archivoA.write("///////////////////////////////////////////////////////////////" +"\n" ) archivoA.write("///////////////////////////////////////////////////////////////" +"\n" ) archivoA.close() #-------------------------------------------------------------------------------------------------------------------------------------- # METODO DEL INGRESO class MetodoDelIngreso(): def __init__ (self,II,IP,IN,D,BC,R,RT,INFE): self.__II=II self.__IP=IP self.__IN=IN self.__D=D self.__BC=BC self.__R=R self.__RT=RT self.__INFE=INFE def formulas(self): print("-"*40) print("IN=(Rt+R+In+Ip+Bc)") print("PIB=(IN+IIE+dep+INFE)") print("-"*40) def PIB(self): IN=(self.__RT+self.__R+self.__IN+self.__IP+self.__BC) pib=(IN+self.__II+self.__D+self.__INFE) textoa=str(IN) textob=str(pib) print("") print("¿¿¿RESPUESTAS???:") print(f"Ingreso Nacional(IN) = {IN} ") print(f"Producto Interno Bruto(PIB) = {pib} ") archivoA=open("./archivos/datos.txt" , 'a') archivoA.write("RESPUESTAS DEL METODO DEL INGRESO :)" +"\n" ) archivoA.write("Ingreso Nacional(IN) = " + textoa + "\n" ) archivoA.write("Producto Interno Bruto(PIB) =" + textob + "\n" ) archivoA.write("///////////////////////////////////////////////////////////////" +"\n" ) archivoA.write("///////////////////////////////////////////////////////////////" +"\n" ) archivoA.close() print("") #------------------------------------------------------------------------------------------------------------------------------------- #METODO DEL GASTO class MetodoDelGasto(): def __init__(self,ID,INFEE,E,D,IM,GG,GCF): self.__ID=ID self.__INFEE=INFEE self.__E=E self.__D=D self.__IM=IM self.__GG=GG self.__GCF=GCF def formulas(self): print("-"*40) print("Estas son las Formulas ") print("Xn=(E-I)") print("PIB=(C+I+G+Xn)") print("IN=(PIN-ingreso neto de los factores-impuestos indirectos)") print("-"*40) def PIB(self): XN=(self.__E-self.__IM) pib=(self.__GCF+self.__INFEE+self.__GG+XN) PIN=(pib-self.__D) IN=(PIN-self.__INFEE-self.__ID) textoa=str(pib) textob=str(PIN) textoc=str(IN) print("¿¿¿RESPUESTAS???:") print(f"Producto Interno Bruto(PIB) = {pib} ") print(f"Producto Interno Neto(PIN) = {PIN} ") print(f"Ingreso Nacional(IN) = {IN} ") print("") archivoA=open("./archivos/datos.txt" , 'a') archivoA.write("RESPUESTAS DEL METODO DEL GASTO :)" +"\n" ) archivoA.write("Producto Interno Bruto(PIB) =" + textoa + "\n" ) archivoA.write("Producto Interno Neto(PIN) = " + textob + "\n" ) archivoA.write("Ingreso Nacional(IN) =" + textoc + "\n" ) archivoA.write("///////////////////////////////////////////////////////////////" +"\n" ) archivoA.write("///////////////////////////////////////////////////////////////" +"\n" ) archivoA.close() #VARIABLES MACROECONOMICAS def formulas(): print("*Indice de Precios : "+ "=" +"(NIVEL DE PRECIOS / BASE DE NIVEL DE PRECIOS * 100") print("*Inflacion : "+ "=" + "INDICE DE PRECIOS – INDICE DE PRECIOS UNO ATRÁS / INDICE DE PRECIOS UNO ATRÁS * 100") print("*PIBR : " + "=" + "PRODUCTO INTERNO BRUTO NOMINAL / INDICE DE PRECIOS * 100") def indice(listaNivel,listaIndice,baseo,listaAño): archivoA=open("./archivos/datos.txt" , 'a') archivoA.write("RESPUESTAS DE LAS VARIABLES MACROECONOMICAS :)" +"\n" ) contador=0 separador=("*"*40) for precio in listaNivel: z=(precio/(listaNivel[baseo]))*100 listaIndice.append(z) print(separador) print("") for numero in listaIndice: print("INDICE DE PRECIOS : ") print(f"El indice de Precios del año {listaAño[contador]} es = {numero}") textoa=str(numero) archivoA.write("Indice de Precios = " + textoa + "\n" ) contador=contador+1 print(separador) print("") archivoA.close() def inflacion(listaIndice,listaAño,cuantos,listaInflacion): archivoA=open("./archivos/datos.txt" , 'a') contador=1 contador2=0 contadorA=1 separador=("*"*40) for numero in range(cuantos-1): resultado=(listaIndice[contador]-listaIndice[contador2])/listaIndice[contador2]*100 contador=contador+1 contador2=contador2+1 if resultado!=0: listaInflacion.append(resultado) for numero in listaInflacion: print("INFLACION : ") print(f"La Inflacion del año {listaAño[contadorA]} es = {numero}") textoa=str(numero) archivoA.write("Inflacion = " + textoa + "\n" ) contadorA=contadorA+1 print(separador) print("") archivoA.close() def PIBR(listaPIBN,listaIndice,listaPIBR,listaAño,cuantos): archivoA=open("./archivos/datos.txt" , 'a') contador=0 contadorA=0 separador=("*"*40) for numero in range(cuantos): resultado=(listaPIBN[contador]/listaIndice[contador])*100 listaPIBR.append(resultado) contador=contador+1 for numero in listaPIBR: print("Producto Interno Bruto Real : ") print(f"El Producto Interno Bruto Real del año {listaAño[contadorA]} es = {numero}") textoa=str(numero) archivoA.write("Producto Interno Bruto Real = " + textoa + "\n" ) contadorA=contadorA+1 print(separador) print("") archivoA.write("///////////////////////////////////////////////////////////////" +"\n" ) archivoA.close()
760105746c32cd11cb537875834c0d6591784b09
[ "Markdown", "Python" ]
3
Markdown
DanielRojas2002/PIB-Tasa_desempleo-Variables_Macroeconomicas
6b7c45ef0e8341af9f418d4be974bc9ad5925a0a
7e96f8ff8e093f67afc61b88810215e1923270c3
refs/heads/main
<file_sep>FROM grafana/promtail:2.2.1 RUN apt-get update && apt-get install -y bc curl dumb-init bash python procps coreutils sysstat vim net-tools RUN mkdir /weatherflow-collector RUN mkdir /weatherflow-collector/export COPY exec-health-check.sh \ exec-host-performance.sh \ exec-local-udp.sh \ exec-remote-forecast.sh \ exec-remote-import.sh \ exec-remote-rest.sh \ exec-remote-socket.sh \ health_check.sh \ jq \ logcli-linux-amd64 \ loki-config.yml \ start-health-check.sh \ start-host-performance.sh \ start-local-udp.sh \ start-remote-export.sh \ start-remote-forecast.sh \ start-remote-import.sh \ start-remote-rest.sh \ start-remote-socket.sh \ start.sh \ weatherflow-collector_details.sh \ weatherflow-listener.py \ websocat_amd64-linux-static \ /weatherflow-collector/ COPY jq /usr/bin/ WORKDIR /weatherflow-collector RUN chmod a+x *.sh RUN chmod +x logcli-linux-amd64 websocat_amd64-linux-static RUN chmod +x /usr/bin/jq ENTRYPOINT ["/usr/bin/dumb-init", "--"] CMD ["/weatherflow-collector/start.sh"] <file_sep>WEATHERFLOW_COLLECTOR_IMPORT_DAYS="365" \ WEATHERFLOW_COLLECTOR_INFLUXDB_PASSWORD="<PASSWORD>" \ WEATHERFLOW_COLLECTOR_INFLUXDB_URL="http://influxdb01.com:8086/write?db=weatherflow" \ WEATHERFLOW_COLLECTOR_INFLUXDB_USERNAME="idejan" \ WEATHERFLOW_COLLECTOR_PERF_INTERVAL="60" \ WEATHERFLOW_COLLECTOR_THREADS="4" \ WEATHERFLOW_COLLECTOR_TOKEN="<PASSWORD>" \ bash ./generate_docker-compose.sh
a795ad04a44fe652349da4d5b6d73f18ff1565ce
[ "Dockerfile", "Shell" ]
2
Dockerfile
BoceJr/weatherflow-collector
f2fa0614d1e1db55b505a9361317bbcff484ee0c
6238c6489c351af0a4e5e62d79fefba6b1843d6c