branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>package com.company; public interface GenericInterface <T> { T getDigit(); T getText(); void setDigit (T digit); void setText (T text); } <file_sep>package com.company; public class Main { public static void main(String[] args) { System.out.println("Integer:"); GenericClass<Integer> genericClass = new GenericClass(); genericClass.setDigit(2020); System.out.println(genericClass.getDigit()); System.out.println("----------------------"); System.out.println("Float:"); GenericClass<Float> genericClass1 = new GenericClass(); genericClass1.setText(2020f); System.out.println(genericClass1.getText()); } }
2e2bbb8b94e849eb3f997efeb484137c82ea9a15
[ "Java" ]
2
Java
nurel77/Lesson2.6
9ad095fb7593578f474864b9c8d131cc3869e993
6b89920610fdf91436ff4be80b4e497cb94c73ec
refs/heads/master
<repo_name>chldyddnjs/dL-project<file_sep>/tensorflow/Rnn/12-4.py from __future__ import print_function import tensorflow as tf import numpy as np from tensorflow.contrib import rnn tf.set_random_seed(777) sentence=("if you want to build a ship, don't drum up people together to " "collect wood and don't assign them tasks and work, but rather " "teach them to long for the endless immensity of the sea.") char_set =list(set(sentence)) # char to index char_dic = {w:i for i,w in enumerate(char_set)} data_dim = len(char_set) hidden_size = len(char_set) num_classes = len(char_set) sequence_length = 10 learning_rate = 0.1 dataX =[] dataY =[] for i in range(0, len(sentence) - sequence_length): x_str = sentence[i:i + sequence_length] y_str = sentence[i+1: i + sequence_length + 1] print(i, x_str, '->', y_str) x = [char_dic[c] for c in x_str] y = [char_dic[c] for c in y_str] dataX.append(x) dataY.append(y) batch_size = len(dataX) X = tf.placeholder(tf.int32, [None, sequence_length]) Y = tf.placeholder(tf.int32, [None, sequence_length]) X_one_hot = tf.one_hot(X, num_classes) print(X_one_hot) def lstm_cell(): cell = rnn.BasicLSTMCell(hidden_size, state_is_tuple=True) return cell multi_cells = rnn.multiRNNCell([lstm_cell() for _ in range(2)], state_is_tuple=True) outputs = tf.nn.dynamic_rnn(multi_cells, X_one_hot, dtype=tf.float32) X_for_fc = tf.reshape(outputs,[-1, hidden_size]) outputs = tf.contrib.layers.fully_connected([X_for_fc, num_classes, activation_fn=None) weights =tf.ones(batch-size,sequence_length) sequence_loss = tf.contrib.seq2seq.sequence_loss(logits=outputs, target=Y, weights=weights) mean_loss = tf,reduce_mean(sequence_loss) train_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(mean_loss) sess = tf.Session() sess.run(tf.global_variables_initializer()) for i in range(500): _, l, results = sess.run( [train_op, mean_loss,outputs], feed_dict={X:dataX,Y:dataY}) for j,result in enumerate(results): index =np.argmax([result, axis=1]) print(i,j,''.join(char_set[t] for t in index), 1) results= sess.run(outputs, feed_dict={X: dataX}) for j,result in enumerate(results): index = np.argmax([result,axis=1]) if j is 0: print(''.join([char_set[t] for t in index]),end='') else: print(char_set[index[-1]],end='') <file_sep>/tensorflow/Deep neural netwark/9-1 forward XOR.py import tensorflow as tf import numpy as np tf.set_random_seed(777) x_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.float32) y_data = np.array([[0], [1], [1], [0]], dtype=np.float32) X =tf.placeholder(tf.float32, [None, 2]) Y =tf.placeholder(tf.float32, [None, 1]) W =tf.Variable(tf.random_normal([2, 1]), name='weight') b =tf.Variable(tf.random_normal([1]), name='bias') hypothesis =tf.sigmoid(tf.matmul(X,W)+b) cost = -tf.reduce_mean(Y*tf.log(hypothesis)+ (1-Y)*tf.log(1-hypothesis)) train = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost) predicted =tf.cast(hypothesis > 0.5, dtype=tf.float32) accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for step in range(10001): _, cost_val, w_val = sess.run([train, cost, W], feed_dict={X:x_data,Y:y_data}) if step % 100 == 0: print(step,cost, cost_val, w_val) h,c,a = sess.run([hypothesis,predicted,accuracy], feed_dict={X:x_data,Y:y_data}) print("\nHypothesis: ", h, "\nCorrect: ", c, "\nAccuracy: ", a) <file_sep>/tensorflow/Learning rate/7-1.py import tensorflow as tf tf.set_random_seed(777) x_data = [[1, 2, 1], [1, 3, 2], [1, 3, 4], [1, 5, 5], [1, 7, 5], [1, 2, 5], [1, 6, 6], [1, 7, 7]] y_data = [[0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 1, 0], [0, 1, 0], [0, 1, 0], [1, 0, 0], [1, 0, 0]] # Evaluation our model using this test dataset x_test = [[2, 1, 1], [3, 1, 2], [3, 3, 4]] y_test = [[0, 0, 1], [0, 0, 1], [0, 0, 1]] X = tf.placeholder("float",[None,3]) Y = tf.placeholder("float",[None,3]) W = tf.Variable(tf.random_normal([3,3])) b = tf.Variable(tf.random_normal([3])) hypothesis = tf.nn.softmax(tf.matmul(X,W) + b) cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1)) optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost) prediction = tf.argmax(hypothesis, 1) is_correct = tf.equal(prediction, tf.argmax(Y,1)) accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for step in range(201): cost_val,W_val,_ = sess.run([cost,W,optimizer],feed_dict={X:x_data,Y:y_data}) print(step,cost_val,W_val) print("prediction:", sess.run(prediction, feed_dict={X:x_test})) print("Accuracy:", sess.run(accuracy, feed_dict={X:x_test,Y:y_test})) <file_sep>/tensorflow/cnn/11-3 class cnn.py import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) tf.set_random_seed(777) learning_rate = 0.01 training_epochs = 15 batch_size=100 class Model: def __init__(self, sess, name): self.sess = sess self.name = name self._build_net() def _build_net(self): with tf.variable_scope(self.name): self.keep_prob = tf.placeholder(tf.float32) self.X = tf.placeholder(tf.float32, [None,784]) X_img = tf.reshape(self.X, [-1,28,28,1]) self.Y = tf.placeholder(tf.float32, [None,10]) W1 = tf.Variable(tf.random_normal([3,3,1,32])) L1 = tf.nn.conv2d(X_img,W1,strides=[1,1,1,1], padding='SAME') L1 = tf.nn.relu(L1) L1 = tf.nn.max_pool(L1, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME') L1 = tf.nn.dropout(L1, keep_prob=self.keep_prob) W2 = tf.Variable(tf.random_normal([3,3,32,64])) L2 = tf.nn.conv2d(L1,W2,strides=[1,1,1,1], padding='SAME') L2 = tf.nn.relu(L2) L2 = tf.nn.max_pool(L2, ksize=[1,2,2,1], strides=[1,2,2,1],padding='SAME') L2 = tf.nn.dropout(L2, keep_prob=self.keep_prob) W3 = tf.Variable(tf.random_normal([3,3,64,128])) L3 = tf.nn.conv2d(L2,W3,strides=[1,1,1,1],padding='SAME') L3 = tf.nn.relu(L3) L3 = tf.nn.max_pool(L3, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME') L3 = tf.nn.dropout(L3, keep_prob=self.keep_prob) L3_flat = tf.reshape(L3,[-1,4*4*128]) W4 = tf.get_variable("W4", shape=[128*4*4,625], initializer = tf.contrib.layers.xavier_initializer()) b4 = tf.Variable(tf.random_normal([625])) L4 = tf.nn.relu(tf.matmul(L3_flat,W4) + b4) L4 = tf.nn.dropout(L4, keep_prob=self.keep_prob) W5 = tf.get_variable("W5", shape=[625,10], initializer = tf.contrib.layers.xavier_initializer()) b5 = tf.Variable(tf.random_normal([10])) self.hypothesis = tf.matmul(L4, W5) + b5 self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.hypothesis,labels=self.Y)) self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(self.cost) correct_prediction = tf.equal(tf.argmax(self.hypothesis, 1), tf.argmax(self.Y,1)) self.accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) def predict(self, x_test, keep_porp=1.0): return self.sess.run(self.hypothesis, feed_dict={self.X:x_test, self.Y:y_test}) def get_accuaracy(self, x_test, y_test, keep_prop=1.0): return self.sess.run(self.accuracy, feed_dict={self.X:x_test,self.Y:y_test}) def train(self, x_data, y_data,keep_prop=0.7): return self.sess.run([self.cost,self.optimizer], feed_dict={ self.X:x_data, self.Y:y_data, self.keep_prob:keep_prop}) sess =tf.Session() m1 = Model(sess, "m1") sess.run(tf.global_variables_initializer()) print("Learning started!") for epoch in range(training_epochs): avg_cost=0 total_batch = int(mnist.train.num_examples / batch_size) for i in range(total_batch): batch_xs,batch_ys = mnist.train.next_batch(batch_size) c,_ = m1.train(batch_xs,batch_ys) avg_cost += c / total_batch print('Epoch:', '%04d' % (epoch + 1), 'cost=','{:.9f}'.format(avg_cost)) print("Learning Finish") print('Auccuracy:', m1.get_accuracy(mnist.test.images, mnist.labels)) <file_sep>/tensorflow/Linear Regression 개념/Lab2.py import tensorflow as tf x_train = [1,2,3] y_train = [1,2,3] w= tf.Variable(tf.random_normal([1]), name='weight') b= tf.Variable(tf.random_normal([1]), name='bias') hypothesis = x_train*w+b cost = tf.reduce_mean(tf.square(hypothesis - y_train)) optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.01) train = optimizer.minimize(cost) sess =tf.Session() sess.run(tf.global_variables_initializer()) for step in range(2001): sess.run(train) if step%20==0: print(step,sess.run(cost),sess.run(w),sess.run(b)) <file_sep>/tensorflow/Linear Regression 개념/Lab2.1.py import tensorflow as tf w= tf.Variable(tf.random_normal([1]), name='weight') b= tf.Variable(tf.random_normal([1]), name='bias') x=tf.placeholder(tf.float32, shape=[None]) y=tf.placeholder(tf.float32, shape=[None]) hypothesis = x*w+b cost = tf.reduce_mean(tf.square(hypothesis - y)) optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.01) train = optimizer.minimize(cost) sess =tf.Session() sess.run(tf.global_variables_initializer()) for step in range(2001): cost_val, w_val, b_val, _ = sess.run([cost, w, b, train], feed_dict={x: [1, 2, 3, 4, 5], y: [2.1, 3.1, 4.1, 5.1, 6.1]}) if step%20==0: print(step, cost_val, w_val, b_val) """ placeholder를 사용하는 이유는 만들어진 모델에 입력을 할수 있다는게 장점 """ <file_sep>/tensorflow/Rnn/12-1Rnn hihello.py import tensorflow as tf import numpy as np tf.set_random_seed(777) idx2char = ['h','i','e','l','o'] x_data = [[0,1,0,2,3,3]] x_one_hot = [[[1,0,0,0,0], [0,1,0,0,0], [1,0,0,0,0], [0,0,0,1,0], [0,0,0,1,0]]] y_data = [[1,0,2,3,3,4]] num_classes = 5 input_dim = 5 hidden_size = 5 batch_size = 1 sequence_length = 6 learning_rate = 0.1 X = tf.placeholder(tf.float32, [None, sequence_length, input_dim]) Y = tf.placeholder(tf.int32, [None, sequence_length]) cell = tf.contrib.rnn.BasicLSTMcell(num_units=hidden_size, state_is_tuple=True) initial_state =cell.zero_state(batch_size, tf.float32) output, _states = tf.nn.dynamic_rnn( cell,X,initial_state=initial_state, dtype=tf.float32) X_for_fc = tf.reshape(outputs, [-1, hidden_size]) #fc_w = tf.get_variable("fc_w", [hidden_size, num_classes]) #fc_b = tf.get_variable("fc_b", [num_classes]) #outputs = tf.matmul(X_for_fc,fc_w) + fc_b outputs = tf.contrib.layers.fully_connected( inputs=X_for_fc, num_ouputs=num_classes, activationn=None) # reshape out for loss outputs = tf.reshape(outputs, [batch_size, sequence_length, num_classes]) weigthts = tf.ones([batch_size, sequence_length]) sequence_loss =tf.contrib.seq2seq.sequence_loss( logits=outputs, targets=Y, weights=weights) loss = tf.reduce_mean(sequence_loss) train = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) prediction = tf.argmax(ouputs, axis=2) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(50): l, _ = sess.run([loss, train], feed_dict={X:x_one_hot, Y:y_data}) result = sess.run(prediction, feed_dict={X:x_one_hot}) print(i, "lost",l,"prediction", result,"true Y:", y_data) result_str= [idx2char[c] for c in np.squeeze(result)] print("\n prediction str: ", ''.join(result_str)) <file_sep>/tensorflow/Logistic Regression/Lab5.py import tensorflow as tf tf.set_random_seed(777) x_data = [[1,2], [2,3], [3,1], [4,3], [5,3], [6,2]] y_data = [[0], [0], [0], [1], [1], [1]] X=tf.placeholder(tf.float32, shape=[None, 2]) Y=tf.placeholder(tf.float32, shape=[None, 1]) W=tf.Variable(tf.random_normal([2, 1]),name='weight') b=tf.Variable(tf.random_normal([2, 1]),name='bias') #Hypothesis using sigmoid: tf.div(1.,1. + tf.exp(tf.matmul(X,W) + b)) hypothesis = tf.sigmoid(tf.matmul(X, W)+b) cost = -tf.reduce_mean(Y*tf.log(hypothesis)+(1-Y)*tf.log(1-hypothesis)) train =tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost) predicted = tf.cast(hypothesis > 0.5, dtype =tf.float32) accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype = tf.float32)) # Train Model with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for step in range(10001): cost_val, _ =sess.run([cost,train], feed_dict={X:x_data,Y:y_data}) if step % 200 ==0: print(step, cost_val) h ,c ,a = sess.run([hypothesis, predicted, accuracy], feed_dict={X:x_data, Y:y_data}) print("\nHypothesis: ", h, "\nCorrect (Y): ", c, "\nAccuracy: ", a) <file_sep>/tensorflow/Rnn/12-2.py import tensorflow as tf import numpy as np tf.set_random_seed(777) sample = "if you want you" idx2char = list(set(sample)) char2idx = {c: i for i, c in enumerate(idx2char)} #char -> index 바꿔준다 dic_size = len(char2idx) # 입력의 갯수(one hot size) hidden_size = len(char2idx) #출력의 갯수 num_classes = len(char2idx)#final output size batch_size = 1 # one sample data, one batch sequence_length = len(sample) - 1 learning_rate = 0.1 sample_idx = [char2idx[c] for c in sample] # char to index 바꿔준다 x_data = [sample_idx[:-1]] y_data = [sample_idx[1:]] X = tf.placeholder(tf.int32, [None, sequence_length]) #X data Y = tf.placeholder(tf.int32, [None, sequence_length]) #Y label x_one_hot = tf.one.hot(X, num_classes) # one hot encoding cell = tf.contrib.rnn.basicLSTMCell( num_units=hidden_size, state_is_tuple= True) initial_state = cell.zero_state(batch_size, tf.float32) output, _states = tf.nndynamic_rnn( cell, x_one_hot, initital_state=initial_state, dtype=tf.float32) X_for_fc = tf.reshape(ouputs, [-1, hidden_size])# 퓰리커넥티드 레이어 outputs = tf.contrib.layers.fully_connected(X_for_fc,num_classes, activation_fn=None) outputs = tf.reshape(outputs, [batch_size, sequence_length, num_classes]) weights = tf.ones([batch_size, sequence_length]) sequence_loss = tf.contrib.seq2seq.sequence_loss(logits=outputs, targets=Y, weights) loss = tf.reduce_mean(seqence_loss) train = tf.AdamOptimizer(learning_rate=learning_rate) prediction = tf.argmax(output, axis=2) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(50): l,_ = sess.run([loss, train], feed_dict={X:x_data,Y:y_data}) result = sess.run(prediction, feed_dict={X:x_data}) result_str = [idx2char[c] for in np.squeeze(result)] print(i, "loss", l,"prediction", ''.join(result_str)) <file_sep>/tensorflow/Learning rate/7-4.py import tensorflow as tf import matplotlib.pyplot as plt import random tf.set_random_seed(777) from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/",onehot=True) nb_casses = 10 X = tf.placeholder(tf.float32, [None,784]) Y = tf.placeholder(tf.float32,[None,nb_classes]) W = tf.Variable(tf.random_normal([None,784])) b = tf.Variable(tf.random_normal([nb_classes])) hypothesis = tf.nn.softmax(tf.matmul(X,W)+b) cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis),axis=1)) train = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost) is_correct = tf.eqaul(tf.argmax(hypothesis,1),tf.argmax(Y,1)) accuracy = tf.reduce_mean(cast(is_correct,tf.float32)) num_epochs = 15 batch_size =100 num_iterations = int(mnist.train.num_examples / batch_size) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(num_epochs): avg_cost = 0 for i in range(num_iteration): batch_xs, batch_ys =mnist.train.next_batch(batch_size) _,cost_val = sess.run([train,cost],feed_dict={X:batch_xs,Y:batch_ys}) avg_cost += cost_val/ num_iteration print("Epoch:{:04d}, cost:{:.9f}".format(epoch + 1, avg_cost)) print("Learning finished") print("Accuracy", accuracy.eval(session=sess,feed_dict={X:mnist.test.images,Y:mnist.test.labels} ), ) r = random.randint(0,mnist.test.num_examples -1) print("Label: ",sess.run(tf.argmax(mnist.test.labels[r:r+1],1))) print("prediction:",sess.run(tf.argmax(mnis.hypothesis,1), feed_dict={X:mnist.test.images[r:r+1]})) plt.imshow(mnist.test.images[r:r+1].reshape(28,28), cmap='Greys',interpolation='nearest') plt.show() <file_sep>/tensorflow/Rnn/12-3 Rnn-softmax.py import tensorflow as tf import numpy as np tf.set_random_seed(777) sample = "if you want you" idx2char = list(set(sample)) char2idx = {c : i for i,c in enumerate(idx2char)} dic_size = len(char2idx) rnn_hidden_size = len(char2idx) num_classes = len(char2idx) batch_size = 1 seqence_length = len(sample) -1 learning_rate = 0.1 sample_idx = [char2idx[c] for c in sample] # char to index x_data = [sample_idx[:-1]] y_data = [sample_idx[1:]] X = tf.placeholder(tf.float32,[None, sequence_length]) Y = tf.placeholder(tf.float32,[None, sequence_length]) X_one_hot = tf.one_hot(X,num_classes) X_for_softmax = tf.reshape(X_one_hot, [-1, rnn_hidden_size]) softmax_w = tf.get_variable("softmax_w",[rnn_hidden_size,num_classes]) softmax_b = tf.get_variable("softmax_b",[num_classes]) outputs = tf.matmul(X_for_softmax, softmax_w) + softmax_b outputs = tf.reshape(outputs, [batch_size, sequence_length, num_classes]) weights = tf.ones([batch_size, sequence_length]) sequence_loss = tf.contrib.seq2seq.sequence_loss( logits=outputs, targets=Y, weights=weights) loss = tf.reduce_mean(sequence_loss) train = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) prediction = tf.argmax(outputs, axis=2) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(3000): l,_ = sess.run([loss, train], feed_dict={X:x_data,Y:y_data}) result = sess.run(prediction, feed_dict={X:x_data}) result_str = [idx2char[c] for c in np.squeeze(result)] print(i, "loss",l,"prediction",''.join(result_str)) <file_sep>/tensorflow/Rnn/f.py import tensorflow as tf tf.set_random_seed(777) sentence=("if you want to build a ship, don't drum up people together to " "collect wood and don't assign them tasks and work, but rather " "teach them to long for the endless immensity of the sea.") char_set =list(set(sentence)) # char to index char_dic = {w:i for i,w in enumerate(char_set)} data_dim = len(char_set) hidden_size = len(char_set) num_classes = len(char_set) sequence_length = 10 learning_rate = 0.1 dataX =[] dataY =[] for i in range(0, len(sentence) - sequence_length): x_str = sentence[i:i + sequence_length] y_str = sentence[i+1: i + sequence_length + 1] # print(i, x_str, '->', y_str) x = [char_dic[c] for c in x_str] y = [char_dic[c] for c in y_str] dataX.append(x) dataY.append(y) batch_size = len(dataX) X = tf.placeholder(tf.int32, [None, sequence_length]) Y = tf.placeholder(tf.int32, [None, sequence_length]) X_one_hot = tf.one_hot(X, num_classes) print(X_one_hot) <file_sep>/tensorflow/Deep neural netwark/9-7 sigmoid backprob.py import tensorflow as tf import numpy as np tf.set_random_seed(777) xy = np.loadtxt('data-04-zoo.csv', delimiter = ',',dtype=np.float32) X_data = xy[:,0:-1] N = X_data.shape[0] Y_data = xy[:,[-1]] print("y has one of the following values") nb_classes = 7 X = tf.placeholder(tf.float32, [None, 16]) Y = tf.placeholder(tf.int32,[None, 1]) target = tf.onehot(y, nb_classes) target = tf.reshape(target, [-1,nb_classes]) target = tf.cast(target, tf.float32) W = tf.Variable(tf.random_normal([16, nb_classes]),name='weight') b = tf.Variable(tf.random_normal([nb_classes]),name='bias') def sigma(x): return 1./(1.+ tf.exp(-x)) def sigma_prime(x): return sigma(x) * (1. - sigma(x)) layer_1 = tf.matmul(X,W)+b y_pred = sigma(layer_1) loss_i = -target*tf.log(y_pred) - (1. - target) * tf.log(1 - y_pred) loss = tf.reduce_sum(loss_i) assert y_pred.shape.as_list() == target.shape.as_list() d_loss = (y_pred - target) / (y_pred * (1. - y_pred) + 1e-7) d_sigma = sigma_prime(layer_1) d_layer = d_loss * d_sigma d_b = d_layer d_w = tf.matmul(tf.transpose(X),d_layer) learning_rate = 0.01 train_step = [ tf.assign(W, W - learning_rate *d_w), tf.assign(b, b - learning_rate * tf.reduce_sum(d_b)), ] prediction = tf.argmax(y_pred, 1) acct_mat = tf.equal(tf.argmax(y_pred,1), tf.argmax(target,1)) acct_res = tf.reduce_mean(tf.cast(acct_mat, tf.float32)) <file_sep>/tensorflow/Linear Regression Matrix/실습Lab4-1.py import tensorflow as tf x_data = [[73., 80., 75.],[93.,88.,93.],[89.,91.,90.],[96.,98.,100],[73.,66.,70.]] y_data = [[152.],[185.],[180.],[196.],[142.]] X = tf.placeholder(tf.float32, shape=[None, 3]) Y = tf.placeholder(tf.float32, shape=[None, 1]) W = tf.Variable(tf.random_normal([3,1]),name='weight') b = tf.Variable(tf.random_normal([1]), name='bias') hypothesis = tf.matmul(X,W)+b cost = tf.reduce_mean(tf.square(hypothesis - Y)) optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5) train = optimizer.minimize(cost) sess = tf.Session() sess.run(tf.global_variables_initializer()) for step in range(2001): cost_val, hy_val,_ = sess.run([cost,hypothesis,train],feed_dict={X:x_data, Y:y_data}) if step %10 == 0: print(step, "cost:",cost_val," |nprediciton: |n",hy_val) <file_sep>/tensorflow/Rnn/12-5 stock.py import tensorflow as tf import numpy as np import matplotlib import os tf.set_random_seed(777) if "DISPLAY" not in os.environ: matplotlib.use('Agg') import matplotlib.pyplot as plt def MinMaxScaler(data): numerator = data - np.min(data,0) denomiator = np.max(data,0) - np.min(data,0) return numerator / (denominator + 1e-7) seq_length = 7 data_dim =5 hidden_dim = 10 output_dim = 1 learning_rate = 0.01 ireations= 500 xy = np.loadtxt('https://github.com/hunkim/DeepLearningZeroToAll/blob/master/data-02-stock_daily.csv', delimiter=',') xy = xy[::-1] train_size =int(len(xy) * 0.7) train_set = xy[0:train_size] test_set = xy[train_size - seq_length] train_set = MinMaxScaler(train_set) test_set = MinMaxScaler(test_set) def build_dataset(time_series, seq_length): dataX = [] dataY = [] for i in range(0, len(time_series) - seq_length): _x = time_series[i:i+swq_length, :] _y = time_series[i+seq_length, [-1]] print(_x,"->",_y) dataX.append(_x) dataY.append(-y) return np.array(dataX), np.array(dataY) trainX, trainY = build_dataset(train_set, seq_length) testX, testY = build_dataset(test_set, seq_length) X = tf.placeholder(tf.float32, [None, seq_length, data_dim]) Y = tf.placeholder(tf.float32, [None, 1]) cell = tf.contrib.rnn.BacsicLSTMCell( num_units=hidden_dim, state_is_tuple=True, activation=tf.tanh) outputs, _states = tf.nn.dynamic_rnn(cell,X,dtype=tf.float32) Y_pred = tf.contrib.layers.fully_connected(outputs[:-1], output_dim, activation_fn=None) loss =tf.reduce_sum(tf.square(Y_pred -Y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train =optimizer.minimize(loss) targets = tf.placeholder(tf.float32, [None,1]) rmse = tf.sqrt(tf.reduce_mean(tf.square(targets - prediction))) with tf.Session() as sess: init = tf.globale_variables_initializer() sess.run(init) for i in range(iterations): _,step_loss = sess.run([train, loss], feed_dict={X:trainX, Y:trainY}) print("[step: {}] loss: {}".format(i, step_loss)) test_predict = sess.run(Y_pred, feed_dict={X:testX}) rmse_val = sess.run(rmse, feed_dict={ targets: testY, predictions: test_predict}) print("RMSE: {}".format(rmse_val)) plt.plot(TestY) plt,plot(test_predict) plt.xlabel("time perid") plt.ylabel("stock price") plt.show() <file_sep>/tensorflow/Linear Regression Matrix/실습4-2.py import tensorflow as tf filename_queue = tf.train.string_input_producer(['data-01-test-score.csv'],shuffle=False,name='filename_queue') reader = tf.TextLineReader() key, value = reader.read(filename_queue) record_defaults = [[0.],[0.],[0.],[0.]] xy = tf.decode_csv(value, record_defaults=record_default) train_x_batch, train_y_batch = tf.train.batch([xy[0:-1],xy[-1:]],batch_size=10) X = tf.placeholder(tf.float32, shape=[None, 3]) Y = tf.placeholder(tf.float32, shape=[None, 1]) W = tf.Variable(tf.random_normal([3,1]), name='weight') b = tf.Variable(tf.random_normal([1]), name ='bias') hypothesis = tf.matmul(X,W)+b cost = tf.reduce_mean(tf.square(hypothesis - Y)) optimizer = tf.GradientDescentOptimizer(learning_rate=1e-5) train = optimizer.mininize(cost) sess = tf.Session() sess.run(tr.global_variables_initializer()) cord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) for step ni range(2001): x_batch,y_batch = sess.run([train_x_batch, train_y_batch]) cost_val, hy_val,_ = sess.run(cost,hypothesis,train), feed_dict=[X;x_batch , Y:y_batch] if step in range(2001): print(step,"cost:", cost_val,"prediction:", hy_val) coord.request_stop() coord.join(threads) <file_sep>/tensorflow/Deep neural netwark/9-5 Linear backpropagation.py import tensorflow as tf tf.set_random_seed(777) x_data = [[1.], [2.], [3.]] y_data = [[1.], [2.], [3.]] X = tf.placeholder(tf.float32, shape=[None,1]) Y = tf.placeholder(tf.float32, shape=[None,1]) W = tf.Variable(tf.truncated_normal([1,1])) b = tf.Variable(5.) hypothesis = tf.matmul(X,W) + b assert hypothesis.shape.as_list() == Y.shape.as_list() diff = (hypothesis - Y) d_l1 = diff d_b = d_l1 d_w =tf.matmul(tf.transpose(X),d_l1) print(X, W, d_l1,d_w) learning_rate = 0.1 step = [ tf.assign(W, W-learning_rate*d_w), tf.assign(b, b-learning_rate*tf.reduce_mean(d_b)), ] RMSE = tf.reduce_mean(tf.square((Y - hypothesis))) sess = tf.InteractiveSession() init = tf.global_variables_initializer() sess.run(init) for i in range(1000): print(i, sess.run([step,RMSE], feed_dict={X:x_data,Y:y_data})) print(sess.run(hypothesis, feed_dict={X:x_data})) <file_sep>/tensorflow/softmax/Lab6-1.py import tensorflow as tf x_data = [[1,2,1,1],[2,1,3,2],[3,1,3,4],[4,1,5,5],[1,7,5,5],[1,2,5,6],[1,6,6,6],[1,7,7,7]] y_data = [[0,0,1],[0,0,1],[0,1,0],[0,1,0],[0,1,0],[1,0,0],[1,0,0]] X =tf.placeholder("float",[None, 4]) Y =tf.placeholder("float",[None,3]) nb_classes = 3 W = tf.Variable(tf.random_normal([4,nb_classes]), name="weight") b = tf.Variable(tf.random_normal([nb_classes]), name="bias") hypothesis = tf.nn.softmax(tf.matmul(X,W)+b) cost = tf.reduce_mean(-tf.reduce_sum(Y*tf.log(hypothesis), axis=1)) optimizer = tf.train.GradientDescentOptimizer(learning_rate= 0.01).minimize(cost) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for step in range(2001): sess.run(optimizer, feed_dict={X: x_data , Y: y_data}) if step % 200 == 0: print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}))
e0bad6b877e709832dc1802b7fc94f5e9e0c1604
[ "Python" ]
18
Python
chldyddnjs/dL-project
3f377004c96fef6392bdde7319bd796bd3da57ea
ada136733be26e26eb7974d78454b225c0d7412a
refs/heads/master
<repo_name>SantiagoNoguera/Sincronizado<file_sep>/index.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <?php $persona=[ "nombre"=>"Pedro", "apellido"=>"Sánchez", "edad"=>50 ]; foreach($persona as $valor){ echo "$valor <br>"; } ?> </body> </html>
98bf344c1c8555b00d2881186e0995ce632d1141
[ "PHP" ]
1
PHP
SantiagoNoguera/Sincronizado
0531cd656c952b92861757569a0033d8e1371a24
5d9a64ef1b711180c63597608a5135da51200edd
refs/heads/master
<repo_name>fallon7284/portfolio<file_sep>/src/projects.js module.exports = [ { name: 'Pixalive', image: require('../src/images/pixalive.png'), description: 'Pixalive is a free, multi-user, real-time editor' + ' for creating animated sprites and pixel art. It was built with' + ' only functional components using React-Hooks ' + 'along with Socket.io, HTML Canvas, and PostgreSQL.', deployed: 'https://pixalive.herokuapp.com', github: 'https://github.com/pixalive/pixalive', }, { name: 'Corona Tracker', image: require('../src/images/coronatracker.png'), description: 'CoronaTracker is an easy-to-use and accessible progressive web application that helps you monitor your wellness and stay informed during the COVID-19 crisis, designed by an open-source community invested in public health.', deployed: 'https://coronatrackerbeta.com/', github: 'https://github.com/COVID-19-electronic-health-system/Corona-tracker', }, { name: 'Swine Sweeper', image: require('../src/images/SwineSweeper.gif'), description: 'Pig-Themed Minesweeper Game.', deployed: 'https://www.brendanfallon.dev/swinesweeper', onSite: true, github: 'http://github.com/fallon7284/swine-sweeper', }, { name: 'Explore Outdoors', image: require('../src/images/Explore.gif'), description: "A personal project, Google Maps- and Mountain Project-based React application along with Node/Express backend finds a user's location (or takes user input as address or location name and centers map to that location) and displays nearby hikes, climbs, and camping areas.", deployed: 'http://explore-outdoors.herokuapp.com', github: 'http://github.com/fallon7284/explore-outdoors', }, { name: 'CatOrNah?', image: require('../src/images/catornah.jpg'), description: 'For a second project at Fullstack Academy,' + ' students were challenged to learn and implement a new technology during a' + ' four-day solo project. CatOrNah? is a React Native ' + ' camera application using the Clarifai image-recognition API to allow a user' + ' to snap a photo and identify the subject as either a cat... or nah.', deployed: null, github: 'https://github.com/fallon7284/catornah-', }, { name: '<NAME>', image: require('../src/images/graceShopper.png'), description: 'The first team project from my time at Fullstack Academy,' + 'Grace Shopper was a Full Stack mock e-commerce web application.', deployed: 'https://sellinbags.herokuapp.com', github: 'https://github.com/graceshoppingbags/sellinbags', }, { name: 'This Portfolio Site!', image: require('../src/images/projects.png'), description: 'This site was created with Create React App along with a Node/Express backend to allow for the comments section' + ' which includes the ability to reply to comments. Style is almost entirely CSS other than the top bar component and the message form inputs.', // deployed: 'https://sellinbags.herokuapp.com', github: 'https://github.com/fallon7284/portfolio', }, { name: 'Like what you see?', image: require('../src/images/happy.gif'), description: "I'd love to hear from you. Click contact above to leave a comment or to send me an email.", github: 'http://github.com/fallon7284', }, ] <file_sep>/src/components/index.js import Home from './Home' import Projects from './Projects' import Bio from './Bio' import Contact from './Contact' import TopBar from './topBar' import Resume from './Resume' import SwineSweeper from './SwineSweeper' export { Home, Projects, Bio, Contact, TopBar, Resume, SwineSweeper } <file_sep>/src/components/Home.js import React from 'react' import { Link } from 'react-router-dom' const cartoon = require('../images/devToon.png') // import TopBar from './topBar' // import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' export default () => { return ( <div> <div className="home"> <Link to="/bio" style={{ textDecoration: 'none', color: 'black' }} rel="prefetch" > <div className="quote"> <div className="quote1">{'{ brendanFallon: '}</div> <div className="quote2"> {"['Fullstack', 'Software', 'Engineer']}"} </div> </div> <img src={cartoon}></img> </Link> </div> </div> ) } <file_sep>/src/components/Bio.js import React from 'react' import TopBar from './topBar' import { Link } from 'react-router-dom' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' const me = require('../images/me.jpg') export default () => { return ( <div className="bio" style={{ display: 'block' }}> <MuiThemeProvider> <TopBar /> </MuiThemeProvider> <div className="bio-body"> <div style={{ display: 'flex' }}> <div style={{ display: 'inline-block' }}> <div>Hi. I'm Brendan. I'm a Software Engineer.</div> <div> I specialize in full stack JavaScript utilizing{' '} <span>Node</span> and <span>Express</span> on the back end, <span>React</span> and <span>Redux</span>{' '} on the front end, <span>PostgreSQL</span> databases and, of course, <span>HTML5</span> and{' '} <span>CSS3</span>. </div> </div> </div> <div className="middle"> <img style={{ marginRight: '1%', marginBottom: '1%' }} src={me} /> <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', }} > <div> Here I am receiving my certificate of completion on my last day at Fullstack Academy! </div> <div> Want to know more about how I got here? Well... </div> </div> </div> <div> In December of 2018, after completing a one-week bootcamp prep course at Fullstack Academy, I decided that I wanted to change my life by changing my career path, and I enrolled in the full-time immersive program at Fullstack Academy. </div> <br /> <div> I love building software that is functional and provides a delightful user experience. From <span>REST API</span>{' '} design to reusable <span>React</span> components to complex{' '} <span>state management</span>, I am focused and driven to master the technologies that underpin visually appealing, fast, and functional software. </div> <br /> <div> <Link style={{ textDecoration: 'none' }} to="/projects"> <b className="link-bio-projects"> Check out some of my work! </b> </Link> </div> </div> </div> ) } <file_sep>/src/components/Contact.js import React from 'react' import TopBar from './topBar' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' // import { FaLinkedin, FaGithub } from 'react-icons/fa' import ContactForm from './ContactForm' import Message from './Message' import axios from 'axios' const github = require('../images/github.png') const linkedin = require('../images/linked.svg') export default class Contact extends React.Component { constructor() { super() this.state = { userName: '', userEmail: '', message: '', isReplyTo: null, replyingTo: { name: '', message: '' }, messages: [], commenting: false, } this.handleSubmit = this.handleSubmit.bind(this) } componentDidMount() { this.getComments() } async getComments() { try { const { data } = await axios.get( 'https://portfolio-comments.herokuapp.com/comments' ) this.setState({ messages: data }) } catch (error) { console.log(error) } } handleChange = e => { this.setState({ [e.target.name]: e.target.value }) } comment = () => { this.setState({ commenting: !this.state.commenting, isReplyTo: null }) window.scrollTo(0, 0) } closeContact = () => { this.setState({ commenting: false, isReplyTo: null, replyingTo: { name: '', message: '' }, }) } reply = (name, message, id) => { const ellipse = message.length > 20 ? '...' : '' message = message.slice(0, 20) + ellipse this.setState({ commenting: true, isReplyTo: id, replyingTo: { name, message }, }) } messageValid = (userName, userEmail, message) => { return ( userName.length > 0 && userEmail.length > 0 && !!this.isEmail(userEmail) && !!message ) } async handleSubmit(e) { const { userName, userEmail, message, isReplyTo } = this.state const body = { userName, userEmail, message, isReplyTo, replies: [] } try { const { data } = await axios.post( 'https://portfolio-comments.herokuapp.com/comments', body ) console.log(data) let messages if (data.isReplyTo) { messages = this.state.messages.map(m => { if (m.id === data.isReplyTo) { m.replies.push(data) } return m }) } else messages = [data, ...this.state.messages] this.setState({ messages: [...messages], userEmail: '', userName: '', message: '', isReplyTo: null, commenting: false, }) } catch (error) { console.log(error) } } isEmail = email => { const regex = /^([A-z\d\.-]+)@([A-z\d-]+)\.([A-z]{2,8})(\.[A-z]{2,8})?$/ return regex.exec(email) !== null } render() { const { userName, userEmail, message } = this.state return ( <div> <MuiThemeProvider> <TopBar /> </MuiThemeProvider> <div className="contact"> <div className="contact-left"> <div className="contact-me"> <div className="link-icons" style={{ marginTop: '5px' }} > <a href="http://linkedin.com/in/brendanfallondev" target="blank" rel="noopener noreferrer" > {/* <FaLinkedin className="icons" /> */} <img style={{ width: '8vh', height: 'auto' }} src={linkedin} /> </a> <a href="http://github.com/fallon7284" target="blank" rel="noopener noreferrer" > {/* <FaGithub className="icons" /> */} <img style={{ width: '8vh', height: 'auto' }} src={github} /> </a> </div> If you'd like to get in touch with me, you can leave a message below, or click the email button in the top bar. I'd love to hear from you. </div> <div className={`comment-button${ this.state.commenting ? '-open' : '' }`} style={{ marginTop: '1vh', fontFamily: 'nick', cursor: 'pointer', }} onClick={() => { this.comment() }} > Leave a Comment </div> <div className="form-area"> {this.state.commenting && ( <ContactForm closeContact={this.closeContact} replyingTo={this.state.replyingTo} className="comment-form" handleSubmit={this.handleSubmit} messageValid={this.messageValid( userName, userEmail, message )} handleChange={this.handleChange} state={this.state} /> )} </div> </div> <div className="messages"> <div className="comments-title">COMMENTS</div> <div className="messages-body"> {this.state.messages.map(m => { return ( <Message replyClick={() => this.reply( m.userName, m.message, m.id ) } key={m.id} number={m.id} message={m.message} userName={m.userName} userEmail={m.userEmail} createdAt={m.createdAt} isReplyTo={m.isReplyTo} replies={m.replies} /> ) })} </div> </div> </div> </div> ) } } <file_sep>/src/components/ProjectThumb.js import React, { useState } from 'react' const github = require('../images/github.png') export default ({ p }) => { const [hover, setHover] = useState(false) const deployedOrGithub = p.deployed ? p.deployed : p.github console.log(p.onSite) return ( <div className="thumb"> <div className="project"> <a target={p.onSite ? '_self' : 'blank'} rel="noopener noreferrer" href={deployedOrGithub} style={{ textDecoration: 'none', }} > {p.name} </a> <hr /> </div> <div className="project-body"> <div className="details"> <a target={p.onSite ? '_self' : 'blank'} rel="noopener noreferrer" href={deployedOrGithub} > <img src={p.image} alt={p.name}></img> </a> </div> <div className="details"> <p className="description">{p.description}</p> <a target="blank" rel="noopener noreferrer" href={p.github}> <img style={{ height: hover ? '9vw' : '8vw' }} src={github} onMouseOver={() => setHover(true)} onMouseOut={() => setHover(false)} ></img> </a> <div className="clearfix"></div> </div> </div> </div> ) } <file_sep>/src/components/SwineSweeper.js import React from 'react' import TopBar from './topBar' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' export default () => { return ( <div> <MuiThemeProvider> <TopBar /> </MuiThemeProvider> <iframe style={{ height: '100vh', width: '100%', }} title="brendan-fallon-resume" src="https://sharp-cray-74c6dd.netlify.com/" ></iframe> </div> ) } <file_sep>/src/components/MessageBody.js import React from 'react' export default ({ userName, createdAt, message, replyName }) => { const date = new Date(createdAt).toDateString() const replyString = replyName !== undefined ? `${userName} replied to ${replyName}: ` : '' const style = replyName ? { width: '95%', alignSelf: 'right', backgroundColor: '#e7e7e7', marginLeft: '5%', } : {} return ( <div className="message" style={style}> <div className="name-date"> <div>{userName}</div> <div>{date}</div> </div> <div className="message-content">{`${replyString}${message}`}</div> </div> ) }
c8afeaf936b20f3b139e7dcad5ba9e1930cea3e8
[ "JavaScript" ]
8
JavaScript
fallon7284/portfolio
7d2e684a9ebd614c4fc41f6b454be293afb68c2d
bf0e921f9903e7be95585cae2ef319e36f9fba04
refs/heads/master
<file_sep>class test { constructor() { this.#foo = 1 } }<file_sep># ESLint Issue - JavaScript Private Member This repo provides a repro for ESLint not recognizing private class member syntax.
25e5dd0410ad00d16f1d6bd2a79d3da2e9aede08
[ "JavaScript", "Markdown" ]
2
JavaScript
samusstrike/eslintIssueJSPrivateMember
e4e8fb2a5e1fd18fc0a4b5aaeaa1e3d4e600aaba
2c10b8bf356ee284ed18b95c575a1e543145b41d
refs/heads/main
<file_sep>This is my personal blog. Feel free to visit :) <file_sep>const BLACKLISTED_KEY_CODES = [ 38 ]; const COMMANDS = { help: 'Supported commands: <span class="code">about</span>, <span class="code">experience</span>, <span class="code">education</span>, <span class="code">articles</span>, <span class="code">skills</span>, <span class="code">certifications</span>, <span class="code">contact</span>', about: "Cyber Security practitioner capable of strategizing, architecting, building and maturing cyber security initiatives. Passionate about analyzing cyber security risks and translating them to actionable countermeasures. 8 years+ of working experience in Cyber Security domain. University Masters degree in Cybersecurity and Forensics from University of Bedfordshire (UK).", skills: "Security Engineering | Threat and Vulnerability Management | Threat Hunting & Intelligence | Red teaming | Security Operation Analysis | Penetration Testing", education: "MSc. in Computer Security & Forensics<br> B.Tech in Computer Engineering", experience:'<span class="code">Total experience: 9 years</span><br>Security Engineering Manager - Tesco - United Kingdom - Present<br> Manager - KPMG New Zealand - New Zealand - 3 years 6 months<br>Security Consultant - NotSosecure - India - 8 months<br>Security Engineer - Zebpay - India - 6 months<br>Security Analyst (Enterprise Customer Service) - India - 1 year 9 months<br>Security Analyst - LetNurture - India - 1 year 6 months', certifications: "SANS MGT 516 - Enterprise and Cloud Vulnerability Management<br>OSCP - Offensive Security Certified Professional<br>CTIA - Cyber Threat Intelligence Analyst<br>CEH - Certified Ethical Hacker<br>CCFH - Certified Crowdstrike Falcon Hunter<br>CCFA - Certified CrowdStrike Falcon Administrator", articles: "<a href='https://github.com/iamthefrogy/FYI' class='success link'>FYI - https://github.com/iamthefrogy/FYI </br> This GitHub repo has the collection of my entire career's work/research/thoughts/webinars/articles/publications.</a>", contact: "You can contact me on any of following links:<br><a href='https://www.linkedin.com/in/chintangurjar/' class='success link'>Linkedin</a>, <a href='mailto:<EMAIL>' class='success link'>Email</a>, <a href='https://twitter.com/iamthefrogy/' class='success link'>Twitter</a>" }; let userInput, terminalOutput; const app = () => { userInput = document.getElementById("userInput"); terminalOutput = document.getElementById("terminalOutput"); document.getElementById("dummyKeyboard").focus(); console.log("Application loaded"); }; const execute = function executeCommand(input) { let output; input = input.toLowerCase(); if (input.length === 0) { return; } output = `<div class="terminal-line"><span class="success">➜</span> <span class="directory">~</span> ${input}</div>`; if (!COMMANDS.hasOwnProperty(input)) { output += `<div class="terminal-line">no such command: ${input}</div>`; console.log("Oops! no such command"); } else { output += COMMANDS[input]; } terminalOutput.innerHTML = `${ terminalOutput.innerHTML }<div class="terminal-line">${output}</div>`; terminalOutput.scrollTop = terminalOutput.scrollHeight; }; const key = function keyEvent(e) { const input = userInput.innerHTML; if (BLACKLISTED_KEY_CODES.includes(e.keyCode)) { return; } if (e.key === "Enter") { execute(input); userInput.innerHTML = ""; return; } userInput.innerHTML = input + e.key; }; const backspace = function backSpaceKeyEvent(e) { if (e.keyCode !== 8 && e.keyCode !== 46) { return; } userInput.innerHTML = userInput.innerHTML.slice( 0, userInput.innerHTML.length - 1 ); }; document.addEventListener("keydown", backspace); document.addEventListener("keypress", key); document.addEventListener("DOMContentLoaded", app);
8a94fea46b705278a109ea4c062cfe10ac668f75
[ "Markdown", "JavaScript" ]
2
Markdown
iamthefrogy/iamthefrogy.github.io
7d6bfa9127e3b6957ab11bbc8e94a331b98b0cc8
4e08e70d22d2121d6f18eb0b5bea5260fb1a0053
refs/heads/master
<repo_name>nelomr/vue-trello<file_sep>/src/store/store.js import Vue from 'vue'; import Vuex from 'vuex'; import createPersistedState from 'vuex-persistedstate'; import initialBoard from '../use/initial-board'; import actions from './actions'; import mutations from './mutations'; Vue.use(Vuex); const board = initialBoard; export default new Vuex.Store({ plugins: [createPersistedState({ storage: window.sessionStorage })], state: { board }, actions, mutations, getters: { getTask(state) { return (id) => { for (const column of state.board.columns) { for (const task of column.tasks) { if (task.id === id) { return task; } } } } } } }) <file_sep>/README.md # Drello A simple trello with vue, you can add delete and drop de task, i've added persistence in order to mantain de actions while you don't close the tab. Demo [https://nelomr.github.io/vue-trello/](https://nelomr.github.io/vue-trello/) ## Project setup ``` yarn install ``` ### Compiles and hot-reloads for development ``` yarn serve ``` ### Compiles and minifies for production ``` yarn build ``` ### Tests ``` yarn test ``` ### Lints and fixes files ``` yarn lint ``` ### Customize configuration See [Configuration Reference](https://cli.vuejs.org/config/). <file_sep>/src/store/mutations.js export default { changeDescription(state, {description, task}) { task.description = description; }, changeTitle(state, {title, task}) { task.name = title; }, addTask(state, {tasks, name}) { tasks.push( { description: '', name: name, id: Math.floor(Math.random() * Date.now()), user: null } ); }, removeTask(state, {tasks, indexTask}) { tasks.splice(indexTask, 1); }, updateColumnsData(state, {tasks, indexColumn}) { state.board.columns[indexColumn].tasks = tasks; } }<file_sep>/src/use/initial-board.js export default { name: 'initialBoard', columns: [ { name: 'todo', tasks: [ { description: '', name: 'first task', id: 1, user: null }, { description: '', name: 'second task', id: 2, user: null }, ] }, { name: 'done', tasks: [ { description: '', name: 'last task', id: 3, user: null } ] } ] }
8ace7fc0cde83a2cee8d2845bc78d9e0c989fcf1
[ "JavaScript", "Markdown" ]
4
JavaScript
nelomr/vue-trello
a459116b9409188878ae5c68d1ac9fcdf9a61705
124539329e3a5b627e2f63b7f52733ddc68c8433
refs/heads/master
<file_sep><?php $name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; $url = isset($_POST['url']) ? htmlspecialchars($_POST['url']) : ''; echo '网站名: ' . $name; echo "\n"; echo 'URL 地址: ' .$url; echo ".<br>"; echo "今天是 " . date("Y-m-d") . "<br>"; $time=date("w",time( )); $array = ["星期天周日,双色球开奖","星期一周一,大乐透开奖","星期二 周二,双色球开奖","星期三周三大乐透开奖","星期四周四,双色球开奖","星期五周 五,七乐彩开奖","星期六周六,大乐透开奖"]; $time=date("w",time( )); echo "今天是 " . date("Y/m/d"); echo $array[$time]; ?> <file_sep><!DOCTYPE html> <html> <head> //引用jquery //引用jquery </head> <body> //以上是html <?php error_reporting(E_ALL^E_NOTICE^E_WARNING); //php关闭错误报告 /* 注释――必须把php代码放到 form标签内 点击提交按钮不跳转 */ echo "<br>"; echo "定胆随机后―――>随机的前区号码"; echo "<br>"; echo "<br>"; //定胆随机核心代码 $a2=$_POST['c']; //把c数组赋值给a2 //创建a1数组 //用于比较数组得到差集 //得到数组差集前先创建数组赋值给$a1 //得出a1数组和c数组的差集 $a1=array("1"=>"1","2"=>"2","3"=>"3","4"=>"4","5"=>"5","6"=>"6","7"=>"7","8"=>"8","9"=>"9","10"=>"10","11"=>"11","12"=>"12","13"=>"13","14"=>"14","15"=>"15","16"=>"16","17"=>"17","18"=>"18","19"=>"19","20"=>"20","21"=>"21","22"=>"22","23"=>"23","24"=>"24","25"=>"25","26"=>"26","27"=>"27","28"=>"28","29"=>"29","30"=>"30","31"=>"31","32"=>"32","33"=>"33","34"=>"34","35"=>"35"); $result2=array_diff_assoc($a1,$a2); //得出a1数组和c数组的差集 $arr4=$_POST['c']; //把c数组赋值给arr4 $x=mt_rand(5,6); //取随机数 $y=count($arr4);//获取C数组长度 $xy=$x - $y; //减法计算 $b5=mt_rand($xy,$xy); //设定位数值 $arr5=array_rand($result2,$b5); //在勾选号码中随机 $arr4=$_POST['c']; // 把c数组赋值给arr4 $he= array_merge($arr5,$arr4); //合并arr5和arr4数组 sort($he); //按照顺序排列数组 $hejoin=join("+", $he); //把数组转换成字符串 echo $hejoin; //输出结果集 echo "<br>"; echo "<br>"; echo "定胆随机后―――>随机的后区号码"; echo "<br>"; echo "<br>"; $arr2=$_POST['b']; //把b数组赋值给arr2 $b1=mt_rand(2,2); //设定位数值 echo " "; $array_name=array_rand($arr2,$b1); //在勾选号码中随机 $join2=join(" ", $array_name); echo $join2; //输出结果集 echo "<br>"; echo "<br>"; ?> <br> <br> <a href="jo66from22dlt66from22jo.php" target="_blank" style="font-size:38px;">点我,返回复选框,独立版主页</a> </form>
ac9a6bedf6d306c8e79c2d27fbc822a53a5f278e
[ "PHP" ]
2
PHP
mgit0028/haoni4094
3d8f8fef93c3ff10544360504d36fa58e5d7a302
0e04e7ed0685837c31f1eefb468aaf754c120a7d
refs/heads/master
<file_sep>using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WinFormDBProject { public partial class Form1 : Form { public Form1() { InitializeComponent(); } MySqlConnection conn; MySqlDataAdapter dataAdapter; DataSet dataSet; private void Form1_Load(object sender, EventArgs e) { conn = new MySqlConnection("server=localhost;port=3306;database=mydb;uid=root;pwd=<PASSWORD>"); dataAdapter = new MySqlDataAdapter("SELECT * FROM book", conn); dataSet = new DataSet(); dataAdapter.Fill(dataSet, "book"); dataGridView1.DataSource = dataSet.Tables["book"]; //dataSet.Clear(); //dataAdapter.Fill(dataSet, "book"); //dataGridView1.DataSource = dataSet.Tables["book"]; } #region Table Select private void RbBook_CheckedChanged(object sender, EventArgs e) { dataAdapter = new MySqlDataAdapter("SELECT * FROM book", conn); dataSet = new DataSet(); dataAdapter.Fill(dataSet, "book"); dataGridView1.DataSource = dataSet.Tables["book"]; gbBook.Visible = true; gbCustomer.Visible = false; gbOrders.Visible = false; } private void RbCustomer_CheckedChanged(object sender, EventArgs e) { dataAdapter = new MySqlDataAdapter("SELECT * FROM customer", conn); dataSet = new DataSet(); dataAdapter.Fill(dataSet, "customer"); dataGridView1.DataSource = dataSet.Tables["customer"]; gbBook.Visible = false; gbCustomer.Visible = true; gbOrders.Visible = false; } private void RbOrders_CheckedChanged(object sender, EventArgs e) { dataAdapter = new MySqlDataAdapter("SELECT orderid, custid, bookid, saleprice, orderdate FROM orders", conn); dataSet = new DataSet(); dataAdapter.Fill(dataSet, "orders"); dataGridView1.DataSource = dataSet.Tables["orders"]; gbBook.Visible = false; gbCustomer.Visible = false; gbOrders.Visible = true; } #endregion private void BtnSelect_Click(object sender, EventArgs e) { if (rbBook.Checked) { #region Book Table Select string queryStr; string[] conditions = new string[5]; conditions[0] = (tbBookID.Text != "") ? "bookid=@bookid" : null; conditions[1] = (tbBookName.Text != "") ? "bookname=@bookname" : null; conditions[2] = (tbBookPublisher.Text != "") ? "publisher=@publisher" : null; conditions[3] = (tbPrice.Text != "") ? "price=@price" : null; //질문!!!!!!!!!!!!!!!!!!!!!! if (conditions[0] != null || conditions[1] != null || conditions[2] != null || conditions[3] != null) //만약 데이터가 다 들어있으면 { queryStr = $"SELECT * FROM book WHERE "; bool firstCondition = true; //firstCondition을 true로 해두고 for (int i = 0; i < conditions.Length; i++) //conditions의 길이(5)만큼 for문을 돌려서 { if (conditions[i] != null) if (firstCondition) { queryStr += conditions[i]; firstCondition = false; } else { queryStr += " and " + conditions[i]; } } } else { queryStr = "SELECT * FROM book"; } #region SelectCommand 객체 생성 및 Parameters 설정 dataAdapter.SelectCommand = new MySqlCommand(queryStr, conn); dataAdapter.SelectCommand.Parameters.AddWithValue("@bookid", tbBookID.Text); dataAdapter.SelectCommand.Parameters.AddWithValue("@bookname", tbBookName.Text); dataAdapter.SelectCommand.Parameters.AddWithValue("@publisher", tbBookPublisher.Text); dataAdapter.SelectCommand.Parameters.AddWithValue("@price", tbPrice.Text); #endregion try { conn.Open(); dataSet.Clear(); if (dataAdapter.Fill(dataSet, "book") > 0) dataGridView1.DataSource = dataSet.Tables["book"]; else MessageBox.Show("찾는 데이터가 없습니다."); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } #endregion } else if(rbCustomer.Checked) { #region Customer Table select string queryStr; string[] conditions = new string[5]; conditions[0] = (tbCustID.Text != "") ? "custid=@custid" : null; conditions[1] = (tbCustName.Text != "") ? "name=@name" : null; conditions[2] = (tbCustAddress.Text != "") ? "address=@address" : null; conditions[3] = (tbCustPhone.Text != "") ? "phone=@phone" : null; //질문!!!!!!!!!!!!!!!!!!!!!! if (conditions[0] != null || conditions[1] != null || conditions[2] != null || conditions[3] != null) //만약 데이터가 다 들어있으면 { queryStr = $"SELECT * FROM customer WHERE "; bool firstCondition = true; //firstCondition을 true로 해두고 for (int i = 0; i < conditions.Length; i++) //conditions의 길이(5)만큼 for문을 돌려서 { if (conditions[i] != null) if (firstCondition) { queryStr += conditions[i]; firstCondition = false; } else { queryStr += " and " + conditions[i]; } } } else { queryStr = "SELECT * FROM customer"; } #region SelectCommand 객체 생성 및 Parameters 설정 dataAdapter.SelectCommand = new MySqlCommand(queryStr, conn); dataAdapter.SelectCommand.Parameters.AddWithValue("@custid", tbCustID.Text); dataAdapter.SelectCommand.Parameters.AddWithValue("@name", tbCustName.Text); dataAdapter.SelectCommand.Parameters.AddWithValue("@address", tbCustAddress.Text); dataAdapter.SelectCommand.Parameters.AddWithValue("@phone", tbCustPhone.Text); #endregion try { conn.Open(); dataSet.Clear(); if (dataAdapter.Fill(dataSet, "customer") > 0) dataGridView1.DataSource = dataSet.Tables["customer"]; else MessageBox.Show("찾는 데이터가 없습니다."); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } #endregion } else { #region Orders Table Select string queryStr; string[] conditions = new string[5]; conditions[0] = (tbOrderID.Text != "") ? "orderid=@orderid" : null; conditions[1] = (tbCustomerID.Text != "") ? "custid=@custid" : null; conditions[2] = (tbBooksID.Text != "") ? "bookid=@bookid" : null; conditions[3] = (tbSalePrice.Text != "") ? "saleprice=@saleprice" : null; conditions[4] = (tbOrderDate.Text != "") ? "orderdate=@orderdate" : null; //질문!!!!!!!!!!!!!!!!!!!!!! if (conditions[0] != null || conditions[1] != null || conditions[2] != null || conditions[3] != null || conditions[4] != null) //만약 데이터가 다 들어있으면 { queryStr = $"SELECT * FROM orders WHERE "; bool firstCondition = true; //firstCondition을 true로 해두고 for (int i = 0; i < conditions.Length; i++) //conditions의 길이(6)만큼 for문을 돌려서 { if (conditions[i] != null) if (firstCondition) { queryStr += conditions[i]; firstCondition = false; } else { queryStr += " and " + conditions[i]; } } } else { queryStr = "SELECT * FROM orders"; } #region SelectCommand 객체 생성 및 Parameters 설정 dataAdapter.SelectCommand = new MySqlCommand(queryStr, conn); dataAdapter.SelectCommand.Parameters.AddWithValue("@orderid", tbOrderID.Text); dataAdapter.SelectCommand.Parameters.AddWithValue("@custid", tbCustomerID.Text); dataAdapter.SelectCommand.Parameters.AddWithValue("@bookid", tbBooksID.Text); dataAdapter.SelectCommand.Parameters.AddWithValue("@saleprice", tbSalePrice.Text); dataAdapter.SelectCommand.Parameters.AddWithValue("@orderdate", tbOrderDate.Text); #endregion try { conn.Open(); dataSet.Clear(); if (dataAdapter.Fill(dataSet, "orders") > 0) dataGridView1.DataSource = dataSet.Tables["orders"]; else MessageBox.Show("찾는 데이터가 없습니다."); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } #endregion } } private void BtnInsert_Click(object sender, EventArgs e) { if (rbBook.Checked) { #region Book Table insert string[] rowDatas = { tbBookID.Text, tbBookName.Text, tbBookPublisher.Text, tbPrice.Text }; string queryStr = "INSERT INTO book (bookid, bookname, publisher, price) " + "VALUES(@bookid, @bookname, @publisher, @price)"; dataAdapter.InsertCommand = new MySqlCommand(queryStr, conn); dataAdapter.InsertCommand.Parameters.Add("@bookid", MySqlDbType.Int32); dataAdapter.InsertCommand.Parameters.Add("@bookname", MySqlDbType.VarChar); dataAdapter.InsertCommand.Parameters.Add("@publisher", MySqlDbType.VarChar); dataAdapter.InsertCommand.Parameters.Add("@price", MySqlDbType.Int32); //Parameter를 이용한 처리 dataAdapter.InsertCommand.Parameters["@bookid"].Value = rowDatas[0]; dataAdapter.InsertCommand.Parameters["@bookname"].Value = rowDatas[1]; dataAdapter.InsertCommand.Parameters["@publisher"].Value = rowDatas[2]; dataAdapter.InsertCommand.Parameters["@price"].Value = rowDatas[3]; try { conn.Open(); dataAdapter.InsertCommand.ExecuteNonQuery(); dataSet.Clear(); // Clear로 이전 데이터 지우기 dataAdapter.Fill(dataSet, "book"); dataGridView1.DataSource = dataSet.Tables["book"]; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } #endregion } else if (rbCustomer.Checked) { #region Customer Table insert string[] rowDatas = { tbCustID.Text, tbCustName.Text, tbCustAddress.Text, tbCustPhone.Text }; string queryStr = "INSERT INTO customer (custid, name, address, phone) " + "VALUES(@custid, @name, @address, @phone)"; dataAdapter.InsertCommand = new MySqlCommand(queryStr, conn); dataAdapter.InsertCommand.Parameters.Add("@custid", MySqlDbType.Int32); dataAdapter.InsertCommand.Parameters.Add("@name", MySqlDbType.VarChar); dataAdapter.InsertCommand.Parameters.Add("@address", MySqlDbType.VarChar); dataAdapter.InsertCommand.Parameters.Add("@phone", MySqlDbType.VarChar); //Parameter를 이용한 처리 dataAdapter.InsertCommand.Parameters["@custid"].Value = rowDatas[0]; dataAdapter.InsertCommand.Parameters["@name"].Value = rowDatas[1]; dataAdapter.InsertCommand.Parameters["@address"].Value = rowDatas[2]; dataAdapter.InsertCommand.Parameters["@phone"].Value = rowDatas[3]; try { conn.Open(); dataAdapter.InsertCommand.ExecuteNonQuery(); dataSet.Clear(); // Clear로 이전 데이터 지우기 dataAdapter.Fill(dataSet, "customer"); dataGridView1.DataSource = dataSet.Tables["customer"]; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } #endregion } else { #region Orders Table insert string[] rowDatas = { tbOrderID.Text, tbCustomerID.Text, tbBooksID.Text, tbSalePrice.Text, tbOrderDate.Text }; string queryStr = "INSERT INTO orders (orderid, custid, bookid, saleprice, orderdate) " + "VALUES(@orderid, @custid, @bookid, @saleprice, @orderdate)"; dataAdapter.InsertCommand = new MySqlCommand(queryStr, conn); dataAdapter.InsertCommand.Parameters.Add("@orderid", MySqlDbType.Int32); dataAdapter.InsertCommand.Parameters.Add("@custid", MySqlDbType.Int32); dataAdapter.InsertCommand.Parameters.Add("@bookid", MySqlDbType.Int32); dataAdapter.InsertCommand.Parameters.Add("@saleprice", MySqlDbType.Int32); dataAdapter.InsertCommand.Parameters.Add("@orderdate", MySqlDbType.VarChar); //Parameter를 이용한 처리 dataAdapter.InsertCommand.Parameters["@orderid"].Value = rowDatas[0]; dataAdapter.InsertCommand.Parameters["@custid"].Value = rowDatas[1]; dataAdapter.InsertCommand.Parameters["@bookid"].Value = rowDatas[2]; dataAdapter.InsertCommand.Parameters["@saleprice"].Value = rowDatas[3]; dataAdapter.InsertCommand.Parameters["@orderdate"].Value = rowDatas[4]; try { conn.Open(); dataAdapter.InsertCommand.ExecuteNonQuery(); dataSet.Clear(); // Clear로 이전 데이터 지우기 dataAdapter.Fill(dataSet, "orders"); dataGridView1.DataSource = dataSet.Tables["orders"]; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } #endregion } } private void BtnUpdate_Click(object sender, EventArgs e) { if (rbBook.Checked) { #region Book Table update string sql = "UPDATE book SET bookid=@bookid, bookname=@bookname, publisher=@publisher, price=@price where bookid=@bookid"; dataAdapter.UpdateCommand = new MySqlCommand(sql, conn); dataAdapter.UpdateCommand.Parameters.AddWithValue("@bookid", tbBookID.Text); dataAdapter.UpdateCommand.Parameters.AddWithValue("@bookname", tbBookName.Text); dataAdapter.UpdateCommand.Parameters.AddWithValue("@publisher", tbBookPublisher.Text); dataAdapter.UpdateCommand.Parameters.AddWithValue("@price", tbPrice.Text); try { conn.Open(); dataAdapter.UpdateCommand.ExecuteNonQuery(); dataSet.Clear(); // 이전 데이터 지우기 dataAdapter.Fill(dataSet, "book"); dataGridView1.DataSource = dataSet.Tables["book"]; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } #endregion } else if (rbCustomer.Checked) { #region Customer Table update string sql = "UPDATE customer SET custid=@custid, name=@name, address=@address, phone=@phone where custid=@custid"; dataAdapter.UpdateCommand = new MySqlCommand(sql, conn); dataAdapter.UpdateCommand.Parameters.AddWithValue("@custid", tbCustID.Text); dataAdapter.UpdateCommand.Parameters.AddWithValue("@name", tbCustName.Text); dataAdapter.UpdateCommand.Parameters.AddWithValue("@address", tbCustAddress.Text); dataAdapter.UpdateCommand.Parameters.AddWithValue("@phone", tbCustPhone.Text); try { conn.Open(); dataAdapter.UpdateCommand.ExecuteNonQuery(); dataSet.Clear(); // 이전 데이터 지우기 dataAdapter.Fill(dataSet, "customer"); dataGridView1.DataSource = dataSet.Tables["customer"]; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } #endregion } else { #region Orders Table update string sql = "UPDATE orders SET orderid=@orderid, custid=@custid, bookid=@bookid, saleprice=@saleprice, orderdate=@orderdate where orderid=@orderid"; dataAdapter.UpdateCommand = new MySqlCommand(sql, conn); dataAdapter.UpdateCommand.Parameters.AddWithValue("@orderid", tbOrderID.Text); dataAdapter.UpdateCommand.Parameters.AddWithValue("@custid", tbCustomerID.Text); dataAdapter.UpdateCommand.Parameters.AddWithValue("@bookid", tbBooksID.Text); dataAdapter.UpdateCommand.Parameters.AddWithValue("@saleprice", tbSalePrice.Text); dataAdapter.UpdateCommand.Parameters.AddWithValue("@orderdate", tbOrderDate.Text); try { conn.Open(); dataAdapter.UpdateCommand.ExecuteNonQuery(); dataSet.Clear(); // 이전 데이터 지우기 dataAdapter.Fill(dataSet, "orders"); dataGridView1.DataSource = dataSet.Tables["orders"]; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } #endregion }//orders DB update안됨 } private void BtnDelete_Click(object sender, EventArgs e) { if (rbBook.Checked) { #region Book Table delete int id; string sql = "DELETE FROM book WHERE bookid=@bookid"; dataAdapter.DeleteCommand = new MySqlCommand(sql, conn); dataAdapter.DeleteCommand.Parameters.Add("@bookid", MySqlDbType.Int32); id = (int)dataGridView1.SelectedRows[0].Cells["bookid"].Value; dataAdapter.DeleteCommand.Parameters["@bookid"].Value = id; try { conn.Open(); dataAdapter.DeleteCommand.ExecuteNonQuery(); dataSet.Clear(); dataAdapter.Fill(dataSet, "book"); dataGridView1.DataSource = dataSet.Tables["book"]; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } #endregion } else if (rbCustomer.Checked) { #region Customer Table delete int id; string sql = "DELETE FROM customer WHERE custid=@custid"; dataAdapter.DeleteCommand = new MySqlCommand(sql, conn); dataAdapter.DeleteCommand.Parameters.Add("@custid", MySqlDbType.Int32); id = (int)dataGridView1.SelectedRows[0].Cells["custid"].Value; dataAdapter.DeleteCommand.Parameters["@custid"].Value = id; try { conn.Open(); dataAdapter.DeleteCommand.ExecuteNonQuery(); dataSet.Clear(); dataAdapter.Fill(dataSet, "customer"); dataGridView1.DataSource = dataSet.Tables["customer"]; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } #endregion } else { #region Orders Table delete int id; string sql = "DELETE FROM orders WHERE orderid=@orderid"; dataAdapter.DeleteCommand = new MySqlCommand(sql, conn); dataAdapter.DeleteCommand.Parameters.Add("@orderid", MySqlDbType.Int32); id = (int)dataGridView1.SelectedRows[0].Cells["orderid"].Value; dataAdapter.DeleteCommand.Parameters["@orderid"].Value = id; try { conn.Open(); dataAdapter.DeleteCommand.ExecuteNonQuery(); dataSet.Clear(); dataAdapter.Fill(dataSet, "customer"); dataGridView1.DataSource = dataSet.Tables["customer"]; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } #endregion } } private void BtnClear_Click(object sender, EventArgs e) { if (rbBook.Checked) { tbBookID.Clear(); tbBookName.Clear(); tbBookPublisher.Text = ""; tbPrice.Text = ""; } else if (rbCustomer.Checked) { tbCustID.Clear(); tbCustName.Clear(); tbCustAddress.Text = ""; tbCustPhone.Text = ""; } else { tbOrderID.Clear(); tbBooksID.Clear(); tbCustomerID.Clear(); tbSalePrice.Text = ""; tbOrderDate.Text = ""; } } } }
f3d86a0e9b0600aadba047d8f41e2db3fd40002a
[ "C#" ]
1
C#
gmlehd/WinFormDBProject
1d4cbefae6f75407844e97e77662931e916d0be6
8f5ecdf8bf89438ad02cfd267834bf80e8f209ad
refs/heads/master
<repo_name>airtype/httpmessagesrestmiddleware<file_sep>/src/Exceptions/RestException.php <?php namespace HttpMessagesRestMiddleware\Exceptions; use HttpMessages\Exceptions\HttpMessagesException; class RestException extends HttpMessagesException { } <file_sep>/src/Transformers/ArrayTransformer.php <?php namespace HttpMessagesRestMiddleware\Transformers; class ArrayTransformer extends BaseTransformer { public function transform(array $array) { return $array; } } <file_sep>/src/Services/ResponseService.php <?php namespace HttpMessagesRestMiddleware\Services; use HttpMessages\Http\Response; use HttpMessagesRestMiddleware\Http\RestResponse; class ResponseService { /** * Get Response * * @return Response Response */ public function getResponse(Response $response) { $response = new RestResponse($response); return $response; } } <file_sep>/src/Http/RestResponse.php <?php namespace HttpMessagesRestMiddleware\Http; use HttpMessages\Http\CraftResponse as Response; use Craft\ElementCriteriaModel; class RestResponse extends Response { /** * Item * * @var array */ protected $item; /** * Collection * * @var array */ protected $collection; /** * Criteria * * @var Craft\ElementCriteriaModel */ protected $criteria; /** * Constructor * * @param Response $response Response */ public function __construct(Response $response) { foreach (get_object_vars($response) as $property => $value) { $this->$property = $value; } } /** * Get Collection * * @return array Collection */ public function getCollection() { return $this->collection; } /** * With Collection * * @param array $collection Collection * * @return RestResponse RestResponse */ public function withCollection(array $collection) { $new = clone $this; $new->collection = $collection; return $new; } /** * Get Item * * @return Item Item */ public function getItem() { return $this->item; } /** * With Item * * @param mixed $item Item * * @return RestResponse RestResponse */ public function withItem($item) { $new = clone $this; $new->item = $item; return $new; } /** * Get Criteria * * @return ElementCriteriaModel Criteria */ public function getCriteria() { return $this->criteria; } /** * With Criteria * * @param ElementCriteriaModel $criteria Criteria * * @return RestResponse RestResponse */ public function withCriteria(ElementCriteriaModel $criteria) { $new = clone $this; $new->criteria = $criteria; return $new; } } <file_sep>/src/Http/RestRequest.php <?php namespace HttpMessagesRestMiddleware\Http; use HttpMessages\Http\CraftRequest as Request; use Craft\ElementCriteriaModel; class RestRequest extends Request { /** * Criteria * * @var Craft\ElementCriteriaModel */ protected $criteria; /** * Constructor * * @param Request $request Request */ public function __construct(Request $request) { foreach (get_object_vars($request) as $property => $value) { $this->$property = $value; } } /** * Get Criteria * * @return ElementCriteriaModel Criteria */ public function getCriteria() { return $this->criteria; } /** * With Criteria * * @param ElementCriteriaModel|null $criteria Criteria * * @return Rest Request Rest Request */ public function withCriteria(ElementCriteriaModel $criteria = null) { $new = clone $this; $new->criteria = $criteria; return $new; } } <file_sep>/src/Transformers/ContentTransformer.php <?php namespace HttpMessagesRestMiddleware\Transformers; class ContentTransformer extends BaseTransformer { public function transform(array $content) { return $content; } } <file_sep>/src/Transformers/Commerce_OrderTransformer.php <?php namespace HttpMessagesRestMiddleware\Transformers; use Craft\Commerce_OrderModel; class Commerce_OrderTransformer extends BaseTransformer { /** * Transform * * @param Commerce_OrderModel $element Commerce Order * * @return array Commerce Order */ public function transform(Commerce_OrderModel $element) { return [ 'id' => (int) $element->id, 'enabled' => (bool) $element->enabled, 'archived' => (bool) $element->archived, 'locale' => $element->locale, 'localeEnabled' => (bool) $element->localeEnabled, 'itemTotal' => (float) $element->itemTotal, 'baseDiscount' => (float) $element->baseDiscount, 'baseShippingCost' => (float) $element->baseShippingCost, 'totalPrice' => (float) $element->totalPrice, 'totalPaid' => (float) $element->totalPaid, 'dateCreated' => $element->dateCreated, 'dateUpdated' => $element->dateUpdated, 'slug' => $element->slug, 'uri' => $element->uri, 'number' => $element->number, 'couponCode' => $element->couponCode, 'orderStatusId' => (int) $element->orderStatusId, 'dateOrdered' => $element->dateOrdered, 'email' => $element->email, 'datePaid' => $element->datePaid, 'currency' => $element->currency, 'lastIp' => $element->lastIp, 'message' => $element->message, 'returnUrl' => $element->returnUrl, 'cancelUrl' => $element->cancelUrl, 'billingAddressId' => (int) $element->billingAddressId, 'shippingAddressId' => (int) $element->shippingAddressId, 'shippingMethod' => $element->shippingMethod, 'paymentMethodId' => (int) $element->paymentMethodId, 'customerId' => (int) $element->customerId, ]; } } <file_sep>/src/Services/RequestService.php <?php namespace HttpMessagesRestMiddleware\Services; use HttpMessages\Http\CraftRequest as Request; use HttpMessagesRestMiddleware\Http\RestRequest; class RequestService { /** * Get Request * * @param Request $request Request * * @return RestRequest RestRequest */ public function getRequest(Request $request) { $request = new RestRequest($request); $request = $this->withCriteria($request); return $request; } /** * With Criteria * * @param Request $request Request * * @return RestRequest RestRequest */ private function withCriteria(Request $request) { $element_type = $request->getAttribute('elementType'); $element_id = $request->getAttribute('elementId'); $attributes = array_merge($request->getQueryParams(), $request->getAttributes()); $criteria = \Craft\craft()->elements->getCriteria($element_type, $attributes); $pagination_parameter = \Craft\craft()->config->get('paginationParameter', 'restfulApi'); if (isset($criteria->$pagination_parameter)) { $criteria->offset = ($criteria->$pagination_parameter - 1) * $criteria->limit; unset($criteria->$pagination_parameter); } if ($element_id) { $criteria->archived = null; $criteria->fixedOrder = null; $criteria->limit = 1; $criteria->localeEnabled = false; $criteria->offset = 0; $criteria->order = null; $criteria->status = null; $criteria->editable = null; if (is_numeric($element_id)) { $criteria->id = $element_id; } else { $criteria->slug = $element_id; } } return $request->withCriteria($criteria); } } <file_sep>/src/Transformers/BaseTransformer.php <?php namespace HttpMessagesRestMiddleware\Transformers; use HttpMessagesRestMiddleware\Services\ConfigService; use HttpMessagesRestMiddleware\Services\ElementService; use League\Fractal\TransformerAbstract; use Craft\BaseElementModel; use League\Fractal\Manager; use League\Fractal\Serializer\ArraySerializer; use League\Fractal\Resource\Collection; use RestfulApi\Transformers\ArrayTransformer; class BaseTransformer extends TransformerAbstract { /** * Depth * * @var integer */ protected $depth = 0; /** * Config Service * * @var HttpMessagesRestMiddleware\Services\ConfigService */ protected $config_service; /** * Element Service * * @var HttpMessagesRestMiddleware\Services\ElementService */ protected $element_service; /** * Available Includes * * @var array */ protected $availableIncludes = ['content']; public function __construct($depth = 0) { $this->depth = $depth; $this->config_service = new ConfigService; $this->element_service = new ElementService; } /** * Include Content * * @param BaseElementModel $element Element * * @return League\Fractal\Resource\Item Content */ public function includeContent(BaseElementModel $element) { $content = []; if ($this->depth > \Craft\craft()->config->get('contentRecursionLimit', 'httpMessagesRestMiddleware') - 1) { return; } foreach ($element->getFieldLayout()->getFields() as $fieldLayoutField) { $field = $fieldLayoutField->getField(); $value = $element->getFieldValue($field->handle); if (get_class($field->getFieldType()) === 'Craft\\RichTextFieldType') { $value = $value->getRawContent(); } if (is_object($value) && get_class($value) === 'Craft\\ElementCriteriaModel') { $class = get_class($value->getElementType()); $element_type = $this->element_service->getElementTypeByClass($class); $manager = new Manager(); $manager->parseIncludes(array_merge(['content'], explode(',', \Craft\craft()->request->getParam('include')))); $manager->setSerializer(new ArraySerializer); $transformer = $this->config_service->getTransformer($element_type); $value = $value->find(); $body = new Collection($value, new $transformer($this->depth + 1)); $value = $manager->createData($body)->toArray(); $value = (!empty($value['data'])) ? $value['data'] : null; } $content[$field->handle] = $value; } if ($content) { return $this->item($content, new ContentTransformer($this->depth), 'content'); } } /** * Call * * @param string $method Method * @param mixed $args Args * * @return void */ public function __call($method, $args) { return; } } <file_sep>/src/Services/RestService.php <?php namespace HttpMessagesRestMiddleware\Services; use HttpMessagesRestMiddleware\Services\ElementService; use HttpMessagesRestMiddleware\Http\RestRequest as Request; class RestService { /** * Element Service * * @var HttpMessagesRestMiddleware\Services\ElementService */ protected $element_service; /** * Constructor */ public function __construct() { $this->element_service = new ElementService; } /** * Get Elements * * @param Request $request Request * * @return array Elements */ public function getElements(Request $request) { return $this->element_service->getElements($request->getCriteria()); } /** * Get Element * * @param Request $request Request * * @return BaseElementModel Element */ public function getElement(Request $request) { return $this->element_service->getElement($request); } /** * Save Element * * @param Request $request Request * * @return BaseElementModel Element */ public function saveElement(Request $request) { $element = $this->element_service->getElement($request); $populated_element = $this->element_service->populateElement($element, $request); $validator = craft()->restfulApi_config->getValidator($populated_element->getElementType()); $this->element_service->validateElement($populated_element, $validator); return $this->element_service->saveElement($populated_element, $request); } /** * Delete Element * * @param Request $request Request * * @return void */ public function deleteElement(Request $request) { $this->element_service->deleteElement($request); } } <file_sep>/config.php <?php return [ /** * Routes */ 'routes' => [ 'api/(?P<elementType>(Asset))(/(?P<elementId>[\w\-\d]+)?)?' => [ 'rest' => [ 'validator' => 'HttpMessagesRestMiddleware\\Validators\\AssetValidator', ], ], 'api/(?P<elementType>(Category))(/(?P<elementId>[\w\-\d]+)?)?' => [ 'rest' => [ 'validator' => 'HttpMessagesRestMiddleware\\Validators\\CategoryValidator', ], ], 'api/(?P<elementType>(Entry))(/(?P<elementId>[\w\-\d]+)?)?' => [ 'rest' => [ 'validator' => 'HttpMessagesRestMiddleware\\Validators\\EntryValidator', ], ], 'api/(?P<elementType>(GlobalSet))(/(?P<elementId>[\w\-\d]+)?)?' => [ 'rest' => [ 'validator' => 'HttpMessagesRestMiddleware\\Validators\\GlobalSetValidator', ], ], 'api/(?P<elementType>(MatrixBlock))(/(?P<elementId>[\w\-\d]+)?)?' => [ 'rest' => [ 'validator' => 'HttpMessagesRestMiddleware\\Validators\\MatrixBlockValidator', ], ], 'api/(?P<elementType>(Commerce_Order))(/(?P<elementId>[\w\-\d]+)?)?' => [ 'rest' => [ 'validator' => 'HttpMessagesRestMiddleware\\Validators\\Commerce_OrderValidator', ], ], 'api/(?P<elementType>(Tag))(/(?P<elementId>[\w\-\d]+)?)?' => [ 'rest' => [ 'validator' => 'HttpMessagesRestMiddleware\\Validators\\TagValidator', ], ], 'api/(?P<elementType>(User))(/(?P<elementId>[\w\-\d]+)?)?' => [ 'rest' => [ 'validator' => 'HttpMessagesRestMiddleware\\Validators\\UserValidator', ], ], ], /** * Api Route Prefix * * The Api Route Prefix acts as a namespace and is prepended to all * routes that the API plugin defines. */ 'apiRoutePrefix' => 'api', /** * Content Recursion Limit * * This is the number of times content fields can be populated recursively. * With complex data models that have multiple relationships, populating content * automatically can pull in a lot of extra data. */ 'contentRecursionLimit' => 2, /** * Default Headers * * These headers will be sent with every Response. */ 'defaultHeaders' => [ 'Pragma' => [ 'no-cache', ], 'Cache-Control' => [ 'no-store', 'no-cache', 'must-revalidate', 'post-check=0', 'pre-check=0', ], 'Content-Type' => [ 'application/json; charset=utf-8', ], ], /** * Default Serializers * * A Serializer structures your Transformed data in certain ways. * For more info, see http://fractal.thephpleague.com/serializers/. */ 'defaultSerializer' => 'ArraySerializer', /** * Serializers * * Available serializers that can be specified as default serializer. */ 'serializers' => [ 'ArraySerializer' => 'League\\Fractal\\Serializer\\ArraySerializer', 'DataArraySerializer' => 'League\\Fractal\\Serializer\\DataArraySerializer', 'JsonApiSerializer' => 'League\\Fractal\\Serializer\\JsonApiSerializer', ], /** * Element Types * * Define settings for each element type. If no setting is defined for an element type, * the default settings defined in the `*` wildcard will be inherited. */ // 'elementTypes' => [ // '*' => [ // 'enabled' => true, // 'transformer' => 'HttpMessagesRestMiddleware\\Transformers\\ArrayTransformer', // 'validator' => null, // 'middleware' => ['auth'], // 'permissions' => [ // 'public' => ['GET'], // 'authenticated' => ['POST', 'PUT', 'PATCH'], // ], // ], // 'Asset' => [ // 'enabled' => true, // 'transformer' => 'HttpMessagesRestMiddleware\\Transformers\\AssetFileTransformer', // 'validator' => 'HttpMessagesRestMiddleware\\Validators\AssetFileValidator', // ], // 'Category' => [ // 'enabled' => true, // 'transformer' => 'HttpMessagesRestMiddleware\\Transformers\\CategoryTransformer', // 'validator' => 'HttpMessagesRestMiddleware\\Validators\\CategoryValidator', // ], // 'Entry' => [ // 'enabled' => true, // 'transformer' => 'HttpMessagesRestMiddleware\\Transformers\\EntryTransformer', // 'validator' => 'HttpMessagesRestMiddleware\\Validators\\EntryValidator', // ], // 'GlobalSet' => [ // 'enabled' => true, // 'transformer' => 'HttpMessagesRestMiddleware\\Transformers\\GlobalSetTransformer', // 'validator' => 'HttpMessagesRestMiddleware\\Validators\\GlobalSetValidator', // ], // 'MatrixBlock' => [ // 'enabled' => true, // 'transformer' => 'HttpMessagesRestMiddleware\\Transformers\\MatrixBlockTransformer', // 'validator' => 'HttpMessagesRestMiddleware\\Validators\\MatrixBlockValidator', // ], // 'Tag' => [ // 'enabled' => true, // 'transformer' => 'HttpMessagesRestMiddleware\\Transformers\\TagTransformer', // 'validator' => 'HttpMessagesRestMiddleware\\Validators\\TagValidator', // ], // 'User' => [ // 'enabled' => true, // 'transformer' => 'HttpMessagesRestMiddleware\\Transformers\\UserTransformer', // 'validator' => 'HttpMessagesRestMiddleware\\Validators\\UserValidator', // ], // ], ]; <file_sep>/src/Middleware/RestMiddleware.php <?php namespace HttpMessagesRestMiddleware\Middleware; use HttpMessagesRestMiddleware\Services\ConfigService; use HttpMessagesRestMiddleware\Services\RequestService; use HttpMessagesRestMiddleware\Services\ResponseService; use HttpMessagesRestMiddleware\Services\RestService; use HttpMessages\Http\Request; use HttpMessages\Http\Response; use HttpMessages\Exceptions\HttpMessagesException; use HttpMessagesRestMiddleware\Http\RestRequest; class RestMiddleware { /** * Config Service * * @var HttpMessagesRestMiddleware\Services\ConfigService */ protected $config_service; /** * Request Service * * @var HttpMessagesRestMiddleware\Services\RequestService */ protected $request_service; /** * Response Service * * @var HttpMessagesRestMiddleware\Services\ResponseService */ protected $response_service; /** * Rest Service * * @var HttpMessagesRestMiddleware\Services\RestService */ protected $rest_service; /** * Constructor */ public function __construct() { $this->config_service = new ConfigService; $this->request_service = new RequestService; $this->response_service = new ResponseService; $this->rest_service = new RestService; } /** * Handle * * @return void */ public function __invoke(Request $request, Response $response, callable $next) { $request = $this->request_service->getRequest($request); $response = $this->response_service->getResponse($response); $action = $this->getAction($request->getMethod(), $request->getAttribute('elementType'), $request->getAttribute('elementId')); $response = $this->$action($request, $response); $response = $response->withCriteria($request->getCriteria()); return $response; } /** * Get Action * * @param string $method Method * @param string $element_type Element Type * @param boolean $element_id Element Id * * @return string Action */ private function getAction($method, $element_type, $element_id = null) { if ($method === 'GET' && !$element_id) { return 'actionIndex'; } if ($method === 'GET' && $element_id) { return 'actionShow'; } if ($method === 'POST' && !$element_id) { return 'actionStore'; } if (in_array($method, ['PUT', 'PATCH']) && $element_id) { return 'actionUpdate'; } if ($method === 'DELETE' && $element_id) { return 'actionDelete'; } $exception = new HttpMessagesException(); $exception ->setStatus(405) ->setMessage(sprintf('`%s` method not allowed for resource `%s`.', $method, $element_type)); throw $exception; } /** * Action Show * * @param array $variables Variables * * @return Response Response */ private function actionIndex(Request $request, Response $response) { $elements = $this->rest_service->getElements($request); return $response->withCollection($elements); } /** * Action Show * * @param array $variables Variables * * @return Response Response */ private function actionShow(Request $request, Response $response) { $element = $this->rest_service->getElement($request); return $response->withItem($element); } /** * Action Store * * @param array $variables Variables * * @return Response Response */ private function actionStore(Request $request, Response $response) { $element = $this->rest_service->saveElement($request); return $response ->withCreated() ->withItem($element); } /** * Action Update * * @param array $variables Variables * * @return Response Response */ private function actionUpdate(Request $request, Response $response) { $element = $this->rest_service->saveElement($request); return $response ->withStatus(200, 'Element updated successfully.') ->withItem($element); } /** * Action Delete * * @param array $variables Variables * * @return Response Response */ private function actionDelete(Request $request, Response $response) { $this->rest_service->deleteElement($request); return $response->withStatus(204, 'Element deleted successfully.'); } }
9a2e69145905c8d579ca9549c40b3c803e0e7acc
[ "PHP" ]
12
PHP
airtype/httpmessagesrestmiddleware
83f27e3ffe87cbe124c7d10d0d4cf182ccf62af3
0819a77b4b1ee00acab07e68c15dc2e1420f5c35
refs/heads/master
<repo_name>Zoomelectrico/Frontend_tesis<file_sep>/src/components/profile.js import React from "react"; import { Link } from "react-router-dom"; class Profile extends React.Component { render() { return ( <div className="container has-text-centered"> <div className="columns"> <div className="column is-half is-offset-one-quarter"> <figure className="image has-text-centered"> <img src="https://via.placeholder.com/250" alt="Profile Pic" className="is-rounded has-shadow profile-pic" /> </figure> <h2 className="title">{this.props.user.name}</h2> <p className="description"> <strong>Email:</strong> <a>{this.props.user.email}</a> <br /> <strong>Carrera:</strong> {this.props.user.major} <br /> </p> <div className="buttons has-addons is-centered"> <Link to="/vote" className="button is-success"> Candidatos </Link> <Link to="/vote" className="button is-info"> Votar </Link> </div> </div> </div> </div> ); } } export default Profile; <file_sep>/src/components/index.js export { default as Navbar } from "./navbar"; export { default as Footer } from "./footer"; export { default as Profile } from "./profile"; export { default as NavTabs } from "./navTabs"; <file_sep>/src/App.js import React from "react"; import { BrowserRouter as Router } from "react-router-dom"; import AppWrapper from "./AppWrapper"; class App extends React.Component { state = {}; render() { return ( <Router> <AppWrapper /> </Router> ); } } export default App; <file_sep>/src/pages/Postulate.js import React from "react"; import { BrowserRouter as Router, Route } from "react-router-dom"; import { Navbar, Footer, NavTabs } from "../components"; import { FacultyCouncil, SchoolCouncil, StudentCenter, StudentCenterFederation } from "../components/postulation"; const routes = [ { path: "/postulate/faculty-council", name: "Consejo de Facultad", Component: props => <FacultyCouncil {...props} /> }, { path: "/postulate/school-council", name: "Consejo de Escuela", Component: props => <SchoolCouncil {...props} /> }, { path: "/postulate/student-center", name: "Centro de Estudiantes", Component: props => <StudentCenter {...props} /> }, { path: "/postulate/student-center-federation", name: "Federacion de Centro de Estudiantes", Component: props => <StudentCenterFederation {...props} /> } ]; class Postulate extends React.Component { state = {}; render() { return ( <> <Navbar login={this.props.user.login} logout={this.props.logout} /> <div className="container"> <Router> <> <NavTabs links={routes} /> {routes.map(({ path, name, Component }) => ( <Route key={name} path={path} component={Component} /> ))} </> </Router> </div> <Footer /> </> ); } } export default Postulate; <file_sep>/src/components/form-elements/password.js import React from "react"; const PasswordInput = props => ( <div className="field"> <label htmlFor={`${props.field.name}`} className="label"> {`${props.field.title}`} </label> <div className="control"> <input type="password" name={`${props.field.name}`} id={`${props.field.name}`} className="input" onChange={props.handleChange} /> </div> </div> ); export default PasswordInput; <file_sep>/src/components/postulation/index.js export { default as FacultyCouncil } from "./facultyCouncil"; export { default as StudentCenter } from "./studentCenter"; export { default as StudentCenterFederation } from "./studentCenterFederation"; export { default as SchoolCouncil } from "./schoolCouncil"; <file_sep>/README.md # Vota UNIMET (Actualmente en Construccion) Es una aplicacion web realizada con [React](https://reactjs.org/) para mi trabajo especial de grado, para optar al titulo de Ingeniero de Sistemas. <file_sep>/src/AppWrapper.js import React from "react"; import Cookies from "universal-cookie"; import { Route } from "react-router-dom"; import { withRouter } from "react-router"; import { About, Dashboard, Documents, Home, Postulation, Results, SignIn, Vote, Postulate } from "./pages"; class AppWrapper extends React.Component { state = { user: { login: false }, token: "", routes: [ { path: "/", exact: true, component: props => ( <Home {...props} user={this.state.user} logout={this.logout} /> ) }, { path: "/about", exact: false, component: props => ( <About {...props} user={this.state.user} logout={this.logout} /> ) }, { path: "/signin", exact: true, component: props => ( <SignIn {...props} user={this.state.user} logout={this.logout} login={this.saveUser} /> ) }, { path: "/documents", exact: true, component: props => ( <Documents {...props} user={this.state.user} logout={this.logout} /> ) }, { path: "/postulation", exact: true, component: props => ( <Postulation {...props} user={this.state.user} logout={this.logout} /> ) }, { path: "/results", exact: true, component: props => ( <Results {...props} user={this.state.user} logout={this.logout} /> ) }, { path: "/profile", exact: true, component: props => ( <Dashboard {...props} user={this.state.user} logout={this.logout} /> ) }, { path: "/vote", exact: true, component: props => ( <Vote {...props} user={this.state.user} logout={this.logout} /> ) }, { path: "/postulate", component: props => ( <Postulate {...props} user={this.state.user} logout={this.logout} /> ) } ] }; componentDidMount() { const user = new Cookies().get("uv__rs__"); const token = new Cookies().get("uv__kn__"); if (user) { user.login = true; this.setState({ user, token }); } } logout = () => { new Cookies().remove("uv__rs__"); new Cookies().remove("uv__kn__"); const { user } = this.state; Object.keys(user).forEach(key => { user[key] = null; }); user.login = false; this.setState({ user, token: null }); this.props.history.push("/"); }; saveUser = ({ user, token }) => { this.setState({ user, token }); const cookies = new Cookies(); // uv__rs__ -> user cookies.set("uv__rs__", user, { maxAge: 1000 * 60 * 60 * 30, path: "/" }); // uv__kn__ -> token cookies.set("uv__kn__", token, { maxAge: 1000 * 60 * 60 * 30, path: "/" }); this.props.history.push("/profile"); }; render() { return ( <> {this.state.routes.map(route => ( <Route path={route.path} component={route.component} key={route.path} exact={route.exact} /> ))} </> ); } } export default withRouter(AppWrapper); <file_sep>/src/pages/index.js export { default as SignIn } from "./SignIn"; export { default as About } from "./About"; export { default as Home } from "./Home"; export { default as Documents } from "./Documents"; export { default as Postulation } from "./Postulation"; export { default as Results } from "./Results"; export { default as Dashboard } from "./Dashboard"; export { default as Vote } from "./vote"; export { default as Postulate } from "./Postulate"; <file_sep>/src/components/postulation/studentCenterFederation.js import React from "react"; const studentCenterFederation = props => ( <div className="container"> <h2 className="title"> <form onSubmit={props.submitFunction}> <p>studentCenterFederation</p> </form> </h2> </div> ); export default studentCenterFederation; <file_sep>/src/pages/Postulation.js import React from "react"; import { Navbar, Footer } from "../components"; import { inputHelper } from "../components/form-elements"; class Postulation extends React.Component { state = { denomination: "", color: "", number: 0, symbol: "", nameRepresentative: "", dni: "", email: "", phone: "", inscriptions: { electoralGroup: [ { name: "denomination", title: "Denominacion", type: "text" }, { name: "color", title: "Color y Numero de Pantone", type: "text" }, { name: "number", title: "Numero", type: "number" }, { name: "symbol", title: "Simbolo", type: "file" } ], representative: [ { name: "nameRepresentative", title: "Nombre y Apellido", type: "text" }, { name: "dni", title: "Cedula", type: "text" }, { name: "email", title: "Correo Electronico", type: "email" }, { name: "phone", title: "Telefono", type: "text" } ] } }; handleChange = e => { this.setState({ [e.target.name]: e.target.value }); }; submitForm = e => { const { denomination, color, number, symbol, nameRepresentative, dni, email, phone } = this.state; const electoralGroup = { denomination, color, number, symbol }; const representative = { electoralGroup: denomination, name: nameRepresentative, dni, email, phone }; e.preventDefault(); }; // Render Field Forms renderFields = field => inputHelper(field, this.handleChange); // Render Funciton render() { return ( <> <Navbar login={this.props.user.login} logout={this.props.logout} /> <div className="container"> <div className="columns"> <div className="column has-text-centered"> <h2 className="title">Postulation</h2> <hr /> </div> </div> <div className="columns"> <div className="column is-half is-offset-one-quarter"> <form onSubmit={this.submitForm}> {/* Grupo Electoral*/} <div className="has-text-centered"> <h3>Datos del Grupo Electoral</h3> </div> {this.state.inscriptions.electoralGroup.map(this.renderFields)} {/* Representate Electoral*/} <div className="has-text-centered"> <h3>Datos del Representante del Electoral</h3> </div> {this.state.inscriptions.representative.map(this.renderFields)} <div className="has-text-centered"> <button className="button is-info" type="submit"> Inscribir </button> </div> </form> </div> </div> </div> <Footer /> </> ); } } export default Postulation; <file_sep>/src/pages/SignIn.js import React from "react"; import axios from "axios"; import { Navbar, Footer } from "../components"; class SignIn extends React.Component { state = { email: "", password: "", login: this.props.login }; // University Email check checkEmail = email => email.includes("@correo.unimet.edu.ve"); // Password Strength Check checkPass = password => password.length >= 8; // On Change Handler handleChange = e => { this.setState({ [e.target.name]: e.target.value }); }; login = async e => { e.preventDefault(); if ( this.checkEmail(this.state.email) && this.checkPass(this.state.password) ) { const { email, password } = this.state; const { data: { success, token, user } } = await axios.post("http://localhost:7777/login", { email, password }); if (success) { return this.props.login({ token, user: { ...user, login: true } }); } // TODO: Lanzar Error console.log("Not Success"); } // TODO: Lanzar Error console.log("pass or email bad"); }; render() { return ( <> <Navbar login={this.props.user.login} logout={this.props.logout} /> <div className="container"> <div className="columns"> <div className="column has-text-centered"> <h2 className="title">Iniciar Sesion</h2> </div> </div> <div className="columns"> <div className="column is-half is-offset-one-quarter"> <form onSubmit={this.login}> <div className="field"> <p className="control has-icons-left"> <input type="email" className="input" placeholder="<EMAIL>" name="email" id="email" onChange={this.handleChange} /> <span className="icon is-small is-left"> <i className="fas fa-envelope" /> </span> </p> </div> <div className="field"> <div className="control has-icons-left"> <input type="<PASSWORD>" name="password" id="password" className="input" placeholder="<PASSWORD>" onChange={this.handleChange} /> <span className="icon is-small is-left"> <i className="fas fa-lock" /> </span> </div> </div> <div className="field"> <p className="control has-text-centered"> <button className="button is-info">Iniciar Sesion</button> </p> </div> </form> </div> </div> </div> <Footer /> </> ); } } export default SignIn; <file_sep>/src/pages/vote.js import React from "react"; import { Navbar, Footer } from "../components"; class Vote extends React.Component { render() { return ( <> <Navbar login={this.props.user.login} logout={this.props.logout} /> <div className="container"> <h2 className="title">Vote</h2> </div> <Footer /> </> ); } } export default Vote; <file_sep>/src/components/navbar.js import React from "react"; import { Link } from "react-router-dom"; const Navbar = props => ( <header> <nav className="navbar has-shadow is-spaced is-fixed-top is-transparent"> <div className="navbar-brand"> <Link to="/" className="navbar-item"> <h2>Vota UNIMET</h2> </Link> <div className="navbar-burger burger" data-target="navbar"> <span /> <span /> <span /> </div> </div> <div id="navbar" className="navbar-menu"> {props.login ? ( <div className="navbar-start"> <div className="navbar-item"> <Link to="/profile">Perfil</Link> </div> <div className="navbar-item"> <Link to="/vote">Votar</Link> </div> <div className="navbar-item"> <Link to="/postulate">Postular</Link> </div> <div className="navbar-item"> <Link to="/results">Resultados</Link> </div> </div> ) : ( <div className="navbar-start"> <div className="navbar-item"> <Link to="/about">Acerca de</Link> </div> <div className="navbar-item"> <Link to="/documents">Documentos</Link> </div> <div className="navbar-item"> <Link to="/postulation">Postulacion</Link> </div> <div className="navbar-item"> <Link to="/results">Resultados</Link> </div> </div> )} <div className="navbar-end"> <div className="navbar-item"> {props.login ? ( <button type="button" className="button is-danger" onClick={props.logout} > Cerrar Sesion </button> ) : ( <Link to="signin" className="button is-info"> Iniciar Sesion </Link> )} </div> </div> </div> </nav> </header> ); export default Navbar; <file_sep>/src/pages/Documents.js import React from "react"; import { Navbar, Footer } from "../components"; const Documents = props => ( <> <Navbar login={props.user.login} logout={props.logout} /> <div className="container"> <h2>Documents</h2> </div> <Footer /> </> ); export default Documents; <file_sep>/src/components/postulation/schoolCouncil.js import React from "react"; const schoolCouncil = props => ( <div className="container"> <h2 className="title">schoolCouncil</h2> </div> ); export default schoolCouncil; <file_sep>/src/components/navTabs.js import React from "react"; import { Link } from "react-router-dom"; const Tabs = ({ links }) => ( <div className="tabs is-centered"> <ul> {links.map(({ path, name }) => ( <li key={name}> <Link to={path}>{name}</Link> </li> ))} </ul> </div> ); export default Tabs; <file_sep>/src/components/form-elements/inputHelper.js import React from "react"; import { EmailInput, FileInput, PasswordInput, TextInput } from "./"; const inputHelper = (field, handleChange) => { switch (field.type) { case "text": return ( <TextInput field={field} handleChange={handleChange} key={field.name} /> ); case "password": return ( <PasswordInput field={field} handleChange={handleChange} key={field.name} /> ); case "email": return ( <EmailInput field={field} handleChange={handleChange} key={field.name} /> ); case "file": return ( <FileInput field={field} handleChange={handleChange} key={field.name} /> ); default: return ( <TextInput field={field} handleChange={handleChange} key={field.name} /> ); } }; export default inputHelper; <file_sep>/src/components/form-elements/index.js export { default as TextInput } from "./text"; export { default as EmailInput } from "./email"; export { default as PasswordInput } from "./password"; export { default as FileInput } from "./file"; export { default as inputHelper } from "./inputHelper";
f4aea6b884f18853b3d530a3e513c60914a733bf
[ "JavaScript", "Markdown" ]
19
JavaScript
Zoomelectrico/Frontend_tesis
ea9315a0bb27fd8fdf61c8684c591a50d65a2f91
712b80909b726185043394c6f4b5f5bd3c724d9b
refs/heads/master
<file_sep><?php /** * @var \App\View\AppView $this */ ?> <nav class="large-3 medium-4 columns" id="actions-sidebar"> <ul class="side-nav"> <li class="heading"><?= __('Actions') ?></li> <li><?= $this->Html->link(__('Edit Ingredientes Receta'), ['action' => 'edit', $ingredientesReceta->id]) ?> </li> <li><?= $this->Form->postLink(__('Delete Ingredientes Receta'), ['action' => 'delete', $ingredientesReceta->id], ['confirm' => __('Are you sure you want to delete # {0}?', $ingredientesReceta->id)]) ?> </li> <li><?= $this->Html->link(__('List Ingredientes Recetas'), ['action' => 'index']) ?> </li> <li><?= $this->Html->link(__('New Ingredientes Receta'), ['action' => 'add']) ?> </li> <li><?= $this->Html->link(__('List Ingredientes'), ['controller' => 'Ingredientes', 'action' => 'index']) ?> </li> <li><?= $this->Html->link(__('New Ingrediente'), ['controller' => 'Ingredientes', 'action' => 'add']) ?> </li> <li><?= $this->Html->link(__('List Recetas'), ['controller' => 'Recetas', 'action' => 'index']) ?> </li> <li><?= $this->Html->link(__('New Receta'), ['controller' => 'Recetas', 'action' => 'add']) ?> </li> </ul> </nav> <div class="ingredientesRecetas view large-9 medium-8 columns content"> <h3><?= h($ingredientesReceta->id) ?></h3> <table class="vertical-table"> <tr> <th scope="row"><?= __('Ingrediente') ?></th> <td><?= $ingredientesReceta->has('ingrediente') ? $this->Html->link($ingredientesReceta->ingrediente->id, ['controller' => 'Ingredientes', 'action' => 'view', $ingredientesReceta->ingrediente->id]) : '' ?></td> </tr> <tr> <th scope="row"><?= __('Receta') ?></th> <td><?= $ingredientesReceta->has('receta') ? $this->Html->link($ingredientesReceta->receta->id, ['controller' => 'Recetas', 'action' => 'view', $ingredientesReceta->receta->id]) : '' ?></td> </tr> <tr> <th scope="row"><?= __('Id') ?></th> <td><?= $this->Number->format($ingredientesReceta->id) ?></td> </tr> </table> </div> <file_sep><?php /** * @var \App\View\AppView $this */ ?> <nav class="large-3 medium-4 columns" id="actions-sidebar"> <ul class="side-nav"> <li class="heading"><?= __('Actions') ?></li> <li><?= $this->Html->link(__('Edit Ingrediente'), ['action' => 'edit', $ingrediente->id]) ?> </li> <li><?= $this->Form->postLink(__('Delete Ingrediente'), ['action' => 'delete', $ingrediente->id], ['confirm' => __('Are you sure you want to delete # {0}?', $ingrediente->id)]) ?> </li> <li><?= $this->Html->link(__('List Ingredientes'), ['action' => 'index']) ?> </li> <li><?= $this->Html->link(__('New Ingrediente'), ['action' => 'add']) ?> </li> <li><?= $this->Html->link(__('List Recetas'), ['controller' => 'Recetas', 'action' => 'index']) ?> </li> <li><?= $this->Html->link(__('New Receta'), ['controller' => 'Recetas', 'action' => 'add']) ?> </li> </ul> </nav> <div class="ingredientes view large-9 medium-8 columns content"> <h3><?= h($ingrediente->id) ?></h3> <table class="vertical-table"> <tr> <th scope="row"><?= __('Nombre') ?></th> <td><?= h($ingrediente->nombre) ?></td> </tr> <tr> <th scope="row"><?= __('Id') ?></th> <td><?= $this->Number->format($ingrediente->id) ?></td> </tr> </table> <div class="related"> <h4><?= __('Related Recetas') ?></h4> <?php if (!empty($ingrediente->recetas)): ?> <table cellpadding="0" cellspacing="0"> <tr> <th scope="col"><?= __('Id') ?></th> <th scope="col"><?= __('Nombre') ?></th> <th scope="col" class="actions"><?= __('Actions') ?></th> </tr> <?php foreach ($ingrediente->recetas as $recetas): ?> <tr> <td><?= h($recetas->id) ?></td> <td><?= h($recetas->nombre) ?></td> <td class="actions"> <?= $this->Html->link(__('View'), ['controller' => 'Recetas', 'action' => 'view', $recetas->id]) ?> <?= $this->Html->link(__('Edit'), ['controller' => 'Recetas', 'action' => 'edit', $recetas->id]) ?> <?= $this->Form->postLink(__('Delete'), ['controller' => 'Recetas', 'action' => 'delete', $recetas->id], ['confirm' => __('Are you sure you want to delete # {0}?', $recetas->id)]) ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> </div> </div> <file_sep># Paginacion-Ajax-CakePHP3 Debido a que en CakePHP3 se descontinuó el uso de Helpers como JSHelper o AjaxHelper, realizar una paginación utilizando Ajax puede no ser tan fácil. CakePHP3 nos brinda una paginación por defecto sin utilizar Ajax. # En que consiste ? Basicamente en utilizar la paginación brindada por CakePHP3 pero recurrir a esta utilizando Ajax. Entran en juego 2 archivos, el controlador y la vista(template), el modelo no esta implicado. En el controlador solo estarán 3 lineas que son las que habilitan la paginación de CakePHP3, y en la vista estará la llamada de Ajax. # Instalacion Para probar este ejemplo, se necesita tener instalado y activado el XAMPP con sus módulos Apache y MySQL. Se recomienda utilizar NetBeans para la administración del directorio de archivos. El archivo vendor.zip se debe descomprimir. Descarga opcional: http://www.mediafire.com/file/2fwsfgh73ofdqfx/PaginacionAJAXCakePHP3.zip # Versión WEB Para ver el resultado de la paginación utilizando Ajax sin descargar nada. http://reflejo.epizy.com/cake/ <file_sep><?php /** * @var \App\View\AppView $this */ ?> <nav class="large-3 medium-4 columns" id="actions-sidebar"> <ul class="side-nav"> <li class="heading"><?= __('Actions') ?></li> <li><?= $this->Html->link(__('Edit Receta'), ['action' => 'edit', $receta->id]) ?> </li> <li><?= $this->Form->postLink(__('Delete Receta'), ['action' => 'delete', $receta->id], ['confirm' => __('Are you sure you want to delete # {0}?', $receta->id)]) ?> </li> <li><?= $this->Html->link(__('List Recetas'), ['action' => 'index']) ?> </li> <li><?= $this->Html->link(__('New Receta'), ['action' => 'add']) ?> </li> <li><?= $this->Html->link(__('List Ingredientes'), ['controller' => 'Ingredientes', 'action' => 'index']) ?> </li> <li><?= $this->Html->link(__('New Ingrediente'), ['controller' => 'Ingredientes', 'action' => 'add']) ?> </li> </ul> </nav> <div class="recetas view large-9 medium-8 columns content"> <h3><?= h($receta->id) ?></h3> <table class="vertical-table"> <tr> <th scope="row"><?= __('Nombre') ?></th> <td><?= h($receta->nombre) ?></td> </tr> <tr> <th scope="row"><?= __('Id') ?></th> <td><?= $this->Number->format($receta->id) ?></td> </tr> </table> <div class="related"> <h4><?= __('Related Ingredientes') ?></h4> <?php if (!empty($receta->ingredientes)): ?> <table cellpadding="0" cellspacing="0"> <tr> <th scope="col"><?= __('Id') ?></th> <th scope="col"><?= __('Nombre') ?></th> <th scope="col" class="actions"><?= __('Actions') ?></th> </tr> <?php foreach ($receta->ingredientes as $ingredientes): ?> <tr> <td><?= h($ingredientes->id) ?></td> <td><?= h($ingredientes->nombre) ?></td> <td class="actions"> <?= $this->Html->link(__('View'), ['controller' => 'Ingredientes', 'action' => 'view', $ingredientes->id]) ?> <?= $this->Html->link(__('Edit'), ['controller' => 'Ingredientes', 'action' => 'edit', $ingredientes->id]) ?> <?= $this->Form->postLink(__('Delete'), ['controller' => 'Ingredientes', 'action' => 'delete', $ingredientes->id], ['confirm' => __('Are you sure you want to delete # {0}?', $ingredientes->id)]) ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> </div> </div> <file_sep>-- phpMyAdmin SQL Dump -- version 4.6.5.2 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 23-05-2017 a las 04:37:08 -- Versión del servidor: 10.1.21-MariaDB -- Versión de PHP: 5.6.30 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `test` -- CREATE DATABASE IF NOT EXISTS `test` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; USE `test`; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `ingredientes` -- CREATE TABLE `ingredientes` ( `id` int(255) NOT NULL, `nombre` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `ingredientes` -- INSERT INTO `ingredientes` (`id`, `nombre`) VALUES (1, 'Jamon'), (2, 'Queso'), (3, 'Tapa de Tarta'), (4, 'Tapa de Empanada'), (5, 'Chocolate'), (6, 'Vainilla'), (7, 'Frutilla'), (8, 'Harina'), (9, 'Ingrediente Secreto'), (10, 'Dulce de Leche'), (11, 'Cacao'), (12, 'Mix de Frutas'), (13, 'Pan'), (14, 'Salame'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `ingredientes_recetas` -- CREATE TABLE `ingredientes_recetas` ( `id` int(255) NOT NULL, `ingrediente_id` int(255) NOT NULL, `receta_id` int(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `ingredientes_recetas` -- INSERT INTO `ingredientes_recetas` (`id`, `ingrediente_id`, `receta_id`) VALUES (22, 1, 9), (23, 2, 9), (24, 3, 9), (25, 1, 10), (26, 2, 10), (27, 4, 10), (28, 5, 11), (29, 6, 11), (30, 7, 11), (31, 8, 11), (32, 9, 11), (33, 10, 11), (34, 12, 11), (35, 1, 12), (36, 2, 12), (37, 13, 12), (38, 9, 13), (39, 13, 13), (40, 2, 14), (41, 13, 14), (42, 14, 14); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `recetas` -- CREATE TABLE `recetas` ( `id` int(255) NOT NULL, `nombre` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `recetas` -- INSERT INTO `recetas` (`id`, `nombre`) VALUES (9, '<NAME> Jamon y Queso'), (10, 'Empanada de Jamon y Queso'), (11, 'Receta Secreta'), (12, 'Sandwich de Jamon y Queso'), (13, 'Sandwich Potente'), (14, 'Sandwich de Salame y Queso'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `ingredientes` -- ALTER TABLE `ingredientes` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `ingredientes_recetas` -- ALTER TABLE `ingredientes_recetas` ADD PRIMARY KEY (`id`), ADD KEY `ingrediente_id` (`ingrediente_id`), ADD KEY `receta_id` (`receta_id`); -- -- Indices de la tabla `recetas` -- ALTER TABLE `recetas` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `ingredientes` -- ALTER TABLE `ingredientes` MODIFY `id` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; -- -- AUTO_INCREMENT de la tabla `ingredientes_recetas` -- ALTER TABLE `ingredientes_recetas` MODIFY `id` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=43; -- -- AUTO_INCREMENT de la tabla `recetas` -- ALTER TABLE `recetas` MODIFY `id` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `ingredientes_recetas` -- ALTER TABLE `ingredientes_recetas` ADD CONSTRAINT `ingredientes_recetas_ibfk_1` FOREIGN KEY (`ingrediente_id`) REFERENCES `ingredientes` (`id`), ADD CONSTRAINT `ingredientes_recetas_ibfk_2` FOREIGN KEY (`receta_id`) REFERENCES `recetas` (`id`); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><head> <?php echo $this->Html->script('jquery-3.2.1.min'); ?> </head> <body> <div id="totalajax"> <nav class="large-3 medium-4 columns" id="actions-sidebar"> <ul class="side-nav"> <li class="heading"><?= __('Actions') ?></li> <li><?= $this->Html->link(__('New Ingrediente'), ['action' => 'add']) ?></li> <li><?= $this->Html->link(__('List Recetas'), ['controller' => 'Recetas', 'action' => 'index']) ?></li> <li><?= $this->Html->link(__('New Receta'), ['controller' => 'Recetas', 'action' => 'add']) ?></li> </ul> </nav> <div class="ingredientes index large-9 medium-8 columns content"> <h3><?= __('Ingredientes') ?></h3> <table cellpadding="0" cellspacing="0"> <thead> <tr> <th scope="col"><?= $this->Paginator->sort('nombre') ?></th> <th scope="col" class="actions"><?= __('Actions') ?></th> </tr> </thead> <tbody> <?php foreach ($ingredientes as $ingrediente): ?> <tr> <td><?= h($ingrediente->nombre) ?></td> <td class="actions"> <?= $this->Html->link(__('View'), ['action' => 'view', $ingrediente->id]) ?> <?= $this->Html->link(__('Edit'), ['action' => 'edit', $ingrediente->id]) ?> <?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $ingrediente->id], ['confirm' => __('Are you sure you want to delete # {0}?', $ingrediente->id)]) ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <div class="paginator"> <ul class="pagination"> <?= $this->Paginator->first('<< ' . __('first')) ?> <?= $this->Paginator->prev('< ' . __('previous')) ?> <?= $this->Paginator->numbers() ?> <?= $this->Paginator->next(__('next') . ' >') ?> <?= $this->Paginator->last(__('last') . ' >>') ?> </ul> <p><?= $this->Paginator->counter(['format' => __('Page {{page}} of {{pages}}, showing {{current}} record(s) out of {{count}} total')]) ?></p> </div> </div> </div> </body> <script type="text/javascript"> $(document).ready(function () { $(".pagination a").bind("click", function (event) { if(!$(this).attr('href')) return false; $.ajax({ type: 'POST', dataType: "html", evalScripts:true, success:function (data, textStatus) { $("#totalajax").html(data); }, url:$(this).attr('href')}); return false; }); }); </script>
56da98a5040df7acd70192aa956a4e15240ddd71
[ "Markdown", "SQL", "PHP" ]
6
PHP
Reflej0/Paginacion-Ajax-CakePHP3
3709398b94264cde4fcc340cbe10acfd0007abd3
14141d39e81e45f550400234032b5da58cf015ef
refs/heads/master
<file_sep>package com.techcasita.android.hwy67.content; import android.content.ContentValues; import android.net.Uri; import com.techcasita.android.hwy67.remote.Story; /** * The Contract, for putting a story into sql columns */ public class Contract { public static final String CONTENT_AUTHORITY = "com.techcasita.android.hwy67"; public static final Uri BASE_URI = Uri.parse("content://com.techcasita.android.hwy67"); private Contract() { } public static ContentValues getContentValues(final Story story) { final ContentValues values = new ContentValues(); values.put(Contract.Items.SID, story.getID()); values.put(Contract.Items.GUID, story.getGuid()); values.put(Contract.Items.DATE, story.getDate()); values.put(Contract.Items.CATEGORIES, story.getCategories()); values.put(Contract.Items.AUTHOR, story.getAuthor()); values.put(Contract.Items.TITLE, story.getTitle()); values.put(Contract.Items.CONTENT, story.getContent()); values.put(Contract.Items.URL, story.getUrl()); values.put(Contract.Items.FOREIGN_URL, story.getForeign_url()); values.put(Contract.Items.IMAGE_URL, story.getImage_url()); return values; } interface Columns { /** * Type: INTEGER PRIMARY KEY AUTOINCREMENT */ String _ID = "_id"; String SID = "sid"; String GUID = "guid"; String DATE = "date"; String CATEGORIES = "categories"; String AUTHOR = "author"; String TITLE = "title"; String CONTENT = "content"; String URL = "url"; String FOREIGN_URL = "foreign_url"; String IMAGE_URL = "image_url"; } @SuppressWarnings("unused") public static class Items implements Columns { public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.com.techcasita.android.hwy67.items"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.com.techcasita.android.hwy67.items"; public static final String DEFAULT_SORT = SID + " DESC"; /** * Matches: /items/ */ public static Uri buildDirUri() { return BASE_URI.buildUpon().appendPath("items").build(); } /** * Matches: /items/[_id]/ */ public static Uri buildItemUri(final long _id) { return BASE_URI.buildUpon().appendPath("items").appendPath(Long.toString(_id)).build(); } /** * Read item ID item detail URI. */ public static long getItemId(final Uri itemUri) { return Long.parseLong(itemUri.getPathSegments().get(1)); } /** * Matches: /items/[category]/ */ public static Uri buildCatUri(final String category) { return BASE_URI.buildUpon().appendPath("items").appendPath(category).build(); } /** * Matches: /items/search/[searchterm]/ */ public static Uri buildSearchUri(final String searchTerm) { return BASE_URI.buildUpon().appendPath("items").appendPath("search").appendPath(searchTerm).build(); } } } <file_sep>package com.techcasita.android.hwy67.gcm; import android.app.IntentService; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import com.google.android.gms.gcm.GcmPubSub; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.iid.InstanceID; import com.techcasita.android.hwy67.R; import java.util.HashSet; import java.util.Set; public class RegistrationIntentService extends IntentService { private static final String TAG = RegistrationIntentService.class.getName(); public RegistrationIntentService() { super(TAG); } @Override protected void onHandleIntent(final Intent intent) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); try { // In the (unlikely) event that multiple refresh operations occur simultaneously, // ensure that they are processed sequentially. synchronized (TAG) { // Initially this call goes out to the network to retrieve the token, subsequent calls are local. InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); Log.i(TAG, "R.string.gcm_defaultSenderId: " + getString(R.string.gcm_defaultSenderId)); Log.i(TAG, "GCM Registration Token: " + token); GcmPubSub.getInstance(this).subscribe(token, "/topics/Demo", null); if (!sharedPreferences.getBoolean(getString(R.string.preference_key_insync), true)) { final String[] all = getResources().getStringArray(R.array.feed_values); final Set<String> topics = sharedPreferences.getStringSet(getString(R.string.preference_key_sources), new HashSet<String>()); for (final String s : all) { if (topics.contains(s)) { GcmPubSub.getInstance(this).subscribe(token, "/topics/" + s.replace(' ', '_'), null); } else { GcmPubSub.getInstance(this).unsubscribe(token, "/topics/" + s.replace(' ', '_')); } } } sharedPreferences.edit().putBoolean(getString(R.string.preference_key_insync), true).apply(); } } catch (Exception e) { Log.d(TAG, "Failed to complete token refresh", e); sharedPreferences.edit().putBoolean(getString(R.string.preference_key_insync), false).apply(); } } }<file_sep>package com.techcasita.android.hwy67; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.provider.Settings; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import com.techcasita.android.hwy67.gcm.RegistrationIntentService; import com.techcasita.android.hwy67.remote.ContentReader; public class SettingsActivity extends AppCompatActivity { private static final String LOG_TAG = SearchActivity.class.getName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setTitle(getString(R.string.title_settings)); if (null != getSupportActionBar()) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } if (getFragmentManager().findFragmentById(R.id.content_frame) == null) { getFragmentManager().beginTransaction().replace(R.id.content_frame, new SettingsFragment()).commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); Preference button = findPreference(getString(R.string.preference_key_demo)); button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { ContentReader.pushDemo( getString(R.string.content_url), Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID)); return true; } }); if (MainActivity.hasPlayServices) { getActivity().startService(new Intent(getActivity(), RegistrationIntentService.class)); } } @Override public void onResume() { super.onResume(); getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } /** * Unregister a this instance as a {@link SharedPreferences.OnSharedPreferenceChangeListener} * * @see #onResume for registering */ @Override public void onPause() { super.onPause(); getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); } // // Implement SharedPreferences.OnSharedPreferenceChangeListener // @Override public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key) { if (key.equals(getString(R.string.preference_key_sources))) { Log.d(LOG_TAG, "Subscriptions changed"); sharedPreferences.edit().putBoolean(getString(R.string.preference_key_insync), false).apply(); getActivity().startService(new Intent(getActivity(), RegistrationIntentService.class)); } } } } <file_sep>package com.techcasita.android.hwy67.gcm; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.provider.Settings.Secure; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.android.gms.gcm.GcmListenerService; import com.techcasita.android.hwy67.MainActivity; import com.techcasita.android.hwy67.R; import com.techcasita.android.hwy67.TimePreference; import com.techcasita.android.hwy67.content.UpdateService; /** * If the BroadcastReceiver (com.google.android.gms.gcm.GcmReceiver) receives a message with * an Action: com.google.android.c2dm.intent.RECEIVE it will be handled here. */ public class MyGcmListenerService extends GcmListenerService { private static final String LOG_TAG = MyGcmListenerService.class.getName(); /** * Called when message is received. * * @param from SenderID of the sender. * @param data Data bundle containing message data as key/value pairs. * For Set of keys use data.keySet(). */ @Override public void onMessageReceived(final String from, final Bundle data) { final String topic = data.getCharSequence("topic", "").toString(); if ("Demo".equals(topic)) { final String uid = data.getCharSequence("uid", "").toString(); if (0 == uid.length() || !uid.equals(Secure.getString(getContentResolver(), Secure.ANDROID_ID))) { Log.d(LOG_TAG, "demo msg. ignored"); return; } } Log.d(LOG_TAG, "GCM Notification Received, therefore start UpdateService"); startService(new Intent(this, UpdateService.class)); if (!TimePreference.isNowQuietTime(this)) { final String title = String.format("%s ( %s )", data.getCharSequence("title", "Hwy67").toString(), topic); final String content = data.getCharSequence("content", "News Alert").toString(); final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); final Notification notification = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_stat_hwy67) .setContentTitle(title) .setContentText(content) .setContentIntent(contentIntent) .build(); notification.flags |= Notification.FLAG_AUTO_CANCEL; NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager.notify(0, notification); Log.d(LOG_TAG, "message: " + title + "/" + content + "/" + topic); } } } <file_sep>package com.techcasita.android.hwy67; import android.app.Fragment; import android.app.LoaderManager; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Typeface; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v4.app.ShareCompat; import android.support.v7.graphics.Palette; import android.support.v7.widget.Toolbar; import android.text.Html; import android.text.method.LinkMovementMethod; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.techcasita.android.hwy67.content.StoryLoader; /** * A placeholder fragment containing a simple view. */ public class DetailActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { public static final String ARG_ITEM_ID = DetailActivityFragment.class.getName() + "_ARG__ITEM_ID"; private static final String LOG_TAG = DetailActivityFragment.class.getName(); private Cursor mCursor; private long mItemId; private View mRootView; private ImageView mPhotoView; private CollapsingToolbarLayout mCollapsingToolbarLayout; /** * @param itemId {@link long} itemid * @return {@link DetailActivityFragment} instance */ public static DetailActivityFragment newInstance(final long itemId) { final Bundle arguments = new Bundle(); arguments.putLong(ARG_ITEM_ID, itemId); final DetailActivityFragment fragment = new DetailActivityFragment(); fragment.setArguments(arguments); return fragment; } @Override public void onActivityCreated(final Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // In support library r8, calling initLoader for a fragment in a FragmentPagerAdapter in // the fragment's onCreate may cause the same LoaderManager to be dealt to multiple // fragments because their mIndex is -1 (haven't been added to the activity yet). Thus, // we do this in onActivityCreated. getLoaderManager().initLoader(0, null, this); } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments().containsKey(ARG_ITEM_ID)) { mItemId = getArguments().getLong(ARG_ITEM_ID); } if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getActivity().getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); //noinspection deprecation window.setStatusBarColor(getActivity().getResources().getColor(R.color.colorPrimaryDark)); } } @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_detail, container, false); mPhotoView = (ImageView) mRootView.findViewById(R.id.photo); mCollapsingToolbarLayout = (CollapsingToolbarLayout) mRootView.findViewById(R.id.collapsing_toolbar); mRootView.findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View view) { startActivity(Intent.createChooser(ShareCompat.IntentBuilder.from(getActivity()) .setType("text/plain") .setText("Some sample text") .getIntent(), getString(R.string.action_share))); } }); final Toolbar toolbar = (Toolbar) mRootView.findViewById(R.id.toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { getActivity().finish(); } }); bindViews(); return mRootView; } // // implements LoaderManager.LoaderCallbacks<Cursor> // private void bindViews() { if (mRootView == null) { return; } final TextView title = (TextView) mRootView.findViewById(R.id.article_title); final TextView subTitle = (TextView) mRootView.findViewById(R.id.article_byline); final TextView content = (TextView) mRootView.findViewById(R.id.article_body); final Button button = (Button) mRootView.findViewById(R.id.btn_open); subTitle.setMovementMethod(new LinkMovementMethod()); content.setTypeface(Typeface.createFromAsset(getResources().getAssets(), "Roboto-Regular.ttf")); if (mCursor != null) { mRootView.setAlpha(0); mRootView.setVisibility(View.VISIBLE); mRootView.animate().alpha(1); mCollapsingToolbarLayout.setTitle(mCursor.getString(StoryLoader.Query.TITLE)); final String author = mCursor.getString(StoryLoader.Query.AUTHOR); final String date = mCursor.getString(StoryLoader.Query.DATE); final String url = mCursor.getString(StoryLoader.Query.FOREIGN_URL); if (url != null && 0 < url.length()) { button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url))); } }); } title.setText(mCursor.getString(StoryLoader.Query.TITLE)); subTitle.setText(String.format("%s by %s", date, author)); content.setText(Html.fromHtml(mCursor.getString(StoryLoader.Query.CONTENT))); Glide.with(DetailActivityFragment.this) .load(mCursor.getString(StoryLoader.Query.IMAGE_URL)) .centerCrop() .listener( new RequestListener<String, GlideDrawable>() { @Override public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) { mPhotoView.setImageResource(R.drawable.web512); mRootView.findViewById(R.id.meta_bar).setBackgroundColor(0xFF333333); return true; } @Override public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { final Bitmap bitmap = Util.drawableToBitmap(resource.getCurrent()); final Palette p = new Palette.Builder(bitmap).generate(); final int col = p.getVibrantColor(0xFF333333); mRootView.findViewById(R.id.meta_bar).setBackgroundColor(col); return false; } }) .into(mPhotoView); } else { mRootView.setVisibility(View.GONE); mCollapsingToolbarLayout.setTitle(getString(R.string.app_name)); title.setText("N/A"); subTitle.setText("N/A"); content.setText("N/A"); } } @Override public Loader<Cursor> onCreateLoader(final int id, final Bundle args) { return StoryLoader.newInstanceForItemId(getActivity(), mItemId); } @Override public void onLoadFinished(final Loader<Cursor> loader, final Cursor cursor) { if (!isAdded()) { if (cursor != null) { cursor.close(); } return; } mCursor = cursor; if (mCursor != null && !mCursor.moveToFirst()) { Log.e(LOG_TAG, "Error reading item detail cursor"); mCursor.close(); mCursor = null; } bindViews(); } @Override public void onLoaderReset(final Loader<Cursor> loader) { mCursor = null; bindViews(); } } <file_sep>package com.techcasita.android.hwy67; import android.app.Fragment; import android.app.FragmentManager; import android.app.LoaderManager; import android.content.Loader; import android.database.Cursor; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v13.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.util.TypedValue; import android.view.MenuItem; import com.techcasita.android.hwy67.content.Contract; import com.techcasita.android.hwy67.content.StoryLoader; /** * DetailActivity shows a full, detail view of story. * Swiping shows other stories (optionally filtered based on a previously selected category (i.e. town name). */ public class DetailActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { private Cursor mCursor; private long mStartId; private ViewPager mPager; private MyAdapter mPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); getLoaderManager().initLoader(0, null, this); mPagerAdapter = new MyAdapter(getFragmentManager()); mPager = (ViewPager) findViewById(R.id.pager); mPager.setAdapter(mPagerAdapter); mPager.setPageMargin((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics())); mPager.setPageMarginDrawable(new ColorDrawable(0x333)); mPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageScrollStateChanged(int state) { super.onPageScrollStateChanged(state); } @Override public void onPageSelected(int position) { if (mCursor != null) { mCursor.moveToPosition(position); } } }); if (savedInstanceState == null) { if (getIntent() != null && getIntent().getData() != null) { mStartId = Contract.Items.getItemId(getIntent().getData()); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } // // implements LoaderManager.LoaderCallbacks<Cursor> // @Override public Loader<Cursor> onCreateLoader(final int id, final Bundle args) { final String cat = this.getIntent().getStringExtra(Contract.Items.CATEGORIES); return cat == null ? StoryLoader.newAllStoriesInstance(this) : StoryLoader.newAllStoriesInstance(this, cat); } @Override public void onLoadFinished(final Loader<Cursor> loader, final Cursor cursor) { mCursor = cursor; mPagerAdapter.notifyDataSetChanged(); if (mStartId > 0) { mCursor.moveToFirst(); while (!mCursor.isAfterLast()) { if (mCursor.getLong(StoryLoader.Query._ID) == mStartId) { final int position = mCursor.getPosition(); mPager.setCurrentItem(position, false); break; } mCursor.moveToNext(); } mStartId = 0; } } @Override public void onLoaderReset(final Loader<Cursor> loader) { mCursor = null; mPagerAdapter.notifyDataSetChanged(); } // // FragmentStatePagerAdapter // http://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html private class MyAdapter extends FragmentStatePagerAdapter { public MyAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return (mCursor != null) ? mCursor.getCount() : 0; } @Override public Fragment getItem(int position) { mCursor.moveToPosition(position); return DetailActivityFragment.newInstance(mCursor.getLong(StoryLoader.Query._ID)); } } } <file_sep>package com.techcasita.android.hwy67; import android.app.LoaderManager; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.techcasita.android.hwy67.content.Contract; import com.techcasita.android.hwy67.content.StoryLoader; import com.techcasita.android.hwy67.content.UpdateService; import com.techcasita.android.hwy67.gcm.RegistrationIntentService; /** * Main Activity, showing a list of all available items, or a list, filtered by category, */ public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SwipeRefreshLayout.OnRefreshListener, LoaderManager.LoaderCallbacks<Cursor> { public static final String STATE_TITLE = MainActivity.class.getName() + "_STATE_TITLE"; private static final String LOG_TAG = MainActivity.class.getName(); private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; public static boolean hasPlayServices = false; private SwipeRefreshLayout mSwipeRefreshLayout; private RecyclerView mRecyclerView; private String mCategory = null; private boolean mInitData = true; private BroadcastReceiver mRefreshingReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { if (UpdateService.BROADCAST_ACTION_STATE_CHANGE.equals(intent.getAction())) { boolean isRefreshing = intent.getBooleanExtra(UpdateService.EXTRA_REFRESHING, false); mSwipeRefreshLayout.setRefreshing(isRefreshing); Log.d(LOG_TAG, "SwipeRefreshLayout isRefreshing is" + isRefreshing); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); if (savedInstanceState != null) { this.setTitle(savedInstanceState.getCharSequence(STATE_TITLE)); } else { setTitle(getString(R.string.default_title)); } final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout); mSwipeRefreshLayout.setOnRefreshListener(this); mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent); mSwipeRefreshLayout.setRefreshing(false); mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int k = mRecyclerView.getChildAdapterPosition(mRecyclerView.getChildAt(0)); mSwipeRefreshLayout.setEnabled(k == 0); } }); getLoaderManager().initLoader(0, null, this); MainActivity.hasPlayServices = checkPlayServices(); if (MainActivity.hasPlayServices) { // Start IntentService to register this application with GCM. startService(new Intent(this, RegistrationIntentService.class)); Log.d(LOG_TAG, "GCM RegistrationIntentService called."); } } /** * Check the device to make sure it has the Google Play Services APK. If * it doesn't, display a dialog that allows users to download the APK from * the Google Play Store or enable it in the device's system settings. */ private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Log.i(LOG_TAG, "This device is not supported."); finish(); } return false; } return true; } @Override public void onSaveInstanceState(Bundle outState) { outState.putCharSequence(STATE_TITLE, this.getTitle()); super.onSaveInstanceState(outState); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); // // cool stuff: http://javapapers.com/android/android-searchview-action-bar-tutorial/ // final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_search) { startActivity(new Intent(this, SearchActivity.class)); } return super.onOptionsItemSelected(item); } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); mSwipeRefreshLayout.setRefreshing(false); LocalBroadcastManager.getInstance(this).registerReceiver(mRefreshingReceiver, new IntentFilter(UpdateService.BROADCAST_ACTION_STATE_CHANGE)); if (mInitData) { onRefresh(); } } @Override protected void onRestart() { mInitData = false; super.onRestart(); } @Override protected void onPause() { LocalBroadcastManager.getInstance(this).unregisterReceiver(mRefreshingReceiver); super.onPause(); } // // Implement NavigationView.OnNavigationItemSelectedListener // @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); switch (id) { case R.id.nav_julian: setTitle("Hwy67 - Julian"); mCategory = "Julian"; getLoaderManager().restartLoader(0, null, this); break; case R.id.nav_ysabel: setTitle("Hwy67 - Santa Ysabel"); mCategory = "Ysabel"; getLoaderManager().restartLoader(0, null, this); break; case R.id.nav_ramona: setTitle("Hwy67 - Ramona"); mCategory = "Ramona"; getLoaderManager().restartLoader(0, null, this); break; case R.id.nav_lakeside: setTitle("Hwy67 - Lakeside"); mCategory = "Lakeside"; getLoaderManager().restartLoader(0, null, this); break; case R.id.nav_santee: setTitle("Hwy67 - Santee"); mCategory = "Santee"; getLoaderManager().restartLoader(0, null, this); break; case R.id.nav_alpine: setTitle("Hwy67 - Alpine"); mCategory = "Alpine"; getLoaderManager().restartLoader(0, null, this); break; case R.id.nav_descanso: setTitle("Hwy67 - Descanso"); mCategory = "Descanso"; getLoaderManager().restartLoader(0, null, this); break; case R.id.nav_settings: startActivity(new Intent(MainActivity.this, SettingsActivity.class)); break; default: mCategory = null; setTitle("Hwy67 - Front Page"); getLoaderManager().restartLoader(0, null, this); break; } final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } // // Implement SwipeRefreshLayout.OnRefreshListener // @Override public void onRefresh() { Log.d(LOG_TAG, "onRefresh called"); startService(new Intent(this, UpdateService.class)); } // // Implement LoaderManager.LoaderCallbacks<Cursor>, // @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return mCategory == null ? StoryLoader.newAllStoriesInstance(this) : StoryLoader.newAllStoriesInstance(this, mCategory); } @Override public void onLoadFinished(final Loader<Cursor> loader, final Cursor data) { final Adapter adapter = new Adapter(data); adapter.setHasStableIds(true); mRecyclerView.setAdapter(adapter); mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); } @Override public void onLoaderReset(Loader<Cursor> loader) { mRecyclerView.setAdapter(null); } // // RecyclerView.ViewHolder // public static class ViewHolder extends RecyclerView.ViewHolder { public ImageView thumbnailView; public TextView titleView; public TextView subtitleView; public ViewHolder(final View view) { super(view); thumbnailView = (ImageView) view.findViewById(R.id.thumbnail); titleView = (TextView) view.findViewById(R.id.article_title); subtitleView = (TextView) view.findViewById(R.id.article_subtitle); } } // // RecyclerView.Adapter // private class Adapter extends RecyclerView.Adapter<ViewHolder> { private Cursor mCursor; public Adapter(final Cursor cursor) { mCursor = cursor; } @Override public long getItemId(final int position) { mCursor.moveToPosition(position); return mCursor.getLong(StoryLoader.Query._ID); } @Override public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) { final View view = getLayoutInflater().inflate(R.layout.list_item, parent, false); final ViewHolder vh = new ViewHolder(view); view.setOnClickListener(new View.OnClickListener() { /** * Create new view intent, for the clicked item, also add the currently selected cat. * @param view {@link View} */ @Override public void onClick(final View view) { final Intent intent = new Intent(Intent.ACTION_VIEW, Contract.Items.buildItemUri(getItemId(vh.getAdapterPosition()))); startActivity(intent.putExtra(Contract.Items.CATEGORIES, mCategory)); } }); return vh; } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { mCursor.moveToPosition(position); final String date = mCursor.getString(StoryLoader.Query.DATE); final String author = mCursor.getString(StoryLoader.Query.AUTHOR); holder.titleView.setText(mCursor.getString(StoryLoader.Query.TITLE)); holder.subtitleView.setText(String.format("%s by %s", date, author)); try { Glide.with(MainActivity.this) .load(mCursor.getString(StoryLoader.Query.IMAGE_URL)) .fallback(R.drawable.web512) .centerCrop() .listener( new RequestListener<String, GlideDrawable>() { @Override public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) { holder.thumbnailView.setImageResource(R.drawable.hwy67); return true; } @Override public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { return false; } }) .into(holder.thumbnailView); } catch (Exception e) { Log.w(LOG_TAG, e.toString()); } } @Override public int getItemCount() { return mCursor.getCount(); } } } <file_sep>package com.techcasita.android.hwy67.widget; import android.content.Context; import android.content.Intent; import android.widget.RemoteViews; import android.widget.RemoteViewsService; import com.techcasita.android.hwy67.R; import com.techcasita.android.hwy67.remote.Story; import java.util.ArrayList; import java.util.List; public class ListProvider implements RemoteViewsService.RemoteViewsFactory { private List<Story> listItemList = new ArrayList<>(); private Context context = null; @SuppressWarnings("UnusedParameters") public ListProvider(Context context, Intent intent, List<Story> listItemList) { this.listItemList = listItemList; this.context = context; } @Override public void onCreate() { } @Override public void onDataSetChanged() { } @Override public void onDestroy() { } @Override public int getCount() { return listItemList.size(); } @Override public long getItemId(int position) { return position; } @Override public boolean hasStableIds() { return true; } @Override public RemoteViews getViewAt(final int position) { int layout = R.layout.widget_list_item; final RemoteViews remoteView = new RemoteViews(context.getPackageName(), layout); final Story story = listItemList.get(position); remoteView.setTextViewText(R.id.article_title, story.getTitle()); remoteView.setTextViewText(R.id.article_subtitle, String.format("%s by %s", story.getDate(), story.getAuthor())); remoteView.setImageViewResource(R.id.thumbnail, R.drawable.hwy67); return remoteView; } @Override public RemoteViews getLoadingView() { return null; } @Override public int getViewTypeCount() { return 1; } } <file_sep>package com.techcasita.android.hwy67.remote; import android.util.Log; import java.util.List; import retrofit.Call; import retrofit.Callback; import retrofit.GsonConverterFactory; import retrofit.Response; import retrofit.Retrofit; import retrofit.http.GET; import retrofit.http.Query; public class ContentReader { private static final String LOG_TAG = ContentReader.class.getName(); public static List<Story> fetchArticles(final String BASE_URL) { // setup Retrofit final Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); // setup api service final Api apiService = retrofit.create(Api.class); final Call<List<Story>> call = apiService.getArticles(""); try { final Response<List<Story>> response = call.execute(); return response.body(); } catch (Exception e) { Log.e(LOG_TAG, e.toString()); } return null; } public static void pushDemo(final String BASE_URL, final String uid) { final Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .build(); // setup api service final Api apiService = retrofit.create(Api.class); final Call<Void> call = apiService.pushDemo(uid); call.enqueue(new Callback<Void>() { @Override public void onResponse(Response<Void> response, Retrofit retrofit) { Log.d(LOG_TAG, "Push Demo requested"); } @Override public void onFailure(Throwable t) { Log.d(LOG_TAG, "Push Demo request failed: " + t.toString()); } }); } // // Describing server-side REST interface // public interface Api { @SuppressWarnings("unused") @GET("rest/hwy67/article") Call<Story> getArticle(@Query("sid") long sid); @GET("rest/hwy67/articles") Call<List<Story>> getArticles(@Query("sort") String sort); @GET("rest/hwy67/push") Call<Void> pushDemo(@Query("uid") String uid); } } <file_sep>package com.techcasita.android.hwy67.content; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.techcasita.android.hwy67.remote.Story; import java.util.ArrayList; import java.util.List; import static com.techcasita.android.hwy67.content.StoriesProvider.Tables; /** * StoriesDB, SQL for creating/upda. the table definition. */ public class StoriesDB extends SQLiteOpenHelper { private static final String LOG_TAG = StoriesDB.class.getName(); private static final String DATABASE_NAME = "hwy67.db"; private static final int DATABASE_VERSION = 4; public StoriesDB(final Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public static List<Story> getAllStories(final Context context) { final List<Story> storyList = new ArrayList<>(); final SQLiteDatabase database = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null); if (database == null) { Log.d(LOG_TAG, "getAllStories() database is null"); return storyList; } final Cursor cursor = database.query(Tables.ITEMS, null, null, null, null, null, "sid DESC", "5"); if (cursor == null) { Log.d(LOG_TAG, "getAllStories() queryResultcursor is null"); return storyList; } if (cursor.moveToFirst()) { do { final String title = cursor.getString(StoryLoader.Query.TITLE); final String date = cursor.getString(StoryLoader.Query.DATE); final String author = cursor.getString(StoryLoader.Query.AUTHOR); final String img_url = cursor.getString(StoryLoader.Query.IMAGE_URL); storyList.add(new Story(title, date, author, img_url)); } while (cursor.moveToNext()); } cursor.close(); return storyList; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + Tables.ITEMS + " (" + Contract.Items._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + Contract.Items.SID + " INTEGER," + Contract.Items.GUID + " TEXT," + Contract.Items.DATE + " TEXT," + Contract.Items.CATEGORIES + " TEXT NOT NULL," + Contract.Items.AUTHOR + " TEXT NOT NULL," + Contract.Items.TITLE + " TEXT NOT NULL," + Contract.Items.CONTENT + " TEXT NOT NULL," + Contract.Items.URL + " TEXT," + Contract.Items.FOREIGN_URL + " TEXT," + Contract.Items.IMAGE_URL + " TEXT" + ")"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + Tables.ITEMS); onCreate(db); } }
82dbb546ff6f2e7334ab4ca665e9032dcefba37e
[ "Java" ]
10
Java
wolfpaulus/Capstone-Project
91e5256f370c45f7d276de5787c4b21b5b73e8b5
460e67adaaffc9b8a4803abb17e2550d4f92a039
refs/heads/master
<file_sep># LaTeX Makefile v0.33 -- LaTeX only THESIS=main CV=cv OUTPUT=thesis_cv.pdf SHELL=/bin/zsh all: ## Compile paper ./latexrun $(THESIS).tex ./latexrun $(CV).tex pdfunite $(THESIS).pdf $(CV).pdf $(OUTPUT) clean: ## Clean output files ./latexrun --clean-all <file_sep>import scipy.misc as scm import skimage.segmentation as sks import skimage.morphology as skm import numpy as np img_file = 'ds13_img.png' gt_file = 'ds13_gt.png' out_file = 'ds13_boundary.png' dilation_size = 3 img = scm.imread(img_file, mode='RGB') gt = scm.imread(gt_file, mode='L') > 0 gt = skm.opening(gt, skm.square(5)).astype(np.uint8) zero_array = np.zeros(img.shape, dtype='uint8')[...,0] mask = sks.mark_boundaries(zero_array, gt > 0, color=(1,0,0), mode='inner')[...,0] out = skm.dilation(mask, skm.square(dilation_size)) out_green = np.concatenate((zero_array[..., np.newaxis], out[..., np.newaxis], zero_array[..., np.newaxis]), axis=-1).astype('uint8') * 255 clear_mask = np.repeat(out[..., np.newaxis], 3, axis=-1) print(img.shape, clear_mask.shape) img[clear_mask > 0] = 0 img = img.astype('uint8') img += out_green # scm.imshow(img) print(img.shape, type(img)) scm.imsave(out_file, img) <file_sep># PhD Thesis Latex Template University of Bern Template is made following the guidelines of [GCB](https://www.gcb.unibe.ch/phd_program/phd_degree/index_eng.html) and it is based on the thesis template of [Sunil Patel](http://www.sunilpatel.co.uk/thesis-template/) <file_sep>#!/usr/bin/env python3 import pandas as pd import numpy as np scores = [[0.687, 0.963, 0.974, 0.976], [0.551, 0.428, 0.482, 0.592], [0.687, 0.963, 0.974, 0.976], [0.223, 0.239, 0.431, 0.631], [0.346, 0.949, 0.959, 0.985], [0.239, 0.711, 0.725, 0.851], [0.687, 0.963, 0.974, 0.976], [0.506, 0.367, 0.494, 0.665]] scores = np.array(scores) # scores = np.concatenate((scores, np.zeros(scores.shape[0])[..., None]), axis=1) datasets = ['Brain', 'Cochlea', 'Tweezer', 'Slitlamp'] method = ['Vilarino et al. \cite{vilarino07}', 'Probability Est.', 'EL', 'EEL'] metrics = ['AUC', 'F1'] index = pd.MultiIndex.from_product([datasets, metrics], names=['Type', 'Metric']) # columns = pd.MultiIndex.from_product([method], names=['Method']) columns = method df = pd.DataFrame(scores, index=index, columns=columns) # add bold tags def myformat(r): idx = r.values.argmax() r.iloc[:, idx] = '$\\bm{' + r.iloc[:, idx].apply(str) + '}$' return r df = df.groupby(['Type', 'Metric']).apply(myformat) caption = "Area Under the Curve (AUC) and performances for each approach on each dataset. Highlight maximum values in bold." out_path = 'results.tex' print('writing table to {}'.format(out_path)) table = df.to_latex( escape=False, # column_format='llp{1.8cm}', multirow=True, caption=caption, label='tab:results') # add horiz line below ours with open(out_path, 'w') as tf: for line in table.splitlines(): # if line.startswith('KSPTrack/GMM'): # line += '\n\hdashline' tf.write(line + '\n') <file_sep>import h5py import scipy.misc as scm import numpy as np import random ds = '09' post = '_gaze_rec_sympadded' imNbr = 97 featFile = './feat_ds' + ds + post + '.h5' # initialize hdf5 files print('read files...') hdInFile = h5py.File(featFile, 'r') imFeat = hdInFile['raw_feat'][...] hdInFile.close() #imNbr = random.randint(0, imFeat.shape[0] - 1) outFile = 'activations_ds' + ds + ('_%04i' % imNbr) + post + '.png' print('image number: %i' % imNbr) img_shape = [imFeat.shape[1] * 4, imFeat.shape[2] * 4] nbr_colums = 3 im_array = list() border_size = img_shape[1] // 15 green_border_size = img_shape[1] // 60 for i, featIdx in enumerate(random.sample(range(imFeat.shape[3]), 12)): if i == 0: img_norm = scm.imread('ds%s_%04d.png' % (ds, imNbr), mode='RGB') img_norm = img_norm.astype('float') / 255 img_norm = scm.imresize(img_norm, (img_shape[0], img_shape[1])) img_norm[...,:green_border_size,1] = 255 img_norm[...,-green_border_size:,1] = 255 img_norm[:green_border_size,...,1] = 255 img_norm[-green_border_size:,...,1] = 255 else: img_norm = np.repeat(imFeat[imNbr,...,featIdx,np.newaxis], 3, axis=-1) img_norm = (img_norm - np.min(img_norm)) / (np.max(img_norm) - np.min(img_norm)) img_norm = scm.imresize(img_norm, (img_shape[0], img_shape[1])) print('feat_idx: %i' % featIdx) if (i % nbr_colums) == 0: im_array.append(img_norm) else: im_array[i // nbr_colums] = np.concatenate([im_array[i // nbr_colums], np.ones([img_norm.shape[0], border_size, 3]) * 255], axis=1) im_array[i // nbr_colums] = np.concatenate([im_array[i // nbr_colums], img_norm], axis=1) out = im_array[0] for i in range(1,len(im_array)): out = np.concatenate([out, np.ones([border_size, out.shape[1], 3]) * 255], axis=0) out = np.concatenate([out, im_array[i]], axis=0) scm.imsave(outFile, out) <file_sep>from os.path import join as pjoin import glob import pandas as pd import os import yaml import seaborn as sns import matplotlib.pyplot as plt from ksptrack.exps import results_dirs as rd import numpy as np types = ['Tweezer', 'Cochlea', 'Slitlamp', 'Brain'] root_path = pjoin('/home/ubelix/lejeune/runs/ksptrack') out_path = './results.tex' exp_names = ['dec', 'gmm'] path_18 = pjoin(root_path, 'plots_results', 'all_self.csv') df_18 = pd.read_csv(path_18) to_drop = np.arange(2, 14) df_18.drop(df_18.columns[to_drop], axis=1, inplace=True) df_18 = df_18.set_index(['Types', 'Methods']).rename( columns={ 'F1 mean': 'F1', 'F1 std': '_F1', 'PR mean': 'PR', 'PR std': '_PR', 'RC mean': 'RC', 'RC std': '_RC' }) records = [] max_seqs = 4 for i, t in enumerate(types): dset_paths = sorted(glob.glob(pjoin(root_path, 'Dataset' + str(i) + '*'))) for dset_path in dset_paths[:max_seqs]: dset_dir = os.path.split(dset_path)[-1] exp_paths = [pjoin(dset_path, x) for x in exp_names] for exp_path in exp_paths: score_path = pjoin(exp_path, 'scores.csv') if (os.path.exists(score_path)): df = pd.read_csv(score_path, index_col=0, header=None, squeeze=True) with open(pjoin(exp_path, 'cfg.yml')) as f: cfg = yaml.load(f, Loader=yaml.FullLoader) records.append([ t, dset_dir, os.path.split(exp_path)[-1], df['f1_ksp'], df['pr_ksp'], df['rc_ksp'] ]) df = pd.DataFrame.from_records(records, columns=('Types', 'dset', 'Methods', 'F1', 'PR', 'RC')) df_mean = df.groupby(['Types', 'Methods']).mean() df_std = df.groupby(['Types', 'Methods']).std().rename(columns={ 'F1': '_F1', 'PR': '_PR', 'RC': '_RC' }) # build full table df = pd.concat((df_mean, df_std), axis=1) df_all = pd.concat((df, df_18), axis=0, levels=1).sort_index(0) df_all = df_all.round(decimals=2) # Methods order = { 'dec': 'KSPTrack/DEC', 'gmm': 'KSPTrack/GMM', 'KSP': 'KSPTrack', 'mic17': 'EEL', 'gaze2': 'Gaze2Segment', 'wtp': 'DL-prior', } # drop some methods df_all = df_all.drop('KSPopt', level='Methods') # rename df_all = df_all.rename(index=order) # add bold field df_all['bold'] = False for t in types: idx = df_all.loc[t]['F1'].values.argmax() df_all.loc[t]['bold'].iloc[idx] = True # add bold tags def myformat(r): if (r['bold'].iat[0]): r['F1'] = '$\\bm{' + r['F1'].apply(str) + '} \pm ' + r['_F1'].apply( str) + '$' else: r['F1'] = '$' + r['F1'].apply(str) + ' \pm ' + r['_F1'].apply( str) + '$' r['PR'] = '$' + r['PR'].apply(str) + ' \pm ' + r['_PR'].apply(str) + '$' r['RC'] = '$' + r['RC'].apply(str) + ' \pm ' + r['_RC'].apply(str) + '$' return r # compute mean over all types means = df_all.groupby(['Methods'])['F1'].mean() std = df_all.groupby(['Methods'])['_F1'].mean() df_all = df_all.groupby(['Types', 'Methods']).apply(myformat) # remove dummy columns df_all = df_all.drop(columns=['_F1', '_PR', '_RC', 'bold']) df_all = df_all.reset_index().pivot('Methods', 'Types') df_all = df_all.reindex([v for v in order.values()]) # take only F1 # df_all = df_all[['F1', 'mean', 'std']] df_all = df_all[['F1']] df_all.columns = df_all.columns.droplevel() print(df_all) caption = """ Quantitative results on all datasets. We report the F1 scores and standard deviations. """ print('writing table to {}'.format(out_path)) table = df_all.to_latex( escape=False, column_format='llp{1.8cm}p{1.8cm}p{1.8cm}p{1.8cm}p{1.8cm}', multirow=True, caption=caption, label='tab:results') # add horiz line below ours with open(out_path, 'w') as tf: for line in table.splitlines(): if line.startswith('KSPTrack/GMM'): line += '\n\hdashline' tf.write(line + '\n') <file_sep>import pickle import matplotlib.pyplot as plt import numpy as np from matplotlib import rc rc('font',**{'family':'serif','serif':['Palatino']}) rc('text', usetex=True) with open('data.pkl', 'rb') as f: data = pickle.load(f) pr_x = data['mean']['pr_curve']['rec'] pr_y = data['mean']['pr_curve']['pre'] f1_score = 2 * (np.multiply(pr_x, pr_y)) / (pr_x + pr_y) idx_max = np.argmax(f1_score) plt.subplots(figsize=(8, 2)) plt.subplot(121) plt.plot(pr_x, pr_y, 'k') plt.plot(pr_x[idx_max], pr_y[idx_max], 'go') plt.grid() plt.xlabel(r'\textbf{Recall}', fontsize=12) plt.ylabel(r'\textbf{Precision}', fontsize=12) plt.subplot(122) plt.plot(pr_x,f1_score, 'k') plt.plot(pr_x[idx_max], f1_score[idx_max], 'go') plt.grid() plt.xlabel(r'\textbf{Recall}', fontsize=11) plt.ylabel(r'\textbf{F1-Score}', fontsize=11) plt.subplots_adjust(wspace=0.4) plt.savefig('f1_score.pdf', bbox_inches="tight") plt.show() <file_sep>import matplotlib.pyplot as plt import numpy as np from prettytable import PrettyTable from matplotlib import colors import sys, getopt, os import csv from matplotlib import rc rc('font',**{'family':'serif','serif':['Palatino']}) rc('text', usetex=True) def main(argv): # datasets = list() reports = ['_allMetrics_ds11_rec.csv','_allMetrics_ds11_rec_maxfeat.csv'] # reports = ['_allMetrics_ds01_prob.csv','_allMetrics_ds09_prob.csv','_allMetrics_ds11_prob.csv','_allMetrics_ds12_prob.csv'] dataset_labels = [r'CT Inner Ear A ($m=\sqrt{p}$)',r'CT Inner Ear A ($m=p$)'] ofile = 'f1_vs_training_rec_maxfeat.pdf' # title = None # ofile = None # try: # opts, args = getopt.getopt(argv,"hd:r:",["dataset=","reports=","ofile=","title="]) # except getopt.GetoptError: # print('eval_reprod.py -d <01-Surgical_Video,09-MRI_Brain> -r <bow-000-009,bow-000-009> --ofile=out_file.png --title=mytitle') # sys.exit(2) # for opt, arg in opts: # if opt == '-h': # print('eval_reprod.py -d <01-Surgical_Video,09-MRI_Brain> -r <bow-000-009,bow-000-009> --ofile=out_file.png --title=mytitle') # sys.exit() # elif opt in ("-d", "--dataset"): # tmp = arg.split(',') # for i, ds in enumerate(tmp): # datasets.append(list()) # tmp2 = ds.rsplit('-') # datasets[i] = [tmp2[0], tmp2[-1].replace('_',' ')] # elif opt in ("-r", "--reports"): # tmp = arg.split(',') # for i, rep in enumerate(tmp): # reports.append(list()) # tmp2 = rep.rsplit('-') # reports[i] = [tmp2[0], tmp2[1], tmp2[-1]] # elif opt in ("--title"): # title = arg.replace('_',' ') # elif opt in ("--ofile"): # ofile = arg # else: # assert False, "unhandled option" # # if only one report numbers specified, take for all the same # if len(reports) == 1: # for i in range(len(datasets) - 1): # reports.append(reports[0]) from collections import OrderedDict data_fscore = OrderedDict() for i_rep, rep in enumerate(reports): print('load csv: %s' % rep) with open(rep, 'rt') as csvfile: numreader = csv.reader(csvfile, delimiter=';', quotechar='|') rep_idx = None fscore_idx = None data_fscore['%s' % rep] = list() for row in numreader: try: fscore_idx = row.index('f1_score_max') except ValueError: data_fscore['%s' % rep].append(float(row[fscore_idx])) # print('fscore: %f' % float(row[fscore_idx])) data_fscore_mean = dict() data_fscore_std = dict() for i_rep, rep in enumerate(reports): my_f1_array = np.asarray(data_fscore['%s' % rep]) data_fscore_mean['%s' % rep] = np.zeros(len(my_f1_array) // 10) data_fscore_std['%s' % rep] = np.zeros(len(my_f1_array) // 10) for i in range(len(my_f1_array) // 10): data_fscore_mean['%s' % rep][i] = np.mean(my_f1_array[(i*10):((i+1)*10)]) data_fscore_std['%s' % rep][i] = np.std(my_f1_array[(i*10):((i+1)*10)]) print('mean: %f, std: %f' % (float(data_fscore_mean['%s' % rep][i]), float(data_fscore_std['%s' % rep][i]))) colors = ['r', 'c'] markers = ['*', '>', '<', '^', 'v', 'p', '*', 'h'] epoch_list = np.array([1,11,21,31,41,51,61,71,81,91]) # epoch_list = np.array([1]) plt.figure(figsize=(6,3)) for i_rep, rep in enumerate(reports): # if i_rep < len(epoch_list): plt.plot(epoch_list, data_fscore_mean['%s' % rep], ms=5, lw=0, clip_on=False, color=colors[i_rep % len(colors)], marker=markers[i_rep % len(markers)], label=r'%s' % dataset_labels[i_rep]) plt.plot(epoch_list, data_fscore_mean['%s' % rep], marker=None, lw=1, color=colors[i_rep % len(colors)]) # plt.xlim([(1.0-pr_win), 1.0]) # plt.ylim([(1.0-pr_win), 1.0]) plt.xlabel(r'\textbf{Epoch}', fontsize=12) plt.ylabel(r'\textbf{Mean \textit{max F1-Score}}', fontsize=12) # plt.legend(bbox_to_anchor=(0,-0.15), loc="upper left", frameon=False) plt.legend(bbox_to_anchor=(1.0,1.0), loc="upper left", frameon=False) plt.grid() plt.savefig(ofile, bbox_inches="tight") plt.show() # plt.xticks(fontsize=fs_ax_ticks) # plt.yticks(fontsize=fs_ax_ticks) # data = np.array([val for (_, val) in data_fscore.items()]).transpose() # key_list = list(data_fscore.keys()) # alpha = 0.1 # # basic plot # plt.boxplot(data, sym='k.') # if title != None: # plt.title(r'\textbf{%s}' % title, fontsize=16) # plt.xticks(np.arange(1, len(key_list)+1), key_list, rotation='vertical', fontsize=10) # plt.yticks(fontsize=9) # for i in range(data.shape[1]): # plt.scatter(np.ones(data.shape[0])*(i+1) + np.random.uniform(-alpha, alpha, data.shape[0]), data[:,i], # label=key_list[i], marker='.', s=3, color=colors.cnames['dimgrey']) # # get means # means = list() # for i in range(data.shape[1]): # means.append(np.mean(data[:,i])) # # get ranks # ranks = list(reversed([i[0] for i in sorted(enumerate(means), key=lambda x: x[1])])) # t = PrettyTable(['Dataset', 'Mean', 'Median', 'Std', 'Rank', 'Support']) # for i in range(data.shape[1]): # t.add_row([key_list[i], '%.4f' % means[i], '%.4f' % np.median(data[:,i]), '%.3e' % np.std(data[:,i]), '%i' % (ranks.index(i)+1), data.shape[0]]) # print(t) # # plt.legend(loc='best') # plt.grid() # plt.ylabel(r'\textbf{max F1-score}', fontsize=12) # if ofile == None: # plt.subplots_adjust(bottom=0.4) # plt.show() # else: # plt.savefig(ofile, bbox_inches="tight") if __name__ == "__main__": main(sys.argv[1:]) <file_sep>import csv import matplotlib.pyplot as plt import numpy as np from matplotlib import rc rc('font',**{'family':'serif','serif':['Palatino']}) rc('text', usetex=True) dataset_nbr = '11_prob' xx = list() mse = list() mse_val = list() print('reading 1....') with open('log_ds' + dataset_nbr + '.csv', 'rt') as csvfile: csv_reader = csv.reader(filter(lambda row: row[0] != '#', csvfile), delimiter=';', quotechar='|') for (i, row) in enumerate(csv_reader): if i > 0: xx.append(float(row[0])) mse.append(float(row[2])) mse_val.append(float(row[8])) print('plotting....') plt.figure(figsize=(8, 2)) plt.plot(xx, mse, 'k') plt.plot(xx, mse_val, 'r') plt.grid() plt.xlabel(r'\textbf{Epochs}', fontsize=12) plt.ylabel(r'\textbf{Loss}', fontsize=12) plt.legend([r'BCE Training Loss',r'BCE Validation Loss']) plt.savefig('learning_curve_ds' + dataset_nbr + '.pdf', bbox_inches="tight") plt.show() <file_sep>import numpy as np import scipy.misc as scm import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.axes_grid1 import make_axes_locatable shape = [150, 200] gazeGaussStd = 0.06 * shape[1] def gaussian_2D(shape=(3,3), sigma=0.5): """ 2D gaussian mask - should give the same result as MATLAB's fspecial('gaussian',[shape],[sigma]) """ m, n = [(ss - 1.) / 2. for ss in shape] y, x = np.ogrid[-m:m + 1, -n:n + 1] h = np.exp(-(x * x + y * y) / (2. * sigma * sigma)) h[h < np.finfo(h.dtype).eps * h.max()] = 0 sumh = h.sum() if sumh != 0: h /= sumh return h kernel_size = np.ceil(gazeGaussStd * 6) // 2 * 2 + 1 gauss_kernel = gaussian_2D((kernel_size, kernel_size), gazeGaussStd) gauss_arr = np.zeros(shape) c_x = round(0.6 * shape[1]) c_y = round(0.4 * shape[0]) edge_x = int(c_x - kernel_size // 2) edge_y = int(c_y - kernel_size // 2) v_range1 = slice(max(0, edge_y), max(min(edge_y + gauss_kernel.shape[0], gauss_arr.shape[0]), 0)) h_range1 = slice(max(0, edge_x), max(min(edge_x + gauss_kernel.shape[1], gauss_arr.shape[1]), 0)) v_range2 = slice(max(0, -edge_y), min(-edge_y + gauss_arr.shape[0], gauss_kernel.shape[0])) h_range2 = slice(max(0, -edge_x), min(-edge_x + gauss_arr.shape[1], gauss_kernel.shape[1])) gauss_arr[v_range1, h_range1] += gauss_kernel[v_range2, h_range2] gauss_arr /= np.max(gauss_arr) plt.figure(figsize=(4, 3)) ax = plt.gca() im = ax.imshow(gauss_arr, cmap='plasma', vmin=0, vmax=1) plt.axis('off') # create an axes on the right side of ax. The width of cax will be 5% # of ax and the padding between cax and ax will be fixed at 0.05 inch. divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax, ticks=[0, 0.5, 1]) plt.savefig('prob_map_06.pdf', bbox_inches="tight") plt.show()
f0b3363da3f5a8d9b551f98b6d4dcb882c7aa1ca
[ "Markdown", "Python", "Makefile" ]
10
Makefile
lejeunel/thesis
168ba65a88ee614156ba563e9847022579f7accf
7e6dcb3f8a64b0b7a0d901513c2a51942653934c
refs/heads/master
<file_sep>package com.example.danie.inventoryapp; import android.app.LoaderManager; import android.content.ContentUris; import android.content.ContentValues; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.example.danie.inventoryapp.data.InventoryContract.InventoryEntry; import com.example.danie.inventoryapp.data.InventoryCursorAdapter; public class InventoryActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { /** * Tag for the log messages */ private static final int INVENTORY_LOADER = 0; private InventoryCursorAdapter mCursorAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inventory); // Setup FAB to open EditorActivity FloatingActionButton fab = findViewById(R.id.fab_add_item); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(InventoryActivity.this, AddInventoryActivity.class); startActivity(intent); } }); // Find the ListView which will be populated with the pet data ListView itemsListView = findViewById(R.id.list_view_inventory); // Find and set empty view on the ListView, so that it only shows when the list has 0 items. View emptyView = findViewById(R.id.empty_view); itemsListView.setEmptyView(emptyView); mCursorAdapter = new InventoryCursorAdapter(this, null); itemsListView.setAdapter(mCursorAdapter); // Setup OnItemClickListener itemsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent lvIntent = new Intent(InventoryActivity.this, AddInventoryActivity.class); Uri currentItemUri = ContentUris.withAppendedId(InventoryEntry.CONTENT_URI, id); lvIntent.setData(currentItemUri); startActivity(lvIntent); } }); getLoaderManager().initLoader(INVENTORY_LOADER, null,this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_inventory, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // User clicked on a menu option in the app bar overflow menu switch (item.getItemId()) { // Respond to a click on the "Insert dummy data" menu option case R.id.action_insert_dummy_data: insertDummyItem(); return true; // Respond to a click on the "Delete dummy data" menu option case R.id.action_remove_dummy_data: deleteDummyItem(); return true; // Respond to a click on the "Delete all entries" menu option case R.id.action_delete_all_entries: showDeleteConfirmationDialog(); return true; } return super.onOptionsItemSelected(item); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // Perform SQL query String[] projection = { InventoryEntry._ID, InventoryEntry.COLUMN_PRODUCT_NAME, InventoryEntry.COLUMN_PRODUCT_PRICE, InventoryEntry.COLUMN_PRODUCT_QTY, InventoryEntry.COLUMN_SUPPLIER_NAME, InventoryEntry.COLUMN_SUPPLIER_PHONE}; return new CursorLoader( this, // Parent Activity context InventoryEntry.CONTENT_URI, // Provider content URI projection, // Columns to include in the resulting Cursor null, // No selection clause null, // No selection argument null); // Default sort order } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mCursorAdapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { mCursorAdapter.swapCursor(null); } // HELPER METHODS private void insertDummyItem() { ContentValues values = new ContentValues(); values.put(InventoryEntry.COLUMN_PRODUCT_NAME, "Dummy Item"); values.put(InventoryEntry.COLUMN_PRODUCT_PRICE, 2); values.put(InventoryEntry.COLUMN_PRODUCT_QTY, 1); values.put(InventoryEntry.COLUMN_SUPPLIER_NAME, "Dummy Supplier"); values.put(InventoryEntry.COLUMN_SUPPLIER_PHONE, "+12406326000"); Uri uri = getContentResolver().insert(InventoryEntry.CONTENT_URI, values); } private void deleteDummyItem() { String[] arguments = {"Dummy Item"}; getContentResolver().delete(InventoryEntry.CONTENT_URI, InventoryEntry.COLUMN_PRODUCT_NAME + "=?", arguments); } private void deleteAllProducts() { int rowsDeleted = getContentResolver().delete( InventoryEntry.CONTENT_URI, null, null); Toast.makeText( this, rowsDeleted + " row(s) were deleted from " + InventoryEntry.TABLE_NAME, Toast.LENGTH_SHORT).show(); } private void showDeleteConfirmationDialog() { // Create an AlertDialog.Builder and set the message, and click listeners // for the positive and negative buttons on the dialog. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.delete_all_confirmation); builder.setPositiveButton(R.string.delete_item, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Delete" button, so delete the pet. deleteAllProducts(); } }); builder.setNegativeButton(R.string.delete_item_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Cancel" button, so dismiss the dialog if (dialog != null) { dialog.dismiss(); } } }); // Create and show the AlertDialog AlertDialog alertDialog = builder.create(); alertDialog.show(); } } <file_sep>package com.example.danie.inventoryapp; import android.Manifest; import android.app.LoaderManager; import android.content.ContentValues; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.Intent; import android.content.Loader; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.NavUtils; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.telephony.PhoneNumberUtils; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.danie.inventoryapp.data.InventoryContract.InventoryEntry; import com.example.danie.inventoryapp.data.InventoryProvider; public class AddInventoryActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { /** * Tag for the log messages */ public static final String LOG_TAG = InventoryProvider.class.getSimpleName(); /** * Identifier for the pet data loader */ private static final int EXISTING_ITEM_LOADER = 0; /** * EditText field to enter the item name */ private EditText txtProductName; /** * TextView for the product price */ private EditText txtProductPrice; /** * TextView for the product quantity */ private TextView txtProductQuantity; /** * Button to increase quantity */ private Button btnIncreaseQuantity; /** * Button to decrease quantity */ private Button btnDecreaseQuantity; /** * EditText field to enter the supplier */ private EditText txtSupplierName; /** * EditText field to enter the supplier phone */ private EditText txtSupplierPhone; /** * Button to decrease quantity */ private Button btnContactSupplier; /** * Boolean flag that to check if item was updated or not (true or false, respectively) */ private boolean mItemChanged = false; /** * Content URI for the existing item (null if it's new) */ private Uri mCurrentUri = null; private View.OnTouchListener mTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { mItemChanged = true; return false; } }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_inventory); Intent intent = getIntent(); mCurrentUri = intent.getData(); if (mCurrentUri == null) { setTitle(getString(R.string.add_item)); // Invalidate the options menu, so the "Delete" menu option can be hidden. invalidateOptionsMenu(); } else { setTitle(getString(R.string.edit_item)); getLoaderManager().initLoader(EXISTING_ITEM_LOADER, null, this); } // EditView and TextView txtProductName = findViewById(R.id.txt_product_name); txtProductPrice = findViewById(R.id.txt_product_price); txtProductQuantity = findViewById(R.id.txt_product_quantity); txtSupplierName = findViewById(R.id.txt_supplier_name); txtSupplierPhone = findViewById(R.id.txt_supplier_telephone); // Button View btnIncreaseQuantity = findViewById(R.id.plus_quantity); btnDecreaseQuantity = findViewById(R.id.minus_quantity); btnContactSupplier = findViewById(R.id.btn_contact_supplier); // Test if both Views are empty or null if (txtProductPrice.getText().toString().isEmpty() && txtProductPrice.getText().toString().isEmpty()) { txtProductPrice.setText("0"); txtProductQuantity.setText("1"); } // OnClickListeners for the buttons that increase/decrease quantity btnIncreaseQuantity.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView txtQty = findViewById(R.id.txt_product_quantity); String currentQty = txtQty.getText().toString(); int quantity = Integer.valueOf(currentQty) + 1; txtQty.setText(String.valueOf(quantity)); Log.e(LOG_TAG, "quantity" + String.valueOf(quantity)); } }); btnDecreaseQuantity.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView txtQty = findViewById(R.id.txt_product_quantity); String currentQty = txtQty.getText().toString(); int quantity = Integer.valueOf(currentQty); if (quantity > 0) { quantity -= 1; } txtQty.setText(String.valueOf(quantity)); Log.e(LOG_TAG, "quantity" + String.valueOf(quantity)); } }); btnContactSupplier.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showTelephoneDialog(); // String supplierTelephone = txtSupplierPhone.getText().toString(); // Intent lvIntent = new Intent(Intent.ACTION_CALL, Uri.fromParts("tel", supplierTelephone, null)); // if (ActivityCompat.checkSelfPermission(AddInventoryActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { // return; // } // startActivity(lvIntent); } }); // OnTouchListeners txtProductName.setOnTouchListener(mTouchListener); txtProductPrice.setOnTouchListener(mTouchListener); txtProductQuantity.setOnTouchListener(mTouchListener); txtSupplierName.setOnTouchListener(mTouchListener); txtSupplierPhone.setOnTouchListener(mTouchListener); btnIncreaseQuantity.setOnTouchListener(mTouchListener); btnDecreaseQuantity.setOnTouchListener(mTouchListener); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { String[] projection = { InventoryEntry._ID, InventoryEntry.COLUMN_PRODUCT_NAME, InventoryEntry.COLUMN_PRODUCT_PRICE, InventoryEntry.COLUMN_PRODUCT_QTY, InventoryEntry.COLUMN_SUPPLIER_NAME, InventoryEntry.COLUMN_SUPPLIER_PHONE}; return new CursorLoader( this, mCurrentUri, projection, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Bail early if the cursor is null or there is less than 1 row in the cursor if (data == null || data.getCount() < 1) { return; } // Proceed with moving to the first row of the cursor and reading data from it if (data.moveToFirst()) { int itemNameColumnIndex = data.getColumnIndex(InventoryEntry.COLUMN_PRODUCT_NAME); int itemPriceColumnIndex = data.getColumnIndex(InventoryEntry.COLUMN_PRODUCT_PRICE); int itemQuantityColumnIndex = data.getColumnIndex(InventoryEntry.COLUMN_PRODUCT_QTY); int supplierNameColumnIndex = data.getColumnIndex(InventoryEntry.COLUMN_SUPPLIER_NAME); int supplierPhoneColumnIndex = data.getColumnIndex(InventoryEntry.COLUMN_SUPPLIER_PHONE); // Extract out the value from the Cursor for the given column index String itemName = data.getString(itemNameColumnIndex); double itemPrice = data.getDouble(itemPriceColumnIndex); int itemQuantity = data.getInt(itemQuantityColumnIndex); String supplierName = data.getString(supplierNameColumnIndex); String supplierPhone = data.getString(supplierPhoneColumnIndex); // Update the views on the screen with the values from the database txtProductName.setText(itemName); txtProductPrice.setText(Double.toString(itemPrice)); txtProductQuantity.setText(Integer.toString(itemQuantity)); txtSupplierName.setText(supplierName); txtSupplierPhone.setText(supplierPhone); } } @Override public void onLoaderReset(Loader<Cursor> loader) { txtProductName.setText(""); txtProductPrice.setText("0"); txtProductQuantity.setText("1"); txtSupplierName.setText(""); txtSupplierPhone.setText(""); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (mCurrentUri == null) { MenuItem menuItem = menu.findItem(R.id.action_delete_item); if (menuItem != null) { menuItem.setVisible(false); } } return true; } @Override public void onBackPressed() { if (!mItemChanged) { // simply return if no update has been made super.onBackPressed(); return; } // create the listener for the ui dialog DialogInterface.OnClickListener discardButtonClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }; // display dialog to the user showUnsavedChangesDialog(discardButtonClickListener); } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); // User clicked on a menu option in the app bar overflow menu switch (item.getItemId()) { // Respond to a click on the "Save" menu option case R.id.action_insert_item: // Add a Pet to the DB boolean returnMsg = addProduct(); // Exit the activity and go back to MainActivity if (returnMsg) { finish(); return true; } else { return true; } // Respond to a click on the "Delete" menu option case R.id.action_delete_item: // Pop up confirmation dialog for deletion showDeleteConfirmationDialog(); return true; // Respond to a click on the "Up" arrow button in the app bar case android.R.id.home: // If the item hasn't changed, continue with navigating up to parent activity if (!mItemChanged) { NavUtils.navigateUpFromSameTask(AddInventoryActivity.this); return true; } // Otherwise if there are unsaved changes, setup a dialog to warn the user. // Create a click listener to handle the user confirming that // changes should be discarded. DialogInterface.OnClickListener discardButtonClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // User clicked "Discard" button, navigate to parent activity. NavUtils.navigateUpFromSameTask(AddInventoryActivity.this); } }; // Show a dialog that notifies the user they have unsaved changes showUnsavedChangesDialog(discardButtonClickListener); return true; case R.id.action_delete_all_entries: deleteAllProducts(); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_inventory_editor, menu); return true; } private boolean addProduct() { String itemName = txtProductName.getText().toString().trim(); String itemPrice = txtProductPrice.getText().toString().trim(); String itemQuantity = txtProductQuantity.getText().toString().trim(); String supplierName = txtSupplierName.getText().toString().trim(); String supplierPhone = txtSupplierPhone.getText().toString().trim(); Log.e(LOG_TAG, String.valueOf(mCurrentUri)); if (mCurrentUri == null && validateViews()) { return false; } else if (mCurrentUri != null && validateViews()) { return false; } else { double price = 0; int quantity = 0; if (!TextUtils.isEmpty(itemPrice)) { price = Double.parseDouble(itemPrice); } if (!TextUtils.isEmpty(itemQuantity)) { quantity = Integer.parseInt(itemQuantity); } ContentValues values = new ContentValues(); values.put(InventoryEntry.COLUMN_PRODUCT_NAME, itemName); values.put(InventoryEntry.COLUMN_PRODUCT_PRICE, price); values.put(InventoryEntry.COLUMN_PRODUCT_QTY, quantity); values.put(InventoryEntry.COLUMN_SUPPLIER_NAME, supplierName); values.put(InventoryEntry.COLUMN_SUPPLIER_PHONE, supplierPhone); if (mCurrentUri == null) { Uri uri = getContentResolver().insert(InventoryEntry.CONTENT_URI, values); if (uri != null) { Toast.makeText(this, getString(R.string.add_item_sucess), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, getString(R.string.add_item_failed), Toast.LENGTH_SHORT).show(); } } else { int rowsAffected = getContentResolver().update(mCurrentUri, values, null, null); // Show a toast message depending on whether or not the update was successful. if (rowsAffected == 0) { // If no rows were affected, then there was an error with the update. Toast.makeText(this, getString(R.string.update_item_failed), Toast.LENGTH_SHORT).show(); } else { // Otherwise, the update was successful and we can display a toast. Toast.makeText(this, getString(R.string.update_item_success), Toast.LENGTH_SHORT).show(); } } return true; } } private void deleteProduct() { // Only perform the delete if this is an existing item. if (mCurrentUri != null) { // Call the ContentResolver to delete the product at the given content URI. int rowsDeleted = getContentResolver().delete( mCurrentUri, null, null); // Show a toast message depending on whether or not the delete was successful. if (rowsDeleted == 0) { // If no rows were deleted, then there was an error with the delete. Toast.makeText( this, getString(R.string.delete_item_failed), Toast.LENGTH_SHORT).show(); } else { // Otherwise, the delete was successful and we can display a toast. Toast.makeText( this, getString(R.string.delete_item_sucess), Toast.LENGTH_SHORT).show(); } } // Close the activity finish(); } private void deleteAllProducts() { int rowsDeleted = getContentResolver().delete( InventoryEntry.CONTENT_URI, null, null); Toast.makeText( this, rowsDeleted + " rows were deleted from " + InventoryEntry.TABLE_NAME, Toast.LENGTH_SHORT).show(); } private void showDeleteConfirmationDialog() { // Create an AlertDialog.Builder and set the message, and click listeners // for the positive and negative buttons on the dialog. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.delete_confirmation); builder.setPositiveButton(R.string.delete_item, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Delete" button, so delete the pet. deleteProduct(); } }); builder.setNegativeButton(R.string.delete_item_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Cancel" button, so dismiss the dialog if (dialog != null) { dialog.dismiss(); } } }); // Create and show the AlertDialog AlertDialog alertDialog = builder.create(); alertDialog.show(); } private void showUnsavedChangesDialog(DialogInterface.OnClickListener discardButtonClickListener) { // Create an AlertDialog.Builder and set the message AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.unsaved_changes); builder.setPositiveButton(R.string.discard, discardButtonClickListener); builder.setNegativeButton(R.string.keep_editing, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Keep editing" button, so dismiss the dialog if (dialog != null) { dialog.dismiss(); } } }); // Create and show the AlertDialog AlertDialog alertDialog = builder.create(); alertDialog.show(); } private void showTelephoneDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); final String supplierTelephone = txtSupplierPhone.getText().toString(); final String questionString = "Would you like to contact the Supplier to '"; builder.setMessage(questionString + supplierTelephone + "' ?"); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent lvIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + supplierTelephone)); if (ActivityCompat.checkSelfPermission(AddInventoryActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { return; } startActivity(lvIntent); } }); builder.setNegativeButton(R.string.delete_item_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Cancel" button, so dismiss the dialog if (dialog != null) { dialog.dismiss(); } } }); // Create and show the AlertDialog AlertDialog alertDialog = builder.create(); alertDialog.show(); } private boolean validateViews() { // returns true if empty or non valid values in the Views if (txtProductName.getText().toString().isEmpty()) { Toast.makeText(this, getString(R.string.fill_out_product_name), Toast.LENGTH_SHORT).show(); return true; } else if (txtProductPrice.getText().toString().isEmpty()) { Toast.makeText(this, getString(R.string.fill_out_product_price), Toast.LENGTH_SHORT).show(); return true; } else if (txtProductQuantity.getText().toString().isEmpty()) { Toast.makeText(this, getString(R.string.fill_out_product_quantity), Toast.LENGTH_SHORT).show(); return true; } else if (txtSupplierName.getText().toString().isEmpty()) { Toast.makeText(this, getString(R.string.fill_out_supplier_name), Toast.LENGTH_SHORT).show(); return true; } else if (txtSupplierPhone.getText().toString().isEmpty() && !PhoneNumberUtils.isGlobalPhoneNumber(txtSupplierPhone.getText().toString())) { Toast.makeText(this, getString(R.string.fill_out_telephone), Toast.LENGTH_SHORT).show(); return true; } return false; } }
c953cdf3d644bdef5adaf560e37c4b89440e1b39
[ "Java" ]
2
Java
dafer660/InventoryApp
f8c7adb599f77175e2e785684c8ad6bec37870ae
008a59a3a44dc9e4fd5a8ca2241ea029f7166fae
refs/heads/master
<file_sep> var showingSourceCode = false; var isInEditMode = true; function enableEditMode() { TextField.document.designMode = 'On'; } function execCmd(command) { TextField.document.execCommand(command, false, null); } function execCommandWithArg(command,arg) { TextField.document.execCommand(command, false, arg); } function toggleSource(){ if (showingSourceCode) { TextField.document.getElementsByTagName('body')[0].innerHTML = TextField.document.getElementsByTagName('body')[0]. textContent; showingSourceCode = false; }else{ TextField.document.getElementsByTagName('body')[0].textContent = TextField.document.getElementsByTagName('body')[0]. innerHTML; showingSourceCode = true; }; } function toggleEdit(){ if (isInEditMode) { TextField.document.designMode = 'Off'; isInEditMode = false; }else{ TextField.document.designMode = 'On'; isInEditMode = true; }; } function submit_form(){ var theForm = document.getElementById("wysiwyg"); theForm.elements['textarea'].value = window.frame['TextField'].document.body.innerHTML; theForm.submit(); //console.log(theForm); }
09f281e571a7bffb19bf20ec1fd0ce2fcbd71583
[ "JavaScript" ]
1
JavaScript
Amriesgrace/WYSIWYG
11a11c4e838ea4fc224492af74c0ac37cffbf001
19b7c3058146b0797db230b3210933464016d92b
refs/heads/main
<file_sep><?php namespace App\Http\Controllers; use App\Models\Blog; use App\Models\Receta; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Intervention\Image\Facades\Image; use Illuminate\Support\Facades\Storage; class RecetaController extends Controller { public function __construct() { $this->middleware('auth', ['except' => 'show']); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $usuario = auth()->user()->id; //Recetas con paginación $recetas = Receta::where('user_id', $usuario)->simplePaginate(3); $blogs = Blog::where('user_id', $usuario)->simplePaginate(3); //$recetas = Auth::user()->recetas; return view('recetas.index', compact('recetas',$recetas), compact('blogs',$blogs)); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // return view("recetas.create"); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // //dd($request['imagen']->store('upload-obras', 'public')); $data = request()->validate([ 'titulo' => 'required', 'autor' => 'required', 'tipo' => 'required', 'tamanio' => 'required', 'precio' => 'required', 'imagen' => 'required|image', 'urlCompra' => 'required', ]); //$rutaImagen = $request['imagen']->store('upload-obras', 'public'); //$rutaImagen = request()->file('imagen')->store( // 'images', // 's3' //); $extension = $request->file('imagen')->extension(); $rutaImagen = Storage::disk('s3')->putFileAs('images', $request->file('imagen'),time().'.'.$extension,'public'); //$img = Image::make(public_path("storage/{$rutaImagen}")); //$img->save(); /* DB::table('recetas')->insert([ 'titulo' => $data['titulo'], 'autor' => $data['autor'], 'tipo' => $data['tipo'], 'tamanio' => $data['tamanio'], 'precio' => $data['precio'], 'user_id' => Auth::user()->id, 'imagen' => $rutaImagen, ]); */ //Almacenar en la base de datos con un modelo auth()->user()->recetas()->create([ 'titulo' => $data['titulo'], 'autor' => $data['autor'], 'tipo' => $data['tipo'], 'tamanio' => $data['tamanio'], 'precio' => $data['precio'], 'urlCompra' => $data['urlCompra'], 'imagen' => $rutaImagen, ]); //Redireccionar return redirect()->action('App\\Http\\Controllers\\RecetaController@index'); } /** * Display the specified resource. * * @param \App\Models\Receta $receta * @return \Illuminate\Http\Response */ public function show(Receta $receta) { // return view("recetas.show", compact('receta')); } /** * Show the form for editing the specified resource. * * @param \App\Models\Receta $receta * @return \Illuminate\Http\Response */ public function edit(Receta $receta) { // return view("recetas.edit", compact('receta')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Receta $receta * @return \Illuminate\Http\Response */ public function update(Request $request, Receta $receta) { //Revisar el policy $this->authorize('update', $receta); //Validación $data = request()->validate([ 'titulo' => 'required', 'autor' => 'required', 'tipo' => 'required', 'tamanio' => 'required', 'precio' => 'required', 'urlCompra' => 'required', ]); $receta->titulo = $data['titulo']; $receta->autor = $data['autor']; $receta->tipo = $data['tipo']; $receta->tamanio = $data['tamanio']; $receta->precio = $data['precio']; $receta->urlCompra = $data['urlCompra']; if(request('imagen')){ $extension = $request->file('imagen')->extension(); $rutaImagen = Storage::disk('s3')->putFileAs('images', $request->file('imagen'),time().'.'.$extension,'public'); $receta->imagen = $rutaImagen; } $receta->save(); //Redireccionar return redirect()->action('App\\Http\\Controllers\\RecetaController@index'); } /** * Remove the specified resource from storage. * * @param \App\Models\Receta $receta * @return \Illuminate\Http\Response */ public function destroy(Receta $receta) { $this->authorize('delete', $receta); // $receta->delete(); return redirect()->action('App\\Http\\Controllers\\RecetaController@index'); } } <file_sep><?php namespace App\Http\Controllers; use App\Models\Blog; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Intervention\Image\Facades\Image; use Illuminate\Support\Facades\Storage; class BlogController extends Controller { public function __construct() { $this->middleware('auth', ['except' => ['show', 'index']]); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // $blogs = Blog::get(); return view('blogs.index', compact('blogs')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // return view("blogs.create"); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $data = request()->validate([ 'titulo' => 'required', 'autor' => 'required', 'portada' => 'required|image', 'contenido' => 'required', ]); $extension = $request->file('portada')->extension(); $rutaImagen = Storage::disk('s3')->putFileAs('images', $request->file('portada'),time().'.'.$extension,'public'); //Almacenar en la base de datos con un modelo auth()->user()->blogs()->create([ 'titulo' => $data['titulo'], 'autor' => $data['autor'], 'contenido' => $data['contenido'], 'portada' => $rutaImagen, ]); //Redireccionar return redirect()->action('App\\Http\\Controllers\\RecetaController@index'); } /** * Display the specified resource. * * @param \App\Models\Blog $blog * @return \Illuminate\Http\Response */ public function show(Blog $blog) { // return view("blogs.show", compact('blog')); } /** * Show the form for editing the specified resource. * * @param \App\Models\Blog $blog * @return \Illuminate\Http\Response */ public function edit(Blog $blog) { // return view("blogs.edit", compact('blog')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Blog $blog * @return \Illuminate\Http\Response */ public function update(Request $request, Blog $blog) { // //Validación $data = request()->validate([ 'titulo' => 'required', 'autor' => 'required', 'contenido' => 'required', ]); $blog->titulo = $data['titulo']; $blog->autor = $data['autor']; $blog->contenido = $data['contenido']; if(request('imagen')){ $extension = $request->file('portada')->extension(); $rutaImagen = Storage::disk('s3')->putFileAs('images', $request->file('portada'),time().'.'.$extension,'public'); $blog->imagen = $rutaImagen; } $blog->save(); //Redireccionar return redirect()->action('App\\Http\\Controllers\\RecetaController@index'); } /** * Remove the specified resource from storage. * * @param \App\Models\Blog $blog * @return \Illuminate\Http\Response */ public function destroy(Blog $blog) { // // $blog->delete(); return redirect()->action('App\\Http\\Controllers\\RecetaController@index'); } } <file_sep><?php namespace App\Http\Controllers; use App\Models\Blog; use App\Models\Receta; use Illuminate\Http\Request; class InicioController extends Controller { // public function index(){ $obras = Receta::latest()->take(3)->get(); $blogs = Blog::latest()->take(3)->get(); return view('inicio.index', compact('obras'), compact('blogs')); } } <file_sep><?php namespace App\Http\Controllers; use App\Models\Receta; use App\Models\Blog; use Illuminate\Http\Request; class ObraController extends Controller { // public function index() { $todas = Receta::get(); $blogs = Blog::get(); return view('obras.obras', compact('todas'), compact('blogs')); } } <file_sep><?php use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', 'App\\Http\\Controllers\\InicioController@index', 'https')->name('inicio.index'); Route::get('/obras', 'App\\Http\\Controllers\\ObraController@index', 'https')->name("obras.index"); Route::get('/contactanos', 'App\\Http\\Controllers\\ContactanosController@index', 'https')->name('contactanos.index'); Route::post('/contactanos', 'App\\Http\\Controllers\\ContactanosController@store', 'https')->name('contactanos.store'); Route::get('/nosotros', 'App\\Http\\Controllers\\NosotrosController@index', 'https')->name('nosotros.index'); Route::get('/recetas', 'App\\Http\\Controllers\\RecetaController@index', 'https')->name("recetas.index"); Route::get('/recetas/create', 'App\\Http\\Controllers\\RecetaController@create', 'https')->name("recetas.create"); Route::post('/recetas', 'App\\Http\\Controllers\\RecetaController@store', 'https')->name("recetas.store"); Route::get('/recetas/{receta}', 'App\\Http\\Controllers\\RecetaController@show', 'https')->name("recetas.show"); Route::get('/recetas/{receta}/edit', 'App\\Http\\Controllers\\RecetaController@edit', 'https')->name("recetas.edit"); Route::put('/recetas/{receta}', 'App\\Http\\Controllers\\RecetaController@update', 'https')->name("recetas.update"); Route::delete('/recetas/{receta}', 'App\\Http\\Controllers\\RecetaController@destroy', 'https')->name("recetas.destroy"); Route::get('/blogs', 'App\\Http\\Controllers\\BlogController@index', 'https')->name("blogs.index"); Route::get('/blogs/create', 'App\\Http\\Controllers\\BlogController@create', 'https')->name("blogs.create"); Route::post('/blogs', 'App\\Http\\Controllers\\BlogController@store', 'https')->name("blogs.store"); Route::get('/blogs/{blog}', 'App\\Http\\Controllers\\BlogController@show', 'https')->name("blogs.show"); Route::get('/blogs/{blog}/edit', 'App\\Http\\Controllers\\BlogController@edit', 'https')->name("blogs.edit"); Route::put('/blogs/{blog}', 'App\\Http\\Controllers\\BlogController@update', 'https')->name("blogs.update"); Route::delete('/blogs/{blog}', 'App\\Http\\Controllers\\BlogController@destroy', 'https')->name("blogs.destroy"); //Route::get('/recetas', 'App\\Http\\Controllers\\RecetaController'); Así se declara con nombre completo del controller Auth::routes();
8a142c3e4a153b7af28aed7e5d1127da7a70f9f4
[ "PHP" ]
5
PHP
Ruveloc02/MuseoDisrupcionMX
cee6b9b8f587dbfbb66f66bd12a2ebd7a8861b67
a16e8c5e948360ea12ea66631a4ddb3da82f61e4
refs/heads/master
<file_sep>package cn.zucc.day02; import java.util.Scanner; public class Demo { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub /* double discount = 0; Scanner sc=new Scanner(System.in); System.out.println("请输入会员积分:"); int x = sc.nextInt(); if(x<2000){ discount=0.9; } if((x>=2000)&&(x<4000)){ discount=0.8; } if((x>=4000)&&(x<8000)){ discount=0.7; } if(x>8000){ discount=0.6; } System.out.println("您的折扣为:"+discount); Scanner sc=new Scanner(System.in); System.out.println("请输入存款:"); int money = sc.nextInt(); if(money<100000){ System.out.println("买捷安特"); } if((money>=100000)&&(money<500000)){ System.out.println("奥拓"); } if((money>=500000)&&(money<1000000)){ System.out.println("伊兰特"); } if((money>1000000)&&(money<5000000)){ System.out.println("帕萨特"); } if(money>=5000000){ System.out.println("凯迪拉克"); } double discount=1.0; Scanner sc=new Scanner(System.in); System.out.println("请输入是否会员:是(y)/否(其他字符)"); String qqq= sc.next(); System.out.println("请输入购物金额:"); int money= sc.nextInt(); if(qqq.equals("y")){ if(money<200){ discount=0.8; } else discount=0.75; } else if(money>=100){ discount=0.9; } else discount=1.0; double pay=money*discount; System.out.println("实际支付:"+pay); */ Scanner sc=new Scanner(System.in); System.out.println("请输入消费金额:"); double pay=sc.nextDouble(); System.out.println("是否参加换购活动:"); System.out.println("1.满50元,加2元换购百事可乐一瓶"); System.out.println("2.满100元,加3元换购500ml可乐一瓶"); System.out.println("3.满100元,加10元换购5公斤面粉"); System.out.println("4.满200元,加10元换购苏泊尔炒菜锅"); System.out.println("5.满200元,加20元换购欧莱雅爽肤水"); System.out.println("0.不换购"); System.out.println("请选择:"); int number=sc.nextInt(); double pay2; double pay3; if(pay<50){ pay3= pay; System.out.println("本次消费"+pay3); } if(pay>=200){ switch (number) { case 1: pay2=2; pay3=pay+pay2; System.out.println("本次消费"+pay3); System.out.println("成功换购:一瓶百事可乐"); break; case 2: pay2=10; pay3=pay+pay2; System.out.println("本次消费"+pay3); System.out.println("成功换购:500ml可乐一瓶"); break; case 3: pay2=2; pay3=pay+pay2; System.out.println("本次消费"+pay3); System.out.println("成功换购:5公斤面粉"); break; case 4: pay2=10; pay3=pay+pay2; System.out.println("本次消费"+pay3); System.out.println("成功换购:苏泊尔炒菜锅一只"); break; case 5: pay2=20; pay3=pay+pay2; System.out.println("本次消费"+pay3); System.out.println("成功换购:欧莱雅爽肤水一瓶"); break; default: pay2=0; pay3=pay+pay2; System.out.println("本次消费"+pay3); break; } } if((pay>=100)&&(pay<200)){ switch (number) { case 1: pay2=2; pay3=pay+pay2; System.out.println("本次消费"+pay3); System.out.println("成功换购:一瓶百事可乐"); break; case 2: pay2=10; pay3=pay+pay2; System.out.println("本次消费"+pay3); System.out.println("成功换购:500ml可乐一瓶"); break; case 3: pay2=2; pay3=pay+pay2; System.out.println("本次消费"+pay3); System.out.println("成功换购:5公斤面粉"); break; default: pay2=0; pay3=pay+pay2; System.out.println("本次消费"+pay3); break; } } if((pay>=50)&&(pay<100)){ switch (number) { case 1: pay2=2; pay3=pay+pay2; System.out.println("本次消费"+pay3); System.out.println("成功换购:一瓶百事可乐"); break; default: pay2=0; pay3=pay+pay2; System.out.println("本次消费"+pay3); break; } } } } <file_sep>package cn.zucc.day02; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Administrator admin1= new Administrator(); admin1.name="admin1"; admin1.password=<PASSWORD>; admin1.show(); Administrator admin2= new Administrator(); admin2.name="admin2"; admin2.password=<PASSWORD>; admin2.show(); } } <file_sep>package cn.zucc.day02; public class Administrator { String name; int password; public void show(){ System.out.println("ΣΓ»§Γϋ£Ί"+name+"ΓάΒλ£Ί"+password); } } <file_sep>package cn.zucc.day02; public class ScoreSalc { int score1; int score2; int score3; public void show(){ int sum= score1+score2+score3; int avg= sum/3; System.out.println("总成绩是:"+sum); System.out.println("平均成绩是:"+avg); } } <file_sep>package cn.zucc.day02; public class Test2 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Customer cus=new Customer(); cus.point=3050; cus.card="½ð¿¨"; cus.show(); } } <file_sep>package cn.zucc.day02; import java.util.Scanner; public class Test1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Administrator2 admin= new Administrator2(); int password2=<PASSWORD>; Scanner sc =new Scanner(System.in); System.out.print("请输入用户名:"); String name1 = sc.next(); System.out.print("请输入密码:"); int password1 = sc.nextInt(); //System.out.println(password2); if((password2==password1)&&(name1==admin.name)){ System.out.print("请输入新的密码:"); int password3= sc.nextInt(); System.out.print("请再次输入新的密码:"); int password4= sc.nextInt(); do{ System.out.println("两次输入的密码不一致,请重新输入!!!"); System.out.print("请输入新的密码:"); password3= sc.nextInt(); System.out.print("请再次输入新的密码:"); password4= sc.nextInt(); }while(password3!=password4); System.out.println("修改密码成功,您的新密码为:"+password3); } } }
0329f2c01b4a330451d19aed727ec503faa906f0
[ "Java" ]
6
Java
SpriteNo/JavaSe2
a7941ba27d76a75cdf4f4c0b680d92f3aa4199ce
c4a7c60096d8faf50386cfd878ef8c6fab840e48
refs/heads/master
<file_sep> $(document).ready(function($) { $(".nav li").mouseenter(function(event) { $(this).find('dl').stop().slideDown(); }); $(".nav li").mouseleave(function(event) { $(this).find('dl').stop().slideUp(); }); $('.nav-btn').click(function(event) { $('.nv-sub').slideToggle(); }); // 返回顶部 $('.Btntop').click(function(){ $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $(window).scroll(function(){ var _top = $(window).scrollTop(); if( _top<200 ){ $('.fix-float').stop().fadeOut(); }else{ $('.fix-float').stop().fadeIn(); } }); // 弹出框 $('.myfancy').click(function(){ var _id = $(this).attr('href'); $(_id).show(); }); $('.close').click(function(){ $(this).parents('.m-pop').hide(); }); $('.close').click(function(){ $(this).parents('.m-invoice').hide(); }); // 点击展开 $('.snav .open').find('dl').stop().slideDown(); $('.snav li').click(function(){ $(this).siblings('.snav li').removeClass('open').find('dl').stop().slideUp(); $(this).toggleClass('open'); if( $(this).hasClass('open') ){ $(this).find('dl').stop().slideDown(); }else{ $(this).find('dl').stop().slideUp(); } }); // 选项卡 鼠标经过切换 $(".TAB li").mousemove(function(){ var tab=$(this).parent(".TAB"); var con=tab.attr("id"); var on=tab.find("li").index(this); $(this).addClass('hover').siblings(tab.find("li")).removeClass('hover'); $(con).eq(on).show().siblings(con).hide(); }); // 选项卡 鼠标点击 $(".TAB_CLICK li").click(function(){ var tab=$(this).parent(".TAB_CLICK"); var con=tab.attr("id"); var on=tab.find("li").index(this); $(this).addClass('on').siblings(tab.find("li")).removeClass('on'); $(con).eq(on).show().siblings(con).hide(); }); function myBox(){ var _winw = $(window).width(); var _sheight = $('.side-col2').height(); var _mheight = $('.main-col2').height(); if( _winw>=992 ){ $('.side-col2,.main-col2').height(Math.max(_sheight,_mheight)); }else{ $('.side-col2,.main-col2').height('auto'); } } myBox(); $(window).on('resize',function(){ myBox(); }); });<file_sep># yinong 5811PC项目
e020519dc811e5c10153b18acc6866e8f6c3442e
[ "JavaScript", "Markdown" ]
2
JavaScript
guoxiujuan/yinong
1f47ef300659fc93b63f5e84da7f362419b323fd
600c4c52bcac469cb0eba7288a0f02b894aee538
refs/heads/master
<repo_name>MatthewShinkfield/ContractorClient<file_sep>/ContractorClient/Models/Contractor.cs using System; using System.Collections.Generic; namespace ContractorClient.Models { [Serializable] public class Contractor: IQMDataObject { public string Name { get; set; } public string Landline { get; set; } public string Mobile { get; set; } public string Email { get; set; } public string Address { get; set; } public int EmployeeID { get; set; } /// <summary> /// Empty Constructor for Contractor /// </summary> public Contractor() { } /// <summary> /// Constructor for Contractor /// </summary> /// <param name="id"></param> /// <param name="name"></param> /// <param name="landline"></param> /// <param name="mobile"></param> /// <param name="email"></param> /// <param name="address"></param> /// <param name="employeeId"></param> public Contractor(int id, string name,string landline, string mobile, string email, string address, int employeeId) { this.Id = id; this.Name = name; this.Landline = landline; this.Mobile = mobile; this.Email = email; this.Address = address; this.EmployeeID = employeeId; } public override object[] AllVariables => new object[] { Id, Name, Landline, Mobile, Email, EmployeeID, Address }; public override string ToString() => "{" + $"ID:{Id}, Name:{Name}, Landline:{Landline}, Mobile:{Mobile}, Email:{Email},Address:{Address}, EmployeeID:{EmployeeID}" + "}"; public override bool Equals(object obj) { var contractor = obj as Contractor; return contractor != null && Name == contractor.Name && Landline == contractor.Landline && Mobile == contractor.Mobile && Email == contractor.Email && Address == contractor.Address && EmployeeID == contractor.EmployeeID; } public override int GetHashCode() { var hashCode = 596822449; hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Name); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Landline); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Mobile); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Email); hashCode = hashCode * -1521134295 + EqualityComparer<int>.Default.GetHashCode(EmployeeID); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Address); return hashCode; } } } <file_sep>/ContractorClient/Partial Forms/IQMSerializer.cs using ContractorClient.Models; using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Windows.Forms; namespace ContractorClient { public partial class ContractorClient : Form { /// <summary> /// Deserializes data given and converts it from the array of objects of objects into an array of the correct IQMDataObject child /// </summary> /// <param name="filepath"></param> /// <returns></returns> public bool FromArray(String filepath) { //Create stream and deserialize file into an array of objects FileStream stream = new FileStream(filepath, FileMode.Open); BinaryFormatter format = new BinaryFormatter(); Object[] objs = (Object[])format.Deserialize(stream); stream.Close(); //Arrays retrieved Object[] contractorVals = (Object[])objs[0]; Object[] clientsVals = (Object[])objs[1]; Object[] jobsVals = (Object[])objs[2]; //Set Contractor Contractor tempContractor = new Contractor((int)contractorVals[0], (String)contractorVals[1], (String)contractorVals[2], (String)contractorVals[3], (String)contractorVals[4], (String)contractorVals[6], (int)contractorVals[5]); if (!tempContractor.Equals(contractor)) { if (!hasExported) { DialogResult dialog = MessageBox.Show($"These jobs are for {tempContractor.Name}, currently added jobs will be removed\nDo you wish to export unsaved data before opening?", "Do you want to export before opening?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); if (dialog == DialogResult.Yes) { saveAllBTN.PerformClick(); exportToolStripMenuItem.PerformClick(); } else if (dialog == DialogResult.Cancel) { return false; } else { hasExported = true; } if (!hasExported) { return false; } } finalJobs.Clear(); jobs.Clear(); } contractor = tempContractor; //Set List of Clients foreach (Object[] client in clientsVals) { //Client Client tempClient = new Client((int)client[0], (String)client[1], (String)client[2], (String)client[3], (String)client[4], (String)client[5], (String)client[6]); if (!clients.ContainsKey(tempClient.Id)) { clients.Add(tempClient.Id, tempClient); } } if (!hasExported) { DialogResult dialog = MessageBox.Show("You have unsaved/unexported data, jobs may be overwritten, do you wish to export before opening?", "Do you want to export before opening?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); if (dialog == DialogResult.Yes) { saveAllBTN.PerformClick(); exportToolStripMenuItem.PerformClick(); } else { hasExported = true; jobs.Clear(); } if (!hasExported) { return false; } } foreach (Object[] job in jobsVals) { Job tempJob = new Job((int)job[0], (int)job[1], (int)job[2], (String)job[3], (System.DateTime)job[5], (String)job[7], (int)job[6], (bool)job[8], (double)job[9], (String)job[4]); if (finalJobs.ContainsKey(tempJob.Id)) { finalJobs.Remove(tempJob.Id); finalJobs.Add(tempJob.Id, tempJob); } else { finalJobs.Add(tempJob.Id, tempJob); } } return true; } /// <summary> /// Serializes the IQMDataObject children into an array of objects of objects /// </summary> /// <param name="filename"></param> public void ToArray(String filename) { FileStream stream = new FileStream(filename, FileMode.Create); BinaryFormatter format = new BinaryFormatter(); Object[] objects = new Object[3]; objects[0] = contractor.AllVariables; List<object> clientsToSerialize = new List<object>(); List<object> jobsToSerialize = new List<object>(); foreach (Client client in clients.Values) { clientsToSerialize.Add(client.AllVariables); } foreach (Job job in finalJobs.Values) { jobsToSerialize.Add(job.AllVariables); } objects[1] = clientsToSerialize.ToArray(); objects[2] = jobsToSerialize.ToArray(); format.Serialize(stream, objects); stream.Close(); } } } <file_sep>/ContractorClient/Forms/ContractorClient.cs using ContractorClient.Models; using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Windows.Forms; namespace ContractorClient { public partial class ContractorClient : Form { public ContractorClient() { InitializeComponent(); } bool hasExported = true; Contractor contractor; Job job; Dictionary<int, Client> clients = new Dictionary<int, Client>(); Dictionary<int, Job> jobs = new Dictionary<int, Job>(); Dictionary<int, Job> finalJobs = new Dictionary<int, Job>(); //On Load Block-------------------------------------------------------------------------------------------------------- private void fieldEdit_Leave(object sender, EventArgs e) { //If fields haven't been changed double cost = 0; if (job.Completed == completedBox.Checked && job.WorkDescription == jobNotesTB.Text && (double.TryParse(jobChargedTB.Text, NumberStyles.Currency, CultureInfo.CreateSpecificCulture("en-AU"), out cost) && job.Cost == cost)) { return; } if (hasExported) { hasExported = false; } if (!jobs.ContainsKey(job.Id)) { jobsDataGrid.CurrentRow.DefaultCellStyle.BackColor = Color.FromArgb(244, 67, 54); job = new Job(job); jobs[job.Id] = job; } if (sender == jobChargedTB) { decimal amount = 0; decimal.TryParse(jobChargedTB.Text.Replace("$", "").Replace(",", ""), out amount); jobChargedTB.Text = string.Format(CultureInfo.CreateSpecificCulture("en-AU"), "{0:C2}", amount); job.Cost = double.Parse(jobChargedTB.Text, NumberStyles.Currency); } if (sender == jobNotesTB) { job.WorkDescription = jobNotesTB.Text; } if (sender == completedBox) { job.Completed = completedBox.Checked; } } //Button Block-------------------------------------------------------------------------------------------------------------------------------------------------------- //Opens the Client info panel private void clientInfoBTN_Click(object sender, EventArgs e) { Client client = clients[job.ClientId]; ClientInfo form = new ClientInfo(client.Id, client.Name, client.Address,client.Landline,client.Mobile,client.Business,client.Email); form.ShowDialog(this); } //Controls charged textbox formatting private void jobChargedTB_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == Char.Parse(".")) { if (jobChargedTB.Text.Contains(".")){ e.Handled = true; } } else if (!char.IsNumber(e.KeyChar) && e.KeyChar != (char)Keys.Back) { e.Handled = true; } } //Saves all modifications private void saveAllBTN_Click(object sender, EventArgs e) { foreach (Job job in jobs.Values) { finalJobs[job.Id] = new Job(job); foreach (DataGridViewRow row in jobsDataGrid.Rows) { if (row.Cells["ID"].Value.Equals(job.Id)) { row.DefaultCellStyle.BackColor = Color.FromArgb(139, 195, 74); break; } } } jobs.Clear(); } //Saves only modifications to the open job private void saveBTN_Click(object sender, EventArgs e) { finalJobs[job.Id] = new Job(job); jobs.Remove(job.Id); jobsDataGrid.CurrentRow.DefaultCellStyle.BackColor = Color.FromArgb(139, 195, 74); } //Undos changes to the current job private void cancelBTN_Click(object sender, EventArgs e) { if (jobs.ContainsKey(job.Id)) { job = new Job(finalJobs[job.Id]); jobs.Remove(job.Id); jobsDataGrid.CurrentRow.DefaultCellStyle.BackColor = Color.FromArgb(139, 195, 74); reloadJob(); } } //Sort Block---------------------------------------------------------------------------------------------------------------------------------------- private void jobsDataGrid_SortCompare(object sender, DataGridViewSortCompareEventArgs e) { if (e.Column.Name.Equals("priority")) { int cell1 = jobs[(int)jobsDataGrid.Rows[e.RowIndex1].Cells["ID"].Value].Id; int cell2 = jobs[(int)jobsDataGrid.Rows[e.RowIndex2].Cells["ID"].Value].Id; e.SortResult = cell1.CompareTo(cell2); e.Handled = true; } } private void reloadJob() { //Enable initially disabled elements if (job == null) { completedBox.Enabled = false; jobChargedTB.Enabled = false; jobNotesTB.Enabled = false; exportToolStripMenuItem.Enabled = false; printToolStripMenuItem.Enabled = false; saveAllBTN.Enabled = false; saveBTN.Enabled = false; clientInfoBTN.Enabled = false; cancelBTN.Enabled = false; return; } completedBox.Enabled = true; jobChargedTB.Enabled = true; jobNotesTB.Enabled = true; exportToolStripMenuItem.Enabled = true; printToolStripMenuItem.Enabled = true; saveAllBTN.Enabled = true; saveBTN.Enabled = true; clientInfoBTN.Enabled = true; cancelBTN.Enabled = true; jobLBL.Text = job.Title; jobBusinessTB.Text = clients[job.ClientId].Business; jobAddressTB.Text = job.Location; jobTimeTB.Text = job.Datetime.ToString(); jobPriorityTB.Text = job.PriorityName(); completedBox.Checked = job.Completed; jobChargedTB.Text = string.Format(CultureInfo.CreateSpecificCulture("en-AU"), "{0:C2}", job.Cost); jobNotesTB.Text = job.WorkDescription; } private void jobsDataGrid_RowEnter(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1 || jobsDataGrid.CurrentRow == null) { return; } int id; if (int.TryParse(jobsDataGrid.Rows[e.RowIndex].Cells["ID"].Value.ToString(), out id)) { if (jobs.ContainsKey(id)) { job = jobs[id]; } else { job = new Job(finalJobs[id]); } } reloadJob(); } private void ContractorClient_FormClosing(object sender, FormClosingEventArgs e) { this.ActiveControl = null; if (!hasExported) { DialogResult dialog = MessageBox.Show("You have unsaved/unexported data, do you wish to export before quitting?", "Do you want to export before quitting?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); if (dialog == DialogResult.Yes){ saveAllBTN.PerformClick(); exportToolStripMenuItem.PerformClick(); } else { hasExported = true; } if (!hasExported) { e.Cancel = true; } } } private void fileToolStripMenuItem_Click(object sender, EventArgs e) { this.ActiveControl = null; } } } <file_sep>/ContractorClient/Forms/ClientInfo.cs using System; using System.Windows.Forms; namespace ContractorClient { public partial class ClientInfo : Form { public ClientInfo(int id, String name, String address, String landline, String mobile, String business, String email) { InitializeComponent(); clientName.Text = name + "'s Information"; clientAddressTB.Text = address; clientLandlineTB.Text = landline; clientMobileTB.Text = mobile; clientBusinessNameTB.Text = business; clientEmailTB.Text = email; this.Text = name + "'s Information - ID: " + id; } private void closeBTN_Click(object sender, EventArgs e) { this.Dispose(); } } } <file_sep>/ContractorClient/Partial Forms/IO.cs using ContractorClient.Models; using System; using System.Windows.Forms; namespace ContractorClient { public partial class ContractorClient : Form { private void openToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "JOBS (*.jobs) | *.jobs"; DialogResult result = openFileDialog.ShowDialog(); String loadName = openFileDialog.FileName; if (loadName == "") { return; } if (FromArray(loadName)) { jobsDataGrid.Rows.Clear(); foreach (Job job in finalJobs.Values) { int row = jobsDataGrid.Rows.Add(); jobsDataGrid.Rows[row].Cells["ID"].Value = job.Id; jobsDataGrid.Rows[row].Cells["Description"].Value = job.Title; jobsDataGrid.Rows[row].Cells["Priority"].Value = job.PriorityName(); } if (jobsDataGrid.Rows.Count >= 1) { this.ActiveControl = jobsDataGrid; jobsDataGrid_RowEnter(this, new DataGridViewCellEventArgs(0, 0)); //job = finalJobs.First().Value; reloadJob(); } } } private void exportToolStripMenuItem_Click(object sender, EventArgs e) { if (jobs.Count != 0) { DialogResult res = MessageBox.Show("There is unsaved data in this program, do you wish to save before exporting?", "Notice! Unsaved Data", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (res == DialogResult.Yes) { saveAllBTN.PerformClick(); } } SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "JOBS (*.jobs) | *.jobs"; DialogResult result = saveFileDialog.ShowDialog(); String saveName = saveFileDialog.FileName; if (saveName == "") { return; } ToArray(saveName); hasExported = true; } } } <file_sep>/ContractorClient/Models/IQMDataObject.cs using System; using System.Xml.Serialization; namespace ContractorClient.Models { [XmlInclude(typeof(Client))] [XmlInclude(typeof(Job))] [XmlInclude(typeof(Contractor))] [Serializable] public abstract class IQMDataObject { public int Id { get; set; } public abstract object[] AllVariables { get; } } } <file_sep>/ContractorClient/Models/Client.cs using System; using System.Collections.Generic; namespace ContractorClient.Models { [Serializable] public class Client : IQMDataObject { public string Name { get; set; } public string Landline { get; set; } public string Mobile { get; set; } public string Email { get; set; } public string Address { get; set; } public string Business { get; set; } /// <summary> /// Empty Constructor for Client /// </summary> public Client() { } /// <summary> /// Constructor for Client /// </summary> /// <param name="id"></param> /// <param name="name"></param> /// <param name="landline"></param> /// <param name="mobile"></param> /// <param name="email"></param> /// <param name="address"></param> /// <param name="business"></param> public Client(int id, string name, string landline, string mobile, string email, string address, string business) { Id = id; Name = name; Landline = landline; Mobile = mobile; Email = email; Address = address; Business = business; } /// <summary> /// Get's All Variables in an object array /// </summary> /// <returns></returns> public override object[] AllVariables => new object[] { Id, Name, Landline, Mobile, Email, Address, Business }; /// <summary> /// ToString Method /// </summary> /// <returns>Pretty String of Variables</returns> public override string ToString() => "{" + $"ID:{Id}, Name:{Name}, Landline:{Landline}, Mobile:{Mobile}, Email:{Email},Address:{Address}" + "}"; public override bool Equals(object obj) { var client = obj as Client; return client != null && Name == client.Name && Landline == client.Landline && Mobile == client.Mobile && Email == client.Email && Address == client.Address && Business == client.Business; } public override int GetHashCode() { var hashCode = -2079501184; hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Name); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Landline); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Mobile); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Email); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Address); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Business); return hashCode; } } } <file_sep>/ContractorClient/Models/Job.cs using System; using System.Collections.Generic; using System.Globalization; namespace ContractorClient.Models { [Serializable] public class Job: IQMDataObject { public int ClientId { get; set; } public int ContractorId { get; set; } public string Title { get; set; } public String WorkDescription { get; set; } public DateTime Datetime { get; set; } public string Location { get; set; } public int Priority { get; set; } public bool Completed { get; set; } public double Cost { get; set; } public Job() { } public Job(int id, int clientId, int contractorId, string title, DateTime datetime, String location, int priority, bool completed = false, double cost = 0.0, String workDescription = "") { this.Id = id; this.ClientId = clientId; this.ContractorId = contractorId; this.Title = title; this.Datetime = datetime; this.Location = location; this.Priority = priority; this.Completed = completed; this.Cost = cost; this.WorkDescription = workDescription; } public Job(Job job) { this.Id = job.Id; this.ClientId = job.ClientId; this.ContractorId = job.ContractorId; this.Title = job.Title; this.Datetime = job.Datetime; this.Location = job.Location; this.Priority = job.Priority; this.Completed = job.Completed; this.Cost = job.Cost; this.WorkDescription = job.WorkDescription; } public String PriorityName() { switch (Priority) { case 2: return "HIGH"; case 1: return "MEDIUM"; case 0: return "LOW"; } return ""; } public override object[] AllVariables => new object[] { Id, ClientId, ContractorId, Title, WorkDescription, Datetime, Priority, Location, Completed, Cost }; public override string ToString() => "{" + $"ID:{Id}, ClientID:{ClientId}, ContractorID:{ContractorId}, Title:{Title}, WorkDescription:{WorkDescription}, DateTime:{Datetime}, Priority:{PriorityName()}, Address:{Location}, Completed:{Completed}, Cost:{string.Format(CultureInfo.CreateSpecificCulture("en-AU"), "{0:C2}", Cost)}" + "}"; public override bool Equals(object obj) { var job = obj as Job; return job != null && ClientId == job.ClientId && ContractorId == job.ContractorId && Title == job.Title && WorkDescription == job.WorkDescription && Datetime == job.Datetime && Location == job.Location && Priority == job.Priority && Completed == job.Completed && Cost == job.Cost; } public override int GetHashCode() { var hashCode = 977509222; hashCode = hashCode * -1521134295 + ClientId.GetHashCode(); hashCode = hashCode * -1521134295 + ContractorId.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Title); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(WorkDescription); hashCode = hashCode * -1521134295 + Datetime.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Location); hashCode = hashCode * -1521134295 + Priority.GetHashCode(); hashCode = hashCode * -1521134295 + Completed.GetHashCode(); hashCode = hashCode * -1521134295 + Cost.GetHashCode(); return hashCode; } } } <file_sep>/ContractorClient/Partial Forms/Print.cs using ContractorClient.Models; using System; using System.Drawing; using System.Drawing.Printing; using System.Globalization; using System.Windows.Forms; namespace ContractorClient { public partial class ContractorClient : Form { private void printToolStripMenuItem_Click(object sender, EventArgs e) { Client client = clients[job.ClientId]; PrintDocument pd = new PrintDocument(); pd.PrintPage += new PrintPageEventHandler(this.PrintPageEvent); PrintDialog printDialog = new PrintDialog(); pd.DocumentName = "Invoice " + job.Id + " for " + client.Name + ".pdf"; printDialog.Document = pd; printDialog.UseEXDialog = true; if (printDialog.ShowDialog() == DialogResult.OK) { pd.Print(); } } private void PrintPageEvent(object sender, PrintPageEventArgs ev) { Client client = clients[job.ClientId]; Graphics g = ev.Graphics; float maxWidth = ev.PageSettings.PrintableArea.Width; float maxHeight = ev.PageSettings.PrintableArea.Height; float marginLeft = ev.PageSettings.Margins.Left; float marginRight = ev.PageSettings.Margins.Right; float marginTop = ev.PageSettings.Margins.Top; float marginBottom = ev.PageSettings.Margins.Bottom; SolidBrush solidBlackBrush = new SolidBrush(Color.Black); Font title = new Font("Arial", 32, FontStyle.Bold); Font heading = new Font("Arial", 20, FontStyle.Bold); Font smallheading = new Font("Arial", 14, FontStyle.Bold); Font text = new Font("Arial", 14); StringFormat centerFormat = new StringFormat(); centerFormat.LineAlignment = StringAlignment.Center; centerFormat.Alignment = StringAlignment.Center; StringFormat leftFormat = new StringFormat(); leftFormat.Alignment = StringAlignment.Near; StringFormat rightFormat = new StringFormat(); rightFormat.Alignment = StringAlignment.Far; //Draw Title g.DrawString("Invoice", title, solidBlackBrush, maxWidth / 2, marginTop, centerFormat); int y = Convert.ToInt32(g.MeasureString("Invoice".ToString(), title).Height + marginTop) + 20; //Draw Headings g.DrawString("Client Details", heading, solidBlackBrush, marginLeft, y, leftFormat); g.DrawString("Invoice Details", heading, solidBlackBrush, maxWidth - marginRight, y, rightFormat); y += Convert.ToInt32(g.MeasureString("Client Details".ToString() + "Invoice Details".ToString(), heading).Height) + 10; //Draw Name and Invoice ID in line int size = Convert.ToInt32(g.MeasureString("Name: " + client.Name + "Invoice ID: #".ToString() + job.Id.ToString(), text).Height); g.DrawString("Name: " + client.Name, text, solidBlackBrush, new RectangleF(marginLeft, y, (maxWidth - marginRight) / 2, size), leftFormat); g.DrawString("Invoice ID: #" + job.Id.ToString(), text, solidBlackBrush, maxWidth - marginRight, y, rightFormat); y += size + 6; //Draw Business name and Cost in line String cost = string.Format(CultureInfo.CreateSpecificCulture("en-AU"), "{0:C2}", job.Cost); size = Convert.ToInt32(g.MeasureString("Business: " + client.Business + "Cost: " + cost, text).Height); g.DrawString("Cost: " + cost, text, solidBlackBrush, maxWidth - marginRight, y, rightFormat); g.DrawString("Business: " + client.Business, text, solidBlackBrush, new RectangleF(marginLeft, y, (maxWidth - marginRight) / 2, size), leftFormat); y += size + 6; //Draw Email g.DrawString("Email: " + client.Email, text, solidBlackBrush, marginLeft, y, leftFormat); y += Convert.ToInt32(g.MeasureString("Email: " + client.Email, text).Height) + 6; //Draw Landline Number g.DrawString("Landline: " + client.Landline, text, solidBlackBrush, marginLeft, y, leftFormat); y += Convert.ToInt32(g.MeasureString("Landline: " + client.Landline, text).Height) + 6; //Draw Mobile Number g.DrawString("Mobile: " + client.Mobile, text, solidBlackBrush, marginLeft, y, leftFormat); y += Convert.ToInt32(g.MeasureString("Mobile: " + client.Mobile, text).Height) + 6; //Draw Address g.DrawString("Address: " + client.Address, text, solidBlackBrush, marginLeft, y, leftFormat); y += Convert.ToInt32(g.MeasureString("Address: " + client.Address, text).Height) + 40; //Draw Short Description //g.DrawString("Job Description", smallheading, solidBlackBrush, marginLeft, y, leftFormat); //y += Convert.ToInt32(g.MeasureString("Job Description", smallheading).Height) + 6; //g.DrawString(job.JobDescription, text, solidBlackBrush, marginLeft, y, leftFormat); //y += Convert.ToInt32(g.MeasureString(job.JobDescription, text).Height) + 6; //Draw Notes and Notes Box g.DrawString("Notes", smallheading, solidBlackBrush, marginLeft, y, leftFormat); y += Convert.ToInt32(g.MeasureString("Notes", smallheading).Height) + 6; String notes = "No Notes Given"; if (!job.WorkDescription.Equals("")) { notes = job.WorkDescription; } g.DrawString(notes, text, solidBlackBrush, new RectangleF(marginLeft + 5, y + 5, maxWidth - (marginRight * 2) - 5, maxHeight - y - marginBottom - 5), leftFormat); g.DrawRectangle(Pens.Black, new Rectangle(((int)marginLeft), y, ((int)maxWidth) - (((int)marginRight) * 2), ((int)maxHeight) - ((int)marginBottom) - y)); } } }
723481a4d28340d2324a4cfd5bc31ad47c4361b3
[ "C#" ]
9
C#
MatthewShinkfield/ContractorClient
53a2946c1b6ecae8dc65a6495ce87fadda194f3a
ebf674f8cc15b5273b748a45801e18ca290cfb3f
refs/heads/master
<repo_name>WebLanjut41-02/praktikum2-fitrianar<file_sep>/application/views/penghuni.php <!DOCTYPE html> <html> <head> <title></title> </head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <body> <div class="container"> <div class="row"> <div class="row mt-3"></div> <div class="col-md-6"> <center> <h1>Form Penghuni</h1> <form action="<?php echo base_url().'index.php/c_penghuni/prosesT'; ?>" method="post"> <table> <tr> <td>No KTP</td> <td>:</td> <td><input type="text" name="noKTP"></td> </tr> <tr> <td>Nama</td> <td>:</td> <td><input type="text" name="nama"></td> </tr> <tr> <td>Unit</td> <td>:</td> <td><input type="text" name="unit"></td> </tr> <tr> <td></td> <td><input type="submit" class="btn btn-primary" name="submit" value="Tambah"></td> <td></td> </tr> </table> </form> </center> </body> </html><file_sep>/application/controllers/c_penghuni.php <?php class c_penghuni extends CI_Controller{ public function __construct(){ parent::__construct(); $this->load->model('postM'); $this->load->helper('url'); } public function index(){ $data['penghuni'] = $this->postM->tampil_data()->result(); $this->load->view('t_penghuni', $data); } public function tambah(){ $this->load->view('penghuni'); } public function prosesT(){ $noKTP = $this->input->post('noKTP'); $nama = $this->input->post('nama'); $unit = $this->input->post('unit'); $data = array( 'noKTP'=>$noKTP, 'nama'=>$nama, 'unit'=>$unit); $this->postM->input_data($data,'penghuni'); redirect('c_penghuni/index'); } } ?>
ff91d141fb508faf36c575e08b7acd635a3e0cd8
[ "PHP" ]
2
PHP
WebLanjut41-02/praktikum2-fitrianar
2901a8d235c6c5691160255c33f1da70dd84abfe
7c3e1ca6cd0dfdb6cfc387fe5b5172bb5b3141fb
refs/heads/master
<file_sep>class PigLatinizer attr_accessor :piglatinized_phrase def piglatinize(str) if single_word?(str) if str.downcase.index(/[aeiou]/) == 0 str + "way" else vowel_index = str.index(/[aeiou]/) front_end = str.slice!(0..vowel_index-1) str + front_end +"ay" end else word_array = str.split(" ") @piglatinized_phrase = word_array.collect {|word| piglatinize(word)}.join(" ") end end def to_pig_latin(phrase) word_array = phrase.split(" ") @piglatinized_phrase = word_array.collect {|word| piglatinize(word)}.join(" ") end def single_word?(string) !string.strip.include? " " end end
1a226d85c5f1794d025b9b38113fa59a8f49950a
[ "Ruby" ]
1
Ruby
MattG-afk/sinatra-mvc-lab-onl01-seng-pt-030220
e2cb62ff1956e19d833e726e64fafea7bf03bc99
6476c8ee45db770e7b333c23e7206d39f0dda07a
refs/heads/main
<file_sep>package com.example.learningservice import android.app.Service import android.content.Intent import android.os.Binder import android.os.IBinder import android.util.Log import kotlinx.coroutines.* import java.util.Random class ServiceClass : Service() { private var job: Job? = null private val binder = MyServiceBinder() override fun onBind(intent: Intent?): IBinder? { return binder } override fun onCreate() { super.onCreate() Log.d("ServiceClass", "Service onCreate") } private val randomGenerator = Random() fun sendRandomNum() = randomGenerator.nextInt(100) override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { Log.d("ServiceClass", "Service onStartCommand") intent?.let { Log.d("ServiceClass", "Service started with name ${it.getStringExtra("name")}") } job = CoroutineScope(Dispatchers.Main).launch { for(i in 0..60){ Log.d("ServiceClass", "Running at $i") delay(1000L) if(i == 60){ stopSelf() } } } return super.onStartCommand(intent, flags, startId) } inner class MyServiceBinder : Binder() { fun getService() = this@ServiceClass } override fun onDestroy() { super.onDestroy() job?.cancel() Log.d("ServiceClass", "Service destroyed") } }<file_sep>package com.example.learningservice import android.content.ComponentName import android.content.Intent import android.content.ServiceConnection import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.IBinder import android.widget.Toast import com.example.learningservice.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding : ActivityMainBinding private lateinit var service : ServiceClass private var isBounded = false private var isServiceStarted = false private val connection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { val binder = service as ServiceClass.MyServiceBinder this@MainActivity.service = binder.getService() isBounded = true } override fun onServiceDisconnected(name: ComponentName?) { isBounded = false } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.btnStartService.setOnClickListener { val intent = Intent(this, ServiceClass::class.java) intent.putExtra("name", "Kshitij") isServiceStarted = true startService(intent) bindToService() } binding.btnStopService.setOnClickListener { isBounded = false unbindService(connection) stopService(Intent(this, ServiceClass::class.java)) isServiceStarted = false } binding.btnFetch.setOnClickListener { if(isBounded){ Toast.makeText(this, "The random num fetched is ${service.sendRandomNum()}", Toast.LENGTH_SHORT).show() } } } override fun onStart() { super.onStart() if(isServiceStarted){ bindToService() } } private fun bindToService() { val intent = Intent(this, ServiceClass::class.java) bindService(intent, connection, BIND_AUTO_CREATE) } override fun onStop() { super.onStop() unbindService(connection) isBounded = false } }
008edce91b2f023f9684b907d7f60940019fcf32
[ "Kotlin" ]
2
Kotlin
kshitijskumar/Learning-service
42ac8a63d25443f089f0e8175e21254278ac59f4
e4c93dfc8c9d1abb1ff010fe3d65e5b8fc011df7
refs/heads/master
<repo_name>Arahir/ngrx-party<file_sep>/src/app/person-list.ts import {Component, Input, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core'; @Component({ selector: 'person-list', template: ` <ul> <li *ngFor="#person of people" [class.attending]="person.attending" > {{person.name}} - Guests: {{person.guests}} <button (click)="addGuest.emit(person.id)">+</button> <button *ngIf="person.guests" (click)="removeGuest.emit(person.id)">-</button> Attending? <input type="checkbox" [checked]="person.attending" (change)="toggleAttending.emit(person.id)" /> <button (click)="removePerson.emit(person.id)">Delete</button> </li> </ul> `, changeDetection: ChangeDetectionStrategy.OnPush }) /* with 'onpush' change detection, components which rely solely on input can skip change detection until those input references change, this can supply a significant performance boost */ export class PersonList { /* "dumb" components do nothing but display data based on input and emit relevant events back up for parent, or "container" components to handle */ @Input() people; @Output() addGuest = new EventEmitter(); @Output() removeGuest = new EventEmitter(); @Output() removePerson = new EventEmitter(); @Output() toggleAttending = new EventEmitter(); } <file_sep>/src/app/party-stats.ts import {Component, Input, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core'; @Component({ selector: 'party-stats', template: ` <strong>Invited:</strong> {{invited}} <strong>Attending:</strong> {{attending}} <strong>Guests:</strong> {{guests}} `, changeDetection: ChangeDetectionStrategy.OnPush }) export class PartyStats { @Input() invited; @Input() attending; @Input() guests; } <file_sep>/src/app.ts import {bootstrap} from '@angular/platform-browser-dynamic'; import {provide, enableProdMode} from '@angular/core'; import {Store, provideStore, usePreMiddleware, usePostMiddleware} from '@ngrx/store'; import {actionLogger, stateLogger, localStorageMiddleware} from './app/middleware'; import {LocalStorageService} from './app/service'; import {reset, RESET_STATE} from './app/reset'; import {people} from './app/people'; import {partyFilter} from './app/party-filter'; import {SeedApp} from './app/seed-app'; // enableProdMode() bootstrap(SeedApp, [ LocalStorageService, //wrap people in reset meta-reducer provideStore({people}) ]) .catch(err => console.error(err)); <file_sep>/src/app/middleware.ts import {createMiddleware} from '@ngrx/store'; import {LocalStorageService} from './service'; //pre middleware takes an observable of actions, returning an observable export const actionLogger = action => { return action.do(a => console.log('DISPATCHED ACTION:', a)); } //post middleware takes an observable of state, returning observable export const stateLogger = state => { return state.do(s => console.log('NEW STATE:', s)); } //create middleware with a dependency on the localStorageService export const localStorageMiddleware = key => createMiddleware(localStorageService => { return state => { //sync specified state slice with local storage return state.do(state => localStorageService.setItem(key, state[key])); } }, [LocalStorageService]); <file_sep>/src/app/actions.ts /* I prefer to keep all action constants in one file, this provides a one stop reference for all relevant user interaction within your application. It also allows those new to project to see everything your app 'does' in a quick glance. */ //Person Action Constants export const ADD_PERSON = 'ADD_PERSON'; export const REMOVE_PERSON = 'REMOVE_PERSON'; export const ADD_GUEST = 'ADD_GUEST'; export const REMOVE_GUEST = 'REMOVE_GUEST'; export const TOGGLE_ATTENDING = 'TOGGLE_ATTENDING'; //Party Filter Constants export const SHOW_ATTENDING = 'SHOW_ATTENDING'; export const SHOW_ALL = 'SHOW_ALL'; export const SHOW_WITH_GUESTS = 'SHOW_GUESTS'; <file_sep>/src/app/reset.ts export const RESET_STATE = 'RESET_STATE'; const INIT = '__NOT_A_REAL_ACTION__'; export const reset = reducer => { let initialState = reducer(undefined, {type: INIT}) return function (state, action) { //if reset action is fired, return initial state if(action.type === RESET_STATE){ return initialState; } //calculate next state based on action let nextState = reducer(state, action); //return nextState as normal when not reset action return nextState; } } <file_sep>/src/app/rehydrate.ts import {provide, Provider} from '@angular/core'; import {INITIAL_STATE} from '@ngrx/store'; export const rehydrateState = key => { //override initial state token for use in store return provide(INITIAL_STATE, { useValue: { [key]: JSON.parse(localStorage.getItem(key))} }); }; <file_sep>/src/app/main.ts import {Component, ChangeDetectionStrategy} from '@angular/core'; import 'rxjs/Rx' import {Observable} from 'rxjs/Observable'; import {AsyncPipe} from '@angular/common'; import {bootstrap} from '@angular/platform-browser-dynamic'; import {Store, provideStore, usePreMiddleware, usePostMiddleware} from '@ngrx/store'; import {id} from './id'; import {people} from './people'; import {partyFilter} from './party-filter'; import {partyModel, percentAttending} from './selectors'; import {actionLogger, stateLogger, localStorageMiddleware} from './middleware'; import {LocalStorageService} from './service'; import {rehydrateState} from './rehydrate'; import {reset, RESET_STATE} from './reset'; import { ADD_PERSON, REMOVE_PERSON, ADD_GUEST, REMOVE_GUEST, TOGGLE_ATTENDING } from './actions'; import {PersonList} from './person-list'; import {PersonInput} from './person-input'; import {FilterSelect} from './filter-select'; import {PartyStats} from './party-stats'; @Component({ selector: 'app', template: ` <h3>@ngrx/store Party Planner</h3> <button (click)="resetParty()" class="margin-bottom-10"> Reset Party </button> <div class="margin-bottom-10"> Percent Attendance: {{percentAttendance | async}}% </div> <party-stats [invited]="(model | async)?.total" [attending]="(model | async)?.attending" [guests]="(model | async)?.guests" > </party-stats> <filter-select (updateFilter)="updateFilter($event)" > </filter-select> <person-input (addPerson)="addPerson($event)" > </person-input> <person-list [people]="(model | async)?.people" (addGuest)="addGuest($event)" (removeGuest)="removeGuest($event)" (removePerson)="removePerson($event)" (toggleAttending)="toggleAttending($event)" > </person-list> `, directives: [PersonList, PersonInput, FilterSelect, PartyStats], pipes: [AsyncPipe], changeDetection: ChangeDetectionStrategy.OnPush, }) export class App { public model; public percentAttendance; constructor( private _store: Store<any> ){ /* Every time people or partyFilter emits, pass the latest value from each into supplied function. We can then calculate and output statistics. */ this.model = Observable.combineLatest( _store.select('people'), _store.select('partyFilter') ) //extracting party model to selector .let(partyModel()); //for demonstration on combining selectors this.percentAttendance = _store.let(percentAttending()); } //all state-changing actions get dispatched to and handled by reducers addPerson(name){ this._store.dispatch({type: ADD_PERSON, payload: {id: id(), name}}) } addGuest(id){ this._store.dispatch({type: ADD_GUEST, payload: id}); } removeGuest(id){ this._store.dispatch({type: REMOVE_GUEST, payload: id}); } removePerson(id){ this._store.dispatch({type: REMOVE_PERSON, payload: id}); } toggleAttending(id){ this._store.dispatch({type: TOGGLE_ATTENDING, payload: id}) } updateFilter(filter){ this._store.dispatch({type: filter}) } resetParty(){ this._store.dispatch({type: RESET_STATE}) } //ngOnDestroy to unsubscribe is no longer necessary } bootstrap(App, [ LocalStorageService, //wrap people in reset meta-reducer provideStore({people: reset(people), partyFilter}), usePreMiddleware(actionLogger), usePostMiddleware(stateLogger, localStorageMiddleware('people')), //to rehydrate state //rehydrateState('people') ]); <file_sep>/src/app/filter-select.ts import {Component, Output, EventEmitter} from "@angular/core"; import { SHOW_ATTENDING, SHOW_ALL, SHOW_WITH_GUESTS } from './actions'; @Component({ selector: 'filter-select', template: ` <div class="margin-bottom-10"> <select #selectList (change)="updateFilter.emit(selectList.value)"> <option *ngFor="#filter of filters" value="{{filter.action}}"> {{filter.friendly}} </option> </select> </div> ` }) export class FilterSelect { public filters = [ {friendly: "All", action: SHOW_ALL}, {friendly: "Attending", action: SHOW_ATTENDING}, {friendly: "Attending w/ Guests", action: SHOW_WITH_GUESTS} ]; @Output() updateFilter : EventEmitter<string> = new EventEmitter<string>(); }
bdbd4075c49f4223d44eb7c792e860b8a1b671eb
[ "TypeScript" ]
9
TypeScript
Arahir/ngrx-party
84ac9b46a80263da95e67398067b28a235fdaf59
ffe9a4552effbc185144592c35dc3b836a5eab5a
refs/heads/master
<repo_name>vieee/react_chat_app<file_sep>/src/firebase.js import firebase from "firebase/app"; import "firebase/auth"; import "firebase/database"; import "firebase/storage"; var firebaseConfig = { apiKey: "<KEY>", authDomain: "react-slack-clone-e6b28.firebaseapp.com", databaseURL: "https://react-slack-clone-e6b28.firebaseio.com", projectId: "react-slack-clone-e6b28", storageBucket: "react-slack-clone-e6b28.appspot.com", messagingSenderId: "921343697113", appId: "1:921343697113:web:9c0b06f3a2e6c3c5df5ec8", measurementId: "G-N684Y9HDVP" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); export default firebase;
3ba609fe07e942ba98e3f2d6e7007e92aa71a5ab
[ "JavaScript" ]
1
JavaScript
vieee/react_chat_app
1ac1f2c620d8801f1e66137495ccbe11dbf6e789
aac3a94d5da7f4b0a114115028b348c1616d534b
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using Utils.Extensions; namespace Application.Sorts { public static class Bubble { public static IList<int> BubbleSort(this IList<int> array) { return array.BubbleSort((a, b) => a > b); } public static IList<T> BubbleSort<T>(this IList<T> array, Func<T, T, bool> comparingFunction) { bool swap = true; while (swap) { swap = false; for (int i = 0; i < array.Count - 1; i++) { if (comparingFunction(array[i], array[i + 1])) { swap = true; array.Swap(i, i + 1); } } } return array; } } } <file_sep>using System; using System.Collections.Generic; using Utils.Extensions; namespace Application.Sorts { public static class Quick { public static IList<T> QuickSort<T>(this IList<T> array, Func<T, T, bool> comparingFunction) { return Sort(array, 0, array.Count - 1, comparingFunction); } public static IList<int> QuickSort(this IList<int> array) { return array.QuickSort<int>((a, b) => (a < b)); } private static IList<T> Sort<T>(IList<T> array, int inicio, int fim, Func<T, T, bool> comparingFunction) { if (inicio < fim) { int pivot = ChoosePivot(array, inicio, fim); array.Swap(pivot, fim); int x = Partition(array, inicio, fim, comparingFunction); Sort(array, inicio, x - 1, comparingFunction); Sort(array, x + 1, fim, comparingFunction); } return array; } public static int Partition<T>(IList<T> array, int inicio, int fim, Func<T, T, bool> comparingFunction) { T pivot = array[fim]; int i = inicio; for (int j = inicio; j < fim - 1; j++) { if (comparingFunction(array[j], pivot)) { array.Swap(i, j); i++; } } array.Swap(i, fim); return i; } private static int ChoosePivot<T>(IList<T> array, int inicio, int fim) => fim; } } <file_sep>using System; using System.Collections.Generic; namespace Application.Sorts { public static class Insertion { public static IList<int> InsertionSort(this IList<int> array) { return array.InsertionSort((a, b) => a < b); } public static IList<T> InsertionSort<T>(this IList<T> array, Func<T, T, bool> comparingFunction) { for (int i = 1; i < array.Count; i++) { T current = array[i]; int j = i - 1; while (j >= 0 && comparingFunction(current, array[j])) { array[j + 1] = array[j]; j--; } array[j + 1] = current; } return array; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Utils.Extensions { public static class Printer { public static IList<T> Print<T>(this IList<T> array) { for (int i = 0; i < array.Count; i++) if (i != array.Count - 1) Console.Write($"{array[i]}, "); else Console.WriteLine(array[i]); return array; } } } <file_sep>using System; using System.Collections.Generic; namespace Utils.Extensions { public static class ArrayUtils { public static IList<T> Swap<T>(this IList<T> array, int firstIndex, int SecondIndex) { T aux = array[firstIndex]; array[firstIndex] = array[SecondIndex]; array[SecondIndex] = aux; return array; } public static IList<int> Randomize(this IList<int> array) { Random rnd = new Random(); for (int i = 0; i < array.Count; i++) array[i] = rnd.Next(0, 100); return array; } public static IList<double> Randomize(this IList<double> array) { Random rnd = new Random(); for (int i = 0; i < array.Count; i++) array[i] = rnd.NextDouble() * 100; return array; } } } <file_sep>using Application.Sorts; using Utils.Extensions; using System; using System.Collections.Generic; namespace Application { class Program { /* BubbleSort - OK InsertionSort - OK SelectionSort MergeSort - OK QuickSort PartitionSort HeapSort */ static void Main(string[] args) { //IList<int> array = new int[] { 3, 9, 1, 2, 7, 4, 8, 5, 0, 6 }; var array = new int[10]; array.Randomize() .Print() .BubbleSort() .Print(); Console.ReadLine(); } } } ;<file_sep> namespace Application.Heap { public interface IHeap<T> { void ConstroiHeap(T[] array); void RemoveDaHeap(); void InserenaHeap(T valor, int prioridade); void AlteraHeap(int indice, int novaPrioridade); } } <file_sep>namespace Application.Heap { public class Heap : IHeap<int> { public HeapItem<int>[] H { get; set; } public void ConstroiHeap(int[] array) { H = array.ToHeap(); for (int i = (array.Length / 2) - 1; i >= 0; i--) CorrigeHeapDescendo(i); } public void RemoveDaHeap() { if (H.Length > 0) { H[0] = H[H.Length - 1]; CorrigeHeapDescendo(0); } HeapItem<int>[] novaHeap = new HeapItem<int>[H.Length - 1]; for (int i = 0; i < novaHeap.Length; i++) novaHeap[i] = H[i]; H = novaHeap; } public void InserenaHeap(int valor, int prioridade) { HeapItem<int>[] novaHeap = new HeapItem<int>[H.Length + 1]; for (int i = 0; i < H.Length; i++) novaHeap[i] = H[i]; novaHeap[H.Length] = new HeapItem<int>() { Value = valor, Prioridade = prioridade }; H = novaHeap; CorrigeHeapSubindo(novaHeap.Length - 1); } public void AlteraHeap(int i, int novaPrioridade) { int aux = H[i].Prioridade; H[i].Prioridade = novaPrioridade; if (aux < novaPrioridade) CorrigeHeapSubindo(i); else if (aux > novaPrioridade) CorrigeHeapDescendo(i); } public void CorrigeHeapDescendo(int i) { int maior = i, esquerda = 2 * i + 1, direita = 2 * i + 2, n = H.Length; if (esquerda < n && H[esquerda].Prioridade > H[maior].Prioridade) maior = esquerda; if (direita < n && H[direita].Prioridade > H[maior].Prioridade) maior = direita; if (maior != i) { var troca = H[i]; H[i] = H[maior]; H[maior] = troca; CorrigeHeapDescendo(maior); } } private void CorrigeHeapSubindo(int i) { int pai = i / 2; if (i >= 1 && H[i].Prioridade > H[pai].Prioridade) { var aux = H[i]; H[i] = H[pai]; H[pai] = aux; CorrigeHeapSubindo(pai); } } } public static class HeapMapper { public static int[] ToArray(this HeapItem<int>[] H) { int[] result = new int[H.Length]; for (int i = 0; i < H.Length; i++) result[i] = H[i].Value; return result; } public static HeapItem<int>[] ToHeap(this int[] array) { HeapItem<int>[] heap = new HeapItem<int>[array.Length]; for (int i = 0; i < array.Length; i++) { heap[i] = new HeapItem<int>(); heap[i].Prioridade = array[i]; heap[i].Value = array[i]; } return heap; } } } <file_sep>namespace Application.Heap { public class HeapItem<T> { public int Prioridade { get; set; } public T Value { get; set; } } } <file_sep>using System; using System.Collections.Generic; namespace Application.Sorts { public static class Merge { public static IList<T> MergeSort<T>(this IList<T> array, Func<T, T, bool> comparingFunction) { return SortAndMerge<T>(array, 0, array.Count - 1, comparingFunction); } public static IList<int> MergeSort(this IList<int> array) { return array.MergeSort<int>((a, b) => a < b); } private static IList<T> SortAndMerge<T>(IList<T> array, int start, int end, Func<T, T, bool> comparingFunction) { if (start < end) { int middle = start + (end - start) / 2; SortAndMerge<T>(array, start, middle, comparingFunction); SortAndMerge<T>(array, middle + 1, end, comparingFunction); MergeArray<T>(array, start, middle, end, comparingFunction); } return array; } private static void MergeArray<T>(IList<T> array, int start, int middle, int end, Func<T, T, bool> comparingFunction) { int sizeL = middle - start + 1; int sizeR = end - middle; T[] L = new T[sizeL]; T[] R = new T[sizeR]; for (int h = 0; h < sizeL; h++) L[h] = array[start + h]; for (int h = 0; h < sizeR; h++) R[h] = array[middle + h + 1]; int i = 0, j = 0, k = start; while (i < sizeL && j < sizeR) { if (comparingFunction(L[i], R[j])) { array[k] = L[i]; i++; } else { array[k] = R[j]; j++; } k++; } while (i < sizeL) { array[k] = L[i]; i++; k++; } while (j < sizeR) { array[k] = R[j]; j++; k++; } } } }
2c287eb71ab2b38aab5caf98e98ac2b4c603feb3
[ "C#" ]
10
C#
dreis0/analise-de-algoritmos
3ce5e9f7c06a0d14481c61cf2e4b16c425fd1367
f358c3757ffd2eb172a6adf5482fe78c01c393fd
refs/heads/master
<file_sep>// AGR2280 2012 - 2015 // Created by Vonsnake using UnityEngine; using System.Collections; /// <summary> /// Stores and updates in-game settings. /// </summary> public class GameSettings : MonoBehaviour { // GRAPHICS | Lighting public bool pixelLightCount; public bool useRealtimeReflections; // GRAPHICS | Shadows public bool bShadowsEnabled; // GRAPHICS | PP public bool bBloomEnabled; public bool bBoostEffectsEnabled; // AUDIO public float volumeMaster; public float volumeShips; public float volumeEnvironment; public float volumeAnnouncer; public float volumeMusic; public bool bMusicEffectsEnabled; public bool bMusicEnabled; public bool bAnnouncerEnabled; // Profile public string profileName; public string profileTag; /// <summary> /// Save the current game settings to the registry /// </summary> public void WritePlayerPreferences() { } /// <summary> /// Read the current game settings from the registry /// </summary> public void ReadPlayerReferences() { } /// <summary> /// Update the player name /// </summary> public void UpdateProfileName(string name) { profileName = name; PlayerPrefs.SetString("Pname", profileName); } } <file_sep>using UnityEngine; using UnityEngine.UI; using System.Collections; public class HighlightTextSwap : MonoBehaviour { public GameObject textObject; public string selectedText; public string unselectedText; void Start() { if (GetComponent<TextSwapManager>()) { GetComponent<TextSwapManager>().functionClass = this; } else { Debug.LogError(gameObject.name + ": No Text Swap Manager found! Please add one or remove this component."); Destroy(this); } textObject.GetComponent<Text>().text = unselectedText; } public void Select() { textObject.GetComponent<Text>().text = selectedText; } public void Unselect() { textObject.GetComponent<Text>().text = unselectedText; } } <file_sep>// AGR2280 2012 - 2015 // Created by Vonsnake using UnityEngine; using UnityEditor; using System.Collections; //[CustomEditor(typeof(ShipSettings))] public class ShipInspector : Editor { private bool bEngineExpanded; private bool bEngineDClassExpanded; private bool bEngineCClassExpanded; private bool bEngineBClassExpanded; private bool bEngineAClassExpanded; private bool bEngineAPClassExpanded; private bool bEngineAPPClassExpanded; private bool bTurningExpanded; private bool bAirbrakesExpanded; private bool bAntiGravityExpanded; private bool bAntiGravityDClassExpanded; private bool bAntiGravityCClassExpanded; private bool bAntiGravityBClassExpanded; private bool bAntiGravityAClassExpanded; private bool bAntiGravityAPClassExpanded; private bool bAntiGravityAPPClassExpanded; private bool bCameraExpanded; private bool bCloseCamExpanded; private bool bFarCamExpanded; private bool bInternalCamExpanded; private bool bBackwardCamExpanded; private bool bBonnetCamExpanded; private bool bMiscExpanded; private bool bFEExpanded; public override void OnInspectorGUI() { // Set class target ShipSettings classTarget = (ShipSettings)target; // Get current editor GUI settings (for resetting after everything below) int origFoldoutFontSize = EditorStyles.foldout.fontSize; FontStyle origFoldoutFontStyle = EditorStyles.foldout.fontStyle; #region EngineFoldout // Engine EditorStyles.foldout.fontSize = 16; EditorStyles.foldout.fontStyle = FontStyle.Italic; bEngineExpanded = EditorGUILayout.Foldout(bEngineExpanded, "Engine Settings"); if (bEngineExpanded) { // Labels GUIContent AccelCap = new GUIContent("Acceleration Cap", "The cap value for how quickly the ship reaches the thrust cap."); GUIContent ThrustCap = new GUIContent("Thrust Cap", "The top force that can be applied to the ship."); GUIContent Gain = new GUIContent("Engine Gain", "How quickly the acceleration reaches it's cap."); GUIContent Falloff = new GUIContent("Engine Falloff", "How quickly the acceleration and thrust decrease."); GUIContent Turbo = new GUIContent("Engine Turbo", "How powerful the Turbo pickup is."); // Font Styles EditorStyles.foldout.fontSize = 12; EditorStyles.foldout.fontStyle = FontStyle.Bold; EditorGUILayout.Separator(); // Others classTarget.engineGain = EditorGUILayout.FloatField(Gain, classTarget.engineGain, GUILayout.ExpandWidth(false)); classTarget.engineFalloff = EditorGUILayout.FloatField(Falloff, classTarget.engineFalloff, GUILayout.ExpandWidth(false)); classTarget.engineTurbo = EditorGUILayout.FloatField(Turbo, classTarget.engineTurbo, GUILayout.ExpandWidth(false)); EditorGUILayout.Separator(); // D Class bEngineDClassExpanded = EditorGUILayout.Foldout(bEngineDClassExpanded, "D Class"); if (bEngineDClassExpanded) { classTarget.engineAccelCapD = EditorGUILayout.FloatField(AccelCap, classTarget.engineAccelCapD, GUILayout.ExpandWidth(false)); classTarget.engineThrustCapD = EditorGUILayout.FloatField(ThrustCap, classTarget.engineThrustCapD, GUILayout.ExpandWidth(false)); } // C Class bEngineCClassExpanded = EditorGUILayout.Foldout(bEngineCClassExpanded, "C Class"); if (bEngineCClassExpanded) { classTarget.engineAccelCapC = EditorGUILayout.FloatField(AccelCap, classTarget.engineAccelCapC, GUILayout.ExpandWidth(false)); classTarget.engineThrustCapC = EditorGUILayout.FloatField(ThrustCap, classTarget.engineThrustCapC, GUILayout.ExpandWidth(false)); } // B Class bEngineBClassExpanded = EditorGUILayout.Foldout(bEngineBClassExpanded, "B Class"); if (bEngineBClassExpanded) { classTarget.engineAccelCapB = EditorGUILayout.FloatField(AccelCap, classTarget.engineAccelCapB, GUILayout.ExpandWidth(false)); classTarget.engineThrustCapB = EditorGUILayout.FloatField(ThrustCap, classTarget.engineThrustCapB, GUILayout.ExpandWidth(false)); } // A Class bEngineAClassExpanded = EditorGUILayout.Foldout(bEngineAClassExpanded, "A Class"); if (bEngineAClassExpanded) { classTarget.engineAccelCapA = EditorGUILayout.FloatField(AccelCap, classTarget.engineAccelCapA, GUILayout.ExpandWidth(false)); classTarget.engineThrustCapA = EditorGUILayout.FloatField(ThrustCap, classTarget.engineThrustCapA, GUILayout.ExpandWidth(false)); } // A+ Class bEngineAPClassExpanded = EditorGUILayout.Foldout(bEngineAPClassExpanded, "A+ Class"); if (bEngineAPClassExpanded) { classTarget.engineAccelCapAP = EditorGUILayout.FloatField(AccelCap, classTarget.engineAccelCapAP, GUILayout.ExpandWidth(false)); classTarget.engineThrustCapAP = EditorGUILayout.FloatField(ThrustCap, classTarget.engineThrustCapAP, GUILayout.ExpandWidth(false)); } // A++ Class bEngineAPPClassExpanded = EditorGUILayout.Foldout(bEngineAPPClassExpanded, "A++ Class"); if (bEngineAPPClassExpanded) { classTarget.engineAccelCapAPP = EditorGUILayout.FloatField(AccelCap, classTarget.engineAccelCapAPP, GUILayout.ExpandWidth(false)); classTarget.engineThrustCapAPP = EditorGUILayout.FloatField(ThrustCap, classTarget.engineThrustCapAPP, GUILayout.ExpandWidth(false)); } } EditorGUILayout.Separator(); #endregion #region TurningFoldout // Turning EditorStyles.foldout.fontSize = 16; EditorStyles.foldout.fontStyle = FontStyle.Italic; bTurningExpanded = EditorGUILayout.Foldout(bTurningExpanded, "Turning Settings"); if (bTurningExpanded) { // Labels GUIContent Amount = new GUIContent("Turning Amount", "How fast the ship can turn."); GUIContent Gain = new GUIContent("Turning Gain", "How quickly the ship starts rotating."); GUIContent Falloff = new GUIContent("Turning Falloff", "How quickly the ship stops rotating."); EditorGUILayout.Separator(); // Settings classTarget.turnAmount = EditorGUILayout.FloatField(Amount, classTarget.turnAmount, GUILayout.ExpandWidth(false)); classTarget.turnGain = EditorGUILayout.FloatField(Gain, classTarget.turnGain, GUILayout.ExpandWidth(false)); classTarget.turnFalloff = EditorGUILayout.FloatField(Falloff, classTarget.turnFalloff, GUILayout.ExpandWidth(false)); } EditorGUILayout.Separator(); #endregion #region AirbrakesFoldout // Airbrakes EditorStyles.foldout.fontSize = 16; EditorStyles.foldout.fontStyle = FontStyle.Italic; bAirbrakesExpanded = EditorGUILayout.Foldout(bAirbrakesExpanded, "Airbrakes Settings"); if (bAirbrakesExpanded) { // Labels GUIContent Amount = new GUIContent("Airbrakes Amount", "How much the airbrakes cause the ship to bank over."); GUIContent Drag = new GUIContent("Airbrakes Drag", "How much air resistance the airbrakes cause."); GUIContent Gain = new GUIContent("Airbrakes Gain", "How quickly the airbrakes start having an effect on the ship."); GUIContent Falloff = new GUIContent("Airbrakes Falloff", "How quickly the airbrakes stop having an effect on the ship."); GUIContent Turn = new GUIContent("Airbrakes Turn", "How sensitive the airbrakes are."); GUIContent Slidegrip = new GUIContent("Airbrakes Slidegrip", "How much the airbrakes grip the ship to the track."); GUIContent Sideshift = new GUIContent("Airbrakes Sideshift", "How strong sideshifting is."); GUIContent VisualAmount = new GUIContent("Visual Amount", "The angle that the airbrakes on the ship raise to."); GUIContent UpSpeed = new GUIContent("Visual Up Speed", "How quickly the airbrake models on the ship raise."); GUIContent DownSpeed = new GUIContent("Visual Down Speed", "How quickly the airbrake models on the ship lower."); EditorGUILayout.Separator(); // Settings classTarget.airbrakesAmount = EditorGUILayout.FloatField(Amount, classTarget.airbrakesAmount, GUILayout.ExpandWidth(false)); classTarget.airbrakesDrag = EditorGUILayout.FloatField(Drag, classTarget.airbrakesDrag, GUILayout.ExpandWidth(false)); classTarget.airbrakesGain = EditorGUILayout.FloatField(Gain, classTarget.airbrakesGain, GUILayout.ExpandWidth(false)); classTarget.airbrakesFalloff = EditorGUILayout.FloatField(Falloff, classTarget.airbrakesFalloff, GUILayout.ExpandWidth(false)); classTarget.airbrakesTurn = EditorGUILayout.FloatField(Turn, classTarget.airbrakesTurn, GUILayout.ExpandWidth(false)); classTarget.airbrakesSlidegrip = EditorGUILayout.FloatField(Slidegrip, classTarget.airbrakesSlidegrip, GUILayout.ExpandWidth(false)); classTarget.airbrakesSideshift = EditorGUILayout.FloatField(Sideshift, classTarget.airbrakesSideshift, GUILayout.ExpandWidth(false)); EditorGUILayout.Separator(); classTarget.airbrakeAmount = EditorGUILayout.FloatField(VisualAmount, classTarget.airbrakeAmount, GUILayout.ExpandWidth(false)); classTarget.airbrakeUpSpeed = EditorGUILayout.FloatField(UpSpeed, classTarget.airbrakeUpSpeed, GUILayout.ExpandWidth(false)); classTarget.airbrakeDownSpeed = EditorGUILayout.FloatField(DownSpeed, classTarget.airbrakeDownSpeed, GUILayout.ExpandWidth(false)); } EditorGUILayout.Separator(); #endregion #region AntiGravityFoldout // Anti-Gravity Foldout EditorStyles.foldout.fontSize = 16; EditorStyles.foldout.fontStyle = FontStyle.Italic; bAntiGravityExpanded = EditorGUILayout.Foldout(bAntiGravityExpanded, "Anti-Gravity Settings"); if (bAntiGravityExpanded) { // Labels GUIContent Rebound = new GUIContent("Rebound", "A force that keeps the ship grounded better."); GUIContent ReboundLanding = new GUIContent("Landing Rebound", "A damping multiplier to prevent the ship bouncing up high from great falls."); GUIContent ReboundJumpTime = new GUIContent("Rebound Jump Time", "How long the rebound force is active for."); GUIContent AirGrip = new GUIContent("Air Grip", "How much grip the ship has when in flight."); GUIContent TrackGrip = new GUIContent("Ground Grip", "How much grip the ship has when hovering above the track."); // Font Styles EditorStyles.foldout.fontSize = 12; EditorStyles.foldout.fontStyle = FontStyle.Bold; EditorGUILayout.Separator(); // Others classTarget.agRebound = EditorGUILayout.FloatField(Rebound, classTarget.engineGain, GUILayout.ExpandWidth(false)); classTarget.agReboundLanding = EditorGUILayout.FloatField(ReboundLanding, classTarget.engineFalloff, GUILayout.ExpandWidth(false)); classTarget.agReboundJumpTime = EditorGUILayout.FloatField(ReboundJumpTime, classTarget.engineTurbo, GUILayout.ExpandWidth(false)); EditorGUILayout.Separator(); // D Class bAntiGravityDClassExpanded = EditorGUILayout.Foldout(bAntiGravityDClassExpanded, "D Class"); if (bAntiGravityDClassExpanded) { classTarget.agGripAirD = EditorGUILayout.FloatField(AirGrip, classTarget.agGripAirD, GUILayout.ExpandWidth(false)); classTarget.agGripGroundD = EditorGUILayout.FloatField(TrackGrip, classTarget.agGripGroundD, GUILayout.ExpandWidth(false)); } // C Class bAntiGravityCClassExpanded = EditorGUILayout.Foldout(bAntiGravityCClassExpanded, "C Class"); if (bAntiGravityCClassExpanded) { classTarget.agGripAirC = EditorGUILayout.FloatField(AirGrip, classTarget.agGripAirC, GUILayout.ExpandWidth(false)); classTarget.agGripGroundC = EditorGUILayout.FloatField(TrackGrip, classTarget.agGripGroundC, GUILayout.ExpandWidth(false)); } // B Class bAntiGravityBClassExpanded = EditorGUILayout.Foldout(bAntiGravityBClassExpanded, "B Class"); if (bAntiGravityBClassExpanded) { classTarget.agGripAirB = EditorGUILayout.FloatField(AirGrip, classTarget.agGripAirB, GUILayout.ExpandWidth(false)); classTarget.agGripGroundB = EditorGUILayout.FloatField(TrackGrip, classTarget.agGripGroundB, GUILayout.ExpandWidth(false)); } // A Class bAntiGravityAClassExpanded = EditorGUILayout.Foldout(bAntiGravityAClassExpanded, "A Class"); if (bAntiGravityAClassExpanded) { classTarget.agGripAirA = EditorGUILayout.FloatField(AirGrip, classTarget.agGripAirA, GUILayout.ExpandWidth(false)); classTarget.agGripGroundA = EditorGUILayout.FloatField(TrackGrip, classTarget.agGripGroundA, GUILayout.ExpandWidth(false)); } // AP Class bAntiGravityAPClassExpanded = EditorGUILayout.Foldout(bAntiGravityAPClassExpanded, "A+ Class"); if (bAntiGravityAPClassExpanded) { classTarget.agGripAirAP = EditorGUILayout.FloatField(AirGrip, classTarget.agGripAirAP, GUILayout.ExpandWidth(false)); classTarget.agGripGroundAP = EditorGUILayout.FloatField(TrackGrip, classTarget.agGripGroundAP, GUILayout.ExpandWidth(false)); } // D Class bAntiGravityAPPClassExpanded = EditorGUILayout.Foldout(bAntiGravityAPPClassExpanded, "A++ Class"); if (bAntiGravityAPPClassExpanded) { classTarget.agGripAirAPP = EditorGUILayout.FloatField(AirGrip, classTarget.agGripAirAPP, GUILayout.ExpandWidth(false)); classTarget.agGripGroundAPP = EditorGUILayout.FloatField(TrackGrip, classTarget.agGripGroundAPP, GUILayout.ExpandWidth(false)); } } EditorGUILayout.Separator(); #endregion #region Camera // Camera Rollout EditorStyles.foldout.fontSize = 16; EditorStyles.foldout.fontStyle = FontStyle.Italic; bCameraExpanded = EditorGUILayout.Foldout(bCameraExpanded, "Camera Settings"); if (bCameraExpanded) { // Labels GUIContent FoV = new GUIContent("Field of View", "How many degrees the camera can see."); // Font Styles EditorStyles.foldout.fontSize = 12; EditorStyles.foldout.fontStyle = FontStyle.Bold; EditorGUILayout.Separator(); // Close Camera bCloseCamExpanded = EditorGUILayout.Foldout(bCloseCamExpanded, "Close Camera"); if (bCloseCamExpanded) { classTarget.camCloseFoV = EditorGUILayout.FloatField(FoV, classTarget.camCloseFoV, GUILayout.ExpandWidth(false)); GUIContent HorSpring = new GUIContent("Horizontal Spring", "How fast the camera chases the ship on the X axis."); classTarget.camCloseSpringHor = EditorGUILayout.FloatField(HorSpring, classTarget.camCloseSpringHor, GUILayout.ExpandWidth(false)); GUIContent VertSpring = new GUIContent("Vertical Spring", "How fast the camera chases the ship on the Y axis."); classTarget.camCloseSpringVert = EditorGUILayout.FloatField(VertSpring, classTarget.camCloseSpringVert, GUILayout.ExpandWidth(false)); GUIContent LA = new GUIContent("Look At", "The position relative to the ship the camera will look at."); classTarget.camCloseLA = EditorGUILayout.Vector3Field(LA, classTarget.camCloseLA); GUIContent POS = new GUIContent("Position", "The target position behind the ship the camera will chase."); classTarget.camCloseOffset = EditorGUILayout.Vector3Field(POS, classTarget.camCloseOffset); } // Far Camera bFarCamExpanded = EditorGUILayout.Foldout(bFarCamExpanded, "Far Camera"); if (bFarCamExpanded) { classTarget.camFarFoV = EditorGUILayout.FloatField(FoV, classTarget.camFarFoV, GUILayout.ExpandWidth(false)); GUIContent HorSpring = new GUIContent("Horizontal Spring", "How fast the camera chases the ship on the X axis."); classTarget.camFarSpringHor = EditorGUILayout.FloatField(HorSpring, classTarget.camFarSpringHor, GUILayout.ExpandWidth(false)); GUIContent VertSpring = new GUIContent("Vertical Spring", "How fast the camera chases the ship on the Y axis."); classTarget.camFarSpringVert = EditorGUILayout.FloatField(VertSpring, classTarget.camFarSpringVert, GUILayout.ExpandWidth(false)); GUIContent LA = new GUIContent("Look At", "The position relative to the ship the camera will look at."); classTarget.camFarLA = EditorGUILayout.Vector3Field(LA, classTarget.camFarLA); GUIContent POS = new GUIContent("Position", "The target position behind the ship the camera will chase."); classTarget.camFarOffset = EditorGUILayout.Vector3Field(POS, classTarget.camFarOffset); } // Internal Camera bInternalCamExpanded = EditorGUILayout.Foldout(bInternalCamExpanded, "Internal Camera"); if (bInternalCamExpanded) { classTarget.camIntFoV = EditorGUILayout.FloatField(FoV, classTarget.camIntFoV, GUILayout.ExpandWidth(false)); GUIContent POS = new GUIContent("Position", "The position relative to the ship the camera will sit."); classTarget.camIntOffset= EditorGUILayout.Vector3Field(POS, classTarget.camIntOffset); } // Backwards Camera bBackwardCamExpanded = EditorGUILayout.Foldout(bBackwardCamExpanded, "Backwards Camera"); if (bBackwardCamExpanded) { classTarget.camBackFoV = EditorGUILayout.FloatField(FoV, classTarget.camBackFoV, GUILayout.ExpandWidth(false)); GUIContent POS = new GUIContent("Position", "The position relative to the ship the camera will sit."); classTarget.camBackOffset = EditorGUILayout.Vector3Field(POS, classTarget.camBackOffset); } // Bonnet Camera bBonnetCamExpanded = EditorGUILayout.Foldout(bBonnetCamExpanded, "Bonnet Camera"); if (bBonnetCamExpanded) { classTarget.camBonnetFoV = EditorGUILayout.FloatField(FoV, classTarget.camBonnetFoV, GUILayout.ExpandWidth(false)); GUIContent POS = new GUIContent("Position", "The position relative to the ship the camera will sit."); classTarget.camBonnetOffset = EditorGUILayout.Vector3Field(POS, classTarget.camBonnetOffset); } } EditorGUILayout.Separator(); #endregion #region Misc // Misc Rollout EditorStyles.foldout.fontSize = 16; EditorStyles.foldout.fontStyle = FontStyle.Italic; bMiscExpanded = EditorGUILayout.Foldout(bMiscExpanded, "Misc Settings"); if (bMiscExpanded) { // Labels GUIContent ColliderSize = new GUIContent("Collider Scale", "The actual physical size of the ship which will be handled by the physics engine."); GUIContent ShieldAmount = new GUIContent("Shield Amount", "How strong the ship's shield generator is (from a range of 0 - 1)."); GUIContent WeightDist = new GUIContent("Weight Distrubution", "Centre of Mass offset to help weight the ship."); GUIContent TiltInternalSpeed = new GUIContent("Internal Tilt Speed", "How fast the internal camera wobbles when the ship looses balance."); GUIContent TiltInternalAmount = new GUIContent("Internal Tilt Amount", "How much the internal camera wobbles when the ship looses balance."); GUIContent TiltShipSpeed = new GUIContent("Ship Tilt Speed", "How fast the ship wobbles when the ship looses balance."); GUIContent TiltShipAmount = new GUIContent("Ship Tilt Amount", "How much the ship wobbles when the ship looses balance."); EditorGUILayout.Separator(); classTarget.physColliderSize = EditorGUILayout.Vector3Field(ColliderSize, classTarget.physColliderSize); classTarget.physShieldAmount = EditorGUILayout.Slider(ShieldAmount, classTarget.physShieldAmount, 0.0f, 1.0f); classTarget.physWeightDist = EditorGUILayout.Slider(WeightDist, classTarget.physWeightDist, -4.0f, 4.0f); EditorGUILayout.Separator(); classTarget.tiltInternalSpeed = EditorGUILayout.FloatField(TiltInternalSpeed, classTarget.tiltInternalSpeed, GUILayout.ExpandWidth(false)); classTarget.tiltInternalAmount = EditorGUILayout.FloatField(TiltInternalAmount, classTarget.tiltInternalAmount, GUILayout.ExpandWidth(false)); classTarget.tiltShipSpeed = EditorGUILayout.FloatField(TiltShipSpeed, classTarget.tiltShipSpeed, GUILayout.ExpandWidth(false)); classTarget.tiltShipAmount = EditorGUILayout.FloatField(TiltShipAmount, classTarget.tiltShipAmount, GUILayout.ExpandWidth(false)); EditorGUILayout.Separator(); } EditorGUILayout.Separator(); #endregion #region FrontEnd // Frontend Rollout EditorStyles.foldout.fontSize = 16; EditorStyles.foldout.fontStyle = FontStyle.Italic; bFEExpanded = EditorGUILayout.Foldout(bFEExpanded, "Front-End Settings"); if (bFEExpanded) { // Labels GUIContent Speed = new GUIContent("Speed", "The value (0 - 10) that is shown on the menu."); GUIContent Thrust = new GUIContent("Thrust", "The value (0 - 10) that is shown on the menu."); GUIContent Handling = new GUIContent("Handling", "The value (0 - 10) that is shown on the menu."); GUIContent Shield = new GUIContent("Shield", "The value (0 - 10) that is shown on the menu."); EditorGUILayout.Separator(); classTarget.feSpeed = EditorGUILayout.IntSlider(Speed, classTarget.feSpeed, 0, 10); classTarget.feThrust = EditorGUILayout.IntSlider(Thrust, classTarget.feThrust, 0, 10); classTarget.feHandling = EditorGUILayout.IntSlider(Handling, classTarget.feHandling, 0, 10); classTarget.feShield = EditorGUILayout.IntSlider(Shield, classTarget.feShield, 0, 10); } EditorGUILayout.Separator(); #endregion // Information EditorGUILayout.LabelField("This custom inspector makes it easier to edit the ship settings."); EditorGUILayout.LabelField("Attach this script to your ship model prefab!"); // Reset editor styles EditorStyles.foldout.fontSize = origFoldoutFontSize; EditorStyles.foldout.fontStyle = origFoldoutFontStyle; } } <file_sep>// AGR2280 2012 - 2015 // Created by Vonsnake using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// Simulates the ship physics. /// </summary> public class ShipSimulator : MonoBehaviour { // Debugging public bool bDebugVisualizeHovering; // Ship References private Rigidbody shipBody; private PhysicMaterial shipPhysicsMaterial; private GameObject shipAxis; private GameObject shipCamera; private ShipController controller; public ShipSettings settings; public GlobalSettings.InputController inputControl; public GlobalSettings.SpeedClasses eventSpeedClass; public RaceManager manager; private FFManager vibrationManager; // Booleans public bool bShipHasCameraControl; public bool bShipIsGrounded; public bool bShipIsOnMagStrip; public bool bShipIsBraking; public bool bShipIsBoosting; public bool bShipBoostingOverride; private bool bIsShipSS; private bool bSSCoolingDown; private bool bCanShipBR; private bool bHasShipBR; private bool bBRSuccess; private bool bShipHitPad; private bool bIsShipColliding; public bool bLookingBehind; private bool turnGainAntiBanding; private bool airbrakeGainAntiBanding; private bool bankingGainAntiBanding; // Vectors private Vector3 shipGravityForce; private Vector3 speedPadDirection; private Vector3 sideShiftDirection; private Vector3 shipHoverAnimOffset; private Vector3 shipCameraBoostOffset; // Floats public float shipIntegrity; public float shipTurningAmount; private float shipTurningGain; private float shipTurningFalloff; private float shipTurningPrevious; public float shipAirbrakeAmount; private float shipAirbrakeGain; private float shipAirbrakeFalloff; private float shipAirbrakePrevious; private float shipAirbrakeResistance; private float shipAirDrag; private float shipPitchAmount; private float shipGripAmount; private float shipCameraSpringTight; private float shipCameraStablizerTight; private float shipCameraSpringFree; private float shipCameraStablizerFree; private float shipCameraSpring; private float shipCameraTurnOffset; private float shipCameraAccelerationLength; private float shipCameraChaseLag; private float shipCameraOffsetLag; private float shipCameraHeightLag; private float shipCameraBoostChase; private float shipCameraPitchModify; private float shipCameraFoV; private float shipCameraBoostFoV; private float shipBankingAmount; private float shipBankingVelocity; private float shopBankingGain; private float shipBankingFalloff; private float shipBankingAirbrakeAmount; private float shipEngineThrust; private float shipEngineAcceleration; private float shipEngineGain; private float shipEngineFalloff; private float shipBrakesAmount; private float shipBrakesGain; private float shipBrakesFalloff; private float shipReboundJump; private float shipReboundLand; private float shipBoostTimer; private float shipSideshiftCooler; private float shipSideshiftCountdown; private float shipHoverAnimTimer; private float shipHoverAnimSpeed = 1.0f; private float shipHoverAnimAmount = 0.2f; private float shipBRProgress; private float shipBRActual; private float shipBRTimer; private float shipBRLastValue; private float shipBRBoostTimer; private float shipCollisionFriction; // Ints public int shipCurrentCamra; private int shipBRState; void Start() { SetupShip(); } void Update() { } void FixedUpdate() { Gravity(); Handling(); Acceleration(); Drag(); FixedUpdateCamera(); ShipAxisAnimations(); } /// <summary> /// Handles the gravity and hovering for the ship. /// </summary> public void Gravity() { // Reset gravity/magstrip bShipIsGrounded = false; bShipIsOnMagStrip = false; // Increase the rideheight slightly (keeps the ship at the actual wanted height) float rideHeight = GlobalSettings.shipRideHeight * 1.2f; // Pitching if (controller.inputPitch != 0) { shipPitchAmount = Mathf.Lerp(shipPitchAmount, controller.inputPitch * GlobalSettings.shipPitchGroundAmount, Time.deltaTime * GlobalSettings.shipPitchDamping); } else { shipPitchAmount = Mathf.Lerp(shipPitchAmount, 0.0f, Time.deltaTime * GlobalSettings.shipPitchDamping); } shipBody.AddTorque(transform.right * (shipPitchAmount * 10)); // Get the current class and set the gravity multipliers float gravityMul = 0; float trackGrav = 0; float flightGrav = 0; switch(eventSpeedClass) { case GlobalSettings.SpeedClasses.D: // Gravity Multiplier gravityMul = GlobalSettings.airGravityMulD; // Track Gravity trackGrav = GlobalSettings.shipTrackGravityD; // Flight Gravity flightGrav = GlobalSettings.shipFlightGravityD; break; case GlobalSettings.SpeedClasses.C: // Gravity Multiplier gravityMul = GlobalSettings.airGravityMulC; // Track Gravity trackGrav = GlobalSettings.shipTrackGravityC; // Flight Gravity flightGrav = GlobalSettings.shipFlightGravityC; break; case GlobalSettings.SpeedClasses.B: // Gravity Multiplier gravityMul = GlobalSettings.airGravityMulB; // Track Gravity trackGrav = GlobalSettings.shipTrackGravityB; // Flight Gravity flightGrav = GlobalSettings.shipFlightGravityB; break; case GlobalSettings.SpeedClasses.A: // Gravity Multiplier gravityMul = GlobalSettings.airGravityMulA; // Track Gravity trackGrav = GlobalSettings.shipTrackGravityA; // Flight Gravity flightGrav = GlobalSettings.shipFlightGravityA; break; case GlobalSettings.SpeedClasses.AP: // Gravity Multiplier gravityMul = GlobalSettings.airGravityMulAP; // Track Gravity trackGrav = GlobalSettings.shipTrackGravityAP; // Flight Gravity flightGrav = GlobalSettings.shipFlightGravityAP; break; case GlobalSettings.SpeedClasses.APP: // Gravity Multiplier gravityMul = GlobalSettings.airGravityMulAPP; // Track Gravity trackGrav = GlobalSettings.shipTrackGravityAPP; // Flight Gravity flightGrav = GlobalSettings.shipFlightGravityAPP; break; } // Create hover points list List<Vector3> hoverPoints = new List<Vector3>(); // Get a slightly smaller area of the ship size Vector2 hoverArea = new Vector2(settings.physColliderSize.x / 2, settings.physColliderSize.z / 2.05f); // Add hover points hoverPoints.Add(transform.TransformPoint(-hoverArea.x, Mathf.Clamp(shipPitchAmount, 0.0f, 0.5f), hoverArea.y)); // Front Left hoverPoints.Add(transform.TransformPoint(hoverArea.x, Mathf.Clamp(shipPitchAmount, 0.0f, 0.5f), hoverArea.y)); // Front Right hoverPoints.Add(transform.TransformPoint(hoverArea.x, Mathf.Clamp(-shipPitchAmount, 0.0f, 0.7f), -hoverArea.y)); // Back Right hoverPoints.Add(transform.TransformPoint(-hoverArea.x, Mathf.Clamp(-shipPitchAmount, 0.0f, 0.7f), -hoverArea.y)); // Back Left // Run through each hover point and apply hover forces if needed for (int i = 0; i < hoverPoints.Count; i++) { // Bitshift track floor and mag lock layers into a new integer for the ship to only check for those two collision layers int trackFloorMask = 1 << LayerMask.NameToLayer("TrackFloor") | 1 << LayerMask.NameToLayer("Maglock"); // Create raycasthit to store hit data into RaycastHit hoverHit; // Raycast down for track if(Physics.Raycast(hoverPoints[i], -transform.up, out hoverHit, rideHeight, trackFloorMask)) { // Get the distance to the ground float dist = hoverHit.distance; // Normalize the distance into a compression ratio float compressionRatio = ((dist / rideHeight) - 1) * -1; // Get the velocity at the hover point Vector3 hoverVel = shipBody.GetPointVelocity(hoverPoints[i]); // Project the velocity onto the ships up vector Vector3 projForce = Vector3.Project(hoverVel, transform.up); // Check to see if the ship is on a magstrip if (hoverHit.collider.gameObject.layer == LayerMask.NameToLayer("Maglock")) bShipIsOnMagStrip = true; /* Calculate force needed to push ship away from track */ // Set a force multiplier float forceMult = 5; // Calcaulate a ratio to multiply the compression ratio by (drasticly increases the hover force as it gets closer to the track) float forceRatio = ((dist / 2) / (rideHeight / 2) - 1) * -forceMult; // Clamp the ratio forceRatio = Mathf.Clamp(forceRatio, 2.0f, 10.0f); // Create the new force float force = 200.0f * (compressionRatio * forceRatio); /* Calculate damping amount to bring the ship to rest quicker */ // Set a damping multiplier float dampMult = 6.5f; // Calculate a ratio to multiply the compression ratio by float dampRatio = ((dist / 2) / (rideHeight / 2) - 1) * -dampMult; // Clamp the ratio dampRatio = Mathf.Clamp(dampRatio, 1.0f, 5.5f); // Clamp the compression ratio, min being the base damp amount float clampedCR = Mathf.Clamp(compressionRatio, 0.5f, 1.0f); // Get the landing rebound to dampen forces straight after a long fall (stops the ship rebounding high off the track) float reboundDamper = Mathf.Clamp(shipReboundLand * 15, 1.0f, Mathf.Infinity); // Create the new damping force float damping = (1 * (clampedCR * dampRatio) * reboundDamper); // If the ship is over a magstrip then we want the ship to act a bit differently if (bShipIsOnMagStrip) { // Calculate how strong the magstrip is based on the ships current angular velocity and speed float magStrength = Mathf.Abs(transform.InverseTransformDirection(shipBody.angularVelocity).x * Time.deltaTime) * Mathf.Abs(transform.InverseTransformDirection(shipBody.velocity).z * Time.deltaTime); // Multiply the strength as the above calculate will result in a terrible lock strength magStrength *= 1000; // Clamp the strength so it can't be too strong magStrength = Mathf.Clamp(magStrength, 0.0f, (transform.InverseTransformDirection(shipBody.velocity).z * Time.deltaTime) * 3.8f); // Set new force and damping multipliers force = (trackGrav * (5.0f + magStrength)); damping = 2f; // Apply the magstrip lock force shipBody.AddForceAtPosition(-transform.up * (trackGrav * (magStrength * 4.0f)), hoverPoints[i], ForceMode.Acceleration); } // Calculate the suspension force Vector3 suspensionForce = transform.up * compressionRatio * force; // Now apply damping Vector3 dampedForce = suspensionForce - (projForce * damping); // Finally, apply the force shipBody.AddForceAtPosition(dampedForce, hoverPoints[i], ForceMode.Acceleration); // Set the grounded boolean to true bShipIsGrounded = true; // Debug line if (bDebugVisualizeHovering) { Debug.DrawLine(hoverPoints[i], hoverHit.point); } // Force feedback if (dist < rideHeight * 0.6f) { vibrationManager.vibLeftMotor = 0.3f; vibrationManager.vibRightMotor = 0.3f; vibrationManager.timerMotor = 1.1f; } } } /* If the ship is grounded then we also want to have the ship be pulled down by gravity We want to do another raycast for the trackfloor layer only from the centre of the ship then calculate everything from that. Don't worry, we are only casting for one layer over a short distance, this isn't very expensive to do. */ // Create raycasthit to store hit data into RaycastHit centreHit; // Raycast down if (Physics.Raycast(transform.position, -transform.up, out centreHit, rideHeight, 1 << LayerMask.NameToLayer("TrackFloor"))) { // Use a dot product to find out how much we need to rotate the ship to get it to face down Vector3 trackRot = transform.forward - (Vector3.Dot(transform.forward, centreHit.normal) * centreHit.normal); // Use the track rotation to calculate how much we are going to rotate the ship float rotAmount = (trackRot.x * trackRot.z) * (Mathf.Clamp(Mathf.Abs(trackRot.y), 0.0f, 0.1f) * 10); // Increase the rotation amount as the ship speeds up float rotForce = 20 + (transform.InverseTransformDirection(shipBody.velocity).z * Time.deltaTime) * 1.2f; // Apply the rotation transform.Rotate(Vector3.up * (rotAmount * Time.deltaTime) * rotForce); // Apply gravity force shipBody.AddForce(new Vector3(centreHit.normal.x, 0, centreHit.normal.z) * (Mathf.Abs(trackRot.x)) * 22); } /* We also want to check for pads on the track. We'll do exactly the same as above to do this. Also we can recycle the centrehit variable! */ // Bitshift pads into integer int padMask = 1 << LayerMask.NameToLayer("SpeedPad") | 1 << LayerMask.NameToLayer("WeaponPad"); // Raycast down if (Physics.Raycast(transform.position, -transform.up, out centreHit, rideHeight + 2, padMask)) { // If the ship hits a speed pad then apply the appropiate force if (centreHit.collider.gameObject.layer == LayerMask.NameToLayer("SpeedPad")) { // Get the pad's forward direction speedPadDirection = centreHit.collider.gameObject.transform.right * GlobalSettings.speedPadAmount; // Set the ships boost timer shipBoostTimer = GlobalSettings.speedPadTime; // Set boosting to true bShipIsBoosting = true; // If we havn't hit this pad already, play the boost sound if (!bShipHitPad) { bShipHitPad = true; // Get sound to play AudioClip boostSFX = Resources.Load("Audio/Ships/BoostSpeedPad") as AudioClip; // Play the sound PlayOneShot.PlayShot("BoostSFX", 1.0f, 1.0f, 50.0f, 500.0f, transform, transform.position, boostSFX); } } } else { // We are not hitting a pad, set the hitting pad boolean to false bShipHitPad = false; } // If the boost timer is over zero then we want to decrease it and apply any boost the ship has if (shipBoostTimer > 0) { // Decrease timer shipBoostTimer -= Time.deltaTime; // Apply pad boost shipBody.AddForce(speedPadDirection, ForceMode.Acceleration); } else { // Make sure that the pad hit boolean is no longer true bShipHitPad = false; // Override boost if the ship has boost power from a barrel rol if (shipBRBoostTimer > 0) { bShipIsBoosting = true; // Apply the barrel roll boost shipBody.AddForce(transform.forward * settings.engineTurbo, ForceMode.Acceleration); } else { // Otherwise the boosting is set to false bShipIsBoosting = false; } } // Allow the turbo pickup to override the boost if (bShipBoostingOverride) { bShipIsBoosting = true; } // Boosting Force Feedback if (bShipIsBoosting) { vibrationManager.timerMotor = 1.1f; vibrationManager.vibLeftMotor = 0.4f; vibrationManager.vibRightMotor = 0.4f; } /* And finally we want to apply gravity, we want to swap out the gravity between two different variables which allows the ship to feel much lighter on the track, this also makes the hovering feel much better too */ // Check to see if the ship is grounded if (bShipIsGrounded) { // If the ship is on a magstrip then the gravity wants to be heavier if (bShipIsOnMagStrip) { // Set gravity shipGravityForce = -transform.up * (trackGrav * 5); } else { // Set gravity shipGravityForce = -transform.up * trackGrav; } // Set the rebound jump time so the stick force is always maxed when the ship enters flight shipReboundJump = settings.agReboundJumpTime; // Decrease the rebound land shipReboundLand -= Time.deltaTime; } else { // Set the gravity shipGravityForce = Vector3.down * (flightGrav * gravityMul); // Decrease the jump shipReboundJump -= Time.deltaTime; // Apply the stick force if (shipReboundJump > 0) { // Apply the force to keep the ship grounded shipBody.AddForce(Vector3.down * ((10 * GlobalSettings.shipNormalGravity) * settings.agRebound), ForceMode.Acceleration); } // Set rebound to zero if it has gone under zero if (shipReboundLand < 0) shipReboundLand = 0; // Increase the rebound land shipReboundLand += Time.deltaTime; // Clamp the rebound land if (shipReboundLand > settings.agReboundLanding) shipReboundLand = settings.agReboundLanding; // Slowly rotate the ship forward transform.Rotate(Vector3.right * 0.05f); } // And finally, apply the gravity shipBody.AddForce(shipGravityForce, ForceMode.Acceleration); } /// <summary> /// Handles the turning and airbrakes for the ship. /// </summary> public void Handling() { // Anti-gain banding if ((controller.inputSteer > 0 && shipTurningAmount < 0) || (controller.inputSteer < 0 && shipTurningAmount > 0)) { if (!turnGainAntiBanding) { turnGainAntiBanding = true; shipBankingVelocity = 0; shipTurningGain = 0; } } else { turnGainAntiBanding = false; } // Turning if (controller.inputSteer != 0) { // Calculate the turn amount float calculatedTurnAmount = settings.turnAmount * Time.deltaTime * Mathf.PI * 7.7f * 2; // Increase the turning gain shipTurningGain = Mathf.Lerp(shipTurningGain, settings.turnGain * Time.deltaTime, Time.deltaTime * 4); // Set falloff to zero to create a gradual slowdown every time we stop turning shipTurningFalloff = 0; // Increase the turning amount shipTurningAmount = Mathf.Lerp(shipTurningAmount, controller.inputSteer * calculatedTurnAmount ,Time.deltaTime * shipTurningGain); // Set the previous turning to the current turning shipTurningPrevious = Mathf.Abs(shipTurningAmount); // Increase the banking velocity shipBankingVelocity = Mathf.Lerp(shipBankingVelocity, settings.tiltShipSpeed, Time.deltaTime * settings.tiltShipAmount); // Set banking falloff to zero shipBankingFalloff = 0; // Increase the banking amount shipBankingAmount = Mathf.Lerp(shipBankingAmount, controller.inputSteer * 45.0f, Time.deltaTime * (shipBankingVelocity * 1.2f)); } else { // Increase the turning falloff shipTurningFalloff = Mathf.Lerp(shipTurningFalloff, settings.turnFalloff * Time.deltaTime, Time.deltaTime * 5); // Set gain to zzero to create a gradual increase every time we start turning shipTurningGain = 0; shipTurningAmount = Mathf.Lerp(shipTurningAmount, 0.0f, Time.deltaTime * shipTurningFalloff); // Increase banking fallof shipBankingFalloff = Mathf.Lerp(shipBankingFalloff, settings.tiltShipSpeed, Time.deltaTime * settings.tiltShipAmount); // Set banking velocity to zero shipBankingVelocity = 0; // Decrease the banking amount shipBankingAmount = Mathf.Lerp(shipBankingAmount, 0.0f, Time.deltaTime * shipBankingFalloff); } // Apply the rotation on the up vector float calculatedAirbrakeTurn = settings.airbrakesTurn * Time.deltaTime * 2.673f; // Airbrakes // Get the overal airbrake input float airbrakeInput = controller.inputLeftAirbrake + controller.inputRightAirbrake; // Use the ships speed to calculate the sensitivity of the airbrakes float airbrakeAmount = ((transform.InverseTransformDirection(shipBody.velocity).z * Time.deltaTime) * calculatedAirbrakeTurn); if (airbrakeInput != 0) { // Increase airbrake gain shipAirbrakeGain = Mathf.Lerp(shipAirbrakeGain, settings.airbrakesGain * Time.deltaTime, Time.deltaTime * 6); // Set falloff to zero shipAirbrakeFalloff = 0; // Increase airbrake amount shipAirbrakeAmount = Mathf.Lerp(shipAirbrakeAmount, airbrakeInput * airbrakeAmount, Time.deltaTime * shipAirbrakeGain); // Set the previous airbrake amount shipAirbrakePrevious = Mathf.Abs(shipAirbrakeAmount); // Airbrake banking shipBankingAirbrakeAmount = Mathf.Lerp(shipBankingAirbrakeAmount, -airbrakeInput * (settings.airbrakesAmount * 1.5f), Time.deltaTime * settings.tiltShipSpeed); } else { // Increase airbrake falloff shipAirbrakeFalloff = Mathf.Lerp(shipAirbrakeFalloff, settings.airbrakesFalloff * Time.deltaTime, Time.deltaTime * 6); // Set gain to zero shipAirbrakeGain = 0; // If the previous airbake is over a certain threshold then increase how fast the airbrake amount decreases to 'spring' // the ship's airbrake rotation back to zero if (Mathf.Abs(shipAirbrakeAmount) > shipAirbrakePrevious * 0.7f) { // Over the threshold shipAirbrakeAmount = Mathf.Lerp(shipAirbrakeAmount, 0.0f, Time.deltaTime * (shipAirbrakeFalloff)); } else { // Under the threshold shipAirbrakeAmount = Mathf.Lerp(shipAirbrakeAmount, 0.0f, Time.deltaTime * (shipAirbrakeFalloff * 2f)); } // Airbrake banking shipBankingAirbrakeAmount = Mathf.Lerp(shipBankingAirbrakeAmount, 0.0f, Time.deltaTime * settings.tiltShipSpeed); } // Apply the overall rotation to the ship transform.Rotate(Vector3.up * (shipTurningAmount + shipAirbrakeAmount)); // Apply the bank rotation to the ship axis shipAxis.transform.localRotation = Quaternion.Euler(0, 0, -shipBankingAmount + shipBankingAirbrakeAmount); } /// <summary> /// Handles the thruster for the ship. /// </summary> public void Acceleration() { // Create top speed values float topThrust = 0; float topAccel = 0; // Choose the top values depending on the speed class switch(eventSpeedClass) { case GlobalSettings.SpeedClasses.D: topThrust = settings.engineThrustCapD; topAccel = settings.engineAccelCapD; break; case GlobalSettings.SpeedClasses.C: topThrust = settings.engineThrustCapC; topAccel = settings.engineAccelCapC; break; case GlobalSettings.SpeedClasses.B: topThrust = settings.engineThrustCapB; topAccel = settings.engineAccelCapB; break; case GlobalSettings.SpeedClasses.A: topThrust = settings.engineThrustCapA; topAccel = settings.engineAccelCapA; break; case GlobalSettings.SpeedClasses.AP: topThrust = settings.engineThrustCapAP; topAccel = settings.engineAccelCapAP; break; case GlobalSettings.SpeedClasses.APP: topThrust = settings.engineThrustCapAPP; topAccel = settings.engineAccelCapAPP; break; } // Ship thrusting if (controller.btnThruster) { // Increase Gain shipEngineGain = Mathf.Lerp(shipEngineGain, (settings.engineGain * 0.1f) * Time.deltaTime, Time.deltaTime); // Set Falloff to zero shipEngineFalloff = 0; // Increase acceleration shipEngineAcceleration = Mathf.Lerp(shipEngineAcceleration, topAccel, Time.deltaTime * shipEngineGain); // Increase thrust shipEngineThrust = Mathf.Lerp(shipEngineThrust, topThrust, Time.deltaTime * (shipEngineAcceleration * 0.1f)); } else { // Increase Falloff shipEngineFalloff = Mathf.Lerp(shipEngineFalloff, settings.engineFalloff * Time.deltaTime, Time.deltaTime); // Set Gain to zero shipEngineGain = 0; // Decrease acceleration shipEngineAcceleration = Mathf.Lerp(shipEngineAcceleration, 0.0f, Time.deltaTime * shipEngineFalloff); // Decrease thrust shipEngineThrust = Mathf.Lerp(shipEngineThrust, 0.0f, Time.deltaTime * shipEngineFalloff); } // Apply Thrust shipBody.AddRelativeForce(Vector3.forward * shipEngineThrust); // Side Shifting if (bIsShipSS) { shipBody.AddForce(sideShiftDirection * (settings.airbrakesSideshift * 1.5f), ForceMode.Acceleration); } } /// <summary> /// Calculates a custom drag to replace Unity's drag. /// </summary> public void Drag() { float gripAmount = 0; if (bShipIsGrounded) { switch (eventSpeedClass) { case GlobalSettings.SpeedClasses.D: gripAmount = settings.agGripGroundD; break; case GlobalSettings.SpeedClasses.C: gripAmount = settings.agGripGroundC; break; case GlobalSettings.SpeedClasses.B: gripAmount = settings.agGripGroundB; break; case GlobalSettings.SpeedClasses.A: gripAmount = settings.agGripGroundA; break; case GlobalSettings.SpeedClasses.AP: gripAmount = settings.agGripGroundAP; break; case GlobalSettings.SpeedClasses.APP: gripAmount = settings.agGripGroundAPP; break; } } else { switch (eventSpeedClass) { case GlobalSettings.SpeedClasses.D: gripAmount = settings.agGripAirD; break; case GlobalSettings.SpeedClasses.C: gripAmount = settings.agGripAirC; break; case GlobalSettings.SpeedClasses.B: gripAmount = settings.agGripAirB; break; case GlobalSettings.SpeedClasses.A: gripAmount = settings.agGripAirA; break; case GlobalSettings.SpeedClasses.AP: gripAmount = settings.agGripAirAP; break; case GlobalSettings.SpeedClasses.APP: gripAmount = settings.agGripAirAPP; break; } } float forwardVelocity = Mathf.Abs(transform.InverseTransformDirection(shipBody.velocity).z); float slideGrip = gripAmount * Time.deltaTime; if (bShipIsGrounded) { // Get turning input float turningInput = Mathf.Abs(controller.inputSteer); //slideGrip -= turningInput * Mathf.Abs(shipTurningAmount * Time.deltaTime); // Get airbrake input float airbrakeInput = Mathf.Abs(controller.inputLeftAirbrake + controller.inputRightAirbrake); //slideGrip -= airbrakeInput * ((Mathf.Abs(shipAirbrakeAmount) - (settings.airbrakesSlidegrip * Time.deltaTime)) * Time.deltaTime) * settings.airbrakesDrag; float absVelX = Mathf.Abs(transform.InverseTransformDirection(shipBody.velocity).x); slideGrip -= Mathf.Abs((shipTurningAmount / 2) * Time.deltaTime); slideGrip -= ((absVelX * Time.deltaTime) * Time.deltaTime) + ((Mathf.Abs(shipAirbrakeAmount* Time.deltaTime) * settings.airbrakesSlidegrip * Time.deltaTime) * settings.airbrakesDrag); } // Airbrake Resistance if (controller.inputLeftAirbrake != 0 || controller.inputRightAirbrake != 0) { // Get the airbrake input float airbrakeInput = Mathf.Abs(controller.inputLeftAirbrake + controller.inputRightAirbrake); airbrakeInput = Mathf.Clamp(airbrakeInput, 0.0f, 1.0f); // Increase resistance shipAirbrakeResistance = Mathf.Lerp(shipAirbrakeResistance, Mathf.Abs(shipAirbrakeAmount) * airbrakeInput, Time.deltaTime * 0.02f); } else { // Decrease resistance shipAirbrakeResistance = Mathf.Lerp(shipAirbrakeResistance, 0.0f, Time.deltaTime * 4.5f); } // Air resistance if (bShipIsGrounded) { shipAirDrag = Mathf.Lerp(shipAirDrag, 0.0f, Time.deltaTime * 4.5f); } else { shipAirDrag = Mathf.Lerp(shipAirDrag, 0.4f, Time.deltaTime * 0.04f); } // Braking Drag Increase if (controller.inputLeftAirbrake != 0 && controller.inputRightAirbrake != 0) { // Ship is now braking bShipIsBraking = true; // Set falloff to zero shipBrakesFalloff = 0; // Increase gain shipBrakesGain = Mathf.Lerp(shipBrakesGain, Time.deltaTime * GlobalSettings.shipBrakesGain * 0.1f, Time.deltaTime); // Increase brakes amount shipBrakesAmount = Mathf.Lerp(shipBrakesAmount, Time.deltaTime * GlobalSettings.shipBrakesAmount, Time.deltaTime * shipBrakesGain); // Decrease Acceleration and Thrust shipEngineAcceleration = Mathf.Lerp(shipEngineAcceleration, 0.0f, Time.deltaTime * shipBrakesGain); shipEngineThrust = Mathf.Lerp(shipEngineThrust, 0.0f, Time.deltaTime * shipBrakesGain); } else { // Ship is no longer breaking bShipIsBraking = false; // Set gain to zero shipBrakesGain = 0; // Increase falloff shipBrakesFalloff = Mathf.Lerp(shipBrakesFalloff, GlobalSettings.shipBrakesFalloff * 0.1f, Time.deltaTime); // Decrease brakes amount shipBrakesAmount = Mathf.Lerp(shipBrakesAmount, 0.0f, Time.deltaTime * shipBrakesFalloff); } Vector3 LocalVelocity = transform.InverseTransformDirection(shipBody.velocity); // Ship grip LocalVelocity.x *= (1 - slideGrip); // Natural Air drag LocalVelocity.y *= 1 - 0.003f; LocalVelocity.z *= 1 - (0.003f + ((forwardVelocity * Time.deltaTime) * 0.007f)); // Drag Resistance LocalVelocity.z *= 1 - ((shipAirbrakeResistance + shipAirDrag) + shipBrakesAmount); Vector3 WorldVelocity = transform.TransformDirection(LocalVelocity); shipBody.velocity = WorldVelocity; } public void FixedUpdateCamera() { // Set default fail-safe spring values float camHorSpring = 12.0f; float camVertSpring = 12.0f; float camFoV = 60.0f; Vector3 camOffset = Vector3.zero; Vector3 camLA = Vector3.zero; // Check which camera is being used and use the right values switch(shipCurrentCamra) { case 0: camHorSpring = settings.camCloseSpringHor; camVertSpring = settings.camCloseSpringVert; camFoV = settings.camCloseFoV; camOffset = settings.camCloseOffset; camLA = settings.camCloseLA; break; case 1: camHorSpring = settings.camFarSpringHor; camVertSpring = settings.camFarSpringVert; camFoV = settings.camFarFoV; camOffset = settings.camFarOffset; camLA = settings.camFarLA; break; } if (shipCurrentCamra == 0 || shipCurrentCamra == 1) { settings.refMeshContainers.SetActive(true); // Camera acceleration length if (controller.btnThruster) { shipCameraAccelerationLength = Mathf.Lerp(shipCameraAccelerationLength, 2.0f, Time.deltaTime * 6); } else if (bShipIsBraking) { shipCameraAccelerationLength = Mathf.Lerp(shipCameraAccelerationLength, -2.0f, Time.deltaTime * 6); } else { shipCameraAccelerationLength = Mathf.Lerp(shipCameraAccelerationLength, 0.0f, Time.deltaTime * 6); } // Get the cameras position in the ships local space Vector3 camDistance = transform.InverseTransformPoint(shipCamera.transform.position); if (controller.inputLeftAirbrake != 0 || controller.inputRightAirbrake != 0) { float camSensitivity = 0.06f; shipCameraSpring = Mathf.Lerp(shipCameraSpring, camSensitivity, Time.deltaTime * (camHorSpring / 2)); } else { shipCameraSpring = Mathf.Lerp(shipCameraSpring, 0.035f, Time.deltaTime * (camHorSpring / 6)); } // Set the x offset float turnSensitivity = 1.5f; if (shipCurrentCamra == 1) turnSensitivity = 3.5f; shipCameraStablizerFree = Mathf.Lerp(shipCameraStablizerFree, Mathf.Abs(camDistance.x) * 2.5f, Time.deltaTime * (camHorSpring / 2)); shipCameraOffsetLag = Mathf.Lerp ( shipCameraOffsetLag, (-transform.InverseTransformDirection(shipBody.velocity).x * shipCameraSpring) + (shipTurningAmount * turnSensitivity), Time.deltaTime * (camHorSpring + (shipCameraStablizerFree)) ); // Set the y offset float heightHelper = camDistance.y; if (heightHelper > 0) heightHelper = 0; heightHelper = Mathf.Clamp(heightHelper, -1f, 0.0f); if (bShipIsGrounded) { shipCameraHeightLag = Mathf.Lerp ( shipCameraHeightLag, -transform.InverseTransformDirection(shipBody.velocity).y * (0.02f + heightHelper), Time.deltaTime * (camVertSpring - (heightHelper * 10)) ); } else { shipCameraHeightLag = Mathf.Lerp ( shipCameraHeightLag, -transform.InverseTransformDirection(shipBody.velocity).y * 0.05f, Time.deltaTime * camVertSpring ); } // Set the z offset shipCameraChaseLag = Mathf.Lerp ( shipCameraChaseLag, (transform.InverseTransformDirection(shipBody.velocity).z * Time.deltaTime) * 0.25f, Time.deltaTime * 2 ); // Parent the camera to the ship shipCamera.transform.parent = transform; // Boost Distance and FoV if (bShipIsBoosting) { shipCameraBoostChase = Mathf.Lerp(shipCameraBoostChase, 0.2f + ((transform.InverseTransformDirection(shipBody.velocity).z * Time.deltaTime) * 0.1f), Time.deltaTime * 15); shipCameraBoostFoV = 15 + ((transform.InverseTransformDirection(shipBody.velocity).z * Time.deltaTime) * 2); } else { shipCameraBoostChase = Mathf.Lerp(shipCameraBoostChase, 0.0f, Time.deltaTime * 4); shipCameraBoostFoV = Mathf.Lerp(shipCameraBoostFoV, 0.0f, Time.deltaTime * 5); } // Set the local offset Vector3 camLocalOffset = camOffset; camLocalOffset.x = shipCameraOffsetLag; camLocalOffset.y = camOffset.y + (shipCameraHeightLag - (transform.InverseTransformDirection(shipBody.velocity).y * Time.deltaTime)) - (shipPitchAmount * 0.1f); camLocalOffset.z = (camOffset.z - shipCameraChaseLag) + (Mathf.Abs(shipCameraOffsetLag) * 0.15f) + shipCameraBoostChase; // Position the camera shipCamera.transform.localPosition = camLocalOffset; // Get camera lookat position float pitchMult = GlobalSettings.camPitchModDownMult; if (!bShipIsGrounded) { pitchMult = 1f; } float camPitchMod = ((transform.InverseTransformDirection(shipBody.velocity).y * Time.deltaTime * pitchMult)); shipCameraPitchModify = Mathf.Lerp(shipCameraPitchModify, camPitchMod, Time.deltaTime * camVertSpring); Vector3 localLA = transform.TransformPoint(camLA.x, camLA.y + shipCameraPitchModify + (shipPitchAmount * GlobalSettings.camPitchModDownMult), camLA.z + shipCameraAccelerationLength + (shipCameraBoostChase * 10)); Quaternion LookAt = Quaternion.LookRotation(localLA - shipCamera.transform.position, transform.up); shipCamera.transform.rotation = LookAt; /* Camera Effects */ // Set field of view shipCameraFoV = Mathf.Lerp(shipCameraFoV, camFoV + ((transform.InverseTransformDirection(shipBody.velocity).z * Time.deltaTime) * 3) + shipCameraBoostFoV, Time.deltaTime * camVertSpring); if (shipCameraFoV < 60) shipCameraFoV = 60; } else { shipCameraFoV = camFoV; shipCamera.transform.localPosition = settings.camIntOffset; shipCamera.transform.localRotation = Quaternion.Euler(0, 0, -shipBankingAmount); settings.refMeshContainers.SetActive(false); } if (bLookingBehind) { settings.refMeshContainers.SetActive(false); shipCameraFoV = settings.camBackFoV; shipCamera.transform.localPosition = settings.camBackOffset; shipCamera.transform.localRotation = Quaternion.Euler(0, 180, shipBankingAmount); } // Apply field of view shipCamera.GetComponent<Camera>().fieldOfView = shipCameraFoV; } public void UpdateCamera() { shipCurrentCamra++; if (shipCurrentCamra > 2) { shipCurrentCamra = 0; } } public void ShipAxisAnimations() { if (Mathf.Abs(transform.InverseTransformDirection(shipBody.velocity).z) < 100 && bShipIsGrounded) { // Anim Settings shipHoverAnimSpeed = 0.5f; shipHoverAnimAmount = 0.2f; shipHoverAnimTimer += Time.deltaTime * shipHoverAnimSpeed; shipHoverAnimOffset.x = (Mathf.Sin(shipHoverAnimTimer * 1.5f) * shipHoverAnimAmount) * Mathf.Sin(shipHoverAnimTimer); shipHoverAnimOffset.y = (Mathf.Cos(shipHoverAnimTimer * 4) * (shipHoverAnimAmount / 2)); } else { shipHoverAnimTimer = 0; shipHoverAnimOffset = Vector3.Lerp(shipHoverAnimOffset, Vector3.zero, Time.deltaTime); } // Apply Hover Anim Offset shipAxis.transform.localPosition = shipHoverAnimOffset; } /// <summary> /// Checks if the ship can sideshift and then starts a sideshift if it can. /// Input -1 for left, 1 for right. /// </summary> /// <param name="direction"></param> public void StartSideShift(int direction) { // Only allow the ship to sideshift if it is not already sideshifting, // if the sideshifting is not cooling down at that the ship is grounded if (!bIsShipSS && !bSSCoolingDown && bShipIsGrounded) { // The ship is now sideshifting bIsShipSS = true; // Invoke the sideshift to stop in 0.28 seconds Invoke("StopSideShift", 0.28f); // Set direction of sideshift if (direction == 1) { sideShiftDirection = transform.right; // Controller Vibration vibrationManager.vibRightMotor = 0.1f; vibrationManager.timerMotor = 1.4f; } else { sideShiftDirection = -transform.right; // Controller Vibration vibrationManager.vibLeftMotor = 0.1f; vibrationManager.timerMotor = 1.4f; } // PLAY SOUND HERE } } /// <summary> /// Stops the ship from sideshifting. /// </summary> public void StopSideShift() { // The ship is no longer sideshifting bIsShipSS = false; // Activate the cooldown bSSCoolingDown = true; // Invoke the cooldown to stop in 1 second Invoke("SideShiftCoolDown", 1.0f); // Reset the sideshift direction sideShiftDirection = Vector3.zero; } /// <summary> /// Allow the ship to sideshift again. /// </summary> public void SideShiftCoolDown() { // The cooldown has ended bSSCoolingDown = false; } /// <summary> /// Handles barrel rolling for the ship. /// </summary> public void ShipBarrelRoll() { } /// <summary> /// Switch to the next camera. /// </summary> public void ProgressCamera() { } /// <summary> /// Returns a vector that can be used to make the ship hover. /// </summary> /// <param name="HoverLocation"></param> /// <param name="DistanceToGround"></param> /// <returns></returns> public Vector3 CalculateHoverForce(Vector3 HoverLocation, float DistanceToGround) { return Vector3.zero; } /// <summary> /// Returns a vector that can be used to make the ship lock above the track. /// </summary> /// <param name="HoverLocation"></param> /// <returns></returns> public Vector3 CalculateMagStripForce(Vector3 HoverLocation) { return Vector3.zero; } public void SetupShip() { // Create rigidbody shipBody = gameObject.AddComponent<Rigidbody>(); shipBody.useGravity = false; shipBody.drag = 0; shipBody.angularDrag = 20; shipBody.constraints = RigidbodyConstraints.FreezeRotationY; // Create physics material shipPhysicsMaterial = new PhysicMaterial(); shipPhysicsMaterial.bounciness = 0; shipPhysicsMaterial.staticFriction = 0; shipPhysicsMaterial.dynamicFriction = 0; shipPhysicsMaterial.bounceCombine = PhysicMaterialCombine.Minimum; shipPhysicsMaterial.frictionCombine = PhysicMaterialCombine.Minimum; // Create ship axis shipAxis = new GameObject("Ship Axis"); shipAxis.transform.parent = transform; shipAxis.transform.localPosition = Vector3.zero; // Load ship GameObject ShipObject = Instantiate(Resources.Load("Ships/Test/LoadMe") as GameObject) as GameObject; ShipObject.transform.parent = shipAxis.transform; ShipObject.transform.localPosition = Vector3.zero; // Get ship settings settings = ShipObject.GetComponent<ShipSettings>(); // Create ship collider GameObject ShipCollider = new GameObject("Ship Collider"); ShipCollider.transform.parent = transform; ShipCollider.transform.localPosition = Vector3.zero; ShipCollider.AddComponent<BoxCollider>(); ShipCollider.GetComponent<BoxCollider>().size = settings.physColliderSize; ShipCollider.GetComponent<BoxCollider>().material = shipPhysicsMaterial; // Create controller controller = gameObject.AddComponent<ShipController>(); controller.controller = inputControl; // Camera if (bShipHasCameraControl) { shipCamera = Camera.main.gameObject; } // Attach forcefeedback manager vibrationManager = gameObject.AddComponent<FFManager>(); // Attach Audio/Visual Manager gameObject.AddComponent<ShipAVManager>(); } } <file_sep>using UnityEngine; using System.Collections; public class PlayOneShot : MonoBehaviour { public static void PlayShot(string SoundName, float volume, float pitch, float minRadius, float maxRadius, Transform parent, Vector3 position, AudioClip sound) { GameObject newSound = new GameObject(SoundName); newSound.AddComponent<AudioSource>(); newSound.GetComponent<AudioSource>().volume = volume; newSound.GetComponent<AudioSource>().pitch = pitch; newSound.GetComponent<AudioSource>().dopplerLevel = 0; newSound.GetComponent<AudioSource>().spatialBlend = 1; newSound.GetComponent<AudioSource>().minDistance = minRadius; newSound.GetComponent<AudioSource>().maxDistance = maxRadius; newSound.GetComponent<AudioSource>().clip = sound; newSound.GetComponent<AudioSource>().loop = false; newSound.transform.parent = parent; newSound.transform.position = position; newSound.GetComponent<AudioSource>().Play(); newSound.AddComponent<AudioShot>(); } } <file_sep>using UnityEngine; using System.Collections; public class FixedFlare : MonoBehaviour { LensFlare FlareComponent; public float Size; void Start() { FlareComponent = GetComponent<LensFlare>(); } void Update() { float ratio = Mathf.Sqrt(Vector3.Distance(transform.position, Camera.main.transform.position)); GetComponent<LensFlare>().brightness = Size / ratio; } } <file_sep>// AGR2280 2012 - 2015 // Created by Vonsnake using UnityEngine; using System.Collections; /// <summary> /// Contains the locations of ships in the resources folder. /// </summary> public class ShipLocations : MonoBehaviour { } <file_sep>using UnityEngine; using UnityEngine.UI; using System.Collections; public class TextSwapManager : Button { public HighlightTextSwap functionClass; void LateUpdate() { if (currentSelectionState == SelectionState.Highlighted || currentSelectionState == SelectionState.Pressed) { functionClass.Select(); } else { functionClass.Unselect(); } } } <file_sep>using UnityEngine; using System.Collections; public class ShipAVManager : MonoBehaviour { // Audio public AudioSource audioEngineSource; public AudioSource audioAirbrakeLeftSource; public AudioSource audioAirbrakeRightSource; // Visual private float visualLightItensity; private float idleLightFlickerSpeed = 100; private float idleLightFlickerAmount = 2f; private float idleLightFlickerTimer; private float visEngineTrailOpacity; private float visEngineTrailStartSize; private float visEngineTrailEndSize; private float visEngineTrailBrightness; void Start() { // Create engine audio GameObject engineAudio = new GameObject("Engine Audio"); engineAudio.transform.parent = transform; engineAudio.transform.localPosition = Vector3.zero; audioEngineSource = engineAudio.AddComponent<AudioSource>(); audioEngineSource.clip = GetComponent<ShipSimulator>().settings.audioEngine; audioEngineSource.spatialBlend = 1; audioEngineSource.minDistance = 100; audioEngineSource.maxDistance = 500; audioEngineSource.dopplerLevel = 0; audioEngineSource.loop = true; audioEngineSource.volume = 0; audioEngineSource.pitch = 1; audioEngineSource.Play(); } void Update() { // Get references to needed classes ShipController controller = GetComponent<ShipController>(); ShipSimulator simulator = GetComponent<ShipSimulator>(); // Engine Pitch and Volume float engineMax = 1.1f; if (simulator.bShipIsBoosting) { engineMax = 1.4f; // Cheeky engine light intensity change :^) visualLightItensity = 5.0f; } float wantedPitch = Mathf.Clamp(transform.InverseTransformDirection(GetComponent<Rigidbody>().velocity).z * Time.deltaTime, 0.5f, engineMax); audioEngineSource.pitch = Mathf.Lerp(audioEngineSource.pitch, wantedPitch, Time.deltaTime * 2); // Volume Control if (controller.btnThruster) { audioEngineSource.volume = Mathf.Lerp(audioEngineSource.volume, 1.0f, Time.deltaTime * 2); } else { audioEngineSource.volume = Mathf.Lerp(audioEngineSource.volume, 0.0f, Time.deltaTime); } // Light Control if (controller.btnThruster) { idleLightFlickerTimer = 0; visualLightItensity = Mathf.Lerp(visualLightItensity, 3.0f, Time.deltaTime); if (visualLightItensity < 1.5f) visualLightItensity = 1.5f; } else { visualLightItensity = Mathf.Lerp(visualLightItensity, 0.0f, Time.deltaTime); if (visualLightItensity < 1.5f) { idleLightFlickerTimer += Time.deltaTime * idleLightFlickerSpeed; visualLightItensity = Mathf.Sin(idleLightFlickerTimer) * idleLightFlickerAmount; } } simulator.settings.refEngineLight.GetComponent<Light>().intensity = visualLightItensity; // Engine Trail if (controller.btnThruster) { if (simulator.bShipIsBoosting) { visEngineTrailStartSize = Mathf.Lerp(visEngineTrailStartSize, 0.8f, Time.deltaTime * 12.0f); visEngineTrailEndSize = Mathf.Lerp(visEngineTrailEndSize, 6f, Time.deltaTime * 12.0f); visEngineTrailOpacity = Mathf.Lerp(visEngineTrailOpacity, 1.0f, Time.deltaTime * 5); } else { if (transform.InverseTransformDirection(GetComponent<Rigidbody>().velocity).z > 50) { visEngineTrailStartSize = Mathf.Lerp(visEngineTrailStartSize, 0.5f, Time.deltaTime * 6.0f); visEngineTrailEndSize = Mathf.Lerp(visEngineTrailEndSize, 5.0f, Time.deltaTime * 6.0f); visEngineTrailOpacity = Mathf.Lerp(visEngineTrailOpacity, 0.5f, Time.deltaTime * 5.0f); } else { visEngineTrailStartSize = Mathf.Lerp(visEngineTrailStartSize, 0.0f, Time.deltaTime * 6.0f); visEngineTrailEndSize = Mathf.Lerp(visEngineTrailEndSize, 0.0f, Time.deltaTime * 6.0f); visEngineTrailOpacity = Mathf.Lerp(visEngineTrailOpacity, 0.0f, Time.deltaTime * 2.0f); } } } else { visEngineTrailStartSize = Mathf.Lerp(visEngineTrailStartSize, 0.50f, Time.deltaTime * 6.0f); visEngineTrailEndSize = Mathf.Lerp(visEngineTrailEndSize, 0.2f, Time.deltaTime * 6.0f); visEngineTrailOpacity = Mathf.Lerp(visEngineTrailOpacity, 0.0f, Time.deltaTime * 2.0f); } simulator.settings.refEngineTrail.GetComponent<TrailRenderer>().startWidth = visEngineTrailStartSize; simulator.settings.refEngineTrail.GetComponent<TrailRenderer>().endWidth = visEngineTrailEndSize; simulator.settings.refEngineTrail.GetComponent<TrailRenderer>().material.SetColor("_TintColor", new Color(1, 1, 1, visEngineTrailOpacity)); Vector2 texOffset = simulator.settings.refEngineTrail.GetComponent<TrailRenderer>().material.GetTextureOffset("_MainTex"); texOffset.x += Time.deltaTime * 10; simulator.settings.refEngineTrail.GetComponent<TrailRenderer>().material.SetTextureOffset("_MainTex", texOffset); } public void ThrusterUp() { PlayOneShot.PlayShot("ThrusterRelease", 1.0f, 1.0f, 200, 100, transform, transform.position, GetComponent<ShipSimulator>().settings.audioEngineCooler); } public void ThrusterDown() { PlayOneShot.PlayShot("ThrusterDown", 1.0f, 1.0f, 200, 100, transform, transform.position, GetComponent<ShipSimulator>().settings.audioEngineStartup); visualLightItensity = 5.0f; } } <file_sep>// AGR2280 2012 - 2015 // Created by Vonsnake using UnityEngine; using System.Collections; using BSGTools.IO; using IM = BSGTools.IO.InputMaster; /// <summary> /// Handles ship input and local race data such as lap times. /// </summary> public class ShipController : MonoBehaviour { // INPUT | Axis public float inputSteer; public float inputPitch; public float inputLeftAirbrake; public float inputRightAirbrake; // INPUT | Buttons public bool btnThruster; // INPUT | Sideshifting private int previousSSInput; private int ssTapAmount; private float ssTimer; private float ssCooler; private bool ssLeft; private bool ssLeftPressed; private bool ssRight; private bool ssRightPressed; // Controller public GlobalSettings.InputController controller; // Manager RaceManager manager; // Bools public bool bHasFinishedRace; void Awake() { // Check to see if controls have already been setup, if not then create them. // This is really only for use when using the Unity Editor since it's more then likely // that you havn't gone through the splash screen which is where the controls are setup if (!ControlsManager.bHasLoadedControls) { ControlsManager.SetDefaultControls(); } IM.Initialize(); } void Update() { // Use a switch to check whether to get player or AI input switch(controller) { case GlobalSettings.InputController.Player: GetPlayerInput(); break; case GlobalSettings.InputController.AI: GetAIInput(); break; } } private void GetPlayerInput() { // Get the input axis inputSteer = IM.GetAxis("Steer").value; inputPitch = IM.GetAxis("Pitch").value; inputLeftAirbrake = IM.GetAxis("LeftAirbrake").value; inputRightAirbrake = IM.GetAxis("RightAirbrake").value; // Get whether the player is accelerating btnThruster = false; if (IM.GetAction("Thrust").state == State.Held) btnThruster = true; // Reset sideshift inputs ssLeft = false; ssRight = false; // Left airbrake tap if ((inputLeftAirbrake != 0 && inputRightAirbrake == 0) && !ssLeftPressed) { ssLeft = true; ssLeftPressed = true; ssRight = false; } // Right airbrake tap if ((inputRightAirbrake != 0 && inputLeftAirbrake == 0) && !ssRightPressed) { ssRight = true; ssRightPressed = true; ssLeft = false; } // No airbrake taps if (inputLeftAirbrake == 0 && inputRightAirbrake == 0) { ssLeftPressed = false; ssRightPressed = false; } SideshiftInput(); // Vibrate the controller when starting to thrust if (IM.GetAction("Thrust").state == State.Down) { GetComponent<FFManager>().timerMotor = 1.2f; GetComponent<FFManager>().vibLeftMotor = 0.4f; GetComponent<FFManager>().vibRightMotor = 0.4f; } // Thruster Events if (IM.GetAction("Thrust").state == State.Down) { GetComponent<ShipAVManager>().ThrusterDown(); } if (IM.GetAction("Thrust").state == State.Up) { GetComponent<ShipAVManager>().ThrusterUp(); GetComponent<FFManager>().timerMotor = 1.2f; GetComponent<FFManager>().vibLeftMotor = 0.3f; GetComponent<FFManager>().vibRightMotor = 0.3f; } // Braking vibration if (GetComponent<ShipSimulator>().bShipIsBraking) { GetComponent<FFManager>().timerMotor = 1.2f; GetComponent<FFManager>().vibLeftMotor = 0.1f; GetComponent<FFManager>().vibRightMotor = 0.1f; } // Camera Change if (IM.GetAction("CameraToggle").state == State.Down) { GetComponent<ShipSimulator>().UpdateCamera(); } // Look Behind if (IM.GetAction("LookBehind").state == State.Held) { GetComponent<ShipSimulator>().bLookingBehind = true; } else { GetComponent<ShipSimulator>().bLookingBehind = false; } } private void SideshiftInput() { // Opposite sideshift inputs cancel each other if ((previousSSInput == -1 && ssRight) || (previousSSInput == 1 && ssLeft)) { ssTapAmount = 0; previousSSInput = 0; } // Double tap left airbrake if (ssLeft) { previousSSInput = -1; if (ssCooler > 0 && ssTapAmount == 1) { GetComponent<ShipSimulator>().StartSideShift(previousSSInput); } else { ssCooler = 0.2f; ssTapAmount++; } } // Double tap right airbrake if (ssRight) { previousSSInput = 1; if (ssCooler > 0 && ssTapAmount == 1) { GetComponent<ShipSimulator>().StartSideShift(previousSSInput); } else { ssCooler = 0.2f; ssTapAmount++; } } // Sideshift Cooler if (ssCooler > 0) { ssCooler -= 1 * Time.deltaTime; } else { ssTapAmount = 0; } } private void GetAIInput() { } } <file_sep>using UnityEngine; using System.Collections; public class AudioShot : MonoBehaviour { AudioSource sound; void Start() { sound = GetComponent<AudioSource>(); } void LateUpdate() { if (!sound.isPlaying) { Destroy(this.gameObject); } } } <file_sep>using UnityEngine; using UnityEngine.UI; using System.Collections; public class SetProfileName : MonoBehaviour { public GameObject textToGet; public void UpdateName() { } } <file_sep>using UnityEngine; using UnityEngine.Audio; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; public class MusicPlayer : MonoBehaviour { public List<AudioClip> MusicClips = new List<AudioClip>(); public List<string> MusicNames = new List<string>(); public List<string> MusicArists = new List<string>(); private AudioSource audioSource; private AudioMixer audioMixer; private float highPassMax = 2178.0f; private float highPassMin = 10.0f; public float highPass = 10.0f; public ShipSimulator shipToCheck; // UI public Text songText; void Start() { GetAvailableMusic(); SetupPlayer(); } // Run on update just to save on performance void LateUpdate() { // If no song is playing then get random song index and play it if (!audioSource.isPlaying) { int rand = Random.Range(0, MusicClips.Count); AudioClip ChosenClip = MusicClips[rand]; // Play clip audioSource.clip = ChosenClip; audioSource.Play(); // Update song text songText.text = "NOW PLAYING: " + ChosenClip.name; // Play Scroll Animation songText.gameObject.GetComponent<Animation>().Play("NowPlayingScroll"); } // High Pass if (shipToCheck != null && !shipToCheck.bShipIsGrounded) { highPass = Mathf.Lerp(highPass, highPassMax, Time.deltaTime); } else { highPass = Mathf.Lerp(highPass, highPassMin, Time.deltaTime * 5); } // Apply high pass audioSource.outputAudioMixerGroup.audioMixer.SetFloat("musicHP", highPass); } private void GetAvailableMusic() { } private void SetupPlayer() { // Create Audio Source audioSource = gameObject.AddComponent<AudioSource>(); // Get audio mixer audioMixer = Resources.Load("Audio/Master") as AudioMixer; // Find music mixer groups AudioMixerGroup[] MusicGroups = audioMixer.FindMatchingGroups("Music"); // Set audio source mixer group to first index audioSource.outputAudioMixerGroup = MusicGroups[0]; } } <file_sep>using UnityEngine; using System.Collections; public class ReflectionProbeUpdate : MonoBehaviour { private ReflectionProbe reflection; void Start() { reflection = GetComponent<ReflectionProbe>(); } void LateUpdate() { reflection.RenderProbe(); } } <file_sep>using UnityEngine; using UnityEngine.UI; using System.Collections; public class ShipHUDManager : MonoBehaviour { public GameObject targetShip; public GameObject speedText; void Update() { // Get the ship speed float speed = targetShip.transform.InverseTransformDirection(targetShip.GetComponent<Rigidbody>().velocity).z * 2; // Set speed text speedText.GetComponent<Text>().text = Mathf.RoundToInt(speed).ToString(); } } <file_sep>using UnityEngine; using BSGTools.IO; using IM = BSGTools.IO.InputMaster; using System.Collections; using System.Collections.Generic; public class ControlsManager : MonoBehaviour { public static bool bHasLoadedControls; public static List<Control> controls = new List<Control>(); public static void SetDefaultControls() { controls.Clear(); IM.Initialize(); controls.AddRange(new Control[] { new ActionControl("Thrust", Scope.All) .AddBinding(Binding.Space) .AddBinding(Binding.JoystickButton0), // A new ActionControl("Fire", Scope.All) .AddBinding(Binding.LeftShift) .AddBinding(Binding.JoystickButton2), // X new ActionControl("Absorb", Scope.All) .AddBinding(Binding.LeftControl) .AddBinding(Binding.JoystickButton1), // B new ActionControl("CameraToggle", Scope.All) .AddBinding(Binding.C) .AddBinding(Binding.JoystickButton3), // Y new ActionControl("LookBehind", Scope.All) .AddBinding(Binding.X) .AddBinding(Binding.JoystickButton4), // Shoulder Left new ActionControl("Special", Scope.All) .AddBinding(Binding.Z) .AddBinding(Binding.JoystickButton5), // Shoulder Right new ActionControl("Pause", Scope.All) .AddBinding(Binding.Escape) .AddBinding(Binding.JoystickButton7), // Start new AxisControl("Steer") .AddBinding(Binding.LeftArrow, -1f) .AddBinding(Binding.RightArrow, 1f) .AddBinding(Binding.LeftX, 1f) .AddBinding(Binding.DPadLeft, -1f) .AddBinding(Binding.DPadRight, 1f), new AxisControl("Pitch") .AddBinding(Binding.DownArrow, -1f) .AddBinding(Binding.UpArrow, 1f) .AddBinding(Binding.LeftY, 1f) .AddBinding(Binding.DPadDown, -1f) .AddBinding(Binding.DPadUp, 1), new AxisControl("LeftAirbrake") .AddBinding(Binding.Q, -1f) .AddBinding(Binding.TriggerLeft, -1f), new AxisControl("RightAirbrake") .AddBinding(Binding.E, 1f) .AddBinding(Binding.TriggerRight, 1f) }); IM.controls.AddRange(controls); } } <file_sep>using UnityEngine; using System.Collections; public class RaceManager : MonoBehaviour { // Race Settings public enum RaceState { Overview = 0, Countdown = 1, Started = 2, Complete = 3 }; public RaceState raceProgression; } <file_sep>// AGR2280 2012 - 2015 // Created by Vonsnake using UnityEngine; using System.Collections; /// <summary> /// Stores settings for the ship simulator to read. /// </summary> public class ShipSettings : MonoBehaviour { // Turning public float turnAmount; public float turnGain; public float turnFalloff; // Acceleration Cap public float engineAccelCapD; public float engineAccelCapC; public float engineAccelCapB; public float engineAccelCapA; public float engineAccelCapAP; public float engineAccelCapAPP; // Thrust Cap public float engineThrustCapD; public float engineThrustCapC; public float engineThrustCapB; public float engineThrustCapA; public float engineThrustCapAP; public float engineThrustCapAPP; // Others public float engineFalloff; public float engineGain; public float engineTurbo; // Air Grip public float agGripAirD; public float agGripAirC; public float agGripAirB; public float agGripAirA; public float agGripAirAP; public float agGripAirAPP; // Ground Grip public float agGripGroundD; public float agGripGroundC; public float agGripGroundB; public float agGripGroundA; public float agGripGroundAP; public float agGripGroundAPP; // Rebound public float agReboundLanding; public float agRebound; public float agReboundJumpTime; // Close Camera public float camCloseFoV; public Vector3 camCloseLA; public Vector3 camCloseOffset; public float camCloseSpringHor; public float camCloseSpringVert; // Far Camera public float camFarFoV; public Vector3 camFarLA; public Vector3 camFarOffset; public float camFarSpringHor; public float camFarSpringVert; // Internal Camera public float camIntFoV; public Vector3 camIntOffset; // Backward Camera public float camBackFoV; public Vector3 camBackOffset; // Bonnet Camera public float camBonnetFoV; public Vector3 camBonnetOffset; // Airbrakes public float airbrakesAmount; public float airbrakesDrag; public float airbrakesFalloff; public float airbrakesGain; public float airbrakesTurn; public float airbrakesSlidegrip; public float airbrakesSideshift; // Airbrake visual public float airbrakeUpSpeed; public float airbrakeDownSpeed; public float airbrakeAmount; // Front-end public int feSpeed; public int feThrust; public int feHandling; public int feShield; // Tilt public float tiltInternalSpeed; public float tiltInternalAmount; public float tiltShipSpeed; public float tiltShipAmount; // Physical public Vector3 physColliderSize; public float physShieldAmount; public float physWeightDist; // Audio public AudioClip audioAirbrake; public AudioClip audioEngine; public AudioClip audioEngineStartup; public AudioClip audioEngineCooler; // References public GameObject refMeshContainers; public GameObject refEngineLight; public GameObject refEngineTrail; } <file_sep>// AGR2280 2012 - 2015 // Created by Vonsnake using UnityEngine; using System.Collections; /// <summary> /// Contains all of the variables needed for shared functionality across all classes. /// </summary> public class GlobalSettings : MonoBehaviour { // Controller public enum InputController { Player = 0, AI = 1 }; // Speed Classes public enum SpeedClasses { D = 0, C = 1, B = 2, A = 3, AP = 4, APP = 5 }; // Global Ship Settings // Pitching public static float shipPitchAirAmount = 0.2f; public static float shipPitchGroundAmount = 1.0f; public static float shipPitchDamping = 5.0f; public static float shipAntiGravHeightAdjust = 1.0f; // Brakes public static float shipBrakesAmount = 100.0f; public static float shipBrakesGain = 100.0f; public static float shipBrakesFalloff = 100.0f; // Gravity Multiplier public static float airGravityMulD = 0.95f; public static float airGravityMulC = 1.0f; public static float airGravityMulB = 1.1f; public static float airGravityMulA = 1.2f; public static float airGravityMulAP = 1.3f; public static float airGravityMulAPP = 1.5f; // Track Gravity public static float shipTrackGravityD = 80.0f; public static float shipTrackGravityC = 80.0f; public static float shipTrackGravityB = 85.0f; public static float shipTrackGravityA = 85.0f; public static float shipTrackGravityAP = 85.0f; public static float shipTrackGravityAPP = 85.0f; // Flight Gravity public static float shipFlightGravityD = 110.0f; public static float shipFlightGravityC = 110.0f; public static float shipFlightGravityB = 115.0f; public static float shipFlightGravityA = 115.0f; public static float shipFlightGravityAP = 115.0f; public static float shipFlightGravityAPP = 115.0f; // Other Gravity public static float shipMass = 1.0f; public static float shipNormalGravity = 5.0f; // Other Settings public static float shipRideHeight = 5.5f; // Global Mods // Specials public static float rollCost = 15f; public static float rollSpeed = 1.5f; public static float rollTurboTime = 0.3f; public static float boostJump = 0.05f; // Zone public static float zoneIncrement = 0.4f; public static float zoneRecharge = 10.0f; public static float zoneStart = 34.0f; // Camera Pitch Mod public static float camPitchModDownMult = 0.35f; public static float camPitchModDownOffset = 3.0f; public static float camPitchModUpMult = 0.35f; public static float camPitchModUpOffset = 3.0f; // Start Boost public static float sbTimeLength = 0.4f; public static float sbBoostMultiplier = 1.7f; // Collision public static float WeaponHitFactor = 0.9f; public static float ShipCoF = 1.0f; public static float ShipCoR = 0.8f; // Other public static float speedPadAmount = 600.0f; public static float speedPadTime = 0.27f; public static float weaponPadRefreshTime = 0.75f; public static float weaponPadEliminationRefreshTime = 0.15f; } <file_sep>using UnityEngine; using XInputDotNetPure; using System.Collections; public class FFManager : MonoBehaviour { public float timerMotor; public float vibLeftMotor; public float vibRightMotor; void Update() { if (timerMotor == -1) { GamePad.SetVibration(0, vibLeftMotor, vibRightMotor); } else { timerMotor -= Time.deltaTime; if (timerMotor < 1) { timerMotor = 0; GamePad.SetVibration(0, 0, 0); } else { GamePad.SetVibration(0, vibLeftMotor, vibRightMotor); } } } public void StopVibration() { GamePad.SetVibration(0, 0, 0); } void OnApplicationQuit() { StopVibration(); } }
779e8dd2e7a524f0bf5d7120ed36c83fc73d8b82
[ "C#" ]
20
C#
bigsnake09/AGR2280
1b2ae1f12cfc5fda76ec68201e98f895547d3bf7
a9ca09edf927684daaa2cbfc2f08f0a9b8a9d907
refs/heads/master
<file_sep><?php if (array_key_exists('getTemperature', $_REQUEST)) { getFile('/temperature/temperature.json'); return true; } else if (array_key_exists('getPrecipitation', $_REQUEST)){ getFile('/precipitation/precipitation.json'); return true; } require('index.html'); function getFile($path){ $pathToFile = $_SERVER['DOCUMENT_ROOT'] . $path; if (file_exists($pathToFile)) { $GetContentFile = file_get_contents($pathToFile); echo $GetContentFile; } }<file_sep>test = { temperature: [], percipitation: [], getJsonData: function (action, name, cb) { if (!action) return; var xhr = new XMLHttpRequest(); xhr.open("GET", 'index.php?' + action, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(); xhr.onreadystatechange = function() { if (xhr.readyState != 4) return; if (xhr.status != 200) { alert(xhr.status + ': ' + xhr.statusText); } else { cb(name, xhr.responseText); } } }, init: function(){ let self = this; let cb = (name, response) => { self[name] = JSON.parse(response); self.tests.avg.call(self, name); }; this.getJsonData('getTemperature', 'temperature', cb); this.getJsonData('getPrecipitation','precipitation', cb); }, tests: { avg: function (name){ var data = this[name]; avgArr = []; for (var i = 0; i < 10; i++){ avgArr.push(data[i].v) } let v = parseFloat( avgArr.reduce( (a, b) => { return a + b } ) / ( avgArr.length == 0 ? 1 : avgArr.length) ).toFixed(1); console.log(v); }, cleardb: function (name){ var db; var version = 12; var dbname = 'MyTestDatabase'; var request = window.indexedDB.open(dbname, version); request.onsuccess = function (event) { var db = event.target.result; var transaction = db.transaction([name], "readwrite"); transaction.onerror = function(event) { console.log('addData error', event); }; var objectStore = transaction.objectStore(name); var request = objectStore.clear(); request.onsuccess = function(event) { console.log('successfull clear', name) }; }; }, clearObjectStore:function (){ debugger; Window.db.clearObjectStore('temperature'); Window.db.clearObjectStore('precipitation'); } } }; <file_sep>let graphic = { elements: { 'year-from': document.getElementById('year-from'), 'year-to': document.getElementById('year-to'), 'date-start': document.getElementById('date-start'), 'date-end': document.getElementById('date-end'), 'temperature-button': document.getElementById('temperature-button'), 'precipitation-button': document.getElementById('precipitation-button'), 'clear-button': document.getElementById('clear-button'), 'r40': document.getElementById('r40'), 'r10': document.getElementById('r10') }, /// массивы среднемесячной температуры temperature: [], precipitation: [], /// массивы среднегодовой температуры avgtemperature: [], avgprecipitation: [], /// текущий тип данных currentState: '', /// название текущего массива с среднегодовой currentStateArrayName: '', /// переменные используемые в canvas canvas: { d1: '', d2: '', /// Y шкала yArr: [40, 30, 20, 10, 0, -10, -20, -30, -40] //yArr: [10, 7.5, 5, 2.5, 0, -2.5, -5, -7.5, -10] }, /// хаб для keyup'ов keyhub: [], /// тип данных по умолчанию defaultDataType: 'temperature', debug: 0, /* * первоначальная инициализация * */ init: function () { this.canvasInit(); let els = this.elements; els['date-start'].addEventListener('change', this.periodChangeHandle.bind(this, els['date-start'])); els['date-end'].addEventListener('change', this.periodChangeHandle.bind(this, els['date-end'])); els['year-from'].addEventListener('keyup', this.fastSelectYear.bind(this, els['year-from'])); els['year-to'].addEventListener('keyup', this.fastSelectYear.bind(this, els['year-to'])); els['temperature-button'].addEventListener('click', this.getData.bind(this, 'temperature', els['temperature-button'])); els['precipitation-button'].addEventListener('click', this.getData.bind(this, 'precipitation', els['precipitation-button'])); els['clear-button'].addEventListener('click', this.clearYearInputs.bind(this)); els['r40'].addEventListener('change', this.degreeChange.bind(this, els['r40'])); els['r10'].addEventListener('change', this.degreeChange.bind(this, els['r10'])); }, /** * базовая инициализация графика * поле и пунктирные линии с градусами * */ canvasInit: function (){ var canvas = document.getElementById("graphic"); var context = canvas.getContext("2d"); context.strokeStyle = 'grey'; context.lineWidth = 0.5; context.lineCap = 'round'; let temp = this.canvas.yArr; /** * внешний цикл - отрисовка градусов, * внутренний цикл - отрисовка пунктирной линнии * this.canvas.yArr.length + 1 , +1 из-за того что у нас -40 * начинается не с границы, а со сдвигом в шаг */ for (let i = 0; i < temp.length; i++){ let step = parseInt(canvas.height / (temp.length + 1 )); let y = step * i + step; context.font = "bold 12px sans-serif"; context.fillText(temp[i], 0, y); for (let j = 0; j < canvas.width; j+=5){ context.strokeStyle = "#000"; context.beginPath(); context.arc(j, y, 1, 0, Math.PI * 2, false); context.closePath(); context.stroke(); } } context.stroke(); }, /** * Функция заполнения периодов по типу данных * Запустит Worker для обработки среднемесячного массива в среднегодовой * можно обойтись и без workera, но с ним чуть-чуть быстре * затем инициализируется заполнение периодов * @params dataType {String} название типа данных temperature\precipitation * @params element {DOMButton} кнопка выбора типа данных, для проставления класса * */ getData: function (dataType, element) { this.clearActiveCss(); element.classList.add('active'); this.currentState = dataType; this.currentStateArrayName = `avg${dataType}`; this.clearPeriod(); worker.postMessage( {'cmd': 'create-period', arr: this[dataType], name: dataType }); return true; }, /** * очистка активного класса * */ clearActiveCss: function(){ this.elements['precipitation-button'].classList.remove('active'); this.elements['temperature-button'].classList.remove('active'); }, /** * Функция очистки селектов, всех либо по одному по ID * @params selectID {String} - если пусто очистит оба селекта * */ clearPeriod: function(){ if (arguments.length == 0) { this.elements['date-start'].options.length = 0; this.elements['date-end'].options.length = 0; } if (typeof arguments[0] == 'string') { if (this.elements[arguments[0]]) { this.elements[arguments[0]].options.length = 0; } } }, /** * Функция записи массива для селектов, с среднегодовыми значениями * @params data {Object} {name: , arr:} * */ setAvgArray: function (data) { this[this.currentStateArrayName] = data.arr; return this; }, /** * Создание элеметов селекта * дефолтные индексы нужны для того чтобы при изменении типа данных * даты не сбрасывались * @params select {DOMSelect} * @params arr {Array} - массив с данными для селекта * @params def1 {Integer} - дефолтный индекс для первой даты * @params def2 {Integer} - дефолтный индекс для второй даты * * */ createOptions: function(select, arr, def1, def2){ for (var i = 0; i < arr.length; i++){ let option = arr[i]; let opt = document.createElement('OPTION'); opt.text = option.t; opt.value = option.t; select.options.add(opt); } select.selectedIndex = select.id == 'date-start' ? (def1 || 0) : (def2 || i-1); return this; }, /** * заполнение переменных canvas.d1 и canvas.d2 с выбранными индексами для графика * @params select {DOM select} * @params index {Integer} индекс выбранного элемента * */ setGraphicIndexes: function(select, index){ if (!index){ index = select.selectedIndex; } select.id == 'date-start' ? this.canvas.d1 = index : this.canvas.d2 = index; return this; }, /** * очистка полей ввода быстрого переключения года * */ clearYearInputs: function(){ this.elements['year-from'].value = ''; this.elements['year-to'].value = ''; this.periodFilter(this.elements['year-from']); this.periodFilter(this.elements['year-to']); }, /** * процедура создания периодов из Workera * @params select {DOM select} * @params data {Object} {name: , arr:} */ createOptionsHandle: function (select, data) { this.createOptions(select, data.arr, this.canvas.d1, this.canvas.d2); this.setGraphicIndexes(select); //this.clearYearInputs(); return this; }, findIndex: function(select){ let index = this[this.currentStateArrayName].findIndex(function(item){ return item.t == select.value; }); return index; }, /** * обработчик события onchange у select * заполняет переменные индекса для графика * запускает отрисовку графика * @param select {DOMSelectElement} select с датами */ periodChangeHandle: function(select){ let index = this.findIndex(select); this.setGraphicIndexes(select, index); this.draw(); }, /** * функция отрисовки графика * @returns true */ draw: function (){ let arr = this[this.currentStateArrayName]; if (this.canvas.d1 > this.canvas.d2) return false; let canvas = document.getElementById("graphic"); let context = canvas.getContext("2d"); /// очистка canvas и последующая инициализация сетки context.clearRect(0, 0, canvas.width, canvas.height); this.canvasInit(); context.beginPath(); context.strokeStyle = "#000"; context.font = "bold 8px sans-serif"; /** * xShift - сдвиг с правого края графика, чтобы линия не упиралась в границу графика * xStep - шаг с учетом уменьшенного размера из-за сдвига * xStepShift - сдвиг шага, чтобы линия начиналась на с левой границы графика * */ let xWidth = canvas.width; let xShift = (xWidth * 0.1); let xStepShift = xShift/2; let xStep = parseFloat( (xWidth - xShift - xStepShift) / ((this.canvas.d2 - this.canvas.d1) == 0 ? 1 : this.canvas.d2 - this.canvas.d1) ); /** * определяем 'у' координату температуры * yZero - координаты нуля * yStep - шаг между десятками градусов * this.canvas.yArr.length + 1 , +1 из-за того что у нас -40 * начинается не с границы, а со сдвигом в шаг * oneDegree - размер 1 шага в пикселях */ let yZero = canvas.height / 2; let yStep = canvas.height / (this.canvas.yArr.length + 1); let oneDegree = yStep / (this.canvas.yArr[0] - this.canvas.yArr[1]); let x,y; /** * в цикле считаем Х и У точки в графике * рисуем в нужном месте точку, прямоугольник с числовым значением средней температуры */ for (let i = 0; i <= (this.canvas.d2 - this.canvas.d1); i++){ let index = this.canvas.d1 + i; let t = arr[index].t; let v = arr[index].v; y = yZero - (parseFloat(v) * oneDegree); x = i * xStep + xStepShift; if (this.debug) console.log(t, v); if (i == 0){ context.moveTo(x, y); } else { context.lineTo(x, y); } context.strokeStyle = "lightgreen"; context.fillStyle = "lightgreen"; context.fillRect(x, y, 17, 13); context.strokeStyle = "#000"; context.fillStyle = "#000"; context.fillText(v, x+3, y+8); context.arc(x, y, 1, 0, Math.PI * 2, false); } context.moveTo(x, y); context.closePath(); context.stroke(); return true; }, /** * обработчик быстрого переключения года, инициатива */ fastSelectYear: function(input){ let self = this; self.keyhub.push(); setTimeout(function(){ if (!self.currentState) return false; /// событий keyup может возникнуть не одно, отсекаем лишние if (self.keyhub.length > 1){ self.keyhub.pop(); return; } self.periodFilter(input); }, 500); } , /** * фильтрация массива в объекте данных по введенной информации * создаем период по отфильтрованному массиву * если фильтр ничего не отфильтровал(введена плохая информация) * то ставим активным первый элемент * @params input {DOMInput} Input по которому происходит фильтрация */ periodFilter: function(input){ let select = input.id == 'year-from' ? this.elements['date-start'] : this.elements['date-end']; let val = input.value; let z = this[this.currentStateArrayName].filter(function(item){ return item.t.indexOf(val) >-1; }); if (!z.length) z.push(this[this.currentStateArrayName][0]); this.clearPeriod(select.id); this.createOptions(select, z); this.periodChangeHandle(select); this.keyhub.length = 0; }, /** * изменение У шкалы графика, инициатива * шкала типа 4 диапазона выше нуля и 4 ниже нуля * @params radio {DOMRadio} радио с значнием максимального градуса по плюсу * */ degreeChange: function(radio){ let value = +radio.value; if (!value) return false; let step = value / 4; let yArr = [value]; for (let i = 1; i < 9; i++){ value = value - step; yArr.push(value); } this.canvas.yArr = yArr; this.draw(); } }; var worker = new Worker('js/worker.js?'+Math.random()); worker.addEventListener('message', function(e) { let methods = { /** * Создание периодов * */ 'create-period': function (data) { graphic.setAvgArray(data); graphic.createOptionsHandle(graphic.elements['date-start'], data); graphic.createOptionsHandle(graphic.elements['date-end'], data); graphic.draw(); }, /** * Вставка в базу данных * */ 'insert-to-database': function (data){ for (var i = 0; i < data.arr.length; i++){ Window.db.addRecord(data.name, data.arr[i]); } }, /** * запись массивов с среднемесячной информацией * */ 'set-graphic-arr': function(data){ graphic[data.name] = data.arr; /// вставлено сюда для ускорения работы при первом запуске, /// как только получили температуру, так сразу инициализируем график if (data.name == graphic.defaultDataType) { this['default-initilize'](); } }, /** * дефолтная инициализация по температуре * */ 'default-initilize': function(){ graphic.getData(graphic.defaultDataType, graphic.elements['temperature-button']); } }; if (methods[e.data.cmd]) { methods[e.data.cmd](e.data.data); } }, false); window.onload = function(){ graphic.init(); }; function clearObjectStore (){ Window.db.clearObjectStore('temperature'); Window.db.clearObjectStore('precipitation'); } <file_sep>self.addEventListener('message', function(e) { var data = e.data; let methods = { 'create-period': function(){ /** * группировка массива по годам для селектов дат * согласно задания: "Пользователь должен иметь возможность уточнить период отображения архива и указать период с точностью до года." */ /// считаем среднее значение температуры по годам let arr = data.arr; let prevYear = 0; let avgArr = []; let resultArr = []; for (let i = 0; i < arr.length; i++){ let year = arr[i].t.split('-')[0]; if ( (year != prevYear) && (prevYear != 0) ){ let v = getAvgByArr(avgArr); resultArr.push({'t': prevYear, 'v': v }); avgArr = []; } avgArr.push(arr[i].v); prevYear = year; } /// для того, чтобы не потерять последний год resultArr.push({'t': prevYear, 'v': getAvgByArr(avgArr) }); self.postMessage({cmd: 'create-period', data: {name: data.name, arr: resultArr}}); }, 'insert-to-database': function(){ /** * Группировка массива по месяцам, и запись в БД согласно задания: * "Запись за отдельный месяц метеорологических измерений должна хранится как отдельный объект/запись в IndexedDB." */ /// считаем среднее значение температуры по месяцам let arr = data.arr; let prevYear = 0; let prevMonth = 0; let avgArr = []; let resultArr = []; for (let i = 0; i < arr.length; i++){ let dateArr = arr[i].t.split('-'); let year = dateArr[0]; let month = dateArr[1]; if ( (month != prevMonth) && (prevMonth != 0) ){ let v = getAvgByArr(avgArr); resultArr.push({'t': prevYear+ '-' +prevMonth, 'v': v }); avgArr = []; } avgArr.push(arr[i].v); prevMonth = month; prevYear = year; } // для того чтобы не потерять последний месяц resultArr.push({'t': `${prevYear}-${prevMonth}`, 'v': getAvgByArr(avgArr) }); self.postMessage({cmd: 'set-graphic-arr', data: {name: data.name, arr: resultArr}}); self.postMessage({cmd: 'insert-to-database', data: {name: data.name, arr: resultArr}}); }, 'set-graphic-arr': function(){ self.postMessage({cmd: 'set-graphic-arr', data: {name: data.name, arr: data.arr}}); } }; /** * Расчет среднего значения по массиву * @param arr {Array} массив значений 'v' * @returns {float} среднее значение по массиву, с точностью до 1 знака. */ function getAvgByArr(arr){ if (!arr.length) return false; let v = parseFloat( arr.reduce( (a, b) => { return parseFloat(a) + parseFloat(b) } ) / ( arr.length == 0 ? 1 : arr.length) ).toFixed(1); return v; } if (methods[data.cmd]) { methods[data.cmd]() } else { self.postMessage('Unknown command: ' + data.msg); } }, false);
9ed5aeb82d47e9616b43101ba42d4d1b31843157
[ "JavaScript", "PHP" ]
4
PHP
iseekyouu/weather_graphic
5d3d9014cb93a599a4a9f440af0d881a674257fe
5e0e940854f5bfb2873bbdbcb869045c2472cc4f
refs/heads/master
<repo_name>Vinicius-rodrigues/Kill_mustache<file_sep>/README.md kill_mustache =============================== version number: 0.0.1 author: <NAME> Overview -------- remove to mustache file Installation / Usage -------------------- To install use pip: $ pip install kill_mustache Or clone the repo: $ git clone https://github.com/Vinicius-rodrigues/kill_mustache.git $ python setup.py install Example ------- $ python kill_mustache <directory> <mustache_name_with_the_content_you_want_to_keep> <file_sep>/kill_mustache/kill_mustache/kill_mustache.py #!/usr/bin/env python # -*- coding: utf-8 -*- import pystache import sys diretorio = sys.argv [1] telas = sys.argv[2:] obj = {tela: True for tela in telas} input_file = None arquivo = open(diretorio, 'r') with open(diretorio) as d: input_file = d.read() file_rendered = pystache.render(input_file, obj) print(file_rendered)
cf96223b01638144d80229085b1afe0a9d60c65e
[ "Markdown", "Python" ]
2
Markdown
Vinicius-rodrigues/Kill_mustache
09a84c8225ac240094078c1ed2ba3edb891908dc
147d61562e219dc1d9e4999a8a59c30e38323fff
refs/heads/master
<repo_name>vasil/notable<file_sep>/lib/notable/app.rb require 'sinatra/base' require 'haml' class Notable::App < Sinatra::Default configure do DataMapper.setup(:default, ENV['DATABASE_URL'] || 'sqlite3:notes.db') DataMapper.auto_upgrade! if !test? and DataMapper.respond_to?(:auto_upgrade!) end # helpers def link_to(page = '/') "#{request.env['SCRIPT_NAME']}#{page}" end def hostname if request.env['HTTP_X_FORWARDED_PROTO'] == 'https' "https://#{request.env['SERVER_NAME']}" else "http://#{request.env['SERVER_NAME']}:#{request.env['SERVER_PORT']}" end end def absolute_url(page = '/') "#{hostname}#{link_to(page)}" end def format_note(note) "#{note.html_body} - <em>#{note.created_at.strftime('%H:%M')} #{note.created_at_to_s}</em>" end def choose_format case request.env['HTTP_ACCEPT'] when 'application/json' content_type 'application/json' body(@notes.to_json) else body(haml(:index)) end end def sort_notes(notes) a = [] notes.each do |n| if a.empty? a.push [n.created_at_to_s, [n.body]] else if a.last.first == n.created_at_to_s a.last.last.push(n.body) else a.push [n.created_at_to_s, [n.body]] end end end a end get '/' do @notes = Notable::Note.all(:order => [:created_at.desc], :limit => 20) choose_format end get '/notes' do count = params['num'].to_i if (count < 1) count = 20 end @notes = Notable::Note.all(:order => [:created_at.desc], :limit => count) @title = "Last #{count} Notes" choose_format end get '/search' do @title = "Notes - #{params['q']}" @notes = Notable::Note.all(:body.like => "%#{params['q']}%") choose_format end post '/' do note_body = params['note'] || request.body.read @note = Notable::Note.new(:body => note_body) if @note.save status 201 response['Location'] = link_to body "Note created!\n" else throw :halt, [400, @note.errors.full_messages.join("\n") + "\n"] end end get '/notes.txt' do @notes = sort_notes(Notable::Note.all(:order => [:created_at.desc])) out = [] @notes.each do |day| out << day.first day.last.each do |n| out << " " + n end end content_type :text body out.join("\n") + "\n" end get '/notable.rss' do @last_modified = Notable::Note.max(:created_at) content_type :xml last_modified(@last_modified ? @last_modified : Time.at(0)) @notes = Notable::Note.all(:order => [:created_at.desc], :limit => 20) haml :rss end get '/style.css' do content_type :css last_modified File.mtime(__FILE__) body = <<-eos @import url("http://yui.yahooapis.com/2.6.0/build/reset-fonts-grids/reset-fonts-grids.css"); html { font-size: 62.5%; font-family: "Tahoma"; } body { background-color: #333; height: 100%; position: absolute; left: 0; right: 0; } #doc { background-color: #ddd; bottom: 0; top: 0; position: absolute; margin-left: auto; margin-right: auto; } #container { margin-left: auto; margin-right: auto; min-width: 750px; width: 59.97em; } ul { margin: 20px 20px 20px 20px; } li { display: block; margin-top: 5px; margin-bottom: 5px; padding-bottom: 2px; padding-top: 2px; } em { font-style: italic; color: #fff; } h1 { font-size: 3em; } eos end end
b13fd7e220daf79ce47107db6563066f8b1e5640
[ "Ruby" ]
1
Ruby
vasil/notable
d53e315cc5b4e9d6f6dc52eecc4b04eddf6ef0d0
135f1a0d5f5f565b221d9e26bced36eb88b32574
refs/heads/master
<file_sep>const tape = require('tape') const UTF8 = require('./helpers/messages').UTF8 tape('strings can be utf-8', function (t) { const ex = { foo: 'ビッグデータ「人間の解釈が必要」「量の問題ではない」論と、もう一つのビッグデータ「人間の解釈が必要」「量の問題ではない」論と、もう一つの', bar: 42 } const b1 = UTF8.encode(ex) t.same(UTF8.decode(b1), ex) t.end() }) <file_sep>const protobuf = require('../') const fs = require('fs') const path = require('path') const messages = protobuf(fs.readFileSync(path.join(__dirname, 'bench.proto'))) const TIMES = 1000000 let then = 0 let diff = 0 const run = function (name, encode, decode) { const EXAMPLE = { foo: 'hello', hello: 42, payload: Buffer.from('a'), meh: { b: { tmp: { baz: 1000 } }, lol: 'lol' } } const EXAMPLE_BUFFER = encode(EXAMPLE) let i console.log('Benchmarking %s', name) console.log(' Running object encoding benchmark...') then = Date.now() for (i = 0; i < TIMES; i++) { encode(EXAMPLE) } diff = Date.now() - then console.log(' Encoded %d objects in %d ms (%d enc/s)\n', TIMES, diff, (1000 * TIMES / diff).toFixed(0)) console.log(' Running object decoding benchmark...') then = Date.now() for (i = 0; i < TIMES; i++) { decode(EXAMPLE_BUFFER) } diff = Date.now() - then console.log(' Decoded %d objects in %d ms (%d dec/s)\n', TIMES, diff, (1000 * TIMES / diff).toFixed(0)) console.log(' Running object encoding+decoding benchmark...') then = Date.now() for (i = 0; i < TIMES; i++) { decode(encode(EXAMPLE)) } diff = Date.now() - then console.log(' Encoded+decoded %d objects in %d ms (%d enc+dec/s)\n', TIMES, diff, (1000 * TIMES / diff).toFixed(0)) } run('JSON (baseline)', JSON.stringify, JSON.parse) run('protocol-buffers', messages.Test.encode, messages.Test.decode) <file_sep>const tape = require('tape') const Nested = require('./helpers/messages').Nested tape('nested encode', function (t) { const b1 = Nested.encode({ num: 1, payload: Buffer.from('lol'), meh: { num: 2, payload: Buffer.from('bar') } }) const b2 = Nested.encode({ num: 1, payload: Buffer.from('lol'), meeeh: 42, meh: { num: 2, payload: Buffer.from('bar') } }) t.same(b2, b1) t.end() }) tape('nested encode + decode', function (t) { const b1 = Nested.encode({ num: 1, payload: Buffer.from('lol'), meh: { num: 2, payload: Buffer.from('bar') } }) const o1 = Nested.decode(b1) t.same(o1.num, 1) t.same(o1.payload, Buffer.from('lol')) t.ok(o1.meh, 'has nested property') t.same(o1.meh.num, 2) t.same(o1.meh.payload, Buffer.from('bar')) const b2 = Nested.encode({ num: 1, payload: Buffer.from('lol'), meeeh: 42, meh: { num: 2, payload: Buffer.from('bar') } }) const o2 = Nested.decode(b2) t.same(o2, o1) t.end() }) <file_sep>const tape = require('tape') const Map = require('./helpers/messages').Map tape('map encode + decode', function (t) { const b1 = Map.encode({ foo: { hello: 'world' } }) const o1 = Map.decode(b1) t.same(o1.foo, { hello: 'world' }) const doc = { foo: { hello: 'world', hi: 'verden' } } const b2 = Map.encode(doc) const o2 = Map.decode(b2) t.same(o2, doc) t.end() }) <file_sep>const tape = require('tape') const messages = require('./helpers/messages') tape('enums', function (t) { const e = messages.FOO t.same(e, { A: 1, B: 2 }, 'enum is defined') t.end() }) tape('hex enums', function (t) { const e = messages.FOO_HEX t.same(e, { A: 1, B: 2 }, 'enum is defined using hex') t.end() }) <file_sep>const tape = require('tape') const Defaults = require('./helpers/messages').Defaults tape('defaults decode', function (t) { const o1 = Defaults.decode(Buffer.alloc(0)) // everything default const b2 = Defaults.encode({ num: 10, foos: [1] }) const b3 = Defaults.encode({ num: 10, foo2: 2 }) t.same(Defaults.decode(b3), { num: 10, foo1: 2, foo2: 2, foos: [] }, '1 default') t.same(o1, { num: 42, foo1: 2, foo2: 1, foos: [] }, 'all defaults') t.same(Defaults.decode(b2), { num: 10, foo1: 2, foo2: 1, foos: [1] }, '2 defaults') t.end() }) <file_sep>const tape = require('tape') const Float = require('./helpers/messages').Float tape('float encode + decode', function (t) { const arr = new Float32Array(3) arr[0] = 1.1 arr[1] = 0 arr[2] = -2.3 const obj = { float1: arr[0], float2: arr[1], float3: arr[2] } const b1 = Float.encode(obj) const o1 = Float.decode(b1) t.same(o1, obj) t.end() }) <file_sep>const tape = require('tape') const Packed = require('./helpers/messages').Packed tape('Packed encode', function (t) { const b1 = Packed.encode({ packed: [ 10, 42, 52 ] }) const b2 = Packed.encode({ packed: [ 10, 42, 52 ], meeh: 42 }) t.same(b2, b1) t.end() }) tape('Packed encode + decode', function (t) { const b1 = Packed.encode({ packed: [ 10, 42, 52 ] }) const o1 = Packed.decode(b1) t.same(o1.packed.length, 3) t.same(o1.packed[0], 10) t.same(o1.packed[1], 42) t.same(o1.packed[2], 52) const b2 = Packed.encode({ packed: [ 10, 42, 52 ], meeh: 42 }) const o2 = Packed.decode(b2) t.same(o2, o1) t.end() }) tape('packed message encode', function (t) { const b1 = Packed.encode({ list: [{ num: 1, payload: Buffer.from('lol') }, { num: 2, payload: Buffer.from('lol1') }] }) const b2 = Packed.encode({ list: [{ num: 1, payload: Buffer.from('lol') }, { num: 2, payload: Buffer.from('lol1'), meeeeh: 100 }], meeh: 42 }) t.same(b2, b1) t.end() }) tape('packed message encode + decode', function (t) { const b1 = Packed.encode({ list: [{ num: 1, payload: Buffer.from('lol') }, { num: 2, payload: Buffer.from('lol1') }] }) const o1 = Packed.decode(b1) t.same(o1.list.length, 2) t.same(o1.list[0].num, 1) t.same(o1.list[0].payload, Buffer.from('lol')) t.same(o1.list[1].num, 2) t.same(o1.list[1].payload, Buffer.from('lol1')) const b2 = Packed.encode({ list: [{ num: 1, payload: Buffer.from('lol') }, { num: 2, payload: Buffer.from('lol1'), meeeeh: 100 }], meeh: 42 }) const o2 = Packed.decode(b2) t.same(o2, o1) t.end() }) <file_sep># protocol-buffers [Protocol Buffers](https://developers.google.com/protocol-buffers/) for Node.js ``` npm install protocol-buffers ``` [![build status](https://github.com/mafintosh/protocol-buffers/actions/workflows/test.yml/badge.svg)](https://github.com/mafintosh/protocol-buffers/actions/workflows/test.yml) ![dat](http://img.shields.io/badge/Development%20sponsored%20by-dat-green.svg?style=flat) ## Usage Assuming the following `test.proto` file exists ```proto enum FOO { BAR = 1; } message Test { required float num = 1; required string payload = 2; } message AnotherOne { repeated FOO list = 1; } ``` Use the above proto file to encode/decode messages by doing ``` js var protobuf = require('protocol-buffers') // pass a proto file as a buffer/string or pass a parsed protobuf-schema object var messages = protobuf(fs.readFileSync('test.proto')) var buf = messages.Test.encode({ num: 42, payload: 'hello world' }) console.log(buf) // should print a buffer ``` To decode a message use `Test.decode` ``` js var obj = messages.Test.decode(buf) console.log(obj) // should print an object similar to above ``` Enums are accessed in the same way as messages ``` js var buf = messages.AnotherOne.encode({ list: [ messages.FOO.BAR ] }) ``` Nested emums are accessed as properties on the corresponding message ``` js var buf = message.SomeMessage.encode({ list: [ messages.SomeMessage.NESTED_ENUM.VALUE ] }) ``` See the [Google Protocol Buffers docs](https://developers.google.com/protocol-buffers/) for more information about the available types etc. ## Compile to a file Since v4 you can now compile your schemas to a JavaScript file you can require from Node. This means you do not have runtime parse the schemas, which is useful if using in the browser or on embedded devices. It also makes the dependency footprint a lot smaller. ``` sh # first install the cli tool npm install -g protocol-buffers # compile the schema protocol-buffers test.proto -o messages.js # then install the runtime dependency in the project npm install --save protocol-buffers-encodings ``` That's it! Then in your application you can simply do ``` js var messages = require('./messages') var buf = messages.Test.encode({ num: 42 }) ``` The compilation functionality is also available as a JavaScript API for programmatic use: ``` js var protobuf = require('protocol-buffers') // protobuf.toJS() takes the same arguments as protobuf() var js = protobuf.toJS(fs.readFileSync('test.proto')) fs.writeFileSync('messages.js', js) ``` ## Imports The cli tool supports protocol buffer [imports][] by default. **Currently all imports are treated as public and the public/weak keywords not supported.** To use it programmatically you need to pass-in a `filename` & a `resolveImport` hooks: ```js var protobuf = require('protocol-buffers') var messages = protobuf(null, { filename: 'initial.proto', resolveImport (filename) { // can return a Buffer, String or Schema } }) ``` [imports]: https://developers.google.com/protocol-buffers/docs/proto3#importing_definitions ## Performance This module is fast. It uses code generation to build as fast as possible encoders/decoders for the protobuf schema. You can run the benchmarks yourself by doing `npm run bench`. On my Macbook Air it gives the following results ``` Benchmarking JSON (baseline) Running object encoding benchmark... Encoded 1000000 objects in 2142 ms (466853 enc/s) Running object decoding benchmark... Decoded 1000000 objects in 970 ms (1030928 dec/s) Running object encoding+decoding benchmark... Encoded+decoded 1000000 objects in 3131 ms (319387 enc+dec/s) Benchmarking protocol-buffers Running object encoding benchmark... Encoded 1000000 objects in 2089 ms (478698 enc/s) Running object decoding benchmark... Decoded 1000000 objects in 735 ms (1360544 dec/s) Running object encoding+decoding benchmark... Encoded+decoded 1000000 objects in 2826 ms (353857 enc+dec/s) ``` Note that JSON parsing/serialization in node is a native function that is *really* fast. ## Leveldb encoding compatibility Compiled protocol buffers messages are valid levelup encodings. This means you can pass them as `valueEncoding` and `keyEncoding`. ``` js var level = require('level') var db = level('db') db.put('hello', {payload:'world'}, {valueEncoding:messages.Test}, function(err) { db.get('hello', {valueEncoding:messages.Test}, function(err, message) { console.log(message) }) }) ``` ## License MIT <file_sep>const protobuf = require('./') const fs = require('fs') const path = require('path') const messages = protobuf(fs.readFileSync(path.join(__dirname, 'example.proto'))) const ex = { foo: 'hello world', num: 42 } const buf = messages.Test.encode(ex) console.log('test message', ex) console.log('encoded test message', buf) console.log('encoded test message decoded', messages.Test.decode(buf)) <file_sep>const tape = require('tape') const Repeated = require('./helpers/messages').Repeated tape('repeated encode', function (t) { const b1 = Repeated.encode({ list: [{ num: 1, payload: Buffer.from('lol') }, { num: 2, payload: Buffer.from('lol1') }] }) const b2 = Repeated.encode({ list: [{ num: 1, payload: Buffer.from('lol') }, { num: 2, payload: Buffer.from('lol1'), meeeeh: 100 }], meeh: 42 }) t.same(b2, b1) t.end() }) tape('repeated encode + decode', function (t) { const b1 = Repeated.encode({ list: [{ num: 1, payload: Buffer.from('lol') }, { num: 2, payload: Buffer.from('lol1') }] }) const o1 = Repeated.decode(b1) t.same(o1.list.length, 2) t.same(o1.list[0].num, 1) t.same(o1.list[0].payload, Buffer.from('lol')) t.same(o1.list[1].num, 2) t.same(o1.list[1].payload, Buffer.from('lol1')) const b2 = Repeated.encode({ list: [{ num: 1, payload: Buffer.from('lol') }, { num: 2, payload: Buffer.from('lol1'), meeeeh: 100 }], meeh: 42 }) const o2 = Repeated.decode(b2) t.same(o2, o1) t.end() }) <file_sep>#!/usr/bin/env node const protobuf = require('./') const fs = require('fs') const path = require('path') let filename = null let output = null let watch = false let encodings = null const importPaths = [] // handrolled parser to not introduce minimist as this is used a bunch of prod places // TODO: if this becomes more complicated / has bugs, move to minimist for (let i = 2; i < process.argv.length; i++) { const parts = process.argv[i].split('=') const key = parts[0] const value = parts.slice(1).join('=') if (key[0] !== '-') { filename = path.resolve(key) } else if (key === '--output' || key === '-o' || key === '-wo') { if (key === '-wo') watch = true output = value || process.argv[++i] } else if (key === '--watch' || key === '-w') { watch = true } else if (key === '--encodings' || key === '-e') { encodings = value || process.argv[++i] } else if (key === '--proto_path' || key === '-I') { importPaths.push(path.resolve(value || process.argv[++i])) } } importPaths.push(process.cwd()) if (!filename) { console.error('Usage: protocol-buffers [schema-file.proto] [options]') console.error() console.error(' --output, -o [output-file.js]') console.error(' --watch, -w (recompile on schema change)') console.error(' --proto_path, -I [path-root] # base to lookup imports, multiple supported') console.error() process.exit(1) } filename = path.relative(process.cwd(), filename) if (watch && !output) { console.error('--watch requires --output') process.exit(1) } if (!output) { process.stdout.write(compile()) } else { write() if (watch) fs.watch(filename, write) } function write () { fs.writeFileSync(output, compile()) } function resolveImport (filename) { for (let i = 0; i < importPaths.length; i++) { const importPath = importPaths[i] try { return fs.readFileSync(path.join(importPath, filename)) } catch (err) {} } throw new Error('File "' + filename + '" not found in import path:\n - ' + importPaths.join('\n - ')) } function compile () { return protobuf.toJS(null, { encodings: encodings, filename: filename, resolveImport: resolveImport }) } <file_sep>const tape = require('tape') const Basic = require('./helpers/messages').Basic tape('basic encode', function (t) { const b1 = Basic.encode({ num: 1, payload: Buffer.from('lol') }) const b2 = Basic.encode({ num: 1, payload: Buffer.from('lol'), meeeh: 42 }) const b3 = Basic.encode({ num: 1, payload: 'lol', meeeh: 42 }) t.same(b2, b1) t.same(b3, b1) t.end() }) tape('basic encode + decode', function (t) { const b1 = Basic.encode({ num: 1, payload: Buffer.from('lol') }) const o1 = Basic.decode(b1) t.same(o1.num, 1) t.same(o1.payload, Buffer.from('lol')) const b2 = Basic.encode({ num: 1, payload: Buffer.from('lol'), meeeh: 42 }) const o2 = Basic.decode(b2) t.same(o2, o1) t.end() }) tape('basic encode + decode floats', function (t) { const b1 = Basic.encode({ num: 1.1, payload: Buffer.from('lol') }) const o1 = Basic.decode(b1) t.same(o1.num, 1.1) t.same(o1.payload, Buffer.from('lol')) t.end() }) <file_sep>const path = require('path') const fs = require('fs') if (process.env.COMPILED) module.exports = require('./compiled.js') else module.exports = require('../../')(fs.readFileSync(path.join(__dirname, '../test.proto')))
3b91ef99e7d3819f1bab2698f0d304ee9e8dd9a9
[ "JavaScript", "Markdown" ]
14
JavaScript
mafintosh/protocol-buffers
f95f5c1bb892b655508eadb3a8e5cf8429bc5ae2
ec559b810b777c1107993dc0cb2f26b92345adb3
refs/heads/master
<repo_name>Emam/XML-Databases-and-the-JDBC-Driver<file_sep>/src/Main.java public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Houssainy h = new Houssainy(); HoussainyMaster ho = new HoussainyMaster(); String s = new String(); ahoGalasaKeda lol = new ahoGalasaKeda(); } }
411e13cd4fe0a81b362de2d84fac77ae89971b7e
[ "Java" ]
1
Java
Emam/XML-Databases-and-the-JDBC-Driver
1ba36bf3541b12704e0822f9444080a3c4f473e5
b05e07db891801bdfac31aee64ad2280fa11053d
refs/heads/master
<repo_name>cocopelli/mi-salesforce-symfonybundle<file_sep>/src/SalesForceApiBundle/Api/sfclient.php <?php namespace Mi\SalesforceApiBundle\Api; class sfclient { private $username; private $password; private $token; private $path; private $connection; /** * @var \SforceEnterpriseClient */ private $mySforceConnection = null; public function __construct($username, $password, $token, $path, $mySforceConnection) { $this->username = $username; $this->password = $<PASSWORD>; $this->token = $token; $this->path = $path; $this->mySforceConnection = $mySforceConnection; } private function getConnection() { if (is_null($this->mySforceConnection->getSessionId())) { $this->mySforceConnection->createConnection($this->path); $this->mySforceConnection->login($this->username, $this->password . $this->token); } return $this->mySforceConnection; } public function salesforceConnection($query) { $this->connection = $this->getConnection(); $response = $this->connection->query($query); return $response; } }<file_sep>/src/SalesForceApiBundle/Model/SforceCustomer.php <?php /** * Created by PhpStorm. * User: oezguer * Date: 11.03.16 * Time: 15:15 */ namespace Mi\SalesforceApiBundle\Model; class SforceCustomer { private $creditorId = 0; private $name = ''; private $videoManagerContents = []; private $upgradePrice = 0.0; private $upgradeUnit = 0; /** * @return int */ public function getCreditorId() { return $this->creditorId; } /** * @param int $creditorId */ public function setCreditorId($creditorId) { $this->creditorId = $creditorId; } /** * @return string */ public function getName() { return $this->name; } /** * @param string $name */ public function setName($name) { $this->name = $name; } /** * @return array */ public function getVideoManagerContents() { return $this->videoManagerContents; } /** * @param array $videoManagerContents */ public function setVideoManagerContents($videoManagerContents) { $this->videoManagerContents = $videoManagerContents; } /** * @return float */ public function getUpgradePrice() { return $this->upgradePrice; } /** * @param float $upgradePrice */ public function setUpgradePrice($upgradePrice) { $this->upgradePrice = $upgradePrice; } /** * @return int */ public function getUpgradeUnit() { return $this->upgradeUnit; } /** * @param int $upgradeUnit */ public function setUpgradeUnit($upgradeUnit) { $this->upgradeUnit = $upgradeUnit; } }<file_sep>/src/SalesForceApiBundle/Helper/OwnerObjectBuilder.php <?php namespace Mi\SalesforceApiBundle\Helper; use Mi\SalesforceApiBundle\Model\SforceCustomer; class OwnerObjectBuilder { public function getOwnerObject($sfArray) { $salesforceObject = new SforceCustomer(); if (isset($sfArray->id)) { $salesforceObject->setCreditorId(); } } }<file_sep>/src/SalesForceApiBundle/SalesforceApiBundle.php <?php namespace Mi\SalesforceApiBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class SalesforceApiBundle extends Bundle { }<file_sep>/README.md <<<<<<< HEAD # mi-salesforce-bundle more information coming soon.... ======= # mi-salesforce-symfony-bundle >>>>>>> origin/master <file_sep>/src/SalesForceApiBundle/Model/SforceOpportunity.php <?php namespace Mi\SalesforceApiBundle\Model; class SforceOpportunity { private $title = ''; private $id = ''; private $product = ''; private $phase = ''; private $turnover2016 = ''; private $opportunityOwner = ''; private $closingDate = ''; private $measure2015 = ''; private $measure2016 = ''; private $description = ''; private $storypoints = ''; private $projecttitle = ''; private $reporter = ''; private $duedate = ''; private $company = ''; private $issuetype = ''; /** * @return string */ public function getDescription() { return $this->description; } /** * @return string */ public function getStorypoints() { return $this->storypoints; } /** * @return string */ public function getProjecttitle() { return $this->projecttitle; } /** * @return string */ public function getReporter() { return $this->reporter; } /** * @return string */ public function getDuedate() { return $this->duedate; } /** * @return string */ public function getCompany() { return $this->company; } /** * @return string */ public function getIssuetype() { return $this->issuetype; } /** * @return mixed */ public function getTitle() { return $this->title; } /** * @param mixed $title * @return SforceOpportunity */ public function setTitle($title) { $this->title = $title; return $this; } /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id * @return SforceOpportunity */ public function setId($id) { $this->id = $id; return $this; } /** * @return mixed */ public function getProduct() { return $this->product; } /** * @param mixed $product * @return SforceOpportunity */ public function setProduct($product) { $this->product = $product; return $this; } /** * @return mixed */ public function getPhase() { return $this->phase; } /** * @param mixed $phase * @return SforceOpportunity */ public function setPhase($phase) { $this->phase = $phase; return $this; } /** * @return mixed */ public function getTurnover2016() { return $this->turnover2016; } /** * @param mixed $turnover2016 * @return SforceOpportunity */ public function setTurnover2016($turnover2016) { $this->turnover2016 = $turnover2016; return $this; } /** * @return mixed */ public function getOpportunityOwner() { return $this->opportunityOwner; } /** * @param mixed $opportunityOwner * @return SforceOpportunity */ public function setOpportunityOwner($opportunityOwner) { $this->opportunityOwner = $opportunityOwner; return $this; } /** * @return mixed */ public function getClosingDate() { return $this->closingDate; } /** * @param mixed $closingDate * @return SforceOpportunity */ public function setClosingDate($closingDate) { $this->closingDate = $closingDate; return $this; } /** * @return mixed */ public function getMeasure2015() { return $this->measure2015; } /** * @param mixed $measure2015 * @return SforceOpportunity */ public function setMeasure2015($measure2015) { $this->measure2015 = $measure2015; return $this; } /** * @return mixed */ public function getMeasure2016() { return $this->measure2016; } /** * @param mixed $measure2016 * @return SforceOpportunity */ public function setMeasure2016($measure2016) { $this->measure2016 = $measure2016; return $this; } public function toArray() { return [ 'name' => $this->getTitle(), 'offerId' => $this->getId(), 'product' => $this->getProduct(), 'phase' => $this->getPhase(), 'turnover2016' => $this->getTurnover2016(), 'opportunityOwner' => $this->getOpportunityOwner(), 'closingDate' => $this->getClosingDate(), 'measure2015' => $this->getMeasure2015(), 'measure2016' => $this->getMeasure2016() ]; } }<file_sep>/Tests/Api/SalesforceOpportunitiesTest.php <?php class SalesforceOpportunitiesTest extends \PHPUnit_Framework_TestCase { public $salesforceConnection; public $opportunityTest; public function setup() { $this->salesforceConnection = \Mockery::mock('Mi\SalesforceApiBundle\Api\SFClient'); $this->opportunityTest = new \Mi\SalesforceApiBundle\Api\SalesforceOpportunities($this->salesforceConnection); } /** * @test */ public function getOpportunitiesTester() { $this->salesforceConnection->shouldReceive('salesforceConnection')->once()->andReturn(['name' => 'Deutsche Post DHL']); $this->opportunityTest->getOpportunities('1234'); } /** * @test */ public function getSalesforceObjectTester() { $this->salesforceConnection->shouldReceive('salesforceConnection')->once()->andReturn(['name' => 'Deutsche Post DHL']); $this->opportunityTest->getSalesforceObject('1234'); } }<file_sep>/src/SalesForceApiBundle/Api/SalesforceOpportunities.php <?php namespace Mi\SalesforceApiBundle\Api; use Mi\SalesforceApiBundle\Model; class SalesforceOpportunities { /** * @var sfclient */ private $salesforceConnection; public function __construct($connectionHelper) { $this->salesforceConnection = $connectionHelper; } public function getOpportunities($opportunitieId) { if (preg_match("/^[0-9]{1,10}$/", $opportunitieId)) { $query = "SELECT Name, Angebots_Nr__c, Produkt_dropdown__c, StageName, Umsatz2016__c, Ma_nahme_2015__c, Ma_nahme_2016__c, CloseDate, Owner.Name FROM Opportunity WHERE Angebots_Nr__c = '$opportunitieId'"; return $this->getSalesforceObject($query); } else { throw new \InvalidArgumentException('Ticket-ID validation fail'); } } public function getSalesforceObject($query) { $salesforceResponse = $this->salesforceConnection->salesforceConnection($query); if (empty($salesforceResponse)) { throw new \Exception('Salesforce ID not exict'); } $salesforceObject = new Model\SforceOpportunity(); if (isset($salesforceResponse->records[0]->Name)) { $salesforceObject->setTitle($salesforceResponse->records[0]->Name); } if (isset($salesforceResponse->records[0]->Angebots_Nr__c)) { $salesforceObject->setId($salesforceResponse->records[0]->Angebots_Nr__c); } if (isset($salesforceResponse->records[0]->Produkt_dropdown__c)) { $salesforceObject->setProduct($salesforceResponse->records[0]->Produkt_dropdown__c); } if (isset($salesforceResponse->records[0]->StageName)) { $salesforceObject->setPhase($salesforceResponse->records[0]->StageName); } if (isset($salesforceResponse->records[0]->Umsatz2016__c)) { $salesforceObject->setTurnover2016($salesforceResponse->records[0]->Umsatz2016__c); } if (isset($salesforceResponse->records[0]->Owner->Name)) { $salesforceObject->setOpportunityOwner($salesforceResponse->records[0]->Owner->Name); } if (isset($salesforceResponse->records[0]->Ma_nahme_2015__c)) { $salesforceObject->setMeasure2015($salesforceResponse->records[0]->Ma_nahme_2015__c); } if (isset($salesforceResponse->records[0]->Ma_nahme_2016__c)) { $salesforceObject->setMeasure2016($salesforceResponse->records[0]->Ma_nahme_2016__c); } if (isset($salesforceResponse->records[0]->CloseDate)) { $salesforceObject->setClosingDate($this->dateFormat($salesforceResponse->records[0]->CloseDate)); } return $salesforceObject; } private function dateFormat($date) { list($y, $m, $d) = explode('-', $date); return $d . '.' . $m . '.' . $y; } }
e4568dc5ce78a111b7e472703a5c32c069275b3e
[ "Markdown", "PHP" ]
8
PHP
cocopelli/mi-salesforce-symfonybundle
71e5124c0c5f02ba73077698c965113de71ba2ff
e7600f5e61d63c36f5dc82516f05c77f90093a56
refs/heads/master
<repo_name>amorhe/juewei-new<file_sep>/pages/common/js/ajax.js import { baseUrl } from './baseUrl'; export const ajax = (url, data = {}, method = "POST", newBaseUrl) => { my.showLoading({ content: '加载中...' }); let headers; if (method == "POST") { headers = { 'content-type': 'application/x-www-form-urlencoded' }; } else { headers = { 'content-type': 'application/json' }; } let promise = new Promise(function(resolve, reject) { let url_pages = getCurrentPages() //获取加载的页面 let url_currentPage = url_pages[url_pages.length-1] //获取当前页面的对象 let redir_url = url_currentPage.route //当前页面url my.request({ url: newBaseUrl ? (newBaseUrl + url) : (baseUrl + url), headers, data, method, timeout: 5000, success: (res) => { my.hideLoading(); let rest = { code: (res.code || res.CODE || ""), data: (res.data || res.DATA), msg: (res.msg || res.MESSAGE) } if (rest.code == 0 || rest.code == "A100" || rest.code == 100) { resolve(rest.data); } else if (rest.code == 30106 || rest.code == "A103" || rest.code == 101) { //nologin my.navigateTo({ url: '/pages/login/auth/auth' }); } else { //提示接口的信息,并且跳转刷新页面 reject(my.showToast({ content: rest.msg, success() { my.redirectTo({ url: '/pages/noNet/noNet?redir='+redir_url, // 需要跳转的应用内非 tabBar 的目标页面路径 ,路径后可以带参数。参数规则如下:路径与参数之间使用 }); } })) } }, fail: (err) => { //加入白名单方式 my.hideLoading(); reject(my.showToast({ content: '您的网络有点卡哦,请稍后再试!', success() { my.redirectTo({ url: '/pages/noNet/noNet?redir='+redir_url, // 需要跳转的应用内非 tabBar 的目标页面路径 ,路径后可以带参数。参数规则如下:路径与参数之间使用 }); } })) } }); }) return promise; } //ajax2改良的ajax url为全url export const ajax2 = (url, method = "POST", data = {}) => { let headers; if (method == "POST") { headers = { 'content-type': 'application/x-www-form-urlencoded' }; } else { //get headers = { 'content-type': 'application/json' }; } let promise = new Promise(function(resolve, reject) { let url_pages = getCurrentPages() //获取加载的页面 let url_currentPage = url_pages[url_pages.length-1] //获取当前页面的对象 let redir_url = url_currentPage.route //当前页面url my.request({ url: url, headers, data, method, timeout: 5000, success: (res) => { let rest = { code: (res.code || res.CODE || ""), data: (res.data || res.DATA), msg: (res.msg || res.MESSAGE) } if (rest.code == 0 || rest.code == "A100" || rest.code == 100) { resolve(rest.data); } else if (rest.code == 30106 || rest.code == "A103" || rest.code == 101) { //用户未登录状态 统一处理 //nologin my.navigateTo({ url: '/pages/login/auth/auth' }); } else { //提示接口的信息,提示错误 reject(my.showToast({ content: rest.msg, success() { my.redirectTo({ url: '/pages/noNet/noNet?redir='+redir_url, // 需要跳转的应用内非 tabBar 的目标页面路径 ,路径后可以带参数。参数规则如下:路径与参数之间使用 }); } })) } }, fail: (err) => { //加入白名单方式 my.hideLoading(); reject(my.showToast({ content: '您的网络有点卡哦,请稍后再试!', success() { my.redirectTo({ url: '/pages/noNet/noNet?redir='+redir_url, // 需要跳转的应用内非 tabBar 的目标页面路径 ,路径后可以带参数。参数规则如下:路径与参数之间使用 }); } })) } }); }) return promise; } <file_sep>/pages/components/shopcartModel/shopcartModel.js import { imageUrl, jsonUrl, myGet, mySet } from '../../common/js/baseUrl' import { compare, upformId } from '../../common/js/time' var app = getApp(); Component({ data: { showShopcar: false, //购物车 mask: false, //遮罩 imageUrl, modalShow: false, //弹框 mask1: false, send_price: "", //起送费 dispatch_price: '', // 配送费 isType: '', content: '', otherGoods: [], confirmButtonText: '', cancelButtonText: '', type: '', btnClick: true, freeId: false, // 是否有包邮活动 isTake: false, isOpen: '' }, props: { shopcartAll: [], shopcartNum: 0, priceAll: 0, activityText: '', freeText: '', mask1:false, onOpenShopcar:(data) => {console.log(data)} }, //组件创建时触发 onInit() { }, //组件创建时和更新前触发 deriveDataFromProps(nextProps) { // 判断是不是起送 if (app.globalData.type == 1) { this.setData({ type: 1, isTake: true }) } else { this.setData({ type: 2, isTake: false }) } if (app.globalData.freeId) { this.setData({ freeId: true }) } else { this.setData({ freeId: false }) } this.setData({ isOpen: app.globalData.isOpen }) //更新起送价 this.getSendPrice(); }, //组件创建完毕后触发 didMount() { this.getSendPrice(); }, //组件更新完毕触发 didUpdate() { }, //组件删除时触发 didUnmount() { }, methods: { // 打开购物车 openShopcart() { this.setData({ showShopcar: true, mask1: true }) this.props.onOpenShopcar({ detail: true }); }, // 隐藏购物车 hiddenShopcart() { this.setData({ showShopcar: false, mask1: false }) this.props.onOpenShopcar({ detail: false }); }, // 清空购物车 clearShopcart() { this.setData({ showShopcar: false, mask1: false, mask: true, modalShow: true, isType: 'clearShopcart', content: '是否清空购物车', confirmButtonText: '确认', cancelButtonText: '取消' }) this.props.onOpenShopcar({ detail: false }); }, onCounterPlusOne(data) { this.setData({ mask: data.mask, modalShow: data.modalShow }) if (data.isType == 'clearShopcart' && data.type == 1) { // 清空购物车 app.globalData.goodsBuy = []; my.removeStorageSync({ key: 'goodsList' }); this.changeshopcart({}, [], 0, 0, 0, 0); } if (data.isType == 'checkshopcart' && data.type == 0 && this.props.shopcartNum > 0) { app.globalData.goodsBuy = this.props.shopcartAll; my.navigateTo({ url: '/pages/home/orderform/orderform' }) } }, changeshopcart(goodlist, shopcartAll, priceAll, shopcartNum, priceFree, repurse_price) { let data = { goodlist, shopcartAll, priceAll, shopcartNum, priceFree, repurse_price } //运行父级函数,向上传递更新的参数 this.props.onChangeShopcart({ detail: data }); }, addshopcart(e) { let goodlist = myGet('goodsList') || {}; let goods_code = e.currentTarget.dataset.goods_code; let goods_format = e.currentTarget.dataset.goods_format goodlist[`${goods_code}_${goods_format}`].num += 1; let shopcartAll = [], priceAll = 0, shopcartNum = 0, priceFree = 0, repurse_price = 0; for (let keys in goodlist) { if (!goodlist[keys].goods_price) { continue; } if (e.currentTarget.dataset.goods_discount) { if (goodlist[keys].goods_order_limit != null && goodlist[`${e.currentTarget.dataset.goods_code}_${goods_format}`].num > e.currentTarget.dataset.goods_order_limit) { my.showToast({ content: `折扣商品限购${e.currentTarget.dataset.goods_order_limit}${e.currentTarget.dataset.goods_unit},超过${e.currentTarget.dataset.goods_order_limit}${e.currentTarget.dataset.goods_unit}恢复原价` }) } } if (goodlist[keys].goods_order_limit != null && goodlist[keys].num > goodlist[keys].goods_order_limit) { priceAll += parseInt(goodlist[keys].goods_price) * goodlist[keys].goods_order_limit + (goodlist[keys].num - goodlist[keys].goods_order_limit) * goodlist[keys].goods_original_price; //套餐不算在内 if (keys.indexOf('PKG') == -1) { priceFree += (goodlist[keys].num - goodlist[keys].goods_order_limit) * goodlist[keys].goods_original_price; } } else if (goodlist[keys].goods_price && goodlist[keys].num) { priceAll += parseInt(goodlist[keys].goods_price) * goodlist[keys].num; } else { } //计算包邮价格 if (!goodlist[keys].goods_discount) { priceFree += goodlist[keys].goods_price * goodlist[keys].num; } // 计算可换购商品价格 if (app.globalData.repurseGoods && app.globalData.repurseGoods.length > 0) { if (goodlist[keys].huangou && goodlist[keys].goods_price && goodlist[keys].num) { repurse_price += parseInt(goodlist[keys].goods_price) * goodlist[keys].num; } } else { repurse_price = parseInt(priceAll) } shopcartAll.push(goodlist[keys]); shopcartNum += goodlist[keys].num } let arr = shopcartAll.filter(item => item.goods_code == goods_code) for (let item of arr) { goodlist[`${item.goods_code}_${item.goods_format}`].sumnum += 1; } this.changeshopcart(goodlist, shopcartAll, priceAll, shopcartNum, priceFree, repurse_price) mySet('goodsList', goodlist) }, reduceshopcart(e) { let code = e.currentTarget.dataset.goods_code; let format = e.currentTarget.dataset.goods_format let goodlist = myGet('goodsList') || {}; goodlist[`${code}_${format}`].num -= 1; // 删除 let shopcartAll = [], priceAll = 0, shopcartNum = 0, priceFree = 0, repurse_price = 0, newGoodlist = {}; let arr = this.props.shopcartAll.filter(item => item.goods_code == code) for (let item of arr) { goodlist[`${item.goods_code}_${item.goods_format}`].sumnum -= 1; } for (let keys in goodlist) { if (!goodlist[keys].goods_price) { continue; } if (goodlist[keys].goods_order_limit && goodlist[keys].num > goodlist[keys].goods_order_limit) { priceAll += parseInt(goodlist[keys].goods_price) * goodlist[keys].goods_order_limit + (goodlist[keys].num - goodlist[keys].goods_order_limit) * goodlist[keys].goods_original_price; //套餐不算在内 if (keys.indexOf('PKG') == -1) { priceFree += (goodlist[keys].num - goodlist[keys].goods_order_limit) * goodlist[keys].goods_original_price; } } else if (goodlist[keys].goods_price && goodlist[keys].num) { priceAll += parseInt(goodlist[keys].goods_price) * goodlist[keys].num; } else { } //计算包邮价格 if (!goodlist[keys].goods_discount) { priceFree += goodlist[keys].goods_price * goodlist[keys].num; } // 计算可换购商品价格 if (app.globalData.repurseGoods && app.globalData.repurseGoods.length > 0) { if (goodlist[keys].huangou && goodlist[keys].goods_price && goodlist[keys].num) { repurse_price += parseInt(goodlist[keys].goods_price) * goodlist[keys].num; } } else { repurse_price = parseInt(priceAll) } if (goodlist[keys].num > 0) { newGoodlist[keys] = goodlist[keys]; shopcartAll.push(goodlist[keys]); shopcartNum += goodlist[keys].num } } this.changeshopcart(newGoodlist, shopcartAll, priceAll, shopcartNum, priceFree, repurse_price); mySet('goodsList', newGoodlist) // 购物车全部为空 if (Object.keys(newGoodlist).length == 0) { this.setData({ showShopcar: false, mask1: false }) } }, // 去结算 goOrderSubmit() { // js节流防短时间重复点击 if (this.data.btnClick == false) { return } this.setData({ btnClick: false }) setTimeout(() => { this.setData({ btnClick: true }) }, 1000) //  数据加载完成前防止点击 if (!app.globalData.goodsArr) { return } // 未登录 if (!my.getStorageSync({ key: 'user_id' }) || !my.getStorageSync({ key: 'user_id' }).data) { my.navigateTo({ url: '/pages/login/auth/auth?next=true' }) return } // 未选择商品 if (this.props.shopcartGoods) { my.showToast({ content: "请至少选择一件商品" }); return } let goodsList = my.getStorageSync({ key: 'goodsList', // 缓存数据的key }).data; let num = 0, // 购物车总数量 shopcartAll = [], // 购物车数组 priceAll = 0, // 总价 shopcartNum = 0, // 购物车总数量 priceFree = 0, // 满多少包邮 shopcartObj = {}, //商品列表 repurse_price = 0, // 换购活动提示价 snum = 0, DIS = app.globalData.DIS || [], PKG = app.globalData.PKG || [], isfresh1 = false, //折扣商品价格更新 isfresh2 = false, //套餐商品价格更新 isfresh3 = false; //普通商品价格更新 if (goodsList == null) return; // 判断购物车商品是否在当前门店里 for (let val in goodsList) { if (goodsList[val].goods_discount) { // 折扣 if (goodsList[val].goods_code.indexOf('PKG') == -1) { for (let ott of DIS) { for (let fn of ott.goods_format) { if (val == `${fn.goods_activity_code}_${fn.type}`) { shopcartObj[val] = goodsList[val]; // 判断购物车商品价格更新 if (parseInt(goodsList[val].goods_price) != parseInt(fn.goods_price)) { snum += shopcartObj[val].num; shopcartObj[val].goods_price = fn.goods_price; isfresh1 = true; } } } } } else { // 套餐 for (let ott of PKG) { for (let fn of ott.goods_format) { if (val == `${fn.goods_activity_code}_${(fn.type ? fn.type : '')}`) { shopcartObj[val] = goodsList[val]; // 判断购物车商品价格更新 if (parseInt(goodsList[val].goods_price) != parseInt(fn.goods_price)) { snum += shopcartObj[val].num; shopcartObj[val].goods_price = fn.goods_price; isfresh2 = true; } } } } } } else { // 普通不带折扣的 for (let value of app.globalData.goodsCommon) { for (let fn of value.goods_format) { // 在门店 if (val == `${value.goods_channel}${value.goods_type}${value.company_goods_id}_${fn.type}`) { shopcartObj[val] = goodsList[val]; // 判断购物车商品价格更新 if (parseInt(goodsList[val].goods_price) != parseInt(fn.goods_price)) { snum += shopcartObj[val].num; shopcartObj[val].goods_price = fn.goods_price; isfresh3 = true; } } } } } num += goodsList[val].num; // 计算购物车是否在门店内后筛选剩余商品价格 if (shopcartObj[val]) {//判断商品是否存在 if (shopcartObj[val].goods_discount && shopcartObj[val].num > shopcartObj[val].goods_order_limit) { priceAll += parseInt(shopcartObj[val].goods_price) * shopcartObj[val].goods_order_limit + (shopcartObj[val].num - goodsList[val].goods_order_limit) * shopcartObj[val].goods_original_price; } else { priceAll += parseInt(shopcartObj[val].goods_price) * shopcartObj[val].num; } // 计算包邮价格 if (!shopcartObj[val].goods_discount) { priceFree += parseInt(shopcartObj[val].goods_price) * shopcartObj[val].num; }else{ } //计算换购价格 if (app.globalData.repurseGoods && app.globalData.repurseGoods.length > 0) { if (shopcartObj[val].huangou && shopcartObj[val].goods_price && shopcartObj[val].num) { repurse_price += parseInt(shopcartObj[val].goods_price) * shopcartObj[val].num; } }else{ repurse_price = parseInt(priceAll) } shopcartAll.push(shopcartObj[val]); shopcartNum += shopcartObj[val].num; } } // 购物车筛选后剩余数量 shopcartNum = Object.entries(shopcartObj).reduce((pre, cur) => { const { num } = cur[1] return pre + num }, 0) this.changeshopcart(shopcartObj, shopcartAll, priceAll, shopcartNum, priceFree, repurse_price); my.setStorageSync({ key: 'goodsList', data: shopcartObj }) app.globalData.goodsBuy = this.props.shopcartAll; if (num - shopcartNum > 0 && snum > 0) { return this.setData({ showShopcar: false, mask1: false, mask: true, modalShow: true, isType: 'checkshopcart', content: `有${num - shopcartNum}个商品已失效,${snum}个商品价格已更新,是否继续下单`, confirmButtonText: '重新选择', cancelButtonText: '继续结算', btnClick: true }) } else if (num - shopcartNum > 0 && snum == 0) { return this.setData({ showShopcar: false, mask1: false, mask: true, modalShow: true, isType: 'checkshopcart', content: `有${num - shopcartNum}个商品已失效,是否继续下单`, confirmButtonText: '重新选择', cancelButtonText: '继续结算', btnClick: true }) } else if (num - shopcartNum == 0 && snum > 0 && (isfresh1 || isfresh2 || isfresh3)) { //折扣,套餐,普通商品 return this.setData({ showShopcar: false, mask1: false, mask: true, modalShow: true, isType: 'checkshopcart', content: `有${snum}个商品价格已更新,是否继续下单`, confirmButtonText: '重新选择', cancelButtonText: '继续结算', btnClick: true }) } my.hideLoading(); app.globalData.coupon_code=''; //默认是空 my.navigateTo({ url: '/pages/home/orderform/orderform' }) }, // 获取起送价格 getSendPrice() { const timestamp = new Date().getTime(); let opencity = (my.getStorageSync({ key: 'opencity' }).data || null); if (!app.globalData.position.cityAdcode || app.globalData.position.cityAdcode == '') { return; } if (opencity) { this.setData({ send_price: opencity[app.globalData.position.cityAdcode].shop_send_price, dispatch_price: opencity[app.globalData.position.cityAdcode].shop_dispatch_price }); //存储一个起送起购价格 my.setStorageSync({ key: 'send_price', data: opencity[app.globalData.position.cityAdcode].shop_send_price }); //存储一个起送起购价格 my.setStorageSync({ key: 'dispatch_price', data: opencity[app.globalData.position.cityAdcode].shop_dispatch_price }); } else { console.log('opencity'); my.request({ url: `${jsonUrl}/api/shop/open-city.json?v=${timestamp}`, success: (res) => { //app.globalData.position.cityAdcode这个参数在手动修改地址的时候缺失。 //这里采用通过门店的具体地址来确定起送价地址 if(res.data.data[app.globalData.position.cityAdcode] && res.data.data[app.globalData.position.cityAdcode].shop_send_price){ this.setData({ send_price: res.data.data[app.globalData.position.cityAdcode].shop_send_price, dispatch_price: res.data.data[app.globalData.position.cityAdcode].shop_dispatch_price }) //存储一个起送起购价格 my.setStorageSync({ key: 'send_price', data: res.data.data[app.globalData.position.cityAdcode].shop_send_price }); //存储一个起送起购价格 my.setStorageSync({ key: 'dispatch_price', data: res.data.data[app.globalData.position.cityAdcode].shop_dispatch_price }); } // my.setStorageSync({ key: 'opencity', data: res.data.data }); }, fail:(e=>{ //出现获取错误 }) }); } }, // 上传模版消息 onSubmit(e) { upformId(e.detail.formId); }, touchstart() { return false } } }); <file_sep>/package_my/pages/myaddress/addaddress/addaddress.js import { imageUrl, ak, geotable_id } from '../../../../pages/common/js/baseUrl' import { getRegion } from '../../../../pages/common/js/li-ajax' import { addressCreate, addressinfo, updateaddress, deleteaddress } from '../../../../pages/common/js/address' import { bd_encrypt } from '../../../../pages/common/js/map' let region = [] var app = getApp() Page({ data: { imageUrl, modalShow: false, // 弹窗 // 地址 name: '', sex: 1, phone: '', address: '', labelList: [ { name: '家', type: 1 }, { name: '公司', type: 2 }, { name: '学校', type: 3 } ], curLabel: 0, selectAddress: false, addressList: region, provinceList: [], cityList: [], countryList: [], defaultAddress: [0, 0, 0], shop_id: '', addressId: '', order: 0, _sid: '', addressdetail: '', modalidShow: false, // 无门店, detailAdd: '', clickadd: false, city: '', show_name_clear:false, show_phone_clear:false, show_addressdetail_clear:false }, onShow() { if (app.globalData.addAddressInfo) { let addAddressInfo = app.globalData.addAddressInfo; //这里不能用全局变量,需要重新获取 this.setData({ province: addAddressInfo.province, city: addAddressInfo.city, district: addAddressInfo.area || addAddressInfo.district, longitude: addAddressInfo.location.lng,// 百度的坐标 latitude: addAddressInfo.location.lat,// 百度的坐标 map_address: addAddressInfo.name || addAddressInfo.address || addAddressInfo.addr, detailAdd: addAddressInfo.address || addAddressInfo.addr }) my.request({ url: 'https://api.map.baidu.com/geosearch/v3/nearby?ak=' + ak + '&geotable_id=' + geotable_id + '&location=' + addAddressInfo.location.lng + ',' + addAddressInfo.location.lat + '&radius=3000', success: (res) => { var arr = [] res.data.contents.forEach(item => { arr.push(item.shop_id) }) this.data.shop_id = arr.join(',') if (this.data.shop_id === '') { this.setData({ modalidShow: true }) } }, }); }else{ this.getLocation() } }, onhide() { // 退出清空addAddressInfo app.globalData.addAddressInfo = null; }, async onLoad(e) { var _sid = my.getStorageSync({ key: '_sid' }).data; this.data._sid = _sid if (e.Id) { this.data.addressId = e.Id this.getInfo(e.Id) } else {// 新建地址 this.data.addressId = '' this.getLocation() } if (e.order) { this.data.order = 1 } region = await getRegion() this.getAddressList() }, getLocation() { var that = this my.getLocation({ type: 3, success(res) { var address = res.pois[0].name ? res.pois[0].name : res.pois[0].address // 获取到的是高德的经纬度,要转换为百度经纬度 let map_position = bd_encrypt(res.longitude, res.latitude); my.request({ url: 'https://api.map.baidu.com/geosearch/v3/nearby?ak=' + ak + '&geotable_id=' + geotable_id + '&location=' + res.longitude + ',' + res.latitude + '&radius=3000', success: (res) => { var arr = [];// 门店id数组 res.data.contents.forEach(item => { arr.push(item.shop_id) }) that.data.shop_id = arr.join(','); // 周边无可用门店时弹窗提示 if (that.data.shop_id === '') { this.setData({ modalidShow: true }) } }, }); // 写入地址信息并渲染,map_address显示地址名称 that.setData({ province: res.province, city: res.city, district: res.district, longitude: map_position.bd_lng, latitude: map_position.bd_lat, map_address: address, detailAdd: res.province + res.city + res.district + res.streetNumber.street + res.streetNumber.number }) }, fail() { that.setData({ address: '定位失败' }) }, }) }, // 地址详情 getInfo(id) { var data = { _sid: this.data._sid, address_id: id } addressinfo(data).then(res => { var lbsArr = res.data.user_address_lbs_baidu.split(',') var data = res.data this.setData({ sex: data.user_address_sex, name: data.user_address_name, // 收货人姓名 phone: data.user_address_phone, // 手机号 map_address: data.user_address_map_addr, // 定位地址 address: data.user_address_detail_address, // 收货地址 detailAdd: data.user_address_detail_address, province: data.province,// 省 city: data.city, // 市 district: data.district, // 区 longitude: lbsArr[0], // 经度 latitude: lbsArr[1], // 纬度 shop_id: '', // 门店 addressdetail: data.user_address_address, // 地址详情 curLabel: data.tag }) }) }, // 选择地址 chooseLocation() { var that = this my.navigateTo({ url: '/package_my/pages/myaddress/selectaddress/selectaddress?address=' }); }, getAddressList() { let [curProvince, curCity, curCountry] = this.data.defaultAddress; let provinceList = region.map(({ addrid, name }) => ({ addrid, name })) let cityList = region[curProvince].sub let countryList = cityList[curCity].sub this.setData({ provinceList, cityList, countryList }) }, changeAddress(e) { let [curProvince, curCity, curCountry] = this.data.defaultAddress; let cur = e.detail.value if (cur[0] != curProvince) { cur = [cur[0], 0, 0] } if (cur[1] != curCity) { cur = [cur[0], cur[1], 0] } this.setData({ defaultAddress: cur, address: region[cur[0]].name + ' ' + region[cur[0]].sub[cur[1]].name + ' ' + ((region[cur[0]].sub[cur[1]].sub[cur[2]] && region[cur[0]].sub[cur[1]].sub[cur[2]].name) || ' ') }, () => this.getAddressList() ) }, showSelectAddress() { this.setData({ selectAddress: true }) }, hideSelectAddress() { this.setData({ selectAddress: false }) }, // 地址 changeSex() { const { sex } = this.data; this.setData({ sex: sex === 0 ? 1 : 0 }) }, changeCur(e) { let curLabel = e.currentTarget.dataset.type this.setData({ curLabel }) }, //用户输入校验 handelChange(e) { let { key } = e.currentTarget.dataset; let reg_name = /^[a-zA-Z0-9_\u4e00-\u9fa5\s]{0,20}$/; let reg_phone = /^\d{0,11}$/; let value =e.detail.value; switch(key){ case 'name': if(reg_name.test(value)){ this.setData({ name: value }); }else{ this.setData({ name: this.data.name }); } break; case 'phone': this.setData({ phone: value }) break; case 'addressdetail': this.setData({ addressdetail: value }) break; default: this.setData({ name:'', phone:'', addressdetail: '' }) break; } }, //清空文字 closeImg(e){ let { key } = e.currentTarget.dataset; switch(key){ case 'name': this.setData({ name: '' }) break; case 'phone': this.setData({ phone: '' }) break; case 'addressdetail': this.setData({ addressdetail: '' }) break; default: break; } }, //获取焦点,显示清空按钮 showclear(e){ let d = e.currentTarget.dataset.key; let v = e.detail.value; let show_name_clear=false; let show_phone_clear=false; let show_addressdetail_clear=false; switch (d) { case 'name': show_name_clear=true; break; case 'phone': show_phone_clear=true; break; case 'addressdetail': show_addressdetail_clear=true; break; } this.setData({ show_name_clear, show_phone_clear, show_addressdetail_clear }) }, //失去焦点,隐藏清空按钮 hideclear(e){ let d = e.currentTarget.dataset.key; switch (d) { case 'name': this.setData({ show_name_clear: false }) break; case 'phone': this.setData({ show_phone_clear:false }) break; case 'addressdetail': this.setData({ show_addressdetail_clear:false }) break; } }, modalidShoFN() { this.setData({ modalidShow: false }) }, //保存地址 Addaddress() { var that = this if (this.data.name === '') { my.showToast({ type: 'none', content: '请输入联系人', duration: 1000 }); return } if (/[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im.test(this.data.name)) { my.showToast({ type: 'none', content: '联系人包含非法字符', duration: 1000 }); return } if (/^1\d{10}$/.test(this.data.phone)) { } else if (this.data.phone === '') { my.showToast({ type: 'none', content: '请填写电话', duration: 1000 }); return } else { my.showToast({ type: 'none', content: '请输入正确手机号', duration: 1000 }); return } if (this.data.addressdetail.replace(/\s+/g, "") == '') { my.showToast({ type: 'none', content: '请输入门牌号', duration: 1000 }); return } //判断地址是否有门店 if (this.data.shop_id==='') { this.setData({ modalidShow: true }) return } if (this.data.clickadd) { return } this.setData({ clickadd: true }) if (this.data.addressId) { var data = { _sid: this.data._sid, address_id: this.data.addressId, sex: this.data.sex, name: this.data.name.trim(), // 收货人姓名 phone: this.data.phone, // 手机号 map_address: this.data.map_address, // 定位地址 address: this.data.addressdetail, // 收货地址 province: this.data.province,// 省 city: this.data.city, // 市 district: this.data.district, // 区 longitude: this.data.longitude, // 经度 latitude: this.data.latitude, // 纬度 detail_address: this.data.detailAdd, // 地址详情 check_edit: false, tag: this.data.curLabel, // 地址标签 } updateaddress(data).then(res => { that.setData({ clickadd: false }) if (res.code == 0) { // 清空app.globalData.addAddressInfo防止错误使用 app.globalData.addAddressInfo = null; my.navigateBack({ url: '/package_my/pages/myaddress/myaddress' }); } else { my.showToast({ type: 'none', content: res.msg, duration: 1000 }); } }) } else { // 添加 var data = { _sid: this.data._sid, sex: this.data.sex, name: this.data.name, // 收货人姓名 phone: this.data.phone, // 手机号 map_address: this.data.map_address, // 定位地址 detail_address: this.data.detailAdd, // 地址详情 province: this.data.province,// 省 city: this.data.city, // 市 district: this.data.district, // 区 longitude: this.data.longitude, // 经度 latitude: this.data.latitude, // 纬度 shop_id: this.data.shop_id, // 门店 address: this.data.addressdetail, // 收货地址 tag: this.data.curLabel, // 地址标签 } addressCreate(data).then(res => { that.setData({ clickadd: false }) if (res.code == 0) { if (this.data.order == 1) { // 清空app.globalData.addAddressInfo防止错误使用 app.globalData.addAddressInfo = null; my.navigateBack({ url: '/pages/home/orderform/selectaddress/selectaddress' }) } else { my.navigateBack({ url: '/package_my/pages/myaddress/myaddress' }); } } else { my.showToast({ type: 'none', content: res.msg, duration: 1000 }); } }) } }, // 删除地址 modalShowFN() { this.setData({ modalShow: true }) }, modalhideFN() { this.setData({ modalShow: false }) }, rmaddress() { var data = { _sid: this.data._sid, address_id: this.data.addressId } deleteaddress(data).then(res => { if (res.code == 0) { this.setData({ modalShow: false }) my.navigateBack({ url: '/package_my/pages/myaddress/myaddress' }); } else { my.showToast({ type: 'none', content: res.msg, duration: 1000 }); } }) }, }); <file_sep>/pages/common/js/login.js import {ajax} from './ajax'; const loginPage = { loginByAuth: '/juewei-api/alimini/loginByAuth', //授权登录 loginByAliUid: '/juewei-api/alimini/loginByAliUid', //用户自动登录 getuserInfo: '/juewei-api/alimini/getUserInfo', //获取用户信息 sendCode:'/juewei-api/alimini/sendCode', // 获取短信验证码 captcha:'/juewei-api/user/captcha', // 获取图片验证码 loginByPhone:'/juewei-api/alimini/loginByPhone', // 手机号登录 LoginOut:'/juewei-api/alimini/LoginOut', // 退出登录 decryptPhone:'/juewei-api/alimini/decryptPhone', // 解密手机 } export const loginByAliUid = (auth_code,nick_name,head_img,_sid) => ajax(loginPage.loginByAliUid,{auth_code,nick_name,head_img,_sid}); export const getuserInfo = (_sid) => ajax(loginPage.getuserInfo,{_sid}); export const loginByAuth = (ali_uid,phone,nick_name,head_img,_sid) => ajax(loginPage.loginByAuth,{ali_uid,phone,nick_name,head_img,_sid}); export const sendCode = (data) => ajax(loginPage.sendCode,data); export const loginByPhone = (data) => ajax(loginPage.loginByPhone,data); export const LoginOut = (_sid) => ajax(loginPage.LoginOut,{_sid}); export const decryptPhone = (data) => ajax(loginPage.decryptPhone,data);<file_sep>/pages/home/goodslist/goodsdetail/goodsdetail.js import { imageUrl, imageUrl2, imageUrl3, img_url, myGet, mySet } from '../../../common/js/baseUrl' import { commentList, DispatchCommentList } from '../../../common/js/home' var app = getApp(); Page({ data: { activeTab: 0, tabActive: 0, tabs: [ { title: '商品简介' }, { title: '商品详情' } ], tabsT: [ { title: '商品口味' }, { title: '配送服务' } ], imageUrl, imageUrl2, imageUrl3, img_url, // 评论 commentArr: {},//商品评价 key: '', index: '', dispatchArr: {},//配送评论 maskView: false, goodsItem: {}, shopcartList: {}, shopcartAll: [], priceAll: 0, goodsLast: '', shopcartNum: 0, goodsKey: '', activityText: '', pagenum: 1, pagesize: 10, freeText: '', freeMoney: 0, goodsInfo: {}, repurse_price: 0, shopcarShow:false }, onLoad: function(e) { my.pageScrollTo({ scrollTop: 0, duration: 0 }) this.setData({ goods_code: e.goods_code }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function() { my.pageScrollTo({ scrollTop: 0, duration: 0 }) }, onShow(e) { my.pageScrollTo({ scrollTop: 0, duration: 0 }) let isPhone = app.globalData.isIphoneX; let num = 0, // 购物车总数量 shopcartAll = [], // 购物车数组 priceAll = 0, // 总价 shopcartNum = 0, // 购物车总数量 priceFree = 0, // 满多少包邮 shopcartObj = {}, //商品列表 repurse_price = 0, // 换购活动提示价 snum = 0, goodsInfo = {}, goods = app.globalData.goodsArr, shop_id = myGet('shop_id') || {}, DIS = app.globalData.DIS, PKG = app.globalData.PKG, goodsList = myGet('goodsList'); if (goodsList == undefined) { shopcartAll = []; shopcartNum = 0; priceFree = 0; priceAll = 0; repurse_price = 0 }; for (let value of goods) { // 折扣套餐爆款 if (value.goods_discount_user_limit || value.goods_discount_id) { if (value.goods_format[0].goods_activity_code == this.data.goods_code) { goodsInfo = value; } } else { if (value.goods_channel + value.goods_type + value.company_goods_id == this.data.goods_code) { goodsInfo = value; } } } // 判断购物车商品是否在当前门店里 for (let val in goodsList) { if (goodsList[val].goods_discount) { if (DIS != null || PKG != null) { // 折扣 if (goodsList[val].goods_code.indexOf('PKG') == -1 && DIS != null) { for (let ott of DIS) { for (let fn of ott.goods_format) { if (val == `${fn.goods_activity_code}_${fn.type}`) { shopcartObj[val] = goodsList[val]; // 判断购物车商品价格更新 if (goodsList[val].goods_price != parseInt(fn.goods_price)) { snum += shopcartObj[val].num; shopcartObj[val].goods_price = parseInt(fn.goods_price) } } } } } else { // 套餐 if (PKG != null) { for (let ott of PKG) { for (let fn of ott.goods_format) { if (val == `${fn.goods_activity_code}_${fn.type != undefined ? fn.type : ''}`) { shopcartObj[val] = goodsList[val]; // 判断购物车商品价格更新 if (goodsList[val].goods_price != parseInt(fn.goods_price)) { snum += shopcartObj[val].num; shopcartObj[val].goods_price = parseInt(fn.goods_price) } } } } } } } } else { // 普通不带折扣的 if (app.globalData.goodsCommon) { for (let value of app.globalData.goodsCommon) { for (let fn of value.goods_format) { // 在门店 if (val == `${value.goods_channel}${value.goods_type}${value.company_goods_id}_${fn.type}`) { shopcartObj[val] = goodsList[val]; // 判断购物车商品价格更新 if (goodsList[val].goods_price != parseInt(fn.goods_price)) { snum += shopcartObj[val].num; shopcartObj[val].goods_price = parseInt(fn.goods_price) } } } } } } num += goodsList[val].num; // 计算购物车是否在门店内后筛选剩余商品价格 if (shopcartObj[val]) { //判断商品是否存在 if (shopcartObj[val].goods_discount && shopcartObj[val].num > shopcartObj[val].goods_order_limit) { priceAll += parseInt(shopcartObj[val].goods_price) * shopcartObj[val].goods_order_limit + (shopcartObj[val].num - goodsList[val].goods_order_limit) * shopcartObj[val].goods_original_price; priceFree += (shopcartObj[val].num - shopcartObj[val].goods_order_limit) * shopcartObj[val].goods_original_price; } else if (shopcartObj[val].goods_price && shopcartObj[val].num) { priceAll += parseInt(shopcartObj[val].goods_price) * shopcartObj[val].num; } else { } // 计算包邮商品价格 if (!shopcartObj[val].goods_discount) { priceFree += shopcartObj[val].goods_price * shopcartObj[val].num; } // 计算可换购商品价格 if (app.globalData.repurseGoods && app.globalData.repurseGoods.length > 0) { if (shopcartObj[val].huangou && shopcartObj[val].goods_price && shopcartObj[val].num) { repurse_price += parseInt(shopcartObj[val].goods_price) * shopcartObj[val].num; } } else { repurse_price = parseInt(priceAll) } shopcartAll.push(shopcartObj[val]); shopcartNum += shopcartObj[val].num; } } // 购物车活动提示 if (!myGet('goodsList')) { let data = {} this.onchangeShopcart(data); } else { this.shopcartPrompt(app.globalData.fullActivity, priceFree, repurse_price) } this.setData({ shopcartList: shopcartObj, priceAll, shopcartAll, shopcartNum, priceFree, repurse_price, goodsInfo, freeMoney: app.globalData.freeMoney || -1, repurse_price, freeId: app.globalData.freeId, type: app.globalData.type }) mySet('goodsList', shopcartObj); // 评论 this.getCommentList(this.data.goods_code, this.data.pagenum, this.data.pagesize); this.getDispatchCommentList(shop_id, this.data.pagenum, this.data.pagesize) }, closeModal(data) { this.setData({ maskView: data.detail.maskView, goodsModal: data.detail.goodsModal }) }, funOpenShopcar(data){ this.setData({ shopcarShow: data.detail }) }, changeMenu(e) { this.setData({ activeTab: e.currentTarget.dataset.cur }) }, changeTab(e) { this.setData({ tabActive: e.currentTarget.dataset.cur, pagenum: 1 }); }, // sku商品 onCart(data) { if (Object.keys(data).length == 0) { return } console.log('onCart',data); this.setData({ shopcartList: data.detail.goodlist || {}, shopcartAll: data.detail.shopcartAll || [], priceAll: data.detail.priceAll || 0, shopcartNum: data.detail.shopcartNum || 0, priceFree: data.detail.priceFree || 0, repurse_price: data.detail.repurse_price || 0 }) // 购物车活动提示 this.shopcartPrompt(app.globalData.fullActivity, data.detail.priceFree || 0, data.detail.repurse_price || 0); }, // 购物车 onchangeShopcart(data) { this.onCart(data) }, addshopcart(e) { let goods_car = {}; let goods_code = e.currentTarget.dataset.goods_code; let goods_format = e.currentTarget.dataset.goods_format; let goodlist = my.getStorageSync({ key: 'goodsList' }).data || {}; if (goodlist[`${goods_code}_${goods_format}`]) { goodlist[`${goods_code}_${goods_format}`].num += 1; goodlist[`${goods_code}_${goods_format}`].sumnum += 1; } else { let oneGood = {}; if (e.currentTarget.dataset.goods_discount) { oneGood = { "goods_name": e.currentTarget.dataset.goods_name, "taste_name": e.currentTarget.dataset.taste_name, "goods_price": parseInt(e.currentTarget.dataset.goods_price), "num": 1, "sumnum": 1, "goods_code": e.currentTarget.dataset.goods_code, "goods_activity_code": e.currentTarget.dataset.goods_activity_code, "goods_discount": e.currentTarget.dataset.goods_discount, "goods_original_price": parseInt(e.currentTarget.dataset.goods_original_price), "goods_discount_user_limit": e.currentTarget.dataset.goods_discount_user_limit, "goods_order_limit": e.currentTarget.dataset.goods_order_limit, "goods_format": goods_format, "goods_img": e.currentTarget.dataset.goods_img, "sap_code": e.currentTarget.dataset.sap_code } } else { oneGood = { "goods_name": e.currentTarget.dataset.goods_name, "taste_name": e.currentTarget.dataset.taste_name, "goods_price": parseInt(e.currentTarget.dataset.goods_price), "num": 1, "sumnum": 1, "goods_code": e.currentTarget.dataset.goods_code, "goods_format": goods_format, "goods_img": e.currentTarget.dataset.goods_img, "sap_code": e.currentTarget.dataset.sap_code, "huangou": e.currentTarget.dataset.huangou } } goodlist[`${goods_code}_${goods_format}`] = oneGood; } let shopcartAll = [], priceAll = 0, shopcartNum = 0, priceFree = 0, repurse_price = 0; for (let keys in goodlist) { if (!goodlist[keys].goods_price) { continue; } if (e.currentTarget.dataset.goods_discount) { if (goodlist[keys].goods_order_limit && goodlist[keys].goods_order_limit != null && goodlist[`${e.currentTarget.dataset.goods_code}_${goods_format}`].num > e.currentTarget.dataset.goods_order_limit) { my.showToast({ content: `折扣商品限购${e.currentTarget.dataset.goods_order_limit}${e.currentTarget.dataset.goods_unit},超过${e.currentTarget.dataset.goods_order_limit}${e.currentTarget.dataset.goods_unit}恢复原价` }) } } if (goodlist[keys].goods_order_limit && goodlist[keys].goods_order_limit != null && goodlist[keys].num > goodlist[keys].goods_order_limit) { priceAll += parseInt(goodlist[keys].goods_price) * goodlist[keys].goods_order_limit + (goodlist[keys].num - goodlist[keys].goods_order_limit) * goodlist[keys].goods_original_price; if (keys.indexOf('PKG') == -1) { priceFree += (goodlist[keys].num - goodlist[keys].goods_order_limit) * goodlist[keys].goods_original_price; } } else if (goodlist[keys].goods_price && goodlist[keys].num) { priceAll += parseInt(goodlist[keys].goods_price) * goodlist[keys].num; } else { } // 计算包邮商品价格 if (!goodlist[keys].goods_discount) { priceFree += goodlist[keys].goods_price * goodlist[keys].num; } // 计算可换购商品价格 if (app.globalData.repurseGoods && app.globalData.repurseGoods.length > 0) { if (goodlist[keys].huangou && goodlist[keys].goods_price && goodlist[keys].num) { repurse_price += parseInt(goodlist[keys].goods_price) * goodlist[keys].num; } } else { repurse_price = parseInt(priceAll) } shopcartAll.push(goodlist[keys]); shopcartNum += goodlist[keys].num } let datas = { detail: { goodlist, shopcartAll, priceAll, shopcartNum, priceFree, repurse_price } }; this.onchangeShopcart(datas) this.setData({ shopcartList: goodlist, shopcartAll, priceAll, shopcartNum }) mySet('goodsList', goodlist) }, reduceshopcart(e) { let code = e.currentTarget.dataset.goods_code; let format = e.currentTarget.dataset.goods_format; let goodlist = my.getStorageSync({ key: 'goodsList' }).data; let shopcartAll = [], priceAll = 0, shopcartNum = 0, priceFree = 0, repurse_price = 0, newGoodlist = {}; goodlist[`${code}_${format}`].num -= 1; goodlist[`${code}_${format}`].sumnum -= 1; for (let keys in goodlist) { if (!goodlist[keys].goods_price) { continue; } if (goodlist[keys].goods_order_limit && goodlist[keys].goods_order_limit != null && goodlist[keys].num > goodlist[keys].goods_order_limit) { priceAll += parseInt(goodlist[keys].goods_price) * goodlist[keys].goods_order_limit + (goodlist[keys].num - goodlist[keys].goods_order_limit) * goodlist[keys].goods_original_price; if (keys.indexOf('PKG') == -1) { priceFree += (parseInt(goodlist[keys].num) - parseInt(goodlist[keys].goods_order_limit)) * parseInt(goodlist[keys].goods_original_price); } } else if (goodlist[keys].goods_price && goodlist[keys].num){ priceAll += parseInt(goodlist[keys].goods_price) * goodlist[keys].num; } else { } // 计算包邮商品价格 if (!goodlist[keys].goods_discount) { priceFree += goodlist[keys].goods_price * goodlist[keys].num; } // 计算可换购商品价格 if (app.globalData.repurseGoods && app.globalData.repurseGoods.length > 0) { if (goodlist[keys].huangou && goodlist[keys].goods_price && goodlist[keys].num) { repurse_price += parseInt(goodlist[keys].goods_price) * goodlist[keys].num; } } else { repurse_price = parseInt(priceAll) } if (goodlist[keys].num > 0) { newGoodlist[keys] = goodlist[keys] shopcartAll.push(goodlist[keys]); shopcartNum += goodlist[keys].num } } let datas = { detail: { goodlist, shopcartAll, priceAll, shopcartNum, priceFree, repurse_price } }; this.onchangeShopcart(datas) this.setData({ shopcartList: newGoodlist, shopcartAll, priceAll, shopcartNum }) mySet('goodsList',newGoodlist) }, // 购物车活动提示 shopcartPrompt(oldArr, priceFree, repurse_price) { let activityText = '', freeText = ''; for (let v of oldArr) { if (oldArr.findIndex(v => v > repurse_price) != -1) { if (oldArr.findIndex(v => v > repurse_price) == 0) { activityText = `只差${(oldArr[0] - repurse_price) / 100}元,超值福利等着你!` } else if (oldArr.findIndex(v => v > repurse_price) > 0 && oldArr.findIndex(v => v > repurse_price) < oldArr.length) { activityText = `已购满${oldArr[oldArr.findIndex(v => v > repurse_price) - 1] / 100}元,去结算享受换购优惠;满${oldArr[oldArr.findIndex(v => v > repurse_price)] / 100}元更高福利等着你!` } else { activityText = `已购满${oldArr[oldArr.length - 1] / 100}元,去结算获取优惠!` } } else { activityText = `已购满${oldArr[oldArr.length - 1] / 100}元,去结算获取优惠!` } } if (this.data.freeMoney > 0) { app.globalData.freetf = false; //orderconform中是否传送freeid if (priceFree == 0) { freeText = `满${this.data.freeMoney / 100}元 免配送费` } else if (priceFree < this.data.freeMoney) { freeText = `还差${(this.data.freeMoney / 100 - priceFree / 100).toFixed(2)}元 免配送费` } else { freeText = `已满${this.data.freeMoney / 100}元 免配送费` //加入变量说明可以免配送 app.globalData.freetf = true; } } else if (this.data.freeMoney == 0) { freeText = '免配送费' //加入变量说明可以免配送 app.globalData.freetf = true; } this.setData({ activityText, freeText }) }, // 清空购物车 onClear() { this.setData({ shopcartList: {} }) }, funGetMoreComment() { this.data.pagenum++; this.getCommentList(this.data.goodsInfo.goods_code, this.data.pagenum, this.data.pagesize); }, funGetMoreDispatch() { this.data.pagenum++; const shop_id = myGet('shop_id') || ''; this.getDispatchCommentList(shop_id, this.data.pagenum, this.data.pagesize) }, // 商品评价 getCommentList(goods_code, pagenum, pagesize) { let that = this; commentList(goods_code, pagenum, pagesize, 1).then((res) => { // 这里判断一下 if (that.data.commentArr.data && that.data.commentArr.data.length > 0) { res.data = [...that.data.commentArr.data, ...res.data]; } this.setData({ commentArr: res }) }) }, // 配送评价 getDispatchCommentList(shop_id, pagenum, pagesize) { let that = this; DispatchCommentList(shop_id, pagenum, pagesize, 1).then((res) => { // 这里判断一下 if (that.data.dispatchArr.data && that.data.dispatchArr.data.length > 0) { res.data = [...that.data.dispatchArr.data, ...res.data]; } this.setData({ dispatchArr: res }) }) }, // 选规格 chooseSizeTap(e) { this.setData({ maskView: true, goodsModal: true, goodsItem: e.currentTarget.dataset.item }) }, onReachBottom() { this.data.pagenum++; const shop_id = my.getStorageSync({ key: 'shop_id' }).data; this.getCommentList(this.data.goodsInfo.goods_code, this.data.pagenum, this.data.pagesize); this.getDispatchCommentList(shop_id, this.data.pagenum, this.data.pagesize) } }); <file_sep>/pages/noposition/noposition.js import { imageUrl } from '../common/js/baseUrl' Page({ data: { imageUrl }, onLoad() { }, goselecttarget(){ my.reLaunch({ url: '/pages/home/selecttarget/selecttarget' }) }, goreload(){ my.reLaunch({ url: '/pages/position/position' }) } }); <file_sep>/package_my/pages/coupon/redeemCodeRecord/redeemCodeRecord.js import {imageUrl,imageUrl2} from '../../../../pages/common/js/baseUrl' import {exchangeCode} from '../../../../pages/common/js/home' Page({ data: { imageUrl, imageUrl2, exchageArr:[] }, onLoad() { const _sid = my.getStorageSync({key: '_sid'}).data; this.getExchangeCode(_sid); }, getExchangeCode(_sid){ exchangeCode(_sid,'history').then((res) => { this.setData({ exchageArr:res.DATA }) }) }, }); <file_sep>/pages/position/position.js import { imageUrl, ak, geotable_id, mySet, myGet } from '../common/js/baseUrl' import { bd_encrypt } from '../common/js/map' import { GetLbsShop, NearbyShop } from '../common/js/home' import { cur_dateTime, compare, sortNum } from '../common/js/time' let timeCount; var app = getApp(); let redir_url = 'pages/position/position' //当前页面url Page({ data: { imageUrl: imageUrl, city: '定位中...', selfok: false //是否完成了自提流程 }, onLoad() { clearInterval(timeCount); my.removeStorageSync({ key: 'takeout', // 缓存数据的key }); my.removeStorageSync({ key: 'self', // 缓存数据的key }); my.removeStorageSync({ key: 'opencity', // 缓存数据的key }); var that = this; my.getLocation({ type: 3, success(res) { my.hideLoading(); // console.log(res) const mapPosition = bd_encrypt(res.longitude, res.latitude); my.setStorageSync({ key: 'lat', // 缓存数据的key data: mapPosition.bd_lat, // 要缓存的数据 }); my.setStorageSync({ key: 'lng', // 缓存数据的key data: mapPosition.bd_lng, // 要缓存的数据 }); // 缓存附近地址 my.setStorageSync({ key: 'nearPois', data: res.pois }) app.globalData.province = res.province; app.globalData.city = res.city; app.globalData.address = res.pois[0].name; app.globalData.position = res; app.globalData.position.longitude = mapPosition.bd_lng; app.globalData.position.latitude = mapPosition.bd_lat; that.getLbsShop(); that.getNearbyShop(); that.setData({ city: res.city }) }, fail() { // 定位失败 my.hideLoading(); my.reLaunch({ url: '/pages/noposition/noposition' }) }, }) }, onShow() { clearInterval(timeCount); }, // 外卖附近门店 getLbsShop() { const lng = my.getStorageSync({ key: 'lng' }).data; const lat = my.getStorageSync({ key: 'lat' }).data; const location = `${lng},${lat}` const shopArr1 = []; const shopArr2 = []; GetLbsShop(lng, lat).then((res) => { if (res.code == 100 && res.data.shop_list.length > 0) { let shop_list = res.data.shop_list; for (let i = 0; i < shop_list.length; i++) { const status = cur_dateTime(shop_list[i].start_time, shop_list[i].end_time); // app.globalData.isOpen = status // 判断是否营业 if (status == 1 || status == 3) { shopArr1.push(shop_list[i]); } else { shopArr2.push(shop_list[i]); } } // 按照goods_num做降序排列 let shopArray = shopArr1.concat(shopArr2); // shopArray.sort((a, b) => { // var value1 = a.goods_num, // value2 = b.goods_num; // if (value1 <= value2) { // return a.distance - b.distance; // } // return value2 - value1; // }); shopArray[0]['jingxuan'] = true; my.setStorageSync({ key: 'takeout', data: shopArray }); // 保存外卖门店到本地 //存储app.golbalData my.setStorageSync({ key: 'appglobalData', data: app.globalData }); // let that = this; //外卖ok this.setData({ selfok: true }) } else if (res.code == 100 && res.data.shop_list.length == 0) { this.setData({ content: '您的定位地址无可配送门店', confirmButtonText: '去自提', cancelButtonText: '修改地址', modalShow: true, mask: true }) } else { my.showToast({ content: '获取附近外卖门店有些吃力,重新定位一下试试!', success: function() { my.reLaunch({ url: '/pages/position/position' }) } }) } }).catch(() => { my.showToast({ content: '您的网络有点卡哦,请稍后再试!', success() { my.redirectTo({ url: '/pages/noNet/noNet?redir='+redir_url, // 需要跳转的应用内非 tabBar 的目标页面路径 ,路径后可以带参数。参数规则如下:路径与参数之间使用 }); } }) }) }, // 自提附近门店 getNearbyShop() { const lng = my.getStorageSync({ key: 'lng' }).data; const lat = my.getStorageSync({ key: 'lat' }).data; const location = `${lng},${lat}` const str = new Date().getTime(); my.request({ url: `https://api.map.baidu.com/geosearch/v3/nearby?geotable_id=${geotable_id}&location=${lng}%2C${lat}&ak=${ak}&radius=3000&sortby=distance%3A1&_=1504837396593&page_index=0&page_size=50&_=${str}`, success: (res) => { // 3公里有门店 if (res.data.contents && res.data.contents.length > 0) { this.getSelf(res.data.contents) } else { // 没有扩大搜索范围到1000000公里 my.request({ url: `https://api.map.baidu.com/geosearch/v3/nearby?geotable_id=${geotable_id}&location=${lng}%2C${lat}&ak=${ak}&radius=1000000000&sortby=distance%3A1&_=1504837396593&page_index=0&page_size=50&_=1563263791821`, success: (conf) => { if (conf.data.contents.length > 0) { this.getSelf(conf.data.contents) } else { // 提示切换地址 my.showToast({ content: "当前定位地址无可浏览的门店,请切换地址!", success: (res) => { my.redirectTo({ url: '/pages/home/selecttarget/selecttarget?type=true' }); }, }); } }, }); } }, }); }, // 自提 getSelf(obj) { let shopArr1 = []; let shopArr2 = []; NearbyShop(JSON.stringify(obj)).then((res) => { for (let i = 0; i < res.length; i++) { let status = cur_dateTime(res[i].start_time, res[i].end_time); // 判断是否营业 if (status == 1 || status == 3) { shopArr1.push(res[i]); } else { shopArr2.push(res[i]); } } // 根据距离最近排序 // shopArr1.sort(sortNum('distance')); // shopArr2.sort(sortNum('distance')); const shopArray = shopArr1.concat(shopArr2); shopArray[0]['jingxuan'] = true; my.setStorageSync({ key: 'self', data: shopArray }); // 保存自提门店到本地 let that = this; timeCount = setInterval(function() { if (that.data.selfok == true) { clearInterval(timeCount); //跳转到商城首页 my.reLaunch({ url: '/pages/home/goodslist/goodslist' }); } }, 1000); }) }, onCounterPlusOne(e) { // 点击左边去自提 if (e.type == 1 && e.isType == "noShop") { this.setData({ modalShow: e.modalShow, mask: e.mask, type: 2 }) app.globalData.type = 2; // this.getNearbyShop(); //存储app.golbalData my.setStorageSync({ key: 'appglobalData', data: app.globalData }); // my.reLaunch({ url: '/pages/home/goodslist/goodslist' }) } else { my.redirectTo({ url: '/pages/home/selecttarget/selecttarget?type=true' }); } }, }); <file_sep>/pages/common/js/baseUrl.js // 测试环境 export const baseUrl = 'https://test-wap.juewei.com/api'; // 新接口 export const newBaseUrl = 'https://test-saas.juewei.com'; // 图片测试cdn export const imageUrl = 'https://test-cdn-wap.juewei.com/m/ali-mini/image/'; export const imageUrl2 = 'https://imgcdnjwd.juewei.com'; export const imageUrl3 = 'https://images.juewei.com'; //jsonUrl export const jsonUrl='https://imgcdnjwd.juewei.com/static/check'; export const serviceUrl='https://test-wap.juewei.com'; //百度测试ak export const ak = 'pRtqXqnajTytAzWDL3HOnPRK'; export const geotable_id='134917'; // // 预发布 // export const baseUrl = 'https://proving-wap.juewei.com/api'; // // 新接口 // export const newBaseUrl = 'https://proving-saas.juewei.com'; // // 图片测试cdn // export const imageUrl = 'https://cdn-wap.juewei.com/m/ali-mini/image/'; // export const imageUrl2 = 'https://imgcdnjwd.juewei.com'; // export const imageUrl3 = 'https://images.juewei.com'; // //jsonUrl // export const jsonUrl='https://imgcdnjwd.juewei.com/static/product'; // export const serviceUrl='https://wap.juewei.com'; // //百度测试ak // export const ak = 'pRtqXqnajTytAzWDL3HOnPRK'; // export const geotable_id='134917'; // // 生产环境 // export const baseUrl = 'https://wap.juewei.com/api'; // // 新接口 // export const newBaseUrl = 'https://saas.juewei.com' // // 图片测试cdn // export const imageUrl = 'https://cdn-wap.juewei.com/m/ali-mini/image/'; // export const imageUrl2 = 'https://imgcdnjwd.juewei.com'; // export const imageUrl3 = 'https://images.juewei.com'; // //jsonUrl // export const jsonUrl='https://imgcdnjwd.juewei.com/static/product'; // export const serviceUrl='https://wap.juewei.com'; // // 百度生产ak // export const ak = 'pRtqXqnajTytAzWDL3HOnPRK'; // export const geotable_id='134917'; // 判断是否测试环境 const isTestUrl = baseUrl.includes('test'); // 套餐图片路径 export const img_url = isTestUrl?imageUrl2:imageUrl3; // 获取缓存 export const myGet = (key) => { let value = my.getStorageSync({ key }).data; return value } // 存储数据 export const mySet = (key, data) => { my.setStorageSync({ key, data }) }<file_sep>/package_my/pages/coupon/couponRecord/couponRecord.js import {imageUrl} from '../../../../pages/common/js/baseUrl' import {couponsList} from '../../../../pages/common/js/home' import {formatTime} from '../../../../pages/common/js/time' import { getSid, log, ajax } from '../../../../pages/common/js/li-ajax' Page({ data: { imageUrl, couponList:[], open2: false, codeImg: '', }, onLoad() { const _sid = my.getStorageSync({key: '_sid'}).data; this.getCouponsList(_sid); }, getCouponsList(_sid){ couponsList(_sid,'history').then((res) => { res.DATA.used.forEach(item => { item.start_time = formatTime(item.start_time,'Y-M-D'); item.end_time = formatTime(item.end_time,'Y-M-D'); }) this.setData({ couponList:res.DATA.used, tabs:this.data.tabs }) }) }, /** * @function 展示规则 */ toggleRule(e) { const { index } = e.currentTarget.dataset; let { couponList } = this.data if (couponList[index].toggleRule) { couponList[index].toggleRule = false } else { couponList.forEach(item => { item.toggleRule = false; }) couponList[index].toggleRule = true } this.setData({ couponList }) } }); <file_sep>/package_my/pages/coupon/explain/explain.js import {imageUrl} from '../../../../pages/common/js/baseUrl' Page({ data: { imageUrl, list:[ { type:1, info:'Q:如何获取优惠券?' }, { type:2, info:' A:点击公众号【抢券】频道参与抢券,我们努力不定期发大券;', info1:'订单支付成功后,参与评价。优质评价直送2元稀有立减;PS:从现在起,所有优惠累加使用;', info2:' 随时上我,关注绝味鸭脖公众号官方活动;在优惠这件事上,我们从不逗逼!' }, { type:1, info:'Q:优惠券的使用条件?' }, { type:2, info:'A:全场通用!' }, { type:1, info:'Q:下单的时候使用了优惠券,但是后来订单取消了,优惠券还会返还吗?' }, { type:2, info:'A:当然必须会。订单取消后优惠券会自动返还到您的账户,请注意查收。没有关注微信公众号的,无法查询。' }, { type:1, info:'Q:优惠券能找零兑换吗?' }, { type:2, info:'A:优惠券不找零,不兑换。' }, { type:2, info:'A:一切优惠活动最终解释权归绝味鸭脖所有。嘎~' }, ] }, onLoad() {}, }); <file_sep>/package_my/pages/membercard/membercard.js import { membercard } from '../../../pages/common/js/my' import { baseUrl, imageUrl, myGet } from '../../../pages/common/js/baseUrl' import { getuserInfo } from '../../../pages/common/js/login' Page({ data: { imgSrc: '', imageUrl, phone: '', userInfo: {}, }, onLoad() { this.getQRcode(); const phone = my.getStorageSync({ key: 'phone' }).data; this.setData({ phone }); // 获取用户信息 getuserInfo(myGet('_sid') || '').then((res) => { if (res.code == 30106) { this.setData({ loginId: res.code, userInfo: {}, }) } if (res.code == 0) { this.getAuthCode(res.data); } }) }, onHide() { }, getAuthCode(userInfo) { my.getAuthCode({ scopes: ['auth_user', 'auth_life_msg'], success: (res) => { my.getAuthUserInfo({ success: (user) => { userInfo['head_img'] = user.avatar userInfo['nick_name'] = user.nickName this.setData({ userInfo }) } }); }, fail: (e) => { this.setData({ userInfo }) } }); }, getQRcode() { const _sid = my.getStorageSync({ key: '_sid' }).data; this.setData({ imgSrc: baseUrl + '/juewei-api/alimini/getQRcode?_sid=' + _sid }) }, goPay() { my.ap.navigateToAlipayPage({ appCode: 'payCode', success: (res) => { // my.alert(JSON.stringify(res)); }, fail: (res) => { // my.alert(JSON.stringify(res)); } }) } }); <file_sep>/pages/home/orderform/orderform.js import { imageUrl, imageUrl2, imageUrl3, img_url, myGet, mySet } from '../../common/js/baseUrl' import { couponsList, confirmOrder, createOrder, useraddressInfo, add_lng_lat, payment, useraddress, AliMiniPay } from '../../common/js/home' import { upformId } from '../../common/js/time' import { gd_decrypt } from '../../common/js/map' import { navigateTo, redirectTo, reLaunch, switchTab } from '../../common/js/router' var app = getApp(); Page({ /** * 页面的初始数据 */ data: { imageUrl, imageUrl2, imageUrl3, img_url, isCheck: true, //协议 // 换购商品列表 repurseList: [], countN: 0, mask: false, modalShow: false, address: false, type: 0, content: "", orderType: 1, //1为外卖,2为自提 longitude: '', latitude: '', markersArray: [], shopObj: {}, // 自提商店的详细信息 couponslist: [], //优惠券列表 couponsDefault: null, coupon_code: '', // 优惠券码 full_money: 0, goodsInfo: '', addressInfo: {}, dispatch_price: 0, // 配送费 remark: '口味偏好等要求', // 备注 goodsReal: [], // 非赠品 goodsInvented: [], // 赠品 gifts: [], // 选择的换购商品 gifts_price: '', // 换购商品价格 gift_id: '', // 换购商品id order_price: '', //订单总价 showRepurse: false, // 是否显示换购商品 coupon_money: 0, // 优惠金额 goodsList: [], notUse: false, isClick: true, phone: '', // 手机号 newArr: [], // 变更商品列表 addressList: [], trueprice: 0, //真实的总价价格 send_price: 0, price_no_count: false, goodsOrder: {}, is_allow_coupon:false,//是否可以优惠 activity_channel:1 //支付宝的 }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options) { // 外卖默认地址 if (app.globalData.type == 1) { this.funGetDefault(); } let goodsList = myGet('goodsList'); let obj1 = {}, obj2 = {}, obj3 = {}, obj4 = {}, obj5 = {}, obj6 = {}, goodlist = []; for (let key in goodsList) { if (goodsList[key].goods_discount) { if (goodsList[key].num > goodsList[key].goods_order_limit) { goodlist.push({ goods_price: goodsList[key].goods_price, goods_quantity: goodsList[key].goods_order_limit, goods_code: goodsList[key].goods_code, goods_format: goodsList[key].goods_format, goods_order_limit: goodsList[key].goods_order_limit }, { goods_price: goodsList[key].goods_original_price, goods_quantity: goodsList[key].num - goodsList[key].goods_order_limit, goods_code: goodsList[key].goods_activity_code, goods_format: goodsList[key].goods_format, }); } else { goodlist.push({ goods_price: goodsList[key].goods_price, goods_quantity: goodsList[key].num, goods_code: goodsList[key].goods_code, goods_format: goodsList[key].goods_format, goods_order_limit: goodsList[key].goods_order_limit }); } } else { //  普通商品 goodsList[key]['goods_quantity'] = goodsList[key].num goodlist.push(goodsList[key]) } } const self = app.globalData.shopTakeOut; this.setData({ goodsList: goodlist, shopObj: self }) if (app.globalData.type == 2) { const shop_id = myGet('shop_id'); const phone = myGet('userInfo').phone; let ott = gd_decrypt(myGet('lng'), myGet('lat')); let location_s = gd_decrypt(self.location[0], self.location[1]); let arr = [{ longitude: ott.lng, latitude: ott.lat, iconPath: `${imageUrl}position_map1.png`, width: 20, height: 20, rotate: 0 }, { longitude: location_s.lng, latitude: location_s.lat, iconPath: `${imageUrl}position_map2.png`, width: 36, height: 36, label: { content: `距你${self.distance}米`, color: "#333333", fontSize: 11, borderRadius: 30, bgColor: "#ffffff", padding: 5, anchorX: -36, anchorY: -60 } } ] this.setData({ longitude: location_s.lng, latitude: location_s.lat, markersArray: arr, orderType: app.globalData.type, phone }) } }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function() { }, /** * 生命周期函数--监听页面显示 */ onShow: function() { // 备注 if (app.globalData.remarks) { this.setData({ remark: app.globalData.remarks }) } if (app.globalData.coupon_code && app.globalData.coupon_code != '') { this.setData({ coupon_code: app.globalData.coupon_code, }) } else { this.setData({ coupon_code: '', }) } if (app.globalData.notUse == 1) { this.setData({ notUse: true }) } else { this.setData({ notUse: false }) } if (app.globalData.address_id) { this.funGetAddress(app.globalData.address_id, myGet('_sid')) } else { this.setData({ address: false, addressList: [] }) } this.funConfirmOrder(myGet('shop_id'), JSON.stringify(this.data.goodsList)); }, /** * 生命周期函数--监听页面隐藏 */ onHide: function() { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function() { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function() { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function() { }, /** * 用户点击右上角分享 */ onShareAppMessage: function() { }, // 换购显示 eveAddRepurseTap(e) { let gifts = [], gifts_price = '', order_price = '', trueprice = 0; gifts.push({ "activity_id": e.currentTarget.dataset.activity_id, "gift_id": e.currentTarget.dataset.gift_id, "id": e.currentTarget.dataset.id, "num": 1, "cash": e.currentTarget.dataset.cash, "point": e.currentTarget.dataset.point, "gift_price": e.currentTarget.dataset.gift_price }); if (e.currentTarget.dataset.cash == 0 && e.currentTarget.dataset.point == 0) { gifts_price = `¥0`; order_price = `¥${this.data.orderInfo.real_price / 100}`; trueprice = this.data.orderInfo.sum_price / 100 - this.data.orderInfo.dispatch_price / 100; } if (e.currentTarget.dataset.cash == 0 && e.currentTarget.dataset.point != 0) { gifts_price = `${e.currentTarget.dataset.point}积分`; order_price = `¥${this.data.orderInfo.real_price / 100}+${e.currentTarget.dataset.point}积分` trueprice = this.data.orderInfo.sum_price / 100 - this.data.orderInfo.dispatch_price / 100; } if (e.currentTarget.dataset.cash != 0 && e.currentTarget.dataset.point == 0) { gifts_price = ` ¥${e.currentTarget.dataset.cash / 100}`; order_price = `¥${e.currentTarget.dataset.cash / 100 + this.data.orderInfo.real_price / 100}`; trueprice = e.currentTarget.dataset.cash / 100 + this.data.orderInfo.sum_price / 100 - this.data.orderInfo.dispatch_price / 100; } if (e.currentTarget.dataset.cash != 0 && e.currentTarget.dataset.point != 0) { gifts_price = `¥${e.currentTarget.dataset.cash / 100}+${e.currentTarget.dataset.point}积分`; order_price = `¥${e.currentTarget.dataset.cash / 100 + this.data.orderInfo.real_price / 100}+${e.currentTarget.dataset.point}积分` trueprice = e.currentTarget.dataset.cash / 100 + this.data.orderInfo.sum_price / 100 - this.data.orderInfo.dispatch_price / 100; } this.setData({ gifts, gift_id: e.currentTarget.dataset.id, gifts_price, order_price, trueprice }) }, // 减 eveReduceBtnTap(e) { this.setData({ gifts: [], gift_id: '', order_price: `¥${this.data.orderInfo.real_price / 100}`, trueprice: this.data.orderInfo.sum_price / 100 - this.data.orderInfo.dispatch_price / 100 }) }, // 弹框事件回调 onCounterPlusOne(data) { let goodlist = myGet('goodsList'); let newShopcart = {}, newGoodsArr = [], obj1 = {}, obj2 = {}; if (this.data.newArr.length > 0 && !this.data.newArr[0].user_id) { for (let _item of this.data.newArr) { for (let item of this.data.goodsList) { // 商品价格变更 //这里不再看大小份,无论大份和小份都清除掉 if (_item.type == 1) { if (`${_item.goodsCode}` == `${item.goods_code}`) { item.goods_price = _item.goodsPrice; } obj1[`${item.goods_code}_${item.goods_format}`] = item; //多 } else { // 商品下架 不堪大小份 if (`${_item.goodsCode}` != `${item.goods_code}`) { obj2[`${item.goods_code}_${item.goods_format}`] = item; //少 } } } } // obj1价格变更 obj2已下架 if (Object.keys(obj2).length > 0 && Object.keys(obj1).length == 0) { newShopcart = obj2; } else if (Object.keys(obj1).length > 0 && Object.keys(obj2).length == 0) { newShopcart = obj1; } else if (Object.keys(obj1).length > 0 && Object.keys(obj2).length > 0) { for (let key in obj1) { if (obj2[key]) { newShopcart[key] = obj1[key]; } } } else { my.removeStorage({ key: 'goodsList' }) switchTab({ url: '/pages/home/goodslist/goodslist' }) return; } }else{ newShopcart = goodlist; } for (let ott in newShopcart) { newGoodsArr.push(newShopcart[ott]) } mySet('goodsList', goodlist); this.setData({ goodsList: newGoodsArr }) // 重新选择商品 if (data.isType == 'orderConfirm' && data.type == 1) { switchTab({ url: '/pages/home/goodslist/goodslist' }) return; } // 继续结算 if (data.isType == 'orderConfirm' && data.type == 0) { this.funConfirmOrder(myGet('shop_id'), JSON.stringify(newGoodsArr)); } this.setData({ mask: false, modalShow: false }) }, // 同意协议 checkedTrueTap() { this.setData({ isCheck: !this.data.isCheck }) }, // 选择地址 funGetAddress(address_id, _sid) { useraddressInfo(address_id, _sid).then((res) => { if (res.code == 0) { this.setData({ address: true, addressInfo: res.data }) } else { this.setData({ address: false, addressInfo: {} }) } }) }, // 获取默认地址 funGetDefault() { useraddress(myGet('shop_id'), myGet('_sid')).then((res) => { let addressList = []; for (let value of res.data) { if (value.is_dis == 1) { addressList.push(value) } } if (addressList.length > 0 && addressList[0].user_address_id) { app.globalData.address_id = addressList[0].user_address_id; this.setData({ address: true, addressInfo: addressList[0], addressList }) } else { this.setData({ address: false, addressList: [] }) } }) }, // 选择优惠券 eveChooseCoupon(e) { navigateTo({ url: '/pages/home/orderform/chooseCoupon/chooseCoupon?coupon=' + (e.currentTarget.dataset.coupon?e.currentTarget.dataset.coupon:'') + '&money=' + e.currentTarget.dataset.money+'&is_allow_coupon='+e.currentTarget.dataset.is_allow_coupon }); }, // 订单确认 funConfirmOrder(shop_id, goods) { let notUse = 0; const gifts = app.globalData.gifts; let giftslist = []; if (app.globalData.notUse) { notUse = app.globalData.notUse } //提交确认订单 // 这里面遇到了选中的换商品字符串无法传入到后台的情况 let gift_list_confirm = []; confirmOrder(this.data.orderType, shop_id, goods, shop_id, this.data.coupon_code, JSON.stringify([]), notUse, (app.globalData.freetf ? app.globalData.freeId : ''), myGet('_sid'),this.data.activity_channel).then((res) => { let goodsList = myGet('goodsList'); if (res.code == 0) { let goodsReal = [], goodsInvented = []; for (let item of res.data.activity_list[''].goods_list) { if (item.is_gifts == 1 && (item.gift_type == 1 || item.gift_type == 2)) { // 赠品虚拟 goodsInvented.push(item) } else { // 非赠品和赠品实物 goodsReal.push(item) } } if (goodsReal.length > 0) { for (let val of goodsReal) { if (!val.is_gifts) { if (val.goods_type == 'PKG') { val['goods_img'] = img_url + app.globalData.goodsArr[app.globalData.goodsArr.findIndex(item => item.goods_code == val.goods_code)].goods_img[0]; } else { val['goods_img'] = app.globalData.goodsArr[app.globalData.goodsArr.findIndex(item => item.sap_code == val.sap_code || item.goods_sap_code == val.sap_code)].goods_img[0].indexOf('http://imgcdnjwd.juewei.com/') == -1 ? 'http://imgcdnjwd.juewei.com/' + app.globalData.goodsArr[app.globalData.goodsArr.findIndex(item => item.sap_code == val.sap_code || item.goods_sap_code == val.sap_code)].goods_img[0] : app.globalData.goodsArr[app.globalData.goodsArr.findIndex(item => item.sap_code == val.sap_code || item.goods_sap_code == val.sap_code)].goods_img[0]; } } } } // 参与加价购的商品 // 加购商品列表 let repurseTotalPrice = 0, arr_money = []; if (app.globalData.repurseGoods) { if (Object.keys(gifts).length > 0) { for (let key in gifts) { gifts[key].forEach(val => { val.goods_count = 0; val.goods_choose = true }) arr_money.push(parseInt(key)); } } // 换购商品不指定,全部换购 if (app.globalData.repurseGoods.length == 0) { let sort_real_price = parseInt(res.data.activity_list[''].real_price); if (arr_money.indexOf(sort_real_price) == -1) { //没有重复的 arr_money.push(sort_real_price); } else { //和价格相互重复了 sort_real_price = sort_real_price + 1; arr_money.push(sort_real_price); } arr_money.sort((a, b) => { return a - b; }); let k = arr_money.findIndex(item => item == sort_real_price); //这里永远会大于 this.setData({ showRepurse: true, repurseList: gifts[arr_money[k - 1]] }) } else { // 换购商品为指定 for (let item of app.globalData.repurseGoods) { for (let value of goodsReal) { if (item.goods_code == value.sap_code && value.goods_type != "DIS") { repurseTotalPrice += value.goods_price * value.goods_quantity; } } } let all_repurseTotalPrice = repurseTotalPrice; if (arr_money.indexOf(all_repurseTotalPrice) == -1) { //没有重复的 arr_money.push(all_repurseTotalPrice); } else { //和价格相互重复了 all_repurseTotalPrice = all_repurseTotalPrice + 1; arr_money.push(all_repurseTotalPrice); } arr_money.sort((a, b) => { return a - b; }); let i = arr_money.findIndex(item => item == all_repurseTotalPrice); this.setData({ showRepurse: true, repurseList: gifts[arr_money[i - 1]] }) } } //  优惠券 let coupon_money = 0; if (res.data.activity_list[''].reduce_detail.length == 1) { coupon_money = res.data.activity_list[''].reduce_detail[0].coupon.reduce } else if (res.data.activity_list[''].reduce_detail.length > 1) { coupon_money = res.data.activity_list[''].reduce_detail[res.data.activity_list[''].reduce_detail.findIndex(val => Math.max(val.coupon.reduce))].coupon.reduce; } //由于orderconfirm不能承接换购商品,所以采用了前端判断换购商品策略 let order_price_num = (res.data.activity_list[''].real_price / 100); let order_price_point = ''; if (this.data.gifts && this.data.gifts.length > 0) { if (parseInt(this.data.gifts[0].cash) > 0) { order_price_num = order_price_num + (this.data.gifts[0].cash / 100); } if (parseInt(this.data.gifts[0].point) > 0) { order_price_point = '+' + this.data.gifts[0].point + '积分'; } } this.setData({ goodsReal, goodsInvented, orderInfo: res.data.activity_list[''], is_allow_coupon:res.data.is_allow_coupon,//是否优惠两单 order_price: `¥${order_price_num}${order_price_point}`, trueprice: res.data.activity_list[''].sum_price / 100 - res.data.activity_list[''].dispatch_price / 100, coupon_money, orderDetail: res.data }) } else if (res.code == 277) { this.setData({ mask: true, modalShow: true, showShopcar: false, isType: 'orderConfirm', content: (res.msg!='')? res.msg + ',系统已经更新,是否确认结算': '系统已经更新,是否确认结算', newArr: res.data }) } else if (res.code == 'A123') { my.alert({ content: res.msg, buttonText: '请重新选择', success() { switchTab({ url: '/pages/home/goodslist/goodslist' }) } }); } else if (res.code == 30106) { //用户未登录状态 // 直接跳转 my.alert({ content: '请重新登录', buttonText: '登录', success() { //用户跳转登录 navigateTo({ url: '/pages/login/auth/auth' }); } }); } else { this.setData({ mask: true, modalShow: true, showShopcar: false, isType: 'orderConfirm', content: res.msg, newArr: [] }) } }) }, // 确认支付 eveConfirmPay() { if (app.globalData.type == 2 && !this.data.isCheck) { my.alert({ content: '请同意到店自提协议', buttonText: '我知道了' }); return } const lng = my.getStorageSync({ key: 'lng' }).data; const lat = my.getStorageSync({ key: 'lat' }).data; const shop_id = my.getStorageSync({ key: 'shop_id' }).data; const goods = JSON.stringify(this.data.goodsList); let type = '', typeClass = '', gift_arr = [], giftObj = {}, notUse = 0, remark = '', str_gift = ''; if (app.globalData.type == 1) { type = 1; typeClass = 2; } if (app.globalData.type == 2) { type = 3; typeClass = 4 } let address_id = app.globalData.address_id; if (app.globalData.type == 1) { if (!address_id) { my.showToast({ content: '请选择收货地址' }) return } } // js节流防短时间重复点击 if (this.data.isClick == false) { return } this.setData({ isClick: false }) if (app.globalData.notUse) { notUse = app.globalData.notUse; } // 备注 if (app.globalData.remarks) { remark = app.globalData.remarks } if (this.data.gifts.length > 0) { giftObj['activity_id'] = this.data.gifts[0].activity_id; giftObj['gift_id'] = this.data.gifts[0].gift_id; giftObj['id'] = this.data.gifts[0].id; gift_arr.push(giftObj); str_gift = JSON.stringify(gift_arr); } // 创建订单 let use_coupons = '' if (this.data.orderInfo.use_coupons[0] && this.data.orderInfo.use_coupons[0] != '') { use_coupons = this.data.orderInfo.use_coupons[0] } createOrder(app.globalData.type, shop_id, goods, shop_id, 11, remark, '阿里小程序', address_id, lng, lat, type, str_gift, use_coupons, notUse, app.globalData.freeId, this.data.activity_channel).then((res) => { // console.log(res); if (res.code == 0) { if (app.globalData.type == 2 && this.data.orderInfo.real_price == 0) { this.setData({ isClick: true, coupon_code: '' }) app.globalData.coupon_code = ''; app.globalData.remarks = ''; add_lng_lat(res.data.order_no, typeClass, lng, lat).then((conf) => { my.removeStorageSync({ key: 'goodsList', // 缓存数据的key }); my.reLaunch({ url: '/pages/home/orderfinish/orderfinish?order_no=' + res.data.order_no, // 需要跳转的应用内非 tabBar 的目标页面路径 ,路径后可以带参数。参数规则如下:路径与参数之间使用 }); }) return } AliMiniPay(res.data.order_no).then((val) => { if (val.code == 0) { // 支付宝调起支付 this.setData({ isClick: true, coupon_code: '' }) app.globalData.coupon_code = ''; app.globalData.remarks = ''; my.tradePay({ tradeNO: val.data.tradeNo, // 调用统一收单交易创建接口(alipay.trade.create),获得返回字段支付宝交易号trade_no success: (value) => { // 支付成功 if (value.resultCode == 9000) { add_lng_lat(res.data.order_no, typeClass, lng, lat).then((conf) => { my.removeStorageSync({ key: 'goodsList', // 缓存数据的key }); my.reLaunch({ url: '/pages/home/orderfinish/orderfinish?order_no=' + res.data.order_no, // 需要跳转的应用内非 tabBar 的目标页面路径 ,路径后可以带参数。参数规则如下:路径与参数之间使用 }); }) } else if (value.resultCode == 4000) { // 支付失败 my.reLaunch({ url: '/pages/home/orderError/orderError', // 需要跳转的应用内非 tabBar 的目标页面路径 ,路径后可以带参数。参数规则如下:路径与参数之间使用 }); } else { // 待支付 my.removeStorageSync({ key: 'goodsList', // 缓存数据的key }); my.redirectTo({ url: '/package_order/pages/orderdetail/orderdetail?order_no=' + res.data.order_no, // 需要跳转的应用内非 tabBar 的目标页面路径 ,路径后可以带参数。参数规则如下:路径与参数之间使用 }) } } }); } }) } else { my.showToast({ content: res.msg, }) this.setData({ isClick: true, }) } }) }, })<file_sep>/pages/common/js/getdistance.js /*地球半径*/ var EARTHRADIUS = 6370996.81; /** * 将度转化为弧度 * @param {degree} Number 度 * @returns {Number} 弧度 */ function degreeToRad(degree) { return Math.PI * degree / 180; } /* * 将v值限定在a,b之间,纬度使用 */ function _getRange(v, a, b) { if (a != null) { v = Math.max(v, a); } if (b != null) { v = Math.min(v, b); } return v; } /** * 将v值限定在a,b之间,经度使用 */ function _getLoop(v, a, b) { while (v > b) { v -= b - a } while (v < a) { v += b - a } return v; } /** * 计算两点之间的距离,两点坐标必须为经纬度 * @param {lng1} Number 点对象 * @param {lat1} Number 点对象 * @param {lng2} Number 点对象 * @param {lat2} Number 点对象 * @returns {Number} 两点之间距离,单位为米 */ export default function getDistance(lng1, lat1, lng2, lat2) { var point1 = { lng: parseFloat(lng1), lat: parseFloat(lat1) } var point2 = { lng: parseFloat(lng2), lat: parseFloat(lat2) } point1.lng = _getLoop(point1.lng, -180, 180); point1.lat = _getRange(point1.lat, -74, 74); point2.lng = _getLoop(point2.lng, -180, 180); point2.lat = _getRange(point2.lat, -74, 74); let x1, x2, y1, y2; x1 = degreeToRad(point1.lng); y1 = degreeToRad(point1.lat); x2 = degreeToRad(point2.lng); y2 = degreeToRad(point2.lat); return EARTHRADIUS * Math.acos((Math.sin(y1) * Math.sin(y2) + Math.cos(y1) * Math.cos(y2) * Math.cos(x2 - x1))); }<file_sep>/package_my/pages/nearshop/nearshop.js import { imageUrl, ak, geotable_id } from '../../../pages/common/js/baseUrl' import { MyNearbyShop } from '../../../pages/common/js/home' import { guide } from '../../../pages/common/js/li-ajax' import { cur_dateTime } from '../../../pages/common/js/time' import { gd_decrypt} from '../../../pages/common/js/map' var app = getApp(); Page({ data: { imageUrl, // 地图中心点 longitude: '', latitude: '', markersArray: [], shopList: [], // 附近门店列表 inputAddress: '', city: '', activeIndex: 0 }, guide, onLoad() { const lng = my.getStorageSync({ key: 'lng' }).data; const lat = my.getStorageSync({ key: 'lat' }).data; let ott = gd_decrypt(lng,lat); this.nearShop(lng, lat); this.setData({ longitude: ott.lng, latitude: ott.lat-0.04, selfshop: false }) }, onShow() { }, // 输入 handleSearch(e) { this.setData({ inputAddress: e.detail.value }) }, // 搜索 addressSearch() { let url = `https://api.map.baidu.com/geocoding/v3/?city=${this.data.city}&address=${this.data.city}${this.data.inputAddress}&output=json&ak=${ak}` url = encodeURI(url); my.request({ url, success: (res) => { my.hideKeyboard(); const lng = res.data.result.location.lng; const lat = res.data.result.location.lat; this.nearShop(lng, lat); let ott = gd_decrypt(lng,lat); this.setData({ longitude:ott.lng, latitude:ott.lat-0.04 }) }, }); }, // 切换门店 switchShop(e) { let arr = this.data.markersArray.map((item, index) => { if (index == e.currentTarget.dataset.index) { return { ...item, iconPath: `${imageUrl}position_map1.png`, markerLevel:10, width: 32, height: 32 } } else { return { ...item, iconPath: `${imageUrl}position_map1.png`, markerLevel:9, width: 15, height: 15 } } }) this.setData({ markersArray: arr, activeIndex: e.currentTarget.dataset.index }) }, // 获取附近门店 nearShop(lng, lat) { my.request({ url: `https://api.map.baidu.com/geosearch/v3/nearby?geotable_id=${geotable_id}&location=${lng}%2C${lat}&ak=${ak}&radius=3000&sortby=distance%3A1&page_index=0&page_size=50&_=`, success: (res) => { const obj = res.data.contents; MyNearbyShop(JSON.stringify(obj)).then((conf) => { conf.forEach(item => { if (cur_dateTime(item.start_time, item.end_time) != 2) { item['isOpen'] = true } }) let arr = conf .map(({ shop_gd_latitude,shop_gd_longitude}) => ({ longitude: shop_gd_longitude, latitude: shop_gd_latitude })) .map((item, index) => { if (index == 0) { return { ...item, iconPath: `${imageUrl}position_map1.png`, markerLevel:10, width: 32, height: 32 } } else { return { ...item, iconPath: `${imageUrl}position_map1.png`, markerLevel:9, width: 15, height: 15 } } }) this.setData({ markersArray: arr, shopList: conf, city:conf[0].city }) }) }, }); }, // 去自提 goSelf(e) { app.globalData.isSelf = true; app.globalData.address1=''; app.globalData.shopIng1 = e.currentTarget.dataset.info; app.globalData.type = 2; my.redirectTo({ url: '/pages/home/selfgoods/selfgoods?isSelf=true', // 跳转的 tabBar 页面的路径(需在 app.json 的 tabBar 字段定义的页面)。注意:路径后不能带参数 success: (res) => { }, }); }, onUnload() {//退出后销毁 app.globalData.isSelf = false; }, // 切换城市 choosecityTap() { my.chooseCity({ showLocatedCity: true, showHotCities: true, success: (res) => { this.setData({ city:res.city + '市' }) }, }); }, }); <file_sep>/package_vip/pages/detail/detail.js import { parseData, getSid, log, isloginFn } from '../../../pages/common/js/li-ajax' import { reqDetail, reqCreateOrder, reqConfirmOrder, reqPay, reqUserPoint } from '../../../pages/common/js/vip' import { imageUrl2 } from '../../../pages/common/js/baseUrl' import { upformId } from '../../../pages/common/js/time' const app = getApp() Page({ data: { modalOpened: false, imageUrl2, openPoint: false, loginOpened: false, content: '', detail: { // "id": "355", // "goods_name": "123", // "total_num": "1", // "valid_num": "1", // "cate_id": "25", // "intro": "<p>123<\/p>", // "goods_type": "2", // "goods_detail_type": "4", // "gift_id": "473", // "exchange_type": "1", // "point": "1", // "amount": 0, // "start_time": "2019-06-22 00:00:00", // "end_time": "2019-07-31 23:59:59", // "receive_type": "2", // "get_start_time": "0000-00-00 00:00:00", // "get_end_time": "0000-00-00 00:00:00", // "scope_type": "3", // "company_id": "0", // "city_id": "1", // "district_id": "0", // "express_type": "1", // "express_fee": "0", // "exchange_limit_type": "1", // "exchange_limit_num": "111", // "exchange_day_num": "0", // "exchange_intro": "<p>123123<\/p>", // "sort_no": "12345", // "status": "2", // "create_time": "2019-06-22 14:47:58", // "update_time": "2019-06-22 14:47:58", // "goods_pic": [{ // "id": "318", // "goods_pic": "\/static\/check\/image\/goods_point\/oXQW34ZBT6Pcbkx0.jpg" // }, { // "id": "454", // "goods_pic": "\/static\/check\/image\/goods_point\/noTHmy1mTM09NrRh.png" // }] }, isClick: true }, parseData, onHide() { this.onModalClose() }, async onLoad(e) { const { id } = e this.setData({ id }) }, async onShow() { const { id } = this.data await this.getDetail(id) }, /** * @function 获取当商品面详情 */ async getDetail(id) { let { code, data: { goods_name, exchange_intro, intro, ...Data } } = await reqDetail(id) if (code === 100) { let _exchange_intro = await this.parseData(exchange_intro) let _intro = await this.parseData(intro) my.setNavigationBar({ title: '商品详情', }); this.setData({ detail: { intro, _intro, exchange_intro, _exchange_intro, goods_name, ...Data } }) } }, /** * @function 创建订单 */ async createOrder() { let { id, exchange_type, point, amount } = this.data.detail; let params = { 'goods[goods_id]': id, 'goods[exchange_type]': exchange_type, 'goods[point]': point, 'goods[amount]': amount, 'pay_type': 11 } let { code, data, msg } = await reqCreateOrder(params) if (code === 100) { return data } if (code !== 100) { my.alert({ title: msg }); return {} } }, /** * @function 确认订单 */ async confirmOrder(order_sn) { let params = { order_sn } let { code, data } = await reqConfirmOrder(params) return code === 100 }, /** * @function 支付订单 */ async pay(order_sn) { let { code, data } = await reqPay(order_sn) return { code, data } }, /** *@function 确认兑换 */ async onModalClick() { let that=this; // goods_type 是 int 订单类型 1 虚拟订单 2 实物订单 // receive_type 是 int 发货方式 0 无需发货 1 到店领取 2公司邮寄 // goods_detail_type 是 int 物品详细类型 1 优惠券 2兑换码 3官方商品 4非官方商品 const { goods_detail_type, receive_type, goods_type, amount } = this.data.detail let fail = false // 虚拟商品,点击兑换按钮,调用创建订单接口, // 有钱的订单或者有运费的订单才调起支付 // 调用确认订单接口,然后调起支付 // id = -1 兑换失败 // 虚拟物品 if (!this.data.isClick) { return } this.setData({ isClick: false }) //虚拟商品 if (goods_type == 1) { let { order_id = '', order_sn } = await this.createOrder() if (!order_id) { this.setData({ isClick: true }) return } let res = await this.confirmOrder(order_sn) if (amount != 0) { let res = await this.pay(order_sn) console.log('amount',res); if (res.code == 0) { my.tradePay({ tradeNO: res.data.tradeNo, // 调用统一收单交易创建接口(alipay.trade.create),获得返回字段支付宝交易号trade_no success: res => { // 用户支付成功 if (res.resultCode == 9000) { return my.redirectTo({ url: '../finish/finish?id=' + order_id + '&fail=' + false }); } // 用户取消支付 if (res.resultCode == 6001) { return my.redirectTo({ url: '../exchangelist/exchangedetail/exchangedetail?id=' + order_id }); } return my.redirectTo({ url: '../finish/finish?id=' + order_id + '&fail=' + true }); }, fail: res => { log('fail') return my.redirectTo({ url: '../finish/finish?id=' + order_id + '&fail=' + true }); } }); } else { that.setData({ isClick: true }) return my.showToast({ content: res.msg }); } return } if (!res) { fail = true } this.setData({ isClick: true }) // 虚拟订单 + 兑换码 => 无需发货 // if (goods_detail_type == 2 && receive_type == 0) { my.navigateTo({ url: '../finish/finish?id=' + order_id + '&fail=' + fail }); } // 虚拟订单 + 优惠卷 => 无需发货 // 跑通 if (goods_detail_type == 1 && receive_type == 0) { my.navigateTo({ url: '../finish/finish?id=' + order_id + '&fail=' + fail }); } } // 实物商品, // 点击兑换按钮, // 调用创建订单接口, // 填写页面表单信息, // 然后点击支付按钮, // 调用确认订单接口, // 然后调起支付 if (goods_type == 2) { let res = await this.createOrder() this.setData({ isClick: true }) if (!res.order_sn) { return } // 实物订单 公司邮寄 if (receive_type == 2) { my.navigateTo({ url: '../waitpay/waitpay?order_sn=' + res.order_sn }); } // 实物订单 到店领取 if (receive_type == 1) { my.navigateTo({ url: '../waitpay/waitpay?order_sn=' + res.order_sn }); } } }, /** * @function 显示modal,立即兑换 */ async showConfirm() { let _sid = await getSid() if (!_sid) { // return this.setData({ // loginOpened: true // }); return isloginFn() } let { goods_name, point } = this.data.detail // 获取 用户 积分 let points = await this.getUserPoint() if (points >= point) { this.setData({ content: `是否兑换“${goods_name}”将消耗你的${point}积分`, modalOpened: true }) } else { this.setData({ openPoint: true }) } }, /** * @function 关闭modal */ onModalClose() { this.setData({ openPoint: false, modalOpened: false, loginOpened: false }) }, /** * @function 赚积分 */ async getMorePoint() { this.onModalClose() my.switchTab({ url: '/pages/home/goodslist/goodslist' }); }, /** * @function 获取用户积分 */ async getUserPoint() { let res = await reqUserPoint() if (res.CODE === 'A100') { return res.DATA.points } }, onSubmit(e) { upformId(e.detail.formId); }, isloginFn });<file_sep>/pages/login/auth/auth.js import { imageUrl, baseUrl,myGet,mySet } from '../../common/js/baseUrl' import { sendCode, captcha, loginByAliUid, loginByAuth, getuserInfo, decryptPhone } from '../../common/js/login' import { upformId } from '../../common/js/time' var app = getApp(); //放在顶部 Page({ data: { imageUrl, baseUrl, modalOpened: false, getCode: false, phone: '', img_code: '', imgUrl: '', next:false }, onLoad(option) { if(option.next=='true'){ this.setData({ next:true }) }else{ this.setData({ next:false }) } }, onShow(aa) { this.getAliId() }, openModal() { this.setData({ modalOpened: true, }); }, onModalClick() { this.setData({ modalOpened: false, }); }, onModalClose() { this.setData({ modalOpened: false, }); }, inputValue(e) { var phone = e.detail.value if (phone.length == 11) { this.setData({ phone: phone, getCode: true }) } else { this.setData({ phone: phone, getCode: false }) } }, getcodeImg(e) { var img_code = e.detail.value this.setData({ img_code: img_code }) }, getImgcodeFn() { if (this.data.img_code === '') { my.showToast({ type: 'none', duration: 1000, content: '图片验证码不可为空' }); return } this.getcodeFn() }, // 获取短信验证码 async getcodeFn() { var that = this if (/^1\d{10}$/.test(this.data.phone)) { } else { my.showToast({ type: 'none', content: '请输入有效手机号', duration: 1000 }); return } my.showLoading({ content: '发送中...', }); if (this.data.getCode) { var time = my.getStorageSync({ key: 'time', // 缓存数据的key }).data; if (time) { if (time != new Date().toLocaleDateString()) { my.removeStorageSync({ key: 'time', }); my.removeStorageSync({ key: 'count', }); } } var count = my.getStorageSync({ key: 'count', // 缓存数据的key }).data || 0; if (count == 0) { my.setStorageSync({ key: 'time', // 缓存数据的key data: new Date().toLocaleDateString(), // 要缓存的数据 }); } if (count >= 5 && !this.data.modalOpened) { my.hideLoading(); this.setData({ modalOpened: true, imgUrl: this.data.baseUrl + '/juewei-api/user/captcha?_sid=' + this.data._sid + '&s=' + (new Date()).getTime() }) return } var data = { _sid: this.data._sid, phone: this.data.phone, img_code: this.data.img_code } let code = await sendCode(data) if (code.code == 0 && code.msg == 'OK') { my.setStorageSync({ key: 'count', // 缓存数据的key data: count - '' + 1, // 要缓存的数据 }); this.setData({ modalOpened: false, img_code: '' }) my.hideLoading(); my.showToast({ type: 'none', duration: 2000, content: '短信发送成功' }); my.navigateTo({ url: '/pages/login/verifycode/verifycode?phone=' + data.phone+ (that.data.next==true?'&next=true':'') }); } else { that.setData({ imgUrl: this.data.baseUrl + '/juewei-api/user/captcha?_sid=' + this.data._sid + '&s=' + (new Date()).getTime() }) my.hideLoading(); my.showToast({ type: 'none', duration: 2000, content: code.msg }); } } }, newImg() { this.setData({ modalOpened: true, imgUrl: this.data.baseUrl + '/juewei-api/user/captcha?_sid=' + this.data._sid + '&s=' + (new Date()).getTime() }) }, getAliId() { var that = this let ali_uid = my.getStorageSync({ key: 'ali_uid' }).data; var _sid = my.getStorageSync({ key: '_sid' }).data; if (ali_uid && _sid) { this.setData({ ali_uid: ali_uid, _sid: _sid }) } else { my.getAuthCode({ scopes: ['auth_base'], success: (res) => { my.setStorageSync({ key: 'authCode', // 缓存数据的key data: res.authCode, // 要缓存的数据 }); loginByAliUid(res.authCode).then((data) => { if (data.code == 0 && data.data.user_id) { my.setStorageSync({ key: 'ali_uid', // 缓存数据的key data: data.data.ali_uid, // 要缓存的数据 }); my.setStorageSync({ key: '_sid', // 缓存数据的key data: data.data._sid, // 要缓存的数据 }); mySet('userInfo',data.data); that.setData({ ali_uid: data.data.ali_uid, _sid: data.data._sid }) } else { my.setStorageSync({ key: 'ali_uid', // 缓存数据的key data: data.data.ali_uid, // 要缓存的数据 }); my.setStorageSync({ key: '_sid', // 缓存数据的key data: data.data._sid, // 要缓存的数据 }); mySet('userInfo',data.data); that.setData({ ali_uid: data.data.ali_uid, _sid: data.data._sid }) } }) }, }); } }, // 授权获取用户信息 onGetAuthorize(res) { var that = this my.getPhoneNumber({ success: (res) => { my.showLoading({ content: '加载中...', delay: 1000, }); let userInfo = JSON.parse(res.response); // 以下方的报文格式解析两层 response var data = { response: userInfo.response } decryptPhone(data).then(res => { if (res.code == 0) { that.loginByAuthFn(that.data.ali_uid, res.data.phone); } }) }, fail() { my.alert({ title: '获取用户信息失败' }); } }); }, // 授权登录 loginByAuthFn(ali_uid, phone) { loginByAuth(ali_uid, phone, '', '').then((res) => { if (res.code == 0) { my.setStorageSync({ key: '_sid', // session_id data: res.data._sid, }); my.setStorageSync({ key: 'user_id', // 缓存数据的key data: res.data.user_id, // 要缓存的数据 }); my.setStorageSync({ key: 'phone', // 缓存数据的key data: res.data.phone, // 要缓存的数据 }); mySet('userInfo',res.data); app.globalData._sid = res.data._sid this.getUserInfo(res.data._sid); } else { my.removeStorageSync({ key: 'authCode', }); my.removeStorageSync({ key: 'ali_uid', }); my.removeStorageSync({ key: '_sid', }); my.removeStorageSync({ key: 'user_id', }); my.removeStorageSync({ key: 'phone', }); my.removeStorageSync({ key: 'userInfo', }); my.showToast({ type: 'none', content: res.msg, duration: 2000 }); } }) }, // 用户信息 getUserInfo(_sid) { let that=this; getuserInfo(_sid).then((res) => { app.globalData.userInfo = res.data; my.hideLoading(); if(that.data.next==true){ // 关闭当前跳转到下订单页面 my.redirectTo({ url: '/pages/home/orderform/orderform' }) }else{ my.navigateBack({ delta: 1 }) } }) }, toUrl(e) { var url = e.currentTarget.dataset.url my.navigateTo({ url: url }); }, onSubmit(e){ upformId(e.detail.formId); } }); <file_sep>/package_my/pages/mycenter/newphone/newphone.js // import {sendCode} from '../../../../pages/common/js/login' Page({ data: { phone:'', _sid:'', }, onLoad(e) { this.setData({ _sid:e.sid }) }, inputValue(e){ this.setData({ phone:e.detail.value }) }, getCode(){ //直接跳转 my.navigateTo({ url:'/package_my/pages/mycenter/bindphone/bindphone?phone='+this.data.phone+'&type=2' }); // var data = { // _sid:this.data._sid, // phone:this.data.phone // } // sendCode(data).then(res=>{ // if(res.code==0){ // my.navigateTo({ // url:'/package_my/pages/mycenter/bindphone/bindphone?phone='+this.data.phone+'&type=2' // }); // }else{ // my.showToast({ // type: 'none', // content: res.msg, // duration: 2000 // }); // } }else{ // my.showToast({ // type: 'none', // content: res.msg, // duration: 2000 // }); // } // }) }, }); <file_sep>/pages/home/orderfinish/orderfinish.js import { imageUrl } from '../../common/js/baseUrl' import { formatTime } from '../../common/js/time' import { ajax, log } from '../../common/js/li-ajax' var app = getApp(); Page({ data: { user_id:'', imageUrl, order_no: '', show: false, new_user: [], newUserShow: false, gifts: false, gift_type: 0 }, async onLoad(e) { this.data.user_id = my.getStorageSync({ key: 'user_id' }).data; const { order_no } = e; this.setData({ order_no }, async () => { await this.isNewUser() }) }, checkOrder() { app.globalData.refresh_state = app.globalData.type - 1; my.switchTab({ url: '/pages/order/list/list', }) }, /** * @function 判断是否是新用户 */ // 订单详情接口 // 中会返回一个 new_user 参数 // new_user如果为空或者不存在或者为0 都说明不是新用户首单 // 如果new_user==1则是新用户首单 新用户下单当天只弹一次 // 不同用户同一设备都要弹 弹框内容是百元大礼包券(请求coupon/list接口 和会员新人礼包券一样) async isNewUser() { const { order_no } = this.data let new_user = my.getStorageSync({ key: this.data.user_id+'_new_user', // 缓存数据的key }).data; // 说明不是 第一次 // new_user=0; if (new_user == 1) { return } let res = await ajax('/juewei-api/order/detail', { order_no }); // res.code=0; // res.data.new_user=1; if (res.code == 0) { // 说明是新用户 if (res.data.new_user == 1) { my.setStorage({ key: this.data.user_id+'_new_user', // 缓存数据的key data: 1, // 要缓存的数据 success: async (res) => { await this.getCouponsList() this.setData({ newUserShow: true }) }, }); } // 虚拟商品弹框 let static_no = 0; if(res.data && res.data.goods_list && res.data.goods_list.length>0){ res.data.goods_list.forEach(item => { if (item.is_gifts == 1 && static_no == 0) { static_no = 1; // 优惠券 if (item.gift_type == 1) { this.setData({ gift_type: 1, gifts: true }) } // 兑换码 if (item.gift_type == 2) { this.setData({ gift_type: 2, gifts: true }) } } else { this.setData({ gifts: false }) } }) } }else{ //获取详情订单失败 this.setData({ newUserShow: false }) } }, confirmTap() { this.setData({ gifts: false }) }, close() { this.setData({ newUserShow: false }) }, /** * @function 获取礼包列表 */ async getCouponsList() { let res = await ajax('/mini/coupons/list', { get_type: 'new_user' }) //res.DATA.new_user=[{full_money:'4000',money:'2000',end_time:'1574749176'},{full_money:'4000',money:'2000',end_time:'1574749176'},{full_money:'4000',money:'2000',end_time:'1574749176'},{full_money:'4000',money:'2000',end_time:'1574749176'},{full_money:'4000',money:'2000',end_time:'1574749176'},{full_money:'4000',money:'2000',end_time:'1574749176'}] if (res.CODE === 'A100' && res.DATA.new_user && res.DATA.new_user.length > 0) { let new_user = res.DATA.new_user.map(({ end_time, ...item }) => ({ end_time: formatTime(end_time,'Y-M-D'), //formatTime(new Date(end_time * 1000).toLocaleDateString(),'Y-M-D'), ...item })) this.setData({ new_user, newUserShow: true }) }else { this.setData({ newUserShow: false, new_user: [] }) } }, toTakeIn() { // app.globalData.type = 1 // log(app.globalData.type) this.close() my.switchTab({ url: '/pages/home/goodslist/goodslist' }); }, }); <file_sep>/app.js import { loginByAliUid } from './pages/common/js/login' import { baseUrl } from './pages/common/js/baseUrl' App({ onLaunch(options) { // 加入小程序检查更新 const updateManager = my.getUpdateManager() updateManager.onCheckForUpdate(function(res) { // 请求完新版本信息的回调 if (res.hasUpdate) { updateManager.onUpdateReady(function() { my.confirm({ title: '更新提示', content: '新版本已经准备好,是否重启应用?', success: function(res) { if (res.confirm) { // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 updateManager.applyUpdate() } } }) }) updateManager.onUpdateFailed(function() { // 新版本下载失败 }) } }) // page是拿不到的信息,只有query可以拿到 if (options.query && options.query.go) { this.globalData.query = options.query.go; my.setStorageSync({ key: 'query', // 缓存数据的key data: options.query.go, // 要缓存的数据 }); } // 检测网络是否正常 my.getNetworkType({ success: (res) => { if (res.networkType == "NOTREACHABLE") { my.redirectTo({ url: '/pages/noNet/noNet?redir=', // 需要跳转的应用内非 tabBar 的目标页面路径 ,路径后可以带参数。参数规则如下:路径与参数之间使用 }); return }else{ //正常网络 } } }) // 监听网络状态变化 my.onNetworkStatusChange((res) => { if (res.networkAvailable == true) { my.reLaunch({ url: '/pages/position/position' }) } }) // 获取授权 my.getAuthCode({ scopes: ['auth_base'], success: (res) => { my.setStorageSync({ key: 'authCode', // 缓存数据的key data: res.authCode, // 要缓存的数据 }); loginByAliUid(res.authCode).then((data) => { if (data.code == 0 && data.data.user_id) {//用户自动登录成功 my.setStorageSync({ key: 'ali_uid', // 缓存数据的key data: data.data.ali_uid, // 要缓存的数据 }); my.setStorageSync({ key: '_sid', // 缓存数据的key data: data.data._sid, // 要缓存的数据 }); my.setStorageSync({ key: 'user_id', // 缓存数据的key data: data.data.user_id, // 要缓存的数据 }); my.setStorageSync({ key: 'phone', // 缓存数据的key data: data.data.phone, // 要缓存的数据 }); my.setStorageSync({ key: 'userInfo', // 缓存数据的key data: data.data, // 要缓存的数据 }); } else {//用户登录失败的情况 my.setStorageSync({ key: 'ali_uid', // 缓存数据的key data: data.data.ali_uid, // 要缓存的数据 }); my.setStorageSync({ key: '_sid', // 缓存数据的key data: data.data._sid, // 要缓存的数据 }); my.removeStorageSync({ key: 'user_id', }); my.removeStorageSync({ key: 'phone', }); my.removeStorageSync({ key: 'userInfo', }); } }) }, //获取授权码失败 fail:(e)=>{ my.removeStorageSync({ key: 'authCode', }); my.removeStorageSync({ key: 'ali_uid', }); my.removeStorageSync({ key: '_sid', }); my.removeStorageSync({ key: 'user_id', }); my.removeStorageSync({ key: 'phone', }); my.removeStorageSync({ key: 'userInfo', }); } }); }, onShow(options) {//多次执行 // page是拿不到的信息,只有query可以拿到 if (options.query && options.query.go) { this.globalData.query = options.query.go; my.setStorageSync({ key: 'query', // 缓存数据的key data: options.query.go, // 要缓存的数据 }); } let that = this; my.getSystemInfo({ success: res => { let modelmes = res.model; //判断iphone x以上的手机 if (modelmes.search('iPhone') > -1 && res.statusBarHeight > 20) { that.globalData.isIphoneX = true } else { that.globalData.isIphoneX = false } } }) }, onHide() { // 当小程序从前台进入后台时触发 }, onError(error) { // 小程序执行出错时 console.log(error); }, onShareAppMessage() { return { title: '绝味鸭脖', desc: '会员专享服务,便捷 实惠 放心', imageUrl: 'https://cdn-wap.juewei.com/m/ali-mini/image/jwdlogo.png', bgImgUrl: 'https://cdn-wap.juewei.com/m/ali-mini/image/share_default.png', path: 'pages/position/position', }; }, globalData: { query: null, location: { //获取地区 longitude: null, latitude: null }, address: null, _sid: null, userInfo: null, //拉去支付宝用户信息 authCode: null, //静默授权 phone: null, //获取手机号权限 addressInfo: null, //切换定位地址 gifts: null, //加购商品 type: 1, // 默认外卖 coupon_code: null, //优惠券 scrollTop: null, isOpen: '', province: null, city: null, chooseBool: false, isSelf: false, refresh: false, // 当前页面是否需要刷新 gopages: '', //跳转到相应文件 isIphoneX: false, notUse:0 //默认用户的可用的 } }); <file_sep>/pages/common/js/time.js import { upAliMiniFormId } from './home' import { myGet } from './baseUrl.js' // 比较两个日期时间相差多少天 export const datedifference = (sDate1, sDate2) => { var dateSpan, iDays; var sDate1 = sDate1.replace(/-/g, '/') var date1 = Date.parse(new Date(sDate1)) var sDate2 = sDate2.replace(/-/g, '/') var date2 = Date.parse(new Date(sDate2)) dateSpan = date2 - date1; iDays = Math.floor(dateSpan / (24 * 3600 * 1000)); return iDays }; // 判断门店是否营业 export const cur_dateTime = (start, end) => { var timestamp = new Date().getTime(); var mytime = new Date().toLocaleDateString(); var time1 = new Date(`${mytime} ${start}`).getTime(); var time2 = new Date(`${mytime} ${end}`).getTime(); if (time2 - timestamp > 0 && time2 - timestamp < 1000 * 3600) { return 3 // 不足一小时 } else if (time2 - timestamp > 1000 * 3600 && timestamp < time2 && timestamp > time1) { return 1 // 营业中 } else { return 2 // 未营业 } } // 比较两个数字大小,大到小 export const compare = (property) => { return (a, b) => { var value1 = a[property]; var value2 = b[property]; return value2 - value1; } } // 小到大 export const sortNum = (property) => { return (a, b) => { var value1 = a[property]; var value2 = b[property]; return value1 - value2; } } // 时间戳转时间 export const formatTime = (number, format) => { var formateArr = ['Y', 'M', 'D', 'h', 'm', 's']; var returnArr = []; var date = new Date(number * 1000); returnArr.push(date.getFullYear()); returnArr.push(formatNumber(date.getMonth() + 1)); returnArr.push(formatNumber(date.getDate())); returnArr.push(formatNumber(date.getHours())); returnArr.push(formatNumber(date.getMinutes())); returnArr.push(formatNumber(date.getSeconds())); for (var i in returnArr) { format = format.replace(formateArr[i], returnArr[i]); } return format; } //数据转化 const formatNumber = (n) => { n = n.toString() return n[1] ? n : '0' + n } // 获取当前日期时间 export const getNowDate = () => { var date = new Date(); var sign1 = "-"; var sign2 = ":"; var year = date.getFullYear() // 年 var month = date.getMonth() + 1; // 月 var day = date.getDate(); // 日 var hour = date.getHours(); // 时 var minutes = date.getMinutes(); // 分 var seconds = date.getSeconds() //秒 var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天']; var week = weekArr[date.getDay()]; // 给一位数数据前面加 “0” if (month >= 1 && month <= 9) { month = "0" + month; } if (day >= 0 && day <= 9) { day = "0" + day; } if (hour >= 0 && hour <= 9) { hour = "0" + hour; } if (minutes >= 0 && minutes <= 9) { minutes = "0" + minutes; } if (seconds >= 0 && seconds <= 9) { seconds = "0" + seconds; } var currentdate = year + sign1 + month + sign1 + day + " " + hour + sign2 + minutes + sign2 + seconds; return currentdate; } export const getNowFormatDate = () => { var date = new Date(); var seperator1 = "-"; var year = date.getFullYear(); var month = date.getMonth() + 1; var strDate = date.getDate(); if (month >= 1 && month <= 9) { month = "0" + month; } if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } var currentdate = year + seperator1 + month + seperator1 + strDate; return currentdate; } // 上传formid,模版消息 export const upformId = (formId) => { upAliMiniFormId(myGet('_sid'), myGet('ali_uid'), formId).then((res) => { // console.log(res) }) }<file_sep>/package_my/pages/entitlement/entitlement.js import {imageUrl} from '../../../pages/common/js/baseUrl' Page({ data: { imageUrl, list:[ { icon:`${imageUrl}exchange.png`, title:'迎新礼包', info:'会员迎新礼包,价值100元优惠券', }, { icon:`${imageUrl}my_quity_02.png`, title:'积分礼', info:'积分可在会员专享兑换专属礼品', }, { icon:`${imageUrl}my_quity_04.png`, title:'会员特惠日', info:'会员特惠日,双倍积分、积分兑券、摇奖、商品特价等丰富的会 员活动', } ] }, onLoad() {}, }); <file_sep>/pages/home/selecttarget/selecttarget.js import { imageUrl, ak, geotable_id,myGet } from '../../common/js/baseUrl' import { addressList, GetLbsShop, NearbyShop } from '../../common/js/home' import { bd_encrypt } from '../../common/js/map' import { cur_dateTime, compare, sortNum } from '../../common/js/time' import { navigateTo } from '../../common/js/router' var app = getApp(); Page({ data: { imageUrl, city: '', //城市 addressIng: '', // 定位地址 canUseAddress: [], // 我的地址 nearAddress: [], // 附近地址 searchedAddress: [], //搜索地址 showClear: false, isSuccess: false, info: '', // 一条地址信息 inputAddress: '', //手动输入的地址 loginOpened: false, showSearched: false, showSearchedMask: false }, onLoad(e) { // console.log(app.globalData.position) if (e.type) { this.setData({ isSuccess: true, city: app.globalData.position.city || app.globalData.city, addressIng: app.globalData.address, info: app.globalData.position }) } }, onShow() { const _sid = my.getStorageSync({ key: '_sid' }).data; //获取用户收货地址,一次性获取下来 if (_sid) { addressList(_sid, 'normal', location).then((res) => { let arr1 = []; if (res.data.length > 0) { arr1 = res.data.filter(item => item.user_address_is_dispatch == 1) } this.setData({ canUseAddress: arr1 }) }); } if (app.globalData.address) { const lng = my.getStorageSync({ key: 'lng' }).data; const lat = my.getStorageSync({ key: 'lat' }).data; const location = `${lng},${lat}`; this.getAddressList(location, lat, lng); } }, // 切换城市 choosecityTap() { this.setData({ inputAddress: '', searchedAddress: [], showClear: false, showSearched: false, showSearchedMask: false }) my.chooseCity({ showLocatedCity: true, showHotCities: true, success: (res) => { console.log(res) if (res.city.indexOf('市') == res.city.length - 1) { this.setData({ city: res.city }) } else { this.setData({ city: res.city + '市' }) } }, }); }, getFocus() { if (this.data.searchedAddress.length == 0) { this.setData({ showSearchedMask: true, showSearched: false }); } if (this.data.searchedAddress.length > 0) { this.setData({ showSearchedMask: false, showSearched: true }); } }, clearSearch() { this.setData({ searchedAddress: [], showSearchedMask: true, showSearched: false, inputAddress: '', showClear: false, }) }, cancelSearch() { this.setData({ searchedAddress: [], showSearchedMask: false, showSearched: false, inputAddress: '', showClear: false, }) }, handleSearch(e) { this.setData({ inputAddress: e.detail.value }); if (e.detail.value.length > 0) { this.searchShop(); this.setData({ showClear: true }) } else { this.setData({ showSearchedMask: true, showSearched: false, searchedAddress: [], showClear: false }); } }, // 输入地址搜索门店 searchShop() { let that = this; //附近地址列表 if (this.data.city + this.data.inputAddress != '') { let url = `https://api.map.baidu.com/geocoding/v3/?address=${this.data.city}${this.data.inputAddress}&output=json&ak=${ak}` url = encodeURI(url); my.request({ url, success: (res) => { const lng = res.data.result.location.lng; const lat = res.data.result.location.lat; const location = `${lng},${lat}`; that.getSearchedAddress(location, lat, lng); }, }); } }, getSearchedAddress(location, lat, lng) { let that = this; //附近地址列表 if (this.data.city + this.data.inputAddress != '') { // let str = `http://api.map.baidu.com/place/v2/search?query=${this.data.inputAddress}&region=${this.data.city}&scope=2&filter=sort_name:distance&output=json&ak=${ak}`; let str = `https://api.map.baidu.com/place/v2/search?query=${this.data.inputAddress}&location=${lat},${lng}&radius=100000&scope=2&output=json&ak=${ak}`; str = encodeURI(str); my.request({ url: str, success: (res) => { if (res.data.status == 0) { this.setData({ searchedAddress: res.data.results, showSearched: true, showSearchedMask: false }) console.log(this.data.searchedAddress) } else { this.setData({ searchedAddress: [], showSearched: true, showSearchedMask: false }) } }, fail: (rej) => { this.setData({ searchedAddress: [], showSearched: true, showSearchedMask: false }) } }); } }, //附近地址列表 getAddressList(location, lat, lng) { //附近列表中没有传出当前的 地区id,城市id等参数 // 百度附近POI let str = `https://api.map.baidu.com/place/v2/search?query=房地产$金融$公司企业$政府机构$医疗$酒店$美食$生活服务$教育培训$交通设施&location=${lat},${lng}&radius=1000&output=json&page_size=50&page_num=0&ak=${ak}`; str = encodeURI(str); my.request({ url: str, success: (res) => { if (res.data.status == 0) { this.setData({ nearAddress: res.data.results }) } else { this.setData({ nearAddress: [] }) } }, fail: (rej) => { this.setData({ nearAddress: [] }) } }); }, // 重新定位 rePosition() { my.showLoading(); var that = this; my.getLocation({ type: 3, success(res) { my.hideLoading(); const mapPosition = bd_encrypt(res.longitude, res.latitude); my.setStorageSync({ key: 'lat', // 缓存数据的key data: mapPosition.bd_lat, // 要缓存的数据 }); my.setStorageSync({ key: 'lng', // 缓存数据的key data: mapPosition.bd_lng, // 要缓存的数据 }); app.globalData.address = res.pois[0].name; app.globalData.position = res; my.showToast({ content: '定位成功!' }) that.setData({ city: res.city, addressIng: res.pois[0].name, info: res, isSuccess: true }) that.getLbsShop(mapPosition.bd_lng, mapPosition.bd_lat, res.pois[0].name); that.getNearbyShop(mapPosition.bd_lng, mapPosition.bd_lat, res.pois[0].name); that.getAddressList((mapPosition.bd_lng, mapPosition.bd_lat), mapPosition.bd_lat, mapPosition.bd_lng); }, fail() { my.hideLoading(); that.setData({ isSuccess: false }) } }) }, //选择附近地址 switchAddress(e) { //手动定位没有地址 if (e.currentTarget.dataset.type == '1' && !this.data.isSuccess && e.currentTarget.dataset.address == '') { my.showToast({ content: '定位失败,请选择其他收货地址!' }); return } //手动定位获得了地址 //这里分两种情况1原先不变地址,2重新定位后地址 // if (e.currentTarget.dataset.type=='1' && this.data.isSuccess && e.currentTarget.dataset.address != '') { // //需要重新获得外卖,和自提门店 // //这里没有做 // my.switchTab({ // url: '/pages/home/goodslist/goodslist' // }); // return // } //定位失败 let mapPosition = ''; let lng, lat; switch (parseInt(e.currentTarget.dataset.type)) { case 1: lng = e.currentTarget.dataset.info.longitude || e.currentTarget.dataset.info.user_address_lbs_baidu.split(',')[0]; lat = e.currentTarget.dataset.info.latitude || e.currentTarget.dataset.info.user_address_lbs_baidu.split(',')[1] mapPosition = bd_encrypt(lng, lat); break; case 3: lng = e.currentTarget.dataset.info.location.lng; lat = e.currentTarget.dataset.info.location.lat; mapPosition = bd_encrypt(e.currentTarget.dataset.info.location.lng, e.currentTarget.dataset.info.location.lat); break; } my.setStorageSync({ key: 'lat', // 缓存数据的key data: mapPosition.bd_lat, // 要缓存的数据 }); my.setStorageSync({ key: 'lng', // 缓存数据的key data: mapPosition.bd_lng, // 要缓存的数据 }); app.globalData.position = e.currentTarget.dataset.info; app.globalData.position.city = e.currentTarget.dataset.info.city; app.globalData.position.district = e.currentTarget.dataset.info.area; app.globalData.position.cityAdcode = ''; app.globalData.position.districtAdcode = ''; app.globalData.shopIng = null; if (e.currentTarget.dataset.info.location) { app.globalData.position.latitude = e.currentTarget.dataset.info.location.lat; app.globalData.position.longitude = e.currentTarget.dataset.info.location.lng; } else { app.globalData.position.latitude = lat; app.globalData.position.longitude = lng; } app.globalData.position.province = e.currentTarget.dataset.info.province; //额外添加两个 app.globalData.city = e.currentTarget.dataset.info.city; app.globalData.province = e.currentTarget.dataset.info.province; let address = ''; if (e.currentTarget.dataset.type == 1) { address = e.currentTarget.dataset.address; } else { address = e.currentTarget.dataset.info.name; } this.getLbsShop(app.globalData.position.longitude, app.globalData.position.latitude, address, 'click'); this.getNearbyShop(app.globalData.position.longitude, app.globalData.position.latitude, address, 'click') }, // 选择我的收货地址 switchPositionAddress(e) { //我的收获地址未能传递地区id,城市id等参数。 // console.log(e) let position = e.currentTarget.dataset.info.user_address_lbs_baidu.split(','); my.setStorageSync({ key: 'lat', // 缓存数据的key data: position[1], // 要缓存的数据 }); my.setStorageSync({ key: 'lng', // 缓存数据的key data: position[0] // 要缓存的数据 }); app.globalData.position = e.currentTarget.dataset.info; app.globalData.position.cityAdcode = ''; app.globalData.position.districtAdcode = ''; app.globalData.shopIng = null; this.getLbsShop(position[0], position[1], e.currentTarget.dataset.info.user_address_map_addr, 'click'); this.getNearbyShop(position[0], position[1], e.currentTarget.dataset.info.user_address_map_addr, 'click') }, // 外卖附近门店 async getLbsShop(lng, lat, address, str) { let that = this; const location = `${lng},${lat}` const shopArr1 = []; const shopArr2 = []; app.globalData.address = address; GetLbsShop(lng, lat).then((res) => { // console.log(res) if (res.code == 100 && res.data.shop_list.length > 0) { let shop_list = res.data.shop_list; my.hideLoading(); for (let i = 0; i < shop_list.length; i++) { const status = cur_dateTime(shop_list[i].start_time, shop_list[i].end_time); app.globalData.isOpen = status // 判断是否营业 if (status == 1 || status == 3) { shopArr1.push(shop_list[i]); } else { shopArr2.push(shop_list[i]); } } // 按照goods_num做降序排列 let shopArray = shopArr1.concat(shopArr2); shopArray.sort((a, b) => { var value1 = a.goods_num, value2 = b.goods_num; if (value1 <= value2) { return a.distance - b.distance; } return value2 - value1; }); shopArray[0]['jingxuan'] = true; app.globalData.position.cityAdcode = shopArray[0].city_id app.globalData.position.districtAdcode = shopArray[0].district_id my.setStorageSync({ key: 'takeout', data: shopArray }); // 保存外卖门店到本地 that.getNearbyShop(lng, lat, address); if (str) { my.switchTab({ url: '/pages/home/goodslist/goodslist' }) } } else if (res.code == 100 && res.data.shop_list.length == 0) { // 无外卖去自提 this.setData({ loginOpened: true }) app.globalData.type = 2; //存储app.golbalData my.setStorageSync({ key: 'appglobalData', data: app.globalData }); // // my.reLaunch({ // url: '/pages/home/goodslist/goodslist' // }) } else { my.alert({ content: '网络错误,请重试!' }) } }).catch(() => { my.alert({ content: '网络错误,请重试!' }) }) }, // 自提附近门店 async getNearbyShop(lng, lat, address) { const location = `${lng},${lat}` const str = new Date().getTime(); my.request({ url: `https://api.map.baidu.com/geosearch/v3/nearby?geotable_id=${geotable_id}&location=${lng}%2C${lat}&ak=${ak}&radius=3000&sortby=distance%3A1&page_index=0&page_size=50&_=${str}`, success: (res) => { // 3公里有门店 if (res.data.contents && res.data.contents.length > 0) { this.getSelf(res.data.contents, address) } else { // 没有扩大搜索范围到1000000公里 my.request({ url: `https://api.map.baidu.com/geosearch/v3/nearby?geotable_id=${geotable_id}&location=${lng}%2C${lat}&ak=${ak}&radius=1000000000&sortby=distance%3A1&page_index=0&page_size=50&_=${str}`, success: (conf) => { if (conf.data.contents && conf.data.contents.length > 0) { this.getSelf(conf.data.contents, address) } else { // 无自提门店 } }, }); } }, }); }, // 获取自提门店信息 getSelf(obj, address) { let shopArr1 = []; let shopArr2 = []; NearbyShop(JSON.stringify(obj)).then((res) => { my.hideLoading(); for (let i = 0; i < res.length; i++) { let status = cur_dateTime(res[i].start_time, res[i].end_time); app.globalData.isOpen = status // 判断是否营业 if (status == 1 || status == 3) { shopArr1.push(res[i]); } else { shopArr2.push(res[i]); } } // 根据距离最近排序 shopArr1.sort(sortNum('distance')); shopArr2.sort(sortNum('distance')); const shopArray = shopArr1.concat(shopArr2); shopArray[0]['jingxuan'] = true; app.globalData.address = address; my.setStorageSync({ key: 'self', data: shopArray }); // 保存自提门店到本地 }) }, // 新增地址 addAddressTap() { // 判断 是否登录 let userInfo = myGet('userInfo'); if (userInfo && userInfo.user_id && userInfo.user_id != '') { app.globalData.addAddressInfo=null; navigateTo({ url: "/package_my/pages/myaddress/addaddress/addaddress" }); } else { navigateTo({ url: '/pages/login/auth/auth' }); } }, // 去自提 onModalRepurse() { app.globalData.type = 2; my.removeStorageSync({ key: 'takeout', // 缓存数据的key }); let shopArray = my.getStorageSync({ key: 'self' }).data; app.globalData.position.cityAdcode = shopArray[0].city_id; app.globalData.position.districtAdcode = shopArray[0].district_id; this.setData({ loginOpened: false }) my.switchTab({ url: '/pages/home/goodslist/goodslist' }) }, //取消按钮 onModalCancel(){ this.setData({ loginOpened: false }) app.globalData.type = 1; } });<file_sep>/package_vip/pages/waitpay/waitpay.js import { imageUrl, imageUrl2 } from '../../../pages/common/js/baseUrl' import { log, ajax, getRegion, getAddressId } from '../../../pages/common/js/li-ajax' import { reqOrderInfo, reqConfirmOrder, reqPay } from '../../../pages/common/js/vip' import getDistance from '../../../pages/common/js/getdistance' let region = [] Page({ data: { a: 0, imageUrl, imageUrl2, // 地址 user_address_name: '', sex: 0, user_address_phone: '', address: '', shop_id: '', shop_name: '', // d: { // "id": "17", // "order_point": "1", // "order_amount": 0, // "exchange_type": "1", // "uid": "295060", // "express_fee": 0.01, // "express_type": "2", // "receive_type": "1", // "order_total_amount": 0.01, // "goods_name": "33", // "goods_pic": "/static/check/image/goods_point/0PqRYnGJ1XUZRKuQ.jpg", // "order_sn": "jwd03190301s175060", // "limit_pay_minute": -3907, // "limit_pay_second": -29, // "code": 'xxx' // }, selectShop: false, selectAddress: false, user_address_map_addr: '', addressList: region, provinceList: [], cityList: [], countryList: [], defaultAddress: [0, 0, 0], shopList: [], user_address_id: '', user_address_detail_address: '', province: '', city: '', district: '', _shopList: '' }, async onLoad(e) { let { order_sn, user_address_map_addr, user_address_id, user_address_name, user_address_phone, province, city, district, shop_id,shop_name, user_address_detail_address } = e console.log(shop_name,province,city,district); this.setData({ order_sn, user_address_map_addr, user_address_id, user_address_name, user_address_phone, province, city, district, shop_id, shop_name:shop_name?shop_name:'请选择领取门店', user_address_detail_address, address: district?(province + '-' + city + '-' + district):'请选择领取城市' }) region = await getRegion() this.getAddressList() }, async onShow(){ const{order_sn} = this.data await this.getOrderInfo({ order_sn }) }, onUnload() { clearInterval(this.data.a) this.setData({ a: -1 }) this.setData = () => { } }, onHide() { clearInterval(this.data.a) this.setData({ a: -1 }) }, /** * @function 添加地址 */ toAddAddress() { const { order_sn } = this.data my.navigateTo({ url: '/package_my/pages/myaddress/myaddress?order_sn=' + order_sn }); }, /** * @function 获取公众号支付前订单详情 */ async getOrderInfo(order_sn) { let { showSelectAddress, a } = this.data; let { code, data: { order_sn: _order_sn, limit_pay_minute, limit_pay_second, ...rest } } = await reqOrderInfo(order_sn) if (code === 100) { this.setData({ d: { _order_sn, limit_pay_minute, limit_pay_second, ...rest } }) a = setInterval(() => { --limit_pay_second if (limit_pay_minute === 0 && limit_pay_second == 0) { return my.navigateBack({ delta: 1 }); } if (limit_pay_second <= 0) { --limit_pay_minute limit_pay_second = 59 } this.setData({ a, 'd.limit_pay_minute': limit_pay_minute, 'd.limit_pay_second': limit_pay_second }) }, 1000) } }, /** * @function 获取当前省市区列表 */ getAddressList() { let [curProvince, curCity, curCountry] = this.data.defaultAddress; let provinceList = region.map(({ addrid, name }) => ({ addrid, name })) let cityList = region[curProvince].sub let countryList = cityList[curCity].sub this.setData({ provinceList, cityList, countryList }) }, /** * @function 修改地址 */ changeAddress(e) { let [curProvince, curCity, curCountry] = this.data.defaultAddress; let cur; if (e) { cur = e.detail.value } else { cur = this.data.defaultAddress } if (cur[0] != curProvince) { cur = [cur[0], 0, 0] } if (cur[1] != curCity) { cur = [cur[0], cur[1], 0] } let province = region[cur[0]].name; let city = region[cur[0]].sub[cur[1]].name; let district = (region[cur[0]].sub[cur[1]].sub[cur[2]] && region[cur[0]].sub[cur[1]].sub[cur[2]].name) || '' this.setData({ defaultAddress: cur, address: province + '-' + city + '-' + district, province, city, district }, () => this.getAddressList() ) }, /** * @function 展示地址选择列表 */ showSelectAddress() { this.setData({ selectAddress: true }) }, /** * @function 隐藏地址选择列表,并确认改变 */ hideSelectAddress() { this.changeAddress() this.setData({ selectAddress: false }) }, /** * @function input表单收集数据 */ handelChange(e) { let { key } = e.currentTarget.dataset; let { value } = e.detail; this.setData({ [key]: value }) }, /** * @function 搜索 */ async search(e) { const { _shopList } = this.data; const { value } = e.detail; let shopList = _shopList.filter(({ shop_name }) => shop_name.includes(value)) this.setData({ shopList }) }, /** * @function 获取当前的商店列表,排序并展示 */ async doSelectShop() { my.hideBackHome() let { address } = this.data; if (!address || address=="请选择领取城市") { return my.showToast({ content: '请先选择领取城市' }); } let [curProvince, curCity, curCountry] = this.data.defaultAddress; let province = region[curProvince].addrid; let city = region[curProvince].sub[curCity].addrid; let district = (region[curProvince].sub[curCity].sub[curCountry] && region[curProvince].sub[curCity].sub[curCountry].addrid) || 0 let parentid = province + ',' + city + ',' + district log(parentid) let res = await ajax('/mini/game/shop', { parentid }) let lat = my.getStorageSync({ key: 'lat' }).data; let lng = my.getStorageSync({ key: 'lng' }).data; if (!lat || !lng) { let { longitude, latitude } = await getAddressId() lat = latitude lng = longitude } if (res.CODE == 'A100') { let shopList = res.DATA .map(({ shop_gd_latitude, shop_gd_longitude, ...rest }) => { let distance = getDistance(lng, lat, shop_gd_longitude, shop_gd_latitude).toFixed(0) return { _distance: distance, distance: distance > 1000 ? (distance / 1000).toFixed(1) + '千' : distance, ...rest } }) .sort((a, b) => a._distance - b._distance) this.setData({ selectShop: true, shopList, _shopList: shopList }) } }, /** * @function 选择商店并返回 */ sureSelectShop(e) { let { shop_id, shop_name } = e.currentTarget.dataset; this.setData({ shop_id, shop_name, selectShop: false }) }, /** * @function 确认订单 */ async confirmOrder() { let { d, order_sn, user_address_id, province, city, district, user_address_phone, shop_id, shop_name, user_address_name } = this.data; // 如果商品是实物并且发货方式到店领取 if (d.receive_type == 1) { let params = { order_sn, user_address_name, user_address_phone, province, city, district, shop_id, shop_name, } let { code, msg } = await reqConfirmOrder(params) if (code !== 100) { my.showToast({ content: msg }); } return code === 100 } // 邮递 if (d.receive_type == 2) { let params = { order_sn, user_address_name, user_address_phone, user_address_id, province, city, district, } let { code, msg } = await reqConfirmOrder(params) if (code !== 100) { my.showToast({ content: msg }); } return code === 100 } }, /** * @function 支付订单 */ async pay() { let { order_sn } = this.data; return await reqPay(order_sn) }, /** * @function 马上支付 */ async payNow() { let { d, order_sn, user_address_id, province, city, district, user_address_phone, shop_id, shop_name, user_address_name } = this.data; if (d.receive_type == 1) { if (!order_sn || !user_address_name || !user_address_phone || !province || !city || !district || !shop_id || !shop_name ) { return } } if (d.receive_type == 2) { if (!order_sn || !user_address_name || !user_address_phone || !province || !city || !district ) { return } } let confirm = await this.confirmOrder() log(confirm) if (!confirm) { return } if (d.order_total_amount == 0) { return my.redirectTo({ url: '../finish/finish?id=' + d.id + '&fail=' + false }); } let r = await this.pay() log(r.data.tradeNo) if (r.code === 0) { my.tradePay({ tradeNO: r.data.tradeNo, // 调用统一收单交易创建接口(alipay.trade.create),获得返回字段支付宝交易号trade_no success: res => { if (res.resultCode == 9000) { return my.redirectTo({ url: '../finish/finish?id=' + d.id + '&fail=' + false }); } // 用户取消支付 if (res.resultCode == 6001) { return my.redirectTo({ url: '../exchangelist/exchangedetail/exchangedetail?id=' + d.id }); } return my.redirectTo({ url: '../finish/finish?id=' + d.id + '&fail=' + true }); }, fail: res => { log('fail') return my.redirectTo({ url: '../finish/finish?id=' + d.id + '&fail=' + true }); } }); } }, /** * @function 键盘失去焦点 */ blur(e) { log(e, this) } }); <file_sep>/package_my/pages/coupon/changedetails/changedetails.js import { exchangedetail } from '../../../../pages/common/js/home' import { imageUrl2 } from '../../../../pages/common/js/baseUrl' import { parseData, contact } from '../../../../pages/common/js/li-ajax' Page({ data: { exchangeObj: {}, imageUrl2, source:'' }, onLoad(e) { const { gift_code_id, gift_id, order_id,source } = e const _sid = my.getStorageSync({ key: '_sid' }).data; this.getDetail({ _sid, gift_code_id, gift_id, order_id }); this.setData({ source }) }, contact, getDetail({ _sid, gift_code_id, gift_id, order_id }) { exchangedetail(_sid, gift_code_id, gift_id, order_id).then(async (res) => { if (res.CODE == 'A100') { res.DATA.gift_application_store = await parseData(res.DATA.gift_application_store); res.DATA.gift_desciption = await parseData(res.DATA.gift_desciption); res.DATA.gift_exchange_process = await parseData(res.DATA.gift_exchange_process) res.DATA.gift_service_telephone = await parseData(res.DATA.gift_service_telephone) this.setData({ exchangeObj: res.DATA }) } }) }, // 复制 handleCopy(e) { my.setClipboard({ text: e.currentTarget.dataset.code, success() { my.showToast({ type: 'success', content: '操作成功' }); } }); }, }); <file_sep>/package_my/pages/mycenter/bindphone/bindphone.js import {sendCode} from '../../../../pages/common/js/login' import {checkPhoneCode,resetPhone} from '../../../../pages/common/js/my' let timeCount Page({ data: { focus: false, value:'', type:'1', phone:'', countTime:60, isnew:false }, onLoad(e) { var _sid = my.getStorageSync({ key: '_sid', // 缓存数据的key }).data; this.setData({ phone:e.phone, type:e.type, _sid:_sid }) this.timeDate() }, // 倒计时60 timeDate(e){ var that = this clearInterval(timeCount) that.setData({ isnew:true, countTime:60, }) this.sendCodeFN() var time = 60 timeCount = setInterval(function(){ time-- that.setData({ countTime:time }) if(time==0){ that.setData({ isnew:false }) clearInterval(timeCount) } },1000) }, sendCodeFN(){ var data = { _sid:this.data._sid, phone:this.data.phone } sendCode(data).then(res=>{ if(res.code==0){ //发送验证码成功 }else{ my.showToast({ type: 'none', content: res.msg, duration: 2000 }); } }) }, bindFocus() { // blur 事件和这个冲突 console.log(this.data.focus) setTimeout(() => { this.onFocus(); }, 100); }, onFocus() { this.setData({ focus: true, }); }, onBlur() { this.setData({ focus: false, }); }, inputValue(e){ var value = e.detail.value this.setData({ value:value }) }, //页面跳转 bindphone(e){ //console.log(getCurrentPages()) var that = this if(that.data.type==1){//旧手机号 checkPhoneCode(this.data._sid,this.data.phone,this.data.value).then(res=>{ if(res.code==0){ my.navigateTo({ url:"/package_my/pages/mycenter/newphone/newphone?sid="+that.data._sid }); }else{ my.showToast({ type: 'none', content: res.msg, duration: 2000 }); } }) }else{//新手机号 resetPhone(this.data._sid,this.data.phone,this.data.value).then(res=>{ if(res.code==0){ my.navigateBack({ delta: 4 }) }else{ my.showToast({ type: 'none', content: res.msg, duration: 2000 }); } }) } }, onHide(){ // clearInterval(timeCount) }, onUnload() { // 页面被关闭 clearInterval(timeCount) }, }); <file_sep>/pages/home/orderform/chooseCoupon/chooseCoupon.js import { imageUrl, imageUrl2, baseUrl } from '../../../common/js/baseUrl' import { couponsList, exchangeCode } from '../../../common/js/home' import { formatTime } from '../../../common/js/time' import { getSid, log, ajax } from '../../../common/js/li-ajax' var app = getApp(); Page({ data: { open2: false, codeImg: '', active: [], activeIndex: '', imageUrl, imageUrl2, couponList: [], // 优惠券列表 defaultcoupon: '', // 默认选中的优惠券 couponChoosed: '', //coupon.code 选择的优惠按 is_allow_coupon: false //是否可以享受优惠 }, onLoad(e) { if(((e.coupon && e.coupon!='')?e.coupon:'')==''){ app.globalData.notUse = 1; }else{ app.globalData.notUse = 0; } this.setData({ couponChoosed:((e.coupon && e.coupon!='')?e.coupon:''), is_allow_coupon:e.is_allow_coupon=='true' }) const _sid = my.getStorageSync({ key: '_sid' }).data; this.getCouponsList(_sid, e.money / 100); }, onHide() { this.closeModel(); }, onShow(){ }, // 优惠券 getCouponsList(_sid, money) { let that=this; couponsList(_sid, 'use', money, my.getStorageSync({ key: 'shop_id' }).data).then((res) => { res.DATA.use.forEach(item => { item.start_time = formatTime(item.start_time, 'Y-M-D'); item.end_time = formatTime(item.end_time, 'Y-M-D'); item.toggleRule = false, item.isChecked = false }) // 已选中的优惠券 if (that.data.couponChoosed!='') { //app.globalData.coupon_code that.setData({ couponList: res.DATA.use, couponChoosed: ((app.globalData.notUse == 0)?that.data.couponChoosed:'') //用户不用优惠券的时候要保持空 }) } else { // 默认不选择优惠券 that.setData({ couponList: res.DATA.use, couponChoosed: '' //this.data.couponChoosed }) } }) }, //选择优惠券 chooseCouponed(e) { // let couponChoosed = {}; // couponChoosed[`e${e.currentTarget.dataset.index}`] = e.currentTarget.dataset.coupon_code; if(this.data.is_allow_coupon){//可以优惠 if (this.data.couponChoosed == e.currentTarget.dataset.coupon_code) { app.globalData.notUse = 1; this.setData({ couponChoosed: '' }) app.globalData.coupon_code =''; } else { app.globalData.notUse = 0; this.setData({ couponChoosed:e.currentTarget.dataset.coupon_code }) app.globalData.coupon_code = e.currentTarget.dataset.coupon_code; } }else{//不能优惠 this.setData({ couponChoosed: '' }) app.globalData.coupon_code = ''; app.globalData.notUse = 1; } my.navigateBack({ url: '/pages/home/orderform/orderform' }); }, //不能选的优惠券 chooseCouponed_noused(e){ }, /** * @function 展示CODE */ async showCode(e) { let { code } = e.currentTarget.dataset let _sid = await getSid() let codeImg = baseUrl + '/juewei-api/coupon/getQRcode?' + '_sid=' + _sid + '&code=' + code this.setData({ open2: true, codeImg }) }, /** * @function 关闭弹窗 */ closeModel() { this.setData({ open2: false }) }, /** * @function 核销 */ async wait() { let res = await ajax('/juewei-api/order/waiting', {}, 'GET') if (res.code == 0) { return this.closeModel() } return my.showToast({ content: res.msg, }); }, /** * @function 展示规则 */ toggleRule(e) { const { index } = e.currentTarget.dataset; let { couponList } = this.data if (couponList[index].toggleRule) { couponList[index].toggleRule = false } else { couponList.forEach(item => { item.toggleRule = false; }) couponList[index].toggleRule = true } this.setData({ couponList }) } }); // 切换是否选中 // selectTapTrue(e) { // let couponChoosed = {}; // couponChoosed[`e${e.currentTarget.dataset.index}`] = e.currentTarget.dataset.code; // app.globalData.notUse = 0; // this.setData({ // couponChoosed // }) // }, // selectTapFalse(e) { // app.globalData.notUse = 1; // this.setData({ // couponChoosed: {} // }) // }, <file_sep>/pages/home/orderform/selectaddress/selectaddress.js import { imageUrl, geotable_id, ak } from '../../../common/js/baseUrl' import { useraddress, GetLbsShop, NearbyShop } from '../../../common/js/home' import { cur_dateTime, sortNum } from '../../../common/js/time' var app = getApp(); Page({ data: { imageUrl, addressList: [], mask: false, modalShow: false, addressListNoUse: [], address_id: '', lng: '', lat: '', address: '' }, onLoad(e) { // if(e.type) { // this.setData({ // orderType:e.orderType // }) // } }, onShow() { this.getAddress(); }, // 选择不在配送范围内的地址 chooseNewAddress(e) { this.setData({ mask: true, modalShow: true, lng: e.currentTarget.dataset.lng, lat: e.currentTarget.dataset.lat, address: e.currentTarget.dataset.address }) }, onCounterPlusOne(data) { if (data.type == 1) { my.setStorageSync({ key: 'lng', // 缓存数据的key data: this.data.lng, // 要缓存的数据 }); my.setStorageSync({ key: 'lat', // 缓存数据的key data: this.data.lat, // 要缓存的数据 }); this.getLbsShop(this.data.lng, this.data.lat, this.data.address); this.getNearbyShop(this.data.lng, this.data.lat, this.data.address) } this.setData({ mask: data.mask, modalShow: data.modalShow }) }, getAddress() { useraddress(my.getStorageSync({ key: 'shop_id' }).data).then((res) => { let addressList = [], addressListNoUse = []; for (let value of res.data) { value.lng = value.user_address_lbs_baidu.split(',')[0]; value.lat = value.user_address_lbs_baidu.split(',')[1]; if (value.is_dis == 1) { addressList.push(value) } else { addressListNoUse.push(value) } } this.setData({ addressList, addressListNoUse }) }) }, chooseAddress(e) { app.globalData.address_id = e.currentTarget.dataset.id; my.navigateBack({ url: '/pages/home/orderform/orderform', // 需要跳转的应用内非 tabBar 的目标页面路径 ,路径后可以带参数。参数规则如下:路径与参数之间使用 success: (res) => { }, }); }, // 编辑收货地址  editAddress(e) { my.navigateTo({ url: "/package_my/pages/myaddress/addaddress/addaddress?Id=" + e.currentTarget.dataset.id }); }, // 外卖附近门店 getLbsShop(lng, lat, address) { let that = this; const location = `${lng},${lat}` const shopArr1 = []; const shopArr2 = []; app.globalData.address = address; GetLbsShop(lng, lat).then((res) => { // console.log(res) if (res.code == 100 && res.data.shop_list.length > 0) { let shop_list = res.data.shop_list; for (let i = 0; i < shop_list.length; i++) { const status = cur_dateTime(shop_list[i].start_time, shop_list[i].end_time); app.globalData.isOpen = status // 判断是否营业 if (status == 1 || status == 3) { shopArr1.push(shop_list[i]); } else { shopArr2.push(shop_list[i]); } } // 按照goods_num做降序排列 let shopArray = shopArr1.concat(shopArr2); shopArray.sort((a, b) => { var value1 = a.goods_num, value2 = b.goods_num; if (value1 <= value2) { return a.distance - b.distance; } return value2 - value1; }); shopArray[0]['jingxuan'] = true; my.setStorageSync({ key: 'takeout', data: shopArray }); // 保存外卖门店到本地 that.getNearbyShop(lng, lat, address); my.switchTab({ url: '/pages/home/goodslist/goodslist' }) } else if(res.code == 100 && res.data.shop_list.length == 0){ // 无外卖去自提 this.setData({ loginOpened: true }) app.globalData.type = 2; //存储app.golbalData my.setStorageSync({ key: 'appglobalData', data: app.globalData }); // // my.reLaunch({ // url: '/pages/home/goodslist/goodslist' // }) }else { my.alert({content: '网络错误,请重试!'}) } }).catch(()=> { my.alert({content: '网络错误,请重试!'}) }) }, onModalRepurse() { app.globalData.type = 2; my.removeStorageSync({ key: 'takeout', // 缓存数据的key }); let shopArray = my.getStorageSync({ key: 'self' }).data; app.globalData.position.cityAdcode = shopArray[0].city_id; app.globalData.position.districtAdcode = shopArray[0].district_id; this.setData({ loginOpened: false }) my.switchTab({ url: '/pages/home/goodslist/goodslist' }) }, // 自提附近门店 getNearbyShop(lng, lat, address) { const location = `${lng},${lat}` const str = new Date().getTime(); my.request({ url: `https://api.map.baidu.com/geosearch/v3/nearby?geotable_id=${geotable_id}&location=${lng}%2C${lat}&ak=${ak}&radius=3000&sortby=distance%3A1&page_index=0&page_size=50&_=${str}`, success: (res) => { // 3公里有门店 if (res.data.contents && res.data.contents.length > 0) { this.getSelf(res.data.contents, address) } else { // 没有扩大搜索范围到1000000公里 my.request({ url: `https://api.map.baidu.com/geosearch/v3/nearby?geotable_id=${geotable_id}&location=${lng}%2C${lat}&ak=${ak}&radius=1000000000&sortby=distance%3A1&page_index=0&page_size=50&_=${str}`, success: (conf) => { if (conf.data.contents && conf.data.contents.length > 0) { this.getSelf(conf.data.contents, address) } else { // 无自提门店 } }, }); } }, }); }, // 自提 getSelf(obj, address) { let shopArr1 = []; let shopArr2 = []; NearbyShop(JSON.stringify(obj)).then((res) => { for (let i = 0; i < res.length; i++) { let status = cur_dateTime(res[i].start_time, res[i].end_time); app.globalData.isOpen = status // 判断是否营业 if (status == 1 || status == 3) { shopArr1.push(res[i]); } else { shopArr2.push(res[i]); } } // 根据距离最近排序 shopArr1.sort(sortNum('distance')); shopArr2.sort(sortNum('distance')); const shopArray = shopArr1.concat(shopArr2); shopArray[0]['jingxuan'] = true; app.globalData.address = address; my.setStorageSync({ key: 'self', data: shopArray }); // 保存自提门店到本地 }) }, }); <file_sep>/package_my/pages/onlineservice/onlineservice.js import { serviceUrl } from '../../../pages/common/js/baseUrl' var app = getApp() Page({ data: { userid:'', phone:'', nickname:'', url:'', }, onLoad() { let userid='',nickname='',phone=''; userid = (my.getStorageSync({ key: 'user_id' }).data || ''); nickname = (my.getStorageSync({ key: 'nick_name' }).data || ''); phone = (my.getStorageSync({ key: 'phone' }).data || ''); this.setData({ userid: userid, nickname: nickname, phone: phone, url: serviceUrl +'/m/shop/onlineservice.html?uid='+encodeURIComponent(userid)+'&name='+ encodeURIComponent(nickname) +'&mobile='+encodeURIComponent(phone)+'&channel='+encodeURIComponent('支付宝小程序') }); }, onShow(){ }, onmessage(e){ // my.alert({ // content: '拿到数据'+JSON.stringify(e), // alert 框的标题 // }); } }); <file_sep>/pages/common/js/vip.js import { ajax } from './li-ajax' /** * @function 获取目录 */ export const reqCategory = type => ajax('/mini/vip/wap/category/category', { type }, 'POST') /** * @function 获取banner图 */ export const reqBanner = bannerListOption => ajax('/mini/vip/wap/banner/banner_list', bannerListOption) /** * @function 获取商品列表 */ export const reqGoodsList = goodslistOption => ajax('/mini/vip/wap/goods/goods_list', goodslistOption) /** * @function getPositionList */ export const reqPositionList = positionListOption => ajax('/mini/vip/wap/show_position/list', positionListOption) /** * @function 获取用户积分 */ export const reqUserPoint = () => ajax('/mini/user/user_point') /** * @function 获取礼包列表 */ export const reqCouponsList = (get_type = 'new_user') => ajax('/mini/coupons/list', { get_type }) /** * @function 获取当商品面详情 */ export const reqDetail = id => ajax('/mini/vip/wap/goods/goods_detail', { id }) /** * @function 创建订单 */ export const reqCreateOrder = params => ajax('/mini/vip/wap/trade/create_order', params) /** * @function 确认订单 */ export const reqConfirmOrder = params => ajax('/mini/vip/wap/trade/confirm_order', params) /** * @function 支付订单 */ export const reqPay = order_no => ajax('/juewei-service/payment/AliMiniPay', { order_no }) /** * @function 获取订单列表 */ export const reqOrderList = ({ page_num, page_size = 10 }) => ajax('/mini/vip/wap/order/order_list', { page_num, page_size }) /** * @function 获取订单详情 */ export const reqOrderDetail = id => ajax('/mini/vip/wap/order/order_detail', { id }) /** * @function 取消订单 */ export const reqCancelOrder = order_sn => ajax('/mini/vip/wap/trade/cancel_order', { order_sn }, 'POST') /** * @function 核销 */ export const reqWait = () => ajax('/juewei-api/order/waiting', {}, 'GET') /** * @function 获取积分详情 */ export const reqPointList = ({ pagenum, pagesize }) => ajax('/mini/point_exchange/point_list', { pagenum, pagesize }, 'GET') /** * @function 获取公众号支付前订单详情 */ export const reqOrderInfo = order_sn => ajax('/mini/vip/wap/order/order_info', order_sn) <file_sep>/pages/vip/index/index.js import { imageUrl, imageUrl2 } from '../../common/js/baseUrl' import { getSid, log, getNavHeight, getAddressId } from '../../common/js/li-ajax' import { reqCategory, reqBanner, reqGoodsList, reqPositionList, reqUserPoint, reqCouponsList } from '../../common/js/vip' import { upformId } from '../../common/js/time' const app = getApp() Page({ data: { imageUrl, imageUrl2, finish: false, toast: false, _sid: '', navHeight: '', loginFinsih: false, menuTop: 0, menuFixed: false, shop_id: '', district_id: 110105, cate_id: 0, page_num: 1, page_size: 10000, company_id: 1, city_id: 110100, release_channel: 1, cur: 0, userPoint: '', bannerList: [], positionList: [], new_user: [], list: [], goodsList: [], }, onLoad() { }, async onShow() { await this.getUserPoint() let _sid = await getSid() //获取当前所需要的分子公司id,城市id,门店id,区域id const { company_sale_id: company_id, city_id, shop_id, district_id } = (app.globalData.shopTakeOut || my.getStorageSync({ key: 'takeout' }).data[0]); let navHeight = getNavHeight() this.setData({ _sid, navHeight, city_id, district_id, company_id, shop_id, loginFinsih: true, cur: 0 }, async () => { this.getBanner() this.getPositionList() await this.getCategory() await this.getGoodsList() await this.getCouponsList() }) // this.initClientRect() }, /** * @function 修改分类 */ listChange(event) { const { list } = this.data; const { cur } = event.currentTarget.dataset; this.setData({ cur, cate_id: list[cur].id }, () => this.getGoodsList()) }, /** * @function 获取分类 */ async getCategory() { const { cur } = this.data; let res = await reqCategory(1) if (res.code === 100 && res.data && res.data.length>0) { this.setData({ list: res.data, cate_id: res.data[cur].id }) } }, /** * @function 获取轮播 */ async getBanner() { const { city_id, district_id, release_channel } = this.data; const bannerListOption = { city_id, district_id, release_channel } let res = await reqBanner(bannerListOption) if (res.code === 100) { this.setData({ bannerList: res.data }) } }, /** * @function 获取商品列表 */ async getGoodsList() { let { shop_id, district_id, city_id, cate_id, page_num, page_size, } = this.data; let goodslistOption = { shop_id, district_id, city_id, cate_id, page_num, page_size } let res = await reqGoodsList(goodslistOption) if (res.code === 100) { this.setData({ finish: true, goodsList: res.data.data }) } }, /** * @function 获取位置列表 */ async getPositionList() { let { city_id, district_id, company_id, release_channel } = this.data; let positionListOption = { city_id, district_id, company_id, release_channel } let res = await reqPositionList(positionListOption) if (res.code === 100) { if (!res.data.length) { return this.setData({ positionList: [] }) } let { pic_src, link_url } = res.data[0]; let positionList = pic_src.map((pic, index) => { return { pic, url: link_url[index] } }) this.setData({ positionList }) } }, /** * @function 获取用户积分 */ async getUserPoint() { let res = await reqUserPoint() if (res.CODE === 'A100') { this.setData({ userPoint: res.DATA }) } }, /** * @function 显示冻结积分 */ showToast() { this.setData({ toast: true }) }, /** * @function 隐藏冻结积分 */ hideToast() { this.setData({ toast: false }) }, /** * @function 跳转详情页面 */ toDetail(e) { const { id, valid_num, exchange_day_num, exchange_day_vaild_num } = e.currentTarget.dataset log(id, valid_num, exchange_day_num, exchange_day_vaild_num) if ((valid_num) == 0 || ((exchange_day_num - 0) > 0 && (exchange_day_vaild_num) == 0)) { return } console.log('vipdetail=','/package_vip/pages/detail/detail?id=' + id) my.navigateTo({ url: '/package_vip/pages/detail/detail?id=' + id }); }, /** * @function 跳转兑换列表页面 */ toExchangeList() { my.navigateTo({ url: '../../../package_vip/pages/exchangelist/exchangelist' }); }, isloginFn() { my.navigateTo({ url: '/pages/login/auth/auth' }); }, /** * @function 去积分详情页面 */ toPointList() { my.navigateTo({ url: '/package_vip/pages/pointlist/pointlist' }); }, /** * @function banner跳转页面 */ linkTo(e) { const { url } = e.currentTarget.dataset if (url.indexOf('https://') > -1 && url.indexOf('https://') < 4) { if(url.indexOf('https://render.alipay.com') > -1 && url.indexOf('https://render.alipay.com') < 4){ //跳转到生活号页面 my.ap.navigateToAlipayPage({ path: url, success:(res) => { }, fail:(error) => { my.alert({content:'跳转失败:url链接为' + url}); } }) }else{ my.navigateTo({ url: '/pages/webview/webview/webview?url=' + encodeURIComponent(url) }); } }else if(url.indexOf('alipays://') > -1 && url.indexOf('alipays://') < 4){ //跳转到支付宝其他小程序页面 my.ap.navigateToAlipayPage({ path: url, success:(res) => { }, fail:(error) => { my.alert({content:'跳转失败:url链接为' + url}); } }) } else { my.navigateTo({ url: url }); } }, /** * @function 获取礼包列表 */ async getCouponsList() { let res = await reqCouponsList() if (res.CODE === 'A100') { this.setData({ new_user: res.DATA.new_user }) } else { this.setData({ new_user: [] }) } }, /** * @function 去首页 */ switchTo() { my.switchTab({ url: '/pages/home/goodslist/goodslist', }); }, onSubmit(e) { upformId(e.detail.formId); } // initClientRect() { // my // .createSelectorQuery() // .select('#affix') // .boundingClientRect() // .exec(res=> { // log(res) // this.setData({ // menuTop: res[0].top // }) // }) // }, // onPageScroll: function(scroll) { // if (this.data.menuFixed === (scroll.scrollTop > this.data.menuTop)) return; // this.setData({ // menuFixed: (scroll.scrollTop > this.data.menuTop) // }) // } }); <file_sep>/README.md #支付宝小程序开发说明 ##后台接口url域名 - 见开发文档 ##图片cdn地址链接url域名 ####测试环境 ``` 小图标cdn路径: https://test-wap.juewei.com/m/alimim/ 商品图片和json文件:https://imgcdnjwd.juewei.com/ ``` ####正式环境 ``` 小图标cdn路径: https://wap.juewei.com/m/alimim/ 商品图片和json文件: https://imgcdnjwd.juewei.com/ ``` ##文件结构说明 ``` ├─ pages 主包 ├─ common 公共引用页面(越少越好) | ├─ js 公共js文件夹 | └─ style 公共css文件夹 | └─ common.acss 公共的css样式 | ├─ component 公共模块 | └─ shopcart 购物车模块 | ├─ home 商城文件夹 | ├─ goodslist 商城首页列表页(外卖和自提是一个) | ├─ orderfinish 订单完成页(外卖和自提是一个) | ├─ orderform 确认订单(外卖和自提是一个) | ├─ selecttarget 手动选择定位地址 | └─ switchshop 切换门店功能 | ├─ login 登录文件夹 | ├─ auth 授权登录和手机号填写页,登录首页 | ├─ protocol 用户协议,静态页 | └─ verifycode 手机号验证码页 | ├─ my 我的文件夹 | └─ index 我的首页 | ├─ order 订单文件夹 | └─ list 订单列表首页 | ├─ positon 欢迎定位页 | └─ vip vip文件夹 └─ index vip专享首页 ├─ package_my 我的包 └─pages ├─ coupon 卡券列表页 | ├─ changedetails 兑换详情 | ├─ exchange 兑换页面 | └─ explain 优惠券使用说明 | ├─ membercard 会员卡 | ├─ myaddress 我的收获地址管理 | └─ addaddress 新增我的收获地址 | ├─ mycenter 个人中心设置 | └─ bindphone 从新绑定手机号页面 | ├─ nearshop 附近门店 | └─ onlineservice 在线客服页 ├─ package_order 订单包 └─ pages ├─ comment 用户评价系统(外卖和自提) | └─ orderdetail 订单详情页(外卖和自提) ├─ package_vip vip专享包 └─ pages ├─ detail vip详情页 | ├─ exchangelist 兑换产品记录页面 | └─ exchangedetail 兑换详情页 | ├─ finish 兑换完成页(成功和失败) | ├─ pointlist 积分消耗列表 | └─ rules 积分规则,静态页 | └─ waitpay 待支付页面 ```<file_sep>/pages/home/switchshop/switchshop.js import { imageUrl } from '../../../pages/common/js/baseUrl' import { gd_decrypt } from '../../../pages/common/js/map' var app = getApp(); Page({ data: { imageUrl, longitude: 0,// 地图中心点 latitude: 0, markersArray: [], shopList: [], //门店列表 type: '' }, onLoad(e) { app.globalData.switchClick = true; // 外卖 let data; if (e.type == 1) { data = my.getStorageSync({ key: 'takeout' }).data } // 自提 if (e.type == 2) { data = my.getStorageSync({ key: 'self' }).data; } let hI = 0; if (app.globalData.hI) { hI = app.globalData.hI } let arr = data .map(({ shop_gd_latitude,shop_gd_longitude }) => ({ longitude: shop_gd_longitude, latitude: shop_gd_latitude })) .map((item, index) => { if (index === hI) { return { ...item, iconPath: `${imageUrl}position_map1.png`, markerLevel:10, width: 32, height: 32 } } else { return { ...item, iconPath: `${imageUrl}position_map1.png`, markerLevel:9, width: 15, height: 15 } } }) this.setData({ shopList: data, markersArray: arr, type: e.type }) }, onHide(){ app.globalData.switchClick = null; }, // 选择门店 chooseshop(e) { // console.log(e) app.globalData.shop_id = e.currentTarget.dataset.id; //商店id app.globalData.type = this.data.type; //外卖自提 app.globalData.hI = e.currentTarget.dataset.index; app.globalData.shopIng = e.currentTarget.dataset.shopIng; app.globalData.position.cityAdcode = e.currentTarget.dataset.shopIng.city_id; app.globalData.position.districtAdcode = e.currentTarget.dataset.shopIng.district_id; app.globalData.switchClick = null my.navigateBack({ //由于商城首页选用的是navigate 所以这里需要用返回 url: '/pages/home/goodslist/goodslist' }) }, onShow() { let ott = gd_decrypt(my.getStorageSync({ key: 'lng' }).data, my.getStorageSync({ key: 'lat' }).data) this.setData({ longitude: ott.lng, latitude: ott.lat-0.04, }) } }); <file_sep>/pages/home/orderError/orderError.js import {imageUrl} from '../../common/js/baseUrl' Page({ data: { imageUrl }, onLoad() {}, continue(){ my.switchTab({ url: '/pages/home/goodslist/goodslist', // 跳转的 tabBar 页面的路径(需在 app.json 的 tabBar 字段定义的页面)。注意:路径后不能带参数 success: (res) => { }, }); } }); <file_sep>/package_my/pages/mycenter/mycenter.js import { imageUrl } from '../../../pages/common/js/baseUrl' import { getRegion } from '../../../pages/common/js/li-ajax' import { UpdateAliUserInfo, UpdateUserInfo } from '../../../pages/common/js/my' import { getuserInfo, LoginOut } from '../../../pages/common/js/login' var app = getApp() let region = [] Page({ data: { imageUrl, showTop: false, modalOpened: false, head_img: '', // 头像 nick_name: '', // 名字 userinfo: '', // 用户信息 sex: 0, // 地址 name: '', phone: '', address: '', labelList: ['学校', '家', '公司'], curLabel: 0, selectAddress: false, addressList: region, provinceList: [], cityList: [], countryList: [], province_i:0, city_i:0, region_i:0, defaultAddress: [0,0,0] }, onLoad(e) { if (e.img && e.name) { this.getInfo(e.img, e.name) } }, async onShow() { // 页面显示 每次显示都执行 // my.alert({ title: 'onShow=='+app.globalData.authCode }); region = await getRegion() this.getUserInfo() }, // 用户信息 getUserInfo() { var that = this var _sid = my.getStorageSync({ key: '_sid' }).data getuserInfo(_sid).then((res) => { var province_i = 0, city_i = 0, region_i = 0; var province = region.filter((item, index) => { if (item.addrid == res.data.province_id) { province_i = index } return item.addrid == res.data.province_id })[0] if (province) { var city = province.sub.filter((item, index) => { if (item.addrid == res.data.city_id) { city_i = index } return item.addrid == res.data.city_id })[0] } if (city) { var regions = city.sub.filter((item, index) => { if (item.addrid == res.data.region_id) { region_i = index } return item.addrid == res.data.region_id })[0] } var phone = res.data.phone && res.data.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'); res.data.provinceName = province && province.name || '' res.data.cityName = city && city.name || '' res.data.regionName = regions && regions.name || '' res.data.fake_phone = phone || '' that.setData({ userinfo: res.data, province_i, city_i, region_i, defaultAddress:[province_i,city_i,region_i] }, () => { that.getAddressList() }) }) }, // 选择性别 genderFN(e) { var that = this var data = e.currentTarget.dataset var sex = data.sex == 1 ? 0 : 1 UpdateUserInfo({ sex: data.sex }).then(res => { that.setData({ 'userinfo.sex': sex, showTop: false, }) }) }, // 保存用户信息 saveUserInfo(data) { var data = { sex: data.sex || '', birthday: data.birthday || '', province_id: data.province_id || '', city_id: data.city_id || '', region_id: data.region_id || '' } UpdateUserInfo(data).then((res) => { console.log(res, '用户保存') }) }, // 生日选择器 Taptime() { var that = this my.datePicker({ currentDate: '', startDate: '1950-1-1', endDate: '', success: (res) => { var birthday = res.date UpdateUserInfo({ birthday: birthday }).then(res => { that.setData({ 'userinfo.birthday': birthday }) }) }, }); }, getAddressList() { let [curProvince, curCity, curCountry] = this.data.defaultAddress; let provinceList = region.map(({ addrid, name }) => ({ addrid, name })) let cityList = region[curProvince].sub let countryList = cityList[curCity].sub this.setData({ provinceList, cityList, countryList }) }, changeAddress(e) { let [curProvince, curCity, curCountry] = this.data.defaultAddress; let cur; if (e) { cur = e.detail.value } else { cur = this.data.defaultAddress } if (cur[0] != curProvince) { cur = [cur[0], 0, 0] } if (cur[1] != curCity) { cur = [cur[0], cur[1], 0] } let province = region[cur[0]].name; let city = region[cur[0]].sub[cur[1]].name; let district = (region[cur[0]].sub[cur[1]].sub[cur[2]] && region[cur[0]].sub[cur[1]].sub[cur[2]].name) || '' this.setData({ defaultAddress: cur, address: province + ' ' + city + ' ' + district, province, city, district }, () => this.getAddressList() ) }, showSelectAddress() { this.setData({ selectAddress: true }) }, hideSelectAddress() { var that = this; var province = that.data.provinceList[that.data.defaultAddress[0]] var curCity = that.data.cityList[that.data.defaultAddress[1]] var region = that.data.countryList[that.data.defaultAddress[2]] var data = { province_id: province.addrid, city_id: curCity.addrid, region_id: region.addrid } UpdateUserInfo(data).then(res => { that.setData({ 'userinfo.province_id': province.addrid, 'userinfo.city_id': curCity.addrid, 'userinfo.region_id': region.addrid, 'userinfo.provinceName': province.name, 'userinfo.cityName': curCity.name, 'userinfo.regionName': region.name, selectAddress: false, }, () => that.changeAddress()) }) }, // 地址 changeCur(e) { let curLabel = e.currentTarget.dataset.cur if (curLabel === this.data.curLabel) curLabel = '-1' this.setData({ curLabel }) }, handelChange(e) { let { key } = e.currentTarget.dataset; let { value } = e.detail; this.setData({ [key]: value }) }, // 姓别选择器显示/隐藏 onTopBtnTap() { this.setData({ showTop: true, }); }, onPopupClose() { this.setData({ showTop: false, }); }, // 退出登录 outLogin() { this.setData({ modalOpened: true, }); }, onModalClick() { // 确认 var _sid = my.getStorageSync({ key: '_sid', // 缓存数据的key }).data; LoginOut(_sid).then(res => { console.log(res) if (res.code == 0) { my.removeStorageSync({ key: '_sid', }); my.removeStorageSync({ key: 'user_id', }); app.globalData._sid = "" my.switchTab({ url: '/pages/my/index/index' }) } else { my.showToast({ type: 'none', content: res.msg, duration: 2000 }); } }) this.setData({ modalOpened: false, }); }, onModalClose() { // 取消 this.setData({ modalOpened: false, }); }, //页面跳转 toUrl(e) { var url = e.currentTarget.dataset.url my.navigateTo({ url: url }); }, getInfo(avatar, nickName) { var that = this var _sid = my.getStorageSync({ key: '_sid', // 缓存数据的key }).data; that.setData({ 'userinfo.head_img': avatar, 'userinfo.nick_name': nickName }) var data = { _sid: _sid, head_img: avatar, nick_name: nickName } UpdateAliUserInfo(data).then(res => { }) }, onReady() { // 页面加载完成 只加载一次 页面初始化用 }, onHide() { // 页面隐藏 } }); <file_sep>/pages/webview/webview/webview.js Page({ data: { src: '' }, onLoad(options) { if (options && options.url && options.url!=''){ this.setData({ src: decodeURIComponent(options.url) }) } }, }); <file_sep>/package_order/pages/orderdetail/orderdetail.js import { imageUrl, imageUrl2, imageUrl3, img_url } from '../../../pages/common/js/baseUrl' import { log, ajax, contact, handleCopy, guide } from '../../../pages/common/js/li-ajax' const app = getApp() Page({ data: { imageUrl, imageUrl2, imageUrl3, img_url, showTop: false, cancleShow: false, orderState: [], takeOutState: [ '等待支付', '订单已提交', '商家已接单', '骑手正在送货', '订单已完成', '订单已取消', '订单已取消', '订单已取消', '订单已取消', '订单已取消', '订单已取消', '骑手已接单', ], pickUpState: [ '等待支付', '等待接单', '商家已接单', '等待取餐', '订单已完成', '订单已取消', '订单已取消', '订单已取消', '订单已取消', '订单已取消', '订单已取消' ], cancelReasonList: [ { reason: '下错单/临时不想要了', value: true, cancel_code: 9 }, { reason: '订单长时间未分配骑手', value: false, cancel_code: 1 }, { reason: '门店商品缺货/无法出货/已售完', value: false, cancel_code: 4 }, { reason: '联系不上门店/门店关门了', value: false, cancel_code: 5 }, { reason: '其他', value: false, cancel_code: 0 }, ], curOrderState: [], payTypes: { 1: '微信', 2: '支付宝', 3: '银联', 4: '微信扫码', 5: '支付宝扫码', 6: '现金',7:'支付宝付款码',8:'微信小程序',9:'微信付款码',10:'统一下单',11:'支付宝小程序' }, postWay: { FNPS: '蜂鸟配送', MTPS: '美团配送', ZPS: '自配送' }, timeArr: [], payStatusList: [], d: {}, dis_type: -1, order_channel: 1 }, async onLoad(e) { let { order_no } = e this.setData({ order_no }) }, async onShow() { await this.getOrderDetail() }, onUnload() { clearInterval(this.data.time) this.setData({ time: -1 }) this.setData = () => { } }, onHide() { clearInterval(this.data.time) this.setData({ time: -1 }) this.closeModel() }, contact, handleCopy, guide, closeModel() { this.setData({ showTop: false, cancleShow: false }) }, /** * @function 获取订单详情 */ async getOrderDetail() { let { curOrderState, order_no, time } = this.data clearInterval(time) let res = await ajax('/juewei-api/order/detail', { order_no }) let timeArr let { order_ctime, pay_time, get_time, dis_get_time, dis_take_time, push_time, dis_finish_time, cancel_time, dis_type, dis_tag, order_status_info } = res.data if (res.code === 0) { // 订单类型 1"官方外卖", 2"门店自取" // 配送方式 1配送 2 自提 if (dis_type == 1) { // //显示状态和时间的语句 // 1) 待支付,时间:data.order_ctime //创建时间 // 2) 待取餐,时间:data.pay_time //支付时间 // 3) 门店已接单,时间:data.push_time //门店接单时间 // 4) 配送已接单,时间:data.dis_get_time //物流接单时间 // 5) 骑手配送中,时间:data.dis_take_time //配送员取货时间 // 6) 订单已完成,时间:data.dis_finish_time //送达时间 // 7) 订单已取消,时间:data.cancel_time //取消时间 timeArr = [ { state: '等待支付', time: order_ctime }, { state: '订单已提交', time: pay_time }, { state: '商家已接单', time: push_time }, { state: '骑手已接单', time: dis_get_time }, { state: '骑手正在送货', time: dis_take_time }, { state: '订单已完成', time: dis_finish_time }, { state: '订单已取消', time: cancel_time }, ] // log(timeArr) // data.order_status_info.order_status // 外卖显示数组 // 0,等待支付 1 // 1,支付成功 1,2 // 2,商家接单/商家已确认 1,2,3 // 3,正在配送/配送中 1,2,3,4,(判断5的时间是否存在,如果有显示5) // 4,确认收货/已送到/完成 1,2,3,4,5,6 // 5,用户取消 1,7 // 6,自动取消 1,7 // 7,后台客服退单 1,2,7 // 8,后台审核退单成功 1,7 // 9,达达主动发起取消订单,1,2,3,7 // 10:店pos取消 1,2,7 let orderStatus = [ { state: '等待支付', timeArr: [1] }, { state: '支付成功', timeArr: [1, 2] }, { state: '商家接单/商家已确认', timeArr: [1, 2, 3] }, { state: '正在配送/配送中', timeArr: [1, 2, 3, 4] }, { state: '确认收货/已送到/完成', timeArr: [1, 2, 3, 4, 5, 6] }, { state: '用户取消', timeArr: [1, 7] }, { state: '自动取消', timeArr: [1, 7] }, { state: '后台客服退单', timeArr: [1, 2, 7] }, { state: '后台审核退单成功', timeArr: [1, 7] }, { state: '达达主动发起取消订单', timeArr: [1, 2, 3, 7] }, { state: '店pos取消', timeArr: [1, 2, 7] }, ] let curState = res.data.order_status_info.order_status let curTimeArr = orderStatus[curState].timeArr; // 自配送 没有骑手已接单 if (curState < 5 && curState > 2) { dis_tag != 'ZPS' ? curTimeArr : (curTimeArr.splice(curTimeArr.findIndex(item => item == 4), 1)); } ; (curState == 2 && order_status_info.dis_status == 2 && dis_tag != 'ZPS' && dis_get_time) ? curTimeArr.push(4) : curTimeArr curState === 3 && dis_take_time != '0000-00-00 00:00:00' ? curTimeArr.push(5) : curTimeArr curOrderState = curTimeArr.map(item => timeArr[item - 1]) } if (dis_type == 2) { // //显示状态和时间的语句 // 1) 待支付,时间:data.order_ctime //创建时间 // 2) 订单已提交,时间:data.pay_time //支付时间 // 6) 订单已完成,时间:data.dis_finish_time //送达时间 // 7) 订单已取消,时间:data.cancel_time //取消时间 timeArr = [ { state: '等待支付', time: order_ctime }, { state: '订单已提交', time: pay_time }, { state: '商家已接单', time: push_time }, { state: '配送已接单', time: dis_get_time }, { state: '骑手配送中', time: dis_take_time }, { state: '订单已完成', time: dis_finish_time }, { state: '订单已取消', time: cancel_time }, ] log(timeArr) // 自提显示数组 // 0,等待支付 1 // 1,支付成功 1,2 // 2,商家接单/商家已确认 1,2 // 3,正在配送/配送中 1,2 // 4,确认收货/已送到/完成 1,2,6 // 5,用户取消 1,7 // 6,自动取消 1,7 // 7,后台客服退单 1,2,7 // 8,后台审核退单成功 1,2,7 // 9,达达主动发起取消订单 1,2,7 // 10:店pos取消 1,2,7 let orderStatus = [ { state: '等待支付', timeArr: [1] }, { state: '支付成功', timeArr: [1, 2] }, { state: '商家接单/商家已确认', timeArr: [1, 2, 3] }, { state: '正在配送/配送中', timeArr: [1, 2, 3] }, { state: '确认收货/已送到/完成', timeArr: [1, 3, 2, 6] }, { state: '用户取消', timeArr: [1, 7] }, { state: '自动取消', timeArr: [1, 7] }, { state: '后台客服退单', timeArr: [1, 2, 7] }, { state: '后台审核退单成功', timeArr: [1, 2, 7] }, { state: '达达主动发起取消订单', timeArr: [1, 2, 7] }, { state: '店pos取消', timeArr: [1, 2, 7] }, ] let curState = res.data.order_status_info.order_status let curTimeArr = orderStatus[curState].timeArr curOrderState = curTimeArr.map(item => timeArr[item - 1]) // log(curOrderState) } let { remaining_pay_minute, remaining_pay_second, ...item } = res.data let { time } = this.data time = setInterval(() => { --remaining_pay_second if (remaining_pay_minute === 0 && remaining_pay_second == -1) { clearInterval(time) // return this.getOrderDetail(order_no) } if (remaining_pay_second <= 0) { --remaining_pay_minute remaining_pay_second = 59 } this.setData({ d: { ...item, remaining_pay_second, remaining_pay_minute }, time, timeArr, curOrderState, dis_type, order_channel: res.data.channel }) }, 1000) } }, /** * @function 打电话 */ makePhoneCall(e) { const { number } = e.currentTarget.dataset my.makePhoneCall({ number }); }, show() { this.setData({ showTop: true }) }, /** * @ 显示选择原因 */ showCancel() { if (this.data.order_channel != 1) { my.showToast({ content: '订单不支持跨平台操作,请去相应平台取消订单!' }); return } this.setData({ cancleShow: true }) }, /** * @function 选择原因 */ selectReason(e) { const { cancelReasonList } = this.data; const { index } = e.currentTarget.dataset; cancelReasonList.forEach(item => item.value = false) cancelReasonList[index].value = true this.setData({ cancelReasonList }) }, /** * @function 取消订单 */ async cancelOrder() { const { d, cancelReasonList } = this.data let cancel_code = cancelReasonList.filter(item => item.value)[0].cancel_code let res = await ajax('/juewei-api/order/cancel', { order_no: d.order_no, cancel_code, cancel_reason: '其他' }) if (res.code == 0) { log('取消成功') app.globalData.refresh = true app.globalData.refresh_state = d.dis_type - 1 my.switchTab({ url: '/pages/order/list/list', }); } else { this.closeModel() my.showToast({ content: res.msg, duration: 2000, }); } }, /** * @function 去评价页面 */ toComment(e) { const { order_no } = e.currentTarget.dataset; my.navigateTo({ url: '/package_order/pages/comment/comment?order_no=' + order_no }); }, /** * @function 立即支付 */ async payNow(e) { const { channel } = this.data.d if (channel != 1) { return } const { order_no } = e.currentTarget.dataset; let r = await ajax('/juewei-service/payment/AliMiniPay', { order_no }, "POST") if (r.code === 0) { let { tradeNo } = r.data if (!tradeNo) { return my.showToast({ content: r.data.erroMSg }) } my.tradePay({ tradeNO: tradeNo, // 调用统一收单交易创建接口(alipay.trade.create),获得返回字段支付宝交易号trade_no success: res => { log('支付成功'.res) if (res.resultCode == 9000) { return my.redirectTo({ url: '/pages/home/orderfinish/orderfinish?order_no=' + order_no }); } // return my.redirectTo({ // url: '/pages/home/orderError/orderError?order_no=' + order_no // }); }, fail: res => { return my.redirectTo({ url: '/pages/home/orderError/orderError?order_no=' + order_no }); } }); } else { return my.redirectTo({ url: '/pages/home/orderError/orderError?order_no=' + order_no }); } }, /** * @function 再来一单 */ buyAgain() { const { dis_type } = this.data app.globalData.type = dis_type; log(app.globalData.type) if (app.globalData.province && app.globalData.city && app.globalData.address && app.globalData.position) { my.switchTab({ url: '/pages/home/goodslist/goodslist' }); } else { my.navigateTo({ url: '/pages/position/position' }); } }, showCode() { this.setData({ open2: true }) }, closeCode() { this.setData({ open2: false }) } }); <file_sep>/pages/common/js/utils.js export const event_getNavHeight = () => { let { titleBarHeight, statusBarHeight, model } = wx.getSystemInfoSync(); return { titleBarHeight: titleBarHeight || 40, statusBarHeight } };<file_sep>/package_my/pages/myaddress/myaddress.js import { imageUrl } from '../../../pages/common/js/baseUrl' import { addressList } from '../../../pages/common/js/my' var app = getApp() Page({ data: { imageUrl, order_sn: '', list: [] }, onLoad(e) { const { order_sn } = e this.setData({ order_sn }) }, onShow() { this.getaddressList() }, back(e) { const { i } = e.currentTarget.dataset; const { order_sn, list } = this.data; const user_address_name = list[i].user_address_name const user_address_phone = list[i].user_address_phone const province = list[i].province const city = list[i].city const district = list[i].district console.log(district) const user_address_id = list[i].user_address_id const user_address_detail_address = list[i].user_address_detail_address const user_address_map_addr = list[i].user_address_map_addr console.log(list) if (order_sn) { my.redirectTo({ url: '/package_vip/pages/waitpay/waitpay?' + 'order_sn=' + order_sn + '&user_address_name=' + user_address_name + '&user_address_phone=' + user_address_phone + '&province=' + province + '&city=' + city + '&district=' + district + '&user_address_id=' + user_address_id + '&user_address_detail_address=' + user_address_detail_address + '&user_address_map_addr=' + user_address_map_addr }); } }, toUrl(e) { var item = e.currentTarget.dataset.item my.navigateTo({ url: "/package_my/pages/myaddress/addaddress/addaddress?Id=" + item.user_address_id }); }, addressFn() { app.globalData.addAddressInfo=null; my.navigateTo({ url: "/package_my/pages/myaddress/addaddress/addaddress" }); }, getaddressList() { var that = this var _sid = my.getStorageSync({ key: '_sid', // 缓存数据的key }).data; var data = { _sid: _sid, type: 'normal' } console.log(data,'data') addressList(data).then(res => { console.log(res,'地址列表返回') if (res.code == 0) { that.setData({ list: res.data }) }else{ my.showToast({ type: 'none', content: res.msg, duration: 2000, }); } }) }, }); <file_sep>/pages/common/js/common.sjs const getImgUrl = function (url) { return url.indexOf('imgcdnjwd.juewei.com') > -1 ? url : 'http://imgcdnjwd.juewei.com' + url; } export default { getImgUrl };<file_sep>/pages/home/orderform/remarks/remarks.js var app = getApp(); Page({ data: { remarks:'' }, onLoad() {}, onShow() { if (app.globalData.remarks) { this.setData({ remarks: app.globalData.remarks }) } }, inputRemarks(e){ this.setData({ remarks: e.detail.value }) }, remarksBtn(){ // my.setStorageSync({ // key: 'remark', // 缓存数据的key // data: this.data.remarks // 要缓存的数据 // }); app.globalData.remarks = this.data.remarks; my.navigateBack({ url: '/pages/home/orderform/orderform' }); } }); <file_sep>/package_my/pages/coupon/exchange/exchange.js import {exchangeCoupon} from '../../../../pages/common/js/home'; import {imageUrl} from '../../../../pages/common/js/baseUrl' Page({ data: { code:'', imageUrl, mask: false, modalShow: false, content:'', }, onLoad() {}, writeCode(e){ this.setData({ code: e.detail.value }) }, exchangeBtn(){ const _sid = my.getStorageSync({key: '_sid'}).data; const {code} = this.data const that = this if(!code) { return that.setData({ content: '请输入兑换码' }, () => setTimeout(() => { that.setData({ content: '' }); }, 2000)); } exchangeCoupon(_sid, code).then((res) => { if(res.CODE == 'A100') { this.setData({ mask: true, modalShow: true }) }else{ that.setData({ content:res.MESSAGE },()=> setTimeout(()=>{ that.setData({ content:'' }); },2000)); } }) }, getCoupons(e) { this.setData({ mask: false, modalShow: false }) if(e.type == 1) { my.navigateTo({ url: '/package_my/pages/coupon/coupon' }); }else { my.navigateTo({ url: '/pages/home/goodslist/goodslist' }); } } }); <file_sep>/package_my/pages/myaddress/selectaddress/selectaddress.js import { imageUrl, ak, geotable_id } from '../../../../pages/common/js/baseUrl' import { gd_decrypt, bd_encrypt } from '../../../../pages/common/js/map' const app = getApp(); Page({ data: { imageUrl, mapiconInfo: '', mapInfo: [], latitude: '', longitude: '', list: [], city: '', addressIng: '', // 定位地址 nearAddress: [], // 附近地址 isSuccess: false, info: '', // 一条地址信息 inputAddress: '', //手动输入的地址 loginOpened: false, addressList: [], addressList_poi:[],//poi数据 currentPos: '', noSearchResult: false, mapCtx: {}, movePosFlag: false, isSearch: false }, onLoad() { this.getLocation(); // let bol = my.canIUse('map.optimize'); // if (bol) { // this.getLocation(); // } else { // my.alert({ // content:'支付宝版本过低,请升级新版本!', // success:() => { // my.navigateBack(); // } // }) // } }, onReady(e) { // 使用 my.createMapContext 获取 map 上下文 this.setData({ mapCtx: my.createMapContext('map') }) this.mapCtx = my.createMapContext('map'); this.data.mapCtx.gestureEnable({ isGestureEnable: 1 }); // 为了使初始化时只执行一遍 setTimeout(() => { this.setData({ movePosFlag: true }) }, 1000) }, //获取当前定位地址信息 getLocation() { var that = this my.getLocation({ type: 3, success(res) { my.hideLoading(); let currentPos = res.pois[0] ? res.pois[0].name : currentPos; that.setData({ longitude: res.longitude, latitude: res.latitude, city: res.city, currentPos: currentPos, addressList: [],//这里地址不能是支付宝的高德地图的 addressList_poi:[] }); //获取附近的绝味鸭脖门店显示 that.setIcon(res.longitude, res.latitude); let baiduPos = bd_encrypt(res.longitude, res.latitude);// 百度经纬度 //获取附近的poi信息 let url = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=${ak}&output=json&coordtype=bd09ll&location=${baiduPos.bd_lat},${baiduPos.bd_lng}&extensions_poi=1`; url = encodeURI(url); my.request({ url, success: (res) => { if (res.data.status === 0) { let result = res.data.result.pois; let addressComponent = res.data.result.addressComponent // 无数据显示无数据页面 if (result.length === 0) { that.setData({ noSearchResult: true }) } result.forEach(item => { item.province = addressComponent.province, item.city = addressComponent.city, item.district = addressComponent.district item.location = { lng: item.point.x, lat: item.point.y } }) that.setData({ addressList_poi: result, noSearchResult: false }) } }, }); }, fail() { my.hideLoading(); my.alert({ title: '定位失败' }); }, }) }, // 切换城市 choosecityTap() { my.chooseCity({ showLocatedCity: true, showHotCities: true, success: (res) => { if (res.city.indexOf('市') == res.city.length - 1 || res.city.indexOf('州') == res.city.length - 1) { this.setData({ city: res.city }) } else { if(res.city) this.setData({ city: res.city + '市' }) } }, }); }, scrollToLower() { // this.setData({ // isSearch: true // }) }, //通过经纬度设置地图上的点位置附近2000米绝味鸭脖的门店 setIcon(long, lat) { // 从地图中获取的和往地图中设置的都是高德经纬度,接口调用和后台存储的都是百度的经纬度,在使用中要注意转换 var that = this let baiduPos = bd_encrypt(long, lat);// 百度经纬度 my.request({ url: 'https://api.map.baidu.com/geosearch/v3/nearby?ak=' + ak + '&geotable_id=' + geotable_id + '&location=' + baiduPos.bd_lng + ',' + baiduPos.bd_lat + '&radius=2000', success: (res) => { // 设置定位位置的图标 if (!this.data.sysInfo) { let sysInfo = my.getSystemInfoSync(); this.setData({ sysInfo: sysInfo }) } let windowWidth = this.data.sysInfo.windowWidth; let windowHeight = this.data.sysInfo.windowHeight; var arr = [ { iconPath: imageUrl + 'position.png', latitude: lat,// 高德经纬度 longitude: long, width: 32, height: 32 } ] // 设置门店的图标 res.data.contents.forEach(item => { var obj = {} obj.iconPath = imageUrl + 'position.png' let gdPos = gd_decrypt(item.location[0], item.location[1]) obj.latitude = gdPos.lat; obj.longitude = gdPos.lng; obj.width = 20 obj.height = 20 arr.push(obj) }) that.setData({ mapInfo: arr }) }, }); }, // 输入事件 searchInput(e) { if (e.detail.value == '') { this.setData({ inputAddress:'', noSearchResult: false, isSearch: false }) return } this.setData({ inputAddress: e.detail.value }) //搜索 this.searchAddress(); }, // 搜索 searchAddress() { let url = `https://api.map.baidu.com/place/v2/search?query=${this.data.inputAddress}&region=${this.data.city}&output=json&ak=${ak}`; url = encodeURI(url); my.request({ url, success: (res) => { if (res.data.status === 0) { let result = res.data.results; // 无数据显示无数据页面 if (result.length === 0) { this.setData({ noSearchResult: true, isSearch: true }) return } result.forEach((item,index)=>{ console.log(item,index); }) this.setData({ addressList: result, noSearchResult: false, isSearch: true }) } // 搜索到的位置 // let centerPos = res.data.results[0]; // if (centerPos) { // const gd_pos = gd_decrypt(centerPos.location.lng, centerPos.location.lat); // this.setData({ // longitude: gd_pos.lng, // latitude: gd_pos.lat // }); // this.setIcon(centerPos.location.lng, centerPos.location.lat); // } }, fail: (e) => { this.setData({ addressList: [], noSearchResult: false, isSearch: true }) } }); }, chooseAdress(e) { let { pos } = e.currentTarget.dataset; app.globalData.addAddressInfo = pos; my.navigateBack(); }, //选择地图上的点,或者拖动地图后 mapTap(e) { let that = this; if (!this.data.movePosFlag) { return; } if (e.type == 'end' || e.type == 'tap') { let newLat = e.latitude; let newLng = e.longitude; //将周边的门店显示到地图上 that.setIcon(e.longitude, e.latitude); //转换成百度的 let baiduPos = bd_encrypt(e.longitude, e.latitude); this.mapCtx.updateComponents({ longitude: e.longitude, latitude: e.latitude, }); //获取附近的poi信息 let url = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=${ak}&output=json&coordtype=bd09ll&location=${baiduPos.bd_lat},${baiduPos.bd_lng}&extensions_poi=1`; url = encodeURI(url); my.request({ url, success: (res) => { if (res.data.status === 0) { let result = res.data.result.pois; let addressComponent = res.data.result.addressComponent // 无数据显示无数据页面 if (result.length === 0) { this.setData({ noSearchResult: true }) } result.forEach(item => { item.province = addressComponent.province, item.city = addressComponent.city, item.district = addressComponent.district item.location = { lng: item.point.x, lat: item.point.y } }) this.setData({ addressList_poi: result, noSearchResult: false }) } }, }); } }, });
09c5a4827ec4e46a040ea76e271e2e6f052f5e13
[ "JavaScript", "Markdown" ]
43
JavaScript
amorhe/juewei-new
6702b06f4d72e3f07f6366915155fd3d9a58eb01
68301049abaaa7fc783ddea28678c9948603ecaf
refs/heads/master
<file_sep>// // ViewController.swift // sound_Nov // // Created by 野崎絵未里 on 2019/11/13. // Copyright © 2019 <EMAIL>. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { var audioplayer: AVAudioPlayer! @IBOutlet weak var button: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func tapBeginButton() { let path = Bundle.main.path(forResource: "guitar", ofType: "mp3")! let url = URL(fileURLWithPath: path) audioplayer = try! AVAudioPlayer(contentsOf: url) audioplayer.play() button.setImage(UIImage(named: "cymbal"), for: .normal) } @IBAction func tapFinish(_ sender: Any) { audioplayer.stop() button.setImage(UIImage(named: "guitar"), for: .normal) } }
757eadeebdde59ac0769a885e8105fbe2c7bd595
[ "Swift" ]
1
Swift
appleEmily/sound_Nov
eee662acb07aacd66128ebcb4211a0b1af923c9d
b713935576ff9ac646bdfca724712ad59efc2f41
refs/heads/master
<file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>PHP基礎</title> </head> <body> <?PHP //ステップ1.db接続 //DB情報 $dsn = 'mysql:dbname=phpkiso;host=localhost'; //user情報 $user = 'root'; $password = ''; //DB接続オブジェクト作成 $dbh = new PDO($dsn,$user,$password); //接続したDBオブジェクトでutf8を使うことを指定 $dbh->query('SET NAMES utf8'); $nickname = $_POST['nickname']; $email = $_POST['email']; $goiken = $_POST['goiken']; echo "ようこそ"; echo $nickname; echo '様'; echo '<br/>'; echo 'ご意見ありがとうございました'; echo "メールアドレス"; echo $email; echo '<br/>'; echo "ご意見『"; echo $goiken; echo '』<br />'; //ステップ2.データベースエンジンにsql文で司令を出す $sql = 'INSERT INTO survey1(`nickname`,`email`,`goiken`)VALUES("'.$nickname.'","'.$email.'","'.$goiken.'")'; var_dump($sql); $stmt = $dbh->prepare($sql); $stmt ->execute(); //ステップ3.データベースから切断 $dbh=null; ?> </body> <file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>PHP基礎</title> </head> <body> <?php //ステップ1.db接続 //DB情報 $dsn = 'mysql:dbname=phpkiso;host=localhost'; //user情報 $user = 'root'; $password = ''; //DB接続オブジェクト作成 $dbh = new PDO($dsn,$user,$password); //接続したDBオブジェクトでutf8を使うことを指定 $dbh->query('SET NAMES utf-8'); //ステップ2.データベースエンジンにsql文で司令を出す $sql='SELECT*FROM survey1 WHERE 1'; var_dump($sql); $stmt = $dbh->prepare($sql); $stmt ->execute(); while(1) { $rec = $stmt->fetch(PDO::FETCH_ASSOC); if($rec==false){ break; } print $rec['code']; print $rec['nickname']; print $rec['email']; print $rec['goiken']; print '<br/>'; } //ステップ3.データベースから切断 $dbh=null; ?> </body>
f1ef119072e89372dba28f8f4da15d1de0ead2a0
[ "PHP" ]
2
PHP
k-nish/survey
2f6eebbf210c80cccce2a975ba505a535cf3599b
d3be60af4e8d2e6d93f9f90dea740a8765fe4531
refs/heads/master
<file_sep>from loss import getLoss import numpy as np class Model: def __init__(self): self.layers = [] self.weights = [] self.final = None def addLayer(self, layer): self.layers.append(layer) # print("Added layer " + layer.type) # print("Layer shape " + str(layer.shape)) def compile(self, loss): self.lossType = loss prev = None for layer in self.layers: prev = layer.compile(prev) layer.last_layer = False self.layers[-1].last_layer = True def loss(self, predicted, y, lambda_=0.0): return getLoss(self.lossType)(self, predicted, y, lambda_) def setInput(self, input): self.input = input def feedforward(self): passThrough = self.batch for layer in self.layers: layer.passThrough = passThrough passThrough = layer.activate(passThrough) self.final = passThrough return self.final def predict(self, input): prevInput = self.batch self.batch = input self.feedforward() output = self.final self.batch = prevInput return output def backpropagate(self, target, lambda_=0.0): """ Returns gradients of trainable layers by backpropagation. """ deltas = [] trainableLayers = list( reversed([layer for layer in self.layers if layer.trainable])) currdelta = self.final - target for i in range(len(trainableLayers)): deltas.append(currdelta) currdelta = currdelta@(trainableLayers[i].weights[:, 1:]) if(i + 1 < len(trainableLayers)): currdelta *= (trainableLayers[i + 1].grad) Deltas = [] for delta, layer in zip(deltas, trainableLayers): delta = delta.T@layer.passThrough / target.shape[0] delta[:, 1:] = delta[:, 1:] + \ (lambda_ / target.shape[0]) * layer.weights[:, 1:] Deltas.append(delta) Deltas.reverse() Gradients = [] for delta in Deltas: Gradients.extend(delta.flatten()) return np.array(Gradients) def setWeights(self, flattened_weights): prevSize = 0 flattened_weights = np.array(flattened_weights) for layer in self.layers: if layer.trainable: size = 1 shape = layer.weights.shape for dim in shape: size *= dim size += prevSize layer.weights = np.array( flattened_weights[prevSize:size]).reshape(*shape) prevSize = size def getWeights(self): flattened_weights = [] for layer in self.layers: if layer.trainable: flattened_weights.extend(layer.weights.ravel()) return flattened_weights def cost(self, input, target, lambda_=0.0): self.feedforward() predicted = self.predict(input) J = self.loss(predicted,target) accuracy = np.argmax(target, axis=1) == np.argmax(predicted, axis=1) accuracy = np.where(accuracy == 1) accuracy = len(accuracy[0]) / target.shape[0] * 100 grad = self.backpropagate(target, lambda_) return J, grad, accuracy def costFunction(self, input, target, p): self.setWeights(p) return self.cost(input, target, lambda_=0.03) def addOptimizer(self, opt): self.opt = opt self.opt.model = self self.train = self.opt.train <file_sep># + import matplotlib.pyplot as plt import matplotlib as mpl from model import Model from layers import Dense, Flatten from scipy import optimize from optimizer import Adam import numpy as np import pandas as pd import pickle train = pd.read_csv('train.csv') train.head() X = train.drop('label', axis=1) Y = train['label'].values X = X.values.reshape((len(X), 28, 28)) # - my_model = Model() my_model.addLayer(Flatten(input_shape=(28, 28))) my_model.addLayer(Dense(units=256, activation='sigmoid')) my_model.addLayer(Dense(units=10, activation='sigmoid')) my_model.addLayer(Dense(units=10, activation='softmax')) my_model.addOptimizer(Adam()) my_model.compile(loss='binary_cross_entropy') '''with open('mnist_weights.pkl', 'rb') as f: weights = pickle.load(f) my_model.setWeights(weights) ''' y = np.eye(10)[Y.reshape(-1)] accuracy = my_model.train(X, y, epochs=30) # + # %matplotlib inline fig = plt.figure(figsize=(9, 13)) columns = 7 rows = 7 # ax enables access to manipulate each of subplots ax = [] for i in range(columns * rows): img = X[i] inputs = np.array([X[i]]) output = my_model.predict(inputs) output = np.argmax(output, axis=1) # create subplot and append to ax ax.append(fig.add_subplot(rows, columns, i + 1)) ax[-1].set_title(str(output[0])) # set title plt.imshow(img, alpha=1) plt.show() # finally, render the plot # - ''' test = pd.read_csv('test.csv') X = test.drop('label', axis=1) Y = test['label'].values X = X.values.reshape((-1, 28, 28)) with open('mnist_weights.pkl', 'wb') as f: pickle.dump(my_model.getWeights(), f) with open('mnist_weights.pkl', 'rb') as f: weights = pickle.load(f) ''' <file_sep>from model import Model from layers import Dense, Flatten from scipy import optimize import numpy as np from activations import _sigmoid from utils import addOnes import math from optimizer import Adam, GA my_model = Model() my_model.addLayer(Flatten(input_shape=(28, 28))) my_model.addLayer(Dense(units=10, activation='sigmoid')) my_model.addLayer(Dense(units=5, activation='sigmoid')) my_model.addLayer(Dense(units=5, activation='softmax')) my_model.addOptimizer(GA()) my_model.compile(loss='binary_cross_entropy') X = np.random.uniform(-1, 1, size=(100, 28, 28)) y = np.random.randint(low=0, high=4, size=(100)) y = np.eye(5)[y.reshape(-1)] # + w = [] history = my_model.train(X,y, popSize= 100, epochs=20) <file_sep># Genie Genie is a project made for independent research related to applying genetic algorithm on a model's weights to optimize training (matrix multiplication is expensive!). If the amount of abstraction in TensorFlow or Keras holds you from understanding what's behind the hood, this might be the right place for you. (I basically built it to understand what is actually happening) Genie's API was purposely kept very similar to that of Tensorflow/Keras, it does lack in a lot of features, but it gives an understanding of multiple things ranging from 1. The model structure and how it's created when you use model.addLayer() (in model.py) and all the different types of Layers. (in layers.py) 2. How the input gets processed through the different layers, and the way activation functions help in feed forward as well as calculating gradients. You can find these activations in activations.py 3. The backpropogation algorithm forms the root for most optimization algorithms. Most places explain it with a couple layers but this is how it can be applied to as many layers as you want. You can find model.backpropagate(target) directly in model.py 4. The optimization algorithms. Genie contains 2 optimizers as of now. Adam and a custom one based on genetic optimizers. You can find these in optimizer.py. Sidenote: If the genetic algorithm seems different to what you have seen before, it's because it uses a multi parent crossover technique for inheritance of genomes that I came upon while researching. The other different thing in GA is something I like to call the asteroid affect. Whenever the optimizer gets stuck in a local minima, 98% of individuals are wiped out and new individuals (according to how stuck the optimizer is) are introduced. # Demo handwritten.py contains code for the MNIST database.You'd need to download the .csv files from https://www.kaggle.com/oddrationale/mnist-in-csv, unzip it and change the paths accordingly. Feel free to experiment with the number of neurons/layers and run the example with python handwritten.py. I achieved ~98% accuracy in little over 20 epochs! # Current Work The current stuff I am working on is to create a version of Adam that chooses new betas in every iteration as well as adding Convolution and Pooling layers. <file_sep>import numpy as np def binary_cross_entropy(self, predicted, y, lambda_=0.0): m = y.shape[0] #print(predicted.shape) #print(y.shape) weights_mats = [layer.weights for layer in self.layers if layer.trainable] reg = 0 for weight_mat in weights_mats: reg += np.sum(np.square(weight_mat[:, 1:])) reg *= lambda_ / (2 * m) loss = (-1 / m) * np.sum((np.log(predicted + 10**-15) * y) + np.log(1 - predicted + 10**-15) * (1 - y)) return loss + reg def getLoss(loss): if(loss == 'binary_cross_entropy'): return binary_cross_entropy <file_sep>from model import Model from layers import Dense, Flatten from scipy import optimize import numpy as np from activations import _sigmoid from utils import addOnes import math from optimizer import Adam my_model = Model() my_model.addLayer(Flatten(input_shape=(28, 28))) my_model.addLayer(Dense(units=50, activation='sigmoid')) my_model.addLayer(Dense(units=5, activation='sigmoid')) my_model.addLayer(Dense(units=5, activation='softmax')) my_model.addOptimizer(Adam()) my_model.compile(loss='binary_cross_entropy') X = np.random.uniform(-1, 1, size=(1000, 28, 28)) y = np.random.randint(low=0, high=4, size=(1000)) y = np.eye(5)[y.reshape(-1)] # + h = [] for i in range(10): h1 = my_model.train(X, y, epochs=20) h2 = my_model.opt.trainR(X,y,epochs=20) h.append(h2-h1) print(np.sum(h)/len(h)) # - <file_sep>import numpy as np # linear algebra def addOnes(a): return np.concatenate([np.ones((a.shape[0], 1)), a], axis=1) <file_sep>import numpy as np from utils import addOnes from activations import getActiv class Dense: def __init__(self, units, activation, epsilon_init=0.12): self.shape = units self.epsilon_init = epsilon_init self.type = 'Dense' self.trainable = True self.activation = activation self.last_layer = False def activate(self, input): activationType = self.activation output = None output, grad = getActiv(activationType)(self.weights,input) if self.last_layer is False: output = addOnes(output) if self.trainable: self.grad = grad return output def compile(self, prev): self.weights = np.random.uniform( low=-1, high=1, size=(self.shape, prev + 1)) return self.shape class Flatten: def __init__(self, input_shape): size = 1 for dim in input_shape: size *= dim self.shape = size self.type = 'Flatten' self.trainable = False def activate(self, input): output = input.reshape(input.shape[0], -1) if self.last_layer is False: output = addOnes(output) return output def compile(self, prev): return self.shape def forward(self, input): return self.activate(input) <file_sep>import numpy as np def relu(weights, input): inputMat = input@weights.T activ = np.maximum(inputMat, 0) grad = np.copy(activ) grad[grad <= 0] = 0 grad[grad > 0] = 1 return activ, grad def sigmoid(weights, input): inputMat = input@weights.T activ = _sigmoid(inputMat) grad = activ * (1 - activ) return activ, grad def _sigmoid(input): activ = 1.0 / (1.0 + np.exp(-input)) activ[activ == 1] = 0.9999 activ[activ == 0] = 0.0001 return activ def softmax(weights, inp): inputMat = inp@weights.T result = [] for i in inputMat: result.append(np.exp( i) / np.sum(np.exp(i))) result = np.array(result) grad = result * (1 - result) return result, grad def tanh(weights, input): x = input@weights.T t = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)) grad = 1 - np.square(t) return t, grad def getActiv(input): activations = { 'tanh': tanh, 'softmax': softmax, 'sigmoid': sigmoid, 'relu': relu } return activations.get(input, "Invalid activation") <file_sep>from random import uniform, randint, random, sample from functools import reduce from operator import add import numpy as np from multiprocessing import Pool from progressbar import progressbar, ProgressBar class GA: def __init__(self, model): self.model = model def individual(self, _, loss='binary_cross_entropy'): ''' Compiles model and all of its layers with random initial weights ''' self.model.compile(loss) weights = self.model.getWeights() return weights def fitness(self, individual, target): self.model.setWeights(individual) self.model.feedforward() return self.loss(target) def population(self, count): """ Create a number of individuals (i.e. a population). count: the number of individuals in the population """ with Pool(2) as p: pop = p.map(self.individual, range(count)) p.terminate() return pop def f(self, x): return self.fitness(x, self.target) def grade(self, pop, target): 'Find average fitness for a population.' self.target = target with Pool(2) as p: mapped = p.map(self.f, pop) summed = reduce(add, mapped) return summed / (len(pop) * 1.0) p.terminate() def mutate(self, individual): """ Function that mutates parents according to input probability Returns mutated individual """ for i in range(randint(1, len(individual))): pos_to_mutate = randint(0, len(individual) - 1) mutated = np.copy(individual) mutated[pos_to_mutate] = uniform(-2, 2) return mutated def evolve(self, pop, target, retain=0.2, random_select=0.1, mutate=0.7): graded = [(self.fitness(x, target), x) for x in pop] graded = [x[1] for x in sorted(graded, key=lambda x: x[0])] retain_length = int(len(graded) * retain) parents = graded[:retain_length] # randomly add other individuals to # promote genetic diversity for individual in graded[retain_length:]: if random_select > random(): parents.append(individual) # mutate some individuals for individual in parents: if mutate > random(): individual = self.mutate(individual) # crossover parents to create children parents_length = len(parents) desired_length = len(pop) - parents_length children = [] childLength = len(parents[0]) possibleNumParents = [i for i in range( 1, min(childLength + 1, parents_length)) if childLength % i == 0] possibleNumParents = possibleNumParents[:-1] while len(children) < desired_length: numParents = sample(possibleNumParents, 1)[0] newChildParents = sample(parents, numParents) newChild = [] start = 0 division = int(childLength / numParents) for newParent in newChildParents: newChild += newParent[start:division] start = division division += division children.append(newChild) parents.extend(children) parents = [(self.fitness(x, target), x) for x in parents] parents = [x[1] for x in sorted(parents, key=lambda x: x[0])] return parents def train(self, popSize, y, epochs=1000): p = self.optimizer.population(popSize) prevGrade = self.optimizer.grade(p, y) for i in range(epochs): print(prevGrade, len(p), self.optimizer.fitness(p[0], y)) p = self.optimizer.evolve(p, y) p = p[:popSize] newGrade = self.optimizer.grade(p, y) asteroid = abs(prevGrade - newGrade) + 0.5 p += self.optimizer.population(int(popSize / asteroid)) if newGrade - prevGrade < 0.00001: p += self.optimizer.population(5 * popSize) prevGrade = newGrade class Adam: def __init__(self, b1=0.5, b2=0.9, a=0.03, e=10e-8): self.b1, self.b2, self.a, self.e = b1, b2, a, e def train(self, input, target, epochs=500): m = 0 v = 0 v_2 = 0 t = 0 i = 0 self.model.setInput(input) w = self.model.getWeights() self.w = w accuracy = 0 for i in range(epochs): t += 1 J, grad, accuracy = self.model.costFunction(target, w) m = self.b1 * m + (1 - self.b1) * grad v = self.b2 * v + (1 - self.b2) * np.square(grad) m, v = m / (1 - self.b1**t), v / (1 - self.b2**t) w -= self.a * m / (np.sqrt(v) + self.e) i += 1 return accuracy def trainR(self, input, target, epochs=500): m = 0 v = 0 v_2 = 0 t = 0 i = 0 self.model.setInput(input) w = self.w accuracy = 0 for i in range(epochs): t += 1 J, grad,accuracy = self.model.costFunction(target, w) self.b1 = np.random.uniform(low = 0, high = 1, size = 1) self.b2 = 1 - self.b1 m = self.b1 * m + (1 - self.b1) * grad v = self.b2 * v + (1 - self.b2) * np.square(grad) m, v = m / (1 - self.b1**t), v / (1 - self.b2**t) w -= self.a * m / (np.sqrt(v) + self.e) i += 1 return accuracy <file_sep>import numpy as np from utils import addOnes from activations import sigmoid def relu(self, input): return np.maximum(addOnes(input)@self.weights.T, 0) def sigmoid(self, input): return 1 / (1 + np.exp(-1 * (addOnes(input)@self.weights.T))) def softmax(self, input): input = sigmoid(self, input) result = [] for i in input: result.append(np.exp( i) / np.sum(np.exp(i))) return np.array(result) def tanh(self, input): x = addOnes(input)@self.weights.T t = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)) return t
981291884c62c706850981bd555d5b1f27ec056f
[ "Markdown", "Python" ]
11
Python
asalik13/Genie
e3243fc818bdaece19e453fa456a40566c641f23
70548350a55cc5f055d3228f7266cb0f14ef8af6
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include "mylib.h" #define SIZE 4 enum{ RIGHT, LEFT, UP, DOWN }; int a[SIZE][SIZE]={{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; void slide( int ); int main( void ) { int i=0,j=0; char c; int s=1; srand( time ( NULL )); while(1){ if(s){ clearScreen(); while(a[i][j]!=0){ i=rand()%SIZE; j=rand()%SIZE; } a[i][j]=2; for(i=0; i<SIZE; i++){ for(j=0; j<SIZE; j++){ textColor( (int)log2(a[i][j])%7+9 ); printf("%d\t", a[i][j]); } printf("\n"); } } s=1; c=getch(); switch(c){ case 'd': slide(RIGHT); break; case 'a': slide(LEFT); break; case 'w': slide(UP); break; case 's': slide(DOWN); break; default: s=0; break; } } } void slide( int d ) { int i,j,k; if(d==RIGHT){ for(k=0; k<SIZE; k++){ for(i=0; i<SIZE; i++){ for(j=1; j<SIZE; j++){ if(a[i][j]==a[i][j-1]){ a[i][j]=a[i][j] + a[i][j-1]; a[i][j-1]=0; } else if(a[i][j]==0 || a[i][j-1]==0){ a[i][j]=a[i][j] + a[i][j-1]; a[i][j-1]=0; } } } } } else if(d==LEFT){ for(k=0; k<SIZE; k++){ for(i=0; i<SIZE; i++){ for(j=SIZE-1; j>0; j--){ if(a[i][j]==a[i][j-1]){ a[i][j-1]=a[i][j] + a[i][j-1]; a[i][j]=0; } else if(a[i][j]==0 || a[i][j-1]==0){ a[i][j-1]=a[i][j] + a[i][j-1]; a[i][j]=0; } } } } } else if(d==UP){ for(k=0; k<SIZE; k++){ for(j=0; j<SIZE; j++){ for(i=SIZE-1; i>0; i--){ if(a[i][j]==a[i-1][j]){ a[i-1][j]=a[i][j] + a[i-1][j]; a[i][j]=0; } else if(a[i][j]==0 || a[i-1][j]==0){ a[i-1][j]=a[i][j] + a[i-1][j]; a[i][j]=0; } } } } } else if(d==DOWN){ for(k=0; k<SIZE; k++){ for(j=0; j<SIZE; j++){ for(i=1; i<SIZE; i++){ if(a[i][j]==a[i-1][j]){ a[i][j]=a[i][j] + a[i-1][j]; a[i-1][j]=0; } else if(a[i][j]==0 || a[i-1][j]==0){ a[i][j]=a[i][j] + a[i-1][j]; a[i-1][j]=0; } } } } } } <file_sep># 2048 ASCII style 2048 game
1c7c9e3628695d5e1afbb91d3075454989e25043
[ "Markdown", "C" ]
2
C
overengineer/2048
bd9b547187a4d514f6c95ec7bd1cc209db2a277e
5b5b70356742b7530b389167f10aeab35c9c6045
refs/heads/master
<file_sep>/* * comm.c * * Created on: Nov 17, 2015 * Author: anoop */ #include "comm.h" // Include Header for this C file uint8_t commReadyForWrite = 0; // Flag: UART TX to the node is ready for the next // data set. uint8_t commRXData[7]; // Buffer: Holds data(commands) received from the pi void commSendData(void) { // Function that sends a new data set over UART to the RasPi // Message format // // [0] compositeSlaveAddress | [1-4] Reading | [5-8] TimeStamp | [9] TimeStamp Set | [10-11] '\r\n' // uint8_t commData[] = {0,0,0,0,0,0,0,0,0,0,'\r','\n'}; // Buffer: Data to be sent dequeue(commData); // Call the dequeue function defined in storage.c to get // the next data set to be sent. UART_Transmit(&UART_1,commData,12); // Add the data to the TX buffer. commReadyForWrite = 0; // Clear the readForWrite flag to show that a TC // operation is currently ongoing. } void commTXHandler(void) { // Handler called on TX complete commReadyForWrite = 1; // Set the flag to show hardware is ready for next TX } void commRXHandler(void) { // Handler called on RC complete // Command structure: // // 0)Start signal // [0-5] = 69 // // 1)Update Slave Preset value // // [0]XMCNUM | [1] Cmd = 1 | [2-5] Preset value // // // 2)Update Minimum interval // // [0]XMCNUM | [1] Cmd = 2 | [2-5] Minimum Interval Value // // 3)Update Slave Threshold value // // [0]XMCNUM | [1] Cmd = 3 | [2-5] Threshold value // union byteToFloat converter1; // uint8_t to Float converter union timeStampUnionType converter2; // uint8_t to uint32_t converter int i,flag = 1, slaveNum; if(commRXData[0] == 68) { switch(commRXData[1]) // Check which command was sent { case 1: // Update slave preset converter1.b[0] = commRXData[3]; converter1.b[1] = commRXData[4]; converter1.b[2] = commRXData[5]; converter1.b[3] = commRXData[6]; for(slaveNum = 1; slaveNum <= MB_MAX_SLAVE; slaveNum++) { mbPreset[slaveNum] = mbPreviousReading[slaveNum] + converter1.f; } break; case 2: // Update minimum interval for readings converter2.b[0] = commRXData[2]; converter2.b[1] = commRXData[3]; converter2.b[2] = commRXData[4]; converter2.b[3] = commRXData[5]; mbMinInterval = converter2.counter; break; case 3: // Update slave threshold converter1.b[0] = commRXData[3]; converter1.b[1] = commRXData[4]; converter1.b[2] = commRXData[5]; converter1.b[3] = commRXData[6]; mbThreshold = converter1.f; break; } } else if(commRXData[0] == 69) { for(i=0;i<6;i++) { if(commRXData[i] != 69) { flag = 0; } } if(flag) { DIGITAL_IO_SetOutputHigh(&DIGITAL_IO_0); timeStampInit(); // Initialise SysTimer for TimeStamp commReadyForWrite = 1; for(slaveNum = 1; slaveNum <= MB_MAX_SLAVE; slaveNum++) { if(mbPreset[slaveNum] == 0) { mbPreset[slaveNum] = mbPreviousReading[slaveNum]; } } } } UART_Receive(&UART_1,commRXData,6); // Setup receive for the next cmd } void startCommRX(void) { // Function to start the first command receive UART_Receive(&UART_1,commRXData,6); } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using System.IO; using System.IO.Ports; using System.Collections.Concurrent; using System.Globalization; namespace civil_infineon { class FileLocks { //master file and day wise file generation public static String[] Months = new String[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; public static readonly object locker = new Object(); public static void AppendAllText(string value) { DateTime now = DateTime.Now; String date = now.Day.ToString(); String month = Months[now.Month - 1]; String year = now.Year.ToString(); String filepath = year + @"\" + month + @"\";// +date; String filename = now.ToString("yyyyMMdd"); Directory.CreateDirectory(Path.GetDirectoryName(filepath)); Directory.CreateDirectory(Path.GetDirectoryName(@"master\")); //lock (locker) try { File.AppendAllText(@"master\master.csv", value); File.AppendAllText(filepath + "" + filename + ".csv", value); } catch(Exception e) { Console.WriteLine("FILEerr"); } } } } <file_sep>/* * modbus.c * * Created on: Nov 16, 2015 * Author: anoop */ #include "modbus/modbus.h" uint8_t mbCurrentSlave = 1; uint8_t mbReadyForRead = 1; uint8_t mbIPData[9]; float mbPreset[MB_MAX_SLAVE + 1] = {0}; float mbThreshold = 10; float mbPreviousReading[MB_MAX_SLAVE + 1] = {0}; uint8_t modbusMessage[7][8] = { {0}, // There's no slave 0 {0x01,0x03,0x00,0x14,0x00,0x02,0x84,0x0F}, {0x02,0x03,0x00,0x14,0x00,0x02,0x84,0x3C}, {0x03,0x03,0x00,0x14,0x00,0x02,0x85,0xED}, {0x04,0x03,0x00,0x14,0x00,0x02,0x84,0x5A}, {0x05,0x03,0x00,0x14,0x00,0x02,0x85,0x8B}, {0x06,0x03,0x00,0x14,0x00,0x02,0x85,0xB8} }; void mbRXCompleteHandler(void) { node newNode; // Create new node with data to be queued newNode.slaveAddress = mbCurrentSlave; newNode.reading.b[1] = mbIPData[3]; newNode.reading.b[0] = mbIPData[4]; newNode.reading.b[3] = mbIPData[5]; newNode.reading.b[2] = mbIPData[6]; newNode.timeStamp = globalTimeStamp; newNode.reading.f -= mbPreset[mbCurrentSlave]; if(mbNeedIntervalReading[mbCurrentSlave] && commReadyForWrite) // Check whether its time to store an interval reading { mbNeedIntervalReading[mbCurrentSlave] = 0; newNode.isThreshold = 0; while(enqueue(newNode)); } else if(abs(newNode.reading.f - mbPreviousReading[mbCurrentSlave]) > mbThreshold && commReadyForWrite) // Check if its above threshold (Vehicle is passing) { newNode.isThreshold = 1; while(enqueue(newNode)); } mbPreviousReading[mbCurrentSlave] = newNode.reading.f; if(mbCurrentSlave == MB_MAX_SLAVE) { mbCurrentSlave = 1; } else { mbCurrentSlave++; } mbTimeout = 0; mbReadyForRead = 1; } void mbReadFloat(uint8_t slaveAddress) { // Send the frame corresponding to the given slave and setup for receive delayMs(3); // Need to have this delay here or things get too fast for the slaves to respond UART_Transmit(&UART_0,&(modbusMessage[slaveAddress][0]),8); // Send to slave UART_Receive(&UART_0, mbIPData, 9); // Start RX for response mbReadyForRead = 0; mbTimeout = 0; } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using System.IO; using System.IO.Ports; using System.Collections.Concurrent; namespace civil_infineon { public partial class Form1 : Form { // Add this variable string RxString; string com1, baud1; ConcurrentQueue<byte[]> q = new ConcurrentQueue<byte[]>(); //DateTime saveNow, saveUtcNow; UInt64 unixTimestamp; DateTime present; //string PATH; public Form1() { InitializeComponent(); } public Form1(string com, string baud)//, string path) { InitializeComponent(); com1 = com; baud1 = baud; //PATH = path; } private void buttonStart_Click(object sender, EventArgs e) { string comName, baudRate; //string appPath = Path.GetDirectoryName(Application.ExecutablePath) + "\\default.ini"; try { comName = comboBoxCom.SelectedItem.ToString(); baudRate = comboBoxBaud.SelectedItem.ToString(); //File.WriteAllText(appPath, (comName + "," + baudRate+"\r\n!Please do not alter this File")); } catch (Exception ce) { MessageBox.Show("Please Select Com Port Name\n and \n Baud Rate\n" + ce.Message.ToString()); return; } try { serialPort1.PortName = comName; serialPort1.BaudRate = int.Parse(baudRate); buttonSave.Enabled = buttonSave2.Enabled = false; serialPort1.Open(); //unixTimestamp = (UInt64)(DateTime.UtcNow.Subtract(new DateTime(1, 1, 1))).TotalMilliseconds; present = DateTime.Now;//new DateTime((long)unixTimestamp); serialPort1.Write("EEEEEE"); serialPort1.Write("EEEEEE"); serialPort1.Write("EEEEEE"); backgroundWorker1.RunWorkerAsync(); if (serialPort1.IsOpen) { buttonStart.Enabled = false; buttonStop.Enabled = true; textBox1.ReadOnly = false; //serialPort1.DtrEnable = true; //Thread.Sleep(100); //serialPort1.DtrEnable = false; } } catch (Exception ioe) { MessageBox.Show("Com port may be in use.\r\nPlease select another port\r\n"); comName = ioe.ToString(); buttonSave.Enabled = buttonSave2.Enabled = true; return; } } private void buttonStop_Click(object sender, EventArgs e) { try { buttonSave.Enabled = buttonSave2.Enabled = true; if (serialPort1.IsOpen) { FileLocks.AppendAllText("DISCONNECTED: Form 1 (" + DateTime.Now.ToString("dd/MM/yyyy-HH:mm:ss") + ")" + Environment.NewLine + Environment.NewLine); buttonStart.Enabled = true; buttonStop.Enabled = false; textBox1.ReadOnly = true; backgroundWorker1.CancelAsync(); backgroundWorker2.CancelAsync(); serialPort1.Close(); } } catch { } } private void Form1_Load(object sender, EventArgs e) { try { string[] ports = SerialPort.GetPortNames(); string[] comvalues = new string[] { "COM1", "9600" }; char[] charsep = new char[] { ',' }; Console.WriteLine("The following serial ports were found:"); comboBoxCom.BeginUpdate(); // Display each port name to the console. foreach (string port in ports) { comboBoxCom.Items.Add(port); } comboBoxCom.EndUpdate(); comboBoxCom.SelectedText = com1; comboBoxBaud.SelectedText = baud1; comboBoxCom.SelectedIndex = comboBoxCom.FindString(com1); comboBoxBaud.SelectedIndex = comboBoxBaud.FindString(baud1); buttonStart_Click(null, null); } catch { } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { try { if (backgroundWorker1.IsBusy) backgroundWorker1.CancelAsync(); if (backgroundWorker2.IsBusy) backgroundWorker2.CancelAsync(); if (serialPort1.IsOpen) serialPort1.Close(); } catch { } } private void DisplayText(object sender, EventArgs e) { try { if (RxString.Equals("\b")) return; else textBox1.AppendText(RxString); } catch { } } private void DisplayText() { try { if (RxString.Equals("\b")) return; else { textBox1.AppendText(RxString); } } catch { } } private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { } private void buttonClearall_Click(object sender, EventArgs e) { try { textBox1.Clear(); } catch { } } private void button1_Click(object sender, EventArgs e) { try { serialPort1.Dispose(); backgroundWorker1.CancelAsync(); backgroundWorker2.CancelAsync(); this.Close(); } catch { } } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { //byte[] byteA = new byte[13]; string reading; char[] charInp; byte[] byteInp; //Console.WriteLine("%d\n", k++); while (true) { try { if (backgroundWorker1.CancellationPending) { backgroundWorker1.CancelAsync(); backgroundWorker2.CancelAsync(); break; } //else reading = serialPort1.ReadLine(); Console.WriteLine("Background"); Console.WriteLine(reading.Length); if (reading.Length != 11) continue; charInp = reading.ToCharArray(); byteInp = Encoding.ASCII.GetBytes(charInp); q.Enqueue(byteInp); if (!backgroundWorker2.IsBusy && !q.IsEmpty) backgroundWorker2.RunWorkerAsync(); } catch { if (backgroundWorker1.CancellationPending) backgroundWorker1.CancelAsync(); break; } } } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { } private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { byte[] inp; while (!q.IsEmpty) { //if (backgroundWorker1.IsBusy) Thread.Sleep(100); q.TryDequeue(out inp); //foreach (byte k in inp) //{ //Console.WriteLine(k.ToString()); try { UInt64 integerVal = (UInt64)BitConverter.ToUInt32(inp, 5); float floatVal = BitConverter.ToSingle(inp, 1); this.Invoke((MethodInvoker)delegate { textBox1.AppendText(inp[0].ToString() + " " + floatVal.ToString() + " " + (present.AddMilliseconds(integerVal)).ToString() + " " + DateTime.Now.ToString()); textBox1.AppendText(Environment.NewLine); }); FileLocks.AppendAllText(inp[0].ToString() + "," + floatVal.ToString() + "," + (present.AddMilliseconds(integerVal)).ToString() + "," + DateTime.Now.ToString() + Environment.NewLine);//, Encoding.ASCII); } catch { } } } private void buttonSave_Click(object sender, EventArgs e) { try { saveFileDialog1.Title = "Save it to..."; saveFileDialog1.Filter = "Text(.txt)|*.txt"; saveFileDialog1.ShowDialog(); if (saveFileDialog1.FileName != "") { File.AppendAllText(saveFileDialog1.FileName, textBox1.Text);//Append } } catch { } } private void buttonSave2_Click(object sender, EventArgs e) { try { buttonSave2.Text = "SAVING... 0%"; saveFileDialog1.Title = "Save it to..."; saveFileDialog1.Filter = "CSV(.csv)|*.csv"; saveFileDialog1.ShowDialog(); if (saveFileDialog1.FileName != "") { backgroundWorker3.RunWorkerAsync(saveFileDialog1.FileName); } } catch { } } private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e) { try { var csv = new StringBuilder(); string s; string csvStr; int len = textBox1.Lines.Length; for (int i = 0; i < len; i++) { s = textBox1.Lines[i]; csvStr = s.Replace(' ', ','); if (csvStr != "") File.AppendAllText((string)e.Argument, csvStr + Environment.NewLine); backgroundWorker3.ReportProgress((i * 100) / len); } } catch { } } private void backgroundWorker3_ProgressChanged(object sender, ProgressChangedEventArgs e) { buttonSave2.Text = "SAVING... " + e.ProgressPercentage + "%"; } private void backgroundWorker3_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { buttonSave2.Text = "Save as .csv"; } } } <file_sep>/* * comm.h * * Created on: Nov 17, 2015 * Author: anoop */ #ifndef COMM_H_ #define COMM_H_ #include <DAVE.h> //DAVE App Includes #include "storage/storage.h" //Temporary Storage Implementation #include "modbus/modbus.h" //Modbus Implementation #include "timer/timer.h" //Timestamp and Delay extern uint8_t commReadyForWrite; //Flag: UART TX to the node is ready for the next //data set. #define XMCNUM 3 void commSendData(void); void commTXHandler(void); void commRXHandler(void); void startCommRX(void); #endif /* COMM_H_ */ <file_sep>/* * timer.h * * Created on: Nov 16, 2015 * Author: anoop */ #ifndef TIMER_H_ #define TIMER_H_ #include <DAVE.h> uint32_t delayHandleCounter; extern uint32_t mbMinInterval; extern uint8_t mbNeedIntervalReading[7]; extern uint32_t mbTimeout; void delayHandler(void); void delayMs(unsigned int); void timeStampHandler(void); void timeStampInit(void); union timeStampUnionType { uint32_t counter; uint8_t b[4]; }; struct timeStampStructureType { union timeStampUnionType ts; uint8_t set; }globalTimeStamp; #endif /* TIMER_H_ */ <file_sep>/* * main.c * * Created on: 2015 Nov 18 13:03:43 * Author: anoop */ #include <DAVE.h> // Declarations from DAVE Code Generation (includes SFR declaration) #include "modbus/modbus.h" // Modbus #include "comm/comm.h" // Connection to the node int main(void) { DAVE_STATUS_t status; // Startup error status = DAVE_Init(); // Initialization of DAVE APPs if(status == DAVE_STATUS_FAILURE) { XMC_DEBUG("DAVE APPs initialization failed\n"); while(1U) { DIGITAL_IO_SetOutputHigh(&DIGITAL_IO_1); // Turn on LED2 for errors } } startCommRX(); // Start serial connection with the node while(1U) { if(mbTimeout > MB_TIMEOUT) // Check if the current slave is taking too long to reply // If it is, move on to the next one { if(mbCurrentSlave == MB_MAX_SLAVE) { mbCurrentSlave = 1; } else { mbCurrentSlave++; } mbReadyForRead = 1; } if(mbReadyForRead) { mbReadFloat(mbCurrentSlave); // Poll the mbReadyForRead flag and start a new reading } if(commReadyForWrite && !queueIsEmpty) { commSendData(); // commReadyForWrite - UART Hardware ready // queueIsEmpty - Readings Queue } } } <file_sep>/* * storage.h * * Created on: Nov 17, 2015 * Author: anoop */ #ifndef STORAGE_H_ #define STORAGE_H_ #define CQ_SIZE 675 #include "timer/timer.h" #include "comm/comm.h" union byteToFloat { float f; uint8_t b[4]; }; typedef struct { uint8_t slaveAddress; union byteToFloat reading; struct timeStampStructureType timeStamp; uint8_t isThreshold; }node; struct circularQueueContainer { node data[CQ_SIZE]; int front; int rear; }cQ; int enqueue(node); void dequeue(uint8_t*); extern int queueIsEmpty; #endif /* STORAGE_H_ */ <file_sep>/* * modbus.h * * Created on: Nov 16, 2015 * Author: anoop */ #ifndef MODBUS_H_ #define MODBUS_H_ #include <DAVE.h> #include <stdint.h> #include <stdlib.h> #include "timer/timer.h" #include "storage/storage.h" #define MB_MAX_SLAVE 6 // Number of MB slaves we have #define MB_TIMEOUT 100 union byteToWord // Convert bytes to uint16 { uint16_t w; uint8_t b[2]; }; void mbReadFloat(uint8_t); // Function to get new reading void mbRXCompleteHandler(void); // UART RX Handler extern uint8_t mbReadyForRead; // Flag: Ready for new ModBus transfer extern uint8_t mbCurrentSlave; // Slave ID of current slave extern float mbPreset[MB_MAX_SLAVE + 1]; // Array of preset values to get the readings to 0 extern float mbThreshold; extern float mbPreviousReading[MB_MAX_SLAVE + 1]; #endif /* MODBUS_H_ */ <file_sep>/* * storage.c * * Created on: Nov 17, 2015 * Author: anoop */ #include "storage.h" // Fairly standard Circular Queue implementation int queueIsEmpty = 1; int enqueue(node newNode) { if(cQ.front == ((cQ.rear+1) % CQ_SIZE) && cQ.rear != -1) { // Queue Full return -1; } else { // Enqueue cQ.rear = (cQ.rear + 1) % CQ_SIZE; cQ.data[cQ.rear] = newNode; queueIsEmpty = 0; return 0; } } void dequeue(uint8_t str[]) { node temp; if(cQ.rear == cQ.front) { temp = cQ.data[cQ.front]; cQ.front = 0; cQ.rear = -1; queueIsEmpty = 1; } else { temp = cQ.data[cQ.front]; cQ.front = (cQ.front + 1) % CQ_SIZE; } str[0] = temp.slaveAddress + XMCNUM * 6; if(temp.isThreshold) { str[0] += 42; } str[1] = temp.reading.b[0]; str[2] = temp.reading.b[1]; str[3] = temp.reading.b[2]; str[4] = temp.reading.b[3]; str[5] = temp.timeStamp.ts.b[0]; str[6] = temp.timeStamp.ts.b[1]; str[7] = temp.timeStamp.ts.b[2]; str[8] = temp.timeStamp.ts.b[3]; str[9] = temp.timeStamp.set; } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.IO.Ports; namespace civil_infineon { public partial class CivilProject : Form { //string PathToCSV; public CivilProject() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string[] ports = SerialPort.GetPortNames(); comboBox1.BeginUpdate(); // Display each port name to the console. foreach (string port in ports) { comboBox1.Items.Add(port); } comboBox1.EndUpdate(); comboBox2.BeginUpdate(); // Display each port name to the console. foreach (string port in ports) { comboBox2.Items.Add(port); } comboBox2.EndUpdate(); comboBox3.BeginUpdate(); // Display each port name to the console. foreach (string port in ports) { comboBox3.Items.Add(port); } comboBox3.EndUpdate(); comboBox4.BeginUpdate(); // Display each port name to the console. foreach (string port in ports) { comboBox4.Items.Add(port); } comboBox4.EndUpdate(); comboBox5.BeginUpdate(); // Display each port name to the console. foreach (string port in ports) { comboBox5.Items.Add(port); } comboBox5.EndUpdate(); comboBox6.BeginUpdate(); // Display each port name to the console. foreach (string port in ports) { comboBox6.Items.Add(port); } comboBox6.EndUpdate(); comboBox7.BeginUpdate(); // Display each port name to the console. foreach (string port in ports) { comboBox7.Items.Add(port); } comboBox7.EndUpdate(); } private void button1_Click(object sender, EventArgs e) { if (comboBox1.Text == "") { MessageBox.Show("Select com port"); return; } Form f = new Form1(comboBox1.Text, comboBoxBaud.Text); f.Show(); } private void button2_Click(object sender, EventArgs e) { if (comboBox2.Text == "") { MessageBox.Show("Select com port"); return; } Form f = new Form2(comboBox2.Text, comboBoxBaud.Text); f.Show(); } private void button3_Click(object sender, EventArgs e) { if (comboBox3.Text == "") { MessageBox.Show("Select com port"); return; } Form f = new Form3(comboBox3.Text, comboBoxBaud.Text); f.Show(); } private void button4_Click(object sender, EventArgs e) { if (comboBox4.Text == "") { MessageBox.Show("Select com port"); return; } Form f = new Form4(comboBox4.Text, comboBoxBaud.Text); f.Show(); } private void button5_Click(object sender, EventArgs e) { if (comboBox5.Text == "") { MessageBox.Show("Select com port"); return; } Form f = new Form5(comboBox5.Text, comboBoxBaud.Text); f.Show(); } private void button6_Click(object sender, EventArgs e) { if (comboBox6.Text == "") { MessageBox.Show("Select com port"); return; } Form f = new Form6(comboBox6.Text, comboBoxBaud.Text); f.Show(); } private void button7_Click(object sender, EventArgs e) { if (comboBox7.Text == "") { MessageBox.Show("Select com port"); return; } Form f = new Form7(comboBox7.Text, comboBoxBaud.Text); f.Show(); } private void button8_Click(object sender, EventArgs e) { int anyCOMselected = 0; //openFileDialog1.Filter = "CSV|*.csv"; //if (openFileDialog1.ShowDialog() == DialogResult.OK) //{ //PathToCSV = openFileDialog1.FileName; if (comboBox1.Text != "") { anyCOMselected = 1; button1_Click(null, null); } if (comboBox2.Text != "") { anyCOMselected = 1; button2_Click(null, null); } if (comboBox3.Text != "") { anyCOMselected = 1; button3_Click(null, null); } if (comboBox4.Text != "") { anyCOMselected = 1; button4_Click(null, null); } if (comboBox5.Text != "") { anyCOMselected = 1; button5_Click(null, null); } if (comboBox6.Text != "") { anyCOMselected = 1; button6_Click(null, null); } if (comboBox7.Text != "") { anyCOMselected = 1; button7_Click(null, null); } //} if (anyCOMselected == 0) { MessageBox.Show("No open COM port"); } } /*private void button9_Click(object sender, EventArgs e) //TEST { int i = 0; while (i < 10) { FileLocks.AppendAllText("\testing button ..."); i++; } //==== TODO ==== }*/ } } <file_sep>/* * timer.c * * Created on: Nov 16, 2015 * Author: anoop */ #include "timer/timer.h" uint32_t mbMinInterval= 10000;//1000 * 60 * 10; // The minimum interval at which readings are to be taken // Default 0 to take all the readings uint32_t mbTimeout = 0; // Time out counter for MB Transfers uint8_t mbNeedIntervalReading[7] = {0}; // Array of flags to check if an interval reading is needed uint32_t timerID = 0; void timeStampInit(void) { // Initialise SysTimer to generate TimeStamps globalTimeStamp.set = 0; globalTimeStamp.ts.counter = 0; if(timerID == 0) { timerID = SYSTIMER_CreateTimer(1000U,SYSTIMER_MODE_PERIODIC,(void*)timeStampHandler,NULL); SYSTIMER_StartTimer(timerID); } } void timeStampHandler(void) { static uint32_t prevInterval = 0; mbTimeout++; if((++(globalTimeStamp.ts.counter)) == 4294967295) { (globalTimeStamp.set)++; globalTimeStamp.ts.counter = 0; } if((globalTimeStamp.ts.counter - prevInterval) > mbMinInterval) { prevInterval = globalTimeStamp.ts.counter; for(int i = 1; i < 7; i++) { mbNeedIntervalReading[i] = 1; } } else if( globalTimeStamp.ts.counter < prevInterval) { prevInterval = 4294967295 - prevInterval; } } void delayHandler(void) { delayHandleCounter++; } void delayMs(unsigned int delayVal) { delayHandleCounter = 0; PWM_Start(&PWM_0); while(delayHandleCounter < delayVal); PWM_Stop(&PWM_0); }
e1b086cc671fe541aa734b259576bd82c0de557a
[ "C#", "C" ]
12
C
anoopknight/civil-xmc
d87b0869f4df0c7bb34e3d1c3afbab73b89f426e
4ac2ded30ef453f132988d5f88d3d93be9acb75a
refs/heads/master
<repo_name>fireteam99/bmbot<file_sep>/simple_agent.py from pysc2.agents import base_agent from pysc2.lib import actions from pysc2.lib import features import time import sys # Functions _BUILD_BARRACKS = actions.FUNCTIONS.Build_Barracks_screen.id _BUILD_SUPPLYDEPOT = actions.FUNCTIONS.Build_SupplyDepot_screen.id _BUILD_REFINERY = actions.FUNCTIONS.Build_Refinery_screen.id _NOOP = actions.FUNCTIONS.no_op.id _SELECT_POINT = actions.FUNCTIONS.select_point.id _TRAIN_MARINE = actions.FUNCTIONS.Train_Marine_quick.id _RALLY_UNITS_MINIMAP = actions.FUNCTIONS.Rally_Units_minimap.id _SELECT_ARMY = actions.FUNCTIONS.select_army.id _ATTACK_MINIMAP = actions.FUNCTIONS.Attack_minimap.id # Features _PLAYER_RELATIVE = features.SCREEN_FEATURES.player_relative.index _UNIT_TYPE = features.SCREEN_FEATURES.unit_type.index # Unit IDs _TERRAN_BARRACKS = 21 _TERRAN_COMMANDCENTER = 18 _TERRAN_SUPPLYDEPOT = 19 _TERRAN_SCV = 45 _VESPENE_GEYSER = 342 # Parameters _PLAYER_SELF = 1 _SUPPLY_USED = 3 _SUPPLY_MAX = 4 _NOT_QUEUED = [0] _QUEUED = [1] class SimpleAgent(base_agent.BaseAgent): base_top_left = None supply_depot_built = False scv_selected = False barracks_built = False barracks_selected = False barracks_rallied = False army_selected = False army_rallied = False refinery_built = False def closestVespeneGeyser(self, base_cord_x, base_cord_y, geysers_x, geysers_y): smallest = sys.maxsize closest_geyser_index = 0 list_len = len(geysers_x) for i in range(0,list_len): geyser_x_cord = geysers_x[i] geyser_y_cord = geysers_y[i] distance = ((base_cord_x - geyser_x_cord)**2 + (base_cord_y - geyser_y_cord)**2) if(distance < smallest): smallest = distance closest_geyser_index = i return [geysers_x[closest_geyser_index], geysers_y[closest_geyser_index]] def transformLocation(self, x, x_distance, y, y_distance): if not self.base_top_left: return [x - x_distance, y - y_distance] return [x + x_distance, y + y_distance] def step(self, obs): super(SimpleAgent, self).step(obs) time.sleep(0.1) if self.base_top_left is None: player_y, player_x = (obs.observation["minimap"][_PLAYER_RELATIVE] == _PLAYER_SELF).nonzero() self.base_top_left = player_y.mean() <= 31 if not self.supply_depot_built: if not self.scv_selected: unit_type = obs.observation["screen"][_UNIT_TYPE] unit_y, unit_x = (unit_type == _TERRAN_SCV).nonzero() target = [unit_x[0], unit_y[0]] self.scv_selected = True return actions.FunctionCall(_SELECT_POINT, [_NOT_QUEUED, target]) elif _BUILD_SUPPLYDEPOT in obs.observation["available_actions"]: unit_type = obs.observation["screen"][_UNIT_TYPE] unit_y, unit_x = (unit_type == _TERRAN_COMMANDCENTER).nonzero() print("cmd center is at: x=" + str(unit_x.mean()) + " y=" + str(unit_y.mean())) target = self.transformLocation(int(unit_x.mean()), 0, int(unit_y.mean()), 20) self.supply_depot_built = True return actions.FunctionCall(_BUILD_SUPPLYDEPOT, [_NOT_QUEUED, target]) elif not self.refinery_built: if not self.scv_selected: unit_type = obs.observation["screen"][_UNIT_TYPE] unit_y, unit_x = (unit_type == _TERRAN_SCV).nonzero() target = [unit_x[0], unit_y[0]] self.scv_selected = True return actions.FunctionCall(_SELECT_POINT, [_NOT_QUEUED, target]) elif _BUILD_REFINERY in obs.observation["available_actions"]: print("attempting to build refinery") unit_type = obs.observation["screen"][_UNIT_TYPE] unit_y, unit_x = (unit_type == _VESPENE_GEYSER).nonzero() print(str(unit_x)) print(str(unit_y)) unit_type = obs.observation["screen"][_UNIT_TYPE] command_center_y, command_center_x = (unit_type == _TERRAN_COMMANDCENTER).nonzero() target = unit_x[23], unit_y[23] #target = self.closestVespeneGeyser(command_center_x[0], command_center_y[0], unit_x, unit_y) self.refinery_built = True return actions.FunctionCall(_BUILD_REFINERY, [_NOT_QUEUED, target]) elif not self.barracks_built and self.refinery_built: if _BUILD_BARRACKS in obs.observation["available_actions"]: unit_type = obs.observation["screen"][_UNIT_TYPE] unit_y, unit_x = (unit_type == _TERRAN_COMMANDCENTER).nonzero() target = self.transformLocation(int(unit_x.mean()), 20, int(unit_y.mean()), 0) self.barracks_built = True return actions.FunctionCall(_BUILD_BARRACKS, [_NOT_QUEUED, target]) elif not self.barracks_rallied: if not self.barracks_selected: unit_type = obs.observation["screen"][_UNIT_TYPE] unit_y, unit_x = (unit_type == _TERRAN_BARRACKS).nonzero() if unit_y.any(): target = [int(unit_x.mean()), int(unit_y.mean())] self.barracks_selected = True return actions.FunctionCall(_SELECT_POINT, [_NOT_QUEUED, target]) else: self.barracks_rallied = True if self.base_top_left: return actions.FunctionCall(_RALLY_UNITS_MINIMAP, [_NOT_QUEUED, [29, 21]]) return actions.FunctionCall(_RALLY_UNITS_MINIMAP, [_NOT_QUEUED, [29, 46]]) elif obs.observation["player"][_SUPPLY_USED] < obs.observation["player"][_SUPPLY_MAX] and _TRAIN_MARINE in \ obs.observation["available_actions"]: return actions.FunctionCall(_TRAIN_MARINE, [_QUEUED]) elif not self.army_rallied: if not self.army_selected: if _SELECT_ARMY in obs.observation["available_actions"]: self.army_selected = True self.barracks_selected = False return actions.FunctionCall(_SELECT_ARMY, [_NOT_QUEUED]) elif _ATTACK_MINIMAP in obs.observation["available_actions"]: self.army_rallied = True self.army_selected = False if self.base_top_left: return actions.FunctionCall(_ATTACK_MINIMAP, [_NOT_QUEUED, [39, 45]]) return actions.FunctionCall(_ATTACK_MINIMAP, [_NOT_QUEUED, [21, 24]]) return actions.FunctionCall(_NOOP, [])
0eccc3ab0ae88620823b93de493ef5836232cd17
[ "Python" ]
1
Python
fireteam99/bmbot
41b550f363a348f5bd07ab7b4deea62dae4bde87
091353bd6726e1e8c1d7ee73ac7e1941d5d8d62b
refs/heads/master
<file_sep>import numpy as np import torch import cv2 from sklearn.metrics import roc_auc_score class AverageMeter(object): def __init__(self): self.initialized = False self.val = None self.avg = None self.sum = None self.count = None def initialize(self, val, weight): self.val = val self.avg = val self.sum = np.multiply(val, weight) self.count = weight self.initialized = True def update(self, val, weight=1): if not self.initialized: self.initialize(val, weight) else: self.add(val, weight) def add(self, val, weight): self.val = val self.sum = np.add(self.sum, np.multiply(val, weight)) self.count = self.count + weight self.avg = self.sum / self.count @property def value(self): return np.round(self.val, 4) @property def average(self): return np.round(self.avg, 4) def get_metrics(predict, target, threshold=None, predict_b=None): predict = torch.sigmoid(predict).cpu().detach().numpy().flatten() if predict_b is not None: predict_b = predict_b.flatten() else: predict_b = np.where(predict >= threshold, 1, 0) if torch.is_tensor(target): target = target.cpu().detach().numpy().flatten() else: target = target.flatten() tp = (predict_b * target).sum() tn = ((1 - predict_b) * (1 - target)).sum() fp = ((1 - target) * predict_b).sum() fn = ((1 - predict_b) * target).sum() auc = roc_auc_score(target, predict) acc = (tp + tn) / (tp + fp + fn + tn) pre = tp / (tp + fp) sen = tp / (tp + fn) spe = tn / (tn + fp) iou = tp / (tp + fp + fn) f1 = 2 * pre * sen / (pre + sen) return { "AUC": np.round(auc, 4), "F1": np.round(f1, 4), "Acc": np.round(acc, 4), "Sen": np.round(sen, 4), "Spe": np.round(spe, 4), "pre": np.round(pre, 4), "IOU": np.round(iou, 4), } def count_connect_component(predict, target, threshold=None, connectivity=8): if threshold != None: predict = torch.sigmoid(predict).cpu().detach().numpy() predict = np.where(predict >= threshold, 1, 0) if torch.is_tensor(target): target = target.cpu().detach().numpy() pre_n, _, _, _ = cv2.connectedComponentsWithStats(np.asarray( predict, dtype=np.uint8)*255, connectivity=connectivity) gt_n, _, _, _ = cv2.connectedComponentsWithStats(np.asarray( target, dtype=np.uint8)*255, connectivity=connectivity) return pre_n/gt_n <file_sep>import torch import torch.nn as nn class FocalLoss(nn.Module): def __init__(self, gamma=2, alpha=None, ignore_index=255, reduction='mean'): super(FocalLoss, self).__init__() self.gamma = gamma self.reduction = reduction self.CE_loss = nn.CrossEntropyLoss( reduction=reduction, ignore_index=ignore_index, weight=alpha) def forward(self, output, target): logpt = self.CE_loss(output, target) pt = torch.exp(-logpt) loss = ((1 - pt) ** self.gamma) * logpt if self.reduction == 'mean': return loss.mean() return loss.sum() class BCELoss(nn.Module): def __init__(self, reduction="mean", pos_weight=1.0): pos_weight = torch.tensor(pos_weight).cuda() super(BCELoss, self).__init__() self.bce_loss = nn.BCEWithLogitsLoss( reduction=reduction, pos_weight=pos_weight) def forward(self, prediction, targets): return self.bce_loss(prediction, targets) class CELoss(nn.Module): def __init__(self, weight=[1, 1], ignore_index=-100, reduction='mean'): super(CELoss, self).__init__() weight = torch.tensor(weight).cuda() self.CE = nn.CrossEntropyLoss( weight=weight, ignore_index=ignore_index, reduction=reduction) def forward(self, output, target): loss = self.CE(output, target.squeeze(1).long()) return loss class DiceLoss(nn.Module): def __init__(self, smooth=1e-8): super(DiceLoss, self).__init__() self.smooth = smooth def forward(self, prediction, target): prediction = torch.sigmoid(prediction) intersection = 2 * torch.sum(prediction * target) + self.smooth union = torch.sum(prediction) + torch.sum(target) + self.smooth loss = 1 - intersection / union return loss class CE_DiceLoss(nn.Module): def __init__(self, reduction="mean", D_weight=0.5): super(CE_DiceLoss, self).__init__() self.DiceLoss = DiceLoss() self.BCELoss = BCELoss(reduction=reduction) self.D_weight = D_weight def forward(self, prediction, targets): return self.D_weight * self.DiceLoss(prediction, targets) + (1 - self.D_weight) * self.BCELoss(prediction, targets) <file_sep>import time import cv2 import torch import numpy as np import torch.backends.cudnn as cudnn import torch.nn as nn import torchvision.transforms.functional as TF from loguru import logger from tqdm import tqdm from trainer import Trainer from utils.helpers import dir_exists, remove_files, double_threshold_iteration from utils.metrics import AverageMeter, get_metrics, get_metrics, count_connect_component import ttach as tta class Tester(Trainer): def __init__(self, model, loss, CFG, checkpoint, test_loader, dataset_path, show=False): # super(Trainer, self).__init__() self.loss = loss self.CFG = CFG self.test_loader = test_loader self.model = nn.DataParallel(model.cuda()) self.dataset_path = dataset_path self.show = show self.model.load_state_dict(checkpoint['state_dict']) if self.show: dir_exists("save_picture") remove_files("save_picture") cudnn.benchmark = True def test(self): if self.CFG.tta: self.model = tta.SegmentationTTAWrapper( self.model, tta.aliases.d4_transform(), merge_mode='mean') self.model.eval() self._reset_metrics() tbar = tqdm(self.test_loader, ncols=150) tic = time.time() with torch.no_grad(): for i, (img, gt) in enumerate(tbar): self.data_time.update(time.time() - tic) img = img.cuda(non_blocking=True) gt = gt.cuda(non_blocking=True) pre = self.model(img) loss = self.loss(pre, gt) self.total_loss.update(loss.item()) self.batch_time.update(time.time() - tic) if self.dataset_path.endswith("DRIVE"): H, W = 584, 565 elif self.dataset_path.endswith("CHASEDB1"): H, W = 960, 999 elif self.dataset_path.endswith("DCA1"): H, W = 300, 300 if not self.dataset_path.endswith("CHUAC"): img = TF.crop(img, 0, 0, H, W) gt = TF.crop(gt, 0, 0, H, W) pre = TF.crop(pre, 0, 0, H, W) img = img[0,0,...] gt = gt[0,0,...] pre = pre[0,0,...] if self.show: predict = torch.sigmoid(pre).cpu().detach().numpy() predict_b = np.where(predict >= self.CFG.threshold, 1, 0) cv2.imwrite( f"save_picture/img{i}.png", np.uint8(img.cpu().numpy()*255)) cv2.imwrite( f"save_picture/gt{i}.png", np.uint8(gt.cpu().numpy()*255)) cv2.imwrite( f"save_picture/pre{i}.png", np.uint8(predict*255)) cv2.imwrite( f"save_picture/pre_b{i}.png", np.uint8(predict_b*255)) if self.CFG.DTI: pre_DTI = double_threshold_iteration( i, pre, self.CFG.threshold, self.CFG.threshold_low, True) self._metrics_update( *get_metrics(pre, gt, predict_b=pre_DTI).values()) if self.CFG.CCC: self.CCC.update(count_connect_component(pre_DTI, gt)) else: self._metrics_update( *get_metrics(pre, gt, self.CFG.threshold).values()) if self.CFG.CCC: self.CCC.update(count_connect_component( pre, gt, threshold=self.CFG.threshold)) tbar.set_description( 'TEST ({}) | Loss: {:.4f} | AUC {:.4f} F1 {:.4f} Acc {:.4f} Sen {:.4f} Spe {:.4f} Pre {:.4f} IOU {:.4f} |B {:.2f} D {:.2f} |'.format( i, self.total_loss.average, *self._metrics_ave().values(), self.batch_time.average, self.data_time.average)) tic = time.time() logger.info(f"###### TEST EVALUATION ######") logger.info(f'test time: {self.batch_time.average}') logger.info(f' loss: {self.total_loss.average}') if self.CFG.CCC: logger.info(f' CCC: {self.CCC.average}') for k, v in self._metrics_ave().items(): logger.info(f'{str(k):5s}: {v}') <file_sep>import torch import torch.nn as nn from .utils import InitWeights_He class conv(nn.Module): def __init__(self, in_c, out_c, dp=0): super(conv, self).__init__() self.in_c = in_c self.out_c = out_c self.conv = nn.Sequential( nn.Conv2d(out_c, out_c, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(out_c), nn.Dropout2d(dp), nn.LeakyReLU(0.1, inplace=True), nn.Conv2d(out_c, out_c, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(out_c), nn.Dropout2d(dp), nn.LeakyReLU(0.1, inplace=True)) self.relu = nn.LeakyReLU(0.1, inplace=True) def forward(self, x): res = x x = self.conv(x) out = x + res out = self.relu(out) return out class feature_fuse(nn.Module): def __init__(self, in_c, out_c): super(feature_fuse, self).__init__() self.conv11 = nn.Conv2d( in_c, out_c, kernel_size=1, padding=0, bias=False) self.conv33 = nn.Conv2d( in_c, out_c, kernel_size=3, padding=1, bias=False) self.conv33_di = nn.Conv2d( in_c, out_c, kernel_size=3, padding=2, bias=False, dilation=2) self.norm = nn.BatchNorm2d(out_c) def forward(self, x): x1 = self.conv11(x) x2 = self.conv33(x) x3 = self.conv33_di(x) out = self.norm(x1+x2+x3) return out class up(nn.Module): def __init__(self, in_c, out_c, dp=0): super(up, self).__init__() self.up = nn.Sequential( nn.ConvTranspose2d(in_c, out_c, kernel_size=2, padding=0, stride=2, bias=False), nn.BatchNorm2d(out_c), nn.LeakyReLU(0.1, inplace=False)) def forward(self, x): x = self.up(x) return x class down(nn.Module): def __init__(self, in_c, out_c, dp=0): super(down, self).__init__() self.down = nn.Sequential( nn.Conv2d(in_c, out_c, kernel_size=2, padding=0, stride=2, bias=False), nn.BatchNorm2d(out_c), nn.LeakyReLU(0.1, inplace=True)) def forward(self, x): x = self.down(x) return x class block(nn.Module): def __init__(self, in_c, out_c, dp=0, is_up=False, is_down=False, fuse=False): super(block, self).__init__() self.in_c = in_c self.out_c = out_c if fuse == True: self.fuse = feature_fuse(in_c, out_c) else: self.fuse = nn.Conv2d(in_c, out_c, kernel_size=1, stride=1) self.is_up = is_up self.is_down = is_down self.conv = conv(out_c, out_c, dp=dp) if self.is_up == True: self.up = up(out_c, out_c//2) if self.is_down == True: self.down = down(out_c, out_c*2) def forward(self, x): if self.in_c != self.out_c: x = self.fuse(x) x = self.conv(x) if self.is_up == False and self.is_down == False: return x elif self.is_up == True and self.is_down == False: x_up = self.up(x) return x, x_up elif self.is_up == False and self.is_down == True: x_down = self.down(x) return x, x_down else: x_up = self.up(x) x_down = self.down(x) return x, x_up, x_down class FR_UNet(nn.Module): def __init__(self, num_classes=1, num_channels=1, feature_scale=2, dropout=0.2, fuse=True, out_ave=True): super(FR_UNet, self).__init__() self.out_ave = out_ave filters = [64, 128, 256, 512, 1024] filters = [int(x / feature_scale) for x in filters] self.block1_3 = block( num_channels, filters[0], dp=dropout, is_up=False, is_down=True, fuse=fuse) self.block1_2 = block( filters[0], filters[0], dp=dropout, is_up=False, is_down=True, fuse=fuse) self.block1_1 = block( filters[0]*2, filters[0], dp=dropout, is_up=False, is_down=True, fuse=fuse) self.block10 = block( filters[0]*2, filters[0], dp=dropout, is_up=False, is_down=True, fuse=fuse) self.block11 = block( filters[0]*2, filters[0], dp=dropout, is_up=False, is_down=True, fuse=fuse) self.block12 = block( filters[0]*2, filters[0], dp=dropout, is_up=False, is_down=False, fuse=fuse) self.block13 = block( filters[0]*2, filters[0], dp=dropout, is_up=False, is_down=False, fuse=fuse) self.block2_2 = block( filters[1], filters[1], dp=dropout, is_up=True, is_down=True, fuse=fuse) self.block2_1 = block( filters[1]*2, filters[1], dp=dropout, is_up=True, is_down=True, fuse=fuse) self.block20 = block( filters[1]*3, filters[1], dp=dropout, is_up=True, is_down=True, fuse=fuse) self.block21 = block( filters[1]*3, filters[1], dp=dropout, is_up=True, is_down=False, fuse=fuse) self.block22 = block( filters[1]*3, filters[1], dp=dropout, is_up=True, is_down=False, fuse=fuse) self.block3_1 = block( filters[2], filters[2], dp=dropout, is_up=True, is_down=True, fuse=fuse) self.block30 = block( filters[2]*2, filters[2], dp=dropout, is_up=True, is_down=False, fuse=fuse) self.block31 = block( filters[2]*3, filters[2], dp=dropout, is_up=True, is_down=False, fuse=fuse) self.block40 = block(filters[3], filters[3], dp=dropout, is_up=True, is_down=False, fuse=fuse) self.final1 = nn.Conv2d( filters[0], num_classes, kernel_size=1, padding=0, bias=True) self.final2 = nn.Conv2d( filters[0], num_classes, kernel_size=1, padding=0, bias=True) self.final3 = nn.Conv2d( filters[0], num_classes, kernel_size=1, padding=0, bias=True) self.final4 = nn.Conv2d( filters[0], num_classes, kernel_size=1, padding=0, bias=True) self.final5 = nn.Conv2d( filters[0], num_classes, kernel_size=1, padding=0, bias=True) self.fuse = nn.Conv2d( 5, num_classes, kernel_size=1, padding=0, bias=True) self.apply(InitWeights_He) def forward(self, x): x1_3, x_down1_3 = self.block1_3(x) x1_2, x_down1_2 = self.block1_2(x1_3) x2_2, x_up2_2, x_down2_2 = self.block2_2(x_down1_3) x1_1, x_down1_1 = self.block1_1(torch.cat([x1_2, x_up2_2], dim=1)) x2_1, x_up2_1, x_down2_1 = self.block2_1( torch.cat([x_down1_2, x2_2], dim=1)) x3_1, x_up3_1, x_down3_1 = self.block3_1(x_down2_2) x10, x_down10 = self.block10(torch.cat([x1_1, x_up2_1], dim=1)) x20, x_up20, x_down20 = self.block20( torch.cat([x_down1_1, x2_1, x_up3_1], dim=1)) x30, x_up30 = self.block30(torch.cat([x_down2_1, x3_1], dim=1)) _, x_up40 = self.block40(x_down3_1) x11, x_down11 = self.block11(torch.cat([x10, x_up20], dim=1)) x21, x_up21 = self.block21(torch.cat([x_down10, x20, x_up30], dim=1)) _, x_up31 = self.block31(torch.cat([x_down20, x30, x_up40], dim=1)) x12 = self.block12(torch.cat([x11, x_up21], dim=1)) _, x_up22 = self.block22(torch.cat([x_down11, x21, x_up31], dim=1)) x13 = self.block13(torch.cat([x12, x_up22], dim=1)) if self.out_ave == True: output = (self.final1(x1_1)+self.final2(x10) + self.final3(x11)+self.final4(x12)+self.final5(x13))/5 else: output = self.final5(x13) return output <file_sep>import os import pickle import random import cv2 import numpy as np import torch from torchvision.transforms import functional as F def get_instance(module, name, config, *args): return getattr(module, config[name]['type'])(*args, **config[name]['args']) def seed_torch(seed=42): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True class Fix_RandomRotation(object): def __init__(self, degrees=360, resample=False, expand=False, center=None): self.degrees = degrees self.resample = resample self.expand = expand self.center = center @staticmethod def get_params(): p = torch.rand(1) if p >= 0 and p < 0.25: angle = -180 elif p >= 0.25 and p < 0.5: angle = -90 elif p >= 0.5 and p < 0.75: angle = 90 else: angle = 0 return angle def __call__(self, img): angle = self.get_params() return F.rotate(img, angle, self.resample, self.expand, self.center) def __repr__(self): format_string = self.__class__.__name__ + \ '(degrees={0}'.format(self.degrees) format_string += ', resample={0}'.format(self.resample) format_string += ', expand={0}'.format(self.expand) if self.center is not None: format_string += ', center={0}'.format(self.center) format_string += ')' return format_string def dir_exists(path): if not os.path.exists(path): os.makedirs(path) def remove_files(path): for root, dirs, files in os.walk(path, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) def read_pickle(path, type): with open(file=path + f"/{type}.pkl", mode='rb') as file: img = pickle.load(file) return img def save_pickle(path, type, img_list): with open(file=path + f"/{type}.pkl", mode='wb') as file: pickle.dump(img_list, file) def double_threshold_iteration(index,img, h_thresh, l_thresh, save=True): h, w = img.shape img = np.array(torch.sigmoid(img).cpu().detach()*255, dtype=np.uint8) bin = np.where(img >= h_thresh*255, 255, 0).astype(np.uint8) gbin = bin.copy() gbin_pre = gbin-1 while(gbin_pre.all() != gbin.all()): gbin_pre = gbin for i in range(h): for j in range(w): if gbin[i][j] == 0 and img[i][j] < h_thresh*255 and img[i][j] >= l_thresh*255: if gbin[i-1][j-1] or gbin[i-1][j] or gbin[i-1][j+1] or gbin[i][j-1] or gbin[i][j+1] or gbin[i+1][j-1] or gbin[i+1][j] or gbin[i+1][j+1]: gbin[i][j] = 255 if save: cv2.imwrite(f"save_picture/bin{index}.png", bin) cv2.imwrite(f"save_picture/gbin{index}.png", gbin) return gbin/255 def recompone_overlap(preds, img_h, img_w, stride_h, stride_w): assert (len(preds.shape) == 4) assert (preds.shape[1] == 1 or preds.shape[1] == 3) patch_h = preds.shape[2] patch_w = preds.shape[3] N_patches_h = (img_h - patch_h) // stride_h + 1 N_patches_w = (img_w - patch_w) // stride_w + 1 N_patches_img = N_patches_h * N_patches_w assert (preds.shape[0] % N_patches_img == 0) N_full_imgs = preds.shape[0] // N_patches_img full_prob = np.zeros((N_full_imgs, preds.shape[1], img_h, img_w)) full_sum = np.zeros((N_full_imgs, preds.shape[1], img_h, img_w)) k = 0 for i in range(N_full_imgs): for h in range((img_h - patch_h) // stride_h + 1): for w in range((img_w - patch_w) // stride_w + 1): full_prob[i, :, h * stride_h:(h * stride_h) + patch_h, w * stride_w:(w * stride_w) + patch_w] += preds[ k] full_sum[i, :, h * stride_h:(h * stride_h) + patch_h, w * stride_w:(w * stride_w) + patch_w] += 1 k += 1 assert (k == preds.shape[0]) assert (np.min(full_sum) >= 1.0) final_avg = full_prob / full_sum return final_avg <file_sep>import os import pickle import torch from torch.utils.data import Dataset from torchvision.transforms import Compose, RandomHorizontalFlip, RandomVerticalFlip from utils.helpers import Fix_RandomRotation class vessel_dataset(Dataset): def __init__(self, path, mode, is_val=False, split=None): self.mode = mode self.is_val = is_val self.data_path = os.path.join(path, f"{mode}_pro") self.data_file = os.listdir(self.data_path) self.img_file = self._select_img(self.data_file) if split is not None and mode == "training": assert split > 0 and split < 1 if not is_val: self.img_file = self.img_file[:int(split*len(self.img_file))] else: self.img_file = self.img_file[int(split*len(self.img_file)):] self.transforms = Compose([ RandomHorizontalFlip(p=0.5), RandomVerticalFlip(p=0.5), Fix_RandomRotation(), ]) def __getitem__(self, idx): img_file = self.img_file[idx] with open(file=os.path.join(self.data_path, img_file), mode='rb') as file: img = torch.from_numpy(pickle.load(file)).float() gt_file = "gt" + img_file[3:] with open(file=os.path.join(self.data_path, gt_file), mode='rb') as file: gt = torch.from_numpy(pickle.load(file)).float() if self.mode == "training" and not self.is_val: seed = torch.seed() torch.manual_seed(seed) img = self.transforms(img) torch.manual_seed(seed) gt = self.transforms(gt) return img, gt def _select_img(self, file_list): img_list = [] for file in file_list: if file[:3] == "img": img_list.append(file) return img_list def __len__(self): return len(self.img_file) <file_sep>import os import time from datetime import datetime import cv2 import torch import numpy as np import torch.backends.cudnn as cudnn import torch.nn as nn import torchvision.transforms.functional as TF from loguru import logger from torch.utils import tensorboard from tqdm import tqdm from utils.helpers import dir_exists, get_instance, remove_files, double_threshold_iteration from utils.metrics import AverageMeter, get_metrics, get_metrics, count_connect_component import ttach as tta class Trainer: def __init__(self, model, CFG=None, loss=None, train_loader=None, val_loader=None): self.CFG = CFG if self.CFG.amp is True: self.scaler = torch.cuda.amp.GradScaler(enabled=True) self.loss = loss self.model = nn.DataParallel(model.cuda()) self.train_loader = train_loader self.val_loader = val_loader self.optimizer = get_instance( torch.optim, "optimizer", CFG, self.model.parameters()) self.lr_scheduler = get_instance( torch.optim.lr_scheduler, "lr_scheduler", CFG, self.optimizer) start_time = datetime.now().strftime('%y%m%d%H%M%S') self.checkpoint_dir = os.path.join( CFG.save_dir, self.CFG['model']['type'], start_time) self.writer = tensorboard.SummaryWriter(self.checkpoint_dir) dir_exists(self.checkpoint_dir) cudnn.benchmark = True def train(self): for epoch in range(1, self.CFG.epochs + 1): self._train_epoch(epoch) if self.val_loader is not None and epoch % self.CFG.val_per_epochs == 0: results = self._valid_epoch(epoch) logger.info(f'## Info for epoch {epoch} ## ') for k, v in results.items(): logger.info(f'{str(k):15s}: {v}') if epoch % self.CFG.save_period == 0: self._save_checkpoint(epoch) def _train_epoch(self, epoch): self.model.train() wrt_mode = 'train' self._reset_metrics() tbar = tqdm(self.train_loader, ncols=160) tic = time.time() for img, gt in tbar: self.data_time.update(time.time() - tic) img = img.cuda(non_blocking=True) gt = gt.cuda(non_blocking=True) self.optimizer.zero_grad() if self.CFG.amp is True: with torch.cuda.amp.autocast(enabled=True): pre = self.model(img) loss = self.loss(pre, gt) self.scaler.scale(loss).backward() self.scaler.step(self.optimizer) self.scaler.update() else: pre = self.model(img) loss = self.loss(pre, gt) loss.backward() self.optimizer.step() self.total_loss.update(loss.item()) self.batch_time.update(time.time() - tic) self._metrics_update( *get_metrics(pre, gt, threshold=self.CFG.threshold).values()) tbar.set_description( 'TRAIN ({}) | Loss: {:.4f} | AUC {:.4f} F1 {:.4f} Acc {:.4f} Sen {:.4f} Spe {:.4f} Pre {:.4f} IOU {:.4f} |B {:.2f} D {:.2f} |'.format( epoch, self.total_loss.average, *self._metrics_ave().values(), self.batch_time.average, self.data_time.average)) tic = time.time() self.writer.add_scalar( f'{wrt_mode}/loss', self.total_loss.average, epoch) for k, v in list(self._metrics_ave().items())[:-1]: self.writer.add_scalar(f'{wrt_mode}/{k}', v, epoch) for i, opt_group in enumerate(self.optimizer.param_groups): self.writer.add_scalar( f'{wrt_mode}/Learning_rate_{i}', opt_group['lr'], epoch) self.lr_scheduler.step() def _valid_epoch(self, epoch): logger.info('\n###### EVALUATION ######') self.model.eval() wrt_mode = 'val' self._reset_metrics() tbar = tqdm(self.val_loader, ncols=160) with torch.no_grad(): for img, gt in tbar: img = img.cuda(non_blocking=True) gt = gt.cuda(non_blocking=True) if self.CFG.amp is True: with torch.cuda.amp.autocast(enabled=True): predict = self.model(img) loss = self.loss(predict, gt) else: predict = self.model(img) loss = self.loss(predict, gt) self.total_loss.update(loss.item()) self._metrics_update( *get_metrics(predict, gt, threshold=self.CFG.threshold).values()) tbar.set_description( 'EVAL ({}) | Loss: {:.4f} | AUC {:.4f} F1 {:.4f} Acc {:.4f} Sen {:.4f} Spe {:.4f} Pre {:.4f} IOU {:.4f} |'.format( epoch, self.total_loss.average, *self._metrics_ave().values())) self.writer.add_scalar( f'{wrt_mode}/loss', self.total_loss.average, epoch) self.writer.add_scalar( f'{wrt_mode}/loss', self.total_loss.average, epoch) for k, v in list(self._metrics_ave().items())[:-1]: self.writer.add_scalar(f'{wrt_mode}/{k}', v, epoch) log = { 'val_loss': self.total_loss.average, **self._metrics_ave() } return log def _save_checkpoint(self, epoch): state = { 'arch': type(self.model).__name__, 'epoch': epoch, 'state_dict': self.model.state_dict(), 'optimizer': self.optimizer.state_dict(), 'config': self.CFG } filename = os.path.join(self.checkpoint_dir, f'checkpoint-epoch{epoch}.pth') logger.info(f'Saving a checkpoint: {filename} ...') torch.save(state, filename) return filename def _reset_metrics(self): self.batch_time = AverageMeter() self.data_time = AverageMeter() self.total_loss = AverageMeter() self.auc = AverageMeter() self.f1 = AverageMeter() self.acc = AverageMeter() self.sen = AverageMeter() self.spe = AverageMeter() self.pre = AverageMeter() self.iou = AverageMeter() self.CCC = AverageMeter() def _metrics_update(self, auc, f1, acc, sen, spe, pre, iou): self.auc.update(auc) self.f1.update(f1) self.acc.update(acc) self.sen.update(sen) self.spe.update(spe) self.pre.update(pre) self.iou.update(iou) def _metrics_ave(self): return { "AUC": self.auc.average, "F1": self.f1.average, "Acc": self.acc.average, "Sen": self.sen.average, "Spe": self.spe.average, "pre": self.pre.average, "IOU": self.iou.average } <file_sep>[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/full-resolution-network-and-dual-threshold/retinal-vessel-segmentation-on-drive)](https://paperswithcode.com/sota/retinal-vessel-segmentation-on-drive?p=full-resolution-network-and-dual-threshold)[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/full-resolution-network-and-dual-threshold/retinal-vessel-segmentation-on-chase_db1)](https://paperswithcode.com/sota/retinal-vessel-segmentation-on-chase_db1?p=full-resolution-network-and-dual-threshold) # FR-UNet This repository is the official PyTorch code for the paper ['Full-Resolution Network and Dual-Threshold Iteration for Retinal Vessel and Coronary Angiograph Segmentation'](https://ieeexplore.ieee.org/abstract/document/9815506). <div align="center"> <img src="figs/FR-UNet.png" width="100%"> </div> ## Prerequisites Download our repo: ``` git clone https://github.com/lseventeen/RF-UNet.git cd RF-UNet ``` Install packages from requirements.txt ``` pip install -r requirements.txt ``` ## Datasets processing Choose a path to create a folder with the dataset name and download datasets [DRIVE](https://www.dropbox.com/sh/z4hbbzqai0ilqht/AAARqnQhjq3wQcSVFNR__6xNa?dl=0),[CHASEDB1](https://blogs.kingston.ac.uk/retinal/chasedb1/),[STARE](https://cecas.clemson.edu/~ahoover/stare/probing/index.html),[CHUAC](https://figshare.com/s/4d24cf3d14bc901a94bf), and [DCA1](http://personal.cimat.mx:8181/~ivan.cruz/DB_Angiograms.html). Type this in terminal to run the data_process.py file ``` python data_process.py -dp DATASET_PATH -dn DATASET_NAME ``` ## Training Type this in terminal to run the train.py file ``` python train.py -dp DATASET_PATH ``` ## Test Type this in terminal to run the test.py file ``` python test.py -dp DATASET_PATH -wp WEIGHT_FILE_PATH ``` We have prepared the pre-trained models for both datasets in the folder 'pretrained_weights'. To replicate the results in the paper, directly run the following commands ``` python test.py -dp DATASET_PATH -wp pretrained_weights/DATASET_NAME ``` ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details <file_sep>import argparse import torch from bunch import Bunch from ruamel.yaml import safe_load from torch.utils.data import DataLoader import models from dataset import vessel_dataset from tester import Tester from utils import losses from utils.helpers import get_instance def main(data_path, weight_path, CFG, show): checkpoint = torch.load(weight_path) CFG_ck = checkpoint['config'] test_dataset = vessel_dataset(data_path, mode="test") test_loader = DataLoader(test_dataset, 1, shuffle=False, num_workers=16, pin_memory=True) model = get_instance(models, 'model', CFG) loss = get_instance(losses, 'loss', CFG_ck) test = Tester(model, loss, CFG, checkpoint, test_loader, data_path, show) test.test() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-dp", "--dataset_path", default="/home/lwt/data_pro/vessel/DRIVE", type=str, help="the path of dataset") parser.add_argument("-wp", "--wetght_path", default="pretrained_weights/DRIVE/checkpoint-epoch40.pth", type=str, help='the path of wetght.pt') parser.add_argument("--show", help="save predict image", required=False, default=False, action="store_true") args = parser.parse_args() with open("config.yaml", encoding="utf-8") as file: CFG = Bunch(safe_load(file)) main(args.dataset_path, args.wetght_path, CFG, args.show) <file_sep>import os import argparse import pickle import cv2 import numpy as np import torch.nn as nn import torch import torch.nn.functional as F from PIL import Image from ruamel.yaml import safe_load from torchvision.transforms import Grayscale, Normalize, ToTensor from utils.helpers import dir_exists, remove_files def data_process(data_path, name, patch_size, stride, mode): save_path = os.path.join(data_path, f"{mode}_pro") dir_exists(save_path) remove_files(save_path) if name == "DRIVE": img_path = os.path.join(data_path, mode, "images") gt_path = os.path.join(data_path, mode, "1st_manual") file_list = list(sorted(os.listdir(img_path))) elif name == "CHASEDB1": file_list = list(sorted(os.listdir(data_path))) elif name == "STARE": img_path = os.path.join(data_path, "stare-images") gt_path = os.path.join(data_path, "labels-ah") file_list = list(sorted(os.listdir(img_path))) elif name == "DCA1": data_path = os.path.join(data_path, "Database_134_Angiograms") file_list = list(sorted(os.listdir(data_path))) elif name == "CHUAC": img_path = os.path.join(data_path, "Original") gt_path = os.path.join(data_path, "Photoshop") file_list = list(sorted(os.listdir(img_path))) img_list = [] gt_list = [] for i, file in enumerate(file_list): if name == "DRIVE": img = Image.open(os.path.join(img_path, file)) gt = Image.open(os.path.join(gt_path, file[0:2] + "_manual1.gif")) img = Grayscale(1)(img) img_list.append(ToTensor()(img)) gt_list.append(ToTensor()(gt)) elif name == "CHASEDB1": if len(file) == 13: if mode == "training" and int(file[6:8]) <= 10: img = Image.open(os.path.join(data_path, file)) gt = Image.open(os.path.join( data_path, file[0:9] + '_1stHO.png')) img = Grayscale(1)(img) img_list.append(ToTensor()(img)) gt_list.append(ToTensor()(gt)) elif mode == "test" and int(file[6:8]) > 10: img = Image.open(os.path.join(data_path, file)) gt = Image.open(os.path.join( data_path, file[0:9] + '_1stHO.png')) img = Grayscale(1)(img) img_list.append(ToTensor()(img)) gt_list.append(ToTensor()(gt)) elif name == "DCA1": if len(file) <= 7: if mode == "training" and int(file[:-4]) <= 100: img = cv2.imread(os.path.join(data_path, file), 0) gt = cv2.imread(os.path.join( data_path, file[:-4] + '_gt.pgm'), 0) gt = np.where(gt >= 100, 255, 0).astype(np.uint8) img_list.append(ToTensor()(img)) gt_list.append(ToTensor()(gt)) elif mode == "test" and int(file[:-4]) > 100: img = cv2.imread(os.path.join(data_path, file), 0) gt = cv2.imread(os.path.join( data_path, file[:-4] + '_gt.pgm'), 0) gt = np.where(gt >= 100, 255, 0).astype(np.uint8) img_list.append(ToTensor()(img)) gt_list.append(ToTensor()(gt)) elif name == "CHUAC": if mode == "training" and int(file[:-4]) <= 20: img = cv2.imread(os.path.join(img_path, file), 0) if int(file[:-4]) <= 17 and int(file[:-4]) >= 11: tail = "PNG" else: tail = "png" gt = cv2.imread(os.path.join( gt_path, "angio"+file[:-4] + "ok."+tail), 0) gt = np.where(gt >= 100, 255, 0).astype(np.uint8) img = cv2.resize( img, (512, 512), interpolation=cv2.INTER_LINEAR) cv2.imwrite(f"save_picture/{i}img.png", img) cv2.imwrite(f"save_picture/{i}gt.png", gt) img_list.append(ToTensor()(img)) gt_list.append(ToTensor()(gt)) elif mode == "test" and int(file[:-4]) > 20: img = cv2.imread(os.path.join(img_path, file), 0) gt = cv2.imread(os.path.join( gt_path, "angio"+file[:-4] + "ok.png"), 0) gt = np.where(gt >= 100, 255, 0).astype(np.uint8) img = cv2.resize( img, (512, 512), interpolation=cv2.INTER_LINEAR) cv2.imwrite(f"save_picture/{i}img.png", img) cv2.imwrite(f"save_picture/{i}gt.png", gt) img_list.append(ToTensor()(img)) gt_list.append(ToTensor()(gt)) elif name == "STARE": if not file.endswith("gz"): img = Image.open(os.path.join(img_path, file)) gt = Image.open(os.path.join(gt_path, file[0:6] + '.ah.ppm')) cv2.imwrite(f"save_picture/{i}img.png", np.array(img)) cv2.imwrite(f"save_picture/{i}gt.png", np.array(gt)) img = Grayscale(1)(img) img_list.append(ToTensor()(img)) gt_list.append(ToTensor()(gt)) img_list = normalization(img_list) if mode == "training": img_patch = get_patch(img_list, patch_size, stride) gt_patch = get_patch(gt_list, patch_size, stride) save_patch(img_patch, save_path, "img_patch", name) save_patch(gt_patch, save_path, "gt_patch", name) elif mode == "test": if name != "CHUAC": img_list = get_square(img_list, name) gt_list = get_square(gt_list, name) save_each_image(img_list, save_path, "img", name) save_each_image(gt_list, save_path, "gt", name) def get_square(img_list, name): img_s = [] if name == "DRIVE": shape = 592 elif name == "CHASEDB1": shape = 1008 elif name == "DCA1": shape = 320 _, h, w = img_list[0].shape pad = nn.ConstantPad2d((0, shape-w, 0, shape-h), 0) for i in range(len(img_list)): img = pad(img_list[i]) img_s.append(img) return img_s def get_patch(imgs_list, patch_size, stride): image_list = [] _, h, w = imgs_list[0].shape pad_h = stride - (h - patch_size) % stride pad_w = stride - (w - patch_size) % stride for sub1 in imgs_list: image = F.pad(sub1, (0, pad_w, 0, pad_h), "constant", 0) image = image.unfold(1, patch_size, stride).unfold( 2, patch_size, stride).permute(1, 2, 0, 3, 4) image = image.contiguous().view( image.shape[0] * image.shape[1], image.shape[2], patch_size, patch_size) for sub2 in image: image_list.append(sub2) return image_list def save_patch(imgs_list, path, type, name): for i, sub in enumerate(imgs_list): with open(file=os.path.join(path, f'{type}_{i}.pkl'), mode='wb') as file: pickle.dump(np.array(sub), file) print(f'save {name} {type} : {type}_{i}.pkl') def save_each_image(imgs_list, path, type, name): for i, sub in enumerate(imgs_list): with open(file=os.path.join(path, f'{type}_{i}.pkl'), mode='wb') as file: pickle.dump(np.array(sub), file) print(f'save {name} {type} : {type}_{i}.pkl') def normalization(imgs_list): imgs = torch.cat(imgs_list, dim=0) mean = torch.mean(imgs) std = torch.std(imgs) normal_list = [] for i in imgs_list: n = Normalize([mean], [std])(i) n = (n - torch.min(n)) / (torch.max(n) - torch.min(n)) normal_list.append(n) return normal_list if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-dp', '--dataset_path', default="datasets/DRIVE", type=str, help='the path of dataset',required=True) parser.add_argument('-dn', '--dataset_name', default="DRIVE", type=str, help='the name of dataset',choices=['DRIVE','CHASEDB1','STARE','CHUAC','DCA1'],required=True) parser.add_argument('-ps', '--patch_size', default=48, help='the size of patch for image partition') parser.add_argument('-s', '--stride', default=6, help='the stride of image partition') args = parser.parse_args() with open('config.yaml', encoding='utf-8') as file: CFG = safe_load(file) # 为列表类型 data_process(args.dataset_path, args.dataset_name, args.patch_size, args.stride, "training") data_process(args.dataset_path, args.dataset_name, args.patch_size, args.stride, "test") <file_sep>from .fr_unet import FR_UNet <file_sep>import argparse from bunch import Bunch from loguru import logger from ruamel.yaml import safe_load from torch.utils.data import DataLoader import models from dataset import vessel_dataset from trainer import Trainer from utils import losses from utils.helpers import get_instance, seed_torch def main(CFG, data_path, batch_size, with_val=False): seed_torch() if with_val: train_dataset = vessel_dataset(data_path, mode="training", split=0.9) val_dataset = vessel_dataset( data_path, mode="training", split=0.9, is_val=True) val_loader = DataLoader( val_dataset, batch_size, shuffle=False, num_workers=16, pin_memory=True, drop_last=False) else: train_dataset = vessel_dataset(data_path, mode="training") train_loader = DataLoader( train_dataset, batch_size, shuffle=True, num_workers=16, pin_memory=True, drop_last=True) logger.info('The patch number of train is %d' % len(train_dataset)) model = get_instance(models, 'model', CFG) logger.info(f'\n{model}\n') loss = get_instance(losses, 'loss', CFG) trainer = Trainer( model=model, loss=loss, CFG=CFG, train_loader=train_loader, val_loader=val_loader if with_val else None ) trainer.train() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-dp', '--dataset_path', default="/home/lwt/data_pro/vessel/DRIVE", type=str, help='the path of dataset') parser.add_argument('-bs', '--batch_size', default=512, help='batch_size for trianing and validation') parser.add_argument("--val", help="split training data for validation", required=False, default=False, action="store_true") args = parser.parse_args() with open('config.yaml', encoding='utf-8') as file: CFG = Bunch(safe_load(file)) main(CFG, args.dataset_path, args.batch_size, args.val) <file_sep>albumentations==0.5.2 bunch==1.0.1 loguru==0.5.3 matplotlib==3.3.2 numpy==1.20.3 opencv_python==4.4.0.46 Pillow==9.0.1 ruamel.base==1.0.0 scikit_learn==1.0.2 segmentation==0.2.2 timm==0.3.2 torch==1.7.0 torchstat==0.0.7 torchvision==0.8.1 tqdm==4.61.1 ttach==0.0.3 yacs==0.1.8
efaf03ee8cc93f27e544c9255d376a40b775cdd4
[ "Markdown", "Python", "Text" ]
13
Python
lseventeen/FRNet-vessel-segmentation
180d485a89af448050f520164fa74fd2a13a8dfa
887debadaefda394f5da960d603f671f103db614
refs/heads/main
<file_sep>import React from 'react' import { Link, Route, Switch } from 'react-router-dom'; import LoginForm from './LoginForm'; import RegisterForm from './RegisterForm'; export default function LoginRegister() { return ( <div className="containerLogin"> <div className="loginBox"> <div className="routerLoginRegister"> <div><Link to="/login" className="link">LOGIN</Link></div> <div><Link to="/register" className="link">REGISTER</Link></div> </div> <div> <div > <Switch> <Route path="/login" component={LoginForm} /> <Route path="/register" component={RegisterForm} /> </Switch> </div> </div> </div> </div> ) } <file_sep>import React, { useEffect, useState } from "react"; import { AiOutlineFileImage, AiOutlineUser } from "react-icons/ai"; import { MdDescription } from "react-icons/md"; import { BiTimeFive } from "react-icons/bi"; import axios from "axios"; import { getCurrentUser } from "./service"; import url from "../config/url"; export default function CreateArtical(props) { const [articalName, setArticalName] = useState(""); const [auther, setAuther] = useState(""); const [autherId, setAutherId] = useState(""); const [timeToRead, setTimeToRead] = useState(""); const [desc, setDesc] = useState(""); const [articalImage, setArticalImage] = useState(""); const [message,setMessage] = useState(""); const currentUser = getCurrentUser(); useEffect(()=>{ const articalId =props.match.params.id; if(articalId === "new") return ; try{ axios.get(`${url}api/articals/${props.match.params.id}`) .then(result=>{ setAuther(result.data.auther); setAutherId(currentUser._id) setArticalName(result.data.name); setDesc(result.data.desc); setTimeToRead(result.data.timeToRead); setArticalImage(result.data.articalImage); })} catch(er){ console.log("something went wrong") } },[]) function handleSubmit(e) { e.preventDefault(); const formData = new FormData(); formData.append("name", articalName); formData.append("desc", desc); formData.append("auther", auther); formData.append("timeToRead", timeToRead); formData.append("articalImage", articalImage); formData.append("autherId", currentUser._id); axios.put(`${url}api/articals`,formData) .then(result=>{ setMessage(`${result.data.name} artical added successfully`); setTimeout(()=>setMessage(""),5000); }) .catch(ex=>{ console.log(ex) setMessage("somthig want wrong"); setTimeout(()=>setMessage(""),5000) } ) setAuther(""); setArticalName(""); setDesc(""); setTimeToRead(""); setArticalImage(""); } return ( <div className="containerLogin"> <form onSubmit={handleSubmit}> <h3 style={{ marginLeft: "10%" }}>Add New Artical</h3> <br /> {message && <h3>{message}</h3>} <div className="formGroup"> <div className="inputfield"> <AiOutlineUser /> <input type="text" name="articalName" placeholder="ArticalName" className="input" value={articalName} onChange={(e) => setArticalName(e.target.value)} /> </div> <div className="inputfield"> <AiOutlineUser /> <input type="text" name="Auther" placeholder="Auther" className="input" value={auther} onChange={(e) => setAuther(e.target.value)} /> </div> <div className="inputfield"> <BiTimeFive /> <input type="text" name="timeToRead" placeholder="TimeToRead" className="input" value={timeToRead} onChange={(e) => setTimeToRead(e.target.value)} /> </div> <div className="inputfield"> <MdDescription /> <textarea name="description" placeholder="Description" className="input" rows="5" value={desc} onChange={(e) => setDesc(e.target.value)} /> </div> <div className="inputfield"> <AiOutlineFileImage /> <input type="file" name="articalImage" className="input" onChange={e=>setArticalImage(e.target.files[0])}/> </div> <div className="inputfield"> <input type="submit" value="add" /> </div> </div> </form> </div> ); } <file_sep>import axios from "axios"; import React, { useState } from "react"; import InputText from "./InputText"; import { AiOutlineUser, AiOutlineMail, AiOutlinePhone } from "react-icons/ai"; import { RiLockPasswordFill } from "react-icons/ri"; import url from "../config/url"; export default function RegisterForm(props) { const [username, setUsername] = useState(""); const [fathername, setFathername] = useState(""); const [surname, setSurname] = useState(""); const [email, setEmail] = useState(""); const [number, setNumber] = useState(""); const [password, setPassword] = useState(""); const [message, setMessage] = useState(""); function handleSubmit(e) { e.preventDefault(); const data = { name: username, fathername, surname, email, number, password, }; axios .post(`${url}api/registration`, data) .then((result) => { localStorage.setItem("token", result.data.token); setMessage(`${result.data.name} register successfully`); setTimeout(() => setMessage(""), 5000); window.location = "/"; }) .catch((ex) => { if (ex.response) { setMessage(ex.response.data); setTimeout(() => setMessage(""), 5000); } }); setUsername(""); setFathername(""); setSurname(""); setEmail(""); setNumber(""); setPassword(""); } const inputFields = [ { type: "text", name: "username", placeholder: "Username", icon: <AiOutlineUser />, value: username, onChange: setUsername, }, { type: "text", name: "fathername", placeholder: "Fathername", icon: <AiOutlineUser />, value: fathername, onChange: setFathername, }, { type: "text", name: "surname", placeholder: "Surname", icon: <AiOutlineUser />, value: surname, onChange: setSurname, }, { type: "email", name: "email", placeholder: "Email", icon: <AiOutlineMail />, value: email, onChange: setEmail, }, { type: "number", name: "number", placeholder: "Number", icon: <AiOutlinePhone />, value: number, onChange: setNumber, }, { type: "password", name: "password", placeholder: "<PASSWORD>", icon: <RiLockPasswordFill />, value: password, onChange: setPassword, }, ]; return ( <form onSubmit={handleSubmit}> {message && <h3>{message}</h3>} <div className="formGroup"> {inputFields.map((field) => ( <InputText field={field} /> ))} <div className="inputfield"> <input type="submit" value="Register" /> </div> </div> </form> ); } <file_sep>import jwtDecode from "jwt-decode"; export function getCurrentUser(){ try{ const jwt = localStorage.getItem('token'); return jwtDecode(jwt) } catch(ex){ return null } }<file_sep> import React from 'react' import { Link } from 'react-router-dom' export default function Navbar({currentUser}) { return ( <div> <nav className="navbar"> <div className="left_menu"> <div><Link to="/articals" className="link" ><h3>Articals</h3></Link></div> </div> <div className="right_menu"> {!currentUser ? <div><Link to="/login" className="link"><button className="button">Login</button></Link></div> : <div>Welcome ,{currentUser}</div>} {currentUser && <div><Link to="/newartical/new" className="link"><button className="button">Add Artical</button></Link></div> } {currentUser && <div><Link to="/myartical" className="link"><button className="button">My Articals</button></Link></div>} {!currentUser && <div><Link to="/register" className="link"><button className="button">Register</button></Link></div>} {currentUser && <div><Link to="/" className="link"><button className="button" onClick={handleLogout}>Logout</button></Link></div>} </div> </nav> </div> ) } function handleLogout(){ localStorage.removeItem("token"); window.location="/" }<file_sep>import axios from "axios"; import React, { useEffect, useState } from "react"; import url from "../config/url"; import Artical from "./Artical"; import ListArtical from "./ListArtical"; // import listOfArtical from "./articaljson"; export default function LandingScreen() { const [listOfArtical, setlistOfArtical] = useState([]) useEffect(()=>{ axios.get(`${url}api/articals`) .then(result=> setlistOfArtical(result.data)) .catch(ex=>console.log(ex)) },[]) return ( <div className="landingScreen"> <div className="landingScreen_left"> {listOfArtical.map((artical) => ( <Artical key={artical._id} artical={artical} /> ))} </div> <div className="landingScreen_right"> TOP ARTICALS {listOfArtical .map((artical) => <ListArtical key={artical._id} artical={artical} />) .slice(0, 5)} </div> </div> ); } <file_sep>import React from 'react' export default function InputText(props) { const field =props.field return ( <div className="inputfield"> {field.icon} <input type={field.type} name={field.name} placeholder={field.placeholder} className="input" value={field.value} onChange={e=>field.onChange(e.target.value)} /> </div> ) } <file_sep>export default "https://articalblog.herokuapp.com/"<file_sep>import axios from "axios"; import React, { useState } from "react"; import { AiOutlineUser } from "react-icons/ai"; import { RiLockPasswordFill } from "react-icons/ri"; import url from "../config/url"; import InputText from "./InputText"; export default function LoginForm(props) { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [message, setMessage] = useState(""); function handleSubmit(e) { e.preventDefault(); const data = { email: username, password, }; axios .post(`${url}api/login`, data) .then((result) => { console.log(props); localStorage.setItem("token", result.data); setMessage(`login successfull`); setTimeout(() => setMessage(""), 5000); window.location = "/"; }) .catch((ex) => { if (ex.response) { setMessage(ex.response.data); setTimeout(() => setMessage(""), 5000); } }); } const inputFields = [ { type: "text", name: "username", placeholder: "Email", icon: <AiOutlineUser />, value: username, onChange: setUsername, }, { type: "password", name: "password", placeholder: "<PASSWORD>", icon: <RiLockPasswordFill />, value: password, onChange: setPassword, }, ] return ( <form onSubmit={handleSubmit}> {message && <h3>{message}</h3>} <div className="formGroup"> { inputFields.map(field=>( <InputText field={field} /> )) } <div className="inputfield"> <input type="submit" value="login" /> </div> </div> </form> ); } <file_sep>module.exports = { primary:"red" }<file_sep>import { Redirect, Route, Switch } from "react-router"; import "./App.css"; import LoginRegister from "./component/LoginRegister"; import Navbar from "./component/Navbar"; import ArticalPage from "./component/ArticalPage"; import CreateArtical from "./component/CreateArtical"; import Myarticals from "./component/Myarticals"; import LandingScreen from "./component/LandingScreen"; import jwtDecode from 'jwt-decode' import React, { useEffect, useState } from 'react' function App() { const [currentUser, setCurrentUser] = useState(null) useEffect(()=>{ try{ const jwt = localStorage.getItem('token'); const currentUser = jwtDecode(jwt).name setCurrentUser(currentUser); }catch(ex){ setCurrentUser(null) } },[currentUser]) return ( <div className="App"> <Navbar currentUser={currentUser}/> <div> <Switch> <Route path="/login" component={LoginRegister} /> <Route path="/register" component={LoginRegister} /> <Route path="/articals" exact component={LandingScreen} /> <Route path="/articals/:id" component={ArticalPage} /> <Route path="/newartical/:id" component={CreateArtical} /> <Route path="/newartical" component={CreateArtical} /> <Route path="/myartical" component={Myarticals} /> <Redirect to="/articals" /> </Switch> </div> </div> ); } export default App;
2733441fd54bf16ab039d9df893ce1172db38ac0
[ "JavaScript" ]
11
JavaScript
nirav7707/internship_task_1_frontend
7883a1266fc1f7337eb5e44d05b24b27c0c691fc
313e147f3f5d440d4ff56745164f921c34167df8
refs/heads/master
<file_sep># Rales Engine Building [Sales Engine](https://github.com/jbrr/sales_engine) in Rails and ActiveRecord, using as little pure Ruby as possible, and exposing API endpoints, though there are no actual views. Data is taken from [Sales Engine](https://github.com/turingschool/sales_engine/tree/master/data). [Original Assignment](https://github.com/turingschool/lesson_plans/blob/master/ruby_03-professional_rails_applications/rails_engine.md) <file_sep>require "test_helper" class Api::V1::CustomersControllerTest < ActionController::TestCase attr_reader :customer, :invoice, :transaction def setup @customer = Customer.create(id: 1, first_name: "Jeff", last_name: "Jeff") @invoice = Invoice.create(id: 5, customer_id: 1, merchant_id: 4) Merchant.create(id: 4, name: "Stuff") @transaction = Transaction.create(id: 3, invoice_id: 5, result: "success") end test "#index" do get :index, format: :json assert_response :success end test "#index returns the right number of objects" do number_of_customers = Customer.count get :index, format: :json json_response = JSON.parse(response.body) assert_equal number_of_customers, json_response.count end test "#show" do get :show, format: :json, id: customer.id assert_response :success assert_equal customer.first_name, json_response["first_name"] end test "#find" do get :find, format: :json, first_name: customer.first_name assert_response :success assert_equal customer.first_name, json_response["first_name"] end test "#find_all" do get :find_all, format: :json, first_name: customer.first_name assert_response :success assert_equal Array, json_response.class assert_equal customer.first_name, json_response[0]["first_name"] end test "#invoices" do get :invoices, format: :json, id: customer.id assert_response :success assert_equal invoice.id, json_response[0]["id"] end test "#transactions" do get :transactions, format: :json, id: customer.id assert_response :success assert_equal transaction.id, json_response[0]["id"] end test "#favorite_merchant" do get :favorite_merchant, format: :json, id: customer.id assert_response :success assert_equal "Stuff", json_response["name"] end end <file_sep>class Merchant < ActiveRecord::Base has_many :invoices has_many :items has_many :invoice_items, through: :invoices def revenue(params) if params[:date] invoices.where(created_at: params[:date]).successful_transactions. joins(:invoice_items).sum("unit_price * quantity") else successful_invoices.joins(:invoice_items).sum("unit_price * quantity") end end def favorite_customer customer_id = successful_invoices.group_by(&:customer_id). max_by { |_k, v| v.count }.flatten.first Customer.find(customer_id) end def pending_customers invoices.pending_transactions.map(&:customer).uniq end def successful_invoices invoices.successful_transactions end end <file_sep>require "test_helper" class Api::V1::InvoiceItemsControllerTest < ActionController::TestCase attr_reader :invoice_item, :invoice, :item def setup @item = Item.create(id: 15) @invoice = Invoice.create(id: 4) @invoice_item = InvoiceItem.create(id: 3, invoice_id: invoice.id, item_id: item.id, quantity: 5, unit_price: 5443) end test "#index" do get :index, format: :json assert_response :success end test "#show" do get :show, format: :json, id: invoice_item.id assert_response :success assert_equal invoice_item.quantity, json_response["quantity"] end test "#find" do get :find, format: :json, quantity: invoice_item.quantity assert_response :success assert_equal invoice_item.quantity, json_response["quantity"] end test "#find by unit_price" do get :find, format: :json, unit_price: "54.43" assert_response :success assert_equal invoice_item.id, json_response["id"] end test "#find_all" do get :find_all, format: :json, quantity: invoice_item.quantity assert_response :success assert_equal Array, json_response.class assert_equal invoice_item.quantity, json_response[0]["quantity"] end test "#invoice" do get :invoice, format: :json, id: invoice_item.id assert_response :success assert_equal invoice.id, json_response["id"] end test "#item" do get :item, format: :json, id: invoice_item.id assert_response :success assert_equal item.id, json_response["id"] end end <file_sep>class InvoiceItem < ActiveRecord::Base belongs_to :invoice belongs_to :item def self.successful_transactions joins(:invoice).merge(Invoice.successful_transactions) end end <file_sep>require "test_helper" class Api::V1::InvoicesControllerTest < ActionController::TestCase attr_reader :invoice, :transaction, :invoice_item, :item, :customer, :merchant def setup @invoice = Invoice.create(id: 1, customer_id: 6, merchant_id: 7, status: "shipped") @transaction = Transaction.create(id: 5, invoice_id: 1) @invoice_item = InvoiceItem.create(id: 9, invoice_id: 1, item_id: 18) @item = Item.create(id: 18) @customer = Customer.create(id: 6) @merchant = Merchant.create(id: 7) end test "#index" do get :index, format: :json assert_response :success end test "#show" do get :show, format: :json, id: invoice.id assert_response :success end test "#find" do get :find, format: :json, customer_id: invoice.customer_id assert_response :success assert_equal invoice.customer_id, json_response["customer_id"] end test "#find_all" do get :find_all, format: :json, customer_id: invoice.customer_id assert_response :success assert_equal Array, json_response.class assert_equal invoice.customer_id, json_response[0]["customer_id"] end test "#transactions" do get :transactions, format: :json, id: invoice.id assert_response :success assert_equal transaction.id, json_response[0]["id"] end test "#invoice_items" do get :invoice_items, format: :json, id: invoice.id assert_response :success assert_equal invoice_item.id, json_response[0]["id"] end test "#items" do get :items, format: :json, id: invoice.id assert_response :success assert_equal item.id, json_response[0]["id"] end test "#customer" do get :customer, format: :json, id: invoice.id assert_response :success assert_equal customer.id, json_response["id"] end test "#merchant" do get :merchant, format: :json, id: invoice.id assert_response :success assert_equal merchant.id, json_response["id"] end end <file_sep>require "application_responder" class ApplicationController < ActionController::Base helper_method :format_unit_price self.responder = ApplicationResponder respond_to :html # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception def format_unit_price if params[:unit_price] params["unit_price"] = BigDecimal.new(params["unit_price"]) * 100 end end end <file_sep>require "test_helper" class Api::V1::MerchantsControllerTest < ActionController::TestCase attr_reader :merchant, :item, :invoice def setup @merchant = Merchant.create(id: 1, name: "Rocky") @item = Item.create(id: 5, merchant_id: 1) @invoice = Invoice.create(id: 4, merchant_id: 1, customer_id: 4, created_at: "Sun, 25 Mar 2012 09:54:09 UTC +00:00") Invoice.create(id: 7, merchant_id: 1, customer_id: 4, created_at: "Sun, 26 Mar 2012 09:55:09 UTC +00:00") Invoice.create(id: 8, merchant_id: 1, customer_id: 5) @transaction = Transaction.create(id: 8, invoice_id: 4, result: "success") Transaction.create(id: 9, invoice_id: 7, result: "success") Transaction.create(id: 10, invoice_id: 8, result: "failed") @invoice_item = InvoiceItem.create(id: 9, invoice_id: 4, quantity: 7, unit_price: 8738) InvoiceItem.create(id: 36, invoice_id: 7, quantity: 8, unit_price: 4732) Customer.create(id: 4, first_name: "Jeff", last_name: "Ruane") Customer.create(id: 5, first_name: "pizza", last_name: "party") end test "#index" do get :index, format: :json assert_response :success end test "#show" do get :show, format: :json, id: merchant.id assert_response :success end test "#find" do get :find, format: :json, name: merchant.name assert_response :success assert_equal merchant.id, json_response["id"] end test "#find_all" do get :find_all, format: :json, name: merchant.name assert_response :success assert_equal Array, json_response.class assert_equal merchant.id, json_response[0]["id"] end test "#items" do get :items, format: :json, id: merchant.id assert_response :success assert_equal item.id, json_response[0]["id"] end test "#invoices" do get :invoices, format: :json, id: merchant.id assert_response :success assert_equal invoice.id, json_response[0]["id"] end test "#revenue" do get :revenue, format: :json, id: merchant.id assert_response :success response = { "revenue" => "990.22" } assert_equal response, json_response end test "#revenue with date" do get :revenue, format: :json, id: merchant.id, date: "2012-03-26 09:55:09" assert_response :success response = { "revenue" => "378.56" } assert_equal response, json_response end test "#favorite_customer" do get :favorite_customer, format: :json, id: merchant.id assert_response :success assert_equal "Jeff", json_response["first_name"] end test "#customers_with_pending_invoices" do get :customers_with_pending_invoices, format: :json, id: merchant.id assert_response :success assert_equal "pizza", json_response[0]["first_name"] end end <file_sep>require "test_helper" class Api::V1::TransactionsControllerTest < ActionController::TestCase attr_reader :transaction, :invoice def setup @transaction = Transaction.create(id: 1, credit_card_number: "1234", invoice_id: 5) @invoice = Invoice.create(id: 5) end test "#index" do get :index, format: :json assert_response :success end test "#show" do get :show, format: :json, id: transaction.id assert_response :success end test "#find" do get :find, format: :json, credit_card_number: transaction.credit_card_number assert_response :success assert_equal transaction.id, json_response["id"] end test "#find_all" do get :find_all, format: :json, credit_card_number: transaction.credit_card_number assert_response :success assert_equal Array, json_response.class assert_equal transaction.id, json_response[0]["id"] end test "#invoice" do get :invoice, format: :json, id: transaction.id assert_response :success assert_equal invoice.id, json_response["id"] end end <file_sep>require "test_helper" class Api::V1::ItemsControllerTest < ActionController::TestCase attr_reader :item, :invoice_item, :merchant def setup @item = Item.create(id: 1, merchant_id: 5, name: "stuff", unit_price: 4372) @invoice_item = InvoiceItem.create(id: 4, item_id: 1, invoice_id: 4, quantity: 5) InvoiceItem.create(id: 5, item_id: 1, invoice_id: 5, quantity: 8) Invoice.create(id: 4, created_at: "Tue, 27 Mar 2012 14:54:09 UTC +00:00") Invoice.create(id: 5, created_at: "Tue, 27 Mar 2012 14:54:09 UTC +00:00") Transaction.create(id: 9, invoice_id: 4, result: "success") Transaction.create(id: 10, invoice_id: 5, result: "success") @merchant = Merchant.create(id: 5) end test "#index" do get :index, format: :json assert_response :success end test "#show" do get :show, format: :json, id: item.id assert_response :success end test "#find" do get :find, format: :json, name: item.name assert_response :success assert_equal item.id, json_response["id"] end test "#find with unit_price" do get :find, format: :json, unit_price: "43.72" assert_response :success assert_equal item.id, json_response["id"] end test "#find_all" do get :find_all, format: :json, name: item.name assert_response :success assert_equal Array, json_response.class assert_equal item.id, json_response[0]["id"] end test "#invoice_items" do get :invoice_items, format: :json, id: item.id assert_response :success assert_equal invoice_item.id, json_response[0]["id"] end test "#merchant" do get :merchant, format: :json, id: item.id assert_response :success assert_equal merchant.id, json_response["id"] end test "#best_day" do get :best_day, format: :json, id: item.id assert_response :success response = { "best_day" => "2012-03-27T14:54:09.000Z" } assert_equal response, json_response end end <file_sep>class Item < ActiveRecord::Base has_many :invoice_items has_many :invoices, through: :invoice_items belongs_to :merchant def best_day invoices.successful_transactions.group('"invoices"."created_at"'). order("sum_quantity DESC").sum("quantity").first[0] end end <file_sep>class Api::V1::MerchantsController < ApplicationController respond_to :json def index respond_with Merchant.all end def show respond_with Merchant.find(params[:id]) end def find respond_with Merchant.find_by(merchant_params) end def find_all respond_with Merchant.where(merchant_params) end def random respond_with Merchant.order("RANDOM()").first end def items respond_with Merchant.find_by(merchant_params).items end def invoices respond_with Merchant.find_by(merchant_params).invoices end def revenue merchant = Merchant.find(params[:id]).revenue(merchant_params) respond_with serialized_message(merchant) end def favorite_customer respond_with Merchant.find(params[:id]).favorite_customer end def customers_with_pending_invoices respond_with Merchant.find(params[:id]).pending_customers end private def merchant_params params.permit(:id, :name, :created_at, :updated_at, :date) end def serialized_message(merchant) MerchantSerializer.new(merchant).revenue end end <file_sep>class Customer < ActiveRecord::Base has_many :invoices has_many :transactions, through: :invoices def favorite_merchant merchant_id = invoices.successful_transactions.group_by(&:merchant_id). max_by { |_k, v| v.count }.flatten.first Merchant.find(merchant_id) end end <file_sep>require 'test_helper' class InvoiceItemTest < ActiveSupport::TestCase end
4b641830ea6061afc0ef8a6d34e7030cda73b442
[ "Markdown", "Ruby" ]
14
Markdown
jbrr/rales-engine
c3d96a51a075ce562771c38c2dba7cce41e454d5
ffedc2e7155d976a6ddf5a37390e52bcb64e64dc
HEAD
<file_sep>root useradd shota7180 passwd <PASSWORD> passwd <PASSWORD> cd .ssh mkdir .ssh cd .ssh cat id_rsa.pub >> authorized_keys cd ls ls cat >> ~/.ssh/authorized_keys logout passwd root vi /etc/ssh/sshd_config vim /etc/ssh/sshd_config vi /etc/ssh/sshd_config /etc/init.d/sshd restart visudo logout logout exit vi /etc/ssh/sshd_config /etc/init.d/sshd restart vi /etc/ssh/sshd_config /etc/init.d/sshd restart vi /etc/ssh/sshd_config /etc/init.d/sshd restart vi /etc/ssh/sshd_config /etc/init.d/sshd restart vi /etc/ssh/sshd_config /etc/init.d/sshd restart vi /etc/ssh/sshd_config /etc/init.d/sshd restart vi /etc/ssh/sshd_config /etc/init.d/sshd restart vi /etc/ssh/sshd_config /etc/init.d/sshd restart logout cd /usr/local/src wget http://asic-linux.com.mx/~izto/checkinstall/files/source/checkinstall-1.6.2.tar.gz tar zxvf checkinstall-1.6.2.tar.gz cd checkinstall-1.6.2 make make install /usr/local/sbin/checkinstall -R cd /usr/src/redhat/RPMS/i386 mkdir /usr/src/redhat/RPMS/i386 rpm -ivh checkinstall-1.6.2-1.i386.rpm /usr/local/sbin/checkinstall -R cd /usr/local/src cd checkinstall-1.6.2 make cd /usr/local/src wget http://asic-linux.com.mx/~izto/checkinstall/files/source/checkinstall-1.6.2.tar.gz tar zxvf checkinstall-1.6.2.tar.gz cd checkinstall-1.6.2 make make install sudo /usr/local/sbin/checkinstall -R mkdir /usr/src/redhat/RPMS/x86_64/ cd /usr/src/redhat/RPMS/x86_64/ rpm -ivh checkinstall-1.6.2-1.i386.rpm rpm -ivh checkinstall-1.6.2-1.x86_64.rpm exit <file_sep>class TopicsController < ApplicationController # GET /topics # GET /topics.json def index @topics = Topic.all respond_to do |format| format.html # index.html.erb format.json { render json: @topics } end end # GET /topics/1 # GET /topics/1.json def show @topic = Topic.find(params[:id]) if @topic.comment_list comments = @topic.comment_list.split(",") end @comments = [] comments.each do |id| comment = Comment.find(id) if comment @comments << comment end end @comment = Comment.new session[:topic_id] = @topic.id respond_to do |format| format.html # show.html.erb format.json { render json: @topic } end end # GET /topics/new # GET /topics/new.json def new @topic = Topic.new session[:project_id] = nil respond_to do |format| format.html # new.html.erb format.json { render json: @topic } end end # GET /topics/1/edit def edit @topic = Topic.find(params[:id]) end # POST /topics # POST /topics.json def create @topic = Topic.new(params[:topic]) if session[:project_id] project = Project.find(session[:project_id]) if project.topic_list == "" || project.topic_list == nil project.topic_list = @topic.id else project.topic_list = project.topic_list.to_s + ',' + @topic.id.to_s end project.save end respond_to do |format| if @topic.save if project format.html { redirect_to project, notice: "Topic and comment were successfully created."} format.json { render json: project, status: :created, location: project} else format.html { redirect_to @topic, notice: 'Topic was successfully created.' } format.json { render json: @topic, status: :created, location: @topic } end else format.html { render action: "new" } format.json { render json: @topic.errors, status: :unprocessable_entity } end end end # PUT /topics/1 # PUT /topics/1.json def update @topic = Topic.find(params[:id]) respond_to do |format| if @topic.update_attributes(params[:topic]) format.html { redirect_to @topic, notice: 'Topic was successfully updated.' } format.json { head :ok } else format.html { render action: "edit" } format.json { render json: @topic.errors, status: :unprocessable_entity } end end end # DELETE /topics/1 # DELETE /topics/1.json def destroy @topic = Topic.find(params[:id]) @topic.destroy project = Project.find(params[:project_id]) topic_list = "" topics = project.topic_list.split(",") topics.each do |id| if id.to_s != params[:id].to_s if topic_list == "" topic_list = id else topic_list = topic_list.to_s + ',' + id.to_s end end end project.topic_list = topic_list project.save respond_to do |format| format.html { redirect_to project} format.json { head :ok } end end end <file_sep>class User < NullModelBase self.abstract_class = true self.db_get_handle("user", "user"); # create user from facebook def self.create_with_omniauth(auth) #logger.debug("debug------------------- user model"); #logger.debug(auth["extra"]["raw_info"]["location"]) create!do |user| user.provider = auth["provider"] user.uid = auth["uid"] user.gender = auth["extra"]["raw_info"]["gender"] user.provider_name = auth["info"]["name"] user.provider_screen_name = auth["info"]["nickname"] || '' user.provider_email = auth["info"]["email"] if (auth["extra"]["raw_info"] && auth["extra"]["raw_info"]["location"]) user.provider_location = auth["extra"]["raw_info"]["location"]["name"] else user.provider_location ='' end user.provider_image_url = auth["info"]["image"] user.provider_user_url = auth["extra"]["raw_info"]["link"] user.reg_date =Time.now.to_i user.last_login =Time.now.to_i end end # get user by facebook info def self.find_by_provider_and_uid(provider, uid) return self.find(:first, :conditions => ['provider = ? and uid = ?', provider, uid]) end # login def login (auth) self.last_login =Time.now.to_i if self.provider_name != auth["info"]["name"] self.provider_name = auth["info"]["name"] end if self.provider_screen_name != auth["info"]["nickname"] self.provider_screen_name = auth["info"]["nickname"] end if self.provider_email != auth["info"]["email"] self.provider_email = auth["info"]["email"] end if self.provider_location != auth["extra"]["raw_info"]["location"]["name"] self.provider_location = auth["extra"]["raw_info"]["location"]["name"] end if self.provider_image_url != auth["info"]["image"] self.provider_image_url = auth["info"]["image"] end res = self.save logger.info("user_login\t#{self.id}\t#{res}") end # user deta wrapper def display_name return (self.plife_name) ? self.plife_name : self.provider_name end def email return (self.plife_email) ? self.plife_email : self.provider_email end def image_url return (self.plife_image_url) ? self.plife_image_url : self.provider_image_url end def location return (self.plife_location) ? self.plife_location : self.provider_location end def self.add_user_info_by_uid (user_list) uids = user_list.map {|user| user['uid'] } users = self.where(["uid in (?)", uids]) user_hash ={} users.each{|user| user_hash[user['uid']] = user } user_list.each{|user| if (user_hash[user['uid']]) user['joined'] = 1 end } end end <file_sep>class CommentsController < ApplicationController def show @comment = Comment.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @comment } end end def create @comment = Comment.new(params[:comment]) @comment.good = 0 @comment.bad = 0 if session[:topic_id] topic = Topic.find(session[:topic_id]) if topic.comment_list == "" || topic.comment_list == nil topic.comment_list = @comment.id else topic.comment_list = topic.comment_list.to_s + ',' + @comment.id.to_s end topic.save end if current_user @comment.user_id = current_user.uid end respond_to do |format| if @comment.save if topic format.html { redirect_to topic, notice: "Topic and comment were successfully created."} format.json { render json: topic, status: :created, location: topic} else format.html { redirect_to @comment, notice: 'Topic was successfully created.' } format.json { render json: @comment, status: :created, location: @comment } end else format.html { render action: "new" } format.json { render json: @comment.errors, status: :unprocessable_entity } end end end def destroy @comment = Comment.find(params[:id]) @comment.destroy topic = Topic.find(params[:topic_id]) comment_list = "" comments = topic.comment_list.split(",") comments.each do |id| if id.to_s != params[:id].to_s if comment_list == "" comment_list = id else comment_list = comment_list.to_s + ',' + id.to_s end end end topic.comment_list = comment_list topic.save respond_to do |format| format.html { redirect_to topic} format.json { head :ok } end end def vote comment = Comment.find(params[:id]) if params[:voting] == "good" comment.good = comment.good + 1 end if params[:voting] == "bad" comment.bad = comment.bad + 1 end comment.save topic = Topic.find(params[:topic_id]) respond_to do |format| format.html { redirect_to topic} format.json { head :ok } end end end <file_sep>class NullModelBase < ActiveRecord::Base def self.db_get_handle(db_name, table_name) establish_connection db_name<<"_"<<ENV['RAILS_ENV'] set_table_name table_name; end end <file_sep>class ApplicationController < ActionController::Base protect_from_forgery private def is_developer if current_user if current_user.provider_name == "<NAME>" true end end end helper_method :is_developer def current_user if (session[:user_id]) @current_user ||= User.find(session[:user_id]) end end helper_method :current_user def current_project if (session[:project_using]) @current_project ||= Project.find(session[:project_using]) end end helper_method :current_project def categories @categories = [] if current_project if current_project.topic_list topics = current_project.topic_list.split(",") end @topics = [] topics.each do |id| topic = Topic.find(id) if topic @topics << topic end end @topics.each do |t| @categories << t end end end helper_method :categories end <file_sep>class Comment include Mongoid::Document field :description, :type => String field :user_id, :type => String field :good, :type => Integer field :bad, :type => Integer end <file_sep>require 'null_model_base.rb' <file_sep>Rails.application.config.middleware.use OmniAuth::Builder do #provider :twitter,"Consumer key","Consumer secret" if ENV['RAILS_ENV'] == "development" provider :facebook,"313301275373366","<KEY>", {:scope => 'publish_stream,offline_access,email, user_birthday '} elsif ENV['RAILS_ENV'] == "test" provider :facebook,"313301275373366","<KEY>fdbf8", {:scope => 'publish_stream,offline_access,email, user_birthday, read_friendlists'} elsif ENV['RAILS_ENV'] == "production" provider :facebook,"313301275373366","<KEY>", {:scope => 'publish_stream,offline_access,email, user_birthday, read_friendlists'} end end <file_sep>class TopController < ApplicationController def recent session[:project_using] = nil session[:project_id] = nil session[:topic_id] = nil project = Project.find(:first, :conditions => {:name => /^#{"null"}/ }) if project session[:project_using] = project.id redirect_to project end end end
f5dad0b49a10cd055ce2d6c605be3be45b356393
[ "Ruby", "Shell" ]
10
Shell
shota7180/null
0814f0e3d2be67dc1c493f8a7f782e11d16aa63e
10c566f801fdaded8bd123963e8d82549c393544
refs/heads/master
<file_sep>using PhotoManagerClient; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Client_PM { public partial class PhotoSlideshow : Form { List<Photo> ListPhoto; public PhotoSlideshow(ref List<Photo> List) { ListPhoto = List; InitializeComponent(); } private void PhotoSlideshow_Load(object sender, EventArgs e) { LoadSettings(); ListToBrowser(); ChangerEtatBouton(); } private void ChangerEtatBouton() { BTN_Delete.Enabled = PhotoBrowser.SelectedPhoto != null; } private void ListToBrowser() { PhotoBrowser.Clear(); foreach(Photo P in ListPhoto) { PhotoBrowser.AddPhoto(P); } } private void LoadSettings() { if (!Properties.Settings.Default.FirstUse_PhotosBrowser) { Size = Properties.Settings.Default.TaillePhotosBrowser; Location = Properties.Settings.Default.PositionPhotosBrowser; } } private void SaveSettings() { Properties.Settings.Default.TaillePhotosBrowser = Size; Properties.Settings.Default.PositionPhotosBrowser = Location; Properties.Settings.Default.FirstUse_PhotosBrowser = false; Properties.Settings.Default.Save(); } private void PhotoBrowser_SelectedChanged(object sender, EventArgs e) { ChangerEtatBouton(); } private void RemovePhoto() { if (PhotoBrowser.SelectedPhoto != null) { ListPhoto.Remove(PhotoBrowser.SelectedPhoto); ListToBrowser(); } } private void BTN_Quitter_Click(object sender, EventArgs e) { Close(); } private void BTN_Delete_Click(object sender, EventArgs e) { RemovePhoto(); } private void PhotoSlideshow_FormClosing(object sender, FormClosingEventArgs e) { SaveSettings(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Validation; namespace Client_PM { public partial class AddEditPhoto : Form { public PhotoManagerClient.Photo Photo { get; set; } private ValidationProvider ValidationProvider; bool EditingMode = false; public AddEditPhoto(bool Editing) { Photo = new PhotoManagerClient.Photo(); EditingMode = Editing; InitializeComponent(); ValidationProvider = new ValidationProvider(this); ValidationProvider.AddControlToValidate(TBX_Title, TB_Titre_Validation); ValidationProvider.AddControlToValidate(ImageBox, ImageValidation); } /* * Méthode de validation */ private bool TB_Titre_Validation(ref string Message) { Message = "Le titre ne doit pas être vide."; return TBX_Title.Text != ""; } private bool ImageValidation(ref string Message) { Message = "Vous devez sélectionner une image"; return ImageBox.BackgroundImage != null; // Si l'image box a une image, celle de le photo devrait être la même } /* * Fin méthode de validation */ private void BTN_Selectionner_Click(object sender, EventArgs e) { if (FileDialog.ShowDialog() == DialogResult.OK) { try { Image Image = Image.FromFile(FileDialog.FileName); ChangerImage(ref Image); BTN_Rotate.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } } } private void ChangerImage(ref Image Image, bool ChangerImageBox = true) { if (Image != null) { if (ChangerImageBox) // Ce cas sera faux seulement si nous changeons l'image de par l'image box ImageBox.BackgroundImage = Image; Photo.SetImage(Image); } } private void BTN_Ajout_Click(object sender, EventArgs e) { Photo.Title = TBX_Title.Text; Photo.Description = RTB_Description.Text; Photo.Keywords = TBX_Keywords.Text; Photo.Shared = !RB_Private.Checked; Photo.CreationDate = DateTime.Now; } private void ImageBox_BackgroundImageChanged(object sender, EventArgs e) { Image Image = ImageBox.BackgroundImage; // On ne peut pas envoyer une référence à une propriété... ChangerImage(ref Image, false); } private void AddEditPhoto_Load(object sender, EventArgs e) { LoadSettings(); if (EditingMode) { BTN_Ajout.Text = "Modifier"; ImageBox.BackgroundImage = Photo.GetOriginalImage(); TBX_Title.Text = Photo.Title; RTB_Description.Text = Photo.Description; TBX_Keywords.Text = Photo.Keywords; RB_Private.Checked = !Photo.Shared; } } private Image Rotate(Image BaseImage) { Image RotatedImage = (Image)BaseImage.Clone(); RotatedImage.RotateFlip(RotateFlipType.Rotate90FlipNone); return RotatedImage; } private void BTN_Rotate_Click(object sender, EventArgs e) { ImageBox.BackgroundImage = Rotate(ImageBox.BackgroundImage); } private void LoadSettings() { if (!Properties.Settings.Default.FirstUse_AddEditPhoto) { // Taille du form Size = Properties.Settings.Default.TailleAddEditPhoto; // Position du form Location = Properties.Settings.Default.PositionAddEditPhoto; } } private void SaveSettings() { // Taille du form Properties.Settings.Default.TailleAddEditPhoto = Size; // Position du form Properties.Settings.Default.PositionAddEditPhoto = Location; Properties.Settings.Default.FirstUse_AddEditPhoto = false; Properties.Settings.Default.Save(); } private void AddEditPhoto_FormClosing(object sender, FormClosingEventArgs e) { SaveSettings(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Client_PM { public partial class A_propos : Form { public A_propos() { InitializeComponent(); } private void LoadSettings() { if (!Properties.Settings.Default.FirstUse_APropos) { // Taille du form Size = Properties.Settings.Default.TailleAPropos; // Position du form Location = Properties.Settings.Default.PositionAPropos; } } private void SaveSettings() { // Taille du form Properties.Settings.Default.TailleAPropos = Size; // Position du form Properties.Settings.Default.PositionAPropos = Location; Properties.Settings.Default.FirstUse_APropos = false; Properties.Settings.Default.Save(); } private void A_propos_Load(object sender, EventArgs e) { LoadSettings(); } private void A_propos_FormClosing(object sender, FormClosingEventArgs e) { SaveSettings(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Client_PM { // Regroupe les paramètres du diaporama. public class ListeSettings { public bool DefilementAleatoire { get; set; } // Vitesse du défilement en seconde public int VitesseCarousel { get; set; } public ListeSettings() { Reset(); } ~ListeSettings() { SaveSettings(); } public void Reset() { DefilementAleatoire = Properties.Settings.Default.DefilementAleatoireDiapo; VitesseCarousel = Properties.Settings.Default.VitesseDiapo; } public void SaveSettings() { Properties.Settings.Default.DefilementAleatoireDiapo = DefilementAleatoire; Properties.Settings.Default.VitesseDiapo = VitesseCarousel; Properties.Settings.Default.Save(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Validation; using PhotoManagerClient; namespace Client_PM { public partial class Profile : Form { public User User = new User(); private ValidationProvider Validation; bool AvatarChanged; bool UName = false, UNameUnique = false, PSD = false, VLD = false, Avatar = false; public Profile() { InitializeComponent(); } private void Profile_Load(object sender, EventArgs e) { Validation = new ValidationProvider(this, SubmitTask); Validation.AddControlToValidate(TBX_Username, Validate_TBX_Username, Validate_TBX_Username_OnSubmit); Validation.AddControlToValidate(TBX_Password, Validate_TBX_Password); Validation.AddControlToValidate(TBX_Validate, Validate_TBX_Validation); Validation.AddControlToValidate(PBX_Avatar, Validate_PBX_Avatar); if (User != null) User_To_DLG(); } private void BTN_Choose_Click(object sender, EventArgs e) { if (OFD_Image.ShowDialog() == System.Windows.Forms.DialogResult.OK) { PBX_Avatar.BackgroundImage = Image.FromFile(OFD_Image.FileName); } } private bool Validate_TBX_Username(ref string message) { message = "Nom d'usager manquant"; UName = TBX_Username.Text != ""; return TBX_Username.Text != ""; } private bool Validate_TBX_Password(ref string message) { PSD = TBX_Password.Text != ""; message = "Mot de passe manquant"; return TBX_Password.Text != ""; } private bool Validate_TBX_Validation(ref string message) { VLD = TBX_Validate.Text == TBX_Password.Text; message = "Mot de passe ne correspond avec vérification"; return TBX_Validate.Text == TBX_Password.Text; } private bool Validate_PBX_Avatar(ref string message) { Avatar = PBX_Avatar.BackgroundImage != null; message = "Veuillez vhoisir votre avatar."; return PBX_Avatar.BackgroundImage != null; } private bool Validate_TBX_Username_OnSubmit(ref string message) { UNameUnique = !DBPhotosWebServices.UserNameAlreadyUsed(User.Id, TBX_Username.Text); message = "Nom d'usager déjà utilisé"; if (User != null) return !DBPhotosWebServices.UserNameAlreadyUsed(User.Id, TBX_Username.Text); else return !DBPhotosWebServices.UserNameExist(TBX_Username.Text); } private void User_To_DLG() { TBX_Username.Text = User.Name; TBX_Password.Text = <PASSWORD>; TBX_Validate.Text = User.Password; PBX_Avatar.BackgroundImage = User.GetAvatarOriginalImage(); } private void PBX_Avatar_BackgroundImageChanged(object sender, EventArgs e) { AvatarChanged = true; Validation.UpdateValid(PBX_Avatar); } private void SubmitTask() { //if (UName && UNameUnique && PSD && VLD && Avatar) //{ User.Name = TBX_Username.Text; User.Password = <PASSWORD>; if (AvatarChanged) User.SetAvatarImage(PBX_Avatar.BackgroundImage); //} //else // BTN_Edit.DialogResult = DialogResult.None; } private void BTN_Edit_Click(object sender, EventArgs e) { SubmitTask(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using PhotoManagerClient; using System.Threading; namespace Client_PM { public partial class Carousel : Form { public List<Photo> PhotoList { get; set; } private List<Photo> Photos; private ListeSettings Settings; private int[] Order; private bool Random = false; private bool FullScreen = false; private int CurrentIndex; public Carousel() { InitializeComponent(); this.DoubleBuffered = true; this.BackColor = Color.Black; this.BackgroundImageLayout = ImageLayout.Zoom; this.AllowTransparency = false; Settings = new ListeSettings(); } private void ChangerFullScreen() { FullScreen = !FullScreen; if (FullScreen) { this.FormBorderStyle = FormBorderStyle.None; this.MS_Carousel.Visible = false; this.WindowState = FormWindowState.Maximized; } else { this.FormBorderStyle = FormBorderStyle.Sizable; this.MS_Carousel.Visible = true; this.WindowState = FormWindowState.Normal; } } private void SettingsManagement(object DLG) { try { ((CarouselSettings)DLG).ShowDialog(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void OpenSettings() { CarouselSettings DLG = new CarouselSettings(ref Settings); Thread ThreadDLG = new Thread(SettingsManagement); ThreadDLG.Start(DLG); } private void Carousel_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.F11) // Plein écran { ChangerFullScreen(); } else if (e.KeyCode == Keys.F1) // Ouverture du menu des settings { OpenSettings(); } else if (e.KeyCode == Keys.Escape) // Fermeture du plein écran { if (FullScreen) ChangerFullScreen(); } } private void TSMI_Settings_Click(object sender, EventArgs e) { OpenSettings(); } private void Carousel_Shown(object sender, EventArgs e) { Photos = new List<Photo>(); foreach (Photo Photo in PhotoList) { if (Photo != null) Photos.Add(Photo); } SetOrder(); Timer.Start(); } private void SetOrder() { CurrentIndex = 0; int Count = Photos.Count; Order = new int[Count]; for (int i = 0; i < Count; i++) { Order[i] = i; } if (Random) Randomize(); Next(); } private void Randomize() { Random Rand = new Random(DateTime.Now.Second); int nb_Photos = Photos.Count; for (int i = 0; i < nb_Photos - 1; i++) { int j = Rand.Next((nb_Photos - i - 2)) + i + 1; int k = Order[i]; Order[i] = Order[j]; Order[j] = k; } } private void Next() { if (Order.Count() > 0) { // Régler l'image de fond avec la prochaine photo this.BackgroundImage = Photos[Order[CurrentIndex]].GetOriginalImage(); // Index de la prochaine photo. Si était la dernière, revenir à la première CurrentIndex = CurrentIndex < Photos.Count - 1 ? CurrentIndex + 1 : 0; } } private void LoadSettings() { if (!Properties.Settings.Default.FirstUse_Carousel) { // Taille du form Size = Properties.Settings.Default.TailleCarousel; // Position du form Location = Properties.Settings.Default.PositionCarousel; } } private void SaveSettings() { // Taille du form Properties.Settings.Default.TailleCarousel = Size; // Position du form Properties.Settings.Default.PositionCarousel = Location; Properties.Settings.Default.FirstUse_Carousel = false; Properties.Settings.Default.Save(); } private void Timer_Tick(object sender, EventArgs e) { Next(); Timer.Interval = 500 * Settings.VitesseCarousel; } private void Carousel_Load(object sender, EventArgs e) { LoadSettings(); } private void Carousel_FormClosing(object sender, FormClosingEventArgs e) { SaveSettings(); } private void TSMI_FullScreen_Click(object sender, EventArgs e) { ChangerFullScreen(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Client_PM { public partial class CarouselSettings : Form { ListeSettings Settings; public CarouselSettings(ref ListeSettings Liste) { InitializeComponent(); Settings = Liste; } private void SetValue() { TrackBarVitesse.Value = Settings.VitesseCarousel; CB_DefilementAleatoire.Checked = Settings.DefilementAleatoire; } private void CarouselSettings_Load(object sender, EventArgs e) { LoadSettings(); SetValue(); } private void LoadSettings() { if (!Properties.Settings.Default.FirstUse_CarouselSettings) { // Taille du form Size = Properties.Settings.Default.TailleCarouselSettings; // Position du form Location = Properties.Settings.Default.PositionCarouselSettings; } } private void SaveSettings() { // Taille du form Properties.Settings.Default.TailleCarouselSettings = Size; // Position du form Properties.Settings.Default.PositionCarousel = Location; Properties.Settings.Default.FirstUse_CarouselSettings = false; Settings.SaveSettings(); Properties.Settings.Default.Save(); } private void CB_DefilementAleatoire_CheckedChanged(object sender, EventArgs e) { Settings.DefilementAleatoire = CB_DefilementAleatoire.Checked; } private void TrackBarVitesse_ValueChanged(object sender, EventArgs e) { Settings.VitesseCarousel = TrackBarVitesse.Value; } private void BTN_Reset_Click(object sender, EventArgs e) { Settings.Reset(); SetValue(); } private void CarouselSettings_FormClosing(object sender, FormClosingEventArgs e) { SaveSettings(); } } } <file_sep>using PhotoManagerClient; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Client_PM { public partial class MainForm : Form { User Logged_User = null; PhotoFilter PhotoFilter = null; bool Initializing = true; InfoPhoto DLG; public bool IsInfoOpen = false; List<Photo> Slideshow = new List<Photo>(); List<int> Blacklist = new List<int>(); bool AddToSlideMode = true; //True: Ajout - False - Retrait bool AddToBlacklistMode = true; //True: Ajout - False - Retrait public MainForm() { InitializeComponent(); Text = "Photo Manager Client - Not connected"; } private void MainForm_Shown(object sender, EventArgs e) { // Get server attention... WaitSplash.Show(this, "Connecting to Photo Manager..."); string bidon = DBPhotosWebServices.GetServerImagesURLBase(); WaitSplash.Hide(); Update_UI(); } private void Update_UI() { UpdateControls(); UpdateFlashButtons(); } private void MainForm_Load(object sender, EventArgs e) { LoadSettings(); UpdateFlashButtons(); } #region FlashButtons private void FB_Image_Add_Click(object sender, EventArgs e) { AddPhoto(); } private void FB_Image_Edit_Click(object sender, EventArgs e) { EditPhoto(); } private void FB_Image_Remove_Click(object sender, EventArgs e) { if (PhotoBrowser.SelectedPhoto != null && PhotoBrowser.SelectedPhoto.OwnerId == Logged_User.Id) { DBPhotosWebServices.DeletePhoto(PhotoBrowser.SelectedPhoto); PhotoBrowser.DeleteSelectedPhoto(); } } private void FB_Image_Show_Click(object sender, EventArgs e) { ShowPhoto(); } private void FB_Scroll_Prev_Click(object sender, EventArgs e) { PhotoBrowser.SelectPrevious(); } private void FB_Scroll_Next_Click(object sender, EventArgs e) { PhotoBrowser.SelectNext(); } private void FB_Slideshow_Add_Click(object sender, EventArgs e) { if (AddToSlideMode) AddToSlideshow(); else RemoveFromSlideshow(); UpdateAddSlideShow(); } private void FB_Slideshow_Start_Click(object sender, EventArgs e) { OpenSlideShow(); } private void FB_Slideshow_Reset_Click(object sender, EventArgs e) { ResetSlideshow(); UpdateAddSlideShow(); } private void FB_Other_Download_Click(object sender, EventArgs e) { DownloadSelectedImage(); } private void FB_Blacklist_Add_Click(object sender, EventArgs e) { if (AddToBlacklistMode) { AddToBlacklist(); } else { RemoveFromBlacklist(); } FB_Blacklist_Add.Enabled = false; LoadPhoto(); UpdateBlacklistFB(); FB_Blacklist_Reset.Enabled = CBX_BlackList.Items.Count > 0; } private void FB_Blacklist_Reset_Click(object sender, EventArgs e) { if (CBX_BlackList.Items.Count > 0) { CBX_BlackList.Items.Clear(); CBX_BlackList.ResetText(); Blacklist.Clear(); LoadPhoto(); FB_Blacklist_Reset.Enabled = CBX_BlackList.Items.Count > 0; } } #endregion #region StripMenu private void MI_Account_Login_Click(object sender, EventArgs e) { DLG_Login dlg = new DLG_Login(); if (dlg.ShowDialog() == DialogResult.OK) { Logged_User = dlg.Logged_User; Setup_Logged_User(); } } private void MI_Account_Profile_Click(object sender, EventArgs e) { Profile DLG = new Profile(); DLG.User = Logged_User; DialogResult DGR = DLG.ShowDialog(); if (DGR == DialogResult.OK) { Logged_User = DLG.User; DBPhotosWebServices.UpdateUser(Logged_User); } else if (DGR == DialogResult.Yes) { DBPhotosWebServices.DeleteUser(Logged_User.Id); Logged_User = null; } Setup_Logged_User(); } private void Mi_Account_Create_Click(object sender, EventArgs e) { DLG_Account dlg = new DLG_Account(); if (dlg.ShowDialog() == DialogResult.OK) { Logged_User = dlg.User; Setup_Logged_User(); LoadPhoto(); } } private void MI_Account_Exit_Click(object sender, EventArgs e) { Disconnect(); } private void MI_Display_Up_Click(object sender, EventArgs e) { PhotoBrowser.Placement = PhotoBrowserPlacement.Top; } private void MI_Display_Down_Click(object sender, EventArgs e) { PhotoBrowser.Placement = PhotoBrowserPlacement.Bottom; } private void MI_Display_Left_Click(object sender, EventArgs e) { PhotoBrowser.Placement = PhotoBrowserPlacement.Left; } private void MI_Display_Right_Click(object sender, EventArgs e) { PhotoBrowser.Placement = PhotoBrowserPlacement.Right; } private void MI_Blacklist_Add_Click(object sender, EventArgs e) { TBC_PhotoManager.SelectTab(1); } private void TSMI_Help_Click(object sender, EventArgs e) { OpenHelp(); } private void TSMI_About_Click(object sender, EventArgs e) { A_propos DLG = new A_propos(); DLG.ShowDialog(); } #endregion #region Filters private void CBX_UsersList_SelectedIndexChanged(object sender, EventArgs e) { if (RB_Users.Checked && CBX_UsersList.SelectedItem.ToString() != "") { User selectedUser = (User)CBX_UsersList.SelectedItem; if (selectedUser.Id == -1) // Only mine { PhotoFilter.SetUserFilter(false, false, 0); } else { if (selectedUser.Id == 0) // All users { PhotoFilter.SetUserFilter(false, true, 0); } else { PhotoFilter.SetUserFilter(true, false, selectedUser.Id); } } Initializing = true; PhotoFilter.SetKeywordsFilter(false, ""); LoadPhoto(); Init_Keywords_List(); Initializing = false; } } private void CBX_Keywords_SelectedIndexChanged(object sender, EventArgs e) { if (RB_Keyword.Checked && CBX_Keywords.Text != "") { if (!Initializing) { PhotoFilter.SetKeywordsFilter(true, CBX_Keywords.SelectedItem.ToString()); LoadPhoto(); PhotoBrowser.SelectNext(); PhotoBrowser.Focus(); } } } private void CB_HideMyPhotos_CheckedChanged(object sender, EventArgs e) { PhotoFilter.SetUserFilter(CB_HideMyPhotos.Checked, PhotoFilter.ShowAllUsers, PhotoFilter.ByOwnerUserId); LoadPhoto(); } #endregion #region Events private void PhotoBrowser_SelectedChanged(object sender, EventArgs e) { FB_Image_Show.Enabled = PhotoBrowser.SelectedPhoto != null; MI_Info.Enabled = PhotoBrowser.SelectedPhoto != null; MI_Info.Enabled = PhotoBrowser.SelectedPhoto != null; FB_Blacklist_Add.Enabled = PhotoBrowser.SelectedPhoto != null; UpdateAddSlideShow(); UpdateBlacklistFB(); if (PhotoBrowser.SelectedPhoto != null) { if (PhotoBrowser.SelectedPhoto.OwnerId == Logged_User.Id) { FB_Image_Edit.Enabled = true; MI_Edit.Enabled = true; FB_Image_Remove.Enabled = true; MI_Delete.Enabled = true; } FB_Other_Download.Enabled = true; } else { MI_Edit.Enabled = false; FB_Image_Edit.Enabled = false; FB_Image_Remove.Enabled = false; MI_Delete.Enabled = false; FB_Other_Download.Enabled = false; } } private void CBX_BlackList_SelectedIndexChanged(object sender, EventArgs e) { if (CBX_BlackList.SelectedIndex >= 0) { FB_Blacklist_Add.Enabled = true; AddToBlacklistMode = false; FB_Blacklist_Add.BackgroundImage = Properties.Resources.Remove_Neutral; FB_Blacklist_Add.ClickedImage = Properties.Resources.Remove_Clicked; FB_Blacklist_Add.DisabledImage = Properties.Resources.Remove_Disabled; FB_Blacklist_Add.NeutralImage = Properties.Resources.Remove_Neutral; FB_Blacklist_Add.OverImage = Properties.Resources.Remove_Over; } else { AddToBlacklistMode = true; FB_Blacklist_Add.BackgroundImage = Properties.Resources.Add_Neutral; FB_Blacklist_Add.ClickedImage = Properties.Resources.Add_Clicked; FB_Blacklist_Add.DisabledImage = Properties.Resources.Add_Disabled; FB_Blacklist_Add.NeutralImage = Properties.Resources.Add_Neutral; FB_Blacklist_Add.OverImage = Properties.Resources.Add_Over; } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { SaveSettings(); } private void MI_Blacklist_Show_Click(object sender, EventArgs e) { ResetSlideshow(); UpdateAddSlideShow(); } #endregion #region Functions private void Setup_Logged_User() { if (Logged_User != null) { Text = "Photo Manager Client - " + Logged_User.Name; PhotoFilter = new PhotoFilter(Logged_User.Id); Init_UsersList(); Initializing = true; LoadPhoto(); Init_Keywords_List(); Initializing = false; } else { Text = "Photo Manager Client - Not connected"; CBX_UsersList.Items.Clear(); CBX_Keywords.Items.Clear(); PhotoBrowser.Clear(); PhotoFilter = null; } Update_UI(); } private void Init_Keywords_List() { CBX_Keywords.Items.Clear(); CBX_Keywords.Items.Add(""); foreach (string keyword in PhotoFilter.KeywordsList) { CBX_Keywords.Items.Add(keyword.Clone()); } CBX_Keywords.SelectedIndex = 0; } private void AddPhoto() { AddEditPhoto DLG = new AddEditPhoto(false); if (DLG.ShowDialog() == DialogResult.OK) { DLG.Photo.OwnerId = Logged_User.Id; DBPhotosWebServices.CreatePhoto(DLG.Photo); LoadPhoto(); } } private void EditPhoto() { AddEditPhoto DLG = new AddEditPhoto(true); DLG.Photo = PhotoBrowser.SelectedPhoto; if (DLG.ShowDialog() == DialogResult.OK) { DBPhotosWebServices.UpdatePhoto(DLG.Photo); LoadPhoto(); } } public void ShowPhoto() { //Modifier la façon de savoir si l'image et en mode show ou hide. if (!IsInfoOpen) { IsInfoOpen = true; DLG = new InfoPhoto(this); DLG.Photo = PhotoBrowser.SelectedPhoto; DLG.User = DBPhotosWebServices.GetUser(PhotoBrowser.SelectedPhoto.OwnerId).ToString(); DLG.Show(); FB_Image_Show.BackgroundImage = Properties.Resources.Hide_Neutral; FB_Image_Show.ClickedImage = Properties.Resources.Hide_Clicked; FB_Image_Show.DisabledImage = Properties.Resources.Hide_Disabled; FB_Image_Show.NeutralImage = Properties.Resources.Hide_Neutral; FB_Image_Show.OverImage = Properties.Resources.Hide_Over; } else { if (!DLG.IsClosing) { DLG.Close(); } FB_Image_Show.BackgroundImage = Properties.Resources.Show_Neutral; FB_Image_Show.ClickedImage = Properties.Resources.Show_Clicked; FB_Image_Show.DisabledImage = Properties.Resources.Show_Disabled; FB_Image_Show.NeutralImage = Properties.Resources.Show_Neutral; FB_Image_Show.OverImage = Properties.Resources.Show_Over; FB_Image_Show.Refresh(); IsInfoOpen = false; } } private void UpdateFlashButtons() { FB_Image_Add.Enabled = Logged_User != null; MI_Add.Enabled = Logged_User != null; FB_Scroll_Prev.Enabled = Logged_User != null; FB_Scroll_Next.Enabled = Logged_User != null; FB_Slideshow_Start.Enabled = Logged_User != null; FB_Slideshow_Reset.Enabled = Logged_User != null; FB_Blacklist_Reset.Enabled = Logged_User != null && CBX_BlackList.Items.Count > 0; FB_Other_Download.Enabled = PhotoBrowser.SelectedPhoto != null; FB_EditDiapo.Enabled = Logged_User != null; } private void OpenHelp() { DLG_Aide DLG = new DLG_Aide(); DLG.Show(); } private void Init_UsersList() { foreach (User user in PhotoFilter.UsersList) { if (user.Name != null) { CBX_UsersList.Items.Add(user); } } CBX_UsersList.SelectedIndex = 1; } private void Disconnect() { Logged_User = null; Setup_Logged_User(); } private void LoadPhoto() { WaitSplash.Show(this, "Loading photos from server..."); PhotoBrowser.LoadPhotos(PhotoFilter.GetPhotos(), Blacklist); WaitSplash.Hide(); } private void UpdateControls() { TSMI_Carousel.Enabled = Logged_User != null; MI_Account_Profile.Enabled = Logged_User != null; MI_Account_Login.Enabled = Logged_User == null; TSMI_Blacklist.Enabled = Logged_User != null; RB_Users.Enabled = Logged_User != null; RB_Keyword.Enabled = Logged_User != null; RB_Date.Enabled = Logged_User != null; CBX_UsersList.Enabled = Logged_User != null; CBX_Keywords.Enabled = Logged_User != null; CBX_BlackList.Enabled = Logged_User != null; DTP_Start.Enabled = Logged_User != null; DTP_End.Enabled = Logged_User != null; CB_HideMyPhotos.Enabled = Logged_User != null; } private void AddToSlideshow() { bool AlreadyInSlideshow = false; foreach (Photo Image in Slideshow) { AlreadyInSlideshow = AlreadyInSlideshow || Image == PhotoBrowser.SelectedPhoto; //Si l'image est déjà présente dans le slideshow. } if (!AlreadyInSlideshow) Slideshow.Add(PhotoBrowser.SelectedPhoto); } private void ModifyPhotoSlideshow() { PhotoSlideshow DLG = new PhotoSlideshow(ref Slideshow); DLG.ShowDialog(); } private void ResetSlideshow() { Slideshow.Clear(); } private void UpdateAddSlideShow() { bool AlreadyInSlideshow = false; FB_Slideshow_Add.Enabled = PhotoBrowser.SelectedPhoto != null; if (PhotoBrowser.SelectedPhoto != null) { foreach (Photo Image in Slideshow) { if (Image == PhotoBrowser.SelectedPhoto) { AlreadyInSlideshow = true; AddToSlideMode = false; FB_Slideshow_Add.BackgroundImage = Properties.Resources.RemoveFromSlide_Neutral; FB_Slideshow_Add.ClickedImage = Properties.Resources.RemoveFromSlide_Clicked; FB_Slideshow_Add.DisabledImage = Properties.Resources.RemoveFromSlide_Disabled; FB_Slideshow_Add.NeutralImage = Properties.Resources.RemoveFromSlide_Neutral; FB_Slideshow_Add.OverImage = Properties.Resources.RemoveFromSlide_Over; } } if (!AlreadyInSlideshow) { AddToSlideMode = true; FB_Slideshow_Add.BackgroundImage = Properties.Resources.AddToSlide_Neutral; FB_Slideshow_Add.ClickedImage = Properties.Resources.AddToSlide_Clicked; FB_Slideshow_Add.DisabledImage = Properties.Resources.AddToSlide_Disabled; FB_Slideshow_Add.NeutralImage = Properties.Resources.AddToSlide_Neutral; FB_Slideshow_Add.OverImage = Properties.Resources.AddToSlide_Over; } } } private void RemoveFromSlideshow() { foreach (Photo Image in Slideshow) { if (Image == PhotoBrowser.SelectedPhoto) { Slideshow.Remove(Image); break; } } } private void OpenSlideShow() { Carousel DLG = new Carousel(); if (Slideshow.Count != 0) DLG.PhotoList = Slideshow; else DLG.PhotoList = DBPhotosWebServices.GetFilteredPhotos(PhotoFilter); DLG.Show(); } private void CloseTabs() { TBC_PhotoManager.Visible = false; PhotoBrowser.Location = TBC_PhotoManager.Location; PhotoBrowser.Size = new Size(TBC_PhotoManager.Size.Width, ClientSize.Height - 37); Refresh(); } private void OpenTabs() { TBC_PhotoManager.Visible = true; PhotoBrowser.Location = new Point(TBC_PhotoManager.Location.X, TBC_PhotoManager.Size.Height + 30); PhotoBrowser.Size = new Size(TBC_PhotoManager.Size.Width, ClientSize.Height - TBC_PhotoManager.Height - 40); Refresh(); } private void DownloadSelectedImage() { try { if (PhotoBrowser.SelectedPhoto != null) { if (FolderBrowser.ShowDialog() == DialogResult.OK) { PhotoBrowser.SelectedPhoto.GetOriginalImage().Save(FolderBrowser.SelectedPath + "/" + PhotoBrowser.SelectedPhoto.Title + ".png", System.Drawing.Imaging.ImageFormat.Png); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void AddToBlacklist() { if (PhotoBrowser.SelectedPhoto != null) { User CurrentUser = DBPhotosWebServices.GetUser(PhotoBrowser.SelectedPhoto.OwnerId); CBX_BlackList.Items.Add(CurrentUser); Blacklist.Add(CurrentUser.Id); } } private void RemoveFromBlacklist() { if (CBX_BlackList.SelectedIndex >= 0) { foreach (int Id in Blacklist) { if (DBPhotosWebServices.GetUser(Id).Name == CBX_BlackList.SelectedItem.ToString()) { CBX_BlackList.Items.Remove(CBX_BlackList.SelectedItem); Blacklist.Remove(Id); CBX_BlackList.ResetText(); break; } } } } private void UpdateBlacklistFB() { bool AlreadyInBlacklist = false; if (PhotoBrowser.SelectedPhoto != null) { User CurrentUser = DBPhotosWebServices.GetUser(PhotoBrowser.SelectedPhoto.OwnerId); foreach (User User in CBX_BlackList.Items) { if (CurrentUser == User) AlreadyInBlacklist = true; } } if (!AlreadyInBlacklist) { AddToBlacklistMode = true; FB_Blacklist_Add.ClickedImage = Properties.Resources.Add_Clicked; FB_Blacklist_Add.DisabledImage = Properties.Resources.Add_Disabled; FB_Blacklist_Add.NeutralImage = Properties.Resources.Add_Neutral; FB_Blacklist_Add.OverImage = Properties.Resources.Add_Over; } } private void SaveSettings() { // Position du fureteur de photo Properties.Settings.Default.PositionFureteur = PhotoBrowser.Placement.ToString(); // Liste des photos dans le carousel // On ne garde que la liste des IDs des photos puisque Properties ne donne pas l'option de stocker une list<Photo> StringCollection List = new StringCollection(); foreach (Photo P in Slideshow) { List.Add(P.Id.ToString()); } Properties.Settings.Default.PhotoCarousel = List; List.Clear(); // Liste des usagers dans la blaclist foreach (int I in Blacklist) { List.Add(I.ToString()); } Properties.Settings.Default.Blacklist = List; // Position du MainForm Properties.Settings.Default.PositionMainForm = Location; // Taille du MainForm Properties.Settings.Default.TailleMainForm = Size; Properties.Settings.Default.FirstUse_MainForm = false; Properties.Settings.Default.Save(); } private void LoadSettings() { if (!Properties.Settings.Default.FirstUse_MainForm) { // Position du fureteur // Puisqu'il que Properties n'offre pas l'option de choisir des enums, il est stocké en string switch (Properties.Settings.Default.PositionFureteur.ToLower()) { case "bottom": PhotoBrowser.Placement = PhotoBrowserPlacement.Bottom; break; case "top": PhotoBrowser.Placement = PhotoBrowserPlacement.Top; break; case "left": PhotoBrowser.Placement = PhotoBrowserPlacement.Left; break; case "right": PhotoBrowser.Placement = PhotoBrowserPlacement.Right; break; } // Liste des photos du carousel foreach (string ID in Properties.Settings.Default.PhotoCarousel) { Photo Photo = DBPhotosWebServices.GetPhoto(int.Parse(ID)); if (Photo != null) Slideshow.Add(Photo); } // Liste des usagers dans la blacklist foreach (string ID in Properties.Settings.Default.Blacklist) { Blacklist.Add(int.Parse(ID)); } CBX_BlackList_Load(); // Position du MainForm Location = Properties.Settings.Default.PositionMainForm; //Taille du MainForm Size = Properties.Settings.Default.TailleMainForm; } } private void CBX_BlackList_Load() { CBX_BlackList.Items.Clear(); foreach (int ID in Blacklist) { CBX_BlackList.Items.Add(DBPhotosWebServices.GetUser(ID)); } } #endregion private void MI_Add_Click(object sender, EventArgs e) { AddPhoto(); } private void MI_Edit_Click(object sender, EventArgs e) { EditPhoto(); } private void MI_Delete_Click(object sender, EventArgs e) { if (PhotoBrowser.SelectedPhoto != null && PhotoBrowser.SelectedPhoto.OwnerId == Logged_User.Id) { DBPhotosWebServices.DeletePhoto(PhotoBrowser.SelectedPhoto); PhotoBrowser.DeleteSelectedPhoto(); } } private void MI_Info_Click(object sender, EventArgs e) { ShowPhoto(); } private void FB_EditDiapo_Click(object sender, EventArgs e) { ModifyPhotoSlideshow(); UpdateAddSlideShow(); } private void MI_AddToSlideshow_Click(object sender, EventArgs e) { if (PhotoBrowser.SelectedPhoto != null) { AddToSlideshow(); UpdateAddSlideShow(); } } private void MI_EditSlideshow_Click(object sender, EventArgs e) { ModifyPhotoSlideshow(); UpdateAddSlideShow(); } private void MI_ResetSlideshow_Click(object sender, EventArgs e) { ResetSlideshow(); UpdateAddSlideShow(); } private void MI_StartSlideshow_Click(object sender, EventArgs e) { OpenSlideShow(); } private void BTN_DateSearch_Click(object sender, EventArgs e) { PhotoFilter.SetDateFilter(true, DTP_Start.Value, DTP_End.Value); LoadPhoto(); } private void RB_Date_CheckedChanged(object sender, EventArgs e) { BTN_DateSearch.Enabled = RB_Date.Checked; if (RB_Date.Checked == false) PhotoFilter.SetDateFilter(false, DTP_Start.Value, DTP_End.Value); } private void RB_Users_CheckedChanged(object sender, EventArgs e) { if (CBX_UsersList.SelectedItem.ToString() != "") CBX_UsersList_SelectedIndexChanged(sender, e); } private void RB_Keyword_CheckedChanged(object sender, EventArgs e) { if (CBX_Keywords.SelectedItem.ToString() != "") PhotoFilter.SetKeywordsFilter(true, CBX_Keywords.SelectedItem.ToString()); LoadPhoto(); } private void masquerLesOngletsToolStripMenuItem_Click(object sender, EventArgs e) { if (TBC_PhotoManager.Visible) CloseTabs(); else OpenTabs(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Client_PM { public partial class DLG_Aide : Form { public DLG_Aide() { InitializeComponent(); } private void Tabs_Load(object sender, EventArgs e) { LoadSettings(); } private void Tabs_FormClosing(object sender, FormClosingEventArgs e) { SaveSettings(); } private void LoadSettings() { if (!Properties.Settings.Default.FirstUse_Tabs) { // Taille du form Size = Properties.Settings.Default.TailleTabs; // Position du form Location = Properties.Settings.Default.PositionTabs; } } private void SaveSettings() { // Taille du form Properties.Settings.Default.TailleTabs = Size; // Position du form Properties.Settings.Default.PositionTabs = Location; Properties.Settings.Default.FirstUse_Tabs = false; Properties.Settings.Default.Save(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using PhotoManagerClient; namespace Client_PM { public partial class InfoPhoto : Form { public PhotoManagerClient.Photo Photo { get; set; } public string User { get; set; } public bool IsClosing = false; private MainForm Parent; public InfoPhoto(MainForm Parent) { if (Parent == null) throw new Exception("Le formulaire parent ne doit pas être null"); this.Parent = Parent; InitializeComponent(); } private void InfoPhoto_Load(object sender, EventArgs e) { LoadSettings(); PictureBox.Image = Photo.GetOriginalImage(); TBX_Author.Text = User; TBX_Title.Text = Photo.Title; TBX_CreationDate.Text = Photo.CreationDate.ToString(); RTB_Description.Text = Photo.Description; TBX_Keywords.Text = Photo.Keywords; TBX_Size.Text = Photo.GetOriginalImage().Width + "x" + Photo.GetOriginalImage().Height + " pixels"; PBX_Avatar.BackgroundImage = DBPhotosWebServices.GetUser(Photo.OwnerId).GetAvatarOriginalImage(); } private void LoadSettings() { if (!Properties.Settings.Default.FirstUse_InfoPhoto) { // Taille du form // Size = Properties.Settings.Default.TailleInfoPhoto; // Position du form Location = Properties.Settings.Default.PositionInfoPhoto; } } private void SaveSettings() { // Taille du form Properties.Settings.Default.TailleInfoPhoto = Size; // Position du form Properties.Settings.Default.PositionInfoPhoto = Location; Properties.Settings.Default.FirstUse_InfoPhoto = false; Properties.Settings.Default.Save(); } private void BTN_Ok_Click(object sender, EventArgs e) { this.Close(); } private void InfoPhoto_FormClosed(object sender, FormClosedEventArgs e) { IsClosing = true; Parent.ShowPhoto(); } private void InfoPhoto_FormClosing(object sender, FormClosingEventArgs e) { SaveSettings(); } } }
17e8df972ed28abac9a6257674c4610ca60b98f4
[ "C#" ]
10
C#
MisterBlackie/TP3
2000a3ea59db4ffadc98581d777820254a50300a
9b89012a7cc86a42f5892ca554be835522f51ca0
refs/heads/master
<repo_name>mollyjohnson/bashMatrixOperationsShellScript<file_sep>/matrix #!/bin/bash # NOTE: my multiply function passed multiple runs with the grading script with # plenty of time, and I have the screenshots if you need proof of this, but I'm # still requesting that you put my results into a file just in case the time runs # out as even though i feel i've optimized my function and kept to a minimal amount # of looping and file i/o, when the server was extremely busy at one point, # the process was killed. So I think it should pass if not run when the server is # experiencing extremely heavy use loads, but just in case am requesting that you # pleae put my results in a file when grading. Thank you. If you need to see the # screenshots of my testing with the grading script that showed all of the multiply # function passed with full points please let me know. # Name: <NAME> # ONID: johnsmol # CS 344 Winter 2019 # Due: 1/28/18 # Assignment 1 # All information used to implement this script is adapted # from the OSU CS 344 Winter 2019 lectures and assignment hints # unless otherwise specifically indicated. Also adapted from my own # work previously created on 10/8/18 (I took the class previously in the Fall 2018 # term but am retaking for a better grade). # trap command for the signals listed in the assignment instructions adapted from # an OSU CS 344 Piazza post discussion. Signals are: INT is for interrupt, HUP is for hangup, and TERM is for terminate trap "trapCommand" INT HUP TERM trapCommand(){ rm -f *.tmp } dims(){ # NAME # dims - figure out dimensions of a given matrix # SYNOPSOS # calculate and print num of rows, a space, and then the num of columns of the matrix # DESCRIPTION # This is the dims function. This function will take a valid file as an argument or # accept input from stdin. If the file is not readable or too many/few arguments # are given, it will print an error message to stderr and return a value of 1. If # the file or stdin input is valid, it will print the number of rows, a space, and # then the number of columns to stdout and returns 0 (0 is returned automatically). # use the tempInputDims variable to hold path to file with passed in matrix (doesn't # matter if passed in from stdin or froma file). $$ added to end of temp file in order # to prevent any duplicate names being used again mistakenly tempInputDims="tempdims$$.tmp" if [ "$#" = "1" ] then cat > "$tempInputDims" elif [ "$#" = "2" ] then tempInputDims=$2 fi # use wc (word count) with the -l option to count the number of lines (i.e. rows) in the file. # to prevent a newline from being output after this to stdout, use tr (transform) with the -d # option and the newline character, as this will remove the newline character that would normally # be sent to stdout after the line count is printed via wc -l. # using wc -l to count lines (i.e. rows) in a file adapted from: # https://stackoverflow.com/questions/3137094/how-to-count-lines-in-a-document and # https://superuser.com/questions/249307/avoid-printing-line-breaks-in-shell-script # this method will be used throughout this program. cat $tempInputDims | wc -l | tr -d '\n' echo -n " " # head normally reads in first 10 lines of text from a file ($2). -1 added to make head # only read in the first row. All tabs are then transformed into newlines, and the number # of newlines counted (wc is word count, and the -l option makes it only give the line count). Hence # the number of new lines counted + the original first line will equal the number of columns from the original file. # adapted from: https://stackoverflow.com/questions/5761212/count-number-of-columns-in-bash/5761234 # this method will be used throughout this program. head -1 $tempInputDims | tr '\t' '\n' | wc -l } transpose(){ # NAME # transpose - reflect matrix elements along the diagonal # SYNOPSOS # transpose matrix elements so that an MxN matrix becomes an NxM matrix, with the diagonal # elements remaining unchanged. # DESCRIPTION # This is the transpose function. This function will take a valid file as an argument # or accept input from stdin. It will check that the num of args is correct and the file # is readable. if has an error, will print error message to stderr and return 1. otherwise, # will transpose the matrix provided and print this transposed matrix to stdout and return 0 automatically. # use the tempInputTrans variable to hold path to file with passed in matrix (doesn't # matter if passed in from stdin or froma file). $$ added to end of temp file in order # to prevent any duplicate names being used again mistakenly tempInputTrans="temptrans$$.tmp" if [ "$#" = "1" ] then cat > "$tempInputTrans" elif [ "$#" = "2" ] then tempInputTrans=$2 fi # store the number of columns in the cols variable. cols="$(head -1 $tempInputTrans | tr '\t' '\n' | wc -l)" # alternate for loop format adapted from: # https://www.cyberciti.biz/faq/bash-for-loop/ # using cut to take a column from the file and paste each column as a new line adapted from: # https://www.thelinuxrain.com/articles/transposing-rows-and-columns-3-methods # details about the cut and command and paste commands adapted from: # https://www.mkssoftware.com/docs/man1/cut.1.asp and https://www.mkssoftware.com/docs/man1/paste.1.asp # -fn where n is an integer tells cut to cut in field delimiter mode, cutting each column where n is the column number # -s tells paste to concatenate all lines from each input file together on the single output line, in this # case to put the values for each column from the file into a new row, hence transposing the elements in the file # this method will be used throughout this program. for (( i=1; i <= cols; i++ )) do cut -f"$i" $tempInputTrans | paste -s done } mean(){ # NAME # mean - calculates the mean of each column # SYNOPSOS # find sum of each column and divide by num of rows to find the mean using the # formula provided. # DESCRIPTION # This is the mean function. Will take a valid file arg or accept input from stdin. If # valid (not too many/few args and file is readable if using a file), this function will # find the sum of each column, then print this out into a 1xN row vector such that # each element of the row vector is the mean of its corresponding column from the original file or stdin. # this will be printed to stdout. if there was an error, an error message # will be printed to sderr, and will return a value of 1. # use the tempInputTrans variable to hold path to file with passed in matrix (doesn't # matter if passed in from stdin or froma file). $$ added to end of temp file in order # to prevent any duplicate names being used again mistakenly tempInputMean="tempmean$$.tmp" if [ "$#" = "1" ] then cat > "$tempInputMean" elif [ "$#" = "2" ] then tempInputMean=$2 fi # store the number of columns in the columns variable. columns="$(head -1 $tempInputMean | tr '\t' '\n' | wc -l)" # create temp file and transpose tempRowFile="temprow$$.tmp" for (( h=1; h <= columns; h++ )) do cut -f"$h" $tempInputMean | paste -s >> $tempRowFile done # calculate rows. while reading each line from the temp row file, take # each element from that line. sum them. find the mean using the formula # provided in the assignment instructions. whileCount=1 tempFileRows="$(cat $tempRowFile | wc -l | tr -d '\n')" origFileRows="$(cat $tempInputMean | wc -l | tr -d '\n')" while read sumLine do sum=0 for num in $sumLine do (( sum = sum + num )) done # mean calculation obtained from assignment instructions mean=$(( ($sum + ($origFileRows/2)*( ($sum>0)*2-1 )) / $origFileRows )) if [ $whileCount -lt $tempFileRows ] then echo -n -e "$mean\t" else echo "$mean" fi (( whileCount = whileCount + 1 )) done < $tempRowFile } add(){ # NAME # add - add two matrices element-wise # SYNOPSOS # adds two MxN matrices element-wise such that # DESCRIPTION # This function is the add function. Will take in two valid matrices (must match in # dimensions). will then use transposing and parallel file input reading to sum # corresponding elements from the two matrices (i.e. add row 1 column 1 from both # matrices, and so on for the entire matrices) and then print the new matrix with # the sum for each of these corresponding elements to stdout. If the matrix files are # mismatched, will send error message to stderr and return 1. otherwise will return 0. # set temp files to the two arguments passed in leftAddInput="leftaddin$$.tmp" rightAddInput="righdaddin$$.tmp" leftAddInput=$1 rightAddInput=$2 # find the num of cols and rows for each matrix leftColsAdd="$(head -1 $leftAddInput | tr '\t' '\n' | wc -l)" leftRowsAdd="$(cat $leftAddInput | wc -l | tr -d '\n')" rightColsAdd="$(head -1 $rightAddInput | tr '\t' '\n' | wc -l)" rightRowsAdd="$(cat $rightAddInput | wc -l | tr -d '\n')" # check that the two matrices entered match (same num cols and rows) if [ $leftColsAdd -ne $rightColsAdd ] || [ $leftRowsAdd -ne $rightRowsAdd ] then echo "error: mismatched matrices entered" 1>&2 exit 1 fi # create loop counter and temp file forLoopCount=1 tempAddFile="tempadd$$.tmp" # read each line from each file. reading two files in simultaneously method adapted from # method described by the instructor on the Piazza OSU CS 344 discussion board. # use reading in the file lines for both file lines simultaneously and the for loop reading # in line elements simultaneously to create one combined file such that each value that # needs to be added to its accompanying value are adjacent. while read leftMatrixLine <&3 && read rightMatrixLine <&4 do # get each element from each line simultaneously. if the count is less than the num of columns, # the variable needs to be printed with a trailing tab. if the count is equal to the num of cols, # then a newline should be printed after the variable # method for using a for loop to get two lines simultaneously from a file adapted from: # https://www.cyberciti.biz/faq/bash-for-loop/ # add tabs to variables written to the file except the last one, then needs newline for num in $leftMatrixLine $rightMatrixLine do if [ $forLoopCount -lt $leftColsAdd ] then echo -n -e "$num\t" >> $tempAddFile elif [ $forLoopCount -eq $leftColsAdd ] then echo "$num" >> $tempAddFile forLoopCount=0 fi (( forLoopCount = forLoopCount + 1 )) done done 3<"$leftAddInput" 4<"$rightAddInput" # get num of cols from the temp file and create a new temp file tempAddCols="$(head -1 $tempAddFile | tr '\t' '\n' | wc -l)" tempAddCut="tempaddcut$$.tmp" tempOutputWithoutTransform="tempnotransform$$.tmp" # transpose the tempAddFile for (( k=1; k <= $tempAddCols ; k++ )) do cut -f"$k" $tempAddFile | paste -s >> $tempAddCut done # create counter variables addCounter=0 colPrintCount=1 # read in the transposed file and for each line, every two elements should # be added together and then the sum written to the file in the same order # as the elements were ORIGINALLY found in their files. use counter variables # to make sure only every 2 elements are summed and that tabs are added after # every new row element except the last one which gets a newline while read myLine do addSum=0 for addNum in $myLine do if [ $addCounter -lt 2 ] then (( addSum = addSum + addNum )) (( addCounter = addCounter + 1 )) else (( addSum = addNum )) (( addCounter = 1 )) fi if [ $addCounter -eq 2 ] then if [ $colPrintCount -lt $leftRowsAdd ] then echo -e -n "$addSum\t" >> $tempOutputWithoutTransform else echo "$addSum" >> $tempOutputWithoutTransform fi (( colPrintCount = colPrintCount + 1 )) fi done (( addCounter = 0 )) (( addSum = 0 )) (( colPrintCount = 1 )) done < $tempAddCut # create temp file and count the cols on the new temp file prior to transposing tempOutputWithTransform="tempwtransform$$.tmp" tempWithoutTransformCols="$(head -1 $tempOutputWithoutTransform | tr '\t' '\n' | wc -l)" # transpose the file back into proper format using transpose method used before for (( m=1; m <= $tempWithoutTransformCols; m++ )) do cut -f"$m" $tempOutputWithoutTransform | paste -s >> $tempOutputWithTransform done # print file to stdout cat $tempOutputWithTransform } multiply(){ # NAME # multiply - use dot multiplication on two matrices # SYNOPSOS # multiply row elements from first matrix by column elements of second matrix (dot multiply) # DESCRIPTION # This is the multiply function. Will take each element from the first file's rows and # multiply by the corresponding columns of the second file, such that row 1 column 2 # of file 1 would be multiplied by row 2 column 1 of the second file. Transposing the # second file will be used to make the multiplication steps easier. The products will # then be summed such that an MxN and NxP matrix will produce an MxP matrix and print # this to stdout and return 0. If the matrices are not valid for dot multiplication, and # error msg will be printed to stderr and the function will return 1. # create temp files and calculate rows and cols leftMultInput="leftmultin$$.tmp" rightMultInput="righdmultin$$.tmp" leftMultInput=$1 rightMultInput=$2 leftColsMult="$(head -1 $leftMultInput | tr '\t' '\n' | wc -l)" leftRowsMult="$(cat $leftMultInput | wc -l | tr -d '\n')" rightColsMult="$(head -1 $rightMultInput | tr '\t' '\n' | wc -l)" rightRowsMult="$(cat $rightMultInput | wc -l | tr -d '\n')" # check that num of columns of the first file match num of rows in second file if [ $leftColsMult -ne $rightRowsMult ] then echo "error: mismatched matrices entered" 1>&2 exit 1 fi transposedRightInput="transrightinput$$.tmp" # transpose second file so the files are in same row/col format for easier multiplication for (( g=1; g <= $rightColsMult; g++ )) do cut -f"$g" $rightMultInput | paste -s >> $transposedRightInput done # read in each line from first arg file, then read in each line from the 2nd # arg transposed file. for each column, extract the element, multiply, and sum for the line, # following the dot multiplication rules found at: https://www.mathsisfun.com/algebra/vectors-dot-product.html # use variables to hold each line, adapted from: # https://superuser.com/questions/121627/how-to-get-elements-from-list-in-bash multSum=0 multResultsFile="multresults$$.tmp" tempMult=0 counter=0 transposedCols="$(head -1 $transposedRightInput | tr '\t' '\n' | wc -l)" while read leftMatrixLineMult do leftLine="$leftMatrixLineMult" while read rightMatrixLineMult do rightLine="$rightMatrixLineMult" for (( a=1; a <= $transposedCols; a++ )) do # -d for cut means to use DELIM instead of tab for field delimiter, # and -f means to select only these fields. so by incrementing a, will access all fields. # taking each element from a line adapted from: # https://superuser.com/questions/121627/how-to-get-elements-from-list-in-bash leftElement="$(echo $leftLine | cut -d" " -f"$a")" rightElement="$(echo $rightLine | cut -d" " -f"$a")" (( tempMult = leftElement * rightElement )) (( multSum = multSum + tempMult )) done (( counter = counter + 1 )) echo -e -n "$multSum" >> $multResultsFile if [ $counter -lt $rightColsMult ] then echo -n -e "\t" >> $multResultsFile else echo >> $multResultsFile fi (( multSum = 0 )) done < $transposedRightInput (( counter = 0 )) done < $leftMultInput cat $multResultsFile } # check for correct number of arguments (1 or 2 for dims, transpose, and mean since they can also take stdin, and 3 for # add and multiply, since they must take in 2 files and can't use stdin). If there's an incorrect number of arguments, # or if a file or files passed in is either unreadable or nonexistent, send error message to stderr and return 1 # (a non-zero number), otherwise call the appropriate function and return 0 automatically. Note: -s means to check if # the file exists and is non-empty, and -r checks that the file is readable. This file checking is adapted from: # https://askubuntu.com/questions/558977/checking-for-a-file-and-whether-it-is-readable-and-writable/558990 if [ "$#" = "1" ] then if [ "$1" = "dims" ] || [ "$1" = "transpose" ] || [ "$1" = "mean" ] then $1 "${@:1}" else echo "error: invalid number of arguments" 1>&2 exit 1 fi elif [ "$#" = "2" ] then if [ "$1" = "dims" ] || [ "$1" = "transpose" ] || [ "$1" = "mean" ] then if [[ -s $2 && -r $2 ]] then $1 "${@:1}" else echo "error: file does not exist or is not readable" 1>&2 exit 1 fi else echo "error: invalid number of arguments" 1>&2 exit 1 fi elif [ "$#" = "3" ] then if [ "$1" = "add" ] || [ "$1" = "multiply" ] then if [[ -s $2 && -r $2 ]] && [[ -s $3 && -r $3 ]] then $1 "${@:2}" else echo "error: file does not exist or is not readable" 1>&2 exit 1 fi else echo "error: invalid number of arguments" 1>&2 exit 1 fi else echo "error: invalid number of arguments" 1>&2 exit 1 fi # idea to add .tmp to all files to make them easy to remove when script completes normally adapted # from OSU CS 344 Piazza post/slack discussion rm -f *.tmp
46ec7a37038acf5a767e2d66386a49e20ab0fe5e
[ "Shell" ]
1
Shell
mollyjohnson/bashMatrixOperationsShellScript
a82f995989af0ad80f8b0a5c87fd434010cdf0d9
097fba986017f421a243f9bdc3743076b18ffa47
refs/heads/master
<file_sep># mustached-turducken <file_sep>class User < ActiveRecord::Base geocoded_by :address after_validation :geocode validates :address, presence: true end <file_sep>json.extract! @user, :id, :venue, :description, :address, :created_at, :updated_at
8712601dfd75c6e52aa45bf07006acb88c38daca
[ "Markdown", "Ruby" ]
3
Markdown
andynguyen11/mustached-turducken
e1cc68b6fc49140f7f201b0ef0a543f5786e05cb
fc37e4276f74f1999c1fa7bb705fdfae8fff9db2
refs/heads/master
<repo_name>wladradchenko/example.weight.spectrum.wladradchenko.ru<file_sep>/spectrum.py def read(path): # Идея в том, чтобы перевести значения из двоичной системы в десятеричную A = [] with open(path) as f: for line in f: A.append(line.rstrip()) n = len(A[0]) # Длина вектора [0] size = len(A) # Количество векторов (строк) в файле # Проверим входной файл по критериям for i in range(size): if len(A[i]) != n: first_message = "Размер строк данных имеет разные длины" second_message = "Строка: " + str(i) return(print(first_message), print(second_message), print("Обработка остановлена...")) else: for j in range(n): if int(A[i][j]) > 1: first_message = "Значение > 1" second_message = "Строка: " + str(i) + " Позиция: " + str(j) return(print(first_message), print(second_message), print("Обработка остановлена...")) for i in range(len(A)): # Перевод из двоичной системы A[i] = int(A[i], 2) return(A, n, size) def result(A, n, size): result = [] # Вектор, для записи конечного результата for r in range(1): basis = [] # Содержит линейно зависимые вектора. for j in range(size): length = len(bin(A[j])[2:]) - 1 for i in range(size): if (A[i] & 2**length): if i != j: A[i] ^= A[j] basis.append(A[i]) # Производим рассчет биномальных коэффициентов, по найденому базису. weight = [0]*(n+1) # Равен длине вектора (n+1, из-за веса 0). z = int(2**(size)) zc = z ^ (z//2) temp = 0 for k in range(zc): if zc % 2 == 1: temp ^= basis[k] zc // 2 # Преобразование значений в двоичные и считаем количество совпадений с 1 location = bin(temp).count('1') weight[location] += 1 # Вес, как количество единиц # Присваиваем значения, для подсчета длины elder, original = zc, (z+1) ^ ((z+1)//2) for j in range(z + 1, int(2**(size) * 2)): # Ищем первое совпадание с 1 в двоичном значении id_j = bin(elder - original)[::-1].find('1') temp ^= basis[id_j] location = bin(temp).count('1') weight[location] += 1 # Возвращаем значение длины в original для сравния elder elder, original = original, (j+1) ^ ((j+1)//2) result.append(weight) return(result) def outfile(path): with open("file.txt", "w") as output: for i in range(len(path[0])): output.write(str(i)+'\t'+str(path[0][i])+'\n') def main(path): A, n, size = read(path) path = result(A, n, size) outfile(path) print("Готово!") <file_sep>/README.md # Вычисление весового спектра линейного подпространства Главный критерий, применение только средства языка Python, без подключения какой-либо библиотеки. Формулировка Процитируем первоначальную формулировку задачи: a) Назовем вектором строку битов (значения 0 или 1) фиксированной длины N: то есть, всего возможно 2^N различных векторов. b) Введем операцию сложения по модулю 2 векторов (операция xor), которая по двум векторам a и b получает вектор a + b той же длины N. c) Пусть дано множество A = {ai | i ∈ 1..K} из 0 ≤ K ≤ 2^N векторов. Назовем его порождающим: при помощи сложения ai множества A можно получить 2^K векторов вида ∑i[1..K]=bi * ai, где bi равно либо 0, либо 1. d) Весом вектора назовем количество единичных (ненулевых) битов в векторе: то есть, вес — это натуральное число от 0 до N. Требуется для заданных порождающих множества векторов и числа N построить гистограмму (спектр) количества различных векторов по их весу. Формат входных данных: Текстовый файл из набора строк одинаковой длины по одному вектору в строке (символы 0 и 1 без разделителей). Для задачи, в качестве входных данных генерировались векторы в количестве 2^N, тем не менее, в разделе "Дополнительно", изложен способ вывода данных их текстового файла в код в качестве тех же переменных. Формат выходных данных: Текстовый файл с парой значений вес/количество разделенных символом табуляции, по одной паре на строку, сортированный по числовому значению веса. # Инструкция по применению: Запуск в Google Colab 1. Скачивание с репозиторий !git clone https://github.com/VladicNaAmure/Weight-Spectrum- 2. Запуск %run /content/Weight-Spectrum-/spectrum.py 3. Запуск вычисления весового спектра линейного подпространства main('/content/.../filename.txt'). 4. Открываем появившийся file.txt, как выходной файл. # Оценка используемых ресурсов file_in | tst_20_32 | tst_20_8192 | tst_24_32 | tst_24_8 | tst_25_8 | tst_30_8 | tst_31_32 | tst_32_256 | tst_32_32 | tst_32_64 | tst_33_64 --- | --- | --- | --- |--- |--- |--- |--- |--- |--- |--- |--- real time| 984 ms | 54.1 s | 15.8 s | 1.38 ms | 1.68 ms | 1.53 ms | 35min 13s | 3h 4min 46s | 1.98 ms | 1h 31min 26s | 3h 3min 53s user time| 981 ms | 54.1 s | 15.8 s | 1.38 ms | 886 µs | 1.44 ms | 35min 13s | 3h 4min 44s | 1.81 ms | 1h 31min 25s | 3h 3min 51s sys time| 2.43 ms | 6.54 ms | 987 µs | 1 µs | 799 µs | 90 µs | 214 ms | 1.48 s | 176 µs | 819 ms | 1.36 s peak memory | 181.35 MiB | 182.39 MiB | 182.42 MiB | 182.43 MiB | 182.07 MiB | 182.14 MiB | 182.07 MiB | 182.55 MiB | 182.05 MiB | 182.86 MiB | 182.50 MiB # Ключевые решения: Для ускорения вычислений, все бинарные числа из входного файла переводятся в десятичную систему счисления. Далее выясняется, длина вектора больше или меньше количества строк для вычисления суммы биномиальных коэффициентов. В качестве выходного файла, сопоставлены каждому возможному весу (от 0 до длины векторов) количество подмножеств, вес суммарного вектора.
442bd2b568c6c281b078137cbef64e76b5829473
[ "Markdown", "Python" ]
2
Python
wladradchenko/example.weight.spectrum.wladradchenko.ru
aae94b5fd74a5ffad62c4642ebb18d2aabc3fe6e
ba66a41f5843aeca0b2443a01f61b555cd3ec936
refs/heads/master
<repo_name>bowserf/android-cmake-sample<file_sep>/app/src/main/cpp/CMakeLists.txt # Define the minimum version of CMake required to use this CMakeList. # Some functions don't exist in previous version of CMake by exampe. cmake_minimum_required(VERSION 3.4.1) # Define a name for this project. It will be accessible with ${PROJECT_NAME}. project(calculator) # Create a library with the name defined for the project. # Set it as SHARED library (will generate a .so file) # Set the source file add_library( ${PROJECT_NAME} SHARED Calculator.cpp) # Define a variable called "subdirectory_DIR" with the following value set( subdirectory_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../../subdirectory) # Indicate that we will use the CMakeList define at the following path. add_subdirectory( ${subdirectory_DIR} ./subdirectory ) # Add the library generated by the other CMakeList in the output of this project. target_link_libraries( ${PROJECT_NAME} subdirectoryLibrary ) # Import an already existing .so file # Here, we add a dependency to the shared_library prebuilt include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../shared_library/include/) set( SHARED_LIBRARY_SO ${CMAKE_CURRENT_SOURCE_DIR}/../../../../shared_library/prebuilt/debug/${CMAKE_ANDROID_ARCH_ABI}/libsharedLibrary.so ) # IMPORTED allows to depends on a library file outside the project. add_library( sharedLibrary SHARED IMPORTED ) # IMPORTED_LOCATION specifies the location of the library file on disk set_target_properties( sharedLibrary PROPERTIES IMPORTED_LOCATION ${SHARED_LIBRARY_SO} ) # Add the library to this project target_link_libraries( ${PROJECT_NAME} sharedLibrary ) # Import an already existing .a file # Here, we add a dependency to the shared_library prebuilt include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../static_library/include/) set( STATIC_LIBRARY_A ${CMAKE_CURRENT_SOURCE_DIR}/../../../../static_library/prebuilt/debug/${CMAKE_ANDROID_ARCH_ABI}/libstaticLibrary.a ) # IMPORTED allows to depends on a library file outside the project. add_library( staticLibrary STATIC IMPORTED ) # IMPORTED_LOCATION specifies the location of the library file on disk set_target_properties( staticLibrary PROPERTIES IMPORTED_LOCATION ${STATIC_LIBRARY_A} ) # Add the library to this project target_link_libraries( ${PROJECT_NAME} staticLibrary )<file_sep>/app/src/main/cpp/Calculator.cpp #include "Calculator.h" extern "C" { JNIEXPORT jlong Java_fr_bowserf_cmakesample_Calculator_multiply( JNIEnv *env, jobject /* this */, jlong value1, jlong value2) { return multiply(value1, value2); } JNIEXPORT jlong Java_fr_bowserf_cmakesample_Calculator_add( JNIEnv *env, jobject /* this */, jlong value1, jlong value2) { return add(value1, value2); } JNIEXPORT jlong Java_fr_bowserf_cmakesample_Calculator_minus( JNIEnv *env, jobject /* this */, jlong value1, jlong value2) { return minus(value1, value2); } }<file_sep>/static_library/src/Subtraction.cpp #include "Subtraction.h" long minus(long value1, long value2) { return value1 - value2; } <file_sep>/README.md [![NDK version](https://img.shields.io/static/v1.svg?label=NDK&message=version%2019&color=blue)]() [![CMake version](https://img.shields.io/static/v1.svg?label=CMake&message=3.6.0&color=red)]() # Android & CMake sample Put his hands in the native code (C/C++) with the Android NDK can be a hard task for an Android developer used to Java/Kotlin and Gradle. This sample shows several use cases about how to use CMake: - to build native library without Android Studio - to use prebuilt library (shared (.so) or static (.a)) - to depends on another native module from your native module - to build Android application with native code. ## Project The application allows you to do some computations on 2 numbers given in input. Computations are realized by native libraries, written in C/C++, embedded in the application. Each computation is realized by one of the library and each library is imported in a different way using CMake. The project contains 4 modules: - app - subdirectory - shared_library - static_library ### Modules The `app` module contains the Android application code and depends on other modules to do computations. Other modules contains C/C++ code and each one does one different computation: - `subdirectory` does a multiplication on 2 numbers. - `shared_library` does an addition on 2 numbers. - `static_library` does a subtraction on 2 numbers. #### App module This module contains the code of the Android application. It contains Kotlin code to manage a basic Android application but also C/C++ code to communicate with the native libraries this application depends on. Dependencies on native libraries are defined in the CMakeList targeted by the `build.gradle` of the module: ``` externalNativeBuild { cmake { path "src/main/cpp/CMakeLists.txt" } } ``` The C/C++ code uses JNI to create a bridge between Kotlin code and pure C/C++ code. It allows to write functions which are called by Kotlin code and from inside JNI function, to call any C/C++ function. #### Subdirectory module This module is imported by the `app` module with a CMake dependency. The CMakeList used by the `app` module targets the CMakeList of this module with the command `add_subdirectory`. The library is built as a shared library. A `.so` file is generated and contains all the code. The `include` directory contains all `public` headers required by the `app` module to be able to use it. The library exposes its headers by using `target_include_directories` with `PUBLIC` visibility. #### Shared_library module This module allows to generate a shared library, a `.so` file, by executing the `library_built.sh` script. This module is not built each time the `app` module is built. `app` module only targets the pre-generated `.so` file and its headers inside the `include` directory. To import headers in the `app` module, we use the command `include_directories` #### Static_library module This module allows to generate a static library, a `.a` file, by executing the `library_built.sh` script. This module is not built each time the `app` module is built. `app` module only targets the pre-generated `.a` file and its headers inside the `include` directory. To import headers in the `app` module, we use the command `include_directories` ## Resources: - [Android NDK guides](https://developer.android.com/ndk/guides) - [Android NDK roadmap](https://android.googlesource.com/platform/ndk/+/master/docs/Roadmap.md) - [Configure CMake from developer android web site](https://developer.android.com/studio/projects/configure-cmake) - [Configure CMake from android ndk web site](https://developer.android.com/ndk/guides/cmake) - [CMake changelog](https://cmake.org/cmake/help/latest/release/index.html) - [Codelab to create a Hello-CMake](https://codelabs.developers.google.com/codelabs/android-studio-cmake/index.html#0) - [Android NDK samples](https://github.com/googlesamples/android-ndk/tree/master) <file_sep>/static_library/include/Subtraction.h #ifndef ANDROID_CMAKE_SAMPLE_SUBTRACTION_H #define ANDROID_CMAKE_SAMPLE_SUBTRACTION_H long minus(long value1, long value2); #endif //ANDROID_CMAKE_SAMPLE_SUBTRACTION_H <file_sep>/shared_library/include/Addition.h #ifndef ANDROID_CMAKE_SAMPLE_ADDITION_H #define ANDROID_CMAKE_SAMPLE_ADDITION_H long add(long value1, long value2); #endif //ANDROID_CMAKE_SAMPLE_ADDITION_H <file_sep>/subdirectory/src/Multiply.cpp #import "Multiply.h" long multiply(long value1, long value2) { return value1 * value2; } <file_sep>/app/src/main/java/fr/bowserf/cmakesample/MainActivity.kt package fr.bowserf.cmakesample import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val calculator = Calculator() val tvResultComputation = findViewById<TextView>(R.id.tv_result_computation) val editTextVal1 = findViewById<EditText>(R.id.edit_value1) val editTextVal2 = findViewById<EditText>(R.id.edit_value2) val operator = findViewById<TextView>(R.id.tv_multiply_symbol) findViewById<Button>(R.id.btn_multiply).setOnClickListener { val value1 = editTextVal1.text.toString().toLong() val value2 = editTextVal2.text.toString().toLong() val result = calculator.multiply(value1, value2) tvResultComputation.text = result.toString() operator.text = "x" } findViewById<Button>(R.id.btn_addition).setOnClickListener { val value1 = editTextVal1.text.toString().toLong() val value2 = editTextVal2.text.toString().toLong() val result = calculator.add(value1, value2) tvResultComputation.text = result.toString() operator.text = "+" } findViewById<Button>(R.id.btn_subtraction).setOnClickListener { val value1 = editTextVal1.text.toString().toLong() val value2 = editTextVal2.text.toString().toLong() val result = calculator.minus(value1, value2) tvResultComputation.text = result.toString() operator.text = "-" } } } <file_sep>/subdirectory/include/Multiply.h #ifndef ANDROID_CMAKE_SAMPLE_MULTIPLY_H #define ANDROID_CMAKE_SAMPLE_MULTIPLY_H long multiply(long value1, long value2); #endif //ANDROID_CMAKE_SAMPLE_MULTIPLY_H <file_sep>/app/src/main/java/fr/bowserf/cmakesample/Calculator.kt package fr.bowserf.cmakesample class Calculator { external fun multiply(value1: Long, value2: Long): Long external fun add(value1: Long, value2: Long): Long external fun minus(value1: Long, value2: Long): Long companion object { init { System.loadLibrary("calculator") } } }<file_sep>/app/build.gradle.kts plugins { id("com.android.application") kotlin("android") } val compileSdkProjectVersion: Int by project val minSdkProjectVersion: Int by project val targetSdkProjectVersion: Int by project android { compileSdk = compileSdkProjectVersion defaultConfig { applicationId = "fr.bowserf.cmakesample" minSdk = minSdkProjectVersion targetSdk = targetSdkProjectVersion versionCode = 1 versionName = "1.0" // specify for which architectures we want to generate native library files. ndk { abiFilters.addAll(listOf("armeabi-v7a", "x86", "x86_64", "arm64-v8a")) } // define the path where prebuilt ".so" files are embedded in the final APK /*sourceSets { debug { jniLibs.srcDirs "../shared_library/prebuilt/debug" } release { jniLibs.srcDirs "../shared_library/prebuilt/release" } }*/ } buildTypes { release { isMinifyEnabled = true proguardFiles(getDefaultProguardFile("proguard-android.txt")) proguardFiles("proguard-rules.pro") } } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = "1.8" } externalNativeBuild { cmake { // define the path where the CMakeList has been put for this module. path("src/main/cpp/CMakeLists.txt") // specify the CMake version we want to use. version = "3.18.1" } } } dependencies { // Kotlin implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.21") // Android support implementation("com.android.support:appcompat-v7:28.0.0") implementation("com.android.support.constraint:constraint-layout:1.1.3") } <file_sep>/shared_library/src/Addition.cpp #include "Addition.h" long add(long value1, long value2) { return value1 + value2; } <file_sep>/static_library/library_build.sh #!/usr/bin/env bash if [ -z "$ANDROID_NDK" ]; then echo "Please set ANDROID_NDK to the Android NDK folder" exit 1 fi if [ -z "$JAVA_HOME" ]; then echo "Please set JAVA_HOME to the java folder" exit 1 fi ROOT_DIR=$(pwd) BUILD_DIR=${ROOT_DIR}/build function build_for_android { ABI=$1 ANDROID_SYSTEM_VERSION=$2 BUILD_TYPE_NAME=$3 echo $BUILD_TYPE_NAME if [[ "$BUILD_TYPE_NAME" == "debug" ]] then BUILD_TYPE="Debug" elif [[ "$BUILD_TYPE_NAME" == "release" ]] then BUILD_TYPE="Release" else echo "the BUILD_TYPE_NAME in second argument isn't managed : ${BUILD_TYPE_NAME}" exit 1 fi ABI_BUILD_DIR=${ROOT_DIR}/build/${ABI} cmake -B${ABI_BUILD_DIR} \ -H. \ -DCMAKE_BUILD_TYPE=${BUILD_TYPE} \ -DANDROID_ABI=${ABI} \ -DCMAKE_RUNTIME_OUTPUT_DIRECTORY=${ROOT_DIR}/prebuilt/${BUILD_TYPE_NAME}/${ABI}/ \ -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=${ROOT_DIR}/prebuilt/${BUILD_TYPE_NAME}/${ABI}/ \ -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=${ROOT_DIR}/prebuilt/${BUILD_TYPE_NAME}/${ABI}/ \ -DANDROID_PLATFORM=${ANDROID_SYSTEM_VERSION} \ -DCMAKE_ANDROID_STL=c++_static \ -DCMAKE_ANDROID_NDK=$ANDROID_NDK \ -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \ -DANDROID_TOOLCHAIN=clang \ -DCMAKE_INSTALL_PREFIX=. pushd ${ABI_BUILD_DIR} make -j5 popd rm -rf ${ABI_BUILD_DIR} } build_for_android armeabi-v7a android-21 debug build_for_android arm64-v8a android-21 debug build_for_android x86 android-21 debug build_for_android x86_64 android-21 debug build_for_android armeabi-v7a android-21 release build_for_android arm64-v8a android-21 release build_for_android x86 android-21 release build_for_android x86_64 android-21 release<file_sep>/app/src/main/cpp/Calculator.h #ifndef ANDROID_CMAKE_SAMPLE_CALCULATOR_H #define ANDROID_CMAKE_SAMPLE_CALCULATOR_H #include <jni.h> #include "Multiply.h" #include "Addition.h" #include "Subtraction.h" extern "C" { JNIEXPORT jlong Java_fr_bowserf_cmakesample_Calculator_multiply( JNIEnv *env, jobject /* this */, jlong value1, jlong value2 ); JNIEXPORT jlong Java_fr_bowserf_cmakesample_Calculator_add( JNIEnv *env, jobject /* this */, jlong value1, jlong value2 ); JNIEXPORT jlong Java_fr_bowserf_cmakesample_Calculator_minus( JNIEnv *env, jobject /* this */, jlong value1, jlong value2 ); } #endif //ANDROID_CMAKE_SAMPLE_CALCULATOR_H <file_sep>/shared_library/CMakeLists.txt cmake_minimum_required(VERSION 3.4.1) project(sharedLibrary) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") file( GLOB_RECURSE shared_library_sources ${CMAKE_CURRENT_SOURCE_DIR}/src/*.c ${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp) file( GLOB_RECURSE shared_library_headers ${CMAKE_CURRENT_SOURCE_DIR}/src/*.h ${CMAKE_CURRENT_SOURCE_DIR}/include/*.h ) add_library( ${PROJECT_NAME} SHARED ${shared_library_sources} ${shared_library_headers} ) target_include_directories( ${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include/ )<file_sep>/subdirectory/CMakeLists.txt cmake_minimum_required(VERSION 3.4.1) project(subdirectoryLibrary) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") file( GLOB_RECURSE subdirectory_library_sources ${CMAKE_CURRENT_SOURCE_DIR}/src/*.c ${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp ) file( GLOB_RECURSE subdirectory_library_headers ${CMAKE_CURRENT_SOURCE_DIR}/src/*.h ${CMAKE_CURRENT_SOURCE_DIR}/include/*.h ) add_library( ${PROJECT_NAME} SHARED ${subdirectory_library_sources} ${subdirectory_library_headers} ) target_include_directories( ${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include )<file_sep>/static_library/CMakeLists.txt cmake_minimum_required(VERSION 3.4.1) project(staticLibrary) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") file( GLOB_RECURSE static_library_sources ${CMAKE_CURRENT_SOURCE_DIR}/src/*.c ${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp ) file( GLOB_RECURSE static_library_headers ${CMAKE_CURRENT_SOURCE_DIR}/src/*.h ${CMAKE_CURRENT_SOURCE_DIR}/include/*.h ) add_library( ${PROJECT_NAME} STATIC ${static_library_sources} ${static_library_headers} ) target_include_directories( ${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include/ )
ff90dd94a2dbdcd5c56d1ab533ee3c8953fc9218
[ "CMake", "Markdown", "Kotlin", "C", "C++", "Shell" ]
17
CMake
bowserf/android-cmake-sample
9af750b23ca9bd9ac510f5c6d32a4af9ec1f5567
0c4a987dbc61bc66b047431ec1c813f37c364f4d
refs/heads/main
<file_sep>package fi.haagahelia.postulo.web; import java.time.LocalDate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @CrossOrigin("http://localhost:8081") @Controller @RequestMapping("/api/csv") public class CSVController { @Autowired CSVService fileService; @GetMapping("/download") public ResponseEntity<Resource> getFile() { String filename = "requirements-" + LocalDate.now() + ".csv"; InputStreamResource file = new InputStreamResource(fileService.load()); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename) .contentType(MediaType.parseMediaType("application/csv")) .body(file); } } <file_sep>package fi.haagahelia.postulo.domain; import java.time.LocalDate; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; // public interface RequirementRepository extends CrudRepository<Requirement, Long>{ public interface RequirementRepository extends CrudRepository<Requirement, Long>, JpaRepository<Requirement, Long>{ List<Requirement> findByReqid(String reqid); List<Requirement> findByType(Type type); List<Requirement> findBySummary(String summary); List<Requirement> findByPriority(String priority); List<Requirement> findBySource(String source); List<Requirement> findByOwner(String owner); List<Requirement> findByRdate(LocalDate rdate); @Query("SELECT r FROM Requirement r WHERE CONCAT(r.reqid, ' ', r.type, ' ', r.summary, ' ', r.rationale, ' ', r.priority, ' ', r.source, ' ', r.owner, ' ', r.rdate, ' ') LIKE %?1%") public List<Requirement> search(String keyword); } <file_sep>package fi.haagahelia.postulo.domain; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import com.fasterxml.jackson.annotation.JsonBackReference; @Entity public class Type { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long typeid; // This would prevent multiple categories with same name @Column(name ="name", nullable = false, unique = true) private String name; // private String description; @JsonBackReference @OneToMany(cascade = CascadeType.ALL, mappedBy = "type") private List<Requirement> requirements; public Type() {} public Type(String name) { super(); this.name = name; } public Long getTypeid() { return typeid; } public void setTypeid(Long typeid) { this.typeid = typeid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Requirement> getRequirements() { return requirements; } public void setRequirements(List<Requirement> requirements) { this.requirements = requirements; } /* public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } */ @Override public String toString() { // return "RequirementType [typeid=" + typeid + ", name=" + name + ", description=" + description + "]"; return "RequirementType [typeid=" + typeid + ", name=" + name + "]"; } } <file_sep># Postulo A very basic requirements repository poc for the Server Programming SWD4TF021-3007 course with following features - Bacic requirements management features - Create, Read, Update and Delete - Register and activate a new account - An API for the requirements - Downloads the requirements as CSV file More features available in the stable and dev branches. <file_sep>package fi.haagahelia.postulo.web; import java.util.List; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.repository.query.Param; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import fi.haagahelia.postulo.domain.Requirement; import fi.haagahelia.postulo.domain.RequirementRepository; import fi.haagahelia.postulo.domain.TypeRepository; @Controller public class RequirementController { @Autowired private RequirementRepository rrepository; @Autowired private TypeRepository trepository; @RequestMapping(value="/login") public String login() { return "login"; } @Autowired private RequirementService service; @RequestMapping(value="/logout") public String logout (HttpServletRequest request, HttpServletResponse response) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null){ new SecurityContextLogoutHandler().logout(request, response, auth); } return "redirect:/login?logout"; } // home page @RequestMapping(value= {"/", "/home"}) public String home() { // return "home"; } // List all requirements @RequestMapping(value= {"/lista"}) public String viewList(Model model, @Param("keyword") String keyword) { List<Requirement> listRequirements = service.listAll(keyword); model.addAttribute("listRequirements", listRequirements); model.addAttribute("keyword", keyword); return "lista"; } // RESTful service to get all requirements @RequestMapping(value="/requirements", method = RequestMethod.GET) public @ResponseBody List<Requirement> requirementListRest() { return (List<Requirement>) rrepository.findAll(); } // RESTful service to get requirement by id @RequestMapping(value="/requirement/{id}", method = RequestMethod.GET) public @ResponseBody Optional<Requirement> findRequirementRest(@PathVariable("id") Long requirementId) { return rrepository.findById(requirementId); } // Add new requirement // @PreAuthorize("hasAuthority('ADMIN')") @RequestMapping(value = "/add") public String addRequirement(Model model){ model.addAttribute("requirement", new Requirement()); model.addAttribute("types", trepository.findAll()); return "addrequirement"; } // Save new requirement @RequestMapping(value = "/save", method = RequestMethod.POST) public String save(Requirement requirement){ rrepository.save(requirement); return "redirect:lista"; } // Delete requirement @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) public String deleteRequirement(@PathVariable("id") Long requirementId, Model model) { rrepository.deleteById(requirementId); return "redirect:../lista"; } // Edit requirement @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET) public String editRequirement(@PathVariable("id") Long requirementId, Model model) { model.addAttribute("requirement", rrepository.findById(requirementId)); model.addAttribute("types", trepository.findAll()); return "editrequirement"; } } <file_sep>package fi.haagahelia.postulo; import static org.assertj.core.api.Assertions.assertThat; import java.time.LocalDate; import java.util.List; //JUnit 5 tests with import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test; //import org.junit.Test and org.junit.runner.RunWith used with JUnit 4 //import org.junit.Test; //import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; //import org.springframework.test.context.junit4.SpringRunner; import fi.haagahelia.postulo.domain.User; import fi.haagahelia.postulo.domain.UserRepository; import fi.haagahelia.postulo.domain.Requirement; import fi.haagahelia.postulo.domain.RequirementRepository; import fi.haagahelia.postulo.domain.Type; import fi.haagahelia.postulo.domain.TypeRepository; /* * These tests works when database configurations has been stated directly in the application.properties * but fails if using eclipse environt variables like * spring.datasource.url=${SPRING_DATASOURCE_URL} * tested and verified that these tests works, but will replace the database configuration with the * environment variables */ @DataJpaTest // @AutoConfigureTestDatabase is needed to test with the real database instead of h2 @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) public class RequirementRepositoryTest { private static final Logger log = LoggerFactory.getLogger(PostuloApplication.class); @Autowired private RequirementRepository requirementRepository; @Autowired private TypeRepository typeRepository; @Autowired private UserRepository userRepository; // RequirementRepository tests @Test public void findByReqIdReturnsOwner() { log.info("Running FindByReqIdReturnsOwner"); List<Requirement> requirements = requirementRepository.findByReqid("foobar-0001"); assertThat(requirements).hasSize(1); assertThat(requirements.get(0).getOwner()).isEqualTo("<NAME>"); } @Test public void createNewRequirement() { log.info("Running createNewRequirement"); Requirement requirement = new Requirement("foobar-0003", typeRepository.findByName("Functional").get(0), "Sample requirement", "Yet another rationale", "Should Have", "Customer Foo", "<NAME>",LocalDate.of(2020, 11, 30)); requirementRepository.save(requirement); assertThat(requirement.getId()).isNotNull(); } @Test public void deleteRequirement() { log.info("Test delete a requirement"); List<Requirement> requirement = requirementRepository.findByReqid("foobar-0002"); if(requirement != null) { requirementRepository.deleteById(requirement.get(0).getId()); } } // TypeRepository tests @Test public void findByType() { log.info("Running findByType"); List<Type> types = typeRepository.findByName("Functional"); assertThat(types.get(0).getName()).isEqualTo("Functional"); } @Test public void createNewType() { log.info("test creating a new type"); Type type = new Type("Just Fiction"); typeRepository.save(type); assertThat(type.getTypeid()).isNotNull(); } // UserRepository tests @Test public void findByUser() { log.info("Running findByUser"); User users = userRepository.findByUsername("user"); assertThat(users.getRole()).isEqualTo("USER"); } @Test public void createNewUser() { log.info("Running createNewUser"); User user = new User("foobar", "$2a$10$Gdr0sij9l1OW.aqtlrkpC.UDQ91uh9tEL4bdmWhT/ZTixsdx57NL.", "foobar<EMAIL>", "USER"); userRepository.save(user); assertThat(user.getId()).isNotNull(); } @Test public void deleteUser() { log.info("delete user test"); User user = userRepository.findByUsername("johndoe"); log.info("test finding johndoe"); if(user != null) { userRepository.delete(user); } } }
a2897613313e154de83fcf787730eaa0bdf81713
[ "Markdown", "Java" ]
6
Java
h4nu/postulo
645dfd4b59f9aba2b0e31c81e6c4073a8bd6250d
205026d219c8f63d400cea49a18d600a274accfc
refs/heads/master
<repo_name>Shumaimnaeem/e-commerceApp<file_sep>/src/app/shared/services/cart.service.ts import { Injectable } from '@angular/core'; import { HttpClient} from '@angular/common/http'; import { ICart } from '../interface/cart'; @Injectable({ providedIn: 'root' }) export class CartService { constructor(private http: HttpClient) { } async getCartItems(): Promise<ICart[]>{ const cartItems: any = await this.http.get('https://61556a8093e3550017b089b8.mockapi.io/cart').toPromise(); const items: ICart[] = cartItems; return items; } async placeOrder(o:any){ return await this.http.post('https://61556a8093e3550017b089b8.mockapi.io/orders', o).toPromise(); } async deleteCart(id:string){ console.log("Id: ", id); const url = `https://61556a8093e3550017b089b8.mockapi.io/cart/${id}`; return await this.http.delete(url).toPromise(); } } <file_sep>/src/app/view-cart/view-cart.component.ts import { Component, OnInit , Input, NgModuleRef } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { UserService } from '../shared/services/user.service'; import { ActivatedRoute } from '@angular/router'; import {map} from 'rxjs/operators'; import { IUser } from '../shared/interface/user'; import { User } from '../shared/models/user'; import { CartService } from '../shared/services/cart.service'; import {NgbModal, ModalDismissReasons, NgbModalOptions} from '@ng-bootstrap/ng-bootstrap'; import { ToastrService } from 'ngx-toastr'; import { ProductService } from '../shared/services/product.service'; import { IProduct } from '../shared/interface/product'; import { ICart } from '../shared/interface/cart'; import { ViewReceiptComponent } from '../view-receipt/view-receipt.component'; @Component({ selector: 'app-view-cart', templateUrl: './view-cart.component.html', styleUrls: ['./view-cart.component.css'] }) export class ViewCartComponent implements OnInit { @Input() id :string =''; @Input() products: IProduct[] =[]; title : string = 'Your Cart' user : IUser= new User; cartProducts : ICart[] = [] ; amount= 0; productsLength =0; constructor(public activeModal: NgbActiveModal, private userService : UserService, private route : ActivatedRoute, private cartService: CartService, private modalService: NgbModal, private toasterService : ToastrService, private productService : ProductService) { } ngOnInit(){ this.productsLength = this.products.length; console.log("productsLength: ", this.productsLength); this.calculateAmount(); } calculateAmount(){ this.products.forEach((item:IProduct) => { console.log("Value: ", item); this.amount += +item.price; console.log("Amount: ", this.amount); }); } async viewFinalReceipt(){ await this.productService.addToCart({userId : this.id , products : this.products }) this.modalService.dismissAll(); const modalRef = this.modalService.open(ViewReceiptComponent, {backdrop: 'static'} ); modalRef.componentInstance.cartProducts = this.products; modalRef.componentInstance.totalAmount = this.amount; modalRef.componentInstance.userId = this.id; } deleteProduct(product:IProduct){ console.log("product: ", product); this.productsLength--; this.productService.setLatestValue(this.productsLength); this.products = this.products.filter((cartProduct) =>{ console.log("p:", cartProduct); return product.id !== cartProduct.id }) this.amount = this.amount - product.price; console.log("Products: ", this.products); } } <file_sep>/src/app/view-receipt/view-receipt.component.ts import { Component, OnInit , Input } from '@angular/core'; import { IUser } from '../shared/interface/user'; import { User } from '../shared/models/user'; import { ICart } from '../shared/interface/cart'; import {NgbModal, ModalDismissReasons, NgbModalOptions} from '@ng-bootstrap/ng-bootstrap'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { UserService } from '../shared/services/user.service'; import { ActivatedRoute, Router } from '@angular/router'; import { CartService } from '../shared/services/cart.service'; import { ToastrService } from 'ngx-toastr'; import { ProductService } from '../shared/services/product.service'; import { IProduct } from '../shared/interface/product'; import { NgxSpinnerService } from "ngx-spinner"; @Component({ selector: 'app-view-receipt', templateUrl: './view-receipt.component.html', styleUrls: ['./view-receipt.component.css'] }) export class ViewReceiptComponent implements OnInit { @Input() cartProducts :IProduct[] = []; @Input() totalAmount : number = 0; @Input() userId :string =''; title : string = 'Your Final Receipt' user : IUser= new User; cart :ICart[] =[]; cartLength = 0; constructor(public activeModal: NgbActiveModal, private userService : UserService, private router : Router, private cartService: CartService, private modalService: NgbModal, private toasterService : ToastrService, private productService : ProductService, private SpinnerService: NgxSpinnerService) { } async ngOnInit(){ // this.SpinnerService.show(); this.cart = await this.getCartItems(); // this.SpinnerService.hide(); this.cartLength = this.cart.length-1; } async placeOrder(){ const productIds:any= []; this.cartProducts.forEach((item:IProduct) => { console.log("Value: ", item); productIds.push(item.id); }); this.toasterService.success('Order Placed Successfully') // this.SpinnerService.show(); this.cartService.placeOrder({userId: this.userId , productIds : productIds, totalAmount: this.totalAmount}); this.productService.setLatestValue(0); this.modalService.dismissAll(); this.productService.setProducts(); await this.deleteCart(); this.router.navigate([`/viewOrders/${this.userId}`]) // this.SpinnerService.hide(); } async deleteCart(){ await this.cartService.deleteCart(this.cart[this.cartLength].id); } async getCartItems(){ const cartItems:ICart[] = await this.cartService.getCartItems(); console.log("cartItems: ", cartItems); return cartItems.filter((item:ICart)=>{ return item.userId == this.userId }); } } <file_sep>/src/app/shared/services/order.service.ts import { Injectable } from '@angular/core'; import { HttpClient} from '@angular/common/http'; import { Observable } from 'rxjs'; import { IOrder } from '../interface/order'; @Injectable({ providedIn: 'root' }) export class OrderService { constructor(private http: HttpClient) { } getAllOrders():Observable<IOrder[]>{ const orders: any = this.http.get('https://61556a8093e3550017b089b8.mockapi.io/orders'); const allOrders : Observable<IOrder[]> = orders; return allOrders; } async getOrderById(id:number): Promise<IOrder>{ const url = `https://61556a8093e3550017b089b8.mockapi.io/orders/${id}`; const order : any = await this.http.get(url).toPromise(); const returnOrder: Promise<IOrder> = order; return returnOrder; } } <file_sep>/src/app/auth/AuthService/auth.service.ts import { Injectable } from '@angular/core'; import { IUser } from 'src/app/shared/interface/user'; import { User } from 'src/app/shared/models/user'; import { UserService } from 'src/app/shared/services/user.service'; @Injectable({ providedIn: 'root' }) export class AuthService { user : IUser = new User; constructor(private userService : UserService) {} isAuthenticated(){ const userId = localStorage.getItem('User'); if(userId != null){ return true; } else{ return false; } } async getUserDetail(){ const userId = localStorage.getItem('User'); console.log("UserId: ", userId); if(userId != null){ const cu:any = await this.userService.getUser(+userId); this.user = cu; } return this.user; } async isUserSame(id:number){ const userId = localStorage.getItem('User'); if(userId){ if(+userId === id) return true; else return false; } else return false; } } <file_sep>/src/app/models/product.ts export class Product { id : string = ''; name: string = ''; category: string = ''; description: string = ''; price :number =0; imageUrl :string ='http://placeimg.com/300/200/tech/grayscale'; quantity : number =1; }<file_sep>/src/app/models/cart.ts import { Product } from "./product"; import { IProduct } from "../interface/product"; export class Cart{ id: string =''; userId : string = ''; products : IProduct = new Product(); }<file_sep>/src/app/auth/login/login.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; import {NgForm, FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; import { UserService } from '../../shared/services/user.service'; import { IUser } from '../../shared/interface/user'; import { User } from '../../shared/models/user'; import { map } from 'rxjs/operators'; import { Subscription } from 'rxjs'; import { AuthService } from '../AuthService/auth.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit, OnDestroy { users : IUser[] = []; subscriptions: Subscription[] = []; user : IUser= new User; userExist : boolean = true; form = this.fb.group({ "username": ["", Validators.required], "password": ["", Validators.required] }); constructor(private router : Router, private userService : UserService, private fb: FormBuilder, private authService : AuthService){ } async ngOnInit(){ const user:IUser = await this.authService.getUserDetail(); console.log("User: ", user); if(user){ this.router.navigate(['/home']); } } onSubmit() { console.log("form: ", this.form); const cUser = this.form.value console.log("cuser: ", cUser); this.subscriptions.push( this.userService.getUsers().pipe( map( (users: IUser[]) => { console.log("Users: ", users, cUser.username, cUser.password); return users.filter((user:IUser) => { console.log("U: ", user); return user.email === cUser.username && user.password === cUser.password} )} ), ).subscribe((user: IUser[] ) => { this.user = user[0] this.userService.user = this.user; console.log("user: ", user); if(this.user){ localStorage.setItem('User', this.user.id); this.router.navigate(['/home']); } else{ this.userExist = false; } }) ) } ngOnDestroy(){ if(!!this.subscriptions){ while(this.subscriptions.length > 0){ this.subscriptions.pop(); } } } } <file_sep>/src/app/shared/services/user.service.ts import { Injectable } from '@angular/core'; import { HttpClient} from '@angular/common/http'; import { IUser } from '../interface/user'; import { User } from '../models/user'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class UserService { user: IUser = new User; users : IUser[] = []; constructor(private http: HttpClient) { } async addUser(u: IUser){ console.log("User service: ", u); return await this.http.post('https://61556a8093e3550017b089b8.mockapi.io/user', u).toPromise(); } getUsers(): Observable<IUser[]>{ const users: any = this.http.get('https://61556a8093e3550017b089b8.mockapi.io/user'); const allUsers: Observable<IUser[]>= users; return allUsers; } async getUser(id:number){ const url = `https://61556a8093e3550017b089b8.mockapi.io/user/${id}`; return await this.http.get(url).toPromise(); } } <file_sep>/src/app/shared/models/order.ts export class Order { id : number = 0; userId: string = ''; productIds: [] = []; totalAmount :number =0; }<file_sep>/src/app/services/cart.service.ts import { Injectable } from '@angular/core'; import { HttpClient} from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class CartService { constructor(private http: HttpClient) { } async getCartItems(){ return await this.http.get('https://61556a8093e3550017b089b8.mockapi.io/cart').toPromise(); } async placeOrder(o:any){ return await this.http.post('https://61556a8093e3550017b089b8.mockapi.io/orders', o).toPromise(); } async deleteCart(id:string){ console.log("Id: ", id); const url = `https://61556a8093e3550017b089b8.mockapi.io/cart/${id}`; return await this.http.delete(url).toPromise(); } } <file_sep>/src/app/shared/header/header.component.ts import { Component, OnInit } from '@angular/core'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { Router } from '@angular/router'; import { User } from '../models/user'; import { ViewCartComponent } from 'src/app/cart/view-cart/view-cart.component'; import { ProductService } from '../services/product.service'; import { IProduct } from '../interface/product'; import { IUser } from '../interface/user'; import { UserService } from '../services/user.service'; import { AuthService } from 'src/app/auth/AuthService/auth.service'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) export class HeaderComponent implements OnInit { user : IUser = new User; productsList : IProduct[] =[] productsCount = 0; constructor( private modalService: NgbModal, private productService : ProductService, private router : Router, private userService : UserService, private authService : AuthService) { } async ngOnInit() { const loggedInUser:any = await this.authService.getUserDetail(); this.user = loggedInUser; console.log("header User: ", this.user); this.productService.productsList.subscribe((products: any)=> { this.productsList = products; console.log("Products List: ", this.productsList); }); this.productService.cartCount.subscribe((count)=>{ this.productsCount = count; console.log("PC: ", this.productsCount); }) } viewCart(){ const modalRef = this.modalService.open(ViewCartComponent, {backdrop: 'static'} ); modalRef.componentInstance.id = this.user.id; modalRef.componentInstance.products = this.productsList; } logout(){ localStorage.removeItem('User'); this.router.navigate(['/']); } } <file_sep>/src/app/home/home.component.ts import { Component, OnInit } from '@angular/core'; import { ProductService } from '../shared/services/product.service'; import { ActivatedRoute, Router } from '@angular/router'; import { UserService } from '../shared/services/user.service'; import { User } from '../shared/models/user'; import { IProduct } from '../shared/interface/product'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent { } <file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeModule } from './home/home.module'; import { AuthModule } from './auth/auth.module'; import { ProductModule } from './product/product.module'; const routes: Routes = [ { path:'', loadChildren:()=> import('./auth/auth.module').then((m: any) => {return m.AuthModule})}, { path:'signup', loadChildren:()=> import('./auth/auth.module').then((m: any) => {return m.AuthModule})}, { path: 'home', loadChildren:()=> import('./home/home.module').then((m: any) => {return m.HomeModule}) }, { path:'addProduct',loadChildren:()=> import('./product/product.module').then((m: any) => {return m.ProductModule})}, { path: 'viewOrders/:id', loadChildren: () => import('./home/home.module').then((m:any) => {return m.HomeModule})}, ]; @NgModule({ imports: [RouterModule.forRoot(routes), HomeModule, AuthModule, ProductModule], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/src/app/services/order.service.ts import { Injectable } from '@angular/core'; import { HttpClient} from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class OrderService { constructor(private http: HttpClient) { } getAllOrders(){ return this.http.get('https://61556a8093e3550017b089b8.mockapi.io/orders'); } async getOrderById(id:number){ const url = `https://61556a8093e3550017b089b8.mockapi.io/orders/${id}`; return await this.http.get(url).toPromise(); } } <file_sep>/src/app/product/add-product/add-product.component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Product } from '../../shared/models/product'; import { ProductService } from '../../shared/services/product.service'; @Component({ selector: 'app-add-product', templateUrl: './add-product.component.html', styleUrls: ['./add-product.component.css'] }) export class AddProductComponent implements OnInit { product : Product = new Product; categories : string[] = ['Mobile', 'Laptop', 'Mobile Accessories'] submitted : boolean = false; constructor(private productService : ProductService, private router: Router) { } ngOnInit(): void { } onSubmit(){ console.log("Product: ", this.product); this.productService.addProduct(this.product); this.submitted = true; this.router.navigate(['./home']) } onFileChange(event: any){ console.log("Event: ", this.product.name); console.log("file: ", event.target.files[0]); this.product.image = event.target.files[0].name; console.log("image: ", this.product.image); } goBack(){ return this.router.navigate(['/home']); } } <file_sep>/src/app/home/view-orders/view-orders.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Subscription } from 'rxjs'; import { map } from 'rxjs/operators'; import { IProduct } from '../../shared/interface/product'; import { IOrder } from '../../shared/interface/order'; import { OrderService } from '../../shared/services/order.service'; import { ProductService } from '../../shared/services/product.service'; import { AuthService } from 'src/app/auth/AuthService/auth.service'; import { NgxSpinnerService } from "ngx-spinner"; interface IOrderAndProducts { order: string, products : IProduct[] amount : number, date : Date } @Component({ selector: 'app-view-orders', templateUrl: './view-orders.component.html', styleUrls: ['./view-orders.component.css'] }) export class ViewOrdersComponent implements OnInit, OnDestroy { orders: IOrder[] = []; products : IProduct[] =[]; productsByOrder: IProduct[] =[]; orderWithProducts : IOrderAndProducts[] = []; subscriptions: Subscription[] = []; isUserSame: Boolean = false; constructor(private orderService : OrderService, private route: ActivatedRoute, private productService :ProductService, private router :Router, private authService : AuthService, private SpinnerService: NgxSpinnerService) { } async ngOnInit(){ const id = this.route.snapshot.paramMap.get('id'); console.log("Id: ", id); if(id){ this.isUserSame = await this.authService.isUserSame(+id); console.log("isUserSame: ", this.isUserSame ); } this.productsByOrder = await this.productService.getProducts(); this.subscriptions.push( this.orderService.getAllOrders().pipe( map((orders: IOrder[])=>{ return orders.filter((order : IOrder) => { return order.userId == id }) }) ). subscribe((orders:IOrder[]) => { this.orders = orders; console.log("All Orders: ", this.orders); if(this.isUserSame ){ this.getOrders(); } }) ) } async getOrders(){ const allOrders = this.orders.map(async order => { const orderAndProducts: IOrderAndProducts | any = {}; orderAndProducts.order = order.id; orderAndProducts.amount = order.totalAmount; orderAndProducts.date = order.createdAt const products = await this.getProductsByOrderId(order.productIds); console.log("prod: ", products); orderAndProducts.products = products; return orderAndProducts; }); this.orderWithProducts = await Promise.all(allOrders); console.log("Order And Products: ", this.orderWithProducts); } async getProductsByOrderId(ids:any){ console.log("ids: ", ids); console.log("productsByOrder: ", this.productsByOrder); return this.productsByOrder.filter((product:IProduct)=>{ return ids.flat(1).includes(product.id); }) } ngOnDestroy(){ if(!!this.subscriptions){ while(this.subscriptions.length > 0){ this.subscriptions.pop(); } } } } <file_sep>/src/app/product/all-products/all-products.component.ts import { Component, OnInit } from '@angular/core'; import { ProductService } from '../../shared/services/product.service'; import { ActivatedRoute, Router } from '@angular/router'; import { UserService } from '../../shared/services/user.service'; import { User } from '../../shared/models/user'; import { IProduct } from '../../shared/interface/product'; import { ViewCartComponent } from 'src/app/cart/view-cart/view-cart.component'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrService } from 'ngx-toastr'; import { DomSanitizer, SafeUrl } from '@angular/platform-browser'; import { IUser } from 'src/app/shared/interface/user'; import { AuthService } from 'src/app/auth/AuthService/auth.service'; @Component({ selector: 'app-all-products', templateUrl: './all-products.component.html', styleUrls: ['./all-products.component.css'] }) export class AllProductsComponent implements OnInit { products : IProduct[]= []; user : IUser = new User; productsCount = 0; count =0; clicked = false; productsList : IProduct[] =[]; constructor(private productService : ProductService, private modalService: NgbModal, private toasterService: ToastrService, private router : Router, private authService : AuthService) { } async ngOnInit(){ this.user = await this.authService.getUserDetail(); console.log("User: ", this.user); const products:any = await this.productService.getProducts(); this.products = products; console.log("products: ", this.products); } addToCart(product: IProduct){ product.quantity = 0; this.productService.addProductsToCart(product); this.productsList.push(product); console.log("Products: ", product); this.count++; this.productService.setLatestValue(this.count); this.toasterService.success('Product has been added to Cart') } viewCart(){ const modalRef = this.modalService.open(ViewCartComponent, {backdrop: 'static'} ); modalRef.componentInstance.id = this.user.id; modalRef.componentInstance.products = this.productsList; } logout(){ localStorage.removeItem('User'); this.router.navigate(['/']); } getUrl(product:IProduct){ // console.log("Url", '/assets/'+product.id+'/'+product.image); return '/assets/'+product.id+'/'+product.image; } } <file_sep>/src/app/home/home.module.ts import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { HomeComponent } from './home.component'; import { RouterModule, Routes } from '@angular/router'; import { CommonModule } from '@angular/common'; import { ViewOrdersComponent } from './view-orders/view-orders.component'; import { AuthGuard } from '../auth/AuthService/auth.guard'; import { HeaderComponent } from '../shared/header/header.component'; import { AllProductsComponent } from '../product/all-products/all-products.component'; import { NgxSpinnerModule } from "ngx-spinner"; const routes : Routes = [ { path: 'viewOrders/:id', component: ViewOrdersComponent, }, { path:'home', component: HomeComponent, canActivate:[AuthGuard]}, ]; @NgModule({ declarations: [ HomeComponent, ViewOrdersComponent, HeaderComponent, AllProductsComponent ], imports: [ CommonModule, FormsModule, ReactiveFormsModule, NgbModule, ToastrModule.forRoot({ positionClass :'toast-bottom-right' }), NgxSpinnerModule, RouterModule.forChild(routes) ], providers: [], exports: [HomeComponent,ViewOrdersComponent], }) export class HomeModule { } <file_sep>/src/app/shared/services/product.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders} from '@angular/common/http'; import { BehaviorSubject, Subject } from 'rxjs'; import { IProduct } from '../interface/product'; import { Product } from '../models/product'; @Injectable({ providedIn: 'root' }) export class ProductService { public productCount = new BehaviorSubject<any>(0); public cartCount = this.productCount.asObservable(); public productsArray = new Subject<IProduct[]>(); public productsList = this.productsArray.asObservable(); products : IProduct[] =[]; constructor(private http : HttpClient) { } async addProduct(p: any){ console.log("P service: ", p); return await this.http.post('https://61556a8093e3550017b089b8.mockapi.io/product', p).toPromise(); } async getProducts():Promise<IProduct[]>{ const products: any = await this.http.get('https://61556a8093e3550017b089b8.mockapi.io/product').toPromise(); const allProducts : IProduct[] = products; return allProducts; } async getProductById(id:number): Promise<IProduct>{ const url = `https://61556a8093e3550017b089b8.mockapi.io/product/${id}`; const product: any = await this.http.get(url).toPromise(); const productById : IProduct = product; return productById; } async addToCart(productAndUserId : any){ console.log("productAndUserId: ", productAndUserId); return await this.http.post('https://61556a8093e3550017b089b8.mockapi.io/cart', productAndUserId).toPromise(); } setLatestValue(value : number) { console.log("Val: ", value); this.productCount.next(value); } addProductsToCart(product : Product){ this.products.push(product); this.productsArray.next(this.products); } setProducts(){ console.log("setProducts"); this.products= []; this.productsArray.next(this.products); console.log("productsArray: ", this.productsArray); } } <file_sep>/src/app/product/product.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { AllProductsComponent } from './all-products/all-products.component'; import { AddProductComponent } from './add-product/add-product.component'; import { FormsModule,ReactiveFormsModule } from '@angular/forms'; import { RouterModule, Routes } from '@angular/router'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; const routes: Routes = [ { path:'addProduct',component: AddProductComponent}, ]; @NgModule({ declarations: [ AddProductComponent, ], imports: [ CommonModule, FormsModule, ReactiveFormsModule, NgbModule, RouterModule.forChild(routes) ], exports: [ AddProductComponent, ] }) export class ProductModule { } <file_sep>/src/app/signup/signup.component.ts import { Component, OnInit } from '@angular/core'; import { FormControl , ReactiveFormsModule } from '@angular/forms'; import {NgForm} from '@angular/forms'; import { UserService } from '../services/user.service'; import { IUser } from '../interface/user'; import { User } from '../models/user'; import { FormGroup } from '@angular/forms'; import { Router } from '@angular/router'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: ['./signup.component.css'] }) export class SignupComponent implements OnInit { signUpForm = new FormGroup({ name: new FormControl(''), email: new FormControl(''), password: new FormControl(''), role: new FormControl(''), }); roles:any []= ['','Admin', 'Normal User']; user : IUser = new User; constructor(private userService : UserService, private router : Router) {} ngOnInit(): void { } onSubmit(){ console.log("Sign Up Creds: ", this.signUpForm.value); this.userService.addUser(this.signUpForm.value) this.router.navigate(['./login']) } } <file_sep>/src/app/shared/interface/file.ts export interface IFile{ src : string; file : File; name : string }<file_sep>/src/app/shared/interface/order.ts export interface IOrder { id : number; userId: string; productIds: []; totalAmount :number; createdAt : Date }
26ae4db89b4e28b9f8dcb641c24d0276733c0a3a
[ "TypeScript" ]
24
TypeScript
Shumaimnaeem/e-commerceApp
e5b56d24689e9b9137135026a792e02f812547c2
3127b0c6f3cd651f4a0aadcdbdbd115f0cb19b16
refs/heads/master
<repo_name>Dev01-5/Dev01-5<file_sep>/RemoteControl/src/newRemoteControl/Command/Radio/PowerRadioOffCommand.java package newRemoteControl.Command.Radio; import newRemoteControl.interfaces.Command; public class PowerRadioOffCommand implements Command { PowerRadio power; public PowerRadioOffCommand(PowerRadio power) { this.power = power; } public void execute() { power.off(); } } <file_sep>/.metadata/.plugins/org.eclipse.core.resources/.history/8c/30d74aa70940001311ed97ab3c24bd4a package newRemoteControl.Command.Lamp; public class LightOne { String state; public void on(){ state = "Lamp 1 staat aan!!"; } public void off(){ state = "Lamp 1 staat uit!!"; } public String getState() { return state; } } <file_sep>/RemoteControl/src/newRemoteControl/Controllers/TvRemoteControlListeners.java package newRemoteControl.Controllers; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JTextArea; import newRemoteControl.Command.Radio.PowerTv; import newRemoteControl.Command.Radio.PowerTvOffCommand; import newRemoteControl.Command.Radio.PowerTvOnCommand; import newRemoteControl.View.FrameView; import newRemoteControl.concretes.Radio.RadioRemoteControlFactory; import newRemoteControl.concretes.Tv.TvRemoteControl; import newRemoteControl.concretes.Tv.TvRemoteControlFactory; import newRemoteControl.interfaces.*; public class TvRemoteControlListeners { private ActionListener listener; private FrameView view; private TvRemoteControlFactory model; private TvRemoteControl remoteControl; private ITv iTv; private JButton TvOn, TvOff, TvMinOne, TvPlusOne; private JTextArea alertChannelStatus, alertDeviceStatus; public TvRemoteControlListeners(FrameView view, TvRemoteControlFactory model, ITv iTv){ this.view = view; this.iTv = iTv; remoteControl = (TvRemoteControl) model.getRemoteControl(); TvOn = view.getPowerOn(); TvOff = view.getPowerOff(); TvPlusOne = view.getChannelPlusOne(); TvMinOne = view.getChannelMinOne(); alertChannelStatus = view.getAlertChannelStatus(); alertDeviceStatus = view.getAlertDeviceStatus(); buttonListener(); TvPlusOne.addActionListener(listener); TvMinOne.addActionListener(listener); TvOn.addActionListener(listener); TvOff.addActionListener(listener); } public void buttonListener() { listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource().equals(TvPlusOne)) { remoteControl.setChannelByButton("+"); alertChannelStatus.setText(remoteControl.getState()); } if (e.getSource().equals(TvMinOne)) { remoteControl.setChannelByButton("-"); alertChannelStatus.setText(remoteControl.getState()); } if (e.getSource().equals(TvOn)) { PowerTv power = new PowerTv(iTv); PowerTvOnCommand powerOn = new PowerTvOnCommand(power); remoteControl.setCommandPowerOn(powerOn); remoteControl.powerOnWasPressed(); alertDeviceStatus.setText(power.getState()); } if (e.getSource().equals(TvOff)) { PowerTv power = new PowerTv(iTv); PowerTvOffCommand powerOff = new PowerTvOffCommand(power); remoteControl.setCommandPowerOff(powerOff); remoteControl.powerOffWasPressed(); alertDeviceStatus.setText(power.getState()); } } }; } } <file_sep>/RemoteControl/src/newRemoteControl/Command/Radio/PowerRadio.java package newRemoteControl.Command.Radio; import newRemoteControl.interfaces.IRadio; public class PowerRadio { String state; IRadio iRadio; public PowerRadio(IRadio iRadio) { this.iRadio = iRadio; } public void on(){ state = "Apparaat staat aan!!"; iRadio.On(); } public void off(){ state = "Apparaat staat uit!!"; iRadio.Off(); } public String getState() { return state; } } <file_sep>/RemoteControl/src/newRemoteControl/Command/Radio/PowerRadioOnCommand.java package newRemoteControl.Command.Radio; import newRemoteControl.interfaces.*; public class PowerRadioOnCommand implements Command { PowerRadio power; public PowerRadioOnCommand(PowerRadio power) { this.power = power; } public void execute() { power.on(); } } <file_sep>/RemoteControl/src/newRemoteControl/concretes/Tv/TvRemoteControl.java package newRemoteControl.concretes.Tv; import newRemoteControl.abstracts.ATvRemoteControl; import newRemoteControl.interfaces.Command; import newRemoteControl.interfaces.ITv; public class TvRemoteControl extends ATvRemoteControl{ Command slot; Command slot2; public TvRemoteControl(ITv iTv) { super(iTv); } public void setChannelByButton(String type) { setChannel(type); } public void setPowerOn(){ On(); } public void setPowerOff(){ Off(); } public void setCommandPowerOn(Command command) { slot = command; } public void powerOnWasPressed() { slot.execute(); } public void setCommandPowerOff(Command command) { slot2 = command; } public void powerOffWasPressed() { slot2.execute(); } } <file_sep>/RemoteControl/src/newRemoteControl/concretes/Lamp/LampRemoteControl.java package newRemoteControl.concretes.Lamp; import newRemoteControl.abstracts.ARemoteControl; import newRemoteControl.interfaces.Command; public class LampRemoteControl extends ARemoteControl{ Command slot; Command slot2; Command slot3; Command slot4; public void setCommandOneOn(Command command) { slot = command; } public void lampOneOnWasPressed() { slot.execute(); } public void setCommandOneOff(Command command) { slot2 = command; } public void lampOneOffWasPressed() { slot2.execute(); } //------------------------------------------------------------------ public void setCommandTwoOn(Command command) { slot3 = command; } public void lampTwoOnWasPressed() { slot3.execute(); } public void setCommandTwoOff(Command command) { slot4 = command; } public void lampTwoOffWasPressed() { slot4.execute(); } } <file_sep>/RemoteControl/src/newRemoteControl/Command/Radio/PowerTvOnCommand.java package newRemoteControl.Command.Radio; import newRemoteControl.interfaces.Command; public class PowerTvOnCommand implements Command { PowerTv power; public PowerTvOnCommand(PowerTv power) { this.power = power; } public void execute() { power.on(); } } <file_sep>/README.md Dev01-5 ======= Repo voor <file_sep>/RemoteControl/src/newRemoteControl/Main.java package newRemoteControl; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JButton; import javax.swing.JFrame; import newRemoteControl.concretes.Lamp.LampRemoteControlFactory; import newRemoteControl.concretes.Radio.RadioRemoteControlFactory; import newRemoteControl.concretes.Tv.TvRemoteControlFactory; import newRemoteControl.interfaces.iRemoteControlFactory; import newRemoteControl.View.FrameView; public class Main { private static JButton btnRadioRemote, btnTvRemote, btnLampRemote; private static JFrame tvRemoteWindow, radioRemoteWindow, lampRemoteWindow; private enum RemoteState {SHOW, CLOSED}; private static RemoteState tvWindow = RemoteState.CLOSED, radioWindow = RemoteState.CLOSED, lampWindow = RemoteState.CLOSED; public static void main(String[] args) { buildMain(); } public static void buildMain() { JFrame frame = new JFrame("Main Menu"); frame.setLocation(0, 0); frame.setSize(300, 250); frame.getContentPane().setBackground(Color.BLACK); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new GridLayout(2,2)); btnRadioRemote = new JButton("Open radio remote"); btnTvRemote = new JButton("Open tv remote"); btnLampRemote = new JButton("Open lamp remote"); btnRadioRemote.addActionListener(buttonListener()); btnTvRemote.addActionListener(buttonListener()); btnLampRemote.addActionListener(buttonListener()); frame.add(btnRadioRemote); frame.add(btnTvRemote); frame.add(btnLampRemote); frame.setVisible(true); } public static JFrame buildRemote(iRemoteControlFactory factory) { FrameView remote = factory.createRemoteControl(); remote.addWindowListener(windowListener()); return remote; } public static ActionListener buttonListener() { return new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if ((e.getSource() == btnTvRemote) && (tvWindow.equals(RemoteState.CLOSED))) { tvRemoteWindow = buildRemote(new TvRemoteControlFactory()); tvWindow = RemoteState.SHOW; } if ((e.getSource() == btnRadioRemote && (radioWindow.equals(RemoteState.CLOSED)))) { radioRemoteWindow = buildRemote(new RadioRemoteControlFactory()); radioWindow = RemoteState.SHOW; } if ((e.getSource() == btnLampRemote && (lampWindow.equals(RemoteState.CLOSED)))) { lampRemoteWindow = buildRemote(new LampRemoteControlFactory()); lampWindow = RemoteState.SHOW; } } }; } public static WindowListener windowListener() { return new WindowListener() { @Override public void windowOpened(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowIconified(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowDeiconified(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowDeactivated(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowClosing(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowClosed(WindowEvent e) { // TODO Auto-generated method stub if (e.getSource().equals(tvRemoteWindow)) tvWindow = RemoteState.CLOSED; if (e.getSource().equals(radioRemoteWindow)) radioWindow = RemoteState.CLOSED; if (e.getSource().equals(lampRemoteWindow)) lampWindow = RemoteState.CLOSED; } @Override public void windowActivated(WindowEvent e) { // TODO Auto-generated method stub } }; } } <file_sep>/RemoteControl/src/newRemoteControl/concretes/Radio/RadioTypeOne.java package newRemoteControl.concretes.Radio; import newRemoteControl.interfaces.IRadio; public class RadioTypeOne implements IRadio { private String state; private int channel = 0; private boolean power = false; @Override public void On() { power = true; } @Override public void Off() { power = false; } @Override public void changeChannel(String type) { if (power){ if (type.equals("+")) this.channel++; else{ if (channel != 0) this.channel--; } } state = "Radio Type One is on channel: " + this.channel; } @Override public String getState() { return state; } } <file_sep>/.metadata/.plugins/org.eclipse.core.resources/.history/79/802949a70940001311ed97ab3c24bd4a package newRemoteControl.Command.Lamp; import newRemoteControl.interfaces.Command; public class LightTwoOffCommand implements Command { LightTwo light; public LightTwoOffCommand(LightTwo light) { this.light = light; } public void execute() { light.off(); } } <file_sep>/RemoteControl/src/newRemoteControl/concretes/Tv/TvRemoteControlFactory.java package newRemoteControl.concretes.Tv; import java.awt.Color; import javax.swing.JButton; import javax.swing.JTextArea; import newRemoteControl.Controllers.RadioRemoteControlListeners; import newRemoteControl.Controllers.TvRemoteControlListeners; import newRemoteControl.abstracts.ARemoteControl; import newRemoteControl.abstracts.aRemoteControlFactory; import newRemoteControl.interfaces.ITv; import newRemoteControl.View.*; public class TvRemoteControlFactory extends aRemoteControlFactory{ private JButton TvPlusOne, TvMinOne, TvOn, TvOff; private JTextArea alertDeviceStatus, alertChannelStatus; @Override public FrameView createRemoteControl() { ITv iTv = new TvTypeOne(); remoteControl = new TvRemoteControl(iTv); remoteControl = ((TvRemoteControl) remoteControl); remoteControl.setWindowSize(FrameView.Size.MEDIUM); remoteControl.setWindowPosition(FrameView.Position.RIGHTTOP); remoteControl.setWindowBackground(Color.BLACK); FrameView frameView = new FrameView(remoteControl); frameView.addButton(FrameView.Buttons.POWERON); frameView.addButton(FrameView.Buttons.POWEROFF); frameView.addButton(FrameView.Buttons.SETCHANNEL); frameView.addTextField(FrameView.TextFields.DEVICEPOWERALERT); frameView.addTextField(FrameView.TextFields.CHANGECHANNELALERT); frameView.buildView(); new TvRemoteControlListeners(frameView, this, iTv); return frameView; } public JTextArea getAlertDeviceStatus() { return alertDeviceStatus; } public JTextArea getAlertChannelStatus() { return alertChannelStatus; } public JButton getTvPlusOne() { return TvPlusOne; } public JButton getTvMinOne() { return TvMinOne; } public JButton getTvOn() { return TvOn; } public JButton getTvOff() { return TvOff; } }
4ca2e1acb081aedfc290d4cd076c8401e6a58f2d
[ "Markdown", "Java" ]
13
Java
Dev01-5/Dev01-5
1c24e5ab2304178fbc7e46459adf56f0f3f0916b
a8c8c92c19232be705a49a192aada92ec42f7523
refs/heads/main
<repo_name>islimakkaya/NumberGuessingGame<file_sep>/README.md # NumberGuessingGame 🔢003-NumberGuessingGame: It is a number guessing game: every time when starting this app, there will be a random number without the user’s knowledge in the background (private) and 100 trials. In this project, it is aimed to control the inputs: If the user 1️⃣ Guesses the wrong number, the test number (trial) decreases. Also, if the user guesses a smaller or a bigger number, a text will appear depends on it. 2️⃣ Does not give any input and press “Tahmin Et” button, trial will not change and a warning text will appear. 3️⃣ Guesses the correct number, input will be disabled, a winning text appears with the score. 4️⃣ Does not guess the correct number and the test number (trial) is 0, input will be disabled and a “failed” message will appear. 🔮In addition, input keyboard will be resized by android:windowSoftInputMode="adjustResize" code line in AndroidManifest. 🔨You can download and build this project on Android Studio. The project's SDK is API 22: Android 5.1. Therefore, you must run the app on the virtual devices that have minimum API level 22. <file_sep>/003-NumberGuessingGame/app/src/main/java/org/islimakkaya/samples/application/numberguessinggame/MainActivity.kt package org.islimakkaya.samples.application.numberguessinggame import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_main.* import org.islimakkaya.samples.application.numberguessinggame.databinding.ActivityMainBinding import kotlin.random.Random class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private var randomNum = 0 private var trial = 100 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) randomNum = Random.nextInt(1, 101) setScoreText(trial) binding.buttonControl.setOnClickListener { if(trial == 0) { setFailedMessage() disableInput() } else { onButtonControlClicked() } } } private fun onButtonControlClicked() { val num = guessNum() if(num.isEmpty()) { binding.textInputEditNumber.error = getString(R.string.input_error_message) return } else playRandomNumGame(num.toInt()) } private fun setFailedMessage() { binding.textMessage.text = getString(R.string.fail_message) binding.textScore.text = null } private fun setScoreText(trial: Int) { binding.textScore.text = getString(R.string.score_message, trial) } private fun disableInput() { binding.textInputEditNumber.isEnabled = false binding.buttonControl.isEnabled = false } private fun guessNum() : String { return binding.textInputEditNumber.text.toString() } private fun playRandomNumGame(num: Int) { when { num == randomNum -> { binding.textMessage.text = getString(R.string.win_message, trial) binding.textScore.text = null disableInput() } num < randomNum -> { trial-- binding.textMessage.text = getString(R.string.biggernum_message) setScoreText(trial) binding.textInputEditNumber.setText("") } else -> { trial-- binding.textMessage.text = getString(R.string.smallernum_message) setScoreText(trial) binding.textInputEditNumber.setText("") } } } }
5b9a3834eeb8b659af5413f47ededb6f43d89966
[ "Markdown", "Kotlin" ]
2
Markdown
islimakkaya/NumberGuessingGame
b911d2f64c269a9cf61ec77c45f9d08197e58e7e
d3694518ec81f54301c01e4368f0be33bc95be74
refs/heads/master
<file_sep># React-Native-Hesap-Makinesi This is my first react-native app! CALCULATOR Please check codes and comment my mistakes :) <file_sep>rootProject.name = 'uyg3' include ':app' <file_sep>import {StyleSheet} from 'react-native'; export default styles = StyleSheet.create({ container: { flex: 1, backgroundColor:'#414e63' }, //Cevap - Textbox Stil cevap:{ flex:1, padding:5, backgroundColor:'#a4bfb7', }, cvptext:{ flex:1, borderRadius:10, fontWeight:'bold', fontSize:30, textAlign:'right', textTransform:'uppercase', }, //Cevap Alanı Stilleri cvpalani:{ flex:1, backgroundColor:'#a4bfb7', padding:10, justifyContent:'center', alignItems:"flex-end", borderBottomWidth:3, borderColor:'#000', }, cvpalanitext:{ textAlign:'right', fontWeight:'bold', fontSize:25, opacity:0.5, color:'#646a72' }, //Cevap Alanı Stilleri Sonu //Tuslar Stil tuslar:{ flex:6, padding:5, flexDirection:'row', }, //Satırlar Stil stn1:{ flex:5, }, stn2:{ flex:2, }, stn1str:{ flex:1, flexDirection:'row', }, stn2silme:{ flex:1 }, stn2str:{ flex:3, }, stn2str1:{ flex:1, }, //BUTONLAR STİL btn:{ padding:10, flex:1, margin:5, alignItems:'center', justifyContent:'center', borderRadius:30, backgroundColor:'#ebf2cb', shadowColor: '#fff', shadowOffset:{ width: 5, height: 5, }, shadowOpacity: 1, borderWidth:3, borderColor:'#000' }, text:{ fontSize:25, fontWeight:'bold', }, islemrenk:{ backgroundColor:"#bec8ce" }, silmerenk:{ backgroundColor:"#e20003", }, silmeyazirenk:{ color:'#fff', fontSize:40, }, esittirrenk:{ backgroundColor:"#301c1c" }, esittiryazirenk:{ color:'#fff' }, });
1b39d56517046910ebd16d7be6514815e7e17f15
[ "Markdown", "JavaScript", "Gradle" ]
3
Markdown
omerdurmaz2/React-Native-Calculator
95b74ada8e08b5139e2b4963488512dc90aeaf8c
f99b2a56ff65bedfa9ff2aefa453f8c2879bb731
refs/heads/main
<file_sep>from csv import reader, writer, QUOTE_ALL skips = ['===>', '____', 'F3=E', 'UPDA', ] cnt = 0 refs = {} csvfile = open('data_parsed.csv', 'w', newline='') writer = writer(csvfile, quoting=QUOTE_ALL) writer.writerow(['no', 'code', 'description', 'function', 'authorization']) with open('data.csv', 'r') as read_obj: try: print('starting...') csv_reader = reader(read_obj) for words in csv_reader: cnt += 1 # remove empty fields words = list(filter(lambda x: len(x.strip())!= 0, words)) # skip irrelevant lines if words[0][:4] in skips: continue rl = len(words) # extract code and description if words[0] == 'RUN DATE:': code = -9999 print(code) continue if code == -9999: code = words[1] description = words[2] bRefs = True bLog = False print('code: %s, desc: %s' % (code, description)) continue if bRefs: if rl == 1 or rl == 3: si = words[rl-1].find(' ') if words[rl-1][:si].isnumeric(): refs[words[rl-1][:si]] = words[rl-1][si+1:] if rl >= 2: refs[words[0]] = words[1] print(refs) # extracting logs if words[0] == 'Selection or command': bRefs = False bLog = True continue # out put result here.... if bLog: if words[0].isnumeric(): no = words[0] print('no:%s' % no) continue if words[0][:4]=='AUTH': line = ' '.join(words) line=line[line.find(' ')+1:] permissions = line.split(' ') print('merged line:%s' % line) print(permissions) for permission in permissions: writer.writerow([no, code, description, refs[no], permission]) except Exception as ex: print('Exception on row# %d' % cnt) print(words) print(ex) else: print('Completed with on error: %d lines were read:' % cnt) csvfile.close()
8c59c4f640bf814e383eff15bc03f7515aef1e98
[ "Python" ]
1
Python
justinzh/HPTrial
fa7bfdc83515489a8bde3c90cbee45e52fc2b092
0e7a9ec7207570a4d7bb41a1d0350a2a5e7ad70f
refs/heads/master
<repo_name>lightsuner/education<file_sep>/IIT/Course 2/TI/lab_1/TI lab1/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace TI_lab1 { public partial class Form1 : Form { Monoalphabetic mo = new Monoalphabetic(); string text = ""; Stream myStream = null; string al = "etaoinsrhldcumfpgwybvkxjqz"; public Form1() { InitializeComponent(); } private void openBtn_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { try { if ((myStream = openFileDialog.OpenFile()) != null) { using (myStream) { text = System.IO.File.ReadAllText(openFileDialog.FileName, Encoding.Default); textBox1.Text = text; keyTextBox.Enabled = true; scramblerBtn.Enabled = true; } } } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } } private void scramblerBtn_Click(object sender, EventArgs e) { decoderBar.Value = 0; decoderBar.Maximum = text.Length; textBox1.Text = ""; for (int i = 0; i < text.Length; i++) { textBox1.Text += mo.Scrambler(text[i], Convert.ToInt32(keyTextBox.Text)); decoderBar.Value += 1; } text = textBox1.Text; decoderBtn.Enabled = true; System.IO.File.WriteAllText(@"decoderText.txt", text); //MessageBox.Show(Convert.ToString(mo.Analyze(text))); } private void decoderBtn_Click(object sender, EventArgs e) { decoderBar.Value = 0; decoderBar.Maximum = text.Length; textBox1.Text = ""; for (int i = 0; i < text.Length; i++) { textBox1.Text += mo.Decoder(text[i], Convert.ToInt32(keyTextBox.Text)); decoderBar.Value += 1; } text = textBox1.Text; } private void statBtn_Click(object sender, EventArgs e) { bool flag = false; int ind = 0, key = 0; char c = mo.Analyze(text); decoderBar.Value = 0; decoderBar.Maximum = text.Length; while (!flag) { textBox1.Text = ""; key = Math.Abs(al[ind] - c); for (int i = 0; i < text.Length; i++) { textBox1.Text += mo.Decoder(text[i], key); decoderBar.Value += 1; } var result = MessageBox.Show("Правильно?", "Подтверждение", MessageBoxButtons.OKCancel); if (result == System.Windows.Forms.DialogResult.OK) { text = textBox1.Text; MessageBox.Show("Ключ - " + key); flag = true; ind = 0; break; } else { if (ind < 27) { key = 0; ind++; } else { flag = true; ind = 0; break; } } } } } } <file_sep>/IIT/Course 2/OOP/lab_2/lab_2/student.h // // student.h // lab_2 // // Created by <NAME> on 25.04.15. // Copyright (c) 2015 Alex. All rights reserved. // #ifndef __lab_2__student__ #define __lab_2__student__ #include <stdio.h> #include <string> class Student { private: std::string firstName; std::string lastName; std::string phoneNumber; public: Student(const char *, const char *, const char *); std::string GetFirstName(); std::string GetLastName(); std::string GetPhoneNumber(); }; #endif /* defined(__lab_2__student__) */ <file_sep>/IIT/Course 2/OOP/lab_4/lab_4/main.cpp // // main.cpp // lab_4 // // Created by <NAME> on 29.04.15. // Copyright (c) 2015 Alex. All rights reserved. // #include <iostream> #include <string> #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ using namespace std; class Point { private: int x; int y; public: Point(){}; Point(int x, int y) { this->x = x; this->y = y; }; int GetX() { return x; }; int GetY() { return y; }; void Print() { cout << "x: " << x << ", y: " << y << endl; }; }; class TransparentTriangle { protected: Point a, b, c; public: TransparentTriangle(){}; TransparentTriangle(Point a, Point b, Point c) { this->a = a; this->b = b; this->c = c; }; void Print() { cout << "Point 1 - "; a.Print(); cout << "Point 2- "; b.Print(); cout << "Point 3 - "; c.Print(); }; }; class ColoredTriangle : public TransparentTriangle { protected: string color; public: ColoredTriangle(Point a, Point b, Point c, string color) : TransparentTriangle(a, b, c) { this->color = color; }; void Print() { TransparentTriangle::Print(); cout << "Color: " << color << endl; }; }; class StrokeTriangle : public TransparentTriangle { protected: string color; int size; public: StrokeTriangle(Point a, Point b, Point c, string color, int size) : TransparentTriangle(a, b, c) { this->color = color; this->size = size; }; void Print() { TransparentTriangle::Print(); cout << "Color: " << color << endl; cout << "Size: " << size << endl; }; }; class Weapon { protected: int attack; int defence; public: Weapon(){}; Weapon(int attack, int defence) { this->attack = attack; this->defence = defence; }; virtual int Attack() { return rand() % attack; }; virtual int Defence() { return rand() % defence; }; virtual int Hit(Weapon & weapon) { return weapon.Defend(Attack()); }; virtual int Defend(int attakPoint) { int damage = attakPoint - Defence(); if (damage > 0) return damage; return 0; } }; class Shield : public Weapon { public: Shield(int defence) { this->attack = 0; this->defence = defence; }; int Attack() { return attack; }; }; class Sword : public Weapon { public: Sword(int attack) { this->attack = attack; this->defence = 0; }; int Defence() { return defence; }; }; class Mace : public Weapon { public: Mace(int attack) { this->attack = attack; this->defence = 0; }; int Defence() { return defence; }; }; int main(int argc, const char * argv[]) { // insert code here... srand(time(NULL)); Point p1(1,3), p2(4,5), p3(7,4); cout << "TransparentTriangle:" << endl; TransparentTriangle tt(p1, p2, p3); tt.Print(); cout << endl << endl; cout << "ColoredTriangle:" << endl; ColoredTriangle ct(p1, p2, p3, "#ff00ff"); ct.Print(); cout << endl << endl; cout << "StrokeTriangle:" << endl; StrokeTriangle st(p1, p2, p3, "#ff00ff", 2); st.Print(); cout << endl << endl; Shield shield(7); Sword sword1(10); Sword sword2(5); Mace mace(15); cout << "Weapons:" << endl; cout << "Sword 1 Hit the Shield, damage is - :" << sword1.Hit(shield) << endl; cout << "Sword 2 Hit the Shield, damage is - :" << sword2.Hit(shield) << endl; cout << "Mace Hit Shield, damage is - :" << mace.Hit(shield) << endl; cout << "Shield Hit Mace, damage is - :" << shield.Hit(mace) << endl; cout << "Sword 1 Hit Mace, damage is - :" << sword1.Hit(mace) << endl; return 0; } <file_sep>/IIT/Course 2/WT/lab_6/database.php <?php /** * User: alkuk * Date: 01.04.15 * Time: 16:26 */ class Lab4DBManager { public function __construct($host, $port, $db, $user, $password) { $this->last_result = null; $this->host = $host; $this->port = $port; $this->db = $db; $this->user = $user; $this->password = $<PASSWORD>; $this->connection = mysql_pconnect($this->host.':'.$this->port, $user, $password); mysql_set_charset('utf8', $this->connection); mysql_select_db($db, $this->connection); } public function getMenuElements($parent = null) { $sql = 'SELECT * FROM `pages`'; if ($parent) { $sql .= ' WHERE parent_id = '.$parent; } else { $sql .= ' WHERE parent_id IS NULL'; } return $this->query($sql)->getAssocResult(); } public function getLatestNews($count = 10) { $sql = 'SELECT * FROM `news` ORDER BY created DESC LIMIT 0,'.$count; return $this->query($sql)->getAssocResult(); } public function query($sql) { $this->last_result = mysql_query($sql, $this->connection); return $this; } public function getAssocResult() { $data = array(); while ($row = mysql_fetch_array($this->last_result, MYSQL_ASSOC)) { $data[] = $row; } return $data; } } <file_sep>/IIT/Course 2/OOP/lab_1/lab_1/lab_1/pairs.cpp // // pairs.cpp // lab_1 // // Created by <NAME> on 25.02.15. // Copyright (c) 2015 Alex. All rights reserved. // #include "pairs.h" #include <string.h> Pairs * InitPairs() { Pairs * pairs; pairs = new Pairs; pairs->count = 0; return pairs; } int GetValue(Pairs * pairs, const char * name, int &value) { for(int i = 0; i < pairs->count; i++) { if (strcmp(pairs->pairs[i].name, name) == 0) { value = pairs->pairs[i].value; return 1; } } return 0; } void SetValue(Pairs * pairs, const char * name, int value) { for(int i = 0; i < pairs->count; i++) { if (strcmp(pairs->pairs[i].name, name) == 0) { pairs->pairs[i].value = value; return; } } //pairs->pairs[pairs->count] = Pair(); pairs->pairs[pairs->count].name = new char[strlen(name)+1]; strcpy(pairs->pairs[pairs->count].name, name); pairs->pairs[pairs->count].value = value; pairs->count++; return; } void PrintPairs(Pairs * pairs) { printf("Pairs:\n"); printf("Total: %d\n", pairs->count); for(int i = 0; i < pairs->count; i++) { printf("%d) name: %s value: %d\n", (i+1), pairs->pairs[i].name, pairs->pairs[i].value); } printf("\n"); }<file_sep>/IIT/Course 2/OOP/lab_2/lab_2/city.cpp // // city.cpp // lab_2 // // Created by <NAME> on 26.04.15. // Copyright (c) 2015 Alex. All rights reserved. // #include "city.h" #include <string> City::City(const char * name , int population, int square) { this->name.assign(name); this->population = population; this->square = square; }; std::string City::GetName() { return name; }; int City::GetPopulation() { return population; }; int City::GetSquare() { return square; };<file_sep>/IIT/Course 2/WT/lab_4/index.php <?php define('APP_PATH', __DIR__); setlocale(LC_TIME, 'ru_RU'); require_once 'functions.php'; $siteConfig = parse_ini_file(pathTOSrc('config/main.cfg')); $db = new Lab4DBManager( $siteConfig['host'], $siteConfig['port'], $siteConfig['database'], $siteConfig['username'], $siteConfig['password'] ); $layout = readTemplate('main'); $blocks = array( //'MAIN_MENU' => readTemplate('main_menu', buildMenuTree($db)), 'MAIN_MENU' => menuRender(buildMenuTree($db)), 'CONTENT' => readTemplate('blocks/content'), 'NEWS' => readTemplate('blocks/news', $db->getLatestNews(4)), 'COPYRIGHT' => readTemplate('blocks/copyright'), 'ADDRESS' => readTemplate('blocks/address'), ); $variables = array( 'HEADER_TITLE' => 'Задание 3 - основы разработки сайтов', 'HEADER_DESCRIPTION' => 'основы разработки сайтов', 'HEADER_KEYWORDS' => 'ИИТ, Сайты, Разработка', 'TODAY_D' => date('d'), 'TODAY_M' => date('m'), 'TODAY_Y' => date('Y'), 'NOW_H' => date('H'), 'NOW_M' => date('i'), 'NOW_S' => date('s'), 'MAIN_COLOR' => $siteConfig['main_color'], 'COPYRIGHT_COLOR' => $siteConfig['copyright_color'], ); echo prepareOutput($layout, $blocks, $variables); <file_sep>/IIT/Course 2/WT/lab_3/functions.php <?php function pathTOSrc($path) { return APP_PATH.'/'.$path; } function readTemplate($name) { return file_get_contents(pathTOSrc('templates/'.$name.'.tpl')); } function placeholdersPrepare($placeholders) { foreach ($placeholders as &$value) { $value = '{'.$value.'}'; } return $placeholders; } function prepareOutput($layout, $blocks, $variables) { $output = str_replace( placeholdersPrepare(array_keys($blocks)), array_values($blocks), $layout ); $output = str_replace( placeholdersPrepare(array_keys($variables)), array_values($variables), $output ); return $output; } <file_sep>/IIT/Course 2/OOP/lab_2/lab_2/students_collection.h // // students_collection.h // lab_2 // // Created by <NAME> on 25.04.15. // Copyright (c) 2015 Alex. All rights reserved. // #ifndef __lab_2__students_collection__ #define __lab_2__students_collection__ #include <stdio.h> #include "student.h" #include <list> class StudentsCollection { private: std::list<Student> * list; public: StudentsCollection(); StudentsCollection(int count, ...); ~StudentsCollection(); StudentsCollection & SortByPhone(); StudentsCollection & SortByLastName(); StudentsCollection & Add(Student); Student * SearchByLastName(const char *); void Print(); }; #endif /* defined(__lab_2__students_collection__) */ <file_sep>/IIT/Course 2/TI/lab_2/lab_2/Crypter.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace lab_2 { class Crypter { byte[] gamma = {1,1,1,0,0,1,0,1,1}; public string CryptString(string inputString) { int gammaSize = gamma.Length; byte[] stringBites = StringToBites(inputString); int stringBitesLength = stringBites.Length; byte[] xoredStringBites = new byte[stringBitesLength]; for (int i = 0; i < stringBitesLength; i++) { xoredStringBites[i] = (byte)(stringBites[i] ^ (gamma[i % gammaSize])); } return BitesToString(xoredStringBites); } public byte[] CryptBytes(byte[] inputBytes) { int gammaSize = gamma.Length; byte[] stringBites = BytesToBites(inputBytes); int stringBitesLength = stringBites.Length; byte[] xoredStringBites = new byte[stringBitesLength]; for (int i = 0; i < stringBitesLength; i++) { xoredStringBites[i] = (byte)(stringBites[i] ^ (gamma[i % gammaSize])); } return BitesToBytes(xoredStringBites); } protected string BitesToString(byte[] bites) { List<Byte> byteList = new List<Byte>(); string bitesString = string.Join("", bites.Select(b => b.ToString()).ToArray()); for (int i = 0; i < bitesString.Length; i += EncodingBytesSupport()) { byteList.Add(Convert.ToByte(bitesString.Substring(i, EncodingBytesSupport()), 2)); } return ClassEncoding().GetString(byteList.ToArray()); } protected byte[] BitesToBytes(byte[] bites) { List<Byte> byteList = new List<Byte>(); string bitesString = string.Join("", bites.Select(b => b.ToString()).ToArray()); for (int i = 0; i < bitesString.Length; i += EncodingBytesSupport()) { byteList.Add(Convert.ToByte(bitesString.Substring(i, EncodingBytesSupport()), 2)); } return byteList.ToArray(); } protected byte[] BytesToBites(byte[] inputBytes) { int bitesCount = inputBytes.Length * EncodingBytesSupport(); byte[] stringToBites = new byte[bitesCount]; int i = 0; foreach (char c in inputBytes) { foreach (char subC in Convert.ToString(c, 2).PadLeft(EncodingBytesSupport(), '0')) { stringToBites[i] = (byte)Char.GetNumericValue(subC); i++; } } return stringToBites; } protected byte[] StringToBites(string inputString) { int bitesCount = ClassEncoding().GetByteCount(inputString) * EncodingBytesSupport(); byte[] stringToBites = new byte[bitesCount]; int i = 0; foreach (char c in inputString.ToCharArray()) { foreach (char subC in Convert.ToString(c, 2).PadLeft(EncodingBytesSupport(), '0')) { stringToBites[i] = (byte)Char.GetNumericValue(subC); i++; } } return stringToBites; } protected int EncodingBytesSupport() { return 8; } protected Encoding ClassEncoding() { return System.Text.Encoding.ASCII; } } } <file_sep>/IIT/Course 2/TI/Course work/PL_Cource_Work_1/PL_Cource_Work_1/app/menu.h // // menu.h // PL_Cource_Work_1 // // Created by <NAME> on 06.12.14. // Copyright (c) 2014 Alex. All rights reserved. // #ifndef PL_Cource_Work_1_menu_h #define PL_Cource_Work_1_menu_h #endif <file_sep>/IIT/Course 2/TI/Course work/PL_Cource_Work_1/PL_Cource_Work_1/app/table_flats.h // // table_flats.h // PL_Cource_Work_1 // // Created by <NAME> on 06.12.14. // Copyright (c) 2014 Alex. All rights reserved. // #ifndef PL_Cource_Work_1_table_flats_h #define PL_Cource_Work_1_table_flats_h #endif <file_sep>/IIT/Course 2/OOP/lab_5/lab_5/main.cpp // // main.cpp // lab_5 // // Created by <NAME> on 28.04.15. // Copyright (c) 2015 Alex. All rights reserved. // #include <iostream> #include <string> template <class TK, class TV> class Pair { private: TK key; TV value; public: Pair(){}; Pair(TK key, TV value) { this->key = key; this->value = value; }; TV GetValue() { return this->value; }; TK GetKey() { return this->key; }; void Print() { std::cout << key << " => " << value << std::endl; }; }; template <class TK, class TV> class Pairs { private: unsigned int size; unsigned int position; Pair<TK, TV> * container; void ImproveSize(unsigned int newSize) { unsigned int i; Pair<TK, TV> * tmpContent = new Pair<TK, TV>[newSize]; for (i=0; i< position; i++) { tmpContent[i] = this->container[i]; } if(this->container) { delete this->container; } this->container = tmpContent; this->size = newSize; }; void CheckForFreeSpace(unsigned int addSize) { if (position + addSize >= size) { int newSize = (size + addSize) * 2; ImproveSize(newSize); } }; void UnsafeAdd(const Pair<TK, TV> & newPair) { this->container[this->position] = newPair; this->position++; }; public: Pairs(unsigned int size = 2) : position(0) { this->size = size > 0 ? size : 2; this->container = new Pair<TK, TV>[this->size]; }; Pairs & operator+=(const Pair<TK, TV> & pair) { CheckForFreeSpace(1); UnsafeAdd(pair); return *this; }; void Print() { int i; std::cout << "Pairs: " << std::endl; for (i=0; i < this->position; i++) { this->container[i].Print(); } std::cout << std::endl << std::endl; }; }; int main(int argc, const char * argv[]) { // insert code here... Pair<int, double> pr1(1, 1.5), pr2(2, 2.3); Pairs<int, double> p1; p1 += pr1; p1 += pr2; p1.Print(); return 0; } <file_sep>/IIT/Course 2/TI/Course work/PL_Cource_Work_1/PL_Cource_Work_1/app/table_buyers.h // // table_buyers.h // PL_Cource_Work_1 // // Created by <NAME> on 06.12.14. // Copyright (c) 2014 Alex. All rights reserved. // #ifndef PL_Cource_Work_1_table_buyers_h #define PL_Cource_Work_1_table_buyers_h #endif <file_sep>/IIT/Course 2/WT/lab_6/boot.php <?php /** * User: alkuk * Date: 04.05.15 * Time: 23:51 */ define('APP_PATH', __DIR__); setlocale(LC_TIME, 'ru_RU'); require_once 'functions.php'; $siteConfig = parse_ini_file(pathTOSrc('config/main.cfg')); $db = new Lab4DBManager( $siteConfig['host'], $siteConfig['port'], $siteConfig['database'], $siteConfig['username'], $siteConfig['password'] ); <file_sep>/IIT/Course 1/SIAOD/Lab_2/Lab_2/main.cpp // // main.cpp // Lab_2 // // Created by <NAME> on 21.05.14. // Copyright (c) 2014 Alex. All rights reserved. // #include <iostream> #define HASH_SIZE 3 struct Word { const char *text; struct Word *next; }; class Vocabulary { public: struct Word *hash_tables[HASH_SIZE]; Vocabulary () { std::fill_n(hash_tables, HASH_SIZE, nullptr); } int hash(const char * key) { unsigned int sum = 0; for (unsigned int i = 0; key[i] != '\0'; i++){ sum += static_cast<int>(key[i]); } return sum % HASH_SIZE; } void add(const char * word) { unsigned int key = hash(word); struct Word * word_item = new Word(); word_item->text = word; if (hash_tables[key] == nullptr) { hash_tables[key] = word_item; } else { word_item->next = hash_tables[key]; hash_tables[key] = word_item; } } void remove(const char * word) { unsigned int key = hash(word); struct Word *cursor, *prev_cursor; cursor = prev_cursor = hash_tables[key]; std::cout << "Removing word: " <<word << "\n"; if (cursor == nullptr) { std::cout << "Word not found!\n"; return; } while (cursor != nullptr) { if (strcmp(cursor->text, word) == 0) { if (prev_cursor == cursor) { if (cursor->next != nullptr) { hash_tables[key] = cursor->next; } else { hash_tables[key] = nullptr; } } else { prev_cursor->next = cursor->next; } return; } prev_cursor = cursor; cursor = cursor->next; } } void find(const char * word) { unsigned int key = hash(word); struct Word *cursor = hash_tables[key]; std::cout << "Finding word: " <<word << "\n"; if (cursor == nullptr) { std::cout << "Word not found!\n"; return; } while (cursor != nullptr) { if (strcmp(cursor->text, word) == 0) { std::cout << "Word successfully found!\n"; return; } cursor = cursor->next; } std::cout << "Word not found!\n"; } void print() { struct Word *cursor = nullptr; for (unsigned int i = 0; i < HASH_SIZE; i++) { std::cout << "Key - " << i << ":\n"; cursor = hash_tables[i]; while (cursor != nullptr) { std::cout << "Word: " << cursor->text << ", "; cursor = cursor->next; } std::cout << "\n"; } } }; int main(int argc, const char * argv[]) { Vocabulary vocabulary; vocabulary.add("First word"); vocabulary.add("Second word"); vocabulary.add("third word"); std::cout << "==================\n\n"; vocabulary.print(); std::cout << "==================\n\n"; vocabulary.find("First word"); vocabulary.find("First word1"); vocabulary.remove("First word"); vocabulary.find("First word"); std::cout << "==================\n\n"; vocabulary.print(); return 0; } <file_sep>/IIT/Course 2/PL/c-lab3/c-lab3/main.c // // main.c // c-lab3 // // Created by <NAME> on 23.10.14. // Copyright (c) 2014 alexkuk. All rights reserved. // #include <stdio.h> #include <string.h> #include <stdlib.h> char * remove_all_parentheses(const char * input_string) { unsigned int open = 0, closed = 0, string_length = strlen(input_string); char * output_string = NULL, * buffer = NULL; buffer = malloc(string_length); unsigned int new_str_cursor = 0; for (unsigned int i = 0; i < string_length; i++) { switch (input_string[i]) { case '(': open++; break; case ')': closed++; break; default: if (open == closed) { buffer[new_str_cursor] = input_string[i]; new_str_cursor++; } break; } } buffer[new_str_cursor] = '\0'; output_string = malloc(strlen(buffer)); strcpy(output_string, buffer); free(buffer); return output_string; } int main(int argc, const char * argv[]) { char base_string[] = "this is a test ((string form (we) should remove all) parentheses ()"; printf("Prepared string - \"%s\"", remove_all_parentheses(base_string)); return 0; }<file_sep>/IIT/Course 2/WT/lab_6/functions.php <?php require_once 'database.php'; function pathTOSrc($path) { return APP_PATH . '/' . $path; } function readTemplate($name, $data = null) { ob_start(); include(pathTOSrc('templates/' . $name . '.tpl')); $ret = ob_get_contents(); ob_end_clean(); return $ret; } function placeholdersPrepare($placeholders) { foreach ($placeholders as &$value) { $value = '{' . $value . '}'; } return $placeholders; } function prepareOutput($layout, $blocks, $variables) { $output = str_replace(placeholdersPrepare(array_keys($blocks)), array_values($blocks), $layout); $output = str_replace(placeholdersPrepare(array_keys($variables)), array_values($variables), $output); return $output; } function buildMenuTree($db) { $parentMenuItems = $db->getMenuElements(); foreach ($parentMenuItems as &$menu) { menuTreeWalk($db, $menu); } return $parentMenuItems; } function menuTreeWalk($db, &$parentMenu) { $children = $db->getMenuElements($parentMenu['id']); if (count($children)) { $parentMenu['children'] = & $children; foreach ($children as &$child) { menuTreeWalk($db, $child); } } } function menuRender($menuItems, $level = 0) { $menuClass = 'mainmenu'; if ($level) { $menuClass = 'mainmenuin' . $level; } $menu = '<ul class="'.$menuClass.'">'; foreach ($menuItems as $menuItem) { $menu .= '<li><a href="#">'.$menuItem['title'].'</a>'; if (!empty($menuItem['children'])) { $menu .= menuRender($menuItem['children'], $level+1); } $menu .= '</li>'; } $menu .= '</ul>'; return $menu; } <file_sep>/IIT/Course 2/TI/Course work/PL_Cource_Work_1/PL_Cource_Work_1/app/menu.c // // menu.c // PL_Cource_Work_1 // // Created by <NAME> on 06.12.14. // Copyright (c) 2014 Alex. All rights reserved. // #include "menu.h" <file_sep>/IIT/Course 2/OOP/lab_2/lab_2/student.cpp // // student.cpp // lab_2 // // Created by <NAME> on 25.04.15. // Copyright (c) 2015 Alex. All rights reserved. // #include <string> #include "student.h" Student::Student(const char * _firstName, const char * _lastName, const char * _phoneNumber): firstName(_firstName), lastName(_lastName), phoneNumber(_phoneNumber) {}; std::string Student::GetFirstName() { return firstName; }; std::string Student::GetLastName() { return lastName; }; std::string Student::GetPhoneNumber() { return phoneNumber; };<file_sep>/IIT/Course 2/TI/lab_2/lab_2/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace lab_2 { public partial class Form1 : Form { Crypter crypter = new Crypter(); Stream myStream = null; string text = ""; public Form1() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { if ((myStream = openFileDialog1.OpenFile()) != null) { using (myStream) { //text = System.IO.File.ReadAllText(openFileDialog1.FileName); byte[] tmp = System.IO.File.ReadAllBytes(openFileDialog1.FileName); string path = Path.GetDirectoryName(openFileDialog1.FileName); string fileName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName); string ext = Path.GetExtension(openFileDialog1.FileName); string newFileName = fileName + "_mod" + ext; label2.Text = newFileName; System.IO.File.WriteAllBytes(path +"\\"+ newFileName, crypter.CryptBytes(tmp)); } } } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } //string result = crypter.CryptString(textBox1.Text); } } } <file_sep>/IIT/Course 2/OOP/lab_2/lab_2/city.h // // city.h // lab_2 // // Created by <NAME> on 26.04.15. // Copyright (c) 2015 Alex. All rights reserved. // #ifndef __lab_2__city__ #define __lab_2__city__ #include <stdio.h> #include <string> class City { private: std::string name; int population; int square; public: City(const char *, int, int); std::string GetName(); int GetPopulation(); int GetSquare(); }; #endif /* defined(__lab_2__city__) */ <file_sep>/IIT/Course 2/OOP/lab_1/lab_1/lab_1/pairs.h // // pairs.h // lab_1 // // Created by <NAME> on 25.02.15. // Copyright (c) 2015 Alex. All rights reserved. // #ifndef __lab_1__pairs__ #define __lab_1__pairs__ #include <stdio.h> #define MAX_PAIRS 100 struct Pair { char * name; //имя int value; //значение }; struct Pairs { Pair pairs[MAX_PAIRS]; int count; }; Pairs * InitPairs(); int GetValue(Pairs * pairs, const char * name, int &value); void SetValue(Pairs * pairs, const char * name, int value); void PrintPairs(Pairs * pairs); #endif /* defined(__lab_1__pairs__) */ <file_sep>/IIT/Course 2/OOP/lab_2/lab_2/main.cpp // // main.cpp // lab_2 // // Created by <NAME> on 25.04.15. // Copyright (c) 2015 Alex. All rights reserved. // #include <iostream> #include <array> #include "city.h" #include "student.h" #include "students_collection.h" int main(int argc, const char * argv[]) { City cities[] = { City("Minsk", 1935000, 348), City("Amsterdam", 821926, 219), City("Berlin", 3419623, 891), City("Bucharest", 1883425, 238), City("Madrid", 3041579, 607), City("Minsk", 2870493, 1287), City("Moscow", 12197, 2511) }; int citiesCount = sizeof(cities)/sizeof(cities[0]); int i; int totalSquare = 0; int millionaireCitiesCount = 0; for (i=0; i< citiesCount; i++) { totalSquare += cities[i].GetSquare(); if (cities[i].GetPopulation() >= 1000000) { millionaireCitiesCount++; } } std::cout << "Cities==============" << std::endl; std::cout << std::endl; std::cout << "Total square: " << totalSquare << std::endl; std::cout << "Millionaire Cities Count: " << millionaireCitiesCount << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << "STUDENTS==============" << std::endl; std::cout << std::endl; std::cout << std::endl; // insert code here... Student student1 = Student("Pavel", "Pretov", "345 39 63"); Student student2 = Student("Nikita", "Gurinenko", "462 29 31"); Student student3 = Student("Dmitriy", "Kurach", "373 19 42"); Student student4 = Student("Vladimir", "Labaza", "376 09 33"); Student student5 = Student("Anton", "Domashkevich", "275 59 34"); Student student6 = Student("Diana", "Korotchenko", "277 58 65"); Student student7 = Student("Maria", "Kukareko", "246 57 36"); StudentsCollection group63 = StudentsCollection(4, &student4, &student5, &student6, &student7); StudentsCollection group64 = StudentsCollection(); group64.Add(student1).Add(student2).Add(student3); std::cout << "Group 63" << std::endl; group63.Print(); std::cout << std::endl; std::cout << std::endl; std::cout << "Group 64" << std::endl; group64.Print(); std::cout << std::endl; std::cout << std::endl; std::cout << "Sorted Group 63" << std::endl; group63.SortByLastName().Print(); std::cout << std::endl; std::cout << std::endl; std::cout << "Search for dfdsf" << std::endl; Student * searched = group63.SearchByLastName("Kukareko"); std::cout << "First Name: " << searched->GetFirstName() << std::endl; std::cout << "Last Name: " << searched->GetLastName() << std::endl; return 0; } <file_sep>/IIT/Course 1/SIAOD/Lab_4/Lab_4/main.cpp // // main.cpp // Lab_4 // // Created by <NAME> on 28.05.14. // Copyright (c) 2014 Alex. All rights reserved. // #include <iostream> #include <stack> class PolishNotationer { protected: std::stack <char> *stack; std::string valid_characters = "()+-*/^0123456789 "; std::string operators = "+-*/^"; std::string numbers = "0123456789"; bool is_numeric(const char *c) { if (numbers.find_first_of(*c) != std::string::npos) { return true; } return false; } bool is_operator(const char *c) { if (operators.find_first_of(*c) != std::string::npos) { return true; } return false; } unsigned char operator_priority(const char *op) { switch (*op) { case '^': return 3; case '*': case '/': return 2; case '+': case '-': return 1; } return 0; } bool is_expression_valid(const std::string *expression) { unsigned int open_parentheses_count = 0, close_parentheses_count = 0, operators_count = 0, numbers_count = 0; std::string::const_iterator next_c; if (expression->empty()) { return false; } for(std::string::const_iterator c = expression->begin(), end = expression->end(); c != end; ++c) { if (valid_characters.find_first_of(*c) == std::string::npos) { return false; } if (is_operator(&(*c))) { operators_count++; continue; } if (is_numeric(&(*c))) { next_c = c+1; if (next_c != end && is_numeric(&(*next_c))) { continue; } numbers_count++; continue; } switch (*c) { case '(': open_parentheses_count++; break; case ')': close_parentheses_count++; break; } } if (open_parentheses_count != close_parentheses_count) { return false; } if (operators_count+1 != numbers_count) { return false; } return true; } void clear_stack() { while (!stack->empty() ) { stack->pop(); } } std::string reverse(const std::string *expression) { std::string output_string; std::stack <char> tmp_stack; bool is_prev_numeric = false; if (expression->empty()) { output_string = *expression; return output_string; } for(std::string::const_iterator c = expression->end()-1, begin = expression->begin(); c >= begin; --c) { if (!is_numeric(&(*c))) { if (is_prev_numeric) { while (!tmp_stack.empty()) { output_string += tmp_stack.top(); tmp_stack.pop(); } } output_string += *c; is_prev_numeric = false; continue; } tmp_stack.push(*c); is_prev_numeric = true; } while (!tmp_stack.empty()) { output_string += tmp_stack.top(); tmp_stack.pop(); } return output_string; } public: PolishNotationer(std::stack <char> *composition_stack) { stack = composition_stack; } std::string toPostfix(const std::string *expression) { std::string output; char tmp_char; bool is_prev_numeric = true; clear_stack(); if (!is_expression_valid(expression)) { output = "Invalid expression."; return output; } for(const char &c : *expression) { if (is_numeric(&c)) { if (!is_prev_numeric) { output += ' '; } output += c; is_prev_numeric = true; continue; } is_prev_numeric = false; if (c == '(') { stack->push(c); continue; } if (c == ')') { while (!stack->empty()) { tmp_char = stack->top(); stack->pop(); if (tmp_char == '(') { break; } output += ' '; output += tmp_char; } } if (is_operator(&c)) { while (!stack->empty()) { tmp_char = stack->top(); if (operator_priority(&c) <= operator_priority(&tmp_char)) { stack->pop(); output += ' '; output += tmp_char; } else { break; } } stack->push(c); continue; } } while (!stack->empty()) { tmp_char = stack->top(); stack->pop(); output += ' '; output += tmp_char; } return output; } std::string toPrefix(const std::string *expression) { std::string prefix_result; if (!is_expression_valid(expression)) { return std::string("Invalid expression."); } prefix_result = toPostfix(expression); return reverse(&prefix_result); } }; int main(int argc, const char * argv[]) { std::stack <char> stack; PolishNotationer polishNotationer(&stack); std::string expression = "15 / (78 - (199 + 1)) * 3 - (2 + (1 + 1)^4)"; std::cout << "Prefix: " << polishNotationer.toPrefix(&expression) << "\n\n"; std::cout << "Postfix: " << polishNotationer.toPostfix(&expression) << "\n\n"; return 0; } <file_sep>/IIT/Course 2/OOP/lab_1/lab_1/lab_1/main.cpp // // main.cpp // lab_1 // // Created by <NAME> on 25.02.15. // Copyright (c) 2015 Alex. All rights reserved. // #include <iostream> #include "pairs.h" int main(int argc, const char * argv[]) { Pairs * pairs; pairs = InitPairs(); int tmp_val; printf("Search for ALEX\n"); if (GetValue(pairs, "alex", tmp_val)) { printf("ALEX's value is: %d\n", tmp_val); } else { printf("ALEX's value not found\n"); } printf("try to set ALEX's value to 7\n"); SetValue(pairs, "alex", 7); if (GetValue(pairs, "alex", tmp_val)) { printf("ALEX's value is: %d\n", tmp_val); } else { printf("ALEX's value not found\n"); } SetValue(pairs, "alex", 8); SetValue(pairs, "bob", 1); SetValue(pairs, "tom", 6); PrintPairs(pairs); return 0; } <file_sep>/IIT/Course 1/SIAOD/Lab_3/Lab_3/main.cpp // // main.cpp // Lab_3 // // Created by <NAME> on 26.05.14. // Copyright (c) 2014 Alex. All rights reserved. // #include <iostream> #define PRIORITY_SIZE 10 struct Message { const char *data = nullptr; struct Message *next = nullptr; }; class WeightedFairQueing { protected: struct Message *queue; struct Message *priority_queue[PRIORITY_SIZE]; void push_to_queue(struct Message **queue, const char *data) { struct Message **walker = queue; while (*walker != nullptr) { walker = &(*walker)->next; } *walker = new Message(); (*walker)->data = data; } void print_queue(const struct Message *queue) { while (queue != nullptr) { std::cout << queue->data << ", "; queue = queue->next; } } struct Message * remove() { struct Message *tmp = nullptr; for (int i = PRIORITY_SIZE-1; i >= 0; i--) { if (priority_queue[i] != nullptr) { tmp = priority_queue[i]; priority_queue[i] = tmp->next; return tmp; } } if (queue != nullptr) { tmp = queue; queue = tmp->next; return tmp; } return nullptr; } struct Message * _find(const char *data) { struct Message *walker = nullptr; for (int i = PRIORITY_SIZE-1; i >= 0; i--) { if (priority_queue[i] != nullptr) { walker = priority_queue[i]; while (walker != nullptr) { if (strcmp(walker->data, data) == 0) { return walker; } walker = walker->next; } } } walker = queue; while (walker != nullptr) { if (strcmp(walker->data, data) == 0) { return walker; } walker = walker->next; } return nullptr; } public: WeightedFairQueing() { std::fill_n(priority_queue, PRIORITY_SIZE, nullptr); queue = nullptr; } void push(const char *data) { push_to_queue(&queue, data); } void push(const char *data, unsigned int priority) { unsigned short priority_level = priority % PRIORITY_SIZE; push_to_queue(&priority_queue[priority_level], data); } bool has_item() { for (int i = PRIORITY_SIZE-1; i >= 0; i--) { if (priority_queue[i] != nullptr) { return true; } } if (queue != nullptr) { return true; } return false; } const char * pop() { struct Message *tmp = remove(); if (tmp == nullptr) { return nullptr; } return tmp->data; } void find(const char *data) { struct Message *finded_element = nullptr; finded_element = _find(data); if (finded_element == nullptr) { std::cout << "Element '" << data << "' not found!\n"; return; } std::cout << "Element '" << data << "' found!\n"; } void print() { std::cout << "Priority Queue:\n"; for (int i = PRIORITY_SIZE-1; i >= 0; i--) { std::cout << "Queue #" << i << ": "; print_queue(priority_queue[i]); std::cout << "\n"; } std::cout << "\nUsual Queue: "; print_queue(queue); std::cout << "\n"; } }; int main(int argc, const char * argv[]) { WeightedFairQueing queue; std::cout << "Show empty queue: \n\n"; queue.print(); queue.push("usual 1"); queue.push("usual 2"); queue.push("usual 3"); queue.push("usual 4"); queue.push("usual 5"); queue.push("usual 6"); std::cout << "\n\nTry to find 'usual 1':\n"; queue.find("usual 1"); std::cout << "\n"; std::cout << "\n\nTry to find 'usual 77':\n"; queue.find("usual 77"); std::cout << "\n"; queue.push("priority - 0", 0); queue.push("priority - 2", 2); queue.push("priority - 4", 4); queue.push("priority - 5", 5); queue.push("priority - 3", 3); queue.push("priority - 1", 1); queue.push("priority - 1,1", 1); queue.push("priority - 1,2", 1); std::cout << "\n\nShow filled queue: \n\n"; queue.print(); std::cout << "\n\nFetch all items: \n\n"; while (queue.has_item()) { std::cout << queue.pop() << "\n"; } std::cout << "Show empty queue: \n\n"; queue.print(); return 0; } <file_sep>/IIT/Course 2/PL/c-lab1/c-lab1/main.c // // main.c // c-lab1 // // Created by <NAME> on 23.10.14. // Copyright (c) 2014 alexkuk. All rights reserved. // #include <stdio.h> #include <math.h> int main(int argc, const char * argv[]) { // insert code here... double sum = 0; for (unsigned int i = 1; i <= 50; i++) { sum += 1/pow(i, 3); } printf("The result is - %.10f\n", sum); return 0; }<file_sep>/IIT/Course 2/WT/lab_2/index.php <?php function echoNewLine($string = '') { echo '<b>' . $string . '</b>', '<br>'; } function taskPrint($number) { echoNewLine(); echoNewLine('Задание ' . $number); echoNewLine(); } header('Content-Type: text/html; charset=utf-8'); $cars = array( array( 'Марка' => 'Peugeot', 'Модели' => array( '207', '406', '307', ), ), array( 'Марка' => 'Лада', 'Модели' => array( 'Калина', 'Приора', ), ) ); #echo strlen('Машина'); echoNewLine('ЛР2 - Основы PHP'); // Task 1 taskPrint(1); $intVar = 1; $stringVar = 'Строка'; $floatVar = 10.3; $boolVar = false; $arrayVar = array( 1, 2, 'строка', 'key' => 'value' ); echoNewLine('Целочисленная переменная $intVar:'); var_Dump($intVar); echoNewLine('Строковая переменная $stringVar:'); var_Dump($stringVar); echoNewLine('Дробная переменная $floatVar:'); var_Dump($floatVar); echoNewLine('Логическая переменная $boolVar:'); var_Dump($boolVar); echo "зднсь логич:"; echo $boolVar; echo null; echoNewLine('Массив $arrayVar:'); var_Dump($arrayVar); // Task 2 $a = 555; $b = 'ZZZ'; taskPrint(2); echoNewLine('Складываем как числа:'); var_dump($a + $b); echoNewLine(); echoNewLine('Складываем как строки:'); var_dump($a . $b); // Task 3 taskPrint(3); $employees = array( array( 'name' => 'Иванов', 'phone' => '77-88-99', 'email' => '<EMAIL>', 'cars' => array( 'Peugeot - 207', 'A<NAME> - Mito' ) ), array( 'name' => 'Попов', 'phone' => '66-55-44', 'email' => '<EMAIL>', 'cars' => array( 'BMW - X5', 'Citroen - C4' ) ), array( 'name' => 'Сидоров', 'phone' => '11-22-33', 'email' => '<EMAIL>', 'cars' => array( 'Fiat - Punto', 'Kia - Avella' ) ) ); var_dump($employees); taskPrint(4); $elements = array( 1, 2, "A", 3.764, 34, "B", 12 ); echoNewLine('Исходный массив:'); var_dump($elements); echoNewLine(); echoNewLine(); foreach ($elements as $key => $value) { if (!is_numeric($value)) { unset($elements[$key]); } } echoNewLine('Массив после фильтрации:'); var_dump($elements); echoNewLine(); echoNewLine(); taskPrint(5); ?> <table width="100%"> <?php for ($i = 1; $i <= 1000; $i++): ?> <?php $hex = dechex($i % 256); $pad = str_pad($hex, 2, '0', STR_PAD_LEFT); $color = '#' . $pad . $pad . $pad; ?> <tr style="background-color: <?php echo $color ?> "> <td width="33%"><?php echo $i ?></td> <td width="33%">&nbsp;</td> <td width="33%">&nbsp;</td> </tr> <?php endfor ?> </table><file_sep>/IIT/Course 2/TI/Course work/PL_Cource_Work_1/PL_Cource_Work_1/app/database.h // // database.h // PL_Cource_Work_1 // // Created by <NAME> on 06.12.14. // Copyright (c) 2014 Alex. All rights reserved. // #ifndef PL_Cource_Work_1_database_h #define PL_Cource_Work_1_database_h #endif <file_sep>/IIT/Course 2/OOP/lab_3/lab_3/main.cpp // // main.cpp // lab_3 // // Created by <NAME> on 27.04.15. // Copyright (c) 2015 Alex. All rights reserved. // #include <iostream> #include <string> #include <iomanip> class Pair { private: char * key; int value; public: Pair(){}; Pair(const Pair & pair) { this->key = new char[strlen(pair.key) + 1]; strcpy(this->key, pair.key); this->value = pair.value; }; Pair(const char * key, int value) { this->key = new char[strlen(key) + 1]; strcpy(this->key, key); this->value = value; }; int GetValue() { return this->value; }; char * GetKey() { return this->key; }; void Print() { std::cout << key << " => " << value << std::endl; }; }; class Pairs { private: unsigned int size; unsigned int position; Pair * container; void ImproveSize(unsigned int newSize) { unsigned int i; Pair * tmpContent =new Pair[newSize]; for (i=0; i< position; i++) { tmpContent[i] = this->container[i]; } if(this->container) { delete this->container; } this->container = tmpContent; this->size = newSize; }; void CheckForFreeSpace(unsigned int addSize) { if (position + addSize >= size) { int newSize = (size + addSize) * 2; ImproveSize(newSize); } }; void UnsafeAdd(const Pair & newPair) { this->container[this->position] = newPair; this->position++; }; public: Pairs(unsigned int size = 2) : position(0) { this->size = size > 0 ? size : 2; this->container = new Pair[this->size]; }; Pairs & Add(const Pair & newPair) { CheckForFreeSpace(1); UnsafeAdd(newPair); return *this; } Pairs & Merge(const Pairs & pairsToMerge) { CheckForFreeSpace(pairsToMerge.position); int i; for (i=0; i< pairsToMerge.position; i++) { UnsafeAdd(pairsToMerge.container[i]); } return *this; }; Pairs & Replace(const Pairs & pairsToReplace) { if (this != &pairsToReplace) { delete this->container; this->size = pairsToReplace.size; this->position = pairsToReplace.position; int i; this->container = new Pair[this->size]; for (i=0; i< pairsToReplace.position; i++) { this->container[i] = Pair(pairsToReplace.container[i]); } } return *this; }; Pairs & operator+=(const Pair& pair) { return Add(pair); }; Pairs & operator+=(const Pairs& pairsToMerge) { return Merge(pairsToMerge); } Pairs & operator=(const Pairs & pairsToReplace) { return Replace(pairsToReplace); }; char * operator[](int search) { int i; for (i=0; i < this->position; i++) { if (this->container[i].GetValue() == search) { return this->container[i].GetKey(); } } return NULL; }; int operator[](const char * search) { int i; for (i=0; i < this->position; i++) { if (!strcmp(this->container[i].GetKey(), search)) { return this->container[i].GetValue(); } } return 0; }; void Print() { int i; std::cout << "Pairs: " << std::endl; for (i=0; i < this->position; i++) { this->container[i].Print(); } std::cout << std::endl << std::endl; }; }; class Matrix { private: int rows; int cols; int ** data; void Init(int rows, int cols) { this->rows = rows; this->cols = cols; this->data = new int*[this->rows]; //fill with zero int i; for (i = 0; i < this->rows; i++) { this->data[i] = new int[this->cols](); } }; public: Matrix(); Matrix( int rows, int cols) { Init(rows, cols); }; Matrix( int rows, int cols, int * data ) { Init(rows, cols); int i, j; for (i = 0; i < this->rows; i++) { for (j = 0; j < this->cols; j++) { this->data[i][j] = data[i*this->rows+j]; } } }; Matrix( int rows, int cols, int ** data ) { Init(rows, cols); int i, j; for (i = 0; i < this->rows; i++) { for (j = 0; j < this->cols; j++) { this->data[i][j] = data[i][j]; } } }; ~Matrix() { int i; for (i = 0; i < this->rows; i++) { delete[] this->data[i]; } delete[] this->data; }; Matrix & resize( int newRows, int newCols ) { int ** oldData = this->data; int oldRows = this->rows; int oldCols = this->cols; int minR, minC, i, j; minR = newRows < oldRows ? newRows : oldRows; minC = newCols < oldCols ? newCols : oldCols; Init(newRows, newCols); for (i = 0; i < minR; i++) { for (j = 0; j < minC; j++) { this->data[i][j] = oldData[i][j]; } } for (i = 0; i < oldRows; i++) { delete[] oldData[i]; } delete[] oldData; return *this; }; Matrix submatrix( int startRow, int startCol, int endRow, int endCol ) { int rows = endRow - startRow; int cols = endCol - startCol; int i, j, newI, newJ; Matrix subM = Matrix(rows, cols); for (i = startRow; i < endRow; i++) { for (j = startCol; j < endCol; j++) { newI = i - startRow; newJ = j - startCol; subM[newI][newJ] = this->data[i][j]; } } return subM; }; Matrix submatrix( int startRow, int startCol) { return submatrix(startRow, startCol, this->rows, this->cols); }; int * operator[](int i) { return this->data[i]; }; void Print() { int i, j; std::cout << "Matrix " << this->rows << "x" << this->cols << " :" << std::endl; for (i = 0; i < this->rows; i++) { for (j = 0; j < this->cols; j++) { std::cout << std::setw(4) << this->data[i][j]; } std::cout << std::endl; } std::cout << std::endl; }; }; int main(int argc, const char * argv[]) { // insert code here... Pair pr1("first", 1), pr2("second", 2), pr3("third", 3), pr4("fourth", 4), pr5("fifth", 5), pr6("sixth", 6); Pairs p1, p2, p3; p1 += pr1; p1 += pr2; p2 += pr3; p2 += pr4; p3 += pr5; p3 += pr6; p1.Print(); std::cout << "Find key by value: " << p1[2] << std::endl; std::cout << "Find value by key: " << p1["second"] << std::endl; std::cout << std::endl << std::endl; p1 += p2; p1.Print(); p1 = p3; p1.Print(); p1 += p2; p1.Print(); p3.Print(); int rows = 8; int cols = 8; int i, total; total = rows*cols; int * dataForMatrix = new int[total]; for (i = 0; i < total; i++) { dataForMatrix[i] = 1+i; } Matrix m1 = Matrix(rows, cols, dataForMatrix); m1.Print(); m1.resize(5, 4); m1.Print(); m1.resize(6, 6); m1.Print(); m1.submatrix(1, 1, 5, 5).Print(); m1.submatrix(1, 1).Print(); return 0; } <file_sep>/IIT/Course 2/WT/lab_6/rss.php <?php require_once 'boot.php'; $dateFormat = 'D, d M Y H:i:s O'; $rssFeed = '<?xml version="1.0" encoding="utf-8" ?>'; $rssFeed .= '<rss version="2.0">'; $rssFeed .= '<channel>'; $rssFeed .= '<title>Наши новости</title>'; $rssFeed .= '<link>http://iit-lab6.dev/rss.php</link>'; $rssFeed .= '<description>Самые свежие в мире новости у нас!</description>'; $rssFeed .= '<lastBuildDate>'.date($dateFormat).'</lastBuildDate>'; foreach ($db->getLatestNews() as $item) { $link = 'http://iit-lab6.dev/content/'.$item['id']; $rssFeed .= '<item>'; $rssFeed .= '<title>'.$item['title'].' ('.date('Y/m/d', $item['created']).')</title>'; $rssFeed .= '<link>'.$link.'</link>'; $rssFeed .= '<description>'.$item['body'].'</description>'; $rssFeed .= '<comments>'.$link.'/'.$item['id'].'#comments</comments>'; $rssFeed .= '<pubDate>'.date($dateFormat, $item['created']).'</pubDate>'; $rssFeed .= '<guid isPermaLink="true">'.$link.'</guid>'; $rssFeed .= '</item>'; } $rssFeed .= '</channel>'; $rssFeed .= '</rss>'; echo $rssFeed; <file_sep>/IIT/Course 2/BPI/lab_4/js/func.js function binaryNod(m, n) { m = parseInt(m, 10); n = parseInt(n, 10); if (!m || !n) { return m+n; } if (m == n) { return m; } if (m == 1 || n == 1) { return 1; } var multiplier = 1; while (m%2==0 && n%2==0) { multiplier <<= 1; m >>= 1; n >>= 1; } while (n > 0) { if (m%2==0 && m>0) { m >>= 1; } else if (n%2==0 && n>0) { n >>= 1; } else { var t = Math.abs(Math.floor((m-n)/2)); if (m > n) { m = t; } else { n = t; } } } return multiplier*m; } function eulerFunction(n) { n = parseInt(n, 10); var output = n; for (var i=2; i*i<=n; ++i) { if (n % i == 0) { while (n % i == 0) { n /= i; } output -= output / i; } } if (n > 1) { output -= output / n; } return output; } function getKs(k0, eiler) { eiler = parseInt(eiler, 10); k0 = parseInt(k0, 10); return fastEx(k0, eulerFunction(eiler)-1, eiler); } function fastEx(multiplier, power, mod) { multiplier = parseInt(multiplier, 10); power = parseInt(power, 10); mod = parseInt(mod, 10); var output = 1; while (power) { while (power % 2 == 0) { power /= 2; multiplier = (multiplier * multiplier) % mod; } power -= 1; output = (output * multiplier) % mod; } return output; } function mgetR(p, q) { return p * q; } function getEiler(p, q) { return (p - 1) * (q - 1); } function euclideX(a, b) { var d0 = a, d1 = b; if (a < b) { d0 = b; d1 = a; } var x0 = 1, x1 = 0, y0 = 0, y1 = 1; while (d1 > 1) { var q = Math.floor(d0 / d1), d2 = d0 % d1, x2 = x0 - q * x1, y2 = y0 - q * y1; d0 = d1; d1 = d2; x0 = x1; x1 = x2; y0 = y1; y1 = y2; } return [x1, y1, d1]; } function getAlphabet() { return 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'; } function hashString(string, prevH, n) { var length = string.length, alphabet = getAlphabet(); string = string.toLowerCase(); for (var i = 0; i < length; i++) { var charPos = alphabet.indexOf(string[i])+1; // +1 - !!! prevH = hashChar(prevH, charPos, n); } return prevH; } function hashChar(prevH, m, n) { return Math.pow(prevH+m, 2) % n; } function generateS(hashM, kC, r) { return fastEx(hashM, kC, r); }<file_sep>/IIT/Course 1/SIAOD/Lab_5/lab_5/main.cpp // // main.cpp // lab_5 // // Created by <NAME> on 29.05.14. // Copyright (c) 2014 Alex. All rights reserved. // #include <iostream> struct Node { int data; //unsigned int depth; Node *parent = nullptr, *left = nullptr, *right = nullptr; }; class Tree { protected: Node *root; Node * node_factory(int data) { Node *node = new Node(); node->data = data; return node; } Node * node_factory(int data, Node *parent) { Node *node = new Node(); node->data = data; node->parent = parent; return node; } void add(Node *root, int input_data) { if (input_data > root->data) { if (root->right == nullptr) { root->right = node_factory(input_data, root); } else { add(root->right, input_data); } } else if (input_data < root->data) { if (root->left == nullptr) { root->left = node_factory(input_data, root); } else { add(root->left, input_data); } } } void remove(Node *root, int input_data) { Node **tmp = nullptr; if (root == nullptr) { return; } if (input_data > root->data) { remove(root->right, input_data); } else if (input_data < root->data) { remove(root->left, input_data); } else { if (root->right == nullptr && root->left == nullptr) { root = nullptr; } else if (root->right != nullptr && root->left != nullptr) { if (root->right->left == nullptr) { root->right->left = root->left; root = root->right; } else { tmp = &(root->right->left); while ((*tmp)->left != nullptr) { *tmp = (*tmp)->left; } root->data = (*tmp)->data; *tmp = nullptr; } } else { if (root->right != nullptr) { root = root->right; } else { root = root->left; } } } } Node * find(Node *root, int input_data) { if (root == nullptr) { return nullptr; } if (root->data == input_data) { return root; } if (input_data > root->data) { return find(root->right, input_data); } else { return find(root->left, input_data); } } void inflex_traverse(Node *root) { if (root == nullptr) { return; } inflex_traverse(root->left); std::cout << root->data << ", "; inflex_traverse(root->right); } void prefix_traverse(Node *root) { if (root == nullptr) { return; } std::cout << root->data << ", "; prefix_traverse(root->left); prefix_traverse(root->right); } void postfix_traverse(Node *root) { if (root == nullptr) { return; } postfix_traverse(root->left); postfix_traverse(root->right); std::cout << root->data << ", "; } public: void add(int input_data) { if (root == nullptr) { root = node_factory(input_data); } else { add(root, input_data); } } void remove(int input_data) { remove(root, input_data); } void find(int input_data) { Node *tmp = find(root, input_data); if (tmp == nullptr) { std::cout << "Element not found\n"; return; } std::cout << "Element found, data is - " << tmp->data << "\n"; } void inflex_traverse() { std::cout << "inflex traverse: "; inflex_traverse(root); std::cout << "\n"; } void prefix_traverse() { std::cout << "prefix traverse: "; prefix_traverse(root); std::cout << "\n"; } void postfix_traverse() { std::cout << "postfix traverse: "; postfix_traverse(root); std::cout << "\n"; } }; int main(int argc, const char * argv[]) { Tree tree; tree.add(42); tree.add(25); tree.add(64); tree.add(12); tree.add(37); tree.add(13); tree.add(30); tree.add(43); tree.add(87); tree.add(99); tree.add(9); tree.add(66); tree.add(67); tree.add(65); tree.find(777); tree.find(9); tree.find(64); std::cout << "Remove 64\n"; tree.remove(64); tree.inflex_traverse(); tree.prefix_traverse(); tree.postfix_traverse(); return 0; } <file_sep>/IIT/Course 2/OOP/lab_2/lab_2/students_collection.cpp // // students_collection.cpp // lab_2 // // Created by <NAME> on 25.04.15. // Copyright (c) 2015 Alex. All rights reserved. // #include "students_collection.h" #include "student.h" #include <list> #include <iostream> #include <iomanip> bool comparePhoneAsc(Student & first, Student & second) { return (first.GetPhoneNumber().compare(second.GetPhoneNumber()) < 0); } bool compareLastNameAsc(Student & first, Student & second) { return (first.GetLastName().compare(second.GetLastName()) < 0); } StudentsCollection::~StudentsCollection() { delete list; }; StudentsCollection::StudentsCollection() { list = new std::list<Student>; } StudentsCollection::StudentsCollection(int count, ...) { list = new std::list<Student>; int i; va_list ap; va_start(ap, count); for (i = 0; i< count; i++) { Student * s = va_arg(ap, Student *); list->push_back(*s); } va_end(ap); }; StudentsCollection & StudentsCollection::Add(Student student) { list->push_back(student); return *this; }; StudentsCollection & StudentsCollection::SortByPhone() { list->sort(comparePhoneAsc); return *this; }; StudentsCollection & StudentsCollection::SortByLastName() { list->sort(compareLastNameAsc); return *this; }; void StudentsCollection::Print() { std::list<Student>::iterator it; int separators = 4 + (3 * 15); std::cout << std::string(separators, '_') << std::endl; printf("|%15s|%15s|%15s|", "First name", "Last name", "Phone"); std::cout << std::string(separators, '_') << std::endl; for (it=list->begin(); it != list->end(); ++it) { std::cout << '|' << std::setw(15) << it->GetFirstName(); std::cout << '|' << std::setw(15) << it->GetLastName(); std::cout << '|' << std::setw(15) << it->GetPhoneNumber(); std::cout << '|' << std::endl; std::cout << std::string(separators, '_') << std::endl; } }; Student * StudentsCollection::SearchByLastName(const char * text) { std::list<Student>::iterator it; for (it=list->begin(); it != list->end(); ++it) { if (it->GetLastName().find(text) != std::string::npos) { return &*it; } } return NULL; }; <file_sep>/IIT/Course 2/WT/lab_5/index.php <?php header('Content-type: text/html; charset=utf-8'); require_once 'functions.php'; printHeader('Задание 1 - проверка email.'); $correctEmails = array( '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', ); $invalidEmails = array( '-<EMAIL>', 'vasya_<EMAIL>..com', '<EMAIL>', '<EMAIL>', '<EMAIL>_', ); checkEmails($correctEmails); checkEmails($invalidEmails); printHeader('Задание 2 - удаления html комментариев.'); $html = ' Текст до комментариев <!-- comments--> <!-- comments--> <!-- comments--> <!--[if IE]> <link href="/css/invstroyIEfix.css" rel="stylesheet" type="text/css" /> <![endif]--> <!-- бла бла бла --> <!-- фвафыва --> Текст после комментариев '; printHeader('До:'); echo nl2br(htmlentities($html)); printHeader('После:'); echo nl2br(htmlentities(removeHTMLComments($html))); printHeader('Задание 3 - Удалить html теги.'); $html = ' <a href="http://somegreatsite.com">Link Name</a> is a link to another nifty site <H1>This is a Header</H1> <H2>This is a Medium Header</H2> Send me mail at <a href="mailto:<EMAIL>"> <EMAIL></a>. <P> This is a new paragraph! <P> <B>This is a new paragraph!</B> <BR> <B><I>This is a new sentence without a paragraph break, in bold italics.</I></B> '; printHeader('До:'); echo nl2br(htmlentities($html)); printHeader('После:'); echo nl2br(htmlentities(removeHTMLTags($html))); printHeader('Задание 5 - Выделить слова которые больше 5 букв и написаны большими буквами.'); $pattern = '/\b[A-Z]{3,4}/s'; $text = "LOREM ipsum DOLOR SIT AMET, A consectetur adipiscing ELIT. Maecenas EFFICITUR justo justo, UT pharetra velit blandit at. nam vitae leo id nibh CONGUE feugiat. Duis IMPERDIET nunc elit, sed efficitur neque placerat in. Sed luctus magna eget sollicitudin semper. Curabitur quis efficitur libero, sed condimentum lectus."; printHeader('До:'); echo $text; printHeader('После:'); echo preg_replace(array( '/\b[A-Z]{5,}/s', '/\b[A-Z]{3,4}[^A-Z]/s', ), array( '<font color="red"><b>$0</b></font>', '<font color="green"><b>$0</b></font>', ), $text); <file_sep>/IIT/Course 1/SIAOD/Lab_1/Lab_1/main.cpp // // main.cpp // Lab_1 // // Created by <NAME> on 21.05.14. // Copyright (c) 2014 Alex. All rights reserved. // #include <math.h> #include <iostream> struct Polynomial { int power; int multiplier; struct Polynomial *next; }; struct Child { unsigned int number; struct Child *next; struct Child *prev; }; struct Polynomial * polynomialFactory(int multiplier, int power) { struct Polynomial *polynomial = new Polynomial(); polynomial->multiplier = multiplier; polynomial->power = power; polynomial->next = nullptr; return polynomial; } void polynomialOnePrinter(const struct Polynomial *polynomial) { if (!polynomial) { return; } if (polynomial->multiplier == 0) { return; } if (polynomial->multiplier != 1) { printf("%d", polynomial->multiplier); } if (polynomial->power == 0) { printf("1"); return; } printf("x"); if (polynomial->power != 1) { printf("^%d", polynomial->power); } } void polynomialPrinter(const struct Polynomial *polynomial) { unsigned int i = 0; while (polynomial != nullptr) { if (i > 0 && polynomial->multiplier >= 0) { printf("+"); } polynomialOnePrinter(polynomial); polynomial = polynomial->next; i++; } } bool polynomial_equality(const struct Polynomial *p_first, const struct Polynomial *p_second) { if (p_first->power == p_second->power && p_first->multiplier == p_second->multiplier) { if (p_first->next == nullptr && p_second->next == nullptr) { return true; } else if (p_first->next == nullptr || p_second->next == nullptr) { return false; } return polynomial_equality(p_first->next, p_second->next); } return false; } int polynomial_meaning(const struct Polynomial *p, int x){ if (p == nullptr) { return 0; } return (p->multiplier * pow(x, p->power)) + polynomial_meaning(p->next, x); } void polynomial_add_current_or_next(struct Polynomial *p, int multiplier, int power) { if (p == nullptr) { p = polynomialFactory(multiplier, power); } else { p->next = polynomialFactory(multiplier, power); p = p->next; } } void polynomial_add( const struct Polynomial *p_first, const struct Polynomial *p_second, struct Polynomial **p_result ) { struct Polynomial *prev = nullptr, *cursor = *p_result = polynomialFactory(0, 1); while (p_first != nullptr || p_second != nullptr) { if (p_first != nullptr && p_second != nullptr) { if (p_first->power == p_second->power) { cursor->multiplier = p_first->multiplier + p_second->multiplier; cursor->power = p_first->power; p_first = p_first->next; p_second = p_second->next; } else if (p_first->power > p_second->power) { cursor->multiplier = p_first->multiplier; cursor->power = p_first->power; p_first = p_first->next; } else { cursor->multiplier = p_second->multiplier; cursor->power = p_second->power; p_second = p_second->next; } } else if (p_first == nullptr) { cursor->multiplier = p_second->multiplier; cursor->power = p_second->power; p_second = p_second->next; } else { cursor->multiplier = p_first->multiplier; cursor->power = p_first->power; p_first = p_first->next; } cursor->next = polynomialFactory(0, 1); prev = cursor; cursor = cursor->next; } if (prev != nullptr) { delete prev->next; prev->next = nullptr; } } void case_1() { struct Polynomial *first_formula = nullptr, *second_formula = nullptr, *third_formula = nullptr, *fourth_formula = nullptr; int x_1 = 10, x_2 = 1, meaning_result_1 = 29505, meaning_result_2 = -6; // '3x^4-5x^2+x-5' first_formula = polynomialFactory(3, 4); first_formula->next = polynomialFactory(-5, 2); first_formula->next->next = polynomialFactory(1, 1); first_formula->next->next->next = polynomialFactory(-5, 0); // '-8x^7-5x^4+x+6' second_formula = polynomialFactory(-8, 7); second_formula->next = polynomialFactory(-5, 4); second_formula->next->next = polynomialFactory(1, 1); second_formula->next->next->next = polynomialFactory(6, 0); // '-8x^7-5x^4+x+6' third_formula = polynomialFactory(-8, 7); third_formula->next = polynomialFactory(-5, 4); third_formula->next->next = polynomialFactory(1, 1); third_formula->next->next->next = polynomialFactory(6, 0); std::cout << "Equal method ------------------------\n"; std::cout << "Is '"; polynomialPrinter(second_formula); std::cout << "' equal to '"; polynomialPrinter(third_formula); std::cout << "' ?? - "; std::cout << (polynomial_equality(second_formula, third_formula) ? "Yes" : "No"); std::cout << "\n"; std::cout << "Is '"; polynomialPrinter(first_formula); std::cout << "' equal to '"; polynomialPrinter(third_formula); std::cout << "' ?? - "; std::cout << (polynomial_equality(first_formula, third_formula) ? "Yes" : "No"); std::cout << "\n"; std::cout << "-------------------------------------\n"; std::cout << "\n\n"; std::cout << "Meaning method ------------------------\n"; std::cout << "The "; polynomialPrinter(first_formula); std::cout << " with x = " << x_1; std::cout << "! should be equal " << meaning_result_1; std::cout << "! Got - " << polynomial_meaning(first_formula, x_1); std::cout << "\n\n"; std::cout << "The "; polynomialPrinter(first_formula); std::cout << " with x = " << x_2; std::cout << "! should be equal " << meaning_result_2; std::cout << "! Got - " << polynomial_meaning(first_formula, x_2); std::cout << "\n"; std::cout << "-------------------------------------\n"; std::cout << "\n\n"; std::cout << "Add method ------------------------\n"; std::cout << "Calculate "; polynomialPrinter(first_formula); std::cout << " and "; polynomialPrinter(second_formula); std::cout << "!\n Got - "; polynomial_add(first_formula, second_formula, &fourth_formula); polynomialPrinter(fourth_formula); std::cout << "\n"; std::cout << "-------------------------------------\n"; } struct Child * child_factory(unsigned int number) { struct Child * child = new Child(); child->number = number; child->next = nullptr; child->prev = nullptr; return child; } void generate_children(struct Child *first_child, unsigned int count) { struct Child *cursor = first_child; cursor->next = first_child; for (unsigned int i = 2; i <= count; i++) { cursor->next = child_factory(i); cursor->next->prev = cursor; cursor = cursor->next; } first_child->prev = cursor; cursor->next = first_child; } void case_2() { unsigned short k = 3; unsigned short counter; struct Child *cursor_prev; struct Child *cursor_next; struct Child *cursor; for (unsigned int i = 1; i <= 64; i++) { cursor = child_factory(1); generate_children(cursor, i); counter = 1; std::cout << "Children count - " << i << "\n"; std::cout << "Leavers - "; while(true) { if (cursor == cursor->next) { break; } if (counter == k) { cursor_prev = cursor->prev; cursor_next = cursor->next; cursor_prev->next = cursor_next; cursor_next->prev = cursor_prev; std::cout << cursor->number << ","; counter = 1; cursor = cursor->next; continue; } cursor = cursor->next; counter++; } std::cout << "\n" << "Winner - " << cursor->number << "!\n"; std::cout << "\n"; } } struct Phones { const char *phone; const char *name; struct Phones *next; }; struct Phones * phones_factory(const char *phone, const char *name) { struct Phones * phone_item = new Phones(); phone_item->name = name; phone_item->phone = phone; phone_item->next = nullptr; return phone_item; } void search_phones_by_name(const struct Phones *phone_item, const char *name) { while (phone_item != nullptr) { if (strstr(phone_item->name, name) != NULL) { std::cout << "Finded phone: " << phone_item->phone << "\n"; } phone_item = phone_item->next; } } void search_names_by_pnone(const struct Phones *phone_item, const char *phone) { while (phone_item != nullptr) { if (strstr(phone_item->phone, phone) != NULL) { std::cout << "Finded name: " << phone_item->name << "\n"; } phone_item = phone_item->next; } } void case_3() { struct Phones * phone_item; phone_item = phones_factory("2976833", "alex"); phone_item->next = phones_factory("2976452", "dob"); phone_item->next->next = phones_factory("2976268", "mick"); phone_item->next->next->next = phones_factory("2976236", "donald"); phone_item->next->next->next->next = phones_factory("2976223", "alexandr"); std::cout << "Finded phones by name 'alex'\n"; search_phones_by_name(phone_item, "alex"); std::cout << "\n"; std::cout << "Finded names by phone '29762'\n"; search_names_by_pnone(phone_item, "29762"); std::cout << "\n"; } struct DoubleDirectionPhones { unsigned int phone; struct DoubleDirectionPhones *next; struct DoubleDirectionPhones *prev; }; struct SingleDirectionPhones { unsigned int phone; struct SingleDirectionPhones *next; }; struct DoubleDirectionPhones * double_direction_phones_factory(unsigned int phone) { struct DoubleDirectionPhones *p = new DoubleDirectionPhones(); p->phone = phone; return p; } struct SingleDirectionPhones * single_direction_phones_factory(unsigned int phone) { struct SingleDirectionPhones *p = new SingleDirectionPhones(); p->phone = phone; return p; } void case_4() { unsigned int phones[] = {2976833,2976452,2976268,2976236,101,102,103,104,2976223,2976205,2976140,2976121}; unsigned int all_phones_count = sizeof(phones)/sizeof(phones[0]); struct DoubleDirectionPhones *first_phone, *double_cursor; struct SingleDirectionPhones *first_single_phone = nullptr, *single_cursor = nullptr; first_phone = double_direction_phones_factory(phones[0]); double_cursor = first_phone; for (unsigned i=1; i < all_phones_count; i++) { double_cursor->next = double_direction_phones_factory(phones[i]); double_cursor->next->prev = double_cursor; double_cursor = double_cursor->next; } first_phone->prev = double_cursor; double_cursor->next = first_phone; double_cursor = first_phone; do { if (double_cursor->phone > 999) { if (first_single_phone == nullptr) { first_single_phone = single_direction_phones_factory(double_cursor->phone); single_cursor = first_single_phone; } else { single_cursor->next = single_direction_phones_factory(double_cursor->phone); single_cursor = single_cursor->next; } } double_cursor = double_cursor->prev; } while (double_cursor != first_phone); std::cout << "Display usual phones:\n"; while (first_single_phone != nullptr) { std::cout << first_single_phone->phone << "\n"; first_single_phone = first_single_phone->next; } std::cout << "\n"; } void menu() { unsigned short lab_num; std::cout << "Please input number of case!\n"; std::cin >> lab_num; switch (lab_num) { case 0: return; case 1: case_1(); break; case 2: case_2(); break; case 3: case_3(); break; case 4: case_4(); break; default: std::cout << "Case not found!\n"; break; } menu(); } int main(int argc, const char * argv[]) { menu(); // insert code here... //std::cout << "Hello, World!\n"; return 0; } <file_sep>/IIT/Course 2/BPI/lab_2/js/func.js function euclidNod(m, n) { m = parseInt(m, 10); n = parseInt(n, 10); if (!m || !n) { return m+n; } if (m == n) { return m; } if (m == 1 || n == 1) { return 1; } while (m && n) { if (m > n) { m = Math.floor(m%n); } else { n = Math.floor(n%m); } } return m + n; } function binaryNod(m, n) { m = parseInt(m, 10); n = parseInt(n, 10); if (!m || !n) { return m+n; } if (m == n) { return m; } if (m == 1 || n == 1) { return 1; } var multiplier = 1; while (m%2==0 && n%2==0) { multiplier <<= 1; m >>= 1; n >>= 1; } while (n > 0) { if (m%2==0 && m>0) { m >>= 1; } else if (n%2==0 && n>0) { n >>= 1; } else { var t = Math.abs(Math.floor((m-n)/2)); if (m > n) { m = t; } else { n = t; } } } return multiplier*m; } function eulerFunction(n) { n = parseInt(n, 10); var output = n; for (var i=2; i*i<=n; ++i) { if (n % i == 0) { while (n % i == 0) { n /= i; } output -= output / i; } } if (n > 1) { output -= output / n; } return output; } function func4(a, b, n) { a = parseInt(a, 10); b = parseInt(b, 10); n = parseInt(n, 10); if (n < 0) { return "Число n меньше 0"; } if (a !== Math.floor(a)) { return "Число a не является челым!" } if (binaryNod(a, n) !== 1) { return "Числа "+a+" и "+n+" не взаимо просты!" } if (eulerFunction(n) !== b) { return "Число "+b+" не является результатам функции эйлера числа "+n; } return "Равенство выполняется. Числа a("+a+") и n("+n+") взаимно просты, число b("+b+") является результатам функции ейлера n("+n+")." } function func5(n, r) { r = parseInt(r, 10); n = parseInt(n, 10); return Math.pow(n, eulerFunction(r)-1)%r; } function fastEx(multiplier, power, mod) { multiplier = parseInt(multiplier, 10); power = parseInt(power, 10); mod = parseInt(mod, 10); var output = 1; while (power) { while (power % 2 == 0) { power /= 2; multiplier = (multiplier * multiplier) % mod; } power -= 1; output = (output * multiplier) % mod; } return output; } <file_sep>/IIT/Course 2/WT/lab_5/functions.php <?php /** * User: alkuk * Date: 04.05.15 * Time: 21:13 */ function printHeader($text) { echo '<h2>'.$text.'</h2><br>'; } function isValidEmail($email) { $pattern = '/^([0-9a-zA-Z]+[-_.])*[0-9a-zA-Z]+@([0-9a-zA-Z-_]+[.])+[a-zA-Z]{2,8}$/'; return preg_match($pattern, $email); } function checkEmails($emails) { foreach ($emails as $email) { echo "Email: ".$email." => "; echo (isValidEmail($email) ? "<font color='green'>Корректен</font>" : "<font color='red'>Не корректен</font>"); echo "<br>"; } } function removeHTMLComments($html) { $pattern = '/<!--((?!-->)(?!\[if.*ie.*\]).)*-->/is'; return preg_replace($pattern, '', $html); } function removeHTMLTags($html) { $pattern = '/<[^>]+>/is'; return preg_replace($pattern, '', $html); } <file_sep>/IIT/Course 2/PL/c-lab2/c-lab2/main.c // // main.c // c-lab2 // // Created by <NAME> on 23.10.14. // Copyright (c) 2014 alexkuk. All rights reserved. // #include <stdio.h> #include <stdlib.h> typedef struct NUM_COUNTER { int num; unsigned int count; } NUM_COUNTER; NUM_COUNTER *create_num_counter(int number) { NUM_COUNTER *c = (NUM_COUNTER *) malloc (sizeof (NUM_COUNTER)); c->num = number; c->count = 1; return c; } void push(NUM_COUNTER *num_counter[], int number) { int i = 0; while (num_counter[i] != NULL) { if (num_counter[i]->num == number) { num_counter[i]->count++; return; } i++; } num_counter[i] = create_num_counter(number); } void print_num_counter(NUM_COUNTER *num_counter[]) { int i = 0; printf("num - count\n"); while (num_counter[i] != NULL) { printf("%2d - %d\n", num_counter[i]->num, num_counter[i]->count); i++; } } int main(int argc, const char * argv[]) { int matrix[6][6] = { {1,2,3,4,5,6}, {2,3,4,5,6,7}, {3,4,5,6,7,8,9}, {4,5,6,7,8,9,0}, {5,6,7,8,9,0,1}, {6,7,8,9,0,1,2} }; NUM_COUNTER *counter[36] = {NULL}; for (int i=0; i < 6; i++) { for (int j=0; j < 6; j++) { printf("%3d", matrix[i][j]); push(&counter, matrix[i][j]); } printf("\n"); } printf("\n\n"); print_num_counter(counter); return 0; }
ea63f21a723b20a56122d4de5bb793abc872d345
[ "JavaScript", "C#", "PHP", "C", "C++" ]
40
C#
lightsuner/education
edb309c0436340c2a8cc4c64be7d6d0d3deccc21
6becbdfa465c22c2709732d9744e2f622cd4677e
refs/heads/master
<file_sep>const obj = new Proxy({}, { get: function (target, propKey, receiver) { console.log(`getting ${propKey}!`); return Reflect.get(target, propKey, receiver); }, set: function (target, propKey, value, receiver) { console.log(`setting ${propKey}!`); return Reflect.set(target, propKey, value, receiver); } }); obj.count = 1; obj.count; var proxy = new Proxy({}, { get: function(target, propKey) { return 35; } }); proxy.time // 35 proxy.name // 35 proxy.title // 35
884c8c96d2ee559e347a1b6103d951d89097001e
[ "JavaScript" ]
1
JavaScript
baiziyu-fe/ES6-guide
a17f623c63a9820ab587478400af45a323d36e1a
667a4010d8c08540e228e908d4911bca4a01f6f0
refs/heads/master
<repo_name>abrahamdio/expressgulpstarter<file_sep>/src/js/services/auth.service.js export default class Auth { constructor(AppConstants, $http, $window) { 'ngInject'; this.isLoggedInBool = false; this._AppConstants = AppConstants; this._$http = $http; this._$window = $window; this.model = { isLoggedInBool: true } } saveToken(token){ this.isLoggedInBool = true; return this._$window.localStorage['flapper-news-token'] = token; } getToken(){ return this._$window.localStorage['flapper-news-token']; } isLoggedIn(){ let token = this.getToken(); if(token){ let payload = JSON.parse(this._$window.atob(token.split('.')[1])); let res = payload.exp > Date.now() / 1000; this.isLoggedInBool = res; return res } else { this.isLoggedInBool = false; return false; } } currentUser(){ if(this.isLoggedIn()){ let token = this.getToken(); let payload = JSON.parse(this._$window.atob(token.split('.')[1])); return payload.username; } } register(user){ return this._$http.post('/register', user).then( (res) => { this.saveToken(res.data.token); } ); } logIn(user){ return this._$http.post('/login', user).then( (res) => { this.saveToken(res.data.token); } ); } logOut(){ this.isLoggedInBool = false; this.model.isLoggedInBool = false; this._$window.localStorage.removeItem('flapper-news-token'); }; }<file_sep>/README.md # MEAN with Gulp Starter Code ## Installation ``` git clone <EMAIL>:abrahamdio/mean-gulp-starter.git cd mean-gulp-starter npm install ``` ## Running the server `npm start` - default to <http://localhost:3000> ## Running front end build with Gulp `gulp`- Build and watch all files in `src/` `gulp build` - Production build (i.e. without watcher) ## Citation Most of the codes are taken from Thinkster tutorial. https://thinkster.io/angularjs-es6-tutorial#setting-up-a-boilerplate-project-for-angular-1-5-es6 https://thinkster.io/mean-stack-tutorial These are the two tutorials that I used to create MEAN Stack with Angular ES6 Components and Gulp. <file_sep>/src/js/home/home.controller.js class HomeCtrl { constructor(AppConstants, Auth, Posts) { 'ngInject'; this.appName = AppConstants.appName; this._Auth = Auth; this._Posts = Posts; this.isLoggedIn = Auth.isLoggedIn(); this.posts = this._Posts.posts; } addPost(){ // check for empty string if (!this.formData.title || this.formData.title === '') {return;} this._Posts.create({ title: this.formData.title, link: this.formData.link }) this.formData.title = ''; this.formData.link = ''; } incrementUpvotes(post){ this._Posts.upvote(post); } } export default HomeCtrl;
0117bd1b50910232bcaf007636655ec66ae997a5
[ "JavaScript", "Markdown" ]
3
JavaScript
abrahamdio/expressgulpstarter
331b74bd25a46f6666deaab7b4592f36b40fb8d5
cef7ebbcce0c6116435e7b5c765ee2fce88af99d
refs/heads/master
<file_sep>package com.example.demo.exception; public class TrainerNotExistedException extends RuntimeException{ public TrainerNotExistedException(String message) { super(message); } } <file_sep>package com.example.demo.exception; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import java.util.Objects; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ErrorResult> handle(MethodArgumentNotValidException exception) { String message = Objects.requireNonNull(exception.getBindingResult().getFieldError()).getDefaultMessage(); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(ErrorResult.builder().code(HttpStatus.BAD_REQUEST.value()).message(message).build()); } @ExceptionHandler({TraineeNotExistedException.class, TrainerNotExistedException.class}) public ResponseEntity<ErrorResult> handle(RuntimeException exception){ return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(ErrorResult.builder().code(HttpStatus.NOT_FOUND.value()).message(exception.getMessage()).build()); } } <file_sep>package com.example.demo.api; import com.example.demo.domain.Trainer; import com.example.demo.dto.TrainerDto; import com.example.demo.service.TrainerService; import org.springframework.http.HttpStatus; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @RestController @RequestMapping("/trainers") @Validated public class TrainerController { private final TrainerService trainerService; public TrainerController(TrainerService trainerService) { this.trainerService = trainerService; } @PostMapping @ResponseStatus(HttpStatus.CREATED) public TrainerDto addTrainer(@RequestBody @Valid Trainer trainer) { return trainerService.addTrainee(trainer); } @GetMapping public List<TrainerDto> getTrainees() { return trainerService.getTrainers(); } @DeleteMapping("/{trainer_id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteTrainee(@PathVariable Long trainer_id) { trainerService.deleteTraineeById(trainer_id); } } <file_sep>package com.example.demo.domain; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.NotNull; @Data @AllArgsConstructor @NoArgsConstructor @Builder public class Trainer { @NotNull(message = "姓名不能为空") private String name; } <file_sep>package com.example.demo.domain; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; @Data @AllArgsConstructor @NoArgsConstructor @Builder public class Trainee { @NotNull(message = "姓名不能为空") private String name; @NotNull(message = "办公室不能为空") private String office; @NotNull(message = "邮箱不能为空") @Email(message = "邮箱不合法") private String email; @NotNull(message = "zoomId不能为空") private String zoomId; @NotNull(message = "Github账户不能为空") private String github; }
789bdd949c9588026769942aa7b5a26c247f7fa6
[ "Java" ]
5
Java
cleoxiii/B-final-quiz
13c92f734fc16fd42efd16be2d38ea28e63a43e7
e0c79d88f30ffa8647c263e1835c9076fb164bd1
refs/heads/master
<repo_name>mrexitium/Exam-project-2016<file_sep>/page-kontakt.php <?php get_header(); ?> <div class="content"> <!-- Div for everything between header and footer --> <div class="headline"> <div class="color-box"></div> <h1>Kontakt</h1> </div> <div class="loop-wrapper"> <!-- Sample of The Loop to use for later --> <?php $query = new WP_Query(array( 'category_name' => 'contact' ) ); while($query->have_posts()) : $query->the_post(); ?> <!-- Shorthand while loop that takes the posts that fits the criteria 3 lines up --> <div class="post-content-contact"> <div class="loop-content-contact"> <h1> <?php the_title(); ?> </h1> <p> <?php the_content(); ?> </p> </div> </div> <?php endwhile; wp_reset_postdata(); ?> <!-- Important to reset the postdata so another custom loop can be made later --> <?php $query2 = new WP_Query(array( 'category_name' => 'contactpicture' ) ); while($query2->have_posts()) : $query2->the_post(); ?> <!-- Shorthand while loop that takes the posts that fits the criteria 3 lines up --> <div class="contact-picture"> <a href="<?php echo get_post_meta($post->ID, 'link', true); ?> "><?php the_post_thumbnail(); ?></a> <h1> <a href="<?php echo get_post_meta($post->ID, 'link', true); ?>"><?php the_title(); ?></a> </h1> </div> <?php endwhile; wp_reset_postdata(); ?> <!-- Important to reset the postdata so another custom loop can be made later --> </div><!-- loop-wrapper --> </div> <!-- End of .content --> <div id='map' style='width: 100%; height: 500px;'></div> <script> mapboxgl.accessToken = '<KEY>'; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/douvanjou/cio9q8imc004avemcqvono1va', center: [10.353518099999974, 55.40931699999999], zoom: 13, hash: true }); map.on('load', function () { map.addSource("markers", { "type": "geojson", "data": { "type":"FeatureCollection", "features":[{ "type":"Feature", "properties":{ "id":"marker-iod3cl120", "title":"<NAME>", "description":"Adresse: TarupgÃ¥rdsvej 3, 5210 Odense <br>\nTelefon: 66 17 98 64", "marker-size":"large", "marker-color":"#e7857f", "marker-symbol":"" }, "geometry":{ "coordinates":[10.353523,55.409392], "type":"Point" }, }], } }); map.addLayer({ "id": "markers", "type": "symbol", "source": "markers", "layout": { "icon-image": "marker-15", "text-field": "{title}", "text-font": ["Open Sans Regular", "Arial Unicode MS Bold"], "text-offset": [0, 0.6], "text-anchor": "top" } }); map.scrollZoom.disable(); }); </script> <?php get_footer(); ?><file_sep>/page-undervisning.php <?php get_header(); ?> <div class="content"> <!-- Div for everything between header and footer --> <div class="headline"> <div class="color-box"></div> <h1>Undervisning</h1> </div> <!-- Sample of The Loop to use for later --> <?php $query = new WP_Query(array( 'category_name' => 'teaching' ) ); while($query->have_posts()) : $query->the_post(); ?> <!-- Shorthand while loop that takes the posts that fits the criteria 3 lines up --> <div class="post-content"> <div class="loop-content"> <h1> <?php the_title(); ?> </h1> <p> <?php the_content(); ?> </p> </div> <?php $post_image_id = get_post_thumbnail_id($post_to_use->ID); if ($post_image_id) { $thumbnail = wp_get_attachment_image_src( $post_image_id, 'post-thumbnail', false); if ($thumbnail) (string)$thumbnail = $thumbnail[0]; } ?> <div class="photo-content" style="background: url('<?php echo $thumbnail; ?>') no-repeat; background-position: top center; background-size: auto 100%;"> </div> </div> <?php endwhile; wp_reset_postdata(); ?> <!-- Important to reset the postdata so another custom loop can be made later --> <div class="headline"> <div class="color-box"></div> <h1>Elevheste</h1> </div> </div> <!-- End of .content --> <div class="modal"></div> <?php get_footer(); ?><file_sep>/functions.php <?php add_filter('show_admin_bar', '__return_false'); add_theme_support('post-thumbnails'); register_nav_menus([ 'left-nav' => 'left menu', 'right-nav' => 'right menu', ]); add_action( 'wp_enqueue_scripts', 'my_enqueue_assets' ); function my_enqueue_assets() { wp_enqueue_style( 'style', get_template_directory_uri().'/style.css' ); wp_enqueue_script( 'ajax-lazy-load', get_stylesheet_directory_uri() . '/scripts/js.js', array( 'jquery' ), '1.0', true ); wp_enqueue_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js' ); } add_action("wp_ajax_lazy_load", "lazy_load"); add_action("wp_ajax_nopriv_lazy_load", "lazy_load"); function lazy_load() { $offset = $_GET['offset']; $args = array( 'category_name' => 'horses', 'posts_per_page' => 2, 'orderby' => 'date', 'order' => 'ASC', 'offset' => $offset, ); $query = new WP_Query( $args ); for ($i=0; $i < count($query->posts); $i++) { $query->posts[$i]->post_content = apply_filters('the_content', $query->posts[$i]->post_content); $query->posts[$i]->thumbnail = get_the_post_thumbnail($query->posts[$i]->ID); } wp_send_json_success($query->posts); wp_die(); } <file_sep>/page-opstaldning.php <?php get_header(); ?> <div class="content"> <div class="headline"> <div class="color-box color-livery"></div> <h1>Opstaldning</h1> </div> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div class="image-wrapper"> <?php the_post_thumbnail(); ?> </div> <div class="livery-content"> <?php the_content(); ?> </div> <?php endwhile; else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?> </div><!-- .content --> <?php get_footer(); ?><file_sep>/footer.php <footer id="site-footer"> <div class="social-wrapper"> <div class="social-media"> <a href="https://www.facebook.com/pages/Fyens-Rideklub/185098101501203?fref=ts"><img src="<?php echo get_template_directory_uri(); ?>/images/facebook.png" alt="facebook"></a> <a href="https://www.facebook.com/pages/Fyens-Rideklub/185098101501203?fref=ts"><p>Like på Facebook</p></a> </div> <div class="social-media"> <a href="https://www.instagram.com/fyensrideklub/"><img src="<?php echo get_template_directory_uri(); ?>/images/instagram.png" alt="instagram"></a> <a href="https://www.instagram.com/fyensrideklub/"><p>Følg os på Instagram</p></a> </div> <div class="social-media"> <a href="<?php echo get_template_directory_uri(); ?>/contact"><img src="<?php echo get_template_directory_uri(); ?>/images/contact.png" alt="email"></a> <a href="<?php echo get_template_directory_uri(); ?>/contact"><p>Kontakt os på Email</p></a> </div> </div> </footer> </div> <!-- End of #site-wrapper --> <?php wp_footer(); ?> </body> </html><file_sep>/index.php <?php get_header(); ?> <div class="vidya"> <div id="vid"> <video autoplay id="bgvid" loop class="fullscreen-bg__video"> <source src="<?php echo get_template_directory_uri(); ?>/videobackground.mp4" type="video/webm"> </video> </div> </div> <?php $query = new WP_Query(array( 'category_name' => 'instagram' ) ); while($query->have_posts()) : $query->the_post(); ?> <!-- Shorthand while loop that takes the posts that fits the criteria 3 lines up --> <?php the_content(); ?> <?php endwhile; wp_reset_postdata(); ?> <!-- Important to reset the postdata so another custom loop can be made later --> <?php get_footer(); ?> <file_sep>/page-om-os.php <?php get_header(); ?> <div class="content"> <!-- Div for everything between header and footer --> <div class="headline-about"> <h1>Om os</h1> </div> <!-- HISTORY --> <!-- Sample of The Loop to use for later --> <?php $query = new WP_Query(array( 'category_name' => 'about', 'order' => 'asc', 'orderby' => 'date',/*This is where you select what criteria your output should have*/ )); while($query->have_posts()) : $query->the_post(); ?> <!-- Shorthand while loop that takes the posts that fits the criteria 3 lines up --> <div class="post-content-about"> <div class="loop-content-about"> <h3> <?php the_title(); ?> </h3> <div class="color-box-history"></div> <p> <?php the_content(); ?> </p> </div> <?php $post_image_id = get_post_thumbnail_id($post_to_use->ID); if ($post_image_id) { $thumbnail = wp_get_attachment_image_src( $post_image_id, 'post-thumbnail', false); if ($thumbnail) (string)$thumbnail = $thumbnail[0]; } ?> <div class="photo-content-about" style="background: url('<?php echo $thumbnail; ?>') no-repeat; background-position: center center; background-size: contain;"> </div> </div> <?php endwhile; wp_reset_postdata(); ?> <!-- Important to reset the postdata so another custom loop can be made later --> <div class="staff-header"> <h4>Personale</h4> <div class="color-box-staff"></div> </div> <!-- STAFF --> <div class="loop-content-staff"><?php $query = new WP_Query([ 'category_name' => 'staff', 'order' => 'asc', 'orderby' => 'date',/*This is where you select what criteria your output should have*/ ]); while($query->have_posts()) : $query->the_post(); ?> <!-- Shorthand while loop that takes the posts that fits the criteria 3 lines up --> <div class="post-content-staff"> <div class="photo-content-staff"> <div class="hover"> <?php the_post_thumbnail(); ?> </div> </div> <h2> <?php the_title(); ?> </h2> <p> <?php the_content(); ?> </p> </div> <?php endwhile; wp_reset_postdata(); ?> <!-- Important to reset the postdata so another custom loop can be made later --></div> <!-- SPONSORS --> <div class="loop-content-sponsors"><?php $query = new WP_Query([ 'category_name' => 'sponsors', 'order' => 'asc', 'orderby' => 'date',/*This is where you select what criteria your output should have*/ ]); while($query->have_posts()) : $query->the_post(); ?> <!-- Shorthand while loop that takes the posts that fits the criteria 3 lines up --> <div class="post-content-sponsors"> <h4> <?php the_title(); ?> </h4> <div class="color-box-sponsors"></div> <p> <?php the_content(); ?> </p> </div> <?php endwhile; wp_reset_postdata(); ?> <!-- Important to reset the postdata so another custom loop can be made later --></div> <div class="loop-content-sponsors-logo"><?php $query = new WP_Query([ 'category_name' => 'sponsors-logo', 'order' => 'asc', 'orderby' => 'date',/*This is where you select what criteria your output should have*/ ]); while($query->have_posts()) : $query->the_post(); ?> <!-- Shorthand while loop that takes the posts that fits the criteria 3 lines up --> <div class="post-content-sponsors-logo"> <?php the_post_thumbnail(); ?> </div> <?php endwhile; wp_reset_postdata(); ?> <!-- Important to reset the postdata so another custom loop can be made later --></div> </div> <!-- End of .content --> <?php get_footer(); ?><file_sep>/page-events.php <?php get_header(); ?> <div class="content"> <!-- Div for everything between header and footer --> <div class="headline-events"> <div class="color-box-events"></div> <h1>EVENTS &<br/>Konkurrencer</h1> </div> <!-- Sample of The Loop to use for later --> <?php $query = new WP_Query(array( 'category_name' => 'competitions' ) ); while($query->have_posts()) : $query->the_post(); ?> <!-- Shorthand while loop that takes the posts that fits the criteria 3 lines up --> <div class="post-content-events"> <div class="loop-content-events center"> <h2> <?php the_title(); ?> </h2> <p> <?php the_excerpt(); ?> </p> <div class="see open hvr-outline-in" >Se mere</div> </div> <?php $post_image_id = get_post_thumbnail_id($post_to_use->ID); if ($post_image_id) { $thumbnail = wp_get_attachment_image_src( $post_image_id, 'post-thumbnail', false); if ($thumbnail) (string)$thumbnail = $thumbnail[0]; } ?> <div class="photo-content-events" style="background: url('<?php echo $thumbnail; ?>') no-repeat; background-position: top center; background-size: cover"> <div class="open-content hidden"> <div class="more-description"> <div class="colour-box-description"> </div> <div class="content-description"> <p> <?php the_content(); ?> </p> </div> </div> </div> </div> </div> <?php endwhile; wp_reset_postdata(); ?> <!-- Important to reset the postdata so another custom loop can be made later --> </div> <!-- End of .content --> <?php get_footer(); ?><file_sep>/header.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fyens Rideklub</title> <?php wp_head(); ?> <!-- Insert below the logo url for the mini logo that will be shown on the tab in the browser--> <link rel="shortcut icon" type="image/x-icon" href="<?php echo get_template_directory_uri(); ?>/images/logo.png"> <!-- Insert all fonts below this --> <link href='https://fonts.googleapis.com/css?family=EB+Garamond' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Playfair+Display+SC' rel='stylesheet' type='text/css'> <script src='https://api.mapbox.com/mapbox-gl-js/v0.18.0/mapbox-gl.js'></script> <link href='https://api.mapbox.com/mapbox-gl-js/v0.18.0/mapbox-gl.css' rel='stylesheet' /> <link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/style.css"> </head> <body> <div id="site-wrapper"> <!-- Header with the navigation --> <header class="site-header"> <nav class="site-nav"> <?php wp_nav_menu(['theme_location' => 'left-nav']); ?> <div class="logo-wrapper"> <a href="http://fyensrideklub.jespers-design.dk/"><img src="<?php echo get_template_directory_uri(); ?>/images/logo.png" alt="Logo"></a> </div> <?php wp_nav_menu(['theme_location' => 'right-nav']); ?> </nav> </header><file_sep>/README.md # Exam-project-2016 ##3rd semester exam project ## Setup GIT ### Mac users #### Step 1 Install Git on your computer with this link ``` http://code.google.com/p/git-osx-installer/downloads/list?can=3 ``` #### Step 2 Go to [github](http://github.com/) and create a user. After that tell me your Github user name so I can add you to the project. #### Step 3 In the terminal go to your local project folder on your local server, and use this command: ``` $ git init ``` Then clone the repository with ``` $ git clone https://github.com/mrexitium/Exam-project-2016.git ``` Then you can set up Git so it is easier to use by running these commands ``` $ git config --global user.name "github username" $ git config --global user.email <EMAIL> ``` You are now ready to do some work! #### Step 4 When you start something new start by checking if your local code is up to date with the online repository by using ``` $ git pull ``` Then you can start working on a file, whenever you want to save that file you use ``` $ git add * $ git pull $ git commit -m "Message description of what you changed" $ git push origin master ``` You can at all times check which files you have changed since your last commit by using ``` $ git status ``` Read by Greta, and Jesper and Emilia ## Setting up wordpress #### Step 1 Install Wordpress on the server, set up database and put the files in the theme folder. #### Step 2 Log in as admin, enable the theme and create the following pages: ``` om os, kontakt, events, opstaldning, undervisning ``` #### Step 3 Go to Appearance - menu and create a menu called ``` left menu ``` In this menu put the pages home, about and teaching, and set its position as left menu. #### Step 4 Go to Appearance - menu and create a menu called ``` right menu ``` In this menu put the pages livery, events and contact, and set its position as right menu. #### Step 5 - Home page Go to plugins and download the plugin Instagram Feed. Activate it, go to Settings and login to instagram. Uncheck the header, follow button and load more buttons, set number of photos to 4 and columns to 4. Add a new post called with the category ``` instagram ``` In the content field of this post write ``` [instagram-feed] ``` #### Step 6 - About page ##### History part Create a new post called 'Historie', and give it the category ``` about ``` then add an image as the featured img. And add the history of the company in the content field. ##### Staff part For each staff member you want, create a new post with the category ``` staff ``` and put their name as the title, their job as the content and their photo as the featured image. ##### Sponsor part Add a new post with the title ``` Sponsorer ``` and the content should be your text about sponsors, category has to be ```sponsors```. Add one new post for each sponsor logo you want to show as featured img with the category ```sponsors-logo``` #### Step 7 Teaching page. Add 2 new posts with category 'teaching' and give them a landscape style foto as thumbnail, aswell as a title and content. Add posts for all the horses with thumbnail pictures and category 'horses'. #### Step 8 Opstaldnings page. Go to the opstaldning page and put in text on the content box, and give it a thumbnail picture. #### Step 9 Events page. For each event create a new post with the date as the title, the description as content, and a short description as the excerpt, remember to set a thumbnail picture aswell. The category of these posts must be ```competitions```. #### Step 10 Contact page @@@@ more content later <file_sep>/scripts/js.js (function($) { var isActive = false; $(window).scroll(function(){ if ((window.location.href == 'http://jespers-design.dk/fyensrideklub/undervisning/') || (window.location.href == 'http://fyensrideklub.jespers-design.dk/undervisning/')) { if (!isActive && $(window).scrollTop() == $(document).height() - $(window).height()){ isActive = true; loadMorePictures(); } } }); offset = ""; offsetNum = ""; function loadMorePictures() { $.ajax({ url: 'http://jespers-design.dk/fyensrideklub/wp-admin/admin-ajax.php' + offset + offsetNum, type: 'post', data: { action: 'lazy_load' }, success: function( result ) { isActive = false; for (var i = 0; i < result.data.length; i++) { console.log(result.data[i]); var content = result.data[i].post_content; var thumbnail = result.data[i].thumbnail; $('.content').append('<div class="horse">' + thumbnail + '<div class="horsetext"><p>' + content + '</p></div></div>'); } if (offset == "") { offset = "?offset="; offsetNum = 2; } else { offset = "?offset="; offsetNum += 2; } } }) } })(jQuery); jQuery('.open').click(function () { jQuery(this).toggleText('Se Mindre', 'Se Mere'); jQuery(this).closest('.post-content-events').find('.open-content').fadeToggle(500); }); jQuery.fn.toggleText = function(t1, t2){ if (this.text() == t1) this.text(t2); else this.text(t1); return this; }; jQuery(".photo-content-staff").mouseenter(function(){ jQuery(this).siblings('h2').css("color","#B2A897"); jQuery(this).siblings('p').css({"color": "#B2A897", "border-bottom": "1px solid #B2A897"}); }); jQuery(".photo-content-staff").mouseleave(function(){ jQuery(this).siblings('h2').css("color","#000000"); jQuery(this).siblings('p').css({"color": "#000", "border-bottom": "0px"}); }); jQuery(document).on({ ajaxStart: function() { jQuery('body').addClass("loading"); }, ajaxStop: function() { jQuery('body').removeClass("loading"); } });
3e8d719d618dfb4a0274817d5f8594c136defa13
[ "Markdown", "JavaScript", "PHP" ]
11
PHP
mrexitium/Exam-project-2016
1b63cd22f5d1bd8af43ee4ec9789448c21a50c20
fea8352a25de9b23fbb0f7bac7cf85e6be01e024
refs/heads/master
<file_sep># Lab2_DSA_2020 Main File in SRC <file_sep>package FRAMEWORK; import javax.swing.SwingUtilities; import javax.swing.UIManager; public class MainApp { public static void main (String[] args) { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); } catch (Exception e) { System.out.println(e.toString()); } SwingUtilities.invokeLater( new Runnable() { @Override public void run() { MainFrame mainFrame = new MainFrame("DSA-2020 Baseline App"); mainFrame.setVisible(true); } }); } }<file_sep>package FRAMEWORK; import GEOM.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.BorderFactory; import javax.swing.JPanel; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; public class WorkingPanel extends JPanel implements MouseMotionListener, MouseListener, ItemListener, ActionListener, ComponentListener { // Create an instance of SpaceMapping Point2D[] pointList = null; SpaceMapping spaceMapping = new SpaceMapping(); Axis axis = new Axis (spaceMapping.getLogViewport()); Graph graph = null; public WorkingPanel () { this.setBorder(BorderFactory.createEtchedBorder()); this.addMouseListener(this); this.addMouseMotionListener(this); this.addComponentListener(this); } @Override public void paintComponent (Graphics g) { super.paintComponent(g); // if(this.axis != null) this.axis.draw(g, spaceMapping); if(this.pointList != null){ for(int idx=0; idx < this.pointList.length; idx++) this.pointList[idx].draw(g, spaceMapping); } if(this.graph != null) this.graph.draw(g, spaceMapping); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == MainFrame.btnCircle){ MainFrame.infoPanel.println("action: draw Circle"); } else if(e.getSource() == MainFrame.btnRect){ MainFrame.infoPanel.println("action: draw Rectangle"); } else if(e.getSource() == MainFrame.btnGraph){ Graph graph; graph = Graph.sin(50, -10, 10,this.spaceMapping.step()); graph.setMode(Graph.GraphMode.SCATTER); this.axis.addGraph(graph, Color.red, 2); // this.axis.addGraph(Graph.quadratic(1, 0, 0, -10, 10, this.spaceMapping.step()), Color.blue, 3); // graph = new Graph(Point2D.linear(100, 1.0, 0.0, -10, 10)); this.axis.addGraph(graph, Color.cyan, 1); //update viewport this.spaceMapping.updateLogViewPort(this.axis.getViewPort()); this.repaint(); } } @Override public void itemStateChanged(ItemEvent e) { int state = e.getStateChange(); if (state == ItemEvent.SELECTED) { MainFrame.infoPanel.println("Selected"); MainFrame.btnSelect.setText("Selecting"); } else { MainFrame.infoPanel.println("DeSelected"); MainFrame.btnSelect.setText("Drawing"); } } @Override public void mouseClicked(MouseEvent e) { //condition of double click if((e.getClickCount() == 2) && !e.isConsumed()) { Point2D logPoint = this.spaceMapping.device2Logic(e.getX(), e.getY()); String message = String.format("mouseClicked: Device (x,y) = (%d, %d);" + "Logic (x,y) = (%6.2f, %6.2f) ", e.getX(), e.getY(), logPoint.getX(), logPoint.getY()); MainFrame.infoPanel.println(message); e.consume(); //stop telling the others listener when this event happened } else { Point2D logPoint = this.spaceMapping.device2Logic(e.getX(), e.getY()); String message = String.format("mouseDoubled Clicked: Device (x,y) = (%d, %d);" + "Logic (x,y) = (%6.2f, %6.2f) ", e.getX(), e.getY(), logPoint.getX(), logPoint.getY()); MainFrame.infoPanel.println(message); } } @Override public void mousePressed(MouseEvent e) { Point2D logPoint = this.spaceMapping.device2Logic(e.getX(), e.getY()); String message = String.format("mousePressed: Device (x,y) = (%d, %d);" + "Logic (x,y) = (%6.2f, %6.2f) ", e.getX(), e.getY(), logPoint.getX(), logPoint.getY()); MainFrame.infoPanel.println(message); } @Override public void mouseReleased(MouseEvent e) { Point2D logPoint = this.spaceMapping.device2Logic(e.getX(), e.getY()); String message = String.format("mouseReleased: Device (x,y) = (%d, %d);" + "Logic (x,y) = (%6.2f, %6.2f) ", e.getX(), e.getY(), logPoint.getX(), logPoint.getY()); MainFrame.infoPanel.println(message); } @Override public void mouseEntered(MouseEvent e) { Point2D logPoint = this.spaceMapping.device2Logic(e.getX(), e.getY()); String message = String.format("mouseEntered: Device (x,y) = (%d, %d);" + "Logic (x,y) = (%6.2f, %6.2f) ", e.getX(), e.getY(), logPoint.getX(), logPoint.getY()); MainFrame.infoPanel.println(message); } @Override public void mouseExited(MouseEvent e) { Point2D logPoint = this.spaceMapping.device2Logic(e.getX(), e.getY()); String message = String.format("mouseExited: Device (x,y) = (%d, %d);" + "Logic (x,y) = (%6.2f, %6.2f) ", e.getX(), e.getY(), logPoint.getX(), logPoint.getY()); MainFrame.infoPanel.println(message); } @Override public void mouseDragged(MouseEvent e) { Point2D logPoint = this.spaceMapping.device2Logic(e.getX(), e.getY()); String message = String.format("mouseDragged: Device (x,y) = (%d, %d);" + "Logic (x,y) = (%6.2f, %6.2f) ", e.getX(), e.getY(), logPoint.getX(), logPoint.getY()); MainFrame.infoPanel.println(message); } @Override public void mouseMoved(MouseEvent e) { Point2D logPoint = this.spaceMapping.device2Logic(e.getX(), e.getY()); String message = String.format("mouseMoved: Device (x,y) = (%d, %d);" + "Logic (x,y) = (%6.2f, %6.2f) ", e.getX(), e.getY(), logPoint.getX(), logPoint.getY()); MainFrame.infoPanel.println(message); } @Override public void componentResized(ComponentEvent e) { Dimension size = this.getSize(); int xGap = 50, yGap = 20; this.spaceMapping.updateDevViewPort(xGap, size.width - 2*xGap, yGap, size.height-2*yGap); } @Override public void componentMoved(ComponentEvent e) { // throw new UnsupportedOperationException("Not supported yet."); // addComponentListener(this); } @Override public void componentShown(ComponentEvent e) { // throw new UnsupportedOperationException("Not supported yet."); // addComponentListener(this); } @Override public void componentHidden(ComponentEvent e) { // throw new UnsupportedOperationException("Not supported yet."); // addComponentListener(this); } }
adda2e2c304bf2d6074d83e6ed6c0aad91f9be72
[ "Markdown", "Java" ]
3
Markdown
marionguyen20/Lab2_DSA_2020
9c1eb78352751fe1e8bda41642aeed48c5e25959
7e58c171da2f4a437a7624549b27a56aebbf1e0a
refs/heads/master
<file_sep>'use strict'; /** * @ngInject */ function OnConfig($stateProvider, $locationProvider, $urlRouterProvider) { $locationProvider.html5Mode(true); $stateProvider .state('seasons', { url: '/', controller: 'SoccerSeasonsCtrl as vm', templateUrl: 'soccerseasons.html', title: 'Soccer Seasons', resolve: { /** * @ngInject */ seasons: function(SoccerSeasonsSvc) { return SoccerSeasonsSvc.getSeasons(); } } }) .state('results', { url: '/soccerseasons/:seasonId/fixtures', controller: 'SeasonResultsCtrl as vm', templateUrl: 'seasonresults.html', title: 'Season Results', resolve: { /** * @ngInject */ results: function(SoccerSeasonsSvc, $stateParams) { var seasonId = $stateParams.seasonId; if (seasonId) { return SoccerSeasonsSvc.getResults(seasonId); } else { return false; } } } }); $urlRouterProvider.otherwise('/'); } module.exports = OnConfig;<file_sep>'use strict'; var controllersModule = require('./_index'); /** * @ngInject */ function SeasonResultsCtrl(results) { angular.extend(this, { page: 'Season Results', results: results }); } controllersModule.controller('SeasonResultsCtrl', SeasonResultsCtrl);<file_sep>'use strict'; var AppSettings = { appTitle: 'JS Competency Test', apiUrl: 'http://api.football-data.org/alpha', apiKey: '<KEY>' }; module.exports = AppSettings;<file_sep>'use strict'; var controllersModule = require('./_index'); /** * @ngInject */ function SoccerSeasonsCtrl(seasons, SoccerSeasonsSvc, $state) { angular.extend(this, { page: 'Soccer Seasons', seasons: seasons, getResults: function(seasonUrl) { var idFromUrl = seasonUrl.substr(seasonUrl.lastIndexOf('/') + 1); var options = {}; $state.go('results', {seasonId: idFromUrl}, options); } }); } controllersModule.controller('SoccerSeasonsCtrl', SoccerSeasonsCtrl);<file_sep>'use strict'; var servicesModule = require('./_index.js'); /** * @ngInject */ function SoccerSeasonsSvc($q, $http, AppSettings) { var service = {}; service.getSeasons = function() { var deferred = $q.defer(); $http.get(AppSettings.apiUrl + '/soccerseasons') .success(function(data) { deferred.resolve(data); }) .error(function(err, status) { deferred.reject(err, status); }); return deferred.promise; }; service.getResults = function(seasonId) { var deferred = $q.defer(); $http.get(AppSettings.apiUrl + '/soccerseasons/' + seasonId + '/fixtures') .success(function(data) { deferred.resolve(data); }) .error(function(err, status) { deferred.reject(err, status); }); return deferred.promise; }; return service; } servicesModule.service('SoccerSeasonsSvc', SoccerSeasonsSvc);<file_sep>## Getting up and running 1. Clone this repo from `https://github.com/rtorino/troll-football.git` 2. Run `npm install` from the root directory 3. Run `gulp dev` (may require installing Gulp globally `npm install gulp -g`) 4. Your browser will automatically be opened and directed to the browser-sync proxy address
d04c03797aa856e5a5a0829a21d2f6a7db119dc1
[ "JavaScript", "Markdown" ]
6
JavaScript
rtorino/troll-football
0023d319cafdf6ba12ade6046ddbf4212b680f84
bd794b6e09cfce7afc265e6c4f67580de1082f10
refs/heads/master
<file_sep>package sgo // switch nanoSecond to milliSecond func MilliSecond(nanoSecond int) (milliSecond int) { milliSecond = nanoSecond / 1e6 return }
bd161322a4f8ed696b4a43ae5fe21fd0cec5514b
[ "Go" ]
1
Go
sovcer/sgo
a3e203bf8f6f57e464f7800a408d230c755587e0
51baba9591a640813524b3d6b6feffcbe87fa8ed
refs/heads/master
<file_sep>let start = 1900; let end = 2016; for (let y = start; y <= end; y++) { if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) { console.log(y) } }<file_sep>let users = [ {name: 'Вася', password: '<PASSWORD>', login: 'Vasya'}, {name: 'Петя', password: '<PASSWORD>', login: 'Petya'}, {name: 'Дима', password: '<PASSWORD>', login: 'Dima'}, {name: 'Аня', password: '<PASSWORD>', login: 'Anna'}, {name: 'Таня', password: '<PASSWORD>', login: 'Tanya'} ]; let customAnswer = { login: prompt('Введите свой логин'), password: prompt('Введите пароль ') }; if (customAnswer.login === '' || customAnswer.password === '') { alert("Вы не ввели логин или пароль"); } // Развёрнутый код /*let logged = []; for (let i = 0; i < users.length; i++) { const filtered = (function (user) { return customAnswer.login === user.login && customAnswer.password === user.password; })(users[i]); if (filtered) { logged.push(users[i]); } }*/ /*function array_filter(list, filterCallback) { let result = []; for (let i = 0; i < list.length; i++) { if (filterCallback(list[i])) { result.push(list[i]); } } return result; } let logged = array_filter(users, function (user) { return customAnswer.login === user.login && customAnswer.password === user.password });*/ // Тоже самое - коротко const logged = users.filter(function (user) { return customAnswer.login === user.login && customAnswer.password === user.password }); if (logged.length === 1) { alert('Привет, ' + logged[0].name); } else { alert('Такого пользователя нет :( '); } <file_sep>let users = [ {name: 'Вася', password: '<PASSWORD>', login: 'Vasya'}, {name: 'Петя', password: '<PASSWORD>', login: 'Petya'}, {name: 'Дима', password: '<PASSWORD>', login: 'Dima'}, {name: 'Аня', password: '<PASSWORD>', login: 'Anna'}, {name: 'Таня', password: '<PASSWORD>', login: 'Tanya'} ]; let customAnswer = { login: prompt('Введите свой логин'), password: prompt('Введите пароль ') }; if (customAnswer.login === '' || customAnswer.password === '') { alert("Вы не ввели логин или пароль"); } for (let i = 0; i < users.length; i++) { if (customAnswer.login === users[i].login && customAnswer.password === users[i].password) { alert('Привет, ' + users[i].name); break; } else if (i === users.length - 1) { alert('Такого пользователя нет :( '); } } <file_sep>let firstNumber = prompt("Введите число"); let secondNumber = prompt("Ввведите ещё одно число"); if (!parseInt(firstNumber) || !parseInt(secondNumber)) { alert('Вы не ввели число') } else if (firstNumber > secondNumber) { alert('Первое число больше второго') } else if (secondNumber > firstNumber) { alert('Второе число больше первого') } else if (firstNumber === secondNumber) { alert('Числа равны') }<file_sep>function getStart() { return function () { let attempts = 1; let number = Math.floor(Math.random() * 1000) + 1; console.log(number); let customNumber = prompt("Попробуйте угадать число от 1 до 1000!"); do { if (customNumber === null) { break; } if (!(customNumber != '' && (customNumber == '0' || Number(customNumber))) ) { customNumber = prompt("Вы не ввели число. Введите число!") } else if (customNumber > number) { customNumber = prompt("Меньше! Попробуйте снова угадать!"); } else if (customNumber < number) { customNumber = prompt("Больше! Попробуйте снова угадать!"); } if (parseInt(customNumber) === parseInt(number)) { alert("Правильно!"); } attempts++; console.log(attempts,customNumber); if (attempts >= 10) { break; } } while (customNumber != number); alert("Конец игры"); } }<file_sep>let name = prompt("Ваше имя?"); let surname = prompt("Ваша фамилия?"); alert(name + ' ' + surname);<file_sep>let start = getStart(); <file_sep>function start() { let customNumber = prompt("Попробуйте угадать число от 0 до 100!"); let number = Math.floor(Math.random() * 100); console.log(number); do { if (customNumber === null) { break; } if (!parseInt(customNumber) || customNumber == '') { customNumber = prompt("Вы не ввели число. Введите число!") } else if (customNumber > number) { customNumber = prompt("Меньше! Попробуйте снова угадать!"); } else if (customNumber < number) { customNumber = prompt("Больше! Попробуйте снова угадать!"); } if (parseInt(customNumber) === parseInt(number)) { alert("Правильно!"); } } while (customNumber != number); alert("Конец игры"); }
b5006e60de941dda7d1f3dfc21a60e5ee4eebbd4
[ "JavaScript" ]
8
JavaScript
Spektra135/Sb
3a3c7d7072377728a61410e35176796820629e95
8ea2c1a5c1370b6689a6ed826e52dedb8db2f11a
refs/heads/master
<repo_name>DimitrisGr/core<file_sep>/org.jcryptool.crypto.flexiprovider.operations/src/org/jcryptool/crypto/flexiprovider/operations/ui/actions/context/messages_de.properties RemoveAction_0=L\u00f6schen RemoveAction_1=L\u00f6schen RemoveAction_2=Operation l\u00f6schen RemoveAction_3=Wollen Sie diese Operation wirklich l\u00f6schen?\nDies kann nicht r\u00fcckg\u00E4ngig gemacht werden! RemoveKeyAction_0=Schl\u00fcssel l\u00f6schen RemoveKeyAction_1=Schl\u00fcssel l\u00f6schen RenameAction_0=Umbenennen RenameAction_1=Umbenennen RenameAction_2=Umbenennen RenameAction_3=Geben Sie einen neuen Namen ein f\u00fcr <file_sep>/org.jcryptool.crypto.flexiprovider.keystore/src/org/jcryptool/crypto/flexiprovider/keystore/actions/messages.properties ImportKeyAction_0=Import ImportKeyAction_1=Import NewKeyPairAction_0=New Key Pair NewKeyPairAction_1=New Key Pair NewKeyPairAction_2=Generating new key pair NewKeyPairAction_3=Key pair generation NewSymmetricKeyAction_0=New Key Pair NewSymmetricKeyAction_1=New Key Pair <file_sep>/org.jcryptool.crypto.flexiprovider.keystore/src/org/jcryptool/crypto/flexiprovider/keystore/actions/messages_de.properties ImportKeyAction_0=Import ImportKeyAction_1=Import NewKeyPairAction_0=Neues Schl\u00fcsselpaar NewKeyPairAction_1=Neues Schl\u00fcsselpaar NewKeyPairAction_2=Neues Schl\u00fcsselpaar wird generiert NewKeyPairAction_3=Generierung Schl\u00fcsselpaar NewSymmetricKeyAction_0=Neues Schl\u00fcsselpaar NewSymmetricKeyAction_1=Neues Schl\u00fcsselpaar <file_sep>/org.jcryptool.crypto.flexiprovider.operations/src/org/jcryptool/crypto/flexiprovider/operations/ui/actions/menu/ExecuteOperationAction.java // -----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2008 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ // -----END DISCLAIMER----- package org.jcryptool.crypto.flexiprovider.operations.ui.actions.menu; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.PlatformUI; import org.jcryptool.core.logging.dialogs.JCTMessageDialog; import org.jcryptool.crypto.flexiprovider.descriptors.IFlexiProviderOperation; import org.jcryptool.crypto.flexiprovider.operations.FlexiProviderOperationsPlugin; import org.jcryptool.crypto.flexiprovider.operations.engines.PerformOperationManager; import org.jcryptool.crypto.flexiprovider.operations.ui.listeners.ISelectedOperationListener; import org.jcryptool.crypto.flexiprovider.types.OperationType; import org.jcryptool.crypto.flexiprovider.types.RegistryType; public class ExecuteOperationAction extends Action { private IFlexiProviderOperation operation; private ISelectedOperationListener listener; public ExecuteOperationAction(ISelectedOperationListener listener) { this.setText(Messages.ExecuteOperationAction_0); this.setToolTipText(Messages.ExecuteOperationAction_1); this.setImageDescriptor(FlexiProviderOperationsPlugin.getImageDescriptor("icons/16x16/start.gif")); //$NON-NLS-1$ this.listener = listener; } public void run() { this.operation = listener.getFlexiProviderOperation(); if (operation == null) { JCTMessageDialog.showInfoDialog(new Status(IStatus.WARNING, FlexiProviderOperationsPlugin.PLUGIN_ID, Messages.ExecuteOperationAction_2)); return; } if (isComplete(operation)) { PerformOperationManager.getInstance().firePerformOperation(operation); } else { showIncompleteDialog(); } } private void showIncompleteDialog() { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), Messages.ExecuteOperationAction_4, Messages.ExecuteOperationAction_5); } private boolean isComplete(IFlexiProviderOperation entry) { // all ciphers need the same parameters (signature almost as well) if (entry.getRegistryType().equals(RegistryType.ASYMMETRIC_BLOCK_CIPHER) || entry.getRegistryType().equals(RegistryType.ASYMMETRIC_HYBRID_CIPHER) || entry.getRegistryType().equals(RegistryType.BLOCK_CIPHER) || entry.getRegistryType().equals(RegistryType.CIPHER) || entry.getRegistryType().equals(RegistryType.SIGNATURE)) { if (entry.getOperation() == null || entry.getOperation().equals(OperationType.UNKNOWN)) { return false; } if (entry.getKeyStoreAlias() == null) { return false; } if (entry.getRegistryType().equals(RegistryType.SIGNATURE)) { if (entry.getInput() == null || entry.getSignature() == null) { return false; } } else { if (entry.getInput() == null || entry.getOutput() == null) { return false; } } } else if (entry.getRegistryType().equals(RegistryType.MAC)) { if (entry.getInput() == null || entry.getOutput() == null) { return false; } if (entry.getKeyStoreAlias() == null) { return false; } } else if (entry.getRegistryType().equals(RegistryType.MESSAGE_DIGEST)) { if (entry.getInput() == null || entry.getOutput() == null) { return false; } } else if (entry.getRegistryType().equals(RegistryType.SECURE_RANDOM)) { if (entry.getOutput() == null) { return false; } } return true; } } <file_sep>/org.jcryptool.editor.text/src/org/jcryptool/editor/text/action/messages_de.properties NewFileJCTTextEditorAction_0=Der Texteditor konnte nicht ge\u00d6ffnet werden. OpenInHexAction_1=Die gew\u00e4hlte Datei konnte nicht im Hexeditor ge\u00d6ffnet werden. OpenInHexAction_2=Es ist kein Hexeditor installiert. OpenInHexAction_errorTitle=Fehler beim \u00d6ffnen des Hexeditors <file_sep>/org.jcryptool.crypto.flexiprovider.keystore/src/org/jcryptool/crypto/flexiprovider/keystore/wizards/messages_de.properties ImportWizard_0=Import ImportWizardPage_0=Import ImportWizardPage_1=Geben Sie die Details des Imports an ImportWizardPage_10=Zertifikat importieren ImportWizardPage_11=<None> ImportWizardPage_12=Passwort ImportWizardPage_13=Geben Sie das Passwort an mit dem der Schl\u00fcssel gesch\u00fctzt werden soll ImportWizardPage_14=Passwort eingeben ImportWizardPage_15=Passwort best\u00e4tigen ImportWizardPage_2=Kontaktdetails ImportWizardPage_3=Geben Sie einen Kontaktnamen ein oder w\u00e4hlen Sie einen aus ImportWizardPage_4=Kontaktnamen ImportWizardPage_5=Import ImportWizardPage_6=Geheimschl\u00fcssel importieren ImportWizardPage_7=Datei ausw\u00e4hlen ImportWizardPage_8=Schl\u00fcsselpaar importieren ImportWizardPage_9=Ausgew\u00e4hlte Datei: NewKeyPairWizard_0=Neues Schl\u00fcsselpaar NewKeyPairWizardPage_0=Neues Schl\u00fcsselpaar NewKeyPairWizardPage_1=Geben Sie die Details des neuen Schl\u00fcsselpaars an NewKeyPairWizardPage_10=Passwort NewKeyPairWizardPage_11=Geben Sie das Passwort an mit dem der Schl\u00fcssel gesch\u00fctzt werden soll NewKeyPairWizardPage_12=Passwort eingeben NewKeyPairWizardPage_13=Passwort best\u0<PASSWORD>igen NewKeyPairWizardPage_2=Kontaktdetails NewKeyPairWizardPage_3=Geben Sie einen Kontaktnamen ein oder w\u00e4hlen Sie einen aus NewKeyPairWizardPage_4=Kontaktname NewKeyPairWizardPage_5=Algorithmus NewKeyPairWizardPage_6=W\u00e4hlen Sie einen Algorithmus aus und legen Sie die Schl\u00fcssell\u00e4nge fest NewKeyPairWizardPage_7=Algorithmus NewKeyPairWizardPage_8=Standardschl\u00fcssell\u00e4nge NewKeyPairWizardPage_9=Schl\u00fcssell\u00e4nge NewSymmetricKeyWizard_0=Neuer symmetrischer Schl\u00fcssel NewSymmetricKeyWizardPage_0=Neuer symmetrischer Schl\u00fcssel NewSymmetricKeyWizardPage_1=Geben Sie die Details des neuen symmetrischen Schl\u00fcssels an NewSymmetricKeyWizardPage_10=Passwort NewSymmetricKeyWizardPage_11=Geben Sie das Passwort an mit dem der Schl\u00fcssel gesch\u00fctzt werden soll NewSymmetricKeyWizardPage_12=Passwort eingeben NewSymmetricKeyWizardPage_13=Passwort best\<PASSWORD> NewSymmetricKeyWizardPage_2=Kontaktdetails NewSymmetricKeyWizardPage_3=Geben Sie einen Kontaktnamen ein oder w\u00e4hlen Sie einen aus NewSymmetricKeyWizardPage_4=Kontaktname NewSymmetricKeyWizardPage_5=Algorithmus NewSymmetricKeyWizardPage_6=W\u00e4hlen Sie einen Algorithmus aus und legen Sie die Schl\u00fcssell\u00e4nge fest NewSymmetricKeyWizardPage_7=Algorithmus NewSymmetricKeyWizardPage_8=Standardschl\u00fcssell\u00e4nge NewSymmetricKeyWizardPage_9=Schl\u00fcssell\u00e4nge <file_sep>/org.jcryptool.editor.text/src/org/jcryptool/editor/text/action/OpenInHexAction.java //-----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2010 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ //-----END DISCLAIMER----- package org.jcryptool.editor.text.action; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IEditorActionDelegate; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPathEditorInput; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.jcryptool.core.operations.IOperationsConstants; import org.jcryptool.core.operations.util.PathEditorInput; /** * The OpenInHexAction class takes an input of an active text editor, shuts the text editor down and * opens it with the hex editor. * * @author amro * @version 0.9.2 */ public class OpenInHexAction implements IEditorActionDelegate { /** The active editor. */ private IEditorPart editor; /** Active workbench page. */ private IWorkbenchPage page; /** * Sets the active editor for the delegate. * * @param action the action proxy that handles presentation portion of the action * @param targetEditor the new editor target */ @Override public void setActiveEditor(IAction action, IEditorPart targetEditor) { editor = targetEditor; if (editor != null) { page = editor.getSite().getPage(); } } /** * Creates the editor input for the hex editor * * @param absolutePath the absolute file path * @return the created editor input */ private IEditorInput createEditorInput(String absolutePath) { return new PathEditorInput(absolutePath); } /** * Performs this action. * * @param action the action proxy that handles the presentation portion of the action */ @Override public void run(IAction action) { IPathEditorInput originalInput = (IPathEditorInput) editor.getEditorInput(); IEditorInput input = createEditorInput(originalInput.getPath().toString()); // check if hex editor plug-in is loaded if (Platform.getBundle(IOperationsConstants.ID_HEX_EDITOR_PLUGIN) != null) { try { page.closeEditor(editor, true); page.openEditor(input, IOperationsConstants.ID_HEX_EDITOR, true); } catch (PartInitException e) { MessageDialog.openError(page.getWorkbenchWindow().getShell(), Messages.OpenInHexAction_errorTitle, Messages.OpenInHexAction_1); } } else { MessageDialog.openError(page.getWorkbenchWindow().getShell(), Messages.OpenInHexAction_errorTitle, Messages.OpenInHexAction_2); } } /** * Notifies this action delegate that the selection in the workbench has changed. * * @param action action the action proxy that handles presentation portion of the action * @param selection the current selection, or <code>null</code> if there is no selection. */ @Override public void selectionChanged(IAction action, ISelection selection) { } } <file_sep>/org.jcryptool.crypto.flexiprovider.integrator/src/org/jcryptool/crypto/flexiprovider/integrator/messages.properties DummyAction.13=Signature stored DummyAction.14=The signature was saved at:\n DummyAction.2=This is a demonstration of the FlexiProvider implementation " DummyAction.3=".\n DummyAction.8=The algorithm could not be found\! DummyAction.encryption=\ encryption DummyAction.error=Error DummyAction.message_authentification_code=\ message authentication code DummyAction.message_digest=\ message digest DummyAction.random_number_generator=\ random number generator DummyAction.signature=\ signature DummyWizardPage.0=Please choose a file where the signature is stored DummyWizardPage.13=Mode: DummyWizardPage.14=Padding: DummyWizardPage.16=Key (Hex) DummyWizardPage.17=Select key: DummyWizardPage.18=Signature file DummyWizardPage.19=File: DummyWizardPage.2=Mode and Padding Scheme DummyWizardPage.20=Open... DummyWizardPage.21=Error DummyWizardPage.22=The file already exists\! DummyWizardPage.24=The file doesn't exists\! DummyWizardPage.27=Filter DummyWizardPage.28=Binary output (into Hexeditor) DummyWizardPage.29=Output size DummyWizardPage.3=Operation DummyWizardPage.30=Size: DummyWizardPage.31=Output as characters out of the following alphabet (into Texteditor) DummyWizardPage.34=Output as numbers in the given range (into Texteditor) DummyWizardPage.35=Pad numbers with zeros DummyWizardPage.4=Verify DummyWizardPage.5=Encrypt DummyWizardPage.6=Please choose a file where the signature is stored DummyWizardPage.7=Sign DummyWizardPage.8=Decrypt DummyWizardPage.9=Please choose a file where the signature should be saved DummyWizardPage.key.key=key DummyWizardPage.key.private=private key DummyWizardPage.key.public=public key DummyWizardPage.key.secret=secret key IntegratorAction.0=Result of verification IntegratorAction.1=Checksum is valid! IntegratorAction.2=Result of verification IntegratorAction.3=Checksum is invalid!\nCalculated: {0} \n Expected: {1} IntegratorAction.titlemask-cryptosystem=To en- or decrypt a message with the %s algorithm, choose a key from the keystore (or create a new key pair) IntegratorAction.titlemask-cryptosystem-padding=To en- or decrypt a message with the %s algorithm, choose a key (manually, from \nthe key store, or a newly created key) and pick a padding and block cipher mode. IntegratorAction.titlemask-digest=Create a message digest with the %s algorithm. IntegratorAction.titlemask-mac=Create a message authentication code with the %s algorithm. The key \ncan be created by hand or selected from the key store. IntegratorAction.titlemask-PRNG=To generate pseudo-random data with the %s algorithm, please choose \nthe amount of data to be generated and your preferred output format. IntegratorAction.titlemask-signature=Decide whether you want to sign or verify with the %s algorithm,\nand select the key to use. IntegratorWizardPage.0=Create IntegratorWizardPage.1=Verify IntegratorWizardPage.2=Checksum to verify IntegratorWizardPage.3=Expected checksum of the content: IntegratorWizardPage.4=Save... IntegratorWizardPage.createNewKeypairButton=Create a new key pair in the keystore IntegratorWizardPage.generatingButtonHint=calculating the key pair... (details: progress view) IntegratorWizardPage.newSymmetricKeyButtonlabel=Create a new key in the keystore IntegratorWizardPage.newSymmetricKeyButtontip=The key will remain in the keystore for later use. IntegratorWizardPage.noFurtherInputNeeded=This algorithm does not need any further input.\nClick the 'Finish' button to display the message digest in a new editor. IntegratorWizardPage.noKeyFound=No key that fits this operation was found in the keystore. IntegratorWizardPage.or=or: IntegratorWizardPage.willRemainInKeystore=The key pair will remain in the keystore for later use. IntegratorWizardPage.youChoseNewKeyLabel=You have chosen this newly created key from the keystore: KeySelectionGroup.KeySource=Key Source KeySelectionGroup.CustomKey=Custom key KeySelectionGroup.KeyFromKeystore=Key from keystore CustomKey.Title=Custom key CustomKey.KeyLength=Key length: KeyFromKeystore.Title=Keystore NewKeyComposite.key_label=Key NewKeyComposite.keypair=Key pair NewKeyComposite.owner=Owner: NewKeyComposite.pkeypart=\ (public key part) NewKeyComposite.privkeypart=\ (private key part) NewKeyComposite.removeKeypairBtn=Remove the key pair from the keystore again <file_sep>/org.jcryptool.editor.text/src/org/jcryptool/editor/text/action/NewEmptyFileJCTTextEditorAction.java //-----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2010 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ //-----END DISCLAIMER----- package org.jcryptool.editor.text.action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowActionDelegate; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.core.operations.editors.AbstractEditorService; import org.jcryptool.editor.text.JCTTextEditorPlugin; import org.jcryptool.editor.text.editor.JCTTextEditor; /** * This NewFileJCTTextEditorAction class opens a new text file with the JCT Texteditor. * * @author amro * @author <NAME> */ public class NewEmptyFileJCTTextEditorAction implements IWorkbenchWindowActionDelegate { /** * Disposes this action delegate. */ public void dispose() { } /** * Initializes this action delegate with the workbench window it will work in. * * @param window the window that provides the context for this delegate */ public void init(IWorkbenchWindow window) { } /** * Performs this action. This method is called by the proxy action when the action has been triggered. * * @param action the action proxy that handles the presentation portion of the action */ public void run(IAction action) { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); try { page.openEditor(AbstractEditorService.createTemporaryEmptyFile(), JCTTextEditor.ID); } catch (PartInitException e) { LogUtil.logError(JCTTextEditorPlugin.PLUGIN_ID, Messages.NewFileJCTTextEditorAction_0, e, true); } } /** * Notifies this action delegate that the selection in the workbench has changed. * * @param action action the action proxy that handles presentation portion of the action * @param selection @param selection the current selection, or <code>null</code> if there is no selection. */ public void selectionChanged(IAction action, ISelection selection) { } } <file_sep>/org.jcryptool.crypto.keystore/src/org/jcryptool/crypto/keystore/ui/actions/AbstractImportKeyStoreEntryAction.java // -----BEGIN DISCLAIMER----- /************************************************************************************************** * Copyright (c) 2013 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *************************************************************************************************/ // -----END DISCLAIMER----- package org.jcryptool.crypto.keystore.ui.actions; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.Certificate; import javax.crypto.SecretKey; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.window.Window; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.crypto.keystore.KeyStorePlugin; import org.jcryptool.crypto.keystore.descriptors.ImportDescriptor; import org.jcryptool.crypto.keystore.descriptors.interfaces.IImportDescriptor; import org.jcryptool.crypto.keystore.keys.KeyType; import codec.asn1.ASN1Exception; import codec.pkcs12.CertBag; import codec.pkcs12.PFX; import codec.pkcs12.PKCS8ShroudedKeyBag; import codec.pkcs12.SafeBag; import de.flexiprovider.core.dsa.interfaces.DSAPublicKey; import de.flexiprovider.core.rsa.interfaces.RSAPublicKey; public abstract class AbstractImportKeyStoreEntryAction extends AbstractKeyStoreAction { protected void performImportAction(IImportDescriptor descriptor, Object importedObject) throws IllegalArgumentException { if (descriptor.getKeyStoreEntryType().equals(KeyType.SECRETKEY)) { if (importedObject instanceof SecretKey) { LogUtil.logInfo("importing secret key"); //$NON-NLS-1$ addSecretKey(descriptor, (SecretKey) importedObject); } else { throw new IllegalArgumentException("Parameter is not as expected an instance of SecretKey"); } } else if (descriptor.getKeyStoreEntryType().equals(KeyType.KEYPAIR)) { if (importedObject instanceof PFX) { LogUtil.logInfo("importing pfx"); //$NON-NLS-1$ PFX pfx = (PFX) importedObject; try { char[] password = promptPassword(); if (password == null) return; SafeBag safeBag = pfx.getAuthSafe().getSafeContents(0).getSafeBag(0); PKCS8ShroudedKeyBag kBag = (PKCS8ShroudedKeyBag) safeBag.getBagValue(); PrivateKey privKey = kBag.getPrivateKey(password); SafeBag certBag = pfx.getAuthSafe().getSafeContents(1, password).getSafeBag(0); CertBag cBag = (CertBag) certBag.getBagValue(); PublicKey pubKey = cBag.getCertificate().getPublicKey(); int keySize = -1; if (pubKey instanceof RSAPublicKey) keySize = ((RSAPublicKey) pubKey).getN().bitLength(); else if (pubKey instanceof DSAPublicKey) keySize = ((DSAPublicKey) pubKey).getParameters().getP().bitLength(); // TODO: Add keySize calculation for the remaining // algorithms. ImportDescriptor newDescriptor = new ImportDescriptor(descriptor.getContactName(), privKey.getAlgorithm(), KeyType.KEYPAIR, descriptor.getFileName(), descriptor.getPassword(), descriptor.getProvider(), keySize); addKeyPair(newDescriptor, privKey, pubKey); } catch (ASN1Exception e) { LogUtil.logError(KeyStorePlugin.PLUGIN_ID, "error while importing key pair", e, true); } catch (IOException e) { LogUtil.logError(KeyStorePlugin.PLUGIN_ID, "error while importing key pair", e, false); } catch (GeneralSecurityException e) { LogUtil.logError(KeyStorePlugin.PLUGIN_ID, "error while importing key pair", e, true); } } else { throw new IllegalArgumentException("Parameter is not an instance of PFX, as expected"); } } else if (descriptor.getKeyStoreEntryType().equals(KeyType.PUBLICKEY)) { if (importedObject instanceof Certificate) { LogUtil.logInfo("importing certificate"); //$NON-NLS-1$ addCertificate(descriptor, (Certificate) importedObject); } else { throw new IllegalArgumentException("Parameter is not an instance of Certificate, as expected"); } } } protected char[] promptPassword() { InputDialog dialog = new InputDialog(null, Messages.getString("PasswordPromt.Title"), //$NON-NLS-1$ Messages.getString("PasswordPromt.Message"), //$NON-NLS-1$ "", null) { //$NON-NLS-1$ protected Control createDialogArea(Composite parent) { Control control = super.createDialogArea(parent); getText().setEchoChar('*'); return control; } }; int result = dialog.open(); if (result == Window.OK) { return dialog.getValue().toCharArray(); } else { return null; } } } <file_sep>/org.jcryptool.core.util/src/org/jcryptool/core/util/input/AbstractUIInput.java // -----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2010 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ // -----END DISCLAIMER----- package org.jcryptool.core.util.input; import java.util.Observable; import java.util.Observer; /** * An AbstractUIInput instance stands for one single user input. It ensures, that the stored input is always <br /> * <br /> * - valid (specify validation routines)<br /> * - coherent with the UI side of the input.<br /> * <br /> * * The AbstractUIInput is an Observable, sending updates <b>with data = null</b> to all Observers when really changed. <br /> * It also send updates whenever a user action was put through verification, with the data part of the update containing * the verification report ({@link InputVerificationResult}). <br /> * <br /> * * Use this class by overriding all necessary methods, and make sure, that every UI-side input made by the user and * concerning either the UI state of the input or the content, notifies this input about it by calling * {@link #synchronizeWithUserSide()}. * * @author <NAME> */ public abstract class AbstractUIInput<Content> extends Observable implements Observer { protected String mask_external_reset = Messages.AbstractUIInput_0; private Content internalRepresentation; /** * Generates a generic AbstractUIInput for putting as origin for rereads originating not from a UIInputObject. * * @param origin the generic origin name * @return a generic AbstractUIInput which exists solely for reading its name. */ private static AbstractUIInput<?> GENERIC_INPUT(final String origin) { return new AbstractUIInput<Object>() { @Override protected InputVerificationResult verifyUserChange() { return InputVerificationResult.DEFAULT_RESULT_EVERYTHING_OK; } @Override public Object readContent() { return null; } @Override public void writeContent(Object content) { } @Override protected Object getDefaultContent() { return null; } @Override public String getName() { return origin; } }; }; /** * Constructs a UI Input and sets the default value. */ public AbstractUIInput() { initializationActions(); tryToSetDefaultValues(); } /** * Anchor method to allow actions before any other things in the constructor. For Subclasses of AbstractUIInput * derivates that use gui elements, this method could be overridden to initialize the gui elements first. */ protected void initializationActions() { } /** * returns the String, just with its first character transformed into uppercase. This for forming correct sentences * from generic blocks. */ public static String firstUppercase(String string) { if (string != null) { if (string.length() > 0) { return String.valueOf(string.charAt(0)).toUpperCase().concat(string.substring(1)); } return string; } return null; } // /** // * calculates what Text will be created when the Modification, intercepted by // * the VerifyEvent, happens. Just character additions are handled. // * // * @param textBeforeTry text before Modification // * @param mod the Verification event that intercepted the modification // * @return // */ // private String calculateTextAfterModification(String textBeforeTry, VerifyEvent mod) { // String beforeSel = textBeforeTry.substring(0, mod.start); // String afterSel = textBeforeTry.substring(mod.start, textBeforeTry.length()); // String result; // // if(mod.character == SWT.DEL) { // if(mod.start == mod.end) { // result = beforeSel + afterSel.substring(1); // } else { // result = beforeSel + afterSel; // } // } else if(mod.character == SWT.DEL) { // if(mod.start == mod.end) { // result = beforeSel.substring(0, beforeSel.length()-1) + afterSel; // } else { // result = beforeSel + afterSel; // } // } else if(mod.character != SWT.MODIFIER_MASK) { // result = beforeSel + mod.text + afterSel; // } else { // result = textBeforeTry; // } // // return result; // } // /** * default inner method to set the default values at initialization. */ private void tryToSetDefaultValues() { setInputContent(getDefaultContent(), InputVerificationResult.DEFAULT_RESULT_EVERYTHING_OK); saveDefaultRawUserInput(); resetUserInput(); } /** * This method should be called, when the user tried to make a change DIRECTLY concerning this input (applies not * when another input was changed, that has influence on e. g. the semantical correctness of this input, because * this is handled over the Observer dependency structure of UIInputs. * * <br/> * <br /> * Use this method, when a text verification event can be retrieved, which allows to revert changes on semantical * incorrectness directly. * * @param evt the VerificationEvent * @param textBeforeTry the text before the tried change * @throws NullPointerException when the event is null * */ /** * Should be used when a reread must be done, but there is no UIInput which requested it. <br /> * <br /> * <b>Note, that this is NOT the standard method for synchronizing UI with Input</b>. The default method to be * called e. g. inside a textfield listener (when the textfield regarding this input has a changed text) is * {@link #synchronizeWithUserSide()}. * * @param originDescription a textual description of the context in which the reread occured. Name pattern: same as * the return value of {@link #getName()} -- think of it as of a name of a AbstractUIInput. */ public void reread(String originDescription) { reread(GENERIC_INPUT(originDescription)); } /** * Should only be invoked, when circumstances change, that do not directly belong to the input, but have influence * on its semantics. Normally, such things should be handled by having these influences as UIInputs, too, and adding * this AbstractUIInput as Observer. <br /> * <br /> * <b>Note, that this is NOT the standard method for synchronizing UI with Input.</b> The default method to be * called e. g. inside a textfield listener (when the textfield regarding this input has a changed text) is * {@link #synchronizeWithUserSide()}. * * @param inputWhichCausedThis The UIInput which caused the reread. */ public void reread(AbstractUIInput<?> inputWhichCausedThis) { InputVerificationResult verificationResult; if ((verificationResult = verifyUserChangeWithAutocorrection()).isValid()) { // if the user made a semantically // OK action setInputContent(readContent(), verificationResult); // read out the user input into the content this.setChanged(); notifyObservers(verificationResult); // send ui the verification result // and (by default this calls nothing) save the user input // (it is assumed that the user input can be reset to the state it is now // by just calling writeContent -- user input and saved data is related bijective. // But if its not, classes will override and change this. saveRawUserInput(); } else { resetExternallyCaused(inputWhichCausedThis); setChanged(); notifyObservers(makeVerificationResultExternallyCaused(verificationResult, inputWhichCausedThis)); } } /** * This method tries to generate a message which indicates that the content of this input just got invalid because * of another input that has changed, making this input invalid.<br /> * <br /> * The standard implementation relies on that the incoming verification results have as message a string "X" that * fits in the scheme <i>The input has been reset/changed automatically, because <b>X</b>.</i> -- the messages best * responds to the "because" scheme. Also, the Verification result type will have the type * {@link MWizardMessage#INFORMATION INFORMATION}. <br /> * <i>This is just a standard implementation as said, so this method is meant to be overridden.</i> * * @param verificationResult comes from the verification that was stating this input is not valid anymore. Contains * mostly a textual reason. * @param inputWhichCausedThis The input which caused the new invalidity. * @return the Verification result that is handed to the observer in the end. */ protected InputVerificationResult makeVerificationResultExternallyCaused( final InputVerificationResult verificationResult, final AbstractUIInput<?> inputWhichCausedThis) { return new InputVerificationResult() { public boolean isStandaloneMessage() { return true; } public MessageType getMessageType() { return MessageType.INFORMATION; } public String getMessage() { String mask = mask_external_reset; return String.format(mask, inputWhichCausedThis.getName(), getName(), verificationResult.getMessage()); } public boolean isValid() { return true; } }; } /** * This is the main method for synchronizing the input object with the user side. Every time the user made a input * that concerns either the internal input representation (the semantic part) or even solely the UI state of this * input (for example the position of the cursor in the corresponding text field) this method should be called. Of * course, only call this method, when the changed information is processed in {@link #saveRawUserInput()} or * {@link #verifyUserChange()} or {@link #readContent()}. * * <br /> * <br /> * The AbstractUIInput tries the following:<br /> * * call {@link #verifyUserChange()}; <br /> * * if the result of it (of type InputVerificationResult) has the flag {@link InputVerificationResult#isValid() * .isValid()} <br /> * ~~> read the input into the internal representation via {@link #readContent()} <br /> * ~~> if the internal representation did change because of this, notification to all Observers (data: null) and * another one (data: verification result object) is sent <br /> * * if the verification was not valid (flag was false): <br /> * ~~> call {@link #resetUserInput()} (try to pretend this erroneus input did not happen) ~~> send notification to * all observers (data: the verification result object) */ public void synchronizeWithUserSide() { InputVerificationResult verificationResult; if ((verificationResult = verifyUserChangeWithAutocorrection()).isValid()) { // if the user made a semantically // OK action Content previousContent = getContent(); boolean changed = setInputContent(readContent(), verificationResult); // read out the user input into the // content if (decideNotifyObserversAboutUserSideSynchronization(changed, previousContent, getContent(), verificationResult)) { this.setChanged(); notifyObservers(verificationResult); // send ui the verification result } // and (by default this calls nothing) save the user input // (it is assumed that the user input can be reset to the state it is now // by just calling writeContent -- user input and saved data is related bijective. // But if its not, classes will override and change this. saveRawUserInput(); } else { // by default, this tries to revert the user's change to the last saved // state (which is supposedly valid) by calling writeContent. Although, when // User input and saved data is not related bijectively, the userInput may not // be directly reverted, and look different and such, confusing, to the user. // so, classes can override this, too. resetUserInput(); this.setChanged(); notifyObservers(verificationResult); // notify UI/whatever observer } } /** * this method decides whether to inform all observers about: - synchronizing with the user side when - the * validation returned 'valid' * * <br> * <br> * by default, the observers are informed when the content of this UIInput object did actually change (see * {@link #setInputContent(Object, InputVerificationResult)} return contract). <br> * Override this function to define your own strategy. * * @param changed * @param previousContent * @param newContent * @param verificationResult * @return */ protected boolean decideNotifyObserversAboutUserSideSynchronization(boolean changed, Content previousContent, Content newContent, InputVerificationResult verificationResult) { return changed; } /** * This method is called when the user input is no more valid because of inputs that were outside the competency of * this input.<br /> * <br /> * It is now tried to reset the input to a state where it complies to the new situation. By default this is the * standard content generated the same way as at default AbstractUIInput construction. Override, to make a better * adaption to changed circumstances (to not erase the whole entered content, in many cases). * * @param inputWhichCausedThis the input which caused this. */ protected void resetExternallyCaused(AbstractUIInput<?> inputWhichCausedThis) { tryToSetDefaultValues(); } /** * This method is intended to reset the user input data on the UI level to the state where it was when the last * valid data was read from the user input. The default implementation uses the {@link #writeContent(Object)} method * to generate a UI user input presentation from the saved, valid input. Although, when user input on the UI side, * and the read data from it (in this class) is not isomorph/bijective formed, this may result in incoherence on the * UI side, and such, this method may be needed to save additional information about what the user told the UI when * the last valid input occured. */ protected void resetUserInput() { writeContent(getContent()); } /** * This method is optional and is intended to save the raw user input which was used to generate the data that is * now contained in this instance. By default, this method does nothing, because the standard implementation uses * the writeContent method to generate the user input back from the data that was drawn from it. So this method may * be subclassed when coherent userdata presentation is needed, because the standard implementation assumes that * user input presentation and saved data presentation is isomorph / bijective. * * <br /> * <br /> * <b>important:</b> If you extend this method to save something the user data can be reset to by calling * {@link #resetUserInput()}, make sure you do also extend {@link #saveDefaultRawUserInput()}, because * {@link #resetUserInput()} is called directly after initializing this instance with the default data ( * {@link #getDefaultContent()}), and such, this method could run into null pointers or other uninitialized data. */ protected void saveRawUserInput() { } /** * Saves generic raw user input information for use of {@link #resetUserInput()}. This method is to ensure that * there is always initialized data for the {@link #resetUserInput()} method (which is optional, so this method is * optional, too). By default, it does nothing but calling {@link #saveRawUserInput()}. * */ protected void saveDefaultRawUserInput() { saveRawUserInput(); } /** * validates the user input (not yet taken into this instances actual content). Note: This method must validate that * the user input is compliant with every other input at this moment, so check in dependency of other inputs, too. <br /> * <br /> * This method will be called, too, when another Input has changed, maybe notifying this input, issuing a * revalidation (happening in this method).<br /> * <br /> * * Note, that this method must absolutely reject every invalid input. The <I>autocorrection</I> methods ( * {@link #canAutocorrect(InputVerificationResult)}, {@link #autocorrect(InputVerificationResult)}) are the * functions to even out minor flaws in the user input, but these flaws have to be pointed out through this method. <br /> * <br /> * * <b>Output format:</b><br /> * - {@link InputVerificationResult#isValid()} must return the right thing<br /> * - {@link InputVerificationResult#getMessageType()} should be {@link MWizardMessage#NONE NONE} if everything is * alright, and in nearly every other case, {@link MWizardMessage#WARNING WARNING}.<br /> * - {@link InputVerificationResult#getMessage()} should return a short reason of the rejection, or warning in the * following style: <i>the frequency input must be a number</i> (or: text fragment stating a reason, which could * follow on 'because')<br /> * * <br /> * <br /> * * Scenario: until 10 milliseconds ago, the user wrote just the text '124.38', a decimal number, which is the * desired input format. Now, hey typed an "§" (accidentally, instead of a '3'), and therefore violates the user * input format. The text field already contains this character in this scenario.<br /> * What has to be done by this function, is: <br /> * return an appropriate InputVerificationResult; recommended: a warning-style message (because this error will be * reverted instantly), with invalid flag. <br /> * <br /> * What follows: The input will of course not be taken into this input object, because it is no decimal number. * Instead, this input object will try to revert the UI side to the last saved validated state. * * @return information object about the validation. Use {@link InputVerificationResult#DEFAULT_RESULT_EVERYTHING_OK} * for signalising completely validation withour errors, tips or warnings. * * @see #saveRawUserInput() * @see #resetUserInput() * */ protected abstract InputVerificationResult verifyUserChange(); /** * @return verifies the user change and applies auto correction if possible */ private InputVerificationResult verifyUserChangeWithAutocorrection() { InputVerificationResult verifyResult = verifyUserChange(); if (canAutocorrect(verifyResult)) { while (canAutocorrect(verifyResult)) { autocorrect(verifyResult); verifyResult = verifyUserChange(); } } return verifyResult; } /** * Reads the userInput from somewhere (SWT widgets, variables, etc.), so that the content can be stored in this * class in its pure form (e. g. the user made a string input which represents a key. With this method, the * AbstractUIInput tries to read the string key from the user, transforming it into a, say, CustomKey object.<br /> * <br /> * This method is normally executed only when the user input from which the data is read is verified semantically * correct.<br /> * <br /> * This method itself does not store information in the object! */ public abstract Content readContent(); /** * Writes the content to somewhere user-visible (write text to swt widgets, call functions which do that, etc). <br /> * Please notice, that the {@link #resetUserInput()} is often making changes to the user interface side too, * sometimes completely shadowing the efforts of this method. * * <br /> * This makes sense, because often the simple conversion of the internal representation into user-visible data can * be ambiguous, so for example, the usere entered the string "100.0000000000", and the number "100" would have been * stored internally. Then, a the user made an erroneous input, maybe an invalid character that has nothing to do * with a number, and now this input of the user has to be reverted to the alst saved state, which was "100". the * string displayed would now be "100", and the string wouldve been jumped from "100.0000000" to "100", which is * bad. <br /> * <br /> * The methods {@link #saveRawUserInput()} and {@link #resetUserInput()} take care of making the user side of the * input look consistent. In the described case, everytime the user made change to the text, the saveRawUserInput * woudve saved the pure string, and in the reset case, the resetUserInput method wouldve reset the text fields * content to the saved string, and not just to the pure number "100". * * * * @param content the content to be written/displayed/whatever. */ public abstract void writeContent(Content content); /** * @return the content that represents the initial state of this input */ protected abstract Content getDefaultContent(); /** * For giving the input a name. * * @return the name of the input. */ public abstract String getName(); /** * @return the internally stored (pure) form of the user input. */ public Content getContent() { return internalRepresentation; } /** * @param internalRepresentation the content * @param verificationResult the verification result that accompanied this setting. * @return whether the input actually did change */ protected boolean setInputContent(Content inputContent, InputVerificationResult verificationResult) { if ((this.internalRepresentation != null && inputContent == null) || (inputContent != null && !inputContent.equals(this.internalRepresentation))) { this.internalRepresentation = inputContent; this.setChanged(); notifyObservers(); return true; } else { this.internalRepresentation = inputContent; return false; } } public void update(Observable o, Object arg) { // the observable that notifies here is another AbstractUIInput. // It signals that it has changed, and since this is an Observer to // the notifying AbstractUIInput, this AbstractUIInput need to be verified semantically now. if (o instanceof AbstractUIInput) { if (arg == null) { // if the input was really changed reread((AbstractUIInput<?>) o); } } } /** * At verification, tries to determine if a InputVerificationResult (preferrably those which would cause a reset) * can be autocorrected. Example: only Uppercase characters are allowed, so the input (in which occurs as it happens * a lowercase character), the verification process returns a result which states that the input is invalid. * However, this method returns true, such, that the method #autocorrect(InputVerificationResult) will fix the input * directly in the textfield (in this example). <br /> * The user input is then verified again, and in this second pass, this verification obstacle will hopefully not * occur again. * * @param result the input verificationResult whichs cause has to be considered now for autocorrection * @return */ @SuppressWarnings("static-method") protected boolean canAutocorrect(InputVerificationResult result) { return false; } /** * see also #canAutocorrect(InputVerificationResult) <br /> * Tries to automatically correct minimal malformed inputs from the user side. This method should restrain to * correct only the "cause" of the verification result which is passed. After returning, the input will be verified * again, and possibly corrected again with the new verificationResult, until * {@link #canAutocorrect(InputVerificationResult)} does return false. * * @param result the InputVerificationResult which caused the autocorrection. * @return */ protected void autocorrect(InputVerificationResult result) { } } <file_sep>/org.jcryptool.crypto.flexiprovider.integrator/src/org/jcryptool/crypto/flexiprovider/integrator/IntegratorAction.java // -----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2010 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ // -----END DISCLAIMER----- package org.jcryptool.crypto.flexiprovider.integrator; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.eclipse.jface.window.Window; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.MessageBox; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.core.operations.algorithm.AbstractAlgorithmAction; import org.jcryptool.core.operations.dataobject.IDataObject; import org.jcryptool.core.operations.editors.EditorsManager; import org.jcryptool.crypto.flexiprovider.descriptors.algorithms.AlgorithmDescriptor; import org.jcryptool.crypto.flexiprovider.descriptors.algorithms.BlockCipherDescriptor; import org.jcryptool.crypto.flexiprovider.descriptors.algorithms.SecureRandomDescriptor; import org.jcryptool.crypto.flexiprovider.descriptors.meta.interfaces.IMetaAlgorithm; import org.jcryptool.crypto.flexiprovider.descriptors.meta.interfaces.IMetaKeyGenerator; import org.jcryptool.crypto.flexiprovider.operations.engines.PerformOperationManager; import org.jcryptool.crypto.flexiprovider.types.OperationType; import org.jcryptool.crypto.flexiprovider.types.RegistryType; import org.jcryptool.crypto.flexiprovider.xml.AlgorithmsXMLManager; import de.flexiprovider.api.MessageDigest; import de.flexiprovider.api.Registry; import de.flexiprovider.api.exceptions.NoSuchAlgorithmException; /** * This class provides the actions for FlexiProvider algorithms. * * @author mwalthart * @version 0.9.0 */ public abstract class IntegratorAction extends AbstractAlgorithmAction { private final String FLEXIPROVIDER_ALGORITHM_NAME = getFlexiProviderAlgorithmName(); private final String READABLE_ALGORITHM_NAME = getReadableAlgorithmName(); private String HEADER_DESCRIPTION; private boolean SHOW_OPERATION_GROUP = true; private boolean SHOW_PADDING_GROUP = false; private final String SHOW_KEY = getShowKey(); private boolean SHOW_SIGNATURE_GROUP = false; private boolean SHOW_RANDOM_GROUP = false; private int SHOW_MESSAGE_DIGEST_GROUP = 0; private boolean SHOW_KEY_SOURCE_GROUP = false; private IntegratorWizard wizard; private int algorithmType; static final int TYPE_ASYMMETRIC_BLOCK = 0x01; static final int TYPE_ASYMMETRIC_HYBRID = 0x02; static final int TYPE_CIPHER_BLOCK = 0x03; static final int TYPE_CIPHER = 0x04; static final int TYPE_MESSAGE_DIGEST = 0x05; static final int TYPE_MESSAGE_AUTHTIFICATION_CODE = 0x06; static final int TYPE_SIGNATURE = 0x07; static final int TYPE_RANDOM_NUMBER_GENERATOR = 0x08; /** * default constructor */ public IntegratorAction() { super(); } /** * returns the name of the algorithms as the FlexiProvider refers to it * * @return the name of the algorithms as the FlexiProvider refers to it */ protected abstract String getFlexiProviderAlgorithmName(); /** * returns the human readable name of the algorithm * * @return the human readable name of the algorithm */ protected abstract String getReadableAlgorithmName(); /** * returns the key id needed for this algorithms * * @return the key id needed for this algorithms */ protected abstract String getShowKey(); private String getHeaderDescription() { String mask = null; switch (algorithmType) { case TYPE_RANDOM_NUMBER_GENERATOR: mask = Messages.getString("IntegratorAction.titlemask-PRNG"); //$NON-NLS-1$ break; case TYPE_SIGNATURE: mask = Messages.getString("IntegratorAction.titlemask-signature"); //$NON-NLS-1$ break; case TYPE_MESSAGE_DIGEST: mask = Messages.getString("IntegratorAction.titlemask-digest"); //$NON-NLS-1$ break; case TYPE_MESSAGE_AUTHTIFICATION_CODE: mask = Messages.getString("IntegratorAction.titlemask-mac"); //$NON-NLS-1$ break; default: if (algorithmType == TYPE_ASYMMETRIC_BLOCK || algorithmType == TYPE_ASYMMETRIC_HYBRID) { mask = Messages.getString("IntegratorAction.titlemask-cryptosystem"); //$NON-NLS-1$ } else if ((algorithmType == TYPE_CIPHER_BLOCK || algorithmType == TYPE_CIPHER) && SHOW_PADDING_GROUP) { mask = Messages.getString("IntegratorAction.titlemask-cryptosystem-padding"); //$NON-NLS-1$ } } if (mask != null) { return String.format(mask, getReadableAlgorithmName()); } return Messages.getString("DummyAction.2") + getReadableAlgorithmName() + Messages.getString("DummyAction.3") //$NON-NLS-1$ //$NON-NLS-2$ + "";// + (algorithmType != TYPE_MESSAGE_DIGEST && algorithmType != TYPE_RANDOM_NUMBER_GENERATOR ? Messages.getString("DummyWizardPage.1") : ""); //$NON-NLS-1$ //$NON-NLS-2$ } private AlgorithmDescriptor searchList(String name, List<IMetaAlgorithm> list) { for (IMetaAlgorithm algorithm : list) { for (String algorithm_name : algorithm.getNames()) { if (algorithm_name.equals(name)) { return new AlgorithmDescriptor(algorithm.getName(), algorithm.getType(), null); } } } return null; } private AlgorithmDescriptor getAlgorithmDescriptor(String name) { AlgorithmDescriptor descriptor = null; descriptor = searchList(name, AlgorithmsXMLManager.getInstance().getAsymmetricBlockCiphers()); if (descriptor != null) { algorithmType = TYPE_ASYMMETRIC_BLOCK; } if (descriptor == null) { descriptor = searchList(name, AlgorithmsXMLManager.getInstance().getAsymmetricHybridCiphers()); if (descriptor != null) { algorithmType = TYPE_ASYMMETRIC_HYBRID; } } if (descriptor == null) { descriptor = searchList(name, AlgorithmsXMLManager.getInstance().getBlockCiphers()); if (descriptor != null) { algorithmType = TYPE_CIPHER_BLOCK; SHOW_PADDING_GROUP = true; } } if (descriptor == null) { descriptor = searchList(name, AlgorithmsXMLManager.getInstance().getCiphers()); if (descriptor != null) { algorithmType = TYPE_CIPHER; } } if (descriptor == null) { descriptor = searchList(name, AlgorithmsXMLManager.getInstance().getMacs()); if (descriptor != null) { algorithmType = TYPE_MESSAGE_AUTHTIFICATION_CODE; SHOW_OPERATION_GROUP = false; } } if (descriptor == null) { descriptor = searchList(name, AlgorithmsXMLManager.getInstance().getMessageDigests()); if (descriptor != null) { algorithmType = TYPE_MESSAGE_DIGEST; try { SHOW_MESSAGE_DIGEST_GROUP = java.security.MessageDigest.getInstance(name).getDigestLength(); SHOW_OPERATION_GROUP = false; } catch (java.security.NoSuchAlgorithmException e) { return null; } } } if (descriptor == null) { descriptor = searchList(name, AlgorithmsXMLManager.getInstance().getSecureRandoms()); if (descriptor != null) { algorithmType = TYPE_RANDOM_NUMBER_GENERATOR; SHOW_OPERATION_GROUP = false; SHOW_RANDOM_GROUP = true; } } if (descriptor == null) { descriptor = searchList(name, AlgorithmsXMLManager.getInstance().getSignatures()); if (descriptor != null) { algorithmType = TYPE_SIGNATURE; SHOW_SIGNATURE_GROUP = true; } } SHOW_KEY_SOURCE_GROUP = (algorithmType == TYPE_CIPHER_BLOCK || algorithmType == TYPE_MESSAGE_AUTHTIFICATION_CODE); HEADER_DESCRIPTION = getHeaderDescription(); return descriptor; } /** * runs the action: setup the algorithm and executed the specified operation */ @Override public void run() { AlgorithmDescriptor descriptor = getAlgorithmDescriptor(FLEXIPROVIDER_ALGORITHM_NAME); if (descriptor == null) { MessageBox messageBox = new MessageBox(getActiveWorkbenchWindow().getShell()); messageBox.setText(Messages.getString("DummyAction.error")); //$NON-NLS-1$ messageBox.setMessage(Messages.getString("DummyAction.8")); //$NON-NLS-1$ messageBox.open(); return; } String readableNameExtension; switch (algorithmType) { case TYPE_RANDOM_NUMBER_GENERATOR: readableNameExtension = Messages.getString("DummyAction.random_number_generator"); //$NON-NLS-1$ break; case TYPE_SIGNATURE: readableNameExtension = Messages.getString("DummyAction.signature"); //$NON-NLS-1$ break; case TYPE_MESSAGE_DIGEST: readableNameExtension = Messages.getString("DummyAction.message_digest"); //$NON-NLS-1$ break; case TYPE_MESSAGE_AUTHTIFICATION_CODE: readableNameExtension = Messages.getString("DummyAction.message_authentification_code"); //$NON-NLS-1$ break; default: readableNameExtension = Messages.getString("DummyAction.encryption"); //$NON-NLS-1$ } // Get which key lengths are valid for this algorithm int[] validKeyLengths = null; IMetaKeyGenerator keyGen = AlgorithmsXMLManager.getInstance().getSecretKeyGenerator( FLEXIPROVIDER_ALGORITHM_NAME); if (keyGen != null) { if (keyGen.getLengths().getLengths() != null) { validKeyLengths = new int[keyGen.getLengths().getLengths().size()]; for (int i = 0; i < validKeyLengths.length; i++) validKeyLengths[i] = keyGen.getLengths().getLengths().get(i); } else { validKeyLengths = new int[1]; validKeyLengths[0] = keyGen.getLengths().getDefaultLength(); } } wizard = new IntegratorWizard(READABLE_ALGORITHM_NAME + readableNameExtension, READABLE_ALGORITHM_NAME, HEADER_DESCRIPTION, SHOW_OPERATION_GROUP, SHOW_PADDING_GROUP, SHOW_KEY, SHOW_KEY_SOURCE_GROUP, validKeyLengths, SHOW_SIGNATURE_GROUP, SHOW_RANDOM_GROUP, SHOW_MESSAGE_DIGEST_GROUP, algorithmType); WizardDialog dialog = new WizardDialog(getActiveWorkbenchWindow().getShell(), wizard); dialog.setHelpAvailable(true); switch (dialog.open()) { case Window.OK: if (algorithmType == TYPE_CIPHER_BLOCK) { descriptor = new BlockCipherDescriptor(descriptor.getAlgorithmName(), AlgorithmsXMLManager .getInstance().getMode(wizard.getMode().getDescription()).getID(), AlgorithmsXMLManager .getInstance().getPaddingScheme(wizard.getPadding().getPaddingSchemeName()).getID(), null, descriptor.getAlgorithmParameterSpec()); } if (algorithmType == TYPE_RANDOM_NUMBER_GENERATOR) { if (wizard.doFilter()) descriptor = new SecureRandomDescriptor(descriptor.getAlgorithmName(), wizard.getRandomSize(), wizard.getFilter()); else descriptor = new SecureRandomDescriptor(descriptor.getAlgorithmName(), wizard.getRandomSize()); } IntegratorOperation operation = new IntegratorOperation(descriptor); operation.setEntryName(""); //$NON-NLS-1$ operation.setInput("<Editor>"); //$NON-NLS-1$ operation.setOutput("<Editor>"); //$NON-NLS-1$ operation.setSignature(wizard.signature()); operation.setUseCustomKey(wizard.useCustomKey()); if (wizard.useCustomKey()) operation.setKeyBytes(wizard.getCustomKey()); try { if (SHOW_KEY != null && !SHOW_KEY.equals("") && !wizard.useCustomKey()) //$NON-NLS-1$ operation.setKeyStoreAlias(wizard.getKey()); if (wizard.encrypt()) { // explicit encrypt if (descriptor.getType() == RegistryType.SIGNATURE) { operation.setOperation(OperationType.VERIFY); } else { operation.setOperation(OperationType.ENCRYPT); } } else { // implicit decrypt if (descriptor.getType() == RegistryType.SIGNATURE) { operation.setOperation(OperationType.SIGN); } else { operation.setOperation(OperationType.DECRYPT); } } if (SHOW_MESSAGE_DIGEST_GROUP > 0 && !wizard.encrypt()) { try { MessageDigest digest = Registry.getMessageDigest(operation.getAlgorithmDescriptor() .getAlgorithmName()); InputStream inputStream = EditorsManager.getInstance().getActiveEditorContentInputStream(); int i; while ((i = inputStream.read()) != -1) { digest.update((byte) i); } byte[] checksumAsBytes = digest.digest(); String checksum = ""; //$NON-NLS-1$ for (byte b : checksumAsBytes) { String temp = Integer.toHexString((int) b); checksum += (temp.length() == 1 ? "0" : "") + temp.substring(Math.max(0, temp.length() - 2)); //$NON-NLS-1$ //$NON-NLS-2$ } String expectedChecksum = wizard.getExpectedChecksum(); if (checksum.equalsIgnoreCase(expectedChecksum)) { MessageBox messageBox = new MessageBox(getActiveWorkbenchWindow().getShell(), SWT.ICON_WORKING); messageBox.setText(Messages.getString("IntegratorAction.0")); //$NON-NLS-1$ messageBox.setMessage(Messages.getString("IntegratorAction.1")); //$NON-NLS-1$ messageBox.open(); } else { MessageBox messageBox = new MessageBox(getActiveWorkbenchWindow().getShell(), SWT.ICON_ERROR); messageBox.setText(Messages.getString("IntegratorAction.2")); //$NON-NLS-1$ messageBox.setMessage(NLS.bind(Messages.getString("IntegratorAction.3"), //$NON-NLS-1$ new Object[] { checksum.toLowerCase(), expectedChecksum.toLowerCase() })); messageBox.open(); } } catch (NoSuchAlgorithmException e) { LogUtil.logError(IntegratorPlugin.PLUGIN_ID, "NoSuchAlgorithmException while initializing a message digest", e, true); //$NON-NLS-1$ } } else { PerformOperationManager.getInstance().firePerformOperation(operation); } if (operation.getOperation() == OperationType.SIGN) { MessageBox messageBox = new MessageBox(getActiveWorkbenchWindow().getShell(), SWT.NONE); messageBox.setText(Messages.getString("DummyAction.13")); //$NON-NLS-1$ messageBox.setMessage(Messages.getString("DummyAction.14") + wizard.signature()); //$NON-NLS-1$ messageBox.open(); } } catch (IOException ex) { LogUtil.logError(ex); } break; case Window.CANCEL: break; } } @Override public void run(IDataObject o) { } }<file_sep>/org.jcryptool.crypto.flexiprovider.operations/src/org/jcryptool/crypto/flexiprovider/operations/ui/actions/context/io/messages.properties SelectInputFileAction_0=Select File... SelectInputFileAction_1=Select File... SelectOutputFileAction_0=Select File... SelectOutputFileAction_1=Select File... SelectSignatureAction_0=Select File... SelectSignatureAction_1=Select File... SetInputEditorAction_0=Use Editor SetInputEditorAction_1=Use Editor SetOutputEditorAction_0=Use Editor SetOutputEditorAction_1=Use Editor <file_sep>/org.jcryptool.crypto.flexiprovider.keystore/src/org/jcryptool/crypto/flexiprovider/keystore/actions/ImportKeyAction.java //-----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2008 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ //-----END DISCLAIMER----- /** * */ package org.jcryptool.crypto.flexiprovider.keystore.actions; import java.security.cert.Certificate; import javax.crypto.SecretKey; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jface.window.Window; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; import org.jcryptool.crypto.flexiprovider.keystore.FlexiProviderKeystorePlugin; import org.jcryptool.crypto.flexiprovider.keystore.ImportManager; import org.jcryptool.crypto.flexiprovider.keystore.wizards.ImportWizard; import org.jcryptool.crypto.keystore.descriptors.ImportDescriptor; import org.jcryptool.crypto.keystore.descriptors.interfaces.IImportDescriptor; import org.jcryptool.crypto.keystore.descriptors.interfaces.IImportWizard; import org.jcryptool.crypto.keystore.keys.KeyType; import org.jcryptool.crypto.keystore.ui.actions.AbstractImportKeyStoreEntryAction; import codec.pkcs12.PFX; /** * @author tkern * */ public class ImportKeyAction extends AbstractImportKeyStoreEntryAction { private Shell shell; private WizardDialog dialog; public ImportKeyAction() { this.setText(Messages.ImportKeyAction_0); this.setToolTipText(Messages.ImportKeyAction_1); this.setImageDescriptor(FlexiProviderKeystorePlugin.getImageDescriptor("icons/16x16/kgpg_import.png")); //$NON-NLS-1$ } public void run() { shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); Wizard wizard = new ImportWizard(); dialog = new WizardDialog(shell, wizard); dialog.setMinimumPageSize(300, 350); int result = dialog.open(); if (result == Window.OK) { if (wizard instanceof IImportWizard) { IImportDescriptor desc = ((IImportWizard)wizard).getImportDescriptor(); IPath path = new Path(desc.getFileName()); if (desc.getKeyStoreEntryType().equals(KeyType.SECRETKEY)) { SecretKey key = ImportManager.getInstance().importSecretKey(path); performImportAction( new ImportDescriptor( desc.getContactName(), key.getAlgorithm(), KeyType.SECRETKEY, desc.getFileName(), desc.getPassword(), "Flex<PASSWORD>", //$NON-NLS-1$ -1 ), key); } else if (desc.getKeyStoreEntryType().equals(KeyType.KEYPAIR)) { PFX pfx = ImportManager.getInstance().importPFX(path); performImportAction(desc, pfx); } else if (desc.getKeyStoreEntryType().equals(KeyType.PUBLICKEY)) { Certificate cert = ImportManager.getInstance().importCertificate(path); performImportAction(desc, cert); } } } } }<file_sep>/org.jcryptool.crypto.flexiprovider.engines/src/org/jcryptool/crypto/flexiprovider/engines/cipher/messages.properties AsymmetricBlockCipherEngine_1=The selected key can not be used with an asymmetric block cipher. AsymmetricHybridCipherEngine_1=The selected key can not be used with an asymmetric hybrid cipher. BlockCipherEngine_5=The selected key can not be used with a block cipher. CipherEngine_2=The selected key can not be used with this cipher. ExAccessKeystorePassword=Cannot access keystore using this password. ExBadPadding=Cannot decrypt the input using this key.<file_sep>/org.jcryptool.crypto.flexiprovider.keystore/src/org/jcryptool/crypto/flexiprovider/keystore/wizards/messages.properties ImportWizard_0=Import ImportWizardPage_0=Import ImportWizardPage_1=Enter the details for the import ImportWizardPage_10=Import Certificate ImportWizardPage_11=<None> ImportWizardPage_12=Password ImportWizardPage_13=Specify the password with which the entry will be protected ImportWizardPage_14=Enter Password ImportWizardPage_15=Confirm Password ImportWizardPage_2=Contact Details ImportWizardPage_3=Enter or select a Contact Name ImportWizardPage_4=Contact Name ImportWizardPage_5=Import ImportWizardPage_6=Import Secret Key ImportWizardPage_7=Select File ImportWizardPage_8=Import Key Pair ImportWizardPage_9=Selected File: NewKeyPairWizard_0=New Key Pair NewKeyPairWizardPage_0=New Key Pair NewKeyPairWizardPage_1=Enter the details for the new key pair NewKeyPairWizardPage_10=Password NewKeyPairWizardPage_11=Specify the password with which the key will be protected NewKeyPairWizardPage_12=Enter Password NewKeyPairWizardPage_13=Confirm Password NewKeyPairWizardPage_2=Contact Details NewKeyPairWizardPage_3=Enter or select a Contact Name NewKeyPairWizardPage_4=Contact Name NewKeyPairWizardPage_5=Algorithm NewKeyPairWizardPage_6=Select an algorithm and specify the key strength NewKeyPairWizardPage_7=Algorithm NewKeyPairWizardPage_8=Standard Key Strength NewKeyPairWizardPage_9=Key Strength NewSymmetricKeyWizard_0=New Symmetric Key NewSymmetricKeyWizardPage_0=New Symmetric Key NewSymmetricKeyWizardPage_1=Enter the details for the new symmetric key NewSymmetricKeyWizardPage_10=Password NewSymmetricKeyWizardPage_11=Specify the password with which the key will be protected NewSymmetricKeyWizardPage_12=Enter Password NewSymmetricKeyWizardPage_13=Confirm Password NewSymmetricKeyWizardPage_2=Contact Details NewSymmetricKeyWizardPage_3=Enter or select a Contact Name NewSymmetricKeyWizardPage_4=Contact Name NewSymmetricKeyWizardPage_5=Algorithm NewSymmetricKeyWizardPage_6=Select an algorithm and specify the key strength NewSymmetricKeyWizardPage_7=Algorithm NewSymmetricKeyWizardPage_8=Standard Key Strength NewSymmetricKeyWizardPage_9=Key Strength <file_sep>/org.jcryptool.crypto.flexiprovider.operations/src/org/jcryptool/crypto/flexiprovider/operations/ui/actions/menu/ImportOperationAction.java // -----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2008 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ // -----END DISCLAIMER----- package org.jcryptool.crypto.flexiprovider.operations.ui.actions.menu; import org.eclipse.jface.action.Action; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.jcryptool.core.util.constants.IConstants; import org.jcryptool.core.util.directories.DirectoryService; import org.jcryptool.crypto.flexiprovider.operations.FlexiProviderOperationsPlugin; import org.jcryptool.crypto.flexiprovider.operations.OperationsManager; public class ImportOperationAction extends Action { public ImportOperationAction() { this.setText(Messages.ImportOperationAction_0); this.setToolTipText(Messages.ImportOperationAction_1); this.setImageDescriptor(FlexiProviderOperationsPlugin.getImageDescriptor("icons/16x16/import.gif")); //$NON-NLS-1$ } public void run() { FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE); dialog.setFilterPath(DirectoryService.getUserHomeDir()); dialog.setFilterExtensions(new String[] {IConstants.ALL_FILTER_EXTENSION}); dialog.setFilterNames(new String[] {IConstants.ALL_FILTER_NAME}); dialog.setOverwrite(true); String fileName = dialog.open(); if (fileName != null) { OperationsManager.getInstance().importOperation(fileName); } } } <file_sep>/org.jcryptool.crypto.keystore/src/org/jcryptool/crypto/keystore/ui/actions/ex/messages.properties ExportCertificateAction.0=*.cer ExportCertificateAction.1=Certificates (*.cer) ExportKeyPairAction.0=Enter Password ExportKeyPairAction.1=Enter the key protection password ExportKeyPairAction.2=*.p12 ExportKeyPairAction.3=Key export failed ExportKeyPairAction.4=Key Pair (*.p12) ExportSecretKeyAction.0=Enter Password ExportSecretKeyAction.1=Enter the key protection password ExportSecretKeyAction.2=*.sec ExportSecretKeyAction.3=Secret Key (*.sec) ExportSecretKeyAction.4=Key export failed Label.ExportKeyPair=Export Key Pair Label.ExportPublicKey=Export Public Key Label.ExportSecretKey=Export Secret Key <file_sep>/org.jcryptool.crypto.flexiprovider.operations/src/org/jcryptool/crypto/flexiprovider/operations/ui/views/nodes/io/messages_de.properties InputNode_0=Eingabe: <nicht angegeben> InputNode_1=Eingabe: {0} InputNode_2=<Editor> InputOutputNode_0=Eingabe/Ausgabe OutputNode_0=Ausgabe: <nicht angegeben> OutputNode_1=Ausgabe: {0} OutputNode_2=<Editor> SignatureIONode_0=Eingabe/Signatur SignatureNode_0=Signatur: <nicht angegeben> SignatureNode_1=Signatur: {0}<file_sep>/org.jcryptool.crypto.flexiprovider.operations/src/org/jcryptool/crypto/flexiprovider/operations/ui/actions/context/messages.properties RemoveAction_0=Remove RemoveAction_1=Remove RemoveAction_2=Remove operation RemoveAction_3=Are you sure you want to remove this operation?\nThis cannot be undone! RemoveKeyAction_0=Remove Key RemoveKeyAction_1=Remove Key RenameAction_0=Rename RenameAction_1=Rename RenameAction_2=Rename RenameAction_3=Enter a new name for <file_sep>/org.jcryptool.crypto.flexiprovider.operations/src/org/jcryptool/crypto/flexiprovider/operations/ui/views/messages.properties FlexiProviderOperationsView_0=Current Entry: <None> FlexiProviderOperationsView_2=Current Entry: {0} FlexiProviderOperationsView_3=Current Entry: <None> FlexiProviderOperationsView_keystore_hint=To set a key, drag and drop it from the key store to this entry. FlexiProviderOperationsView_keystore_hint_operations=The operation type will be derived automatically from the key type. <file_sep>/org.jcryptool.crypto.flexiprovider.engines/src/org/jcryptool/crypto/flexiprovider/engines/mac/messages.properties MacEngine_2=The selected key can not be used with a MAC. ExAccessKeystorePassword=Cannot access keystore using this password.<file_sep>/org.jcryptool.crypto.flexiprovider.keystore/src/org/jcryptool/crypto/flexiprovider/keystore/actions/NewSymmetricKeyAction.java //-----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2008 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ //-----END DISCLAIMER----- package org.jcryptool.crypto.flexiprovider.keystore.actions; import java.lang.reflect.InvocationTargetException; import org.eclipse.jface.window.Window; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.crypto.flexiprovider.descriptors.meta.interfaces.IMetaKeyGenerator; import org.jcryptool.crypto.flexiprovider.descriptors.meta.interfaces.IMetaLength; import org.jcryptool.crypto.flexiprovider.keystore.FlexiProviderKeystorePlugin; import org.jcryptool.crypto.flexiprovider.keystore.wizards.NewSymmetricKeyWizard; import org.jcryptool.crypto.flexiprovider.reflect.Reflector; import org.jcryptool.crypto.flexiprovider.xml.AlgorithmsXMLManager; import org.jcryptool.crypto.keystore.KeyStorePlugin; import org.jcryptool.crypto.keystore.descriptors.NewSecretKeyDescriptor; import org.jcryptool.crypto.keystore.descriptors.interfaces.INewEntryDescriptor; import org.jcryptool.crypto.keystore.descriptors.interfaces.INewKeyWizard; import org.jcryptool.crypto.keystore.ui.actions.AbstractNewKeyStoreEntryAction; import de.flexiprovider.api.Registry; import de.flexiprovider.api.exceptions.InvalidAlgorithmParameterException; import de.flexiprovider.api.exceptions.NoSuchAlgorithmException; import de.flexiprovider.api.keys.SecretKey; import de.flexiprovider.api.keys.SecretKeyGenerator; import de.flexiprovider.api.parameters.AlgorithmParameterSpec; /** * @author tkern * */ public class NewSymmetricKeyAction extends AbstractNewKeyStoreEntryAction { /** The shell is required for the wizard */ private Shell shell; /** The wizard dialog containing the wizards */ private WizardDialog dialog; /** * Creates a new instance of NewSymmetricKeyAction. */ public NewSymmetricKeyAction() { this.setText(Messages.NewSymmetricKeyAction_0); this.setToolTipText(Messages.NewSymmetricKeyAction_1); this.setImageDescriptor(KeyStorePlugin.getImageDescriptor("icons/16x16/kgpg_key1.png")); //$NON-NLS-1$ } /** * @see org.eclipse.jface.action.Action#run() */ public void run() { LogUtil.logInfo("NewSymmetricKeyAction"); //$NON-NLS-1$ shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); Wizard wizard = new NewSymmetricKeyWizard(); dialog = new WizardDialog(shell, wizard); dialog.setMinimumPageSize(300, 350); int result = dialog.open(); if (result == Window.OK) { if (wizard instanceof INewKeyWizard) { INewEntryDescriptor nkd = ((INewKeyWizard)wizard).getNewEntryDescriptor(); Integer[] argument = new Integer[1]; argument[0] = nkd.getKeyLength(); Integer keyLen = argument[0]; LogUtil.logInfo("key strength: " + argument[0]); //$NON-NLS-1$ try { IMetaKeyGenerator gen = AlgorithmsXMLManager.getInstance().getSecretKeyGenerator(nkd.getAlgorithmName()); IMetaLength validKeyLengths = gen.getLengths(); //Check if entered key length is valid boolean isValidKeyLength = true; if(validKeyLengths != null) { isValidKeyLength = (validKeyLengths.getDefaultLength() == keyLen) || (keyLen >= validKeyLengths.getLowerBound() && keyLen <= validKeyLengths.getUpperBound()) || (validKeyLengths.getLengths() != null && validKeyLengths.getLengths().contains(keyLen)); } if(!isValidKeyLength) { throw new InvalidAlgorithmParameterException("illegal key length"); } AlgorithmParameterSpec spec = null; if (gen.getParameterSpecClassName() != null) { spec = Reflector.getInstance().instantiateParameterSpec(gen.getParameterSpecClassName(), argument); } SecretKeyGenerator generator = Registry.getSecretKeyGenerator(nkd.getAlgorithmName()); if (spec != null) { LogUtil.logInfo("initializing generator with spec"); //$NON-NLS-1$ generator.init(spec, FlexiProviderKeystorePlugin.getSecureRandom()); } else { generator.init(FlexiProviderKeystorePlugin.getSecureRandom()); } SecretKey key = generator.generateKey(); performNewKeyAction(new NewSecretKeyDescriptor(nkd, key)); } catch (SecurityException e) { LogUtil.logError(FlexiProviderKeystorePlugin.PLUGIN_ID, "SecurityException while generating a secret key", e, true); } catch (IllegalArgumentException e) { LogUtil.logError(FlexiProviderKeystorePlugin.PLUGIN_ID, "IllegalArgumentException while generating a secret key", e, true); } catch (ClassNotFoundException e) { LogUtil.logError(FlexiProviderKeystorePlugin.PLUGIN_ID, "ClassNotFoundException while generating a secret key", e, true); } catch (NoSuchMethodException e) { LogUtil.logError(FlexiProviderKeystorePlugin.PLUGIN_ID, "NoSuchMethodException while generating a secret key", e, true); } catch (InstantiationException e) { LogUtil.logError(FlexiProviderKeystorePlugin.PLUGIN_ID, "InstantiationException while generating a secret key", e, true); } catch (IllegalAccessException e) { LogUtil.logError(FlexiProviderKeystorePlugin.PLUGIN_ID, "IllegalAccessException while generating a secret key", e, true); } catch (InvocationTargetException e) { LogUtil.logError(FlexiProviderKeystorePlugin.PLUGIN_ID, "InvocationTargetException while generating a secret key", e, true); } catch (NoSuchAlgorithmException e) { LogUtil.logError(FlexiProviderKeystorePlugin.PLUGIN_ID, "NoSuchAlgorithmException while generating a secret key", e, true); } catch (InvalidAlgorithmParameterException e) { LogUtil.logError(FlexiProviderKeystorePlugin.PLUGIN_ID, "InvalidAlgorithmParameterException while generating a secret key", e, true); } } } } } <file_sep>/org.jcryptool.crypto.flexiprovider.engines/src/org/jcryptool/crypto/flexiprovider/engines/messages_de.properties FlexiProviderEngine_0=Passwort eingeben FlexiProviderEngine_1=Bitte geben Sie das Schl\u00fcsselpasswort ein. FlexiProviderEngine_2=Kein ge\u00f6ffneter Editor FlexiProviderEngine_3=Sie m\u00fcssen zun\u00e4chst einen Editor \u00f6ffnen. <file_sep>/org.jcryptool.crypto.flexiprovider.operations/src/org/jcryptool/crypto/flexiprovider/operations/ui/views/EditorDragListener.java // -----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2008 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ // -----END DISCLAIMER----- package org.jcryptool.crypto.flexiprovider.operations.ui.views; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.dnd.DragSourceAdapter; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.ui.part.EditorInputTransfer; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.core.operations.IOperationsConstants; import org.jcryptool.core.operations.util.PathEditorInput; import org.jcryptool.crypto.flexiprovider.operations.ui.views.nodes.io.InputNode; import org.jcryptool.crypto.flexiprovider.operations.ui.views.nodes.io.OutputNode; public class EditorDragListener extends DragSourceAdapter { private TreeViewer viewer; public EditorDragListener(TreeViewer viewer) { this.viewer = viewer; } public void dragStart(DragSourceEvent event) { Object selected = viewer.getTree().getSelection()[0].getData(); LogUtil.logInfo("Selected for drag: " + selected.getClass().getName()); //$NON-NLS-1$ if (!(selected instanceof InputNode) && !(selected instanceof OutputNode)) { event.doit = false; return; } if (selected instanceof InputNode) { InputNode node = (InputNode) selected; if (node.getInput().equals("-1") || node.getInput().equals("<Editor>")) { //$NON-NLS-1$ //$NON-NLS-2$ LogUtil.logInfo("not doing it"); //$NON-NLS-1$ event.doit = false; } } else if (selected instanceof OutputNode) { OutputNode node = (OutputNode) selected; if (!node.getOutput().equals("-1") && !node.getOutput().equals("<Editor>")) { //$NON-NLS-1$ //$NON-NLS-2$ LogUtil.logInfo("not doing it"); //$NON-NLS-1$ event.doit = false; } } } public void dragSetData(DragSourceEvent event) { Object selected = viewer.getTree().getSelection()[0].getData(); if (selected instanceof InputNode) { InputNode node = (InputNode) selected; LogUtil.logInfo("Input: " + node.getInput()); //$NON-NLS-1$ if (!node.getInput().equals("-1") && !node.getInput().equals("<Editor>")) { //$NON-NLS-1$ //$NON-NLS-2$ EditorInputTransfer.EditorInputData data = EditorInputTransfer.createEditorInputData( IOperationsConstants.ID_HEX_EDITOR, new PathEditorInput(node.getInput())); //$NON-NLS-1$ event.data = new EditorInputTransfer.EditorInputData[] { data }; } } else if (selected instanceof OutputNode) { OutputNode node = (OutputNode) selected; LogUtil.logInfo("Output: " + node.getOutput()); //$NON-NLS-1$ if (!node.getOutput().equals("-1") && !node.getOutput().equals("<Editor>")) { //$NON-NLS-1$ //$NON-NLS-2$ EditorInputTransfer.EditorInputData data = EditorInputTransfer.createEditorInputData( IOperationsConstants.ID_HEX_EDITOR, new PathEditorInput(node.getOutput())); //$NON-NLS-1$ event.data = new EditorInputTransfer.EditorInputData[] { data }; } } } } <file_sep>/org.jcryptool.crypto.flexiprovider.operations/src/org/jcryptool/crypto/flexiprovider/operations/ui/actions/context/io/messages_de.properties SelectInputFileAction_0=Datei ausw\u00E4hlen... SelectInputFileAction_1=Datei ausw\u00E4hlen... SelectOutputFileAction_0=Datei ausw\u00E4hlen... SelectOutputFileAction_1=Datei ausw\u00E4hlen... SelectSignatureAction_0=Datei ausw\u00E4hlen... SelectSignatureAction_1=Datei ausw\u00E4hlen... SetInputEditorAction_0=Editor verwenden SetInputEditorAction_1=Editor verwenden SetOutputEditorAction_0=Editor verwenden SetOutputEditorAction_1=Editor verwenden <file_sep>/org.jcryptool.crypto.keystore/src/org/jcryptool/crypto/keystore/ui/actions/ex/ExportCertificateAction.java // -----BEGIN DISCLAIMER----- /************************************************************************************************** * Copyright (c) 2013 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *************************************************************************************************/ // -----END DISCLAIMER----- package org.jcryptool.crypto.keystore.ui.actions.ex; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableEntryException; import org.eclipse.core.runtime.Path; import org.eclipse.jface.action.Action; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.core.util.directories.DirectoryService; import org.jcryptool.crypto.keystore.KeyStorePlugin; import org.jcryptool.crypto.keystore.backend.ImportExportManager; import org.jcryptool.crypto.keystore.backend.KeyStoreManager; import org.jcryptool.crypto.keystore.ui.views.interfaces.IViewKeyInformation; /** * @author t-kern * */ public class ExportCertificateAction extends Action { private IViewKeyInformation info; /** * Creates a new instance of ExportSecretKeyAction */ public ExportCertificateAction(IViewKeyInformation info) { this.info = info; this.setText(Messages.getString("Label.ExportPublicKey")); //$NON-NLS-1$ this.setToolTipText(Messages.getString("Label.ExportPublicKey")); //$NON-NLS-1$ this.setImageDescriptor(KeyStorePlugin.getImageDescriptor("icons/16x16/kgpg_export.png")); //$NON-NLS-1$ } public void run() { FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE); dialog.setFilterPath(DirectoryService.getUserHomeDir()); dialog.setFilterExtensions(new String[] { Messages.getString("ExportCertificateAction.0") }); //$NON-NLS-1$ dialog.setFilterNames(new String[] { Messages.getString("ExportCertificateAction.1") }); //$NON-NLS-1$ dialog.setOverwrite(true); String filename = dialog.open(); if (filename != null && info != null) { try { ImportExportManager.getInstance().exportCertificate(new Path(filename), KeyStoreManager.getInstance().getCertificate(info.getSelectedKeyAlias())); } catch (UnrecoverableEntryException e) { LogUtil.logError(KeyStorePlugin.PLUGIN_ID, e); } catch (NoSuchAlgorithmException e) { LogUtil.logError(KeyStorePlugin.PLUGIN_ID, e); } } } } <file_sep>/org.jcryptool.crypto.keystore/src/org/jcryptool/crypto/keystore/ui/actions/AbstractKeyStoreAction.java // -----BEGIN DISCLAIMER----- /************************************************************************************************** * Copyright (c) 2013 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *************************************************************************************************/ // -----END DISCLAIMER----- package org.jcryptool.crypto.keystore.ui.actions; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.Calendar; import javax.crypto.SecretKey; import org.eclipse.jface.action.Action; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.core.operations.util.ByteArrayUtils; import org.jcryptool.crypto.keystore.KeyStorePlugin; import org.jcryptool.crypto.keystore.backend.KeyStoreAlias; import org.jcryptool.crypto.keystore.backend.KeyStoreManager; import org.jcryptool.crypto.keystore.certificates.CertificateFactory; import org.jcryptool.crypto.keystore.descriptors.interfaces.INewEntryDescriptor; import org.jcryptool.crypto.keystore.keys.KeyType; /** * Abstract (and empty) top-level action for plug-in. * * @author tkern * */ public abstract class AbstractKeyStoreAction extends Action { protected void addCertificate(INewEntryDescriptor descriptor, Certificate certificate) { KeyStoreManager.getInstance().addCertificate( certificate, new KeyStoreAlias(descriptor.getContactName(), KeyType.PUBLICKEY, certificate.getPublicKey() .getAlgorithm(), descriptor.getKeyLength(), ByteArrayUtils .toHexString(getHashValue(descriptor)), certificate.getPublicKey().getClass().getName())); } public static KeyStoreAlias addSecretKeyStatic(INewEntryDescriptor descriptor, SecretKey key) { LogUtil.logInfo("adding SecretKey"); //$NON-NLS-1$ KeyStoreAlias alias = new KeyStoreAlias(descriptor.getContactName(), KeyType.SECRETKEY, // key.getAlgorithm(), descriptor.getDisplayedName(), (key.getEncoded().length * 8), ByteArrayUtils.toHexString(getHashValue(descriptor)), key.getClass().getName()); KeyStoreManager.getInstance().addSecretKey(key, descriptor.getPassword().toCharArray(), alias); return alias; } protected KeyStoreAlias addSecretKey(INewEntryDescriptor descriptor, SecretKey key) { return addSecretKeyStatic(descriptor, key); } public static KeyStoreAlias addKeyPairStatic(INewEntryDescriptor descriptor, PrivateKey privateKey, PublicKey publicKey) { KeyStoreAlias privateAlias = new KeyStoreAlias(descriptor.getContactName(), KeyType.KEYPAIR_PRIVATE_KEY, descriptor.getDisplayedName(), descriptor.getKeyLength(), ByteArrayUtils.toHexString(getHashValue(descriptor)), privateKey.getClass().getName()); KeyStoreAlias publicAlias = new KeyStoreAlias(descriptor.getContactName(), KeyType.KEYPAIR_PUBLIC_KEY, descriptor.getDisplayedName(), descriptor.getKeyLength(), ByteArrayUtils.toHexString(getHashValue(descriptor)), publicKey.getClass().getName()); X509Certificate jctCertificate = CertificateFactory.createJCrypToolCertificate(publicKey); KeyStoreManager.getInstance().addKeyPair(privateKey, jctCertificate, descriptor.getPassword().toCharArray(), privateAlias, publicAlias); return publicAlias; } protected KeyStoreAlias addKeyPair(INewEntryDescriptor descriptor, PrivateKey privateKey, PublicKey publicKey) { return addKeyPairStatic(descriptor, privateKey, publicKey); } private static byte[] getHashValue(INewEntryDescriptor descriptor) { String timeStamp = Calendar.getInstance().getTime().toString(); MessageDigest sha1; try { sha1 = MessageDigest.getInstance("SHA-1"); //$NON-NLS-1$ sha1.update(descriptor.getContactName().getBytes()); sha1.update(descriptor.getAlgorithmName().getBytes()); sha1.update(descriptor.getProvider().getBytes()); return sha1.digest(timeStamp.getBytes()); } catch (NoSuchAlgorithmException e) { LogUtil.logError(KeyStorePlugin.PLUGIN_ID, "NoSuchAlgorithmException while digesting", e, true); } return new byte[] { 0 }; } } <file_sep>/org.jcryptool.crypto.keystore/src/org/jcryptool/crypto/keystore/ui/actions/ShadowKeyStoreAction.java // -----BEGIN DISCLAIMER----- /************************************************************************************************** * Copyright (c) 2013 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *************************************************************************************************/ // -----END DISCLAIMER----- package org.jcryptool.crypto.keystore.ui.actions; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.action.Action; import org.eclipse.ui.PlatformUI; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.crypto.keystore.IKeyStoreConstants; import org.jcryptool.crypto.keystore.KeyStorePlugin; public class ShadowKeyStoreAction extends Action { private String extensionUID; private String icon; private String text; private String tooltip; private String id; public ShadowKeyStoreAction(IKeyStoreActionDescriptor descriptor) { extensionUID = descriptor.getExtensionUID(); LogUtil.logInfo("ExtensionUID: " + extensionUID); //$NON-NLS-1$ icon = descriptor.getIcon(); text = descriptor.getText(); tooltip = descriptor.getToolTipText(); id = descriptor.getID(); setText(text); setToolTipText(tooltip); setImageDescriptor(KeyStorePlugin.getImageDescriptor(extensionUID, icon)); } public void run() { IExtensionRegistry registry = Platform.getExtensionRegistry(); IExtensionPoint extensionPoint = registry.getExtensionPoint(KeyStorePlugin.PLUGIN_ID, IKeyStoreConstants.PL_KEYSTORE_ACTIONS); IExtension extension = extensionPoint.getExtension(extensionUID); IConfigurationElement[] configElements = extension.getConfigurationElements(); for (int i = 0; i < configElements.length; i++) { IConfigurationElement element = configElements[i]; if (element.getName().equals(IKeyStoreConstants.TAG_KEYSTORE_ACTION)) { LogUtil.logInfo("NAME: " + element.getName()); //$NON-NLS-1$ if (id.equals(element.getAttribute(IKeyStoreConstants.ATT_ACTION_ID))) { try { final AbstractKeyStoreAction action = (AbstractKeyStoreAction) element .createExecutableExtension(IKeyStoreConstants.ATT_ACTION_CLASS); PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { action.run(); } }); } catch (CoreException e) { LogUtil.logError(KeyStorePlugin.PLUGIN_ID, "CoreException while creating an executable extension", e, true); } } } } } } <file_sep>/org.jcryptool.crypto.flexiprovider.engines/src/org/jcryptool/crypto/flexiprovider/engines/messages.properties FlexiProviderEngine_0=Enter Password FlexiProviderEngine_1=Please enter the key protection password FlexiProviderEngine_2=No open Editor FlexiProviderEngine_3=Please open an editor first. <file_sep>/org.jcryptool.actions.ui/src/org/jcryptool/actions/ui/handler/messages_de.properties ExportHandler_1=\u00dcberschreiben best\u00e4tigen ExportHandler_2=Die Datei {0} besteht bereits. M\u00f6chten Sie die bestehende Datei ersetzen? ExportHandler_3=Export der Action Kaskade unm\u00f6glich ExportHandler_4=Die Datei f\u00fcr die Action Kaskade konnte nicht erstellt werden. ExportHandler_5=Die Aktionen-Sicht ist leer, ein Export ist nicht m\u00f6glich. ImportHandler_0=\u00dcberschreiben best\u00e4tigen ImportHandler_1=Die Aktionen-Sicht enth\u00e4lt bereits Daten die durch den Import ersetzt werden wenn Sie fortfahren. ImportHandler_2=Import fehlgeschlagen ImportHandler_3=Die ausgew\u00e4hlte Datei enth\u00e4lt keine g\u00fcltige Action Kaskade. ImportActionCascadeHandler_0=Die Aktionen-Sicht konnte nicht ge\u00f6ffnet werden. NewCascadeHandler_0=Anlegen best\u00e4tigen NewCascadeHandler_1=Die Aktionen-Sicht enth\u00e4lt bereits Daten die verloren gehen werden wenn Sie fortfahren. StartHandler_0=Action Kaskade ist leer StartHandler_1=Die Aktionen-Sicht ist leer. Sie m\u00fcssen eine Action Kaskade erstellen oder importieren bevor Sie die Wiedergabe starten k\u00f6nnen. StartHandler_2=Algorithmus konnte nicht gefunden werden: StartHandler_3=Fehler beim Ausf\u00FChren der Kaskade StartHandler_4=\ Die Ausf\u00FChrung der Kaskade wird abgebrochen\! StartHandler_5=Action Kaskade: <file_sep>/org.jcryptool.editor.text/src/org/jcryptool/editor/text/action/messages.properties NewFileJCTTextEditorAction_0=Exception while opening the Texteditor OpenInHexAction_1=Could not open the selected file in the Hexeditor. OpenInHexAction_2=No Hexeditor is available. OpenInHexAction_errorTitle=Error opening Hexeditor <file_sep>/org.jcryptool.actions.ui/src/org/jcryptool/actions/ui/handler/messages.properties ExportHandler_1=Confirm overwrite ExportHandler_2=The file {0} already exists. Do you want to replace the existing file? ExportHandler_3=Action Cascade export impossible ExportHandler_4=Could not create the file for the action cascade. ExportHandler_5=The Actions view is empty, export is impossible. ImportActionCascadeHandler_0=Could not open the Actions view. ImportHandler_0=Confirm overwrite ImportHandler_1=The Actions view already contains data which will be replaced if you continue. ImportHandler_2=Import failed ImportHandler_3=The selected file to import does not contain a valid action cascade. NewCascadeHandler_0=Confirm new NewCascadeHandler_1=The Actions view already contains data which will be lost if you continue. StartHandler_0=Action cascade is empty StartHandler_1=The active action cascade is empty. You have to create or import one before you can replay it. StartHandler_2=Algorithm could not be found: StartHandler_3=Exception in the cascade execution StartHandler_4=Execution of the cascade is not continued! StartHandler_5=Action Cascade: <file_sep>/org.jcryptool.crypto.keystore/src/org/jcryptool/crypto/keystore/ui/actions/ex/messages_de.properties ExportCertificateAction.0=*.cer ExportCertificateAction.1=Zertifikate (*.cer) ExportKeyPairAction.0=Passwort eingeben ExportKeyPairAction.1=Bitte geben Sie das Schl\u00fcsselpasswort ein. ExportKeyPairAction.2=*.p12 ExportKeyPairAction.3=Der Schl\u00fcsselexport ist fehlgeschlagen ExportKeyPairAction.4=Schl\u00fcsselpaar (*.p12) ExportSecretKeyAction.0=Passwort eingeben ExportSecretKeyAction.1=Bitte geben Sie das Schl\u00fcsselpasswort ein. ExportSecretKeyAction.2=*.sec ExportSecretKeyAction.3=Geheimschl\u00fcssel (*.sec) ExportSecretKeyAction.4=Der Schl\u00fcsselexport ist fehlgeschlagen Label.ExportKeyPair=Schl\u00fcsselpaar exportieren Label.ExportPublicKey=Zertifikat exportieren Label.ExportSecretKey=Geheimen Schl\u00fcssel exportieren <file_sep>/org.jcryptool.crypto.flexiprovider.integrator/src/org/jcryptool/crypto/flexiprovider/integrator/messages_de.properties DummyAction.13=Signatur gespeichert DummyAction.14=Die Signatur wurde unter gespeichert:\n DummyAction.2=Dies ist eine Demonstration der FlexiProvider-Implementierung von " DummyAction.3=".\n DummyAction.8=Der Algorithmus wurde nicht gefunden\! DummyAction.encryption=-Verschl\u00fcsselung DummyAction.error=Fehler DummyAction.message_authentification_code=-Message Authentication Code DummyAction.message_digest=-Hashwert DummyAction.random_number_generator=-Zufallszahlengenerator DummyAction.signature=-Signatur DummyWizardPage.0=Bitte w\u00e4hlen Sie den Speicherort der Signatur DummyWizardPage.13=Modus: DummyWizardPage.14=Padding: DummyWizardPage.16=Schl\u00fcssel (Hex) DummyWizardPage.17=Schl\u00fcssel w\u00e4hlen: DummyWizardPage.18=Signatur DummyWizardPage.19=Datei: DummyWizardPage.2=Modus und Padding-Schema DummyWizardPage.20=\u00d6ffnen... DummyWizardPage.21=Fehler DummyWizardPage.22=Die Datei existiert bereits\! DummyWizardPage.24=Die Datei existiert nicht\! DummyWizardPage.27=Ausgabeformat DummyWizardPage.28=Bin\u00e4re Zeichen (Ausgabe in den Hexeditor) DummyWizardPage.29=Ausgabemenge DummyWizardPage.3=Funktion DummyWizardPage.30=Gr\u00f6\u00dfe: DummyWizardPage.31=Zeichen aus dem im folgenden Feld angezeigten Alphabet (Ausgabe in den Texteditor) DummyWizardPage.34=Zahlen innerhalb eines Zahlbereiches (Ausgabe in den Texteditor) DummyWizardPage.35=Mit Nullen auff\u00fcllen DummyWizardPage.4=Verifizieren DummyWizardPage.5=Verschl\u00fcsseln DummyWizardPage.6=Bitte w\u00e4hlen Sie den Speicherort der Signatur DummyWizardPage.7=Signieren DummyWizardPage.8=Entschl\u00fcsseln DummyWizardPage.9=Bitte w\u00e4hlen Sie den Speicherort der Signatur DummyWizardPage.key.key=Schl\u00fcssel DummyWizardPage.key.private=privater Schl\u00fcssel DummyWizardPage.key.public=\u00f6ffentlicher Schl\u00fcssel DummyWizardPage.key.secret=geheimer Schl\u00fcssel IntegratorAction.0=Ergebnis der Validierung IntegratorAction.1=Pr\u00fcfsumme ist g\u00fcltig! IntegratorAction.2=Ergebnis der Validierung IntegratorAction.3=Pr\u00fcfsumme ist ung\u00fcltig\!\nBerechnet: {0} \n Erwartet: {1} IntegratorAction.titlemask-cryptosystem=Um einen Text mit dem %s-Algorithmus zu ver- oder zu entschl\u00fcsseln, w\u00e4hlen Sie einen \nschon vorhandenen Schl\u00fcssel oder erstellen Sie einen neuen Schl\u00fcssel. IntegratorAction.titlemask-cryptosystem-padding=Um einen Text mit dem %s-Algorithmus zu ver- oder zu entschl\u00fcsseln, w\u00e4hlen Sie einen Schl\u00fcssel (manuell, aus dem\n Schl\u00fcsselspeicher, oder einen neu erstellten Schl\u00fcssel) und legen Sie den Padding- und den Blockchiffre-Modus fest. IntegratorAction.titlemask-digest=Berechnet den Hashwert eines Textes mit dem %s-Algorithmus. IntegratorAction.titlemask-mac=Berechnet einen Message Authentication Code mit dem %s-Algorithmus. Der Schl\u00fcssel \nkann per Hand eingegeben oder aus dem Schl\u00fcsselspeicher ausgew\u00e4hlt werden. IntegratorAction.titlemask-PRNG=F\u00fcr die Erstellung von pseudo-zuf\u00e4lligen Daten mit dem %s-Algorithmus, w\u00e4hlen \nSie die zu generierende Datenmenge und das Ausgabeformat. IntegratorAction.titlemask-signature=W\u00e4hlen Sie, ob mit dem %s-Algorithmus eine Signatur erstellt oder \nverifiziert werden soll und legen Sie den zu verwendenden Schl\u00fcssel fest. IntegratorWizardPage.0=Erstellen IntegratorWizardPage.1=Validieren IntegratorWizardPage.2=Zu validierende Pr\u00fcfsumme IntegratorWizardPage.3=Erwartete Pr\u00fcfsumme des Inhalts: IntegratorWizardPage.4=Speichern... IntegratorWizardPage.createNewKeypairButton=Ein neues Schl\u00fcsselpaar im Schl\u00fcsselspeicher erzeugen IntegratorWizardPage.generatingButtonHint=Erzeugung des Schl\u00fcsselpaars im Gange... (Details: Fortschritt-Sicht) IntegratorWizardPage.newSymmetricKeyButtonlabel=Einen neuen Schl\u00fcssel im Schl\u00fcsselspeicher erzeugen IntegratorWizardPage.newSymmetricKeyButtontip=Der erstellte Schl\u00fcssel kann nach der Operation durch den Schl\u00fcsselspeicher weiterverwendet werden. IntegratorWizardPage.noFurtherInputNeeded=Dieser Algorithmus ben\u00f6tigt keine weiteren Eingaben.\nNach einem Klick auf "Fertigstellen"wird der Hashwert\ndes Textes in einem neuen Editor angezeigt. IntegratorWizardPage.noKeyFound=Keine Schl\u00fcssel f\u00fcr diese Operation im Keystore gefunden. IntegratorWizardPage.or=oder: IntegratorWizardPage.willRemainInKeystore=Das erstellte Schl\u00fcsselpaar kann nach der Operation durch den Schl\u00fcsselspeicher weiterverwendet werden. IntegratorWizardPage.youChoseNewKeyLabel=Sie haben Ihren neu erstellten Schl\u00fcssel ausgew\u00e4hlt: KeySelectionGroup.KeySource=Schl\u00fcsselquelle KeySelectionGroup.CustomKey=Manuelle Schl\u00fcsseleingabe KeySelectionGroup.KeyFromKeystore=Schl\u00fcssel CustomKey.Title=Manuelle Schl\u00fcsseleingabe CustomKey.KeyLength=Schl\u00fcssell\u00e4nge: KeyFromKeystore.Title=Schl\u00fcsselspeicher NewKeyComposite.key_label=Schl\u00fcssel NewKeyComposite.keypair=Schl\u00fcsselpaar NewKeyComposite.owner=Besitzer: NewKeyComposite.pkeypart=\ (\u00f6ffentlicher Teil) NewKeyComposite.privkeypart=\ (privater Teil) NewKeyComposite.removeKeypairBtn=Das Schl\u00fcsselpaar wieder aus dem Schl\u00fcsselspeicher entfernen <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <groupId>org.jcryptool</groupId> <artifactId>org.jcryptool.releng</artifactId> <version>0.9.8</version> <relativePath>org.jcryptool.releng</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>org.jcryptool.core.parent</artifactId> <packaging>pom</packaging> <name>JCrypTool Core</name> <issueManagement> <system>GitHub</system> <url>https://github.com/jcryptool/core/issues</url> </issueManagement> <modules> <module>com.thoughtworks.qdox</module> <module>de.flexiprovider</module> <module>net.sourceforge.codec</module> <module>net.sourceforge.ehep</module> <module>net.sourceforge.ehep.nl_de</module> <module>org.apache.commons.cli</module> <module>org.bouncycastle</module> <module>org.jcryptool.actions.core</module> <module>org.jcryptool.actions.ui</module> <module>org.jcryptool.commands.core</module> <module>org.jcryptool.commands.ui</module> <module>org.jcryptool.core</module> <module>org.jcryptool.core.action</module> <module>org.jcryptool.core.cryptosystem</module> <module>org.jcryptool.core.dependencies.feature</module> <module>org.jcryptool.core.dependencies.nl_de.feature</module> <module>org.jcryptool.core.feature</module> <module>org.jcryptool.core.help</module> <module>org.jcryptool.core.logging</module> <module>org.jcryptool.core.nl</module> <module>org.jcryptool.core.operations</module> <module>org.jcryptool.core.util</module> <module>org.jcryptool.core.views</module> <module>org.jcryptool.crypto.feature</module> <module>org.jcryptool.crypto.flexiprovider</module> <module>org.jcryptool.crypto.flexiprovider.algorithms</module> <module>org.jcryptool.crypto.flexiprovider.engines</module> <module>org.jcryptool.crypto.flexiprovider.feature</module> <module>org.jcryptool.crypto.flexiprovider.integrator</module> <module>org.jcryptool.crypto.flexiprovider.keystore</module> <module>org.jcryptool.crypto.flexiprovider.operations</module> <module>org.jcryptool.crypto.keystore</module> <module>org.jcryptool.editor.hex</module> <module>org.jcryptool.editor.text</module> <module>org.jcryptool.editors.feature</module> <module>org.jcryptool.fileexplorer</module> <module>org.jcryptool.providers.feature</module> <module>org.jcryptool.product</module> <module>org.jcryptool.repository</module> <module>org.jcryptool.views.feature</module> <module>org.jcryptool.webbrowser</module> <module>org.jdom</module> </modules> </project><file_sep>/org.jcryptool.crypto.flexiprovider.operations/src/org/jcryptool/crypto/flexiprovider/operations/ui/views/nodes/io/messages.properties InputNode_0=Input: <not specified> InputNode_1=Input: {0} InputNode_2=<Editor> InputOutputNode_0=Input/Output OutputNode_0=Output: <not specified> OutputNode_1=Output: {0} OutputNode_2=<Editor> SignatureIONode_0=Input/Signature SignatureNode_0=Signature: <not specified> SignatureNode_1=Signature: {0}
0585955c4248b4632c80211095b2f6100b108783
[ "Java", "Maven POM", "INI" ]
37
INI
DimitrisGr/core
ff4327eb4ba1ef88eda5648e1a1ee3b3a8fa4376
9543ff544e877d4d5f94c8c2fb4580bdee2035f7
refs/heads/master
<file_sep>import React, { Component } from "react"; class NuevaCita extends Component { state = { cita : { mascota:'', propietario:'', fecha:'', hora:'', sintomas:'' } }; handleChange = e =>{ // Colocar lo que el usuario escribe en el state this.setState({ cita : { ...this.state.cita, [e.target.name] : e.target.value } }) } render() { return ( <div className="card mt-5 py-5"> <div className="card_body mx-5"> <h2 className="card-title text-center mb-5"> Rellena los datos para pedir tu cita </h2> <form> {/* Start of first form group */} <div className="form-group row"> <label className="col-sm-4 col-lg-2 col-form-label"> Nombre Mascota </label> <div className="col-sm-8 col-lg-10"> <input type="text" className="form-control" placeholder="Nombre de tu mascota" name="mascota" onChange={this.handleChange} value={this.state.cita.mascota} /> </div> </div> {/* End of first form group */} {/* Start of second form group */} <div className="form-group row"> <label className="col-sm-4 col-lg-2 col-form-label"> Tú Nombre </label> <div className="col-sm-8 col-lg-10"> <input type="text" className="form-control" placeholder="Nombre Dueño mascota" name="propietario" onChange={this.handleChange} value={this.state.cita.propietario} /> </div> </div> {/* End of second form group */} {/* Start of third form group */} <div className="form-group row"> <label className="col-sm-4 col-lg-2 col-form-label"> Fecha Cita </label> <div className="col-sm-8 col-lg-4"> <input type="date" className="form-control" placeholder="Nombre de tu mascota" name="fecha" onChange={this.handleChange} value={this.state.cita.fecha} /> </div> <label className="col-sm-4 col-lg-2 col-form-label"> Hora Cita </label> <div className="col-sm-8 col-lg-4"> <input type="time" className="form-control" placeholder="Nombre de tu mascota" name="hora" onChange={this.handleChange} value={this.state.cita.hora} /> </div> </div> {/* End of third form group */} {/* Start of fourth form group */} <div className="form-group row"> <label className="col-sm-4 col-lg-2 col-form-label"> Sintomas </label> <div className="col-sm-8 col-lg-10"> <textarea className="form-control" name="sintomas" placeholder="Describe los sintomas de tu mascota" onChange={this.handleChange} value={this.state.cita.sintomas} ></textarea> </div> </div> {/* End of form fourth group */} {/* Start Button for submit */} <input type="submit" className="py-3 mt-2 btn btn-success btn-block" value="Agregar nueva cita"></input> {/* End Button for submit */} </form> </div> </div> ); } } export default NuevaCita;
4c7c3f3997701f3445aed4690c87528e518a6e59
[ "JavaScript" ]
1
JavaScript
victormrch/-VeterinaryPatientAdministrator
bfe8de3913663d7e09da89a739699a5d1484d99e
18b65886a0568a9aa1e8dbe3bbc8fc47dcc30712
refs/heads/master
<file_sep> # coding: utf-8 # In[39]: #import dependencies from bs4 import BeautifulSoup as bs from splinter import Browser import os import pandas as pd import time import requests # In[40]: # https://splinter.readthedocs.io/en/latest/drivers/chrome.html get_ipython().system('which chromedriver') # In[41]: executable_path = {'executable_path': '/usr/local/bin/chromedriver'} browser = Browser('chrome', **executable_path, headless=False) # In[42]: #visiting the page url = "https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest" browser.visit(url) browser.html news = bs(browser.html,"html.parser") # In[43]: list_text = news.find("div", class_="list_text") # In[44]: title = list_text.find("a").get_text() # In[47]: title # In[48]: paragraph = list_text.find("div", class_="article_teaser_body").get_text() # In[60]: paragraph # In[69]: #visiting the page url = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars" browser.visit(url) # In[70]: time.sleep(2) image_button = browser.find_by_id("full_image").click() # In[71]: time.sleep(2) more_info_button = browser.find_link_by_partial_text("more info").click() # In[72]: image = bs(browser.html, "html.parser") # In[75]: image_url=image.find("figure", class_="lede").find("img")["src"] image_url # In[77]: final_url = "https://www.jpl.nasa.gov" + image_url final_url <file_sep> # coding: utf-8 # In[ ]: #import dependencies from bs4 import BeautifulSoup as bs from splinter import Browser import os import pandas as pd import time import requests # In[ ]: # https://splinter.readthedocs.io/en/latest/drivers/chrome.html get_ipython().system('which chromedriver') # In[ ]: executable_path = {'executable_path': '/usr/local/bin/chromedriver'} browser = Browser('chrome', **executable_path, headless=False) # In[ ]: # Defining scrape & dictionary def scrape(): final_data = {} output = marsNews() final_data["mars_news"] = output[0] final_data["mars_paragraph"] = output[1] final_data["mars_image"] = marsImage() final_data["mars_weather"] = marsWeather() final_data["mars_facts"] = marsFacts() final_data["mars_hemisphere"] = marsHem() return final_data # # NASA Mars News # # NASA Mars News # In[ ]: #visiting the page url = "https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest" browser.visit(url) browser.html news = bs(browser.html,"html.parser") # In[ ]: list_text = news.find("div", class_="list_text") # In[ ]: title = list_text.find("a").get_text() # In[ ]: title # In[ ]: paragraph = list_text.find("div", class_="article_teaser_body").get_text() # In[ ]: paragraph # In[ ]: #visiting the page url = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars" browser.visit(url) # In[ ]: time.sleep(2) image_button = browser.find_by_id("full_image").click() # In[ ]: time.sleep(2) more_info_button = browser.find_link_by_partial_text("more info").click() # In[ ]: image = bs(browser.html, "html.parser") # In[ ]: image_url=image.find("figure", class_="lede").find("img")["src"] image_url # In[ ]: final_url = "https://www.jpl.nasa.gov" + image_url final_url # # JPL Mars Space Images - Featured Image # In[ ]: url_image = "https://www.jpl.nasa.gov/spaceimages/?search=&category=featured#submit" browser.visit(url_image) # In[ ]: #Getting the base url from urllib.parse import urlsplit base_url = "{0.scheme}://{0.netloc}/".format(urlsplit(url_image)) print(base_url) # In[ ]: #Design an xpath selector to grab the image#Design xpath = "//*[@id=\"page\"]/section[3]/div/ul/li[1]/a/div/div[2]/img" # In[ ]: #Use splinter to click on the mars featured image #to bring the full resolution image results = browser.find_by_xpath(xpath) img = results[0] img.click() # In[ ]: #get image url using BeautifulSoup html_image = browser.html soup = bs(html_image, "html.parser") img_url = soup.find("img", class_="fancybox-image")["src"] full_img_url = base_url + img_url print(full_img_url) # # Mars Weather # In[ ]: #get mars weather's latest tweet from the website url_weather = "https://twitter.com/marswxreport?lang=en" browser.visit(url_weather) # In[ ]: html_weather = browser.html soup = bs(html_weather, "html.parser") #temp = soup.find('div', attrs={"class": "tweet", "data-name": "<NAME>"}) mars_weather = soup.find("p", class_="TweetTextSize TweetTextSize--normal js-tweet-text tweet-text").text print(mars_weather) #temp # # Mars Facts # In[ ]: url_facts = "https://space-facts.com/mars/" # In[ ]: table = pd.read_html(url_facts) table[0] # In[ ]: df_mars_facts = table[0] df_mars_facts.columns = ["Parameter", "Values"] df_mars_facts.set_index(["Parameter"]) # In[ ]: mars_html_table = df_mars_facts.to_html() mars_html_table = mars_html_table.replace("\n", "") mars_html_table # # Mars Hemisperes # In[ ]: url_hemisphere = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars" browser.visit(url_hemisphere) # In[ ]: #Getting the base url hemisphere_base_url = "{0.scheme}://{0.netloc}/".format(urlsplit(url_hemisphere)) print(hemisphere_base_url) # # Cerberus-Hemisphere-image-url # In[ ]: hemisphere_img_urls = [] results = browser.find_by_xpath( "//*[@id='product-section']/div[2]/div[1]/a/img").click() time.sleep(2) cerberus_open_click = browser.find_by_xpath( "//*[@id='wide-image-toggle']").click() time.sleep(1) cerberus_image = browser.html soup = bs(cerberus_image, "html.parser") cerberus_url = soup.find("img", class_="wide-image")["src"] cerberus_img_url = hemisphere_base_url + cerberus_url print(cerberus_img_url) cerberus_title = soup.find("h2",class_="title").text print(cerberus_title) back_button = browser.find_by_xpath("//*[@id='splashy']/div[1]/div[1]/div[3]/section/a").click() cerberus = {"image title":cerberus_title, "image url": cerberus_img_url} hemisphere_img_urls.append(cerberus) # # Schiaparelli-Hemisphere-image-url # In[ ]: results1 = browser.find_by_xpath( "//*[@id='product-section']/div[2]/div[2]/a/img").click() time.sleep(2) schiaparelli_open_click = browser.find_by_xpath( "//*[@id='wide-image-toggle']").click() time.sleep(1) schiaparelli_image = browser.html soup = bs(schiaparelli_image, "html.parser") schiaparelli_url = soup.find("img", class_="wide-image")["src"] schiaparelli_img_url = hemisphere_base_url + schiaparelli_url print(schiaparelli_img_url) schiaparelli_title = soup.find("h2",class_="title").text print(schiaparelli_title) back_button = browser.find_by_xpath("//*[@id='splashy']/div[1]/div[1]/div[3]/section/a").click() schiaparelli = {"image title":schiaparelli_title, "image url": schiaparelli_img_url} hemisphere_img_urls.append(schiaparelli) # # Syrtis Major Hemisphere # In[ ]: results1 = browser.find_by_xpath( "//*[@id='product-section']/div[2]/div[3]/a/img").click() time.sleep(2) syrtis_major_open_click = browser.find_by_xpath( "//*[@id='wide-image-toggle']").click() time.sleep(1) syrtis_major_image = browser.html soup = bs(syrtis_major_image, "html.parser") syrtis_major_url = soup.find("img", class_="wide-image")["src"] syrtis_major_img_url = hemisphere_base_url + syrtis_major_url print(syrtis_major_img_url) syrtis_major_title = soup.find("h2",class_="title").text print(syrtis_major_title) back_button = browser.find_by_xpath("//*[@id='splashy']/div[1]/div[1]/div[3]/section/a").click() syrtis_major = {"image title":syrtis_major_title, "image url": syrtis_major_img_url} hemisphere_img_urls.append(syrtis_major) # # Valles Marineris Hemisphere # In[ ]: results1 = browser.find_by_xpath( "//*[@id='product-section']/div[2]/div[4]/a/img").click() time.sleep(2) valles_marineris_open_click = browser.find_by_xpath( "//*[@id='wide-image-toggle']").click() time.sleep(1) valles_marineris_image = browser.html soup = bs(valles_marineris_image, "html.parser") valles_marineris_url = soup.find("img", class_="wide-image")["src"] valles_marineris_img_url = hemisphere_base_url + syrtis_major_url print(valles_marineris_img_url) valles_marineris_title = soup.find("h2",class_="title").text print(valles_marineris_title) back_button = browser.find_by_xpath("//*[@id='splashy']/div[1]/div[1]/div[3]/section/a").click() valles_marineris = {"image title":valles_marineris_title, "image url": valles_marineris_img_url} hemisphere_img_urls.append(valles_marineris) # In[ ]: hemisphere_img_urls
1187ecec4dae3ba389c3accf93fcaf0ef6e14620
[ "Python" ]
2
Python
dcohriner/Mission-to-Mars-Web-Scraping-Project
9a6e09b4515f0b901f065ab79babf5ed3834f135
5e0d2132be72dd556bcecbbbc76719f56e66f276
refs/heads/main
<file_sep>package com.willroth.mypackagelibrary import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.widget.doAfterTextChanged import com.willroth.mypackagelibrary.databinding.MyComponentLayoutBinding class MyComponent : ConstraintLayout { private var binding: MyComponentLayoutBinding constructor(context: Context) : super(context) { binding = MyComponentLayoutBinding.inflate(LayoutInflater.from(context), this) configBehaviour() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { binding = MyComponentLayoutBinding.inflate(LayoutInflater.from(context), this) configBehaviour() } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { binding = MyComponentLayoutBinding.inflate(LayoutInflater.from(context), this) configBehaviour() } private fun configBehaviour() { binding.et.doAfterTextChanged { binding.tv.text = it?.toString() } } }<file_sep>rootProject.name = "My Test Package" include ':app' include ':my_package_library' <file_sep>plugins { id("com.android.library") kotlin("android") id("maven-publish") } android { compileSdkVersion(30) buildToolsVersion("30.0.3") defaultConfig { minSdkVersion(23) targetSdkVersion(30) versionCode = 1 versionName = "1.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" consumerProguardFiles("consumer-rules.pro") } buildTypes { getByName("release") { isMinifyEnabled = false proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") } } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = "1.8" } buildFeatures { viewBinding = true } } dependencies { implementation("org.jetbrains.kotlin:kotlin-stdlib:1.5.10") implementation("androidx.core:core-ktx:1.5.0") implementation("androidx.appcompat:appcompat:1.3.0") implementation("com.google.android.material:material:1.3.0") implementation("androidx.constraintlayout:constraintlayout:2.0.4") testImplementation("junit:junit:4.13.2") androidTestImplementation("androidx.test.ext:junit:1.1.2") androidTestImplementation("androidx.test.espresso:espresso-core:3.3.0") } publishing { repositories { maven { name = "GitHubPackages" url = uri("https://maven.pkg.github.com/Guille88C/my-test-android-package") credentials { username = "Guille88C" password = "<PASSWORD>" } } } publications { create<MavenPublication>("gpr") { run { groupId = "com.rocket.packages" artifactId = "my_package_library" version = "1.0.0" artifact("$buildDir/outputs/aar/$artifactId-debug.aar") } } } }
0b02f2fc0be638baa2ea9a451f069d2b745d11b8
[ "Kotlin", "Gradle" ]
3
Kotlin
Guille88C/my-test-android-package
21a910b2f378b163667d8b9a90fb5dfa381c89e8
5269a49b4a295c6b431141a7f560a223a3a6a59e
refs/heads/main
<repo_name>GraemeMalcolm/AI-102<file_sep>/README.md This repo is now retired, and may be out of date. You'll find the latest version of these exercises at https://github.com/microsoftlearning/ai-102-aiengineer <file_sep>/instructions/20-form-recognizer.md # Build custom models with the Form Recognizer service **Form Recognizer** is a cognitive service that enables users to build automated data processing software. This software can extract text, key/value pairs, and tables from form documents using optical character recognition (OCR). Form Recognizer has pre-built models for recognizing invoices, receipts, and business cards. The service also provides the capability to train custom models. In this exercise, we will focus on building custom models. ## Clone the repository for this course If you have not already done so, you must clone the code repository for this course: 1. Start Visual Studio Code. 2. Open the palette (SHIFT+CTRL+P) and run a `Git: Clone` command to clone the `https://github/com/MicrosoftLearning/AI-102-AIEngineer` repository to a local folder. 3. When the repository has been cloned, open the folder in Visual Studio Code. <a id="getform"></a> ## Create a Form Recognizer resource 1. Navigate to the Azure Portal [https://portal.azure.com](https://portal.azure.com), and sign in using the Microsoft account associated with your Azure subscription. 2. Select the **&#65291;Create a resource** button, search for *Form Recognizer*, and create a **Form Recognizer** resource with the following settings: - **Subscription**: *Your Azure subscription* - **Resource group**: *Choose or create a resource group (if you are using a restricted subscription, you may not have permission to create a new resource group - use the one provided)* - **Region**: *Choose any available region* - **Name**: *Enter a unique name* - **Pricing tier**: F0 > **Note**: If you already have an F0 custom vision service in your subscription, select **S0** for this one. 3. When the resource has been deployed, go to it and view its **Keys and Endpoint** page. You will need the endpoint and one of the keys from this page to manage access from your code later on. ## Case: Automating Hero Limited's data entry process Suppose the company Hero Limited asks you to automate a data entry process. Currently an employee at Hero Limited manually reads a purchase order and enters the data into a database. You want to build a model that will use a machine learning model to read the form and produce structured data that can be used to automatically update a database. You will use Form Recognizer to train and test custom form recognition models. First you'll train a model **without** labeled sample forms, then train a model **with** labeled sample forms. Overview of next steps: - Gather and upload training documents to an Azure Storage Blob - Configure program environment variables - Run a program to train a model without labels - Run a program to test the model trained without labels - Repeat process to train and test a model with labels ## Gather documents for training ![An image of a Hero Limited invoice.](../20-custom-form/sample-forms/Form_1.jpg) You'll use the sample forms in the **20-custom-form/sample-forms** folder in this repo, which contain all the files you'll need to train a model with labels and without labels. >**Important**: Take a look at the files in the folder. In the **AI-102** project, and in the **Explorer** pane, select the **20-custom-form** folder and expand the **sample-forms** folder. Notice there are files ending in **.json** and **.jpg**. >**Now**: You will use the **.jpg** files to train your first model _without_ labels. >**Later**: You will use the files ending in **.json** and **.jpg** to train your second model _with_ labels. The **.json** files contain special label information. To train with labels, you need to have special label information files (<mark>&lt;filename&gt;.jpg.labels.json</mark>) in your blob storage container alongside the forms. You can learn more about custom model input requirements [here](https://docs.microsoft.com/azure/cognitive-services/form-recognizer/build-training-data-set#custom-model-input-requirements). <a id="blob"></a> ## Store training data in an Azure blob storage container 1. Return to the Azure portal at [https://portal.azure.com](https://portal.azure.com). 2. View the **Resource groups** in your subscription. 3. If you are using a restricted subscription in which a resource group has been provided for you, select the resource group to view its properties. Otherwise, create a new resource group with a name of your choice, and go to it when it has been created. 4. On the **Overview** page for your resource group, note the **Subscription ID** and **Location**. You will need these values, along with the name of the resource group in subsequent steps. 5. In Visual Studio Code, in the **AI-102** project, expand the **20-custom-form** folder and select **setup.cmd**. You will use this batch script to run the Azure command line interface (CLI) commands required to create the Azure resources you need. 6. Right-click the the **20-custom-form** folder and select **Open in Integrated Terminal**. 7. In the terminal pane, enter the following command to establish an authenticated connection to your Azure subscription. ```bash az login --output none ``` 8. When prompted, open `https://microsoft.com/devicelogin`, enter the provided code, and sign into your Azure subscription. Then return to Visual Studio Code and wait for the sign-in process to complete. 9. Run the following command to list Azure locations. ```bash az account list-locations -o table ``` 10. In the output, find the **Name** value that corresponds with the location of your resource group (for example, for *East US* the corresponding name is *eastus*). 11. In the **setup.cmd** script, modify the **subscription_id**, **resource_group**, and **location** variable declarations with the appropriate values for your subscription ID, resource group name, and location name. Then save your changes. 12. In the terminal for the **20-custom-form** folder, enter the following command to run the script: ```bash setup ``` 13. When the script completes, review the displayed output and note your Azure resource's Storage account name. 14. In the Azure portal, refresh the resource group and verify that it contains the Azure Storage account just created and a container with the **sampleforms** blob. The blob should contain all the forms from your local **20-custom-form/sample-forms** folder. ![Screenshot of sampleforms container.](./images/container_img.jpg) ## Train a model **without labels** using the client library You will use the Form Recognizer SDK to train and test a custom model. > **Note**: In this exercise, you can choose to use the API from either the **C#** or **Python** SDK. In the steps below, perform the actions appropriate for your preferred language. 1. Browse to the **20-custom-form** folder and expand the **C-Sharp** or **Python** folder depending on your language preference. 2. Right-click the **train-without-labels** folder and open an integrated terminal. <a id="package"></a> Install the Form Recognizer package by running the appropriate command for your language preference: **C#** ``` dotnet add package Azure.AI.FormRecognizer --version 3.0.0 ``` **Python** ``` pip install azure-ai-formrecognizer ``` 3. View the contents of the **train-without-labels** folder, and note that it contains a file for configuration settings: - **C#**: appsettings.json - **Python**: .env Open the configuration file. You will need a Form Recognizer key and endpoint, and the URI of your blob container for the configuration file. ### Get the Form Recognizer keys and endpoint 1. Navigate from the Azure Portal to the **Form Recognizer** resource you created earlier. 2. Select **Keys and Endpoint** on the left hand panel. Copy **Key 1** and **Endpoint** into the configuration file. <a id ="sig"></a> ### Create a Shared Access Signature Now you will obtain our storage blob container's URI by creating a Shared Access Signature. 1. Navigate from the Azure Portal to your resources. From the main menu of your Storage Account, navigate to **Storage Explorer**, select **BLOB CONTAINERS**, and right click on the container **sampleforms**. ![Visual of how to get shared access signature.](./images/shared_access_sig.jpg) 2. Select **Get Shared Access Signature**. Then use the following configurations: - Access Policy: (none) - Start time: *leave as is for this exercise* - End time: *leave as is for this exercise* - Time Zone: Local - Permissions: _Select **Read** and **List**_ 3. Select **Create** and copy the **URI**. ![Visual of how to copy Shared Access Signature URI.](./images/sas_example.jpg) 4. Paste it to your local configuration file's storage url value. 4. Note that the **train-without-labels** folder contains a code file for the client application: - **C#**: Program.cs - **Python**: train-model-without-labels&period;py Open the code file and review the code it contains, noting the following details: - Namespaces from the package you installed are imported - The **Main** function retrieves the configuration settings, and uses the key and endpoint to create an authenticated **Client**. > **C#**: The code uses the the training client with the <mark>StartTrainingAsync</mark> function and <mark>useTrainingLabels: false</mark> parameter. > **Python**: The code uses the training client with the <mark>begin_training</mark> function and <mark>use_training_labels=False</mark> parameter. 5. Return the integrated terminal for the **train-without-labels** folder, and enter the following command to run the program: **C#** ``` dotnet run ``` **Python** ``` python train-model-without-labels.py ``` 6. Wait for the program to end. 7. Review the model output and locate the Model ID in the terminal. 8. Copy the Model ID from the terminal output. You will use it when analyzing new forms. Now you're ready use your trained model. Notice how you trained your model using files from a storage container URI. You could also have trained the model using local files. Similarly, you can test your model using forms from a URI or from local files. You will test the form model with a local file. ## Test the model created without labels Now that you've got the model ID, you can use it from a client application. Once again, you can choose to use **C#** or **Python**. 1. Browse to the **20-custom-form** folder and in the folder for your preferred language (**C-Sharp** or **Python**), expand the **test-without-labels** folder. 2. Right-click the **test-without-labels** folder. Open the code file for your client application (*Program.cs* for C#, *test-model-without-labels&period;py* for Python) and review the code it contains, noting the following details: - Namespaces from the package you installed are imported - The **Main** function retrieves the configuration settings, and uses the key and endpoint to create an authenticated **Client**. >**C#**: Notice that the program uses the <mark>StartRecognizeCustomForms</mark> function. If we were to analyze files from a storage blob URI we would use the <mark>StartRecognizeCustomFormsFromUri</mark> function. >**Python**: Notice the program uses the same <mark>begin_recognize_custom_forms</mark> function with different parameters depending on whether we are analyzing files from a storage blob URI or local file. 5. Return the integrated terminal for the **test-without-labels** folder, and enter the following SDK-specific command to run the program: **C#** ``` dotnet run ``` **Python** ``` python test-model-without-labels.py ``` 6. View the output and notice the prediction confidence scores. Notice how the output provides field names field-1, field-2 etc. >**Check In**: Can you find either of these fields in the terminal output? >Field 'field-X' has label 'Vendor Name:' with value 'Dwight Schrute' and a confidence score of .. >Field 'field-X' has label 'Company Name:' with value 'Dunder Mifflin Paper' and a confidence score of .. Now let's train a model using labels. ## Train a model **with** labels using the client library Suppose after you trained a model with the invoice forms, you wanted to see how a model trained on labeled data performs. If you have not done so, please return to the [top of the page](#blob) and follow instructions to upload all the sample form files to a Storage Blob. 1. In Visual Studio Code open the **AI-102** project, and in the **Explorer** pane, browse to the **20-custom-form** folder and expand the **C-Sharp** or **Python** folder depending on your language preference. 2. Right-click the **train-with-labels** folder and open an integrated terminal. If you have not already done so, [see here for directions](#package) to install the Form Recognizer package by running the appropriate command for your language. 3. When you trained a model without labels you only used the **.jpg** forms from your Azure blob container. Now you will train a model using the **.jpg** and **.json** files. 4. View the contents of the **train-with-labels** folder, and note that it contains a file for configuration settings: - **C#**: appsettings.json - **Python**: .env Open the configuration file. Update the configuration values it contains to reflect the endpoint and key for your Form Recognizer resource, and container Shared Access Signature. You can use the same Form Recognizer key and endpoint created earlier. If you have not created a Form Recognizer Resource, [follow the directions here](#getform). ### Get the Form Recognizer keys and endpoint 1. Navigate to the Form Recognizer resource. 2. Select **Keys and Endpoint** on the left hand panel. Copy the key and endpoint into the configuration file. You can use the same Shared Access Signature as you did before to configure the storage URI setting. You can review the [get Container's Shared Access Signature](#sig) section if you have not created your container's Shared Access Signature. 5. Note that the **train-with-labels** folder contains a code file for the client application: - **C#**: Program.cs - **Python**: train-model-with-labels&period;py Open the code file and review the code it contains, noting the following details: - Namespaces from the package you installed are imported - The **Main** function retrieves the configuration settings, and uses the key and endpoint to create an authenticated **Client**. > **C#**: The code uses the the training client with the <mark>StartTrainingAsync</mark> function and <mark>useTrainingLabels: true</mark> parameter. > **Python**: The code uses the training client with the <mark>begin_training</mark> function and <mark>use_training_labels=True</mark> parameter. 6. Return the integrated terminal for the **train-with-labels** folder, and enter the following command to run the program: **C#** ``` dotnet run ``` **Python** ``` python train-model-with-labels.py ``` 7. Wait for the program to end, then review the model output. 8. Copy the Model ID in the terminal output. You will use your Model ID when analyzing new forms. ## Test the model created with labels Now that you've got the model ID, test out the model. Once again, you can choose to use **C#** or **Python**. 1. In Visual Studio Code, in the **AI-102** project, browse to the **20-custom-form** folder and in the folder for your preferred language (**C-Sharp** or **Python**), expand the **test-with-labels** folder. 2. Right-click the **test-with-labels** folder. Open the code file for your client application (*Program.cs* for C#, *test-model-with-labels&period;py* for Python) and review the code it contains, noting the following details: - Namespaces from the package you installed are imported - The **Main** function retrieves the configuration settings, and uses the key and endpoint to create an authenticated **Client**. >**C#**: Notice that the program uses the <mark>StartRecognizeCustomForms</mark> function. If we were to analyze files from a storage blob URI we would use the <mark>StartRecognizeCustomFormsFromUri</mark> function. >**Python**: Notice the program uses the same <mark>begin_recognize_custom_forms</mark> function with different parameters depending on whether we are analyzing files from a storage blob URI or local file. 3. Return the integrated terminal for the **test-with-labels** folder, and enter the following SDK-specific command to run the program: **C#** ``` dotnet run ``` **Python** ``` python test-model-with-labels.py ``` 4. View the output and notice the prediction confidence scores. Observe how the output for the model trained **with** labels provides field names like "CompanyPhoneNumber" and "DatedAs" unlike the output from the model trained **without** labels, which produced an output of field-1, field-2 etc. >**Check in**: Now that you have trained a custom model using Form Recognizer _with_ and _without_ labels, what similarities and differences do you see in the processes? While the program code for training a model with labels may not differ greatly from the code for training without labels, choosing one versus another can greatly change your project timeline. For example, if you use labeled forms you will need to label your documents (something we did not cover in this exercise but you can explore [here with the sample labeling tool](https://docs.microsoft.com/en-us/azure/cognitive-services/form-recognizer/quickstarts/label-tool?tabs=v2-0)). The choice of model also affects the downstream processes based on what fields the model returns and how confident you are with the returned values. ## More information For more information about the Form Recognizer service, see the [Form Recognizer documentation](https://docs.microsoft.com/azure/cognitive-services/form-recognizer/). <file_sep>/02-cognitive-security/Python/keyvault-client/keyvault-client.py from dotenv import load_dotenv import os from azure.ai.textanalytics import TextAnalyticsClient from azure.core.credentials import AzureKeyCredential from azure.keyvault.secrets import SecretClient from azure.identity import DefaultAzureCredential def main(): global cog_endpoint global cog_key try: # Get Configuration Settings load_dotenv() cog_endpoint = os.getenv('COG_SERVICE_ENDPOINT') key_vault_name = os.getenv('KEY_VAULT') # Get secret cognitive services key from keyvault key_vault_uri = f"https://{key_vault_name}.vault.azure.net/" credential = DefaultAzureCredential() secret_client = SecretClient(key_vault_uri, credential) secret_key = secret_client.get_secret("Cognitive-Services-Key") cog_key = secret_key.value # Get user input (until they enter "quit") userText ='' while userText.lower() != 'quit': userText = input('\nEnter some text ("quit" to stop)\n') if userText.lower() != 'quit': language = GetLanguage(userText) print('Language:', language) except Exception as ex: print(ex) def GetLanguage(text): # Create client using endpoint and key credential = AzureKeyCredential(cog_key) client = TextAnalyticsClient(endpoint=cog_endpoint, credential=credential) # Call the service to get the detected language detectedLanguage = client.detect_language(documents = [text])[0] return detectedLanguage.primary_language.name if __name__ == "__main__": main()<file_sep>/instructions/02-cognitive-services-security.md # Manage Cognitive Services Security Security is a critical consideration for any application, and as a developer you should ensure that access to resources such as cognitive services is restricted to only those who require it. Access to cognitive services is typically controlled through authentication keys, which are generated when you initially create a cognitive services resource. ## Clone the repository for this course If you have not already done so, you must clone the code repository for this course: 1. Start Visual Studio Code. 2. Open the palette (SHIFT+CTRL+P) and run a `Git: Clone` command to clone the `https://github.com/GraemeMalcolm/AI-102` repository to a local folder. 3. When the repository has been cloned, open the folder in Visual Studio Code. 4. Wait while additional files are installed to support the C# code projects in the repo. ## Provision a Cognitive Services resource If you don't already have on in your subscription, you'll need to provision a **Cognitive Services** resource. 1. Open the Azure portal at [https://portal.azure.com](https://portal.azure.com), and sign in using the Microsoft account associated with your Azure subscription. 2. Select the **&#65291;Create a resource** button, search for *cognitive services*, and create a **Cognitive Services** resource with the following settings: - **Subscription**: *Your Azure subscription* - **Resource group**: *Choose or create a resource group (if you are using a restricted subscription, you may not have permission to create a new resource group - use the one provided)* - **Region**: *Choose any available region* - **Name**: *Enter a unique name* - **Pricing tier**: Standard S0 3. Select the required checkboxes and create the resource. 4. Wait for deployment to complete, and then view the deployment details. ## Manage authentication keys When you created your cognitive services resource, two authentication keys were generated. You can manage these in the Azure portal or by using the Azure command line interface (CLI). 1. In the Azure portal, go to your cognitive services resource and view its **Keys and Endpoint** page. This page contains the information that you will need to connect to your resource and use it from applications you develop. Specifically: - An HTTP *endpoint* to which client applications can send requests. - Two *keys* that can be used for authentication (client applications can use either of the keys. A common practice is to use one for development, and another for production. You can easily regenerate the development key after developers have finished their work to prevent continued access). - The *location* where the resource is hosted. This is required for requests to some (but not all) APIs. 2. In Visual Studio Code, open a terminal and enter the following command to sign into your Azure subscription by using the Azure CLI. ```azurecli az login ``` If you are not already signed in, a web browser will open and prompt you to sign into Azure. Do so, and then close the browser and return to Visual Studio Code. > **Tip**: If you have multiple subscriptions, you'll need to ensure that you are working in the one that contains your cognitive services resource. Use this command to determine your current subscription. > > ```azurecli > az account show > ``` > > If you need to change the subscription, run this command, changing *&lt;subscriptionName&gt;* to the correct subscription name. > > ```azurecli > az account set --subscription <subscriptionName> > ``` 3. Now you can use the following command to get the list of cognitive services keys, replacing *&lt;resourceName&gt;* with the name of your cognitive services resource, and *&lt;resourceGroup&gt;* with the name of the resource group in which you created it. ```azurecli az cognitiveservices account keys list --name <resourceName> --resource-group <resourceGroup> ``` The command returns a list of the keys for your cognitive services resource - there are two keys, named **key1** and **key2**. 4. To test your cognitive service, you can use *curl* - a command line tool for HTTP requests. Enter the following command (on a single line), replacing *&lt;yourEndpoint&gt;* and *&lt;yourKey&gt;* with your endpoint URI and **Key1** key to use the Text Analytics API in your cognitive services resource. ```curl curl -X POST "<yourEndpoint>/text/analytics/v3.0/languages?" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: <yourKey>" --data-ascii "{'documents':[{'id':1,'text':'hello'}]}" ``` The command returns a JSON document containing information about the language detected in the input data (which should be English). 5. If a key becomes compromised, or the developers who have it no longer require access, you can regenerate it in the portal or by using the Azure CLI. Run the following command to regenerate your **key1** key (replacing *&lt;resourceName&gt;* and *&lt;resourceGroup&gt;* for your resource). ```azurecli az cognitiveservices account keys regenerate --name <resourceName> --resource-group <resourceGroup> --key-name key1 ``` The list of keys for your cognitive services resource is returned - note that **key1** has changed since you last retrieved them. 6. Re-run the *curl* command with the old key (you can use the **^** key to cycle through previous commands), and verify that it now fails. 7. Re-run the *curl* command, replacing the key with the new **key1** value and verify that it succeeds. > **Tip**: In this exercise, you used the full names of Azure CLI parameters, such as ``` --resource-group ```. You can also use shorter alternatives, such as ``` -g ```, to make your commands less verbose (but a little harder to understand). The [Cognitive Services CLI command reference](https://docs.microsoft.com/cli/azure/cognitiveservices?view=azure-cli-latest) lists the parameter options for each cognitive services CLI command. ## Secure key access with Azure Key Vault You can develop applications that consume cognitive services by using a key for authentication. However, this means that the application code must be able to obtain the key. One option is to store the key in an environment variable or a configuration file where the application is deployed, but this approach leaves the key vulnerable to unauthorized access. A better approach when developing applications on Azure is to store the key securely in Azure Key Vault, and provide access to the key through a *managed identity* (in other words, a user account used by the application itself). ### Create a key vault and add a secret First, you need to create a key vault and add a *secret* for the cognitive services key. 1. Make a note of the **key1** value for your cognitive services resource (or copy it to the clipboard). 2. In the Azure portal, select the **&#65291;Create a resource** button, search for *Key Vault*, and create a **Key Vault** resource with the following settings: - **Subscription**: *Your Azure subscription* - **Resource group**: *The same resource group as your cognitive service resource* - **Key vault name**: *Enter a unique name* - **Region**: *The same region as your cognitive service resource* - **Pricing tier**: Standard 3. Wait for deployment to complete and then go to your key vault resource. 4. In the left navigation pane, select **Secrets** (in the Settings section). 5. Select **+ Generate/Import** and add a new secret with the following settings : - **Upload options**: Manual - **Name**: Cognitive-Services-Key *(it's important to match this exactly, because later you'll run code that retrieves the secret based on this name)* - **Value**: *Your **key1** cognitive services key* ### Create a service principal To access the secret in the key vault, your application must use a service principal that has access to the secret. 1. To create a service principal with owner role on the resource group, run the following Azure CLI command, replacing *&lt;spName&gt;* with a suitable name for an application identity (for example, *ai-app*). Also replace *&lt;subscriptionId&gt;* and *&lt;resourceGroup&gt;* with the correct values for your subscription ID and the resource group containing your cognitive services and key vault resources: > **Tip**: If you are unsure of your subscription ID, use the `az account show` command to retrieve your subscription information - the subscription ID is the **id** attribute in the output. ```azurecli az ad sp create-for-rbac -n "https://<spName>" --role owner --scopes subscriptions/<subscriptionId>/resourceGroups/<resourceGroup> ``` The output of this command includes information about your new service principal. It should look similar to this: ```azurecli { "appId": "abcd1<PASSWORD>", "displayName": "ai-app", "name": "https://ai-app", "password": "<PASSWORD>", "tenant": "1234abcd5<PASSWORD>" } ``` Make a note of the **appId**, **password**, and **tenant** values - you will need them later (if you close this terminal, you won't be able to retrieve the password; so it's important to note the values now!) 2. To assign permission for your new service principal to access secrets in your Key Vault, run the following Azure CLI command, replacing *&lt;keyVaultName&gt;* with the name of your Azure Key Vault resource and *&lt;spName&gt;* with the same value you provided when creating the service principal. ```azurecli az keyvault set-policy -n <keyVaultName> --spn "https://<spName>" --secret-permissions get list ``` ### Use the service principal in an application Now you're ready to use the service principal identity in an application, so it can access the secret congitive services key in your key vault and use it to connect to your cognitive services resource. > **Note**: In this exercise, we'll store the service principal credentials in environment variables and use them to authenticate the **DefaultAzureCredential** identity in your application code. This is fine for development and testing, but in a real production application, an administrator would assign a *managed identity* to the application so that it uses the service principal identity to access resources, without caching or storing the password. 1. In Visual Studio Code, in the **AI-102** project, browse to the **02-cognitive-security** folder and expand the **C-Sharp** or **Python** folder depending on your language preference. 2. Right-click the **keyvault-client** folder and open an integrated terminal. Then install the packages you will need to use Azure Key Vault and the Text Analytics API in your cognitive services resource by running the appropriate command for your language preference: **C#** ``` dotnet add package Azure.AI.TextAnalytics --version 5.0.0 dotnet add package Azure.Identity --version 1.3.0 dotnet add package Azure.Security.KeyVaults.Secrets --version 4.1.0 ``` **Python** ``` pip install azure-ai-textanalytics==5.0.0 pip install azure-identity==1.5.0 pip install azure-keyvault-secrets==4.2.0 ``` 3. View the contents of the **keyvault-client** folder, and note that it contains a file for configuration settings: - **C#**: appsettings.json - **Python**: .env Open the configuration file and update the configuration value it contains to reflect the **endpoint** for your Cognitive Services resource and the name of the Azure Key Vault resource. Save your changes. 4. Note that the **keyvault-client** folder contains a code file for the client application: - **C#**: Program.cs - **Python**: keyvault-client&period;py Open the code file and review the code it contains, noting the following details: - The namespace for the SDK you installed is imported - Code in the **Main** function retrieves the cognitive services endpoint and name of your key vault resource, and then it uses the default Azure credentials to get the cognitive services key from the key vault. - The **GetLanguage** function uses the SDK to create a client for the service, and then uses the client to detect the language of the text that was entered. 5. Return to the integrated terminal for the **keyvault-client** folder, and run the following commands to set environment variables, replacing *&lt;appId&gt;*, *&lt;tenant&gt;*, and, *&lt;password&gt;* with the corresponding values from the output when you created the service principal. These are used for the default Azure credentials, and will cause your application to use the service principal identity. ```azurecli setx AZURE_CLIENT_ID <appId> setx AZURE_TENANT_ID <tenant> setx AZURE_CLIENT_SECRET <password> ``` 6. Enter the following command to run the program: **C#** ``` dotnet run ``` **Python** ``` python keyvault-client.py ``` 6. When prompted, enter some text and review the language that is detected by the service. For example, try entering "Hello", "Bonjour", and "Hola". 7. When you have finished testing the application, enter "quit" to stop the program. ### Reset the security context 1. In the Terminal window, enter the command `az logout` to log out of your Azure subscription. 2. In the Windows Search box, enter **Edit the system environment variables**. Then in the **System Properties** dialog box, select **Environment variables**. 3. Delete the following system environment variables: - AZURE_CLIENT_ID - AZURE_TENANT_ID - AZURE_CLIENT_SECRET ## More information For more information about securing cognitive services, see the [Cognitive Services security documentation](https://docs.microsoft.com/azure/cognitive-services/cognitive-services-security).<file_sep>/instructions/21-video-indexer.md # Analyze Video with Video Indexer A large proportion of the data created and consumed today is in the format of video. **Video Indexer** is an AI-powered service that you can use to index videos and extract insights from them. ## Clone the repository for this course If you have not already done so, you must clone the code repository for this course: 1. Start Visual Studio Code. 2. Open the palette (SHIFT+CTRL+P) and run a `Git: Clone` command to clone the `https://github.com/GraemeMalcolm/AI-102` repository to a local folder. 3. When the repository has been cloned, open the folder in Visual Studio Code. 4. Wait while additional files are installed to support the C# code projects in the repo. ## Sign into the Video Indexer portal The Video Indexer portal provides a web-based interface for managing video indexer projects. 1. Open the Video Indexer portal at [https://www.videoindexer.ai/](https://www.videoindexer.ai/). 2. If you have an existing Video Indexer account, sign in. Otherwise, sign up for a free account and sign in using your Microsoft account (or any other valid account type). ## Upload and index a video You can use the Video Indexer portal to upload and index a video. 1. In Visual Studio Code, expand the **21-video-indexer** folder, and then right-click **responsible_ai.mp4** and select **Reveal in File Explorer**. 2. In Video Indexer, select the **Upload** option. Then drag the **responsible_ai.mp4** from File Manager to the upload area, review the default names and settings, select the checkbox to verify compliance with Microsoft's policies for facial recognition, and upload it. 3. After the file has uploaded, wait a few minutes while Video Indexer automatically indexes it. ## Review video insights The indexing process extracts insights from the video, which you can view in the portal. 1. When the video is indexed, select it to view it in the portal. You'll see the video player alongside a pane that shows insights extracted from the video. ![Video indexer with a video player and Insights pane](./images/video-indexer-insights.png) 2. As the video plays, select the **Timeline** tab to view a transcript of the video audio. ![Video indexer with a video player and Timeline pane showing the vide transcript.](./images/video-indexer-transcript.png) 3. At the top left of the portal, select the **View** symbol (which looks similar to &#128455;), and in the list of insights, in addition to **Transcript**, select **OCR** and **Speakers**. ![Video indexer view menu with Transcript, OCR, and Speakers selected](./images/video-indexer-view-menu.png) 4. Observe that the **Timeline** pane now includes: - Transcript of audio narration. - Text visible in the video. - Indications of speakers who appear in the video. Some well-known people are automatically recognized by name, others are indicated by number (for example *Speaker #1*). 5. Switch back to the **Insights** pane and view the insights show there. They include: - Individual people who appear in the video. - Topics discussed in the video. - Labels for objects that appear in the video. - Named entities, such as people and brands that appear in the video. - Key scenes. 6. With the **Insights** pane visible, select the **View** symbol again, and in the list of insights, add **Keywords** and **Sentiments** to the pane. The insights found can help you determine the main themes in the video. For example, the **topics** for this video show that it is clearly about technology, social responsibility, and ethics. ## Search for insights You can use Video indexer to search the video for insights. 1. In the **Insights** pane, in the **Search** box, enter *Bee*. You may need to scroll down in the Insights pane to see results for all types of insight. 2. Observe that one matching *label* is found, with its location in the video indicated beneath. 3. Select the beginning of the section where the presence of a bee is indicated, and view the video at that point (you may need to pause the video and select carefully - the bee only appears briefly!) ![Video indexer search results for Bee](./images/video-indexer-search.png) ## Edit insights You can use Video Indexer to edit the insights that have been found, adding custom information to make even more sense of the video. 1. Rewind the video to the start and view the **people** listed at the top of the **Insights** pane. Observe that some people have been recognized, including **<NAME>**, a computer scientist and Technical Fellow at Microsoft. ![Video indexer insights for a known person](./images/video-indexer-known-person.png) 2. Select the photo of <NAME>, and view the information underneath - expanding the **Show biography** section to see information about this person. 3. Observe that the locations in the video where this person appears are indicated. You can use these to view those sections of the video. 4. In the video player, find the person speaking at approximately 0:34: ![Video indexer insights for an unknown person](./images/video-indexer-unknown-person.png) 5. Observe that this person is not recognized, and has been assigned a generic name such as **Unknown #1**. However, the video does include a caption with this person's name, so we can enrich the insights by editing the details for this person. 6. At the top right of the portal, select the **Edit** icon (&#x1F589;). Then change the name of the unknown person to **<NAME>**. ![Editing a person in Video Indexer](./images/video-indexer-edit-name.png) 7. After you have made the name change, search the **Insights** pane for *Natasha*. The results should include one person, and indicate the sections of the video in which they appear. 8. At the top left of the portal, expand the menu (&#8801;) and select the **Model customizations** page. Then on the **People** tab, observe that the **Default** people model has one person in it. Video Indexer has added the person you named to a people model, so that they will be recognized in any future videos you index in your account. ![The default people model in Video Indexer](./images/video-indexer-custom-model.png) You can add images of people to the default people model, or add new models of your own. This enables you to define collections of people with images of their face so that Video Indexer can recognize them in your videos. Observe also that you can also create custom models for language (for example to specify industry-specific terminology you want Video Indexer to recognize) and brands (for example, company or product names). ## Use Video Indexer widgets The Video Indexer portal is a useful interface to manage video indexing projects. However, there may be occasions when you want to make the video and its insights available to people who don't have access to your Video Indexer account. Video Indexer provides widgets that you can embed in a web page for this purpose. 1. In Visual Studio Code, in the **21-video-indexer** folder, open **analyze-video.html**. This is a basic HTML page to which you will add the Video Indexer **Player** and **Insights** widgets. Note the reference to the **vb.widgets.mediator.js** script in the header - this script enables multiple Video Indexer widgets on the page to interact with one another. 2. In the Video Indexer portal, return to the **Media files** page and open your **responsible_ai** video. 3. Under the video player, select **\</> Embed** to view the HTML iframe code to embed the widgets. 4. In the **Share and Embed** dialog box, select the **Player** widget and then copy the embed code to the clipboard. 5. In Visual Studio Code, in the **analyze-video.html** file, paste the copied code under the comment **\<-- Player widget goes here -- >**. 6. Edit the Player widget code to change the **width** and **height** properties to **400** and **300* respectively. 6. Back in the **Share and Embed** dialog box, select the **Insights** widget and then copy the embed code to the clipboard. Then close the **Share and Embed** dialog box, switch back to Visual Studio Code, and paste the copied code under the comment **\<-- Insights widget goes here -- >**. 7. Edit the Insights widget code to change the **width** and **height** properties to **350** and **600** respectively. 8. Save the file. Then in the **Explorer** pane, right-click **analyze-video.html** and select **Reveal in File Explorer**. 9. In File Explorer, open **analyze-video.html** in your browser to see the web page. 10. Experiment with the widgets, using the **Insights** widget to search for insights and jump to them in the video. ![Video Indexer widgets in a web page](./images/video-indexer-widgets.png) ## More information For more information about **Video Indexer****, see the [Video Indexer documentation](https://docs.microsoft.com/azure/media-services/video-indexer/). <file_sep>/instructions/04-use-a-container.md # Use a Cognitive Services Container Using cognitive services hosted in Azure enables application developers to focus on the infrastructure for their own code while benefiting from scalable services that are managed by Microsoft. However, in many scenarios, organizations require more control over their service infrastructure and the data that is passed between services. Many of the cognitive services APIs can be packaged and deployed in a *container*, enabling organizations to host cognitive services in their own infrastructure; for example in local Docker servers, Azure Container Instances, or Azure Kubernetes Services clusters. Containerized cognitive services need to communicate with an Azure-based cognitive services account to support billing; but application data is not passed to the back-end service, and organizations have greater control over the deployment configuration of their containers, enabling custom solutions for authentication, scalability, and other considerations. ## Provision a Cognitive Services resource If you don't already have on in your subscription, you'll need to provision a **Cognitive Services** resource. 1. Open the Azure portal at [https://portal.azure.com](https://portal.azure.com), and sign in using the Microsoft account associated with your Azure subscription. 2. Select the **&#65291;Create a resource** button, search for *cognitive services*, and create a **Cognitive Services** resource with the following settings: - **Subscription**: *Your Azure subscription* - **Resource group**: *Choose or create a resource group (if you are using a restricted subscription, you may not have permission to create a new resource group - use the one provided)* - **Region**: *Choose any available region* - **Name**: *Enter a unique name* - **Pricing tier**: Standard S0 3. Select the required checkboxes and create the resource. 4. Wait for deployment to complete, and then view the deployment details. 5. When the resource has been deployed, go to it and view its **Keys and Endpoint** page. You will need the endpoint and one of the keys from this page in the next procedure. ## Deploy and run a Text Analytics container Many commonly used cognitive services APIs are available in container images. For a full list, check out the [cognitive services documentation](https://docs.microsoft.com/azure/cognitive-services/cognitive-services-container-support#container-availability-in-azure-cognitive-services). In this exercise, you'll use the container image for the Text Analytics *language detection* API; but the principles are the same for all of the available images. 1. In the Azure portal, select the **&#65291;Create a resource** button, search for *container instances*, and create a **Container Instances** resource with the following settings: - **Basics**: - **Subscription**: *Your Azure subscription* - **Resource group**: *Choose the resource group containing your cogntive services resource* - **Container name**: *Enter a unique name* - **Region**: *Choose any available region* - **Image source**: Docker Hub or other Registry - **Image type**: Public - **Image**: `mcr.microsoft.com/azure-cognitive-services/textanalytics/language` - **OS type**: Linux - **Size**: 1 vcpu, 4 GB memory - **Networking**: - **Networking type**: Public - **DNS name label**: *Enter a unique name for the container endpoint* - **Ports**: *Change the TCP port from 80 to **5000*** - **Advanced**: - **Restart policy**: On failure - **Environment variables**: | Mark as secure | Key | Value | | -------------- | --- | ----- | | Yes | ApiKey | *Either key for your cognitive services resource* | | Yes | Billing | *The endpoint URI for your cognitive services resource* | | No | Eula | accept | - **Command override**: [ ] - **Tags**: - *Don't add any tags* 2. Wait for deployment to complete, and then go to the deployed resource. 3. Observe the following properties of your container instance resource on its **Overview**page: - **Status**: This should be *Running*. - **IP Address**: This is the public IP address you can use to access your container instances. - **FQDN**: This is the *fully-qualified domain name* of the container instances resource, you can use this to access the container instances instead of the IP address. > **Note**: In this exercise, you've deployed the cognitive services container image for text translation to an Azure Container Instances (ACI) resource. You can use a similar approach to deploy it to a *[Docker](https://www.docker.com/products/docker-desktop)* host on your own computer or network by running the following command (on a single line) to deploy the language detection container to your local Docker instance, replacing *&lt;yourEndpoint&gt;* and *&lt;yourKey&gt;* with your endpoint URI and either of the keys for your cognitive services resource. > > ```bash > docker run --rm -it -p 5000:5000 --memory 4g --cpus 1 mcr.microsoft.com/azure-cognitive-services/textanalytics/language Eula=accept Billing=<yourEndpoint> ApiKey=<yourKey> > ``` > > The command will look for the image on your local machine, and if it doesn't find it there it will pull it from the *mcr&period;microsoft&period;com* image registry and deploy it to your Docker instance. When deployment is complete, the container will start and listen for incoming requests on port 5000. ## Use the container 1. Start Visual Studio Code and open a new terminal window. 2. In the new terminal, enter the following command (replacing *<your_ACI_IP_address_or_FQDN>* with the IP address or FQDN for your container) to call the language detection REST API in your container. Note that you do not need to specify the cognitive services endpoint or key - the request is processed by the containerized service. The container in turn communicates periodically with the service in Azure to report usage for billing, but does not send request data. ```curl curl -X POST "http://<your_ACI_IP_address_or_FQDN>:5000/text/analytics/v3.0/languages?" -H "Content-Type: application/json" --data-ascii "{'documents':[{'id':1,'text':'Hello world.'},{'id':2,'text':'Salut tout le monde.'}]}" ``` The command returns a JSON document containing information about the language detected in the two input documents (which should be English and French). ## More information For more information about containerizing cognitive services, see the [Cognitive Services containers documentation](https://docs.microsoft.com/azure/cognitive-services/containers/). <file_sep>/22-Create-a-search-solution/C-Sharp/margies-travel/Pages/Index.cshtml.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.WebUtilities; using search_client.Models; using Microsoft.Extensions.Configuration; // Import namespaces namespace search_client.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } private Uri SearchEndpoint; private string QueryKey; private string IndexName; public string SearchTerms { get; set; } = ""; public string SortOrder { get; set; } = "search.score()"; public string FilterExpression { get; set; } = ""; public SearchResults<SearchResult> search_results; //Wrapper function for request to search index public SearchResults<SearchResult> search_query(string searchText, string filterBy, string sortOrder) { // Create a search client // Submit search query } public void OnGet() { // Get the search endpoint and key IConfigurationBuilder _builder = new ConfigurationBuilder().AddJsonFile("appsettings.json"); IConfigurationRoot _configuration = _builder.Build(); SearchEndpoint = new Uri(_configuration["SearchServiceEndpoint"]); QueryKey = _configuration["SearchServiceQueryApiKey"]; IndexName = _configuration["SearchIndexName"]; if (Request.QueryString.HasValue){ var queryString = QueryHelpers.ParseQuery(Request.QueryString.ToString()); SearchTerms = queryString["search"]; if (queryString.Keys.Contains("sort")){ SortOrder = queryString["sort"]; } if (queryString.Keys.Contains("facet")){ FilterExpression = "metadata_author eq '" + queryString["facet"] + "'"; } else { FilterExpression = ""; } search_results = search_query(SearchTerms, SortOrder, FilterExpression); } else{ SearchTerms=""; } } } } <file_sep>/20-custom-form/Python/train-with-labels/train-model-with-labels.py import os from dotenv import load_dotenv from azure.core.exceptions import ResourceNotFoundError from azure.ai.formrecognizer import FormRecognizerClient from azure.ai.formrecognizer import FormTrainingClient from azure.core.credentials import AzureKeyCredential def main(): try: # Get configuration settings load_dotenv() form_endpoint = os.getenv('FORM_ENDPOINT') form_key = os.getenv('FORM_KEY') # To train a model you need your Blob URI to access your training files trainingDataUrl = os.getenv('STORAGE_URL') # Create client using endpoint and key form_recognizer_client = FormRecognizerClient(form_endpoint, AzureKeyCredential(form_key)) form_training_client = FormTrainingClient(form_endpoint, AzureKeyCredential(form_key)) # Use Training Labels = True poller = form_training_client.begin_training(trainingDataUrl, use_training_labels=True) model = poller.result() print("Model ID: {}".format(model.model_id)) print("Status: {}".format(model.status)) print("Training started on: {}".format(model.training_started_on)) print("Training completed on: {}".format(model.training_completed_on)) print("\nRecognized fields:") for submodel in model.submodels: print( "The submodel with form type '{}' has recognized the following fields: {}".format( submodel.form_type, ", ".join( [ field.label if field.label else name for name, field in submodel.fields.items() ] ), ) ) # Training result information for doc in model.training_documents: print("Document name: {}".format(doc.name)) print("Document status: {}".format(doc.status)) print("Document page count: {}".format(doc.page_count)) print("Document errors: {}".format(doc.errors)) except Exception as ex: print(ex) if __name__ == '__main__': main()
ed56fe0cc940a398f80ebf77163269f3844894a9
[ "Markdown", "C#", "Python" ]
8
Markdown
GraemeMalcolm/AI-102
f5d2d5601df761bb93560e4549d345c62fb79e17
629c560b8919fbbebeea7b8917240a524e5760e2
refs/heads/master
<repo_name>HyunSu-Jin/Graph<file_sep>/README.md # Graph ###implemented by AjacentList ##BFS <file_sep>/main.cpp #include <iostream> #include "graph.h" int main() { int vertices[] = { 0,1,2,3,4}; Edge edges[] = { Edge(0,1),Edge(0,2),Edge(1,2),Edge(2,3),Edge(1,3),Edge(1,4) }; Graph graph = Graph(vertices,sizeof(vertices)/sizeof(int),edges,sizeof(edges)/sizeof(Edge)); //graph.printGraph(); graph.showAjacentList(); cout << "from 0 to 3 edge exist?" << endl; if (graph.hasEdge(0, 3)) { cout << "true" << endl; } else { cout << "false" << endl; } graph.BFS(0); }<file_sep>/graph.h #include <iostream> #include <list> #include <string> #include <queue> using namespace std; class Edge { private: int from; int to; int weight; public: Edge(int from, int to) :from(from),to(to),weight(1){ } Edge(int from, int to,int weight) :from(from), to(to), weight(weight) { } int getFrom() { return from; } int getTo() { return to; } int getWeight() { return weight; } string toString() { string str = "(" + to_string(from) + "," + to_string(to) + ") : " + to_string(weight); return str; } }; class Graph { class AjacentNode { private: int vertex; int weight; public: AjacentNode(int vertex, int weight) { this->vertex = vertex; this->weight = weight; } int getVertex() { return vertex; } int getWeight() { return weight; } }; private: int* vertice; int vertexNum; Edge* edges; int edgeNum; list<AjacentNode>* ajacentList; public: Graph(int* vertice, int vertexNum, Edge* edges, int edgeNum) { this->vertice = vertice; this->vertexNum = vertexNum; this->edges = edges; this->edgeNum = edgeNum; ajacentList = new list<AjacentNode>[vertexNum]; for (int i = 0; i < edgeNum; i++) { Edge edge = edges[i]; int from = edge.getFrom(); int to = edge.getTo(); int weight = edge.getWeight(); ajacentList[from].push_back(AjacentNode(to, weight)); ajacentList[to].push_back(AjacentNode(from, weight)); } } void showVertice(){ cout << "vertice : "; for (int i = 0; i < vertexNum; i++) { cout << vertice[i] << " "; } cout << endl; } void showEdges() { cout << "edges : "; for (int i = 0; i < edgeNum; i++) { cout << edges[i].toString() << " "; } cout << endl; } void printGraph() { showVertice(); showEdges(); } void showAjacentList() { for (int i = 0; i < vertexNum; i++) { list<AjacentNode> items = ajacentList[i]; cout << "from vertex , " << i << " : "; for (AjacentNode item : items) { cout << "(" << item.getVertex() << "," << item.getWeight() << ") "; } cout << endl; } } /*It costs Big O of vertexNum <=> O(V)*/ bool hasEdge(int from, int to) { list<AjacentNode> items = ajacentList[from]; for (AjacentNode item : items) { if (item.getVertex() == to) { return true; } } return false; } void BFS(int root) { enum COLOR{ WHITE, // It is not discovered GRAY, // It is discovered BLACK // It is ended }; class Vertex { public: int idx; COLOR color; int distance; Vertex * predecessor; public: Vertex() { } Vertex(const Vertex & copy) { this->idx = copy.idx; this->color = copy.color; this->distance = copy.distance; this->predecessor = copy.predecessor; } Vertex(int idx, COLOR color) { this->idx = idx; this->color = color; distance = 9999; predecessor = NULL; } }; Vertex * verticeArr = new Vertex[vertexNum]; //initialize for (int i = 0; i < vertexNum; i++) { verticeArr[i].idx = i; verticeArr[i].color = WHITE; verticeArr[i].distance = 9999; verticeArr[i].predecessor = NULL; } verticeArr[root].color = GRAY; verticeArr[root].distance = 0; verticeArr[root].predecessor = NULL; queue<Vertex> myQueue= queue<Vertex>(); myQueue.push(verticeArr[root]); while (!myQueue.empty()) { Vertex * itemPtr = new Vertex(myQueue.front()); cout << "poped" << (*itemPtr).idx << endl; myQueue.pop(); list<AjacentNode> items = ajacentList[(*itemPtr).idx]; for (AjacentNode ele : items) { Vertex &connectedItem = verticeArr[ele.getVertex()]; if (connectedItem.color == WHITE) { connectedItem.color = GRAY; connectedItem.distance = (*itemPtr).distance + 1; connectedItem.predecessor = itemPtr; myQueue.push(connectedItem); } } (*itemPtr).color = BLACK; } for (int i = 0; i < vertexNum; i++) { if (verticeArr[i].predecessor != NULL) { cout << "edge : (" << verticeArr[i].idx << "," << (*(verticeArr[i].predecessor)).idx << ")" << endl; } } } };
7c2030a7bb14be02c461e4c5e7c44dfb3758045b
[ "Markdown", "C++" ]
3
Markdown
HyunSu-Jin/Graph
c0721843654dcaa0875f3cb10d8eaf66a06265ce
61dd88caaf0855b84d5c52492a6c81acc7b761fa
refs/heads/master
<repo_name>alexis900/MobileDataBase<file_sep>/add_brand.php <!DOCTYPE html> <html> <head> <?php include './include/header.php'; ?> <title>Add Brand</title> </head> <body> <?php include './include/nav.php'; ?> <main> <div> <?php include './include/database.php'; if (isset($_FILES) & !empty($_FILES)) { $logo_name = $_FILES['logo']['name']; $logo_type = $_FILES['logo']['type']; $logo_tmp_name = $_FILES['logo']['tmp_name']; $logo_size = $_FILES['logo']['size']; $logo_default = "./images/logo-default.png"; } $location = "./logo_upload/"; $maxsize = 100000; if (isset($logo_name) & !empty($logo_name)) { if ($logo_type == "image/jpeg" || "image/svg" || "image/png" && $logo_size <= $maxsize) { if (move_uploaded_file($logo_tmp_name, $location.$logo_name)) { echo "Upload success!"; } else { echo "ERROR!"; } } else { echo "File should be JPG, PNG or SVG image"; } } if (isset($_POST['brand_submit'])) { $brand = $_POST['brand']; $description = $_POST['description']; if (!empty($logo_name)) { $sql = "INSERT INTO brand (id, brand, description, logo) VALUES ('', '$brand', '$description', '$location$logo_name')"; } else { $sql = "INSERT INTO brand (id, brand, description, logo) VALUES ('', '$brand', '$description', '$logo_default')"; } if ($conn->query($sql) === TRUE) { echo "The brand " . $brand . " has added"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Add Brand</title> </head> <body> <form class="" action="add_brand.php" method="post" enctype="multipart/form-data"> <input type="text" name="brand" value="" placeholder="Name of the brand"><br> <textarea name="description" rows="8" cols="80" placeholder="Description"></textarea><br> <input type="file" name="logo" value=""><br> <input type="submit" name="brand_submit" value="Submit"> </form> <main class="mdl-layout__content"> <div class="page-content"> </div> </main> </div> </div> </body> </html> <file_sep>/list_brand.php <!DOCTYPE html> <html> <head> <?php include './include/header.php';?> <title>List Brand</title> </head> <body> <?php include './include/nav.php'; include './include/database.php'; $sql = "SELECT * FROM brand"; $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { ?> <?php echo " <div class='first_div_list_brand'> <div style='background:url(".$row['logo']."); background-repeat: no-repeat; background-size: 100%;' class='image_logo_brand'> <h2>" . $row['brand']."</h2> </div> <div> " . $row['description']. " </div> <div> <a href='./ibrand.php?id=" . $row['id'] . "'>Read more</a> <a href='./dbrand.php?id=" . $row['id']. "'>Delete</a> </div> </div>"; } }else { echo "0 results"; } $conn->close(); ?> </body> </html> <file_sep>/dbrand.php <?php include 'database.php'; $brand_id = $_GET['id']; // sql to delete a record $sql = "DELETE FROM brand WHERE id=$brand_id"; if ($conn->query($sql) === TRUE) { //header('Location: /messages/branddeleted.php'); header('Location: ./list_brand.php'); } else { echo 'ERROR!' . $conn->error; } $conn->close(); ?> <file_sep>/ibrand.php <!DOCTYPE html> <html> <head> <?php include './include/header.php'; ?> <title></title> </head> <body> <?php include './include/nav.php'; include './include/database.php'; $id = $_GET['id']; /* stackoverflow user: https://stackoverflow.com/users/493122/shoe */ $query = "SELECT * FROM brand WHERE id ='$id'"; if ($result=mysqli_query($conn,$query)) { if(mysqli_num_rows($result) > 0) { echo "Exists"; } else Header('Location: ./errors/404.php'); } else Header('Location: ./errors/500.php'); $conn->close(); ?> </body> </html>
64877b04d9961f289344614c7cda531049331bb1
[ "PHP" ]
4
PHP
alexis900/MobileDataBase
7939c7461c900f72fad29ec61c8a192c93c2ef06
4369e973ed1ad182b8ccbfb465753463f7c26dce
refs/heads/main
<file_sep>#!/usr/bin/env python3 import os # the custom command to be executed with every URL, the URL is substituted inside the {} command = r'.\youtube-dl.exe -f best -ciw -o "%(uploader)s/%(title)s.%(ext)s" -v {}' # channels list file channels_file = 'channels.txt' # file in the same folder # Program entry point if __name__ == "__main__": # open the file try: f = open(channels_file) except: print("There was a problem opening the file {}, please check the file and try again".format(channels_file)) exit() # read the URLs try: channels_list = f.readlines() print("Read {} files".format(len(channels_list))) except: print("There was a problem reading the file {}, please check the file and try again".format(channels_file)) # Execute the custom command for every URL for i, c in enumerate(channels_list): print("Downloading {} of {}".format(i+1, len(channels_list))) os.system(command.format(c)) <file_sep># YTDLChannelArchive NOTE: YTDL IS CURRENTLY EXPERIENCING ISSUES WITH DOWNLOAD SPEED, WE ARE WORKING ON ADDING A DIFFERENT PROGRAM TO THIS REPO TO HELP WITH DOWNLOAD SPEED Use this script to download a list of channels all at once! Currently only working on Windows. Make a channels.txt file in the same dir as the script. download FFMPEG and YTDL No python deps needed, just install python3 and run! #How to run 1. Open powershell as admin 2. Navigate to dir where extracted zip is located 3. type python download.py or python3 download.py depending on configuration 4. Watch the script run! #Tips and tricks If you are going to run on a different HDD. use Set-Location D: (where d is your drive letter) to change drives in powershell! Use cd to change directories and ls to show where you currently are Download file list: add on channel per line for script to work Notes: if you clone directly from this repo, you will need to download the latest ffmpeg windows binaries, which can be found on ffmpegs website Disclaimer: In our release package we include the latest version of ffmpeg and ytdl, all rights go to both of these teams, and shoutout to them for creating awesome software!
aad462c594d9d7fc901abe6bc8fb3ffc8d7633c7
[ "Markdown", "Python" ]
2
Python
baxtmann/YTDLChannelArchive
f548578ac9472201499aadd361105155c888ae75
18fcf4c7addecec613ffbbbbb82c3202b4cba5c8
refs/heads/master
<file_sep>def bubble_sort(our_list): # We go through the list as many times as there are elements for i in range(len(our_list)): # We want the last pair of adjacent elements to be (n-2, n-1) for j in range(len(our_list) - 1): if our_list[j] > our_list[j+1]: # Swap our_list[j], our_list[j+1] = our_list[j+1], our_list[j] # def bubble_sorting(our_list): # last_item = len(our_list) - 1 # for i in range(0, last_item): # for j in range(0, last_item): # if our_list[j] > our_list[j + 1]: # our_list[j], our_list[j + 1] = our_list[j + 1], our_list[j] arr = [3, 2, 13, 4, 6, 5, 7, 8, 1, 20] bubble_sort(arr) print(arr) <file_sep>def check(string_1, string_2): if sorted(string_1.replace(' ', '').lower()) == sorted(string_2.replace(' ', '').lower()): print("Anagram") else: print("Sorry but not this time") s1 = "listen" s2 = "silent" check(s1, s2) s11 = "clint eastwood" s22 = "old west action" check(s11, s22) s111 = "clint eastwwood" s222 = "old west aaaction" check(s111, s222)<file_sep>def binary_search(array, value): first = 0 last = len(array) - 1 found = False while first <= last and not found: mid = (first + last) // 2 if array[mid] == value: found = True else: if value < array[mid]: last = mid - 1 else: first = mid + 1 return found arr = list(range(0, 11)) print(binary_search(arr, 5)) <file_sep>def double_return(fn): def wrapper(*args, **kwargs): val = fn(*args, **kwargs) return [val, val] return wrapper <file_sep>mylist = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow'] def only_ones_in_list(collection): temp_dict = dict() for i in collection: if i in temp_dict: temp_dict[i] += 1 else: temp_dict[i] = 1 res = list([i for i in temp_dict if temp_dict[i] == 1]) return print(res) only_ones_in_list(mylist) <file_sep>def fibonacci(num): if num < 1: return "Wrong input" if num == 1: return 0 if num == 2: return 1 return fibonacci(num - 2) + fibonacci(num - 1) print([fibonacci(num) for num in range(15)]) print(fibonacci(-1)) <file_sep>arr1 = [2, 5, 1, 2, 3, 5, 1, 2, 4] arr2 = [2, 5, 1, 3, 4] ch = "geeksforgeeks" def first(arr): res = {} for i in arr: if i in res: print(res) return f"{i} Is first recurring char in collection" else: res[i] = 0 print(first(arr1))
e4b140a9fa0219f31b9ee15de5273d2b601ba03a
[ "Python" ]
7
Python
N1ki4/python-random-tasks
b9d653e494b42b05b7e17c6d717d5f8149f1c330
c76f976afedaa3aad35306a6ab1ee2f1eb77a696
refs/heads/main
<repo_name>SealSiil/SmiteScrapper<file_sep>/scrapper.py from bs4 import BeautifulSoup import requests import re import pandas as pd def process(match, match_num, playersdict): ''' The function extracts information from the given match by connecting to Smite.guru. Takes three inputs: match an interger that repersents the match ID from Smite, match_num is a interger that prevents the player enties in the playersdict for overlapping, playersdict is a dictionary that is used to hold the records obtained from the scrapping. ''' website = 'https://smite.guru/match/' + str(match) matchweb = requests.get(website) soup = BeautifulSoup(matchweb.text, 'html.parser') section_match = soup.find('section', id="match-stats") winners = section_match.find('div', class_="match-table win") w_matchtable = winners.find_all('div', class_="match-table__row") losers = section_match.find('div', class_="match-table loss") l_matchtable = losers.find_all('div', class_="match-table__row") game_mode = soup.find('h1').text for player_num, player in enumerate(w_matchtable): row_group = player.find_all('div', class_="row__item") playerdict = {'name': player.find('a', class_="row__player__name").text, 'god': player.find_all('img')[0]['alt'], 'Victory': 1, 'level': row_group[0].text, 'kda': row_group[1].text, 'gold': row_group[2].text, 'GMP': row_group[3].text, 'damage': row_group[4].text, 'taken': row_group[5].text, 'mitigated': row_group[6].text, 'build': [i['alt'] for i in player.find_all('img')[1:]], 'game_mode': game_mode, 'match_id': match} playersdict[player_num + match_num] = playerdict for player_num, player in enumerate(l_matchtable): row_group = player.find_all('div', class_="row__item") playerdict = {'name': player.find('a', class_="row__player__name").text, 'god': player.find_all('img')[0]['alt'], 'Victory': 0, 'level': row_group[0].text, 'kda': row_group[1].text, 'gold': row_group[2].text, 'GMP': row_group[3].text, 'damage': row_group[4].text, 'taken': row_group[5].text, 'mitigated': row_group[6].text, 'build': [i['alt'] for i in player.find_all('img')[1:]], 'game_mode': game_mode, 'match_id': match} playersdict[player_num + match_num + 5] = playerdict return playersdict def find_matches(username): '''A function that finds all the match IDs that a given user has played. Taking as input a string username, and outputs a list of the matches. ''' page = 1 new_matches = [] matches = [] while new_matches or page == 1: website = f'https://smite.guru/profile/{username}/matches?page={page}' response = requests.get(website) new_matches = pattern.findall(response.text) matches = matches + new_matches page += 1 print(f"{username} games stop at: {page}") return matches pattern = re.compile(r'href=\"\/match\/(\d*)') matchList = [] failures = [] match_num = 0 accounts = ["5339344-Stagefault", "6434393-PantsuRaider", "440605-JDiablo6G6", "11056361-zdude18"] file_path = r"C:/Users/jason/Desktop/Coding/pythonProgramMemes/smitedata.xlsx" playersdict = {} for account in accounts: matchList += find_matches(account) match_set = set(matchList) for match in match_set: print(f"Processing match: {match}") try: playersdict = process(match, match_num, playersdict) match_num += 10 except: print(f"Failure at match: {match}") failures.append(match) for match in failures: print(f"Processing match: {match}") try: playersdict = process(match, match_num, playersdict) match_num += 10 except: print(f"Failure at match: {match}") smite_df = pd.DataFrame.from_dict(playersdict, orient='index') smite_df.to_excel(file_path, index=False)
0c1d4e46b1121f1171ba91c771ace79018175fe0
[ "Python" ]
1
Python
SealSiil/SmiteScrapper
62bd7711e1d3004fce0084587b589d76d8504da0
87b7c58c0f298f589bd9047353556e4387d4403c
refs/heads/master
<file_sep># run.py example import sys import time from datetime import datetime while True: print(datetime.utcnow().isoformat()) sys.stdout.flush() time.sleep(1)<file_sep># docker-templates Dockerfile templates for all kind of purposes <file_sep>#!/bin/bash echo "******** Python environment information ********" python -V pip3 -V echo "******** Run project ********" cd /opt/${PROJECT_NAME} python run.py<file_sep># Use phusion/baseimage as base image. To make your builds reproducible, make # sure you lock down to a specific version, not to `latest`! # See https://github.com/phusion/baseimage-docker/blob/master/Changelog.md for # a list of version numbers. FROM phusion/baseimage:bionic-1.0.0 LABEL maintainer="<EMAIL>" # Use baseimage-docker's init system. CMD ["/sbin/my_init"] # Container config ENV PROJECT_NAME=project-name ENV PYTHON_MAJOR_VERSION=3 ENV PYTHON_MINOR_VERSION=7 ENV DEPENDENCIES="git libxml2-dev libxslt1-dev" # Make sure python won't buffer stdout # https://docs.python.org/3/using/cmdline.html#envvar-PYTHONUNBUFFERED ENV PYTHONUNBUFFERED=1 # Container build ENV PYTHON_VERSION=${PYTHON_MAJOR_VERSION}.${PYTHON_MINOR_VERSION} RUN echo "******** Adding deadsnakes PPA ********" && \ apt-get update && \ add-apt-repository -k hkp://keyserver.ubuntu.com:80 -y ppa:deadsnakes/ppa && \ echo "******** Installing base dependencies ********" && \ apt-get update && \ install_clean \ python${PYTHON_VERSION} \ python${PYTHON_MAJOR_VERSION}-pip \ ${DEPENDENCIES} && \ echo "******** Setting python${PYTHON_VERSION} as default python executable ********" && \ update-alternatives --install /usr/bin/python python /usr/bin/python${PYTHON_VERSION} 1 && \ update-alternatives --install /usr/bin/python${PYTHON_MAJOR_VERSION} python${PYTHON_MAJOR_VERSION} /usr/bin/python${PYTHON_VERSION} 1 && \ update-alternatives --config python && \ update-alternatives --config python${PYTHON_MAJOR_VERSION} && \ echo "******** Setting up ${PROJECT_NAME} project executable ********" && \ mkdir /etc/service/${PROJECT_NAME} COPY ./src /opt/${PROJECT_NAME} RUN echo "******** Install python dependencies ********" && \ pip3 install --upgrade pip setuptools wheel && \ pip3 install -r /opt/${PROJECT_NAME}/requirements.txt COPY entrypoint.sh /etc/service/${PROJECT_NAME}/run RUN chmod +x /etc/service/${PROJECT_NAME}/run && \ echo "******** Clean up APT ********" && \ apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* # Exposed port EXPOSE 80 <file_sep>#!/bin/bash echo "******** Python environment information ********" python -V pip3 -V echo "******** Installing python dependencies ********" cd /opt/${PROJECT_NAME} pip3 install --upgrade pip setuptools wheel pip3 install -r requirements.txt echo "******** Run project ********" python run.py<file_sep># requirements.txt example pytz>=2020.1
78b0805dc3ccbd2ca5d1ae4da2688e931da0b3c0
[ "Markdown", "Python", "Text", "Dockerfile", "Shell" ]
6
Python
pcamelo/docker-templates
07efb85e6a4e5aba2a255f13125b43b29394a62b
64303ac2f62726db76d8dab5edaf7e3757b88610
refs/heads/master
<file_sep>const int ECHO_PIN_1 = D1; // ECHO PIN WORKING ONLY WITH THIS PINS: D1,D2,D8 const int ECHO_PIN_2 = D2; // ECHO PIN WORKING ONLY WITH THIS PINS: D1,D2,D8 const int TRIG_PIN_1 = D3; const int TRIG_PIN_2 = D4; const int ReleMaxDistance = 60; // in cm const int RelePin = D5; int LastDistance1 = 0; int LastDistance2 = 0; int EnableReleS1 = 0; int EnableReleS2 = 0; int CurrentSetDistance = 0; void setup() { // initialize serial communication: Serial.begin(115200); pinMode(TRIG_PIN_1,OUTPUT); pinMode(ECHO_PIN_1,INPUT); pinMode(TRIG_PIN_2,OUTPUT); pinMode(ECHO_PIN_2,INPUT); pinMode(BUILTIN_LED, OUTPUT); digitalWrite(BUILTIN_LED, LOW); pinMode(RelePin, OUTPUT); digitalWrite(RelePin, HIGH); } long duration1, distanceCm1; long duration2, distanceCm2; long potentiometerValue = 0; const char STRING_cm[] PROGMEM = "cm "; const char STRING_oof[] PROGMEM = "Out of range "; const char STRING_s1[] PROGMEM = "S1: "; const char STRING_s2[] PROGMEM = "S1: "; const char STRING_releState[] PROGMEM = "releState: "; const char STRING_currentSet[] PROGMEM = " current_set:"; void loop() { // read current position of potentiometer and calculate allowed distance potentiometerValue = analogRead(A0); CurrentSetDistance = ReleMaxDistance * potentiometerValue / 530; // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: digitalWrite(TRIG_PIN_1, LOW); delayMicroseconds(2); digitalWrite(TRIG_PIN_1, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN_1, LOW); duration1 = pulseIn(ECHO_PIN_1,HIGH); // convert the time into a distance distanceCm1 = duration1 / 29.1 / 2 ; delay(50); // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: digitalWrite(TRIG_PIN_2, LOW); delayMicroseconds(2); digitalWrite(TRIG_PIN_2, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN_2, LOW); duration2 = pulseIn(ECHO_PIN_2,HIGH); // convert the time into a distance distanceCm2 = duration2 / 29.1 / 2 ; EnableReleS1 = 0; if (distanceCm1 <= 0){ // Out of range distanceCm1 = 1000; } else if (distanceCm1 <= CurrentSetDistance & LastDistance1 < 100) // Aggiungo un check per evitare che becchi misurazioni inesistenti { EnableReleS1 = 1; } EnableReleS2 = 0; if (distanceCm2 <= 0){ // Out of range distanceCm2 = 1000; } else if (distanceCm2 <= CurrentSetDistance & LastDistance2 < 100) // Aggiungo un check per evitare che becchi misurazioni inesistenti { EnableReleS2 = 1; } digitalWrite(RelePin, (EnableReleS1 & EnableReleS2) ? LOW : HIGH); int releState = digitalRead(RelePin); Serial.print(FPSTR(STRING_s1)); if (distanceCm1 == 1000) { Serial.print(FPSTR(STRING_oof)); } else { Serial.print(distanceCm1); Serial.print(FPSTR(STRING_cm)); } Serial.print(FPSTR(STRING_s2)); if (distanceCm2 == 1000) { Serial.print(FPSTR(STRING_oof)); } else { Serial.print(distanceCm2); Serial.print(FPSTR(STRING_cm)); } Serial.print(FPSTR(STRING_releState)); Serial.print(!releState); Serial.print(FPSTR(STRING_currentSet) ); Serial.print(potentiometerValue); Serial.print(" "); Serial.print(CurrentSetDistance); Serial.print(FPSTR(STRING_cm)); Serial.println(); LastDistance1 = distanceCm1; LastDistance2 = distanceCm2; // delay(50); }
868fad4b2378ea2f9ae72665ad62d8184d0f2e12
[ "C++" ]
1
C++
Leen15/NODEMCU_2x_SR04_with_distance_regulator
699821d36df9c462ac08bb72826844739a8ea120
d9f350b6d33b04c14c729a5687f808c6306802b7
refs/heads/master
<file_sep>package transport import ( "github.com/sirupsen/logrus" "github.com/linuxkit/virtsock/pkg/vsock" "github.com/pkg/errors" ) const ( vmaddrCidHost = 2 vmaddrCidAny = 0xffffffff ) // VsockTransport is an implementation of Transport which uses vsock // sockets. type VsockTransport struct{} var _ Transport = &VsockTransport{} // Dial accepts a vsock socket port number as configuration, and // returns an unconnected VsockConnection struct. func (t *VsockTransport) Dial(port uint32) (Connection, error) { logrus.Infof("vsock Dial port (%d)", port) conn, err := vsock.Dial(vmaddrCidHost, port) if err != nil { return nil, errors.Wrap(err, "failed connecting the VsockConnection") } logrus.Infof("vsock Connect port (%d)", port) return conn, nil } <file_sep># Custom Linux kernel for LCOW Here you will find the steps to build a custom kernel for the Linux Hyper-V container on Windows (**LCOW**). To build the full image, please follow the instruction from [how to produce a custom Linux OS image](../docs/customosbuildinstructions.md) ## Patches So far **LCOW** is based on Linux Kernel 4.11, you can download the Linux source code from [kernel.org](https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.11.tar.xz). Once you get the _4.11 kernel_, apply all the patches files located in the [patches-4.11.x](./patches-4.11.x) directory. You should be in the Linux kernel source directory ``` patch -p1 < /path/to/kernel/patches-4.11.x/0001-* patch -p1 < /path/to/kernel/patches-4.11.x/0002-* ``` or in a simple line ``` for p in /path/to/kernel/patches-4.11.x/*.patch; do patch -p1 < $p; done ``` Beside the patches located in the [patches-4.11.x](./patches-4.11.x) directory, you need to apply a set of patches to enable the **Hyper-V vsock transport** feature in the Linux kernel. Please refer to the following section to view the instructions to get them. #### Instructions for getting Hyper-V vsock patch set These patches enables the **Hyper-V vsock transport** feature, this instructions is to get them from a developer repository and assuming you have a _Linux GIT repository_ already ``` git config --global user.name "yourname" git config --global user.email youremailaddress git remote add -f dexuan-github https://github.com/dcui/linux.git git cherry-pick c248b14174e1337c1461f9b13a573ad90a136e1c git cherry-pick 008d8d8bc0c86473a8549a365bee9a479243e412 git cherry-pick 4713066c11b2396eafd2873cbed7bdd72d1571eb git cherry-pick 1df677b35ff010d0def33f5420773015815cf843 git cherry-pick 3476be340d2ff777609fca3e763da0292acbfc45 git cherry-pick b5566b1b6e5cb19b381590587f841f950caabe4d git cherry-pick 6f1aa69011356ff95ed6c57400095e5f2d9eb900 git cherry-pick 2fac74605d2db862caaaf4890239b57095fba832 git cherry-pick 2e307800c6a01cd789afe34eccbcabf384959b3f git cherry-pick 83c8635b893bbc0b5b329c632cea0382d5479763 git cherry-pick a2c08e77b8ceb1f146cdc5136e85e7a4c2c9b7cb git cherry-pick be1ce15dfbdfe3f42c8ed23c5904674d5d90b545 git cherry-pick 8457502df9dd379ddbdfa42a8c9a6421bb3482f1 git cherry-pick 1b91aa6d0e745d9765e3d90058928829f0b0bd40 git cherry-pick 531389d1dc73e2be3ee5dbf2091b6f5e74d9764c git cherry-pick c49aced6328557e6c1f5cf6f58e1fae96fb58fa0 git cherry-pick 651dae7de6c6f066c08845ec7335bfb231d5eabe git cherry-pick e37da6e7a52ea60825ca676e0c59fe5e4ecd89d6 ``` Another way to get the patches is to download them from the following list and apply them in the same order: 1. https://github.com/dcui/linux/commit/c248b14174e1337c1461f9b13a573ad90a136e1c.patch 2. https://github.com/dcui/linux/commit/008d8d8bc0c86473a8549a365bee9a479243e412.patch 3. https://github.com/dcui/linux/commit/4713066c11b2396eafd2873cbed7bdd72d1571eb.patch 4. https://github.com/dcui/linux/commit/1df677b35ff010d0def33f5420773015815cf843.patch 5. https://github.com/dcui/linux/commit/3476be340d2ff777609fca3e763da0292acbfc45.patch 6. https://github.com/dcui/linux/commit/b5566b1b6e5cb19b381590587f841f950caabe4d.patch 7. https://github.com/dcui/linux/commit/6f1aa69011356ff95ed6c57400095e5f2d9eb900.patch 8. https://github.com/dcui/linux/commit/2fac74605d2db862caaaf4890239b57095fba832.patch 9. https://github.com/dcui/linux/commit/2e307800c6a01cd789afe34eccbcabf384959b3f.patch 10. https://github.com/dcui/linux/commit/83c8635b893bbc0b5b329c632cea0382d5479763.patch 11. https://github.com/dcui/linux/commit/a2c08e77b8ceb1f146cdc5136e85e7a4c2c9b7cb.patch 12. https://github.com/dcui/linux/commit/be1ce15dfbdfe3f42c8ed23c5904674d5d90b545.patch 13. https://github.com/dcui/linux/commit/8457502df9dd379ddbdfa42a8c9a6421bb3482f1.patch 14. https://github.com/dcui/linux/commit/1b91aa6d0e745d9765e3d90058928829f0b0bd40.patch 15. https://github.com/dcui/linux/commit/531389d1dc73e2be3ee5dbf2091b6f5e74d9764c.patch 16. https://github.com/dcui/linux/commit/c49aced6328557e6c1f5cf6f58e1fae96fb58fa0.patch 17. https://github.com/dcui/linux/commit/651dae7de6c6f066c08845ec7335bfb231d5eabe.patch 18. https://github.com/dcui/linux/commit/e37da6e7a52ea60825ca676e0c59fe5e4ecd89d6.patch ### Patches structure In the [patches-4.11.x](./patches-4.11.x) directory you will find the following patches: - [9pfs: added vsock transport support](./patches-4.11.x/0001-Added-vsock-transport-support-to-9pfs.patch) - [nvdimm: Lower minimum PMEM size](./patches-4.11.x/0002-NVDIMM-reducded-ND_MIN_NAMESPACE_SIZE-from-4MB-to-4K.patch)
bbf535df3f3d098062ab040e3e7e919aff9125c1
[ "Markdown", "Go" ]
2
Go
lilyfang/opengcs
203a54283e0b0d58c1bc9d8d0f0b4bea8503fe37
004b6b0788432aa5436858b1a3b41f9dae7aeb3e
refs/heads/master
<file_sep># Node.js Tutorial In this part of the tutorial, we focus on package management and using Express to develop a backend server exposing a REST API. ## Package mangement with npm NPM is a very powerful tool that can help you manage project dependencies and in general automate development workflows, much like `ant` or `make` in java and C. In the exercises folder we have a project called *hello*, which uses an external module: `express`. How do we manage this dependency? ### Package.json The file `package.json` contains the metadata regarding your project, including name, version, license, and dependencies. Although you can install dependencies without a `package.json` file, it is the best way to keep track of your local dependencies. How do we start? We execute the command below and follow the instructions prompted. ```shell npm init ``` This generates the `package.json` file containing with a structure similar to this one: ```json { "name": "hello", "version": "1.0.0", "description": "Cool package", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Marcos", "license": "ISC" } ``` ### Installing modules To install an external module, we can use the `npm install` command ```shell npm install --save express ``` The save params indicates npm to add the module to the list of dependencies in the `package.json` file. Indeed, if you check its contents, you'll now see: ```json { "name": "hello", "version": "1.0.0", "description": "Cool package", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Marcos", "license": "ISC", "dependencies": { "express": "^4.16.3" } } ``` ### Installing all dependencies from a project When someone shares the source code of their project (on a github, other source code management system, but even on a memory stick), they will not put their local dependency builds with their source code but give you only the `package.json` dependecies. Let us "uninstall" express for a second, using `npm uninstall express` (if you add --save you'll also remove it from `package.json` but that's not what we want in this case). This removes the module from our project, and put it at the state you'll find any project on github. The way you install the dependencies of the project is then with the following command. ```shell npm install ``` ### Scripts and more You can do so much more with npm, but here we are covering only the basics. A very useful feature you want to look into is `scripts`, which help you automate some tasks. Those interested can check the further reading section. ## Express Web framework for Node.js. *Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.* (Source: https://expressjs.com/). Let's rewrite our node server based on the `http` module using express: ### Hello World! ```javascript var express = require('express'); var app = express(); var port = 3000; // Handling GET requests app.get('/', function(req, res){ res.send('Hello World!'); }); app.listen(port, function() { console.log('Server running on port ', port); }); ``` There are a few interesting concepts that we can highlight in this trivial example: - we can listen to specific http verbs (`app.get`) - we can specify specific routes (`/`) The above help us focus on the services that we want to implement, without worriying about the logic for handling the request (e.g., checking manually that the request method is GET, and that the request url is '/'). ### Serving static files If we had to implement a way to serve static files, one way would be to: - Check the request URL - Look for the file in the local file system - Check the type / format, and set the headers manually This requires quite some work, fortunately express provides some standard way of managing common features like this one. Look at the example `mid-static`. ```javascript var express = require('express'); var app = express(); var port = 3000; app.use(express.static('public')); // Handling GET requests app.get('/hello', function(req, res){ res.send('Hello World!'); }); app.listen(port, function() { console.log('Server running on port ', port); }); ``` What the above does is to mount the built-in `static` middleware, which facilitates the task of servicing static assets. Run the script and then open [http://localhost:3000](http://localhost:3000) in your browser. What happens when you request the following?: - [http://localhost:3000/hello](http://localhost:3000/hello) - [http://localhost:3000/index.html](http://localhost:3000/index.html) - [http://localhost:3000/image1.jpg](http://localhost:3000/image1.jpg) You can decide where path in which the static files will be access, by simply specifying the root as first parameter in `app.use`: ```javascript app.use('/static', express.static('public')); ``` But what are middlewares, and how do they work?. Let's look at the following informative figure by [hannahhoward](https://github.com/hannahhoward): [![](https://camo.githubusercontent.com/af25dcefb2d951a9925adfc0c2c11f9684e19c1e/687474703a2f2f61647269616e6d656a69612e636f6d2f696d616765732f657870726573732d6d6964646c6577617265732e706e67)](https://gist.github.com/hannahhoward/fe639ca2f6e95eaf0ede34a218e948f9 "") ### Handling requests from a browser Serving requests to web forms can be done easily by extending our previous example in the following way (source code in `exercises/forms`): ```javascript var express = require('express'); var app = express(); // Loading utils to inspect the content of js objects var util = require('util'); var port = 3000; app.use('/', express.static('public')); // Handling GET requests app.get('/search', function(req, res){ console.log(util.inspect(req.headers, {showHidden: false, depth: null})) console.log(util.inspect(req.url, {showHidden: false, depth: null})) console.log(util.inspect(req.query, {showHidden: false, depth: null})) res.status(200).send('These are the items found!'); }); app.post('/subscribe', function(req, res){ console.log(util.inspect(req.headers, {showHidden: false, depth: null})) console.log(util.inspect(req.params, {showHidden: false, depth: null})) res.status(201).send('You are now subscribed!'); }); app.listen(port, function() { console.log('Server running on port ', port); }); ``` Run the script of this skeleton. In the code you can see that we are listening to two different routes `subscribe` and `search`. Both rely on different HTTP verbs (post and get), and are built to serve the needs of two different types of requests. Let's open the example clients: - http://localhost:3000/search.html - http://localhost:3000/subscribe.html Play with the above forms, submit some example requests and analyse what arrives to the server. Some points to discuss: 1. What do you think is the reason behind using GET / POST ? 2. Where is the data we are sending? On the first point, there is nice an extensive discussion here (https://www.w3schools.com/tags/ref_httpmethods.asp). Apart from some obvious practical reasons, we'll discuss some more fundamentals one when we get to REST APIs. On the second point, an alternative would be to process the put together the response body by concatenating chunks from the stream (remember when we did this in the first day?) but that is not necessary, because the body-parser middleware provides this funcionality already. **Parsing request body contents** First, we install the library ```shell npm install --save body-parser ``` and then add the following code to our forms app.js ```javascript // Load the module var bodyParser = require('body-parser'); // Mount body-parser middleware, and instruct it to // process form url-encoded data app.use(bodyParser.urlencoded()); ``` After doing this, we should be able to access the form data by directy using `req.body` ```javascript console.log(req.body); ``` Notice that in this case we were parsing form data, but depending on the type of data you want your service to handle, you'll need a different type of parsing. This post provides a nice overview: https://www.quora.com/What-exactly-does-body-parser-do-with-express-js-and-why-do-I-need-it - bodyParser.raw(): Doesn't actually parse the body, but just exposes the buffered up contents from before in a Buffer on req.body. - bodyParser.text(): Reads the buffer as plain text and exposes the resulting string on req.body. - bodyParser.urlencoded(): Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST) and exposes the resulting object (containing the keys and values) on req.body. For comparison; in PHP all of this is automatically done and exposed in $_POST. - bodyParser.json(): Parses the text as JSON and exposes the resulting object on req.body. **What about HTTP status codes?** You can read the following blog post, which summarises nicely what each stands for and when to use them: https://www.digitalocean.com/community/tutorials/how-to-troubleshoot-common-http-error-codes - 1xx: Informational - 2xx: Success - 3xx: Redirection - 4xx: Client Error - 5xx: Server Error ### Exercises 1. Finish implementing the subcription service, using the array of people as "database" 2. Finish implementing the search functionality, looking for subscribers in the people array. ## RESTful APIs *Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. Web Services that conform to the REST architectural style, or RESTful web services, provide interoperability between computer systems on the Internet. **REST-compliant web services allow the requesting systems to access and manipulate textual representations of web resources by using a uniform and predefined set of stateless operations.*** (Source [Wikipedia](https://en.wikipedia.org/wiki/Representational_state_transfer)) * web resource: any resource on the web that can be identied by an URI (universal resource identifier - urls are the most common type of identifiers). * text representation: json, xml, ... * operations: In our case we are talking about HTTP operations (GET, POST, PUT, DELETE) ### Managing a web resource For example, let's say we want to implement a REST API to manage products. ```json { "id" : 1, "name" : "iPhone XL", "description" : "Extra large" } ``` We then map CRUD (or CRUSD) operations to the standard HTTP verbs. | Operation | HTTP Verb | URI | Req body | Resp body | |-----------|--------------|----------------|-------------|------------| | Search | GET | /products | Empty | [Product+] | | Create | POST | /products | Product | Empty | | Read | GET | /products/:id | Empty | Product | | Update | PUT / PATCH | /products/:id | Product* | Product | | Delete | DELETE | /products/:id | Empty | Empty | This works pretty well with simple resources. More complex APIs will require special attention to the relationship between web resources, and ways of traversing the relationships. For example, to get the list of products associated to a user (`/user/:id/products`). Our challenge: Implementing the products API!. There is a stub implementation in `exercises/products-api`, which includes a simple client web app. ### Exercises 1. Finish implementing the Products API backend 2. Implement the web API for managing student registrations as specified here: https://www.studytonight.com/rest-web-service/designing-the-rest-api ### Challenge Create the Zlatan service, replicating the functionality of the Chuck Norris Internet Database, and using Google Spreadsheet as you database. Tip: You can use the link a downloaded CSV file (File -> Download as -> Comma Separated Values) and transform it to json. ## References and further reading - https://nodesource.com/blog/an-absolute-beginners-guide-to-using-npm/ - https://docs.npmjs.com/misc/scripts - https://ourcodeworld.com/articles/read/261/how-to-create-an-http-server-with-express-in-node-js <file_sep>/* * cmd.js * In this example we see how to access commmand * line arguments. */ for (var i = 0; i < process.argv.length; i++) { console.log(i + ' -> ' + (process.argv[i])); }<file_sep>/* * http-get-today.js * In this example we see how to perform http(s) get requests * using the standard http(s) library. */ var https = require('https'); var url = "https://history.muffinlabs.com/date"; https.get(url, function(resp) { var data = ""; // We receive the response data in a stream, so here // we specify what to do with each chunk we receive resp.on("data", function(chunk) { data += chunk; }); // We specify what to do when we finish receiving the // stream of data. resp.on("end", function() { // We receive the content as "text" and print it console.log(data); }); }).on("error", function(err) { console.log("Error: " + err.message); });<file_sep># Node.js Tutorial We start this tutorial by looking at the basics of node.js. ## 1. Basic scripting ### Hello world! Let's open our editor and create a file named *hello.js* ```javascript /* Hello World! program in Node.js */ console.log("Hello World!"); ``` Running the script ```shell $ node hello.js ``` As you can see, we are simply echo-ing the contents in the console. This is the exact equivalent of what we would see in the browser console. Indeed, you can access the same type of interactive console by simply typing *node* in your terminal. For example: ```shell $ node > 1+1 2 > var a = 2 undefined > a 2 ``` ### Command line parameters Often you need to access to command line parameters. For example, ```shell $ node evennumbers.js <from> <to> ``` In node.js you do this by accessing *process*, which is a global variable containing informationan about the current node.js process. For example: ```javascript for (var i = 0; i < process.argv.length; i++) { console.log(i + ' -> ' + (process.argv[i])); } ``` ### Accessing the file system Another useful feature is accessing the file system. Let's start right away from an example: ```javascript // Loading the file system library var fs = require("fs"); // File name from the common line params var fileName = process.argv[2]; // Accessing the content of the file synchnously var data = fs.readFileSync(fileName, "utf8"); console.log(data); console.log("Program ended."); ``` Now try running the code ```shell node files.js path/to/file ``` There are two things to highlight in the above code. #### a. Loading libraries To access the file system we need to load the File System module. This module comes with the standard Node.js installation, so we do not need to install any third-party libraries (We'll get to that later in this tutorial). ```javascript var fs = require("fs"); ``` The require instruction above loads the module "fs" and assigns an instance to the variable fs. Through this instance then we can have access to all the funcions exported by that module. For more on how require works, [check this interesting blog post](http://fredkschott.com/post/2014/06/require-and-the-module-system/). #### b. Blocking / synchronous call As you might have noticed, the following operations are exececuted in sequence, meaning that you see the contents of the file and then the "Program ended." message. ```javascript var data = fs.readFileSync(fileName, "utf8"); console.log(data); console.log("Program ended."); ``` This happens because the *readFileSync* functions is a synchronous implementation, that make the process to wait until the funcion finished its operation to continue. However, this is typically an undesired feature, and as you will see Node.js is built around the concept of non-blocking / asynchonous calls. Why do you think this un undesired feature. Can you think of any instances where you'd need a non-blocking implementation? ### Non-blocking calls Let's try now an alternative implementation of our files script, the *files-async.js*. ```javascript // Loading the file system library var fs = require("fs"); // File name from the common line params var fileName = process.argv[2]; // Accessing the content of the file asynchnously fs.readFile(fileName, "utf8", function(error, data) { console.log(data); }); console.log("Program ended."); ``` What is the difference now?. In this case readFile expects a *callback* function. These are very common in javascript libraries, and is the function that will be called when the method invoked realises its purpose (which can be one or multiple times). In this specific case, we also have an anonymous function, meaning a function that was declared on the spot (declared at runtime) and that unlike typical functions, it does not have a name. Later in the tutorial we'll have a look at *Promises*, which are a nicer looking alternatives to callback functions for asynchnous calls. ## Exercises Let's take 10 minutes to work on the following exercises. We do not expect you to finish both right now, so do as much as you can and leave the rest as homework. 1. **Implement evennumbers.js**, verying that the user provides the right number of parameters (2) and in the right format (numbers). 2. **Create a frequency table** from an input file containing on word per line. Example Input: ```shell $ cat tags.txt Dog Cat Dog Dog ``` Example output: ```shell $ node freq.js tags.txt Tag Frequency Dog 3 Cat 1 ``` ## 2. Interacting with online services As we already know, this is how a typical http server interacts with a client. [![Source: Wikipedia](https://upload.wikimedia.org/wikipedia/commons/b/bc/HTTP_cookie_exchange.svg)](https://commons.wikimedia.org/wiki/File:HTTP_cookie_exchange.svg "") In our case, the client is actually a script and not really a web browser. We can invoke service calls using the standard *http* and *https* modules that come with the standard Node.js installation. Run the script *http-get-today.js*, which requests a service that tells us what happened today in history. ```javascript var https = require('https'); var url = "https://history.muffinlabs.com/date"; https.get(url, function(resp) { var data = ""; // We receive the response data in a stream, so here // we specify what to do with each chunk we receive resp.on("data", function(chunk) { data += chunk; }); // We specify what to do when we finish receiving the // stream of data. resp.on("end", function() { // We receive the content as "text" and print it console.log(data); }); }).on("error", function(err) { console.log("Error: " + err.message); }); ``` The function https.get works by specifying a url and a callback function. It works at very low level, informing us of every single chunk in the response in a stream of data, thus requiring us to put together the response body. ```javascript resp.on("data", function(chunk) { data += chunk; }); ``` Then when we finish receiving the data, we can process process the information. The output of the service is in JSON format. What is JSON? (source: [w3school](https://www.w3schools.com/js/js_json_intro.asp)) - JSON: stands for: **J**ava**S**cript **O**bject **N**otation. - JSON is a syntax for storing and exchanging data. - JSON is text, written with JavaScript object notation. ```json { "date":"September 11", "url":"https://wikipedia.org/wiki/September_11", "data":{ "Events":[ ], "Births":[ ], "Deaths":[ ] } } ``` Since server / client exchange data in "text" format, we need to transform to a Javascript object. This is very straightforward with JSON, since the content is essentially in javascript object notation. Let's modify the "end" callback function: ```javascript resp.on("end", function() { // We receive the content as "text" and print it var obj = JSON.parse(data) console.log(obj.date); }); ``` The *http* and *https* modules are powerful, but certainly not simplest ones out there. There are many ways in which you can perform http / https calls. [This great blog post summarises](https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html) five different ways you can do this. ## Exercises 3. **Random joke**: Implement a script *jokes.js* that returns a random joke from the *The Internet Chuck Norris database*. The documentation specifies: ``` // To get a random joke, invoke: http://api.icndb.com/jokes/random // If you want to change the name of "<NAME>", // specify the firstName and lastName parameters: http://api.icndb.com/jokes/random?firstName=John&lastName=Doe ``` 4. **Wiki pages**: Implement a script that given an input term, search for the (top 5) matching Wiki pages. For example: ```shell $ node wikisearch.js "<NAME>" <NAME> <NAME> Outline of Albert Einstein Albert Einstein's brain Einstein family ``` The documentation of the Wikipedia API suggests the following call: ``` https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=Albert%20Einstein&format=json ``` which has the following output format. You elements to display are in the query.search array. ```json { "batchcomplete":"", "continue":{ "sroffset":10, "continue":"-||" }, "query":{ "searchinfo":{ "totalhits":5166 }, "search":[ { "ns":0, "title":"<NAME>" }, ] } } ``` ## 3. Creating a node server What if we want to create our own server? Creating a server that can handle requests from a client is very simple with node, and we can do it with the same standard http module. Let's try our *server.js* script. ```javascript var http = require('http'); var port = 3000; var requestHandler = function(request, response) { console.log(request.url); response.end('Hello World!'); } var server = http.createServer(requestHandler); server.listen(port); ``` Is it running? Now then let's open [http://localhost:3000](http://localhost:3000) in a browser (`ctrl+c` in the terminal to end the execution). Let's try to inspect the contents of the request.headers. We won't go into detail into this way of creating a node server, as it is a bit low level. In the next class we'll dig into a popular web framework called Express.js. ## Challenge: Can you create a service that tells Zlatan jokes? You can use a format similar to that of the Internet Chuck Norris Database. You can store your jokes in an array, in a file, or simply reuse the Chuck Norris Service. ## References & further reading - https://nodejs.org/en/docs/guides/ - https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/ <file_sep>/* * app.js * Main entry point of the mid-static project * This script shows how to create a server * servig static files using app.use middleware feature */ var express = require('express'); var app = express(); var port = 3000; app.use('/', express.static('public')); // Handling GET requests app.get('/hello', function(req, res){ res.send('Hello World!'); }); app.listen(port, function() { console.log('Server running on port ', port); }); <file_sep>/* * app.js * Main entry point of the forms project * This script shows how to create a server * that can handle request from web forms */ var express = require('express'); var app = express(); // Loading utils to inspect the content of js objects var util = require('util'); var port = 3000; app.use('/', express.static('public')); var people = [{ name : "<NAME>", email : "<EMAIL>"}, { name : "<NAME>", email : "<EMAIL>"}, { name : "<NAME>", email : "<EMAIL>"}]; // Handling GET requests app.get('/search', function(req, res){ console.log(util.inspect(req.headers, {showHidden: false, depth: null})) console.log(util.inspect(req.url, {showHidden: false, depth: null})) console.log(util.inspect(req.query, {showHidden: false, depth: null})) res.status(200).send('These are the items found!'); }); app.post('/subscribe', function(req, res){ console.log(util.inspect(req.headers, {showHidden: false, depth: null})) console.log(util.inspect(req.params, {showHidden: false, depth: null})) res.status(201).send('You are now subscribed!'); }); app.listen(port, function() { console.log('Server running on port ', port); }); <file_sep>/* Implement your solution here */ <file_sep># Corso di Ingegneria del Software 2 - Laboratorio 2018-2019 DISI - Università di Trento Materiale didattico ## Software richiesto: - Browser web (e.g. Chrome) - Tool per testare api REST (e.g. Postman) - Editor di testo (e.g. Brackets, Visual Studio Code, Sublime Text) - Git CLI - Node.js - Heroku CLI ## Servizi online utilizzati: - Heroku - mLab - GitHub - GitHub Pages ## Risorse online JavaScript: - http://www.html.it/guide/guida-nodejs/ - https://developers.google.com/web/fundamentals/getting-started/primers/promises - https://www.html5rocks.com/en/tutorials/cors/ (richieste CORS) Git e Markdown language: - https://git-scm.com/docs - https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet (riassunto sintassi markdown per file readme.md) Node.js: - https://nodejs.org/en/docs/guides/ - https://www.w3schools.com/nodejs/default.asp - http://www.html.it/guide/guida-nodejs/ Npm: - https://docs.npmjs.com/getting-started/what-is-npm Heroku: - https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction Swagger: - https://swagger.io/docs/specification/about/ Jest: - https://facebook.github.io/jest/ Api.ai: - https://api.ai/docs/getting-started/basics # Web 2.0 Il web 2.0 si è sviluppato attorno agli anni 2000 grazie ad un insieme di diverse tecnologie a cui è stato dato il nome di AJAX, abbreviazione di Asynchronous JavaScript + XML. Gmail e Google Maps sono due esempi di questo nuovo approccio alle applicazioni web. ![Web 1.0 e 2.0](http://www.adaptivepath.org/uploads/archive/images/publications/essays/ajax-fig1_small.png?timestamp=1536825780398) Links: - https://en.wikipedia.org/wiki/Ajax_(programming) - http://www.adaptivepath.org/ideas/ajax-new-approach-web-applications/ ## Node.js Node.js è una piattaforma web lato server basata su JavaScript Engine (V8 Engine) di Google Chrome. Node.js usa un modello di elaborazione delle richieste http non bloccante, basato sugli eventi. Con Node.js javascript è diventato il linguaggio del web, non più solo per quanto riguarda il lato client (browser) ma ora anche lato server. Per un introduzione alle principali caratteristiche di Node.js si veda il seguente video: [![](http://img.youtube.com/vi/jOupHNvDIq8/0.jpg)](http://www.youtube.com/watch?v=jOupHNvDIq8 "") ### Installazione Potete installare Node.js seguendo le istruzioni dalla pagina ufficiale ([https://nodejs.org/en/](https://nodejs.org/en/)). <file_sep>/* * files.js * Example of synchronous access to files */ // Loading the file system library var fs = require("fs"); // File name from the common line params var fileName = process.argv[2]; // Accessing the content of the file synchnously var data = fs.readFileSync(fileName, "utf8"); console.log(data); console.log("Program ended.");<file_sep># Exercises Let's take 10 minutes to work on the following exercises. We do not expect you to finish both right now, so do as much as you can and leave the rest as homework. 1. **Implement evennumbers.js**, verying that the user provides the right number of parameters (2) and in the right format (numbers). 2. **Create a frequency table** from an input file containing on word per line. Example Input: ```shell $ cat tags.txt Dog Cat Dog Dog ``` Example output: ```shell $ node freq.js tags.txt Tag Frequency Dog 3 Cat 1 ``` Tips: - Try to split the file contents by the newline character (\n) - Use the readline module ([suggestions from StackOverflow](https://stackoverflow.com/questions/6156501/read-a-file-one-line-at-a-time-in-node-js)) 3. **Random joke**: Implement a script *jokes.js* that returns a random joke from the *The Internet Chuck Norris database*. The documentation specifies: ``` // To get a random joke, invoke: http://api.icndb.com/jokes/random // If you want to change the name of "<NAME>", // specify the firstName and lastName parameters: http://api.icndb.com/jokes/random?firstName=John&lastName=Doe ``` 4. **Wiki pages**: Implement a script that given an input term, search for the (top 5) matching Wiki pages. For example: ```shell $ node wikisearch.js "<NAME>" <NAME> <NAME> Outline of Albert Einstein Albert Einstein's brain Einstein family ``` The documentation of the Wikipedia API suggests the following call: ``` https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=Albert%20Einstein&format=json ``` which has the following output format. You elements to display are in the query.search array. ```json { "batchcomplete":"", "continue":{ "sroffset":10, "continue":"-||" }, "query":{ "searchinfo":{ "totalhits":5166 }, "search":[ { "ns":0, "title":"<NAME>" }, ] } } ``` ## Challenge: Can you create a service that tells Zlatan jokes? You can use a format similar to that of the Internet Chuck Norris Database. You can store your jokes in an array, in a file, or simply reuse the Chuck Norris Service.
390151281f204cfb19d2bd44ce8d75e6194ccd7c
[ "Markdown", "JavaScript" ]
10
Markdown
marcorobol/2018-Trento-SEII-INFORG
106bd04c04dcccd27df3c33e689574030386f92f
62963a4e6c51eef0d8dcec303229a094c91b5428
refs/heads/master
<file_sep># install homebrew formulae ./install-brew.sh # install zsh ./install-zsh.sh # symlink rc files from ./rc/ to ~/ ./install-rc.sh <file_sep># dotfiles My configurations ## Before use The setup script depends on some tools: First, install [Homebrew](http://brew.sh/). Then install tools required: $ brew install git stow Then download the git repository: $ git clone <EMAIL>:chitsaou/dotfiles.git ~/.dotfiles ## How to use Run the scripts inside `~/.dotfiles` ### Install a new machine $ ./setup.sh ### Apply Settings (RC Files) $ ./install-rc.sh ## Side Notes * [GNU Stow](https://www.gnu.org/software/stow/) is a tool to symlink files inside directories in a batch. I got this idea from [shashankmehta's dotfiles](https://github.com/shashankmehta/dotfiles). ## Credits * My ZSH Theme is from [shashankmehta's dotfiles](https://github.com/shashankmehta/dotfiles/blob/master/thesetup/zsh/.oh-my-zsh/custom/themes/gitster.zsh-theme). (MIT License) ## License MIT License <file_sep>cd rc stow -vv * --target ~ <file_sep>brew tap universal-ctags/universal-ctags cat brew.txt | xargs brew install brew install --HEAD universal-ctags brew tap caskroom/versions cat brew-cask.txt | xargs brew cask install brew cleanup brew cask cleanup
cb398f284030ecef1f049507d7c155249aeae414
[ "Markdown", "Shell" ]
4
Shell
optionalg/dotfiles-72
07dbdd6c25b355a3f6e47b59fe0e7f28ca049d74
cc93a3401f2b7c3fb4b2da342258fb862f019024
refs/heads/master
<repo_name>arvinmoj/UploadFiles_MVC_ASP.NET<file_sep>/Models/Image.cs using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.AspNetCore.Http; namespace My_Application.Models { public class Image { public Image() : base() { ImageId = Guid.NewGuid(); } [Key] public Guid ImageId { get; set; } [MaxLength(50)] public string Title { get; set; } [MaxLength(50)] public string ImageName { get; set; } [NotMapped] [Display(Name = "Upload File")] public IFormFile ImageFile { get; set; } } }<file_sep>/Controllers/UploadImageController.cs using System; using System.IO; using System.Linq; using System.Diagnostics; using My_Application.Models; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; using Microsoft.EntityFrameworkCore; using My_Application.Models.Context; namespace My_Application.Controllers { public class UploadImageController : Controller { private readonly DatabaseContext _context; private readonly IWebHostEnvironment _hostEnvironment; public UploadImageController(DatabaseContext context, IWebHostEnvironment hostEnvironment) { _context = context; _hostEnvironment = hostEnvironment; } [HttpGet] public async Task<IActionResult> Index() { return View(await _context.Images.ToListAsync()); } [HttpGet] public async Task<IActionResult> Details(Guid? id) { if (id == null) { return NotFound(); } var image = await _context.Images .FirstOrDefaultAsync(m => m.ImageId == id); if (image == null) { return NotFound(); } return View(image); } [HttpGet] public IActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("ImageId,Title,ImageFile")] Image imageModel) { if (ModelState.IsValid) { //Save image to wwwroot/image string wwwRootPath = _hostEnvironment.WebRootPath; string fileName = Path.GetFileNameWithoutExtension(imageModel.ImageFile.FileName); string extension = Path.GetExtension(imageModel.ImageFile.FileName); imageModel.ImageName = fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension; string path = Path.Combine(wwwRootPath + "/Image/", fileName); using (var fileStream = new FileStream(path, FileMode.Create)) { await imageModel.ImageFile.CopyToAsync(fileStream); } //Insert record _context.Add(imageModel); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(imageModel); } [HttpGet] public async Task<IActionResult> Edit(Guid? id) { if (id == null) { return NotFound(); } var image = await _context.Images.FindAsync(id); if (image == null) { return NotFound(); } return View(image); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(Guid id, [Bind("ImageId,Title,ImageFile")] Image imageModel) { if (id != imageModel.ImageId) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(imageModel); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ImageExists(imageModel.ImageId)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(imageModel); } public async Task<IActionResult> Delete(Guid? id) { if (id == null) { return NotFound(); } var image = await _context.Images .FirstOrDefaultAsync(m => m.ImageId == id); if (image == null) { return NotFound(); } return View(image); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(Guid id) { var imageModel = await _context.Images.FindAsync(id); //delete image from wwwroot/image var imagePath = Path.Combine(_hostEnvironment.WebRootPath, "Image", imageModel.ImageName); if (System.IO.File.Exists(imagePath)) System.IO.File.Delete(imagePath); //delete the record _context.Images.Remove(imageModel); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool ImageExists(Guid id) { return _context.Images.Any(e => e.ImageId == id); } } }<file_sep>/Controllers/UploadFileController.cs using System; using System.IO; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using My_Application.Models.Context; namespace My_Application.Controllers { public class UploadFileController : Controller { private readonly DatabaseContext _context; public UploadFileController(DatabaseContext context) { _context = context; } public IActionResult Index() { return View(); } [HttpPost] public IActionResult Index(IFormFile files) { if (files != null) { if (files.Length > 0) { //Getting FileName var fileName = Path.GetFileName(files.FileName); //Getting file Extension var fileExtension = Path.GetExtension(fileName); // concatenating FileName + FileExtension var newFileName = String.Concat(Convert.ToString(Guid.NewGuid()), fileExtension); var objfiles = new Models.File() { DocumentId = Guid.NewGuid(), Name= newFileName, FileType = fileExtension, CreatedOn = DateTime.Now }; using (var target = new MemoryStream()) { files.CopyTo(target); objfiles.DataFiles = target.ToArray(); } _context.Files.Add(objfiles); _context.SaveChanges(); } } return View(); } } }<file_sep>/Models/Context/DatabaseContext.cs using Microsoft.EntityFrameworkCore; namespace My_Application.Models.Context { public class DatabaseContext : DbContext { public DatabaseContext() : base() { } public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { } public DbSet<File> Files { get; set; } public DbSet<Image> Images { get; set; } } }<file_sep>/Models/File.cs using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace My_Application.Models { [Table("File")] public class File { public File() : base() { DocumentId = Guid .NewGuid(); } [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid DocumentId { get; set; } [MaxLength(100)] public string Name { get; set; } [MaxLength(100)] public string FileType { get; set; } [MaxLength] public byte[] DataFiles { get; set; } [DataType(DataType.DateTime)] public DateTime? CreatedOn { get; set; } } }
7305917e2292ff3cd738a677f702c9a22d5cf7e7
[ "C#" ]
5
C#
arvinmoj/UploadFiles_MVC_ASP.NET
44ee311cc4ecd3ae9317c62334b4488d0dd6e8a7
00d8a1b89e0a1e4de49bdc798df957b514e1df16
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Linq; using Backend.Models; namespace Backend.Repositories { public class UserRepository { public static IList<User> Users = new List<User> { new User { Username = "Lucas", Password = "123" }, new User { Username = "Mariana", Password = "123" }, }; public User GetByUsername(string username) { return Users.Where(x => x.Username.ToLower() == username.ToLower()) .FirstOrDefault(); } } }<file_sep>using System; namespace Backend.Models { public class Boletados { public long Id {get; set;} public string Name {get;set;} public string CPF {get; set;} public string UF {get; set;} public string Bithday {get; set;} } }<file_sep>## Desafio proposto Uma consulta que traga as informações de contas a pagar e contas pagas, sendo que ele precisa do número do processo de pagamento, nome do fornecedor, data de vencimento, data de pagamento, valor líquido e um identificador se é conta a pagar ou paga. Dado a requisição acima, o sistema trabalha com duas tabelas uma para armazenar as contas a pagar e outra para armazenar as contas pagas, o número do processo de pagamento é único entre as tabelas, e o cliente precisa que essa informação venha em uma única consulta. Segue MER abaixo, das tabelas necessárias. ![Captura de tela de 2021-04-14 11-40-25](/assets/Captura%20de%20tela%20de%202021-04-14%2011-40-25.png) ## Solução Essa desafio pode ser simplificado para usar uma única tabela no banco de dados e gerar views diferentes, entretanto essa solução pode esbarrar em alguma regra de negocio. Assim é necessário que se crie um método no sistema para validar a mudança de tabela prevenindo que exista contas duplicadas. Dessa forma existem duas possível soluções uma usando JOIN e outra usando UNION, acredito que nesse caso o ideal seria fazer usar o Join para gerar as view, alterando o nome de campos para identificar de qual tabela vem o dado. ### Usando JOIN SELECT Pessoas.Nome, contasPagas.Numero as CodPago, contasAPagar.Numero as CondNaoPago FROM Pessoas,ContasAPagar, ContasPagas WHERE Pessoas.ID = contasPagas.CodigoFornecedor OR Pessoas.ID = ContasAPagar.CodigoFornecedor OUTER JOIN Pessoas.id on ContasAPagar.CodigoFornecedor AND contasPagas.CodigoFornecedor ### Usando UNION SELECT Numero, CodigoFornecedor, dataPagamento, dataVencimento, valor, Pessoas.Nome FROM( SELECT Numero, CodigoFornecedor, dataPagamento, dataVencimento, valor FROM contasPagas WHERE CodigoFornecedor = Pessoas.id UNION SELECT Numero, CodigoFornecedor,dataPagamento, dataVencimento, valor FROM contasAPagas WHERE CodigoFornecedor = Pessoas.id ) GROUP BY Numero <file_sep>using Microsoft.EntityFrameworkCore; namespace Backend.Models { public class BoletadosContext : DbContext { public BoletadosContext(DbContextOptions<BoletadosContext> options): base(options){ } public DbSet<Boletados> Boletados{get;set;} public DbSet<User> User{get;set;} } }<file_sep>namespace Backend { public static class Settings { //Hash gerada usando MD5 // public static string Secret = "<KEY>"; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Backend.Models; using Backend.Repositories; using Backend.Services; using Microsoft.AspNetCore.Authorization; namespace Backend.Controllers { [Route("api/[controller]")] [ApiController] public class BoletadosController : ControllerBase { private readonly BoletadosContext _context; public BoletadosController(BoletadosContext context) { _context = context; } // GET: api/Boletados/login [HttpPost] [Route("login")] public async Task<ActionResult<dynamic>> Authenticate([FromBody]User model) { var userExists = new UserRepository().GetByUsername(model.Username); if (userExists == null) return BadRequest(new { Message = "Username e/ou senha está(ão) inválido(s)." }); if(userExists.Password != model.Password) return BadRequest(new { Message = "Username e/ou senha está(ão) inválido(s)." }); var token = TokenService.GenerateToken(userExists); return Ok(new { Token = token, Usuario = userExists }); } // GET: api/Boletados/user [HttpGet] [Route("user")] public IActionResult GetUsers() { return Ok("Olá " + User.Identity.Name + " rota aberta a todos os colaboradores."); } // GET: api/Boletados [HttpGet] public async Task<ActionResult<IEnumerable<Boletados>>> GetBoletados() { return await _context.Boletados.ToListAsync(); } // GET: api/Boletados/5 [HttpGet] [Route("{id}")] public async Task<ActionResult<Boletados>> GetBoletados(long id) { var boletados = await _context.Boletados.FindAsync(id); if (boletados == null) { return NotFound(); } return boletados; } // GET: api/Boletados/UF/go [HttpGet] [Route("uf/{uf}")] public async Task<IQueryable<Boletados>> GetBoletadosUF(string uf) { //var boletados = await _context.Boletados.FirstOrDefaultAsync(x=> x.UF==uf); var boletados = _context.Boletados.Where(x=> x.UF.Contains(uf)); if (boletados == null) { return (IQueryable<Boletados>)NotFound(); } return boletados;; } // PUT: api/Boletados/update/5 [HttpPut] [Route("update/{id}")] public async Task<IActionResult> PutBoletados(long id, Boletados boletados) { if (id != boletados.Id) { return BadRequest(); } _context.Entry(boletados).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BoletadosExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Boletados/cadastro [HttpPost] [Route("cadastro")] public async Task<ActionResult<Boletados>> PostBoletados(Boletados boletados) { _context.Boletados.Add(boletados); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(GetBoletados), new { id = boletados.Id }, boletados); } // DELETE: api/Boletados/delete/5 [HttpDelete] [Route("delete/{id}")] public async Task<IActionResult> DeleteBoletados(long id) { var boletados = await _context.Boletados.FindAsync(id); if (boletados == null) { return NotFound(); } _context.Boletados.Remove(boletados); await _context.SaveChangesAsync(); return NoContent(); } private bool BoletadosExists(long id) { return _context.Boletados.Any(e => e.Id == id); } } } <file_sep># Boletados ![](https://img.shields.io/badge/Boletados-60%25-yellowgreen) ## API criada usando o AspNet Core 5. É uma API simples de consulta e cadastro de pessoas que deve ter autenticação e algumas rotas. A ideia principal é poder acessar uma rota que retorne as pessoas com seus atributos em rotas que tenham autenticação. Partindo disso é possível cadastrar cadastrar as contas dessas pessoas e retornar os seus boletos pagos e não pagos. ## Rotas da API | Função | Rota | |:----------------------|:-----------------------------:| | Todos os dados | api/Boletados | | Dados idividuais | api/Boletados/{id} | | buscar por UF | api/Boletados/UF/{uf} | | Cadastro de dados | api/Boletados/cadastro | | Atualizar Cadastro | api/Boletados/update/{id} | | Deletar Cadastro | api/Boletados/delete/{id} | | Autenticar usuarios | api/Boletados/login | | Lista de ususarios | api/Boletados/user | ## Proximos passos 1. Concertar token de autenticação 2. Criar controler de contas 2. Banco de dados 1. Criar 2. Conectar 3. Terminar front-end 4. Rodar testes ## Situação atual Com os problemas no token de autenticação, foi necessário remover o atributo [Authorize] do controller para que as rotas funcionem. Ainda é necessário criar o banco de dados e mudar os tipos dos campos.
68498dbaa6d1ea8312f4a7a3da5c1b363948ca7c
[ "Markdown", "C#" ]
7
C#
gobila/boletados
ea40cdaf5f5e051589b07a265d856103f0fbdea4
ef31a3a4efada55afe04f8c7f4ea86555705e85d
refs/heads/main
<repo_name>8328344106/spring-mvc<file_sep>/Question5/src/test/java/org/websparrow/controller/CreateControllerTest.java package org.websparrow.controller; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.websparrow.config.WebMvcConfig; import org.websparrow.dao.StudentDao; import org.websparrow.model.Employee; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = WebMvcConfig.class) @WebAppConfiguration class CreateControllerTest { MockMvc mockMvc; @Autowired private WebApplicationContext context; @Autowired private StudentDao studentDao; @BeforeEach void setUp() throws Exception { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); studentDao = mock(StudentDao.class); } @Test public void CreateStudentTest() throws Exception { Employee user = new Employee(); user.setEmployeeDepartment("niha"); user.setEmployeeDesignation("niha"); user.setEmployeeName("niha"); user.setEmployeeSalary(12000); when(studentDao.create(user)).thenReturn(1); mockMvc.perform(post("/create") .param("employeeName", "niharika") .param("employeeDepartment", "<EMAIL>") .param("employeeDesignation", "niha@1232") .param("employeeSalary", "12000")) .andExpect(status().isOk()) .andExpect(model().attributeExists("msg")) .andExpect(view().name("create")).andReturn(); } } <file_sep>/spring-mvc-crud/src/main/java/org/websparrow/controller/CreateController.java package org.websparrow.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import org.websparrow.dao.StudentDao; import org.websparrow.model.Employee; @Controller public class CreateController { @Autowired private StudentDao studentDao; @RequestMapping(value = "/create", method = RequestMethod.POST) public ModelAndView createStudent(@RequestParam("employeeName") String name, @RequestParam("employeeDepartment") String department, @RequestParam("employeeDesignation") String designation,@RequestParam("employeeSalary") int salary, ModelAndView mv) { Employee student = new Employee(); student.setEmployeeName(name); student.setEmployeeDepartment(department); student.setEmployeeDesignation(designation); student.setEmployeeSalary(salary); System.out.println(student); int counter = studentDao.create(student); if (counter > 0) { mv.addObject("msg", "Student registration successful."); } else { mv.addObject("msg", "Error- check the console log."); } mv.setViewName("create"); return mv; } } <file_sep>/Question4/src/test/java/org/Question4/controller/ReadControllerTest.java package org.Question4.controller; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import java.util.ArrayList; import java.util.List; import org.Question4.Config.WebMvcConfig; import org.Question4.Dao.UserDao; import org.Question4.Model.User; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = WebMvcConfig.class) @WebAppConfiguration class ReadControllerTest { MockMvc mockMvc; @Autowired private WebApplicationContext context; @Autowired private UserDao studentDao; @BeforeEach void setUp() throws Exception { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); studentDao = mock(UserDao.class); // MockitoAnnotations.initMocks(this); } @Test public void UserLoginTest() throws Exception { User user1 = new User(1,"niha","teja","niha"); User user2 = new User(2,"niha1","teja","niha"); User user3 = new User(3,"niha2","teja","niha"); List<User> studentList = new ArrayList<>(); studentList.add(user1); studentList.add(user2); studentList.add(user3); Mockito.when(studentDao.read()).thenReturn(studentList); mockMvc.perform(get("/read")) .andExpect(status().isOk()) .andExpect(model().attributeExists("listStudent")) .andExpect(view().name("read")).andReturn(); } } <file_sep>/Question5/src/test/java/org/websparrow/dao/StudentDaoTest.java package org.websparrow.dao; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.websparrow.config.WebMvcConfig; import org.websparrow.model.Employee; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = WebMvcConfig.class) @WebAppConfiguration class StudentDaoTest { MockMvc mockMvc; @Autowired private WebApplicationContext context; @Autowired private StudentDao studentDao; @BeforeEach void setUp() throws Exception { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); studentDao = mock(StudentDao.class); } @Test public void CreateMethodTest() throws Exception { Employee user = new Employee(); user.setEmployeeDepartment("niha"); user.setEmployeeDesignation("niha"); user.setEmployeeName("niha"); user.setEmployeeSalary(12000); when(studentDao.create(user)).thenReturn(1); assertEquals(1, studentDao.create(user)); assertNotNull(studentDao.create(user)); } @Test public void ReadMethodTest() throws Exception { Employee user1 = new Employee(1,"niha","teja","niha",12000); Employee user2 = new Employee(2,"niha1","teja","niha",1000); Employee user3 = new Employee(3,"niha2","teja","niha",30000); List<Employee> studentList = new ArrayList<>(); studentList.add(user1); studentList.add(user2); studentList.add(user3); when(studentDao.read()).thenReturn(studentList); assertEquals(studentList, studentDao.read()); assertNotNull(studentDao.read()); } @Test public void FindByIdTest() throws Exception { Employee user1 = new Employee(1,"niha","teja","niha",12000); List<Employee> studentList = new ArrayList<>(); studentList.add(user1); when(studentDao.findStudentById(1)).thenReturn(studentList); assertEquals(studentList,studentDao.findStudentById(1) ); assertNotNull(studentDao.findStudentById(1)); } @Test public void UpdateMethodTest() throws Exception { Employee user = new Employee(); user.setEmployeeId(1); user.setEmployeeDepartment("niha"); user.setEmployeeDesignation("niha"); user.setEmployeeName("niha"); user.setEmployeeSalary(12000); when(studentDao.update(user)).thenReturn(1); assertEquals(1, studentDao.update(user)); assertNotNull(studentDao.update(user)); } @Test public void DeleteMethodTest() throws Exception { when(studentDao.delete(1)).thenReturn(1); assertEquals(1, studentDao.delete(1)); assertNotNull(studentDao.delete(1)); } } <file_sep>/Question5/src/main/java/org/Question5/EmployeeController/UpdateController.java package org.Question5.EmployeeController; import java.io.IOException; import java.util.List; import org.Question5.Dao.EmployeeDao; import org.Question5.Model.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller public class UpdateController { @Autowired private EmployeeDao studentDao; @RequestMapping(value = "/update/{studentId}") public ModelAndView findStudentById(ModelAndView model, @PathVariable("studentId") int studentId) throws IOException { List<Employee> listStudent = studentDao.findStudentById(studentId); model.addObject("listStudent", listStudent); model.setViewName("update"); return model; } @RequestMapping(value = "/update", method = RequestMethod.POST) public ModelAndView updateStudent(@ModelAttribute("employee") Employee emp, ModelAndView mv) { Employee student = new Employee(); student.setEmployeeId(emp.getEmployeeId()); student.setEmployeeName(emp.getEmployeeName()); student.setEmployeeDepartment(emp.getEmployeeDepartment()); student.setEmployeeDesignation(emp.getEmployeeDesignation()); student.setEmployeeSalary(emp.getEmployeeSalary()); int counter = studentDao.update(student); if (counter > 0) { mv.addObject("msg", "Student records updated against student id: " + student.getEmployeeId()); } else { mv.addObject("msg", "Error- check the console log."); } mv.setViewName("update"); return mv; } } <file_sep>/Question4/src/test/java/org/Question4/controller/LoginControllerTest.java package org.Question4.controller; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import org.Question4.Config.WebMvcConfig; import org.Question4.Dao.UserDao; import org.Question4.Model.User; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = WebMvcConfig.class) @WebAppConfiguration class LoginControllerTest { MockMvc mockMvc; @Autowired private WebApplicationContext context; @Autowired private UserDao studentDao; @BeforeEach void setUp() throws Exception { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); studentDao = mock(UserDao.class); } @Test public void UserLoginTest() throws Exception { User user = new User(); user.setPassword("<PASSWORD>"); user.setUsername("niha"); Mockito.when(studentDao.userlogin(user)).thenReturn(true); mockMvc.perform(post("/login") .flashAttr("userlog", user)) .andExpect(status().isOk()) .andExpect(model().attributeExists("msg")) .andExpect(view().name("success")).andReturn(); } } <file_sep>/Question5/src/main/java/org/websparrow/dao/StudentDao.java package org.websparrow.dao; import java.util.List; import org.websparrow.model.Employee; public interface StudentDao { public int create(Employee student); public List<Employee> read(); public List<Employee> findStudentById(int studentId); public int update(Employee student); public int delete(int studentId); }
725f0da22714e270e9429e5593754168befd4eed
[ "Java" ]
7
Java
8328344106/spring-mvc
8928b70b842d457af74473e8a9e2b2fabab214be
620c593e9e027f766bbe546309f9299c19583221
refs/heads/master
<repo_name>comoyi/hall-client-react<file_sep>/src/App.js import React from 'react'; import './index.css'; import Chat from './components/chat/Chat' import Simulator from './components/simulator/Simulator' import Nav from './components/nav/Nav' import { Switch, Route } from 'react-router-dom' import Home from './components/home/Home' import User from './components/user/User' class App extends React.Component { render() { return ( <div> <Nav/> <Switch> <Route path='/home' component={Home}/> <Route path='/chat' component={Chat}/> <Route path='/user' component={User}/> <Route path='/simulator' component={Simulator}/> <Route component={Chat}/> </Switch> </div> ); } } export default App; <file_sep>/src/components/chat/MessageList.js import React from 'react'; import Message from './Message'; class MessageList extends React.Component { constructor(props) { super(props); this.state = { }; } render() { let lists = []; this.props.messages.forEach((message, index) => { lists.push( <div key={index}> <Message message={message} /> </div> ); }); return ( <div> {lists} </div> ); } } export default MessageList; <file_sep>/src/components/simulator/Simulator.js import React from 'react'; import './simulator.css' import MessageList from './MessageList'; class Simulator extends React.Component { constructor(props) { super(props); this.state = { input: "", connect: null, messages: [], }; this.messageListRef = (el) => { this.messageList = el; } this.messageInputRef = (el) => { this.messageInput = el; } this.handleSendMessage = this.handleSendMessage.bind(this); this.handleMessageInputChange = this.handleMessageInputChange.bind(this); } componentDidMount() { if (!window["WebSocket"]) { alert("Your browser does not support websocket"); return; } var server = new WebSocket("ws://127.0.0.1:8080/ws"); server.onmessage = (ev) => {this.onMessage(ev)}; server.onclose = () => {this.onClose()}; this.setState({ connect: server, }); this.messageInput.focus(); } componentWillUnmount() { this.state.connect.close(); } onMessage(ev) { var data = ev.data; var packet = JSON.parse(data); var message = { "type": 1, "content": JSON.stringify(packet.data[0]) }; this.setState(preState => ({ // messages: [...preState.messages, message], messages: preState.messages.concat(message), })); this.messageList.scrollTop = this.messageList.firstChild.clientHeight; } onClose(ev) { console.log("Connection closed"); } handleMessageInputChange(e) { this.setState({ input: e.target.value, }); } handleSendMessage(e) { e.preventDefault(); if (!this.state.connect) { return false; } if (!this.state.input) { return false; } var data = JSON.parse(this.state.input); // TODO 完善消息包数据 var packet = { "packageId":"", "clientId":"", "packageType":"", "token":"", "data":[ // {"cmd":"Ping"}, // 目前一个包一条消息 data ] }; this.state.connect.send(JSON.stringify(packet)); this.setState({ input: "", }); this.messageInput.focus(); } render() { return ( <div> Simulator <div id="message-list" ref={this.messageListRef}> <MessageList messages={this.state.messages} /> </div> <form id="form" onSubmit={this.handleSendMessage}> <input id="message" type="text" ref={this.messageInputRef} value={this.state.input} onChange={this.handleMessageInputChange} /> <input id="btn-send" type="submit" value="Send" /> </form> </div> ); } } export default Simulator;
9036a64c9c492a61da290d15a29b1b095bdbd31c
[ "JavaScript" ]
3
JavaScript
comoyi/hall-client-react
32af6ea350867e11caf3870b5fb7bfddcaca9b7b
b433561806aa3bafd0178482fb77c2fcc8f3084d
refs/heads/main
<file_sep>from PEtools import gen_primes from collections import defaultdict from itertools import islice prime_concat = defaultdict(list) arr = list(islice(gen_primes(), 1, 1000)) for i, prime in enumerate(arr): print(prime) for conc in arr[i+1:]: string1 = str(prime) + str(conc) string2 = str(conc) + str(prime) if string1 in arr or string2 in arr: prime_concat[prime] = prime_concat[prime].append(conc) print(list(prime_concat)) <file_sep># Maximum path sum II # Problem 67 # By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total # from top to bottom is 23. # # 3 # 7 4 # 2 4 6 # 8 5 9 3 # # That is, 3 + 7 + 4 + 9 = 23. # # Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text # file containing a triangle with one-hundred rows. # # NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this # problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take # over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o) data = open('data/p067_triangle.txt', 'r') triangle = data.readlines() tri_dict = {i: x.strip('\n').split() for i, x in enumerate(triangle)} for x in range(len(tri_dict.keys())): tri_dict[x] = [int(stuff) for stuff in tri_dict[x]] size = len(tri_dict.keys()) for x in range(1, size): tri_dict[size - x - 1] = [elem + max(tri_dict[size - x][i:i+2]) for i, elem in enumerate(tri_dict[size - x - 1])] print(tri_dict[0]) <file_sep># Largest palindrome product # Problem 4 # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is # 9009 = 91 × 99. # # Find the largest palindrome made from the product of two 3-digit numbers. candidates, n = [], 3 for a in range(10 ** n - 1, 10 ** (n - 1) - 1, -1): for b in range(a, 10 ** (n - 1) - 1, -1): test = str(a * b) if test == test[::-1]: candidates.append(int(test)) print(max(candidates)) <file_sep># Counting Sundays # Problem 19 # You are given the following information, but you may prefer to do some research for yourself. # # 1 Jan 1900 was a Monday. # Thirty days has September, # April, June and November. # All the rest have thirty-one, # Saving February alone, # Which has twenty-eight, rain or shine. # And on leap years, twenty-nine. # A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. # How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? import datetime date = datetime.date(1901, 1, 1) day = datetime.timedelta(days=1) end = datetime.date(2000, 12, 31) count = 0 while date != end: if date.day == 1 and date.weekday() == 6: count += 1 date = date + day print(count) <file_sep># Power digit sum # Problem 16 # 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. # # What is the sum of the digits of the number 2^1000? digit_array = [int(char) for char in str(2 ** 1111)] print(sum(digit_array)) <file_sep># Lattice paths # Problem 15 # Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, # there are exactly 6 routes to the bottom right corner. # # # How many such routes are there through a 20×20 grid? import math as math array = [] for n in range(1, 21): array.append(int(math.factorial(2*n)/math.factorial(n)**2)) print(array) <file_sep># 1000-digit Fibonacci number # Problem 25 # The Fibonacci sequence is defined by the recurrence relation: # # Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. # Hence the first 12 terms will be: # # F1 = 1 # F2 = 1 # F3 = 2 # F4 = 3 # F5 = 5 # F6 = 8 # F7 = 13 # F8 = 21 # F9 = 34 # F10 = 55 # F11 = 89 # F12 = 144 # The 12th term, F12, is the first term to contain three digits. # # What is the index of the first term in the Fibonacci sequence to contain 1000 digits? import functools @functools.lru_cache(maxsize=4) def fib(n): if n < 2: return n else: return fib(n - 1) + fib(n - 2) fib_dict = {} old_length = 0 for x in range(1, 25000): new_length = len(str(fib(x))) if new_length > old_length: fib_dict[new_length] = x old_length = new_length print(fib_dict[1000]) <file_sep># Largest product in a grid # Problem 11 # In the 20×20 grid below, four numbers along a diagonal line have been marked in red. # # 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 # 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 # 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 # 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 # 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 # 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 # 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 # 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 # 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 # 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 # 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 # 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 # 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 # 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 # 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 # 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 # 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 # 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 # 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 # 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 # # The product of these numbers is 26 × 63 × 78 × 14 = 1788696. # # What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) # in the 20×20 grid? import numpy as np # Load the grid into a matrix data = open("data/p011_data.txt", "r") raw_data = (data.read().rstrip().split('\n')) string_array = [] for i in range(len(raw_data)): string_array.append(np.array(raw_data[i].split(' '))) data_matrix = np.matrix(np.asarray(string_array).astype(int)) vert_matrix = data_matrix.transpose() # calculate array of horizontal and vertical products horizontal_product, vertical_product = [], [] for i in range(0, 20): for j in range(0, 17): prod1, prod2 = 1, 1 for k in range(0, 4): prod1 *= int(data_matrix[i, j + k]) prod2 *= int(vert_matrix[i, j + k]) horizontal_product.append(prod1) vertical_product.append(prod2) # calculate array of diagonal products rdiag_product, ldiag_product = [], [] for i in range(0, 17): for j in range(0, 17): prod3, prod4 = 1, 1 for k in range(0, 4): prod3 *= int(data_matrix[i + k, j + k]) prod4 *= int(data_matrix[i - k + 3, j + k]) ldiag_product.append(prod3) rdiag_product.append(prod4) # calculate results final_array = horizontal_product + vertical_product + ldiag_product + rdiag_product print(max(final_array)) <file_sep># Consecutive prime sum # Problem 50 # The prime 41, can be written as the sum of six consecutive primes: # # 41 = 2 + 3 + 5 + 7 + 11 + 13 # This is the longest sum of consecutive primes that adds to a prime below one-hundred. # # The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. # # Which prime, below one-million, can be written as the sum of the most consecutive primes? import json data = open('primes less than 1 million.json', 'r') primes = json.load(data) conseq, end_result = 21, [] while True: results, offset, conseq_sum = [], 0, 0 while conseq_sum < 1000000: conseq_sum = sum(primes[offset: conseq+offset]) if conseq_sum in primes: results.append((offset, conseq, sum(primes[offset: conseq+offset]))) offset += 1 if len(results) == 1: end_string = str(results[0][2])+', a sum of '+str(conseq)+' primes starting at '+str(primes[results[0][0]]) if sum(primes[:conseq]) > 1000000: print(end_string) break conseq += 2 <file_sep># Quadratic primes # Problem 27 # Euler discovered the remarkable quadratic formula: # # n^2+n+41 # It turns out that the formula will produce 40 primes for the consecutive integer values 0≤n≤39. However, when # n=40,40^2+40+41=40(40+1)+41n=40, is divisible by 41, and certainly # when n=41,41^2+41+41n=41,41^2+41+41 is clearly divisible by 41. # # The incredible formula n^2−79n+1601 was discovered, which produces 80 primes for the consecutive values # 0≤n≤79. The product of the coefficients, −79 and 1601, is −126479. # # Considering quadratics of the form: # # n^2+an+b, where |a|<1000|a|<1000 and |b|≤1000|b|≤1000 # # where |n| is the modulus/absolute value of n # e.g. |11|=11 and |−4|=4 # Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of # primes for consecutive values of n, starting with n=0. def is_prime(num): if num < 2: return False if num == 2: return True for x in range(2, int(num ** 0.5) + 1): if not num % x: return False return True primes = [x for x in range(1001) if is_prime(x)] neg_primes = [-x for x in range(1001) if is_prime(x)] primes = primes + neg_primes consecutive = [] for b in primes: for a in range(-999, 1000): index = 0 while is_prime(index ** 2 + a * index + b): index += 1 if index > 1: consecutive.append((a, b, index + 1)) test = [] for i in consecutive: test.append(i[2]) for j in consecutive: if j[2] == max(test): print(j[0]*j[1]) <file_sep># Names scores # Problem 22 # Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, # begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this # value by its alphabetical position in the list to obtain a name score. # # For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the # 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. # # What is the total of all the name scores in the file? def alpha_value(word): sum_array = [] for char in word: sum_array.append(ord(char) - 64) return sum(sum_array) data = open('data/p022_names.txt', 'r') raw_data = data.read() parse = raw_data.split(',') parse = [word.strip('"') for word in parse] parse = sorted(parse) result = [] for i, elem in enumerate(parse): result.append(alpha_value(elem) * (i + 1)) print(sum(result)) <file_sep># Powerful digit counts # Problem 63 # The 5-digit number, 16807=7^5, is also a fifth power. Similarly, the 9-digit number, 134217728=8^9, is a ninth power. # # How many n-digit positive integers exist which are also an nth power? integer_list = [] for power in range(99): x = 1 while len(str(x ** power)) <= power: if len(str(x ** power)) == power: integer_list.append(x ** power) x += 1 print(len(integer_list))<file_sep>#%% def list_product(nums): total = 1 for num in nums: total *= num return total def gen_primes(): """ Generate an infinite sequence of prime numbers """ d, q = {}, 2 while True: if q not in d: yield q d[q * q] = [q] else: for p in d[q]: d.setdefault(p + q, []).append(p) del d[q] q += 1 def factorize(num, primes=gen_primes()): """ Returns a list of prime factors of num """ prime_factors, max_prime = [], int(num ** 0.5) + 1 for prime in primes: while not num % prime: prime_factors.append(prime) num = num // prime if num == 1: return prime_factors if prime >= max_prime: # print(prime) return [num] + prime_factors def totient(num, primes=gen_primes()): factors = factorize(num, primes) numers, denoms = [x - 1 for x in factors], [x for x in factors] l_numers, l_denoms = list_product(numers), list_product(denoms) # print(num, numers, denoms, l_numers, l_denoms) return num * l_numers // l_denoms #%% print('calculating primes...') primer, max_n, p_list = gen_primes(), 10 ** 7, [] prime = next(primer) while prime < max_n ** 0.5 + 1: p_list.append(prime) prime = next(primer) #%% print('calculating totients...') totients = {} for n in range(2, max_n): totients[n] = totient(n, (n for n in p_list)) if not n % 10 ** 5: print(n // 10 ** 5, ' percent') print('testing permutations...') tester, solutions = {x: p_list[x] for x in range(10)}, {} for n, t in totients.items(): n_digits = [tester[int(char)] for char in str(n)] t_digits = [tester[int(char)] for char in str(t)] if list_product(n_digits) == list_product(t_digits): solutions[n] = t if not n % 10 ** 5: print(n // 10 ** 5, ' percent') print('found ', len(solutions), ' solutions') print('finding minimum...') ratios = {} for k, v in solutions.items(): ratios[k] = k / v print(min(ratios, key=ratios.get)) <file_sep># Integer right triangles # Problem 39 # If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three # solutions for p = 120. # # {20,48,52}, {24,45,51}, {30,40,50} # # For which value of p ≤ 1000, is the number of solutions maximised? triples = [] for k in range(1, 251): for m in range(1, 251): for n in range(m + 1, 251): a = k * (n ** 2 - m ** 2) b = k * (2 * m * n) c = k * (n ** 2 + m ** 2) if a + b + c <= 1000 and a ** 2 + b ** 2 == c ** 2: triples.append((a, b, c)) print(a, b, c) perimeters = [sum(tri) for tri in set(triples)] print(max(perimeters, key=perimeters.count)) <file_sep># Counting summations # Problem 76 # It is possible to write five as a sum in exactly six different ways: # # 4 + 1 # 3 + 2 # 3 + 1 + 1 # 2 + 2 + 1 # 2 + 1 + 1 + 1 # 1 + 1 + 1 + 1 + 1 # # How many different ways can one hundred be written as a sum of at least two positive integers? from functools import lru_cache @lru_cache(maxsize=2**30) def coins(n, denoms): x = len(denoms) if n < 0 or x <= 0: return 0 if n == 0: return 1 removed, reduced = denoms[-1], denoms[:-1] return coins(n, reduced) + coins(n - removed, denoms) for N in range(1, 101): denominations = tuple(range(1, N)) print(N, coins(N, denominations)) <file_sep># Combinatoric selections # Problem 53 # There are exactly ten ways of selecting three from five, 12345: # # 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345 # # In combinatorics, we use the notation, 5C3 = 10. # # In general, # # nCr = # n!/ # r!(n−r)! # ,where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1. # It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066. # # How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater than one-million? def n_comb_r(n, r): from math import factorial return factorial(n) / (factorial(r) * factorial(n - r)) result = 0 for n in range(1,101): for r in range(1, n + 1): if n_comb_r(n, r) > 1000000: result += 1 print(result) <file_sep># Permuted multiples # Problem 52 # It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different # order. # # Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. def find_number(num=1): test_variable = num while test_variable: test_string = str(test_variable) print(test_string) index = 6 while index: if sorted(str(test_variable * index)) == sorted(test_string): index -= 1 if not index: return test_string else: break if len(str(test_variable * 6)) > len(test_string): test_variable = 10 ** len(test_string) else: test_variable += 1 print(find_number()) <file_sep># Double-base palindromes # Problem 36 # The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. # # Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. # # (Please note that the palindromic number, in either base, may not include leading zeros.) def _stringify(num): array = [] string = str(num) for x in range(len(string)): array.append(string[x]) return array def _gen_palidrome_number(): array = [] for x in range(1, 1000000): test = _stringify(x) for y in range(len(test)): if test[y - 1] != test[-y]: break else: array.append(x) return array def _dec_to_bin(x): return int(bin(x)[2:]) palin_nums = _gen_palidrome_number() sum_array = [] for i in palin_nums: binary = _dec_to_bin(i) strung = _stringify(binary) for j in range(len(strung)): if strung[j - 1] != strung[-j]: break else: sum_array.append(i) print(sum(sum_array)) <file_sep>def poker_value(hand): rank_table, hand_value = str.maketrans('TJQKA', 'abcde'), 0 ranks = list(reversed(sorted([elem[0].translate(rank_table) for elem in hand]))) suits, unique = set(elem[1] for elem in hand), set(ranks) unique_rank = len(unique) if unique_rank == 5: # Test for high card / flush / straight if len(suits) == 1: hand_value += 5 if int(ranks[0], 16) - int(ranks[4], 16) == 4: hand_value += 4 r_result = ranks.copy() elif unique_rank == 4: # Test for one pair hand_value = 1 pair_rank = ranks.copy() for elem in unique: pair_rank.remove(elem) r_result = pair_rank * 2 + [elem for elem in ranks if elem not in pair_rank] elif unique_rank == 3: # Test for two pair / three of a kind tok_test = [len(set(ranks[x:x+3])) for x in range(3)] if 1 in tok_test: hand_value = 3 r_result = [ranks[2]] * 3 + [elem for elem in ranks if elem != ranks[2]] else: hand_value = 2 r_result = [ranks[1]] * 2 + [ranks[3]] * 2 + [elem for elem in ranks if elem not in [ranks[1], ranks[3]]] elif unique_rank == 2: # test for full house / four of a kind if ranks[1] == ranks[3]: hand_value = 7 r_result = [ranks[1]] * 4 + [elem for elem in ranks if elem != ranks[4]] else: hand_value = 6 r_result = [ranks[2]] * 3 + [elem for elem in ranks if elem != ranks[2]] return int(''.join([str(hand_value)] + r_result), 16) f, p1_wins = open('data/p054_poker.txt', 'r'), 0 f1 = f.readlines() for hand in f1: cards = hand.split() player1, player2 = cards[:5], cards[5:] value1, value2 = poker_value(player1), poker_value(player2) if value1 > value2: p1_wins += 1 print(p1_wins) f.close() <file_sep># Circular primes # Problem 35 # The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are # themselves prime. # # There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. # # How many circular primes are there below one million? import json data = open("primes less than 1 million.json", 'r') primes = json.loads(data.read()) result = [] for elem in primes: prime_string = str(elem) pcheck = True test = [char for char in prime_string] for rotate in range(len(test)): mover = test.pop(0) test.append(mover) check = int(''.join(test)) if check not in primes: pcheck = False break if pcheck: result.append(elem) print(elem) print(len(result)) <file_sep># Sub-string divisibility # Problem 43 # The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some # order, but it also has a rather interesting sub-string divisibility property. # # Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: # # d2d3d4=406 is divisible by 2 # d3d4d5=063 is divisible by 3 # d4d5d6=635 is divisible by 5 # d5d6d7=357 is divisible by 7 # d6d7d8=572 is divisible by 11 # d7d8d9=728 is divisible by 13 # d8d9d10=289 is divisible by 17 # Find the sum of all 0 to 9 pandigital numbers with this property. from itertools import permutations perm_data = list(permutations('0123456789')) def p043_check(permute): divisors, index = [2, 3, 5, 7, 11, 13, 17], 0 while index < 7: test_string = ''.join(permute[index + 1 : index + 4]) if int(test_string) % divisors[index]: return False index += 1 return True results = [] for perm in perm_data: if p043_check(perm): results.append(perm) pandigits = [] for x in results: pandigits.append(int(''.join(x))) print(sum(pandigits))<file_sep># Convergents of e # Problem 65 # The square root of 2 can be written as an infinite continued fraction. # # The infinite continued fraction can be written, √2 = [1;(2)], (2) indicates that 2 repeats ad infinitum. # In a similar way, √23 = [4;(1,3,1,8)]. # # It turns out that the sequence of partial values of continued fractions for square roots provide the best rational # approximations. Let us consider the convergents for √2. # # Hence the sequence of the first ten convergents for √2 are: # # 1, 3 / 2, 7 / 5, 17 / 12, 41 / 29, 99 / 70, 239 / 169, 577 / 408, 1393 / 985, 3363 / 2378, ... # # What is most surprising is that the important mathematical # constant, e = [2; 1, 2, 1, 1, 4, 1, 1, 6, 1, ..., 1, 2k, 1, ...]. # # The first ten terms in the sequence of convergents for e are: # # 2, 3, 8 / 3, 11 / 4, 19 / 7, 87 / 32, 106 / 39, 193 / 71, 1264 / 465, 1457 / 536, ... # # The sum of digits in the numerator of the 10th convergent is 1 + 4 + 5 + 7 = 17. # # Find the sum of digits in the numerator of the 100th convergent of the continued fraction for e. def fract_e(): yield 2 count = 1 while True: yield 1 yield 2 * count yield 1 count += 1 def calc_cont_fract(seq): d, n = seq.pop(), 1 while len(seq) > 1: n = d * seq.pop() + n d, n = n, d return seq.pop() * d + n, d e_gen = fract_e() e_seq = [next(e_gen) for x in range(100)] fraction = calc_cont_fract(e_seq) res = [int(x) for x in str(fraction[0])] print(sum(res)) <file_sep># Coded triangle numbers # Problem 42 # The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: # # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # # By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we # form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle # number then we shall call the word a triangle word. # # Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common # English words, how many are triangle words? def alpha_value(word): sum_array = [] for char in word: sum_array.append(ord(char) - 64) return sum(sum_array) data = open('data/p042_words.txt', 'r') raw_data = data.read().split(',') parsed = [word.strip('"') for word in raw_data] tri_nums = [(n * (n + 1) / 2) for n in range(1, 20)] result = [] for elem in parsed: if alpha_value(elem) in tri_nums: result.append((elem, alpha_value(elem))) print(len(result)) <file_sep># Digit factorials # Problem 34 # 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. # # Find the sum of all numbers which are equal to the sum of the factorial of their digits. # # Note: as 1! = 1 and 2! = 2 are not sums they are not included. import math as math def digit_factorial(input_array): res = 0 for i in range(len(input_array)): res += math.factorial(int(input_array[i])) return res array = [] percent = 1 for x in range(10, 46448640): stringify = [char for char in str(x)] if x % 464486 == 0: print(percent, "percent complete") percent += 1 if digit_factorial(stringify) == x: array.append(x) print(sum(array)) <file_sep># Highly divisible triangular number # Problem 12 # The sequence of triangle numbers is generated by adding the natural numbers. # So the 7th triangle number would be # 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. # # The first ten terms would be: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # # Let us list the factors of the first seven triangle numbers: # # 1: 1 # 3: 1,3 # 6: 1,2,3,6 # 10: 1,2,5,10 # 15: 1,3,5,15 # 21: 1,3,7,21 # 28: 1,2,4,7,14,28 # # We can see that 28 is the first triangle number to have over five divisors. # # What is the value of the first triangle number to have over five hundred # divisors? from collections import Counter def gen_primes(): """ Generate an infinite sequence of prime numbers """ d, q = {}, 2 while True: if q not in d: yield q d[q * q] = [q] else: for p in d[q]: d.setdefault(p + q, []).append(p) del d[q] q += 1 def factorize(num, primes=gen_primes()): """ Returns a list of prime factors of num """ if not float(num).is_integer() or num < 1: raise Exception("Error: Can only factorize positive integers.") prime_factors = [] for prime in primes: while not num % prime: prime_factors.append(prime) num = num // prime if num == 1: return prime_factors if prime > num ** 0.5: return prime_factors + [num] p_range, primer = 10000, gen_primes() prime, prime_array = next(primer), [] while prime <= p_range: prime_array.append(prime) prime = next(primer) max_div, n = 0, 1 div1 = [] while(max_div < 501 and n < p_range ** 2): div2, divnum = factorize(n + 1, prime_array), 1 div_total = sorted(div1 + div2) for x in Counter(div_total[1:]).values(): divnum *= x + 1 if divnum > max_div: max_div = divnum print(n, ': ', (n * (n + 1)) // 2, ' ', divnum) div1, n = div2, n + 1 print(n - 1, (n * (n - 1)) // 2) <file_sep># Champernowne's constant # Problem 40 # An irrational decimal fraction is created by concatenating the positive integers: # # 0.123456789101112131415161718192021... # # It can be seen that the 12th digit of the fractional part is 1. # # If dn represents the nth digit of the fractional part, find the value of the following expression. # # d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 concat = '' index = 1 while len(concat) < 1000001: concat = concat + str(index) index += 1 strung = concat[0]+concat[9]+concat[99]+concat[999]+concat[9999]+concat[99999]+concat[999999] strung_array = [int(char) for char in strung] res = 1 for x in strung_array: res *= x print(res) <file_sep># Pentagon numbers # Problem 44 # Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are: # # 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... # # It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal. # # Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| # is minimised; what is the value of D? from math import sqrt def is_pentagonal(num): return ((1 + sqrt(1 + 24 * num)) / 6).is_integer() def gen_pent_num(num): return num * (3 * num - 1) // 2 pent_nums = [1] pent_index = 2 D = 0 while not D: new_pent = gen_pent_num(pent_index) for x in pent_nums: sub_value = new_pent - x add_value = new_pent + x if sub_value in pent_nums: if is_pentagonal(add_value): D = sub_value break pent_nums.append(new_pent) pent_index += 1 print(D) <file_sep># Lychrel numbers # Problem 55 # If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. # # Not all numbers produce palindromes so quickly. For example, # # 349 + 943 = 1292, # 1292 + 2921 = 4213 # 4213 + 3124 = 7337 # # That is, 349 took three iterations to arrive at a palindrome. # # Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. # A number that never forms a palindrome through the reverse and add process is called a Lychrel number. # Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume # that a number is Lychrel until proven otherwise. In addition you are given that for every number below # ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all # the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first # number to be shown to require over fifty iterations before producing a # palindrome: 4668731596684224866951378664 (53 iterations, 28-digits). # # Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994. # # How many Lychrel numbers are there below ten-thousand? # # NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers. def isPalindrome(num): strung = [int(char) for char in str(num)] for _ in range(len(strung) // 2): if strung.pop() != strung.pop(0): return False break return True result = [] for x in range(10000): z = x for y in range(50): rev = [char for char in str(z)] test = z + int(''.join(rev[::-1])) if isPalindrome(test): break z = test if y == 49: result.append(x) print(len(result))<file_sep># Summation of primes # Problem 10 # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # # Find the sum of all the primes below two million. data = open("Primes Below 2 Million.txt", "r") sum_array = [int(lines.rstrip('\n')) for lines in data.readlines()] print(sum(sum_array)) <file_sep># Concealed Square # Problem 206 # Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0, # where each “_” is a single digit. def check_condition(num): string_array = [char for char in str(num)] for index in range(len(string_array)): if (index + 1) % 2: if int(string_array[index]) != (((index + 1) // 2) + 1) % 10: return False return True low = 1010101010 high = 1389026623 for x in range(high, low, -1): if not x % 1000000: print(int((x-low)*100/(high-low)), 'percent complete') if check_condition(x ** 2): print(x, 'with square:', x ** 2) break <file_sep># Multiples of 3 and 5 # Problem 1 # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. # The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. print((333*(3+999)+199*(5+995)-66*(15+990))/2) <file_sep># Distinct primes factors # Problem 47 # The first two consecutive numbers to have two distinct prime factors are: # # 14 = 2 × 7 # 15 = 3 × 5 # # The first three consecutive numbers to have three distinct prime factors are: # # 644 = 2² × 7 × 23 # 645 = 3 × 5 × 43 # 646 = 2 × 17 × 19. # # Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers? # # eventually found at 134043 def prime_factor_expansion(num): data = dict() for x in range(2, num // 2 + 1): while not num % x: if x not in data: data[x] = 1 else: data[x] += 1 num = num // x return data order = 4 index = 129000 while True: expansion = [] for x in range(order): factors = [tuple(y) for y in prime_factor_expansion(index + x).items()] expansion += factors if len(expansion) == order ** 2: print('found number at index:', index) break print(index, len(expansion)) index += 1 <file_sep># Reciprocal cycles # Problem 26 # A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators # 2 to 10 are given: # # 1/2 = 0.5 # 1/3 = 0.(3) # 1/4 = 0.25 # 1/5 = 0.2 # 1/6 = 0.1(6) # 1/7 = 0.(142857) # 1/8 = 0.125 # 1/9 = 0.(1) # 1/10 = 0.1 # Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit # recurring cycle. # # Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. def fract(num, rem = 1): return divmod(10 * rem, num) fract_dict = {} for x in range(2, 1000): fract_dict[x] = [fract(x)] while fract_dict[x][-1][1]: test = fract(x, fract_dict[x][-1][1]) if test in fract_dict[x]: fract_dict[x].append("repeat") fract_dict[x].append(test) break elif test[1] == 0: fract_dict[x].append("terminate") fract_dict[x].append(test) else: fract_dict[x].append(test) result = [len(value) for value in fract_dict.values()] print(result.index(max(result)) + 2)<file_sep>from functools import lru_cache from collections import Counter def list_product(nums): total = 1 for num in nums: total *= num return total def gen_primes(): """ Generate an infinite sequence of prime numbers """ d, q = {}, 2 while True: if q not in d: yield q d[q * q] = [q] else: for p in d[q]: d.setdefault(p + q, []).append(p) del d[q] q += 1 def factorize(num): """ Returns a list of prime factors of num """ prime_factors, primes, root_num = [num], gen_primes(), num ** 0.5 for prime in primes: while not num % prime: prime_factors.append(prime) num = num // prime if num == 1: return sorted(prime_factors) # if prime > root_num: # return sorted(prime_factors) def divisor_num(num): """ Returns the number of divisors from a list of prime factors """ res, pfactors = 1, list(factorize(num)) print(pfactors) for x in Counter(pfactors).values(): res *= (x + 1) return res def is_prime(num): """ Test for primality """ if num == 2 or num == 3: return True if num < 2 or num % 2 == 0: return False for x in range(3, int(num ** 0.5) + 1, 2): if not num % x: return False return True @ lru_cache(maxsize=2**18) def collatz_chain(n): """ Returns list with collatz chain starting at n """ if n == 1: return [1] if n % 2: return [n] + collatz_chain(3 * n + 1) else: return [n] + collatz_chain(n // 2) @lru_cache(maxsize=2**18) def collatz_chain_length(n): """ Returns an the integer number of elements in thh collatz chain of n """ if n == 1: return 1 if n % 2: return collatz_chain_length(3 * n + 1) + 1 else: return collatz_chain_length(n // 2) + 1 def is_palindrome(n): """ Determines if n is palindromic (read the same back to front) """ n_str = str(n) n_len = len(n_str) a, b = n_str[:n_len//2], n_str[:-n_len//2] if a == b: return True return False <file_sep># Ordered fractions # Problem 71 # Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced # proper fraction. # # If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: # # 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 # # It can be seen that 2/5 is the fraction immediately to the left of 3/7. # # By listing the set of reduced proper fractions for d ≤ 1,000,000 in ascending order of size, find the numerator # of the fraction immediately to the left of 3/7. from math import gcd reduced_fractions, lower, upper_bound = [(0.0, 0, 0)], 1, 3 / 7 for d in range(2, 1000001): for n in range(lower, d): if n / d >= upper_bound: break if gcd(n, d) == 1: lower = n reduced_fractions.append((n/d, n, d)) print(max(reduced_fractions)[1]) <file_sep>from time import time from PEtools import gen_primes from functools import lru_cache def list_product(nums): total = 1 for num in nums: total *= num return total @lru_cache(maxsize=2**20) def factorize(num): """ Returns a list of prime factors of num """ root_num, factor_list, primes = num ** 0.5, set(), gen_primes() while True: prime = next(primes) while not num % prime: factor_list.add(prime) num = num // prime if num == 1: return factor_list if prime > root_num: factor_list.add(num) return factor_list def totient(num): factors = factorize(num) numers, denoms = [x - 1 for x in factors], [x for x in factors] l_numers, l_denoms = list_product(numers), list_product(denoms) # print(num, numers, denoms, l_numers, l_denoms) return num * l_numers // l_denoms start = time() tot_list = [totient(x) for x in range(2,1000001)] print(sum(tot_list), time() - start)<file_sep># Number spiral diagonals # Problem 28 # Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: # # 21 22 23 24 25 # 20 7 8 9 10 # 19 6 1 2 11 # 18 5 4 3 12 # 17 16 15 14 13 # # It can be verified that the sum of the numbers on the diagonals is 101. # # What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? def draw_number_spiral(num): import numpy as np if not num % 2: return None spiral = np.zeros((num, num)) row = (num // 2) col = row check = 'R' for step in range(1, (num ** 2) + 1): spiral[row][col] = step if check == 'R': if not spiral[row][col + 1]: check = 'D' col += 1 else: row -= 1 elif check == 'L': if not spiral[row][col - 1]: check = 'U' col -= 1 else: row += 1 elif check == 'U': if not spiral[row - 1][col]: check = 'R' row -= 1 else: col -= 1 elif check == 'D': if not spiral[row + 1][col]: check = 'L' row += 1 else: col += 1 return spiral number_spiral = draw_number_spiral(1001) print(int(number_spiral[::-1].transpose().trace() + number_spiral.trace() - 1)) <file_sep># Square root digital expansion # Problem 80 # It is well known that if the square root of a natural number is not an integer, then it is irrational. The decimal # expansion of such square roots is infinite without any repeating pattern at all. # # The square root of two is 1.41421356237309504880..., and the digital sum of the first one hundred decimal # digits is 475. # # For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits # for all the irrational square roots. from decimal import * getcontext().prec = 102 squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] total = 0 for x in range(100): if x not in squares: root = Decimal(x).sqrt() parsed = str(root).replace('.', '')[:100] digits = [int(char) for char in parsed] total += sum(digits) print(total) <file_sep># Pandigital multiples # Problem 38 # Take the number 192 and multiply it by each of 1, 2, and 3: # # 192 × 1 = 192 # 192 × 2 = 384 # 192 × 3 = 576 # By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product # of 192 and (1,2,3) # # The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, # which is the concatenated product of 9 and (1,2,3,4,5). # # What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer # with (1,2, ... , n) where n > 1? from itertools import permutations tulip_array = list(permutations(range(1, 10))) perm_array = [] for tulip in tulip_array: string_array = [str(elem) for elem in tulip] perm_array.append(''.join(string_array)) results = [] for x in range(9, 10000): concat_string, index = '', 1 while len(concat_string) < 9: concat_string += str(x * index) index += 1 if len(concat_string) == 9: if concat_string in perm_array: results.append(int(concat_string)) print(max(results)) <file_sep># Maximum path sum I # Problem 18 # By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total # from top to bottom is 23. # # 3 # 7 4 # 2 4 6 # 8 5 9 3 # # That is, 3 + 7 + 4 + 9 = 23. # # Find the maximum total from top to bottom of the triangle below: # # 75 # 95 64 # 17 47 82 # 18 35 87 10 # 20 04 82 47 65 # 19 01 23 75 03 34 # 88 02 77 73 07 63 67 # 99 65 04 28 06 16 70 92 # 41 41 26 56 83 40 80 70 33 # 41 48 72 33 47 32 37 16 94 29 # 53 71 44 65 25 43 91 52 97 51 14 # 70 11 33 28 77 73 17 78 39 68 17 57 # 91 71 52 38 17 14 91 43 58 50 27 29 48 # 63 66 04 68 89 53 67 30 73 16 69 87 40 31 # 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23) # # NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. # However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot # be solved by brute force, and requires a clever method! ;o data = open('data/p018_data.txt', 'r') triangle = data.readlines() tri_dict = {i: x.strip('\n').split() for i, x in enumerate(triangle)} for x in range(len(tri_dict.keys())): tri_dict[x] = [int(stuff) for stuff in tri_dict[x]] size = len(tri_dict.keys()) for x in range(1, size): tri_dict[size - x - 1] = [elem + max(tri_dict[size - x][i:i+2]) for i, elem in enumerate(tri_dict[size - x - 1])] print(tri_dict[0]) <file_sep># Special Pythagorean triplet # Problem 9 # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # # a**2 + b**2 = c**2 # For example, 32 + 42 = 9 + 16 = 25 = 52. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. import numpy as np root_array=[] for n in range (0,1000): r=np.roots([1,n,-1000]) root_array.append(r) for i in root_array: if root_array[i,0].is_integer() and root_array[i,1].is_integer() root_array # I ended up working this out by hand a=375 b=200 c=425 with abc=31875000 <file_sep># Non-abundant sums # Problem 23 # A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, # the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. # # A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this # sum exceeds n. # # As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum # of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be # written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even # though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than # this limit. # # Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. def proper_divisors(number): divisors = [] for count in range(1, number): if not number % count: divisors.append(count) return divisors def abundant(num): output_array = [] for count in range(1, num): if sum(proper_divisors(count)) > count: output_array.append(count) return output_array a = abundant(28123) elim_list = list(range(1, 28124)) for i, x in enumerate(a): print(i, 'of', len(a), 'complete') for y in a[i:]: test = x + y if test > 28123: break if test in elim_list: elim_list.remove(test) print(sum(elim_list)) <file_sep># Longest Collatz sequence # Problem 14 # The following iterative sequence is defined for the set of positive integers: # # n → n/2 (n is even) # n → 3n + 1 (n is odd) # # Using the rule above and starting with 13, we generate the following sequence: # # 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 # It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. # Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. # # Which starting number, under one million, produces the longest chain? # # NOTE: Once the chain starts the terms are allowed to go above one million. from time import time from functools import lru_cache @ lru_cache(maxsize=2**18) def collatz_chain(n): if n == 1: return [1] if n % 2: return [n] + collatz_chain(3 * n + 1) else: return [n] + collatz_chain(n // 2) @lru_cache(maxsize=2**18) def collatz_chain_length(n): if n == 1: return 1 if n % 2: return collatz_chain_length(3 * n + 1) + 1 else: return collatz_chain_length(n // 2) + 1 n_max = 1000000 n_min = n_max // 2 # This is a brute force approach. We will not need to seach below n / 2, # because all those values map to 2n values with greater collatz numbers. # it is also not neccessay to test even numbers. The biggest collatz sequence # from an odd number is larger then the maximum even number sequence. n_range = range(n_min, n_max, 2) if n_min % 2 else range(n_min + 1, n_max, 2) start = time() chain_lengths = ((collatz_chain_length(n), n) for n in n_range) print(max(chain_lengths)) print(time() - start) <file_sep># Sum square difference # Problem 6 # The sum of the squares of the first ten natural numbers is, # # 1^2 + 2^2 + ... + 10^2 = 385 # The square of the sum of the first ten natural numbers is, # # (1 + 2 + ... + 10)^2 = 552 = 3025 # Hence the difference between the sum of the squares of the first ten natural # numbers and the square of the sum is # 3025 − 385 = 2640. # # Find the difference between the sum of the squares of the first one hundred # natural numbers and the square of the sum. n = 100 squares_of_naturals = [i ** 2 for i in range(1, n + 1)] sum_of_naturals = n * (n + 1) // 2 # arithemetic progression print(sum_of_naturals ** 2 - sum(squares_of_naturals)) <file_sep># Coin partitions # Problem 78 # Let p(n) represent the number of different ways in which n coins can be separated into piles. For example, five # coins can be separated into piles in exactly seven different ways, so p(5)=7. # # OOOOO # OOOO O # OOO OO # OOO O O # OO OO O # OO O O O # O O O O O # Find the least value of n for which p(n) is divisible by one million. from functools import lru_cache def pent_num(num): return num * (3 * num - 1) // 2 @lru_cache(maxsize=2**30) def part(num): if num < 0: return 0 if num == 0: return 1 k_range = int(((24 * num + 1) ** 0.5 + 1) / 6) k_range = [i for i in range(-k_range, k_range + 1) if i] p_sum = 0 for k in k_range: coef = (-1) ** (abs(k) - 1) p_sum += coef * part(num - pent_num(k)) return p_sum N, x = 1000000, 0 while True: if not part(x) % N: print(x) break x += 1 <file_sep># Prime permutations # Problem 49 # The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two # ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another. # # There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but # there is one other 4-digit increasing sequence. # # What 12-digit number do you form by concatenating the three terms in this sequence? def is_prime(num): if num == 2 or num == 3: return True if num < 2 or num % 2 == 0: return False for divisor in range(3, int(num ** 0.5) + 1, 2): if not num % divisor: return False return True primes = [] for x in range(1001, 10000, 2): if is_prime(x): primes.append(x) perm_dict = {} for i, x in enumerate(primes): first_perm = sorted([int(char) for char in str(x)]) for y in primes[i + 1:]: second_perm = sorted([int(char) for char in str(y)]) if second_perm == first_perm: z = 2 * y - x third_perm = sorted([int(char) for char in str(z)]) if z in primes and third_perm == first_perm and x != 1487: print(str(x) + str(y) + str(z)) <file_sep># Diophantine equation # Problem 66 # Consider quadratic Diophantine equations of the form: # # x^2 – Dy^2 = 1 # # For example, when D=13, the minimal solution in x is 6492 – 13×1802 = 1. # # It can be assumed that there are no solutions in positive integers when D is # square. # # By finding minimal solutions in x for D = {2, 3, 5, 6, 7}, we obtain the # following: # # 3^2 – 2×2^2 = 1 # 2^2 – 3×1^2 = 1 # 9^2 – 5×4^2 = 1 # 5^2 – 6×2^2 = 1 # 8^2 – 7×3^2 = 1 # # Hence, by considering minimal solutions in x for D ≤ 7, the largest x is # obtained when D=5. # # Find the value of D ≤ 1000 in minimal solutions of x for which the largest # value of x is obtained. def calc_cont_fract(seq): d, n = seq.pop(), 1 while len(seq) > 1: n = d * seq.pop() + n d, n = n, d return seq.pop() * d + n, d def gen_cont_frac_root(S): m, d, a0 = 0, 1, int(S ** 0.5) yield a0 a = a0 while True: m = d * a - m d = (S - m ** 2) // d a = (a0 + m) // d yield a def gen_best_fraction_expansion_root(D): root = gen_cont_frac_root(D) a0, a1 = next(root), next(root) yield (a0, 1) yield (a0 * a1 + a0, a1) cont_fract_seq = [a0, a1] while True: cont_fract_seq.append(next(root)) yield calc_cont_fract(cont_fract_seq.copy()) D_minimal_x = {} for D in [x for x in range(2, 1000) if not (x ** 0.5).is_integer()]: expansions = gen_best_fraction_expansion_root(D) while True: x, y = next(expansions) if x ** 2 - D * (y ** 2) == 1: D_minimal_x[D] = x break print(max(D_minimal_x, key=D_minimal_x.get)) <file_sep># Truncatable primes # Problem 37 # The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from # left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to # left: 3797, 379, 37, and 3. # # Find the sum of the only eleven primes that are both truncatable from left to right and right to left. # # NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. def is_prime(num): if num == 0 or num == 1: return False for index in range(2, int(num ** 0.5) + 1): if not num % index: return False return True primes = [2, 3, 5, 7] x = 11 result = [] while True: if is_prime(x): primes.append(x) x_string = str(x) left_trunc = [int(x_string[index + 1:]) for index in range(len(x_string) - 1)] right_trunc = [int(x_string[:index + 1]) for index in range(len(x_string) - 1)] trun_list = left_trunc + right_trunc if all(elem in primes for elem in trun_list): result.append(x) if len(result) == 11: print(sum(result)) break x += 2 <file_sep># Singular integer right triangles # Problem 75 # It turns out that 12 cm is the smallest length of wire # that can be bent to form an integer sided right angle # triangle in exactly one way, but there are many more examples. # 12 cm: (3,4,5) # 24 cm: (6,8,10) # 30 cm: (5,12,13) # 36 cm: (9,12,15) # 40 cm: (8,15,17) # 48 cm: (12,16,20) # In contrast, some lengths of wire, like 20 cm, cannot be bent # to form an integer sided right angle triangle, and other lengths # allow more than one solution to be found; for example, using 120 # cm it is possible to form exactly three different integer sided # right angle triangles. # 120 cm: (30,40,50), (20,48,52), (24,45,51) # Given that L is the length of the wire, for how many values # of L ≤ 1,500,000 can exactly one integer sided right angle # triangle be formed? from collections import Counter n, m, trip, per, max_per, triples = 1, 2, [3, 4, 5], 0, 1500000, set() while per <= max_per: while per <= max_per: k = 1 while True: triple = [k * i for i in trip] k += 1 if sum(triple) >= max_per: break else: triples.add(tuple(triple)) m += 1 trip = sorted([m ** 2 - n ** 2, 2 * m * n, m ** 2 + n ** 2]) per = sum(trip) n += 1 m = n + 1 trip = sorted([m ** 2 - n ** 2, 2 * m * n, m ** 2 + n ** 2]) per = sum(trip) c = Counter() c.update([sum(i) for i in triples]) print(len([x for x, y in c.items() if y == 1])) <file_sep># Digit fifth powers # Problem 30 # Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: # # 1634 = 14 + 64 + 34 + 44 # 8208 = 84 + 24 + 04 + 84 # 9474 = 94 + 44 + 74 + 44 # As 1 = 14 is not a sum it is not included. # # The sum of these numbers is 1634 + 8208 + 9474 = 19316. # # Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. def _stringify(num): string_array = [char for char in str(num)] return string_array def _sum_fifth(input_array): total = 0 for i in input_array: total += int(i) ** 5 return total from time import time start = time() fp_digits = [] for x in range(10, 1000000): if sum([int(char) ** 5 for char in str(x)]) == x: fp_digits.append(x) print(sum(fp_digits)) print(time() - start)<file_sep># A Modified Collatz sequence # Problem 277 # A modified Collatz sequence of integers is obtained from a starting value a1 in the following way: # # an+1 = an/3 if an is divisible by 3. We shall denote this as a large downward step, "D". # # an+1 = (4an + 2)/3 if an divided by 3 gives a remainder of 1. We shall denote this as an upward step, "U". # # an+1 = (2an - 1)/3 if an divided by 3 gives a remainder of 2. We shall denote this as a small downward step, "d". # # The sequence terminates when some an = 1. # # Given any integer, we can list out the sequence of steps. # For instance if a1=231, then the sequence {an}={231,77,51,17,11,7,10,14,9,3,1} corresponds to the steps "DdDddUUdDD". # # Of course, there are other sequences that begin with that same sequence "DdDddUUdDD....". # For instance, if a1=1004064, then the sequence is DdDddUUdDDDdUDUUUdDdUUDDDUdDD. # In fact, 1004064 is the smallest possible a1 > 10^6 that begins with the sequence DdDddUUdDD. # # What is the smallest a1 > 10^15 that begins with the sequence "UDDDUdddDDUDDddDdDddDDUDDdUUDd"? def modified_collatz(num): if num % 3 == 0: return num // 3, "D" if num % 3 == 1: return (4 * num + 2) // 3, "U" if num % 3 == 2: return (2 * num - 1) // 3, "d" def find_value(value = 10 ** 15 + 3359500581): test_string = "UDDDUdddDDUDDddDdDddDDUDDdUUDd" while True: index = 0 temp = (value, "") temp_string = "" while True: if index == len(test_string): return value temp = modified_collatz(temp[0]) temp_string += temp[1] if temp[1] != test_string[index]: break index += 1 value += 3486784401 print(find_value()) <file_sep># All square roots are periodic when written as continued fractions and can be written in the form: # # √N = a0 + [1 / a1 + [1 / a2 + [1 / a3 + ... # For example, let us consider √23: # # √23 = 4+√23—4 = 4 + 1/[1/(√23-4)] = 4+1/[1+(√23-3)/7] # # If we continue we would get the following expansion: # # √23 = 4+[1+[1/[3+1/[1+(8+... # # The process can be summarised as follows: # # a0 = 4 # a1 = 1 # a2 = 3 # a3 = 1 # a4 = 8 # a5 = 1 # a6 = 3 # a7 = 1 # # It can be seen that the sequence is repeating. For conciseness, # we use the notation √23 = [4;(1,3,1,8)], to indicate that the # block (1,3,1,8) repeats indefinitely. # # The first ten continued fraction representations of (irrational) # square roots are: # # √2=[1;(2)], period=1 # √3=[1;(1,2)], period=2 # √5=[2;(4)], period=1 # √6=[2;(2,4)], period=2 # √7=[2;(1,1,1,4)], period=4 # √8=[2;(1,4)], period=2 # √10=[3;(6)], period=1 # √11=[3;(3,6)], period=2 # √12= [3;(2,6)], period=2 # √13=[3;(1,1,1,1,6)], period=5 # # Exactly four continued fractions, for N ≤ 13, have an odd period. # # How many continued fractions for N ≤ 10000 have an odd period? # %% def cont_frac_root_repeating(S): m, d, a0, repeat = 0, 1, int(S ** 0.5), [] a = a0 while a != 2 * a0: m = d * a - m d = (S - m ** 2) // d a = (a0 + m) // d repeat.append(a) return repeat # %% N, count = 10000, 0 for x in [y for y in range(2, N + 1) if not (y ** 0.5).is_integer()]: if len(cont_frac_root_repeating(x)) % 2: count += 1 print(count) <file_sep># Triangular, pentagonal, and hexagonal # Problem 45 # Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: # # Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ... # Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ... # Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ... # It can be verified that T285 = P165 = H143 = 40755. # # Find the next triangle number that is also pentagonal and hexagonal. def triangular(num): return num * (num + 1) // 2 def pentagonal(num): return num * (3 * num - 1) // 2 def hexagonal(num): return num * (2 * num - 1) tri_list = [triangular(x) for x in range(1, 400100)] pen_list = [pentagonal(x) for x in range(1, 232100)] hex_list = [hexagonal(x) for x in range(1, 200100)] answer = set(tri_list).intersection(set(pen_list)).intersection(set(hex_list)) print(answer) <file_sep># Spiral primes # Problem 58 # Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed. # # 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 # 42 21 22 23 24 25 26 # 43 44 45 46 47 48 49 # # It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is # that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%. # # If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If # this process is continued, what is the side length of the square spiral for which the ratio of primes along both # diagonals first falls below 10%? def prime_list(n): """ Returns a list of primes < n """ sieve = [True] * n for i in range(3, int(n ** 0.5) + 1, 2): if sieve[i]: sieve[i * i:: 2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1) return [2] + [i for i in range(3, n, 2) if sieve[i]] def is_prime(num): for prime in prime_divisors: if prime > int(num ** 0.5): break if not num % prime: return False return True def gen_ullam_corners(sidelength=3): k, j, value = 1, 1, 0 while True: batch = set() value = 4 * k ** 2 + 1 while value < sidelength ** 2: batch.add(value) k += 1 value = 4 * k ** 2 + 1 value = j ** 2 + j + 1 while value < sidelength ** 2: batch.add(value) j += 1 value = j ** 2 + j + 1 yield batch sidelength += 2 c_gen = gen_ullam_corners() prime_divisors = prime_list(32768) side, p_count = 3, 0 while True: c_list = set(next(c_gen)) for elem in c_list: if is_prime(elem): p_count += 1 percentage = p_count / (2 * side - 1) if percentage < 0.1: print(side) break side += 2 <file_sep># Cyclical figurate numbers # Problem 61 # Triangle, square, pentagonal, hexagonal, heptagonal, # and octagonal numbers are all figurate (polygonal) # numbers and are generated by the following formulae: # Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ... # Square P4,n=n2 1, 4, 9, 16, 25, ... # Pentagonal P5,n=n(3n−1)/2 1, 5, 12, 22, 35, ... # Hexagonal P6,n=n(2n−1) 1, 6, 15, 28, 45, ... # Heptagonal P7,n=n(5n−3)/2 1, 7, 18, 34, 55, ... # Octagonal P8,n=n(3n−2) 1, 8, 21, 40, 65, ... # The ordered set of three 4-digit numbers: # 8128, 2882, 8281, has three interesting properties. # The set is cyclic, in that the last two digits of each # number is the first two digits of the next number # (including the last number with the first). # Each polygonal type: triangle (P3,127=8128), # square (P4,91=8281), and pentagonal (P5,44=2882), # is represented by a different number in the set. # This is the only set of 4-digit numbers with this property. # Find the sum of the only ordered set of six cyclic 4-digit numbers # for which each polygonal type: triangle, square, pentagonal, # hexagonal, heptagonal, and octagonal, is represented by a # different number in the set. def tri_num(n): return (n * (n + 1) // 2) def squ_num(n): return n ** 2 def pen_num(n): return (n * (3 * n - 1) // 2) def hex_num(n): return n * (2 * n - 1) def hep_num(n): return (n * (5 * n - 3)) // 2 def oct_num(n): return n * (3 * n - 2) funclist = [tri_num, squ_num, pen_num, hex_num, hep_num, oct_num] values = {x.__name__: [] for x in funclist} for func in funclist: val, n = 0, 1 print(func.__name__) while val < 10000: val = func(n) if val > 999: values[func.__name__] = values[func.__name__] + [val] n += 1 # this produces the lists just fine<file_sep># Pandigital prime # Problem 41 # We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. # For example, 2143 is a 4-digit pandigital and is also prime. # # What is the largest n-digit pandigital prime that exists? from itertools import * def is_prime(num): if num == 0 or num == 1: return False for x in range(2, int(num ** 0.5) + 1): if num % x == 0: return False else: return True perm_array = [] for i in permutations("1234567", 7): string = "" for j in range(len(i)): string = string + i[j] perm_array.append(int(string)) prime_array = [] for i in perm_array: if is_prime(i): prime_array.append(i) print(max(prime_array)) <file_sep># Cubic permutations # Problem 62 # The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). # In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube. # # Find the smallest cube for which exactly five permutations of its digits are cube. cubes = {} for x in range(10000): digits = [int(char) for char in str(x ** 3)] cubes[x] = sorted(digits) for x in cubes: count = 0 for y in cubes.values(): if cubes[x] == y: count += 1 if count == 5: print(x ** 3) break <file_sep># Sieve of Eratosthenes # Code by <NAME>, UC Irvine, 28 Feb 2002 # http://code.activestate.com/recipes/117119/ from collections import Counter def gen_primes(): """ Generate an infinite sequence of prime numbers. """ # Maps composites to primes witnessing their compositeness. # This is memory efficient, as the sieve is not "run forward" # indefinitely, but only as long as required by the current # number being tested. # D = {} # The running integer that's checked for primeness q = 2 while True: if q not in D: # q is a new prime. # Yield it and mark its first multiple that isn't # already marked in previous iterations # yield q D[q * q] = [q] else: # q is composite. D[q] is the list of primes that # divide it. Since we've reached q, we no longer # need it in the map, but we'll mark the next # multiples of its witnesses to prepare for larger # numbers # for p in D[q]: D.setdefault(p + q, []).append(p) del D[q] q += 1 # def primes_by_digits(n): # primer, primes = gen_primes(), [] # while True: # test_prime = str(next(primer)) # if len(test_prime) == n: # primes.append(test_prime) # elif len(test_prime) > n: # break # return primes # def prime_search(prime_list, repeat): # short = [] # for prime in prime_list: # digits = [char for char in prime] # if len(set(digits)) < len(digits) - repeat: # short.append(prime) # return short # # %% # search_primes = primes_by_digits(6) # print(len(search_primes)) # # %% # short = prime_search(search_primes, 2) # len(short) # print(short) # shorter = [tuple(set(x)) for x in [char for char in [word for word in short]]] # print(shorter) # pattern = Counter(shorter) # print(pattern) from collections import Counter from itertools import permutations primer, max_prime = gen_primes(), 10 ** 5 prime, candidates = next(primer), [] while prime < max_prime: candidates.append(prime) prime = next(primer) candidates = [num for num in candidates if len(str(num)) == 5] print(len(candidates)) perms = list(permutations([1,1,1,0,0])) num_list = [] for n in range(1000): nums = [int(char) for char in str(n)] for per in perms: for x in range(10): new_num = [a if per[i] else x for a, i in nums, range(5)] print(new_num) <file_sep>from collections import deque def gen_primes(): """ Generate an infinite sequence of prime numbers """ d, q = {}, 2 while True: if q not in d: yield q d[q * q] = [q] else: for p in d[q]: d.setdefault(p + q, []).append(p) del d[q] q += 1 def pfactor(num, p): """ Returns a dict of prime factors of num """ """ dict keys are the prime factors """ """ values contain the number of factors (exponent) """ prime_factors = {} for prime in p: while not num % prime: prime_factors[prime] = prime_factors.get(prime, 0) + 1 num = num // prime if num == 1: return prime_factors if prime > num ** 0.5: prime_factors[num] = 1 return prime_factors def divisors(num, p): """ takes a dict of prime factors from pfactor() """ """ returns list of divisors """ num_dict = pfactor(num, p) def inner_divisors(num_dict, num_list={1}): if not num_dict: return num_list prime = min(num_dict.keys()) exp = num_dict[prime] del num_dict[prime] back_list = inner_divisors(num_dict, num_list) work_list = [prime ** (i + 1) for i in range(exp)] for div in work_list: num_list = num_list.union(x * div for x in back_list) num_list = num_list.union(work_list).union(back_list) return num_list return sorted(list(inner_divisors(num_dict))[1: -1]) from time import time start = time() max_n, primer, res = 10 ** 8, gen_primes(), 0 prime = next(primer) pri_list = {prime} while True: prime = next(primer) pri_list.add(prime) n = prime - 1 if n > max_n: break div = deque(divisors(n, pri_list)) while len(div) not in [0, 1]: if div.pop() + div.popleft() not in pri_list: break if not div: res += n print(res + 3, time() - start) <file_sep>from functools import lru_cache @lru_cache(maxsize=2 ** 8) def is_prime(num): return not (num < 2 or any(num % i == 0 for i in range(2, int(num ** 0.5) + 1))) def gen_prime(num): step, count = 3, 0 yield 2 while True: if is_prime(step): yield step count += 1 if count >= num: break step += 2 primes = list(gen_prime(16)) n_local_minima, totient_local_minima, product, a = [], [], 1, 1 for prime in primes: product *= prime a *= prime - 1 n_local_minima.append(product) totient_local_minima.append(a) totient_dict = dict(zip(n_local_minima, totient_local_minima)) N = 1000000 for x in sorted(list(totient_dict.keys()))[::-1]: if x <= N: print(x) break<file_sep># Square root convergents # Problem 57 # It is possible to show that the square root of two can be expressed as an infinite continued fraction. # # √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213... # # By expanding this for the first four iterations, we get: # # 1 + 1/2 = 3/2 = 1.5 # 1 + 1/(2 + 1/2) = 7/5 = 1.4 # 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666... # 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379... # # The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the # first example where the number of digits in the numerator exceeds the number of digits in the denominator. # # In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator? num_gt_denom, expansions = [], [] prev_denom, denominator, numerator = 1, 2, 3 while len(expansions) <= 999: expansions.append(numerator / denominator) if len(str(numerator)) > len(str(denominator)): num_gt_denom.append((numerator, denominator)) denominator, prev_denom = 2 * denominator + prev_denom, denominator numerator = denominator + prev_denom print(len(num_gt_denom)) <file_sep># 10001st prime # Problem 7 # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # # What is the 10 001st prime number? def gen_primes(): """ Generate an infinite sequence of prime numbers """ d, q = {}, 2 while True: if q not in d: yield q d[q * q] = [q] else: for p in d[q]: d.setdefault(p + q, []).append(p) del d[q] q += 1 primer = gen_primes() for _ in range(10000): next(primer) print(next(primer)) <file_sep># Prime summations # Problem 77 # It is possible to write ten as the sum of primes in exactly five different ways: # # 7 + 3 # 5 + 5 # 5 + 3 + 2 # 3 + 3 + 2 + 2 # 2 + 2 + 2 + 2 + 2 # # What is the first value which can be written as the sum of primes in over five thousand different ways? from functools import lru_cache @lru_cache(maxsize=2**30) def coins(n, denoms): x = len(denoms) if n < 0 or x <= 0: return 0 if n == 0: return 1 removed, reduced = denoms[-1], denoms[:-1] return coins(n, reduced) + coins(n - removed, denoms) @lru_cache(maxsize=2 ** 8) def is_prime(num): return not (num < 2 or any(num % i == 0 for i in range(2, int(num ** 0.5) + 1))) def gen_prime(num=2**32): step, count = 3, 0 yield 2 while True: if is_prime(step): yield step count += 1 if count >= num: break step += 2 N = 5000 primes, number, maxpartitions = gen_prime(), 1, 1 prime_denoms = next(primes), while True: if number > max(prime_denoms): prime_denoms = (*prime_denoms, next(primes)) partitions = coins(number, prime_denoms) if partitions >= N: print(number) break number += 1 <file_sep># Digit factorial chains # Problem 74 # The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145: # # 1! + 4! + 5! = 1 + 24 + 120 = 145 # # Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out # that there are only three such loops that exist: # # 169 → 363601 → 1454 → 169 # 871 → 45361 → 871 # 872 → 45362 → 872 # # It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example, # # 69 → 363600 → 1454 → 169 → 363601 (→ 1454) # 78 → 45360 → 871 → 45361 (→ 871) # 540 → 145 (→ 145) # # Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting # number below one million is sixty terms. # # How many chains, with a starting number below one million, contain exactly sixty non-repeating terms? from math import * def digit_factorial(num): digit_string = [factorial(int(char)) for char in str(num)] return sum(digit_string) result = [] for x in range(1000000): if not x % 10000: print(x // 10000,'percent complete') index = 0 chain_test = x while chain_test not in [digit_factorial(chain_test), 169, 363601, 1454, 871, 872, 45361, 45362]: index += 1 chain_test = digit_factorial(chain_test) if index > 56: if chain_test == 169 or index == 58: result.append(x) print(result) print(len(result)) <file_sep># Self powers # Problem 48 # The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. # # Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. series_sum = 0 for i in range(1, 1001): series_sum += i ** i print(series_sum) <file_sep># Even Fibonacci numbers # Problem 2 # Each new term in the Fibonacci sequence is generated by adding the previous two terms. # By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million, find the sum of the even-valued terms. fibolist = [1, 2] max_value = 4 * 10 ** 6 current = sum(fibolist[-2:]) while current < max_value: fibolist.append(current) current = sum(fibolist[-2:]) print(sum([x for x in fibolist if not x % 2])) <file_sep>from itertools import product from collections import Counter pete_rolls = [sum(x) for x in product((1, 2, 3, 4), repeat=9)] colin_rolls = [sum(x) for x in product((1, 2, 3, 4, 5, 6), repeat=6)] pete_roll_dict = Counter(pete_rolls) colin_roll_dict = Counter(colin_rolls) pete_roll_range = sorted(pete_roll_dict.keys()) print(pete_roll_range)<file_sep># Amicable numbers # Problem 21 # Let d(n) be defined as the sum of proper divisors of n (numbers less than n # which divide evenly into n). # If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and # each of a and b are called amicable # numbers. # # For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, # 55 and 110; therefore d(220) = 284. # The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. # # Evaluate the sum of all the amicable numbers under 10000. def gen_primes(): """ Generate an infinite sequence of prime numbers """ d, q = {}, 2 while True: if q not in d: yield q d[q * q] = [q] else: for p in d[q]: d.setdefault(p + q, []).append(p) del d[q] q += 1 def pfactor(num): """ Returns a dict of prime factors of num """ """ dict keys are the prime factors """ """ values contain the number of factors (exponent) """ prime_factors, primes = {}, gen_primes() for prime in primes: while not num % prime: prime_factors[prime] = prime_factors.get(prime, 0) + 1 num = num // prime if num == 1: return prime_factors if prime > num ** 0.5: prime_factors[num] = 1 return prime_factors def divisors(num): """ takes a dict of prime factors from pfactor() """ """ returns list of divisors """ num_dict = pfactor(num) def inner_divisors(num_dict, num_list={1}): if not num_dict: return num_list prime = min(num_dict.keys()) exp = num_dict[prime] del num_dict[prime] back_list = inner_divisors(num_dict, num_list) work_list = [prime ** (i + 1) for i in range(exp)] for div in work_list: num_list = num_list.union(x * div for x in back_list) num_list = num_list.union(work_list).union(back_list) return num_list return sorted(list(inner_divisors(num_dict))) max_N = 10 ** 5 s = {x: sum(divisors(x)[:-1]) for x in range(2, max_N)} am = {x: y for x, y in s.items() if 1 < x < y < max_N and s[y] == x} print(sum(list(am.keys()) + list(am.values()))) print(s) <file_sep># Passcode derivation # Problem 79 # A common security method used for online banking is to ask the user for three random characters from a passcode. # For example, if the passcode was 53<PASSWORD>, they may ask for the 2nd, 3rd, and 5th characters; the expected reply # would be: 317. # # The text file, keylog.txt, contains fifty successful login attempts. # # Given that the three characters are always asked for in order, analyse the file so as to determine the shortest # possible secret passcode of unknown length. data = open('data/p079_keylog.txt', 'r') keylogs = [] for line in data.readlines(): keylogs.append([int(char) for char in line.strip('\n')]) result = [] while len(keylogs) > 0: head_nums, tail_nums = set(), set() for log in keylogs.copy(): if len(log) > 0: head_nums.add(log[0]) if len(log) > 1: tail_nums.add(log[1]) if len(log) > 2: tail_nums.add(log[2]) first_numeral = head_nums.difference(tail_nums).pop() for i, log in enumerate(keylogs.copy()): if len(log) > 0 and log[0] == first_numeral: del keylogs[i][0] result.append(first_numeral) keylogs = [x for x in keylogs if x != []] print(''.join([str(x) for x in result])) <file_sep># Digit cancelling fractions # Problem 33 # The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may # incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. # # We shall consider fractions like, 30/50 = 3/5, to be trivial examples. # # There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two # digits in the numerator and denominator. # # If the product of these four fractions is given in its lowest common terms, find the value of the denominator. import fractions stor = dict() for x in range(10, 100): for y in range(x + 1, 100): stor[(x, y)] = 1 i_stor = stor.copy() for fract in i_stor: a = set([char for char in str(fract[0])]) b = set([char for char in str(fract[1])]) if a == b: del stor[fract] else: cancel = int(*a.intersection(b)) if cancel: stor[fract] = cancel else: del stor[fract] for key, value in stor.items(): a = [int(char) for char in str(key[0])] b = [int(char) for char in str(key[1])] a.remove(value) b.remove(value) stor[key] = (*a, *b) i_stor = stor.copy() for key, value in i_stor.items(): if value[1] == 0: if __name__ == '__main__': del stor[key] result = [] for key, value in stor.items(): if key[0] / key[1] == value[0] / value[1]: result.append((key, value, key[0] / key[1])) a = 1 b = 1 for fract in result: a *= fract[0][0] b *= fract[0][1] print(b // fractions.gcd(a, b))<file_sep>def list_product(nums): total = 1 for num in nums: total *= num return total def gen_primes(): """ Generate an infinite sequence of prime numbers """ d, q = {}, 2 while True: if q not in d: yield q d[q * q] = [q] else: for p in d[q]: d.setdefault(p + q, []).append(p) del d[q] q += 1 def factorize(num, primes): """ Returns a list of prime factors of num """ prime_factors, max_prime = set(), int(num ** 0.5) + 1 for prime in primes: while not num % prime: prime_factors.add(prime) num = num // prime if num == 1: return prime_factors if prime >= max_prime: # print(prime) return list(prime_factors) def totient(num, primes): factors = factorize(num, primes) numers, denoms = [x - 1 for x in factors], [x for x in factors] l_numers, l_denoms = list_product(numers), list_product(denoms) return (num * l_numers) // l_denoms prime, d, R = gen_primes(), 2, 1 p_list = [next(prime)] while R >= 14599 / 94744: while d > p_list[-1]: p_list.append(next(prime)) if d not in p_list: R = totient(d, p_list) / (d - 1) if not d % 100000: print(d) d += 1 print('Found: d=', d, ' with R(d) value: ', R) <file_sep># XOR decryption # Problem 59 # Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code # for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107. # # A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given # value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the # cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65. # # For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random # bytes. The user would keep the encrypted message and the encryption key in different locations, and without both # "halves", it is impossible to decrypt the message. # # Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. # If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. # The balance for this method is using a sufficiently long password key for security, but short enough to be memorable. # # Your task has been made easy, as the encryption key consists of three lower case characters. Using cipher.txt # (right click and 'Save Link/Target As...'), a file containing the encrypted ASCII codes, and the knowledge # that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values # in the original text. data = open("data/p059_cipher.txt", 'r') cipher = [int(char)for char in data.read().split(',')] cipher.append(32) cipher.append(32) cipher_dict = {} for c1 in range(97, 123): for c2 in range(97, 123): for c3 in range(97, 123): decipher = [] for x in range(len(cipher) // 3): decipher.append(chr(c1 ^ cipher[3 * x])) decipher.append(chr(c2 ^ cipher[3 * x + 1])) decipher.append(chr(c3 ^ cipher[3 * x + 2])) cipher_dict[(chr(c1),chr(c2),chr(c3))] = ''.join(decipher) for x in cipher_dict: if cipher_dict[x].find(' the ') != -1: cipher_string = cipher_dict[x][:-2] result = [ord(char) for char in cipher_string] print(sum(result))<file_sep># Coin sums # Problem 31 # In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: # # 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). # It is possible to make £2 in the following way: # # 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p # How many different ways can £2 be made using any number of coins? import sys from functools import lru_cache sys.setrecursionlimit(2000) @lru_cache(maxsize=2**16) def coins(n, denoms): x = len(denoms) if n < 0 or x <= 0: return 0 if n == 0: return 1 removed, reduced = denoms[-1], denoms[:-1] return coins(n, reduced) + coins(n - removed, denoms) denominations = (1, 2, 5, 10, 20, 50, 100, 200) N = 200 print(coins(N, denominations)) <file_sep># Goldbach's other conjecture # Problem 46 # It was proposed by <NAME> that every odd composite number can be written as the sum of a prime and twice # a square. # # 9 = 7 + 2×1^2 # 15 = 7 + 2×2^2 # 21 = 3 + 2×3^2 # 25 = 7 + 2×3^2 # 27 = 19 + 2×2^2 # 33 = 31 + 2×1^2 # # It turns out that the conjecture was false. # # What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? def is_prime(num): if num == 0 or num == 1: return False for index in range(2, int(num ** 0.5) + 1): if not num % index: return False return True primes = [2] x = 3 while True: flag = False if is_prime(x): flag = True primes.append(x) else: square_check, s = 0, 1 while 2 + 2 * s ** 2 <= x and square_check != x: for prime in primes: square_check = prime + 2 * s ** 2 if square_check == x: flag = True break s += 1 if not flag: print(x) break x += 2<file_sep># Path sum: two ways # Problem 81 # In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the # right and down, is indicated in bold red and is equal to 2427. # # matrix = [[131, 673, 234, 103, 18], # [201, 96, 342, 965, 150], # [630, 803, 746, 422, 111], # [537, 699, 497, 121, 956], # [805, 732, 524, 37, 331]] # # Find the minimal path sum, in matrix.txt (right click and "Save Link/Target As..."), a 31K text file # containing a 80 by 80 matrix, from the top left to the bottom right by only moving right and down. data = open('data/p081_matrix.txt', 'r') matrix = [] for line in data.readlines(): matrix.append([int(char) for char in line.split(',')]) flag = True for z in range(2): for y in range(len(matrix)): for x in range(y + 1): row, column = x, y - x left = matrix[row][column - 1] if column - 1 >= 0 else 2 ** 32 up = matrix[row - 1][column] if row - 1 >= 0 else 2 ** 32 minimum = min([left, up]) if left != up else 0 matrix[row][column] = matrix[row][column] + minimum for i, row in enumerate(matrix.copy()): matrix[i] = list(reversed(row)) if flag: matrix = list(reversed(matrix)) flag = False print(min([matrix[i][i] for i in range(len(matrix[0]))])) <file_sep># Counting fractions in a range # Problem 73 # Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced # proper fraction. # # If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: # # 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 # # It can be seen that there are 3 fractions between 1/3 and 1/2. # # How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d ≤ 12,000? from math import gcd max_d = 12000 upper_bound = 1 / 2 lower_bound = 1 / 3 fractions = [] for d in range(2, max_d + 1): for n in range(1, d): decimal = n / d if decimal >= upper_bound: break if gcd(n, d) == 1: if decimal > lower_bound: fractions.append((decimal, n, d)) print(len(fractions)) <file_sep># Number letter counts # Problem 17 # If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are # 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # # If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many # letters would be used? # # # NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains # 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing # out numbers is in compliance with British usage. def number_word(num): words = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety', 100: 'one hundred', 200: 'two hundred', 300: 'three hundred', 400: 'four hundred', 500: 'five hundred', 600: 'six hundred', 700: 'seven hundred', 800: 'eight hundred', 900: 'nine hundred', 1000: 'one thousand' } if num in words: word_string = words[num] elif 100 < num < 1000: word_string = number_word(num // 100) + " hundred and " + number_word(num % 100) else: word_string = number_word((num // 10) * 10) + "-" + number_word(num % 10) return word_string result_array = [] for x in range(1, 1001): word_list = number_word(x).replace('-', ' ').split() letter_count = [len(word) for word in word_list] result_array.append(sum(letter_count)) print(sum(result_array)) <file_sep># Powerful digit sum # Problem 56 # A googol (10^100) is a massive number: one followed by one-hundred zeros; 100^100 is almost unimaginably large: # one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1. # # Considering natural numbers of the form, a^b, where a, b < 100, what is the maximum digital sum? def digit_sum(num): sum_array = [int(char) for char in str(num)] return sum(sum_array) sums = [] for a in range(1, 100): for b in range(1, 100): sums.append(digit_sum(a ** b)) print('Max:', max(sums)) <file_sep># Largest prime factor # Problem 3 # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? factorize_this = 600851475143 def gen_primes(): """ Generate an infinite sequence of prime numbers """ d, q = {}, 2 while True: if q not in d: yield q d[q * q] = [q] else: for p in d[q]: d.setdefault(p + q, []).append(p) del d[q] q += 1 def factorize(n): """ Returns a list of prime factors of n """ primer, factors, p_stop = gen_primes(), [], int(n ** 0.5) + 1 prime = next(primer) while True: if not n % prime: factors.append(prime) while not n % prime: n = n // prime if prime >= n: return factors if prime > p_stop: return factors + [n] prime = next(primer) res = factorize(factorize_this) print(max(res)) <file_sep># Pandigital products # Problem 32 # We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; # for example, the 5-digit number, 15234, is 1 through 5 pandigital. # # The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, # and product is 1 through 9 pandigital. # # Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 # pandigital. # # HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. result = [] for x in range(1, 100000): for y in range(1, 100000): test = str(x * y) digits = len(str(x)) + len(str(y)) if len(test) > 9 - digits: break else: strung = [int(char) for char in test] + [int(char) for char in str(x)] + [int(char) for char in str(y)] if 0 not in strung: if len(set(strung)) == 9: result.append(int(test)) print(sum(set(result)))
66a3362637b864eb3954c01902a2e4f37cd02e21
[ "Python" ]
80
Python
DlabrecquePE/PE-work
6509419c0f3de9f7875e257b149cae6f27565108
127e0af1ff2b0bb6dedc15ecc25dcbc7d6c8eb09
refs/heads/master
<repo_name>SaschaLK/VGDA_Mini<file_sep>/VGDA_Mini/Assets/Scripts/MobJump.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MobJump : MonoBehaviour { // Use this for initialization public MobBehavior thisMob; private Transform targetPos ; public float jumpSpeed = 3f; public bool isGround = true; private void Awake() { targetPos = MobManager.GetPlayerPosition(); } void Start () { } // Update is called once per frame void Update () { jump(); } void jump() { if ((targetPos.position.y - thisMob.transform.position.y) > 0f && isGround) { //thisMob.transform.Translate(new Vector3(thisMob.rb.velocity.x, jumpSpeed * Time.deltaTime, 0)); //thisMob.GetComponent<Rigidbody2D>().velocity = new Vector2(thisMob.rb.velocity.x, //(targetPos.position.y - thisMob.transform.position.y) * jumpSpeed); isGround = false; } } private void OnTriggerEnter2D(Collider2D collision) { //thisMob.GetComponent<Rigidbody2D>().velocity = new Vector2(thisMob.rb.velocity.x, 0); //isGround = true; } } <file_sep>/VGDA_Mini/Assets/Scripts/LoaderBehaviour.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class LoaderBehaviour : MonoBehaviour { public GameObject gameManager; private void Awake() { if(GameObject.Find("GameManager(Clone)") == null) { Instantiate(gameManager); } } } <file_sep>/VGDA_Mini/Assets/Scripts/MainMenuScrollBehaviour.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MainMenuScrollBehaviour : MonoBehaviour { public List<Image> images = new List<Image>(); public float scrollSpeed; private Vector3 setbackPosition; private Vector3 forwardPosition; private List<float> imagesStartY = new List<float>(); private void Start() { //Set image scale to Windows Size foreach (Image image in images) { image.rectTransform.sizeDelta = new Vector2(Screen.width, Screen.height); } //Set image starting positions Vector3 tempLoadingPosition = transform.position; foreach(Image image in images) { image.transform.position = tempLoadingPosition; tempLoadingPosition = new Vector3(transform.position.x, -image.transform.position.y, transform.position.z); } //Add image starting positions to starting position list foreach (Image image in images) { imagesStartY.Add(image.transform.position.y); } setbackPosition = images[images.Count - 1].transform.position; forwardPosition = setbackPosition * -3; } private void Update() { for (int i = 0; i < images.Count; i++) { if (images[i].transform.position.y >= forwardPosition.y) { images[i].transform.position = setbackPosition; } else { images[i].transform.position = images[i].transform.position + (new Vector3(0, scrollSpeed * Time.deltaTime, 0)); } } } } <file_sep>/VGDA_Mini/Assets/Scripts/PlayerShoot.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerShoot : MonoBehaviour { public Transform playerTransform; public float shootRange = 100f; // Use this for initialization Camera cam; void Start () { cam = Camera.main; } // Update is called once per frame void Update () { if (Input.GetButtonDown("Fire1")) { shoot(); } } public void shoot() { //RaycastHit hit; Vector3 mousePos = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0)); Vector2 raycastDir = new Vector2(mousePos.x - playerTransform.position.x, mousePos.y - playerTransform.position.y); //Debug.Log("X"); // Debug.Log(raycastDir.x); Debug.DrawRay(playerTransform.position, raycastDir, Color.red, 5); //if (Physics.Raycast(playerTransform.position, raycastDir, out hit, shootRange)) // DOESNT WORK FOR 2D STUFF // { // hit.collider.gameObject.SetActive(false); // Debug.Log("Did Hit"); // } RaycastHit2D hitt = Physics2D.Raycast(playerTransform.position, raycastDir); if (hitt.collider != null) { if (hitt.collider.tag == "Enemy") { hitt.collider.gameObject.SetActive(false); Debug.Log("Did Hit"); } } } } <file_sep>/VGDA_Mini/Assets/Scripts/ScoreBehaviour.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ScoreBehaviour : MonoBehaviour { //private float score; private Text score; private void Awake() { score = GetComponent<Text>(); } private void Update() { score.text = "Score: " + Time.timeSinceLevelLoad.ToString(); } } <file_sep>/VGDA_Mini/Assets/Scripts/MobBehavior.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MobBehavior : MonoBehaviour { private Transform targetPos;//set target from inspector instead of looking in Update public float speed; public GameObject projectilePrefab; private Rigidbody2D rb; private Animator mobAnimator; public bool isFlying; private void Awake() { LoadProjectile(); } void Start() { mobAnimator = GetComponent<Animator>(); rb = this.GetComponent<Rigidbody2D>(); targetPos = MobManager.GetPlayerPosition(); } void Update() { if (isFlying) { Fly(); } else { FollowPlayer(); //move towards the player } Shoot(); } private void LoadProjectile() { projectilePrefab = GameObject.Instantiate(projectilePrefab); projectilePrefab.SetActive(false); } private void FollowPlayer() { if ((targetPos.position.x - transform.position.x) > 0.1f) { transform.Translate(new Vector3(speed * Time.deltaTime, rb.velocity.y, 0)); } else { if ((targetPos.position.x - transform.position.x) < -0.1f) { transform.Translate(new Vector3(-1 * speed * Time.deltaTime, rb.velocity.y, 0)); } } } private void Fly() { if(targetPos.position != transform.position) { rb.velocity = new Vector2((targetPos.position.x - transform.position.x) * .3f, (targetPos.position.y - transform.position.y) * .3f); } } private void Shoot() { if (!projectilePrefab.activeSelf) { mobAnimator.SetTrigger("Attack"); projectilePrefab.SetActive(true); projectilePrefab.transform.position = this.transform.position; projectilePrefab.GetComponent<Rigidbody2D>().velocity = new Vector2((targetPos.position.x - transform.position.x) * .3f, (targetPos.position.y - transform.position.y) * .3f); Invoke("KillProjectile", 4f); } } private void KillProjectile() { projectilePrefab.SetActive(false); } }<file_sep>/VGDA_Mini/Assets/Scripts/MobManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MobManager : MonoBehaviour { public static MobManager instance; public Transform playerPos; public GameObject[] mobs; private List<GameObject> mobList = new List<GameObject>(); public int mobCount; public float spawnDelay; private void Awake() { if (instance == null) { instance = this; } } void Start() { LoadMobs(); StartCoroutine(SpawnMob()); } private void LoadMobs() { for (int i = 0; i < mobCount; i++) { mobList.Add(GameObject.Instantiate(mobs[0])); mobList[i].SetActive(false); } } public static Transform GetPlayerPosition() { return instance.playerPos; } private IEnumerator SpawnMob() { if(this.transform != null) { foreach (GameObject mob in mobList) { if (!mob.activeSelf) { mob.transform.position = this.transform.position; mob.SetActive(true); yield return new WaitForSecondsRealtime(spawnDelay); } } } else { StopAllCoroutines(); } } } <file_sep>/VGDA_Mini/Assets/Scripts/GameManagerBehaviour.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameManagerBehaviour : MonoBehaviour { public static GameManagerBehaviour instance; private void Awake() { instance = this; DontDestroyOnLoad(instance); } public void GoBackToMainMenu() { SceneManager.LoadScene("MainMenu"); } } <file_sep>/VGDA_Mini/Assets/Scripts/PlayerControler.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerControler : MonoBehaviour { public static PlayerControler instance; public Rigidbody2D myRigidBody; //player RigidBody public float jumpForce = 4; public float movementSpeed = 5; public float deathTime; private bool isAlive; private bool onFloor = true; //to see if it's grounded private float horizontalInput; private Vector3 right = new Vector3(-1,1,1); private Vector3 left = new Vector3(1,1,1); private Animator playerAnimator; private SpriteRenderer sr; private AudioSource audioSource; private void Awake() { instance = this; } private void Start() { playerAnimator = GetComponent<Animator>(); sr = GetComponent<SpriteRenderer>(); audioSource = GetComponent<AudioSource>(); sr.enabled = true; isAlive = true; } private void Update() { MovePlayer(); } // this function makes the player move left, right and jump. private void MovePlayer() { if(Input.GetAxis("Horizontal") > 0.5) { transform.localScale = right; playerAnimator.SetTrigger("playerWalk"); } else if(Input.GetAxis("Horizontal") < -0.5) { transform.localScale = left; playerAnimator.SetTrigger("playerWalk"); } else { playerAnimator.SetTrigger("playerIdle"); } horizontalInput = Input.GetAxis("Horizontal"); transform.position = transform.position + new Vector3(horizontalInput * movementSpeed * Time.deltaTime, 0, 0); if (Input.GetButtonDown("Jump") && onFloor) { myRigidBody.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse); onFloor = false; } } //check the collision with the floor to avoid jumping in the air void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.CompareTag("Floor") && onFloor == false) { onFloor = true; } if (other.gameObject.CompareTag("Enemy") && isAlive) { isAlive = false; sr.enabled = false; audioSource.Play(); Invoke("Die", deathTime); } } private void Die() { GameManagerBehaviour.instance.GoBackToMainMenu(); } }
08346ce4b6a4498e6b1fbb416c1894e54265b236
[ "C#" ]
9
C#
SaschaLK/VGDA_Mini
8e109629ec476d4600adb2bb9c60132a832fe44c
1106eff78ced1f1b7413a31ab671749382a9a736
refs/heads/master
<file_sep> const fs = require('fs'); const path = require('path'); const {copyFilesToFolder} = require('./utils'); const fileDir = '/Users/lyk/Desktop/stock_data'; const sourceDir = path.join(fileDir, 'processed'); const targetDir = path.join(fileDir, 'filterd'); // 筛除ST、科创、创业版 const filterByFilename = fileName => { if (/(300|301|688|689)[0-9]{3}/.test(fileName)) { return false; } if (/ST/.test(fileName)) { return false; } return true; } // 得到排好序的文件路径列表 const filePaths = fs.readdirSync(sourceDir) .filter(fileName => filterByFilename(fileName)) // 有效文件名 .map(fileName => path.join(sourceDir, fileName)); // 生成绝对路径 copyFilesToFolder(filePaths, targetDir); <file_sep>// 当天的主力进流入 > 过去n天主力净流入最大值的x倍 const getAvgLargerByRatio = (stockInfos, ratio, n, targetDate) => { const {inflows, dates} = stockInfos; const index = dates.findIndex(date => date === targetDate); const filteredInflows = inflows.slice(index - n + 1, index + 1); const avg = filteredInflows.reduce((sum, inflow) => Number(sum) + Number(inflow), 0) / n; let posCount = 0; const avgPos = filteredInflows.reduce((sum, inflow) => { if (inflow > 0) { posCount++; return sum + inflow; } return sum; }, 0) / posCount; let negCount = 0; const avgNeg = filteredInflows.reduce((sum, inflow) => { if (inflow < 0) { negCount++; return sum + inflow; } return sum; }, 0) / negCount; const targetInflow = inflows[index]; const exactRatio = targetInflow / avgPos; const isAvgLarger = exactRatio > ratio; return {isAvgLarger, exactRatio, filteredInflows, posCount, avg, targetInflow}; }; module.exports = ({stockInfos, ratio = 6.5, dayCount, date}) => { const {isAvgLarger, exactRatio, filteredInflows, posCount, avg, targetInflow} = getAvgLargerByRatio(stockInfos, ratio, dayCount, date); const {code, name} = stockInfos; if (isAvgLarger && posCount >= 15) { console.log( `${code}${name}`.padEnd(15, ' '), '|比值:', exactRatio.toFixed(1).padStart(4, ' '), '|正次数:', posCount.toFixed(0).padStart(2, ' '), '|当日流入: ', targetInflow.toFixed(2).padStart(8, ' '), '|平均流入: ', avg.toFixed(2).padStart(6, ' '), '|5日涨幅:', getRiseRatio(stockInfos, 5, date).toFixed(2).padStart(6, ' '), '|10日涨幅:', getRiseRatio(stockInfos, 10, date).toFixed(2).padStart(6, ' '), '|20日涨幅:', getRiseRatio(stockInfos, 20, date).toFixed(2).padStart(6, ' '), '|日期:', date ); // console.log(filteredInflows); console.log('-------------------------------------------------------------------------------------------------------------------------------------------------------------------'); return true; } }; <file_sep>const avg_ratio = require('./avg_ratio'); const largest_ratio = require('./lagest_ratio'); const long_inflow = require('./long_inflow'); const rising_inflow_ratio = require('./rising_inflow_ratio'); const rising_inflow = require('./rising_inflow'); const largest = require('./largest'); module.exports = { avg_ratio, largest_ratio, long_inflow, rising_inflow_ratio, rising_inflow, largest, } <file_sep>const fs = require('fs'); const path = require('path'); const moment = require('moment'); const ProgressBar = require('./utils/process_bar'); const {getStockRawData, getInfosFromStockRawData, generateDates, exportExcel} = require('./utils'); const {avg_ratio, largest_ratio, long_inflow, rising_inflow_ratio, rising_inflow, largest} = require('./stategies') const filteredStocks = []; const riseRatios = []; // 隔日/两日/三日/五日涨幅 const fileDir = '/Users/lyk/Desktop/stock_data/processed' const filePaths = fs.readdirSync(fileDir).map(fileName => path.join(fileDir, fileName)); const cachedStockInfos = {}; const exectStrategy = ({date, dayCount = 40, stratege, ratio}) => { // 周六日 if (moment(date).day() === 0 || moment(date).day() === 6) { return; } filePaths.slice(0).forEach((filePath, index) => { // 不是股票文件,跳过 if (!(/[0-9]{6}/.test(filePath))) { return; } // 科创、创业版、错误数据跳过 if (/(300|301|688|689)[0-9]{3}/.test(filePath)) { return; } // 过滤ST if (/ST/.test(filePath)) { return; } let stockInfos; if (cachedStockInfos[filePath]) { stockInfos = cachedStockInfos[filePath]; } else { const stockRawData = getStockRawData(filePath); stockInfos = getInfosFromStockRawData(stockRawData); cachedStockInfos[filePath] = stockInfos; } const {dates, name} = stockInfos; // 非法日期 if (dates.indexOf(date) === -1) { return; } const filteredStock = stratege({stockInfos, date, dayCount, ratio}); if (filteredStock) { filteredStocks.push(filteredStock); } }); } const dates = generateDates('2021-08-06', '2021-08-06', 1); const startTime = Date.now() dates.slice(0).forEach(date => { exectStrategy({ date: date, dayCount: 20, // ratio: 4, stratege: long_inflow }); }); result = filteredStocks || filteredStocks.reduce((res, stock) => { if (!res.find(item => item[1] === stock[1])) { res.push(stock); } return res; }, []) exportExcel(path.join('/Users/lyk/Desktop/stock_data/', 'result_long_inflow.xls'), result); console.log('耗时:', moment.utc(Date.now() - startTime).format('HH时mm分ss秒')) <file_sep>const {getRiseRatio} = require('../utils'); // 主力净流入、净流入率、前n天最大, const getLargest = ({stockInfos, dayCount: n, date: targetDate}) => { const {inflows, tradeAmounts, inflowRatios, dates, code} = stockInfos; const index = dates.findIndex(date => date === targetDate); const filteredInflows = inflows.slice(index - n + 1, index + 1); const filteredTradeAmounts = tradeAmounts.slice(index - n + 1, index + 1); const filteredInflowRatios = inflowRatios.slice(index - n + 1, index + 1); const inflow = filteredInflows.pop(); const tradeAmount = filteredTradeAmounts.pop(); const inflowRatio = filteredInflowRatios.pop(); let isInflowLargest, isTradeAmountLargest, isInflowRatioLargest; if (inflow && tradeAmount && inflow) { isInflowLargest = filteredInflows.find(x => Number(x) >= Number(inflow)) === undefined; isTradeAmountLargest = filteredTradeAmounts.find(x => Number(x) >= Number(tradeAmount)) === undefined; isInflowRatioLargest = filteredInflowRatios.find(x => Number(x) >= Number(inflowRatio)) === undefined } return { result: isInflowLargest && isTradeAmountLargest && isInflowRatioLargest, inflow, tradeAmount, inflowRatio }; }; module.exports = ({stockInfos, dayCount = 30, date}) => { const {code, name, inflows} = stockInfos; try { const {result, inflow, tradeAmount, inflowRatio} = getLargest({stockInfos, dayCount, date}); if (result) { console.log( `${code}${name}`.padEnd(15, ' '), '|日期:', date, '|净流入:', inflow.toFixed(0).padStart(6, ' '), '|净流入率:', inflowRatio.toFixed(1).padStart(4, ' '), '|交易额:', tradeAmount.toFixed(0).padStart(6, ' '), // '|隔日涨幅:', getRiseRatio(stockInfos, 1, date).toFixed(2).padStart(6, ' '), '|第2日涨幅:', (getRiseRatio(stockInfos, 2, date) - getRiseRatio(stockInfos, 1, date)).toFixed(2).padStart(6, ' '), '|3日涨幅:', getRiseRatio(stockInfos, 3, date).toFixed(2).padStart(6, ' '), '|5日涨幅:', getRiseRatio(stockInfos, 5, date).toFixed(2).padStart(6, ' '), '|10日涨幅:', getRiseRatio(stockInfos, 10, date).toFixed(2).padStart(6, ' '), '|20日涨幅:', getRiseRatio(stockInfos, 20, date).toFixed(2).padStart(6, ' '), ); console.log('-------------------------------------------------------------------------------------------------------------------------------------------------------------------'); // return { // '1day': getRiseRatio(stockInfos, 1, date).toFixed(2).padStart(6, ' '), // '2day': getRiseRatio(stockInfos, 2, date).toFixed(2).padStart(6, ' '), // '3day': getRiseRatio(stockInfos, 3, date).toFixed(2).padStart(6, ' '), // '5day': getRiseRatio(stockInfos, 5, date).toFixed(2).padStart(6, ' '), // }; return [ date, code, name, // Number((getRiseRatio(stockInfos, 2, date) - getRiseRatio(stockInfos, 1, date)).toFixed(2).padStart(6, ' ')), // Number((getRiseRatio(stockInfos, 3, date) - getRiseRatio(stockInfos, 1, date)).toFixed(2).padStart(6, ' ')), // Number((getRiseRatio(stockInfos, 4, date) - getRiseRatio(stockInfos, 1, date)).toFixed(2).padStart(6, ' ')), // Number((getRiseRatio(stockInfos, 5, date) - getRiseRatio(stockInfos, 1, date)).toFixed(2).padStart(6, ' ')), ] } } catch (e) { console.log(e); console.log(`${code}${name}`); console.log(`date: ${date}`); } }; <file_sep>// 这里用到一个很实用的 npm 模块,用以在同一行打印文本 const slog = require('single-line-log').stdout; function ProgressBar(description, bar_length) { this.description = description || 'Progress'; this.length = bar_length || 100; this.render = function(opts) { const percent = (opts.completed / opts.total).toFixed(4); // 计算进度(子任务的 完成数 除以 总数) const cell_num = Math.floor(percent * this.length); // 计算需要多少个 █ 符号来拼凑图案 // 拼接黑色条 const cell = '█'.repeat(cell_num); // 拼接灰色条 const empty = '░'.repeat(this.length - cell_num); // 拼接最终文本 const cmdText = this.description + ': ' + (100*percent).toFixed(2) + '% ' + cell + empty + ' ' + opts.completed + '/' + opts.total; // 在单行输出文本 slog(cmdText); } } module.exports = ProgressBar; <file_sep>const fs = require('fs'); const path = require('path'); const moment = require('moment'); const {getStockData, appendStockDataRow} = require('./utils'); const startTime = Date.now(); const handleFiles = (filePaths, targetDir) => { const datasMap = new Map(); const startProcessTime = Date.now(); filePaths.forEach(filePath => { const stockDatas = getStockData(filePath); stockDatas.forEach(stockData => { const {code, stockName, data} = stockData; const fileName = `${stockName}${code}.xls`; const sheetName = `${stockName}${code}`.replace('*', ''); if (datasMap.get(sheetName)) { datasMap.get(sheetName).data.push(data); } else { datasMap.set(sheetName, { filePath: path.join(targetDir, fileName), sheetName: sheetName, data: [data], }); } }); }); console.log('读文件+执行耗时:', moment.utc(Date.now() - startProcessTime).format('HH时mm分ss秒')); const startWriteTime = Date.now(); datasMap.forEach(({filePath, sheetName, data}, key) => { appendStockDataRow(filePath, sheetName, data); // 写完就丢,释放内容 datasMap.delete(key); }); console.log('写文件耗时:', moment.utc(Date.now() - startWriteTime).format('HH时mm分ss秒')) }; const getSplitFilePathsArray = (filePaths, splitCount) => { return filePaths.reduce((result, filePath) => { const currentIdx = result.length - 1; if (currentIdx >= 0 && result[currentIdx].length < splitCount) { result[currentIdx].push(filePath); } else { result.push([filePath]); } return result; }, []); }; const fileDir = '/Users/lyk/Desktop/stock_data' const sourceDir = path.join(fileDir, 'original'); const targetDir = path.join(fileDir, 'processed'); // 得到排好序的文件路径列表 const filePaths = fs.readdirSync(sourceDir) .filter(fileName => /\(每日统计[0-9]{8}\)\.xls$/.test(fileName)) // 有效文件名 .sort((name1, name2) => Number(/([0-9]{8})/.exec(name1)[1]) - Number(/([0-9]{8})/.exec(name2)[1])) // 按日期排序 .map(fileName => path.join(sourceDir, fileName)); // 生成绝对路径 // const filePathsArray = getSplitFilePathsArray(filePaths, 80); const filePathsArray = [filePaths]; filePathsArray.forEach(filePaths => handleFiles(filePaths, targetDir)); console.log('总耗时:', moment.utc(Date.now() - startTime).format('HH时mm分ss秒'))
f3332f5117ba80a5476244d65a508400db5221c7
[ "JavaScript" ]
7
JavaScript
ykli109/stock-tools
b021641115d5649bf1fb806cc65eff639b470ce8
6cb4d60ef12be8dd8bfc08cd67f13fcdf472ed03
refs/heads/master
<repo_name>aarontiger/maven_aggregate_study<file_sep>/e3parent/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>e3.mall</groupId> <artifactId>e3-parent</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.6.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <lombok.version>1.18.12</lombok.version> <mybatis-plus.version>3.3.1</mybatis-plus.version> <hutool.version>5.3.2</hutool.version> <gson.version>2.8.6</gson.version> <httpclient.version>4.5.12</httpclient.version> <mysql.version>8.0.19</mysql.version> <druid.version>1.1.22</druid.version> <mybatis-plus.version>3.3.1</mybatis-plus.version> <minio.version>7.1.0</minio.version> <bingo-class>com.bingoyes.Gat1400BingoClientApp</bingo-class> <service-class>com.bingoyes.Gat1400ServiceApp</service-class> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- spring boot test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <scope>provided</scope> </dependency> <!-- HuTool --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>${hutool.version}</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>${gson.version}</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${httpclient.version}</version> </dependency> <!--mqtt--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-integration</artifactId> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-stream</artifactId> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-mqtt</artifactId> </dependency> <!-- spring boot configuration processor --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>${minio.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <!--add by shuhu --> <!-- <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>2.1.3.RELEASE</version> </dependency>--> <!--<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.54</version> </dependency> </dependencies> </project> <file_sep>/README.md 使用maven 建立父项目和子项目的例子 <file_sep>/e3manager/e3-manager-web/src/main/java/cn/e3/controller/TestController.java package cn.e3.controller; import cn.e3.service.TestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("rest/v1/std") public class TestController { @Autowired TestService testService; @GetMapping("test") public String test(){ return testService.test(); } }
f248f8e8732616e19bfcad16e4aae7f81164a691
[ "Markdown", "Java", "Maven POM" ]
3
Maven POM
aarontiger/maven_aggregate_study
64f8a80ad94d1659f913a57f99065eebd9a0d353
07617578d2a09696963cc130ec950e7fb87990b5
refs/heads/master
<file_sep>import React, { useState } from 'react'; // child components import TodoItem from './components/TodoItem'; import TodoForm from './components/TodoForm'; // styles import './app.css'; function TodoApp() { // temp local state data (TODO: persist with localStorage, get via API, store in DB etc) const initialTodos = [ { title: 'Dev a Cool React TodoApp with Hooks', isCompleted: true }, { title: 'Get a New React Gig', isCompleted: false }, { title: 'Have a Big Beer', isCompleted: false }, ]; const [todos, setTodos] = useState(initialTodos); // component methods const addTodo = (title) => { const newTodos = [...todos, { title: title, isCompleted: false }]; setTodos(newTodos); }; const deleteTodo = (index) => { const newTodos = [...todos]; newTodos.splice(index, 1); setTodos(newTodos); }; const completeTodo = (index) => { const newTodos = [...todos]; newTodos[index].isCompleted = true; setTodos(newTodos); }; return ( <div> <header className="app-header"> <h1>Todo App</h1> <ul className="app-todo-list"> {todos.map((todo, index) => ( <TodoItem key={index} index={index} title={todo.title} isCompleted={todo.isCompleted} completeTodo={completeTodo} deleteTodo={deleteTodo} /> ))} </ul> <TodoForm addTodo={addTodo} /> </header> </div> ); } export default TodoApp; <file_sep># React TODO Hooks ## React TODO app reference implementation coded up from memory as interview prep (2020) -- seeded with create-react-app
538b5332961a5dc3fed28c49716217b3c8746ebf
[ "JavaScript", "Markdown" ]
2
JavaScript
wlorand/react-todo-hooks
50173cc84c34dcac42a37383afec6da170aabacb
9519d76a049398fb33ece3a0903e956ea086aa6d
refs/heads/master
<file_sep>#!/bin/bash #install nginx yum install gcc-c++ yum -y install zlib zlib-devel openssl openssl--devel pcre pcre-devel wget http://nginx.org/download/nginx-1.9.15.tar.gz tar -xf nginx-1.9.15.tar.gz cd nginx-1.9.15 ./configure make make install <file_sep>#export PATH=/etc/rc.d/init.d:$PATH iptables -A INPUT -s $1 -p tcp -j ACCEPT # drop #iptables -I INPUT -s 172.16.17.32 -j DROP <file_sep>#export PATH=/etc/rc.d/init.d:$PATH iptables -L -n #清除自己设置的规则 #iptables -X #清除所有规则 iptables -F #设定预设规则 iptables -P INPUT DROP #ptables -P INPUT ACCEPT iptables -P OUTPUT ACCEPT #iptables -P OUTPUT DROP iptables -P FORWARD DROP #iptables -P FORWARD ACCEPT #开启常用端口 iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT iptables -A INPUT -p tcp --dport 22 -j ACCEPT iptables -A INPUT -p tcp --dport 80 -j ACCEPT iptables -A INPUT -p tcp --dport 443 -j ACCEPT #iptables -A INPUT -p tcp --dport 6379 -j ACCEPT #iptables -A INPUT -p tcp -s 172.16.58.3 --dport 6379 -j ACCEPT #xz logstash access iptables -A INPUT -p tcp -s 192.168.127.12 --dport 6379 -j ACCEPT iptables -A INPUT -s 172.16.17.32 -p tcp --dport 6379 -j ACCEPT iptables -A INPUT -p tcp --dport 9003 -j ACCEPT #iptables -A INPUT -p tcp --dport 9005 -j ACCEPT #iptables -A INPUT -p tcp --dport 8081 -j ACCEPT #iptables -A INPUT -p tcp --dport 8082 -j ACCEPT #iptables -A INPUT -p tcp --dport 8083 -j ACCEPT #iptables -A INPUT -p tcp --dport 9006 -j ACCEPT #iptables -A INPUT -p tcp --dport 8888 -j ACCEPT #iptables -A INPUT -p tcp --dport 28080 -j ACCEPT ## deubg port #iptables -A INPUT -p tcp --dport 9900 -j ACCEPT #iptables -A INPUT -p tcp --dport 9901 -j ACCEPT #iptables -A INPUT -p tcp --dport 9902 -j ACCEPT #iptables -A INPUT -p tcp --dport 9903 -j ACCEPT #iptables -A INPUT -p tcp --dport 9904 -j ACCEPT #iptables -A INPUT -p tcp --dport 9905 -j ACCEPT #iptables -A INPUT -p tcp --dport 9906 -j ACCEPT #iptables -A INPUT -p tcp --dport 9907 -j ACCEPT #iptables -A INPUT -p tcp --dport 3000 -j ACCEPT #iptables -A INPUT -p tcp --dport 81 -j ACCEPT #iptables -A INPUT -p tcp --dport 3307 -j ACCEPT #iptables -A INPUT -p tcp --dport 8081 -j ACCEPT #iptables -A INPUT -p tcp --dport 28081 -j ACCEPT #iptables -A INPUT -p tcp --dport 28082 -j ACCEPT #iptables -A INPUT -p tcp --dport 28083 -j ACCEPT #iptables -A INPUT -p tcp --dport 28084 -j ACCEPT #iptables -A INPUT -p tcp --dport 28085 -j ACCEPT iptables -A INPUT -i lo -p all -j ACCEPT iptables -A INPUT -s 192.168.1.2 -p tcp -j ACCEPT iptables -A INPUT -s 192.168.1.4 -p tcp -j ACCEPT #iptables -A INPUT -s 172.16.17.32 -p tcp -j ACCEPT #iptables -A INPUT -s 172.16.58.3 -p tcp -j ACCEPT #iptables -A INPUT -s 192.168.3.11 -p tcp -j ACCEPT #iptables -A INPUT -s 172.16.58.3 -p tcp -j ACCEPT # drop iptables -I INPUT -s 192.168.3.11 -j DROP <file_sep>#!/bin/bash #clear old tomcat log #remove app logs echo "remove app logs before 1 days" find /u01/logs/app/ -type f -atime +1 | xargs rm -fr #clear logstash log echo "clear logstash logs" echo > /u01/logstash-2.3.1/logs/inner.log echo > /u01/logstash-2.3.1/logs/outer.log #clear nginx logs echo "clear nginx logs" find /u01/logs/nginx/ -type f | while read file; do echo -n >"$file"; done #clear tomcat log echo "clear tomcat logs" find /u01/deploy/project/tomcat_*/logs -type f | while read file; do echo -n >"$file"; done echo "remove tomcat app bak before 7 days" find /u01/deploy/project/tomcat_*/bak/ -mtime +7 -name "*.BAK" | xargs rm -fr #clear task log log_name=`date "+%Y.%m"` curl_cmd="curl 'http://localhost:9200/task_log-$log_name' -X DELETE -H 'Pragma: no-cache' -H 'Origin: http://localhost:9200' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' -H 'Accept: application/json, text/javascript, */*; q=0.01' -H 'Cache-Control: no-cache' -H 'X-Requested-With: XMLHttpRequest' -H 'Cookie: JSESSIONID=<KEY>' -H 'Connection: keep-alive' -H 'Referer: http://localhost:9200/_plugin/head/' --compressed" eval $curl_cmd <file_sep>#!/bin/bash #clear old tomcat log module=$1 if [ -z $module ] then cmd="find /u01 -size +100M | grep "logs" | xargs rm -fr" echo ${cmd} eval ${cmd} exit 0 fi rm_arr=("manager" "localhost" "host" "catalina.2015-0" "catalina.2015-11") for var in ${rm_arr[@]}; do rm_cmd="rm -fr /u01/deploy/project/tomcat_${module}/logs/${var}*" echo ${rm_cmd} eval ${rm_cmd} done <file_sep>#!/bin/bash #http://www.redis.cn/download.html wget http://download.redis.io/releases/redis-3.2.0.tar.gz tar xzf redis-3.2.0.tar.gz cd redis-3.2.0 make
12b284effb405237402c312f6ff75cb5103ea3f8
[ "Shell" ]
6
Shell
tss0823/shell
6306c88cf17f618e279d0218dffda20490048006
88321c8c184661baa781cb35c90e57051fadb18e
refs/heads/master
<repo_name>monsterkodi/color-ls<file_sep>/js/test.js // monsterkodi/kode 0.211.0 var _k_ = {in: function (a,l) {return (typeof l === 'string' && typeof a === 'string' && a.length ? '' : []).indexOf.call(l,a) >= 0}} var cls, kstr, ls, out, slash slash = require('kslash') kstr = require('kstr') ls = require('../') cls = function () { var lines, raw, stripped, trimmed raw = ls.apply(ls,arguments) stripped = kstr.stripAnsi(raw) lines = stripped.split('\n') trimmed = lines.map(function (s) { return s.trim() }) trimmed.lines = lines trimmed.clrzd = raw.split('\n') return trimmed } module.exports["ls"] = function () { section("module", function () { compare(typeof(ls) === 'function',true) }) section("ls", function () { out = cls() compare(_k_.in('js',out) && _k_.in('bin',out) && _k_.in('kode',out) && _k_.in('node_modules',out) && _k_.in('package.noon',out) && _k_.in('package.json',out) && _k_.in('readme.md',out),true) }) section("ls .", function () { out = cls('.') compare(_k_.in('js',out) && _k_.in('bin',out) && _k_.in('kode',out) && _k_.in('node_modules',out) && _k_.in('package.noon',out) && _k_.in('package.json',out) && _k_.in('readme.md',out),true) }) section("ls bin", function () { out = cls('./bin') compare(_k_.in('img',out) && _k_.in('test',out) && _k_.in('color-ls',out),true) }) section("cd bin/test and ls .", function () { process.chdir('./bin/test') out = cls('.') compare(_k_.in('Makefile',out),true) }) section("offset", function () { out = cls('.',{offset:true}) compare(_k_.in(' Makefile',out.lines) && _k_.in(' coffee.coffee',out.lines),true) }) section("tree", function () { out = cls('a',{tree:true,depth:99,followSymLinks:true}) compare(_k_.in('a',out[1]),true) compare(_k_.in('a.b.c',out[2]),true) compare(_k_.in('a.txt',out[3]),true) compare(_k_.in('txt.txt',out[4]),true) compare(_k_.in('b',out[5]),true) if (!slash.win()) { compare(_k_.in('b.lnk ► b.txt',out[6]),true) } }) section("recursive", function () { out = cls('a',{recurse:true,depth:99,followSymLinks:true}) compare(_k_.in('▶ a',out[1]),true) compare(_k_.in('b',out[3]) && _k_.in('a.b.c',out[4]) && _k_.in('a.txt',out[5]) && _k_.in('txt.txt',out[6]) && _k_.in('▶ a/b',out[8]),true) compare(_k_.in('c',out[10]),true) if (!slash.win()) { compare(_k_.in('b.lnk ► b.txt',out[11]),true) } }) } module.exports["ls"]._section_ = true module.exports._test_ = true module.exports <file_sep>/readme.md ![icon](./bin/img/icon.png) ![example](./bin/img/example.png) ### tree ![tree](./bin/img/tree.png) ### find files ![find](./bin/img/find.png) ### nerd font icons ![nerdy](./bin/img/nerdy.png) icon map by [lsd](https://github.com/Peltoche/lsd), works only with a [nerd font](https://github.com/ryanoasis/nerd-fonts) ### pretty nerdy ![pretty](./bin/img/pretty.png) ### usage ![usage](./bin/img/usage.png) ### install ```shell npm install -g color-ls ``` If you don't use `node`, go try out [ls-go](https://github.com/acarl005/ls-go), which is similar to color-ls. [lsd](https://github.com/Peltoche/lsd) and [exa](https://github.com/ogham/exa) are also quite colorful alternatives. ### notes * needs a terminal that supports 256 colors * optimized for dark backgrounds * call a doctor if your eyes start bleeding :) [![npm package][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [npm-image]:https://img.shields.io/npm/v/color-ls.svg [npm-url]:http://npmjs.org/package/color-ls [downloads-image]:https://img.shields.io/npm/dm/color-ls.svg [downloads-url]:https://www.npmtrends.com/color-ls <file_sep>/bin/color-ls #!/usr/bin/env node require('../js/color-ls');
60a54131af3dc1ee924afeddb1ad46069c0d2132
[ "JavaScript", "Markdown" ]
3
JavaScript
monsterkodi/color-ls
fba3ced3a7d9366ec1970eb20e4c8a6f0af8e4bd
4343b5c9534d90354ccb521dfa4a592390495448
refs/heads/master
<file_sep># TestingTask Приложение отправляет список объектов из БД (генерируется автоматически) в integration поток. Так как задача состояла только в отправке объектов (без ответа), использовался DirectChannel с активатором. Сервис модифицирует каждый объект в отдельном потоке (метод, модифицирующий объект, возвращает CompletableFuture<> в соответствии с заданием), после чего обновляет состояние объектов в базе данных. Применяется логирование с помощью сквозной функциональности (используется spring AOP с AspectJ аннотациями). <file_sep>package sergeyrusakov.testingtask; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.integration.channel.DirectChannel; import org.springframework.messaging.support.GenericMessage; import org.springframework.scheduling.annotation.Scheduled; import java.util.*; public class TaskManager { @Autowired private AccountsRepository repository; private DirectChannel channel; public void setChannel(DirectChannel channel) { this.channel = channel; } //Генерирует список объектов и отправляет через GenericMessage в поток @Scheduled(fixedDelay = 5000) public void getNextObject(){ ArrayList<BankAccount> accountArrayList = (ArrayList<BankAccount>) repository.findAll(); LinkedHashSet<BankAccount> processingAccounts = new LinkedHashSet<>(); int accountsTotal = accountArrayList.size(); Random random = new Random(); for(int i=0;i<random.nextInt(accountsTotal);i++){ processingAccounts.add(accountArrayList.get(random.nextInt(accountsTotal))); } if(processingAccounts.size()!=0) { channel.send(new GenericMessage<>(processingAccounts)); } } } <file_sep>package sergeyrusakov.testingtask; import org.springframework.messaging.support.GenericMessage; import java.util.Collection; public class MainServiceActivator { private MainService mainService; public MainServiceActivator(MainService mainService) { this.mainService=mainService; } //Запускает обработку списка объектов при получении сообщения public void startService(GenericMessage<Collection<BankAccount>> message){ mainService.processAccounts(message.getPayload()); } } <file_sep>package sergeyrusakov.testingtask; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.config.EnableIntegration; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @SpringBootApplication @EnableTransactionManagement @EnableScheduling @EnableIntegration @IntegrationComponentScan @EnableAspectJAutoProxy public class SpringApp { public static void main(String[] args) { SpringApplication.run(SpringApp.class,args); } @Bean(name="inputChannel") public DirectChannel inputChannel(){ return new DirectChannel(); } @Bean public IntegrationFlow integrationFlows(){ return IntegrationFlows.from("inputChannel") .handle("activator","startService") .get(); } @Bean public MainServiceActivator activator(){ return new MainServiceActivator(mainService()); } @Bean public MainService mainService(){ return new MainService(); } @Bean public TaskManager taskManager(){ TaskManager taskManager = new TaskManager(); taskManager.setChannel(inputChannel()); return taskManager; } @Bean public ExecutorService executorService(){ return Executors.newCachedThreadPool(); } @Bean public AccountProcessor accountProcessor(){ return new AccountProcessor(); } } <file_sep>package sergeyrusakov.testingtask; import org.springframework.beans.factory.annotation.Autowired; import java.util.*; import java.util.concurrent.*; public class MainService { @Autowired private AccountProcessor accountProcessor; //Вызывает методы по обработке и сохранению списка объектов public void processAccounts(Collection<BankAccount> collection){ List<CompletableFuture<BankAccount>> completableFutureList = new ArrayList<>(); collection.forEach((x)->completableFutureList.add(accountProcessor.processAccount(x))); for(CompletableFuture<BankAccount> future:completableFutureList){ try { BankAccount account = accountProcessor.getAccount(future); accountProcessor.saveAccount(account); } catch (ExecutionException | InterruptedException e) { e.printStackTrace(); } } } }
d293bf93cbe9f938df1465bc681e03419eef2a0d
[ "Markdown", "Java" ]
5
Markdown
SergeyRusakov/TestingTask
191c5eb9ab4eae1454bda56fdf6c5ebe7a9be3a5
627eaa789422dab20fbe1a5c44f5769cca450ed4
refs/heads/main
<repo_name>zlibutmatthew/Sentiment-Analysis-RNN<file_sep>/Sentiment Analysis.py # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.11.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="zZOwGUpCUi5m" # **************************************************** # # To run this code in **Google Colab**. # # Google Drive Structure: # # - My Drive # - Colab Notebooks # - Data # - amazon_reviews.csv # - Sentiment Analysis.ipynb # # Uncomment "using_colab = False" on line 4 to run this code on jupyter. # # **************************************************** # + [markdown] id="EpFGOWLv208v" # # Sentiment Analysis on Amazon Commerce Reviews - TensorFlow # + [markdown] id="oKUIypPNr7pb" # Team Memebers: <NAME> & <NAME> # + [markdown] id="A-Odp34Y208w" # ### Background # Sentiment Analysis is a technique used in order to understand the emotional tone behind a series of words. It is used for many different purposes such as gaining an idea of public opinion on certain topics, used to understand customer reviews, for market research, and customer service approaches. There are many nuances in the english language, grammer, slang, cultural variation, and tone can change a review in a way that is hard for a machine to understand. Consider the sentence "My package was delayed. Brilliant!"- most humans would recognize this as sarcasm, but the machine may see "Brilliant!" and decide that this is a positive review. Our goal is to try and maximize the machines accuracy using a Recurrent Neural Network. # + [markdown] id="dwcrUhzG208x" # ### Dataset # Our dataset was a subset of the data retrieved on Kaggle (https://www.kaggle.com/bittlingmayer/amazonreviews#train.ft.txt.bz2). # The datasets author is <NAME> # The dataset can also be found in .csv format in Xiang Zhang's Google Drive directory (https://drive.google.com/drive/folders/0Bz8a_Dbh9Qhbfll6bVpmNUtUcFdjYmF2SEpmZUZUcVNiMUw1TWN6RDV3a0JHT3kxLVhVR2M) # # Dataset has 150k instances with 2 attributes # + [markdown] id="PKxuVzPx208x" # #### Variables # Independent - Text (string of sentences). # Dependent -Label (Negative 0, Positive 1) # + colab={"base_uri": "https://localhost:8080/"} id="kI2zqvs_GUWV" executionInfo={"status": "ok", "timestamp": 1621044136378, "user_tz": 300, "elapsed": 18470, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "02380624916791193636"}} outputId="e3cdc832-2812-4b17-ad7f-6cfc78f66e54" using_colab = True from google.colab import drive drive.mount('/content/drive') #using_colab = False # + colab={"base_uri": "https://localhost:8080/"} id="j3t5cYT5QVFv" executionInfo={"status": "ok", "timestamp": 1621044144956, "user_tz": 300, "elapsed": 265, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "02380624916791193636"}} outputId="2359923c-9d75-4a20-9565-dd1e9c0b2077" # %cd "/content/drive/MyDrive/Colab Notebooks" # + colab={"base_uri": "https://localhost:8080/"} id="t4Q9V2wfRBAJ" executionInfo={"status": "ok", "timestamp": 1621044146049, "user_tz": 300, "elapsed": 261, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "02380624916791193636"}} outputId="e50a78af-db20-43f1-afce-883d00286a8b" # %set_env TFDS_DATA_DIR=/content/drive/MyDrive/Colab Notebooks/tfds/ # + id="nJEnCR73nX9l" #Import necessary packages import re import tensorflow as tf from collections import Counter import numpy as np import pandas as pd import tensorflow_datasets as tfds from tensorflow.keras.layers import Bidirectional from tensorflow.keras import Sequential from tensorflow.keras.layers import Embedding from tensorflow.keras.layers import SimpleRNN from tensorflow.keras.layers import LSTM from tensorflow.keras.layers import GRU from tensorflow.keras.layers import Dense # + colab={"base_uri": "https://localhost:8080/", "height": 204} id="luyebS0Q_vDy" executionInfo={"status": "ok", "timestamp": 1621044153498, "user_tz": 300, "elapsed": 2587, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "02380624916791193636"}} outputId="8303ed07-b492-4433-f093-844ba6d7584c" if using_colab: df = pd.read_csv('./Data/amazon_reviews.csv') else: data = pd.read_csv('amazon_reviews.csv') df.head() # + id="xExhCTu39ISA" #Preprocessing def remove_numbers(x): x = re.sub('[0-9]{5,}', '#####', x) x = re.sub('[0-9]{4}', '####', x) x = re.sub('[0-9]{3}', '###', x) x = re.sub('[0-9]{2}', '##', x) return x #Removing Numbers df['text'] = df['text'].apply(lambda x: remove_numbers(x)) # + colab={"base_uri": "https://localhost:8080/"} id="ngXLEK0ll_dM" executionInfo={"status": "ok", "timestamp": 1621044173398, "user_tz": 300, "elapsed": 476, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "02380624916791193636"}} outputId="944510fe-34c9-4d72-a837-3a8b4eaadb39" # Create a dataset target = df.pop('label') ds_raw = tf.data.Dataset.from_tensor_slices( (df.values, target.values)) ## inspection: for ex in ds_raw.take(3): tf.print(ex[0].numpy()[0][:50], ex[1]) # + [markdown] id="0T2tCwX_pJdH" # TRAIN, VALIDATION, TEST SPLITS # + id="K6HeiEkcpNbm" tf.random.set_seed(1) ds_raw = ds_raw.shuffle( 150000, reshuffle_each_iteration=False) ds_raw_test = ds_raw.take(75000) ds_raw_train_valid = ds_raw.skip(75000) ds_raw_train = ds_raw_train_valid.take(37000) ds_raw_valid = ds_raw_train_valid.skip(37000) # + [markdown] id="3afOxC8zppNb" # TOKENIZER # + colab={"base_uri": "https://localhost:8080/"} id="8fMYEip4puID" executionInfo={"status": "ok", "timestamp": 1621044964227, "user_tz": 300, "elapsed": 7684, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "02380624916791193636"}} outputId="1273666e-79e7-43a7-ea4c-6a48fc6dc6ff" ## find unique tokens (words) tokenizer = tfds.deprecated.text.Tokenizer() token_counts = Counter() for example in ds_raw_train: tokens = tokenizer.tokenize(example[0].numpy()[0]) token_counts.update(tokens) print('Vocab-size:', len(token_counts)) # + colab={"base_uri": "https://localhost:8080/"} id="Yd5xlJPXtMod" executionInfo={"status": "ok", "timestamp": 1621044968906, "user_tz": 300, "elapsed": 338, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "02380624916791193636"}} outputId="498d9714-7367-42f8-8921-e2b26ac52c53" ## Encoding each unique token into integers encoder = tfds.deprecated.text.TokenTextEncoder(token_counts) example_str = 'This is an example!' encoder.encode(example_str) # + id="N6K115AJtXRp" ## Define the function for transformation def encode(text_tensor, label): text = text_tensor.numpy()[0] encoded_text = encoder.encode(text) return encoded_text, label ## Wrap the encode function to a TF Op. def encode_map_fn(text, label): return tf.py_function(encode, inp=[text, label], Tout=(tf.int64, tf.int64)) # + colab={"base_uri": "https://localhost:8080/"} id="s3cbJ2VAth97" executionInfo={"status": "ok", "timestamp": 1621044982555, "user_tz": 300, "elapsed": 1126, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "02380624916791193636"}} outputId="5517716f-81c7-4d5c-bcfc-23e2444342e8" ds_train = ds_raw_train.map(encode_map_fn) ds_valid = ds_raw_valid.map(encode_map_fn) ds_test = ds_raw_test.map(encode_map_fn) tf.random.set_seed(1) for example in ds_train.shuffle(1000).take(5): print('Sequence length:', example[0].shape) #example # + id="EXeYLPn1uOEm" ## batching the datasets train_data = ds_train.padded_batch( 32, padded_shapes=([-1],[])) valid_data = ds_valid.padded_batch( 32, padded_shapes=([-1],[])) test_data = ds_test.padded_batch( 32, padded_shapes=([-1],[])) # + [markdown] id="E3MnAIbkwND0" # BUILD RNN MODEL # + id="8Wl6uhEqwPqI" def build_rnn_model(embedding_dim, vocab_size, recurrent_type='SimpleRNN', n_recurrent_units=64, n_recurrent_layers=1, bidirectional=True): tf.random.set_seed(1) # build the model model = tf.keras.Sequential() model.add( Embedding( input_dim=vocab_size, output_dim=embedding_dim, name='embed-layer') ) for i in range(n_recurrent_layers): return_sequences = (i < n_recurrent_layers-1) if recurrent_type == 'SimpleRNN': recurrent_layer = SimpleRNN( units=n_recurrent_units, return_sequences=return_sequences, name='simprnn-layer-{}'.format(i)) elif recurrent_type == 'LSTM': recurrent_layer = LSTM( units=n_recurrent_units, return_sequences=return_sequences, name='lstm-layer-{}'.format(i)) elif recurrent_type == 'GRU': recurrent_layer = GRU( units=n_recurrent_units, return_sequences=return_sequences, name='gru-layer-{}'.format(i)) if bidirectional: recurrent_layer = Bidirectional( recurrent_layer, name='bidir-'+recurrent_layer.name) model.add(recurrent_layer) model.add(tf.keras.layers.Dense(64, activation='relu')) model.add(tf.keras.layers.Dense(1, activation='sigmoid')) return model # + colab={"base_uri": "https://localhost:8080/"} id="rejTqqOAxEIn" executionInfo={"status": "ok", "timestamp": 1621049774568, "user_tz": 300, "elapsed": 820, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "02380624916791193636"}} outputId="09795024-2045-43c3-9d8e-40ae15d636bf" embedding_dim = 20 vocab_size = len(token_counts) + 2 rnn_model = build_rnn_model( embedding_dim, vocab_size, recurrent_type='LSTM', n_recurrent_units=64, n_recurrent_layers=1, bidirectional=True) rnn_model.summary() # + colab={"base_uri": "https://localhost:8080/"} id="r5FwUWXnynhh" executionInfo={"status": "ok", "timestamp": 1621050571346, "user_tz": 300, "elapsed": 435130, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "02380624916791193636"}} outputId="82044a98-96f6-4482-d9a7-19d6548b7b74" rnn_model.compile(optimizer=tf.keras.optimizers.Adam(1e-3), loss=tf.keras.losses.BinaryCrossentropy(from_logits=False), metrics=['accuracy']) history = rnn_model.fit( train_data, validation_data=valid_data, epochs=3) # + id="9FeMYgOZy91f" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1621050952501, "user_tz": 300, "elapsed": 120474, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "02380624916791193636"}} outputId="8b67f471-686f-4f7b-dedf-600bba1fe3c1" results = rnn_model.evaluate(test_data) print('Test Acc.: {:.2f}%'.format(results[1]*100)) # + [markdown] id="twRP7CEv2083" # ### Results # Accuracy for each model # 1. A Simple RNN and 2 epochs: 84.91% # 2. A RNN with 1 GRU Layer and 3 epochs: 86.63% # 3. A RNN with 1 LSTM Layer and 1 epochs: 87.04% # 4. A RNN with 2 GRU Layer and 5 epochs: 84.48% # 5. A RNN with 2 LSTM Layer and 1 epochs: 86.36% # # NEW ACCURACY FOR EACH MODEL (with corrected data splitting) # 1. A Simple RNN and 2 epochs: # 2. A RNN with 1 GRU Layer and 3 epochs: 87.13 # 3. A RNN with 1 LSTM Layer and 1 epochs: 88.02 # 4. A RNN with 2 GRU Layer and 5 epochs: # 5. A RNN with 2 LSTM Layer and 1 epochs: 88.9 # 6. A RNN with 1 GRU Layer and 1 epochs: 88.02 # 7. A RNN with 1 LSTM Layer and 3 epochs: 85.73% # + [markdown] id="7BZHq45_2083" # ### Conclusion and Future Work # The LSTM model trained with 1 epoch was shown to have the best accuracy of 87.04%. If training time weren't an issue, we would be able to train models with much a much more complex layer structure. Also, getting more data on amazon reviews reviews would help since we're working with text. The future work would be to do those. # + id="rJzXkY9C2083" <file_sep>/README.md # Sentiment-Analysis-RNN Our data is a subset of the data found on Kaggle. https://www.kaggle.com/bittlingmayer/amazonreviews#train.ft.txt.bz2
d4812b8d7e364c7f56727c6293739164f262059c
[ "Markdown", "Python" ]
2
Python
zlibutmatthew/Sentiment-Analysis-RNN
f3dc4192df13d52a66c123e8525965de70e56532
b5c541f42139a979af6ee37e8d6dfc0a6a94837a
refs/heads/master
<repo_name>EriN-B/PHP-Blog<file_sep>/blog.php <?php $user = 'root'; $password = ''; $pdo = new PDO('mysql:host=localhost;dbname=blog', $user, $password, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', ]); ?> <?php $thanks = false; $formSent = false; $namesent = false; $titlesent = false; $urlsent = false; $messagesent= false; if($_SERVER['REQUEST_METHOD'] === 'POST'){ $name = htmlentities( $_POST["name1"] ?? ''); $title = htmlentities($_POST["title"] ?? '' ); $URL = ($_POST["url"]??''); $message =htmlentities($_POST["message"] ?? ''); $errors = []; $thanks = false; $formSent = false; $namesent = false; $titlesent = false; $urlsent = false; $messagesent= false; if($name === ''){ $errors[]='Bitte geben Sie einen Namen ein.'; $formSent = true; $namesent = true; } if($title===''){ $errors[]='Bitte geben Sie einen Titel ein. '; $formSent = true; $titlesent = true; } if($URL===''){ $errors='Geben Sie eine URL ein.'; $formSent = true; $urlsent = true; } if($message===''){ $errors='Geben Sie eine Nachricht ein.'; $formSent = true; $messagesent= true; } $user = 'root'; $password = ''; $pdo = new PDO('mysql:host=localhost;dbname=blog', $user, $password, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', ]); if ($formSent===false){ $stmt = $pdo->prepare("INSERT INTO `posts` (created_by,post_title,post_text,post_url) VALUES(:by, :title, :text,:url) "); $stmt->execute([':by' => $name, ':title' => $title, ':text' => $message, ':url' => $URL]); $thanks = true; } } ?> <!DOCTYPE html> <html > <head> <!-- Site made with Mobirise Website Builder v4.11.6, https://mobirise.com --> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="generator" content="Mobirise v4.11.6, mobirise.com"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1"> <link rel="shortcut icon" href="assets/images/logo2.png" type="image/x-icon"> <meta name="description" content="Website Creator Description"> <title>Make Your Own Blog</title> <link rel="stylesheet" href="assets/blog/error_style.css"> <link rel="stylesheet" href="assets/web/assets/mobirise-icons/mobirise-icons.css"> <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/bootstrap/css/bootstrap-grid.min.css"> <link rel="stylesheet" href="assets/bootstrap/css/bootstrap-reboot.min.css"> <link rel="stylesheet" href="assets/tether/tether.min.css"> <link rel="stylesheet" href="assets/dropdown/css/style.css"> <link rel="stylesheet" href="assets/theme/css/style.css"> <link rel="preload" as="style" href="assets/mobirise/css/mbr-additional.css"><link rel="stylesheet" href="assets/mobirise/css/mbr-additional.css" type="text/css"> </head> <body> <section class="menu cid-rJ8cpPvY2x" once="menu" id="menu1-13"> <nav class="navbar navbar-expand beta-menu navbar-dropdown align-items-center navbar-fixed-top navbar-toggleable-sm"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <div class="hamburger"> <span></span> <span></span> <span></span> <span></span> </div> </button> <div class="menu-logo"> <div class="navbar-brand"> <span class="navbar-logo"> <a href="index.php"> <img src="pictures/icon.png" alt="Mobirise" style="height: 3.8rem;"> </a> </span> <span class="navbar-caption-wrap"><a class="navbar-caption text-white display-4" href="index.php">Your Blog</a></span> </div> </div> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav nav-dropdown" data-app-modern-menu="true"><li class="nav-item"> <a class="nav-link link text-white display-4" href="posts.php"> <span class="mbri-search mbr-iconfont mbr-iconfont-btn"></span>Alle Posts </a> </li><li class="nav-item"> <a class="nav-link link text-white display-4" href="index.php"> <span class="mbri-home mbr-iconfont mbr-iconfont-btn"></span>Home</a> </li></ul> <div class="navbar-buttons mbr-section-btn"><a class="btn btn-sm btn-primary display-4" href="blog.php"> <span class="mbri-save mbr-iconfont mbr-iconfont-btn "></span> Make yor own Blog</a></div> </div> </nav> </section> <section class="engine"><a href="">web creation software</a></section><section class="mbr-section fo rm1 cid-rJ8gireKJO" id="form1-14"> <div class="container"> <div class="row justify-content-center"> <div class="title col-12 col-lg-8"> <h2 class="mbr-section-title align-center pb-3 mbr-fonts-style display-2"> Create Your Own Blog </h2> <h3 class="mbr-section-subtitle align-center mbr-light pb-3 mbr-fonts-style display-5"> Schreiben Sie ganz einfach Ihren eigenen Blog </h3> </div> </div> </div> <div class="wrapper"> <?php if ($namesent===true){ echo "Bitte geben Sie einen Namen ein.<br>"; } if ($titlesent=== true){ echo "Bitte geben Sie einen Titel ein.<br>"; } if ($urlsent===true){ echo "Bitte geben Sie eine URL ein.<br>"; } if ($messagesent===true){ echo "Bitte geben Sie eine Nachricht ein.<br><br><br><br>"; } ?> </div> <div class="true"> <?php if ($thanks===true){ echo "Danke für deinen Eintrag.<br><br><br><br>"; } ?> </div> <div class="container"> <div class="row justify-content-center"> <div class="media-container-column col-lg-8" data-form-type="formoid"> <!---Formbuilder Form---> <form action="blog.php" method="POST"> <div class="row"> <div hidden="hidden" data-form-alert="" class="alert alert-success col-12">Vielen Dank! Ihre Nachricht wurde verschickt!</div> <div hidden="hidden" data-form-alert-danger="" class="alert alert-danger col-12"> </div> </div> <div class="dragArea row"> <div class="col-md-4 form-group" data-for="name"> <label for="name-form1-a" class="form-control-label mbr-fonts-style display-7">Name</label> <input type="text" name="name1" data-form-field="Name"class="form-control display-7" id="name-form1-a"> </div> <div class="col-md-4 form-group" data-for="email"> <label for="email-form1-a" class="form-control-label mbr-fonts-style display-7">Titel Ihres Beitrags</label> <input type="text" name="title" data-form-field="title"class="form-control display-7" id="email-form1-a"> </div> <div class="col-md-4 form-group" data-for="url"> <label for="name-form1-a" class="form-control-label mbr-fonts-style display-7">Bild URL</label> <input type="text" name="url" data-form-field="url"class="form-control display-7" id="name-form1-a"> </div> <div data-for="message" class="col-md-12 form-group"> <label for="message-form1-a" class="form-control-label mbr-fonts-style display-7">Ihr Beitrag</label> <textarea name="message" data-form-field="Message" class="form-control display-7" id="message-form1-a"></textarea> </div> <div class="col-md-12 input-group-btn align-center"> <button type="submit" href="landing_page.php"class="btn btn-primary btn-form display-4">Veröffentlichen</button> </div> </div> </form><!---Formbuilder Form---> </div> </div> </div> </section> <script src="assets/web/assets/jquery/jquery.min.js"></script> <script src="assets/popper/popper.min.js"></script> <script src="assets/bootstrap/js/bootstrap.min.js"></script> <script src="assets/tether/tether.min.js"></script> <script src="assets/smoothscroll/smooth-scroll.js"></script> <script src="assets/dropdown/js/nav-dropdown.js"></script> <script src="assets/dropdown/js/navbar-dropdown.js"></script> <script src="assets/touchswipe/jquery.touch-swipe.min.js"></script> <script src="assets/theme/js/script.js"></script> </body> </html> <file_sep>/posts.php <?php $user = 'root'; $password = ''; $pdo = new PDO('mysql:host=localhost;dbname=blog', $user, $password, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', ]); ?> <!DOCTYPE html> <html> <head> <!-- Site made with Mobirise Website Builder v4.11.6, https://mobirise.com --> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="generator" content="Mobirise v4.11.6, mobirise.com"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1"> <link rel="shortcut icon" href="assets/images/logo2.png" type="image/x-icon"> <meta name="description" content="Website Creator Description"> <title>Make Your Own Blog</title> <link rel="stylesheet" href="assets/posts/post_style187.css"> <link rel="stylesheet" href="assets/web/assets/mobirise-icons/mobirise-icons.css"> <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/bootstrap/css/bootstrap-grid.min.css"> <link rel="stylesheet" href="assets/bootstrap/css/bootstrap-reboot.min.css"> <link rel="stylesheet" href="assets/tether/tether.min.css"> <link rel="stylesheet" href="assets/dropdown/css/style.css"> <link rel="stylesheet" href="assets/theme/css/style.css"> <link rel="preload" as="style" href="assets/mobirise/css/mbr-additional.css"><link rel="stylesheet" href="assets/mobirise/css/mbr-additional.css" type="text/css"> </head> <body> <section class="menu cid-rJ8cpPvY2x" once="menu" id="menu1-13"> <nav class="navbar navbar-expand beta-menu navbar-dropdown align-items-center navbar-fixed-top navbar-toggleable-sm"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <div class="hamburger"> <span></span> <span></span> <span></span> <span></span> </div> </button> <div class="menu-logo"> <div class="navbar-brand"> <span class="navbar-logo"> <a href="index.php"> <img src="pictures/icon.png" alt="Mobirise" style="height: 3.8rem;"> </a> </span> <span class="navbar-caption-wrap"><a class="navbar-caption text-white display-4" href="index.php">Your Blog</a></span> </div> </div> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav nav-dropdown" data-app-modern-menu="true"><li class="nav-item"> <a class="nav-link link text-white display-4" href="posts.php"> <span class="mbri-search mbr-iconfont mbr-iconfont-btn"></span>Alle Posts </a> </li><li class="nav-item"> <a class="nav-link link text-white display-4" href="index.php"> <span class="mbri-home mbr-iconfont mbr-iconfont-btn"></span>Home</a> </li></ul> <div class="navbar-buttons mbr-section-btn"><a class="btn btn-sm btn-primary display-4" href="blog.php"> <span class="mbri-save mbr-iconfont mbr-iconfont-btn "></span> Make yor own Blog</a></div> </div> </nav> </section> <br> <br> <br> <br> <?php $stmt = $pdo->query('SELECT * FROM `posts` ORDER BY id DESC limit 2000'); $all = $stmt->fetchAll(); ?> <?php foreach($all as $zeile): ?> <div class= jeje> <h1 class="titel"><?= $zeile["post_title"]?></h1><br> <img class="bild" src="<?= $zeile["post_url"];?>"> <br> <br> <div class="message"> <p class="text"> <?= $zeile["post_text"];?></p> </div> <br> <p class="name">Erstellt von: <?= $zeile["created_by"];?></p> <br> <p class="datum">Erstellt am: <?= $zeile["created_at"];?></p> <br> </div> <?php endforeach ?> </body> </html>
d471cc31382c16252f3d0aa12f1b0b829032822b
[ "PHP" ]
2
PHP
EriN-B/PHP-Blog
c8d89f177c290a1b5ff697252abd44c91ae78599
28464ec713dd55022fc9e2a77c788af4b0d53cd6
refs/heads/master
<file_sep>import React from 'react' import './App.css' export default function People (props) { return( <div className='people-card'> <img src={`https://robohash.org/${props.data.name}`} alt=""/> <h2>Name:{props.data.name}, Gender:{props.data.gender}</h2> <h2>"{props.data.catchphrase}"</h2> <h3>From:{props.data.city}, {props.data.country}</h3> <h4>Favorite Movie:{props.data.favorite_movie}</h4> <h4>{props.data.movie_genre}</h4> </div> ) }<file_sep>import React, { Component } from "react"; import "./App.css"; import axios from "axios"; import People from "./People"; class App extends Component { constructor() { super(); this.state = { people: [], country: "", genre: "" }; } countryChange(e) { this.setState({ country: e }); } genreChange(e) { this.setState({ genre: e }); } getAllPeople() { axios .get(`/api/people`) .then(res => this.setState({ people: res.data })) .catch(err => { alert("could not find people"); }); } getFemales() { axios .get(`/api/people/females`) .then(res => this.setState({ people: res.data })) .catch(err => { alert("could not find only females"); }); } getMales() { axios .get(`/api/people/males`) .then(res => this.setState({ people: res.data })) .catch(err => { alert("could not find only males"); }); } searchByCountry(count) { axios .get(`/api/people/country?count=${count}`) .then(res => this.setState({ people: res.data })) .catch(err => { alert("cannot search by country"); }); } searchByGenre(gen) { axios .get(`/api/people/genre?gen=${gen}`) .then(res => this.setState({ people: res.data })) .catch(err => { alert("cannot search by genre"); }); } render() { console.log(this.state.country); return ( <div className="outer-app"> <div className="nav"> <button onClick={() => this.getAllPeople()}>Get All People</button> <button onClick={() => this.getFemales()}>Females</button> <button onClick={() => this.getMales()}>Males</button> <div> <input value={this.state.country} onChange={e => this.countryChange(e.target.value)} type="text" placeholder="...type a country" /> <button onClick={e => { this.searchByCountry(this.state.country); this.setState({ country: "" }); }} > Submit Country </button> </div> <div> <input value={this.state.genre} onChange={e => this.genreChange(e.target.value)} type="text" placeholder="...type a movie genre" /> <button onClick={e => { this.searchByGenre(this.state.genre); this.setState({ genre: "" }); }} > Submit Genre </button> </div> </div> <div className="App"> {this.state.people.map(el => ( <People key={el.id} data={el} /> ))} </div> </div> ); } } export default App; <file_sep>const people = require('./data') module.exports = { getAllPeople(req, res, next) { // console.log(people) res.status(200).send(people) }, getAllFemales(req, res, next) { let females = people.filter(el => { return (el.gender === "F") }) // console.log(females) res.status(200).send(females) }, getAllMales(req, res, next) { let males = people.filter(el => { return (el.gender === "M") }) // console.log(males) res.status(200).send(males) }, getPeopleByCountry(req, res, next) { // console.log(req.query) const {count} = req.query let countries = people.filter(el => { return el.country.toLowerCase().includes(count.toLowerCase()) }) res.status(200).send(countries) // console.log(countries) }, getPeopleByGenre(req, res, next) { console.log(req.query) const {gen} = req.query let genres = people.filter(el => { return el.movie_genre.toLowerCase().includes(gen.toLowerCase()) }) res.status(200).send(genres) console.log(genres) } }
ff220e706c1ee0d21d5d8ba90fcb551d82317406
[ "JavaScript" ]
3
JavaScript
jnjagod/wlh12-node1-review
a382397ce5b29093661bd0ecd2569b0ae7120114
54eb0b25846e77d1124d0c00aa9336a2640cfed6
refs/heads/master
<file_sep>ajshfdhjg asdgasv ugasdasf asdyugrtgglvdf sdfiusgdffsdf
ece3a832df4b0f299c2f76db589bb696f5aaa33f
[ "Python" ]
1
Python
ducpv-1644/testappproject
7141cef9337fc4bd730ea5f5c3e7a2b61e5f08ae
f0068ad07c0a07e6d29bcb344a04d8701e04bc94
refs/heads/master
<file_sep>package com.example.prathabodas.cupertinoconnect; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; /** * Created by prathabodas on 4/8/17. */ public class MainActivity extends Activity { protected void onCreate(Bundle icicle) { super.onCreate(icicle); final Button go = (Button)findViewById(R.id.go); go.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent(MainActivity.this, MapActivity.class)); } }); } }
f39db1f1b2560221cb173cf08e73d5ad10929057
[ "Java" ]
1
Java
nathan-149/CupertinoConnect
1adaddffba6e603ee0aaa8a562c03ce22719bd4a
25a23d679304c289dc35c0e7677fc8d075f06a2d
refs/heads/master
<repo_name>pilotak/wisol<file_sep>/README.md # Mbed Wisol library [![Framework Badge mbed](https://img.shields.io/badge/framework-mbed-008fbe.svg)](https://os.mbed.com/) Mbed library for Wisol WSSFM10 SigFox modem ## Example ```cpp #include "mbed.h" #include "Wisol.h" Wisol wisol(PC_4, PC_5); int main() { if (!wisol.init()) { printf("Could not init"); return 0; } uint8_t data[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}; if (wisol.sendFrame(data, sizeof(data))) { printf("Message sent!\n"); } else { printf("Sending message failed\n"); } return 0; } ``` ## Detailed example `mbed_app.json` ```json { "config": { "trace-level": { "help": "Options are TRACE_LEVEL_ERROR,TRACE_LEVEL_WARN,TRACE_LEVEL_INFO,TRACE_LEVEL_DEBUG", "macro_name": "MBED_TRACE_MAX_LEVEL", "value": "TRACE_LEVEL_DEBUG" } }, "target_overrides": { "*": { "mbed-trace.enable": true, "target.printf_lib": "std" } } } ``` `main.cpp` ```cpp #include "mbed.h" #include "Wisol.h" #if MBED_CONF_MBED_TRACE_ENABLE #include "mbed-trace/mbed_trace.h" static Mutex trace_mutex; static void trace_wait() { trace_mutex.lock(); } static void trace_release() { trace_mutex.unlock(); } void trace_init() { mbed_trace_init(); mbed_trace_mutex_wait_function_set(trace_wait); mbed_trace_mutex_release_function_set(trace_release); } #endif Wisol wisol(PC_4, PC_5); int main() { #if MBED_CONF_MBED_TRACE_ENABLE trace_init(); #endif uint8_t data[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}; uint8_t id[SIGFOX_ID_LENGTH]; uint8_t pac[SIGFOX_PAC_LENGTH]; if (!wisol.init(true)) { printf("Could not init"); return 0; } wisol.getId(id); wisol.getPac(pac); wisol.setTransmitRepeat(2); wisol.sendFrame(data, sizeof(data)); wisol.getTemperature(nullptr); wisol.getVoltage(nullptr, nullptr); if (wisol.setPowerMode(Wisol::Sleep)) { ThisThread::sleep_for(5s); wisol.sendBreak(); while (!wisol.init(true)) { ThisThread::sleep_for(250ms); } } wisol.reset(); return 0; } ``` <file_sep>/Wisol.h /* MIT License Copyright (c) 2020 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef WISOL_H #define WISOL_H #include "mbed.h" #include "mbed-trace/mbed_trace.h" #ifndef TRACE_GROUP #define TRACE_GROUP "WISL" #endif #define SIGFOX_ID_LENGTH 4 #define SIGFOX_PAC_LENGTH 8 #define SIGFOX_MAX_DATA_LENGTH 12 class Wisol { public: Wisol(PinName tx, PinName rx); ~Wisol(); typedef enum { Reset = 0, Sleep, DeepSleep } power_mode_t; /** * @brief Initializes library and checks communication with the modem * * @param debug enable/disable AT commands printout * @return success/failure */ bool init(bool debug = false); /** * @brief Get an ID - 4 bytes * * @param id * @return success/failure */ bool getId(uint8_t *id); /** * @brief Get a PAC number - 8 bytes * * @param pac pointer where to copy * @return success/failure */ bool getPac(uint8_t *pac); /** * @brief Set a power mode * * @see power_mode_t * * @param mode any value from power_mode_t * @return success/failure */ bool setPowerMode(power_mode_t mode); /** * @brief Software reset * * @return success/failure */ bool reset(); /** * @brief Send a break condition for wake up after sleep (not deep sleep!) * */ void sendBreak(); /** * @brief Send a bit * * @param bit to send * @param downlink point to downlink response should you need * @return success/failure */ bool sendBit(bool bit, char *downlink = nullptr); /** * @brief Send a data buffer * * @param data pointer to a data buffer * @param length length of data * @param downlink pointer to a downlink data buffer, should you need * @return success/failure */ bool sendFrame(const void *data, size_t length, char *downlink = nullptr); /** * @brief Get a temperature (result in 1/10th °C) * * @param temperature pointer to where to copy the temperature * @return success/failure */ bool getTemperature(int *temperature); /** * @brief Get a voltage (result in mV) * * @param current pointer to where to copy current voltage * @param last pointer to where to copy voltage during last transmission * @return true * @return false */ bool getVoltage(int *current, int *last); /** * @brief Sets transmit repeat * * @param repeats number or repeats (default: 2) * @return success/failure */ bool setTransmitRepeat(uint8_t repeats); private: BufferedSerial _serial; ATCmdParser *_parser; // this will force parser to be in RAM instead of HEAP uint32_t parser_buffer[sizeof(ATCmdParser) / sizeof(uint32_t)]; const char hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; }; #endif // WISOL_H <file_sep>/Wisol.cpp /* MIT License Copyright (c) 2020 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Wisol.h" Wisol::Wisol(PinName tx, PinName rx): _serial(tx, rx, 9600) { } Wisol::~Wisol() { if (_parser == reinterpret_cast<ATCmdParser *>(parser_buffer)) { _parser->~ATCmdParser(); } } bool Wisol::init(bool debug) { tr_debug("Init"); if (_parser == reinterpret_cast<ATCmdParser *>(parser_buffer)) { _parser->~ATCmdParser(); } _parser = new (parser_buffer) ATCmdParser(&_serial, "\r", 256, MBED_CONF_WISOL_TIMEOUT, debug); _parser->send("AT"); bool res = _parser->recv("OK\n"); if (res) { tr_info("Alive"); } else { tr_error("No response"); } return res; } bool Wisol::getPac(uint8_t *pac) { uint16_t data[SIGFOX_PAC_LENGTH] = {0}; tr_debug("Getting PAC"); _parser->send("AT$I=11"); bool ok = _parser->recv("%02hX%02hX%02hX%02hX%02hX%02hX%02hX%02hX\n", &data[0], &data[1], &data[2], &data[3], &data[4], &data[5], &data[6], &data[7]); if (!ok) { tr_error("Couldn't parse string"); return false; } for (auto i = 0; i < SIGFOX_PAC_LENGTH; i++) { pac[i] = (uint8_t)data[i]; } tr_info("PAC: %s", tr_array(pac, SIGFOX_PAC_LENGTH)); return true; } bool Wisol::getId(uint8_t *id) { uint16_t data[SIGFOX_ID_LENGTH] = {0}; tr_debug("Getting ID"); _parser->send("AT$I=10"); bool ok = _parser->recv("%02hX%02hX%02hX%02hX\n", &data[0], &data[1], &data[2], &data[3]); if (!ok) { tr_error("Couldn't parse string"); return false; } for (auto i = 0; i < SIGFOX_ID_LENGTH; i++) { id[i] = (uint8_t)data[i]; } tr_info("ID: %s", tr_array(id, SIGFOX_ID_LENGTH)); return true; } bool Wisol::setPowerMode(power_mode_t mode) { tr_debug("Setting power mode: %u", mode); _parser->send("AT$P=%u", mode); return _parser->recv("OK\n"); } bool Wisol::reset() { return setPowerMode(Reset); } void Wisol::sendBreak() { // pseudo break, because _serial.send_break() is private _parser->putc(0xFF); } bool Wisol::sendBit(bool bit, char *downlink) { tr_debug("Sending bit: %u%s", bit, (downlink != nullptr ? ", expecting a downlink" : "")); // set longer timeout _parser->set_timeout(MBED_CONF_WISOL_EXTENDED_TIMEOUT); _parser->send("AT$SB=%u,%u", bit, (downlink != nullptr ? 1 : 0)); bool res = _parser->recv("OK\n"); if (downlink != nullptr) { tr_debug("Waiting for downlink"); res = _parser->recv("RX=%[^\n]", downlink); if (res) { tr_info("Response: %s", downlink); } else { tr_error("No response"); } } // restore timeout _parser->set_timeout(MBED_CONF_WISOL_TIMEOUT); return res; } bool Wisol::sendFrame(const void *data, size_t length, char *downlink) { bool res = false; if (data == nullptr || length == 0 || length > SIGFOX_MAX_DATA_LENGTH) { return res; } auto *buffer = reinterpret_cast<const uint8_t *>(data); tr_debug("Sending frame[%u]: %s%s", length, tr_array(buffer, length), (downlink != nullptr ? ", expecting a downlink" : "")); // set longer timeout _parser->set_timeout(MBED_CONF_WISOL_EXTENDED_TIMEOUT); _parser->write("AT$SF=", 6); // convert buffer to ASCII for (size_t i = 0; i < length; i++) { _parser->putc(hex_chars[(buffer[i] & 0xF0) >> 4 ]); _parser->putc(hex_chars[(buffer[i] & 0x0F) >> 0 ]); } if (downlink != nullptr) { _parser->send(",1"); if (_parser->recv("OK\n")) { tr_info("Sent"); tr_debug("Waiting for downlink"); res = _parser->recv("RX=%[^\n]", downlink); if (res) { tr_info("Response: %s", downlink); } else { tr_error("No response"); } } } else { _parser->putc('\r'); res = _parser->recv("OK\n"); if (res) { tr_info("Sent"); } } if (!res) { tr_error("Sending failed"); } // restore timeout _parser->set_timeout(MBED_CONF_WISOL_TIMEOUT); return res; } bool Wisol::setTransmitRepeat(uint8_t repeats) { tr_debug("Setting transmit repeat: %u", repeats); _parser->send("AT$TR=%u", repeats); if (!_parser->recv("OK\n")) { return false; } // get transmit repeat to compare _parser->send("AT$TR?"); int data; bool ok = _parser->recv("%u\n", &data); if (!ok || data != repeats) { return false; } return true; } bool Wisol::getTemperature(int *temperature) { tr_debug("Getting temperature"); int temp; _parser->send("AT$T?"); bool ok = _parser->recv("%d\n", &temp); if (!ok) { return false; } tr_info("Temperature: %d", temp); if (temperature) { *temperature = temp; } return true; } bool Wisol::getVoltage(int *current, int *last) { tr_debug("Getting voltage"); int voltage[2]; _parser->send("AT$V?"); // first response is current voltage bool ok = _parser->recv("%d\n", &voltage[0]); if (!ok) { return false; } // second response is during last transmission ok = _parser->recv("%d\n", &voltage[1]); if (!ok) { return false; } tr_info("Voltage: %d, %d", voltage[0], voltage[1]); if (current) { *current = voltage[0]; } if (last) { *last = voltage[1]; } return true; }
8c30c1ae46775172de734978de61879eeafe2b16
[ "Markdown", "C++" ]
3
Markdown
pilotak/wisol
2bd4a2910328f4d17252d880252e229c064c73dc
98ab6b5ef3a7709afb12200fed0858e58b1f79fc
refs/heads/master
<file_sep>const program = require('commander'); const { prompt } = require('inquirer'); const { cluePrompt } = require('./prompts'); const { crosswordHeavenSearch, nexusSearch, } = require('./search'); const SEARCH_WHITELIST = [ crosswordHeavenSearch, nexusSearch, ]; const resolveSearches = (clue, pattern = '') => Promise.all( SEARCH_WHITELIST.map(searchFn => searchFn(clue, pattern)) ); program .version('0.0.1') .description('Crossword Helper'); program .command('clue') .alias('c') .description('search matching clues') .action(() => { // only prompt if no args are passed // assumes cw="node index.js clue" alias has been set if (process.argv[3]) { resolveSearches(process.argv.slice(3).join(' ')); } else { prompt(cluePrompt) .then(({ clue, pattern }) => resolveSearches(clue, pattern)); } }); program.parse(process.argv); <file_sep>const fetch = require('isomorphic-fetch'); const { URL } = require('url'); const { CROSSWORD_HEAVEN_URL, NEXUS_URL, } = require('./constants'); const searchClueFactory = (siteName, urlBuilder, htmlParser) => async (clue, pattern) => { const borderString = Array(siteName.length + 1).join('-'); const answers = await fetch(urlBuilder(clue, pattern)) .then(res => res.text()) .then(htmlParser) .catch(console.error); console.log(borderString); console.log(siteName); console.log(borderString); console.log(answers.join('\n').toUpperCase(), '\n'); }; const crosswordHeavenURLBuilder = (clue, pattern) => { const url = new URL(CROSSWORD_HEAVEN_URL); url.searchParams.append('clue', clue); url.searchParams.append('answer', pattern); return url.href; }; const crosswordHeavenHTMLParser = html => html.match(/(?<=href="\/words\/)(\w+)/gmi) || []; const crosswordHeavenSearch = searchClueFactory( 'Crossword Heaven', crosswordHeavenURLBuilder, crosswordHeavenHTMLParser ); const nexusURLBuilder = (clue, pattern) => { const url = new URL(NEXUS_URL); url.searchParams.append('clue', clue); url.searchParams.append('pattern', pattern); return url.href; }; const nexusHTMLParser = html => html.match(/(?<=href="\/word\/)(\w+)/gmi) || []; const nexusSearch = searchClueFactory( 'Nexus', nexusURLBuilder, nexusHTMLParser ); module.exports = { crosswordHeavenSearch, nexusSearch, };
edebcb8bc7ebf513f245d55603f2a758dd87246c
[ "JavaScript" ]
2
JavaScript
amdilley/cw-helper
d5fb9399fe7163019ebc33d67376a959c1e7225b
a9cfd70f09acaf446b02fc2b1f79a24f5b978f17
refs/heads/master
<repo_name>suzukiken/cdk-ec2-qmk<file_sep>/lib/cdk-ec2-qmk-secgrp-ec2-stack.ts import * as cdk from '@aws-cdk/core'; import * as ec2 from '@aws-cdk/aws-ec2'; export class CdkEc2QmkSecgrpEc2Stack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const vpc_id = this.node.tryGetContext('vpc_id') const vpc_name = this.node.tryGetContext('vpc_name') const alb_arn = this.node.tryGetContext('alb_arn') const vpc = ec2.Vpc.fromLookup(this, 'Vpc', { vpcId: vpc_id, vpcName: vpc_name }) const security_group = new ec2.SecurityGroup(this, 'Ec2SecurityGrp', { vpc: vpc, allowAllOutbound: true }) security_group.addIngressRule(ec2.Peer.ipv4('10.0.0.0/16'), ec2.Port.tcp(80)) security_group.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(80)) new cdk.CfnOutput(this, 'Ec2SecGrpOutput', { exportName: this.node.tryGetContext('ec2standalone_securitygroupid_exportname'), value: security_group.securityGroupId }) } } <file_sep>/userdata/tornado_server.py import tornado.ioloop import tornado.web from tornado.log import enable_pretty_logging, app_log, access_log, gen_log import logging import os import boto3 import json import subprocess import zipfile import shutil from pathlib import Path client = boto3.client('s3') port = int(os.environ.get('PORT', '80')) log_file = os.environ.get('LOG_FILE') qmk_dir = os.environ.get('QMK_DIR') if log_file: handler = logging.FileHandler(log_file) enable_pretty_logging() app_log.addHandler(handler) access_log.addHandler(handler) gen_log.addHandler(handler) class IndexHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, I am Tornado.") class GenByZipHandler(tornado.web.RequestHandler): def get(self): app_log.info(self.request.body) zip_filepath = '/tmp/upload.zip' target_dirpath = 'keyboards' build_dirpath = '.build' keyboard_name = None with open(zip_filepath, 'wb') as zip_ref: zip_ref.write(self.request.body) with zipfile.ZipFile(zip_filepath, 'r') as zip_ref: app_log.info(zip_ref.namelist()) # ['suzuki/', 'suzuki/config.h', ....] keyboard_name = zip_ref.namelist()[0].replace('/', '') app_log.info(keyboard_name) zip_ref.extractall(target_dirpath) if not keyboard_name: self.write('no name') make_result = subprocess.run( ['make {}:default'.format(keyboard_name)], capture_output=True, text=True, shell=True, ) app_log.info(make_result.stdout) app_log.info(make_result.stderr) filename = '{}_default.hex'.format(keyboard_name) self.set_header('Content-Type', 'application/octet-stream') self.set_header('Content-Disposition', 'attachment; filename=' + filename) self.write(open(filename, 'rb').read()) os.remove(filename) shutil.rmtree(os.path.join(target_dirpath, keyboard_name), ignore_errors=True) for path in Path(build_dirpath).glob('*'): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(path) def make_app(): return tornado.web.Application([ (r"/", IndexHandler), (r"/genbyzip/", GenByZipHandler) ]) if __name__ == "__main__": app = make_app() app.listen(port) tornado.ioloop.IOLoop.current().start()<file_sep>/lib/cdk-ec2-qmk-function-stack.ts import * as cdk from '@aws-cdk/core'; import * as s3 from '@aws-cdk/aws-s3'; import * as lambda from '@aws-cdk/aws-lambda'; import { PythonFunction } from "@aws-cdk/aws-lambda-python"; export class CdkEc2QmkFunctionStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const bucketname = cdk.Fn.importValue(this.node.tryGetContext('bucketname_exportname')) const bucket = s3.Bucket.fromBucketName(this, 'Bucket', bucketname) const hostip = cdk.Fn.importValue(this.node.tryGetContext('ec2_publicip_exportname')) /* const vpc_id = this.node.tryGetContext('vpc_id') const vpc_name = this.node.tryGetContext('vpc_name') const vpc = ec2.Vpc.fromLookup(this, 'Vpc', { vpcId: vpc_id, vpcName: vpc_name }) const securitygroup_id = cdk.Fn.importValue(this.node.tryGetContext('vpclambda_securitygroupid_exportname')) const subnet_id = cdk.Fn.importValue(this.node.tryGetContext('public_subnetid_exportname')) const subnet = ec2.Subnet.fromSubnetId(this, 'Subnet', subnet_id) */ const lambda_function = new PythonFunction(this, "CompilerCallerFunction", { entry: "lambda", index: "caller.py", handler: "lambda_handler", runtime: lambda.Runtime.PYTHON_3_8, timeout: cdk.Duration.seconds(60), environment: { BUCKET_NAME: bucket.bucketName, KEY_PREFIX: 'keyboards', QMK_URL: 'http://' + hostip + '/' }, /* vpc: vpc, vpcSubnets: { subnets: [ subnet ] }, securityGroup: ec2.SecurityGroup.fromSecurityGroupId(this, 'LambdaSecurityGrp', securitygroup_id) */ }) bucket.grantReadWrite(lambda_function) } } <file_sep>/lambda/caller.py # -*- coding: utf-8 -*- import boto3 import json import os from botocore.config import Config import urllib.request ''' このpythonが行うこと Qmkのコンパイラが必要とするキーボードの情報を生成してS3バケットに置く Qmkのコンパイラが乗っているEC2のインスタンスにhttp経由でコンパイルを要求する この要求の際にS3に置いたデータのキーをhttpのペイロードに付加する。 EC2はコンパイル結果をS3に置き、コンパイルが完了したこと通知するレスポンスを返す。 ''' BUCKET_NAME = os.environ.get('BUCKET_NAME') KEY_PREFIX = os.environ.get('KEY_PREFIX') QMK_URL = os.environ.get('QMK_URL') def lambda_handler(event, context): print(event) ''' event { "keyboard": "2key2crawl/info.json", "keymap": "default" } ''' print(os.environ) req = urllib.request.Request(QMK_URL, data=json.dumps({}).encode("utf-8"), method='GET') f = urllib.request.urlopen(req) print(f.read().decode('utf-8')) client = boto3.client('s3') response = client.get_object( Bucket=BUCKET_NAME, Key=KEY_PREFIX + '/' + event.get('keyboard', '2key2crawl') ) print(response['Body'].read().decode('utf-8'))<file_sep>/lib/cdk-ec2-qmk-ec2-stack.ts import * as cdk from '@aws-cdk/core'; import * as ec2 from '@aws-cdk/aws-ec2'; import * as iam from '@aws-cdk/aws-iam'; import * as assets from '@aws-cdk/aws-s3-assets'; import * as s3 from '@aws-cdk/aws-s3'; import * as path from 'path' export class CdkEc2QmkEc2Stack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const vpc_id = this.node.tryGetContext('vpc_id') const vpc_name = this.node.tryGetContext('vpc_name') const ami_id = this.node.tryGetContext('base_ami_id') const key_name = this.node.tryGetContext('key_name') const securitygroup_id = cdk.Fn.importValue(this.node.tryGetContext('ec2standalone_securitygroupid_exportname')) const bucketname = cdk.Fn.importValue(this.node.tryGetContext('bucketname_exportname')) const vpc = ec2.Vpc.fromLookup(this, 'Vpc', { vpcId: vpc_id, vpcName: vpc_name }) const bucket = s3.Bucket.fromBucketName(this, 'Bucket', bucketname) const asset = new assets.Asset(this, 'UserdataAsset', { path: path.join(__dirname, '..', 'userdata'), }) const userData = ec2.UserData.forLinux() userData.addCommands('apt update') // userData.addCommands('apt upgrade -y') userData.addCommands('apt install unzip -y') userData.addCommands('apt install python3-pip -y') userData.addCommands('curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"') userData.addCommands('unzip awscliv2.zip') userData.addCommands('./aws/install') userData.addCommands( cdk.Fn.join(" ", [ 'aws s3api get-object --bucket', asset.s3BucketName, '--key', asset.s3ObjectKey, '/tmp/userdata.zip' ]) ) userData.addCommands('unzip /tmp/userdata.zip') userData.addCommands('chmod +x initialize.sh') userData.addCommands('./initialize.sh') const linux = ec2.MachineImage.genericLinux({ 'ap-northeast-1': ami_id }) const role = new iam.Role(this, "Role", { assumedBy: new iam.ServicePrincipal("ec2.amazonaws.com"), managedPolicies: [ iam.ManagedPolicy.fromAwsManagedPolicyName( "CloudWatchAgentServerPolicy", ) ] }) const instance = new ec2.Instance(this, 'Instance', { vpc: vpc, machineImage: linux, instanceType: new ec2.InstanceType('t3.nano'), role: role, keyName: key_name, userData: userData, securityGroup: ec2.SecurityGroup.fromSecurityGroupId(this, 'Ec2SecurityGrp', securitygroup_id) }) asset.grantRead( instance.role ) bucket.grantReadWrite( instance.role ) new cdk.CfnOutput(this, 'PrivateIp', { exportName: this.node.tryGetContext('ec2_privateip_exportname'), value: instance.instancePrivateIp }) new cdk.CfnOutput(this, 'PublicIp', { exportName: this.node.tryGetContext('ec2_publicip_exportname'), value: instance.instancePublicIp }) } } <file_sep>/sample/suzuki/keymaps/default/keymap.c #include QMK_KEYBOARD_H #include "keymap.h" const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = { [0] = LAYOUT( \ KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, \ KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, \ KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, \ KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, \ KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, \ KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, \ KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, \ KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, \ KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, \ KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0 \ ) }; const macro_t *action_get_macro(keyrecord_t *record, uint8_t id, uint8_t opt) { keyevent_t event = record->event; (void)event; switch (id) { } return MACRO_NONE; } bool process_record_user(uint16_t keycode, keyrecord_t *record) { return true; } <file_sep>/sample/suzuki/suzuki.c #include "suzuki.h" <file_sep>/test/tornado_client_index.py import os import urllib.request EC2_PRIVATE_URL = os.environ.get('EC2_PRIVATE_URL') req = urllib.request.Request( url=EC2_PRIVATE_URL + '/', method='GET' ) response = urllib.request.urlopen(req) print(response.read().decode('utf-8'))<file_sep>/lib/cdk-ec2-qmk-secgrp-lbtgt-stack.ts import * as cdk from '@aws-cdk/core'; import * as ec2 from '@aws-cdk/aws-ec2'; export class CdkEc2QmkSecgrpLbtgtStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const vpc_id = this.node.tryGetContext('vpc_id') const vpc_name = this.node.tryGetContext('vpc_name') const lb_securitygroup_id = cdk.Fn.importValue(this.node.tryGetContext('lb_securitygroupid_exportname')) const vpc = ec2.Vpc.fromLookup(this, 'Vpc', { vpcId: vpc_id, vpcName: vpc_name }) const lb_security_group = ec2.SecurityGroup.fromSecurityGroupId(this, 'LbSecurityGrp', lb_securitygroup_id) const target_security_group = new ec2.SecurityGroup(this, 'Ec2SecurityGrp', { vpc: vpc, allowAllOutbound: true }) target_security_group.addIngressRule(lb_security_group, ec2.Port.tcp(80)) new cdk.CfnOutput(this, 'TargetSecGrpOutput', { exportName: this.node.tryGetContext('lbtarget_securitygroupid_exportname'), value: target_security_group.securityGroupId }) } } <file_sep>/sample/suzuki/config.h #ifndef CONFIG_H #define CONFIG_H #include "config_common.h" /* USB Device descriptor parameter */ #define VENDOR_ID 0xFEED #define PRODUCT_ID 0x0310 #define DEVICE_VER 0x0001 #define MANUFACTURER <NAME> #define PRODUCT SUZUKI #define DESCRIPTION A 100 key keyboard /* key matrix size */ #define MATRIX_ROWS 10 #define MATRIX_COLS 10 /* key matrix pins */ #define MATRIX_ROW_PINS { C4, C5, C6, C7, B5, B7, B6, B4, B3, B2 } #define MATRIX_COL_PINS { C2, D0, D1, D2, D3, D4, D5, D6, B0, B1 } #define UNUSED_PINS /* COL2ROW or ROW2COL */ #define DIODE_DIRECTION COL2ROW /* Set 0 if debouncing isn't needed */ #define DEBOUNCING_DELAY 5 /* Mechanical locking support. Use KC_LCAP, KC_LNUM or KC_LSCR instead in keymap */ #define LOCKING_SUPPORT_ENABLE /* Locking resynchronize hack */ #define LOCKING_RESYNC_ENABLE /* key combination for command */ #define IS_COMMAND() ( \ keyboard_report->mods == (MOD_BIT(KC_LSHIFT) | MOD_BIT(KC_RSHIFT)) \ ) /* prevent stuck modifiers */ #define PREVENT_STUCK_MODIFIERS #endif<file_sep>/lib/cdk-ec2-qmk-autoscaling-stack.ts import * as cdk from '@aws-cdk/core'; import * as ec2 from '@aws-cdk/aws-ec2'; import * as iam from '@aws-cdk/aws-iam'; import * as autoscaling from '@aws-cdk/aws-autoscaling'; import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2'; import * as route53 from '@aws-cdk/aws-route53'; import * as targets from '@aws-cdk/aws-route53-targets/lib'; export class CdkEc2QmkAutoscalingStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const vpc_id = this.node.tryGetContext('vpc_id') const vpc_name = this.node.tryGetContext('vpc_name') const securitygroup_id = cdk.Fn.importValue(this.node.tryGetContext('lbtarget_securitygroupid_exportname')) const alb_arn = this.node.tryGetContext('alb_arn') const ami_id = this.node.tryGetContext('private_ami_id') const domain = this.node.tryGetContext('domain') const subdomain = this.node.tryGetContext('subdomain') const host = subdomain + '.' + domain const vpc = ec2.Vpc.fromLookup(this, 'Vpc', { vpcId: vpc_id, vpcName: vpc_name }) const security_group = ec2.SecurityGroup.fromSecurityGroupId(this, 'Ec2SecurityGrp', securitygroup_id) const linux = ec2.MachineImage.genericLinux({ 'ap-northeast-1': ami_id }) const role = new iam.Role(this, "Role", { assumedBy: new iam.ServicePrincipal("ec2.amazonaws.com"), managedPolicies: [ iam.ManagedPolicy.fromAwsManagedPolicyName( "CloudWatchAgentServerPolicy", ) ] }) const asgrop = new autoscaling.AutoScalingGroup(this, 'ASG', { vpc, instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.NANO), machineImage: linux, securityGroup: security_group, role: role, minCapacity: 1, maxCapacity: 1 }) const alb = elbv2.ApplicationLoadBalancer.fromLookup(this, 'Alb', { loadBalancerArn: alb_arn }) const listener = elbv2.ApplicationListener.fromLookup(this, 'HttpsListener', { listenerArn: this.node.tryGetContext('alb_https_listener_arn') }) const targetGroup = new elbv2.ApplicationTargetGroup(this, 'TargetGroup', { port: 80, targets: [asgrop], vpc: vpc }) listener.addTargetGroups('Groups', { targetGroups: [targetGroup], conditions: [ elbv2.ListenerCondition.hostHeaders([host]) ], priority: 10 }) const zone = route53.HostedZone.fromLookup(this, "zone", { domainName: domain, }) const record = new route53.ARecord(this, "record", { recordName: subdomain, target: route53.RecordTarget.fromAlias( new targets.LoadBalancerTarget(alb) ), zone: zone, }) } } <file_sep>/userdata/initialize.sh #!/usr/bin/sh apt install --no-install-recommends -y git apt install --no-install-recommends -y avr-libc apt install --no-install-recommends -y avrdude apt install --no-install-recommends -y binutils-arm-none-eabi apt install --no-install-recommends -y binutils-avr apt install --no-install-recommends -y build-essential apt install --no-install-recommends -y ca-certificates apt install --no-install-recommends -y clang-format-7 apt install --no-install-recommends -y dfu-programmer apt install --no-install-recommends -y dfu-util apt install --no-install-recommends -y dos2unix apt install --no-install-recommends -y ca-certificates apt install --no-install-recommends -y gcc apt install --no-install-recommends -y gcc-avr apt install --no-install-recommends -y git apt install --no-install-recommends -y libnewlib-arm-none-eabi apt install --no-install-recommends -y python3 apt install --no-install-recommends -y python3-pip apt install --no-install-recommends -y software-properties-common apt install --no-install-recommends -y tar apt install --no-install-recommends -y unzip apt install --no-install-recommends -y tar apt install --no-install-recommends -y wget apt install --no-install-recommends -y zip python3 -m pip install --upgrade pip setuptools wheel python3 -m pip install qmk qmk setup -y -H /opt/qmk_firmware rm -Rf /opt/qmk_firmware/keyboards/* rm -Rf /opt/qmk_firmware/.git* rm -Rf /opt/qmk_firmware/.vscode rm -Rf /opt/qmk_firmware/api_data rm -Rf /opt/qmk_firmware/bin rm -Rf /opt/qmk_firmware/users/ rm -Rf /opt/qmk_firmware/.build/* rm -Rf /opt/qmk_firmware/docs rm -Rf /opt/qmk_firmware/nix rm -Rf /opt/qmk_firmware/platforms rm -Rf /opt/qmk_firmware/tests python3 -m pip install boto3 python3 -m pip install tornado mv tornado_server.py /opt/tornado_server.py mv tornado.service /etc/systemd/system/tornado.service chmod 644 /etc/systemd/system/tornado.service systemctl daemon-reload systemctl enable tornado.service systemctl start tornado.service wget https://s3.ap-northeast-1.amazonaws.com/amazoncloudwatch-agent-ap-northeast-1/debian/amd64/latest/amazon-cloudwatch-agent.deb dpkg -i -E ./amazon-cloudwatch-agent.deb mv amazon-cloudwatch-agent-config.json /opt/aws/amazon-cloudwatch-agent/bin/config.json /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json -s<file_sep>/test/README.md ``` python -m venv test/env source test/env/bin/activate pip install python-lambda-local source test/setenv.sh python-lambda-local -f lambda_handler lambda/caller.py test/event.json ```<file_sep>/README.md # Welcome to your CDK TypeScript project! ## commands * `cdk deploy CdkEc2QmkStorageStack` * `cdk deploy CdkEc2QmkSecgrpEc2Stack` * `cdk deploy CdkEc2QmkSecgrpLbtgtStack` * `cdk deploy CdkEc2QmkEc2Stack` * `cdk deploy CdkEc2QmkAutoscalingStack` * `cdk deploy CdkEc2QmkFunctionStack` ## How to 1. create CdkEc2QmkEc2Stack. 2. make the ec2 instance AMI. 3. delete the ec2 instance. 3. set the AMI id to cdk.json. 4. launch service using CdkEc2QmkAutoscalingStack. ## Login to Ec2 Instance * `ssh admin@172.30.1.xxx -i ~/.ssh/xxxxxxxxx.pem` ## Send file to Ec2 Instance * `scp userdata/tornado_server.py admin@172.30.1.xxx:/opt` * `scp -i ~/.ssh/figment-researchawsserver.pem userdata/tornado_server.py admin@172.30.1.149:/opt` * <file_sep>/test/tornado_client_genbyzip.py import os import urllib.request EC2_PRIVATE_URL = os.environ.get('EC2_PRIVATE_URL') zipfile_path = os.path.join(os.path.dirname(__file__), 'suzuki.zip') f = open(zipfile_path, 'rb') req = urllib.request.Request( url=EC2_PRIVATE_URL + '/genbyzip/', data=f, method='GET' ) response = urllib.request.urlopen(req) print(response.read().decode('utf-8'))
acb06a3b690804236f56fbaa09eafb740017609a
[ "Markdown", "Python", "C", "TypeScript", "Shell" ]
15
TypeScript
suzukiken/cdk-ec2-qmk
d2ac90ab1d66c490f0877da4fa20d33702bded4f
1eee1c7e11488d42909c4702104df28b18fe4c63
refs/heads/master
<file_sep>angular.module('App.Models').factory('Order', [ '$resource', function( $resource ) { return $resource(config.API_ROOT + '/api/v1/chip/order', {}, { placeOrder: { method: "post", params: { } } }) } ]) <file_sep>angular.module('App.Models').factory('Coupon', [ '$resource', function( $resource ) { return $resource(config.API_ROOT + '/api/v1/coupon', {}, { getCouponDetail: { method: "get", params: { } } }) } ]) <file_sep>angular.module('App.Enroll', []).controller('App.Enroll.Controller', [ '$scope', '$state', 'Game', 'User', function ($scope, $state, Game, User) { $scope.user = User.getUserProfile(); $scope.user.$promise.then(function(user){ if(!user.has_base_info){ $state.go('user-person'); } }); $scope.$state = $state; $scope.event_list = Game.getEventList({ id: $state.params.enroll_id }); $scope.goEventDeclaration = function (event) { //判断是否已经过报名时间 if (Date.parse(new Date()) > Date.parse(new Date(event.reg_end_time))) { alert('已经过了报名时间,无法报名!'); return; } //判断是否已经报名 Game.signed({ id: $state.params.enroll_id }).$promise.then(function (signed) { $("#productId").val(""); if (!signed.detail) { if (signed.shopping) { $state.go('game-package', { event_id: event.id }); } else { $state.go('event-declaration', { event_id: event.id }); } } else { alert('您已经报名了此赛事,不能重复报名!') } } ); } } ]);<file_sep>angular.module('App.Models').factory('Chips', [ '$resource', function( $resource ) { return $resource(config.API_ROOT + '/api/v1/chips/:event', {}, { getChipsList: { method: "get", params: { }, isArray: true }, placeOrder: { method: "get", params: { event: 'order' }, isArray: true } }) } ]) <file_sep>angular.module('App.GamePerson', []).controller('App.GamePerson.Controller', [ '$scope', '$sce', '$state', 'Event', '$timeout', function ($scope, $sce, $state, Event, $timeout) { $scope.$state = $state; $scope.sub_ing = false; // $scope.event_declaration = Event.getEventDeclaration({ // id: $state.params.event_id // }) // $scope.trustAsHtml = function(contents){ // return $sce.trustAsHtml(contents) // } var init_uploader = function(){ var pickers = $("div[id^=picker_]"); $.each(pickers, function(i, picker){ var picker_id = $(picker).attr("id"); var uploader_name = picker_id.split("_")[1]; $scope['upload_state_' + i] = "pending"; $scope['uploader_' + i] = WebUploader.create({ // swf文件路径 swf: config.API_ROOT + '/wap/webuploader/Uploader.swf', // 文件接收服务端。 server: config.API_ROOT + '/api/v1/match/event/person_sign/uploadfile', // 选择文件的按钮。可选。 // 内部根据当前运行是创建,可能是input元素,也可能是flash. pick: '#' + picker_id, // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传! resize: false, // 解决android 4+ bug sendAsBinary: true, fileNumLimit: 1 }); // 当有文件被添加进队列的时候 $scope['uploader_' + i].on('fileQueued', function (file) { // $scope.uploader.fileSingleSizeLimit var $list = $("#thelist_" + uploader_name); $list.append('<div id="' + file.id + '" class="item">' + '<h4 class="info">' + file.name + '</h4>' + '<p class="state">等待上传...</p>' + '</div>'); }); // 文件上传过程中创建进度条实时显示。 $scope['uploader_' + i].on('uploadProgress', function (file, percentage) { var $li = $('#' + file.id), $percent = $li.find('.progress .progress-bar'); // 避免重复创建 if (!$percent.length) { $percent = $('<div class="progress progress-striped active">' + '<div class="progress-bar" role="progressbar" style="width: 0%">' + '</div>' + '</div>').appendTo($li).find('.progress-bar'); } $li.find('p.state').text('上传中'); $percent.css('width', percentage * 100 + '%'); }); $scope['uploader_' + i].on('uploadSuccess', function (file, resp) { $("input[data-upload-for]").val(resp.file_path); console.log($("input[data-upload-for]").val()); $('#' + file.id).find('p.state').text('已上传'); }); $scope['uploader_' + i].on('uploadError', function (file) { $('#' + file.id).find('p.state').text('上传出错'); }); $scope['uploader_' + i].on('uploadComplete', function (file) { $('#' + file.id).find('.progress').fadeOut(); }); $scope["btnStartUpload_" + i] = $('#btnStartUpload_' + uploader_name); $scope["btnStartUpload_" + i].on('click', function () { if ($scope["upload_state_" + i] === 'uploading') { $scope['uploader_' + i].stop(); } else { $scope['uploader_' + i].upload(); } }); }); //if ($("#picker")) { // $scope.upload_state = "pending"; // // //} }; $scope.questions = Event.getPersonSignForm({ id: $state.params.event_id }); $scope.questions.$promise.then(function (questions) { questions.forEach(function (question) { question.html = $sce.trustAsHtml(question.field) }); $timeout(function () { init_uploader(); $('#id_nationality').change(function () { var national_id = $('#id_nationality').val(); console.log(national_id); $.ajax({ url: config.API_ROOT + "/api/v1/core/get_province?national_id=" + national_id, type: "get", success: function (data) { data.details.forEach(function (province) { $("#id_province").append('<option value="' + province.id + '">' + province.value + '</option>') }) }, error: function (respon) { debugger } }) }); $('#id_province').change(function () { var id_province = $('#id_province').val(); $("#id_city").html(''); $.ajax({ url: config.API_ROOT + "/api/v1/core/get_province?province_id=" + id_province, type: "get", success: function (data) { data.details.forEach(function (city) { $("#id_city").append('<option value="' + city.id + '">' + city.value + '</option>') }) }, error: function (respon) { debugger } }) }) }) }); $scope.trustAsHtml = function (string) { return $sce.trustAsHtml(string) }; $scope.trustAsHtmlaaa = function (text) { return $sce.trustAsHtml(text) }; $scope.checkForm = function () { var checkAllInput = function (els) { var ret = true, msg = '请完善所有带 * 的资料'; $.each(els, function (i, el) { var elVal = $(el).val(); if (elVal == '') { alert(msg); ret = false; return false; } }); return ret }; var elements = $("input[class*='required'], select[class*='required']"); return checkAllInput(elements); }; $scope.goGamePackage = function ($event) { $event.stopPropagation(); $event.preventDefault(); $scope.sub_ing = true; //表单是否完整 var form_flag = true; if (!$scope.checkForm()) { form_flag = false; $scope.sub_ing = false; } if (form_flag) { var data = {}; for (var i = 0; i < $scope.questions.length; i++) { var question = $scope.questions[i]; data[question.name] = $('#id_' + question.name).val(); } data['product_id'] = $("#productId").val(); Event.postPersonSignForm({ id: $state.params.event_id }, data).$promise.then(function (reps) { if (reps.is_pre_sign) { $state.go('user-enroll'); } else { $state.go('game-person-sign-detail', { person_sign_id: reps.person_sign_id }); $scope.sub_ing = false; } }, function (error) { alert(error.data.detail); $scope.sub_ing = false; }); } }; } ]);<file_sep>angular.module('App.Order', ['App.Order.Pay']).controller('App.Order.Controller', [ '$scope', '$state', '$ionicHistory', "$ionicPopup", 'Chips', 'Order', 'Coupon', function( $scope, $state, $ionicHistory, $ionicPopup, Chips, Order, Coupon ) { $scope.back = function() { $ionicHistory.goBack(); } $scope.p_chip = $state.params.id; $scope.p_color = $state.params.color; $scope.p_combo = $state.params.combo; $scope.buy_type = $state.params.buy_type; $scope.chip_name = $state.params.name; // 获取套餐 $scope.getCombos = function(arr) { var combos_list = []; for (var i = 0; i < arr.packageprice_set.length; i++) { var temp_flag = true; for (var j = 0; j < combos_list.length; j++) { if (arr.packageprice_set[i].combo.id === combos_list[j].id) { temp_flag = false; } } if (temp_flag) { combos_list.push(arr.packageprice_set[i].combo); } else { continue; } } // console.log(combos_list); $scope.combos_list = combos_list; } // 获取颜色 $scope.getColors = function(arr) { var colors_list = []; for (var i = 0; i < arr.packageprice_set.length; i++) { var temp_flag = true; for (var j = 0; j < colors_list.length; j++) { if (arr.packageprice_set[i].color.id === colors_list[j].id) { temp_flag = false; } } if (temp_flag) { colors_list.push(arr.packageprice_set[i].color); } else { continue; } } // console.log(colors_list); $scope.colors_list = colors_list; } // 获取芯片信息列表 Chips.getChipsList().$promise.then(function(response) { $scope.chips_list = response; $scope.chip = $scope.chips_list[0]; $scope.getCombos($scope.chip); $scope.getColors($scope.chip); $scope.prices = $scope.chip.prices; // console.log( $scope.combos_list ); // 根据id获取套餐和颜色 $scope.getColor = function(obj, id) { // console.log(obj); for (var i = 0; i < obj.length; i++) { if (obj[i].id == id) { return obj[i].name; } } } // 订单信息 $scope.order = { color: $scope.getColor($scope.colors_list, $scope.p_color), combo: $scope.getColor($scope.combos_list, $scope.p_combo), price: $scope.prices[$scope.p_color + '_' + $scope.p_combo], buy_type: $scope.buy_type, //使用类型: 1-自用,2-帮别人买 receive_name: "", //收货人 receive_address: "", //收货地址 receive_cellphone: "", //收货人电话 user_name: "", //使用人 user_identity: "", //使用人身份证号 user_cellphone: "", //使用人手机号 coupon: "" //优惠券码,可为空 }; // console.log($scope.order.price); }, function(response) { // console.log(response); }); // 下订单 $scope.placeOrder = function() { if (checkInfo()) { //表单验证通过 Order.placeOrder({ "chip": $scope.p_chip, "color": $scope.p_color, "combo": $scope.p_combo, "receive_name": $scope.order.receive_name, "receive_address": $scope.order.receive_address, "receive_cellphone": $scope.order.receive_cellphone, "user_name": $scope.order.user_name, "user_identity": $scope.order.user_identity, "user_cellphone": $scope.order.user_cellphone, "coupon": $scope.order.coupon, "buy_type": $scope.order.buy_type }).$promise.then(function(response) { // console.log(response); var str_detail = "购买" + $scope.chip_name + "(颜色:" + $scope.order.color + ",套餐:" + $scope.order.color + ")"; $state.go('order-pay', { id: response.id, detail: str_detail, price: $scope.prices, trade_no: response.trade_no }); }, function(response) { console.log(response); }) } } // 验证优惠券 $scope.checkCoupon = function() { if ($scope.order.coupon.trim() != "") { Coupon.getCouponDetail({ code: $scope.order.coupon }).$promise.then(function(response) { // console.log(response); $scope.coupon_text = "(此优惠券可以抵用" + response.detail + "元)"; }, function(response) { $scope.coupon_text = "(此优惠券不可用)"; }) } } $scope.coupon_input = function() { $scope.coupon_text = ""; } // 表单验证 function checkInfo() { var checkResult = true; // 收货人姓名 非空 if ($scope.order.receive_name.trim().length === 0) { $ionicPopup.alert({ title: "<span class='assertive'>请输入收货人姓名</span>", okText: "确定" }); checkResult = false; return checkResult; } // 收货人地址 非空 if ($scope.order.receive_address.trim().length === 0) { $ionicPopup.alert({ title: "<span class='assertive'>请输入收货人地址</span>", okText: "确定" }); checkResult = false; return checkResult; } // 收货人手机号码 11手机号码 var reg_phone = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-3]{1})|(18[5-9]{1}))+\d{8})$/; if (!reg_phone.test($scope.order.receive_cellphone)) { $ionicPopup.alert({ title: "<span class='assertive'>请输入正确的收货人手机号码</span>", okText: "确定" }); checkResult = false; return checkResult; } // 芯片使用人姓名 非空 if ($scope.order.user_name.trim().length === 0) { $ionicPopup.alert({ title: "<span class='assertive'>请输入芯片使用人姓名</span>", okText: "确定" }); checkResult = false; return checkResult; } // 芯片使用人身份证号码 15位或18位 var reg_cardNo = /\d{15}|\d{18}/; if (!reg_cardNo.test($scope.order.user_identity)) { $ionicPopup.alert({ title: "<span class='assertive'>请输入正确的芯片使用人身份证号码</span>", okText: "确定" }); checkResult = false; return checkResult; } // 芯片使用人手机号码 11手机号码 if (!reg_phone.test($scope.order.user_cellphone)) { $ionicPopup.alert({ title: "<span class='assertive'>请输入正确的芯片使用人手机号码</span>", okText: "确定" }); checkResult = false; return checkResult; } return checkResult; } } ]); <file_sep>angular.module('App.User.Buy', []).controller('App.User.Buy.Controller', [ '$scope', '$state', "$ionicHistory", "$sce", "$ionicSlideBoxDelegate", "Chips", function( $scope, $state, $ionicHistory, $sce, $ionicSlideBoxDelegate, Chips ) { $scope.back = function() { $ionicHistory.goBack(); } // 获取套餐 $scope.getCombos = function(arr) { console.log(arr.packageprice_set); var combos_list = []; for (var i = 0; i < arr.packageprice_set.length; i++) { var temp_flag = true; for (var j = 0; j < combos_list.length; j++) { if (arr.packageprice_set[i].combo.id === combos_list[j].id) { temp_flag = false; } } if (temp_flag) { combos_list.push(arr.packageprice_set[i].combo); } else { continue; } } // console.log(combos_list); $scope.combos_list = combos_list; } // 获取颜色 $scope.getColors = function(arr) { var colors_list = []; for (var i = 0; i < arr.packageprice_set.length; i++) { var temp_flag = true; for (var j = 0; j < colors_list.length; j++) { if (arr.packageprice_set[i].color.id === colors_list[j].id) { temp_flag = false; } } if (temp_flag) { colors_list.push(arr.packageprice_set[i].color); } else { continue; } } // console.log(colors_list); $scope.colors_list = colors_list; } // 获取芯片信息列表 Chips.getChipsList().$promise.then(function(response) { $scope.chips_list = response; $scope.chip = $scope.chips_list[0]; $scope.getCombos($scope.chip); $scope.getColors($scope.chip); $scope.prices = $scope.chip.prices; // console.log( $scope.combos_list ); $ionicSlideBoxDelegate.update(); }, function(response) { // console.log(response); }) // 选择套餐 $scope.choseType = 1; $scope.selectType = function(index) { $scope.choseType = index; $scope.price_field = $scope.choseColor + "_" + $scope.choseType; // console.log($scope.price_field); } // 选择颜色 $scope.choseColor = 1; $scope.selectColor = function(index) { $scope.choseColor = index; $scope.price_field = $scope.choseColor + "_" + $scope.choseType; // console.log($scope.price_field); } // 价格字段初始化 $scope.price_field = $scope.choseColor + "_" + $scope.choseType; // tab切换 $scope.activeTab = 1; $scope.setTabs = function(index) { $scope.activeTab = index; } // 购买 $scope.buy = function(buy_type) { $state.go('order', { id: $scope.chip.id, name: $scope.chip.name, color: $scope.choseColor, combo: $scope.choseType, buy_type: buy_type }); } } ]); <file_sep>angular.module('App.GamePersonSignDetail', []).controller('App.GamePersonSignDetail.Controller', [ '$scope', '$state', 'Event', function ($scope, $state, Event) { $scope.$state = $state; //防止重复提交订单支付 $scope.pay_ing = false; $scope.getOrderConfirm = Event.getOrderConfirm({ id: $state.params.person_sign_id }); $scope.postOrder = Event.postOrderConfirm({ id: $state.params.person_sign_id }, {}); console.log('=======$state.params.person_sign_id======'); console.log($state.params.person_sign_id); var setPaying = function (bol) { console.log($scope.pay_ing); $scope.pay_ing = bol; console.log($scope.pay_ing); }; var paySuccess = function(){ $.post( config.API_ROOT + '/wechat/pay/query_order', { trade_no: $scope.postOrder.trade_no }, function (resp) { } ); alert('支付成功!'); $state.go('user-enroll'); }; $scope.postOrderConfirm = function () { setPaying(true); $.ajax({ type: "POST", url: config.API_ROOT + '/wechat/pay/get_bridge_params', dataType: 'json', data: { trade_no: $scope.postOrder.trade_no }, success: function (resp) { if(resp.detail && resp.detail == "fee:0"){ paySuccess(); return; } var payOptions = resp; WeixinJSBridge.invoke('getBrandWCPayRequest', { "appId": payOptions.appId, "timeStamp": payOptions.timestamp, "nonceStr": payOptions.nonceStr, "package": payOptions["package"], "signType": payOptions.signType, "paySign": payOptions.paySign }, function (res) { if (res.err_msg === "get_brand_wcpay_request:ok") { paySuccess(); } else if (res.err_msg === "get_brand_wcpay_request:cancel") { $("#btnPay").removeAttr('disabled'); } else { $("#btnPay").removeAttr('disabled'); alert('支付失败!'); $.post( config.API_ROOT + '/wechat/pay/fail_log', { trade_no: $scope.postOrder.trade_no, data: JSON.stringify(res) } ); $.each(res, function (i, n) { //alert("Name: " + i + ", Value: " + n); }); } } ); }, error: function (resp) { alert(resp.responseJSON.detail); } }); }; $scope.goGamePerson = function () { $state.go('game-person', { event_id: $scope.getOrderConfirm.event.id }); } } ]);<file_sep>var config = { // API_ROOT : 'http://www.beijing-anfang.com' API_ROOT : 'http://run.niren.org' };
44bb29a2dbb027a3774a31579be0125c7b8ef4e6
[ "JavaScript" ]
9
JavaScript
aoxiaoqiang/game
9c999db7130c95ac3aad3ba2cc54cec82424f2e7
1a0b5587e085a17116c48e61fd67f717f5e24ae4