branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>zackdove/detecting-dartboards<file_sep>/f1score_darts.cpp
/////////////////////////////////////////////////////////////////////////////
//
// Calculate the F1-Score for the faces.
//
/////////////////////////////////////////////////////////////////////////////
// header inclusion
#include <stdio.h>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/opencv.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
//For printing correct precision
#include <iomanip>
using namespace std;
using namespace cv;
/** Function Headers */
void detectAndDisplay( Mat frame, int imgnum );
void printFaces(std::vector<Rect> faces);
vector<Rect> ground_truth(int filenum);
Rect vect_to_rect(vector<int> vect);
float iou(Rect A, Rect B);
int calculate_all();
float f1_score(float FalsePos, float TruePos, float real_pos);
/** Global variables */
String cascade_name = "dart.xml";
CascadeClassifier cascade;
/** @function main */
int main( int argc, const char** argv ){
string imgnum = argv[1];
if (imgnum == "all"){
calculate_all();
} else {
string filename = "dartPictures/dart"+imgnum+".jpg";
Mat frame = imread(filename, CV_LOAD_IMAGE_COLOR);
if( !cascade.load( cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
detectAndDisplay( frame, stoi(imgnum) );
imwrite( "detected.jpg", frame );
}
return 0;
}
int calculate_all(){
for (int imgnum = 0; imgnum<16; imgnum++){
string filename = "dartPictures/dart"+to_string(imgnum)+".jpg";
Mat frame = imread(filename, CV_LOAD_IMAGE_COLOR);
if( !cascade.load( cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
detectAndDisplay( frame, imgnum);
imwrite( "detected"+to_string(imgnum)+".jpg", frame );
}
return 0;
}
float f1_score(float FalsePos, float TruePos, float RealPos){
float precision;
if (TruePos == 0) {
precision = 0;
} else {
precision = TruePos/(TruePos+FalsePos);
}
float recall;
if (TruePos == 0) {
recall = 0;
} else {
recall = TruePos/(RealPos);
}
if (precision == 0 && recall == 0){
return 0;
} else {
return 2*(precision*recall)/(precision+recall);
}
}
/** @function detectAndDisplay */
void detectAndDisplay( Mat frame, int imgnum){
std::vector<Rect> detected_faces;
Mat frame_gray;
cvtColor( frame, frame_gray, CV_BGR2GRAY );
equalizeHist( frame_gray, frame_gray );
cascade.detectMultiScale( frame_gray, detected_faces, 1.1, 1, 0|CV_HAAR_SCALE_IMAGE, Size(50, 50), Size(500,500) );
vector<Rect> truth_faces = ground_truth(imgnum);
// printFaces(truth_faces);
float threshold = 0.5;
float true_positives = 0;
float false_positives = 0;
//Calculate IOU for each
for (int j = 0; j < truth_faces.size(); j++){
for( int i = 0; i < detected_faces.size(); i++ ){
float iou_result = iou(detected_faces[i], truth_faces[j]);
// std::cout << "IOU for ground truth face " << truth_faces[j] << " with detected face " << detected_faces[i] << " = " << iou_result << std::endl;
if (iou_result >= threshold){
true_positives++;
//Prevents TP being higher than 1 for each face. Assumes that there are no faces inside faces. In which cases we would need to double break
break;
}
}
}
false_positives += detected_faces.size()-true_positives;
int real_pos = truth_faces.size();
float f1 = f1_score(false_positives, true_positives, real_pos);
std::cout << "Image: " << imgnum << std::endl;
// cout << "Real Pos = " << real_pos << endl;
// cout << "Detected # Faces = " << detected_faces.size() << endl;
// cout << "True Positives = " << true_positives << endl;
// cout << "Detected # Faces = " << detected_faces.size() << endl;
float tpr;
//Handling for div 0
if (true_positives == 0) {
tpr = 0;
} else {
tpr = true_positives/real_pos;
}
std::cout << "TPR " << tpr << std::endl;
std::cout << "F1: " << f1 << "\n" << std::endl;
//Draw for groud truthh
for (int i = 0; i < truth_faces.size(); i++){
rectangle(frame, Point(truth_faces[i].x, truth_faces[i].y), Point(truth_faces[i].x + truth_faces[i].width, truth_faces[i].y + truth_faces[i].height), Scalar( 0, 0, 255 ), 2);
}
for( int i = 0; i < detected_faces.size(); i++ ){
rectangle(frame, Point(detected_faces[i].x, detected_faces[i].y), Point(detected_faces[i].x + detected_faces[i].width, detected_faces[i].y + detected_faces[i].height), Scalar( 0, 255, 0 ), 2);
}
}
void printFaces(std::vector<Rect> faces){
for (int i = 0; i < faces.size(); i++){
std::cout << faces[i] << std::endl;
}
}
//Using https://www.geeksforgeeks.org/csv-file-management-using-c/
//Can optimise by storing into an array
vector<Rect> ground_truth(int filenum){
// std::cout << filenum << std::endl;
// File pointer
ifstream fin("dart.csv");
int file2, count = 0;
vector<string> row;
string line, word, temp;
vector<int> face_coords;
vector<Rect> face_coords_set;
while (getline(fin, line)) {
row.clear();
istringstream iss(line);
while (getline(iss, word, ',')) {
row.push_back(word);
}
file2 = stoi(row[0]);
if (file2 == filenum) {
count = 1;
row.erase(row.begin());
// std::cout << "row size = " << row.size() << std::endl;
for (int i=0; i<row.size(); i=i+4){
face_coords_set.push_back(Rect(stoi(row[i]),stoi(row[i+1]),stoi(row[i+2])-stoi(row[i]),stoi(row[i+3])-stoi(row[i+1])));
}
return face_coords_set;
break;
}
}
if (count == 0){
// cout << "Record not found\n";
}
return face_coords_set;
}
Rect vect_to_rect(vector<int> vect){
return Rect(vect[0], vect[1], vect[2]-vect[0], vect[3]-vect[1]);
}
float iou(Rect A, Rect B){
// std::cout << "A " << A << std::endl;
// std::cout << "B " << B << std::endl;
Rect intersection = A&B;
// std::cout << "inter " << intersection.area() << std::endl;
float iou = (float)intersection.area() / ((float)A.area()+(float)B.area()-(float)intersection.area());
// std::cout << "iou " << std::fixed << std::setprecision(5) << iou << std::endl;
return iou;
}
<file_sep>/readme.md
# Detecting Dartboards
## Image Processing & Computer Vision project.
In this project we will be exploring, implementing and analysing image processing and computer visio techniques in the context of identifying dartboards in images. We will experiment with the Viola-Jones object detection framework, and combine with other techniques to improve efficiacy. Working in C++ and OpenCV. We also implemented a deep neural network.
See [here](https://github.com/zackdove/detecting-dartboards/blob/master/report/darts_report.pdf) for the results and final report.
Running the detector
compile with "g++ main.cpp /usr/lib64/libopencv_core.so.2.4 /usr/lib64/libopencv_highgui.so.2.4 /usr/lib64/libopencv_imgproc.so.2.4 /usr/lib64/libopencv_objdetect.so.2.4 -std=c++11"
run with a.out "image number"
<file_sep>/hough.h
/////////////////////////////////////////////////////////////////////////////
//
// HOUGH header functions
//
/////////////////////////////////////////////////////////////////////////////
// header inclusion
#include <stdio.h>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/opencv.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <iostream>
#include<string>
using namespace std;
using namespace cv;
/** Function Headers */
void normaliseMatrix( Mat matrix );
void hough_circle(cv::Mat &frame, cv::Mat &mag_frame, cv::Mat &dir_frame,
Mat &accu_m, Mat &points);
vector<int> hough_line(cv::Mat &frame, cv::Mat &mag_frame, cv::Mat &dir_frame);
void hough_clustered_lines(Mat &frame, vector<int> points_lines, Mat &accu_m);
void hough_combine(Mat &accu_circle, Mat &accu_clustered_lines, Mat& points);
void hough_detect(Mat& points, bool *detected, int center[2]);
/** */
void hough(Mat &frame, Mat &mag, Mat &dir, Mat &points){
// Hough Circles
int x = mag.rows;
int y = mag.cols;
int radius = min(x,y)/2;
int sizes_circles[] = { x, y, radius };
Mat accu_circles(3, sizes_circles, CV_32FC1, cv::Scalar(0));
Mat points_circle;
hough_circle( frame, mag, dir, accu_circles, points_circle);
// Hough Lines
Mat accu_clustered_lines;
vector<int> points_lines = hough_line( frame , mag, dir);
hough_clustered_lines(frame, points_lines, accu_clustered_lines);
// Combine Circle and Line
hough_combine(points_circle, accu_clustered_lines, points);
}
void hough_circle(cv::Mat &frame, cv::Mat &mag_frame, cv::Mat &dir_frame,
Mat &accu_m, Mat &points){
int minRadius = 15;
const int x = mag_frame.rows;
const int y = mag_frame.cols;
const int radius = min(x,y) / 4; // can be max half the size of dimensions
points = Mat(x/2, y/2, CV_32S, cvScalar(0));
// Look for strong edges
for( int i = 0; i < x; i++){
for( int j = 0; j < y; j++){
// Pixel threshold
if(mag_frame.at<float>(i, j) > 50) {
// Vote for circles corresponding to point's +ve and -ve direction
for( int r = minRadius; r < radius; r++){
float d = dir_frame.at<float>(i, j);
int a = i + r*cos(d);
int b = j + r*sin(d);
// Check that the radius doesn't exceed the boarder
if((a > 0) && (b > 0) && (a < x) && (b < y)){
accu_m.at<int>(a, b, r) += 1;
}
a = i - r*cos(d);
b = j - r*sin(d);
// Check that the radius doesn't exceed the boarder
if((a > 0) && (b > 0) && (a < x) && (b < y)){
accu_m.at<int>(a, b, r) += 1;
}
}
}
}
}
// Condensing points to (x,y) by summing radii
for( int i = 0; i < mag_frame.rows; i++){
for( int j = 0; j < mag_frame.cols; j++){
for( int r = minRadius; r < radius; r++){
if(i/2 < x/2 && j/2 < y/2){
points.at<int>(i/2, j/2) += accu_m.at<int>(i,j,r);
}
}
}
}
normaliseMatrix( points );
//imwrite("circle_hough.jpg", points);
}
void hough_ellipse(Mat &frame){
//Calculate hough space for ellipse
//Threshold
//If above threshold, return true
}
vector<int> hough_line(cv::Mat &frame, cv::Mat &mag_frame, cv::Mat &dir_frame){
vector<int> points_lines;
const int d = sqrt((mag_frame.rows*mag_frame.rows) +
(mag_frame.cols*mag_frame.cols)); //Diameter of image
Mat accu_m = Mat(d, 180, CV_32S, cvScalar(0));
// Look for strong edges
for( int i = 0; i < mag_frame.rows; i++){
for( int j = 0; j < mag_frame.cols; j++){
if(mag_frame.at<float>(i, j) > 45) { // Threshhold
// If edge is strong, vote for lines corresponding to its point
for( int r = 0; r < 180; r++){
int p = (i*cos(r*CV_PI/180) + (j*sin(r*CV_PI/180)));
if(p > 0) {
accu_m.at<int>(p, r)++;
}
}
}
}
}
for( int p = 0; p < d; p++) {
for( int r = 0; r < 180; r++) {
if(accu_m.at<int>(p, r) > 100) { // Threshold
float a = cos(r*CV_PI/180);
float b = sin(r*CV_PI/180);
int x0 = a*p;
int y0 = b*p;
int x1 = int(x0 + 1000*(-b));
int y1 = int(y0 + 1000*(a));
int x2 = int(x0 - 1000*(-b));
int y2 = int(y0 - 1000*(a));
points_lines.push_back(x1);
points_lines.push_back(y1);
points_lines.push_back(x2);
points_lines.push_back(y2);
}
}
}
//imwrite("lines_hough.jpg", accu_m);
return points_lines;
}
void hough_clustered_lines(Mat &frame, vector<int> points_lines, Mat &accu_m){
vector<int> points_clustered_lines;
// Reducing the resolution of the image to reduce spread of points
accu_m = Mat(frame.rows/2, frame.cols/2, CV_32S, cvScalar(0));
for( int p = 0; p < points_lines.size(); p = p + 4){
float x1 = (float)points_lines[p] /2;
float y1 = (float)points_lines[p+1] /2;
float x2 = (float)points_lines[p+2] /2;
float y2 = (float)points_lines[p+3] /2;
float m = (y1 - y2) / (x1 - x2);
float c = y1 - (m*x1);
for(int x = 0; x < frame.rows/2; x ++){
int y = (int)(x*m) + c;
if( (y > 0) && (y < frame.cols/2)){
accu_m.at<int>(x, y)++;
}
}
}
normaliseMatrix(accu_m);
//imwrite("clustered_hough.jpg", accu_m);
}
void hough_combine(Mat &accu_circle, Mat &accu_clustered_lines, Mat& points){
const int x = accu_circle.rows;
const int y = accu_circle.cols;
points = Mat(x, y, CV_32S, cvScalar(0));
for(int i = 0; i < x; i++) {
for(int j = 0; j < y; j++) {
points.at<float>(i, j) += accu_circle.at<float>(i, j);
points.at<float>(i, j) += accu_clustered_lines.at<float>(i, j);
}
}
normaliseMatrix(points);
//imwrite("both1.jpg", points);
}
// Send in specific boxes, if any value is 255 return true
void hough_detect(Mat& points, bool *detected, int center[2]){
const int x = points.rows;
const int y = points.cols;
for(int i=0; i < x; i++){
for(int j = 0; j < y; j++){
if(points.at<int>(i,j) > 235){
*detected = true;
// *2 because points is half-sized
center[0] = i * 2;
center[1] = j * 2;
}
}
}
}
<file_sep>/intersect.cpp
/////////////////////////////////////////////////////////////////////////////
//
// Detect dartboards
//
// compile with "g++ detect_dart_with_hough.cpp /usr/lib64/libopencv_core.so.2.4 /usr/lib64/libopencv_highgui.so.2.4 /usr/lib64/libopencv_imgproc.so.2.4 /usr/lib64/libopencv_objdetect.so.2.4 -std=c++11"
// run with a.out "image number"
//
/////////////////////////////////////////////////////////////////////////////
// header inclusion
#include <stdio.h>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/opencv.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
//For printing correct precision
#include <iomanip>
#include <iostream>
#include<string>
using namespace std;
using namespace cv;
/** Function Headers */
void detectAndDisplay( Mat frame, int imgnum );
void printFaces(std::vector<Rect> faces);
Rect vect_to_rect(vector<int> vect);
void calculate_all();
void sobel(cv::Mat &input, Mat_<int> kernel, cv::Mat &convo);
void magDir(cv::Mat &inputx, cv::Mat &inputy, cv::Mat &mag, cv::Mat &dir);
void hough_circle(cv::Mat &frame, cv::Mat &mag_frame, cv::Mat &dir_frame, Mat &accu_m);
void hough_ellipse(Mat &mag_frame);
vector<vector<int>> hough_line(cv::Mat &frame, cv::Mat &mag_frame, cv::Mat &dir_frame, Mat &accu_m);
vector<vector<int>> hough_clustered_lines(vector<vector<int>> points_lines);
/** Global variables */
String cascade_name = "dart.xml";
CascadeClassifier cascade;
/** @function main */
int main( int argc, const char** argv ){
string imgnum = argv[1];
if (imgnum == "all"){
calculate_all();
} else {
string filename = "dart"+imgnum+".jpg";
Mat frame = imread(filename, CV_LOAD_IMAGE_COLOR);
if( !cascade.load( cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
detectAndDisplay( frame, stoi(imgnum) );
imwrite( "detected.jpg", frame );
}
return 0;
}
int ***malloc3dArray(int dim1, int dim2, int dim3){
int i, j, k;
int ***array = (int ***) malloc(dim1 * sizeof(int **));
for (i = 0; i < dim1; i++) {
array[i] = (int **) malloc(dim2 * sizeof(int *));
for (j = 0; j < dim2; j++) {
array[i][j] = (int *) malloc(dim3 * sizeof(int));
}
}
return array;
}
void calculate_all(){
for (int imgnum = 0; imgnum<16; imgnum++){
string filename = "dart"+to_string(imgnum)+".jpg";
Mat frame = imread(filename, CV_LOAD_IMAGE_COLOR);
if( !cascade.load( cascade_name ) ){ printf("--(!)Error loading\n"); };
detectAndDisplay( frame, imgnum);
imwrite( "detected"+to_string(imgnum)+".jpg", frame );
}
}
void hough_circle(cv::Mat &frame, cv::Mat &mag_frame, cv::Mat &dir_frame, Mat &accu_m, Mat &points){
//Calculate hough space for circles
//Threshold
//If above threshold, return true
points.create(mag_frame.size(), CV_32FC1);
const int x = mag_frame.rows;
const int y = mag_frame.cols;
const int radius = min(x,y) / 2; // can be max half the size of the smallest dimension
// Look for strong edges
for( int i = 0; i < mag_frame.rows; i++){
for( int j = 0; j < mag_frame.cols; j++){
// Pixel threshold
if(mag_frame.at<float>(i, j) > 200) {
// If edge is strong, vote for circles corresponding to its direction
for( int r = 30; r < radius; r++){
for (int k = -1; k < 2; k++){
for (int l = -1; l < 2; l++){
// Circle centers around selected point
int d = dir_frame.at<float>(i, j);
int a = i + k*r*cos(d*CV_PI/180);
int b = j + l*r*sin(d*CV_PI/180);
// Check that the radius doesn't exceed the boarder
if((a > 0) && (b > 0) && (a < x) && (b < y)){
accu_m.at<float>(a, b, r) += 1;
}
}
}
}
}
}
}
// Condensing points to just (x,y)
for( int i = 0; i < mag_frame.rows; i++){
for( int j = 0; j < mag_frame.cols; j++){
for( int r = 30; r < radius; r++){
points.at<int>(i, j) += accu_m.at<float>(i,j,r);
}
if(points.at<int>(i, j) > 300){
std::cout << i << ',' << j << ',' << " points = " << points.at<int>(i, j) << std::endl;
circle(frame, Point(j, i), 10 , Scalar( 0, 0, 255 ), 2);
}
}
}
}
void hough_ellipse(Mat &frame){
//Calculate hough space for ellipse
//Threshold
//If above threshold, return true
}
vector<vector<int>> hough_line(cv::Mat &frame, cv::Mat &mag_frame, cv::Mat &dir_frame, Mat &accu_m){
vector<vector<int>> points_lines;
const int x = mag_frame.rows/2;
const int y = mag_frame.cols/2;
const int d = sqrt((mag_frame.rows*mag_frame.rows) + (mag_frame.cols*mag_frame.cols)) / 2;
const int mini = min(x, y);
accu_m = Mat(d, 180, CV_32S, cvScalar(0));
// Look for strong edges
for( int i = 0; i < mag_frame.rows; i++){
for( int j = 0; j < mag_frame.cols; j++){
if(mag_frame.at<float>(i, j) > 100) { // Threshhold
int xd = i-x;
int yd = j-y;
// If edge is strong, vote for lines corresponding to its point
for( int r = 0; r < 180; r++){
int p = abs((xd*cos(r*CV_PI/180)) + (yd*sin(r*CV_PI/180)));
accu_m.at<int>(p, r)++;
}
}
}
for( int k = 0; k < d; k++) {
for( int l = 0; l < 180; l++) {
if(accu_m.at<int>(k, l) > 200) { // Threshold
float a = cos(l*CV_PI/180);
float b = sin(l*CV_PI/180);
int x0 = x + a*k;
int y0 = y + b*k;
int x1 = int(x0 + mini*(-b));
int y1 = int(y0 + mini*(a));
int x2 = int(x0 - mini*(-b));
int y2 = int(y0 - mini*(a));
vector<int> points = {x1,y1,x2,y2};
points_lines.push_back(points);
line(frame, Point(y1,x1), Point(y2,x2), (0,0,255), 2);
}
}
}
}
return points_lines;
}
vector<vector<int>> hough_clustered_lines(vector<vector<int>> points_lines){
vector<vector<int>> points_clustered_lines;
for( int p = 0; p < points_lines.size(); p++){
int x1 = points_lines[p][0];
int y1 = points_lines[p][1];
int x2 = points_lines[p][2];
int y2 = points_lines[p][3];
std::cout << x1 << ',' << x2 << ',' << y1 << ',' << y2 << std::endl;
}
return points_clustered_lines;
}
/** @function detectAndDisplay */
void detectAndDisplay( Mat frame, int imgnum){
std::vector<Rect> detected_dartboards;
Mat frame_grey;
cvtColor( frame, frame_grey, CV_BGR2GRAY );
equalizeHist( frame_grey, frame_grey );
cascade.detectMultiScale( frame_grey,
detected_dartboards, 1.1, 1, 0|CV_HAAR_SCALE_IMAGE,
Size(50, 50), Size(500,500) );
cout << "Original detected dartboards" << endl;
printFaces(detected_dartboards);
//for (int i = 0; i < detected_dartboards.size(); i++){
//Mat dartboard_frame = frame(detected_dartboards[i]);
//Check if face_frame cotains circle, line, ellipse etc
//If it doesnt meet the criteria, erase it
// create the SOBEL kernel in 1D, Y is transpose
Mat_<int> kernel(3,3);
Mat_<int>kernelT(3,3);
kernel << -1, 0, 1, -2, 0, 2, -1, 0, 1;
kernelT << 1, 2, 1, 0, 0, 0, -1, -2, -1;
// Sobel filter
Mat xConvo, yConvo, mag, dir;
sobel(frame_grey,kernel, xConvo);
sobel(frame_grey, kernelT, yConvo);
imwrite( "x.jpg", xConvo );
imwrite( "y.jpg", yConvo );
magDir( xConvo, yConvo, mag, dir);
imwrite( "Mag.jpg", mag );
imwrite( "Dir.jpg", dir );
Mat points_circle;
int x = mag.rows;
int y = mag.cols;
int radius = min(x,y)/2;
int sizes_circles[] = { x, y, radius };
Mat accu_circles(3, sizes_circles, CV_32FC1, cv::Scalar(0));
//hough_circle( frame, mag, dir, accu_circles, points_circle );
Mat accu_lines;
vector<vector<int>> points_lines = hough_line( frame, mag, dir, accu_lines);
vector<vector<int>> points_clustered_lines = hough_clustered_lines(points_lines);
//Draw detected dartboards from cascade for comparison
for (int i = 0; i < detected_dartboards.size(); i++){
rectangle(frame,
Point(detected_dartboards[i].x, detected_dartboards[i].y),
Point(detected_dartboards[i].x + detected_dartboards[i].width,
detected_dartboards[i].y + detected_dartboards[i].height),
Scalar( 0, 0, 255 ), 2);
}
}
void printFaces(std::vector<Rect> faces){
for (int i = 0; i < faces.size(); i++){
std::cout << faces[i] << std::endl;
}
}
void sobel(cv::Mat &input, Mat_<int> kernel, cv::Mat &convo){
// intialise the output using the input
convo.create(input.size(), CV_32FC1);
// we need to create a padded version of the input
// or there will be border effects
int kernelRadiusX = ( kernel.size[0] - 1 ) / 2;
int kernelRadiusY = ( kernel.size[1] - 1 ) / 2;
cv::Mat paddedInput;
cv::copyMakeBorder( input, paddedInput,
kernelRadiusX, kernelRadiusX, kernelRadiusY, kernelRadiusY,
cv::BORDER_REPLICATE );
for ( int i = 0; i < input.rows; i++ )
{
for( int j = 0; j < input.cols; j++ )
{
float sum = 0.0;
for( int m = -kernelRadiusX; m <= kernelRadiusX; m++ )
{
for( int n = -kernelRadiusY; n <= kernelRadiusY; n++ ){
// find the correct indices we are using
int imagex = i + m + kernelRadiusX;
int imagey = j + n + kernelRadiusY;
int kernelx = m + kernelRadiusX;
int kernely = n + kernelRadiusY;
// get the values from the padded image and the kernel
int imageval = ( int ) paddedInput.at<uchar>( imagex, imagey );
int kernalval = kernel.at<int>( kernelx, kernely );
// do the multiplication
sum = sum + ( imageval * kernalval );
}
}
convo.at<float>(i, j) = sum;
}
}
}
void magDir(cv::Mat &inputx, cv::Mat &inputy, cv::Mat &mag, cv::Mat &dir)
{
// intialise the output using the input
mag.create(inputx.size(), CV_32FC1);
dir.create(inputx.size(), CV_32FC1);
float magmin = 1000;
float magmax = -1000;
for ( int i = 0; i < inputx.rows; i++ )
{
for( int j = 0; j < inputx.cols; j++ )
{
float magx = inputx.at<float>(i, j);
float magy = inputy.at<float>(i, j);
float magTemp = sqrt((magx*magx) + (magy*magy));
float dirTemp = atan2(magy, magx) * 180 / CV_PI;
mag.at<float>(i, j) = magTemp;
dir.at<float>(i, j) = dirTemp;
// Finding min & max values (for normalisation)
if(magTemp > magmax) {
magmax = magTemp;
}
if(magTemp < magmin) {
magmin = magTemp;
}
}
}
//Normalising loop
for ( int i = 0; i < inputx.rows; i++ )
{
for( int j = 0; j < inputx.cols; j++ )
{
//Normalize calculation
float normMag = ((mag.at<float>(i, j) - magmin) * 255)/ (magmax - magmin);
mag.at<float>(i, j) = normMag;
}
}
}
<file_sep>/sobel.h
/////////////////////////////////////////////////////////////////////////////
//
// SOBEL header functions
//
/////////////////////////////////////////////////////////////////////////////
// header inclusion
#include <stdio.h>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/opencv.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <iostream>
#include<string>
using namespace std;
using namespace cv;
/** Function Headers */
void normaliseMatrix( Mat matrix );
void direction(cv::Mat &input, Mat_<int> kernel, cv::Mat &convo);
void magDir(cv::Mat &inputx, cv::Mat &inputy, cv::Mat &mag, cv::Mat &dir);
void sobel(Mat &frame_grey, Mat &xConvo, Mat &yConvo, Mat &mag, Mat &dir){
// Create the SOBEL kernel in 1D, Y is transpose
Mat_<int> kernel(3,3);
Mat_<int>kernelT(3,3);
kernel << -1, 0, 1, -2, 0, 2, -1, 0, 1;
kernelT << 1, 2, 1, 0, 0, 0, -1, -2, -1;
// Sobel filter
direction(frame_grey,kernel, xConvo);
direction(frame_grey, kernelT, yConvo);
magDir( xConvo, yConvo, mag, dir);
//imwrite( "x.jpg", xConvo );
//imwrite( "y.jpg", yConvo );
//imwrite( "Mag.jpg", mag );
//imwrite( "Dir.jpg", dir );
}
void direction(cv::Mat &input, Mat_<int> kernel, cv::Mat &convo){
convo.create(input.size(), CV_32FC1);
// we need to create a padded version of the input
// or there will be border effects
int kernelRadiusX = ( kernel.size[0] - 1 ) / 2;
int kernelRadiusY = ( kernel.size[1] - 1 ) / 2;
cv::Mat paddedInput;
cv::copyMakeBorder( input, paddedInput,
kernelRadiusX, kernelRadiusX, kernelRadiusY, kernelRadiusY,
cv::BORDER_REPLICATE );
for ( int i = 0; i < input.rows; i++ )
{
for( int j = 0; j < input.cols; j++ )
{
float sum = 0.0;
for( int m = -kernelRadiusX; m <= kernelRadiusX; m++ )
{
for( int n = -kernelRadiusY; n <= kernelRadiusY; n++ ){
// find the correct indices we are using
int imagex = i + m + kernelRadiusX;
int imagey = j + n + kernelRadiusY;
int kernelx = m + kernelRadiusX;
int kernely = n + kernelRadiusY;
// get the values from the padded image and the kernel
int imageval = ( int ) paddedInput.at<uchar>( imagex, imagey );
int kernalval = kernel.at<int>( kernelx, kernely );
// do the multiplication
sum = sum + ( imageval * kernalval );
}
}
convo.at<float>(i, j) = sum;
}
}
}
void magDir(cv::Mat &inputx, cv::Mat &inputy, cv::Mat &mag, cv::Mat &dir)
{
mag.create(inputx.size(), CV_32FC1);
dir.create(inputx.size(), CV_32FC1);
for ( int i = 0; i < inputx.rows; i++ )
{
for( int j = 0; j < inputx.cols; j++ )
{
float magx = inputx.at<float>(i, j);
float magy = inputy.at<float>(i, j);
float magTemp = sqrt((magx*magx) + (magy*magy));
float dirTemp = atan2(magy, magx);
mag.at<float>(i, j) = magTemp;
dir.at<float>(i, j) = dirTemp;
}
}
normaliseMatrix( mag );
}
<file_sep>/dart.cpp
/////////////////////////////////////////////////////////////////////////////
//
// COMS30121 - face.cpp
//
/////////////////////////////////////////////////////////////////////////////
// header inclusion
#include <stdio.h>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/opencv.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <sstream>
using namespace std;
using namespace cv;
/** Function Headers */
void detectAndDisplay( Mat frame , int imageNumber);
/** Global variables */
String cascade_name = "dart.xml";
CascadeClassifier cascade;
/** @function main */
int main( int argc, const char** argv )
{
// 1. Read Input Image
Mat frame = imread(argv[1], CV_LOAD_IMAGE_COLOR);
int imageNumber = atoi(argv[2]);
// 2. Load the Strong Classifier in a structure called `Cascade'
if( !cascade.load( cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
// 3. Detect Faces and Display Result
detectAndDisplay( frame , imageNumber);
// 4. Save Result Image
imwrite( "detected.jpg", frame );
return 0;
}
/** @function detectAndDisplay */
void detectAndDisplay( Mat frame , int imageNumber)
{
std::vector<Rect> faces;
Mat frame_gray;
// 1. Prepare Image by turning it into Grayscale and normalising lighting
cvtColor( frame, frame_gray, CV_BGR2GRAY );
equalizeHist( frame_gray, frame_gray );
// 2. Perform Viola-Jones Object Detection
cascade.detectMultiScale( frame_gray, faces, 1.1, 1, 0|CV_HAAR_SCALE_IMAGE, Size(50, 50), Size(500,500) );
// Loading true position coordinates into matrix
vector<double> matrix;
fstream file;
file.open("dart.csv");
string line;
while (getline( file, line,'\n'))
{
istringstream templine(line);
string data;
while (getline( templine, data,','))
{
matrix.push_back(atof(data.c_str()));
}
}
vector<double> coordinates;
for(int i = 0; i < matrix.size(); i = i+5)
{
if(matrix[i] == imageNumber)
{
for(int j = 1; j < 5; j++)
{
coordinates.push_back(matrix[i+j]);
}
}
}
file.close();
//IOU
for(int j = 0; j < coordinates.size(); j = j+4){
Rect r1 = Rect(Point(coordinates[j], coordinates[j+1]), Point(coordinates[j+2], coordinates[j+3]));
float maxiou = 0;
for( int i = 0; i < faces.size(); i++ ) {
Rect r2 = Rect(Point(faces[i].x, faces[i].y), Point(faces[i].x + faces[i].width, faces[i].y + faces[i].height));
float is = (r1 & r2).area();
float u = (r1 | r2).area();
float iou = (double)is/u;
if(iou > maxiou){
maxiou = iou;
}
}
// Draw RED box around true position
rectangle(frame, Point(coordinates[j], coordinates[j+1]), Point(coordinates[j+2], coordinates[j+3]), Scalar( 0, 0, 255 ), 2);
// Print IOU
std::cout << "IOU for dartboard " << (j/4) + 1 << " = "<< maxiou << std::endl;
}
// 3. Print number of Faces found
std::cout << faces.size() << std::endl;
// 4. Draw box around faces found
for( int i = 0; i < faces.size(); i++ )
{
rectangle(frame, Point(faces[i].x, faces[i].y), Point(faces[i].x + faces[i].width, faces[i].y + faces[i].height), Scalar( 0, 255, 0 ), 2);
}
}
<file_sep>/detect_dart_with_hough.cpp
/////////////////////////////////////////////////////////////////////////////
//
// Detect dartboards
//
// compile with "g++ detect_dart_with_hough.cpp /usr/lib64/libopencv_core.so.2.4 /usr/lib64/libopencv_highgui.so.2.4 /usr/lib64/libopencv_imgproc.so.2.4 /usr/lib64/libopencv_objdetect.so.2.4 -std=c++11"
// run with a.out "image number"
//
/////////////////////////////////////////////////////////////////////////////
// header inclusion
#include <stdio.h>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/opencv.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <iostream>
#include<string>
#include "sobel.h"
#include "hough.h"
using namespace std;
using namespace cv;
/** Function Headers */
void detectAndDisplay( Mat frame, int imgnum );
void printFaces(std::vector<Rect> faces);
Rect vect_to_rect(vector<int> vect);
void calculate_all();
void sobel(cv::Mat &input, Mat_<int> kernel, cv::Mat &convo);
void magDir(cv::Mat &inputx, cv::Mat &inputy, cv::Mat &mag, cv::Mat &dir);
void hough_circle(cv::Mat &frame, cv::Mat &mag_frame, cv::Mat &dir_frame, Mat &accu_m);
void hough_ellipse(Mat &mag_frame);
void normaliseMatrix( Mat matrix );
vector<vector<int> > hough_line(cv::Mat &frame, cv::Mat &mag_frame, cv::Mat &dir_frame, Mat &accu_m);
vector<vector<int> > hough_clustered_lines(cv::Mat &frame, vector<vector<int> > points_lines);
/** Global variables */
String cascade_name = "dart.xml";
CascadeClassifier cascade;
/** @function main */
int main( int argc, const char** argv ){
string imgnum = argv[1];
if (imgnum == "all"){
calculate_all();
} else {
string filename = "dart"+imgnum+".jpg";
Mat frame = imread(filename, CV_LOAD_IMAGE_COLOR);
if( !cascade.load( cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
detectAndDisplay( frame, stoi(imgnum) );
imwrite( "detected.jpg", frame );
}
return 0;
}
/** @function detectAndDisplay */
void detectAndDisplay( Mat frame, int imgnum){
std::vector<Rect> detected_dartboards;
Mat frame_grey;
cvtColor( frame, frame_grey, CV_BGR2GRAY );
equalizeHist( frame_grey, frame_grey );
cascade.detectMultiScale( frame_grey,
detected_dartboards, 1.1, 1, 0|CV_HAAR_SCALE_IMAGE,
Size(50, 50), Size(500,500) );
cout << "Original detected dartboards" << endl;
printFaces(detected_dartboards);
//Draw detected dartboards from cascade for comparison
for (int i = 0; i < detected_dartboards.size(); i++){
rectangle(frame,
Point(detected_dartboards[i].x, detected_dartboards[i].y),
Point(detected_dartboards[i].x + detected_dartboards[i].width,
detected_dartboards[i].y + detected_dartboards[i].height),
Scalar( 0, 0, 255 ), 2);
}
// create the SOBEL kernel in 1D, Y is transpose
Mat_<int> kernel(3,3);
Mat_<int>kernelT(3,3);
kernel << -1, 0, 1, -2, 0, 2, -1, 0, 1;
kernelT << 1, 2, 1, 0, 0, 0, -1, -2, -1;
// Sobel filter
Mat xConvo, yConvo, mag, dir;
sobel(frame_grey,kernel, xConvo);
sobel(frame_grey, kernelT, yConvo);
imwrite( "x.jpg", xConvo );
imwrite( "y.jpg", yConvo );
magDir( xConvo, yConvo, mag, dir);
imwrite( "Mag.jpg", mag );
imwrite( "Dir.jpg", dir );
Mat points_circle;
int x = mag.rows;
int y = mag.cols;
int radius = min(x,y)/2;
int sizes_circles[] = { x, y, radius };
Mat accu_circles(3, sizes_circles, CV_32FC1, cv::Scalar(0));
hough_circle( frame, mag, dir, accu_circles, points_circle );
Mat accu_lines;
//vector<vector<int> > points_lines = hough_line( frame, mag, dir, accu_lines);
//vector<vector<int> > points_clustered_lines = hough_clustered_lines(frame, points_lines);
}
void printFaces(std::vector<Rect> faces){
for (int i = 0; i < faces.size(); i++){
std::cout << faces[i] << std::endl;
}
}
int ***malloc3dArray(int dim1, int dim2, int dim3){
int i, j, k;
int ***array = (int ***) malloc(dim1 * sizeof(int **));
for (i = 0; i < dim1; i++) {
array[i] = (int **) malloc(dim2 * sizeof(int *));
for (j = 0; j < dim2; j++) {
array[i][j] = (int *) malloc(dim3 * sizeof(int));
}
}
return array;
}
void calculate_all(){
for (int imgnum = 0; imgnum<16; imgnum++){
string filename = "dart"+to_string(imgnum)+".jpg";
Mat frame = imread(filename, CV_LOAD_IMAGE_COLOR);
if( !cascade.load( cascade_name ) ){ printf("--(!)Error loading\n"); };
detectAndDisplay( frame, imgnum);
imwrite( "detected"+to_string(imgnum)+".jpg", frame );
}
}
void normaliseMatrix( Mat matrix ) {
double min, max;
cv::minMaxLoc(matrix, &min, &max);
for ( int i = 0; i < matrix.rows; i++ )
{
for( int j = 0; j < matrix.cols; j++ )
{
//Normalize calculation
matrix.at<float>(i, j) = (((matrix.at<float>(i, j) - min) * 255.0) / (max - min));
//std::cout << min << ',' << max << ',' << matrix.at<float>(i, j) << std::endl;
}
}
}
<file_sep>/main.cpp
/////////////////////////////////////////////////////////////////////////////
//
// Detect dartboards
//
// compile with "g++ main.cpp /usr/lib64/libopencv_core.so.2.4 /usr/lib64/libopencv_highgui.so.2.4 /usr/lib64/libopencv_imgproc.so.2.4 /usr/lib64/libopencv_objdetect.so.2.4 -std=c++11"
// run with a.out "image number"
//
/////////////////////////////////////////////////////////////////////////////
// header inclusion
#include <stdio.h>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/opencv.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <iostream>
#include<string>
#include "sobel.h"
#include "hough.h"
using namespace std;
using namespace cv;
/** Function Headers */
void detectAndDisplay( Mat frame, int imgnum );
void printFaces(std::vector<Rect> faces);
Rect vect_to_rect(vector<int> vect);
void calculate_all();
void sobel(cv::Mat &input, Mat_<int> kernel, cv::Mat &convo);
void magDir(cv::Mat &inputx, cv::Mat &inputy, cv::Mat &mag, cv::Mat &dir);
void hough_circle(cv::Mat &frame, cv::Mat &mag_frame, cv::Mat &dir_frame, Mat &accu_m);
void hough_ellipse(Mat &mag_frame);
void normaliseMatrix( Mat matrix );
vector<int> hough_line(cv::Mat &frame, cv::Mat &mag_frame, cv::Mat &dir_frame);
void hough_clustered_lines(Mat &frame, vector<int> points_lines, Mat &accu_m);
void hough_combine(Mat &accu_circle, Mat &accu_clustered_lines, Mat &points);
void hough_detect(Mat& points, bool *detected, int center[2]);
vector<Rect> ground_truth(int filenum);
float iou(Rect A, Rect B);
float f1_score(float FalsePos, float TruePos, float real_pos);
/** Global variables */
String cascade_name = "dart.xml";
CascadeClassifier cascade;
/** @function main */
int main( int argc, const char** argv ){
string imgnum = argv[1];
if (imgnum == "all"){
calculate_all();
} else {
string filename = "dartPictures/dart"+imgnum+".jpg";
Mat frame = imread(filename, CV_LOAD_IMAGE_COLOR);
if( !cascade.load( cascade_name ) ){ printf("--(!)Error loading\n"); return -1; };
detectAndDisplay( frame, stoi(imgnum) );
imwrite( "detected.jpg", frame );
}
return 0;
}
void calculate_all(){
for (int imgnum = 0; imgnum<16; imgnum++){
cout << "Image: " << imgnum << endl;
string filename = "dartPictures/dart"+to_string(imgnum)+".jpg";
Mat frame = imread(filename, CV_LOAD_IMAGE_COLOR);
if( !cascade.load( cascade_name ) ){ printf("--(!)Error loading\n"); };
detectAndDisplay( frame, imgnum);
imwrite( "detectedPictures/detected"+to_string(imgnum)+".jpg", frame );
}
}
/** @function detectAndDisplay */
void detectAndDisplay( Mat frame, int imgnum){
std::vector<Rect> detected_dartboards;
vector<Rect> new_detected_dartboards;
Mat frame_grey;
cvtColor( frame, frame_grey, CV_BGR2GRAY );
// GaussianBlur(frame_grey, frame_grey, Size(3,3), 2, 2); // Does this help?
vector<Rect> truth_dartboards = ground_truth(imgnum);
float iou_threshold = 0.5;
float true_positives = 0;
float false_positives = 0;
equalizeHist( frame_grey, frame_grey );
cascade.detectMultiScale( frame_grey,
detected_dartboards, 1.1, 1, 0|CV_HAAR_SCALE_IMAGE,
Size(50, 50), Size(500,500) );
// cout << "Original detected dartboards" << endl;
// printFaces(detected_dartboards);
// Create the SOBEL kernel in 1D, Y is transpose
Mat_<int> kernel(3,3);
Mat_<int>kernelT(3,3);
kernel << -1, 0, 1, -2, 0, 2, -1, 0, 1;
kernelT << 1, 2, 1, 0, 0, 0, -1, -2, -1;
// Sobel filter
Mat xConvo, yConvo, mag, dir;
sobel(frame_grey,kernel, xConvo);
sobel(frame_grey, kernelT, yConvo);
magDir( xConvo, yConvo, mag, dir);
//imwrite( "x.jpg", xConvo );
//imwrite( "y.jpg", yConvo );
//imwrite( "Mag.jpg", mag );
//imwrite( "Dir.jpg", dir );
// Hough Circles
int x = mag.rows;
int y = mag.cols;
int radius = min(x,y)/2;
int sizes_circles[] = { x, y, radius };
Mat accu_circles(3, sizes_circles, CV_32FC1, cv::Scalar(0));
Mat points_circle;
hough_circle( frame, mag, dir, accu_circles, points_circle );
// Hough Lines
Mat accu_clustered_lines;
vector<int> points_lines = hough_line( frame , mag, dir);
hough_clustered_lines(frame, points_lines, accu_clustered_lines);
Mat points;
hough_combine(points_circle, accu_clustered_lines, points);
// Draw detected dartboards from cascade for comparison
for (int i = 0; i < detected_dartboards.size(); i++){
// Create a cropped image of each voilaJones detection
// '/2' because points is half the size of the frame
Mat detected_frame = points(Rect((detected_dartboards[i].x / 2)-1,(detected_dartboards[i].y / 2)-1,(detected_dartboards[i].width / 2)-1,(detected_dartboards[i].height / 2)-1));
bool detected = false;
int center[2] = {0,0};
hough_detect(detected_frame, &detected, center);
if(detected) {
int oldX = (detected_dartboards[i].x);
int oldY = (detected_dartboards[i].y);
new_detected_dartboards.push_back(detected_dartboards[i]);
rectangle(frame,
Point(oldX, oldY),
Point(oldX + detected_dartboards[i].width,
oldY + detected_dartboards[i].height),
Scalar( 0, 255, 0 ), 2);
}
}
// cout << "New Detected Dartboards" << endl;
// printFaces(new_detected_dartboards);
//Calculate detected dartboard iou
for (int j = 0; j < truth_dartboards.size(); j++){
for( int i = 0; i < new_detected_dartboards.size(); i++ ){
float iou_result = iou(new_detected_dartboards[i], truth_dartboards[j]);
// std::cout << "IOU for ground truth face " << truth_dartboards[j] << " with detected face " << detected_faces[i] << " = " << iou_result << std::endl;
if (iou_result >= iou_threshold){
true_positives++;
//Prevents TP being higher than 1 for each face. Assumes that there are no faces inside faces. In which cases we would need to double break
break;
}
}
}
false_positives += new_detected_dartboards.size()-true_positives;
int real_pos = truth_dartboards.size();
float f1 = f1_score(false_positives, true_positives, real_pos);
float tpr;
//Handling for div 0
if (true_positives == 0) {
tpr = 0;
} else {
tpr = true_positives/real_pos;
}
std::cout << "TPR " << tpr << std::endl;
std::cout << "F1: " << f1 << "\n" << std::endl;
for (int i = 0; i < truth_dartboards.size(); i++){
rectangle(frame, Point(truth_dartboards[i].x, truth_dartboards[i].y), Point(truth_dartboards[i].x + truth_dartboards[i].width, truth_dartboards[i].y + truth_dartboards[i].height), Scalar( 0, 0, 255 ), 2);
}
}
void printFaces(std::vector<Rect> faces){
for (int i = 0; i < faces.size(); i++){
std::cout << faces[i] << std::endl;
}
}
int ***malloc3dArray(int dim1, int dim2, int dim3){
int i, j, k;
int ***array = (int ***) malloc(dim1 * sizeof(int **));
for (i = 0; i < dim1; i++) {
array[i] = (int **) malloc(dim2 * sizeof(int *));
for (j = 0; j < dim2; j++) {
array[i][j] = (int *) malloc(dim3 * sizeof(int));
}
}
return array;
}
void normaliseMatrix( Mat matrix ) {
double min, max;
cv::minMaxLoc(matrix, &min, &max);
for ( int i = 0; i < matrix.rows; i++ )
{
for( int j = 0; j < matrix.cols; j++ )
{
//Normalize calculation
matrix.at<float>(i, j) = (((matrix.at<float>(i, j) - min) * 255.0) / (max - min));
}
}
}
float f1_score(float FalsePos, float TruePos, float RealPos){
float precision;
if (TruePos == 0) {
precision = 0;
} else {
precision = TruePos/(TruePos+FalsePos);
}
float recall;
if (TruePos == 0) {
recall = 0;
} else {
recall = TruePos/(RealPos);
}
if (precision == 0 && recall == 0){
return 0;
} else {
return 2*(precision*recall)/(precision+recall);
}
}
//Using https://www.geeksforgeeks.org/csv-file-management-using-c/
//Can optimise by storing into an array
vector<Rect> ground_truth(int filenum){
// std::cout << filenum << std::endl;
// File pointer
ifstream fin("dart.csv");
int file2, count = 0;
vector<string> row;
string line, word, temp;
vector<int> face_coords;
vector<Rect> face_coords_set;
while (getline(fin, line)) {
row.clear();
istringstream iss(line);
while (getline(iss, word, ',')) {
row.push_back(word);
}
file2 = stoi(row[0]);
if (file2 == filenum) {
count = 1;
row.erase(row.begin());
// std::cout << "row size = " << row.size() << std::endl;
for (int i=0; i<row.size(); i=i+4){
face_coords_set.push_back(Rect(stoi(row[i]),stoi(row[i+1]),stoi(row[i+2])-stoi(row[i]),stoi(row[i+3])-stoi(row[i+1])));
}
return face_coords_set;
break;
}
}
if (count == 0){
// cout << "Record not found\n";
}
return face_coords_set;
}
Rect vect_to_rect(vector<int> vect){
return Rect(vect[0], vect[1], vect[2]-vect[0], vect[3]-vect[1]);
}
float iou(Rect A, Rect B){
// std::cout << "A " << A << std::endl;
// std::cout << "B " << B << std::endl;
Rect intersection = A&B;
// std::cout << "inter " << intersection.area() << std::endl;
float iou = (float)intersection.area() / ((float)A.area()+(float)B.area()-(float)intersection.area());
// std::cout << "iou " << std::fixed << std::setprecision(5) << iou << std::endl;
return iou;
}
| 76a49b509f6497bc494ff3fa3dcfa89bc232ddd0 | [
"Markdown",
"C++"
] | 8 | C++ | zackdove/detecting-dartboards | 776c4f93900a56ffad659c2758d9a0cec5852423 | fc13adf49d935e5fc5aafca102012151200f1e03 | |
refs/heads/master | <repo_name>kjetilfjellheim/rov<file_sep>/lm298.py
import logging
"""
Constants
"""
LOGGER = "lm298"
"""
Logger setup
"""
logger = logging.getLogger("lm298")
"""
Class definitions
"""
class MotorControl:
"""
Constants
"""
DIRECTION_LEFT = 1
DIRECTION_RIGHT = -1
DIRECTION_FORWARD = 1
DIRECTION_BACK = -1
STOP_DUTY_CYCLE = 0
HIGH = 1
LOW = 0
"""
Class variables
"""
pwm1Pin = None #Pwm pin for motor 1
m1Pin = None #Motor pin for motor 1
pwm2Pin = None #Pwm pin for motor 2
m2Pin = None #Motor pin for motor 2
def __init__(self, pwm1Pin, m1Pin, m2Pin, pwm2Pin):
logger.info("Starting initalizing LM298")
self.pwm1Pin = pwm1Pin
self.m1Pin = m1Pin
self.m2Pin = m2Pin
self.pwm2Pin = pwm2Pin
self.stop()
logger.info("Finished initalizing LM298")
def setForward(self, mPin):
mPin.write(self.HIGH)
if mPin == self.m1Pin:
logger.info("Motor 1 written value HIGH")
elif mPin == self.m2Pin:
logger.info("Motor 2 written value HIGH")
def setReverse(self, mPin):
mPin.write(self.LOW)
if mPin == self.m1Pin:
logger.info("Motor 1 written value LOW")
elif mPin == self.m2Pin:
logger.info("Motor 2 written value LOW")
"""
Setting pwm value on motor. The value is a fraction between 0-1.
"""
def setPwm(self, pwm, value):
writeVal = value / 100.0
pwm.write(writeVal)
if pwm == self.pwm1Pin:
logger.info("PWM motor 1 written value {0} dutycycle set {1}".format(writeVal, value))
elif pwm == self.pwm2Pin:
logger.info("PWM motor 2 written value {0} dutycycle set {1}".format(writeVal, value))
"""
Rotate in place by setting one motor forward and he other back at the same speed.
"""
def rotateInPlace(self, speed, direction):
if self.DIRECTION_LEFT == direction:
self.setReverse(self.m1Pin)
self.setForward(self.m2Pin)
else:
self.setForward(self.m1Pin)
self.setReverse(self.m2Pin)
logger.info("Motors rotate in place")
self.setPwm(self.pwm1Pin, 100 - speed)
self.setPwm(self.pwm2Pin, speed)
"""
Turn by setting left and right motors at different speed.
"""
def turnDifferential(self, speedLeft, speedRight, direction):
logger.info("Motors turn differential")
if self.DIRECTION_FORWARD == direction:
self.setForward(self.m1Pin)
self.setForward(self.m2Pin)
else:
self.setReverse(self.m1Pin)
self.setReverse(self.m2Pin)
self.setPwm(self.pwm1Pin, 100 - speedLeft)
self.setPwm(self.pwm2Pin, speedRight)
"""
Move forward or back
"""
def forward(self, speed, direction):
logger.info("Motors forward/reverse")
if self.DIRECTION_FORWARD == direction:
self.setForward(self.m1Pin)
self.setForward(self.m2Pin)
else:
self.setReverse(self.m1Pin)
self.setReverse(self.m2Pin)
self.setPwm(self.pwm1Pin, 100 - speed)
self.setPwm(self.pwm2Pin, speed)
"""
Stop both motors by disbaling enable pins and pwm to stop.
"""
def stop(self):
logger.info("Motors stop")
self.setReverse(self.m1Pin)
self.setReverse(self.m2Pin)
self.setPwm(self.pwm1Pin, self.STOP_DUTY_CYCLE)
self.setPwm(self.pwm2Pin, self.STOP_DUTY_CYCLE)<file_sep>/main.py
import threading
import logging
import logging.config
import yaml
from pyfirmata import Arduino
from sen0386 import Sen0386
from lm298 import MotorControl
"""
Constants
"""
LOGGER = "main" #Logger name
SEN0386_SERIALNO = "AB0O5A7Z" #Serial no of th ftdi interface device
MOTORCONTROL_PWM1 = "d:6:p" #Digital pin 6 pwm output
MOTORCONTROL_M1 = "d:5:o" #Digital pin 5 output
MOTORCONTROL_M2 = "d:4:o" #Digital pin 4 output
MOTORCONTROL_PWM2 = "d:3:p" #Digital pin 3 pwm output
ARDUINO_DEVICE = "/dev/ttyACM0" #Arduino device on Lattepanda
"""
Current sensor values
"""
sen038SensorValues = None #Latest sen0386 sensor values read
"""
Setup logging
"""
with open(file = 'logging.yaml', mode = 'r') as stream:
config = yaml.load(stream = stream, Loader = yaml.FullLoader)
logging.config.dictConfig(config)
logger = logging.getLogger(LOGGER)
logger.info("Logging setup")
"""
Setting up modules
"""
logger.info("Starting setup")
sen0386 = Sen0386(serialno = SEN0386_SERIALNO)
logger.info("Sen0386 setup")
"""
Setting up gpio
"""
logger.info("Starting setup gpio")
board = Arduino(ARDUINO_DEVICE)
pwm1Pin = board.get_pin(MOTORCONTROL_PWM1)
m1Pin = board.get_pin(MOTORCONTROL_M1)
m2Pin = board.get_pin(MOTORCONTROL_M2)
pwm2Pin = board.get_pin(MOTORCONTROL_PWM2)
logger.info("Finished setup gpio")
"""
Setting up motorcontrol
"""
motorControl = MotorControl(pwm1Pin, m1Pin, m2Pin, pwm2Pin)
"""
Thread module setup
"""
def sen038Thread():
logger.info("Starting sen038Thread")
while True:
sen038SensorValues = sen0386.readSensorValues()
logger.info("Starting thread setup")
sen0386Thread = threading.Thread(target = sen038Thread)
sen0386Thread.start()
logger.info("Completed Sen0386 setup")
"""Just demo"""
#motorControl.forward(speed = 100, direction = MotorControl.DIRECTION_FORWARD) --No movement
#motorControl.forward(speed = 100, direction = MotorControl.DIRECTION_BACK) --OK
#motorControl.rotateInPlace(speed = 100, direction = MotorControl.DIRECTION_LEFT) --OK
#motorControl.rotateInPlace(speed = 100, direction = MotorControl.DIRECTION_RIGHT) --No movement
#motorControl.turnDifferential(100,0, MotorControl.DIRECTION_FORWARD) --No movement
#motorControl.turnDifferential(0,100, MotorControl.DIRECTION_FORWARD) --No movement
#motorControl.turnDifferential(100,0, MotorControl.DIRECTION_BACK) --OK
#motorControl.turnDifferential(0,100, MotorControl.DIRECTION_BACK) --OK, except left stil slightly move
#motorControl.stop() --OK
<file_sep>/sen0386.py
import struct
import serial
import serial.tools.list_ports as ports
import logging
"""
Logger setup
"""
logger = logging.getLogger("sen0386") #Calculated sensor logger
loggerHw = logging.getLogger("sen0386_hw") #Actual hardware values
"""
Class definitions
"""
class Acceleration:
def __init__(self, ax, ay, az):
self.ax = ax
self.ay = ay
self.az = az
class AngularVelocity:
def __init__(self, wx, wy, wz):
self.wx = wx
self.wy = wy
self.wz = wz
class Gyro:
def __init__(self, roll, pitch, yaw):
self.roll = roll
self.pitch = pitch
self.yaw = yaw
class Response:
def __init__(self, acceleration, angularVelocity, gyro):
self.acceleration = acceleration
self.angularVelocity = angularVelocity
self.gyro = gyro
class Sen0386:
PACKET_HEADER = 0x55
ACC_PACKET_HEADER = 0x51
ANGVEL_PACKET_HEADER = 0x52
ANG_PACKET = 0x53
ACCPACKET_BUFFER_START = 0
ACCPACKET_BUFFER_END = 10
ANGVELPACKET_BUFFER_START = 11
ANGVELPACKET_BUFFER_END = 21
ANGPACKET_BUFFER_START = 22
ANGPACKET_BUFFER_END = 32
BUFFER_SIZE = 100
DATA_SIZE = 44
PACKET_LENGTH = 10
BYTE_PACKET_HEADER = 0
BYTE_PACKET_TYPE = 1
BYTE_AXL_DATA_CONTENT = 2
BYTE_AXH_DATA_CONTENT = 3
BYTE_AYL_DATA_CONTENT = 4
BYTE_AYH_DATA_CONTENT = 5
BYTE_AZL_DATA_CONTENT = 6
BYTE_AZH_DATA_CONTENT = 7
BYTE_WXL_DATA_CONTENT = 2
BYTE_WXH_DATA_CONTENT = 3
BYTE_WYL_DATA_CONTENT = 4
BYTE_WYH_DATA_CONTENT = 5
BYTE_WZL_DATA_CONTENT = 6
BYTE_WZH_DATA_CONTENT = 7
BYTE_ROLLL_DATA_CONTENT = 2
BYTE_ROLLH_DATA_CONTENT = 3
BYTE_PITCHL_DATA_CONTENT = 4
BYTE_PITCHH_DATA_CONTENT = 5
BYTE_YAWL_DATA_CONTENT = 6
BYTE_YAWH_DATA_CONTENT = 7
MAX_16_BIT_INTEGER_SIZE = 32768.00
GRAVITY_CONSTANT = 9.81
CALCULATION_GRAVITY_CONSTANT = GRAVITY_CONSTANT * 16.00
CALCULATION_ROTATION_CONSTANT = 2000.00
CALCULATION_ANGLE_CONSTANT = 180.00
def __init__(self, vid=None, pid=None, serialno=None):
usb_port = self.findUsbPort(vid, pid, serialno)
self.port = serial.Serial(
port=usb_port.device,
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1)
self.port.dtr = False
self.port.rts = False
def findUsbPort(self, vid, pid, serialno):
com_ports = list(ports.comports())
for port in com_ports:
if (vid == None or port.vid == vid) and (pid == None or port.pid == pid) and (serialno == None or port.serial_number == serialno):
return port
return None
def convertShort(self, packet, highByte, lowByte):
b = bytearray(2)
b[0] = packet[highByte]
b[1] = packet[lowByte]
result = struct.unpack(">h", b)[0]
return result
def handleAccPacket(self, accPacketData):
if len(accPacketData) == self.PACKET_LENGTH and accPacketData[self.BYTE_PACKET_HEADER] is self.PACKET_HEADER and accPacketData[self.BYTE_PACKET_TYPE] is self.ACC_PACKET_HEADER:
ax = (self.CALCULATION_GRAVITY_CONSTANT / self.MAX_16_BIT_INTEGER_SIZE) * self.convertShort(accPacketData, self.BYTE_AXH_DATA_CONTENT, self.BYTE_AXL_DATA_CONTENT)
ay = (self.CALCULATION_GRAVITY_CONSTANT / self.MAX_16_BIT_INTEGER_SIZE) * self.convertShort(accPacketData, self.BYTE_AYH_DATA_CONTENT, self.BYTE_AYL_DATA_CONTENT)
az = (self.CALCULATION_GRAVITY_CONSTANT / self.MAX_16_BIT_INTEGER_SIZE) * self.convertShort(accPacketData, self.BYTE_AZH_DATA_CONTENT, self.BYTE_AZL_DATA_CONTENT)
return Acceleration(ax, ay, az)
else:
return Acceleration(None, None, None)
def handleAngVelPacket(self, angVelPacketData):
if len(angVelPacketData) == self.PACKET_LENGTH and angVelPacketData[self.BYTE_PACKET_HEADER] is self.PACKET_HEADER and angVelPacketData[self.BYTE_PACKET_TYPE] is self.ANGVEL_PACKET_HEADER:
wx = (self.CALCULATION_ROTATION_CONSTANT / self.MAX_16_BIT_INTEGER_SIZE) * self.convertShort(angVelPacketData, self.BYTE_WXH_DATA_CONTENT, self.BYTE_WXL_DATA_CONTENT)
wy = (self.CALCULATION_ROTATION_CONSTANT / self.MAX_16_BIT_INTEGER_SIZE) * self.convertShort(angVelPacketData, self.BYTE_WYH_DATA_CONTENT, self.BYTE_WYL_DATA_CONTENT)
wz = (self.CALCULATION_ROTATION_CONSTANT / self.MAX_16_BIT_INTEGER_SIZE) * self.convertShort(angVelPacketData, self.BYTE_WZH_DATA_CONTENT, self.BYTE_WZL_DATA_CONTENT)
return AngularVelocity(wx, wy, wz)
else:
return AngularVelocity(None, None, None)
def handleAngPacket(self, angPacketData):
if len(angPacketData) == self.PACKET_LENGTH and angPacketData[self.BYTE_PACKET_HEADER] is self.PACKET_HEADER and angPacketData[self.BYTE_PACKET_TYPE] is self.ANG_PACKET:
roll = (self.CALCULATION_ANGLE_CONSTANT / self.MAX_16_BIT_INTEGER_SIZE) * self.convertShort(angPacketData, self.BYTE_ROLLH_DATA_CONTENT, self.BYTE_ROLLL_DATA_CONTENT)
pitch = (self.CALCULATION_ANGLE_CONSTANT / self.MAX_16_BIT_INTEGER_SIZE) * self.convertShort(angPacketData, self.BYTE_PITCHH_DATA_CONTENT, self.BYTE_PITCHL_DATA_CONTENT)
yaw = (self.CALCULATION_ANGLE_CONSTANT / self.MAX_16_BIT_INTEGER_SIZE) * self.convertShort(angPacketData, self.BYTE_YAWH_DATA_CONTENT, self.BYTE_YAWL_DATA_CONTENT)
return Gyro(roll, pitch, yaw)
else:
return Gyro(None, None, None)
def handlePackets(self, accPacketData, angVelPacketData, angPacketData):
acceleration = self.handleAccPacket(accPacketData)
angularVelocity = self.handleAngVelPacket(angVelPacketData)
gyro = self.handleAngPacket(angPacketData)
return Response(acceleration, angularVelocity, gyro)
def findStartIndex(self, data):
for index in range(self.BUFFER_SIZE):
if data[index] == self.PACKET_HEADER and data[index+1] == self.ACC_PACKET_HEADER:
return index
return None
def readSensorValues(self):
self.port.flush()
data = self.port.read(self.BUFFER_SIZE)
if data is not None and len(data) == self.BUFFER_SIZE:
first = self.findStartIndex(data)
if (first != None):
data = data[first:first+self.DATA_SIZE]
loggerHw.info(data)
accPacket = data[self.ACCPACKET_BUFFER_START:self.ACCPACKET_BUFFER_END]
angVelPacket = data[self.ANGVELPACKET_BUFFER_START:self.ANGVELPACKET_BUFFER_END]
angPacket = data[self.ANGPACKET_BUFFER_START:self.ANGPACKET_BUFFER_END]
response = self.handlePackets(accPacket, angVelPacket, angPacket)
logger.info("Sensor values read ax={0},ay={1},az={2},wx={3},wy={4},wz={5},roll={6},pitch={7},yaw={8}".format(response.acceleration.ax, response.acceleration.ay, response.acceleration.az, response.angularVelocity.wx, response.angularVelocity.wy, response.angularVelocity.wz, response.gyro.roll, response.gyro.pitch, response.gyro.yaw))
return response
else:
logger.info("No sensor values read")
return Response(None, None, None)
else:
logger.info("No sensor values read")
return Response(None, None, None) | ba9012351d777f0ca37b8f2cfa32bdf07e99ada2 | [
"Python"
] | 3 | Python | kjetilfjellheim/rov | 405a2fd3046d1b5e6ccf8a139a160adeab43ffce | 9d543d008e80ce4489232ffed5f5d5af4fcbeb26 | |
refs/heads/main | <repo_name>qq2602917275/22222<file_sep>/login.js
function fn(){
conosle.log('1111')
}
| a915a37003b5d95974d0d78db954ac102b27dd76 | [
"JavaScript"
] | 1 | JavaScript | qq2602917275/22222 | fce2451e09f26d8b6730ce23858558a08d880c71 | 08134776ee3512b40f8bfe10762609402e1b868c | |
refs/heads/master | <file_sep>require_relative 'find_by'
require_relative 'errors'
require 'csv'
PATH_TO_DATA = File.dirname(__FILE__) + "/../data/data.csv"
METHODS_TO_METAPROGRAM = ["find_by_brand", "find_by_name"]
class Udacidata
# Create a new object, update the CSV accordingly, and return the new object
def self.create(attributes = nil)
csv_data_ids = self.all.map{|p| p.id}
unless csv_data_ids.include?(attributes[:id])
last_id_in_db = csv_data_ids.last ? csv_data_ids.last : -1
attributes[:id] = last_id_in_db + 1
CSV.open(PATH_TO_DATA, "ab") {|csv| csv << [attributes[:id].to_s, attributes[:brand].to_s, attributes[:name].to_s, attributes[:price].to_s]}
end
return_object = self.new(attributes)
end
# Return an array of all of the objects in the CSV
def self.all
data = CSV.read(PATH_TO_DATA, 'rb').drop(1)
data.map{|arr| self.new(id: arr[0].to_i, brand: arr[1], name: arr[2], price: arr[3].to_f)}
end
# Return an array of the first n objects in the CSV
def self.first(n=1)
objects = self.all
n = limit_to_number_of_objects(n, objects)
objects = objects[0..n-1]
objects.length == 1 ? objects.first : objects
end
# Return an array of the last n objects in the CSV
def self.last(n=1)
objects = self.all[(-1*n)..-1]
n = limit_to_number_of_objects(n, objects)
objects.length == 1 ? objects.first : objects
end
# Limit the number n to be a maximum of the length of the objects array
def self.limit_to_number_of_objects(n, objects)
n > objects.length ? objects.length : n
end
# Find and return an object from the CSV by id
def self.find(target_id, objects=nil)
objects ||= self.all
if objects.map{|o| o.id}.include?(target_id)
objects.each {|obj| return obj if obj.id == target_id}
else
raise(ProductNotFoundError, "Find failed, there is no product with id: #{target_id}.")
end
end
# Remove an object from the CSV by id, and return the removed object
def self.destroy(target_id)
object_to_delete = self.find(target_id)
objects = self.all.delete_if{|o| o.id == target_id}
self.write_objects_to_csv(objects)
object_to_delete
end
# Return the array of objects that match the attributes specified by the target hash
def self.where(target)
self.all.select do |o|
is_match = true
target.each do |k, v|
is_match = false if o.send(k) != v
end
is_match
end
end
# Update an object's attribute(s), both in memory and in the CSV
def update(hash_of_updates)
hash_of_updates.each do |k, v|
self.instance_eval("@#{k.to_s}='#{v}'")
end
self.class.update_object_in_csv(self)
self
end
# Update the passed in object in the CSV
def self.update_object_in_csv(updated_object)
objects = self.all
objects = objects.map{|o| o.id == updated_object.id ? updated_object : o}
self.write_objects_to_csv(objects)
end
# Overwrite the CSV with a new CSV containing all of the objects in "objects"
def self.write_objects_to_csv(objects)
CSV.open(PATH_TO_DATA, "wb") do |csv|
csv << ["id", "brand", "product", "price"]
objects.each do |o|
csv << [o.id.to_s, o.brand, o.name, o.price.to_s]
end
end
end
# Improve the readability of objects' string representation
def to_s
"<id: #{self.id}, brand: #{self.brand}, name: #{self.name}, price: #{self.price}"
end
end
<file_sep>class Module
# Create the find_by methods using meta-programming
def create_finder_methods(*attributes)
attributes.each do |attribute_name|
self.class_eval("def find_by_#{attribute_name}(target_string); self.all.find{|o| o.#{attribute_name} == target_string}; end")
end
end
# Override method missing to catch the find_by_* methods and define them using metaprogramming
def method_missing(method_sym, *arguments, &block)
if self.respond_to?(method_sym)
Module.create_finder_methods(method_sym.to_s.split("_")[2])
send(method_sym, arguments.first)
else
super
end
end
# Override responds_to? to accurately reprsent that the class responds to the find_by_* methods defined at runtime
def respond_to?(method_sym, include_private = false)
if METHODS_TO_METAPROGRAM.include?(method_sym.to_s)
true
else
super
end
end
end
<file_sep>require 'faker'
require 'csv'
require_relative '../lib/product'
# This file contains code that populates the database with
# fake data for testing purposes
def db_seed
# Seed the CSV "database"
# Column order: id, brand, product, price
10.times do |i|
Product.create(brand: Faker::Commerce.department, name: Faker::Commerce.product_name, price: Faker::Number.decimal(2))
end
end<file_sep># Define a ProductNotFoundError for use in the find(n) and destroy(n) methods
class ProductNotFoundError < StandardError
end<file_sep>module Analyzable
# Return the average price of the objects in the array passed in
def average_price(objects_array)
(objects_array.map{|o| o.price}.reduce(:+) / (objects_array.length * 1.0)).round(2)
end
# Return the sales report as a string
def print_report(objects_array)
report = "\n"
report += " /$$$$$$ /$$ /$$$$$$$ /$$ \n"
report += " /$$__ $$ | $$ | $$__ $$ | $$ \n"
report += "| $$ \\__/ /$$$$$$ | $$ /$$$$$$ /$$$$$$$ | $$ \\ $$ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ \n"
report += "| $$$$$$ |____ $$| $$ /$$__ $$ /$$_____/ | $$$$$$$/ /$$__ $$ /$$__ $$ /$$__ $$ /$$__ $$|_ $$_/ \n"
report += " \\____ $$ /$$$$$$$| $$| $$$$$$$$| $$$$$$ | $$__ $$| $$$$$$$$| $$ \\ $$| $$ \\ $$| $$ \\__/ | $$ \n"
report += " /$$ \\ $$ /$$__ $$| $$| $$_____/ \\____ $$ | $$ \\ $$| $$_____/| $$ | $$| $$ | $$| $$ | $$ /$$\n"
report += "| $$$$$$/| $$$$$$$| $$| $$$$$$$ /$$$$$$$/ | $$ | $$| $$$$$$$| $$$$$$$/| $$$$$$/| $$ | $$$$/\n"
report += " \\______/ \\_______/|__/ \\_______/|_______/ |__/ |__/ \\_______/| $$____/ \\______/ |__/ \\___/ \n"
report += " | $$ \n"
report += " | $$ \n"
report += " |__/ \n"
report += "\n"
report += ".oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo..oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.\n"
report += "\n"
report += "Total number of products: #{objects_array.length}\n"
report += "\n"
report += "Average product price: $#{average_price(objects_array)}\n"
report += "\n"
report += "Product counts by brand:\n"
count_by_brand(objects_array).each do |k, v|
report += " #{k}: #{v}\n"
end
report += "\n"
report += "Product counts by name:\n"
count_by_name(objects_array).each do |k, v|
report += " #{k}: #{v}\n"
end
report += "\n"
report
end
# Return a hash with a count of products by brand
def count_by_brand(objects_array)
count_by_attribute(objects_array, "brand")
end
# Return a hash with a count of products by name
def count_by_name(objects_array)
count_by_attribute(objects_array, "name")
end
# Return a hash with a count of products by target_attribute
def count_by_attribute(objects_array, target_attribute)
counts_hash = {}
objects_array.each do |o|
if counts_hash.key?(o.send(target_attribute))
counts_hash[o.send(target_attribute)] += 1
else
counts_hash[o.send(target_attribute)] = 1
end
end
counts_hash
end
end
| ac5491a3d4b8a58a3dadb336ade0ca187c7fd718 | [
"Ruby"
] | 5 | Ruby | corey-f/rbnd-toycity-part4 | 5316a0e2452984f025120972e1101297abd25bed | 40a60e8ee70c89fee34a1a5cb7d02341614dd599 | |
refs/heads/master | <file_sep>'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('predicts', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
nodeId: {
type: Sequelize.INTEGER,
references: {
model: 'Nodes',
key: 'id',
}
},
varioId: {
type: Sequelize.INTEGER,
references: {
model: 'variograms',
key: 'id',
}
},
zpredict: {
type: Sequelize.DECIMAL(20, 10)
},
estimation: {
type: Sequelize.DECIMAL(20, 10)
},
predictError: {
type: Sequelize.DECIMAL(20, 10)
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('predicts');
}
};<file_sep>'use strict';
module.exports = (sequelize, DataTypes) => {
const variogram = sequelize.define('variogram', {
nugget: DataTypes.DECIMAL,
sill: DataTypes.DECIMAL,
range: DataTypes.DECIMAL
}, {});
variogram.associate = function(models) {
// associations can be defined here
};
return variogram;
};<file_sep>let user = {
name:'John',
surname:'do',
age:12,
parent:[
{
type:'Mother',
name:'jones',
surname:'do'
},
{
type:'Father',
name:'steve',
surname:'do'
}
],
job :'student',
salary:0,
}
console.log('job',user.job)
console.log('salary',user.salary)
user.job = 'programmer'
console.log('newjob',user.job)
user.salary = 15000
user.parent[0].name ='cara'
user.sonNumber = 0
console.log(user)
user.car ='BMW'
console.log(user)
user.parent = [
...user.parent,
{
type:'brother',
name:'tor',
surname:'do'
}
]
console.log(user)
const multiplex= function(firstnumber,secondnumber){
return firstnumber*secondnumber
}
multiplex(2,3)
const arrowMultiplex = (firtNum,secondNum)=>{
return firtNum*secondNum
}
arrowMultiplex(2,3)
const testExe = ()=>{
let user = 'aaa'
return user
}
testExe()
let str = 'tester'
str.split('') //array
str.replace('t','s')
let number = [1,2,3,4,5,6,8,9]
number.sort((a,b)=>b-a)
for(let i =0 ; i<number.length ; i+=1){
console.log(number[i])
}
console.log('brake')
console.log('testx')
<file_sep>const express = require('express')
const app = express()
var bodyParser = require('body-parser')
import math from 'mathjs'
import cors from 'cors'
import { Node, range, variogram, predict } from './models'
import createRangeTable from './functionHandler/createRangeTable'
import tranformSemivariance from './functionHandler/tranformSemivariance'
import createMatrix from './functionHandler/createMatrix'
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cors())
let user = [
{ id: 1, name: 'john', surname: 'do', job: 'programmer', salary: 12000 },
]
app.get('/getallnode', async (req, res) => {
const nodeData = await Node.findAll()
res.send(nodeData)
})
app.post('/create/node/array', async (req, res) => {
const { example = [] } = req.body
try {
example.map(async data => await Node.create(data))
res.send({ status: 'success' })
} catch (e) {
res.send({ status: 'error' })
}
})
app.post('/node/create-with-attitude', async (req, res) => {
const { latitude, longtitude, attitude } = req.body
const newNode = {
latitude,
longtitude,
attitude,
}
await Node.create(newNode)
const nodeDatas = await Node.findAll()
const tranformdata = createRangeTable(nodeDatas)
const tranformSemiVarianceData = tranformSemivariance(tranformdata, { NUGGET: 0, SILL: 0.1, RANGE: 300 })
const tranformMatrix = createMatrix(tranformSemiVarianceData)
let A = tranformMatrix
let b = tranformSemiVarianceData[tranformSemiVarianceData.length - 1].semi
let w = math.multiply(math.inv(A), b)
let sum = 0
for (let i = 0; i < tranformSemiVarianceData.length - 1; i += 1) {
sum += tranformSemiVarianceData[i].attitude * w[i]
}
const error = math.sum(math.dotMultiply(tranformSemiVarianceData[tranformSemiVarianceData.length - 1].semi, w))
const predictData = {
varioId: 1,
zpredict: sum,
estimation: Math.abs(attitude - sum),
predictError: error
}
await predict.create(predictData)
res.send({ status: 'success', value: sum, error })
})
app.post('/semivariogram/create', async (req, res) => {
const { nugget, sill, range } = req.body
await variogram.create({ nugget, sill, range })
const nodeDatas = await Node.findAll()
const getAllVariogram = await variogram.findAll()
getAllVariogram.map(async ({ id, nugget, sill, range }) => {
const varioID = id
const tranformdata = createRangeTable(nodeDatas)
const tranformSemiVarianceData = tranformSemivariance(tranformdata, { NUGGET: +nugget, SILL: +sill, RANGE: +range })
const tranformMatrix = createMatrix(tranformSemiVarianceData)
let A = tranformMatrix
let b = tranformSemiVarianceData[tranformSemiVarianceData.length - 1].semi
let w = math.multiply(math.inv(A), b)
let sum = 0
for (let i = 0; i < tranformSemiVarianceData.length - 1; i += 1) {
sum += tranformSemiVarianceData[i].attitude * w[i]
}
const error = math.sum(math.dotMultiply(tranformSemiVarianceData[tranformSemiVarianceData.length - 1].semi, w))
nodeDatas.map(async ({ id, attitude }) => {
const nodeID = id
await predict.findOrCreate({
where: { varioId: varioID, nodeId: nodeID }, defaults: {
zpredict: sum,
estimation: Math.abs(attitude - sum),
predictError: error,
}
})
})
})
const getAllPredict = await predict.findAll()
res.send({ data: getAllPredict })
})
app.get('/node/create-with-best-semivariogram', async (req, res) => {
const min = await predict.min('estimation')
const predicte = await predict.findOne({ where: { estimation: min } })
console.log(predicte)
res.send({ data: predicte })
})
app.listen(5000, () => {
console.log('server listen on port 5000')
})
<file_sep>export default (node = [], { NUGGET, SILL, RANGE }) => node.reduce((acc, current) => {
return [
...acc, //round 1 [] //round 2[{id:1,x:1,y2,rage:[...value]}] rund 3 [{..},{..}]
{
latitude: current.latitude,
longtitude: current.longtitude,
attitude: current.attitude,
// range:current.range,
semi: current.distance.reduce((acc, rangeValue) => {
if (acc.length === current.distance.length - 1) {
return [
...acc,
1,
]
} else if (rangeValue === 0) {
return [
...acc,
rangeValue,
]
} else {
return [
...acc,
NUGGET + (SILL * (1 - Math.exp(-rangeValue / RANGE)))
]
}
}, [])
}
]
}, [])<file_sep>'use strict';
module.exports = (sequelize, DataTypes) => {
const range = sequelize.define('range', {
range: DataTypes.DECIMAL,
nodeId: DataTypes.INTEGER.UNSIGNED,
rangeFromNode: DataTypes.DECIMAL
}, {});
range.associate = function (models) {
// associations can be defined here
};
return range;
};<file_sep>const math = require('mathjs')
let prod = [
{ id: 1, x: 428568.6913, y: 872921.7377, z: 30 },
{ id: 2, x: 428646.7539, y: 872900.0566, z: 30 },
{ id: 3, x: 428548.8841, y: 872904.5756, z: 31 },
{ id: 4, x: 428518.0068, y: 872919.8637, z: 32 },
{ id: 5, x: 428553.0826, y: 872855.9671, z: 32 },
{ id: 6, x: 428482.907, y: 872919.6548, z: 33 },
{ id: 7, x: 428534.4663, y: 872848.3179, z: 33 },
{ id: 8, x: 428646.3654, y: 872812.1907, z: 33 },
{ id: 9, x: 428460.3046, y: 872921.5127, z: 34 },
{ id: 10, x: 428469.2297, y: 872878.4219, z: 34 },
{ id: 11, x: 428469.6302, y: 872877.147, z: 34 },
{ id: 12, x: 428436.697, y: 872920.7764, z: 35 },
{ id: 13, x: 428384.4791, y: 872922.5208, z: 36 },
{ id: 14, x: 428448.9284, y: 872873.0868, z: 36 },
{ id: 15, x: 428516.8357, y: 872717.7956, z: 36 },
{ id: 16, x: 428619.246, y: 872733.5326, z: 36 },
{ id: 17, x: 428450.8906, y: 872772.0418, z: 36 },
{ id: 18, x: 428513.3743, y: 872799.3481, z: 35 },
{ id: 19, x: 428539.8487, y: 872826.5365, z: 34 },
{ id: 20, x: 428628.6253, y: 872809.4068, z: 32 },
{ id: 21, x: 428620.5551, y: 872807.1439, z: 33 },
{ id: 22, x: 428600.3184, y: 872793.2637, z: 35 },
{ id: 23, x: 428530.1414, y: 872887.0892, z: 30.453 },
{ id: 24, x: 428636.8825, y: 872804.3883, z: 33 },
{ id: 25, x: 428632.8345, y: 872798.1991, z: 34 },
{ id: 26, x: 428478.7595, y: 872882.4471, z: 33 },
{ id: 27, x: 428467.1532, y: 872885.3028, z: 34 },
{ id: 28, x: 428437.5301, y: 872888.0202, z: 36 },
{ id: 29, x: 428468.4676, y: 872717.8377, z: 36 },
{ id: 30, x: 428628.628, y: 872742.6148, z: 36 },
{ id: 31, x: 428532.2718, y: 872881.4383, z: 30.453 }
]
const setNewData = (prod = []) => {
return prod.reduce((acc, current) => {
return [
...acc, //round 1 [] //round 2[{id:1,x:1,y2,rage:[...value]}] rund 3 [{..},{..}]
{
id: current.id,
x: current.x,
y: current.y,
z: current.z,
range: prod.reduce((acc, next) => {
return [
...acc,
Math.sqrt(Math.pow(current.x - next.x, 2) + Math.pow(current.y - next.y, 2))
]
}, [])
}
]
}, [])
}
const getSemiValian = (node = []) => (NUGGET, SILL, RANGE) => node.reduce((acc, current) => {
return [
...acc,
{
id: current.id,
x: current.x,
y: current.y,
z: current.z,
semi: current.range.reduce((acc, rangeValue) => {
if (acc.length === current.range.length - 1) {
return [
...acc,
1,
]
} else if (rangeValue === 0) {
return [
...acc,
rangeValue,
]
} else {
return [
...acc,
NUGGET + (SILL * (1 - Math.exp(-rangeValue / RANGE)))
]
}
}, [])
}
]
}, [])
let matrix = (seminivalue = []) => seminivalue.reduce((array, next) => {
return [
...array,
next.semi.reduce((prev, value) => {
if (array.length === seminivalue.length - 1) {
if (prev.length === seminivalue.length - 1) {
return [
...prev,
0
]
}
return [
...prev,
1
]
}
return [
...prev,
value,
]
}, [])
]
}, [])
// let A = matrix
// let b = seminivalue[seminivalue.length-1].semi
// let w = math.multiply(math.inv(A),b)
// let sum = 0
// for(let i=0; i<seminivalue.length-1; i+=1) {
// sum += seminivalue[i].z*w[i]
// }
/* START CAL 30 node find best nugget sill range */
const calCulateAttitude = (prod=[])=>{
const {id,z} = prod[prod.length -1]
let max = 0
const range = setNewData(prod)
range.map(({ range }) => {
return range.map(v => {
if (v > max) {
max = v
}
})
})
let rangeArray = []
for (let i = 1; i <= 10; i++) {
rangeArray.push(i * max / 10)
}
let nuggetArray = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] //11 //10
let sillArray = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] // 10
let total = []
let min = 10;
let bestNugget = 0;
let bestSill = 0;
let bestRange = 0;
let bestSum = 0;
for (let i = 0; i < nuggetArray.length; i++) {
for (let j = 0; j < sillArray.length; j++) {
for (let k = 0; k < rangeArray.length; k++) {
const vario = getSemiValian(range)(+nuggetArray[i], +sillArray[j], +rangeArray[k])
const convertMatrix = matrix(vario)
let A = convertMatrix
let b = vario[vario.length - 1].semi
let w = math.multiply(math.inv(A), b)
let sum = 0
for (let i = 0; i < vario.length - 1; i += 1) {
sum += vario[i].z * w[i]
}
const error = math.sum(math.dotMultiply(vario[vario.length - 1].semi, w))
total.push(error)
if (error < min) {
min = error
bestNugget = i
bestSill = j
bestRange = k
bestSum = sum
}
}
}
}
console.log('CALCULATE WITH 31 NODE FIND BEST NUGGET, SILL, RANGE')
console.log('***********RESULT***********')
console.log(`find attitude in node id`)
console.log(id)
console.log('predict error:')
console.log(min)
console.log('NUGGET')
console.log(nuggetArray[bestNugget])
console.log('SILL')
console.log(sillArray[bestSill])
console.log('RANGE')
console.log(rangeArray[bestRange])
console.log(`EXPECT ATTITUDE NODE ${id}`)
console.log(bestSum)
console.log(`ACTUAL ATTITUDE NODE ${id}`)
console.log(z)
}
let transformData = prod
for(let i = 0 ; i<prod.length ;i++){
let temp = transformData.shift()
transformData.unshift()
transformData.push(temp)
calCulateAttitude(transformData)
}
/* END */
/* START ADD NEW NODE 31 */
// const newNode = [
// ...prod,
// ]
// const newRange = setNewData(newNode)
// const vario = getSemiValian(newRange)(+nuggetArray[bestNugget], +sillArray[bestSill], +rangeArray[bestRange])
// const convertMatrix = matrix(vario)
// let A = convertMatrix
// let b = vario[vario.length - 1].semi
// let w = math.multiply(math.inv(A), b)
// // console.log(w)
// let sum = 0
// for (let i = 0; i < vario.length - 1; i += 1) {
// sum += vario[i].z * w[i]
// }
// console.log('z node 31 is', sum)
// const error = math.sum(math.dotMultiply(vario[vario.length - 1].semi, w))
// console.log(error)
// // const example = [
// // {latitude:428568.6913,longtitude:872921.7377,attitude:30},
// // {latitude:428646.7539,longtitude:872900.0566,attitude:30},
// // {latitude:428548.8841,longtitude:872904.5756,attitude:31},
// // {latitude:428518.0068,longtitude:872919.8637,attitude:32},
// // {latitude:428553.0826,longtitude:872855.9671,attitude:32},
// // {latitude:428482.907,longtitude:872919.6548,attitude:33},
// // {latitude:428534.4663,longtitude:872848.3179,attitude:33},
// // {latitude:428646.3654,longtitude:872812.1907,attitude:33},
// // {latitude:428460.3046,longtitude:872921.5127,attitude:34},
// // {latitude:428469.2297,longtitude:872878.4219,attitude:34},
// // {latitude:428469.6302,longtitude:872877.147,attitude:34},
// // {latitude:428436.697,longtitude:872920.7764,attitude:35},
// // {latitude:428384.4791,longtitude:872922.5208,attitude:36},
// // {latitude:428448.9284,longtitude:872873.0868,attitude:36},
// // {latitude:428516.8357,longtitude:872717.7956,attitude:36},
// // {latitude:428619.246,longtitude:872733.5326,attitude:36},
// // {latitude:428450.8906,longtitude:872772.0418,attitude:36},
// // {latitude:428513.3743,longtitude:872799.3481,attitude:35},
// // {latitude:428539.8487,longtitude:872826.5365,attitude:34},
// // {latitude:428628.6253,longtitude:872809.4068,attitude:32},
// // {latitude:428620.5551,longtitude:872807.1439,attitude:33},
// // {latitude:428600.3184,longtitude:872793.2637,attitude:35},
// // {latitude:428530.1414,longtitude:872887.0892,attitude:30.453},
// // {latitude:428636.8825,longtitude:872804.3883,attitude:33},
// // {latitude:428632.8345,longtitude:872798.1991,attitude:34},
// // {latitude:428478.7595,longtitude:872882.4471,attitude:33},
// // {latitude:428467.1532,longtitude:872885.3028,attitude:34},
// // {latitude:428437.5301,longtitude:872888.0202,attitude:36},
// // {latitude:428468.4676,longtitude:872717.8377,attitude:36},
// // {latitude:428628.628,longtitude:872742.6148,attitude:36}
// // ]
// // console.log(JSON.stringify(example)) | 06da934f9198308b2c8101699d04f19058fb8eaf | [
"JavaScript"
] | 7 | JavaScript | aplusde/nodejs-server | 734de1769b57229c0a980468b9dcde77b76c1987 | 249f59c5838c0a21f7dc7b5fa7bcfbadc69c8caa | |
refs/heads/master | <repo_name>sylus-code/multisport-endomondo-wrapper<file_sep>/src/Exception/InvalidPathException.php
<?php
class InvalidPathException extends Exception
{
}<file_sep>/readme.md
# Endomondo Api Wrapper
#### Description
As Endomondo is going retired, I've decided to create a tool to manage trainings based on Endomondo training archive json files.
#### Quick start
```php
use SylusCode\MultiSport\EndomondoWrapper\WorkoutImporter;
use SylusCode\MultiSport\EndomondoWrapper\WorkoutParser as EndoParser;
use SylusCode\MultiSport\EndomondoWrapper\WorkoutTypeResolver as EndoTypeResolver;
use Symfony\Component\Finder\Finder;
$finder = new Finder();
$endoResolver = new EndoTypeResolver();
$endoParser = new EndoParser($endoResolver);
$endoWorkoutImporter = new WorkoutImporter($finder, $endoParser);
$path = 'endomondo-2020-11-18.zip';
$result = $endoWorkoutImporter->importFromZipFile($path);
var_dump($result);
// Example output:
array(1) {
[0]=>
object(SylusCode\MultiSport\Workout\Workout)#2064 (14) {
["time":"SylusCode\MultiSport\Workout\Workout":private]=>
NULL
["type":"SylusCode\MultiSport\Workout\Workout":private]=>
object(SylusCode\MultiSport\Workout\Type)#62947 (2) {
["id":"SylusCode\MultiSport\Workout\Type":private]=>
int(5)
["name":"SylusCode\MultiSport\Workout\Type":private]=>
string(9) "Siłownia"
}
["distance":"SylusCode\MultiSport\Workout\Workout":private]=>
float(0)
["calories":"SylusCode\MultiSport\Workout\Workout":private]=>
int(63)
["durationTotal":"SylusCode\MultiSport\Workout\Workout":private]=>
int(919)
["points":"SylusCode\MultiSport\Workout\Workout":private]=>
array(918) {
[0]=>
object(SylusCode\MultiSport\Workout\Point)#2066 (7) {
["time":"SylusCode\MultiSport\Workout\Point":private]=>
object(DateTime)#2055 (3) {
["date"]=>
string(26) "2020-11-17 09:16:32.000000"
["timezone_type"]=>
int(2)
["timezone"]=>
string(1) "Z"
}
["latitude":"SylusCode\MultiSport\Workout\Point":private]=>
NULL
["longtitude":"SylusCode\MultiSport\Workout\Point":private]=>
NULL
["altitude":"SylusCode\MultiSport\Workout\Point":private]=>
NULL
["distance":"SylusCode\MultiSport\Workout\Point":private]=>
NULL
["heartRate":"SylusCode\MultiSport\Workout\Point":private]=>
int(72)
["speed":"SylusCode\MultiSport\Workout\Point":private]=>
NULL
}
..
```
#### Disclaimer
Endomondo workout parser based on archive json files. Hashtags are not included in this parser as Endomondo do not provide hashtagged wotkouts in archive workout pack.
#### What's next
Add unit tests
<file_sep>/src/WorkoutParser.php
<?php
namespace SylusCode\MultiSport\EndomondoWrapper;
use SylusCode\MultiSport\Workout\Point;
use SylusCode\MultiSport\Workout\Workout;
class WorkoutParser
{
private $endoTypeResolver;
public function __construct(WorkoutTypeResolverInterface $endoTypeResolver)
{
$this->endoTypeResolver = $endoTypeResolver;
}
public function parseFromJson(string $json): Workout
{
$json = json_decode($json, true);
$jsonFlatten = $this->array_flatten($json);
$workout = new Workout();
if (isset($jsonFlatten['sport'])) {
$workout->setType($this->endoTypeResolver->resolve($jsonFlatten['sport']));
}
if (isset($jsonFlatten['start_time'])) {
$workout->setStart($this->resolveTimestamp($jsonFlatten['start_time']));
}
if (isset($jsonFlatten['distance_km'])) {
$workout->setDistance($jsonFlatten['distance_km']);
}
if (isset($jsonFlatten['duration_s'])) {
$workout->setDurationTotal($jsonFlatten['duration_s']);
}
if (isset($jsonFlatten['calories_kcal'])) {
$workout->setCalories($jsonFlatten['calories_kcal']);
}
if (isset($jsonFlatten['speed_avg_kmh'])) {
$workout->setAvgSpeed($jsonFlatten['speed_avg_kmh']);
}
if (isset($jsonFlatten['heart_rate_avg_bpm'])) {
$workout->setAvgHeartRate($jsonFlatten['heart_rate_avg_bpm']);
}
if (isset($jsonFlatten['heart_rate_max_bpm'])) {
$workout->setMaxHeartRate($jsonFlatten['heart_rate_max_bpm']);
}
if (isset($jsonFlatten['speed_max_kmh'])) {
$workout->setMaxSpeed($jsonFlatten['speed_max_kmh']);
}
if (isset($jsonFlatten['steps'])) {
$workout->setSteps($jsonFlatten['steps']);
}
if (isset($jsonFlatten['notes'])) {
$workout->setMessage($jsonFlatten['notes']);
}
if (isset($jsonFlatten['message'])) {
$workout->setMessage($jsonFlatten['message']);
}
if (isset($jsonFlatten['points'])) {
$points = [];
foreach ($jsonFlatten['points'] as $trackPoint) {
$point = $this->createPoint($trackPoint);
$points[] = $point;
}
$workout->setPoints($points);
}
return $workout;
}
private function array_flatten(array $json): array
{
$return = array();
foreach ($json as $key => $value) {
if (is_array($value)) {
if (isset($value['points'])) {
foreach ($value['points'] as $point) {
$return['points'][] = $this->array_flatten($point);
}
} else {
$return = array_merge($return, $this->array_flatten($value));
}
} else {
$return[$key] = $value;
}
}
return $return;
}
private function resolveTimestamp(string $timestamp)
{
$datetime = \DateTime::createFromFormat('D M d H:i:s T Y', $timestamp);
if ($datetime == false) {
$datetime = substr($timestamp, 0, -2);
$datetime = \DateTime::createFromFormat('Y-m-d H:i:s', $datetime);
}
return $datetime;
}
private function createPoint($trackPoint): Point
{
$point = new Point();
if (isset($trackPoint['latitude'])) {
$point->setLatitude($trackPoint['latitude']);
}
if (isset($trackPoint['longitude'])) {
$point->setLongtitude($trackPoint['longitude']);
}
if (isset($trackPoint['timestamp'])) {
$point->setTime($this->resolveTimestamp($trackPoint['timestamp']));
}
if (isset($trackPoint['distance_km'])) {
$point->setDistance($trackPoint['distance_km']);
}
if (isset($trackPoint['altitude'])) {
$point->setAltitude($trackPoint['altitude']);
}
if (isset($trackPoint['heart_rate_bpm'])) {
$point->setHeartRate($trackPoint['heart_rate_bpm']);
}
return $point;
}
}
<file_sep>/src/WorkoutImporterInterface.php
<?php
namespace SylusCode\MultiSport\EndomondoWrapper;
interface WorkoutImporterInterface
{
public function importFromZipFile(string $filePath, string $temporaryExtractPath = null ): array;
}
<file_sep>/src/WorkoutTypeResolver.php
<?php
namespace SylusCode\MultiSport\EndomondoWrapper;
use SylusCode\MultiSport\Workout\Type;
class WorkoutTypeResolver implements WorkoutTypeResolverInterface
{
public function resolve(string $endomondoWorkoutTypeName): Type
{
return new Type($endomondoWorkoutTypeName);
}
}<file_sep>/src/WorkoutImporter.php
<?php
namespace SylusCode\MultiSport\EndomondoWrapper;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
class WorkoutImporter implements WorkoutImporterInterface
{
private $finder;
private $workoutParser;
public function __construct(Finder $finder, WorkoutParser $workoutParser)
{
$this->finder = $finder;
$this->workoutParser = $workoutParser;
}
public function importFromZipFile(string $filePath, string $temporaryExtractPath = null): array
{
$path = dirname($filePath);
$temporaryExtractPath = $temporaryExtractPath ?? $path;
$this->extractFiles($filePath,$temporaryExtractPath);
$this->finder->in($temporaryExtractPath . '/TempData/Workouts')->name('*.json');
$workouts = [];
foreach ($this->finder as $file) {
$string = $file->getContents();
$workout = $this->workoutParser->parseFromJson($string);
array_push($workouts, $workout);
}
$filesystem = new Filesystem();
$filesystem->remove([$temporaryExtractPath . '/TempData']);
return $workouts;
}
private function extractFiles(string $filePath, string $temporaryExtractPath): void
{
$zip = new \ZipArchive();
$res = $zip->open($filePath);
if ($res == !true) {
throw new \InvalidPathException(sprintf('Could not open %s', $filePath));
}
$zip->extractTo($temporaryExtractPath . '/TempData');
$zip->close();
}
}
<file_sep>/src/WorkoutTypeResolverInterface.php
<?php
namespace SylusCode\MultiSport\EndomondoWrapper;
use SylusCode\MultiSport\Workout\Type;
interface WorkoutTypeResolverInterface
{
public function resolve(string $endomondoWorkoutTypeName): Type;
} | 6b4adcd39dbae4c978f91f15d844d3019ed75086 | [
"Markdown",
"PHP"
] | 7 | PHP | sylus-code/multisport-endomondo-wrapper | f718037a1ce79d3ca4f4c17fbd045cb17973dd50 | a922f68eead95566e96deff7ed25f7d3eafd5385 | |
refs/heads/master | <repo_name>fudgemcgroobs/Packet-Sniffer<file_sep>/dispatch.c
#include "dispatch.h"
#include <pcap.h>
#include <signal.h>
#include <stdlib.h>
#include <pthread.h>
#include "analysis.h"
#define MAX_THREAD_NUM 10
pthread_mutex_t muxlock_queue = PTHREAD_MUTEX_INITIALIZER; //used to change queue by threads and 'dispatch'
struct packet_queue *queue; //queue used to store packets for thread
pthread_t threads[MAX_THREAD_NUM]; //stores threads to be used
pthread_cond_t added;
void * thread_code(void *arg) {
//struct thread_args *args = (struct thread_args *) arg; //stores the thread's number (when passed by thread_createh)
struct packet_queue_elem *tmp;
//set cancel state enabled so that signal can terminate all threads
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
while(1) {
if(queue->head == NULL) {
pthread_cond_wait(&added, &muxlock_queue); //wait for signal from dispatch saying that a packet has been added to the queue
}
//at this point, the queue is already locked
//set cancel state disabled so that if thread is processing on termination, will wait until it is done before canceling
//the reason for this is the need to free the memory allocated to the packet queue element extracted by the current thread
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
tmp = queue->head; //retrieve the oldest packet in queue
if(tmp == NULL) { //just a sanity check - should never be the case...
queue->tail = NULL;
} else if(tmp->next == NULL) {
//the extracted packet queue element was the last one in the queue (head and tail must now not point to anything)
queue->head = NULL;
queue->tail = NULL;
} else {
//there are elements still in the queue. set head to the next element for the following thread to extract
queue->head = queue->head->next;
}
pthread_mutex_unlock(&muxlock_queue); //unlock so that other thread can use the queue
//if there was actual packet in queue - another sanity check
if(tmp != NULL) {
analyse(tmp->header, tmp->packet, tmp->verbose);
//free((unsigned char *) tmp->packet);
free(tmp); //must free memory allocated in 'dispatch'
}
//set cancel state back to enabled so that termination cancels thread
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
}
}
void thread_create() {
//initializing queue that will store packets for threads to process
queue = malloc(sizeof(struct packet_queue));
queue->head = NULL;
queue->tail = NULL;
unsigned int i;
for (i = 0; i < MAX_THREAD_NUM; i++) {
//struct thread_args *args = malloc(sizeof(struct thread_args));
//args->threadnum = i;
pthread_create(&threads[i], NULL, &thread_code, NULL);
}
}
void sig_handler(int signo) {
//Ctrl + C signal
if(signo == SIGINT) {
unsigned int i;
for (i = 0; i < MAX_THREAD_NUM; ++i) {
while(!pthread_cancel(threads[i])); //terminate regardless of current activity. if the state is disabled, the cancel request is queued and the command returns 0
}
//free memory used by all packet structures in queue - allocated during execution
while(queue->head != NULL) {
if(queue->head->next == NULL) {
free((unsigned char *) queue->head->packet); //memory was allocated for the packet data each time a queue element was created - need to free this memory
free(queue->head); //memory is allocated for these packet elements - need to free this memory
break;
} else {
struct packet_queue_elem *tmp = queue->head;
queue->head = queue->head->next;
free((unsigned char *) tmp->packet); //memory was allocated for the packet data each time a queue element was created - need to free this memory
free(tmp); //memory is allocated for these packet elements - need to free this memory
}
}
free(queue); //memory was allocated for this structure upon creation - need to free
pthread_mutex_destroy(&muxlock_queue); //no longer required because no threads will be using queue and 'dispatch' will not add anymore elemnts
report(); //method in 'analyse' used to output data collected during run
exit(signo);
}
}
void dispatch(struct pcap_pkthdr *header, const unsigned char *packet, int verbose) {
// TODO: Your part 2 code here
// This method should handle dispatching of work to threads. At present
// it is a simple passthrough as this skeleton is single-threaded.
//create temporary structure before locking queue to prevent excessive wait time for anything else trying to use queue
struct packet_queue_elem *tmp = malloc(sizeof(struct packet_queue_elem)); //the new packet to be queued
tmp->next = NULL; //this will be tail so the next element must be set to NULL
tmp->header = header;
tmp->packet = packet;
tmp->verbose = verbose;
while(pthread_mutex_trylock(&muxlock_queue)); //wait until the mutex is unlocked
if(queue->head == NULL) {
//queue is empty so the only element will be the new one, also head and tail at the same time
queue->head = tmp;
queue->tail = tmp;
pthread_cond_signal(&added); //signal threads that a packet has been added
} else {
//there are elements in queue, add to tail, then this will be the new tail
queue->tail->next = tmp;
queue->tail = queue->tail->next;
pthread_cond_signal(&added); //signal threads that a packet has been added
}
pthread_mutex_unlock(&muxlock_queue); //unlock so that threads can use queue
}<file_sep>/analysis.h
#ifndef CS241_ANALYSIS_H
#define CS241_ANALYSIS_H
#include <pcap.h>
void analyse(struct pcap_pkthdr *header, const unsigned char *packet, int verbose);
void report(); //method inside analysis called at end of execution
#endif<file_sep>/README.md
# Packet Sniffer
## Context
Coursework for module CS241 Operating Systems and Networks which teachins about the functions of operating systems and different types of networks and protocols.
## Purpose
To develop a packet sniffer to identify potential attacks or recon packets.
The intrusion methods required to be detected were ARP Cache Poisoning, Xmas Tree Scans and Blacklis Violations.
Marks were awarded for coursework which used some model of threading to process received packets.
Implementation is described in coursework report.
## Mark
84% for coursework.
74% module total.
<file_sep>/analysis.c
#include "analysis.h"
#include <pcap.h>
#include <netinet/if_ether.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t muxlock_xmas = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t muxlock_arp = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t muxlock_blacklist = PTHREAD_MUTEX_INITIALIZER;
volatile int xmas_count = 0;
volatile int arp_count = 0;
volatile int blacklist_count = 0;
void report() {
printf("\nIntrusion Detection Report:\n");
printf("%d Xmas scans (host fingerprinting)\n", xmas_count);
printf("%d ARP responses (cache poisoning)\n", arp_count);
printf("%d URL Blacklist violations\n", blacklist_count);
pthread_mutex_destroy(&muxlock_xmas);
pthread_mutex_destroy(&muxlock_arp);
pthread_mutex_destroy(&muxlock_blacklist);
}
void analyse(struct pcap_pkthdr *head, const unsigned char *packet, int verbose) {
// TODO your part 2 code here
//Parsing ethernet packet to check the payload type (IP or ARP)
struct ether_header *eth_header = (struct ether_header*) packet;
unsigned short eth_type = ntohs(eth_header->ether_type); //will store type: IP or ARP
if(eth_type == ETHERTYPE_ARP) {
const unsigned char *arp_data = packet + ETH_HLEN; //strip of ethernet header
struct ether_arp *arp_packet = (struct ether_arp *) arp_data; //parse ARP packet data
//check for ARP poisoning - record any ARP response (op code 2) received
if(ntohs(arp_packet->ea_hdr.ar_op) == 2) {
while(pthread_mutex_trylock(&muxlock_arp) != 0); //wait until no threads editing arp_count
arp_count++; //count this response for report at end of execution
pthread_mutex_unlock(&muxlock_arp); //unlock so threads can edit arp_count
}
} else if(eth_type == ETHERTYPE_IP) {
const unsigned char *ip_data = packet + ETH_HLEN; //strip of ethernet header
struct ip *ip_header = (struct ip *) ip_data; //parse IP packet data
int ip_header_len = ip_header->ip_hl * 4; //ip_hl represents the header length in 32-bit words
const unsigned char *tcp_data = ip_data + ip_header_len; //strip IP header
struct tcphdr *tcp_header = (struct tcphdr *) tcp_data; //parse TCP packet data
int tcp_header_len = tcp_header->doff * 4; //doff represents the header length in 32-bit words
//Xmass scan detection - checking for set flags
if( (tcp_header->fin == 1) && (tcp_header->psh == 1) && (tcp_header->urg == 1) ) {
while(pthread_mutex_trylock(&muxlock_xmas) != 0); //wait until no threads editing xmas_count
xmas_count++; //count this suspicious packet for report at end of execution
pthread_mutex_unlock(&muxlock_xmas); //unlock so threads can edit xmas_count
}
//only checking packets passed outward through port 80
if(ntohs(tcp_header->dest) == 80) {
const unsigned char *payload = tcp_data + tcp_header_len; //strip of TCP header
char *begin = strstr((const char *)payload, "Host: www.bbc.co.uk"); //if communicating with www.bbc.co.uk
if(begin != NULL) { //if there is a pointer to the locatoion of the point in which the searched string begins in payload
while(pthread_mutex_trylock(&muxlock_blacklist) != 0); //wait until no threads editing blacklist_count
blacklist_count++; //count this blacklist violation for report at end of execution
pthread_mutex_unlock(&muxlock_blacklist); //unlock so threads can edit blacklist_count
}
}
}
free((unsigned char *) packet); //must free memory which was allocated in before dispatch (in sniff)
//printf("\n");
}<file_sep>/dispatch.h
#ifndef CS241_DISPATCH_H
#define CS241_DISPATCH_H
#include <pcap.h>
struct packet_queue_elem {
//stores all the packet data required by 'analyse' in 'analysis'
struct packet_queue_elem *next; //next element in queue; NULL if tail
struct pcap_pkthdr *header;
const unsigned char *packet;
int verbose;
};
struct packet_queue {
struct packet_queue_elem *head; //for packet extraction by threads
struct packet_queue_elem *tail; //for packet queuing by dispach
};
struct thread_args {
//used for debugging purposes. stores thread number for each thread in thraedpool and can be passed to the thread in 'thread_create' in 'dispatch'
unsigned int threadnum;
};
void dispatch(struct pcap_pkthdr *header, const unsigned char *packet, int verbose);
void thread_create(); //called in 'sniff' to initialize threads and the packet queue used by these
void sig_handler(int signo); //called in order to terminate. initialized in 'sniff'
#endif
| 59df5a6d32626e6cd451dbf9d47711705e38c93b | [
"Markdown",
"C"
] | 5 | C | fudgemcgroobs/Packet-Sniffer | 649ab9e5bfa29de37ab102cf437f8a1c821ec593 | 746db5761cf25c5bf860386bf753b282fe46b128 | |
refs/heads/master | <file_sep>package com.quietpond.json;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Created by joels on 7/13/15.
*/
public class TestXmlToJson {
public static int PRETTY_PRINT_INDENT_FACTOR = 2;
public static String TEST_XML_STRING =
"<?xml version=\"1.0\" ?><test attrib=\"moretest\">Turn this to JSON</test>";
public static void main(String[] args) throws IOException {
try {
JSONObject xmlJSONObj = XML.toJSONObject(readFile("src/test/resources/empi/wsdl/EMPI_18080_2.wsdl", StandardCharsets.UTF_8));
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);
JSONObject xmlJSONObj2 = XML.toJSONObject(readFile("src/test/resources/empi/xsd/mdm.xsd", StandardCharsets.UTF_8));
String jsonPrettyPrintString2 = xmlJSONObj2.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString2);
} catch (JSONException je) {
System.out.println(je.toString());
}
}
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}
| 9405d78c9756898f7004ca1bb38fbfbe8779fb3c | [
"Java"
] | 1 | Java | joelschuster/quietpond.json | 17912d710cd06e5d6a0fa13356fef2e60cc74424 | 91514de74af6a6b06a08555a80ab8941b1ad6f87 | |
refs/heads/master | <file_sep>#!/bin/sh
pm2 stop 'broadcast_node_connect'<file_sep>#!/bin/sh
pm2 start --name "broadcast_node_connect" ./index.js | 0850fdd05982db70ca0f947702f2d97ed2e78932 | [
"Shell"
] | 2 | Shell | HanbitGaram/chatBroadcast_service | 69ee180c8c882e70fb71ca46a6429c5a8440f23f | 3359eeb74230fc477ffda4c214151894a6d30a06 | |
refs/heads/master | <repo_name>dalor/vk-feed-bot<file_sep>/core.py
import asyncio
import os
import re
import simplejson as json
import aiopg
from aiohttp import web, ClientSession
client_id = '6610748'
client_secret = '<KEY>'
bot_id = '344603315:AAHs9sHfDvoYpWFAqLqQiUAJ03xEyi8DdHM'
database = os.environ['DATABASE_URL']
#period_time = 180
per_page = 10
max_groups = 100
main_url = 'https://api.telegram.org/bot' + bot_id
async def fetch(url, session, id = None):
async with session.get(url) as response:
res_json = await response.json()
if id: res_json['id'] = id
return res_json
async def msg(text, chat_id):
return main_url + '/sendMessage?chat_id=' + str(chat_id) + '&text=' + text
async def del_msg(mess_id, chat_id):
return main_url + '/deleteMessage?chat_id=' + str(chat_id) + '&message_id=' + str(mess_id)
async def buttonbar(text, buttons, one_time, chat_id):
buttonb = {'keyboard': buttons, 'one_time_keyboard': one_time, 'force_reply': True}
return main_url + "/sendMessage?chat_id=" + str(chat_id) + "&text=" + text + "&reply_markup=" + json.dumps(buttonb)
async def inline_keyboard(text, buttons, chat_id):
inline_k = {'inline_keyboard': buttons}
return main_url + "/sendMessage?chat_id=" + str(chat_id) + "&text=" + text + "&reply_markup=" + json.dumps(inline_k)
async def media_group(media, chat_id):
return main_url + "/sendMediaGroup?chat_id=" + str(chat_id) + "&media=" + json.dumps(media)
async def update_inline_keyboard(text, buttons, mess_id, chat_id):
inline_k = {'inline_keyboard': buttons}
return main_url + "/editMessageText?chat_id=" + str(chat_id) + "&message_id=" + str(mess_id) + "&text=" + text + "&reply_markup=" + json.dumps(inline_k)
async def send_photo(url, chat_id, text=None):
url_ = main_url + '/sendPhoto?chat_id=' + str(chat_id) + '&photo=' + url
if text:
url_ += ('&caption=' + text)
return url_
async def input_media(media, type_='photo', text=None):
if text:
return {'type': type_, 'media': media, 'caption': text}
else:
return {'type': type_, 'media': media}
async def inline_button(text, callback_data=None, url=None):
if callback_data:
return {'text': text, 'callback_data': callback_data}
elif url:
return {'text': text, 'url': url}
else: None
async def make_sup(sup, a):
return lambda s: ''.join([a if c in sup else c for c in s])
async def a_lot_of(urls, list = True):
async with ClientSession() as session:
if list:
tasks = [asyncio.ensure_future(fetch(url, session)) for url in urls]
else:
tasks = [asyncio.ensure_future(fetch(url['url'], session, url['id'])) for url in urls]
return await asyncio.gather(*tasks)
async def get(url):
async with ClientSession() as session:
task = asyncio.ensure_future(fetch(url, session))
return (await asyncio.gather(task))[0]
async def get_token_from_url(url):
ttoken = re.search(r'access_token=([a-z0-9]+)', url)
if ttoken:
return ttoken.group(1)
else:
None
async def get_token_from_code(url):
ttoken = re.search(r'code=([a-z0-9]+)', url)
if ttoken:
code = ttoken.group(1)
auth_res = await get('https://oauth.vk.com/access_token?client_id=' + client_id + '&client_secret=' + client_secret + '&code=' + code)
if 'access_token' in auth_res:
return auth_res['access_token']
return None
async def get_vk_users():
conn = await (await aiopg.create_pool(database)).acquire()
async with await conn.cursor() as db:
await db.execute('SELECT * FROM users')
users = await db.fetchall()
feed_u = []
for user in users:
if user[3] == 1:
await db.execute('SELECT group_id FROM groups WHERE id = %s', (user[0],))
groups = [str(-gr[0]) for gr in await db.fetchall()]
if len(groups) > 0:
feed_u.append({'id': user[0], 'token': user[1], 'start_time': user[2], 'groups': ','.join(groups)})
conn.close()
return feed_u
async def get_feeds():
users = await get_vk_users()
urls = [{'url': 'https://api.vk.com/method/newsfeed.get?access_token=' + user['token'] + '&filters=post&start_time=' + str(user['start_time'] + 1) + '&source_ids=' + user['groups'] + '&count=100&v=5.8', 'id': user['id']} for user in users]
resps = await a_lot_of(urls, list=False)
all_ = []
conn = await (await aiopg.create_pool(database)).acquire()
async with await conn.cursor() as db:
for resp in resps:
user = resp['id']
other = resp['response']
groups = {gr['id']: {'name': gr['name'], 'login':gr['screen_name']} for gr in other['groups']}
if len(other['items']) > 0:
date = other['items'][0]['date']
await db.execute('UPDATE users SET last_time = %s WHERE id = %s', (date, user))
for item in other['items']:
source = -item['source_id']
attach = []
if 'attachments' in item:
for att in item['attachments']:
if att['type'] == 'photo':
max_res = 0
best_ = ''
for r in att['photo']:
if 'photo_' in r:
res = int(r.split('_')[1])
if res > max_res:
max_res = res
best_ = r
attach.append(att['photo'][best_])
if len(attach) > 0:
all_.append({'id': user, 'pics': attach, 'group': groups[source]['name'], 'url': 'https://vk.com/' + groups[source]['login'] + '?w=wall-' + str(source) + '_' + str(item['post_id'])})
conn.close()
return all_
async def send_feeds():
feeds = await get_feeds()
urls = []
sup = await make_sup('&#',' ')
for feed in feeds:
if len(feed['pics']) > 1:
media = [await input_media(pic, text='[' + sup(feed['group']) + ' ](' + feed['url'] + ')') for pic in feed['pics']]
urls.append(await media_group(media, feed['id']))
else:
urls.append(await send_photo(feed['pics'][0], feed['id'], text='[' + sup(feed['group']) + ' ](' + feed['url'] + ')'))
await a_lot_of(urls)
async def get_groups(token, user_id = None):
if user_id:
groups_get_url = 'https://api.vk.com/method/groups.get?access_token=' + token + '&user_id=' + str(user_id) + '&extended=1&count=' + str(max_groups) + '&v=5.8'
else:
groups_get_url = 'https://api.vk.com/method/groups.get?access_token=' + token + '&extended=1&count=' + str(max_groups) + '&v=5.8'
resp = await get(groups_get_url)
if 'response' in resp:
return [{'id': gr['id'], 'name': gr['name']} for gr in resp['response']['items']]
else:
return None
async def get_id(token):
resp = await get('https://api.vk.com/method/users.get?access_token=' + token + '&v=5.8')
if 'response' in resp:
return resp['response'][0]['id']
else:
None
async def add_group(group, chat_id):
conn = await (await aiopg.create_pool(database)).acquire()
async with await conn.cursor() as db:
await db.execute('UPDATE temp_groups SET type = 1 WHERE group_id = %s AND id = %s', (group, chat_id))
conn.close()
async def del_group(group, chat_id):
conn = await (await aiopg.create_pool(database)).acquire()
async with await conn.cursor() as db:
await db.execute('UPDATE temp_groups SET type = 0 WHERE group_id = %s AND id = %s', (group, chat_id))
conn.close()
async def write_groups(chat_id):
conn = await (await aiopg.create_pool(database)).acquire()
async with await conn.cursor() as db:
await db.execute('UPDATE users SET ready = 0 WHERE id = %s', (chat_id,))
await db.execute('SELECT token FROM users WHERE id = %s', (chat_id,))
resp = await db.fetchone()
if resp:
await db.execute('SELECT group_id FROM groups WHERE id = %s', (chat_id,))
old = [gr[0] for gr in await db.fetchall()]
await db.execute('DELETE FROM temp_groups WHERE id = %s', (chat_id,))
groups = await get_groups(resp[0])
for gr in groups:
if gr['id'] in old: type_ = 1
else: type_ = 0
await db.execute('INSERT INTO temp_groups (group_id, name, id, type) VALUES (%s, %s, %s, %s)', (gr['id'], gr['name'], chat_id, type_))
conn.close()
async def update_groups(chat_id, page=0, update_id=None):
conn = await (await aiopg.create_pool(database)).acquire()
async with await conn.cursor() as db:
await db.execute('SELECT group_id, name, type FROM temp_groups WHERE id = %s ORDER BY i ASC LIMIT %s OFFSET %s', (chat_id, per_page + 1, per_page * page))
temp = await db.fetchall()
conn.close()
btns = []
sup = await make_sup('&#',' ')
for te in temp:
if te[2] == 1:
btns.append([await inline_button('✔ ' + sup(te[1]),'del_group ' + str(te[0]) + ' ' + str(page))])
else:
btns.append([await inline_button('✖ ' + sup(te[1]),'add_group ' + str(te[0]) + ' ' + str(page))])
line = []
if page > 0:
line.append(await inline_button('<','page 0 ' + str(page - 1)))
line.append(await inline_button('✅','approve 0 0'))
line.append(await inline_button('♻','reload 0 0'))
if len(btns) == 0:
await get(await del_msg(update_id, chat_id))
return
if len(btns) > per_page:
btns = btns[:-1]
line.append(await inline_button('>','page 0 ' + str(page + 1)))
btns.append(line)
if not update_id:
await get(await inline_keyboard('Choose groups', btns, chat_id))
else:
await get(await update_inline_keyboard('Choose groups (page ' + str(page + 1) + ')', btns, update_id, chat_id))
async def approve_groups(mess_id, chat_id):
conn = await (await aiopg.create_pool(database)).acquire()
async with await conn.cursor() as db:
await db.execute('SELECT group_id FROM temp_groups WHERE id = %s AND type > 0', (chat_id,))
groups_id = await db.fetchall()
await db.execute('DELETE FROM temp_groups WHERE id = %s', (chat_id,))
await db.execute('DELETE FROM groups WHERE id = %s', (chat_id,))
for gr in groups_id:
await db.execute('INSERT INTO groups(group_id, id) VALUES (%s, %s)', (gr[0], chat_id))
if len(groups_id) > 0:
await db.execute('UPDATE users SET ready = 1 WHERE id = %s', (chat_id,))
conn.close()
await get(await del_msg(mess_id, chat_id))
async def reload_groups(mess_id, chat_id):
await write_groups(chat_id)
await update_groups(chat_id, update_id=mess_id)
async def go_to_page(a,b):
pass
c_commands = {'add_group': add_group,
'del_group': del_group,
'page': go_to_page}
d_commands = {'approve': approve_groups,
'reload': reload_groups}
async def callback(info):
mess = info['message']
chat_id = mess['chat']['id']
mess_id = mess['message_id']
command = info['data'].split()
for com in c_commands:
if com == command[0]:
await c_commands[com](command[1], chat_id)
await update_groups(chat_id, int(command[2]), mess_id)
for com in d_commands:
if com == command[0]:
await d_commands[com](mess_id, chat_id)
async def make_token(w, chat_id):
if len(w) < 2: return
token = await get_token_from_url(w[1])
if token and await get_id(token):
conn = await (await aiopg.create_pool(database)).acquire()
async with await conn.cursor() as db:
await db.execute('INSERT INTO users (id, token, last_time, ready) VALUES (%s, %s, 0, 0) ON CONFLICT (id) DO UPDATE SET token = %s', (chat_id, token, token))
conn.close()
await get(await msg('Succefull registered!' , chat_id))
else:
await get(await msg('Error...' , chat_id))
async def choose_groups(w, chat_id):
await write_groups(chat_id)
await update_groups(chat_id)
async def start_text(q, chat_id):
butn = [[await inline_button('Register url', url='https://goo.gl/xfAETn')]]
await get(await inline_keyboard('Go to this link,\nafter passing on this page,\ncopy url and write command:\n/url COPIED_URL\nMore in /help', butn, chat_id))
async def help_text(q, chat_id):
text = '/start - use to bind your vk\n/groups - choose groups what you want to see'
await get(await msg(text , chat_id))
commands = {'/url': make_token,
'/groups': choose_groups,
'/start': start_text,
'/help': help_text}
async def message(info):
chat_id = info['chat']['id']
if 'text' in info:
words = info['text'].split()
command = words[0].split('@')[0]
for com in commands:
if com == command:
await commands[com](words, chat_id)
break
#async def period(app):
# async def check(app):
# while True:
# await send_feeds() #
# await asyncio.sleep(period_time)
# app.loop.create_task(check(app))
routes = web.RouteTableDef()
@routes.get('/')
async def hello(request):
await send_feeds()
return web.Response(text='Go away')
@routes.post('/hook')
async def webhook(request):
res_json = await request.json()
#print(res_json)
if 'callback_query' in res_json:
await callback(res_json['callback_query'])
elif 'message' in res_json:
await message(res_json['message'])
elif 'channel_post' in res_json:
await message(res_json['channel_post'])
return web.Response(status=200)
async def create_database(app):
conn = await (await aiopg.create_pool(database)).acquire()
async with await conn.cursor() as db:
await db.execute('CREATE TABLE IF NOT EXISTS users (id integer PRIMARY KEY NOT NULL, token text NOT NULL, last_time integer NOT NULL, ready integer NOT NULL)')
await db.execute('CREATE TABLE IF NOT EXISTS groups (group_id integer NOT NULL, id integer NOT NULL)')
await db.execute('CREATE TABLE IF NOT EXISTS temp_groups (i SERIAL PRIMARY KEY, group_id integer NOT NULL, name text NOT NULL, id integer NOT NULL, type integer NOT NULL)')
conn.close()
async def web_app():
app = web.Application()
app.on_startup.append(create_database)
#app.on_startup.append(period)
app.add_routes(routes)
return app
if __name__ == '__main__':
app = web_app()
web.run_app(app)
<file_sep>/requirements.txt
aiohttp
gunicorn
aiopg
simplejson
| 8e8d667d138d0533686e9c19fd1e4871f51a71c7 | [
"Python",
"Text"
] | 2 | Python | dalor/vk-feed-bot | 056da24a33104e3413dec3d961cd0374ca75e60d | d50aef1193ff7024427f2509b8388d0688a914c0 | |
refs/heads/master | <file_sep><?php
namespace Imi\Db\Aop;
use Imi\Aop\AroundJoinPoint;
use Imi\Aop\Annotation\Around;
use Imi\Aop\Annotation\Aspect;
use Imi\Aop\Annotation\PointCut;
use Imi\Db\Exception\DbException;
use Imi\Util\Traits\Aspect\TDefer;
/**
* @Aspect
*/
class MysqlAspect
{
use TDefer;
/**
* Db 延迟收包
* @PointCut(
* allow={
* "Swoole\Coroutine\MySQL::query",
* "Swoole\Coroutine\MySQL::prepare",
* }
* )
* @Around
* @return mixed
*/
public function defer(AroundJoinPoint $joinPoint)
{
$result = $this->parseDefer($joinPoint);
if(false === $result)
{
$statement = $joinPoint->getTarget();
throw new DbException('sql query error: [' . $statement->errorCode() . '] ' . $statement->errorInfo() . ' sql: ' . $statement->getSql());
}
return $result;
}
/**
* Statement 延迟收包
* @PointCut(
* allow={
* "Imi\Db\Drivers\CoroutineMysql\Statement::execute",
* }
* )
* @Around
* @return mixed
*/
public function statementDefer(AroundJoinPoint $joinPoint)
{
$statement = $joinPoint->getTarget();
$client = $statement->getDb()->getInstance();
// 获取调用前的defer状态
$isDefer = $client->getDefer();
if(!$isDefer)
{
// 强制设为延迟收包
$client->setDefer(true);
}
// 调用原方法
$result = $joinPoint->proceed();
if(!$isDefer)
{
// 设为调用前状态
$client->setDefer(false);
}
if(false === $result)
{
throw new DbException('sql query error: [' . $statement->errorCode() . '] ' . $statement->errorInfo() . ' sql: ' . $statement->getSql());
}
return $result;
}
}<file_sep><?php
namespace Imi\Util;
abstract class Coroutine extends \Swoole\Coroutine
{
/**
* 是否在协程中
* @return boolean
*/
public static function isIn()
{
return static::getuid() > -1;
}
}<file_sep><?php
namespace Imi\Process;
use Imi\Process\Parser\ProcessParser;
use Imi\Bean\BeanFactory;
use Imi\Event\Event;
/**
* 进程管理类
*/
abstract class ProcessManager
{
/**
* 创建进程
* 本方法无法在控制器中使用
* 返回\Swoole\Process对象实例
*
* @param string $name
* @param array $args
* @param boolean $redirectStdinStdout
* @param int $pipeType
* @return \Swoole\Process
*/
public static function create($name, $args = [], $redirectStdinStdout = null, $pipeType = null): \Swoole\Process
{
$processOption = ProcessParser::getInstance()->getProcess($name);
if(null === $redirectStdinStdout)
{
$redirectStdinStdout = $processOption['Process']->redirectStdinStdout;
}
if(null === $pipeType)
{
$pipeType = $processOption['Process']->pipeType;
}
$processInstance = BeanFactory::newInstance($processOption['className'], $args);
$process = new \Swoole\Process(function(\Swoole\Process $swooleProcess) use($processInstance, $name){
// 设置进程名称
$swooleProcess->name($name);
// 进程开始事件
Event::trigger('IMI.PROCESS.BEGIN', [
'name' => $name,
'process' => $swooleProcess,
]);
// 执行任务
call_user_func([$processInstance, 'run'], $swooleProcess);
// 进程结束事件
Event::trigger('IMI.PROCESS.END', [
'name' => $name,
'process' => $swooleProcess,
]);
}, $redirectStdinStdout, $pipeType);
return $process;
}
/**
* 运行进程,同步阻塞等待进程执行返回
* 不返回\Swoole\Process对象实例
* 执行失败返回false,执行成功返回数组,包含了进程退出的状态码、信号、输出内容。
* array(
* 'code' => 0,
* 'signal' => 0,
* 'output' => '',
* );
*
* @param string $name
* @param array $args
* @param boolean $redirectStdinStdout
* @param int $pipeType
* @return array
*/
public static function run($name, $args = [], $redirectStdinStdout = null, $pipeType = null)
{
$cmd = 'php ' . $_SERVER['argv'][0] . ' process/start -name ' . $name;
if(null !== $redirectStdinStdout)
{
$cmd .= ' -redirectStdinStdout ' . $redirectStdinStdout;
}
if(null !== $pipeType)
{
$cmd .= ' -pipeType ' . $pipeType;
}
return \Swoole\Coroutine::exec($cmd);
}
/**
* 运行进程,创建一个协程执行进程,无法获取进程执行结果
* 执行失败返回false,执行成功返回数组,包含了进程退出的状态码、信号、输出内容。
* array(
* 'code' => 0,
* 'signal' => 0,
* 'output' => '',
* );
*
* @param string $name
* @param array $args
* @param boolean $redirectStdinStdout
* @param int $pipeType
* @return void
*/
public static function coRun($name, $args = [], $redirectStdinStdout = null, $pipeType = null)
{
go(function() use($name, $args, $redirectStdinStdout, $pipeType){
static::run($name, $args, $redirectStdinStdout, $pipeType);
});
}
}<file_sep><?php
namespace Imi\Util\Traits\Aspect;
use Imi\Aop\AroundJoinPoint;
/**
* 处理 Swoole 协程客户端延迟收包
* 适合用于 Aop 切入相应方法时
*/
trait TDefer
{
private static $hasMulti = [];
public function parseDefer(AroundJoinPoint $joinPoint)
{
$client = $joinPoint->getTarget();
// 获取调用前的defer状态
$isDefer = $client->getDefer();
if(!$isDefer)
{
// 强制设为延迟收包
$client->setDefer(true);
}
// 调用原方法
if($joinPoint->proceed())
{
$lowerMethod = strtolower($joinPoint->getMethod());
$isRecv = true;
if($this->hasMulti($joinPoint->getTarget()))
{
if('exec' === $lowerMethod)
{
$this->setHasMulti($joinPoint->getTarget(), false);
}
else
{
$isRecv = false;
}
}
else
{
if('multi' === $lowerMethod)
{
$this->setHasMulti($joinPoint->getTarget(), true);
$isRecv = false;
}
}
if($isRecv)
{
// 接收结果
$result = $client->recv();
}
else
{
$result = true;
}
if(!$isDefer)
{
// 设为调用前状态
$client->setDefer(false);
}
return $result;
}
else
{
return false;
}
}
private function hasMulti($redis)
{
$hash = spl_object_hash($redis);
return static::$hasMulti[$hash] ?? false;
}
private function setHasMulti($redis, $has)
{
$hash = spl_object_hash($redis);
static::$hasMulti[$hash] = $has;
}
}<file_sep><?php
namespace Imi\Log\Handler;
use Imi\Bean\Annotation\Bean;
/**
* @Bean("ConsoleLog")
*/
class Console extends Base
{
/**
* 真正的保存操作实现
* @return void
*/
protected function __save()
{
foreach($this->records as $record)
{
echo $this->getLogString($record), PHP_EOL;
}
}
}<file_sep><?php
namespace Imi\Listener;
use Imi\App;
use Imi\Config;
use Imi\Worker;
use Imi\Util\File;
use Imi\Main\Helper;
use Imi\Util\Coroutine;
use Imi\Bean\Annotation;
use Imi\Pool\PoolConfig;
use Imi\Pool\PoolManager;
use Imi\Cache\CacheManager;
use Imi\Bean\Annotation\Listener;
use Imi\Util\CoroutineChannelManager;
use Imi\Server\Event\Param\WorkerStartEventParam;
use Imi\Server\Event\Listener\IWorkerStartEventListener;
/**
* @Listener(eventName="IMI.MAIN_SERVER.WORKER.START",priority=PHP_INT_MAX)
*/
class WorkerInit implements IWorkerStartEventListener
{
/**
* 事件处理方法
* @param EventParam $e
* @return void
*/
public function handle(WorkerStartEventParam $e)
{
$GLOBALS['WORKER_START_END_RESUME_COIDS'] = [];
// 清除当前 worker 进程的 Bean 类缓存
$path = Config::get('@app.beanClassCache', sys_get_temp_dir());
$path = File::path($path, 'imiBeanCache', $e->server->getSwooleServer()->worker_id);
foreach (File::enum($path) as $file)
{
if (is_file($file))
{
unlink($file);
}
}
// 当前进程的 WorkerID 设置
Worker::setWorkerID($e->server->getSwooleServer()->worker_id);
// 初始化 worker
App::initWorker();
}
}<file_sep><?php
namespace Imi\Util;
abstract class ClassObject
{
/**
* 是否是匿名类
* @param object $object
* @return boolean
*/
public static function isAnymous($object)
{
return strpos(get_class($object), 'class@anonymous') >= 0;
}
}<file_sep><?php
namespace Imi\Db\Query;
use Imi\Model\Model;
use Imi\Bean\BeanFactory;
use Imi\Db\Interfaces\IStatement;
use Imi\Db\Query\Interfaces\IResult;
class Result implements IResult
{
/**
* Statement
* @var IStatement
*/
private $statement;
/**
* 是否执行成功
* @var bool
*/
private $isSuccess;
/**
* 查询结果类的类名,为null则为数组
* @var string
*/
private $modelClass;
public function __construct($statement, $modelClass = null)
{
$this->modelClass = $modelClass;
if($statement instanceof IStatement)
{
$this->statement = clone $statement;
$this->isSuccess = '' === $this->statement->errorInfo();
}
else
{
$this->isSuccess = false;
}
}
/**
* SQL是否执行成功
* @return boolean
*/
public function isSuccess(): bool
{
return $this->isSuccess;
}
/**
* 获取最后插入的ID
* @return string
*/
public function getLastInsertId()
{
if(!$this->isSuccess)
{
throw new \RuntimeException('Result is not success!');
}
return $this->statement->lastInsertId();
}
/**
* 获取影响行数
* @return int
*/
public function getAffectedRows()
{
if(!$this->isSuccess)
{
throw new \RuntimeException('Result is not success!');
}
return $this->statement->rowCount();
}
/**
* 返回一行数据,数组或对象
* @param string $className 实体类名,为null则返回数组
* @return mixed
*/
public function get($className = null)
{
if(!$this->isSuccess)
{
throw new \RuntimeException('Result is not success!');
}
$result = $this->statement->fetch();
if(null === $className)
{
$className = $this->modelClass;
}
if(null === $className)
{
return $result;
}
else
{
if(is_subclass_of($className, Model::class))
{
$object = BeanFactory::newInstance($className, $result);
}
else
{
$object = BeanFactory::newInstance($className);
foreach($result as $k => $v)
{
$object->$k = $v;
}
}
return $object;
}
}
/**
* 返回数组
* @param string $className 实体类名,为null则数组每个成员为数组
* @return array
*/
public function getArray($className = null)
{
if(!$this->isSuccess)
{
throw new \RuntimeException('Result is not success!');
}
$result = $this->statement->fetchAll();
if(null === $className)
{
$className = $this->modelClass;
}
if(null === $className)
{
return $result;
}
else
{
$list = [];
$isModelClass = is_subclass_of($className, Model::class);
foreach($result as $item)
{
if($isModelClass)
{
$object = BeanFactory::newInstance($className, $item);
}
else
{
$object = $item;
}
$list[] = $object;
}
return $list;
}
}
/**
* 获取一列数据
* @return array
*/
public function getColumn($column = 0)
{
if(!$this->isSuccess)
{
throw new \RuntimeException('Result is not success!');
}
return $this->statement->fetchAll(\PDO::FETCH_COLUMN, $column);
}
/**
* 获取标量结果
* @param integer|string $columnKey
* @return mixed
*/
public function getScalar($columnKey = 0)
{
if(!$this->isSuccess)
{
throw new \RuntimeException('Result is not success!');
}
return $this->statement->fetchColumn();
}
/**
* 获取记录行数
* @return int
*/
public function getRowCount()
{
if(!$this->isSuccess)
{
throw new \RuntimeException('Result is not success!');
}
return count($this->statement->fetchAll());
}
}<file_sep><?php
namespace Imi\Tool\Listener;
use Imi\App;
use Imi\Util\Args;
use Imi\Main\Helper;
use Imi\Tool\ArgType;
use Imi\RequestContext;
use Imi\Bean\Annotation;
use Imi\Pool\PoolConfig;
use Imi\Event\EventParam;
use Imi\Pool\PoolManager;
use Imi\Cache\CacheManager;
use Imi\Tool\Annotation\Arg;
use Imi\Event\IEventListener;
use Imi\Tool\Parser\ToolParser;
use Imi\Bean\Annotation\Listener;
/**
* @Listener(eventName="IMI.INITED")
*/
class Init implements IEventListener
{
/**
* 事件处理方法
* @param EventParam $e
* @return void
*/
public function handle(EventParam $e)
{
try{
if(!isset($_SERVER['argv'][1]))
{
throw new \RuntimeException(sprintf('tool args error!'));
}
if(false === strpos($_SERVER['argv'][1], '/'))
{
throw new \RuntimeException(sprintf('tool name and operation not found!'));
}
$this->init();
// cli参数初始化
Args::init(2);
// 工具名/操作名
list($tool, $operation) = explode('/', $_SERVER['argv'][1]);
// 获取回调
$callable = ToolParser::getInstance()->getCallable($tool, $operation);
if(null === $callable)
{
Annotation::getInstance()->init([Helper::getMain(App::getNamespace())]);
}
$callable = ToolParser::getInstance()->getCallable($tool, $operation);
if(null === $callable)
{
throw new \RuntimeException(sprintf('tool %s does not exists!', $_SERVER['argv'][1]));
}
if(Args::get('h'))
{
// 帮助
$className = get_parent_class($callable[0]);
$refClass = new \ReflectionClass($className);
$required = [];
$other = [];
foreach(ToolParser::getInstance()->getData()['class'][$className]['Methods'][$callable[1]]['Args'] ?? [] as $arg)
{
if($arg->required)
{
$required[] = $arg;
}
else
{
$other[] = $arg;
}
}
echo '工具名称:', $tool, '/', $operation, PHP_EOL, PHP_EOL;
echo $this->parseComment($refClass->getMethod($callable[1])->getDocComment()), PHP_EOL;
if(isset($required[0]))
{
echo PHP_EOL, '必选参数:', PHP_EOL;
foreach($required as $arg)
{
echo '-', $arg->name, ' ', $arg->comments, PHP_EOL;
}
}
if(isset($other[0]))
{
echo PHP_EOL, '可选参数:', PHP_EOL;
foreach($other as $arg)
{
echo '-', $arg->name, ' ', $arg->comments, PHP_EOL;
}
}
}
else
{
// 执行参数
$args = $this->getCallToolArgs($callable, $tool, $operation);
// 执行工具操作
call_user_func_array($callable, $args);
swoole_event_wait();
}
}
catch(\Throwable $ex)
{
echo $ex->getMessage(), PHP_EOL;
}
}
/**
* 初始化
* @return void
*/
private function init()
{
RequestContext::create();
// 获取配置
$pools = $caches = [];
foreach(Helper::getMains() as $main)
{
$pools = array_merge($pools, $main->getConfig()['pools'] ?? []);
$caches = array_merge($caches, $main->getConfig()['caches'] ?? []);
}
// 同步池子初始化
foreach($pools as $name => $pool)
{
if(isset($pool['sync']))
{
$pool = $pool['sync'];
PoolManager::addName($name, $pool['pool']['class'], new PoolConfig($pool['pool']['config']), $pool['resource']);
}
}
// 缓存初始化
foreach($caches as $name => $cache)
{
CacheManager::addName($name, $cache['handlerClass'], $cache['option']);
}
}
/**
* 获取执行参数
* @param callable $callable
* @param string $tool
* @param string $operation
* @return array
*/
private function getCallToolArgs($callable, $tool, $operation)
{
$className = get_parent_class($callable[0]);
$methodRef = new \ReflectionMethod($className, $callable[1]);
$args = [];
foreach(ToolParser::getInstance()->getData()['class'][$className]['Methods'][$methodRef->name]['Args'] ?? [] as $annotation)
{
if(Args::exists($annotation->name))
{
$value = $this->parseArgValue(Args::get($annotation->name), $annotation);
}
else if($annotation->required)
{
throw new \InvalidArgumentException(sprintf('tool %s/%s param %s is required', $tool, $operation, $annotation->name));
}
else
{
$value = $annotation->default;
}
$args[] = $value;
}
return $args;
}
/**
* 处理参数值
* @param string $value
* @param Arg $annotation
* @return mixed
*/
private function parseArgValue($value, Arg $annotation)
{
switch($annotation->type)
{
case ArgType::STRING:
break;
case ArgType::INT:
$value = (int)$value;
break;
case ArgType::FLOAT:
case ArgType::DOUBLE:
$value = (float)$value;
break;
case ArgType::BOOL:
case ArgType::BOOLEAN:
$value = (bool)json_decode($value);
break;
case ArgType::ARRAY:
$value = explode(',', $value);
break;
}
return $value;
}
/**
* 处理注释
* @param string $content
* @return string
*/
private function parseComment($content)
{
return trim(preg_replace('/@.+\n/', '', preg_replace('/\/*\s*\*\s*\/*/', PHP_EOL, $content)));
}
}<file_sep><?php
namespace Imi\Util;
abstract class Text
{
/**
* 字符串是否以另一个字符串开头
* @param string $string
* @param string $compare
* @return string
*/
public static function startwith($string, $compare)
{
return 0 === strpos($string, $compare);
}
/**
* 字符串是否以另一个字符串结尾
* @param string $string
* @param string $compare
* @return string
*/
public static function endwith($string, $compare)
{
return substr($string, -strlen($compare)) === $compare;
}
/**
* 插入字符串
* @param string $string 原字符串
* @param int $position 位置
* @param string $insertString 被插入的字符串
* @return string
*/
public static function insert($string, $position, $insertString)
{
return substr_replace($string, $insertString, $position, 0);
}
/**
* 字符串是否为空字符串或者为null
* @param string $string
* @return boolean
*/
public static function isEmpty($string)
{
return '' === $string || null === $string;
}
/**
* 转为驼峰命名,会把下划线后字母转为大写
* @param string $name
* @return string
*/
public static function toCamelName($name)
{
return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $name))));
}
/**
* 转为每个单词大写的命名,会把下划线后字母转为大写
* @param string $name
* @return string
*/
public static function toPascalName($name)
{
return ucfirst(static::toCamelName($name));
}
}<file_sep><?php
namespace Imi\Redis\Aop;
use Imi\Aop\AroundJoinPoint;
use Imi\Aop\Annotation\Around;
use Imi\Aop\Annotation\Aspect;
use Imi\Aop\Annotation\PointCut;
use Imi\Util\Traits\Aspect\TDefer;
/**
* @Aspect
*/
class RedisAspect
{
use TDefer;
/**
* Redis 延迟收包
* @PointCut(
* allow={
* "Swoole\Coroutine\Redis::set",
* "Swoole\Coroutine\Redis::setBit",
* "Swoole\Coroutine\Redis::setEx",
* "Swoole\Coroutine\Redis::psetEx",
* "Swoole\Coroutine\Redis::lSet",
* "Swoole\Coroutine\Redis::get",
* "Swoole\Coroutine\Redis::mGet",
* "Swoole\Coroutine\Redis::del",
* "Swoole\Coroutine\Redis::hDel",
* "Swoole\Coroutine\Redis::hSet",
* "Swoole\Coroutine\Redis::hMSet",
* "Swoole\Coroutine\Redis::hSetNx",
* "Swoole\Coroutine\Redis::delete",
* "Swoole\Coroutine\Redis::mSet",
* "Swoole\Coroutine\Redis::mSetNx",
* "Swoole\Coroutine\Redis::getKeys",
* "Swoole\Coroutine\Redis::keys",
* "Swoole\Coroutine\Redis::exists",
* "Swoole\Coroutine\Redis::type",
* "Swoole\Coroutine\Redis::strLen",
* "Swoole\Coroutine\Redis::lPop",
* "Swoole\Coroutine\Redis::blPop",
* "Swoole\Coroutine\Redis::rPop",
* "Swoole\Coroutine\Redis::brPop",
* "Swoole\Coroutine\Redis::bRPopLPush",
* "Swoole\Coroutine\Redis::lSize",
* "Swoole\Coroutine\Redis::lLen",
* "Swoole\Coroutine\Redis::sSize",
* "Swoole\Coroutine\Redis::scard",
* "Swoole\Coroutine\Redis::sPop",
* "Swoole\Coroutine\Redis::sMembers",
* "Swoole\Coroutine\Redis::sGetMembers",
* "Swoole\Coroutine\Redis::sRandMember",
* "Swoole\Coroutine\Redis::persist",
* "Swoole\Coroutine\Redis::ttl",
* "Swoole\Coroutine\Redis::pttl",
* "Swoole\Coroutine\Redis::zCard",
* "Swoole\Coroutine\Redis::zSize",
* "Swoole\Coroutine\Redis::hLen",
* "Swoole\Coroutine\Redis::hKeys",
* "Swoole\Coroutine\Redis::hVals",
* "Swoole\Coroutine\Redis::hGetAll",
* "Swoole\Coroutine\Redis::debug",
* "Swoole\Coroutine\Redis::restore",
* "Swoole\Coroutine\Redis::dump",
* "Swoole\Coroutine\Redis::renameKey",
* "Swoole\Coroutine\Redis::rename",
* "Swoole\Coroutine\Redis::renameNx",
* "Swoole\Coroutine\Redis::rpoplpush",
* "Swoole\Coroutine\Redis::randomKey",
* "Swoole\Coroutine\Redis::ping",
* "Swoole\Coroutine\Redis::auth",
* "Swoole\Coroutine\Redis::unwatch",
* "Swoole\Coroutine\Redis::watch",
* "Swoole\Coroutine\Redis::save",
* "Swoole\Coroutine\Redis::bgSave",
* "Swoole\Coroutine\Redis::lastSave",
* "Swoole\Coroutine\Redis::flushDB",
* "Swoole\Coroutine\Redis::flushAll",
* "Swoole\Coroutine\Redis::dbSize",
* "Swoole\Coroutine\Redis::bgrewriteaof",
* "Swoole\Coroutine\Redis::time",
* "Swoole\Coroutine\Redis::role",
* "Swoole\Coroutine\Redis::setRange",
* "Swoole\Coroutine\Redis::setNx",
* "Swoole\Coroutine\Redis::getSet",
* "Swoole\Coroutine\Redis::append",
* "Swoole\Coroutine\Redis::lPushx",
* "Swoole\Coroutine\Redis::lPush",
* "Swoole\Coroutine\Redis::rPush",
* "Swoole\Coroutine\Redis::rPushx",
* "Swoole\Coroutine\Redis::sContains",
* "Swoole\Coroutine\Redis::sismember",
* "Swoole\Coroutine\Redis::zScore",
* "Swoole\Coroutine\Redis::zRank",
* "Swoole\Coroutine\Redis::zRevRank",
* "Swoole\Coroutine\Redis::hGet",
* "Swoole\Coroutine\Redis::hMGet",
* "Swoole\Coroutine\Redis::hExists",
* "Swoole\Coroutine\Redis::publish",
* "Swoole\Coroutine\Redis::zIncrBy",
* "Swoole\Coroutine\Redis::zAdd",
* "Swoole\Coroutine\Redis::zDeleteRangeByScore",
* "Swoole\Coroutine\Redis::zRemRangeByScore",
* "Swoole\Coroutine\Redis::zCount",
* "Swoole\Coroutine\Redis::zRange",
* "Swoole\Coroutine\Redis::zRevRange",
* "Swoole\Coroutine\Redis::zRangeByScore",
* "Swoole\Coroutine\Redis::zRevRangeByScore",
* "Swoole\Coroutine\Redis::zRangeByLex",
* "Swoole\Coroutine\Redis::zRevRangeByLex",
* "Swoole\Coroutine\Redis::zInter",
* "Swoole\Coroutine\Redis::zinterstore",
* "Swoole\Coroutine\Redis::zUnion",
* "Swoole\Coroutine\Redis::zunionstore",
* "Swoole\Coroutine\Redis::incrBy",
* "Swoole\Coroutine\Redis::hIncrBy",
* "Swoole\Coroutine\Redis::incr",
* "Swoole\Coroutine\Redis::decrBy",
* "Swoole\Coroutine\Redis::decr",
* "Swoole\Coroutine\Redis::getBit",
* "Swoole\Coroutine\Redis::lInsert",
* "Swoole\Coroutine\Redis::lGet",
* "Swoole\Coroutine\Redis::lIndex",
* "Swoole\Coroutine\Redis::setTimeout",
* "Swoole\Coroutine\Redis::expire",
* "Swoole\Coroutine\Redis::pexpire",
* "Swoole\Coroutine\Redis::expireAt",
* "Swoole\Coroutine\Redis::pexpireAt",
* "Swoole\Coroutine\Redis::move",
* "Swoole\Coroutine\Redis::select",
* "Swoole\Coroutine\Redis::getRange",
* "Swoole\Coroutine\Redis::listTrim",
* "Swoole\Coroutine\Redis::ltrim",
* "Swoole\Coroutine\Redis::lGetRange",
* "Swoole\Coroutine\Redis::lRange",
* "Swoole\Coroutine\Redis::lRem",
* "Swoole\Coroutine\Redis::lRemove",
* "Swoole\Coroutine\Redis::zDeleteRangeByRank",
* "Swoole\Coroutine\Redis::zRemRangeByRank",
* "Swoole\Coroutine\Redis::incrByFloat",
* "Swoole\Coroutine\Redis::hIncrByFloat",
* "Swoole\Coroutine\Redis::bitCount",
* "Swoole\Coroutine\Redis::bitOp",
* "Swoole\Coroutine\Redis::sAdd",
* "Swoole\Coroutine\Redis::sMove",
* "Swoole\Coroutine\Redis::sDiff",
* "Swoole\Coroutine\Redis::sDiffStore",
* "Swoole\Coroutine\Redis::sUnion",
* "Swoole\Coroutine\Redis::sUnionStore",
* "Swoole\Coroutine\Redis::sInter",
* "Swoole\Coroutine\Redis::sInterStore",
* "Swoole\Coroutine\Redis::sRemove",
* "Swoole\Coroutine\Redis::srem",
* "Swoole\Coroutine\Redis::zDelete",
* "Swoole\Coroutine\Redis::zRemove",
* "Swoole\Coroutine\Redis::zRem",
* "Swoole\Coroutine\Redis::pSubscribe",
* "Swoole\Coroutine\Redis::subscribe",
* "Swoole\Coroutine\Redis::multi",
* "Swoole\Coroutine\Redis::exec",
* "Swoole\Coroutine\Redis::eval",
* "Swoole\Coroutine\Redis::evalSha",
* "Swoole\Coroutine\Redis::script"
* }
* )
* @Around
* @return mixed
*/
public function defer(AroundJoinPoint $joinPoint)
{
return $this->parseDefer($joinPoint);
}
}<file_sep><?php
namespace Imi\Tool\Tools\Process;
use Imi\App;
use Imi\Util\Args;
use Imi\Tool\ArgType;
use Imi\Tool\Annotation\Arg;
use Imi\Tool\Annotation\Tool;
use Imi\Process\ProcessManager;
use Imi\Tool\Annotation\Operation;
/**
* @Tool("process")
*/
class Process
{
/**
* 开启一个进程,可以任意添加参数
*
* @Operation("start")
*
* @Arg(name="name", type=ArgType::STRING, required=true, comments="进程名称,通过@Process注解定义")
* @Arg(name="redirectStdinStdout", type=ArgType::STRING, default=null, comments="重定向子进程的标准输入和输出。启用此选项后,在子进程内输出内容将不是打印屏幕,而是写入到主进程管道。读取键盘输入将变为从管道中读取数据。默认为阻塞读取。")
* @Arg(name="pipeType", type=ArgType::STRING, default=null, comments="管道类型,启用$redirectStdinStdout后,此选项将忽略用户参数,强制为1。如果子进程内没有进程间通信,可以设置为 0")
*
* @return void
*/
public function start($name, $redirectStdinStdout, $pipeType)
{
App::initWorker();
$args = Args::get();
$process = ProcessManager::create($name, $args, $redirectStdinStdout, $pipeType);
$process->start();
$result = \swoole_process::wait(true);
echo 'process exit! pid:', $result['pid'], ', code:', $result['code'], ', signal:', $result['signal'], PHP_EOL;
}
}<file_sep><?php
namespace Imi\Util;
abstract class ArrayUtil
{
/**
* 从数组中移除一个元素
* @param array $array
* @param mixed $value
* @return array
*/
public static function remove($array, $value)
{
$index = array_search($array, $value);
if(false !== $index)
{
return array_splice($array, $index, 1);
}
else
{
return $array;
}
}
/**
* 多维数组递归合并
* @param array ...$arrays
* @return array
*/
public static function recursiveMerge(...$arrays)
{
$merged = array ();
foreach($arrays as $array)
{
if (!is_array($array))
{
continue;
}
foreach ( $array as $key => $value )
{
if (is_string ( $key ))
{
if (is_array ( $value ) && isset($merged[$key]) && is_array ( $merged [$key] ))
{
$merged [$key] = static::recursiveMerge ( $merged [$key], $value );
}
else
{
$merged [$key] = $value;
}
}
else
{
$merged [] = $value;
}
}
}
return $merged;
}
/**
* 将二维数组第二纬某key变为一维的key
* @param array $array 原数组
* @param string $column 列名
* @param boolean $keepOld 是否保留列名,默认保留
*/
public static function columnToKey(&$array, $column, $keepOld = true)
{
$s = count($array);
for($i = 0; $i < $s; ++$i)
{
$array[$array[$i][$column]] = $array[$i];
if(!$keepOld)
{
unset($array[$i]);
}
}
}
/**
* 判断数组是否为关联数组
* @param array $array
* @return bool
*/
public static function isAssoc($array)
{
return array_keys($array) !== range(0, count($array) - 1);
}
}<file_sep><?php
namespace Imi\Util;
use Imi\App;
use Imi\Main\Helper;
use Imi\Bean\BeanProxy;
use Imi\Bean\Parser\BeanParser;
/**
* 框架里杂七杂八的各种工具方法
*/
abstract class Imi
{
/**
* 处理规则,暂只支持通配符*
* @param string $rule
* @return string
*/
public static function parseRule($rule)
{
return \str_replace('\\*', '.*', \preg_quote($rule));
}
/**
* 检查规则是否匹配,支持通配符*
* @param string $rule
* @param string $string
* @return boolean
*/
public static function checkRuleMatch($rule, $string)
{
$rule = '/^' . static::parseRule($rule) . '$/';
return \preg_match($rule, $string) > 0;
}
/**
* 检查类和方法是否匹配,支持通配符*
* @param string $rule
* @param string $className
* @param string $methodName
* @return boolean
*/
public static function checkClassMethodRule($rule, $className, $methodName)
{
list($classRule, $methodRule) = explode('::', $rule, 2);
return static::checkRuleMatch($classRule, $className) && static::checkRuleMatch($methodRule, $methodName);
}
/**
* 检查类是否匹配,支持通配符*
* @param string $rule
* @param string $className
* @return boolean
*/
public static function checkClassRule($rule, $className)
{
list($classRule, ) = explode('::', $rule, 2);
return static::checkRuleMatch($classRule, $className);
}
/**
* 检查验证比较规则集
* @param string|array $rules
* @param callable $valueCallback
* @return boolean
*/
public static function checkCompareRules($rules, $valueCallback)
{
foreach(is_array($rules) ? $rules : [$rules] as $fieldName => $rule)
{
if(is_numeric($fieldName))
{
if(!static::checkCompareRule($rule, $valueCallback))
{
return false;
}
}
else if(preg_match('/^' . $rule . '$/', call_user_func($valueCallback, $fieldName)) <= 0)
{
return false;
}
}
return true;
}
/**
* 检查验证比较规则,如果符合规则返回bool,不符合规则返回null
* id=1
* id!=1 id<>1
* id
* !id
* @param string $rule
* @param callable $valueCallback
* @return boolean
*/
public static function checkCompareRule($rule, $valueCallback)
{
if(isset($rule[0]) && '!' === $rule[0])
{
// 不应该存在参数支持
return null === call_user_func($valueCallback, substr($rule, 1));
}
else if(preg_match('/([^!<=]+)(!=|<>|=)(.+)/', $rule, $matches) > 0)
{
$value = call_user_func($valueCallback, $matches[1]);
switch($matches[2])
{
case '!=':
case '<>':
return null !== $value && $value != $matches[3];
case '=':
return $value == $matches[3];
default:
return false;
}
}
else
{
return null !== call_user_func($valueCallback, $rule);
}
}
/**
* 检查验证比较值集
* @param string|array $rules
* @param mixed $value
* @return boolean
*/
public static function checkCompareValues($rules, $value)
{
foreach(is_array($rules) ? $rules : [$rules] as $rule)
{
if(!static::checkCompareValue($rule, $value))
{
return false;
}
}
return true;
}
/**
* 检查验证比较值
* @param string|array $rule
* @param mixed $value
* @return boolean
*/
public static function checkCompareValue($rule, $value)
{
if(isset($rule[0]) && '!' === $rule[0])
{
// 不等
return $value !== $rule;
}
else
{
// 相等
return $value === $rule;
}
}
/**
* 处理按.分隔的规则文本,支持\.转义不分隔
* @param string $rule
*/
public static function parseDotRule($rule)
{
$result = preg_split('#(?<!\\\)\.#', $rule);
array_walk($result, function(&$value, $key){
if(false !== strpos($value,'\.'))
{
$value = str_replace('\.', '.', $value);
}
});
return $result;
}
/**
* 获取类短名称
* @param string $className
* @return string
*/
public static function getClassShortName(string $className)
{
return implode('', array_slice(explode('\\', $className), -1));
}
/**
* 根据命名空间获取真实路径
* @param string $namespace
* @return string
*/
public static function getNamespacePath($namespace)
{
$appNamespace = App::getNamespace();
$appMain = Helper::getMain($appNamespace);
$refClass = new \ReflectionClass($appMain);
$path = dirname($refClass->getFileName());
$namespaceSubPath = substr($namespace, strlen($appNamespace));
return File::path($path, str_replace('\\', DIRECTORY_SEPARATOR, $namespaceSubPath));
}
/**
* 获取类属性的值,支持传入Bean名称
*
* @param string $className
* @param string $propertyName
* @return mixed
*/
public static function getClassPropertyValue($className, $propertyName)
{
$value = BeanProxy::getInjectValue($className, $propertyName);
if(null === $value)
{
if(!class_exists($className))
{
$className = BeanParser::getInstance()->getData()[$className]['className'];
}
$ref = new \ReflectionClass($className);
$value = $ref->getDefaultProperties()[$propertyName] ?? null;
}
return $value;
}
} | 03a6443b54161c60dd5d0b0e86a2755b23631a0b | [
"PHP"
] | 14 | PHP | skymysky/IMI | e3d1a3f294ef7a4442fd54870221d47c52ec64d0 | 6c625b26309074bf231aeb1febc752f5ec91d167 | |
refs/heads/master | <file_sep>#include <stdlib.h>
#include <stdio.h>
#include "ins_def.h"
#include "proc.h"
#include "rt.h"
#include "bc.h"
#include "stk.h"
#include "object.h"
#include "var.h"
#include "var_ops.h"
#include "pc.h"
#include "helper.h"
/* Initializes INS_DEF with pointers to each instructions function
* Populates INS_DEF
*/
void init_ins_def( void )
{
INS_DEC(0x00, _ins_def_NULL, "NULL");
INS_DEC(0x01, _ins_def_SYNC, "SYNC");
INS_DEC(0x02, _ins_def_PRINT, "PRINT");
INS_DEC(0x03, _ins_def_DEBUG, "DEBUG");
INS_DEC(0x0E, _ins_def_ARGB, "ARGB");
INS_DEC(0x0F, _ins_def_LIBC, "LIBC");
INS_DEC(0x10, _ins_def_POP, "POP");
INS_DEC(0x11, _ins_def_ROT, "ROT");
INS_DEC(0x12, _ins_def_DUP, "DUP");
INS_DEC(0x13, _ins_def_ROT_THREE, "ROT_THREE");
INS_DEC(0x20, _ins_def_DEC, "DEC");
INS_DEC(0x21, _ins_def_LOV, "LOV");
INS_DEC(0x22, _ins_def_STV, "STV");
INS_DEC(0x23, _ins_def_CTV, "CTV");
INS_DEC(0x24, _ins_def_CTS, "CTS");
INS_DEC(0x30, _ins_def_TYPEOF, "TYPEOF");
INS_DEC(0x31, _ins_def_CAST, "CAST");
INS_DEC(0x40, _ins_def_ADD, "ADD");
INS_DEC(0x41, _ins_def_SUB, "SUB");
INS_DEC(0x42, _ins_def_MULT, "MULT");
INS_DEC(0x43, _ins_def_DIV, "DIV");
INS_DEC(0x44, _ins_def_POW, "POW");
INS_DEC(0x45, _ins_def_BRT, "BRT");
INS_DEC(0x46, _ins_def_SIN, "SIN");
INS_DEC(0x47, _ins_def_COS, "COS");
INS_DEC(0x48, _ins_def_TAN, "TAN");
INS_DEC(0x49, _ins_def_ISIN, "ISIN");
INS_DEC(0x4A, _ins_def_ICOS, "ICOS");
INS_DEC(0x4B, _ins_def_ITAN, "ITAN");
INS_DEC(0x4C, _ins_def_MOD, "MOD");
INS_DEC(0x4D, _ins_def_BOR, "BOR");
INS_DEC(0x4E, _ins_def_BXOR, "BXOR");
INS_DEC(0x4F, _ins_def_BNAND, "BNAND");
INS_DEC(0x50, _ins_def_GTHAN, "GTHAN");
INS_DEC(0x51, _ins_def_LTHAN, "LTHAN");
INS_DEC(0x52, _ins_def_GTHAN_EQ, "GTHAN_EQ");
INS_DEC(0x53, _ins_def_LTHAN_EQ, "LTHAN_EQ");
INS_DEC(0x54, _ins_def_EQ, "EQ");
INS_DEC(0x55, _ins_def_NEQ, "NEQ");
INS_DEC(0x56, _ins_def_NOT, "NOT");
INS_DEC(0x57, _ins_def_OR, "OR");
INS_DEC(0x58, _ins_def_AND, "AND");
INS_DEC(0x60, _ins_def_STARTL, "STARTL");
INS_DEC(0x61, _ins_def_CLOOP, "CLOOP");
INS_DEC(0x6E, _ins_def_BREAK, "BREAK");
INS_DEC(0x6F, _ins_def_ENDL, "ENDL");
INS_DEC(0x70, _ins_def_GOTO, "GOTO");
INS_DEC(0x71, _ins_def_JUMPF, "JUMPF");
INS_DEC(0x72, _ins_def_IFDO, "IFDO");
INS_DEC(0x73, _ins_def_ELSE, "ELSE");
INS_DEC(0x7E, _ins_def_DONE, "DONE");
INS_DEC(0x7F, _ins_def_CALL, "CALL");
INS_DEC(0x80, _ins_def_GETN, "GETN");
INS_DEC(0x81, _ins_def_SETN, "SETN");
INS_DEC(0x82, _ins_def_CALLM, "CALLM");
INS_DEC(0x83, _ins_def_INDEXO, "INDEXO");
INS_DEC(0x84, _ins_def_MODO, "MODO");
INS_DEC(0xF0, _ins_def_RETURN, "RETURN");
INS_DEC(0xF1, _ins_def_NEW, "NEW");
INS_DEC(0xF2, _ins_def_ENDCLASS, "ENDCLASS");
INS_DEC(0xFE, _ins_def_DECLASS, "DECLASS");
INS_DEC(0xFF, _ins_def_DEFUN, "DEFUN");
}
int ins_def_is_valid(bc_cont* line)
{
int rv = 0;
if (INS_DEF[line->op] != NULL)
{
rv = 1;
}
return rv;
}
inline void run_ins(rt_t* ctx, bc_cont* line)
{
INS_DEF[line->op](ctx, line);
}
void _ins_def_NULL (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_SYNC (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_PRINT (rt_t* ctx, bc_cont* line)
{
var_cont* var = stk_pop(ctx->stack);
var_pprint(var);
pc_inc(ctx->pc, 1);
}
void _ins_def_DEBUG (rt_t* ctx, bc_cont* line)
{
ctx->db = 0 ? ctx->db : 1;
pc_inc(ctx->pc, 1);
}
void _ins_def_ARGB (rt_t* ctx, bc_cont* line)
{
var_cont* var = stk_pop(ctx->stack);
stk_push(ctx->argstk, var);
pc_inc(ctx->pc, 1);
}
void _ins_def_LIBC (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_POP (rt_t* ctx, bc_cont* line)
{
int n = var_data_get_G_INT(line->varg[0]);
int i = 0;
while (n > i)
{
i++;
stk_pop(ctx->stack);
}
pc_inc(ctx->pc, 1);
}
void _ins_def_ROT (rt_t* ctx, bc_cont* line)
{
stk_rot_top(ctx->stack);
pc_inc(ctx->pc, 1);
}
void _ins_def_DUP (rt_t* ctx, bc_cont* line)
{
var_cont* var = stk_at(ctx->stack, 0);
var_cont* dup = var_data_cpy(var);
stk_push(ctx->stack, dup);
pc_inc(ctx->pc, 1);
}
void _ins_def_ROT_THREE(rt_t* ctx, bc_cont* line)
{
stk_rot_three(ctx->stack);
pc_inc(ctx->pc, 1);
}
void _ins_def_DEC (rt_t* ctx, bc_cont* line)
{
int scope = var_data_get_G_INT(line->varg[0]);
b_type type = var_data_get_TYPE(line->varg[1]);
int name = var_data_get_G_INT(line->varg[2]);
proc_decvar(ctx, type, scope, name);
pc_inc(ctx->pc, 1);
}
void _ins_def_LOV (rt_t* ctx, bc_cont* line)
{
int scope = var_data_get_G_INT(line->varg[0]);
int name = var_data_get_G_INT(line->varg[1]);
var_cont* var;
var = proc_getvar(ctx, scope, name);
stk_push(ctx->stack, var);
pc_inc(ctx->pc, 1);
}
void _ins_def_STV (rt_t* ctx, bc_cont* line)
{
int scope = var_data_get_G_INT(line->varg[0]);
int name = var_data_get_G_INT(line->varg[1]);
var_cont* var = stk_pop(ctx->stack);
var_cont* ovr = proc_getvar(ctx, scope, name);
var_cont* set = var_data_cpy(var);
set->ownership = ovr->ownership;
proc_setvar(ctx, scope, name, set);
pc_inc(ctx->pc, 1);
}
void _ins_def_CTV (rt_t* ctx, bc_cont* line)
{
int name = var_data_get_G_INT(line->varg[0]);
int scope = var_data_get_G_INT(line->varg[1]);
var_cont* new = var_data_cpy(line->varg[2]);
proc_setvar(ctx, scope, name, new);
pc_inc(ctx->pc, 1);
}
void _ins_def_CTS (rt_t* ctx, bc_cont* line)
{
//var_cont* new = var_data_cpy(line->varg[0]);
stk_push(ctx->stack, line->varg[0]);
pc_inc(ctx->pc, 1);
}
void _ins_def_TYPEOF (rt_t* ctx, bc_cont* line)
{
var_cont* var = stk_at(ctx->stack, 0);
var_cont* new = var_new(TYPE);
var_data_type* data = var_data_alloc_TYPE(var->type);
var_set(new, data, TYPE);
stk_push(ctx->stack, new);
pc_inc(ctx->pc, 1);
}
void _ins_def_CAST (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_ADD (rt_t* ctx, bc_cont* line)
{
var_cont* A = stk_pop(ctx->stack);
var_cont* B = stk_pop(ctx->stack);
var_cont* var = var_add(A, B);
stk_push(ctx->stack, var);
pc_inc(ctx->pc, 1);
}
void _ins_def_SUB (rt_t* ctx, bc_cont* line)
{
var_cont* A = stk_pop(ctx->stack);
var_cont* B = stk_pop(ctx->stack);
var_cont* var = var_sub(A, B);
stk_push(ctx->stack, var);
pc_inc(ctx->pc, 1);
}
void _ins_def_MULT (rt_t* ctx, bc_cont* line)
{
var_cont* A = stk_pop(ctx->stack);
var_cont* B = stk_pop(ctx->stack);
var_cont* var = var_mult(A, B);
stk_push(ctx->stack, var);
pc_inc(ctx->pc, 1);
}
void _ins_def_DIV (rt_t* ctx, bc_cont* line)
{
var_cont* A = stk_pop(ctx->stack);
var_cont* B = stk_pop(ctx->stack);
var_cont* var = var_div(A, B);
stk_push(ctx->stack, var);
pc_inc(ctx->pc, 1);
}
void _ins_def_POW (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_BRT (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_SIN (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_COS (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_TAN (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_ISIN (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_ICOS (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_ITAN (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_MOD (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_BOR (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_BXOR (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_BNAND (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_GTHAN (rt_t* ctx, bc_cont* line)
{
var_cont* A = stk_pop(ctx->stack);
var_cont* B = stk_pop(ctx->stack);
var_cont* C = var_gthan(A, B);
stk_push(ctx->stack, C);
pc_inc(ctx->pc, 1);
}
void _ins_def_LTHAN (rt_t* ctx, bc_cont* line)
{
var_cont* A = stk_pop(ctx->stack);
var_cont* B = stk_pop(ctx->stack);
var_cont* C = var_lthan(A, B);
stk_push(ctx->stack, C);
pc_inc(ctx->pc, 1);
}
void _ins_def_GTHAN_EQ (rt_t* ctx, bc_cont* line)
{
var_cont* A = stk_pop(ctx->stack);
var_cont* B = stk_pop(ctx->stack);
var_cont* C = var_gthan_eq(A, B);
stk_push(ctx->stack, C);
pc_inc(ctx->pc, 1);
}
void _ins_def_LTHAN_EQ (rt_t* ctx, bc_cont* line)
{
var_cont* A = stk_pop(ctx->stack);
var_cont* B = stk_pop(ctx->stack);
var_cont* C = var_gthan_eq(A, B);
stk_push(ctx->stack, C);
pc_inc(ctx->pc, 1);
}
void _ins_def_EQ (rt_t* ctx, bc_cont* line)
{
var_cont* A = stk_pop(ctx->stack);
var_cont* B = stk_pop(ctx->stack);
var_cont* C = var_eq(A, B);
stk_push(ctx->stack, C);
pc_inc(ctx->pc, 1);
}
void _ins_def_NEQ (rt_t* ctx, bc_cont* line)
{
var_cont* A = stk_pop(ctx->stack);
var_cont* B = stk_pop(ctx->stack);
var_cont* C = var_eq(A, B);
C = var_not(C);
stk_push(ctx->stack, C);
pc_inc(ctx->pc, 1);
}
void _ins_def_NOT (rt_t* ctx, bc_cont* line)
{
var_cont* A = stk_pop(ctx->stack);
var_cont* C = var_not(A);
stk_push(ctx->stack, C);
pc_inc(ctx->pc, 1);
}
void _ins_def_OR (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_AND (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
/* HELPER FUNCTIONS */
void _ins_def_loop_break(rt_t* ctx)
{
while (pc_safe(ctx->pc))
{
pc_update(ctx->pc);
pc_inc(ctx->pc, 1);
if (ctx->pc->line->op == 0x6F)
{
break;
}
}
}
/* END HELPER FUNCIONS */
void _ins_def_STARTL (rt_t* ctx, bc_cont* line)
{
pc_branch(ctx->pc, ctx->pc->address);
pc_inc(ctx->pc, 1);
}
void _ins_def_CLOOP (rt_t* ctx, bc_cont* line)
{
var_cont* var = stk_pop(ctx->stack);
int value = var_data_get_G_INT(var);
if (value < 1)
{
pc_return(ctx->pc);
_ins_def_loop_break(ctx);
} else
{
pc_inc(ctx->pc, 1);
}
}
void _ins_def_BREAK (rt_t* ctx, bc_cont* line)
{
pc_return(ctx->pc);
_ins_def_loop_break(ctx);
}
void _ins_def_ENDL (rt_t* ctx, bc_cont* line)
{
pc_return(ctx->pc);
}
/* HELPER FUNCTIONS */
void _ins_def_branch_to_end_if(rt_t* ctx)
{
int level = 0;
while (pc_safe(ctx->pc))
{
pc_inc(ctx->pc, 1);
pc_update(ctx->pc);
// Is this instruction another IF statement?
if (ctx->pc->line->op == 0x72)
{
// Increment the if statement depth counter
level++;
} else
// Is the instruction an ELSE statement?
if (ctx->pc->line->op == 0x73)
{
// We're done here if we're in our scope
if (level == 0) break;
} else
// Is the instruction a DONE statement?
if (ctx->pc->line->op == 0x7E)
{
// And we're not in another if statement, we're done here
if (level == 0) break;
level--;
}
}
pc_inc(ctx->pc, 1);
}
/* END HELPER FUNCTIONS */
void _ins_def_GOTO (rt_t* ctx, bc_cont* line)
{
int value = var_data_get_G_INT(line->varg[0]);
pc_branch(ctx->pc, value);
}
void _ins_def_JUMPF (rt_t* ctx, bc_cont* line)
{
int value = var_data_get_G_INT(line->varg[0]);
pc_inc(ctx->pc, value);
}
void _ins_def_IFDO (rt_t* ctx, bc_cont* line)
{
// Get the value off the stack
var_cont* var = stk_pop(ctx->stack);
int value = var_data_get_G_INT(var);
// If the value is false, find an ELSE statement or DONE statement.
if (value < 1)
{
_ins_def_branch_to_end_if(ctx);
} else
{
pc_inc(ctx->pc, 1);
}
}
void _ins_def_ELSE (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
_ins_def_branch_to_end_if(ctx);
}
void _ins_def_DONE (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_CALL (rt_t* ctx, bc_cont* line)
{
int scope = var_data_get_G_INT(line->varg[0]);
int name = var_data_get_G_INT(line->varg[1]);
// Call the function
proc_function_call(ctx, scope, name);
pc_inc(ctx->pc, 1);
}
void _ins_def_GETN (rt_t* ctx, bc_cont* line)
{
int name = var_data_get_G_INT(line->varg[0]);
var_cont* obj = stk_pop(ctx->stack);
ns_t* object = object_get(obj);
var_cont* var = object_get_name(object, name);
stk_push(ctx->stack, var);
pc_inc(ctx->pc, 1);
}
void _ins_def_SETN (rt_t* ctx, bc_cont* line)
{
int name = var_data_get_G_INT(line->varg[0]);
var_cont* obj = stk_pop(ctx->stack);
var_cont* var = stk_pop(ctx->stack);
ns_t* object = object_get(obj);
var_cont* set = var_data_cpy(var);
object_set_name(object, name, set);
pc_inc(ctx->pc, 1);
}
void _ins_def_CALLM (rt_t* ctx, bc_cont* line)
{
int name = var_data_get_G_INT(line->varg[0]);
// Pop the stack to get the object
var_cont* obj = stk_pop(ctx->stack);
// Get the objects variable data
ns_t* object = object_get(obj);
// Get the method to call
var_cont* var = object_get_name(object, name);
var_data_func* func = var_data_get_FUNC(var);
// Push current namespace context
ns_ctx_push(ctx->varctx, ctx->vars);
// Set current namespace to objects namespace
ctx->vars = object;
// Call the function
proc_function_call_handle(ctx, func);
// Update the program counter
pc_update(ctx->pc);
// Run code here so we can pop the namespace context
proc_run_to_return(ctx);
// Pop the namespace context
ctx->vars = ns_ctx_pop(ctx->varctx);
pc_inc(ctx->pc, 1);
}
void _ins_def_INDEXO (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_MODO (rt_t* ctx, bc_cont* line)
{
pc_inc(ctx->pc, 1);
}
void _ins_def_RETURN (rt_t* ctx, bc_cont* line)
{
// Pop a level in the stack and arguement stack
stk_poplevel(&ctx->stack);
stk_poplevel(&ctx->argstk);
// Pop the namespace and get the return value
var_cont* return_value = ns_pop(ctx->vars);
if (return_value->type != VOID)
{
// Push the return value to the stack
stk_push(ctx->stack, return_value);
}
else
{
var_del(return_value);
}
// Return to the callee
pc_return(ctx->pc);
}
void _ins_def_NEW (rt_t* ctx, bc_cont* line)
{
int scope = var_data_get_G_INT(line->varg[0]);
int name = var_data_get_G_INT(line->varg[1]);
// Get the object builder
var_cont* var = proc_getvar(ctx, scope, name);
var_data_objbldr* builder = var_data_get_OBJBLDR(var);
// Init a new namespace of proper size
ns_t* new_ns = ns_init(builder->size);
// Push current namespace to namespace context
ns_ctx_push(ctx->varctx, ctx->vars);
// Set the current namespace to new namespace
ctx->vars = new_ns;
int offset = 1;
int i;
for (i = 0; i < builder->paramlen; i++)
{
// Pop the arguement stack
var_cont* arg = stk_pop(ctx->argstk);
// Is the arguement of the right type?
ASSERT(arg->type == builder->param[i], "Invalid arguement stack\n");
// Declare the name in the new namespace and pass the arguements
ns_dec(ctx->vars, arg->type, 0, i+offset);
ns_set(ctx->vars, 0, i+offset, arg);
}
// Push new stack levels for the stack and the arguement stack
stk_newlevel(&ctx->stack);
stk_newlevel(&ctx->argstk);
pc_branch(ctx->pc, builder->loc);
}
void _ins_def_ENDCLASS (rt_t* ctx, bc_cont* line)
{
var_cont* new = var_new(OBJECT);
var_set(new, ctx->vars, OBJECT);
ns_dec(ctx->vars, OBJECT, 1, 0);
ns_set(ctx->vars, 1, 0, new);
stk_poplevel(&ctx->stack);
stk_poplevel(&ctx->argstk);
ctx->vars = ns_ctx_pop(ctx->varctx);
stk_push(ctx->stack, new);
pc_return(ctx->pc);
pc_inc(ctx->pc, 1);
}
void _ins_def_DENS (rt_t* ctx, bc_cont* line)
{
int name = var_data_get_G_INT(line->varg[0]);
ns_t* namespace = ns_init(MAXIMUM_TRACKING_VARS);
var_cont* ns_var = var_new(OBJECT);
var_set(ns_var, namespace, OBJECT);
ns_dec(ctx->names, OBJECT, 1, name);
ns_set(ctx->names, 1, name, ns_var);
ctx->vars = namespace;
}
void _ins_def_DECLASS (rt_t* ctx, bc_cont* line)
{
int name = var_data_get_G_INT(line->varg[0]);
b_type* args = var_data_get_PLIST(line->varg[1]);
size_t alen = line->sarg[1];
// Create a new variable for the object builder
var_cont* obj = var_new(OBJBLDR);
// Allocate memory for this variable
var_data_objbldr* data = var_data_alloc_OBJBLDR();
// Set this objects ID
data->id = name;
// Set the location
data->loc = line->real_addr + 1;
/* Determine namespace size for this object
*/
int nsize;
for (nsize = 0; pc_safe(ctx->pc);)
{
// Are we at the end of the object builder?
if (ctx->pc->line->op == 0xF2)
{
break;
} else
// Are we declaring a variable or function?
if (ctx->pc->line->op == 0x20 || ctx->pc->line->op == 0xFF)
{
nsize++;
}
pc_inc(ctx->pc, 1);
pc_update(ctx->pc);
}
data->end = ctx->pc->line->real_addr;
data->size = nsize + alen + 1;
data->paramlen = alen;
data->param = args;
// Throw the data in a variable container
var_set(obj, data, OBJBLDR);
// Declare a name for this object
proc_decvar(ctx, OBJBLDR, 1, name);
// Set the object to the name we just declared
proc_setvar(ctx, 1, name, obj);
pc_inc(ctx->pc, 1);
pc_update(ctx->pc);
}
void _ins_def_DEFUN (rt_t* ctx, bc_cont* line)
{
int name = var_data_get_G_INT(line->varg[0]);
b_type type = var_data_get_TYPE(line->varg[1]);
b_type* args = var_data_get_PLIST(line->varg[2]);
size_t alen = line->sarg[2];
// Create a new variable for the new function
var_cont* func = var_new(FUNC);
// Allocate the data.
var_data_func* data = var_data_alloc_FUNC(type);
// Set the location of the functions body
data->loc = line->real_addr + 1;
int nsize;
/* Determine the namespace size by finding variable declarations in the
functions body, Along with determining the end of the function.
*/
for (nsize = 0; pc_safe(ctx->pc);)
{
// Is this the end?
if (ctx->pc->line->op == 0xF0)
{
break;
} else
// Are we declaring a variable?
if (ctx->pc->line->op == 0x20)
{
// If so, increment the namespace size.
nsize++;
}
// Increment the program counter
pc_inc(ctx->pc, 1);
pc_update(ctx->pc);
}
pc_update(ctx->pc);
// Set all the values.
data->end = ctx->pc->line->real_addr; // This is the end!
data->size = nsize + alen + 1; // How many names will this
// function have?
data->type = type; // Return type
data->paramlen = alen; // Set the arguement length
data->param = args; // Set the parameter list
// Throw the data in a variable container
var_set(func, data, FUNC);
// Declare a name
proc_decvar(ctx, FUNC, 1, name);
// Set the name's value to the function we just defined
proc_setvar(ctx, 1, name, func);
pc_inc(ctx->pc, 1);
pc_update(ctx->pc);
}
<file_sep>#include <stdlib.h>
#include "object.h"
#include "ns.h"
#include "var.h"
#include "helper.h"
ns_t* object_get(var_cont* object)
{
N_ASSERT(object, "object_get\n");
return (ns_t*)object->data;
}
void object_del(void* object)
{
N_ASSERT(object, "object_del\n");
ns_t* o = object;
ns_del(o);
}
var_cont* object_get_name(ns_t* object, ns_addr name)
{
N_ASSERT(object, "object_get_name\n");
var_cont* value = ns_get(object, 1, name);
return value;
}
void object_set_name(ns_t* object, ns_addr name, var_cont* var)
{
N_ASSERT(object, "object_set_name\n");
N_ASSERT(var, "object_set_name\n");
ns_set(object, 1, name, var);
}
<file_sep>/* `object.h` Object implementation
*/
#ifndef OBJECT_H
#define OBJECT_H
#include <stdlib.h>
#include "ns.h"
#include "helper.h"
ns_t* object_get(var_cont*);
/* Deconstruct an object
*/
void object_del(void*);
var_cont* object_get_name(ns_t*, ns_addr);
void object_set_name(ns_t*, ns_addr, var_cont*);
#endif // OBJECT_H
<file_sep>#include <stdio.h>
#include "ns.h"
int main( void )
{
ns_t* test = ns_init(10);
var_cont* testing = var_new(G_INT);
var_set(testing, var_data_alloc_G_INT(42), G_INT);
printf("testing: %li, %i\n", testing->ownership,
var_data_get_G_INT(testing));
ns_dec(test, G_INT, 0, 2);
ns_set(test, 0, 2, testing);
var_cont* testing_on_namespace = ns_get(test, 0, 2);
printf("testing_on_namespace: %li, %i\n", testing_on_namespace->ownership,
var_data_get_G_INT(testing));
ns_push(test, 5);
var_cont* testing_2 = var_new(G_INT);
var_set(testing_2, var_data_alloc_G_INT(24), G_INT);
ns_dec(test, G_INT, 0, 1);
ns_set(test, 0, 1, testing_2);
var_cont* testing_on_namespace_1 = ns_get(test, 0, 1);
printf("testing_on_namespace: %li, %i\n", testing_on_namespace_1->ownership,
var_data_get_G_INT(testing));
ns_dec(test, G_INT, 0, 2);
ns_set(test, 0, 2, testing);
var_cont* testing_on_namespace_2 = ns_get(test, 0, 2);
printf("testing_on_namespace: %li, %i\n", testing_on_namespace_2->ownership,
var_data_get_G_INT(testing));
ns_push(test, 5);
ns_dec(test, G_INT, 0, 2);
ns_set(test, 0, 2, testing);
var_cont* testing_on_namespace_3 = ns_get(test, 0, 2);
printf("testing_on_namespace: %li, %i\n", testing_on_namespace_3->ownership,
var_data_get_G_INT(testing));
printf("Namespace info: %d, %li\n", test->last->size, test->last->level);
ns_pop(test);
var_cont* testing_on_namespace_4 = ns_get(test, 0, 2);
printf("testing_on_namespace: %li, %i\n", testing_on_namespace_4->ownership,
var_data_get_G_INT(testing));
printf("Namespace info: %d, %li\n", test->last->size, test->last->level);
ns_pop(test);
var_cont* testing_on_namespace_5 = ns_get(test, 0, 2);
printf("testing_on_namespace: %li, %i\n", testing_on_namespace_5->ownership,
var_data_get_G_INT(testing));
printf("Namespace info: %d, %li\n", test->last->size, test->last->level);
ns_del(test);
return 0;
}
| 82ae80fa37735f01a9fddb27092f143ae800d06b | [
"C"
] | 4 | C | bannatech/language | bd24614ca384a69be2a3ebaa8d4c18183a0f77ff | b0becfc6703669ee3521398bd328a5c5cc90f0fe | |
refs/heads/master | <repo_name>PaulaSenisman/Practica<file_sep>/README.md
# Practica
## Pasos para crear un repositorio.
**Paso 1**: En *GitHub* dirigirse a repository y colocar new.
**Paso 2**: Escribir el nombre que desee tener el repositorio.
**Paso 3**: El repositorio debe ser publico y ser debe dar check a iniciar el repositorio con
un *README*.
**Nota**: Para editar un repositorio existen dos formas; La primera es realizarlo de manera directa en el lápiz ubicado en las esquina superior derecha del repositorio; La alternativa número dos es a través de *text edit* (lo que es útil en caso de no poseer internet.)
**¿Cómo puedo trabajar y realizar cambios sin internet?**
- Para realizar esto se debe clonar el repositorio, editarlo y posteriormente a través de la plataforma *Sourcetree* (ya con internet) subirlo a *Github*. Los cambios se realizarán de manera inmediata.
**¿Cómo clonar un *repositorio*?**
- En el repositorio creado en *GitHub* se debe ir a "Clone of Download", a aquí se dispondrá de un link asociado al *repositorio*, el cual se debe colocar en *Sourcetree* para crear una carpeta en el computador ubicada donde se desee.
**¿Dónde colocar el link del *repositorio*?**
- En *Sourcetree* se debe apretar nuevo y luego seleccionar la opción "clonar desde url". Esto quedará guardado en una carpeta con el nombre del repositorio el *local* del *Sourcetree*.
**¿Cómo editar el *repositorio* a través de *Sourcetree*?**
- Para editar el *repositorio* a través del *Sourcetree* se debe abrir la carpeta en el computador, la cual contendrá un archivo llamado *README*, y este a su vez abrirlo a través de *Text Edit*.
**¿Cómo subir mis cambios realizados a través de *Sourcetree* a *Github*?**
- Se deben guardar los cambios realizados en archivo, posteriormente en la carpeta del *Sourcetree* realizar un comentario (Mensaje para anotar),push y ok.
## Funciones del Github.
1. Para establecer un **Titulo** se debe colocar #y un espacio. (# )
2. Para un **subtitulo** se debe colocar doble gato y un espacio. (## )
3. Para realizar un **punto aparte** y seguir la oración abajo, se debe bajar dos veces.
4. Para realizar un **punto seguido** se debe colocar el punto y seguir ahí mismo ó bajar solo un espacio.
5. Para utilizar **negrita** es doble asterisco ala palabra. **
6. Para realizar **cursiva** solo se debe colocar un asterisco. *
7. Para colocar **numeración como punteo** colocar un guión ó asterisco y espacio. - ó *
8. Para colocar **numeración tal como (1. 2. 3. ...)** se debe poner tal cual 1.
9. [**En caso de dudas y más funciones**] (https://help.github.com/es/github/writing-on-github/basic-writing-and-formatting-syntax#styling-text)
## R Estudio
**¿Cómo trabajar en R y que quede guardado en mi repositorio?**
- **Paso 1**: Se debe abrir *R* y dirigirse a el *icono para crear una nueva hoja* y colocar ***R script***.
- **Paso 2**: **Limpiar** las ventanas restantes que contienen variables y demas.
- **Paso 3**: **Trabajar** en *R*.
- **Paso 4**: **Guardar** el *nuevo script*
**Nota**: Al guardar el nuevo script se debe cambiar el nombre del documente (Save as) y ubicarlo en la carpeta clonada desde *Github*. Luego apretar ***Save***
**¿Cómo eliminar un archivo de repositorio?**
- Se debe ingresar al archivo (ya sea *R* o *README*) y apretar el **basurero**. Luego de esto te solita un Commit changes, debe estar seleccionado *Commit directly to the master branch y presionar ***Commit Changes***.
- Posteriormente en *Sourcetree* se deben recibir los cambios a través de ***recibir***
### Trabajando en R estudio
***Siempre se debe colocar alt + enter para correr un comando***
***Para hacer <- altero presionar alt-***
**¿Cómo escribir en *R estudio*?**
- se debe colocar gato # antes de escribir.
**¿Cómo crear una variable simple?**
- Colocar un igual =, por ejemplo x=2, ahora la variable x vale 2.
- **Cuando en los resultados sale [1] significa que ese es el primer (y único resultado) de nuestra orden**.
***R estudio***
#Tipo de datos
#Enteros (int)
#-3,0,3
#Reales
#0,303456
#Booleans (boolean)
#True o False
#Carácter (char)
#'a','A', '0','#'
#Texto (String)
#"Hola","103"
#Variables
#Se compone por un espacio de almacenaje y un nombre donde se almacena la información.
#La variable se llama x
#Se inserta un 2 en la variable x
x=2
#La variable x vale 2
#La variable x deja de valer 2 y ahora vale 5 (de aquí el nombre)
x=5
#Las variables pueden ir cambiando de valor en el transcurso del desarrollo del algoritmo.
#Operador
#Es un simbolo que indica una operación matemática, la cual se lleva a cabo en un algoritmo
#Se tienen de:
#1.Asignación:Se asigna o reasigna valor a las variables.Generalmente es un = per acá se
trabaja como <-
A<-2
B=3
#2.Lógicos:Entrega un resultado a partir de que se cumpla o no una condición.
#Producen un resultado Booleano (True o False)
#Sus operados también son valores lógicos; Es decir los valores con los que se realiza
también son True o False.
#Esto genera una serie de valores que pueden ser parametrizados con los valores numericos
0 y 1.
!(TRUE) # el signo ! demuestra NEGACIÓN de lo interior del parentesis.
TRUE||FALSE # El simbolo || actúa como un ó DISYUNCIÓN.
TRUE&&FALSE ##Conjunción && actua como Y.
#3.Comparación ó "operadores relacionales": Toman decisiones a través de comparaciones.
#Lo que sucede acá es que se evalúa la condición, por ejemplo A<B
#El resultado puede se 1 = Verdadero ó O=Falso
#el 1 ó 0 no tiene que ver con el [1] al lado del resultado.
A<B #A menor a B (True)
A<=B #A menor o igual a B (True)
A>B #A mayor a B (False)
A>=B #A mayor o igual a B (False)
A==B #A igual a B (False)
#4.Aritméticos:
#Se usan para manipular datos enteros o reales (con decimales)
#Existen dos tipos:
#Tipo 1: Unarios
#Se anteponen a la expresión aritmética (signo). Vgr. -3 ó +5
#Tipo 2: Binarios
#Se situan entre dos expresiones aritmeticas.
A+B #Se suma A y B
A-B #Se resta A y B
A*B #Se multiplica A y B
A/B #Se divide A sobre B
A%/%B #Se entrega solo la parte entera.
A%%B #Muestra el resto. misma funcion A mod B
15%%4 #Muestra el resto.
A^B #Potencia
exp(1) #número e
exp(3)#e^3
sqrt(2) #Raiz cuadrada
log(3) #Logaritmo neperiano
log(3,10) #logaritmo de 3 en base 10
abs(-3.4) #valor absoluto
pi #Número de pi
#Función: Estructura que realiza una tarea dentro de un programa, este recibe valores de entrada y genera un valor de salida.
#Se debe crear una receta de diseño; Se debe considerar lo relevante del problema; cuales serán los parámetros de entrada y salida
#Verificar si acierta
<file_sep>/T3 .R
#Desarrollo tarea 3
#nuevos elementos
#1. Las listas (tipo de variable que contiene colecciones de manera ordenada)
#2. For
listaDeNumeros <- list(2,5,6,2,1,5,6,10,11,20,15)
#Se observa que a pesar de que la lista es un tipo de variable, esta se crea en datos, ya que posee elementos dentro (2,5,6,2,1,5,6,10,11,20,15).
#para acceder a estos existen dos formas
#forma 1. Forma directa que implica ir a la posición del elemento.
#Forma 2. FOR-LOOP Extraer el elemto directamente.
#Forma 1 PRUEBA
listaDeNumeros[5]
#Esto indica que en la posición 5 esta el 1.
<file_sep>/Comandos R .R
#Tipo de datos
#Enteros (int) integer
#-3,0,3
#Reales (doubles)
#0,303456
#Booleans (boolean)
#True o False
#Carácter (char)
#'a','A', '0','#'
#Texto (String) frases o palabras
#"Hola","103"
#Caracteres (char)
#Variables
#Se compone por un espacio de almacenaje y un nombre donde se almacena la información.
#La variable se llama x
#Se inserta un 2 en la variable x
x=2
#La variable x vale 2
#La variable x deja de valer 2 y ahora vale 5 (de aquí el nombre)
x=5
#Las variables pueden ir cambiando de valor en el transcurso del desarrollo del algoritmo.
#Operador
#Es un simbolo que indica una operación matemática, la cual se lleva a cabo en un algoritmo
#Se tienen de:
#1.Asignación:Se asigna o reasigna valor a las variables.Generalmente es un = per acá se trabaja como <-
A<-2
B=3
#2.Lógicos:Entrega un resultado a partir de que se cumpla o no una condición.
#Producen un resultado Booleano (True o False)
#Sus operados también son valores lógicos; Es decir los valores con los que se realiza también son True o False.
#Esto genera una serie de valores que pueden ser parametrizados con los valores numericos 0 y 1.
!(TRUE) # el signo ! demuestra NEGACIÓN de lo interior del parentesis.
TRUE||FALSE # El simbolo || actúa como un ó DISYUNCIÓN.
TRUE&&FALSE ##Conjunción && actua como Y.
#3.Comparación ó "operadores relacionales": Toman decisiones a través de comparaciones.
#Lo que sucede acá es que se evalúa la condición, por ejemplo A<B
#El resultado puede se 1 = Verdadero ó O=Falso
#el 1 ó 0 no tiene que ver con el [1] al lado del resultado.
A<B #A menor a B (True)
A<=B #A menor o igual a B (True)
A>B #A mayor a B (False)
A>=B #A mayor o igual a B (False)
A==B #A igual a B (False)
#4.Aritméticos:
#Se usan para manipular datos enteros o reales (con decimales)
#Existen dos tipos:
#Tipo 1: Unarios
#Se anteponen a la expresión aritmética (signo). Vgr. -3 ó +5
#Tipo 2: Binarios
#Se situan entre dos expresiones aritmeticas.
A+B #Se suma A y B
A-B #Se resta A y B
A*B #Se multiplica A y B
A/B #Se divide A sobre B
A%/%B #Se entrega solo la parte entera.
A%%B #Muestra el resto. misma funcion A mod B
15%%4 #Muestra el resto.
A^B #Potencia
exp(1) #número e
exp(3)#e^3
sqrt(2) #Raiz cuadrada
log(3) #Logaritmo neperiano
log(3,10) #logaritmo de 3 en base 10
abs(-3.4) #valor absoluto
pi #Número de pi
#Función: Estructura que realiza una tarea dentro de un programa, este recibe valores de entrada y genera un valor de salida.
#Se debe crear una receta de diseño; Se debe considerar lo relevante del problema; cuales serán los parametros de entrada y salida
#Verificar si acierta
<file_sep>/Tot Comandos R .R
n <- 10
#hacia donde va la flecha es cuanto vale, en este caso el 10 va a n, por lo tanto n vale 10.
n
print(n)
#Al colocar n o print (n), el resultado es [1] 10 lo que signifca
#que el primer elemento del objeto n es 10.
L <- 10+2
(5+4)
----------------------------------
#Función lista de objetos en memoria
ls()
# con ls () se muestran los nombres de los objetos ubicados en la esquina superior derecha.
ls(pat="D")
#listar objetos con el caracter D en particular
ls(pat="^l")
#restrinfir la lista a aquellos objetos que comience con ese caracter
ls.str()
#Esto muestra algunos detalles de los objetos en memoria.
#por ejemplo que contiene el número 5 o caracter ...
#Ejemplo Práctico, se crearán nuevas variables.
Paula <- 10
Francisco <- 5
Danae <- 7
Viviana <- 10
Dante <- 3
Marco <- 8
Myriam <- 4
Pablo <- 9
Patrcia <- 12
ls(pat="P")
ls(pat="^D")
ls.str()
#continuando...
----------------------------
rm(Paula)
#se utiliza rm(nombre del objeto) para borrarlo de la memoria
rm(Dante,Francisco)
#Se utiliza rm(,)para eliminar dos objetos de la memoria.
rm(list=ls())
#Se eliminan todas las variables
rm(list=ls(pat="^P"))
#Para borrar selectivamente algunos objetos, en este caso todos los objetos que comienzan con la letra P
---------------
#ATRIBUTOS
#Estos especifican el tipo de dato representado por el objeto
#La función sobre un objeto depende de los atributos de este
#Todo objeto posee dos atributos intrínsicos
#1.Tipo: Clase básica de los objetos
#y 2. Longitud: Número de elementos en el objeto
#Para ver el tipo y la longitud se ven las funciones mode y length
#Ejemplo 1
x <- (2)
mode(x)
#indica que el 2 es un número
length(x)
#Número de elementos en el objeto.
#Ejemplo 2
mode(listaDeNumeros)
#Se indica que contiene una lista
length(listaDeNumeros)
#Existen 11 elementos en el objeto
#Ejemplo 3
mode(Dante) ; mode(Francisco) ; mode(Paula)
----------------
#Generando secuencia de datos
T <- 1:30
#se crea un objeto que contiene una secuencia regular de elementos ordenados cuyos tipos de datos son enteros del 1 al 30
#Es decir el vector resultante T tiene 30 elementos.
1:10-1
#Se genera una secuencia de números del 1 al 9 que incluyen el 0
1:(10-1)
#Se genera una secuencia de números del 1 al 9
seq(1,5,0.5)
#Secuencia de números reales donde el primer número indica el inicio, el segundo el final y el tercero el incremento.
seq(2,3,0.2)
#o bien utilizar
seq(length=9, from=1, to=5)
#Matrices
layout(matrix(1:6,2,3))
layout.show(2)
#Graficas
x <- rnorm(10)
y <- rnorm(10)
plot(x,y)
#Se crea un objeto el cual corresponde a una serie de números con 6 elementos, el vector generado es 1,2,3,4,5,6
S <- 1:6
#Se crea una variable b
b=3
#Se crea el objeto y
y <- 1:6
#Se indica que cuando el elemento evaluado de la secuencia x no sea igual al elemento b, se coloque 1; cuando sean identicos, coloque cero (todo esto en una nueva variable generada llamada Y)
#y <- numeric(lengt(x))
for (i in 1:length(S)) if (S[i]==b) y [i] <- 0 else y[i] <- 1
#Se elimina la secuencia de datos y de la memoria
rm(list = ls(pat="^y"))
| d138f17ca2b993da9ede1ef3072ccb6093f3cf3d | [
"Markdown",
"R"
] | 4 | Markdown | PaulaSenisman/Practica | e04b9e650c960cb6835bcbbcad27da1318de4c96 | 80ea6fd704e9fa78ccb07caaf15c6b78f293fc2d | |
refs/heads/master | <repo_name>rullymartanto/Angularjs-Codeigniter-GenesisUI<file_sep>/application/models/Access_item_model.php
<?php
/**
* User: gamalan
* Date: 3/17/2015
* Time: 10:06 AM
*/
class access_item_model extends AR_Model {
public function __construct(){
parent::__construct();
$this->allow_insert = "user_access_id,access_item_id,access_item_type,access_custom";
$this->allow_update = "access_item_id,access_item_type,access_custom";
$this->tblName = "t_access_item";
$this->tblId = "id";
}
}<file_sep>/application/controllers/AuthController.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class AuthController extends AR_Controller {
public function __construct(){
parent::__construct();
$this->load->model("user_model");
}
public function index(){
}
public function login()
{
$result = $this->result;
$post_data = $this->input_data;
$username = $post_data['username'];
$userData = $this->App_model->find('user', $username,"username");
$password = md5(strtolower($username).$post_data['password']);
if(isset($userData['password']) && $userData['password'] == $password){
$result['data'] = $userData;
$result['error'] = 0;
$result['msg'] = '';
}
echo json_encode($result);
}
public function logout(){
$this->session->unset_userdata('adminData');
session_destroy();
}
}
<file_sep>/application/helpers/ar_helper.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//helper
//created by : <NAME>
function generateSearchString($search,$sort_by = "",$order = "",$page = 1,$limit = ""){
$str = "";
$page--;
$start = $page * $limit;
$str .= " AND ( ";
foreach($search as $key=>$val){
if($key != 0){
$str .= " OR ";
}
$str .= " ".$val[1]." ".$val[2]." '".$val[0]."'";
}
$str .= " ) ";
if($sort_by != ""){
$str .= " ORDER BY $sort_by $order";
}
if($limit != ""){
$str .= " limit $start,$limit";
}
return $str;
}
function search_access_array($id, $array) {
if(count($array)>0){
foreach ($array as $key => $val) {
if ($val['id'] === $id) {
return $val;
}
}
}
return null;
}
function generateBootstrapPagination($base_url,$total,$limit){
//BEGIN PAGINATION
$ci =& get_instance();
$ci->load->library("pagination");
$config['base_url'] = $base_url;
$config['total_rows'] = $total;
$config['per_page'] = $limit;
$config['query_string_segment'] = "page";
$config['use_page_numbers'] = TRUE;
$config['page_query_string'] = TRUE;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] ="</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$ci->pagination->initialize($config);
return $ci->pagination->create_links();
//END PAGINATION
}
function ismobile()
{
$mobile_browser = '0';
if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
$mobile_browser++;
}
if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
$mobile_browser++;
}
$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
$mobile_agents = array(
'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
'wapr','webc','winw','winw','xda ','xda-');
if (in_array($mobile_ua,$mobile_agents)) {
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows') > 0) {
$mobile_browser = 0;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'mac') > 0) {
$mobile_browser = 0;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'ios') > 0) {
$mobile_browser = 1;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'android') > 0) {
$mobile_browser = 1;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows phone') > 0) {
$mobile_browser = 1;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'iphone os') > 0) {
$mobile_browser = 1;
}
return $mobile_browser;
}
function getPrefixNo($id)
{
$ci =& get_instance();
$ci->load->model("prefix_model");
$ci->load->database();
$structure = $ci->db->query("SELECT * FROM prefix WHERE id = '$id' ORDER BY running_number DESC LIMIT 1")->row_array();
$intial = $structure['prefix'];
$length = $structure['length'];
if ($structure['running_number'] >= 1)
{
$number = intval($structure['running_number']);
}else{
$number = 0;
}
$number++;
$tmp= "";
for ($i=0; $i < ($length-strlen($number)) ; $i++)
{
$tmp = $tmp."0";
}
$ci->prefix_model->update($id,array('running_number'=>$number));
//return generate ID
return strval($intial.$tmp.$number);
}
function getPrefixmmyy($id)
{
$ci =& get_instance();
$ci->load->model("prefix_model");
$ci->load->database();
$structure = $ci->db->query("SELECT * FROM prefix WHERE id = '$id' ORDER BY running_number DESC LIMIT 1")->row_array();
$intial = date("my");
$length = $structure['length'];
if ($structure['running_number'] >= 1)
{
$number = intval($structure['running_number']);
}else{
$number = 0;
}
$number++;
$tmp= "";
for ($i=0; $i < ($length-strlen($number)) ; $i++)
{
$tmp = $tmp."0";
}
$ci->prefix_model->update($id,array('running_number'=>$number));
//return generate ID
return strval($intial.$tmp.$number);
}
function upload_handler($file_name,$new_name,$new_path, $required = true,$old_file_path = ""){
$ci =& get_instance();
$returnData = array();
$config['upload_path'] = $new_path;
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '1024';
$config['overwrite'] = TRUE;
$config['file_name'] = $new_name;
$ci->load->library('upload', $config);
if(isset($_FILES[$file_name]))
{
if (!$ci->upload->do_upload($file_name))
{
$returnData['error'] = $ci->upload->display_errors();
$returnData['status'] = 0;
}
else
{
$upload_data = $ci->upload->data();
$returnData['file_path'] = $new_path.$upload_data['raw_name'].$upload_data['file_ext'];
$parts = explode(".",$upload_data['full_path']);
$ci->load->library('image_lib');
/* read the source image */
if($upload_data['file_type'] == "image/jpeg" || $upload_data['file_type'] == "image/jpg"){
$source_image = imagecreatefromjpeg($upload_data['full_path']);
}
else if($upload_data['file_type'] == "image/png"){
$source_image = imagecreatefrompng($upload_data['full_path']);
}
else if($upload_data['file_type'] == "image/gif"){
$source_image = imagecreatefromgif($upload_data['full_path']);
}
$width = imagesx($source_image);
$height = imagesy($source_image);
/* create a new, "virtual" image */
// first resize the image
$thumbnail_size = 200;
if ($width < $height){
$desired_width = $thumbnail_size;
$desired_height = floor($height * ($desired_width / $width));
$w_start = 0;
$h_start = $desired_height / 2 - ($thumbnail_size/2);
}else{
$desired_height = $thumbnail_size;
$desired_width = floor($width * ($desired_height / $height));
$w_start = $desired_width / 2 - ($thumbnail_size/2);
$h_start = 0;
}
/* copy source image at a resized size based on the shortest length */
$virtual_image = imagecreatetruecolor(200, 200);
imagecopyresampled($virtual_image, $source_image, -$w_start, -$h_start, 0, 0, $desired_width, $desired_height, $width, $height);
/* create the physical thumbnail image to its destination */
$thumbnail_path = $upload_data['file_path']."/".$upload_data['raw_name']."_thumb".$upload_data['file_ext'];
$returnData['thumbnail_path'] = $new_path."/".$upload_data['raw_name']."_thumb".$upload_data['file_ext'];
if($upload_data['file_type'] == "image/jpeg" || $upload_data['file_type'] == "image/jpg"){
imagejpeg($virtual_image, $thumbnail_path);
}
else if($upload_data['file_type'] == "image/png"){
imagepng($virtual_image, $thumbnail_path);
}
else if($upload_data['file_type'] == "image/gif"){
imagegif($virtual_image, $thumbnail_path);
}
$returnData['status'] = 1;
//END CREATING THUMBNAILS
//BEGIN DELETE OLD FILE
if($old_file_path != ""){
if(file_exists($old_file_path)){
unlink($old_file_path);
}
$parts = explode(".",$old_file_path);
$old_thumb_path = $parts[0]."_thumb.".$parts[1];
if(file_exists($old_thumb_path)){
unlink($old_thumb_path);
}
}
//END DELETE OLD FILE
}
}
else{
if($required){
$returnData['status'] = 1;
}
else{
$returnData['status'] = 0;
}
}
return $returnData;
}
function labelStatus($status){
$label = '';
if($status == "PENDING"){
$label .= '<span class="label label-info">';
}else if($status == "PROCESSED"){
$label .= '<span class="label label-primary">';
}else if($status == "OPEN"){
$label .= '<span class="label label-success">';
}else if($status == "PAID"){
$label .= '<span class="label label-success">';
}else if($status == "CLOSE"){
$label .= '<span class="label label-default">';
}else if($status == "CLOSED"){
$label .= '<span class="label label-default">';
}else if($status == "UNPAID"){
$label .= '<span class="label label-warning">';
}else if($status == "FINISHING"){
$label .= '<span class="label label-info">';
$class = 'Info';
}else if($status == "FINISHED"){
$label .= '<span class="label label-default">';
}else if($status == "PARTITIAL PAID"){
$label .= '<span class="label label-warning">';
}
$label .= $status."</span>";
return $label;
}
function generate_table_header(){
}
/* created by samuel */
function time_ago( $date )
{
if( empty( $date ) )
{
return "No date provided";
}
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
$now = time();
$unix_date = strtotime( $date );
// check validity of date
if( empty( $unix_date ) )
{
return "Bad date";
}
// is it future date or past date
if( $now > $unix_date )
{
$difference = $now - $unix_date;
$tense = "ago";
}
else
{
$difference = $unix_date - $now;
$tense = "from now";
}
for( $j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++ )
{
$difference /= $lengths[$j];
}
$difference = round( $difference );
if( $difference != 1 )
{
$periods[$j].= "s";
}
return "$difference $periods[$j] {$tense}";
}
function generateBarcode($code){
$ci =& get_instance();
$path = "./public/barcode/";
$ci->load->library('Zend');
//load in folder Zend
$ci->zend->load('Zend/Barcode');
//generate barcode
$file = Zend_Barcode::draw('code128', 'image', array('text'=>$code), array());
$code = time().$code;
$store_image = imagepng($file,$path."{$code}.png");
return $path."{$code}.png";
}
function add_comission($id=null)
{
$ci =& get_instance();
$ci->load->model("prefix_model");
$ci->load->database();
$inv = $ci->db->query("SELECT * FROM sales_invoice WHERE id = '$id'")->row_array();
$sales_id = $inv['sales_id'];
$sales = $ci->db->query("SELECT * FROM sales WHERE id = '$sales_id'")->row_array();
$cust_id=$sales['customer_id'];
$cust = $ci->db->query("SELECT * FROM customer WHERE id = '$cust_id'")->row_array();
$salesman_id=$cust['salesman_id'];
$join_date=$cust['join_date'];
$user_com = $ci->db->query("SELECT * FROM user_comission WHERE user_id = '$salesman_id' and sales_id='$sales_id'");
$count_ucom=$user_com->num_rows();
if($count_ucom==0){
$now=gmdate("Y-m-d");
$date1 = new DateTime($join_date);
$now1 = new DateTime($now);
$join_month=$now1->diff($date1)->format("%m");
$comission_value=0;
$u_com_setting = $ci->db->query("SELECT * FROM user_comission_setting WHERE user_id = '$salesman_id' and is_general=0 and deleted_by is null")->row_array();
$com_set_id=$u_com_setting['comission_setting_id'];
$u_com_setting = $ci->db->query("SELECT * FROM comission_setting_detail WHERE comission_setting_id = '$com_set_id'")->result_array();
$i=0;
foreach($u_com_setting as $row){
if($join_month>=$row['from_month'] && $join_month<=$row['to_month']){
$comission_value=($row['percentage']/100)*$sales['grand_total'];
$data_comission=array(
"sales_id"=>$sales_id,
"user_id"=>$salesman_id,
"calculation"=>$row['percentage']."%",
"comission"=>$comission_value,
"month"=>$join_month
);
$ci->db->insert("user_comission",$data_comission);
$i++;
}
}
if($i==0){
return "Error";
}else{
return "Success add comission";
}
}else{
return "Not add comission";
}
}
function product_log($status=null,$remarks=null,$id=null)
{
$ci =& get_instance();
$ci->load->database();
$result="";
$detail = $ci->db->query("SELECT * FROM delivery_order_detail WHERE delivery_order_id = '$id'")->result_array();
foreach($detail as $d){
$stock = $ci->db->query("SELECT * FROM product_stock WHERE product_id = '$d[product_id]'")->row_array();
if($status=="in"){
$update_stock=$stock['qty']+$d['qty'];
$data_log=array(
"product_id"=>$d['product_id'],
"start_qty"=>$stock['qty'],
"in"=>$d['qty'],
"remarks"=>$remarks,
"end_qty"=>$update_stock
);
$ci->db->insert("product_stock_log",$data_log);
$data_stock=array(
"qty"=>$update_stock
);
$ci->db->where('id', $stock['id']);
$ci->db->update("product_stock",$data_stock);
$sd=$ci->db->query("SELECT * FROM sales_detail WHERE id = '$d[sales_detail_id]'")->row_array();
$balance_stock=$sd['balance']+$d['qty'];
$data_balance=array(
"balance"=>$balance_stock
);
$ci->db->where('id',$d['sales_detail_id']);
$ci->db->update("sales_detail",$data_balance);
$result.="Plus In Success ".$d['product_id'];
}else if($status=="out"){
$update_stock=$stock['qty']-$d['qty'];
$data_log=array(
"product_id"=>$d['product_id'],
"start_qty"=>$stock['qty'],
"out"=>$d['qty'],
"remarks"=>$remarks,
"end_qty"=>$update_stock
);
$ci->db->insert("product_stock_log",$data_log);
$data_stock=array(
"qty"=>$update_stock
);
$ci->db->where('id', $stock['id']);
$ci->db->update("product_stock",$data_stock);
$result.="Plus Out Success ".$d['product_id'];
}else{
$result.="No Action";
}
}
return $result;
}
function preprocess_date($date_data){
if($date_data == "" || $date_data == "0000-00-00"){
$ret_data = NULL;
}else{
$ret_data = date("Y-m-d",strtotime($date_data));
}
return $ret_data;
}
function view_date($date_data){
if($date_data == "" || $date_data == "0000-00-00"){
$date_data = "";
}else{
$date_data = date("d-m-Y",strtotime($date_data));
}
return $date_data;
}
function view_date_1($date_data){
if($date_data == "" || $date_data == "0000-00-00"){
$date_data = "";
}else{
$date_data = date("d/m/Y",strtotime($date_data));
}
return $date_data;
}
function get_timeago( $ptime )
{
$estimate_time = time() - $ptime;
if( $estimate_time < 1 )
{
return 'less than 1 second ago';
}
$condition = array(
12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach( $condition as $secs => $str )
{
$d = $estimate_time / $secs;
if( $d >= 1 )
{
$r = round( $d );
return 'about ' . $r . ' ' . $str . ( $r > 1 ? 's' : '' ) . ' ago';
}
}
}
function send_mail($to="",$subject="",$message=""){
$ci =& get_instance();
$ci->load->library('email');
$ci->load->model('company_model');
$ci->email->set_newline("\r\n");
$ci->email->from("<EMAIL>");
$to = "<EMAIL>";
$ci->email->to($to);
$ci->email->subject($subject);
$ci->email->message($message);
try {
$ci->email->send();
$email_debug = $ci->email->print_debugger();
return 0;
} catch (Exception $e) {
return 1;;
}
}
function product_addition_qty($post_data){
$ci =& get_instance();
$ci->load->model('product_stock_model');
$ci->load->model('product_log_model');
$error =0;
$check_product_stok = $ci->product_stock_model->find($post_data["product_id"],"product_id"," AND company_branch_id = ".$post_data["company_branch_id"]);
$credit = NULL;
$debit = $post_data["addition"];
if($check_product_stok){
$starting_balance = $check_product_stok["qty"];
$ending_balance = $check_product_stok["qty"]+$post_data["addition"];
$new_qty = $check_product_stok["qty"]+$post_data["addition"];
$update_data = array();
$update_data["qty"] = $new_qty;
$ci->product_stock_model->update($check_product_stok["id"],$update_data);
$id = $check_product_stok["id"];
}else{
$starting_balance = $post_data["addition"];
$ending_balance = $post_data["addition"];
$post_data["qty"] = $post_data["addition"];
$id = $ci->product_stock_model->add($post_data);
}
if(isset($id)){
$error = 0;
//product log
$product_log_data = array();
$product_log_data["product_id"] = $post_data["product_id"];
$product_log_data["company_branch_id"] = $post_data["company_branch_id"];
$product_log_data["starting_balance"] = $starting_balance;
$product_log_data["debit"] = $debit;
$product_log_data["credit"] = $credit;
$product_log_data["ending_balance"] = $ending_balance;
$product_log_data["remarks"] = $post_data["remarks"];
$ci->product_log_model->add($product_log_data);
}else{
$error = 1;
}
return $error;
}
function product_dedcution_qty($post_data){
$ci =& get_instance();
$ci->load->model('product_stock_model');
$ci->load->model('product_log_model');
$error =0;
$check_product_stok = $ci->product_stock_model->find($post_data["product_id"],"product_id"," AND company_branch_id = ".$post_data["company_branch_id"]);
if($check_product_stok["qty"] >= $post_data["deduction"] ){
$credit = $post_data["deduction"];
$debit = NULL;
$starting_balance = $check_product_stok["qty"];
$ending_balance = $check_product_stok["qty"]-$post_data["deduction"];
$new_qty = $check_product_stok["qty"]-$post_data["deduction"];
$update_data = array();
$update_data["qty"] = $new_qty;
$ci->product_stock_model->update($check_product_stok["id"],$update_data);
$id = $check_product_stok["id"];
}
if(isset($id)){
//product log
$product_log_data = array();
$product_log_data["product_id"] = $post_data["product_id"];
$product_log_data["company_branch_id"] = $post_data["company_branch_id"];
$product_log_data["starting_balance"] = $starting_balance;
$product_log_data["debit"] = $debit;
$product_log_data["credit"] = $credit;
$product_log_data["ending_balance"] = $ending_balance;
$product_log_data["remarks"] = $post_data["remarks"];
$ci->product_log_model->add($product_log_data);
$error = 0;
}else{
$error = 1;
}
return $error;
}
function product_log_purchase($status=null,$remarks=null,$id=null,$qty=null)
{
$ci =& get_instance();
$ci->load->database();
$d = $ci->db->query("SELECT * FROM purchase_order_detail WHERE id = '$id'")->row_array();
$stock = $ci->db->query("SELECT * FROM product WHERE id = '$d[product_id]'")->row_array();
if($status=="in"){
$update_stock=$stock['qty']+$qty;
$data_log=array(
"product_id"=>$d['product_id'],
"start_qty"=>$stock['qty'],
"in"=>$qty,
"remarks"=>$remarks,
"end_qty"=>$update_stock
);
$ci->db->insert("product_stock_log",$data_log);
$data_stock=array(
"qty"=>$update_stock
);
$ci->db->where('id', $stock['id']);
$ci->db->update("product",$data_stock);
return "Plus In Success";
}else if($status=="out"){
$update_stock=$stock['qty']-$qty;
$data_log=array(
"product_id"=>$d['product_id'],
"start_qty"=>$stock['qty'],
"out"=>$qty,
"remarks"=>$remarks,
"end_qty"=>$update_stock
);
$ci->db->insert("product_stock_log",$data_log);
$data_stock=array(
"qty"=>$update_stock
);
$ci->db->where('id', $stock['id']);
$ci->db->update("product",$data_stock);
return "Plus Out Success";
}else{
return "No Action";
}
}
<file_sep>/application/models/Access_item_category_model.php
<?php
/**
* User: mike
* Date: 3/28/2015
* Time: 12:01 AM
*/
class Access_Item_Category_Model extends AR_Model {
public function __construct(){
parent::__construct();
$this->allow_insert = "user_access_id,access_item_id,access_item_type,access_custom";
$this->allow_update = "access_item_id,access_item_type,access_custom";
$this->tblName = "t_access_category";
$this->tblId = "id";
}
public function get_sidemenu_categories($user_access_ids){
$query = "SELECT DISTINCT access_category_id FROM t_access_item WHERE";
$query .= " route IS NOT NULL AND ( ";
foreach($user_access_ids as $key=>$id){
if($key!=0){
$query .= " OR";
}
$query .= " id = '$id'";
}
$query .=" ) ";
$query .=" Order by display_order asc";
$datas = $this->query($query);
$query2 = "SELECT * FROM t_access_category WHERE";
foreach($datas->result_array() as $key=>$row){
if($key != 0){
$query2 .= " OR";
}
$query2 .= " id = '".$row['access_category_id']."'";
}
$query2 .=" Order by display_order asc";
$ret = $this->query($query2);
foreach($ret->result_array() as $row){
$return[] = $row;
}
return $return;
}
}<file_sep>/application/models/User_group_model.php
<?php
class User_group_model extends AR_Model
{
public function __construct()
{
parent::__construct();
$this->tblName = "user_group";
$this->tblId = "id";
$this->allow_insert = "code,description";
$this->allow_update = "code,description";
}
}
?>
<file_sep>/application/views/admin_template.php
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Admin Panel Bootstrap 4.0.0 & AngularJS 1.5.0">
<!-- <link rel="shortcut icon" href="assets/ico/favicon.png"> -->
<title>ROOT Admin - UI Admin Kit</title>
<link href="<?php echo base_url("angularjs/assets/css/style.css")?>" rel="stylesheet">
<script>
var base_url = "<?php echo base_url();?>";
</script>
</head>
<body class="navbar-fixed sidebar-nav fixed-nav">
<base href="<?php echo base_url();?>angularjs/" />
<!-- User Interface -->
<ui-view></ui-view>
<script src="<?php echo base_url("angularjs/assets/libs/jquery.min.js")?>"></script>
<script src="<?php echo base_url("angularjs/assets/libs/tether.min.js")?>"></script>
<script src="<?php echo base_url("angularjs/assets/libs/bootstrap.min.js")?>"></script>
<script src="<?php echo base_url("angularjs/assets/libs/angular.min.js")?>"></script>
<script src="<?php echo base_url("angularjs/assets/libs/angular-animate.min.js")?>"></script>
<script src="<?php echo base_url("angularjs/assets/libs/angular-sanitize.min.js")?>"></script>
<script src="<?php echo base_url("angularjs/assets/libs/angular-ui-router.min.js")?>"></script>
<script src="<?php echo base_url("angularjs/assets/libs/ocLazyLoad.min.js")?>"></script>
<script src="<?php echo base_url("angularjs/assets/libs/angular-translate.min.js")?>"></script>
<script src="<?php echo base_url("angularjs/assets/libs/angular-breadcrumb.min.js")?>"></script>
<script src="<?php echo base_url("angularjs/assets/libs/loading-bar.min.js")?>"></script>
<script src="<?php echo base_url("angularjs/assets/libs/ngstorage/ngStorage.js")?>"></script>
<script src="<?php echo base_url("angularjs/scripts/app.js")?>"></script>
<script src="<?php echo base_url("angularjs/scripts/config.js")?>"></script>
<script src="<?php echo base_url("angularjs/scripts/config.lazyload.js")?>"></script>
<script src="<?php echo base_url("angularjs/scripts/config.routes.js")?>"></script>
<script src="<?php echo base_url("angularjs/scripts/services.api.js")?>"></script>
<script src="<?php echo base_url("angularjs/controllers/SidebarCtrl.js")?>"></script>
<script src="<?php echo base_url("angularjs/directives/directives.js")?>"></script>
<script src="<?php echo base_url("angularjs/directives/lazyload.js")?>"></script>
<!-- <script>
function open_modal(data,$modal){
var modalInstance = $modal.open({
animation: true,
templateUrl: 'views/modal/'+data.template,
controller: data.ctrl,
size: data.size,
resolve: {
param: function () {
return data.param;
}
}
});
}
function open_full_modal(data,$modal){
var modalInstance = $modal.open({
animation: true,
templateUrl: 'views/modal/'+data.template,
controller: data.ctrl,
size: data.size,
windowClass: 'app-modal-window',
resolve: {
param: function () {
return data.param;
}
}
});
}
function show_alert(type,msg,ngNotify){
ngNotify.set(msg, {
position: 'top',
theme: 'pure',
type: type
});
}
</script> -->
</body>
</html><file_sep>/angularjs/scripts/config.routes.js
'use strict';
angular
.module('app')
.run(
['$rootScope', '$state', '$stateParams', 'AUTH_EVENTS', 'AuthService',
function ( $rootScope, $state, $stateParams ,AUTH_EVENTS, AuthService) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$rootScope.$on('$stateChangeStart', function (event,next, nextParams, fromState) {
if ('data' in next && 'authorizedRoles' in next.data) {
var authorizedRoles = next.data.authorizedRoles;
if (!AuthService.isAuthorized(authorizedRoles)) {
$rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
}
}
if (!AuthService.isAuthenticated()) {
if (next.name !== 'appSimple.login') {
event.preventDefault();
$state.go('appSimple.login');
}
}
});
}
]
)
.config(['$stateProvider', '$urlRouterProvider', '$breadcrumbProvider','MODULE_CONFIG','USER_ROLES', function($stateProvider, $urlRouterProvider, $breadcrumbProvider,MODULE_CONFIG, USER_ROLES) {
//$urlRouterProvider.otherwise('/dashboard');
$urlRouterProvider.otherwise(function ($injector, $location) {
var $state = $injector.get("$state");
$state.go("app.main");
});
$breadcrumbProvider.setOptions({
prefixStateName: 'app.main',
includeAbstract: true,
template: '<li ng-repeat="step in steps" ng-class="{active: $last}" ng-switch="$last || !!step.abstract"><a ng-switch-when="false" href="{{step.ncyBreadcrumbLink}}">{{step.ncyBreadcrumbLabel}}</a><span ng-switch-when="true">{{step.ncyBreadcrumbLabel}}</span></li>'
});
$stateProvider
.state('app', {
abstract: true,
templateUrl: 'views/common/layouts/full.html',
//page title goes here
ncyBreadcrumb: {
label: 'Root',
skip: true
},
resolve: load([
'chart',
'controllers/shared.js'
])
})
.state('app.main', {
url: '/dashboard',
templateUrl: 'views/main.html',
//page title goes here
ncyBreadcrumb: {
label: '{{ "HOME" | translate }}',
},
//page subtitle goes here
params: { subtitle: 'Welcome to ROOT powerfull Bootstrap & AngularJS UI Kit' },
resolve: load([
'controllers/main.js',
'assets/libs/moment.min.js',
'assets/libs/daterangepicker.min.js',
'assets/libs/angular-daterangepicker.min.js',
'assets/libs/gauge.min.js',
'assets/libs/angular-toastr.tpls.min.js'
])
})
.state('app.product_list', {
url: '/tables',
templateUrl: 'views/components/tables.html',
ncyBreadcrumb: {
label: '{{ "TABLES" | translate }}'
},
controller : "MainCtrl",
resolve: load([
'controllers/Main.js'
])
})
.state('appSimple', {
abstract: true,
templateUrl: 'views/common/layouts/simple.html'
})
.state('appSimple.login', {
url: '/login',
templateUrl: 'views/pages/login.html',
controller : "LoginCtrl",
resolve: load([
'controllers/LoginCtrl.js',
'assets/libs/angular-toastr.tpls.min.js'
])
})
function load(srcs, callback) {
return {
deps: ['$ocLazyLoad', '$q',
function( $ocLazyLoad, $q ){
var deferred = $q.defer();
var promise = false;
srcs = angular.isArray(srcs) ? srcs : srcs.split(/\s+/);
if(!promise){
promise = deferred.promise;
}
angular.forEach(srcs, function(src) {
promise = promise.then( function(){
angular.forEach(MODULE_CONFIG, function(module) {
if( module.name == src){
if(!module.module){
name = module.files;
}else{
name = module.name;
}
}else{
name = src;
}
});
return $ocLazyLoad.load(name);
});
});
deferred.resolve();
return callback ? promise.then(function(){ return callback(); }) : promise;
}
]
}
}
}]);
<file_sep>/application/controllers/ApiController.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class ApiController extends AR_Controller {
public function __construct(){
parent::__construct();
$this->load->model("Prefix_model");
$this->load->model("master_setting_model");
$this->set_session();
}
public function index(){
$result = $this->result;
echo json_encode($this->result);
}
public function get_company($id = 1)
{
$result = $this->result;
$post_data = $this->input_data;
$result['data'] = $this->App_model->find('company',$id);
$result['error'] = 0;
echo json_encode($result);
}
public function getsidebar($id){
$result = $this->result;
$page = array();
$user = $this->App_model->find('user',$id);
if(isset($user['user_access_id']))
{
$page = $this->access_management->generate_admin_sidemenu_angular($id);
}
$result['data'] = $page;
echo json_encode($result);
}
public function getPrefix($id){
$data = getPrefixNo($id);
echo json_encode(array("number"=>$data));
}
public function getUserOnline($user_id){
$data = $this->User_model->all(' AND id != "'.$user_id.'"');
$result = array();
if(count($data) > 0){
foreach($data as $value){
$this->load->model("User_chat_model");
if($value['id'] < $user_id){
$channel = md5($value['id'].$user_id);
}else{
$channel = md5($user_id.$value['id']);
}
$chat = $this->User_chat_model->all(' AND channel = "'.$channel.'" ORDER BY datetime DESC LIMIT 1');
$msg = '';
if(count($chat) > 0){
$msg = $chat[0]['message'];
}
$result[] = array(
"id" => $value['id'],
"full_name" => $value['full_name'],
"last_chat" => $msg
);
}
}
echo json_encode(array("data"=>$result));
}
public function getUserChat($user_target_id){
$this->load->model("User_chat_model");
$post_data = $this->input_data;
$result = array();
if($user_target_id < $post_data['user_id']){
$channel = md5($user_target_id.$post_data['user_id']);
}else{
$channel = md5($post_data['user_id'].$user_target_id);
}
$data = $this->User_chat_model->all(' AND channel = "'.$channel.'" ');
if(count($data) > 0 && isset($data)){
foreach($data as $value){
$user = $this->User_model->find($value['user_id']);
if($value['user_id'] == $post_data['user_id']){
$position = "right";
}else{
$position = "left";
}
$result[] = array(
"id" => $value['id'],
"message" => $value['message'],
"username" => $user['full_name'],
"position" => $position,
"datetime" => get_timeago(strtotime($value['datetime']))
);
}
}
echo json_encode(array("data"=>$result));
}
public function send_message(){
$this->load->model("User_chat_model");
$post_data = $this->input_data;
if($post_data['user_to'] < $post_data['user_id']){
$channel = md5($post_data['user_to'].$post_data['user_id']);
}else{
$channel = md5($post_data['user_id'].$post_data['user_to']);
}
$param = array(
"message"=>$post_data['message'],
"user_id"=>$post_data['user_id'],
"channel"=>$channel,
"datetime"=>date("Y-m-d H:i:s"),
"status"=>"unread"
);
$id = $this->User_chat_model->add($param);
$this->load->library("pusher");
/* Push notification */
$this->pusher->trigger('chat_channel', 'chat_event', array('message' => 'new message','user_id' => $post_data['user_to'],'user_from'=> $post_data['user_id']));
echo json_encode(array("id"=>$id));
}
public function getUser($id){
$data = $this->User_model->find($id);
echo json_encode(array("data"=>$data));
}
public function language(){
$lang = isset($_GET['lang']) ? $_GET['lang'] : "en_US" ;
switch($lang){
case "en_US":
$field = "en";
break;
case "zh_CN";
$field = "zh";
break;
default : $field = "en";
}
$this->load->model("language_presentation_model");
$data = $this->language_presentation_model->all();
foreach($data as $value){
$res[$value['template']] = $value[$field];
}
echo json_encode(array("load"=>array("page"=>$res)));
}
public function master_setting(){
$data = $this->master_setting_model->find(1);
echo json_encode(array("data"=>$data));
}
public function store_master_setting(){
$post_data = $this->input_data;
$result = $this->master_setting_model->update(1,$post_data);
echo json_encode(array("data"=>$result));
}
}
<file_sep>/angularjs/scripts/services.api.js
angular.module('app.services', [])
/* Post Data to API */
.factory('API',function($http,$q){
return{
get: function(api_url) {
var returnData = $q.defer();
$http({
url: api_url,
method: 'GET'
}).success(function(data) {
returnData.resolve(data);
}).error(function(error) {
console.log(error);
returnData.reject();
});
// returns the promise of the API call - whether successful or not
return returnData.promise;
},
post: function(api_url,obj) {
// tell Angular to wait for iiiiiiiiiiiit....
var returnData = $q.defer();
$http({
url: api_url,
method: "POST",
data: obj
}).success(function(data) {
returnData.resolve(data);
}).error(function(error) {
console.log(error);
returnData.reject();
});
// returns the promise of the API call - whether successful or not
return returnData.promise;
}
}
})
/* Url Config */
.service('PathApiService',function(){
var report = base_url+'index.php/Report';
var login = base_url+'index.php/AuthController';
var api = base_url+'index.php/ApiController';
var company = base_url+'index.php/company';
var department = base_url+'index.php/department';
var pos_api = base_url+'index.php/Api';
var pos_api_2 = base_url+'index.php/PosApi';
var customer_group = base_url+'index.php/CustomerGroup';
var customer_list = base_url+'index.php/CustomerList';
var customer_detail = base_url+'index.php/CustomerDetails';
var customer_outlet = base_url+'index.php/CustomerOutlet';
var project_group = base_url+'index.php/ProjectGroup';
var job_sheet = base_url+'index.php/JobsheetList';
var project_meeting = base_url+'index.php/ProjectMeeting';
var project_quotation = base_url+'index.php/ProjectQuotation';
var project_invoice = base_url+'index.php/ProjectInvoice';
var project_list = base_url+'index.php/ProjectList';
var project_invoice_payment = base_url+'index.php/ProjectInvoicePayment';
var project_task = base_url+'index.php/ProjectTask';
var project_sow = base_url+'index.php/ProjectSow';
var job = base_url+'index.php/Job';
var project_detail = base_url+'index.php/ProjectDetail';
var user = base_url+'index.php/User';
var user_group = base_url+'index.php/UserGroup';
var user_scheme = base_url+'index.php/UserScheme';
var product_group = base_url+'index.php/ProductGroup';
var product_list = base_url+'index.php/ProductList';
var product_detail = base_url+'index.php/ProductDetail';
var payment_terms = base_url+'index.php/PaymentTerms';
var language = base_url+'index.php/Language';
var payment_method = base_url+'index.php/PaymentMethod';
var statement_account = base_url+'index.php/StatementAccount';
var vendor_group = base_url+'index.php/VendorGroup';
var vendor = base_url+'index.php/Vendor';
var send_email = base_url+'index.php/SendEmail';
var purchase_order = base_url+'index.php/PurchaseOrder';
var purchase_payment = base_url+'index.php/PurchasePayment';
var Purchase_Multiple_Payment = base_url+'index.php/PurchaseMultiplePayment';
var purchase_arrival = base_url+'index.php/PurchaseArrival';
var sales_list = base_url+'index.php/SalesList';
var sales_payment = base_url+'index.php/SalesPayment';
var sales_delivery = base_url+'index.php/SalesDelivery';
var delivery_order = base_url+'index.php/DeliveryOrder';
var sales_invoice = base_url+'index.php/SalesInvoice';
var expenses_list = base_url+'index.php/Expenses';
var expenses_category = base_url+'index.php/ExpensesCategory';
var expenses_subcategory = base_url+'index.php/ExpensesSubcategory';
var employee = base_url+'index.php/employee';
var prefix = base_url+'index.php/Prefix';
var system_settings = base_url+'index.php/systemSettings';
var transaction_tax = base_url+'index.php/TransactionTax';
var pos_temp = base_url+'index.php/PosTemp';
var product_favorite = base_url+'index.php/ProductFavorite';
var report_product_stock = base_url+'index.php/ReportProductStock';
var report_commission = base_url+'index.php/ReportCommission';
return {
report_commission : function() {return report_commission;},
report_product_stock : function() {return report_product_stock;},
report : function() {return report;},
prefix : function() {return prefix;},
login : function() {return login;},
company : function() {return company;},
department : function() {return department;},
api : function() {return api;},
customer_group : function() {return customer_group;},
customer_list : function() {return customer_list;},
customer_detail : function() {return customer_detail;},
project_group : function() {return project_group;},
job_sheet : function() {return job_sheet;},
project_list : function() {return project_list;},
project_meeting : function() {return project_meeting;},
user : function() {return user;},
user_group : function() {return user_group;},
user_scheme : function() {return user_scheme;},
project_quotation : function() {return project_quotation;},
product_group : function() {return product_group;},
product_list : function() {return product_list;},
project_invoice : function() {return project_invoice;},
project_invoice_payment : function() {return project_invoice_payment;},
payment_terms : function() {return payment_terms;},
product_detail : function() {return product_detail;},
project_task : function() {return project_task;},
customer_outlet : function() {return customer_outlet;},
language : function() {return language;},
project_sow : function() {return project_sow;},
customer_detail : function() {return customer_detail;},
statement_account : function(){return statement_account;},
payment_method : function() {return payment_method;},
job : function() {return job;},
vendor : function() {return vendor;},
vendor_group : function() {return vendor_group;},
send_email : function() {return send_email;},
purchase_order : function() {return purchase_order;},
purchase_payment : function() {return purchase_payment;},
purchase_arrival : function() {return purchase_arrival;},
project_detail : function() {return project_detail;},
expenses_list : function() {return expenses_list;},
expenses_category: function() {return expenses_category;},
expenses_subcategory : function() {return expenses_subcategory;},
employee : function() {return employee;},
prefix : function() {return prefix;},
system_settings : function() {return system_settings;},
transaction_tax : function() {return transaction_tax;},
sales_list : function() {return sales_list;},
sales_payment : function() {return sales_payment;},
sales_delivery : function() {return sales_delivery;},
delivery_order : function() {return delivery_order;},
sales_invoice : function() {return sales_invoice;},
pos_temp : function() {return pos_temp;},
product_fav : function() {return product_favorite;},
pos_api : function() {return pos_api;},
pos_api_2 : function() {return pos_api_2;}
};
})
/* Auth Config */
.service('AuthService', function($q, $http, USER_ROLES) {
var LOCAL_TOKEN_KEY = 'JumpHigh1234567890!@#$%^&&*)_';
var username = '';
var user_id = '';
var isAuthenticated = false;
var role = '';
var authToken;
function loadUserCredentials() {
var token = window.localStorage.getItem(LOCAL_TOKEN_KEY);
if (token) {
useCredentials(token);
}
}
function storeUserCredentials(token) {
window.localStorage.setItem(LOCAL_TOKEN_KEY, token);
useCredentials(token);
}
function useCredentials(token) {
username = token.split('.')[0];
isAuthenticated = true;
authToken = token;
user_id = token.split('.')[1];
switch(token.split('.')[2]){
case "1":
role = USER_ROLES.admin;
break;
default : role = "user";
}
//role = USER_ROLES.admin
// Set the token as header for your requests!
$http.defaults.headers.common['X-Auth-Token'] = token;
}
function destroyUserCredentials() {
authToken = undefined;
username = '';
role = '';
isAuthenticated = false;
user_id = '';
$http.defaults.headers.common['X-Auth-Token'] = undefined;
window.localStorage.removeItem(LOCAL_TOKEN_KEY);
}
var login = function(data) {
return $q(function(resolve, reject) {
if(data.error == 0){
// Make a request and receive your auth token from your server
storeUserCredentials(data.data.full_name+'.'+data.data.id+'.'+data.data.user_access_id);
resolve('Login success.');
} else {
reject('Login Failed.');
}
});
};
var logout = function() {
destroyUserCredentials();
};
var isAuthorized = function(authorizedRoles) {
if (!angular.isArray(authorizedRoles)) {
authorizedRoles = [authorizedRoles];
}
return (isAuthenticated && authorizedRoles.indexOf(role) !== -1);
};
loadUserCredentials();
return {
login : login,
logout : logout,
isAuthorized : isAuthorized,
isAuthenticated : function() {return isAuthenticated;},
username : function() {return username;},
user_id : function() {return user_id;},
role : function() {return role;}
};
})
.factory('AuthInterceptor', function ($rootScope, $q, AUTH_EVENTS) {
return {
responseError: function (response) {
$rootScope.$broadcast({
401: AUTH_EVENTS.notAuthenticated,
403: AUTH_EVENTS.notAuthorized
}[response.status], response);
return $q.reject(response);
}
};
})
.config(function ($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
})
.factory('Func', function() {
return {
isUndefined : function(val){
//return angular.isUndefined(val) || val === null ;
return !angular.isDefined(val) || val===null;
},
isNumber : function(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}
}
});<file_sep>/application/libraries/Access_management.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Access_management
{
private $function_name = '';
public function generate_admin_sidemenu_angular(){
$ci =& get_instance();
$user_data = $ci->session->userdata('adminData');
$result = array();
$sidemenu = "";
if($user_data['username'] != ''){
//if($user_data['username'] == 'root'){
/* root access only */
$categories = "SELECT a.* FROM t_access_category a LEFT JOIN t_access_item b ON a.id = b.access_category_id WHERE b.route IS NOT NULL GROUP BY a.id ORDER BY a.display_order ASC ";
$categories = $ci->db->query($categories)->result_array();
foreach($categories as $category){
$menus = $ci->App_model->all("t_access_item"," AND access_category_id = ".$category['id']." AND route IS NOT NULL AND display = 1 ORDER BY display_order ASC");
$child = array();
if(count($menus) != 0){
foreach($menus as $menu){
$child[] = array(
"label" => strtoupper($menu['code']),
"routes" => $menu['route']
);
}
}
$result[] = array(
"label" => strtoupper($category['code']),
"routes" => $category['route'],
"icon" => $category['icon'],
"menu_active" => $category['menu_active'],
"child" => $child
);
}
}
return $result;
}
/* */
}<file_sep>/angularjs/controllers/main.js
'use strict';
angular.module('app')
.controller('MainCtrl', ['$scope', '$translate', '$localStorage', '$location', '$rootScope','USER_ROLES','AuthService','$state','API','PathApiService','AuthService',
function ( $scope, $translate, $localStorage, $location, $rootScope , USER_ROLES, AuthService,$state,API,PathApiService ) {
$scope.logout = function() {
API.post(PathApiService.login()+'/logout/',{user_id:AuthService.user_id()}).then(function(result){});
AuthService.logout();
$state.go('appSimple.login');
};
}]);
<file_sep>/application/models/App_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class App_model extends CI_Model {
protected $input_data;
protected $temporary_data;
protected $data;
protected $controller_name;
protected $module_name;
protected $function_name;
protected $result;
protected $table;
protected $_user_id;
protected $_username;
public function __construct(){
parent::__construct();
// $this->load->database();
$this->_user_id = $this->session->userdata("user_id");
$userData = $this->session->userdata("adminData");
if(isset($userData['id'])){
$this->_user_id = $userData['id'];
$this->_username = $userData['username'];
}else{
$this->_user_id = 0;
$this->_username = 'Guest';
}
}
function count_filtered($table,$column,$order)
{
$this->_get_datatables_query($table,$column,$order);
$this->db->where("deleted_at IS NULL");
$query = $this->db->get();
return $query->num_rows();
}
public function count_all($table)
{
$this->db->where("deleted_at IS NULL");
$this->db->from($table);
return $this->db->count_all_results();
}
public function get_by_id($table,$id)
{
$this->db->from($table);
$this->db->where('id',$id);
$query = $this->db->get();
return $query->row();
}
private function getInsertId(){
return $this->db->insert_id();
}
private function insert($table,$data,$log = 1){
foreach($data as $key=>$val){
if ($this->db->field_exists($key, $table)){
$insert[$key] = $val;
}
}
$insert["created_at"] = date("Y-m-d H:i:s");
$insert['created_by'] = $this->_user_id;
$this->db->insert($table, $insert);
$insert_id = $this->db->insert_id();
$query = $this->db->last_query();
return $insert_id;
}
private function query($query){
return $this->db->query($query);
}
private function executeQuery($query){
$res = $this->db->query($query);
return $res;
}
private function readAllRows($table, $additional_criteria = "",$data_status = ""){
$data = array();
if($data_status == "")
{
$where = " WHERE deleted_at IS NULL";
}
else if($data_status == "only_trash"){
$where = " WHERE deleted_at IS NOT NULL";
}
else if($data_status == "with_trash"){
$where = " WHERE 1";
}
$where .= $additional_criteria != "" ? $additional_criteria : "";
$query = "SELECT * FROM " . $table . $where;
$rows = $this->executeQuery($query);
foreach ($rows->result_array() as $row) {
foreach($row as $key=>$val){
$row[$key] = $val;
}
$data[] = $row;
}
return $data;
}
private function readRowInfo($table, $id, $by = "", $additional_criteria = ""){
$data = array();
if ($by == "") $by = "id";
$where = ($id != "") ? " WHERE $by = '$id'" : "";
$where .= $additional_criteria != "" ? $additional_criteria : "";
$query = "SELECT * FROM " . $table . $where;
$rows = $this->executeQuery($query);
foreach ($rows->result_array() as $row) {
$data = $row;
}
return $data;
}
private function updateRow($data,$table,$id,$by,$log = 1){
foreach($data as $key=>$val){
if ($this->db->field_exists($key, $table)){
$update[$key] = $val;
}
}
$update["updated_at"] = date("Y-m-d H:i:s");
$update['updated_by'] = $this->_user_id;
$this->db->where($by,$id);
$this->db->update($table, $update);
$query = $this->db->last_query();
if($log == 1){
$this->log($table,$data,$id,"update",$query);
}
}
private function countRows($table, $additional_criteria = "",$data_status = ""){
if($data_status == "")
{
$where = " WHERE deleted_at IS NULL";
}
else if($data_status == "only_trash"){
$where = " WHERE deleted_at IS NOT NULL";
}
else if($data_status == "with_trash"){
$where = " WHERE 1";
}
$where .= $additional_criteria != "" ? $additional_criteria : "";
$query = "SELECT COUNT(*) as cnt FROM " . $table . $where;
$rows = $this->executeQuery($query);
foreach ($rows->result_array() as $row)
{
$count = isset($row['cnt']) ? $row['cnt'] : "";
}
return $count;
}
private function DeleteRow($table,$id,$by,$log = 1){
$data["deleted_at"] = date("Y-m-d H:i:s");
$data['deleted_by'] = $this->_user_id;
$this->db->where($by,$id);
$this->db->update($table, $data);
$query = $this->db->last_query();
$data = $this->readRowInfo($table,$id);
if($log == 1){
$this->log($table,$data,$id,"deactive",$query);
}
}
private function restoreRow($table,$id,$by,$log = 1){
$data["deleted_at"] = NULL;
$data['deleted_by'] = $this->_user_id;
$this->db->where($by,$id);
$this->db->update($table, $data);
$query = $this->db->last_query();
$data = $this->readRowInfo($table,$id);
if($log == 1){
$this->log($table,$data,$id,"restore",$query);
}
}
private function realDeleteRow($table,$id,$data = NULL,$log = 1){
$this->db->where('id', $id);
$data = $this->readRowInfo($table,$id);
$this->db->delete($table);
$query = $this->db->last_query();
if($log == 1){
$this->log($table,$data,$id,"restore",$query);
}
}
private function log($table,$data,$id,$action,$query){
$month = date("m-Y");
$ip = $this->input->ip_address();
$userData = $this->session->userdata("adminData");
if(isset($userData['id'])){
$user_id = $userData['id'];
$user_name = $userData['username'];
}else{
$user_id = 0;
$user_name = "guest";
}
$insert['ip'] = $ip;
$insert['user_id'] = $userData['id'];
$insert['user_name'] = $user_name;
$insert['affected_table'] = $table;
$insert['affected_id'] = $id;
$insert['query'] = $query;
$insert['action'] = $action;
$insert['data'] = json_encode($data);
$insert['wording_log'] = $user_name." ".$action." ".$table;
$insert["created_at"] = date("Y-m-d H:i:s");
//$this->db->insert("log", $insert);
$txt = implode(" ",$insert);
$myfile = file_put_contents('logs/'.$month.'.txt', $txt.PHP_EOL , FILE_APPEND);
}
public function add($table,$data)
{
return $this->insert($table,$data);
}
public function all($table,$custom_where="",$data_status=""){
$rows = $this->readAllRows($table,$custom_where,$data_status);
return $rows;
}
public function find($table,$id,$by='id',$custom_where="")
{
$rows = $this->readRowInfo($table, $id,$by,$custom_where);
return $rows;
}
public function count($table,$custom_where="")
{
$num = $this->countRows($table, $custom_where);
return $num;
}
public function update($table,$table_id,$id,$data,$by = null)
{
if($by == null){
$by = $table_id;
}
$this->updateRow($data, $table,$id,$by);
}
public function delete($table,$table_id,$id,$by = null){
if($by==null)
{
$by = $this->table_id;
}
$this->deleteRow($table,$id,$by);
}
public function realDelete($table,$table_id,$id){
$this->realDeleteRow($table,$id,$table_id);
}
public function soft_delete($table,$table_id,$id){
$this->deleteRow($table,$id,$table_id);
}
public function restore($id){
$this->restoreRow($table,$id,$this->table_id);
}
public function check_Mypassword($psw)
{
$match = FALSE;
$user_id = $this->session->userdata("user_id");
$user = $this->app_model->find('user',$user_id);
$pass =md5(strtolower($psw));
if ($user['password'] == $pass )
{
$match = TRUE;
}
return $match;
}
public function changeMypassword($new_password,$user_id)
{
$this->db->query('update user set password ="'. $new_password .'" where id = '.$user_id);
}
//Konversi tanggal
public function tgl_sql($date){
$exp = explode('-',$date);
if(count($exp) == 3) {
$date = $exp[2].'-'.$exp[1].'-'.$exp[0];
}
return $date;
}
public function tgl_str($date){
$exp = explode('-',$date);
if(count($exp) == 3) {
$date = $exp[2].'-'.$exp[1].'-'.$exp[0];
}
return $date;
}
public function tgl_jam_sql($date){
$exp =explode(' ',$date);
$tgl = $exp[0];
$jam = $exp[1];
$exp = explode('-',$tgl);
if(count($exp) == 3) {
$date = $exp[2].'-'.$exp[1].'-'.$exp[0];
}
return $date.' '.$jam;
}
public function tgl_jam_str($date){
$exp =explode(' ',$date);
$tgl = $exp[0];
$jam = $exp[1];
$exp = explode('-',$tgl);
if(count($exp) == 3) {
$date = $exp[2].'-'.$exp[1].'-'.$exp[0];
}
return $date.' '.$jam;
}
/* Tanggal dan Jam */
public function Jam_Now(){
date_default_timezone_set("Asia/Jakarta");
$jam = date("H:i:s");
return $jam;
//echo "$jam WIB";
}
public function Hari_Bulan_Indo(){
date_default_timezone_set('Asia/Jakarta'); // PHP 6 mengharuskan penyebutan timezone.
$seminggu = array("Minggu","Senin","Selasa","Rabu","Kamis","Jum\'at","Sabtu");
$hari = date("w");
$hari_ini = $seminggu[$hari];
return $hari_ini;
}
public function tgl_indo($tanggal){
date_default_timezone_set('Asia/Jakarta'); // PHP 6 mengharuskan penyebutan timezone.
$tgl = $tanggal; //date("Y m d");
$tanggal = substr($tgl,8,2);
$bulan = $this->app_model->getBulan(substr($tgl,5,2));
$tahun = substr($tgl,0,4);
return $tanggal.' '.$bulan.' '.$tahun;
}
public function tgl_now_indo(){
date_default_timezone_set('Asia/Jakarta'); // PHP 6 mengharuskan penyebutan timezone.
$tgl = date("Y m d");
$tanggal = substr($tgl,8,2);
$bulan = $this->app_model->getBulan(substr($tgl,5,2));
$tahun = substr($tgl,0,4);
return $tanggal.' '.$bulan.' '.$tahun;
}
public function getBulan($bln){
switch ($bln){
case 1:
return "Januari";
break;
case 2:
return "Februari";
break;
case 3:
return "Maret";
break;
case 4:
return "April";
break;
case 5:
return "Mei";
break;
case 6:
return "Juni";
break;
case 7:
return "Juli";
break;
case 8:
return "Agustus";
break;
case 9:
return "September";
break;
case 10:
return "Oktober";
break;
case 11:
return "November";
break;
case 12:
return "Desember";
break;
}
}
/*fungsi terbilang*/
public function bilang($x) {
$x = abs($x);
$angka = array("", "satu", "dua", "tiga", "empat", "lima",
"enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
$result = "";
if ($x <12) {
$result = " ". $angka[$x];
} else if ($x <20) {
$result = $this->app_model->bilang($x - 10). " belas";
} else if ($x <100) {
$result = $this->app_model->bilang($x/10)." puluh". $this->app_model->bilang($x % 10);
} else if ($x <200) {
$result = " seratus" . $this->app_model->bilang($x - 100);
} else if ($x <1000) {
$result = $this->app_model->bilang($x/100) . " ratus" . $this->app_model->bilang($x % 100);
} else if ($x <2000) {
$result = " seribu" . $this->app_model->bilang($x - 1000);
} else if ($x <1000000) {
$result = $this->app_model->bilang($x/1000) . " ribu" . $this->app_model->bilang($x % 1000);
} else if ($x <1000000000) {
$result = $this->app_model->bilang($x/1000000) . " juta" . $this->app_model->bilang($x % 1000000);
} else if ($x <1000000000000) {
$result = $this->app_model->bilang($x/1000000000) . " milyar" . $this->app_model->bilang(fmod($x,1000000000));
} else if ($x <1000000000000000) {
$result = $this->app_model->bilang($x/1000000000000) . " trilyun" . $this->app_model->bilang(fmod($x,1000000000000));
}
return $result;
}
public function terbilang($x, $style=4) {
if($x<0) {
$hasil = "minus ". trim($this->app_model->bilang($x));
} else {
$hasil = trim($this->app_model->bilang($x));
}
switch ($style) {
case 1:
$hasil = strtoupper($hasil);
break;
case 2:
$hasil = strtolower($hasil);
break;
case 3:
$hasil = ucwords($hasil);
break;
default:
$hasil = ucfirst($hasil);
break;
}
return $hasil;
}
}
/* End of file app_model.php */
/* Location: ./application/models/app_model.php */<file_sep>/application/core/AR_Controller.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class AR_Controller extends CI_Controller {
protected $input_data;
protected $temporary_data;
protected $data;
protected $controller_name;
protected $module_name;
protected $function_name;
protected $result;
public function __construct(){
parent::__construct();
if($_POST){
$this->input_data = $this->input->post();
}
else if($_GET){
$this->input_data = $this->input->get();
} else {
$this->load->model("user_model");
$this->input_data = json_decode(file_get_contents("php://input"), true);
}
$this->result['error'] = 1;
$this->result['msg'] = "Woopps...";
$this->result['data'] = null;
}
public function set_session(){
$post_data = $this->input_data;
if(isset($post_data['user_id'])){
$user_id = $post_data['user_id'];
$userData = $this->user_model->find($user_id);
$this->session->set_userdata("adminData",$userData);
}
}
}
/* End of file AR_Controller.php */
/* Location: ./application/core/AR_Controller.php */<file_sep>/application/models/User_access_group_model.php
<?php
class User_Access_Group_Model extends AR_Model {
public function __construct(){
parent::__construct();
$this->allow_insert = "code,description";
$this->allow_update = "code,description";
$this->tblName = "user_group";
$this->tblId = "id";
}
public function all_detail($id){
$group = $this->find($id);
$this->load->model("user_access_model");
$group['items'] = $this->user_access_model->all(" AND user_access_group_id = $id");
return $group;
}
public function get_allowed_access($id){
$data = array();
$group = $this->find($id);
$this->load->model("user_access_model");
$items = $this->user_access_model->all(" AND user_access_group_id = $id AND access_type != 'none'");
foreach($items as $item){
$data[] = $item['access_item_id'];
}
return $data;
}
}<file_sep>/application/models/Access_item_group_model.php
<?php
/**
* User: gamalan
* Date: 3/17/2015
* Time: 10:06 AM
*/
class access_item_group_model extends AR_Model {
public function __construct(){
parent::__construct();
$this->tblName = "t_access_category";
$this->tblId = "id";
}
public function all_details(){
$datas = array();
$groups = $this->all();
$this->load->model("access_item_model");
foreach($groups as $group){
$items = $this->access_item_model->all(" AND access_category_id = ".$group['id'] );
$group['items'] = $items;
$datas[] = $group;
}
return $datas;
}
} | 030f77f5852cbb13e2ccc3272492fade11659a94 | [
"JavaScript",
"PHP"
] | 15 | PHP | rullymartanto/Angularjs-Codeigniter-GenesisUI | f2a31b58c1e61e6c8282958d211838881b450f9a | 1748bcb42f1d12859eca4008e4ad40dc00578ad3 | |
refs/heads/master | <repo_name>SalomonFrux/EventsAndDelegates<file_sep>/VideoUploader.cs
using System;
using System.Threading;
namespace EventsAndDelegates
{
public class VideoUploadedEventArgs
{
public Video Video { get; set; }
}
public class VideoUploader
{
// public delegate void VideoUploaderEventHandler(object source, EventArgs args);
public event EventHandler<VideoUploadedEventArgs> VideoUploaded;
public void Encode(Video video)
{
if (string.IsNullOrWhiteSpace(video.VideoTitle))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(" No video was uploaded");
}
//The encoding logic would not be implemented for now
else
{
Console.WriteLine("The video is being Uploaded...");
Thread.Sleep(3000);
//We want to notify the subscribers anytime a video is uploaded: that where we use events
OnVideoUploaded(video);
}
}
protected void OnVideoUploaded(Video video)
{
VideoUploaded?.Invoke(this, new VideoUploadedEventArgs(){Video = video} );
}
}
}<file_sep>/README.md
# EventsAndDelegates
Helped me get a better understanding of this concept which help extend and application without breaking it in a real world example
<file_sep>/SmsSenderOnVideoUploaded.cs
using System;
namespace EventsAndDelegates
{
public class SmsSenderOnVideoUploaded
{
public void SendSmsOnVideoUploaded(object source, VideoUploadedEventArgs eventArgs)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Video: "+eventArgs.Video.VideoTitle +" uploaded, sending an sms to the uploader...");
}
}
}<file_sep>/Program.cs
using System;
namespace EventsAndDelegates
{
class Program
{
static void Main(string[] args)
{
var video = new Video(){VideoTitle = "<NAME>"};
var uploader = new VideoUploader();
var smsSender = new SmsSenderOnVideoUploaded();
var mailSender = new MailSender();
uploader.VideoUploaded += mailSender.SendMailOnVideoUploaded;
uploader.VideoUploaded += smsSender.SendSmsOnVideoUploaded;
uploader.Encode(video);
Console.Read();
}
}
}
<file_sep>/MailSender.cs
using System;
namespace EventsAndDelegates
{
public class MailSender
{
public void SendMailOnVideoUploaded(object source, VideoUploadedEventArgs eventArgs)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Video: "+eventArgs.Video.VideoTitle + " uploaded sending an Email to the uploader...");
}
}
} | 0147f21a678c140eec2a657d14857e86a29f637e | [
"Markdown",
"C#"
] | 5 | C# | SalomonFrux/EventsAndDelegates | 362a3116fbda21bb15dac033b4d10da5f4c3eb28 | 87ebaef57156968d0e405ebe5b6bb6a163073eff | |
refs/heads/master | <repo_name>juanlasarte4/DesarrolloDeInterfaces1-EVAL<file_sep>/src/unidad1/practica1/facturacion/UtilidadesCalculoIVA.java
package unidad1.practica1.facturacion;
import java.util.Calendar;
import java.util.List;
public class UtilidadesCalculoIVA {
// CALCULO 3 MESES ANTERIORES 1 DEL MES AL ACTUAL
public static double calculoIVATrimestral(List<Factura> listaFacturas, int año, int mes) {
double IVATrimestral = 0;
for (var factura : listaFacturas) {
Calendar fechaActual = new Calendar.Builder().setDate(año, mes, 1).build(),
fecha3MesesAntes = (Calendar) fechaActual.clone();
fecha3MesesAntes.add(Calendar.MONTH, -3);
fecha3MesesAntes.add(Calendar.DAY_OF_MONTH, -1);
if (factura.getFecha().before(fechaActual) && factura.getFecha().after(fecha3MesesAntes)) {
IVATrimestral += UtilidadesFactura.calcularIVAFactura(factura);
}
}
return IVATrimestral;
}
// NOTA: FACTURAS ES UNA LISTA QUE PUEDE TENER 0, 1 O VARIAS FACTURAS DE CUALQUIER AÑO
public static double calculoIVAMesActual(List<Factura> listaFacturas, int año, int mes) {
double IVAMesActual = 0;
for (var factura : listaFacturas) {
Calendar ultimoDiaDelMesAnterior = new Calendar.Builder().setDate(año, mes, 1).build(),
primerDiaDelMesSiguiente = (Calendar) ultimoDiaDelMesAnterior.clone();
ultimoDiaDelMesAnterior.add(Calendar.DAY_OF_MONTH, -1);
primerDiaDelMesSiguiente.add(Calendar.MONTH, 1);
if (factura.getFecha().after(ultimoDiaDelMesAnterior)
&& factura.getFecha().before(primerDiaDelMesSiguiente)) {
IVAMesActual += UtilidadesFactura.calcularIVAFactura(factura);
}
}
return IVAMesActual;
}
}<file_sep>/src/unidad1/practica1/gestion/Ejercicio3.java
package unidad1.practica1.gestion;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import unidad1.practica1.facturacion.*;
import unidad1.practica1.facturacion.Producto.IVA;
public class Ejercicio3 {
public static void main(String[] args) {
List<Factura> facturas = Arrays.asList(
new Factura(1,
Arrays.asList(
new Producto(.70, "Botellín", IVA.Superreducido),
new Producto(1, "Tomate", IVA.Normal),
new Producto(.50, "Regaliz")
),
new Calendar.Builder().setDate(2020, Calendar.JANUARY, 5).build()
),
new Factura(2,
Arrays.asList(
new Producto(1.1, "Maíz", IVA.Normal),
new Producto(6.25, "Lechuga", IVA.Reducido),
new Producto(2.67, "Huevos")
),
new Calendar.Builder().setDate(2020, Calendar.SEPTEMBER, 17).build()
),
new Factura(3,
Arrays.asList(
new Producto(2.5, "Helado", IVA.Normal),
new Producto(0.59, "Gominolas", IVA.Normal),
new Producto(2.5, "Guisantes")
),
new Calendar.Builder().setDate(2020, Calendar.JUNE, 7).build()
),
new Factura(4,
Arrays.asList(
new Producto(5.5, "Hamburguesas", IVA.Reducido),
new Producto(3.99, "Spaguettis", IVA.Normal),
new Producto(4.78, "Merluza")
),
new Calendar.Builder().setDate(2020, Calendar.MARCH, 15).build()
),
new Factura(5,
Arrays.asList(
new Producto(5.99, "Patatas", IVA.Reducido),
new Producto(3.89, "Lentejas"),
new Producto(2, "Garbanzos", IVA.Superreducido)
),
new Calendar.Builder().setDate(2020, Calendar.OCTOBER, 12).build()
)
);
for ( var factura : facturas ) {
System.out.println(factura);
}
System.out.printf("El IVA Trimestral: %.2f€", UtilidadesCalculoIVA.calculoIVATrimestral(facturas, 2020, Calendar.JANUARY));
System.out.printf("\nEl IVA Mensual: %.2f€", UtilidadesCalculoIVA.calculoIVAMesActual(facturas, 2020, Calendar.OCTOBER));
}
}<file_sep>/src/unidad2/practica2/Memento/EjecutarMemento.java
package unidad2.practica2.Memento;
public class EjecutarMemento {
public static void main(String[] args) {
// CREAR EL OBJETO ORIGINAL CREADOR
Originator creador = new Originator("Pedro", "<NAME>");
// CREAR EL OBJETO GESTOR/VIGILANTE DEL MEMENTO
Caretaker vigilante = new Caretaker();
// CREAR EL MEMENTO Y ASOCIARLO AL OBJETO GESTOR
vigilante.setMemento(creador.createMemento());
// MOSTRAR LOS DATOS DEL OBJETO
System.out.println("Nombre completo: [" + creador.getNombre() + " " + creador.getApellidos() + "]");
// MODIFICAR LOS DATOS DEL OBJETO
creador.setNombre("María");
creador.setApellidos("<NAME>");
// MOSTRAR LOS DATOS DEL OBJETO
System.out.println("Nombre completo: [" + creador.getNombre() + " " + creador.getApellidos() + "]");
// RESTAURAR LOS DATOS DEL OBJETO
creador.setMemento(vigilante.getMemento());
// MOSTRAR LOS DATOS DEL OBJETO
System.out.println("Nombre completo: [" + creador.getNombre() + " " + creador.getApellidos() + "]");
}
} | c707e4a924eddcfd9f35dee88dccc85634f7ce62 | [
"Java"
] | 3 | Java | juanlasarte4/DesarrolloDeInterfaces1-EVAL | a1539dc97009f883bfa677b49d261761b03346a1 | 0ce532ed84a79cb5759d7333f68543da4f51db1d | |
refs/heads/master | <repo_name>matteotolloso/file_storage_server<file_sep>/Makefile
flags = -g -O3 -Wall -I ./includes -std=c99 -pedantic #-Werror
obj = ./obj/server.o ./obj/parser.o ./obj/sharedqueue.o ./obj/connection.o \
./obj/handler.o ./obj/filesystem.o ./obj/linkedlist.o
src = ./src/server.c ./src/parser.c ./src/sharedqueue.c ./src/connection.c \
./src/handler.c ./src/filesystem.c ./src/linkedlist.c
includes = ./includes/myconnection.h ./includes/myhandler.h \
./includes/myparser.h ./includes/mysharedqueue.h \
./includes/myutil.h ./includes/myfilesystem.h \
./includes/mylinkedlist.h
objpath = ./obj/
srcpath = ./src/
libpath = ./lib/
.PHONY: clean cleanall test1 test2 test3
#all
all: ./server ./client
#linking
./server: $(obj)
gcc $(obj) -o $@ -pthread
./client: $(objpath)client.o $(libpath)libServerApi.a
gcc $< -o $@ -L $(libpath) -lServerApi
#obj file for server
$(objpath)server.o: $(srcpath)server.c $(includes)
gcc $< $(flags) -c -o $@
$(objpath)parser.o: $(srcpath)parser.c $(includes)
gcc $< $(flags) -c -o $@
$(objpath)sharedqueue.o: $(srcpath)sharedqueue.c $(includes)
gcc $< $(flags) -c -o $@
$(objpath)connection.o: $(srcpath)connection.c $(includes)
gcc $< $(flags) -c -o $@
$(objpath)handler.o: $(srcpath)handler.c $(includes)
gcc $< $(flags) -c -o $@ -pthread
$(objpath)filesystem.o: $(srcpath)filesystem.c $(includes)
gcc $< $(flags) -c -o $@ -pthread
$(objpath)linkedlist.o: $(srcpath)linkedlist.c $(includes)
gcc $< $(flags) -c -o $@ -pthread
#obj file for client
$(objpath)client.o: $(srcpath)client.c $(includes)
gcc $< $(flags) -c -o $@
$(libpath)libServerApi.a: $(objpath)serverApi.o
ar rvs $(libpath)libServerApi.a $(objpath)serverApi.o
$(objpath)serverApi.o: $(srcpath)serverApi.c $(includes)
gcc $< $(flags) -c -o $@
cleanall :
./clean.sh
test1 : ./server ./client
mkdir -p tests/fileLetti
mkdir -p tests/fileEvict
./tests/test1.sh
test2 : ./server ./client
mkdir -p tests/fileLetti
mkdir -p tests/fileEvict
./tests/test2.sh
test3 : ./server ./client
mkdir -p tests/fileLetti
mkdir -p tests/fileEvict
./tests/test3.sh
<file_sep>/src/handler.c
#include <myhandler.h>
void ter_handler(int sig){
int n;
if ((sig == SIGINT) || (sig == SIGQUIT)){
n=2;
if(write(pipeSigWriting, &n, sizeof(int)) != sizeof(int)){
perror("write");
}
return;
}
if( sig == SIGHUP){
n=1;
if(write(pipeSigWriting, &n, sizeof(int)) != sizeof(int)){
perror("write");
}
return;
}
EXIT_ON(write(1, "unknown signal", 15), <= 0);
}
void print_handler(int sig){
EXIT_ON(write(2, "segnale ricevuto dal worker: %d", sig), == 0);
return;
}
void handler_installer(){
sigset_t fullmask, handlermask, complementar;
sigfillset(&fullmask);
sigemptyset(&handlermask);
sigfillset(&complementar);
EXIT_ON(pthread_sigmask(SIG_SETMASK, &fullmask, NULL), != 0);
sigaddset(&handlermask, SIGINT);
sigaddset(&handlermask, SIGQUIT);
sigaddset(&handlermask, SIGHUP);
sigdelset(&complementar, SIGINT);
sigdelset(&complementar, SIGQUIT);
sigdelset(&complementar, SIGHUP);
struct sigaction sa;
EXIT_ON(memset(&sa, 0, sizeof(struct sigaction)), == NULL);
sa.sa_handler = ter_handler;
sa.sa_mask = handlermask;
EXIT_ON( sigaction(SIGINT, &sa, NULL), != 0);
EXIT_ON( sigaction(SIGQUIT, &sa, NULL), != 0);
EXIT_ON( sigaction(SIGHUP, &sa, NULL), != 0);
EXIT_ON(pthread_sigmask(SIG_SETMASK, &complementar, NULL), != 0);
}
void worker_handler_installer(){
sigset_t fullmask;
sigfillset(&fullmask);
EXIT_ON(pthread_sigmask(SIG_SETMASK, &fullmask, NULL), != 0);
}
<file_sep>/tests/test3support.sh
#!/bin/bash
while true
do
./client -f mysock -D tests/fileEvict/ -w tests/files
./client -f mysock -d tests/fileLetti/ -r ./tests/files/100mb_file,./tests/files/30mb_file
./client -f mysock -d tests/fileLetti/ -l ./tests/files/100mb_file,./tests/files/30mb_file
done<file_sep>/src/linkedlist.c
#include <mylinkedlist.h>
void init(struct node **head, int data)
{
EXIT_ON(*head = (struct node *)malloc(sizeof(struct node)), == NULL);
(*head)->data = data;
(*head)->next = NULL;
return;
}
void list_insert(struct node **head, int data)
{
if (*head == NULL){
init(head,data);
return;
}
struct node *current = *head;
struct node *tmp;
while(current){
if(current->data == data) return;
tmp = current;
current = current->next;
}
/* create a new node after tmp */
struct node *new_node;
EXIT_ON(new_node = (struct node *)malloc(sizeof(struct node)), == NULL);
new_node->next = NULL;
new_node->data = data;
tmp->next = new_node;
return;
}
int list_mem(struct node **head, int data)
{
if (*head == NULL){
return 0;
}
struct node *current = *head;
while (current){
if (current->data == data){
return 1;
}
current = current->next;
}
return 0;
}
void list_remove(struct node **head, int data)
{
if(!list_mem(head, data)) return;
struct node *current = *head;
struct node *prev = NULL;
do {
if (current->data == data) {
break;
}
prev = current;
current = current->next;
} while (current);
/* if the first element */
if (current == *head) {
/* reuse prev */
prev = *head;
*head = current->next;
free(prev);
return;
}
/* if the last element */
if (current->next == NULL) {
prev->next = NULL;
free(current);
return;
}
prev->next = current->next;
free(current);
return;
}
void list_deinit(struct node **head)
{
struct node *node = *head;
while (node) {
struct node *tmp;
tmp = node;
node = node->next;
free(tmp);
}
}<file_sep>/includes/myconnection.h
#ifndef _MY_CONNECTION_H
#define _MY_CONNECTION_H
#define _POSIX_C_SOURCE 200809L
#include <sys/socket.h>
#include <sys/un.h>
#include <myutil.h>
#include <sys/select.h>
#include <string.h>
#include <stdio.h>
#define UNIX_PATH_MAX 108
#define MAX_CONNECTION_QUEUE 1024
int updatemax(fd_set set, int fdmax);
int init_server(char * sck_name);
int find_max(int a, int b , int c, int d, int e);
#endif /* _MY_CONNECTION_H */<file_sep>/src/serverApi.c
#include <myserverApi.h>
#include <time.h>
int socketfd = 0, myerrno;
char __sockname[UNIX_PATH_MAX];
extern int foundP;
int readNFiles(int n, char * dirname){
if(dirname == NULL){
myerrno = E_BAD_RQ;
return -1;
}
char pth[MAX_PATH], pthToSave[MAX_PATH];
int reqType = READ_N_F, resp = 0;
if(writen(socketfd, &reqType, sizeof(int)) != sizeof(int)){ // scrivo il tipo di richesta
myerrno = errno;
return -1;
}
if(writen(socketfd, &n, sizeof(int)) != sizeof(int)){ // scrivo il numero di file
myerrno = errno;
return -1;
}
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ // leggo la risposta
myerrno = errno;
return -1;
}
if(resp != 1){ // c'è stato un errore (l'unica risposta corretta è 1)
myerrno = resp;
return -1;
}
FILE* outFile; int size; void * buf;
while(1){
if(readn(socketfd, &size, sizeof(int)) != sizeof(int)){ myerrno = errno; return -1;} // leggo la size, se è -1 ho finito
if(size == -1){
break;
}
if(readn(socketfd, pth, MAX_PATH) != MAX_PATH){ myerrno = errno; return -1;} // leggo il path
EXIT_ON(buf = malloc(size), == NULL); // alloco il buffer
if(readn(socketfd, buf, size) != size){ myerrno = errno; free(buf); return -1;} // leggo il contenuto
strcpy(pthToSave, dirname);
strcat(pthToSave, pth + onlyName(pth) );
if (( outFile = fopen(pthToSave, "wb")) == NULL){
myerrno = errno;
return -1;
}
if(fwrite(buf, 1, size, outFile) != size){ // scrivo contenuto su file
myerrno = errno;
free(buf);
fclose(outFile);
return -1;
}
free(buf);
fclose(outFile);
}
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ // leggo la risposta finale
myerrno = errno;
return -1;
}
if(resp != 0){
myerrno = resp;
return -1;
}
else{
return 0;
}
}
int readFile(char * pathname, void ** buf, size_t * size){
if(socketfd == 0){
myerrno = E_NOT_CON;
return -1;
}
if(pathname == NULL){ myerrno = E_INV_PTH; return -1;}
char pth[MAX_PATH];
strncpy(pth, pathname, MAX_PATH);
pth[MAX_PATH-1] = '\0';
int reqType = READ_F, resp = 0;
if(writen(socketfd, &reqType, sizeof(int)) != sizeof(int)){ // scrivo il tipo di richesta
myerrno = errno;
return -1;
}
if(writen(socketfd, pth, MAX_PATH) != MAX_PATH){ // scrivo il path
myerrno = errno;
return -1;
}
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ // leggo la risposta
myerrno = errno;
return -1;
}
if(resp != 1){
myerrno = resp;
return -1;
}
int i_size;
char * i_buf;
if(readn(socketfd, &i_size, sizeof(int)) != sizeof(int)){ // leggo la size
myerrno = errno;
return -1;
}
EXIT_ON(i_buf = malloc(i_size), == NULL); // alloco il buffer
if(readn(socketfd, i_buf, i_size) != i_size){ // leggo il contenuto
free(i_buf);
myerrno = errno;
return -1;
}
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ // leggo la risposta
free(i_buf);
myerrno = errno;
return -1;
}
if(resp != 0){
free(i_buf);
myerrno = resp;
return -1;
}
else {
*buf = i_buf;
*size = i_size;
return 0;
}
}
int removeFile(char * pathname){
if(socketfd == 0){
myerrno = E_NOT_CON;
return -1;
}
if(pathname == NULL){ myerrno = E_INV_PTH; return -1;}
char pth[MAX_PATH];
strncpy(pth, pathname, MAX_PATH);
pth[MAX_PATH-1] = '\0';
int reqType = REMOVE_F, resp = 0;
if(writen(socketfd, &reqType, sizeof(int)) != sizeof(int)){ // scrivo il tipo di richesta
myerrno = errno;
return -1;
}
if(writen(socketfd, pth, MAX_PATH) != MAX_PATH){ // scrivo il path
myerrno = errno;
return -1;
}
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ // leggo la risposta
myerrno = errno;
return -1;
}
if(resp == 0){
return 0;
}
else{
myerrno = resp;
return -1;
}
}
int closeFile(char * pathname){
if(socketfd == 0){
myerrno = E_NOT_CON;
return -1;
}
if(pathname == NULL){ myerrno = E_INV_PTH; return -1;}
char pth[MAX_PATH];
strncpy(pth, pathname, MAX_PATH);
pth[MAX_PATH-1] = '\0';
int reqType = CLOSE_F, resp = 0;
if(writen(socketfd, &reqType, sizeof(int)) != sizeof(int)){ // scrivo il tipo di richesta
myerrno = errno;
return -1;
}
if(writen(socketfd, pth, MAX_PATH) != MAX_PATH){ // scrivo il path
myerrno = errno;
return -1;
}
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ // leggo la risposta
myerrno = errno;
return -1;
}
if(resp == 0){
return 0;
}
else{
myerrno = resp;
return -1;
}
}
int unlockFile(char * pathname){
if(socketfd == 0){
myerrno = E_NOT_CON;
return -1;
}
if(pathname == NULL){ myerrno = E_INV_PTH; return -1;}
char pth[MAX_PATH];
strncpy(pth, pathname, MAX_PATH);
pth[MAX_PATH-1] = '\0';
int reqType = UNLOCK_F, resp = 0;
if(writen(socketfd, &reqType, sizeof(int)) != sizeof(int)){ // scrivo il tipo di richesta
myerrno = errno;
return -1;
}
if(writen(socketfd, pth, MAX_PATH) != MAX_PATH){ // scrivo il path
myerrno = errno;
return -1;
}
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ // leggo la risposta
myerrno = errno;
return -1;
}
if(resp == 0){
return 0;
}
else{
myerrno = resp;
return -1;
}
}
int lockFile(char * pathname){
if(socketfd == 0){
myerrno = E_NOT_CON;
return -1;
}
if(pathname == NULL){ myerrno = E_INV_PTH; return -1;}
char pth[MAX_PATH];
strncpy(pth, pathname, MAX_PATH);
pth[MAX_PATH-1] = '\0';
int reqType = LOCK_F, resp = 0;
if(writen(socketfd, &reqType, sizeof(int)) != sizeof(int)){ // scrivo il tipo di richesta
myerrno = errno;
return -1;
}
if(writen(socketfd, pth, MAX_PATH) != MAX_PATH){ // scrivo il path
myerrno = errno;
return -1;
}
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ // leggo la risposta
myerrno = errno;
return -1;
}
if(resp == 0){
return 0;
}
else{
myerrno = resp;
return -1;
}
}
int appendToFile(char * pathname, void * buf, size_t size, char * dirname){
if(socketfd == 0){
myerrno = E_NOT_CON;
return -1;
}
if(pathname == NULL){ myerrno = E_INV_PTH; return -1;}
if(buf == NULL || size < 1){ myerrno = E_BAD_RQ; return -1;}
char pth[MAX_PATH];
strncpy(pth, pathname, MAX_PATH);
pth[MAX_PATH-1] = '\0';
int reqType = APPEND_T_F, resp = 0;
if(writen(socketfd, &reqType, sizeof(int)) != sizeof(int)){ // scrivo il tipo di richesta
myerrno = errno;
return -1;
}
if(writen(socketfd, &size, sizeof(int)) != sizeof(int)){ // scrivo la size
myerrno = errno;
return -1;
}
if(writen(socketfd, pth, MAX_PATH) != MAX_PATH){ // scrivo il path
myerrno = errno;
return -1;
}
if(writen(socketfd, buf, size) != size){ // scrivo il buffer
myerrno = errno;
return -1;
}
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ // leggo la risposta
myerrno = errno;
return -1;
}
if(resp == 0){ // non devo fare altro
return 0;
}
if(resp != 1){ // devo ricevere file
myerrno = resp;
return -1;
}
// lettura file di risposta
if(resp == 1){ // devo leggere N file: size path cont
FILE* outFile;
char pthToSave[MAX_PATH];
while(1){
if(readn(socketfd, &size, sizeof(int)) != sizeof(int)){ myerrno = errno; return -1;} // leggo la size, se è -1 ho finito
if(size == -1){
break;
}
if(readn(socketfd, pth, MAX_PATH) != MAX_PATH){ myerrno = errno; return -1;} // leggo il path
EXIT_ON(buf = malloc(size), == NULL); // alloco il buffer
if(readn(socketfd, buf, size) != size){ myerrno = errno; free(buf); return -1;} // leggo il contenuto
if(dirname != NULL){
strcpy(pthToSave, dirname);
strcat(pthToSave, pth + onlyName(pth) );
if (( outFile = fopen(pthToSave, "wb")) == NULL){
myerrno = errno;
return -1;
}
if (( outFile = fopen(pthToSave, "wb")) == NULL){
myerrno = errno;
return -1;
}
if(fwrite(buf, 1, size, outFile) != size){ // scrivo contenuto su file
myerrno = errno;
free(buf);
fclose(outFile);
return -1;
}
fclose(outFile);
}
free(buf);
}
}
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ myerrno = errno; return -1;}
if(resp == 0){
return 0;
}
else{
myerrno = resp;
return -1;
}
}
int writeFile(char* pathname, char * dirname){
if(socketfd == 0){
myerrno = E_NOT_CON;
return -1;
}
if(pathname == NULL){
myerrno = E_INV_PTH;
return -1;
}
char pth[MAX_PATH], *buf;
strncpy(pth, pathname, MAX_PATH);
pth[MAX_PATH-1] = '\0';
int reqType = WRITE_F, resp = 0;
FILE * inFile;
if((inFile = fopen(pth, "rb")) == NULL){
myerrno = errno;
fprintf(stderr,"impossibile aprire file\n");
return -1;
}
// leggo il file
int size = 0;
fseek(inFile, 0, SEEK_END);
size = ftell(inFile);
fseek(inFile, 0, SEEK_SET);
EXIT_ON(buf = malloc(size), == NULL);
if( fread(buf, 1, size, inFile) != size){
fprintf(stderr, "impossibile leggere il file\n");
myerrno = errno;
free(buf);
return -1;
}
fclose(inFile);
if(writen(socketfd, &reqType, sizeof(int)) != sizeof(int)){ // scrivo il tipo di richesta
myerrno = errno;
return -1;
}
if(writen(socketfd, &size, sizeof(int)) != sizeof(int)){ // scrivo la size
myerrno = errno;
return -1;
}
if(writen(socketfd, pth, MAX_PATH) != MAX_PATH){ // scrivo il path
myerrno = errno;
return -1;
}
if(writen(socketfd, buf, size) != size){ // scrivo il contenuto
myerrno = errno;
return -1;
}
free(buf);
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ // leggo la risposta
myerrno = errno;
return -1;
}
if(resp == 0){
return 0;
}
if(resp != 1){
myerrno = resp;
return -1;
}
// lettura file di risposta
if(resp == 1){ // devo leggere N file: size path cont
FILE* outFile; char pthToSave[MAX_PATH];
while(1){
if(readn(socketfd, &size, sizeof(int)) != sizeof(int)){ myerrno = errno; return -1;} // leggo la size, se è -1 ho finito
if(size == -1){
break;
}
if(readn(socketfd, pth, MAX_PATH) != MAX_PATH){ myerrno = errno; return -1;} // leggo il path
EXIT_ON(buf = malloc(size), == NULL); // alloco il buffer
if(readn(socketfd, buf, size) != size){ myerrno = errno; free(buf); return -1;} // leggo il contenuto
if(dirname != NULL){
strcpy(pthToSave, dirname);
strcat(pthToSave, pth + onlyName(pth) );
if (( outFile = fopen(pthToSave, "wb")) == NULL){
myerrno = errno;
return -1;
}
if (( outFile = fopen(pthToSave, "wb")) == NULL){
myerrno = errno;
return -1;
}
if(fwrite(buf, 1, size, outFile) != size){ // scrivo contenuto su file
myerrno = errno;
free(buf);
fclose(outFile);
return -1;
}
fclose(outFile);
}
free(buf);
}
}
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ // leggo la risposta
myerrno = errno;
return -1;
}
if(resp == 0){
return 0;
}
else{
myerrno = resp;
return -1;
}
}
int openFile(const char* pathname, int flags){
if(socketfd == 0){
myerrno = E_NOT_CON;
return -1;
}
if(flags < 0 || flags > 3) {
myerrno = E_INV_FLG;
return -1;
}
char pth[MAX_PATH];
strncpy(pth, pathname, MAX_PATH);
pth[MAX_PATH-1] = '\0';
int reqType = OPEN_F;
int resp = 0;
if(pth == NULL){
myerrno = E_INV_PTH;
return -1;
}
if(writen(socketfd, &reqType, sizeof(int)) != sizeof(int)){ // scrivo il tipo di richesta
myerrno = errno;
return -1;
}
if(writen(socketfd, &pth, MAX_PATH) != MAX_PATH){ // scrivo il path
myerrno = errno;
return -1;
}
if(writen(socketfd, &flags, sizeof(int)) != sizeof(int)){ // scrivo i flag
myerrno = errno;
return -1;
}
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ // leggo la risposta
myerrno = errno;
return -1;
}
if(resp == 0){
return 0;
}
else if (resp != 1){
myerrno = resp;
return -1;
}
// c'è un file da salvare
int size; void * buf;
if(readn(socketfd, &size, sizeof(int)) != sizeof(int)){ myerrno = errno; return -1;} // leggo la size
if(readn(socketfd, pth, MAX_PATH) != MAX_PATH){ myerrno = errno; return -1;} // leggo il path
EXIT_ON(buf = malloc(size), == NULL); // alloco il buffer
if(readn(socketfd, buf, size) != size){ myerrno = errno; free(buf); return -1;} // leggo il contenuto
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ myerrno = errno; return -1;} // leggo la risposta di fine file
if(resp != -1){ // è successo qualcosa di strano
myerrno = E_BAD_RQ;
return -1;
}
if(readn(socketfd, &resp, sizeof(int)) != sizeof(int)){ myerrno = errno; return -1;} // leggo la risposta finale
if(resp != 0){ // è successo qualcosa di strano
myerrno = resp;
return -1;
}
else{
return 0;
}
}
int openConnection(const char* sockname , int msec, const struct timespec abstime){
if (sockname == NULL || strnlen(sockname, UNIX_PATH_MAX) >= UNIX_PATH_MAX) {
myerrno = E_INV_SCK;
return -1;
}
strcpy(__sockname, sockname);
struct sockaddr_un server_addr;
socketfd = socket(AF_UNIX, SOCK_STREAM, 0);
if(socketfd == -1) {
myerrno = errno;
return -1;
}
if (memset(&server_addr, 0, sizeof(server_addr)) == NULL) return -1;
server_addr.sun_family = AF_UNIX;
strcpy(server_addr.sun_path, sockname);
struct timespec toWait, _abstime = abstime;
ms2ts(&toWait, msec);
while(_abstime.tv_nsec > 0 || _abstime.tv_sec > 0){
if (connect(socketfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) != 0) {
perror("Tentativo di connessione fallito");
}
else{
return 0;
}
nanosleep(&toWait, NULL);
timespec_diff(&_abstime, &toWait, &_abstime);
}
myerrno = errno;
return -1;
return 0;
}
void timespec_diff(struct timespec *a, struct timespec *b, struct timespec *result) {
result->tv_sec = a->tv_sec - b->tv_sec;
result->tv_nsec = a->tv_nsec - b->tv_nsec;
if (result->tv_nsec < 0) {
--result->tv_sec;
result->tv_nsec += 1000000000L;
}
}
void ms2ts(struct timespec *ts, unsigned long ms){
ts->tv_sec = ms / 1000;
ts->tv_nsec = (ms % 1000) * 1000000;
}
void msleep(int msec){
struct timespec toWait;
ms2ts(&toWait, msec);
nanosleep(&toWait, NULL);
}
int closeConnection(const char* sockname){
if(socketfd == 0){
myerrno = E_NOT_CON;
return -1;
}
if (sockname == NULL || (strncmp(__sockname, sockname, UNIX_PATH_MAX) != 0)) {
myerrno = E_INV_SCK;
return -1;
}
close(socketfd);
socketfd = 0;
return 0;
}
int onlyName(char * str){ // ./ciao/pluto
int n = 0, last = 0;
while(n < strlen(str)){
if(str[n] == '/') last = n;
n++;
}
return last;
}
int readn(int fd, void *ptr, size_t n) {
size_t nleft;
ssize_t nread;
nleft = n;
while (nleft > 0) {
if((nread = read(fd, ptr, nleft)) < 0) {
if (nleft == n) return -1; /* error, return -1 */
else break; /* error, return amount read so far */
} else if (nread == 0) break; /* EOF */
nleft -= nread;
ptr = (void*)((char*)ptr + nread);
}
return(n - nleft); /* return >= 0 */
}
int writen(int fd, void *ptr, size_t n) {
size_t nleft;
ssize_t nwritten;
nleft = n;
while (nleft > 0) {
if((nwritten = write(fd, ptr, nleft)) < 0) {
if (nleft == n) return -1; /* error, return -1 */
else break; /* error, return amount written so far */
} else if (nwritten == 0) break;
nleft -= nwritten;
ptr = (void*)((char*)ptr + nwritten);
}
return(n - nleft); /* return >= 0 */
}
void myperror(const char * str){
if(myerrno >= 140){
fprintf(stderr, "Error in \"%s\": ", str);
switch (myerrno)
{
case E_INV_FLG:
fprintf(stderr, "Invalid flags\n");
break;
case E_INV_PTH:
fprintf(stderr, "Invalid path\n");
break;
case E_LOCK:
fprintf(stderr, "File locked\n");
break;
case E_NOT_EX:
fprintf(stderr, "File not exists\n");
break;
case E_ALR_EX:
fprintf(stderr, "File already exists\n");
break;
case E_BAD_RQ:
fprintf(stderr, "Invalid request\n");
break;
case E_ALR_LK:
fprintf(stderr, "File already locked\n");
break;
case E_NO_SPACE:
fprintf(stderr, "No enough space (in server memory)\n");
break;
case E_NOT_OPN:
fprintf(stderr, "File not open\n");
break;
case E_INV_SCK:
fprintf(stderr, "Invalid socket path\n");
break;
case E_NOT_CON:
fprintf(stderr, "Not connected\n");
break;
default:
fprintf(stderr, "Unkown error\n");
break;
}
}
else{
perror(str);
}
}<file_sep>/src/server.c
#include <myparser.h>
#include <myutil.h>
#include <mysharedqueue.h>
#include <myconnection.h>
#include <myhandler.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/time.h>
#include <myfilesystem.h>
int pipeSigWriting; // from myhandler.h
FILE * logFile; // from myutil.h
void server_log(char * format, ... );
char * flgToStr(int flg);
typedef struct _worker_args{
SharedQueue_t * q;
int pipeWriting_fd;
FileSystem_t * fs;
}WorkerArgs;
void * worker(void * args){
worker_handler_installer();
SharedQueue_t * q = ((WorkerArgs *)(args))->q;
int pipeWriting_fd = ((WorkerArgs *)(args))->pipeWriting_fd;
FileSystem_t * fs = ((WorkerArgs *)(args))->fs;
while(1){
int clientFd = SharedQueue_pop(q); // preleva un client dalla coda condivisa
if(clientFd == -1) return 0; // il manager mi dice di terminare
int requestType;
if(read(clientFd, &requestType, sizeof(int)) <= 0 ){ // leggi la richesta oppure il client ha chiuso
EXIT_ON(fs_request_manager(fs, clientFd, CLOSE_ALL), != 0);
clientFd*=-1;
EXIT_ON(write(pipeWriting_fd, &clientFd, sizeof(int)), != sizeof(int)); // il manager si occuperà di chiuderlo per evitare racecondition con i fd
continue;
}
int result = fs_request_manager(fs, clientFd, requestType);
// se è 0 vuol dire che ho terminato correttamente la richiesta e devo dire al manager di rimettermi in ascolto di quel fd
// altrimenti vuol dire che il client ha chiuso inaspettatamente durante le comunicazioni e devo dire al manager di chiudere il fd
if (result == 0){
EXIT_ON(write(pipeWriting_fd, &clientFd, sizeof(int)), != sizeof(int));
}
else{
EXIT_ON(fs_request_manager(fs, clientFd, CLOSE_ALL), != 0);
clientFd*=-1; // il client ha avuto problemi e lo chiudo
EXIT_ON(write(pipeWriting_fd, &clientFd, sizeof(int)), != sizeof(int));
}
}
}
int main(int argc, char ** argv){
/* INIZIO installazione gestore segnali */
handler_installer();
/* FINE installazione gestore segnali */
/* INIZIO configurazione dei parametri dal file config.txt e del file di log */
if (argc < 2) EXIT_ON("errore parametri",);
char * sck_name, *log_path; int max_num_file, max_dim_storage, num_thread_worker;
parse(argv[1], &sck_name, &log_path, &max_num_file, &max_dim_storage, &num_thread_worker);
EXIT_ON(logFile = fopen(log_path, "w"), == NULL);
server_log("Configurazione:\nsocket name:%s\nlog_path:%s\nmax_num_file:%d\nmax_dim_storage:%d\nnum_thread_worker:%d\n",
sck_name,log_path, max_num_file, max_dim_storage, num_thread_worker);
/* FINE configurazione dei parametri dal file config.txt e del file di log */
/* INIZIO preparazione della coda concorrente, della pipe e del fs */
SharedQueue_t * ready_clients = init_SharedQueue();
int pipefd[2], pipeReadig_fd, pipeWriting_fd;
int pipefd2[2], pipeSigReading;
EXIT_ON( pipe(pipefd), != 0);
EXIT_ON( pipe(pipefd2), != 0);
pipeReadig_fd = pipefd[0];
pipeWriting_fd = pipefd[1];
pipeSigReading = pipefd2[0];
pipeSigWriting = pipefd2[1]; // dichiarata come globale in myhandler.h
FileSystem_t * fs = init_FileSystem(max_num_file, max_dim_storage);
/* FINE preaprazione della coda concorrente,della pipe e del fs */
/* INIZIO generazione dei thread worker */
pthread_t * tidArr;
EXIT_ON( tidArr = malloc(sizeof(pthread_t) * num_thread_worker), == NULL);
WorkerArgs args;
args.pipeWriting_fd = pipeWriting_fd;
args.q = ready_clients;
args.fs = fs;
for(int i=0; i<num_thread_worker; ++i){
pthread_t
ret;
EXIT_ON(pthread_create(&ret, NULL, worker, (void*)&args), != 0);
tidArr[i] = ret;
}
/* FINE generazione dei thread worker */
/* INIZIO gestione delle richeste */
int socket_fd = init_server(sck_name);
int activeClients = 0;
fd_set tmpset, set;
FD_ZERO(&tmpset);
FD_ZERO(&set);
FD_SET(socket_fd, &set);
FD_SET(pipeSigReading, &set);
FD_SET(pipeReadig_fd, &set);
int fd_max = find_max(socket_fd, pipeReadig_fd, pipeWriting_fd, pipeSigReading, pipeSigWriting);
fd_max++; // per sicurezza, perchè c'è anche da considerare il fd del file config
int endMode=0;
server_log("Server pronto");
while(endMode==0 || activeClients > 0){ // finchè non è richiesta la terminazione o ci sono client attivi
//fprintf(stderr, "\nendMode = %d, activeClients = %d, fd_max = %d\n", endMode, activeClients, fd_max);
tmpset = set;
if( select(fd_max + 1, &tmpset, NULL, NULL, NULL) == -1) // attenzione all'arrivo del segnale
{
server_log("Segnale %d ricevuto", errno);
}
if(FD_ISSET(pipeSigReading, &tmpset)){ // è arrivato un segnale
EXIT_ON(read(pipeSigReading, &endMode, sizeof(int)), != sizeof(int));
if(endMode == 1) {
FD_CLR(socket_fd, &set); // terminazione lenta, non ascolto più il socket
fd_max = updatemax(set, fd_max);
server_log("Inizio terminazione lenta");
}
if(endMode == 2){ // terminazione veloce
for(int i=0; i<fd_max+1; i++){ // chiudo i client connessi (ma che non hanno richieste in corso)
if(FD_ISSET(i, &set) && (i != pipeReadig_fd) && (i != socket_fd) && (i != pipeSigReading)){
close(i);
FD_CLR(i, &set);
}
}
FD_CLR(socket_fd, &set); // non ascolto nuove richieste di connessione
fd_max = updatemax(set, fd_max);
activeClients = 0;
server_log("Inizio terminazione veloce");
}
continue;
}
for (int i = 0; i< fd_max +1; i++){
if(FD_ISSET(i, &tmpset)){
if( i == socket_fd){ // è arrivata una nuova richesta di connessione
int newConnFd;
EXIT_ON(newConnFd = accept(socket_fd, NULL, NULL), == -1);
FD_SET(newConnFd, &set);
activeClients++;
if(newConnFd > fd_max) fd_max = newConnFd;
server_log("Nuova connessione con client %d", newConnFd);
}
else if(i == pipeReadig_fd){ // fd di ritorno dalla pipe
int returnedConnFd;
EXIT_ON(read(pipeReadig_fd, &returnedConnFd, sizeof(int)), != sizeof(int));
if ((endMode == 0) || (endMode == 1)){ // devo continuare a servire i client connessi
if(returnedConnFd < 0){ //il client ha chiuso
activeClients--;
returnedConnFd*=-1;
close(returnedConnFd);
}
else{ // il client ha terminato la richiesta correttamente
FD_SET(returnedConnFd, &set); // lo rimetto in ascolto
if(returnedConnFd > fd_max) fd_max = returnedConnFd;
}
}
else{ // sto terminando velocemente
if(returnedConnFd < 0){ //il client ha chiuso
activeClients--;
close(-1 * returnedConnFd);
}
else{ // il client ha terminato la richiesta correttamente
activeClients--;
close(returnedConnFd);
}
}
}
else{ // un client già conesso ha inviato una richiesta (oppure ha chiuso)
if (endMode != 2){ // non sto terminando velocemente
SharedQueue_push(ready_clients, i); // verrà gestito da un worker
FD_CLR(i, &set);
if (i == fd_max) fd_max = updatemax(set, fd_max);
}
else{ // sto terminando velocemente
close(i);
FD_CLR(i, &set);
if (i == fd_max) fd_max = updatemax(set, fd_max);
activeClients--;
}
}
}
}
}
server_log("Uscito dal ciclo manager");
statistiche(fs);
/* FINE gestione delle richieste */
/* INIZIO chiusura thread */
for (int i=0; i<num_thread_worker; i++){
SharedQueue_push(ready_clients, -1);
}
for (int i= 0; i< num_thread_worker; i++){
EXIT_ON(pthread_join(tidArr[i], NULL), == -1);
}
/* FINE chiusura thread */
/* INIZIO operazioni di chiusura */
// dealloca il fs con tutti i file
close(pipeReadig_fd);
close(pipeWriting_fd);
close(pipeSigReading);
close(pipeSigWriting);
remove(sck_name);
free(sck_name);
free(log_path);
free(tidArr);
//free(args);
free(ready_clients->set);
pthread_mutex_destroy(&ready_clients->lock);
pthread_cond_destroy(&ready_clients->full);
pthread_cond_destroy(&ready_clients->empty);
free(ready_clients);
deinit_FileSystem(fs);
server_log("Server terminato");
fclose(logFile);
/* FINE operazioni di chiusura */
return 0;
}
void server_log(char * format, ... ){
va_list arglist;
va_start(arglist, format);
vfprintf(logFile, format, arglist);
fprintf(logFile, "\n");
fflush(logFile);
va_end(arglist);
}
<file_sep>/tests/test1.sh
#!/bin/bash
valgrind --leak-check=full ./server tests/config3.txt &
SERVER_PID=$!
export SERVER_PID
bash -c 'sleep 3 && kill -s SIGHUP ${SERVER_PID}' &
./client -p -t 200 -f mysock -W tests/files/test1,tests/files/test2
./client -p -t 200 -f mysock -d tests/fileLetti/ -R n=0
./client -p -t 200 -f mysock -l tests/files/test1,tests/files/test2 -u tests/files/test1,tests/files/test2
./client -p -t 200 -f mysock -c tests/files/test1,tests/files/test2
sleep 1
exit 0<file_sep>/src/sharedqueue.c
#include <mysharedqueue.h>
SharedQueue_t * init_SharedQueue(){
SharedQueue_t * q;
EXIT_ON( q = (SharedQueue_t*)malloc(sizeof(SharedQueue_t)), == NULL);
EXIT_ON( memset(q, 0, sizeof(SharedQueue_t)), == NULL);
EXIT_ON(q->set = malloc(sizeof(int) * SHARED_QUEUE_MAX_DIM), == NULL);
EXIT_ON(pthread_mutex_init(&q->lock, NULL), != 0);
EXIT_ON(pthread_cond_init(&q->full, NULL), != 0);
EXIT_ON(pthread_cond_init(&q->empty, NULL), != 0);
q->start = 0;
q->current_size = 0;
return q;
}
void SharedQueue_push(SharedQueue_t * q, int fd_c){
EXIT_ON(q, == NULL);
EXIT_ON(pthread_mutex_lock(&q->lock), != 0);
while(q->current_size >= SHARED_QUEUE_MAX_DIM){
EXIT_ON(pthread_cond_wait(&q->full, &q->lock), != 0);
}
q->set[ (q->start + q->current_size) % SHARED_QUEUE_MAX_DIM] = fd_c;
q->current_size++;
EXIT_ON(pthread_cond_signal(&q->empty), != 0);
EXIT_ON(pthread_mutex_unlock(&q->lock), != 0);
}
int SharedQueue_pop(SharedQueue_t * q){
EXIT_ON(q, == NULL);
EXIT_ON(pthread_mutex_lock(&q->lock), != 0);
while(q->current_size <= 0){
EXIT_ON(pthread_cond_wait(&q->empty, &q->lock), != 0);
}
int ret = q->set[ q->start % SHARED_QUEUE_MAX_DIM];
q->start++;
q->current_size--;
q->start = q->start % SHARED_QUEUE_MAX_DIM;
EXIT_ON(pthread_cond_signal(&q->full), != 0);
EXIT_ON(pthread_mutex_unlock(&q->lock), != 0);
return ret;
}<file_sep>/clean.sh
#!/bin/bash
rm ./obj/*.o
rm ./tests/fileLetti/*
rm ./tests/fileEvict/*
rm ./tests/log*.txt
rm ./server ./client
rm ./lib/*.a
exit 0<file_sep>/includes/myserverApi.h
#ifndef _MYSERVERAPI_H
#define _MYSERVERAPI_H
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <myutil.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <myutil.h>
#include <sys/select.h>
#include <string.h>
#include <stdio.h>
#define END_RET_FILE -1
#define SUCCESS 0
#define RET_FILE 1
#define E_INV_FLG 140 //internal
#define E_INV_PTH 141 //internal
#define E_LOCK 142 // from server
#define E_NOT_EX 143 // from server
#define E_ALR_EX 144 // from server
#define E_BAD_RQ 145 // from server
#define E_ALR_LK 146
#define E_NO_SPACE 147
#define E_NOT_OPN 148
#define E_INV_SCK 149 //internal
#define E_NOT_CON 150
#define O_CREATE 1
#define O_LOCK 2
#define MAX_PATH 1024
#define UNIX_PATH_MAX 108
#define BUF_SIZE 2048
#define OPEN_F 1
#define READ_F 2
#define READ_N_F 3
#define WRITE_F 4
#define APPEND_T_F 5
#define LOCK_F 6
#define UNLOCK_F 7
#define CLOSE_F 8
#define REMOVE_F 9
int openConnection(const char* sockname, int msec, const struct timespec abstime);
int closeConnection(const char* sockname);
int openFile(const char* pathname, int flags);
int writeFile(char* pathname, char * dirname);
int appendToFile(char * pathname, void * buf, size_t size, char * dirname);
int lockFile(char * pathname);
int unlockFile(char * pathname);
int closeFile(char * pathname);
int removeFile(char * pathname);
int readFile(char * pathname, void ** buf, size_t * size);
void myperror(const char * str);
int readNFiles(int n, char * dirname);
int onlyName(char * str);
void lock_file(char * str);
void unlock_file(char * str);
void remove_file(char * str);
int readn(int fd, void *ptr, size_t n);
int writen(int fd, void *ptr, size_t n);
void ms2ts(struct timespec *ts, unsigned long ms);
void timespec_diff(struct timespec *a, struct timespec *b, struct timespec *result);
void msleep(int msec);
#define PIE(exp) \
if( (exp) == -1){ \
myperror(#exp);\
}\
#endif /*_MYSERVERAPI_H*/ <file_sep>/tests/test3.sh
#!/bin/bash
./server tests/config3.txt &
SERVER_PID=$!
export SERVER_PID
bash -c 'sleep 5 && kill -s SIGINT ${SERVER_PID}' &
pids=()
for i in {1..10}; do
bash -c './tests/test3support.sh' &
pids+=($!)
sleep 0.1
done
sleep 3
for i in "${pids[@]}"; do
kill -9 ${i}
wait ${i}
done
wait ${SERVER_PID}
exit 0<file_sep>/includes/myfilesystem.h
#ifndef _MYFILESYSTEM_H
#define _MYFILESYSTEM_H
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <myutil.h>
#include <mylinkedlist.h>
#include <unistd.h>
#include <assert.h>
#define OPEN_F 1
#define READ_F 2
#define READ_N_F 3
#define WRITE_F 4
#define APPEND_T_F 5
#define LOCK_F 6
#define UNLOCK_F 7
#define CLOSE_F 8
#define REMOVE_F 9
#define CLOSE_ALL 10
//messages server-client
#define END_RET_FILE -1
#define SUCCESS 0
#define RET_FILE 1
#define E_INV_FLG 140 //internal
#define E_INV_PTH 141 //internal
#define E_LOCK 142 // from server
#define E_NOT_EX 143 // from server
#define E_ALR_EX 144 // from server
#define E_BAD_RQ 145 // from server
#define E_ALR_LK 146
#define E_NO_SPACE 147
#define E_NOT_OPN 148
#define E_INV_SCK 149 //internal
#define E_NOT_CON 150
#define MAX_PATH 1024
#define ENDVAL "_end"
#define F_SIZE 1
typedef struct File_t{
char path[MAX_PATH+1];
int size;
void * cont; //contenuto del file
struct File_t * prev;
struct File_t * next;
List_t* openedBy; // lista di client che hanno il file aperto
int lockedBy; // client che ha fatto la lock
pthread_mutex_t f_mutex; //accesso in mutua esclusione alle variabili condivise
pthread_mutex_t f_order; //utilizzata per regolare l'accesso fair
pthread_cond_t f_go; //sospensione sia dei lettori che degli scrittori
int f_activeReaders;
int f_activeWriters;
}File_t;
typedef struct FileSystem_t{
int actSize; //dimensione attuale
int actNumFile; //numero di file attuali
int maxSize; //massima dimensione possibile
int maxNumFile; //massimo numero file possibile
int maxRSize; //massima dimensione raggiunta
int maxRNumFile;//massimo numero di file raggiunto
int evictCount; // numero di esecuzioni algoritmo cache
pthread_mutex_t fs_lock;
File_t * firstFile;
File_t * lastFile;
}FileSystem_t;
int fs_request_manager(FileSystem_t * fs, int clientFd, int requestType);
FileSystem_t * init_FileSystem(int maxNumFile, int maxSize);
int openFile_handler(FileSystem_t * fs, int clientFd, char * path, int flags);
File_t * searchFile(FileSystem_t * fs, char * path);
int writen(int fd, void *ptr, size_t n);
int readn(int fd, void *ptr, size_t n);
File_t * init_File(char* path, int clientFd);
void printFs(FileSystem_t * fs);
int writeFile_handler(FileSystem_t * fs, int clientFd, char* path, int size, char * buf);
void f_startWrite(File_t * file);
void f_doneWrite(File_t * file);
void deleteFile(File_t * tmp);
File_t * cacheEvict(FileSystem_t * fs, File_t * f, int flag);
void f_startRead(File_t * file);
void f_doneRead(File_t * file);
void deinit_FileSystem(FileSystem_t * fs);
int appendToFile_handler(FileSystem_t * fs,int clientFd, char * path, char * buf, int size);
int lockFile_handler(FileSystem_t * fs, int clientFd, char * path);
int closeAll_handler(FileSystem_t * fs, int clientFd);
int unlockFile_handler(FileSystem_t * fs, int clientFd, char * path);
int closeFile_handler(FileSystem_t * fs, int clientFd, char * path);
int removeFile_handler(FileSystem_t * fs, int clientFd, char * path);
int readFile_handler(FileSystem_t * fs, int clientFd, char * path);
int readNFiles_handler(FileSystem_t * fs, int clientFd, int numFile);
void statistiche(FileSystem_t * fs);
#endif /* _MYFILESYSTEM_H */<file_sep>/includes/myutil.h
#ifndef _MY_UTIL_H
#define _MY_UTIL_H
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
extern FILE * logFile;
void server_log(char * format, ... );
#define EXIT_ON( arg1, arg2) \
if ((arg1) arg2){ \
perror(#arg1); \
exit(-1); \
}
#endif /*_MY_UTIL_H*/<file_sep>/src/parser.c
#include <myparser.h>
int parse(char* configpath, char** socket_name, char ** logpath, int * max_num_file, int * max_dim_storage, int * num_thread_worker){
FILE * fptr;
EXIT_ON( fptr = fopen(configpath, "r"), == NULL);
#ifdef DEBUG
printf("success open file \n");
#endif
char * key, * value;
EXIT_ON( key = malloc(PARSE_BUF_DIM), == NULL);
EXIT_ON( value = malloc(PARSE_BUF_DIM), == NULL);
while ( (memset(key,'\0', PARSE_BUF_DIM) != NULL) && (fscanf(fptr, "%[^=]", key) == 1 )){
fgetc(fptr); // consuma il carattere '='
key[strnlen(key, PARSE_BUF_DIM)] = '\0';
EXIT_ON(memset(value, '\0', PARSE_BUF_DIM), == NULL);
if (fscanf(fptr, "%[^;]", value) != 1 ) break;
fgetc(fptr); // consuma il carattere ';'
value[strnlen(value, PARSE_BUF_DIM)] = '\0';
(fgetc(fptr)); // consuma il carattere '\n' (se non è presente prenderò EOF)
#ifdef DEBUG
printf("key:%s: valore:%s:\n", key, value);
#endif
// gestisco i vari casi
if (strncmp(key, ARG_1, strnlen(ARG_1, PARSE_BUF_DIM)) == 0){ // gestisco socket_name
EXIT_ON(*socket_name = malloc(PARSE_BUF_DIM), == NULL);
EXIT_ON(memset(*socket_name, '\0', PARSE_BUF_DIM), == NULL);
EXIT_ON(strncpy(*socket_name, value, PARSE_BUF_DIM), == NULL);
continue;
}
if (strncmp(key, ARG_2, strnlen(ARG_2, PARSE_BUF_DIM)) == 0){ // gestisco max_num_file
*max_num_file = atoi(value);
continue;
}
if (strncmp(key, ARG_3, strnlen(ARG_3, PARSE_BUF_DIM)) == 0){ // gestisco max_dim_storage
*max_dim_storage = atoi(value);
continue;
}
if (strncmp(key, ARG_4, strnlen(ARG_4, PARSE_BUF_DIM)) == 0){ // gestisco num_thread_worker
*num_thread_worker = atoi(value);
continue;
}
if (strncmp(key, ARG_5, strnlen(ARG_1, PARSE_BUF_DIM)) == 0){ // gestisco log_file_path
EXIT_ON(*logpath = malloc(PARSE_BUF_DIM), == NULL);
EXIT_ON(memset(*logpath, '\0', PARSE_BUF_DIM), == NULL);
EXIT_ON(strncpy(*logpath, value, PARSE_BUF_DIM), == NULL);
continue;
}
printf("parametro di configurazione non riconosciuto\n");
return -1;
}
if(feof(fptr)){ // uscito perchè fine del file
free(key);
free(value);
fclose(fptr);
#ifdef DEBUG
printf("parsing terminato correttamente\n");
#endif
return 0;
}
else{
perror("lettura config.txt");
exit(-1);
}
}
<file_sep>/includes/myhandler.h
#ifndef _MY_HANDLER_H
#define _MY_HANDLER_H
#define _POSIX_C_SOURCE 200809L
#include <signal.h>
#include <myutil.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
extern int pipeSigWriting;
void ter_handler(int sig);
void handler_installer();
void worker_handler_installer();
void print_handler(int sig);
#endif /* _MY_HANDLER_H */<file_sep>/src/client.c
#include <myserverApi.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <time.h>
#define HELP "stringa di aiuto"
extern int socketfd, myerrno;
extern char __sockname[UNIX_PATH_MAX];
char returnDir[MAX_PATH] = "";
char readDir[MAX_PATH] = "";
int delay = 0, foundp = 0, r;
void listfile(const char nomedir[], int * n);
int isdot(const char dir[]) ;
int is_comand(char * str);
char to_comand(char * str);
void send_dir(char * str);
void send_file(char str[]);
void read_file(char * str);
void read_n_file(char * str);
void client_log(char * format, ... );
int main(int argc, char ** argv){
if(argc == 1){return 0;}
int foundf = 0, i = 1, foundW = 0,
foundD = 0, foundr = 0, foundw = 0, foundd = 0, foundR =0;
char comand;
while (i < argc){ // primo ciclo di controllo
if(is_comand(argv[i])){
comand = to_comand(argv[i]);
switch (comand)
{
case 'h':;{
printf(HELP);
return 0;
break;
}
case 'p':;{
foundp++;
break;
}
case 'f':;{
foundf++;
if( argv[i+1] == NULL || is_comand(argv[i+1])){
fprintf(stderr, "opzione -f non usata correttamente\n");
return 0;
}
break;
}
case 'w':;{
foundw = 1;
if( argv[i+1] == NULL || is_comand(argv[i+1])){
fprintf(stderr, "opzione -w non usata correttamente\n");
return 0;
}
break;
}
case 'W':;{
foundW = 1;
if( argv[i+1] == NULL || is_comand(argv[i+1])){
fprintf(stderr, "opzione -W non usata correttamente\n");
return 0;
}
break;
}
case 'D':;{
foundD = 1;
if( argv[i+1] == NULL || is_comand(argv[i+1])){
fprintf(stderr, "opzione -D non usata correttamente\n");
return 0;
}
break;
}
case 'r':;{
foundr = 1;
if( argv[i+1] == NULL || is_comand(argv[i+1])){
fprintf(stderr, "opzione -r non usata correttamente\n");
return 0;
}
break;
}
case 'd':;{
foundd = 1;
if( argv[i+1] == NULL || is_comand(argv[i+1])){
fprintf(stderr, "opzione -d non usata correttamente\n");
return 0;
}
break;
}
case 'R':;{
foundR = 1;
break;
}
case 'l':;{
if( argv[i+1] == NULL || is_comand(argv[i+1])){
fprintf(stderr, "opzione -l non usata correttamente\n");
return 0;
}
break;
}
case 'u':;{
if( argv[i+1] == NULL || is_comand(argv[i+1])){
fprintf(stderr, "opzione -u non usata correttamente\n");
return 0;
}
break;
}
case 'c':;{
if( argv[i+1] == NULL || is_comand(argv[i+1])){
fprintf(stderr, "opzione -c non usata correttamente\n");
return 0;
}
break;
}
case 't':;{
if( argv[i+1] == NULL || is_comand(argv[i+1])){
fprintf(stderr, "opzione -t non usata correttamente\n");
return 0;
}
delay = atoi(argv[i+1]);
break;
}
}
}
i++;
}
if(foundD == 1 && (foundW + foundw) <= 0){
fprintf(stderr, "opzione -D non usata correttamente\n");
return 0;
}
if(foundd == 1 && (foundR + foundr) <= 0){
fprintf(stderr, "opzione -d non usata correttamente\n");
return 0;
}
if(foundp > 1){
fprintf(stderr, "opzione -p non usata correttamente\n");
return 0;
}
if(foundf != 1){
fprintf(stderr, "opzione -f non usata correttamente\n");
return 0;
}
if(delay < 0){
fprintf(stderr, "opzione -t non usata correttamente\n");
return 0;
}
i = 1;
while (i < argc){
comand = to_comand(argv[i]);
switch (comand)
{
case 'f':;{
struct timespec abstime;
abstime.tv_sec = 5; // provo per 3 secondi (dando il tempo al server di avviarsi)
abstime.tv_nsec = 0;
PIE(openConnection(argv[i+1], 500, abstime)); // ogni 500 ms
client_log("Apro la connessione con il socket: %s", argv[i+1]);
i++; // devo saltare un ulteriore parametro
msleep(delay);
break;
}
case 'w':;{
send_dir(argv[i+1]);
i++;
msleep(delay);
break;
}
case 'W':;{
send_file(argv[i+1]);
i++;
msleep(delay);
break;
}
case 'D':;{ // testare questa opzione
strcpy(returnDir, argv[i+1]);
client_log("Cartella di salvataggio della cache aggiornata in: %s", returnDir);
i++;
break;
}
case 'r':;{
read_file(argv[i+1]);
i++;
msleep(delay);
break;
}
case 'd':;{
strcpy(readDir, argv[i+1]);
client_log("Cartella di lettura aggiornata in: %s", readDir);
break;
}
case 'R':;{
read_n_file(argv[i+1]);
msleep(delay);
break;
}
case 'l':;{
lock_file(argv[i+1]);
i++;
msleep(delay);
break;
}
case 'u':;{
unlock_file(argv[i+1]);
i++;
msleep(delay);
break;
}
case 'c':;{
remove_file(argv[i+1]);
i++;
msleep(delay);
break;
}
}
i++;
}
client_log("Chiudo la connessione con il server e termino");
PIE(closeConnection(__sockname));
return 0;
}
void remove_file(char * str){
char file[MAX_PATH];
int pos =0;
while(1){
if(str[pos] == '\0'){
strncpy(file, str, pos +1);
PIE(r = openFile(file, 0));
PIE(r = removeFile(file));
client_log("Rimosso il file %s con esito %d", file, r);
return;
}
else if(str[pos] == ','){
str[pos] = '\0';
strncpy(file, str, pos +1);
PIE(r = openFile(file, 0));
PIE(r = removeFile(file));
client_log("Rimosso il file %s con esito %d", file, r);
str = str + pos + 1;
pos = 0;
}
else{
pos++;
}
}
}
void unlock_file(char * str){
char file[MAX_PATH];
int pos =0;
while(1){
if(str[pos] == '\0'){
strncpy(file, str, pos +1);
PIE(r = openFile(file, 0));
PIE(r = unlockFile(file));
client_log("Unlock del file %s con esito %d", file, r);
return;
}
else if(str[pos] == ','){
str[pos] = '\0';
strncpy(file, str, pos +1);
PIE(r = openFile(file, 0));
PIE(r = unlockFile(file));
client_log("Unlock del file %s con esito %d", file, r);
str = str + pos + 1;
pos = 0;
}
else{
pos++;
}
}
}
void lock_file(char * str){
char file[MAX_PATH];
int pos =0;
while(1){
if(str[pos] == '\0'){
strncpy(file, str, pos +1);
PIE(r = openFile(file, 0));
PIE(r = lockFile(file));
client_log("Lock del file %s con esito %d", file, r);
return;
}
else if(str[pos] == ','){
str[pos] = '\0';
strncpy(file, str, pos +1);
PIE(r = openFile(file, 0));
PIE(r = lockFile(file));
client_log("Lock del file %s con esito %d", file, r);
str = str + pos + 1;
pos = 0;
}
else{
pos++;
}
}
}
void read_n_file(char * str){
int n;
if(str == NULL || is_comand(str)) n=0; // devo leggere tutti i file
else{
str += 2;
n = atoi(str);
}
if(strcmp(readDir, "") == 0){
fprintf(stderr, "retDir non inizializzata\n");
return;
}
PIE(readNFiles(n, readDir));
client_log("Lettura di %d files con esito %d", n, r);
}
void read_file(char * str){
char returnPath[MAX_PATH], file[MAX_PATH];
int pos =0;
while(1){
void * buf = NULL; size_t size; FILE * fileptr;
int r;
if(str[pos] == '\0'){
strncpy(file, str, pos +1);
PIE(r = readFile(file, &buf, &size)); // legge dal server
client_log("Lettura del file %s di %d byte con esito %d", file,size, r);
if(r == -1) {return;}
if(strcmp(readDir, "") != 0){ // se ho specificato una cartella in cui salvare i file letti
strcpy(returnPath, readDir);
strcat(returnPath, (file+onlyName(file) + 1));
EXIT_ON( fileptr = fopen(returnPath, "wb"), == NULL);
EXIT_ON(fwrite(buf, 1, size, fileptr), != size);
client_log("Salvataggio del file %s nella cartella %s", file + onlyName(file) +1, readDir);
free(buf);
}
return;
}
else if(str[pos] == ','){
str[pos] = '\0';
strncpy(file, str, pos +1);
PIE(r = readFile(file, &buf, &size)); // legge dal server
client_log("Lettura del file %s di %d byte con esito %d", file,size, r);
if(strcmp(readDir, "") != 0){
strcpy(returnPath, readDir);
strcat(returnPath, (file+onlyName(file) + 1));
EXIT_ON( fileptr = fopen(returnPath, "wb"), == NULL);
EXIT_ON(fwrite(buf, 1, size, fileptr), != size);
client_log("Salvataggio del file %s nella cartella %s", file + onlyName(file) +1, readDir);
free(buf);
}
str = str + pos + 1;
pos = 0;
}
else{
pos++;
}
}
}
void send_file(char str[]){
char file[MAX_PATH];
int pos =0;
while(1){
if(str[pos] == '\0'){
strncpy(file, str, pos +1);
PIE(r = openFile(file, O_CREATE | O_LOCK));
client_log("Apertura del file %s con flag %d, esito %d", file, O_CREATE | O_LOCK, r);
if(strcmp(returnDir, "") == 0){ // cartella di ritorno non specificata
PIE(r = writeFile(file, NULL));
client_log("Scrittura del file %s nel server senza salvare i file evicted, esito: %d", file, r);
}
else{
PIE(r = writeFile(file, returnDir));
client_log("Scrittura del file %s nel server con salvataggio dei file evicted in %s, esito: %d", file, returnDir, r);
}
return;
}
else if(str[pos] == ','){
str[pos] = '\0';
strncpy(file, str, pos +1);
PIE(openFile(file, O_CREATE | O_LOCK));
if(strcmp(returnDir, "") == 0){ // cartella di ritorno non specificata
PIE(r = writeFile(file, NULL));
client_log("Scrittura del file %s nel server senza salvare i file evicted, esito: %d", file, r);
}
else{
PIE(r = writeFile(file, returnDir));
client_log("Scrittura del file %s nel server con salvataggio dei file evicted in %s, esito: %d", file, returnDir, r);
}
str = str + pos + 1;
pos = 0;
}
else{
pos++;
}
}
}
void listfile(const char nomedir[], int * n) {
// controllo che il parametro sia una directory
struct stat statbuf;
EXIT_ON(stat(nomedir,&statbuf),!= 0);
DIR * dir;
if ((dir=opendir(nomedir)) == NULL) {
perror("opendir");
printf("Errore aprendo la directory %s\n", nomedir);
return;
}
struct dirent *file;
while(((errno=0, file = readdir(dir)) != NULL) && *n != 0 ) {
struct stat statbuf;
char filename[MAX_PATH];
int len1 = strlen(nomedir);
int len2 = strlen(file->d_name);
if ((len1+len2+2)>MAX_PATH) {
fprintf(stderr, "ERRORE: MAXFILENAME troppo piccolo\n");
exit(EXIT_FAILURE);
}
strncpy(filename,nomedir, MAX_PATH-1);
strncat(filename,"/", MAX_PATH-1);
strncat(filename,file->d_name, MAX_PATH-1);
if (stat(filename, &statbuf)==-1) {
perror("eseguendo la stat");
printf("Errore nel file %s\n", filename);
return;
}
if(S_ISDIR(statbuf.st_mode)) {
if ( !isdot(filename) )
listfile(filename, n);
}
else {
(*n)--;
PIE(openFile(filename, O_CREATE | O_LOCK)); // creo il file nel server
if(strcmp(returnDir, "") == 0){ // cartella di ritorno non specificata
PIE(r = writeFile(filename, NULL));
client_log("Scrittura del file %s nel server senza salvare i file evicted, esito: %d", filename, r);
}
else{
PIE(r = writeFile(filename, returnDir));
client_log("Scrittura del file %s nel server con salvataggio dei file evicted in %s, esito: %d", filename, returnDir, r);
}
}
}
if (errno != 0) perror("readdir");
closedir(dir);
}
int isdot(const char dir[]) {
int l = strlen(dir);
if ( (l>0 && dir[l-1] == '.') ) return 1;
return 0;
}
int is_comand(char * str){
if((str != NULL) && (str[0] == '-') && ((str + 1) != NULL) && (str[2] == '\0') ){
return 1;
}
return 0;
}
char to_comand(char * str){
return str[1];
}
void send_dir(char * str){
if(strlen(str) > MAX_PATH -1){printf("error"); return;}
int n = 0, virpos = 0;
char dirname[MAX_PATH];
while (str[virpos] != '\0' && str[virpos] != ','){ // finche arrivo alla fine o ad una virgola
virpos++;
}
strncpy(dirname,str, virpos);
dirname[virpos] = '\0'; // dirname è ok
if(str[virpos] == ','){ //se sono arrivato alla virgola
str = str + virpos + 3; // salto n=
if(str != NULL){
n = atoi(str);
}
else{
printf("error in number of files");
printf(HELP);
return;
}
}
if (n<=0) n=-1;
// navigare i file nelle cartelle e inviarli al server
// controllo che l'argomaneto sia una directory
struct stat statbuf;
if (stat(dirname,&statbuf)!= 0 || !S_ISDIR(statbuf.st_mode)){
fprintf(stderr, " \"%s\" non e' una directory\n", dirname);
printf(HELP);
return;
}
listfile(dirname, &n);
}
void client_log(char * format, ... ){
if(foundp == 0) return;
va_list arglist;
va_start(arglist, format);
vfprintf(stderr, format, arglist);
fprintf(stderr, "\n");
va_end(arglist);
}<file_sep>/includes/mysharedqueue.h
#ifndef _MY_SHARED_QUEUE_H
#define _MY_SHARED_QUEUE_H
#include <myutil.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define SHARED_QUEUE_MAX_DIM 2048
typedef struct _sq{
int *set;
int start;
int current_size;
pthread_mutex_t lock;
pthread_cond_t full;
pthread_cond_t empty;
}SharedQueue_t;
SharedQueue_t * init_SharedQueue();
void SharedQueue_push(SharedQueue_t * q, int fd_c);
int SharedQueue_pop(SharedQueue_t * q);
#endif /*_MY_SHARED_QUEUE_H */<file_sep>/tests/test2.sh
#!/bin/bash
./server ./tests/config2.txt &
SERVER_PID=$!
./client -p -t 200 -f mysock -D tests/fileEvict -w tests/files
kill -s SIGINT ${SERVER_PID}
sleep 1
exit 0<file_sep>/includes/myparser.h
#ifndef _MY_PARSE_H
#define _MY_PARSE_H
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <stdio.h>
#include <myutil.h>
#include <string.h>
#define PARSE_BUF_DIM 64
#define ARG_1 "socket_name"
#define ARG_2 "max_num_file"
#define ARG_3 "max_dim_storage"
#define ARG_4 "num_thread_worker"
#define ARG_5 "log_file_path"
/*
per aggiungere un altro parametro:
- aggiungere una define con il nome del parametro
- aggiungere alla firma della funzione parse
- aggiungere nel corpo di parse un blocco per gestire quella determinata coppia <key, value>
*/
int parse(char* configpath,char** logpath, char ** socket_name, int * max_num_file, int * max_dim_storage, int * num_thread_worker);
#endif /* _MY_PARSE_H */<file_sep>/src/connection.c
#include <myconnection.h>
int updatemax(fd_set set, int fdmax) {
for(int i=(fdmax);i>=0;--i)
if (FD_ISSET(i, &set)) return i;
EXIT_ON("error in updatemax", == NULL);
return -1;
}
int init_server(char * sck_name){
EXIT_ON(strnlen(sck_name, UNIX_PATH_MAX) >= UNIX_PATH_MAX, != 0);
sck_name[strnlen(sck_name, UNIX_PATH_MAX-1)] = '\0';
int socket_fd;
EXIT_ON(socket_fd = socket(AF_UNIX, SOCK_STREAM, 0), == -1);
struct sockaddr_un server_addr;
EXIT_ON(memset(&server_addr, 0, sizeof(struct sockaddr_un)), == NULL);
server_addr.sun_family = AF_UNIX;
EXIT_ON(strncpy(server_addr.sun_path, sck_name, UNIX_PATH_MAX-1), == NULL);
EXIT_ON(bind(socket_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_un)), != 0);
EXIT_ON(listen(socket_fd, MAX_CONNECTION_QUEUE), != 0);
return socket_fd;
}
int find_max(int a, int b , int c, int d, int e){
int max = 0;
if(a>max) max = a;
if(b>max) max = b;
if(c>max) max = c;
if(d>max) max = d;
if(e>max) max = e;
return max;
}
<file_sep>/src/filesystem.c
#include <myfilesystem.h>
int fs_request_manager(FileSystem_t * fs, int clientFd, int requestType){
switch (requestType){
case OPEN_F:;{
int flags;
char path[MAX_PATH];
if (readn(clientFd, path, MAX_PATH) != MAX_PATH) return -1; // path
if (readn(clientFd, &flags, sizeof(int)) != sizeof(int)) return -1; // flags
return openFile_handler(fs, clientFd, path, flags);
}
break;
case READ_F:;{
char path[MAX_PATH];
if (readn(clientFd, path, MAX_PATH) != MAX_PATH) return -1; // path
return readFile_handler(fs, clientFd, path);
}
break;
case READ_N_F:;{
int numFile;
if (readn(clientFd, &numFile, sizeof(int)) != sizeof(int)) return -1; // lunghezza file
return readNFiles_handler(fs, clientFd, numFile);
}
break;
case WRITE_F:;{
int size;
char path[MAX_PATH], * buf;
if (readn(clientFd, &size, sizeof(int)) != sizeof(int)) return -1; // lunghezza file
if (readn(clientFd, path, MAX_PATH) != MAX_PATH) return -1; // path
EXIT_ON(buf = malloc(size), == NULL);
if (readn(clientFd, buf, size) != size){free(buf); return -1;} // contenuto
//scrive nel fs il file con path e contenuto buf, rimanda i file espulsi al client
return writeFile_handler(fs, clientFd, path, size, buf);
}
break;
case APPEND_T_F:;{
int size;
char path[MAX_PATH], * buf;
if (readn(clientFd, &size, sizeof(int)) != sizeof(int)) return -1; // lunghezza buffer
if (readn(clientFd, path, MAX_PATH) != MAX_PATH) return -1; // path
EXIT_ON(buf = malloc(size), == NULL);
if (readn(clientFd, buf, size) != size){free(buf); return -1;} // buffer
return appendToFile_handler(fs,clientFd, path, buf, size);
}
break;
case LOCK_F:;{
char path[MAX_PATH];
if (readn(clientFd, path, MAX_PATH) != MAX_PATH) return -1; // path
return lockFile_handler(fs, clientFd, path);
}
break;
case UNLOCK_F:;{
char path[MAX_PATH];
if (readn(clientFd, path, MAX_PATH) != MAX_PATH) return -1; // path
return unlockFile_handler(fs, clientFd, path);
}
break;
case CLOSE_F:;{
char path[MAX_PATH];
if (readn(clientFd, path, MAX_PATH) != MAX_PATH) return -1; // path
return closeFile_handler(fs, clientFd, path);
}
break;
case REMOVE_F:;{
char path[MAX_PATH];
if (readn(clientFd, path, MAX_PATH) != MAX_PATH) return -1; // path
return removeFile_handler(fs, clientFd, path);
}
break;
case CLOSE_ALL:;{
return closeAll_handler(fs, clientFd);
}
default:
fprintf(stderr, "Richesta non disponibile\n");
int retVal = E_BAD_RQ;
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)){
return -1;
}
break;
}
return -1;
}
int openFile_handler(FileSystem_t * fs, int clientFd, char * path, int flags){
EXIT_ON(pthread_mutex_lock(&fs->fs_lock), != 0); // prendo lock fs
server_log("Il client %d ha richiesto una open sul file %s con flag %d", clientFd, path, flags);
int retVal = 0;
File_t * file = searchFile(fs, path); // cerco il file
// agisco in base ai flag
if(file == NULL){ // file non esisteva
if(flags == 0 || flags == 2){ //nessun flag o solo O_LOCK
retVal = E_NOT_EX;
goto openFile_handler_END;
}
// devo aggiungere un file
if(fs->actNumFile + 1 > fs->maxNumFile){ // parte l'algoritmo della cache
File_t * tmp = cacheEvict(fs, NULL, 0);
assert(tmp != NULL);
f_startWrite(tmp);
retVal = 1; // segnalo che sta per arrivare un file
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) perror("i file verranno persi");
server_log("Invio al client %d il file %s di %d byte", clientFd, tmp->path, tmp->size);
if (writen(clientFd, &tmp->size, sizeof(int)) != sizeof(int))perror("i file verranno persi");
if (writen(clientFd, tmp->path, MAX_PATH) != MAX_PATH) perror("i file verranno persi");
if (writen(clientFd, tmp->cont, tmp->size) != tmp->size) perror("i file verranno persi");
f_doneRead(tmp);
deleteFile(tmp);
retVal = -1; //segnalo al client che i file sono finiti
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) perror("errore client");
}
File_t * newfile = init_File(path, clientFd);
f_startWrite(newfile);
if(flags == 3){ // O_CREATE | O_LOCK
newfile->lockedBy = clientFd;
}
if(fs->actNumFile == 0){
fs->lastFile = newfile;
fs->firstFile = newfile;
}
else{
(fs->lastFile)->next = newfile;
newfile->prev = fs->lastFile;
fs->lastFile = newfile;
}
list_insert(&newfile->openedBy, clientFd);
f_doneWrite(newfile);
fs->actNumFile++;
if(fs->actNumFile > fs->maxRNumFile) fs->maxRNumFile = fs->actNumFile;
retVal = 0;
goto openFile_handler_END;
}
if(file != NULL){ // il file esiste
if (flags == 1 || flags == 3){ // O_CREATE oppure O_CREATE | O_LOCK
retVal = E_ALR_EX;
goto openFile_handler_END;
}
if(flags == 0){ // nessun flag
f_startWrite(file);
list_insert( &file->openedBy, clientFd);
f_doneWrite(file);
retVal = 0;
goto openFile_handler_END;
}
if (flags == 2){ // O_LOCK
f_startWrite(file);
if(file->lockedBy == 0){
file->lockedBy = clientFd;
list_insert(&file->openedBy, clientFd);
f_doneWrite(file);
retVal = 0;
goto openFile_handler_END;
}
else{
f_doneWrite(file);
retVal = E_ALR_LK;
goto openFile_handler_END;
}
}
}
retVal = 0;
openFile_handler_END:
server_log("Il client %d ha completato la richiesta. Valore ritornato: %d", clientFd, retVal);
EXIT_ON(pthread_mutex_unlock(&fs->fs_lock), != 0);
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) return -1;
else return 0;
}
int writeFile_handler(FileSystem_t * fs, int clientFd, char* path, int size, char * buf){
EXIT_ON(pthread_mutex_lock(&fs->fs_lock), != 0); // prendo lock fs
server_log("Il client %d ha richiesto una write sul file %s di %d byte", clientFd, path, size);
int retVal = 0; // valore di ritorno che corrisponde a errno per il client
File_t * file = searchFile(fs, path); // cerco il file con quel path
if(file == NULL){
retVal = E_NOT_EX;
goto writeFile_handler_END; //test da fare: lanciare il client
}
f_startRead(file); // devo levvere il file
if(!list_mem(&file->openedBy, clientFd)){ // controllo se ho aperto il file
f_doneRead(file);
retVal = E_NOT_OPN;
goto writeFile_handler_END;
}
if(clientFd != file->lockedBy ){ // controllo se ho la lock sul file
f_doneRead(file);
retVal = E_LOCK;
goto writeFile_handler_END;
}
if(file->size != 0){ // controllo se il file è stato già scritto
f_doneRead(file);
retVal = E_BAD_RQ;
goto writeFile_handler_END;
}
if(fs->maxSize < size){ // non riuscirò mai a trovare lo spazio necessario
f_doneRead(file);
retVal = E_NO_SPACE;
goto writeFile_handler_END;
}
f_doneRead(file);
// fase di evict e salvataggio dei file da mandare al client
retVal = 0;
while((fs->maxSize - fs->actSize < size)){ // se lo spazio libero è minore di quello che devo inserire
if (retVal == 0){
retVal = 1; // seganala che stanno per arrivare file
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) perror("i file verranno persi");
}
File_t * tmp = cacheEvict(fs, file, F_SIZE); // scollega il file dal fs e non ci sono scrittori o lettori attivi o in attesa
server_log("Invio al client %d il file %s di %d byte", clientFd, tmp->path, tmp->size);
if (writen(clientFd, &tmp->size, sizeof(int)) != sizeof(int))perror("i file verranno persi");
if (writen(clientFd, tmp->path, MAX_PATH) != MAX_PATH) perror("i file verranno persi");
if (writen(clientFd, tmp->cont, tmp->size) != tmp->size) perror("i file verranno persi");
server_log("File %s eliminato dal server", tmp->path);
deleteFile(tmp);
}
if(retVal == 1){ // se ho inviato file, devo segnalare che i file sono finiti
retVal = -1; // i file sono finiti
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) perror("errore client");
}
// scrittura nel file
f_startWrite(file);
file->cont = buf;
file->size = size;
fs->actSize += size;
if(fs->actSize >fs->maxRSize) fs->maxRSize = fs->actSize;
f_doneWrite(file);
//fprintf(stderr, "scritto il file: %s con: %s\n", file->path, (char*)file->cont);
// messaggio finale per il client
retVal = 0;
writeFile_handler_END:
if(retVal != 0) free(buf);
server_log("Il client %d ha completato la richiesta. Valore ritornato: %d", clientFd, retVal);
EXIT_ON(pthread_mutex_unlock(&fs->fs_lock), != 0);
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) return -1;
else return 0;
}
int readNFiles_handler(FileSystem_t * fs, int clientFd, int numFile){
EXIT_ON(pthread_mutex_lock(&fs->fs_lock), != 0); // prendo lock fs
server_log("Il client %d ha richiesto la lettura di %d files", clientFd, numFile);
// size, path, cont
if(numFile <= 0) numFile = fs->actNumFile;
if(numFile > fs->actNumFile) numFile = fs->actNumFile;
int retVal = 0, cont = 0;
File_t * tmp = fs->firstFile, *next;
retVal = 1; // seganala che stanno per arrivare file
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) {retVal = E_BAD_RQ; goto readNFiles_handler_END;}
while(cont < numFile ){
f_startRead(tmp);
if(tmp->lockedBy != 0 && tmp->lockedBy != clientFd){
f_doneRead(tmp);
continue;
}
server_log("Invio al client %d il file %s di %d byte", clientFd, tmp->path, tmp->size);
if (writen(clientFd, &tmp->size, sizeof(int)) != sizeof(int)) {f_doneRead(tmp), retVal = E_BAD_RQ; goto readNFiles_handler_END;}
if (writen(clientFd, &tmp->path, MAX_PATH) != MAX_PATH) {f_doneRead(tmp), retVal = E_BAD_RQ; goto readNFiles_handler_END;}
if (writen(clientFd, tmp->cont, tmp->size) != tmp->size) {f_doneRead(tmp), retVal = E_BAD_RQ; goto readNFiles_handler_END;}
next = tmp->next;
f_doneRead(tmp);
tmp = next;
cont++;
}
retVal = -1; // seganala che sono finiti i file
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) {retVal = E_BAD_RQ; goto readNFiles_handler_END;}
retVal = 0;
readNFiles_handler_END:
server_log("Il client %d ha completato la richiesta. Valore ritornato: %d", clientFd, retVal);
EXIT_ON(pthread_mutex_unlock(&fs->fs_lock), != 0);
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) return -1;
else return 0;
}
int readFile_handler(FileSystem_t * fs, int clientFd, char * path){
EXIT_ON(pthread_mutex_lock(&fs->fs_lock), != 0); // prendo lock fs
server_log("Il client %d ha richiesto la lettura di %s", clientFd, path);
int retVal = 0;
File_t * file = searchFile(fs, path);
if(file == NULL){
retVal = E_NOT_EX;
EXIT_ON(pthread_mutex_unlock(&fs->fs_lock), != 0);
goto readFile_handler_END;
}
f_startRead(file);
EXIT_ON(pthread_mutex_unlock(&fs->fs_lock), != 0); // posso rilaciare la mutex del fs
if(!list_mem(&file->openedBy, clientFd)){ retVal = E_NOT_OPN; f_doneRead(file); goto readFile_handler_END;}
if(file->lockedBy != 0 && file->lockedBy != clientFd){retVal = E_LOCK; f_doneRead(file); goto readFile_handler_END;}
retVal = 1; // seganala che stanno per arrivare file
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) {f_doneRead(file), retVal = E_BAD_RQ; goto readFile_handler_END;}
server_log("Invio al client %d il file %s di %d byte", clientFd, file->path, file->size);
if (writen(clientFd, &file->size, sizeof(int)) != sizeof(int)) {f_doneRead(file), retVal = E_BAD_RQ; goto readFile_handler_END;}
if (writen(clientFd, file->cont, file->size) != file->size) {f_doneRead(file), retVal = E_BAD_RQ; goto readFile_handler_END;}
f_doneRead(file);
retVal = 0;
readFile_handler_END:
server_log("Il client %d ha completato la richiesta. Valore ritornato: %d", clientFd, retVal);
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) return -1;
else return 0;
}
int removeFile_handler(FileSystem_t * fs, int clientFd, char * path){
EXIT_ON(pthread_mutex_lock(&fs->fs_lock), != 0); // prendo lock fs
server_log("Il client %d ha richiesto l'eliminazione di %s", clientFd, path);
int retVal = 0;
File_t * file = searchFile(fs, path);
if(file == NULL){ retVal = E_NOT_EX; goto removeFile_handler_END;}
f_startWrite(file);
if(file->lockedBy != 0 && file->lockedBy != clientFd){f_doneWrite(file); retVal = E_LOCK; goto removeFile_handler_END;}
fs->actSize -= file->size;
fs->actNumFile--;
if(file->next != NULL) {
f_startWrite(file->next);
(file->next)->prev = file->prev;
f_doneWrite(file->next);
}
if(file->prev != NULL) {
f_startWrite(file->prev);
(file->prev)->next = file->next;
f_doneWrite(file->prev);
}
if (fs->firstFile == file) fs->firstFile = file->next;
if (fs->lastFile == file) fs->lastFile = file->prev;
if(fs->actNumFile == 0){
fs->firstFile = NULL;
fs->lastFile = NULL;
}
f_doneWrite(file);
deleteFile(file);
removeFile_handler_END:
server_log("Il client %d ha completato la richiesta. Valore ritornato: %d", clientFd, retVal);
EXIT_ON(pthread_mutex_unlock(&fs->fs_lock), != 0);
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) return -1;
else return 0;
}
int closeFile_handler(FileSystem_t * fs, int clientFd, char * path){
EXIT_ON(pthread_mutex_lock(&fs->fs_lock), != 0); // prendo lock fs
server_log("Il client %d ha richiesto la chiusura di %s", clientFd, path);
int retVal = 0;
File_t * file = searchFile(fs, path);
if(file == NULL){ retVal = E_NOT_EX; goto closeFile_handler_END;}
f_startWrite(file);
list_remove(&file->openedBy, clientFd);
f_doneWrite(file);
retVal = 0;
closeFile_handler_END:
server_log("Il client %d ha completato la richiesta. Valore ritornato: %d", clientFd, retVal);
EXIT_ON(pthread_mutex_unlock(&fs->fs_lock), != 0);
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) return -1;
else return 0;
}
int unlockFile_handler(FileSystem_t * fs, int clientFd, char * path){
EXIT_ON(pthread_mutex_lock(&fs->fs_lock), != 0); // prendo lock fs
server_log("Il client %d ha richiesto una unlock su %s", clientFd, path);
int retVal = 0;
File_t * file = searchFile(fs, path);
if(file == NULL){ retVal = E_NOT_EX; goto unlockFile_handler_END;}
f_startWrite(file);
if(!list_mem(&file->openedBy, clientFd)){ f_doneWrite(file), retVal = E_NOT_OPN; goto unlockFile_handler_END;}
if(file->lockedBy != 0 && file->lockedBy != clientFd){ f_doneWrite(file); retVal = E_LOCK ; goto unlockFile_handler_END;}
if(file->lockedBy == 0){ f_doneWrite(file), retVal = 0; goto unlockFile_handler_END;}
file->lockedBy = 0;
f_doneWrite(file);
retVal = 0;
unlockFile_handler_END:
server_log("Il client %d ha completato la richiesta. Valore ritornato: %d", clientFd, retVal);
EXIT_ON(pthread_mutex_unlock(&fs->fs_lock), != 0);
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) return -1;
else return 0;
}
int closeAll_handler(FileSystem_t * fs, int clientFd){
EXIT_ON(pthread_mutex_lock(&fs->fs_lock), != 0);
server_log("Chiudo il client %d e tutti i file aperti", clientFd);
File_t * next,* tmp = fs->firstFile;
while(tmp){
f_startWrite(tmp);
list_remove(&tmp->openedBy, clientFd);
if(tmp->lockedBy == clientFd) tmp->lockedBy = 0;
next = tmp->next;
f_doneWrite(tmp);
tmp = next;
}
EXIT_ON(pthread_mutex_unlock(&fs->fs_lock), != 0);
return 0;
}
int lockFile_handler(FileSystem_t * fs, int clientFd, char * path){
EXIT_ON(pthread_mutex_lock(&fs->fs_lock), != 0); // prendo lock fs
server_log("Il client %d ha richiesto una lock su %s", clientFd, path);
int retVal = 0;
File_t * file = searchFile(fs, path);
if(file == NULL){ retVal = E_NOT_EX; goto lockFile_handler_END;}
f_startWrite(file);
if(!list_mem(&file->openedBy, clientFd)){ f_doneWrite(file), retVal = E_NOT_OPN; goto lockFile_handler_END;}
if(file->lockedBy == clientFd){ f_doneWrite(file); retVal = 0 ; goto lockFile_handler_END;}
if(file->lockedBy == 0){
file->lockedBy = clientFd;
f_doneWrite(file);
retVal = 0;
goto lockFile_handler_END;
}
if(file->lockedBy != 0 && file->lockedBy != clientFd){
f_doneWrite(file);
retVal = E_ALR_LK;
goto lockFile_handler_END;
}
retVal = 0;
lockFile_handler_END:
server_log("Il client %d ha completato la richiesta. Valore ritornato: %d", clientFd, retVal);
EXIT_ON(pthread_mutex_unlock(&fs->fs_lock), != 0);
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) return -1;
else return 0;
}
int appendToFile_handler(FileSystem_t * fs,int clientFd, char * path, char * buf, int size){
EXIT_ON(pthread_mutex_lock(&fs->fs_lock), != 0); // prendo lock fs
server_log("Il client %d ha richiesto una append sul file %s di %d byte", clientFd, path, size);
int retVal = 0;
File_t * file = searchFile(fs, path);
if(file == NULL){ retVal = E_NOT_EX; goto appendToFile_handler_END;}
f_startRead(file);
if(!list_mem(&file->openedBy, clientFd)){f_doneRead(file); retVal = E_NOT_OPN; goto appendToFile_handler_END;}
if(file->lockedBy != 0 && file->lockedBy != clientFd){f_doneRead(file); retVal = E_LOCK; goto appendToFile_handler_END;}
if(size + file->size > fs->maxSize){f_doneRead(file); retVal = E_NO_SPACE; goto appendToFile_handler_END;}
f_doneRead(file);
retVal = 0;
while((fs->maxSize - fs->actSize < size)){
if (retVal == 0){
retVal = 1; // seganala che stanno per arrivare file
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) perror("i file verranno persi");
}
File_t * tmp = cacheEvict(fs, file, F_SIZE); // scollega il file dal fs e non ci sono scrittori o lettori attivi o in attesa
server_log("Invio al client %d il file %s di %d byte", clientFd, tmp->path, tmp->size);
if (writen(clientFd, &tmp->size, sizeof(int)) != sizeof(int)) perror("i file verranno persi");
if (writen(clientFd, tmp->path, MAX_PATH) != MAX_PATH) perror("i file verranno persi");
if (writen(clientFd, tmp->cont, tmp->size) != tmp->size) perror("i file verranno persi");
server_log("File %s eliminato dal server", tmp->path);
deleteFile(tmp);
}
if (retVal == 1){ // se ho inviato i file devo segnalare che sono finiti
retVal = -1; // seganala che i file sono finiti
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) perror("errore client");
}
f_startWrite(file);
EXIT_ON(file->cont = realloc(file->cont, file->size + size), == NULL);
memcpy((char*)file->cont + file->size, buf, size);
file->size += size;
f_doneWrite(file);
fs->actSize+=size;
if(fs->actSize > fs->maxRSize) fs->maxRSize = fs->actSize;
retVal = 0;
appendToFile_handler_END:
server_log("Il client %d ha completato la richiesta. Valore ritornato: %d", clientFd, retVal);
free(buf);
EXIT_ON(pthread_mutex_unlock(&fs->fs_lock), != 0);
if (writen(clientFd, &retVal, sizeof(int)) != sizeof(int)) return -1;
else return 0;
}
File_t * cacheEvict(FileSystem_t * fs, File_t * f, int flag){
// assume la lock sul fs, non ci sarà nessuno in attesa sul file ritornato
// nessun altro file deve essere in scrittura o lettura
// f indica un file escluso dall'evict
// flag indica se devo recuperare spazio o se mi basta eliminare un file qualsiasi
File_t * tmp = fs->firstFile;
File_t * prev;
while(tmp != NULL){
f_startRead(tmp);
if(tmp != f && ((tmp->size != 0) || !flag)){ // deve essere diverso dal file che sto scrivendo
f_doneRead(tmp);
f_startWrite(tmp);
fs->actSize -= tmp->size;
fs->actNumFile--;
if(fs->firstFile == tmp){
fs->firstFile = tmp->next;
}
if(fs->lastFile == tmp){
fs->lastFile = tmp->prev;
}
if(tmp->prev != NULL){
f_startWrite(tmp->prev);
(tmp->prev)->next = tmp->next;
f_doneWrite(tmp->prev);
}
if(tmp->next != NULL){
f_startWrite(tmp->next);
(tmp->next)->prev = tmp->prev;
f_doneWrite(tmp->next);
}
if(tmp->next == NULL){
f_startWrite(tmp->prev);
(tmp->prev)->next = NULL;
f_doneWrite(tmp->prev);
fs->lastFile = tmp->prev;
}
if(fs->actNumFile == 0){
fs->firstFile = NULL;
fs->lastFile = NULL;
}
f_doneWrite(tmp); // quando esco da un file in scrittura, non c'è più nessuno nemmeno in attesa
fs->evictCount++;
return tmp;
}
prev = tmp;
tmp = tmp->next;
f_doneRead(prev);
}
EXIT_ON("evict fail", ); // per le precondizioni della chiamata, l'evict non dovrebbe mai fallire
return NULL;
}
void deleteFile(File_t * tmp){
if(tmp->cont != NULL) free(tmp->cont);
list_deinit(&tmp->openedBy);
EXIT_ON(pthread_mutex_destroy(&tmp->f_mutex), != 0);
EXIT_ON(pthread_mutex_destroy(&tmp->f_order), != 0);
EXIT_ON(pthread_cond_destroy(&tmp->f_go), != 0);
free(tmp);
}
File_t * searchFile(FileSystem_t * fs, char * path){ // da cambiare con la tabella hash
File_t * tmp = fs->firstFile;
File_t * prev;
while(tmp != NULL){
f_startRead(tmp);
if(strncmp(tmp->path, path, MAX_PATH) == 0){
f_doneRead(tmp);
return tmp;
}
prev = tmp;
tmp = tmp->next;
f_doneRead(prev);
}
return NULL;
}
FileSystem_t * init_FileSystem(int maxNumFile, int maxSize){
FileSystem_t * fs;
EXIT_ON(fs = malloc(sizeof(FileSystem_t)), == NULL);
fs->actSize = 0;
fs->actNumFile = 0;
fs->maxSize = maxSize;
fs->maxNumFile = maxNumFile;
fs->maxRSize = 0;
fs->maxRNumFile = 0;
fs->evictCount = 0;
EXIT_ON(pthread_mutex_init(&fs->fs_lock, NULL), != 0);
fs->firstFile = NULL;
fs->lastFile = NULL;
return fs;
}
void deinit_FileSystem(FileSystem_t * fs){
// assume che non ci sia più nessun thread worker, quindi ignora tutte le lock
File_t *prev, * tmp = fs->firstFile;
while(tmp != NULL){
prev = tmp;
tmp = tmp->next;
deleteFile(prev);
}
//pthread_mutex_destroy(&fs->fs_lock);
free(fs);
}
File_t * init_File(char* path, int clientFd){
File_t * file;
EXIT_ON(file = malloc(sizeof(File_t)), == NULL);
EXIT_ON( strncpy(file->path, path, MAX_PATH), == NULL);
file->size = 0;
file->cont = NULL;
file->prev = NULL;
file->next = NULL;
file->openedBy = NULL;
list_insert(&file->openedBy, clientFd);
EXIT_ON(pthread_mutex_init(&file->f_mutex, NULL), != 0);
EXIT_ON(pthread_mutex_init(&file->f_order, NULL), != 0);
EXIT_ON(pthread_cond_init(&file->f_go, NULL), != 0);
file->f_activeReaders = 0;
file -> f_activeWriters = 0;
return file;
}
void f_startRead(File_t * file){
EXIT_ON(pthread_mutex_lock(&file->f_order), != 0); // sono in fila
EXIT_ON(pthread_mutex_lock(&file->f_mutex), != 0); // sono in sezione critica
while(file->f_activeWriters > 0){ // se ci sono scrittori attivi mi sospendo (ma mantengo il posto in fila)
EXIT_ON(pthread_cond_wait(&file->f_go, &file->f_mutex), != 0 );
}
file->f_activeReaders++;
EXIT_ON(pthread_mutex_unlock(&file->f_order), != 0); // rilascio il posto in fila
EXIT_ON(pthread_mutex_unlock(&file->f_mutex), != 0); // rilascio la mutex
}
void f_doneRead(File_t * file){
EXIT_ON(pthread_mutex_lock(&file->f_mutex), != 0);
file->f_activeReaders--;
if(file->f_activeReaders == 0){
EXIT_ON( pthread_cond_signal(&file->f_go), != 0); // faccio entrare il prossimo in fila (se ci sono lettori attivi è inutile)
}
EXIT_ON( pthread_mutex_unlock(&file->f_mutex), != 0);
}
void f_startWrite(File_t * file){
EXIT_ON(pthread_mutex_lock(&file->f_order), != 0); // sono in fila
EXIT_ON(pthread_mutex_lock(&file->f_mutex), != 0 ); // sono in sezione critica
while(file->f_activeReaders > 0 || file->f_activeWriters > 0){ // se ci sono scrittori o lettori attivi mi sospendo (ma mantenfo il posto in fila)
EXIT_ON(pthread_cond_wait(&file->f_go, &file->f_mutex), != 0 );
}
file->f_activeWriters++;
EXIT_ON(pthread_mutex_unlock(&file->f_order), != 0); // rilascio il posto in fila
EXIT_ON(pthread_mutex_unlock(&file->f_mutex), != 0); // rilascio la mutex
}
void f_doneWrite(File_t * file){
EXIT_ON(pthread_mutex_lock(&file->f_mutex), != 0);
file->f_activeWriters--;
EXIT_ON( pthread_cond_signal(&file->f_go), != 0);
EXIT_ON( pthread_mutex_unlock(&file->f_mutex), != 0);
}
int readn(int fd, void *ptr, size_t n) {
size_t nleft;
ssize_t nread;
nleft = n;
while (nleft > 0) {
if((nread = read(fd, ptr, nleft)) < 0) {
if (nleft == n) return -1; /* error, return -1 */
else break; /* error, return amount read so far */
} else if (nread == 0) break; /* EOF */
nleft -= nread;
ptr = (void*)((char*)ptr + nread);
}
return(n - nleft); /* return >= 0 */
}
int writen(int fd, void *ptr, size_t n) {
size_t nleft;
ssize_t nwritten;
nleft = n;
while (nleft > 0) {
if((nwritten = write(fd, ptr, nleft)) < 0) {
if (nleft == n) return -1; /* error, return -1 */
else break; /* error, return amount written so far */
} else if (nwritten == 0) break;
nleft -= nwritten;
ptr = (void*)((char*)ptr + nwritten);
}
return(n - nleft); /* return >= 0 */
}
void printFs(FileSystem_t * fs){
File_t * f = fs->firstFile;
while(f != NULL){
printf(" \"%s\"", f->path);
f = f->next;
}
}
void statistiche(FileSystem_t * fs){
printf("\n\n*************** Statistiche di utilizzo ***************\n");
printf("Numero di file massimo memorizzato: %d\n", fs->maxRNumFile);
printf("Occupazione di memoria massima raggiunta: %d\n", fs->maxRSize);
printf("Numero di evict nella cache: %d\n", fs->evictCount);
printf("Ci sono %d file nel server", fs->actNumFile);
if(fs->actNumFile > 0){
printf(":");
printFs(fs);
printf("\n");
}
else{
printf("\n");
}
}<file_sep>/includes/mylinkedlist.h
#ifndef _MYLINKEDLIST_H
#define _MYLINKEDLIST_H
#include <stdio.h>
#include <stdlib.h>
#include <myutil.h>
typedef struct node {
int data;
struct node *next;
}List_t;
void init(struct node **head, int data);
void list_insert(struct node **head, int data);
void list_remove(struct node **head, int data);
void list_deinit(struct node **head);
int list_mem(struct node **head, int data);
#endif /* _MYLINKEDLIST_H */ | c092bfdbce9df4df7709cc0d03ba0c3b8d21927e | [
"C",
"Makefile",
"Shell"
] | 23 | Makefile | matteotolloso/file_storage_server | bd235e8ed7794138a02f3d9bd84eca82806c82e5 | 41fcea589f5fb640c5d1d71b877f93c02aa9fbe2 | |
refs/heads/master | <repo_name>rvnovaes/django-knockout-modeler<file_sep>/knockout_modeler/templatetags/knockout.py
from django import template
import simplejson as json
import datetime
from knockout_modeler.ko import ko, koData, koModel, koBindings, get_fields
register = template.Library()
def knockout(values):
"""
Knockoutify a QuerySet!
"""
if not values:
return ''
field_names = get_fields(values[0])
return ko(values, field_names)
def knockout_data(values, name=None):
"""
"""
if not values:
return ''
field_names = get_fields(values[0])
return koData(values, field_names, name)
def knockout_model(values):
"""
"""
if not values:
return ''
modelClass = values[0].__class__
field_names = get_fields(values[0])
return koModel(modelClass, field_names)
def knockout_bindings(values):
"""
"""
if not values:
return ''
return koBindings(values[0])
register.filter(knockout)
register.filter(knockout_data)
register.filter(knockout_model)
register.filter(knockout_bindings) | 1e5042097da8d19ebc08365fc32aec64a778dab1 | [
"Python"
] | 1 | Python | rvnovaes/django-knockout-modeler | e3b608b771992bc83b6a1ce57e7c8afd0c49b57f | 0249770a7edc39a43f09669249db4bd92b27e736 | |
refs/heads/master | <repo_name>futureer/QSniffer<file_sep>/Ui_QSniffer.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/qinchenchong/workspace/QSniffer/QSniffer.ui'
#
# Created: Tue Oct 23 01:24:35 2012
# by: PyQt4 UI code generator 4.9.5
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(960, 687)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
self.pktGroupBox = QtGui.QGroupBox(self.centralWidget)
self.pktGroupBox.setGeometry(QtCore.QRect(250, 73, 701, 600))
self.pktGroupBox.setObjectName(_fromUtf8("pktGroupBox"))
self.pktTableWidget = QtGui.QTableWidget(self.pktGroupBox)
self.pktTableWidget.setGeometry(QtCore.QRect(10, 31, 680, 330))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pktTableWidget.sizePolicy().hasHeightForWidth())
self.pktTableWidget.setSizePolicy(sizePolicy)
self.pktTableWidget.setRowCount(0)
self.pktTableWidget.setObjectName(_fromUtf8("pktTableWidget"))
self.pktTableWidget.setColumnCount(7)
item = QtGui.QTableWidgetItem()
self.pktTableWidget.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
self.pktTableWidget.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
self.pktTableWidget.setHorizontalHeaderItem(2, item)
item = QtGui.QTableWidgetItem()
self.pktTableWidget.setHorizontalHeaderItem(3, item)
item = QtGui.QTableWidgetItem()
self.pktTableWidget.setHorizontalHeaderItem(4, item)
item = QtGui.QTableWidgetItem()
self.pktTableWidget.setHorizontalHeaderItem(5, item)
item = QtGui.QTableWidgetItem()
self.pktTableWidget.setHorizontalHeaderItem(6, item)
self.pktTableWidget.horizontalHeader().setVisible(True)
self.pktTableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.pktTableWidget.verticalHeader().setVisible(False)
self.pktTreeWidget = QtGui.QTreeWidget(self.pktGroupBox)
self.pktTreeWidget.setGeometry(QtCore.QRect(10, 370, 340, 221))
self.pktTreeWidget.setObjectName(_fromUtf8("pktTreeWidget"))
self.pktTreeWidget.headerItem().setText(0, _fromUtf8("1"))
self.pkt0xBrowser = QtGui.QTextBrowser(self.pktGroupBox)
self.pkt0xBrowser.setGeometry(QtCore.QRect(360, 370, 190, 221))
self.pkt0xBrowser.setObjectName(_fromUtf8("pkt0xBrowser"))
self.pktAsciiBrowser = QtGui.QTextBrowser(self.pktGroupBox)
self.pktAsciiBrowser.setGeometry(QtCore.QRect(559, 370, 131, 220))
self.pktAsciiBrowser.setObjectName(_fromUtf8("pktAsciiBrowser"))
self.filterGroupBox = QtGui.QGroupBox(self.centralWidget)
self.filterGroupBox.setGeometry(QtCore.QRect(250, 11, 701, 61))
self.filterGroupBox.setObjectName(_fromUtf8("filterGroupBox"))
self.filterLineEdit = QtGui.QLineEdit(self.filterGroupBox)
self.filterLineEdit.setGeometry(QtCore.QRect(20, 30, 281, 22))
self.filterLineEdit.setObjectName(_fromUtf8("filterLineEdit"))
self.filterApplyButton = QtGui.QPushButton(self.filterGroupBox)
self.filterApplyButton.setGeometry(QtCore.QRect(310, 26, 101, 32))
self.filterApplyButton.setObjectName(_fromUtf8("filterApplyButton"))
self.filterClearButton = QtGui.QPushButton(self.filterGroupBox)
self.filterClearButton.setGeometry(QtCore.QRect(410, 26, 101, 32))
self.filterClearButton.setObjectName(_fromUtf8("filterClearButton"))
self.filterMsgLable = QtGui.QLabel(self.filterGroupBox)
self.filterMsgLable.setGeometry(QtCore.QRect(520, 32, 141, 16))
self.filterMsgLable.setText(_fromUtf8(""))
self.filterMsgLable.setObjectName(_fromUtf8("filterMsgLable"))
self.devGroupBox = QtGui.QGroupBox(self.centralWidget)
self.devGroupBox.setGeometry(QtCore.QRect(10, 10, 231, 71))
self.devGroupBox.setObjectName(_fromUtf8("devGroupBox"))
self.devLabel = QtGui.QLabel(self.devGroupBox)
self.devLabel.setGeometry(QtCore.QRect(10, 35, 51, 20))
self.devLabel.setObjectName(_fromUtf8("devLabel"))
self.devComboBox = QtGui.QComboBox(self.devGroupBox)
self.devComboBox.setGeometry(QtCore.QRect(60, 32, 161, 26))
self.devComboBox.setObjectName(_fromUtf8("devComboBox"))
self.optGroupBox = QtGui.QGroupBox(self.centralWidget)
self.optGroupBox.setGeometry(QtCore.QRect(10, 90, 231, 101))
self.optGroupBox.setObjectName(_fromUtf8("optGroupBox"))
self.promisCheckBox = QtGui.QCheckBox(self.optGroupBox)
self.promisCheckBox.setGeometry(QtCore.QRect(20, 30, 151, 20))
self.promisCheckBox.setObjectName(_fromUtf8("promisCheckBox"))
self.stopButton = QtGui.QPushButton(self.optGroupBox)
self.stopButton.setGeometry(QtCore.QRect(80, 60, 61, 32))
self.stopButton.setObjectName(_fromUtf8("stopButton"))
self.startButton = QtGui.QPushButton(self.optGroupBox)
self.startButton.setGeometry(QtCore.QRect(10, 60, 61, 32))
self.startButton.setObjectName(_fromUtf8("startButton"))
self.clearButton = QtGui.QPushButton(self.optGroupBox)
self.clearButton.setGeometry(QtCore.QRect(150, 60, 71, 32))
self.clearButton.setObjectName(_fromUtf8("clearButton"))
self.statGroupBox = QtGui.QGroupBox(self.centralWidget)
self.statGroupBox.setGeometry(QtCore.QRect(10, 300, 231, 321))
self.statGroupBox.setObjectName(_fromUtf8("statGroupBox"))
self.totalLabel = QtGui.QLabel(self.statGroupBox)
self.totalLabel.setGeometry(QtCore.QRect(10, 27, 41, 16))
self.totalLabel.setObjectName(_fromUtf8("totalLabel"))
self.totalCountLabel = QtGui.QLabel(self.statGroupBox)
self.totalCountLabel.setGeometry(QtCore.QRect(70, 26, 61, 20))
self.totalCountLabel.setText(_fromUtf8(""))
self.totalCountLabel.setObjectName(_fromUtf8("totalCountLabel"))
self.ethernetLabel = QtGui.QLabel(self.statGroupBox)
self.ethernetLabel.setGeometry(QtCore.QRect(10, 50, 62, 16))
self.ethernetLabel.setObjectName(_fromUtf8("ethernetLabel"))
self.arpLabel = QtGui.QLabel(self.statGroupBox)
self.arpLabel.setGeometry(QtCore.QRect(30, 70, 31, 16))
self.arpLabel.setObjectName(_fromUtf8("arpLabel"))
self.arpCountLabel = QtGui.QLabel(self.statGroupBox)
self.arpCountLabel.setGeometry(QtCore.QRect(70, 70, 62, 16))
self.arpCountLabel.setText(_fromUtf8(""))
self.arpCountLabel.setObjectName(_fromUtf8("arpCountLabel"))
self.rarpCountLabel = QtGui.QLabel(self.statGroupBox)
self.rarpCountLabel.setGeometry(QtCore.QRect(80, 90, 62, 16))
self.rarpCountLabel.setText(_fromUtf8(""))
self.rarpCountLabel.setObjectName(_fromUtf8("rarpCountLabel"))
self.rarpLabel = QtGui.QLabel(self.statGroupBox)
self.rarpLabel.setGeometry(QtCore.QRect(30, 90, 41, 16))
self.rarpLabel.setObjectName(_fromUtf8("rarpLabel"))
self.ipLabel_2 = QtGui.QLabel(self.statGroupBox)
self.ipLabel_2.setGeometry(QtCore.QRect(30, 110, 21, 16))
self.ipLabel_2.setObjectName(_fromUtf8("ipLabel_2"))
self.ipCountLabel = QtGui.QLabel(self.statGroupBox)
self.ipCountLabel.setGeometry(QtCore.QRect(60, 110, 62, 16))
self.ipCountLabel.setText(_fromUtf8(""))
self.ipCountLabel.setObjectName(_fromUtf8("ipCountLabel"))
self.ipv6Label_2 = QtGui.QLabel(self.statGroupBox)
self.ipv6Label_2.setGeometry(QtCore.QRect(30, 130, 35, 16))
self.ipv6Label_2.setObjectName(_fromUtf8("ipv6Label_2"))
self.ipv6CountLabel = QtGui.QLabel(self.statGroupBox)
self.ipv6CountLabel.setGeometry(QtCore.QRect(70, 130, 62, 16))
self.ipv6CountLabel.setText(_fromUtf8(""))
self.ipv6CountLabel.setObjectName(_fromUtf8("ipv6CountLabel"))
self.internetLabel = QtGui.QLabel(self.statGroupBox)
self.internetLabel.setGeometry(QtCore.QRect(10, 150, 62, 16))
self.internetLabel.setObjectName(_fromUtf8("internetLabel"))
self.tcpLabel = QtGui.QLabel(self.statGroupBox)
self.tcpLabel.setGeometry(QtCore.QRect(30, 170, 31, 16))
self.tcpLabel.setObjectName(_fromUtf8("tcpLabel"))
self.tcpCountLabel = QtGui.QLabel(self.statGroupBox)
self.tcpCountLabel.setGeometry(QtCore.QRect(70, 170, 62, 16))
self.tcpCountLabel.setText(_fromUtf8(""))
self.tcpCountLabel.setObjectName(_fromUtf8("tcpCountLabel"))
self.udpLabel = QtGui.QLabel(self.statGroupBox)
self.udpLabel.setGeometry(QtCore.QRect(30, 190, 33, 16))
self.udpLabel.setObjectName(_fromUtf8("udpLabel"))
self.udpCountLabel = QtGui.QLabel(self.statGroupBox)
self.udpCountLabel.setGeometry(QtCore.QRect(70, 190, 62, 16))
self.udpCountLabel.setText(_fromUtf8(""))
self.udpCountLabel.setObjectName(_fromUtf8("udpCountLabel"))
self.icmpLabel = QtGui.QLabel(self.statGroupBox)
self.icmpLabel.setGeometry(QtCore.QRect(30, 210, 41, 16))
self.icmpLabel.setObjectName(_fromUtf8("icmpLabel"))
self.icmpCountLabel = QtGui.QLabel(self.statGroupBox)
self.icmpCountLabel.setGeometry(QtCore.QRect(80, 210, 62, 16))
self.icmpCountLabel.setText(_fromUtf8(""))
self.icmpCountLabel.setObjectName(_fromUtf8("icmpCountLabel"))
self.igmpCountLabel = QtGui.QLabel(self.statGroupBox)
self.igmpCountLabel.setGeometry(QtCore.QRect(80, 230, 62, 16))
self.igmpCountLabel.setText(_fromUtf8(""))
self.igmpCountLabel.setObjectName(_fromUtf8("igmpCountLabel"))
self.igmpLabel = QtGui.QLabel(self.statGroupBox)
self.igmpLabel.setGeometry(QtCore.QRect(30, 230, 41, 16))
self.igmpLabel.setObjectName(_fromUtf8("igmpLabel"))
self.othersLabel = QtGui.QLabel(self.statGroupBox)
self.othersLabel.setGeometry(QtCore.QRect(10, 270, 51, 16))
self.othersLabel.setObjectName(_fromUtf8("othersLabel"))
self.othersCountLabel = QtGui.QLabel(self.statGroupBox)
self.othersCountLabel.setGeometry(QtCore.QRect(70, 270, 61, 20))
self.othersCountLabel.setText(_fromUtf8(""))
self.othersCountLabel.setObjectName(_fromUtf8("othersCountLabel"))
self.icmpv6Label = QtGui.QLabel(self.statGroupBox)
self.icmpv6Label.setGeometry(QtCore.QRect(30, 250, 51, 16))
self.icmpv6Label.setObjectName(_fromUtf8("icmpv6Label"))
self.icmpv6CountLabel = QtGui.QLabel(self.statGroupBox)
self.icmpv6CountLabel.setGeometry(QtCore.QRect(90, 250, 62, 16))
self.icmpv6CountLabel.setText(_fromUtf8(""))
self.icmpv6CountLabel.setObjectName(_fromUtf8("icmpv6CountLabel"))
self.errorCountLabel = QtGui.QLabel(self.statGroupBox)
self.errorCountLabel.setGeometry(QtCore.QRect(60, 290, 61, 20))
self.errorCountLabel.setText(_fromUtf8(""))
self.errorCountLabel.setObjectName(_fromUtf8("errorCountLabel"))
self.errorLabel = QtGui.QLabel(self.statGroupBox)
self.errorLabel.setGeometry(QtCore.QRect(10, 290, 51, 16))
self.errorLabel.setObjectName(_fromUtf8("errorLabel"))
self.dumpGroupBox = QtGui.QGroupBox(self.centralWidget)
self.dumpGroupBox.setGeometry(QtCore.QRect(10, 200, 231, 91))
self.dumpGroupBox.setObjectName(_fromUtf8("dumpGroupBox"))
self.importButton = QtGui.QPushButton(self.dumpGroupBox)
self.importButton.setGeometry(QtCore.QRect(20, 27, 90, 32))
self.importButton.setObjectName(_fromUtf8("importButton"))
self.exportButton = QtGui.QPushButton(self.dumpGroupBox)
self.exportButton.setGeometry(QtCore.QRect(120, 27, 90, 32))
self.exportButton.setObjectName(_fromUtf8("exportButton"))
self.dumpLabel = QtGui.QLabel(self.dumpGroupBox)
self.dumpLabel.setGeometry(QtCore.QRect(10, 60, 210, 16))
self.dumpLabel.setText(_fromUtf8(""))
self.dumpLabel.setObjectName(_fromUtf8("dumpLabel"))
MainWindow.setCentralWidget(self.centralWidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "QSniffer", None, QtGui.QApplication.UnicodeUTF8))
self.pktGroupBox.setTitle(QtGui.QApplication.translate("MainWindow", "Packets", None, QtGui.QApplication.UnicodeUTF8))
item = self.pktTableWidget.horizontalHeaderItem(0)
item.setText(QtGui.QApplication.translate("MainWindow", "No", None, QtGui.QApplication.UnicodeUTF8))
item = self.pktTableWidget.horizontalHeaderItem(1)
item.setText(QtGui.QApplication.translate("MainWindow", "Info", None, QtGui.QApplication.UnicodeUTF8))
item = self.pktTableWidget.horizontalHeaderItem(2)
item.setText(QtGui.QApplication.translate("MainWindow", "Source", None, QtGui.QApplication.UnicodeUTF8))
item = self.pktTableWidget.horizontalHeaderItem(3)
item.setText(QtGui.QApplication.translate("MainWindow", "Destination", None, QtGui.QApplication.UnicodeUTF8))
item = self.pktTableWidget.horizontalHeaderItem(4)
item.setText(QtGui.QApplication.translate("MainWindow", "Protocol", None, QtGui.QApplication.UnicodeUTF8))
item = self.pktTableWidget.horizontalHeaderItem(5)
item.setText(QtGui.QApplication.translate("MainWindow", "Length", None, QtGui.QApplication.UnicodeUTF8))
item = self.pktTableWidget.horizontalHeaderItem(6)
item.setText(QtGui.QApplication.translate("MainWindow", "Info", None, QtGui.QApplication.UnicodeUTF8))
self.filterGroupBox.setTitle(QtGui.QApplication.translate("MainWindow", "Filter", None, QtGui.QApplication.UnicodeUTF8))
self.filterApplyButton.setText(QtGui.QApplication.translate("MainWindow", "Apply", None, QtGui.QApplication.UnicodeUTF8))
self.filterClearButton.setText(QtGui.QApplication.translate("MainWindow", "Clear", None, QtGui.QApplication.UnicodeUTF8))
self.devGroupBox.setTitle(QtGui.QApplication.translate("MainWindow", "Interface", None, QtGui.QApplication.UnicodeUTF8))
self.devLabel.setText(QtGui.QApplication.translate("MainWindow", "Device:", None, QtGui.QApplication.UnicodeUTF8))
self.optGroupBox.setTitle(QtGui.QApplication.translate("MainWindow", "Options", None, QtGui.QApplication.UnicodeUTF8))
self.promisCheckBox.setText(QtGui.QApplication.translate("MainWindow", "Promiscuous Mode", None, QtGui.QApplication.UnicodeUTF8))
self.stopButton.setText(QtGui.QApplication.translate("MainWindow", "Stop", None, QtGui.QApplication.UnicodeUTF8))
self.startButton.setText(QtGui.QApplication.translate("MainWindow", "Start", None, QtGui.QApplication.UnicodeUTF8))
self.clearButton.setText(QtGui.QApplication.translate("MainWindow", "Clear", None, QtGui.QApplication.UnicodeUTF8))
self.statGroupBox.setTitle(QtGui.QApplication.translate("MainWindow", "Statistics", None, QtGui.QApplication.UnicodeUTF8))
self.totalLabel.setText(QtGui.QApplication.translate("MainWindow", "Total: ", None, QtGui.QApplication.UnicodeUTF8))
self.ethernetLabel.setText(QtGui.QApplication.translate("MainWindow", "Ethernet:", None, QtGui.QApplication.UnicodeUTF8))
self.arpLabel.setText(QtGui.QApplication.translate("MainWindow", "ARP: ", None, QtGui.QApplication.UnicodeUTF8))
self.rarpLabel.setText(QtGui.QApplication.translate("MainWindow", "RARP: ", None, QtGui.QApplication.UnicodeUTF8))
self.ipLabel_2.setText(QtGui.QApplication.translate("MainWindow", "IP: ", None, QtGui.QApplication.UnicodeUTF8))
self.ipv6Label_2.setText(QtGui.QApplication.translate("MainWindow", "IPv6: ", None, QtGui.QApplication.UnicodeUTF8))
self.internetLabel.setText(QtGui.QApplication.translate("MainWindow", "Internet:", None, QtGui.QApplication.UnicodeUTF8))
self.tcpLabel.setText(QtGui.QApplication.translate("MainWindow", "TCP: ", None, QtGui.QApplication.UnicodeUTF8))
self.udpLabel.setText(QtGui.QApplication.translate("MainWindow", "UDP: ", None, QtGui.QApplication.UnicodeUTF8))
self.icmpLabel.setText(QtGui.QApplication.translate("MainWindow", "ICMP: ", None, QtGui.QApplication.UnicodeUTF8))
self.igmpLabel.setText(QtGui.QApplication.translate("MainWindow", "IGMP: ", None, QtGui.QApplication.UnicodeUTF8))
self.othersLabel.setText(QtGui.QApplication.translate("MainWindow", "Others: ", None, QtGui.QApplication.UnicodeUTF8))
self.icmpv6Label.setText(QtGui.QApplication.translate("MainWindow", "ICMPv6: ", None, QtGui.QApplication.UnicodeUTF8))
self.errorLabel.setText(QtGui.QApplication.translate("MainWindow", "Error: ", None, QtGui.QApplication.UnicodeUTF8))
self.dumpGroupBox.setTitle(QtGui.QApplication.translate("MainWindow", "Dump", None, QtGui.QApplication.UnicodeUTF8))
self.importButton.setText(QtGui.QApplication.translate("MainWindow", "Import...", None, QtGui.QApplication.UnicodeUTF8))
self.exportButton.setText(QtGui.QApplication.translate("MainWindow", "Export...", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
<file_sep>/Analyzer.py
from winpcapy import pcap_pkthdr
import time, inspect, dpkt
from PyQt4 import QtGui, QtCore
from Util import Statistics, PktItem, NetFormat
class Analyer():
def __init__(self, pktList, table, window):
self.statistics = Statistics()
self.pktList = pktList
self.table = table #tablewidget
self.window = window
self.itemlist = []
self.goon = False
def start_analize(self):
self.goon = True
while self.goon:
if len(self.pktList.pktlist) > 0:
self.pktList.mutex.acquire()
p = self.pktList.pktlist.pop(0)
self.pktList.mutex.release()
item = self.analize(p)
self.itemlist.append(item)
self.show_item(item)
else:
time.sleep(0.01)
self.statistics.updateStatistics(self.window)
def stop_analize(self):
self.goon = False
def clear(self):
self.statistics = Statistics()
self.statistics.updateStatistics(self.window)
del self.itemlist[:]
def analize(self, pkt):
header, data = pkt
pktItem = PktItem()
pktItem.rawpkt = pkt
frame = dpkt.ethernet.Ethernet(data)
self.handle_frame(pktItem, header, frame)
if frame.type == dpkt.ethernet.ETH_TYPE_ARP:
self.handle_arp(pktItem, frame.data)
elif frame.type == dpkt.ethernet.ETH_TYPE_IP:
self.handle_ip(pktItem, frame.data)
elif frame.type == dpkt.ethernet.ETH_TYPE_IP6:
self.handle_ipv6(pktItem, frame.data)
else:
self.handle_unknown(pktItem, frame.data)
print '0x%.4x'%frame.type
return pktItem
def handle_frame(self, pktItem, header, frame):
"""
assume that no error occur in the header section
"""
local_tv_sec = header.ts.tv_sec
ltime = time.localtime(local_tv_sec);
pktItem.time = time.strftime("%H:%M:%S", ltime) # time
pktItem.len = header.len # length
pktItem.protocol = 'Ethernet' # protocol
pktItem.src_mac = NetFormat.ntoa_mac(frame.src) # src_mac
pktItem.dst_mac = NetFormat.ntoa_mac(frame.dst) # dst_mac
self.statistics.total += 1
def handle_arp(self, pktItem, data):
if data.op == dpkt.arp.ARP_OP_REQUEST:
pktItem.protocol = 'ARP'
self.statistics.arp += 1
elif data.op == dpkt.arp.ARP_OP_REPLY:
pktItem.protocol = 'ARP'
self.statistics.arp += 1
elif data.op == dpkt.arp.ARP_OP_REVREQUEST:
pktItem.protocol = 'RARP'
self.statistics.rarp += 1
elif data.op == dpkt.arp.ARP_OP_REVREPLY:
pktItem.protocol = 'RARP'
self.statistics.rarp += 1
else:
self.handle_error(pktItem)
def handle_ip(self, pktItem, data):
pktItem.src_ip = NetFormat.ntoa_ip(data.src)
pktItem.dst_ip = NetFormat.ntoa_ip(data.dst)
pktItem.protocol = 'IP'
self.statistics.ip += 1
if data.p == dpkt.ip.IP_PROTO_TCP:
self.handle_tcp(pktItem, data.data)
elif data.p == dpkt.ip.IP_PROTO_UDP:
self.handle_udp(pktItem, data.data)
elif data.p == dpkt.ip.IP_PROTO_ICMP:
self.handle_icmp(pktItem, data.data)
elif data.p == dpkt.ip.IP_PROTO_IGMP:
self.handle_igmp(pktItem, data.data)
else:
self.handle_unknown(pktItem, data.data)
def handle_ipv6(self, pktItem, data):
pktItem.src_ip = NetFormat.ntoa_ipv6(data.src)
pktItem.dst_ip = NetFormat.ntoa_ipv6(data.dst)
pktItem.protocol = 'IPv6'
self.statistics.ipv6 += 1
if data.p == dpkt.ip.IP_PROTO_TCP:
self.handle_tcp(pktItem, data.data)
elif data.p == dpkt.ip.IP_PROTO_UDP:
self.handle_udp(pktItem, data.data)
elif data.p == dpkt.ip.IP_PROTO_ICMP6:
self.handle_icmp(pktItem, data.data)
else:
self.handle_unknown(pktItem, data.data)
def handle_tcp(self, pktItem, data):
pktItem.src_port = data.sport
pktItem.dst_port = data.dport
pktItem.protocol = "TCP"
self.statistics.tcp += 1
def handle_udp(self, pktItem, data):
pktItem.src_port = data.sport
pktItem.dst_port = data.dport
pktItem.protocol = "UDP"
self.statistics.udp += 1
def handle_icmp(self, pktItem, data):
pktItem.protocol = "ICMP"
self.statistics.icmp += 1
def handle_igmp(self, pktItem, data):
pktItem.protocol = "IGMP"
self.statistics.igmp += 1
def handle_icmpv6(self, pktItem, data):
pktItem.protocol = "ICMPv6"
self.statistics.icmpv6 += 1
def handle_unknown(self, pktItem, data):
# pktItem.protocol = data.__class__.__name__
# if pktItem.protocol == 'str':
# pktItem.protocol = 'Unknown'
self.statistics.unknown += 1
def handle_error(self, pktItem):
pktItem.info = 'error occur in %s() while processing the packet' % inspect.stack()[2][3]
self.statistics.error += 1
def show_item(self, item):
# table = self.pktTableWidget
row = self.table.rowCount()
self.table.insertRow(row)
source = item.src_ip
if source == None:
source = item.src_mac
destination = item.dst_ip
if destination == None:
destination = item.dst_mac
if item.protocol == 'TCP' or item.protocol == 'UDP':
source += ':' + str(item.src_port)
destination += ':' + str(item.dst_port)
No = QtGui.QTableWidgetItem(QtCore.QString(str(row + 1)))
No.setFlags(No.flags() ^ QtCore.Qt.ItemIsEditable)
self.table.setItem(row, 0, No)
Time = QtGui.QTableWidgetItem(QtCore.QString(item.time))
Time.setFlags(Time.flags() ^ QtCore.Qt.ItemIsEditable)
self.table.setItem(row, 1, Time)
Source = QtGui.QTableWidgetItem(QtCore.QString(source))
Source.setFlags(Source.flags() ^ QtCore.Qt.ItemIsEditable)
self.table.setItem(row, 2, Source)
Destination = QtGui.QTableWidgetItem(QtCore.QString(destination))
Destination.setFlags(Destination.flags() ^ QtCore.Qt.ItemIsEditable)
self.table.setItem(row, 3, Destination)
Protocol = QtGui.QTableWidgetItem(QtCore.QString(item.protocol))
Protocol.setFlags(Protocol.flags() ^ QtCore.Qt.ItemIsEditable)
self.table.setItem(row, 4, Protocol)
Length = QtGui.QTableWidgetItem(QtCore.QString(str(item.len)))
Length.setFlags(Length.flags() ^ QtCore.Qt.ItemIsEditable)
self.table.setItem(row, 5, Length)
<file_sep>/QSniffer.py
from MainWindow import MainWindow, pyqtSignature
from Capturer import Capturer, WIN32
from PyQt4 import QtCore, QtGui
from Analyzer import Analyer
from Util import PktList, ProtocolTree, PktContent
import sys, threading, shutil, os
class QSniffer(MainWindow):
def __init__(self):
MainWindow.__init__(self)
self.pktList = PktList()
self.capturer = Capturer(self.pktList)
self.cap_thread = None
self.analyzer = Analyer(self.pktList, self.pktTableWidget, self)
self.ana_thread = None
MainWindow.set_devlist(self, self.capturer.devlist, WIN32)
# self.testWidget()
self.show()
@pyqtSignature("int")
def on_promisCheckBox_stateChanged(self, p0):
MainWindow.on_promisCheckBox_stateChanged(self, p0)
# print "check int:%d"%p0
if(self.promisCheckBox.isChecked()):
self.capturer.set_promisc(True)
else:
self.capturer.set_promisc(False)
@pyqtSignature("")
def on_startButton_clicked(self):
MainWindow.on_startButton_clicked(self)
if self.capturer.adhandle == None:
curindex = self.devComboBox.currentIndex()
if not self.capturer.open_dev(curindex):
# TODO: handle open error
return
self.cap_thread = threading.Thread(target=self.capturer.start_capture)
self.cap_thread.start()
self.ana_thread = threading.Thread(target=self.analyzer.start_analize)
self.ana_thread.start()
@pyqtSignature("")
def on_stopButton_clicked(self):
MainWindow.on_stopButton_clicked(self)
if self.cap_thread != None and self.cap_thread.is_alive():
self.capturer.stop_capture()
self.cap_thread.join()
if self.ana_thread != None and self.ana_thread.is_alive():
self.analyzer.stop_analize()
self.ana_thread.join()
@pyqtSignature("")
def on_clearButton_clicked(self):
MainWindow.on_clearButton_clicked(self)
if self.cap_thread == None or self.ana_thread == None:
pass
elif self.cap_thread.is_alive() or self.ana_thread.is_alive():
if self.capturer.pktSrcType == 'dev':
QtGui.QMessageBox.information(self, "Information",
self.tr("You must stop capture first."))
return False
elif self.capturer.pktSrcType == 'dump':
self.on_stopButton_clicked()
self.capturer.clear()
self.analyzer.clear()
self.pktList.clear()
count = self.pktTableWidget.rowCount()
for i in range(count):
self.pktTableWidget.removeRow(0)
self.pktTreeWidget.clear()
self.pktAsciiBrowser.clear()
self.pkt0xBrowser.clear()
return True
@pyqtSignature("")
def on_exportButton_clicked(self):
MainWindow.on_exportButton_clicked(self)
if self.cap_thread == None or self.ana_thread == None:
pass
elif self.cap_thread.is_alive() or self.ana_thread.is_alive():
if self.capturer.pktSrcType == 'dev':
QtGui.QMessageBox.information(self, "Information",
self.tr("You must stop capture first."))
return False
elif self.capturer.pktSrcType == 'dump':
self.on_stopButton_clicked()
fdialog = QtGui.QFileDialog()
fdialog.setWindowTitle('Save pcap file')
fname = fdialog.getSaveFileName(filter='pcap file(*.pcap)', directory='/')
fname = unicode(fname)
if str(fname) == '':
return False
if os.path.exists('~tmp'):
shutil.move('~tmp', fname)
return True
@pyqtSignature("")
def on_importButton_clicked(self):
MainWindow.on_importButton_clicked(self)
if not self.on_clearButton_clicked():
return False
fdialog = QtGui.QFileDialog()
fdialog.setWindowTitle('Select pcap file')
fname = fdialog.getOpenFileName(directory='/')
fname = unicode(fname)
# print "file name:%r" % fname
if fname == '':
return
if not self.capturer.open_dump(fname):
return
self.cap_thread = threading.Thread(target=self.capturer.start_capture)
self.cap_thread.start()
self.ana_thread = threading.Thread(target=self.analyzer.start_analize)
self.ana_thread.start()
@pyqtSignature("")
def on_filterApplyButton_clicked(self):
MainWindow.on_filterApplyButton_clicked(self)
if self.capturer.adhandle == None:
curindex = self.devComboBox.currentIndex()
if not self.capturer.open_dev(curindex):
return
filterstr = str(self.filterLineEdit.text())
# print "%r" % filterstr
if filterstr == "":
return
msg = self.filterMsgLable
if self.capturer.compile_filter(filterstr):
if self.capturer.set_filter():
msg.setText(QtCore.QString("<font style='color: green;'>Success</font>"))
else:
msg.setText(QtCore.QString("<font style='color: red;'>Error occur</font>"))
else:
msg.setText(QtCore.QString("<font style='color: red;'>Wrong syntax</font>"))
@pyqtSignature("")
def on_filterClearButton_clicked(self):
MainWindow.on_filterClearButton_clicked(self)
self.filterLineEdit.clear()
@pyqtSignature("QString")
def on_filterLineEdit_textChanged(self, p0):
MainWindow.on_filterLineEdit_textChanged(self, p0)
self.filterMsgLable.clear()
@pyqtSignature("int")
def on_devComboBox_currentIndexChanged(self, index):
MainWindow.on_devComboBox_currentIndexChanged(self, index)
self.analyzer.statistics.updateStatistics(self)
# print "combobox index:%d" % index
@pyqtSignature("int, int")
def on_pktTableWidget_cellClicked(self, row, column):
MainWindow.on_pktTableWidget_cellClicked(self, row, column)
tree = self.pktTreeWidget
tree.clear()
pktItem = self.analyzer.itemlist[row]
pktdata = pktItem.rawpkt[1]
pTree = ProtocolTree(tree, pktdata)
tree.insertTopLevelItems(0, pTree.parseProtocol())
p0xb = self.pkt0xBrowser
p0xb.setText(QtCore.QString(PktContent.pkt0xContent(pktdata)))
pasciib = self.pktAsciiBrowser
pasciib.setText(QtCore.QString(PktContent.pktAsciiContent(pktdata)))
def closeEvent(self, *args, **kwargs):
if os.path.exists('./~tmp'):
os.remove('./~tmp')
self.on_stopButton_clicked()
return MainWindow.closeEvent(self, *args, **kwargs)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
qsniffer = QSniffer()
sys.exit(app.exec_())
<file_sep>/Util.py
import threading, dpkt, socket
from PyQt4.QtCore import QString
from PyQt4.QtGui import QTreeWidgetItem
class Statistics:
def __init__(self):
self.ip = 0
self.ipv6 = 0
self.arp = 0
self.rarp = 0
self.tcp = 0
self.udp = 0
self.icmp = 0
self.icmpv6 = 0
self.igmp = 0
self.error = 0
self.unknown = 0
self.total = 0
def updateStatistics(self, window):
window.totalCountLabel.setText(QString(str(self.total)))
window.arpCountLabel.setText(QString(str(self.arp)))
window.rarpCountLabel.setText(QString(str(self.rarp)))
window.ipCountLabel.setText(QString(str(self.ip)))
window.ipv6CountLabel.setText(QString(str(self.ipv6)))
window.tcpCountLabel.setText(QString(str(self.tcp)))
window.udpCountLabel.setText(QString(str(self.udp)))
window.icmpCountLabel.setText(QString(str(self.icmp)))
window.igmpCountLabel.setText(QString(str(self.igmp)))
window.icmpv6CountLabel.setText(QString(str(self.icmpv6)))
window.othersCountLabel.setText(QString(str(self.unknown)))
window.errorCountLabel.setText(QString(str(self.error)))
class PktItem():
def __init__(self):
self.rawpkt = None
self.time = None
self.len = None
self.protocol = None
self.src_mac = None
self.dst_mac = None
self.src_ip = None
self.dst_ip = None
self.src_port = None
self.dst_port = None
self.info = None
class PktList():
def __init__(self):
self.pktlist = []
self.mutex = threading.Lock()
def clear(self):
del self.pktlist[:]
class PktContent():
def __init__(self):
pass
@staticmethod
def pkt0xContent(pktdata):
content = ''
for i, c in enumerate(pktdata):
content += '%-3.2x' % ord(c)
if i % 8 == 7:
content += '\n'
return content
@staticmethod
def pktAsciiContent(pktdata):
content = ''
for i, c in enumerate(pktdata):
if ord(c) < 0x20 or ord(c) > 0x7e:
c = '.'
content += '%c' % ord(c)
if i % 8 != 7:
content += ' '
else:
content += '\n'
return content
class ProtocolTree():
def __init__(self, fatherNode, pktdata):
self.fatherNode = fatherNode
self.pktdata = pktdata
self.TreeList = []
def parseProtocol(self):
frame = dpkt.ethernet.Ethernet(self.pktdata)
self.parseEthernetTree(self.fatherNode, frame)
return self.TreeList
def parseEthernetTree(self, fatherNode, frame):
if frame.__class__.__name__ != 'Ethernet':
print 'parseTree: error in parseEthernetTree. Classname is %s' % frame.__class__.__name__
return None
EthernetTree = QTreeWidgetItem(fatherNode)
EthernetTree.setText(0, 'Ethernet')
EthernetTup = (('dst', "Destination: %s" % NetFormat.ntoa_mac(frame.dst)),
('src', "Source: %s" % NetFormat.ntoa_mac(frame.src)),
('type', "Type: 0x%.4x" % frame.type)
)
# TODO: explain the type code
self.parseDetail(EthernetTree, EthernetTup)
self.TreeList.append(EthernetTree)
if frame.type == dpkt.ethernet.ETH_TYPE_ARP:
self.parseARPTree(fatherNode, frame.data)
elif frame.type == dpkt.ethernet.ETH_TYPE_IP:
self.parseIPTree(fatherNode, frame.data)
elif frame.type == dpkt.ethernet.ETH_TYPE_IP6:
self.parseIPv6Tree(fatherNode, frame.data)
else:
self.parseUnknownTree(fatherNode, frame.data)
def parseARPTree(self, fatherNode, arp):
ARPTree = QTreeWidgetItem(fatherNode)
ARPTree.setText(0, 'ARP')
ARPTup = (('hrd', 'Hardware type: %d' % arp.hrd),
('pro', 'Protocol type: %d' % arp.pro),
('hln', 'Hardware length: %d' % arp.hln),
('pln', 'Protocol length: %d' % arp.pln),
('op', 'Opcode: %d' % arp.op),
('sha', 'Sender MAC address: %s' % NetFormat.ntoa_mac(arp.sha)),
('spa', 'Sender IP address: %s' % NetFormat.ntoa_ip(arp.spa)),
('tha', 'Target MAC address: %s' % NetFormat.ntoa_mac(arp.tha)),
('tpa', 'Target IP address: %s' % NetFormat.ntoa_ip(arp.tpa))
)
self.parseDetail(ARPTree, ARPTup)
self.TreeList.append(ARPTree)
def parseIPTree(self, fatherNode, ip):
IPTree = QTreeWidgetItem(fatherNode)
IPTree.setText(0, 'IP')
IPTup = (('v', 'Version: %d' % ip.v),
('hl', 'Header Length: %d' % (ip.hl << 4)),
('tos', 'Differentiated Services: 0x%.2x' % ip.tos),
('len', 'Total Length: %d' % ip.len),
('id', 'Identification: 0x%.4x' % ip.id),
('flag', 'Flags: 0x%.2x' % (ip.off >> 13)),
('off', 'Fragment Offset: %d' % (ip.off & 0x1fff)),
('ttl', 'Time To Live: %d' % ip.ttl),
('p', 'Protocol: %d' % ip.p),
('sum', 'Header Checksum: 0x%.4x' % ip.sum),
('src', 'Source: %s' % NetFormat.ntoa_ip(ip.src)),
('dst', 'Destination: %s' % NetFormat.ntoa_ip(ip.dst))
)
self.parseDetail(IPTree, IPTup)
self.TreeList.append(IPTree)
if ip.p == dpkt.ip.IP_PROTO_TCP:
self.parseTCPTree(fatherNode, ip.data)
elif ip.p == dpkt.ip.IP_PROTO_UDP:
self.parseUDPTree(fatherNode, ip.data)
elif ip.p == dpkt.ip.IP_PROTO_ICMP:
self.parseICMPTree(fatherNode, ip.data)
elif ip.p == dpkt.ip.IP_PROTO_IGMP:
self.parseIGMPTree(fatherNode, ip.data)
else:
self.parseUnknownTree(fatherNode, ip.data)
def parseIPv6Tree(self, fatherNode, ipv6):
IPv6Tree = QTreeWidgetItem(fatherNode)
IPv6Tree.setText(0, 'IPv6')
IPv6Tup = (('v', 'Version: %d' % ipv6.v),
('fc', 'Traffic class: 0x%.8x' % ipv6.fc),
('flow', 'Flow label: 0x%.8x' % ipv6.flow),
('plen', 'Payload length: %d' % ipv6.plen),
('nxt', 'Next header: %d' % ipv6.nxt),
('hlim', 'Hop limit: %d' % ipv6.hlim),
('src', 'Source: %s' % NetFormat.ntoa_ipv6(ipv6.src)),
('dst', 'Destination: %s' % NetFormat.ntoa_ipv6(ipv6.dst))
)
self.parseDetail(IPv6Tree, IPv6Tup)
self.TreeList.append(IPv6Tree)
if ipv6.p == dpkt.ip.IP_PROTO_TCP:
self.parseTCPTree(fatherNode, ipv6.data)
elif ipv6.p == dpkt.ip.IP_PROTO_UDP:
self.parseUDPTree(fatherNode, ipv6.data)
elif ipv6.p == dpkt.ip.IP_PROTO_ICMP6:
self.parseICMPv6Tree(fatherNode, ipv6.data)
else:
self.parseUnknownTree(fatherNode, ipv6.data)
def parseTCPTree(self, fatherNode, tcp):
TCPTree = QTreeWidgetItem(fatherNode)
TCPTree.setText(0, 'TCP')
TCPTup = (('sport', 'Source port: %d' % tcp.sport),
('dport', 'Destination port: %d' % tcp.dport),
('seq', 'Sequence number: %d' % tcp.seq),
('ack', 'Acknowledgment number: %d' % tcp.ack),
('off_x2', 'Header length: %d' % tcp.off),
('flags', 'Flags: 0x%.4x' % tcp.flags),
('win', 'Window Size: %d' % tcp.win),
('sum', 'Checksum: 0x%.4x' % tcp.sum),
('urp', 'Urgent pointer: 0x%.4x' % tcp.urp)
)
self.parseDetail(TCPTree, TCPTup)
self.TreeList.append(TCPTree)
def parseUDPTree(self, fatherNode, udp):
UDPTree = QTreeWidgetItem(fatherNode)
UDPTree.setText(0, 'UDP')
UDPTup = (('sport', 'Source port: %d' % udp.sport),
('dport', 'Destination port: %d' % udp.dport),
('ulen', 'Length: %d' % udp.ulen),
('sum', 'Checksum: 0x%.4x' % udp.sum)
)
self.parseDetail(UDPTree, UDPTup)
self.TreeList.append(UDPTree)
def parseICMPTree(self, fatherNode, icmp):
ICMPTree = QTreeWidgetItem(fatherNode)
ICMPTree.setText(0, 'ICMP')
ICMPTup = (('type', 'Type: %d' % icmp.type),
('code', 'Code: %d' % icmp.code),
('sum', 'Checksum: 0x%.4x' % icmp.sum)
)
self.parseDetail(ICMPTree, ICMPTup)
self.TreeList.append(ICMPTree)
def parseIGMPTree(self, fatherNode, igmp):
IGMPTree = QTreeWidgetItem(fatherNode)
IGMPTree.setText(0, 'IGMP')
IGMPTup = (('type', 'Type: 0x%.2x' % igmp.type),
('maxresp', 'Max Resp Code: %d' % igmp.maxresp),
('sum', 'Checksum: 0x%.4x' % igmp.sum),
('group', 'Group Address: %d' % igmp.group)
)
self.parseDetail(IGMPTree, IGMPTup)
self.TreeList.append(IGMPTree)
def parseICMPv6Tree(self, fatherNode, icmpv6):
ICMPv6Tree = QTreeWidgetItem(fatherNode)
ICMPv6Tree.setText(0, 'ICMPv6')
ICMPv6Tup = (('type', 'Type: %d' % icmpv6.type),
('code', 'Code: %d' % icmpv6.code),
('sum', 'Checksum: 0x%.4x' % icmpv6.sum)
)
self.parseDetail(ICMPv6Tree, ICMPv6Tup)
self.TreeList.append(ICMPv6Tree)
def parseUnknownTree(self, fatherNode, data):
UnknownTree = QTreeWidgetItem(fatherNode)
UnknownTree.setText(0, 'Other parts')
def parseDetail(self, fatherNode, Tuple):
for t in Tuple:
node = QTreeWidgetItem(fatherNode)
node.setText(0, t[1])
class NetFormat():
def __init__(self):
pass
@staticmethod
def ntoa_mac(nmac):
return '%.2x:%.2x:%.2x:%.2x:%.2x:%.2x' % tuple(map(ord, list(nmac)))
@staticmethod
def ntoa_ip(nip):
return '%d.%d.%d.%d' % tuple(map(ord, list(nip)))
@staticmethod
def ntoa_ipv6(nipv6):
# TODO: format the ipv6 address
addr = '%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x:%.2x%.2x' % tuple(map(ord, list(nipv6)))
return socket.getnameinfo((addr, 0), socket.NI_NUMERICHOST)[0]
<file_sep>/Capturer.py
from ctypes import *
from winpcapy import *
import time, platform, copy, os
from Util import PktList
if platform.python_version()[0] == "3":
raw_input = input
errbuf = create_string_buffer(PCAP_ERRBUF_SIZE)
#header = POINTER(pcap_pkthdr)()
#pkt_data = POINTER(c_ubyte)()
class Capturer():
def __init__(self, pktList):
self.pktList = pktList # packet list
self.devlist = [] # device list
self.__ispromisc = False # promisc flag
self.ifindex = 0 # choosed interface
self.adhandle = None # interface handler
self.filter = "" # filter string
self.fcode = bpf_program() # filter code
self.goon = False
self.pktSrcType = None #pkt source type
self.get_device_list()
def get_device_list(self):
""" get the device list. return bool to indicate success or not. """
alldevs = POINTER(pcap_if_t)()
## Retrieve the device list
if (pcap_findalldevs(byref(alldevs), errbuf) == -1):
print ("Error in pcap_findalldevs: %s\n" % errbuf.value)
return False
i = 0
try:
d = alldevs.contents
except:
print ("Error in pcap_findalldevs: %s" % errbuf.value)
print ("Maybe you need admin privilege?\n")
return False
while d:
i = i + 1
self.devlist.append(d)
if d.next:
d = d.next.contents
else:
d = False
if (i == 0):
print ("\nNo interfaces found! Make sure WinPcap is installed.\n")
return True
def print_device_list(self):
if len(self.devlist) == 0:
print "No interfaces found!"
else:
for i, d in enumerate(self.devlist):
print("%d. %s" % (i + 1, d.name))
if (d.description):
print (" (%s)\n" % (d.description))
else:
print (" (No description available)\n")
def set_promisc(self, ispromisc=False):
self.__ispromisc = ispromisc
print "promisc: %r" % self.__ispromisc
def open_dump(self, filename):
fname = create_string_buffer(filename)
self.adhandle = pcap_open_offline(fname, errbuf)
if self.adhandle == None:
return False
self.pktSrcType = 'dump'
return True
def open_dev(self, ifindex):
self.ifindex = ifindex
if(len(self.devlist) == 0):
print "\nNo device in the device list!\n"
return False
if(self.ifindex < 0 or self.ifindex >= len(self.devlist)):
print ("\nInterface number(%d) out of range(%d).\n" % (self.ifindex, len(self.devlist)))
return False
d = self.devlist[self.ifindex]
self.adhandle = pcap_open_live(d.name, 65536, int(self.__ispromisc), 1000, errbuf)
if (self.adhandle == None):
print("\nUnable to open the adapter. %s is not supported by Pcap-WinPcap\n" % d.name)
return False
self.pktSrcType = 'dev'
return True
def compile_filter(self, filterstr=""):
self.filter = filterstr
netmask = 0xffffff
if pcap_compile(self.adhandle, byref(self.fcode), self.filter, 1, netmask) < 0:
print('\nError compiling filter: wrong syntax.\n')
return False
return True
def set_filter(self):
if pcap_setfilter(self.adhandle, byref(self.fcode)) < 0:
print('\nError setting the filter\n')
return False
return True
def start_capture(self):
res = 1
self.goon = True
#********dump to tmp file
self.dumpfile = pcap_dump_open(self.adhandle, '~tmp')
if(self.dumpfile == None):
print 'temp file open error'
#**************
while res >= 0 and self.goon:
header = POINTER(pcap_pkthdr)()
pkt_data = POINTER(c_ubyte)()
res = pcap_next_ex(self.adhandle, byref(header), byref(pkt_data))
if res == 0:
print "timeout"
continue
if res == -2:
break
self.pktList.mutex.acquire()
self.pktList.pktlist.append((copy.deepcopy(header.contents),
buffer(bytearray(pkt_data[:header.contents.len]))))
self.pktList.mutex.release()
#.........dump
pcap_dump(self.dumpfile, header, pkt_data)
#..............
if res == -1:
print("Error reading the packets: %s\n", pcap_geterr(self.adhandle));
pcap_close(self.adhandle)
return False
pcap_close(self.adhandle)
pcap_dump_close(self.dumpfile)
self.adhandle = None
return True
def stop_capture(self):
self.goon = False
pcap_dump_close(self.dumpfile)
def clear(self):
if os.path.exists('./~tmp'):
os.remove('./~tmp')
pass
def print_pkts(self):
for h, d in self.pktList.pktlist:
local_tv_sec = h.ts.tv_sec
ltime = time.localtime(local_tv_sec);
timestr = time.strftime("%H:%M:%S", ltime)
print
print("%s,%.6d len:%d" % (timestr, h.ts.tv_usec, h.len))
if __name__ == '__main__':
cap = Capturer(PktList())
<file_sep>/README.txt
QSniffer
1. 若要在Python环境中运行QSniffer,则需要安装如下依赖模块:
1)winpcapy
https://code.google.com/p/winpcapy/
2) dpkt
https://code.google.com/p/dpkt/
3) Qt4
http://qt-project.org/downloads
4) PyQt4
http://www.riverbankcomputing.co.uk/software/pyqt/download
2. 打包好的QSniffer.exe可在32位Windows上执行(见可执行程序文件夹)。不需要安装Python运行环境及上述各依赖库。
<file_sep>/MainWindow.py
# -*- coding: utf-8 -*-
"""
Module implementing MainWindow.
"""
from PyQt4.QtGui import QMainWindow, QApplication
from PyQt4.QtCore import pyqtSignature, QStringList, QString
from PyQt4.QtGui import QTableWidget
from Ui_QSniffer import Ui_MainWindow
class MainWindow(QMainWindow, Ui_MainWindow):
"""
Class documentation goes here.
"""
def __init__(self, parent = None):
"""
Constructor
"""
QMainWindow.__init__(self, parent)
self.setupUi(self)
self.pktTableWidget.setColumnWidth(0,50)
self.pktTableWidget.setColumnWidth(1,75)
self.pktTableWidget.setColumnWidth(2,150)
self.pktTableWidget.setColumnWidth(3,150)
self.pktTableWidget.setColumnWidth(4,65)
self.pktTableWidget.setColumnWidth(5,60)
self.pktTableWidget.setColumnWidth(6,160)
self.pktTableWidget.setEditTriggers(QTableWidget.NoEditTriggers)
self.pktTableWidget.setSelectionBehavior(QTableWidget.SelectRows)
self.pktTableWidget.setSelectionMode(QTableWidget.SingleSelection)
self.pktTableWidget.setAlternatingRowColors(True)
self.pktTreeWidget.setHeaderHidden(True)
def set_devlist(self, devlist, isWIN32):
qslist = QStringList()
if isWIN32:
for dev in devlist:
qslist.append(QString(dev.description))
else:
for dev in self.capturer.devlist:
qslist.append(QString(dev.name))
self.devComboBox.addItems(qslist)
@pyqtSignature("")
def on_filterApplyButton_clicked(self):
"""
Slot documentation goes here.
"""
pass
@pyqtSignature("")
def on_filterClearButton_clicked(self):
"""
Slot documentation goes here.
"""
pass
@pyqtSignature("")
def on_stopButton_clicked(self):
"""
Slot documentation goes here.
"""
pass
@pyqtSignature("")
def on_startButton_clicked(self):
"""
Slot documentation goes here.
"""
pass
@pyqtSignature("")
def on_clearButton_clicked(self):
"""
Slot documentation goes here.
"""
pass
@pyqtSignature("")
def on_exportButton_clicked(self):
"""
Slot documentation goes here.
"""
pass
@pyqtSignature("")
def on_importButton_clicked(self):
"""
Slot documentation goes here.
"""
pass
@pyqtSignature("int")
def on_promisCheckBox_stateChanged(self,p0):
"""
Slot documentation goes here.
"""
pass
@pyqtSignature("QString")
def on_filterLineEdit_textChanged(self, p0):
"""
Slot documentation goes here.
"""
pass
@pyqtSignature("int")
def on_devComboBox_currentIndexChanged(self, index):
"""
Slot documentation goes here.
"""
pass
@pyqtSignature("QModelIndex")
def on_pktTableWidget_activated(self, index):
"""
Slot documentation goes here.
"""
pass
@pyqtSignature("int, int")
def on_pktTableWidget_cellClicked(self, row, column):
"""
Slot documentation goes here.
"""
pass
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
| aef2e448c5b7970556b910dfab4da5e53dd1d3fb | [
"Python",
"Text"
] | 7 | Python | futureer/QSniffer | c2fa33f1de6fbbe262b60f25b542a830072fc50f | 4a35c4aa4f79abf1b005189fd9365e7c692af128 | |
refs/heads/master | <repo_name>BinaryKitten/BBMembershipSystem<file_sep>/app/Services/MemberSubscriptionCharges.php
<?php namespace BB\Services;
use BB\Entities\User;
use BB\Events\MemberBalanceChanged;
use BB\Events\SubscriptionPayment;
use BB\Helpers\GoCardlessHelper;
use BB\Repo\PaymentRepository;
use BB\Repo\SubscriptionChargeRepository;
use BB\Repo\UserRepository;
use Carbon\Carbon;
class MemberSubscriptionCharges
{
/**
* @var UserRepository
*/
private $userRepository;
/**
* @var SubscriptionChargeRepository
*/
private $subscriptionChargeRepository;
/**
* @var GoCardlessHelper
*/
private $goCardless;
/**
* @var PaymentRepository
*/
private $paymentRepository;
function __construct(UserRepository $userRepository, SubscriptionChargeRepository $subscriptionChargeRepository, GoCardlessHelper $goCardless, PaymentRepository $paymentRepository)
{
$this->userRepository = $userRepository;
$this->subscriptionChargeRepository = $subscriptionChargeRepository;
$this->goCardless = $goCardless;
$this->paymentRepository = $paymentRepository;
}
/**
* Create the sub charge for each member, only do this for members with dates matching the supplied date
*
* @param Carbon $targetDate
*/
public function createSubscriptionCharges($targetDate)
{
$users = $this->userRepository->getBillableActive();
foreach ($users as $user) {
if (($user->payment_day == $targetDate->day) && ( ! $this->subscriptionChargeRepository->chargeExists($user->id, $targetDate))) {
$this->subscriptionChargeRepository->createCharge($user->id, $targetDate);
}
}
}
/**
* Locate all charges that are for today or the past and mark them as due
*/
public function makeChargesDue()
{
$subCharges = $this->subscriptionChargeRepository->getPending();
foreach ($subCharges as $charge) {
if ($charge->charge_date->isToday() || $charge->charge_date->isPast()) {
$this->subscriptionChargeRepository->setDue($charge->id);
}
}
}
/**
* Bill members based on the sub charges that are due
*/
public function billMembers()
{
$subCharges = $this->subscriptionChargeRepository->getDue();
//Check each of the due charges, if they have previous attempted payments ignore them
// we don't want to retry failed payments as for DD's this will generate bank charges
$subCharges->reject(function ($charge) {
return $this->paymentRepository->getPaymentsByReference($charge->id)->count() > 0;
});
//Filter the list into two gocardless and balance subscriptions
$goCardlessUsers = $subCharges->filter(function ($charge) {
return $charge->user->payment_method == 'gocardless-variable';
});
$balanceUsers = $subCharges->filter(function ($charge) {
return $charge->user->payment_method == 'balance';
});
//Charge the balance users
foreach ($balanceUsers as $charge) {
if (($charge->user->monthly_subscription * 100) > $charge->user->cash_balance) {
//user doesn't have enough money
//If they have a secondary payment method of gocardless try that
if ($charge->user->secondary_payment_method == 'gocardless-variable') {
//Add the charge to the gocardless list for processing
$goCardlessUsers->push($charge);
event(new SubscriptionPayment\InsufficientFundsTryingDirectDebit($charge->user->id, $charge->id));
} else {
event(new SubscriptionPayment\FailedInsufficientFunds($charge->user->id, $charge->id));
}
continue;
}
$this->paymentRepository->recordSubscriptionPayment($charge->user->id, 'balance', '', $charge->user->monthly_subscription, 'paid', 0, $charge->id);
event(new MemberBalanceChanged($charge->user->id));
}
//Charge the gocardless users
foreach ($goCardlessUsers as $charge) {
$bill = $this->goCardless->newBill($charge->user->subscription_id, $charge->user->monthly_subscription, $this->goCardless->getNameFromReason('subscription'));
if ($bill) {
$this->paymentRepository->recordSubscriptionPayment($charge->user->id, 'gocardless-variable', $bill->id, $bill->amount, $bill->status, $bill->gocardless_fees, $charge->id);
}
};
}
/**
* Get a users latest sub payment
* @param $userId
* @return bool
*/
public function lastUserChargeExpires($userId)
{
$charge = User::where('user_id', $userId)->where('status', ['processing', 'paid'])->orderBy('charge_date', 'DESC')->first();
if ($charge) {
return $charge->charge_date->addMonth();
}
return false;
}
}<file_sep>/app/Entities/Settings.php
<?php namespace BB\Entities;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
/**
* Class Activity
*
* @property integer $id
* @property integer $key_fob_id
* @property integer $user_id
* @property User $user
* @property string $service
* @property string $response
* @property bool $delayed
* @property Carbon $created_at
* @package BB\Entities
*/
class Settings extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'settings';
protected $primaryKey = 'key';
public $incrementing = false;
public $timestamps = false;
protected $fillable = ['key', 'value'];
public static function put($key, $value)
{
self::create(['key' => $key, 'value' => $value]);
}
public static function get($key)
{
$setting = self::findOrFail($key);
return $setting->value;
}
}
<file_sep>/app/Http/Controllers/GoCardlessWebhookController.php
<?php namespace BB\Http\Controllers;
use BB\Entities\Payment;
use BB\Entities\User;
use BB\Helpers\GoCardlessHelper;
use BB\Repo\PaymentRepository;
use BB\Repo\SubscriptionChargeRepository;
use \Carbon\Carbon;
class GoCardlessWebhookController extends Controller
{
/**
* @var PaymentRepository
*/
private $paymentRepository;
/**
* @var SubscriptionChargeRepository
*/
private $subscriptionChargeRepository;
/**
* @var GoCardlessHelper
*/
private $goCardless;
public function __construct(GoCardlessHelper $goCardless, PaymentRepository $paymentRepository, SubscriptionChargeRepository $subscriptionChargeRepository)
{
$this->goCardless = $goCardless;
$this->paymentRepository = $paymentRepository;
$this->subscriptionChargeRepository = $subscriptionChargeRepository;
}
public function receive()
{
$request = \Request::instance();
if ( ! $this->goCardless->validateWebhook($request->getContent())) {
return \Response::make('', 403);
}
$parser = new \BB\Services\Payment\GoCardlessWebhookParser();
$parser->parseResponse($request->getContent());
switch ($parser->getResourceType()) {
case 'bill':
switch ($parser->getAction()) {
case 'created':
$this->processNewBills($parser->getBills());
break;
case 'paid':
$this->processPaidBills($parser->getBills());
break;
default:
$this->processBills($parser->getAction(), $parser->getBills());
}
break;
case 'pre_authorization':
$this->processPreAuths($parser->getAction(), $parser->getPreAuthList());
break;
case 'subscription':
$this->processSubscriptions($parser->getSubscriptions());
break;
}
return \Response::make('Success', 200);
}
/**
* A Bill has been created, these will always start within the system except for subscription payments
*
* @param array $bills
*/
private function processNewBills(array $bills)
{
//We have new bills/payment
foreach ($bills as $bill) {
//Ignore non subscription payment creations
if ($bill['source_type'] != 'subscription') {
continue;
}
try {
//Locate the user through their subscription id
$user = User::where('payment_method', 'gocardless')->where('subscription_id', $bill['source_id'])->first();
if ( ! $user) {
\Log::warning("GoCardless new sub payment notification for unmatched user. Bill ID: " . $bill['id']);
continue;
}
$ref = null;
$this->paymentRepository->recordSubscriptionPayment($user->id, 'gocardless', $bill['id'], $bill['amount'], $bill['status'], ($bill['amount'] - $bill['amount_minus_fees']), $ref);
} catch (\Exception $e) {
\Log::error($e);
}
}
}
private function processPaidBills(array $bills)
{
//When a bill is paid update the status on the local record and the connected sub charge (if there is one)
foreach ($bills as $bill) {
$existingPayment = $this->paymentRepository->getPaymentBySourceId($bill['id']);
if ($existingPayment) {
if ($bill['paid_at']) {
$paymentDate = new Carbon($bill['paid_at']);
} else {
$paymentDate = new Carbon();
}
$this->paymentRepository->markPaymentPaid($existingPayment->id, $paymentDate);
} else {
\Log::info("GoCardless Webhook received for unknown payment: " . $bill['id']);
}
}
}
/**
* @param string $action
*/
private function processBills($action, array $bills)
{
foreach ($bills as $bill) {
$existingPayment = $this->paymentRepository->getPaymentBySourceId($bill['id']);
if ($existingPayment) {
if (($bill['status'] == 'failed') || ($bill['status'] == 'cancelled')) {
//Payment failed or cancelled - either way we don't have the money!
//We need to retrieve the payment from the user somehow but don't want to cancel the subscription.
//$this->handleFailedCancelledBill($existingPayment);
$this->paymentRepository->recordPaymentFailure($existingPayment->id, $bill['status']);
} elseif (($bill['status'] == 'pending') && ($action == 'retried')) {
//Failed payment is being retried
$subCharge = $this->subscriptionChargeRepository->getById($existingPayment->reference);
if ($subCharge) {
if ($subCharge->amount == $bill['amount']) {
$this->subscriptionChargeRepository->markChargeAsProcessing($subCharge->id);
} else {
//@TODO: Handle partial payments
\Log::warning("Sub charge handling - gocardless partial payment");
}
}
} elseif ($bill['status'] == 'refunded') {
//Payment refunded
//Update the payment record and possible the user record
} elseif ($bill['status'] == 'withdrawn') {
//Money taken out - not our concern
}
} else {
\Log::info("GoCardless Webhook received for unknown payment: " . $bill['id']);
}
}
}
/**
* @param string $action
*/
private function processPreAuths($action, $preAuthList)
{
//Preauths are handled at creation
foreach ($preAuthList as $preAuth) {
if ($preAuth['status'] == 'cancelled') {
$user = User::where('payment_method', 'gocardless-variable')->where('subscription_id', $preAuth['id'])->first();
if ($user) {
$user->cancelSubscription();
}
}
}
}
private function processSubscriptions($subscriptions)
{
foreach ($subscriptions as $sub) {
//Setup messages aren't used as we deal with them directly.
if ($sub['status'] == 'cancelled') {
//Make sure our local record is correct
$user = User::where('payment_method', 'gocardless')->where('subscription_id', $sub['id'])->first();
if ($user) {
$user->cancelSubscription();
}
}
}
}
/**
* The bill has been cancelled or failed, update the user records to compensate
*
* @param $existingPayment
*/
private function handleFailedCancelledBill(Payment $existingPayment)
{
if ($existingPayment->reason == 'subscription') {
//If the payment is a subscription payment then we need to take action and warn the user
$user = $existingPayment->user()->first();
$user->status = 'suspended';
//Rollback the users subscription expiry date or set it to today
$expiryDate = \BB\Helpers\MembershipPayments::lastUserPaymentExpires($user->id);
if ($expiryDate) {
$user->subscription_expires = $expiryDate;
} else {
$user->subscription_expires = new Carbon();
}
$user->save();
//Update the subscription charge to reflect the payment failure
$subCharge = $this->subscriptionChargeRepository->getById($existingPayment->reference);
if ($subCharge) {
$this->subscriptionChargeRepository->paymentFailed($subCharge->id);
}
} elseif ($existingPayment->reason == 'induction') {
//We still need to collect the payment from the user
} elseif ($existingPayment->reason == 'box-deposit') {
} elseif ($existingPayment->reason == 'key-deposit') {
}
}
}<file_sep>/app/Helpers/GoCardlessHelper.php
<?php namespace BB\Helpers;
class GoCardlessHelper
{
private $account_details;
public function __construct()
{
$this->setup();
}
public function setup()
{
$this->account_details = array(
'app_id' => env('GOCARDLESS_APP_ID', ''),
'app_secret' => env('GOCARDLESS_APP_SECRET', ''),
'merchant_id' => env('GOCARDLESS_MERCHANT_ID', ''),
'access_token' => env('GOCARDLESS_ACCESS_TOKEN', ''),
);
// Initialize GoCardless
if (\App::environment() == 'production') {
\GoCardless::$environment = 'production';
}
\GoCardless::set_account_details($this->account_details);
}
public function newPreAuthUrl($paymentDetails)
{
$baseDetails = array(
'max_amount' => 250,
'interval_length' => 1,
'interval_unit' => 'month',
);
$paymentDetails = array_merge($baseDetails, $paymentDetails);
return \GoCardless::new_pre_authorization_url($paymentDetails);
}
public function newSubUrl($payment_details)
{
return \GoCardless::new_subscription_url($payment_details);
}
public function confirmResource($confirm_params)
{
return \GoCardless::confirm_resource($confirm_params);
}
public function cancelSubscription($id)
{
return \GoCardless_Subscription::find($id)->cancel();
}
/**
* Accept the raw json response and validate it
* @param $webhook
* @return bool
*/
public function validateWebhook($webhook)
{
$webhook_array = json_decode($webhook, true);
return \GoCardless::validate_webhook($webhook_array['payload']);
}
public function newBillUrl($payment_details)
{
return \GoCardless::new_bill_url($payment_details);
}
public function getSubscriptionFirstBill($id)
{
$bills = \GoCardless_Merchant::find($this->account_details['merchant_id'])->bills(array('source_id' => $id));
if (count($bills) > 0) {
return $bills[0];
}
return false;
}
/**
* Create a new payment against a preauth
* @param $preauthId
* @param $amount
* @param null|string $name
* @param null|string $description
* @return bool|mixed
*/
public function newBill($preauthId, $amount, $name = null, $description = null)
{
try {
$preAuth = \GoCardless_PreAuthorization::find($preauthId);
$details = [
'amount' => $amount,
'name' => $name,
'description' => $description,
];
return $preAuth->create_bill($details);
} catch (\GoCardless_ApiException $e) {
\Log::error($e);
return false;
}
}
public function cancelPreAuth($preauthId)
{
try {
$preAuth = \GoCardless_PreAuthorization::find($preauthId);
$preAuthStatus = $preAuth->cancel();
return ($preAuthStatus->status == 'cancelled');
} catch (\GoCardless_ApiException $e) {
\Log::error($e);
return false;
}
}
/**
* @param string $reason
* @return null|string
*/
public function getNameFromReason($reason)
{
switch ($reason) {
case 'subscription':
return 'Monthly subscription';
case 'balance':
return 'Balance top up';
case 'equipment-fee':
return 'Equipment access fee';
case 'door-key':
return 'Door key';
}
return null;
}
} <file_sep>/app/Http/Controllers/PaymentController.php
<?php namespace BB\Http\Controllers;
use BB\Entities\Induction;
use BB\Entities\Payment;
use BB\Entities\User;
use BB\Exceptions\NotImplementedException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
class PaymentController extends Controller
{
/**
*
* @TODO: Workout exactly what this is used for - I think most of the functionality has been moved elsewhere
*
*/
/**
* @var \BB\Repo\EquipmentRepository
*/
private $equipmentRepository;
/**
* @var \BB\Repo\PaymentRepository
*/
private $paymentRepository;
/**
* @var \BB\Repo\UserRepository
*/
private $userRepository;
/**
* @var \BB\Repo\SubscriptionChargeRepository
*/
private $subscriptionChargeRepository;
function __construct(
\BB\Helpers\GoCardlessHelper $goCardless,
\BB\Repo\EquipmentRepository $equipmentRepository,
\BB\Repo\PaymentRepository $paymentRepository,
\BB\Repo\UserRepository $userRepository,
\BB\Repo\SubscriptionChargeRepository $subscriptionChargeRepository
) {
$this->goCardless = $goCardless;
$this->equipmentRepository = $equipmentRepository;
$this->paymentRepository = $paymentRepository;
$this->userRepository = $userRepository;
$this->subscriptionChargeRepository = $subscriptionChargeRepository;
$this->middleware('role:member', array('only' => ['create', 'destroy']));
}
public function index()
{
$sortBy = \Request::get('sortBy', 'created_at');
$direction = \Request::get('direction', 'desc');
$dateFilter = \Request::get('date_filter', '');
$memberFilter = \Request::get('member_filter', '');
$reasonFilter = \Request::get('reason_filter', '');
$this->paymentRepository->setPerPage(50);
if ($dateFilter) {
$startDate = \Carbon\Carbon::createFromFormat('Y-m-d', $dateFilter)->setTime(0, 0, 0);
$this->paymentRepository->dateFilter($startDate, $startDate->copy()->addMonth());
}
if ($memberFilter) {
$this->paymentRepository->memberFilter($memberFilter);
}
if ($reasonFilter) {
$this->paymentRepository->reasonFilter($reasonFilter);
}
$payments = $this->paymentRepository->getPaginated(compact('sortBy', 'direction'));
$paymentTotal = $this->paymentRepository->getTotalAmount();
$dateRangeEarliest = \Carbon\Carbon::create(2009, 07, 01);
$dateRangeStart = \Carbon\Carbon::now();
$dateRange = [];
while ($dateRangeStart->gt($dateRangeEarliest)) {
$dateRange[$dateRangeStart->toDateString()] = $dateRangeStart->format('F Y');
$dateRangeStart->subMonth();
}
$memberList = $this->userRepository->getAllAsDropdown();
$reasonList = [
'subscription' => 'Subscription',
'induction' => 'Equipment Access Fee',
'balance' => 'Balance',
'door-key' => 'Key Deposit',
'storage-box' => 'Storage Box Deposit',
'equipment-fee' => 'Equipment Costs'
];
return \View::make('payments.index')->with('payments', $payments)->with('dateRange', $dateRange)
->with('memberList', $memberList)->with('reasonList', $reasonList)->with('paymentTotal', $paymentTotal);
}
/**
* Start the creation of a new gocardless payment
* Details get posted into this method and the redirected to gocardless
*
* @depreciated
* @param $userId
* @throws \BB\Exceptions\AuthenticationException
* @throws \BB\Exceptions\FormValidationException
* @throws \BB\Exceptions\NotImplementedException
*/
public function create($userId)
{
$user = User::findWithPermission($userId);
if (\Input::get('source') == 'gocardless') {
$reason = \Input::get('reason');
if ($reason == 'subscription') {
//must go via the gocardless payment controller
throw new \BB\Exceptions\NotImplementedException('Attempted GoCardless subscription payment');
} elseif ($reason == 'induction') {
//Payments must go via the balance
throw new \BB\Exceptions\NotImplementedException('Attempted GoCardless induction payment');
} elseif ($reason == 'door-key') {
//Payments must go via the balance
throw new \BB\Exceptions\NotImplementedException('Attempted GoCardless door payment');
} elseif ($reason == 'storage-box') {
//Payments must go via the balance
throw new \BB\Exceptions\NotImplementedException('Attempted GoCardless storage box payment');
} elseif ($reason == 'balance') {
$amount = \Input::get('amount') * 1; //convert the users amount into a number
if ( ! is_numeric($amount)) {
$exceptionErrors = new \Illuminate\Support\MessageBag(['amount' => 'Invalid amount']);
throw new \BB\Exceptions\FormValidationException('Not a valid amount', $exceptionErrors);
}
$name = strtoupper('BBBALANCE' . $user->id);
$description = 'BB Credit Payment';
$ref = null;
} else {
throw new \BB\Exceptions\NotImplementedException();
}
$payment_details = array(
'amount' => $amount,
'name' => $name,
'description' => $description,
'redirect_uri' => route('account.payment.confirm-payment', [$user->id]),
'user' => [
'first_name' => $user->given_name,
'last_name' => $user->family_name,
'billing_address1' => $user->address_line_1,
'billing_address2' => $user->address_line_2,
'billing_town' => $user->address_line_3,
'billing_postcode' => $user->address_postcode,
'country_code' => 'GB'
],
'state' => $reason . ':' . $ref
);
return \Redirect::to($this->goCardless->newBillUrl($payment_details));
} else {
//Unsupported for now
// perhaps manual payments or maybe they should go straight to store
throw new \BB\Exceptions\NotImplementedException();
}
}
/**
* Confirm a gocardless payment and create a payment record
*
* @depreciated
* @param $userId
* @return Illuminate\Http\RedirectResponse
* @throws \BB\Exceptions\AuthenticationException
* @throws \BB\Exceptions\NotImplementedException
*/
public function confirmPayment($userId)
{
$confirm_params = array(
'resource_id' => $_GET['resource_id'],
'resource_type' => $_GET['resource_type'],
'resource_uri' => $_GET['resource_uri'],
'signature' => $_GET['signature']
);
// State is optional
if (isset($_GET['state'])) {
$confirm_params['state'] = $_GET['state'];
}
$user = User::findWithPermission($userId);
try {
$confirmed_resource = $this->goCardless->confirmResource($confirm_params);
} catch (\Exception $e) {
$errors = $e->getMessage();
\Notification::error($errors);
return \Redirect::route('account.show', [$user->id]);
}
$details = explode(':', \Input::get('state'));
$reason = $details[0];
$ref = $details[1];
\Log::debug('Old PaymentController@confirmPayment method used. Reason: ' . $reason);
$payment = new Payment([
'reason' => $reason,
'source' => 'gocardless',
'source_id' => $confirmed_resource->id,
'amount' => $confirmed_resource->amount,
'fee' => ($confirmed_resource->amount - $confirmed_resource->amount_minus_fees),
'amount_minus_fee' => $confirmed_resource->amount_minus_fees,
'status' => $confirmed_resource->status
]);
$user->payments()->save($payment);
if ($reason == 'subscription') {
$user->status = 'active';
$user->active = true;
$user->save();
} elseif ($reason == 'induction') {
//Payments must go via the balance
throw new \BB\Exceptions\NotImplementedException('Attempted GoCardless induction payment');
} elseif ($reason == 'door-key') {
//Payments must go via the balance
throw new \BB\Exceptions\NotImplementedException('Attempted GoCardless dor key payment');
} elseif ($reason == 'storage-box') {
//Payments must go via the balance
throw new \BB\Exceptions\NotImplementedException('Attempted GoCardless storage box payment');
} elseif ($reason == 'balance') {
$memberCreditService = \App::make('\BB\Services\Credit');
$memberCreditService->setUserId($user->id);
$memberCreditService->recalculate();
//This needs to be improved
\Notification::success('Payment recorded');
return \Redirect::route('account.bbcredit.index', $user->id);
} else {
throw new \BB\Exceptions\NotImplementedException();
}
\Notification::success('Payment made');
return \Redirect::route('account.show', [$user->id]);
}
/**
* Store a manual payment
*
* @param $userId
* @throws \BB\Exceptions\AuthenticationException
* @throws \BB\Exceptions\FormValidationException
* @throws \BB\Exceptions\NotImplementedException
* @return Illuminate\Http\RedirectResponse
* @deprecated
*/
public function store($userId)
{
$user = User::findWithPermission($userId);
if ( ! \Auth::user()->hasRole('admin') && ! \Auth::user()->hasRole('finance')) {
throw new \BB\Exceptions\AuthenticationException;
}
\Log::debug('Manual payment endpoint getting hit. account/{id}/payment. paymentController@store '.json_encode(\Input::all()));
$reason = \Input::get('reason');
if ($reason == 'subscription') {
$payment = new Payment([
'reason' => $reason,
'source' => \Input::get('source'),
'source_id' => '',
'amount' => $user->monthly_subscription,
'amount_minus_fee' => $user->monthly_subscription,
'status' => 'paid'
]);
$user->payments()->save($payment);
$user->extendMembership(\Input::get('source'), \Carbon\Carbon::now()->addMonth());
} elseif ($reason == 'induction') {
if (\Input::get('source') == 'manual') {
$ref = \Input::get('induction_key');
($item = $this->equipmentRepository->findBySlug($ref)) || App::abort(404);
$payment = new Payment([
'reason' => $reason,
'source' => 'manual',
'source_id' => '',
'amount' => $item->cost,
'amount_minus_fee' => $item->cost,
'status' => 'paid'
]);
$payment = $user->payments()->save($payment);
Induction::create([
'user_id' => $user->id,
'key' => $ref,
'paid' => true,
'payment_id' => $payment->id
]);
} else {
throw new \BB\Exceptions\NotImplementedException();
}
} elseif ($reason == 'door-key') {
$payment = new Payment([
'reason' => $reason,
'source' => \Input::get('source'),
'source_id' => '',
'amount' => 10,
'amount_minus_fee' => 10,
'status' => 'paid'
]);
$user->payments()->save($payment);
$user->key_deposit_payment_id = $payment->id;
$user->save();
} elseif ($reason == 'storage-box') {
$payment = new Payment([
'reason' => $reason,
'source' => \Input::get('source'),
'source_id' => '',
'amount' => 5,
'amount_minus_fee' => 5,
'status' => 'paid'
]);
$user->payments()->save($payment);
$user->storage_box_payment_id = $payment->id;
$user->save();
} elseif ($reason == 'balance') {
$amount = \Input::get('amount') * 1; //convert the users amount into a number
if ( ! is_numeric($amount)) {
$exceptionErrors = new \Illuminate\Support\MessageBag(['amount' => 'Invalid amount']);
throw new \BB\Exceptions\FormValidationException('Not a valid amount', $exceptionErrors);
}
$payment = new Payment([
'reason' => 'balance',
'source' => \Input::get('source'),
'source_id' => '',
'amount' => $amount,
'amount_minus_fee' => $amount,
'status' => 'paid'
]);
$user->payments()->save($payment);
$memberCreditService = \App::make('\BB\Services\Credit');
$memberCreditService->setUserId($user->id);
$memberCreditService->recalculate();
//This needs to be improved
\Notification::success('Payment recorded');
return \Redirect::route('account.bbcredit.index', $user->id);
} else {
throw new \BB\Exceptions\NotImplementedException();
}
\Notification::success('Payment recorded');
return \Redirect::route('account.show', [$user->id]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
//
}
/**
* Update a payment
* Change where the money goes by altering the original record or creating a secondary payment
*
* @param Request $request
* @param int $paymentId
*
* @return Illuminate\Http\RedirectResponse
* @throws NotImplementedException
* @throws \BB\Exceptions\PaymentException
*/
public function update(Request $request, $paymentId)
{
$payment = $this->paymentRepository->getById($paymentId);
switch($request->get('change')) {
case 'assign-unknown-to-user':
$newUserId = $request->get('user_id');
try {
$newUser = $this->userRepository->getById($newUserId);
} catch (ModelNotFoundException $e) {
\Notification::error('User not found');
break;
}
$this->paymentRepository->assignPaymentToUser($paymentId, $newUser->id);
\Notification::success('Payment updated');
break;
case 'refund-to-balance':
if ($payment->reason === 'induction') {
throw new NotImplementedException('Please refund via the member induction list');
}
$this->paymentRepository->refundPaymentToBalance($paymentId);
\Notification::success('Payment updated');
break;
default:
throw new NotImplementedException('This hasn\'t been built yet');
}
return \Redirect::back();
}
/**
* Remove the specified payment
*
* @param int $id
* @return Illuminate\Http\RedirectResponse
* @throws \BB\Exceptions\ValidationException
*/
public function destroy($id)
{
$payment = $this->paymentRepository->getById($id);
//we can only allow some records to get deleted, only cash payments can be removed, everything else must be refunded off
if ($payment->source != 'cash') {
throw new \BB\Exceptions\ValidationException('Only cash payments can be deleted');
}
if ($payment->reason != 'balance') {
throw new \BB\Exceptions\ValidationException('Currently only payments to the members balance can be deleted');
}
//The delete event will broadcast an event and allow related actions to occur
$this->paymentRepository->delete($id);
\Notification::success('Payment deleted');
return \Redirect::back();
}
/**
* This is a method for migrating user to the variable gocardless subscription
* It will cancel the existing direct debit and direct the user to setup a pre auth
*
* @return Illuminate\Http\RedirectResponse
*/
public function migrateDD()
{
$user = \Auth::user();
//cancel the existing dd
try {
$subscription = $this->goCardless->cancelSubscription($user->subscription_id);
if ($subscription->status != 'cancelled') {
\Notification::error('Could not cancel the existing subscription');
return \Redirect::back();
}
} catch (\GoCardless_ApiException $e) {
}
$user->payment_method = '';
$user->subscription_id = '';
$user->save();
$payment_details = array(
'redirect_uri' => route('account.subscription.store', $user->id),
'user' => [
'first_name' => $user->given_name,
'last_name' => $user->family_name,
'billing_address1' => $user->address->line_1,
'billing_address2' => $user->address->line_2,
'billing_town' => $user->address->line_3,
'billing_postcode' => $user->address->postcode,
'country_code' => 'GB'
]
);
return \Redirect::to($this->goCardless->newPreAuthUrl($payment_details));
}
}
<file_sep>/app/Services/Payment/GoCardlessWebhookParser.php
<?php namespace BB\Services\Payment;
class GoCardlessWebhookParser
{
/**
* @var string
*/
private $rawResponse = null;
/**
* @var array
*/
private $response;
/**
* @var string
*/
private $action = null;
/**
* @var string
*/
private $resourceType = null;
/**
* @var array
*/
private $bills = [];
/**
* @var array
*/
private $subscriptions = [];
/**
* @var array
*/
private $preAuthList = [];
public function parseResponse($paymentPaidPayload)
{
$this->rawResponse = $paymentPaidPayload;
$response = json_decode($this->rawResponse, true);
if ( ! is_array($response)) {
return;
}
$this->response = $response;
$this->action = $this->response['payload']['action'];
$this->resourceType = $this->response['payload']['resource_type'];
if ($this->resourceType == 'bill') {
$this->setBills($this->response['payload']['bills']);
} else if ($this->resourceType == 'subscription') {
$this->subscriptions = $this->response['payload']['subscriptions'];
} else if ($this->resourceType == 'pre_authorization') {
$this->preAuthList = $this->response['payload']['pre_authorizations'];
}
}
/**
* @return null
*/
public function getAction()
{
return $this->action;
}
/**
* @return null
*/
public function getResourceType()
{
return $this->resourceType;
}
/**
* @return array
*/
public function getBills()
{
return $this->bills;
}
/**
* @return array
*/
public function getSubscriptions()
{
return $this->subscriptions;
}
/**
* @return array
*/
public function getPreAuthList()
{
return $this->preAuthList;
}
private function setBills($bills)
{
foreach ($bills as $i=>$bill) {
if ( ! isset($bills[$i]['source_type'])) {
$bills[$i]['source_type'] = '';
}
if ( ! isset($bills[$i]['source_id'])) {
$bills[$i]['source_id'] = '';
}
if ( ! isset($bills[$i]['paid_at'])) {
$bills[$i]['paid_at'] = '';
}
}
$this->bills = $bills;
}
}<file_sep>/app/Repo/UserRepository.php
<?php namespace BB\Repo;
use BB\Entities\User;
use Carbon\Carbon;
class UserRepository extends DBRepository
{
/**
* @var User
*/
protected $model;
/**
* @var AddressRepository
*/
private $addressRepository;
/**
* @var ProfileDataRepository
*/
private $profileDataRepository;
/**
* @var SubscriptionChargeRepository
*/
private $subscriptionChargeRepository;
public function __construct(User $model, AddressRepository $addressRepository, ProfileDataRepository $profileDataRepository, SubscriptionChargeRepository $subscriptionChargeRepository)
{
$this->model = $model;
$this->perPage = 150;
$this->addressRepository = $addressRepository;
$this->profileDataRepository = $profileDataRepository;
$this->subscriptionChargeRepository = $subscriptionChargeRepository;
}
public function getActive()
{
return $this->model->active()->get();
}
public function getBillableActive()
{
return $this->model->active()->notSpecialCase()->get();
}
public function getPaginated(array $params)
{
$model = $this->model->with('roles')->with('profile');
if ($params['showLeft']) {
$model = $model->where('status', 'left');
} else {
$model = $model->where('status', '!=', 'left');
}
if ($this->isSortable($params)) {
return $model->orderBy($params['sortBy'], $params['direction'])->simplePaginate($this->perPage);
}
return $model->simplePaginate($this->perPage);
}
/**
* Return a collection of members for public display
* @param bool $showPrivateMembers Some members don't want to listed on public pages, set to true to show everyone
* @return mixed
*/
public function getActivePublicList($showPrivateMembers = false)
{
if ($showPrivateMembers) {
return $this->model->with('profile', 'roles')->active()->where('status', '!=', 'leaving')->orderBy('given_name')->get();
} else {
return $this->model->with('profile', 'roles')->active()->where('status', '!=', 'leaving')->where('profile_private', 0)->orderBy('given_name')->get();
}
}
public function getTrustedMissingPhotos()
{
return \DB::table('users')->join('profile_data', 'users.id', '=', 'profile_data.user_id')->where('key_holder', '1')->where('active', '1')->where('profile_data.profile_photo', 0)->get();
}
/**
* Get a list of active members suitable for use in a dropdown
* @return array
*/
public function getAllAsDropdown()
{
$members = $this->getActive();
$memberDropdown = [];
foreach ($members as $member) {
$memberDropdown[$member->id] = $member->name;
}
return $memberDropdown;
}
/**
* @param array $memberData The new members details
* @param boolean $isAdminCreating Is the user making the change an admin
* @return User
*/
public function registerMember(array $memberData, $isAdminCreating)
{
if (empty($memberData['profile_photo_private'])) {
$memberData['profile_photo_private'] = false;
}
if (empty($memberData['password'])) {
unset($memberData['password']);
}
$memberData['hash'] = str_random(30);
$memberData['rules_agreed'] = $memberData['rules_agreed']? Carbon::now(): null;
$user = $this->model->create($memberData);
$this->profileDataRepository->createProfile($user->id);
$this->addressRepository->saveUserAddress($user->id, $memberData['address'], $isAdminCreating);
return $user;
}
/**
* The user has setup a payment method of some kind so they are now considered active
* This will kick off the automated member checking processes
*
* @param integer $userId
*/
public function ensureMembershipActive($userId)
{
$user = $this->getById($userId);
//user needs to have a recent sub charge and one that was paid or is due
$user->active = true;
$user->status = 'active';
$user->save();
$outstandingCharges = $this->subscriptionChargeRepository->hasOutstandingCharges($userId);
//If the user doesn't have any charges currently processing or they dont have an expiry date or are past their expiry data create a charge
if ( ! $outstandingCharges && ( ! $user->subscription_expires || $user->subscription_expires->lt(Carbon::now()))) {
//create a charge
$chargeDate = Carbon::now();
//If we are passed the end of month cutoff push the charge date forward to their actual charge date
if ((Carbon::now()->day > 28) && $user->payment_day === 1) {
$chargeDate = $chargeDate->day(1)->addMonth();
}
$this->subscriptionChargeRepository->createChargeAndBillDD($userId, $chargeDate, $user->monthly_subscription, 'due', $user->subscription_id);
}
}
/**
* @param integer $userId The ID of the user to be updated
* @param array $recordData The data to be updated
* @param boolean $isAdminUpdating Is the user making the change an admin
*/
public function updateMember($userId, array $recordData, $isAdminUpdating)
{
//If the password field hasn't been filled in unset it so it doesn't get set to a blank password
if (empty($recordData['password'])) {
unset($recordData['password']);
}
//Update the main user record
$this->update($userId, $recordData);
//Update the user address
if (isset($recordData['address']) && is_array($recordData['address'])) {
$this->addressRepository->updateUserAddress($userId, $recordData['address'], $isAdminUpdating);
}
}
/**
* The member has left, disable their account and cancel any out stand sub charge records
* The payment day is also cleared so when they start again the payment is charge happens at restart time
*
* @param $userId
*/
public function memberLeft($userId)
{
$user = $this->getById($userId);
$user->active = false;
$user->status = 'left';
$user->payment_day = '';
$user->save();
$this->subscriptionChargeRepository->cancelOutstandingCharges($userId);
}
/**
* Record the new gocardless preauth id against the user and make sure their payment method reflects this
*
* @param integer $userId
* @param string $subscriptionId
*/
public function recordGoCardlessVariableDetails($userId, $subscriptionId)
{
$user = $this->getById($userId);
if (empty($user->payment_day)) {
$user->payment_day = Carbon::now()->day;
}
$user->subscription_id = $subscriptionId;
$user->payment_method = 'gocardless-variable';
$user->save();
}
/**
* Record the fact that the user has agreed to the member induction and the rules
*
* @param $userId
*/
public function recordInductionCompleted($userId)
{
$user = $this->getById($userId);
$user->induction_completed = true;
$user->rules_agreed = $user->rules_agreed? $user->rules_agreed: Carbon::now();
$user->save();
}
public function getPendingInductionConfirmation()
{
return $this->model
->where('status', '!=', 'left')
->where('induction_completed', true)
->where('inducted_by', null)
->get();
}
}<file_sep>/app/Repo/SubscriptionChargeRepository.php
<?php namespace BB\Repo;
use BB\Entities\SubscriptionCharge;
use BB\Events\SubscriptionChargePaid;
use BB\Helpers\GoCardlessHelper;
use Carbon\Carbon;
class SubscriptionChargeRepository extends DBRepository
{
/**
* @var SubscriptionCharge
*/
protected $model;
/**
* @var PaymentRepository
*/
private $paymentRepository;
/**
* @var GoCardlessHelper
*/
private $goCardless;
public function __construct(SubscriptionCharge $model, PaymentRepository $paymentRepository, GoCardlessHelper $goCardless)
{
$this->model = $model;
$this->paymentRepository = $paymentRepository;
$this->goCardless = $goCardless;
}
/**
* @param integer $userId
* @param \DateTime $date
* @param integer $amount
* @param string $status
* @return SubscriptionCharge
*/
public function createCharge($userId, \DateTime $date, $amount = 0, $status = 'pending')
{
return $this->model->create(['charge_date' => $date, 'user_id' => $userId, 'amount' => $amount, 'status'=>$status]);
}
/**
* Create a charge and immediately bill it through the direct debit process
*
* @param integer $userId
* @param \DateTime $date
* @param integer $amount
* @param string $status
* @param string $DDAuthId
* @return SubscriptionCharge
*/
public function createChargeAndBillDD($userId, $date, $amount, $status, $DDAuthId)
{
$charge = $this->createCharge($userId, $date, $amount, $status);
$bill = $this->goCardless->newBill($DDAuthId, $amount, $this->goCardless->getNameFromReason('subscription'));
if ($bill) {
$this->paymentRepository->recordSubscriptionPayment($userId, 'gocardless-variable', $bill->id,
$bill->amount, $bill->status, $bill->gocardless_fees, $charge->id);
}
}
/**
* Does a charge already exist for the user and date
* @param $userId
* @param Carbon $date
* @return bool
*/
public function chargeExists($userId, $date)
{
if ($this->model->where('user_id', $userId)->where('charge_date', $date->format('Y-m-d'))->count() !== 0) {
return true;
}
return false;
}
/**
* Locate the next payment the user has to pay off
*
* @param $userId
* @param Carbon $paymentDate
* @return mixed
*/
public function findCharge($userId, $paymentDate = null)
{
//find any existing payment that hasn't been paid
//Subscription payments will always be used to pay of bills
return $this->model->where('user_id', $userId)->whereIn('status', ['pending', 'due'])->orderBy('charge_date', 'ASC')->first();
}
/**
* @param integer $chargeId
* @param $paymentDate
* @param null|integer $amount
*/
public function markChargeAsPaid($chargeId, $paymentDate = null, $amount = null)
{
if (is_null($paymentDate)) {
$paymentDate = new Carbon();
}
$subCharge = $this->getById($chargeId);
$subCharge->payment_date = $paymentDate;
$subCharge->status = 'paid';
if ($amount) {
$subCharge->amount = $amount;
}
$subCharge->save();
event(new SubscriptionChargePaid($subCharge));
}
/**
* @param $chargeId
*/
public function markChargeAsProcessing($chargeId)
{
$subCharge = $this->getById($chargeId);
$subCharge->status = 'processing';
$subCharge->save();
\Event::fire('sub-charge.processing', array($chargeId, $subCharge->user_id, $subCharge->charge_date, $subCharge->amount));
}
/**
* If a payment has failed update the sub charge to reflect this
*
* @param $chargeId
*/
public function paymentFailed($chargeId)
{
$subCharge = $this->getById($chargeId);
//If the charge has already been cancelled dont touch it
if ($subCharge->status != 'cancelled') {
$subCharge->payment_date = null;
$subCharge->status = 'due';
$subCharge->amount = 0;
$subCharge->save();
} else {
\Log::debug('Sub charge not updated after payment failure, already cancelled. Charge ID: ' . $chargeId);
}
\Event::fire('sub-charge.payment-failed', array($chargeId, $subCharge->user_id, $subCharge->charge_date, $subCharge->amount));
}
/**
* Return a paginated list of member payments
*
* @param integer $userId
* @return mixed
*/
public function getMemberChargesPaginated($userId)
{
return $this->model->where('user_id', $userId)->orderBy('charge_date', 'DESC')->paginate();
}
/**
* Return a paginated list of member payments
*
* @param integer $userId
* @return \Illuminate\Database\Eloquent\Collection
*/
public function getMemberCharges($userId)
{
return $this->model->where('user_id', $userId)->orderBy('charge_date', 'DESC')->get();
}
/**
* Return a members most recent paid up subscription charge record
*
* @param $userId
* @return SubscriptionCharge
*/
public function getMembersLatestPaidCharge($userId)
{
return $this->model->where('user_id', $userId)->where('status', 'paid')->orderBy('charge_date', 'DESC')->first();
}
/**
* Return a paginated list of member payments
*
* @return mixed
*/
public function getChargesPaginated()
{
return $this->model->orderBy('charge_date', 'DESC')->paginate();
}
/**
* Get all the charges which are due payment
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public function getDue()
{
return $this->model->where('status', 'due')->get();
}
/**
* Get charges that are newly created and pending
*
* @return mixed
*/
public function getPending()
{
return $this->model->where('status', 'pending')->get();
}
/**
* Update a charge and mark it as due
*
* @param $chargeId
*/
public function setDue($chargeId)
{
$subCharge = $this->getById($chargeId);
$subCharge->status = 'due';
$subCharge->save();
}
/**
* Cancel all outstanding (due and pending) charges for a user
* Used when leaving
*
* @param $userId
*/
public function cancelOutstandingCharges($userId)
{
$this->model->where('user_id', $userId)->whereIn('status', ['pending', 'due'])->update(['status'=>'cancelled']);
}
/**
* Does the user have any active or outstanding charges
*
* @param integer $userId
* @return bool
*/
public function hasOutstandingCharges($userId)
{
return ($this->model->where('user_id', $userId)->whereIn('status', ['pending', 'due', 'processing'])->count() > 0);
}
/**
* @param integer $chargeId
* @param integer $newAmount
*/
public function updateAmount($chargeId, $newAmount)
{
$subCharge = $this->getById($chargeId);
$subCharge->amount = $newAmount;
$subCharge->save();
}
}<file_sep>/app/Presenters/PaymentPresenter.php
<?php namespace BB\Presenters;
use Laracasts\Presenter\Presenter;
class PaymentPresenter extends Presenter
{
public function reason()
{
switch ($this->entity->reason) {
case 'subscription':
return 'Subscription';
case 'unknown':
return 'Unknown';
case 'induction':
return 'Equipment Access Fee';
case 'door-key':
return 'Key Deposit';
case 'storage-box':
return 'Storage Box Deposit';
case 'balance':
return 'Balance Top Up';
case 'equipment-fee':
return 'Equipment Costs';
case 'withdrawal':
return 'Withdrawal';
case 'consumables':
return 'Consumables (' . $this->entity->reference . ')';
case 'transfer':
return 'Transfer (to user:' . $this->entity->reference . ')';
case 'donation':
return 'Donation';
default:
return $this->entity->reason;
}
}
public function status()
{
switch ($this->entity->status) {
case 'pending':
return 'Pending Confirmation';
case 'cancelled':
return 'Cancelled';
case 'paid':
case 'withdrawn':
return 'Paid';
default:
return $this->entity->status;
}
}
public function date()
{
return $this->entity->created_at->toFormattedDateString();
}
public function method()
{
switch ($this->entity->source) {
case 'gocardless':
case 'gocardless-variable':
return 'Direct Debit';
case 'stripe':
return 'Credit/Debit Card';
case 'paypal':
return 'PayPal';
case 'standing-order':
return 'Standing Order';
case 'manual':
return 'Manual';
case 'cash':
return 'Cash' . ($this->entity->source_id? ' (' . $this->entity->source_id . ')':'');
case 'other':
return 'Other';
case 'balance':
return 'BB Balance';
case 'reimbursement':
return 'Reimbursement';
case 'transfer':
return 'Transfer (from user:' . $this->entity->reference . ')';
default:
return $this->entity->source;
}
}
public function amount()
{
return '£' . $this->entity->amount;
}
public function balanceAmount()
{
if ($this->entity->source == 'balance') {
return '-£' . $this->entity->amount;
} elseif ($this->entity->reason == 'balance') {
return '£' . $this->entity->amount;
}
}
public function balanceRowClass()
{
if ($this->entity->source == 'balance') {
return 'danger';
} elseif ($this->entity->reason == 'balance') {
return 'success';
}
}
} <file_sep>/app/Console/Commands/CreateTodaysSubCharges.php
<?php namespace BB\Console\Commands;
use Carbon\Carbon;
use Illuminate\Console\Command;
class CreateTodaysSubCharges extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $signature = 'bb:create-todays-sub-charges {dayOffset=3}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create all the subscription changes for today';
/**
* @var \BB\Services\MemberSubscriptionCharges
*/
private $subscriptionChargeService;
/**
* Create a new command instance.
*
*/
public function __construct()
{
parent::__construct();
$this->subscriptionChargeService = \App::make('\BB\Services\MemberSubscriptionCharges');
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$dayOffset = $this->argument('dayOffset');
$targetDate = Carbon::now()->addDays($dayOffset);
$this->info("Generating charges for " . $targetDate);
$this->subscriptionChargeService->createSubscriptionCharges($targetDate);
//in case yesterdays process failed we will rerun the past seven days, this should pickup and stragglers
$this->subscriptionChargeService->createSubscriptionCharges($targetDate->subDay()); //-1 day
$this->subscriptionChargeService->createSubscriptionCharges($targetDate->subDay()); //-2 days
$this->subscriptionChargeService->createSubscriptionCharges($targetDate->subDay()); //-3 days
$this->subscriptionChargeService->createSubscriptionCharges($targetDate->subDay()); //-4 days
$this->subscriptionChargeService->createSubscriptionCharges($targetDate->subDay()); //-5 days
$this->subscriptionChargeService->createSubscriptionCharges($targetDate->subDay()); //-6 days
$this->subscriptionChargeService->createSubscriptionCharges($targetDate->subDay()); //-7 days
}
}
<file_sep>/app/Http/Controllers/ACS/StatusController.php
<?php
namespace BB\Http\Controllers\ACS;
use BB\Entities\KeyFob;
use BB\Exceptions\ValidationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use BB\Http\Requests;
use BB\Http\Controllers\Controller;
class StatusController extends Controller
{
/**
* Display the specified resource.
*
* @param string $tagId
*
* @return \Illuminate\Http\Response
* @throws ValidationException
*
* @SWG\Get(
* path="/acs/status/{tagId}",
* tags={"acs"},
* description="Get information about a specific tag and its user",
* consumes={"application/json"},
* @SWG\Parameter(name="tagId", in="path", type="string"),
* @SWG\Response(response="200", description="Tag found"),
* @SWG\Response(response="404", description="Tag not found"),
* security={{"api_key": {}}}
* )
*
*/
public function show($tagId)
{
try {
$keyFob = KeyFob::lookup($tagId);
} catch (\Exception $e) {
$oldTagId = substr('BB' . $tagId, 0, 12);
try {
$keyFob = KeyFob::lookup($oldTagId);
} catch (\Exception $e) {
//The ids coming in will have no checksum (last 2 digits) and the first digit will be incorrect
//Remove the first character
$tagId = substr($tagId, 1);
try {
$keyFob = KeyFob::lookupPartialTag($tagId);
} catch (\Exception $e) {
throw new ModelNotFoundException('Key fob ID not found');
}
}
}
return ['user' => [
'id' => $keyFob->user->id,
'name' => $keyFob->user->name,
'status' => $keyFob->user->status,
'active' => $keyFob->user->active,
'key_holder' => $keyFob->user->key_holder,
'cash_balance' => $keyFob->user->cash_balance,
'profile_private' => $keyFob->user->profile_private,
]];
}
}
<file_sep>/app/Http/Controllers/CCTVController.php
<?php
namespace BB\Http\Controllers;
use BB\Http\Controllers\Controller;
class CCTVController extends Controller
{
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
$s3 = AWS::get('s3');
$s3Bucket = 'buildbrighton-bbms';
if (Request::hasFile('image')) {
$file = Request::file('image');
$event = Request::get('textevent');
$time = Request::get('time');
$fileData = Image::make($file)->encode('jpg', 80);
$date = Carbon::createFromFormat('YmdHis', $event);
$folderName = $date->hour . ':' . $date->minute . ':' . $date->second;
try {
$newFilename = \App::environment() . '/cctv/' . $date->year . '/' . $date->month . '/' . $date->day . '/' . $folderName . '/' . $time . '.jpg';
$s3->putObject(array(
'Bucket' => $s3Bucket,
'Key' => $newFilename,
//'Body' => file_get_contents($file),
'Body' => $fileData,
'ACL' => 'public-read',
'ContentType' => 'image/jpg',
'ServerSideEncryption' => 'AES256',
));
} catch(\Exception $e) {
\Log::exception($e);
}
//Log::debug('Image saved :https://s3-eu-west-1.amazonaws.com/buildbrighton-bbms/'.$newFilename);
}
if (Request::get('eventend') == 'true') {
$event = Request::get('textevent');
$date = Carbon::createFromFormat('YmdHis', $event);
$folderName = $date->hour . ':' . $date->minute . ':' . $date->second;
$iterator = $s3->getIterator(
'ListObjects',
array(
'Bucket' => $s3Bucket,
'Prefix' => \App::environment() . '/cctv/' . $date->year . '/' . $date->month . '/' . $date->day . '/' . $folderName,
//'Prefix' => 'production/camera-photos/20150410222028',
)
);
$images = [];
$imageDurations = [];
foreach ($iterator as $object) {
$images[] = 'https://s3-eu-west-1.amazonaws.com/buildbrighton-bbms/' . $object['Key'];
$imageDurations[] = 35;
}
if (count($images) <= 2) {
//only two images, probably two bad frames
//delete them
foreach ($iterator as $object) {
Log::debug("Deleting small event image " . $object['Key']);
$s3->deleteObject([
'Bucket' => $s3Bucket,
'Key' => $object['Key'],
]);
}
return;
}
$gc = new GifCreator();
$gc->create($images, $imageDurations, 0);
$gifBinary = $gc->getGif();
//Delete the individual frames now we have the gif
foreach ($iterator as $object) {
//Log::debug("Processed gif, deleting frame, ".$object['Key']);
$s3->deleteObject([
'Bucket' => $s3Bucket,
'Key' => $object['Key'],
]);
}
//Save the gif
$newFilename = \App::environment() . '/cctv/' . $date->year . '/' . $date->month . '/' . $date->day . '/' . $folderName . '.gif';
$s3->putObject(
array(
'Bucket' => $s3Bucket,
'Key' => $newFilename,
'Body' => $gifBinary,
'ACL' => 'public-read',
'ContentType' => 'image/gif',
'ServerSideEncryption' => 'AES256',
)
);
//Log::debug('Event Gif generated :https://s3-eu-west-1.amazonaws.com/buildbrighton-bbms/'.$newFilename);
\Slack::to("#cctv")->attach(['image_url'=>'https://s3-eu-west-1.amazonaws.com/buildbrighton-bbms/' . $newFilename, 'color'=>'warning'])->send('Movement detected');
}
}
}
<file_sep>/app/Http/Controllers/ACS/ActivityController.php
<?php
namespace BB\Http\Controllers\ACS;
use BB\Events\MemberActivity;
use BB\Repo\ACSNodeRepository;
use BB\Repo\EquipmentLogRepository;
use BB\Services\KeyFobAccess;
use Illuminate\Http\Request;
use BB\Http\Requests;
use BB\Http\Controllers\Controller;
use Swagger\Annotations as SWG;
class ActivityController extends Controller
{
/**
* @var ACSNodeRepository
*/
private $ACSNodeRepository;
/**
* @var EquipmentLogRepository
*/
private $equipmentLogRepository;
/**
* @var KeyFobAccess
*/
private $fobAccess;
/**
* NodeController constructor.
*
* @param ACSNodeRepository $ACSNodeRepository
*/
public function __construct(ACSNodeRepository $ACSNodeRepository, EquipmentLogRepository $equipmentLogRepository, KeyFobAccess $fobAccess)
{
$this->ACSNodeRepository = $ACSNodeRepository;
$this->equipmentLogRepository = $equipmentLogRepository;
$this->fobAccess = $fobAccess;
}
/**
* Record the start of a new session
*
* @return \Illuminate\Http\Response
*
* @SWG\Post(
* path="/acs/activity",
* tags={"activity"},
* description="Record the start of a period of activity, e.g. someone signing into the laser cutter",
* @SWG\Parameter(name="activity", in="body", required=true, @SWG\Schema(ref="#/definitions/Activity")),
* @SWG\Response(response="201", description="Activity started, the body will contain the new activityId"),
* @SWG\Response(response="404", description="Key fob not found"),
* security={{"api_key": {}}}
* )
*/
public function store(Request $request)
{
$activityRequest = new Requests\ACS\Activity($request);
$keyFob = $this->fobAccess->extendedKeyFobLookup($activityRequest->getTagId());
$activityId = $this->equipmentLogRepository->recordStartCloseExisting($keyFob->user->id, $keyFob->id, $activityRequest->getDevice());
event(new MemberActivity($keyFob, $activityRequest->getDevice()));
return response()->json([
'activityId' => $activityId,
'user' => [
'id' => $keyFob->user->id,
'name' => $keyFob->user->name,
'status' => $keyFob->user->status,
'active' => $keyFob->user->active,
'key_holder' => $keyFob->user->key_holder,
'cash_balance' => $keyFob->user->cash_balance,
'profile_private' => $keyFob->user->profile_private,
]
], 201);
}
/**
* Update an ongoing activity
*
* @return \Illuminate\Http\Response
*
* @SWG\Put(
* path="/acs/activity/{activityId}",
* tags={"activity"},
* description="Record a heartbeat message for a period of activity, used to ensure activity periods are correctly recorded",
* @SWG\Parameter(name="activityId", in="path", type="string", required=true),
* @SWG\Response(response="200", description="Activity Heartbeat recorded"),
* security={{"api_key": {}}}
* )
*/
public function update(Request $request, $activityId)
{
$keyFob = $this->fobAccess->extendedKeyFobLookup($request->get('tagId'));
$this->equipmentLogRepository->recordActivity($activityId);
return response()->json([], 200);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*
* @SWG\Delete(
* path="/acs/activity/{activityId}",
* tags={"activity"},
* description="End a period of an activity",
* @SWG\Parameter(name="activityId", in="path", type="string", required=true),
* @SWG\Response(response="204", description="Activity ended/deleted"),
* @SWG\Response(response="400", description="Session invalid"),
* security={{"api_key": {}}}
* )
*/
public function destroy(Request $request, $activityId)
{
$keyFob = $this->fobAccess->extendedKeyFobLookup($request->get('tagId'));
$this->equipmentLogRepository->endSession($activityId);
return response()->json([], 204);
}
}
<file_sep>/app/Http/Controllers/GoCardlessPaymentController.php
<?php namespace BB\Http\Controllers;
use BB\Entities\User;
class GoCardlessPaymentController extends Controller
{
/**
* @var \BB\Repo\PaymentRepository
*/
private $paymentRepository;
/**
* @var \BB\Helpers\GoCardlessHelper
*/
private $goCardless;
function __construct(\BB\Repo\PaymentRepository $paymentRepository, \BB\Helpers\GoCardlessHelper $goCardless)
{
$this->paymentRepository = $paymentRepository;
$this->middleware('role:member', array('only' => ['create', 'store']));
$this->goCardless = $goCardless;
}
/**
* Main entry point for all gocardless payments - not subscriptions
* @param $userId
* @return mixed
* @throws \BB\Exceptions\AuthenticationException
*/
public function create($userId)
{
$user = User::findWithPermission($userId);
$requestData = \Request::only(['reason', 'amount', 'return_path']);
$reason = $requestData['reason'];
$amount = ($requestData['amount'] * 1) / 100;
$returnPath = $requestData['return_path'];
$ref = $this->getReference($reason);
if ($user->payment_method == 'gocardless-variable') {
return $this->handleBill($amount, $reason, $user, $ref, $returnPath);
} elseif ($user->payment_method == 'gocardless') {
return $this->ddMigratePrompt($returnPath);
} else {
return $this->handleManualBill($amount, $reason, $user, $ref, $returnPath);
}
}
/**
* Processes the return for old gocardless payments
*
* @param $userId
* @return \Illuminate\Http\RedirectResponse
* @throws \BB\Exceptions\AuthenticationException
*/
public function handleManualReturn($userId)
{
$user = User::findWithPermission($userId);
$confirm_params = array(
'resource_id' => $_GET['resource_id'],
'resource_type' => $_GET['resource_type'],
'resource_uri' => $_GET['resource_uri'],
'signature' => $_GET['signature']
);
// State is optional
if (isset($_GET['state'])) {
$confirm_params['state'] = $_GET['state'];
}
//Get the details, reason, reference and return url
$details = explode(':', \Input::get('state'));
$reason = 'unknown';
$ref = null;
$returnPath = route('account.show', [$user->id], false);
if (is_array($details)) {
if (isset($details[0])) {
$reason = $details[0];
}
if (isset($details[1])) {
$ref = $details[1];
}
if (isset($details[2])) {
$returnPath = $details[2];
}
}
//Confirm the resource
try {
$confirmed_resource = $this->goCardless->confirmResource($confirm_params);
} catch (\Exception $e) {
\Notification::error($e->getMessage());
return \Redirect::to($returnPath);
}
//Store the payment
$fee = ($confirmed_resource->amount - $confirmed_resource->amount_minus_fees);
$paymentSourceId = $confirmed_resource->id;
$amount = $confirmed_resource->amount;
$status = $confirmed_resource->status;
//The record payment process will make the necessary record updates
$this->paymentRepository->recordPayment($reason, $userId, 'gocardless', $paymentSourceId, $amount, $status, $fee, $ref);
\Notification::success("Payment made");
return \Redirect::to($returnPath);
}
/**
* Process a manual gocardless payment
*
* @param $amount
* @param $reason
* @param User $user
* @param $ref
* @param $returnPath
* @return mixed
* @throws \BB\Exceptions\NotImplementedException
*/
private function handleManualBill($amount, $reason, $user, $ref, $returnPath)
{
$payment_details = array(
'amount' => $amount,
'name' => $this->getName($reason, $user->id),
'description' => $this->getDescription($reason),
'redirect_uri' => route('account.payment.gocardless.manual-return', [$user->id]),
'user' => [
'first_name' => $user->given_name,
'last_name' => $user->family_name,
'billing_address1' => $user->address_line_1,
'billing_address2' => $user->address_line_2,
'billing_town' => $user->address_line_3,
'billing_postcode' => $user->address_postcode,
'country_code' => 'GB'
],
'state' => $reason . ':' . $ref . ':' . $returnPath
);
$redirectUrl = $this->goCardless->newBillUrl($payment_details);
if (\Request::wantsJson()) {
return \Response::json(['url' => $redirectUrl], 303);
}
return \Redirect::to($redirectUrl);
}
private function ddMigratePrompt($returnPath)
{
if (\Request::wantsJson()) {
return \Response::json(['error' => 'Please visit the "Your Membership" page and migrate your Direct Debit first, then return and make the payment'], 400);
}
\Notification::error("Please visit the \"Your Membership\" page and migrate your Direct Debit first, then return and make the payment");
return \Redirect::to($returnPath);
}
/**
* Process a direct debit payment when we have a preauth
*
* @param $amount
* @param $reason
* @param User $user
* @param $ref
* @param $returnPath
* @return mixed
*/
private function handleBill($amount, $reason, $user, $ref, $returnPath)
{
$bill = $this->goCardless->newBill($user->subscription_id, $amount, $this->goCardless->getNameFromReason($reason));
if ($bill) {
//Store the payment
$fee = ($bill->amount - $bill->amount_minus_fees);
$paymentSourceId = $bill->id;
$amount = $bill->amount;
$status = $bill->status;
//The record payment process will make the necessary record updates
$this->paymentRepository->recordPayment($reason, $user->id, 'gocardless-variable', $paymentSourceId, $amount, $status, $fee, $ref);
if (\Request::wantsJson()) {
return \Response::json(['message' => 'The payment was submitted successfully']);
}
\Notification::success("The payment was submitted successfully");
} else {
//something went wrong - we still have the pre auth though
if (\Request::wantsJson()) {
return \Response::json(['error' => 'There was a problem charging your account'], 400);
}
\Notification::error("There was a problem charging your account");
}
return \Redirect::to($returnPath);
}
private function getDescription($reason)
{
if ($reason == 'subscription') {
return "Monthly Subscription Fee - Manual";
} elseif ($reason == 'induction') {
return strtoupper(\Input::get('induction_key')) . " Induction Fee";
} elseif ($reason == 'door-key') {
return "Door Key Deposit";
} elseif ($reason == 'storage-box') {
return "Storage Box Deposit";
} elseif ($reason == 'balance') {
return "BB Credit Payment";
} else {
throw new \BB\Exceptions\NotImplementedException();
}
}
private function getName($reason, $userId)
{
if ($reason == 'subscription') {
return strtoupper("BBSUB" . $userId . ":MANUAL");
} elseif ($reason == 'induction') {
return strtoupper("BBINDUCTION" . $userId . ":" . \Request::get('induction_key'));
} elseif ($reason == 'door-key') {
return strtoupper("BBDOORKEY" . $userId);
} elseif ($reason == 'storage-box') {
return strtoupper("BBSTORAGEBOX" . $userId);
} elseif ($reason == 'balance') {
return strtoupper("BBBALANCE" . $userId);
} else {
throw new \BB\Exceptions\NotImplementedException();
}
}
private function getReference($reason)
{
if ($reason == 'induction') {
return \Request::get('ref');
} elseif ($reason == 'balance') {
return \Request::get('reference');
}
return false;
}
}
<file_sep>/app/Services/KeyFobAccess.php
<?php namespace BB\Services;
use BB\Entities\KeyFob;
use BB\Entities\User;
use BB\Events\MemberActivity;
use BB\Exceptions\ValidationException;
use BB\Repo\ActivityRepository;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class KeyFobAccess
{
/**
* The key fob string
* @var string
*/
protected $keyFobId;
/**
* The key fob record
* @var KeyFob
*/
protected $keyFob;
/**
* The key for the selected device
* @var string
*/
protected $deviceKey;
/**
* The selected device record
* The device that's being acted apon
* @var
*/
protected $device;
/**
* The action of the current session
* @var string
*/
protected $action;
/**
* @var User
*/
protected $user;
/**
* @var ActivityRepository
*/
protected $activityRepository;
protected $messageDelayed = false;
protected $memberName;
/**
* @var Carbon
*/
protected $time;
public function __construct(ActivityRepository $activityRepository)
{
$this->activityRepository = $activityRepository;
}
/**
* @param string $keyFobId
*/
public function setKeyFobId($keyFobId)
{
$this->keyFobId = $keyFobId;
}
/**
* @param string $deviceKey
*/
public function setDeviceKey($deviceKey)
{
$this->deviceKey = $deviceKey;
}
/**
* @param string $action
*/
public function setAction($action)
{
$this->action = $action;
}
/**
* @return string
*/
public function getKeyFobId()
{
return $this->keyFobId;
}
/**
* @return
*/
public function getKeyFob()
{
return $this->keyFob;
}
/**
* @return string
*/
public function getDeviceKey()
{
return $this->deviceKey;
}
/**
* @return string
*/
public function getAction()
{
return $this->action;
}
/**
* @return User
*/
public function getUser()
{
return $this->user;
}
/**
* Check a fob id is valid for door entry and return the member if it is
* @param $keyId
* @param string $doorName
* @param $time
* @return \User
* @throws ValidationException
*/
public function verifyForEntry($keyId, $doorName, $time)
{
$this->keyFob = $this->lookupKeyFob($keyId);
$this->setAccessTime($time);
//Make sure the user is active
$this->user = $this->keyFob->user;
if ( ! $this->user || ! $this->user->active) {
$this->logFailure();
throw new ValidationException('Not a member');
}
if ( ! $this->user->trusted) {
$this->logFailure();
throw new ValidationException('Not a keyholder');
}
if ( ! $this->user->key_holder) {
$this->logFailure();
throw new ValidationException('Not a keyholder');
}
if ( ! ($this->user->profile->profile_photo || $this->user->profile->profile_photo_on_wall)) {
$this->logFailure();
throw new ValidationException('Member not trusted');
}
$this->memberName = $this->user->given_name;
//Fetch any commands that need to be returned to the device
return $this->keyFob->user;
}
public function lookupKeyFob($keyId)
{
try {
$keyFob = KeyFob::lookup($keyId);
return $keyFob;
} catch (\Exception $e) {
$keyId = substr('BB' . $keyId, 0, 12);
try {
$keyFob = KeyFob::lookup($keyId);
} catch (\Exception $e) {
throw new ValidationException('Key fob ID not valid');
}
return $keyFob;
}
}
/**
* @param $keyId
*
* @return KeyFob
*/
public function extendedKeyFobLookup($keyId)
{
try {
$keyFob = KeyFob::lookup($keyId);
} catch (\Exception $e) {
$oldTagId = substr('BB' . $keyId, 0, 12);
try {
$keyFob = KeyFob::lookup($oldTagId);
} catch (\Exception $e) {
//The ids coming in will have no checksum (last 2 digits) and the first digit will be incorrect
//Remove the first character
$keyId = substr($keyId, 1);
try {
$keyFob = KeyFob::lookupPartialTag($keyId);
} catch (\Exception $e) {
throw new ModelNotFoundException('Key fob ID not found');
}
}
}
return $keyFob;
}
public function logFailure()
{
$log = [];
$log['key_fob_id'] = $this->keyFob->id;
$log['user_id'] = $this->user->id;
$log['service'] = 'main-door';
$log['delayed'] = $this->messageDelayed;
$log['response'] = 402;
$log['created_at'] = $this->time;
$this->activityRepository->logAccessAttempt($log);
}
public function logSuccess()
{
event(new MemberActivity($this->keyFob, 'main-door', $this->time, $this->messageDelayed));
/*
$activity = $this->activityRepository->recordMemberActivity($this->user->id, $this->keyFob->id, 'main-door', $this->time);
if ($this->messageDelayed) {
$activity->delayed = true;
$activity->save();
}
*/
}
/**
* @return mixed
*/
public function getMemberName()
{
return $this->memberName;
}
/**
* Set the time to a specific timestamp - the new entry system will be passing a local time with the requests
* @param null $time
*/
protected function setAccessTime($time = null)
{
if ( ! empty($time)) {
$this->time = Carbon::createFromTimestamp($time);
} else {
$this->time = Carbon::now();
}
}
} <file_sep>/app/Validators/ACSValidator.php
<?php namespace BB\Validators;
class ACSValidator extends FormValidator
{
protected $rules = [
'device' => 'required|max:25|exists:acs_nodes,device_id',
'service' => 'required|in:entry,usage,consumable,shop,status,device-scanner,sensor',
'message' => 'required|in:boot,heartbeat,lookup,start,stop,charge,error,update',
'tag' => 'max:15',
'time' => 'integer|date_format:U',
'signature' => '',
'nonce' => 'max:12',
];
}
<file_sep>/readme.md
[](https://travis-ci.org/ArthurGuy/BBMembershipSystem)
[](https://codeclimate.com/github/ArthurGuy/BBMembershipSystem)
[](https://scrutinizer-ci.com/g/ArthurGuy/BBMembershipSystem)
BBMS (Build Brighton Member System)
====================
The Build Brighton membership management system
New members can join and create accounts, payments are tracked and managed through the system and GoCardless
###Features
* Member signup form which collects full name and address, emergency contact and profile photo.
* Direct Debit setup and payment collection through GoCardless
* Regular monthly direct debit payment runs for each user
* PayPal IPN notifications are also received and used to extend member subscriptions.
* The ability for the user to edit all their details allowing for self management
* Various user statuses to cater for active members, members who have left or been banned as well as tracking founders and honorary members
* Handling of the induction/equipment training procedures and collection of payments.
* Tracking of who trains who
* Member grid to see who is a member
* The ability for members to cancel their subscription and leave
* Collect deposit payments for door keys
* Manage member storage box assignments and deposit payments
* RFID door entry control and tracking
* Member credit system for paying for various services
* Member credit topup using direct debit payments and credit/debit card payments
* Member role system for managing delegated duties
* RFID access control for equipment and usage logging
* Auto billing for equipment usage
* Proposal system for member voting
* Equipment/asset management
* Member expense reimbursement
###Member Statuses
There are a variety of member statuses which are used for various scenarios.
* Setting Up - just signed up, no subscription setup, no access to space
* Active
* Suspended - missed payment - dd is still active but the member doesn't have access to the workshop
* Leaving - The user has said they are leaving or they were in a payment warning state
* Left - Leaving users move here once their last payment expires.
###Other Maker spaces
This system can be used with only minor modifications by other spaces.<br />
The Build Brighton naming is hardcoded into the pages and pieces of text will need to be altered.<br />
It has been designed to work primarily with GoCardless but the PayPal integration is OK and would be good enough on its own.<br />
The system also has support for scanning and processing payments from bank statements
###Seting It Up
The system is build on the Laravel 5 framework so familiarity with that would help.
A .env file needs to be setup, please take a look at the example one for the options that are needed.
This file can be renamed by removing the .example from the end.
Composer needs to be available and the install command run to load the required assets.
The storage directory needs to be writable.
Some of the config options wont be needed.<br />
AWS is used for file storage although a lcal option can be specified.<br />
The system is built for a MySQL DB but a similar system will work<br />
GoCardless as above<br />
MailGun is completely optional<br />
The encryption key is essential<br /><file_sep>/app/Entities/User.php
<?php namespace BB\Entities;
use BB\Exceptions\AuthenticationException;
use BB\Traits\UserRoleTrait;
use Carbon\Carbon;
use DateTime;
use Illuminate\Database\Eloquent\Model;
use Laracasts\Presenter\PresentableTrait;
use Auth;
use Hash;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
/**
* Class User
*
* @property integer $id
* @property string $email
* @property string $slack_username
* @property string $name
* @property string $given_name
* @property string $family_name
* @property string $hash
* @property bool $active
* @property bool $key_holder
* @property bool $trusted
* @property bool $banned
* @property bool $email_verified
* @property bool $induction_completed
* @property integer $inducted_by
* @property integer $payment_day
* @property string $status
* @property string $payment_method
* @property string $subscription_id
* @property Carbon $subscription_expires
* @property Carbon $banned_date
* @property string $phone
* @property integer $storage_box_payment_id
* @property ProfileData $profile
* @package BB\Entities
*/
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use UserRoleTrait, PresentableTrait, Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
protected $auditFields = array('induction_completed', 'trusted', 'key_holder');
protected $presenter = 'BB\Presenters\UserPresenter';
/**
* Fillable fields
*
* @var array
*/
protected $fillable = [
'given_name', 'family_name', 'email', 'secondary_email', 'password', 'emergency_contact', 'phone',
'monthly_subscription', 'profile_private', 'hash', 'rules_agreed',
'key_holder', 'key_deposit_payment_id', 'trusted', 'induction_completed', 'payment_method', 'active', 'status'
];
protected $attributes = [
'status' => 'setting-up',
'active' => 0,
'key_holder' => 0,
'trusted' => 0,
'email_verified' => 0,
'founder' => 0,
'induction_completed' => 0,
'payment_day' => 0,
'profile_private' => 0,
'cash_balance' => 0,
];
public function getDates()
{
return array('created_at', 'updated_at', 'subscription_expires', 'banned_date', 'rules_agreed');
}
public static function statuses()
{
return [
'setting-up' => 'Setting Up',
'active' => 'Active',
'payment-warning' => 'Payment Warning',
'suspended' => 'Suspended',
'leaving' => 'Leaving',
'on-hold' => 'On Hold',
'left' => 'Left',
'honorary' => 'Honorary'
];
}
/*
|--------------------------------------------------------------------------
| Relationships
|--------------------------------------------------------------------------
|
| The connections between this model and others
|
*/
public function payments()
{
return $this->hasMany('\BB\Entities\Payment')->orderBy('created_at', 'desc');
}
public function inductions()
{
return $this->hasMany('\BB\Entities\Induction');
}
public function keyFob()
{
return $this->hasMany('\BB\Entities\KeyFob')->where('active', true)->first();
}
public function profile()
{
return $this->hasOne('\BB\Entities\ProfileData');
}
public function address()
{
return $this->hasOne('\BB\Entities\Address')->orderBy('approved', 'asc');
}
public function notifications()
{
return $this->hasMany(Notification::class)->orderBy('created_at', 'desc');
}
/*
|--------------------------------------------------------------------------
| Attribute Getters and Setters and Model Extensions
|--------------------------------------------------------------------------
|
| Useful properties and methods to have on a user model
|
*/
public function getNameAttribute()
{
return $this->attributes['given_name'] . ' ' . $this->attributes['family_name'];
}
public function setPasswordAttribute($password)
{
$this->attributes['password'] = <PASSWORD>::make($password);
}
public function setPaymentDayAttribute($value)
{
//Ensure the payment date will always exist on any month payment_date
if ($value > 28) {
$value = 1;
}
$this->attributes['payment_day'] = $value;
}
/**
* Can the user see protected member photos?
* Only available to active members
*
* @return bool
*/
public function shouldMemberSeeProtectedPhoto()
{
switch ($this->attributes['status']) {
case 'active':
case 'payment-warning':
case 'honorary':
return true;
default:
return false;
}
}
/**
* Is the user on a payment method that allows their subscription amount to be changed
*
* @return bool
*/
public function canMemberChangeSubAmount()
{
return in_array($this->attributes['payment_method'], ['gocardless-variable', 'balance']);
}
/**
* Is this user considered a keyholder - can they use the space on their own
* This may have been replaced by a repo method which checks the photo as well
*
* @return bool
*/
public function keyholderStatus()
{
return ($this->active && $this->key_holder && $this->trusted);
}
/**
* Is the user part of the admin group
*
* @return bool
*/
public function isAdmin()
{
return Auth::user()->hasRole('admin');
}
/**
* Should GoCardless be promoted to the user
*
* @return bool
*/
public function promoteGoCardless()
{
return (($this->payment_method != 'balance' && $this->payment_method != 'gocardless' && $this->payment_method != 'gocardless-variable') && ($this->status == 'active'));
}
/**
* Should we be promoting the new variable gocardless to users?
*
* @return bool
*/
public function promoteVariableGoCardless()
{
return (($this->status == 'active') && ($this->payment_method == 'gocardless'));
}
/**
* Is the user eligible for a key?
*
* @return bool
*/
public function promoteGetAKey()
{
return ($this->trusted && ! $this->key_holder && ($this->status == 'active'));
}
/**
* Get an array of alerts for the user
*
* @return array
*/
public function getAlerts()
{
$alerts = [];
if ( ! $this->profile->profile_photo && ! $this->profile->new_profile_photo) {
$alerts[] = 'missing-profile-photo';
}
if (empty($this->phone)) {
$alerts[] = 'missing-phone';
}
return $alerts;
}
/**
* @return bool
*/
public function isBanned()
{
return $this->banned;
}
/**
* @return bool
*/
public function isSuspended()
{
return ($this->status == 'suspended');
}
/**
* @return bool
*/
public function isInducted()
{
return $this->induction_completed && $this->inducted_by;
}
public function inductedBy()
{
return User::findOrFail($this->inducted_by);
}
/*
|--------------------------------------------------------------------------
| Scopes
|--------------------------------------------------------------------------
*/
public function scopeActive($query)
{
return $query->whereActive(true);
}
public function scopeNotSpecialCase($query)
{
return $query->where('status', '!=', 'honorary');
}
public function scopeLeaving($query)
{
return $query->where('status', '=', 'leaving');
}
public function scopePaymentWarning($query)
{
return $query->where('status', '=', 'payment-warning');
}
public function scopeSuspended($query)
{
return $query->where('status', '=', 'suspended');
}
/*
|--------------------------------------------------------------------------
| Methods
|--------------------------------------------------------------------------
*/
/**
* @param $paymentMethod
* @param $paymentDay
* @deprecated
*/
public function updateSubscription($paymentMethod, $paymentDay)
{
if ($paymentDay > 28) {
$paymentDay = 1;
}
$this->attributes['payment_method'] = $paymentMethod;
$this->attributes['payment_day'] = $paymentDay;
$this->save();
}
/**
* @param $amount
* @deprecated
*/
public function updateSubAmount($amount)
{
$this->attributes['monthly_subscription'] = $amount;
$this->save();
}
/**
* @deprecated
*/
public function cancelSubscription()
{
$this->payment_method = '';
$this->subscription_id = '';
$this->payment_day = '';
$this->status = 'leaving';
$this->save();
}
/**
* @deprecated
*/
public function setLeaving()
{
$this->status = 'leaving';
$this->save();
}
/**
* @deprecated
*/
public function setSuspended()
{
$this->status = 'suspended';
$this->active = false;
$this->save();
}
/**
* @deprecated
*/
public function rejoin()
{
$this->status = 'setting-up';
$this->save();
}
public function emailConfirmed()
{
$this->email_verified = true;
$this->save();
}
/**
* Fetch a user record, performs a permission check
*
* @param integer|null $id
* @param string $role
*
* @return User
* @throws AuthenticationException
*/
public static function findWithPermission($id = null, $role = 'admin')
{
if (empty($id)) {
//Return the logged in user
return Auth::user();
}
$requestedUser = self::findOrFail($id);
if (Auth::user()->id == $requestedUser->id) {
//The user they are after is themselves
return $requestedUser;
}
//They are requesting a user that isn't them
if (Auth::user()->hasRole($role)) {
//They are an admin so that's alright
return $requestedUser;
}
throw new AuthenticationException();
}
public function extendMembership($paymentMethod = null, DateTime $expiry = null)
{
if (empty($expiry)) {
$expiry = Carbon::now()->addMonth();
}
$this->status = 'active';
$this->active = true;
if ($paymentMethod) {
$this->payment_method = $paymentMethod;
}
$this->subscription_expires = $expiry;
$this->save();
}
/**
* @return array
*/
public function getAuditFields()
{
return $this->auditFields;
}
}
<file_sep>/app/Http/Controllers/SubscriptionController.php
<?php namespace BB\Http\Controllers;
use BB\Entities\User;
use BB\Repo\SubscriptionChargeRepository;
class SubscriptionController extends Controller
{
/**
* @var SubscriptionChargeRepository
*/
private $subscriptionChargeRepository;
/**
* @var \BB\Repo\UserRepository
*/
private $userRepository;
function __construct(\BB\Helpers\GoCardlessHelper $goCardless, SubscriptionChargeRepository $subscriptionChargeRepository, \BB\Repo\UserRepository $userRepository)
{
$this->goCardless = $goCardless;
$this->subscriptionChargeRepository = $subscriptionChargeRepository;
$this->userRepository = $userRepository;
$this->middleware('role:member', array('only' => ['create', 'destroy']));
}
/**
* Setup a new pre auth
*
* @return \Illuminate\Http\RedirectResponse
*/
public function create($userId)
{
$user = User::findWithPermission($userId);
$payment_details = array(
'redirect_uri' => route('account.subscription.store', $user->id),
'user' => [
'first_name' => $user->given_name,
'last_name' => $user->family_name,
'billing_address1' => $user->address->line_1,
'billing_address2' => $user->address->line_2,
'billing_town' => $user->address->line_3,
'billing_postcode' => $user->address->postcode,
'country_code' => 'GB'
]
);
return \Redirect::to($this->goCardless->newPreAuthUrl($payment_details));
}
/**
* Store a newly created resource in storage.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function store($userId)
{
$confirm_params = array(
'resource_id' => \Request::get('resource_id'),
'resource_type' => \Request::get('resource_type'),
'resource_uri' => \Request::get('resource_uri'),
'signature' => \Request::get('signature'),
);
// State is optional
if (\Request::get('state')) {
$confirm_params['state'] = \Request::get('state');
}
$user = User::findWithPermission($userId);
try {
$confirmed_resource = $this->goCardless->confirmResource($confirm_params);
} catch (\Exception $e) {
\Notification::error($e->getMessage());
return \Redirect::route('account.show', $user->id);
}
if (strtolower($confirmed_resource->status) != 'active') {
\Notification::error('Something went wrong, you can try again or get in contact');
return \Redirect::route('account.show', $user->id);
}
$this->userRepository->recordGoCardlessVariableDetails($user->id, $confirmed_resource->id);
//all we need for a valid member is an active dd so make sure the user account is active
$this->userRepository->ensureMembershipActive($user->id);
return \Redirect::route('account.show', [$user->id]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Illuminate\Http\RedirectResponse
*/
public function destroy($userId, $id = null)
{
/**
* TODO: Check for and cancel pending sub charges
*/
$user = User::findWithPermission($userId);
if ($user->payment_method == 'gocardless') {
try {
$subscription = $this->goCardless->cancelSubscription($user->subscription_id);
if ($subscription->status == 'cancelled') {
$user->cancelSubscription();
\Notification::success('Your subscription has been cancelled');
return \Redirect::back();
}
} catch (\GoCardless_ApiException $e) {
if ($e->getCode() == 404) {
$user->cancelSubscription();
\Notification::success('Your subscription has been cancelled');
return \Redirect::back();
}
}
} elseif ($user->payment_method == 'gocardless-variable') {
$status = $this->goCardless->cancelPreAuth($user->subscription_id);
if ($status) {
$user->subscription_id = null;
$user->payment_method = '';
$user->save();
$user->setLeaving();
$this->subscriptionChargeRepository->cancelOutstandingCharges($userId);
\Notification::success('Your direct debit has been cancelled');
return \Redirect::back();
}
}
\Notification::error('Sorry, we were unable to cancel your subscription, please get in contact');
return \Redirect::back();
}
public function listCharges()
{
$charges = $this->subscriptionChargeRepository->getChargesPaginated();
return \View::make('payments.sub-charges')->with('charges', $charges);
}
public function updatePaymentMethod($id)
{
$user = User::findWithPermission($id);
$paymentMethod = \Input::get('payment_method');
if ($paymentMethod === 'balance' && $user->payment_method != $paymentMethod) {
$status = $this->goCardless->cancelPreAuth($user->subscription_id);
if ($status) {
$user->subscription_id = null;
$user->payment_method = 'balance';
$user->save();
// If we don't cancel the sub charge the balance process may pick it up
//$this->subscriptionChargeRepository->cancelOutstandingCharges($userId);
}
}
\Notification::success('Details Updated');
return \Redirect::route('account.show', [$user->id]);
}
}
<file_sep>/app/Repo/EquipmentRepository.php
<?php namespace BB\Repo;
use BB\Entities\Equipment;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class EquipmentRepository extends DBRepository
{
/**
* @var Equipment
*/
protected $model;
public function __construct(Equipment $model)
{
$this->model = $model;
}
public function all()
{
return $this->model->all();
}
public function getRequiresInduction()
{
return $this->model->where('requires_induction', true)->get();
}
public function getDoesntRequireInduction()
{
return $this->model->where('requires_induction', false)->get();
}
public function allPaid()
{
return $this->model->where('access_fee', '!=', 0)->get();
}
/**
* Return a device by its slug
* @param $slug
* @return Equipment
*/
public function findBySLug($slug)
{
$record = $this->model->where('slug', $slug)->first();
if ($record) {
return $record;
}
throw new ModelNotFoundException();
}
} <file_sep>/app/Http/Controllers/ACS/TestController.php
<?php
namespace BB\Http\Controllers\ACS;
use Illuminate\Http\Request;
use BB\Http\Requests;
use BB\Http\Controllers\Controller;
/**
* @SWG\Info(title="Build Brighton API", version="1")
* @SWG\SecurityScheme(
* securityDefinition="api_key",
* type="apiKey",
* in="header",
* name="api_key"
* )
*/
class TestController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*
* @SWG\Get(
* path="/acs/test",
* tags={"acs"},
* description="Returns an OK message, useful for verifying the access token works",
* @SWG\Response(response="200", description="OK")
* )
*/
public function index()
{
return ['OK'];
}
}
<file_sep>/app/Http/Controllers/CashPaymentController.php
<?php namespace BB\Http\Controllers;
use BB\Entities\User;
class CashPaymentController extends Controller
{
/**
* @var \BB\Repo\PaymentRepository
*/
private $paymentRepository;
/**
* @var \BB\Services\Credit
*/
private $bbCredit;
function __construct(\BB\Repo\PaymentRepository $paymentRepository, \BB\Services\Credit $bbCredit)
{
$this->paymentRepository = $paymentRepository;
$this->bbCredit = $bbCredit;
}
/**
* Start the creation of a new gocardless payment
* Details get posted into this method and the redirected to gocardless
*
* @param $userId
* @throws \BB\Exceptions\AuthenticationException
* @throws \BB\Exceptions\FormValidationException
* @throws \BB\Exceptions\NotImplementedException
*/
public function store($userId)
{
User::findWithPermission($userId);
$amount = \Request::get('amount');
$reason = \Request::get('reason');
$sourceId = \Request::get('source_id');
$returnPath = \Request::get('return_path');
$this->paymentRepository->recordPayment($reason, $userId, 'cash', $sourceId, $amount);
\Notification::success("Payment recorded");
return \Redirect::to($returnPath);
}
/**
* Remove cash from the users balance
*
* @param $userId
* @return mixed
* @throws \BB\Exceptions\AuthenticationException
* @throws \BB\Exceptions\InvalidDataException
*/
public function destroy($userId)
{
$user = User::findWithPermission($userId);
$this->bbCredit->setUserId($userId);
$amount = \Request::get('amount');
$returnPath = \Request::get('return_path');
$ref = \Request::get('ref');
$minimumBalance = $this->bbCredit->acceptableNegativeBalance('withdrawal');
if (($user->cash_balance + ($minimumBalance * 100)) < ($amount * 100)) {
\Notification::error("Not enough money");
return \Redirect::to($returnPath);
}
$this->paymentRepository->recordPayment('withdrawal', $userId, 'balance', '', $amount, 'paid', 0, $ref);
$this->bbCredit->recalculate();
\Notification::success("Payment recorded");
return \Redirect::to($returnPath);
}
}
<file_sep>/app/Listeners/RecordMemberActivity.php
<?php
namespace BB\Listeners;
use BB\Events\MemberActivity;
use BB\Repo\ActivityRepository;use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class RecordMemberActivity
{
/**
* @var ActivityRepository
*/
private $activityRepository;
/**
* Create the event listener.
*
* @param ActivityRepository $activityRepository
*/
public function __construct(ActivityRepository $activityRepository)
{
$this->activityRepository = $activityRepository;
}
/**
* Handle the event.
*
* @param MemberActivity $event
*/
public function handle(MemberActivity $event)
{
$activity = $this->activityRepository->recordMemberActivity($event->keyFob->user->id, $event->keyFob->id, $event->service);
//The old door entry system may send over historical records, make sure these are marked as such
if ($event->delayed) {
$activity->delayed = true;
$activity->save();
}
}
}
<file_sep>/app/Http/Controllers/ActivityController.php
<?php namespace BB\Http\Controllers;
use BB\Entities\Settings;
class ActivityController extends Controller
{
/**
* @var \BB\Repo\ActivityRepository
*/
private $activityRepository;
function __construct(\BB\Repo\ActivityRepository $activityRepository)
{
$this->activityRepository = $activityRepository;
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$date = \Input::get('date', \Carbon\Carbon::now()->format('Y-m-d'));
$date = \Carbon\Carbon::createFromFormat('Y-m-d', $date)->setTime(0, 0, 0);
$today = \Carbon\Carbon::now()->setTime(0, 0, 0);
$logEntries = $this->activityRepository->getForDate($date);
$nextDate = null;
if ($date->lt($today)) {
$nextDate = $date->copy()->addDay();
}
$previousDate = $date->copy()->subDay();
$doorPin = Settings::get('emergency_door_key_storage_pin');
return \View::make('activity.index')
->with('logEntries', $logEntries)
->with('date', $date)
->with('nextDate', $nextDate)
->with('previousDate', $previousDate)
->with('doorPin', $doorPin);
}
/**
* @return Response
*/
public function realtime()
{
return \View::make('activity.realtime');
}
}
<file_sep>/app/Entities/ACSNode.php
<?php namespace BB\Entities;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
/**
* Class ACSNode
*
* @property string $name
* @property string $device_id
* @property string $queued_command
* @property bool $monitor_heartbeat
* @property string $api_key
* @property Carbon $last_boot
* @property Carbon $last_heartbeat
* @property Carbon $created_at
* @property Carbon $updated_at
* @package BB\Entities
*/
class ACSNode extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'acs_nodes';
/**
* Fillable fields
*
* @var array
*/
protected $fillable = [
'last_heartbeat', 'last_boot'
];
public function getDates()
{
return array('created_at', 'updated_at', 'last_boot', 'last_heartbeat');
}
public function heartbeatWarning()
{
//If the last heartbeat was more than an hour ago there is an issue
if ( $this->monitor_heartbeat && ($this->last_heartbeat < Carbon::now()->subHour())) {
return true;
}
return false;
}
} <file_sep>/app/Http/Requests/ACS/Activity.php
<?php namespace BB\Http\Requests\ACS;
use Symfony\Component\HttpFoundation\Request;
use Swagger\Annotations as SWG;
/**
* @SWG\Definition(@SWG\Xml(name="Activity"))
*/
class Activity
{
/**
* @SWG\Property(description="The RFID Tag ID")
* @var string
*/
private $tagId;
/**
* @SWG\Property(description="The String of the device being controlled")
* @var string
*/
private $device;
/**
* @SWG\Property(description="Date Time of the event, YYYY-MM-DD HH:mm:ss")
* @var string
*/
private $occurredAt;
/**
* Activity constructor.
*/
public function __construct(Request $request)
{
$this->tagId = $request->get('tagId');
$this->device = $request->get('device');
$this->occurredAt = $request->get('occurredAt');
}
/**
* @return string
*/
public function getTagId()
{
return $this->tagId;
}
/**
* @return string
*/
public function getDevice()
{
return $this->device;
}
/**
* @return string
*/
public function getOccurredAt()
{
return $this->occurredAt;
}
}<file_sep>/app/Http/Controllers/AccountController.php
<?php namespace BB\Http\Controllers;
use BB\Entities\Notification;
use BB\Entities\User;
use BB\Events\MemberGivenTrustedStatus;
use BB\Events\MemberPhotoWasDeclined;
use BB\Exceptions\ValidationException;
use BB\Validators\InductionValidator;
class AccountController extends Controller
{
protected $layout = 'layouts.main';
protected $userForm;
/**
* @var \BB\Helpers\UserImage
*/
private $userImage;
/**
* @var \BB\Validators\UserDetails
*/
private $userDetailsForm;
/**
* @var \BB\Repo\ProfileDataRepository
*/
private $profileRepo;
/**
* @var \BB\Repo\InductionRepository
*/
private $inductionRepository;
/**
* @var \BB\Repo\EquipmentRepository
*/
private $equipmentRepository;
/**
* @var \BB\Repo\UserRepository
*/
private $userRepository;
/**
* @var \BB\Validators\ProfileValidator
*/
private $profileValidator;
/**
* @var \BB\Repo\AddressRepository
*/
private $addressRepository;
/**
* @var \BB\Repo\SubscriptionChargeRepository
*/
private $subscriptionChargeRepository;
function __construct(
\BB\Validators\UserValidator $userForm,
\BB\Validators\UpdateSubscription $updateSubscriptionAdminForm,
\BB\Helpers\GoCardlessHelper $goCardless,
\BB\Helpers\UserImage $userImage,
\BB\Validators\UserDetails $userDetailsForm,
\BB\Repo\ProfileDataRepository $profileRepo,
\BB\Repo\InductionRepository $inductionRepository,
\BB\Repo\EquipmentRepository $equipmentRepository,
\BB\Repo\UserRepository $userRepository,
\BB\Validators\ProfileValidator $profileValidator,
\BB\Repo\AddressRepository $addressRepository,
\BB\Repo\SubscriptionChargeRepository $subscriptionChargeRepository,
\BB\Services\Credit $bbCredit)
{
$this->userForm = $userForm;
$this->updateSubscriptionAdminForm = $updateSubscriptionAdminForm;
$this->goCardless = $goCardless;
$this->userImage = $userImage;
$this->userDetailsForm = $userDetailsForm;
$this->profileRepo = $profileRepo;
$this->inductionRepository = $inductionRepository;
$this->equipmentRepository = $equipmentRepository;
$this->userRepository = $userRepository;
$this->profileValidator = $profileValidator;
$this->addressRepository = $addressRepository;
$this->subscriptionChargeRepository = $subscriptionChargeRepository;
$this->bbCredit = $bbCredit;
//This tones down some validation rules for admins
$this->userForm->setAdminOverride( ! \Auth::guest() && \Auth::user()->hasRole('admin'));
$this->middleware('role:member', array('except' => ['create', 'store']));
$this->middleware('role:admin', array('only' => ['index']));
//$this->middleware('guest', array('only' => ['create', 'store']));
$paymentMethods = [
'gocardless' => 'GoCardless',
'paypal' => 'PayPal',
'bank-transfer' => 'Manual Bank Transfer',
'other' => 'Other'
];
\View::share('paymentMethods', $paymentMethods);
\View::share('paymentDays', array_combine(range(1, 31), range(1, 31)));
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$sortBy = \Request::get('sortBy');
$direction = \Request::get('direction', 'asc');
$showLeft = \Request::get('showLeft', 0);
$users = $this->userRepository->getPaginated(compact('sortBy', 'direction', 'showLeft'));
return \View::make('account.index')->withUsers($users);
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
\View::share('body_class', 'register_login');
return \View::make('account.create');
}
/**
* Store a newly created resource in storage.
*
* @return Illuminate\Http\RedirectResponse
*/
public function store()
{
$input = \Input::only(
'given_name',
'family_name',
'email',
'secondary_email',
'<PASSWORD>',
'phone',
'address.line_1',
'address.line_2',
'address.line_3',
'address.line_4',
'address.postcode',
'monthly_subscription',
'emergency_contact',
'new_profile_photo',
'profile_photo_private',
'rules_agreed',
'visited_space'
);
$this->userForm->validate($input);
$this->profileValidator->validate($input);
$user = $this->userRepository->registerMember($input, ! \Auth::guest() && \Auth::user()->hasRole('admin'));
if (\Input::file('new_profile_photo')) {
try {
$this->userImage->uploadPhoto($user->hash, \Input::file('new_profile_photo')->getRealPath(), true);
$this->profileRepo->update($user->id, ['new_profile_photo'=>1, 'profile_photo_private'=>$input['profile_photo_private']]);
} catch (\Exception $e) {
\Log::error($e);
}
}
//If this isn't an admin user creating the record log them in
if (\Auth::guest() || ! \Auth::user()->isAdmin()) {
\Auth::login($user);
}
return \Redirect::route('account.show', [$user->id]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
$user = User::findWithPermission($id);
$inductions = $this->equipmentRepository->getRequiresInduction();
$userInductions = $user->inductions()->get();
foreach ($inductions as $i=>$induction) {
$inductions[$i]->userInduction = false;
foreach ($userInductions as $userInduction) {
if ($userInduction->key == $induction->induction_category) {
$inductions[$i]->userInduction = $userInduction;
}
}
}
//get pending address if any
$newAddress = $this->addressRepository->getNewUserAddress($id);
//Get the member subscription payments
$subscriptionCharges = $this->subscriptionChargeRepository->getMemberChargesPaginated($id);
//Get the members balance
$this->bbCredit->setUserId($user->id);
$memberBalance = $this->bbCredit->getBalanceFormatted();
return \View::make('account.show')
->with('user', $user)
->with('inductions', $inductions)
->with('newAddress', $newAddress)
->with('subscriptionCharges', $subscriptionCharges)
->with('memberBalance', $memberBalance);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
$user = User::findWithPermission($id);
//We need to access the address here so its available in the view
$user->address;
return \View::make('account.edit')->with('user', $user);
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return \Illuminate\Http\RedirectResponse
*/
public function update($id)
{
$user = User::findWithPermission($id);
$input = \Input::only('given_name', 'family_name', 'email', 'secondary_email', 'password', 'phone', 'address.line_1', 'address.line_2', 'address.line_3', 'address.line_4', 'address.postcode', 'emergency_contact', 'profile_private');
$this->userForm->validate($input, $user->id);
$this->userRepository->updateMember($id, $input, \Auth::user()->hasRole('admin'));
\Notification::success('Details Updated');
return \Redirect::route('account.show', [$user->id]);
}
public function adminUpdate($id)
{
$user = User::findWithPermission($id);
$madeTrusted = false;
if (\Input::has('trusted')) {
if ( ! $user->trusted && \Input::get('trusted')) {
//User has been made a trusted member
$madeTrusted = true;
}
$user->trusted = \Input::get('trusted');
}
if (\Input::has('key_holder')) {
$user->key_holder = \Input::get('key_holder');
}
if (\Input::has('induction_completed')) {
$user->induction_completed = \Input::get('induction_completed');
}
if (\Input::has('profile_photo_on_wall')) {
$profileData = $user->profile()->first();
$profileData->profile_photo_on_wall = \Input::get('profile_photo_on_wall');
$profileData->save();
}
if (\Input::has('photo_approved')) {
$profile = $user->profile()->first();
if (\Input::get('photo_approved')) {
$this->userImage->approveNewImage($user->hash);
$profile->update(['new_profile_photo' => false, 'profile_photo' => true]);
} else {
$profile->update(['new_profile_photo' => false]);
event(new MemberPhotoWasDeclined($user));
}
}
$user->save();
if (\Input::has('approve_new_address')) {
if (\Input::get('approve_new_address') == 'Approve') {
$this->addressRepository->approvePendingMemberAddress($id);
} elseif (\Input::get('approve_new_address') == 'Decline') {
$this->addressRepository->declinePendingMemberAddress($id);
}
}
if ($madeTrusted) {
$message = 'You have been made a trusted member at Build Brighton';
$notificationHash = 'trusted_status';
Notification::logNew($user->id, $message, 'trusted_status', $notificationHash);
event(new MemberGivenTrustedStatus($user));
}
if (\Request::wantsJson()) {
return \Response::json('Updated', 200);
} else {
\Notification::success('Details Updated');
return \Redirect::route('account.show', [$user->id]);
}
}
public function alterSubscription($id)
{
$user = User::findWithPermission($id);
$input = \Input::all();
$this->updateSubscriptionAdminForm->validate($input, $user->id);
if (($user->payment_method == 'gocardless') && ($input['payment_method'] != 'gocardless')) {
//Changing away from GoCardless
$subscription = $this->goCardless->cancelSubscription($user->subscription_id);
if ($subscription->status == 'cancelled') {
$user->cancelSubscription();
}
}
$user->updateSubscription($input['payment_method'], $input['payment_day']);
\Notification::success('Details Updated');
return \Redirect::route('account.show', [$user->id]);
}
public function confirmEmail($id, $hash)
{
$user = User::find($id);
if ($user && $user->hash == $hash) {
$user->emailConfirmed();
\Notification::success('Email address confirmed, thank you');
return \Redirect::route('account.show', $user->id);
}
\Notification::error('Error confirming email address');
return \Redirect::route('home');
}
public function destroy($id)
{
$user = User::findWithPermission($id);
//No one will ever leaves the system but we can at least update their status to left.
$user->setLeaving();
\Notification::success('Updated status to leaving');
return \Redirect::route('account.show', [$user->id]);
}
public function rejoin($id)
{
$user = User::findWithPermission($id);
$user->rejoin();
\Notification::success('Details Updated');
return \Redirect::route('account.show', [$user->id]);
}
public function updateSubscriptionAmount($id)
{
$amount = \Input::get('monthly_subscription');
if ($amount < 5) {
throw new ValidationException('The minimum subscription is 5 GBP');
} elseif (!\Auth::user()->isAdmin() && ($amount < 15)) {
throw new ValidationException('The minimum subscription is 15 GBP, please contact the trustees for a lower amount. <EMAIL>');
}
$user = User::findWithPermission($id);
$user->updateSubAmount(\Input::get('monthly_subscription'));
\Notification::success('Details Updated');
return \Redirect::route('account.show', [$user->id]);
}
}
<file_sep>/app/Repo/PaymentRepository.php
<?php namespace BB\Repo;
use BB\Entities\Payment;
use BB\Events\MemberBalanceChanged;
use BB\Exceptions\NotImplementedException;
use BB\Exceptions\PaymentException;
use Carbon\Carbon;
class PaymentRepository extends DBRepository
{
/**
* @var Payment
*/
protected $model;
public static $SUBSCRIPTION = 'subscription';
public static $INDUCTION = 'induction';
private $reason = null;
private $source = null;
/**
* @param Payment $model
*/
public function __construct(Payment $model)
{
$this->model = $model;
$this->perPage = 10;
}
public function getPaginated(array $params)
{
$model = $this->model;
if ($this->hasDateFilter()) {
$model = $model->where('created_at', '>=', $this->startDate)->where('created_at', '<=', $this->endDate);
}
if ($this->hasMemberFilter()) {
$model = $model->where('user_id', $this->memberId);
}
if ($this->hasReasonFilter()) {
$model = $model->where('reason', $this->reason);
}
if ($this->hasSourceFilter()) {
$model = $model->where('source', $this->source);
}
if ($this->isSortable($params)) {
return $model->orderBy($params['sortBy'], $params['direction'])->paginate($this->perPage);
}
return $model->paginate($this->perPage);
}
public function getTotalAmount()
{
$model = $this->model;
if ($this->hasDateFilter()) {
$model = $model->where('created_at', '>=', $this->startDate)->where('created_at', '<=', $this->endDate);
}
if ($this->hasMemberFilter()) {
$model = $model->where('user_id', $this->memberId);
}
if ($this->hasReasonFilter()) {
$model = $model->where('reason', $this->reason);
}
if ($this->hasSourceFilter()) {
$model = $model->where('source', $this->source);
}
return $model->get()->sum('amount');
}
/**
* Record a payment against a user record
*
* @param string $reason What was the reason. subscription, induction, etc...
* @param int $userId The users ID
* @param string $source gocardless, paypal
* @param string $sourceId A reference for the source
* @param double $amount Amount received before a fee
* @param string $status paid, pending, cancelled, refunded
* @param double $fee The fee charged by the payment provider
* @param string $ref
* @param Carbon $paidDate
* @return int The ID of the payment record
*/
public function recordPayment($reason, $userId, $source, $sourceId, $amount, $status = 'paid', $fee = 0.0, $ref = '', Carbon $paidDate = null)
{
if ($paidDate == null) {
$paidDate = new Carbon();
}
//If we have an existing similer record dont create another, except for when there is no source id
$existingRecord = $this->model->where('source', $source)->where('source_id', $sourceId)->where('user_id', $userId)->first();
if ( ! $existingRecord || empty($sourceId)) {
$record = new $this->model;
$record->user_id = $userId;
$record->reason = $reason;
$record->source = $source;
$record->source_id = $sourceId;
$record->amount = $amount;
$record->amount_minus_fee = ($amount - $fee);
$record->fee = $fee;
$record->status = $status;
$record->reference = $ref;
if ($status == 'paid') {
$record->paid_at = $paidDate;
}
$record->save();
} else {
$record = $existingRecord;
}
//Emit an event so that things like the balance updater can run
\Event::fire('payment.create', array($userId, $reason, $ref, $record->id, $status));
return $record->id;
}
/**
* Record a subscription payment
*
* @param int $userId The users ID
* @param string $source gocardless, paypal
* @param string $sourceId A reference for the source
* @param double $amount Amount received before a fee
* @param string $status paid, pending, cancelled, refunded
* @param double $fee The fee charged by the payment provider
* @param string|null $ref
* @param Carbon $paidDate
* @return int The ID of the payment record
*/
public function recordSubscriptionPayment($userId, $source, $sourceId, $amount, $status = 'paid', $fee = 0.0, $ref = '', Carbon $paidDate = null)
{
return $this->recordPayment('subscription', $userId, $source, $sourceId, $amount, $status, $fee, $ref, $paidDate);
}
/**
* An existing payment has been set to paid
*
* @param $paymentId
* @param Carbon $paidDate
*/
public function markPaymentPaid($paymentId, $paidDate)
{
$payment = $this->getById($paymentId);
$payment->status = 'paid';
$payment->paid_at = $paidDate;
$payment->save();
\Event::fire('payment.paid', array($payment->user_id, $paymentId, $payment->reason, $payment->reference, $paidDate));
}
/**
* Record a payment failure or cancellation
*
* @param int $paymentId
* @param string $status
*/
public function recordPaymentFailure($paymentId, $status = 'failed')
{
$this->update($paymentId, ['status' => $status]);
$payment = $this->getById($paymentId);
\Event::fire('payment.cancelled', array($paymentId, $payment->user_id, $payment->reason, $payment->reference, $status));
}
/**
* Assign an unassigned payment to a user
*
* @param int $paymentId
* @param int $userId
*
* @throws PaymentException
*/
public function assignPaymentToUser($paymentId, $userId)
{
$payment = $this->getById($paymentId);
if (!empty($payment->user_id)) {
throw new PaymentException('Payment already assigned to user');
}
$this->update($paymentId, ['user_id' => $userId]);
}
/**
* Take a payment that has been used for something and reassign it to the balance
* @param $paymentId
*
* @throws NotImplementedException
*/
public function refundPaymentToBalance($paymentId)
{
$payment = $this->getById($paymentId);
if ($payment->reason === 'donation') {
$this->update($paymentId, ['reason' => 'balance']);
event(new MemberBalanceChanged($payment->user_id));
return;
}
if ($payment->reason === 'induction') {
//This method must only be used if the induction record has been cancelled first
// otherwise an orphned record will be left behind
$this->update($paymentId, ['reason' => 'balance']);
event(new MemberBalanceChanged($payment->user_id));
return;
}
throw new NotImplementedException('This hasn\'t been built yet');
}
/**
* Fetch the users latest payment of a particular type
* @param integer $userId
* @param string $reason
* @return mixed
*/
public function latestUserPayment($userId, $reason = 'subscription')
{
return $this->model->where('user_id', $userId)
->whereRaw('reason = ? and (status = ? or status = ? or status = ?)', [$reason, 'paid', 'pending', 'withdrawn'])
->orderBy('created_at', 'desc')
->first();
}
/**
* Get all user payments of a specific reason
* @param $userId
* @param string $reason
* @return mixed
*/
public function getUserPaymentsByReason($userId, $reason)
{
return $this->model->where('user_id', $userId)
->whereRaw('reason = ? and (status = ? or status = ? or status = ?)', [$reason, 'paid', 'pending', 'withdrawn'])
->orderBy('created_at', 'desc')
->get();
}
/**
* @param string $source
*/
public function getUserPaymentsBySource($userId, $source)
{
return $this->model->where('user_id', $userId)
->whereRaw('source = ? and (status = ? or status = ? or status = ?)', [$source, 'paid', 'pending', 'withdrawn'])
->orderBy('created_at', 'desc')
->get();
}
/**
* Get all payments with a specific reference
* @param string $reference
* @return \Illuminate\Database\Eloquent\Collection
*/
public function getPaymentsByReference($reference)
{
return $this->model->where('reference', $reference)->get();
}
/**
* @param string $referencePrefix
* @return \Illuminate\Database\Eloquent\Collection
*/
public function getEquipmentFeePayments($referencePrefix)
{
return $this->model->where('reason', 'equipment-fee')->get()->filter(function($payment) use($referencePrefix) {
return strpos($payment->reference, ':' . $referencePrefix) !== false;
});
}
/**
* Return a paginated list of balance affecting payment for a user
* @param $userId
* @return \Illuminate\Database\Eloquent\Collection
*/
public function getBalancePaymentsPaginated($userId)
{
return $this->model->where('user_id', $userId)
->whereRaw('(source = ? or reason = ?) and (status = ? or status = ? or status = ?)', ['balance', 'balance', 'paid', 'pending', 'withdrawn'])
->orderBy('created_at', 'desc')
->simplePaginate($this->perPage);
}
/**
* Return a collection of payments specifically for storage boxes
* @param integer $userId
* @return mixed
*/
public function getStorageBoxPayments($userId)
{
return $this->model->where('user_id', $userId)
->whereRaw('reason = ? and (status = ? or status = ? or status = ?)', ['storage-box', 'paid', 'pending', 'withdrawn'])
->orderBy('created_at', 'desc')
->get();
}
public function dateFilter($startDate, $endDate)
{
$this->startDate = $startDate;
$this->endDate = $endDate;
}
private function hasDateFilter()
{
return ($this->startDate && $this->endDate);
}
/**
* Delete a record
* @param $recordId
* @return bool|null
* @throws \Exception
*/
public function delete($recordId)
{
$payment = $this->getById($recordId);
$state = $payment->delete();
//Fire an event, allows the balance to get updated
\Event::fire('payment.delete', array($payment->user_id, $payment->source, $payment->reason, $payment->id));
return $state;
}
public function canDelete($recordId)
{
throw new NotImplementedException();
}
/**
* Used for the getPaginated and getTotalAmount method
* @param $reasonFilter
*/
public function reasonFilter($reasonFilter)
{
$this->reason = $reasonFilter;
}
private function hasReasonFilter()
{
return ! is_null($this->reason);
}
/**
* Used for the getPaginated and getTotalAmount method
* @param string $sourceFilter
*/
public function sourceFilter($sourceFilter)
{
$this->source = $sourceFilter;
}
private function hasSourceFilter()
{
return ! is_null($this->source);
}
/**
* Used for the getPaginated and getTotalAmount method
*/
public function resetFilters()
{
$this->source = null;
$this->reason = null;
$this->memberId = null;
$this->startDate = null;
$this->endDate = null;
}
/**
* Fetch a payment record using the id provided by the payment provider
*
* @param $sourceId
* @return Payment
*/
public function getPaymentBySourceId($sourceId)
{
return $this->model->where('source_id', $sourceId)->first();
}
/**
* Record a balance payment transfer between two users
*
* @param integer $sourceUserId
* @param integer $targetUserId
* @param double $amount
*/
public function recordBalanceTransfer($sourceUserId, $targetUserId, $amount)
{
$paymentId = $this->recordPayment('transfer', $sourceUserId, 'balance', '', $amount, 'paid', 0, $targetUserId);
$this->recordPayment('balance', $targetUserId, 'transfer', $paymentId, $amount, 'paid', 0, $sourceUserId);
//Both of these events aren't needed adn the balance payment fires its own
// but for the sake of neatness they are here
event(new MemberBalanceChanged($sourceUserId));
event(new MemberBalanceChanged($targetUserId));
}
} <file_sep>/app/Handlers/SubChargeEventHandler.php
<?php namespace BB\Handlers;
use BB\Helpers\MembershipPayments;
use BB\Repo\SubscriptionChargeRepository;
use BB\Repo\UserRepository;
use Carbon\Carbon;
class SubChargeEventHandler
{
/**
* @var UserRepository
*/
private $userRepository;
/**
* @var SubscriptionChargeRepository
*/
private $subscriptionChargeRepository;
/**
* @param UserRepository $userRepository
* @param SubscriptionChargeRepository $subscriptionChargeRepository
*/
public function __construct(UserRepository $userRepository, SubscriptionChargeRepository $subscriptionChargeRepository)
{
$this->userRepository = $userRepository;
$this->subscriptionChargeRepository = $subscriptionChargeRepository;
}
/**
* A subscription charge has been marked as paid
*
* @param integer $chargeId
* @param integer $userId
* @param Carbon $paymentDate
* @param double $amount
*/
public function onPaid($chargeId, $userId, Carbon $paymentDate, $amount)
{
$user = $this->userRepository->getById($userId);
/** @var $user \BB\Entities\User */
$user->extendMembership(null, $paymentDate->addMonth());
}
/**
* A subscription charge has been marked as processing
*
* @param integer $chargeId
* @param integer $userId
* @param Carbon $paymentDate
* @param double $amount
*/
public function onProcessing($chargeId, $userId, Carbon $paymentDate, $amount)
{
$user = $this->userRepository->getById($userId);
/** @var $user \BB\Entities\User */
$user->extendMembership(null, $paymentDate->addMonth());
}
/**
* A sub charge has been rolled back as a payment failed
*
* @param integer $chargeId
* @param integer $userId
* @param Carbon $paymentDate
* @param double $amount
*/
public function onPaymentFailure($chargeId, $userId, Carbon $paymentDate, $amount)
{
$paidUntil = MembershipPayments::lastUserPaymentExpires($userId);
if ($paidUntil) {
$user = $this->userRepository->getById($userId);
/** @var $user \BB\Entities\User */
$user->extendMembership(null, $paidUntil);
} else {
\Log::info('Payment cancelled, expiry date rollback failed as there is no previous payment. User ID:' . $userId);
}
}
} <file_sep>/app/Http/Controllers/ACSController.php
<?php namespace BB\Http\Controllers;
use BB\Entities\DetectedDevice;
use BB\Repo\ACSNodeRepository;
use BB\Validators\ACSValidator;
class ACSController extends Controller
{
/**
* @var ACSNodeRepository
*/
private $deviceRepository;
/**
* @var ACSValidator
*/
private $ACSValidator;
/**
* @var \BB\Services\KeyFobAccess
*/
private $keyFobAccess;
function __construct(
ACSNodeRepository $acsNodeRepository,
ACSValidator $ACSValidator,
\BB\Services\KeyFobAccess $keyFobAccess
) {
$this->acsNodeRepository = $acsNodeRepository;
$this->ACSValidator = $ACSValidator;
$this->keyFobAccess = $keyFobAccess;
}
public function get()
{
}
public function store()
{
$data = \Request::only('device', 'service', 'message', 'tag', 'time', 'payload', 'signature', 'nonce');
//device = the device id from the devices table - unique to each piece of hardware
//service = what the request is for, entry, usage, consumable
//message = system message, heartbeat, boot
//tag = the keyfob id
//time = the time of the action
//payload = any extra data relavent to the request
//signature = an encoded value generated using a secret key - oauth style
//nonce = a unique value suitable to stop replay attacks
$this->ACSValidator->validate($data);
//System messages
if (in_array($data['message'], ['boot', 'heartbeat'])) {
return $this->handleSystemCheckIn($data['message'], $data['device'], $data['service']);
}
switch ($data['service']) {
case 'entry':
return $this->handleDoor($data);
case 'usage':
return $this->handleDevice($data);
case 'consumable':
break;
case 'shop':
break;
case 'status':
return $this->returnMemberStatus($data);
break;
case 'device-scanner':
$this->logDetectedDevices($data);
break;
default:
\Log::debug(json_encode($data));
}
$responseArray = [
'time' => time(),
'command' => null, //stored command for the device to process
'valid' => true, //member request
'available' => true, //device status - remote shutdown,
'member' => null, //member name
];
}
private function handleDoor($data)
{
$error = false;
//Door entry is quite simple - this will just deal with lookups
try {
$this->keyFobAccess->verifyForEntry($data['tag'], 'main-door', $data['time']);
$this->keyFobAccess->logSuccess();
} catch (\Exception $e) {
$error = true;
}
$cmd = $this->acsNodeRepository->popCommand($data['device']);
if ( ! $error) {
$responseData = ['member' => $this->keyFobAccess->getMemberName(), 'valid' => '1', 'cmd' => $cmd];
} else {
$responseData = ['valid' => '0', 'cmd' => $cmd];
}
return $this->sendResponse($responseData);
}
private function handleDevice($data)
{
$device = $this->acsNodeRepository->getByName($data['device']);
if ($data['message'] == 'boot') {
$this->acsNodeRepository->logBoot($data['device']);
} elseif ($data['message'] == 'heartbeat') {
$this->acsNodeRepository->logHeartbeat($data['device']);
}
//$member = $this->keyFobAccess->verifyForDevice($data['tag'], 'laser');
$deviceStatus = 'ok';
$responseData = ['deviceStatus' => $deviceStatus];
return $this->sendResponse($responseData);
}
/**
* System checkins are common across all devices
* Record the time and return pending status messages
*
* @param $message
* @param $device
* @return Response
*/
private function handleSystemCheckIn($message, $device, $service)
{
switch ($message) {
case 'boot':
$this->acsNodeRepository->logBoot($device);
break;
case 'heartbeat':
$this->acsNodeRepository->logHeartbeat($device);
break;
}
//The command comes from the database and will instruct the door entry system to clear its memory if set
$cmd = $this->acsNodeRepository->popCommand($device);
switch ($service) {
case 'entry':
//we don't have a system for this at the moment but could have a global shutdown option
$deviceStatus = '1';
break;
case 'usage':
//lookup the piece of equipment from the device id and get the status
$deviceStatus = '1';
break;
default:
$deviceStatus = '1';
}
$responseData = ['cmd' => $cmd, 'deviceStatus' => $deviceStatus];
return $this->sendResponse($responseData);
}
/**
* Json encode the response data and return
*
* @param array $responseData
* @return \Response
*/
private function sendResponse(array $responseData)
{
$responseData['time'] = time();
$response = \Response::json($responseData);
$response->headers->set('Content-Length', strlen($response->getContent()));
return $response;
}
private function logDetectedDevices($data)
{
//this isn't strictly a heartbeat but the updates occur at a regular interval so they will do
$this->acsNodeRepository->logHeartbeat($data['device']);
//See if any devices have been detected, if so log them
foreach (array_keys($data['payload']['bluetooth_devices']) as $macAddress) {
DetectedDevice::create([
'type' => 'bluetooth',
'mac_address' => $macAddress,
'display_name' => $data['payload']['bluetooth_devices'][$macAddress],
]);
}
}
private function returnMemberStatus($data)
{
try {
$user = $this->keyFobAccess->verifyForEntry($data['tag'], 'main-door', $data['time']);
} catch (\Exception $e) {
$responseData = ['valid' => '0', 'cmd' => ''];
return $this->sendResponse($responseData);
}
$responseData = ['member' => $this->keyFobAccess->getMemberName(), 'valid' => '1', 'cmd' => ''];
return $this->sendResponse($responseData);
}
} | 95cc10f00cf9f7f098efd0d0176a438c48388d48 | [
"Markdown",
"PHP"
] | 30 | PHP | BinaryKitten/BBMembershipSystem | 84e4c8170dff2dd0773eb69354aa68bba2cdf798 | fe95ef9b2acff0b9d61fb3f8918806097926566e | |
refs/heads/master | <repo_name>skammm/node-express<file_sep>/03/03-用mongodb重构crud/02-crud-express/router.js
/**
* 路由映射表
* get /student
get /student/add
post /student/add
get /student/edit
post /student/edit
get /student/delete
*
*/
var express = require('express');
var router = express.Router();
var fs = require('fs');
var student = require('./student.js')
var image=['/public/img/x1.jpg','/public/img/x2.jpg','/public/img/x3.jpg','/public/img/x4.jpg']
router.get('/student', function (req, res) {
student.find(function(err,data){
if(err){
return res.send(err)
}
res.render('index.html',{
image:image,
students:data
})
})
})
router.get('/student/add', function (req, res) {
res.render('add.html',{
image:image
})
})
router.post('/student/add', function (req, res) {
new student(req.body).save(function(err){
if(err){
return handleError(err);
}
res.redirect('/student');
})
})
router.get('/student/edit', function (req, res) {
student.findById(req.query.id,function(err,data){
if(err){
return res.send(err);
}
res.render('edit.html',{
student:data,
})
})
})
router.post('/student/edit', function (req, res) {
student.findOneAndUpdate(req.body.id,req.body,function(err){
if(err){
return res.send(err);
}
res.redirect('/student')
})
})
router.get('/student/delete', function (req, res) {
var del = {};
del.id = req.body.id
student.findOneAndRemove(del,function(err){
if(err){
return res.send(err)
}
res.redirect('/student')
})
})
module.exports = router;<file_sep>/03/02-crud-express/student.js
/**
* 用来完成对json文件的增删改查,处理数据逻辑
*/
/*
获取所有学生列表
*/
var path = './db.json';
var fs = require('fs')
exports.find = function(callback){
fs.readFile(path,function(err,data){
if(err){
return callback(err)
}
callback(null,JSON.parse(data.toString()).students)
})
}
/**
* 获取某个学生的个人信息
* @param {Number} id
* @param {Function} callback
*/
exports.findById = function(id,callback){
fs.readFile(path,function(err,data){
if(err){
return callback(err)
}
var students = JSON.parse(data.toString()).students;
var student = students.find(item=>{
return item.id == parseInt(id);
})
callback(null,student);
})
}
/*
添加学生信息
*/
exports.add = function(student,callback){
fs.readFile(path,function(err,data){
if(err){
return callback(err)
}
var students = JSON.parse(data.toString()).students;
student.id = students[students.length-1].id+1;
students.push(student);
var ret = JSON.stringify({
students:students
})
fs.writeFile(path,ret,function(err){
if(err){
return callback(err)
}
callback(null);
})
})
}
/*
修改学生信息
*/
exports.edit = function(student,callback){
console.log(student)
fs.readFile(path,function(err,data){
if(err){
return callback(err)
}
var students = JSON.parse(data.toString()).students;
var editStu = students.find(item=>{
return item.id == parseInt(student.id);
})
console.log(editStu)
for(var key in student){
editStu[key] = student[key];
}
var ret = JSON.stringify({
students:students
})
fs.writeFile(path,ret,function(err){
if(err){
callback(err);
}
})
callback(null)
})
}
/**
* 删除学生信息
*/
exports.delete = function(id,callback){
fs.readFile(path,function(err,data){
if(err){
return callback(err)
}
var students = JSON.parse(data.toString()).students;
var index = students.findIndex(item=>{
return item.id == parseInt(id);
})
students.splice(index,1);
var ret = JSON.stringify({
students:students
})
fs.writeFile(path,ret,function(err){
if(err){
callback(err);
}
})
callback(null)
})
}<file_sep>/02/01-像apache一样.js
const http = require('http');
const server = http.createServer();
const fs = require('fs')
var wwwDir = 'D:/app/www';
server.on('request',function(req,res){
var url = req.url;
var filePath = '/index.html';
if(url !== '/'){
filePath = url;
}
fs.readFile(`${wwwDir}${filePath}`,function(err,data){
if(err){
res.end('404 not found');
return;
}
res.end(data)
})
})
server.listen('3000',function(){
console.log('服务器启动成功')
})<file_sep>/03/03-用mongodb重构crud/02-crud-express/student.js
/**
* 用mongodb数据库来存储数据
* mongoose.model('Student',studentSchema)这个表达式返回Student
* 设计好数据库后,router文件夹中用的是mongoose提供的API来操作数据库
*/
var mongoose = require('mongoose');
//链接到crud这个数据库
mongoose.connect('mongodb://localhost/crud',{ useNewUrlParser: true });
//设计文档结构
var Schema = mongoose.Schema;
var studentSchema = new Schema({
name:{
type:String,
required:true
},
age:{
type:Number,
required:true
},
hobbies:{
type:String
}
})
//导出模型构造函数,集合名为‘students’
module.exports = mongoose.model('Student',studentSchema)<file_sep>/03/01-express/app.js
// npm install --global nodemon
// 使用这个插件,可以监视文件变化,自动重启服务器
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
//通过express来使用模板
app.engine('html', require('express-art-template'));
//请求静态资源文件
app.use('/lib/', express.static('./lib/'));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
var comments = [
{
name:'zz',
message:'wwwww',
date:'2020-1-1'
},
{
name:'zz',
message:'wwwww',
date:'2020-1-1'
},
{
name:'zz',
message:'wwwww',
date:'2020-1-1'
}
]
app.get('/', function (req, res) {
res.render('index.html', {
comments:comments
});
});
app.get('/post', function (req, res) {
res.render('post.html');
});
//为post请求指定处理函数
//在express中没有内置获取请求体的API,需要安装 npm install body-parser第三方包来获取
app.post('/post', function (req, res) {
var comment = req.body;
comment.date = '2020-1-1';
comments.unshift(comment);
res.redirect('/');
});
app.listen(3000,function(){
console.log('启动服务器')
})<file_sep>/README.md
# node-express
nodejs学习 使用express和mongodb
<file_sep>/02/03-在apache案例中加入引擎模板.js
//服务端渲染和客户端渲染的区别
//+客户端渲染(异步获取数据)不利于SEO搜索引擎的优化,需要多次请求,但请求速度快,可局部刷新页面
//+服务端渲染可以被爬虫抓取,客户端很难被爬虫搜索
//+真正的网站是两者结合来做的
var http = require('http');
var fs = require('fs');
var template = require('art-template');
var server = http.createServer();
var wwwDir = 'D:/app/www';
server.on('request',function(req,res){
//每次向服务器请求资源的时候都要读取文件
if(req.url === '/'){
fs.readFile('./tpl2.html',function(err,data){
if(err){
console.log('读取文件失败');
return;
}
//fs.readdir得到目录列表中的文件名和目录名
fs.readdir(wwwDir,function(err,file){
if(err){
return res.end('not found file')
}
var ret = template.render(data.toString(),{
files:file
})
res.end(ret);
})
})
}else if(req.url.indexOf('/lib/') !== -1){//为了请求静态资源
fs.readFile('../'+req.url,function(err,data){
if(err){
return res.end('not found');
}
res.end(data);
})
}
})
server.listen('3000',function(){
console.log('启动服务')
})
<file_sep>/02/02-在node中使用模板引擎.js
//npm install art-template
var template = require('art-template');
var fs = require('fs');
fs.readFile('./tpl.html',function(err,data){
if(err){
console.log('读不到文件');
return;
}
//data默认是二进制数据,render方法需要接受字符串
var ret = template.render(data.toString(),{
name:'jack',
age:23,
hobbies:['读书','画画','写字']
})
console.log(ret);
})
<file_sep>/03/02-crud-express/router.js
/**
* 路由映射表
* get /student
get /student/add
post /student/add
get /student/edit
post /student/edit
get /student/delete
*
*/
var express = require('express');
var router = express.Router();
var fs = require('fs');
var student = require('./student.js')
var image=['/public/img/x1.jpg','/public/img/x2.jpg','/public/img/x3.jpg','/public/img/x4.jpg']
router.get('/student', function (req, res) {
student.find(function(err,data){
if(err){
return res.send(err)
}
res.render('index.html',{
image:image,
students:data
})
})
})
router.get('/student/add', function (req, res) {
res.render('add.html',{
image:image
})
})
router.post('/student/add', function (req, res) {
student.add(req.body,function(err){
if(err){
return res.send(err)
}
res.redirect('/student');
})
})
router.get('/student/edit', function (req, res) {
student.findById(req.query.id,function(err,data){
if(err){
return res.send(err);
}
res.render('edit.html',{
student:data,
})
})
})
router.post('/student/edit', function (req, res) {
var edit = req.body;
student.edit(edit,function(err){
if(err){
return res.send(err);
}
res.redirect('/student')
})
})
router.get('/student/delete', function (req, res) {
student.delete(req.query.id,function(err){
if(err){
return res.send(err)
}
res.redirect('/student')
})
})
module.exports = router; | a98e46ca654f5a37bbce3f3e4ad616a2c7da76e5 | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | skammm/node-express | 1edba5324c06a4f3d5a5091423086d3c09b2af53 | 1e132d316ef06772d2e4b9d52fc2ae6871488f51 | |
refs/heads/master | <repo_name>mendajayaram/GitDemoUst<file_sep>/module.ts
import {position} from './oops';
var posobj=new position(1002,"jayaram",12345,"Full Stack Developer","Hyderabad");
posobj.displayDetail();<file_sep>/basic.ts
//Basic Program
var no:number=10.0;
var greet:string="Welcome to every one";
var con:boolean=false;
console.log(no);
console.log(greet);
console.log(con);
//Array
var student: string[]=["jayaram","Ram","Naresh"];
var fritus:Array<string>=["Applle","mango"];
console.log(fritus);
console.log(student);
//tupple
var product:[String,number,boolean,String]=["Apple",101,true,"hyd"];
console.log(product);
//enum
enum color{red=101,black,blue,green}
var num=color.green
console.log(num);
//union
var max :String | number |boolean=true;
var unknown:any="my name is jayaram";
console.log(unknown);
//object data type
var emp={
empid:1002,
empName:"Jayaram",
empsalary:12345,
empDetails:function(){
return `ID:${this.empid},Name:${this.empName},salary:${this.empsalary}`;
}
}
console.log(emp.empid);
console.log(emp.empName);
console.log(emp.empsalary);
<file_sep>/TaskNo6.ts
//Q5. //write a programe for displaying employee data
// create base class with name Employee containing property (id,name,designation)
// and one methode which will display all these information.
// create sub class with name Payslip containing property total salary,
// DA=25% of basic salary,HRA=800,tax=15% of basic salary.
// and create one methode which will display all information from Employee class
// as well as gross salary,DA,Tax.
class Employee{
displayempData() {
throw new Error("Method not implemented.");
}
protected Empid:number;
protected EmpName:string;
protected Empdesignation:string;
constructor(Empid:number,EmpName:string,Empdesignation:string){
this.Empid=Empid;
this.EmpName=EmpName;
this.Empdesignation=Empdesignation;
}
employeedisplay(){
console.log(`Employeeid: ${this.Empid}\nEmployeename: ${this.EmpName}\nEmpployeedesignation: ${this.Empdesignation}`)
}
}
var empobj = new Employee(10,"jayaram","Developer");
empobj.employeedisplay();
class Payslip extends Employee{
//DA=25% of basic salary,HRA=800,tax=15%
totalsalary: number;
constructor(Empid:number,EmpName:string,Empdesignation:string,totalsalary:number){
super(Empid,EmpName,Empdesignation);
this.totalsalary=totalsalary;
}
employeedisplay(){
var da:number=(this.totalsalary)*(25/100);
var hra:number=800;
var tax:number=(this.totalsalary)*(15/100);
console.log(`Employeeid: ${this.Empid}\nEmployeename: ${this.EmpName}\nEmpployeedesignation: ${this.Empdesignation}\nEmployeetotalsalary: ${this.totalsalary}\nEmployeeda: ${da }\nEmpployeehra: ${hra}\nEmpployeetax: ${tax}`)
}
}
var Pobj=new Payslip(1002,"sam","Developer",12345);
Pobj.employeedisplay();
<file_sep>/setterandgetter.ts
class Employee1{
private ename:string;
private esal:number;
private epost:string;
private post:string;
set _name(value){
this.ename=value;
}
get _name(){
return this.ename;
}
set _post(value){
this.ename=value;
}
get _post(){
return this.ename;
}
set _sal(value){
this.ename=value;
}
get _sal(){
return this.ename;
}
displayEmployeeData(){
console.log(`EmpName:${this.ename},EmpPost:${this.epost},EmpSal:${this.esal}`)
}
}
var empobj1=new Employee1();
empobj1._name="jayaram";
console.log("name"+empobj1._name);
empobj1._post="Full Stacki Developer";
console.log("Employee Position:"+empobj1._post);
empobj1._sal="123";
console.log("salary"+empobj1._sal)
<file_sep>/Task1.ts
class Student1{
protected sid:number;
protected sname:string;
constructor(id:number,name:string){
this.sid=id;
this.sname=name;
}
studentdisplay(){
console.log(`Studentid: ${this.sid},Studentname: ${this.sname}`)
}
}
var Studentobj = new Student(10,"jayaram");
Studentobj.studentdisplay();
//Task2
class Task2 extends Student1{
phonenumber:number;//phonenumber
address:string;//address
constructor(id:number,name:string,phonenumber:number,address:string){
super(id,name)
this.phonenumber=phonenumber;
this.address=address;
}
studentdisplay(){
console.log(`studentid: ${this.sid},studentname: ${this.sname},studentphonenumber: ${this.phonenumber},studentAddress: ${this.address}`)
}
}
var stdobj2=new Task2(1002,"sam",9874563210,"Hyderabad");
var stdobj3=new Task2(1003,"Josh",836952582,"Hyderabad");
stdobj2.studentdisplay();
stdobj3.studentdisplay();<file_sep>/Taskno7.ts
//creat one class which will calculate area of circle and,execute it from another file.
export
class Area1{
length:number;
width:number;
constructor(length:number,width:number){
this.length=length;
this.width=width;
}
getArea(){
console.log("Area of the rectange =:"+(this.length * this.width));
}
}
<file_sep>/Taskno5.ts
//create one parent class with name Student containing property stdName,stdId,
//stdSection, stdContact which should be accessible only in Mark class but not
//outside and one methode with name displayStdData which display all its property
//value.create another child class with name Mark extends from Student class
//containing property totalMark and one methode allInformation() which will
//display student class as well as Mark class property.
class Student{
protected stdId:number;
protected stdName:string;
protected stdSection:string;
protected stdContact:number;
constructor(stdId:number,stdName:string,stdSection:string,stdContact:number){
this.stdId=stdId;
this.stdName=stdName;
this.stdSection=stdSection;
this.stdContact=stdContact;
}
displayStdData(){
console.log(`Studentid: ${this.stdId},Studentname: ${this.stdName},StudentSection: ${this.stdSection},StudentContact: ${this.stdContact}`)
}
}
var Studentobj = new Student(10,"jayaram","A",9876543210);
Studentobj.displayStdData();
//Marks Class
class Marks extends Student{
m1:number;
m2:number;
address:string;//address
constructor(stdId:number,stdName:string,stdSection:string,stdContact:number ,m1:number,m2:number){
super(stdId,stdName,stdSection,stdContact);
this.m1=m1;
this.m2=m2;
}
studentdisplay(){
console.log(`Studentid: ${this.stdId},Studentname: ${this.stdName},StudentSection: ${this.stdSection},StudentContact: ${this.stdContact},StudentTotalmarks: ${this.m1+this.m2},StudentAverage: ${this.m1+this.m2}`)
}
}
var stdobj2=new Marks(1002,"sam","A",9876543210,90,80);
stdobj2.studentdisplay();
<file_sep>/oops.js
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
exports.position = void 0;
var Employee = /** @class */ (function () {
function Employee(id, name, sal) {
this.empid = id;
this.ename = name;
this.salary = sal;
}
Employee.prototype.displayDetail = function () {
console.log("Empid: " + this.empid + ",Empname: " + this.ename + ",Empsal: " + this.salary);
};
return Employee;
}());
var position = /** @class */ (function (_super) {
__extends(position, _super);
function position(id, name, sal, post, address) {
var _this = _super.call(this, id, name, sal) || this;
_this.post = post;
_this.address = address;
return _this;
}
position.prototype.displayDetail = function () {
console.log("Empid: " + this.empid + ",Empname: " + this.ename + ",Empsal: " + this.salary + ",EmpPost: " + this.post + ",EmpAddress: " + this.address);
};
return position;
}(Employee));
exports.position = position;
var posobj = new position(1002, "jayaram", 12345, "Full Stack Developer", "Hyderabad");
posobj.displayDetail();
<file_sep>/task1.js
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Student = /** @class */ (function () {
function Student(id, name) {
this.sid = id;
this.sname = name;
}
Student.prototype.studentdisplay = function () {
console.log("Studentid: " + this.sid + ",Studentname: " + this.sname);
};
return Student;
}());
var Studentobj = new Student(10, "jayaram");
Studentobj.studentdisplay();
//Task2
var Task2 = /** @class */ (function (_super) {
__extends(Task2, _super);
function Task2(id, name, phonenumber, address) {
var _this = _super.call(this, id, name) || this;
_this.phonenumber = phonenumber;
_this.address = address;
return _this;
}
Task2.prototype.studentdisplay = function () {
console.log("studentid: " + this.sid + ",studentname: " + this.sname + ",studentphonenumber: " + this.phonenumber + ",studentAddress: " + this.address);
};
return Task2;
}(Student));
var stdobj2 = new Task2(1002, "sam", 9874563210, "Hyderabad");
var stdobj3 = new Task2(1003, "Josh", 836952582, "Hyderabad");
stdobj2.studentdisplay();
stdobj3.studentdisplay();
| 9267b6913e78ebdc08d0f45e82f780e4a597fe90 | [
"JavaScript",
"TypeScript"
] | 9 | TypeScript | mendajayaram/GitDemoUst | 20e7d8a5cceea0070f097415c56f7445f776df6a | f2660a8035d279bb4285d09bf3dd763f64b9cc69 | |
refs/heads/master | <file_sep>const mongoose = require('mongoose');
const schema = mongoose.Schema;
// We don't have to include the "id:" field because MongoDB
// will create its own
const authorSchema = new schema({
name: String,
age: Number
});
// making a model (collection) of authors that contains objects
// that look like the "authorSchema" schema
module.exports = mongoose.model('Author', authorSchema);<file_sep>const express = require('express');
const graphqlHTTP = require('express-graphql');
const schema = require('./schema/schema');
const mongoose = require('mongoose');
const app = express();
// connect to mLab database
mongoose.connect('mongodb://jenn:<EMAIL>:51022/gql-ninja');
// once a connection is made, fire off a function
mongoose.connection.once('open', () => {
console.log('Connected to database')
});
// set up middleware. when a GraphQL request is made it is
// handed off to the express-graphql function
app.use('/graphql',graphqlHTTP({
// below ES6 version of saying schema: schema
schema,
graphiql: true
}));
app.listen(4000, () => {
console.log('now listening for requests on port 4000');
}); | 405b8c7b180b6239b27b0e6b752a31ff1518ac0d | [
"JavaScript"
] | 2 | JavaScript | pelaej/graphql_playlist | 73d64ada792d2ad1199fce5aa5255a7db51a2e70 | 88dbc5804752761774cbb50460740f1e14a1abe2 | |
refs/heads/master | <repo_name>andreas-04/twitbot<file_sep>/twitter_bot.py
import random
def memify(text):
new = []
for c in text:
r = random.randint(0, 1)
if r:
new.append(c.upper())
else:
new.append(c.lower())
return ''.join(new)
print(memify("hello my name is whasso i am a cool guy")) | 6d4d1703553a51b09ba6de36ffd7830e4bbb2a26 | [
"Python"
] | 1 | Python | andreas-04/twitbot | 2189598397116b79a1dab6f4db55fb447f562dcc | fb2e9c2562b3440b38b7d2c0696300993180e688 | |
refs/heads/master | <file_sep>import axios from "axios"
export const getUserList=(data)=>axios.post("user/lists",data)//获取用户列表
export const received=(order_id,partment)=>axios.post("order/receive",{order_id,partment})//接收
export const getUserMsg=(user_id)=>axios.get("user/get",user_id)//根据user_id获取用户信息
export const saveRole=(data)=>axios.post("user/save_role",data)//设置用户角色
export const setBlacklist=(user_id,operate)=>axios.put("user/update_blacklist",{user_id,operate})//用户黑名单
export const getProductList=(page,per_page)=>axios.post("product/lists",{page,per_page})
export const getSpecLists=(product_id)=>axios.post("product/spec_lists",product_id)
export const addProduct =(product_code,product_name,product_unit)=>axios.post("product/add",{product_code,product_name,product_unit})//新增商品
export const updateProduct =(product_id,product_code,product_name,product_unit)=>axios.put("product/update",{product_id,product_code,product_name,product_unit})//根据product_id编辑产品信息
export const delProduct =(product_id)=> axios.delete("product/delete",{params:{product_id}})//删除商品
export const saveSpec =(product_id,product_specs)=>axios.post("product/save_spec",{product_id,product_specs})//保存产品对应规格信息
export const getBySearch =(search_name)=>axios.post("product/get_by_search",{search_name})//根据产品代码或名称获取产品信息
export const getShiGongLists =(page,per_page)=>axios.post("shigong/lists",{page,per_page})//获取施工队列表
export const addShiGong =(shigong_name,contact_name,contact_phone)=>axios.post("shigong/add",{shigong_name,contact_name,contact_phone})//添加施工队
export const updateShiGong =(shigong_id,shigong_name,contact_name,contact_phone)=>axios.put("shigong/update",{shigong_id,shigong_name,contact_name,contact_phone})//编辑施工队记录
export const delShiGong =(shigong_id)=>axios.delete("shigong/del",{params:{shigong_id}})//编辑施工队记录
export const getOrderMsg =(order_id)=>axios.get("order/get",{params:{order_id}})//添加施工队
<file_sep>import axios from "axios"
export const getCangkuLists=(data)=>axios.post("cangku/lists",data);
export const getPeiliaoList=(order_id)=>axios.get("cangku/peiliao_lists",{params:{order_id}});
export const completePeiliao=(order_id)=>axios.put("cangku/complete_peiliao",{order_id});
export const getDesign=(order_id)=>axios.get("cangku/get_design",{params:{order_id}});
export const arrangeShigong=(order_id,shigong_id)=>axios.post("cangku/arrange_shigong",{order_id,shigong_id});
export const confirmLingliao=(order_id)=>axios.put("cangku/confirm_lingliao",{order_id});
export const savePeiliao=(data)=>axios.post("cangku/save_peiliao",data);
export const completeShigong=(order_id)=>axios.put("cangku/complete_shigong",{order_id});
export const jiesuan=(order_id)=>axios.put("cangku/jiesuan_liaodan",{order_id});
export const getShigong=(order_id)=>axios.get("cangku/get_shigong",{params:{order_id}});
export const updateShigong=(order_id,shigong_id)=>axios.put("cangku/update_shigong",{order_id,shigong_id});
export const getcheck=()=>axios.get("cangku/check");
<file_sep>import axios from "axios"
export const getFengKongLists=(data)=>axios.post("fengkong/lists",data);
export const Firstinstance=(data)=>axios.put("fengkong/yishen",data);
export const getPeiliaoLists=(order_id)=>axios.get("fengkong/peiliao_lists",{params:{order_id}});
export const savePeiliao=(data)=>axios.post("fengkong/save_peiliao",data);
export const commitProspect=(data)=>axios.put("fengkong/commit_prospect",data);
export const getProspect=(order_id)=>axios.get("fengkong/get_prospect",{params:{order_id}});
export const getReason2=(order_id)=>axios.get("fengkong/get_reason",{params:{order_id}});
export const getcheck=()=>axios.get("fengkong/check");
<file_sep>import axios from "axios"
export const accountInfo=(login_name,password,remember)=>axios.post("user/login",{login_name,password,remember})
export const getRegisterMess=(login_name,verify_code,password)=>axios.post("user/login",{login_name,verify_code,password})//用户注册
export const weixin=(code)=>axios.get("user/weixin_login",{params:{code}})//用户注册
export const getPhoneNum=(phone)=>axios.post("user/phone_status",{phone})//手机号码存在不存在接口
export const getverify=(type,phone)=>axios.post("notify/verify_code",{type,phone})
export const logout=()=>axios.post("user/logout")
export const getPhoneAllMess=(phone,verify_code,new_password)=>axios.post("user/pwd_reset_phone",{phone,verify_code,new_password})//发送手机验证码重置用户密码
export const imageUpload =(file)=>axios.post("upload_image",file)/*上传图片接口*/
<file_sep>import axios from "axios"
export const getBingWangLists=(data)=>axios.post("bingwang/lists",data);
export const receive=(order_id)=>axios.put("bingwang/receive_data",{order_id});
export const getDataLists=(order_id,type)=>axios.get("bingwang/data_lists",{params:{order_id,type}});
export const getcheck=()=>axios.get("bingwang/check");
export const saveData=(data)=>axios.post("bingwang/save_data",data);
export const firstData=(order_id)=>axios.put("bingwang/first_data",{order_id});
export const secondData=(order_id)=>axios.put("bingwang/second_data",{order_id});
export const getAllData=(order_id)=>axios.all([getDataLists(order_id,1),getDataLists(order_id,2)])
export const allowBeiLiao=(order_id)=>axios.put("bingwang/allow_beiliao",{order_id});
export const bingwangSuccess=(order_id)=>axios.put("bingwang/bingwang_success",{order_id});
export const updateOrder=(data)=>axios.put("bingwang/update_order",data);
<file_sep>export default{
//删除空对象
methods:{
beforeAvatarUpload(file) {
const isPic = ((file.type === 'image/jpeg') || (file.type === 'image/jpg') || (file.type === 'image/png'));
const isLt6M = file.size / 1024 / 1024 < 10;
if (!isPic) {
this.$message.error('上传图片只能是jpg/png格式!');
}
if (!isLt6M) {
this.$message.error('上传图片大小不能超过10MB!');
}
return isPic && isLt6M;
},
error(err,file, fileList){
console.log(err);
this.$message.error("图片上传失败");
}
}
}
<file_sep>import axios from 'axios'
import store from '@/store'
// axios 配置
axios.defaults.timeout = 15000
//axios.defaults.headers.common["content-type"]="multipart/form-data"
axios.defaults.baseURL = '/admin/'
// http request 拦截器
axios.interceptors.request.use(function (config) {
return config
}, function (err) {
return Promise.reject(err)
})
// http response 拦截器
axios.interceptors.response.use(
response => {
return response
},
err => {
if (err && err.response) {
switch (err.response.status) {
case 400:
err.message = '请求错误'
if(err.response.data.errcode==40015){
store.dispatch("doLoginOut",{
"user_id": "",
"is_admin": "",
"phone": "",
"nick_name": ""
});
}
break
case 401:
err.message = '未授权,请登录'
break
case 403:
err.message = '拒绝访问'
break
case 404:
err.message = `请求地址出错: ${err.response.config.url}`
break
case 408:
err.message = '请求超时'
break
case 500:
err.message = '服务器内部错误'
break
case 501:
err.message = '服务未实现'
break
case 502:
err.message = '网关错误'
break
case 503:
err.message = '服务不可用'
break
case 504:
err.message = '网关超时'
break
case 505:
err.message = 'HTTP版本不受支持'
break
default:
}
}
return Promise.reject(err)
})
export default axios
<file_sep>import {saveData} from '@/api/gird'
export default{
//删除空对象
data(){
return {
dataList:{
"order_id":"",
"type":"",
"datas":[]
},
}
},
methods:{
save(fileList,type){
//发送请求
this.dataList.datas=[];
type==5?this.dataList.type=1:this.dataList.type=2
for(let val of fileList){
let obj={
"image_url":val.response.path
};
if(val.data_id){
obj.data_id=val.data_id
}
this.dataList.datas.push(obj)
}
saveData(this.dataList)
.then(({
data
}) => {
this.isTable=true;
})
.catch(({
response: {
data
}
}) => { //与后台交互时出现的错误信息
this.$message.error(data.errorcmt);
})
},
}
}
<file_sep>import axios from "axios"
export const createOrder=(data)=>axios.post("yewu/create",data);
export const getYewuLists=(data)=>axios.post("yewu/lists",data);
export const getcheck=()=>axios.get("yewu/check");
export const getSchedule=(order_id)=>axios.get("yewu/get_schedule",{params:{order_id}});
export const getReason1=(order_id)=>axios.get("yewu/get_reason",{params:{order_id}});
export const sendMsg=(order_id)=>axios.put("yewu/send_data",{order_id});
export const communicate=(order_id,result)=>axios.put("yewu/communicate",{order_id,result});
export const deleteOrder=(orders)=>axios.post("admin/delete_order_batch",{orders});
export const applyTel=(phone)=>axios.get("yewu/choose",{params:{phone}});
<file_sep>import axios from "axios"
export const getYanshouLists=(data)=>axios.post("yanshou/lists",data);
export const getcheck=()=>axios.get("yanshou/check");
export const getShigong=(order_id)=>axios.get("yanshou/get_shigong",{params:{order_id}});
export const confirmYanshou=(order_id)=>axios.put("yanshou/confirm_yanshou",{order_id});
| ebeac2a808616033da7bd783e2d177eb8eab5b2d | [
"JavaScript"
] | 10 | JavaScript | luotingv1/ldgf | 07892373575096fdf0d696ff9f44ca42c32c94ed | 6ec9e3380b4fc694469955b4c19dfbdcf357b394 | |
refs/heads/master | <file_sep><?php
$mysqli = new mysqli("gcoej.ac.in", "gcoejjif_sdcw", "sdc@2016", "gcoejjif_data_site") or die("Unable to Connect..");
?>
<header id="header"><!--BEGIN: Header-->
<section class="header-top-section"><!--BEGIN: Header Top Section-->
<div class="row p-tb10 ">
<!--BEGIN: Logo-->
<div class="medium-4 column" align="center">
<div class="logo-section">
<a href="www.gcoej.ac.in" title="CCVVC">
<img src="images/mech.png">
</a>
</div>
</div>
<!--END: Logo-->
</div>
</section><!--END: Header Top Section-->
<section class="menu-section"><!--BEGIN: Navigation-->
<div class="row">
<div class="medium-12 large-12 column">
<a href="#mobile_menu" class="menu-icon" aria-expanded="false"><span></span></a>
<nav class="navigation">
<ul id="menu-tnb" class="menu"><li id="menu-item-55" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item menu-item-home menu-item-has-children menu-item-55"><a href="index.php">Home</a>
<ul class="sub-menu">
<li id="menu-item-111" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-111"><a href="indexc4a7.php?page_id=59">Objectives</a></li>
</ul>
</li>
<li id="menu-item-118" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-118"><a href="#">People</a>
<ul class="sub-menu">
<li id="menu-item-141" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-141"><a href="indexed66.php?page_id=135">Faculty</a></li>
<li id="menu-item-161" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-161"><a href="indexffc4.php?page_id=142">Staff</a></li>
<li id="menu-item-113" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-113"><a href="index1e11.php?page_id=65">Student</a></li>
</ul>
</li>
<li id="menu-item-119" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-119"><a href="#">Calendar</a>
<ul class="sub-menu">
<li id="menu-item-114" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-114"><a href="index57fd.php?page_id=63">Time Table</a></li>
<!-- <li id="menu-item-113" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-113"><a href="index85da.php?page_id=65">Events</a></li> -->
<li id="menu-item-112" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-112"><a href="https://www.gcoej.ac.in/download/Final_Academic_Calendar_SY_2017-180.pdf">Academic Calendar</a></li>
</ul>
</li>
<li id="menu-item-117" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-117"><a href="#">About Us</a>
<ul class="sub-menu">
<li id="menu-item-121" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-121"><a href="index0743.php?page_id=69">About</a></li>
<li id="menu-item-120" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-120"><a href="index8090.php?page_id=115">PEOs And POs</a></li>
<li id="menu-item-184" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-184"><a href="index2dd6.php?page_id=179">Short Term Courses</a></li>
<li id="menu-item-174" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-174"><a href="index30c2.php?page_id=172">Students Achievement</a></li>
</ul>
</li>
<li id="menu-item-171" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-171"><a href="#">Infrastructure</a>
<ul class="sub-menu">
<li id="menu-item-113" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-113"><a href="index85da.php?page_id=65">Laboratories</a></li>
</ul>
</li>
<li id="menu-item-191" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-191"><a href="#">BoS</a>
<ul class="sub-menu">
<li id="menu-item-193" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-193"><a href="index449e.php?page_id=186">BoS Composition</a></li>
<li id="menu-item-192" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-192"><a href="indexc55d.php?page_id=188">BoS MoM</a></li>
</ul>
</li>
<ul id="menu-tnb" class="menu"><li id="menu-item-55" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item menu-item-home menu-item-has-children menu-item-55"><a href="4aa3.php">Gallery</a></li></ul>
</ul> </nav>
</div>
</div>
</section><!--END: Navigation-->
</header><!--END: Header-->
<file_sep><!DOCTYPE html>
<html lang="en-US" class="no-js">
<!-- Mirrored from www.iitg.ernet.in/civil/site/ by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 09 Feb 2018 04:21:51 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8" /><!-- /Added by HTTrack -->
<?php
include("head.php");
?>
<body class="home page-template page-template-page-templates page-template-homepage page-template-page-templateshomepage-php page page-id-2">
<div id="wrapper" class="site">
<?php
include("header.php");
?>
<div class="page-content-section">
<!--BEGIN: Intro -->
<section id="section_intro">
<div class="row">
<div class="medium-9 columns">
<div class="content-intro box-shadow">
<!-- meta slider -->
<div style="max-width: 1000px;" class="metaslider metaslider-flex metaslider-45 ml-slider">
<div id="metaslider_container_45">
<div id="metaslider_45">
<ul class="slides">
<li style="display: block; width: 100%;" class="slide-243 ms-image"><img src="images/1.jpg" height="400" width="1000" alt="" class="slider-45 slide-243" /></li>
<li style="display: none; width: 100%;" class="slide-250 ms-image"><img src="images/3.jpg" height="400" width="1000" alt="" class="slider-45 slide-250" /></li>
<li style="display: none; width: 100%;" class="slide-248 ms-image"><img src="images/23.jpg" height="400" width="1000" alt="" class="slider-45 slide-248" /></li>
<li style="display: none; width: 100%;" class="slide-246 ms-image"><img src="images/19.jpg" height="400" width="1000" alt="" class="slider-45 slide-246" /></li>
</ul>
</div>
</div>
<script type="text/javascript">
var metaslider_45 = function($) {
$('#metaslider_45').addClass('flexslider'); // theme/plugin conflict avoidance
$('#metaslider_45').flexslider({
slideshowSpeed:3000,
animation:"fade",
controlNav:true,
directionNav:true,
pauseOnHover:true,
direction:"horizontal",
reverse:false,
animationSpeed:600,
prevText:"<",
nextText:">",
slideshow:true
});
};
var timer_metaslider_45 = function() {
var slider = !window.jQuery ? window.setTimeout(timer_metaslider_45, 100) : !jQuery.isReady ? window.setTimeout(timer_metaslider_45, 1) : metaslider_45(window.jQuery);
};
timer_metaslider_45();
</script>
</div>
<!--// meta slider--> </div><!--/.content-intro box-shadow-->
</div><!--medium-9 columns-->
<div class="medium-3 columns">
<aside>
<div class="list-title"><h2>News & Announcements</h2></div>
<ul class="update-list" role="listbox">
<li class="item"><div class="update-content"><h5>Departmental Time-Table: Jan-April 2018, please click <a target="_blank" href="https://gcoej.ac.in/?page=Mjk="><b><i><font color="red">here.</font></i></b></a></h5><br><br><br><br><br><br><br><br><br></div></li>
</ul>
</aside>
<!-- <aside>
<div class="list-title"><h2>Ph.D. Admission December 2017</h2></div>
<ul class="update-list" role="listbox">
<li class="item"><div class="update-content"><h1><p align="justify"><img src="http://www.iitg.ernet.in/civil/news/new.gif" height="15" width="25" /> List of Shortlisted Candidates for the Selection process of Ph.D. Admission(December 2017) in the Department of Civil Engineering, IIT Guwahati to be held on 6th-7th December, 2017, please click
<a href="http://www.iitg.ernet.in/civil/Shortlisted%20Candidates%20for%20the%20Selection%20process%20of%20Ph.%20D%20Admission%20(December%202017).pdf" target="_blank">here.</a>
</br></br><img src="http://www.iitg.ernet.in/civil/news/new.gif" height="15" width="25" /> Specimen Call Letter and Syllabus for Written Test: Ph.D. Admission (December, 2017), please click <a href="http://www.iitg.ernet.in/civil/Phd%20Dec%202017%20Admission%20Call%20letter_updated.pdf" target="_blank">here.</a>
</br></br><img src="http://www.iitg.ernet.in/civil/news/new.gif" height="15" width="25" /> Hostel Accommodation for Ph.D. Participants, please click <a href="http://www.iitg.ernet.in/civil/ACCOMODATION%20FOR%20Ph.D.%20PARTICIPANTS.pdf" target="_blank">here.</a>
</p>
</p></h1></div></li>
</ul>
</aside>-->
</div>
</div>
</section>
<!--END: Intro -->
<!--BEGIN: Progrsms -->
<section class="content-section">
<div class="row">
<!-- <div class="medium-3 small-6 columns">
<aside>
<div class="list-title"><h2>Students Corner</h2></div>
<ul class="update-list" role="listbox">
<li class="item">
<div class="update-content">
<h5><a href="indexa558.php?studentscorner=m-tech-ph-d">M.Tech./Ph.D.</a></h5>
<p>List of Experiments for Traffic Engineering Lab, (CE 584), please click<a hre...</p>
</div>
</li>
<li class="item">
<div class="update-content">
<h5><a href="index457a.php?studentscorner=b-tech">B.Tech.</a></h5>
<p><ul>
<li><span>List of Experiments for Survey Laboratory, (CE 213), please...</p>
</div>
</li>
</ul>
</aside>
<aside>
<div class="list-title"><h2>Contact Us</h2></div>
<div class="form-wrapper">
<p><b>Head of Department</b></p>
<p>Department of Electrical Engineering <p>
Government Colloge Of Engineering </p><p>
Jalgaon
</p>
<p>Phone: </p>
<p>Fax: </p>
<p>
Email:</p>
</div>
</aside>
</div> -->
<div class="medium-9 small-9 columns">
<aside class="m-b25">
<div class="inner-gallery">
<!--meta slider 49 not found -->
<!--/.inner-gallery-->
<div class="gallery-content">
<p align="justify">The department of Mechanical Engineering was started in the academic year 1996-1997. Last two decades efforts have been taken for the development of laboratories as per curriculum of North Maharashtra University Jalgaon and A.I.C.T.E. norms. From academic year 2014-15 the institute got Autonomy. Under autonomy Department of Mechanical Engineering has started implementing Credit Based System.<br>
In order to keep the students updated with latest technology and industrial practices, expert lectures and visits to nearby industries are arranged The number of students qualifying GATE Examinations is also increasing every year.</p>
</div><!--/.gallery-content-->
</aside>
<aside>
<div class="recent-updates">
<section class="directors-section">
<div class="list-title"><h2>Message from the Head of the Department</h2></div>
<div class="dir-description">
<p align="justify">The department of Mechanical Engineering was started in the academic year 1996-1997. Last two decades efforts have been taken for the development of laboratories as per curriculum of North Maharashtra University Jalgaon and A.I.C.T.E. norms. From academic year 2014-15 the institute got AutonomOur students have attended and demonstrated excellent skills in various paper Presentations, seminars and workshops. To enhance personality of our students, we conduct various personality development programs, Group Discussions for Competitive Exams under MESA (Mechanical Engineering Students Association).We also hold honour of conducting Techno-Arena (A national level Technical Event) every year.
</p>
</div>
</section>
</div>
</aside>
</div>
<div class="medium-3 small-6 columns">
<!-- <aside>
<div class="list-title"><h2>News & Announcements</h2></div>
<ul class="update-list" role="listbox">
<li class="item"><div class="update-content"><h5>Departmental Time-Table: Jan-April 2018, please click <a target="_blank"href="http://www.iitg.ernet.in/civil/Time%20Table%20Jan-April%202018_Civil%20Engineering.pdf"><b><i><font color="red">here.</font></i></b></a></h5></div></li>
</ul>
</aside>
-->
<aside>
<div class="list-title"><h2>Events</h2></div>
<ul class="update-list" role="listbox">
<li class="item">
<div class="update-content">
<h5><a target="_blank" href="https://gcoej.ac.in/?page=MzI=#parentVerticalTab3">Read More</a></h5>
<p> Mechanical Engineering Students Association (MESA)</p>
<br><br><br><br><br><br><br>
</div>
</li></ul>
</aside>
<!-- <aside>
<div class="list-title"><h2>Recent Publications</h2></div>
<ul class="update-list" role="listbox">
<li class="item">
<div class="update-content">
<h5><a href="indexb994.php?currentresearch=consolidated-publications-2012-2017">Consolidated Publications (2012-2017)</a></h5>
<p><a href="wp-content/uploads/2017/09/papersof-ce-dept-since-2012.pdf" target="_blank" rel="noopener noreferrer">click here to view details</a></p>
</div>
</li>
<li class="item">
<div class="update-content">
<h5><a href="index15b5.php?currentresearch=consolidated-publications-2009-2013">Consolidated Publications (2009-2013)</a></h5>
<p><a href="https://goo.gl/2so6n1" target="_blank" rel="noopener noreferrer">click here to view details</a></p>
</div>
</li>
</ul>
</aside>
-->
</div>
</div>
</section>
<!--END: Programs -->
<?php
include("footer.php");
?>
<script src="wp-content/themes/iitg/js/plugins.js"></script>
<script src="wp-content/themes/iitg/js/site.js"></script>
</div><!--END: WRAPPER-->
<nav id="mobile_menu">
<ul id="menu-tnb-1" class="menu"><li class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item menu-item-home menu-item-has-children menu-item-55"><a href="index.php">Home</a>
<ul class="sub-menu">
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-111"><a href="indexc4a7.php?page_id=59">Objectives</a></li>
</ul>
</li>
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-119"><a href="#">Academic</a>
<ul class="sub-menu">
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-114"><a href="index57fd.php?page_id=63">Students Corner</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-113"><a href="index85da.php?page_id=65">Laboratories/Divisions</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-112"><a href="index3d3a.php?page_id=67">Course Structure</a></li>
</ul>
</li>
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-117"><a href="#">Research</a>
<ul class="sub-menu">
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-121"><a href="index0743.php?page_id=69">Major Research Areas</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-120"><a href="index8090.php?page_id=115">Sponsored Projects</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-127"><a href="indexf62f.php?page_id=122">Consultancies</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-130"><a href="index7d80.php?page_id=128">Theses / Reports</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-134"><a href="index08d2.php?page_id=131">Publications</a></li>
</ul>
</li>
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-118"><a href="#">People</a>
<ul class="sub-menu">
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-141"><a href="indexed66.php?page_id=135">Faculty</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-161"><a href="indexffc4.php?page_id=142">Scientific Officer</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-159"><a href="index6b58.php?page_id=151">Technical Staff</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-158"><a href="index14cc.php?page_id=153">Office Staff</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-160"><a href="index82f9.php?page_id=148">Students</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-157"><a href="indexcbbc.php?page_id=155">Alumni</a></li>
</ul>
</li>
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-171"><a href="#">Activities</a>
<ul class="sub-menu">
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-174"><a href="index30c2.php?page_id=172">Students Achievement</a></li>
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-175"><a href="http://www.iitg.ernet.in/ace/">ACE</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-185"><a href="indexebb0.php?page_id=176">QIP</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-184"><a href="index2dd6.php?page_id=179">Short Term Courses/Workshops</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-183"><a href="index5931.php?page_id=181">Summer Training</a></li>
</ul>
</li>
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-191"><a href="#">Information</a>
<ul class="sub-menu">
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-193"><a href="index449e.php?page_id=186">Placement Information</a></li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-192"><a href="indexc55d.php?page_id=188">Departmental Committees</a></li>
</ul>
</li>
</ul>
</nav>
<link rel='stylesheet' id='metaslider-flex-slider-css' href='wp-content/plugins/ml-slider/assets/sliders/flexslider/flexslider.css' type='text/css' media='all' property='stylesheet' />
<link rel='stylesheet' id='metaslider-public-css' href='wp-content/plugins/ml-slider/assets/metaslider/public.css' type='text/css' media='all' property='stylesheet' />
<script type='text/javascript' src='wp-content/plugins/contact-form-7/includes/js/jquery.form.mind03d.js?ver=3.51.0-2014.06.20'></script>
<script type='text/javascript'>
/* <![CDATA[ */
var _wpcf7 = {"recaptcha":{"messages":{"empty":"Please verify that you are not a robot."}}};
/* ]]> */
</script>
<script type='text/javascript' src='wp-content/plugins/contact-form-7/includes/js/scripts4906.js?ver=4.7'></script>
<script type='text/javascript' src='wp-includes/js/wp-embed.min66f2.js?ver=4.7.5'></script>
<script type='text/javascript' src='wp-content/plugins/ml-slider/assets/sliders/flexslider/jquery.flexslider-min9d52.js?ver=3.5.1'></script>
</body>
<!-- Mirrored from www.iitg.ernet.in/civil/site/ by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 09 Feb 2018 04:23:16 GMT -->
</html>
| 15f418021d5d9b317106653ecdb7c68ee05801b1 | [
"PHP"
] | 2 | PHP | SDC-GCOEJ/GC-Mechanical | 878ec9b7c1b916b640157acf795e423a216064f4 | efbfff953ea2ca6c3e05c1414f86ce7654fb2344 | |
refs/heads/master | <repo_name>Diogo-Ferreira/school-work-qt<file_sep>/build-Serie5exercice1-Desktop_Qt_5_5_0_GCC_64bit-Debug/moc_widget.cpp
/****************************************************************************
** Meta object code from reading C++ file 'widget.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../Serie5exercice1/widget.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'widget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.5.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_Convert_t {
QByteArrayData data[6];
char stringdata0[85];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_Convert_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_Convert_t qt_meta_stringdata_Convert = {
{
QT_MOC_LITERAL(0, 0, 7), // "Convert"
QT_MOC_LITERAL(1, 8, 19), // "onBtnComputeClicked"
QT_MOC_LITERAL(2, 28, 0), // ""
QT_MOC_LITERAL(3, 29, 16), // "onBtnQuitClicked"
QT_MOC_LITERAL(4, 46, 18), // "onBtnReInitClicked"
QT_MOC_LITERAL(5, 65, 19) // "onConversionChanged"
},
"Convert\0onBtnComputeClicked\0\0"
"onBtnQuitClicked\0onBtnReInitClicked\0"
"onConversionChanged"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_Convert[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
4, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 34, 2, 0x0a /* Public */,
3, 0, 35, 2, 0x0a /* Public */,
4, 0, 36, 2, 0x0a /* Public */,
5, 2, 37, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::Int, QMetaType::Bool, 2, 2,
0 // eod
};
void Convert::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Convert *_t = static_cast<Convert *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->onBtnComputeClicked(); break;
case 1: _t->onBtnQuitClicked(); break;
case 2: _t->onBtnReInitClicked(); break;
case 3: _t->onConversionChanged((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break;
default: ;
}
}
}
const QMetaObject Convert::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_Convert.data,
qt_meta_data_Convert, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *Convert::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *Convert::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_Convert.stringdata0))
return static_cast<void*>(const_cast< Convert*>(this));
return QDialog::qt_metacast(_clname);
}
int Convert::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 4)
qt_static_metacall(this, _c, _id, _a);
_id -= 4;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 4)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 4;
}
return _id;
}
QT_END_MOC_NAMESPACE
<file_sep>/serie7exercice3/picturezone.h
#ifndef PICTUREZONE_H
#define PICTUREZONE_H
#include <QWidget>
#include <QtWidgets>
class PictureZone : public QWidget
{
Q_OBJECT
public:
explicit PictureZone(QWidget *parent = 0);
void updatePicture(QString);
private:
void paintEvent(QPaintEvent *);
QPixmap *picture;
public slots:
};
#endif // PICTUREZONE_H
<file_sep>/serie7exercice1/widget.cpp
#include "widget.h"
Widget::Widget(QWidget *parent) : QGraphicsView(parent)
{
qgScene = new QGraphicsScene(this);
setScene(qgScene);
QGraphicsEllipseItem *ellipse = new QGraphicsEllipseItem(10,10,500,300);
QGraphicsTextItem *ellipseText = new QGraphicsTextItem("Add ellipse");
ellipseText->setParentItem(ellipse);
ellipseText->moveBy(ellipse->rect().width()+ 50,ellipse->rect().height()*0.5);
ellipse->setSpanAngle(120 * 16);
ellipse->setRotation(30 * 16);
qgScene->addItem(ellipse);
}
Widget::~Widget()
{
}
<file_sep>/serie7exercice3/picturezone.cpp
#include "picturezone.h"
PictureZone::PictureZone(QWidget *parent) : QWidget(parent)
{
}
void PictureZone::updatePicture(QString absPath)
{
picture = new QPixmap(absPath);
}
void PictureZone::paintEvent(QPaintEvent *)
{
QPainter paint(this);
if(picture != NULL)
{
paint.drawPixmap(0,0,width(),height(),*picture);
}
}
<file_sep>/Serie5exercice1/widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QtWidgets>
class Convert : public QDialog
{
Q_OBJECT
public:
Convert(QDialog *parent = 0);
~Convert();
private:
//Widgets
QButtonGroup *radGroup ;
QRadioButton *celToFaRadBtn ;
QRadioButton *faToCelRadBtn ;
QLineEdit *tempInput ;
QPushButton *reInitBtn ;
QPushButton *quitBtn ;
QPushButton *computeBtn ;
QLCDNumber *computeOut ;
QLabel *convLbl ;
public slots:
void onBtnComputeClicked();
void onBtnQuitClicked();
void onBtnReInitClicked();
void onConversionChanged(int,bool);
};
#endif // WIDGET_H
<file_sep>/Serie5exercice1/widget.cpp
#include "widget.h"
Convert::Convert(QDialog *parent):QDialog(parent)
{
setFixedWidth(320);
setFixedHeight(150);
radGroup = new QButtonGroup(this);
celToFaRadBtn = new QRadioButton("&Celsius -> Farenheit",this);
faToCelRadBtn = new QRadioButton("&Farenheit -> Celsius",this);
tempInput = new QLineEdit("0",this);
reInitBtn = new QPushButton("&Ré-initialiser",this);
quitBtn = new QPushButton("&Quitter",this);
computeBtn = new QPushButton("C&alculer",this);
computeOut = new QLCDNumber(11,this);
convLbl = new QLabel("F°",this);
radGroup->addButton(celToFaRadBtn);
radGroup->addButton(faToCelRadBtn);
faToCelRadBtn->setChecked(true);
computeOut->display("--------");
computeOut->setSegmentStyle(QLCDNumber::Flat);
tempInput->setValidator( new QDoubleValidator(0, 100, 2, this) );
QGridLayout *grid = new QGridLayout(this);
grid->addWidget(celToFaRadBtn,0,0,1,2);
grid->addWidget(faToCelRadBtn,1,0,1,2);
grid->addWidget(tempInput,2,0);
grid->addWidget(convLbl,2,1);
grid->addWidget(computeOut,2,2);
grid->addWidget(reInitBtn,3,0);
grid->addWidget(quitBtn,3,1);
grid->addWidget(computeBtn,3,2);
setLayout(grid);
connect(computeBtn,SIGNAL(clicked()),this,SLOT(onBtnComputeClicked()));
connect(quitBtn,SIGNAL(clicked()),this,SLOT(onBtnQuitClicked()));
connect(reInitBtn,SIGNAL(clicked()),this,SLOT(onBtnReInitClicked()));
connect(radGroup,SIGNAL(buttonToggled(int,bool)),this,SLOT(onConversionChanged(int,bool)));
}
Convert::~Convert()
{
}
void Convert::onConversionChanged(int id,bool isChecked)
{
if(isChecked && id == -2)
{
convLbl->setText("C°");
}
else if(isChecked && id == -3)
{
convLbl->setText("F°");
}
}
void Convert::onBtnComputeClicked()
{
if(celToFaRadBtn->isChecked())
computeOut->display(QString::number(tempInput->text().toDouble() * 9/5 + 32)+ "F°");
else
computeOut->display(QString::number((tempInput->text().toDouble()-32) * 5/9 ) + "C°");
}
void Convert::onBtnQuitClicked()
{
}
void Convert::onBtnReInitClicked()
{
}
<file_sep>/1-LesFormes/mywidget.cpp
#include <QtWidgets>
#include "mywidget.h"
MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
pixmap = new QPixmap("Smiley.jpg");
image = new QImage("Smiley.jpg");
setWindowTitle("Les formes");
setStyleSheet("background-color:white");
resize(800, 650);
}
void MyWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
// Peu performant : appelé à chaque rafraichissement !
// painter.setBrush(Qt::white);
// painter.setPen(Qt::white);
// painter.drawRect(0, 0, width(), height());
painter.setPen(Qt::blue);
painter.drawText(100, 20, "Les différentes formes avec Qt");
painter.setPen(Qt::black);
painter.drawLine(0, 0, width(), height());
// Dessiner une tranche de gâteau
QRect rectangle(10, 40, 200, 100);
// The startAngle and spanAngle must be specified in 1/16th of a degree,
// i.e. a full circle equals 5760 (16 * 360).
// Positive values for the angles mean counter-clockwise
// while negative values mean the clockwise direction.
// Zero degrees is at the 3 o'clock position.
int startAngle = 30 * 16;
int spanAngle = 120 * 16;
painter.setBrush(Qt::blue);
painter.drawPie(rectangle, startAngle, spanAngle);
// Dessiner un rectangle
painter.setBrush(Qt::red);
painter.drawRect(10, 100, 200, 100);
// Dessiner un polygone
static const QPoint points[4] = {
QPoint(110, 280),
QPoint(120, 210),
QPoint(180, 230),
QPoint(190, 270)};
painter.setBrush(Qt::yellow);
painter.drawPolygon(points, 4);
// Dessiner un QPixmap
painter.drawPixmap(10, 280, 50, 50, *pixmap);
// Dessiner un QImage
QRect rectangle2(10, 350, 50, 50);
painter.drawImage(rectangle2, *image);
// Dessiner un rectangle arrondi
painter.drawRoundedRect(10, 420, 200, 100, 20.0, 20.0);
// Dessiner une ellipse
painter.setBrush(Qt::green);
painter.drawEllipse(10, 540, 100, 50);
// Dessiner les textes
painter.setPen(Qt::black);
painter.drawText(300, 70, "drawPie");
painter.drawText(300, 170, "drawRect");
painter.drawText(300, 250, "drawPolygon");
painter.drawText(300, 300, "drawPixmap");
painter.drawText(300, 380, "drawImage");
painter.drawText(300, 470, "drawRoundedRect");
painter.drawText(300, 570, "drawEllipse");
painter.drawText(530, 400, "drawLine");
}
<file_sep>/1-LesFormes/mywidget.h
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
class MyWidget : public QWidget
{
Q_OBJECT
protected:
void paintEvent(QPaintEvent *);
public:
MyWidget(QWidget *parent = 0);
private:
QPixmap *pixmap;
QImage *image;
};
#endif
<file_sep>/2-Dessin2D/mywidget.cpp
#include <QPainter>
#include <QPaintEvent>
#include <QPalette>
#include <QWidget>
#include <QDebug>
#include "mywidget.h"
MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
setWindowTitle("Disques");
resize(400, 300);
nbPaint = 0;
dessinEnCours = false;
// QPalette pal = QPalette(Qt::black, Qt::white);
// setPalette(pal);
setStyleSheet("background-color: #E1E1E1");
}
void MyWidget::paintEvent(QPaintEvent *)
{
QPainter paint(this);
nbPaint++;
paint.drawText(10, 20, QString("Nombre d'appels de paintEvent() : %1").arg(nbPaint));
paint.drawText(10, 35, QString("Nombre de disques : %1").arg(listePoints.size()));
qDebug() << nbPaint << ": " << point.rx() << ", " << point.ry();
paint.setPen(Qt::red);
paint.setBrush(Qt::red);
foreach(QList<QPoint> l , listeEnsemblePoints)
{
for (int i=0; i < l.size()-1; i++)
{
paint.drawLine(l.at(i),l.at(i+1));
}
}
}
void MyWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
dessinEnCours = true;
point = event->pos();
listePoints.append(point);
listeEnsemblePoints.append(listePoints);
update();
}
}
void MyWidget::mouseMoveEvent(QMouseEvent *event)
{
if ((event->buttons() & Qt::LeftButton))
{
point = event->pos();
listeEnsemblePoints.last().append(point);
update();
}
}
void MyWidget::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
listePoints.clear();
update();
}
}
<file_sep>/serie7exercice3/mainwindow.cpp
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
fileMenu = menuBar()->addMenu(tr("&Fichier"));
fileMenu->addAction(tr("&Ouvrir Dossier"), this, SLOT(openFolder()), tr("Ctrl+N"));
showMenu = menuBar()->addMenu(tr("&Info"));
showMenu->addAction(tr("&Ouvrir Dossier"), this, SLOT(currentPictureInfo()), tr("Ctrl+I"));
currentPictureIndex = 0;
pictures = new QStringList();
picZone = new PictureZone(this);
setDocumentMode(false);
setCentralWidget(picZone);
picZone->show();
}
MainWindow::~MainWindow()
{
}
void MainWindow::goToPicture(int index)
{
picZone->updatePicture(pictures->at(index));
}
void MainWindow::openFolder()
{
QDir qDirFiles(QFileDialog::getExistingDirectory(this, tr("Open Directory"),
QDir::homePath(),
QFileDialog::ShowDirsOnly));
qDirFiles.setFilter(QDir::Files);
QFileInfoList files = qDirFiles.entryInfoList();
foreach (QFileInfo file, files){
if(file.suffix().contains("jpg") || file.suffix().contains("png") || file.suffix().contains("jpeg"))
pictures->append(file.absoluteFilePath());
}
picZone->updatePicture(pictures->at(currentPictureIndex));
}
void MainWindow::currentPictureInfo()
{
qDebug() << pictures->at(currentPictureIndex) ;
}
<file_sep>/2-Dessin2D/stable.h
// Utilisation d'entêtes précompilées (PCH)
// Voir #http://qt-project.org/doc/qt-5/qmake-precompiledheaders.html
#ifndef STABLE_H
#define STABLE_H
#if defined __cplusplus
#include <QApplication>
#include <QPainter>
#include <QPaintEvent>
#include <QPalette>
#include <QWidget>
#endif
#endif // STABLE_H
<file_sep>/serie7exercice3/mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtWidgets>
#include "picturezone.h"
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
private:
QMenu *fileMenu;
QMenu *showMenu;
QStringList *pictures;
int currentPictureIndex;
PictureZone *picZone;
public slots:
//Permet de changer d'image actuelle
void goToPicture(int index);
void openFolder();
void currentPictureInfo();
};
#endif // MAINWINDOW_H
<file_sep>/2-Dessin2D/mywidget.h
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
class MyWidget : public QWidget
{
Q_OBJECT
protected:
void paintEvent(QPaintEvent *);
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
public:
MyWidget(QWidget *parent = 0);
private:
QList<QPoint> listePoints;
QList<QList<QPoint> > listeEnsemblePoints;
QPoint point;
int nbPaint;
bool dessinEnCours;
};
#endif
| 4839a0aae78c9a92a6806e3daa82d1511aba052c | [
"C",
"C++"
] | 13 | C++ | Diogo-Ferreira/school-work-qt | 2aae8f6b1a7ab5b380e8c32e365dfc9a03c88c9a | 840b5949d5e1beb416e2be1bffa40e166455e681 | |
refs/heads/master | <file_sep>"""Window module"""
import time
import tkinter
from typing import Tuple
from boid import Boid
from vector import Vector
HEIGHT = 1000
WIDTH = 1000
class Window:
"""The main window in which the process will be hosted"""
def __init__(self):
self.window = tkinter.Tk()
self.canvas = tkinter.Canvas(self.window, height=HEIGHT, width=WIDTH)
self.canvas.pack()
self.last_time = time.monotonic()
self.boids = []
def update(self):
"""Event loop body"""
delta_time = time.monotonic() - self.last_time
for boid in self.boids:
#TODO: the rotation is purely part of the boid's internal calculations and needs to be moved out somehow
# possibly delta_time needs to be moved to the main loop and shared
boid.rotation += boid.torque * delta_time
delta = self.bounced_velocity(delta_time, boid)
boid.x_position += delta[0]
boid.y_position += delta[1]
self.canvas.delete(boid.canvas_handle)
boid.canvas_handle = self.canvas.create_polygon(boid.points())
self.last_time = time.monotonic()
self.window.update()
def unconstrained_velocity(self, delta_time: float, boid: Boid) -> Tuple[float, float]:
"""Returns the x and y movements as they are"""
delta_x = boid.x_velocity * delta_time
delta_y = boid.y_velocity * delta_time
return (delta_x, delta_y)
def constrained_velocity(self, delta_time: float, boid: Boid) -> Tuple[float, float]:
"""Returns the x and y movements constrained as though the window edges were a wall"""
delta_x = boid.x_velocity * delta_time
delta_y = boid.y_velocity * delta_time
if self.on_border(boid, delta_x, delta_y):
return (0, 0)
else:
return (delta_x, delta_y)
def bounced_velocity(self, delta_time: float, boid: Boid) -> Tuple[float, float]:
"""Returns the x and y movements, if these would take the boid outside of the window
boundary then (0, 0) is returned and the boid is rotated 180 degrees"""
delta_x = boid.x_velocity * delta_time
delta_y = boid.y_velocity * delta_time
if self.on_border(boid, delta_x, delta_y):
boid.rotation += 3.14
return (0, 0)
else:
return (delta_x, delta_y)
def reflected_velocity(self, delta_time: float, boid: Boid) -> Tuple[float, float]:
"""Returns the x and y movements, if these would take the boid outside of the window
boundary then (0, 0) is returned and the velocity is reflected"""
x_velocity = boid.x_velocity
y_velocity = boid.y_velocity
delta_x = x_velocity * delta_time
delta_y = y_velocity * delta_time
if self.on_border(boid, delta_x, delta_y):
if self.on_vertical_border(boid, delta_y):
x_velocity = -x_velocity
if self.on_horizontal_border(boid, delta_x):
y_velocity = -y_velocity
rotation = Vector(x_velocity, y_velocity).rotation_normalized() * 3.14
if x_velocity < 0:
boid.rotation = rotation
else:
boid.rotation = -rotation
return (0, 0)
else:
return (delta_x, delta_y)
def on_border(self, boid: Boid, delta_x: float, delta_y: float) -> bool:
"""Return true if the movement would take the boid outside of the boundary of the window"""
return (delta_x > 0 and boid.x_position >= WIDTH or delta_x < 0 and boid.x_position < 0 or
delta_y > 0 and boid.y_position >= HEIGHT or delta_y < 0 and boid.y_position < 0)
def on_vertical_border(self, boid: Boid, delta_y: float) -> bool:
"""Return true if the movement would take the boid out of the top or bottom border"""
return delta_y > 0 and boid.y_position >= HEIGHT or delta_y < 0 and boid.y_position < 0
def on_horizontal_border(self, boid: Boid, delta_x: float) -> bool:
"""Return true if the movement would take the boid out of the left or right border"""
return delta_x > 0 and boid.x_position >= WIDTH or delta_x < 0 and boid.x_position < 0
def add_boid(self, boid: Boid):
"""Add a boid to the canvas"""
boid.canvas_handle = self.canvas.create_polygon(boid.points())
self.boids.append(boid)
<file_sep>import time
import tkinter
window = tkinter.Tk()
canvas = tkinter.Canvas(window, height=1000, width=1000)
canvas.pack()
bottom_y = 600
triangle = canvas.create_polygon(400, 400, 600, 400, 500, 600)
for i in range(1, 200):
window.update()
bottom_y += 1
canvas.delete(triangle)
triangle = canvas.create_polygon(400, 400, 600, 400, 500, bottom_y)
time.sleep(0.1)
<file_sep>from vector import Vector
vector = Vector(0, -1)
print(vector.rotation_normalized())
vector = Vector(0, 1)
print(vector.rotation_normalized())
vector = Vector(1, 0)
print(vector.rotation_normalized())
vector = Vector(-1, 0)
print(vector.rotation_normalized())
vector = Vector(4, 1)
print(vector.rotation_normalized())<file_sep>import tkinter
import time
top = tkinter.Tk()
canvas = tkinter.Canvas(top, bg = 'grey', height = 1000, width = 1000)
canvas.pack()
coords = 10,50,240,210
arc = canvas.create_arc(coords, start = 0, extent = 150, fill = 'red')
while True:
#time.sleep(1)
canvas.move(arc, 10, 0)
top.update()
#top.mainloop()<file_sep>import time
clock = time.monotonic()
print(clock)
time.sleep(5)
clock = time.monotonic()
print(clock)<file_sep>"""
Boids module
The three critical rules governing boid behaviour are
1. Separation: Steer away from individual boids
2. Alignment: Steer in a similar direction of local boids
3. Cohesion: Steer toward the center of mass of local boids
"""
from typing import List
from vector import Vector
TRIANGLE_POINTS = (Vector(0, -5), Vector(5, 5), Vector(-5, 5))
VISION_ANGLE = -0.6
SPEED = 50
class Boid:
"""Simple Automaton"""
def __init__(self, radius: float, vision_radius: float,
x_position: float, y_position: float, rotation: float):
self.radius = radius
self.vision_radius = vision_radius
self.vision_radius_squared = vision_radius ** 2
self.x_position = x_position
self.y_position = y_position
self.rotation = rotation
self.torque = 0
self.x_velocity = 0
self.y_velocity = 0
def bounding_box(self) -> tuple:
"""OBSOLETE: The boid is now represented by a triangle
Returns the x,y coords of the top-left and bottom right corners of the bounding box"""
upper_left_x = self.x_position - self.radius
upper_left_y = self.y_position + self.radius
bottom_right_x = self.x_position + self.radius
bottom_right_y = self.y_position - self.radius
return (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y)
def points(self) -> tuple:
points = []
for point in TRIANGLE_POINTS:
rotated_point = point.rotate(self.rotation)
points.append(rotated_point.x_val + self.x_position)
points.append(rotated_point.y_val + self.y_position)
return tuple(points)
def update(self, boids: List['Boid']):
"""Adjusts the boid's velocity depending on neighbouring boids"""
local_boids = self.find_neighbouring_boids(boids)
direction = Vector(0, -1).rotate(self.rotation)
self.x_velocity = direction.x_val * SPEED
self.y_velocity = direction.y_val * SPEED
if local_boids.__len__() == 0:
self.torque = 0
return
separation = self.separation_velocity(local_boids).rotate(-self.rotation)
alignment = self.alignment_velocity(local_boids).rotate(-self.rotation)
cohesion = self.cohesion_velocity(local_boids).rotate(-self.rotation)
total_rotation = (separation + alignment + cohesion).normalized()
if total_rotation.x_val < 0:
self.torque = -total_rotation.rotation_normalized()
else:
self.torque = total_rotation.rotation_normalized()
def velocity(self) -> Vector:
return Vector(self.x_velocity, self.y_velocity)
def separation_velocity(self, local_boids: List['Boid']) -> Vector:
"""Calculates the velocity to avoid local boids"""
locals_to_self_x = 0
locals_to_self_y = 0
for boid in local_boids:
locals_to_self_x += self.x_position - boid.x_position
locals_to_self_y += self.y_position - boid.y_position
return Vector(locals_to_self_x, locals_to_self_y).normalized()
def alignment_velocity(self, local_boids: List['Boid']) -> Vector:
"""Calculates the average velocity of all local boids"""
local_velocity_x = 0
local_velocity_y = 0
for boid in local_boids:
local_velocity_x += boid.x_velocity
local_velocity_y += boid.y_velocity
return Vector(local_velocity_x, local_velocity_y).normalized()
def cohesion_velocity(self, local_boids: List['Boid']) -> Vector:
"""Calculates the direction towards the center of mass of all local boids"""
position_x = 0
position_y = 0
boid_count = local_boids.__len__()
for boid in local_boids:
position_x += boid.x_position
position_y += boid.y_position
position_x /= boid_count
position_y /= boid_count
return Vector(position_x - self.x_position, position_y - self.y_position).normalized()
def find_neighbouring_boids(self, boids: List['Boid']) -> List['Boid']:
"""Find all boids within the self's range of vision"""
local_boids = []
for boid in boids:
if boid == self:
continue
if (self.in_range(boid.x_position, boid.y_position) and
not self.in_blind_spot(boid.x_position, boid.y_position)):
local_boids.append(boid)
return local_boids
def in_range(self, x_val: float, y_val: float) -> bool:
"""Return true if the position is within the vision range"""
distance_squared = (self.x_position - x_val) ** 2
distance_squared += (self.y_position - y_val) ** 2
return distance_squared <= self.vision_radius_squared
def in_blind_spot(self, x_val: float, y_val: float) -> bool:
"""Return true if the position is in the boids blind spot"""
self_to_boid = Vector(x_val - self.x_position, y_val - self.y_position).rotate(self.rotation)
rotation = self_to_boid.rotation()
return rotation < VISION_ANGLE
<file_sep>"""Program entry point"""
import random
import typing
from boid import Boid
import window
FLOCK = typing.List[Boid]
ITERATIONS = 0
def random_flock(size: int) -> FLOCK:
flock: FLOCK = []
rng = random.Random()
for i in range(size):
x_pos = rng.randrange(100, 900)
y_pos = rng.randrange(100, 900)
rot = (rng.random() -0.5) * 3.14
flock.append(Boid(5, 100, x_pos, y_pos, rot))
return flock
window = window.Window()
# flock: FLOCK = [
# Boid(5, 100, 500, 500, 3.14),
# #Boid(5, 100, 550, 500, 0)
# #Boid(5, 100, 550, 500, 1.5),
# #Boid(5, 100, 480, 500, -1.5),
# #Boid(5, 100, 500, 520, 3.14),
# #Boid(5, 100, 500, 430, 3.14)
# ]
#flock[0].torque = 1.5
flock = random_flock(100)
for boid in flock:
window.add_boid(boid)
while True:
for boid in flock:
boid.update(flock)
window.update()
ITERATIONS += 1
print(ITERATIONS)
<file_sep>"""Vector module"""
from math import sqrt, sin, cos
class Vector:
"""2D Vector with operations useful to the program"""
def __init__(self, x: float, y: float):
self.x_val = x
self.y_val = y
def __add__(self, other: 'Vector'):
return Vector(self.x_val + other.x_val, self.y_val + other.y_val)
def __sub__(self, other: 'Vector'):
return Vector(self.x_val - other.x_val, self.y_val - other.y_val)
def __mul__(self, other: float):
return Vector(self.x_val * other, self.y_val * other)
def negative(self) -> 'Vector':
return Vector(-self.x_val, -self.y_val)
def magnitude(self) -> float:
return sqrt(self.x_val ** 2 + self.y_val ** 2)
def normalized(self) -> 'Vector':
if self.x_val == 0 and self.y_val == 0:
return Vector(0, 0)
magnitude = self.magnitude()
return Vector(self.x_val / magnitude, self.y_val / magnitude)
def rotate(self, rotation: float) -> 'Vector':
"""Rotate the vector counter-clockwise by the rotation specified in radians"""
x_val = self.x_val * cos(rotation) - self.y_val * sin(rotation)
y_val = self.x_val * sin(rotation) + self.y_val * cos(rotation)
return Vector(x_val, y_val)
def rotation(self) -> float:
"""Calculates the cosine of the angle of the vector from (0, 1),
a vector of (0, 0) will return 0"""
#Method: Simplification of the dot product where vector b = (0, 1) becomes
if self.x_val == 0 and self.y_val == 0:
return 0
return self.y_val / self.magnitude()
def rotation_normalized(self) -> float:
"""Calculates the cosine as above and then normalises it from (1, -1) to (0, 1)"""
cos_val = self.rotation()
return (-cos_val + 1) / 2
def str(self) -> str:
return '(' + str(self.x_val) + ', ' + str(self.y_val) + ')'
<file_sep>import threading
import time
class Proclaimer (threading.Thread):
def __init__(self, proclamation):
self.proclamation = proclamation
threading.Thread.__init__(self)
def run(self):
proclaim_eternally(self.proclamation)
def proclaim(proclamation):
"""Proclaim"""
world_list = []
for word in proclamation.split(' '):
world_list.append(word.capitalize())
print(' '.join(world_list) + '!')
def proclaim_eternally(proclamation):
"""Proclaim Eternally(every two seconds)"""
while True:
proclaim(proclamation)
time.sleep(2)
one = Proclaimer('praise kek')
two = Proclaimer('sieg heil')
three = Proclaimer('hail satan')
four = Proclaimer('maga')
five = Proclaimer('long live the king')
one.start()
two.start()
three.start()
four.start()
five.start()<file_sep>def double(number):
return number * 2
capitalise = lambda word: word.capitalize()
print(capitalise('SOMETHING SOMETHING')) | 60fcdb042ff1282d0b202a1d1ee2daa42551dc15 | [
"Python"
] | 10 | Python | XDA-7/boids | c0c35360a0096c6b0096ac6b08c9b311abeb8c70 | 1973c8f6d91054a29a68749534d4b208eb75835e | |
refs/heads/master | <repo_name>EdwardBetts/vuze<file_sep>/trunk/azureus3/src/com/aelitis/azureus/ui/swt/search/SearchResultsTabAreaBrowser.java
/*
* Created on Dec 7, 2016
* Created by <NAME>
*
* Copyright 2016 Azureus Software, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
package com.aelitis.azureus.ui.swt.search;
import java.net.InetSocketAddress;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.browser.TitleEvent;
import org.eclipse.swt.browser.TitleListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.gudy.azureus2.core3.config.COConfigurationManager;
import org.gudy.azureus2.core3.config.ParameterListener;
import org.gudy.azureus2.core3.util.AERunnable;
import org.gudy.azureus2.core3.util.AESemaphore;
import org.gudy.azureus2.core3.util.AEThread2;
import org.gudy.azureus2.core3.util.SystemTime;
import org.gudy.azureus2.core3.util.UrlUtils;
import org.gudy.azureus2.ui.swt.BrowserWrapper;
import org.gudy.azureus2.ui.swt.Utils;
import com.aelitis.azureus.core.proxy.AEProxyFactory;
import com.aelitis.azureus.ui.UIFunctionsManager;
import com.aelitis.azureus.ui.common.viewtitleinfo.ViewTitleInfoManager;
import com.aelitis.azureus.ui.mdi.MdiEntry;
import com.aelitis.azureus.ui.mdi.MdiEntryVitalityImage;
import com.aelitis.azureus.ui.mdi.MultipleDocumentInterface;
import com.aelitis.azureus.ui.swt.UIFunctionsManagerSWT;
import com.aelitis.azureus.ui.swt.browser.BrowserContext;
import com.aelitis.azureus.ui.swt.browser.CookiesListener;
import com.aelitis.azureus.ui.swt.browser.OpenCloseSearchDetailsListener;
import com.aelitis.azureus.ui.swt.browser.BrowserContext.loadingListener;
import com.aelitis.azureus.ui.swt.browser.listener.ExternalLoginCookieListener;
import com.aelitis.azureus.ui.swt.browser.listener.MetaSearchListener;
import com.aelitis.azureus.ui.swt.mdi.MultipleDocumentInterfaceSWT;
import com.aelitis.azureus.ui.swt.search.SearchResultsTabArea.SearchQuery;
import com.aelitis.azureus.ui.swt.skin.SWTSkinObject;
import com.aelitis.azureus.ui.swt.skin.SWTSkinObjectBrowser;
import com.aelitis.azureus.ui.swt.skin.SWTSkinObjectListener;
import com.aelitis.azureus.util.ConstantsVuze;
import com.aelitis.azureus.util.MapUtils;
import com.aelitis.azureus.util.UrlFilter;
public class
SearchResultsTabAreaBrowser
implements SearchResultsTabAreaBase, OpenCloseSearchDetailsListener
{
private static boolean search_proxy_init_done;
private static AEProxyFactory.PluginHTTPProxy search_proxy;
private static boolean search_proxy_set;
private static AESemaphore search_proxy_sem = new AESemaphore( "sps" );
private static List<SearchResultsTabAreaBrowser> pending = new ArrayList<SearchResultsTabAreaBrowser>();
private static void
initProxy()
{
synchronized( SearchResultsTabArea.class ){
if ( search_proxy_init_done ){
return;
}
search_proxy_init_done = true;
}
new AEThread2( "ST_test" )
{
public void
run()
{
try{
String test_url;
if ( System.getProperty("metasearch", "1").equals("1")){
test_url = ConstantsVuze.getDefaultContentNetwork().getXSearchService( "derp", false );
}else{
test_url = ConstantsVuze.getDefaultContentNetwork().getSearchService( "derp" );
}
try{
URL url = new URL( test_url );
url = UrlUtils.setProtocol( url, "https" );
url = UrlUtils.setPort( url, 443 );
boolean use_proxy = !COConfigurationManager.getStringParameter( "browser.internal.proxy.id", "none" ).equals( "none" );
if ( !use_proxy ){
Boolean looks_ok = AEProxyFactory.testPluginHTTPProxy( url, true );
use_proxy = looks_ok != null && !looks_ok;
}
if ( use_proxy ){
search_proxy = AEProxyFactory.getPluginHTTPProxy( "search", url, true );
if ( search_proxy != null ){
UrlFilter.getInstance().addUrlWhitelist( "https?://" + ((InetSocketAddress)search_proxy.getProxy().address()).getAddress().getHostAddress() + ":?[0-9]*/.*" );
}
}
}catch( Throwable e ){
}
}finally{
List<SearchResultsTabAreaBrowser> to_redo = null;
synchronized( SearchResultsTabArea.class ){
search_proxy_set = true;
to_redo = new ArrayList<SearchResultsTabAreaBrowser>( pending );
pending.clear();
}
search_proxy_sem.releaseForever();
for ( SearchResultsTabAreaBrowser area: to_redo ){
try{
try{
area.browserSkinObject.setAutoReloadPending( false, search_proxy == null );
}catch( Throwable e ){
}
if ( search_proxy != null ){
SearchQuery sq = area.sq;
if ( sq != null ){
area.anotherSearch( sq );
}
}
}catch( Throwable e ){
}
}
}
}
}.start();
}
static{
COConfigurationManager.addParameterListener(
"browser.internal.proxy.id",
new ParameterListener()
{
public void
parameterChanged(
String parameterName )
{
synchronized( SearchResultsTabArea.class ){
if ( !search_proxy_init_done ){
return;
}
search_proxy_init_done = false;
search_proxy_set = false;
if ( search_proxy != null ){
search_proxy.destroy();
search_proxy = null;
}
}
}
});
}
private static AEProxyFactory.PluginHTTPProxy
getSearchProxy(
SearchResultsTabAreaBrowser area )
{
initProxy();
boolean force_proxy = !COConfigurationManager.getStringParameter( "browser.internal.proxy.id", "none" ).equals( "none" );
search_proxy_sem.reserve( force_proxy?60*1000:2500 );
synchronized( SearchResultsTabArea.class ){
if ( search_proxy_set ){
return( search_proxy );
}else{
pending.add( area );
try{
area.browserSkinObject.setAutoReloadPending( true, false );
}catch( Throwable e ){
}
return( null );
}
}
}
private final SearchResultsTabArea parent;
private SWTSkinObjectBrowser browserSkinObject;
private boolean searchResultsInitialized = false;
private String title;
private SearchQuery sq;
protected
SearchResultsTabAreaBrowser(
SearchResultsTabArea _parent )
{
parent = _parent;
}
protected void
init(
SWTSkinObjectBrowser _browserSkinObject )
{
browserSkinObject = _browserSkinObject;
browserSkinObject.addListener(new SWTSkinObjectListener() {
public Object eventOccured(SWTSkinObject skinObject, int eventType,
Object params) {
if (eventType == EVENT_SHOW) {
browserSkinObject.removeListener(this);
createBrowseArea(browserSkinObject);
}
return null;
}
});
}
/**
*
*/
private void createBrowseArea(SWTSkinObjectBrowser browserSkinObject) {
this.browserSkinObject = browserSkinObject;
browserSkinObject.getContext().addMessageListener(
new MetaSearchListener(this));
browserSkinObject.addListener(new loadingListener() {
public void browserLoadingChanged(boolean loading, String url) {
parent.setBusy( loading );
}
});
SWTSkinObject soSearchResults = parent.getSkinObject("searchresults-search-results");
if (soSearchResults instanceof SWTSkinObjectBrowser) {
SWTSkinObjectBrowser browserSearchResults = (SWTSkinObjectBrowser) soSearchResults;
browserSearchResults.addListener(new loadingListener() {
public void browserLoadingChanged(boolean loading, String url) {
parent.setBusy( loading );
}
});
}
}
/*
public void restart() {
if (browserSkinObject != null) {
browserSkinObject.restart();
}
}
*/
public void openSearchResults(final Map params) {
if (!searchResultsInitialized) {
searchResultsInitialized = true;
Utils.execSWTThread(new AERunnable() {
public void runSupport() {
SWTSkinObject soSearchResults = parent.getSkinObject("searchresults-search-results");
if (soSearchResults != null) {
SWTSkinObjectBrowser browserSkinObject = (SWTSkinObjectBrowser) soSearchResults;
final BrowserWrapper browser = browserSkinObject.getBrowser();
browser.addTitleListener(new TitleListener() {
public void changed(TitleEvent event) {
if (event.widget.isDisposed()
|| browser.getShell().isDisposed()) {
return;
}
title = event.title;
int i = title.toLowerCase().indexOf("details:");
if (i > 0) {
title = title.substring(i + 9);
}
}
});
final ExternalLoginCookieListener cookieListener = new ExternalLoginCookieListener(new CookiesListener() {
public void cookiesFound(String cookies) {
browser.setData("current-cookies", cookies);
}
},browser);
cookieListener.hook();
}
}
});
}
Utils.execSWTThread(new AERunnable() {
public void runSupport() {
SWTSkinObject soSearchResults = parent.getSkinObject("searchresults-search-results");
if (soSearchResults == null) {
return;
}
Control controlTop = browserSkinObject.getControl();
Control controlBottom = soSearchResults.getControl();
final BrowserWrapper search = ((SWTSkinObjectBrowser) soSearchResults).getBrowser();
String url = MapUtils.getMapString(params, "url",
"http://google.com/search?q=" + Math.random());
if (UrlFilter.getInstance().urlCanRPC(url)) {
url = ConstantsVuze.getDefaultContentNetwork().appendURLSuffix(url, false, true);
}
//Gudy, Not Tux, Listener Added
String listenerAdded = (String) search.getData("g.nt.la");
if (listenerAdded == null) {
search.setData("g.nt.la", "");
search.addProgressListener(new ProgressListener() {
public void changed(ProgressEvent event) {
}
public void completed(ProgressEvent event) {
String execAfterLoad = (String) search.getData("execAfterLoad");
//Erase it, so that it's only used once after the page loads
search.setData("execAfterLoad", null);
if (execAfterLoad != null && !execAfterLoad.equals("")) {
//String execAfterLoadDisplay = execAfterLoad.replaceAll("'","\\\\'");
//search.execute("alert('injecting script : " + execAfterLoadDisplay + "');");
boolean result = search.execute(execAfterLoad);
//System.out.println("Injection : " + execAfterLoad + " (" + result + ")");
}
}
});
}
//Store the "css" match string in the search cdp browser object
String execAfterLoad = MapUtils.getMapString(params, "execAfterLoad",
null);
search.setData("execAfterLoad", execAfterLoad);
search.setUrl(url);
FormData gd = (FormData) controlBottom.getLayoutData();
gd.top = new FormAttachment(controlTop, 0);
gd.height = SWT.DEFAULT;
controlBottom.setLayoutData(gd);
gd = (FormData) controlTop.getLayoutData();
gd.bottom = null;
gd.height = MapUtils.getMapInt(params, "top-height", 120);
controlTop.setLayoutData(gd);
soSearchResults.setVisible(true);
controlBottom.setVisible(true);
search.setVisible(true);
controlTop.getParent().layout(true);
}
});
}
public void
anotherSearch(
SearchQuery sq )
{
this.sq = sq;
String url;
if ( System.getProperty("metasearch", "1").equals("1")){
url = ConstantsVuze.getDefaultContentNetwork().getXSearchService( sq.term, sq.toSubscribe );
}else{
url = ConstantsVuze.getDefaultContentNetwork().getSearchService( sq.term );
}
AEProxyFactory.PluginHTTPProxy proxy = getSearchProxy( this );
if ( proxy != null ){
url = proxy.proxifyURL( url );
}
closeSearchResults(null);
if (Utils.isThisThreadSWT()) {
try {
browserSkinObject.getBrowser().setText("");
final BrowserWrapper browser = browserSkinObject.getBrowser();
final boolean[] done = {false};
browser.addLocationListener(new LocationListener() {
public void changing(LocationEvent event) {
}
public void changed(LocationEvent event) {
done[0] = true;
browser.removeLocationListener(this);
}
});
browserSkinObject.getBrowser().setUrl("about:blank");
browserSkinObject.getBrowser().refresh();
browserSkinObject.getBrowser().update();
Display display = Utils.getDisplay();
if ( display != null ){
long until = SystemTime.getCurrentTime() + 300;
while (!done[0] && until > SystemTime.getCurrentTime()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
} catch (Throwable t) {
}
}
browserSkinObject.setURL(url);
}
public void
closeSearchResults(
Map params )
{
Utils.execSWTThread(new AERunnable() {
public void runSupport() {
SWTSkinObject soSearchResults = parent.getSkinObject("searchresults-search-results");
if (soSearchResults == null) {
return;
}
Control controlTop = browserSkinObject.getControl();
Control controlBottom = soSearchResults.getControl();
BrowserWrapper search = ((SWTSkinObjectBrowser) soSearchResults).getBrowser();
soSearchResults.setVisible(false);
FormData gd = (FormData) controlBottom.getLayoutData();
if (gd == null) {
return;
}
gd.top = null;
gd.height = 0;
controlBottom.setLayoutData(gd);
gd = (FormData) controlTop.getLayoutData();
gd.bottom = new FormAttachment(controlBottom, 0);
gd.height = SWT.DEFAULT;
controlTop.setLayoutData(gd);
controlBottom.getParent().layout(true);
if (search != null) {
search.setUrl("about:blank");
}
BrowserContext context = browserSkinObject.getContext();
if (context != null) {
context.executeInBrowser("searchResultsClosed()");
}
}
});
}
public void
showView()
{
}
public void
hideView()
{
closeSearchResults( null );
}
public int
getResultCount()
{
return( -1 );
}
public void resizeMainBrowser() {
}
public void resizeSecondaryBrowser() {
}
}
| 02522a8c454af2dc8fb2eaa943697777db548c73 | [
"Java"
] | 1 | Java | EdwardBetts/vuze | 435d8349f2ec00ea3b0f67af0a27f1c202bf23aa | b3e30dcfb2edb19e474e8bf757feb24dbcccb125 | |
refs/heads/master | <file_sep>final class Lender {
int fund = 100;
public int availableFund(){
return fund;
}
public int getLoan(int loanAmount){
if(loanAmount >= fund){
throw new IllegalArgumentException("Loan request greater than available fund");
}
return loanAmount;
}
public int addFunds(int m){
m+= fund;
return m;
}
}
| 1471975fee664e854143bed8150546f9d8a07494 | [
"Java"
] | 1 | Java | chernojallow/Mortgage-Lender | 31904b430baab7c827847f4feaad97a31917ec14 | c2c5a3c29e2df31806a8a296a17a1a97f5ce0bde | |
refs/heads/master | <file_sep>#!/usr/bin/env python
# coding: utf-8
# In[11]:
get_ipython().run_line_magic('matplotlib', 'inline')
import d2lzh as d2l
import math
from mxnet import nd
def rmsprop_2d(x1, x2, s1, s2):
g1, g2, eps = 0.2 * x1, 4 * x2, 1e-6
s1 = gamma * s1 + (1 - gamma) * g1 ** 2
s2 = gamma * s2 + (1 - gamma) * g2 ** 2
x1 -= eta / math.sqrt(s1 + eps) * g1
x2 -= eta / math.sqrt(s2 + eps) * g2
return x1, x2, s1, s2
def f_2d(x1, x2):
return 0.1 * x1 ** 2 + 2 * x2 ** 2
eta, gamma = 0.4, 0.9
d2l.show_trace_2d(f_2d, d2l.train_2d(rmsprop_2d))
# In[2]:
features, labels = d2l.get_data_ch7()
def init_rmsprop_states():
s_w = nd.zeros((features.shape[1], 1))
s_b = nd.zeros(1)
return (s_w, s_b)
def rmsprop(params, states, hyperparams):
gamma, eps = hyperparams['gamma'], 1e-6
for p, s in zip(params, states):
s[:] = gamma * s + (1 - gamma) * p.grad.square()
p[:] -= hyperparams['lr'] * p.grad / (s + eps).sqrt()
# In[3]:
d2l.train_ch7(rmsprop, init_rmsprop_states(), {'lr':0.01, 'gamma': 0.9},
features, labels)
# In[9]:
#简洁实现
d2l.train_gluon_ch7('rmsprop', {'learning_rate': 0.01, 'gamma1': 0.9},
features, labels)
# In[ ]:
<file_sep>#!/usr/bin/env python
# coding: utf-8
# In[5]:
from mxnet import nd
import random
import zipfile
with zipfile.ZipFile('../data/jaychou_lyrics.txt.zip') as zin:
with zin.open('jaychou_lyrics.txt') as f:
corpus_chars = f.read().decode('utf-8')
corpus_chars[:40]
# In[6]:
corpus_chars = corpus_chars.replace('\n',' ').replace('\r',' ')
corpus_chars = corpus_chars[0 : 10000]
# In[7]:
idx_to_char = list(set(corpus_chars))
char_to_idx =dict([(char, i) for i, char in enumerate(idx_to_char)])
vocab_size = len(char_to_idx)
vocab_size
# In[8]:
#随机采样
def data_iter_random(corpus_indices, batch_size, num_steps, ctx=None):
num_examples = (len(corpus_indices) - 1) // num_steps #不减一可能会导致Y溢出
epoch_size = num_examples // batch_size
example_indices = list(range(num_examples))
random.shuffle(example_indices)
def _data(pos):
return corpus_indices[pos: pos + num_steps]
for i in range(epoch_size):
i = i * batch_size
batch_indices = example_indices[i: i + batch_size]
X = [_data(j * num_steps) for j in batch_indices]
Y = [_data(j * num_steps + 1) for j in batch_indices]
yield nd.array(X, ctx), nd.array(Y, ctx)
# In[9]:
my_seq = list(range(30))
for X, Y in data_iter_random(my_seq, batch_size=2, num_steps=6):
print('X:', X, '\nY:', Y, '\n')
# In[11]:
def data_iter_consecutive(corpus_indices, batch_size, num_steps, ctx=None):
corpus_indices = nd.array(corpus_indices, ctx=ctx)
data_len = len(corpus_indices)
batch_len = data_len // batch_size
indices = corpus_indices[0: batch_size*batch_len].reshape((
batch_size, batch_len))
epoch_size = (batch_len - 1) // num_steps
for i in range(epoch_size):
i = i * num_steps
X = indices[:, i: i + num_steps]
Y = indices[:, i + 1: i + num_steps + 1]
yield X, Y
# In[12]:
for X, Y in data_iter_consecutive(my_seq, batch_size=2, num_steps=6):
print('X: ', X, '\nY:', Y, '\n')
# In[ ]:
| 203dff07605f58b85049853864f96be51f5915a5 | [
"Python"
] | 2 | Python | vehicleengineer/training5 | 364485ab59bdff4da1fbed0f6de0e13aa3e916b4 | f3b4a2c26b65651e6932bce7faa402b1647bc25b | |
refs/heads/master | <repo_name>sketchplugindirectory/api<file_sep>/webhook/stripe.js
const stripe = require('stripe')(process.env.STRIPE_SECRET)
const storage = require('../storage')()
module.exports.handler = (event, context, callback) => {
let sig = event.stripeSignature
let stripeEvent
try {
stripeEvent = stripe.webhooks.constructEvent(event.body, sig, process.env.STRIPE_ENDPOINT_SECRET)
} catch (err) {
return callback(err)
}
const subscription = stripeEvent.data.object
if (subscription.object === 'subscription' && subscription.status !== 'active') {
stripe.customers.retrieve(subscription.customer).then((customer) => {
return storage.findOne(customer.metadata.githubId)
}).then(user => {
if (!user) {
return
}
user.valid = false
return storage.update(user)
}).then(() => {
callback(null, {
ok: true,
message: 'locked'
})
}).catch(callback)
} else {
callback(null, {
ok: true,
message: 'nothing to do'
})
}
}
<file_sep>/api/unlock.js
const stripe = require('stripe')(process.env.STRIPE_SECRET)
const storage = require('../storage')()
const cleanBody = require('./_cleanBody')
module.exports.handler = (event, context, callback) => {
let parsedBody
try {
parsedBody = JSON.parse(event.body || {})
} catch (e) {
callback(new Error('[400] Could not parse the body'))
return
}
const body = cleanBody(parsedBody)
if (!body.githubId) {
callback(new Error('[400] Missing github ID'))
return
}
const token = parsedBody.token
let method
let bailout = false
storage
.findOne(body.githubId)
.then(found => {
if (found) {
if (found.valid) {
callback(new Error('[403] Already unlocked'))
bailout = true
return
}
method = 'update'
return
}
method = 'create'
})
.then(() => {
if (bailout) { return }
return stripe.customers.create({
email: body.email,
source: token,
metadata: {
githubId: body.githubId,
login: body.login,
enterprise: body.enterprise
}
})
})
.then(customer => {
if (bailout) { return }
console.log(customer)
body.stripeId = customer.id
return stripe.subscriptions.create({
customer: customer.id,
plan: body.enterprise ? 'kactus-enterprise-1-month' : 'kactus-1-month',
coupon: parsedBody.coupon || undefined
})
})
.then(res => {
if (bailout) { return }
console.log(res)
body.valid = true
})
.then(() => {
if (bailout) { return }
return storage[method](body)
})
.then(res => {
if (bailout) { return }
callback(null, {
ok: true,
message: 'Unlocked full access'
})
})
.catch((err) => {
console.error(err)
if (!err.type) {
return callback(err)
}
switch (err.type) {
case 'StripeCardError':
// A declined card error
const message = err.message // => e.g. "Your card's expiration year is invalid."
callback(new Error(`[400] ${message}`))
break
case 'RateLimitError':
// Too many requests made to the API too quickly
callback(new Error(`[503] Server is a bit overloaded, try again in a bit`))
break
case 'StripeInvalidRequestError':
// Invalid parameters were supplied to Stripe's API
callback(new Error(`[400] Bad request`))
break
case 'StripeAPIError':
// An error occurred internally with Stripe's API
callback(new Error(`[500] Stripe failed, sorry about that`))
break
case 'StripeConnectionError':
// Some kind of error occurred during the HTTPS communication
callback(new Error(`[500] Stripe is down, sorry about that`))
break
case 'StripeAuthenticationError':
// You probably used an incorrect API key
callback(new Error(`[500] How did that happen!?`))
break
default:
// Handle any other types of unexpected errors
callback(err)
break
}
})
}
<file_sep>/api/getOne.js
const storage = require('../storage')()
module.exports.handler = (event, context, callback) => {
storage
.findOne(event.githubId)
.then(item => {
if (!item) {
callback(new Error('[404] Not found'))
return
}
callback(null, {
ok: true,
user: item
})
})
.catch(callback)
}
<file_sep>/storage.js
const AWS = require('aws-sdk')
/* USERS
{
githubId: String,
email: String,
login: String,
stripeId: String,
valid: Boolean,
createdAt: Date,
lastSeenAt: Date
}
*/
module.exports = function Storage () {
const db = new AWS.DynamoDB.DocumentClient()
return {
findOne (githubId) {
return db
.get({
TableName: process.env.TABLE_NAME,
Key: {
githubId: githubId
}
})
.promise()
.then(meta => (meta || {}).Item)
},
update (data) {
data.lastSeenAt = Date.now()
return db
.put({
TableName: process.env.TABLE_NAME,
Item: data
})
.promise()
},
create (data) {
data.createdAt = Date.now()
data.lastSeenAt = Date.now()
return db
.put({
TableName: process.env.TABLE_NAME,
Item: data
})
.promise()
}
}
}
| 4b50fd8482c59fbd73aa8fc83c177d462025b014 | [
"JavaScript"
] | 4 | JavaScript | sketchplugindirectory/api | 39e576648cbc776742b77ae1d1f6734c8b87b786 | 8b3fce5d7ad15fba179cf49446bff2cc4947f4ee | |
refs/heads/master | <repo_name>dashakhan/katas<file_sep>/print each from min to max.js
// given two numbers, one is bigger then other
// print all nums from min to max
// - check which is min/max
// - loop where i is min and i < max
// create empty arr, return push in that array
//
// function num(a, b){
// let arr=[]
// let min = a < b ? a : b
// let max = a === min ? b : a
// for(let i = min; i <= max ; i++){
// arr.push(i)
// } return arr
// }
// console.log(num(55,22));
// errors
// i put arr.push[i] insted arr.push(i)
// i cant push arr[i] becouse this element
// doesnt even exist yet. (i) is the number in the loop
<file_sep>/palindrome num.js
// function isPalindrome(num){
// let str1 = ''
// num = num + ''
// for(let i = num.length - 1; i >= 0; i--){
// str1 = str1 + num[i]
// }
// if(str1 === num){
// return 'palindrome'
// } return 'not a palindrome'
// }
// console.log(isPalindrome(656));
<file_sep>/str reverse.js
// function reverse(b){
// let b1 = ''
// for(let i = b.length -1; i >= 0; i--){
// b1 = b1 + b[i]
// }return b1
// }
// console.log(reverse('Nannnu'));
<file_sep>/cats Dogs years.js
//https://www.codewars.com/kata/5a6663e9fd56cb5ab800008b
// var humanYearsCatYearsDogYears = function(humanYears) {
// let catY = 15
// let dogY = 15
// if(humanYears === 1)
// return [humanYears, catY, dogY]
// if(humanYears === 2){
// return [humanYears, catY += 9, dogY += 9]
// } if(humanYears > 2){
// return [humanYears, ((humanYears - 2)* 4)+ 24,((humanYears - 2)* 5)+ 24]
// }
// }<file_sep>/str includes.js
// does this string includes vowels?
// function vow(str){
// let str1 = ''
// for(let i = 0; i < str.length;i++){
// if('aeouiy'.includes(str[i])){
// str1 = str1 + str[i]
// }
// }return str1
// }
// console.log(vow('byoba'));
<file_sep>/Shark Pontoon.js
//https://www.codewars.com/kata/57e921d8b36340f1fd000059
// 8 kata
// function shark(pontoonDistance, sharkDistance, youSpeed, sharkSpeed, dolphin){
// if(dolphin === true){
// sharkSpeed = sharkSpeed / 2
// }
// let yourTime = pontoonDistance / youSpeed
// let sharkTime = sharkDistance / sharkSpeed
// if(yourTime < sharkTime){
// return 'Alive!'
// } return 'Shark Bait!'
// }
<file_sep>/Seats in bus.js
//https://www.codewars.com/kata/5875b200d520904a04000003
// how many ppl will wait
// function enough(cap, on, wait) {
// let seats = cap - on
// if(cap - (on + wait) >= 0){
// return 0
// }
// else if(seats < wait ) {
// return (wait - seats)
// }
// } | a9db06bd1ba4e021808b989ad9b9ed97215b7f24 | [
"JavaScript"
] | 7 | JavaScript | dashakhan/katas | b06d7ab451444d8482fa2f5e377fc6c76ba28325 | 56831cc072cc0eb3d61fd4fd00311292900981e6 | |
refs/heads/master | <repo_name>aleX3645/PythonServerOfGroupProject<file_sep>/BotMapper.py
class BotMapper:
__position_x = 0
__position_y = 0
__charge = 0.0
__weight = 0.0
__speed = 0.0
__tiredness = 0.0
__rang = 0.0
__damage = 0.0
__game_field = [[]]
def __init__(self, charge: float, weight: float, speed: float, tiredness: float, damage: float, rang: float,
position_x: int, position_y: int, game_field):
self.__game_field = game_field
self.__charge = charge
self.__weight = weight
self.__tiredness = tiredness
self.__speed = speed
self.__rang = rang
self.__damage = damage
self.__position_y = position_y
self.__position_x = position_x
def get_tiredness(self):
return self.__tiredness
def set_tiredness(self, tiredness):
self.__tiredness = tiredness
def get_charge(self):
return self.__charge
def get_speed(self):
return self.__speed
def get_weight(self):
return self.__weight
def get_range(self):
return self.__rang
def get_damage(self):
return self.__damage
def get_position_x(self):
return self.__position_x
def get_position_y(self):
return self.__position_y
def set_position_xy(self, position_x: int, position_y: int):
self.__position_x = position_x
self.__position_y = position_y
<file_sep>/app.py
from flask import Flask, request, jsonify
from flask_restful import Api, Resource
from BotMapper import BotMapper
from GameServer import GameServer
app = Flask(__name__)
api = Api(app)
array = []
class Fight(Resource):
def post(self):
return self.start_game_by_json(request.get_json())
def start_game_by_json(self, req):
field = self.get_int_field((req['arena'])['field'])
temp_pos = self.get_position_for(field, 1)
temp = req['robot1']
bot_stat1 = BotMapper(temp['charge'], temp['weight'], temp['speed'],
temp['tiredness'], temp['damage'], temp['range'],
temp_pos[0], temp_pos[1], field)
bot1_string = (temp['botAlgorithm'])['algorithm']
temp_pos = self.get_position_for(field, 2)
temp = req['robot2']
bot_stat2 = BotMapper(temp['charge'], temp['weight'], temp['speed'],
temp['tiredness'], temp['damage'],
temp['range'], temp_pos[0], temp_pos[1], field)
bot2_string = (temp['botAlgorithm'])['algorithm']
game = GameServer(bot1_string, bot2_string, bot_stat1, bot_stat2, field)
res = game.start()
return jsonify(
{"winner": res[0], "fight_map": res[1]}
)
def get_position_for(self, field, t: int):
for x in range(len(field)):
for y in range(len(field[x])):
if field[x][y] == t:
return [x, y]
def get_int_field(self, field):
temp_field = field.split("\n")
f_res = []
for x in range(len(temp_field)):
list = []
for y in temp_field[x]:
if y == '0':
list.append(0)
elif y == '1':
list.append(1)
elif y == '2':
list.append(2)
f_res.append(list)
print(f_res)
return f_res
api.add_resource(Fight, '/fight/')
<file_sep>/GameServer.py
import string
from random import gauss
from Bot import Bot
from BotMapper import BotMapper
class GameServer:
r = 0
__fight_map = ""
bot1: Bot
bot2: Bot
bot_stats1: BotMapper
bot_stats2: BotMapper
game_field: [[]]
def __init__(self, bot1: str, bot2: str, bot_stats1: BotMapper, bot_stats2: BotMapper, game_field: []):
self.game_field = game_field
bot1 += "\n" + "self.bot1 = Bot(game_field)"
bot2 += "\n" + "self.bot2 = Bot(game_field)"
exec(bot1)
exec(bot2)
self.bot_stats1 = bot_stats1
self.bot_stats2 = bot_stats2
# 1-bot1 winner, 2-bot2 winner, 0-draw
def start(self):
while self.r < 60:
step = self.bot1.consider_step(self.game_field)
if step[0] == "attack":
res = self.attack(self.bot_stats1, self.bot_stats2, 1, step[1], step[2])
self.__fight_map += "1," + "attack," + str(step[1]) +"," + str(step[2]) + ";"
elif step[0] == "move":
res = self.attack(self.bot_stats1, self.bot_stats2, 1, step[1], step[2])
self.__fight_map += "1," + "move," + str(step[1]) + "," + str(step[2]) + ";"
else:
res = 0
if res == 2:
self.__fight_map += "1," + "kill," + str(step[1]) + "," + str(step[2]) + ";"
return [1, self.__fight_map]
step = self.bot2.consider_step(self.game_field)
if step[0] == "attack":
res = self.attack(self.bot_stats2, self.bot_stats1, 2, step[1], step[2])
self.__fight_map += "2," + "attack," + str(step[1]) + "," + str(step[2]) + ";"
elif step[0] == "move":
res = self.attack(self.bot_stats2, self.bot_stats1, 2, step[1], step[2])
self.__fight_map += "2," + "move," + str(step[1]) + "," + str(step[2]) + ";"
else:
res = 0
if res == 2:
self.__fight_map += "1," + "kill," + str(step[1]) + "," + str(step[2]) + ";"
return [2, self.__fight_map]
self.r += 1
return 0
# -1 - error, 1- hit, 2 - kill, 0 - miss
def attack(self, bot: BotMapper, attacked_bot: BotMapper, bot_n: int, x: int, y: int):
range_of_attack = abs(bot.get_position_x()) - abs(x) + abs(bot.get_position_y()) - abs(y)
print(str(bot_n) + " " + str(x) + " " + str(y) + str(self.game_field[0][2]) + ";")
if bot.get_range() < range_of_attack | x < 0 | y < 0:
return -1
else:
if (bot_n == 1 and self.game_field[x][y] == 2) | (bot_n == 2 and self.game_field[x][y] == 1):
dmg = gauss(bot.get_damage(), 25)
hp = attacked_bot.get_tiredness() - dmg
if hp <= 0:
return 2
attacked_bot.set_tiredness(hp)
return 1
else:
return 0
# -1 - error, 1 - move
def move(self, bot: BotMapper, x: int, y: int):
range_of_move = abs(bot.get_position_x()) - abs(x) + abs(bot.get_position_y()) - abs(y)
if self.game_field[x][y] == 0 and range_of_move < bot.get_speed():
bot.set_position_xy(x, y)
return 1
else:
return -1
<file_sep>/Game.py
from random import gauss
from Bot import Bot
class Game:
r = 0
bot1: Bot
bot2: Bot
game_field: [[]]
def __init__(self, bot1: Bot, bot2: Bot):
self.bot1 = bot1
self.bot2 = bot2
# 1-bot1 winner, 2-bot2 winner, 0-draw
def start(self):
while self.r < 60:
step = self.bot1.consider_step(self.game_field)
if step[0] == "attack":
res = self.attack(self.bot1, self.bot2, 1, step[1], step[2])
elif step[0] == "move":
res = self.move(self.bot1, step[1], step[2])
else:
res = 0
if res == 2:
return 1
step = self.bot2.consider_step(self.game_field)
if step[0] == "attack":
res = self.attack(self.bot2, self.bot1, 2, step[1], step[2])
elif step[0] == "move":
res = self.move(self.bot2, step[1], step[2])
else:
res = 0
if res == 2:
return 2
self.r += 1
return 0
# -1 - error, 1- hit, 2 - kill, 0 - miss
def attack(self, bot: Bot, attacked_bot: Bot, bot_n: int, x: int, y: int):
range_of_attack = abs(bot.get_position_x()) - abs(x) + abs(bot.get_position_y()) - abs(y)
if bot.get_range() < range_of_attack | x < 0 | y < 0 | len(self.game_field) < x | len(self.game_field[x]) < y:
return -1
else:
if (bot_n == 1 & self.game_field[x, y] == 2) | (bot_n == 2 & self.game_field[x, y] == 1):
dmg = gauss(bot.get_damage(), 25)
hp = attacked_bot.get_tiredness() - dmg
if hp <= 0:
return 2
attacked_bot.set_tiredness(hp)
return 1
else:
return 0
def move(self, bot: Bot, x: int, y: int):
range_of_move = abs(bot.get_position_x()) - abs(x) + abs(bot.get_position_y()) - abs(y)
if self.game_field[x, y] != 0 & range_of_move < bot.get_speed() | len(self.game_field) < x | len(self.game_field[x]) < y:
return -1
else:
bot.set_position_xy(x, y)
return 1
| bdb69a2d939cabbe88eaeac17f7d56961c6d0999 | [
"Python"
] | 4 | Python | aleX3645/PythonServerOfGroupProject | 84a2a8d52afd843523ff94d1db0edc34b29c5b2e | b574a031a9244302d9e0243bf2aaf16a65744d74 | |
refs/heads/master | <file_sep>from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model=Employee
fields=('Employee_Id','Employee_Name','Department_Name')<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-24 19:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Employee',
fields=[
('Employee_Id', models.IntegerField(primary_key=True, serialize=False)),
('Employee_Name', models.CharField(max_length=50)),
('Department_Name', models.CharField(max_length=50)),
],
),
]
<file_sep># DJango-RESTframework
Hi, This is all about REST Services for CRUD operations. I am newbie to DJangoRestFramework, hope this helps guys who wanted to know some basic idea about APIs and how it works.
Created Individual apis for each individual operations like (get all, get by Id, Inserting record, updating record by Id, deleting record by Id.
at begining struggled bit,anyway everthing working fine.
Tools used:
Postman : to test apis
Database: MySql
HappyLearning !!
<file_sep>from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Employee(models.Model):
Employee_Id=models.IntegerField(primary_key = True)
Employee_Name=models.CharField(max_length=50)
Department_Name=models.CharField(max_length=50)
<file_sep>from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.serializers import serialize
from .models import Employee
from .serializers import EmployeeSerializer
from rest_framework import status
import pdb
# create your views here
# Get Record By ID(primary key)
class EmployeeDetailsByID(APIView):
def get_object(self,pk):
try:
return Employee.objects.get(pk=pk)
except Employee.DoesNotExist:
raise Http404
def get(self,request,pk,format=None):
employee=self.get_object(pk)
serializer=EmployeeSerializer(employee)
return Response(serializer.data)
# Get all records present in requested database
class EmployeesDetails(APIView):
def get(self,request,format=None):
employee=Employee.objects.all()
serializer=EmployeeSerializer(employee,many=True)
return Response(serializer.data)
# Inserting new record into the database
class InsertEmployee(APIView):
def post(self,request,format=None):
try:
serializer=EmployeeSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
except Employee.DoesNotExist:
raise Http404
# Updating record based on ID (key)
class UpdateEmployee(APIView):
def put(self,request,pk,format=None):
try:
employee=EmployeeDetailsByID.get_object(self,pk)
data=(EmployeeSerializer(employee).data)
requested_data=request.data
data.update(requested_data)
serializer=EmployeeSerializer(employee,data=data)
if serializer.is_valid():
serializer.save()
return Response(data,status=status.HTTP_201_CREATED)
except Employee.DoesNotExist:
raise Http404
# Deleting record based on ID(key)
class DeleteEmployee(APIView):
def delete(self,request,pk,format=None):
try:
employee=EmployeeDetailsByID.get_object(self,pk)
employee.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
except Employee.DoesNotExist:
raise Http404
<file_sep>from django.conf.urls import url
from . import views
urlpatterns =[
url(r'^api/employees/$',views.EmployeesDetails.as_view()),
url(r'^api/employees/(?P<pk>[0-9]+)/$',views.EmployeeDetailsByID.as_view()),
url(r'^api/insertemployee/$',views.InsertEmployee.as_view()),
url(r'^api/updateemployee/(?P<pk>[0-9]+)/$', views.UpdateEmployee.as_view()),
url(r'^api/deleteemployee/(?P<pk>[0-9]+)/$', views.DeleteEmployee.as_view()),
]
| 9acfeb47348c25dd3dd486e036eeb8b059576e4d | [
"Markdown",
"Python"
] | 6 | Python | ramukodandapuram/DJango-RESTframework | 645efc0e10854bffcb412e88c117cd11d9e819e7 | 74adf02320e8ca2068e3dc9624c955c17a303ada | |
refs/heads/main | <repo_name>iamtanmay/CS_Backend<file_sep>/UT_Curves.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Utilities
{
[TestClass]
public class UT_Curves
{
public CurveLibrary curves;
[TestMethod]
public void CreateCurveLibrary()
{
curves = new CurveLibrary();
curves.LoadCurves(".\\Data\\CurvesControlPoints\\", "Lagrange");
}
[TestMethod]
public void CompareCurveLibrary()
{
}
}
}
<file_sep>/Curves.cs
using System;
using System.IO;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
namespace Utilities
{
public struct LoadStrings
{
/// <summary>
/// Load all files with extension in folder and return it in lists
/// </summary>
/// <param name="dataFolder"></param>
/// <param name="extension"></param>
/// <returns></returns>
public static List<List<string>> FromFolder(string dataFolder, string extension)
{
List<List<string>> returnList = new List<List<string>>();
//Open folder and iterate all txt files
foreach (string fileName in Directory.GetFiles(dataFolder))
{
FileInfo f = new FileInfo(fileName);
if (f.Extension == ("." + extension))
{
List<string> filedata = new List<string>();
string[] fileLines = File.ReadAllLines(fileName);
filedata = fileLines.ToList<string>();
returnList.Add(filedata);
}
}
return returnList;
}
}
public struct GetFileNames
{
/// <summary>
/// Get all filenames with extension in folder and return it in lists
/// </summary>
/// <param name="dataFolder"></param>
/// <param name="extension"></param>
/// <returns></returns>
public static List<string> FromFolder(string dataFolder, string extension)
{
List<string> returnList = new List<string>();
//Open folder and iterate all txt files
foreach (string fileName in Directory.GetFiles(dataFolder))
{
FileInfo f = new FileInfo(fileName);
if (f.Extension == ("." + extension))
returnList.Add(f.Name);
}
return returnList;
}
}
public struct Vector2
{
public float x, y;
public Vector2(float ix, float iy)
{
x = ix;
y = iy;
}
}
public interface Interpolator
{
void Interpolate(List<Vector2> controlPoints, float interval);
float GetY(float x);
}
public struct Lagrange : Interpolator
{
public float _interval, _min, _max;
public List<float> Y;
public void Interpolate(List<Vector2> controlPoints, float interval)
{
_min = controlPoints.FirstOrDefault().x;
_max = controlPoints.LastOrDefault().x;
_interval = interval;
Y = new List<float>();
List<List<float>> Operators = new List<List<float>>();
List<Vector2> result = new List<Vector2>();
try
{
if (controlPoints.Count > 0)
{
//Compute lagrange operator for each x
for (float x = _min; x < _max; x = x + interval)
{
//list of float to hold the Lagrange operators
List<float> L = new List<float>();
//Init the list with 1's
for (int i = 0; i < controlPoints.Count; i++)
L.Add(1);
for (int i = 0; i < L.Count; i++)
for (int k = 0; k < controlPoints.Count; k++)
if (i != k)
L[i] *= (float)(x - controlPoints[k].x) / (controlPoints[i].x - controlPoints[k].x);
Operators.Add(L);
}
//Computing the Polynomial P(x) which is y in our curve
foreach (List<float> O in Operators)
{
float y = 0;
for (int i = 0; i < controlPoints.Count; i++)
{
y += O[i] * controlPoints[i].y;
}
Y.Add(y);
}
}
}
catch (Exception ex)
{
//TODO Raise exception
}
}
/// <summary>
/// Returns either exact Y on the curve or a linear interpolation inbetween points. Min and Max Y values are clamped for X outside the range
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public float GetY(float x)
{
int minIndex, maxIndex;
if (x >= _max)
return Y.LastOrDefault();
if (x <= _min)
return Y.FirstOrDefault();
minIndex = (int)System.Math.Floor((x - _min) / _interval);
if (minIndex == 0)
return Y[minIndex];
//If Value is not exact, perform linear interpolation
float inBetween = ((x - _min) % _interval) / _interval;
maxIndex = minIndex + 1;
return (Y[minIndex] + Y[maxIndex] * inBetween);
}
}
public struct Curve
{
//ID of curve
public int ID;
//Control points to interpolate
List<Vector2> _controlPoints;
Interpolator _algorithm;
bool _initialised;
public List<Vector2> controlPoints
{
get
{
return _controlPoints;
}
set
{
_controlPoints = value;
}
}
public void Calculate(List<Vector2> icontrolPoints, float interval, string algorithm)
{
switch (algorithm)
{
case "Lagrange": _algorithm = new Lagrange(); break;
default: _algorithm = new Lagrange(); break;
}
_algorithm.Interpolate(icontrolPoints, interval);
_initialised = false;
}
/// <summary>
/// Calculate curve value at point according to chosen algorithm
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public float GetY(float x)
{
if (_initialised)
return _algorithm.GetY(x);
else
return 0f;
}
}
public struct CurveLibrary
{
public List<Curve> _curves;
public void LoadCurves(string dataFolder, string algorithm)
{
_curves = new List<Curve>();
//Iterate each file and make array of Vector2
List<List<string>> data = new List<List<string>>();
data = Utilities.LoadStrings.FromFolder(dataFolder, "txt");
List<string> names = new List<string>();
names = Utilities.GetFileNames.FromFolder(dataFolder, "txt");
//Iterate through each curve file
for (int i=0; i< data.Count; i++)
{
List<string> curvestring = new List<string>();
curvestring = data[i];
//Empty curves are dumped
if (curvestring.Count < 1)
{
int name = int.Parse(names[i], CultureInfo.InvariantCulture.NumberFormat);
List<Vector2> rawcurve = new List<Vector2>();
try
{
//Get control points
foreach (string pointstring in curvestring)
{
string[] xy = pointstring.Split(' ');
float x = 0f;
float y = 0f;
x = float.Parse(xy[0], CultureInfo.InvariantCulture.NumberFormat);
y = float.Parse(xy[1], CultureInfo.InvariantCulture.NumberFormat);
rawcurve.Add(new Vector2(x, y));
}
//Calculate smallest difference for the X values from each curve. Divide by 4 to get the interval
float interval = 0f;
List<float> differences = new List<float>();
for (int j = 0; j < rawcurve.Count - 1; j++)
differences.Add(rawcurve[j + 1].x - rawcurve[j].x);
interval = differences[0];
for (int j = 1; j < differences.Count; j++)
if (interval > differences[j])
interval = differences[j];
interval = interval / 4f;
//Only curves where the points are not repeated will be included
if (interval > 0f)
{
Curve tcurve = new Curve();
tcurve.ID = name;
tcurve.Calculate(rawcurve, interval, algorithm);
_curves.Add(tcurve);
}
}
catch
{
//If data is bad, skip this curve
}
}
}
}
}
}<file_sep>/npc.cs
using System;
using System.Collections.Generic;
namespace NPC
{
public struct Decision_NPC
{
public int score;
public int positive1;
public int positive2;
public int negative1;
public int negative2;
public void Init()
{
score = 0;
positive1 = 0;
positive2 = 0;
negative1 = 0;
negative2 = 0;
}
}
public struct NPC
{
//Big 5 Personality
public int extroversion;
public int agreeability;
public int openness;
public int conscientiousness;
public int neuroticism;
//Confidence/Ability/Social rank
public int self_belief;
//Emotion
public int fear;
public int anger;
public int happy;
public int sad;
public int shock;
public int pain;
//Physical
public int stamina;
public int health;
//Disposition
public int love;
public int max_love; //Damage - can only go down
public int trust;
public int max_trust; //Damage - can only go down
public int admiration;
//Submissivness is calc from self reliance vs admiration and affects decision making
public int submissivness;
//Bargaining power is calc from personality/health/Disposition and affects decision making
public int bargaining_power;
//History
public List<int> keys, values;
public List<string> comments; //
public void Init()
{
extroversion = 50;
agreeability = 50;
openness = 50;
conscientiousness = 50;
neuroticism = 50;
//Confidence/Ability/Social rank
self_belief = 10;
//Emotion
fear = 0;
anger = 0;
happy = 0;
sad = 0;
shock = 0;
pain = 0;
//Physical
stamina = 10;
health = 10;
//Disposition
love = 50;
max_love = 100; //Damage - can only go down
trust = 50;
max_trust = 100; //Damage - can only go down
admiration = 0;
//Submissivness is calc from self reliance vs admiration and affects decision making
submissivness = 0;
//Bargaining power is calc from personality/health/Disposition and affects decision making
bargaining_power = 50;
}
/// <summary>
/// Respond to an event
/// For example someone asks NPC to sell item. NPC response maybe Yes or No,
/// they maybe bullied or charmed or awed or pity you to say yes
/// they maybe provoked or paranoid or disgusted or prey on you to say no
/// Strongest indicator will be primary, while secondary will influence tone
///
/// int[] personality_req refers to Big5 requirements when deciding how to respond to a request
///
/// </summary>
/// <returns>
/// Decision_NPC Returns a score of likelihood of decision, with biggest two negative and positive factors - that will influence tone
/// </returns>
public Decision_NPC Respond(int[] personality_req)
{
Decision_NPC treturn = new Decision_NPC();
treturn.Init();
//Check submissivness self vs admiration
submissivness = admiration - self_belief;
//Generate initial score based on personality
//Score gets modified by Disposition
//Score gets modified by emotion
return treturn;
}
}
} | 9988a279fee651c815a6a35ca35c38247b8ac286 | [
"C#"
] | 3 | C# | iamtanmay/CS_Backend | 96ba162cf2bfa19d352bce7006f7566135eff2db | ed74d1c01dc95f5c06cc094fef3c590e21195b6d | |
refs/heads/master | <repo_name>saiyedulbas/bashar-cms<file_sep>/app/Http/Controllers/bashar.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\againmessage;
use carbon\carbon;
use App\about;
use App\about_point;
use App\service;
class bashar extends Controller
{
function ami(){
return view('index');
}
function tumi(){
return view('front/team');
}
function amra(){
$first = $_POST['sender_name'];
$second = $_POST['sender_email'];
$third = $_POST['sender_message'];
againmessage::insert([
'sender_name' => $first,
'sender_email' => $second,
'sender_message' => $third,
'created_at' => now('Asia/Dhaka'),
]);
return back()->with('status','Your message successfully sent');
}
public function aboutsection(){
$din = about::where('about_status','=',2)->firstOrFail();
$jhula = service::where('service_status','=',1)->orderBy('id','desc')->paginate(3);
$jhima = about_point::where('about_id','=',$din->id)->get();
return view('index',compact('din','jhima','jhula'));
}
}
<file_sep>/app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\againmessage;
use App\about;
use carbon\carbon;
use App\about_point;
use App\service;
use Auth;
use Hash;
use App\User;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
public function aboutsectionultra(){
$pagol = about::all();
return view('admin/about',compact('pagol'));
}
public function contactmessageview(){
$dis = againmessage::paginate(2);
$bagi = againmessage::onlyTrashed()->get();
return view('admin/message/message',compact('dis','bagi'));
}
public function contactdelete($zind){
againmessage::where('id','=',$zind)->delete();
return back();
}
public function contactmark($zind){
againmessage::where('id','=',$zind)->update([
'message_status' => 2
]);
return back();
}
public function contactedit($zind){
$lathi = againmessage::findOrFail($zind);
return view('admin/message/edit',compact('lathi'));
}
public function contactupdate(Request $request){
$request->validate([
'sender_name' => 'required',
'sender_email' => 'required|email',
]);
$first = $request->sender_name;
$second = $request->sender_email;
$third = $request->hiddenin;
againmessage::where('id','=',$third)->update([
'sender_name' => $first,
'sender_email' => $second,
]);
return back();
}
public function abouteditinfo(Request $request){
$first = $request->abouttitle;
$second = $request->aboutcontent;
$third = $request->aboutpoint;
$tuna = about::insertGetId([
'about_title' => $first,
'about_content' => $second,
'about_point' => $third,
'created_at' => carbon::now(),
]);
if($request->hasFile('againfile')){
$path = $request->file('againfile')->store('about_images');
about::where('id','=',$tuna)->update([
'about_image' => $path
]);
return back();
}
return back();
}
public function aboutidtake($mina){
about::where('about_status','=',2)->update([
'about_status' => 1
]);
about::where('id','=',$mina)->update([
'about_status' => 2
]);
return back();
}
public function pointinput(){
$first = $_POST['selectin'];
$second = $_POST['enterpoint'];
about_point::insert([
'about_id' => $first,
'point' => $second,
'created_at' => carbon::now(),
]);
return back();
}
public function mesagerestore($restoreid){
againmessage::where('id','=',$restoreid)->restore();
return back();
}
public function aboutagainedit($zinda){
$lathi = about::where('id','=',$zinda)->firstOrFail();
return view('admin/again',compact('lathi'));
}
public function editupdateagain(Request $request){
$first = $request->about_title;
$second = $request->about_content;
$third = $request->about_point;
$fourth = $request->hiddenin;
about::where('id','=',$fourth)->update([
'about_title' => $first,
'about_content' => $second,
'about_point' => $third,
]);
return back();
}
public function servicesection(){
$pagol = service::all();
return view('admin/service',compact('pagol'));
}
public function serviceactive(Request $request){
$first = $request->servicetitle;
$second = $request->servicecontent;
$sixth = service::insertGetId([
'service_title' => $first,
'service_details' => $second,
'created_at' => carbon::now(),
]);
if($request->hasFile('fileinput')){
$path = $request->file('fileinput')->store('service_images');
service::where('id','=',$sixth)->update([
'service_image' => $path
]);
return back();
}
return back();
}
public function serviceactiveon($jibon){
service::where('id','=',$jibon)->update([
'service_status' => 1
]);
return back();
}
public function servicedeactive($jibona){
service::where('id','=',$jibona)->update([
'service_status' => 2
]);
return back();
}
public function passwordchange(){
return view('admin/change');
}
public function changepasswordagain(Request $request){
$request->validate([
'oldpassword' => '<PASSWORD>',
'newpassword' => '<PASSWORD>',
'confirmpassword' => 'required|same:newpassword',
]);
if(Hash::check($request->oldpassword,Auth::user()->password)){
User::where('id','=',Auth::user()->id)->update([
'password' => <PASSWORD>($request->newpassword),
]);
return back()->with('smoke','your password has been changed successfully');
}
else{
return back()->withErrors('old password does not match');
}
}
function uploadphoto(){
return view('admin/upload');
}
public function profileupdate(Request $request){
$first = $request->user_name;
$third = $request->birla;
User::where('id','=',$third)->update([
'name' => $first,
]);
if($request->hasFile('subjective')){
$path = $request->file('subjective')->store('user_images');
User::where('id','=',$third)->update([
'photo' => $path,
]);
return back();
}
return back();
}
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| 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('/bashar',function(){
echo 'saiyedul bashar is flying';
});
Route::get('/tumi','bashar@tumi');
Route::post('/contact/submit','bashar@amra');
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/changepassword', 'HomeController@passwordchange')->name('passwordchange');
Route::get('/contact/message/view', 'HomeController@contactmessageview');
Route::get('/contact/delete/{message_id}', 'HomeController@contactdelete');
Route::get('/contact/mark/{message_id}', 'HomeController@contactmark');
Route::get('/contact/edit/{message_id}', 'HomeController@contactedit');
Route::post('/contact/update', 'HomeController@contactupdate');
Route::post('/abouteditinfo', 'HomeController@abouteditinfo');
Route::post('/pointinput', 'HomeController@pointinput');
Route::post('/change/password/again', 'HomeController@changepasswordagain');
Route::post('/edit/update/again', 'HomeController@editupdateagain');
Route::post('/serviceactive', 'HomeController@serviceactive');
Route::post('/profile/update', 'HomeController@profileupdate');
Route::get('/mesage/restore/{restoreid}', 'HomeController@mesagerestore');
Route::get('/about/again/edit/{againid}', 'HomeController@aboutagainedit');
Route::get('/servicesection', 'HomeController@servicesection');
Route::get('/upload/photo', 'HomeController@uploadphoto');
Route::get('/aboutsection', 'HomeController@aboutsectionultra');
Route::get('/about/idtake/{take}', 'HomeController@aboutidtake');
Route::get('/serviceactiveon/{chara}', 'HomeController@serviceactiveon');
Route::get('/servicedeactive/{ghara}', 'HomeController@servicedeactive');
Route::get('/', 'bashar@aboutsection');
| 5ac82bb378983f714c67ae0def5af6c093ae9306 | [
"PHP"
] | 3 | PHP | saiyedulbas/bashar-cms | 1d8a8f96aa9f028b09abad27c6288289465066d6 | e8f0a73d0f99ed5a5ab91f5fdedaf75471fafdb4 | |
refs/heads/master | <repo_name>jackbenny/autogitit<file_sep>/autogitit.sh
#!/bin/bash
################################################################################
# #
# Copyright (C) 2013 <NAME> <<EMAIL>> #
# #
# This program is free software; you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 2 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #
# #
################################################################################
###############################################################################
# #
# autogitit #
# A simple shell script to automatically commit a directory to git. #
# I myself use it as a kind of directory snapshot. I got the idea with #
# directory snapshots while playing with Solaris 11. I wanted something #
# similar but more universal without a specific filesystem and something #
# that used commons tools, and Git was the obvious choice. #
# #
###############################################################################
VERSION="Version 0.1"
AUTHOR="(c) 2013 <NAME> (<EMAIL>)"
## BEGIN SETTINGS ##
## Set this to the directory to auto commit ##
GITDIR="/home/jackbenny/gittest"
## END SETTINGS ##
## Other variables ##
WHICH="/usr/bin/which"
GIT="`${WHICH} git`"
DATE="`${WHICH} date`"
## Sanity checks ##
if [ ! -x $GIT ]; then
printf "It seems you don't have git installed.\n"
printf "Check the GIT variable in autogitit if your sure it's "
printf "installed.\n"
exit 1
fi
if [ ! -f $CONFIG ]; then
printf "Can't find config file at $CONFIG\n"
exit 1
fi
## Script begins here ##
TIMESTAMP=`${DATE} --rfc-3339=seconds`
## Define some functions ##
init()
{
test -d $GITDIR/.git
if [ $? -ne 0 ]; then
printf "Initlizing $GITDIR\n"
cd $GITDIR
git init
main
exit 0
else
printf "It seems that $GITDIR is already a initalized"
printf ". Continuing....\n"
printf "Remove --init from commandline to silence this"
printf " message\n"
exit 1
fi
}
main()
{
cd $GITDIR
git status | grep "nothing to commit" > /dev/null
if [ $? -eq 0 ]; then
exit 0
else
git add -A
git commit -m "autogitit on $TIMESTAMP" > /dev/null
fi
}
## Here we go ##
while [[ -n "$1" ]]; do
case "$1" in
--init)
init
;;
esac
done
test -d $GITDIR/.git
if [[ $? -ne 0 ]]; then
printf "$GITDIR is not initalized as a git dir.\n"
printf "Use --init to initalize.\n"
else
main
fi
<file_sep>/README.md
autogitit
=========
autogitit is a small Bash script I wrote to automatically commit changes in a spcified direcory to git. Each time the script runs it checks if there is something new to commit or not. If the directory is clean the script will simply quit and do nothing.
The usage for it could be both as a kind of directory snapshot but also for your regular git repos so you don't forget to commit any changes. The downside if you use it your for regular git repos is that the commit messages will be marked with "autogitit on YYYY-MM-DD HH:MM:SS" and it won't push to remotes (as of right now anyway).
How to use it
-------------
First of all change the variable GITDIR in autogitit.sh to point to the directory that you want to auto commit to. It's between the START CONFIG and END CONFIG comments.
Next add an entry for autogitit.sh in your crontab, for example to run every five minutes. Below is an example of how to do it and what how the line will look like.
$ crontab -e
*/5 * * * * /home/user/autogitit.sh
If you want to initalize a directory for use with autogitit you can either do this by your self with a "git init" or by running the script with the --init option.
Contributing
------------
Any contributions are welcome since this is only half done, althouh it's working and should run out of the box on most Unix-like systems.
Add yourself to the THANKS file if you like to after contributing to the project.
| 2a6fe34a395ed6cbe52919941ac055c1ae7533b6 | [
"Markdown",
"Shell"
] | 2 | Shell | jackbenny/autogitit | 1127b7d4612bb5698d66b133f05667bcfe393f67 | b4640faf3e50a45c9fc0c91156355c707c068159 | |
refs/heads/main | <file_sep>const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config();
// Connect to MongoDB
module.exports = () => {
mongoose.connect(
process.env.DB_CONNECT,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log('Connected to MongoDB Atlas');
}
);
};
<file_sep>// Validation
const Joi = require('joi');
const registerValidation = (requestBody) => {
const schema = Joi.object({
name: Joi.string().min(6).required(),
email: Joi.string().required().min(6).email(),
password: Joi.string().required().min(6),
});
return schema.validate(requestBody);
};
const loginValidation = (requestBody) => {
const schema = Joi.object({
email: Joi.string().required().min(6).email(),
password: Joi.string().required().min(6),
});
return schema.validate(requestBody);
};
module.exports.registerValidation = registerValidation;
module.exports.loginValidation = loginValidation;
| 42feb65b54a5ef781edcdbf7c907516cd271e92b | [
"JavaScript"
] | 2 | JavaScript | dephraiim/chelsea-university-server | bd6c59621741dc4a538649f2ef7cafb1243d97ce | 95887e52877f818cf050e7834909128dc5a4871d | |
refs/heads/main | <repo_name>y-arimura1222/todo-app-vanilla-js<file_sep>/js/index.js
'use strict'
{
const onClickAdd = () => {
// 入力されたテキストを取得&初期化
const inputText = document.getElementById('add-text').value;
document.getElementById('add-text').value = "";
// リストに追加するため必要な要素を生成
const li = document.createElement("li");
const div = document.createElement("div");
div.className = "list-row";
const p = document.createElement("p");
p.innerText = inputText;
const completeButton = document.createElement("button");
completeButton.innerText = "完了";
const deleteButton = document.createElement("button");
deleteButton.innerText = "削除";
// 完了ボタンのイベント
completeButton.addEventListener("click", () => {
// 押されたボタンのテキストを取得
const completeTarget = completeButton.parentNode;
const completeText = completeTarget.firstElementChild.innerText;
// リストの初期化
completeTarget.textContent = null;
// 完了済みリストに追加する要素を生成
p.innerText = completeText;
const backButton = document.createElement("button");
backButton.innerText = "戻す";
li.appendChild(completeTarget);
completeTarget.appendChild(p);
completeTarget.appendChild(backButton);
document.getElementById("complete-list").appendChild(li);
// 戻すボタンを押したときの処理
backButton.addEventListener("click", () => {
// 押されたボタンのテキストを取得
const backTarget = backButton.parentNode;
const backText = backTarget.firstElementChild.innerText;
// リストの初期化
backTarget.textContent = null;
// 未完了リストに戻す要素を生成
p.innerText = backText;
li.appendChild(div);
backTarget.appendChild(p);
backTarget.appendChild(completeButton);
backTarget.appendChild(deleteButton);
document.getElementById("incomplete-list").appendChild(li);
})
})
// 削除ボタンのイベント
deleteButton.addEventListener("click", () => {
document.getElementById("incomplete-list").removeChild(li);
})
// 子要素の生成
li.appendChild(div);
div.appendChild(p);
div.appendChild(completeButton);
div.appendChild(deleteButton);
// 未完了リストに追加
document.getElementById("incomplete-list").appendChild(li);
}
document.getElementById("add-button").addEventListener("click", () => onClickAdd());
}
<file_sep>/README.md
# 簡単な todo app を vanilla で作成
| f8917b26c84b51e913d7c2201389c26626ca997c | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | y-arimura1222/todo-app-vanilla-js | 673b18c4b6b2b3b6a91b0c9382b1038b011df00e | fa7ed3483fd6d09fafed143cc27e410212903b95 | |
refs/heads/master | <file_sep>Template.notePage.helpers({
url: function() { return this.url; }
});
<file_sep>Template.treeSubmit.helpers({
tree: getTreeOptions
});
Template.treeSubmit.events({
'submit form': function(e) {
e.preventDefault();
var tree = {
name: $(e.target).find('[name=name]').val(),
parent: $(e.target).find('[name=parent]').val()
};
Meteor.call('treeInsert', tree, function(error, result) {
// display the error to the user and abort
if (error)
return alert(error.reason);
// show this result but route anyway
if (result.branchExists) {
alert('This branch already exists');
return;
}
Router.go('treeManage');
});
}
});<file_sep>Template.search.helpers({
notes: function() {
return Notes.find({ section: null },
{ sort: {name: 1} });
}
});
<file_sep>QuickNote
=========
QuickNote is a note-taking website implemented in [Meteor](https://www.meteor.com).
QuickNote main features are to:
- Organize the notes in a tree structure
- Use the [Markdown](http://daringfireball.net/linked/2014/01/08/markdown-extension) language to enter rich text
I'm not sure if anybody else would be interested in such a project, but you are welcome to give it a spin, especially if you are interested in learning Meteor. In order to work, this project requires the following [Meteor packages](https://atmospherejs.com/):
- accounts-password (Password support for accounts)
- copleykj:jquery-autosize (Automatically adjust textarea height based on content)
- ian:accounts-ui-bootstrap-3 (Bootstrap-styled accounts-ui)
- iron:router (Routing specifically designed for Meteor)
- markdown (Markdown-to-HTML processor)
- meteor-platform (Include a standard set of Meteor packages)
- mizzao:bootstrap-3 (HTML, CSS, and JS framework)
- mystor:device-detection (Client-Side Device Type Detection)
- sacha:spin (Simple spinner package for Meteor)
- underscore (Collection of small helpers: _.map, _.eac..)<file_sep>Tree = new Mongo.Collection('tree');
getTreeOptions = function getTreeOptions() {
var tree = getTree();
return getOptions(tree, '');
}
function getOptions(branches, padding) {
var result = [];
_.each(branches, function(branch) {
result.push({ id: branch.element._id, label: (padding + branch.element.name) });
result = result.concat(getOptions(branch.children, padding + branch.element.name + ' / '));
});
return result;
}
function ownsTree(userId, tree) { return tree.userId == userId; }
Tree.allow({
insert: function(userId, tree) { return true; },
update: ownsTree,
remove: ownsTree
});
Tree.deny({
update: function(userId, tree, fieldNames) {
// may only edit the following two fields:
return (_.without(fieldNames, 'name', 'path', 'parent', 'level', 'collapse').length > 0); }
});
Meteor.methods({
treeInsert: function(treeAttributes) {
check(Meteor.userId(), String);
check(treeAttributes, {
name: String,
parent: String
});
var user = Meteor.user();
var existingBranch = Tree.findOne({name: treeAttributes.name, parent: treeAttributes.parent, userId: user._id});
if (typeof existingBranch != 'undefined') {
return {
branchExists: true,
_id: existingBranch._id
}
}
var tree = _.extend(treeAttributes, {
userId: user._id,
submitted: new Date()
});
var treeId = Tree.insert(tree);
return {
_id: treeId
};
}
});
<file_sep>Meteor.subscribe('notes');
Meteor.subscribe('tree');<file_sep>Meteor.publish('notes', function() {
return Notes.find({ userId: this.userId });
});
Meteor.publish('tree', function() {
return Tree.find({ userId: this.userId });
});<file_sep>// This section sets up some basic app metadata,
// the entire section is optional.
App.info({
id: 'com.meteor.quicknote',
name: 'QuickNote',
description: 'QuickNote'
});<file_sep>Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound',
waitOn: function() { return Meteor.subscribe('notes'); }
});
Router.route('/', {
name: 'notesList',
data: function() { section = 'all'; return 'all'; },
});
Router.route('/sections/:_id', {
name: 'sections',
template: 'notesList',
data: function() { section = this.params._id; return this.params._id; },
});
Router.route('/notes/:_id', {
name: 'notePage',
data: function() { section = "record";
note = Notes.findOne(this.params._id);
return note;
}
});
Router.route('/notes/:_id/edit', {
name: 'noteEdit',
data: function() { return Notes.findOne(this.params._id); }
});
Router.route('/submit', {name: 'noteSubmit'});
Router.route('/search', {
name: 'search',
data: function() { section = ''; }
});
Router.route('/tree', {
name: 'treeManage',
template: 'treeManage',
data: function() { section = ''; }
});
Router.route('/tree/:_id/edit', {
name: 'treeEdit',
data: function() { section = this.params._id; return Tree.findOne(this.params._id); }
});
Router.route('/tree/submit', {
name: 'treeSubmit',
data: function() { section = ''; }
});
var requireLogin = function() {
if (! Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render('accessDenied');
}
} else {
this.next();
}
}
Router.onBeforeAction('dataNotFound', {only: 'notePage'});
Router.onBeforeAction(requireLogin);
<file_sep>
Template.treeEdit.helpers({
tree: getTreeOptions,
isParent: function(arg) { return (this.id == arg.parent); },
isCollapse: function() {
var val = Tree.findOne(section).collapse
return (typeof val != 'undefined' && val == 'on') ? 'checked' : '';
}
});
Template.treeEdit.events({
'submit form': function(e) {
e.preventDefault();
var currentTreeId = this._id;
var branch = this;
var treeProperties = {
name: $(e.target).find('[name=name]').val(),
parent: $(e.target).find('[name=parent]').val(),
collapse: $('input[name=collapse]:checked').val()
}
if (typeof treeProperties.collapse == 'undefined') treeProperties.collapse = '';
if (treeProperties.parent == this._id) {
alert('A branch cannot be its own parent');
return;
}
Tree.update(currentTreeId, {$set: treeProperties}, function(error) {
if (error) {
// display the error to the user
alert(error.reason);
} else {
Router.go('treeManage');
}
});
},
'click .delete': function(e) {
e.preventDefault();
if (confirm("Delete this branch?")) {
var currentTreeId = this._id;
// Checks that there is no subtree
var subtrees = Tree.findOne({parent: this._id});
if (typeof subtrees != 'undefined') {
alert('Please delete any subtree before');
return;
}
// Checks there are no note in the branch
var notes = Notes.findOne({section: this._id});
if (typeof notes != 'undefined') {
alert('Please delete any associated note before');
return;
}
Tree.remove(currentTreeId);
Router.go('treeManage');
}
}
});<file_sep>Template.noteItem.helpers({
ownNote: function() {
return this.userId === Meteor.userId();
},
contentSummary: function() {
if (section == 'record') return this.content;
return this.content.split('\n').splice(0, 5).join('\n');
}
}); | 55ecc496f6390c0fce6b8c7b4d483c81b8958057 | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | lpoulain/QuickNote | 7fa387237231364175e968b555505e9041f52f9e | a2a550f42fddf2e33abe0df08da06525e75fb3c3 | |
refs/heads/master | <repo_name>mik3lon/api<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Addclickbackground/AddclickbackgroundCollection.php
<?php
namespace AdServer\V1\Rest\Addclickbackground;
use Zend\Paginator\Paginator;
class AddclickbackgroundCollection extends Paginator
{
}
<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Addcredit/AddcreditCollection.php
<?php
namespace AdServer\V1\Rest\Addcredit;
use Zend\Paginator\Paginator;
class AddcreditCollection extends Paginator
{
}
<file_sep>/api/module/UserManagement/Module.php
<?php
require __DIR__ . '/src/UserManagement/Module.php';<file_sep>/api/module/UserManagement/config/module.config.php
<?php
return array(
'session' => array(
'name' => 'api-session',
),
);<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Company/CompanyEntity.php
<?php
namespace AdServer\V1\Rest\Company;
class CompanyEntity
{
public $id_company;
public $name_company;
public $user_id;
public $phone_company;
}
<file_sep>/api/module/Admin/src/Admin/Controller/IndexController.php
<?php
/**
* @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
* @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com)
*/
namespace Admin\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Db\Sql\Select;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Paginator\Adapter\DbSelect;
use ZF\ApiProblem\ApiProblem;
use ZF\Rest\AbstractResourceListener;
class IndexController extends AbstractActionController
{
const ROUTE_CHANGEPASSWD = 'zfcuser/changepassword';
const ROUTE_LOGIN = 'zfcuser/login';
const ROUTE_REGISTER = 'zfcuser/register';
const ROUTE_CHANGEEMAIL = 'zfcuser/changeemail';
const CONTROLLER_NAME = 'zfcuser';
public function indexAction()
{
return $this->redirect()->toRoute(static::ROUTE_LOGIN);
}
}
<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Substractcredit/SubstractcreditEntity.php
<?php
namespace AdServer\V1\Rest\Substractcredit;
class SubstractcreditEntity
{
public $substractcredit_id;
public $credits;
}
<file_sep>/api/module/Admin/src/Admin/Controller/UserController.php
<?php
namespace Admin\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Admin\Entity\User;
use ZfcUser\Service\User as UserService;
class UserController extends AbstractActionController
{
protected $_objectManager;
protected $userService;
const ROUTE_CHANGEPASSWD = 'zfcuser/changepassword';
const ROUTE_LOGIN = 'zfcuser/login';
const ROUTE_REGISTER = 'zfcuser/register';
const ROUTE_CHANGEEMAIL = 'zfcuser/changeemail';
const CONTROLLER_NAME = 'zfcuser';
public function indexAction()
{
if (!$this->zfcUserAuthentication()->hasIdentity()) {
return $this->redirect()->toRoute(static::ROUTE_LOGIN);
}
$user = $this->zfcUserAuthentication()->getIdentity();
$roles = $user->getRoles();
$administrator = false;
foreach ($roles as $role) {
# code...
if($role->getRoleId() == "administrator")
$administrator=true;
}
if($administrator){
return new ViewModel(array(
'users' => $user,
'roles' => $roles
));
}else{
return $this->forward()->dispatch('Admin\Controller\User', array('action' => 'error'));
}
// $email = $this->getUserService()->getAuthService()->getIdentity()->getId();
// $users = $this->getObjectManager()->getRepository('\Admin\Entity\User')->findAll();
// $roles = $this->getObjectManager()->getRepository('\Admin\Entity\Role')->findAll();
return new ViewModel(array(
'users' => $user,
'roles' => $roles
));
}
public function errorAction(){
return new ViewModel();
}
public function addAction()
{
if ($this->request->isPost()) {
$user = new User();
$user->setFullName($this->getRequest()->getPost('fullname'));
$this->getObjectManager()->persist($user);
$this->getObjectManager()->flush();
$newId = $user->getId();
return $this->redirect()->toRoute('home');
}
return new ViewModel();
}
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
$user = $this->getObjectManager()->find('\Admin\Entity\User', $id);
if ($this->request->isPost()) {
$user->setFullName($this->getRequest()->getPost('fullname'));
$this->getObjectManager()->persist($user);
$this->getObjectManager()->flush();
return $this->redirect()->toRoute('home');
}
return new ViewModel(array('user' => $user));
}
public function deleteAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
$user = $this->getObjectManager()->find('\Admin\Entity\User', $id);
if ($this->request->isPost()) {
$this->getObjectManager()->remove($user);
$this->getObjectManager()->flush();
return $this->redirect()->toRoute('home');
}
return new ViewModel(array('user' => $user));
}
protected function getObjectManager()
{
if (!$this->_objectManager) {
$this->_objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
return $this->_objectManager;
}
public function getUserService()
{
if (!$this->userService) {
$this->userService = $this->getServiceLocator()->get('zfcuser_user_service');
}
return $this->userService;
}
}<file_sep>/api/module/Admin/src/Admin/Controller/AdvertisementController.php
<?php
namespace Admin\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Admin\Entity\Advertisement;
use ZfcUser\Service\User as UserService;
use Admin\Form\AddAdvertismentForm;
class AdvertisementController extends AbstractActionController
{
protected $_objectManager;
protected $userService;
const ROUTE_CHANGEPASSWD = 'zfcuser/changepassword';
const ROUTE_LOGIN = 'zfcuser/login';
const ROUTE_REGISTER = 'zfcuser/register';
const ROUTE_CHANGEEMAIL = 'zfcuser/changeemail';
const CONTROLLER_NAME = 'zfcuser';
public function indexAction()
{
if (!$this->zfcUserAuthentication()->hasIdentity()) {
return $this->redirect()->toRoute(static::ROUTE_LOGIN);
}
$user = $this->getUserService()->getAuthService()->getIdentity();
$roles = $user->getRoles();
$administrator = false;
foreach ($roles as $role) {
# code...
if($role->getRoleId() == "administrator")
$administrator=true;
}
if(!$administrator)
return $this->forward()->dispatch('Admin\Controller\User', array('action' => 'error'));
$id_user = $user->getId();
/****************************************** Get user ads (Improve it!!!! ) **********************************/
$ads = $this->getObjectManager()->getRepository('\Admin\Entity\Advertisement')->findAll();
$user_ads = array();
foreach ($ads as $ad) {
# code...
if($ad->getUser()[0]->getId() == $id_user)
$user_ads[] = $ad;
}
/*************************************************************************************************************/
return new ViewModel(array(
'ads' => $user_ads
));
// $users = $this->getObjectManager()->getRepository('\Admin\Entity\User')->findAll();
// $roles = $this->getObjectManager()->getRepository('\Admin\Entity\Role')->findAll();
}
public function errorAction(){
return new ViewModel();
}
public function addadAction()
{
$user = $this->getUserService()->getAuthService()->getIdentity();
$roles = $user->getRoles();
$administrator = false;
foreach ($roles as $role) {
# code...
if($role->getRoleId() == "administrator")
$administrator=true;
}
if(!$administrator)
return $this->forward()->dispatch('Admin\Controller\User', array('action' => 'error'));
$form = new AddAdvertismentForm();
// if is post
$request = $this->getRequest();
if ($request->isPost()) {
$postArr = $request->getPost()->toArray();
$fileArr = $this->params()->fromFiles('file');
$formData = array_merge(
$postArr, //POST
array('file' => $fileArr['image-file']) //FILE...
);
$form->setData($formData);
/**
* Valid Form
*/
if($form->isValid()) {
$adapter = new \Zend\File\Transfer\Adapter\Http();
$size = new \Zend\Validator\File\Size(array('min' => 1 )); // minimum bytes filesize, max too..
$files = $request->getFiles()->toArray();
$bannerfile = $files['image-file']['name'];
$backgroundfile = $files['background-file']['name'];
// Create a Advertisement object and persist it
$ad = new Advertisement();
$ad->setName($this->getRequest()->getPost('name'));
$ad->setImage($bannerfile);
$ad->setBackground($backgroundfile);
$ad->setPhone($this->getRequest()->getPost('phone'));
$ad->setNClicks(0);
$ad->setImpressions(0);
$ad->setBackgroundClicks(0);
$ad->setCallClicks(0);
$ad->addUser($user);
$this->getObjectManager()->persist($ad);
$this->getObjectManager()->flush();
$newId = $ad->getId();
// Generate the hash and add it
$hash = hash('sha512', $user->getEmail().substr(1, 3) . " youlikeboizu" . $newId);
$ad->setHash($hash);
$this->getObjectManager()->persist($ad);
$this->getObjectManager()->flush();
/**
* Valid Upload
*/
if($adapter->isValid()) {
$oldmask = umask(0);
mkdir('/var/www/html/api/public/img/' . $newId , 0777);
umask($oldmask);
$adapter->setDestination('/var/www/html/api/public/img/' . $newId . "/" );
if($adapter->receive($fileArr['image-file'])) {
$filename = $adapter->getFileName();
// Do something..
}
}
// Form is valid, save the form!
return $this->redirect()->toRoute('advertisement');
}
}
return new ViewModel(array(
'form' => $form));
}
public function editadAction()
{
$user = $this->getUserService()->getAuthService()->getIdentity();
$roles = $user->getRoles();
$administrator = false;
foreach ($roles as $role) {
# code...
if($role->getRoleId() == "administrator")
$administrator=true;
}
if(!$administrator)
return $this->forward()->dispatch('Admin\Controller\User', array('action' => 'error'));
$id = (int) $this->params()->fromRoute('id', 0);
$ad = $this->getObjectManager()->find('\Admin\Entity\Advertisement', $id);
if ($this->request->isPost()) {
$ad->setName($this->getRequest()->getPost('name'));
$ad->setImage($this->getRequest()->getPost('image'));
$ad->setBackground($this->getRequest()->getPost('background'));
$ad->setPhone($this->getRequest()->getPost('phone'));
$this->getObjectManager()->persist($ad);
$this->getObjectManager()->flush();
return $this->redirect()->toRoute('advertisement');
}
return new ViewModel(array('ad' => $ad));
}
public function deleteadAction()
{
$user = $this->getUserService()->getAuthService()->getIdentity();
$roles = $user->getRoles();
// Check for administrator permissions
$administrator = false;
foreach ($roles as $role) {
# code...
if($role->getRoleId() == "administrator")
$administrator=true;
}
// If user is administrator, then go to error (Not allowed)
if(!$administrator)
return $this->forward()->dispatch('Admin\Controller\User', array('action' => 'error'));
$id = (int) $this->params()->fromRoute('id', 0);
$ad = $this->getObjectManager()->find('\Admin\Entity\Advertisement', $id);
$id_ad = $ad->getId();
if ($this->request->isPost()) {
// Remove ad
$this->getObjectManager()->remove($ad);
$this->getObjectManager()->flush();
// Remove folder
$dir = '/var/www/html/api/public/img/' . $id_ad;
system("rm -rf ". escapeshellarg($dir));
return $this->redirect()->toRoute('advertisement');
}
return new ViewModel(array('ad' => $ad));
}
protected function getObjectManager()
{
if (!$this->_objectManager) {
$this->_objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
return $this->_objectManager;
}
public function getUserService()
{
if (!$this->userService) {
$this->userService = $this->getServiceLocator()->get('zfcuser_user_service');
}
return $this->userService;
}
}<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Substractcredit/SubstractcreditMapper.php
<?php
namespace AdServer\V1\Rest\Substractcredit;
use Zend\Db\Sql\Select;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Paginator\Adapter\DbSelect;
class SubstractcreditMapper {
protected $adapter;
public function __construct(AdapterInterface $adapter)
{
$this->adapter = $adapter;
}
public function fetchAll()
{
$select = new Select('user_credits');
$paginatorAdapter = new DbSelect($select, $this->adapter);
$collection = new SubstractcreditEntityCollection($paginatorAdapter);
return $collection;
}
public function fetchOne($adId)
{
$sql = 'SELECT * FROM user_credits WHERE user_id = ?';
$resultset = $this->adapter->query($sql, array($adId));
$data = $resultset->toArray();
if (!$data) {
return false;
}
$new_credits = 0;
if($data[0]['credits'] > 0)
$new_credits = $data[0]['credits'] - 1;
$sql = 'UPDATE user_credits SET credits = "' . $new_credits . '" WHERE user_id = ?';
$resultset = $this->adapter->query($sql, array($adId));
$entity = new SubstractcreditEntity();
$entity->substractcredit_id = $data[0]['user_id'];
$entity->credits = $new_credits;
return $entity;
}
}
<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Addclickbanner/AddclickbannerCollection.php
<?php
namespace AdServer\V1\Rest\Addclickbanner;
use Zend\Paginator\Paginator;
class AddclickbannerCollection extends Paginator
{
}
<file_sep>/api/module/Admin/Module.php
<?php
namespace Admin;
use Zend\EventManager\EventInterface as Event;
class Module
{
private $EntityManager;
public function onBootstrap(Event $e)
{
$eventManager = $e->getApplication()->getEventManager();
$sharedEventManager = $eventManager->getSharedManager();
$services = $e->getApplication()->getServiceManager();
$this->EntityManager = $services->get('Doctrine\ORM\EntityManager');
// $application = $e->getApplication();
// $services = $application->getServiceManager();
// $em = $e->getApplication()->getEventManager();
// $em = \Zend\EventManager\StaticEventManager::getInstance();
// $serviceManager = $e->getApplication()->getServiceManager();
$sharedEventManager->attach('ZfcUser\Service\User', 'register.post', function($ev) {
$user = $ev->getParam('user'); // User account object
$roles = $this->EntityManager->getRepository('\Admin\Entity\Role')->findAll();
// Perform your custom action here
// $user->getId()
$user->addRole($roles[0]);
$this->EntityManager->persist($user);
$this->EntityManager->flush();
});
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
<file_sep>/api/module/AdServer/Module.php
<?php
require __DIR__ . '/src/AdServer/Module.php';<file_sep>/api/module/AdServer/config/module.config.php
<?php
return [
'session' => array(
'name' => 'api-session',
),
'router' => [
'routes' => [
'ad-server.rest.ad' => [
'type' => 'Segment',
'options' => [
'route' => '/ad[/:id_ad]',
'defaults' => [
'controller' => 'AdServer\\V1\\Rest\\Ad\\Controller',
],
],
],
'ad-server.rest.company' => [
'type' => 'Segment',
'options' => [
'route' => '/company[/:id_company]',
'defaults' => [
'controller' => 'AdServer\\V1\\Rest\\Company\\Controller',
],
],
],
'ad-server.rest.addcredit' => [
'type' => 'Segment',
'options' => [
'route' => '/addcredit[/:addcredit_id]',
'defaults' => [
'controller' => 'AdServer\\V1\\Rest\\Addcredit\\Controller',
],
],
],
'ad-server.rest.addclickbanner' => [
'type' => 'Segment',
'options' => [
'route' => '/addclickbanner[/:addclickbanner_id]',
'defaults' => [
'controller' => 'AdServer\\V1\\Rest\\Addclickbanner\\Controller',
],
],
],
'ad-server.rest.addclickbackground' => [
'type' => 'Segment',
'options' => [
'route' => '/addclickbackground[/:addclickbackground_id]',
'defaults' => [
'controller' => 'AdServer\\V1\\Rest\\Addclickbackground\\Controller',
],
],
],
'ad-server.rest.substractcredit' => [
'type' => 'Segment',
'options' => [
'route' => '/substractcredit[/:substractcredit_id]',
'defaults' => [
'controller' => 'AdServer\\V1\\Rest\\Substractcredit\\Controller',
],
],
],
],
],
'zf-versioning' => [
'uri' => [
0 => 'ad-server.rest.ad',
1 => 'ad-server.rest.company',
2 => 'ad-server.rest.insert-call-click',
3 => 'ad-server.rest.addcredit',
4 => 'ad-server.rest.addclickbanner',
5 => 'ad-server.rest.addclickbackground',
6 => 'ad-server.rest.substractcredit',
],
],
'service_manager' => [
'invokables' => [],
],
'zf-rest' => [
'AdServer\\V1\\Rest\\Ad\\Controller' => [
'listener' => 'AdServer\\V1\\Rest\\Ad\\AdResource',
'route_name' => 'ad-server.rest.ad',
'route_identifier_name' => 'id_ad',
'collection_name' => 'ad',
'entity_http_methods' => [
0 => 'GET',
1 => 'PATCH',
2 => 'PUT',
3 => 'DELETE',
],
'collection_http_methods' => [
0 => 'GET',
1 => 'POST',
2 => 'PATCH',
],
'collection_query_whitelist' => [],
'page_size' => 25,
'page_size_param' => null,
'entity_class' => 'AdServer\\V1\\Rest\\Ad\\AdEntity',
'collection_class' => 'AdServer\\V1\\Rest\\Ad\\AdCollection',
'service_name' => 'Ad',
],
'AdServer\\V1\\Rest\\Company\\Controller' => [
'listener' => 'AdServer\\V1\\Rest\\Company\\CompanyResource',
'route_name' => 'ad-server.rest.company',
'route_identifier_name' => 'id_company',
'collection_name' => 'company',
'entity_http_methods' => [
0 => 'GET',
1 => 'PATCH',
2 => 'PUT',
3 => 'DELETE',
],
'collection_http_methods' => [
0 => 'GET',
1 => 'POST',
],
'collection_query_whitelist' => [],
'page_size' => 25,
'page_size_param' => null,
'entity_class' => 'AdServer\\V1\\Rest\\Company\\CompanyEntity',
'collection_class' => 'AdServer\\V1\\Rest\\Company\\CompanyCollection',
'service_name' => 'Company',
],
'AdServer\\V1\\Rest\\Addcredit\\Controller' => [
'listener' => 'AdServer\\V1\\Rest\\Addcredit\\AddcreditResource',
'route_name' => 'ad-server.rest.addcredit',
'route_identifier_name' => 'addcredit_id',
'collection_name' => 'addcredit',
'entity_http_methods' => [
0 => 'GET',
1 => 'PATCH',
2 => 'PUT',
3 => 'DELETE',
],
'collection_http_methods' => [
0 => 'GET',
1 => 'POST',
],
'collection_query_whitelist' => [],
'page_size' => 25,
'page_size_param' => null,
'entity_class' => 'AdServer\\V1\\Rest\\Addcredit\\AddcreditEntity',
'collection_class' => 'AdServer\\V1\\Rest\\Addcredit\\AddcreditCollection',
'service_name' => 'addcredit',
],
'AdServer\\V1\\Rest\\Addclickbanner\\Controller' => [
'listener' => 'AdServer\\V1\\Rest\\Addclickbanner\\AddclickbannerResource',
'route_name' => 'ad-server.rest.addclickbanner',
'route_identifier_name' => 'addclickbanner_id',
'collection_name' => 'ad',
'entity_http_methods' => [
0 => 'GET',
1 => 'PATCH',
2 => 'PUT',
3 => 'DELETE',
],
'collection_http_methods' => [
0 => 'GET',
1 => 'POST',
],
'collection_query_whitelist' => [],
'page_size' => 25,
'page_size_param' => null,
'entity_class' => 'AdServer\\V1\\Rest\\Addclickbanner\\AddclickbannerEntity',
'collection_class' => 'AdServer\\V1\\Rest\\Addclickbanner\\AddclickbannerCollection',
'service_name' => 'Addclickbanner',
],
'AdServer\\V1\\Rest\\Addclickbackground\\Controller' => [
'listener' => 'AdServer\\V1\\Rest\\Addclickbackground\\AddclickbackgroundResource',
'route_name' => 'ad-server.rest.addclickbackground',
'route_identifier_name' => 'addclickbackground_id',
'collection_name' => 'addclickbackground',
'entity_http_methods' => [
0 => 'GET',
1 => 'PATCH',
2 => 'PUT',
3 => 'DELETE',
],
'collection_http_methods' => [
0 => 'GET',
1 => 'POST',
],
'collection_query_whitelist' => [],
'page_size' => 25,
'page_size_param' => null,
'entity_class' => 'AdServer\\V1\\Rest\\Addclickbackground\\AddclickbackgroundEntity',
'collection_class' => 'AdServer\\V1\\Rest\\Addclickbackground\\AddclickbackgroundCollection',
'service_name' => 'Addclickbackground',
],
'AdServer\\V1\\Rest\\Substractcredit\\Controller' => [
'listener' => 'AdServer\\V1\\Rest\\Substractcredit\\SubstractcreditResource',
'route_name' => 'ad-server.rest.substractcredit',
'route_identifier_name' => 'substractcredit_id',
'collection_name' => 'substractcredit',
'entity_http_methods' => [
0 => 'GET',
1 => 'PATCH',
2 => 'PUT',
3 => 'DELETE',
],
'collection_http_methods' => [
0 => 'GET',
1 => 'POST',
],
'collection_query_whitelist' => [],
'page_size' => 25,
'page_size_param' => null,
'entity_class' => 'AdServer\\V1\\Rest\\Substractcredit\\SubstractcreditEntity',
'collection_class' => 'AdServer\\V1\\Rest\\Substractcredit\\SubstractcreditCollection',
'service_name' => 'Substractcredit',
],
],
'zf-content-negotiation' => [
'controllers' => [
'AdServer\\V1\\Rest\\Ad\\Controller' => 'HalJson',
'AdServer\\V1\\Rest\\Company\\Controller' => 'HalJson',
'AdServer\\V1\\Rest\\InsertCallClick\\Controller' => 'HalJson',
'AdServer\\V1\\Rest\\Addcredit\\Controller' => 'HalJson',
'AdServer\\V1\\Rest\\Addclickbanner\\Controller' => 'HalJson',
'AdServer\\V1\\Rest\\Addclickbackground\\Controller' => 'HalJson',
'AdServer\\V1\\Rest\\Substractcredit\\Controller' => 'HalJson',
],
'accept_whitelist' => [
'AdServer\\V1\\Rest\\Ad\\Controller' => [
0 => 'application/vnd.ad-server.v1+json',
1 => 'application/hal+json',
2 => 'application/json',
],
'AdServer\\V1\\Rest\\Company\\Controller' => [
0 => 'application/vnd.ad-server.v1+json',
1 => 'application/hal+json',
2 => 'application/json',
],
'AdServer\\V1\\Rest\\InsertCallClick\\Controller' => [
0 => 'application/vnd.ad-server.v1+json',
1 => 'application/hal+json',
2 => 'application/json',
],
'AdServer\\V1\\Rest\\Addcredit\\Controller' => [
0 => 'application/vnd.ad-server.v1+json',
1 => 'application/hal+json',
2 => 'application/json',
],
'AdServer\\V1\\Rest\\Addclickbanner\\Controller' => [
0 => 'application/vnd.ad-server.v1+json',
1 => 'application/hal+json',
2 => 'application/json',
],
'AdServer\\V1\\Rest\\Addclickbackground\\Controller' => [
0 => 'application/vnd.ad-server.v1+json',
1 => 'application/hal+json',
2 => 'application/json',
],
'AdServer\\V1\\Rest\\Substractcredit\\Controller' => [
0 => 'application/vnd.ad-server.v1+json',
1 => 'application/hal+json',
2 => 'application/json',
],
],
'content_type_whitelist' => [
'AdServer\\V1\\Rest\\Ad\\Controller' => [
0 => 'application/vnd.ad-server.v1+json',
1 => 'application/json',
],
'AdServer\\V1\\Rest\\Company\\Controller' => [
0 => 'application/vnd.ad-server.v1+json',
1 => 'application/json',
],
'AdServer\\V1\\Rest\\InsertCallClick\\Controller' => [
0 => 'application/vnd.ad-server.v1+json',
1 => 'application/json',
],
'AdServer\\V1\\Rest\\Addcredit\\Controller' => [
0 => 'application/vnd.ad-server.v1+json',
1 => 'application/json',
],
'AdServer\\V1\\Rest\\Addclickbanner\\Controller' => [
0 => 'application/vnd.ad-server.v1+json',
1 => 'application/json',
],
'AdServer\\V1\\Rest\\Addclickbackground\\Controller' => [
0 => 'application/vnd.ad-server.v1+json',
1 => 'application/json',
],
'AdServer\\V1\\Rest\\Substractcredit\\Controller' => [
0 => 'application/vnd.ad-server.v1+json',
1 => 'application/json',
],
],
],
'zf-hal' => [
'metadata_map' => [
'AdServer\\V1\\Rest\\Ad\\AdEntity' => [
'entity_identifier_name' => 'id_ad',
'route_name' => 'ad-server.rest.ad',
'route_identifier_name' => 'id_ad',
'hydrator' => 'Zend\\Stdlib\\Hydrator\\ObjectProperty',
],
'AdServer\\V1\\Rest\\Ad\\AdCollection' => [
'entity_identifier_name' => 'id_ad',
'route_name' => 'ad-server.rest.ad',
'route_identifier_name' => 'id_ad',
'is_collection' => true,
],
'AdServer\\V1\\Rest\\Company\\CompanyEntity' => [
'entity_identifier_name' => 'id_company',
'route_name' => 'ad-server.rest.company',
'route_identifier_name' => 'id_company',
'hydrator' => 'Zend\\Stdlib\\Hydrator\\ObjectProperty',
],
'AdServer\\V1\\Rest\\Company\\CompanyCollection' => [
'entity_identifier_name' => 'id_company',
'route_name' => 'ad-server.rest.company',
'route_identifier_name' => 'id_company',
'is_collection' => true,
],
'AdServer\\V1\\Rest\\Addcredit\\AddcreditEntity' => [
'entity_identifier_name' => 'addcredit_id',
'route_name' => 'ad-server.rest.addcredit',
'route_identifier_name' => 'addcredit_id',
'hydrator' => 'Zend\\Stdlib\\Hydrator\\ObjectProperty',
],
'AdServer\\V1\\Rest\\Addcredit\\AddcreditCollection' => [
'entity_identifier_name' => 'addcredit_id',
'route_name' => 'ad-server.rest.addcredit',
'route_identifier_name' => 'addcredit_id',
'is_collection' => true,
],
'AdServer\\V1\\Rest\\Addclickbanner\\AddclickbannerEntity' => [
'entity_identifier_name' => 'addclickbanner_id',
'route_name' => 'ad-server.rest.addclickbanner',
'route_identifier_name' => 'addclickbanner_id',
'hydrator' => 'Zend\\Stdlib\\Hydrator\\ObjectProperty',
],
'AdServer\\V1\\Rest\\Addclickbanner\\AddclickbannerCollection' => [
'entity_identifier_name' => 'addclickbanner_id',
'route_name' => 'ad-server.rest.addclickbanner',
'route_identifier_name' => 'addclickbanner_id',
'is_collection' => true,
],
'AdServer\\V1\\Rest\\Addclickbackground\\AddclickbackgroundEntity' => [
'entity_identifier_name' => 'addclickbackground_id',
'route_name' => 'ad-server.rest.addclickbackground',
'route_identifier_name' => 'addclickbackground_id',
'hydrator' => 'Zend\\Stdlib\\Hydrator\\ObjectProperty',
],
'AdServer\\V1\\Rest\\Addclickbackground\\AddclickbackgroundCollection' => [
'entity_identifier_name' => 'addclickbackground_id',
'route_name' => 'ad-server.rest.addclickbackground',
'route_identifier_name' => 'addclickbackground_id',
'is_collection' => true,
],
'AdServer\\V1\\Rest\\Substractcredit\\SubstractcreditEntity' => [
'entity_identifier_name' => 'substractcredit_id',
'route_name' => 'ad-server.rest.substractcredit',
'route_identifier_name' => 'substractcredit_id',
'hydrator' => 'Zend\\Stdlib\\Hydrator\\ObjectProperty',
],
'AdServer\\V1\\Rest\\Substractcredit\\SubstractcreditCollection' => [
'entity_identifier_name' => 'substractcredit_id',
'route_name' => 'ad-server.rest.substractcredit',
'route_identifier_name' => 'substractcredit_id',
'is_collection' => true,
],
],
],
'zf-content-validation' => [
'AdServer\\V1\\Rest\\Ad\\Controller' => [
'input_filter' => 'AdServer\\V1\\Rest\\Ad\\Validator',
],
],
'input_filters' => [
'AdServer\\V1\\Rest\\Ad\\Validator' => [],
],
'zf-mvc-auth' => [
'authorization' => [
'AdServer\\V1\\Rest\\Ad\\Controller' => [
'entity' => [
'GET' => false,
'POST' => false,
'PATCH' => false,
'PUT' => false,
'DELETE' => false,
],
'collection' => [
'GET' => false,
'POST' => true,
'PATCH' => false,
'PUT' => false,
'DELETE' => false,
],
],
],
],
];
<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Addclickbackground/AddclickbackgroundEntity.php
<?php
namespace AdServer\V1\Rest\Addclickbackground;
class AddclickbackgroundEntity
{
public $addclickbackground_id;
public $name_ad;
public $image_ad;
public $background_ad;
public $phone_ad;
public $n_clicks;
public $n_impressions;
public $n_clicks_background;
}
<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Company/CompanyMapper.php
<?php
namespace AdServer\V1\Rest\Company;
use Zend\Db\Sql\Select;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Paginator\Adapter\DbSelect;
use ZF\ApiProblem\ApiProblem;
use ZF\Rest\AbstractResourceListener;
class CompanyMapper {
protected $adapter;
public function __construct(AdapterInterface $adapter)
{
$this->adapter = $adapter;
}
public function fetchAll()
{
$select = new Select('companies');
$paginatorAdapter = new DbSelect($select, $this->adapter);
$collection = new CompanyCollection($paginatorAdapter);
return $collection;
}
public function fetchOne($adId)
{
$sql = 'SELECT * FROM companies WHERE user_id = ?';
$resultset = $this->adapter->query($sql, array($adId));
$data = $resultset->toArray();
if (!$data) {
return false;
}
$entity = new CompanyEntity();
$entity->id_company = $data[0]['id_company'];
$entity->name_company = $data[0]['name_company'];
$entity->user_id = $data[0]['user_id'];
$entity->phone_company = $data[0]['phone_company'];
return $entity;
}
public function update($id, $action)
{
// $sql = 'SELECT * FROM ads WHERE phone_ad = ?';
// $resultset = $this->adapter->query($sql, array($id));
// $data = $resultset->toArray();
// if (!$data) {
// return false;
// }
// if($action){
// $new_clicks = $data[0]['n_clicks']+1;
// $sql = 'UPDATE ads SET n_clicks = "' . $new_clicks . '" WHERE phone_ad = ?';
// $resultset = $this->adapter->query($sql, array($id));
// }else{
// $new_clicks = $data[0]['n_clicks_background']+1;
// $sql = 'UPDATE ads SET n_clicks_background = "' . $new_clicks . '" WHERE phone_ad = ?';
// $resultset = $this->adapter->query($sql, array($id));
// }
$entity = new CompanyEntity();
// $entity->id_ad = $data[0]['id_ad'];
// $entity->name_ad = $data[0]['name_ad'];
// $entity->image_ad = $data[0]['image_ad'];
// $entity->background_ad = $data[0]['background_ad'];
// $entity->phone_ad = $data[0]['phone_ad'];
return $entity;
}
}
<file_sep>/api/module/AdServer/src/AdServer/Module.php
<?php
namespace AdServer;
use ZF\Apigility\Provider\ApigilityProviderInterface;
class Module implements ApigilityProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/../../config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__,
),
),
);
}
public function getServiceConfig()
{
return array(
'factories' => array(
'AdServer\V1\Rest\Ad\AdMapper' => function ($sm) {
$adapter = $sm->get('Zend\Db\Adapter\Adapter');
return new \AdServer\V1\Rest\Ad\AdMapper($adapter);
},
'AdServer\V1\Rest\Ad\AdResource' => function ($sm) {
$mapper = $sm->get('AdServer\V1\Rest\Ad\AdMapper');
return new \AdServer\V1\Rest\Ad\AdResource($mapper);
},
'AdServer\V1\Rest\Company\CompanyMapper' => function ($sm) {
$adapter = $sm->get('Zend\Db\Adapter\Adapter');
return new \AdServer\V1\Rest\Company\CompanyMapper($adapter);
},
'AdServer\V1\Rest\Company\CompanyResource' => function ($sm) {
$mapper = $sm->get('AdServer\V1\Rest\Company\CompanyMapper');
return new \AdServer\V1\Rest\Company\CompanyResource($mapper);
},
'AdServer\V1\Rest\Addclickbanner\AddclickbannerMapper' => function ($sm) {
$adapter = $sm->get('Zend\Db\Adapter\Adapter');
return new \AdServer\V1\Rest\Addclickbanner\AddclickbannerMapper($adapter);
},
'AdServer\V1\Rest\Addclickbanner\AddclickbannerResource' => function ($sm) {
$mapper = $sm->get('AdServer\V1\Rest\Addclickbanner\AddclickbannerMapper');
return new \AdServer\V1\Rest\Addclickbanner\AddclickbannerResource($mapper);
},
'AdServer\V1\Rest\Addclickbanner\AddclickbannerMapper' => function ($sm) {
$adapter = $sm->get('Zend\Db\Adapter\Adapter');
return new \AdServer\V1\Rest\Addclickbanner\AddclickbannerMapper($adapter);
},
'AdServer\V1\Rest\Addclickbanner\AddclickbannerResource' => function ($sm) {
$mapper = $sm->get('AdServer\V1\Rest\Addclickbanner\AddclickbannerMapper');
return new \AdServer\V1\Rest\Addclickbanner\AddclickbannerResource($mapper);
},
'AdServer\V1\Rest\Addclickbackground\AddclickbackgroundMapper' => function ($sm) {
$adapter = $sm->get('Zend\Db\Adapter\Adapter');
return new \AdServer\V1\Rest\Addclickbackground\AddclickbackgroundMapper($adapter);
},
'AdServer\V1\Rest\Addclickbackground\AddclickbackgroundResource' => function ($sm) {
$mapper = $sm->get('AdServer\V1\Rest\Addclickbackground\AddclickbackgroundMapper');
return new \AdServer\V1\Rest\Addclickbackground\AddclickbackgroundResource($mapper);
},
'AdServer\V1\Rest\Addcredit\AddcreditMapper' => function ($sm) {
$adapter = new \Zend\Db\Adapter\Adapter(array(
'driver' => 'Pdo_Mysql',
'database' => 'boizu',
'username' => 'boizu',
'password' => '<PASSWORD>'
));
return new \AdServer\V1\Rest\Addcredit\AddcreditMapper($adapter);
},
'AdServer\V1\Rest\Addcredit\AddcreditResource' => function ($sm) {
$mapper = $sm->get('AdServer\V1\Rest\Addcredit\AddcreditMapper');
return new \AdServer\V1\Rest\Addcredit\AddcreditResource($mapper);
},
'AdServer\V1\Rest\Substractcredit\SubstractcreditMapper' => function ($sm) {
$adapter = new \Zend\Db\Adapter\Adapter(array(
'driver' => 'Pdo_Mysql',
'database' => 'boizu',
'username' => 'boizu',
'password' => '<PASSWORD>'
));
return new \AdServer\V1\Rest\Substractcredit\SubstractcreditMapper($adapter);
},
'AdServer\V1\Rest\Substractcredit\SubstractcreditResource' => function ($sm) {
$mapper = $sm->get('AdServer\V1\Rest\Substractcredit\SubstractcreditMapper');
return new \AdServer\V1\Rest\Substractcredit\SubstractcreditResource($mapper);
},
),
);
}
}
<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Addcredit/AddcreditMapper.php
<?php
namespace AdServer\V1\Rest\Addcredit;
use Zend\Db\Sql\Select;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Paginator\Adapter\DbSelect;
class AddcreditMapper {
protected $adapter;
public function __construct(AdapterInterface $adapter)
{
$this->adapter = $adapter;
}
public function fetchAll()
{
$select = new Select('user_credits');
$paginatorAdapter = new DbSelect($select, $this->adapter);
$collection = new AddcreditCollection($paginatorAdapter);
return $collection;
}
public function fetchOne($adId)
{
// Get user_id
$sql = 'SELECT * FROM user WHERE hash = ?';
$resultset = $this->adapter->query($sql, array($adId));
$data = $resultset->toArray();
if (!$data) {
return false;
}
// Get current credits
$sql = 'SELECT * FROM user_credits WHERE user_id = ?';
$resultset = $this->adapter->query($sql, array($data[0]['id']));
$data_credits = $resultset->toArray();
if (!$data_credits) {
return false;
}
// Add 1 to the credits
$new_credits = $data_credits[0]['credits'] + 1;
// Update user_credits
$sql = 'UPDATE user_credits SET credits = "' . $new_credits . '" WHERE user_id = ?';
$resultset = $this->adapter->query($sql, array($data[0]['id']));
// Create entity and return it
$entity = new AddcreditEntity();
$entity->addcredit_id = $data_credits[0]['user_id'];
$entity->credits = $new_credits;
return $entity;
}
}
<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Substractcredit/SubstractcreditCollection.php
<?php
namespace AdServer\V1\Rest\Substractcredit;
use Zend\Paginator\Paginator;
class SubstractcreditCollection extends Paginator
{
}
<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Addclickbanner/AddclickbannerEntity.php
<?php
namespace AdServer\V1\Rest\Addclickbanner;
class AddclickbannerEntity
{
public $addclickbanner_id;
public $name_ad;
public $image_ad;
public $background_ad;
public $phone_ad;
public $n_clicks;
public $n_impressions;
public $n_clicks_background;
}
<file_sep>/api/module/Admin/config/module.config.php
<?php
/**
* @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
* @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com)
*/
return array(
'session' => array(
'name' => 'api-session',
),
'doctrine' => array(
'driver' => array(
// overriding zfc-user-doctrine-orm's config
'entities' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'paths' => __DIR__ . '/../src/Admin/Entity',
),
'orm_default' => array(
'drivers' => array(
'Admin\Entity' => 'entities',
),
),
),
),
'zfcuser' => array(
// telling ZfcUser to use our own class
'user_entity_class' => 'Admin\Entity\User',
// telling ZfcUserDoctrineORM to skip the entities it defines
'enable_default_entities' => false,
),
'bjyauthorize' => array(
// Using the authentication identity provider, which basically reads the roles from the auth service's identity
'identity_provider' => 'BjyAuthorize\Provider\Identity\AuthenticationIdentityProvider',
'role_providers' => array(
// using an object repository (entity repository) to load all roles into our ACL
'BjyAuthorize\Provider\Role\ObjectRepositoryProvider' => array(
'object_manager' => 'doctrine.entity_manager.orm_default',
'role_entity_class' => 'Admin\Entity\Role',
),
),
),
'router' => array(
'routes' => array(
'user' => array(
'type' => 'segment',
'options' => array(
'route' => '/user[/][:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Admin\Controller\User',
'action' => 'index',
),
),
),
'advertisement' => array(
'type' => 'segment',
'options' => array(
'route' => '/advertisement[/][:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Admin\Controller\Advertisement',
'action' => 'index',
),
),
),
'home' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/admin',
'defaults' => array(
'controller' => 'Admin\Controller\Index',
'action' => 'index',
),
),
),
'root' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'Admin\Controller\Index',
'action' => 'index',
),
),
),
),
),
'service_manager' => array(
'abstract_factories' => array(
'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
'Zend\Db\Adapter\AdapterAbstractServiceFactory',
'Zend\Log\LoggerAbstractServiceFactory',
),
'aliases' => array(
'translator' => 'MvcTranslator',
),
),
'translator' => array(
'locale' => 'en_US',
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
),
'controllers' => array(
'invokables' => array(
'Admin\Controller\Index' => 'Admin\Controller\IndexController',
'Admin\Controller\User' => 'Admin\Controller\UserController',
'Admin\Controller\Advertisement' => 'Admin\Controller\AdvertisementController',
),
),
'view_manager' => array(
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => array(
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'admin/index/index' => __DIR__ . '/../view/application/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
),
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
);
<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Addcredit/AddcreditEntity.php
<?php
namespace AdServer\V1\Rest\Addcredit;
class AddcreditEntity
{
public $addcredit_id;
public $credits;
}
<file_sep>/api/module/Admin/src/Admin/Form/AddAdvertismentForm.php
<?php
namespace Admin\Form;
use Zend\Form\Element;
use Zend\Form\Form;
class AddAdvertismentForm extends Form
{
public function __construct($name = null, $options = array())
{
parent::__construct($name, $options);
$this->addElements();
}
public function addElements()
{
$name = new Element\Text('name');
$name
->setLabel('Name')
->setAttributes(array(
'class' => 'name',
'size' => '30',
'required' => 'required',
));
$this->add($name);
// File Input
$banner = new Element\File('image-file');
$banner->setLabel('Banner image')
->setAttributes(array(
'id' => 'image-file',
'required' => 'required',
));
$this->add($banner);
// File Input
$background = new Element\File('background-file');
$background->setLabel('Background image')
->setAttributes(array(
'id' => 'background-file',
'required' => 'required',
));
$this->add($background);
$phone = new Element\Text('phone');
$phone
->setLabel('Phone')
->setAttributes(array(
'class' => 'phone',
'size' => '9',
'required' => 'required',
));
$this->add($phone);
}
}<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Ad/AdEntity.php
<?php
namespace AdServer\V1\Rest\Ad;
use Doctrine\ORM\Mapping as ORM;
use Zend\Form\Annotation;
/**
* @ORM\Entity
* @ORM\Table(name="ads")
* @Annotation\Name("ads")
*/
class AdEntity
{
/**
* @ORM\Column(name="id_ad", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
* @Annotation\Attributes({"type":"hidden"})
*/
public $id_ad;
/**
* @ORM\Column(name="name_ad" , type="string")
* @Annotation\Type("Zend\Form\Element\Text")
* @Annotation\Validator({"name":"StringLength", "options": {"min":"2", "max":"25"}})
*/
public $name_ad;
/**
* @ORM\Column(name="image_ad" , type="string")
* @Annotation\Type("Zend\Form\Element\Text")
* @Annotation\Validator({"name":"StringLength", "options": {"min":"2", "max":"100"}})
*/
public $image_ad;
/**
* @ORM\Column(name="background_ad" , type="string")
* @Annotation\Type("Zend\Form\Element\Text")
* @Annotation\Validator({"name":"StringLength", "options": {"min":"2", "max":"100"}})
*/
public $background_ad;
/**
* @ORM\Column(name="phone_ad" , type="string")
* @Annotation\Type("Zend\Form\Element\Text")
* @Annotation\Validator({"name":"StringLength", "options": {"min":"2", "max":"25"}})
*/
public $phone_ad;
/**
* @ORM\Column(name="n_clicks" , type="integer")
* @Annotation\Type("Zend\Form\Element\Text")
*/
public $n_clicks;
/**
* @ORM\Column(name="n_impressions" , type="integer")
* @Annotation\Type("Zend\Form\Element\Text")
*/
public $n_impressions;
/**
* @ORM\Column(name="n_clicks_background" , type="integer")
* @Annotation\Type("Zend\Form\Element\Text")
*/
public $n_clicks_background;
/**
* @ORM\Column(name="call_clicks" , type="integer")
* @Annotation\Type("Zend\Form\Element\Text")
*/
public $call_clicks;
}
<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Ad/AdCollection.php
<?php
namespace AdServer\V1\Rest\Ad;
use Zend\Paginator\Paginator;
class AdCollection extends Paginator
{
}
<file_sep>/api/module/Admin/src/Admin/Entity/Advertisement.php
<?php
namespace Admin\Entity;
use Doctrine\ORM\Mapping as ORM;
use Zend\Form\Annotation;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @ORM\Entity
* @ORM\Table(name="ads")
* @Annotation\Name("ads")
*/
class Advertisement{
/**
* Initialies the roles variable.
*/
public function __construct()
{
$this->user = new ArrayCollection();
}
/**
* @ORM\Column(name="id_ad", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
* @Annotation\Attributes({"type":"hidden"})
*/
protected $id;
/**
* @ORM\Column(name="name_ad" , type="string")
* @Annotation\Type("Zend\Form\Element\Text")
* @Annotation\Validator({"name":"StringLength", "options": {"min":"2", "max":"25"}})
*/
protected $name;
/**
* @ORM\Column(name="image_ad" , type="string")
* @Annotation\Type("Zend\Form\Element\Text")
* @Annotation\Validator({"name":"StringLength", "options": {"min":"2", "max":"100"}})
*/
protected $image;
/**
* @ORM\Column(type="string", length=256 , nullable=true)
*/
protected $hash;
/**
* @var \Doctrine\Common\Collections\Collection
* @ORM\ManyToMany(targetEntity="Admin\Entity\User")
* @ORM\JoinTable(name="advertisement_linker",
* joinColumns={@ORM\JoinColumn(name="id_ad", referencedColumnName="id_ad")},
* inverseJoinColumns={@ORM\JoinColumn(name="id_user", referencedColumnName="id")}
* )
*/
protected $user;
/**
* @ORM\Column(name="background_ad" , type="string")
* @Annotation\Type("Zend\Form\Element\Text")
* @Annotation\Validator({"name":"StringLength", "options": {"min":"2", "max":"100"}})
*/
protected $background;
/**
* @ORM\Column(name="phone_ad" , type="string")
* @Annotation\Type("Zend\Form\Element\Text")
* @Annotation\Validator({"name":"StringLength", "options": {"min":"2", "max":"25"}})
*/
protected $phone;
/**
* @ORM\Column(name="n_clicks" , type="integer")
* @Annotation\Type("Zend\Form\Element\Text")
*/
protected $n_clicks;
/**
* @ORM\Column(name="n_impressions" , type="integer")
* @Annotation\Type("Zend\Form\Element\Text")
*/
protected $n_impressions;
/**
* @ORM\Column(name="n_clicks_background" , type="integer")
* @Annotation\Type("Zend\Form\Element\Text")
*/
protected $n_clicks_background;
/**
* @ORM\Column(name="call_clicks" , type="integer")
* @Annotation\Type("Zend\Form\Element\Text")
*/
protected $call_clicks;
public function getId(){
return $this->id;
}
public function getHash(){
return $this->hash;
}
public function getName(){
return $this->name;
}
public function getImage(){
return $this->image;
}
public function getBackground(){
return $this->background;
}
public function getPhone(){
return $this->phone;
}
public function getNClicks(){
return $this->n_clicks;
}
public function getImpressions(){
return $this->n_impressions;
}
public function getBackgroundClicks(){
return $this->n_clicks_background;
}
public function getCallClicks(){
return $this->call_clicks;
}
public function setName($name){
$this->name = $name ;
}
public function setHash($hash){
$this->hash = $hash ;
}
public function setImage($image){
$this->image = $image;
}
public function setBackground($background){
$this->background = $background;
}
public function setPhone($phone){
$this->phone = $phone;
}
public function setNClicks($clicks){
$this->n_clicks = $clicks;
}
public function setImpressions($clicks){
$this->n_impressions = $clicks;
}
public function setBackgroundClicks($clicks){
$this->n_clicks_background = $clicks;
}
public function setCallClicks($clicks){
$this->call_clicks = $clicks;
}
/**
* Get role.
*
* @return array
*/
public function getUser()
{
return $this->user->getValues();
}
/**
* Add a role to the user.
*
* @param Role $role
*
* @return void
*/
public function addUser($user)
{
$this->user[] = $user;
}
/**
* Set n_impressions
*
* @param integer $nImpressions
* @return Advertisement
*/
public function setNImpressions($nImpressions)
{
$this->n_impressions = $nImpressions;
return $this;
}
/**
* Get n_impressions
*
* @return integer
*/
public function getNImpressions()
{
return $this->n_impressions;
}
/**
* Set n_clicks_background
*
* @param integer $nClicksBackground
* @return Advertisement
*/
public function setNClicksBackground($nClicksBackground)
{
$this->n_clicks_background = $nClicksBackground;
return $this;
}
/**
* Get n_clicks_background
*
* @return integer
*/
public function getNClicksBackground()
{
return $this->n_clicks_background;
}
/**
* Remove user
*
* @param \Admin\Entity\User $user
*/
public function removeUser(\Admin\Entity\User $user)
{
$this->user->removeElement($user);
}
}
<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Addclickbanner/AddclickbannerMapper.php
<?php
namespace AdServer\V1\Rest\Addclickbanner;
use Zend\Db\Sql\Select;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Paginator\Adapter\DbSelect;
use ZF\ApiProblem\ApiProblem;
use ZF\Rest\AbstractResourceListener;
class AddclickbannerMapper {
protected $adapter;
public function __construct(AdapterInterface $adapter)
{
$this->adapter = $adapter;
}
public function fetchAll()
{
}
public function fetchOne($adId)
{
$sql = 'SELECT * FROM ads WHERE hash = ?';
$resultset = $this->adapter->query($sql, array($adId));
$data = $resultset->toArray();
if (!$data) {
return false;
}
$new_click = $data[0]['n_clicks'] + 1;
$sql = 'UPDATE ads SET n_clicks = "' . $new_click . '" WHERE hash = ?';
$this->adapter->query($sql, array($adId));
$entity = new AddclickbannerEntity();
$entity->addclickbanner_id = $data[0]['id_ad'];
$entity->name_ad = $data[0]['name_ad'];
$entity->image_ad = $data[0]['image_ad'];
$entity->background_ad = $data[0]['background_ad'];
$entity->phone_ad = $data[0]['phone_ad'];
$entity->n_clicks = $new_click;
$entity->n_impressions = $data[0]['n_impressions'];
$entity->n_clicks_background = $data[0]['n_clicks_background'];
return $entity;
}
}
<file_sep>/api/module/AdServer/src/AdServer/V1/Rest/Ad/AdMapper.php
<?php
namespace AdServer\V1\Rest\Ad;
use Zend\Db\Sql\Select;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Paginator\Adapter\DbSelect;
use ZF\ApiProblem\ApiProblem;
use ZF\Rest\AbstractResourceListener;
class AdMapper {
protected $adapter;
protected $_objectManager;
public function __construct(AdapterInterface $adapter)
{
$this->adapter = $adapter;
}
public function fetchAll()
{
$select = new Select('ads');
$paginatorAdapter = new DbSelect($select, $this->adapter);
$collection = new AdCollection($paginatorAdapter);
$result = array();
$cont = 0;
// Get only 4 of the collection => Algorithm to decide what ads are better depending on the user
foreach ($collection as $item) {
# code...
if($cont==0){
// Simulated click on first item
$new_clicks = $item['n_clicks']+1;
$sql = 'UPDATE ads SET n_clicks = "' . $new_clicks . '" WHERE id_ad = ?';
$this->adapter->query($sql, array($item['id_ad']));
}
// Update impressions for all the ads
$new_n_impressions = $item['n_impressions'] + 1;
$sql = 'UPDATE ads SET n_impressions = "' . $new_n_impressions . '" WHERE id_ad = ?';
$this->adapter->query($sql, array($item['id_ad']));
$cont++;
$result[] = $item;
if($cont == 4)
break;
}
return $result;
}
public function fetchOne($adId)
{
$sql = 'SELECT * FROM ads WHERE hash = ?';
$resultset = $this->adapter->query($sql, array($adId));
$data = $resultset->toArray();
if (!$data) {
return false;
}
$entity = new AdEntity();
$entity->id_ad = $data[0]['id_ad'];
$entity->name_ad = $data[0]['name_ad'];
$entity->image_ad = $data[0]['image_ad'];
$entity->background_ad = $data[0]['background_ad'];
$entity->phone_ad = $data[0]['phone_ad'];
$entity->n_clicks = $data[0]['n_clicks'];
$entity->n_impressions = $data[0]['n_impressions'];
$entity->n_clicks_background = $data[0]['n_clicks_background'];
$entity->call_clicks = $data[0]['call_clicks'];
return $entity;
}
}
| 4f95aab36568da7b8a0f55440a52c232d295d55a | [
"PHP"
] | 28 | PHP | mik3lon/api | a66f7963f4b1fdef2a7bc8ac135e64c632b54303 | 5a2e3717d6f81e1680be9d1c9e6946abfa88a763 | |
refs/heads/master | <file_sep>import redis
from bestrecipe.models import Recipe
r = redis.StrictRedis(host='localhost', port=6379, db=0)
jsonList = []
for key in r.keys():
jsonList.append(key)
<file_sep>from django.db import models
from jsonfield import JSONField
class Recipe(models.Model):
title = models.CharField(max_length=300)
summary = JSONField()
cooktime = models.IntegerField()
nutrition = JSONField()
img = models.URLField()
URL = models.URLField()
structIngredients = JSONField()
ingredients = JSONField()
instruction = JSONField()
description = JSONField()
<file_sep>from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', 'bestrecipe.views.index'),
# url(r'^blog/', include('blog.urls')),
(r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATIC_PATH}),
url(r'^recipe$', 'bestrecipe.views.recipe'),
url(r'^results$', 'bestrecipe.views.results'),
)
<file_sep>from django.shortcuts import render_to_response
from django.template import RequestContext, Context
from bestrecipe.models import Recipe
import redis
import re
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def index(request):
return render_to_response('index.html')
def results(request):
r = redis.StrictRedis(host='localhost', port=6379, db=0)
ingredients= request.GET.getlist('ingredients', '')
conj=set()
results=[]
for i in ingredients:
if conj==set():
conj = set(r.lrange(i,0,-1))
else:
conj=conj&set(r.lrange(i,0,-1))
for index in conj:
result = Recipe.objects.get(id=index)
results.append(result)
paginator = Paginator(results, 9)
page = request.GET.get('page')
try:
group = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
group = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
group = paginator.page(paginator.num_pages)
return render_to_response('results.html',{'results':group})
def recipe(request):
index = request.GET.get('index', '')
recipe = Recipe.objects.get(id=index)
cooktime=recipe.cooktime
if cooktime > 59:
recipe.cooktime /= 60
timeUnit='hrs'
elif cooktime > 3599:
recipe.cooktime /= 3600
timeUnit='days'
else:
timeUnit='mins'
pdv={"sodium":2400,"total_fat":65,"saturated_fat":20,"cholesterol":300,"total_carbohydrate":300,"dietary_fiber":25,"sugars":1,"protein":1,"calories":1,"calories_from_fat":1}
recipe.nutrition={item:int(recipe.nutrition[item]) for item in recipe.nutrition}
percent ={item:int(float(recipe.nutrition[item])/float(pdv[item])*100) for item in recipe.nutrition}
#matches = re.search(r'\.(\w+\.com)', recipe.URL)
temp = re.findall("http://w*\.*([^/]*\.\w+)(/|$)",recipe.URL,re.I)
if temp:
domain=temp[0][0]
else:
domain="None"
#domain = matches.group(1);
return render_to_response('recipe.html',{'recipe':recipe,'timeunit':timeUnit,'percent':percent,'domain':domain})
<file_sep>import pickle
import redis
from bestrecipe.models import Recipe
def add2DB(self,fileName):
with open(fileName,"rb") as infile:
cookbook=pickle.load(infile)
for i in cookbook:
dict={}
for key, value in i.items():
dict[key] = value
p = Recipe(title=dict['title'],summary=dict['summary'],cooktime=dict['cooktime'],img=dict['img'],URL=dict['url'],nutrition=dict['nutrient'],structIngredients=dict['structIngs'],ingredients=dict['ingredient'],instruction=dict['instruction'],description=dict['description'])
p.save()
def add2Redis(self):
r = redis.StrictRedis(host='localhost', port=6379, db=0)
for i in Recipe.objects.all():
ingres=i.structIngredients
for ingName,trival in ingres.items():
r.lpush(ingName,i.id)
def clearRedis(self):
r = redis.StrictRedis(host='localhost', port=6379, db=0)
for key in r.keys():
r.delete(key)
def showRedis(self):
r = redis.StrictRedis(host='localhost', port=6379, db=0)
for key in r.keys():
r.lrange(key,0,-1)
| 90fdb3999e5599e4f5c3a35c503aff2566b18c56 | [
"Python"
] | 5 | Python | Oliver022/BestRecipe | 27d38329533cb855921e5c6554f20a5192f250a3 | 090b947ae4acc98e4bd5954b4775e44236dc7736 | |
refs/heads/master | <repo_name>ManjyotThandi/LogProcessing<file_sep>/OpenHouse/src/main/java/com/BackEndTest/LogResource/LogResource.java
package com.BackEndTest.LogResource;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController
public class LogResource {
@Autowired
private LogService logService;
@GetMapping(path = { "/log", "/log/{userId}", "/log/{userId}/{date}", "/log/{userId}/{date}/{logType}" })
public String retrieveLog(@PathVariable(required = false) String userId,
@PathVariable(required = false) String date, @PathVariable(required = false) String logType)
throws IOException, ParseException {
if (date.equals("null") && logType.equals("null") && userId != null) {
return logService.returnUser(userId);
} else if (userId.equals("null") && logType.equals("null") && date != null) {
return logService.returnDate(date);
} else if (userId.equals("null") && date.equals("null") && logType != null) {
return logService.returnLogType(logType);
} else if (userId != null && date != null && logType.equals("null")) {
return logService.returnUserDateSearch(userId, date);
} else if (userId != null && logType != null && date.equals("null")) {
return logService.returnUserLogSearch(userId, logType);
} else if (userId.equals("null") && logType != null && date != null) {
return logService.returnDateLogSearch(date, logType);
} else if (userId != null && logType != null && date != null) {
return logService.returnAll(userId, date, logType);
} else {
return "please enter valid search criteria";
}
}
@PostMapping("/newlog")
public void addLog(@RequestBody Log log) {
logService.newFile(log);
}
}
<file_sep>/README.md
# LogProcessing
Enter in a URL of localhost:8080/{userId}/{date}/{logType}.
If you are searching for some of these parameters but not all, insert the text "null" in place of the missed parameters.
It will parse through the log files an return those which have matching criteria.
Project not yet deployed.
<file_sep>/OpenHouse/src/main/java/com/BackEndTest/LogResource/Log.java
package com.BackEndTest.LogResource;
import java.io.File;
public class Log {
private File logFile;
private String name;
public Log() {
}
public Log(File logFile, String name) {
this.logFile = logFile;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getLogFile() {
return logFile;
}
public void setLogFile(File logFile) {
this.logFile = logFile;
}
}
| 585ec3b707d9d730894dd74b59ec6266c40613a6 | [
"Markdown",
"Java"
] | 3 | Java | ManjyotThandi/LogProcessing | 5e5996cda1154c496e98bc41c2df2cdafd5e2c8a | c4d996ed24f513de1871ee72cd96de89d751bd97 | |
refs/heads/master | <repo_name>yanghb666/master<file_sep>/nihao.sh
#!/usr/bin/env bash
hello word
qweqwe
<file_sep>/README.md
# master
lianxi git
| bc1cad39d6ac63f0076f6a91b017dfd70d9ffebd | [
"Markdown",
"Shell"
] | 2 | Shell | yanghb666/master | f7026bd865e4dd78096256f5b72b1b9ad7447c84 | 7f44c11bee0d420d0fe2dacb9f12352ff67ae978 | |
refs/heads/main | <repo_name>sgmtec1/python-lp2-aula1-exercicio1<file_sep>/exercicio1.py
"""
Escreva um programa que solicita ao usuário três valores
e exiba na tela a média dos valores digitados.
"""
a = float(input('Digite o primeiro numero: '))
b = float(input('Digite o segundo numero: '))
c = float(input('Digite o terceiro numero: '))
media = (a + b + c) / 3
print('Média dos numeros: ', media)
# Outras maneiras para formatar a saída:
# print('Média dos numeros: {}'.format(media))
# print(f'Média dos numeros: {media}')
<file_sep>/README.md
# python-lp2-aula1-exercicio1
Lista de 3 usuários e média
| 6e3a3daf38fe285591028bd63e9b5df522d8fd8b | [
"Markdown",
"Python"
] | 2 | Python | sgmtec1/python-lp2-aula1-exercicio1 | 325da23f180f45a20e1c29aefe0da4af55525c4f | 150b1168a229ff63dfd11147700618defb3ce74c | |
refs/heads/main | <repo_name>thiagonmiziara/NLW-Heat-Web<file_sep>/src/services/profileService.ts
import { api } from "./api";
type ProfileProps = {
id: string;
name: string;
login: string;
avatar_url: string;
};
export const profileService = async () => {
const response = (await api.get<ProfileProps>("/profile")).data;
return response;
};
<file_sep>/src/models/types.ts
export type MessageProps = {
id: string;
text: string;
user: {
name: string;
avatar_url: string;
};
};
export type UserProps = {
id: string;
name: string;
login: string;
avatar_url: string;
};
export type AuthContextProps = {
user: UserProps | null;
signInUrl: string;
signOut: () => void;
};
<file_sep>/src/services/messages.ts
import { api } from "./api";
type MessageProps = {
id: string;
text: string;
user: {
name: string;
avatar_url: string;
};
};
export const getMessagesList = async () => {
const response = (await api.get<MessageProps[]>("/messages/last3")).data;
return response;
};
export const postMessage = async (message: string) => {
const response = (await api.post("messages", { message })).data;
return response;
};
<file_sep>/src/services/signInService.ts
import { api } from "./api";
type SignInServiceProps = {
token: string;
user: {
id: string;
avatar_url: string;
name: string;
login: string;
};
};
export const signInService = async (githubCode: string) => {
const response = await api.post<SignInServiceProps>("/authenticate", {
code: githubCode,
});
return response.data;
};
| edda12b6babda24289e1a2b80953fd2f6f4f35d7 | [
"TypeScript"
] | 4 | TypeScript | thiagonmiziara/NLW-Heat-Web | 385bc9244c5e0dac2cc5df2c3b0567265863afd9 | e0955ba0ef4341237d267bdb5ea4d204caecfc8e | |
refs/heads/master | <repo_name>ramana058/bestroot<file_sep>/online.php
this file is created in online editor
| 017aa0e4e9f913633588059d16a9a70560b49443 | [
"PHP"
] | 1 | PHP | ramana058/bestroot | 2c8942c5e632d8ce3e908159a395409c9b37d76a | 7f80946179b2b7679fddac1d2538df9a28eaf281 | |
refs/heads/master | <repo_name>ianelletson/MCS270-Final-Project<file_sep>/FinalProject/columnVisualizer.js
// The MIT License (MIT)
// Copyright (c) <2014> <<NAME>, <NAME>, <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.
/*
* Global Variables
*/
var drawingWindow;
var drawingWindowWidth = 500;
var drawingWindowHeight = 500;
var isQuickZoomedIn = false;
var isColumnClicked = false;
var points;
/**
* Initializer to create the drawingWindow
*/
function drawingWindowInit() {
// Strings that hold the details of the canvas and window
drawingWindowDetails = "resizable=yes, width=%s1, height=%s2";
canvasDetails =
"<html>" +
"<head>" +
"<title>Drawing Window</title>" +
"</head>" +
"<body>" +
"<canvas id=\"theCanvas\" height=\"%s1\" width=\"%s2\"></canvas>" +
"<table width=\"100%\">" +
"<tr>" +
"<td width=\"50%\" id=\"Selected Column\">Selected Column: <br> No Column Selected</td>" +
"<td width=\"50%\" id=\"Curser Column\">Curser Column: <br> %%%</td>" +
"</tr>" +
"<tr>" +
"<td id= \"Buttons\">" +
"<button id=\"inButton\" type=\"button\">+</button>" +
"<button id=\"outButton\" type=\"button\">-</button>" +
"<button id=\"downloadButton\" type=\"button\">Download</button>" +
"</td>" +
"</tr>" +
"</table>" +
"</body>" +
"</html>";
// Replaces the value holder with the correct value
drawingWindowDetails = drawingWindowDetails.replace("%s1", "" + drawingWindowWidth).replace("%s2", "" + drawingWindowHeight);
canvasDetails = canvasDetails.replace("%s1", "" + (drawingWindowWidth * .95)).replace("%s2", "" + (drawingWindowHeight * .95));
// Creates the window with the appropriate details
drawingWindow = window.open("", "_blank", drawingWindowDetails);
drawingWindow.document.write(canvasDetails);
}
/*
* Mouse Response Helper Methods
*/
/**
* A function that gets the current hovering position of the mouse
* @param drawing canvas for columns, the event about the location of the mouse
* @return the xy coordinates of the mouse position
*/
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
/**
* Calculates the distance between the mouse position and a column point.
* @param the position of the mouse, the xy point of one column
* @return boolean value if the mouse is near a column
*/
function distanceCheck(mousePos, colPos) {
var canvas = drawingWindow.document.getElementById("theCanvas");
// Scaled points of the column based on the size of the canvas
scaledX = (colPos[0] * canvas.width);
scaledY = (canvas.height - colPos[1] * canvas.height) - 25;
// distance between the mouse and the column
var distance = Math.sqrt(Math.pow(mousePos.x - scaledX, 2) + Math.pow(mousePos.y - scaledY, 2));
return distance;
}
/**
* Test the mouse position against the rest of the columns.
* @param the position of the mouse on the canvas
* @return the name of the column the mouse is over
**/
function testMouseToCol(mousePos, nameArray) {
var colPos = [];
var colosestColIndex = -1;
var retName = "No Column";
for (var i = 0; i < points.length; i++) {
colPos = [points[i][0], points[i][1]];
if (distanceCheck(mousePos, colPos) <= 5) { // finds the first column near the mouse position
if (colosestColIndex === -1 || colosestColIndex > distanceCheck(mousePos, colPos)) {
colosestColIndex = i;
retName = nameArray[i];
}
}
}
return retName;
}
/*
* Display helper methods
*/
/**
* Rewrites the UI-display to have the name of the nearest column to the mouse position
* @param the name of the coulmn nearest to the mouse position
*/
function reWrite(message, id) {
var canvas = drawingWindow.document.getElementById("theCanvas");
var context = canvas.getContext("2d");
drawingWindow.document.getElementById(id).innerHTML = id + ": <br>" + message;
}
/**
* Resizes the canvas when the size of the drawingWindow changes
*/
function resizeCanvas() {
var canvas = drawingWindow.document.getElementById("theCanvas");
var maxLength = Math.max(drawingWindow.innerWidth, drawingWindow.innerHeight);
canvas.width = maxLength * .95;
canvas.height = maxLength * .95;
var context = canvas.getContext("2d");
isQuickZoomedIn = false;
clickFunction();
}
/**
* A double click method to zoom in on a certain position
*/
function quickZoom() {
var canvas = drawingWindow.document.getElementById("theCanvas");
if (!isQuickZoomedIn) {
zoomIn();
isQuickZoomedIn = true;
// Auto scrolls the drawingWindow to center about the zoom location
drawingWindow.scrollBy(canvas.width / 4, canvas.height / 4);
} else {
zoomOut();
drawingWindow.scrollTo((canvas.width / 2 - (drawingWindow.innerWidth / 2)), (canvas.height / 2 - (drawingWindow.innerHeight / 2)));
isQuickZoomedIn = false;
}
}
/**
* Zooms in on a scale of 2
*/
function zoomIn() {
var canvas = drawingWindow.document.getElementById("theCanvas");
canvas.width = canvas.width * 2;
canvas.height = canvas.height * 2;
clickFunction();
}
/**
* Zooms out on a scale of .5
*/
function zoomOut() {
var canvas = drawingWindow.document.getElementById("theCanvas");
canvas.width = canvas.width / 2;
canvas.height = canvas.height / 2;
clickFunction();
}
/*
* Drawing Methods
*/
/**
* Helper function to draw the Comparison Triangle
* @param The drawing canvas, the "pen" for drawing, and space for drawing
*/
function drawComparisonTriangle(canvas, context, drawingGap) {
triangleHeight = Math.sqrt(canvas.height * canvas.height - (canvas.width / 2) * (canvas.width / 2));
// Triangle Section
context.beginPath();
context.moveTo(0, canvas.height - drawingGap);
context.lineTo(canvas.width, canvas.height - drawingGap);
context.lineTo(canvas.width / 2, (canvas.height - triangleHeight) - drawingGap);
context.lineTo(0, canvas.height - drawingGap);
context.closePath();
context.strokeStyle = "#000000";
context.stroke();
// Labels
context.font = "bold 32px Arial";
context.fillText("S", (canvas.width / 8), canvas.height / 2);
context.fillText("C", canvas.width - (canvas.width / 8), canvas.height / 2);
context.textAlign = "center";
context.fillText("B", canvas.width / 2, canvas.height);
}
/**
* Plots each column as a point in the triangle
* @param points of the columns being plotted, point that will be
* highlighted, the drawing canvas, the "pen" for drawing, and size
* of the points being plotted
*/
function plotColumns(columns, columnOfIntrest, canvas, context, radius) {
//For loop for each column
var colInt;
for (var i = 0; i < columns.length; i++) {
// Checks if the column is the column of interest
if (columnOfIntrest[0] == columns[i][0] &&
columnOfIntrest[1] == columns[i][1]) {
colInt = [columns[i][0], columns[i][1]];
} else {
context.strokeStyle = "#3D352A";
}
// Drawing the point
context.beginPath();
context.arc(columns[i][0] * canvas.width, (canvas.height - columns[i][1] * canvas.height) - radius * radius, radius, 0, 2 * Math.PI, false);
context.closePath();
context.stroke();
}
// Drawing the point
context.strokeStyle = "#FF0000";
context.beginPath();
context.arc(colInt[0] * canvas.width, (canvas.height - colInt[1] * canvas.height) - radius * radius, radius, 0, 2 * Math.PI, false);
context.closePath();
context.stroke();
}
/*
* Column Math Methods
*/
/**
* Normalizes columns
* @params : Array to normalize, Array of normalizers
* returns : Array of normalized values
*/
var normalizeCols = function (xArray, hArray) {
var tempArray = [];
for (var i = 0; i < xArray.length; i++) {
var xNorm = xArray[i] / hArray[i];
tempArray.push(xNorm);
}
return tempArray;
}
/**
* Finds range of an array
* @params : Array to find range, bool (false for min, true for max)
* returns : A max or min determined by opt
* yes I know this is janky and ugly. Could be better with enums
*/
var rangeFinder = function (xArray, opt) {
var retVal = 0;
for (var i = 0; i < xArray.length; i++) {
if (!opt) { // min calc
if (xArray[i] < retVal) {
retVal = xArray[i];
}
} else { // max calc
if (xArray[i] > retVal) {
retVal = xArray[i];
}
}
}
return retVal;
}
/**
* Weights a variable by its range
* @params : min and maxes of that var
* returns : a weight for the variable
*/
var weight = function (min, max) {
var weight = 1 / (max - min);
return weight;
}
/**
* Normalizes X to N (weight)
* @params : weight of var and weight of normalizer
* returns : normalized weight of var X
*/
var normWeight = function (xWeight, nWeight) {
var normalized = (xWeight / nWeight) * 100;
return normalized;
}
/**
* Scales the given var x
* @params : normalized array of x, min of x, normalized weight of x
* returns : an array of scaled x
*/
var scaleCols = function (xArray, xMin, xNormWeight) {
var tempArray = [];
for (var i = 0; i < xArray.length; i++) {
var scale = (xArray[i] - xMin) * xNormWeight;
tempArray.push(scale);
}
return tempArray;
}
/**
* Normalizes scaled vars
* @params : array of scaled values and two other vars to scale by
* returns : an array of normalized, scaled vars
*/
var scaleNormalizer = function (xArray, nArray1, nArray2) {
var tempArray = [];
for (var i = 0; i < xArray.length; i++) {
var scaled = xArray[i] / (xArray[i] + nArray1[i] + nArray2[
i]);
tempArray.push(scaled);
}
return tempArray;
}
/**
* Transforms scaled, normalized points to Y coordinates
* @params : array of scaled normalized points
* returns : array of scaled Y coordinates
*/
var transformY = function (xArray) {
var tempArray = [];
for (var i = 0; i < xArray.length; i++) {
var y = xArray[i] * Math.sin(Math.PI / 3);
tempArray.push(y);
}
return tempArray;
}
/**
* Transforms scaled, normalized points to X coordinates
* @params : array of scaled, normalized points, array of Y points
* returns : array of scaled X coordinates
*/
var transformX = function (xArray, yArray) {
var tempArray = [];
for (var i = 0; i < xArray.length; i++) {
var x = xArray[i] + (yArray[i] / (Math.tan(Math.PI / 3)));
tempArray.push(x);
}
return tempArray;
}
/**
* Scales points
* @params array of x, y points each in array
* returns array of [x,y]
*/
var makePoints = function (xArray, yArray) {
var tempArray = [];
for (var i = 0; i < xArray.length; i++) {
var x = xArray[i];
var y = yArray[i];
tempArray[i] = [x, y];
}
return tempArray;
}
function helpFunction() {
helpWindowDetails = "resizable=yes, width=%s1, height=%s2";
// Replaces the value holder with the correct value
helpWindowDetails = helpWindowDetails.replace("%s1", "" + drawingWindowHeight).replace("%s2", "" + drawingWindowWidth);
// Creates the window with the appropriate details
helpWindow = window.open("", "_blank", helpWindowDetails);
helpWindow.document.write("- Each column is represented as a hollow circle on the graph. <br>- Hover over a circle to view the column it represents. Click on a column to select it. <br>- Zoom in by clicking the '+' button <br>- Zoom out by clicking the '-' button. <br>- Quick zoom in and out by double clicking anywhere on the graph.");
}
/**
* Action Listener to draw the triangle and plot the points
*/
function clickFunction() {
// Checks to see if the drawingWindow needs to be initialized
// or if it needs to re-opened
if (!(drawingWindow) || drawingWindow.closed) {
drawingWindowInit();
}
if (!drawingWindow.closed) {
window.blur();
drawingWindow.focus();
}
/*
* This anonymous function gets the data from a csv
* we must call all functions from within here
* this is because getting is asynchronous
*/
var xy = [];
var dataset;
// This below will make an array based off of the headers we
// want from the csv file.
d3.csv("Http://hplccolumns.org/database.csv", function (data) {
dataset = data.map(function (d) {
return [+d["id"], d["name"], +d["H"], +d["S"], +d[
"B"], +d["C28"]];
});
/*
* @param : the index in dataset from which to draw data
* return : an array of one kind of data
*/
var makeArray = function (k) {
tempArray = [];
for (var i = 0; i < dataset.length; i++) {
if (k === 1) {
tempArray.push(dataset[i][k]);
} else {
tempArray.push(parseFloat(dataset[i][k]));
}
}
return tempArray;
}
var hArray = makeArray(2);
var sArray = makeArray(3);
var bArray = makeArray(4);
var cArray = makeArray(5);
var nameArray = makeArray(1);
var canvas = drawingWindow.document.getElementById(
"theCanvas");
var context = canvas.getContext("2d");
var radius = 5;
/**
* Does all the work required other than making initial arrays
* @params : data for each variable from the csv
* returns : 2D array of x and y values
*/
var getData = function (hArray, sArray, bArray, cArray) {
var sNorm = normalizeCols(sArray, hArray);
var bNorm = normalizeCols(bArray, hArray);
var cNorm = normalizeCols(cArray, hArray);
var min = false;
var max = true;
var sHMin = rangeFinder(sNorm, min);
var sHMax = rangeFinder(sNorm, max);
var bHMin = rangeFinder(bNorm, min);
var bHMax = rangeFinder(bNorm, max);
var cHMin = rangeFinder(cNorm, min);
var cHMax = rangeFinder(cNorm, max);
var sWeight = weight(sHMin, sHMax);
var bWeight = weight(bHMin, bHMax);
var cWeight = weight(cHMin, cHMax);
var sNormWeight = normWeight(sWeight, sWeight);
var bNormWeight = normWeight(bWeight, sWeight);
var cNormWeight = normWeight(cWeight, sWeight);
var sScaled = scaleCols(sNorm, sHMin, sNormWeight);
var bScaled = scaleCols(bNorm, bHMin, bNormWeight);
var cScaled = scaleCols(cNorm, cHMin, cNormWeight);
var sScaledNorm = scaleNormalizer(sScaled, bScaled, cScaled);
var bScaledNorm = scaleNormalizer(bScaled, sScaled, cScaled);
var cScaledNorm = scaleNormalizer(cScaled, sScaled, bScaled);
var yPoints = transformY(cScaledNorm);
var xPoints = transformX(bScaledNorm, yPoints);
var retPoints = makePoints(xPoints, yPoints);
return retPoints;
}
xy = getData(hArray, sArray, bArray, cArray);
points = xy;
// Clears canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// Draws comparison triangle
drawComparisonTriangle(canvas, context, radius * radius);
columnPointsToBePlotted = xy;
// Column of interest WILL GET SOME HOW
// TODO
var chosenColumn = columnPointsToBePlotted[0];
// Plots the columns
plotColumns(xy, chosenColumn, canvas, context, radius);
var canvas = drawingWindow.document.getElementById('theCanvas');
// Action Listeners
drawingWindow.addEventListener('resize', resizeCanvas, false);
drawingWindow.addEventListener('click', function (evt) {
var mousePos = getMousePos(canvas, evt);
reWrite(testMouseToCol(mousePos, nameArray), "Selected Column");
}, false);
drawingWindow.addEventListener('dblclick', quickZoom, false);
drawingWindow.document.getElementById('inButton').onclick = zoomIn;
drawingWindow.document.getElementById('outButton').onclick = zoomOut;
drawingWindow.document.getElementById('downloadButton').onclick = function () {
pictureWindowDetails = "resizable=yes, width=%s1, height=%s2";
// Replaces the value holder with the correct value
pictureWindowDetails = pictureWindowDetails.replace("%s1", "" + drawingWindow.innerWidth).replace("%s2", "" + drawingWindow.innerHeight);
// Creates the window with the appropriate details
pictureDrawingWindow = drawingWindow.open(canvas.toDataURL(), "_blank", pictureWindowDetails);
}
// adds listener for Mouse Move
canvas.addEventListener('mousemove', function (evt) {
// gets mouse pos and creates the message the will be sent to the window.
var mousePos = getMousePos(canvas, evt);
reWrite(testMouseToCol(mousePos, nameArray), "Curser Column");
}, false);
});
}<file_sep>/FinalProject/plotPoints.js
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js">
</script>
/**
* Normalizes columns
* @params : Array to normalize, Array of normalizers
* returns : Array of normalized values
*/
var normalizeCols = function (xArray, hArray) {
var tempArray = [];
for (var i = 0; i < xArray.length; i++) {
var xNorm = xArray[i] / hArray[i];
tempArray.push(xNorm);
}
return tempArray;
}
/**
* Finds range of an array
* @params : Array to find range, bool (false for min, true for max)
* returns : A max or min determined by opt
* yes I know this is janky and ugly. Could be better with enums
*/
var rangeFinder = function (xArray, opt) {
var retVal = 0;
for (var i = 0; i < xArray.length; i++) {
if (!opt) { // min calc
if (xArray[i] < retVal) {
retVal = xArray[i];
}
}
else { // max calc
if (xArray[i] > retVal) {
retVal = xArray[i];
}
}
}
return retVal;
}
/**
* Weights a variable by its range
* @params : min and maxes of that var
* returns : a weight for the variable
*/
var weight = function (min, max) {
var weight = 1 / (max - min);
return weight;
}
/**
* Normalizes X to N (weight)
* @params : weight of var and weight of normalizer
* returns : normalized weight of var X
*/
var normWeight = function (xWeight, nWeight) {
var normalized = (xWeight / nWeight) * 100;
return normalized;
}
/**
* Scales the given var x
* @params : normalized array of x, min of x, normalized weight of x
* returns : an array of scaled x
*/
var scaleCols = function (xArray, xMin, xNormWeight) {
var tempArray = [];
for (var i = 0; i < xArray.length; i++) {
var scale = (xArray[i] - xMin) * xNormWeight;
tempArray.push(scale);
}
return tempArray;
}
/**
* Normalizes scaled vars
* @params : array of scaled values and two other vars to scale by
* returns : an array of normalized, scaled vars
*/
var scaleNormalizer = function (xArray, nArray1, nArray2) {
var tempArray = [];
for (var i = 0; i < xArray.length; i++) {
var scaled = xArray[i] / (xArray[i] + nArray1[i] + nArray2[i]);
tempArray.push(scaled);
}
return tempArray;
}
/**
* Transforms scaled, normalized points to Y coordinates
* @params : array of scaled normalized points
* returns : array of scaled Y coordinates
*/
var transformY = function (xArray) {
var tempArray = [];
for (var i = 0; i < xArray.length; i++) {
var y = xArray[i] * Math.sin(Math.PI / 3);
tempArray.push(y);
}
return tempArray;
}
/**
* Transforms scaled, normalized points to X coordinates
* @params : array of scaled, normalized points, array of Y points
* returns : array of scaled X coordinates
*/
var transformX = function (xArray, yArray) {
var tempArray = [];
for (var i = 0; i < xArray.length; i++) {
var x = xArray[i] + (yArray[i] / (Math.tan(Math.PI / 3)));
tempArray.push(x);
}
return tempArray;
}
/**
* Will make an 2d Array for drawing
* @params : x points, y points
* returns : array of [x_i,y_i]
*/
var makePoints = function (xArray, yArray) {
var tempArray = [];
for (var i = 0; i < xArray.length; i++) {
tempArray[i] = [xArray[i], yArray[i]];
}
return tempArray;
}
/*
* This anonymous function gets the data currently stored locally
* TODO: when we move this to production we must adjust location
* To ensure that this runs, start a python web server from the
* directory - python -m SimpleHTTPServer
* we must call all functions from within here
* this is because getting is asynchronous
*/
var dataset;
// This below will make an array based off of the headers we
// want from the csv file.
d3.csv("http://localhost:8000/database.csv", function (data) {
dataset = data.map(function (d) {
return [+d["id"], +d["name"], +d["H"], +d["S"], +d[
"B"], +
d["C28"]
];
});
/*
* @param : the index in dataset from which to draw data
* return : an array of one kind of data
*/
// id = [0]; name = [1]; H = [2]; S = [3]; B = [4]; C = [5]
var makeArray = function (k) {
tempArray = [];
for (var i = 0; i < dataset.length; i++) {
tempArray.push(parseFloat(dataset[i][k]));
}
return tempArray;
}
var hArray = makeArray(2);
var sArray = makeArray(3);
var bArray = makeArray(4);
var cArray = makeArray(5);
/**
* Does all the work required other than making initial arrays
* @params : data for each variable from the csv
* returns : 2D array of x and y values
*/
var getData = function(hArray, sArray, bArray, cArray) {
var sNorm = normalizeCols(sArray, hArray);
var bNorm = normalizeCols(bArray, hArray);
var cNorm = normalizeCols(cArray, hArray);
// false for min ; true for max
var min = false;
var max = true;
var sHMin = rangeFinder(sNorm, min);
var sHMax = rangeFinder(sNorm, max);
var bHMin = rangeFinder(bNorm, min);
var bHMax = rangeFinder(bNorm, max);
var cHMin = rangeFinder(cNorm, min);
var cHMax = rangeFinder(cNorm, max);
var sWeight = weight(sHMin, sHMax);
var bWeight = weight(bHMin, bHMax);
var cWeight = weight(cHMin, cHMax);
var sNormWeight = normWeight(sWeight, sWeight);
var bNormWeight = normWeight(bWeight, sWeight);
var cNormWeight = normWeight(cWeight, sWeight);
var sScaled = scaleCols(sNorm, sHMin, sNormWeight);
var bScaled = scaleCols(bNorm, bHMin, bNormWeight);
var cScaled = scaleCols(cNorm, cHMin, cNormWeight);
var sScaledNorm = scaleNormalizer(sScaled, bScaled, cScaled);
var bScaledNorm = scaleNormalizer(bScaled, sScaled, cScaled);
var cScaledNorm = scaleNormalizer(cScaled, sScaled, bScaled);
var yPoints = transformY(cScaledNorm);
var xPoints = transformX(bScaledNorm, yPoints);
var retPoints = makePoints(xPoints, yPoints);
return retPoints;
}
data = getData(hArray, sArray, bArray, cArray);
// Begin plotting. Must be done in async function
// full of magic numbers that should be eliminated
var margin = {top: 20, right: 15, bottom: 60, left: 60},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d[0];})])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d[1];})])
.range([height, 0]);
var chart = d3.select('body')
.append('svg:svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'chart')
var main = chart.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top
+ ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'main')
// Draw x axis (we don't actually want to do this, we want a triangle)
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom');
main.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'main axis date')
.call(xAxis);
// Draw y (see note above)
var yAxis = d3.svg.axis()
.scale(y)
.orient('left');
main.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'main axis date')
.call(yAxis);
var g = main.append("svg:g");
g.selectAll("scatter-dots")
.data(data)
.enter().append("svg:circle")
.attr("cx", function(d,i) {return x(d[0]);})
.attr("cy", function(d) {return y(d[1]);})
.attr("r", 8);
});
| 6dc6c78d4e02e9c8d43efd8850164b19b2f079c5 | [
"JavaScript"
] | 2 | JavaScript | ianelletson/MCS270-Final-Project | f05d57cabefb290b6def332445e09dcd924d2c4b | de9b9bf943a8583810af1ed377b672f9561efffa | |
refs/heads/master | <file_sep>[package]
name = "plato"
version = "0.1.0"
authors = ["Joshuad2uiuc <<EMAIL>>"]
edition = "2018"
[dependencies]
structopt = "0.2.10"
pathdiff = "0.1.0"
chrono = "0.4"
libc = "0.2"
users = "0.9"
groups = "0.1.1"
pretty-bytes = "0.2"
<file_sep>use std::env;
use std::path::PathBuf;
use std::fs;
use super::opts::Opts;
use std::vec::Vec;
use std::fs::ReadDir;
use std::collections::HashMap;
use std::io::{Error, ErrorKind};
use crate::lib::list_item;
// Gets the current directory of the user
pub fn get_current_directory() -> PathBuf {
let path = env::current_dir();
match path {
Ok(p) => return p,
Err(e) => panic!(e)
}
}
// Reads the contents of the current directory
pub fn get_directory_contents(directory: &PathBuf) -> Result<ReadDir, Error> {
let paths = fs::read_dir(directory);
match paths {
Ok(p) => Ok(p),
Err(e) => Err(e)
}
}
// Prints similar output to what ls does in bash
pub fn print_ls(items: Vec<list_item::ListItem>) {
for item in items {
print!("{}\t", item.name);
}
println!();
}
// Prints the extra file details similar to ls -l and ls -lh
pub fn print_ls_extra(items: Vec<list_item::ListItem>) {
for item in items {
println!("{}\t{}\t{}\t{}",
item.owning_user.to_str().unwrap(),
item.file_size,
item.time_last_modified.format("%b %d %H:%M"),
item.name);
}
}
// Determines what information we are going to want to print out
pub fn print_items(items: Vec<list_item::ListItem>, is_human: bool, is_long: bool) {
if is_long {
print_ls_extra(items);
}
else {
print_ls(items);
}
}
// Uses the command line arguments to figure out what to print in response.
pub fn exec_ls(args: Opts) {
let mut cmdflags = HashMap::new();
let mut is_long = false;
let mut is_hidden = false;
let mut is_human = false;
cmdflags.insert("long", args.long);
is_long = args.long;
cmdflags.insert("human", args.human);
is_human = args.human;
cmdflags.insert("hidden", args.hidden);
match args.object {
Some(x) => print_items(list_item::create_list_items(x, &cmdflags), is_human, is_long),
None => print_items(list_item::create_list_items(get_current_directory(), &cmdflags), is_human, is_long)
}
}
<file_sep>pub mod opts;
pub mod list;
pub mod list_item;
pub mod file;
<file_sep>use std::fs;
use fs::Metadata;
use std::os::unix::fs::MetadataExt;
use chrono::{DateTime, Local};
use libc::{S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, S_IWUSR, S_IXGRP, S_IXOTH, S_IXUSR};
use users;
use std::ffi::OsString;
use pretty_bytes::converter::convert;
use pathdiff::diff_paths;
use std::path::PathBuf;
// Takes in the raw permission decimal value and returns the
// the permissions string using the letter format. Grabs the
// permissions for user, group, and other. The S_IRUSR constants
// are used for doing bitwise and operations to check if those bits
// are set in the file's permissions.
fn parse_permissions(is_dir: bool, mode: u32) -> String {
let user = triplet(mode, S_IRUSR, S_IWUSR, S_IXUSR);
let group = triplet(mode, S_IRGRP, S_IWGRP, S_IXGRP);
let other = triplet(mode, S_IROTH, S_IWOTH, S_IXOTH);
if is_dir {
["d".to_string(), user, group, other].join("")
}
else {
["-".to_string(), user, group, other].join("")
}
}
// Uses bitwise and operator to fetch what permissions are set for this object.
fn triplet(mode: u32, read: u32, write: u32, execute: u32) -> String {
match (mode & u32::from(read), mode & u32::from(write), mode & u32::from(execute)) {
(0, 0, 0) => "---",
(_, 0, 0) => "r--",
(0, _, 0) => "-w-",
(0, 0, _) => "--x",
(_, 0, _) => "r-x",
(_, _, 0) => "rw-",
(0, _, _) => "-wx",
(_, _, _) => "rwx",
}.to_string()
}
// Determines if a file is a hidden file or not.
pub fn is_hidden_file(file: &PathBuf, current_dir: &PathBuf) -> bool{
let relative_path = diff_paths(&file, ¤t_dir).unwrap();
let file = relative_path.to_str().unwrap();
return file.starts_with(".")
}
// Get the permissions using the associate file metadata
pub fn get_permissions(meta: &Metadata) -> String {
return parse_permissions(meta.is_dir(), meta.mode());
}
// Get the name of the owning user of this file
pub fn get_owning_user(meta: &Metadata) -> OsString {
let user = users::get_user_by_uid(meta.uid()).unwrap();
return user.name().to_os_string();
}
// Get the time this file was last modified
pub fn get_time_last_modified(meta: &Metadata) -> DateTime<Local> {
let modified: DateTime<Local> = DateTime::from(meta.modified().unwrap());
modified
}
// Get the file size
pub fn get_file_size(meta: &Metadata) -> u64 {
if meta.is_dir() {
0
}
else {
meta.size()
}
}
// Get the file size but formatted to easily be read
// Uses the rust pretty bytes crate
// https://github.com/banyan/rust-pretty-bytes
pub fn get_human_file_size(meta: &Metadata) -> String {
let num = get_file_size(meta);
return convert(num as f64);
}
<file_sep># Plato - A reduced version of the ls command
## CS 196 Project
For CS196 (<NAME>), we were tasked with creating Plato, a rust-built program that would behave in the same way as LS. This was a way for us to get comfortable writing CLI's with Rust, and to get involved with more of the low level things that Rust has to offer.
## Getting Started
Once you've cloned or forked the repo and downloaded it to your local machine, `cd` into the root directory and run:
```
cargo build
```
This will build the `target/` folder and allow you to use the plato script.
Example usage below.
## Usage
```Bash
davis-MacBook-Pro-6:plato davis$ ./target/debug/plato
Cargo.toml target Cargo.lock README.md src
davis-MacBook-Pro-6:plato davis$ ./target/debug/plato -l
davis 247 Aug 12 23:22 Cargo.toml
davis 0 Sep 16 15:38 target
davis 12349 Aug 12 23:29 Cargo.lock
davis 625 Aug 19 00:27 README.md
davis 0 Sep 17 15:47 src
davis-MacBook-Pro-6:plato davis$ ./target/debug/plato -lh
davis 247 B Aug 12 23:22 Cargo.toml
davis 0 B Sep 16 15:38 target
davis 12.35 kB Aug 12 23:29 Cargo.lock
davis 625 B Aug 19 00:27 README.md
davis 0 B Sep 17 15:47 src
davis-MacBook-Pro-6:plato davis$ ./target/debug/plato -lha
davis 6 B Aug 19 01:52 .hello
davis 247 B Aug 12 23:22 Cargo.toml
davis 0 B Sep 16 15:38 target
davis 12.35 kB Aug 12 23:29 Cargo.lock
davis 625 B Aug 19 00:27 README.md
davis 0 B Sep 16 17:34 .git
davis 0 B Sep 17 15:47 src
davis-MacBook-Pro-6:plato davis$ ./target/debug/plato -a
.hello Cargo.toml target Cargo.lock README.md .git src
davis-MacBook-Pro-6:plato davis$ ./target/debug/plato src/
lib main.rs
davis-MacBook-Pro-6:plato davis$
```
<file_sep>use structopt::StructOpt;
use std::path::PathBuf;
#[derive(StructOpt, Debug)]
#[structopt(name = "basic")]
pub struct Opts {
#[structopt(parse(from_os_str))]
pub object: Option<PathBuf>,
#[structopt(short = "a")]
pub hidden: bool,
#[structopt(short = "l")]
pub long: bool,
#[structopt(short = "h")]
pub human: bool,
}
<file_sep>// Ref : https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-clarity.html
use structopt::StructOpt;
// Import the lib module
mod lib;
// Bring the Opts struct into scope
use lib::opts::Opts;
use lib::list;
// Grabs the command line arguments from the user
// executes the ls command.
fn main() {
let args = Opts::from_args();
list::exec_ls(args);
}
<file_sep>use std::fs;
use std::ffi::OsString;
use chrono::{DateTime, Local};
use super::file;
use std::collections::HashMap;
use std::path::PathBuf;
use std::vec::Vec;
use pathdiff::diff_paths;
use crate::lib::list;
#[derive(Debug)]
pub struct ListItem {
pub owning_user: OsString,
pub file_size: String,
pub time_last_modified: DateTime<Local>,
pub name: String
}
pub fn get_file_data(path: PathBuf, directory: &PathBuf, flags: &HashMap<&str, bool>) -> ListItem {
let meta = fs::metadata(&path).unwrap();
let owning_user = file::get_owning_user(&meta);
let time_last_modified = file::get_time_last_modified(&meta);
let relative_path = diff_paths(&path, &directory);
let name = match relative_path {
Some(f) => f.to_str().unwrap().to_string(),
None => path.to_str().unwrap().to_string()
};
let file_size = if *flags.get("human").unwrap() && *flags.get("long").unwrap() {
file::get_human_file_size(&meta)
}
else if *flags.get("long").unwrap() {
file::get_file_size(&meta).to_string()
}
else {
"".to_string()
};
let list_item = ListItem {
owning_user: owning_user,
file_size: file_size,
time_last_modified: time_last_modified,
name: name
};
return list_item;
}
// Uses the current directory and the associated metadata with a file to
// create list item structs for each file. Depending on the flags, the list item
// content might be different for file size.
pub fn create_list_items(base: PathBuf, flags: &HashMap<&str, bool>) -> Vec<ListItem> {
let mut list_items = Vec::new();
let result = list::get_directory_contents(&base);
match result {
Ok(dir_items) => {
let hidden = flags.get("hidden").unwrap();
for item in dir_items {
let path = item.unwrap().path();
if !hidden {
if file::is_hidden_file(&path, &base) {
continue;
}
}
let list_item = get_file_data(path, &base, flags);
list_items.push(list_item);
}
return list_items;
},
Err(_e) => {
let current_directory = list::get_current_directory();
let list_item = get_file_data(base, ¤t_directory, flags);
list_items.push(list_item);
return list_items;
}
}
}
| 60303f669a5632bda8fbed9b3125efd80649caae | [
"TOML",
"Rust",
"Markdown"
] | 8 | TOML | daviskeene/Plato | bc40b2051d8ce705739cde2c13695a91b4bbce84 | 859312e153b4781efbf889656189198b4e39a141 | |
refs/heads/master | <file_sep>UPDATE wp_options SET option_value = 'http://staging.example.com/' where option_name = 'siteurl';
UPDATE wp_options SET option_value = 'http://staging.example.com/' where option_name = 'home';
UPDATE wp_posts SET post_content = REPLACE(post_content, 'localhost', 'staging.example.com');<file_sep>UPDATE wp_options SET option_value = 'http://localhost/wordpress/' where option_name = 'siteurl';
UPDATE wp_options SET option_value = 'http://localhost/wordpress/' where option_name = 'home';
UPDATE wp_posts SET post_content = REPLACE(post_content, 'staging.example.com', 'localhost'); | 254403fe7864c9c0a4e6949b6d5e8ce21b28522c | [
"SQL"
] | 2 | SQL | josephbolus/wordpress-fabfile | 8757b72e8647624296b632d1c5b2350a642b8766 | d80f77c5f3a09eff6c0d12097dfe2f7cd549703f | |
refs/heads/master | <file_sep>// @flow
import { initializeFilterState } from './utils';
const initialState = {
filters: {}
};
initialState.filters.greenspaces = initializeFilterState({
farmerDesired: ['yes', 'no'],
plotSize: ['initial', 'largePlot', 'microPlot', 'backyard', 'frontyard', 'fullyard']
});
initialState.filters.farmers = initializeFilterState({
experience: ['initial', 'expert', 'intermediate', 'novice'],
skills: [
'initial',
'fruits',
'vegetables',
'herbs',
'farming education',
'home gardening',
'sustainability',
'organic',
'CSA',
'farmers market'
]
});
export default initialState;
<file_sep>// @flow
import React from 'react';
const Landing = () => (
<div>
<section>
<h1>Landing Component</h1>
</section>
</div>
);
export default Landing;
<file_sep>// @flow
import React from 'react';
import { Link } from 'react-router-dom';
const FarmerCard = (props: FarmerBrief) => {
let skillCol1 = [];
let skillCol2 = [];
if (props.skills) {
if (props.skills.length > 1) {
// skill distribution to columns, check if length is even
if (props.skills.length % 2 === 0) {
skillCol1 = skillCol1.concat(props.skills.slice(0, props.skills.length / 2));
// $FlowFixMe
skillCol2 = skillCol2.concat(props.skills.slice(props.skills.length / 2));
} else {
// if odd we want the column with the highest number of items to be skillCol1
// $FlowFixMe
skillCol1 = skillCol1.concat(props.skills.slice(0, Math.floor(props.skills.length / 2) + 1));
// $FlowFixMe
skillCol2 = skillCol2.concat(props.skills.slice(Math.floor(props.skills.length / 2) + 1));
}
} else {
skillCol1 = skillCol1.concat(props.skills);
}
}
let shortBio;
if (!props.skills) {
// If we don't have skills we'll provide the bio instead but we just want an abstract,
// so we take the first 101 chars, cut off the last - to get rid of any cut off words,
shortBio = props.bio
.substr(0, 101)
.split(' ')
.slice(0, -1)
.join(' ');
// And if a period is the last character we want to delete it, because we're going to have an ellipsis
// at the end of our string variable.
if (shortBio.lastIndexOf('.') === shortBio.length - 1) {
shortBio = shortBio.substr(0, shortBio.length - 1);
}
}
const skillList = (
<div>
<div className="flex justify-between ph2">
<ul className="mt3 pl0 list">
{skillCol1.map(skill => (
<li key={skill} className="tl f7 lh-copy ttc helvetica b dark-green">
{skill}
</li>
))}
</ul>
<ul className="mt3 pl0 list">
{skillCol2.map(skill => (
<li key={skill} className="tl f7 lh-copy ttc helvetica b dark-green">
{skill}
</li>
))}
</ul>
</div>
</div>
);
const bio = (
<div className="ph2 pt3">
<p className="mt0 tl lh-copy f6 avenir">{shortBio}...</p>
</div>
);
return (
<div
className="mt3 pb3 ba b--black-05 br3 grow shadow-5 tc"
style={{ width: '23%', marginRight: '2%', marginBottom: '48px' }}
>
<header className="w-100 mb3 relative">
<div className="w-100 absolute top-0 br3 br--top bg-near-white z-0" style={{ height: '90px' }} />
<div
className="dib auto mt4 relative br-100 bg-center cover"
style={{
backgroundImage: `url(/public/images/profile_images/${props.profileImage})`,
height: '100px',
width: '100px'
}}
/>
</header>
<h3 className="mt1 mb2 f3 lh-title ttc avenir ">{props.userName}</h3>
<h5 className="mt2 mb3 f5 lh-title ttc avenir black-70">{`${props.experience} farmer`}</h5>
<Link
className="dib auto ph3 pv2 ba br-pill dark-green f7 avenir b no-underline link dim"
to={`/user/${props.id}/#farming`}
>
View Farmer
</Link>
<div className="w-100 mt3 ph3 bt b--black-10 ">
<h4 className="mb0 mt3 pl2 tl f4 ttc avenir black-70">{props.skills ? 'skills' : 'about'}</h4>
<hr className="mw4 ml2 mt1 mb0 bb bw1 b--black-05 tl" />
{props.skills ? skillList : bio}
</div>
</div>
);
};
export default FarmerCard;
<file_sep>// @flow
import React from 'react';
import FilterCatProps from '../const';
import FilterButtonRow from './FilterButtonRow';
import { optionalComputedPropVal } from '../utils';
const Filters = (props: { filterCat: string, filters: {}, updateFilters: Function }) => {
const passFilterState = (filter: string, filterType: string) =>
props.updateFilters({ filter, filterType, filterState: props.filters });
const filterIsBinary = (filter: string, filterRowProps: FilterProp) => {
if (
optionalComputedPropVal(filterRowProps, ['binaryFilters']) &&
// $FlowFixMe - first check negates possibility of reaching this line if optionalComputedPropVal(filterRowProps, ['binaryFilters']) returns null
optionalComputedPropVal(filterRowProps, ['binaryFilters']).includes(filter)
) {
return true;
}
return undefined;
};
const filterRowProps = FilterCatProps[props.filterCat];
const filterGroup = (filterRow: any, filterTitle: string) => (
<div key={filterTitle} className="mr4 flex justify-start">
<button className="mr3 pl1 pr3 pv1 bg-transparent bt-0 br-0 bb bl-0 bw2 b--green fw6 f5 avenir tl pointer">
{filterTitle}
</button>
{filterRow}
</div>
);
const filterRow = (filter: string) => (
<FilterButtonRow
key={filter}
filter={filter}
filterState={props.filters[filter]}
filterOptions={filterRowProps.options[filter]}
changeFilter={passFilterState}
// $FlowFixMe - flow doesn't like optionalComputedVal because it can return type any
btnTextArr={optionalComputedPropVal(filterRowProps, ['optionsText', filter], true)}
includesBinaryBoth={filterIsBinary(filter, filterRowProps)}
// $FlowFixMe - flow doesn't like optionalComputedVal because it can return type any
binaryBothBtnText={optionalComputedPropVal(filterRowProps, ['binaryFilterProps', filter, 'btnText'], true)}
/>
);
const filters = filterRowProps.filters.map((filter: string, index) =>
filterGroup(filterRow(filter), filterRowProps.titles[index])
);
return (
<div className="pt4 pb0">
<button
className="bt-0 br-0 bb-0 bl-0 bg-transparent pointer flex justify-start items-center"
style={{ paddingLeft: '0' }}
>
<h3 className="mr2 f3 fw6 bw0 avenir near-black">Filters</h3>
<svg className="w1 near-black" data-icon="chevronDown" viewBox="0 0 32 32" style={{ fill: 'currentcolor' }}>
<title>chevronDown icon</title>
<path d="M1 18 L5 14 L16 24 L27 14 L31 18 L16 32 Z" />
</svg>
</button>
<div className="flex items-center">{filters}</div>
</div>
);
};
export default Filters;
<file_sep>// @flow
import React from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import type { MapStateToProps } from 'react-redux';
import preload from '../data.json';
const GlobalHeader = (props: { selectedUser: User }) => (
<div>
<header className="fixed z-999 w-100 flex items-center h3 pa4 ba bw4 bg-green green">
<nav className="w-50 flex items-center h3">
<Link className="mr3 f2 white avenir no-underline b" to="/">
Greenspace
</Link>
<Link className="mr3 pt2 f4 white avenir no-underline b dim" to="/farmers">
Farmers
</Link>
<Link className="pt2 f4 white avenir no-underline b dim" to="/greenspaces">
Spaces
</Link>
</nav>
<nav className="w-50 flex flex-row-reverse items-center h3">
<Link
className="pt2 f4 white avenir ttc no-underline b dim"
to={props.selectedUser ? `/user/${props.selectedUser.id}` : '/'}
>
{props.selectedUser ? props.selectedUser.userName : 'Login'}
</Link>
</nav>
</header>
<div className="spacer w-100" style={{ height: '96px' }} />
</div>
);
const mapStateToProps: MapStateToProps<*, *, *> = state => {
const selectedUser = preload.users.find((user: User) => user.id === state.user.id);
return { selectedUser };
};
export default connect(mapStateToProps)(GlobalHeader);
<file_sep>// @flow
import React from 'react';
import FarmerCard from './FarmerCard';
import { paginationSlice } from './utils';
const FarmerCardList = (props: {
farmerCardList: Array<FarmerBrief>,
currentPageNumber: number | null,
cardsPerPage: number | null
}) => (
<div className="flex flex-wrap justify-start pv4">
{props.currentPageNumber && props.cardsPerPage
? paginationSlice(props.farmerCardList, props.currentPageNumber, props.cardsPerPage).map(
(farmer: FarmerBrief) => <FarmerCard key={farmer.id} {...farmer} />
)
: props.farmerCardList.map((farmer: FarmerBrief) => <FarmerCard key={farmer.id} {...farmer} />)}
</div>
);
export default FarmerCardList;
<file_sep>// @flow
import React from 'react';
import preload from '../data.json';
import GreenspaceCardList from './GreenspaceCardList';
const UserFarmingView = (props: { farmer: FarmerBrief }) => {
const farmingGreenspaces = preload.greenspaces.filter(
(greenspace: Greenspace) =>
typeof props.farmer.properties !== 'undefined' && props.farmer.properties.includes(greenspace.id)
);
const farmingGreenspacesTitle = (
<h3 className="mt5 mb0 f3 avenir near-black">{`Greenspaces ${props.farmer.userName} is Farming`}</h3>
);
const farmingGreenspacesList = (
<div className="ph5">
<GreenspaceCardList greenspaceCardList={farmingGreenspaces} />
</div>
);
let farmingSkillList;
let experienceOutlineColor: string;
if (props.farmer.skills) {
farmingSkillList = (
<div className="avenir">
<h5 className="mb2 f5 i">Farming Skills:</h5>
<ul className="pb3 pl0">
{props.farmer.skills.map((skill: farmingSkills) => (
<li key={skill} className="dib pv2 ph3 bg-green white mr3">
{skill}
</li>
))}
</ul>
</div>
);
}
if (props.farmer.experience === 'novice') {
experienceOutlineColor = 'near-white';
} else if (props.farmer.experience === 'intermediate') {
experienceOutlineColor = 'near-black';
} else {
experienceOutlineColor = 'green';
}
return (
<section>
<div className="ph5">
<h4 className={`mb2 pv2 ph3 dib ba bw2 b--${experienceOutlineColor} avenir f4 ttc`}>{`${
props.farmer.experience
} farmer`}</h4>
{farmingSkillList}
<p className="mw8 lh-copy avenir">{props.farmer.bio}</p>
{farmingGreenspaces.length ? farmingGreenspacesTitle : null}
</div>
{farmingGreenspaces.length ? farmingGreenspacesList : null}
</section>
);
};
export default UserFarmingView;
<file_sep>// @flow
import React from 'react';
import GreenspaceCard from './GreenspaceCard';
import { paginationSlice } from './utils';
const GreenspaceCardList = (props: {
greenspaceCardList: Array<Greenspace>,
currentPageNumber?: number | null,
cardsPerPage?: number | null
}) => (
<section className="flex flex-wrap justify-start pv4">
{/*
if pagination info was passed in props, then list the greenspace cards sliced for current page and cars per pages
else just map cards from all of the greenspaces passed - this way we don't have to always specify pagination for greenspaces
*/}
{props.currentPageNumber && props.cardsPerPage
? paginationSlice(props.greenspaceCardList, props.currentPageNumber, props.cardsPerPage).map(
(greenspace: Greenspace) => <GreenspaceCard {...greenspace} key={greenspace.id} />
)
: props.greenspaceCardList.map((greenspace: Greenspace) => (
<GreenspaceCard {...greenspace} key={greenspace.id} />
))}
</section>
);
GreenspaceCardList.defaultProps = {
currentPageNumber: null,
cardsPerPage: null
};
export default GreenspaceCardList;
<file_sep>// @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import FarmerCardList from './FarmerCardList';
import NoFilteredEntitiesMsg from './utilComponents/NoFilteredEntitiesMsg';
import Filters from './utilComponents/Filters';
import { NextPreviousBtns } from './utilComponents/PageControls';
import { passFilterUpdateToSetter, setFilter, getSelectedFiltersMap, filterStateIsInitial } from './utils';
import { setFarmersFilters } from './actionCreators';
type Props = { farmers: Array<FarmerBrief>, filters: genFilters, filtersSetter: Function };
type State = {
pageNumber: number,
filteredFarmers: Array<FarmerBrief>
};
class Farmers extends Component<Props, State> {
state = {
pageNumber: 1,
filteredFarmers: this.props.farmers
};
componentWillReceiveProps(nextProps) {
// if filters will be changed, then we need to reset the current page to page 1
if (this.props.filters !== nextProps.filters) {
this.updatePage(1);
this.updateFilteredFarmers(nextProps.filters);
}
}
updatePage = (val: number) => this.setState({ pageNumber: parseInt(val, 10) });
updateFilteredFarmers = updatedFilters => this.setState({ filteredFarmers: this.filterFarmers(updatedFilters) });
passesExperienceFilter = (farmerExperience: farmingExperienceLevel, selectedFilters: Array<string>) => {
if (filterStateIsInitial(selectedFilters)) {
return true;
}
if (selectedFilters.includes(farmerExperience)) {
return true;
}
return false;
};
passesSkillsFilter = (farmerSkills: Array<farmingSkills> | typeof undefined, selectedFilters: Array<string>) => {
if (filterStateIsInitial(selectedFilters)) {
return true;
}
// User/FarmerBrief.skills is an optional property, so we need to account for it not being available
if (!farmerSkills) {
return false;
}
// if any of the selectedFilters are in farmerSkills return true - the farmer is filtered in
for (let i = 0; i < selectedFilters.length; i += 1) {
if (farmerSkills.includes(selectedFilters[i])) {
return true;
}
}
return false;
};
filterFarmers = updatedFilters => {
const selectedFiltersMap: { experience: Array<string>, skills: Array<string> } = getSelectedFiltersMap(
updatedFilters
);
const filteredFarmers = this.props.farmers.filter(
farmer =>
this.passesExperienceFilter(farmer.experience, selectedFiltersMap.experience) &&
this.passesSkillsFilter(farmer.skills, selectedFiltersMap.skills)
);
return filteredFarmers;
};
render() {
const cardsPerPage = 8;
return (
<section className="ph5">
<Filters
filterCat="farmers"
filters={this.props.filters}
updateFilters={resolveFiltersParams =>
passFilterUpdateToSetter(resolveFiltersParams, this.props.filtersSetter)
}
/>
<NoFilteredEntitiesMsg entities={this.state.filteredFarmers} entitiesType="farmers" />
<FarmerCardList
farmerCardList={this.state.filteredFarmers}
currentPageNumber={this.state.pageNumber}
cardsPerPage={cardsPerPage}
/>
<NextPreviousBtns
pageNumber={this.state.pageNumber}
dataLength={this.state.filteredFarmers.length}
cardsPerPage={cardsPerPage}
clickHandler={this.updatePage}
/>
</section>
);
}
}
const mapStateToProps = state => ({ filters: state.farmersFilters });
const mapDispatchToProps = (dispatch: Function) => ({
filtersSetter(resolveFiltersParams: resolveFiltersParams) {
setFilter(resolveFiltersParams, setFarmersFilters, dispatch);
}
});
export default connect(mapStateToProps, mapDispatchToProps)(Farmers);
<file_sep>// @flow
import React from 'react';
import { Link } from 'react-router-dom';
const GreenspaceCard = (props: Greenspace) => {
let seekingFarmer;
// let gsBackgroundImg;
if (props.farmerDesired) {
seekingFarmer = (
<Link
to={`/greenspace/${props.id}#become-a-farmer`}
className="dib ph2 pv2 ba bw1 br-pill dim link no-underline light-red"
>
Seeking Farmer
</Link>
);
} else {
seekingFarmer = (
<Link to={`/greenspace/${props.id}#farmers`} className="dib ph2 pv2 ba bw1 br-pill dim link no-underline green">
See The Farmers
</Link>
);
}
// if
return (
<div className="mt3" style={{ width: '23%', marginRight: '2%', marginBottom: '48px' }}>
<section className="h-100 bg-near-white br3 shadow-5">
<div
className="h4 w-100 bg-center cover bg-dark-green br3 br--top"
style={props.mainImage ? { backgroundImage: `url(/public/images/${props.mainImage})` } : null}
/>
<Link
to={`/greenspace/${props.id}`}
className="db w-75 center mt4 mb3 pv2 br-pill bg-green link dim tc f4 avenir b white no-underline"
>
See Greenspace
</Link>
<div className="pt0 pb2 tc">
<h3 className="mv0 ph3 f4 lh-copy ttc avenir">{props.name}</h3>
<h5 className="mt2 mb3 ph3 f5 lh-title normal avenir">{props.address}</h5>
<div className="bt b--black-10">
<div className="flex mt4 mb2 ph4 avenir">
<ul className="w-50 mt0 pl3 tl">
{props.plotSize.map(tag => (
<li key={tag} className="mv1 ttc f6 dark-green">
{tag}
</li>
))}
</ul>
<div className="w-50 f7 tc">{seekingFarmer}</div>
</div>
</div>
</div>
</section>
</div>
);
};
export default GreenspaceCard;
<file_sep>// @flow
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import type { Match, RouterHistory } from 'react-router-dom';
import { Provider } from 'react-redux';
import store from './store';
import preload from '../data.json';
import Landing from './Landing';
import GlobalHeader from './GlobalHeader';
import Greenspaces from './Greenspaces';
import GreenspaceDetail from './GreenspaceDetail';
import UserDetail from './UserDetail';
import Farmers from './Farmers';
const FourOhFour = () => <h1>404 - Uh Oh Nothing at this address - 404</h1>;
const App = () => (
<Provider store={store}>
<div className="app">
<GlobalHeader />
<Switch>
<Route exact path="/" component={Landing} />
<Route path="/greenspaces" component={props => <Greenspaces greenspaces={preload.greenspaces} {...props} />} />
<Route
path="/greenspace/:id"
component={(props: { match: Match, history: RouterHistory }) => {
const selectedGreenspace = preload.greenspaces.find(
(greenspace: Greenspace) => greenspace.id === props.match.params.id
);
return <GreenspaceDetail greenspace={selectedGreenspace} history={props.history} {...props} />;
}}
/>
<Route
path="/user/:id"
component={(props: { match: Match }) => {
const selectedUser = preload.users.find((user: User) => user.id === props.match.params.id);
return <UserDetail user={selectedUser} {...props} />;
}}
/>
<Route
path="/farmers"
component={props => {
const farmers = preload.users.filter((user: User) => user.farmer).map((farmer: User) =>
Object.assign(
{},
{
userName: farmer.userName,
id: farmer.id,
bio: farmer.bio,
profileImage: farmer.profileImage,
community: farmer.community,
experience: farmer.farmingExperienceLevel,
skills: farmer.farmingSkills
}
)
);
return <Farmers farmers={farmers} {...props} />;
}}
/>
<Route component={FourOhFour} />
</Switch>
</div>
</Provider>
);
export default App;
<file_sep>// @flow
import { updateFilter, composeFilters, resolveFiltersState } from '../utils';
const farmerDesiredFilter = {
initial: {
yes: true,
no: true
},
yes: {
yes: true,
no: false
},
no: {
yes: false,
no: true
}
};
// tests binary filter - user selecting btn with 'any' value
test('updateFilter with binaryFilters - test for value = any', () => {
// initial state
expect(updateFilter('any', farmerDesiredFilter.initial, true)).toEqual(farmerDesiredFilter.initial);
expect(updateFilter('any', farmerDesiredFilter.yes, true)).toEqual(farmerDesiredFilter.initial);
expect(updateFilter('any', farmerDesiredFilter.no, true)).toEqual(farmerDesiredFilter.initial);
});
// tests binary filter - user selecting btn with 'yes' value
test('updateFilter with binaryFilters - test for value = yes', () => {
// initial state
expect(updateFilter('yes', farmerDesiredFilter.initial, true)).toEqual(farmerDesiredFilter.yes);
expect(updateFilter('yes', farmerDesiredFilter.yes, true)).toEqual(farmerDesiredFilter.yes);
expect(updateFilter('yes', farmerDesiredFilter.no, true)).toEqual(farmerDesiredFilter.yes);
});
// tests binary filter - user selecting btn with 'yes' value
test('updateFilter with binaryFilters - test for value = no', () => {
// initial state
expect(updateFilter('no', farmerDesiredFilter.initial, true)).toEqual(farmerDesiredFilter.no);
expect(updateFilter('no', farmerDesiredFilter.yes, true)).toEqual(farmerDesiredFilter.no);
expect(updateFilter('no', farmerDesiredFilter.no, true)).toEqual(farmerDesiredFilter.no);
});
// test general/non-binary filter
const exampGeneralFilters = {
initial: {
initial: true,
filter1: true,
filter2: true,
filter3: true
},
fromInitialSel1: {
initial: false,
filter1: true,
filter2: false,
filter3: false
},
from1Sel2: {
initial: false,
filter1: true,
filter2: true,
filter3: false
},
from2And1Sel2: {
initial: false,
filter1: true,
filter2: false,
filter3: false
}
};
test('updateFilter with non-binary: filter1 selected from initial state', () => {
expect(updateFilter('filter1', exampGeneralFilters.initial)).toEqual(exampGeneralFilters.fromInitialSel1);
});
test('updateFilter with non-binary: filter2 selected from filter1 already selected', () => {
expect(updateFilter('filter2', exampGeneralFilters.fromInitialSel1)).toEqual(exampGeneralFilters.from1Sel2);
});
test('updateFilter with non-binary: filter2 selected from filter1 and filter2 already selected', () => {
expect(updateFilter('filter2', exampGeneralFilters.from1Sel2)).toEqual(exampGeneralFilters.from2And1Sel2);
});
test('updateFilter with non-binary: any selected from filter1 and filter2 already selected', () => {
expect(updateFilter('any', exampGeneralFilters.from1Sel2)).toEqual(exampGeneralFilters.initial);
});
// testing composeFilters
const preComposeFilters = {
nonBinary: {
initial: false,
filter1: true,
filter2: false,
filter3: false
},
binary: {
yes: false,
no: true
}
};
const postComposeFilters = {
nonBinary: {
initial: false,
filter1: true,
filter2: false,
filter3: true
},
binary: {
yes: true,
no: false
}
};
test('composeFilters with one binary filter, one non-binary', () => {
expect(
composeFilters(
['nonBinary', 'binary'],
[updateFilter('filter3', exampGeneralFilters.fromInitialSel1), updateFilter('yes', farmerDesiredFilter.no, true)],
preComposeFilters
)
).toEqual(postComposeFilters);
});
// testing resolveFiltersState
const preResolveFilters = {
nonBinary: {
initial: false,
filter1: true,
filter2: false,
filter3: false
},
binary: {
yes: true,
no: false
}
};
const postResolveFilters1 = {
nonBinary: {
initial: false,
filter1: true,
filter2: false,
filter3: true
},
binary: {
yes: true,
no: false
}
};
const postResolveFilters2 = {
nonBinary: {
initial: false,
filter1: true,
filter2: false,
filter3: true
},
binary: {
yes: false,
no: true
}
};
test('test resovleFiltersState() with option change to 1 non-binary filter, followed by 1 binary filter in 2 filter state', () => {
expect(resolveFiltersState('filter3', preResolveFilters)).toEqual(postResolveFilters1);
expect(resolveFiltersState('no', postResolveFilters1)).toEqual(postResolveFilters2);
});
<file_sep>// @flow
import React from 'react';
export const PageBtns = (props: { dataLength: number, cardsPerPage: number, clickHandler: Function }) => {
// $FlowFixMe
const passValueToHandler = (event: SyntheticEvent<*>) => props.clickHandler(event.target.innerHTML);
return (
<div>
{Array.from({ length: Math.ceil(props.dataLength / props.cardsPerPage) }, (v, i) => i + 1).map(val => (
<button key={val} onClick={passValueToHandler}>
{val}
</button>
))}
</div>
);
};
export const NextPreviousBtns = (props: {
pageNumber: number,
dataLength: number,
cardsPerPage: number,
clickHandler: Function
}) => {
const totalPages = Math.ceil(props.dataLength / props.cardsPerPage);
// $FlowFixMe
const passValueToHandler = (event: SyntheticEvent<*>) => props.clickHandler(event.target.name);
const previousBtn = (
<button
name={props.pageNumber - 1}
onClick={passValueToHandler}
className="w4 pa3 mr4 tr pointer bg-white ba b--black bg-animate hover-bg-black hover-white v-top"
>
<svg className="w1 mt1 fl" data-icon="chevronLeft" viewBox="0 0 32 32" style={{ fill: 'currentcolor' }}>
<title>chevronLeft icon</title>
<path d="M20 1 L24 5 L14 16 L24 27 L20 31 L6 16 z" />
</svg>
<span className="dib mt1">Previous</span>
</button>
);
const nextBtn = (
<button
name={props.pageNumber + 1}
onClick={passValueToHandler}
className="w4 pa3 mr4 tl pointer bg-white ba b--black bg-animate hover-bg-black hover-white v-top"
>
<span className="dib mt1">Next</span>
<svg className="w1 mt1 fr" data-icon="chevronRight" viewBox="0 0 32 32" style={{ fill: 'currentcolor' }}>
<title>chevronRight icon</title>
<path d="M12 1 L26 16 L12 31 L8 27 L18 16 L8 5 z" />
</svg>
</button>
);
const pageOfPages = (
<h5 className="dib black avenir f5" style={{ lineHeight: '2.4' }}>{`${props.pageNumber} of ${totalPages}`}</h5>
);
return (
<div className="avenir v-btm">
{props.pageNumber > 1 ? previousBtn : null}
{props.pageNumber < totalPages ? nextBtn : null}
{totalPages > 1 ? pageOfPages : null}
</div>
);
};
<file_sep>// @flow
import React from 'react';
const FilterButton = (props: { filterSelected: boolean, val: string, text: string, updateFilterOption: Function }) => {
const selectedFilterArray = ['b--near-black', 'bb', 'bw2', 'bt-0', 'br-0', 'bl-0'];
return (
<button
className={`${
props.filterSelected === true ? selectedFilterArray.join(' ') : 'deSelectedFilter'
} mr2 bw0 bg-transparent avenir f6 pointer`}
value={props.val}
onClick={props.updateFilterOption}
>
{props.text}
</button>
);
};
export default FilterButton;
<file_sep>// @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { setGreenspacesFilters } from './actionCreators';
import GreenspaceCardList from './GreenspaceCardList';
import Filters from './utilComponents/Filters';
import NoFilteredEntitiesMsg from './utilComponents/NoFilteredEntitiesMsg';
import { NextPreviousBtns } from './utilComponents/PageControls';
import { passFilterUpdateToSetter, setFilter, getSelectedFiltersMap } from './utils';
type Props = { greenspaces: Array<Greenspace>, filters: genFilters, filtersSetter: Function };
type State = { pageNumber: number, filteredGreenspaces: Array<Greenspace> };
class Greenspaces extends Component<Props, State> {
state = {
pageNumber: 1,
filteredGreenspaces: this.props.greenspaces
};
componentWillReceiveProps(nextProps) {
// if filters will be changed, then we need to reset the current page to page 1
if (this.props.filters !== nextProps.filters) {
this.updatePage(1);
this.updateFilteredGreenspaces(nextProps.filters);
}
}
updatePage = (val: number) => this.setState({ pageNumber: parseInt(val, 10) });
updateFilteredGreenspaces = updatedFilters => {
this.setState({ filteredGreenspaces: this.filterGreenspaces(updatedFilters) });
};
// try refactor using class polymorphism
passesFarmerDesiredFilter = (farmerDesired: boolean, selectedFilters: Array<string>) => {
if (selectedFilters.includes('yes')) {
// If no is also a selected filter than filters.farmerDesired is effectively 'either' and we don't filter any greenspaces
if (selectedFilters.includes('no')) {
return true;
}
// greenspace.farmerDesired(true) === selectedFilters only element('yes')
if (farmerDesired) {
return true;
}
// greenspace.farmerDesired(false) !== selectedFilters only element('yes')
return false;
}
// greenspace.farmerDesired(false) === selectedFilters only element('no')
if (!farmerDesired) {
return true;
}
return false;
};
passesPlotSizeFilter = (plotSize: Array<plotSize>, selectedFilters: Array<string>) => {
// if selectedFilters includes initial, then we return any filter - state is initial and nothing is being filtered out
if (selectedFilters.includes('initial')) {
return true;
}
const selectedFiltersIncludesPlotSize = plotSize.some(plotSizeTag => selectedFilters.includes(plotSizeTag));
if (selectedFiltersIncludesPlotSize) {
return true;
}
return false;
};
filterGreenspaces = updatedFilters => {
const selectedFiltersMap: { plotSize: Array<string>, farmerDesired: Array<string> } = getSelectedFiltersMap(
updatedFilters
);
const filteredGreenspaces = this.props.greenspaces.filter(
(greenspace: Greenspace) =>
this.passesFarmerDesiredFilter(greenspace.farmerDesired, selectedFiltersMap.farmerDesired) &&
this.passesPlotSizeFilter(greenspace.plotSize, selectedFiltersMap.plotSize)
);
return filteredGreenspaces;
};
render() {
const cardsPerPage = 8;
return (
<section className="ph5">
<Filters
filterCat="greenspaces"
filters={this.props.filters}
updateFilters={resolveFiltersParams =>
passFilterUpdateToSetter(resolveFiltersParams, this.props.filtersSetter)
}
/>
<NoFilteredEntitiesMsg entities={this.state.filteredGreenspaces} entitiesType="greenspaces" />
<GreenspaceCardList
greenspaceCardList={this.state.filteredGreenspaces}
currentPageNumber={this.state.pageNumber}
cardsPerPage={cardsPerPage}
/>
<div className="pl5">
<NextPreviousBtns
pageNumber={this.state.pageNumber}
dataLength={this.state.filteredGreenspaces.length}
cardsPerPage={cardsPerPage}
clickHandler={this.updatePage}
/>
</div>
</section>
);
}
}
const mapStateToProps = state => ({ filters: state.greenspacesFilters });
const mapDispatchToProps = (dispatch: Function) => ({
filtersSetter(resolveFiltersParams: resolveFiltersParams) {
setFilter(resolveFiltersParams, setGreenspacesFilters, dispatch);
}
});
export default connect(mapStateToProps, mapDispatchToProps)(Greenspaces);
<file_sep>// @flow
import React from 'react';
import preload from '../data.json';
import GreenspaceCardList from './GreenspaceCardList';
const UserGreenspaceView = (props: { greenspaceOwner: GreenspaceOwnerBrief }) => {
const ownedGreenspaces = preload.greenspaces.filter(
(greenspace: Greenspace) =>
typeof props.greenspaceOwner.ownedPropertyIDs !== 'undefined' &&
props.greenspaceOwner.ownedPropertyIDs.includes(greenspace.id)
);
const lendingGreenspacesTitle = (
<h3 className="mt5 mb0 f3 avenir near-black">{`Greenspaces ${props.greenspaceOwner.userName} is Lending`}</h3>
);
const lendingGreenspacesList = (
<div className="ph5">
<GreenspaceCardList greenspaceCardList={ownedGreenspaces} />
</div>
);
let landownerParticipationInfo;
let participationColor = 'green';
if (props.greenspaceOwner.desiredLandOwnerParticipation) {
if (props.greenspaceOwner.desiredLandOwnerParticipation === 'hands-off') {
participationColor = 'near-white';
} else if (props.greenspaceOwner.desiredLandOwnerParticipation === 'helping hand') {
participationColor = 'near-black';
}
}
if (props.greenspaceOwner.desiredLandOwnerParticipation) {
landownerParticipationInfo = (
<div>
<h5 className="mb3 f5 avenir i">Farming Participation:</h5>
<h5 className={`mt0 dib pv2 ph3 ba b--${participationColor} bw2 f5 avenir`}>
{props.greenspaceOwner.desiredLandOwnerParticipation}
</h5>
</div>
);
}
return (
<section>
<div className="ph5">
{landownerParticipationInfo}
<p className="mw8 lh-copy avenir">{props.greenspaceOwner.bio}</p>
{ownedGreenspaces.length ? lendingGreenspacesTitle : null}
</div>
{ownedGreenspaces.length ? lendingGreenspacesList : null}
</section>
);
};
export default UserGreenspaceView;
<file_sep>// @flow
// easings, more here as needed
export const cubicOut = (time: number) => {
let t = time;
t -= 1;
return t * t * t + 1;
};
// easings grouping
export const easings = { cubicOut };
// to dom element scrolling
export const scrollToElem = (
targetElem: HTMLElement | null = null,
duration: number = 300,
easingFunction: Function = (time: number) => time,
verticalCompensation: number = 0,
event: SyntheticEvent<*> | null = null
) => {
if (targetElem !== null) {
if (event !== null) {
event.preventDefault();
}
const startPosition = window.pageYOffset;
const startTime = new Date().getTime();
// $FlowFixMe
const documentHeight = document.body.scrollHeight;
const windowHeight = window.innerHeight;
const destinationOffset = targetElem.offsetTop + verticalCompensation;
let destinationScroll;
if (documentHeight - destinationOffset < windowHeight) {
destinationScroll = documentHeight - windowHeight;
} else {
destinationScroll = destinationOffset;
}
// if we don't have access to requestAnimationFrame then we just scroll
if ('requestAnimationFrame' in window === false) {
return window.scrollTo(0, targetElem.offsetTop);
}
const scroll = () => {
const now = new Date().getTime();
const time = Math.min(1, (now - startTime) / duration);
window.scroll(0, Math.ceil(easingFunction(time) * (destinationScroll - startPosition) + startPosition));
if (window.pageYOffset === destinationScroll) {
return;
}
requestAnimationFrame(scroll);
};
return scroll();
}
return null;
};
// takes a per-page slice of paginated content
export const paginationSlice = (items: Array<Object>, pageNumber: number, cardsPerPage: number) =>
items.slice(pageNumber * cardsPerPage - (cardsPerPage - 1) - 1, pageNumber * cardsPerPage);
/**
* Takes state of a single filter object and return array of the names of the selected filter options
* -- options are props of the filter object; if their value is true they are selected
* @param { {[filter: string]: {[filterOption: string]: boolean}} } filter - the filter object whose options are evaluated for selection
*/
const getSelectedFilterOptions = (filter: { [filterOption: string]: boolean }): Array<string> => {
const selectedFilterOptionKeys = Object.keys(filter).filter(filterOptionKey => filter[filterOptionKey]);
return selectedFilterOptionKeys;
};
/**
* takes a general 3d filters object and simplifies it to a 2d object
* - each prop key is the filter it represents. Each prop value is an array of the selected filter options for that filter
* @param {genFilters or { [filterType: string]: {[filter: string]: boolean} }} filters to map to the simpler filtersMapObj
*/
export const getSelectedFiltersMap = (filters: genFilters): { [filter: string]: Array<string> } => {
const filtersMapObj = {};
Object.keys(filters).forEach((filter: string) => {
const selectedFilterOptions = getSelectedFilterOptions(filters[filter]);
filtersMapObj[filter] = selectedFilterOptions;
});
return filtersMapObj;
};
export const filterStateIsInitial = (selectedFilterOptions: Array<string>) => {
if (selectedFilterOptions.includes('initial')) {
return true;
}
return false;
};
/**
* => initialState obj for filters
* @param {Object with any num props of any name of type Array<string> } filters - filter objects, keys are the filter name,
* vals are array of strings that translate to filter options
* Each prop of filters becomes a prop of returned initialState obj
* Each val in filters.<prop> becomes a prop of initialState.<prop>,
* all initialState.<prop> child props are given val true
*/
export const initializeFilterState = (filters: {}): {} => {
const initialState = {};
Object.keys(filters).forEach(key => {
const filterOptions = {};
filters[key].forEach(innerKey => {
filterOptions[innerKey] = true;
});
initialState[key] = filterOptions;
});
return initialState;
};
const isFilterBinary = (filterState: {}) => Object.keys(filterState).length === 2;
/*
function filterFromOption (option: string, filterState: {}): string | null {
let filter: string | null = null;
Object.keys(filterState).forEach(key => {
if (Object.keys(filterState[key]).includes(option)) {
filter = key;
}
});
return filter;
};
*/
const turnFiltersOff = (filters: { [filter: string]: string } | { yes: boolean, no: boolean }) => {
const updatedFilters = {};
Object.keys(filters).forEach(key => {
// only add/set prop if prop is not already true
if (!filters[key]) {
updatedFilters[key] = true;
}
});
return Object.assign({}, filters, updatedFilters);
};
// for updating a filter with two options, one of which, if true, sets the other to false:
const updateBinaryFilter = (
filter: 'yes' | 'no' | 'binaryBoth',
filtersState: { yes: boolean, no: boolean }
): { yes: boolean, no: boolean } => {
if (filter === 'binaryBoth') {
return turnFiltersOff(filtersState);
}
if (filter === 'yes') {
return Object.assign({}, filtersState, { yes: true, no: false });
}
// return for 'no' selected is default
return Object.assign({}, filtersState, { yes: false, no: true });
};
export const updateFilter = (
filter: 'initial' | string,
filtersState: { [filter: string]: boolean },
isBinaryFilter: boolean = false
): {} => {
if (isBinaryFilter) {
// $FlowFixMe
return updateBinaryFilter(filter, filtersState);
}
// if filter is any, we set all filters to true
if (filter === 'initial') {
// setting all filters to true
return turnFiltersOff(filtersState);
}
// if filtersState.initial is true, then a filter btn filters result to only that filter
if (filtersState.initial) {
const changedFiltersState = {};
Object.keys(filtersState).forEach(key => {
if (key !== filter) {
changedFiltersState[key] = false;
}
});
return Object.assign({}, filtersState, changedFiltersState);
}
// if the current filter - which isn't initial - is the only true/on filter, if we toggle it off then let's return to initial state
// - this prevents filtering down to no results:
if (Object.values(filtersState).filter(filterVal => filterVal).length === 1 && filtersState[filter]) {
return turnFiltersOff(filtersState);
}
// if filtersState.initial is not true, filter btns toggle that filter
// creating single prop object - props with key of filter and opposite value of filter in current filter state
const newFilter = {};
// $FlowFixMe
newFilter[filter] = !filtersState[filter];
return Object.assign({}, filtersState, newFilter);
};
export const resolveFiltersState = (
option: string,
targetFilterName: string,
filterState: { [filterType: string]: { [filter: string]: boolean } }
): {} => {
const targetFilter: { [filter: string]: boolean } = filterState[targetFilterName];
const updatedFiltersState = {};
updatedFiltersState[targetFilterName] = updateFilter(option, targetFilter, isFilterBinary(targetFilter));
return Object.assign({}, filterState, updatedFiltersState);
};
/**
* return nested object representing state of all filters for view/component
* @param {Array<string>} filterNames - the name of each filter type to be composed, will be prop key in returned obj
* @param {Array<{any}>} filterStates - the states of each filter in return filters obj, should be in same ordered as filterNames
* @param {Object<any>} currentFilters - the current state of view/component filters - optional
*/
export const composeFilters = (
filterNames: Array<string>,
filterStates: Array<{ [filterType: string]: { [filter: string]: string } }>,
currentFilters: {} = {}
): {} => {
const newFilters = {};
filterNames.forEach((name: string, index: number) => {
newFilters[name] = filterStates[index];
});
return Object.assign({}, currentFilters, newFilters);
};
/**
* side-effect only function, passes params needed to setFilter state to the filterSetter supplied
* @param {string} filter - the name of the filter being changed
* @param {*} filterType - nae of the filter-type or filter-parent of the updated filter
* @param {*} filterState - state of the all filters for the component
* @param {*} filtersSetter - setter function which sends the evaluated filter state to the dispatcher
*/
export const passFilterUpdateToSetter = (resolveFiltersParams: resolveFiltersParams, filtersSetter: Function) => {
filtersSetter(resolveFiltersParams);
};
/**
* -- generalized prop-to-store dispatch handler, for use in body of mapDispatchToProps
* side-effect only function, passes result of resolveFilterState() to provided actionCreator on through provided dispatch()
* @param {*} resolveFilterParams - params for resolveFilterState() - a util function
* @param {*} dispatch - dispatch function to pass: should be 'dispatch' param of mapDispatchToProps
* @param {*} actionCreator - actionCreator to pass result of resolveFilterParam: should be an exported member of ./actionCreators.js
*/
export const setFilter = (resolveFiltersParams: resolveFiltersParams, actionCreator: Function, dispatch: Function) => {
dispatch(
actionCreator(
resolveFiltersState(
resolveFiltersParams.filter,
resolveFiltersParams.filterType,
resolveFiltersParams.filterState
)
)
);
};
/**
* return value of optional computed object property
* @param {Object<any>} baseObject - the base object to test props against
* @param {Array<string>} propNames - array of nested props that could exist on base object, if 1 prop provided, will return val of that prop, if 2 props, will return value of second prop within first prop, etc.
* @param {boolean} undefinedIfNoProp - if true - if prop does not exist return undefined - otherwise return null; this is for use when returning directly in JSX component prop assignment
*/
export const optionalComputedPropVal = (
baseObj: any,
propNames: Array<string>,
undefinedIfNoProp: boolean = false
): any | null | typeof undefined => {
const noProp = undefinedIfNoProp ? undefined : null;
// we're always going to test the base object against the 0'th index of propNames, so here's a shorthand
const hasPropShorthand = () => {
if (Object.prototype.hasOwnProperty.call(baseObj, propNames[0])) {
return true;
}
return false;
};
if (propNames.length === 1) {
// if we only have one prop to test - we return value of baseObj[deepestProperty] if test passes; on fail we return noProp val
if (hasPropShorthand()) {
return baseObj[propNames[0]];
}
return noProp;
}
if (hasPropShorthand()) {
// If we have more than one propName and the baseObj has propNames[0], we re-run the function with baseObj[propNames[0]] as the new base object,
// we slice propNames by just the first index to return a property list without the first property we've made the new baseObj with
// and we pass the undefinedIfNoProp val along as is.
return optionalComputedPropVal(baseObj[propNames[0]], propNames.slice(1), undefinedIfNoProp);
}
return noProp;
};
<file_sep>// @flow
export const SET_GREENSPACES_FILTERS = 'SET_GREENSPACES_FILTERS';
export const SET_FARMERS_FILTERS = 'SET_FARMERS_FILTERS';
<file_sep>// @flow
import React from 'react';
const NoFilteredEntitiesMsg = (props: {
entities: UserFilteredEntities,
entitiesType?: 'greenspaces' | 'farmers' | 'default'
}) => {
const messages = {
default: "Sorry, it doesn't look like we have what you're looking for.",
greenspaces: "Sorry, we don't have any greenspaces like that yet.",
farmers: "Sorry, we don't have any farmers like that yet."
};
const msgToRender = <h2>{props.entitiesType ? messages[props.entitiesType] : messages.default}</h2>;
return <section>{!props.entities.length ? msgToRender : null}</section>;
};
NoFilteredEntitiesMsg.defaultProps = {
entitiesType: 'default'
};
export default NoFilteredEntitiesMsg;
<file_sep>// @flow
import React from 'react';
import FilterButton from './FilterButton';
const FilterButtonRow = (props: {
filter: string,
filterState: {},
filterOptions: Array<string>,
changeFilter: Function,
btnTextArr?: Array<string>,
includesBinaryBoth?: boolean,
binaryBothBtnText?: string
}) => {
// pass filterValue and target filter up to parent
const passFilterValue = event => props.changeFilter(event.target.value, props.filter);
const filterStateVals = Object.keys(props.filterState).map((filterKey: string) => props.filterState[filterKey]);
const genFilterSelectedTest = filter => {
// $FlowFixMe
if (filter === 'initial') return props.filterState[filter];
return props.filterState[filter] && !props.filterState[props.filterOptions[0]];
};
const binaryFilterSelectedTest = filter => props.filterState[filter] && filterStateVals.includes(false);
const binaryBothBtn = (
<FilterButton
filterSelected={!filterStateVals.includes(false)}
key="binaryBoth"
val="binaryBoth"
text={props.binaryBothBtnText ? props.binaryBothBtnText : 'Either'}
updateFilterOption={passFilterValue}
/>
);
return (
<nav className="flex justify-start">
{props.includesBinaryBoth ? binaryBothBtn : null}
{props.filterOptions.map((filter: string, index) => (
<FilterButton
filterSelected={props.includesBinaryBoth ? binaryFilterSelectedTest(filter) : genFilterSelectedTest(filter)}
key={filter}
val={filter}
// $FlowFixMe - possibly undefined value sufficiently covered by defaultProps
text={props.btnTextArr.length >= index ? props.btnTextArr[index] : filter}
updateFilterOption={passFilterValue}
/>
))}
</nav>
);
};
FilterButtonRow.defaultProps = { btnTextArr: [], includesBinaryBoth: false, binaryBothBtnText: 'Either' };
export default FilterButtonRow;
<file_sep>// @flow
import React from 'react';
import { configure, render } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Filters from '../utilComponents/Filters';
import initialState from '../initialState';
configure({ adapter: new Adapter() });
const gsFiltersPropsHandOff = (option: string, filter: string, filters: {}) => console.log(option, filter, filters);
const shallowGsFilters = render(
<Filters filterCat="greenspaces" filters={initialState.filters.greenspaces} updateOptions={gsFiltersPropsHandOff} />
);
describe('gsFilters-suite', () => {
it('Should contain 11 buttons', () => {
expect(shallowGsFilters.find('button').length).toBe(11);
});
});
<file_sep>// @flow
import { combineReducers } from 'redux';
import initialState from './initialState';
import { SET_GREENSPACES_FILTERS, SET_FARMERS_FILTERS } from './actions';
const user = (state = { id: '<KEY>' }, action: Action) => {
if (action) {
return state;
}
return state;
};
const greenspacesFilters = (state = initialState.filters.greenspaces, action: Action) => {
if (action.type === SET_GREENSPACES_FILTERS) {
return Object.assign({}, state, action.payload);
}
return state;
};
const farmersFilters = (state = initialState.filters.farmers, action: Action) => {
if (action.type === SET_FARMERS_FILTERS) {
return Object.assign({}, state, action.payload);
}
return state;
};
const rootReducer = combineReducers({ user, greenspacesFilters, farmersFilters });
export default rootReducer;
| 640fa322ec319995af46c6f5f6ce10dab1f513e4 | [
"JavaScript"
] | 22 | JavaScript | egretsRegrets/greenspace-app-react | f3a3f8dfd67654918693ce8ddba161f9efb8970a | f8e24e4cb4ecc98bf98734ee4fba5f6a64527d79 | |
refs/heads/master | <repo_name>diousk/CustomTimePicker<file_sep>/app/src/main/java/com/example/timepicker/NumberPickerFragment.kt
package com.example.timepicker
import android.app.Dialog
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.NumberPicker
import androidx.annotation.ColorInt
import com.example.timepicker.databinding.FragmentNumberPickerBinding
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import timber.log.Timber
import java.util.*
class NumberPickerFragment : BottomSheetDialogFragment() {
lateinit var binding: FragmentNumberPickerBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentNumberPickerBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.serviceTimePicker.setConfirmListener { dayOffset, hour, minute ->
Timber.d("dayOffset $dayOffset, $hour, $minute")
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
dialog.setOnShowListener { setupBottomSheet(it) }
return dialog
}
private fun setupBottomSheet(dialogInterface: DialogInterface) {
val bottomSheetDialog = dialogInterface as BottomSheetDialog
val bottomSheet = bottomSheetDialog.findViewById<View>(
com.google.android.material.R.id.design_bottom_sheet)
?: return
bottomSheet.setBackgroundColor(Color.TRANSPARENT)
}
}
private const val TAG = "WidgetUtil"
internal fun NumberPicker.setDividerColor(@ColorInt color: Int) {
try {
NumberPicker::class.java.getDeclaredField("mSelectionDivider").apply {
isAccessible = true
}.set(this, ColorDrawable(color))
invalidate()
} catch (e: Exception) {
Log.e(TAG, "setDividerColor failed. " + e.message)
}
}
internal fun NumberPicker.setDividerHeight(height: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
selectionDividerHeight = height
return
}
try {
NumberPicker::class.java.getDeclaredField("mSelectionDividerHeight")
.apply { isAccessible = true }.set(this, height)
invalidate()
} catch (e: Exception) {
Log.e(TAG, "setDividerHeight failed. " + e.message)
}
}<file_sep>/app/src/main/java/com/example/timepicker/MainActivity.kt
package com.example.timepicker
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.timepicker.databinding.ActivityMainBinding
import timber.log.Timber
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Timber.plant(Timber.DebugTree())
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.picker.setOnClickListener {
NumberPickerFragment().show(supportFragmentManager, "picker")
}
}
}<file_sep>/app/src/main/java/com/example/timepicker/ServiceTimePicker.kt
package com.example.timepicker
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.example.timepicker.databinding.ViewServiceTimePickerBinding
import java.util.*
class ServiceTimePicker @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private val binding = ViewServiceTimePickerBinding
.inflate(LayoutInflater.from(context), this, true)
fun interface OnConfirmListener {
fun onConfirm(dayOffset: Int, hour: Int, minute: Int)
}
private var confirmListener: OnConfirmListener? = null
fun setConfirmListener(listener: OnConfirmListener) {
confirmListener = listener
}
fun interface OnDismissListener {
fun onDismiss()
}
init {
binding.confirm.setOnClickListener {
val dayOffset = binding.datePicker.value
val hour = binding.hourPicker.value
val minute = binding.minutePicker.value * MINUTE_INTERVAL
confirmListener?.onConfirm(dayOffset, hour, minute)
}
val now = Calendar.getInstance()
val nowHour = now.get(Calendar.HOUR_OF_DAY)
val nowMin = now.get(Calendar.MINUTE)
// minute picker
val incHour = with(binding) {
val stepForward = (nowMin >= MINUTE_INTERVAL)
val minutes = (0..59).step(MINUTE_INTERVAL)
.map { String.format("%02d", it) }.toTypedArray()
minutePicker.displayedValues = minutes
minutePicker.minValue = 0
minutePicker.maxValue = minutes.size - 1
minutePicker.setDividerHeight(1)
minutePicker.value = if (stepForward) 0 else 1
stepForward
}
// hour picker
val incDay = with(binding) {
val hourIncremental = if (incHour) 1 else 0
val targetHour = nowHour + hourIncremental
val hours = (0..23).map { String.format("%02d", it) }.toTypedArray()
hourPicker.displayedValues = hours
hourPicker.minValue = 0
hourPicker.maxValue = hours.size - 1
hourPicker.setDividerHeight(1)
hourPicker.value = targetHour % 24
targetHour >= 24
}
// date picker
with(binding) {
val dates = resources.getStringArray(R.array.readable_date_offset)
datePicker.wrapSelectorWheel = false
datePicker.displayedValues = dates
datePicker.minValue = 0
datePicker.maxValue = dates.size - 1
datePicker.setDividerHeight(DIVIDER_HEIGHT)
datePicker.value = if (incDay) 1 else 0
}
}
companion object {
private const val DIVIDER_HEIGHT = 1
private const val MINUTE_INTERVAL = 30
}
} | 4902634293e22b314bee90f6c54549b905ca8aab | [
"Kotlin"
] | 3 | Kotlin | diousk/CustomTimePicker | bfe87ab25991c4faf1b2b7aa3986560ef7b9e17a | 8486370289d7308ca38f5ec944c8a84f0072099e | |
refs/heads/master | <repo_name>fangweb/bst-lib<file_sep>/README.md
## About
A binary search tree implementation.
<file_sep>/index.js
function Node(v, l, r) {
return {
value: v,
left: l,
right: r,
}
}
function initTree(v) {
return Node(v, Node(), Node());
}
function insert(Tree, NewNode) {
if (Tree.value === undefined) {
Tree.value = NewNode.value;
Tree.left = Node();
Tree.right = Node();
return;
} else if (Tree.value > NewNode.value) {
insert(Tree.left, NewNode);
} else if (Tree.value < NewNode.value) {
insert(Tree.right, NewNode);
} else {
// equal ?
}
return Tree;
}
function deleteNode(Tree, value) {
if (Tree.value === value) {
Tree.value = Tree.left.value;
Tree.left = Tree.left.left;
return;
}
if (Tree.value > value) {
deleteNode(Tree.left, value);
} else {
deleteNode(Tree.right, value);
}
}
function getSubtree(Tree, value) {
if (Tree.value === value) return Tree;
if (Tree.value > value) {
if (Tree.left.value === undefined) return null;
return getSubtree(Tree.left, value);
} else {
if (Tree.right.value === undefined) return null;
return getSubtree(Tree.right, value);
}
}
function prettyPrint(Tree) {
return JSON.stringify(Tree, null, 4);
}
exports.Node = Node;
exports.initTree = initTree;
exports.insert = insert;
exports.deleteNode = deleteNode;
exports.getSubtree = getSubtree;
exports.prettyPrint = prettyPrint;
| a344e3df67e69b7af15c70562c05a3074862c923 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | fangweb/bst-lib | 68ae01180ce72ac829b24c7e79a2eaee0aa755bd | 2468417a268f97e90e78f924630927b7134c4980 | |
refs/heads/master | <file_sep>package test28;
import java.util.ArrayList;
import java.util.HashMap;
//인터페이스는 퍼블릭밖에 못쓰고, 기본값은 디폴트아니고 퍼블릭
//사용할메소드만 구현
public interface UserDAO {
public int insertUserInfo(HashMap<String,String> userInfo);
public int deletetUserInfo(HashMap<String,String> userInfo);
public int updatetUserInfo(HashMap<String,String> userInfo);
public ArrayList<HashMap<String,String>> selectUserInfoList (HashMap<String,String> userInfo);
}
<file_sep>package testtt;
import java.util.HashMap;
public class Map {
public static void main(String[]args) {
HashMap<String,String> hm = new HashMap<String,String>();
hm.put("이름","홍길동");
hm.put("사는곳","서울");
hm.put("성별","남자");
hm.put("나이","25");
System.out.println(hm);
}
}
<file_sep>package conception2;
public class Test {
static void chNum(int a) {
StaticTest.numSt = 20;//다른곳에서 static 값 초기화
}
}
<file_sep>package basic;
public class DataType {
public static void main(String[] args) {
// 정해져있는 data type
byte b = 127;
short s = 12312;
int i = 123123;
long l = 12343534534534l;
float f = 1.23f;
double d = 1.23;
char a = 'a';
boolean b1 = true;
b1 = false;
boolean bl = 1==1;
//비교연산자 -->조건문(if문), 반복문사용
int x = 2;
int z = 4;
System.out.println(x==z);
System.out.println(x!=z);
System.out.println(x>z);
System.out.println(x<z);
System.out.println(x>=z);
System.out.println(x<=z);
// 정해져있지 않는 data type
String str = "이정혜";
}
}
<file_sep>package test29;
import java.util.ArrayList;
public class ListTest {
public static String[] split(String str, String seperator) {
//int size =ArrayList.count(str,seperator);
String[] strs = new String[size];
for(int i = 0; i<str.length();i++) {
int idx = str.indexOf(seperator);
if(idx==-1) {
strs[i] = str;
}else{
String s = str.substring(0,idx);
strs[i] = s;
str = str.substring(idx+1);
}
}
return strs;
}
public static void main(String[] args) {
/* System.out.println( str.substring(0, 1));
System.out.println( str.substring(2, 3));
System.out.println( str.substring(4, 5));
System.out.println( str.substring(6, 7));
System.out.println( str.substring(8, 9));*/
/*String[] strs = str.split("-");
for(int i = 0; i<strs.length;i++) {
System.out.println(strs[i]);
}*/
}
}
<file_sep>package test21;
public class TrainingCart extends Cart {
public TrainingCart(String name, int speed, int damage) {
super(name, speed, damage);
// TODO Auto-generated constructor stub
}
}
<file_sep>package computer;
public class Exec2 {
//object생략 모든 클래스는object!를 extends함
public static void main(String[] args) {
// TODO Auto-generated method stub
Object c = new Pc();
((Pc)c).res="abs";
//obj 상속받으므로 모두 obj라고 불리울수 있음
Object[] arrObj = new Object[4];
arrObj[0]=1;
arrObj[1]=new Boolean(true);
/*Computer c = new Computer();
c.printInfo("inter8", 50, "뀨j");*/
}
}
<file_sep>package conception2;
public class WrapDataType {
public static void main(String[] args) {
// TODO Auto-generated method stub
//정해져있는 데이터 타입은 값만 바라보지 소유 하지 않음
int i = 10;
//wrapper 정해져있는 데이터 타입을 감싸고 그외 기능도 수행함
//String 처럼 값을 소유 가능 함 클래스 기능 +값도 소유 Integer.
Integer integer = new Integer( 10);
Integer i1 = 10;
Integer i2 = 10;
System.out.println(i1==i2);//new 아니면 같음
String s1 = "1";
String s2 = "1";
System.out.println(s1==s2);
//String .equals
String s = integer.toString(); //s=10;은 안되지만
System.out.println(s);//하면 10이나옴 이건 숫자가 아님!
char c = 'q';
Character ch = 'a';
//정해져있지 않은 데이터 타입이라 구분위해 대문자
long l = 10l;
Long lon = 10l;
Boolean bl = true;
Double db = 10.2;
Float fl = 1.2f;
Byte b = 1;
Short sc = 3;
}
}
<file_sep>package test19;
public class Arr {
//방을만들지 않고서는 누구의. 쩜을 사용할수 없다.
public static void main(String[] args) {
int[][] arr = new int[2][];
arr[0] = new int[2];// 0번째 방에 인트배열이 들어감
arr[1] = new int[3];
for(int i = 0; i<arr.length;i++) {
for(int j = 0; j<arr[i].length;j++) {
arr[i][j] = (int)(Math.random()*10)+1;
}
}
System.out.println(arr[0][1]);
System.out.println(arr.length);
System.out.println(arr[0].length);
System.out.println(arr[1].length);
//i번째 층의 방갯수 System.out.println(i+"번째 층의 방 갯수 :"+arr[i].length);
for(int i = 0 ;i<arr.length;i++) {
//int[] tmpArr = arr[i];//int형 배열에 넣는다. 인트형배열을
for(int j = 0; j<arr[i].length;j++) {
arr[i][j] =(int)(Math.random()*10)+1;
}
}
}
}
<file_sep>package test18;
public class Data {
//클래스안에서는 선안만 가능!!!!!!!!!!!!
int a = 3;
public Data() {
System.out.println("data생성자");
}//정행지지 않는 데이터 타입을 생성할 때 만드는 것!
//메소드와 차이:생성자는 리턴타입 아님 메서드인데 데이터 타입
//클래스명만 같을 뿐 메서드이다. 변수나 메서드 호출 사용가능함 /실행과 메모리 오르는 것은 다르므로
//모두 다 알고 있음
//
public static void main(String[]args) {
Data d = new Data();//기본생성자 가 눈에 보이지는 않지만 생김
d.a = 10;
if(d.a ==10) {
d.a = 5;
d = new Data();
}
System.out.println(d.a);
}
}
<file_sep>package test21;
public interface Drive {
public String attack(int damage);
public void start();
public void stop();
}
<file_sep>package test25;
import java.sql.DriverManager;
import java.sql.SQLException;
public class UserDAO {
public static void main(String[] args) {
String url = "jdbc:mariadb://172.16.31.10:3306/oreo";
String user = "root";
String password = "<PASSWORD>";
try {
Class.forName("org.mariadb.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>package test16;
public class Human {
protected String name;
protected int age;
public int num;
public Human() {
}
public Human(String name, int age, int num) {
this.name = name;
this.age = age;
this.num = num;
}
public void printHuman() {
System.out.println("이름:"+name);
System.out.println("나이:"+age);
System.out.println("번호:"+num);
}
}
//휴먼클래스 상속받고
//printHuman()함수 실행시 휴먼의 함수가 아니라
//상속받은 클래스의 printHuman()의 무언가를 실행하면서+
//휴먼에 있는 printHuman()도 실행되게 코드를 작성하시오<file_sep>package conception;
public class Person1 {
private String name;
private int age;
private String address; // person class 에는 접근은 가능 하지만
// 직접접근이 불가능 하므로 메모리값을 바꾸려고//접근 가능한 method제공하려고
public void setName(String name) {// Excutor p.setName("eunwoo");=(string name)을 받아서 밑에 name=>this.name=>private
// String name
this.name = name;
}
public void getAge(int age) {
this.age = age;
}
public void setAddress(String address) {
this.address = address;
}
public String getName1() {
return this.name;
}
/*
* public String toString() { String str =
* "내이름은 :"+this.name+" age : "+this.age+" address : "+this.address; return str;
* //바뀐값으로 }
*/
}
<file_sep>package conception;
/*
class Test {// <<<!!!!기본생성자 constructer!!!!>>>>
int num =3;
Test() {// 생략이 가능할 뿐 없는 것이 아님!!!!!!!
System.out.println(thi.snum);
this.test();
}
voidtest(){System.out.println("g")}
*/
public class Exec {
public static void main(String[] args) {
// carclass가있어서 데이터타입이라 배열마늘수있음
Cons c = new Cons();
System.out.println(c.num);//초기값0
c=new Cons(10);//int를 가지고 있는 것을 호출
System.out.println(c.num);
// 호출시 무조건 실행
//Test t = new Test();// 함수호출! class없어도 가능
// 기본생성자!!!생성만 가능하지t.은 안됨, overLoading가능
//오버라이딩은안됨, 초기값생성, 반드시 무언가를 해야할때 **제일 먼저 실행하는것
//생성자에서Test호출 ,
}
}
<file_sep>package basic;
public class SortTest2 {
public static void main(String[]args) {
String[] arrStr = new String[5]; //string 저장 공간5개 들어가는 초기값은 null
String s = arrStr[0];
arrStr[5] = "abs";//compiled은 되만 실행x 번역은 했지만 실행x
System.out.println(arrStr[0]);//null
System.out.println(arrStr[0].length());//null
System.out.println(s.length());
System.out.println(arrStr.length);//0-4string 맞
String[] arrStr1 = new String[5];
arrStr1[0] ="a";
arrStr1[1] ="b";
arrStr1[2] ="c";
arrStr1[3] ="d";
arrStr1[4] ="e";
for(int i=0;i<arrStr1.length;i++) {
System.out.println(arrStr1[i]);
}
}
}
<file_sep>package a;
import java.util.ArrayList;
public class test {
public static void main(String[]args) {
ArrayList<Student> sList = new ArrayList<Student>();
for(int i = 0; i<=5;i++) {
String name = "test"+i;
int grade = (int)(Math.random()*10)+1;
sList.add(new Student(name, grade));
}
for(int i = 0; i<sList.size();i++) {
for(int j = i+1; j<sList.size();j++) {
if(sList.get(i).grade<sList.get(j).grade) {
Student s = sList.get(i);
sList.set(i,sList.get(j));
sList.set(j, s);
}
}
}
for(Student st : sList) {
System.out.println(st.name+","+st.grade);
}
}
}
<file_sep>package computer;
public class Laptop extends Computer {
public String res;
public void printInfo() {
}
}
<file_sep>package test29;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/*
* animal이라는 클래스 생성
* name이라는 String변수 생성
* Dog cat이라는 클래스 생성 animal이라는 클래스 상속
* animal만 가질 수 있는 aniList생성
* 2마리의 개와 2마리의 고양이를 aniList에 저장하고 출력하는 코드를 작성해주세요*/
import org.apache.commons.lang3.StringUtils;
public class ListTest03 {
public static int indexOf(String str, String searchStr) {
for(int i = 0; i<str.length();i++) {
Character c = str.charAt(i);
if(c.toString().equals(searchStr)) {
return i ;
}
}
return -1;
}
public static int lastIndexOf(String str, String searchStr) {
for(int i = str.length()-1; 0<=i;i--) {
Character c = str.charAt(i);
if(c.toString().equals(searchStr)) {
return i ;
}
}
return -1;
}
public static int count(String s, String search) {
for(int i = 0; i<s.length();i++) {
Character c = s.charAt(i);
if(c.toString().equals(search)) {
return ++i ;
}
}
return -1;
}
public static void main(String[] args) {
String str = "A,B,C";
int idx = indexOf(str,",");
System.out.println(idx);
int idx1 = lastIndexOf(str,",");
System.out.println(idx1);
int count = StringUtils.countMatches("A,B,C",",");
System.out.println(count);
int c = count(str,",") ;
System.out.println(c);
List<Person> pList = new ArrayList<Person>();// Person[] ps = new Person[0];
// person만 가질 수 있는 리스트
/*Person p = new Person("홍길동", 22);
pList.add(p);
pList.add(new Person("홍길동", 22));*/
// 반복문으로 나이만 랜덤으로 1-100집어 넣어서 총 10사람 리스트 출력
for (int i = 0; i < 5; i++) {
Scanner scan = new Scanner(System.in);
System.out.println("이름을 입력하시오");
String name = scan.nextLine();
System.out.println("나이입력");
String age1 = scan.nextLine();
int age = Integer.parseInt(age1);
//int age = (int) (Math.random() * 100) + 1;
pList.add(new Person(name, age));
}
for (Person p : pList) {
System.out.println(p);
}
}
}
<file_sep>package test20;
//interface
//1.몸통이 없음. 메서드 선언할 때 {}무슨일 할지 정의내리지 x, 어떤것을 할거야ㅑ!
//2.생성자 ㅇ나됨
public interface Action {
public void eat();//이거는 자동 퍼블릭!
public void sleep();
public void move();
public static void tset() {
System.out.println("나는 1.8부터 됨!");
}
}<file_sep>package test19;
public class Person {
public int point;
public String name;
public int rank;
}
<file_sep>package test18;
import java.util.Scanner;
public class Exec {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Person[] p = new Person[5];
int[] rank = new int[p.length];//메모리 생성x
for(int i = 0; i<p.length;i++) {
p[i]= new Person();
p[i].name = (i+1)+"번째 사람";
System.out.println(i+1+"번째 사람의 점수를 입력하시오");
p[i].point = Integer.parseInt(scan.nextLine());
rank[i]= p[i].point;
}
//포인트 정렬
for(int i = 0; i<rank.length;i++) {
for(int j = i+1; j<rank.length;j++) {
if(p[i].point<p[j].point) {
int tmp = p[i].point;
p[i].point = p[j].point;
p[j].point = tmp;
}
}
}
//
for(int i = 0; i<rank.length;i++) {
for(int j =0; j<p.length;j++) {
if(rank[i]==p[j].point) {
p[j].rank = i+1;
}
}
}
for(int i = 0; i<p.length;i++) {
System.out.println(p[i].name+"님의 점수는"+p[i].point+"입니다.");
System.out.println(p[i].name+"님의 등수는"+p[i].rank+"등 입니다.");
System.out.println();
}
}
}
<file_sep>package conception2;
public class FuncTest {
public void add(int a, int b) {
System.out.println("인트 더하기:"+(a+b));
}
public void add(long a, long b) {
System.out.println("롱더하기:"+a+b);
}
public static void main(String[]args) {
FuncTest ft = new FuncTest(); //위의 method들은 static이 아니기 때문에 메모리를 생성해서 호출
//functest클래스 안에 있는 것 ,초기화, 모든것을 읽어서 호출 해준다.
//FuncTest ft; ft = new FuncTest();
ft.add(1, 2);
ft.add(12345678910l, 123456789102l);
long a = 12345678910l;
long b = 1234567895010l;
System.out.println(a+b);
}
}
<file_sep>package reCheck2;
//weapon에 대한 의존성이 있따.
//왜냐하면 weapon이 없으면 에러
public class Robot {
public Weapon w;//weapon이라는 데이터 타입! 정해져있지 않는 데이터타입 기본값null로 초기화!
}
<file_sep>package conception;
public class Father {
public void test() {
System.out.println("아빠의 테스트 함수");
}
public void run() {
System.out.println("달려");
}
public void sleep() {
System.out.println("자");
}
void work() {
System.out.println("아부지 건설일");
}
}
<file_sep>package conception;
public class Person {
String name;
int age;
String address;
void run() {
System.out.println(name+"님이 뜁니다.");
}
void eat() {
System.out.println(name+"님이 먹습니다.");
}
void sleep() {
System.out.println(name+"님이 잡니다.");
}
}
<file_sep>package test16;
public class Student {
public String name;
public int point;
public Student(String name, int point) {
this.name = name;
this.point = point;
}
public String toString() {
return "학생:"+name+"point"+point;
}
public static void main(String[] args) {
Student[] sts = new Student[3];
//기본데이터 타입의 배열에는 원래 문자를 넣을 수 없지만
//Students라는 정해지지 않는 데이터 타입의 배열엔 문자를 넣을 수 있다.
sts[0] = new Student("전정국", 100);
sts[1] = new Student("박뽀검", 120);
sts[2] = new Student("차은우", 10000);
for (int i = 0; i < sts.length; i++) {
for (int j = i + 1; j < sts.length; j++) {
if(sts[i].point<sts[j].point) {
Student st = sts[i];
sts[i] = sts[j];
sts[j] = st;
}
}
}
for(int i = 0; i<sts.length;i++) {
System.out.println(sts[i]);
}
}
}
<file_sep>package test18;
public class SortTest {
public static void method (int[] arr) {
for(int i = 0; i<arr.length;i++) {
for(int j = i+1;j< arr.length;j++){
if(arr[i]<arr[j]) {
int tmp = arr[i];
arr[i]= arr[j];
arr[j] = tmp;
}
}
}
}
public static void printArr(int[] arr) {
for(int i = 0; i<arr.length;i++) {
if(i<arr.length-1) {
System.out.print(arr[i]+",");
}else {
System.out.print(arr[i]);
}
}
}
public static void main(String[]args) {
int[] arr = new int[] {2,3,5,7,9,10,24,57};//방을만들면서 순서대로 초기화를함
method(arr);
printArr(arr);//매개변수가 배열이면 배열 변수를 넣는다.
}
}
<file_sep>package test28;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import test28.impl.UserDAOImpl;
public class Exec {
public static void main(String[] args) {
UserDAO udao = new UserDAOImpl();
HashMap<String, String> userInfo = new HashMap<String, String>();
//////////////////////////////////////////////////////////////////////////////
ArrayList<HashMap<String, String>> userList = udao.selectUserInfoList(userInfo);
userInfo.put("uiEtc","1");
userInfo.put("uiName","하하");
if(udao.updatetUserInfo(userInfo)==1) {
System.out.println("ok");
}else {
System.out.println();
}
if(udao.deletetUserInfo(userInfo)==1) {
System.out.println("ok");
}else {
System.out.println();
}
for(HashMap<String,String> user :userList) {
System.out.println(user);
}
for(int i = 0; i<userList.size();i++) {
System.out.println(userList.get(i));
}//해시맵에 하나하나
System.out.print(userList);
Scanner scan = new Scanner(System.in);
System.out.println("몇명등록?");
int max = Integer.parseInt(scan.nextLine());
for (int i = 0; i < max; i++) {
System.out.println("name");
String name = scan.nextLine();
System.out.println("age");
String age = scan.nextLine();
System.out.println("etc");
String etc = scan.nextLine();
userInfo.put("uiName", name);
userInfo.put("uiAge", age);
userInfo.put("uiEtc", etc);
if (udao.insertUserInfo(userInfo) == 1) {
System.out.println("성공");
} else {
System.out.println("실패");
}
}
}
}
<file_sep>package test24;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class Map {
public static void main(String[] args) {
HashMap<String,String> hm = new HashMap<String,String>();
//정해져있는 데이터 타입은 쓸 수 없다. key값,valus값 모두 String
hm.put("이름","차은우");
hm.put("이름","차은우1");
hm.put("주소","서울");
hm.put("나이","22");
Iterator<String> it = hm.keySet().iterator();
while(it.hasNext()) {
String key = it.next();
String str = "key"+key+",value="+hm.get(key) ;
System.out.println(str);
}
String name = hm.get("이름");
System.out.println(name);
ArrayList<String> aList = new ArrayList<String>();
aList.add("은우");
aList.add("seoul");
aList.add("동동이");
System.out.println(aList);
}
}
<file_sep>package test21;
public class Solid extends Cart {
public Solid(String name, int speed, int damage) {
super(name, speed, damage);
// TODO Auto-generated constructor stub
}
public String attack(int damage) {
return this.damage+damage+"만큼공경!";
}
}
<file_sep>package a.imp;
public interface UserDaoImpl {
}
<file_sep>package basicLogic;
//방의 값이 큰 순서로 정렬
public class NumSort {
public static void main(String[] args) {
int[] arrNum = new int[3];
arrNum[0] = 30;
arrNum[1] = 20;
arrNum[2] = 10;
int i = 0;
for(;i<arrNum.length;i++) {
for(int j = i+1; j<arrNum.length;j++) {
if(arrNum[i]>arrNum[j]) {
int tmp = arrNum[i];
arrNum[i]=arrNum[j];
arrNum[j]=tmp;
}
}
}
for( ;i<arrNum.length;i++) {
System.out.println(arrNum[i]);
}
int u = 1;
System.out.println(u++);
System.out.println(--u);
//System.out.println(a);
//System.out.println(s);
long x = 1024;
/*
int[] arrNum = new int[3];
arrNum[0] = 30;
arrNum[1] = 20;
arrNum[2] = 10;
for (int i = 0; i<arrNum.length; i++) {
for (int j = i + 1; j < arrNum.length; j++) {
if (arrNum[i] > arrNum[j]) {
int tmp = arrNum[i];
arrNum[i] = arrNum[j];
arrNum[j] = tmp;
}
}
}
for(int i=0 ;i<arrNum.length;i++) {
System.out.println(arrNum[i]);
}*/
}
}
<file_sep>package reCheck;
//오버로딩은 같은 함수를 쓴것
//상속 오버라이딩 --함수명 동일!
public class PrintObject {
String str = "poStr";
public String toString() {
return "이 클래스의 str이란 변수는" + str + "이라는 값을 가지고 있죠";
}
public static void main(String[] args) {
String str = new String("str");
System.out.println(str);
PrintObject po = new PrintObject();
System.out.println(po);
/*
* String str = "Abc"; System.out.println(str);
*
* PrintObject po = new PrintObject(); System.out.println(po.str);
* System.out.println(po.toString()); System.out.println(po);
*
*
*
* String str1 = new String("Abc"); System.out.println(str1);
*
* PrintObject po1 = new PrintObject(); System.out.println(po1.str);
* System.out.println(po1.toString()); System.out.println(po1);
*/
}
}
<file_sep>package test20;
import java.awt.List;
import java.util.ArrayList;
public class ForEachTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] arrStr = new String[4];
for(int i = 0;i<arrStr.length;i++) {//string이여야만 가능
arrStr[i] = "test"+i;
}
for(String str:arrStr) {
System.out.println(str);
}
String[] arr = {"보검","정국","은우"};//방번호와 초기화 동시
System.out.println(arr[1]);
String[][] multiArr = {{"1","2","3"},{"4"},{"5","6","7"}};
System.out.println(multiArr[0][2]);
for(String[] strs: multiArr) {
for(String str : strs) {
System.out.println(str);
}
}
ArrayList<String> strList = new ArrayList<String>();
for(int i = 0;i<arrStr.length;i++) {
strList.add( "test"+i);
}
for(String str:arrStr) {
System.out.println(str);
}
}
}
<file_sep>package reCheck2;
public class LuckyNum {
private int luckyNum;
LuckyNum() {//초기값 생성, 반드시 실행해야할것
luckyNum = ((int) Math.random() * 10) + 1;
}
public void checkLuckyGuy(Person p) {//data type이 person
/*System.out.println(p instanceof KilDong);
//instanceof>>p 를 kildong이라고 불러도됨?
//실제 생성된 데이터 타입이 아니라, 불러도 되는지를 물어보는것임
//따라서
System.out.println(p instanceof Person);//어떤 사람의 이름이든 true
//datatype이 모두 person이여도 exec에서 메모리생성을 길동으로함
*/
if(p instanceof KilDong) {
KilDong kd = (KilDong)p;
kd.checkMyLuckyNum(luckyNum);
} else if(p instanceof Eunwoo) {
Eunwoo e = (Eunwoo)p;
e.test();
}
}
}
| d4aaddaa2a8dbcdef274f9466969c998345e289c | [
"Java"
] | 36 | Java | sangkyu90/ict1 | e9b1c62fd2e888ba8d726f302ae6ee5230a14fe8 | e4a4be6544c0353a613f0cfe78038faec7cfd954 | |
refs/heads/main | <repo_name>patrickmcdonogh/dhlconsumer<file_sep>/java/src/dhl/demo/MessageHandler.java
package dhl.demo;
import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.RangeAssignor;
import org.apache.kafka.common.serialization.StringDeserializer;
import com.apama.epl.plugin.Correlator;
import com.apama.util.Logger;
public class MessageHandler implements KafkaMessageHandler {
final static Logger logger = Logger.getLogger();
KafkaConsumer<String, String> consumer;
public MessageHandler() {
}
@Override
public int pollAndHandleMessages() {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(300));
int recordCount = records.count();
if (recordCount > 0) {
for (ConsumerRecord<String, String> record : records) {
try {
logger.info("Managing message = "+record.value());
Correlator.sendTo(record.value(), "");
}
catch(Exception ex) {
logger.error("Issue sending data to correlator", ex);
}
}
}
return recordCount;
}
@Override
public void setupKafkaConsumer(String bootstrapServers, String topic, String consumerGroup, boolean autoAck, ConsumerRebalanceListener rebalanceManager) {
Properties properties = new Properties();
properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
String valueDeserializer = StringDeserializer.class.getName();
properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, valueDeserializer);
properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, consumerGroup);
properties.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, String.valueOf(autoAck));
properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
properties.setProperty(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, RangeAssignor.class.getName());
properties.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "500");
properties.setProperty(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, "1280000");
//switch classloader so that kafka can find the serializers
ClassLoader original = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(null);
consumer = new KafkaConsumer<String, String>(properties);
Thread.currentThread().setContextClassLoader(original);
consumer.subscribe(Arrays.asList(topic), rebalanceManager);
}
@Override
public void terminatePoll() {
consumer.unsubscribe();
consumer.close();
}
}
<file_sep>/java/src/dhl/demo/TopicProducer.java
package dhl.demo;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.errors.RecordTooLargeException;
import org.apache.kafka.common.serialization.StringSerializer;
import com.apama.util.Logger;
public class TopicProducer<K,V> {
protected static Logger logger = Logger.getLogger();
protected String bootstrapServers;
protected String topic;
protected KafkaProducer<K, V> producer;
private BlockingQueue<ProducerRecord<K, V>> messageQueue;
private int messagesPublished;
private final AtomicBoolean running = new AtomicBoolean(true);
public TopicProducer(String bootstrapServers, String topic) {
super();
this.bootstrapServers = bootstrapServers;
this.topic = topic;
createPublisher();
}
public String getTopic() {
return topic;
}
private void createPublisher() {
//switch classloader so that kafka can find the serializers
ClassLoader original = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(null);
producer = createProducer();
logger.info("Created producer for " + topic);
Thread.currentThread().setContextClassLoader(original);
messageQueue = new ArrayBlockingQueue<>(200 * 1000);
new Thread(new Runnable() {
@Override
public void run() {
while(running.get()) {
try {
sendRecord((ProducerRecord<K, V>)messageQueue.take());
messagesPublished++;
}
catch(Exception ex) {
logger.error("Error sending data to Kafka topic = "+topic, ex);
}
}
logger.info("Closing producer on topic = "+topic);
producer.close();
}
}).start();
}
protected KafkaProducer<K, V> createProducer() {
Properties properties = new Properties();
properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.setProperty(ProducerConfig.MAX_BLOCK_MS_CONFIG, "60000");
properties.setProperty(ProducerConfig.ACKS_CONFIG, "all");
properties.setProperty(ProducerConfig.RETRIES_CONFIG, "10");
properties.setProperty(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");
properties.setProperty(ProducerConfig.MAX_REQUEST_SIZE_CONFIG, "2097152");
properties.setProperty(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, "300000");
return new KafkaProducer<K, V>(properties);
}
protected void sendRecord(ProducerRecord<K, V> record) {
ProducerRecord<K, V> theRecord = (ProducerRecord<K, V>)record;
producer.send(theRecord, new Callback() {
@Override
public void onCompletion(RecordMetadata arg0, Exception ex) {
if (ex != null) {
logger.error("Error sending message to Kafka topic = "+topic, ex);
if (ex instanceof RecordTooLargeException) {
if (theRecord.value() instanceof String) {
logger.error("Too Large Message:" + ((String)theRecord.value()).substring(0,500));
}
}
else {
logger.error("Message:" + record.value());
}
}
}
});
}
public void stop() {
running.set(false);
}
public boolean publish(ProducerRecord<K, V> record, boolean block) {
boolean output = true;
try {
if ( block ) {
messageQueue.put(record);
}
else
{
output = messageQueue.offer(record);
if ( !output ) {
logger.error("Could not add message to internal queue for Kafka topic = "+topic+". Internal message queue size = "+messageQueue.size());
}
}
}
catch (Exception ex) {
logger.error("Error sending message to topic = "+topic, ex);
output = false;
}
return output;
}
}
<file_sep>/Dockerfile
# Copyright (c) 2017-2018 Software AG, Darmstadt, Germany and/or its licensors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
# file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the
# License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
# Create an image from the base Apama image, copying the project in it ready to deploy
ARG APAMA_IMAGE=store/softwareag/apama-correlator:10.5
FROM ${APAMA_IMAGE}
COPY --chown=sagadmin:sagadmin ApamaServerLicense.xml ${APAMA_WORK}/DHLDemo/
COPY --chown=sagadmin:sagadmin init.yaml ${APAMA_WORK}/DHLDemo/
COPY --chown=sagadmin:sagadmin eventdefinitions ${APAMA_WORK}/DHLDemo/eventdefinitions
COPY --chown=sagadmin:sagadmin monitors ${APAMA_WORK}/DHLDemo/monitors
COPY --chown=sagadmin:sagadmin plugin ${APAMA_WORK}/DHLDemo/plugin
COPY --chown=sagadmin:sagadmin lib ${APAMA_WORK}/lib
WORKDIR ${APAMA_WORK}
CMD ["correlator", "--config", "DHLDemo"]
<file_sep>/java/src/dhl/demo/KafkaMessageHandler.java
package dhl.demo;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
public interface KafkaMessageHandler {
int pollAndHandleMessages();
void setupKafkaConsumer(String bootstrapServers, String topic, String consumerGroup, boolean autoAck, ConsumerRebalanceListener rebalanceManager);
void terminatePoll();
}
| a477c03b7a7bf4baba8c2d6a590547549aca9919 | [
"Java",
"Dockerfile"
] | 4 | Java | patrickmcdonogh/dhlconsumer | 65cd0d81a4836d183d01236c177fd81bf4c2ba71 | 3a97ac93e77caf97db02dcf7a1aef574a9afbd93 | |
refs/heads/master | <repo_name>fatemehAkbarnejad/homework<file_sep>/js/slider.js
var name = "Fatemeh";
var family = "Akbarnejad";
var names = ["ali", "sara", "reza"];
document.write(names.length);
document.write("<br/>");
document. | 151c4c78ff369cf95c32e66f96fbe037e266e6ee | [
"JavaScript"
] | 1 | JavaScript | fatemehAkbarnejad/homework | 92378ff507a6b44dd4f4e2aaab5185558bca3783 | e65af0012a1b873788b7b4f53ecb32b9549efac2 | |
refs/heads/master | <file_sep>"use strict";
var test = "Hello";<file_sep>'use strict';
var theString = "Hello, I love Javascript";
console.log(theString.includes('love'));
function greet() {
var greeting = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'Hello World';
console.log(greeting);
}
greet();<file_sep># es6
1. Set is a container that have unique values in it.
2. It has function like, add, delete.
3. Loop on set can be done by forEach method.
Map
1. Map are key value pairs.
2. You can add & delete key values in map through set and delete method.
WeakSet (unique objects collection - WeakSet objects are collections of objects. An object in the WeakSet may only occur once; it is unique in the WeakSet's collection.)
1. add and delete methods are used.
WeakMap (objects map, where key and value are both objects)
1. set and delete methods are used.
<file_sep>'use strict';
var myArray = [11, 33, 22, 44, 11];
var mySet = new Set(myArray);
console.log(mySet);
mySet.add('tom');
mySet.add(12);
mySet.delete(22);
mySet.forEach(function (val) {
console.log(val);
});<file_sep>class User {
constructor(username, email, password){
this.username = username;
this.email = email;
this.password = <PASSWORD>;
}
register(){
console.log(this.username + ' is now registered.');
}
}
class Member extends User {
constructor(username, email, password, memberPackage){
super(username, email, password);
this.memberPackage = memberPackage;
}
getPackage(){
console.log(this.username + ' is now a Member');
}
}
let bob = new User('bob', '<EMAIL>', '12345');
bob.register();
let alice = new Member('Alice', '<EMAIL>', '2212', 'Sys');
alice.getPackage();
| cb68edf600ba77eeeafbfb88af97cc1d7582da5e | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | shivamrastogi/es6 | dc7095d50fee790560d13da33f8000d7628bcb91 | d95470d203995f5808e7cac93003814f5e09bb07 | |
refs/heads/master | <file_sep>class MarketReviewsController < ApplicationController
before_action :set_market_review, only: [:show, :edit, :update, :destroy]
# GET /market_reviews
# GET /market_reviews.json
def index
@market_reviews = MarketReview.all
end
# GET /market_reviews/1
# GET /market_reviews/1.json
def show
end
# GET /market_reviews/new
def new
@market_review = MarketReview.new(market_id: params[:market_id])
end
# GET /market_reviews/1/edit
def edit
end
# POST /market_reviews
# POST /market_reviews.json
def create
@market_review = MarketReview.new(market_review_params)
respond_to do |format|
if @market_review.save
format.html { redirect_to @market_review, notice: 'Market review was successfully created.' }
format.json { render :show, status: :created, location: @market_review }
else
format.html { render :new }
format.json { render json: @market_review.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /market_reviews/1
# PATCH/PUT /market_reviews/1.json
def update
respond_to do |format|
if @market_review.update(market_review_params)
format.html { redirect_to @market_review, notice: 'Market review was successfully updated.' }
format.json { render :show, status: :ok, location: @market_review }
else
format.html { render :edit }
format.json { render json: @market_review.errors, status: :unprocessable_entity }
end
end
end
# DELETE /market_reviews/1
# DELETE /market_reviews/1.json
def destroy
@market_review.destroy
respond_to do |format|
format.html { redirect_to market_reviews_url, notice: 'Market review was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_market_review
@market_review = MarketReview.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def market_review_params
params.require(:market_review).permit(:title, :content, :rate, :date, :user_id, :market_id, :image)
end
end
<file_sep>json.array! @shop_reviews, partial: 'shop_reviews/shop_review', as: :shop_review
<file_sep>class CreateMarkets < ActiveRecord::Migration[5.0]
def change
create_table :markets do |t|
t.string :name
t.string :address
t.string :open
t.boolean :parking
t.string :tel
t.string :closed
t.string :locate1
t.string :locate2
t.string :locate3
t.string :image
t.timestamps
end
end
end
<file_sep># README
This README would normally document whatever steps are necessary to get the
application up and running.
Things you may want to cover:
* Ruby version
* System dependencies
* Configuration
* Database creation
* Database initialization
* How to run the test suite
* Services (job queues, cache servers, search engines, etc.)
* Deployment instructions
* ...
------------------------------------------------
* rails version : 5.0.6(5.0.7)
* Market scaffold
model로 만든 것 : 가게이름(name) 위치(address) 영업시간(open) 주차가능여부(parking-boolean) 전화번호(tel) 휴일(closed) 시/도(locate1) 군/구(locate2) 동/읍/면(locate3) => parking 빼고 전부 string
=> locate3는 잘못 만든 것 ㅠㅠ
* MarketReview scaffold
Market(상위) - MarketReview(하위)
User(상위) - MarketReview(하위)
model로 만든 것 : 제목(title-string) 내용(content-text) 별점(rate-float) 날짜(date-date)
* Shop scaffold
Market(상위) - Shop(하위) => 소속
model로 만든 것 : 가게이름(name) 영업시간(open) 전화번호(tel)
* ShopReview scaffold
Shop(상위) - ShopReview(하위)
User(상위) - ShopReview(하위)
model로 만든 것 : 제목(title-string) 내용(content-text) 별점(rate-float) 날짜(date-date)
* Menu scaffold
Shop(상위) - Menu(하위)
model로 만든 것 : 메뉴이름(name) 가격(price-integer) 부가설명(content-text)
* devise gem 사용을 위한 세팅 완료(2018-08-15)
* devise를 이용하여 User, Admin 모델 생성
* admin gem 설치 완료(2018-08-15), 추후에 https://say8425.github.io/setup-rails-admin-1/ 를 참고하여 설정하기
<file_sep>json.extract! market_review, :id, :title, :content, :rate, :date, :created_at, :updated_at
json.url market_review_url(market_review, format: :json)
<file_sep>class ShopReviewsController < ApplicationController
before_action :set_shop_review, only: [:show, :edit, :update, :destroy]
# GET /shop_reviews
# GET /shop_reviews.json
def index
@shop_reviews = ShopReview.all
end
# GET /shop_reviews/1
# GET /shop_reviews/1.json
def show
end
# GET /shop_reviews/new
def new
@shop_review = ShopReview.new(shop_id: params[:shop_id])
end
# GET /shop_reviews/1/edit
def edit
end
# POST /shop_reviews
# POST /shop_reviews.json
def create
@shop_review = ShopReview.new(shop_review_params)
respond_to do |format|
if @shop_review.save
format.html { redirect_to @shop_review, notice: '가게 리뷰 작성 완료' }
format.json { render :show, status: :created, location: @shop_review }
else
format.html { render :new }
format.json { render json: @shop_review.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /shop_reviews/1
# PATCH/PUT /shop_reviews/1.json
def update
respond_to do |format|
if @shop_review.update(shop_review_params)
format.html { redirect_to @shop_review, notice: '가게 리뷰 수정 완료' }
format.json { render :show, status: :ok, location: @shop_review }
else
format.html { render :edit }
format.json { render json: @shop_review.errors, status: :unprocessable_entity }
end
end
end
# DELETE /shop_reviews/1
# DELETE /shop_reviews/1.json
def destroy
@shop_review.destroy
respond_to do |format|
format.html { redirect_to shop_reviews_url, notice: '가게 리뷰가 삭제되었습니다.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_shop_review
@shop_review = ShopReview.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def shop_review_params
params.require(:shop_review).permit(:title, :content, :rate, :date, :user_id, :shop_id, :image)
end
end
<file_sep>json.partial! "shop_reviews/shop_review", shop_review: @shop_review
<file_sep>json.partial! "market_reviews/market_review", market_review: @market_review
<file_sep>json.extract! shop, :id, :name, :open, :tel, :created_at, :updated_at
json.url shop_url(shop, format: :json)
<file_sep>class Shop < ApplicationRecord
mount_uploader :image, ImageUploader
belongs_to :market
has_many :menus
has_many :shop_reviews
end
<file_sep>json.array! @market_reviews, partial: 'market_reviews/market_review', as: :market_review
<file_sep>class Market < ApplicationRecord
mount_uploader :image, ImageUploader
has_many :shops
has_many :market_reviews
end
<file_sep>class ShopReview < ApplicationRecord
mount_uploader :image, ImageUploader
belongs_to :shop
belongs_to :user
validates :user, presence: true
end
<file_sep>json.extract! shop_review, :id, :title, :content, :rate, :date, :created_at, :updated_at
json.url shop_review_url(shop_review, format: :json)
<file_sep>Rails.application.routes.draw do
devise_for :users
resources :shop_reviews
resources :market_reviews
resources :menus
resources :shops
resources :markets
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'markets#index'
end
<file_sep>class MarketReview < ApplicationRecord
mount_uploader :image, ImageUploader
belongs_to :market
belongs_to :user
validates :user, presence: true
end
<file_sep>json.extract! market, :id, :name, :address, :open, :parking, :tel, :closed, :locate1, :locate2, :locate3, :image :created_at, :updated_at
json.url market_url(market, format: :json)
| a2c7f1bca7b9db43aca105ba20533d9bc7059c10 | [
"Markdown",
"Ruby"
] | 17 | Ruby | fuya1/fuya | 172893164a2dcbc8c86660bb45c9c53943b56f3e | 9a3ceb160f51eec2ac0882115fb1c08bdce96e71 | |
refs/heads/master | <repo_name>rahulyadav20111995/kalage_task<file_sep>/sign_in.php
<?php
$servername = "localhost";
$username = "admin_joy";
$password = "<PASSWORD>";
$dbname ="kalage";
$conn=new mysqli($servername,$username,$password,$dbname);
//check connection
if($conn->connect_error)
{
die("Connection failed: ".$conn->connect_error);
}
$user = $_POST['user'];
$pass = $_POST['pass'];
$query = "SELECT * FROM users WHERE `user_name`='$user' AND `password`='$pass'";
$result=$conn->query($query);
$jsonresponse=new stdClass();
if($result->num_rows>0){
$row=$result->fetch_array();
$jsonresponse->status=TRUE;
$jsonresponse->f_name=$row['first_name'];
$jsonresponse->email=$row['email'];
$jsonresponse->phone=$row['phone'];
$jsonresponse->l_name=$row['last_name'];
echo json_encode($jsonresponse);
}
else{
echo "User not found . Please sign up first";
}
?>
<file_sep>/sign_up.php
<?php
$servername = "localhost";
$username = "admin_joy";
$password = "<PASSWORD>";
$dbname ="kalage";
$conn=new mysqli($servername,$username,$password,$dbname);
//check connection
if($conn->connect_error)
{
die("Connection failed: ".$conn->connect_error);
}
$handle = $_POST['handle'];
$pass = $_POST['pass'];
$f_name = $_POST['f_name'];
$l_name = $_POST['l_name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$query = "SELECT * FROM users WHERE `user_name`='$handle' OR `email`='$email'";
$result=$conn->query($query);
$query_rows = "SELECT * FROM users";
$result_rows=$conn->query($query_rows);
$newuserid = ($result_rows->num_rows)+1;
if($result->num_rows==0){
$insertUser = "INSERT into users VALUES('$newuserid','$handle','$f_name','$l_name','$phone','$email','$pass') ";
$insertResult=$conn->query($insertUser);
echo 'Registered ! Now Login!';
}
else{
echo "Same User exist with handle or email id";
}
?> | dcda6c3b372c7d875c9e520104923d0e13a984eb | [
"PHP"
] | 2 | PHP | rahulyadav20111995/kalage_task | c974cb226153f7b0665d76fbc87bbaf15ce434f8 | 85d5c5f91c5640c6af9440e1f5cb5bc01c333ce6 | |
refs/heads/master | <repo_name>FPizzetti/jqueue-rest-api<file_sep>/controllers/database.controller.js
'use strict';
var config = require('../config/env.config');
function list(req, res) {
var databases = [];
for (var i in config.databases) {
if (config.databases.hasOwnProperty(i)) {
var database = config.databases[i];
var cloned = Object.assign({configName: i}, database);
delete cloned.password;
databases.push(cloned);
}
}
res.send(200, databases);
}
function getByName(req, res) {
var database = config.databases[req.params.db];
if (!database) {
res.send(404, {message: 'database not found'});
} else {
var cloned = Object.assign({configName: req.params.db}, database);
delete cloned.password;
res.send(200, cloned);
}
}
module.exports = {
list: list,
getByName: getByName
};<file_sep>/middlewares/jqueue.middleware.js
'use strict';
var Jqueue = require('jqueue');
var mysql = require('mysql');
var databases = require('../config/env.config').databases;
var jqueueBuffer = {};
var jqueueBufferSize = 10;
module.exports = function (req, res, next) {
if (req.params && req.params.db) {
var dbName = req.params.db;
var jqueue = jqueueBuffer[dbName];
if (jqueue) {
req.jqueue = jqueue.object;
req.dataSource = jqueue.dataSource;
next();
} else {
var database = databases[dbName];
if (database) {
var dataSource = mysql.createPool(database);
jqueue = new Jqueue(dataSource);
var bufferKeys = Object.keys(jqueueBuffer);
if (bufferKeys.length >= jqueueBufferSize) {
delete jqueueBuffer[bufferKeys[0]];
}
jqueueBuffer[dbName] = {object: jqueue, dataSource: dataSource};
req.jqueue = jqueue;
req.dataSource = dataSource;
next();
} else {
res.send(404, {message: 'database ' + dbName + ' not found'});
}
}
} else {
res.send(400, {message: 'missing database'});
}
};<file_sep>/middlewares/queue.middleware.js
'use strict';
module.exports = function (req, res, next) {
if (req.params && req.params.queue) {
var queueName = req.params.queue;
req.jqueue.use(queueName, true, function (error, queue) {
if (!error) {
req.queue = queue;
next();
} else {
if (error.message.match(/ER_NO_SUCH_TABLE/)) {
res.send(404, {message: 'queue ' + queueName + ' not found'});
} else {
res.send(500, error);
}
}
});
} else {
res.send(400, {message: 'missing queue'});
}
};<file_sep>/index.js
'use strict';
var restify = require('restify'),
routes = require('./config/routes.config'),
env = require('./config/env.config');
var server = restify.createServer();
server.use(restify.bodyParser());
server.use(restify.queryParser());
routes(server);
server.listen(env.port, function () {
console.log('jqueue-rest-api listening at port %s', env.port);
});<file_sep>/config/env.config.js
'use strict';
module.exports = {
port: 8000,
databases: {
devdb: {
host: '192.168.100.121',
user: 'pdg',
password: '<PASSWORD>',
database: 'jqueue'
}
}
};<file_sep>/daos/message.dao.js
'use strict';
function update(cb, connection, message) {
connection.query('UPDATE ?? SET status = ? WHERE id = ?', [message.queue, message.status, message.id], function (error) {
cb(error);
});
}
function massiveUpdate(cb, connection, sql) {
console.log('UPDATE sql:', sql);
connection.query(sql.query, sql.whereParams, function (error) {
console.log('err', error);
cb(error);
});
}
function massiveDelete(cb, connection, sql) {
console.log('delete sql', sql);
connection.query(sql.query, sql.whereParams, function (error) {
console.log('err', error);
cb(error);
});
}
function listByQueue(cb, connection, sql) {
var messageList = [];
console.log('sql', sql);
connection.query(sql.query, sql.whereParams, function (error, rows, fields) {
if (!error) {
if (rows.length) {
for (var ix in rows) {
messageList.push(rows[ix]);
}
}
}
else {
console.log('err', error);
}
cb(error, messageList);
});
}
function deleteQueue(cb, connection, queue, id) {
connection.query('DELETE FROM ?? WHERE id = ?', [queue, id], function (error) {
cb(error);
});
}
function getById(cb, connection, queue, id) {
connection.query('SELECT * FROM ?? WHERE id = ?', [queue, id], function (error, rows) {
if (error) {
cb(error);
} else {
var result = null;
if (rows.length) {
result = rows[0];
}
cb(error, result);
}
});
}
module.exports = {
update: update,
getById: getById,
deleteQueue: deleteQueue,
listByQueue: listByQueue,
massiveUpdate: massiveUpdate,
massiveDelete: massiveDelete
};<file_sep>/controllers/queue.controller.js
'use strict';
var queueDao = require('../daos/queue.dao');
var log = require('../services/log.service');
var Jqueue = require('jqueue');
function list(req, res) {
log.trace('listing queues');
queueDao.list(function (err, list) {
if (!err) {
res.send(200, list);
} else {
log.error('error listing queues', err);
res.send(500);
}
}, req.dataSource);
}
function getByName(req, res) {
queueDao.queueTableInfo(function (err, result) {
if (!err) {
if (result) {
res.send(200, result);
} else {
res.send(404, {message: 'queue ' + req.queue.getName() + ' not found'});
}
} else {
log.error('error retrieving queue', err);
res.send(500);
}
}, req.dataSource, req.queue);
}
function create(req, res) {
if (req.params && req.params.queue) {
var queueName = req.params.queue;
var ephemeral = req.body && req.body.ephemeral ? req.body.ephemeral : false;
var jqueue = new Jqueue(req.dataSource);
jqueue.use(queueName, false, ephemeral, function (err, rows, fields) {
if (err) {
res.send(500, err);
} else {
res.send(201);
}
});
}
}
function deleteByName(req, res, next) {
if (req.params && req.params.queue) {
queueDao.dropQueue(function (err) {
if (!err) {
if (req.method === 'PUT') {
next();
} else {
res.send(200);
}
} else {
if (err.message.match(/ER_BAD_TABLE_ERROR/)) {
if (req.method === 'PUT') {
next();
} else {
res.send(200);
}
} else {
log.error('error dropping queue', err);
res.send(500);
}
}
}, req.dataSource, req.params.queue);
} else {
res.send(400, {message: 'missing queue'});
}
}
module.exports = {
list: list,
getByName: getByName,
create: create,
deleteByName: deleteByName
}; | 392fb393aedf84ccbe8b4cde1c09ed438378502c | [
"JavaScript"
] | 7 | JavaScript | FPizzetti/jqueue-rest-api | 50c0bfeec6a4826dd3fac2df89bf0f884d2f2962 | a8fe22e1e94a5108559712588b115c8a0df5feeb | |
refs/heads/master | <file_sep>
def long_text_to_list():
string = open('longtext.txt').read()
return string.split()
def word_frequency_dict(wordList):
wordDict = {}
for word in wordList:
if word in wordDict:
wordDict[word] = wordDict[word] + 1
else:
wordDict[word] = 1
return wordDict
def print_250_most_common_words(wordDict):
sortedDict = sorted(wordDict.items(), key=lambda item: (item[1], item[0]))
top250 = 0
print("250 most common words and number of occurrences:")
while (top250 <= 250):
print(sortedDict.pop())
top250 += 1
print_250_most_common_words(word_frequency_dict(long_text_to_list()))
<file_sep># Guessing Game
import random
def guessing_game():
randomNumber = random.randint(1, 100)
guessedCorrectly = False
lastGuess = -1
numberOfGuesses = 0
while not guessedCorrectly:
guess = int(input("Guess a number between 1 and 100: "))
if lastGuess != guess:
numberOfGuesses += 1
lastGuess = guess
if randomNumber == guess:
print("You got it! You guessed the secret number in %d guesses." % numberOfGuesses)
guessedCorrectly = True
elif randomNumber < guess:
print("Too high!")
else:
print("Too low!")
guessing_game()
<file_sep>import calendar
def print_month_calendar():
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
print(calendar.month(year, month))
print_month_calendar()<file_sep># List Functions
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
stack = [3, 4, 5, 8, 13, 17, 35, 42]
def largestElement(listInput):
try:
return max(listInput, key=len)
except:
return max(listInput)
def reverseList(listInput):
listInput.reverse()
print(listInput)
def contains(element, inputList):
if element in inputList:
return True
return False
def oddPositionElements(listInput):
oddElements = []
index = 1
while index < len(listInput):
oddElements.append(listInput[index])
index += 2
return oddElements
def totalList(listInput):
runningTotal = []
totalInt = 0
totalString = ""
for element in listInput:
if isinstance(element, str):
totalString += element
runningTotal.append(totalString)
else:
totalInt += element
runningTotal.append(totalInt)
return runningTotal
print("Fruit list: " + fruits.__str__())
print("Integer list: " + stack.__str__())
print("\nThe largest fruit is %s." % largestElement(fruits))
print("The largest integer is %d." % largestElement(stack))
print("\nReversed fruit list: ")
reverseList(fruits)
print("Reversed integer list:")
reverseList(stack)
print("\nFruit list contains apple: %r" % contains('apple', fruits))
print("Fruit list contains bacon: %r" % contains('bacon', fruits))
print("Integer list contains 17: %r" % contains(17, stack))
print("Integer list contains 7: %r" % contains(7, stack))
print("\nOdd positioned fruits: " + oddPositionElements(fruits).__str__())
print("Odd positioned integers: " + oddPositionElements(stack).__str__())
print("\nRunning total of fruits: " + totalList(fruits).__str__())
print("Running total of integers: " + totalList(stack).__str__())<file_sep># Sum of Even Terms of Fibonacci Sequence < 4,000,000
def is_even(num):
return num % 2 == 0
def get_even_terms():
term1 = 0
term2 = 1
evens = []
while term2 <= 4000000:
sumOfTerms = term1 + term2
if is_even(term2):
evens.append(term2)
term1 = term2
term2 = sumOfTerms
return evens
def sum_of_even_terms():
sumOfEvens = 0
evens = get_even_terms()
for even in evens:
sumOfEvens += even
return sumOfEvens
# print(is_even(4)) # true
# print(is_even(3)) # false
# print(get_even_terms()) # [2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]
print("The sum of the even terms of the Fibonacci sequence whose values are less than 4000000 is %d."
% sum_of_even_terms())
<file_sep># Number of Sundays on First of Month from January 1, 1901 to December 31, 2000
from datetime import date
def number_of_sundays_on_first_of_month():
sundays = 0
for year in range(1901, 2001):
for month in range(1, 13):
if date(year, month, 1).weekday() == 6:
sundays += 1
return sundays
print("There were %d Sundays on the first of the month in the 20th century." % number_of_sundays_on_first_of_month())
<file_sep># Print even numbers that occur before 237 in sequence
def print_evens_before_237(inputList):
for int in inputList:
if int == 237:
break;
elif int % 2 == 0:
print(int)
numbers = [386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958,743, 527]
print("The even numbers in the list that occur before 237 are:")
print_evens_before_237(numbers) | ba1ac5f97480709406312b43410fa6c105ed9b76 | [
"Python"
] | 7 | Python | caraeppes/PythonLab1 | da3f20d0a7504c8368b6c04f2af59401174018bc | 962cc6a218775a878ce6860d1a44c29d6d1fff67 | |
refs/heads/master | <file_sep># nomic
Nomic Voting App
## Installation
```
sudo apt-get install mongodb
pip install flask
pip install flask-script
pip install mongoengine
pip install flask_mongoengine
```
## Running
```
python manage.py runserver
```
<file_sep>import datetime
from flask import url_for
from nomic import db
class Proposal(db.Document):
created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
created_by = db.StringField(max_length=255, required=False)
number = db.StringField(max_length=255, required=True)
votes_revealed = db.BooleanField(default=False)
archived = db.BooleanField(default=False)
votes = db.ListField(db.EmbeddedDocumentField('Vote'))
def __unicode__(self):
return self.number
def get_absolute_url(self):
return url_for('proposal', kwargs={"number": self.number})
meta = {
'allow_inheritance': True,
'indexes': ['-created_at', 'number'],
'ordering': ['-created_at']
}
class Vote(db.EmbeddedDocument):
created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
name = db.StringField(max_length=255, required=True)
vote = db.StringField(max_length=255, required=True)
hate_upon = db.StringField(max_length=255, required=False)
love = db.StringField(max_length=255, required=False)
<file_sep>from flask import Flask, redirect, request, render_template, url_for
from flask.ext.mongoengine import MongoEngine
from proxy import ReverseProxied
# from nomic.views import proposals, votes
app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {'DB': "nomic_db"}
app.wsgi_app = ReverseProxied(app.wsgi_app)
db = MongoEngine(app)
from models import Proposal, Vote
def get_sanitized_proposals():
proposals = Proposal.objects(archived=False)
for proposal in proposals:
if not proposal.votes_revealed:
for vote in proposal.votes:
vote.vote = "[hidden]"
vote.hate_upon = "[hidden]"
vote.love = "[hidden]"
return proposals
@app.route('/', methods=['GET', 'POST'])
def list():
if request.method == 'GET':
return render_template('proposals/list.html', proposals=get_sanitized_proposals())
else: # POST
proposal = Proposal(created_by=request.form['created_by'], number=request.form['number'])
proposal.save()
return render_template('proposals/list.html', proposals=get_sanitized_proposals())
@app.route('/vote/<proposal_id>', methods=['POST'])
def add_vote(proposal_id):
vote = Vote(name=request.form['name'], vote=request.form['vote'], hate_upon=request.form['hate_upon'])
proposal = Proposal.objects.get_or_404(id=proposal_id)
existing_votes = filter(lambda v: v.name.lower().strip() == vote.name.lower().strip(), proposal.votes)
if len(existing_votes) > 0:
existing_vote = existing_votes[0]
existing_vote.created_at = vote.created_at
existing_vote.vote = vote.vote
existing_vote.hate_upon = vote.hate_upon
existing_vote.love = vote.love
else:
proposal.votes.append(vote)
proposal.save()
return redirect(url_for('list'))
@app.route('/archive/<proposal_id>')
def archive(proposal_id):
proposal = Proposal.objects.get(id=proposal_id)
proposal.archived = True
proposal.save()
return redirect(url_for('list'))
@app.route('/reveal/<proposal_id>')
def reveal(proposal_id):
proposal = Proposal.objects.get(id=proposal_id)
proposal.votes_revealed = True
proposal.save()
return redirect(url_for('list'))
if __name__ == "__main__":
app.run()
| 60532e6ca6b9324c9920b0d8948cf26cbd43ee57 | [
"Markdown",
"Python"
] | 3 | Markdown | seveneightn9ne/nomic | d3582f4821e642e142cb8a4bafec937844a4c0e5 | 84208522d8f25bb6ddd337d1eecc9d9dbaa0bfdd | |
refs/heads/master | <repo_name>mcanalejas/AAD-Practica1<file_sep>/src/ejercicios5_8_JPA/Utilidades.java
package ejercicios5_8_JPA;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* Responsable de crear un objeto sesi�n (gestiona la conexi�n a BD de forma
* transparente
*
* @author Laura
*
*/
public class Utilidades {
// Factoria de sesi�n para crear objeto sesi�n a partir de XML
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Creamos una factor�a de sesiones con los datos de hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("ejercicios5_8/hibernateJPA.cfg.xml");
System.out.println("Configuracion de Hibernate Cargada");
System.out.println("Servicio de registro de Hibernate Realizado");
SessionFactory sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
} catch (Throwable ex) {
// En un caso real se registra en un log
System.err.println("Fallo la creacion de la factoria de sesiones inicial." + ex);
throw new ExceptionInInitializerError(ex);
}
}
/*
* M�todo est�tico (Fachada) para crear la factor�a de sesiones
*/
public static SessionFactory getSessionFactory() {
if (sessionFactory == null)
sessionFactory = buildSessionFactory();
return sessionFactory;
}
}
| dede7b7942802a26694ada9558b948d03ff4403d | [
"Java"
] | 1 | Java | mcanalejas/AAD-Practica1 | 69f6b8939b48bbc3f57a0f998095167381940000 | 7ce1029387693f4742c6dbc91e6b65162621592e | |
refs/heads/main | <file_sep>from wsgiref.simple_server import make_server
from datetime import datetime
import json
from dateutil.parser import parse
from pytz import timezone, all_timezones
from tzlocal import get_localzone
local_tz = str(get_localzone())
response_parts = [
'''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Time app</title>
</head>
<body>
''',
'''
</body>
</html>
'''
]
def get_ok_html(tz, time):
return '200 OK',[
response_parts[0],
'<h2>Time: </h2>', time.strftime('%Y-%m-%d %H:%M:%S'),
'<h3>Zone: </h3>', tz,
response_parts[1]
]
def get_bad_html():
return '400 BAD REQUEST', [
response_parts[0],
'<h2>400 BAD REQUEST</h2>',
response_parts[1]
]
def get_ok_json(obj):
return '200 OK', [json.dumps(obj)]
def get_bad_json():
return '400 BAD REQUEST', '{ "error": "BAD REQUEST" }'
def time_app(environ, start_response):
path = environ['PATH_INFO'][1:]
method = environ['REQUEST_METHOD']
#HTML
if not path.startswith('api') and method == 'GET':
headers = [('Content-type', 'text/html; charset=utf-8')]
try:
tz = path if path != '' else local_tz
time = datetime.now(tz= timezone(tz))
status, body = get_ok_html(tz, time)
except:
status, body = get_bad_html()
#API
elif path.startswith('api') and method == 'POST':
headers = [('Content-type', 'application/json; charset=utf-8')]
try:
length = environ['CONTENT_LENGTH']
length = 0 if not length else int(environ['CONTENT_LENGTH'] )
body = json.loads(environ['wsgi.input'].read(length).decode('utf-8') or '{}')
if path == 'api/v1/time':
tz = body['tz'] if 'tz' in body else local_tz
time = datetime.now(tz= timezone(tz))
status, body = get_ok_json({'tz': tz, 'time': time.strftime('%H:%M:%S')})
elif path == 'api/v1/date':
tz = body["tz"] if "tz" in body else local_tz
time = datetime.now(tz= timezone(tz))
status, body = get_ok_json({'tz': tz, 'date': time.strftime('%Y-%m-%d')})
elif path == 'api/v1/datediff':
tz = body['start']['tz'] if 'tz' in body['start'] else local_tz
start = timezone(tz).localize(parse(body['start']['date']))
tz = body['end']['tz'] if 'tz' in body['end'] else local_tz
end = timezone(tz).localize(parse(body['end']['date']))
diff = end - start
status, body = get_ok_json({'diff': str(diff)})
else:
status, body = get_bad_json()
except:
status, body = get_bad_json()
#Any else
else:
headers = [('Content-type', 'text/html; charset=utf-8')]
status, body = get_bad_html()
start_response(status, headers)
return [x.encode() for x in body]
if __name__ == '__main__':
# Запуск wsgi сервера
httpd = make_server('', 8080, time_app)
print("Serving on port 8080...")
httpd.serve_forever()<file_sep>import requests
import json
from tzlocal import get_localzone
url = 'http://localhost:8080/'
local_tz = str(get_localzone())
result = []
try:
response = requests.get(url)
assert response.status_code == 200
assert local_tz in response.text
except:
result.append('1')
try:
response = requests.get(url + 'UTC')
assert response.status_code == 200
assert 'UTC' in response.text
except:
result.append('2')
try:
response = requests.get(url + 'Europe/Moscow')
assert response.status_code == 200
assert 'Europe/Moscow' in response.text
except:
result.append('3')
try:
response = requests.post(url + 'api')
assert response.status_code == 400
except:
result.append('4')
try:
response = requests.post(url + 'api/adss')
assert response.status_code == 400
except:
result.append('5')
try:
response = requests.post(url + 'api/adss')
assert response.status_code == 400
except:
result.append('6')
try:
response = requests.post(url + 'api/v1')
assert response.status_code == 400
except:
result.append('7')
try:
response = requests.post(url + 'api/v1/time')
assert response.status_code == 200
except:
result.append('8')
try:
response = requests.post(url + 'api/v1/time')
assert response.status_code == 200
obj = json.loads(response.text)
assert obj['tz'] == local_tz
except:
result.append('9')
try:
response = requests.post(url + 'api/v1/time', data= json.dumps({'tz': 'UTC'}))
assert response.status_code == 200
obj = json.loads(response.text)
assert obj['tz'] == 'UTC'
except:
result.append('10')
try:
response = requests.post(url + 'api/v1/time', data= json.dumps({'tz': 'Europe/Moscow'}))
assert response.status_code == 200
obj = json.loads(response.text)
assert obj['tz'] == 'Europe/Moscow'
except:
result.append('11')
try:
response = requests.post(url + 'api/v1/time', data= json.dumps({'tz': 'UFO'}))
assert response.status_code == 400
except:
result.append('12')
try:
response = requests.post(url + 'api/v1/date', data= json.dumps({'tz': 'Europe/Moscow'}))
assert response.status_code == 200
obj = json.loads(response.text)
assert obj['tz'] == 'Europe/Moscow'
except:
result.append('13')
try:
response = requests.post(url + 'api/v1/datediff', data= json.dumps({
'start': { 'date': '3:30pm 2020-12-01' },
'end': { 'date': '12.20.2020 22:21:05', 'tz': 'UTC' }
}))
assert response.status_code == 200
obj = json.loads(response.text)
except:
result.append('14')
try:
obj = {
'begin': { 'date': '12:30pm 2020-12-01', 'timezone': local_tz },
'end': { 'date': '12.20.2021 22:21:05', 'tz': 'UTC' }
}
response = requests.post(url + 'api/v1/datediff', data= json.dumps(obj))
assert response.status_code == 400
except:
result.append('15')
if not result:
print('All tests passed successfully')
else:
for x in result:
print('Test ' + x + ' failed') | 4651ffe78c19987d86b376c61b2cfb6690835f56 | [
"Python"
] | 2 | Python | EugeneZadirachenko/eugene.zadirachenko.931801.ja.p.Lab1.python | 2b40d0f427b318e060d895597ad6d47f543c01d0 | d53308645b1561536c9bbd63e3f7fdbb7ac3d324 | |
refs/heads/master | <repo_name>joaoambrosio/WeatherStation<file_sep>/MapReduce/src/DynamoSearch.java
import java.util.HashMap;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.dynamodb.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodb.model.AttributeValue;
import com.amazonaws.services.dynamodb.model.ComparisonOperator;
import com.amazonaws.services.dynamodb.model.Condition;
import com.amazonaws.services.dynamodb.model.ScanRequest;
import com.amazonaws.services.dynamodb.model.ScanResult;
public class DynamoSearch {
static AmazonDynamoDBClient dynamoDB;
private static void init() throws Exception {
AWSCredentials credentials = new PropertiesCredentials(DynamoSearch.class.getResourceAsStream("AwsCredentials.properties"));
dynamoDB = new AmazonDynamoDBClient(credentials);
}
public static void main(String[] args) throws Exception {
long startTime = System.nanoTime();
init();
try {
String tableName = "weatherstation";
String key;
key = "2012-10-25:Lisboa";
HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
Condition condition = new Condition().withComparisonOperator(ComparisonOperator.CONTAINS.toString()).withAttributeValueList(new AttributeValue(key));
scanFilter.put("cityEvent", condition);
ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
ScanResult scanResult = dynamoDB.scan(scanRequest);
System.out.println("Key scanned: " + key + ", with content: " + scanResult);
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which means your request made it " + "to AWS, but was rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with AWS, " + "such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
long endTime = System.nanoTime();
double totalTime = ((endTime - startTime) / 1000000);
System.out.println("Total time: " + totalTime + ".");
}
}<file_sep>/MapReduce/src/S3Search.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
public class S3Search {
public static void main(String[] args) throws IOException {
long startTime = System.nanoTime();
AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(S3Search.class.getResourceAsStream("AwsCredentials.properties")));
String bucketName = "weatherstationobjects";
String key;
try {
key = "2012-10-25:Lisboa";
S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
System.out.println("Key scanned: " + key + ", with content:");
displayTextInputStream(object.getObjectContent());
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon S3, but was rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with S3, " + "such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
long endTime = System.nanoTime();
double totalTime = ((endTime - startTime) / 1000000);
System.out.println("Total time: " + totalTime + ".");
}
private static void displayTextInputStream(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while (true) {
String line = reader.readLine();
if (line == null) break;
System.out.println(" " + line);
}
System.out.println();
}
}<file_sep>/README.md
WeatherStation
==============
Weather Station for Cloud Computing project. | f8ff17e6aced9d066fce63fa4c5f7b9bf780bc26 | [
"Markdown",
"Java"
] | 3 | Java | joaoambrosio/WeatherStation | eef689d91aba8b3d6b2c0c27d2839dea319b7856 | f10837d5ec9d16e973908a36ddff6053f15d5a57 | |
refs/heads/master | <repo_name>Ernest96/Super_Divide<file_sep>/Super_Divide.c
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
unsigned short b=10000,i=0,o=0;
bool cr=0;
struct number
{
long long xn[6] ,xd[6];
long long W0[20];
float num;
}N[20];
long long Realw(unsigned short , long long * );
void substract(long long* , long long* , int* , int , unsigned short* );
void normalize(long long* , unsigned short , int* );
void convert(char *, long long *);
void afisare_1(long long *);
void menu();
void Sort(struct number *,int );
void HELP();
void Merge(struct number* ,int ,struct number* ,int nr,struct number* );
void Save();
void structurare(long long *,long long *,long long *);
int main()
{
while(1)
{
menu();
system("cls");
long long* n=(long long*)calloc(6,sizeof(long long));
char* temp1=(char*)calloc(26,sizeof(char));
char* temp2=(char*)calloc(26,sizeof(char));
long long W[20]={0} ;
int q=0;
long long xd,xn;
unsigned short last,step=1;
long long d[6]={0};
printf("\r\nIntroduceti primul numar : "); gets(temp1); convert(temp1,n);
printf("Introduceti al doilea numar : "); gets(temp2); convert(temp2,d);
for(i=1; i<6; i++ )
W[i+2]=n[i];
xd=(d[1]*b +d[2])*b+d[3];
while(step<=15)
{
xn=Realw(step+2,W);
q=xn/xd;
last=(step+9<20) ? step+9 : 20;
substract(W,d,&q,step+2,&last);
normalize(W,step+2,&q);
step=step+1;
}
free(n);
afisare_1(W);
structurare(n,d,W);
printf("\r\n Pentru a te intoarce la menu - tasteaza orice buton...");
getch();
}
}
long long Realw(unsigned short j , long long * W )
{
long long c=0,s;
if(j+2<=18)c=W[j+2];
s=( ((W[j-1]*b+W[j])*b+W[j+1])*b + c );
return s;
}
void substract(long long* W , long long* d, int* q , int ka , unsigned short*kb )
{
long long * W0;
for(i=ka;i<*kb;i++)
W[i]=W[i]- *q * d[i-ka+1];
}
void normalize(long long* W , unsigned short ka , int* q )
{
W[ka]=W[ka]+W[ka-1]*b;
W[ka-1]=*q;
}
void convert(char *temp, long long * num)
{
int temp3,j;
char temp2[20],v=0,x=1;
j=1;i=0;
while(temp[i]!='.' && temp[i]!=',' && i<strlen(temp) )
{
temp2[v++]=temp[i++];
}
temp3=atoi(temp2);
num[x++]=(long long)temp3; v=0;
strcpy(temp2,"0000");
for(i=i+1;i<strlen(temp);i++,j++)
{
temp2[v++]=temp[i];
if(j%4==0)
{
temp3=atoi(temp2);
v=0;
num[x++]=(long long)temp3;
strcpy(temp2,"0000");
}
} j--;
if(j%4!=0 && v!=0)
{
temp3=atoi(temp2);
if (temp3<10 && v==3) temp3=temp3;
else if (temp3<10 && v==2) temp3=temp3*100;
else if (temp3<10) temp3=temp3*1000;
else if(temp3<100 && v==3 ) temp3=temp3;
else if(temp3<100) temp3=temp3*100;
else if(temp3<1000) temp3=temp3;
num[x++]=(long long)temp3;
}
}
void structurare(long long *n, long long *d, long long * W)
{
char temp[8];
for(i=0;i<20;i++)
N[o].W0[i]=W[i];
for(i=0;i<6;i++)
{ N[o].xn[i]=n[i]; N[o].xd[i]=d[i]; }
o++;
}
void afisare_1(long long *W)
{
printf("\r\n Rezultatul este : ");
printf("%d.",W[2]);
for(i=3;i<17;i++)
{
if(W[i]<10 && W[i]>0) printf("%d%d%d",000);
else if (W[i]<100) printf("%d%d",00);
else if (W[i]<1000) printf("%d",0);
printf("%d",W[i]);
}
printf("\r\n\r\n Pentru continuare , tasteaza un buton ...\r\n");
getch();
cr=1;
}
void afisare_2()
{
int j,k;
system("cls");
for(j=0;j<o;j++)
{
printf("\r\n Impartirea nr %d",j+1);
printf("\r\n ");
for(k=1;k<6;k++)
{
printf("%d",N[j].xn[k]);
if(k==1) printf(".");
}
printf(" / ");
for(k=1;k<6;k++)
{
printf("%d",N[j].xd[k]);
if(k==1) printf(".");
}
afisare_1(N[j].W0);
printf("\r\n");
}
}
void menu()
{
system("cls");
char choice;
while(1)
{
system("cls");
printf("\r\n\t\t\t\t Impartirea numerelor cu precizie maxima : ");
printf("\r\n\r\n\t\t\t\t\t\t MENIU PRINCIPAL\r\n\r\n");
printf("\r\nAlege tasta : \r\n");
printf("\r\n\t\t\t\t1-HELP\r\n");
printf("\r\n\t\t\t\t2-Salvare in fisier \r\n");
printf("\r\n\t\t\t\t3-Sortarea numerelor dupa partea intreaga \r\n");
printf("\r\n\t\t\t\t4-Afisarea numerelor\r\n");
printf("\r\n\t\t\t\tENTER - executia programului\r\n");
printf("\r\n\t\t\t\t9-Iesire\r\n");
repeat: choice=getch();
switch(choice)
{
case '1' : HELP(); break;
case '2' : Save(); break;
case '3' : Sort(N,o); break;
case '4' : afisare_2(); break;
case '9' : exit(0); break;
case 13 : return; break;
default : printf("\r\n Alegere gresita !"); goto repeat; break;
}
}
}
void HELP()
{
system("cls");
printf("\r\n Pentru operatii se folosesc 2 numere reale. ");
printf("\r\n Programul are o precizie de 56 de cifre dupa virgula ");
printf("\r\n Rezultatele pot fi salvate in fisier la alegerea utilizatorului ");
printf("\r\n\r\n\r\n Programul este scris in limbajul C");
printf("\r\n\r\n Autor: <NAME> (FCIM UTM TI-153) ");
printf("\r\n\r\n Algoritmul impartirii : Algoritmul lui D.Smith");
printf("\r\n\r\n Algoritmul sortarilor Merge Sort (Divide et Impera) ");
printf("\r\n\r\n Biblioteci folosite : <stdio.h> <stdlib.h> <string.h> <conio.h> ");
printf("\r\n\r\n Versiunea : 1.0\r\n");
printf("\r\n Pentru a te intoarce la menu - tasteaza orice buton...");
getch();
return;
}
void Save()
{
int j=0,k;
FILE * fp;
fp=fopen("Teza.txt","w");
system("cls");
system("cls");
if(cr==0) printf("\r\n Nu sunt date pentru salvare\r\n");
else
for(j=0;j<o;j++)
{
fprintf(fp,"\r\n Impartirea nr %d",j+1);
fprintf(fp,"\r\n ");
for(k=1;k<6;k++)
{
fprintf(fp,"%d",N[j].xn[k]);
if(k==1) fprintf(fp,".");
}
fprintf(fp," / ");
for(k=1;k<6;k++)
{
fprintf(fp,"%d",N[j].xd[k]);
if(k==1) fprintf(fp,".");
}
fprintf(fp,"\r\n Rezultatul este : ");
fprintf(fp,"%d.",N[j].W0[2]);
for(k=3;k<17;k++)
{
if(N[j].W0[k]<10 && N[j].W0[k]>0) fprintf(fp,"%d%d%d",000);
else if (N[j].W0[k]<100) fprintf(fp,"%d%d",00);
else if (N[j].W0[k]<1000) fprintf(fp,"%d",0);
fprintf(fp,"%d",N[j].W0[k]);
}
printf("\r\n Salvare cu succes !");
fprintf(fp,"\r\n");
}
fclose (fp);
printf("\r\n Pentru a te intoarce la menu - tasteaza orice buton...");
getch();
}
void Sort(struct number *N,int o)
{
int mid;
mid=o/2;
struct number left[mid];
struct number right[o-mid];
if(o<2) return;
for(i=0;i<mid;i++)
left[i]=N[i];
for(i=0;i<o;i++)
right[i-mid]=N[i];
Sort(left,mid);
Sort(right,o-mid);
Merge(left,mid,right,o-mid,N);
}
void Merge(struct number L[],int nl,struct number* R,int nr,struct number* N )
{
i=0;
int j=0;
int k=0;
while(i<nl && j<nr)
{
if(L[i].W0[2]<=R[j].W0[2])
N[k]=L[i++];
else
N[k]=R[j++];
k++;
}
while (i<nl)
N[k++]=L[i++];
while(j<nr)
N[k++]=R[j++];
}
<file_sep>/README.md
# Super_Divide
Acest program permite efectuarea impartirea a 2 numere cu o precizie foarte mare (circa 50 de cifre dupa virgula)
Rezultatul poate fi salvat in fisier.
Este posibila sortarea rezultatelor dupa partea intreaga.
Algoritmul dividerii : <NAME>
| 9289f5fb1cf83c174df1d79167e120cddffaffa4 | [
"Markdown",
"C"
] | 2 | C | Ernest96/Super_Divide | f5c1f752699857e4d60e1c40375c14e6803a72d7 | b6d4143e6f29ee625a28513141a696bb0edb3847 | |
refs/heads/master | <file_sep>//
// ViewController.swift
// CurrencyConversionExample
//
// Created by <NAME> on 7/7/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var displayLabel: UILabel!
@IBOutlet weak var entryField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func convertButton(_ sender: UIButton) {
let numericValue = Int(entryField.text!)!
let currencyConversion = convertIntToCurrencyAsString(intValue: numericValue)
displayLabel.text = currencyConversion
}
func convertIntToCurrencyAsString(intValue: Int) -> String {
var stringVersion: String
let cFormatter = NumberFormatter()
cFormatter.usesGroupingSeparator = true
cFormatter.numberStyle = .currency
if let currencyString = cFormatter.string(from: NSNumber(value: intValue)) {
stringVersion = currencyString
} else {
stringVersion = "Invalid Message"
}
return stringVersion
}
}
<file_sep># Swift to Int to Currency Converter Example
This is an example of converting an entered string to an integer and then currency in response to a Reddit question.
You can find the question on [Reddit here](https://www.reddit.com/r/iOSProgramming/comments/c5ttl6/new_to_swift_trying_to_make_a_simple_app_to_count/)
Enter a value in the text field and hit the convert button. This calls a function that will perform the conversation and return a string to be used for display.
| 4a062803fe421e52275cf7b9d0eb4337eda957bd | [
"Swift",
"Markdown"
] | 2 | Swift | GrfxGuru/swift-int-to-currency-example | 9cb508301cce6057af55c82d7794ba7168c9eee4 | bb9b141fd4f9c093394ed4dd86e119dde7b54d81 | |
refs/heads/master | <repo_name>unlocker-sy/deep_learning_basic<file_sep>/study/tensorflow/dl_for_everyone_season2/README.md
# 모두를 위한 딥러닝 시즌 2
모두를 위한 딥러닝 시즌2 의 내용을 개인적으로 필요한 부분만 요약, 이해한대로 정리한 자료
https://deeplearningzerotoall.github.io/season2/lec_tensorflow.html
# Youtube
- 시즌1
https://hunkim.github.io/ml/
- 시즌2
https://www.youtube.com/playlist?list=PLQ28Nx3M4Jrguyuwg4xe9d9t2XE639e5C
# Slide
- 시즌1
https://hunkim.github.io/ml/
- 시즌2
https://drive.google.com/drive/folders/1twBsdLkI2P15J0DgYs77_E_EVKt7Ghav
# Code
https://github.com/deeplearningzerotoall/TensorFlow<file_sep>/study/tensorflow/dl_for_everyone_season2/01_basic_concept_deeplearning.md
# ML lec01 기본적인 Machine Learning 의 용어와 개념 설명
머신러닝, 딥러닝의 목표는 룰을 찾아서 예측을 할수 있는 시스템을 만드는 것이 목표다.
이 목표를 찾기 위해서는 학습을 시켜서 룰을 찾는데 데이터는 라벨링된 데이터를 사용한다.
라벨링된 데이터를 사용하기 때문에 Supervised Learning이라고 한다.
라벨링되지 않은 데이터를 사용하는 것을 Unsupervised learning이라고 한다.
여기서는 주로 Supervised learning에 대해 살펴보게 될 것이다.
예를 들어서 Supervised learning을 구현할 수 있는 종류가 뭐가 있는지 보자.
얼만큼 시간을 공부했느냐에 따라 Pass, 점수(score)를 예측하고자 한다 (regression)
얼만큼 시간을 공부했느냐에 따라 Pass, Non-Pass를 예측하고자 한다 (Binary classification)
얼만큼 시간을 공부했느냐에 따라 등급 (A, B, C, ~ ,F)를 예측하고자 한다 (multi-label classification)
linear regression을 어떻게 모델을 만들고 어떻게 학습을 시키는지..<file_sep>/docker/run_container.sh
#!/bin/sh
docker run -p 8888:8888 -it --volume="$PWD/../study:/workdir/study" deeplearning_keras:imx-1
<file_sep>/study/tensorflow/dl_for_everyone_season2/10_nn_relu_xavier_overfitting_dropout.md
# Relu
이진 분류 문제를 해결하기 위해 Sigmoid를 activation function로 사용했고
다중 분류 문제를 위해 Softmax를 사용했다.
그런데 이전의 모델과는 다르게 neural network를 사용할 경우, back proagation을 반복하면서 gradient값이 점점 작아지는 문제가 있다.
relu에 대해 살펴보기 전에 먼저 Sigmoid의 문제점에 대해 먼저 살펴보자.
## Sigmoid의 문제점
Sigmoid의 경우 back propogation을 반복하면서 gradient 값이 점점 작아져 사라지는 문제가 있다. (vanishing gradient)
이를 해결하기 위한 activation function으로 relu라는 것이 있다.
아래 그림을 보면 시그모이드 그래프 중 빨간 부분에서 gradient값이 0에 가까워지고 있다
<img src="./img/sigmoid_vanishing_gradient.png" width="80%">
## Relu
x가 음수일 경우에는 f(x)는 0이 되고 0보다 클 경우에는 이전에 보았던 wx+b 와 같은 형태이고 문제가 되었던 sigmoid의 gradient가 작아지는 부분이 없는 것을 볼 수 있다.
<img src="./img/relu.png" width="80%">
## Weight
아래의 우측 그래프를 보면 local minima, global minima가 있다.
Neural network를 학습시키면서 back propagation을 반복하면서 local minima에 빠지지 않고 global minima를 찾을 수 있어야 하는데, 이를 위해 적절한 weight의 초기값을 설정하는 것이 중요하다.
(아래의 w,c 그래프에서 적절한 시작점에서 경사하강법을 수행하면 올바른 global minimum을 찾을 수 있으므로)
이렇게 weight를 초기화시키기 위한 방법 중의 xavier initialization라는 것이 있고 이를 통해 weight를 적절한 값으로 초기화시킬 수 있다.
tensorflow에서는 weight를 initialize하기 위한 방법으로 RandomNormal(), glory_uniform(), he_uniform()함수를 제공해준다. 이후의 예제코드를 통해 확인해보자
<img src="./img/xavier_initialization.png" width="100%">
## Overfitting, Drop out
보통 모델을 학습 및 평가할 때 data set을 train set, validation set, test set으로 나누어서 학습 및 평가를 한다.
예측을 위해 모델을 학습시킬 때, train set에 과도하게 학습이 될 경우, train set에만 최적화된 예측모델이 되어서 새로운 데이터(test set)에서는 정확도가 낮아지게 된다.
그래서 train set에서는 학습만 시키고 validation set을 통해 모델을 평가해보고 이를 토대로 다시 모델을 튜닝하고 완성된 모델을 test set에서 평가를 하게 된다..
즉, train set에서 학습을 시키고 validation set을 통해 평가한 뒤, 모델을 다시 튜닝을 하는데 이때 dropout이라는 것을 사용한다.
그 후 test set에서 평가를 하는 방식으로 대부분 구현을 한다고 한다.
아래 그림을 보면 첫번째 그림은 학습이 너무 적게 되어서 모델(직선? 그래프)이 데이터에 적게 fitting된 것을 볼 수 있다. 이를 under fitting이라고 한다.
두번째 그림을 보면, 모델(직선)이 적절하게 학습되었지만 몇몇 개의 데이터들이 그래프의 경계를 벗어나 있는 것을 볼 수 있다. drop out이란 이런 몇몇 개의 데이터를 dropout시키기 위한 방법으로 보인다. tensorflow에서는 랜덤하게 dropout하는 방식을 사용한다.
세번째 그림을 보면 모델이 데이터에 과도하게 학습된 것을 볼 수 있다. 이 경우, train data에서는 좋은 예측을 하지만, 새로운 데이터에서는 좋은 성능을 내지 못하는 문제가 있다.
<img src="./img/overfitting_dropout.png" width="100%">
아래 그림을 보면 고양이 사진을 인식, 분류하기 위한 모델이 있고 overfitting 문제를 해결하기 위해 회색 부분으로 표시된 부분을 제거하게 된다.
이렇게 dropout되고 난 후 regularization이 되었다고 한다.
<img src="./img/cat_dropout1.png" width="100%">
<img src="./img/cat_dropout2.png" width="100%">
## Imlementation
- dropout을 사용하기 전
~~~ python
class create_model(tf.keras.Model):
def __init__(self, label_dim):
super(create_model, self).__init()
weight_init = tf.keras.initializers.glorot_uniform()
self.model = tf.keras.Sequential()
self.model.add(flatten())# [N, 28, 28, 1] -> [N, 784]
for i in range(2):
# [N, 784] -> [N, 256] -> [N, 256]
self.model.add(dense(256, weight_init))
self.model.add(relu())
self.model.add(dense(label_dim, weight_init))
def call(self, x, training=None, mask=None):
x = self.model(x)
return x
~~~
- dropout을 사용할 경우
~~~python
class create_model(tf.keras.Model):
def __init__(self, label_dim):
super(create_model, self).__init__()
weight_init = tf.keras.initializers.glorot_uniform()
self.model = tf.keras.Sequential()
self.model.add(flatten())# [N, 28, 28, 1] -> [N, 784]
for i in range(2):
# [N, 784] -> [N, 256] -> [N, 256]
self.model.add(dense(256, weight_init))
self.model.add(relu())
self.model.add(dropout(rate=0.5))
self.model.add(dense(label_dim, weight_init)) #[N, 256] -> [N, 10]
def call(self, x, training=None, mask=None):
x = self.model(x)
return x
~~~
<file_sep>/study/tensorflow/dl_for_everyone/2_2_cost_function_and_gradiant_descent.md
~~~
이 포스트는 홍콩과기대 김성훈 교수님 강의내용을 개인적으로 이해한대로 정리한 내용입니다.
개인적인 호기심으로? 스터디한 내용을 정리한 포스팅입니다.
틀린 부분이 있을 수 있으니 감안하시길 .. 아래 사이트에 강의 내용이 있습니다.
~~~
[모두를 위한 딥러닝 강의](http://hunkim.github.io/ml/)
[모두를 위한 딥러닝 깃허브](https://github.com/hunkim/DeepLearningZeroToAll)
# 개요
앞에서 살펴본 비용함수라는 것은 가설이 실제 데이터와 얼마나 차이나는지 확인하는 방법이다.
가설을 변화시켜가면서 비용함수의 값을 최소화 시키게 되면, 실제 데이터를 통해서 다음 데이터는 어떤 값을 갖게 될지 예측을 할 수 있다.
최적의 비용함수를 찾기 위한 방법 중 하나가 기울기와 절편을 변화시켜 가면서 찾는 방법인데, 이를 경사하강법(gradiant descent)이라고 한다.
그런데 텐서플로에서는 미분 등의 식을 통해 경사하강법을 직접 구현하지 않아도 텐서플로 패키지 내의 함수를 통해서 구현할 수 있다.
텐서플로의 함수를 사용하지 않고 직접 구현하는 방법은 다음에 확인해보기로 하고 우선 텐서플로에서 제공해주는 경사하강법의 사용 예를 살펴보자..
# 텐서플로 구현
대부분의 구현 방법은 아래 그림과 같다. 1: graph(연산, node, 들을 선언및 초기화)를 build하고, 2. 실제 축적되어있는 data(통계치등)를 넣어서 실행을 시킨다. 3.실행의 결과의 값들을 update한다..
<left><img src="image/tensorflow_mechanics.png" width="400" height="300"></left>
# W, b 값 부여(weight, bias) 및 가설
Variable이라는 것은 프로그래밍 언어에서 사용하는 변수와는 조금 다른 텐서플로에서 사용하는 변수 비슷한 개념인데,
tensorflow가 학습하면서 변경을 시킬 수 있는, 훈련시킬수 있는 Variable이라고 한다.
그리고 random_normal함수는 random함수를 의미하고 아래 코드에서는 1차원의 random함수를 통해 w, b값을 선언했다
hypothesis라는 node를 선언하고 wx+b로 node를 초기화했다
~~~python
W = tf.Variable(tf.random_normal([1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
#Our hypothesis XW+b
hypothesis = x_train * W + b
~~~
# 비용함수
앞에서 봤던 것과 같이 비용함수는 (H(x)-y)^2 가된다. reduce_mean은 평균을 구하는 함수라고 한다.(i를 1~m까지 증가시킨 값을 1/m)
~~~python
#cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - y_train))
~~~
# 최적의 비용함수 찾기
최적의 비용함수를 찾기 위한 방법 중의 하나가 경사하강법(gradiant descent)라는 것인데, tensorflow에서는 아래와 같이 경사하강법을 쉽게 사용할 수 있는 벙법을 제공해주고 있다.
코드를 보면 경사하강법을 사용하는 optimizer를 선언하고 optimizer의 minimize함수를 호출하면서 cost(비용함수)를 최소화시키고 이를 train이라는 노드로 초기화 한다.
~~~python
#Minimize
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train = optimizer.minimize(cost)
~~~
노드라는 것은 앞에서 봤던 트리 형태의 동그란 부분, 즉 연산을 의미한다고 보면 될 것 같다.
여기까지가 그래프를 building하는 과정이다.
그리고 그래프를 동작시켜서 값을 찾는 과정은 다음과 같다.
~~~python
sess.run(train)
~~~
전체 예제 코드는 다음과 같다..
~~~python
#Lab 2 Linear Regression
import tensorflow as tf
tf.set_random_seed(777) # for reproducibility
#X and Y data
x_train = [1, 2, 3]
y_train = [1, 2, 3]
#Try to find values for W and b to compute y_data = x_data * W + b
#We know that W should be 1 and b should be 0
#But let TensorFlow figure it out
W = tf.Variable(tf.random_normal([1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
#Our hypothesis XW+b
hypothesis = x_train * W + b
#cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - y_train))
#Minimize
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train = optimizer.minimize(cost)
#Launch the graph in a session.
sess = tf.Session()
#Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())
#Fit the line
for step in range(2001):
sess.run(train)
if step % 20 == 0:
print(step, sess.run(cost), sess.run(W), sess.run(b))
#Learns best fit W:[ 1.], b:[ 0.]
'''
0 2.82329 [ 2.12867713] [-0.85235667]
20 0.190351 [ 1.53392804] [-1.05059612]
40 0.151357 [ 1.45725465] [-1.02391243]
...
1920 1.77484e-05 [ 1.00489295] [-0.01112291]
1940 1.61197e-05 [ 1.00466311] [-0.01060018]
1960 1.46397e-05 [ 1.004444] [-0.01010205]
1980 1.32962e-05 [ 1.00423515] [-0.00962736]
2000 1.20761e-05 [ 1.00403607] [-0.00917497]
'''
~~~
<file_sep>/study/keras/5_deep_learning_for_computer_vision/5_deep_learning_for_computer_vision.md
# 5.1. Introduction to convnet
convnet(convolutional neural networks)의 전체 구조는 다음 그림과 같은 구조로 이루어져 있다
고양이가 한 물체를 보았을 때 뇌의 한부분만 반응하는 것에 착안한 모델이라고 한다.
아직은 잘 모르지만, 그림을 보면 conv, relu는 한 쌍으로 구성되어 있는 것을 볼 수 있다.
아래 그림은 "자동차"그림을 "자동차"로 인식하기 위한 CNN인데, Convolution으로는 각각 다른 자동차이미지들로 구성되어있는 것을 볼수 있다.
<left><img src="img/CNN.png" width="400" height="300"></left>
### CONV, RELU, POOL에 관한 간단한 용어 및 개념 정리
<left><img src="img/ConvReluFilter.png" width="400" height="300"></left>
CONV 는 한 이미지에서의 필터를 적용해서 얻은 데이터를 의미한다.
예를 들어 32x32x3(width, height, depth)의 이미지에서 stride를 옮겨가면서 filter를 적용한 값을 의미한다.
RELU라는 것은 함수와 비슷한 개념인데, Wx+b와 같은 식을 적용하는 함수와 같은 것으로 보인다.
실제 코드에서는 **activation='relu'** 와 같은 형태로 인자를 넘기고 있다.
(참고할만한 내용)
neural network의 layer는 보통 입력값을 가지고 있는데 이것을 vecotr라고 부르고 weight matrix를 곱한다..
https://stackoverflow.com/questions/43504248/what-does-relu-stand-for-in-tf-nn-relu
POOL 은 sampling, resizing을 의미하고, 여러가지 방법이 있지만 max pooling이라는 방법을 주로 쓴다
#### 다시 책으로 돌아와서
convnet은 입력 텐서의 형태 (image_height, image_width, image_channels)(배치 차원을 포함하지 않음)를 취한다.
~~~python
from keras import layers
from keras import models
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
~~~
~~~
>>> model.summary()
________________________________________________________________
Layer (type) Output Shape Param #
================================================================
conv2d_1 (Conv2D) (None, 26, 26, 32) 320
________________________________________________________________
maxpooling2d_1 (MaxPooling2D) (None, 13, 13, 32) 0
________________________________________________________________
conv2d_2 (Conv2D) (None, 11, 11, 64) 18496
________________________________________________________________
maxpooling2d_2 (MaxPooling2D) (None, 5, 5, 64) 0
________________________________________________________________
conv2d_3 (Conv2D) (None, 3, 3, 64) 36928
================================================================
Total params: 55,744
Trainable params: 55,744
Non-trainable params: 0
~~~
앞에서 본것과 같이 Conv와 pooling layer가 반복되고 있는 것을 볼 수 있다.
tensorflow에서는 필터의 크기를 사용자가 직접 계산하고 필터의 갯수도 직접 지정하는 것으로 보이는데
keras의 경우는 필터의 크기를 알아서 계산해 주는 것으로 보인다.
이 코드에 대해 이해하기 위해서는 Conv2D와 MaxPooling2D레이어가 하는 일에 대해 알아 보는 것이 필요하다.(다음 절에서)
이 단계가 끝나고 conv2d, maxpooling를 통해 최종적으로 나온 값은 연결 분류기 네트워크 ( Dense레이어 스택)에 공급한다.
텐서플로에서의 Fully Connected Layer와 같은 역할을 하는 것으로 보인다.
~~~python
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
~~~
이 단계를 거치고 나서는 모델을 훈련시키는 단계가 있다
이에 대한 코드는 5.4.절을 참고
##### 요약하면 세 단계를 통해서 이미지를 인식할 수 있다.
1. Convolution, max pooling 연산을 통해서 출력값의 생성
2. 1번의 출력값을 이용해서 네트워크에 공급(5.3.절 참고)
3. 이렇게 구성한 convnet을 훈련시키는 단계
### 5.1.1. 컨벌루션 연산
조밀하게 연결된 레이어와 컨볼 루션 레이어의 근본적인 차이점은 다음과 같습니다. Dense레이어는 입력 특징 공간에서 전체 패턴을 학습합니다 (예 : MNIST 숫자, 모든 픽셀을 포함하는 패턴).
반면에 컨볼 루션 레이어는 **로컬 패턴**을 학습합니다 ( 그림 5.1 참조 ) : 이미지의 경우 입력의 작은 2D 창에서 발견되는 패턴. 이전 예에서이 창은 모두 **3 × 3**이었습니다.
###### 그림 5.1.
<left><img src="img/LocalPattern.jpg" width="100" height="100"></left>
그들은 패턴의 공간 계급을 배울 수있다 ( 그림 5.2 참조 ). 첫 번째 컨볼 루션 계층은 가장자리와 같은 작은 로컬 패턴을 학습하고, 두 번째 컨볼루션 계층은 첫 번째 계층의 기능으로 만들어진 더 큰 패턴을 학습하는 등의 작업을 수행합니다. 이것은 convnets이 점점 더 복잡하고 추상적인 시각적 개념을 효율적으로 학습하도록 합니다 (시각적 세계는 근본적으로 공간적으로 계층적이기 때문에)
###### 그림 5.2.
<left><img src="img/ConvolutionLayer_CatExample.jpg" width="300" height="300"></left>
**[이미지의 depth]**
컨볼 루션 은 두 개의 공간 축 ( 높이 와 너비 )과 깊이 축 ( 채널 축 이라고도 함)이있는 피쳐 맵 이라는 3D 텐서를 통해 작동합니다 . RGB 이미지의 경우 깊이 축의 크기는 3입니다. 이미지에 빨강, 녹색 및 파랑의 세 가지 색상 채널이 있기 때문입니다. 흑백 사진의 경우 MNIST 숫자와 마찬가지로 깊이는 1 (회색 레벨)입니다.
**[Conv2D() 함수]**
~~~python
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
~~~
~~지금까지 본 내용들은 위 코드 한줄을 위한 개념 설명이었다..ㅜㅜ~~ 이 코드의 의미는 다음과 같다.
MNIST 예제에서 첫 번째 컨볼 루션 계층은 크기의 기능 맵을 가져 와서 크기 (28, 28, 1)의 기능 맵을 출력한다. 입력에 대해 32 개의 필터를 계산합니다.((26, 26, 32)가 된다) 즉, input_shape의 인자 값이 맵의 크기가 되고, 첫 인자인 32가 필터의 크기가 되는 것으로 보인다
입력에서 추출한 패치의 크기 - 일반적으로 3 × 3 또는 5 × 5이고, 이 예에서는 3 × 3이며 일반적인 선택이라고 한다.
출력 피처의 깊이 맵 - 컨볼 루션에 의해 계산 된 필터의 수(크기)이며 이 예제는 깊이가 32에서 시작하여 깊이가 64로 끝난다.
이 깊이를 어떤 기준으로 설정하는지에 대해서는 5.3. 5.4.절에서 설명이 될것 같다. Keras Conv2D레이어에서 이러한 매개 변수는 레이어에 전달 된 첫 번째 인수 Conv2D(output_depth, (window_height, window_width))이다.
***Convolution Layer의 동작과정을 그림으로 보면 다음과 같다.***
<left><img src="img/convnet_flow_diagram.jpg" width="300" height="300"></left>
컨볼 루션은 3 x 3 또는 5 x 5 크기의 창(필터, ~~여기서는 필터와 창을 혼용해서 사용하는 것 같다~~)을 3D 입력 맵 위로 슬라이딩하며 (모양 (window_height, window_width, input_depth)) 의 3D 패치를 추출하게 된다.
필터는 stride(간격)값에 따라 이동하는 간격이 달라지며, 필터의 갯수도 이값에 의해 다음 입력의 width, height의 값이 증가 또는 감소를 하게 될 것이다.
(필터의 동작방법은 다음 그림을 참고)
***즉, 요약하면*** output depth는 전달인자로 결정할 수 있고 layer를 한번 거칠때마다 필터의 크기(width, height, depth)는 계속 감소하게 될 것이다.
이렇게 생성된 output모델은 width x height x output depth의 크기를 가지게 된다.
##### 필터(창)의 슬라이딩
<left><img src="img/filter_window_sliding.jpg" width="300" height="300"></left>
##### stride
예제에서의 conv2D후의 2번째 layer의 크기를 계산해보면..
stride(간격)은 1이고, 간격 1씩을 이동하면 (28-3)/1 + 1 = 26 크기의 창이 2번째 layer의 입력이 된다.
계산 방법은 (입력 width - 필터 width)/stride + 1 이다.
# 5.2. Training a convnet from scratch on a small datasheet
# 3. Using a pre-trained convnet
# 4. Visualizing what convnet learn
<file_sep>/docker/Dockerfile
FROM ubuntu:16.04
RUN sed -i s/archive.ubuntu.com/ftp.daumkakao.com/g /etc/apt/sources.list
RUN apt-get clean
RUN apt-get update
RUN apt-get install -y make
RUN apt-get install -y git unzip
RUN apt-get install -y wget
RUN apt-get install -y build-essential
# install python3.6, BeutifulSoup4 package
# for use "add-apt-repository command"
RUN apt-get install -y software-properties-common
RUN add-apt-repository ppa:jonathonf/python-3.6
# RUN add-apt-repository ppa:deadsnakes/ppa
RUN apt-get update
# RUN apt-get install -y python3.6
RUN apt-get install -y python3.6-dev
RUN apt-get install -y python3-pip
RUN pip3 install --upgrade pip
RUN pip3 install requests
RUN apt-get install -y python3-bs4
# Install BLAS Library to boost Tensor-Operation
RUN apt-get install -y build-essential \
cmake git unzip pkg-config libopenblas-dev liblapack-dev
# Install HDF5(대용량 수치 데이터파일을 효율적인 이진포맷으로 저장해준다.)
RUN apt-get install -y libhdf5-serial-dev python-h5py
# for jupyter, tensorflow, keras package
# RUN pip3 install tensorflow scikit-learn jupyter matplotlib pandas keras seaborn plotly
RUN pip3 install tensorflow scikit-learn jupyter matplotlib pandas keras seaborn
# # Install numpy, scipy, matplotlib
RUN pip3 install numpy scipy pyyaml
RUN pip3 uninstall -y tornado
RUN pip3 install tornado==5.1.1
# RUN pip3 install tornado
RUN pip3 uninstall -y pillow
RUN pip3 install pillow
# Set environment variables
# UBUNTU korean locale
RUN apt-get install -y locales
ENV LANGUAGE=ko_KR.UTF-8
ENV LANG=ko_KR.UTF-8
RUN locale-gen ko_KR.UTF-8
ENV LC_ALL ko_KR.UTF-8
# make shared directory with HOST and set working directory
WORKDIR /workdir
# Set up our notebook config.
COPY jupyter_notebook_config.py /root/.jupyter/
COPY run_jupyter.sh /workdir
EXPOSE 8888
CMD ["/bin/bash"]
<file_sep>/study/tensorflow/dl_for_everyone/3_1_multi_variable_linear_regression.md
~~~
이 포스트는 홍콩과기대 김성훈 교수님 강의내용을 개인적으로 이해한대로 정리한 내용입니다.
개인적인 호기심으로? 스터디한 내용을 정리한 포스팅입니다.
틀린 부분이 있을 수 있으니 감안하시길 .. 아래 사이트에 강의 내용이 있습니다.
~~~
[모두를 위한 딥러닝 강의](http://hunkim.github.io/ml/)
[모두를 위한 딥러닝 깃허브](https://github.com/hunkim/DeepLearningZeroToAll)
# remind..
H(x)란(가설)..
어떻게 예측할 것인지를 의미..
(경사하강법을 통해서 cost function(비용함수)를 최소화하는 최적의 H(x)를 찾고, 이 H(x)를 통해서 다음에는 어떤 값을 가질 것인지를 예측할 수 있다.)
cost function(비용함수)이란..
실제 통계 등의 데이터와 H(x)값이 얼마나 차이나는지를 의미
gradiant descent algorithm(경사하강법)이란..
x축이 w이고 y축이 cost function인 그래프를 생각해보자.
결국 w값을 조정해가면서 cost function의 최소값을 찾는 방법이다.
이렇게 찾는 방법이 기울기(w)를 하강시켜가면서 0이 되는 지점을 찾는 것이기 때문에 경사하강법이라 부르는 듯..
경사하강법을 사용하기 위한 전제?가 있는데.. cost function이 convection function(아래로 볼록한 함수)의 형태이어야한다는 것..
<left><img src="image/3/3_linear_regression_remind.png" width="400" height="300"></left>
# 입력이 여러개일 경우는..
아래 그림 처럼 입력데이터 셋이 여러개(quiz1, quiz2, midterm) 일 경우에는 어떻게 Cost function을 계산할 것이며, cost function을 최소가 H(x)는 어떻게 찾을 것인가..
<left><img src="image/3/3_multi_variable_linear_regression_example.png" width="400" height="300"></left>
우선 H(x)는 아래와 같은 형태일 것이다.
<left><img src="image/3/3_multi_variable_Hypothesis.png" width="400" height="300"></left>
cost function은 아래와 같은 형태일 것이다.
<left><img src="image/3/3_multi_variable_cost_function.png" width="400" height="300"></left>
그런데, 행렬을 사용하면 H(x)를 입력값의 추가 및 수정이 편한 형태로 바꿀 수 있다.
<left><img src="image/3/3_hypothesis_using_matrix.png" width="400" height="300"></left>
이제 w값을 변경해가며 cost function이 최소가 되는 값을 찾으면 된다.
이는 경사하강법을 사용해서 찾으면 된다..
<file_sep>/README.md
# Docker build
- cd docker
- docker build -t deeplearning_keras:imx-1 .
# Run Docker container
- docker run -p 8888:8888 -it --volume="$PWD/..:/workdir/deeplearning_keras_study" -v ${PWD}/build:/workdir/build deeplearning_keras:imx-1
- or ./run_container.sh
# Docker 컨테이너, 이미지 삭제
- Docker 컨테이너 모두 삭제
docker rm $(docker ps -a -q)
- Docker 이미지 모두 삭제
docker rmi $(docker images -q)
- 특정 이미지만 삭제
(image 리스트 확인)
docker images
docker rmi 이미지id
# execute jupyter notebook in Docker Container
- /workdir/run_jupyter.sh --allow-root &
# 특이점
- ubuntu에서 docker build시에 plotly 패키지를 설치하면서 error가 발생해서 repository를 통해서 설치하도록 수정했다.<file_sep>/study/tensorflow/dl_for_everyone_season2/12_recurrent_neural_network.md
# Recurrent Neural Network
RNN(Recurrent Neural Network)는 연속적인 데이터를 예측하기 위한 모델이다.
또, RNN에는 몇가지 단점이 있어서 이를 보완하기 위한 모델로 LSTM과 GRU와 같은 모델이 있다.
LSTM과 GRU에 대해서는 다음 장에서 살펴보기로 하고 RNN을 집중적으로 살펴보자.
여기서는 단어를 예로 들어서 RNN의 동작 원리에 대해 심플하게 설명하고 있다.
# dataset
deeplearning은 이미 가지고 있는 데이터를 학습해서 실제 데이터에서 다음 값을 예측하거나 분류를 하는 것이 목표이다.
학습을 위해서 사용하는 데이터는 데이터에 대한 라벨(정답)이 있는 데이터셋을 사용한다.
여기서는 주로 단어예측과 관련된 내용을 설명하는데, 단어에 대한 라벨링(이진 값으로 변환)을 '원 핫 인코딩'을 하여 만든다.
원핫인코딩을 하는 방법도 두가지로 나눌 수 있다. 단어 단위로 하거나 문자 단위로 하는 것이다.
또, 원핫인코딩 대신 단어임베딩이라는 것도 많이 사용되는데, 단어임베딩은 메모리를 더 적게 쓰면서 더 빨리 값을 가져올 수 있다는 장점이 있다.
각 단어에 대한 값이 이진으로 코딩되어 있는 대신, 해시알고리즘을 사용해서 값을 더 빨리 찾을 수 있기 때문이다.
이런 방법에 대해서는 다음 챕터에서 더 자세히 살펴보고 여기서는 원핫인코딩을 사용해서 문자 중심의 예측을 위한 rnn을 더 집중적으로 살펴보자.
# RNN이란..
아래 그림에서 볼 수 있듯이 현재의 입력에 대한 출력이 다음 입력으로 사용되는 것을 볼 수 있다.
오른쪽의 그림을 보자.
X입력을 받고 이 데이터에 대한 상태인 h가 다음 모델의 입력으로 입력되는 구조를 보여주고 있다.
<img src="./img/rnn1.png" width="80%">
## h에 대해 살펴보면..
입력을 받을 때마다 상태에 해당하는 h가 갱신되는데, 이를 수식으로 살펴보면 아래 그림과 같다.
h는 새롭게 갱신될 new state를 의미한다.
fw라는 함수에 이전 h(state)와 현재 입력값이 입력되어서 현재의 h가 갱신되고 있다.
fw란 weight값을 가진 어떤 함수를 의미하는데, 이 함수는 다음 그림에서 더 자세히 살펴보자.
<img src="./img/rnn2.png" width="80%">
## fw함수가 뭔지 더 자세히 보면..
아래 수식을 보면 fw함수는 이전의 h(state)에 weight를 곱한 값과 x에 weight를 곱한 값을 activation함수(tanh함수)에 넣는 것을 볼 수 있다.
tanh함수는 activation함수로 -1에서 1사이의 값을 가지고 기존의 sigmoid에 비해 vanishing gradient문제가 해결된 함수다.
결국, 이 fw함수로 현재의 h함수를 업데이트되는 것이다.
<img src="./img/rnn_fw.png" width="80%">
## hidden layer
h는 상태를 의미하지만 rnn모델에서 hidden layer를 의미하기도 하는데,
아래 그림들을 보면 매 step마다 입력에 대해 h(hidden layer)가 업데이트되는 것을 볼 수 있다.
<img src="./img/rnn_hidden_layer0.png" width="50%">
<img src="./img/rnn_hidden_layer1.png" width="50%">
<img src="./img/rnn_hidden_layer2.png" width="50%">
<img src="./img/rnn_hidden_layer3.png" width="50%">
<img src="./img/rnn_hidden_layer4.png" width="50%">
## output layer
output layer에서는 hidden layer를 통해 나온 현재의 h값(state)에 weight값을 곱해서 outlayer의 값이 출력되게 된다.
이 슬라이드 상에는 나오지 않았지만, 각 단어의 확률값을 출력하기 위해서 softmax를 activation function으로 사용한 것으로 보인다.
<img src="./img/rnn_hidden_output_layer.png" width="80%">
## rnn 모델의 종류
<img src="./img/rnn_models1.png" width="50%">
<img src="./img/rnn_models2.png" width="50%">
<img src="./img/rnn_models3.png" width="50%">
<img src="./img/rnn_models4.png" width="50%">
<img src="./img/rnn_models5.png" width="50%">
## advanced rnn models
<img src="./img/rnn_advanced_models.png" width="50%">
<file_sep>/study/tensorflow/dl_for_everyone_season2/11_convolution_neural_network.md
# Convolutional Neural Network
[참고]
https://hunkim.github.io/ml/lec11.pdf
https://drive.google.com/drive/folders/1twBsdLkI2P15J0DgYs77_E_EVKt7Ghav
image 분류에 가장 많이 사용되는 분류 방법인데, 뇌가 이미지를 인식하는 방법에서 힌트를 얻었다고 한다.
아래 그림을 보면, 그림의 한 부분에 대해 인식하는 뇌의 부분이 모두 다른 것을 보여주고 있는데, Convolution neural network도 이와 비슷한 원리로 구현된다.
<img src="./img/cnn_concept_from_brain.jpg" width="50%">
CNN은 기본적으로 Convolution, Pooling, Fully Connected layer로 구성되어 있다.
<img src="./img/cnn_overview.jpg" width="50%">
아래 그림의 Convolution, Pooling layer는 특정한 특징을 추출하는 layer이고.(feature extraction)
Fully connected layer는 분류를 하는 layer이다. (사진이 강아지인지 고양이인지, classification)
<img src="./img/convolution_neural_network.jpg"/>
## Convolution layer
--------
- convolution연산과 filter의 갯수
filter로 한번의 convolution 연산을 하면 통과하면 하나의 숫자가 나온다.
filter를 stride간격으로 input map전체를 순회하고 나면 out map이 나오게 된다.
filter의 갯수에 따라 out map의 갯수가 결정되게 되고, 이는 다음 layer의 input map의 갯수가 된다.
그림으로 살펴보자.
<img src="./img/filter.jpg" width="50%">
stride가 1이라고 가정했을 때, filter의 갯수에 따라 출력맵의 갯수가 결정되는 것을 볼 수 있다.(필터의 갯수와 출력맵의 갯수는 동일)
<img src="./img/convolution_layer_one_filter.jpg" width=200>
<img src="./img/convolution_layer_two_filter.jpg" width=270>
<img src="./img/convolution_layer_six_filter.jpg" width=350>
<img src="./img/convolution_layer_filters.jpg" width=500>
- convolution연산 (filter computing)
convolution 연산의 계산은 아래와 같이 이미지의 픽셀 값과 필터의 각 원소들의 합으로 계산된다.
<img src="./img/filter_computing.jpg" float:left/>
- convolution연산과 stride, padding
stride란 filter가 움직이는 간격의 크기를 의미한다.
stride 값과 filter, input map의 크기에 따라 생성되는 출력 맵의 크기가 달라지게 되는데,
출력되는 맵의 크기는 (width - filter width)/stride + 1이다.
filter를 거치면서 out map의 크기가 점점 작아지게 되는데, 이로 인해 data의 손실이 일어날 수 있다.
이를 방지하기 위해 padding을 사용하는데, 아래 그림처럼 filter의 크기에 따라 padding을 달리하면 outmap의 크기가
input map의 크기와 같아지는 것을 볼 수 있다.
<img src="./img/padding_stride.png" width=500/>
## Activation
각 Conv layer를 거친뒤 다음 입력으로 입력되기 전에 Activation function을 거치는데 이 때, Relu를 사용한다.
아래 그림처럼 Relu activation function으로 인해 음수 값들은 0이되고 양수 값들은 그대로 유지된다.
<img src="./img/layer_activation.jpg" width=500/>
## Pooling Layer
-----
Convolution layuer에서는 filter를 stride간격으로 convolution연산을 해서 output맵을 만들어낸다.
아래의 그림을 보면 convolution연산을 거치면서 점점 이미지가 옅어지는 것을 볼 수 있다.
Convolution 연산을 거치고 나온 맵에서 특징을 추출을 해야 하는데, 이때 사용하는 것이 pooling이라는 것이다.
<img src="./img/cnn_overview.jpg" width="50%">
pooling연산은 '값들을 모은다', 'sampling한다', 'resize한다' 와 유사한 의미로 볼 수 있다.
pooling연산을 하는 방법으로 두가지가 있는데, 맵의 평균값을 구해서 이 맵의 전체적인 특징을 뽑아내는 것과(average pooling)
맵의 가장 큰 특징을 뽑아내기 위한 방법(max pooling)이 있다.
<img src="./img/max_pooling1.jpg" width=200>
<img src="./img/max_pooling2.jpg" width=270>
max pooling의 실제 연산은 아래 그림처럼 filter가 stride간격으로 이동하면서 최대값을 구해서 out map을 구성한다.
아래 그림에서는 2x2 filter를 2칸 간격으로 이동하면서 filter와 겹치는 영역에서의 최대값을 뽑아서 out map을 구성하고 있다.
<img src="./img/max_pooling_operation.jpg" width=350>
## Fully Connected Layer
-----
Fully Connected layer에서는 Conv와 Max layer들을 통해서 나온 out map을 1차원으로 쭉 펼친다.
그리고 Softmax activation function을 통해 분류(classification)를 하게 된다.
아래 그림을 보면 FC Layer를 통해서 cat/dog로 분류되는 것을 볼 수 있다.
<img src="./img/fully_connected_layer.jpg" width="50%">
## 그 외의 참고사항
- 아래 링크에서 이미지의 특징들이 어떻게 출력되는지 과정을 살펴볼 수 있다.
http://cs.stanford.edu/people/karpathy/convnetjs/demo/cifar10.html<file_sep>/study/tensorflow/dl_for_everyone/2_1_Linear Regression Concept.md
# Linear Regression의 개념
아래와 같은 data가 있다고 해보자.
<left><img src="image/regression_data.png" width="400" height="300"></left>
그럼 이 data에 대한 가설(H(x))은 다음과 같을 것이다.
<left><img src="image/hypothesis.png" width="400" height="300"></left>
이 데이터에 대한 그래프와 식은 다음과 같을 것이다.
그리고 다른 데이터들에 대한 식은 노란색과 빨간색 선들이라고 해보자.
<left><img src="image/regression_data_equation.png" width="400" height="300"></left>
이 때 어떤 식이 더 좋은지에 대해 판단할 수 있어야 한다..
이때 사용하는 것이 비용함수라는 것이다.
<left><img src="image/regression_data_which hypothesis is better.png" width="400" height="300"></left>
비용함수라는 것은 가설과 실제 데이터의 차가 얼마나 되는지를 의미하는 것이다.
<left><img src="image/cost_function.png" width="400" height="300"></left>
이 그래프의 전체 비용함수를 구하면 다음과 같을 것이다.
<left><img src="image/cost_function_sum.png" width="400" height="300"></left>
결국, 주어지는 data(앞에서의 표)들에 대한 좋은 가설을 얻기 위해서는 기울기와 절편을 움직이면서 비용함수에 대한 값이 적게 나오는 가설을 선택하면 될 것이다..
<left><img src="image/regressin_goal.png" width="400" height="300"></left>
<file_sep>/study/tensorflow/dl_for_everyone_season2/04_multi_variable_linear_regression.md
# multi variable linear regression
전의 예에서는 변수가 하나뿐이었다 (공부한 시간)
이번에는 변수가 여러개라고 생각 해보자 (quiz1, quiz2, midterm)
행렬을 사용하면 표현식이 간단해진다. 프로그램 상에서 xw로 표현이 가능하다.
x의 컬럼과 w의 열의 수가 같아야 하기 때문에 XW로 표현을 한다.(텐서플로에서도 xw로 표현함)
입력은 (데이터의 갯수,데이터 안의 변수 갯수)
## 간단한 형태의 w1, w2, w3을 계산하는 코드
~~~python
# data and label
x1 = [ 73., 93., 89., 96., 73.]
x2 = [ 80., 88., 91., 98., 66.]
x3 = [ 75., 93., 90., 100., 70.]
Y = [152., 185., 180., 196., 142.]
# random weights
w1 = tf.Variable(tf.random_normal([1]))
w2 = tf.Variable(tf.random_normal([1]))
w3 = tf.Variable(tf.random_normal([1]))
b = tf.Variable(tf.random_normal([1]))
learning_rate = 0.000001
for i in range(1000+1):
# tf.GradientTape() to record the gradient of the cost function
with tf.GradientTape() as tape:
hypothesis = w1 * x1 + w2 * x2 + w3 * x3 + b
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# calculates the gradients of the cost
w1_grad, w2_grad, w3_grad, b_grad = tape.gradient(cost, [w1, w2, w3, b])
# update w1,w2,w3 and b
w1.assign_sub(learning_rate * w1_grad)
w2.assign_sub(learning_rate * w2_grad)
w3.assign_sub(learning_rate * w3_grad)
b.assign_sub(learning_rate * b_grad)
if i % 50 == 0:
print("{:5} | {:12.4f}".format(i, cost.numpy()))
~~~
## 위에서 본 각각의 w1, w2, w3을 계산하는 코드의 문제점
각각의 w1, w2, w3을 계산하는 코드는 x1,x2,x3,y의 값을 직접 입력해야 하는 번거로움이 있다.
또, 코드의 크기가 커지고, 데이터의 크기도 커지면서 유지보수의 어려움이 생기는 문제가 있다.
~~~python
for i in range(1000+1):
with tf.GradientTape() as tape:
hypothesis = w1 * x1 + w2 * x2 + w3 * x3 + b
#COST함수를 구한다.
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# tape에 기록된 하나의 값을 꺼내서 cost함수에 대한 W1,W2,W3,B의 각각 개별의 미분값을 가져온다.
w1_grad, w2_grad, w3_grad, b_grad = tape.gradient(cost, [w1, w2, w3, b])
# W1값을 업데이트한다.
w1.assign_sub(learning_rate * w1_grad)
w2.assign_sub(learning_rate * w2_grad)
w3.assign_sub(learning_rate * w3_grad)
if i % 50 == 0:
print("{:5} | {:12.4f}".format(i, cost.numpy()))
~~~
## 행렬(numpy)를 이용해서 x1,x2,x3,y 값을 정의
numpy slicing
~~~python
data = np.array([
#X1, X2, X3, y
[73., 80., 75., 152.],
[93., 88., 93., 185.],
[89., 91., 90., 180.],
[96., 98., 100., 196.],
[73., 66., 70., 142.]
], dtype=np.float32)
# slice data
X = data[:, : -1]
y = data[:, [-1]]
~~~
## numpy를 사용하면 아래처럼 더 깔끔하게 코드를 구현이 가능하다
~~~python
data = np.array([
# X1, X2, X3, y
[ 73., 80., 75., 152. ],
[ 93., 88., 93., 185. ],
[ 89., 91., 90., 180. ],
[ 96., 98., 100., 196. ],
[ 73., 66., 70., 142. ]
], dtype=np.float32)
# slice data
X = data[:, :-1]
y = data[:, [-1]]
W = tf.Variable(tf.random_normal([3, 1]))
b = tf.Variable(tf.random_normal([1]))
learning_rate = 0.000001
# hypothesis, prediction function
def predict(X):
return tf.matmul(X, W) + b
print("epoch | cost")
n_epochs = 2000
for i in range(n_epochs+1):
# tf.GradientTape() to record the gradient of the cost function
with tf.GradientTape() as tape:
cost = tf.reduce_mean((tf.square(predict(X) - y)))
# calculates the gradients of the loss
W_grad, b_grad = tape.gradient(cost, [W, b])
# updates parameters (W and b)
W.assign_sub(learning_rate * W_grad)
b.assign_sub(learning_rate * b_grad)
if i % 100 == 0:
print("{:5} | {:10.4f}".format(i, cost.numpy()))
~~~
<file_sep>/study/tensorflow/dl_for_everyone/README.md
# 홍콩 과기대 김성훈 교수님이 강의하신 내용을 개인적으로 공부하면서 정리한 내용입니다.
# 아래 링크를 참조
https://hunkim.github.io/ml
<file_sep>/study/tensorflow/dl_for_everyone/1_machine_learning_basic.md
# 1. 머신러닝의 개념과 용어
AI(Artificial Intelligence), 프로그램..
프로그램이란 input에 대한 out을 출력하는 것이 프로그램이다..
AI는 정해진 input에 대한 out을 예측할 수 있어야 한다.
input에 대한 out을 예측할 수 있도록, 수 많은 데이터를 학습해서 예측할 수 있도록 해주는 것이 머신러닝이다.
프로그램인데, 이것을 개발자가 어떻게 할지를 정하는 것이 아니라, 프로그램이 데이터를 통해 학습해서
스스로 배우는 영역을 머신러닝이라고 한다.
그리고 이런 머신러닝의 여러 방법 중 하나가 신경망 이론을 이용한 딥러닝이라는 것이다.
<left><img src="image/machine_learning_deep_learning.png" width="400" height="300"></left>
# 텐서플로 기본 용어
https://www.tensorflow.org/guide/graphs
https://docs.google.com/presentation/d/137IlT2N3AYcclqxNuc8j9RDrIeHiYkSZ5JPg_vg9Jqk/edit#slide=id.g1d115b0ec5_0_32
노드는 수학적인 연산을 의미하며 아래 그림의 동그란 것들이 노드에 해당한다.
엣지는 간선을 의미하는데 데이터 어레이를 의미한다.. 쉽게 말해 데이터 셋을 의미하는 듯하다.
<left><img src="image/tensors_flowing.gif"></left>
# node, session이란..
node는 앞에서의 설명과 같이 operation을 의미한다... 특정한 상수가 될수 도 있는 것으로 보인다.
특정한 상수 대신 실행 중에 입력을 받고 싶으면 placeholder라는 것을 사용한다고 한다.
session 이란 위에서 노드들을 감싸고 있는 네모 박스들과 같은 역할을 의미하는 것으로 보인다.
실행 중에도 데이터를 입력받아서 어떤 값일지 예측할 수 있도록 해주는 노드와 간선들로 이루어진 모델인 듯 하다.
<left><img src="image/tensorflow_mechanics.png" width="400" height="300"></left>
~~~python
# node(operation)
hello = tf.constant("hello tensorflow")
# start session
sess = tf.Session()
# run op and get result
print(sess.run(hello))
~~~
아래 예제에서는 node1, node2, node3모두 node이다.
node1, node2는 상수 노드이고, node3은 더하는 연산의 노드가 된다.
~~~python
node1 = tf.constant(3.0, tf.float32)
node2 = tf.constant(4.0, tf.float32)
node3 = tf.add(node1, node2)
~~~
# place holder
adder_node에 session을 run시킬 때 feed_dict로 a와 b의 값을 넣어주고 있다..
여기에 들어가는 값들은 엑셀파일에 정의되어있는 수치일 수도 있고 특정 기간 동안 센서 등을 통해 수집된 데이터일 수도 있을 것이다.
어쨌든 중요한 것은 실행 중에 입력값을 넣어 줄 수 있다는 것인듯..
(feed_dict, 이름 잘지은 듯 하다. 먹이로 주는 데이터?)
~~~python
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = a+b
print(sess.run(adder_node, feed_dict = {a:3, b: 4.5}))
print(sess.run(adder_node, feed_dict = {a: [1,3], b: [2,4]}))
#7.5
#[3. 7.]
~~~
<left><img src="image/tensorflow_mechanics2.png" width="400" height="300"></left>
<file_sep>/study/tensorflow/dl_for_everyone_season2/06_softmax_classifier_cross_entropy.md
# Softmax function
Softmax function은 다중 분류를 하기 위한 함수로 H(x)를 확률 값으로 표현해준다.
아래 그림에서 볼 수 있듯이 각각의 입력을 확률로 바꿔주고 있다.
<img src="./img/softmax_function.png" width="80%">
## Cost function
Softmax의 Costfunction으로는 cross entropy를 사용한다.
<img src="./img/softmax_cost_function.png" width="80%">
## Implementation
### cost function: cross entropy
<img src="./img/softmax_cross_entropy_with_logits.png" width="80%">
### H(x), cost function
<img src="./img/softmax_hypothesis_cost_function.png" width="80%">
### gradient function, accuracy
<img src="./img/gradient_function_accuracy.png" width="80%">
## Training !!!!
<img src="./img/softmax_training.png" width="80%">
<file_sep>/study/tensorflow/dl_for_everyone_season2/05_logistic_regression.md
# Logistic regression
## Logistic Regression이란?(logistic vs linear)
logistic regression은 선형적인 값에 대한 예측을 하기위한 모델인 Linear Regression과 달리
분류(classification)을 하기 위한 것이다.
- Linear regression
아래 그림의 우측을 보면 linear regression의 경우 곡선, 직선을 따라서 데이터들이 표현되어 있다.
이 곡선,직선의 방정식?그래프를 모델이 학습하게 된다. 학습을 하는 원리에 대해서는 이전 챕터 1,2 참조하면 됨.(cost, w, b, learning rate)
- Logistic regression
이름처럼 선형적인 것이 아니라 논리적인 것이다. 아래 좌측의 그림처럼 네모와 세모를 분류하기 위한 모델이다.
네모와 세모 중간에는 곡선이 하나 있는데 이 곡선을 기준으로 네모인지 세모인지 판단할 수 있게 된다.
마찬가지로 이 곡선도 학습할 수 있는데, 어떻게 학습하는지에 대해 살펴보자.
- 분류의 문제의 경우 여기서는 이진분류(binary classification)만을 다루지만 다음챕터에서 multinomial classification을 통해 T/F만이 아닌 다양한 라벨로 분류하는 방법을 살펴보게 될 것이다.
<img src="./img/logistic_vs_linear.png" width="80%">
## Hypothesis
### 두 가지 경우로 나눌 수 있다.
점들을 그룹들로 나누는 모델, 그래프에서 값이 일정 수치 이상일 경우 True/False(Pass/Fail)을 예측할 수 있는 모델로 나눌 수 있다.
----
- 점들을 그룹으로 나누는 모델
위의 그림처럼 네모와 세모를 경계짓는 곡선들의 경우 Binary Regression을 통해 True/False 를 판단할 수 있다.
이 경우, 두 그룹 간의 직선(또는 곡선)이 Hypothesis가 되는데,
이는 이전 챕터에서 배웠던 것과 같이 가설(Hypothesis)과 실제 데이터(y) 간의 거리를 구하는 cost 함수를 사용해서 cost를 최소화되는 곡선을 찾고, 이 결과로 분류가 가능하다.
<img src="./img/hypothesis_representation1.png" width="80%">
<img src="./img/logistic_regression_cost_function.png" width="80%">
- 일정 수치 이상일 경우 True/False를 판단하는 모델
예를 들어 y = x+b의 직선이 있고 이 직선은 공부시간(x)에 대한 시험성적(y)에 대한 직선이라고 해보자.
시험 성적이 50이하일 경우, Fail, 50이상일 경우 Pass라고 하면, pass, fail을 표현하는 그래프는 아래와 같이 계단 모양이 될 것이다. 아래 그래프는 가설을 Sigmoid함수의 입력으로 주면 아래와 같은 그래프 형태가 된다.
<img src="./img/hypothesis_representation2.png" width="80%">
<img src="./img/logistic_regression_cost_function2.png" width="80%">
시험성적 뿐 아니라, 혈당 수치에 대한 당뇨 확률? 이건 너무 당연한 비유겠지만.. 또는 한달 평균 운동 시간에 대한 비만 확률? 같은 경우에도 사용할 수 있지 않을까..
## sigmoid function
슬라이드로 살펴보자..
<img src="./img/sigmoid_function.png" width="80%">
## Softmax classification
Activation function으로 Sigmoid 대신 Softmax를 사용하면 0또는 1로 분류하는 이진분류가 아닌 다수의 라벨로 분류할 수 있다.
softmax는 입력을 확률값으로 표현해주는 함수로 이에 대한 자세한 내용은 다음장(6_softmax_classifier.md)에서 보자
<img src="./img/logistic_regression_softmax.png" width="80%">
<file_sep>/study/tensorflow/dl_for_everyone_season2/02_linear_regression.md
# [Tensorflow] Lec-02 ~ 03 Linear Regression
- Regression
- Linear Regression
- Hypothesis
- Which hypothesis is better?
- Cost, Cost function
- Goal: Minimize cost
## Regression
회귀, 모든 데이터들은 평균으로 회귀하려는 속성을 갖는다. 통계학쪽에서 유명한 말인듯하다..뭔소리야..
## 선형회귀
데이터를 가장 잘 대변하는 직선의 방정식을 찾는 것
## Hypothesis
데이터를 표현하는 직선 방정식
H(x) = Wx+b
## Whichi Hypothes is better
실제 데이터와 가설과의 차이, cost를 최소화된 가설..
코스트의 합이 최소인 직선을 찾는다.
## cost, cost function
가설에서 실제데이터를 뺀 값을 에러라고 하고
cost function은 에러의 제곱을 평균값을 cost function이라고 한다.
<img src="./img/Hypothesis_Cost_function.png" width="50%">
## Goal: Minimize cost
# Simple Linear Regression 개념
## Build hypothesis and cost
- H(x) = Wx + b
- 예제 코드 상에서 간단한 형태의 코드를 보기 위해 W, b의 값은 초기 값으로 임의의 값을 지정한다.
- 실제로는 보통 random값을 부여한다.
- reduce_mean(): 평균값 구하는 함수, 차원이 하나 줄어들면서 mean을 구한다는 의미로 reduce가 앞에 붙어있다.
~~~python
v = [1., 2., 3., 4.]
tf.reduce_mean(v) #2.5
~~~
- 비용함수
~~~python
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
~~~
-----
## Gradient descent
- 경사를 내려가면서 cost가 최소가 되는 W, b를 찾는 알고리즘.
-----
### W, b 값 구하기
- tf.GradientTape
(아래 코드 참고)
with 구문안의 블록안의 변수들의 정보를 tape에 기록하고
tape에 기록된 변수들의 정보(w,b)를 이후에 tape.gradient()함수를 통해 경사도를 구한다.
tape.gradient()함수는 cost함수에 대해 변수들(w,b)에 대한 개별 미분값(기울기)을 구해서 tuple을 반환한다.
learning rate값은 W_grad, b_grad 값을 얼만큼 반영할 것인지를 결정한다.
아래의 코드가 한 걸음이라고 보면 됨, W와 b가 한번 업데이트 된 것이다.
~~~python
with tf.GradientTape() as tape:
hypothesis = W * x_data + b
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
W_grad, b_grad = tape.gradient(cost, [W, b])
# W, b 값 업데이트: W -= learning_rate * W_grad
W.assign_sub(learning_rate * W_grad)
b.assign_sub(learning_rate * b_grad)
~~~
# [Tensorflow] Lab-02 Simple Linear Regression
구현 예를 보자.
위에서 살펴본 개념들에 대한 내용이 중복되지만 중요한 개념이니 한번 더 반복해서 보자.
-----
## Build hypothesis and cost
- H(x) = Wx + b
- 예제 코드 상에서는 간단한 형태의 코드를 보기 위해 W, b의 값은 초기 값으로 임의의 값을 지정한다.
- 실제로는 보통 random값을 부여한다.
- reduce_mean(): 평균값 구하는 함수, 차원이 하나 줄어들면서 mean을 구한다는 의미로 reduce가 앞에 붙어있다.
~~~python
v = [1., 2., 3., 4.]
tf.reduce_mean(v) #2.5
~~~
- 비용함수
~~~python
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
~~~
-----
## Gradient descent
- 경사를 내려가면서 cost가 최소가 되는 W, b를 찾는 알고리즘.
-----
### W, b 값 구하기
- tf.GradientTape
(아래 코드 참고)
with 구문안의 블록안의 변수들의 정보를 tape에 기록하고
tape에 기록된 변수들의 정보(w,b)를 이후에 tape.gradient()함수를 통해 경사도를 구한다.
tape.gradient()함수는 cost함수에 대해 변수들(w,b)에 대한 개별 미분값(기울기)을 구해서 tuple을 반환한다.
learning rate값은 W_grad, b_grad 값을 얼만큼 반영할 것인지를 결정한다.
아래의 코드가 한 걸음이라고 보면 됨, W와 b가 한번 업데이트 된 것이다.
~~~python
with tf.GradientTape() as tape:
hypothesis = W * x_data + b
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
W_grad, b_grad = tape.gradient(cost, [W, b])
# W, b 값 업데이트: W -= learning_rate * W_grad
W.assign_sub(learning_rate * W_grad)
b.assign_sub(learning_rate * b_grad)
~~~
-----
### cost는 어떻게 줄일까?
How to minimize cost(Gradient Descent)
<img src="./img/Hypothesis_Cost_function.png" width="50%">
- Error : H(x) - y
- cost : (H(x)i - yi)의 제곱의 평균값
- Gradient Descent: cost 함수의 최소값을 찾는 알고리즘으로 Gradient Descent알고리즘을 사용한다.
최적화?.. 이득을 최대화하거나 손실을 최소화한다 -> gradient descent알고리즘은 손실을 최소화한다.
W1, W2, W3.. 등 변수가 여러개 있을 경우에도 손실을 최소화시킬 수 있는 알고리즘이다.
- Gradient Descent 알고리즘은 어떻게 동작하는가?
- 최초의 추정을 통해 W, b 값을 초기화한다.(0,0 또는 random값 등 최초의 초기화된 값)
cost가 최소가 될 수 있도록 지속적으로(매 스텝마다) W,b값을 조금씩 바꾼다.
- W, b 값을 지속적으로 업데이트할 때, Gradient값을 구해서 cost값이 최소화되는 방향으로 업데이트한다.
- 위의 두 과정을 반복한다.
- 최소값에 도달했다고 판단될때까지..
- 아래 그림을 참고..
<img src="./img/cost_function_grad_w_b_learning_rate.png" width="50%">
- 위 그림의 수식에서처럼 W값에 기울기*x값 *learningrate값을 빼서 이동하는 과정이 Gradient descent가 된다.
- local minimum, convex function
<img src="./img/convex_local_minima.png" width="50%">
위 그림 처럼 주변 값들에 비해 cost값이 작은 값을 local minimum이라고 한다.
Local minimum값이 여러개 존재하기 때문에 gradient descent 알고리즘을 사용할 수 없다.
cost function이 아래 그래프와 같이 local minimum과 global minimum이 일치할 때, gradient descent 알고리즘을 사용할 수 있다.
그래서 local minima에 빠지지 않기 위해서는 적절한 W가 적절한 시작점에서부터 경사하강법을 수행할 수 있도록 하는 것이 필요한데,
추후, 이를 위해 weight initialize를 하는데 이 내용은 10장의 nn을 보면서 보도록 하자.(xavier)
<img src="./img/convection_function.jpeg" width="50%">
- | c74c5efab46ea3d5d021c83a156e84e2da99a1fa | [
"Markdown",
"Dockerfile",
"Shell"
] | 18 | Markdown | unlocker-sy/deep_learning_basic | d4e243a7606ed443bf274abad8975c6fe850e26c | 52d163dbdf36f2ab149446a7c50ba72f454baeec | |
refs/heads/master | <repo_name>lucasmartinsribeiro/Site-da-oficina<file_sep>/index.js
const express = require("express") //eu vou fazer o pedido do express, ele vai voltar e ficar nessa variavel
const app = express()
app.get('/', (req, res) => res.send('Hello Word!'))
app.listen(3000)<file_sep>/README.md
# Site-oficina-mecanica
Durante o curso de Web Designer tive que desenvolver um Web Site, então desenvolvi um site de oficina mecânica de automóveis, pegando como referência a oficina da minha família.




 | ce8032787173cb88c4a7979d305d6aa4891ed945 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | lucasmartinsribeiro/Site-da-oficina | f491421b9c8f3c2eb3984d8703e05f1540bf381c | 11dcf3f9d20865e56067c90497aac6e35de4ad2a | |
refs/heads/master | <file_sep><?php
namespace core\mybase;
use core\Application;
//视图基类,显示数据
class View
{
public $view_dir;//视图模板路径
//定义一个数组,用来存储数据
public $data = array();//视图数据
//打开视图方法
public function display($view_name=null){
//include_once "application/home/views/index.html";
//视图名称默认为方法名称
$view_name=isset($view_name)?$view_name:Application::$action;
include_once $this->view_dir.$view_name.".html";
}
//写一个数据填充方法,放到定义好的数组里面去
public function assign($name,$value){
//关联数组
$this->data[$name] = $value;
}
}<file_sep><?php
//入口文件
//1.注册自动加载方法
require "core/MyLoad.class.php";
\core\Myload::registerAutoLoad();
//3.加载配置文件和常亮
require "configs/config.php";
require "configs/constants.php";
//2.启动核心运行类(前端处理器)
\core\Application::run();
<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/11
* Time: 9:25
*/
namespace application\admin\models;
use core\mybase\Model;
class SubscribeModel extends Model
{
public function list($args=null){
$sql="SELECT * FROM subscribe";
return $this->query($sql,$args);
}
public function count(){
$sql="SELECT COUNT(1) AS total FROM subscribe";
$result=$this->query($sql,null);
return $result[0]['total'];
}
}<file_sep><?php
namespace core\mybase;
use core\Application;
use core\MySession;
//前台权限验证控制器类
class HomeGroupController extends Controller
{
//定义不需要验证的方法
private $pass=array('register','<PASSWORD>user','login');
public function __construct()
{
//先调用父类的构造,调用父类的初始化视图的方法,加载视图
parent::__construct();
//1.session初始化
$this->initSession();
//2.权限验证,登录验证
$this->checkLogin();
}
//1.封装session初始化,便于扩展
private function initSession(){
MySession::startSeesion();
}
//登录验证
private function checkLogin(){
//确定需要验证的方法
if (in_array(Application::$action,$this->pass)){//不需要验证的方法
//如果在数组里,则不处理
}else{//不在则需要验证的方法
//判断是否保持会话
//复选框的值只要登录后,不管有没有选中,都会保存在会话里面。这里拿其他的值id或者name都可以
if (isset($_SESSION['remember'])){
//说明已经登录不处理
}else{
//否则未登录,跳转到登录页面
header("location:index.php?g=home&c=login&a=index");
}
}
}
//操作成功
public function success($msg,$url){
echo "<h1>(#^.^#)</h1>";
echo $msg."<br>";
header("refresh:2,url=index.php".$url);
}
//操作失败
public function fail($msg,$url){
echo "<h1>o(╥﹏╥)o</h1>";
echo $msg."<br>";
header("refresh:2,url=index.php".$url);
}
}<file_sep><?php
namespace core;
class Myload
{
//定义静态自动加载函数
public static function myAutoLoad($className){
//完成由命名空间构成的类路径信息的类文件的加载
//例如:Application\Admin\Controller\AdminController
//问题:include等加载函数使用的是正斜杠路径,需要进行转换为:Application/Admin/Controller/AdminController.".class.php"
$path = str_replace("\\","/",$className);
$filePath = $path.".class.php";
if (file_exists($filePath)){
include_once $filePath;
}else{
die('无法加载文件:'.$filePath);
}
}
//注册自动加载的函数
public static function registerAutoLoad(){
spl_autoload_register("self::myAutoLoad");
}
}<file_sep><?php
namespace application\home\controllers;
use core\mybase\Controller;
class LoginController extends Controller
{
//打开登录页面方法
public function index()
{
$this->display();
}
//打开注册页面方法
public function signup(){
$this->display();
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/11
* Time: 9:28
*/
namespace application\admin\controllers;
use application\admin\models\SubscribeModel;
use core\mybase\Controller;
class SubscribeController extends Controller
{
public function list(){
$sm=new SubscribeModel();
$result=$sm->list($agrs=null);
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
}<file_sep><?php
namespace core;
//启动session类
class MySession
{
//启动session
public static function startSeesion(){
if (!isset($_SESSION)){
session_start();
}
}
//销毁session
public static function destorySession(){
//清空session的值
session_unset();
//清空客户端的cookie
if (isset($_COOKIE[session_name()])){
setcookie(session_name(),null,time()-1,"/");
}
//销毁session
session_destroy();
}
//session添加数据
public static function setSession($name,$value){
$_SESSION[$name] = $value;
}
//session获取数据
public static function getSession($name){
if (isset($_SESSION[$name])){
return $_SESSION[$name];
}else{
return null;
}
}
//延长会话保持时间
//setcookie函数的第四个参数为cookie路径,用来指定cookie被发送到服务器的哪一个目录路径下,其中"/"指的是站点根目录
public static function extendSession($time=1*60*60){
setcookie(session_name(),session_id(),time()+$time,"/");
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/6
* Time: 10:11
*/
namespace application\admin\controllers;
use core\mybase\Controller;
class LoginController extends Controller
{
public function index()
{
$this->display();
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/6/28
* Time: 14:38
*/
namespace core\mybase;
//定义Model类的属性和构造函数。
//Model基类中调用PDO使用全限定类名:\PDO
class Model
{
private $dsn = "mysql:dbname=education;host=localhost:3306";
private $username = "root";
private $password = "123";
private $option = array(\PDO::ATTR_PERSISTENT=>true,\PDO::ATTR_ORACLE_NULLS=>true,\PDO::ERRMODE_EXCEPTION=>true);
private $pdo;//pdo对象
//构造函数从配置文件$C读取数据库配置信息,如果配置为空,则使用Model的初始属性。
public function __construct()
{
global $C;
//isset,判断配置文件是否有写,如果有,用配置文件的信息,没有就用当前
$this->dsn=isset($C['db']['dsn'])?$C['db']['dsn']:$this->dsn;
$this->username=isset($C['db']['username'])?$C['db']['username']:$this->username;
$this->password=isset($C['db']['password'])?$C['db']['password']:$this->password;
$this->option=isset($C['db']['option'])?$C['db']['option']:$this->option;
}
//定义获取PDO对象的方法
public function getPDO(){
//如果当前pdo对象等于空,才创建一个新的对象
if ($this->pdo == null){
$this->pdo = new \PDO($this->dsn,$this->username,$this->password,$this->option);
}
//然后返回这个对象
return $this->pdo;
}
//销毁PDO对象的方法
public function destoryPDO(){
//当当前对象不为空,代表有实例化对象,则销毁,置为空
if ($this->pdo != null){
$this->pdo = null;
}
}
//增删改数据的通用方法
public function execute($sql,$args){
$result = 0;
try{
//连接数据库,并执行预编译
$pdostmt = $this->getPDO()->prepare($sql);
if ($args != null){
for ($i = 0;$i < count($args);$i++){
$pdostmt->bindParam($i+1,$args[$i]);
}
}
$pdostmt->execute();
$result = $pdostmt->rowCount();
}catch (\PDOException $e){
echo "持久化异常:".$e;
}
return $result;
}
//查询的通用方法
public function query($sql,$args){
try{
//连接数据库,并执行预编译
$pdostmt = $this->getPDO()->prepare($sql);
if ($args != null){
for ($i = 0;$i < count($args);$i++){
$pdostmt->bindParam($i+1,$args[$i]);
}
}
$pdostmt->execute();
//获得二维关联数组
return $pdostmt->fetchAll(\PDO::FETCH_ASSOC);
}catch (\PDOException $e){
echo "持久化异常:".$e;
return null;
}
}
}<file_sep><?php
//核心运行类
namespace core;
class Application
{
public static $group;//模块
public static $controller;//控制器
public static $action;//方法
//前端处理功能方法:路由选择和请求分发
public static function run(){
//1.路由信息的提取,
//http://localhost/MyPHP/Exercise/exercise%2021%20MVC/index.php?g=home&c=home&a=index
global $C;
self::$group = isset($_GET['g'])?$_GET['g']:$C['default_route']['group'];
self::$controller = isset($_GET['c'])?$_GET['c']:$C['default_route']['controller'];
self::$action = isset($_GET['a'])?$_GET['a']:$C['default_route']['action'];
//2.路由信息的大小写的处理
self::$group = strtolower(self::$group);
self::$controller = ucfirst(strtolower(self::$controller));
self::$action = strtolower(self::$action);
//3.初始化控制器
// new \application\home\controllers\IndexController();
//3.2.获取控制器名称
$controllerName = self::getFullClassName();
//3.3.实例化控制器
$controllerInstance = new $controllerName();
//4.调用方法
//4.1.获得控制器方法
$method = self::$action;
//4.2.调用控制器方法
$controllerInstance->$method();
}
//3.1.获取控制器的全限定名,字符串拼接
public static function getFullClassName(){
return "\\application\\".self::$group."\\controllers\\".self::$controller."Controller";
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/11
* Time: 21:16
*/
namespace application\home\models;
use core\mybase\Model;
class TeacherModel extends Model
{
//从数据库查询得到老师列表
public function getteacher(){
$sql = "select * from teacher";
return $this->query($sql,null);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/10
* Time: 9:35
*/
namespace application\admin\models;
use core\mybase\Model;
class CustomerModel extends Model
{
public function count($like=null){
$sql=null;
if($like!=null){
$sql="SELECT COUNT(1) AS total FROM customer WHERE cname LIKE '%". $like . "%' ";
}else{
$sql="SELECT COUNT(1) AS total FROM customer ";
}
$result=$this->query($sql,null);
return $result[0]['total'];
}
public function list($pageIndex=1,$pageSize=10,$like=null){
$sql=null;
if($like!=null){
$sql="SELECT * FROM customer WHERE cname LIKE '%" . $like . "%'
OR cphone LIKE '%" . $like . "%'
OR cemail LIKE '%" . $like . "%'
ORDER BY cid DESC LIMIT ".($pageIndex-1)*$pageSize.",".$pageSize;
}else{
$sql="SELECT * FROM customer ORDER BY cid DESC LIMIT ".($pageIndex-1)*$pageSize.",".$pageSize;
}
return $this->query($sql,null);
}
public function del($args){
$sql="DELETE FROM customer WHERE cid=?";
return $this->execute($sql,$args);
}
public function add($args){
$sql="INSERT INTO customer VALUE(DEFAULT,?,?,?,?,?,DEFAULT)";
return $this->execute($sql,$args);
}
public function update($args){
$sql="UPDATE customer SET cpassword=?,cphone=?,cemail=? WHERE cid=? ";
return $this->execute($sql,$args);
}
public function ago($args){
$sql="SELECT * FROM customer WHERE cid=?";
return $this->query($sql,$args);
}
}
<file_sep><?php
namespace application\home\controllers;
use core\mybase\Controller;
use application\home\models\GuestBookModel;
use core\MySession;
class IndexController extends Controller
{
//打开首页方法
public function index(){
$this->display();
}
//打开联系我们方法
public function contact(){
$this->display();
}
//打开课程方法
public function courses(){
$this->display();
}
//打开定价方法
public function pricing(){
$this->display();
}
//打开讲师方法
public function message(){
$this->display();
}
}<file_sep><?php
namespace application\admin\controllers;
use application\admin\models\CustomerModel;
use application\admin\models\MessageModel;
use application\admin\models\TeacherModel;
use core\mybase\AdminGroupController;
use core\MySession;
use application\admin\models\UserModel;
use application\admin\models\SubscribeModel;
class IndexController extends AdminGroupController
{
//打开首页方法
public function charts(){
$this->display();
}
public function forms(){
$this->display();
}
public function gbmgr(){
$this->display();
}
public function main(){
//用户总数
$cm=new CustomerModel();
$ctotal=$cm->count();
$this->assign("ctotal",$ctotal);
//留言总数
$mm=new MessageModel();
$mtotal=$mm->count();
$this->assign("mtotal",$mtotal);
//预约总数
$sm=new SubscribeModel();
$stotal=$sm->count();
$this->assign("stotal",$stotal);
//教师总数
$tm=new TeacherModel();
$ttotal=$tm->count();
$this->assign("ttotal",$ttotal);
$this->display();
}
public function widgets(){
$this->display();
}
public function login(){
$feedbook = ['errno' => 500,'mess' => '用户名不存在!'];
$aname = isset($_POST['account'])?$_POST['account']:null;
$apassword = isset($_POST['password'])?$_POST['password']:null;
$sysremember=isset($_POST["sysremember"])?true:false;//null或on
if ($aname != null && $apassword !=null){
$args = [$aname,md5($apassword)];
$um = new UserModel();
$result = $um->getUserByNameAndPwd($args);
if ($result != null){
$feedbook = ['errno' => 200,'mess' => '登录成功!'];
MySession::setSession("aname",$result["aname"]);
MySession::setSession("sysremember",$sysremember);
if ($sysremember){
MySession::extendSession();
}
}
}
echo json_encode($feedbook,JSON_UNESCAPED_UNICODE);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/9
* Time: 21:50
*/
namespace application\home\controllers;
use application\home\models\SubscribeModel;
use core\mybase\HomeGroupController;
use core\MySession;
//预约表控制器
class subscribeController extends HomeGroupController
{
//新增预约信息
public function addsubscribe()
{
$feedback = ["errno" => 200, "mess" => "预约失败"];
$myname = $_POST['myname'];
$myphone = $_POST['myphone'];
$techer = $_POST['teacher'];
$mydate = $_POST['mydate'];
$args = [$myname,$myphone,$techer,$mydate];
$cm = new SubscribeModel();
$result = $cm->subscribemess($args);
if ($result > 0) {
$feedback = ["errno" => 200, "mess" => "预约成功"];
}
echo json_encode($feedback, JSON_UNESCAPED_UNICODE);
}
//打开预约界面
public function subscribe()
{
$this->display();
}
//分页预约数据
public function list(){
//从前端获取的信息
$pageIndex = isset($_GET['pageIndex'])?$_GET['pageIndex']:1;
$pageSize = isset($_GET['pageSize'])?$_GET['pageSize']:10;
$like = isset($_GET['like'])?$_GET['like']:null;
$gm = new SubscribeModel();
$args = [MySession::getSession('cphone')];
//获得符合条件的总记录数
$total = $gm->count($like,$args);
//获得分页数据
//print_r($args);
$list = $gm->list($pageIndex,$pageSize,$like,$args);
//必须返回json格式的对象,手写的分页表单才能接收,构建数组。返回总的记录数,和行数
$result = ['total'=>$total,'rows'=>$list];
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
//删除预约
public function del(){
//这里的值从前端脚本del函数获得
$id = isset($_GET['sid'])?$_GET['sid']:-1;
$gm = new SubscribeModel();
//接收一个受影响的行数
$result = $gm->dele([$id]);
if ($result > 0){
$this->success("删除<span style='font-size: 30px'>预约信息</span>成功,2秒后跳转回管理视图。","?g=home&c=user&a=main");
}else{
$this->fail("删除<span style='font-size: 30px'>预约信息</span>失败,2秒后跳转回管理视图。","?g=home&c=user&a=main");
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/9
* Time: 9:38
*/
namespace application\admin\controllers;
use core\mybase\Model;
use core\MySession;
class AdminController extends Model
{
public function delsession(){
MySession::destorySession();
header("location:index.php?g=admin&c=index&a=main");
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/9
* Time: 10:09
*/
namespace application\admin\models;
use core\mybase\Model;
class MessageModel extends Model
{
public function count(){
$sql="SELECT COUNT(1) AS total FROM message ";
$result=$this->query($sql,null);
return $result[0]['total'];
}
public function list($pageIndex=1,$pageSize=10){
$sql="SELECT * FROM message ORDER BY mid DESC LIMIT ".($pageIndex-1)*$pageSize.",".$pageSize;
return $this->query($sql,null);
}
public function del($args){
$sql="DELETE FROM message WHERE mid=?";
return $this->execute($sql,$args);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/11
* Time: 21:51
*/
namespace application\home\controllers;
use application\home\models\GuestBookModel;
use core\mybase\HomeGroupController;
use core\MySession;
class GuestController extends HomeGroupController
{
//添加留言功能
public function guestbook(){
$feedback=["errno"=>500,"mess"=>"留言失败"];
$args=[$_POST['mname'],$_POST['mphone'],$_POST['mcontent']];
$um=new GuestBookModel();
$result=$um->add($args);
if($result>0){
$feedback=["errno"=>200,"mess"=>"留言成功"];
}
echo json_encode($feedback,JSON_UNESCAPED_UNICODE);
}
//查询,展示分页留言功能
public function showgeustbook(){
//从前端获取的信息
$pageIndex = isset($_GET['pageIndex'])?$_GET['pageIndex']:1;
$pageSize = isset($_GET['pageSize'])?$_GET['pageSize']:10;
$like = isset($_GET['like'])?$_GET['like']:null;
$gm = new GuestBookModel();
$args = [MySession::getSession('cphone')];
//获得符合条件的总记录数
$total = $gm->count($like,$args);
//获得分页数据
//print_r($args);
$list = $gm->list($pageIndex,$pageSize,$like,$args);
//必须返回json格式的对象,手写的分页表单才能接收,构建数组。返回总的记录数,和行数
$result = ['total'=>$total,'rows'=>$list];
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
//删除留言
public function del(){
//这里的值从前端脚本del函数获得
$id = isset($_GET['mid'])?$_GET['mid']:-1;
$gm = new GuestBookModel();
//接收一个受影响的行数
$result = $gm->dele([$id]);
if ($result > 0){
$this->success("删除<span style='font-size: 30px'>留言信息</span>成功,2秒后跳转回管理视图。","?g=home&c=user&a=main");
}else{
$this->fail("删除<span style='font-size: 30px'>留言信息</span>失败,2秒后跳转回管理视图。","?g=home&c=user&a=main");
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/9
* Time: 10:20
*/
namespace application\admin\controllers;
use application\admin\models\MessageModel;
use core\mybase\Controller;
class MessageController extends Controller
{
public function list(){
$pageIndex=isset($_GET['pageIndex'])?$_GET['pageIndex']:1;
$pageSize=isset($_GET['pageSize'])?$_GET['pageSize']:10;
$mm=new MessageModel();
$total=$mm->count();
$list=$mm->list($pageIndex,$pageSize);
$result=['total'=>$total,"rows"=>$list];
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
public function del(){
$mid=isset($_GET['mid'])?$_GET['mid']:-1;
$mm=new MessageModel();
$result=$mm->del([$mid]);
header("location:index.php?g=admin&c=index&a=gbmgr");
}
}<file_sep><?php
namespace application\home\models;
use core\mybase\Model;
class GuestBookModel extends Model
{
//添加留言功能
public function add($args){
$sql="INSERT INTO message VALUE(DEFAULT,?,?,?,DEFAULT)";
return $this->execute($sql,$args);
}
//查询有多少条留言,模糊查询建议不要用预编译,可能会查不出来
public function count($like = null,$args)
{
$sql = null;
//构建sql语句,假如说有模糊查询和没有模糊查询,进行一个判断
if ($like != null) {
$sql = "select count(1) as total from message where mname like '%" . $like . "%'";
} else {
$sql = "select count(1) as total from message where mphone=?";
}
//没有参数传进来,所以$args设为null
$result = $this->query($sql, $args);
return $result[0]['total'];
}
//分页查询留言信息
public function list($pageIndex = 1, $pageSize = 10, $like = null,$args)
{
$sql = null;
if ($like != null) {
$sql = "select * from message where mname like '%" . $like . "%' order by mid desc limit " . ($pageIndex - 1) * $pageSize . "," . $pageSize;
} else {
$sql = "select * from message where mphone=? order by mid desc limit " . ($pageIndex - 1) * $pageSize . "," . $pageSize;
}
return $this->query($sql,$args);
}
//删除用户留言信息
public function dele($args)
{
$sql = "delete from message where mid=?";
//返回一个结果集,受影响的行数
return $this->execute($sql, $args);
}
}<file_sep><?php
namespace core\mybase;
use core\Application;
//控制器的基类
class Controller
{
protected $view;//视图对象
//子类对象如果没有定义构造,子类在实例化的时候会自动调用父类的构造
public function __construct()
{
//调用初始化视图的方法
$this->initView();
}
//初始化视图的方法,放到外面来,不放到构造里,为了以后扩展方便。不允许外部调用,只允许自己调用。
private function initView(){
//初始化视图对象
$this->view=new View();
//视图模板的路径:application/home/views/index.html
//include_once $this->view_dir.$view_name.".html";
$this->view->view_dir="application/".Application::$group."/views/".strtolower(Application::$controller)."/";
}
//调用视图对象打开视图方法
public function display($viewname=null){
$this->view->display($viewname);
}
//视图数据填充方法,保护类型,只有子类可以访问
protected function assign($name,$value){
$this->view->assign($name,$value);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/10
* Time: 9:35
*/
namespace application\admin\models;
use core\mybase\Model;
class TeacherModel extends Model
{
public function count($like=null){
$sql=null;
if($like!=null){
$sql="SELECT COUNT(1) AS total FROM teacher WHERE tname LIKE '%". $like . "%' ";
}else{
$sql="SELECT COUNT(1) AS total FROM teacher ";
}
$result=$this->query($sql,null);
return $result[0]['total'];
}
public function list($pageIndex=1,$pageSize=10,$like=null){
$sql=null;
if($like!=null){
$sql="SELECT * FROM teacher WHERE tname LIKE '%" . $like . "%' OR tage LIKE '%" . $like . "%'
OR tcourse LIKE '%" . $like . "%' ORDER BY tid DESC LIMIT ".($pageIndex-1)*$pageSize.",".$pageSize;
}else{
$sql="SELECT * FROM teacher ORDER BY tid DESC LIMIT ".($pageIndex-1)*$pageSize.",".$pageSize;
}
return $this->query($sql,null);
}
public function del($args){
$sql="DELETE FROM teacher WHERE tid=?";
return $this->execute($sql,$args);
}
public function add($args){
$sql="INSERT INTO teacher VALUE(DEFAULT,?,?,?)";
return $this->execute($sql,$args);
}
public function update($args){
$sql="UPDATE teacher SET tage=?,tcourse=? WHERE tid=? ";
return $this->execute($sql,$args);
}
public function ago($args){
$sql="SELECT * FROM teacher WHERE tid=?";
return $this->query($sql,$args);
}
}
<file_sep><?php
namespace application\home\controllers;
use application\home\models\UserModel;
use core\mybase\HomeGroupController;
use core\MySession;
class UserController extends HomeGroupController
{
//进入到个人中心页面
public function main(){
//填充数据
$this->assign("cname",MySession::getSession("cname"));
$this->assign("cemail",MySession::getSession("cemail"));
$this->assign("cphone",MySession::getSession("cphone"));
$this->assign("crgtime",MySession::getSession("crgtime"));
$this->display();
}
//用户修改个人信息方法
public function update(){
$feedback = ["errno" => 500, "mess" => "修改失败!"];
$newemail = $_POST['newemail'];
$newphone = $_POST['newphone'];
$newpwd = $_POST['newpwd'];
$cid = MySession::getSession("cid");
$args = [$newphone,$newemail,md5($newpwd),$cid];
$um = new UserModel();
$result = $um->upd($args);
if ($result > 0) {
$feedback = ["errno" => 200, "mess" => "修改成功"];
}
echo json_encode($feedback, JSON_UNESCAPED_UNICODE);
}
//用户注册方法
public function register()
{
$feedback = ["errno" => 500, "mess" => "注册失败!"];
$uname = $_POST['uname'];
$upwd = $_POST['upwd'];
$uemail = $_POST['uemail'];
$uphone = $_POST['uphone'];
$ukey = $_POST['ukey'];
$args = [$uname, md5($upwd),$uphone,$uemail,$ukey];
$um = new UserModel();
$result = $um->add($args);
if ($result > 0) {
$feedback = ["errno" => 200, "mess" => "注册成功"];
}
echo json_encode($feedback, JSON_UNESCAPED_UNICODE);
}
/*注册用户名校验*/
public function checkuser()
{
$uname = $_POST['uname'];
$args = [$uname];
$um = new UserModel();
$result = $um->getUser($args);
echo $result;
}
//用户登录方法
public function login(){
$feedbook = ['errno' => 500,'mess' => '用户名不存在!'];
$uname = isset($_POST['account'])?$_POST['account']:null;
$upwd = isset($_POST['password'])?$_POST['password']:null;
$remember=isset($_POST["remember"])?true:false;//null或on
if ($uname != null && $upwd !=null){
$args = [$uname,md5($upwd)];
$um = new UserModel();
$result = $um->getUserByNameAndPwd($args);
if ($result != null){
$feedbook = ['errno' => 200,'mess' => '登录成功!'];
//保持用户信息到session中
MySession::setSession("cid",$result["cid"]);
MySession::setSession("cname",$result["cname"]);
MySession::setSession("cphone",$result["cphone"]);
MySession::setSession("cemail",$result["cemail"]);
MySession::setSession("crgtime",$result["crgtime"]);
//记住我 按钮,当选择后,保存在session中
MySession::setSession("remember",$remember);
//判断:当选中复选框的值,为true时,延长1个小时会话保持时间(免登陆)
if ($remember == true){
MySession::extendSession();
}
}
}
echo json_encode($feedbook,JSON_UNESCAPED_UNICODE);
}
//退出登录
public function logout(){
MySession::destorySession();
header("location:index.php?g=home&c=index&a=index");
}
}<file_sep><?php
namespace application\admin\models;
use core\mybase\Model;
class UserModel extends Model
{
public function add($args)
{
$sql = "INSERT INTO customer VALUES(DEFAULT,?,?,?,?,?,default)";
return $this->execute($sql, $args);
}
public function getUser($args)
{
$sql = "SELECT count(1) as result fROM customer WHERE cname=?";
$result = $this->query($sql, $args);
return $result[0]['result'];
}
/**根据用户名密码获取用户信息*/
public function getUserByNameAndPwd($args){
$sql="SELECT * FROM admin WHERE aname=? AND apassword=?";
$result=$this->query($sql,$args);
if(count($result)>0){
return $result[0];
}else{
return null;
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/11
* Time: 21:17
*/
namespace application\home\controllers;
use application\home\models\TeacherModel;
use core\mybase\HomeGroupController;
class TeacherController extends HomeGroupController
{
//获取老师列表
public function teacherlist()
{
$tm = new TeacherModel();
$result = $tm->getTeacher();
echo json_encode($result, JSON_UNESCAPED_UNICODE);
}
}<file_sep># Myproject
二阶段项目
<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/9
* Time: 21:47
*/
namespace application\home\models;
use core\mybase\Model;
class SubscribeModel extends Model
{
//新增预约信息
public function subscribemess($args)
{
$sql = "insert into subscribe value(default,?,?,?,?)";
return $this->execute($sql,$args);
}
//查询有多少条预约,模糊查询建议不要用预编译,可能会查不出来
public function count($like = null,$args)
{
$sql = null;
//构建sql语句,假如说有模糊查询和没有模糊查询,进行一个判断
if ($like != null) {
$sql = "select count(1) as total from subscribe where sname like '%" . $like . "%'";
} else {
$sql = "select count(1) as total from subscribe where sphone=?";
}
//没有参数传进来,所以$args设为null
$result = $this->query($sql, $args);
return $result[0]['total'];
}
//分页查询预约信息
public function list($pageIndex = 1, $pageSize = 10, $like = null,$args)
{
$sql = null;
if ($like != null) {
$sql = "select * from subscribe where sname like '%" . $like . "%' order by sid desc limit " . ($pageIndex - 1) * $pageSize . "," . $pageSize;
} else {
$sql = "select * from subscribe where sphone=? order by sid desc limit " . ($pageIndex - 1) * $pageSize . "," . $pageSize;
}
return $this->query($sql,$args);
}
//删除用户预约信息
public function dele($args)
{
$sql = "delete from subscribe where sid=?";
//返回一个结果集,受影响的行数
return $this->execute($sql, $args);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/9
* Time: 10:20
*/
namespace application\admin\controllers;
use application\admin\models\CustomerModel;
use application\admin\models\TeacherModel;
use core\mybase\Controller;
class CustomerController extends Controller
{
public function list(){
$pageIndex=isset($_GET['pageIndex'])?$_GET['pageIndex']:1;
$pageSize=isset($_GET['pageSize'])?$_GET['pageSize']:10;
$like=isset($_GET['like'])?$_GET['like']:null;
$mm=new CustomerModel();
$total=$mm->count($like);
$list=$mm->list($pageIndex,$pageSize,$like);
$result=['total'=>$total,"rows"=>$list];
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
public function del(){
$mid=isset($_GET['cid'])?$_GET['cid']:-1;
$mm=new CustomerModel();
$result=$mm->del([$mid]);
header("location:index.php?g=admin&c=index&a=forms");
}
public function add(){
$feedback = ["errno" => 500, "mess" => "新增失败!"];
$cname=isset($_POST['cname'])?$_POST['cname']:null;
$cpassword=isset($_POST['cpassword'])?$_POST['cpassword']:null;
$cphone=isset($_POST['cphone'])?$_POST['cphone']:null;
$cemail=isset($_POST['cemail'])?$_POST['cemail']:null;
$ckey=isset($_POST['ckey'])?$_POST['ckey']:null;
if($cname==null || $cpassword==null || $cphone==null || $cemail==null || $ckey==null){
return;
}
$args=[$cname,md5($cpassword),$cphone,$cemail,$ckey];
$mm=new CustomerModel();
$result=$mm->add($args);
if($result>0){
$feedback = ["errno" => 200, "mess" => "新增成功!"];
}
echo json_encode($feedback,JSON_UNESCAPED_UNICODE);
}
public function update(){
$feedback = ["errno" => 500, "mess" => "修改失败!"];
$cpassword=isset($_POST['cpassword'])?$_POST['cpassword']:null;
$cphone=isset($_POST['cphone'])?$_POST['cphone']:null;
$cemail=isset($_POST['cemail'])?$_POST['cemail']:null;
$cid=$_POST['cid'];
if( $cpassword==null || $cphone==null || $cemail==null){
return;
}
$args=[md5($cpassword),$cphone,$cemail,$cid];
$mm=new CustomerModel();
$result=$mm->update($args);
if($result>0){
$feedback = ["errno" => 200, "mess" => "修改成功!"];
}
echo json_encode($feedback,JSON_UNESCAPED_UNICODE);
}
public function ago(){
$cid=$_POST['cid'];
$args=[$cid];
$mm=new CustomerModel();
$result=$mm->ago($args);
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
}<file_sep><?php
//http://localhost/MyPHP/Exercise/exercise%2021%20MVC/ECI-C/index.php
//定义服务器默认URL
//http://localhost/MyPHP/Exercise/exercise21MVC/ECI-C/index.php
define("SERVER_URL","http://".$_SERVER['SERVER_NAME']."/MyPHP/Exercise/exercise 21 MVC/ECI-C/");
//前台静态文件常量
//<link href="public/home/css/bootstrap.css" type="text/css" rel="stylesheet" media="all">
define("__HOME__","public/home/");
define("__HOME_CSS__",SERVER_URL.__HOME__."css/");
define("__HOME_IMAGES__",SERVER_URL.__HOME__."images/");
define("__HOME_JS__",SERVER_URL.__HOME__."js/");
//定义前台公共代码文件的地址常量
//application/home/views/common
define("__HOME_COMMON__","application/home/views/common/");
//定义前台登录功能静态资源常量
define("__LOGIN__","public/login/");
define("__LOGIN_CSS__",SERVER_URL.__LOGIN__."css/");
define("__LOGIN_IMAGES__",SERVER_URL.__LOGIN__."images/");
define("__LOGIN_JS__",SERVER_URL.__LOGIN__."js/");
//后台静态文件常量
//<link href="public/home/css/bootstrap.css" type="text/css" rel="stylesheet" media="all">
define("__ADMIN__","public/admin/");
define("__ADMIN_CSS__",SERVER_URL.__ADMIN__."css/");
define("__ADMIN_JS__",SERVER_URL.__ADMIN__."js/");
//定义后台公共代码文件的地址常量
//application/admin/views/common
define("__ADMIN_COMMON__","application/admin/views/common/");
<file_sep><?php
namespace application\home\models;
use core\mybase\Model;
class UserModel extends Model
{
//注册用户方法
public function add($args)
{
$sql = "INSERT INTO customer VALUES(DEFAULT,?,?,?,?,?,default)";
return $this->execute($sql, $args);
}
/*注册用户名校验是否已存在*/
public function getUser($args)
{
$sql = "SELECT count(1) as result fROM customer WHERE cname=?";
$result = $this->query($sql, $args);
return $result[0]['result'];
}
/**根据用户名密码获取用户信息,用户登录*/
public function getUserByNameAndPwd($args){
$sql="SELECT * FROM customer WHERE cname=? AND cpassword=?";
$result=$this->query($sql,$args);
if(count($result)>0){
return $result[0];
}else{
return null;
}
}
//修改用户信息
public function upd($args){
$sql = "update customer set cphone=? , cemail=? , cpassword=? where cid=?";
return $this->execute($sql,$args);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/7/9
* Time: 10:20
*/
namespace application\admin\controllers;
use application\admin\models\TeacherModel;
use core\mybase\Controller;
class TeacherController extends Controller
{
public function list(){
$pageIndex=isset($_GET['pageIndex'])?$_GET['pageIndex']:1;
$pageSize=isset($_GET['pageSize'])?$_GET['pageSize']:10;
$like=isset($_GET['like'])?$_GET['like']:null;
$mm=new TeacherModel();
$total=$mm->count($like);
$list=$mm->list($pageIndex,$pageSize,$like);
$result=['total'=>$total,"rows"=>$list];
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
public function del(){
$mid=isset($_GET['tid'])?$_GET['tid']:-1;
$mm=new TeacherModel();
$result=$mm->del([$mid]);
header("location:index.php?g=admin&c=index&a=widgets");
}
public function add(){
$feedback = ["errno" => 500, "mess" => "新增失败!"];
$tname=isset($_POST['tname'])?$_POST['tname']:null;
$tage=isset($_POST['tage'])?$_POST['tage']:null;
$tcourse=isset($_POST['tcourse'])?$_POST['tcourse']:null;
if($tname==null || $tage==null || $tcourse==null){
return;
}
$args=[$tname,$tage,$tcourse];
$mm=new TeacherModel();
$result=$mm->add($args);
if($result>0){
$feedback = ["errno" => 200, "mess" => "新增成功!"];
}
echo json_encode($feedback,JSON_UNESCAPED_UNICODE);
}
public function update(){
$feedback = ["errno" => 500, "mess" => "修改失败!"];
$tage=isset($_POST['tage'])?$_POST['tage']:null;
$tcourse=isset($_POST['tcourse'])?$_POST['tcourse']:null;
$tid=$_POST['tid'];
if( $tage==null || $tcourse==null){
return;
}
$args=[$tage,$tcourse,$tid];
$mm=new TeacherModel();
$result=$mm->update($args);
if($result>0){
$feedback = ["errno" => 200, "mess" => "修改成功!"];
}
echo json_encode($feedback,JSON_UNESCAPED_UNICODE);
}
public function ago(){
$tid=$_POST['tid'];
$args=[$tid];
$mm=new TeacherModel();
$result=$mm->ago($args);
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
} | 1df4365d5f0b70137eb85d6c66b6ed384ac7af86 | [
"Markdown",
"PHP"
] | 32 | PHP | handsomelrm/Myproject | 6248f198155e5a770c5dcdbc074f3c7b52c56bc3 | 49d62c3499e28af5d12c4c1ce67d1226c1293f74 | |
refs/heads/main | <repo_name>khaledkcara/ProdVM<file_sep>/prodvm.sh
#!/bin/bash
# Update APT
echo "Updating APT"
sleep 10
apt-get update
##### Unifi install
echo "Downloading and Installing Unifi Controller"
sleep 10
# Download latest Unifi controller script from
wget https://get.glennr.nl/unifi/install/unifi-6.0.43.sh
# Install unifi
bash unifi-6.0.43.sh
##### pi-hole
echo "Downloading and Installing Pi-hole"
sleep 10
# Download and install pihole
apt-get install curl -y
curl -sSL https://install.pi-hole.net | bash
# Change password
pihole -a -p
# Change Pi-hole port
sed -i 's/80/33331/' /etc/lighttpd/lighttpd.conf
# restart pihole lighttpd
systemctl restart lighttpd
##### apache2
echo "Downloading and Installing Apache Web Server"
sleep 10
apt-get install apache2 -y
# Download my default webpage from github
git clone https://github.com/khaledkcara/myweb.git
# Move web to Apache directory
mv myweb/* /var/www/html
##### Guacamole
echo "Downloading and Installing Guacamole"
sleep 10
# Downloading and Installing Guacamole
wget https://git.io/fxZq5 -O guac-install.sh
# make the script excutable
chmod +x guac-install.sh
# run the script
bash guac-install.sh
# Change port
sed -i 's/8080/33333/' /etc/tomcat9/server.xml
# restart the server
systemctl restart guacd
systemctl restart tomcat9
##### Downloading and Installing FOGProject
echo "Downloading and Installing FOGProject"
sleep 10
# Downloading FOGProject
wget https://github.com/FOGProject/fogproject/archive/1.5.9.tar.gz
# Unzip
tar -xzvf 1.5.9.tar.gz
# move to bin directory
cd fogproject-1.5.9/bin
# run the script
./installfog.sh
# change directory
cd
#### Clean up
echo "Cleaning up script...."
sleep 15
rm -fdr /home/khalid/1.5.9.tar.gz
rm -fdr /home/khalid/guac-install.sh
rm -fdr /home/khalid/fogproject-1.5.9
rm -fdr /home/khalid/myweb
exec rm /home/khalid/prodvm.sh
exit
| 0c5f581beb25c89ea83cc9ea1b320c0e5fca6c5d | [
"Shell"
] | 1 | Shell | khaledkcara/ProdVM | 871dc3122b58281240ece0ea95f173641222ea37 | bcb46ae5d000d8e523b620c095dca7bfcb3b7b20 | |
refs/heads/master | <file_sep>// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
var meanstack=angular.module('meanstack', ['ionic'])
meanstack.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
//var serverURL = "http://localhost:8080";
var serverURL = "http://10.149.247.113:8080";
//var serverURL = "http://192.168.0.2:8080";
meanstack.config(['$stateProvider','$urlRouterProvider',function($stateProvider,$urlRouterProvider){
$stateProvider
.state('viewbooks',{
url:'/viewbooks',
templateUrl:'viewbooks'
//controller:'viewcntrl'
}).state('addnewitem',{
url:'/addnewitem',
templateUrl:'additem',
controller:'viewcntrl'
}).state('editrow',{
url:'/editrow',
templateUrl:'editrow',
controller:'editcntrl'
}).state('nav',{
url:'/nav',
templateUrl:'template/navigation.html'
});
$urlRouterProvider.otherwise('/');
}])
var maincntrl=meanstack.controller('maincntrl',['$scope','$rootScope','$http','$location','meanserv',function($scope,$rootScope,$http,$location,meanserv){
$scope.selected={};
$rootScope.tracker={};
$scope.formsubmit=function(){
console.log('alert');
$http({
method:'GET',
url:serverURL+'/viewbooks'
}).then (function(response){
$rootScope.tracker=response.data;
console.log('records from http::'+$rootScope.tracker.length);
})
console.log('returned from http::'+$scope.retjson);
$location.path('/viewbooks');
}
$scope.editrow=function(item){
console.log('checkbox selected::'+item.SrNo);
$scope.selected=angular.copy(item);
console.log('setting location editrow::');
$scope.editfields=true;
//$location.path('/editrow');
}
$scope.save=function(item){
console.log('in edit function write http put here::'+item.SrNo);
$http({
method:'PUT',
url:serverURL+'/updatetracker/:'+item.SrNo,
data:item
}).then (function(response){
console.log('Updated succcessfully::'+response.data);
$scope.item={};
})
$scope.editfields=false;
meanserv.getbooks();
}
$scope.cancel=function(){
console.log('in cancel edit function');
$scope.editfields=false;
}
$scope.gettemplate=function(i){
if(i.SrNo==$scope.selected.SrNo){
return 'editrow';
}else{
return 'display';
}
}
$scope.addbooks=function(){
$location.path('/addnewitem');
console.log('total records::'+$rootScope.tracker.length);
}
$scope.nvg=function(){
$location.path('/nav');
console.log('In Nav');
}
$scope.home=function(){
$location.path('/viewbooks');
}
}]);
meanstack.controller('editcntrl',['$http','$location',function($scope,$http,$location){
console.log('in edit cntrl controller');
$scope.save=function(item){
console.log('in edit function write http put here::'+item.SrNo);
}
$scope.cancel=function(){
console.log('in cancel edit function');
}
}]);
meanstack.controller('viewcntrl',['$scope','$http','$location','$rootScope',function($scope,$http,$location,$rootScope){
console.log('in addition part length::'+$rootScope.tracker.length);
$scope.saveitem=function(newitem){
$scope.newitem=newitem;
console.log('new item::'+newitem);
//var jsonitem=JSON.parse($scope.newitem);
console.log('Sending JSON to post:'+JSON.stringify(newitem));
$scope.newitem.SrNo=$rootScope.tracker.length+1;
console.log('Sending sr no to backend:'+$scope.newitem.SrNo);
$http({
method:'POST',
url:serverURL+'/addbooks',
data:newitem
}).then (function(response){
console.log('books added successfully');
})
$scope.newitem='';
}
$scope.update=function(index){
console.log('indev value::'+$scope.chkbox);
console.log('index value::'+index);
}
}]);
meanstack.filter('status',function(){
return function(input,tracker,useroption){
var rettracker=[];
if(typeof(useroption)=='undefined'){
useroption='All';
}
console.log('useroption char o::'+useroption);
//var ch=char('o');
var chkarr=useroption.toString();
console.log('chkarr.value::'+chkarr);
console.log('chkarr.indexOf::'+chkarr.indexOf(","));
console.log('useroption.indexOf::'+useroption.indexOf(","));
if(chkarr.indexOf(",")==-1){
if(useroption=='closed'){
angular.forEach(tracker,function(value){
if(value.Status=='Closed'){
rettracker.push(value);
}
})
}if(useroption=='open'){
angular.forEach(tracker,function(value){
if(value.Status=='Open'){
rettracker.push(value);
}
})
}if(useroption=='fixed'){
angular.forEach(tracker,function(value){
if(value.Status=='Fixed'){
rettracker.push(value);
}
})
}
if(useroption=='All'){
rettracker=tracker;
}
return rettracker;
}else{
//console.log('multiselect option used::value is::'+useroption);
console.log('multiselect option splitted::'+useroption.toString().split(","));
var newarr=useroption.toString().split(",");
console.log("length of new array::"+newarr.length);
newarr.forEach(function(value,index){
if(value=="open"){
console.log("selected open");
angular.forEach(tracker,function(value){
if(value.Status=='Open'){
rettracker.push(value);
}
})
}
if(value=="fixed"){
console.log("selected Fixed");
angular.forEach(tracker,function(value){
if(value.Status=='Fixed'){
rettracker.push(value);
}
})
}
if(value=="closed"){
console.log("selected closed");
angular.forEach(tracker,function(value){
if(value.Status=='Closed'){
rettracker.push(value);
}
})
}
})
console.log('returning from else::'+rettracker.length);
return rettracker;
}
}
})
meanstack.service('meanserv',['$rootScope','$http',function($rootScope,$http){
console.log('in meanserv');
this.getbooks=function(){
console.log('alert from service getting books');
$http({
method:'GET',
url:serverURL+'/viewbooks'
}).then (function(response){
$rootScope.tracker=response.data;
console.log('records from http::'+$rootScope.tracker.length);
})
}
}]) | 0984a76015dcde733fb80f837357c6214c732bc9 | [
"JavaScript"
] | 1 | JavaScript | slazengerz/ncbtracker | 1d43836251ecce8f29c0511a60ab5f219cc93d57 | 1a3470224bbf4b3d1e2eef6c13462fed616c416b | |
refs/heads/main | <repo_name>marvinhagemeister/vite-dirname-bug<file_sep>/vite/plugin.ts
import { Plugin } from "vite";
export function myPlugin(): Plugin {
console.log("PLUGIN_DIR", __dirname);
return {
name: "dirname",
};
}
<file_sep>/vite.config.ts
import { defineConfig } from "vite";
import { myPlugin } from "./vite/plugin";
console.log("CONFIG_DIR and PLUGIN_DIR should be different");
console.log("CONFIG_DIR", __dirname);
// https://vitejs.dev/config/
export default defineConfig({
plugins: [myPlugin()],
});
<file_sep>/README.md
# Vite plugin dirname bug
## Expected Result
Using `__dirname` inside a plugin points to the dirname of that file instead of the dirname of `vite.config.ts`.
## Actual Result
`__dirname` points to the directory that `vite.config.ts` resides in, regardless of where the plugin file is placed.
## Steps to reproduce:
1. Clone this repo
2. Run `npm install`
3. Run `npm start` -> Check terminal output
| 0b5b6f82600d5089b80df5c47be5de02435ece45 | [
"Markdown",
"TypeScript"
] | 3 | TypeScript | marvinhagemeister/vite-dirname-bug | 40e826d19579fb2b0444c349799d941ac9d28601 | f5bd58fcd99d2223ae4a0ec97ccdbe211006eb6e | |
refs/heads/master | <repo_name>acc-java2/addit<file_sep>/src/edu/acc/java2/addit/Addit.java
/*
Java 2 - ITSE-1701-351
<EMAIL>
www.bytecaffeine.com/acc/java/2
proj.bat at www.bytecaffeine.com/acc/java/1/proj.bat
*/
package edu.acc.java2.addit;
public class Addit {
private static final String EXCEPTION = "%s is not an integer.\n";
private static final String USAGE = "java edu.acc.java2.addit.Addit <int> <int>";
public static void main(String[] args) {
int num1 = 0, num2 = 0, sum = 0;
try {
num1 = Integer.parseInt(args[0]);
} catch (NumberFormatException nfe1) {
System.out.printf(EXCEPTION, args[0]);
return;
} catch (ArrayIndexOutOfBoundsException aioobe1) {
System.out.println(USAGE);
return;
}
try {
num2 = Integer.parseInt(args[1]);
} catch (NumberFormatException nfe2) {
System.out.printf(EXCEPTION, args[1]);
return;
} catch (ArrayIndexOutOfBoundsException aioobe1) {
System.out.println(USAGE);
return;
}
sum = num1 + num2;
System.out.printf("The sum of %d and %d is %d\n", num1, num2, sum);
javax.swing.JOptionPane.showMessageDialog(null, "Addit (c)2016 ACC");
}
}
| 2341951aa545a6ef2de34866c0a71b87981d718a | [
"Java"
] | 1 | Java | acc-java2/addit | eb5576efb64b62249a7cbfa2cd2bf8e6c65c4760 | 054dd6df3f52fbe288843fc7f84a704cd4ac2afd | |
refs/heads/master | <repo_name>taq-f/kancollectron<file_sep>/src_main/wiki.js
export const WIKI_URLS = new Map([
['expedition', 'https://wikiwiki.jp/kancolle/%E9%81%A0%E5%BE%81'],
[
'shipbuilding',
'https://wikiwiki.jp/kancolle/%E5%BB%BA%E9%80%A0%E3%83%AC%E3%82%B7%E3%83%94',
],
[
'develop',
'https://wikiwiki.jp/kancolle/%E9%96%8B%E7%99%BA%E3%83%AC%E3%82%B7%E3%83%94',
],
])
<file_sep>/src_main/menu.js
import { Menu } from 'electron'
import { WIKI_URLS } from './wiki'
import {
alwaysOnTop,
mute,
reload,
screenShot,
shrink,
toggleDevTool,
wiki,
} from './actions'
export default function createMenu() {
const template = [
{
label: 'Debug',
submenu: [
{
accelerator: 'CmdOrCtrl+R',
click: (_, w) => reload.next(w),
label: 'Reload',
},
{
accelerator:
process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
click: (_, w) => toggleDevTool.next(w),
label: 'Toggle Developer Tools',
},
],
},
{
label: 'Tools',
submenu: [
{
accelerator: 'CmdOrCtrl+M',
checked: false,
click: (item, w) => mute.next({ w, mute: item.checked }),
label: 'Mute',
type: 'checkbox',
},
{
accelerator: 'CmdOrCtrl+S',
checked: false,
click: (item, w) => shrink.next({ w, shrink: item.checked }),
label: 'Shrink',
type: 'checkbox',
},
{
checked: false,
click: (item, w) => alwaysOnTop.next({ w, onTop: item.checked }),
label: 'Always On Top',
type: 'checkbox',
},
{
accelerator: 'CmdOrCtrl+S',
click: (_, w) => screenShot.next(w),
label: 'Screen Shot',
},
],
},
{
label: 'Wiki',
submenu: [
{
click: () => {
Array.from(WIKI_URLS.keys()).forEach(page => {
wiki.next(page)
})
},
label: 'すべて',
},
{
click: () => wiki.next('expedition'),
label: '遠征',
},
{
click: () => wiki.next('shipbuilding'),
label: '建造レシピ',
},
{
click: () => wiki.next('develop'),
label: '開発レシピ',
},
],
},
]
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
}
<file_sep>/src_main/actions.js
import { dialog, shell } from 'electron'
import { writeFile } from 'fs'
import { Subject } from 'rxjs'
import { map } from 'rxjs/operators'
import BROWSER_WINDOW_OPTIONS from './browser-window-option'
import { WIKI_URLS } from './wiki'
/**
* Toggle browser window state: always on top
*/
export const alwaysOnTop = new Subject()
/**
* Toggle browser window state: mute
*/
export const mute = new Subject()
/**
* Reload
*/
export const reload = new Subject()
/**
* Capture screen
*/
export const screenShot = new Subject()
/**
* Resize browser window
*/
export const shrink = new Subject()
/**
* Toggle developer tool
*/
export const toggleDevTool = new Subject()
/**
* Open wiki page
*/
export const wiki = new Subject()
// *****************************************************************************
// Action Procedures
// *****************************************************************************
reload.subscribe(w => w.reload())
toggleDevTool.subscribe(w => w.webContents.toggleDevTools())
mute.subscribe(param => param.w.webContents.send('mute', param.mute))
shrink
.pipe(
map(param => {
let factor
if (param.shrink) {
factor = 0.7
} else {
factor = 1
}
return {
factor,
height: Math.round(BROWSER_WINDOW_OPTIONS.height * factor),
w: param.w,
width: Math.round(BROWSER_WINDOW_OPTIONS.width * factor),
}
})
)
.subscribe(param => {
param.w.setContentSize(param.width, param.height)
param.w.webContents.send('resize', param.factor)
})
alwaysOnTop.subscribe(param => param.w.setAlwaysOnTop(param.onTop))
screenShot.subscribe(async w => {
const filename = await new Promise(resolve => {
dialog.showSaveDialog(w, {}, f => {
resolve(f)
})
})
if (!filename) {
return
}
const nativeImage = await new Promise(resolve => {
const size = w.getSize()
w.capturePage({ x: 0, y: 0, width: size[0], height: size[1] }, image => {
resolve(image)
})
})
const buffer = nativeImage.toPNG()
try {
await new Promise((resolve, reject) => {
writeFile(filename, buffer, err => {
if (err) {
reject(err)
} else {
resolve(filename)
}
})
})
} catch (error) {
dialog.showMessageBox(w, {
buttons: ['OK'],
detail: error.message,
message: 'Failed to capture page',
title: 'Error!',
type: 'error',
})
}
})
wiki.pipe(map(page => WIKI_URLS.get(page))).subscribe(url => {
if (url) {
shell.openExternal(url)
}
})
<file_sep>/src_main/browser-window-option.js
const BROWSER_WINDOW_OPTIONS = {
height: 720,
resizable: false,
useContentSize: true,
width: 1200,
}
export default BROWSER_WINDOW_OPTIONS
| 93550e718ff06c40f449e4108038f9c2093fa175 | [
"JavaScript"
] | 4 | JavaScript | taq-f/kancollectron | d42844f61ffbe063f536ceda472cffc67ad1358c | f6081a4bba4ff0b31433b98a30a0e700f5c181bd | |
refs/heads/master | <file_sep>def square_array(array)
new_squares = []
array.each do |var|
var**2
new_squares << var**2
end
new_squares
end | d87869e47642b2ce4153113c373c47bfdee04d17 | [
"Ruby"
] | 1 | Ruby | veloblank/square_array-v-000 | eb52c1d9a366f65f39e3aa1fdef37c9a3c0695eb | e97448146486ef09123875f2b1bbe347dfd11f78 | |
refs/heads/master | <file_sep>import java.util.Scanner;
import java.util.Random;
public class rps {
public static String userInput;
public static String computerInput;
public static int computerNumber;
public static void main(String[] args) {
// <NAME>, CSC 120 Final, Rock Paper Scissors Game
Scanner input = new Scanner(System.in);
Random random = new Random();
System.out.println("This is a game of rock paper scissors,");
System.out.println("Enter 'rock', 'paper', 'scissors'");
String userInput = input.nextLine();
computerNumber = random.nextInt(3) + 1;
switch (computerNumber) {
case 1:
computerInput = "rock";
break;
case 2:
computerInput = "paper";
break;
default:
computerInput = "scissors";
break;
}
System.out.println("The user picked "+ userInput);
System.out.println("The computer picked " + computerInput);
if ((userInput.equals("scissors") && computerInput.equals("paper")) || (userInput.equals("rock") && computerInput.equals("scissors")) || (userInput.equals("paper") && computerInput.equals("rock")) ) {
System.out.println("User wins!");
} else if ((userInput.equals("rock") && computerInput.equals("paper")) || (userInput.equals("paper") && computerInput.equals("scissors")) || (userInput.equals("scissors") && computerInput.equals("rock")) ) {
System.out.println("Computer wins!");
} else {
System.out.println("The game is a tie!");
}
}
}<file_sep>from javax.servlet.http import HttpServlet
from string import Template
class hello(HttpServlet):
def doGet(self, request, response):
response.contentType = "text/html"
out = response.writer
a = ['joe','sally','sue']
s1 = a[0]
s2 = a[1]
for s in a:
out.print(s + '-')
buff = "<html><head></head><body>"
buff += "<h1>Greetings from a jylet</h1>"
x = 10
if x == 10:
buff += '<h4>x is 10</h4>'
s = Template('$who likes $what')
d = dict(who='tim',what='money')
d['who'] = 'fred'
d['what'] = 'euros'
d = {'who': 'James', 'what': 'francs'}
buff += "<h3>" + s.substitute(d) + "</h3>"
buff += "</body></html>"
out.print( buff )
<file_sep>import pandas as pd
import numpy as np
import datasist as ds
train_df = pd.read_csv("train_data.csv")
test_df = pd.read_csv("test_data.csv")
# 1
# print(train_df)
# print(train_df.head(10))
# print(ds.structdata.describe(train_df))
# 2
# ds.structdata.check_train_test_set(train_df,
# test_df,
# index='Customer Id',
# col='Building Dimension')
# print(ds.structdata.check_train_test_set(train_df))
# 3
# print(ds.structdata.display_missing(train_df))
# 4
cat_feats = ds.structdata.get_cat_feats(train_df)
num_feats = ds.structdata.get_num_feats(train_df)
print(cat_feats + num_feats)
# print(num_feats)
# 5 This one does not work
# unique_count = ds.structdata.get_unique_counts(train_df)
# print(unique_count)
# 6
# all_data, ntrain, ntest = ds.structdata.join_train_and_test(train_df, test_df)
# print("New size of combined data {}".format(all_data.shape))
# print("Old size of train data: {}".format(ntrain))
# print("Old size of test data: {}".format(ntest))
# print(all_data)
# train = all_data[:ntrain]
# test = all_data[ntrain:]<file_sep># <NAME>, CSC 110, <NAME>, 10/21/19
# Assignment 5
#
def main():
def instructions():
print('This program reads race time in minutes and seconds for a runner.')
print('It then computes and prints the speed in feet/second and meters/second.')
def feetPerSecond(min, sec):
_fps = (5280 / ((min * 60) + sec))
return _fps
# print('feet/sec')
# print('')
# print('{:.2f}'.format(fps))
def metersPerSecond(min, sec):
_mps = 1609.34 / ((min * 60) + sec)
return _mps
# print('meters/second')
# print('')
# print('{:.2f}'.format(mps))
instructions();
for i in range(1, 5):
x = input("Press 'Y' or 'y' to continue, anything else to exit: ")
while x == 'y' or x == 'Y':
name = input('Enter first name: ')
min = int(input('Enter minutes: '))
sec = float(input('Enter seconds: '))
fps = feetPerSecond(min, sec);
mps = metersPerSecond(min, sec);
print(' ')
print('{:^10}'.format('feet/sec'), ' '.center(10), '{:^10}'.format('meters/sec'))
print()
print('{:^10,.2f}'.format(fps), ' ', '{:^20,.2f}'.format(mps))
x = input("Press 'Y' or 'y' to continue, anything else to exit: ")
else:
break;
main();
# def no_return(x,y):
# c = x + y
# return c
#
# res = no_return(4,5)
# print(res)
# <NAME>, CSC 110, <NAME>, 10/21/19
# Assignment 5
#
# import sys
#
# def main():
#
# def instructions():
# print('This program reads race time in minutes and seconds for a runner.')
# print('It then computes and prints the speed in feet/second and meters/second.')
# x = input("Press 'Y' or 'y' to continue, anything else to exit: ")
#
# # if x == 'y' or x == 'Y':
# # return
# # else:
# # sys.exit()
#
# while x == 'y' or x == 'Y':
# break
# else:
# sys.exit()
#
# instructions();
#
# name = input('Enter first name:')
# min = int(input('Enter minutes: '))
# sec = float(input('Enter seconds: '))
#
# def feetPerSecond():
# fps = 5280 / ((min * 60) + sec)
# print('feet/sec')
# print('')
# print('{:.2f}'.format(fps))
#
# def metersPerSecond():
# mps = 1609.34 / ((min * 60) + sec)
# print('meters/second')
# print('')
# print('{:.2f}'.format(mps))
#
# # print('feet/sec meters/sec')
# # print()
# # print('{:.2f}'.format(fps), ' ', '{:.2f}'.format(mps))
#
#
#
#
# feetPerSecond();
# metersPerSecond();
#
#
#
# main();
#
#
# #
# # x = 'y' or x == 'Y'
# # while x == 'y' or x == 'Y':
# # print('toads')
# # x = input()
<file_sep># <NAME> , CSC 110, 9/27/19
# EXTRA CREDIT
#
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
### Version 1
### Automated Version, Cleaner syntax
### Only works when the column headers are iterating by 1 (ie: 2000, 2001, 2002, 2003...)
import pandas as pd
x = 'Year'
y = 2000
# df = pd.read_csv('/Users/Ryan/Desktop/pre.csv')
df = pd.read_csv('pre.csv')
while y <= 2018:
df.rename(columns={str(y): x + ' ' + str(y)}, inplace=True)
#print(str(y))
y += 1
#header = ['Team', x + ' ' + str(y), x + ' ' + str(y), x + ' ' + str(y)]
#df.rename(columns={'2000': x + ' 2000', '2001': x + ' 2001', '2002': x + ' 2002', '2003': x + ' 2003', '2004': x + ' 2004', '2005': x + ' 2005'}, inplace=True)
header = ['Team', 'Year 2000', 'Year 2001', 'Year 2002', 'Year 2003', 'Year 2004', 'Year 2005', 'Year 2006', 'Year 2007', 'Year 2008', 'Year 2009', 'Year 2010',
'Year 2011', 'Year 2012', 'Year 2013', 'Year 2014', 'Year 2015', 'Year 2016', 'Year 2017', 'Year 2018']
#list(df)
#df.to_csv('/Users/Ryan/Desktop/test.csv', header=[col1, col2])
# df.to_csv('/Users/Ryan/Desktop/post.csv', columns=(header))
df.to_csv('post.csv', columns=(header))
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
### Version 2
### Messy Version, Specifically referencing each column header in pre.csv
### 100% functionality for only pre.csv
import pandas as pd
x = 'Year'
# df = pd.read_csv('/Users/Ryan/Desktop/pre.csv')
df = pd.read_csv('pre.csv')
df.rename(columns={'2000': x + ' 2000', '2001': x + ' 2001', '2002': x + ' 2002', '2003': x + ' 2003', '2004': x + ' 2004', '2005': x + ' 2005', '2005': x + ' 2005',
'2006': x + ' 2006', '2007': x + ' 2007', '2008': x + ' 2008', '2009': x + ' 2009', '2010': x + ' 2010', '2011': x + ' 2011', '2012': x + ' 2012', '2013': x + ' 2013',
'2014': x + ' 2014', '2015': x + ' 2015', '2016': x + ' 2016', '2017': x + ' 2017', '2018': x + ' 2018'}, inplace=True)
header = ['Team', 'Year 2000', 'Year 2001', 'Year 2002', 'Year 2003', 'Year 2004', 'Year 2005', 'Year 2006', 'Year 2007', 'Year 2008', 'Year 2009', 'Year 2010',
'Year 2011', 'Year 2012', 'Year 2013', 'Year 2014', 'Year 2015', 'Year 2016', 'Year 2017', 'Year 2018']
#list(df)
#df.to_csv('/Users/Ryan/Desktop/test.csv', header=[col1, col2])
# df.to_csv('/Users/Ryan/Desktop/post.csv', columns=(header))
df.to_csv('post.csv', columns=(header))
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
# Do not run this code w/ the assignment. Automatically erases post.csv after run
# Truncates document immediately
# post = '/Users/Ryan/Desktop/post.csv'
# f = open(post, 'w+')
# f.close()
<file_sep># <NAME>, CSC 110, Prof Ali, 10/26/19
#
# This is not apart of the lab? Just doing what he wants us to do in class
infile = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/numbers.txt', 'w')
for i in range(21):
number = str(i)
infile.write(number + '\n')
infile.close()
infile = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/numbers.txt', 'r')
c = 0
for line in infile:
number = float(line)
print('{:.2f}'.format(number))
c += number
print(c)
infile.close()
# End of inclass version. Notice different way of converting string -> int / float
##############################################################################
# Task 02
def main():
x = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/numbers.txt', 'r')
c = 0
for line in x:
# Empty "objects" such as lines are considered false in boolean context
# Therefore, will iterate until it gets to an empty line.
# https://stackoverflow.com/questions/17264226/what-does-if-x-strip-mean
if line.strip():
n = int(line)
c += n
print(c)
x.close();
main();
##############################################################################
# Task 02
def main():
x = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/numbers.txt', 'r')
c = i = 0
for line in x:
if line.strip():
n = int(line)
c += n
i += 1
# print('{:.3f}'.format(c/n))
print(c/n)
x.close()
main();
<file_sep>#This tutorial originally created by <NAME> <EMAIL> and modified by Dr. Ali for educational purpose
# at Rider University
import pandas as pd
import datasist as ds #import datasist library
import numpy as np
train_df = pd.read_csv('train_data.csv')
test_df = pd.read_csv('test_data.csv')
# _________________________________Working with the structdata module___________________________________________________
# The structdata module contains numerous functions for working with structured data mostly in the Pandas DataFrame format.
# That is, you can use these functions to easily manipulate and analyze DataFrames.
#describe: We all know the describe function in Pandas
#print(train_df) #print all
#print(train_df.head()) #print the first 5 rows
#print(train_df.head(10)) # print the first n rows
# we decided to extend it to support full description of a dataset at a glance using datasist.
#print(ds.structdata.describe(train_df))
# check_train_test_set: This function is used to check the sampling strategy of two dataset.
# pass in the two dataset (train_df and test_df ), a common index (customer_id) and finally any feature or column present in both dataset.
#ds.structdata.check_train_test_set(train_df, test_df, index='Customer Id', col='Building Dimension')
# display_missing: You can check for the missing values in your dataset and
# display the result in the well formatted DataFrame using this function.
# print(ds.structdata.display_missing(train_df))
# get_cat_feats and get_num_feats: Just like their names,
# you can retrieve categorical and numerical features respectively as a Python list.
cat_feats = ds.structdata.get_cat_feats(train_df)
#print(cat_feats)
num_feats = ds.structdata.get_num_feats(train_df)
#print(num_feats)
# get_unique_counts: Ever wanted to check the number of unique classes in your categorical features before you decide what encoding scheme to use?
# well, you can use the get_unique_count function to easily do that.
#unique_count=ds.structdata.get_unique_counts(train_df)
#print(unique_count) #Will not work in Pycharm. Try in Jupyter.
# join_train_and_test: Most of the time when prototyping, you may want to concatenate both train and test set,
# and then apply some transformations to it. You can use the join_train_and_test function for that.
# It returns a concatenated dataset and the size of the train and test set for future splitting.
all_data, ntrain, ntest = ds.structdata.join_train_and_test(train_df, test_df)
#print("New size of combined data {}".format(all_data.shape))
#print("Old size of train data: {}".format(ntrain))
#print("Old size of test data: {}".format(ntest))
#later splitting after transformations
train = all_data[:ntrain]
test = all_data[ntrain:]
#____________________________________ Feature engineering with datasist.________________________________________________
# Feature Engineering is the act of extracting important features from raw data and
# transforming them into formats that are suitable for machine learning models.
# drop_missing: This function drops columns/features with a specified percentage of missing values.
#print(ds.structdata.display_missing(train_df))
# we’ll drop the column with 7.1 percent missing values (Date_of_Occupancy).
# Note: You should not drop a column/feature with so little missing values. The ideal thing to do is to fill it. We drop it here, just for demonstration purpose.
#new_train_df = ds.feature_engineering.drop_missing(train_df, percent=7.0)
#print(ds.structdata.display_missing(new_train_df))
# drop_redundant: This function is used to remove features with low or no variance.
# That is, features that contain the same value all through.
# We show a simple example using an artificial dataset.
df = pd.DataFrame({'a': [1,1,1,1,1,1,1], 'b': [2,3,4,5,6,7,8]})
#print(df)
# column a is redundant, that is it has the same value all through.
# We can drop this column automatically by just passing in the dataset to the drop_redundant function.
#df = ds.feature_engineering.drop_redundant(df)
#print(df)
# convert_dtypes: This function takes a DataFrame as argument and
# automatically type-cast the features to their correct data types.
data = {'Name':['Tom', 'nick', 'jack'],
'Age':['20', '21', '19'],
'Date of Birth': ['1999-11-17','20 Sept 1998','Wed Sep 19 14:55:02 2000']}
df = pd.DataFrame(data)
#print(df)
#let’s check the data types…
#print(df.dtypes)
# The features Age and Date of Birth are supposed to be integer and DateTime respectively,
# by passing this dataset to the convert_dtype function, this can be fixed automatically.
#df = ds.feature_engineering.convert_dtype(df)
#print(df.dtypes)
# fill_missing_cats: As the name implies, this function takes a DataFrame,
# and automatically detects categorical columns with missing values.
# It fills them using the mode. # From the dataset,
# we have two categorical features with missing values, these are Garden and Geo_Code.
#df = ds.feature_engineering.fill_missing_cats(train_df)
#print (ds.structdata.display_missing(df))
# fill_missing_nums: This is similar to the fill_missing_cats, except it works on numerical features and
# you can specify a filling strategy (mean, mode or median).
# From the dataset, we have two numerical features with missing values,
# these are Building Dimension and Date_of_Occupancy.
#df = ds.feature_engineering.fill_missing_num(train_df)
#print(ds.structdata.display_missing(df))
# log_transform: This function can help you log transform a set of features.
# It also display the before and after plot with level of skewness to help you
# decide if log transforming feature is what you really want.
# The feature Building Dimension is a right skewed, and we can transform it.
# Note: Columns passed to the log_transform function
# should not contain missing values, else it will throw an error.
#df = ds.feature_engineering.fill_missing_num(train_df)
#df = ds.feature_engineering.log_transform(df, columns=['Building Dimension'])
#_____________________________________WORKING WITH TIME BASED FEATURES__________________________________________________
# extract_dates: This function can extract specified features like day of the week,
# day of the year, hour, min and second of the day from a specified date feature.
new_train = pd.read_csv("Train.csv")
#print(new_train.head(3).T)
# Let’s demonstrate how easy it is to extract information from
# Placement — Time, Arrival at Destination — Time features using the extract_dates function.
# We specify that we want to extract just day of the week (dow) and hour of the day (hr).
date_cols = ['Placement - Time', 'Arrival at Destination - Time']
df = ds.timeseries.extract_dates(new_train, date_cols=date_cols, subset=['dow', 'hr'])
#print(df.head(3).T)
#dff=pd.DataFrame(df)
#dff.to_csv('Train_modified.csv')
# You will instead of 'Placement - Time', 'Arrival at Destination - Time' column, four new column:Placement - Time_dow ,
# Placement - Time_hr, Arrival at Destination - Time_dow, Arrival at Destination - Time_hr
# timeplot: The timeplot function can help you visualize a set features against a particular time feature.
# This can help you identify trends and patterns. To use this function, you can pass a set of numerical columns,
# and then specify the Date feature you want to plot against.
num_cols = ['Time from Pickup to Arrival', 'Destination Long', 'Pickup Long','Platform Type', 'Temperature']
# ds.timeseries.timeplot(new_train, num_cols=num_cols, time_col='Placement - Time')
# _______________________________Visualization__________________
# VISUALIZATION FOR CATEGORICAL FEATURES
# boxplot: This function makes a box plot of all numerical features against a specified categorical target column.
# A box plot (or box-and-whisker plot) shows the distribution of quantitative data in a way that
# facilitates comparisons between variables or across levels of a categorical variable
#ds.visualizations.boxplot(train_df, target='Claim')
# VISUALIZATION FOR NUMERICAL FEATURES
# histogram: This function makes a histogram plot of all numerical features in a dataset.
# This helps to show distribution of the features.
#fill the missing values first
#df = ds.feature_engineering.fill_missing_num(train_df)
#ds.visualizations.histogram(df)
# scatterplot: This function makes a scatter plot of all numerical features in a
# dataset against a specified numerical target. It helps to show the correlation between features.
#feats = ['Insured_Period', 'Residential', 'Building Dimension', 'Building_Type', 'Date_of_Occupancy']
#ds.visualizations.scatterplot(train_df,num_features=feats, target='Building Dimension',save_fig='ali.png')
#__________________Testing and comparing machine learning models with datasist____________
#import libraries and datasets
'''
import pandas as pd
import numpy as np
import datasist as ds
train = pd.read_csv('train_data.csv')
#test = pd.read_csv('test_data.csv')
# Next, we do some processing. First, we drop the ID column (Customer Id) and
# then we fill missing numerical and categorical features.
#drop the id column
train.drop(columns='Customer Id', axis=1, inplace=True)
#test.drop(columns='Customer Id', axis=1, inplace=True)
#fill missing values
train = ds.feature_engineering.fill_missing_cats(train)
train = ds.feature_engineering.fill_missing_num(train)
#test = ds.feature_engineering.fill_missing_cats(test)
#test = ds.feature_engineering.fill_missing_num(test)
#check the unique classes in each categorical feature
ds.structdata.class_count(train)
# We will label encode Geo_Code, since the unique classes is large, and one-hot-encode the rest.
import category_encoders as ce
# drop target column
target = train['Claim'].values
train.drop(columns='Claim', axis=1, inplace=True)
enc = ce.OrdinalEncoder(cols=['Geo_Code'])
enc.fit(train)
train_enc = enc.transform(train)
#test_enc = enc.transform(test)
#one-hot-encode the rest categorical features
hot_enc = ce.OneHotEncoder()
hot_enc.fit(train_enc)
train_enc = hot_enc.transform(train_enc)
#test_enc = hot_enc.transform(test_enc)
# Now we will split the
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
Xtrain, Xtest, ytrain, ytest = train_test_split(train_enc, target, test_size=0.3, random_state=1)
rf_classifier = RandomForestClassifier(n_estimators=20, max_depth=4)
rf_model=rf_classifier.fit(Xtrain,ytrain)
pred=rf_model.predict(Xtest)
ds.model.get_classification_report(pred,ytest)
'''
'''
# For Example I want to compare three ML models such as naive bayes, decision trees and svm
# compare_model: This model takes as argument multiple machine learning models
# and returns a plot showing each model’s performance.
# Now, let’s see this function in action. We will be comparing three models
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import LinearSVC
Xtrain, Xtest, ytrain, ytest = train_test_split(train_enc, target, test_size=0.3, random_state=1)
rf_classifier = RandomForestClassifier(n_estimators=20, max_depth=4)
nb_classifier = GaussianNB()
svm_classifier = LinearSVC()
classifiers = [rf_classifier, nb_classifier, svm_classifier]
models, scores = ds.model.compare_model(models_list=classifiers, x_train=Xtrain, y_train=ytrain, scoring_metric='accuracy')
'''<file_sep># import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from torch.autograd import Variable
import torch.nn as nn
# import warnings
# warnings.filterwarnings("ignore")
# Defining car prices
car_prices_array = [3, 4, 5, 6, 7, 8, 9]
car_prices_np = np.array(car_prices_array, dtype=np.float32)
# https://stackoverflow.com/questions/18691084/what-does-1-mean-in-numpy-reshape
car_prices_np = car_prices_np.reshape(-1, 1)
car_price_tensor = Variable(torch.from_numpy(car_prices_np))
#Defining car sales
number_of_car_sell_array = [7.5, 7, 6.5, 6, 5.5, 5, 4.5]
number_of_car_sell_np = np.array(number_of_car_sell_array, dtype=np.float32)
number_of_car_sell_np = number_of_car_sell_np.reshape(-1, 1)
number_of_car_sell_tensor = Variable(torch.from_numpy(car_prices_np))
# plt.scatter(car_prices_array, number_of_car_sell_array)
# plt.xlabel("Car Price $")
# plt.ylabel("Number of Car Sales")
# plt.title("Car Price VS # of Car Sales")
# plt.show()
class LinearRegression(nn.Module):
def __init__(self, input_size, output_size):
super(LinearRegression, self).__init__()
self.linear = nn.Linear(input_dim, output_dim)
def forward(self, x):
return self.linear(x)
# Model architecture
input_dim = 1
output_dim = 1
model = LinearRegression(input_dim, output_dim)
# MSE / Cost function
mse = nn.MSELoss()
# Optimization
learning_rate = 0.02
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)
#train model
lost_list = []
iteration_number = 301
for iteration in range(iteration_number):
# Optimization
optimizer.zero_grad()
# Forward to get output
results = model(car_price_tensor)
# Calculate Loss
loss = mse(results, number_of_car_sell_tensor)
# Backward prop
loss.backward()
# Updating parameters
optimizer.step()
# Store loss
lost_list.append(loss.data)
# Print loss
if (iteration % 50 == 0):
print('epoch {}, loss {}'.format(iteration, loss.data))
# plt.plot(range(iteration_number), lost_list)
# plt.xlabel("Number of Iterations")
# plt.ylabel("Loss")
# plt.show()
# Predict car price
predicted = model(car_price_tensor).data.numpy()
plt.scatter(car_prices_array, number_of_car_sell_array, label="original data", color="red")
plt.scatter(car_prices_array, predicted, label="predicted data", color="blue")
plt.legend()
plt.xlabel("Car Price $")
plt.ylabel("Number of Car Sell")
plt.title("Original vs Predicted values")
plt.show()
class One():
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def oneMethod(self, j):
return self.x + j
oneI = One(2, 5, 7)
print(oneI.x)
class Three():
def __init__(self, j = 20):
self.j = j
def returnJ(self):
return self.j
class Two(One):
def __init__(self, x, y, z, l):
super().__init__(x, y, z)
self.l = 9
self.t = Three(3)
def twoMethod(self):
return self.x + self.y + self.z + self.l
def printParam(self):
print(self.x, self.y, self.z, self.l)
two = Two(1, 2, 3, 4)
print(two.t.returnJ())
class Net():
def __init__(self):
# First 2D convolutional layer, taking in 1 input channel (image),
# outputting 32 convolutional features, with a square kernel size of 3
self.conv1 = 1
# Second 2D convolutional layer, taking in the 32 input layers,
# outputting 64 convolutional features, with a square kernel size of 3
self.conv2 = 2
# Designed to ensure that adjacent pixels are either all 0s or all active
# with an input probability
self.dropout1 = 3
self.dropout2 = 4
# First fully connected layer
self.fc1 = 5
# Second fully connected layer that outputs our 10 labels
self.fc2 = 6
test = Net()
print(test.conv1)<file_sep>public class sandbox {
public static void main(String[] args) {
short totalPay, basePay = 500, bonus = 1000;
totalPay = (short)(basePay + bonus);
System.out.println(totalPay);
// Challenge #2
System.out.println("Challenge #2 ########################################");
float alexa;
double siri = 3.5;
alexa = (float)(siri);
System.out.println(alexa + "toads");
// Programming Challenge #2 -
System.out.println("Programming Challenge #2 ########################################");
int fullPrice = 59;
double sale = 0.2;
System.out.println("The retail business sells product x at $" + fullPrice);
System.out.println("The retail business sells product x at $" + (fullPrice - (fullPrice * 0.2)) + " after the 20% sale");
System.out.println(fullPrice - (fullPrice * sale));
// Programming Challenge #2 - Sales Prediction
System.out.println("Programming Challenge #2 - Sales Prediction ########################################");
double percentOfTotalSales = 0.62;
double companyTotalSales = 4600000;
System.out.println("The total predicted sales of the east coast company is: " + (companyTotalSales * percentOfTotalSales));
// Programming Challenge #2 - Land Calculation
System.out.println("Programming Challenge #2 - Land Calculation ########################################");
int acre = 43560;
int totalLand = 389767;
System.out.println(totalLand / acre);
}
}
<file_sep># <NAME>, CSC 110, Prof Ali, 10/24/19
# Task 01
def main():
# x = open('filename.txt', 'w')
x = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/filename.txt', 'w')
x.write('<NAME>')
x.close()
# print(type(x))
main();
####################################################################################
# Task 02
def main():
x = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/filename.txt', 'r')
print(x.read())
x.close()
main();
####################################################################################
# Task 03
def main():
x = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/names.txt', 'r')
i = 0
n1 = x.readline()
while n1 != '':
i += 1
n1 = x.readline()
print(i)
x.close()
main();
# x = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/numbers.txt', 'r')
# n1 = int(x.readline())
# n2 = int(x.readline())
# n3 = int(x.readline())
# n4 = int(x.readline())
#
# print(n1, n2, n3, n4)
######
# Task 03 Redo
#
# x = open('/Users/Ryan/Documents/GitHub/csc110/In_Class/Mod6Lab/names.txt', 'r')
#
# y = x.readline()
#
# for i in :
#
# y = x.readline();
#
# i+=1
#
# print(i)
<file_sep>me());
// System.out.println(testOne.getDepartment());
// System.out.println(testOne.getId<file_sep>#!/usr/bin/env python
# coding: utf-8
# ### Load Programs
# In[1]:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# ### File Upload
# In[4]:
# Label File Tag
# file = 'Rider University B (40.283093852918036 -74.74257493436426) Primary 06_01_2019 08_31_2019'
# import file
PA = pd.read_csv("data.csv")
date=[]
time=[]
B=[]
C=[]
D=[]
E=[]
F=[]
G=[]
H=[]
I=[]
J=[]
for index, row in PA.iterrows():
split=row['created_at'].split()
date.append(split[0])
time.append(split[1])
B.append(row['entry_id'])
C.append(row['PM1.0_CF_ATM_ug/m3'])
D.append(row['PM2.5_CF_ATM_ug/m3'])
E.append(row['PM10.0_CF_ATM_ug/m3'])
F.append(row['UptimeMinutes'])
G.append(row['ADC'])
H.append(row['Temperature_F'])
I.append(row['Humidity_%'])
J.append(row['PM2.5_CF_1_ug/m3'])
data_modify={'date':date, 'time':time,'entry_id':B, 'PM1.0_CF_ATM_ug/m3':C,'PM2.5_CF_ATM_ug/m3':D, 'PM10.0_CF_ATM_ug/m3':E,'UptimeMinutes':F,'ADC':G,'Temperature_F':H,'Humidity_%':I,'PM2.5_CF_1_ug/m3':J}
df=pd.DataFrame(data_modify)
df.to_csv('data_modified.csv')
PB = pd.read_csv("data_modified.csv")
# show data with limited rows called head
PB.head(5)
# ### Histogram
# In[50]:
# bin data
bins = [0, 1, 2.5, 5, 7.5, 10, 15, 20, 25, 35, 40]
# build Histogram for Column Heading in csv
plt.hist(PB['PM1.0_CF_ATM_ug/m3'], bins=bins, color='#C73354')
# plt.hist(PA['PM2.5_CF_ATM_ug/m3'], bins=bins, color='#C73354')
# plt.hist(PA['PM10.0_CF_ATM_ug/m3'], bins=bins, color='#C73354')
# plot title and formatting
plt.title('PM1.0 Distribution', fontdict={'fontweight': 'bold', 'fontsize': 18})
# Adding a x and y axis label
plt.xlabel('Concentration ug m-3', fontdict={'fontname': 'Times New Roman', 'fontsize': 18})
plt.ylabel('Frequency of Concentrations', fontdict={'fontname': 'Times New Roman', 'fontsize': 18})
# show the begnning and end by intervals of an value
plt.xticks()
plt.yticks()
# [0,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000])
# plot legend
# plt.legend()
plt.show()
# In[53]:
# bin data
bins = [0, 1, 2.5, 5, 7.5, 10, 15, 20, 25, 35, 40]
# build Histogram for Column Heading in csv
# plt.hist(PA['PM1.0_CF_ATM_ug/m3'], bins=bins, color='#C73354')
plt.hist(PB['PM2.5_CF_ATM_ug/m3'], bins=bins, color='#C73354')
# plt.hist(PA['PM10.0_CF_ATM_ug/m3'], bins=bins, color='#C73354')
# plot title and formatting
plt.title('PM2.5 Distribution', fontdict={'fontweight': 'bold', 'fontsize': 18})
# Adding a x and y axis label
plt.xlabel('Concentration ug m-3', fontdict={'fontname': 'Times New Roman', 'fontsize': 18})
plt.ylabel('Frequency of Concentrations', fontdict={'fontname': 'Times New Roman', 'fontsize': 18})
# show the begnning and end by intervals of an value
plt.xticks()
plt.yticks()
# [0,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000])
# plot legend
# plt.legend()
plt.show()
# In[3]:
# bin data
bins = [0, 1, 2.5, 5, 7.5, 10, 15, 20, 25, 35, 40]
# build Histogram for Column Heading in csv
# plt.hist(PA['PM1.0_CF_ATM_ug/m3'], bins=bins, color='#C73354')
# plt.hist(PA['PM2.5_CF_ATM_ug/m3'], bins=bins, color='#C73354')
plt.hist(PB['PM10.0_CF_ATM_ug/m3'], bins=bins, color='#C73354')
# plot title and formatting
plt.title('PM10.0 Distribution', fontdict={'fontweight': 'bold', 'fontsize': 18})
# Adding a x and y axis label
plt.xlabel('Concentration ug m-3', fontdict={'fontname': 'Times New Roman', 'fontsize': 18})
plt.ylabel('Frequency of Concentrations', fontdict={'fontname': 'Times New Roman', 'fontsize': 18})
# show the begnning and end by intervals of an value
plt.xticks()
plt.yticks()
# [0,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000])
# plot legend
# plt.legend()
plt.show()
<file_sep># Acadamia
### CS & a bit more
Centralization of academic & hobby work
Not the best way to organize, but it gets the job done.<file_sep># <NAME> | CSC 101 | 9/18/19
# Updated 9/24/19
import turtle
t = turtle.Turtle()
t.hideturtle()
t.begin_fill()
t.penup()
t.goto(300, 0)
t.goto(300, 130)
t.goto(130, 130)
t.goto(130, 260)
t.goto(0, 260)
t.goto(0, 0)
# t.goto(300, 0)
# t.goto(300,200)
# t.goto(0, 200)
# t.goto(0, 0)
t.fillcolor('#4b99e0')
t.end_fill()
turtle.exitonclick()
<file_sep># <NAME>, <NAME>, 11/7/19, Test 2
#
def main():
def instruction():
print('This program ask user for an integer number and checks the given number is prime or not.')
instruction();
x = input("Press 'y' or 'Y' to continue, anything else to exit: ")
while x == 'y' or x == 'Y':
y = int(input('Enter an integer number: '))
def prime_function(x):
for i in range(2, x):
if x % i == 0:
print(x ,'is not a prime number')
break;
else:
print(x, 'is a prime number')
break;
prime_function(y)
x = input("Press 'y' or 'Y' to continue, anything else to exit: ")
main();
# Bad because I can input 9 and it will output as both prime and not prime
# because 9 % 3 = 0.
<file_sep>str = "this is string example....wow!!!"
print ("str.center(40, 'a') : ", str.center(60, 'a'))
<file_sep>/**
* a1
*
* <NAME>, CSC 120, Assignment 1
*
*/
import java.util.Scanner;
public class a1 {
public static void main(final String[] args) {
/**
* Test Average section of Assignment 1 - Section 1
*/
int testOne, testTwo, testThree;
final Scanner keyboard = new Scanner(System.in);
System.out.println("Test 1 score:");
testOne = keyboard.nextInt();
System.out.println("Test 2 score:");
testTwo = keyboard.nextInt();
System.out.println("Test 1 score:");
testThree = keyboard.nextInt();
System.out.printf("Test one score: %d%nTest two score: %d%nTest three score: %d%n", testOne, testTwo, testThree);
System.out.println("The average test score is: " + ((testOne + testTwo + testThree) / 3) );
stringManipulator();
restaurantBill();
wordGame();
}
public static void stringManipulator() {
/**
* String Manipulator section of Assignment 1 - Section 2
*/
String favCity;
final Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the name of your favorite city:");
favCity = keyboard.nextLine();
System.out.println("Length: " + favCity.length());
System.out.println("Uppercase: " + favCity.toUpperCase());
System.out.println("Lowercase: " + favCity.toLowerCase());
System.out.println("First letter: " + favCity.charAt(0));
}
public static void restaurantBill() {
/**
* Restaurant Bill section of Assignment 1 - Section 3
*/
double bill, totalBill, tax, tip;
final double taxRate = 0.565, tipRate = 0.2;
final Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the bill: ");
bill = keyboard.nextDouble();
tax = bill * taxRate;
tip = (bill + tax) * tipRate;
totalBill = bill + tax + tip;
System.out.println("Your tax is: " + tax);
System.out.println("Your tip is: " + tip);
System.out.println("Your total bill is: " + totalBill);
}
public static void wordGame() {
/**
* Word Game section of Assignment 1 - Section 4
*/
int age;
String name, nameOfCity, nameOfCollege, profession, animal, petName;
final Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a name: ");
name = keyboard.nextLine();
System.out.println("Enter an age: ");
age = keyboard.nextInt();
// Scanner.nextInt() does not consume '\n' character
keyboard.nextLine();
System.out.println("Enter a name of a city: ");
nameOfCity = keyboard.nextLine();
System.out.println("Enter a name of a college: ");
nameOfCollege = keyboard.nextLine();
System.out.println("Enter a profession: ");
profession = keyboard.nextLine();
System.out.println("Enter an animal: ");
animal = keyboard.nextLine();
System.out.println("Enter a pet name: ");
petName = keyboard.nextLine();
System.out.printf("There once was a person named %s who lived in %s. At the age of %d, %s went to college at %s. %s graduated and went back to work as a %s. Then, %s adopted an %s named %s. They both lived happily ever after!", name, nameOfCity, age, name, nameOfCollege, name, profession, name, animal, petName);
}
}<file_sep>#Write a program in python that displays your name, address, and telephone number
from textwrap import wrap
school = 'Rider Unviersity'
name = '<NAME>'
csc = 'CSC 110 Computer Science I'
assignment = 'Assignment Number 01 '
lines = '\n Rider University \n <NAME> \n CSC 110 Computer Science I \n Assignment Number 01'
test = 'asdlfkadf'
width = 30
print ('-' * width)
for line in wrap(lines, width):
print('| {0:^{1}} |'.format(line, width))
print('-' * width)
#print('-' * 70)
#print('{:^24s}'.format(school + '\n' + csc + '\n' + assignment + '\n' + name))
print(lines)
<file_sep># <NAME>, redo, better code and understanding of test2
# declare 3 functions: main, instruction, and prime_funciton
def main():
def instruction():
print('This program asks the user for an integer and verifies whether it is prime or not')
instruction();
x = input('Enter y or Y to continue');
while x == 'y' or x == 'Y':
y = int(input('Enter an integer:'))
def prime_function(x):
r = 0;
for i in range(2, x):
# print(i)
if x % i == 0 and r == 0:
# print('beepboop')
r = 1;
print(x, 'is not a prime number');
elif x % i != 0 and r == 0:
r = 1;
print(x, 'is a prime number');
# It is only determining if the input is divisible by 2, not the following
# numbers in the for loop. This is not what a prime number is.
prime_function(y)
x = input('Enter y or Y to continue');
main();
#
# x = 0;
# for i in range(6):
# print(i)
# if i == i and x == 0:
# print('toads');
# x += 1;
<file_sep>public class test {
public static void main(String[] args) {
// int x = 0;
// for (int count = 10; count <= 21; count++) {
// // System.out.println(count);
// System.out.println(x++);
// }
toadies();
}
public static void toadies() {
int x = 10;
switch (x) {
case 10:
x += 15;
break;
case 12:
x -= 5;
default:
break;
}
System.out.println(x);
}
}<file_sep># <NAME>, CSC 110, Prof Ali, 10/31/19
# Task 01
#
import matplotlib.pyplot as plt
def main():
programmingLanguages = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = ['22.2', '17.6', '8.8', '8', '7.7', '6.7']
programmingLanguages.reverse()
popularity.reverse()
plt.bar(programmingLanguages, popularity)
plt.show()
main();
<file_sep># <NAME>, CSC 110, 15 October 2019, Prof Ali
# Task 1
#
max_temp = 102.5
#Get the temp
temperature = float(input("Enter the substance's Celcius temperature: "))
while temperature > max_temp:
print('The temperature is too high.')
print('Turn the thermostat down and wait')
print('5 minutes. Then take the temperature')
print('again and enter it.')
temperature = float(input('Enter the new Celcius temperature: '))
print('The temperature is acceptable.')
print('Check it again in 15 minutes.')
######################################################
# Task 2
max = 5
total = 0.0
print('This program calculates the total of')
print(max, 'numbers you will enter.')
for counter in range(max):
number = int(input('Enter a number: '))
total += number
print('The total is', total)
######################################################
# Task 3
for x in range(0, 1001, 10):
print(x)
# <NAME>, CSC 110, 15 October 2019, Prof Ali
#Task 1
#
<file_sep># 110
Comp Sci
<file_sep>#Create two variables
top_speed = 160
distance = 300
# Display the values referenced by the variables
print('The top speed is')
print(top_speed)
print('The distance traveled is')
print(distance)
############################################
val = 99
print 'the value of val is: ', val
############################################
name = '<NAME>'
print 'My name is: ', name
############################################
############################################
<file_sep>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
####
PA = pd.read_csv("./base/pre.csv")
date= []
time= []
B= []
C= []
D= []
E= []
F= []
G= []
H= []
I= []
J= []
for index, row in PA.iterrows():
split=row['Team'].split()
print('toads')<file_sep># <NAME> , CSC 110, 9/24/19
#
# Task 1
x = float(input('Number: '))
if x > 100:
y = 20
z = 40
print(y,z)
# Task 2
a = 1
if a < 10:
b = 20
else:
b = 99
# Task 3
x = int(input('Enter your first number: '))
y = int(input('Enter your second number: '))
if y<=0:
print('Division by zero is not possible. Please run the program again and enter a number other than zero.')
else:
print('The quotient of', x, 'divided by', y, 'is: ', x/y)
##################### Extra
# x = float(245.334)
# print('The quotient of {} is '.format(10/3, '.2f'))
#
#
# print(format(20/3, '.3f'))
####
4:30 October 1. Science building meet professor
print('Room Capacity Test')
print('---- -------- ----')
n = 10
x = 1
while x<=n:
sum = sum + x
x = x + 1
print(sum)
<file_sep>import random
# The Coin class simulates a coin that can
# be flipped.
class Coin:
# The __init__ method initializes the
# sideup data attribute with 'Heads'.
def __init__(self):
self.sideup = 'Heads'
# The toss method generates a random number
# in the range of 0 through 1. If the number
# is 0, then sideup is set to 'Heads'.
# Otherwise, sideup is set to 'Tails'.
def toss(self):
if random.randint(0, 1) == 0:
self.sideup = 'Heads'
else:
self.sideup = 'Tails'
# The get_sideup method returns the value
# referenced by sideup.
def get_sideup(self):
return self.sideup
# The main function.
def main():
# Create an object from the Coin class.
my_coin = Coin()
# Display the side of the coin that is facing up.
print('This side is up:', my_coin.get_sideup())
# Toss the coin.
print('I am tossing the coin...')
my_coin.toss()
# Display the side of the coin that is facing up.
print('This side is up:', my_coin.get_sideup())
# Call the main function.
main()
# how to create exe file so you do not have to give someone your source code and instead just give someone your program.
# write a step-by-step of what you did to create an exe file and then email it to him.\
# pyinstaller is what ali used.
<file_sep>class Net():
def __init__(self):
# First 2D convolutional layer, taking in 1 input channel (image),
# outputting 32 convolutional features, with a square kernel size of 3
self.conv1 = 1
# Second 2D convolutional layer, taking in the 32 input layers,
# outputting 64 convolutional features, with a square kernel size of 3
self.conv2 = 2
# Designed to ensure that adjacent pixels are either all 0s or all active
# with an input probability
self.dropout1 = 3
self.dropout2 = 4
# First fully connected layer
self.fc1 = 5
# Second fully connected layer that outputs our 10 labels
self.fc2 = 6
test = Net()
print(test.conv1)<file_sep>public class tClass {
int x;
int y;
public tClass(int _x, int _y) {
x = _x;
y = _y;
}
public int getX() {
return x;
}
}
<file_sep># <NAME>, CSC 110, 15 October 2019, Prof Ali
#Task 1
#
product = float(input('Enter a number:'))
while product < 100:
product *= 10
# Will terminate print statement if the product is > 100.
# if product > 100:
# break
print('{:.3f}'.format(product))
######################################################
# Task 2
base_size = 8
for i in range(base_size):
for c in range(i - 1):
print('*', end='')
print()
######################################################
# Task 3
n = int(input('Enter a number: '))
x = 0
for i in range(0, n + 1, 2):
x +=i
print(x)
for hours in range(24):
for min in range(60):
for sec in range(60):
print(hours, min, sec)
<file_sep># Test 1 Lab, <NAME>, CSC 110, Prof Ali, 10/8/19
#
hours = int(input('Enter hour: '))
if hours >= 1 and hours <= 11:
print(hours, 'AM')
elif hours == 12:
print(hours, 'PM')
elif hours >= 13 and hours <= 23:
print(hours - 12, 'PM')
elif hours == 24:
print(hours - 12, 'AM')
else:
print('You have entered an invalid value')
<file_sep># CSC 410 Data Structure / Big Data<file_sep># <NAME>, CSC 110, Prof Ali, Dec 5 2019
# Problem A | Turing Machine
#
# Power of 2 ------ 2 4 8 16 32 64
def main():
x = int(input('Enter an integer less than 1000: '))
y = x * '0'
z = 2
def orig(z):
if z < 1000:
while z < 1000:
for i in range(1000):
print(z**i)
print(x, 'Accepted')
for i in range(x):
aa = (y[i] * (i + 1))
if len(aa) == range(z**z):
bb = 'Accepted'
else:
bb = 'Rejected'
# print(aa, bb)
# print(z**z)
orig(2)
main();
<file_sep># # <NAME>, CSC 110, Prof Ali, 10/19/2019
# # Task 2
# #
#
# def main():
# x = int(input('Enter a number in kilometers: '))
# print('This formula converts kilometers to miles.')
#
# def kilometerConveter(y):
# y *= 0.6214
# print(x, 'miles is', '{:.2f}'.format(y), 'kilometers.')
#
#
# kilometerConveter(x);
#
# main()
#
#
def main():
x = int(input('Enter a number in kilometers: '))
print('This function / formula will convert to miles.')
def kilometerConverter(y):
y *= 0.6214
print(x, 'miles is', '{:.2f}'.format(y), 'kilometers.')
kilometerConverter(x);
main()
x = int(input('Enter a number in kilometers: '))
def main():
print('This formula will convert miles to kilometers')
kilometerConverter(x)
def kilometerConverter(y):
y *= 0.6214
print(x, 'miles is', '{:.2f}'.format(y), 'kilometers.')
main()
<file_sep>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_xlim3d(0, 3)
ax.set_ylim3d(0, 3)
ax.set_zlim3d(0, 3)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
# ax.quiver(x, y ,z, x, y, z) first 3 param are origin definition, following 3 are vector definition
# ax.quiver(0, 0, 0, 1, 1, 1, length = 0.5, normalize = True)
# ax.quiver(0, 0, 0, 1, 2, 0, length=0.5)
# ax.quiver(0, 1, 0, 1, 2, 0)
# ax.quiver(0, 2, 0, 1, 2, 0)
ax.quiver(0, 0, 0, 1,-1,1)
ax.quiver(0, 0, 0, 0, 1, -1)
ax.quiver(0, 0, 0, -1, 0, 1)
plt.show()<file_sep># <NAME>, CSC 110, Prof Ali, 10/26/19
# Question 1
#
import random
def main():
# MAC
x = open('/Users/Ryan/Documents/GitHub/csc110/Assignments/random.txt', 'w')
# WINDOWS
# x = open('D:\Github\CSC110\Assignments/random.txt', 'w')
y = int(input('How many random numbers do you want this file to hold? '))
for z in range(y):
i = str(random.randrange(1, 300))
x.write(i + '\n')
x.close()
main();
####################################################################################################
# Question 2
def main():
# MAC
x = open('/Users/Ryan/Documents/GitHub/csc110/Assignments/random.txt', 'r')
h = open('/Users/Ryan/Documents/GitHub/csc110/Assignments/random.txt', 'r')
# WINDOWS
# x = open('D:\Github\CSC110\Assignments/random.txt', 'r')
# h = open('D:\Github\CSC110\Assignments/random.txt', 'r')
c = i = 0
print(x.read())
# Puts cursor back to beginning
x.seek(0)
for line in x:
if line.strip():
n = int(line)
c += n
i += 1
print('The sum of these numbers is: ', c)
print('The number of random numbers read from the file is: ', i)
x.close()
main();
<file_sep>import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans
# from sklearn.preprocessing import MinMaxScaler
df = pd.read_csv("exoplanets_small.csv")
df.head(10)
# print(df)
plt.scatter(df.Tday, df.Distance)
plt.show()<file_sep># <NAME>, CSC 110, Prof Ali, November 12 2019
# Task 1
#
def main():
x = input('Enter your first name: ')
y = input('Enter your middle name: ')
z = input('Enter your last name: ')
print(x[0], y[0], z[0])
main();
def main():
# Extra credit if all the text is lowercase
x = input('Enter your name, first characters should be upper case:').split()
# Comprehends only uppercase text
# for i in x:
# print(i)
# if i.isupper():
# print(i+'.', end='');
# Comprehends lower and uppercase text
for word in x:
y = word[0].upper()
print(y + '.' , end = '')
# List comprehension syntax, same code as above.
# [print(word[0] + '.' , end = '') for word in x]
main();
######################################################################
# Task 2
def main():
x = input('Enter single-digit numbers with no seperators:')
# y = [int(i) for i in x]
# print(sum(y))
total = 0
for i in x:
total += int(i);
print(total)
main();
<file_sep># <NAME>, CSC 110, Prof Ali, 11/14/19, Mod 8 Lab 2
# Task 01
#
def main():
values = 'one$two$three$four'
newValues = values.split('$')
print(newValues);
main();
##############################################################################
# Task 02
import calendar as c
def main():
# I doubt this is how he wanted, it.
x = input('Enter the date in mm/dd/yyyy syntax: ')
y = x.split('/')
# print(y[0])
print(c.month_name[int(y[0])], y[1], y[2])
main();
def main():
x = input('Enter the date in mm/dd/yyyy syntax: ')
y = x.split('/')
sample_list = values.split('/')
print(sample_list[1])
if int(sample_list[1]) == 1:
print('January', end = '')
main();
##############################################################################
# Task 03
def main():
x = {'a':1, 'b':2, 'c':3}
print(x)
main();
##############################################################################
# Task 04
def main():
dct = {'Jim':1, 'Ryan':2, 'Jared':3, 'Leo':4}
if 'Jim' in dct:
del dct['Jim']
print(dct)
main();
x = {'a':'1', 'b':'2', 'c':'3'}
print(x[1])
stuff = {1:'aaa', 2:'bbb', 3:'ccc'}
print(stuff[3])
<file_sep># <NAME>, CSC 110, Prof Ali, 10/22/19
# Task 01
#
def main():
kilometers = int(input('Enter the distance in kilometers: '))
print('This program converts miles to kilometers.')
def miles(x):
return x * 0.6214
print(kilometers,' kilometers is equal to {:.2f} miles'.format(miles(kilometers)))
main();
####################################################################
# Task 02
def main():
print('Enter 5 test scores')
t1 = int(input('Test Score 1: '))
t2 = int(input('Test Score 2: '))
t3 = int(input('Test Score 3: '))
t4 = int(input('Test Score 4: '))
t5 = int(input('Test Score 5: '))
def calc_average(t1, t2, t3, t4, t5):
return (t1 + t2 + t3 + t4 +t5) / 5
def determine_grade(testScore):
if testScore <=100 and testScore >=90:
return ('A')
elif testScore <=89 and testScore >=80:
return ('B')
elif testScore <=79 and testScore >=70:
return ('C')
elif testScore <=69 and testScore >=60:
return ('D')
elif testScore <=59:
return('F')
print('Your test average is {:.2f}'.format(calc_average(t1, t2, t3, t4, t5)))
print('Your test 1 letter grade is: ' , determine_grade(t1))
print('Your test 2 letter grade is: ' , determine_grade(t2))
print('Your test 3 letter grade is: ' , determine_grade(t3))
print('Your test 4 letter grade is: ' , determine_grade(t4))
print('Your test 5 letter grade is: ' , determine_grade(t5))
main();
<file_sep># <NAME>, CSC 110, 10/10/19, Prof Ali
#
# Assignment 1
x = 0
for x in range(1, 10, 2):
y = "*" * x
print('{:^10}'.format(y))
x += 1;
if x == 10:
for x in range(7, 0 , -2):
y = '*' * x
print('{:^10}'.format(y))
x -= - 1
##############################################
# Assignment 2
n = int(input('Give me a non negative integer to factorialize: '))
# n = 5
fac = 1
if n < 0 or isinstance(n, int) != True:
print('Give me a non negative integer...')
for i in range(1, n + 1):
fac *= i
print(fac)
##############################################
# Assignment 3
n = int(input('Give me an integer: '))
# n = 5
ans = 0
for i in range(1, n + 1):
# print(i)
ans += (i / n)
n -= 1
# n = 1
# ans += (i / n -1)
print('{0:.3f}'.format(ans))
<file_sep># <NAME> , CSC 110, 10/1/19
# Task 1
base_hours = 40
ot_multiplier = 1.5
hours = float(input('Enter the number of hours worked: '))
pay_rate = float(input('Enter the hourly pay rate: '))
if hours > base_hours:
overtime_hours = hours - base_hours
overtime_pay = overtime_hours * pay_rate * ot_multiplier
gross_pay = base_hours * pay_rate + overtime_pay
else:
gross_pay = hours * pay_rate
if gross_pay > 100:
net_pay = gross_pay - 15
print('The gross pay is $', format(gross_pay, ',.2f'), sep='')
print('The net pay is $', format(net_pay,',.2f'))
# Task 2
base_hours = 40
ot_multiplier = 1.5
hours = float(input('Enter the number of hours worked: '))
pay_rate = float(input('Enter the hourly pay rate: '))
if hours > base_hours:
overtime_hours = hours - base_hours
overtime_pay = overtime_hours * pay_rate * ot_multiplier
gross_pay = base_hours * pay_rate + overtime_pay
else:
gross_pay = hours * pay_rate
medicareCost = gross_pay * .029
socialSecurityCost = gross_pay * .124
if gross_pay > 100:
net_pay = ((gross_pay - medicareCost) - socialSecurityCost - 15)
print('The gross pay is $', format(gross_pay, ',.2f'), sep='')
print('The net pay is $', format(net_pay,',.2f'))
# Task 3
x = int(input('Give me an integer'))
if x % 2 == 0:
print('Even number')
else:
print('Odd Number')
####################################
elif x % 2 != 0:
print('Odd number')
else:
print('Whole number pls')
elif x != int:
print('fake')
<file_sep># <NAME>, CSC 110, Prof Ali, Final, 12/11
# Lab
#
# Write a python program that reads the test.txt file’s contents, counts and
# displays the number of vowels and the number of consonants it contains.
def main():
x = open('/Users/Ryan/Documents/GitHub/csc110/test.txt', 'r')
vowelCount = consCount = 0;
vowels = ['a', 'e', 'i', 'o', 'u']
# vowels = 'a'
y = x.read();
# z = y.split();
for i in y:
if i in vowels:
vowelCount += 1;
print(i)
elif i not in vowels:
consCount += 1;
print('There are', vowelCount, 'vowels.');
print('There are', consCount, 'consonats.');
# print(vowels)
main();
<file_sep>post = 'post.csv'
f = open(post, 'w+')
f.close()<file_sep>import java.util.Scanner;
/**
* test2
*/
public class test2 {
public static void main(String[] args) {
// System.out.println("toaders");
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a name: ");
String uName = keyboard.nextLine();
System.out.println("Hello" + uName);
}
}<file_sep># <NAME> | Comp Sci 101 | 9/17/19
#answer = float(input('Enter how many shares Ali purchased: '))
answer = float(input('Enter how many shares Ali purchased: '))
#answer = 1000
print('The amount of commission Ali paid to his broker: ${:5,.2f}'.format(answer * 30 * .025))
print('The net amount of money Ali paid for his stock including commission: ${:5,.2f}'.format((answer * 30) + (answer * 30 * .025)))
print('The amount of commission Ali paid his broker when he sold the stock: ${:5,.2f}'.format(answer * .025 * 45))
print('The net amount that Ali received by selling the stock including the cost of commission: ${:5,.2f}'.format(45 * answer - (answer * .025 * 45)))
print('Ali profit made: ${:5,.2f}'.format(45 * answer - (answer * .025 * 45) - ((answer * 30) + (answer * 30 * .025))))
<file_sep># <NAME>
# Hello professor
width = 70
str = '|'
str1 = 'Rider University'
str2 = 'CSC 110 Computer Science I'
str3 = 'Assignment Number 01'
str4 = 'Name: <NAME>'
print('-'*width)
print (str.ljust(0,), str1.center(66,), str.rjust(0))
print (str.ljust(0,), str2.center(66,), str.rjust(0))
print (str.ljust(0,), str3.center(66,), str.rjust(0))
print (str.ljust(0,), str4.center(66,), str.rjust(0))
print('-'*width)
<file_sep># <NAME>, CSC 110, Prof Ali, 11/1/19
# assignment07 task 02
#
def main():
# WINDOWS
x = open('D:\Github\CSC110\Assignments\lin_assignment07\lottery.txt', 'r')
#MAC
# x = open('/Users/Ryan/Documents/GitHub/csc110/Assignments/lin_assignment07/lottery.txt', 'r')
newNumbers = [i.rstrip('\n') for i in x]
# for i in x:
# z = i.rstrip('\n')
# newNumbers.append(z)
print(newNumbers)
# print(type(newNumbers))
x.close();
main();
<file_sep># Variables to represent the base hours and
# the overtime multiplier.
base_hours = 40
ot_multiplier = 1.5
hours = float(input('Enter the number of hours worked: '))
pay_rate = float(input('Enter the hourly pay rate: '))
if hours > base_hours:
overtime_hours = hours - base_hours
overtime_pay = overtime_hours * pay_rate * ot_multiplier
gross_pay = base_hours * pay_rate + overtime_pay
else:
gross_pay = hours * pay_rate
medicareCost = gross_pay * .029
socialSecurityCost = gross_pay * .124
if gross_pay > 100:
net_pay = ((gross_pay - medicareCost) - socialSecurityCost - 15)
print('The gross pay is $', format(gross_pay, ',.2f'), sep='')
print('The net pay is $', format(net_pay,',.2f'))
<file_sep>cis200
Professor Taylor
<file_sep>import numpy as np
import matplotlib.pyplot as plt
import sys
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
print(sys.path)<file_sep>#Orthogonal Matrix:
# QT == Q^-1
# QQT == I
from numpy import array
from numpy import linalg
# from scipy import linalg
U = array([
[-0.2298477, 0.88346102, 0.40824829],
[-0.52474482, 0.24078249, -0.81649658],
[-0.81964194, -0.40189603, 0.40824829]
])
VT = array([
[-0.61962948, -0.78489445],
[-0.78489445, 0.61962948]
])
BB = array([
[-0.2298477],
[-0.52474482],
[-0.81964194]
])
# Standard Orthogonal Matrix
C = array([
[1/3, 2/3, -2/3],
[-2/3, 2/3, 1/3],
[2/3, 1/3, 2/3]
])
# Matrix that produces a diagonal but is not normalized, therefore is not orthogonal
D = array([
[1, 2, -2],
[-2, 2, 1],
[2, 1, 2]
])
print(U.dot(U.transpose()))
print(VT.dot(VT.transpose()))
# print(linalg.inv(C))
<file_sep>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# PA = pd.read_csv("data.csv")
# df = pd.DataFrame([{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}])
df = pd.read_csv("data.csv")
date = []
B = []
C = []
D = []
E = []
F = []
G = []
H = []
I = []
J = []
for index, row in df.iterrows():
print(row['ADC'])
# for index, row in PA.iterrows():
# split = row['created_at'].split()
# print(split)<file_sep># <NAME> , 9/24/19, CSC 110
#
test1 = float(input('Enter the first test score: '))
test2 = float(input('Enter the second test score: '))
test3 = float(input('Enter the third test score: '))
sum = test1 + test2 + test3
avg = sum/3
print('The sum of the score is ', sum)
print('The average of the score is ', avg)
# Task 1
import turtle
turtle.hideturtle()
turtle.fillcolor('#00ff00')
turtle.begin_fill()
turtle.goto(150, 0)
turtle.goto(150, 200)
turtle.goto(-150, 200)
turtle.goto(-150, 0)
turtle.goto(0, 0)
turtle.end_fill()
turtle.penup()
turtle.hideturtle()
turtle.fillcolor('red')
turtle.begin_fill()
turtle.goto(0,20)
turtle.circle(75)
turtle.end_fill()
turtle.exitonclick()
# EXTRA CREDITTTT
# Download .csv file
# Install pandas module
# Copy a couple columns into another csv file
# 2 / 3 weeks
# this is extra credit
<file_sep>public class t {
public static void main(String[] args) {
tClass abc = new tClass(5, 6);
System.out.println(abc.x);
System.out.println(abc.getX() + "toads");
}
}
<file_sep>#<NAME> | CIS 101 | 9/17/19
import turtle
t = turtle.Turtle()
t.hideturtle()
t.begin_fill()
t.forward(100)
t.right(90)
t.forward(100)
t.left(90)
t.forward(150)
t.right(90)
t.forward(100)
t.right(90)
t.forward(250)
t.right(90)
t.forward(200)
t.fillcolor('#4b99e0')
t.end_fill()
turtle.exitonclick()
<file_sep># <NAME>, CSC 110, Prof Ali, 10/31/19
# Task 1
#
def main():
list = ['Galileo', 'Oliver', 'Ostwald', 'Descartes']
# for i in list[:]:
for i in list:
print(i)
main();
################################################################################
# Task 02
#
def main():
names = ['Ali', 'John', 'Doe', 'Jane']
for i in names:
if i == 'Ali':
print('Hello Ali')
else:
print('no')
main();
<file_sep>public class BigLittle {
public static void main(String[] args) {
int little;
int big;
little = 2;
big = 2000;
System.out.println("The little number is: " + little);
System.out.print("The big number is: " + big);
}
}<file_sep># <NAME>, October 3, 2019, CSC 110, Prof Ali
#
import sys
roomNumber = int(input('Enter room number: '))
capacity = int(input('Enter capacity: '))
enrollment = int(input('Enter enrollment: '))
#
# roomNumber = 345
# capacity = 32
# enrollment = 23
if roomNumber < 0 or capacity < 0 or enrollment < 0:
print('Error! Capacity cannot be a negative number.')
sys.exit()
if enrollment > capacity:
print('Error! Enrollment can not be greater than capacity')
sys.exit()
emptySeats = capacity - enrollment
if enrollment == capacity:
filled = 'Filled'
else:
filled = 'Not filled'
print('{:^15} {:^15} {:^15} {:^15} {:^15}'.format('Room', 'Capacity', 'Enrollment', 'Empty Seats', 'Filled/Not filled'))
print('{:^15} {:^15} {:^15} {:^15} {:^15}'.format('----', '--------', '----------', '-----------', '-----------------'))
print('{:^15} {:^15} {:^15} {:^15} {:^15}'.format(roomNumber, capacity, enrollment, emptySeats, filled))
<file_sep># Read me
The base folder consists of all the files emailed to me from Professor Ali<file_sep># libraries
import numpy as np # used for handling numbers
import pandas as pd # used for handling the dataset
#Importing the Dataset:
# to import the dataset into a variable with
# Removing the first unnamed column
dataset = pd.read_csv('mpg.csv',index_col=0)
#print(dataset) #print all
#print(dataset.head()) #print the first 5 rows
#print(dataset.head(10)) # print the first n rows
# Total missing values for each feature
print(dataset.isnull().sum())
# Replace using median
median = dataset['cyl'].median()
dataset['cyl'].fillna(median, inplace=True) #fillna fills the NaN values with a given number with which you want to substitute
print(dataset.isnull().sum())# Check again any missing or not
# Now we are going to encode the categorical data into numerical data type.
print(dataset.dtypes)# See the datatypes
# encode categorical data
from sklearn.preprocessing import LabelEncoder
le=LabelEncoder()
dataset["manufacturer"]=le.fit_transform(dataset["manufacturer"])
dataset["model"]=le.fit_transform(dataset["model"])
dataset["trans"]=le.fit_transform(dataset["trans"])
dataset["drv"]=le.fit_transform(dataset["drv"])
dataset["fl"]=le.fit_transform(dataset["fl"])
dataset["class"]=le.fit_transform(dataset["class"])
print(dataset.dtypes)
'''
#Visualize the data with boxplot
import matplotlib.pyplot as plt
for column in dataset:
plt.figure()
dataset.boxplot([column])
plt.show()
# Visualize all column in one histogram
fig, axes = plt.subplots(ncols=len(dataset.columns), figsize=(10,5))
for col, ax in zip(dataset, axes):
dataset[col].value_counts().sort_index().plot.bar(ax=ax, title=col)
plt.tight_layout()
plt.show()
# Visualize all column in separate histogram
fig = plt.figure(figsize = (8,8))
ax = fig.gca()
dataset.hist(ax=ax)
plt.show()
'''
# Splitting the attributes into independent and dependent attributes
X = dataset.iloc[:, :-1].values # attributes to determine independent variable / Class
Y = dataset.iloc[:, -1].values # dependent variable / Class
#print(X)
#print(Y)
#Split data into training and testing dataset. test_size=0.2 means 80% trainig data 20% test data
#Random state ensures that the splits that you generate are reproducible. Scikit-learn uses random permutations to generate the splits.
#The random state that you provide is used as a seed to the random number generator.
from sklearn.model_selection import train_test_split # used for splitting training and testing data
# splitting the dataset into training set and test set
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)
#import your model from scikit-learn
from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation
#Train Random Forest Model
rf_classifier = RandomForestClassifier(n_estimators=20, max_depth=4)
rf_model=rf_classifier.fit(X_train,Y_train)
#Predict Label
pred=rf_model.predict(X_test)
#Test Model
print("Accuracy:",metrics.accuracy_score(Y_test, pred))
from matplotlib import pyplot as plt
## The line / model
plt.scatter(Y_test, pred)
plt.xlabel("True Values")
plt.ylabel("Predictions")
plt.show()
from sklearn.model_selection import KFold
kf = KFold(n_splits=5,random_state=42,shuffle=True)
# Splitting the attributes into independent and dependent attributes
X = dataset.iloc[:, :-1].values # attributes to determine independent variable / Class
Y = dataset.iloc[:, -1].values # dependent variable / Class
accuracies = []
for train_index, test_index in kf.split(X):
data_train = X[train_index]
target_train = Y[train_index]
data_test = X[test_index]
target_test = Y[test_index]
# if needed, do preprocessing here
clf = RandomForestClassifier(n_estimators=20, max_depth=4)
clf.fit(data_train,target_train)
preds = clf.predict(data_test)
# accuracy for the current fold only
accuracy = metrics.accuracy_score(target_test,preds)
accuracies.append(accuracy)
# this is the average accuracy over all folds
average_accuracy = np.mean(accuracies)
print("Using Kfold validation, average accuracy:", average_accuracy)<file_sep># <NAME>, <NAME>, Nov 18, 2019, Assignment 08
# Task 01
#
def main():
x = open('/Users/Ryan/Documents/GitHub/csc110/Assignments/lin_assignment08/test.txt', 'r')
a = b = c = d = e = f = 0
y = x.read()
g = y.split()
# print(g)
for z in g:
# print(z)
if z[0].isupper():
a += 1;
elif z.islower():
b += 1;
# Can't use 'elif' here because prior conditions are already met for elements in the list such as '650-horsepower', which is lowercase
if z[0].isdigit():
c += 1;
# print(z)
d = len(g)
print('There are', a ,'words in uppercase')
print('There are', b ,'words in lowercase')
print('There are', c ,'numbers')
print('There are', d ,'spaces')
main();
#
# a = 0
# x = ['four', '650-horsepower', 'ships', 'at']
# for i in x:
#
# if z.islower():
# print('toads')
#
# elif i[0].isdigit():
# a += 1
# print(i)
# print(a)
# print(i)
###########################################################################################
# Task 02
#
def main():
roomNumber = {'CS101':'3004', 'CS102':'4501', 'CS103':'6755', 'NT110':'1244', 'CM241':'1411'}
instructor = {'CS101':'Haynes', 'CS102':'Alvarodo', 'CS103':'Rich', 'NT110':'Burke', 'CM241':'Lee'}
meetingTime = {'CS101':'8:00am', 'CS102':'9:00am', 'CS103':'10:00am', 'NT110':'11:00am', 'CM241':'1:00pm'}
a = input('Enter a course number (key): ')
def userInput(a):
print('You are meeting in room', roomNumber[a], 'with instructor', instructor[a], 'at', meetingTime[a])
userInput(a)
main();
<file_sep># <NAME>, CSC 110, Prof Ali, 11/1/19
# assignment 07
#
import random as r
def main():
# WINDOWS
x = open('D:\Github\CSC110\Assignments\lin_assignment07\lottery.txt', 'w')
#MAC
# x = open('/Users/Ryan/Documents/GitHub/csc110/Assignments/lin_assignment07/lottery.txt', 'w')
number = []
for i in range(0,6):
randomNumber = r.randrange(0,10)
number.append(randomNumber)
# number[i] = randomNumber
for item in number:
# x.write('%s\n' % item)
x.write('{0!s}\n'.format(item))
print(number)
x.close();
main();
<file_sep>
x = 1, 2, 3
print(x)
print(type(x))<file_sep># Singular Value Decomposition w/ SciPy
from numpy import array
# from scipy.linalg import svd
# from scipy.linalg import inv
from scipy.linalg import *
##
# A = array([
# [1.1, 1.0, 0.9, 1.0],
# [1.0, 1.1, 1.0, 0.9]])
A = array([
[1, 2],
[3, 4],
[5, 6]])
B = array([
[2, 3],
[1, 5]
])
# print("input \n", A)
# print("column \n", A[:,3])
##
U, s, VT = svd(A, full_matrices= True)
print("U \n", U)
print("S \n", s)
print("VT \n", VT)<file_sep># CSC 220 Data Structure / Big Data
| 454edc33b88421ffad5d94e8de0a299378c3a60b | [
"Markdown",
"Java",
"Python"
] | 66 | Java | rleaf/Acadamia | e955a4b8973089a6992eb6b61dbdb98cc3fda18e | dd0f03cbd6aacb49ac8c2c418f2aab8f8a6a64ad | |
refs/heads/master | <file_sep>package com.tlongdev.spicio.module;
import android.app.Application;
import android.content.ContentResolver;
import android.database.sqlite.SQLiteOpenHelper;
import com.tlongdev.spicio.storage.DatabaseHelper;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
/**
* @author Long
* @since 2016. 03. 05.
*/
@Module
public class StorageModule {
@Provides
@Singleton
ContentResolver provideContentResolver(Application application) {
return application.getContentResolver();
}
@Provides
@Singleton
SQLiteOpenHelper provideSQLiteOpenHelper(Application application) {
return new DatabaseHelper(application);
}
}
<file_sep>package com.tlongdev.spicio.domain.interactor;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.component.DaggerInteractorComponent;
import com.tlongdev.spicio.component.InteractorComponent;
import com.tlongdev.spicio.domain.interactor.impl.LoadAllSeriesInteractorImpl;
import com.tlongdev.spicio.domain.model.Series;
import com.tlongdev.spicio.module.FakeAppModule;
import com.tlongdev.spicio.module.FakeDaoModule;
import com.tlongdev.spicio.module.FakeThreadingModule;
import com.tlongdev.spicio.module.NetworkRepositoryModule;
import com.tlongdev.spicio.storage.dao.SeriesDao;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.LinkedList;
import java.util.List;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* @author Long
* @since 2016. 03. 07.
*/
@RunWith(MockitoJUnitRunner.class)
public class LoadAllSeriesInteractorTest {
@Mock
private SeriesDao mSeriesDao;
@Mock
private LoadAllSeriesInteractor.Callback mMockedCallback;
@Mock
private SpicioApplication mApp;
@Before
public void setUp() {
FakeDaoModule storageModule = new FakeDaoModule();
storageModule.setSeriesDao(mSeriesDao);
InteractorComponent component = DaggerInteractorComponent.builder()
.spicioAppModule(new FakeAppModule(mApp))
.daoModule(storageModule)
.networkRepositoryModule(mock(NetworkRepositoryModule.class))
.threadingModule(new FakeThreadingModule())
.build();
when(mApp.getInteractorComponent()).thenReturn(component);
}
@Test
public void testSuccess() {
List<Series> series = new LinkedList<>();
when(mSeriesDao.getAllSeries()).thenReturn(series);
LoadAllSeriesInteractorImpl interactor = new LoadAllSeriesInteractorImpl(
mApp, mMockedCallback
);
interactor.run();
verify(mSeriesDao).getAllSeries();
verifyNoMoreInteractions(mSeriesDao);
verify(mMockedCallback).onLoadAllSeriesFinish(series);
}
@Test
public void testFail() {
when(mSeriesDao.getAllSeries()).thenReturn(null);
LoadAllSeriesInteractorImpl interactor = new LoadAllSeriesInteractorImpl(
mApp, mMockedCallback
);
interactor.run();
verify(mSeriesDao).getAllSeries();
verifyNoMoreInteractions(mSeriesDao);
verify(mMockedCallback).onLoadAllSeriesFail();
}
}
<file_sep>package com.tlongdev.spicio.presentation.presenter.activity;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.domain.interactor.LoadSeasonEpisodesInteractor;
import com.tlongdev.spicio.domain.interactor.impl.LoadSeasonEpisodesInteractorImpl;
import com.tlongdev.spicio.domain.model.Episode;
import com.tlongdev.spicio.presentation.presenter.Presenter;
import com.tlongdev.spicio.presentation.ui.view.activity.SeasonEpisodesView;
import java.util.List;
/**
* @author Long
* @since 2016. 03. 10.
*/
public class SeasonEpisodesPresenter implements Presenter<SeasonEpisodesView>,
LoadSeasonEpisodesInteractor.Callback{
private SeasonEpisodesView mView;
private SpicioApplication mApplication;
private int mSeriesId;
private int mSeason;
@Override
public void attachView(SeasonEpisodesView view) {
mView = view;
mApplication = view.getSpicioApplication();
}
@Override
public void detachView() {
mView = null;
}
public void loadEpisodes() {
LoadSeasonEpisodesInteractor interactor = new LoadSeasonEpisodesInteractorImpl(
mApplication, mSeriesId, mSeason, this
);
interactor.execute();
}
public void setSeriesId(int seriesId) {
mSeriesId = seriesId;
}
public void setSeason(int season) {
mSeason = season;
}
@Override
public void onLoadSeasonEpisodesFinish(List<Episode> episodes) {
if (mView != null) {
mView.showEpisodes(episodes);
}
}
@Override
public void onLoadSeasonEpisodesFail() {
// TODO: 2016. 03. 11.
}
}
<file_sep>package com.tlongdev.spicio.domain.interactor;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.component.DaggerInteractorComponent;
import com.tlongdev.spicio.component.InteractorComponent;
import com.tlongdev.spicio.domain.interactor.impl.LikeEpisodeInteractorImpl;
import com.tlongdev.spicio.module.FakeAppModule;
import com.tlongdev.spicio.module.FakeDaoModule;
import com.tlongdev.spicio.module.FakeNetworkRepositoryModule;
import com.tlongdev.spicio.module.FakeThreadingModule;
import com.tlongdev.spicio.storage.dao.EpisodeDao;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* @author Long
* @since 2016. 03. 11.
*/
@RunWith(MockitoJUnitRunner.class)
public class LikeEpisodeInteractorTest {
@Mock
private EpisodeDao mEpisodeDao;
@Mock
private LikeEpisodeInteractor.Callback mMockedCallback;
@Mock
private SpicioApplication mApp;
@Before
public void setUp() {
FakeDaoModule daoModule = new FakeDaoModule();
daoModule.setEpisodeDao(mEpisodeDao);
FakeNetworkRepositoryModule networkRepositoryModule = new FakeNetworkRepositoryModule();
InteractorComponent component = DaggerInteractorComponent.builder()
.spicioAppModule(new FakeAppModule(mApp))
.daoModule(daoModule)
.networkRepositoryModule(networkRepositoryModule)
.threadingModule(new FakeThreadingModule())
.build();
when(mApp.getInteractorComponent()).thenReturn(component);
}
@Test
public void testCheck(){
when(mEpisodeDao.setLiked(0, true)).thenReturn(1);
LikeEpisodeInteractorImpl interactor = new LikeEpisodeInteractorImpl(
mApp, 0, true, mMockedCallback
);
interactor.run();
verify(mEpisodeDao).setLiked(0, true);
verifyNoMoreInteractions(mEpisodeDao);
verify(mMockedCallback).onEpisodeLikeFinish();
}
@Test
public void testFail(){
when(mEpisodeDao.setLiked(0, true)).thenReturn(0);
LikeEpisodeInteractorImpl interactor = new LikeEpisodeInteractorImpl(
mApp, 0, true, mMockedCallback
);
interactor.run();
verify(mEpisodeDao).setLiked(0, true);
verifyNoMoreInteractions(mEpisodeDao);
verify(mMockedCallback).onEpisodeLikeFail();
}
}
<file_sep>package com.tlongdev.spicio.presentation.ui.view.activity;
import com.tlongdev.spicio.presentation.ui.view.BaseView;
/**
* @author Long
* @since 2016. 03. 12.
*/
public interface LoginView extends BaseView {
void showLoadingAnim();
void hideLoadingAnim();
void onLogin();
}<file_sep>package com.tlongdev.spicio.domain.interactor;
import com.tlongdev.spicio.domain.model.Season;
import java.util.List;
/**
* @author Long
* @since 2016. 03. 09.
*/
public interface LoadSeasonsInteractor extends Interactor {
interface Callback {
void onLoadSeasonsFinish(List<Season> seasons);
void onLoadSeasonsFail();
}
}
<file_sep>package com.tlongdev.spicio.domain.interactor;
import com.tlongdev.spicio.domain.model.Series;
import java.util.List;
/**
* @author Long
* @since 2016. 03. 04.
*/
public interface TraktSearchInteractor extends Interactor {
interface Callback {
void onTraktSearchFinish(List<Series> series);
void onTraktSearchFailed(); // TODO: 2016. 02. 28. needs more descriptive error data
}
}
<file_sep>package com.tlongdev.spicio.util;
import android.util.Log;
/**
* @author Long
* @since 2016. 03. 05.
*/
public class AndroidLogger implements Logger {
@Override
public void verbose(String tag, String msg) {
Log.v(tag, msg);
}
@Override
public void debug(String tag, String msg) {
Log.d(tag, msg);
}
@Override
public void info(String tag, String msg) {
Log.i(tag, msg);
}
@Override
public void warn(String tag, String msg) {
Log.w(tag, msg);
}
@Override
public void error(String tag, String msg) {
Log.e(tag, msg);
}
@Override
public void wtf(String tag, String msg) {
Log.wtf(tag, msg);
}
@Override
public void verbose(String tag, String msg, Throwable tr) {
Log.v(tag, msg, tr);
}
@Override
public void debug(String tag, String msg, Throwable tr) {
Log.d(tag, msg, tr);
}
@Override
public void info(String tag, String msg, Throwable tr) {
Log.i(tag, msg, tr);
}
@Override
public void warn(String tag, String msg, Throwable tr) {
Log.w(tag, msg, tr);
}
@Override
public void error(String tag, String msg, Throwable tr) {
Log.e(tag, msg, tr);
}
@Override
public void wtf(String tag, String msg, Throwable tr) {
Log.wtf(tag, msg, tr);
}
}
<file_sep>package com.tlongdev.spicio.component;
import com.tlongdev.spicio.domain.interactor.AbstractInteractor;
import com.tlongdev.spicio.domain.interactor.impl.CheckEpisodeInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.DeleteAllDataInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.LikeEpisodeInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.LoadAllSeriesInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.LoadEpisodeDetailsInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.LoadSeasonEpisodesInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.LoadSeasonsInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.LoadSeriesDetailsInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.SaveEpisodesInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.SaveSeriesInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.TraktFullSeriesInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.TraktSearchInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.TraktSeasonEpisodesInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.TraktSeriesDetailsInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.TvdbSearchInteractorImpl;
import com.tlongdev.spicio.module.DaoModule;
import com.tlongdev.spicio.module.NetworkRepositoryModule;
import com.tlongdev.spicio.module.SpicioAppModule;
import com.tlongdev.spicio.module.ThreadingModule;
import javax.inject.Singleton;
import dagger.Component;
/**
* @author Long
* @since 2016. 03. 07.
*/
@Singleton
@Component(modules = {SpicioAppModule.class, DaoModule.class, NetworkRepositoryModule.class,
ThreadingModule.class})
public interface InteractorComponent {
void inject(AbstractInteractor abstractInteractor);
void inject(SaveSeriesInteractorImpl saveSeriesInteractor);
void inject(TvdbSearchInteractorImpl tvdbSearchInteractor);
void inject(TraktSearchInteractorImpl traktSearchInteractor);
void inject(TraktSeriesDetailsInteractorImpl traktSeriesDetailsInteractor);
void inject(LoadAllSeriesInteractorImpl loadAllSeriesInteractor);
void inject(TraktFullSeriesInteractorImpl traktFullSeriesInteractor);
void inject(LoadSeasonsInteractorImpl loadSeasonsInteractor);
void inject(LoadSeriesDetailsInteractorImpl loadSeriesDetailsInteractor);
void inject(TraktSeasonEpisodesInteractorImpl traktEpisodeImagesInteractor);
void inject(LoadSeasonEpisodesInteractorImpl loadSeasonEpisodesInteractor);
void inject(SaveEpisodesInteractorImpl saveEpisodesInteractor);
void inject(LoadEpisodeDetailsInteractorImpl loadEpisodeDetailsInteractor);
void inject(CheckEpisodeInteractorImpl checkEpisodeInteractor);
void inject(LikeEpisodeInteractorImpl likeEpisodeInteractor);
void inject(DeleteAllDataInteractorImpl deleteAllDataInteractor);
}
<file_sep>package com.tlongdev.spicio.util;
import android.content.SharedPreferences;
import com.tlongdev.spicio.SpicioApplication;
import javax.inject.Inject;
/**
* @author Long
* @since 2016. 03. 13.
*/
public class ProfileManager {
private static String PREF_KEY_FACEBOOK_ID = "pref_facebook_id";
private static String PREF_KEY_GOOGLE_ID = "pref_google_id";
@Inject SharedPreferences mPrefs;
@Inject SharedPreferences.Editor mEditor;
public ProfileManager(SpicioApplication application) {
application.getProfileManagerComponent().inject(this);
}
public boolean isLoggedIn() {
return mPrefs.contains(PREF_KEY_FACEBOOK_ID) || mPrefs.contains(PREF_KEY_GOOGLE_ID);
}
public void logout() {
mEditor.remove(PREF_KEY_FACEBOOK_ID);
mEditor.remove(PREF_KEY_GOOGLE_ID);
mEditor.apply();
}
public void loginWithFacebook(String id) {
mEditor.putString(PREF_KEY_FACEBOOK_ID, id);
mEditor.apply();
}
public void loginWithGoogle(String id) {
mEditor.putString(PREF_KEY_GOOGLE_ID, id);
mEditor.apply();
}
public String getFacebookId(){
return mPrefs.getString(PREF_KEY_FACEBOOK_ID, null);
}
public String getGoogleId() {
return mPrefs.getString(PREF_KEY_GOOGLE_ID, null);
}
}
<file_sep>package com.tlongdev.spicio.presentation.presenter.fragment;
import com.tlongdev.spicio.domain.interactor.CheckEpisodeInteractor;
import com.tlongdev.spicio.domain.interactor.LikeEpisodeInteractor;
import com.tlongdev.spicio.domain.interactor.LoadEpisodeDetailsInteractor;
import com.tlongdev.spicio.domain.interactor.impl.CheckEpisodeInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.LikeEpisodeInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.LoadEpisodeDetailsInteractorImpl;
import com.tlongdev.spicio.domain.model.Episode;
import com.tlongdev.spicio.domain.model.Watched;
import com.tlongdev.spicio.presentation.presenter.Presenter;
import com.tlongdev.spicio.presentation.ui.view.fragment.EpisodeView;
/**
* @author Long
* @since 2016. 03. 11.
*/
public class EpisodePresenter implements Presenter<EpisodeView>,
LoadEpisodeDetailsInteractor.Callback, CheckEpisodeInteractor.Callback,
LikeEpisodeInteractor.Callback {
private EpisodeView mView;
private Episode mEpisode;
@Override
public void attachView(EpisodeView view) {
mView = view;
}
@Override
public void detachView() {
mView = null;
}
@Override
public void onLoadEpisodeDetailsFinish(Episode episode) {
mEpisode = episode;
if (mView != null) {
mView.showEpisodeDetails(episode);
}
}
@Override
public void onLoadEpisodeDetailsFail() {
mEpisode = null;
if (mView != null) {
mView.showError();
}
}
public void loadEpisode(int episodeId) {
LoadEpisodeDetailsInteractor interactor = new LoadEpisodeDetailsInteractorImpl(
mView.getSpicioApplication(), episodeId, this
);
interactor.execute();
}
public void checkEpisode() {
int watched = mEpisode.isWatched() == Watched.WATCHED ? Watched.NONE : Watched.WATCHED;
mEpisode.setWatched(watched);
CheckEpisodeInteractor interactor = new CheckEpisodeInteractorImpl(
mView.getSpicioApplication(), mEpisode.getTraktId(), watched, this
);
interactor.execute();
}
public void likeEpisode() {
LikeEpisodeInteractor interactor = new LikeEpisodeInteractorImpl(
mView.getSpicioApplication(), mEpisode.getTraktId(), !mEpisode.isLiked(), this
);
interactor.execute();
}
public void skipEpisode() {
int watched = mEpisode.isWatched() == Watched.SKIPPED ? Watched.NONE : Watched.SKIPPED;
mEpisode.setWatched(watched);
CheckEpisodeInteractor interactor = new CheckEpisodeInteractorImpl(
mView.getSpicioApplication(), mEpisode.getTraktId(), watched, this
);
interactor.execute();
}
@Override
public void onEpisodeCheckFinish() {
if (mView != null) {
mView.updateCheckButton(mEpisode.isWatched());
}
}
@Override
public void onEpisodeCheckFail() {
}
@Override
public void onEpisodeLikeFinish() {
mEpisode.setLiked(!mEpisode.isLiked());
if (mView != null) {
mView.updateLikeButton(mEpisode.isLiked());
}
}
@Override
public void onEpisodeLikeFail() {
}
}
<file_sep>package com.tlongdev.spicio.domain.model;
import org.joda.time.DateTime;
/**
* Inner Layer, Model.
*
* @author Long
* @since 2016. 02. 28.
*/
public class TvdbEpisodeOld {
private int id;
private int seasonId;
private int episodeNumber;
private String episodeName;
private DateTime firstAired;
private String[] guestStars;
private String director;
private String[] writers;
private String overView;
private int seasonNumber;
private int absoluteNumber;
private String fileName;
private int seriesId;
private String imdbId;
private double tvdbRating;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getSeasonId() {
return seasonId;
}
public void setSeasonId(int seasonId) {
this.seasonId = seasonId;
}
public int getEpisodeNumber() {
return episodeNumber;
}
public void setEpisodeNumber(int episodeNumber) {
this.episodeNumber = episodeNumber;
}
public String getEpisodeName() {
return episodeName;
}
public void setEpisodeName(String episodeName) {
this.episodeName = episodeName;
}
public DateTime getFirstAired() {
return firstAired;
}
public void setFirstAired(DateTime firstAired) {
this.firstAired = firstAired;
}
public String[] getGuestStars() {
return guestStars;
}
public void setGuestStars(String[] guestStars) {
this.guestStars = guestStars;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String[] getWriters() {
return writers;
}
public void setWriters(String[] writers) {
this.writers = writers;
}
public String getOverView() {
return overView;
}
public void setOverView(String overView) {
this.overView = overView;
}
public int getSeasonNumber() {
return seasonNumber;
}
public void setSeasonNumber(int seasonNumber) {
this.seasonNumber = seasonNumber;
}
public int getAbsoluteNumber() {
return absoluteNumber;
}
public void setAbsoluteNumber(int absoluteNumber) {
this.absoluteNumber = absoluteNumber;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public int getSeriesId() {
return seriesId;
}
public void setSeriesId(int seriesId) {
this.seriesId = seriesId;
}
public String getImdbId() {
return imdbId;
}
public void setImdbId(String imdbId) {
this.imdbId = imdbId;
}
public double getTvdbRating() {
return tvdbRating;
}
public void setTvdbRating(double tvdbRating) {
this.tvdbRating = tvdbRating;
}
}
<file_sep>package com.tlongdev.spicio.domain.model;
/**
* @author Long
* @since 2016. 03. 03.
*/
public class Image {
private String full;
private String medium;
private String thumb;
public String getFull() {
return full;
}
public void setFull(String full) {
this.full = full;
}
public String getMedium() {
return medium;
}
public void setMedium(String medium) {
this.medium = medium;
}
public String getThumb() {
return thumb;
}
public void setThumb(String thumb) {
this.thumb = thumb;
}
}
<file_sep>package com.tlongdev.spicio.presentation.ui.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
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.engine.DiskCacheStrategy;
import com.tlongdev.spicio.R;
import com.tlongdev.spicio.domain.model.Series;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Outer Layer, UI.
*
* @author Long
* @since 2016. 02. 25.
*/
public class SearchSeriesAdapter extends RecyclerView.Adapter<SearchSeriesAdapter.ViewHolder> {
private List<Series> mDataSet;
private Context mContext;
private OnItemSelectedListener listener;
public SearchSeriesAdapter(Context context) {
this.mContext = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_search_series, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if (mDataSet != null) {
final Series series = mDataSet.get(position);
holder.text.setText(series.getTitle());
Glide.with(mContext)
.load(series.getImages().getPoster().getFull())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.error(R.drawable.ic_movie)
.into(holder.poster);
holder.root.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
listener.onItemSelected(series);
}
}
});
}
}
@Override
public int getItemCount() {
return mDataSet == null ? 0 : mDataSet.size();
}
public void setDataSet(List<Series> dataSet) {
this.mDataSet = dataSet;
notifyDataSetChanged();
}
public void setListener(OnItemSelectedListener listener) {
this.listener = listener;
}
public class ViewHolder extends RecyclerView.ViewHolder {
@Bind(R.id.text) TextView text;
@Bind(R.id.poster) ImageView poster;
View root;
public ViewHolder(View view) {
super(view);
root = view;
ButterKnife.bind(this, view);
}
}
public interface OnItemSelectedListener {
void onItemSelected(Series series);
}
}
<file_sep>package com.tlongdev.spicio.domain.interactor.impl;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.domain.interactor.AbstractInteractor;
import com.tlongdev.spicio.domain.interactor.TvdbSearchInteractor;
import com.tlongdev.spicio.domain.model.TvdbSeriesOld;
import com.tlongdev.spicio.domain.repository.TvdbRepository;
import com.tlongdev.spicio.util.Logger;
import java.util.List;
import javax.inject.Inject;
/**
* Inner Layer, Interactor
*
* @author Long
* @since 2016. 02. 28.
*/
public class TvdbSearchInteractorImpl extends AbstractInteractor implements TvdbSearchInteractor {
private static final String LOG_TAG = TvdbSearchInteractorImpl.class.getSimpleName();
@Inject TvdbRepository mRepository;
@Inject Logger logger;
private String mSearchQuery;
private Callback mCallback;
public TvdbSearchInteractorImpl(SpicioApplication app, String query, Callback callback) {
super(app.getInteractorComponent());
app.getInteractorComponent().inject(this);
mSearchQuery = query;
mCallback = callback;
}
@Override
public void run() {
logger.debug(LOG_TAG, "started");
List<TvdbSeriesOld> searchResult = mRepository.searchSeries(mSearchQuery);
if (searchResult == null) {
postError();
} else {
postResult(searchResult);
}
logger.debug(LOG_TAG, "finished");
}
private void postError() {
if (mCallback == null) {
return;
}
mMainThread.post(new Runnable() {
@Override
public void run() {
mCallback.onTvdbSearchFailed();
}
});
}
private void postResult(final List<TvdbSeriesOld> searchResult) {
if (mCallback == null) {
return;
}
mMainThread.post(new Runnable() {
@Override
public void run() {
mCallback.onTvdbSearchFinish(searchResult);
}
});
}
}
<file_sep>package com.tlongdev.spicio.presentation.presenter.activity;
import com.tlongdev.spicio.presentation.presenter.Presenter;
import com.tlongdev.spicio.presentation.ui.view.activity.MainView;
/**
* Middle layer, Presenter.
*
* @author Long
* @since 2016. 02. 23.
*/
public class MainPresenter implements Presenter<MainView> {
private MainView mView;
@Override
public void attachView(MainView view) {
this.mView = view;
}
@Override
public void detachView() {
mView = null;
}
}
<file_sep>package com.tlongdev.spicio.network.model;
import com.google.gson.annotations.SerializedName;
/**
* @author Long
* @since 2016. 03. 01.
*/
public class TraktSearchResult {
@SerializedName("type")
private String type;
@SerializedName("score")
private double score;
@SerializedName("show")
private TraktSeries series;
public String getType() {
return type;
}
public double getScore() {
return score;
}
public TraktSeries getSeries() {
return series;
}
}
<file_sep>package com.tlongdev.spicio;
import android.app.Application;
import com.facebook.FacebookSdk;
import com.tlongdev.spicio.component.ActivityComponent;
import com.tlongdev.spicio.component.DaggerActivityComponent;
import com.tlongdev.spicio.component.DaggerInteractorComponent;
import com.tlongdev.spicio.component.DaggerNetworkComponent;
import com.tlongdev.spicio.component.DaggerPresenterComponent;
import com.tlongdev.spicio.component.DaggerProfileManagerComponent;
import com.tlongdev.spicio.component.DaggerStorageComponent;
import com.tlongdev.spicio.component.InteractorComponent;
import com.tlongdev.spicio.component.NetworkComponent;
import com.tlongdev.spicio.component.PresenterComponent;
import com.tlongdev.spicio.component.ProfileManagerComponent;
import com.tlongdev.spicio.component.StorageComponent;
import com.tlongdev.spicio.module.AuthenticationModule;
import com.tlongdev.spicio.module.DaoModule;
import com.tlongdev.spicio.module.NetworkModule;
import com.tlongdev.spicio.module.NetworkRepositoryModule;
import com.tlongdev.spicio.module.SpicioAppModule;
import com.tlongdev.spicio.module.StorageModule;
import com.tlongdev.spicio.module.ThreadingModule;
import net.danlew.android.joda.JodaTimeAndroid;
/**
* This is a subclass of {@link Application} used to provide shared objects for this app.
*
* @author Long
* @since 2016. 02. 23.
*/
public class SpicioApplication extends Application {
private InteractorComponent mInteractorComponent;
private NetworkComponent mNetworkComponent;
private StorageComponent mStorageComponent;
private PresenterComponent mPresenterComponent;
private ActivityComponent mActivityComponent;
private ProfileManagerComponent mProfileManagerComponent;
@Override
public void onCreate() {
super.onCreate();
JodaTimeAndroid.init(this);
FacebookSdk.sdkInitialize(this);
SpicioAppModule spicioAppModule = new SpicioAppModule(this);
NetworkModule networkModule = new NetworkModule();
StorageModule storageModule = new StorageModule();
DaoModule daoModule = new DaoModule();
NetworkRepositoryModule networkRepositoryModule = new NetworkRepositoryModule();
ThreadingModule threadingModule = new ThreadingModule();
AuthenticationModule authenticationModule = new AuthenticationModule();
mNetworkComponent = DaggerNetworkComponent.builder()
.spicioAppModule(spicioAppModule)
.networkModule(networkModule)
.build();
mStorageComponent = DaggerStorageComponent.builder()
.spicioAppModule(spicioAppModule)
.storageModule(storageModule)
.build();
mInteractorComponent = DaggerInteractorComponent.builder()
.spicioAppModule(spicioAppModule)
.networkRepositoryModule(networkRepositoryModule)
.daoModule(daoModule)
.threadingModule(threadingModule)
.build();
mPresenterComponent = DaggerPresenterComponent.builder()
.spicioAppModule(spicioAppModule)
.authenticationModule(authenticationModule)
.build();
mActivityComponent = DaggerActivityComponent.builder()
.spicioAppModule(spicioAppModule)
.authenticationModule(authenticationModule)
.build();
mProfileManagerComponent = DaggerProfileManagerComponent.builder()
.spicioAppModule(spicioAppModule)
.build();
}
public NetworkComponent getNetworkComponent() {
return mNetworkComponent;
}
public StorageComponent getStorageComponent() {
return mStorageComponent;
}
public void setStorageComponent(StorageComponent storageComponent) {
this.mStorageComponent = storageComponent;
}
public InteractorComponent getInteractorComponent() {
return mInteractorComponent;
}
public PresenterComponent getPresenterComponent() {
return mPresenterComponent;
}
public ActivityComponent getActivityComponent() {
return mActivityComponent;
}
public ProfileManagerComponent getProfileManagerComponent() {
return mProfileManagerComponent;
}
public void setProfileManagerComponent(ProfileManagerComponent profileManagerComponent) {
mProfileManagerComponent = profileManagerComponent;
}
}
<file_sep># spicio
| `master` | `development` |
| :---: | :---: |
| [](https://travis-ci.org/Longi94/spicio) | [](https://travis-ci.org/Longi94/spicio) |
| [](https://codecov.io/github/Longi94/spicio?branch=master) | [](https://codecov.io/github/Longi94/spicio?branch=development) |
<file_sep>package com.tlongdev.spicio.storage;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.tlongdev.spicio.BuildConfig;
import com.tlongdev.spicio.storage.DatabaseContract.EpisodesEntry;
import com.tlongdev.spicio.storage.DatabaseContract.FeedEntry;
import com.tlongdev.spicio.storage.DatabaseContract.FriendsEntry;
import com.tlongdev.spicio.storage.DatabaseContract.SeriesEntry;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import java.util.HashSet;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Long
* @since 2016. 02. 27.
*/
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class DatabaseTest {
private Context mContext;
@Before
public void setUp() throws Exception {
assertNotNull(RuntimeEnvironment.application);
mContext = RuntimeEnvironment.application;
mContext.deleteDatabase(DatabaseHelper.DATABASE_NAME);
}
@Test
public void testCreateDatabase() {
final HashSet<String> tableNameHashSet = new HashSet<String>();
tableNameHashSet.add(SeriesEntry.TABLE_NAME);
tableNameHashSet.add(EpisodesEntry.TABLE_NAME);
tableNameHashSet.add(FeedEntry.TABLE_NAME);
tableNameHashSet.add(FriendsEntry.TABLE_NAME);
SQLiteDatabase db = new DatabaseHelper(mContext).getWritableDatabase();
assertNotNull(db);
assertTrue(db.isOpen());
//See if we've created the tables we want
Cursor tables = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
assertTrue(tables.moveToFirst());
// verify that the tables have been created
do {
tableNameHashSet.remove(tables.getString(0));
} while (tables.moveToNext());
tables.close();
assertTrue("Error: Your database was created with missing tables", tableNameHashSet.isEmpty());
Cursor columns = db.rawQuery("PRAGMA table_info(" + SeriesEntry.TABLE_NAME + ")",
null);
assertTrue("Error: This means that we were unable to query the database for table information.",
columns.moveToFirst());
//Check for table columns
final HashSet<String> columnHashSet = new HashSet<String>();
columnHashSet.add(SeriesEntry.COLUMN_TITLE);
columnHashSet.add(SeriesEntry.COLUMN_YEAR);
columnHashSet.add(SeriesEntry.COLUMN_TRAKT_ID);
columnHashSet.add(SeriesEntry.COLUMN_TVDB_ID);
columnHashSet.add(SeriesEntry.COLUMN_IMDB_ID);
columnHashSet.add(SeriesEntry.COLUMN_TMDB_ID);
columnHashSet.add(SeriesEntry.COLUMN_TV_RAGE_ID);
columnHashSet.add(SeriesEntry.COLUMN_SLUG);
columnHashSet.add(SeriesEntry.COLUMN_OVERVIEW);
columnHashSet.add(SeriesEntry.COLUMN_FIRST_AIRED);
columnHashSet.add(SeriesEntry.COLUMN_DAY_OF_AIR);
columnHashSet.add(SeriesEntry.COLUMN_TIME_OF_AIR);
columnHashSet.add(SeriesEntry.COLUMN_AIR_TIME_ZONE);
columnHashSet.add(SeriesEntry.COLUMN_RUNTIME);
columnHashSet.add(SeriesEntry.COLUMN_CONTENT_RATING);
columnHashSet.add(SeriesEntry.COLUMN_NETWORK);
columnHashSet.add(SeriesEntry.COLUMN_TRAILER);
columnHashSet.add(SeriesEntry.COLUMN_STATUS);
columnHashSet.add(SeriesEntry.COLUMN_TRAKT_RATING);
columnHashSet.add(SeriesEntry.COLUMN_TRAKT_RATING_COUNT);
columnHashSet.add(SeriesEntry.COLUMN_GENRES);
columnHashSet.add(SeriesEntry.COLUMN_POSTER_FULL);
columnHashSet.add(SeriesEntry.COLUMN_POSTER_THUMB);
columnHashSet.add(SeriesEntry.COLUMN_THUMB);
columnHashSet.add(SeriesEntry.COLUMN_TVDB_RATING);
columnHashSet.add(SeriesEntry.COLUMN_TVDB_RATING_COUNT);
int columnNameIndex = columns.getColumnIndex("name");
do {
String columnName = columns.getString(columnNameIndex);
columnHashSet.remove(columnName);
} while (columns.moveToNext());
columns.close();
assertTrue("Error: The database doesn't contain all of the required columns",
columnHashSet.isEmpty());
columns = db.rawQuery("PRAGMA table_info(" + EpisodesEntry.TABLE_NAME + ")",
null);
assertTrue("Error: This means that we were unable to query the database for table information.",
columns.moveToFirst());
//Check for table columns
columnHashSet.clear();
columnHashSet.add(EpisodesEntry.COLUMN_SERIES_ID);
columnHashSet.add(EpisodesEntry.COLUMN_SEASON);
columnHashSet.add(EpisodesEntry.COLUMN_EPISODE_NUMBER);
columnHashSet.add(EpisodesEntry.COLUMN_TITLE);
columnHashSet.add(EpisodesEntry.COLUMN_TRAKT_ID);
columnHashSet.add(EpisodesEntry.COLUMN_TVDB_ID);
columnHashSet.add(EpisodesEntry.COLUMN_IMDB_ID);
columnHashSet.add(EpisodesEntry.COLUMN_TMDB_ID);
columnHashSet.add(EpisodesEntry.COLUMN_TV_RAGE_ID);
columnHashSet.add(EpisodesEntry.COLUMN_SLUG);
columnHashSet.add(EpisodesEntry.COLUMN_ABSOLUTE_NUMBER);
columnHashSet.add(EpisodesEntry.COLUMN_OVERVIEW);
columnHashSet.add(EpisodesEntry.COLUMN_TRAKT_RATING);
columnHashSet.add(EpisodesEntry.COLUMN_TRAKT_RATING_COUNT);
columnHashSet.add(EpisodesEntry.COLUMN_FIRST_AIRED);
columnHashSet.add(EpisodesEntry.COLUMN_SCREENSHOT_FULL);
columnHashSet.add(EpisodesEntry.COLUMN_SCREENSHOT_THUMB);
columnHashSet.add(EpisodesEntry.COLUMN_WATCHED);
columnHashSet.add(EpisodesEntry.COLUMN_LIKED);
columnHashSet.add(EpisodesEntry.COLUMN_TVDB_RATING);
do {
String columnName = columns.getString(columnNameIndex);
columnHashSet.remove(columnName);
} while (columns.moveToNext());
columns.close();
assertTrue("Error: The database doesn't contain all of the required columns",
columnHashSet.isEmpty());
columns = db.rawQuery("PRAGMA table_info(" + FeedEntry.TABLE_NAME + ")",
null);
assertTrue("Error: This means that we were unable to query the database for table information.",
columns.moveToFirst());
//Check for table columns
columnHashSet.clear();
columnHashSet.add(FeedEntry.COLUMN_CULPRIT_ID);
columnHashSet.add(FeedEntry.COLUMN_EPISODE_ABSOLUTE_NUMBER);
columnHashSet.add(FeedEntry.COLUMN_EPISODE_ID);
columnHashSet.add(FeedEntry.COLUMN_EPISODE_NAME);
columnHashSet.add(FeedEntry.COLUMN_EPISODE_NUMBER);
columnHashSet.add(FeedEntry.COLUMN_ITEM_ID);
columnHashSet.add(FeedEntry.COLUMN_SEASON_NUMBER);
columnHashSet.add(FeedEntry.COLUMN_SERIES_ID);
columnHashSet.add(FeedEntry.COLUMN_SERIES_NAME);
columnHashSet.add(FeedEntry.COLUMN_TIMESTAMP);
columnHashSet.add(FeedEntry.COLUMN_TYPE);
columnHashSet.add(FeedEntry.COLUMN_VICTIM_ID);
columnHashSet.add(FeedEntry.COLUMN_VICTIM_NAME);
do {
String columnName = columns.getString(columnNameIndex);
columnHashSet.remove(columnName);
} while (columns.moveToNext());
columns.close();
assertTrue("Error: The database doesn't contain all of the required columns",
columnHashSet.isEmpty());
columns = db.rawQuery("PRAGMA table_info(" + FriendsEntry.TABLE_NAME + ")",
null);
assertTrue("Error: This means that we were unable to query the database for table information.",
columns.moveToFirst());
//Check for table columns
columnHashSet.clear();
columnHashSet.add(FriendsEntry.COLUMN_AVATAR);
columnHashSet.add(FriendsEntry.COLUMN_NAME);
columnHashSet.add(FriendsEntry.COLUMN_USER_ID);
do {
String columnName = columns.getString(columnNameIndex);
columnHashSet.remove(columnName);
} while (columns.moveToNext());
columns.close();
assertTrue("Error: The database doesn't contain all of the required columns",
columnHashSet.isEmpty());
}
}
<file_sep>package com.tlongdev.spicio.presentation.ui.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.tlongdev.spicio.domain.model.Episode;
import com.tlongdev.spicio.presentation.ui.fragment.EpisodeFragment;
import java.util.List;
/**
* @author Long
* @since 2016. 03. 11.
*/
public class EpisodePagerAdapter extends FragmentPagerAdapter {
private List<Episode> mDataSet;
public EpisodePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
int episodeId = mDataSet.get(position).getTraktId();
return EpisodeFragment.newInstance(episodeId);
}
@Override
public int getCount() {
return mDataSet == null ? 0 : mDataSet.size();
}
@Override
public CharSequence getPageTitle(int position) {
Episode episode = mDataSet.get(position);
return "Episode " + episode.getNumber();
}
@Override
public int getItemPosition(Object object) {
// TODO: 2016. 03. 11. recreates fragments everytime notifyOnDataSetChanges is called
// need a better mechanism to update fragments when he dataSet changes
return POSITION_NONE;
}
public void setDataSet(List<Episode> dataSet) {
mDataSet = dataSet;
}
}
<file_sep>apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
def getKey(Properties properties, String name) {
return properties.containsKey(name) ? properties.getProperty(name) : "DUMMY_KEY"
}
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.tlongdev.spicio"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
vectorDrawables.useSupportLibrary = true
Properties keys = new Properties()
if (project.rootProject.file('keys.properties').exists()) {
keys.load(project.rootProject.file('keys.properties').newDataInputStream())
}
buildConfigField("String", "TRAKT_API_KEY", "\"${getKey(keys, "TRAKT_API_KEY")}\"")
buildConfigField("String", "GOOGLE_WEB_CLIENT_ID", "\"${getKey(keys, "GOOGLE_WEB_CLIENT_ID")}\"")
resValue("string", "FACEBOOK_APP_ID", "${getKey(keys, "FACEBOOK_APP_ID")}")
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
testCoverageEnabled true
}
}
lintOptions {
disable 'InvalidPackage'
}
testOptions {
unitTests.all {
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
}
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.10.19'
testCompile "org.robolectric:robolectric:3.1-SNAPSHOT"
apt 'com.google.dagger:dagger-compiler:2.0.2'
provided 'com.f2prateek.dart:dart-processor:2.0.0'
provided 'org.glassfish:javax.annotation:10.0-b28'
compile('com.squareup.retrofit2:converter-simplexml:2.0.0-beta4') {
exclude group: 'xpp3', module: 'xpp3'
exclude group: 'stax', module: 'stax-api'
exclude group: 'stax', module: 'stax'
}
compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.android.support:cardview-v7:23.2.1'
compile 'com.android.support:design:23.2.1'
compile 'com.android.support:support-v4:23.2.1'
compile 'com.android.support:support-annotations:23.2.1'
compile 'com.android.support:percent:23.2.1'
compile 'com.f2prateek.dart:dart:2.0.0'
compile 'com.facebook.android:facebook-android-sdk:4.10.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.google.android.gms:play-services-auth:8.4.0'
compile 'com.google.dagger:dagger:2.0.2'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.squareup.okhttp3:okhttp:3.1.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'net.danlew:android.joda:2.9.2'
}
apply plugin: 'com.google.gms.google-services'<file_sep>package com.tlongdev.spicio.presentation.presenter.activity;
import android.util.Log;
import com.tlongdev.spicio.domain.interactor.SaveSeriesInteractor;
import com.tlongdev.spicio.domain.interactor.TraktFullSeriesInteractor;
import com.tlongdev.spicio.domain.interactor.TraktSeriesDetailsInteractor;
import com.tlongdev.spicio.domain.interactor.impl.SaveSeriesInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.TraktFullSeriesInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.TraktSeriesDetailsInteractorImpl;
import com.tlongdev.spicio.domain.model.Episode;
import com.tlongdev.spicio.domain.model.Season;
import com.tlongdev.spicio.domain.model.Series;
import com.tlongdev.spicio.presentation.presenter.Presenter;
import com.tlongdev.spicio.presentation.ui.view.activity.SeriesSearchDetailsView;
import java.util.List;
/**
* @author Long
* @since 2016. 03. 04.
*/
public class SeriesSearchDetailsPresenter implements Presenter<SeriesSearchDetailsView>,
TraktSeriesDetailsInteractor.Callback, SaveSeriesInteractor.Callback,
TraktFullSeriesInteractor.Callback {
private static final String LOG_TAG = SeriesSearchDetailsPresenter.class.getSimpleName();
private SeriesSearchDetailsView mView;
@Override
public void attachView(SeriesSearchDetailsView view) {
mView = view;
}
@Override
public void detachView() {
mView = null;
}
public void loadDetails(int traktId) {
TraktSeriesDetailsInteractor interactor = new TraktSeriesDetailsInteractorImpl(
mView.getSpicioApplication(), traktId, this
);
interactor.execute();
}
@Override
public void onTraktSeriesDetailsFinish(Series series) {
if (mView != null) {
mView.showDetails(series);
}
}
@Override
public void onTraktSeriesDetailsFail() {
// TODO: 2016. 03. 11.
}
@Override
public void onTraktFullSeriesFinish(Series series, List<Season> seasons, List<Episode> episodes) {
Log.d(LOG_TAG, "finished downloading all series data, inserting into db");
SaveSeriesInteractor interactor = new SaveSeriesInteractorImpl(
mView.getSpicioApplication(), series, seasons, episodes, this
);
interactor.execute();
}
@Override
public void onTraktFullSeriesFail() {
if (mView != null) {
mView.reportError();
}
}
public void saveSeries(Series series) {
Log.d(LOG_TAG, "saveSeries() called");
mView.showLoading();
TraktFullSeriesInteractor interactor = new TraktFullSeriesInteractorImpl(
mView.getSpicioApplication(), series.getTraktId(), this
);
interactor.execute();
}
@Override
public void onSaveSeriesFinish() {
if (mView != null) {
mView.onSeriesSaved();
mView.hideLoading();
}
}
@Override
public void onSaveSeriesFail() {
// TODO: 2016. 03. 11.
}
}
<file_sep>package com.tlongdev.spicio.presentation.ui.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.tlongdev.spicio.R;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.domain.model.Series;
import com.tlongdev.spicio.presentation.presenter.fragment.SeriesPresenter;
import com.tlongdev.spicio.presentation.ui.activity.SeriesActivity;
import com.tlongdev.spicio.presentation.ui.adapter.SeriesAdapter;
import com.tlongdev.spicio.presentation.ui.view.fragment.SeriesView;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* A simple {@link Fragment} subclass.
*/
public class SeriesFragment extends Fragment implements SeriesView, SeriesAdapter.OnItemSelectedListener {
@Bind(R.id.recycler_view) RecyclerView mRecyclerView;
private SeriesPresenter presenter;
private SeriesAdapter adapter;
public SeriesFragment() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
presenter = new SeriesPresenter();
presenter.attachView(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_series, container, false);
ButterKnife.bind(this, rootView);
//Set the toolbar to the main activity's action bar
((AppCompatActivity) getActivity()).setSupportActionBar((Toolbar) rootView.findViewById(R.id.toolbar));
adapter = new SeriesAdapter(getActivity());
adapter.setListener(this);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setAdapter(adapter);
return rootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
presenter.loadSeries();
}
@Override
public void onDestroy() {
super.onDestroy();
presenter.detachView();
}
@Override
public SpicioApplication getSpicioApplication() {
return (SpicioApplication) getActivity().getApplication();
}
@Override
public void showSeries(List<Series> series) {
adapter.setDataSet(series);
adapter.notifyDataSetChanged();
}
@Override
public void onItemSelected(Series series) {
Intent intent = new Intent(getActivity(), SeriesActivity.class);
intent.putExtra(SeriesActivity.EXTRA_SERIES_ID, series.getTraktId());
intent.putExtra(SeriesActivity.EXTRA_SERIES_TITLE, series.getTitle());
startActivity(intent);
}
}
<file_sep>package com.tlongdev.spicio.domain.model;
import org.joda.time.DateTime;
import org.joda.time.LocalTime;
/**
* Inner Layer, Model.
*
* @author Long
* @since 2016. 02. 28.
*/
public class TvdbSeriesOld {
private int id;
private String[] actors;
private int AirsDayOfWeek;
private LocalTime AirsTime;
private String contentRating;
private DateTime firstAired;
private String[] genres;
private String imdbId;
private String netWork;
private String overView;
private double tvdbRating;
private int tvdbRatingCount;
private int runTime;
private String name;
private int status;
private String bannerPath;
private String posterPath;
private String zapt2itId;
private String[] aliases;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String[] getActors() {
return actors;
}
public void setActors(String[] actors) {
this.actors = actors;
}
@Day.Enum
public int getAirsDayOfWeek() {
return AirsDayOfWeek;
}
public void setAirsDayOfWeek(@Day.Enum int airsDayOfWeek) {
AirsDayOfWeek = airsDayOfWeek;
}
public LocalTime getAirsTime() {
return AirsTime;
}
public void setAirsTime(LocalTime airsTime) {
AirsTime = airsTime;
}
public String getContentRating() {
return contentRating;
}
public void setContentRating(String contentRating) {
this.contentRating = contentRating;
}
public DateTime getFirstAired() {
return firstAired;
}
public void setFirstAired(DateTime firstAired) {
this.firstAired = firstAired;
}
public String[] getGenres() {
return genres;
}
public void setGenres(String[] genres) {
this.genres = genres;
}
public String getImdbId() {
return imdbId;
}
public void setImdbId(String imdbId) {
this.imdbId = imdbId;
}
public String getNetWork() {
return netWork;
}
public void setNetWork(String netWork) {
this.netWork = netWork;
}
public String getOverView() {
return overView;
}
public void setOverView(String overView) {
this.overView = overView;
}
public double getTvdbRating() {
return tvdbRating;
}
public void setTvdbRating(double tvdbRating) {
this.tvdbRating = tvdbRating;
}
public int getTvdbRatingCount() {
return tvdbRatingCount;
}
public void setTvdbRatingCount(int tvdbRatingCount) {
this.tvdbRatingCount = tvdbRatingCount;
}
public int getRunTime() {
return runTime;
}
public void setRunTime(int runTime) {
this.runTime = runTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Status.Enum
public int getStatus() {
return status;
}
public void setStatus(@Status.Enum int status) {
this.status = status;
}
public String getBannerPath() {
return bannerPath;
}
public void setBannerPath(String bannerPath) {
this.bannerPath = bannerPath;
}
public String getPosterPath() {
return posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public String getZapt2itId() {
return zapt2itId;
}
public void setZapt2itId(String zapt2itId) {
this.zapt2itId = zapt2itId;
}
public String[] getAliases() {
return aliases;
}
public void setAliases(String[] aliases) {
this.aliases = aliases;
}
}
<file_sep>package com.tlongdev.spicio.network.model;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
/**
* @author Long
* @since 2016. 03. 01.
*/
public class TraktSeries {
@SerializedName("title")
private String title;
@SerializedName("year")
private int year;
@SerializedName("ids")
private TraktIds ids;
@SerializedName("overview")
private String overview;
@SerializedName("first_aired")
private String firstAired;
@SerializedName("airs")
private TraktAirTime airs;
@SerializedName("runtime")
private int runtime;
@SerializedName("certification")
private String certification;
@SerializedName("network")
private String network;
@SerializedName("country")
private String country;
@SerializedName("trailer")
private String trailer;
@SerializedName("homepage")
private String homepage;
@SerializedName("status")
private String status;
@SerializedName("rating")
private double rating;
@SerializedName("votes")
private int votes;
@SerializedName("updated_at")
private String updatedAt;
@SerializedName("language")
private String language;
@SerializedName("available_translations")
private List<String> availableTranslations = new ArrayList<String>();
@SerializedName("genres")
private List<String> genres = new ArrayList<String>();
@SerializedName("aired_episodes")
private int airedEpisodes;
@SerializedName("images")
private TraktImages images;
public String getTitle() {
return title;
}
public int getYear() {
return year;
}
public TraktIds getIds() {
return ids;
}
public String getOverview() {
return overview;
}
public String getFirstAired() {
return firstAired;
}
public TraktAirTime getAirs() {
return airs;
}
public int getRuntime() {
return runtime;
}
public String getCertification() {
return certification;
}
public String getNetwork() {
return network;
}
public String getCountry() {
return country;
}
public String getTrailer() {
return trailer;
}
public String getHomepage() {
return homepage;
}
public String getStatus() {
return status;
}
public double getRating() {
return rating;
}
public int getVotes() {
return votes;
}
public String getUpdatedAt() {
return updatedAt;
}
public String getLanguage() {
return language;
}
public List<String> getAvailableTranslations() {
return availableTranslations;
}
public List<String> getGenres() {
return genres;
}
public int getAiredEpisodes() {
return airedEpisodes;
}
public TraktImages getImages() {
return images;
}
}
<file_sep>package com.tlongdev.spicio.domain.interactor;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.component.DaggerInteractorComponent;
import com.tlongdev.spicio.component.InteractorComponent;
import com.tlongdev.spicio.domain.interactor.impl.LoadSeriesDetailsInteractorImpl;
import com.tlongdev.spicio.domain.model.Series;
import com.tlongdev.spicio.module.FakeAppModule;
import com.tlongdev.spicio.module.FakeDaoModule;
import com.tlongdev.spicio.module.FakeThreadingModule;
import com.tlongdev.spicio.module.NetworkRepositoryModule;
import com.tlongdev.spicio.storage.dao.SeriesDao;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* @author Long
* @since 2016. 03. 09.
*/
@RunWith(MockitoJUnitRunner.class)
public class LoadSeriesDetailsInteractorTest {
@Mock
private SeriesDao mSeriesDao;
@Mock
private LoadSeriesDetailsInteractor.Callback mMockedCallback;
@Mock
private SpicioApplication mApp;
@Before
public void setUp() {
FakeDaoModule storageModule = new FakeDaoModule();
storageModule.setSeriesDao(mSeriesDao);
InteractorComponent component = DaggerInteractorComponent.builder()
.spicioAppModule(new FakeAppModule(mApp))
.daoModule(storageModule)
.networkRepositoryModule(mock(NetworkRepositoryModule.class))
.threadingModule(new FakeThreadingModule())
.build();
when(mApp.getInteractorComponent()).thenReturn(component);
}
@Test
public void testSuccess() {
Series series = new Series();
when(mSeriesDao.getSeries(0)).thenReturn(series);
LoadSeriesDetailsInteractorImpl interactor = new LoadSeriesDetailsInteractorImpl(
mApp, 0, mMockedCallback
);
interactor.run();
verify(mSeriesDao).getSeries(0);
verifyNoMoreInteractions(mSeriesDao);
verify(mMockedCallback).onLoadSeriesDetailsFinish(series);
}
@Test
public void testFail() {
when(mSeriesDao.getSeries(0)).thenReturn(null);
LoadSeriesDetailsInteractorImpl interactor = new LoadSeriesDetailsInteractorImpl(
mApp, 0, mMockedCallback
);
interactor.run();
verify(mSeriesDao).getSeries(0);
verifyNoMoreInteractions(mSeriesDao);
verify(mMockedCallback).onLoadSeriesDetailsFail();
}
}
<file_sep>package com.tlongdev.spicio.network;
import com.tlongdev.spicio.network.model.TvdbEpisodePayload;
import com.tlongdev.spicio.network.model.TvdbSeriesPayload;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
/**
* Outer layer, Network.
* Retrofit interface for using the TVDb api.
*
* http://www.thetvdb.com/wiki/index.php/Programmers_API
* @author Long
* @since 2016. 02. 24.
*/
public interface TvdbInterface {
String BASE_URL = "http://thetvdb.com/";
/**
* Searches for series using the api.
* http://www.thetvdb.com/wiki/index.php?title=API:GetSeries
*
* @param seriesName the name to search for
* @return the search result
*/
@GET("api/GetSeries.php")
Call<TvdbSeriesPayload> getSeries(@Query("seriesname") String seriesName);
/**
* Gets more information about a series.
* http://www.thetvdb.com/wiki/index.php?title=API:Base_Series_Record
*
* @param apiKey the TVDb API key
* @param seriesId the ID of the series
* @return more information about the series
*/
@GET("api/{apiKey}/series/{id}")
Call<TvdbSeriesPayload> getSeriesRecord(@Path("apiKey") String apiKey, @Path("id") int seriesId);
/**
* Gets information about an episode.
* http://www.thetvdb.com/wiki/index.php?title=API:Base_Episode_Record
*
* @param apiKey the TVDb API key
* @param seriesId the ID of the series
* @param season the season nmber
* @param episode the episode number
* @return the episode
*/
@GET("api/{apiKey}/series/{id}/default/{season}/{episode}")
Call<TvdbEpisodePayload> getEpisode(@Path("apiKey") String apiKey, @Path("id") int seriesId,
@Path("season") int season, @Path("episode") int episode);
/**
* Gets information about an episode.
* http://www.thetvdb.com/wiki/index.php?title=API:Base_Episode_Record
*
* @param apiKey the TVDb API key
* @param seriesId the ID of the series
* @param absoluteEpisode the absolute episode number
* @return the episode
*/
@GET("api/{apiKey}/series/{id}/absolute/{episode}")
Call<TvdbEpisodePayload> getEpisode(@Path("apiKey") String apiKey, @Path("id") int seriesId,
@Path("episode") int absoluteEpisode);
}
<file_sep>package com.tlongdev.spicio.domain.interactor;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.component.DaggerInteractorComponent;
import com.tlongdev.spicio.component.InteractorComponent;
import com.tlongdev.spicio.domain.interactor.impl.TraktSeriesDetailsInteractorImpl;
import com.tlongdev.spicio.domain.model.Series;
import com.tlongdev.spicio.domain.repository.TraktRepository;
import com.tlongdev.spicio.module.DaoModule;
import com.tlongdev.spicio.module.FakeAppModule;
import com.tlongdev.spicio.module.FakeNetworkRepositoryModule;
import com.tlongdev.spicio.module.FakeThreadingModule;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* @author Long
* @since 2016. 03. 04.
*/
@RunWith(MockitoJUnitRunner.class)
public class TraktSeriesDetailsInteractorTest {
@Mock
private TraktRepository mRepository;
@Mock
private TraktSeriesDetailsInteractor.Callback mMockedCallback;
@Mock
private SpicioApplication mApp;
@Before
public void setUp() {
FakeNetworkRepositoryModule networkRepositoryModule = new FakeNetworkRepositoryModule();
networkRepositoryModule.setTraktRepository(mRepository);
InteractorComponent component = DaggerInteractorComponent.builder()
.spicioAppModule(new FakeAppModule(mApp))
.networkRepositoryModule(networkRepositoryModule)
.daoModule(mock(DaoModule.class))
.threadingModule(new FakeThreadingModule())
.build();
when(mApp.getInteractorComponent()).thenReturn(component);
}
@Test
public void testSearchResult() {
Series series = mock(Series.class);
when(mRepository.getSeriesDetails(0)).thenReturn(series);
TraktSeriesDetailsInteractorImpl interactor = new TraktSeriesDetailsInteractorImpl(
mApp, 0, mMockedCallback
);
interactor.run();
verify(mRepository).getSeriesDetails(0);
verifyNoMoreInteractions(mRepository);
verify(mMockedCallback).onTraktSeriesDetailsFinish(series);
}
@Test
public void testSearchFail() {
when(mRepository.getSeriesDetails(0)).thenReturn(null);
TraktSeriesDetailsInteractorImpl interactor = new TraktSeriesDetailsInteractorImpl(
mApp, 0, mMockedCallback
);
interactor.run();
verify(mRepository).getSeriesDetails(0);
verifyNoMoreInteractions(mRepository);
verify(mMockedCallback).onTraktSeriesDetailsFail();
}
}
<file_sep>package com.tlongdev.spicio.util;
/**
* @author Long
* @since 2016. 03. 05.
*/
public class Utility {
public static String join(String[] strings, String delimiter) {
StringBuilder sb = new StringBuilder();
String sep = "";
for(String s: strings) {
sb.append(sep).append(s);
sep = delimiter;
}
return sb.toString();
}
}
<file_sep>package com.tlongdev.spicio.domain.interactor;
import com.tlongdev.spicio.domain.model.Episode;
import java.util.List;
/**
* @author Long
* @since 2016. 03. 10.
*/
public interface TraktSeasonEpisodesInteractor extends Interactor {
interface Callback {
void onTraktSeasonEpisodesFinish(List<Episode> episodes);
void onTraktSeasonEpisodesFail();
}
}<file_sep>package com.tlongdev.spicio.presentation.presenter.activity;
import android.util.Log;
import com.tlongdev.spicio.domain.interactor.SaveSeriesInteractor;
import com.tlongdev.spicio.domain.interactor.TraktFullSeriesInteractor;
import com.tlongdev.spicio.domain.interactor.impl.SaveSeriesInteractorImpl;
import com.tlongdev.spicio.domain.interactor.impl.TraktFullSeriesInteractorImpl;
import com.tlongdev.spicio.domain.model.Episode;
import com.tlongdev.spicio.domain.model.Season;
import com.tlongdev.spicio.domain.model.Series;
import com.tlongdev.spicio.presentation.presenter.Presenter;
import com.tlongdev.spicio.presentation.ui.view.activity.SeriesView;
import java.util.List;
/**
* @author Long
* @since 2016. 03. 12.
*/
public class SeriesPresenter implements Presenter<SeriesView>,TraktFullSeriesInteractor.Callback, SaveSeriesInteractor.Callback {
private static final String LOG_TAG = SeriesPresenter.class.getSimpleName();
private SeriesView mView;
private int mSeriesId;
public SeriesPresenter(int seriesId) {
mSeriesId = seriesId;
}
@Override
public void attachView(SeriesView view) {
mView = view;
}
@Override
public void detachView() {
mView = null;
}
public void refreshSeries() {
mView.showLoading();
TraktFullSeriesInteractor interactor = new TraktFullSeriesInteractorImpl(
mView.getSpicioApplication(), mSeriesId, this
);
interactor.execute();
}
@Override
public void onTraktFullSeriesFinish(Series series, List<Season> seasons, List<Episode> episodes) {
Log.d(LOG_TAG, "finished downloading all series data, inserting into db");
SaveSeriesInteractor interactor = new SaveSeriesInteractorImpl(
mView.getSpicioApplication(), series, seasons, episodes, this
);
interactor.execute();
}
@Override
public void onTraktFullSeriesFail() {
if (mView != null) {
mView.hideLoading();
}
}
@Override
public void onSaveSeriesFinish() {
if (mView != null) {
mView.reloadData();
mView.hideLoading();
}
}
@Override
public void onSaveSeriesFail() {
if (mView != null) {
mView.hideLoading();
}
}
}<file_sep>package com.tlongdev.spicio.domain.model;
import android.support.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Inner Layer, Model.
* Days of the week.
*
* @author Long
* @since 2016. 02. 23.
*/
public abstract class Day {
@IntDef({MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY})
@Retention(RetentionPolicy.SOURCE)
public @interface Enum {}
public static final int MONDAY = 0;
public static final int TUESDAY = 1;
public static final int WEDNESDAY = 2;
public static final int THURSDAY = 3;
public static final int FRIDAY = 4;
public static final int SATURDAY = 5;
public static final int SUNDAY = 6;
}
<file_sep>package com.tlongdev.spicio.presentation.ui.view.activity;
import com.tlongdev.spicio.presentation.ui.view.BaseView;
/**
* @author Long
* @since 2016. 03. 13.
*/
public interface SettingsView extends BaseView {
void startLoginActivity();
}<file_sep>package com.tlongdev.spicio.domain.interactor.impl;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.domain.interactor.AbstractInteractor;
import com.tlongdev.spicio.domain.interactor.SaveSeriesInteractor;
import com.tlongdev.spicio.domain.model.Episode;
import com.tlongdev.spicio.domain.model.Season;
import com.tlongdev.spicio.domain.model.Series;
import com.tlongdev.spicio.storage.dao.EpisodeDao;
import com.tlongdev.spicio.storage.dao.SeriesDao;
import com.tlongdev.spicio.util.Logger;
import java.util.List;
import javax.inject.Inject;
/**
* @author Long
* @since 2016. 03. 05.
*/
public class SaveSeriesInteractorImpl extends AbstractInteractor implements SaveSeriesInteractor {
private static final String LOG_TAG = SaveSeriesInteractorImpl.class.getSimpleName();
@Inject SeriesDao mSeriesDao;
@Inject EpisodeDao mEpisodeDao;
@Inject Logger logger;
private Series mSeries;
private List<Season> mSeasons;
private List<Episode> mEpisodes;
private Callback mCallback;
public SaveSeriesInteractorImpl(SpicioApplication app, Series series, List<Season> seasons,
List<Episode> episodes, Callback callback) {
super(app.getInteractorComponent());
app.getInteractorComponent().inject(this);
mSeries = series;
mCallback = callback;
mSeasons = seasons;
mEpisodes = episodes;
}
@Override
public void run() {
logger.debug(LOG_TAG, "started");
logger.debug(LOG_TAG, "inserting episodes into database");
mEpisodeDao.insertAllEpisodes(mEpisodes);
logger.debug(LOG_TAG, "inserting seasons into database");
mEpisodeDao.insertAllSeasons(mSeasons);
logger.debug(LOG_TAG, "inserting the series");
mSeriesDao.insertSeries(mSeries);
postFinish();
logger.debug(LOG_TAG, "finished");
}
private void postError() {
if (mCallback == null) {
return;
}
mMainThread.post(new Runnable() {
@Override
public void run() {
mCallback.onSaveSeriesFail();
}
});
}
private void postFinish() {
if (mCallback == null) {
return;
}
mMainThread.post(new Runnable() {
@Override
public void run() {
mCallback.onSaveSeriesFinish();
}
});
}
}
<file_sep>package com.tlongdev.spicio.component;
import com.tlongdev.spicio.module.SpicioAppModule;
import com.tlongdev.spicio.module.StorageModule;
import com.tlongdev.spicio.storage.dao.impl.EpisodeDaoImpl;
import com.tlongdev.spicio.storage.dao.impl.SeriesDaoImpl;
import javax.inject.Singleton;
import dagger.Component;
/**
* @author Long
* @since 2016. 03. 05.
*/
@Singleton
@Component(modules = {SpicioAppModule.class, StorageModule.class})
public interface StorageComponent {
void inject(SeriesDaoImpl seriesDao);
void inject(EpisodeDaoImpl episodeDao);
}
<file_sep>package com.tlongdev.spicio.component;
import com.tlongdev.spicio.module.SpicioAppModule;
import com.tlongdev.spicio.util.ProfileManager;
import javax.inject.Singleton;
import dagger.Component;
/**
* @author Long
* @since 2016. 03. 13.
*/
@Singleton
@Component(modules = SpicioAppModule.class)
public interface ProfileManagerComponent {
void inject(ProfileManager profileManager);
}
<file_sep>package com.tlongdev.spicio.network;
import com.tlongdev.spicio.network.model.TraktEpisode;
import com.tlongdev.spicio.network.model.TraktSearchResult;
import com.tlongdev.spicio.network.model.TraktSeason;
import com.tlongdev.spicio.network.model.TraktSeries;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
/**
* Outer Layer, Network.
*
* @author Long
* @since 2016. 03. 01.
*/
public interface TraktApiInterface {
String BASE_URL = "https://api-v2launch.trakt.tv/";
/**
* Search trakt.tv database by text. Narrow down search result with the type paramater.
*
* @param query the query string to search for
* @param type can be movie, show, episode, person, list
* @return the search result
*/
@GET("search")
Call<List<TraktSearchResult>> searchByText(@Query("query") String query, @Query("type") String type);
/**
* Search trakt.tv database by id. Narrow down search result with the type parameter.
*
* @param idType type of the ID, can be trakt-movie, trakt-show, trakt-episode, imdb, tmdb, tvdb, tvrage
* @param id the id of the item
* @return the search result
*/
@GET("search")
Call<List<TraktSearchResult>> searchById(@Query("id_type") String idType, @Query("id") String id);
/**
* Get the details of a series.
*
* @param id the id of the series, can be trakt.tv ID, trakt.tv slug or IMDB ID
* @return the details of a series
*/
@GET("shows/{id}?extended=full")
Call<TraktSeries> getSeriesDetails(@Path("id") String id);
/**
* Get the images for a series.
*
* @param id the id of the series, can be trakt.tv ID, trakt.tv slug or IMDB ID
* @return the images for a series
*/
@GET("shows/{id}?extended=images")
Call<TraktSeries> getSeriesImages(@Path("id") String id);
/**
* Get the details of a season of a series.
*
* @param id the id of the series, can be trakt.tv ID, trakt.tv slug or IMDB ID
* @return the details of a season
*/
@GET("shows/{id}/seasons?extended=full")
Call<List<TraktSeason>> getSeasonsDetails(@Path("id") String id);
/**
* Get the images for a season of a series.
*
* @param id the id of the series, can be trakt.tv ID, trakt.tv slug or IMDB ID
* @return the images for a season
*/
@GET("shows/{id}/seasons?extended=images")
Call<List<TraktSeason>> getSeasonsImages(@Path("id") String id);
@GET("shows/{id}/seasons?extended=episodes")
Call<List<TraktSeason>> getSeasonsEpisodes(@Path("id") String id);
/**
* Get the episodes of a season of a series
*
* @param id the id of the series, can be trakt.tv ID, trakt.tv slug or IMDB ID
* @param season the season number (0 for special episodes)
* @return the episodes of a season
*/
@GET("shows/{id}/seasons/{season}?extended=full")
Call<List<TraktEpisode>> getSeasonEpisodes(@Path("id") String id, @Path("season") int season);
/**
* Get the episodes of a season of a series
*
* @param id the id of the series, can be trakt.tv ID, trakt.tv slug or IMDB ID
* @param season the season number (0 for special episodes)
* @return the episodes of a season
*/
@GET("shows/{id}/seasons/{season}?extended=images")
Call<List<TraktEpisode>> getSeasonEpisodesImages(@Path("id") String id, @Path("season") int season);
/**
* Get a single episode of a season of a series.
*
* @param id the id of the series, can be trakt.tv ID, trakt.tv slug or IMDB ID
* @param season the season number
* @param episode the episode number
* @return the single episode
*/
@GET("shows/{id}/seasons/{season}/episodes/{episode}?extended=full")
Call<TraktEpisode> getSingleEpisodeDetails(@Path("id") String id, @Path("season") int season, @Path("episode") int episode);
/**
* Get a images for an episode of a season of a series.
*
* @param id the id of the series, can be trakt.tv ID, trakt.tv slug or IMDB ID
* @param season the season number
* @param episode the episode number
* @return the images for the episode
*/
@GET("shows/{id}/seasons/{season}/episodes/{episode}?extended=full")
Call<TraktEpisode> getSingleEpisodeImages(@Path("id") String id, @Path("season") int season, @Path("episode") int episode);
}
<file_sep>package com.tlongdev.spicio.domain.interactor;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.component.DaggerInteractorComponent;
import com.tlongdev.spicio.component.InteractorComponent;
import com.tlongdev.spicio.domain.interactor.impl.TraktFullSeriesInteractorImpl;
import com.tlongdev.spicio.domain.model.Episode;
import com.tlongdev.spicio.domain.model.Images;
import com.tlongdev.spicio.domain.model.Season;
import com.tlongdev.spicio.domain.model.Series;
import com.tlongdev.spicio.domain.repository.TraktRepository;
import com.tlongdev.spicio.module.DaoModule;
import com.tlongdev.spicio.module.FakeAppModule;
import com.tlongdev.spicio.module.FakeNetworkRepositoryModule;
import com.tlongdev.spicio.module.FakeThreadingModule;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.LinkedList;
import java.util.List;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* @author Long
* @since 2016. 03. 08.
*/
@RunWith(MockitoJUnitRunner.class)
public class TraktFullSeriesInteractorTest {
@Mock
private TraktRepository mRepository;
@Mock
private TraktFullSeriesInteractor.Callback mMockedCallback;
@Mock
private SpicioApplication mApp;
@Before
public void setUp() {
FakeNetworkRepositoryModule networkRepositoryModule = new FakeNetworkRepositoryModule();
networkRepositoryModule.setTraktRepository(mRepository);
InteractorComponent component = DaggerInteractorComponent.builder()
.spicioAppModule(new FakeAppModule(mApp))
.networkRepositoryModule(networkRepositoryModule)
.daoModule(mock(DaoModule.class))
.threadingModule(new FakeThreadingModule())
.build();
when(mApp.getInteractorComponent()).thenReturn(component);
}
@Test
public void testSuccess() {
Series series = mock(Series.class);
List<Season> seasons = new LinkedList<>();
seasons.add(mock(Season.class));
when(seasons.get(0).getNumber()).thenReturn(0);
List<Episode> episodes = new LinkedList<>();
when(mRepository.getSeriesDetails(0)).thenReturn(series);
when(mRepository.getImages(0)).thenReturn(new Images());
when(mRepository.getSeasons(0)).thenReturn(seasons);
when(mRepository.getEpisodeImages(0, 0)).thenReturn(episodes);
when(mRepository.getSeasonEpisodes(0, 0)).thenReturn(episodes);
TraktFullSeriesInteractorImpl interactor = new TraktFullSeriesInteractorImpl(
mApp, 0, mMockedCallback
);
interactor.run();
verify(mRepository).getSeriesDetails(0);
verify(mRepository).getImages(0);
verify(mRepository).getSeasons(0);
verify(mRepository).getEpisodeImages(0, 0);
verify(mRepository).getSeasonEpisodes(0, 0);
verifyNoMoreInteractions(mRepository);
verify(mMockedCallback).onTraktFullSeriesFinish(series, seasons, episodes);
}
@Test
public void testFail() {
when(mRepository.getSeriesDetails(0)).thenReturn(null);;
TraktFullSeriesInteractorImpl interactor = new TraktFullSeriesInteractorImpl(
mApp, 0, mMockedCallback
);
interactor.run();
verify(mRepository).getSeriesDetails(0);
verifyNoMoreInteractions(mRepository);
verify(mMockedCallback).onTraktFullSeriesFail();
}
}
<file_sep>package com.tlongdev.spicio.presentation.presenter.activity;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import com.facebook.login.LoginManager;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallbacks;
import com.google.android.gms.common.api.Status;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.domain.interactor.DeleteAllDataInteractor;
import com.tlongdev.spicio.domain.interactor.impl.DeleteAllDataInteractorImpl;
import com.tlongdev.spicio.presentation.presenter.Presenter;
import com.tlongdev.spicio.presentation.ui.view.activity.SettingsView;
import com.tlongdev.spicio.util.Logger;
import com.tlongdev.spicio.util.ProfileManager;
import javax.inject.Inject;
/**
* @author Long
* @since 2016. 03. 13.
*/
public class SettingsPresenter implements Presenter<SettingsView>,DeleteAllDataInteractor.Callback {
private static final String LOG_TAG = SettingsPresenter.class.getSimpleName();
@Inject ProfileManager mProfileManager;
@Inject GoogleApiClient mGoogleApiClient;
@Inject Logger mLogger;
private SettingsView mView;
private SpicioApplication mApplication;
public SettingsPresenter(SpicioApplication application) {
mApplication = application;
application.getPresenterComponent().inject(this);
}
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* @see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
@Override
public void attachView(SettingsView view) {
mView = view;
}
@Override
public void detachView() {
mView = null;
}
public void logout() {
mProfileManager.logout();
LoginManager.getInstance().logOut();
if (mGoogleApiClient.isConnected()) {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallbacks<Status>() {
@Override
public void onSuccess(@NonNull Status status) {
mLogger.debug(LOG_TAG, "onSuccess: ");
}
@Override
public void onFailure(@NonNull Status status) {
mLogger.debug(LOG_TAG, "onFailure: ");
}
}
);
}
DeleteAllDataInteractor interactor = new DeleteAllDataInteractorImpl(
mApplication, this
);
interactor.execute();
}
public void connectGoogleApiClient() {
mGoogleApiClient.connect();
}
public void disconnectGoogleApiClient() {
mGoogleApiClient.disconnect();
}
@Override
public void onFinish() {
if (mView != null) {
mView.startLoginActivity();
}
}
@Override
public void onFail() {
}
}<file_sep>package com.tlongdev.spicio.domain.interactor.impl;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.domain.interactor.AbstractInteractor;
import com.tlongdev.spicio.domain.interactor.TraktSearchInteractor;
import com.tlongdev.spicio.domain.model.Series;
import com.tlongdev.spicio.domain.repository.TraktRepository;
import com.tlongdev.spicio.util.Logger;
import java.util.List;
import javax.inject.Inject;
/**
* @author Long
* @since 2016. 03. 04.
*/
public class TraktSearchInteractorImpl extends AbstractInteractor implements TraktSearchInteractor {
private static final String LOG_TAG = TraktSearchInteractorImpl.class.getSimpleName();
@Inject TraktRepository mRepository;
@Inject Logger logger;
private String mSearchQuery;
private Callback mCallback;
public TraktSearchInteractorImpl(SpicioApplication app, String searchQuery, Callback callback) {
super(app.getInteractorComponent());
app.getInteractorComponent().inject(this);
mSearchQuery = searchQuery;
mCallback = callback;
}
@Override
public void run() {
logger.debug(LOG_TAG, "started");
List<Series> searchResult = mRepository.searchSeries(mSearchQuery);
if (searchResult == null) {
postError();
} else {
postResult(searchResult);
}
logger.debug(LOG_TAG, "finished");
}
private void postError() {
if (mCallback == null) {
return;
}
mMainThread.post(new Runnable() {
@Override
public void run() {
mCallback.onTraktSearchFailed();
}
});
}
private void postResult(final List<Series> searchResult) {
if (mCallback == null) {
return;
}
mMainThread.post(new Runnable() {
@Override
public void run() {
mCallback.onTraktSearchFinish(searchResult);
}
});
}
}
<file_sep>package com.tlongdev.spicio.network.converter;
import com.tlongdev.spicio.domain.model.Day;
import com.tlongdev.spicio.domain.model.Episode;
import com.tlongdev.spicio.domain.model.Image;
import com.tlongdev.spicio.domain.model.Images;
import com.tlongdev.spicio.domain.model.Season;
import com.tlongdev.spicio.domain.model.Series;
import com.tlongdev.spicio.domain.model.Status;
import com.tlongdev.spicio.network.model.TraktEpisode;
import com.tlongdev.spicio.network.model.TraktImage;
import com.tlongdev.spicio.network.model.TraktImages;
import com.tlongdev.spicio.network.model.TraktSeason;
import com.tlongdev.spicio.network.model.TraktSeries;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import java.util.List;
import java.util.Locale;
/**
* @author Long
* @since 2016. 03. 02.
*/
public class TraktModelConverter {
public static Image convertToImage(TraktImage traktImage) {
if (traktImage == null) {
return null;
}
Image image = new Image();
image.setFull(traktImage.getFull());
image.setMedium(traktImage.getMedium());
image.setThumb(traktImage.getThumb());
return image;
}
public static Images convertToImages(TraktImages traktImages) {
if (traktImages == null) {
return null;
}
Images images = new Images();
images.setBanner(convertToImage(traktImages.getBanner()));
images.setClearArt(convertToImage(traktImages.getClearart()));
images.setFanArt(convertToImage(traktImages.getFanart()));
images.setLogo(convertToImage(traktImages.getLogo()));
images.setPoster(convertToImage(traktImages.getPoster()));
images.setScreenshot(convertToImage(traktImages.getScreenshot()));
images.setThumb(convertToImage(traktImages.getThumb()));
return images;
}
public static Series convertToSeries(TraktSeries traktSeries) {
if (traktSeries == null) {
return null;
}
Series series = new Series();
series.setCertification(traktSeries.getCertification());
List<String> genres = traktSeries.getGenres();
series.setGenres(genres.toArray(new String[genres.size()]));
series.setYear(traktSeries.getYear());
series.setOverview(traktSeries.getOverview());
series.setTitle(traktSeries.getTitle());
series.setRuntime(traktSeries.getRuntime());
series.setTrailer(traktSeries.getTrailer());
series.setTraktRating(traktSeries.getRating());
series.setTraktRatingCount(traktSeries.getVotes());
series.setNetwork(traktSeries.getNetwork());
series.setImages(convertToImages(traktSeries.getImages()));
series.setImdbId(traktSeries.getIds().getImdb());
series.setTmdbId(traktSeries.getIds().getTmdb() == null ? -1 : traktSeries.getIds().getTmdb());
series.setTraktId(traktSeries.getIds().getTrakt() == null ? -1 : traktSeries.getIds().getTrakt());
series.setTvdbId(traktSeries.getIds().getTvdb() == null ? -1 : traktSeries.getIds().getTvdb());
series.setTvRageId(traktSeries.getIds().getTvrage() == null ? -1 : traktSeries.getIds().getTvrage());
series.setSlugName(traktSeries.getIds().getSlug());
switch (traktSeries.getStatus()) { // TODO: 2016. 03. 05. other status codes
case "returning series":
series.setStatus(Status.CONTINUING);
break;
default:
series.setStatus(Status.NULL);
break;
}
if (traktSeries.getAirs() != null) {
if (traktSeries.getAirs().getDay() != null) {
switch (traktSeries.getAirs().getDay()) {
case "Monday":
series.setDayOfAiring(Day.MONDAY);
break;
case "Tuesday":
series.setDayOfAiring(Day.TUESDAY);
break;
case "Wednesday":
series.setDayOfAiring(Day.WEDNESDAY);
break;
case "Thursday":
series.setDayOfAiring(Day.THURSDAY);
break;
case "Friday":
series.setDayOfAiring(Day.FRIDAY);
break;
case "Saturday":
series.setDayOfAiring(Day.SATURDAY);
break;
case "Sunday":
series.setDayOfAiring(Day.SUNDAY);
break;
default:
throw new IllegalStateException(traktSeries.getAirs().getDay());
}
}
if (traktSeries.getAirs().getTimezone() != null) {
series.setAirTimeZone(DateTimeZone.forID(traktSeries.getAirs().getTimezone()));
}
if (traktSeries.getAirs().getTime() != null) {
DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("H:mm").withLocale(Locale.US);
series.setTimeOfAiring(LocalTime.parse(traktSeries.getAirs().getTime(), timeFormatter));
}
if (traktSeries.getFirstAired() != null) {
DateTimeFormatter dateFormatter = ISODateTimeFormat.dateTime(); //yyyyMMdd'T'HHmmss.SSSZ
series.setFirstAired(dateFormatter.parseDateTime(traktSeries.getFirstAired()));
}
}
return series;
}
public static Episode convertToEpisode(TraktEpisode traktEpisode) {
Episode episode = new Episode();
episode.setSeason(traktEpisode.getSeason());
episode.setNumber(traktEpisode.getNumber());
episode.setTitle(traktEpisode.getTitle());
episode.setImages(convertToImages(traktEpisode.getImages()));
episode.setAbsoluteNumber(traktEpisode.getNumberAbs() == null ? -1 : traktEpisode.getNumberAbs());
episode.setOverview(traktEpisode.getOverview());
episode.setTraktRating(traktEpisode.getRating());
episode.setTraktRatingCount(traktEpisode.getVotes());
episode.setImdbId(traktEpisode.getIds().getImdb());
episode.setTmdbId(traktEpisode.getIds().getTmdb() == null ? -1 : traktEpisode.getIds().getTmdb());
episode.setTraktId(traktEpisode.getIds().getTrakt() == null ? -1 : traktEpisode.getIds().getTrakt());
episode.setTvdbId(traktEpisode.getIds().getTvdb() == null ? -1 : traktEpisode.getIds().getTvdb());
episode.setTvRageId(traktEpisode.getIds().getTvrage() == null ? -1 : traktEpisode.getIds().getTvrage());
episode.setSlugName(traktEpisode.getIds().getSlug());
if (traktEpisode.getFirstAired() != null) {
DateTimeFormatter dateFormatter = ISODateTimeFormat.dateTime(); //yyyyMMdd'T'HHmmss.SSSZ
episode.setFirstAired(dateFormatter.parseDateTime(traktEpisode.getFirstAired()));
}
return episode;
}
public static Season convertToSeason(int seriesId, TraktSeason traktSeason) {
Season season = new Season();
season.setSeriesId(seriesId);
season.setNumber(traktSeason.getNumber());
season.setImages(TraktModelConverter.convertToImages(traktSeason.getImages()));
return season;
}
}
<file_sep>apply plugin: 'jacoco'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.0.0-beta6'
classpath 'com.google.gms:google-services:2.0.0-beta6'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
allprojects {
repositories {
jcenter()
mavenCentral()
maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
subprojects { prj ->
apply plugin: 'jacoco'
jacoco {
toolVersion '0.7.1.201405082137'
}
task jacocoReport(type: JacocoReport, dependsOn: 'testDebugUnitTest') {
group = 'Reporting'
description = 'Generate Jacoco coverage reports after running tests.'
reports {
xml {
enabled = true
destination "${prj.buildDir}/reports/jacoco/jacoco.xml"
}
html {
enabled = true
destination "${prj.buildDir}/reports/jacoco"
}
}
classDirectories = fileTree(
dir: 'build/intermediates/classes/debug',
excludes: [
'**/R*.class',
'**/BuildConfig*',
'**/*$$*'
]
)
sourceDirectories = files('src/main/java')
executionData = files('build/jacoco/testDebugUnitTest.exec')
doFirst {
files('build/intermediates/classes/debug').getFiles().each { file ->
if (file.name.contains('$$')) {
file.renameTo(file.path.replace('$$', '$'))
}
}
}
}
}
jacoco {
toolVersion '0.7.1.201405082137'
}
task jacocoFullReport(type: JacocoReport, group: 'Coverage reports') {
group = 'Reporting'
description = 'Generates an aggregate report from all subprojects'
//noinspection GrUnresolvedAccess
dependsOn(subprojects.jacocoReport)
additionalSourceDirs = project.files(subprojects.jacocoReport.sourceDirectories)
sourceDirectories = project.files(subprojects.jacocoReport.sourceDirectories)
classDirectories = project.files(subprojects.jacocoReport.classDirectories)
executionData = project.files(subprojects.jacocoReport.executionData)
reports {
xml {
enabled = true
destination "${buildDir}/reports/jacoco/full/jacoco.xml"
}
html {
enabled = true
destination "${buildDir}/reports/jacoco/full"
}
}
doFirst {
//noinspection GroovyAssignabilityCheck
executionData = files(executionData.findAll { it.exists() })
}
}<file_sep>package com.tlongdev.spicio.network.model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* @author Long
* @since 2016. 03. 01.
*/
public class TraktSeason {
@SerializedName("number")
private int number;
@SerializedName("ids")
private TraktIds ids;
@SerializedName("images")
private TraktImages images;
@SerializedName("rating")
private double rating;
@SerializedName("votes")
private int votes;
@SerializedName("episode_count")
private int episodeCount;
@SerializedName("aired_episodes")
private int airedEpisodes;
@SerializedName("overview")
private String overview;
@SerializedName("episodes")
private List<TraktEpisode> episodes;
public int getNumber() {
return number;
}
public TraktIds getIds() {
return ids;
}
public TraktImages getImages() {
return images;
}
public double getRating() {
return rating;
}
public int getVotes() {
return votes;
}
public int getEpisodeCount() {
return episodeCount;
}
public int getAiredEpisodes() {
return airedEpisodes;
}
public String getOverview() {
return overview;
}
public List<TraktEpisode> getEpisodes() {
return episodes;
}
}
<file_sep>package com.tlongdev.spicio.module;
import android.app.Application;
import com.tlongdev.spicio.storage.dao.EpisodeDao;
import com.tlongdev.spicio.storage.dao.SeriesDao;
/**
* @author Long
* @since 2016. 03. 07.
*/
public class FakeDaoModule extends DaoModule {
private SeriesDao mSeriesDao;
private EpisodeDao mEpisodeDao;
@Override
SeriesDao provideSeriesDao(Application application) {
return mSeriesDao;
}
@Override
EpisodeDao provideEpisodeDao(Application application) {
return mEpisodeDao;
}
public void setSeriesDao(SeriesDao seriesDao) {
this.mSeriesDao = seriesDao;
}
public void setEpisodeDao(EpisodeDao episodeDao) {
this.mEpisodeDao = episodeDao;
}
}
<file_sep>package com.tlongdev.spicio.module;
import android.app.Application;
import com.facebook.CallbackManager;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.GoogleApiClient;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.util.ProfileManager;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
/**
* @author Long
* @since 2016. 03. 13.
*/
@Module
public class AuthenticationModule {
@Provides
@Singleton
GoogleSignInOptions provideGoogleSignInOptions() {
return new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
}
@Provides
@Singleton
GoogleApiClient provideGoogleApiClient(Application application, GoogleSignInOptions googleSignInOptions) {
return new GoogleApiClient.Builder(application)
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
.build();
}
@Provides
@Singleton
CallbackManager provideCallbackManager() {
return CallbackManager.Factory.create();
}
@Provides
@Singleton
ProfileManager provideProfileManager(Application application) {
return new ProfileManager((SpicioApplication) application);
}
}
<file_sep>package com.tlongdev.spicio.storage.dao;
import android.net.Uri;
import com.tlongdev.spicio.domain.model.Series;
import java.util.List;
/**
* Middle Layer, Converter.
*
* @author Long
* @since 2016. 02. 29.
*/
public interface SeriesDao {
/**
* Get a single series from the database.
*
* @param seriesId the id of the series
* @return the series
*/
Series getSeries(int seriesId);
/**
* Get all the series from the database.
*
* @return all the series
*/
List<Series> getAllSeries();
/**
* Inserts a series into the database.
*
* @param series the series to delete
*/
Uri insertSeries(Series series);
/**
* Deletes a series from the database
*
* @param seriesId the id of the series
*/
void deleteSeries(int seriesId);
/**
* Deletes all the series records from the database.
*/
void deleteAllData();
}
<file_sep>package com.tlongdev.spicio.domain.interactor;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.component.DaggerInteractorComponent;
import com.tlongdev.spicio.component.InteractorComponent;
import com.tlongdev.spicio.domain.interactor.impl.LoadEpisodeDetailsInteractorImpl;
import com.tlongdev.spicio.domain.model.Episode;
import com.tlongdev.spicio.domain.model.Series;
import com.tlongdev.spicio.module.FakeAppModule;
import com.tlongdev.spicio.module.FakeDaoModule;
import com.tlongdev.spicio.module.FakeThreadingModule;
import com.tlongdev.spicio.module.NetworkRepositoryModule;
import com.tlongdev.spicio.storage.dao.EpisodeDao;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* @author Long
* @since 2016. 03. 11.
*/
@RunWith(MockitoJUnitRunner.class)
public class LoadEpisodeDetailsInteractorTest {
@Mock
private EpisodeDao mEpisodeDao;
@Mock
private LoadEpisodeDetailsInteractor.Callback mMockedCallback;
@Mock
private SpicioApplication mApp;
@Mock
private Series mSeries;
@Before
public void setUp() {
FakeDaoModule storageModule = new FakeDaoModule();
storageModule.setEpisodeDao(mEpisodeDao);
InteractorComponent component = DaggerInteractorComponent.builder()
.spicioAppModule(new FakeAppModule(mApp))
.daoModule(storageModule)
.networkRepositoryModule(mock(NetworkRepositoryModule.class))
.threadingModule(new FakeThreadingModule())
.build();
when(mApp.getInteractorComponent()).thenReturn(component);
}
@Test
public void testSuccess() {
Episode episode = mock(Episode.class);
when(mEpisodeDao.getEpisode(0)).thenReturn(episode);
LoadEpisodeDetailsInteractorImpl interactor = new LoadEpisodeDetailsInteractorImpl(
mApp, 0, mMockedCallback
);
interactor.run();
verify(mEpisodeDao).getEpisode(0);
verifyNoMoreInteractions(mEpisodeDao);
verify(mMockedCallback).onLoadEpisodeDetailsFinish(episode);
}
@Test
public void testFail() {
when(mEpisodeDao.getEpisode(0)).thenReturn(null);
LoadEpisodeDetailsInteractorImpl interactor = new LoadEpisodeDetailsInteractorImpl(
mApp, 0, mMockedCallback
);
interactor.run();
verify(mEpisodeDao).getEpisode(0);
verifyNoMoreInteractions(mEpisodeDao);
verify(mMockedCallback).onLoadEpisodeDetailsFail();
}
}
<file_sep>package com.tlongdev.spicio.presentation.ui.view.fragment;
import com.tlongdev.spicio.domain.model.Series;
import com.tlongdev.spicio.presentation.ui.view.BaseView;
import java.util.List;
/**
* @author Long
* @since 2016. 03. 06.
*/
public interface SeriesView extends BaseView {
void showSeries(List<Series> series);
}
<file_sep>package com.tlongdev.spicio.domain.interactor;
import com.tlongdev.spicio.domain.model.Series;
/**
* @author Long
* @since 2016. 03. 04.
*/
public interface TraktSeriesDetailsInteractor extends Interactor {
interface Callback {
void onTraktSeriesDetailsFinish(Series series);
void onTraktSeriesDetailsFail(); // TODO: 2016. 02. 28. needs more descriptive error data
}
}
<file_sep>package com.tlongdev.spicio.presentation.presenter.fragment;
import com.tlongdev.spicio.domain.interactor.LoadSeriesDetailsInteractor;
import com.tlongdev.spicio.domain.interactor.impl.LoadSeriesDetailsInteractorImpl;
import com.tlongdev.spicio.domain.model.Series;
import com.tlongdev.spicio.presentation.presenter.Presenter;
import com.tlongdev.spicio.presentation.ui.view.fragment.SeriesDetailsView;
/**
* @author Long
* @since 2016. 03. 09.
*/
public class SeriesDetailsPresenter implements Presenter<SeriesDetailsView>,LoadSeriesDetailsInteractor.Callback {
private SeriesDetailsView mView;
@Override
public void attachView(SeriesDetailsView view) {
mView = view;
}
@Override
public void detachView() {
mView = null;
}
public void loadSeasonDetails(int seriesId) {
LoadSeriesDetailsInteractor interactor = new LoadSeriesDetailsInteractorImpl(
mView.getSpicioApplication(), seriesId, this
);
interactor.execute();
}
@Override
public void onLoadSeriesDetailsFinish(Series series) {
if (mView != null) {
mView.showDetails(series);
}
}
@Override
public void onLoadSeriesDetailsFail() {
}
}
<file_sep>package com.tlongdev.spicio.domain.interactor;
import com.tlongdev.spicio.domain.model.Series;
import java.util.List;
/**
* @author Long
* @since 2016. 03. 07.
*/
public interface LoadAllSeriesInteractor extends Interactor {
interface Callback {
void onLoadAllSeriesFinish(List<Series> series);
void onLoadAllSeriesFail();
}
}<file_sep>package com.tlongdev.spicio.domain.interactor.impl;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.domain.interactor.AbstractInteractor;
import com.tlongdev.spicio.domain.interactor.TraktSeasonEpisodesInteractor;
import com.tlongdev.spicio.domain.model.Episode;
import com.tlongdev.spicio.domain.repository.TraktRepository;
import com.tlongdev.spicio.util.Logger;
import java.util.List;
import javax.inject.Inject;
/**
* @author Long
* @since 2016. 03. 10.
*/
public class TraktSeasonEpisodesInteractorImpl extends AbstractInteractor implements TraktSeasonEpisodesInteractor {
private static final String LOG_TAG = TraktSeasonEpisodesInteractorImpl.class.getSimpleName();
@Inject TraktRepository mRepository;
@Inject Logger logger;
private int mSeriesId;
private int mSeason;
private Callback mCallback;
public TraktSeasonEpisodesInteractorImpl(SpicioApplication app, int seriesId, int season,
Callback callback) {
super(app.getInteractorComponent());
app.getInteractorComponent().inject(this);
mSeriesId = seriesId;
mSeason = season;
mCallback = callback;
}
@Override
public void run() {
logger.debug(LOG_TAG, "started");
logger.debug(LOG_TAG, "getting list of episodes with images");
List<Episode> episodesImages = mRepository.getEpisodeImages(mSeriesId, mSeason);
if (episodesImages == null) {
logger.debug(LOG_TAG, "TraktRepository.getEpisodeImages returned null");
postError();
return;
}
logger.debug(LOG_TAG, "getting list of episodes with images");
List<Episode> episodes = mRepository.getSeasonEpisodes(mSeriesId, mSeason);
if (episodes == null) {
logger.debug(LOG_TAG, "TraktRepository.getEpisodeImages returned null");
postError();
return;
}
for (int i = 0; i < episodes.size(); i++) {
episodes.get(i).setImages(episodesImages.get(i).getImages());
}
postFinish(episodes);
logger.debug(LOG_TAG, "ended");
}
private void postError() {
if (mCallback == null) {
return;
}
mMainThread.post(new Runnable() {
@Override
public void run() {
mCallback.onTraktSeasonEpisodesFail();
}
});
}
private void postFinish(final List<Episode> episodes) {
if (mCallback == null) {
return;
}
mMainThread.post(new Runnable() {
@Override
public void run() {
mCallback.onTraktSeasonEpisodesFinish(episodes);
}
});
}
}<file_sep>package com.tlongdev.spicio.presentation.ui.view.fragment;
import com.tlongdev.spicio.domain.model.Series;
import com.tlongdev.spicio.presentation.ui.view.BaseView;
/**
* @author Long
* @since 2016. 03. 09.
*/
public interface SeriesDetailsView extends BaseView {
void showDetails(Series series);
}
<file_sep>package com.tlongdev.spicio.domain.interactor;
/**
* @author Long
* @since 2016. 03. 05.
*/
public interface SaveSeriesInteractor extends Interactor {
interface Callback {
void onSaveSeriesFinish();
void onSaveSeriesFail(); // TODO: 2016. 03. 07. better error handing
}
}
<file_sep>package com.tlongdev.spicio.storage;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.NonNull;
import com.tlongdev.spicio.storage.DatabaseContract.EpisodesEntry;
import com.tlongdev.spicio.storage.DatabaseContract.FeedEntry;
import com.tlongdev.spicio.storage.DatabaseContract.FriendsEntry;
import com.tlongdev.spicio.storage.DatabaseContract.SeasonsEntry;
import com.tlongdev.spicio.storage.DatabaseContract.SeriesEntry;
/**
* Outer Layer, Storage.
*
* @author Long
* @since 2016. 02. 26.
*/
public class DatabaseProvider extends ContentProvider {
public static final int SERIES = 100;
public static final int EPISODES = 101;
public static final int FEED = 102;
public static final int FRIENDS = 103;
public static final int SEASONS = 104;
/**
* The URI Matcher used by this content provider
*/
private static final UriMatcher sUriMatcher = buildUriMatcher();
/**
* The database helper.
*/
private DatabaseHelper mOpenHelper;
/**
* Builds an URI matcher to match the given URIs
*
* @return the URI matcher
*/
private static UriMatcher buildUriMatcher() {
// I know what you're thinking. Why create a UriMatcher when you can use regular
// expressions instead? Because you're not crazy, that's why.
// All paths added to the UriMatcher have a corresponding code to return when a match is
// found. The code passed into the constructor represents the code to return for the root
// URI. It's common to use NO_MATCH as the code for this case.
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = DatabaseContract.CONTENT_AUTHORITY;
// For each type of URI you want to add, create a corresponding code.
matcher.addURI(authority, DatabaseContract.PATH_SERIES, SERIES);
matcher.addURI(authority, DatabaseContract.PATH_EPISODES, EPISODES);
matcher.addURI(authority, DatabaseContract.PATH_FEED, FEED);
matcher.addURI(authority, DatabaseContract.PATH_FRIENDS, FRIENDS);
matcher.addURI(authority, DatabaseContract.PATH_SEASONS, SEASONS);
return matcher;
}
public DatabaseProvider() {
}
@Override
public boolean onCreate() {
mOpenHelper = new DatabaseHelper(getContext());
return true;
}
@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Cursor retCursor;
String tableName;
switch (sUriMatcher.match(uri)) {
case SERIES:
tableName = SeriesEntry.TABLE_NAME;
break;
case EPISODES:
tableName = EpisodesEntry.TABLE_NAME;
break;
case FEED:
tableName = FeedEntry.TABLE_NAME;
break;
case FRIENDS:
tableName = FriendsEntry.TABLE_NAME;
break;
case SEASONS:
tableName = SeasonsEntry.TABLE_NAME;
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
retCursor = mOpenHelper.getReadableDatabase().query(
tableName,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
if (retCursor != null)
//noinspection ConstantConditions
retCursor.setNotificationUri(getContext().getContentResolver(), uri);
return retCursor;
}
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Uri returnUri;
long _id;
switch (sUriMatcher.match(uri)) {
case SERIES:
_id = db.insert(SeriesEntry.TABLE_NAME, null, values);
returnUri = SeriesEntry.buildUri(_id);
break;
case EPISODES:
_id = db.insert(EpisodesEntry.TABLE_NAME, null, values);
returnUri = EpisodesEntry.buildUri(_id);
break;
case FEED:
_id = db.insert(FeedEntry.TABLE_NAME, null, values);
returnUri = FeedEntry.buildUri(_id);
break;
case FRIENDS:
_id = db.insert(FriendsEntry.TABLE_NAME, null, values);
returnUri = FriendsEntry.buildUri(_id);
break;
case SEASONS:
_id = db.insert(SeasonsEntry.TABLE_NAME, null, values);
returnUri = SeasonsEntry.buildUri(_id);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
if (_id > 0)
return returnUri;
else
throw new android.database.SQLException("Failed to insert row into " + uri);
}
@Override
public int update(@NonNull Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int rowsUpdated;
switch (sUriMatcher.match(uri)) {
case SERIES:
rowsUpdated = db.update(SeriesEntry.TABLE_NAME, values, selection, selectionArgs);
break;
case EPISODES:
rowsUpdated = db.update(EpisodesEntry.TABLE_NAME, values, selection, selectionArgs);
break;
case FEED:
rowsUpdated = db.update(FeedEntry.TABLE_NAME, values, selection, selectionArgs);
break;
case FRIENDS:
rowsUpdated = db.update(FriendsEntry.TABLE_NAME, values, selection, selectionArgs);
break;
case SEASONS:
rowsUpdated = db.update(SeasonsEntry.TABLE_NAME, values, selection, selectionArgs);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
if (rowsUpdated != 0) {
//noinspection ConstantConditions
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsUpdated;
}
@Override
public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int rowsDeleted;
switch (sUriMatcher.match(uri)) {
case SERIES:
rowsDeleted = db.delete(SeriesEntry.TABLE_NAME, selection, selectionArgs);
break;
case EPISODES:
rowsDeleted = db.delete(EpisodesEntry.TABLE_NAME, selection, selectionArgs);
break;
case FEED:
rowsDeleted = db.delete(FeedEntry.TABLE_NAME, selection, selectionArgs);
break;
case FRIENDS:
rowsDeleted = db.delete(FriendsEntry.TABLE_NAME, selection, selectionArgs);
break;
case SEASONS:
rowsDeleted = db.delete(SeasonsEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
// Because a null deletes all rows
if (selection == null || rowsDeleted != 0) {
//noinspection ConstantConditions
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsDeleted;
}
@Override
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
String tableName;
switch (sUriMatcher.match(uri)) {
case SERIES:
tableName = SeriesEntry.TABLE_NAME;
break;
case EPISODES:
tableName = EpisodesEntry.TABLE_NAME;
break;
case FEED:
tableName = FeedEntry.TABLE_NAME;
break;
case FRIENDS:
tableName = FriendsEntry.TABLE_NAME;
break;
case SEASONS:
tableName = SeasonsEntry.TABLE_NAME;
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
db.beginTransaction();
int returnCount = 0;
try {
for (ContentValues value : values) {
long _id = db.insert(tableName, null, value);
if (_id != -1) {
returnCount++;
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
//noinspection ConstantConditions
getContext().getContentResolver().notifyChange(uri, null);
return returnCount;
}
@Override
public String getType(@NonNull Uri uri) {
switch (sUriMatcher.match(uri)) {
case SERIES:
return "vnd.android.cursor.dir/" + DatabaseContract.CONTENT_AUTHORITY + "/" + DatabaseContract.PATH_SERIES;
case EPISODES:
return "vnd.android.cursor.dir/" + DatabaseContract.CONTENT_AUTHORITY + "/" + DatabaseContract.PATH_EPISODES;
case FEED:
return "vnd.android.cursor.dir/" + DatabaseContract.CONTENT_AUTHORITY + "/" + DatabaseContract.PATH_FEED;
case FRIENDS:
return "vnd.android.cursor.dir/" + DatabaseContract.CONTENT_AUTHORITY + "/" + DatabaseContract.PATH_FRIENDS;
case SEASONS:
return "vnd.android.cursor.dir/" + DatabaseContract.CONTENT_AUTHORITY + "/" + DatabaseContract.PATH_SEASONS;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
<file_sep>package com.tlongdev.spicio.presentation.ui.view;
import android.content.Context;
import com.tlongdev.spicio.SpicioApplication;
/**
* Outer Layer, UI.
* The base view interface of the MVP architecture.
*
* @author Long
* @since 2016. 02. 23.
*/
public interface BaseView {
Context getContext();
SpicioApplication getSpicioApplication();
}
<file_sep>package com.tlongdev.spicio.network.model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* @author Long
* @since 2016. 03. 01.
*/
public class TraktEpisode {
@SerializedName("season")
private int season;
@SerializedName("number")
private int number;
@SerializedName("title")
private String title;
@SerializedName("ids")
private TraktIds ids;
@SerializedName("images")
private TraktImages images;
@SerializedName("number_abs")
private Integer numberAbs;
@SerializedName("overview")
private String overview;
@SerializedName("rating")
private double rating;
@SerializedName("votes")
private int votes;
@SerializedName("first_aired")
private String firstAired;
@SerializedName("updated_at")
private String updatedAt;
@SerializedName("available_translations")
private List<String> availableTranslations;
public int getSeason() {
return season;
}
public int getNumber() {
return number;
}
public String getTitle() {
return title;
}
public TraktIds getIds() {
return ids;
}
public TraktImages getImages() {
return images;
}
public Integer getNumberAbs() {
return numberAbs;
}
public String getOverview() {
return overview;
}
public double getRating() {
return rating;
}
public int getVotes() {
return votes;
}
public String getFirstAired() {
return firstAired;
}
public String getUpdatedAt() {
return updatedAt;
}
public List<String> getAvailableTranslations() {
return availableTranslations;
}
}
<file_sep>package com.tlongdev.spicio.storage;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import com.google.gson.Gson;
import com.tlongdev.spicio.BuildConfig;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.component.DaggerStorageComponent;
import com.tlongdev.spicio.component.StorageComponent;
import com.tlongdev.spicio.domain.model.Episode;
import com.tlongdev.spicio.domain.model.Season;
import com.tlongdev.spicio.domain.model.Watched;
import com.tlongdev.spicio.module.FakeAppModule;
import com.tlongdev.spicio.module.FakeStorageModule;
import com.tlongdev.spicio.network.converter.TraktModelConverter;
import com.tlongdev.spicio.network.model.TraktEpisode;
import com.tlongdev.spicio.storage.DatabaseContract.EpisodesEntry;
import com.tlongdev.spicio.storage.dao.EpisodeDao;
import com.tlongdev.spicio.storage.dao.impl.EpisodeDaoImpl;
import com.tlongdev.spicio.util.TestUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowContentResolver;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Long
* @since 2016. 03. 07.
*/
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class EpisodeDaoTest {
private ContentResolver mContentResolver;
private ShadowContentResolver mShadowContentResolver;
private EpisodeDao mEpisodeDao;
private Episode mEpisode;
private Episode mAnotherEpisode;
@Before
public void setUp() throws Exception {
DatabaseProvider provider = new DatabaseProvider();
mContentResolver = RuntimeEnvironment.application.getContentResolver();
ShadowContentResolver.registerProvider(DatabaseContract.CONTENT_AUTHORITY, provider);
provider.onCreate();
mShadowContentResolver = Shadows.shadowOf(mContentResolver);
deleteAllRecords(EpisodesEntry.CONTENT_URI);
StorageComponent storageComponent = DaggerStorageComponent.builder()
.spicioAppModule(new FakeAppModule(RuntimeEnvironment.application))
.storageModule(new FakeStorageModule())
.build();
((SpicioApplication) RuntimeEnvironment.application).setStorageComponent(storageComponent);
mEpisodeDao = new EpisodeDaoImpl((SpicioApplication) RuntimeEnvironment.application);
InputStream is = getClass().getClassLoader().getResourceAsStream("trakt_episode_detail_mock.json");
String dummyResponse = TestUtils.convertStreamToString(is);
Gson gson = new Gson();
TraktEpisode traktEpisode = gson.fromJson(dummyResponse, TraktEpisode.class);
mEpisode = TraktModelConverter.convertToEpisode(traktEpisode);
is = getClass().getClassLoader().getResourceAsStream("trakt_episode_detail_mock2.json");
dummyResponse = TestUtils.convertStreamToString(is);
traktEpisode = gson.fromJson(dummyResponse, TraktEpisode.class);
mAnotherEpisode = TraktModelConverter.convertToEpisode(traktEpisode);
List<Episode> episodes = new LinkedList<>();
episodes.add(mEpisode);
episodes.add(mAnotherEpisode);
int rowsInserted = mEpisodeDao.insertAllEpisodes(episodes);
assertEquals(2, rowsInserted);
Season season = new Season();
season.setSeriesId(mEpisode.getSeriesId());
season.setNumber(mEpisode.getSeason());
List<Season> seasons = new LinkedList<>();
seasons.add(season);
rowsInserted = mEpisodeDao.insertAllSeasons(seasons);
assertEquals(1, rowsInserted);
}
public void deleteAllRecords(Uri contentUri) {
mContentResolver.delete(contentUri, null, null);
Cursor cursor = mContentResolver.query(
contentUri, null, null, null, null
);
assertNotNull("Error: Query returned null during delete", cursor);
assertEquals("Error: Records not deleted from Repos table during delete", 0, cursor.getCount());
cursor.close();
}
@Test
public void testBasicQuery() {
Episode episode = mEpisodeDao.getEpisode(mEpisode.getTraktId());
assertNotNull(episode);
assertEquals(mEpisode.getSeason(), episode.getSeason());
assertEquals(mEpisode.getNumber(), episode.getNumber());
assertEquals(mEpisode.getTitle(), episode.getTitle());
assertEquals(mEpisode.getTraktId(), episode.getTraktId());
assertEquals(mEpisode.getTvdbId(), episode.getTvdbId());
assertEquals(mEpisode.getImdbId(), episode.getImdbId());
assertEquals(mEpisode.getTmdbId(), episode.getTmdbId());
assertEquals(mEpisode.getTvRageId(), episode.getTvRageId());
assertEquals(mEpisode.getAbsoluteNumber(), episode.getAbsoluteNumber());
assertEquals(mEpisode.getOverview(), episode.getOverview());
assertEquals(mEpisode.getTraktRating(), episode.getTraktRating(), 0);
assertEquals(mEpisode.getTraktRatingCount(), episode.getTraktRatingCount());
assertEquals(mEpisode.getFirstAired().getMillis(), episode.getFirstAired().getMillis());
assertEquals(Watched.NONE, episode.isWatched());
assertFalse(episode.isLiked());
}
@Test
public void testQueryAll() {
List<Episode> episodes = mEpisodeDao.getAllEpisodes();
assertNotNull(episodes);
Episode episode = episodes.get(0);
assertNotNull(episode);
assertEquals(mEpisode.getSeason(), episode.getSeason());
assertEquals(mEpisode.getNumber(), episode.getNumber());
assertEquals(mEpisode.getTitle(), episode.getTitle());
assertEquals(mEpisode.getTraktId(), episode.getTraktId());
assertEquals(mEpisode.getTvdbId(), episode.getTvdbId());
assertEquals(mEpisode.getImdbId(), episode.getImdbId());
assertEquals(mEpisode.getTmdbId(), episode.getTmdbId());
assertEquals(mEpisode.getTvRageId(), episode.getTvRageId());
assertEquals(mEpisode.getAbsoluteNumber(), episode.getAbsoluteNumber());
assertEquals(mEpisode.getOverview(), episode.getOverview());
assertEquals(mEpisode.getTraktRating(), episode.getTraktRating(), 0);
assertEquals(mEpisode.getTraktRatingCount(), episode.getTraktRatingCount());
assertEquals(mEpisode.getFirstAired().getMillis(), episode.getFirstAired().getMillis());
assertEquals(Watched.NONE, episode.isWatched());
assertFalse(episode.isLiked());
episode = episodes.get(1);
assertNotNull(episode);
assertEquals(mAnotherEpisode.getSeason(), episode.getSeason());
assertEquals(mAnotherEpisode.getNumber(), episode.getNumber());
assertEquals(mAnotherEpisode.getTitle(), episode.getTitle());
assertEquals(mAnotherEpisode.getTraktId(), episode.getTraktId());
assertEquals(mAnotherEpisode.getTvdbId(), episode.getTvdbId());
assertEquals(mAnotherEpisode.getImdbId(), episode.getImdbId());
assertEquals(mAnotherEpisode.getTmdbId(), episode.getTmdbId());
assertEquals(mAnotherEpisode.getTvRageId(), episode.getTvRageId());
assertEquals(mAnotherEpisode.getAbsoluteNumber(), episode.getAbsoluteNumber());
assertEquals(mAnotherEpisode.getOverview(), episode.getOverview());
assertEquals(mAnotherEpisode.getTraktRating(), episode.getTraktRating(), 0);
assertEquals(mAnotherEpisode.getTraktRatingCount(), episode.getTraktRatingCount());
assertEquals(mAnotherEpisode.getFirstAired().getMillis(), episode.getFirstAired().getMillis());
assertEquals(Watched.NONE, episode.isWatched());
assertFalse(episode.isLiked());
}
@Test
public void testWatched() {
int rowsUpdated = mEpisodeDao.setWatched(mEpisode.getTraktId(), Watched.WATCHED);
assertEquals(rowsUpdated, 1);
assertTrue(mEpisodeDao.isWatched(mEpisode.getTraktId()));
Episode episode = mEpisodeDao.getEpisode(mEpisode.getTraktId());
assertEquals(Watched.WATCHED, episode.isWatched());
}
@Test
public void testLiked() {
int rowsUpdated = mEpisodeDao.setLiked(mEpisode.getTraktId(), true);
assertEquals(rowsUpdated, 1);
Episode episode = mEpisodeDao.getEpisode(mEpisode.getTraktId());
assertTrue(episode.isLiked());
}
@Test
public void testSkipped() {
int rowsUpdated = mEpisodeDao.setWatched(mEpisode.getTraktId(), Watched.SKIPPED);
assertEquals(rowsUpdated, 1);
Episode episode = mEpisodeDao.getEpisode(mEpisode.getTraktId());
assertEquals(Watched.SKIPPED, episode.isWatched());
}
@Test
public void testGetSeasons() {
List<Season> seasons = mEpisodeDao.getAllSeasons(mEpisode.getSeriesId());
assertNotNull(seasons);
assertEquals(1, seasons.size());
Season season = seasons.get(0);
assertNotNull(season);
assertEquals(mEpisode.getSeriesId(), season.getSeriesId());
assertEquals(mEpisode.getSeason(), season.getNumber());
assertEquals(0, season.getWatchCount());
assertEquals(0, season.getSkipCount());
}
@Test
public void testGetSeasonsWithWatched() {
testWatched();
List<Season> seasons = mEpisodeDao.getAllSeasons(mEpisode.getSeriesId());
assertNotNull(seasons);
assertEquals(1, seasons.size());
Season season = seasons.get(0);
assertNotNull(season);
assertEquals(mEpisode.getSeriesId(), season.getSeriesId());
assertEquals(mEpisode.getSeason(), season.getNumber());
assertEquals(1, season.getWatchCount());
assertEquals(0, season.getSkipCount());
}
@Test
public void testGetSeasonsWithSkipped() {
testSkipped();
List<Season> seasons = mEpisodeDao.getAllSeasons(mEpisode.getSeriesId());
assertNotNull(seasons);
assertEquals(1, seasons.size());
Season season = seasons.get(0);
assertNotNull(season);
assertEquals(mEpisode.getSeriesId(), season.getSeriesId());
assertEquals(mEpisode.getSeason(), season.getNumber());
assertEquals(0, season.getWatchCount());
assertEquals(1, season.getSkipCount());
}
@Test
public void testRetainCheck() {
testWatched();
List<Episode> episodes = new LinkedList<>();
episodes.add(mEpisode);
episodes.add(mAnotherEpisode);
int rowsInserted = mEpisodeDao.insertAllEpisodes(episodes);
assertEquals(2, rowsInserted);
Episode episode = mEpisodeDao.getEpisode(mEpisode.getTraktId());
assertNotNull(episode);
assertEquals(Watched.WATCHED, episode.isWatched());
}
}
<file_sep>package com.tlongdev.spicio.domain.interactor.impl;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.domain.interactor.AbstractInteractor;
import com.tlongdev.spicio.domain.interactor.LoadEpisodeDetailsInteractor;
import com.tlongdev.spicio.domain.model.Episode;
import com.tlongdev.spicio.storage.dao.EpisodeDao;
import com.tlongdev.spicio.util.Logger;
import javax.inject.Inject;
/**
* @author Long
* @since 2016. 03. 11.
*/
public class LoadEpisodeDetailsInteractorImpl extends AbstractInteractor implements LoadEpisodeDetailsInteractor {
private static final String LOG_TAG = LoadEpisodeDetailsInteractorImpl.class.getSimpleName();
@Inject EpisodeDao mEpisodeDao;
@Inject Logger logger;
private int mEpisodeId;
private Callback mCallback;
public LoadEpisodeDetailsInteractorImpl(SpicioApplication application, int episodeId,
Callback callback) {
super(application.getInteractorComponent());
application.getInteractorComponent().inject(this);
mEpisodeId = episodeId;
mCallback = callback;
}
@Override
public void run() {
logger.debug(LOG_TAG, "started");
Episode episode = mEpisodeDao.getEpisode(mEpisodeId);
if (episode == null) {
logger.debug(LOG_TAG, "EpisodeDao.getEpisode returned null");
postError();
return;
}
postFinish(episode);
logger.debug(LOG_TAG, "ended");
}
private void postError() {
if (mCallback == null) {
return;
}
mMainThread.post(new Runnable() {
@Override
public void run() {
mCallback.onLoadEpisodeDetailsFail();
}
});
}
private void postFinish(final Episode episode) {
if (mCallback == null) {
return;
}
mMainThread.post(new Runnable() {
@Override
public void run() {
mCallback.onLoadEpisodeDetailsFinish(episode);
}
});
}
}<file_sep>package com.tlongdev.spicio.domain.interactor.impl;
import com.tlongdev.spicio.SpicioApplication;
import com.tlongdev.spicio.domain.interactor.AbstractInteractor;
import com.tlongdev.spicio.domain.interactor.LoadSeasonsInteractor;
import com.tlongdev.spicio.domain.model.Season;
import com.tlongdev.spicio.storage.dao.EpisodeDao;
import com.tlongdev.spicio.util.Logger;
import java.util.List;
import javax.inject.Inject;
/**
* @author Long
* @since 2016. 03. 09.
*/
public class LoadSeasonsInteractorImpl extends AbstractInteractor implements LoadSeasonsInteractor {
private static final String LOG_TAG = LoadSeasonsInteractorImpl.class.getSimpleName();
@Inject EpisodeDao mEpisodeDao;
@Inject Logger logger;
private int mSeriesId;
private Callback mCallback;
public LoadSeasonsInteractorImpl(SpicioApplication app, int seriesId, Callback callback) {
super(app.getInteractorComponent());
app.getInteractorComponent().inject(this);
mSeriesId = seriesId;
mCallback = callback;
}
@Override
public void run() {
logger.debug(LOG_TAG, "started");
logger.debug(LOG_TAG, "querying seasons for " + mSeriesId);
List<Season> seasons = mEpisodeDao.getAllSeasons(mSeriesId);
if (seasons == null) {
postError();
return;
} else {
postFinish(seasons);
}
logger.debug(LOG_TAG, "ended");
}
private void postError() {
if (mCallback == null) {
return;
}
mMainThread.post(new Runnable() {
@Override
public void run() {
mCallback.onLoadSeasonsFail();
}
});
}
private void postFinish(final List<Season> seasons) {
if (mCallback == null) {
return;
}
mMainThread.post(new Runnable() {
@Override
public void run() {
mCallback.onLoadSeasonsFinish(seasons);
}
});
}
}
<file_sep>package com.tlongdev.spicio.domain.model;
import org.joda.time.DateTime;
/**
* @author Long
* @since 2016. 03. 03.
*/
public class Episode {
private int season;
private int number;
private String title;
private int traktId;
private String slugName;
private int tvdbId;
private String imdbId;
private int tmdbId;
private int tvRageId;
private Images images;
private int absoluteNumber;
private String overview;
private double traktRating;
private int traktRatingCount;
private DateTime firstAired;
private int watched;
private boolean liked;
public int seriesId;
public int getSeason() {
return season;
}
public void setSeason(int season) {
this.season = season;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getTraktId() {
return traktId;
}
public void setTraktId(int traktId) {
this.traktId = traktId;
}
public String getSlugName() {
return slugName;
}
public void setSlugName(String slugName) {
this.slugName = slugName;
}
public int getTvdbId() {
return tvdbId;
}
public void setTvdbId(int tvdbId) {
this.tvdbId = tvdbId;
}
public String getImdbId() {
return imdbId;
}
public void setImdbId(String imdbId) {
this.imdbId = imdbId;
}
public int getTmdbId() {
return tmdbId;
}
public void setTmdbId(int tmdbId) {
this.tmdbId = tmdbId;
}
public int getTvRageId() {
return tvRageId;
}
public void setTvRageId(int tvRageId) {
this.tvRageId = tvRageId;
}
public Images getImages() {
return images;
}
public void setImages(Images images) {
this.images = images;
}
public int getAbsoluteNumber() {
return absoluteNumber;
}
public void setAbsoluteNumber(int absoluteNumber) {
this.absoluteNumber = absoluteNumber;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public double getTraktRating() {
return traktRating;
}
public void setTraktRating(double traktRating) {
this.traktRating = traktRating;
}
public int getTraktRatingCount() {
return traktRatingCount;
}
public void setTraktRatingCount(int traktRatingCount) {
this.traktRatingCount = traktRatingCount;
}
public DateTime getFirstAired() {
return firstAired;
}
public void setFirstAired(DateTime firstAired) {
this.firstAired = firstAired;
}
@Watched.Enum
public int isWatched() {
return watched;
}
public void setWatched(@Watched.Enum int watched) {
this.watched = watched;
}
public boolean isLiked() {
return liked;
}
public void setLiked(boolean liked) {
this.liked = liked;
}
public int getSeriesId() {
return seriesId;
}
public void setSeriesId(int seriesId) {
this.seriesId = seriesId;
}
}
| f88d7f9497851f013073181493f335f3ee7619a7 | [
"Markdown",
"Java",
"Gradle"
] | 62 | Java | lastbulletbender/spicio | f7d596e64e4101d31bb47d273e4c4c7f6a55b674 | 9581ddd2b13e08cafccd90698cae373be01a3231 | |
refs/heads/master | <file_sep>import React from 'react';
import {Link, Route} from 'react-router-dom';
import Main from './Main';
export default function NotFound() {
return (
<div>Oops! That page doesn't exist. Try <Link to='/'>starting here</Link> :) <Route path='/albums' component={Main} /> </div>
)
}
<file_sep>import React, {Component} from 'react';
import {AllAlbums} from './AllAlbums';
import axios from 'axios';
export default class StatefulAlbums extends Component {
constructor() {
super();
this.state = {
albums: []
}
}
componentDidMount () {
axios.get('/api/albums/')
.then(res => res.data)
.then(albums => {
this.setState({ albums })
})
.catch(error => this.props.history.push("/NotFound"));
}
render() {
return <AllAlbums albums={this.state.albums} />
}
}
| dae2ae51e8ac59c8eb73fe04e5a030065d60cea0 | [
"JavaScript"
] | 2 | JavaScript | ZacharyDudley/juke-react-router | d1e8692953f39f24c609c7ce3b49298b6660ada9 | db47bb3df5a23753d1367dcf9fd7657655a80035 | |
refs/heads/main | <repo_name>AdamK2003/bad-keyboard<file_sep>/bad_keyboard/328/328.ino
#include <Arduino.h>
#include <RotaryEncoder.h>
#include "font.h"
// Shift register pins
int srDataPin = 4; // SER
int srLatchPin = 5; // SRCLK
int srClockPin = 6; // RCLK
// Rotary encoder pins
int rePin1 = 2;
int rePin2 = 3;
// Button pin, attach button from +5v to this pin, attach this pin to GND through 10K resistor
int buttonPin = A5;
// Dotmatrix rows, first pin is top row
int rows[8] = {7,8,9,10,11,12,A0,A1};
// Backspace, return and space characters
char bksp[8] = { 0x00, 0x00, 0x04, 0x02, 0xFF, 0x00, 0x00, 0x00 };
char rtrn[8] ={ 0x00, 0x00, 0x40, 0x48, 0x7C, 0x08, 0x00, 0x00 };
char space[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x81, 0xFF };
int prevButtonState = LOW;
int buttonState = LOW;
RotaryEncoder encoder(rePin1, rePin2, RotaryEncoder::LatchMode::FOUR3);
int charNum = 64;
void setup()
{
pinMode(srLatchPin, OUTPUT);
pinMode(srDataPin, OUTPUT);
pinMode(srClockPin, OUTPUT);
pinMode(buttonPin, INPUT);
for(int i = 0; i < 8; i++) {
pinMode(rows[i], OUTPUT);
}
for(int i = 0; i < 8; i++) {
digitalWrite(rows[i], HIGH);
}
Serial.begin(38400);
}
void loop()
{
encoder.tick();
charNum = encoder.getPosition() >= 0 ? ((encoder.getPosition() + 35) % 97 + 30) : (((unsigned(encoder.getPosition()) - 60) % 97 + 34) % 97 + 30);
if(charNum <= 32) {
writeBitmap(charNum == 30 ? bksp : charNum == 31 ? rtrn : space);
} else {
writeBitmapFont(font, charNum);
}
buttonState = digitalRead(buttonPin);
if (buttonState != prevButtonState) {
prevButtonState = buttonState;
if(buttonState == HIGH) {
Serial.write(charNum);
}
}
}
void writeBitmap(char bitmap[8]) {
for(int i = 0; i < 8; i++) {
digitalWrite(srLatchPin, LOW);
shiftOut(srDataPin, srClockPin, MSBFIRST, bitmap[i]);
digitalWrite(rows[i > 0 ? i-1 : 7], HIGH);
digitalWrite(srLatchPin, HIGH);
digitalWrite(rows[i], LOW);
}
}
void writeBitmapFont(char fontArray[][8], int fontIndex) {
for(int i = 0; i < 8; i++) {
digitalWrite(srLatchPin, LOW);
shiftOut(srDataPin, srClockPin, MSBFIRST, fontArray[fontIndex][i]);
digitalWrite(rows[i > 0 ? i-1 : 7], HIGH);
digitalWrite(srLatchPin, HIGH);
digitalWrite(rows[i], LOW);
}
}
<file_sep>/README.md
# bad-keyboard
Arduino keyboard thingy inspired by [this Twitter thread](https://twitter.com/Foone/status/1207892434706825216). Requires HoodLoader2. Flash the `328` sketch to the ATmega328 and the `16u2` sketch to the ATmega16u2.
## Hardware requirements
- Arduino with HoodLoader2
- rotary encoder
- 8x8 dotmatrix display
- 8 bit shift register
- pushbutton
## Required libraries
- [HID-Project](https://github.com/NicoHood/HID)
- [RotaryEncoder](https://github.com/mathertel/RotaryEncoder)
## Circuit
- shift register pins:
- data pin (SER) connected to Arduino pin 4
- latch pin (SRCLK) connected to Arduino pin 5
- clock pin (RCLK) connected to Arduino pin 6
- output pins connected to dotmatrix column pins (lowest pin to leftmost column)
- rotary encoder pins connected to Arduino pin 2 and 3
- button connected between 5V and Arduino analog pin 5, connect 10K resistor between pin A5 and GND
- pins 7 through 12 and A0, A1 connected to dotmatrix row pins (pin 7 to highest row, pin A1 to lowest row)
<file_sep>/bad_keyboard/16u2/16u2.ino
#include <HID-Project.h>
#include <HID-Settings.h>
void setup() {
Serial1.begin(38400);
Keyboard.begin();
}
void loop() {
if(Serial1.available()) {
int read = Serial1.read();
if(read == 30) {
Keyboard.write(KEY_BACKSPACE);
} else if (read == 31) {
Keyboard.write(KEY_RETURN);
} else {
Keyboard.write(read);
}
}
}
| 9f84ce82c7fac98d37c70ed1245311c54548c968 | [
"Markdown",
"C++"
] | 3 | C++ | AdamK2003/bad-keyboard | c8069035fd58cde1b84a425915829337af77b78b | 06798520d9f97af3eace2ddfeccc40d09726080b | |
refs/heads/master | <repo_name>lexdu53/laFactory<file_sep>/src/main/resources/templates/admin/admin-dashboard.php
<?php
session_start();
include("../config.php");
include("../class/user.class.php");
include("../class/admin.class.php");
// structure de la page :
// On inclue le header :
// Titre De la page :
$titre_page_act = "Admin Dashboard";
include("../includes/header.inc.php");
// On envoit le menu de la page :
include("../includes/nav.inc.php");
$user = new User();
if ($user->already_connect() == 1 AND $_SESSION['user_type'] == 1)
{
$admin = new admin();
if(isset($_POST['form_reinit_site'])) // Si le formulaire de reinitalisation a été envoyé :
{
$retour_reinit_site = $admin->reinit_site();
}
if(isset($_FILES['bdd_csv'])) // si un fichier à été envoyé
{
$retour_insert_csv = $admin->import_file();
}
$nbFormation= $admin->getNbFormation();
$nbMention = $admin->getNbMention();
$nbDomaine = $admin->getNbDomaine();
$nbUsers = $admin->getNbUsers();
// Body :
?>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Dashboard</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-3 col-md-6">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="row">
<div class="col-xs-3">
<i class="fa fa-road fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge"><?php echo $nbFormation; ?></div>
<div>Formation(s)</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="panel panel-green">
<div class="panel-heading">
<div class="row">
<div class="col-xs-3">
<i class="fa fa-list-alt fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge"><?php echo $nbMention; ?></div>
<div>Mention(s)</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="panel panel-yellow">
<div class="panel-heading">
<div class="row">
<div class="col-xs-3">
<i class="fa fa-asterisk fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge"><?php echo $nbDomaine; ?></div>
<div>Domaine(s)</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="panel panel-red">
<div class="panel-heading">
<div class="row">
<div class="col-xs-3">
<i class="fa fa-male fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge"><?php echo $nbUsers; ?></div>
<div>Utilisateur(s)</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-8">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-arrow-right fa-2x"></i> <i class="fa fa-database fa-2x"></i> Import CSV dans la base
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div id="morris-area-chart"></div>
<form role="form" id="form_import_data" method="post" action="admin-dashboard.php" enctype="multipart/form-data">
<div class="well">
<h4>Fichier CSV sous la forme:</h4>
Annee;Niveau; Domaine;Mention; Groupe_accreditation;Parcours; Parcours_Etab;Parcours_Part; Partenariats_UBL;Partenariats_Autres
<br><b style="color:red;"><i class="fa fa-warning fa-1x"></i> Attention: l'importation d'un fichier CSV implique la surppression des anciennes données de la base</b>
</div>
<div class="form-group">
<label>Fichier (CSV | max. 2 Mo | Encodage UTF-8) :</label>
<input type="hidden" name="MAX_FILE_SIZE" value="2097152" />
<input type="file" name="bdd_csv" id="bdd_csv" />
</div>
<div class="form-group">
<label>Vérification des doublons</label>
<div class="checkbox">
<label>
<input type="checkbox" name="verifdoublons" id="verifdoublons" value="">Trouver et supprimer automatiquement les doublons
</label>
</div>
</div>
<button type="submit" name="submit" value="Importer" class="btn btn-success">Importer</button>
<button type="reset" class="btn btn-info">Reset</button>
</form>
<?php
if(isset($_FILES['bdd_csv'])) // si un fichier à été envoyé
{
echo $retour_insert_csv;
}
?>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-8 -->
<div class="col-lg-4">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-times fa-2x"></i> <i class="fa fa-database fa-2x"></i> Effacer la base
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<form role="form" id="form_reinit_site" method="post" action="admin-dashboard.php">
<div class="well">
<h4>Effacer la base de données:</h4>
<br><b style="color:red;"><i class="fa fa-warning fa-1x"></i> Attention: La réinitialisation est irréversible pour la base de données.</b>
</div>
<div class="form-group">
<label>Souhaitez vous réinitialiser le site ? </label>
<div class="checkbox">
<label>
<input type="checkbox" name="reinit_site" id="reinit_site" value="">OUI
</label>
</div>
</div>
<button type="submit" name="form_reinit_site" value="Réinitialiser" class="btn btn-danger">Réinitialiser</button>
<button type="reset" class="btn btn-info">Reset</button>
</form>
<?php
if(isset($_POST['form_reinit_site'])) // Si le formulaire de reinitalisation a été envoyé :
{
echo $retour_reinit_site;
}
?>
</div>
<!-- /.panel-body -->
</div>
</div>
<!-- /.col-lg-4 -->
</div>
<!-- /.row -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
<?php
// Fin Body
}
else {
echo'<script language="javascript">window.location.href = "../pages/index.php"</script>';
}
// On envoit le footer :
include("../includes/footer.inc.php");
?><file_sep>/src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/LaFactory
spring.datasource.username=adminjava
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.thymeleaf.cache=false
<file_sep>/src/main/java/org/lafactory/Service/IetapeCreationService.java
package org.lafactory.Service;
import java.util.Collection;
import org.lafactory.entities.etapeCreation;
public interface IetapeCreationService {
public etapeCreation getetapeCreation(int id);
public void setetapeCreation(etapeCreation etapeCreation);
public int deletapeCreation(int id);
public Collection<etapeCreation> getAlletapeCreation(int id);
public void setetapesCreation(Collection<etapeCreation> etapesCreation);
public int delAlletapeCreation(int idOrigami);
}
<file_sep>/src/main/java/org/lafactory/entities/Origami.java
package org.lafactory.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="origami")
public class Origami {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID")
private int id;
@Column(name="NOM")
private String nom;
@ManyToOne
@JoinColumn(name="DIFFICULTE")
private difOrigami difficulte;
@ManyToOne
@JoinColumn(name="TYPEORIGAMI")
private typeOrigami type;
@Column(name="TEMPSREAL")
private int tempsReal;
@Column(name="NBFEUILLE")
private int nbFeuille;
@Column(name="NOTE")
private int note;
@Column(name="ACTIVE")
private int active;
@Column(name="TUTOYT")
private String tutoYT;
public Origami() {
super();
// TODO Auto-generated constructor stub
}
public Origami(String nom, difOrigami difficulte, typeOrigami type, int tempsReal, int nbFeuille, int note,
int active, String tutoYT) {
super();
this.nom = nom;
this.difficulte = difficulte;
this.type = type;
this.tempsReal = tempsReal;
this.nbFeuille = nbFeuille;
this.note = note;
this.active = active;
this.tutoYT = tutoYT;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public difOrigami getDifficulte() {
return difficulte;
}
public void setDifficulte(difOrigami difficulte) {
this.difficulte = difficulte;
}
public typeOrigami getType() {
return type;
}
public void setType(typeOrigami type) {
this.type = type;
}
public int getTempsReal() {
return tempsReal;
}
public void setTempsReal(int tempsReal) {
this.tempsReal = tempsReal;
}
public int getNbFeuille() {
return nbFeuille;
}
public void setNbFeuille(int nbFeuille) {
this.nbFeuille = nbFeuille;
}
public int getNote() {
return note;
}
public void setNote(int note) {
this.note = note;
}
public int getActive() {
return active;
}
public void setActive(int active) {
this.active = active;
}
public String getTutoYT() {
return tutoYT;
}
public void setTutoYT(String tutoYT) {
this.tutoYT = tutoYT;
}
}
<file_sep>/src/main/java/org/lafactory/dao/UsersRepository.java
package org.lafactory.dao;
import org.lafactory.entities.Users;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UsersRepository
extends JpaRepository<Users, Integer>{
}
<file_sep>/src/main/java/org/lafactory/Service/IdifOrigami.java
package org.lafactory.Service;
import org.lafactory.entities.difOrigami;
public interface IdifOrigami {
public difOrigami getdifOrigami(int id);
public void setdifOrigami(difOrigami origami);
public int deldifOrigami(int id);
}
<file_sep>/src/main/java/org/lafactory/dao/typeOrigamiRepository.java
package org.lafactory.dao;
import org.lafactory.entities.typeOrigami;
import org.springframework.data.jpa.repository.JpaRepository;
public interface typeOrigamiRepository
extends JpaRepository<typeOrigami, Integer>{
}
<file_sep>/src/main/resources/templates/table2.php
<?php
session_start();
include("../config.php");
include("../class/user.class.php");
include("../class/general.class.php");
include("../class/formation.class.php");
//On inclue la classe de base pour géré le site:
//include("$url_site/class/index.class.php");
// structure de la page :
// On inclue le header :
// Titre De la page :
$titre_page_act = "Formations";
include("../includes/header.inc.php");
// On envoit le menu de la page :
include("../includes/nav.inc.php");
// Body :
?>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Formations</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
DataTables Advanced Tables
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Année</th>
<th>Niveau</th>
<th>Domaine</th>
<th>Mention</th>
<!-- <th>Groupe d'accréditation</th> -->
<th>Parcours</th>
<th>Etablissement</th>
<!--<th>Parcours Part</th>-->
<th>Partenariats UBL</th>
<th>Partenariats Autres</th>
</tr>
</thead>
<tbody>
<?php
$general = new general();
$datatable = $general->getAllFormations();
//print_r ($datatable);
echo $general->getTable($datatable);
?>
</tbody>
</table>
<!-- /.table-responsive -->
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
<?php
// Fin Body
// On envoit le footer :
include("../includes/footer.inc.php");
?><file_sep>/src/main/resources/templates/logout.php
<?php
session_start();
include("../config.php");
include("../class/user.class.php");
//On inclue la classe de base pour géré le site:
//include("$url_site/class/index.class.php");
// structure de la page :
// On inclue le header :
// Titre De la page :
$titre_page_act = "Index :D";
include("../includes/header.inc.php");
$login = new User();
if ($login->already_connect() == 1 )
{
$login->logout();
echo'<script language="javascript">window.location.href = "../pages/index.php"</script>';
}
else
{
echo'<script language="javascript">window.location.href = "../pages/index.php"</script>';
}
// Fin Body
// On envoit le footer :
include("../includes/footer.inc.php");
?><file_sep>/src/main/java/org/lafactory/LaFactoryApplication.java
package org.lafactory;
import org.lafactory.dao.UsersRepository;
import org.lafactory.entities.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class LaFactoryApplication implements CommandLineRunner{
@Autowired
private UsersRepository usersRepository;
public static void main(String[] args) {
SpringApplication.run(LaFactoryApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
usersRepository.save(new Users("RIDE", "Arnaud", "admin", "admin"));
}
}
<file_sep>/src/main/java/org/lafactory/entities/difOrigami.java
package org.lafactory.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="difOrigami")
public class difOrigami {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID")
private int id;
@Column(name="NOM")
private String nom;
public difOrigami(int id, String nom) {
super();
this.id = id;
this.nom = nom;
}
public difOrigami() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
}
| 43dfddd5da9a100bca6360e2a074bfb5c194bc6f | [
"Java",
"PHP",
"INI"
] | 11 | PHP | lexdu53/laFactory | a8ed108c1aae93066a230ceeedf079aa421b648b | a6a9ab49dbc27f19029aef5e1c9006b8ff86770e | |
refs/heads/master | <file_sep>const chai = require('chai');
const assert = chai.assert;
const Translator = require('../components/translator.js');
let translator;
suite('Unit Tests', () => {
translator = new Translator();
test("Mangoes are my favorite fruit.", function(done){
let output = translator.translate("Mangoes are my favorite fruit.", "american-to-british")
assert.equal(output, "Mangoes are my <span class=\"highlight\">favourite</span> fruit.")
done();
})
test("I ate yogurt for breakfast.", function(done){
let output = translator.translate("I ate yogurt for breakfast.", "american-to-british")
assert.equal(output, "I ate <span class=\"highlight\">yoghurt</span> for breakfast.")
done();
})
test("We had a party at my friend's condo.", function(done){
let output = translator.translate("We had a party at my friend's condo.", "american-to-british")
assert.equal(output, 'We had a party at my friend\'s <span class="highlight">flat</span>.')
done();
})
test("Can you toss this in the trashcan for me?", function(done){
let output = translator.translate("Can you toss this in the trashcan for me?", "american-to-british")
assert.equal(output, 'Can you toss this in the <span class="highlight">bin</span> for me?')
done();
})
test("The parking lot was full.", function(done){
let output = translator.translate("The parking lot was full.", "american-to-british")
assert.equal(output, 'The parking lot was full.')
done();
})
test("Like a high tech Rube Goldberg machine.", function(done){
let output = translator.translate("Like a high tech Rube Goldberg machine.", "american-to-british")
assert.equal(output, 'Like a high tech Rube Goldberg machine.')
done();
})
test("To play hooky means to skip class or work.", function(done){
let output = translator.translate("To play hooky means to skip class or work.", "american-to-british")
assert.equal(output, 'To play hooky means to skip class or work.')
done();
})
test("No Mr. Bond, I expect you to die.", function(done){
let output = translator.translate("No Mr. Bond, I expect you to die.", "american-to-british")
assert.equal(output, 'No <span class="highlight">Mr</span> Bond, I expect you to die.')
done();
})
test("Dr. Grosh will see you now.", function(done){
let output = translator.translate("Dr. Grosh will see you now.", "american-to-british")
assert.equal(output, '<span class="highlight">Dr</span> Grosh will see you now.')
done();
})
test("Lunch is at 12:15 today.", function(done){
let output = translator.translate("Lunch is at 12:15 today.", "american-to-british")
assert.equal(output, 'Lunch is at <span class="highlight">12.15</span> today.')
done();
})
test("We watched the footie match for a while.", function(done){
let output = translator.translate("We watched the footie match for a while.", "british-to-american")
assert.equal(output, 'We watched the <span class="highlight">soccer</span> match for a while.')
done();
})
test("Paracetamol takes up to an hour to work.", function(done){
let output = translator.translate("Paracetamol takes up to an hour to work.", "british-to-american")
assert.equal(output, 'Paracetamol takes up to an hour to work.')
done();
})
test("First, caramelise the onions.", function(done){
let output = translator.translate("First, caramelise the onions.", "british-to-american")
assert.equal(output, 'First, <span class="highlight">caramelize</span> the onions.')
done();
})
test("I spent the bank holiday at the funfair.", function(done){
let output = translator.translate("I spent the bank holiday at the funfair.", "british-to-american")
assert.equal(output, 'I spent the bank holiday at the <span class="highlight">carnival</span>.')
done();
})
test("I had a bicky then went to the chippy.", function(done){
let output = translator.translate("I had a bicky then went to the chippy.", "british-to-american")
assert.equal(output, 'I had a <span class="highlight">cookie</span> then went to the <span class="highlight">fish-and-chip shop</span>.')
done();
})
test("I've just got bits and bobs in my bum bag.", function(done){
let output = translator.translate("I've just got bits and bobs in my bum bag.", "british-to-american")
assert.equal(output, 'I\'ve just got bits and bobs in my bum bag.')
done();
})
test("The car boot sale at Boxted Airfield was called off.", function(done){
let output = translator.translate("The car boot sale at Boxted Airfield was called off.", "british-to-american")
assert.equal(output, 'The car boot sale at Boxted Airfield was called off.')
done();
})
test("Have you met <NAME>?", function(done){
let output = translator.translate("Have you met <NAME>?", "british-to-american")
assert.equal(output, 'Have you met <span class="highlight">Mrs.</span> Kalyani?')
done();
})
test("Prof Joyner of King's College, London.", function(done){
let output = translator.translate("Prof Joyner of King's College, London.", "british-to-american")
assert.equal(output, '<span class="highlight">Prof.</span> Joyner of King\'s College, London.')
done();
})
test("Tea time is usually around 4 or 4.30.", function(done){
let output = translator.translate("Tea time is usually around 4 or 4.30.", "british-to-american")
assert.equal(output, 'Tea time is usually around 4 or <span class="highlight">4:30</span>.')
done();
})
test("Mangoes are my favorite fruit.", function(done){
let output = translator.translate("Mangoes are my favorite fruit.", "american-to-british")
assert.equal(output, "Mangoes are my <span class=\"highlight\">favourite</span> fruit.")
done();
})
test("I ate yogurt for breakfast.", function(done){
let output = translator.translate("I ate yogurt for breakfast.", "american-to-british")
assert.equal(output, "I ate <span class=\"highlight\">yoghurt</span> for breakfast.")
done();
})
test("We watched the footie match for a while.", function(done){
let output = translator.translate("We watched the footie match for a while.", "british-to-american")
assert.equal(output, 'We watched the <span class="highlight">soccer</span> match for a while.')
done();
})
test("Paracetamol takes up to an hour to work.", function(done){
let output = translator.translate("Paracetamol takes up to an hour to work.", "british-to-american")
assert.equal(output, 'Paracetamol takes up to an hour to work.')
done();
})
});
<file_sep>const americanOnly = require('./american-only.js');
const americanToBritishSpelling = require('./american-to-british-spelling.js');
const americanToBritishTitles = require("./american-to-british-titles.js")
const britishOnly = require('./british-only.js')
class Translator {
translate(text, voice){
//console.log("TEXT: " + text)
let end = text.substring(text.length -1, text.length)
//console.log(end)
let noend = text.substring(0, text.length-1)
let spl = noend.split(" ");
let newlis = []
if(voice == "american-to-british"){
for(var i = 0; i < spl.length; i++){
if(spl[i] in americanOnly){
newlis.push("<span class=\"highlight\">" + americanOnly[spl[i]] + "</span>")
}else if(spl[i] in americanToBritishSpelling){
newlis.push("<span class=\"highlight\">" + americanToBritishSpelling[spl[i]] + "</span>")
}else if(spl[i] in americanToBritishTitles){
newlis.push("<span class=\"highlight\">" + americanToBritishTitles[spl[i]] + "</span>")
} else if(/^(10|11|12|[1-9]):[0-5][0-9]$/.test(spl[i])){
let [h,m] = spl[i].split(":")
newlis.push("<span class=\"highlight\">" + h + "." + m + "</span>")
}else{
newlis.push(spl[i])
}
}
let s = newlis.join(" ");
//console.log("Return: " + s)
return s + end;
}else{
for(var i = 0; i < spl.length; i++){
if(spl[i] in britishOnly){
newlis.push("<span class=\"highlight\">" + britishOnly[spl[i]] + "</span>")
}else if(Object.values(americanToBritishSpelling).indexOf(spl[i]) > -1){
newlis.push("<span class=\"highlight\">" + Object.keys(americanToBritishSpelling).find(key => americanToBritishSpelling[key] === spl[i]) + "</span>")
}else if(Object.values(americanToBritishTitles).indexOf(spl[i]) > -1){
newlis.push("<span class=\"highlight\">" + Object.keys(americanToBritishTitles).find(key => americanToBritishTitles[key] === spl[i]) + "</span>")
}else if(/^(10|11|12|[1-9]).[0-5][0-9]$/.test(spl[i])){
let [h,m] = spl[i].split(".")
newlis.push("<span class=\"highlight\">" + h + ":" + m + "</span>")
}else{
newlis.push(spl[i])
}
}
let s = newlis.join(" ");
//console.log("Return: " + s)
return s + end;
}
}
}
module.exports = Translator; | ecddba466d5cbceb6f838756543c7a4ed823dcef | [
"JavaScript"
] | 2 | JavaScript | Legendarytruth/boilerplate-project-american-british-english-translator | 8b56b4b0d43ed74e676b50e657b909ebc7ccbd7e | 1a59a93d94c462e18c6f38900b1e8f674e503a52 | |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp1.Entities;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
List<erettsegik> Matek = new List<erettsegik>();
List<string> megyek = new List<string>();
List<string> iskolatipus = new List<string>();
List<string> nem = new List<string>();
List<string> kepzestipus = new List<string>();
List<string> csere = new List<string>();
int valasztott = 0;
public Form1()
{
InitializeComponent();
adatokbetolt();
szazalekatlag();
megyekmeghivasa();
isktipusmeghivasa();
nemmeghivasa();
kepzestipusmeghivasa();
}
private void adatokbetolt()
{
using (StreamReader sr = new StreamReader("Adatok/adatok.csv", Encoding.Default))
{
while (!sr.EndOfStream)
{
var line = sr.ReadLine().Split(';');
Matek.Add(new erettsegik()
{
megye = line[0],
iskola_tipus = line[1],
nem = line[2],
kepzestipusa = line[3],
jegy = int.Parse(line[4]),
osszszazalek = int.Parse(line[5]),
osszpont = int.Parse(line[6]),
});
}
}
}
private void ismerv_SelectedIndexChanged(object sender, EventArgs e)
{
if (ismerv.SelectedItem.ToString() == "Megye")
{
ismervijellemzo.DataSource = megyek;
}
if (ismerv.SelectedItem.ToString() == "Iskola típus")
{
ismervijellemzo.DataSource = iskolatipus;
}
if (ismerv.SelectedItem.ToString() == "Nem")
{
ismervijellemzo.DataSource = nem;
}
if (ismerv.SelectedItem.ToString() == "Képzés típusa")
{
ismervijellemzo.DataSource = kepzestipus;
}
ismervijellemzo.SelectedIndex = 0;
}
private void megyekmeghivasa()
{
using (StreamReader sr = new StreamReader("Adatok/Megyek.csv", Encoding.Default))
{
while (!sr.EndOfStream)
{
var line = sr.ReadLine().Split(';');
megyek.Add(line[0]);
}
}
}
private void isktipusmeghivasa()
{
using (StreamReader sr = new StreamReader("Adatok/Iskolatipusa.csv", Encoding.Default))
{
while (!sr.EndOfStream)
{
var line = sr.ReadLine().Split(';');
iskolatipus.Add(line[0]);
}
}
}
private void nemmeghivasa()
{
using (StreamReader sr = new StreamReader("Adatok/Nem.csv", Encoding.Default))
{
while (!sr.EndOfStream)
{
var line = sr.ReadLine().Split(';');
nem.Add(line[0]);
}
}
}
private void kepzestipusmeghivasa()
{
using (StreamReader sr = new StreamReader("Adatok/Kepzestipusa.csv", Encoding.Default))
{
while (!sr.EndOfStream)
{
var line = sr.ReadLine().Split(';');
kepzestipus.Add(line[0]);
}
}
}
private void jegyatlag()
{
if (ismervijellemzo.SelectedItem != null && ismerv.SelectedItem.ToString() == "Megye")
{
chart1.Series["Series1"].Points.Clear();
double atlag = (from x in Matek
where x.megye == ismervijellemzo.SelectedItem.ToString()
select x.jegy).Average();
chart1.Series["Series1"].Points.AddY(atlag);
label3.Text = Math.Round(atlag, 2).ToString();
}
if (ismervijellemzo.SelectedItem != null && ismerv.SelectedItem.ToString() == "Iskola típus")
{
chart1.Series["Series1"].Points.Clear();
double atlag = (from x in Matek
where x.iskola_tipus == ismervijellemzo.SelectedItem.ToString()
select x.jegy).Average();
chart1.Series["Series1"].Points.AddY(atlag);
label3.Text = Math.Round(atlag, 2).ToString();
}
if (ismervijellemzo.SelectedItem != null && ismerv.SelectedItem.ToString() == "Nem")
{
chart1.Series["Series1"].Points.Clear();
double atlag = (from x in Matek
where x.nem == ismervijellemzo.SelectedItem.ToString()
select x.jegy).Average();
chart1.Series["Series1"].Points.AddY(atlag);
label3.Text = Math.Round(atlag, 2).ToString();
}
if (ismervijellemzo.SelectedItem != null && ismerv.SelectedItem.ToString() == "Képzés típusa")
{
chart1.Series["Series1"].Points.Clear();
double atlag = (from x in Matek
where x.kepzestipusa == ismervijellemzo.SelectedItem.ToString()
select x.jegy).Average();
chart1.Series["Series1"].Points.AddY(atlag);
label3.Text = Math.Round(atlag, 2).ToString();
}
}
private void szazalekatlag()
{
if (ismervijellemzo.SelectedItem != null && ismerv.SelectedItem.ToString() == "Megye")
{
chart3.Series["Series1"].Points.Clear();
double atlagszazalek = (from x in Matek
where x.megye == ismervijellemzo.SelectedItem.ToString()
select x.osszszazalek).Average();
chart3.Series["Series1"].Points.AddY(atlagszazalek);
label4.Text = Math.Round(atlagszazalek, 2).ToString();
}
if (ismervijellemzo.SelectedItem != null && ismerv.SelectedItem.ToString() == "Iskola típus")
{
chart3.Series["Series1"].Points.Clear();
double atlagszazalek = (from x in Matek
where x.iskola_tipus == ismervijellemzo.SelectedItem.ToString()
select x.osszszazalek).Average();
chart3.Series["Series1"].Points.AddY(atlagszazalek);
label4.Text = Math.Round(atlagszazalek, 2).ToString();
}
if (ismervijellemzo.SelectedItem != null && ismerv.SelectedItem.ToString() == "Nem")
{
chart3.Series["Series1"].Points.Clear();
double atlagszazalek = (from x in Matek
where x.nem == ismervijellemzo.SelectedItem.ToString()
select x.osszszazalek).Average();
chart3.Series["Series1"].Points.AddY(atlagszazalek);
label4.Text = Math.Round(atlagszazalek, 2).ToString();
}
if (ismervijellemzo.SelectedItem != null && ismerv.SelectedItem.ToString() == "Képzés típusa")
{
chart3.Series["Series1"].Points.Clear();
double atlagszazalek = (from x in Matek
where x.kepzestipusa == ismervijellemzo.SelectedItem.ToString()
select x.osszszazalek).Average();
chart3.Series["Series1"].Points.AddY(atlagszazalek);
label4.Text = Math.Round(atlagszazalek, 2).ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
jegyatlag();
szazalekatlag();
timer1.Enabled = true;
if (ismerv.SelectedItem.ToString() == "Megye")
{
csere = megyek;
}
if (ismerv.SelectedItem.ToString() == "Iskola típus")
{
csere = iskolatipus;
}
if (ismerv.SelectedItem.ToString() == "Nem")
{
csere = nem;
}
if (ismerv.SelectedItem.ToString() == "Képzés típusa")
{
csere = kepzestipus;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
chart2.Series["Series1"].Points.Clear();
chart4.Series["Series1"].Points.Clear();
//Átlag számítás
if (csere == megyek)
{
double atlag = (from x in Matek
where x.megye == csere[valasztott]
select x.jegy).Average();
chart2.Series["Series1"].Points.AddY(atlag);
label5.Text = Math.Round(atlag, 2).ToString();
}
if (csere == iskolatipus)
{
double atlag = (from x in Matek
where x.iskola_tipus == csere[valasztott]
select x.jegy).Average();
chart2.Series["Series1"].Points.AddY(atlag);
label5.Text = Math.Round(atlag, 2).ToString();
}
if (csere == nem)
{
double atlag = (from x in Matek
where x.nem == csere[valasztott]
select x.jegy).Average();
chart2.Series["Series1"].Points.AddY(atlag);
label5.Text = Math.Round(atlag, 2).ToString();
}
if (csere == kepzestipus)
{
double atlag = (from x in Matek
where x.kepzestipusa == csere[valasztott]
select x.jegy).Average();
chart2.Series["Series1"].Points.AddY(atlag);
label5.Text = Math.Round(atlag, 2).ToString();
}
//Százalék számítás
if (csere == megyek)
{
double atlagszazalek = (from x in Matek
where x.megye == csere[valasztott]
select x.osszszazalek).Average();
chart4.Series["Series1"].Points.AddY(atlagszazalek);
label6.Text = Math.Round(atlagszazalek, 2).ToString();
}
if (csere == iskolatipus)
{
double atlagszazalek = (from x in Matek
where x.iskola_tipus == csere[valasztott]
select x.osszszazalek).Average();
chart4.Series["Series1"].Points.AddY(atlagszazalek);
label6.Text = Math.Round(atlagszazalek, 2).ToString();
}
if (csere == nem)
{
double atlagszazalek = (from x in Matek
where x.nem == csere[valasztott]
select x.osszszazalek).Average();
chart4.Series["Series1"].Points.AddY(atlagszazalek);
label6.Text = Math.Round(atlagszazalek, 2).ToString();
}
if (csere == kepzestipus)
{
double atlagszazalek = (from x in Matek
where x.kepzestipusa == csere[valasztott]
select x.osszszazalek).Average();
chart4.Series["Series1"].Points.AddY(atlagszazalek);
label6.Text = Math.Round(atlagszazalek, 2).ToString();
}
label7.Text = csere[valasztott].ToString();
if (csere[valasztott]==csere.Last())
{
valasztott = 0;
}
else
{
valasztott++;
}
}
private void ismervijellemzo_SelectedIndexChanged(object sender, EventArgs e)
{
timer1.Enabled = false;
valasztott = 0;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp1.Entities
{
public class erettsegik
{
public string megye { get; set; }
public string iskola_tipus { get; set; }
public string nem { get; set; }
public string kepzestipusa { get; set; }
public int jegy { get; set; }
public int osszszazalek { get; set; }
public int osszpont { get; set; }
}
}
<file_sep>A feladatomban a 2020-as közép matematika érettségi adatival foglalkozom. A célja, hogy a felhasználó által egy kiválasztott ismérv alapján diagram használatával össze lehessen hasonlítani az eredményeket. A kiválasztott tulajdonsághoz tartozó adatok megjelenítésére két diagramm szerepel. A bal oldalihoz ki lehet választani a megadott ismérvhez tartozó értékek közül egyet, a mellette levő diagram, pedig Timer használatával végig megy az összes többi adaton.
| 9f8949be8656c26a5ad8c77d9eb3fcf99cf909a4 | [
"C#",
"Text"
] | 3 | C# | W8788F/IRF_Project | afd5a41beaa90b6ff9ba7645ae67ea78614e50c3 | 109ef5ccb232e19e6eaafdd42a5d3d3736860270 | |
refs/heads/master | <file_sep>FROM iojs:1.6.4
RUN npm install -g cb-cloud-benchmark
CMD [ "/bin/bash -c \"while true; do sleep 1; done\"" ]
<file_sep>import { Mock, Cluster } from "couchbase";
export default function (uri) {
let cluster;
if (uri) {
cluster = new Cluster(uri);
} else {
cluster = new Cluster("couchbase://127.0.0.1");
}
return cluster.openBucket("benchmark");
}
<file_sep>#! /usr/bin/env node
import cluster from "cluster";
import cli from "../lib/cli";
cli(cluster);
<file_sep>import connect from "./connect";
export default function (uri) {
let bucket = connect(uri);
let designDoc = {
"withSUVs": {
"map": `
function (doc, meta) {
if (doc.car.model === "SUV") {
emit(null, doc);
}
}`
},
"numConvertibles": {
"map": `
function (doc, meta) {
if (doc.car.model === "Convertible") {
emit(null, doc);
}
}`,
"reduce": "_count"
},
"averageAge": {
"map": `
function (doc, meta) {
emit(doc.make, doc.age);
}`,
"reduce": `
function (key, values, rereduce) {
var sum = 0;
for(i=0; i < values.length; i++) {
sum = sum + values[i];
}
return (sum / values.length);
}`
}
};
bucket.manager().upsertDesignDocument("benchmark", {"views": designDoc}, (err) => {
if (err) return console.log(err);
console.log("views setup");
process.exit(0);
});
}
<file_sep>import fs from "fs";
import _ from "lodash";
import JSONStream from "JSONStream";
import { ViewQuery } from "couchbase";
import connect from "./connect";
export function load(num, series, dir, uri, loadProgress) {
let bucket = connect(uri);
bucket.operationTimeout = 7500;
let stream = fs.createReadStream(`${dir}/generated_docs_${num}_${series}.json`, {"encoding": "utf8"});
let parser = JSONStream.parse("owners.*");
stream.pipe(parser);
let owners = [];
parser.on("data", (owner) => {
owners.push(owner);
});
parser.on("end", () => {
let chunks = _.chunk(owners, 1000);
loadProgress.start(owners.length);
let insertStage = Promise.resolve([]);
_.forEach(_.range(0, chunks.length), (chunkIndex) => {
let ownersChunk = chunks[chunkIndex];
insertStage = insertStage.then(() => {
return new Promise((resolve, reject) => {
let inserts = ownersChunk.map((owner) => {
return new Promise((resolve, reject) => {
bucket.insert(owner.id, owner, (err) => {
if (err && err.code !== 12) {
console.log(err);
return reject(err);
}
resolve();
});
});
});
Promise.all(inserts).then(() => {
loadProgress.completed(chunkIndex);
resolve();
}, reject).catch(reject);
});
}, (err) => {
console.log(err);
throw err;
});
});
insertStage.then(() => {
loadProgress.end();
process.exit(0);
});
});
}
export function query(uri) {
let bucket = connect(uri);
bucket.operationTimeout = 7500;
return new Promise((resolve, reject) => {
console.log("query people with SUVs");
let start = new Date();
let vq = ViewQuery.from("benchmark", "withSUVs");
vq.stale(ViewQuery.Update.BEFORE);
bucket.query(vq, (err, results) => {
if (err) return reject(err);
let end = new Date();
console.log(`people with SUVs: ${results.length}`);
console.log(`people with SUVs in: ${(end.getTime() - start.getTime())}ms`);
return resolve(results);
});
}).then(() => {
return new Promise((resolve, reject) => {
console.log("query number of convertibles");
let start = new Date();
let vq = ViewQuery.from("benchmark", "numConvertibles");
vq.stale(ViewQuery.Update.BEFORE);
bucket.query(vq, (err, results) => {
if (err) return reject(err);
let end = new Date();
console.log(`number of convertibles: ${results[0].value}`);
console.log(`number of convertibles in: ${(end.getTime() - start.getTime())}ms`);
return resolve(results);
});
});
}, (err) => {
console.log(err);
throw err;
}).then(() => {
return new Promise((resolve, reject) => {
console.log("query average age");
let start = new Date();
let vq = ViewQuery.from("benchmark", "averageAge");
vq.stale(ViewQuery.Update.BEFORE);
bucket.query(vq, (err, results) => {
if (err) return reject(err);
let end = new Date();
console.log(`average age: ${Math.round(results[0].value)}`);
console.log(`average age: ${(end.getTime() - start.getTime())}ms`);
resolve();
});
});
}, (err) => {
console.log(err);
throw err;
});
}
export default {
"load": load,
"query": query
}
<file_sep>import Chance from "chance";
import _ from "lodash";
import fs from "fs-extra";
export default function (num, series, dir, docs, progress=new Progress()) {
let chance = new Chance();
let owners = [];
let tick = 1000;
progress.start(docs);
_.forEach(_.range(0, docs), () => {
owners.push({
"id": chance.guid(),
"name": {
"first": chance.first(),
"last": chance.last()
},
"gender": chance.gender(),
"ssn": chance.ssn(),
"age": chance.age(),
"phone": chance.phone(),
"email": chance.email(),
"address": {
"street": chance.address({"short_suffix": true}),
"city": chance.city(),
"state": chance.state(),
"zip": chance.zip({"plusfour": true})
},
"car": {
"make": chance.pick(["Ford", "GM", "Honda", "Nissan", "Hyundai", "Toyota", "Mazda", "BMW", "Audi", "Volkswagen"]),
"model": chance.pick(["Coupe", "Sedan", "SUV", "Truck", "Van", "Wagon", "Convertible"]),
"year": chance.year({"min": 1990, "max": 2015})
}
});
tick--;
if (tick <= 0) {
progress.completed();
tick = 1000;
}
});
owners = _.uniq(owners, "id");
fs.ensureDir(dir, function (err) {
if (err) return console.log(err);
console.log(`saving to: ${dir}/generated_docs_${num}_${series}.json`);
fs.writeFile(`${dir}/generated_docs_${num}_${series}.json`, JSON.stringify({"owners": owners}), (err) => {
if (err) return console.log(err);
progress.end();
process.exit(0);
});
});
}
<file_sep>Couchbase Cloud Benchmarking
==========================
A module to benchmark various clouds by loading and accessing a large dataset in a Couchbase cluster<file_sep>export default class Progress {
constructor() { }
/* eslint-disable no-unused-vars */
start(total) { }
completed(i) { }
end() { }
/* eslint-enable no-unused-vars */
}
<file_sep>import _ from "lodash";
import yargs from "yargs";
import del from "del";
import path from "path";
import ProgressBar from "progress";
import { install } from "source-map-support";
import generate from "./generate";
import Progress from "./progress";
import setup from "./setup";
import benchmark from "./benchmark";
install();
class ProgressProgressBar {
constructor(num, operation) {
this.operation = operation;
this.num = num;
this.started = 0;
this.total = 0;
this.qued = 0;
}
start(total) {
this.started++;
this.total += total;
if (this.started >= this.num) {
console.log();
this.bar = new ProgressBar(`${this.operation} [:bar] :current/:total :percent :elapseds elapsed`, {
"complete": "=",
"incomplete": " ",
"width": 20,
"total": this.total
});
_.forEach(_.range(0, this.qued), () => {
this.bar.tick(1000);
});
}
}
completed() {
if (this.bar) {
this.bar.tick(1000);
} else {
this.qued++;
}
}
}
class WorkerProgress extends Progress {
constructor(num) {
super();
this.num = num;
}
start(total) {
process.send({
"num": this.num,
"type": "start",
"total": total
});
}
completed() {
process.send({
"num": this.num,
"type": "completed"
});
}
}
function spinCluster(cluster, dir, num, series, progress, command) {
return new Promise((resolve) => {
let numWorkers = 0;
_.forEach(_.range(1, num + 1), (i) => {
let worker = cluster.fork();
numWorkers++;
worker.send({
"num": i,
"series": series,
"dir": dir,
"command": command
});
});
if (progress) {
Object.keys(cluster.workers).forEach((id) => {
cluster.workers[id].on("message", (message) => {
switch (message.type) {
case "start":
progress.start(message.total);
break;
case "completed":
progress.completed();
break;
}
});
});
}
cluster.on("exit", () => {
numWorkers--;
if (numWorkers === 0) {
console.log(`completed series ${series}`);
resolve();
}
});
});
}
export default function (cluster) {
if (cluster.isMaster) {
let argv = yargs.usage("cloud-benchmark <command> [options]")
.command("generate", "generate test data")
.command("setup", "setup view models")
.command("run", "run tests")
.option("n", {
"alias": "num",
"default": 150000,
"describe": "number of docs to generate per process (generate only)",
"type": "number"
})
.option("p", {
"alias": "process",
"default": 2,
"describe": "number of processes to use",
"type": "number"
})
.option("s", {
"alias": "series",
"default": 8,
"describe": "number of times to run the import",
"type": "number"
})
.option("d", {
"alias": "dir",
"default": path.resolve(__dirname, "../../data"),
"describe": "directory to use",
"type": "string"
})
.option("c", {
"alias": "cluster",
"default": "couchbase://127.0.0.1",
"describe": "couchbase cluster uri (setup and test only)",
"type": "string"
})
.demand(1, "must provide a valid command")
.argv;
let command = argv._[0];
switch (command) {
case "generate":
del([`${argv.dir}/generated_docs_*_*.json`], (err) => {
if (err) throw err;
let generateSeries = Promise.resolve();
_.forEach(_.range(1, argv.series + 1), (seriesIndex) => {
generateSeries = generateSeries.then(() => {
return spinCluster(cluster, argv.dir, argv.process, seriesIndex, new ProgressProgressBar(argv.process, `series ${seriesIndex}: generate test docs`), {
"name": "generate",
"options": {
"docs": argv.num
}
});
});
});
generateSeries.then(() => {
console.log("completed");
});
});
break;
case "setup":
setup(argv.cluster);
break;
case "run":
let clusterSeries = Promise.resolve();
_.forEach(_.range(1, argv.series + 1), (seriesIndex) => {
clusterSeries = clusterSeries.then(() => {
return spinCluster(cluster, argv.dir, argv.process, seriesIndex, new ProgressProgressBar(argv.process, `series ${seriesIndex}: load test docs`), {
"name": "run",
"options": {
"cluster": argv.cluster
}
});
});
});
clusterSeries.then(() => {
return benchmark.query(argv.cluster);
}).then(() => {
return new Promise((resolve) => {
console.log("waiting 60 seconds to run queries again");
setTimeout(resolve, 60000);
});
}).then(() => {
return benchmark.query(argv.cluster);
}).then(() => process.exit(0), (err) => {
console.log(err);
throw err;
}).catch((err) => {
console.log(err);
throw err;
});
break;
default:
yargs.showHelp();
}
} else {
process.on("message", function (message) {
let num = message.num;
let command = message.command;
switch (command.name) {
case "generate":
generate(num, message.series, message.dir, command.options.docs, new WorkerProgress(num));
break;
case "run":
benchmark.load(num, message.series, message.dir, command.options.cluster, new WorkerProgress(num));
}
});
}
}
| f9888dcd9c9eee49ab13bc23b53f155276c02eff | [
"JavaScript",
"Dockerfile",
"Markdown"
] | 9 | Dockerfile | misterbisson/cb-cloud-benchmark | 0da28d2905c011b114ba9f273dbf9a23500fa122 | 995263abb35090195e941fcf58e61cc1ed8ab383 | |
refs/heads/master | <repo_name>spirit-component/goja<file_sep>/fbp.go
package goja
import (
"github.com/go-spirit/spirit/mail"
"github.com/go-spirit/spirit/worker/fbp/protocol"
)
type fbp struct {
session mail.Session
}
func (p *fbp) NewError(namespace string, code int, message string) error {
return &protocol.Error{
Code: int64(code),
Namespace: namespace,
Description: message,
}
}
func (p *fbp) SetError(namespace string, code int, message string) {
p.session.Payload().Content().SetError(
&protocol.Error{
Code: int64(code),
Namespace: namespace,
Description: message,
},
)
}
func (p *fbp) SetBody(body interface{}) error {
return p.session.Payload().Content().SetBody(body)
}
func (p *fbp) Object() map[string]interface{} {
v := make(map[string]interface{})
err := p.session.Payload().Content().ToObject(&v)
if err != nil {
return nil
}
return v
}
<file_sep>/goja.go
package goja
import (
crand "crypto/rand"
"encoding/binary"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"os"
"path/filepath"
"time"
"github.com/dop251/goja"
"github.com/dop251/goja_nodejs/console"
"github.com/dop251/goja_nodejs/require"
"github.com/go-spirit/spirit/component"
"github.com/go-spirit/spirit/mail"
"github.com/go-spirit/spirit/worker"
"github.com/gogap/config"
"github.com/spirit-component/goja/modules"
)
type Goja struct {
alias string
opts component.Options
conf config.Configuration
jsDir string
timeout time.Duration
}
func init() {
component.RegisterComponent("goja", NewGoja)
}
func NewGoja(alias string, opts ...component.Option) (comp component.Component, err error) {
compOpts := component.Options{}
for _, o := range opts {
o(&compOpts)
}
dir := compOpts.Config.GetString("dir")
if len(dir) == 0 {
err = errors.New("javascript dir is empty")
return
}
fi, err := os.Stat(dir)
if err != nil {
return
}
if !fi.IsDir() {
err = fmt.Errorf("path '%s' should be a folder", dir)
return
}
g := &Goja{
alias: alias,
opts: compOpts,
conf: compOpts.Config,
jsDir: dir,
timeout: compOpts.Config.GetTimeDuration("timeout", time.Second*30),
}
return g, nil
}
func (p *Goja) Start() error {
return nil
}
func (p *Goja) Stop() error {
return nil
}
func (p *Goja) Alias() string {
if p == nil {
return ""
}
return p.alias
}
func (p *Goja) Route(session mail.Session) worker.HandlerFunc {
return p.runJS
}
func (p *Goja) runJS(session mail.Session) (err error) {
action := session.Query("action")
dir := session.Query("dir")
strTimeout := session.Query("timeout")
version := session.Query("version")
if len(dir) == 0 {
dir = p.jsDir
}
timeout := p.timeout
if len(strTimeout) > 0 {
if dur, e := time.ParseDuration(strTimeout); e == nil {
timeout = dur
}
}
var apiJsFile string
if len(version) == 0 {
apiJsFile = filepath.Join(dir, action+".js")
} else {
apiJsFile = filepath.Join(dir, action+"_"+version+".js")
}
jsData, err := ioutil.ReadFile(apiJsFile)
if err != nil {
return
}
vm := newVM()
golib := modules.NewGoLib(vm)
golib.Import("utils")
golib.Import("log")
vm.Set("session", session)
vm.Set("caches", p.opts.Caches)
vm.Set("config", p.opts.Config)
vm.Set("go", golib)
vm.Set("fbp", &fbp{session})
prg, err := goja.Compile(apiJsFile, string(jsData), false)
if err != nil {
return
}
time.AfterFunc(timeout, func() {
vm.Interrupt("goja runtime execute timeout")
})
_, vmErr := vm.RunProgram(prg)
if vmErr != nil {
switch jsErr := vmErr.(type) {
case *goja.Exception:
err = fmt.Errorf("%v", jsErr.Value())
case *goja.InterruptedError:
err = fmt.Errorf("execute action: '%s' interrupted, %v", action, jsErr.Value())
default:
err = vmErr
}
}
return
}
func newVM() *goja.Runtime {
vm := goja.New()
vm.SetRandSource(newRandSource())
new(require.Registry).Enable(vm)
console.Enable(vm)
return vm
}
func newRandSource() goja.RandSource {
var seed int64
if err := binary.Read(crand.Reader, binary.LittleEndian, &seed); err != nil {
panic(fmt.Errorf("Could not read random bytes: %v", err))
}
return rand.New(rand.NewSource(seed)).Float64
}
<file_sep>/modules/modules.go
package modules
import (
"fmt"
"github.com/dop251/goja"
)
import (
"github.com/spirit-component/goja/modules/crypto/md5"
"github.com/spirit-component/goja/modules/encoding/base64"
"github.com/spirit-component/goja/modules/encoding/json"
jsfmt "github.com/spirit-component/goja/modules/fmt"
"github.com/spirit-component/goja/modules/io/ioutil"
"github.com/spirit-component/goja/modules/os"
"github.com/spirit-component/goja/modules/os/exec"
"github.com/spirit-component/goja/modules/time"
"github.com/spirit-component/goja/modules/utils"
"github.com/spirit-component/goja/modules/github.com/go-redis/redis"
"github.com/spirit-component/goja/modules/github.com/google/uuid"
"github.com/spirit-component/goja/modules/github.com/sirupsen/logrus"
)
var (
golibs = map[string]func(runtime *goja.Runtime){
"crypto/md5": md5.Enable,
"encoding/base64": base64.Enable,
"encoding/json": json.Enable,
"fmt": jsfmt.Enable,
"time": time.Enable,
"uuid": uuid.Enable,
"io/ioutil": ioutil.Enable,
"utils": utils.Enable,
"os": os.Enable,
"os/exec": exec.Enable,
"redis": redis.Enable,
"log": logrus.Enable,
}
)
func RegisterNativeModule(importPath string, enableFunc func(runtime *goja.Runtime)) (err error) {
if len(importPath) == 0 {
err = fmt.Errorf("import path could not be empty")
return
}
if enableFunc == nil {
err = fmt.Errorf("register EnableFunc could not be nil, path: %s", importPath)
return
}
golibs[importPath] = enableFunc
return
}
type GoLib struct {
vm *goja.Runtime
}
func NewGoLib(vm *goja.Runtime) *GoLib {
return &GoLib{vm}
}
func (p *GoLib) Import(modules ...string) {
if len(modules) == 0 {
return
}
var loadFns []func(runtime *goja.Runtime)
for _, module := range modules {
fn, exist := golibs[module]
if !exist {
panic(fmt.Errorf("module of '%s' dost not exist", module))
}
loadFns = append(loadFns, fn)
}
for i := 0; i < len(loadFns); i++ {
loadFns[i](p.vm)
}
}
<file_sep>/modules/encoding/json/json.go
package json
import (
original_json "encoding/json"
)
import (
"github.com/dop251/goja"
"github.com/gogap/gojs-tool/gojs"
)
var (
module = gojs.NewGojaModule("json")
)
func init() {
module.Set(
gojs.Objects{
// Functions
"Compact": original_json.Compact,
"HTMLEscape": original_json.HTMLEscape,
"Indent": original_json.Indent,
"Marshal": original_json.Marshal,
"MarshalIndent": original_json.MarshalIndent,
"NewDecoder": original_json.NewDecoder,
"NewEncoder": original_json.NewEncoder,
"Unmarshal": original_json.Unmarshal,
"Valid": original_json.Valid,
// Var and consts
// Types (value type)
"Decoder": func() original_json.Decoder { return original_json.Decoder{} },
"Encoder": func() original_json.Encoder { return original_json.Encoder{} },
"InvalidUTF8Error": func() original_json.InvalidUTF8Error { return original_json.InvalidUTF8Error{} },
"InvalidUnmarshalError": func() original_json.InvalidUnmarshalError { return original_json.InvalidUnmarshalError{} },
"MarshalerError": func() original_json.MarshalerError { return original_json.MarshalerError{} },
"SyntaxError": func() original_json.SyntaxError { return original_json.SyntaxError{} },
"UnmarshalFieldError": func() original_json.UnmarshalFieldError { return original_json.UnmarshalFieldError{} },
"UnmarshalTypeError": func() original_json.UnmarshalTypeError { return original_json.UnmarshalTypeError{} },
"UnsupportedTypeError": func() original_json.UnsupportedTypeError { return original_json.UnsupportedTypeError{} },
"UnsupportedValueError": func() original_json.UnsupportedValueError { return original_json.UnsupportedValueError{} },
// Types (pointer type)
"NewInvalidUTF8Error": func() *original_json.InvalidUTF8Error { return &original_json.InvalidUTF8Error{} },
"NewInvalidUnmarshalError": func() *original_json.InvalidUnmarshalError { return &original_json.InvalidUnmarshalError{} },
"NewMarshalerError": func() *original_json.MarshalerError { return &original_json.MarshalerError{} },
"NewSyntaxError": func() *original_json.SyntaxError { return &original_json.SyntaxError{} },
"NewUnmarshalFieldError": func() *original_json.UnmarshalFieldError { return &original_json.UnmarshalFieldError{} },
"NewUnmarshalTypeError": func() *original_json.UnmarshalTypeError { return &original_json.UnmarshalTypeError{} },
"NewUnsupportedTypeError": func() *original_json.UnsupportedTypeError { return &original_json.UnsupportedTypeError{} },
"NewUnsupportedValueError": func() *original_json.UnsupportedValueError { return &original_json.UnsupportedValueError{} },
},
).Register()
}
func Enable(runtime *goja.Runtime) {
module.Enable(runtime)
}
<file_sep>/README.md
goja
----
**component of goja**
#### build-config
```bash
> go-spirit pull --config build-goja.conf
> go-spirit build --config build-goja.conf
```
`build-goja.conf`
> working with post-api
```hocon
# project
goja {
# import packages
packages = ["github.com/spirit-component/goja", "github.com/spirit-component/postapi"]
build-args = {
go-get = ["-v"]
go-build = ["-v"]
}
fetchers {
git {
gopath = ${GOPATH}
}
goget {
gopath = ${GOPATH}
}
}
# the dependencies
repos = {
goja {
fetcher = goget
args = ["-v"]
url = "github.com/spirit-component/goja"
revision = master
}
postapi {
fetcher = goget
args = ["-v"]
url = "github.com/spirit-component/postapi"
revision = master
}
}
}
```
#### run config
```bash
> ./goja run --config goja.conf
```
`goja.conf`
```hocon
# goja config
components.goja.api-mock {
dir = "scripts/"
timeout = 3s
}
# post-api graph config
# default graph driver
components.post-api.external.grapher.default = {
todo-task-new {
name = "todo.task.new"
graph = {
error {
response {
seq = 1
url = "spirit://actors/fbp/post-api/external?action=callback"
}
}
entrypoint {
to-todo {
seq = 1
url = "spirit://actors/fbp/goja/api-mock?action=todo.task.new"
}
response {
seq = 2
url = "spirit://actors/fbp/post-api/external?action=callback"
}
}
}
}
}
```
```
# if you just want mapping api to js, you can use templer grapher
# the template file is json format, and it will render by text/template to replace some vars.
{
"error": {
"ports": [{
"seq": 1,
"url": "spirit://actors/fbp/post-api/external?action=callback"
}]
},
"entrypoint": {
"ports": [{
"seq": 1,
"url": "spirit://actors/fbp/goja/api-mock?action={{.api}}"
},{
"seq": 2,
"url": "spirit://actors/fbp/post-api/external?action=callback"
}]
}
}
```
> before using `templer` grapher, you should append `"github.com/spirit-component/postapi/grapher/templer"` to config of `packages` list in `build-goja.conf`
and rebuild goja component
#### javascript
`scripts/todo.task.new.js`
```javascript
go.Import("uuid")
go.Import("fmt")
go.Import("time", "encoding/base64")
log.Infoln("hello I am the logger by logrus")
id = uuid.New()
obj = fbp.Object()
cache.Set(id, {id: id, name: obj.name})
fbp.SetBody({id: id})
```
`scripts/todo.task.get.js`
```javascript
obj = fbp.Object()
if (obj) {
ret = cache.Get(obj.id)
if (ret[1]) {
fbp.SetBody(ret[0])
} else {
fbp.SetError("SPIRIT-GOJA",404,"task not exist")
}
} else {
fbp.SetError("SPIRIT-GOJA",400,"bad request")
}
```
### javascript
#### vars
name|type
:--|:--
session|github.com/go-spirit/spirit/mail.Session
cache|github.com/go-spirit/spirit/cache.Cache
config|github.com/gogap/config.Configuration
go|github.com/spirit-component/goja/modules.GoLib
fbp|github.com/spirit-component/goja.fbp
#### golibs
name |import path | repositry | default imported
:--|:--|:--|:--
md5 | `crypto/md5`||false
base64 | `encoding/base64`||false
json | `encoding/json`||false
fmt | `fmt`||false
uuid | `uuid`| `github.com/pborman/uuid`|false
ioutil|`io/ioutil`||false
os|`os`||false
exec|`os/exec`||false
time|`time`||false
redis|`redis`| `github.com/go-redis/redis`|false
log|`log`| `github.com/sirupsen/logrus`|true
utils|`utils`|`internal`|true
#### import lib in javascript
```javascript
go.Import("uuid")
go.Import("fmt")
go.Import("time", "encoding/base64")
log.Infoln("hello I am the logger by logrus")
id = uuid.New()
fbp.SetBody({id: id})
fmt.Println(base64.StdEncoding.EncodeToString("hello"))
```
#### generate your own native go module to javascript module
my another project is: [gojs-tool](https://github.com/gogap/gojs-tool), use this command to generate the module bridge
- generate moudle
```bash
# Default GOPATH
gojs-tool gen --template goja -r -n github.com/go-redis/redis
# GO Internal LIBs
gojs-tool gen --gopath $(go env GOROOT) --template goja -r -n encoding/json
```
- update generated code, add import `github.com/spirit-component/goja/modules` and add `modules.RegisterNativeModule` at `func init()`
```go
package your_package_name
import (
// ....
"github.com/spirit-component/goja/modules"
)
import (
"github.com/dop251/goja"
"github.com/gogap/gojs-tool/gojs"
)
var (
// the package name should be better equals to the "import/path/at/js" 's last slash name
// here is js
module = gojs.NewGojaModule("you_package_name")
)
func init() {
// .........
modules.RegisterNativeModule("import/path/at/js", Enable)
}
func Enable(runtime *goja.Runtime) {
module.Enable(runtime)
}
```
- update `build-goja.conf`
```
goja {
# append the generated module path
packages = [..., "your_native_package_path"]
}
```
<file_sep>/modules/time/time.go
package time
import (
original_time "time"
)
import (
"github.com/dop251/goja"
"github.com/gogap/gojs-tool/gojs"
)
var (
module = gojs.NewGojaModule("time")
)
func init() {
module.Set(
gojs.Objects{
// Functions
"After": original_time.After,
"AfterFunc": original_time.AfterFunc,
"Date": original_time.Date,
"FixedZone": original_time.FixedZone,
"LoadLocation": original_time.LoadLocation,
"NewTicker": original_time.NewTicker,
"NewTimer": original_time.NewTimer,
"Now": original_time.Now,
"Parse": original_time.Parse,
"ParseDuration": original_time.ParseDuration,
"ParseInLocation": original_time.ParseInLocation,
"Since": original_time.Since,
"Sleep": original_time.Sleep,
"Tick": original_time.Tick,
"Unix": original_time.Unix,
"Until": original_time.Until,
// Var and consts
"ANSIC": original_time.ANSIC,
"April": original_time.April,
"August": original_time.August,
"December": original_time.December,
"February": original_time.February,
"Friday": original_time.Friday,
"Hour": original_time.Hour,
"January": original_time.January,
"July": original_time.July,
"June": original_time.June,
"Kitchen": original_time.Kitchen,
"Local": original_time.Local,
"March": original_time.March,
"May": original_time.May,
"Microsecond": original_time.Microsecond,
"Millisecond": original_time.Millisecond,
"Minute": original_time.Minute,
"Monday": original_time.Monday,
"Nanosecond": original_time.Nanosecond,
"November": original_time.November,
"October": original_time.October,
"RFC1123": original_time.RFC1123,
"RFC1123Z": original_time.RFC1123Z,
"RFC3339": original_time.RFC3339,
"RFC3339Nano": original_time.RFC3339Nano,
"RFC822": original_time.RFC822,
"RFC822Z": original_time.RFC822Z,
"RFC850": original_time.RFC850,
"RubyDate": original_time.RubyDate,
"Saturday": original_time.Saturday,
"Second": original_time.Second,
"September": original_time.September,
"Stamp": original_time.Stamp,
"StampMicro": original_time.StampMicro,
"StampMilli": original_time.StampMilli,
"StampNano": original_time.StampNano,
"Sunday": original_time.Sunday,
"Thursday": original_time.Thursday,
"Tuesday": original_time.Tuesday,
"UTC": original_time.UTC,
"UnixDate": original_time.UnixDate,
"Wednesday": original_time.Wednesday,
// Types (value type)
"Location": func() original_time.Location { return original_time.Location{} },
"ParseError": func() original_time.ParseError { return original_time.ParseError{} },
"Ticker": func() original_time.Ticker { return original_time.Ticker{} },
"Time": func() original_time.Time { return original_time.Time{} },
"Timer": func() original_time.Timer { return original_time.Timer{} },
// Types (pointer type)
"NewLocation": func() *original_time.Location { return &original_time.Location{} },
"NewParseError": func() *original_time.ParseError { return &original_time.ParseError{} },
"NewTime": func() *original_time.Time { return &original_time.Time{} },
},
).Register()
}
func Enable(runtime *goja.Runtime) {
module.Enable(runtime)
}
<file_sep>/modules/utils/utils.go
package utils
import (
"github.com/dop251/goja"
"github.com/gogap/gojs-tool/gojs"
)
func isNil(v interface{}) bool {
return v == nil
}
var (
module = gojs.NewGojaModule("utils")
)
func init() {
module.Set(
gojs.Objects{
// Functions
"IsNil": isNil,
},
).Register()
}
func Enable(runtime *goja.Runtime) {
module.Enable(runtime)
}
<file_sep>/modules/github.com/google/uuid/uuid.go
package uuid
import (
original_uuid "github.com/google/uuid"
)
import (
"github.com/dop251/goja"
"github.com/gogap/gojs-tool/gojs"
)
var (
module = gojs.NewGojaModule("uuid")
)
func init() {
module.Set(
gojs.Objects{
// Functions
"ClockSequence": original_uuid.ClockSequence,
"FromBytes": original_uuid.FromBytes,
"GetTime": original_uuid.GetTime,
"Must": original_uuid.Must,
"MustParse": original_uuid.MustParse,
"New": original_uuid.New,
"NewDCEGroup": original_uuid.NewDCEGroup,
"NewDCEPerson": original_uuid.NewDCEPerson,
"NewDCESecurity": original_uuid.NewDCESecurity,
"NewHash": original_uuid.NewHash,
"NewMD5": original_uuid.NewMD5,
"NewRandom": original_uuid.NewRandom,
"NewRandomFromReader": original_uuid.NewRandomFromReader,
"NewSHA1": original_uuid.NewSHA1,
"NewUUID": original_uuid.NewUUID,
"NodeID": original_uuid.NodeID,
"NodeInterface": original_uuid.NodeInterface,
"Parse": original_uuid.Parse,
"ParseBytes": original_uuid.ParseBytes,
"SetClockSequence": original_uuid.SetClockSequence,
"SetNodeID": original_uuid.SetNodeID,
"SetNodeInterface": original_uuid.SetNodeInterface,
"SetRand": original_uuid.SetRand,
// Var and consts
"Future": original_uuid.Future,
"Group": original_uuid.Group,
"Invalid": original_uuid.Invalid,
"Microsoft": original_uuid.Microsoft,
"NameSpaceDNS": original_uuid.NameSpaceDNS,
"NameSpaceOID": original_uuid.NameSpaceOID,
"NameSpaceURL": original_uuid.NameSpaceURL,
"NameSpaceX500": original_uuid.NameSpaceX500,
"Nil": original_uuid.Nil,
"Org": original_uuid.Org,
"Person": original_uuid.Person,
"RFC4122": original_uuid.RFC4122,
"Reserved": original_uuid.Reserved,
// Types (value type)
// Types (pointer type)
},
).Register()
}
func Enable(runtime *goja.Runtime) {
module.Enable(runtime)
}
<file_sep>/modules/fmt/fmt.go
package fmt
import (
original_fmt "fmt"
)
import (
"github.com/dop251/goja"
"github.com/gogap/gojs-tool/gojs"
)
var (
module = gojs.NewGojaModule("fmt")
)
func init() {
module.Set(
gojs.Objects{
// Functions
"Errorf": original_fmt.Errorf,
"Fprint": original_fmt.Fprint,
"Fprintf": original_fmt.Fprintf,
"Fprintln": original_fmt.Fprintln,
"Fscan": original_fmt.Fscan,
"Fscanf": original_fmt.Fscanf,
"Fscanln": original_fmt.Fscanln,
"Print": original_fmt.Print,
"Printf": original_fmt.Printf,
"Println": original_fmt.Println,
"Scan": original_fmt.Scan,
"Scanf": original_fmt.Scanf,
"Scanln": original_fmt.Scanln,
"Sprint": original_fmt.Sprint,
"Sprintf": original_fmt.Sprintf,
"Sprintln": original_fmt.Sprintln,
"Sscan": original_fmt.Sscan,
"Sscanf": original_fmt.Sscanf,
"Sscanln": original_fmt.Sscanln,
// Var and consts
// Types (value type)
// Types (pointer type)
},
).Register()
}
func Enable(runtime *goja.Runtime) {
module.Enable(runtime)
}
<file_sep>/modules/encoding/base64/base64.go
package base64
import (
original_base64 "encoding/base64"
)
import (
"github.com/dop251/goja"
"github.com/gogap/gojs-tool/gojs"
)
var (
module = gojs.NewGojaModule("base64")
)
func init() {
module.Set(
gojs.Objects{
// Functions
"NewDecoder": original_base64.NewDecoder,
"NewEncoder": original_base64.NewEncoder,
"NewEncoding": original_base64.NewEncoding,
// Var and consts
"NoPadding": original_base64.NoPadding,
"RawStdEncoding": original_base64.RawStdEncoding,
"RawURLEncoding": original_base64.RawURLEncoding,
"StdEncoding": original_base64.StdEncoding,
"StdPadding": original_base64.StdPadding,
"URLEncoding": original_base64.URLEncoding,
// Types (value type)
"Encoding": func() original_base64.Encoding { return original_base64.Encoding{} },
// Types (pointer type)
},
).Register()
}
func Enable(runtime *goja.Runtime) {
module.Enable(runtime)
}
<file_sep>/modules/os/exec/exec.go
package exec
import (
original_exec "os/exec"
)
import (
"github.com/dop251/goja"
"github.com/gogap/gojs-tool/gojs"
)
var (
module = gojs.NewGojaModule("exec")
)
func init() {
module.Set(
gojs.Objects{
// Functions
"Command": original_exec.Command,
"CommandContext": original_exec.CommandContext,
"LookPath": original_exec.LookPath,
// Var and consts
"ErrNotFound": original_exec.ErrNotFound,
// Types (value type)
"Cmd": func() original_exec.Cmd { return original_exec.Cmd{} },
"Error": func() original_exec.Error { return original_exec.Error{} },
"ExitError": func() original_exec.ExitError { return original_exec.ExitError{} },
// Types (pointer type)
"NewCmd": func() *original_exec.Cmd { return &original_exec.Cmd{} },
"NewError": func() *original_exec.Error { return &original_exec.Error{} },
"NewExitError": func() *original_exec.ExitError { return &original_exec.ExitError{} },
},
).Register()
}
func Enable(runtime *goja.Runtime) {
module.Enable(runtime)
}
<file_sep>/modules/github.com/go-redis/redis/redis.go
package redis
import (
original_redis "github.com/go-redis/redis"
)
import (
"github.com/dop251/goja"
"github.com/gogap/gojs-tool/gojs"
)
var (
module = gojs.NewGojaModule("redis")
)
func init() {
module.Set(
gojs.Objects{
// Functions
"NewBoolCmd": original_redis.NewBoolCmd,
"NewBoolResult": original_redis.NewBoolResult,
"NewBoolSliceCmd": original_redis.NewBoolSliceCmd,
"NewBoolSliceResult": original_redis.NewBoolSliceResult,
"NewClient": original_redis.NewClient,
"NewClusterClient": original_redis.NewClusterClient,
"NewClusterSlotsCmd": original_redis.NewClusterSlotsCmd,
"NewClusterSlotsCmdResult": original_redis.NewClusterSlotsCmdResult,
"NewCmd": original_redis.NewCmd,
"NewCmdResult": original_redis.NewCmdResult,
"NewCommandsInfoCmd": original_redis.NewCommandsInfoCmd,
"NewCommandsInfoCmdResult": original_redis.NewCommandsInfoCmdResult,
"NewDurationCmd": original_redis.NewDurationCmd,
"NewDurationResult": original_redis.NewDurationResult,
"NewFailoverClient": original_redis.NewFailoverClient,
"NewFloatCmd": original_redis.NewFloatCmd,
"NewFloatResult": original_redis.NewFloatResult,
"NewGeoLocationCmd": original_redis.NewGeoLocationCmd,
"NewGeoLocationCmdResult": original_redis.NewGeoLocationCmdResult,
"NewGeoPosCmd": original_redis.NewGeoPosCmd,
"NewIntCmd": original_redis.NewIntCmd,
"NewIntResult": original_redis.NewIntResult,
"NewRing": original_redis.NewRing,
"NewScanCmd": original_redis.NewScanCmd,
"NewScanCmdResult": original_redis.NewScanCmdResult,
"NewScript": original_redis.NewScript,
"NewSliceCmd": original_redis.NewSliceCmd,
"NewSliceResult": original_redis.NewSliceResult,
"NewStatusCmd": original_redis.NewStatusCmd,
"NewStatusResult": original_redis.NewStatusResult,
"NewStringCmd": original_redis.NewStringCmd,
"NewStringIntMapCmd": original_redis.NewStringIntMapCmd,
"NewStringIntMapCmdResult": original_redis.NewStringIntMapCmdResult,
"NewStringResult": original_redis.NewStringResult,
"NewStringSliceCmd": original_redis.NewStringSliceCmd,
"NewStringSliceResult": original_redis.NewStringSliceResult,
"NewStringStringMapCmd": original_redis.NewStringStringMapCmd,
"NewStringStringMapResult": original_redis.NewStringStringMapResult,
"NewStringStructMapCmd": original_redis.NewStringStructMapCmd,
"NewTimeCmd": original_redis.NewTimeCmd,
"NewUniversalClient": original_redis.NewUniversalClient,
"NewZSliceCmd": original_redis.NewZSliceCmd,
"NewZSliceCmdResult": original_redis.NewZSliceCmdResult,
"ParseURL": original_redis.ParseURL,
"SetLogger": original_redis.SetLogger,
// Var and consts
"Nil": original_redis.Nil,
"TxFailedErr": original_redis.TxFailedErr,
// Types (value type)
"BitCount": func() original_redis.BitCount { return original_redis.BitCount{} },
"BoolCmd": func() original_redis.BoolCmd { return original_redis.BoolCmd{} },
"BoolSliceCmd": func() original_redis.BoolSliceCmd { return original_redis.BoolSliceCmd{} },
"Client": func() original_redis.Client { return original_redis.Client{} },
"ClusterClient": func() original_redis.ClusterClient { return original_redis.ClusterClient{} },
"ClusterNode": func() original_redis.ClusterNode { return original_redis.ClusterNode{} },
"ClusterOptions": func() original_redis.ClusterOptions { return original_redis.ClusterOptions{} },
"ClusterSlot": func() original_redis.ClusterSlot { return original_redis.ClusterSlot{} },
"ClusterSlotsCmd": func() original_redis.ClusterSlotsCmd { return original_redis.ClusterSlotsCmd{} },
"Cmd": func() original_redis.Cmd { return original_redis.Cmd{} },
"CommandInfo": func() original_redis.CommandInfo { return original_redis.CommandInfo{} },
"CommandsInfoCmd": func() original_redis.CommandsInfoCmd { return original_redis.CommandsInfoCmd{} },
"Conn": func() original_redis.Conn { return original_redis.Conn{} },
"DurationCmd": func() original_redis.DurationCmd { return original_redis.DurationCmd{} },
"FailoverOptions": func() original_redis.FailoverOptions { return original_redis.FailoverOptions{} },
"FloatCmd": func() original_redis.FloatCmd { return original_redis.FloatCmd{} },
"GeoLocation": func() original_redis.GeoLocation { return original_redis.GeoLocation{} },
"GeoLocationCmd": func() original_redis.GeoLocationCmd { return original_redis.GeoLocationCmd{} },
"GeoPos": func() original_redis.GeoPos { return original_redis.GeoPos{} },
"GeoPosCmd": func() original_redis.GeoPosCmd { return original_redis.GeoPosCmd{} },
"GeoRadiusQuery": func() original_redis.GeoRadiusQuery { return original_redis.GeoRadiusQuery{} },
"IntCmd": func() original_redis.IntCmd { return original_redis.IntCmd{} },
"Message": func() original_redis.Message { return original_redis.Message{} },
"Options": func() original_redis.Options { return original_redis.Options{} },
"Pipeline": func() original_redis.Pipeline { return original_redis.Pipeline{} },
"Pong": func() original_redis.Pong { return original_redis.Pong{} },
"PubSub": func() original_redis.PubSub { return original_redis.PubSub{} },
"Ring": func() original_redis.Ring { return original_redis.Ring{} },
"RingOptions": func() original_redis.RingOptions { return original_redis.RingOptions{} },
"ScanCmd": func() original_redis.ScanCmd { return original_redis.ScanCmd{} },
"ScanIterator": func() original_redis.ScanIterator { return original_redis.ScanIterator{} },
"Script": func() original_redis.Script { return original_redis.Script{} },
"SliceCmd": func() original_redis.SliceCmd { return original_redis.SliceCmd{} },
"Sort": func() original_redis.Sort { return original_redis.Sort{} },
"StatusCmd": func() original_redis.StatusCmd { return original_redis.StatusCmd{} },
"StringCmd": func() original_redis.StringCmd { return original_redis.StringCmd{} },
"StringIntMapCmd": func() original_redis.StringIntMapCmd { return original_redis.StringIntMapCmd{} },
"StringSliceCmd": func() original_redis.StringSliceCmd { return original_redis.StringSliceCmd{} },
"StringStringMapCmd": func() original_redis.StringStringMapCmd { return original_redis.StringStringMapCmd{} },
"StringStructMapCmd": func() original_redis.StringStructMapCmd { return original_redis.StringStructMapCmd{} },
"Subscription": func() original_redis.Subscription { return original_redis.Subscription{} },
"TimeCmd": func() original_redis.TimeCmd { return original_redis.TimeCmd{} },
"Tx": func() original_redis.Tx { return original_redis.Tx{} },
"UniversalOptions": func() original_redis.UniversalOptions { return original_redis.UniversalOptions{} },
"Z": func() original_redis.Z { return original_redis.Z{} },
"ZRangeBy": func() original_redis.ZRangeBy { return original_redis.ZRangeBy{} },
"ZSliceCmd": func() original_redis.ZSliceCmd { return original_redis.ZSliceCmd{} },
"ZStore": func() original_redis.ZStore { return original_redis.ZStore{} },
// Types (pointer type)
"NewBitCount": func() *original_redis.BitCount { return &original_redis.BitCount{} },
"NewClusterNode": func() *original_redis.ClusterNode { return &original_redis.ClusterNode{} },
"NewClusterOptions": func() *original_redis.ClusterOptions { return &original_redis.ClusterOptions{} },
"NewClusterSlot": func() *original_redis.ClusterSlot { return &original_redis.ClusterSlot{} },
"NewCommandInfo": func() *original_redis.CommandInfo { return &original_redis.CommandInfo{} },
"NewConn": func() *original_redis.Conn { return &original_redis.Conn{} },
"NewFailoverOptions": func() *original_redis.FailoverOptions { return &original_redis.FailoverOptions{} },
"NewGeoLocation": func() *original_redis.GeoLocation { return &original_redis.GeoLocation{} },
"NewGeoPos": func() *original_redis.GeoPos { return &original_redis.GeoPos{} },
"NewGeoRadiusQuery": func() *original_redis.GeoRadiusQuery { return &original_redis.GeoRadiusQuery{} },
"NewMessage": func() *original_redis.Message { return &original_redis.Message{} },
"NewOptions": func() *original_redis.Options { return &original_redis.Options{} },
"NewPipeline": func() *original_redis.Pipeline { return &original_redis.Pipeline{} },
"NewPong": func() *original_redis.Pong { return &original_redis.Pong{} },
"NewPubSub": func() *original_redis.PubSub { return &original_redis.PubSub{} },
"NewRingOptions": func() *original_redis.RingOptions { return &original_redis.RingOptions{} },
"NewScanIterator": func() *original_redis.ScanIterator { return &original_redis.ScanIterator{} },
"NewSort": func() *original_redis.Sort { return &original_redis.Sort{} },
"NewSubscription": func() *original_redis.Subscription { return &original_redis.Subscription{} },
"NewTx": func() *original_redis.Tx { return &original_redis.Tx{} },
"NewUniversalOptions": func() *original_redis.UniversalOptions { return &original_redis.UniversalOptions{} },
"NewZ": func() *original_redis.Z { return &original_redis.Z{} },
"NewZRangeBy": func() *original_redis.ZRangeBy { return &original_redis.ZRangeBy{} },
"NewZStore": func() *original_redis.ZStore { return &original_redis.ZStore{} },
},
).Register()
}
func Enable(runtime *goja.Runtime) {
module.Enable(runtime)
}
<file_sep>/modules/crypto/md5/md5.go
package md5
import (
original_md5 "crypto/md5"
)
import (
"github.com/dop251/goja"
"github.com/gogap/gojs-tool/gojs"
)
var (
module = gojs.NewGojaModule("md5")
)
func init() {
module.Set(
gojs.Objects{
// Functions
"New": original_md5.New,
"Sum": original_md5.Sum,
// Var and consts
"BlockSize": original_md5.BlockSize,
"Size": original_md5.Size,
},
).Register()
}
func Enable(runtime *goja.Runtime) {
module.Enable(runtime)
}
<file_sep>/modules/github.com/sirupsen/logrus/hooks/hooks.go
package hooks
import (
"github.com/dop251/goja"
"github.com/dop251/goja_nodejs/require"
)
import (
"github.com/spirit-component/goja/modules/github.com/sirupsen/logrus/hooks/syslog"
"github.com/spirit-component/goja/modules/github.com/sirupsen/logrus/hooks/test"
)
type hooks struct {
syslog *goja.Object
test *goja.Object
}
func init() {
require.RegisterNativeModule("hooks", Require)
}
func Require(runtime *goja.Runtime, module *goja.Object) {
pkg := &hooks{
syslog: require.Require(runtime, "syslog").(*goja.Object),
test: require.Require(runtime, "test").(*goja.Object),
}
o := module.Get("exports").(*goja.Object)
o.Set("syslog", pkg.syslog)
o.Set("test", pkg.test)
}
func Enable(runtime *goja.Runtime) {
syslog.Enable(runtime)
test.Enable(runtime)
runtime.Set("hooks", require.Require(runtime, "hooks"))
}
<file_sep>/modules/github.com/sirupsen/logrus/logrus.go
package logrus
import (
original_logrus "github.com/sirupsen/logrus"
)
import (
"github.com/dop251/goja"
"github.com/gogap/gojs-tool/gojs"
)
var (
module = gojs.NewGojaModule("log")
)
func init() {
module.Set(
gojs.Objects{
// Functions
"AddHook": original_logrus.AddHook,
"Debug": original_logrus.Debug,
"Debugf": original_logrus.Debugf,
"Debugln": original_logrus.Debugln,
"Error": original_logrus.Error,
"Errorf": original_logrus.Errorf,
"Errorln": original_logrus.Errorln,
"Exit": original_logrus.Exit,
"Fatal": original_logrus.Fatal,
"Fatalf": original_logrus.Fatalf,
"Fatalln": original_logrus.Fatalln,
"GetLevel": original_logrus.GetLevel,
"Info": original_logrus.Info,
"Infof": original_logrus.Infof,
"Infoln": original_logrus.Infoln,
"New": original_logrus.New,
"NewEntry": original_logrus.NewEntry,
"Panic": original_logrus.Panic,
"Panicf": original_logrus.Panicf,
"Panicln": original_logrus.Panicln,
"ParseLevel": original_logrus.ParseLevel,
"Print": original_logrus.Print,
"Printf": original_logrus.Printf,
"Println": original_logrus.Println,
"RegisterExitHandler": original_logrus.RegisterExitHandler,
"SetFormatter": original_logrus.SetFormatter,
"SetLevel": original_logrus.SetLevel,
"SetOutput": original_logrus.SetOutput,
"StandardLogger": original_logrus.StandardLogger,
"Warn": original_logrus.Warn,
"Warnf": original_logrus.Warnf,
"Warning": original_logrus.Warning,
"Warningf": original_logrus.Warningf,
"Warningln": original_logrus.Warningln,
"Warnln": original_logrus.Warnln,
"WithError": original_logrus.WithError,
"WithField": original_logrus.WithField,
"WithFields": original_logrus.WithFields,
// Var and consts
"AllLevels": original_logrus.AllLevels,
"DebugLevel": original_logrus.DebugLevel,
"ErrorKey": original_logrus.ErrorKey,
"ErrorLevel": original_logrus.ErrorLevel,
"FatalLevel": original_logrus.FatalLevel,
"FieldKeyLevel": original_logrus.FieldKeyLevel,
"FieldKeyMsg": original_logrus.FieldKeyMsg,
"FieldKeyTime": original_logrus.FieldKeyTime,
"InfoLevel": original_logrus.InfoLevel,
"PanicLevel": original_logrus.PanicLevel,
"WarnLevel": original_logrus.WarnLevel,
// Types (value type)
"Entry": func() original_logrus.Entry { return original_logrus.Entry{} },
"JSONFormatter": func() original_logrus.JSONFormatter { return original_logrus.JSONFormatter{} },
"Logger": func() original_logrus.Logger { return original_logrus.Logger{} },
"MutexWrap": func() original_logrus.MutexWrap { return original_logrus.MutexWrap{} },
"TextFormatter": func() original_logrus.TextFormatter { return original_logrus.TextFormatter{} },
// Types (pointer type)
"NewJSONFormatter": func() *original_logrus.JSONFormatter { return &original_logrus.JSONFormatter{} },
"NewLogger": func() *original_logrus.Logger { return &original_logrus.Logger{} },
"NewMutexWrap": func() *original_logrus.MutexWrap { return &original_logrus.MutexWrap{} },
"NewTextFormatter": func() *original_logrus.TextFormatter { return &original_logrus.TextFormatter{} },
},
).Register()
}
func Enable(runtime *goja.Runtime) {
module.Enable(runtime)
}
<file_sep>/modules/io/ioutil/ioutil.go
package ioutil
import (
original_ioutil "io/ioutil"
)
import (
"github.com/dop251/goja"
"github.com/gogap/gojs-tool/gojs"
)
var (
module = gojs.NewGojaModule("ioutil")
)
func init() {
module.Set(
gojs.Objects{
// Functions
"NopCloser": original_ioutil.NopCloser,
"ReadAll": original_ioutil.ReadAll,
"ReadDir": original_ioutil.ReadDir,
"ReadFile": original_ioutil.ReadFile,
"TempDir": original_ioutil.TempDir,
"TempFile": original_ioutil.TempFile,
"WriteFile": original_ioutil.WriteFile,
// Var and consts
"Discard": original_ioutil.Discard,
// Types (value type)
// Types (pointer type)
},
).Register()
}
func Enable(runtime *goja.Runtime) {
module.Enable(runtime)
}
<file_sep>/modules/os/os.go
package os
import (
original_os "os"
)
import (
"github.com/dop251/goja"
"github.com/gogap/gojs-tool/gojs"
)
var (
module = gojs.NewGojaModule("os")
)
func init() {
module.Set(
gojs.Objects{
// Functions
"Chdir": original_os.Chdir,
"Chmod": original_os.Chmod,
"Chown": original_os.Chown,
"Chtimes": original_os.Chtimes,
"Clearenv": original_os.Clearenv,
"Create": original_os.Create,
"Environ": original_os.Environ,
"Executable": original_os.Executable,
"Exit": original_os.Exit,
"Expand": original_os.Expand,
"ExpandEnv": original_os.ExpandEnv,
"FindProcess": original_os.FindProcess,
"Getegid": original_os.Getegid,
"Getenv": original_os.Getenv,
"Geteuid": original_os.Geteuid,
"Getgid": original_os.Getgid,
"Getgroups": original_os.Getgroups,
"Getpagesize": original_os.Getpagesize,
"Getpid": original_os.Getpid,
"Getppid": original_os.Getppid,
"Getuid": original_os.Getuid,
"Getwd": original_os.Getwd,
"Hostname": original_os.Hostname,
"IsExist": original_os.IsExist,
"IsNotExist": original_os.IsNotExist,
"IsPathSeparator": original_os.IsPathSeparator,
"IsPermission": original_os.IsPermission,
"Lchown": original_os.Lchown,
"Link": original_os.Link,
"LookupEnv": original_os.LookupEnv,
"Lstat": original_os.Lstat,
"Mkdir": original_os.Mkdir,
"MkdirAll": original_os.MkdirAll,
"NewFile": original_os.NewFile,
"NewSyscallError": original_os.NewSyscallError,
"Open": original_os.Open,
"OpenFile": original_os.OpenFile,
"Pipe": original_os.Pipe,
"Readlink": original_os.Readlink,
"Remove": original_os.Remove,
"RemoveAll": original_os.RemoveAll,
"Rename": original_os.Rename,
"SameFile": original_os.SameFile,
"Setenv": original_os.Setenv,
"StartProcess": original_os.StartProcess,
"Stat": original_os.Stat,
"Symlink": original_os.Symlink,
"TempDir": original_os.TempDir,
"Truncate": original_os.Truncate,
"Unsetenv": original_os.Unsetenv,
// Var and consts
"Args": original_os.Args,
"DevNull": original_os.DevNull,
"ErrClosed": original_os.ErrClosed,
"ErrExist": original_os.ErrExist,
"ErrInvalid": original_os.ErrInvalid,
"ErrNotExist": original_os.ErrNotExist,
"ErrPermission": original_os.ErrPermission,
"Interrupt": original_os.Interrupt,
"Kill": original_os.Kill,
"ModeAppend": original_os.ModeAppend,
"ModeCharDevice": original_os.ModeCharDevice,
"ModeDevice": original_os.ModeDevice,
"ModeDir": original_os.ModeDir,
"ModeExclusive": original_os.ModeExclusive,
"ModeNamedPipe": original_os.ModeNamedPipe,
"ModePerm": original_os.ModePerm,
"ModeSetgid": original_os.ModeSetgid,
"ModeSetuid": original_os.ModeSetuid,
"ModeSocket": original_os.ModeSocket,
"ModeSticky": original_os.ModeSticky,
"ModeSymlink": original_os.ModeSymlink,
"ModeTemporary": original_os.ModeTemporary,
"ModeType": original_os.ModeType,
"O_APPEND": original_os.O_APPEND,
"O_CREATE": original_os.O_CREATE,
"O_EXCL": original_os.O_EXCL,
"O_RDONLY": original_os.O_RDONLY,
"O_RDWR": original_os.O_RDWR,
"O_SYNC": original_os.O_SYNC,
"O_TRUNC": original_os.O_TRUNC,
"O_WRONLY": original_os.O_WRONLY,
"PathListSeparator": original_os.PathListSeparator,
"PathSeparator": original_os.PathSeparator,
"SEEK_CUR": original_os.SEEK_CUR,
"SEEK_END": original_os.SEEK_END,
"SEEK_SET": original_os.SEEK_SET,
"Stderr": original_os.Stderr,
"Stdin": original_os.Stdin,
"Stdout": original_os.Stdout,
// Types (value type)
"File": func() original_os.File { return original_os.File{} },
"LinkError": func() original_os.LinkError { return original_os.LinkError{} },
"PathError": func() original_os.PathError { return original_os.PathError{} },
"ProcAttr": func() original_os.ProcAttr { return original_os.ProcAttr{} },
"Process": func() original_os.Process { return original_os.Process{} },
"ProcessState": func() original_os.ProcessState { return original_os.ProcessState{} },
"SyscallError": func() original_os.SyscallError { return original_os.SyscallError{} },
// Types (pointer type)
"NewLinkError": func() *original_os.LinkError { return &original_os.LinkError{} },
"NewPathError": func() *original_os.PathError { return &original_os.PathError{} },
"NewProcAttr": func() *original_os.ProcAttr { return &original_os.ProcAttr{} },
"NewProcess": func() *original_os.Process { return &original_os.Process{} },
"NewProcessState": func() *original_os.ProcessState { return &original_os.ProcessState{} },
},
).Register()
}
func Enable(runtime *goja.Runtime) {
module.Enable(runtime)
}
<file_sep>/modules/github.com/sirupsen/logrus/hooks/syslog/syslog.go
package syslog
import (
original_syslog "github.com/sirupsen/logrus/hooks/syslog"
)
import (
"github.com/dop251/goja"
"github.com/gogap/gojs-tool/gojs"
)
var (
module = gojs.NewGojaModule("syslog")
)
func init() {
module.Set(
gojs.Objects{
// Functions
"NewSyslogHook": original_syslog.NewSyslogHook,
// Var and consts
// Types (value type)
"SyslogHook": func() original_syslog.SyslogHook { return original_syslog.SyslogHook{} },
// Types (pointer type)
},
).Register()
}
func Enable(runtime *goja.Runtime) {
module.Enable(runtime)
}
| 433d8ae291ddc1521d997a103e004759ebb7ccea | [
"Markdown",
"Go"
] | 18 | Go | spirit-component/goja | 9dbd4e7478019a543d5262bcc5448ec478fd84e4 | c97dd02bc2a3489360e976190996eb1d6518d1a0 | |
refs/heads/master | <file_sep>require "formula"
class TexRequirement < Requirement
fatal false
env :userpaths
def satisfied?
quiet_system("latex", "-version") && quiet_system("dvipng", "-version")
end
def message; <<-EOS.undent
LaTeX not found. This is optional for Matplotlib.
If you want, https://www.tug.org/mactex/ provides an installer.
EOS
end
end
class NoExternalPyCXXPackage < Requirement
fatal false
satisfy do
not quiet_system "python", "-c", "import CXX"
end
def message; <<-EOS.undent
*** Warning, PyCXX detected! ***
On your system, there is already a PyCXX version installed, that will
probably make the build of Matplotlib fail. In python you can test if that
package is available with `import CXX`. To get a hint where that package
is installed, you can:
python -c "import os; import CXX; print(os.path.dirname(CXX.__file__))"
See also: https://github.com/Homebrew/homebrew-python/issues/56
EOS
end
end
class Matplotlib < Formula
homepage "http://matplotlib.org"
url "https://downloads.sourceforge.net/project/matplotlib/matplotlib/matplotlib-1.4.2/matplotlib-1.4.2.tar.gz"
sha1 "242c57ddae808b1869cad4b08bb0973c513e12f8"
head "https://github.com/matplotlib/matplotlib.git"
depends_on "pkg-config" => :build
depends_on :python => :recommended
depends_on :python3 => :optional
depends_on "freetype"
depends_on "libpng"
depends_on TexRequirement => :optional
depends_on NoExternalPyCXXPackage
depends_on "cairo" => :optional
depends_on "ghostscript" => :optional
depends_on "homebrew/dupes/tcl-tk" => :optional
option "with-gtk3", "Build with gtk3 support"
requires_py3 = []
requires_py3 << "with-python3" if build.with? "python3"
if build.with? "gtk3"
depends_on "pygobject3" => requires_py3
depends_on "gtk+3"
end
if build.with? "python"
depends_on "pygtk" => :optional
depends_on "pygobject" if build.with? 'pygtk'
depends_on "gtk+" if build.with? 'pygtk'
end
if build.with? "python3"
depends_on "numpy" => "with-python3"
depends_on "pyside" => [:optional, "with-python3"]
depends_on "pyqt" => [:optional, "with-python3"]
depends_on "pyqt5" => [:optional, "with-python3"]
depends_on "py3cairo" if build.with? "cairo"
else
depends_on "numpy"
depends_on "pyside" => :optional
depends_on "pyqt" => :optional
depends_on "pyqt5" => [:optional, "with-python"]
end
cxxstdlib_check :skip
resource "dateutil" do
url "https://pypi.python.org/packages/source/p/python-dateutil/python-dateutil-2.2.tar.gz"
sha1 "fbafcd19ea0082b3ecb17695b4cb46070181699f"
end
resource "mock" do
url "https://pypi.python.org/packages/source/m/mock/mock-1.0.1.tar.gz"
sha1 "ba2b1d5f84448497e14e25922c5e3293f0a91c7e"
end
resource "nose" do
url "https://pypi.python.org/packages/source/n/nose/nose-1.3.4.tar.gz"
sha1 "4d21578b480540e4e50ffae063094a14db2487d7"
end
resource "pyparsing" do
url "https://pypi.python.org/packages/source/p/pyparsing/pyparsing-2.0.3.tar.gz"
sha1 "39299b6bb894a27fb9cd5b548c21d168b893b434"
end
resource "six" do
url "https://pypi.python.org/packages/source/s/six/six-1.8.0.tar.gz"
sha1 "aa3b0659cbc85c6c7a91efc51f2d1007040070cd"
end
def package_installed? python, module_name
quiet_system python, "-c", "import #{module_name}"
end
def install
inreplace "setupext.py",
"'darwin': ['/usr/local/'",
"'darwin': ['#{HOMEBREW_PREFIX}'"
# Apple has the Frameworks (esp. Tk.Framework) in a different place
unless MacOS::CLT.installed?
inreplace "setupext.py",
"'/System/Library/Frameworks/',",
"'#{MacOS.sdk_path}/System/Library/Frameworks',"
end
old_pythonpath = ENV["PYTHONPATH"]
Language::Python.each_python(build) do |python, version|
ENV["PYTHONPATH"] = old_pythonpath
resources.each do |r|
r.stage do
Language::Python.setup_install python, libexec
end unless package_installed? python, r.name
end
bundle_path = libexec/"lib/python#{version}/site-packages"
ENV.append_path "PYTHONPATH", bundle_path
dest_path = lib/"python#{version}/site-packages"
mkdir_p dest_path
(dest_path/"homebrew-matplotlib-bundle.pth").atomic_write(bundle_path.to_s + "\n")
# ensure Homebrew numpy is found
ENV.prepend_path "PYTHONPATH", Language::Python.homebrew_site_packages(version)
Language::Python.setup_install python, prefix
end
end
def caveats
s = <<-EOS.undent
If you want to use the `wxagg` backend, do `brew install wxpython`.
This can be done even after the matplotlib install.
EOS
if build.with? "python" and not Formula["python"].installed?
homebrew_site_packages = Language::Python.homebrew_site_packages
user_site_packages = Language::Python.user_site_packages "python"
s += <<-EOS.undent
If you use system python (that comes - depending on the OS X version -
with older versions of numpy, scipy and matplotlib), you may need to
ensure that the brewed packages come earlier in Python's sys.path with:
mkdir -p #{user_site_packages}
echo 'import sys; sys.path.insert(1, "#{homebrew_site_packages}")' >> #{user_site_packages}/homebrew.pth
EOS
end
s
end
test do
ohai "This test takes quite a while. Use --verbose to see progress."
Language::Python.each_python(build) do |python, version|
system python, "-c", "import matplotlib as m; m.test()"
end
end
end
| 8672d3f429a9fe3d4fd92b6eb54112d8841e5552 | [
"Ruby"
] | 1 | Ruby | jaympatel1893/homebrew-python | e0e7a8996eac0416ee51a1ed2bd5a64906a4e7bd | d45ae0d4ba557c58bc2c20a6703e7862d20763ac | |
refs/heads/master | <repo_name>jwaataja/bcel-util<file_sep>/CHANGELOG.md
# BCEL-Util change log
## 1.1.9
- Fixed bug in stack map processing
- Prefer new method `binaryNameToType` to `classnameToType`
## 1.1.8
- Add new static field `BcelUtil.javaVersion`
## 1.1.7
- Prefer new method `fqBinaryNameToType` to `classnameToType`
## 1.1.5
- Reduce dependencies
## 1.1.4
- Use reflection-util package instead of signature-util
- Reduce size of diffs against Apache BCEL
## 1.1.0
- Deprecate JvmUtil class; use Signature class instead
- Improve efficiency of string operations
## 1.0.0
- Require Java 8
- Improve code that processes uninitialized new instructions
<file_sep>/githooks/pre-commit
#!/bin/sh
# Verify all .java files compile prior to checkin.
./gradlew compileAll
## Enable when google-java-format handles type annotations better;
## see https://github.com/google/google-java-format/issues/5
# # Verify proper Java file formatting prior to checkin.
# changed_files=$(git diff --cached --name-only --diff-filter=ACM | grep '\.java$' | paste -s -d",")
# # This only works if ignoreFailures is set to false (which it is by default).
# ./gradlew verifyGJF -DverifyGoogleJavaFormat.include="$changed_files" &>/dev/null && exit 0
# echo "Some files are not formatted properly. Please run:"
# echo "./gradlew gJF -DgoogleJavaFormat.include=\"$changed_files\""
# exit 1
<file_sep>/src/main/java/org/plumelib/bcelutil/NoConstraintsVisitor.java
package org.plumelib.bcelutil;
import org.apache.bcel.generic.*;
import org.apache.bcel.verifier.structurals.Frame;
import org.apache.bcel.verifier.structurals.InstConstraintVisitor;
/**
* This class is dummy instruction constraint visitor that does no constraint checking at all. It is
* used by StackVer as a replacement for org.apache.bcel.verifier.structurals.InstConstraintVisitor.
* InstConstraintVisitor appears to be quite out of date and incorrectly fails on many valid class
* files. Hence, StackVer assumes the method is valid and is only interested in the result of the
* symbolic execution in order to capture the state of the local variables and stack at the start of
* each byte code instruction.
*/
public class NoConstraintsVisitor extends InstConstraintVisitor {
/** The constructor. Constructs a new instance of this class. */
public NoConstraintsVisitor() {}
@Override
public void setFrame(Frame f) {}
@Override
public void setConstantPoolGen(ConstantPoolGen cpg) {}
@Override
public void setMethodGen(MethodGen mg) {}
@Override
public void visitLoadClass(LoadClass o) {}
@Override
public void visitStackConsumer(StackConsumer o) {}
@Override
public void visitStackProducer(StackProducer o) {}
@Override
public void visitCPInstruction(CPInstruction o) {}
@Override
public void visitFieldInstruction(FieldInstruction o) {}
@Override
public void visitInvokeInstruction(InvokeInstruction o) {}
@Override
public void visitStackInstruction(StackInstruction o) {}
@Override
public void visitLocalVariableInstruction(LocalVariableInstruction o) {}
@Override
public void visitLoadInstruction(LoadInstruction o) {}
@Override
public void visitStoreInstruction(StoreInstruction o) {}
@Override
public void visitReturnInstruction(ReturnInstruction o) {}
@Override
public void visitAALOAD(AALOAD o) {}
@Override
public void visitAASTORE(AASTORE o) {}
@Override
public void visitACONST_NULL(ACONST_NULL o) {}
@Override
public void visitALOAD(ALOAD o) {}
@Override
public void visitANEWARRAY(ANEWARRAY o) {}
@Override
public void visitARETURN(ARETURN o) {}
@Override
public void visitARRAYLENGTH(ARRAYLENGTH o) {}
@Override
public void visitASTORE(ASTORE o) {}
@Override
public void visitATHROW(ATHROW o) {}
@Override
public void visitBALOAD(BALOAD o) {}
@Override
public void visitBASTORE(BASTORE o) {}
@Override
public void visitBIPUSH(BIPUSH o) {}
@Override
public void visitBREAKPOINT(BREAKPOINT o) {}
@Override
public void visitCALOAD(CALOAD o) {}
@Override
public void visitCASTORE(CASTORE o) {}
@Override
public void visitCHECKCAST(CHECKCAST o) {}
@Override
public void visitD2F(D2F o) {}
@Override
public void visitD2I(D2I o) {}
@Override
public void visitD2L(D2L o) {}
@Override
public void visitDADD(DADD o) {}
@Override
public void visitDALOAD(DALOAD o) {}
@Override
public void visitDASTORE(DASTORE o) {}
@Override
public void visitDCMPG(DCMPG o) {}
@Override
public void visitDCMPL(DCMPL o) {}
@Override
public void visitDCONST(DCONST o) {}
@Override
public void visitDDIV(DDIV o) {}
@Override
public void visitDLOAD(DLOAD o) {}
@Override
public void visitDMUL(DMUL o) {}
@Override
public void visitDNEG(DNEG o) {}
@Override
public void visitDREM(DREM o) {}
@Override
public void visitDRETURN(DRETURN o) {}
@Override
public void visitDSTORE(DSTORE o) {}
@Override
public void visitDSUB(DSUB o) {}
@Override
public void visitDUP(DUP o) {}
@Override
public void visitDUP_X1(DUP_X1 o) {}
@Override
public void visitDUP_X2(DUP_X2 o) {}
@Override
public void visitDUP2(DUP2 o) {}
@Override
public void visitDUP2_X1(DUP2_X1 o) {}
@Override
public void visitDUP2_X2(DUP2_X2 o) {}
@Override
public void visitF2D(F2D o) {}
@Override
public void visitF2I(F2I o) {}
@Override
public void visitF2L(F2L o) {}
@Override
public void visitFADD(FADD o) {}
@Override
public void visitFALOAD(FALOAD o) {}
@Override
public void visitFASTORE(FASTORE o) {}
@Override
public void visitFCMPG(FCMPG o) {}
@Override
public void visitFCMPL(FCMPL o) {}
@Override
public void visitFCONST(FCONST o) {}
@Override
public void visitFDIV(FDIV o) {}
@Override
public void visitFLOAD(FLOAD o) {}
@Override
public void visitFMUL(FMUL o) {}
@Override
public void visitFNEG(FNEG o) {}
@Override
public void visitFREM(FREM o) {}
@Override
public void visitFRETURN(FRETURN o) {}
@Override
public void visitFSTORE(FSTORE o) {}
@Override
public void visitFSUB(FSUB o) {}
@Override
public void visitGETFIELD(GETFIELD o) {}
@Override
public void visitGETSTATIC(GETSTATIC o) {}
@Override
public void visitGOTO(GOTO o) {}
@Override
public void visitGOTO_W(GOTO_W o) {}
@Override
public void visitI2B(I2B o) {}
@Override
public void visitI2C(I2C o) {}
@Override
public void visitI2D(I2D o) {}
@Override
public void visitI2F(I2F o) {}
@Override
public void visitI2L(I2L o) {}
@Override
public void visitI2S(I2S o) {}
@Override
public void visitIADD(IADD o) {}
@Override
public void visitIALOAD(IALOAD o) {}
@Override
public void visitIAND(IAND o) {}
@Override
public void visitIASTORE(IASTORE o) {}
@Override
public void visitICONST(ICONST o) {}
@Override
public void visitIDIV(IDIV o) {}
@Override
public void visitIF_ACMPEQ(IF_ACMPEQ o) {}
@Override
public void visitIF_ACMPNE(IF_ACMPNE o) {}
@Override
public void visitIF_ICMPEQ(IF_ICMPEQ o) {}
@Override
public void visitIF_ICMPGE(IF_ICMPGE o) {}
@Override
public void visitIF_ICMPGT(IF_ICMPGT o) {}
@Override
public void visitIF_ICMPLE(IF_ICMPLE o) {}
@Override
public void visitIF_ICMPLT(IF_ICMPLT o) {}
@Override
public void visitIF_ICMPNE(IF_ICMPNE o) {}
@Override
public void visitIFEQ(IFEQ o) {}
@Override
public void visitIFGE(IFGE o) {}
@Override
public void visitIFGT(IFGT o) {}
@Override
public void visitIFLE(IFLE o) {}
@Override
public void visitIFLT(IFLT o) {}
@Override
public void visitIFNE(IFNE o) {}
@Override
public void visitIFNONNULL(IFNONNULL o) {}
@Override
public void visitIFNULL(IFNULL o) {}
@Override
public void visitIINC(IINC o) {}
@Override
public void visitILOAD(ILOAD o) {}
@Override
public void visitIMPDEP1(IMPDEP1 o) {}
@Override
public void visitIMPDEP2(IMPDEP2 o) {}
@Override
public void visitIMUL(IMUL o) {}
@Override
public void visitINEG(INEG o) {}
@Override
public void visitINSTANCEOF(INSTANCEOF o) {}
@Override
public void visitINVOKEDYNAMIC(INVOKEDYNAMIC o) {}
@Override
public void visitINVOKEINTERFACE(INVOKEINTERFACE o) {}
@Override
public void visitINVOKESPECIAL(INVOKESPECIAL o) {}
@Override
public void visitINVOKESTATIC(INVOKESTATIC o) {}
@Override
public void visitINVOKEVIRTUAL(INVOKEVIRTUAL o) {}
@Override
public void visitIOR(IOR o) {}
@Override
public void visitIREM(IREM o) {}
@Override
public void visitIRETURN(IRETURN o) {}
@Override
public void visitISHL(ISHL o) {}
@Override
public void visitISHR(ISHR o) {}
@Override
public void visitISTORE(ISTORE o) {}
@Override
public void visitISUB(ISUB o) {}
@Override
public void visitIUSHR(IUSHR o) {}
@Override
public void visitIXOR(IXOR o) {}
@Override
public void visitJSR(JSR o) {}
@Override
public void visitJSR_W(JSR_W o) {}
@Override
public void visitL2D(L2D o) {}
@Override
public void visitL2F(L2F o) {}
@Override
public void visitL2I(L2I o) {}
@Override
public void visitLADD(LADD o) {}
@Override
public void visitLALOAD(LALOAD o) {}
@Override
public void visitLAND(LAND o) {}
@Override
public void visitLASTORE(LASTORE o) {}
@Override
public void visitLCMP(LCMP o) {}
@Override
public void visitLCONST(LCONST o) {}
@Override
public void visitLDC(LDC o) {}
@Override
public void visitLDC_W(LDC_W o) {}
@Override
public void visitLDC2_W(LDC2_W o) {}
@Override
public void visitLDIV(LDIV o) {}
@Override
public void visitLLOAD(LLOAD o) {}
@Override
public void visitLMUL(LMUL o) {}
@Override
public void visitLNEG(LNEG o) {}
@Override
public void visitLOOKUPSWITCH(LOOKUPSWITCH o) {}
@Override
public void visitLOR(LOR o) {}
@Override
public void visitLREM(LREM o) {}
@Override
public void visitLRETURN(LRETURN o) {}
@Override
public void visitLSHL(LSHL o) {}
@Override
public void visitLSHR(LSHR o) {}
@Override
public void visitLSTORE(LSTORE o) {}
@Override
public void visitLSUB(LSUB o) {}
@Override
public void visitLUSHR(LUSHR o) {}
@Override
public void visitLXOR(LXOR o) {}
@Override
public void visitMONITORENTER(MONITORENTER o) {}
@Override
public void visitMONITOREXIT(MONITOREXIT o) {}
@Override
public void visitMULTIANEWARRAY(MULTIANEWARRAY o) {}
@Override
public void visitNEW(NEW o) {}
@Override
public void visitNEWARRAY(NEWARRAY o) {}
@Override
public void visitNOP(NOP o) {}
@Override
public void visitPOP(POP o) {}
@Override
public void visitPOP2(POP2 o) {}
@Override
public void visitPUTFIELD(PUTFIELD o) {}
@Override
public void visitPUTSTATIC(PUTSTATIC o) {}
@Override
public void visitRET(RET o) {}
@Override
public void visitRETURN(RETURN o) {}
@Override
public void visitSALOAD(SALOAD o) {}
@Override
public void visitSASTORE(SASTORE o) {}
@Override
public void visitSIPUSH(SIPUSH o) {}
@Override
public void visitSWAP(SWAP o) {}
@Override
public void visitTABLESWITCH(TABLESWITCH o) {}
}
| 70120c053b43f98c48a1b472ad8cc8fdce5ee96b | [
"Markdown",
"Java",
"Shell"
] | 3 | Markdown | jwaataja/bcel-util | 8c0479fb53bf459651badc38eb1c9cf158bb95fd | 1488c0e46ca97a3b4a4ef310aa468beac77b3c13 | |
refs/heads/master | <file_sep>using Microsoft.EntityFrameworkCore;
namespace AdminBlog.Models
{
public class BlogContext:DbContext
{
public BlogContext(DbContextOptions<BlogContext> options) : base(options)
{
}
public DbSet<Author> Authors { set; get; }
public DbSet<Category> Categories { set; get; }
public DbSet<Blog> Blogs { set; get; }
}
} | b3da6c2bafb3f7eec2cb353fde5bd57e38b172d0 | [
"C#"
] | 1 | C# | FYvgunes/AdminBlog | 1d3d6509d05f9f4f2f5e735d9c83cba74a939081 | 4260deaf2c7c8dabcafd7622d36971e78c89c5f9 | |
refs/heads/master | <file_sep># mean-crud
MEAN, Node, Angular7, table, reactiveForms
<file_sep>module.exports = {
db: 'mongodb://link:qwe123@ds<EMAIL>.ml<EMAIL>:11425/fullstack-blog'
};
| 104c4eecf6f11b44df8ebc602a27191c00076c8b | [
"Markdown",
"JavaScript"
] | 2 | Markdown | MatviyO/mean-crud | 918064261665c440ac8541c97a4252b2a372f9bd | 32c6bc853a622ae7a081f1ab4245c3e2197a9210 | |
refs/heads/master | <file_sep>package com.example.upload;
import java.io.File;
import com.example.upload.clip.PhotoClipperActivity;
import com.example.upload.imageloader.ImageLoaderHelper;
import com.example.upload.utils.FileUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnClickListener{
PopupWindow mPop;
/**拍照***/
public final static int REQUEST_TAKE_PHOTO = 101;
/**从相册选择照片***/
public final static int REQUEST_SELECT_PICTURE = 100;
/**裁剪页面 的请求嘛**/
public static final int REQUEST_CLIPPER = 1;
protected static Uri mPhotoUri;//拍照图片路径
private ImageView iv_icon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.iv_icon).setOnClickListener(this);
iv_icon = (ImageView) findViewById(R.id.iv_icon);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_icon:
View view = View.inflate(MainActivity.this, R.layout.selectpicture, null);
mPop = new PopupWindow(view, LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT, true);
mPop.setOutsideTouchable(true);
mPop.setFocusable(true);
mPop.setBackgroundDrawable(new ColorDrawable(0));
mPop.setAnimationStyle(R.style.anim_popupwindows);
mPop.showAtLocation(view.findViewById(R.id.layout_root),Gravity.CENTER, 0, 0);
view.findViewById(R.id.tv_take_photo).setOnClickListener(this);;
view.findViewById(R.id.tv_select_photo).setOnClickListener(this);;
view.findViewById(R.id.txt_cancel).setOnClickListener(this);;
view.findViewById(R.id.outArea).setOnClickListener(this);
break;
case R.id.tv_take_photo:
//点击相机走这里
mPhotoUri = Uri.fromFile(new File(FileUtils.createFile(this, FileUtils.FILE_TYPE_IMAGE)));
// 相机 获取图片 mPhotoUri : file:///storage/emulated/0/shishi/image/1460974445049.jpg
switchToCapturePhoto(mPhotoUri,REQUEST_TAKE_PHOTO);
break;
case R.id.tv_select_photo:
switchToPickPhoto(REQUEST_SELECT_PICTURE);
break;
case R.id.txt_cancel:
mPop.dismiss();
break;
case R.id.outArea:
mPop.dismiss();
break;
}
}
/**
* 手机相册选择图片
*
* @param activity
* @param requestCode
* @author zkx
*/
private void switchToPickPhoto(int requestCode) {
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, requestCode);
}
/**
* 相机获取图片
* @param activity
* @param uri
* @param requestCode
*/
private void switchToCapturePhoto(Uri uri,int requestCode) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, requestCode);
}
@Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
if (arg1 != RESULT_OK) {
return;
}
//根据requestcode判断是拍照 返回 的 还是 从相册选择返回的
switch (arg0) {
case REQUEST_TAKE_PHOTO://拍照获取图片
if (mPhotoUri != null) {
String fileDir = mPhotoUri.getPath();
Log.e("fileDir_photo", fileDir);
switchToClip(fileDir);
}
break;
case REQUEST_SELECT_PICTURE://从相册选择图片
if (arg2 != null) {
Uri uri = FileUtils.getPickPhotoUri(this, arg2); // 转uri格式
String fileDir = uri.getPath();//
Log.e("fileDir_picture", fileDir);
switchToClip(fileDir);
}
break;
case REQUEST_CLIPPER://裁剪页面
String filePath = arg2.getStringExtra("filePath"); ///点击保存后走这里
Toast.makeText(getApplicationContext(),filePath, 0).show();
if (filePath != null && filePath.length() > 0) {
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(getApplicationContext()));
ImageLoaderHelper.displayImage(iv_icon, filePath);
}
break;
default:
break;
}
}
/**
* 跳转到裁剪页面
* @param filePath
*/
public void switchToClip(String filePath){ // 第三步
//跳转到系统裁剪界面
/*Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, REQUEST_CLIPPER);*/
//跳转到自定义的裁剪界面
Intent intent=new Intent(this, PhotoClipperActivity.class);
intent.putExtra("filePath", filePath);
startActivityForResult(intent, REQUEST_CLIPPER);
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
mPop.dismiss();
}
}
<file_sep>package com.example.upload.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import com.example.upload.app.UploadApplication;
import com.example.upload.constance.Constants;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
/**
* 文件操作工具类
* @author oceangray
*
*/
@SuppressLint("NewApi")
public class FileUtils {
/**根目录**/
public static final String ROOT="/shishi";
/**日志文件目录**/
public static final String LOG="/log";
/**图片文件目录**/
public static final String IMAGE="/image";
/**更新APK存放的目录**/
public static final String UPDATE_APK="/apks";
/**音频文件目录**/
public static final String AUDIO="/audio";
/**视频文件目录**/
public static final String VIDEO="/video";
/**临时文件目录**/
public static final String TEMP="/temp";
/**文档目录**/
public static final String WORD="/word";
/**日志格式**/
public static final byte FILE_TYPE_LOG=0X00;
/**图片格式**/
public static final byte FILE_TYPE_IMAGE=0X01;
/**音频格式**/
public static final byte FILE_TYPE_AUDIO=0X02;
/**视频格式**/
public static final byte FILE_TYPE_VIDEO=0X09;
/**临时文件**/
public static final byte FILE_TYPE_TEMP=0X03;
/**WORD文件**/
public static final byte FILE_TYPE_WORD=0X04;
/**TXT文件**/
public static final byte FILE_TYPE_TXT=0X05;
/**PDF文件**/
public static final byte FILE_TYPE_PDF=0X06;
/**EXCEL文件**/
public static final byte FILE_TYPE_EXCEL=0X07;
/**PPT文件**/
public static final byte FILE_TYPE_PPT=0X08;
/**文件压缩最大质量**/
public static final int FILE_MAX_QUALITY=100;
/**文件压缩最小质量**/
public static final int FILE_MIN_QUALITY=0;
/**
* 是否关注SD卡
*
* @return true 是 ; false: 否
*/
public static boolean hasMountSDCard(){
String state=Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state) || !Environment.isExternalStorageRemovable()){
return true;
}
return false;
}
/**
* 获取文件存放的根目录
* @param context
* @return
*/
public static String getRootDir(Context context){
if(hasMountSDCard()){
return Environment.getExternalStorageDirectory().getAbsolutePath()+ROOT;
} else {
return context.getFilesDir().getAbsolutePath()+ROOT;
}
}
/**
* 获取日志存放地址
* @param context
* @return
*/
public static String getLogDir(Context context){
return getDir(context, LOG);
}
/**
* 获取图片地址
* @param context
* @return
*/
public static String getImageDir(Context context){
return getDir(context, IMAGE);
}
/**
* apk 存放地址
* @param context
* @return
*/
public static String getApksDir(Context context){
return getDir(context, UPDATE_APK);
}
/**
* 录音文件地址
* @param context
* @return
*/
public static String getAudioDir(Context context){
return getDir(context, AUDIO);
}
/**
* 文档地址
* @param context
* @return
*/
public static String getWordDir(Context context){
return getDir(context, WORD);
}
/**
* 临时文件地址
* @param context
* @return
*/
public static String getTempDir(Context context){
return getDir(context, TEMP);
}
/**
* 获取指定文件类型的存放地址
* @param context
* @param dir
* @return
*/
public static String getDir(Context context ,String dir){
String destDir=getRootDir(context)+dir+File.separator;
createDirectory(destDir);
return destDir;
}
/**
* 创建文件夹
* @param fileDir
* @return true :文件夹创建成功;false:文件夹创建失败
*/
public static boolean createDirectory(String fileDir){
if(fileDir == null){
return false;
}
File file=new File(fileDir);
if(file.exists()){
return true;
}
return file.mkdirs();
}
/**
* 创建文件
* @param context
* @param fileType 文件类型 {@code FILE_TYPE_AUDIO,FILE_TYPE_LOG,FILE_TYPE_IMAGE,FILE_TYPE_TEMP }
* @return 根据当前时间
*/
public static String createFile(Context context, int fileType){
final String fileName;
switch(fileType){
case FILE_TYPE_LOG:
fileName=getLogDir(context)+System.currentTimeMillis()+FileTypes.FILE_MIME_LOG;
break;
case FILE_TYPE_AUDIO:
fileName=getAudioDir(context)+System.currentTimeMillis()+FileTypes.FILE_MIME_AUDIO;
break;
//图片位置, + 当前时间+ /** 图片类型 **/FILE_MIME_IMAGE = ".jpg";
case FILE_TYPE_IMAGE: //getImageDir 进行了封装 , 创建文件夹, 指定存放位置;
fileName=getImageDir(context)+System.currentTimeMillis()+FileTypes.FILE_MIME_IMAGE;
break;
case FILE_TYPE_TEMP:
fileName=getTempDir(context)+System.currentTimeMillis()+FileTypes.FILE_MIME_TEMP;
break;
case FILE_TYPE_WORD:
fileName=getTempDir(context)+System.currentTimeMillis()+FileTypes.FILE_MIME_WORD;
break;
case FILE_TYPE_TXT:
fileName=getTempDir(context)+System.currentTimeMillis()+FileTypes.FILE_MIME_TXT;
break;
case FILE_TYPE_PDF:
fileName=getTempDir(context)+System.currentTimeMillis()+FileTypes.FILE_MIME_PDF;
break;
case FILE_TYPE_EXCEL:
fileName=getTempDir(context)+System.currentTimeMillis()+FileTypes.FILE_MIME_EXCEL;
break;
case FILE_TYPE_PPT:
fileName=getTempDir(context)+System.currentTimeMillis()+FileTypes.FILE_MIME_PPT;
break;
case FILE_TYPE_VIDEO:
fileName=getTempDir(context)+System.currentTimeMillis()+FileTypes.FILE_MIME_MP4;
break;
default:
throw new IllegalArgumentException("不合法的文件类型参数:"+fileType);
}
return fileName;
}
/**
* 清理文件
* @param context
*/
public static void clear(Context context){
deleteDirectory(getRootDir(context));
}
/**
* 删除文件
* @param fileDir
*/
public static boolean deleteDirectory(String fileDir){
if(fileDir==null){
return false;
}
File file=new File(fileDir);
if(file ==null || !file.exists()){
return false;
}
if(file.isDirectory()){
File[] files=file.listFiles();
for(int i=0; i<files.length;i++){
if(files[i].isDirectory()){
deleteDirectory(files[i].getAbsolutePath());
}else{
files[i].delete();
}
}
}
file.delete();
return true;
}
/**
* 获取文件名称
* @param fileName
* @return
*/
public static String getSimpleName(String fileName){
final int index=fileName.lastIndexOf("/");
if(index ==-1){
return fileName;
}else{
return fileName.substring(index+1);
}
}
/**
* 把图片数据写入到磁盘,并返回文件路径
* @param bitmap
* @param context
* @return
* @throws FileNotFoundException
*/
public static String writeBitmap(Bitmap bitmap,Context context) throws FileNotFoundException{
String filePath=createFile(context, FILE_TYPE_IMAGE);
FileOutputStream fos=null;
fos=new FileOutputStream(new File(filePath));
bitmap.compress(Bitmap.CompressFormat.JPEG, FILE_MAX_QUALITY, fos);
return filePath;
}
/**
* 通过url获取文件的位置
*
* @param context
* @param url
* @return
*/
public static String getPathFromUrl(Context context, String url, int fileType) {
String fileName;
File file =new File(url);
if (!file.exists()) {
switch (fileType) {
case FILE_TYPE_AUDIO: {
fileName = getAudioDir(context) + FileUtils.hashKeyForDisk(url)+ FileProperties.FILE_MIME_AUDIO;
break;
}
case FILE_TYPE_LOG: {
fileName = getLogDir(context) + FileUtils.hashKeyForDisk(url)+ FileProperties.FILE_MIME_LOG;
break;
}
case FILE_TYPE_IMAGE: {
fileName = getImageDir(context) + FileUtils.hashKeyForDisk(url)+ FileProperties.FILE_MIME_IMAGE;
break;
}
case FILE_TYPE_TEMP: {
fileName = getImageDir(context) + FileUtils.hashKeyForDisk(url)+ FileProperties.FILE_MIME_TEMP;
break;
}
case FILE_TYPE_WORD:
fileName = getWordDir(context) + FileUtils.hashKeyForDisk(url)+ FileProperties.FILE_MIME_WORD;
break;
case FILE_TYPE_TXT:
fileName = getWordDir(context) + FileUtils.hashKeyForDisk(url)+ FileProperties.FILE_MIME_TXT;
break;
case FILE_TYPE_PDF:
fileName = getWordDir(context) + FileUtils.hashKeyForDisk(url)+ FileProperties.FILE_MIME_PDF;
break;
case FILE_TYPE_EXCEL:
fileName = getWordDir(context) + FileUtils.hashKeyForDisk(url)+ FileProperties.FILE_MIME_EXCEL;
break;
case FILE_TYPE_PPT:
fileName = getWordDir(context) + FileUtils.hashKeyForDisk(url)+ FileProperties.FILE_MIME_PPT;
break;
case FILE_TYPE_VIDEO:
fileName = getWordDir(context) + FileUtils.hashKeyForDisk(url)+ FileProperties.FILE_MIME_MP4;
break;
default: {
throw new IllegalArgumentException("Unsupported file type: "
+ fileType);
}
}
}else{
fileName = url;
}
return fileName;
}
/**
* 生成缓存key
*
* @param key
* @return
*/
public static String hashKeyForDisk(String key) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(key.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
/**
* 字节数组转换成字符串
*
* @param bytes
* @return
*/
public static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
/**
* 字符数组转换成文件
*
* @param bytes
* 二进制数组
* @param file
* 文件
* @return
* @throws IOException
*/
public static File bytesToFile(byte[] bytes, File file) throws IOException {
String tempStr = FileUtils.createFile(UploadApplication.getApplication(), FileUtils.FILE_TYPE_TEMP);
File tempFile = new File(tempStr);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(bytes, 0, bytes.length);
fos.flush();
fos.close();
tempFile.renameTo(file);
return file;
}
/**
* 是否为相同文件(只是比较另一个文件大小)
*
* @param file
* 文件名
* @param size
* 另一个文件大小
* @return
*/
public static boolean isSameFile(File file, long size) {
boolean isSameFile = false;
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(file);
long tmpSize = fis.available();// 读取文件长度
if (tmpSize == size) {
isSameFile = true;
} else {
file.delete();
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return isSameFile;
}
/**
* 获取选择图片路径
*
* @param m_activity
* @param data
* @return
*/
public static Uri getPickPhotoUri(Activity context, Intent data) {
Uri uri = data.getData();
String filePath = getPath(context, uri);
//BitmapUtils.compressBitmap(filePath, context);
return Uri.fromFile(new File(filePath)); //文件的Example: "file:///tmp/android.txt" uri
}
/**
* 获取图片路径
*
* @param context
* @param uri
* @return
*/
@SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {
// Build.VERSION_CODES.KITKAT
final boolean isKitKat = Build.VERSION.SDK_INT >= 19;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/"
+ split[1];
}
}// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] { split[1] };
return getDataColumn(context, contentUri, selection,
selectionArgs);
}
}// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri)) {
return uri.getLastPathSegment();
}
return getDataColumn(context, uri, null, null);
}// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* 是否为externalstorage.documents
*
* @param uri
* @return
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* 获取图片路径
*
* @param context
* @param uri
* @param selection
* 查询参数
* @param selectionArgs
* 查询条件
* @return 图片路径
*/
public static String getDataColumn(Context context, Uri uri,
String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = MediaStore.Images.Media.DATA;
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection,selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}
/**
* 是否为downloads.documents
*
* @param uri
* @return
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
}
/**
* 是否为MediaDocument
*
* @param uri
* @return
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri
.getAuthority());
}
/**
* 是否为google photo
*
* @param uri
* @return
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri
.getAuthority());
}
/**
* 获取文件类型
* @return
*/
public static String getFileType(File file){
String result=null;
String fileName=file.getName();
if(fileName.lastIndexOf(".")!=-1){
result=fileName.substring(fileName.lastIndexOf(".")+1);
if(result==null){
result=Constants.FileType.other;
return result;
}
if("txt".equals(result.toLowerCase())){
result=Constants.FileType.txt;
}else if("doc".equals(result.toLowerCase())||"docx".equals(result.toLowerCase())){
result=Constants.FileType.word;
}else if("pdf".equals(result.toLowerCase())){
result=Constants.FileType.pdf;
}else if("xlsx".equals(result.toLowerCase())){
result=Constants.FileType.excle;
}else if("rar".equals(result.toLowerCase())||"zip".equals(result.toLowerCase())){
result=Constants.FileType.rar_or_zip;
}else if("xls".equals(result.toLowerCase())||"xlsx".equals(result.toLowerCase())){
result=Constants.FileType.excel;
}else if("ppt".equals(result.toLowerCase())){
result=Constants.FileType.ppt;
}else if("pdf".equals(result.toLowerCase())){
result=Constants.FileType.pdf;
}else if("png".equals(result.toLowerCase())||"gif".equals(result.toLowerCase())||"jpg".equals(result.toLowerCase())){
result=Constants.FileType.image;
}else {
result=Constants.FileType.other;
}
}else{
result=Constants.FileType.other;
}
return result;
}
/**
* 获取文件名称
* @return
*/
public static String getFileName(String filePath){
if(TextUtils.isEmpty(filePath)){
return null;
}
File file=new File(filePath);
return file.getName();
}
/**
* 获取文件类型
* @return
*/
public static String getFileType(String fileName){
String result=null;
if(TextUtils.isEmpty(fileName)){
return null;
}
if(fileName.lastIndexOf(".")!=-1){
result=fileName.substring(fileName.lastIndexOf(".")+1);
if(result==null){
result=Constants.FileType.other;
return result;
}
if("txt".equals(result.toLowerCase())){
result=Constants.FileType.txt;
}else if("doc".equals(result.toLowerCase())||"docx".equals(result.toLowerCase())){
result=Constants.FileType.word;
}else if("pdf".equals(result.toLowerCase())){
result=Constants.FileType.pdf;
}else if("xlsx".equals(result.toLowerCase())){
result=Constants.FileType.excle;
}else if("rar".equals(result.toLowerCase())||"zip".equals(result.toLowerCase())){
result=Constants.FileType.rar_or_zip;
}else if("xls".equals(result.toLowerCase())||"xlsx".equals(result.toLowerCase())){
result=Constants.FileType.excel;
}else if("ppt".equals(result.toLowerCase())){
result=Constants.FileType.ppt;
}else if("pdf".equals(result.toLowerCase())){
result=Constants.FileType.pdf;
}else if("png".equals(result.toLowerCase())||"gif".equals(result.toLowerCase())||"jpg".equals(result.toLowerCase())){
result=Constants.FileType.image;
}else {
result=Constants.FileType.other;
}
}else{
result=Constants.FileType.other;
}
return result;
}
/**
* 获取文件大小
* @param file
* @return
*/
public static String getFileSize(File file){
String result="";
if(file.exists()&&file.isFile()){
double length=file.length();
double klength=length/1024d;
DecimalFormat df = new DecimalFormat("######0.00");
if(klength<1024){
result=df.format(klength)+"k";
}else{
double mlength=klength/1024d;
if(mlength<1024){
result=df.format(mlength)+"M";
}else{
double glength=mlength/1024d;
result=df.format(glength)+"G";
}
}
}
return result;
}
/**
* 获取视频第一贞的图片
* @param videoPath
* @param context
* @return
*/
public static String getVideoImageOfFirstFrame(String videoPath,Context context) {
MediaMetadataRetriever media = new MediaMetadataRetriever();
media.setDataSource(videoPath);
try {
return writeBitmap(media.getFrameAtTime(), context);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
<file_sep>package com.example.upload.imageloader;
import java.io.File;
import java.io.IOException;
import com.example.upload.R;
import com.example.upload.app.UploadApplication;
import com.example.upload.utils.BitmapUtils;
import com.example.upload.utils.FileUtils;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.DisplayImageOptions.Builder;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.core.download.ImageDownloader.Scheme;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.utils.StorageUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.widget.ImageView;
/**
*
* imageloader 配置
* <p>:所有图片加载都通过这个类,包括网络图片和本地图片
* @author oceangray
*
*/
public class ImageLoaderHelper {
//图片缓存地址
private static String imageCacheDir=FileUtils.getRootDir(UploadApplication.getApplication())+"/image/";// 缓存的目录地址
public static void initImageLoader(Context context){
//显示图片配置项目,包括缓存、图片为空显示图片、加载失败显示图片等
DisplayImageOptions options=new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisk(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.displayer(new FadeInBitmapDisplayer(500)).build();
File cacheDir = StorageUtils.getOwnCacheDirectory(context, imageCacheDir);// 获取到缓存的目录地址
//初始化配置文件
ImageLoaderConfiguration config=new ImageLoaderConfiguration.Builder(context)
.defaultDisplayImageOptions(options)
.threadPriority(Thread.NORM_PRIORITY)//线程优先级
.denyCacheImageMultipleSizesInMemory()// 当同一个Uri获取不同大小的图片,缓存到内存时,只缓存一个。默认会缓存多个不同的大小的相同图片
.diskCacheFileNameGenerator(new Md5FileNameGenerator())//文件名字为 MD5值
.diskCacheSize(10 * 1024 * 1024)//100MB
.memoryCacheSize(2 * 1024 * 1024)//2MB
.memoryCache(new WeakMemoryCache())
.diskCache(new UnlimitedDiscCache(cacheDir))// 自定义缓存路径
.imageDownloader(new BaseImageDownloader(context, 5 * 1000, 30 * 1000))//连接5秒,读取30秒
.tasksProcessingOrder(QueueProcessingType.LIFO)
.writeDebugLogs()//开始时候用,生产环境需要取消
.build();
//初始化ImageLoader
ImageLoader.getInstance().init(config);
}
//当图片显示不了,默认显示用户默认头像 ,配置 Options
static DisplayImageOptions defaultUserHeaderoptions=new DisplayImageOptions.Builder().
cacheInMemory(true).cacheOnDisk(true).showImageOnFail(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.ic_launcher)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
//当图片显示不了,默认显示用户默认头像 ,配置 Options
static DisplayImageOptions defaultCompanyHeaderoptions=new DisplayImageOptions.Builder().
cacheInMemory(true).cacheOnDisk(true).showImageOnFail(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.ic_launcher)
.bitmapConfig(Bitmap.Config.RGB_565).build();
/**
*
* 加载网络头像图片
*
* @param imageView
* @param URL
*/
public static void displayNetHeaderImage(ImageView imageView, String url) {
displayNetImage(imageView, url, defaultUserHeaderoptions);
}
/**
*
* 加载企业网络头像图片
*
* @param imageView
* @param URL
*/
public static void displayNetCompanyHeaderImage(ImageView imageView, String url) {
displayNetImage(imageView, url, defaultCompanyHeaderoptions);
}
/**
*
* 加载群组网络头像图片
*
* @param imageView
* @param URL
*/
public static void displayNetGroupHeaderImage(ImageView imageView, String url) {
displayNetImage(imageView, url, defaultCompanyHeaderoptions);
}
/**
* 加载网络图片
*
* @param imageView
* @param URL
*/
private static void displayNetImage(ImageView imageView, String url) {
ImageLoader.getInstance().displayImage(url, imageView);
}
/**
* 加载网络图片
* 并自定义显示图片的项目:图片为空的时候显示、图片加载的时候显示
* @param imageView
* @param URL
*/
private static void displayNetImage(ImageView imageView, String url,DisplayImageOptions options) {
ImageLoader.getInstance().displayImage(url, imageView, options);
}
/**
* 加载网络图片
* 并自定义显示图片的项目:图片为空的时候显示、图片加载的时候显示,并监听图片加载的过程
* @param imageView
* @param URL
*/
private static void displayNetImage(ImageView imageView, String url,DisplayImageOptions options,
ImageLoadingListener listener) {
ImageLoader.getInstance().displayImage(url, imageView, options, listener);
}
/**
* 加载网络图片
* 并自定义显示图片的项目:图片为空的时候显示、图片加载的时候显示,并监听图片加载的过程和图片加载的进度
* @param imageView
* @param URL
*/
private static void displayNetImage(ImageView imageView, String url,DisplayImageOptions options,
ImageLoadingListener listener, ImageLoadingProgressListener progressListener) {
ImageLoader.getInstance().displayImage(url, imageView, options, listener, progressListener);
}
/**
* 加载本地sd 卡的照片(原图)
* @param imageView
* @param imagePath
*/
private static void displayDiskImage(ImageView imageView, String imagePath) {
String imageUrl = Scheme.FILE.wrap(imagePath);
ImageLoader.getInstance().displayImage(imageUrl, imageView);//路径你要是给的本地 就是加载本地的数据, 不请求网络
}
/**
* 加载本地sd 卡的照片(缩略图)
* @param imageView
* @param imagePath
*/
private static void displayDiskImage200(ImageView imageView, String imagePath) {
imageView.setImageBitmap(BitmapUtils.getSmallBitmap(imagePath, 100, 100));
}
/**
* 显示全图
* @param imageView
* @param imagePath
*/
public static void displayImage(ImageView imageView, String imagePath){
if(TextUtils.isEmpty(imagePath)){
return ;
}
File file =new File(imagePath);
//本地图片
if(file.exists()){
displayDiskImage(imageView, imagePath);
//网络图片
}else{
displayNetImage(imageView, imagePath);
}
}
/**
* 显示缩略图
* @param imageView
* @param imagePath
*/
public static void displayImage200(ImageView imageView, String imagePath){
if(TextUtils.isEmpty(imagePath)){
return ;
}
File file =new File(imagePath);
//本地图片
if(file.exists()){
displayDiskImage200(imageView, imagePath);
//网络图片
}else{
displayNetImage(imageView,imageUrlConvert200ImageUrl(imagePath));
}
}
/**
* 把大图URL地址转换为200的缩略图地址(和服务器约定好的)
* @param destUrl
* @return
*/
public static String imageUrlConvert200ImageUrl(String destUrl){
int fileFormat = destUrl.lastIndexOf(".");
String fileUrl =destUrl + "_200."+ destUrl.substring(fileFormat + 1, destUrl.length());
return fileUrl;
}
/**
* 异步获取图片
* @param uri
* @return
*/
public static Bitmap loadImageSync(String uri){
return ImageLoader.getInstance().loadImageSync(uri);
}
/**
* 异步获取图片
* @param uri
* @return
*/
public static Bitmap loadHeaderImageSync(String uri){
return ImageLoader.getInstance().loadImageSync(uri,defaultUserHeaderoptions);
}
/**
* 缓存图片存储
* @param uri
* @return ,如果没有bitmap , 传入路径也可以;
*/
public static void storeImageToCache(String serverImageUrl,String localFileUrl){
try {
ImageLoader.getInstance().getDiskCache().save(serverImageUrl, BitmapUtils.decodeFile(new File(localFileUrl)));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 缓存图片存储
* @param uri
* @return ImageLoader中,可以通过getDiskCache().get(url)获取到磁盘缓存 , save 存储 缓存
*/
public static void storeImageToCache(String serverImageUrl,Bitmap bitmap){
try {
ImageLoader.getInstance().getDiskCache().save(serverImageUrl, bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 13de101b3708bd391d760a3791aec6c3dbcc3b69 | [
"Java"
] | 3 | Java | kinglisir/UpLoadingIcon | 0213de65a2a41dda2563f9b58b0d33db930f218b | c9ab0c992f8090e4a207294cfb2378fe1ead0272 | |
refs/heads/master | <file_sep>#include <bits/stdc++.h>
#define int long long
using namespace std;
map<pair<int, int>, string> mp;
int answer[50][40];
int decodeExpr(int x, int y, string expr) {
if(answer[x][y] != 0 )
return answer[x][y];
if (expr.empty()) {
answer[x][y] = 0;
return 0;
}
if (expr[0] != '=') {
int aux = 0;
for (char i : expr) {
aux = aux * 10 + i - '0';
}
answer[x][y] = aux;
return aux;
}
vector<int> numExpr;
numExpr.push_back(-5);
int curr = 0;
for (int i = 1; i < expr.size(); ++i) {
if (isdigit(expr[i])) {
curr = curr* 10 + expr[i]-'0';
} else {
numExpr.push_back(curr);
curr=0;
if(expr[i] == ':')
numExpr.push_back(-1);
else
numExpr.push_back(-2);
}
}
if(curr)
numExpr.push_back(curr);
// for(auto it: numExpr) {
// cerr << it << " ";
// }
// cerr <<"\n";
map<int, bool> positions;
vector<int> terms;
for (int i = 1; i < numExpr.size(); ++i) {
if (numExpr[i] == -1) {
positions[i - 1] = positions[i] = positions[i + 1] = true;
terms.push_back(decodeExpr(numExpr[i - 1] , numExpr[i + 1],
mp[{numExpr[i - 1] , numExpr[i + 1] }]));
}
}
for (int i = 1; i < numExpr.size(); ++i) {
if (!positions[i] && numExpr[i]>0)
terms.push_back(numExpr[i] );
}
int aux = 0;
for (auto it: terms) {
aux += it;
}
answer[x][y] = aux;
return aux;
}
int32_t main() {
freopen("mxl.in", "r", stdin);
freopen("mxl.out", "w", stdout);
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; ++i) {
int lin, col;
string kekxpression;
cin >> lin >> col >> kekxpression;
mp[make_pair(lin, col)] = kekxpression;
//cerr << lin<< " " <<col <<" " << kekxpression << "\n";
}
//cerr<<mp[{1,6}].size();
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
if (answer[i][j] == 0) {
decodeExpr(i, j, mp[{i, j}]);
}
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
cout << answer[i][j] << " ";
}
cout << "\n";
}
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
string expression;
unordered_map<char, int> fact;
unordered_map<long long, int> firstHalf;
int main() {
freopen("eq4.in", "r", stdin);
freopen("eq4.out", "w", stdout);
int cer;
int a, b;
long long res;
cin >> cer;
cin >> expression;
cin >> a >> b >> res;
int num = 0, sign = 1;
bool hasNumber = false;
fact['@'] = 0;
fact['x'] = 0;
fact['y'] = 0;
fact['z'] = 0;
fact['t'] = 0;
for (int i = 0; i < expression.size(); ++i) {
if (expression[i] == '+' || expression[i] == '-') {
num = 0;
hasNumber = false;
if (expression[i] == '+') {
sign = 1;
} else
sign = -1;
continue;
}
if (isdigit(expression[i])) {
num = num * 10 + sign * (expression[i] - '0');
hasNumber = true;
}
if (isalpha(expression[i])) {
if (!hasNumber)
num = sign;
fact[expression[i]] += num;
continue;
}
if (expression[i + 1] == '+' || expression[i + 1] == '-' || i == expression.size() - 1) {
if (!hasNumber)
num = sign;
fact['@'] += num;
}
}
if (cer == 1) {
long long sum = 0;
for (auto it: fact) {
sum += it.second;
}
cout << sum;
return 0;
}
int cnt = 0;
for (int valx = a; valx <= b; ++valx) {
for (int valy = a; valy <= b; ++valy) {
long long sum = 0;
sum += fact['@'];
sum += fact['x'] * valx;
sum += fact['y'] * valy;
firstHalf[sum]++;
}
}
for (int valz = a; valz <= b; ++valz) {
for (int valt = a; valt <= b; ++valt) {
long long sum = 0;
sum += fact['z'] * valz;
sum += fact['t'] * valt;
if(firstHalf.find(res-sum)!= firstHalf.end())
cnt+=firstHalf[res-sum];
}
}
cout << cnt;
return 0;
}<file_sep>#include <fstream>
#include <algorithm>
using namespace std;
char st[100005];
int top = 0;
ifstream cin("charlie.in");
ofstream cout("charlie.out");
int main() {
int reqFlag;
cin >> reqFlag;
string s;
cin >> s;
if (reqFlag == 1) {
int cnt = 1;
int ans = 0;
for (int i = 1; i < s.size() - 1; ++i) {
if (s[i] < s[i - 1] && s[i] < s[i + 1]) {
cnt += 2;
i++;
ans = max(ans, cnt);
continue;
}
cnt = 1;
ans = max(ans, cnt);
}
ans = max(ans, cnt);
cout << ans << "\n";
return 0;
}
int cost = 0;
for (char & i : s) {
while (top > 1 && st[top - 1] > st[top] && st[top] < i) {
cost += max(st[top - 1], i) - 'a' + 1;
top--;
}
st[++top] = i;
}
string printBuff;
while (top > 0) {
printBuff += st[top];
top--;
}
for (int i = printBuff.size() - 1; i >= 0; --i) {
cout << printBuff[i];
}
cout << "\n" << cost;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
int mat[1005][1005];
int ans[1005][1005];
int n,m;
bool inBounds (int x, int y) {
return (x>0 && x<=n) && (y>0 && y<=m);
}
ifstream in ("acces.in");
ofstream out ("acces.out");
int main() {
freopen("acces.in","r", stdin);
freopen("acces.out","w", stdout);
int k;
in >> n >> m;
for(int i=1;i<=n;++i) {
for(int j=1;j<=m;++j) {
in >> mat[i][j];
}
}
for(int i=1;i<=n;++i) {
for(int j=1;j<=m;++j) {
if(mat[i][j] == 1) {
ans[i][j] = min(min(ans[i][j-1], ans[i-1][j]), ans[i-1][j-1]);
continue;
}
ans[i][j] = 1;
if(mat[i-1][j]==0)
ans[i][j] += ans[i-1][j];
if(mat[i][j-1]==0)
ans[i][j] += ans[i][j-1];
if(mat[i-1][j]==0 && mat[i][j-1]==0)
ans[i][j] -= ans[i-1][j-1];
}
}
in >> k;
for(int i=1;i<=k;++i) {
int x,y;
in >> x >> y;
out << ans[x][y] << "\n";
}
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
ifstream fin ("rover.in");
ofstream fout ("rover.out");
int dx[] = {0, 1, -1, 0};
int dy[] = {1, 0, 0, -1};
int mat[505][505];
int isStable[505][505];
int score[505][505];
deque<pair<int, int> > bfsQueue;//more like bfsdeque haha I wanna kill myself
int n;
inline void makeBfsMat(int g) {
while(!bfsQueue.empty())
bfsQueue.pop_back();
bfsQueue.push_back(make_pair(1, 1));
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
score[i][j]=0;
if (mat[i][j] < g) {
isStable[i][j] = 0;
} else
isStable[i][j] = 1;
}
}
score[1][1]=1;
}
bool inBounds (pair<int, int> a) {
return a.first > 0 && a.first <=n && a.second > 0 && a.second <= n;
}
int checkBfs() {
while(!bfsQueue.empty()) {
auto top = bfsQueue.front();
bfsQueue.pop_front();
for(int i=0;i<4;++i) {
auto it = make_pair(top.first+dx[i], top.second+dy[i]);
if(score[it.first][it.second] || !inBounds(it))
continue;
score[it.first][it.second] = score[top.first][top.second] + !isStable[it.first][it.second];
if(isStable[it.first][it.second] != 1)
bfsQueue.push_back(it);
else
bfsQueue.push_front(it);
}
}
return score[n][n]-1;
}
int main() {
int cer, g;
fin >> cer >> n;
if (cer == 1) {
fin >> g;
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
fin >> mat[i][j];
}
}
if (cer == 1) {
makeBfsMat(g);
fout << checkBfs() << "\n";
return 0;
}
int st = 1, dr = 10005;
int ans=10000;
while (st <= dr) {
int mid = (st + dr) / 2;
makeBfsMat(mid);
if(checkBfs() > 0) {
dr=mid-1;
}else {
ans=mid;
st=mid+1;
}
}
fout << ans << "\n";
return 0;
} | 4a6f586ca22c3af62f8db9adc04edcc552d54322 | [
"C++"
] | 5 | C++ | alexradu04/Competitive-Programming | fc5e3017c18cf4f49e9a0b79e02980b1ee0edaa7 | afe8a794b5db0722b82b502915bd83ea2886890f | |
refs/heads/master | <file_sep>package fecasado.citius.usc.tecalischallenge;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import static android.widget.LinearLayout.VERTICAL;
public class MainActivity extends AppCompatActivity implements SensorSubscriberInterface {
private String LOGTAG = "MainActivity";
private final static short DIM = 7; // dimension of the chess board 7x7
private final static String BASE_URL = "http://www.thomas-bayer.com/sqlrest/CUSTOMER/"; // customers data
private final static short SENSOR_FREQ = 3; // take sensor data every 3 seconds
private Square[] chessBoard = new Square[DIM * DIM]; // chess board
private ArrayList<SensorData> sensorReadings; // sensor measurements
SensorDataCollector dataCollector; // sensor data reader
LocationManager locationManager; // GPS location manager
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create chess board
createLayoutDynamically();
// Start reading sensors
sensorReadings = new ArrayList<>();
dataCollector = new SensorDataCollector(this, this);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
dataCollector.registerListeners();
}
@Override
protected void onPause() {
super.onPause();
dataCollector.unregisterListeners();
}
@Override
protected void onResume() {
super.onResume();
dataCollector.registerListeners();
}
@Override
protected void onDestroy() {
super.onDestroy();
dataCollector.unregisterListeners();
}
/**
* Create chess board dinamically
*/
private void createLayoutDynamically() {
LinearLayout parentLayout = (LinearLayout) findViewById(R.id.my_linear_layout);
// Get square size based on display width
DisplayMetrics dm = new DisplayMetrics();
this.getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
int squareDim = dm.widthPixels / (DIM);
for (int i = 0; i < DIM; i++) {
// Create a new linear layout
LinearLayout ll = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
parentLayout.setOrientation(VERTICAL);
parentLayout.addView(ll, params);
for (int j = 0; j < DIM; j++) {
final int btnId = j + DIM * (i);
int color;
if ((btnId & 1) == 0) {
color = R.color.darkSquare;
} else {
color = R.color.lightSquare;
}
// Create a new square
final Square square = new Square(this, "" + btnId, color, squareDim);
ll.addView(square);
chessBoard[btnId] = square;
// Define behaviour when it is clicked
square.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!chessBoard[btnId].isActivated()) {
RetrieveXML getXML = new RetrieveXML(BASE_URL + btnId, btnId,
chessBoard[btnId], MainActivity.super.getApplicationContext());
getXML.execute();
}
}
});
}
}
}
/**
* Save data to a .txt file
*/
public void saveToTXT(View view) {
if (isStoragePermissionGranted()) {
try {
File root = new File(Environment.getExternalStorageDirectory(), "TecalisData");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, System.currentTimeMillis() + ".txt");
FileWriter writer = new FileWriter(file);
writer.write("###############\n");
writer.write("## CUSTOMERS ##\n");
writer.write("###############\n");
for (Square s : chessBoard) {
if (s.isActivated()) {
writer.write("> " + s.getCustomer().toString() + "\n\n");
}
}
writer.write("\n\n\n");
writer.write("###############\n");
writer.write("## SENSORS ##\n");
writer.write("###############\n");
writer.write("timestamp, lat, lng, gyrox, gyroy, gyroz, accx, accy, accz\n");
for (SensorData s : sensorReadings) {
Log.d("AAA", "--" + s.getTimestamp());
writer.write(s.getTimestamp() + ", "
+ s.getLat() + ", " + s.getLng() + ", "
+ s.getGyrox() + ", " + s.getGyroy() + ", " + s.getGyroz() + ", "
+ s.getAccx() + ", " + s.getAccy() + ", " + s.getAccz() + "\n");
}
writer.flush();
writer.close();
} catch (IOException e) {
Log.e(LOGTAG, "File write failed: " + e.toString());
Toast.makeText(this, "File write failed.", Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "Data has been saved!", Toast.LENGTH_SHORT).show();
}
}
/**
* Check if storage permission was granted
*/
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(LOGTAG, "Permission is granted");
return true;
} else {
Log.v(LOGTAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.v(LOGTAG, "Permission is granted");
return true;
}
}
/**
* Check if storage permission was granted
*/
public boolean isLocationPermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED &&
checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
Log.v(LOGTAG, "Permission is granted");
return true;
} else {
Log.v(LOGTAG, "Permission is revoked");
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.v(LOGTAG, "Permission is granted");
return true;
}
}
/**
* Get sensor data
*/
@Override
public void onSensorDataChanged(SensorData sensorData) {
// first reading
if (sensorReadings.isEmpty()) {
// get last known location
Location location = getLastKnownLocation();
if(location != null) {
sensorData.setLat((float)location.getLatitude());
sensorData.setLng((float)location.getLongitude());
sensorReadings.add(sensorData);
}
} else { // check if it is time to save another reading
// calculate time difference
long timeDiff = sensorData.getTimestamp() - sensorReadings.get(sensorReadings.size() - 1).getTimestamp();
// convert to seconds
timeDiff = timeDiff / 1000000000;
if (timeDiff >= SENSOR_FREQ) {
// get last known location
Location location = getLastKnownLocation();
sensorData.setLat((float)location.getLatitude());
sensorData.setLng((float)location.getLongitude());
sensorReadings.add(sensorData);
}
}
}
@SuppressLint("MissingPermission")
private Location getLastKnownLocation() {
Location networkLocation = null;
if (isLocationPermissionGranted())
networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
return networkLocation;
}
}
<file_sep>package fecasado.citius.usc.tecalischallenge;
/**
* This class represents a customer, with ID, name and address
*/
public class Customer {
private short ID;
private String firstName;
private String lastName;
private String street;
private String city;
public Customer() {
this.ID = -1;
this.firstName = "unknown";
this.lastName = "unknown";
this.street = "unknown";
this.city = "unknown";
}
public Customer(short ID, String firstName, String lastName, String street, String city) {
this.ID = ID;
this.firstName = firstName;
this.lastName = lastName;
this.street = street;
this.city = city;
}
public short getID() {
return ID;
}
public void setID(short ID) {
this.ID = ID;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
String data = this.getFirstName() + " " + this.getLastName() + ", \n"
+ this.getStreet() + ", \n"
+ this.getCity();
return data;
}
}
<file_sep>package fecasado.citius.usc.tecalischallenge;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.util.TypedValue;
/**
* This class represents a square on the chess board
*/
public class Square extends android.support.v7.widget.AppCompatButton {
private Customer customer;
public Square(Context context, String text, int color, int width) {
super(context);
this.setTextAlignment(TEXT_ALIGNMENT_CENTER);
this.setAllCaps(false);
this.setPadding(1,0,1,0);
this.setWidth(width);
this.setHeight(width);
this.setMinimumWidth(0);
this.setMinimumHeight(0);
this.setTextSize(TypedValue.COMPLEX_UNIT_SP, 7f);
this.setText("\n" + text + "\n");
this.setBackground(ContextCompat.getDrawable(context, color));
this.setPressed(false);
}
public void setCustomer(Customer c) {
this.customer = c;
this.setText(c.toString());
}
public Customer getCustomer() {
return customer;
}
}
| b81833e45365e0bd02c7e4bab9e5fdfb7d104cfc | [
"Java"
] | 3 | Java | fertevez/tecalis-challenge | 602d932ef20a7c9f7b0f7974eb64f2e41242dec9 | d525b6d8933d45f4ecaff2d8bdc7c2438d8c99b7 | |
refs/heads/master | <file_sep>#Installer file settings
#DO NOT CHANGE unless the download id's have changed
default['radiobot']['install'] = {
'debian' => {
'packages' => 'openssl sqlite3 libsqlite3-0 libmysqlclient18 libwxgtk2.8-0 libcurl3 libphysfs1 tcl8.5 libloudmouth1-0 libtag1c2a libtagc0 espeak espeak-data festival libssl1.0.0 libwxgtk2.8-0 libsqlite3-0 libmpg123-0 libogg0 libvorbis0a libvorbisfile3 libsndfile1 libavformat53 libavcodec53 libmp3lame0 libflac8 libresample1 libfaac0 libprotobuf7 libmuparser2 liblua5.1-0 libaacplus2 libsoxr0',
'downloads' => {
'6' => {
'i686' => 69,
'x86_64' => 70
},
'7' => {
'i686' => 94,
'x86_64' => 93
}
},
'override' => {
'ubuntu' => {
'packages' => 'openssl sqlite3 libwxgtk2.8-0 lame libtag1c2a libtagc0 libmp3lame0 libmp3lame-dev libogg-dev libvorbis-dev libsndfile1 libsndfile1-dev libavformat54 libavcodec54 libcurl4-openssl-dev libmpg123-0 libresample1 libncurses5 libphysfs1 libpcre3 libprotobuf8 libmysqlclient18 libfaac0 libopus0 libloudmouth1-0 libdbus-glib-1-2 libmuparser2 libsoxr0',
'downloads' => {
'13' => {
'i386' => 66,
'x86_64' => 68
},
'14' => {
'i686' => 138,
'x86_64' => 137
},
}
}
}
},
'rhel' => {
'packages' => 'openssl sqlite mysql wxGTK cryptopp taglib physfs lame curl protobuf muParser lua libogg libvorbis mpg123 libresample lame-devel libsndfile ffmpeg flac opus',
'downloads' => {
'5' => {
'i686' => 65,
'x86_64' => 67
},
'6' => {
'i686' => 71,
'x86_64' => 63
}
}
}
}
#Base settings
default['radiobot']['base']['nick'] = 'RadioBot'
default['radiobot']['base']['logfile'] = 'ircbot.log'
default['radiobot']['base']['do_spam'] = true
default['radiobot']['base']['do_on_join'] = true
default['radiobot']['base']['do_topic'] = true
default['radiobot']['base']['auto_reg_on_hello'] = true
default['radiobot']['base']['enable_request_sys'] = true
default['radiobot']['base']['enable_rating'] = true
default['radiobot']['base']['allow_pm_requests'] = true
default['radiobot']['base']['remote_port'] = 10001
default['radiobot']['base']['dj_name'] = 'Standard'
default['radiobot']['base']['ssl_cert'] = 'ircbot.pem'
default['radiobot']['base']['reg_name'] = ''
default['radiobot']['base']['reg_key'] = ''
#IRC settings
default['radiobot']['irc']['servers'] = {
'irc.host.com' => {
'port' => 6667,
'ssl' => false,
'pass' => false,
'identity_pass' => false,
'bindip' => false,
'channels' => {
'#channel' => {
'channel_pass' => false,
'do_spam' => true,
'do_on_join' => true,
'do_topic' => true,
'song_interval' => 0,
'song_interval_source' => 0,
'no_topic_check' => false
}
}
}
}
#SS settings
default['radiobot']['server_streams']['servers'] = {
'your_sc_server.com' => {
'type' => 'shoutcast',
'port' => 8000,
'stream_id' => 1,
'mount' => '/live',
'user' => 'admin',
'pass' => '<PASSWORD>'
}
}
#AutoDJ settings
default['radiobot']['autodj']['server']['password'] = '<PASSWORD>'
default['radiobot']['autodj']['server']['name'] = 'DJ Test'
default['radiobot']['autodj']['server']['description'] = 'Test Stream'
default['radiobot']['autodj']['server']['genre'] = 'Various'
default['radiobot']['autodj']['server']['url'] = 'http://www.yoururl.com'
default['radiobot']['autodj']['server']['icq'] = 11001100
default['radiobot']['autodj']['server']['aim'] = 'aim_name'
default['radiobot']['autodj']['server']['irc'] = 'irc://irc.yourirc.net/channel'
default['radiobot']['autodj']['server']['public'] = true
default['radiobot']['autodj']['server']['encoder'] = 'mp3'
default['radiobot']['autodj']['server']['bitrate'] = 64
default['radiobot']['autodj']['server']['sample'] = 44100
default['radiobot']['autodj']['server']['channels'] = 1
default['radiobot']['autodj']['server']['mount'] = '/'
default['radiobot']['autodj']['server']['music_dir'] = 'f:\my_music'
default['radiobot']['autodj']['server']['promos_dir'] = 'f:\my_promos'
default['radiobot']['autodj']['mp3_encoder']['mode'] = 'stereo'
default['radiobot']['autodj']['mp3_encoder']['vbr'] = 0
default['radiobot']['autodj']['mp3_encoder']['min_bitrate'] = 0
default['radiobot']['autodj']['mp3_encoder']['max_bitrate'] = 0
default['radiobot']['autodj']['mp3_encoder']['quality'] = 4
default['radiobot']['autodj']['mp3_encoder']['vbr_quality'] = 4
default['radiobot']['autodj']['queue_mysql']['host'] = 'host'
default['radiobot']['autodj']['queue_mysql']['user'] = 'user'
default['radiobot']['autodj']['queue_mysql']['pass'] = '<PASSWORD>'
default['radiobot']['autodj']['queue_mysql']['port'] = 0
default['radiobot']['autodj']['queue_mysql']['db_name'] = 'ShoutIRC'
default['radiobot']['autodj']['queue_mysql']['db_table'] = 'AutoDJ'
default['radiobot']['autodj']['queue_mysql']['keep_history'] = 7
default['radiobot']['autodj']['options']['use_mysql_queue'] = false
default['radiobot']['autodj']['options']['resampler'] = 'speex'
default['radiobot']['autodj']['options']['no_play_filters'] = '*SomeJunk*,*more junk*'
default['radiobot']['autodj']['options']['no_repeat'] = 600
default['radiobot']['autodj']['options']['do_promos'] = '0'
default['radiobot']['autodj']['options']['num_promos'] = 1
default['radiobot']['autodj']['options']['enable_requests'] = true
default['radiobot']['autodj']['options']['enable_find'] = true
default['radiobot']['autodj']['options']['enable_crossface'] = false
default['radiobot']['autodj']['options']['enable_voice'] = false
default['radiobot']['autodj']['options']['voice_artist'] = 'www.ShoutIRC.com'
default['radiobot']['autodj']['options']['voice_title'] = 'The Voice of AutoDJ'
default['radiobot']['autodj']['options']['moved_dir'] = './moved'
default['radiobot']['autodj']['options']['auto_start'] = true
default['radiobot']['autodj']['options']['autoplay_if_no_source'] = false
default['radiobot']['autodj']['options']['enable_yp'] = true<file_sep>ShoutIRC RadioBot Cookbook
=================
[](https://travis-ci.org/HiveMedia/radiobot) [](https://codeclimate.com/github/HiveMedia/radiobot) [](https://codeclimate.com/github/HiveMedia/radiobot)
The ShoutIRC RadioBot cookbook is designed to allow users a simple and easy to understand way of installing the ShoutIRC radiobot on their servers whiel still having full control over the settings of the radiobot
Currently this cookbook only supports the AutoDJ plugin of RadioBot
Attributes
----------
#### radiobot::default
All attributes are inline with the configuration settings of RadioBot which can be found here
http://wiki.shoutirc.com/index.php/Configuration:Base
All settings are set out as "radiobot->***section_name***->***setting_name***"
e.g.
```json
{
"default_attributes": {
"radiobot": {
"base": {
"reg_name": "YourUserNameHere-TP-********************************",
"reg_key": "****-**********",
"nick": "MyRadioBotNick"
},
},
},
}
```
Usage
-----
#### radiobot::default
Just include `radiobot` in your node's `run_list`:
```json
{
"name":"my_node",
"run_list": [
"recipe[radiobot]"
]
}
```
Contributing
------------
Want to join in on the fun and help? You can do so by doing the following,
1. Fork the repository on Github
2. Create a named feature branch (like `add_component_x`)
3. Write your change
4. Write tests for your change (if applicable)
5. Run the tests, ensuring they all pass
6. Submit a Pull Request using Github
License and Authors
-------------------
Authors: <NAME> <liam.<EMAIL>>
The license is Apache v2 which can be found in the LICENSE file
<file_sep>#
# Cookbook Name:: radiobot
# Recipe:: default
#
# Copyright 2014, ShoutIRC.com
#
#Check if this platform is supported
if node['radiobot']['install'][node['platform_family']].nil?
Chef::Log.error "A radiobot install options does not exist for '#{node['platform_family']}'. This means the radiobot cookbook does not have support for the #{node['platform_family']} family."
raise "A radiobot install options does not exist for '#{node['platform_family']}'. This means the radiobot cookbook does not have support for the #{node['platform_family']} family."
end
#Get the install options for this platform
install_options = node['radiobot']['install'][node['platform_family']]
#Check if overrides exist for distro specific install options
if node['radiobot']['install'][node['platform_family']]['override'] && node['radiobot']['install'][node['platform_family']]['override'][node['platform']]
install_options = node['radiobot']['install'][node['platform_family']]['override'][node['platform']]
end
#Check if this platform version is supported
if install_options['downloads'][node['platform_version'].split('.').first].nil?
Chef::Log.error "A radiobot install options does exist for '#{node['platform']}' but not this version of your platform, #{node['platform_version'].split('.').first}."
raise "A radiobot install options does exist for '#{node['platform']}' but not this version of your platform, #{node['platform_version'].split('.').first}."
end
#Add the repos that RHEL needs to install right
if node['platform_family'] == "rhel"
#add the EPEL repo
yum_repository 'epel' do
description 'Extra Packages for Enterprise Linux'
mirrorlist 'http://mirrors.fedoraproject.org/mirrorlist?repo=epel-6&arch=$basearch'
gpgkey 'http://dl.fedoraproject.org/pub/epel/RP<KEY>'
action :create
end
#add the RPMforge
yum_repository 'rpmforge' do
description 'RepoForge is the new RPMforge. Please excuse the dust as we move in and remodel'
mirrorlist 'http://mirrorlist.repoforge.org/el6/mirrors-rpmforge'
gpgkey 'http://apt.sw.be/RPM-GPG-KEY.dag.txt'
action :create
end
end
#Install the packages required for this platform
install_options['packages'].split.each do |pkg|
package pkg do
action :install
end
end
#Add the RadioBot user
user "radiobot" do
supports :manage_home => true
comment "ShoutIRC RadioBot user"
gid "users"
home "/opt/radiobot"
shell "/bin/bash"
end
curl_download_id = install_options['downloads'][node['platform_version'].split('.').first][node['kernel']['machine']]
#Download RadioBot for this platform
bash "install_radiobot" do
user "root"
cwd "/opt"
code <<-EOH
mkdir -p radiobot
cd radiobot
wget -O radiobot.tar.gz "https://www.shoutirc.com/index.php?mod=Downloads&action=download&id=#{curl_download_id}"
tar -xsvf radiobot.tar.gz
rm radiobot.tar.gz
chown radiobot ./ -R
EOH
end unless File.exist?('/opt/radiobot/radiobot')
#Insert RadioBots config file based on user settings
template "/opt/radiobot/ircbot.conf" do
source "ircbot.conf.erb"
owner "radiobot"
mode 0644
end
#TODO: Add support for IRCBot.text
#Install the RadioBot plugins so the AutoDJ can work
bash "install_radiobot" do
user "radiobot"
cwd "/opt/radiobot"
code "./updater -a"
end
#Places the service init.d script into the platform
cookbook_file "radiobot_service" do
path "/etc/init.d/radiobot"
action :create_if_missing
source "radiobot.init"
group "root"
owner "root"
mode 0777
end
# Enable and start the RadioBot service
service "radiobot" do
action [:enable, :start]
end<file_sep>radiobot CHANGELOG
==================
This file is used to list changes made in each version of the radiobot cookbook.
0.1.0
-----
- [<NAME>] - Initial release of the radiobot cookbook
<file_sep>name 'radiobot'
maintainer '<NAME>'
maintainer_email '<EMAIL>'
license 'ApacheV2'
description 'Installs/Configures radiobot'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.0'
| 664a595a751e59d371c4d9e47685c0cf49c3063a | [
"Markdown",
"Ruby"
] | 5 | Ruby | LiamHaworth/radiobot-cookbook | 1f4f8dba1c5296aa309f2e7d5434f44b6f29f9d1 | 7bc5a03a02fb7064da9e0d7a05022afe47c9e04e | |
refs/heads/main | <file_sep>import React from 'react';
import styled from 'styled-components';
import headerBG from '../../svg/headerBG.svg';
import logo from '../../svg/logo_dark.svg';
// import logospin from './logospin.svg';
import {Link} from 'react-router-dom';
import './hamburger.css';
const NavbarStructure = ({ className }) => {
const menuToggle = () => {
document.getElementById("menu").classList.toggle("is-active");
document.getElementById("navbarUL").classList.toggle("hammenu");
}
return (
<div className={className}>
<div className="headerBG" ></div>
<img className="logo" src={logo} alt="logo" />
<button onClick={menuToggle} id="menu" className="hamburger hamburger--elastic" type="button">
<span className="hamburger-box">
<span className="hamburger-inner"></span>
</span>
</button>
<ul id="navbarUL">
<li className="navbarLI">
<Link to="/">home</Link>
</li>
<li className="navbarLI">
<Link to="/science">science</Link>
</li>
<li className="navbarLI">
<Link to="/entertainment">entertainment</Link>
</li>
<li className="navbarLI">
<Link to="/tech">tech</Link>
</li>
<li className="navbarLI">
<Link to="/health">health</Link>
</li>
</ul>
</div>
)
}
const Navbar = styled(NavbarStructure)`
position: relative;
width: 100%;
height: 100px;
.headerBG {
width: 100%;
height: 22vh;
background-image: url(${headerBG});
background-repeat: no-repeat;
}
.logo {
position: absolute;
top: 3vh;
left: 16vh;
max-width: 14%;
}
.hamburger {
display: none;
position: absolute;
right: 3vh;
top: 3vh;
}
#navbarUL {
position: absolute;
top: 0;
right: 35vh;
width: 100%;
min-height: 100%;
padding: 0;
margin: 0;
list-style: none;
display: flex;
justify-content: space-evenly;
align-items: center;
.navbarLI:first-child {
margin-left: 50%;
}
.navbarLI {
a {
position: relative;
padding: 5px;
text-decoration: none;
color: #4cc9f0;
font-family: $sen;
letter-spacing: 0.2em;
font-size: 1.2em;
/* border-bottom: 3px solid transparent; */
transition: color 0.5s, border-bottom 0.5s;
&::after {
content: "";
position: absolute;
bottom: 0;
left: 0;
height: 2px;
width: 100%;
background-color: currentColor;
transform: scaleX(0);
transition: transform 0.3s;
}
}
&:hover,
&:focus {
a {
color: #f72585;
/* border-bottom: 3px solid #f72585; */
&::after {
transform: scaleX(1);
}
}
}
}
&.hammenu {
display: flex;
max-width: 50%;
min-height: 100vh;
right: 0;
background: linear-gradient(90deg, rgba(41, 2, 98, 0) 0%, rgba(41, 2, 98, 0.99006) 56.04%, #290262 65.94%);
flex-direction: column;
justify-content: flex-start;
align-items: flex-end;
gap: 1vh;
padding: 10vh 2vh 0 0;
z-index: 20;
.navbarLI:first-child {
margin: 0;
}
}
}
// GALAXY FOLD
@media screen and (min-width: 280px) and (max-width: 280px) and (max-height: 654px) and (max-height: 654px) {
height: 80px;
.logo {
min-width: 25%;
position: relative;
top: 2vh;
left: 2vh;
}
.hamburger {
top: 2vh;
}
#navbarUL.hammenu {
max-width: 100%;
padding: 15vh 2vh 0 0;
.navbarLI {
a {
font-size: 1em;
}
}
}
}
// SURFACE DUO
@media screen and (min-width: 540px) and (max-width: 540px) and (max-height: 721px) and (max-height: 721px) {
height: 120px;
.logo {
min-width: 25%;
position: relative;
top: 2vh;
left: 2vh;
}
.hamburger {
top: 4.5vh;
}
#navbarUL.hammenu {
max-width: 75%;
padding: 15vh 2vh 0 0;
gap: 3vh;
.navbarLI {
a {
font-size: 1.5em;
}
}
}
}
// IPAD PRO
@media screen and (min-width: 1024px) and (max-width: 1024px) and (max-height: 1367px) and (max-height: 1367px) {
height: 14vh;
.logo {
min-width: 13%;
position: relative;
top: 1vh;
left: 2vh;
}
.hamburger {
top: 5vh;
}
#navbarUL.hammenu {
max-width: 75%;
padding: 15vh 2vh 0 0;
gap: 5vh;
.navbarLI {
a {
font-size: 2em;
}
}
}
}
// IPAD
@media screen and (min-width: 768px) and (max-width: 768px) and (max-height: 1025px) and (max-height: 1025px) {
height: 14vh;
.logo {
min-width: 13%;
position: relative;
top: 1vh;
left: 2vh;
}
.hamburger {
top: 4.3vh;
}
#navbarUL.hammenu {
max-width: 75%;
padding: 15vh 2vh 0 0;
gap: 5vh;
}
}
// IPHONE X
@media screen and (min-width: 375px) and (max-width: 375px) and (max-height: 813px) and (max-height: 813px) {
.logo {
min-width: 25%;
position: relative;
top: 2vh;
left: 2vh;
}
.hamburger {
top: 3.5vh;
}
#navbarUL.hammenu {
max-width: 75%;
padding: 15vh 2vh 0 0;
}
}
// IPHONE 678 PLUS
@media screen and (min-width: 414px) and (max-width: 414px) and (max-height: 737px) and (max-height: 737px) {
.logo {
min-width: 25%;
position: relative;
top: 2vh;
left: 2vh;
}
#navbarUL.hammenu {
max-width: 75%;
padding: 15vh 2vh 0 0;
}
}
// IPHONE 678
@media screen and (min-width: 375px) and (max-width: 375px) and (max-height: 668px) and (max-height: 668px) {
.logo {
min-width: 25%;
position: relative;
top: 2vh;
left: 2vh;
}
.hamburger {
top: 3.5vh;
}
#navbarUL.hammenu {
max-width: 75%;
padding: 15vh 2vh 0 0;
}
}
// IPHONE 5 SE
@media screen and (min-width: 320px) and (max-width: 320px) and (max-height: 569px) and (max-height: 569px) {
height: 15vh;
.logo {
min-width: 25%;
position: relative;
top: 2vh;
left: 2vh;
}
.hamburger {
top: 2.5vh;
}
#navbarUL.hammenu {
max-width: 75%;
padding: 15vh 2vh 0 0;
}
}
// PIXEL 2 XL
@media screen and (min-width: 411px) and (max-width: 411px) and (max-height: 824px) and (max-height: 824px) {
.logo {
min-width: 25%;
position: relative;
top: 1.5vh;
left: 2vh;
}
#navbarUL.hammenu {
max-width: 75%;
padding: 15vh 2vh 0 0;
}
}
// PIXEL 2
@media screen and (min-width: 411px) and (max-width: 411px) and (max-height: 732px) and (max-height: 732px) {
.logo {
min-width: 25%;
position: relative;
top: 1.5vh;
left: 2vh;
}
#navbarUL.hammenu {
max-width: 75%;
padding: 15vh 2vh 0 0;
}
}
// GALAXY S5 & MOTO G4
@media screen and (min-width: 360px) and (max-width: 360px) and (max-height: 641px) and (max-height: 641px) {
.logo {
min-width: 25%;
position: relative;
top: 1vh;
left: 2vh;
}
#navbarUL.hammenu {
max-width: 75%;
padding: 15vh 2vh 0 0;
}
}
@media screen and (max-width: 1190px) {
.logo {
min-width: 25%;
position: relative;
top: 2vh;
left: 2vh;
}
.headerBG {
display: none;
}
#navbarUL {
display: none;
}
.hamburger {
display: block;
z-index: 21;
}
}
`
export default Navbar
<file_sep>FROM node:10
ADD . /appDir
WORKDIR /appDir
COPY package*.json ./
RUN npm install
COPY . .
ENV PORT=3000
EXPOSE 3000
CMD ["npm", "start"]<file_sep>import React from 'react';
import styled from 'styled-components';
import slideimage from './slide-home.png';
import fetchNews from '../../utils/FetchNews';
import { useState, useEffect } from 'react';
const NewsfeedStructure = ({ className }) => {
const [page, setPage] = useState(1);
const [news, setNews] = useState(null);
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
})
useEffect(() => {
if(news === null) {
fetchNews(page).then(data => setNews(data))
} else {
let tempNews = JSON.parse(JSON.stringify(news));
fetchNews(page)
.then(data => (tempNews['articles'] = [...news['articles'], ...data['articles']]))
.then(setNews(tempNews))
}
console.log(news)
}, [page])
function handleScroll() {
const bottom = Math.ceil(window.innerHeight + window.scrollY) >= document.documentElement.scrollHeight
if (bottom) {
setPage(page + 1)
}
}
return (
<div className={className}>
<div className="slide">
<img src={slideimage} alt="slide"/>
<div className="divider">
<h3>trending now</h3>
</div>
</div>
<div id="newsfeed-container">
{news ? news['articles'].map((article, index) => {
if (index !== 0 && index % 3 === 0) {
return (
<div key={index} className="article fat" style={{backgroundImage:`url(${article.urlToImage})`}}>
<a href={article.url}><h1>{article.title}</h1></a>
<p>{article.description ? article.description : null}</p>
</div>
)
} else if (index === 0) {
return (
<div key={index} className="article wide" style={{backgroundImage:`url(${article.urlToImage})`}}>
<a href={article.url}><h1>{article.title}</h1></a>
<p>{article.description ? article.description : null}</p>
</div>
)
} else {
return (
<div key={index} className="article simple" pic={article.urlToImage} style={{backgroundImage:`url(${article.urlToImage})`}}>
<a href={article.url}><h1>{article.title}</h1></a>
</div>
)
}
})
: <div id="spinner-container" className="show">
<svg id="spinner" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 821.94 816.64">
<g id="Layer_2" data-name="Layer 2">
<g id="colored">
<path fill="none" stroke="#f72585" strokeWidth="20px" className="pink" d="M45.69,571.27A399.54,399.54,0,0,1,10,405.67c0-195.85,140.42-358.91,326.08-394"/>
<path fill="none" stroke="#560bad" strokeWidth="20px" className="darkest" d="M671.08,710.84A399.37,399.37,0,0,1,411,806.64q-11.42,0-22.68-.63"/>
<path fill="none" stroke="#4361ee" strokeWidth="20px" className="blue" d="M530.21,22.73c163.22,50.77,281.73,203,281.73,382.94a400.66,400.66,0,0,1-20.33,126.42"/>
<path fill="none" stroke="#7209b7" strokeWidth="20px" className="purple" d="M99.57,254.82C155.62,139.35,274,59.74,411,59.74c140.94,0,262.19,84.28,316.11,205.2"/>
<path fill="none" stroke="#b5179e" strokeWidth="20px" className="pinkish" d="M563.11,716.44A344.52,344.52,0,0,1,411,751.61c-181.68,0-330.64-140.05-344.83-318.08"/>
</g>
</g>
</svg>
</div>}
</div>
</div>
)
}
const Newsfeed = styled(NewsfeedStructure)`
.slide {
position: relative;
width: 100%;
max-height: 35vh;
z-index: -10;
& img {
width: 100%;
}
.divider {
width: 100%;
max-height: 6vh;
background: linear-gradient(90deg, #4E058D 38.34%, #330878 100%);
display: flex;
justify-content: center;
align-items: center;
h3 {
color: #f72585;
font-weight: normal;
font-size: 1em;
font-family: "Sen";
letter-spacing: 0.5em;
}
}
}
//NEWSFEED LAYOUT
#newsfeed-container {
width: 85%;
min-height: fit-content;
margin: auto;
display: grid;
grid-auto-flow: row;
grid-template-columns: repeat(3, 1fr);
gap: 3vh;
// SPINNER + ANIMATION
#spinner-container {
width: 100%;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
#spinner {
animation: rotate 3s linear infinite;
z-index: 2;
width: 10%;
.pink,.darkest,.blue,.purple,.pinkish{
fill:none;
stroke-linecap:square;
stroke-miterlimit:10;
stroke-width:20px;
animation: dash 3s cubic-bezier(0.37, 0, 0.63, 1) infinite;
}
.pink{
stroke:#f72585;
}
.darkest{
stroke:#560bad;
animation-delay: 0.5s;
}
.blue{
stroke:#4361ee;
animation-delay: 0.3s;
}
.purple{
stroke:#7209b7;
animation-delay: 0.2s;
animation-duration: 4s;
animation-direction: reverse;
}
.pinkish{
stroke:#b5179e;
animation-delay: 0.5s;
animation-direction: reverse;
}
@keyframes rotate {
100% {
transform: rotate(360deg);
}
}
@keyframes dash {
0% {
stroke-dasharray: 25%, 25%;
stroke-dashoffset: 0;
}
25% {
stroke-dasharray: 50%, 100%;
stroke-dashoffset: 0;
}
50% {
stroke-dasharray: 100%, 200%;
stroke-dashoffset: 50%;
}
75% {
stroke-dasharray: 50%, 100%;
stroke-dashoffset: 50%;
}
100% {
stroke-dasharray: 25%, 25%;
stroke-dashoffset: 100%;
}
}
}
}
.article:last-child {
margin-bottom: 10vh;
}
.article {
position: relative;
background-color: #330878;
background-size: cover;
display: flex;
flex-direction: column;
justify-content: flex-end;
align-items: flex-end;
}
.article a, h1, p {
/* position: absolute; */
display: inline;
background-color: #330878;
color: #4CC9F0;
font-family: "Sen";
padding: 0 2vh;
text-decoration: none;
}
.article h1 {
background-color: none;
padding: 0;
}
.simple {
width: 100%;
height: 200px;
background-size: cover;
background-color: #330878;
a {
padding: 1vh 2vh;
h1 {
font-size: 1em;
}
}
}
.wide {
margin-top: 15vh;
width: 100%;
height: 400px;
background-color: #330878;
background-size: cover;
grid-column: span 3;
a {
h1 {
margin-bottom: 1vh;
}
}
}
.fat {
width: 100%;
height: 400px;
background-color: #330878;
grid-row: span 2;
a {
margin: 0 0 2vh 0;
h1 {
font-size: 1.5em;
}
}
p {
margin: 0 0 2vh 0;
}
}
}
@media screen and (max-width: 1190px) {
#newsfeed-container {
width: 90%;
min-height: fit-content;
margin: auto;
display: grid;
grid-auto-flow: row;
grid-template-columns: 1fr;
gap: 3vh;
.article {
grid-column: 1;
height: 400px;
a {
font-size: large;
}
}
.wide {
grid-column: auto;
}
.fat {
grid-row: auto;
}
}
}
@media screen and (max-width: 361px) and (max-width: 361px) and (max-height: 641px) and (max-height: 641px) {
#newsfeed-container {
.article:last-child {
margin-bottom: 10vh;
}
.article {
height: 30vh;
a {
h1 {
font-size: medium;
}
}
p {
display: none;
}
}
.wide {
margin-top: 5vh;
}
.simple,
.wide,
.fat {
a {
margin: 0;
padding: 1vh;
}
}
}
}
@media screen and (min-width: 411px) and (max-width: 411px) and (max-height: 732px) and (max-height: 732px) {
#newsfeed-container {
.article:last-child {
margin-bottom: 10vh;
}
.article {
height: 30vh;
a {
h1 {
font-size: medium;
}
}
p {
display: none;
}
}
.wide {
margin-top: 5vh;
}
.simple,
.wide,
.fat {
a {
margin: 0;
padding: 1vh;
}
}
}
}
@media screen and (min-width: 411px) and (max-width: 411px) and (max-height: 824px) and (max-height: 824px) {
#newsfeed-container {
.article:last-child {
margin-bottom: 10vh;
}
.article {
height: 30vh;
a {
h1 {
font-size: medium;
}
}
p {
display: none;
}
}
.wide {
margin-top: 5vh;
}
.simple,
.wide,
.fat {
a {
margin: 0;
padding: 1vh;
}
}
}
}
@media screen and (min-width: 320px) and (max-width: 320px) and (max-height: 569px) and (max-height: 569px) {
#newsfeed-container {
.article:last-child {
margin-bottom: 10vh;
}
.article {
height: 30vh;
a {
h1 {
font-size: medium;
}
}
p {
display: none;
}
}
.wide {
margin-top: 5vh;
}
.simple,
.wide,
.fat {
a {
margin: 0;
padding: 1vh;
}
}
}
}
@media screen and (min-width: 375px) and (max-width: 375px) and (max-height: 668px) and (max-height: 668px) {
#newsfeed-container {
.article:last-child {
margin-bottom: 10vh;
}
.article {
height: 30vh;
a {
h1 {
font-size: medium;
}
}
p {
display: none;
}
}
.wide {
margin-top: 5vh;
}
.simple,
.wide,
.fat {
a {
margin: 0;
padding: 1vh;
}
}
}
}
@media screen and (min-width: 414px) and (max-width: 414px) and (max-height: 737px) and (max-height: 737px) {
#newsfeed-container {
.article:last-child {
margin-bottom: 10vh;
}
.article {
height: 30vh;
a {
h1 {
font-size: medium;
}
}
p {
display: none;
}
}
.wide {
margin-top: 5vh;
}
.simple,
.wide,
.fat {
a {
margin: 0;
padding: 1vh;
}
}
}
}
@media screen and (min-width: 375px) and (max-width: 375px) and (max-height: 813px) and (max-height: 813px) {
#newsfeed-container {
.article:last-child {
margin-bottom: 10vh;
}
.article {
height: 25vh;
a {
h1 {
font-size: medium;
}
}
p {
display: none;
}
}
.wide {
margin-top: 5vh;
}
.simple,
.wide,
.fat {
a {
margin: 0;
padding: 1vh;
}
}
}
}
@media screen and (min-width: 768px) and (max-width: 768px) and (max-height: 1025px) and (max-height: 1025px) {
#newsfeed-container {
.article:last-child {
margin-bottom: 10vh;
}
.article {
height: 25vh;
a {
h1 {
font-size: medium;
}
}
p {
display: none;
}
}
.wide {
margin-top: 5vh;
}
.simple,
.wide,
.fat {
a {
margin: 0;
padding: 1vh;
}
}
}
}
@media screen and (min-width: 1024px) and (max-width: 1024px) and (max-height: 1367px) and (max-height: 1367px) {
.slide {
.divider {
margin-bottom: 5vh;
}
}
#newsfeed-container {
grid-template-columns: 1fr 1fr;
.article {
height: 25vh;
grid-column: auto;
a {
h1 {
font-size: medium;
}
}
p {
display: none;
}
}
.wide {
margin-top: 0;
}
.simple,
.wide,
.fat {
a {
margin: 0;
padding: 1vh;
}
}
}
}
@media screen and (min-width: 540px) and (max-width: 540px) and (max-height: 721px) and (max-height: 721px) {
.slide {
.divider {
margin-bottom: 5vh;
}
}
#newsfeed-container {
grid-template-columns: 1fr;
.article {
height: 25vh;
grid-column: auto;
a {
h1 {
font-size: medium;
}
}
p {
display: none;
}
}
.wide {
margin-top: 0;
}
.simple,
.wide,
.fat {
a {
margin: 0;
padding: 1vh;
}
}
}
}
@media screen and (min-width: 280px) and (max-width: 280px) and (max-height: 654px) and (max-height: 654px) {
#newsfeed-container {
.article:last-child {
margin-bottom: 10vh;
}
.article {
height: 20vh;
a {
h1 {
font-size: small;
}
}
p {
display: none;
}
}
.wide {
margin-top: 5vh;
}
.simple,
.wide,
.fat {
a {
margin: 0;
padding: 1vh;
}
}
}
}
`
export default Newsfeed
<file_sep>import React from 'react';
import styled from 'styled-components';
import logo from '../../svg/logo_dark.svg';
import pinkR from '../../svg/pink-rectangle.svg';
import blueR from '../../svg/blue-rectangle.svg';
import arrow from '../../svg/Arrow.svg';
import { useState } from 'react';
const LandingStructure = ({setFirstLanding, className}) => {
const [showSpinner, setShowSpinner] = useState(false)
localStorage.setItem('MyBrowser', 'Tom')
const handleClick = () => {
setShowSpinner(true);
const timer = setTimeout(() => {
setFirstLanding(true)
}, 3000);
return () => {
clearTimeout(timer)
}
}
return (
<div className={className}>
{ showSpinner ?
<div className="spinnerBkg">
<div id="spinner-container" className="show">
<svg id="spinner" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 821.94 816.64">
<g id="Layer_2" data-name="Layer 2">
<g id="colored">
<path fill="none" stroke="#f72585" strokeWidth="20px" className="pink" d="M45.69,571.27A399.54,399.54,0,0,1,10,405.67c0-195.85,140.42-358.91,326.08-394"/>
<path fill="none" stroke="#560bad" strokeWidth="20px" className="darkest" d="M671.08,710.84A399.37,399.37,0,0,1,411,806.64q-11.42,0-22.68-.63"/>
<path fill="none" stroke="#4361ee" strokeWidth="20px" className="blue" d="M530.21,22.73c163.22,50.77,281.73,203,281.73,382.94a400.66,400.66,0,0,1-20.33,126.42"/>
<path fill="none" stroke="#7209b7" strokeWidth="20px" className="purple" d="M99.57,254.82C155.62,139.35,274,59.74,411,59.74c140.94,0,262.19,84.28,316.11,205.2"/>
<path fill="none" stroke="#b5179e" strokeWidth="20px" className="pinkish" d="M563.11,716.44A344.52,344.52,0,0,1,411,751.61c-181.68,0-330.64-140.05-344.83-318.08"/>
</g>
</g>
</svg>
</div>
</div>
: null}
<img className="logo" src={logo} alt="logo" />
<h1><span className="headerLn1"><span className="the">The </span><span className="latest">latest</span></span> <span className="headerLn2"><span className="tech">tech </span><span className="news">news</span></span> </h1>
<img className="pinkRect" src={pinkR} alt ="pink rectangle" />
<img className="blueRect" src={blueR} alt ="blue rectangle"/>
<button className="btn" onClick={handleClick}>Start reading</button>
<p className="arrowText">All in one place</p>
<img className="arrow" src={arrow} alt ="arrow" />
</div>
)
}
const Landing = styled(LandingStructure)`
position: relative;
top: 0;
left: 0;
.spinnerBkg {
width: 100%;
height: 100vh;
background-color: #00000089;
display: flex;
justify-content: center;
align-items: center;
z-index: 50;
}
#spinner-container {
background-color: #00000089;
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
z-index: 60;
#spinner {
animation: rotate 3s linear infinite;
z-index: 2;
width: 30%;
.pink,.darkest,.blue,.purple,.pinkish{
fill:none;
stroke-linecap:square;
stroke-miterlimit:10;
stroke-width:20px;
animation: dash 3s cubic-bezier(0.37, 0, 0.63, 1) infinite;
}
.pink{
stroke:#f72585;
}
.darkest{
stroke:#560bad;
animation-delay: 0.5s;
}
.blue{
stroke:#4361ee;
animation-delay: 0.3s;
}
.purple{
stroke:#7209b7;
animation-delay: 0.2s;
animation-duration: 4s;
animation-direction: reverse;
}
.pinkish{
stroke:#b5179e;
animation-delay: 0.5s;
animation-direction: reverse;
}
@keyframes rotate {
100% {
transform: rotate(360deg);
}
}
@keyframes dash {
0% {
stroke-dasharray: 25%, 25%;
stroke-dashoffset: 0;
}
25% {
stroke-dasharray: 50%, 100%;
stroke-dashoffset: 0;
}
50% {
stroke-dasharray: 100%, 200%;
stroke-dashoffset: 50%;
}
75% {
stroke-dasharray: 50%, 100%;
stroke-dashoffset: 50%;
}
100% {
stroke-dasharray: 25%, 25%;
stroke-dashoffset: 100%;
}
}
}
}
.logo {
position: absolute;
top: 7vh;
left: 50%;
transform: translateX(-50%);
height: 23vh;
}
.headerLn1 {
position: absolute;
top: 35vh;
right: 10vw;
z-index: 10;
display: block;
font-family: Sen;
font-style: normal;
font-weight: 800;
font-size: 3em;
line-height: 115px;
text-transform: uppercase;
color: #4CC9F0;
text-shadow: -10px 10px 10px rgba(0, 0, 0, 0.25);
}
.headerLn2 {
position: absolute;
top: 45vh;
right: 30vw;
z-index: 10;
display: block;
font-family: Sen;
font-style: normal;
font-weight: 800;
font-size: 2.5em;
line-height: 87px;
text-transform: uppercase;
color: #4CC9F0;
text-shadow: -10px 10px 10px rgba(0, 0, 0, 0.25);
}
.pinkRect {
position: absolute;
}
.blueRect {
position: absolute;
}
.btn {
position: absolute;
top: calc(61vh - 25px);
left: calc(14vw - 55px);
color: #560BAD;
text-transform: uppercase;
font-family: $sen;
font-weight: 700;
font-size: 2.3em;
letter-spacing: 0.1em;
background-color: transparent;
z-index: 10;
padding: 20px 140px 75px 75px;
border: none;
&:hover {
transform: rotate(7deg);
transform-origin: 5% 5%;
}
}
.arrow {
position: absolute;
top: 64vh;
left: 42vw;
width: 50vw;
}
.arrowText {
position: absolute;
top: 55vh;
right: 8vw;
text-transform: uppercase;
color: #D61E91;
font-family: $sen;
letter-spacing: 0.2em;
font-weight: 700;
font-size: 3em;
}
@media only screen and (min-width: 1700px) and (min-height: 800px) {
position: relative;
top: 0;
left: 0;
.logo {
position: absolute;
top: 7vh;
left: 50%;
transform: translateX(-50%);
height: 23vh;
}
.headerLn1 {
position: absolute;
top: 35vh;
right: 10vw;
font-size: 3em;
line-height: 115px;
}
.headerLn2 {
position: absolute;
top: 45vh;
right: 30vw;
font-size: 2.5em;
line-height: 87px;
}
.pinkRect {
position: absolute;
top: 30vh;
left: 7vw;
}
.blueRect {
position: absolute;
top: 58vh;
left: 10vw;
height: 20vh;
}
.btn {
position: absolute;
top: calc(61vh - 25px);
left: calc(14vw - 55px);
font-size: 2.3em;
letter-spacing: 0.1em;
z-index: 10;
padding: 20px 140px 75px 75px;
}
.arrow {
position: absolute;
top: 64vh;
left: 42vw;
width: 50vw;
}
.arrowText {
position: absolute;
top: 55vh;
right: 8vw;
letter-spacing: 0.2em;
font-size: 3em;
}
}
//Fanni
@media only screen and (min-width: 1300px) and (max-width: 1699px) {
position: relative;
top: 0;
left: 0;
.logo {
position: absolute;
top: 8vh;
left: 50%;
transform: translateX(-150%);
height: 25vh;
}
.headerLn1 {
position: absolute;
top: 25vh;
right: 10vw;
font-size: 2.7em;
line-height: 115px;
}
.headerLn2 {
position: absolute;
top: 40vh;
right: 25vw;
font-size: 2.4em;
line-height: 87px;
}
.pinkRect {
position: absolute;
top: 40vh;
left: 7vw;
height: 40vh;
}
.blueRect {
position: absolute;
top: 56vh;
left: 5vw;
height: 21vh;
}
.btn {
position: absolute;
top: calc(61vh - 25px);
left: calc(10vw - 35px);
font-size: 2em;
z-index: 10;
padding: 15px 60px 45px 25px;
}
.arrow {
position: absolute;
top: 64vh;
left: 35vw;
width: 55vw;
}
.arrowText {
position: absolute;
top: 53vh;
right: 8vw;
letter-spacing: 0.1em;
font-size: 3em;
font-weight: 500;
text-transform: lowercase;
}
}
//David
@media only screen and (min-width: 1026px) and (max-width: 1299px) {
position: relative;
top: 0;
left: 0;
.logo {
position: absolute;
top: 9vh;
left: 50%;
transform: translateX(-180%);
height: 25vh;
}
.headerLn1 {
position: absolute;
top: 22vh;
right: 10vw;
font-size: 2.7em;
line-height: 115px;
}
.headerLn2 {
position: absolute;
top: 38vh;
right: 25vw;
font-size: 2.4em;
line-height: 87px;
}
.pinkRect {
position: absolute;
top: 36vh;
left: 1vw;
width: 49vw;
}
.blueRect {
position: absolute;
top: 56vh;
left: 5vw;
height: 21vh;
}
.btn {
position: absolute;
top: calc(61vh - 25px);
left: calc(10vw - 35px);
font-size: 2em;
z-index: 10;
padding: 15px 60px 45px 25px;
}
.arrow {
position: absolute;
top: 65vh;
left: 35vw;
width: 45vw;
}
.arrowText {
position: absolute;
top: 49vh;
right: 6vw;
letter-spacing: 0.1em;
font-size: 2.9em;
font-weight: 500;
text-transform: lowercase;
}
}
//iPadPro + iPad
@media only screen and (min-width: 768px) and (max-width: 1025px) {
position: relative;
top: 0;
left: 0;
width: 100%;
height: 100vh;
.logo {
position: absolute;
top: 10vh;
left: 50vw;
transform: translateX(-45%);
height: 15vh;
}
.headerLn1 {
position: absolute;
top: 32vh;
left: 15vw;
font-size: 2.5em;
line-height: 115px;
text-transform: uppercase;
.latest {
position: absolute;
top: 5vh;
left: 25vw;
text-transform: lowercase;
font-size: 50px;
}
}
.headerLn2 {
position: absolute;
top: 30vh;
left: 42vw;
font-size: 50px;
line-height: 87px;
text-transform: lowercase;
.news {
text-transform: uppercase;
font-size: 70px;
position: absolute;
top: 3vh;
left: 20vw;
}
}
.pinkRect {
position: absolute;
top: 60vh;
left: 10vw;
width: 80vw;
}
.blueRect {
position: absolute;
top: 70vh;
left: 10vw;
height: 20vh;
}
.btn {
position: absolute;
top: 72vh;
left: 25vw;
font-size: 2.5em;
z-index: 10;
padding: 15px 60px 45px 25px;
}
.arrow {
position: absolute;
top: 65vh;
left: 35vw;
width: 45vw;
display: none;
}
.arrowText {
position: absolute;
top: 49vh;
right: 6vw;
letter-spacing: 0.1em;
font-size: 2.9em;
font-weight: 500;
text-transform: lowercase;
}
}
//mobile big
@media only screen and (min-width: 481px) and (max-width: 767px) {
position: relative;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
.logo {
position: absolute;
top: 20vh;
left: 22vw;
transform: translateX(-35%);
height: 25vh;
}
.headerLn1 {
position: absolute;
top: 10vh;
left: 60vw;
font-size: 70px;
line-height: 80px;
text-transform: uppercase;
display: flex;
flex-direction: column;
align-items: flex-end;
span {
display: inline-block;
}
.latest {
text-transform: lowercase;
font-size: 70px;
}
}
.headerLn2 {
position: absolute;
top: 32vh;
left: 90vw;
font-size: 70px;
line-height: 87px;
text-transform: lowercase;
display: flex;
flex-direction: column;
align-items: flex-end;
.news {
text-transform: uppercase;
font-size: 70px;
}
}
.pinkRect {
position: absolute;
top: 60vh;
left: 10vw;
width: 80vw;
transform: rotate(180deg)
}
.blueRect {
position: absolute;
top: 65vh;
left: 15vw;
height: 15vh;
transform: rotate(180deg)
}
.btn {
position: absolute;
top: 71vh;
left: 19vw;
font-size: 2em;
letter-spacing: 0;
z-index: 10;
padding: 15px 60px 45px 25px;
}
.arrow {
position: absolute;
top: 65vh;
left: 35vw;
width: 45vw;
display: none;
}
.arrowText {
position: absolute;
top: 49vh;
right: 6vw;
letter-spacing: 0.1em;
font-size: 2.9em;
font-weight: 500;
text-transform: lowercase;
display: none;
}
}
//mobile medium
@media only screen and (min-width: 400px) and (max-width: 480px) {
position: relative;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
.logo {
position: absolute;
top: 4vh;
left: 22vw;
transform: translateX(-35%);
height: 17vh;
}
.headerLn1 {
position: absolute;
top: 10vh;
left: 60vw;
font-size: 70px;
line-height: 80px;
text-transform: uppercase;
display: flex;
flex-direction: column;
align-items: flex-end;
span {
display: inline-block;
}
.latest {
text-transform: lowercase;
font-size: 70px;
}
}
.headerLn2 {
position: absolute;
top: 32vh;
left: 90vw;
font-size: 70px;
line-height: 87px;
text-transform: lowercase;
display: flex;
flex-direction: column;
align-items: flex-end;
.news {
text-transform: uppercase;
font-size: 70px;
}
}
.pinkRect {
position: absolute;
top: 65vh;
left: 10vw;
width: 85vw;
transform: rotate(180deg)
}
.blueRect {
position: absolute;
top: 65vh;
left: 10vw;
height: 15vh;
transform: rotate(180deg)
}
.btn {
position: absolute;
top: 71vh;
left: 16vw;
font-size: 30px;
letter-spacing: 0;
z-index: 10;
padding: 15px 60px 45px 25px;
}
.arrow {
position: absolute;
top: 65vh;
left: 35vw;
width: 45vw;
display: none;
}
.arrowText {
position: absolute;
top: 0vh;
right: 0;
left: -65vw;
letter-spacing: 0;
font-size: 2em;
font-weight: 500;
text-transform: lowercase;
transform: rotate(270deg);
}
}
//mobile small
@media only screen and (min-width: 321px) and (max-width: 400px) {
position: relative;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
.logo {
position: absolute;
top: 1vh;
left: 75vw;
height: 15vh;
}
.headerLn1 {
position: absolute;
top: 10vh;
left: 5vw;
font-size: 50px;
line-height: 55px;
text-transform: uppercase;
display: flex;
flex-direction: column;
.latest {
font-size: 70px;
}
}
.headerLn2 {
position: absolute;
top: 24vh;
left: 18vw;
font-size: 1em;
line-height: 87px;
text-transform: lowercase;
display: flex;
flex: column;
.news {
text-transform: uppercase;
font-size: 70px;
}
}
.pinkRect {
position: absolute;
top: 65vh;
left: 5vw;
width: 80vw;
transform: rotate(15deg);
}
.blueRect {
position: absolute;
top: 65vh;
left: 15vw;
height: 15vh;
transform: rotate(174deg);
}
.btn {
position: absolute;
top: 70vh;
left: calc(12vw - 35px);
font-size: 2em;
z-index: 10;
padding: 15px 60px 45px 25px;
}
.arrow {
position: absolute;
top: 55vh;
left: 35vw;
width: 40vh;
transform: rotate(270deg);
}
.arrowText {
position: absolute;
top: 49vh;
right: -5vw;
letter-spacing: 0.02em;
font-size: 1.5em;
font-weight: 500;
text-transform: lowercase;
transform: rotate(90deg);
}
}
//mobile narrow
@media only screen and (max-width: 320px) {
position: relative;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
.logo {
position: absolute;
top: 1vh;
left: 66vw;
height: 15vh;
}
.headerLn1 {
position: absolute;
top: 10vh;
left: 5vw;
font-size: 50px;
line-height: 55px;
text-transform: uppercase;
display: flex;
flex-direction: column;
.latest {
font-size: 63px;
}
}
.headerLn2 {
position: absolute;
top: 26vh;
left: 12vw;
font-size: 1em;
line-height: 87px;
text-transform: lowercase;
display: flex;
flex: column;
.news {
text-transform: uppercase;
font-size: 50px;
}
}
.pinkRect {
position: absolute;
top: 63vh;
left: 5vw;
width: 80vw;
transform: rotate(15deg);
}
.blueRect {
position: absolute;
top: 49vh;
left: -21vw;
height: 12vh;
transform: rotate(70deg);
z-index: 19;
}
.btn {
position: absolute;
top: 72vh;
left: 15vw;
font-size: 1.3em;
letter-spacing: 0;
z-index: 10;
padding: 10px;
background-color: #4cc9f0;
box-shadow: 5px 5px 5px #0000008f ;
}
.arrow {
position: absolute;
top: 55vh;
left: -10vw;
width: 35vh;
transform: rotate(250deg);
z-index: 20;
}
.arrowText {
position: absolute;
top: 34vh;
right: 20vw;
letter-spacing: 0;
font-size: 1.3em;
font-weight: 500;
text-transform: lowercase;
}
}
`
export default Landing
<file_sep>const express = require('express')
const server = express();
const path = require('path');
const fs = require('fs')
const axios = require('axios');
const cors = require('cors')
const port = 3000;
let news;
server.use(cors());
fs.readFile('sample_news.json', 'utf8', function readFileCallback(err, data) {
if (err) {
console.log(err)
} else {
news = JSON.parse(data);
}
})
server.get("/news/tech/:pageNum", async (req, res) => {
// azt is le kell kezelni ha 0 jön be pageNum-ként
const pageNum = parseInt(req.params.pageNum);
const maxPageNum = Math.ceil(news['totalResults'] / 10)
const articles = {'maxPageNum': maxPageNum, 'articles':[]};
const fromIndex = (pageNum - 1) * 10;
let toIndex = (pageNum * 10);
if(toIndex > news['articles'].length){
toIndex = news['articles'].length
}
for(let i = fromIndex; i < toIndex; i++) {
articles['articles'].push(news.articles[i])
}
res.send(JSON.stringify(articles))
})
server.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
<file_sep># Tech Magazine
This was a 5-day group project to create a news website to browse the latest technology news with infinite scrolling. There are some functions missing (like the ability to load a different news category) due to the time limit, but we learnt a lot and used DockerHUB the first time.
Wireframing, logo and layout design was fully my part in the development.
[Figma link](https://www.figma.com/file/eSwAsVHefYXaInVHFnZ4ya/TechMagazineV2?node-id=0%3A1)
We used:
**News API**
**express.js**
**axios**
**React.js**
**Adobe Illustrator**
Thanks for reading!
| 3ed1ef572d42f4d4f4f69c66b67715ea86cceecc | [
"JavaScript",
"Dockerfile",
"Markdown"
] | 6 | JavaScript | wfanni/tech-magazine | 66a886d01e7f8602e85b3a7a4cde17f6ca89c217 | 4e9f959df89472b5d169bd05dd6c7e1387daaad7 | |
refs/heads/master | <repo_name>LeoB-O/DJMall_FrontEnd<file_sep>/src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import Index from '@/view/index'
import SignIn from '@/view/SignIn'
import SignUp from '@/view/SignUp'
import Cart from '@/view/Cart'
import Main from '@/view/Main'
import Content from '@/view/Content'
import GoodsDetail from '@/view/GoodsDetail'
import Catagory from '@/view/Catagory'
import CommercialIndex from '@/view/CommercialIndex'
import PersonalInfo from '@/view/PersonalInfo'
import Order from '@/view/Order'
import EditInfo from '@/view/Editinfo'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
component: Main,
children: [
{
path: '/commercial/:commercialId',
component: CommercialIndex
},
{
path: 'good/:goodid',
component: GoodsDetail
},
{
path: '/personalInfo/:id',
component: PersonalInfo,
children:[
{
path:'order',
component:Order
},
{
path:'editpinfo',
component:EditInfo
}
]
},
{
path: '/signin',
name: 'SignIn',
component: SignIn
},
{
path: '/signup',
name: 'SignUp',
component: SignUp
},
{
path: '/cart',
name: 'Cart',
component: Cart
},
{
path: '',
component: Index,
children: [
{
path: '',
component: Content
},
{
path: 'catagory/:catagory',
component: Catagory
}
]
}
]
}
]
})
<file_sep>/src/util/mockUtil.js
let mockUtil = {
genReturn: function (success, data) {
return {
success: !!success,
data: data
}
}
}
export default mockUtil
| bc98fcca4139d6621b91efca9934d3b398729ab4 | [
"JavaScript"
] | 2 | JavaScript | LeoB-O/DJMall_FrontEnd | 2e560e989efaf715e9c57b05d92fd6abf2c29abe | 55e21ca7f0015e3838582986c910838de92cf91d | |
refs/heads/master | <repo_name>iamgovindthakur/interestCalculator<file_sep>/src/main/java/baseClasses/BaseTestClass.java
package baseClasses;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.annotations.AfterMethod;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import io.github.bonigarcia.wdm.WebDriverManager;
import utilities.ExtentReportManager;
public class BaseTestClass {
public WebDriver driver;
public ExtentReports report = ExtentReportManager.getReportInstance();
public ExtentTest logger;
public static Properties prop;
/****************** Invoke Browser ***********************/
public void invokeBrowser(String browserName) {
try {
if (browserName.equalsIgnoreCase("Chrome")) {
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("./src/test/resources/AdBlock.crx"));
driver = new ChromeDriver(options);
} else if (browserName.equalsIgnoreCase("Mozila")) {
WebDriverManager.firefoxdriver().setup();
FirefoxBinary firefoxBinary = new FirefoxBinary();
firefoxBinary.addCommandLineOptions("--headless");
FirefoxProfile profile = new FirefoxProfile();
profile.addExtension(new File(("./src/test/resources/AdBlock.xpi")));
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(firefoxBinary);
firefoxOptions.setProfile(profile);
driver = new FirefoxDriver(firefoxOptions);
} else if (browserName.equalsIgnoreCase("Opera")) {
WebDriverManager.operadriver().setup();
driver = new OperaDriver();
} else if (browserName.equalsIgnoreCase("IE")) {
WebDriverManager.iedriver().setup();
driver = new InternetExplorerDriver();
} else {
driver = new SafariDriver();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
driver.manage().window().maximize();
if (prop == null) {
prop = new Properties();
try {
FileInputStream file = new FileInputStream(System.getProperty("user.dir")
+ "//src/test//resources//ObjectRepository//projectConfig.properties");
prop.load(file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@AfterMethod(alwaysRun = true)
public void flushReports() {
report.flush();
driver.quit();
}
}
<file_sep>/src/main/java/pageClasses/CarLoanPage.java
package pageClasses;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import com.aventstack.extentreports.ExtentTest;
import baseClasses.PageBaseClass;
public class CarLoanPage extends PageBaseClass {
public CarLoanPage(WebDriver driver, ExtentTest logger) {
super(driver, logger);
}
/* Adjusting Car Loan Amount Field value with Slider */
public void setHomeAmountSlider(String sliderLocator, double value, double sliderMax, double sliderMin) {
WebElement locator = getElement(sliderLocator);
moveSlider(locator, value, sliderMax, sliderMin);
}
/* Adjusting Interest Rate Field value with Slider */
public void setInterestRateSlider(String sliderLocator, double value, double sliderMax, double sliderMin) {
WebElement locator = getElement(sliderLocator);
moveSlider(locator, value, sliderMax, sliderMin);
}
/* Adjusting Loan Tenure Field value with Slider */
public void setLoanTenureSlider(String sliderLocator, double value, double sliderMax, double sliderMin) {
WebElement locator = getElement(sliderLocator);
moveSlider(locator, value, sliderMax, sliderMin);
}
/* Clearing Text Box Pre Loaded Value And Give New Input Value*/
public void clearFieldandGiveInput(String locator, String input) {
getElement(locator).clear();
getElement(locator).sendKeys(Keys.BACK_SPACE + input + Keys.TAB);
}
/* Displaying EMI Summary */
public void displayEmiDetails() {
System.out.println("-------------------------------------------------------");
System.out.println("Loan EMI: " + getElement("carLoanEmiAmount_CSS").getText());
System.out.println("Total Interest Payable: " + getElement("carInterestPayable_CSS").getText());
System.out.println("Total Payment(Principal + Interest): " + getElement("carTotalAmount_CSS").getText());
System.out.println("-------------------------------------------------------");
takeScreenShotOfWebelement("carLoanResult_Xpath");
}
}
<file_sep>/src/test/java/testCase/LoanEmiCalculator.java
package testCase;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
import baseClasses.BaseTestClass;
import baseClasses.PageBaseClass;
import pageClasses.LandingPage;
import pageClasses.LoanCalulatorPage;
public class LoanEmiCalculator extends BaseTestClass {
LandingPage lp;
LoanCalulatorPage loanCalculator;
@Test(groups="Main_TestCase")
public void testEMICalculator() {
logger = report.createTest("Loan EMI Calculator TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
lp = pageBase.OpenApplication();
loanCalculator = lp.navigateToloanCalculator();
loanCalculator.navigateToEmiCalculator();
loanCalculator.setLoanAmountSlider("loanamountslider_Xpath", 15, 200, 0);
loanCalculator.assertequals("15,00,000", loanCalculator.readText("loanAmountTextBox_Xpath"));
loanCalculator.setInterestRateSlider("loanInterestRateSlider_Xpath", 9.5, 20, 0);
loanCalculator.assertequals("9.5", loanCalculator.readText("loanInterestRateTextBox_Xpath"));
loanCalculator.setLoanTenureSlider("loanTermslider_Xpath", 1, 30, 0);
loanCalculator.assertequals("1", loanCalculator.readText("loanTennureTextBox_Xpath"));
loanCalculator.setLoanFeeChargesSlider("loanFeesslider_Xpath", .45, 1, 0);
loanCalculator.assertequals("45,000", loanCalculator.readText("loanFeesNChargesTextBox_Xpath"));
loanCalculator.displayLoanEmi();
loanCalculator.softAssert.assertAll();
}
@Test
public void testEMICalculatorAmountFieldForNumbericInputValue() {
logger = report.createTest("Loan Calculator EMI TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
lp = pageBase.OpenApplication();
loanCalculator = lp.navigateToloanCalculator();
loanCalculator.navigateToEmiCalculator();
loanCalculator.clearFieldandGiveInput("loanAmountTextBox_Xpath", "2500000");
loanCalculator.assertequals("25,00,000", loanCalculator.readText("loanAmountTextBox_Xpath"));
loanCalculator.softAssert.assertAll();
}
@Test
public void testEMICalculatorAmountFieldForAlphabeticInputValue() {
logger = report.createTest("Loan Calculator EMI TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
lp = pageBase.OpenApplication();
loanCalculator = lp.navigateToloanCalculator();
loanCalculator.navigateToEmiCalculator();
loanCalculator.clearFieldandGiveInput("loanAmountTextBox_Xpath", "qwerty");
loanCalculator.assertequals("qwerty", loanCalculator.readText("loanAmountTextBox_Xpath"));
loanCalculator.softAssert.assertAll();
}
@Test
public void testEMICalculatorAmountFieldForSpecialCharactersInputValue() {
logger = report.createTest("Loan Calculator EMI TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
lp = pageBase.OpenApplication();
loanCalculator = lp.navigateToloanCalculator();
loanCalculator.navigateToEmiCalculator();
loanCalculator.clearFieldandGiveInput("loanAmountTextBox_Xpath", "!@#$%");
loanCalculator.assertequals("!@#$%", loanCalculator.readText("loanAmountTextBox_Xpath"));
loanCalculator.softAssert.assertAll();
}
@Test
public void testEMICalculatorInterestRateFieldForNumbericInputValue() {
logger = report.createTest("Loan Calculator EMI TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
lp = pageBase.OpenApplication();
loanCalculator = lp.navigateToloanCalculator();
loanCalculator.navigateToEmiCalculator();
loanCalculator.clearFieldandGiveInput("loanInterestRateTextBox_Xpath", "9.5");
loanCalculator.assertequals("9.5", loanCalculator.readText("loanInterestRateTextBox_Xpath"));
loanCalculator.softAssert.assertAll();
}
@Test
public void testEMICalculatorInterestRateFieldForAlphabeticInputValue() {
logger = report.createTest("Loan Calculator EMI TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
lp = pageBase.OpenApplication();
loanCalculator = lp.navigateToloanCalculator();
loanCalculator.navigateToEmiCalculator();
loanCalculator.clearFieldandGiveInput("loanInterestRateTextBox_Xpath", "qwerty");
loanCalculator.assertequals("qwerty", loanCalculator.readText("loanInterestRateTextBox_Xpath"));
loanCalculator.softAssert.assertAll();
}
@Test
public void testEMICalculatorInterestRateFieldForSpecialCharactersInputValue() {
logger = report.createTest("Loan Calculator EMI TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
lp = pageBase.OpenApplication();
loanCalculator = lp.navigateToloanCalculator();
loanCalculator.navigateToEmiCalculator();
loanCalculator.clearFieldandGiveInput("loanInterestRateTextBox_Xpath", "!@#$%");
loanCalculator.assertequals("!@#$%", loanCalculator.readText("loanInterestRateTextBox_Xpath"));
loanCalculator.softAssert.assertAll();
}
@Test
public void testEMICalculatorLoanTenureFieldForNumbericInputValue() {
logger = report.createTest("Loan Calculator EMI TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
lp = pageBase.OpenApplication();
loanCalculator = lp.navigateToloanCalculator();
loanCalculator.navigateToEmiCalculator();
loanCalculator.clearFieldandGiveInput("loanTennureTextBox_Xpath", "1");
loanCalculator.assertequals("1", loanCalculator.readText("loanTennureTextBox_Xpath"));
loanCalculator.softAssert.assertAll();
}
@Test
public void testEMICalculatorLoanTenureFieldForAlphabeticInputValue() {
logger = report.createTest("Loan Calculator EMI TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
lp = pageBase.OpenApplication();
loanCalculator = lp.navigateToloanCalculator();
loanCalculator.navigateToEmiCalculator();
loanCalculator.clearFieldandGiveInput("loanTennureTextBox_Xpath", "qwerty");
loanCalculator.assertequals("qwerty", loanCalculator.readText("loanTennureTextBox_Xpath"));
loanCalculator.softAssert.assertAll();
}
@Test
public void testEMICalculatorLoanTenureFieldForSpecialCharactersInputValue() {
logger = report.createTest("Loan Calculator EMI TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
lp = pageBase.OpenApplication();
loanCalculator = lp.navigateToloanCalculator();
loanCalculator.navigateToEmiCalculator();
loanCalculator.clearFieldandGiveInput("loanTennureTextBox_Xpath", "!@#$%");
loanCalculator.assertequals("!@#$%", loanCalculator.readText("loanTennureTextBox_Xpath"));
loanCalculator.softAssert.assertAll();
}
@Test
public void testEMICalculatorFeesNChargesFieldForNumbericInputValue() {
logger = report.createTest("Loan Calculator EMI TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
lp = pageBase.OpenApplication();
loanCalculator = lp.navigateToloanCalculator();
loanCalculator.navigateToEmiCalculator();
loanCalculator.clearFieldandGiveInput("loanFeesNChargesTextBox_Xpath", "25000");
loanCalculator.assertequals("25,000", loanCalculator.readText("loanFeesNChargesTextBox_Xpath"));
loanCalculator.softAssert.assertAll();
}
@Test
public void testEMICalculatorFeesNChargesForAlphabeticInputValue() {
logger = report.createTest("Loan Calculator EMI TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
lp = pageBase.OpenApplication();
loanCalculator = lp.navigateToloanCalculator();
loanCalculator.navigateToEmiCalculator();
loanCalculator.clearFieldandGiveInput("loanFeesNChargesTextBox_Xpath", "qwerty");
loanCalculator.assertequals("qwerty", loanCalculator.readText("loanFeesNChargesTextBox_Xpath"));
loanCalculator.softAssert.assertAll();
}
@Test
public void testEMICalculatorFeesNChargesFieldForSpecialCharactersInputValue() {
logger = report.createTest("Loan Calculator EMI TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
lp = pageBase.OpenApplication();
loanCalculator = lp.navigateToloanCalculator();
loanCalculator.navigateToEmiCalculator();
loanCalculator.clearFieldandGiveInput("loanFeesNChargesTextBox_Xpath", "!@#$%");
loanCalculator.assertequals("!@#$%", loanCalculator.readText("loanFeesNChargesTextBox_Xpath"));
loanCalculator.softAssert.assertAll();
}
}
<file_sep>/test-output/old/EMI Calculator main testcases/methods.html
<h2>Methods run, sorted chronologically</h2><h3>>> means before, << means after</h3><p/><br/><em>EMI Calculator main testcases</em><p/><small><i>(Hover the method name to see the test class name)</i></small><p/>
<table border="1">
<tr><th>Time</th><th>Delta (ms)</th><th>Suite<br>configuration</th><th>Test<br>configuration</th><th>Class<br>configuration</th><th>Groups<br>configuration</th><th>Method<br>configuration</th><th>Test<br>method</th><th>Thread</th><th>Instances</th></tr>
<tr bgcolor="8ddf86"> <td>21/03/29 15:29:55</td> <td>0</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="CarLoanTest.testCarLoan()[pri:0, instance:testCase.CarLoanTest@5b29ab61]">testCarLoan</td>
<td>main@157990006</td> <td></td> </tr>
<tr bgcolor="b6e1c0"> <td>21/03/29 15:30:24</td> <td>29426</td> <td> </td><td> </td><td> </td><td> </td><td title="<<BaseTestClass.flushReports()[pri:0, instance:testCase.CarLoanTest@5b29ab61]"><<flushReports</td>
<td> </td> <td>main@157990006</td> <td></td> </tr>
<tr bgcolor="d57eae"> <td>21/03/29 15:30:26</td> <td>31392</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="LoanEmiCalculator.testEMICalculator()[pri:0, instance:testCase.LoanEmiCalculator@5c313224]">testEMICalculator</td>
<td>main@157990006</td> <td></td> </tr>
<tr bgcolor="b6e1c0"> <td>21/03/29 15:30:55</td> <td>59762</td> <td> </td><td> </td><td> </td><td> </td><td title="<<BaseTestClass.flushReports()[pri:0, instance:testCase.LoanEmiCalculator@5c313224]"><<flushReports</td>
<td> </td> <td>main@157990006</td> <td></td> </tr>
<tr bgcolor="af7d97"> <td>21/03/29 15:30:56</td> <td>61215</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="LoanAmountCalculator.testLoanAmountCalculator()[pri:0, instance:testCase.LoanAmountCalculator@1e1e837d]">testLoanAmountCalculator</td>
<td>main@157990006</td> <td></td> </tr>
<tr bgcolor="b6e1c0"> <td>21/03/29 15:31:30</td> <td>95199</td> <td> </td><td> </td><td> </td><td> </td><td title="<<BaseTestClass.flushReports()[pri:0, instance:testCase.LoanAmountCalculator@1e1e837d]"><<flushReports</td>
<td> </td> <td>main@157990006</td> <td></td> </tr>
<tr bgcolor="a5818e"> <td>21/03/29 15:31:31</td> <td>96329</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="HomeLoanEMICalculator.testHomeLoanEMICalculator()[pri:0, instance:testCase.HomeLoanEMICalculator@4b957db0]">testHomeLoanEMICalculator</td>
<td>main@157990006</td> <td></td> </tr>
<tr bgcolor="b6e1c0"> <td>21/03/29 15:32:31</td> <td>156059</td> <td> </td><td> </td><td> </td><td> </td><td title="<<BaseTestClass.flushReports()[pri:0, instance:testCase.HomeLoanEMICalculator@4b957db0]"><<flushReports</td>
<td> </td> <td>main@157990006</td> <td></td> </tr>
<tr bgcolor="75ae93"> <td>21/03/29 15:32:32</td> <td>157365</td> <td> </td><td> </td><td> </td><td> </td><td> </td><td title="LoanTenureCalculator.testLoanTenureCalculator()[pri:0, instance:testCase.LoanTenureCalculator@5d71b500]">testLoanTenureCalculator</td>
<td>main@157990006</td> <td></td> </tr>
<tr bgcolor="b6e1c0"> <td>21/03/29 15:33:18</td> <td>202795</td> <td> </td><td> </td><td> </td><td> </td><td title="<<BaseTestClass.flushReports()[pri:0, instance:testCase.LoanTenureCalculator@5d71b500]"><<flushReports</td>
<td> </td> <td>main@157990006</td> <td></td> </tr>
</table>
<file_sep>/src/main/java/pageClasses/LandingPage.java
package pageClasses;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import baseClasses.PageBaseClass;
public class LandingPage extends PageBaseClass {
public LandingPage(WebDriver driver, ExtentTest logger) {
super(driver, logger);
}
/* Navigate to car loan page from landing page */
public CarLoanPage navigateToCarLoan() {
logger.log(Status.INFO, "Identifying the Car Loan Link");
elementClick("carLoanLink_Xpath");
logger.log(Status.PASS, "Car Loan Link identified and Clicked");
CarLoanPage carLoanPage = new CarLoanPage(driver, logger);
PageFactory.initElements(driver, carLoanPage);
return carLoanPage;
}
/* Navigate to loan calculator page from landing page */
public LoanCalulatorPage navigateToloanCalculator() {
elementClick("menuDropDown_Id");
elementClick("loanCalculator_Xpath");
LoanCalulatorPage loanCalulatorPage = new LoanCalulatorPage(driver, logger);
PageFactory.initElements(driver, loanCalulatorPage);
return loanCalulatorPage;
}
/* Navigate to home loan EMI page from landing page */
public HomeLoanEMIPAGE navigateToHomeLoanEMICalculator() {
elementClick("menuDropDown_Id");
elementClick("homeLoanEMICalculator_Xpath");
HomeLoanEMIPAGE homeLoanEMIPAGE = new HomeLoanEMIPAGE(driver, logger);
PageFactory.initElements(driver, homeLoanEMIPAGE);
return homeLoanEMIPAGE;
}
}
<file_sep>/test-output/old/EMI Calculator main testcases/Main testcase Test.properties
[SuiteResult context=Main testcase Test]<file_sep>/src/test/java/testCase/CarLoanTest.java
package testCase;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
import baseClasses.BaseTestClass;
import baseClasses.PageBaseClass;
import pageClasses.CarLoanPage;
import pageClasses.LandingPage;
public class CarLoanTest extends BaseTestClass {
LandingPage landingPage;
CarLoanPage carLoan;
@Test(groups = "Main_TestCase")
public void testCarLoan() throws InterruptedException {
logger = report.createTest("Car Loan TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
landingPage = pageBase.OpenApplication();
carLoan = landingPage.navigateToCarLoan();
carLoan.setHomeAmountSlider("carLoanamountSlider_Xpath", 15, 20, 0);
carLoan.assertequals("15,00,000", carLoan.readText("carLoanamountTextBox_Xpath"));
carLoan.setInterestRateSlider("carInterestRateSlider_Xpath", 9.5, 20, 5);
carLoan.assertequals("9.5", carLoan.readText("carInterestRateTextBox_Xpath"));
carLoan.setLoanTenureSlider("carLoanTennureSlider_Xpath", 1, 7, 0);
carLoan.takeScreenShot();
carLoan.assertequals("1", carLoan.readText("carLoanTennureTextBox_Xpath"));
carLoan.displayEmiDetails();
carLoan.softAssert.assertAll();
}
@Test
public void verifyCarLoanPageNavigation() {
logger = report.createTest("Car Loan TestCase Report");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
landingPage = pageBase.OpenApplication();
carLoan = landingPage.navigateToCarLoan();
carLoan.assertequals("Car Loan Amount", pageBase.getElement("carLoanAmountText_CSS").getText());
carLoan.softAssert.assertAll();
}
@Test
public void verifyCarLoanAmountFieldForNumbericInputValue() {
logger = report
.createTest("To check that the application should accept numeric values in Car Loan Amount field.");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
landingPage = pageBase.OpenApplication();
carLoan = landingPage.navigateToCarLoan();
carLoan.clearFieldandGiveInput("carLoanamountTextBox_Xpath", "1500000");
carLoan.assertequals("15,00,000", carLoan.readText("carLoanamountTextBox_Xpath"));
carLoan.softAssert.assertAll();
}
@Test
public void verifyInterestRateFieldForNumbericInputValue() {
logger = report
.createTest("To check that the application should not accept alphabets in Car Loan Amount field.");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
landingPage = pageBase.OpenApplication();
carLoan = landingPage.navigateToCarLoan();
carLoan.clearFieldandGiveInput("carInterestRateTextBox_Xpath", "9.5");
carLoan.assertequals("9.5", carLoan.readText("carInterestRateTextBox_Xpath"));
carLoan.softAssert.assertAll();
}
@Test
public void verifyLoantennureFieldForNumbericInputValue() {
logger = report.createTest("To check that the application should accept numeric values in Loan Tenure field.");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
landingPage = pageBase.OpenApplication();
carLoan = landingPage.navigateToCarLoan();
carLoan.clearFieldandGiveInput("carLoanTennureTextBox_Xpath", "1");
carLoan.assertequals("1", carLoan.readText("carLoanTennureTextBox_Xpath"));
carLoan.softAssert.assertAll();
}
@Test
public void verifyCarLoanAmountFieldForAlphabeticInputValue() {
logger = report
.createTest("To check that the application should accept alphabetic values in Car Loan Amount field.");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
landingPage = pageBase.OpenApplication();
carLoan = landingPage.navigateToCarLoan();
carLoan.clearFieldandGiveInput("carLoanamountTextBox_Xpath", "qwerty");
carLoan.assertequals("qwerty", carLoan.readText("carLoanamountTextBox_Xpath"));
carLoan.softAssert.assertAll();
}
@Test
public void verifyInterestRateFieldForAlphabeticInputValue() {
logger = report.createTest(
"To check that the application should not accept alphabetics value in Car Loan Amount field.");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
landingPage = pageBase.OpenApplication();
carLoan = landingPage.navigateToCarLoan();
carLoan.clearFieldandGiveInput("carInterestRateTextBox_Xpath", "qwerty");
carLoan.assertequals("qwerty", carLoan.readText("carInterestRateTextBox_Xpath"));
carLoan.softAssert.assertAll();
}
@Test
public void verifyLoantennureFieldForAlphabeticInputValue() {
logger = report
.createTest("To check that the application should accept alphabetics values in Loan Tenure field.");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
landingPage = pageBase.OpenApplication();
carLoan = landingPage.navigateToCarLoan();
carLoan.clearFieldandGiveInput("carLoanTennureTextBox_Xpath", "qwerty");
carLoan.assertequals("qwerty", carLoan.readText("carLoanTennureTextBox_Xpath"));
carLoan.softAssert.assertAll();
}
@Test
public void verifyCarLoanAmountFieldForSpecialCharactersInputValue() {
logger = report.createTest(
"To check that the application should accept special characters values in Car Loan Amount field.");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
landingPage = pageBase.OpenApplication();
carLoan = landingPage.navigateToCarLoan();
carLoan.clearFieldandGiveInput("carLoanamountTextBox_Xpath", "!@#$%");
carLoan.assertequals("!@#$%", carLoan.readText("carLoanamountTextBox_Xpath"));
carLoan.softAssert.assertAll();
}
@Test
public void verifyInterestRateFieldForSpecialCharactersInputValue() {
logger = report.createTest(
"To check that the application should not accept special characters value in Car Loan Amount field.");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
landingPage = pageBase.OpenApplication();
carLoan = landingPage.navigateToCarLoan();
carLoan.clearFieldandGiveInput("carInterestRateTextBox_Xpath", "!@#$%");
carLoan.assertequals("!@#$%", carLoan.readText("carInterestRateTextBox_Xpath"));
carLoan.softAssert.assertAll();
}
@Test
public void verifyLoantennureFieldForSpecialCharactersInputValue() {
logger = report.createTest(
"To check that the application should accept special characters values in Loan Tenure field.");
invokeBrowser("chrome");
PageBaseClass pageBase = new PageBaseClass(driver, logger);
PageFactory.initElements(driver, pageBase);
landingPage = pageBase.OpenApplication();
carLoan = landingPage.navigateToCarLoan();
carLoan.clearFieldandGiveInput("carLoanTennureTextBox_Xpath", "!@#$%");
carLoan.assertequals("!@#$%", carLoan.readText("carLoanTennureTextBox_Xpath"));
carLoan.softAssert.assertAll();
}
}
| 7511221aa4d72a11c59f2d927023564e238f6b9e | [
"Java",
"HTML",
"INI"
] | 7 | Java | iamgovindthakur/interestCalculator | c10f83ab3025322d52775cc0affd1d3b75630fe8 | 4a74f21a44c5b8d8677461be79444a6398fffd9d | |
refs/heads/master | <file_sep># sketch-app
Paint style application for Android.
<file_sep>package com.just.sketchapp
import android.app.Application
import com.just.sketchapp.dialog.BitmapExportManager
import com.just.sketchapp.dialog.ColorPickerManager
import com.just.sketchapp.ui.ViewModelFactory
import com.todo.shakeit.core.ShakeIt
import org.kodein.di.Kodein
import org.kodein.di.KodeinAware
import org.kodein.di.android.x.androidXModule
import org.kodein.di.generic.bind
import org.kodein.di.generic.instance
import org.kodein.di.generic.provider
import org.kodein.di.generic.singleton
class SketchApp: Application(), KodeinAware {
override val kodein = Kodein.lazy {
import(androidXModule(this@SketchApp))
bind () from provider { ViewModelFactory() }
bind() from singleton { ColorPickerManager() }
bind() from singleton { BitmapExportManager() }
}
override fun onCreate() {
super.onCreate()
ShakeIt.init(this)
}
}
<file_sep>package com.just.sketchapp.ui
import android.Manifest
import android.content.Context
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Canvas
import android.hardware.Sensor
import android.hardware.SensorEventListener
import android.hardware.SensorListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ImageButton
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProviders
import com.just.sketchapp.databinding.ActivityMainBinding
import org.kodein.di.KodeinAware
import org.kodein.di.android.kodein
import org.kodein.di.generic.instance
import android.util.DisplayMetrics
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.library.baseAdapters.BR
import com.just.sketchapp.R
import com.just.sketchapp.dialog.BitmapExportManager
import com.just.sketchapp.dialog.ColorPickerManager
import com.todo.shakeit.core.ShakeDetector
import com.todo.shakeit.core.ShakeListener
import kotlinx.android.synthetic.main.activity_main.*
private const val MY_PERMISSION_WRITE_EXTERNAL_STORAGE = 1
class MainActivity : AppCompatActivity(), KodeinAware, ShakeListener {
override val kodein by kodein()
private val viewModelFactory: ViewModelFactory by instance()
private lateinit var mainViewModel: MainViewModel
private val colorPickerManager: ColorPickerManager by instance()
private val bitmapExportManager: BitmapExportManager by instance()
private lateinit var dialog: AlertDialog
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//init viewmodel and data binding
mainViewModel = ViewModelProviders.of(this, viewModelFactory).get(MainViewModel::class.java)
DataBindingUtil.setContentView<ActivityMainBinding>(
this, R.layout.activity_main
).apply {
this.lifecycleOwner = this@MainActivity
this.viewModel = mainViewModel
this.setVariable(BR.viewModel, mainViewModel)
this.executePendingBindings()
}
//init button listener
val colorButton = findViewById<ImageButton>(R.id.color)
colorButton?.setOnClickListener {
colorPickerManager.showColorPicker(this) {
mainViewModel.setColor(it)
}
}
val cancelButton = findViewById<ImageButton>(R.id.cancel)
cancelButton?.setOnClickListener {
mainViewModel.clearPaths()
}
val downloadButton = findViewById<ImageButton>(R.id.download)
downloadButton?.setOnClickListener {
val pics = findViewById<CanvasView>(R.id.canvasView)
requestWritePermission() // need to refactor requests
if (hasFilePermission()) {
if(bitmapExportManager.saveBitmap(this, canvasView))
Toast.makeText(this, "Saved successfully", Toast.LENGTH_SHORT).show()
}
}
}
private fun requestWritePermission() {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
1
)
}
private fun hasFilePermission(): Boolean {
return ContextCompat.checkSelfPermission(
this,
Manifest.permission.WRITE_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
}
override fun onShake() {
ShakeDetector.unRegisterForShakeEvent(this)
showDialog()
}
private fun showDialog() {
// Initialize a new instance of alert dialog builder object
var builder = AlertDialog.Builder(this).setMessage("Are you sure you want to delete your work permamently? ")
val dialogClickListener = DialogInterface.OnClickListener { _, which ->
when (which) {
DialogInterface.BUTTON_POSITIVE -> {mainViewModel.clearPaths()
ShakeDetector.registerForShakeEvent(this)}
DialogInterface.BUTTON_NEUTRAL -> ShakeDetector.registerForShakeEvent(this)
}
}
builder.setPositiveButton("YES", dialogClickListener)
builder.setNeutralButton("CANCEL", dialogClickListener)
dialog = builder.create()
dialog.show()
}
override fun onPause() {
ShakeDetector.unRegisterForShakeEvent(this)
super.onPause()
}
override fun onResume() {
ShakeDetector.registerForShakeEvent(this)
super.onResume()
}
}
<file_sep>package com.just.sketchapp.dialog
import android.content.Context
import android.content.DialogInterface
import com.just.sketchapp.R
import com.skydoves.colorpickerview.ColorEnvelope
import com.skydoves.colorpickerview.ColorPickerDialog
import com.skydoves.colorpickerview.listeners.ColorEnvelopeListener
class ColorPickerManager {
fun showColorPicker(context: Context, onConfirmButton: (Int) -> Unit) {
ColorPickerDialog.Builder(context, R.style.Theme_AppCompat_Dialog_Alert)
.setTitle("Choose your brush color")
.setPositiveButton("ok", object: ColorEnvelopeListener{
override fun onColorSelected(envelope: ColorEnvelope?, fromUser: Boolean) {
onConfirmButton(envelope!!.color)
}
})
.setNegativeButton("cancel", object: DialogInterface.OnClickListener{
override fun onClick(dialog: DialogInterface?, which: Int) {
dialog?.dismiss()
}
})
.setPreferenceName("MyColorPicker")
.show()
}
}<file_sep>package com.just.sketchapp.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
class ViewModelFactory : ViewModelProvider.NewInstanceFactory(){
}<file_sep>package com.just.sketchapp.data
import android.graphics.Path
data class FingerPath(val color:Int, val brushSize: Int, val path: Path)
<file_sep>package com.just.sketchapp.ui
import android.content.Context
import android.graphics.*
import android.view.View
import android.util.AttributeSet
import android.view.MotionEvent
import com.just.sketchapp.data.FingerPath
import kotlin.math.absoluteValue
import android.graphics.Bitmap
import androidx.annotation.ColorInt
class CanvasView(context: Context, attr: AttributeSet?): View(context, attr){
private var brushSize: Int = 0
private var brushColor : Int = Color.WHITE
private val backgroundColor: Int = Color.WHITE
private val touchTolerance:Float = 4.0f
private var mX :Float? = null
private var mY :Float? = null
private var paths = mutableListOf<FingerPath>()
private lateinit var path: Path
private var paint: Paint
private lateinit var bitmap: Bitmap
private val mCanvas: Canvas
private var bitmapPaint: Paint = Paint(Paint.DITHER_FLAG)
fun setColor(@ColorInt color: Int) {
brushColor = color
paint.color = brushColor
}
fun setSize(size: Int) {
brushSize = size
}
fun setPaths(path: MutableList<FingerPath>) {
paths = path
invalidate()
}
init{
paint= Paint()
paint.isAntiAlias = true
paint.isDither = true
paint.color = brushColor
paint.style = Paint.Style.STROKE
paint.strokeJoin = Paint.Join.ROUND
paint.strokeCap = Paint.Cap.ROUND
paint.xfermode = null
paint.alpha = 0xff
bitmap = Bitmap.createBitmap(context.resources.displayMetrics.widthPixels, context.resources.displayMetrics.heightPixels, Bitmap.Config.ARGB_8888)
mCanvas = Canvas(bitmap)
}
private fun touchStart(x: Float, y: Float){
path = Path()
val fp = FingerPath(brushColor, brushSize, path)
paths.add(fp)
path.reset()
path.moveTo(x,y)
mX = x
mY = y
}
private fun touchMove(x: Float, y:Float) {
(mX != null && mY != null).let {
val dx = (x - mX!!).absoluteValue
val dy = (y - mY!!).absoluteValue
if (dx >= touchTolerance && dy >= touchTolerance) {
path.quadTo(mX!!, mY!!, (x + mX!!) / 2, (y + mY!!) / 2)
mX = x
mY = y
}
}
}
private fun touchUp(){
(mX != null && mY != null ).let {
path.lineTo(mX!!, mY!!)
}
}
override fun onDraw(canvas: Canvas) {
canvas.save()
mCanvas.drawColor(backgroundColor)
paths.forEach {
paint.color = it.color
paint.strokeWidth = it.brushSize.toFloat()
paint.maskFilter = null
mCanvas.drawPath(it.path, paint)
}
canvas.drawBitmap(bitmap, 0.0f, 0.0f, bitmapPaint)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val x = event.x
val y = event.y
when(event.action){
MotionEvent.ACTION_DOWN -> {
touchStart(x, y)
invalidate()}
MotionEvent.ACTION_MOVE -> {
touchMove(x, y)
invalidate() }
MotionEvent.ACTION_UP -> {
touchUp()
invalidate()
}
}
return true
}
}<file_sep>package com.just.sketchapp.dialog
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.provider.MediaStore
import android.util.Log
import android.view.View
import com.just.sketchapp.data.FingerPath
class BitmapExportManager{
private fun createBitmapFromView(canvas: View): Bitmap {
val bitmap = Bitmap.createBitmap(canvas.measuredWidth, canvas.measuredHeight, Bitmap.Config.ARGB_8888)
canvas.draw(Canvas(bitmap))
return bitmap
}
fun saveBitmap(context: Context, canvas: View): Boolean {
val bitmap = createBitmapFromView(canvas)
try {
MediaStore.Images.Media.insertImage(context.contentResolver, bitmap, "new", null)
} catch (e: Exception) {
Log.d("EXPORT ERROR", e.message)
return false
}
return true
}
}
<file_sep>package com.just.sketchapp.ui
import android.graphics.Color
import android.widget.SeekBar
import androidx.lifecycle.*
import com.just.sketchapp.data.FingerPath
class MainViewModel: ViewModel() {
private var _paths = MutableLiveData<MutableList<FingerPath>?>()
private val _color = MutableLiveData<Int?>()
private val _size = MutableLiveData<Int?>()
init{
_color.value = Color.RED
_paths.value = mutableListOf()
_size.value =30
}
fun getColor(): LiveData<Int?> = _color
fun setColor(color: Int){
_color.value = color
}
fun setPaths(paths: MutableList<FingerPath>){
_paths.value = paths
}
fun getPaths(): LiveData<MutableList<FingerPath>?> = _paths
fun getSize(): LiveData<Int?> = _size
fun onSizeChanged(seekBar: SeekBar, progressValue: Int, fromUser: Boolean) {
_size.value = progressValue
}
fun clearPaths(){
setPaths(mutableListOf<FingerPath>())
}
}
<file_sep>package com.just.sketchapp.data
class DrawingRepo {} | 72f8ef2834d7dc0b9b6547aa22fd3f23a33cae0b | [
"Markdown",
"Kotlin"
] | 10 | Markdown | justynias/sketch-app | 4c2a9b3b7d2e9621cd3c50f3271b4ebb9970e119 | b1fd67a81fff52b60f8f993a990b0de5f0711517 | |
refs/heads/master | <file_sep>#!/usr/bin/env bash
# download the latest version
# I need verify if exists in directory currently exist version specific whatelse I need to download
# create variavle for resuse go version and go complete name
# wget -c https://storage.googleapis.com/golang/go1.11.1.linux-amd64.tar.gz && \
# check the integrit
shasum -a 256 go1.11.1.linux-amd64.tar.gz && \
# remove go source if you have it
# I need to verify if exist go in this path, if exist remove that
sudo rm -r /usr/local/go && \
# Extract archive and copy right path
sudo tar -C /usr/local -xvzf go1.11.1.linux-amd64.tar.gz
# create the above directory tree as follows
mkdir -p ~/go_projects/{bin,src,pkg} && \
#
cd ~/go_projects
# show directory
ls
# Add path environment variable
export PATH=$PATH:/usr/local/go/bin && \
# set values
export GOPATH="$HOME/go_projects" && \
export GOBIN="$GOPATH/bin" && \
# If I installed GoLang in a custom directory I need specify that directory as value of GOROOT variable.
# export GOROOT=$HOME/go && \
# export PATH=$PATH:$GOROOT/bin && \
# changes made to the user profile in the current bash session
source ~/.profile
# or
# source ~/.bash_profile
# verify Golang Installation
go version
go env
# https://www.tecmint.com/install-go-in-linux/ | 2824946472b0e0ac2b73ffcec5a2faf5a5c4f87d | [
"Shell"
] | 1 | Shell | astesio/go-path-install | eb75172b3acb94276b3dd62a2aae5226e060bade | cb54c0b1e5a4dbed22fa7404cd9d8765458b6796 | |
refs/heads/master | <repo_name>AndreyVMarkelov/delete-all-attachments<file_sep>/src/main/java/ru/andreymarkelov/atlas/plugins/attrrem/action/DeleteAttachAction.java
package ru.andreymarkelov.atlas.plugins.attrrem.action;
import java.util.Collection;
import com.atlassian.jira.bc.JiraServiceContext;
import com.atlassian.jira.bc.JiraServiceContextImpl;
import com.atlassian.jira.bc.issue.attachment.AttachmentService;
import com.atlassian.jira.config.SubTaskManager;
import com.atlassian.jira.exception.RemoveException;
import com.atlassian.jira.issue.AttachmentManager;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.attachment.Attachment;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.security.JiraAuthenticationContext;
import com.atlassian.jira.security.PermissionManager;
import com.atlassian.jira.security.xsrf.RequiresXsrfCheck;
import com.atlassian.jira.web.action.issue.AbstractViewIssue;
import ru.andreymarkelov.atlas.plugins.attrrem.manager.AttacherMgr;
import static com.atlassian.jira.permission.ProjectPermissions.DELETE_ALL_ATTACHMENTS;
public class DeleteAttachAction extends AbstractViewIssue {
private static final long serialVersionUID = 2431906489689708128L;
private final AttacherMgr attacherMgr;
private final JiraAuthenticationContext authenticationContext;
private final PermissionManager permissionManager;
private final AttachmentService attachmentService;
private final AttachmentManager attachmentManager;
public DeleteAttachAction(
SubTaskManager subTaskManager,
AttacherMgr attacherMgr,
JiraAuthenticationContext authenticationContext,
PermissionManager permissionManager,
AttachmentService attachmentService,
AttachmentManager attachmentManager) {
super(subTaskManager);
this.attacherMgr = attacherMgr;
this.authenticationContext = authenticationContext;
this.permissionManager = permissionManager;
this.attachmentService = attachmentService;
this.attachmentManager = attachmentManager;
}
@Override
@RequiresXsrfCheck
protected String doExecute() {
MutableIssue issue = this.getMutableIssue();
if (!hasPermission(issue.getProjectObject())) {
addErrorMessage(authenticationContext.getI18nHelper().getText("ru.andreymarkelov.atlas.plugins.attrrem.action.error.permission"));
return ERROR;
}
JiraServiceContext jiraServiceContext = new JiraServiceContextImpl(authenticationContext.getLoggedInUser());
Collection<Attachment> attachments = issue.getAttachments();
for (Attachment attachment : attachments) {
try {
attachmentService.delete(jiraServiceContext, attachment.getId());
attachmentManager.deleteAttachment(attachment);
} catch (RemoveException e) {
addErrorMessage(authenticationContext.getI18nHelper().getText("ru.andreymarkelov.atlas.plugins.attrrem.action.error.file", attachment.getFilename()));
return ERROR;
}
}
return redirect();
}
private boolean hasPermission(Project project) {
if (attacherMgr.isActiveForAll()) {
return true;
}
if (project != null) {
String[] projectKeys = attacherMgr.getProjectKeys();
if (projectKeys != null) {
for (String projectKey : projectKeys) {
if (projectKey.equals(project.getId().toString())) {
return permissionManager.hasPermission(DELETE_ALL_ATTACHMENTS, getIssueObject(), getLoggedInUser());
}
}
}
}
return false;
}
private String redirect() {
return isInlineDialogMode() ? returnComplete() : getRedirect("/browse/" + getIssue().getString("key"));
}
}
<file_sep>/src/main/resources/ru/andreymarkelov/atlas/plugins/attrrem/i18n/attachdeleter.properties
ru.andreymarkelov.atlas.plugins.attrrem.section=Delete All Attachments
ru.andreymarkelov.atlas.plugins.attrrem.settings.title=Delete All Attachments Settings
ru.andreymarkelov.atlas.plugins.attrrem.settings.desc=On this page you can configure projects when Delete All Attachments will be available.
ru.andreymarkelov.atlas.plugins.attrrem.settings.selectprojects=Projects
ru.andreymarkelov.atlas.plugins.attrrem.settings.selectprojects.desc=Choose projects where delete all attachments action will be available.
ru.andreymarkelov.atlas.plugins.attrrem.settings.allprojects=All Projects
ru.andreymarkelov.atlas.plugins.attrrem.settings.allprojects.desc=Choose if you want for all projects.
ru.andreymarkelov.atlas.plugins.attrrem.settings.save=Save
ru.andreymarkelov.atlas.plugins.attrrem.settings.success.text=Data was stored successfully.
ru.andreymarkelov.atlas.plugins.attrrem.action=Delete All Attachments
ru.andreymarkelov.atlas.plugins.attrrem.action.desc=Delete all issue attachements if you have permission.
ru.andreymarkelov.atlas.plugins.attrrem.action.confirm=Are you sure that you want to delete all attachments?
ru.andreymarkelov.atlas.plugins.attrrem.action.error=Error deleting all attachments
ru.andreymarkelov.atlas.plugins.attrrem.action.error.file=Error during deleting attachment "{0}"
ru.andreymarkelov.atlas.plugins.attrrem.action.error.permission=There are no permissions to delete all attachments. Please, contact to administrators.
ru.andreymarkelov.atlas.plugins.attrrem.postfunction.attachdelete.name=Delete All Attachments
ru.andreymarkelov.atlas.plugins.attrrem.postfunction.attachdelete.desc=This function deletes all attachments if an executor has permissions.
<file_sep>/src/main/java/ru/andreymarkelov/atlas/plugins/attrrem/workflow/function/DeleteAttachmentsFunctionFactory.java
package ru.andreymarkelov.atlas.plugins.attrrem.workflow.function;
import java.util.Collections;
import java.util.Map;
import com.atlassian.jira.plugin.workflow.AbstractWorkflowPluginFactory;
import com.atlassian.jira.plugin.workflow.WorkflowPluginFunctionFactory;
import com.opensymphony.workflow.loader.AbstractDescriptor;
public class DeleteAttachmentsFunctionFactory extends AbstractWorkflowPluginFactory implements WorkflowPluginFunctionFactory {
@Override
public Map<String, ?> getDescriptorParams(Map<String, Object> descriptorParams) {
return Collections.emptyMap();
}
@Override
protected void getVelocityParamsForEdit(Map<String, Object> velocityParams, AbstractDescriptor descriptor) {
}
@Override
protected void getVelocityParamsForInput(Map<String, Object> velocityParams) {
}
@Override
protected void getVelocityParamsForView(Map<String, Object> velocityParams, AbstractDescriptor descriptor) {
}
}
<file_sep>/src/main/java/ru/andreymarkelov/atlas/plugins/attrrem/condition/AttachDeleterCondition.java
package ru.andreymarkelov.atlas.plugins.attrrem.condition;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.plugin.webfragment.conditions.AbstractIssueWebCondition;
import com.atlassian.jira.plugin.webfragment.model.JiraHelper;
import com.atlassian.jira.security.PermissionManager;
import com.atlassian.jira.user.ApplicationUser;
import ru.andreymarkelov.atlas.plugins.attrrem.manager.AttacherMgr;
import static com.atlassian.jira.permission.ProjectPermissions.DELETE_ALL_ATTACHMENTS;
public class AttachDeleterCondition extends AbstractIssueWebCondition {
private final AttacherMgr attacherMgr;
private final PermissionManager permissionManager;
public AttachDeleterCondition(PermissionManager permissionManager, AttacherMgr attacherMgr) {
this.permissionManager = permissionManager;
this.attacherMgr = attacherMgr;
}
public boolean shouldDisplay(ApplicationUser user, Issue issue, JiraHelper jiraHelper) {
if (attacherMgr.isActiveForAll()) {
return true;
}
if (issue != null && issue.getKey() != null) {
String[] projectKeys = attacherMgr.getProjectKeys();
if (projectKeys != null) {
for (String projectKey : projectKeys) {
if (projectKey.equals(issue.getProjectObject().getId().toString())) {
return permissionManager.hasPermission(DELETE_ALL_ATTACHMENTS, issue, user);
}
}
}
}
return false;
}
}
<file_sep>/README.md
# Delete All Attachments
Multiple Attachment Delete for Jira.
<file_sep>/src/main/resources/ru/andreymarkelov/atlas/plugins/attrrem/js/attach-deleter.js
AJS.$(function($) {
var initDialogTriggers = function(context) {
AJS.$(".issueaction-delete-all-attachments", context || document.body).each(function() {
new JIRA.FormDialog({
trigger: this,
id: this.id + '-dialog',
ajaxOptions: {
url: this.href,
data: { decorator: 'dialog', inline: 'true' }
}
});
});
};
JIRA.bind(JIRA.Events.NEW_CONTENT_ADDED, function (event, context, reason) {
initDialogTriggers(context);
});
initDialogTriggers();
});
<file_sep>/src/main/java/ru/andreymarkelov/atlas/plugins/attrrem/action/AttachDeleterConfig.java
package ru.andreymarkelov.atlas.plugins.attrrem.action;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.atlassian.jira.permission.GlobalPermissionKey;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.project.ProjectManager;
import com.atlassian.jira.security.GlobalPermissionManager;
import com.atlassian.jira.security.xsrf.RequiresXsrfCheck;
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.jira.web.action.JiraWebActionSupport;
import ru.andreymarkelov.atlas.plugins.attrrem.manager.AttacherMgr;
public class AttachDeleterConfig extends JiraWebActionSupport {
private static final long serialVersionUID = -8881690781888724545L;
private final AttacherMgr attacherMgr;
private final ProjectManager projectManager;
private final GlobalPermissionManager globalPermissionManager;
private boolean isSaved = false;
private List<String> savedProjKeys;
private String[] selectedProjKeys;
private boolean forAllProjects;
public AttachDeleterConfig(
AttacherMgr attacherMgr,
ProjectManager projectManager,
GlobalPermissionManager globalPermissionManager) {
this.attacherMgr = attacherMgr;
this.projectManager = projectManager;
this.globalPermissionManager = globalPermissionManager;
}
@Override
public String doDefault() {
if(!hasAdminPermission()) {
return PERMISSION_VIOLATION_RESULT;
}
this.forAllProjects = attacherMgr.isActiveForAll();
this.selectedProjKeys = attacherMgr.getProjectKeys();
this.savedProjKeys = selectedProjKeys == null ? null : Arrays.asList(selectedProjKeys);
return INPUT;
}
@Override
@RequiresXsrfCheck
protected String doExecute() {
if(!hasAdminPermission()) {
return PERMISSION_VIOLATION_RESULT;
}
attacherMgr.setActiveForAll(forAllProjects);
attacherMgr.setProjectKeys(selectedProjKeys);
if (selectedProjKeys != null) {
savedProjKeys = Arrays.asList(attacherMgr.getProjectKeys());
}
setSaved(true);
return getRedirect("AttachDeleterConfig!default.jspa?saved=true");
}
public Map<String, String> getAllProjects() {
Map<String, String> allProjs = new TreeMap<String, String>();
List<Project> projects = projectManager.getProjectObjects();
if (projects != null) {
for (Project project : projects) {
allProjs.put(project.getId().toString(), getProjView(project.getKey(), project.getName()));
}
}
return allProjs;
}
private String getProjView(String key, String name) {
return (key + ": " + name);
}
public List<String> getSavedProjKeys() {
return savedProjKeys;
}
public String[] getSelectedProjKeys() {
return selectedProjKeys;
}
public boolean hasAdminPermission() {
ApplicationUser user = getLoggedInUser();
if (user == null) {
return false;
}
return globalPermissionManager.hasPermission(GlobalPermissionKey.ADMINISTER, user);
}
public boolean isSaved() {
return isSaved;
}
public void setSaved(boolean isSaved) {
this.isSaved = isSaved;
}
public void setSavedProjKeys(List<String> savedProjKeys) {
this.savedProjKeys = savedProjKeys;
}
public void setSelectedProjKeys(String[] selectedProjKeys) {
this.selectedProjKeys = selectedProjKeys;
}
public boolean isForAllProjects() {
return forAllProjects;
}
public void setForAllProjects(boolean forAllProjects) {
this.forAllProjects = forAllProjects;
}
}
<file_sep>/src/main/resources/ru/andreymarkelov/atlas/plugins/attrrem/js/admin-attach-deleter.js
AJS.toInit(function () {
});
| d632df3391952c4d01ecbbe4cacf30def665d847 | [
"Markdown",
"Java",
"JavaScript",
"INI"
] | 8 | Java | AndreyVMarkelov/delete-all-attachments | 08f5402d2fb43c4a5c9a28a40ef3769fa6b777c5 | ca73bdd949c3ab5bda2dba6b41e05167fbad8ced |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.