branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep># Project: Bike Share Rental # Author : <NAME> # Date : 11-11-2015 # Bike rentals feature selection # loading files CHANGE AS PER REQUIREMENT train <- read.csv("~/Desktop/train.csv") test <- read.csv("~/Desktop/test.csv") #libraries required library(ggplot2) library(lubridate) library(randomForest) # processing data extractFeatures <- function(data) { features <- c("season", "holiday", "workingday", "weather", "temp", "atemp", "humidity", "windspeed", "hour") data$hour <- hour(ymd_hms(data$datetime)) return(data[,features]) } trainF <- extractFeatures(train) testF <- extractFeatures(test) submission <- data.frame(datetime=test$datetime, count=NA) # Only past data is used to make predictions on the test set, for (i_year in unique(year(ymd_hms(test$datetime)))) { for (i_month in unique(month(ymd_hms(test$datetime)))) { cat("Year: ", i_year, "\tMonth: ", i_month, "\n") testLocs <- year(ymd_hms(test$datetime))==i_year & month(ymd_hms(test$datetime))==i_month testSubset <- test[testLocs,] trainLocs <- ymd_hms(train$datetime) <= min(ymd_hms(testSubset$datetime)) rf <- randomForest(extractFeatures(train[trainLocs,]), train[trainLocs,"count"], ntree=100) output[testLocs, "count"] <- predict(rf, extractFeatures(testSubset)) } } write.csv(output, file = "1_random_forest_submission.csv", row.names=FALSE) # Train a model across all the training data and plot the variable importance rf <- randomForest(extractFeatures(train), train$count, ntree=100, importance=TRUE) imp <- importance(rf, type=1) featureImportance <- data.frame(Feature=row.names(imp), Importance=imp[,1]) plot <- ggplot(featureImportance, aes(x=reorder(Feature, Importance), y=Importance)) + geom_bar(stat="identity", fill="#00ff00") + coord_flip() + theme_light(base_size=20) + xlab("Importance") + ylab("Importance level") + ggtitle("Random Forest Feature Importance\n") + theme(plot.title=element_text(size=18)) ggsave("2_feature_importance.png", plot) <file_sep># Project: Predict Bike Sharing Demand using R # Author : <NAME> # Date : 11-14-2015 # Random Forest tree prediction of count # loading files CHANGE AS PER REQUIREMENT train <- read.csv("~/Desktop/train.csv") test <- read.csv("~/Desktop/test.csv") #install libraries library(lubridate) library(randomForest) #pre processing--------------- #Compute hour of the day train$hour <-hour(train$datetime) train$dow <- wday(train$datetime) test$hour <- hour(test$datetime) #Compute day of the week test$dow <- wday(test$datetime) test$count<-0 #---------------------------- #Create a random forest fit <- randomForest(as.factor(count) ~ season + weather + dow + hour + temp + humidity , data=train, ntree = 250, importance=TRUE) varImpPlot(fit) #Predict values and save output Prediction <- predict(fit, test) output <- data.frame(datetime = test$datetime, count = Prediction) summary(train) write.csv(output, file = "randomforestOutputfeature.csv", row.names = FALSE) <file_sep># Project: Bike Share Rental # Author : <NAME> # Date : 11-11-2015 #Linear Regression for predicting count # loading files CHANGE AS PER REQUIREMENT train <- read.csv("~/Desktop/train.csv") test <- read.csv("~/Desktop/test.csv") #install libraries library(lubridate) library(lmtest) library(miscTools) library(boot) #Preprocessing ---------- #Compute hour of the day train$hour <-hour(train$datetime) test$hour <- hour(test$datetime) #Compute day of the week test$dow <- wday(test$datetime) train$dow <- wday(train$datetime) test$count<-0 #------------------------ # apply Linear regression model <- lm(count ~season+ temp+ dow+workingday+weather+humidity, data = train) plot(count ~ ., data = train) meancount <- mean(test$count) abline(h=meancount) abline(model,col="red") plot(model) pre <- predict(model,test) coeftest(model) fitted(model) # predicted values residuals(model) # residuals anova(model) # anova table vcov(model) #covariance matrix layout(matrix(c(1,2,3,4),2,2)) # 4 graphs/page plot(model) (r21 <- rSquared(test$count, test$count - pre)) (mse <- mean ((test$count - pre))^2) #predict the test cases and write in a file output <- data.frame(datetime = test$datetime, count = pre) write.csv(output, file = "LinearRegression1.csv", row.names = FALSE) <file_sep># Project: Bike Share Rental # Author : <NAME> # Date : 11-11-2015 # Bike rentals vs weekdays # loading files CHANGE AS PER REQUIREMENT train <- read.csv("~/Desktop/train.csv") #include libraries library(ggplot2) library(lubridate) library(readr) library(scales) #pre processing data train$hour <- hour(ymd_hms(train$datetime)) train$times <- as.POSIXct(strftime(ymd_hms(train$datetime), format="%H:%M:%S"), format="%H:%M:%S") train$day <- wday(ymd_hms(train$datetime), label=TRUE) #plotting the graph plot <- ggplot(train, aes(x=times, y=count, color=day)) + geom_smooth(ce=FALSE, fill=NA, size=2) + theme_light(base_size=20) + xlab("Hour") + scale_x_datetime(breaks = date_breaks("4 hours"), labels=date_format("%I:%M %p")) + ylab("# of Bike Rentals") + scale_color_manual(values = c("red","green","blue","cyan","orange","magenta","yellow")) + ggtitle("People rent bikes commutes on weekdays and weekends\n") + theme(plot.title=element_text(size=12)) ggsave("#bikerental_day.png") <file_sep># Project: Bike Share Rental # Author : <NAME> # Date : 11-09-2015 #Decision tree and predict if biking is YES or NO # loading files CHANGE AS PER REQUIREMENT train <- read.csv("~/Desktop/train.csv") test <- read.csv("~/Desktop/test.csv") #install libraries library(lubridate) library(rpart) library(caret) library(FSelector) library(e1071) library(party) #Preprocessing ---------- #Compute hour of the day train$hour <-hour(train$datetime) test$hour <- hour(test$datetime) #Compute day of the week test$dow <- wday(test$datetime) train$dow <- wday(train$datetime) test$count<-0 #------------------------ #create binary count attribute train$binarycount <- cut(train$count,br=c(-1,250,10000), labels= c("no","yes")) test$binarycount <- cut(test$count,br=c(-1,250,10000), labels= c("no","yes")) #entropy calculation weights <- information.gain(binarycount~., train) print(weights) #create decision tree fit <- ctree(binarycount ~ dow + hour + temp + humidity +season +holiday+workingday+weather+windspeed, data = train) #summary(fit) #prune the tree #pfit <- prune(fit,cp=fit$cptable[which.min(fit$cptable[,"xerror"]),"CP"]) #print the tree #plot(fit, uniform = T, compress = T, margin = 0.1, branch = 0.3) #text(fit, use.n = T, digits = 3, cex = 0.6) #predict the test cases and write in a file pre <- predict(fit,test)#,type="class") #confusion matrix confusionMatrix(pre,test$binarycount) output <- data.frame(datetime = test$datetime, binarycount = pre) write.csv(output, file = "DecisionBinary11.csv", row.names = FALSE) <file_sep># Project: Bike Share Rental # Author : <NAME> # Date : 11-09-2015 #Time vs #of rentals plot with Temperature and Humidity variation # loading files CHANGE AS PER REQUIREMENT train <- read.csv("~/Desktop/train.csv") test <- read.csv("~/Desktop/test.csv") # libraries required library(ggplot2) library(lubridate) library(scales) #axis definition x_axis <- "jitter_times" y_axis <- "count" color <- "temp" # can be replaced by Humidity #preprocessing train$hour <- hour(ymd_hms(train$datetime)) train$times <- as.POSIXct(strftime(ymd_hms(train$datetime), format="%H:%M:%S"), format="%H:%M:%S") train$jitter_times <- train$times+minutes(round(runif(nrow(train),min=0,max=59))) train$day <- wday(ymd_hms(train$datetime), label=TRUE) #generating the plot plot <- ggplot(train[train$workingday==1,], aes_string(x=x_axis, y=y_axis, color=color)) + geom_point(position=position_jitter(w=0.0, h=0.8)) + theme_light(base_size=12) + xlab("Hour") + scale_x_datetime(breaks = date_breaks("4 hours"), labels=date_format("%I:%M %p")) + ylab("# of Bike Rental") + scale_colour_gradientn("Temp(°C))", colours=c("#9400D3","#4B0082", "#0000FF", "#00FF00", "#FFFF00", "#FF7F00", "#FF0000")) + theme(plot.title=element_text(size=11)) ggsave("#ofbikerental_vs_time_temp.png", plot)
f33716c3b10dd372ee68e13956c04b0a8b84e0d2
[ "R" ]
6
R
shrirang91/BikeShareDemand
7865143bca578b41c86a66aa89aa87f52658b8d0
1b5bc11a5c16904da377f4e7dd67a7a6743a33e7
refs/heads/master
<file_sep> // This child of Straight is specific for a large straight public class LargeStraight extends Straight { public LargeStraight() { straight = 5; upperOrLower = lower; } @Override public void setScore(Die[] dice, boolean wildCard) { if(isScorable(dice, wildCard)) { this.score = 40; } else { setZeroScore(); } } } <file_sep>import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.Stack; import javax.swing.ImageIcon; import javax.swing.JOptionPane; // This is the class for the game logic public class YahtzeeGame implements Serializable { Die[] dice; int roll = 1; boolean endOfRound; boolean wildCard; boolean bonus; ScoreCard scoreCard; Stack<Round> rounds; public YahtzeeGame() { dice = new Die[5]; for(int i = 0; i < dice.length; ++i) { dice[i] = new Die(); } scoreCard = new ScoreCard(); rounds = new Stack<Round>(); roll = 1; endOfRound = false; wildCard = false; bonus = false; } // roll for a new set of die faces public Die[] roll() { if (!endOfRound) { if (roll <= 3) { for (int i = 0; i < dice.length; ++i) { // If a die is held, do not roll for a new one if (dice[i].isHeld() != true) { dice[i] = new Die(); //TESTING ONLY- COMMENT OUT AFTER TESTING // dice[i].setDieFace(5); //------------------------------------------l } } //TESTING FULL HOUSE. DELETE // dice[0].setDieFace(2); // dice[1].setDieFace(2); // dice[2].setDieFace(3); // dice[3].setDieFace(3); // dice[4].setDieFace(3); //---------------------------- } ++roll; } return dice; } // This method sets all the dice to be unheld public void unholdDice() { for (int i = 0; i < dice.length;++i) { dice[i].setHeld(false); } } // this method initiates the next round public void nextRound() { if (!bonus) { roll = 1; unholdDice(); endOfRound = false; } } //Score a category for the current round /** * @param category * @return */ public boolean scoreRound(Categories category) { boolean roundScored = false; // there are five checks below to score for the round. // first, check to see if a bonus chip has been used(1). if it has, the player must take a zero in a category. // then, check to see if a wild card can be used(2). if so, player gets full points in a lower category even if they // do not have the required dice. // then, if it is not already the end of the round(3), check to see if the attempted category is a yahtzee(4). // if it is not, the category is scored normally. Otherwise, special yahtzee rules are put into play(bonuses and wild cards). // the final check looks at whether the round was scored on the score card(or, in the yahtzee category, how many times its been scored)(5). // player cannot take a zero in the yahtzee category if (!bonus) //(1) { if (scoreCard.yahtzee.isScorable(dice, wildCard) && (scoreCard.yahtzee.getScored() > 3))//(2) { wildCard = true; } if (!endOfRound)//(3) { if (!(category.equals(Categories.YAHTZEE)))//(4) { if (scoreCard.scoreRound(dice, category, wildCard))//(5) { rounds.push(new Round((rounds.size() + 1), scoreCard.getCategory(category))); // System.out.println(rounds.peek().getRoundNum() + ", " // + rounds.peek().getCategoryScored() + ", " // + rounds.peek().getPointsScored()); // for debugging endOfRound = true; roundScored = true; } } else if(scoreCard.yahtzee.getScored() < 4 && scoreCard.yahtzee.isScorable(dice, wildCard))//(5) { scoreCard.scoreYahtzee(dice); rounds.push(new Round((rounds.size() + 1), scoreCard.getCategory(category))); // System.out.println(rounds.peek().getRoundNum() + ", " // + rounds.peek().getCategoryScored() + ", " // + rounds.peek().getPointsScored()); // for debugging if (scoreCard.yahtzee.getScored() < 2) { endOfRound = true; } else { JOptionPane.showMessageDialog(null , "Choose a category to take a zero in."); bonus = true; } roundScored = true; } } // System.out.println(rounds.peek().getRoundNum() + ", " // + rounds.peek().getCategoryScored() + ", " // + rounds.peek().getPointsScored()); // for debugging } else//(1) { if (category != Categories.YAHTZEE) { scoreCard.takeZero(category); endOfRound = true; roundScored = true; // System.out.println(rounds.peek().getRoundNum() + ", " // + rounds.peek().getCategoryScored() + ", " // + rounds.peek().getPointsScored()); // for debugging } } wildCard = false; return roundScored; } //get the score for the current round public int getPointsForCurrentRound() { if (!bonus) { if (!rounds.isEmpty()) { Round currentRound = rounds.peek(); return currentRound.getPointsScored(); } else { return 0; } } else { bonus = false; return 0; } } public int getLowerScore() { return scoreCard.getLowerScore(); } public int getUpperScore() { return scoreCard.getUpperScore(); } public int getTotalScore() { return scoreCard.getTotalScore(); } // this method change the hold state of a die public void holdDie(int dieNumber) { if(dice[dieNumber].isHeld() == true) { dice[dieNumber].setHeld(false); dice[dieNumber].setDieImage(new ImageIcon(getClass().getClassLoader().getResource("die"+dice[dieNumber].getDieFace()+".jpg"))); } else { dice[dieNumber].setHeld(true); dice[dieNumber].setDieImage(new ImageIcon(getClass().getClassLoader().getResource("die"+dice[dieNumber].getDieFace()+"held.jpg"))); } } public Die[] getDice() { return dice; } public void newGame() { scoreCard = new ScoreCard(); rounds.removeAllElements(); } public void loadGame(File savedGame) { YahtzeeGame yg; try { FileInputStream fis = new FileInputStream(savedGame); ObjectInputStream ois = new ObjectInputStream(fis); try { yg = (YahtzeeGame) ois.readObject(); //System.out.println(yg.getUpperScore()); dice = yg.dice; roll = yg.roll; endOfRound = yg.endOfRound; wildCard = yg.wildCard; bonus = yg.bonus; scoreCard = yg.scoreCard; rounds = yg.rounds; } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } ois.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void changeRound(int roundNum) { while(roundNum <= rounds.size()) { scoreCard.removeRound(rounds.peek().getCategoryScored(), rounds.peek().getPointsScored()); rounds.pop(); } roll(); } } <file_sep> public class Sixes extends ScoreCategory { public Sixes() { upperOrLower = upper; } @Override public void setScore(Die[] dice, boolean wildCard) { for(Die element: dice) { if(element.getDieFace() == 6) { this.score += 6; } } } } <file_sep>// This is the GUI for the Yahtzee game import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JTextField; public class GameBoard extends JFrame { //create the menu bar JMenuBar menuBar; //file menu JMenu fileMenu; JMenuItem newGameMenuItem; JMenuItem saveGameMenuItem; JMenuItem loadGameMenuItem; JMenuItem exitGameMenuItem; //Round menu JMenu roundMenu; JMenuItem lastRoundMenuItem; JMenu roundSelectMenu; JMenuItem round1MenuItem; JMenuItem round2MenuItem; JMenuItem round3MenuItem; JMenuItem round4MenuItem; JMenuItem round5MenuItem; JMenuItem round6MenuItem; JMenuItem round7MenuItem; JMenuItem round8MenuItem; JMenuItem round9MenuItem; JMenuItem round10MenuItem; JMenuItem round11MenuItem; JMenuItem round12MenuItem; JMenuItem round13MenuItem; //Array of the round menu items for convenience later JMenuItem[] roundMenuItems = {round1MenuItem,round2MenuItem,round3MenuItem,round4MenuItem,round5MenuItem,round6MenuItem,round7MenuItem,round8MenuItem, round9MenuItem,round10MenuItem,round11MenuItem,round12MenuItem,round13MenuItem,}; // Panels for all the components JPanel northPanel; JPanel diePanel1; JPanel diePanel2; JPanel centerPanel; JPanel upperScorePanel; JPanel lowerScorePanel; JPanel southPanel; JPanel yahtzeePanel; JPanel scoreLabelPanel; JPanel rollNextPanel; // Die buttons for the die panels and array to manipulate them all JButton dieButton1; JButton dieButton2; JButton dieButton3; JButton dieButton4; JButton dieButton5; //labels, buttons, and text fields for the upper score card JLabel upperLabel; JButton onesButton; JButton twosButton; JButton threesButton; JButton foursButton; JButton fivesButton; JButton sixesButton; JTextField onesTextField; JTextField twosTextField; JTextField threesTextField; JTextField foursTextField; JTextField fivesTextField; JTextField sixesTextField; //labels, buttons, and text fields for the lower score card JLabel lowerLabel; JButton threeOfAKindButton; JButton fourOfAKindButton; JButton fullHouseButton; JButton smallStraightButton; JButton largeStraightButton; JButton chanceButton; JTextField threeOfAKindTextField; JTextField fourOfAKindTextField; JTextField fullHouseTextField; JTextField smallStraightTextField; JTextField largeStraightTextField; JTextField chanceTextField; //components for yahtee score panel JButton yahtzeeButton; JTextField yahtzeeTextField; JCheckBox bonusCheckBox1; JCheckBox bonusCheckBox2; JCheckBox bonusCheckBox3; JCheckBox[] bonusCheckBoxes; // Scoring panel components JLabel upperScoreLabel; JLabel lowerScoreLabel; JLabel totalScoreLabel; JLabel upperPointsLabel; JLabel lowerPointsLabel; JLabel totalPointsLabel; // roll/next panel components JButton rollButton; JButton nextButton; public GameBoard() { // Call methods to add component to the window createMenu(); makeGameBoard(); //set window properties and make visible super.setJMenuBar(menuBar); super.setTitle("Matt's Yahtzeee game"); super.setSize(800,850); super.setResizable(false); super.setVisible(true); super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private void createMenu() { // Initialize all menu components menuBar = new JMenuBar(); fileMenu = new JMenu("File"); newGameMenuItem = new JMenuItem("New Game"); saveGameMenuItem = new JMenuItem("Save Game"); loadGameMenuItem = new JMenuItem("Load Game"); exitGameMenuItem = new JMenuItem("Exit"); roundMenu = new JMenu("Round"); lastRoundMenuItem = new JMenuItem("Last Round"); roundSelectMenu = new JMenu("Round Select"); // Add file menu items to file menu fileMenu.add(newGameMenuItem); fileMenu.add(saveGameMenuItem); fileMenu.add(loadGameMenuItem); fileMenu.add(exitGameMenuItem); //add round menu items roundMenu.add(lastRoundMenuItem); roundMenu.add(roundSelectMenu); // Add menus to menu bar menuBar.add(fileMenu); menuBar.add(roundMenu); } public void makeGameBoard() { super.setLayout(new BorderLayout()); GridBagConstraints c = new GridBagConstraints();//to be used for the GridBag sections //initialize panels northPanel = new JPanel(new GridLayout(2,1)); northPanel.setPreferredSize(new Dimension(200,300)); //northPanel.setBorder(BorderFactory.createLineBorder(Color.black)); diePanel1 = new JPanel(); diePanel2 = new JPanel(); centerPanel = new JPanel(new GridLayout(1,2)); //centerPanel.setBorder(BorderFactory.createLineBorder(Color.black)); centerPanel.setSize(200,100); upperScorePanel = new JPanel(new GridBagLayout()); lowerScorePanel = new JPanel(new GridBagLayout()); southPanel = new JPanel(new GridLayout(2,2)); yahtzeePanel = new JPanel(new GridBagLayout()); scoreLabelPanel = new JPanel(new GridLayout(3,3)); rollNextPanel = new JPanel(new GridLayout(2,1)); // This array is to make all of the panel backgrounds the same color later JPanel[] panels = {northPanel, diePanel1, diePanel2,centerPanel, upperScorePanel, lowerScorePanel, southPanel, yahtzeePanel, scoreLabelPanel, rollNextPanel}; // Layout the north panel components dieButton1 = new JButton(); dieButton2 = new JButton(); dieButton3 = new JButton(); dieButton4 = new JButton(); dieButton5 = new JButton(); JButton[] dieButtons = {dieButton1, dieButton2, dieButton3, dieButton4, dieButton5}; for (int i = 0; i < dieButtons.length; i++) { //hide default JButton background dieButtons[i].setBorderPainted(false); dieButtons[i].setContentAreaFilled(false); dieButtons[i].setFocusPainted(false); dieButtons[i].setOpaque(false); } //add dieButtons to die panels diePanel1.add(dieButton1); diePanel1.add(dieButton2); diePanel1.add(dieButton3); diePanel2.add(dieButton4); diePanel2.add(dieButton5); //layout all center panel components // Upper upperLabel = new JLabel("Upper"); onesButton = new JButton("Ones"); twosButton = new JButton("Twos"); threesButton = new JButton("Threes"); foursButton = new JButton("Fours"); fivesButton = new JButton("Fives"); sixesButton = new JButton("Sixes"); JButton[] upperButtons = {onesButton, twosButton, threesButton, foursButton, fivesButton, sixesButton}; onesTextField = new JTextField(5); twosTextField = new JTextField(5); threesTextField = new JTextField(5); foursTextField = new JTextField(5); fivesTextField = new JTextField(5); sixesTextField = new JTextField(5); JTextField[] upperTextFields = {onesTextField, twosTextField, threesTextField, foursTextField, fivesTextField, sixesTextField}; //set alignment and color of all text field and disable them; for(int i = 0; i < upperTextFields.length; ++i) { upperTextFields[i].setHorizontalAlignment(JTextField.CENTER); upperTextFields[i].setBackground(Color.gray); upperTextFields[i].setEditable(false);; } // Add Components using grid bag constraints c.gridx = 1; upperScorePanel.add(upperLabel, c); for(int i = 0; i < upperButtons.length; i++) { c.gridx = 0; c.gridy = i+1; upperScorePanel.add(upperButtons[i], c); c.gridx = 2; upperScorePanel.add(upperTextFields[i],c); } // Lower lowerLabel = new JLabel("Lower"); threeOfAKindButton = new JButton("Three of a Kind"); fourOfAKindButton = new JButton("Four of a Kind"); fullHouseButton = new JButton("Full House"); smallStraightButton = new JButton("Small Straight"); largeStraightButton = new JButton("Large Straight"); chanceButton = new JButton("Chance"); JButton[] lowerButtons = {threeOfAKindButton, fourOfAKindButton, fullHouseButton, smallStraightButton, largeStraightButton,chanceButton}; threeOfAKindTextField = new JTextField(5); fourOfAKindTextField = new JTextField(5); fullHouseTextField = new JTextField(5); smallStraightTextField = new JTextField(5); largeStraightTextField = new JTextField(5); chanceTextField = new JTextField(5); JTextField[] lowerTextFields = {threeOfAKindTextField, fourOfAKindTextField, fullHouseTextField, smallStraightTextField, largeStraightTextField,chanceTextField}; //set alignment and color of all text field and disable them; for(int i = 0; i < lowerTextFields.length; ++i) { lowerTextFields[i].setHorizontalAlignment(JTextField.CENTER); lowerTextFields[i].setBackground(Color.gray); lowerTextFields[i].setEditable(false); } // Add Components using grid bag constraints c = new GridBagConstraints(); c.gridx = 1; lowerScorePanel.add(lowerLabel, c); for(int i = 0; i < lowerButtons.length; i++) { c.gridx = 0; c.gridy = i+1; lowerScorePanel.add(lowerButtons[i], c); c.gridx = 2; lowerScorePanel.add(lowerTextFields[i],c); } //layout all south panel components // Yahtzee score card yahtzeeButton = new JButton("Yahtzee"); yahtzeeTextField = new JTextField(5); yahtzeeTextField.setEditable(false); yahtzeeTextField.setBackground(Color.gray); bonusCheckBox1 = new JCheckBox(); bonusCheckBox2 = new JCheckBox(); bonusCheckBox3 = new JCheckBox(); bonusCheckBoxes = new JCheckBox[3]; bonusCheckBoxes[0] = bonusCheckBox1; bonusCheckBoxes[1] = bonusCheckBox2; bonusCheckBoxes[2] = bonusCheckBox3; for(int i = 0; i < bonusCheckBoxes.length; ++i) { bonusCheckBoxes[i].setEnabled(false); } c = new GridBagConstraints(); yahtzeePanel.add(yahtzeeButton,c); c.gridx = 2; yahtzeePanel.add(yahtzeeTextField,c); c.gridy = 1; c.gridx = 0; yahtzeePanel.add(bonusCheckBox1, c); c.gridx = 1; yahtzeePanel.add(bonusCheckBox2, c); c.gridx = 2; yahtzeePanel.add(bonusCheckBox3, c); //score panel upperScoreLabel = new JLabel("Upper Score:"); lowerScoreLabel = new JLabel("Lower Score:"); totalScoreLabel = new JLabel("Total Score:"); upperPointsLabel = new JLabel("0"); lowerPointsLabel = new JLabel("0"); totalPointsLabel = new JLabel("0"); scoreLabelPanel.add(upperScoreLabel); scoreLabelPanel.add(upperPointsLabel); scoreLabelPanel.add(lowerScoreLabel); scoreLabelPanel.add(lowerPointsLabel); scoreLabelPanel.add(totalScoreLabel); scoreLabelPanel.add(totalPointsLabel); //roll next panel rollButton = new JButton("Roll"); nextButton = new JButton("Next"); rollNextPanel.add(rollButton); rollNextPanel.add(nextButton); //add all panels northPanel.add(diePanel1); northPanel.add(diePanel2); centerPanel.add(upperScorePanel); centerPanel.add(lowerScorePanel); southPanel.add(yahtzeePanel); southPanel.add(scoreLabelPanel); southPanel.add(rollNextPanel); add(northPanel,BorderLayout.PAGE_START); add(centerPanel, BorderLayout.CENTER); add(southPanel, BorderLayout.PAGE_END); //set background of all panels to be dark green this.setBackground(new Color(26,122,34)); for(JPanel element: panels) { element.setBackground(new Color(26,122,34)); } } //adds a round to the round menu public void addRoundMenuItem(int roundNum, ActionListener listener) { JMenuItem newRoundMenuItem = new JMenuItem(); roundMenuItems[roundNum - 1] = new JMenuItem("Round "+roundNum); newRoundMenuItem = roundMenuItems[roundNum - 1]; roundSelectMenu.add(newRoundMenuItem); newRoundMenuItem.addActionListener(listener); newRoundMenuItem.setActionCommand(newRoundMenuItem.getText()); } // redraw the die buttons with new die faces public void drawDice(Die[] dice) { JButton[] dieButtons = {dieButton1, dieButton2, dieButton3, dieButton4, dieButton5}; for(int i = 0; i < dice.length; ++i) dieButtons[i].setIcon(dice[i].getDieImage()); } //add action listeners to all controls void addActionListeners(ActionListener listener) { rollButton.addActionListener(listener); rollButton.setActionCommand("roll"); JButton[] dieButtons = {dieButton1,dieButton2, dieButton3, dieButton4, dieButton5}; for(int i = 0; i < dieButtons.length; ++i) { dieButtons[i].addActionListener(listener); dieButtons[i].setActionCommand("die"+(i+1)); } nextButton.addActionListener(listener); nextButton.setActionCommand("next"); onesButton.addActionListener(listener); onesButton.setActionCommand("ONES"); twosButton.addActionListener(listener); twosButton.setActionCommand("TWOS"); threesButton.addActionListener(listener); threesButton.setActionCommand("THREES"); foursButton.addActionListener(listener); foursButton.setActionCommand("FOURS"); fivesButton.addActionListener(listener); fivesButton.setActionCommand("FIVES"); sixesButton.addActionListener(listener); sixesButton.setActionCommand("SIXES"); threeOfAKindButton.addActionListener(listener); threeOfAKindButton.setActionCommand("THREE_OF_A_KIND"); fourOfAKindButton.addActionListener(listener); fourOfAKindButton.setActionCommand("FOUR_OF_A_KIND"); fullHouseButton.addActionListener(listener); fullHouseButton.setActionCommand("FULL_HOUSE"); smallStraightButton.addActionListener(listener); smallStraightButton.setActionCommand("SMALL_STRAIGHT"); largeStraightButton.addActionListener(listener); largeStraightButton.setActionCommand("LARGE_STRAIGHT"); yahtzeeButton.addActionListener(listener); yahtzeeButton.setActionCommand("YAHTZEE"); chanceButton.addActionListener(listener); chanceButton.setActionCommand("CHANCE"); newGameMenuItem.addActionListener(listener); newGameMenuItem.setActionCommand("new game"); saveGameMenuItem.addActionListener(listener); saveGameMenuItem.setActionCommand("save game"); loadGameMenuItem.addActionListener(listener); loadGameMenuItem.setActionCommand("load game"); exitGameMenuItem.addActionListener(listener); exitGameMenuItem.setActionCommand("exit"); lastRoundMenuItem.addActionListener(listener); lastRoundMenuItem.setActionCommand("last round"); } public void clear() { onesTextField.setText(""); twosTextField.setText(""); threesTextField.setText(""); foursTextField.setText(""); fivesTextField.setText(""); sixesTextField.setText(""); threeOfAKindTextField.setText(""); fourOfAKindTextField.setText(""); fullHouseTextField.setText(""); smallStraightTextField.setText(""); largeStraightTextField.setText(""); chanceTextField.setText(""); yahtzeeTextField.setText(""); bonusCheckBox1.setSelected(false); bonusCheckBox2.setSelected(false); bonusCheckBox3.setSelected(false); upperPointsLabel.setText("0"); lowerPointsLabel.setText("0"); totalPointsLabel.setText("0"); } } <file_sep>import java.io.Serializable; import java.util.Random; import javax.swing.ImageIcon; // This a die for the yahtzee game to use. It will keep track of it's hold state and has a number and associated picture icon public class Die implements Serializable { private int dieFace; private ImageIcon dieImage; private boolean isHeld; //Constructor gets a random integer value and uses it to set the die and die face. Each die starts out unheld public Die() { Random randomNumber = new Random(); dieFace = randomNumber.nextInt(6)+1; //set dieImage based on what die face was given dieImage = new ImageIcon(getClass().getClassLoader().getResource("die"+dieFace+".jpg")); isHeld = false; } public Die roll() { return new Die(); } public void setDieFace(int dieFace) { this.dieFace = dieFace; //set dieImage based on what die face was given this.dieImage = new ImageIcon(getClass().getClassLoader().getResource("die"+dieFace+".jpg")); } public boolean isHeld() { return isHeld; } public void setDieImage(ImageIcon dieImage) { this.dieImage = dieImage; } public void setHeld(boolean isHeld) { this.isHeld = isHeld; } public int getDieFace() { return dieFace; } public ImageIcon getDieImage() { return dieImage; } } <file_sep>// This class is a child of ScoreCategory that checks an array of five dice for different numbers of matches public abstract class MatchingCategory extends ScoreCategory { //will be altered by child classes to the right match number protected int matchNumber; @Override public boolean isScorable(Die[] dice, boolean wildCard) { if (!wildCard) { // This array will keep track of any matches. The index will coordinate with the // number on the die face minus 1 int[] matches = new int[6]; boolean isMatch = false; //loop through the dieNumbers array and keep count of any matches // by adding to the matches array for (int i = 0; i < dice.length; ++i) { ++matches[dice[i].getDieFace() - 1]; } for (int i = 0; i < matches.length; ++i) { if (matches[i] >= matchNumber) { isMatch = true; } } if (isMatch && (!isScored)) { return true; } else { return false; } } else { return true; } } public abstract void setScore(Die[] dice, boolean wildCard); } <file_sep> public enum UpperCategories { ONES, TWOS, THREES, FOURS, FIVES, SIXES }
5637560d03030f7951e5cc26dd7f473ebbaa94ef
[ "Java" ]
7
Java
Mayme123/Yahtzee
6648c2376435df7508a95fba0f63b8bb4afbf059
5c537f19275ce7eb6ba9783559cb393ee19eefb1
refs/heads/master
<file_sep>(function (app) { app.controller('roomEditController', roomEditController); roomEditController.$inject = ['apiService', '$scope', '$state', '$stateParams']; function roomEditController(apiService, $scope, $state, $stateParams) { $scope.room = { CreatedDate: new Date(), Status: true } $scope.UpdateRoom = UpdateRoom; function UpdateRoom() { apiService.put('api/room/update', $scope.room, function (result) { $state.go('rooms') }, function (error) { console.log('Update room fail');; }); } function LoadRoomDetail() { apiService.get('api/room/getbyid/' + $stateParams.id, null, function (result) { $scope.room = result.data; }, function (error) { console.log('Load room fail'); }); } function loadAllDepartment() { apiService.get('api/department/getalldepartment', null, function (result) { $scope.allDepartment = result.data; }, function () { console.log('Cannot get list parent'); }); } loadAllDepartment(); LoadRoomDetail(); } })(angular.module('xephang.rooms'));<file_sep>using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using XepHang.Model.Models; using XepHang.Service; using XepHang.Web.Infrastructure.Core; using XepHang.Web.Infrastructure.Extensions; using XepHang.Web.Models; namespace XepHang.Web.API { [RoutePrefix("api/room")] [Authorize] public class RoomController : ApiControllerBase { IRoomService _roomService; public RoomController(IErrorService errorService, IRoomService roomService) : base(errorService) { this._roomService = roomService; } [Route("getall")] public HttpResponseMessage Get(HttpRequestMessage request, int page, int pageSize = 20) { return CreateHttpResponse(request, () => { int totalRow = 0; var listRoom = _roomService.GetAll(); totalRow = listRoom.Count(); var query = listRoom.OrderBy(x => x.RoomId).Skip(page * pageSize).Take(pageSize); var listRoomVm = Mapper.Map<IEnumerable<Room>, IEnumerable<RoomViewModel>>(query); var paginationSet = new PaginationSet<RoomViewModel>() { Items = listRoomVm, Page = page, TotalCount = totalRow, TotalPages = (int)Math.Ceiling((decimal)totalRow / pageSize) }; HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK, paginationSet); return response; }); } [Route("create")] [HttpPost] [AllowAnonymous] public HttpResponseMessage Create(HttpRequestMessage request, RoomViewModel roomVM) { return CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } else { var newRoom = new Room(); newRoom.UpdateRoom(roomVM); newRoom.CreatedDate = DateTime.Now; _roomService.Add(newRoom); _roomService.SaveChanges(); var responseData = Mapper.Map<Room, RoomViewModel>(newRoom); response = request.CreateResponse(HttpStatusCode.Created, responseData); } return response; }); } [Route("update")] public HttpResponseMessage Put(HttpRequestMessage request, RoomViewModel roomVM) { return CreateHttpResponse(request, () => { HttpResponseMessage respone = null; if (!ModelState.IsValid) { respone = request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } else { var dbRoom = _roomService.GetById(roomVM.RoomId); dbRoom.UpdateRoom(roomVM); dbRoom.ModifiledDate = DateTime.Now; dbRoom.ModifiledBy = User.Identity.Name; _roomService.Update(dbRoom); _roomService.SaveChanges(); var responseData = Mapper.Map<Room, RoomViewModel>(dbRoom); respone = request.CreateResponse(HttpStatusCode.Created, responseData); } return respone; }); } [Route("getbyid/{id:int}")] public HttpResponseMessage Get(HttpRequestMessage request, int id) { return CreateHttpResponse(request, () => { var model = _roomService.GetById(id); var reponseData = Mapper.Map<Room, RoomViewModel>(model); HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK, reponseData); return response; }); } [Route("delete")] public HttpResponseMessage Delete(HttpRequestMessage request, int id) { return CreateHttpResponse(request, () => { HttpResponseMessage respone = null; if (!ModelState.IsValid) { respone = request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } else { var oldRoom = _roomService.Delete(id); _roomService.SaveChanges(); var reponseData = Mapper.Map<Room, RoomViewModel>(oldRoom); respone = request.CreateResponse(HttpStatusCode.OK, reponseData); } return respone; }); } [Route("getallroom")] [HttpGet] public HttpResponseMessage GetAll(HttpRequestMessage request) { return CreateHttpResponse(request, () => { var model = _roomService.GetAll(); var responseData = Mapper.Map<IEnumerable<Room>, IEnumerable<RoomViewModel>>(model); var response = request.CreateResponse(HttpStatusCode.OK, responseData); return response; }); } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using XepHang.Data.Repositories; using XepHang.Data.Infrastructure; using XepHang.Service; using XepHang.Model.Models; using System.Collections.Generic; namespace XepHang.Test.ServiceTest { [TestClass] public class DepartmentServiceTest { private Mock<IDepartmentRepository> _mockRepository; private Mock<IUnitOfWork> _mockUnitOfWork; private IDepartmentService _departmentService; private List<Department> _listDepartment; [TestInitialize] public void Initialize() { _mockRepository = new Mock<IDepartmentRepository>(); _mockUnitOfWork = new Mock<IUnitOfWork>(); _departmentService = new DepartmentService(_mockRepository.Object, _mockUnitOfWork.Object); _listDepartment = new List<Department> { new Department() {DepartmentId=1,DepartmentName="Xin chao", CreatedDate=DateTime.Now,Status=true }, new Department() {DepartmentId=2,DepartmentName="Xin hi", CreatedDate=DateTime.Now,Status=true }, new Department() {DepartmentId=3,DepartmentName="Xin chao hi", CreatedDate=DateTime.Now,Status=true }, }; } [TestMethod] public void Department_Service_GetAll() { // setup method _mockRepository.Setup(m => m.GetAll(null)).Returns(_listDepartment); // goi phuong thuc var result = _departmentService.GetAll() as List<Department>; //so sanh Assert.IsNotNull(result); Assert.AreEqual(3, result.Count); } [TestMethod] public void Department_Service_Create() { Department department = new Department(); department.DepartmentName = "Da liễu"; department.CreateBy = "thanhpt"; department.CreatedDate = DateTime.Now; department.Status = true; _mockRepository.Setup(m => m.Add(department)).Returns((Department d) => { d.DepartmentId = 1; return d; }); var result = _departmentService.Add(department); Assert.IsNotNull(result); Assert.AreEqual(1, result.DepartmentId); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using XepHang.Data.Infrastructure; using XepHang.Model.Models; namespace XepHang.Data.Repositories { public interface IRoomRepository : IRepository<Room> { } public class RoomRepository : RepositoryBase<Room>, IRoomRepository { public RoomRepository(IDbFactory dbFactory) : base(dbFactory) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using XepHang.Model.Models; using XepHang.Service; using XepHang.Web.Infrastructure.Core; using XepHang.Web.Models; using XepHang.Web.Infrastructure.Extensions; using AutoMapper; namespace XepHang.Web.API { [RoutePrefix("api/department")] [Authorize] public class DepartmentController : ApiControllerBase { IDepartmentService _departmentService; public DepartmentController(IErrorService errorService, IDepartmentService departmentService) : base(errorService) { this._departmentService = departmentService; } [Route("getall")] public HttpResponseMessage Get(HttpRequestMessage request, int page, int pageSize = 20) { return CreateHttpResponse(request, () => { int totalRow = 0; var listDepartment = _departmentService.GetAll(); totalRow = listDepartment.Count(); var query = listDepartment.OrderBy(x=>x.DepartmentId).Skip(page * pageSize).Take(pageSize); var listDepartmentVm = Mapper.Map<IEnumerable<Department>,IEnumerable<DepartmentViewModel>>(query); var paginationSet = new PaginationSet<DepartmentViewModel>() { Items = listDepartmentVm, Page = page, TotalCount = totalRow, TotalPages = (int)Math.Ceiling((decimal)totalRow / pageSize) }; HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK, paginationSet); return response; }); } [Route("create")] public HttpResponseMessage Post(HttpRequestMessage request, DepartmentViewModel departmentVM) { return CreateHttpResponse(request, () => { HttpResponseMessage respone = null; if (!ModelState.IsValid) { respone = request.CreateResponse(HttpStatusCode.BadRequest, ModelState); }else { var newDepartment = new Department(); newDepartment.UpdateDepartment(departmentVM); newDepartment.CreatedDate = DateTime.Now; newDepartment.CreateBy = User.Identity.Name; _departmentService.Add(newDepartment); _departmentService.SaveChanges(); var responseData = Mapper.Map<Department, DepartmentViewModel>(newDepartment); respone = request.CreateResponse(HttpStatusCode.Created, responseData); } return respone; }); } [Route("update")] public HttpResponseMessage Put(HttpRequestMessage request, DepartmentViewModel departmentVM) { return CreateHttpResponse(request, () => { HttpResponseMessage respone = null; if (!ModelState.IsValid) { respone = request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } else { var dbDepartment = _departmentService.GetById(departmentVM.DepartmentId); dbDepartment.UpdateDepartment(departmentVM); dbDepartment.ModifiledDate = DateTime.Now; dbDepartment.ModifiledBy = User.Identity.Name; _departmentService.Update(dbDepartment); _departmentService.SaveChanges(); var responseData = Mapper.Map<Department, DepartmentViewModel>(dbDepartment); respone = request.CreateResponse(HttpStatusCode.Created, responseData); } return respone; }); } [Route("getbyid/{id:int}")] public HttpResponseMessage Get(HttpRequestMessage request, int id) { return CreateHttpResponse(request, () => { var model = _departmentService.GetById(id); var reponseData = Mapper.Map<Department, DepartmentViewModel>(model); HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK, reponseData); return response; }); } [Route("delete")] public HttpResponseMessage Delete(HttpRequestMessage request, int id) { return CreateHttpResponse(request, () => { HttpResponseMessage respone = null; if (!ModelState.IsValid) { respone = request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } else { var oldDepartment = _departmentService.Delete(id); _departmentService.SaveChanges(); var reponseData = Mapper.Map<Department, DepartmentViewModel>(oldDepartment); respone = request.CreateResponse(HttpStatusCode.OK, reponseData); } return respone; }); } [Route("getalldepartment")] [HttpGet] public HttpResponseMessage GetAll(HttpRequestMessage request) { return CreateHttpResponse(request, () => { var model = _departmentService.GetAll(); var responseData = Mapper.Map<IEnumerable<Department>, IEnumerable<DepartmentViewModel>>(model); var response = request.CreateResponse(HttpStatusCode.OK, responseData); return response; }); } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XepHang.Model.Models { public class NumberReport { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public int RoomId { get; set; } [ForeignKey("RoomId")] public virtual Room Room { set; get; } public DateTime OrderDate { get; set; } public int CurrentNumbebOrder { get; set; } public int TotalNumberOrder { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using XepHang.Data.Infrastructure; using XepHang.Data.Repositories; using XepHang.Model.Models; namespace XepHang.Service { public interface IOrderService { void Add(Order order); void Update(Order order); Order Delete(int id); IEnumerable<Order> GetAll(); IEnumerable<Order> GetAllPaging(int page, int pageSize, out int totalRow); IEnumerable<Order> GetAllByRoomPaging(int room, int page, int pageSize, out int totalRow); Order GetById(int id); IEnumerable<Order> GetAllByDate(string date, int page, int pageSize, out int totalRow); void SaveChanges(); } public class OrderService : IOrderService { IOrderRepository _orderRepository; INumberReportRepository _numberreportRepository; IUnitOfWork _unitOfWork; public OrderService(IOrderRepository orderRepository, INumberReportRepository numberreportRepository, IUnitOfWork unitOfWork) { this._orderRepository = orderRepository; this._numberreportRepository = numberreportRepository; this._unitOfWork = unitOfWork; } public void Add(Order order) { IQueryable<NumberReport> numReports = _numberreportRepository.GetByRoomAndDate(order.RoomId); NumberReport num = numReports.First(); order.ChosenNumber = num.TotalNumberOrder + 1; _orderRepository.Add(order); num.TotalNumberOrder = num.TotalNumberOrder + 1; _numberreportRepository.Update(num); } public Order Delete(int id) { return _orderRepository.Delete(id); } public IEnumerable<Order> GetAll() { return _orderRepository.GetAll(); } public IEnumerable<Order> GetAllByDate(string date, int page, int pageSize, out int totalRow) { throw new NotImplementedException(); } public IEnumerable<Order> GetAllByRoomPaging(int room, int page, int pageSize, out int totalRow) { throw new NotImplementedException(); } public IEnumerable<Order> GetAllPaging(int page, int pageSize, out int totalRow) { throw new NotImplementedException(); } public Order GetById(int id) { return _orderRepository.GetSingleById(id); } public void SaveChanges() { _unitOfWork.Commit(); } public void Update(Order order) { _orderRepository.Update(order); } } } <file_sep>using System; using System.Linq; using System.Collections.Generic; using XepHang.Data.Infrastructure; using XepHang.Model.Models; namespace XepHang.Data.Repositories { public interface INumberReportRepository : IRepository<NumberReport> { IQueryable<NumberReport> GetByRoomAndDate(int roomId); } public class NumberReportRepository : RepositoryBase<NumberReport>, INumberReportRepository { public NumberReportRepository(IDbFactory dbFactory) : base(dbFactory) { } public IQueryable<NumberReport> GetByRoomAndDate(int roomId) { //linq to sql from join on var query = from p in DbContext.NumberReports where p.RoomId == roomId select p; query.Single(); return query; } } } <file_sep>namespace XepHang.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class ResetAll : DbMigration { public override void Up() { DropForeignKey("dbo.Rooms", "DepartmentId", "dbo.Departments"); DropPrimaryKey("dbo.Departments"); DropColumn("dbo.Departments", "DepartmentId"); DropColumn("dbo.Departments", "DepartmentName"); AddColumn("dbo.Departments", "DepartmentId", c => c.Int(nullable: false, identity: true)); AddColumn("dbo.Departments", "DepartmentName", c => c.String(nullable: false, maxLength: 50)); AddPrimaryKey("dbo.Departments", "DepartmentId"); AddForeignKey("dbo.Rooms", "DepartmentId", "dbo.Departments", "DepartmentId", cascadeDelete: true); } public override void Down() { AddColumn("dbo.Departments", "DepartmentName", c => c.String(nullable: false, maxLength: 50)); AddColumn("dbo.Departments", "DepartmentId", c => c.Int(nullable: false, identity: true)); DropForeignKey("dbo.Rooms", "DepartmentId", "dbo.Departments"); DropPrimaryKey("dbo.Departments"); DropColumn("dbo.Departments", "DepartmentName"); DropColumn("dbo.Departments", "DepartmentId"); AddPrimaryKey("dbo.Departments", "DepartmentId"); AddForeignKey("dbo.Rooms", "DepartmentId", "dbo.Departments", "DepartmentId", cascadeDelete: true); } } } <file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using XepHang.Data.Infrastructure; using XepHang.Data.Repositories; using XepHang.Model.Models; namespace XepHang.Test.Respository { [TestClass] public class DepartmentRepositoryTest { IDbFactory dbFactory; IDepartmentRepository objRepository; IUnitOfWork unitOfWork; [TestInitialize()] public void Initialize() { dbFactory = new DbFactory(); objRepository = new DepartmentRepository(dbFactory); unitOfWork = new UnitOfWork(dbFactory); } [TestMethod] public void Department_Repository_Create() { Department department = new Department(); department.DepartmentName = "Da liễu"; department.CreateBy = "thanhpt"; department.CreatedDate = DateTime.Now; department.Status = true; var result = objRepository.Add(department); unitOfWork.Commit(); Assert.IsNotNull(result); Assert.AreEqual(9, result.DepartmentId); } [TestMethod] public void Department_Repository_GetAll() { var list = objRepository.GetAll().ToList(); Assert.AreEqual(4, list.Count); } } } <file_sep>using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using XepHang.Model.Models; using XepHang.Service; using XepHang.Web.Infrastructure.Core; using XepHang.Web.Infrastructure.Extensions; using XepHang.Web.Models; namespace XepHang.Web.API { [RoutePrefix("api/numberreport")] [Authorize] public class NumberReportController : ApiControllerBase { INumberReportService _numberreportService; public NumberReportController(IErrorService errorService, INumberReportService numberreportService) : base(errorService) { this._numberreportService = numberreportService; } [Route("getall")] public HttpResponseMessage Get(HttpRequestMessage request, int page, int pageSize = 20) { return CreateHttpResponse(request, () => { int totalRow = 0; var listOrder = _numberreportService.GetAll(); totalRow = listOrder.Count(); var query = listOrder.OrderBy(x => x.RoomId).Skip(page * pageSize).Take(pageSize); var listNumberReportVm = Mapper.Map<IEnumerable<NumberReport>, IEnumerable<NumberReportViewModel>>(query); var paginationSet = new PaginationSet<NumberReportViewModel>() { Items = listNumberReportVm, Page = page, TotalCount = totalRow, TotalPages = (int)Math.Ceiling((decimal)totalRow / pageSize) }; HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK, paginationSet); return response; }); } [Route("delete")] public HttpResponseMessage Delete(HttpRequestMessage request, int id) { return CreateHttpResponse(request, () => { HttpResponseMessage respone = null; if (!ModelState.IsValid) { respone = request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } else { var oldNumberreport = _numberreportService.Delete(id); _numberreportService.SaveChanges(); var reponseData = Mapper.Map<NumberReport, NumberReportViewModel>(oldNumberreport); respone = request.CreateResponse(HttpStatusCode.OK, reponseData); } return respone; }); } [Route("getbyid/{id:int}")] public HttpResponseMessage Get(HttpRequestMessage request, int id) { return CreateHttpResponse(request, () => { var model = _numberreportService.GetById(id); var reponseData = Mapper.Map<NumberReport, NumberReportViewModel>(model); HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK, reponseData); return response; }); } [Route("update")] public HttpResponseMessage Put(HttpRequestMessage request, NumberReportViewModel numberreportVM) { return CreateHttpResponse(request, () => { HttpResponseMessage respone = null; if (!ModelState.IsValid) { respone = request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } else { var dbNumberreport = _numberreportService.GetById(numberreportVM.Id); dbNumberreport.UpdateNumberreport(numberreportVM); _numberreportService.Update(dbNumberreport); _numberreportService.SaveChanges(); var responseData = Mapper.Map<NumberReport, NumberReportViewModel>(dbNumberreport); respone = request.CreateResponse(HttpStatusCode.Created, responseData); } return respone; }); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace XepHang.Web.Models { public class RoomViewModel { public int RoomId { get; set; } public string RoomName { get; set; } public int DepartmentId { get; set; } public virtual DepartmentViewModel Department { set; get; } public DateTime CreatedDate { get; set; } public string CreateBy { get; set; } public DateTime? ModifiledDate { get; set; } public string ModifiledBy { get; set; } public string Note { get; set; } public bool Status { set; get; } public IEnumerable<NumberReportViewModel> NumberReport { set; get; } public IEnumerable<OrderViewModel> Order { set; get; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XepHang.Model.Models { [Table("Rooms")] public class Room { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int RoomId { get; set; } [Required] [MaxLength(50)] public string RoomName { get; set; } [Required] public int DepartmentId { get; set; } [ForeignKey("DepartmentId")] public virtual Department Department { set; get; } public DateTime? CreatedDate { get; set; } public string CreateBy { get; set; } public DateTime? ModifiledDate { get; set; } public string ModifiledBy { get; set; } public string Note { get; set; } [Required] public bool Status { set; get; } public IEnumerable<NumberReport> NumberReport { set; get; } public IEnumerable<Order> Order{ set; get; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace XepHang.Web.Models { public class NumberReportViewModel { public int Id { get; set; } public int RoomId { get; set; } public virtual RoomViewModel Room { set; get; } public DateTime OrderDate { get; set; } public int CurrentNumbebOrder { get; set; } public int TotalNumberOrder { get; set; } } }<file_sep>(function (app) { app.controller('numberreportEditController', numberreportEditController); numberreportEditController.$inject = ['apiService', '$scope', '$state', '$stateParams']; function numberreportEditController(apiService, $scope, $state, $stateParams) { $scope.numberreport = { CreatedDate: new Date(), Status: true } $scope.UpdateNumberreport = UpdateNumberreport; function UpdateNumberreport() { apiService.put('api/numberreport/update', $scope.numberreport, function (result) { $state.go('numberreports') }, function (error) { console.log('Update report fail');; }); } function LoadNumberreportDetail() { apiService.get('api/numberreport/getbyid/' + $stateParams.id, null, function (result) { $scope.numberreport = result.data; }, function (error) { console.log('Load report fail'); }); } function loadAllRoom() { apiService.get('api/room/getallroom', null, function (result) { $scope.allRoom = result.data; }, function () { console.log('Cannot get list parent'); }); } loadAllRoom(); LoadNumberreportDetail(); } })(angular.module('xephang.numberreports'));<file_sep>using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Web; using XepHang.Model.Models; using XepHang.Web.Models; namespace XepHang.Web.Mappings { public class AutoMapperConfiguration { public static void Configure() { Mapper.CreateMap<Department, DepartmentViewModel>(); Mapper.CreateMap<Room, RoomViewModel>(); Mapper.CreateMap<Order, OrderViewModel>(); Mapper.CreateMap<NumberReport, NumberReportViewModel>(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using XepHang.Model.Models; using XepHang.Web.Models; namespace XepHang.Web.Infrastructure.Extensions { public static class EntityExtensions { public static void UpdateDepartment(this Department department, DepartmentViewModel departmentVM) { department.DepartmentId = departmentVM.DepartmentId; department.DepartmentName = departmentVM.DepartmentName; department.CreatedDate = departmentVM.CreatedDate; department.Note = departmentVM.Note; department.CreateBy = departmentVM.CreateBy; department.ModifiledDate = departmentVM.ModifiledDate; department.ModifiledBy = departmentVM.ModifiledBy; department.Status = departmentVM.Status; } public static void UpdateRoom(this Room room, RoomViewModel roomVM) { room.RoomId = roomVM.RoomId; room.RoomName = roomVM.RoomName; room.DepartmentId = roomVM.DepartmentId; room.CreatedDate = roomVM.CreatedDate; room.Note = roomVM.Note; room.CreateBy = roomVM.CreateBy; room.ModifiledDate = roomVM.ModifiledDate; room.ModifiledBy = roomVM.ModifiledBy; room.Status = roomVM.Status; } public static void UpdateOrder(this Order order, OrderViewModel orderVM) { order.OrderId = orderVM.OrderId; order.Username = orderVM.Username; order.OrderDate = orderVM.OrderDate; order.RoomId = orderVM.RoomId; //order.ChosenNumber = orderVM.ChosenNumber; order.Username = orderVM.Username; order.ModifiledDate = orderVM.ModifiledDate; order.ModifiledBy = orderVM.ModifiledBy; order.Status = orderVM.Status; } public static void UpdateNumberreport(this NumberReport report, NumberReportViewModel reportVM) { report.Id = reportVM.Id; report.RoomId = reportVM.RoomId; report.CurrentNumbebOrder = reportVM.CurrentNumbebOrder; report.TotalNumberOrder = reportVM.TotalNumberOrder; } } }<file_sep>(function (app) { app.controller('orderListController', orderListController); orderListController.$inject = ['$scope', 'apiService', '$ngBootbox']; function orderListController($scope, apiService, $ngBootbox) { $scope.orders = []; $scope.page = 0; $scope.pagesCount = 0;; $scope.getListOrders = getListOrders; $scope.deleteOrder = deleteOrder; function deleteOrder(id) { $ngBootbox.confirm('Bạn có chắc muốn xóa không?').then(function () { var config = { params: { id: id } } apiService.del('api/order/delete', config, function () { $ngBootbox.alert('Xóa thành công'); getListOrders(); }, function () { console.log('Xóa không thành công'); }) }); } function getListOrders(page) { page = page || 0; var config = { params: { page: page, pageSize: 10 } } apiService.get('/api/order/getall', config, function (result) { $scope.orders = result.data.Items; $scope.page = result.data.Page; $scope.pagesCount = result.data.TotalPages; $scope.totalCount = result.data.TotalCount; }, function (error) { console.log('Load order fail'); }); } function loadAllRoom() { apiService.get('api/room/getallroom', null, function (result) { $scope.allRoom = result.data; }, function () { console.log('Cannot get list parent'); }); } loadAllRoom(); $scope.getListOrders(); } })(angular.module('xephang.orders'));<file_sep>using System; using System.Collections.Generic; using XepHang.Data.Infrastructure; using XepHang.Data.Repositories; using XepHang.Model.Models; namespace XepHang.Service { public interface INumberReportService { void Add(NumberReport report); void Update(NumberReport report); NumberReport Delete(int id); IEnumerable<NumberReport> GetAll(); IEnumerable<NumberReport> GetAllPaging(int page, int pageSize, out int totalRow); IEnumerable<NumberReport> GetAllByRoomPaging(int room, int page, int pageSize, out int totalRow); NumberReport GetById(int id); IEnumerable<NumberReport> GetAllByDate(string date, int page, int pageSize, out int totalRow); void SaveChanges(); } public class NumberReportService : INumberReportService { INumberReportRepository _numberreportRepository; IUnitOfWork _unitOfWork; public NumberReportService(INumberReportRepository numberreportRepository, IUnitOfWork unitOfWork) { this._numberreportRepository = numberreportRepository; this._unitOfWork = unitOfWork; } public void Add(NumberReport report) { _numberreportRepository.Add(report); } public NumberReport Delete(int id) { return _numberreportRepository.Delete(id); } public IEnumerable<NumberReport> GetAll() { return _numberreportRepository.GetAll(); } public IEnumerable<NumberReport> GetAllByDate(string date, int page, int pageSize, out int totalRow) { throw new NotImplementedException(); } public IEnumerable<NumberReport> GetAllByRoomPaging(int room, int page, int pageSize, out int totalRow) { throw new NotImplementedException(); } public IEnumerable<NumberReport> GetAllPaging(int page, int pageSize, out int totalRow) { throw new NotImplementedException(); } public NumberReport GetById(int id) { return _numberreportRepository.GetSingleById(id); } public void SaveChanges() { _unitOfWork.Commit(); } public void Update(NumberReport report) { _numberreportRepository.Update(report); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using XepHang.Data.Infrastructure; using XepHang.Data.Repositories; using XepHang.Model.Models; namespace XepHang.Service { public interface IRoomService { Room Add(Room room); void Update(Room room); Room Delete(int id); IEnumerable<Room> GetAll(); IEnumerable<Room> GetAllPaging(int page, int pageSize, out int totalRow); IEnumerable<Room> GetAllByRoomPaging(int room, int page, int pageSize, out int totalRow); Room GetById(int id); void SaveChanges(); } public class RoomService : IRoomService { IRoomRepository _roomRepository; IUnitOfWork _unitOfWork; public RoomService(IRoomRepository roomRepository, IUnitOfWork unitOfWork) { this._roomRepository = roomRepository; this._unitOfWork = unitOfWork; } public Room Add(Room room) { return _roomRepository.Add(room); } public Room Delete(int id) { return _roomRepository.Delete(id); } public IEnumerable<Room> GetAll() { return _roomRepository.GetAll(); } public IEnumerable<Room> GetAllByRoomPaging(int room, int page, int pageSize, out int totalRow) { throw new NotImplementedException(); } public IEnumerable<Room> GetAllPaging(int page, int pageSize, out int totalRow) { throw new NotImplementedException(); } public Room GetById(int id) { return _roomRepository.GetSingleById(id); } public void SaveChanges() { _unitOfWork.Commit(); } public void Update(Room room) { _roomRepository.Update(room); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using XepHang.Data.Infrastructure; using XepHang.Model.Models; namespace XepHang.Data.Repositories { public interface IDepartmentRepository : IRepository<Department> { IEnumerable<Department> GetByName(string name); } public class DepartmentRepository : RepositoryBase<Department>, IDepartmentRepository { public DepartmentRepository(IDbFactory dbFactory) : base(dbFactory) { } public IEnumerable<Department> GetByName(string name) { return DbContext.Departments.Where(x => x.DepartmentName == name); } } } <file_sep>namespace XepHang.Data.Migrations { using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Model.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<XepHangDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(XepHangDbContext context) { CreateDepartmentSample(context); var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new XepHangDbContext())); var rolemanager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new XepHangDbContext())); var user = new ApplicationUser() { UserName = "thanhpt", Email = "<EMAIL>", EmailConfirmed = true, //BirthDay = DateTime.Now, FullName = "<NAME>" }; manager.Create(user, "123456"); if (!rolemanager.Roles.Any()) { rolemanager.Create(new IdentityRole { Name = "Admin" }); rolemanager.Create(new IdentityRole { Name = "User" }); rolemanager.Create(new IdentityRole { Name = "Doctor" }); } var adminuser = manager.FindByEmail("<EMAIL>"); manager.AddToRoles(adminuser.Id, new string[] { "Admin", "User", "Doctor" }); } private void CreateDepartmentSample(XepHangDbContext context) { if (context.Departments.Count() == 0) { List<Department> listDepartment = new List<Department>() { new Department() {DepartmentName="Da Liễu",CreatedDate=DateTime.Now,Status=true }, new Department() {DepartmentName="Nhi",CreatedDate=DateTime.Now,Status=true }, new Department() {DepartmentName="Răng Hàm Mặt",CreatedDate=DateTime.Now,Status=true }, new Department() {DepartmentName="Phụ Sản",CreatedDate=DateTime.Now,Status=true }, }; context.Departments.AddRange(listDepartment); context.SaveChanges(); } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace XepHang.Web.Models { public class DepartmentViewModel { public int DepartmentId { get; set; } [Required] public string DepartmentName { get; set; } public DateTime CreatedDate { get; set; } public string CreateBy { get; set; } public DateTime? ModifiledDate { get; set; } public string ModifiledBy { get; set; } public string Note { get; set; } public bool Status { set; get; } public virtual IEnumerable<RoomViewModel> Room { set; get; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using XepHang.Data.Infrastructure; using XepHang.Data.Repositories; using XepHang.Model.Models; namespace XepHang.Service { public interface IDepartmentService { Department Add(Department department); void Update(Department department); Department Delete(int id); IEnumerable<Department> GetAll(); IEnumerable<Department> GetAllPaging(int page, int pageSize, out int totalRow); IEnumerable<Department> GetAllByRoomPaging(int room, int page, int pageSize, out int totalRow); Department GetById(int id); void SaveChanges(); } public class DepartmentService : IDepartmentService { IDepartmentRepository _departmentRepository; IUnitOfWork _unitOfWork; public DepartmentService(IDepartmentRepository departmentRepository, IUnitOfWork unitOfWork) { this._departmentRepository = departmentRepository; this._unitOfWork = unitOfWork; } public Department Add(Department department) { return _departmentRepository.Add(department); } public Department Delete(int id) { return _departmentRepository.Delete(id); } public IEnumerable<Department> GetAll() { return _departmentRepository.GetAll(); } public IEnumerable<Department> GetAllByRoomPaging(int room, int page, int pageSize, out int totalRow) { throw new NotImplementedException(); } public IEnumerable<Department> GetAllPaging(int page, int pageSize, out int totalRow) { throw new NotImplementedException(); } public Department GetById(int id) { return _departmentRepository.GetSingleById(id); } public void SaveChanges() { _unitOfWork.Commit(); } public void Update(Department department) { _departmentRepository.Update(department); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace XepHang.Web.Models { public class OrderViewModel { public int OrderId { get; set; } public DateTime OrderDate { get; set; } public String Username { get; set; } public int RoomId { get; set; } public virtual RoomViewModel Room { set; get; } [Required] public int ChosenNumber { get; set; } public DateTime CreateDate { get; set; } public DateTime? ModifiledDate { get; set; } public string ModifiledBy { get; set; } public bool Status { set; get; } } }<file_sep>(function (app) { app.controller('orderEditController', orderEditController); orderEditController.$inject = ['apiService', '$scope', '$state', '$stateParams']; function orderEditController(apiService, $scope, $state, $stateParams) { $scope.order = { CreatedDate: new Date(), Status: true } $scope.UpdateOrder = UpdateOrder; function UpdateOrder() { apiService.put('api/order/update', $scope.order, function (result) { $state.go('orders') }, function (error) { console.log('Update order fail');; }); } function LoadOrderDetail() { apiService.get('api/order/getbyid/' + $stateParams.id, null, function (result) { $scope.order = result.data; }, function (error) { console.log('Load order fail'); }); } function loadAllRoom() { apiService.get('api/room/getallroom', null, function (result) { $scope.allRoom = result.data; }, function () { console.log('Cannot get list parent'); }); } loadAllRoom(); LoadOrderDetail(); } })(angular.module('xephang.orders'));<file_sep>using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using XepHang.Model.Models; namespace XepHang.Data { public class XepHangDbContext : IdentityDbContext<ApplicationUser> { public XepHangDbContext() : base("XepHangDb") { this.Configuration.LazyLoadingEnabled = false; } //public static XepHangDbContext Create() //{ // return new XepHangDbContext(); //} public DbSet<Department> Departments { set; get; } public DbSet<NumberReport> NumberReports { set; get; } public DbSet<Order> Orders { set; get; } public DbSet<Room> Rooms { set; get; } public DbSet<Error> Errors { set; get; } public static XepHangDbContext Create() { return new XepHangDbContext(); } protected override void OnModelCreating(DbModelBuilder builder) { //builder.Entity<IdentityUserRole>().HasKey(i => new { i.UserId, i.RoleId }).ToTable("ApplicationUserRoles"); //builder.Entity<IdentityUserLogin>().HasKey(i => i.UserId).ToTable("ApplicationUserLogins"); //builder.Entity<IdentityRole>().ToTable("ApplicationRoles"); //builder.Entity<IdentityUserClaim>().HasKey(i => i.UserId).ToTable("ApplicationUserClaims"); builder.Entity<IdentityUserRole>().HasKey(i => new { i.UserId, i.RoleId }); builder.Entity<IdentityUserLogin>().HasKey(i => i.UserId); } } } <file_sep>(function (app) { app.controller('departmentListController', departmentListController); departmentListController.$inject = ['$scope', 'apiService', '$ngBootbox']; function departmentListController($scope, apiService, $ngBootbox) { $scope.departments = []; $scope.page = 0; $scope.pagesCount = 0;; $scope.getListDepartments = getListDepartments; $scope.deleteDepartment = deleteDepartment; function deleteDepartment(id) { $ngBootbox.confirm('Các phòng liên quan đến khoa này sẽ bị xóa hết. Bạn có chắc muốn xóa không?').then(function () { var config = { params: { id: id } } apiService.del('api/department/delete', config, function () { $ngBootbox.alert('Xóa thành công'); getListDepartments(); }, function () { console.log('Xóa không thành công'); }) }); } function getListDepartments(page) { page = page || 0; var config = { params: { page: page, pageSize: 10 } } apiService.get('/api/department/getall', config, function (result) { $scope.departments = result.data.Items; $scope.page = result.data.Page; $scope.pagesCount = result.data.TotalPages; $scope.totalCount = result.data.TotalCount; }, function (error) { console.log('Load department fail'); }); } $scope.getListDepartments(); } })(angular.module('xephang.departments'));<file_sep>using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using XepHang.Model.Models; using XepHang.Service; using XepHang.Web.Infrastructure.Core; using XepHang.Web.Infrastructure.Extensions; using XepHang.Web.Models; namespace XepHang.Web.API { [RoutePrefix("api/order")] //[Authorize] public class OrderController : ApiControllerBase { IOrderService _orderService; public OrderController(IErrorService errorService, IOrderService orderService) : base(errorService) { this._orderService = orderService; } [Route("getall")] public HttpResponseMessage Get(HttpRequestMessage request, int page, int pageSize = 20) { return CreateHttpResponse(request, () => { int totalRow = 0; var listOrder = _orderService.GetAll(); totalRow = listOrder.Count(); var query = listOrder.OrderBy(x => x.RoomId).Skip(page * pageSize).Take(pageSize); var listOrderVm = Mapper.Map<IEnumerable<Order>, IEnumerable<OrderViewModel>>(query); var paginationSet = new PaginationSet<OrderViewModel>() { Items = listOrderVm, Page = page, TotalCount = totalRow, TotalPages = (int)Math.Ceiling((decimal)totalRow / pageSize) }; HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK, paginationSet); return response; }); } [Route("create")] public HttpResponseMessage Post(HttpRequestMessage request, OrderViewModel orderVM) { return CreateHttpResponse(request, () => { HttpResponseMessage respone = null; if (!ModelState.IsValid) { respone = request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } else { var newOrder = new Order(); newOrder.UpdateOrder(orderVM); if (newOrder.Username == null || newOrder.Username == "") { newOrder.Username = User.Identity.Name; } newOrder.CreateDate = DateTime.Now; _orderService.Add(newOrder); _orderService.SaveChanges(); var responseData = Mapper.Map<Order, OrderViewModel>(newOrder); respone = request.CreateResponse(HttpStatusCode.Created, responseData); } return respone; }); } [Route("delete")] public HttpResponseMessage Delete(HttpRequestMessage request, int id) { return CreateHttpResponse(request, () => { HttpResponseMessage respone = null; if (!ModelState.IsValid) { respone = request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } else { var oldOrder = _orderService.Delete(id); _orderService.SaveChanges(); var reponseData = Mapper.Map<Order, OrderViewModel>(oldOrder); respone = request.CreateResponse(HttpStatusCode.OK, reponseData); } return respone; }); } [Route("getbyid/{id:int}")] public HttpResponseMessage Get(HttpRequestMessage request, int id) { return CreateHttpResponse(request, () => { var model = _orderService.GetById(id); var reponseData = Mapper.Map<Order, OrderViewModel>(model); HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK, reponseData); return response; }); } [Route("update")] public HttpResponseMessage Put(HttpRequestMessage request, OrderViewModel orderVM) { return CreateHttpResponse(request, () => { HttpResponseMessage respone = null; if (!ModelState.IsValid) { respone = request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } else { var dbOrder = _orderService.GetById(orderVM.OrderId); dbOrder.UpdateOrder(orderVM); dbOrder.ModifiledDate = DateTime.Now; dbOrder.ModifiledBy = User.Identity.Name; _orderService.Update(dbOrder); _orderService.SaveChanges(); var responseData = Mapper.Map<Order, OrderViewModel>(dbOrder); respone = request.CreateResponse(HttpStatusCode.Created, responseData); } return respone; }); } } }
a3b7e6170f4f9065b8dd3cecd21db22463ba24d2
[ "JavaScript", "C#" ]
29
JavaScript
thanhffan/xephangproject
98e546e68a813b812280b3c95eaaca5ac3fb0633
0a555f5a4d2a66c028a2af6f2e6010aac340fbe3
refs/heads/master
<file_sep> # Add code here! def prime?(num) new_array = (2..num - 1).to_a if num <= 1 return false end new_array.each do |n| if num % n == 0 return false end end true end
48efadf41a7550244af029d4b0738d6d7de73caa
[ "Ruby" ]
1
Ruby
Jmiller1294/prime-ruby-online-web-pt-100719
65885b50ee0996585a016d91656a714a20d3de33
94537a227e8b7e91a2977821512ba1fe4216e462
refs/heads/master
<repo_name>caseril/src_varius<file_sep>/GretaAnalogWriter/library/base_drago.py import logging import os import time import sys import traceback import asyncio import library.utils as utils from abc import ABC, abstractmethod import aenum from library.base_modbus import BaseModbus, ModbusTypes, ModbusAccess from enum import Enum, auto from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder from pymodbus.payload import BinaryPayloadBuilder from pymodbus.client.sync import ModbusSerialClient # logging config # logging.basicConfig(filename='log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') # logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) # logging.basicConfig(filename='log', filemode='w', format='%(asctime)s - %(module)s - %(name)s - %(levelname)s - %(message)s') # logging.getLogger(__name__).setLevel(logging.DEBUG) # logging.getLogger("pymodbus").setLevel(logging.CRITICAL) # logging.getLogger("azure.iot").setLevel(logging.CRITICAL) # logging.getLogger("azure").setLevel(logging.CRITICAL) # logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) class IdentifiersCommands(aenum.Enum): _init_ = 'value register modbus_type access uom count' DEVICE_IDENTIFIER = auto(), 3000, ModbusTypes.UINT16, ModbusAccess.READ, 'NONE', None HARDWARE_VERSION = auto(), 3001, ModbusTypes.UINT16, ModbusAccess.READ, 'NONE', None RFID_IDENTIFIER = auto(), 3004, ModbusTypes.STRING, ModbusAccess.READ, 'NONE', 8 FIRMWARE_VERSION = auto(), 3028, ModbusTypes.UINT16, ModbusAccess.READ, 'NONE', None POINT_OF_MEASURING = auto(), 5150, ModbusTypes.STRING, ModbusAccess.READ_WRITE, 'NONE', 8 class DIPCommands(aenum.Enum): _init_ = 'value register modbus_type access uom count' CURRENT_DIP_SWITCHES = auto(), 100, ModbusTypes.UINT32, ModbusAccess.READ, 'NONE', None CURRENT_PC_CONFIG = auto(), 102, ModbusTypes.UINT16, ModbusAccess.READ, 'NONE', None class CommonCommands(aenum.Enum): _init_ = 'value register modbus_type access uom count' MODBUS_PC_UNIT_ID = auto(), 5009, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None MODBUS_PC_BAUDRATE = auto(), 5010, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None MODBUS_PC_PARITY_STOPBITS = auto(), 5011, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None MODBUS_PC_RESPONSE_DELAY = auto(), 5012, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None MODBUS_DIP_UNIT_ID = auto(), 5019, ModbusTypes.UINT16, ModbusAccess.READ, 'NONE', None MODBUS_DIP_PARITY_STOPBITS = auto(), 5020, ModbusTypes.UINT16, ModbusAccess.READ, 'NONE', None MODBUS_DIP_BAUDRATE = auto(), 5021, ModbusTypes.UINT16, ModbusAccess.READ, 'NONE', None MODBUS_DIP_RESPONSE_DELAY = auto(), 5022, ModbusTypes.UINT16, ModbusAccess.READ, 'NONE', None SAVE_SETTINGS = auto(), 8212, ModbusTypes.UINT16, ModbusAccess.WRITE, 'NONE', None class BaseDrago(BaseModbus): def __init__(self, variables_dict=None, logger=None): super().__init__(variables_dict=variables_dict, logger=logger) # self.modbus_id = utils.parse_int(self.get('MODBUS_ID', 1), 1) self.modbus_port = self.get('MODBUS_PORT', '/dev/ttyUSB0') self.modbus_stopbits = utils.parse_int(self.get('MODBUS_STOPBITS', 1), 1) self.modbus_bytesize = utils.parse_int(self.get('MODBUS_BYTESIZE', 8), 8) self.modbus_baudrate = utils.parse_int(self.get('MODBUS_BAUDRATE', 19200), 19200) self.modbus_timeout = utils.parse_int(self.get('MODBUS_TIMEOUT', 1), 1) self.modbus_method = self.get('MODBUS_METHOD', 'rtu') self.modbus_parity = self.get('MODBUS_PARITY', 'E') def get_list_command_main_enums(self): return [] def get_list_command_enums(self): return [IdentifiersCommands, DIPCommands, CommonCommands] @abstractmethod def get_command_from_channel(self, channel): pass def connect(self): self.client = ModbusSerialClient(port=self.modbus_port, stopbits=self.modbus_stopbits, bytesize=self.modbus_bytesize, parity=self.modbus_parity, baudrate=self.modbus_baudrate, timeout=self.modbus_timeout, method=self.modbus_method) return self.client.connect() <file_sep>/ModBus_PLC2PLC/ModBus_PLC2PLC_v_0.0.2/main.py import json import os import logging import sys from plc_readwrite import PlcReadWrite, PlcRwMode from plc_looper import PlcLooper import library.utils as utils ###################################################################################################################### # Parametri di configurazione plc_config_file = './config/plc_modbus.config' ###################################################################################################################### # Initializzazione del logger # def init_logging(logger, filename, level=logging.INFO, stdout=True, maxBytes=10000, backupCount=5): logging.getLogger().setLevel(logging.NOTSET) logging.getLogger().handlers = [] rotatingHandler = logging.handlers.RotatingFileHandler(filename=filename, maxBytes=maxBytes, backupCount=backupCount) rotatingHandler.setLevel(logging.DEBUG) rotatingHandler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) logging.getLogger().addHandler(rotatingHandler) logging.getLogger(__name__).setLevel(level) logging.getLogger("pymodbus").setLevel(logging.DEBUG) if stdout: logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) logger = logging.getLogger(__name__) logger.info('init_logging::end') ###################################################################################################################### def get_plc_read_write_and_connect(logger, plc_dictionary): plc_read=[] plc_write=[] for d in plc_dictionary: client = PlcReadWrite(logger, d) if client.connect_device(): if client.rw_mode == PlcRwMode.READ: plc_read.append(client) else: plc_write.append(client) client.disconnect_device() else: if client.rw_mode == PlcRwMode.READ: plc_read.append(None) else: plc_write.append(None) return plc_read, plc_write ###################################################################################################################### def parseJsonConfig(file_full_path): #pwd = os.getcwd() if (os.path.isfile(file_full_path)): with open(file_full_path,"r") as f: return json.load(f) return None ###################################################################################################################### ### MAIN if __name__ == "__main__": logger = logging log_filename = 'test.log' init_logging(logger, log_filename) logger.info("::START::") logger.info("------------------------------------------------------") meas_ok:bool=True # Parsing delle variabili da file di configurazione. plc_dictinoary = parseJsonConfig(plc_config_file) # Lettori da PLC plc_readers, plc_writers = get_plc_read_write_and_connect(logger, plc_dictinoary) if any(ele is None for ele in plc_readers): logger.error("ERROR while connecting plc_readers") if any(ele is None for ele in plc_writers): logger.error("ERROR while connecting plc_writers") #else: PlcLooper(plc_readers, plc_writers).start_testing() # Avvio del loop di test logger.info("::STOP::") logger.info("------------------------------------------------------") <file_sep>/Bilancino/programma (copy)/results-plotting.py import numpy as np import matplotlib.pyplot as plt import sys import os def get_g_from_flow_and_setpoint(time_array, flow_array, sp): mass_mg = np.zeros_like(time_array) for i in range(1, time_array.size): mass_mg[i] = sp*flow_array[i]*(time_array[i] - time_array[i-1])/3600. + mass_mg[i-1] return mass_mg/1000. def get_g_from_bilancia(bilancia_array): return (bilancia_array - bilancia_array[0]) def get_g_corrected_from_flow_and_setpoint(time_array, flow_array, sp, act, dyn): mass_g = get_g_from_flow_and_setpoint(time_array, flow_array, sp) unique_dyn = list() for d in dyn: if d not in unique_dyn: unique_dyn.append(d) unique_dyn = np.asarray(unique_dyn) for i in range(1, unique_dyn.size): d_mask = dyn == unique_dyn[i-1] mass_g[d_mask] = mass_g[d_mask]*unique_dyn[i]/act[d_mask] return mass_g def get_error(bilancia_array, flow_array): return (bilancia_array - flow_array)*100./bilancia_array if __name__ == '__main__': folder_path = str(sys.argv[1]) time_array = np.loadtxt(os.path.join(folder_path, "time.txt")) bilancia_array = np.loadtxt(os.path.join(folder_path, "bilancia.txt")) flow_array = np.loadtxt(os.path.join(folder_path, "portata.txt")) r_act_array = np.loadtxt(os.path.join(folder_path, "r_act.txt")) r_dyn_array = np.loadtxt(os.path.join(folder_path, "r_dyn.txt")) g_bilancia = get_g_from_bilancia(bilancia_array) g_from_flow = get_g_from_flow_and_setpoint(time_array, flow_array, 22.) fig = plt.figure(1) DPI = fig.get_dpi() fig.set_size_inches(float(800) / float(DPI), float(600) / float(DPI)) plt.plot(time_array - time_array[0], g_bilancia, '-o') plt.plot(time_array - time_array[0], g_from_flow) plt.plot(time_array - time_array[0], get_g_corrected_from_flow_and_setpoint(time_array, flow_array, 22., r_act_array, r_dyn_array)) plt.xlabel("Time [s]") plt.ylabel("Mass [g]") plt.title(folder_path.split("/")[1]) plt.legend(["Bilancia", "From flow", "From level"]) plt.savefig("img/mass_" + folder_path.split("/")[1] + ".svg", dpi=DPI) fig = plt.figure(2) DPI = fig.get_dpi() fig.set_size_inches(float(800) / float(DPI), float(600) / float(DPI)) plt.plot(time_array - time_array[0], get_error(g_bilancia, g_from_flow)) plt.xlabel("Time [s]") plt.ylabel("Error [%]") plt.title(folder_path.split("/")[1]) plt.ylim([0,35]) plt.savefig("img/error_" + folder_path.split("/")[1] + ".svg", dpi=DPI) plt.show() <file_sep>/IoTHub_RemoteMethodTester/library/measurement.py from abc import ABC, abstractmethod import logging import math import traceback from numpy.core.numeric import Infinity import library.utils as utils from library.base_db_manager import BaseDBManager, Query class Measurement(ABC): def __init__(self, machine_type, sensor_type, properties_dict, common_dictionary, parameters_keys=None): self.sensor_type = sensor_type self.machine_type = machine_type self.command = utils.get(properties_dict, 'COMMAND', default=None) self.interval = utils.parse_float(utils.get(properties_dict, 'INTERVAL', default=3600., common_dictionary=common_dictionary), default=3600.) self.uom = utils.get(properties_dict, 'UOM', default=None, common_dictionary=common_dictionary) self.skip_same_value = utils.parse_bool(utils.get(properties_dict, 'SKIP_SAME_VALUE', default=None, common_dictionary=common_dictionary), default=True) self.skip_max_time = utils.parse_float(utils.get(properties_dict, 'SKIP_MAX_TIME', default=None, common_dictionary=common_dictionary), default=900.) self.skip_threshold = utils.parse_float(utils.get(properties_dict, 'SKIP_THRESHOLD', default=None, common_dictionary=common_dictionary), default=1.e-6) self.skip_first = utils.parse_bool(utils.get(properties_dict, 'SKIP_FIRST', default=False, common_dictionary=common_dictionary), default=False) self.scale = utils.parse_float(utils.get(properties_dict, 'SCALE', default=1., common_dictionary=common_dictionary), default=1.) self.offset = utils.parse_float(utils.get(properties_dict, 'OFFSET', default=0., common_dictionary=common_dictionary), default=0.) self.not_send = utils.parse_bool(utils.get(properties_dict, 'NOT_SEND', default=False, common_dictionary=common_dictionary), default=False) self.operation = utils.get(properties_dict, 'OPERATION', default='READ', common_dictionary=common_dictionary) self.write_value = utils.parse_float(utils.get(properties_dict, 'VALUE', default=None, common_dictionary=common_dictionary), default=None) self.version = utils.parse_int(utils.get(properties_dict, 'VERSION', default=None, common_dictionary=common_dictionary), default=None) self.module_type = utils.get(properties_dict, 'MODULE_TYPE', default=None, common_dictionary=common_dictionary) self.pre_write_command = utils.get(properties_dict, 'PRE_WRITE_COMMAND', default=None, common_dictionary=common_dictionary) # SENSOR_TYPE OF PRE WRITE COMMAND self.post_write_command = utils.get(properties_dict, 'POST_WRITE_COMMAND', default=None, common_dictionary=common_dictionary) # SENSOR_TYPE OF POST WRITE COMMAND self.enabled = utils.parse_bool(utils.get(properties_dict, 'ENABLED', default=None, common_dictionary=common_dictionary), default=True) self.target_bit = utils.parse_int(utils.get(properties_dict, 'TARGET_BIT', default=None, common_dictionary=common_dictionary), default=None) self.target_bitmask_name = utils.get(properties_dict, 'TARGET_BITMASK_NAME', default=None, common_dictionary=common_dictionary) self.output_list = utils.get_single_or_list(properties_dict, 'OUTPUT', default=['output1'], common_dictionary=common_dictionary) self.timeout_safety_write = utils.parse_int(utils.get(properties_dict, 'TIMEOUT_SAFETY', default=None, common_dictionary=common_dictionary), default=None) self.default_value_timeout = utils.parse_float(utils.get(properties_dict, 'DEFAULT_VALUE_TIMEOUT', default=None), default=None) self.min_range = utils.parse_float(utils.get(properties_dict, 'MIN_RANGE', default=-Infinity, common_dictionary=common_dictionary), default=-Infinity) self.max_range = utils.parse_float(utils.get(properties_dict, 'MAX_rANGE', default=Infinity, common_dictionary=common_dictionary), default=Infinity) self.already_skipped = False # flag to be toggled in case of skip first self.time = None self.value = None # time and value not sent self.latest_time = None self.latest_value = None # old time and value sent self.old_time = None self.old_value = None # time and value for las variable write self.latest_time_write = None self.latest_value_write = None self.parameters = {} if parameters_keys is not None: for key in parameters_keys: self.parameters[key] = utils.get(properties_dict, key, default=None, common_dictionary=common_dictionary) def set_value(self, time, value, uom=None): self.time = time self.value = value if uom is not None: self.uom = uom def set_write_value(self, time, value, uom=None): self.latest_time_write = time self.latest_value_write = value if uom is not None: self.uom = uom @property def value_processed(self): return self.post_process_value(self.value) @property def old_value_processed(self): return self.post_process_value(self.old_value) @property def latest_value_processed(self): return self.post_process_value(self.old_value) def post_process_value(self, value): if isinstance(value, list): return [v * self.scale + self.offset for v in value] else: return value * self.scale + self.offset def can_send(self, new_time, new_value, uom=None): # UPDATE THE VALUE AND RETURN IF CAN SEND logging.getLogger().info(f'newvalue: {new_value}. value: {self.value}. skip_threshold: {self.skip_threshold}') ############################################################### logging.getLogger().info(f'new_time: {new_time}. time: {self.time}. skip_max_time: {self.skip_max_time}') ############################################################### print(f'newvalue: {new_value}. value: {self.value}. skip_threshold: {self.skip_threshold}') ############################################################### print(f'new_time: {new_time}. time: {self.time}. skip_max_time: {self.skip_max_time}') ############################################################### if not self.skip_same_value: self.set_value(new_time, new_value, uom=uom) return True value_threshold_flag = self.value is not None and abs(new_value - self.value) > self.skip_threshold time_threshold_flag = self.time is not None and (new_time - self.time).total_seconds() > self.skip_max_time if ( self.value is None or self.time is None or value_threshold_flag or time_threshold_flag ): self.old_value = self.value self.old_time = self.time self.set_value(new_time, new_value, uom=uom) if not value_threshold_flag: # not keep track of latest if we are updating due to long time from latest self.latest_time = None self.latest_value = None logging.getLogger().info(f'can_send: TRUE. new_value: {new_value}. self.value: {self.value}. new_time {new_time}. self.time: {self.time}') ############################################################### return True else: self.latest_time = new_time self.latest_value = new_value logging.getLogger().info(f'can_send: FALSE') ############################################################### return False def _get_type_key_(self): return 'sensor_type' def _get_default_version_(self): return 0 def _get_default_module_type_(self): return None def get_messages_json(self, current_only=False): if self.not_send: return [] payloads = [] # if we do not skip same value,we have already sent the latest if ( self.skip_same_value and not current_only and self.latest_value is not None and self.latest_time is not None and (isinstance(self.latest_value, list) or not math.isnan(self.latest_value)) ): if self.time != self.latest_time and self.value != self.latest_value: # append latest value before the jump if not math.isnan(self.latest_value): logging.getLogger().critical(f"SENDING EVEN THE LATEST VALUE!! {vars(self)}") msg = {} msg[self._get_type_key_()] = self.sensor_type msg['time'] = self.latest_time.strftime('%Y-%m-%dT%H:%M:%S') # .isoformat() msg['machine_type'] = self.machine_type msg['value'] = self.post_process_value(self.latest_value) msg['uom'] = self.uom msg['version'] = self.version if self.version is not None else self._get_default_version_() msg['module_type'] = self.module_type if self.module_type is not None else self._get_default_module_type_() # TODO # if msg['version'] is None: # in case of None version we let the azure function to guess a default value # def msg['version'] payloads.append(msg) # payloads.append({'time': self.latest_time.isoformat(), 'machine_type': self.machine_type, self._get_type_key_(): self.sensor_type, 'value': self.post_process_value(self.latest_value), 'uom': self.uom}) self.latest_time = None self.latest_value = None if self.value is not None and (isinstance(self.value, list) or not math.isnan(self.value)): msg = {} msg[self._get_type_key_()] = self.sensor_type msg['time'] = self.time.strftime('%Y-%m-%dT%H:%M:%S') # .isoformat() msg['machine_type'] = self.machine_type msg['value'] = self.post_process_value(self.value) msg['uom'] = self.uom msg['version'] = self.version if self.version is not None else self._get_default_version_() msg['module_type'] = self.module_type if self.module_type is not None else self._get_default_module_type_() # TODO # if msg['version'] is None: # in case of None version we let the azure function to guess a default value # def msg['version'] payloads.append(msg) # payloads.append({'time': self.time.isoformat(), 'machine_type': self.machine_type, self._get_type_key_(): self.sensor_type, 'value': self.post_process_value(self.value), 'uom': self.uom}) logging.getLogger().info(f'get_messages_json: {payloads}') ############################################################### return payloads class ModbusMeasurement(Measurement): def __init__(self, machine_type, sensor_type, properties_dict, common_dictionary, parameters_keys=None): super().__init__(machine_type, sensor_type, properties_dict, common_dictionary, parameters_keys=parameters_keys) self.register_number = utils.parse_int(utils.get(properties_dict, 'REGISTER_NUMBER', default=3600., common_dictionary=common_dictionary), default=None) self.register_type = utils.get(properties_dict, 'REGISTER_TYPE', default=None, common_dictionary=common_dictionary) self.value_type = utils.get(properties_dict, 'VALUE_TYPE', default=None, common_dictionary=common_dictionary) self.count = utils.get(properties_dict, 'COUNT', default=None, common_dictionary=common_dictionary) self.array_count = utils.get(properties_dict, 'ARRAY_COUNT', default=1, common_dictionary=common_dictionary) class FunctionMeasurement(Measurement): def __init__(self, machine_type, sensor_type, properties_dict, common_dictionary, parameters_keys=None): super().__init__(machine_type, sensor_type, properties_dict, common_dictionary, parameters_keys=parameters_keys) self.function = utils.get(properties_dict, 'FUNCTION', default=None, common_dictionary=common_dictionary) def evaluate(self, measurement_list): import library.math_parser as math_parser measurement_dict = {m.sensor_type: m for m in measurement_list} parser = math_parser.NumericStringParser(measurement_dict) try: value = parser.eval(self.function) return value except Exception as e: logging.error('ERROR in evaluate parser {}. traceback: {}'.format(e, traceback.format_exc())) logging.debug(e, exc_info=True) return None class QueryMeasurement(Measurement): def __init__(self, machine_type, sensor_type, properties_dict, common_dictionary, parameters_keys=None): super().__init__(machine_type, sensor_type, properties_dict, common_dictionary, parameters_keys=parameters_keys) self.query = properties_dict['QUERY'] # Mandatory def evaluate(self, db_manager): if self.query is None or len(self.query) == 0: return None result = db_manager.query_execute(Query(self.query), fetch=True, aslist=True) # result examples: # - [24.2599998] # - [None] result = result[0] return result class BitmaskMeasurement(Measurement): def __init__(self, machine_type, sensor_type, properties_dict, common_dictionary, parameters_keys=None): super().__init__(machine_type, sensor_type, properties_dict, common_dictionary, parameters_keys=parameters_keys) def evaluate(self, measurement_list): value = 0 for measurement in measurement_list: if measurement.target_bitmask_name is not None and measurement.target_bit is not None: if measurement.target_bitmask_name == self.sensor_type: if isinstance(measurement.value, list): for i, v in enumerate(value): # first item in the list goes to lowest bit value = value + (bool(round(v)) << measurement.target_bit + i) elif math.fabs(value, round(value)) < 1e-10: # manage it as an int of many bits value = value + (int(round(measurement.value)) << measurement.target_bit) else: # cast as bool value = value + (bool(round(measurement.value)) << measurement.target_bit) return value class AdamMeasurement(Measurement): def __init__(self, machine_type, sensor_type, properties_dict, common_dictionary, parameters_keys=None): super().__init__(machine_type, sensor_type, properties_dict, common_dictionary, parameters_keys=parameters_keys) self.channel = utils.parse_int(utils.get(properties_dict, 'CHANNEL', default=0, common_dictionary=common_dictionary), default=None) class ConfigMeasurement(Measurement): def __init__(self, machine_type, configuration_type, properties_dict, common_dictionary, parameters_keys=None): super().__init__(machine_type, configuration_type, properties_dict, common_dictionary, parameters_keys=parameters_keys) def _get_type_key_(self): return 'configuration_type' def _get_default_version_(self): return 1000 class ConfigModbusMeasurement(ModbusMeasurement): def __init__(self, machine_type, configuration_type, properties_dict, common_dictionary, parameters_keys=None): super().__init__(machine_type, configuration_type, properties_dict, common_dictionary, parameters_keys=parameters_keys) def _get_type_key_(self): return 'configuration_type' def _get_default_version_(self): return 1000 class ConfigFunctionMeasurement(FunctionMeasurement): def __init__(self, machine_type, configuration_type, properties_dict, common_dictionary, parameters_keys=None): super().__init__(machine_type, configuration_type, properties_dict, common_dictionary, parameters_keys=parameters_keys) def _get_type_key_(self): return 'configuration_type' def _get_default_version_(self): return 1000 class ConfigQueryMeasurement(QueryMeasurement): def __init__(self, machine_type, configuration_type, properties_dict, common_dictionary, parameters_keys=None): super().__init__(machine_type, configuration_type, properties_dict, common_dictionary, parameters_keys=parameters_keys) def _get_type_key_(self): return 'configuration_type' def _get_default_version_(self): return 1000 class ConfigBitmaskMeasurement(BitmaskMeasurement): def __init__(self, machine_type, configuration_type, properties_dict, common_dictionary, parameters_keys=None): super().__init__(machine_type, configuration_type, properties_dict, common_dictionary, parameters_keys=parameters_keys) def _get_type_key_(self): return 'configuration_type' def _get_default_version_(self): return 1000 if __name__ == "__main__": import datetime import time delta_time = 0.1 max_delta_time = 11 * 0.1 a = {"SKIP_SAME_VALUE": True, "SKIP_MAX_TIME": max_delta_time, 'SKIP_THRESHOLD': 1e-15} m = Measurement("MACHINE_TYPE", 'SENSOR_TYPE', a, {}) values_1 = [0] * 20 + [1] * 1 + [0] * 20 results = [] for value in values_1: m.can_send(datetime.datetime.utcnow(), value) results.extend(m.get_messages_json()) time.sleep(delta_time) <file_sep>/2_DEPLOY/RTUModbusModule/V1/library/__base_module_class.py import time import os import sys import asyncio from six.moves import input import datetime import json import library.utils as utils import threading import traceback import logging import random from abc import ABC, abstractmethod from azure.iot.device.aio import IoTHubModuleClient from azure.iot.device import MethodResponse, Message class BaseModuleClass(ABC): STATUS_OK = 200 STATUS_NOT_FOUND = 404 STATUS_ERROR = 500 def __init__(self): self.alive_delay = 60 self.alive_message = "I'M ALIVE" self.list_background_functions = [] self.init_logging('log.main') def init_logging(self, filename, level=logging.DEBUG, stdout=True): # logging config # for key in logging.Logger.manager.loggerDict: # print(key) # logging.basicConfig(filename=filename, filemode='w', level=logging.DEBUG, format='%(asctime)s - %(module)s - %(name)s - %(levelname)s - %(message)s') logging.basicConfig(filename=filename, filemode='w', format='%(asctime)s - %(module)s - %(name)s - %(levelname)s - %(message)s') logging.getLogger(__name__).setLevel(logging.DEBUG) logging.getLogger("pymodbus").setLevel(logging.CRITICAL) logging.getLogger("azure.iot").setLevel(logging.CRITICAL) logging.getLogger("azure").setLevel(logging.CRITICAL) if stdout: logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) self.logger = logging.getLogger(__name__) def is_simulator(self): return utils.parse_bool(os.getenv("SIMULATOR", default=False), default=False) def is_enabled(self): return utils.parse_bool(os.getenv("ENABLED", default=True), default=True) def check_python_version(self): if not sys.version >= "3.5.3": raise Exception( "The sample requires python 3.5.3+. Current version of Python: %s" % sys.version ) async def send_message_json(self, module_client, results, output='output1'): json_message = json.dumps(results) message = Message(json_message) self.logger.info("SENDING MESSAGE to {}: {}".format(output, json_message)) await module_client.send_message_to_output(message, output) def _init_module_client(self): self.module_client = IoTHubModuleClient.create_from_edge_environment() async def _connect_module_client(self): self.logger.info("CONNECTING TO MODULE CLIENT") await self.module_client.connect() self.logger.info("CONNECTED TO MODULE CLIENT") async def _disconnect_module_client(self): self.logger.info("DISCONNECTING MODULE CLIENT") await self.module_client.disconnect() self.logger.info("DISCONNECTED FROM MODULE CLIENT") def stdin_listener(self): while True: self.logger.debug(self.alive_message) time.sleep(self.alive_delay) def _run_background(self, *functions): listeners = asyncio.gather(*[f(self.module_client) for f in functions]) return listeners def _run_foreground(self): loop = asyncio.get_event_loop() user_finished = loop.run_in_executor(None, self.stdin_listener) return user_finished async def _run_async(self): try: self.check_python_version() self._init_module_client() await self._connect_module_client() print('self.list_background_functions', self.list_background_functions) listeners = self._run_background(*self.list_background_functions) user_finished = self._run_foreground() await user_finished listeners.cancel() await self._disconnect_module_client() except Exception as e: print ( "Unexpected error %s " % e ) raise def run(self): asyncio.run(self._run_async()) <file_sep>/ModBus_PLC2AzureDirectMethod/ModBus_PLC2AzureDirectMethod_v_0.0.1/setup.sh #bash! sudo docker kill mb_plc2azure_directmethod sudo docker rm mb_plc2azure_directmethod sudo docker-compose build sudo docker run --name mb_plc2azure_directmethod -d mb_plc2azure_directmethod <file_sep>/Modbus2DBs/Bilancia_Serial_2_Influx/device_looper.py import logging import logging.handlers import asyncio from sartorius import Sartorius from influxdb_module_class import InfluxDBModuleClass import copy from datetime import datetime class DeviceLooper(): def __init__(self, logger, bilancia: Sartorius, influxdb_client: InfluxDBModuleClass): self.bialncia = bilancia self.influx_client = influxdb_client self.logger = logger async def device_2_influx_db(self, device_instance, samplint_time, max_attempts): bkp_max_attemps=max_attempts while max_attempts>0: try: # lettura del valore try: _, value = device_instance.readValue() value = value if value is not None else -99.99 # Reset numero di tentativi max_attempts=bkp_max_attemps except Exception as e_in: self.logger.critical(f'::error: {e_in}::') device_instance.connect_to_sartorius() max_attempts-=1 # scrittura dati acquisiti su influxDB finally: asyncio.gather(self.influx_client.write_data('SARTORIUS_WEIGHT', value, datetime.utcnow().isoformat())) except Exception as e: self.logger.critical(f'::error: {e}::') # tempo di campionamento dal plc await asyncio.sleep(samplint_time) ######################################################################################################################## ### MAIN STARTER def start(self): # avvio lettura da device e scrittura su db loop = asyncio.run(self.device_2_influx_db(self.bialncia, self.bialncia.sampling_time/1000, self.bialncia.max_attempts)) loop.cancel() <file_sep>/GretaAnalogWriter/library/drago_aiao_96400.py import logging import os import time import sys import traceback import asyncio # import library.utils as utils import aenum from enum import Enum, auto from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder from pymodbus.payload import BinaryPayloadBuilder from pymodbus.client.sync import ModbusSerialClient from library.base_drago import ModbusTypes, IdentifiersCommands, DIPCommands, CommonCommands, BaseDrago, ModbusAccess # logging config # logging.basicConfig(filename='log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') # logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) class DragoAIAO96400Commands(aenum.Enum): _init_ = 'value register modbus_type access uom count' VALUE_AI_1 = auto(), 0, ModbusTypes.INT16, ModbusAccess.READ, 'uA', None VALUE_AI_2 = auto(), 1, ModbusTypes.INT16, ModbusAccess.READ, 'uA', None VALUE_AO_1 = auto(), 2, ModbusTypes.INT16, ModbusAccess.READ_WRITE, 'uA', None VALUE_AO_2 = auto(), 3, ModbusTypes.INT16, ModbusAccess.READ_WRITE, 'uA', None STATUS = auto(), 4, ModbusTypes.UINT16, ModbusAccess.READ, 'NONE', None DISCRETE_IO = auto(), 10, ModbusTypes.INT16, ModbusAccess.READ_WRITE, 'NONE', None VALUE_SCALED_AI_1 = auto(), 50, ModbusTypes.FLOAT32, ModbusAccess.READ, 'NONE', None VALUE_SCALED_AI_2 = auto(), 52, ModbusTypes.FLOAT32, ModbusAccess.READ, 'NONE', None VALUE_SCALED_AO_1 = auto(), 54, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'NONE', None VALUE_SCALED_AO_2 = auto(), 56, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'NONE', None INPUT_MODE_AI_1 = auto(), 2000, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'mA', None INPUT_FILTER_AI_1 = auto(), 2001, ModbusTypes.INT16, ModbusAccess.READ_WRITE, 'mA', None SCALE_IN_MIN_AI_1 = auto(), 2002, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'uA', None SCALE_IN_MAX_AI_1 = auto(), 2004, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'uA', None SCALE_OUT_MIN_AI_1 = auto(), 2006, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'NONE', None SCALE_OUT_MAX_AI_1 = auto(), 2008, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'NONE', None INPUT_LEVEL_AI_1 = auto(), 2030, ModbusTypes.INT16, ModbusAccess.READ_WRITE, 'NONE', None INPUT_MODE_AI_2 = auto(), 2100, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'mA', None INPUT_FILTER_AI_2 = auto(), 2101, ModbusTypes.INT16, ModbusAccess.READ_WRITE, 'mA', None SCALE_IN_MIN_AI_2 = auto(), 2102, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'uA', None SCALE_IN_MAX_AI_2 = auto(), 2104, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'uA', None SCALE_OUT_MIN_AI_2 = auto(), 2106, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'NONE', None SCALE_OUT_MAX_AI_2 = auto(), 2108, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'NONE', None INPUT_LEVEL_AI_2 = auto(), 2130, ModbusTypes.INT16, ModbusAccess.READ_WRITE, 'mA', None OUTPUT_MODE_AO_1 = auto(), 2400, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'mA', None OUTPUT_TIMEOUT_AO_1 = auto(), 2401, ModbusTypes.INT16, ModbusAccess.READ_WRITE, 'mA', None OUTPUT_INIT_AO_1 = auto(), 2402, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'uA', None OUTPUT_MODE_AO_2 = auto(), 2500, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'mA', None OUTPUT_TIMEOUT_AO_2 = auto(), 2501, ModbusTypes.INT16, ModbusAccess.READ_WRITE, 'mA', None OUTPUT_INIT_AO_2 = auto(), 2502, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'uA', None DIGITAL_IO_1 = auto(), 0, ModbusTypes.COIL, ModbusAccess.READ_WRITE, None, 1 DIGITAL_IO_2 = auto(), 1, ModbusTypes.COIL, ModbusAccess.READ_WRITE, None, 1 class DragoAIAO96400(BaseDrago): def __init__(self, variables_dict=None, logger=None): super().__init__(variables_dict=variables_dict, logger=logger) # self.setup_scale() def get_list_command_enums(self): return super().get_list_command_enums() + [DragoAIAO96400Commands] # async def setup_scale(self): # scale_in_min = utils.parse_float(self.get('ANALOG_SCALE_IN_MIN', default=4), default=4) # scale_in_max = utils.parse_float(self.get('ANALOG_SCALE_IN_MAX', default=20), default=20) # scale_out_min = utils.parse_float(self.get('ANALOG_SCALE_OUT_MIN', default=4), default=4) # scale_out_max = utils.parse_float(self.get('ANALOG_SCALE_OUT_MAX', default=20), default=20) # await self.execute_command_write(DragoAIAO96400Commands.SCALE_IN_MIN, scale_in_min) # await self.execute_command_write(DragoAIAO96400Commands.SCALE_IN_MAX, scale_in_max) # await self.execute_command_write(DragoAIAO96400Commands.SCALE_OUT_MIN, scale_out_min) # await self.execute_command_write(DragoAIAO96400Commands.SCALE_OUT_MAX, scale_out_max) async def setup_config_for_greta(self): commands_dict = {} commands_dict[DragoAIAO96400Commands.INPUT_MODE_AI_1] = 512 # digital input mode commands_dict[DragoAIAO96400Commands.INPUT_LEVEL_AI_1] = 1 # 12/24 v commands_dict[DragoAIAO96400Commands.OUTPUT_MODE_AO_1] = 0 # 0-20000 Ma commands_dict[DragoAIAO96400Commands.OUTPUT_TIMEOUT_AO_1] = 0 # timeout commands_dict[DragoAIAO96400Commands.OUTPUT_INIT_AO_1] = 1 # 12/24 v commands_dict[DragoAIAO96400Commands.OUTPUT_MODE_AO_2] = 0 # 0-20000 Ma commands_dict[DragoAIAO96400Commands.OUTPUT_TIMEOUT_AO_2] = 0 # timeout commands_dict[DragoAIAO96400Commands.OUTPUT_INIT_AO_2] = 1 # 12/24 v # commands_dict[CommonCommands.MODBUS_PC_UNIT_ID] = 10 # 12/24 v await self.write_configuration(commands_dict) async def setup_config_for_test(self): commands_dict = {} commands_dict[DragoAIAO96400Commands.INPUT_MODE_AI_2] = 0 # 0-20mA await self.write_configuration(commands_dict) async def get_config_for_greta(self): commands_list = [ DragoAIAO96400Commands.INPUT_MODE_AI_1, \ DragoAIAO96400Commands.INPUT_LEVEL_AI_1, \ DragoAIAO96400Commands.OUTPUT_MODE_AO_1, \ DragoAIAO96400Commands.OUTPUT_INIT_AO_1, \ DragoAIAO96400Commands.OUTPUT_TIMEOUT_AO_1, \ DragoAIAO96400Commands.OUTPUT_MODE_AO_2, \ DragoAIAO96400Commands.OUTPUT_INIT_AO_2, \ DragoAIAO96400Commands.OUTPUT_TIMEOUT_AO_2 ] results_dict = {} for command in commands_list: value, uom = await self.execute_command_read(command) results_dict[command] = value return results_dict def get_command_from_channel(self, channel): if channel == 'AI1': return DragoAIAO96400Commands.VALUE_AI_1 elif channel == 'AI2': return DragoAIAO96400Commands.VALUE_AI_2 elif channel == 'AO1': return DragoAIAO96400Commands.VALUE_AO_1 elif channel == 'AO2': return DragoAIAO96400Commands.VALUE_AO_2 elif channel == 'DO1' or channel == "DI1": return DragoAIAO96400Commands.DIGITAL_IO_1 elif channel == 'DO2' or channel == "DI2": return DragoAIAO96400Commands.DIGITAL_IO_2 if __name__ == "__main__": sys.path.append('./') sys.path.append('./library') async def main(): drago = DragoAIAO96400({"MODBUS_ID": 3}) # drago = DragoAIAO96400({"MODBUS_ID": 4}) await drago.connect_to_modbus_server() drago.modbus_id = 3 await drago.execute_command_write(DragoAIAO96400Commands.INPUT_MODE_AI_1, 768) # DO await drago.execute_command_write(DragoAIAO96400Commands.INPUT_LEVEL_AI_1, 1) # 12/24V INPUT # useless ? drago.modbus_id = 4 await drago.execute_command_write(DragoAIAO96400Commands.INPUT_MODE_AI_1, 512) # DI await drago.execute_command_write(DragoAIAO96400Commands.INPUT_LEVEL_AI_1, 1) # 12/24V INPUT for i in range(100): if i % 5 == 0: drago.modbus_id = 3 print('Read drago DISCRETE_IO: ', await drago.execute_command_read(DragoAIAO96400Commands.DISCRETE_IO)) if i % 10 == 0: await drago.execute_command_write(DragoAIAO96400Commands.DISCRETE_IO, 3) else: await drago.execute_command_write(DragoAIAO96400Commands.DISCRETE_IO, 3) drago.modbus_id = 4 print('Read drago: ', await drago.execute_command_read(DragoAIAO96400Commands.VALUE_AI_1)) await asyncio.sleep(1) # await drago.setup_scale() # print(f"Read {DragoAI96100Commands.VALUE_SCALED} : ", await drago.execute_command_read(DragoAI96100Commands.VALUE_SCALED)) # for e in drago.get_list_command_enums(): # for i in e: # print(f"Read {i} : ", await drago.execute_command_read(i)) asyncio.run(main()) <file_sep>/Modbus2DBs/Bilancia_Serial_2_Influx/main.py import json import os import logging import sys from influxdb_module_class import InfluxDBModuleClass from device_looper import DeviceLooper import library.utils as utils from sartorius import Sartorius ###################################################################################################################### # Parametri di configurazione sartorius_config_file = './config/sartorius.config' db_config_file = './config/db.config' ###################################################################################################################### # Initializzazione del logger # def init_logging(logger, filename, level=logging.INFO, stdout=True, maxBytes=10000, backupCount=5): logging.getLogger().setLevel(logging.NOTSET) logging.getLogger().handlers = [] rotatingHandler = logging.handlers.RotatingFileHandler(filename=filename, maxBytes=maxBytes, backupCount=backupCount) rotatingHandler.setLevel(logging.DEBUG) rotatingHandler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) logging.getLogger().addHandler(rotatingHandler) logging.getLogger(__name__).setLevel(level) logging.getLogger("bilancina").setLevel(logging.DEBUG) if stdout: logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) logger = logging.getLogger(__name__) logger.info('init_logging::end') ###################################################################################################################### def parseJsonConfig(file_full_path): #pwd = os.getcwd() if (os.path.isfile(file_full_path)): with open(file_full_path,"r") as f: return json.load(f) return None ###################################################################################################################### ### MAIN if __name__ == "__main__": logger = logging log_filename = 'test.log' init_logging(logger, log_filename) logger.info("::START::") logger.info("------------------------------------------------------") meas_ok:bool=True # Parsing delle variabili da file di configurazione. sartorius_dictinoary = parseJsonConfig(sartorius_config_file) db_dictionary = parseJsonConfig(db_config_file) # Connessione alla bilancia bilancia = Sartorius(logger, sartorius_dictinoary) # Connessione al DB InfluxDB #influxdb_client = InfluxDBModuleClass(logger, utils.get(db_dictionary,'INFLUXDB')) influxdb_client = None if bilancia.connect_to_sartorius(): logger.info("::SARTORIUS CONNECTED::") # Avvio lettura in loop delle variabili logger.info("::START READING SARTORIUS::") # device looper dev_loop = DeviceLooper(logger, bilancia, influxdb_client) # avvio loop dev_loop.start() logger.info("::STOP::") logger.info("------------------------------------------------------") <file_sep>/Bilancino/programma (copy)/main.py from sartorius import Sartorius from ingrid_modbus import IngridModbus import numpy as np import os import datetime import time import json import math import logging def get_flow(input_dict): register_num = input_dict["value"]["MASSFLOW"]["REGISTER_NUMBER"] value_type = input_dict["value"]["MASSFLOW"]["VALUE_TYPE"] return register_num, value_type if __name__ == '__main__': date_now = datetime.datetime.now() folder_path = os.path.join("results", date_now.strftime("%Y-%m-%dT%H:%M")) os.mkdir(folder_path) os.mknod(os.path.join(folder_path, "time.txt")) os.mknod(os.path.join(folder_path, "bilancia.txt")) os.mknod(os.path.join(folder_path, "portata.txt")) exp_duration = 5 # *60. with open("IngridModbusModule_3003.json") as json_file: modbus_json = json.load(json_file) logger = logging.getLogger("ingrid") ingrid = IngridModbus(logger, None, variables_dict=modbus_json) if not ingrid.connect(): raise Exception("Ingrid not able to connect") bilancia = Sartorius('/dev/ttyUSB0') if not bilancia.connect_to_sartorius(): raise Exception("Bilancia not able to connect") flow_register, flow_value_type = get_flow(modbus_json) for i in range(0, exp_duration): startime = time.time() time_array = np.loadtxt(os.path.join(folder_path, "time.txt")) bilancia_array = np.loadtxt(os.path.join(folder_path, "bilancia.txt")) flow_array = np.loadtxt(os.path.join(folder_path, "portata.txt")) try: time_array = np.append(time_array, datetime.datetime.now().timestamp() - date_now.timestamp()) bilancia_value = bilancia.readValue() flow_value = ingrid.read_value(flow_register, flow_value_type) if flow_value is not None: flow_array = np.append(flow_array, flow_value) # s.readValue() if not math.isnan(bilancia_value): bilancia_array = np.append(bilancia_array, bilancia_value) except: print("Wrong readed") np.savetxt(os.path.join(folder_path, "time.txt"), time_array) np.savetxt(os.path.join(folder_path, "bilancia.txt"), bilancia_array) np.savetxt(os.path.join(folder_path, "portata.txt"), flow_array) print("Run: ", i + 1, " ", round(time.time() - startime, 4), " s") sleeptime = 1 - (time.time() - startime) time.sleep(sleeptime) <file_sep>/ModBus_PLC2PLC/old/test_casa/plc_tester/library/postgresql_utils.py from sqlalchemy import create_engine import psycopg2 import psycopg2.extras import io import os import logging import traceback import itertools from io import StringIO from library.base_db_manager import BaseDBManager import library.utils as utils # engine = create_engine('postgresql+psycopg2://username:password@host:port/database') class Query(): def __init__(self, query, params=None, fast=False): self.query = query self.params = params self.fast = fast class PostgreSQLManager(BaseDBManager): def __init__(self, user=None, password=None, host=None, port=None, database=None, variables_dict=None, logger=None): super().__init__() variables_dict = utils.merge_dicts_priority(variables_dict, os.environ) self.user = utils.get(variables_dict, "POSTGRESQL_USERNAME", default=None) if user is None else user self.password = utils.get(variables_dict, "POSTGRESQL_PASSWORD", default=None) if password is None else password self.host = utils.get(variables_dict, "POSTGRESQL_HOST", default=None) if host is None else host self.port = utils.get(variables_dict, "POSTGRESQL_PORT", default=None) if port is None else port self.database = utils.get(variables_dict, "POSTGRESQL_DATABASE", default=None) if database is None else database self.logger = logger if logger is not None else logging.getLogger() @utils.overrides(BaseDBManager) def connect(self): # TODO IMPLEMENT RETRY POLICY # connection = psycopg2.connect( user=os.getenv("POSTGRESQL_USERNAME"), # password=os.getenv("<PASSWORD>"), # host=os.getenv("POSTGRESQL_HOST"), # port=os.getenv("POSTGRESQL_PORT"), # database=os.getenv("POSTGRESQL_DATABASE")) self.logger.info(f'Connecting to {self.user}@{self.host}:{self.port}/{self.database}.') self.connection = psycopg2.connect( user=self.user, password=<PASSWORD>, host=self.host, port=self.port, database=self.database) @utils.overrides(BaseDBManager) def disconnect(self): if self.connection is not None: if not self.connection.closed: self.logger.info(f'Disconnecting from {self.user}@{self.host}:{self.port}/{self.database}.') self.connection.close() # def get_connection(self): # if self.connection is None: # self.connect() # return self.connection @utils.overrides(BaseDBManager) def query_execute_many(self, query: Query, commit=False, fetch=False, aslist=False, asdataframe=False, columns=None): # connection = None cursor = None try: connection = self.get_connection() cursor = connection.cursor() # print ( connection.get_dsn_parameters(),"\n") # Print PostgreSQL Connection properties # executemany: 25s # execute_batch 12.5s # cursor.executemany(query, params) psycopg2.extras.execute_batch(cursor, query.query, query.params, page_size=500) if commit: connection.commit() except: print(traceback.format_exc()) finally: # if(connection): cursor.close() # connection.close() @utils.overrides(BaseDBManager) def query_execute(self, query: Query, commit=False, fetch=False, aslist=False, asdataframe=False, columns=None): cursor = None try: connection = self.get_connection() cursor = connection.cursor() # print ( connection.get_dsn_parameters(),"\n") # Print PostgreSQL Connection properties cursor.execute(query.query) results = None if fetch: results = [] row = cursor.fetchone() while row: results_list = list() for el in list(row): if isinstance(el, str): results_list.append(el.strip()) elif isinstance(el, float): results_list.append(round(el, 7)) # TODO else: results_list.append(el) results.append(results_list) row = cursor.fetchone() if commit: connection.commit() if results is not None and aslist: results = list(itertools.chain(*results)) elif results is not None and asdataframe: import pandas results = pandas.DataFrame(results, columns=columns) return results except: print(traceback.format_exc()) finally: # if(connection): cursor.close() # connection.close() @utils.overrides(BaseDBManager) def query_execute_list(self, query_list, commit=False): cursor = None try: connection = self.get_connection() cursor = connection.cursor() # print ( connection.get_dsn_parameters(),"\n") # Print PostgreSQL Connection properties for query in query_list: # cursor.fast_executemany = query.fast # TODO find an alternative if query.params is None: cursor.execute(query.query) else: if len(query.params) > 0: cursor.executemany(query.query, query.params) if commit: connection.commit() except: if cursor is not None: cursor.rollback() print(traceback.format_exc()) finally: # if(connection): cursor.close() # connection.close() @utils.overrides(BaseDBManager) def query_execute_copy(self, df, destination_table, columns=None, commit=False): cursor = None try: connection = self.get_connection() cursor = connection.cursor() f = StringIO() df.to_csv(f, sep=',', header=False, index=False, quoting=3) f.seek(0) cursor.copy_from(f, destination_table, columns=columns, sep=',') if commit: connection.commit() except: # if cursor is not None: # cursor.rollback() if connection is not None: print('ROLLBACK') connection.rollback() print(traceback.format_exc()) finally: # if(connection): cursor.close() # connection.close()<file_sep>/IoTHub_RemoteMethodTester/library/base_iothub_readwriter_client.py import time import os import sys import asyncio from six.moves import input import datetime import json import threading import traceback import logging import random from abc import ABC, abstractmethod # from azure.iot.device.aio import IoTHubModuleClient from azure.iot.device import MethodResponse, Message import library.utils as utils # from library.base_module_class import BaseModuleClass from library.base_iothub_client import BaseIotHubClient, IobHubRemoteMethodStatus from library.measurement import Measurement, ModbusMeasurement, FunctionMeasurement, BitmaskMeasurement, QueryMeasurement from library.postgresql_utils import PostgreSQLManager class BaseIotHubReadWriterClient(BaseIotHubClient): STATUS_OK = 200 def __init__(self, measurement_list, config_measurement_list=[], variables_dict=None): super().__init__(variables_dict=variables_dict) self.list_background_functions.append(self.command_directmethod) self.list_background_functions.append(self.start_reader_loop) self.list_background_functions.append(self.start_config_reader_loop) self.list_background_functions.append(self.default_values_write_loop) self.sleep_interval = utils.parse_float(self._get_('SLEEP_INTERVAL'), default=30.) # default 30 seconds self.sleep_write_timeout_check = utils.parse_float(self._get_('SLEEP_WRITE_TIMEOUT_CHECK'), default=self.sleep_interval) # default 30 seconds self.config_sleep_interval = utils.parse_float(self._get_('CONFIG_SLEEP_INTERVAL'), default=3600.) # default 30 seconds self.enable_db = utils.parse_bool(self._get_('ENABLE_LOCAL_DB_CONNECTION'), default=False) # default disabled self.measurement_list = measurement_list self.config_measurement_list = config_measurement_list self.db_manager = PostgreSQLManager(variables_dict=variables_dict, logger=self.logger) ####################################################################### @abstractmethod async def init_device_instance(self): return None @abstractmethod async def connect_device(self, device_instance): pass @abstractmethod async def disconnect_device(self, device_instance): pass ####################################################################### def _get_measurement_from_sensor_type_(self, sensor_type): for m in self.measurement_list: if m.sensor_type == sensor_type: return m return None ############################################################################################### async def process_measurement_group(self, measurement_list, f_to_call, time=None): if self.enable_db: self.db_manager.connect() results_measurement = await self.process_device_measurements(self, measurement_list, f_to_call, time) if self.enable_db: self.db_manager.disconnect() return results_measurement async def process_device_measurements(self, measurement_list, f_to_call, *args, **kwargs): device_instance = await self.init_device_instance() await self.connect_device(device_instance) results_measurement = await self.process_measurements(measurement_list, device_instance, f_to_call, *args, **kwargs) await self.disconnect_device(device_instance) return results_measurement async def process_measurements(self, measurement_list, f_to_call, *args, **kwargs): results_measurement = [] # if time is None: time = datetime.datetime.utcnow() query_measurement_list, other_measurement_list = utils.split_list(measurement_list, lambda x: isinstance(x, QueryMeasurement)) function_measurement_list, other_measurement_list = utils.split_list(other_measurement_list, lambda x: isinstance(x, FunctionMeasurement)) bitmask_measurement_list, other_measurement_list = utils.split_list(other_measurement_list, lambda x: isinstance(x, BitmaskMeasurement)) # execute other_measurement_list before function_measurement_list for m in other_measurement_list + query_measurement_list + function_measurement_list + bitmask_measurement_list: result = await f_to_call(self, m, time, *args, **kwargs) if result is not None: results_measurement.append(m) # m.get_messages_json()) return results_measurement async def process_reads(self, m, measurement_list, time, *args, **kwargs): logging.info(f'time - m.time: {time} - {m.time}. m.interval: {m.interval}') ############################################################### if m.time is None or abs((time - m.time).total_seconds()) >= m.interval: return await self.check_and_process_measurements(m, measurement_list, *args, **kwargs) async def process_default_periodic_writes(self, m, measurement_list, time, *args, **kwargs): logging.default(f'time - m.latest_time_write: {time} - {m.latest_time_write}. m.timeout_safety_write: {m.timeout_safety_write}') ############################################################### if m.timeout_safety_write is not None and abs((time - m.latest_time_write).total_seconds()) >= m.timeout_safety_write: m.write_value = m.default_value_timeout old_operation = m.operation m.operation = 'WRITE' value = await self.check_and_process_measurements(m, measurement_list, *args, **kwargs) m.operation = old_operation m.set_write_value(time, value) return value async def check_and_process_measurements(self, m, measurement_list, *args, **kwargs): value = None try: # if the first time has not to be skipped or it has already been skippen execute the measurement if m.enabled: if not m.skip_first or m.already_skipped: value, uom = await self.execute_measurement_switch(m, measurement_list, *args, **kwargs) else: m.already_skipped = True m.set_value(datetime.datetime.utcnow(), None) else: self.logger.info(f'process_measurements::disabled_measurement::{m.command}') except Exception as e: value = None uom = None self.logger.error(f'process_measurements::error::sensor_type::{m.sensor_type}') self.logger.debug(f'process_measurements::error::{traceback.format_exc()}') # self.logger.error('ERROR reading: {}'.format(m.sensor_type)) # self.logger.debug(e, exc_info=True) if value is not None and m.can_send(time, value, uom): return value async def execute_measurement_switch(self, measurement, measurement_list, *args, **kwargs): if isinstance(measurement, BitmaskMeasurement): value, uom = await self.execute_bitmask_measurement(measurement, measurement_list, *args, **kwargs) elif isinstance(measurement, FunctionMeasurement): value, uom = await self.execute_function_measurement(measurement, measurement_list, *args, **kwargs) elif isinstance(measurement, QueryMeasurement): value, uom = await self.execute_query_measurement(measurement, measurement_list, *args, **kwargs) elif isinstance(measurement, ModbusMeasurement): value, uom = await self.execute_modbus_measurement(measurement, measurement_list, *args, **kwargs) else: value, uom = await self.execute_measurement(measurement, measurement_list, *args, **kwargs) return value, uom async def execute_measurement(self, measurement, measurement_list, *args, **kwargs): self.logger.debug(f'execute_measurement::measurement::{vars(measurement)}') if not self.is_simulator(): device_instance = args[0] if measurement.operation == 'READ': value, uom = await device_instance.execute_command_str(measurement.command) else: # WRITE await self._pre_write_command_execute_(measurement, measurement_list, *args, **kwargs) value, uom = await device_instance.execute_command_str_write(measurement.command, measurement.write_value) await self._post_write_command_execute_(measurement, measurement_list, *args, **kwargs) else: value, uom = await self._execute_measurement_modbus_simulator_(measurement, *args, **kwargs) self.logger.info(f'execute_measurement::{measurement.sensor_type}::{value}::{uom}') # self.logger.info(f' : value: {value}') return value, uom async def execute_modbus_measurement(self, measurement, measurement_list, *args, **kwargs): self.logger.debug(f'execute_modbus_measurement::measurement::{vars(measurement)}') if not self.is_simulator(): device_instance = args[0] if measurement.operation == 'READ': value = await device_instance.read_value(measurement.register_number, measurement.value_type, register_type=measurement.register_type, count=measurement.count, array_count=measurement.array_count) elif measurement.operation == 'DUMP': value = await device_instance.read_registers_in_batch(measurement.register_number, measurement.count, register_type=measurement.register_type, max_batch_size=100) else: # WRITE value = await self.device_write_pre_and_post(device_instance, measurement, measurement_list, *args, **kwargs) uom = measurement.uom else: value, uom = await self._execute_measurement_modbus_simulator_(measurement, *args, **kwargs) self.logger.info(f'execute_modbus_measurement::{measurement.sensor_type}::{value}::{uom}') return value, uom async def device_write_pre_and_post(self, device_instance, measurement, measurement_list, *args, **kwargs): await self._pre_write_command_execute_(measurement, measurement_list, *args, **kwargs) value = await device_instance.write_value(measurement.register_number, measurement.value_type, measurement.write_value, count=measurement.count) await self._post_write_command_execute_(measurement, measurement_list, *args, **kwargs) return value async def execute_function_measurement(self, measurement, measurement_list, *args, **kwargs): self.logger.debug(f'execute_function_measurement::measurement::{vars(measurement)}') if not self.is_simulator(): value = measurement.evaluate(measurement_list) uom = measurement.uom else: value, uom = await self._execute_measurement_function_simulator_(measurement, *args, **kwargs) self.logger.info(f'execute_function_measurement::{measurement.sensor_type}::{value}::{uom}') return value, uom async def execute_query_measurement(self, measurement, measurement_list, *args, **kwargs): self.logger.debug(f'execute_query_measurement::measurement::{vars(measurement)}') if not self.is_simulator(): if not self.enable_db: self.logger.critical(f'ENABLE_LOCAL_DB_CONNECTION is {self.enable_db}. Enable it to run QUERY_MEASUREMENT') return None, None value = measurement.evaluate(self.db_manager) uom = measurement.uom else: value, uom = await self._execute_measurement_query_simulator_(measurement, *args, **kwargs) self.logger.info(f'execute_query_measurement::{measurement.sensor_type}::{value}::{uom}') return value, uom async def execute_bitmask_measurement(self, measurement, measurement_list, *args, **kwargs): self.logger.debug(f'execute_bitmask_measurement::measurement::{vars(measurement)}') if not self.is_simulator(): value = measurement.evaluate(measurement_list) uom = measurement.uom else: value, uom = await self._execute_measurement_bitmask_simulator_(measurement, *args, **kwargs) self.logger.info(f'execute_bitmask_measurement::{measurement.sensor_type}::{value}::{uom}') return value, uom ############################################################################################### async def _pre_write_command_execute_(self, measurement, measurement_list, *args, **kwargs): if measurement.pre_write_command is not None: self.logger.info(f'_pre_write_command_execute_::{measurement.pre_write_command}') pre_measurement = self._get_measurement_from_sensor_type_(measurement.pre_write_command) await self.execute_measurement_switch(pre_measurement, measurement_list, *args, **kwargs) async def _post_write_command_execute_(self, measurement, measurement_list, *args, **kwargs): if measurement.post_write_command is not None: self.logger.info(f'_post_write_command_execute_::{measurement.post_write_command}') pre_measurement = self._get_measurement_from_sensor_type_(measurement.post_write_command) await self.execute_measurement_switch(pre_measurement, measurement_list, *args, **kwargs) ############################################################################################### async def _execute_measurement_simulator_(self, measurement, *args, **kwargs): return None, None async def _execute_measurement_modbus_simulator_(self, measurement, *args, **kwargs): return None, None async def _execute_measurement_function_simulator_(self, measurement, *args, **kwargs): return None, None async def _execute_measurement_query_simulator_(self, measurement, *args, **kwargs): return None, None async def _execute_measurement_bitmask_simulator_(self, measurement, *args, **kwargs): return None, None ############################################################################################### async def get_measurement_from_command(self, command_data): self.logger.debug(f'get_measurement_from_command::command_data::{command_data}') properties_dict = utils.merge_dicts_priority({'SKIP_SAME_VALUE': False}, command_data) measurement = Measurement(self.machine_type, command_data['COMMAND'], properties_dict=properties_dict, common_dictionary={}) self.logger.debug(f'get_measurement_from_command::measurement::{vars(measurement)}') return [measurement] async def get_measurement_from_modbus_command(self, command_data): self.logger.debug(f'get_measurement_from_modbus_command::command_data::{command_data}') # if command_data['DEVICE'] == 'INGRID': register = command_data['REGISTER_NUMBER'] name = command_data['NAME'] if 'NAME' in command_data else "REGISTER_{}".format(register) properties_dict = utils.merge_dicts_priority({'SKIP_SAME_VALUE': False}, command_data) measurement = ModbusMeasurement(self.machine_type, name, properties_dict=properties_dict, common_dictionary={}) self.logger.debug(f'get_measurement_from_modbus_command::measurement::{vars(measurement)}') return [measurement] async def get_measurement_from_function_command(self, command_data): self.logger.debug(f'get_measurement_from_function_command::command_data::{command_data}') # if command_data['DEVICE'] == 'INGRID': # function = command_data['Function'] name = command_data['NAME'] if 'NAME' in command_data else "FUNCTION" properties_dict = utils.merge_dicts_priority({'SKIP_SAME_VALUE': False}, command_data) measurement = FunctionMeasurement(self.machine_type, name, properties_dict=properties_dict, common_dictionary={}) self.logger.debug(f'get_measurement_from_function_command::measurement::{vars(measurement)}') return [measurement] async def get_measurement_from_query_command(self, command_data): self.logger.debug(f'get_measurement_from_query_command::command_data::{command_data}') name = command_data['NAME'] if 'NAME' in command_data else "QUERY" properties_dict = utils.merge_dicts_priority({'SKIP_SAME_VALUE': False}, command_data) measurement = QueryMeasurement(self.machine_type, name, properties_dict=properties_dict, common_dictionary={}) self.logger.debug(f'get_measurement_from_query_command::measurement::{vars(measurement)}') return [measurement] async def get_measurement_from_bitmask_command(self, command_data): self.logger.debug(f'get_measurement_from_bitmask_command::command_data::{command_data}') name = command_data['NAME'] if 'NAME' in command_data else "BITMASK" properties_dict = utils.merge_dicts_priority({'SKIP_SAME_VALUE': False}, command_data) measurement = BitmaskMeasurement(self.machine_type, name, properties_dict=properties_dict, common_dictionary={}) self.logger.debug(f'get_measurement_from_bitmask_command::measurement::{vars(measurement)}') return [measurement] ############################################################################################### ############################################################################################### async def default_values_write_loop(self, iothub_client): self.logger.debug(f'default_values_write_loop::start') ############################################################### while True: if not self.is_enabled(): await asyncio.sleep(10) else: try: if self.measurement_list is not None and len(self.measurement_list) > 0: results_measurement = await self.process_measurement_group(self.measurement_list, f_to_call=self.process_default_periodic_writes) group_masurement_by_output = self.group_measurement_list_by_output(results_measurement) for output, measurements_for_output in group_masurement_by_output.items(): # send messages for single output if len(measurements_for_output) > 0: await self.send_measurement_list(iothub_client, measurements_for_output, output) except Exception as e: self.logger.error(f'default_values_write_loop::error') self.logger.debug(f'default_values_write_loop::error::{traceback.format_exc()}') # self.logger.error(e, exc_info=True) # self.logger.debug(traceback.format_exc()) await asyncio.sleep(self.sleep_write_timeout_check) ############################################################################################### ############################################################################################### async def start_reader_loop(self, iothub_client): self.logger.info(f'start_reader_loop::start') ############################################################### while True: if not self.is_enabled(): await asyncio.sleep(10) else: try: if self.measurement_list is not None and len(self.measurement_list) > 0: results_measurement = await self.process_measurement_group(self.measurement_list, f_to_call=self.process_reads) group_masurement_by_output = self.group_measurement_list_by_output(results_measurement) for output, measurements_for_output in group_masurement_by_output.items(): # send messages for single output if len(measurements_for_output) > 0: await self.send_measurement_list(iothub_client, measurements_for_output, output) except Exception as e: self.logger.error(f'start_reader_loop::error') self.logger.debug(f'start_reader_loop::error::{traceback.format_exc()}') # self.logger.error(e, exc_info=True) # self.logger.debug(traceback.format_exc()) await asyncio.sleep(self.sleep_interval) ############################################################################################### ############################################################################################### async def start_config_reader_loop(self, iothub_client): self.logger.info(f'start_config_reader_loop::start') ############################################################### while True: if not self.is_config_enabled(): await asyncio.sleep(10) else: try: if self.config_measurement_list is not None and len(self.config_measurement_list) > 0: results_measurement = await self.process_measurement_group(self.config_measurement_list, f_to_call=self.process_reads) if len(results_measurement) > 0: group_masurement_by_output = self.group_measurement_list_by_output(results_measurement) for output, measurements_for_output in group_masurement_by_output.items(): if len(measurements_for_output) > 0: # send messages for single output await self.send_measurement_list(iothub_client, measurements_for_output, output) else: self.logger.info(f'start_config_reader_loop::results:{results_measurement}::none_or_empty') ############################################################### else: self.logger.info(f'start_config_reader_loop::config_measurement_list:{self.config_measurement_list}::none_or_empty') ############################################################### except Exception as e: self.logger.error(f'start_config_reader_loop::error') self.logger.debug(f'start_config_reader_loop::error::{traceback.format_exc()}') # self.logger.error(e, exc_info=True) # self.logger.debug(traceback.format_exc()) await asyncio.sleep(self.config_sleep_interval) ############################################################################################### ############################################################################################### async def command_directmethod(self, iothub_client, output_topic=None): await utils.base_listener_directmethod(iothub_client, 'command', self._command_raw_, output_topic=output_topic, logger=self.logger) ############################################################################################### ############################################################################################### async def get_measurement_from_command_switch(self, data): measurement_sublist = None if utils.get(data, 'PROTOCOL', default='') == 'MODBUS': measurement_sublist = await self.get_measurement_from_modbus_command(data) elif utils.get(data, 'PROTOCOL', default='') == 'FUNCTION': measurement_sublist = await self.get_measurement_from_function_command(data) elif utils.get(data, 'PROTOCOL', default='') == 'QUERY': measurement_sublist = await self.get_measurement_from_query_command(data) elif utils.get(data, 'PROTOCOL', default='') == '': measurement_sublist = await self.get_measurement_from_function_command(data) else: measurement_sublist = await self.get_measurement_from_command(data) return measurement_sublist async def _command_raw_(self, payload): """ { "DEVICE": "INGRID", "PROTOCOL": "MODBUS", "OPERATION": "READ", "REGISTER_NUMBER": 100, "VALUE_TYPE": "FLOAT32" } """ try: self.logger.info(f'_command_raw_::start::payload::{payload}') if not isinstance(payload, dict): data = json.loads(payload) else: data = payload measurement_list = [] if 'COMMANDS' not in data: # SINGLE COMMAND SENT measurement_sublist = await self.get_measurement_from_command_switch(data) if measurement_sublist is not None: measurement_list.extend(measurement_sublist) else: # results = [] for command in data['COMMANDS']: command_data = utils.merge_dicts_priority(command, utils.without_keys(data, 'COMMANDS')) measurement_sublist = await self.get_measurement_from_command_switch(command_data) if measurement_sublist is not None: measurement_list.extend(measurement_sublist) results = await self.process_measurement_group(measurement_list, self.process_reads) self.logger.info(f'_command_raw_::results::{results}') return IobHubRemoteMethodStatus.STATUS_OK, results except Exception as e: self.logger.error(f'_command_raw_::error::payload::{payload}') self.logger.debug(f'_command_raw_::error::{traceback.format_exc()}') # self.logger.error('ERROR in command {}. Payload: {}. Type Payload: {}'.format(e, payload, type(payload))) # self.logger.debug(e, exc_info=True) return IobHubRemoteMethodStatus.STATUS_OK, traceback.format_exc() ############################################################################################### ############################################################################################### def group_measurement_list_by_output(self, measurement_list): groups = {} for m in measurement_list: for output in m.output_list: # insert outputs in groups if missing if output not in groups: groups[output] = [] # append measurement to the correspondant group groups[output].append(m) return groups async def send_measurement_list(self, iothub_client, measurement_list, output): if len(measurement_list) > 0: results_json = [] for m in measurement_list: results_json.extend(m.get_messages_json()) if len(results_json) > 0: self.logger.info(f"output topic: {output}") self.logger.info(results_json) await self.send_message_json(iothub_client, results_json, output=output) <file_sep>/Modbus2DBs/Microturbine_RTU_2_Influx/testing_ok/plc_reader (copy)/reconfigure.sh #bash! # da eseguire in seguito a modifiche a file di configurazione o software export sudo_password='<PASSWORD>' echo $sudo_password | sudo -S docker kill plc_read_2_influxdb sudo docker rm plc_writer sudo docker-compose build sudo docker run --name plc_read_2_influxdb -d plc_read_2_influxdb <file_sep>/2_DEPLOY/RTUModbusModule/V1/library/base_iothub_client.py import time import os import sys import asyncio from six.moves import input import datetime import json import library.utils as utils import threading import traceback import logging import logging.handlers import random from enum import Enum, auto from abc import ABC, abstractmethod # from azure.iot.device.aio import IoTHubModuleClient from azure.iot.device import MethodResponse, Message class IobHubRemoteMethodStatus(Enum): STATUS_OK = 200 STATUS_NOT_FOUND = 404 STATUS_ERROR = 500 class BaseIotHubClient(ABC): # STATUS_OK = 200 # STATUS_NOT_FOUND = 404 # STATUS_ERROR = 500 def __init__(self, machine_type, variables_dict=None): self.machine_type = machine_type self.variables_dict = utils.merge_dicts_priority(variables_dict, os.environ) # os.environ if variables_dict is None else variables_dict self.alive_delay = 60 self.alive_message = "I'M ALIVE" self.list_background_functions = [] self.init_logging('log.main') self.iothub_client = None ###################################################################################################################### def _get_(self, key, default=None): return utils.get(self.variables_dict, key, default=default) ###################################################################################################################### def init_logging(self, filename, level=logging.DEBUG, stdout=True, maxBytes=10000, backupCount=5): # logging.basicConfig(filename=filename, filemode='w', format='%(asctime)s - %(module)s - %(name)s - %(levelname)s - %(message)s') logging.getLogger().setLevel(logging.NOTSET) logging.getLogger().handlers = [] rotatingHandler = logging.handlers.RotatingFileHandler(filename=filename, maxBytes=maxBytes, backupCount=backupCount) rotatingHandler.setLevel(logging.DEBUG) rotatingHandler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) logging.getLogger().addHandler(rotatingHandler) logging.getLogger(__name__).setLevel(level) logging.getLogger("pymodbus").setLevel(logging.CRITICAL) logging.getLogger("azure.iot").setLevel(logging.CRITICAL) logging.getLogger("azure").setLevel(logging.CRITICAL) if stdout: logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) self.logger = logging.getLogger(__name__) self.logger.info('init_logging::end') ###################################################################################################################### def is_simulator(self): return utils.parse_bool(self._get_("SIMULATOR"), default=False) def is_enabled(self): return utils.parse_bool(self._get_("ENABLED"), default=True) def is_config_enabled(self): return utils.parse_bool(self._get_("CONFIG_ENABLED"), default=True) def check_python_version(self): if not sys.version >= "3.5.3": raise Exception( "The sample requires python 3.5.3+. Current version of Python: %s" % sys.version ) ###################################################################################################################### async def send_message_json(self, module_client, message_json, *args, **kwargs): #output='output1'): message_str = json.dumps(message_json) message = Message(message_str) self.logger.info(f'send_message_json::{message_str}') await self._internal_send_message_(message, *args, **kwargs) async def call_remote_method(self, device_id, method_name, module_id=None, payload="{}", response_timeout=5, connect_timeout=5): method_params = { "methodName": method_name, "payload": payload, "responseTimeoutInSeconds": response_timeout, "connectTimeoutInSeconds": connect_timeout, } response = await self.iothub_client.invoke_method(method_params=method_params, device_id=device_id, module_id=module_id) return response ###################################################################################################################### async def get_twin(self): # TODO TRY CATCH IN CASE OF ERRORS self.twin = await self.iothub_client.iothub_client.get_twin()['desired'] return self.twin async def set_twin(self): # TODO TRY CATCH IN CASE OF ERRORS await self.iothub_client.patch_twin_reported_properties(self.twin) #twin['desired']) ###################################################################################################################### ###################################################################################################################### def stdin_listener(self): while True: if self.alive_message is not None: self.logger.debug(self.alive_message) time.sleep(self.alive_delay) def _run_background_(self, *functions): listeners = asyncio.gather(*[f(self.iothub_client) for f in functions]) return listeners def _run_foreground_(self): loop = asyncio.get_event_loop() user_finished = loop.run_in_executor(None, self.stdin_listener) return user_finished async def _run_async_(self): try: self.check_python_version() await self._init_iothub_client_() await self._connect_module_client_() listeners = self._run_background_(*self.list_background_functions) user_finished = self._run_foreground_() await user_finished listeners.cancel() await self._disconnect_module_client_() except Exception as e: print ( "Unexpected error %s " % e ) raise def run(self): asyncio.run(self._run_async_()) ###################################################################################################################### ###################################################################################################################### @abstractmethod async def _internal_send_message_(self, message, *args, **kwargs): pass @abstractmethod async def _init_iothub_client_(self): pass async def _connect_module_client_(self): await self.iothub_client.connect() async def _disconnect_module_client_(self): await self.iothub_client.disconnect() ###################################################################################################################### ###################################################################################################################### def register_twin_properties_listener(self): self.list_background_functions.append(self.twin_properties_listener) async def twin_properties_listener(self, iothub_client): await utils.twin_properties_listener(iothub_client, self.twin_properties_updated, logger=self.logger) async def twin_properties_updated(self, patch): pass<file_sep>/GretaAnalogWriter/door_module_class.py import time import os import sys import asyncio from six.moves import input import datetime import json import threading import traceback import logging import random from abc import ABC, abstractmethod from azure.iot.device.aio import IoTHubModuleClient from azure.iot.device import MethodResponse, Message # from library.base_module_class import BaseModuleClass # from library.base_reader_module_class import BaseReaderModuleClass from library.base_iothub_reader_module_client import BaseIotHubReaderModuleClient from library.measurement import Measurement, ModbusMeasurement import library.utils as utils from library.drago_aiao_96400 import DragoAIAO96400, DragoAIAO96400Commands from library.drago_ai_96100 import DragoAI96100, DragoAI96100Commands from library.drago_dido_96700 import DragoDIDO96700, DragoDIDO96700Commands from library.drago_rele_96800 import DragoRELE96800, DragoRELE96800Commands class DoorModuleClass(BaseIotHubReaderModuleClient): MACHINE_TYPE = "SECURITY" def __init__(self): super().__init__(self.MACHINE_TYPE, None, None) measurement_list = utils.get_all_measurement_list(DoorModuleClass.MACHINE_TYPE, os.environ) config_measurement_list = utils.get_config_measurement_list(DoorModuleClass.MACHINE_TYPE, os.environ, logger=self.logger) self.measurement_list = measurement_list self.config_measurement_list = config_measurement_list self.device_type = utils.get(self.variables_dict, 'DEVICE_TYPE', default='DragoAIAO96400') def _get_device_(self): if self.device_type == 'DragoAI96100': device_class = DragoAI96100 elif self.device_type == 'DragoAIAO96400': device_class = DragoAIAO96400 elif self.device_type == 'DragoDIDO96700': device_class = DragoDIDO96700 elif self.device_type == 'DragoRELE96800': device_class = DragoRELE96800 else: self.logger.critical(f'DoorModuleClass::_get_device_::device_type {self.device_type} not recognized') return None return device_class(variables_dict=self.variables_dict, logger=self.logger) async def init_device_instance(self): return self._get_device_() # return DragoDIDO96700(os.environ, logger=self.logger) async def connect_device(self, device_instance): await device_instance.connect_to_modbus_server() async def disconnect_device(self, device_instance): await device_instance.close_modbus_client() <file_sep>/ModBus_PLC2PLC/ModBus_PLC2PLC_v_0.0.1/requirements.txt pymodbus asyncio datetime six pyparsing pandas<file_sep>/Modbus2DBs/Bilancia_Serial_2_Influx/reconfigure.sh #bash! # da eseguire in seguito a modifiche a file di configurazione o software export sudo_password='<PASSWORD>' echo $sudo_password | sudo -S docker kill serial_2_influxdb sudo docker rm serial_2_influxdb sudo docker-compose build # RUN con apertura della porta seriale sudo docker run --device=/dev/ttyUSB0 --privileged --name serial_2_influxdb -d serial_2_influxdb <file_sep>/Bilancino/programma (another copy)/ingrid_modbus.py # from pymodbus.client.asynchronous.tcp import AsyncModbusTCPClient as ModbusTcpClient # from pymodbus.client.asynchronous.udp import (AsyncModbusUDPClient as ModbusUdpClient) # from pymodbus.client.asynchronous import schedulers import logging import os import time import sys import traceback import asyncio from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder from pymodbus.payload import BinaryPayloadBuilder from pymodbus.client.sync import ModbusTcpClient import library.utils as utils from library.base_modbus import BaseModbus, ModbusTypes, ModbusAccess, ModbusRegisterType from library.measurement import Measurement, ModbusMeasurement import aenum from enum import Enum, auto # logging config # logging.basicConfig(filename='log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') # logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) # class IngridModbusCommands(aenum.Enum): # _init_ = 'value register register_type modbus_type access uom count' # COMMAND = auto(), 0, ModbusRegisterType.HOLDING, ModbusTypes.INT16, ModbusAccess.WRITE, 'status', None # HOLDING class IngridModbusMainCommands(Enum): WRITE_ODO_SETPOINT = 'write_odo_setpoint' class IngridModbus(BaseModbus): def __init__(self, logger, setpoint_measurement, variables_dict=None): # passargli un logger, None, dictionary super().__init__(variables_dict) self.logger = logger self.ip = variables_dict["MODBUS_IP"]["value"] self.port = utils.parse_int(variables_dict["MODBUS_PORT"]["value"], 1) self.setpoint_measurement = setpoint_measurement # _, self.odosetpoint_dict = odosetpoint_dict# utils.parse_reading_env(self.get('INGRID_ODO_SETPOINT')) # self.id = utils.parse_int(os.getenv('MODBUS_ID', 1), 1) def connect(self): self.client = ModbusTcpClient(self.ip, self.port) return self.client.connect() def get_list_command_enums(self): return [] def get_list_command_main_enums(self): return [IngridModbusMainCommands] async def write_odo_setpoint(self, value): if utils.parse_bool(self.get('FEEDBACK_ACTIVATION', default=False), default=False): # _, odosetpoint_dict = utils.parse_reading_env(os.getenv('INGRID_ODO_SETPOINT')) # await self.connect_to_modbus_server() if self.setpoint_measurement is None: self.logger.info('-------------------------------------------------------') self.logger.info('CANNOT WRITE SETPOINT to value {}. (missing ODORANT_SETPOINT measurement in env variables)'.format(value)) self.logger.info('-------------------------------------------------------') else: self.logger.info('-------------------------------------------------------') self.logger.info('WRITING. Set point CHANGED to value {}.'.format(value)) await self.write_value(self.setpoint_measurement.register_number, self.setpoint_measurement.value_type, value, count=self.setpoint_measurement.count) # await asyncio.sleep(0.5) value = await self.read_value(self.setpoint_measurement.register_number, self.setpoint_measurement.value_type, register_type=self.setpoint_measurement.register_type, count=self.setpoint_measurement.count) self.logger.info('READ SET POINT: {}.'.format(value)) self.logger.info('-------------------------------------------------------') # await self.write_value(self.odosetpoint_dict["register"], self.odosetpoint_dict["type"], value) # await self.close_modbus_client() else: self.logger.info('-------------------------------------------------------') self.logger.info('FEEDBACK_ACTIVATION is false. Set point NOT CHANGED to value {}'.format(value)) self.logger.info('-------------------------------------------------------') <file_sep>/Modbus2DBs/Microturbine_RTU_2_Influx/testing_ok/plc_reader (copy)/first_setup.sh #bash! # da eseguire in seguito a modifiche a file di configurazione o software export sudo_password='<PASSWORD>' # avvio di influxdb echo $sudo_password | sudo service influxdb stop sudo docker run --name influxdb_1_8 -p 8086:8086 \ -v influxdb:/var/lib/influxdb \ -d influxdb:1.8 # avvio di grafana sudo docker run --name grafana -d -p 3000:3000 grafana/grafana sudo docker-compose build sudo docker run --name plc_read_2_influxdb -d plc_read_2_influxdb <file_sep>/ModBus_PLC2PLC/old/test_casa/plc_tester/influxdb_module_class.py import library.utils as utils from influxdb import InfluxDBClient from datetime import datetime from enum import Enum, auto import logging class InputType(Enum): real = auto() simulation = auto() class InfluxDBModuleClass: def __init__(self, logger, config_dict): self.logger = logger database = utils.get(config_dict, 'DATABASE') host = utils.get(config_dict, 'HOST') port = utils.get(config_dict, 'PORT') username = utils.get(config_dict, 'USERNAME') password = utils.get(config_dict, 'PASSWORD') ssl = str(utils.get(config_dict, 'SSL')).lower() == 'true' verify_ssl = str(utils.get(config_dict, 'VERIFY_SSL')).lower() == 'true' if username is None: self.client=InfluxDBClient(host=host, port=port) else: self.client = InfluxDBClient(host=host, port=port, username=username, password=<PASSWORD>, ssl=ssl, verify_ssl=verify_ssl) # verifica esistenza db lst = self.client.get_list_database() check = next((item for item in lst if item["name"] == database), None) # ritorna l'indice: #index = next((i for i, item in enumerate(lst) if item["name"] == database), None) if(len(lst)==0 or check is None): self.client.create_database(database) self.client.switch_database(database) def disconnect(self): return self.client.close() def write_data(self, value, meas_name:str, value_type:str, register_number:int=None, uom:str=None, input_type:InputType=InputType.real, time=None): if time is None: time = datetime.utcnow().isoformat() json_body = [ { "measurement": f'{meas_name}', "tags": { "type": f'{input_type.name}', "register_number": register_number, "value_type": f'{value_type}', "uom": f'{uom}' }, "time": f'{time}', "fields": { "value": value } } ] self.logger.debug(f'writing::{meas_name}::value::{value}::input_type{input_type}') return self.client.write_points(json_body) ### Inserimento dati molteplici async def write_all_data(self, data_dict): time = datetime.utcnow().isoformat() json_body = [] first:str=None last:str try: for d in data_dict: meas_name=list(d.keys())[0] vals=list(d.values())[0] register_number=utils.get(vals, 'REGISTER_NUMBER') value_type=utils.get(vals,'VALUE_TYPE') uom=utils.get(vals,'UOM') input_type=utils.get(vals,'INPUT_TYPE', InputType.real.name) value=utils.get(vals,'VALUE') if first is None: first=meas_name last = meas_name json_body.append({ "measurement": f'{meas_name}', "tags": { "type": f'{input_type}', "register_number": register_number, "value_type": f'{value_type}', "uom": f'{uom}' }, "time": f'{time}', "fields": { "value": value } }) self.logger.info(f'writing::FROM{first}::TO::{last}') return self.client.write_points(json_body) except Exception as e: self.logger.error(f'error::{e}') return None ############################################################################################################### ### PER TEST: if __name__ =='__main__': db_name = 'h2_test' meas_name = 'test' + datetime.utcnow().isoformat() value_type = 'FLOAT32' val = 1 influxdb_client=InfluxDBModuleClass(None, db_name) res = influxdb_client.write_data(val, meas_name, value_type, InputType.simulation) print(res) result = influxdb_client.client.query(f'select value from {meas_name};') print("Result: {0}".format(result)) <file_sep>/MeasurementWriteFastAPI/library/remote_methods_caller.py import base64 import hmac import hashlib import time import requests import urllib import json import os import sys API_VERSION = '2019-07-01-preview' # os.getenv('API_VERSION') # TOKEN_VALID_SECS = 365 * 24 * 60 * 60 # os.getenv('TOKEN_VALID_SECS') # TOKEN_FORMAT = 'SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s' # os.getenv('TOKEN_FORMAT') # METHOD_IOT_HUB_URL_FORMAT = 'https://{}.azure-devices.net/twins/{}/modules/{}/methods?api-version={}' # os.getenv('METHOD_IOT_HUB_URL_FORMAT') # IOT_HUB_NAME = 'greta-simulation-iothub' # os.getenv('IOT_HUB_NAME') # CONNECTION_STRING = "HostName=greta-simulation-iothub.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=<KEY> # os.getenv('CONNECTION_STRING') def generate_sas_token(connectionString): iotHost, keyName, keyValue = [sub[sub.index('=') + 1:] for sub in connectionString.split(";")] targetUri = iotHost.lower() expiryTime = '%d' % (time.time() + int(TOKEN_VALID_SECS)) toSign = '%s\n%s' % (targetUri, expiryTime) key = base64.b64decode(keyValue.encode('utf-8')) signature = urllib.parse.quote(base64.b64encode(hmac.HMAC(key, toSign.encode('utf-8'), hashlib.sha256).digest())).replace('/', '%2F') return TOKEN_FORMAT % (targetUri, signature, expiryTime, keyName) def call_direct_method(deviceID, moduleID, methodName, payload, retry_count=3, connection_string=None): connection_string = CONNECTION_STRING if connection_string is None else connection_string sasToken = generate_sas_token(connection_string) url = METHOD_IOT_HUB_URL_FORMAT.format(IOT_HUB_NAME, deviceID, moduleID, API_VERSION) data = {"methodName": methodName, "responseTimeoutInSeconds": 10, "payload": payload} for _ in range(retry_count): r = requests.post(url, headers={'Authorization': sasToken}, data=json.dumps(data)) #print(r.text, r.status_code) if r.status_code == 200: return True, r.text, r.status_code #return False return False, r.text, r.status_code if __name__ == "__main__": iot_edge_name = sys.argv[1] module_name = sys.argv[2] method_name = sys.argv[3] message = sys.argv[4] success_only = bool(sys.argv[5]) if len(sys.argv) > 5 else False if not success_only: print(f'iot_edge_name: {iot_edge_name}') print(f'module_name: {module_name}') print(f'method_name: {method_name}') print(f'message: {message}') if len(sys.argv) > 6: import utils secret_key = sys.argv[6] message = json.dumps(utils.generate_message_hash(message, secret_key=secret_key)) print(f'Message: {message}') success, response, status_code = call_direct_method(iot_edge_name, module_name, method_name, message, retry_count=3, connection_string=CONNECTION_STRING) if not success_only: print(f'Success: {success}') print(f'Status: {status_code}') if not success_only and success: print('Payload: \n{}'.format(json.loads(response)["payload"].replace("\\n", "\n"))) if success_only: print(int(success)) <file_sep>/CurveFitting/main.py import pandas as pd import numpy as np import matplotlib.pyplot as plt import pylab import itertools import datetime from datetime import datetime from logger import logging import math import os.path import os from pathlib import Path import shutil from scipy.signal import butter, lfilter, freqz, lfilter_zi, filtfilt def butter_lowpass(cutoff, fs, order=5): nyq = 0.5 * fs normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='low', analog=False) return b, a def butter_lowpass_filter(data, cutoff, fs, order=5, zi_val=0): b, a = butter_lowpass(cutoff, fs, order=order) zi=lfilter_zi(b,a)*zi_val z, _ = lfilter(b, a, data, zi=zi) z2,_ = lfilter(b, a, z, zi=zi*z[0]) y = filtfilt(b, a, data) return y, z, z2 def hand_made_lowpass_2(x, cutoff, fs, order, zi_val=0): b, a = butter_lowpass(cutoff, fs, order=order) y=x.copy() for j in range(len(x)): i=order y[j]=0 while(j>=i and i>0): y[j]=y[j] + b[i]*x[j-i] - a[i]*y[j-i] i-=1 y[j]=y[j]+b[0]*x[j] y[j]=(1/a[0])*y[j] return y def hand_made_lowpass(x, cutoff, fs, order, zi_val=0): b, a = butter_lowpass(cutoff, fs, order=order) y=x.copy() d=np.full((order+1,1), 0) for j in range(len(x)): i=order-1 while (i): if (j >= i): d[i - 1,0] = b[i] * x[j - i] - a[i] * y[j - i] + d[i,0] i-=1 y[i] = b[0] * x[i] + d[0,0] y[i] = y[i]/a[0] return y if __name__=='__main__': print("::STARTING::") # Filter requirements. order = 2 fs = 1 # sample rate, Hz cutoff = 1/100 # desired cutoff frequency of the filter, Hz # Get the filter coefficients so we can check its frequency response. b, a = butter_lowpass(cutoff, fs, order) # colonne meas = ['RAW_1', 'RAW_2'] filtered = ['FILTERED'] # dati random data = {} T = 1000 x = np.arange(0,T) max_val = 1 min_val = 0 sin_wave = 4*np.sin(4*np.pi*x/T) noise = np.random.uniform(min_val, max_val, size=T) noisy_sin_wave = sin_wave + noise data[meas[0]] = pd.DataFrame(noisy_sin_wave, columns = ['value']) # Plot the frequency response. w, h = freqz(b, a, worN=8000) plt.subplot(2, 1, 1) plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b') plt.plot(cutoff, 0.5*np.sqrt(2), 'ko') plt.axvline(cutoff, color='k') plt.xlim(0, 0.5*fs) plt.title("Lowpass Filter Frequency Response") plt.xlabel('Frequency [Hz]') plt.grid() # Filter the data, and plot both the original and filtered signals. data[filtered[0]] = data[meas[0]].copy() zi_val=data[meas[0]]['value'][0] y, z, z2 = butter_lowpass_filter(data[meas[0]]['value'], cutoff, fs, order, zi_val) data[filtered[0]]['value_y'] = y data[filtered[0]]['value_z'] = z data[filtered[0]]['value_z2'] = z2 data[filtered[0]]['value_hm'] = hand_made_lowpass_2(data[meas[0]]['value'], cutoff, fs, order, zi_val) plt.subplot(2, 1, 2) #plt.plot(data[meas[0]], 'b-', label='RAW') plt.plot(data[filtered[0]].index, data[filtered[0]]['value_y'], 'g.', linewidth=1, label='RAW_FILTERED_y') plt.plot(data[filtered[0]].index, data[filtered[0]]['value_z'], 'y.', linewidth=1, label='RAW_FILTERED_z') plt.plot(data[filtered[0]].index, data[filtered[0]]['value_z2'], 'pink', linewidth=1, label='RAW_FILTERED_z2') plt.plot(data[filtered[0]].index, data[filtered[0]]['value_hm'], 'r.', linewidth=1, label='RAW_FILTERED_hm') plt.plot(data[meas[0]], 'black', linewidth=1, label='RAW') plt.xlabel('Time [sec]') plt.grid() plt.legend() plt.subplots_adjust(hspace=0.35) plt.show() print('::END::')<file_sep>/GretaAnalogWriter/library/drago_dido_96700.py import logging import os import time import sys import traceback import asyncio import library.utils as utils import aenum from enum import Enum, auto from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder from pymodbus.payload import BinaryPayloadBuilder from pymodbus.client.sync import ModbusSerialClient from library.base_drago import ModbusTypes, IdentifiersCommands, DIPCommands, CommonCommands, BaseDrago, ModbusAccess # logging config # logging.basicConfig(filename='log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') # logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) # client = ModbusSerialClient(port='/dev/ttyS1', # stopbits=1, # bytesize=8, # parity='E', # baudrate=19200, # timeout=1, # method='rtu') # client.connect() class DragoDIDO96700Commands(aenum.Enum): _init_ = 'value register modbus_type access uom count' DIGITAL_IO_1 = auto(), 0, ModbusTypes.COIL, ModbusAccess.READ_WRITE, None, 1 DIGITAL_IO_2 = auto(), 1, ModbusTypes.COIL, ModbusAccess.READ_WRITE, None, 1 DIGITAL_IO_3 = auto(), 2, ModbusTypes.COIL, ModbusAccess.READ_WRITE, None, 1 DIGITAL_IO_4 = auto(), 3, ModbusTypes.COIL, ModbusAccess.READ_WRITE, None, 1 DIGITAL_IO_DIRECT = auto(), 10, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, None, None OPERATING_MODE_CH1 = auto(), 2000, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: INPUT / 16: OUTPUT INPUT_LEVEL_CH1 = auto(), 2001, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: 5V / 1: 12V / 2: 24V PULSE_WIDTH_CH1 = auto(), 2002, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: 300ms CONTACT_TYPE_CH1 = auto(), 2011, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: NO / 1: NC MIN_ACTIVATION_TYPE_CH1 = auto(), 2012, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: OFF MAX_ACTIVATION_TYPE_CH1 = auto(), 2013, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: OFF ON_DELAY_CH1 = auto(), 2014, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: IMMEDIATE OFF_DELAY_CH1 = auto(), 2015, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: IMMEDIATE INITIAL_STATE_CH1 = auto(), 2016, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: OFF / 1: ON OPERATING_MODE_CH2 = auto(), 2100, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: INPUT / 16: OUTPUT INPUT_LEVEL_CH2 = auto(), 2101, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: 5V / 1: 12V / 2: 24V PULSE_WIDTH_CH2 = auto(), 2102, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: 300ms CONTACT_TYPE_CH2 = auto(), 2111, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: NO / 1: NC MIN_ACTIVATION_TYPE_CH2 = auto(), 2112, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: OFF MAX_ACTIVATION_TYPE_CH2 = auto(), 2113, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: OFF ON_DELAY_CH2 = auto(), 2114, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: IMMEDIATE OFF_DELAY_CH2 = auto(), 2115, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: IMMEDIATE INITIAL_STATE_CH2 = auto(), 2116, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: OFF / 1: ON OPERATING_MODE_CH3 = auto(), 2200, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: INPUT / 16: OUTPUT INPUT_LEVEL_CH3 = auto(), 2201, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: 5V / 1: 12V / 2: 24V PULSE_WIDTH_CH3 = auto(), 2202, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: 300ms CONTACT_TYPE_CH3 = auto(), 2211, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: NO / 1: NC MIN_ACTIVATION_TYPE_CH3 = auto(), 2212, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: OFF MAX_ACTIVATION_TYPE_CH3 = auto(), 2213, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: OFF ON_DELAY_CH3 = auto(), 2214, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: IMMEDIATE OFF_DELAY_CH3 = auto(), 2215, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: IMMEDIATE INITIAL_STATE_CH3 = auto(), 2216, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: OFF / 1: ON OPERATING_MODE_CH4 = auto(), 2300, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: INPUT / 16: OUTPUT INPUT_LEVEL_CH4 = auto(), 2301, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: 5V / 1: 12V / 2: 24V PULSE_WIDTH_CH4 = auto(), 2302, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: 300ms CONTACT_TYPE_CH4 = auto(), 2311, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: NO / 1: NC MIN_ACTIVATION_TYPE_CH4 = auto(), 2312, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: OFF MAX_ACTIVATION_TYPE_CH4 = auto(), 2313, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: OFF ON_DELAY_CH4 = auto(), 2314, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: IMMEDIATE OFF_DELAY_CH4 = auto(), 2315, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: IMMEDIATE INITIAL_STATE_CH4 = auto(), 2316, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None # 0: OFF / 1: ON class DragoDIDO96700(BaseDrago): def __init__(self, variables_dict=None, logger=None): super().__init__(variables_dict=variables_dict, logger=logger) def get_list_command_enums(self): return super().get_list_command_enums() + [DragoDIDO96700Commands] def get_command_from_channel(self, channel): if channel == 'DO1' or channel == "DI1": return DragoDIDO96700Commands.DIGITAL_IO_1 elif channel == 'DO2' or channel == "DI2": return DragoDIDO96700Commands.DIGITAL_IO_2 elif channel == 'DO3' or channel == "DI3": return DragoDIDO96700Commands.DIGITAL_IO_3 elif channel == 'DO4' or channel == "DI4": return DragoDIDO96700Commands.DIGITAL_IO_4 async def setup_config_for_greta_photovoltaic(self): commands_dict = {} commands_dict[DragoDIDO96700Commands.OPERATING_MODE_CH1] = 0 # DI commands_dict[DragoDIDO96700Commands.INPUT_LEVEL_CH1] = 2 # 12/24 v commands_dict[DragoDIDO96700Commands.OPERATING_MODE_CH2] = 16 # DO commands_dict[DragoDIDO96700Commands.CONTACT_TYPE_CH2] = 0 # NO commands_dict[DragoDIDO96700Commands.INITIAL_STATE_CH2] = 1 # ON AT START commands_dict[DragoDIDO96700Commands.DIGITAL_IO_2] = 1 # START CHANNEL 2 # commands_dict[CommonCommands.MODBUS_PC_UNIT_ID] = 1 await self.write_configuration(commands_dict) if __name__ == "__main__": async def main(): drago = DragoDIDO96700({"MODBUS_ID": 1}) await drago.connect_to_modbus_server() print("io_1 : FALSE (write)", await drago.execute_command_write(DragoDIDO96700Commands.DIGITAL_IO_1, False)) print("io_3 : TRUE (write)", await drago.execute_command_write(DragoDIDO96700Commands.DIGITAL_IO_3, True)) print("io_1 : ", await drago.execute_command_read(DragoDIDO96700Commands.DIGITAL_IO_1)) print("io_2 : ", await drago.execute_command_read(DragoDIDO96700Commands.DIGITAL_IO_2)) print("io_3 : ", await drago.execute_command_read(DragoDIDO96700Commands.DIGITAL_IO_3)) print("io_4 : ", await drago.execute_command_read(DragoDIDO96700Commands.DIGITAL_IO_4)) print("DIGITAL_IO_DIRECT : ", await drago.execute_command_read(DragoDIDO96700Commands.DIGITAL_IO_DIRECT)) print("io_1 : TRUE (write)", await drago.execute_command_write(DragoDIDO96700Commands.DIGITAL_IO_1, True)) print("io_3 : FALSE (write)", await drago.execute_command_write(DragoDIDO96700Commands.DIGITAL_IO_3, False)) print("io_1 : ", await drago.execute_command_read(DragoDIDO96700Commands.DIGITAL_IO_1)) print("io_2 : ", await drago.execute_command_read(DragoDIDO96700Commands.DIGITAL_IO_2)) print("io_3 : ", await drago.execute_command_read(DragoDIDO96700Commands.DIGITAL_IO_3)) print("io_4 : ", await drago.execute_command_read(DragoDIDO96700Commands.DIGITAL_IO_4)) for e in drago.get_list_command_enums(): for i in e: print(f"Read {i} : ", await drago.execute_command_read(i)) asyncio.run(main()) <file_sep>/ModBus_PLC2PLC/old/test_casa/plc_tester/start_plc_tester.sh export password='<PASSWORD>' echo $password | sudo service inluxdb stop # avvio della vpn sudo openvpn --config ./<EMAIL>.ovpn --daemon #avvio dei docker for i in {1..3} do sudo docker start $(sudo docker ps -a -q) done <file_sep>/2_DEPLOY/RTUModbusModule/V1/library/rtu_modbus.py # from pymodbus.client.asynchronous.tcp import AsyncModbusTCPClient as ModbusTcpClient # from pymodbus.client.asynchronous.udp import (AsyncModbusUDPClient as ModbusUdpClient) # from pymodbus.client.asynchronous import schedulers import logging import os import time import sys import traceback import asyncio from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder from pymodbus.payload import BinaryPayloadBuilder from pymodbus.client.sync import ModbusSerialClient import library.utils as utils from library.base_modbus import BaseModbus, ModbusTypes, ModbusAccess, ModbusRegisterType from library.measurement import Measurement, ModbusMeasurement import aenum from enum import Enum, auto class RtuModbus(BaseModbus): def __init__(self, logger, variables_dict=None): super().__init__(variables_dict=variables_dict, logger=logger) self.port = self.get('MODBUS_PORT' , default= '/dev/ttyUSB0') self.stopbits = int(self.get('MODBUS_STOPBITS' , default= 1)) self.bytesize = int(self.get('MODBUS_BYTESIZE' , default= 8)) self.baudrate = int(self.get('MODBUS_BAUDRATE' , default= 19200)) self.timeout = int(self.get('MODBUS_TIMEOUT' , default= 1)) self.method = self.get('MODBUS_METHOD' , default= 'rtu') self.parity = self.get('MODBUS_PARITY' , default= 'N') def connect(self): self.client = ModbusSerialClient(method=self.method, port = self.port, stopbits = self.stopbits, bytesize=self.bytesize, baudrate = self.baudrate, timeout = self.timeout, parity=self.parity) return self.client.connect() def get_list_command_enums(self): return [] def get_list_command_main_enums(self): return [] def get_command_from_channel(self, channel): None<file_sep>/Modbus2DBs/Bilancia_Serial_2_Influx/influxdb_module_class.py import library.utils as utils from influxdb import InfluxDBClient from enum import Enum, auto class InputType(Enum): real = auto() simulation = auto() class InfluxDBModuleClass: def __init__(self, logger, config_dict): self.logger = logger database = utils.get(config_dict, 'DATABASE') host = utils.get(config_dict, 'HOST') port = utils.get(config_dict, 'PORT') username = utils.get(config_dict, 'USERNAME') password = utils.get(config_dict, 'PASSWORD') ssl = str(utils.get(config_dict, 'SSL')).lower() == 'true' verify_ssl = str(utils.get(config_dict, 'VERIFY_SSL')).lower() == 'true' if username is None: self.client=InfluxDBClient(host=host, port=port) else: self.client = InfluxDBClient(host=host, port=port, username=username, password=<PASSWORD>, ssl=ssl, verify_ssl=verify_ssl) # verifica esistenza db lst = self.client.get_list_database() check = next((item for item in lst if item["name"] == database), None) # ritorna l'indice: #index = next((i for i, item in enumerate(lst) if item["name"] == database), None) if(len(lst)==0 or check is None): self.client.create_database(database) self.client.switch_database(database) def disconnect(self): return self.client.close() ### Inserimento dati molteplici async def write_data(self, meas_name, value, time=None): try: value = value if value is not None else 0 json_body=[] json_body.append({ "measurement": f'{meas_name}', "time": f'{time}', "fields": {"value": value}}) result = self.client.write_points(json_body) return result except Exception as e: self.logger.error(f'error::{e}') return None async def write_all_data(self, data_dict): ''' Le variabili passate devono avere un parametro di valore denominato VALUE e un parametro di tempo denominato TIME ''' json_body = [] first:str=None last:str try: for d in data_dict: # nomi delle chiavi keys=list(d.keys()) # nome della misura meas_name=keys[0] if first is None: first=meas_name last = meas_name # acquisizione della lista dei valori vals=d[meas_name] # acquisizione del valore: value=vals['VALUE'] # acquisizione del tempo time = vals['TIME'] if (value is not None): # correzione lista di tags del json per l'insert del vals['VALUE'] # json 2 string # json.dumps(x, indent=4, separators=(", ", " : ")) json_body.append({ "measurement": f'{meas_name}', "tags": vals, "time": f'{time}', "fields": { "value": value } }) self.logger.info(f'writing::FROM::{first}::TO::{last}') result = self.client.write_points(json_body) return result except Exception as e: self.logger.error(f'error::{e}') return None <file_sep>/ModBus_PLC2PLC/ModBus_PLC2PLC_v_0.0.1/plc_looper.py import logging import logging.handlers import asyncio from plc_readwrite import PlcVariableTags, PlcReadWrite import copy from datetime import datetime class PlcLooper(): def __init__(self, plc_readers, plc_writers): self.plc_readers = plc_readers self.plc_writers = plc_writers async def plc_2_plc(self, reader:PlcReadWrite): try: tasks = [] for group in reader.measurement_list_dict: # Lista di task divisa per tempo di campionamento sampling_time =group[PlcVariableTags.R_SAMPLING_TIME_MS.name]/1000 measurements =group[PlcVariableTags.MEASUREMENTS.name] tasks.append(self.read_write_variables( reader = reader, sampling_time=sampling_time, measurement_list_dict = measurements)) # attesa della fine di tutti i task await asyncio.wait(tasks) except Exception as e: logging.critical(f'::error: {e}::') async def plc_ping(self): for p in self.plc_readers + self.plc_writers: if p.device_instance is not None: asyncio.gather(p.device_instance.periodic_ping()) async def read_write_variables(self, reader, sampling_time, measurement_list_dict): while True: now = datetime.now() try: # lista di task di lettura divise per tempo di campionamento tasks = [reader.read_var_async(m) for m in measurement_list_dict] # attesa della fine di tutti i task await asyncio.wait(tasks) # scrittura dati acquisiti su influxDB asyncio.gather(self.write_variables(self.plc_writers, copy.deepcopy(measurement_list_dict))) except Exception as e: logging.critical(f'::error: {e}::') # tempo di campionamento dal plc end_time = datetime.now() net_sampling_time = sampling_time - (end_time-now).microseconds/1e6 net_sampling_time = net_sampling_time if net_sampling_time > 0 else 0 await asyncio.sleep(sampling_time) async def write_variables(self, writers, measurement_list_dict): if len(writers)>0: for w in writers: sublist = [value for value in measurement_list_dict if list(value.keys())[0] in w.measurement_list_dict[0][PlcVariableTags.MEASUREMENT_NAMES.name]] for m in [value for value in sublist if list(value.values())[0][PlcVariableTags.WRITE_VALUE.name] is not None]: res = await w.write_var_async(m, list(m.values())[0][PlcVariableTags.WRITE_VALUE.name]) ######################################################################################################################## ### MAIN STARTER def start_testing(self): # avvio lettura da database e scrittura su plc if not(len(self.plc_readers) >0 or len(self.plc_writers) >0): return loop = asyncio.get_event_loop() for reader in [reader for reader in self.plc_readers if reader is not None]: loop.create_task(self.plc_2_plc(reader = reader)) loop.create_task(self.plc_ping()) loop.run_forever() <file_sep>/ModBus_PLC2PLC/old/test_casa/plc_tester/plc_looper.py import logging import sys import asyncio from plc_module_class import PlcModuleClass from influxdb_module_class import InfluxDBModuleClass from mssql_module_class import MSSQLManager, Query import logging import logging.handlers import library.utils as utils import json import os import shutil import ntpath import datetime from datetime import datetime, timedelta import threading import pandas as pd import numpy as np import time class PlcLooper(): def __init__(self, plc_client: PlcModuleClass, influxdb_client: InfluxDBModuleClass, mssql_client: MSSQLManager): self.plc_client = plc_client self.influx_client = influxdb_client self.mssql_client = mssql_client self.mssql_client.init_testing() async def plc_2_influx_db_variables(self): while True: try: for m in self.plc_client.measurement_list_dict: plc_res = await self.plc_client.read_var_async(m) # scrittura dati acquisiti su influxDB influx_res = await self.influx_client.write_all_data(self.plc_client.measurement_list_dict) except Exception as e: logging.critical(f'::error: {e}::') # tempo di campionamento dal plc await asyncio.sleep(self.plc_client.r_sampling_time) async def mssql_2_plc_variables(self): data_fr_str = 'DATA_FRAME' ts = int(self.plc_client.w_sampling_time) ts_str = str(ts)+'s' while True: for i in self.plc_client.inputs_list_dict: try: meas_name=list(i.keys())[0] vals=list(i.values())[0] register_num=utils.get(vals,'REGISTER_NUMBER') value_type=utils.get(vals,'VALUE_TYPE') time_span=utils.get(vals, 'TIME_SPAN') from_device:str=utils.get(vals, 'FROM_DEVICE', 'N').lower() default_value=utils.get(vals, 'DEFAULT_VALUE', 0) if from_device == 'y' or from_device == 'yes' or from_device == 's': if data_fr_str not in vals: vals[data_fr_str] = pd.DataFrame() if len(vals[data_fr_str].index)<2: query_result = self.query_meas(meas_name, time_span, ts_str) vals[data_fr_str] = query_result # scrittura nel plc in modalità FIFO first_df_val = vals[data_fr_str]['value'][0] else: first_df_val=default_value res = await self.plc_client.write_imput_with_delay(register_num, value_type, 0, first_df_val) # rimozione primo valore inserito vals[data_fr_str]=vals[data_fr_str].iloc[1:] except Exception as e: logging.critical(f'::error: {e}::') await asyncio.sleep(int(ts)) def query_meas(self, meas_name, time_span:str, ts:str) -> pd.DataFrame: dt_str = utils.get_past_time(time_span, _2str=True) query_str = f"select time, value \ from {self.mssql_client.data_source} \ where time > '{dt_str}'\ and machine_name = '{self.mssql_client.machine_twin}' \ and sensor_type = '{meas_name}' \ order by time asc" pd= self.mssql_client.query_execute(Query(query_str), fetch = True, asdataframe=True, columns=['time','value']) return pd.resample(ts, on = 'time').mean() ######################################################################################################################## ### MAIN STARTER def start_testing(self): # avvio lettura da database e scrittura su plc #asyncio.run(self.mssql_2_plc_variables()) loop = asyncio.get_event_loop() loop.create_task(self.mssql_2_plc_variables()) loop.create_task(self.plc_2_influx_db_variables()) loop.run_forever() <file_sep>/Modbus2DBs/PLC_Schneider_Modbus_2_Influx/plc_reader/main.py import json import os import logging import sys from plc_module_class import PlcModuleClass from influxdb_module_class import InfluxDBModuleClass from plc_looper import PlcLooper import library.utils as utils ###################################################################################################################### # Parametri di configurazione plc_config_file = './config/plc_modbus.config' db_config_file = './config/db.config' ###################################################################################################################### # Initializzazione del logger # def init_logging(logger, filename, level=logging.INFO, stdout=True, maxBytes=10000, backupCount=5): logging.getLogger().setLevel(logging.NOTSET) logging.getLogger().handlers = [] rotatingHandler = logging.handlers.RotatingFileHandler(filename=filename, maxBytes=maxBytes, backupCount=backupCount) rotatingHandler.setLevel(logging.DEBUG) rotatingHandler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) logging.getLogger().addHandler(rotatingHandler) logging.getLogger(__name__).setLevel(level) logging.getLogger("pymodbus").setLevel(logging.DEBUG) if stdout: logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) logger = logging.getLogger(__name__) logger.info('init_logging::end') ###################################################################################################################### def connect_device(logger, plc_config_file): plc_modbus_client = PlcModuleClass(logger, plc_config_file) conn_res = plc_modbus_client.connect_device() return plc_modbus_client if conn_res else None ###################################################################################################################### def parseJsonConfig(file_full_path): #pwd = os.getcwd() if (os.path.isfile(file_full_path)): with open(file_full_path,"r") as f: return json.load(f) return None ###################################################################################################################### ### MAIN if __name__ == "__main__": logger = logging log_filename = 'test.log' init_logging(logger, log_filename) logger.info("::START::") logger.info("------------------------------------------------------") meas_ok:bool=True # Parsing delle variabili da file di configurazione. plc_dictinoary = parseJsonConfig(plc_config_file) db_dictionary = parseJsonConfig(db_config_file) # Connessione al PLC tramite Modbus plc_modbus_client = connect_device(logger, plc_dictinoary) # Connessione al DB InfluxDB influxdb_client = InfluxDBModuleClass(logger, utils.get(db_dictionary,'INFLUXDB')) if plc_modbus_client is not None: logger.info("::PLC CONNECTED::") # Avvio lettura in loop delle variabili logger.info("::START CONTROLLING PLC::") # plc looper plc_looper = PlcLooper(plc_modbus_client, influxdb_client) # avvio loop plc_looper.start_testing() logger.info("::STOP::") logger.info("------------------------------------------------------") <file_sep>/MeasurementWriteFastAPI/main.py from os import write from fastapi import FastAPI import library.remote_methods_caller as rmc import library.utils as utils import logging app = FastAPI() @app.post("/write_measurement/{device_id}") def itemz(device_id: str, options:dict): module_id = utils.get(options, 'module_id') method_name = utils.get(options, 'method_name') payload = utils.get(options, 'payload') done, message, code = rmc.call_direct_method(deviceID=device_id, moduleID=module_id, methodName=method_name, payload=payload) return {"done": done, "message": message, "code":code} @app.get("/write_measurement/{device_id}/{module_id}/{method_name}/{measurement_name}/{write_value}") def itemz(device_id: str, module_id:str, method_name:str, measurement_name: str, write_value: str): payload={measurement_name:{"VALUE": write_value}} print(payload) done, message, code = rmc.call_direct_method(deviceID=device_id, moduleID=module_id, methodName=method_name, payload=payload) print({"done": done, "message": message, "code":code}) return {"done": done, "message": message, "code":code} <file_sep>/IoTHub_RemoteMethodTester/remote_methods_tester.py import time import os import asyncio import datetime import json import traceback import random from library.base_iothub_reader_module_client import BaseIotHubReaderModuleClient from library.base_iothub_client import IobHubRemoteMethodStatus import library.utils as utils class RemoteMethodsTester(BaseIotHubReaderModuleClient): def __init__(self): super().__init__(None, None) self.machine_type = utils.get(os.environ, 'MACHINE_TYPE', 'INGRID') measurement_list = utils.get_all_measurement_list(self.machine_type, os.environ) config_measurement_list = utils.get_config_measurement_list(self.machine_type, os.environ, logger=self.logger) self.measurement_list = measurement_list self.config_measurement_list = config_measurement_list self.list_background_functions.append(self.write_directmethod_listener) self.list_background_functions.append(self.write_directmethod_crypto_listener) async def init_device_instance(self): return None async def connect_device(self, device_instance): pass async def disconnect_device(self, device_instance): pass ############################################################################################# async def write_directmethod(self, payload): self.logger.info('WRITE_DIRECTMETHOD TRIGGERED. Payload: {}'.format(payload)) value = await self.log_result(payload) if value is not None: return IobHubRemoteMethodStatus.STATUS_OK, value else: self.logger.error('ERROR in WRITE_DIRECTMETHOD {}. Payload: {}.'.format(payload)) return IobHubRemoteMethodStatus.STATUS_OK, traceback.format_exc() async def write_directmethod_crypto(self, payload): self.logger.info('WRITE_DIRECTMETHOD_CRYPTO TRIGGERED. Payload: {}'.format(payload)) try: is_safe, content = utils.validate_message_hash(payload) if is_safe: value = await self.log_result(content) if value is not None: return IobHubRemoteMethodStatus.STATUS_OK, value return IobHubRemoteMethodStatus.STATUS_OK, value else: return IobHubRemoteMethodStatus.STATUS_OK, 'HASH DECRYPTION FAILED' except Exception as e: self.logger.error('ERROR in WRITE_DIRECTMETHOD_CRYPTO {}. Payload: {}.'.format(e, payload)) self.logger.debug(e, exc_info=True) return IobHubRemoteMethodStatus.STATUS_OK, traceback.format_exc() async def log_result(self, content): value = None try: measurement = utils.get_modbus_measurement_from_dict(content, self.machine_type) if measurement is not None: measurement.last_time_write=time.time() value = max(measurement.min_range, min(measurement.max_range, measurement.write_value)) # clamp between min and max self.logger.debug("MEASUREMENT: {}, ODO_MAX: {}, ODO_MIN: {}, VALUE: {}".format(measurement.sensor_type, measurement.max_range, measurement.min_range, value)) else: return IobHubRemoteMethodStatus.STATUS_OK, f'MEASUREMENT not in content: {content}' except Exception as e: self.logger.error(e, exc_info=True) return value ############################################################################################# async def write_directmethod_listener(self, module_client, output_topic='output1'): await utils.base_listener_directmethod(module_client, 'write_directmethod', self.write_directmethod, output_topic=output_topic, logger=self.logger) async def write_directmethod_crypto_listener(self, module_client, output_topic='output1'): await utils.base_listener_directmethod(module_client, 'write_directmethod_crypto', self.write_directmethod_crypto, output_topic=output_topic, logger=self.logger) <file_sep>/MeasurementWriteFastAPI/stop.sh #bash! sudo docker kill fastapi_edgedev_write #uvicorn main:app --stop <file_sep>/Modbus2DBs/Microturbine_RTU_2_Influx/testing_ok/plc_reader (copy)/modbus_looper.py import logging import logging.handlers import asyncio from rtu_module_class import RtuModuleClass, ModbusVariableTags from influxdb_module_class import InfluxDBModuleClass import copy from datetime import datetime class ModbusLooper(): def __init__(self, client: RtuModuleClass, influxdb_client: InfluxDBModuleClass): self.client = client self.influx_client = influxdb_client async def modbus_2_influx_db_variables(self, meas_dict, samplint_time): while True: now = datetime.now() try: # lista di task per la lettura dal plc in modo asincrono tasks = [self.client.read_var_async(m) for m in meas_dict] # attesa della fine di tutti i task await asyncio.wait(tasks) # scrittura dati acquisiti su influxDB asyncio.gather(self.influx_client.write_all_data(meas_dict)) except Exception as e: logging.critical(f'::error: {e}::') # tempo di campionamento dal plc end_time = datetime.now() net_sampling_time = samplint_time - (end_time-now).microseconds/1e6 net_sampling_time = net_sampling_time if net_sampling_time > 0 else 0 await asyncio.sleep(samplint_time) ######################################################################################################################## ### MAIN STARTER def start_testing(self): # avvio lettura da database e scrittura su modbus #asyncio.run(self.mssql_2_plc_variables()) if len(self.client.measurement_list_dict) <=0 : return loop = asyncio.get_event_loop() for group in self.client.measurement_list_dict: sampling_time=group[ModbusVariableTags.R_SAMPLING_TIME_MS.name]/1000 measurements=group[ModbusVariableTags.MEASUREMENTS.name] loop.create_task(self.modbus_2_influx_db_variables(meas_dict=copy.deepcopy(measurements), samplint_time=copy.deepcopy(sampling_time))) loop.run_forever() <file_sep>/ModBusTCPDeviceTester/v_0.1/library/device_modbus.py import logging import os import time import sys import traceback import asyncio from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder from pymodbus.payload import BinaryPayloadBuilder from pymodbus.transaction import ModbusRtuFramer as ModbusFramer from pymodbus.client.sync import ModbusSerialClient from pymodbus.client.sync import ModbusTcpClient import library.utils as utils from library.base_modbus import BaseModbus, ModbusTypes, ModbusAccess, ModbusRegisterType from library.measurement import Measurement, ModbusMeasurement import aenum from enum import Enum, auto # class IngridModbusCommands(aenum.Enum): # _init_ = 'value register register_type modbus_type access uom count' # COMMAND = auto(), 0, ModbusRegisterType.HOLDING, ModbusTypes.INT16, ModbusAccess.WRITE, 'status', None # HOLDING class RtuModbus(BaseModbus): def __init__(self, logger, id, port, stopbits, bytesize, baudrate, timeout, method, parity, byteorder, wordorder, variables_dict=None): super().__init__(variables_dict=variables_dict, logger=logger) self.modbus_id = id self.modbus_port = port self.modbus_stopbits= stopbits self.modbus_bytesize = bytesize self.modbus_baudrate = baudrate self.modbus_timeout = timeout self.modbus_method = method self.modbus_parity = parity self.modbus_byteorder = Endian.Little if byteorder.lower() == 'little' else Endian.Big self.modbus_wordorder = Endian.Little if wordorder.lower() == 'little' else Endian.Big def connect(self): self.client = ModbusSerialClient(method= self.modbus_method, port = self.modbus_port, timeout = self.modbus_timeout, baudrate = self.modbus_baudrate, stopbits = self.modbus_stopbits, bytesize = self.modbus_bytesize, parity=self.modbus_parity) return self.client.connect() def disconnect(self): return self.client.close() class TcpModbus(BaseModbus): def __init__(self, logger, ip, port, id, byteorder, wordorder, variables_dict=None): super().__init__(variables_dict=variables_dict, logger=logger) self.modbus_ip = ip self.modbus_id = id self.modbus_port = port self.modbus_byteorder = Endian.Little if byteorder.lower() == 'little' else Endian.Little self.modbus_wordorder = Endian.Little if wordorder.lower() == 'little' else Endian.Little def connect(self): self.client = ModbusTcpClient(self.modbus_ip, port = self.modbus_port) return self.client.connect() def disconnect(self): return self.client.close() <file_sep>/Modbus2DBs/PlcSimulationEnv_DB/plc_writer/plc_module_class.py import time import os import sys import asyncio from six.moves import input import datetime import json import logging from abc import ABC, abstractmethod from library.plc_modbus import PlcModbus from library.measurement import Measurement, ModbusMeasurement import library.utils as utils from influxdb_module_class import InfluxDBModuleClass from multiprocessing import Process class PlcModuleClass(): MACHINE_TYPE = "INGRID" async_cmd_list=[] def __init__(self, logger, plc_config_dict): self.ip = utils.get(plc_config_dict,'MODBUS_IP') self.port = utils.get(plc_config_dict,'MODBUS_PORT') self.r_sampling_time = utils.get(plc_config_dict, 'R_SAMPLING_TIME_MS')/1000 self.w_sampling_time = utils.get(plc_config_dict, 'W_SAMPLING_TIME_MS')/1000 self.max_attempts=utils.get(plc_config_dict,'MAX_ATTEMPTS') self.measurement_list_dict = utils.get(plc_config_dict,'MODBUS_MEASUREMENTS') self.inputs_list_dict = utils.get(plc_config_dict, 'MODBUS_INPUTS') self.logger = logger self.device_instance = PlcModbus(self.logger, variables_dict=plc_config_dict, ip=self.ip, port = self.port) def get_meas_info_from_name(self, meas_name)->dict: for m in self.measurement_list_dict: if list(m.keys())[0] == meas_name: return list(m.values())[0] return None ############################################################################################# ### INIZIALIZZAZIONE e Shut down def connect_device(self): return self.device_instance.connect() def disconnect_device(self): return self.device_instance.disconnect() ############################################################################################# ### LETTURA variabili async def read_var_async(self, meas_dict): result = None try: key=list(meas_dict.keys())[0] vals=list(meas_dict.values())[0] register_number=utils.get(vals, 'REGISTER_NUMBER') value_type=utils.get(vals,'VALUE_TYPE') uom=utils.get(vals,'UOM') self.logger.debug(f'reading::{key}::{register_number}::value type::{value_type}::uom::{uom}') result = await self.device_instance.read_value(register_number, value_type, register_type=None, count=None, array_count=1) #aggiunta del valore vals['VALUE']=result except Exception as e: self.logger.critical(f'error::{e}') return result ############################################################################################# ### SCRITTURA variabili def start_manual_ctrl(self): data = None while data!= -1: data, val = self.ask_user() if data is not None and isinstance(data, dict): register_num=utils.get(data,'REGISTER_NUMBER') value_type=utils.get(data,'VALUE_TYPE') #chiamta in asincrono asyncio.run(self.device_instance.write_value(register_num, value_type, val)) def ask_user(self): data=None val=None print("Write value or check modbus parameters list") print(" - to set a value just write '<MODBUS_VARIABLE_NAME>=<VALUE>") print(" - to check modbus parameters list just type '--show-list'") print(" - to exit just type '--exit'") res=input('write here:') res=res.strip() if(res.lower()=='--show-list'): print(json.dumps(self.measurement_list_dict, indent=4, sort_keys=True)) elif res.lower()=='--exit': print('ciao.') data=-1 elif('=' in res): input_splitted=res.split('=') if(len(input_splitted)>1): key=input_splitted[0].strip() val=input_splitted[1].strip() for m in self.measurement_list_dict: self.get_meas_info_from_name(key) else: print('error, retry') else: print('nada, retry') return data,val async def sample_inputs(self, data_dict): ''' Inserimento dati multipli in modalità asincrona. ''' if(len(data_dict)>0): for key, val in data_dict: #chiamta in sincrono vals = self.get_meas_info_from_name(key) if(vals is not None): register_num=utils.get(vals,'REGISTER_NUMBER') value_type=utils.get(vals,'VALUE_TYPE') await self.device_instance.write_value(register_num, value_type, val) async def set_periodic_inputs(self, data_dict): ''' dict defined as: REGISTER_NUMBER VALUE_TYPE SAMPLING_TIME [ms] ''' while(len(data_dict)>0): for key, val in data_dict: #chiamta in sincrono vals = self.get_meas_info_from_name(key) if(vals is not None): register_num=utils.get(vals,'REGISTER_NUMBER') value_type=utils.get(vals,'VALUE_TYPE') sampling_time=utils.get(vals,'SAMPLING_TIME')/1000 asyncio.run(self.write_imput_with_delay(register_num, value_type, sampling_time, val)) async def write_imput_with_delay(self, register_num, value_type, delay, val): await asyncio.sleep(delay) return await self.device_instance.write_value(register_num, value_type, val) <file_sep>/IoTHub_RemoteMethodTester/library/base_iothub_reader_module_client.py import time import os import sys import asyncio from six.moves import input import datetime import json import threading import traceback import logging import random from abc import ABC, abstractmethod from azure.iot.device.aio import IoTHubModuleClient from azure.iot.device import MethodResponse, Message import library.utils as utils # from library.base_module_class import BaseModuleClass from library.base_iothub_client import BaseIotHubClient, IobHubRemoteMethodStatus from library.base_iothub_readwriter_client import BaseIotHubReadWriterClient from library.measurement import Measurement, ModbusMeasurement, FunctionMeasurement class BaseIotHubReaderModuleClient(BaseIotHubReadWriterClient): def __init__(self, measurement_list, config_measurement_list=[], variables_dict=None): super().__init__(measurement_list, config_measurement_list=config_measurement_list, variables_dict=variables_dict) async def _internal_send_message_(self, message, *args, **kwargs): if 'output' in kwargs: output = kwargs['output'] elif len(args) > 0: output = args[0] else: output = 'output1' await self.iothub_client.send_message_to_output(message, output) async def _init_iothub_client_(self): self.iothub_client = IoTHubModuleClient.create_from_edge_environment() <file_sep>/ModBus_PLC2PLC/old/test_casa/prepare-install.sh #!/bin/bash folder=./ # install docker-compose #sudo curl -L "https://github.com/docker/compose/releases/download/1.28.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose #sudo chmod +x /usr/local/bin/docker-compose # install Command-line completion #sudo curl -L "https://raw.githubusercontent.com/docker/compose/1.28.4/contrib/completion/bash/docker-compose" -o /etc/bash_completion.d/docker-compose # Installazioni necessarie per Pyodbc per Microsoft SQL Server: sudo apt-get install python3-dev sudo apt-get install unixodbc-dev sudo su curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - #Download appropriate package for the OS version #Choose only ONE of the following, corresponding to your OS version #Ubuntu 16.04 curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > /etc/apt/sources.list.d/mssql-release.list #Ubuntu 18.04 curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.list #Ubuntu 20.04 curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list #Ubuntu 20.10 curl https://packages.microsoft.com/config/ubuntu/20.10/prod.list > /etc/apt/sources.list.d/mssql-release.list exit sudo apt-get update sudo ACCEPT_EULA=Y apt-get install msodbcsql17 # optional: for bcp and sqlcmd sudo ACCEPT_EULA=Y apt-get install mssql-tools echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc source ~/.bashrc # optional: for unixODBC development headers sudo apt-get install unixodbc-dev <file_sep>/IoTHub_RemoteMethodTester/requirements.txt azure-iot-device==2.4.0 pymodbus numpy aenum pyparsing psycopg2-binary sqlalchemy<file_sep>/ModBus_PLC2AzureDirectMethod/ModBus_PLC2AzureDirectMethod_v_0.0.1/plc_readwrite.py import library.utils as utils from enum import Enum, auto from library.plc_modbus import PlcModbus from datetime import datetime from library.measurement import Measurement class PlcVariableTags(Enum): REGISTER_NUMBER = auto() VALUE_TYPE = auto() VALUE = auto() WRITE_VALUE = auto() TIME = auto() R_SAMPLING_TIME_MS = auto() MEASUREMENTS = auto() MEASUREMENT_NAMES = auto() OFFSET = auto() SCALE = auto() class PlcRwMode(Enum): READ = auto() WRITE = auto() class PlcReadWrite(): def __init__(self, logger, plc_config_dict): self.logger = logger self.name = utils.get(plc_config_dict,'NAME', "plc_test") self.priority = utils.get(plc_config_dict,'PRIORITY', 1) self.rw_mode = PlcRwMode[utils.get(plc_config_dict,'RW_MODE', 'READ')] self.max_attempts = utils.get(plc_config_dict,'MAX_ATTEMPTS', 3) setup = utils.get(plc_config_dict,'SETUP') self.measurement_list_dict = utils.get(setup,'MODBUS_MEASUREMENTS') for group in self.measurement_list_dict: group[PlcVariableTags.MEASUREMENT_NAMES.name] = [list(value.keys())[0] for value in group[PlcVariableTags.MEASUREMENTS.name]] self.device_instance = PlcModbus(self.logger, variables_dict=setup) def get_meas_info_from_name(self, meas_name)->dict: for m in self.measurement_list_dict: if list(m.keys())[0] == meas_name: return list(m.values())[0] return None ############################################################################################# ### INIZIALIZZAZIONE e Shut down def connect_device(self): return self.device_instance.connect() def disconnect_device(self): return self.device_instance.disconnect() ############################################################################################# ### LETTURA variabili async def read_var_async(self, meas_dict): result = None try: # acquisizione della chiave key=list(meas_dict.keys())[0] # acquisizione dei parametri vals=list(meas_dict.values())[0] register_number=utils.get(vals, PlcVariableTags.REGISTER_NUMBER.name) value_type=utils.get(vals, PlcVariableTags.VALUE_TYPE.name) scale = utils.get(vals, PlcVariableTags.SCALE.name, 1) offset = utils.get(vals, PlcVariableTags.OFFSET.name, 0) result = await self.device_instance.read_value(register_number, value_type, register_type=None, count=None, array_count=1) self.logger.debug(f'reading::{key}::{register_number}::value type::{value_type}::value::{result}') #aggiunta del valore vals[PlcVariableTags.VALUE.name]=result vals[PlcVariableTags.WRITE_VALUE.name]=self.post_process_value(result, scale, offset) vals[PlcVariableTags.TIME.name]= datetime.utcnow().isoformat() except Exception as e: self.logger.critical(f'error::{e}') return result async def write_var_async(self, meas_dict, value): result = None try: # acquisizione della chiave key=list(meas_dict.keys())[0] # acquisizione dei parametri vals=list(meas_dict.values())[0] # scrittura della variabile register_number=utils.get(vals, PlcVariableTags.REGISTER_NUMBER.name) value_type=utils.get(vals, PlcVariableTags.VALUE_TYPE.name) result = await self.device_instance.write_value(register_number, value_type, value) self.logger.debug(f'write::{key}::{register_number}::value type::{value_type}::values::{value}') except Exception as e: self.logger.critical(f'error::{e}') return result def post_process_value(self, value, scale, offset): return value * scale + offset<file_sep>/Modbus2DBs/Microturbine_RTU_2_Influx/testing_ok/plc_reader/library/math_parser.py import pyparsing as pyp import math import operator import datetime class NumericStringParser(object): ''' Most of this code comes from the fourFn.py pyparsing example http://pyparsing.wikispaces.com/file/view/fourFn.py http://pyparsing.wikispaces.com/message/view/home/15549426 __author__='<NAME>' All I've done is rewrap Paul McGuire's fourFn.py as a class, so I can use it more easily in other places. ''' def __init__(self, dict_var={}): self.dict_var = dict_var """ expop :: '^' multop :: '*' | '/' addop :: '+' | '-' integer :: ['+' | '-'] '0'..'9'+ atom :: PI | E | real | fn '(' expr ')' | '(' expr ')' factor :: atom [ expop factor ]* term :: factor [ multop factor ]* expr :: term [ addop term ]* """ point = pyp.Literal( "." ) e = pyp.CaselessLiteral( "E" ) fnumber = pyp.Combine( pyp.Word( "+-" + pyp.nums, pyp.nums ) + pyp.Optional( point + pyp.Optional( pyp.Word( pyp.nums ) ) ) + pyp.Optional( e + pyp.Word( "+-" + pyp.nums, pyp.nums ) ) ) ident = pyp.Word(pyp.alphas, pyp.alphas + pyp.nums + "_$") plus = pyp.Literal( "+" ) minus = pyp.Literal( "-" ) mult = pyp.Literal( "*" ) div = pyp.Literal( "/" ) pow_ = pyp.Literal( "^" ) lshift = pyp.Literal( "<<" ) rshift = pyp.Literal( ">>" ) # not_ = pyp.Literal( "not" ) and_ = pyp.Literal( "and" ) or_ = pyp.Literal( "or" ) xor_ = pyp.Literal( "xor" ) eq = pyp.Literal( "==" ) neq = pyp.Literal( "!=" ) gt = pyp.Literal( ">" ) ge = pyp.Literal( ">=" ) lt = pyp.Literal( "<" ) le = pyp.Literal( "<=" ) lpar = pyp.Literal( "(" ).suppress() rpar = pyp.Literal( ")" ).suppress() addop = plus | minus | and_ | or_ | xor_ multop = mult | div | lshift | rshift equop = eq | neq | ge | gt | le | lt expop = pow_ # | not_ pi = pyp.CaselessLiteral( "PI" ) variables = pyp.Word("$", pyp.alphanums + '.' + '_') expr = pyp.Forward() equation = pyp.Forward() atom = ( ( pyp.Optional(pyp.oneOf("- +")) + (pi | e | fnumber | ident + lpar + expr + rpar | variables).setParseAction(self.pushFirst) ) | pyp.Optional(pyp.oneOf("- +")) + pyp.Group(lpar + expr + rpar) ).setParseAction(self.pushUMinus) # by defining exponentiation as "atom [ ^ factor ]..." instead of # "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-right # that is, 2^3^2 = 2^(3^2), not (2^3)^2. factor = pyp.Forward() factor << atom + pyp.ZeroOrMore( ( expop + factor ).setParseAction( self.pushFirst ) ) term = factor + pyp.ZeroOrMore( ( multop + factor ).setParseAction( self.pushFirst ) ) expr << term + pyp.ZeroOrMore( ( addop + term ).setParseAction( self.pushFirst ) ) equation << expr + pyp.ZeroOrMore( ( equop + expr ).setParseAction( self.pushFirst ) ) self.bnf = equation # map operator symbols to corresponding arithmetic operations epsilon = 1e-12 self.opn = { "+" : operator.add, "-" : operator.sub, "*" : operator.mul, "/" : operator.truediv, "^" : operator.pow, "<<" : operator.lshift, ">>" : operator.rshift } self.equality_opn = { "==" : operator.eq, "!=" : operator.ne, ">=" : operator.ge, ">" : operator.gt, "<=" : operator.le, "<" : operator.lt } self.logical_opn = { "and" : operator.and_, "or" : operator.or_, "not" : operator.not_, "xor" : operator.xor, } self.fn = { "sin" : math.sin, "cos" : math.cos, "tan" : math.tan, "acos" : math.acos, "asin" : math.asin, "atan" : math.atan, "sqrt" : math.sqrt, "abs" : abs, "trunc" : lambda a: int(a), "round" : round, "exp" : math.exp, "log" : math.log, "log2" : math.log2, "Log" : math.log10, "not" : operator.not_, # For Python3 compatibility, cmp replaced by ((a > 0) - (a < 0)). See # https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons "sgn" : lambda a: abs(a) > epsilon and ((a > 0) - (a < 0)) or 0 } self.exprStack = [] def pushFirst(self, strg, loc, toks ): self.exprStack.append( toks[0] ) def pushUMinus(self, strg, loc, toks ): if toks and toks[0] == '-': self.exprStack.append( 'unary -' ) def evaluateStack(self, s ): op = s.pop() if op == 'unary -': op1 = self.evaluateStack(s) if op1 is None: return None return 0. - op1 elif op == 'not': op1 = self.evaluateStack(s) if op1 is None: return None return int(self.logical_opn[op]( int(op1))) elif op in ['>>', '<<']: op2 = self.evaluateStack( s ) op1 = self.evaluateStack( s ) if op1 is None or op2 is None: return None return self.opn[op]( int(op1), int(op2) ) elif op in list(self.opn.keys()): op2 = self.evaluateStack( s ) op1 = self.evaluateStack( s ) if op1 is None or op2 is None: return None return self.opn[op]( op1, op2 ) elif op in list(self.logical_opn.keys()): op2 = self.evaluateStack( s ) op1 = self.evaluateStack( s ) if op1 is None or op2 is None: return None return self.logical_opn[op]( int(op1), int(op2) ) elif op in list(self.equality_opn.keys()): op2 = self.evaluateStack( s ) op1 = self.evaluateStack( s ) if op1 is None or op2 is None: return None return int(self.equality_opn[op]( op1, op2 )) elif op == "PI": return math.pi # 3.1415926535 elif op.startswith('$'): # custom variables op = op[1:] split_op = op.split('.') key = split_op[0] property_name = split_op[1] if len(split_op) > 1 else None if property_name is None: value = self.dict_var[key] else: value = getattr(self.dict_var[key], property_name) if isinstance(value, datetime.datetime): value = (value - datetime.datetime(1970,1,1)).total_seconds() return value elif op == "E": return math.e # 2.718281828 elif op in self.fn: op1 = self.evaluateStack(s) if op1 is None: return None return self.fn[op](op1) elif op[0].isalpha(): return 0 else: return float(op) def eval(self, num_string, parseAll = True): self.exprStack = [] results = self.bnf.parseString(num_string, parseAll) val = self.evaluateStack( self.exprStack[:] ) return val if __name__ == "__main__": dict_var = {"A": 10, "B": 100} nsp = NumericStringParser(dict_var) print(nsp.eval('$A+$B / 3 ')) import dataclasses @dataclasses.dataclass class TestClass: name: str value_A: float valueB: int = 0 dict_var = {"A_A": TestClass('nameA', 10.01), "B_B": TestClass('nameB', 100 , 10)} nsp = NumericStringParser(dict_var) print(nsp.eval('$A_A.value_A * $A_A.valueB + $B_B.value_A * $B_B.valueB / 3 ')) # @dataclasses.dataclass class TestClass2: def __init__(self, name, value): self.name = name self.value = value @property def value2(self): return self.value * self.value expression = """ 0.5 * $A.value * ( 0.25 * $C.value * $D.value - ( $D.value - 2 * $E.value ) * sqrt( 100 + $E.value * $D.value - $E.value^ 2) ) """ expression = """ $A.value2 """ dict_var = {} dict_var["A"] = TestClass2('nameA', 10.0) dict_var["B"] = TestClass2('nameB', 2.0) dict_var["C"] = TestClass2('nameC', 4.0) dict_var["D"] = TestClass2('nameD', 3.0) dict_var["E"] = TestClass2('nameE', 5.0) nsp = NumericStringParser(dict_var) print(nsp.eval(expression)) expressions = [] expressions.append('1 or 0') expressions.append('1 or 1') expressions.append('0 or 1') expressions.append('0 or 0') expressions.append('1 and 0') expressions.append('1 and 1') expressions.append('0 and 1') expressions.append('0 and 0') expressions.append('1 xor 0') expressions.append('1 xor 1') expressions.append('0 xor 1') expressions.append('0 xor 0') expressions.append('1 or not(0)') expressions.append('1 or not(1)') expressions.append('0 or not(1)') expressions.append('0 or not(0)') expressions.append('1 and not(0)') expressions.append('1 and not(1)') expressions.append('0 and not(1)') expressions.append('0 and not(0)') expressions.append('1 xor not(0)') expressions.append('1 xor not(1)') expressions.append('0 xor not(1)') expressions.append('not(0)*3.5') expressions.append('not(1)*3.5') expressions.append('5 - 3 > 5 - 3') expressions.append('5 - 3 < 5 - 3') expressions.append('5 - 3 == 5 - 3') expressions.append('5 - 3 != 5 - 3') expressions.append('5 - 3 <= 5 - 3') expressions.append('5 - 3 >= 5 - 3') expressions.append('(1 and (1 or 0)) == (1 or not(1))') expressions.append('2 >> 10') expressions.append('1 << 10') nsp = NumericStringParser(dict_var) for e in expressions: try: answer = int(eval(e)) except: answer = None print(f'{e} = {nsp.eval(e)} (Correct answer: {answer})') <file_sep>/Modbus2DBs/H2_Modbus_2_Influx/plc_reader/start_testing.sh #avvio dei docker for i in {1..3} do sudo docker start $(sudo docker ps -a -q) done <file_sep>/GretaAnalogWriter/library/drago_ai_96100.py import logging import os import time import sys import traceback import asyncio import library.utils as utils import aenum from enum import Enum, auto from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder from pymodbus.payload import BinaryPayloadBuilder from pymodbus.client.sync import ModbusSerialClient from library.base_drago import ModbusTypes, IdentifiersCommands, DIPCommands, CommonCommands, BaseDrago, ModbusAccess # logging config # logging.basicConfig(filename='log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') # logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) class DragoAI96100Commands(aenum.Enum): _init_ = 'value register modbus_type access uom count' VALUE_0_20UA = auto(), 0, ModbusTypes.INT16, ModbusAccess.READ, 'uA', None VALUE_0_20MA = auto(), 1, ModbusTypes.INT16, ModbusAccess.READ, 'mA', None STATUS = auto(), 4, ModbusTypes.INT16, ModbusAccess.READ, 'NONE', None VALUE_SCALED = auto(), 50, ModbusTypes.FLOAT32, ModbusAccess.READ, 'NONE', None SCALE_IN_MIN = auto(), 2006, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'mA', None SCALE_IN_MAX = auto(), 2008, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'mA', None SCALE_OUT_MIN = auto(), 2010, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'NONE', None SCALE_OUT_MAX = auto(), 2012, ModbusTypes.FLOAT32, ModbusAccess.READ_WRITE, 'NONE', None CURRENT_VOLTAGE_DIP_MODE = auto(), 2512, ModbusTypes.INT16, ModbusAccess.READ, 'NONE', None class DragoAI96100(BaseDrago): def __init__(self, variables_dict=None, logger=None): super().__init__(variables_dict=variables_dict, logger=logger) # self.setup_scale() def get_list_command_enums(self): return super().get_list_command_enums() + [DragoAI96100Commands] async def setup_scale(self): scale_in_min = utils.parse_float(self.get('ANALOG_SCALE_IN_MIN', default=4), default=4) scale_in_max = utils.parse_float(self.get('ANALOG_SCALE_IN_MAX', default=20), default=20) scale_out_min = utils.parse_float(self.get('ANALOG_SCALE_OUT_MIN', default=4), default=4) scale_out_max = utils.parse_float(self.get('ANALOG_SCALE_OUT_MAX', default=20), default=20) await self.execute_command_write(DragoAI96100Commands.SCALE_IN_MIN, scale_in_min) await self.execute_command_write(DragoAI96100Commands.SCALE_IN_MAX, scale_in_max) await self.execute_command_write(DragoAI96100Commands.SCALE_OUT_MIN, scale_out_min) await self.execute_command_write(DragoAI96100Commands.SCALE_OUT_MAX, scale_out_max) def get_command_from_channel(self, channel): if channel == 'AI1': return DragoAI96100Commands.VALUE_0_20MA if __name__ == "__main__": async def main(): drago = DragoAI96100({"MODBUS_ID": 1}) await drago.connect_to_modbus_server() await drago.setup_scale() print(f"Read {DragoAI96100Commands.VALUE_SCALED} : ", await drago.execute_command_read(DragoAI96100Commands.VALUE_SCALED)) for e in drago.get_list_command_enums(): for i in e: print(f"Read {i} : ", await drago.execute_command_read(i)) asyncio.run(main()) <file_sep>/IoTHub_RemoteMethodTester/library/tcpip_modbus.py # from pymodbus.client.asynchronous.tcp import AsyncModbusTCPClient as ModbusTcpClient # from pymodbus.client.asynchronous.udp import (AsyncModbusUDPClient as ModbusUdpClient) # from pymodbus.client.asynchronous import schedulers import logging import os import time import sys import traceback import asyncio from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder from pymodbus.payload import BinaryPayloadBuilder from pymodbus.client.sync import ModbusTcpClient import library.utils as utils from library.base_modbus import BaseModbus, ModbusTypes, ModbusAccess, ModbusRegisterType from library.measurement import Measurement, ModbusMeasurement import aenum from enum import Enum, auto class TcpIpModbus(BaseModbus): def __init__(self, logger, setpoint_measurement, variables_dict=None): super().__init__(variables_dict=variables_dict, logger=logger) self.ip = self.get('MODBUS_IP', default='192.168.0.1') self.port = utils.parse_int(self.get('MODBUS_PORT'), default=502) def connect(self): self.client = ModbusTcpClient(self.ip, self.port) return self.client.connect() def get_list_command_enums(self): return [] def get_command_from_channel(self, channel): None<file_sep>/Encrypting/main.py import json import os import hashlib import logging import datetime ''' from cryptography.fernet import Fernet key = b'<KEY> cipher_suite = Fernet(key) ciphered_text = cipher_suite.encrypt(b"SuperSecretPassword") #required to be bytes print(ciphered_text.decode("utf-8")) unciphered_text = (cipher_suite.decrypt(ciphered_text)) print(unciphered_text.decode("utf-8")) test = "CIAO".encode('utf-8') print(test) ''' def generate_message_hash(message, time=None, secret_key=None, hash_algorithm=None, hash_timeout=None): SECRET_KEY = os.getenv("SECRET_KEY", default=None) if secret_key is None else secret_key HASH_ALGORITHM = os.getenv("HASH_ALGORITHM", default='sha1') if hash_algorithm is None else hash_algorithm if SECRET_KEY is None: logging.getLogger().critical('MISSING SECRET_KEY ENV VARIABLE') return False, None message_to_hash = json.dumps(message, sort_keys=True) + SECRET_KEY # print('message_to_hash', message_to_hash.encode('utf-8')) hash_object = hashlib.new(HASH_ALGORITHM) hash_object.update(message_to_hash.encode('utf-8')) hash_str = hash_object.hexdigest() message_encoded = hash_str.encode('utf-8') message_decoded = message_encoded.decode('utf-8') return message_encoded, message_decoded if __name__ == "__main__": test = generate_message_hash("CIAO", 10, "ASDFDSAASDF", "sha512_256", 100 ) print(test)<file_sep>/ModBus_PLC2AzureDirectMethod/ModBus_PLC2AzureDirectMethod_v_0.0.1/library/base_db_manager.py from abc import ABC, abstractmethod from typing import List # engine = create_engine('postgresql+psycopg2://username:password@host:port/database') class Query(): def __init__(self, query, params=None, fast=False): self.query = query self.params = params self.fast = fast class BaseDBManager(ABC): def __init__(self): self.connection = None @abstractmethod def connect(self): pass @abstractmethod def disconnect(self): pass def get_connection(self): if self.connection is None: self.connect() return self.connection @abstractmethod def query_execute_many(self, query: Query, params, commit=False, fetch=False, aslist=False, asdataframe=False, columns=None): pass @abstractmethod def query_execute(self, query: Query, commit=False, fetch=False, aslist=False, asdataframe=False, columns=None): pass @abstractmethod def query_execute_list(self, query_list: List[Query], commit=False): pass @abstractmethod def query_execute_copy(self, df, destination_table, columns=None, commit=False): pass<file_sep>/ModBus_PLC2AzureDirectMethod/ModBus_PLC2AzureDirectMethod_v_0.0.1/requirements.txt pymodbus asyncio datetime six pyparsing pandas requests <file_sep>/Modbus2DBs/PLC_Schneider_Modbus_2_Influx/plc_reader/plc_looper.py import logging import logging.handlers import asyncio from plc_module_class import PlcModuleClass, PlcVariableTags from influxdb_module_class import InfluxDBModuleClass import copy class PlcLooper(): def __init__(self, plc_client: PlcModuleClass, influxdb_client: InfluxDBModuleClass): self.plc_client = plc_client self.influx_client = influxdb_client async def plc_2_influx_db_variables(self, meas_dict, samplint_time): while True: try: # lista di task per la lettura dal plc in modo asincrono tasks = [self.plc_client.read_var_async(m) for m in meas_dict] # attesa della fine di tutti i task await asyncio.wait(tasks) # scrittura dati acquisiti su influxDB asyncio.gather(self.influx_client.write_all_data(meas_dict)) except Exception as e: logging.critical(f'::error: {e}::') # tempo di campionamento dal plc await asyncio.sleep(samplint_time) ######################################################################################################################## ### MAIN STARTER def start_testing(self): # avvio lettura da database e scrittura su plc #asyncio.run(self.mssql_2_plc_variables()) if len(self.plc_client.measurement_list_dict) <=0 : return loop = asyncio.get_event_loop() for group in self.plc_client.measurement_list_dict: sampling_time=group[PlcVariableTags.R_SAMPLING_TIME_MS.name]/1000 measurements=group[PlcVariableTags.MEASUREMENTS.name] loop.create_task(self.plc_2_influx_db_variables(meas_dict=copy.deepcopy(measurements), samplint_time=copy.deepcopy(sampling_time))) loop.run_forever() <file_sep>/Modbus2DBs/H2_Modbus_2_Influx/plc_reader/mssql_module_class.py import pyodbc import pandas as pd import os import logging import traceback import itertools from io import StringIO from library.base_db_manager import BaseDBManager import library.utils as utils class Query(): def __init__(self, query, params=None, fast=False): self.query = query self.params = params self.fast = fast class MSSQLManager(BaseDBManager): def __init__(self, user=None, password=<PASSWORD>, server=None, database=None, config_dict=None, logger=None): super().__init__() self.config_dict = utils.merge_dicts_priority(config_dict, os.environ) self.user = utils.get(self.config_dict, "USERNAME", default=None) if user is None else user self.password = utils.get(self.config_dict, "PASSWORD", default=None) if password is None else password self.server = utils.get(self.config_dict, "SERVER", default=None) if server is None else server self.database = utils.get(self.config_dict, "DATABASE", default=None) if database is None else database self.logger = logger if logger is not None else logging.getLogger() def init_testing(self, data_source =None, machine_twin=None, sensor_data=None): self.data_source = utils.get(self.config_dict, "DATA_SOURCE", default=None) if data_source is None else data_source self.machine_twin = utils.get(self.config_dict, "MACHINE_TWIN", default=None) if machine_twin is None else machine_twin self.sensor_data = utils.get(self.config_dict, "SENSORS_DATA", default=None) if sensor_data is None else sensor_data @utils.overrides(BaseDBManager) def connect(self): # TODO IMPLEMENT RETRY POLICY # connection = psycopg2.connect( user=os.getenv("POSTGRESQL_USERNAME"), # password=os.getenv("POSTGRESQL_PASSWORD"), # host=os.getenv("POSTGRESQL_HOST"), # port=os.getenv("POSTGRESQL_PORT"), # database=os.getenv("POSTGRESQL_DATABASE")) self.logger.info(f'Connecting to {self.user}@{self.server}/{self.database}.') self.connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+self.server+';DATABASE='+self.database+';UID='+self.user+';PWD='+ self.password) @utils.overrides(BaseDBManager) def disconnect(self): if self.connection is not None: if not self.connection.closed: self.logger.info(f'Disconnecting from {self.user}@{self.server}/{self.database}.') self.connection.close() # def get_connection(self): # if self.connection is None: # self.connect() # return self.connection @utils.overrides(BaseDBManager) def query_execute_many(self, query: Query, commit=False, fetch=False, aslist=False, asdataframe=False, columns=None): # connection = None cursor = None try: connection = self.get_connection() cursor = connection.cursor() # executemany: 25s # execute_batch 12.5s # cursor.executemany(query, params) cursor.executemany(query.query, query.params) if commit: connection.commit() except: print(traceback.format_exc()) finally: # if(connection): cursor.close() # connection.close() @utils.overrides(BaseDBManager) def query_execute(self, query: Query, commit=False, fetch=False, aslist=False, asdataframe=False, columns=None): cursor = None try: connection = self.get_connection() cursor = connection.cursor() # print ( connection.get_dsn_parameters(),"\n") # Print PostgreSQL Connection properties cursor.execute(query.query) results = None if fetch: results = [] row = cursor.fetchone() while row: results_list = list() for el in list(row): if isinstance(el, str): results_list.append(el.strip()) elif isinstance(el, float): results_list.append(round(el, 7)) # TODO else: results_list.append(el) results.append(results_list) row = cursor.fetchone() if commit: connection.commit() if results is not None and aslist: results = list(itertools.chain(*results)) elif results is not None and asdataframe: results = pd.DataFrame(results, columns=columns) return results except: print(traceback.format_exc()) finally: if(connection): cursor.close() # connection.close() @utils.overrides(BaseDBManager) def query_execute_list(self, query_list, commit=False): cursor = None try: connection = self.get_connection() cursor = connection.cursor() # print ( connection.get_dsn_parameters(),"\n") # Print PostgreSQL Connection properties for query in query_list: # cursor.fast_executemany = query.fast # TODO find an alternative if query.params is None: cursor.execute(query.query) else: if len(query.params) > 0: cursor.executemany(query.query, query.params) if commit: connection.commit() except: if cursor is not None: cursor.rollback() print(traceback.format_exc()) finally: # if(connection): cursor.close() # connection.close() @utils.overrides(BaseDBManager) def query_execute_copy(self, df, destination_table, columns=None, commit=False): cursor = None try: connection = self.get_connection() cursor = connection.cursor() f = StringIO() df.to_csv(f, sep=',', header=False, index=False, quoting=3) f.seek(0) cursor.copy_from(f, destination_table, columns=columns, sep=',') if commit: connection.commit() except: # if cursor is not None: # cursor.rollback() if connection is not None: print('ROLLBACK') connection.rollback() print(traceback.format_exc()) finally: # if(connection): cursor.close() # connection.close() # TESTING if __name__=='__main__': server = 'greta-simulation.database.windows.net' database = 'regasphere_dev' user = 'rose_reader@greta-simulation' password = '<PASSWORD>' mssql_client = MSSQLManager(user, password, server, database) query_str = "select time, value \ from vw_sensors_data \ where time > '2021/02/27 08:00:00'\ and machine_name = 'sandonato_ingrid_certosa' \ and sensor_type = 'MASSFLOW' \ order by time asc" query = Query(query_str) res = mssql_client.query_execute(query, commit=False, fetch=True, asdataframe=True, columns=['time', 'value']) print(res)<file_sep>/ModBusRtuDeviceTester/v_0.1/main.py import json import os import logging from logging import handlers import sys from library.rtu_modbus import RtuModbus import library.utils as utils import asyncio ###################################################################################################################### ### MAIN def init_logging(logger, filename, level=logging.INFO, stdout=True, maxBytes=10000, backupCount=5): logging.getLogger().setLevel(logging.NOTSET) logging.getLogger().handlers = [] rotatingHandler = logging.handlers.RotatingFileHandler(filename=filename, maxBytes=maxBytes, backupCount=backupCount) rotatingHandler.setLevel(logging.DEBUG) rotatingHandler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) logging.getLogger().addHandler(rotatingHandler) logging.getLogger(__name__).setLevel(level) logging.getLogger("pymodbus").setLevel(logging.DEBUG) if stdout: logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) logger = logging.getLogger(__name__) logger.info('init_logging::end') ###################################################################################################################### # Parametri di configurazione modbus_port = '/dev/ttyUSB0' modbus_id = 1 modbus_stopbits = 1 modbus_bytesize = 8 modbus_baudrate = 9600 modbus_timeout = 1 modbus_method = 'rtu' modbus_parity = 'N' modbus_byteorder = 'Big' modbus_wordorder = 'Big' ###################################################################################################################### # MAIN async def main(): # Logging logger = logging init_logging(logger, 'test.log') # Connessione al RTU tramite Modbus rtu_modbus_client = RtuModbus( logger, modbus_id, modbus_port, modbus_stopbits, modbus_bytesize, modbus_baudrate, modbus_timeout, modbus_method, modbus_parity, modbus_byteorder, modbus_wordorder) if rtu_modbus_client.connect() == True: # Lettura dei valori try: register_num = 40238 type_str = 'UINT16' array_count = 1 value = True enable_write:bool = False read_result = await rtu_modbus_client.read_value(register_num, type_str, array_count=array_count) print(read_result) # Scrittura dei valori if enable_write == True: write_result = await rtu_modbus_client.write_value(register_num, type_str, value) print(write_result) read_result = await rtu_modbus_client.read_value(register_num, type_str, array_count=array_count) print(read_result) except Exception as e: print(e) rtu_modbus_client.disconnect() logger.info("::STOP::") logger.info("------------------------------------------------------") ############################# Avvio TEST if __name__ == "__main__": asyncio.run(main()) <file_sep>/2_DEPLOY/RTUModbusModule/V2/main.py from rtu_module_class import RtuModuleClass if __name__ == "__main__": RtuModuleClass().run()<file_sep>/Modbus2DBs/Microturbine_RTU_2_Influx/testing_ok/plc_reader/README.md PER LA PRIMA ESECUZIONE AVVIARE IL SEGUENTE COMANDO DA BASH: source ./first_setup.sh IN CASO DI MODIFICA DEL SW O DEL FILE DI CONFIGURAZIONE ESEGUIRE source ./reconfigure.sh IN CASO DI AVVIO DELLA MACCHINA, SE GIA' TUTTO E' CONFIGURATO CORRETTAMENTE, ESEGUIRE source ./start_testing.sh <file_sep>/Modbus2DBs/PLC_Schneider_Modbus_2_Influx/plc_reader/plc_module_class.py import datetime from library.plc_modbus import PlcModbus import library.utils as utils from enum import Enum, auto from datetime import datetime class PlcVariableTags(Enum): REGISTER_NUMBER = auto() VALUE_TYPE = auto() VALUE = auto() TIME = auto() R_SAMPLING_TIME_MS = auto() MEASUREMENTS = auto() class PlcModuleClass(): MACHINE_TYPE = "INGRID" async_cmd_list=[] def __init__(self, logger, plc_config_dict): self.ip = utils.get(plc_config_dict,'MODBUS_IP', "192.168.0.1") self.port = utils.get(plc_config_dict,'MODBUS_PORT', 502) self.max_attempts=utils.get(plc_config_dict,'MAX_ATTEMPTS', 3) self.measurement_list_dict = utils.get(plc_config_dict,'MODBUS_MEASUREMENTS') self.logger = logger self.device_instance = PlcModbus(self.logger, variables_dict=plc_config_dict, ip=self.ip, port = self.port) def get_meas_info_from_name(self, meas_name)->dict: for m in self.measurement_list_dict: if list(m.keys())[0] == meas_name: return list(m.values())[0] return None ############################################################################################# ### INIZIALIZZAZIONE e Shut down def connect_device(self): return self.device_instance.connect() def disconnect_device(self): return self.device_instance.disconnect() ############################################################################################# ### LETTURA variabili async def read_var_async(self, meas_dict): result = None try: # acquisizione della chiave key=list(meas_dict.keys())[0] # acquisizione dei parametri vals=list(meas_dict.values())[0] register_number=utils.get(vals, PlcVariableTags.REGISTER_NUMBER.name) value_type=utils.get(vals, PlcVariableTags.VALUE_TYPE.name) self.logger.debug(f'reading::{key}::{register_number}::value type::{value_type}') result = await self.device_instance.read_value(register_number, value_type, register_type=None, count=None, array_count=1) #aggiunta del valore vals[PlcVariableTags.VALUE.name]=result vals[PlcVariableTags.TIME.name]=datetime.utcnow().isoformat() except Exception as e: self.logger.critical(f'error::{e}') return result <file_sep>/GretaAnalogWriter/library/drago_rele_96800.py import logging import os import time import sys import traceback import asyncio import library.utils as utils import aenum from enum import Enum, auto from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder from pymodbus.payload import BinaryPayloadBuilder from pymodbus.client.sync import ModbusSerialClient from library.base_drago import ModbusTypes, IdentifiersCommands, DIPCommands, CommonCommands, BaseDrago, ModbusAccess # logging config # logging.basicConfig(filename='log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') # logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) class DragoRELE96800Commands(aenum.Enum): _init_ = 'value register modbus_type access uom count' RELE_1 = auto(), 0, ModbusTypes.COIL, ModbusAccess.READ_WRITE, 'NONE', None RELE_2 = auto(), 1, ModbusTypes.COIL, ModbusAccess.READ_WRITE, 'NONE', None RELE_3 = auto(), 2, ModbusTypes.COIL, ModbusAccess.READ_WRITE, 'NONE', None RELE_4 = auto(), 3, ModbusTypes.COIL, ModbusAccess.READ_WRITE, 'NONE', None RELE_DIRECT = auto(), 10, ModbusTypes.UINT16, ModbusAccess.READ_WRITE, 'NONE', None class DragoRELE96800(BaseDrago): def __init__(self, variables_dict=None, logger=None): super().__init__(variables_dict=variables_dict, logger=logger) def get_list_command_enums(self): return super().get_list_command_enums() + [DragoRELE96800Commands] def get_command_from_channel(self, channel): if channel == 'DO1' or channel == 'RELE1': return DragoRELE96800Commands.RELE_1 elif channel == 'DO2' or channel == 'RELE2': return DragoRELE96800Commands.RELE_2 elif channel == 'DO3' or channel == 'RELE3': return DragoRELE96800Commands.RELE_3 elif channel == 'DO4' or channel == 'RELE4': return DragoRELE96800Commands.RELE_4 if __name__ == "__main__": async def main(): drago = DragoRELE96800({"MODBUS_ID": 2}) await drago.connect_to_modbus_server() # print("Coils 1: FALSE (write)", drago.client.write_coil(0, False, unit=2)) # print("Coils 3: TRUE (write)", drago.client.write_coil(2, True, unit=2)) # print("Coils 1: ", drago.client.read_coils(0, 1, unit=2).bits) # print("Coils 2: ", drago.client.read_coils(1, 1, unit=2).bits) # print("Coils 3: ", drago.client.read_coils(2, 1, unit=2).bits) # print("Coils 4: ", drago.client.read_coils(3, 1, unit=2).bits) # print("Coils 1: TRUE (write)", drago.client.write_coil(0, True, unit=2)) # print("Coils 3: FALSE (write)", drago.client.write_coil(2, False, unit=2)) # print("Coils 1: ", drago.client.read_coils(0, 1, unit=2).bits) # print("Coils 2: ", drago.client.read_coils(1, 1, unit=2).bits) # print("Coils 3: ", drago.client.read_coils(2, 1, unit=2).bits) # print("Coils 4: ", drago.client.read_coils(3, 1, unit=2).bits) print("Rele1 : FALSE (write)", await drago.execute_command_write(DragoRELE96800Commands.RELE_1, False)) print("Rele3 : TRUE (write)", await drago.execute_command_write(DragoRELE96800Commands.RELE_3, True)) print("Rele1 : ", await drago.execute_command_read(DragoRELE96800Commands.RELE_1)) print("Rele2 : ", await drago.execute_command_read(DragoRELE96800Commands.RELE_2)) print("Rele3 : ", await drago.execute_command_read(DragoRELE96800Commands.RELE_3)) print("Rele4 : ", await drago.execute_command_read(DragoRELE96800Commands.RELE_4)) print("RELE_DIRECT : ", await drago.execute_command_read(DragoRELE96800Commands.RELE_DIRECT)) print("Rele1 : TRUE (write)", await drago.execute_command_write(DragoRELE96800Commands.RELE_1, True)) print("Rele3 : FALSE (write)", await drago.execute_command_write(DragoRELE96800Commands.RELE_3, False)) print("Rele1 : ", await drago.execute_command_read(DragoRELE96800Commands.RELE_1)) print("Rele2 : ", await drago.execute_command_read(DragoRELE96800Commands.RELE_2)) print("Rele3 : ", await drago.execute_command_read(DragoRELE96800Commands.RELE_3)) print("Rele4 : ", await drago.execute_command_read(DragoRELE96800Commands.RELE_4)) for e in drago.get_list_command_enums(): for i in e: print(f"Read {i} : ", await drago.execute_command_read(i)) asyncio.run(main()) <file_sep>/IoTHub_RemoteMethodTester/library/base_modbus.py import logging import os import time import sys import traceback import asyncio import library.utils as utils import aenum from abc import ABC, abstractmethod from enum import Enum, auto from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder from pymodbus.payload import BinaryPayloadBuilder from pymodbus.client.sync import ModbusSerialClient # logging config # logging.basicConfig(filename='log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') # self.logger.addHandler(logging.StreamHandler(sys.stdout)) # logging.basicConfig(filename='log', filemode='w', format='%(asctime)s - %(module)s - %(name)s - %(levelname)s - %(message)s') # logging.getLogger(__name__).setLevel(logging.DEBUG) # logging.getLogger("pymodbus").setLevel(logging.CRITICAL) # logging.getLogger("azure.iot").setLevel(logging.CRITICAL) # logging.getLogger("azure").setLevel(logging.CRITICAL) # self.logger.addHandler(logging.StreamHandler(sys.stdout)) class ModbusTypes(Enum): COIL = auto() BOOL1 = auto() INT8HIGH = auto() INT8LOW = auto() INT16 = auto() INT32 = auto() INT64 = auto() UINT8HIGH = auto() UINT8LOW = auto() UINT16 = auto() UINT32 = auto() UINT64 = auto() FLOAT16 = auto() FLOAT32 = auto() FLOAT64 = auto() STRING = auto() # BIT0 = auto() # num & 00000001 BIT1 = auto() # num & 00000010 BIT2 = auto() # num & 00000100 BIT3 = auto() # num & 00001000 BIT4 = auto() # num & 00010000 BIT5 = auto() # num & 00100000 BIT6 = auto() # num & 01000000 BIT7 = auto() # num & 10000000 BIT0HIGH = auto() # num & 00000001 BIT1HIGH = auto() # num & 00000010 BIT2HIGH = auto() # num & 00000100 BIT3HIGH = auto() # num & 00001000 BIT4HIGH = auto() # num & 00010000 BIT5HIGH = auto() # num & 00100000 BIT6HIGH = auto() # num & 01000000 BIT7HIGH = auto() # num & 10000000 BIT0LOW = auto() # num & 00000001 BIT1LOW = auto() # num & 00000010 BIT2LOW = auto() # num & 00000100 BIT3LOW = auto() # num & 00001000 BIT4LOW = auto() # num & 00010000 BIT5LOW = auto() # num & 00100000 BIT6LOW = auto() # num & 01000000 BIT7LOW = auto() # num & 10000000 class ModbusAccess(Enum): READ = auto() WRITE = auto() READ_WRITE = auto() class ModbusRegisterType(Enum): COIL = auto() INPUT = auto() HOLDING = auto() class BaseModbus(ABC): def __init__(self, variables_dict=None, logger=None): self.logger = logger if self.logger is None: self.logger = logging.getLogger() self.variables_dict = utils.merge_dicts_priority(variables_dict, os.environ) # os.environ if variables_dict is None else variables_dict self.client = None self.modbus_id = utils.parse_int(self.get('MODBUS_ID'), default=1) # self.modbus_port = self.get('MODBUS_PORT', '/dev/ttyUSB0') # self.modbus_stopbits = utils.parse_int(self.get('MODBUS_STOPBITS', 1), 1) # self.modbus_bytesize = utils.parse_int(self.get('MODBUS_BYTESIZE', 8), 8) # self.modbus_baudrate = utils.parse_int(self.get('MODBUS_BAUDRATE', 19200), 19200) # self.modbus_timeout = utils.parse_int(self.get('MODBUS_TIMEOUT', 1), 1) # self.modbus_method = self.get('MODBUS_METHOD', 'rtu') # self.modbus_parity = self.get('MODBUS_PARITY', 'E') def is_simulator(self): return utils.parse_bool(self.get("SIMULATOR", default=False), default=False) def is_enabled(self): return utils.parse_bool(self.get("ENABLED", default=True), default=True) def get(self, key, default=None): return utils.get(self.variables_dict, key, default=default) @abstractmethod def get_list_command_enums(self): pass @abstractmethod def get_list_command_main_enums(self): return [] @abstractmethod def get_command_from_channel(self, channel): pass async def execute_command_str(self, command_str): self.logger.info(f'execute_command_str::start') # FIRST: TRY TO RUN AS MAIN COMMAND for commands_enum in self.get_list_command_main_enums(): if command_str in [k.name for k in commands_enum]: command = commands_enum[command_str] return await self.execute_command_main(command) # SECOND: TRY TO RUN AS READ COMMAND return await self.execute_command_str_read(command_str) async def execute_command_str_read(self, command_str): self.logger.info(f'execute_command_str_read::start') for commands_enum in self.get_list_command_enums(): if command_str in [k.name for k in commands_enum]: command = commands_enum[command_str] return await self.execute_command_read(command) return None, None async def execute_command_str_write(self, command_str, value): self.logger.info(f'execute_command_str_write::start') for commands_enum in self.get_list_command_enums(): if command_str in [k.name for k in commands_enum]: command = commands_enum[command_str] return await self.execute_command_write(command, value) return None, None async def execute_command_str_main(self, command_str): self.logger.info(f'execute_command_str_main::start') for commands_enum in self.get_list_command_main_enums(): if command_str in [k.name for k in commands_enum]: command = commands_enum[command_str] return await self.execute_command_main(command) return None, None async def execute_command_read(self, command): self.logger.info(f'execute_command_read::start') if command.access == ModbusAccess.READ or command.access == ModbusAccess.READ_WRITE: register_type = self._get_register_type_from_command_(command) value = await self.read_value(command.register, command.modbus_type.name, register_type=register_type, count=command.count) return self._read_decode_(command, value), command.uom return None, None async def execute_command_write(self, command, value): self.logger.info(f'execute_command_write::start') if command.access == ModbusAccess.WRITE or command.access == ModbusAccess.READ_WRITE: return await self.write_value(command.register, command.modbus_type.name, self._write_encode_(command, value)), command.uom return None, None async def execute_command_main(self, command): self.logger.info(f'execute_command_main::start') # RUN FUNCTION AS COMMAND VALUE NAME return await getattr(self, command.value)() def _get_register_type_from_command_(self, command): if 'register_type' in vars(command): return command.register_type else: return ModbusRegisterType.HOLDING # default are HOLDING async def write_configuration(self, commands_dict): for command, value in commands_dict.items(): await self.execute_command_write(command, value) @abstractmethod def connect(self): pass def _read_decode_(self, command, value): return value def _write_encode_(self, command, value): return value async def connect_to_modbus_server(self): if not self.is_simulator(): self.logger.debug(f'connect_to_modbus_server::start') if (await utils.run_and_try_if_true_async(self.connect, 10, 0.1)): self.logger.info(f'connect_to_modbus_server::connected') else: self.logger.critical(f'connect_to_modbus_server::failed_to_connect') else: self.logger.debug(f'connect_to_modbus_server::simulator') async def close_modbus_client(self): if not self.is_simulator(): await utils.run_and_try_async(self.client.close, 3, 0.1) self.logger.info(f'close_modbus_client::disconnected') else: self.logger.debug(f'close_modbus_client::simulator::start') def read_holding_registers(self, register, count): if not self.is_simulator(): registers = self.client.read_holding_registers(register, count, unit=self.modbus_id).registers self.logger.debug(f'read_holding_registers::register::{register}::count::{count}::values::{registers}') # self.logger.debug("READ HOLDING: number: {}, Count: {}, values: {}".format(register, count, registers)) return registers else: self.logger.debug(f'read_holding_registers::simulator') def read_input_registers(self, register, count): if not self.is_simulator(): registers = self.client.read_input_registers(register, count, unit=self.modbus_id).registers self.logger.debug(f'read_input_registers::register::{register}::count::{count}::values::{registers}') # self.logger.debug("READ INPUT: number: {}, Count: {}, values: {}".format(register, count, registers)) return registers else: self.logger.debug(f'read_input_registers::simulator') def read_coils(self, register, count): if not self.is_simulator(): bits = self.client.read_coils(register, count=count, unit=self.modbus_id).bits self.logger.debug(f'read_coils::register::{register}::count::{count}::values::{bits}') # self.logger.info("READ COILS: number: {}, Count: {}, values: {}".format(register, count, bits)) # TODO return bits else: self.logger.debug(f'read_coils::simulator') async def read_registers_in_batch(self, register_start, total_count, max_batch_size=50, register_type=None): _start = register_start end = register_start + total_count registers = [] while _start < end: _count = min(max_batch_size, end - _start) if register_type == None or register_type == ModbusRegisterType.HOLDING: registers.extend(await utils.run_and_try_async(self.read_holding_registers, 3, 0.1, _start, _count)) else: # register_type == ModbusRegisterType.INPUT: registers.extend(await utils.run_and_try_async(self.read_input_registers, 3, 0.1, _start, _count)) _start = _start + _count return registers async def write_value(self, register_num, type_str, value, count=None): if not self.is_simulator(): if type_str in ModbusTypes.__members__: value_type = ModbusTypes[type_str] if value_type == ModbusTypes.COIL: self.logger.critical(f'write_value::coil::register::{register_num}::value::{value}') # self.logger.critical("WRITING values: {} to coil register number: {}".format(value, register_num)) await utils.run_and_try_async(self.client.write_coil, 3, 0.1, register_num, value, unit=self.modbus_id) else: builder = BinaryPayloadBuilder(byteorder=self._get_byteorder(), wordorder=self._get_wordorder()) if value_type == ModbusTypes.FLOAT16: builder.add_16bit_float(value) elif value_type == ModbusTypes.FLOAT32: builder.add_32bit_float(value) elif value_type == ModbusTypes.FLOAT64: builder.add_64bit_float(value) elif value_type == ModbusTypes.INT16: builder.add_16bit_int(int(round(value))) elif value_type == ModbusTypes.INT32: builder.add_32bit_int(int(round(value))) elif value_type == ModbusTypes.INT64: builder.add_64bit_int(int(round(value))) elif value_type == ModbusTypes.UINT16: builder.add_16bit_uint(int(round(value))) elif value_type == ModbusTypes.UINT32: builder.add_32bit_uint(int(round(value))) elif value_type == ModbusTypes.UINT64: builder.add_64bit_uint(int(round(value))) elif value_type == ModbusTypes.INT8HIGH: registers = await utils.run_and_try_async(self.read_holding_registers, 3, 0.1, register_num, 1) decoder = BinaryPayloadDecoder.fromRegisters(registers, byteorder=self._get_byteorder(), wordorder=self._get_wordorder()) high_value = decoder.decode_8bit_int() # DISCARD FIRST 8 BIT OF THE 16 BIT MODBUS WORD low_value = decoder.decode_8bit_int() builder.add_8bit_int(int(round(value))) # TODO ROUND INSTEAD OF FLOOR builder.add_8bit_int(low_value) elif value_type == ModbusTypes.INT8LOW: registers = await utils.run_and_try_async(self.read_holding_registers, 3, 0.1, register_num, 1) decoder = BinaryPayloadDecoder.fromRegisters(registers, byteorder=self._get_byteorder(), wordorder=self._get_wordorder()) high_value = decoder.decode_8bit_int() low_value = decoder.decode_8bit_int() # DISCARD LAST 8 BIT OF THE 16 BIT MODBUS WORD builder.add_8bit_int(high_value) builder.add_8bit_int(int(round(value))) elif value_type == ModbusTypes.UINT8HIGH: registers = await utils.run_and_try_async(self.read_holding_registers, 3, 0.1, register_num, 1) decoder = BinaryPayloadDecoder.fromRegisters(registers, byteorder=self._get_byteorder(), wordorder=self._get_wordorder()) high_value = decoder.decode_8bit_uint() # DISCARD FIRST 8 BIT OF THE 16 BIT MODBUS WORD low_value = decoder.decode_8bit_uint() builder.add_8bit_uint(int(round(value))) builder.add_8bit_uint(low_value) elif value_type == ModbusTypes.UINT8LOW: registers = await utils.run_and_try_async(self.read_holding_registers, 3, 0.1, register_num, 1) decoder = BinaryPayloadDecoder.fromRegisters(registers, byteorder=self._get_byteorder(), wordorder=self._get_wordorder()) high_value = decoder.decode_8bit_uint() low_value = decoder.decode_8bit_uint() # DISCARD LAST 8 BIT OF THE 16 BIT MODBUS WORD builder.add_8bit_uint(high_value) builder.add_8bit_uint(int(round(value))) elif type_str.startswith('BIT'): registers = await utils.run_and_try_async(self.read_holding_registers, 3, 0.1, register_num, 1) decoder = BinaryPayloadDecoder.fromRegisters(registers, byteorder=self._get_byteorder(), wordorder=self._get_wordorder()) bits_high = decoder.decode_bits() bits_low = decoder.decode_bits() bit_num = int(type_str.replace('BIT', '').replace('HIGH', '').replace('LOW', '')) if type_str.endswith("HIGH"): bits_high[bit_num] = value # override single bit of interest elif type_str.endswith("LOW"): bits_low[bit_num] = value # override single bit of interest else: # default low bits bits_low[bit_num] = value # override single bit of interest builder.add_bits(bits_high) builder.add_bits(bits_low) # self.logger.critical('-------------------------------------------------------') self.logger.critical(f'write_value::holding::register::{register_num}::value::{builder.to_registers()}') # self.logger.critical("WRITING values: {} to register number: {}".format(builder.to_registers(), register_num)) await utils.run_and_try_async(self.client.write_registers, 3, 0.1, register_num, builder.to_registers(), unit=self.modbus_id) # self.logger.critical('-------------------------------------------------------') else: self.logger.info(f'write_value::simulator') # print('SIMULATOR: skipping write_value') return None async def read_value(self, register_num, type_str, register_type=None, count=None, array_count=1): if array_count is None: array_count = 1 if not self.is_simulator(): if type_str in ModbusTypes.__members__: value_type = ModbusTypes[type_str] if type_str.startswith('BIT'): count = 1 elif count == None: if '64' in type_str: count = 4 elif '32' in type_str: count = 2 elif '16' in type_str: count = 1 elif '8' in type_str: count = 1 else: count = 1 if value_type == ModbusTypes.COIL: bits = await utils.run_and_try_async(self.read_coils, 3, 0.1, register_num, count) self.logger.debug(f'read_value::coil::{register_num}::count::{count}::values::{bits}') # self.logger.info('COIL REGISTER_NUM = {}, COUNT: {}, bits: {}'.format(register_num, count, bits)) values = bits[:count] return values[0] if count == 1 else values else: if register_type == None or register_type == ModbusRegisterType.HOLDING: registers = await utils.run_and_try_async(self.read_holding_registers, 3, 0.1, register_num, count) else: # register_type == ModbusRegisterType.INPUT: registers = await utils.run_and_try_async(self.read_input_registers, 3, 0.1, register_num, count) self.logger.info(f'read_value::register::{register_num}::count::{count}::values::{registers}') if registers == None: return None decoder = BinaryPayloadDecoder.fromRegisters(registers, byteorder=self._get_byteorder(), wordorder=self._get_wordorder()) values = [] for _ in range(array_count): if type_str.startswith('BIT'): bits_high = decoder.decode_bits() bits_low = decoder.decode_bits() bit_num = int(type_str.replace('BIT', '').replace('HIGH', '').replace('LOW', '')) self.logger.info(f'read_value::bits_high::{bits_high}::bits_low::{bits_low}::bit_num::{bit_num}') # self.logger.critical(f"bits_high: {bits_high}. bits_low: {bits_low}. bit_num: {bit_num}") if type_str.endswith("HIGH"): value = bits_high[bit_num] elif type_str.endswith("LOW"): value = bits_low[bit_num] else: # default high bits value = bits_high[bit_num] # value = int(registers[0] & (1 << bit_num) == (1 << bit_num)) # TODO TEST IF IT WORKS elif value_type == ModbusTypes.FLOAT16: value = decoder.decode_16bit_float() elif value_type == ModbusTypes.FLOAT32: value = decoder.decode_32bit_float() elif value_type == ModbusTypes.FLOAT64: value = decoder.decode_64bit_float() elif value_type == ModbusTypes.INT16: value = decoder.decode_16bit_int() elif value_type == ModbusTypes.INT32: value = decoder.decode_32bit_int() elif value_type == ModbusTypes.INT64: value = decoder.decode_64bit_int() elif value_type == ModbusTypes.UINT16: value = decoder.decode_16bit_uint() elif value_type == ModbusTypes.UINT32: value = decoder.decode_32bit_uint() elif value_type == ModbusTypes.UINT64: value = decoder.decode_64bit_uint() elif value_type == ModbusTypes.INT8HIGH: value = decoder.decode_8bit_int() elif value_type == ModbusTypes.INT8LOW: decoder.decode_8bit_int() # DISCARD FIRST 8 BIT OF THE 16 BIT MODBUS WORD value = decoder.decode_8bit_int() elif value_type == ModbusTypes.UINT8HIGH: value = decoder.decode_8bit_uint() elif value_type == ModbusTypes.UINT8LOW: decoder.decode_8bit_uint() # DISCARD FIRST 8 BIT OF THE 16 BIT MODBUS WORD value = decoder.decode_8bit_uint() else: return registers # value = registers values.append(value) return values[0] if array_count == 1 else values else: self.logger.error(f'read_value::invalid_modbus_type::{type_str}') # self.logger.error('{} is NOT a valid ModbusTypes value'.format(type_str)) return None else: self.logger.info(f'read_value::simulator') # self.logger.info('SIMULATOR: skipping read_value') return None def _get_byteorder(self): value = self.get('ENDIAN_BYTEORDER', default='Big') if value.lower() == 'little': return Endian.Little elif value.lower() == 'auto': return Endian.Auto else: return Endian.Big def _get_wordorder(self): value = self.get('ENDIAN_WORDORDER', default='Big') if value.lower() == 'little': return Endian.Little elif value.lower() == 'auto': return Endian.Auto else: return Endian.Big async def dump(self, register_start, register_end, max_count, register_type): return await self.read_registers_in_batch(register_start, register_end - register_start, max_batch_size=max_count, register_type=register_type) <file_sep>/MeasurementWriteFastAPI/start.sh #bash! sudo docker kill fastapi_edgedev_write && sudo docker rm fastapi_edgedev_write sudo docker-compose build sudo docker run --name fastapi_edgedev_write -d fastapi_edgedev_write #uvicorn main:app --reload <file_sep>/Bilancino/programma (copy)/sartorius.py # -*- coding: utf-8 -*- """ Python Interface for Sartorius Serial Interface for CPA, GCA and GPA scales. Originally by <NAME> - <EMAIL> Modified by <NAME> - <EMAIL> See LICENSE. """ import math import serial import aenum import traceback class SartoriusCommands(aenum.Enum): _init_ = 'value command' BLOCK = 110, 'O' READ_VALUE = 120, 'P' READ_UOM = 130, 'P' READ_VALUE_AND_UOM = 135, 'P' UNBLOCK = 140, 'R' RESTART = 150, 'S' TARE_ZERO = 160, 'T' TARE_ONLY = 170, 'U' ZERO = 180, 'V' CALIBRATION_EXTERNAL = 190, 'W' CALIBRATION_INTERNAL = 200, 'Z' class SartoriusError(aenum.IntEnum): OK = 0 ERROR_SERIAL = 1 ERROR_PARSE = 2 ERROR_EMPTY = 3 class SartoriusResponseType(aenum.Enum): _init_ = 'value start16 count16 start22 count22' STRING = 0, 0, 16, 0, 22 FLOAT = 1, 0, 11, 6, 11 INT = 2, 0, 11, 6, 11 UOM = 3, 11, 3, 17, 3 FLOAT_AND_UOM = 4, 0, 14, 6, 14 INT_AND_UOM = 5, 0, 14, 6, 14 class SartoriusResponseMode(aenum.IntEnum): RESPONSE_16 = 16 RESPONSE_22 = 22 RESPONSE_AUTO = 30 class Sartorius(): def __init__(self, port='/dev/ttyUSB0'): """ Initialise Sartorius device. Example: scale = Sartorius('COM1') """ self.port = port self.response_mode = SartoriusResponseMode.RESPONSE_AUTO self.ser = None def connect_to_sartorius(self, port=None, retry=5, timeout=0.5): iteration = 0 while iteration < retry: try: self.ser = serial.Serial(port if port is not None else self.port) self.ser.baudrate = 19200 self.ser.bytesize = serial.SEVENBITS self.ser.parity = serial.PARITY_ODD self.ser.stopbits = serial.STOPBITS_ONE # INDICA HENDSHAKE SOFTWARE E NON HARDWARE self.ser.xonxoff = True self.ser.timeout = timeout return True except: iteration = iteration + 1 return False def comm(self, command, read=False, response_type=None): try: # ESC + LETTER + \r + \n bin_comm = chr(27) + command + chr(13) + chr(10) bin_comm = bin_comm.encode('ascii') self.ser.write(bin_comm) if read: try: response = self.ser.readline() response = response.decode('ascii') if len(response) == 0: return SartoriusError.ERROR_EMPTY, None return SartoriusError.OK, self.__parse_response(response, response_type) except: print(traceback.format_exc()) return SartoriusError.ERROR_PARSE, None return SartoriusError.OK, None except: print(traceback.format_exc()) return SartoriusError.ERROR_SERIAL, None def __extract_sub_response(self, response, response_type): if self.response_mode == SartoriusResponseMode.RESPONSE_AUTO: mode = SartoriusResponseMode.RESPONSE_16 if len(response) == 16 else SartoriusResponseMode.RESPONSE_22 else: mode = self.response_mode if mode == SartoriusResponseMode.RESPONSE_16: return response[response_type.start16: response_type.start16 + response_type.count16] else: # if mode == SartoriusResponseMode.RESPONSE_22: return response[response_type.start22: response_type.start22 + response_type.count22] def __parse_response(self, response, response_type): sub_response = self.__extract_sub_response(response, response_type) if response_type == SartoriusResponseType.INT: sub_response = sub_response.replace(' ', '') return int(sub_response) elif response_type == SartoriusResponseType.FLOAT: sub_response = sub_response.replace(' ', '') return float(sub_response) elif response_type == SartoriusResponseType.INT_AND_UOM: sub_response_int = self.__extract_sub_response(response, SartoriusResponseType.INT) sub_response_uom = self.__extract_sub_response(response, SartoriusResponseType.UOM) sub_response_int = sub_response_int.replace(' ', '') sub_response_uom = sub_response_uom.replace(' ', '') return int(sub_response_int), sub_response_uom elif response_type == SartoriusResponseType.FLOAT_AND_UOM: sub_response_float = self.__extract_sub_response(response, SartoriusResponseType.FLOAT) sub_response_uom = self.__extract_sub_response(response, SartoriusResponseType.UOM) sub_response_float = sub_response_float.replace(' ', '') sub_response_uom = sub_response_uom.replace(' ', '') return float(sub_response_float), sub_response_uom elif response_type == SartoriusResponseType.UOM: sub_response = sub_response.replace(' ', '') return sub_response else: return sub_response def readValue(self): return self.comm(SartoriusCommands.READ_VALUE.command, read=True, response_type=SartoriusResponseType.FLOAT) def readUom(self): return self.comm(SartoriusCommands.READ_UOM.command, read=True, response_type=SartoriusResponseType.UOM) def readValueAndUom(self): return self.comm(SartoriusCommands.READ_VALUE_AND_UOM.command, read=True, response_type=SartoriusResponseType.FLOAT_AND_UOM) def tareZero(self): return self.comm(SartoriusCommands.TARE_ZERO.command) def tare(self): return self.comm(SartoriusCommands.TARE_ONLY.command) def block(self): return self.comm(SartoriusCommands.BLOCK.command) def unblock(self): return self.comm(SartoriusCommands.UNBLOCK.command) def restart(self): return self.comm(SartoriusCommands.RESTART.command) def zero(self): return self.comm(SartoriusCommands.ZERO.command) def calibrationExternal(self): return self.comm(SartoriusCommands.CALIBRATION_EXTERNAL.command) def calibrationInternal(self): return self.comm(SartoriusCommands.CALIBRATION_INTERNAL.command) # def value(self): # """ # Return displayed scale value. # """ # try: # if self.inWaiting() == 0: ##print("Sending: '{}' = '{}'".format('\x1bP\r\n', bytes('\x1bP\r\n', 'ascii').hex())) ##print("Sending: '{}'".format(bytes('\x1bP\r\n', 'ascii').hex())) # self.write('\x1bP\r\n'.encode("ascii")) # answer = self.readline() ##print("Receiving: '{}' = '{}'".format(answer.decode('ascii').replace('\r\n', ''), answer.hex())) # answer = answer.decode("ascii") ##print("str: '{}'".format(answer)) ##print(answer) # if len(answer) == 16: # menu code 7.2.1 # answer = float(answer[0:11].replace(' ', '')) # else: # menu code 7.2.2 # answer = float(answer[6:17].replace(' ','')) # return answer # except: # return math.nan # def display_unit(self): # """ # Return unit. # """ # self.write('\x1bP\r\n'.encode("ascii")) # answer = self.readline() # try: # answer = answer[11].strip() # except: # answer = "" # return answer # def tare(self): # """ # (TARE) Key. # """ # self.write('\x1bT\r\n'.encode("ascii")) # def block(self): # """ # Block keys. # """ # self.write('\x1bO\r\n'.encode("ascii")) # def unblock(self): # """ # Unblock Keys. # """ # self.write('x1bR\r\n'.encode("ascii")) # def restart(self): # """ # Restart/self-test. # """ # self.write('x1bS\r\n'.encode("ascii")) # def ical(self): # """ # Internal calibration/adjustment. # """ # self.write('x1bZ\r\n'.encode("ascii")) if __name__ == '__main__': import time import datetime import matplotlib.pyplot as plt s = Sartorius('/dev/ttyUSB0') s.connect_to_sartorius() print('------------------------------------') print('s.readValue()') print(s.readValue()) input("Press to continue.") for i in range(100): print('------------------------------------') print('s.readValueAndUom()') print(s.readValueAndUom()) input("Press to continue.") print('------------------------------------') print('s.tareZero()') print(s.tareZero()) input("Press to continue.") print('------------------------------------') print('s.tare()') print(s.tare()) input("Press to continue.") print('s.block()') print(s.block()) input("Press to continue.") print('s.unblock()') print(s.unblock()) input("Press to continue.") print('s.restart()') print(s.restart()) input("Press to continue.") print('s.zero()') print(s.zero()) input("Press to continue.") print('s.calibrationInternal()') print(s.calibrationInternal()) input("Press to continue.") print('s.calibrationExternal()') print(s.calibrationExternal()) exit() while True: v = [] starttime = time.time() for i in range(200): value = s.value() if not math.isnan(value): v.append(value) print('Time: {}. Lettura bilancia: {} g.'.format(datetime.datetime.now(), value)) # time.sleep(0.01) else: raise Exception() endtime = time.time() print('Total time: {} s. Single time: {} s'.format(endtime - starttime, (endtime - starttime) / 200)) plt.plot(v, '-o') plt.show() # print(s.display_unit()) <file_sep>/ModBus_PLC2PLC/ModBus_PLC2PLC_v_0.0.1/setup.sh #bash! sudo docker kill modbus_plc2plc_writer sudo docker rm modbus_plc2plc_writer # avvio della vpn #sudo openvpn --config "./../vpn_clients/[email protected]" --daemon sudo docker-compose build sudo docker run --name modbus_plc2plc_writer -d modbus_plc2plc_writer <file_sep>/Modbus2DBs/Microturbine_RTU_2_Influx/testing_ok/plc_reader (copy)/main.py import json import os import logging import sys from rtu_module_class import RtuModuleClass from influxdb_module_class import InfluxDBModuleClass from modbus_looper import ModbusLooper import library.utils as utils ###################################################################################################################### # Parametri di configurazione rtu_config_file = './config/rtu_modbus.config' db_config_file = './config/db.config' ###################################################################################################################### # Initializzazione del logger # def init_logging(logger, filename, level=logging.INFO, stdout=True, maxBytes=10000, backupCount=5): logging.getLogger().setLevel(logging.NOTSET) logging.getLogger().handlers = [] rotatingHandler = logging.handlers.RotatingFileHandler(filename=filename, maxBytes=maxBytes, backupCount=backupCount) rotatingHandler.setLevel(logging.DEBUG) rotatingHandler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) logging.getLogger().addHandler(rotatingHandler) logging.getLogger(__name__).setLevel(level) logging.getLogger("pymodbus").setLevel(logging.DEBUG) if stdout: logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) logger = logging.getLogger(__name__) logger.info('init_logging::end') ###################################################################################################################### def connect_device(logger, rtu_config_file): plc_modbus_client = RtuModuleClass(logger, rtu_config_file) conn_res = plc_modbus_client.connect_device() return plc_modbus_client if conn_res else None ###################################################################################################################### def parseJsonConfig(file_full_path): #pwd = os.getcwd() if (os.path.isfile(file_full_path)): with open(file_full_path,"r") as f: return json.load(f) return None ###################################################################################################################### ### MAIN if __name__ == "__main__": logger = logging log_filename = 'test.log' init_logging(logger, log_filename) logger.info("::START::") logger.info("------------------------------------------------------") meas_ok:bool=True # Parsing delle variabili da file di configurazione. rtu_dictinoary = parseJsonConfig(rtu_config_file) db_dictionary = parseJsonConfig(db_config_file) # Connessione al RTU tramite Modbus rtu_modbus_client = connect_device(logger, rtu_dictinoary) # Connessione al DB InfluxDB influxdb_client = InfluxDBModuleClass(logger, utils.get(db_dictionary,'INFLUXDB')) if rtu_modbus_client is not None: logger.info("::RTU CONNECTED::") # Avvio lettura in loop delle variabili logger.info("::START CONTROLLING RTU::") # test looper test_looper = ModbusLooper(rtu_modbus_client, influxdb_client) # avvio loop test_looper.start_testing() logger.info("::STOP::") logger.info("------------------------------------------------------") <file_sep>/Modbus2DBs/Microturbine_RTU_2_Influx/testing_ok/plc_reader/rtu_module_class.py import datetime from library.rtu_modbus import RtuModbus, ModbusRegisterType import library.utils as utils from enum import Enum, auto from datetime import datetime class ModbusVariableTags(Enum): REGISTER_NUMBER = auto() VALUE_TYPE = auto() VALUE = auto() TIME = auto() R_SAMPLING_TIME_MS = auto() MEASUREMENTS = auto() REGISTER_TYPE = auto() class RtuModuleClass(): MACHINE_TYPE = "RTU" async_cmd_list=[] def __init__(self, logger, modbus_config_dict): self.modbus_port = utils.get(modbus_config_dict,'MODBUS_PORT', '/dev/ttyUSB0') self.modbus_stopbits = utils.get(modbus_config_dict,'MODBUS_STOPBITS', 1) self.modbus_bytesize = utils.get(modbus_config_dict,'MODBUS_BYTESIZE', 8) self.modbus_baudrate = utils.get(modbus_config_dict,'MODBUS_BAUDRATE', 19200) self.modbus_timeout = utils.get(modbus_config_dict,'MODBUS_TIMEOUT', 1) self.modbus_method = utils.get(modbus_config_dict,'MODBUS_METHOD', 'rtu') self.modbus_parity = utils.get(modbus_config_dict,'MODBUS_PARITY', 'N') self.max_attempts=utils.get(modbus_config_dict,'MAX_ATTEMPTS', 3) self.measurement_list_dict = utils.get(modbus_config_dict,'MODBUS_MEASUREMENTS') self.logger = logger self.device_instance = RtuModbus(self.logger, self.modbus_port, self.modbus_stopbits, self.modbus_bytesize, self.modbus_baudrate, self.modbus_timeout, self.modbus_method, self.modbus_parity, variables_dict=modbus_config_dict) def get_meas_info_from_name(self, meas_name)->dict: for m in self.measurement_list_dict: if list(m.keys())[0] == meas_name: return list(m.values())[0] return None ############################################################################################# ### INIZIALIZZAZIONE e Shut down def connect_device(self): return self.device_instance.connect() def disconnect_device(self): return self.device_instance.disconnect() ############################################################################################# ### LETTURA variabili async def read_var_async(self, meas_dict): result = None try: # acquisizione della chiave key=list(meas_dict.keys())[0] # acquisizione dei parametri vals=list(meas_dict.values())[0] register_number=utils.get(vals, ModbusVariableTags.REGISTER_NUMBER.name) register_type_name = utils.get(vals, ModbusVariableTags.REGISTER_TYPE.name) register_type = ModbusRegisterType[register_type_name] if register_type_name in [r.name for r in ModbusRegisterType] else None value_type= utils.get(vals, ModbusVariableTags.VALUE_TYPE.name) self.logger.debug(f'reading::{key}::{register_number}::value type::{value_type}') result = await self.device_instance.read_value(register_number, value_type, register_type=register_type, count=None, array_count=1) #aggiunta del valore vals[ModbusVariableTags.VALUE.name]=result vals[ModbusVariableTags.TIME.name]=datetime.utcnow().isoformat() except Exception as e: self.logger.critical(f'error::{e}') return result <file_sep>/MeasurementWriteFastAPI/requirements.txt pymodbus asyncio datetime six pyparsing pandas fastapi uvicorn[standard] <file_sep>/Modbus2DBs/PLC_Schneider_Modbus_2_Influx/plc_reader/library/plc_modbus.py import logging import os import time import sys import traceback import asyncio from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder from pymodbus.payload import BinaryPayloadBuilder from pymodbus.client.sync import ModbusTcpClient import library.utils as utils from library.base_modbus import BaseModbus, ModbusTypes, ModbusAccess, ModbusRegisterType from library.measurement import Measurement, ModbusMeasurement import aenum from enum import Enum, auto # class IngridModbusCommands(aenum.Enum): # _init_ = 'value register register_type modbus_type access uom count' # COMMAND = auto(), 0, ModbusRegisterType.HOLDING, ModbusTypes.INT16, ModbusAccess.WRITE, 'status', None # HOLDING class PlcModbus(BaseModbus): def __init__(self, logger, variables_dict=None, ip='192.168.0.1', port =502): super().__init__(variables_dict=variables_dict, logger=logger) self.ip = ip self.port = port def connect(self): self.client = ModbusTcpClient(self.ip, self.port, id = self.modbus_id) return self.client.connect() def disconnect(self): return self.client.close() <file_sep>/MeasurementWriteFastAPI/README.md SA.SA. PROVA.PROVA. <file_sep>/ModBusTCPDeviceTester/v_0.1/main.py import json from library.base_modbus import ModbusRegisterType import os import logging from logging import handlers import sys from library.device_modbus import TcpModbus import library.utils as utils import asyncio import datetime ###################################################################################################################### ### MAIN def init_logging(logger, filename, level=logging.INFO, stdout=True, maxBytes=10000, backupCount=5): logging.getLogger().setLevel(logging.NOTSET) logging.getLogger().handlers = [] rotatingHandler = logging.handlers.RotatingFileHandler(filename=filename, maxBytes=maxBytes, backupCount=backupCount) rotatingHandler.setLevel(logging.DEBUG) rotatingHandler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) logging.getLogger().addHandler(rotatingHandler) logging.getLogger(__name__).setLevel(level) logging.getLogger("pymodbus").setLevel(logging.DEBUG) if stdout: logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) logger = logging.getLogger(__name__) logger.info('init_logging::end') ###################################################################################################################### # Parametri di configurazione modbus_ip = '192.168.103.158' modbus_id = 1 modbus_port = 510 modbus_byteorder = 'Big' modbus_wordorder = 'Big' ###################################################################################################################### # MAIN async def main(): # Logging logger = logging init_logging(logger, 'test.log') # Connessione al RTU tramite Modbus rtu_modbus_client = TcpModbus( logger, modbus_ip, modbus_port, modbus_id, modbus_byteorder, modbus_wordorder) if rtu_modbus_client.connect() == True: # Lettura dei valori try: register_num = 50 type_str = 'INT16' array_count = 1 register_type = ModbusRegisterType.HOLDING value = 100 enable_write:bool = True read_result = await rtu_modbus_client.read_value(register_num, type_str, register_type=register_type, array_count=array_count) print(read_result) # Scrittura dei valori if enable_write == True: write_result = await rtu_modbus_client.write_value(register_num, type_str, value) print(write_result) read_result = await rtu_modbus_client.read_value(register_num, type_str, array_count=array_count, register_type=register_type) print(read_result) except Exception as e: print(e) rtu_modbus_client.disconnect() logger.info("::STOP::") logger.info("------------------------------------------------------") ############################# Avvio TEST if __name__ == "__main__": asyncio.run(main()) <file_sep>/IoTHub_RemoteMethodTester/main.py from remote_methods_tester import RemoteMethodsTester if __name__ == "__main__": RemoteMethodsTester().run()<file_sep>/ModBus_PLC2AzureDirectMethod/ModBus_PLC2AzureDirectMethod_v_0.0.1/dm_writer.py import library.utils as utils import library.remote_methods_caller as rmc class DM_Wrter(): def __init__(self, logger, configs_dict): self.logger = logger self.retry_count = utils.get(configs_dict,'RETRY_COUNT', 3) self.name = utils.get(configs_dict,'NAME', "plc_test") self.priority = utils.get(configs_dict,'PRIORITY', 1) self.measurement_list_dict = utils.get(configs_dict,'MEASUREMENTS') self.measurement_names = [list(value.keys())[0] for value in self.measurement_list_dict] def get_meas_info_from_name(self, meas_name)->dict: for m in self.measurement_list_dict: if list(m.keys())[0] == meas_name: return list(m.values())[0] return None async def write_var_async(self, meas_dict, value): result = None try: # acquisizione della chiave key=list(meas_dict.keys())[0] # acquisizione dei parametri vals=list(meas_dict.values())[0] # scrittura della variabile deviceID=utils.get(vals, 'DEVICE_ID') moduleID=utils.get(vals, 'MODULE_ID') methodName=utils.get(vals, 'METHOD_NAME') payload={key:{"VALUE": value}} done, message, code = rmc.call_direct_method(deviceID, moduleID, methodName, payload) self.logger.debug(f'write::{key}::deviceId{deviceID}::moduleId::{moduleID}::methodName::{methodName}::payload::{payload}') self.logger.debug(f'done::{done}::message::{message}::code{code}') except Exception as e: self.logger.critical(f'error::{e}') return result<file_sep>/Modbus2DBs/PlcSimulationEnv_DB/prepare-install.sh #!/bin/bash folder=./ # Abilitazione SSH sudo apt update sudo apt install openssh-server # install docker-compose sudo curl -L "https://github.com/docker/compose/releases/download/1.28.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose # install Command-line completion sudo curl -L "https://raw.githubusercontent.com/docker/compose/1.28.4/contrib/completion/bash/docker-compose" -o /etc/bash_completion.d/docker-compose <file_sep>/CSV_TimeSeriesComparison/timeSeriesCompare.py import pandas as pd import numpy as np import matplotlib.pyplot as plt import pylab import itertools import datetime from datetime import datetime import math import os.path import os from pathlib import Path import shutil import random def resampleCsv(dataDir:str, ts:str = '50ms', timeColumn:str = 'Time', dateFormat:str ='%Y-%m-%d %H:%M:%S', mtd:str='linear', interpolation:str = 'mean', ignoreTime:bool=True) -> pd.DataFrame : if (dataDir == None): return None if not(os.path.isfile(dataDir)): return None #Import dati portata alle Remi timeValueData: pd.DataFrame = pd.read_csv(dataDir) timeValueData[timeColumn]=pd.to_datetime(timeValueData[timeColumn], format = dateFormat) if(interpolation == 'mean'): timeValueData= timeValueData.resample(ts, on = timeColumn).mean() elif(interpolation == 'sum'): timeValueData= timeValueData.resample(ts, on = timeColumn).sum() elif(interpolation == 'pad'): timeValueData= timeValueData.resample(ts, on = timeColumn).pad() else: return None timeValueData = timeValueData.interpolate(method = mtd) if (ignoreTime): return pd.DataFrame(data=timeValueData.values) return timeValueData def getAllCsv(dir:str=None): farr=[] # acquisizione della directory della cartella di lavoro if not(dir) : cwd = os.getcwd() #os.listdir('.') else: cwd = dir # acquisizione dell'elenco dei file csv presenti nella directory. files = [f for f in os.listdir('.') if (os.path.isfile(f))] for f in files: if(f.lower().endswith('.csv')): farr.append(f) return farr def outReport(data, outputDir) -> None: if not len(data) > 0 : return result:pd.DataFrame = pd.concat(data, axis=1) result.to_csv(outputDir) def moveDataCsv2History(farr, historyDir) -> None: Path(historyDir).mkdir(parents=True, exist_ok=True) for f in farr: shutil.move(f, historyDir+'/'+f) if __name__ == "__main__": #dataColumn='MASSFLOW', mtd='linear', interpolation='mean') ylabel = 'Portata [sm^3/h]' title = 'Confronto dati Portata' ts = '900s' timeColumn = 'Time' valueColumn = 'MASSFLOW' dateFormat:str ='%Y-%m-%d %H:%M:%S' interp_method = 'linear' interpolation = 'mean' ignoreTime:bool = True colors = ["blue", "black", "red", "red"] linestyles = ['-','-.','--',':', ] now_str = datetime.now().strftime("%d_%m_%Y_%H_%M_%S") outputDir:str = './Result/out'+now_str+'.csv' historyDir:str = './History/inputs'+title+'_'+now_str arrFiles=[] data=[] arrFiles = getAllCsv() arrFiles.sort() fig, ax = plt.subplots() for f in arrFiles: res = resampleCsv(f,ts, timeColumn, dateFormat, interp_method, interpolation, ignoreTime) data.append(res) ax.plot(res.values, color=random.choice(colors), linestyle=random.choice(linestyles), label = f) # Spostamento dei file nelle rispettive directory al termine delle operazioni. outReport(data, outputDir) moveDataCsv2History(arrFiles, historyDir) plt.ylabel(ylabel) plt.title(title) plt.legend() plt.show() <file_sep>/CurveFitting/main_ts_ingrid_curve_fit.py import pandas as pd import numpy as np import matplotlib.pyplot as plt import pylab import itertools import datetime from datetime import datetime import math import os, os.path from pathlib import Path import shutil from scipy.signal import butter, lfilter, freqz, lfilter_zi, filtfilt from sklearn.linear_model import LinearRegression from sklearn.metrics import r2_score from aenum import Enum, auto import json def resample_all_tests(tsts, time_colum:str, ts:str, label:str='right', closed:str = 'right', origin:str='epoch'): if origin == 'epoch': for tst in tsts: for d in tst['DATA']: d['DATA'].index = pd.to_datetime(d['DATA'][time_column], unit='s') df = d['DATA'] d['DATA'] = df.resample(ts, label=closed, closed=closed).pad() return tsts def get_all_tests(dir: str): ''' Acquisizione di tutti i dati in formato df ''' tests = [] for root, dirs, files in os.walk(data_dir, topdown=False): tests.append({ 'NAME': os.path.basename(root), 'DATA':[{'NAME': root + '/' + f, 'DATA': pd.read_csv(root + '/' + f)} for f in files] }) return tests def add_sqrt_column(df:pd.DataFrame, column_name: str): df[column_name+' sqrt']=np.sqrt(df[column_name]) def add_sqrt_column_to_all_tests(tests, column_name: str)-> str: for t in tests: for d in t['DATA']: add_sqrt_column(d['DATA'], column_name) return like_in_list(tests[0]['DATA'][0]['DATA'].columns, [column_name, 'sqrt'])[0] def like_in_list(ref:list, checks:list): return [r for r in ref if all(c.lower() in r.lower() for c in checks)] def add_col_variation_by_col_ref(df: pd.DataFrame, col_variation: str, col_ref: str = 'time', delta = -1): return df[col_variation].diff() def filter_by_std(df: pd.DataFrame, column:str, coeff=1)-> pd.DataFrame: descr = df[column].describe() return df.loc[ (df[column] >= (descr['mean'] - descr['std']*coeff)) & (df[column] <= (descr['mean'] + descr['std']*coeff)) ] if __name__ == "__main__": data_dir='data/input/' sampling_time = '2000ms' # Acquisizione di tutti i dati tsts = get_all_tests(data_dir) # Lettura dei nomi delle colonne col_names =tsts[0]['DATA'][0]['DATA'].columns press_column = like_in_list(col_names, ['press'])[0] mass_column = like_in_list(col_names, ['mass'])[0] n_inj_column = like_in_list(col_names, ['inject'])[0] time_column = like_in_list(col_names, ['time'])[0] # Resampling tsts = resample_all_tests(tsts, time_column, sampling_time) # Introduzione del quadrato della pressione e acquisizione del nome della colonna sqrt_press_column = add_sqrt_column_to_all_tests(tsts, press_column) # DataFrame di riferimento d_test:pd.DataFrame = tsts[0]['DATA'][0]['DATA'] # mass ratio d_test[mass_column + ' fst_der'] = d_test[mass_column] / (d_test[n_inj_column] +1 - d_test[n_inj_column].min()) d_test[mass_column + ' diff'] = add_col_variation_by_col_ref(d_test, mass_column) # riacquisizione nome mass_fst_der_column = like_in_list(d_test.columns, ['mass', 'fst_der'])[0] # test ratio filtered d_test_filtered = filter_by_std(d_test, mass_fst_der_column, 3) # Regressione lineare length = len(d_test_filtered[sqrt_press_column].values) x = d_test_filtered[sqrt_press_column].values.reshape(length, 1) y = d_test_filtered[mass_fst_der_column].values.reshape(length, 1) reg = LinearRegression().fit(x, y) # PLOT DATA plt.subplot(2,1,1) plt.title("DELTA_MASS / time") plt.plot(d_test.index, d_test[mass_fst_der_column ]) plt.grid() plt.subplot(2,1,2) plt.title("DELTA MASS / SQRT(PRESSURE)") plt.plot(d_test_filtered[sqrt_press_column], d_test_filtered[mass_fst_der_column]) plt.plot(x, reg.predict(x)) plt.grid() plt.show() print('FINE') #plt.plot(df_data) #plt.show()<file_sep>/Modbus2DBs/Bilancia_Serial_2_Influx/library/utils.py import time import os import sys import asyncio from six.moves import input from datetime import datetime, timedelta import json import threading import logging import traceback import hashlib import subprocess import csv import re from azure.iot.device.aio import IoTHubModuleClient from azure.iot.device import MethodResponse, Message ####################################################################### async def base_listener_directmethod(iothub_client, method_name, method, output_topic='output1', logger=None): if logger is None: logging = logging.getLogger() logger.info(f'base_listener_directmethod::start::{method_name}') while True: try: method_request = await iothub_client.receive_method_request(method_name) logger.info(f'base_listener_directmethod::{method_name}::{method_request.payload}::called') # logging.getLogger().info(f'{method_name}. Payload: {method_request.payload}') try: status, result = await method(method_request.payload) except Exception as e: logger.error(f'base_listener_directmethod::{method_name}::{method_request.payload}::error') logger.debug(f'base_listener_directmethod::{method_name}::error::{traceback.format_exc()}') from library.base_iothub_client import IobHubRemoteMethodStatus status, result = IobHubRemoteMethodStatus.STATUS_ERROR, traceback.format_exc() method_response = MethodResponse.create_from_method_request(method_request, status=status.value, payload=json.dumps(result)) if result is not None and output_topic is not None: message_response = Message(json.dumps(result)) logger.info(f'base_listener_directmethod::{method_name}::send_message_to_output::{vars(message_response)}') await iothub_client.send_message_to_output(message_response, output_topic) logger.info(f'base_listener_directmethod::{method_name}::method_response::{vars(method_response)}') await iothub_client.send_method_response(method_response) except Exception as e: logger.error(f'base_listener_directmethod::{method_name}::error') logger.debug(f'base_listener_directmethod::{method_name}::error::{traceback.format_exc()}') async def base_listener_message_on_input(iothub_client, input_topic, method, output_topic='output1', logger=None): if logger is None: logging = logging.getLogger() logger.info(f'base_listener_message::start::{input_topic}') while True: try: input_message = await iothub_client.receive_message_on_input(input_topic) logger.info(f'base_listener_message_on_input::{input_topic}::{input_message}::called') try: status, result = await method(input_message.data) except Exception as e: logger.error(f'base_listener_message_on_input::{input_topic}::{input_message.data}::error') logger.debug(f'base_listener_message_on_input::{input_topic}::error::{traceback.format_exc()}') from library.base_iothub_client import IobHubRemoteMethodStatus status, result = IobHubRemoteMethodStatus.STATUS_ERROR, traceback.format_exc() if isinstance(result, dict): result['status'] = status.value dict_response = result else: dict_response = {"status": status.value, 'data': result} message_response = Message(json.dumps(dict_response)) await iothub_client.send_message_to_output(message_response, output_topic) except Exception as e: logger.error(f'base_listener_message_on_input::{input_topic}::error') logger.debug(f'base_listener_message_on_input::{input_topic}::error::{traceback.format_exc()}') async def base_listener_message(iothub_client, input_topic, method, logger=None): if logger is None: logging = logging.getLogger() logger.info(f'base_listener_message::start::{input_topic}') while True: try: input_message = await iothub_client.receive_message() logger.info(f'base_listener_message::{input_topic}::{input_message}::called') try: status, result = await method(input_message.data) except Exception as e: logger.error(f'base_listener_message::{input_topic}::{input_message.data}::error') logger.debug(f'base_listener_message::{input_topic}::error::{traceback.format_exc()}') from library.base_iothub_client import IobHubRemoteMethodStatus status, result = IobHubRemoteMethodStatus.STATUS_ERROR, traceback.format_exc() if isinstance(result, dict): result['status'] = status.value dict_response = result else: dict_response = {"status": status.value, 'data': result} message_response = Message(json.dumps(dict_response)) await iothub_client.send_message(message_response) except Exception as e: logger.error(f'base_listener_message::{input_topic}::error') logger.debug(f'base_listener_message::{input_topic}::error::{traceback.format_exc()}') async def twin_properties_listener(iothub_client, method, logger=None): if logger is None: logging = logging.getLogger() logger.info(f'twin_properties_listener::start::{method}') while True: try: patch = await iothub_client.receive_twin_desired_properties_patch() logger.info(f'twin_properties_listener::{patch}::called') try: status, result = await method(patch) except Exception as e: logger.error(f'twin_properties_listener::{patch}::error') logger.debug(f'twin_properties_listener::error::{traceback.format_exc()}') from library.base_iothub_client import IobHubRemoteMethodStatus status, result = IobHubRemoteMethodStatus.STATUS_ERROR, traceback.format_exc() if isinstance(result, dict): result['status'] = status.value dict_response = result else: dict_response = {"status": status.value, 'data': result} message_response = Message(json.dumps(dict_response)) await iothub_client.send_message(message_response) except Exception as e: logger.error(f'twin_properties_listener::error') logger.debug(f'twin_properties_listener::error::{traceback.format_exc()}') ####################################################################### def parse_json(payload): try: return json.loads(payload) except: return None def parse_int(string, default=0): try: return int(string) except: return default def parse_float(string, default=0.): try: return float(string) except: return default def parse_bool(string, default=False): if string is None: return default try: return str(string).lower() in ['true', 't', 'on', '1'] except: return default def parse_list(obj, default=[]): if obj is None: return default try: if isinstance(obj, list): return obj if ',' in obj: return obj.split(',') else: return obj.split() except: return default def parse_reading_env(string, fields=[]): try: dictionary = json.loads(string) key = list(dictionary.keys())[0] if all(field in dictionary[key] for field in fields): # if "register" in dictionary[key] and "type" in dictionary[key] and "uom" in dictionary[key]: # return dictionary["register"], dictionary["type"], dictionary["uom"] # print(string, dictionary) return key, dictionary[key] return None, None except: return None, None def parse_reading_envs_dict(fields=[]): dictionary = {} for env in os.environ: if env.startswith('READING_VALUES_'): key, value = parse_reading_env(os.getenv(env), fields=fields) dictionary[key] = value return dictionary # [parse_reading_env(os.getenv(env)) for env in os.environ if env.startswith('READING_VALUES_')] ############################################################# def get_measurement_list_from_dict(machine_type, dictionary, parameters_keys=None, logger=None): logger = logging.getLogger() if logger is None else logger import library.measurement measurement_list = [] prefix_classes_dict = {} prefix_classes_dict['MEASUREMENT_'] = library.measurement.Measurement # prefix_classes_dict['ADAM_MEASUREMENT_'] = library.measurement.AdamMeasurement prefix_classes_dict['MODBUS_MEASUREMENT_'] = library.measurement.ModbusMeasurement prefix_classes_dict['QUERY_MEASUREMENT_'] = library.measurement.QueryMeasurement prefix_classes_dict['FUNCTION_MEASUREMENT_'] = library.measurement.FunctionMeasurement for key in sorted(dictionary): # sorted(dictionary) returns a list of keys sorted alphabetically for p in prefix_classes_dict: if key.startswith(p): try: # dictionary[key] is a dictionary in string measurement_dict = json.loads(dictionary[key]) sensor_type = list(measurement_dict.keys())[0] measurement = prefix_classes_dict[p](machine_type, sensor_type, measurement_dict[sensor_type], dictionary, parameters_keys=parameters_keys) measurement_list.append(measurement) except Exception as e: logger.critical(F'EXCLUDING MEASUREMENT: {dictionary[key]}') logger.debug(e, exc_info=True) return measurement_list ############################################################# # RETROCOMPATIBILITÀ ############################################################# def get_all_measurement_list(machine_type, dictionary, parameters_keys=None): measurement_list = get_measurement_list(machine_type, dictionary, parameters_keys=parameters_keys) modbus_measurement_list = get_modbus_measurement_list(machine_type, dictionary, parameters_keys=parameters_keys) function_measurement_list = get_function_measurement_list(machine_type, dictionary, parameters_keys=parameters_keys) # adam_measurement_list = get_adam_measurement_list(machine_type, dictionary, parameters_keys=parameters_keys) return measurement_list + modbus_measurement_list + function_measurement_list # + adam_measurement_list def get_measurement_list(machine_type, dictionary, prefix='MEASUREMENT_', parameters_keys=None): import library.measurement measurement_list = [] for key in sorted(dictionary): # sorted(dictionary) returns a list of keys sorted alphabetically if key.startswith(prefix): try: # dictionary[key] is a dictionary in string measurement_dict = json.loads(dictionary[key]) sensor_type = list(measurement_dict.keys())[0] m = library.measurement.Measurement(machine_type, sensor_type, measurement_dict[sensor_type], dictionary, parameters_keys=parameters_keys) measurement_list.append(m) except Exception as e: logging.critical(F'EXCLUDING MEASUREMENT: {dictionary[key]}') logging.getLogger().debug(e, exc_info=True) pass return measurement_list def get_modbus_measurement_list(machine_type, dictionary, prefix='MODBUS_MEASUREMENT_', parameters_keys=None): import library.measurement measurement_list = [] for key in sorted(dictionary): # sorted(dictionary) returns a list of keys sorted alphabetically if key.startswith(prefix): try: # dictionary[key] is a dictionary in string measurement_dict = json.loads(dictionary[key]) sensor_type = list(measurement_dict.keys())[0] measurement = library.measurement.ModbusMeasurement(machine_type, sensor_type, measurement_dict[sensor_type], dictionary, parameters_keys=parameters_keys) measurement_list.append(measurement) except Exception as e: logging.critical(F'EXCLUDING MEASUREMENT: {dictionary[key]}') logging.getLogger().debug(e, exc_info=True) return measurement_list def get_function_measurement_list(machine_type, dictionary, prefix='FUNCTION_MEASUREMENT_', parameters_keys=None): import library.measurement measurement_list = [] for key in sorted(dictionary): # sorted(dictionary) returns a list of keys sorted alphabetically if key.startswith(prefix): try: # dictionary[key] is a dictionary in string measurement_dict = json.loads(dictionary[key]) sensor_type = list(measurement_dict.keys())[0] measurement = library.measurement.FunctionMeasurement(machine_type, sensor_type, measurement_dict[sensor_type], dictionary, parameters_keys=parameters_keys) measurement_list.append(measurement) except Exception as e: logging.critical(F'EXCLUDING MEASUREMENT: {dictionary[key]}') logging.getLogger().debug(e, exc_info=True) return measurement_list def get_adam_measurement_list(machine_type, dictionary, prefix='ADAM_MEASUREMENT_', parameters_keys=None): import library.measurement measurement_list = [] for key in sorted(dictionary): # sorted(dictionary) returns a list of keys sorted alphabetically if key.startswith(prefix): try: # dictionary[key] is a dictionary in string measurement_dict = json.loads(dictionary[key]) sensor_type = list(measurement_dict.keys())[0] m = library.measurement.Measurement(machine_type, sensor_type, measurement_dict[sensor_type], dictionary, parameters_keys=parameters_keys) measurement_list.append(m) except Exception as e: logging.critical(F'EXCLUDING MEASUREMENT: {dictionary[key]}') logging.getLogger().debug(e, exc_info=True) return measurement_list ############################################################# def get_config_measurement_list(machine_type, dictionary, prefix='CONFIG_MEASUREMENT_', parameters_keys=None, logger=None): logger = logging.getLogger() if logger is None else logger filename = get(dictionary, 'CONFIG_FILE', None) logger.info(f'get_config_measurement_list::filename:{filename}') if filename is not None: config_list_from_file = get_config_measurement_list_from_file(machine_type, filename, dictionary, folder='./files', parameters_keys=None, logger=logger) else: config_list_from_file = [] logger.info(f'get_config_measurement_list::config_list_from_file:{config_list_from_file}') config_dict_from_file = {m.sensor_type: m for m in config_list_from_file} config_list_from_dict = get_config_measurement_list_from_dict(machine_type, dictionary, prefix=prefix, parameters_keys=None, logger=logger) logger.info(f'get_config_measurement_list::config_list_from_dict:{config_list_from_dict}') config_dict_from_dict = {m.sensor_type: m for m in config_list_from_dict} config_dict = merge_dicts_priority(config_dict_from_dict, config_dict_from_file) return list(config_dict.values()) def get_config_measurement_list_from_dict(machine_type, dictionary, prefix='CONFIG_', parameters_keys=None, logger=None): logger = logging.getLogger() if logger is None else logger import library.measurement measurement_list = [] prefix_classes_dict = {} prefix_classes_dict[prefix + 'MEASUREMENT_'] = library.measurement.ConfigMeasurement prefix_classes_dict[prefix + 'MODBUS_MEASUREMENT_'] = library.measurement.ConfigModbusMeasurement prefix_classes_dict[prefix + 'QUERY_MEASUREMENT_'] = library.measurement.ConfigQueryMeasurement prefix_classes_dict[prefix + 'FUNCTION_MEASUREMENT_'] = library.measurement.ConfigFunctionMeasurement for key in sorted(dictionary): # sorted(dictionary) returns a list of keys sorted alphabetically for p in prefix_classes_dict: if key.startswith(p): try: # dictionary[key] is a dictionary in string measurement_dict = json.loads(dictionary[key]) sensor_type = list(measurement_dict.keys())[0] measurement = prefix_classes_dict[p](machine_type, sensor_type, measurement_dict[sensor_type], dictionary, parameters_keys=parameters_keys) measurement_list.append(measurement) except Exception as e: logger.critical(F'EXCLUDING MEASUREMENT: {dictionary[key]}') logger.debug(e, exc_info=True) # if key.startswith(prefix + 'MEASUREMENT_'): # try: # # dictionary[key] is a dictionary in string # measurement_dict = json.loads(dictionary[key]) # sensor_type = list(measurement_dict.keys())[0] # measurement = library.measurement.ConfigMeasurement(machine_type, sensor_type, measurement_dict[sensor_type], dictionary, parameters_keys=parameters_keys) # measurement_list.append(measurement) # except Exception as e: # logging.critical(F'EXCLUDING MEASUREMENT: {dictionary[key]}') # logging.getLogger().debug(e, exc_info=True) # elif key.startswith(prefix + 'MODBUS_MEASUREMENT_'): # try: # # dictionary[key] is a dictionary in string # measurement_dict = json.loads(dictionary[key]) # sensor_type = list(measurement_dict.keys())[0] # measurement = library.measurement.ConfigModbusMeasurement(machine_type, sensor_type, measurement_dict[sensor_type], dictionary, parameters_keys=parameters_keys) # measurement_list.append(measurement) # except Exception as e: # logging.critical(F'EXCLUDING MEASUREMENT: {dictionary[key]}') # logging.getLogger().debug(e, exc_info=True) # elif key.startswith(prefix + 'FUNCTION_MEASUREMENT_'): # try: # # dictionary[key] is a dictionary in string # measurement_dict = json.loads(dictionary[key]) # sensor_type = list(measurement_dict.keys())[0] # measurement = library.measurement.ConfigFunctionMeasurement(machine_type, sensor_type, measurement_dict[sensor_type], dictionary, parameters_keys=parameters_keys) # measurement_list.append(measurement) # except Exception as e: # logging.critical(F'EXCLUDING MEASUREMENT: {dictionary[key]}') # logging.getLogger().debug(e, exc_info=True) return measurement_list def get_config_measurement_list_from_file(machine_type, filename, common_dict, folder='./files', parameters_keys=None, logger=None): logger = logging.getLogger() if logger is None else logger import library.measurement common_dict_parsed = { key.replace('CONFIG_', ''): common_dict[key] for key in common_dict if key.startswith('CONFIG_') and not key.startswith ('CONFIG_MEASUREMENT_')} logger.info(f'get_config_measurement_list_from_file::common_dict_parsed:{common_dict_parsed}') measurement_list = [] try: with open(os.path.join(folder, filename), 'r') as f: json_content = json.load(f) logger.info(f'get_config_measurement_list_from_file::json_content:{json_content}') measurement_type_class_dict = {} measurement_type_class_dict['MEASUREMENTS'] = library.measurement.ConfigMeasurement measurement_type_class_dict['MODBUS_MEASUREMENTS'] = library.measurement.ConfigModbusMeasurement measurement_type_class_dict['QUERY_MEASUREMENT'] = library.measurement.ConfigQueryMeasurement measurement_type_class_dict['FUNCTION_MEASUREMENTS'] = library.measurement.ConfigFunctionMeasurement for measurement_type in measurement_type_class_dict: if measurement_type in json_content: for row in json_content[measurement_type]: try: configuration_type = list(row.keys())[0] m = measurement_type_class_dict[measurement_type](machine_type, configuration_type, row[configuration_type], common_dict_parsed, parameters_keys=parameters_keys) measurement_list.append(m) except Exception as e: logger.critical(f'get_config_measurement_list_from_file::excluding_measurement:{row}') logger.debug(e, exc_info=True) # if 'MEASUREMENTS' in json_content: # for row in json_content['MEASUREMENTS']: # try: # configuration_type = list(row.keys())[0] # m = library.measurement.ConfigMeasurement(machine_type, configuration_type, row[configuration_type], common_dict_parsed, parameters_keys=parameters_keys) # measurement_list.append(m) # except Exception as e: # logging.critical(f'get_config_measurement_list_from_file::excluding_measurement:{row}') # logging.getLogger().debug(e, exc_info=True) # if 'MODBUS_MEASUREMENTS' in json_content: # for row in json_content['MODBUS_MEASUREMENTS']: # try: # configuration_type = list(row.keys())[0] # m = library.measurement.ConfigModbusMeasurement(machine_type, configuration_type, row[configuration_type], common_dict_parsed, parameters_keys=parameters_keys) # measurement_list.append(m) # except Exception as e: # logging.critical(f'get_config_measurement_list_from_file::excluding_measurement:{row}') # logging.getLogger().debug(e, exc_info=True) # if 'FUNCTION_MEASUREMENTS' in json_content: # for row in json_content['FUNCTION_MEASUREMENTS']: # try: # configuration_type = list(row.keys())[0] # m = library.measurement.ConfigFunctionMeasurement(machine_type, configuration_type, row[configuration_type], common_dict_parsed, parameters_keys=parameters_keys) # measurement_list.append(m) # except Exception as e: # logging.critical(f'get_config_measurement_list_from_file::excluding_measurement:{row}') # logging.getLogger().debug(e, exc_info=True) except Exception as e: logger.critical(f'get_config_measurement_list_from_file::error_parsing_json:{os.path.join(folder, filename)}') logger.debug(e, exc_info=True) return measurement_list ############################################################# def merge_dicts(*list_of_dicts): result = {} for d in list_of_dicts: if d is not None: result.update(d) return result def merge_dicts_priority(first, second): if first is None: return second if second is None: return first # common keys of second will be overwritten by first return {**second, **first} def without_keys(d, keys): return {k: v for k, v in d.items() if k not in keys} ####################################################################### async def run_and_try_async(f, retry_count, delay, *args, **kwargs): for i in range(retry_count): try: return f(*args, **kwargs) except: logging.debug('run_and_try_if_true iteration {}'.format(i)) if i == 0: logging.error(traceback.format_exc()) await asyncio.sleep(delay) async def run_and_try_if_true_async(f, retry_count, delay, *args, **kwargs): for i in range(retry_count): try: if f(*args, **kwargs): return True except: logging.debug('run_and_try_if_true iteration {}'.format(i)) if i == 0: logging.error(traceback.format_exc()) await asyncio.sleep(delay) return False def run_and_try_sync(f, retry_count, delay, *args, **kwargs): for i in range(retry_count): try: return f(*args, **kwargs) except: logging.debug('run_and_try_if_true iteration {}'.format(i)) if i == 0: logging.error(traceback.format_exc()) time.sleep(delay) def run_and_try_if_true_sync(f, retry_count, delay, *args, **kwargs): for i in range(retry_count): try: if f(*args, **kwargs): return True except: logging.debug('run_and_try_if_true iteration {}'.format(i)) if i == 0: logging.error(traceback.format_exc()) time.sleep(delay) return False def get_iotedge_device_name(): if 'EdgeHubConnectionString' in os.environ: EdgeHubConnectionString = os.getenv('EdgeHubConnectionString') #'IOTEDGE_MODULEID') # EdgeHubConnectionString is: # HostName=;GatewayHostName=;DeviceId=;ModuleId=;SharedAccessKey= iot_edge_device_name = EdgeHubConnectionString.split(';')[2].split('=')[1] else: iot_edge_device_name = os.getenv('IOTEDGE_DEVICEID') return iot_edge_device_name ################################################################# def return_on_failure(value): def decorate(f): def applicator(*args, **kwargs): try: return f(*args,**kwargs) except Exception as e: logging.getLogger().debug(e, exc_info=True) return value return applicator return decorate ################################################################# def get(dictionary, key, default=None, common_dictionary=None): if key in dictionary: return dictionary[key] elif common_dictionary is not None and key in common_dictionary: return common_dictionary[key] return default # IF KEY_LIST IS PRESENT RETURN THAT DICTIONARY['KEY_LIST'] # IF KEY IS PRESENT RETURN [ DICTIONARY['KEY'] ] # ELSE RETURN DEFAULT def get_single_or_list(dictionary, key, list_suffix="_LIST", default=None, common_dictionary=None): # KEY_LIST in dictionary if key + list_suffix in dictionary: return parse_list(dictionary[key + list_suffix], default=default) # KEY in dictionary if key in dictionary: return [ dictionary[key] ] # KEY_LIST in common_dictionary if common_dictionary is not None and key + list_suffix in common_dictionary: return parse_list(common_dictionary[key + list_suffix], default=default) # KEY in common_dictionary if common_dictionary is not None and key in common_dictionary: return [ common_dictionary[key] ] return default ################################################################# def split_list(full_list, condition): true_list = [x for x in full_list if condition(x)] false_list = [x for x in full_list if not condition(x)] return true_list, false_list ################################################################# def validate_message_hash(message_str, secret_key=None, hash_algorithm=None, hash_timeout=None): SECRET_KEY = os.getenv("SECRET_KEY", default=None) if secret_key is None else secret_key HASH_ALGORITHM = os.getenv("HASH_ALGORITHM", default='sha1') if hash_algorithm is None else hash_algorithm HASH_TIMOUT = parse_float(os.getenv("HASH_TIMOUT", default=None), default=5*60) if hash_timeout is None else hash_timeout if SECRET_KEY is None: logging.getLogger().critical('MISSING SECRET_KEY ENV VARIABLE') return False, None try: message_dict = json.loads(message_str) except: logging.getLogger().critical(f'CANNOT PARSE to json message: {message_str}') return False, None hash_str = get(message_dict, 'hash', default=None) if hash_str is None: logging.getLogger().critical(f'MISSING HASH key in message: {message_str}') return False, None time_str = get(message_dict, 'time', default=None) if time_str is None: logging.getLogger().critical(f'MISSING time key in message: {message_str}') return False, None if (datetime.fromisoformat(time_str) - datetime.utcnow()).total_seconds() > HASH_TIMOUT: logging.getLogger().critical(f'OLD MESSAGE. message: {message_str}. max timeout: {HASH_TIMOUT}. real delay: {(datetime.fromisoformat(time_str) - datetime.utcnow()).total_seconds()}') return False, None message_dict.pop('hash', None) message_to_hash = json.dumps(message_dict, sort_keys=True) + SECRET_KEY hash_object = hashlib.new(HASH_ALGORITHM) hash_object.update(message_to_hash.encode('utf-8')) hash_correct = hash_object.hexdigest() # print('message_to_hash', message_to_hash.encode('utf-8')) # print(hash_correct) # print(hash_str) if hash_str == hash_correct: return True, message_dict else: logging.getLogger().critical(f'WRONG HASH. message: {message_str}') return False, None def generate_message_hash(message, time=None, secret_key=None, hash_algorithm=None, hash_timeout=None): SECRET_KEY = os.getenv("SECRET_KEY", default=None) if secret_key is None else secret_key HASH_ALGORITHM = os.getenv("HASH_ALGORITHM", default='sha1') if hash_algorithm is None else hash_algorithm if SECRET_KEY is None: logging.getLogger().critical('MISSING SECRET_KEY ENV VARIABLE') return False, None try: message_dict = json.loads(message) if isinstance(message, str) else message except: logging.getLogger().critical(f'CANNOT PARSE to json message: {message}') return None message_dict['time'] = (datetime.utcnow() if time is None else time).isoformat() message_to_hash = json.dumps(message_dict, sort_keys=True) + SECRET_KEY # print('message_to_hash', message_to_hash.encode('utf-8')) hash_object = hashlib.new(HASH_ALGORITHM) hash_object.update(message_to_hash.encode('utf-8')) hash_str = hash_object.hexdigest() message_dict['hash'] = hash_str return message_dict ################################################################# def ping(hostname, count=1, timeout=2.): import library.ping_utils as ping_utils for _ in range(count): if ping_utils.do_one(hostname, timeout) is not None: return True return False # return subprocess.run(["ping", "-c", f"{count}", "-w", "2", hostname]).returncode == 0 # return os.system(f"ping -c {count} -w2 {hostname} > /dev/null 2>&1") == 0 ################################################################# def compute_ranges(nums): # from a list of int return start and end # EX: ranges([2, 3, 4, 7, 8, 9, 15]) # [(2, 4), (7, 9), (15, 15)] nums = sorted(set(nums)) gaps = [[s, e] for s, e in zip(nums, nums[1:]) if s+1 < e] edges = iter(nums[:1] + sum(gaps, []) + nums[-1:]) return list(zip(edges, edges)) ################################################################# def parse_enum(enum_class, name, upper=True, default=None): if name is None: return default name = name.upper() if upper else name if name in enum_class._member_names_: return enum_class[name] return default def parse_enum_list(enum_class, names_list, upper=True, default=None): try: if names_list is None: return default parsed_list = [] for name in names_list: enum_value = parse_enum(enum_class, name, upper=upper, default=None) if enum_value is not None: parsed_list.append(enum_value) return parsed_list except: return default ################################################################# # OVERRIDES DECORATOR def overrides(interface_class): def overrider(method): assert(method.__name__ in dir(interface_class)) return method return overrider ################################################################# # APPLICAZION JSON PER VARIABILI PLC DA FILE CSV def add_csv2json_config(main_key:str, csv_dir:str, use_first_val_as_key:bool=True, json_dir:str=None): ''' viene pasato il path pre del csv per la configurazione da aggiungere al file json ''' data ={} # creazione del file di configurazoine se non presente. if (json_dir is None or not(os.path.isfile(json_dir))): json_dir='./config/json_'+datetime.datetime.now().strftime("%m%d%Y%H%M%S")+'.config' if (os.path.isfile(csv_dir)): #lettura da file csv with open(csv_dir, encoding='utf-8') as csvf: csvReader = csv.DictReader(csvf) for row in csvReader: _first_key= list(row.keys())[0] if use_first_val_as_key: key = list(row.values())[0] else: key = _first_key # rimozione del valore "chiave" del row[_first_key] data[key] = row # aggiunta dict al file json add_2_json(main_key, data, json_dir) def add_2_json(key, data_dict, json_dir): with open(json_dir,"r") as f: data:dict = json.load(f) data[key]=data_dict with open(json_dir , "w") as json_write: json.dump(data, json_write, indent=4) #### Creation delta time from string def parse_delta_time(time_str)->timedelta: regex = re.compile(r'((?P<hours>\d+?)h)?((?P<minutes>\d+?)m)?((?P<seconds>\d+?)s)?') parts = regex.match(time_str) if not parts: return parts = parts.groupdict() time_params = {} for (name, param) in parts.items(): if param: time_params[name] = int(param) return timedelta(**time_params) def get_past_time(delta_time_str:str, dt:datetime=None, _2str:bool=False, _2str_format:str=''): dt = datetime.utcnow() if dt is None else dt tdelta = parse_delta_time(delta_time_str) if tdelta is None: return dt = dt - tdelta if _2str==False: return dt return dt.strftime("%Y/%m/%d %H:%M:%S") def get_delta_time_2_seconds(delta_time_str:str): tdelta = parse_delta_time(delta_time_str) if tdelta is None: return return tdelta.total_seconds() <file_sep>/Bilancino/programma (another copy)/library/utils.py import time import os import sys import asyncio from six.moves import input from datetime import datetime import json import threading import logging import traceback import hashlib import subprocess from azure.iot.device.aio import IoTHubModuleClient from azure.iot.device import MethodResponse, Message ####################################################################### async def base_listener_directmethod(module_client, method_name, method, output_topic='output1'): while True: try: method_request = await module_client.receive_method_request(method_name) logging.getLogger().info(f'{method_name}. Payload: {method_request.payload}') try: status, result = await method(method_request.payload) except Exception as e: logging.error(f'ERROR in {method_name} {e}. Payload: {method_request.payload}.') logging.debug(e, exc_info=True) from library.base_module_class import BaseModuleClass status, result = BaseModuleClass.STATUS_ERROR, traceback.format_exc() method_response = MethodResponse.create_from_method_request(method_request, status, json.dumps(result)) if result is not None and output_topic is not None: message_response = Message(json.dumps(result)) await module_client.send_message_to_output(message_response, output_topic) await module_client.send_method_response(method_response) except Exception as e: logging.error('ERROR in input listener loop {}. traceback: {}'.format(e, traceback.format_exc())) logging.debug(e, exc_info=True) async def base_listener_message(module_client, input_topic, method, output_topic='output1'): while True: try: input_message = await module_client.receive_message_on_input(input_topic) status, result = await method(input_message.data) if isinstance(result, dict): result['status'] = status dict_response = result else: dict_response = {"status": status, 'data': result} message_response = Message(json.dumps(dict_response)) await module_client.send_message_to_output(message_response, output_topic) except Exception as e: logging.error('ERROR in input listener loop {}. traceback: {}'.format(e, traceback.format_exc())) logging.debug(e, exc_info=True) ####################################################################### def parse_json(payload): try: return json.loads(payload) except: return None def parse_int(string, default=0): try: return int(string) except: return default def parse_float(string, default=0.): try: return float(string) except: return default def parse_bool(string, default=False): if string is None: return default try: return str(string).lower() in ['true', 't', 'on', '1'] except: return default def parse_reading_env(string, fields=[]): try: dictionary = json.loads(string) key = list(dictionary.keys())[0] if all(field in dictionary[key] for field in fields): # if "register" in dictionary[key] and "type" in dictionary[key] and "uom" in dictionary[key]: # return dictionary["register"], dictionary["type"], dictionary["uom"] # print(string, dictionary) return key, dictionary[key] return None, None except: return None, None def parse_reading_envs_dict(fields=[]): dictionary = {} for env in os.environ: if env.startswith('READING_VALUES_'): key, value = parse_reading_env(os.getenv(env), fields=fields) dictionary[key] = value return dictionary # [parse_reading_env(os.getenv(env)) for env in os.environ if env.startswith('READING_VALUES_')] def get_all_measurement_list(machine_type, dictionary, parameters_keys=None): measurement_list = get_measurement_list(machine_type, dictionary, parameters_keys=parameters_keys) modbus_measurement_list = get_modbus_measurement_list(machine_type, dictionary, parameters_keys=parameters_keys) function_measurement_list = get_function_measurement_list(machine_type, dictionary, parameters_keys=parameters_keys) adam_measurement_list = get_adam_measurement_list(machine_type, dictionary, parameters_keys=parameters_keys) return measurement_list + modbus_measurement_list + function_measurement_list # + adam_measurement_list def get_measurement_list(machine_type, dictionary, prefix='MEASUREMENT_', parameters_keys=None): import library.measurement measurement_list = [] for key in sorted(dictionary): # sorted(dictionary) returns a list of keys sorted alphabetically if key.startswith(prefix): try: # dictionary[key] is a dictionary in string measurement_dict = json.loads(dictionary[key]) sensor_type = list(measurement_dict.keys())[0] m = library.measurement.Measurement(machine_type, sensor_type, measurement_dict[sensor_type], dictionary, parameters_keys=parameters_keys) measurement_list.append(m) except Exception as e: logging.critical(F'EXCLUDING MEASUREMENT: {dictionary[key]}') logging.getLogger().debug(e, exc_info=True) pass return measurement_list def get_modbus_measurement_list(machine_type, dictionary, prefix='MODBUS_MEASUREMENT_', parameters_keys=None): import library.measurement measurement_list = [] for key in sorted(dictionary): # sorted(dictionary) returns a list of keys sorted alphabetically if key.startswith(prefix): try: # dictionary[key] is a dictionary in string measurement_dict = json.loads(dictionary[key]) sensor_type = list(measurement_dict.keys())[0] measurement = library.measurement.ModbusMeasurement(machine_type, sensor_type, measurement_dict[sensor_type], dictionary, parameters_keys=parameters_keys) measurement_list.append(measurement) except Exception as e: logging.critical(F'EXCLUDING MEASUREMENT: {dictionary[key]}') logging.getLogger().debug(e, exc_info=True) return measurement_list def get_function_measurement_list(machine_type, dictionary, prefix='FUNCTION_MEASUREMENT_', parameters_keys=None): import library.measurement measurement_list = [] for key in sorted(dictionary): # sorted(dictionary) returns a list of keys sorted alphabetically if key.startswith(prefix): try: # dictionary[key] is a dictionary in string measurement_dict = json.loads(dictionary[key]) sensor_type = list(measurement_dict.keys())[0] measurement = library.measurement.FunctionMeasurement(machine_type, sensor_type, measurement_dict[sensor_type], dictionary, parameters_keys=parameters_keys) measurement_list.append(measurement) except Exception as e: logging.critical(F'EXCLUDING MEASUREMENT: {dictionary[key]}') logging.getLogger().debug(e, exc_info=True) return measurement_list def get_adam_measurement_list(machine_type, dictionary, prefix='ADAM_MEASUREMENT_', parameters_keys=None): import library.measurement measurement_list = [] for key in sorted(dictionary): # sorted(dictionary) returns a list of keys sorted alphabetically if key.startswith(prefix): try: # dictionary[key] is a dictionary in string measurement_dict = json.loads(dictionary[key]) sensor_type = list(measurement_dict.keys())[0] m = library.measurement.Measurement(machine_type, sensor_type, measurement_dict[sensor_type], dictionary, parameters_keys=parameters_keys) measurement_list.append(m) except Exception as e: logging.critical(F'EXCLUDING MEASUREMENT: {dictionary[key]}') logging.getLogger().debug(e, exc_info=True) return measurement_list def merge_dicts(*list_of_dicts): result = {} for d in list_of_dicts: if d is not None: result.update(d) return result def merge_dicts_priority(first, second): if first is None: return second if second is None: return first # common keys of second will be overwritten by first return {**second, **first} def without_keys(d, keys): return {k: v for k, v in d.items() if k not in keys} ####################################################################### async def run_and_try_async(f, retry_count, delay, *args, **kwargs): for i in range(retry_count): try: return f(*args, **kwargs) except: logging.debug('run_and_try_if_true iteration {}'.format(i)) if i == 0: logging.error(traceback.format_exc()) await asyncio.sleep(delay) async def run_and_try_if_true_async(f, retry_count, delay, *args, **kwargs): for i in range(retry_count): try: if f(*args, **kwargs): return True except: logging.debug('run_and_try_if_true iteration {}'.format(i)) if i == 0: logging.error(traceback.format_exc()) await asyncio.sleep(delay) return False def run_and_try_sync(f, retry_count, delay, *args, **kwargs): for i in range(retry_count): try: return f(*args, **kwargs) except: logging.debug('run_and_try_if_true iteration {}'.format(i)) if i == 0: logging.error(traceback.format_exc()) time.sleep(delay) def run_and_try_if_true_sync(f, retry_count, delay, *args, **kwargs): for i in range(retry_count): try: if f(*args, **kwargs): return True except: logging.debug('run_and_try_if_true iteration {}'.format(i)) if i == 0: logging.error(traceback.format_exc()) time.sleep(delay) return False def get_iotedge_device_name(): if 'EdgeHubConnectionString' in os.environ: EdgeHubConnectionString = os.getenv('EdgeHubConnectionString') #'IOTEDGE_MODULEID') # EdgeHubConnectionString is: # HostName=;GatewayHostName=;DeviceId=;ModuleId=;SharedAccessKey= iot_edge_device_name = EdgeHubConnectionString.split(';')[2].split('=')[1] else: iot_edge_device_name = os.getenv('IOTEDGE_DEVICEID') return iot_edge_device_name ################################################################# def return_on_failure(value): def decorate(f): def applicator(*args, **kwargs): try: return f(*args,**kwargs) except Exception as e: logging.getLogger().debug(e, exc_info=True) return value return applicator return decorate ################################################################# def get(dictionary, key, default=None, common_dictionary=None): if key in dictionary: return dictionary[key] elif common_dictionary is not None and key in common_dictionary: return common_dictionary[key] return default ################################################################# def split_list(full_list, condition): true_list = [x for x in full_list if condition(x)] false_list = [x for x in full_list if not condition(x)] return true_list, false_list ################################################################# def validate_message_hash(message_str, secret_key=None, hash_algorithm=None, hash_timeout=None): SECRET_KEY = os.getenv("SECRET_KEY", default=None) if secret_key is None else secret_key HASH_ALGORITHM = os.getenv("HASH_ALGORITHM", default='sha1') if hash_algorithm is None else hash_algorithm HASH_TIMOUT = parse_float(os.getenv("HASH_TIMOUT", default=None), default=5*60) if hash_timeout is None else hash_timeout if SECRET_KEY is None: logging.getLogger().critical('MISSING SECRET_KEY ENV VARIABLE') return False, None try: message_dict = json.loads(message_str) except: logging.getLogger().critical(f'CANNOT PARSE to json message: {message_str}') return False, None hash_str = get(message_dict, 'hash', default=None) if hash_str is None: logging.getLogger().critical(f'MISSING HASH key in message: {message_str}') return False, None time_str = get(message_dict, 'time', default=None) if time_str is None: logging.getLogger().critical(f'MISSING time key in message: {message_str}') return False, None if (datetime.fromisoformat(time_str) - datetime.utcnow()).total_seconds() > HASH_TIMOUT: logging.getLogger().critical(f'OLD MESSAGE. message: {message_str}. max timeout: {HASH_TIMOUT}. real delay: {(datetime.fromisoformat(time_str) - datetime.utcnow()).total_seconds()}') return False, None message_dict.pop('hash', None) message_to_hash = json.dumps(message_dict, sort_keys=True) + SECRET_KEY hash_object = hashlib.new(HASH_ALGORITHM) hash_object.update(message_to_hash.encode('utf-8')) hash_correct = hash_object.hexdigest() # print('message_to_hash', message_to_hash.encode('utf-8')) # print(hash_correct) # print(hash_str) if hash_str == hash_correct: return True, message_dict else: logging.getLogger().critical(f'WRONG HASH. message: {message_str}') return False, None def generate_message_hash(message, time=None, secret_key=None, hash_algorithm=None, hash_timeout=None): SECRET_KEY = os.getenv("SECRET_KEY", default=None) if secret_key is None else secret_key HASH_ALGORITHM = os.getenv("HASH_ALGORITHM", default='sha1') if hash_algorithm is None else hash_algorithm if SECRET_KEY is None: logging.getLogger().critical('MISSING SECRET_KEY ENV VARIABLE') return False, None try: message_dict = json.loads(message) if isinstance(message, str) else message except: logging.getLogger().critical(f'CANNOT PARSE to json message: {message}') return None message_dict['time'] = (datetime.utcnow() if time is None else time).isoformat() message_to_hash = json.dumps(message_dict, sort_keys=True) + SECRET_KEY # print('message_to_hash', message_to_hash.encode('utf-8')) hash_object = hashlib.new(HASH_ALGORITHM) hash_object.update(message_to_hash.encode('utf-8')) hash_str = hash_object.hexdigest() message_dict['hash'] = hash_str return message_dict ################################################################# def ping(hostname, count=1, timeout=2.): import library.ping_utils as ping_utils for _ in range(count): if ping_utils.do_one(hostname, timeout) is not None: return True return False # return subprocess.run(["ping", "-c", f"{count}", "-w", "2", hostname]).returncode == 0 # return os.system(f"ping -c {count} -w2 {hostname} > /dev/null 2>&1") == 0 <file_sep>/Modbus2DBs/Microturbine_RTU_2_Influx/testing_ok/plc_reader/library/rtu_modbus.py import logging import os import time import sys import traceback import asyncio from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder from pymodbus.payload import BinaryPayloadBuilder from pymodbus.transaction import ModbusRtuFramer as ModbusFramer from pymodbus.client.sync import ModbusSerialClient as ModbusClient import library.utils as utils from library.base_modbus import BaseModbus, ModbusTypes, ModbusAccess, ModbusRegisterType from library.measurement import Measurement, ModbusMeasurement import aenum from enum import Enum, auto # class IngridModbusCommands(aenum.Enum): # _init_ = 'value register register_type modbus_type access uom count' # COMMAND = auto(), 0, ModbusRegisterType.HOLDING, ModbusTypes.INT16, ModbusAccess.WRITE, 'status', None # HOLDING class RtuModbus(BaseModbus): def __init__(self, logger, port, stopbits, bytesize, baudrate, timeout, method, parity, variables_dict=None): super().__init__(variables_dict=variables_dict, logger=logger) self.port = port self.stopbits= stopbits self.bytesize = bytesize self.baudrate = baudrate self.timeout = timeout self.method = method self.parity = parity def connect(self): self.client = ModbusClient(method= self.method, port = self.port, timeout = self.timeout, baudrate = self.baudrate, stopbits = self.stopbits, bytesize = self.bytesize, parity=self.parity) return self.client.connect() def disconnect(self): return self.client.close() <file_sep>/2_DEPLOY/RTUModbusModule/V2/rtu_module_class.py import time import os import sys import asyncio from six.moves import input import datetime import json import threading import traceback import logging import random from abc import ABC, abstractmethod from azure.iot.device.aio import IoTHubModuleClient from azure.iot.device import MethodResponse, Message # from library.base_module_class import BaseModuleClass # from library.base_reader_module_class import BaseReaderModuleClass from library.base_iothub_reader_module_client import BaseIotHubReaderModuleClient from library.base_iothub_client import IobHubRemoteMethodStatus from library.rtu_modbus import RtuModbus from library.measurement import Measurement, ModbusMeasurement import library.utils as utils class RtuModuleClass(BaseIotHubReaderModuleClient): MACHINE_TYPE = "MICROTURBINE" def __init__(self): super().__init__(self.MACHINE_TYPE, None, None) measurement_list = utils.get_all_measurement_list(self.MACHINE_TYPE, os.environ) config_measurement_list = utils.get_config_measurement_list(RtuModuleClass.MACHINE_TYPE, os.environ, logger=self.logger) self.measurement_list = measurement_list self.config_measurement_list = config_measurement_list # self.list_background_functions.append(self.set_interval_listener_directmethod) self.simulator_setpoint = None ############################################################################################# async def init_device_instance(self): return RtuModbus(self.logger) async def connect_device(self, device_instance): await device_instance.connect_to_modbus_server() async def disconnect_device(self, device_instance): await device_instance.close_modbus_client() ############################################################################################# async def check_meas_bounds(): self.logger.info('SET_ODO_SETPOINT TRIGGERED. Payload: {}'.format(payload)) try: ingrid_modbus_instance = await self.init_device_instance() self.latest_command_time = time.time() ODO_DEFAULT = utils.parse_float(os.getenv('ODO_DEFAULT', 20.), default=20) ODO_MAX = utils.parse_float(os.getenv('ODO_MAX', 30.), default=30) ODO_MIN = utils.parse_float(os.getenv('ODO_MIN', 10.), default=10) value = utils.parse_float(payload, default=ODO_DEFAULT) if value > 0: value = max(ODO_MIN, min(ODO_MAX, value)) # clamp between min and max else: value = ODO_DEFAULT self.logger.debug("ODO_DEFAULT: {}, ODO_MAX: {}, ODO_MIN: {}, VALUE: {}".format(ODO_DEFAULT, ODO_MAX, ODO_MIN, value)) if not self.is_simulator(): await ingrid_modbus_instance.connect_to_modbus_server() await ingrid_modbus_instance.write_odo_setpoint(value) await ingrid_modbus_instance.close_modbus_client() else: self.simulator_setpoint = value return IobHubRemoteMethodStatus.STATUS_OK, value except Exception as e: self.logger.error('ERROR in set_odo_setpoint {}. Payload: {}.'.format(e, payload)) self.logger.debug(e, exc_info=True) return IobHubRemoteMethodStatus.STATUS_OK, traceback.format_exc()<file_sep>/2_DEPLOY/RTUModbusModule/V1/rtu_module_class.py import time import os import sys import asyncio from six.moves import input import datetime import json import threading import traceback import logging import random from abc import ABC, abstractmethod from azure.iot.device.aio import IoTHubModuleClient from azure.iot.device import MethodResponse, Message # from library.base_module_class import BaseModuleClass # from library.base_reader_module_class import BaseReaderModuleClass from library.base_iothub_reader_module_client import BaseIotHubReaderModuleClient from library.base_iothub_client import IobHubRemoteMethodStatus from library.rtu_modbus import RtuModbus from library.measurement import Measurement, ModbusMeasurement import library.utils as utils class RtuModuleClass(BaseIotHubReaderModuleClient): MACHINE_TYPE = "MICROTURBINE" def __init__(self): super().__init__(self.MACHINE_TYPE, None, None) measurement_list = utils.get_all_measurement_list(self.MACHINE_TYPE, os.environ) config_measurement_list = utils.get_config_measurement_list(RtuModuleClass.MACHINE_TYPE, os.environ, logger=self.logger) self.measurement_list = measurement_list self.config_measurement_list = config_measurement_list # self.list_background_functions.append(self.set_interval_listener_directmethod) self.simulator_setpoint = None ############################################################################################# async def init_device_instance(self): return RtuModbus(self.logger) async def connect_device(self, device_instance): await device_instance.connect_to_modbus_server() async def disconnect_device(self, device_instance): await device_instance.close_modbus_client() #############################################################################################<file_sep>/ModBus_PLC2PLC/ModBus_PLC2PLC_v_0.0.1/library/plc_modbus.py from pymodbus.client.sync import ModbusTcpClient import library.utils as utils from library.base_modbus import BaseModbus import asyncio class PlcModbus(BaseModbus): def __init__(self, logger, variables_dict=None): super().__init__(variables_dict=variables_dict, logger=logger) self.ip = utils.get(variables_dict,'MODBUS_IP', "192.168.0.1") self.port = utils.get(variables_dict,'MODBUS_PORT', 502) self.max_attempts=utils.get(variables_dict,'MAX_ATTEMPTS', 3) self.ping_interval = utils.get(variables_dict, 'PING_INTERVAL', 10) def connect(self): self.client = ModbusTcpClient(self.ip, self.port, id = self.modbus_id) connected = self.client.connect() return connected def disconnect(self): return self.client.close() async def periodic_ping(self): while True: if utils.ping(self.ip): self.logger.debug(f'PING::{self.ip}:{self.port}::RECEIVED') else: self.logger.debug(f'PING::{self.ip}:{self.port}::REFUSED') await asyncio.sleep(self.ping_interval) <file_sep>/Modbus2DBs/PlcSimulationEnv_DB/plc_writer/main.py import logging import sys import asyncio from plc_module_class import PlcModuleClass from influxdb_module_class import InfluxDBModuleClass from mssql_module_class import MSSQLManager from plc_looper import PlcLooper import logging import logging.handlers import library.utils as utils import json import os import shutil import ntpath import datetime ###################################################################################################################### # Parametri di configurazione config_dir = './config' old_config_dir = './config/old' plc_config_file = './config/plc_modbus.config' db_config_file = './config/db.config' modbus_measurements_key = 'MODBUS_MEASUREMENTS' ###################################################################################################################### # Initializzazione del logger # def init_logging(logger, filename, level=logging.INFO, stdout=True, maxBytes=10000, backupCount=5): logging.getLogger().setLevel(logging.NOTSET) logging.getLogger().handlers = [] rotatingHandler = logging.handlers.RotatingFileHandler(filename=filename, maxBytes=maxBytes, backupCount=backupCount) rotatingHandler.setLevel(logging.DEBUG) rotatingHandler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) logging.getLogger().addHandler(rotatingHandler) logging.getLogger(__name__).setLevel(level) logging.getLogger("pymodbus").setLevel(logging.DEBUG) if stdout: logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) logger = logging.getLogger(__name__) logger.info('init_logging::end') ###################################################################################################################### def connect_device(logger, plc_config_file): plc_modbus_client = PlcModuleClass(logger, plc_config_file) conn_res = plc_modbus_client.connect_device() return plc_modbus_client if conn_res else None ###################################################################################################################### def parseJsonConfig(file_full_path): #pwd = os.getcwd() if (os.path.isfile(file_full_path)): with open(file_full_path,"r") as f: return json.load(f) return None ###################################################################################################################### ### GENERAZIONE FILE DI CONFIGURAZIONE DA .CSV def get_plc_config(): files = [f for f in os.listdir(config_dir) if os.path.isfile(config_dir+'/'+f) and f.endswith('.csv')] if len(files)>0: #reset dei dati di configurazione de PLC reset_plc_config() for csv in files: utils.add_csv2json_config(modbus_measurements_key, config_dir+'/'+csv, json_dir=plc_config_file) #destinazione file di configurazione csv bkp_plc_config=old_config_dir+'/'+ntpath.basename(csv) +'.' + datetime.datetime.now().strftime("%m%d%Y%H%M%S") shutil.move(config_dir+'/'+csv, bkp_plc_config) def reset_plc_config(): with open(plc_config_file, 'r') as data_file: data:dict = json.load(data_file) #destinazione file di configurazione json bkp_plc_config=old_config_dir+'/'+ntpath.basename(plc_config_file) +'.' + datetime.datetime.now().strftime("%m%d%Y%H%M%S") #popped = data.pop(modbus_measurements_key, None) if modbus_measurements_key in data: del data[modbus_measurements_key] #spostamento file in backup shutil.move(plc_config_file, bkp_plc_config) with open(plc_config_file, 'w') as data_file: json.dump(data, data_file, indent=4) return data ###################################################################################################################### ### MAIN if __name__ == "__main__": logger = logging log_filename = 'test.log' init_logging(logger, log_filename) logger.info("::START::") logger.info("------------------------------------------------------") meas_ok:bool=True # Acquisizione dei file di configurazione get_plc_config() # Parsing delle variabili da file di configurazione. plc_dictinoary = parseJsonConfig(plc_config_file) db_dictionary = parseJsonConfig(db_config_file) # Connessione al PLC tramite Modbus plc_modbus_client = connect_device(logger, plc_dictinoary) # Connessione al DB InfluxDB influxdb_client = InfluxDBModuleClass(logger, utils.get(db_dictionary,'INFLUXDB')) # Connessione al DB MSSQLServer mssqldb_client = MSSQLManager(logger=logger, config_dict=utils.get(db_dictionary,'MSSQLDB')) if plc_modbus_client is not None: logger.info("::PLC CONNECTED::") # Avvio lettura in loop delle variabili logger.info("::START CONTROLLING PLC::") # plc looper plc_looper = PlcLooper(plc_modbus_client, influxdb_client, mssqldb_client) # avvio loop plc_looper.start_testing() logger.info("::STOP::") logger.info("------------------------------------------------------") <file_sep>/GretaAnalogWriter/requirements.txt azure-iot-device~=2.0.0 pymodbus numpy aenum pyparsing<file_sep>/GretaAnalogWriter/main.py from door_module_class import DoorModuleClass if __name__ == "__main__": DoorModuleClass().run() <file_sep>/MeasurementWriteFastAPI/docker-compose.yml version: "3.9" services: fastapi_edgedev_write: image: fastapi_edgedev_write build: context: ./ dockerfile: ./Dockerfile.amd64 dns: - 8.8.8.8 - 8.8.4.4 ports: - "8000:8000" container_name: fastapi_edgedev_write environment: LOCAL_NETWORK: ${LOCAL_NETWORK} HOST_IP: ${HOST_IP} cap_add: - net_admin volumes: - ~/.ssh:/root/.ssh
d384c1c3cac48db5fca6786c7a58547555bc1770
[ "YAML", "Markdown", "Python", "Text", "Shell" ]
78
Python
caseril/src_varius
6bbd6013f0f1b776371d73ddb779fb1c89ce4368
a47e297fe7a0c9e2fe49f2631c98caaa7ea3aee3
refs/heads/master
<repo_name>akash-plackal/coming-soon-page-react<file_sep>/src/Texts.js import React from "react"; import logo from "./logo.svg"; import Email from "./Email"; import "./texts.css"; export default function Texts() { return ( <div className="container"> <div className="content"> <img src={logo} alt="logo"></img> <h1 className="lightH1">we're</h1> <h1 className="boldH1">coming</h1> <h1 className="boldH1">soon</h1> <p> Hello fellow shoppers! We're currently building our new fashion store.Add your email below to stay up to date with announcements and our launch deals. </p> </div> <Email /> </div> ); } <file_sep>/src/Image.js import React from "react"; import "./image.css"; import hero from "./hero-desktop.jpg"; import Mhero from "./hero-mobile.jpg"; export default function Image() { return ( <div> <div className="hero"> <img className="hero-d" src={hero} alt="girl" /> <img className="hero-m" src={Mhero} alt="girl" /> </div> </div> ); }
553852e51eb28efac10a05dfeabe1d89402e0e26
[ "JavaScript" ]
2
JavaScript
akash-plackal/coming-soon-page-react
2802c1b5135d459826f7436bd1bb55d14df521ff
8ed76cc070ac2890968a7c6b7885fc93795b351d
refs/heads/master
<file_sep>import cv2 import Image import ImageDraw def detectFaces(image_name): img = cv2.imread(image_name) #face_cascade = cv2.CascadeClassifier("/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml") face_cascade = cv2.CascadeClassifier("C:/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml") if img.ndim == 3: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) else: gray = img #if no-gray for 3, gray for 2 faces = face_cascade.detectMultiScale(gray, 1.2, 5) #1.3~5 detect range result = [] for (x,y,width,height) in faces: result.append((x,y,x+width,y+height)) return result def saveFaces(image_name): faces = detectFaces(image_name) if faces: #save face to sace_dir save_dir = image_name.split('.')[0]+"_faces" os.mkdir(save_dir) count = 0 for (x1,y1,x2,y2) in faces: file_name = os.path.join(save_dir,str(count)+".jpg") Image.open(image_name).crop((x1,y1,x2,y2)).save(file_name) count+=1 def drawFaces(image_name): faces = detectFaces(image_name) if faces: img = Image.open(image_name) draw_instance = ImageDraw.Draw(img) for (x1,y1,x2,y2) in faces: draw_instance.rectangle((x1,y1,x2,y2), outline=(255, 0,0)) img.save('drawfaces_'+image_name) drawFaces('Oceans-Eleven.jpg')
1eb9b5d885bc89c5cb226616e262065b055e6de8
[ "Python" ]
1
Python
aaron0922/python_facedetect
1857b17dc6282480dc0797bf1149740de21d0c53
24fd3eeb5f800380fded15c56f4a6396aa85cbae
refs/heads/master
<file_sep># Process/thread synchronization FIFO buffer with n elements (n>3). There is one producer and three consumers (A, B, C). Producer produces one element if there is a free space in the buffer. Element can be removed from the buffer when it is read by either consumer A and B or B and C. None of the consumers can read the same element multiple times. Consumer A cannot read the element if it was read before by consumer C and vice versa. Problem solved using two different approaches: * semaphores `sem.c` - each consumer and producer is a different process and use shared memory. More about [shared memory](http://man7.org/linux/man-pages/man2/mmap.2.html) and [semaphores](http://pubs.opengroup.org/onlinepubs/7908799/xsh/semaphore.h.html). * monitors `mon.cpp` - each consumer and producer is a different thread and use process memory. I'm using my own implementation of monitors. More about [boost thread library](http://www.boost.org/doc/libs/1_64_0/doc/html/thread.html). Project was done as a part of Operating Systems Course at Warsaw University of Technology. <file_sep>//g++ -o mon mon.c -lpthread -lboost_thread #include <boost/thread/thread.hpp> #include <boost/random/mersenne_twister.hpp> #include <iostream> #include <queue> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <pthread.h> #include <unistd.h> #include <semaphore.h> using namespace std; #define NO_ONE 0 #define CONSUMER_A 1 #define CONSUMER_B 2 #define CONSUMER_C 3 #define READ 1 #define POP 2 // inicjalizacja generatora wartosci pseudolosowych boost::random::mt19937 gen(time(0)); //////////////////////////////////////////////////////////////////////////////////////////////////////////// class Semaphore { public: Semaphore( int value ) { if( sem_init( & sem, 0, value ) != 0 ) throw "sem_init: failed"; } ~Semaphore() { sem_destroy( & sem ); } void p() { if( sem_wait( & sem ) != 0 ) throw "sem_wait: failed"; } void v() { if( sem_post( & sem ) != 0 ) throw "sem_post: failed"; } private: sem_t sem; }; class Condition { friend class Monitor; public: Condition() : w( 0 ) { waitingCount = 0; } void wait() { w.p(); } bool signal() { if( waitingCount ) { -- waitingCount; w.v(); return true; } else return false; } private: Semaphore w; int waitingCount; //liczba oczekujacych watkow }; class Monitor { public: Monitor() : s( 1 ) {} void enter() { s.p(); } void leave() { s.v(); } void wait( Condition & cond ) { ++ cond.waitingCount; leave(); cond.wait(); } void signal( Condition & cond ) { if( cond.signal() ) enter(); } private: Semaphore s; }; class buffer : public Monitor { public: buffer (int s) : who_read(NO_ONE), buffer_size(s), status(0) {} ~buffer () {} void produce() { enter(); if(q.size() == buffer_size) wait(full); char i = 65 + gen() % (90 - 65); q.push_back(i); cout << "Producent odklada: " << i << ", liczba elementow: " << q.size() << endl; print(); if(q.size() > 0) signal(empty); if(q.size() > 3) signal(con_3); leave(); } void read_or_pop(int consumer) { enter(); switch(consumer) { case CONSUMER_A: if (who_read == CONSUMER_A || who_read == CONSUMER_C) wait(con_A); if (who_read == CONSUMER_B) { status = POP; } else if (who_read == NO_ONE) { status = READ; } break; case CONSUMER_B: if (who_read == CONSUMER_B) wait(con_B); if (who_read == CONSUMER_A || who_read == CONSUMER_C) { status = POP; } else if (who_read == NO_ONE) { status = READ; } break; case CONSUMER_C: if (who_read == CONSUMER_C || who_read == CONSUMER_A) wait(con_C); if (who_read == CONSUMER_B) { status = POP; } else if (who_read == NO_ONE) { status = READ; } break; } if(q.size() == 0) wait(empty); if (status == POP) { if(q.size() <= 3) wait(con_3); char i = q.front(); q.pop_front(); cout << get_consumer(consumer) << " zdejmuje: " << i << ", liczba elementow: " << q.size() << endl; print(); who_read = NO_ONE; } else if (status == READ) { char i = q.front(); cout << get_consumer(consumer) << " czyta: " << i << ", liczba elementow: " << q.size() << endl; print(); who_read = consumer; } if(q.size() < buffer_size) signal(full); if (who_read != CONSUMER_A && who_read != CONSUMER_C) signal(con_A); if (who_read != CONSUMER_B) signal(con_B); if (who_read != CONSUMER_C && who_read != CONSUMER_A) signal(con_C); leave(); } string get_consumer(int c) { switch(c) { case CONSUMER_A: return "Konsument_A"; break; case CONSUMER_B: return "Konsument_B"; break; case CONSUMER_C: return "Konsument_C"; break; } } void print() // funkcja drukująca zawartość bufora { if (q.empty()) { cout << "[]" << endl; return; } cout << " [ "; for (deque<char>::iterator it = q.begin(); it != q.end(); ++it) { cout << *it << " "; } cout << "] " << endl; } private: deque<char> q; // kolejka int who_read; // przechowuje informacje o tym kto przeczytal ostatni element int buffer_size; int status; Condition full, empty, con_A, con_B, con_C, con_3; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////// const int CONSUMER_A_MAX_SLEEP = 5; // w sekundach const int CONSUMER_B_MAX_SLEEP = 6; const int CONSUMER_C_MAX_SLEEP = 7; const int PRODUCER_MAX_SLEEP = 3; const int CONSUMER_A_MIN_SLEEP = 4; const int CONSUMER_B_MIN_SLEEP = 3; const int CONSUMER_C_MIN_SLEEP = 6; const int PRODUCER_MIN_SLEEP = 1; buffer buf(8); // utworzenie obiektu klasy bufor inline void wait(int _min, int _max) // funkcja czekająca { usleep(1000000 * _min + gen() % (1000000 * (_max - _min))); } void konsumentA() { for (;;) { wait(CONSUMER_A_MIN_SLEEP, CONSUMER_A_MAX_SLEEP); cout << "Konsument A probuje zdjac...\n"; buf.read_or_pop(CONSUMER_A); } } void konsumentC() { for (;;) { wait(CONSUMER_C_MIN_SLEEP, CONSUMER_C_MAX_SLEEP); cout << "Konsument C probuje zdjac...\n"; buf.read_or_pop(CONSUMER_C); } } void konsumentB() { for (;;) { wait(CONSUMER_B_MIN_SLEEP, CONSUMER_B_MAX_SLEEP); cout << "Konsument B probuje zdjac...\n"; buf.read_or_pop(CONSUMER_B); } } void producent() { for (;;) { wait(PRODUCER_MIN_SLEEP, PRODUCER_MAX_SLEEP); cout << "Producent probuje odlozyc...\n"; buf.produce(); } } int main() { boost::thread thread1(konsumentA); boost::thread thread2(konsumentB); boost::thread thread3(konsumentC); boost::thread thread4(producent); thread1.join(); thread2.join(); thread3.join(); thread4.join(); return 0; } <file_sep>//gcc -o sem sem.c -lpthread #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/mman.h> #include <unistd.h> #include <semaphore.h> #define NO_ONE 0 #define CONSUMER_A 1 #define CONSUMER_B 2 #define CONSUMER_C 3 #define SIZE 10 sem_t *mutex, *mutex_3, *full, *empty, *mutex_A, *mutex_B, *mutex_C, *mutex_AC; void createProducer(); void createConsumerA(); void createConsumerC(); void createConsumerB(); typedef struct { char var; int who; } comp; typedef struct { comp buffer[SIZE]; int reads; int current_readers_counter; int length; int head; int tail; } Queue; void init (Queue* q, int length); void add(Queue* q, comp element); comp remove_element(Queue *q); comp read_element_queue(Queue* q); int get_queue_current_length(Queue *q); void print_queue(Queue* q); void update_element(Queue* q, int v); Queue* q; int main() { q = mmap(NULL, sizeof(Queue), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0); init(q,SIZE+1); mutex = mmap(NULL, sizeof(sem_t), PROT_READ |PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1, 0); mutex_3 = mmap(NULL, sizeof(sem_t), PROT_READ |PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1, 0); full = mmap(NULL, sizeof(sem_t), PROT_READ |PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1, 0); empty = mmap(NULL, sizeof(sem_t), PROT_READ |PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1, 0); mutex_A = mmap(NULL, sizeof(sem_t), PROT_READ |PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1, 0); mutex_B = mmap(NULL, sizeof(sem_t), PROT_READ |PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1, 0); mutex_C = mmap(NULL, sizeof(sem_t), PROT_READ |PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1, 0); mutex_AC = mmap(NULL, sizeof(sem_t), PROT_READ |PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1, 0); sem_init(mutex,1,1); sem_init(mutex_3,1,0); sem_init(full,1,SIZE); sem_init(empty,1,0); sem_init(mutex_A,1,0); sem_init(mutex_B,1,0); sem_init(mutex_C,1,0); sem_init(mutex_AC,1,1); createProducer(); createConsumerA(); createConsumerC(); createConsumerB(); return 0; } void createProducer() { pid_t pid; pid = fork(); comp element; int t; char c; if(pid == 0) { while(1) { t =(rand() % 4); sleep((unsigned int) t); printf("Producent probuje odlozyc...\n"); sem_wait(full); sem_wait(mutex); c = 65 + rand() % (90 - 65); element.var = c; element.who = NO_ONE; add(q, element); printf("Producent odlozyl element: %c ilosc elementow: %d\n", c, get_queue_current_length(q)); print_queue(q); if (get_queue_current_length(q)>3) sem_post(mutex_3); sem_post(mutex); sem_post(empty); } } return; }; void createConsumerA() { pid_t pid; pid = fork(); comp element; int t; if (pid == 0) { while(1) { t =(rand() % 6); sleep((unsigned int) t); printf("Konsument A probuje zdjac\n"); sem_wait(mutex_AC); sem_wait(empty); sem_wait(mutex); element = read_element_queue(q); if(element.who == CONSUMER_B) { sem_post(mutex); sem_wait(mutex_3); sem_wait(mutex); element = remove_element(q); printf("Konsument A zdjal: %c ilosc elementow: %d\n", element.var, get_queue_current_length(q)); print_queue(q); sem_post(full); if (get_queue_current_length(q)>3) sem_post(mutex_3); sem_post(mutex); sem_post(mutex_B); sem_post(mutex_AC); } else if(element.who == NO_ONE) { update_element(q,CONSUMER_A); printf("Konsument A przeczytal: %c ilosc elementow: %d\n", element.var, get_queue_current_length(q)); print_queue(q); sem_post(empty); sem_post(mutex); sem_wait(mutex_A); } } } return; }; void createConsumerC() { pid_t pid; pid = fork(); comp element; int t; if (pid == 0) { while(1) { t =(rand() % 10); sleep((unsigned int) t); printf("Konsument C probuje zdjac\n"); sem_wait(mutex_AC); sem_wait(empty); sem_wait(mutex); element = read_element_queue(q); if(element.who == CONSUMER_B) { sem_post(mutex); sem_wait(mutex_3); sem_wait(mutex); element = remove_element(q); printf("Konsument C zdjal: %c ilosc elementow: %d\n", element.var, get_queue_current_length(q)); print_queue(q); sem_post(full); if (get_queue_current_length(q)>3) sem_post(mutex_3); sem_post(mutex); sem_post(mutex_B); sem_post(mutex_AC); } else if(element.who == NO_ONE) { update_element(q,CONSUMER_C); printf("Konsument C przeczytal: %c ilosc elementow: %d\n", element.var, get_queue_current_length(q)); print_queue(q); sem_post(empty); sem_post(mutex); sem_wait(mutex_C); } } } return; }; void createConsumerB() { pid_t pid; pid = fork(); comp element; int t; if (pid == 0) { while(1) { t =(rand() % 6); sleep((unsigned int) t); printf("Konsument B probuje zdjac\n"); sem_wait(empty); sem_wait(mutex); element = read_element_queue(q); if(element.who == CONSUMER_A || element.who == CONSUMER_C) { sem_post(mutex); sem_wait(mutex_3); sem_wait(mutex); element = remove_element(q); printf("Konsument B zdjal: %c ilosc elementow: %d\n", element.var, get_queue_current_length(q)); print_queue(q); sem_post(full); if (get_queue_current_length(q)>3) sem_post(mutex_3); sem_post(mutex); if(element.who == CONSUMER_A) { sem_post(mutex_A); }else { sem_post(mutex_C); } sem_post(mutex_AC); } else if(element.who == NO_ONE) { update_element(q,CONSUMER_B); printf("Konsument B przeczytal: %c ilosc elementow: %d\n", element.var, get_queue_current_length(q)); print_queue(q); sem_post(empty); sem_post(mutex); sem_wait(mutex_B); } } } return; }; void init (Queue* q, int length){ q -> reads = 0; q -> length = length; q -> head = 0; q -> tail = 0; } void add(Queue* q, comp element){ q -> buffer[q -> head] = element; (q -> head)++; q -> head = (q -> head) % q -> length; } int get_queue_current_length(Queue *q){ return (q -> head + q -> length - q ->tail) % q -> length; } comp remove_element(Queue *q){ comp element = q -> buffer[q -> tail]; comp temp; temp.var = '-'; temp.who = NO_ONE; q -> buffer[q -> tail] = temp; (q -> tail)++; q -> tail = (q -> tail) % q -> length; q -> reads = 0; return element; } comp read_element_queue(Queue* q){ comp element = q -> buffer[q -> tail]; q -> reads++; return element; } void print_queue(Queue* q){ if ((q -> tail) <= (q -> head)) { for (int i = (q -> tail); i < (q -> head); i++) { printf("%c ", q -> buffer[i].var); } }else { for (int i = (q -> tail); i < (q -> length-1); i++) { printf("%c ", q -> buffer[i].var); } for (int i = 0; i < (q -> head); i++) { printf("%c ", q -> buffer[i].var); } } printf("\n"); } void update_element(Queue* q, int v){ q -> buffer[q -> tail].who = v; }
5fe536cc54aba33555b921a1666e696066f960c3
[ "Markdown", "C", "C++" ]
3
Markdown
KarolloS/Process-thread-synchronization
93cd679ba71c1c13adffa507f990114a2ded9599
859926173d6c966e88c7ef6b12d97588f4a0ad2d
refs/heads/main
<file_sep>![SnapWindow](https://github.com/Th3On3/SnapWindow/blob/main/resources/splash.png?raw=true) ## 1. About Already happened to you that you needed [Kodi](https://kodi.tv/) or [VLC](https://www.videolan.org/) in a small snapped window always on top while you are working or doing other stuff, well then you don't need to wait more, you can use SnapWindow. ## 2. AutoHotKey This software was developed with [AutoHotKey](https://www.autohotkey.com/) and AutoHotKey.exe must be on your $PATH or in the bin directory. ## 3. Screenshots - SnapWindow in action: ![SnapWindow in action](https://github.com/Th3On3/SnapWindow/blob/main/resources/screen1.png?raw=true) - Select another window: ![Select another window](https://github.com/Th3On3/SnapWindow/blob/main/resources/screen2.png?raw=true) - Change transparecy: ![Change transparecy](https://github.com/Th3On3/SnapWindow/blob/main/resources/screen3.png?raw=true) - Change size: ![Change size](https://github.com/Th3On3/SnapWindow/blob/main/resources/screen4.png?raw=true) - Open Youtube link on VLC: ![Open Youtube link on VLC](https://github.com/Th3On3/SnapWindow/blob/main/resources/screen5.png?raw=true) ## 4. Features - Multimonitor support - Transparecy - Resizing - Fullscreen toggle - Targeting other window - Open Youtube link on VLC - Etc. ## 5. Help - CTRL+SHIFT+u - Top Left - CTRL+SHIFT+j - Bottom Left - CTRL+SHIFT+i - Top Right - CTRL+SHIFT+k - Bottom Right - CTRL+SHIFT+o - Target window - CTRL+SHIFT+s - Size - CTRL+SHIFT+t - Transparecy - CTRL+SHIFT+f - Toggle fullscreen - CTRL+SHIFT+v - Open VLC - CTRL+SHIFT+b - Open Youtube link on VLC - CTRL+SHIFT+h - Help - CTRL+SHIFT+x - Exit ## 6. Donate and pay me a beer [![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/donate?cmd=_donations&business=<EMAIL>&currency_code=EUR) ![paypal](https://github.com/Th3On3/SnapWindow/blob/main/resources/paypal.png?raw=true) ## 7. Enjoy <file_sep>/* * Filename: launcher.js * * Copyright (c) 2020 <NAME> <<EMAIL>> */ var wshShell = WScript.CreateObject("WScript.Shell"); var objArgs = WScript.Arguments; var args=""; for (i = 0; i < objArgs.length; i++){ if (args=="") { args+=objArgs(i); } else{ args+=" "+objArgs(i); } } wshShell.Run( '%SystemRoot%\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -executionpolicy bypass -Command &{' + args + '} ', 0, false );
138146767c0f38913f83798aab530db27fb91a4e
[ "Markdown", "JavaScript" ]
2
Markdown
Th3On3/SnapWindow
58e2c6c5a947619ab2d6f42fb765739f5faf72d1
066548fa8e966e31ba82795c5a95693b2e06abff
refs/heads/master
<file_sep>#!/bin/bash SITENAME=askubuntu_unix_superuser CQ_DATA_DIR=clarification_question_generation_pytorch/$SITENAME SCRIPT_DIR=clarification_question_generation_pytorch/src EMB_DIR=clarification_question_generation_pytorch/embeddings/$SITENAME python $SCRIPT_DIR/decode.py --test_context $CQ_DATA_DIR/test_context.txt \ --test_ques $CQ_DATA_DIR/test_question.txt \ --test_ans $CQ_DATA_DIR/test_answer.txt \ --test_ids $CQ_DATA_DIR/test_ids \ --test_pred_ques $CQ_DATA_DIR/test_pred_question.txt \ --q_encoder_params $CQ_DATA_DIR/q_encoder_params.epoch100.GAN_selfcritic_pred_ans.epoch12 \ --q_decoder_params $CQ_DATA_DIR/q_decoder_params.epoch100.GAN_selfcritic_pred_ans.epoch12 \ --word_embeddings $EMB_DIR/word_embeddings.p \ --vocab $EMB_DIR/vocab.p \ --model GAN.epoch12 \ --max_post_len 100 \ --max_ques_len 20 \ --max_ans_len 20 \ --batch_size 256 \ --beam True \ <file_sep>python src/decode.py --test_context baseline_data/valid_context.txt \ --test_ques baseline_data/valid_question.txt \ --test_ans baseline_data/valid_answer.txt \ --test_ids baseline_data/valid_asin.txt \ --test_pred_ques baseline_data/valid_predicted_question.txt \ --q_encoder_params baseline_data/seq2seq-pretrain-ques-v3/q_encoder_params.epoch49 \ --q_decoder_params baseline_data/seq2seq-pretrain-ques-v3/q_decoder_params.epoch49 \ --word_embeddings embeddings/amazon_200d_embeddings.p \ --vocab embeddings/amazon_200d_vocab.p \ --model seq2seq.epoch49 \ --max_post_len 100 \ --max_ques_len 20 \ --max_ans_len 20 \ --batch_size 10 \ --n_epochs 40 \ --greedy True #--beam True <file_sep>from constants import * import math import numpy as np import nltk import random import time import torch def as_minutes(s): m = math.floor(s / 60) s -= m * 60 return '%dm %ds' % (m, s) def time_since(since, percent): now = time.time() s = now - since es = s / (percent) rs = es - s return '%s (- %s)' % (as_minutes(s), as_minutes(rs)) def iterate_minibatches(id_seqs, input_seqs, input_lens, output_seqs, output_lens, batch_size, shuffle=True): if shuffle: indices = np.arange(len(input_seqs)) np.random.shuffle(indices) for start_idx in range(0, len(input_seqs) - batch_size + 1, batch_size): if shuffle: ex = indices[start_idx:start_idx + batch_size] else: ex = slice(start_idx, start_idx + batch_size) yield np.array(id_seqs)[ex], np.array(input_seqs)[ex], np.array(input_lens)[ex], \ np.array(output_seqs)[ex], np.array(output_lens)[ex] def reverse_dict(word2index): index2word = {} for w in word2index: ix = word2index[w] index2word[ix] = w return index2word def calculate_bleu(true, true_lens, pred, pred_lens, index2word, max_len): sent_bleu_scores = torch.zeros(len(pred)) for i in range(len(pred)): true_sent = [index2word[idx] for idx in true[i][:true_lens[i]]] pred_sent = [index2word[idx] for idx in pred[i][:pred_lens[i]]] sent_bleu_scores[i] = nltk.translate.bleu_score.sentence_bleu([true_sent], pred_sent) if USE_CUDA: sent_bleu_scores = sent_bleu_scores.cuda() return sent_bleu_scores <file_sep>#!/bin/bash SITENAME=Home_and_Kitchen CQ_DATA_DIR=/fs/clip-amr/clarification_question_generation_pytorch/$SITENAME BLEU_SCRIPT=/fs/clip-software/user-supported/mosesdecoder/3.0/scripts/generic/multi-bleu.perl $BLEU_SCRIPT $CQ_DATA_DIR/test_ref < $CQ_DATA_DIR/GAN_test_pred_question.txt.epoch8.hasrefs <file_sep>import torch import torch.nn as nn import sys sys.path.append('src/seq2seq') from attn import * class AttnDecoderRNN(nn.Module): def __init__(self, hidden_size, output_size, word_embeddings, n_layers=1, dropout=0.1): super(AttnDecoderRNN, self).__init__() # Keep for reference self.hidden_size = hidden_size self.output_size = output_size self.n_layers = n_layers self.dropout = dropout # Define layers self.embedding = nn.Embedding(len(word_embeddings), len(word_embeddings[0])) self.embedding.weight.data.copy_(torch.from_numpy(word_embeddings)) self.embedding.weight.requires_grad = False self.embedding_dropout = nn.Dropout(dropout) self.gru = nn.GRU(len(word_embeddings[0]), hidden_size, n_layers, dropout=dropout) self.concat = nn.Linear(hidden_size * 2, hidden_size) self.out = nn.Linear(hidden_size, output_size) self.attn = Attn(hidden_size) def forward(self, input_seq, last_hidden, p_encoder_outputs): # Note: we run this one step at a time # Get the embedding of the current input word (last output word) embedded = self.embedding(input_seq) embedded = self.embedding_dropout(embedded) embedded = embedded.view(1, embedded.shape[0], embedded.shape[1]) # S=1 x B x N # Get current hidden state from input word and last hidden state rnn_output, hidden = self.gru(embedded, last_hidden) # Calculate attention from current RNN state and all p_encoder outputs; # apply to p_encoder outputs to get weighted average p_attn_weights = self.attn(rnn_output, p_encoder_outputs) p_context = p_attn_weights.bmm(p_encoder_outputs.transpose(0, 1)) # B x S=1 x N # Attentional vector using the RNN hidden state and context vector # concatenated together (Luong eq. 5) rnn_output = rnn_output.squeeze(0) # S=1 x B x N -> B x N p_context = p_context.squeeze(1) # B x S=1 x N -> B x N concat_input = torch.cat((rnn_output, p_context), 1) concat_output = F.tanh(self.concat(concat_input)) # Finally predict next token (Luong eq. 6, without softmax) output = self.out(concat_output) # Return final output, hidden state, and attention weights (for visualization) return output, hidden <file_sep>import argparse import csv from collections import defaultdict import sys import numpy as np import pdb on_topic_levels = {'Yes': 1, 'No': 0} is_grammatical_levels = {'Grammatical': 2, 'Comprehensible': 1, 'Incomprehensible': 0} is_specific_levels = {'Specific pretty much only to this product': 4, 'Specific to this and other very similar products (or the same product from a different manufacturer)': 3, 'Generic enough to be applicable to many other products of this type': 2, 'Generic enough to be applicable to any product under Home and Kitchen': 1, 'N/A (Not Applicable)': 0} asks_new_info_levels = {'Completely': 3, 'Somewhat': 2, 'No': 1, 'N/A (Not Applicable)': 0} useful_levels = {'Useful enough to be included in the product description': 4, 'Useful to a large number of potential buyers (or current users)': 3, 'Useful to a small number of potential buyers (or current users)': 2, 'Useful only to the person asking the question': 1, 'N/A (Not Applicable)': 0} model_dict = {'ref': 0, 'lucene': 1, 'seq2seq.beam': 2, 'rl.beam': 3, 'gan.beam': 4} model_list = ['ref', 'lucene', 'seq2seq.beam', 'rl.beam', 'gan.beam'] frequent_words = ['dimensions', 'dimension', 'size', 'measurements', 'measurement', 'weight', 'height', 'width', 'diameter', 'density', 'bpa', 'difference', 'thread', 'china', 'usa'] def get_avg_score(score_dict, ignore_na=False): curr_on_topic_score = 0. N = 0 for score, count in score_dict.iteritems(): curr_on_topic_score += score * count if ignore_na: if score != 0: N += count else: N += count # print N return curr_on_topic_score * 1.0 / N def main(args): num_models = len(model_list) on_topic_scores = [None] * num_models is_grammatical_scores = [None] * num_models is_specific_scores = [None] * num_models asks_new_info_scores = [None] * num_models useful_scores = [None] * num_models asins_so_far = [None] * num_models for i in range(num_models): on_topic_scores[i] = defaultdict(int) is_grammatical_scores[i] = defaultdict(int) is_specific_scores[i] = defaultdict(int) asks_new_info_scores[i] = defaultdict(int) useful_scores[i] = defaultdict(int) asins_so_far[i] = [] with open(args.aggregate_results_v1) as csvfile: reader = csv.DictReader(csvfile) for row in reader: if row['_golden'] == 'true' or row['_unit_state'] == 'golden': continue asin = row['asin'] question = row['question'] model_name = row['model_name'] if model_name not in model_list: continue if asin not in asins_so_far[model_dict[model_name]]: asins_so_far[model_dict[model_name]].append(asin) else: print '%s duplicate %s' % (model_name, asin) continue on_topic_score = on_topic_levels[row['on_topic']] is_grammatical_score = is_grammatical_levels[row['grammatical']] specific_score = is_specific_levels[row['is_specific']] asks_new_info_score = asks_new_info_levels[row['new_info']] useful_score = useful_levels[row['useful_to_another_buyer']] if on_topic_score == 0: specific_score = 0 asks_new_info_score = 0 useful_score = 0 if is_grammatical_score == 0: specific_score = 0 asks_new_info_score = 0 useful_score = 0 on_topic_scores[model_dict[model_name]][on_topic_score] += 1 is_grammatical_scores[model_dict[model_name]][is_grammatical_score] += 1 is_specific_scores[model_dict[model_name]][specific_score] += 1 asks_new_info_scores[model_dict[model_name]][asks_new_info_score] += 1 useful_scores[model_dict[model_name]][useful_score] += 1 with open(args.aggregate_results_v2) as csvfile: reader = csv.DictReader(csvfile) for row in reader: if row['_golden'] == 'true' or row['_unit_state'] == 'golden': continue asin = row['asin'] question = row['question'] model_name = row['model_name'] if model_name not in model_list: continue if asin not in asins_so_far[model_dict[model_name]]: asins_so_far[model_dict[model_name]].append(asin) else: print '%s duplicate %s' % (model_name, asin) continue on_topic_score = on_topic_levels[row['on_topic']] is_grammatical_score = is_grammatical_levels[row['grammatical']] specific_score = is_specific_levels[row['is_specific']] asks_new_info_score = asks_new_info_levels[row['new_info']] useful_score = useful_levels[row['useful_to_another_buyer']] if on_topic_score == 0: specific_score = 0 asks_new_info_score = 0 useful_score = 0 if is_grammatical_score == 0: specific_score = 0 asks_new_info_score = 0 useful_score = 0 on_topic_scores[model_dict[model_name]][on_topic_score] += 1 is_grammatical_scores[model_dict[model_name]][is_grammatical_score] += 1 is_specific_scores[model_dict[model_name]][specific_score] += 1 asks_new_info_scores[model_dict[model_name]][asks_new_info_score] += 1 useful_scores[model_dict[model_name]][useful_score] += 1 for i in range(num_models): print model_list[i] # print len(asins_so_far[i]) # print 'Avg on topic score: %.2f' % get_avg_score(on_topic_scores[i]) # print 'Avg grammaticality score: %.2f' % get_avg_score(is_grammatical_scores[i]) # print 'Avg specificity score: %.2f' % get_avg_score(is_specific_scores[i]) # print 'Avg new info score: %.2f' % get_avg_score(asks_new_info_scores[i]) # print 'Avg useful score: %.2f' % get_avg_score(useful_scores[i]) # print # print 'On topic:', on_topic_scores[i] # print 'Is grammatical: ', is_grammatical_scores[i] # print 'Is specific: ', is_specific_scores[i] # print 'Asks new info: ', asks_new_info_scores[i] print 'Useful: ', useful_scores[i] if __name__ == '__main__': argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--aggregate_results_v1", type = str) argparser.add_argument("--aggregate_results_v2", type=str) args = argparser.parse_args() print args print "" main(args)<file_sep>#!/bin/bash SITENAME=askubuntu_unix_superuser CQ_DATA_DIR=clarification_question_generation_pytorch/$SITENAME SCRIPT_DIR=clarification_question_generation_pytorch/src EMB_DIR=clarification_question_generation_pytorch/embeddings/$SITENAME python $SCRIPT_DIR/GAN_main.py --train_context $CQ_DATA_DIR/train_context.txt \ --train_ques $CQ_DATA_DIR/train_question.txt \ --train_ans $CQ_DATA_DIR/train_answer.txt \ --tune_context $CQ_DATA_DIR/tune_context.txt \ --tune_ques $CQ_DATA_DIR/tune_question.txt \ --tune_ans $CQ_DATA_DIR/tune_answer.txt \ --test_context $CQ_DATA_DIR/test_context.txt \ --test_ques $CQ_DATA_DIR/test_question.txt \ --test_ans $CQ_DATA_DIR/test_answer.txt \ --test_pred_ques $CQ_DATA_DIR/GAN_test_pred_question.txt \ --q_encoder_params $CQ_DATA_DIR/q_encoder_params.epoch100 \ --q_decoder_params $CQ_DATA_DIR/q_decoder_params.epoch100 \ --a_encoder_params $CQ_DATA_DIR/a_encoder_params.epoch100 \ --a_decoder_params $CQ_DATA_DIR/a_decoder_params.epoch100 \ --context_params $CQ_DATA_DIR/context_params.epoch10 \ --question_params $CQ_DATA_DIR/question_params.epoch10 \ --answer_params $CQ_DATA_DIR/answer_params.epoch10 \ --utility_params $CQ_DATA_DIR/utility_params.epoch10 \ --word_embeddings $EMB_DIR/word_embeddings.p \ --vocab $EMB_DIR/vocab.p \ --model GAN_selfcritic_pred_ans \ --max_post_len 100 \ --max_ques_len 20 \ --max_ans_len 20 \ --batch_size 256 \ --n_epochs 40 \ <file_sep>#!/bin/bash #SBATCH --job-name=candqs_Home_and_Kitchen #SBATCH --output=candqs_Home_and_Kitchen #SBATCH --qos=batch #SBATCH --mem=4g #SBATCH --time=4:00:00 SITENAME=Home_and_Kitchen METADATA_DIR=/fs/clip-corpora/amazon_qa #DATA_DIR=/fs/clip-corpora/amazon_qa/$SITENAME DATA_DIR=/fs/clip-scratch/raosudha/amazon_qa/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation/src-opennmt CQ_DATA_DIR=/fs/clip-scratch/raosudha/clarification_question_generation/data/amazon/$SITENAME mkdir $CQ_DATA_DIR #mkdir /fs/clip-corpora/amazon_qa/$SITENAME #mkdir /fs/clip-amr/clarification_question_generation/data/amazon/$SITENAME python $SCRIPT_DIR/create_amazon_data.py --prod_dir $DATA_DIR/prod_docs \ --ques_dir $DATA_DIR/ques_docs \ --metadata_fname $METADATA_DIR/meta_${SITENAME}.json.gz \ --sim_prod_fname $DATA_DIR/lucene_similar_prods.txt \ --sim_ques_fname $DATA_DIR/lucene_similar_ques.txt \ --train_src_fname $CQ_DATA_DIR/train_src \ --train_tgt_fname $CQ_DATA_DIR/train_tgt \ --tune_src_fname $CQ_DATA_DIR/tune_src \ --tune_tgt_fname $CQ_DATA_DIR/tune_tgt \ --test_src_fname $CQ_DATA_DIR/test_src \ --test_tgt_fname $CQ_DATA_DIR/test_tgt \ --train_ids_file $CQ_DATA_DIR/train_ids \ --tune_ids_file $CQ_DATA_DIR/tune_ids \ --test_ids_file $CQ_DATA_DIR/test_ids \ --candqs True\ #--onlycontext True \ #--simqs True \ #--template True \ #--nocontext True \ <file_sep>import argparse import sys, os from collections import defaultdict import csv import math import pdb import random def read_data(args): print("Reading lines...") posts = {} question_candidates = {} with open(args.post_data_tsvfile, 'rb') as tsvfile: post_reader = csv.reader(tsvfile, delimiter='\t') N = 0 for row in post_reader: if N == 0: N += 1 continue N += 1 post_id,title,post = row post = title + ' ' + post post = post.lower().strip() posts[post_id] = post with open(args.qa_data_tsvfile, 'rb') as tsvfile: qa_reader = csv.reader(tsvfile, delimiter='\t') i = 0 for row in qa_reader: if i == 0: i += 1 continue post_id,questions = row[0], row[2:11] #Ignore the first question since that is the true question question_candidates[post_id] = questions test_ids = [test_id.strip('\n') for test_id in open(args.test_ids_file, 'r').readlines()] lucene_out_file = open(args.lucene_output_file, 'w') for i, test_id in enumerate(test_ids): r = random.randint(0,8) lucene_out_file.write(question_candidates[test_id][r] + '\n') lucene_out_file.close() if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--post_data_tsvfile", type = str) argparser.add_argument("--qa_data_tsvfile", type = str) argparser.add_argument("--test_ids_file", type = str) argparser.add_argument("--lucene_output_file", type = str) args = argparser.parse_args() print args print "" read_data(args) <file_sep>#!/bin/bash #SBATCH --job-name=lucene_Home_and_Kitchen_test #SBATCH --output=lucene_Home_and_Kitchen_test #SBATCH --qos=batch #SBATCH --mem=4g #SBATCH --time=4:00:00 SITENAME=Home_and_Kitchen SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/lucene CQ_DATA_DIR=/fs/clip-amr/clarification_question_generation_pytorch/$SITENAME python $SCRIPT_DIR/create_amazon_lucene_baseline.py --ques_dir $CQ_DATA_DIR/ques_docs \ --sim_prod_fname $CQ_DATA_DIR/lucene_similar_prods.txt \ --test_ids_file $CQ_DATA_DIR/blind_test_pred_ques.txt.seq2seq.epoch100.beam0.ids \ --lucene_pred_fname $CQ_DATA_DIR/blind_test_pred_question.lucene.txt \ --metadata_fname $CQ_DATA_DIR/meta_Home_and_Kitchen.json.gz \ <file_sep>from attn import * from attnDecoderRNN import * from constants import * from encoderRNN import * from evaluate import * from helper import * from train import * import torch import torch.optim as optim from prepare_data import * def run_seq2seq(train_data, test_data, word2index, word_embeddings, encoder_params_file, decoder_params_file, encoder_params_contd_file, decoder_params_contd_file, max_target_length, n_epochs, batch_size, n_layers): # Initialize q models print('Initializing models') encoder = EncoderRNN(HIDDEN_SIZE, word_embeddings, n_layers, dropout=DROPOUT) decoder = AttnDecoderRNN(HIDDEN_SIZE, len(word2index), word_embeddings, n_layers) # Initialize optimizers encoder_optimizer = optim.Adam([par for par in encoder.parameters() if par.requires_grad], lr=LEARNING_RATE) decoder_optimizer = optim.Adam([par for par in decoder.parameters() if par.requires_grad], lr=LEARNING_RATE * DECODER_LEARNING_RATIO) # Move models to GPU if USE_CUDA: encoder.cuda() decoder.cuda() # Keep track of time elapsed and running averages start = time.time() print_loss_total = 0 # Reset every print_every epoch = 0.0 #epoch = 12.0 #print('Loading encoded, decoder params') #encoder.load_state_dict(torch.load(encoder_params_contd_file+'.epoch%d' % epoch)) #decoder.load_state_dict(torch.load(decoder_params_contd_file+'.epoch%d' % epoch)) ids_seqs, input_seqs, input_lens, output_seqs, output_lens = train_data n_batches = len(input_seqs) / batch_size teacher_forcing_ratio = 1.0 # decr = teacher_forcing_ratio/n_epochs prev_test_loss = None num_decrease = 0.0 while epoch < n_epochs: epoch += 1 for ids_seqs_batch, input_seqs_batch, input_lens_batch, \ output_seqs_batch, output_lens_batch in \ iterate_minibatches(ids_seqs, input_seqs, input_lens, output_seqs, output_lens, batch_size): start_time = time.time() # Run the train function loss = train( input_seqs_batch, input_lens_batch, output_seqs_batch, output_lens_batch, encoder, decoder, encoder_optimizer, decoder_optimizer, word2index[SOS_token], max_target_length, batch_size, teacher_forcing_ratio ) # Keep track of loss print_loss_total += loss # teacher_forcing_ratio = teacher_forcing_ratio - decr print_loss_avg = print_loss_total / n_batches print_loss_total = 0 print('Epoch: %d' % epoch) print('Train Set') print_summary = '%s %d %.4f' % (time_since(start, epoch / n_epochs), epoch, print_loss_avg) print(print_summary) print('Dev Set') curr_test_loss = evaluate(word2index, None, encoder, decoder, test_data, max_target_length, batch_size, None) print('%.4f ' % curr_test_loss) # if prev_test_loss is not None: # diff_test_loss = prev_test_loss - curr_test_loss # if diff_test_loss <= 0: # num_decrease += 1 # if num_decrease > 5: # print 'Early stopping' # print 'Saving model params' # torch.save(encoder.state_dict(), encoder_params_file + '.epoch%d' % epoch) # torch.save(decoder.state_dict(), decoder_params_file + '.epoch%d' % epoch) # return # if epoch % 5 == 0: print('Saving model params') torch.save(encoder.state_dict(), encoder_params_file+'.epoch%d' % epoch) torch.save(decoder.state_dict(), decoder_params_file+'.epoch%d' % epoch) <file_sep>import re import csv from constants import * import unicodedata from collections import defaultdict import math def unicode_to_ascii(s): return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' ) # Lowercase, trim, and remove non-letter characters def normalize_string(s, max_len): #s = unicode_to_ascii(s.lower().strip()) s = s.lower().strip() words = s.split() s = ' '.join(words[:max_len]) return s def get_context(line, max_post_len, max_ques_len): is_specific, is_generic = False, False if '<specific>' in line: line = line.replace(' <specific>', '') is_specific = True if '<generic>' in line: line = line.replace(' <generic>', '') is_generic = True if is_specific or is_generic: context = normalize_string(line, max_post_len-2) # one token space for specificity and another for EOS else: context = normalize_string(line, max_post_len-1) if is_specific: context = '<specific> ' + context if is_generic: context += '<generic> ' + context return context def read_data(context_fname, question_fname, answer_fname, ids_fname, max_post_len, max_ques_len, max_ans_len, count=None, mode='train'): if ids_fname is not None: ids = [] for line in open(ids_fname, 'r').readlines(): curr_id = line.strip('\n') ids.append(curr_id) print("Reading lines...") data = [] i = 0 for line in open(context_fname, 'r').readlines(): context = get_context(line, max_post_len, max_ques_len) if ids_fname is not None: data.append([ids[i], context, None, None]) else: data.append([None, context, None, None]) i += 1 if count and i == count: break i = 0 for line in open(question_fname, 'r').readlines(): question = normalize_string(line, max_ques_len-1) data[i][2] = question i += 1 if count and i == count: break assert(i == len(data)) if answer_fname is not None: i = 0 for line in open(answer_fname, 'r').readlines(): answer = normalize_string(line, max_ans_len-1) # one token space for EOS data[i][3] = answer i += 1 if count and i == count: break assert(i == len(data)) if ids_fname is not None: updated_data = [] i = 0 if mode == 'test': max_per_id_count = 1 else: max_per_id_count = 20 data_ct_per_id = defaultdict(int) for curr_id in ids: data_ct_per_id[curr_id] += 1 if data_ct_per_id[curr_id] <= max_per_id_count: updated_data.append(data[i]) i += 1 if count and i == count: break assert (i == len(data)) return updated_data return data <file_sep>from constants import * import math import numpy as np import nltk import time import torch def as_minutes(s): m = math.floor(s / 60) s -= m * 60 return '%dm %ds' % (m, s) def time_since(since, percent): now = time.time() s = now - since es = s / (percent) rs = es - s return '%s (- %s)' % (as_minutes(s), as_minutes(rs)) def iterate_minibatches(p, pl, q, ql, pq, pql, a, al, batch_size, shuffle=True): if shuffle: indices = np.arange(len(p)) np.random.shuffle(indices) for start_idx in range(0, len(p) - batch_size + 1, batch_size): if shuffle: ex = indices[start_idx:start_idx + batch_size] else: ex = slice(start_idx, start_idx + batch_size) yield np.array(p)[ex], np.array(pl)[ex], np.array(q)[ex], np.array(ql)[ex], \ np.array(pq)[ex], np.array(pql)[ex], np.array(a)[ex], np.array(al)[ex] def reverse_dict(word2index): index2word = {} for w in word2index: ix = word2index[w] index2word[ix] = w return index2word def calculate_bleu(true, true_lens, pred, pred_lens, index2word, max_len): sent_bleu_scores = torch.zeros(len(pred)) for i in range(len(pred)): true_sent = [index2word[idx] for idx in true[i][:true_lens[i]]] pred_sent = [index2word[idx] for idx in pred[i][:pred_lens[i]]] sent_bleu_scores[i] = nltk.translate.bleu_score.sentence_bleu(true_sent, pred_sent) if USE_CUDA: sent_bleu_scores = sent_bleu_scores.cuda() return sent_bleu_scores <file_sep>#!/bin/bash #SBATCH --job-name=create_crowdflower_HK_compare_batchD #SBATCH --output=create_crowdflower_HK_compare_batchD #SBATCH --qos=batch #SBATCH --mem=32g #SBATCH --time=4:00:00 SITENAME=Home_and_Kitchen CORPORA_DIR=/fs/clip-corpora/amazon_qa DATA_DIR=/fs/clip-amr/clarification_question_generation_pytorch/$SITENAME CROWDFLOWER_DIR=/fs/clip-amr/clarification_question_generation_pytorch/evaluation/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/evaluation export PATH="/fs/clip-amr/anaconda2/bin:$PATH" python $SCRIPT_DIR/create_crowdflower_data_compare_ques.py --qa_data_fname $CORPORA_DIR/qa_${SITENAME}.json.gz \ --metadata_fname $CORPORA_DIR/meta_${SITENAME}.json.gz \ --csv_file $CROWDFLOWER_DIR/crowdflower_compare_ques_batchD_100.csv \ --train_asins $DATA_DIR/train_asin.txt \ --previous_csv_file_v1 $CROWDFLOWER_DIR/crowdflower_compare_ques_batchA_100.csv \ --previous_csv_file_v2 $CROWDFLOWER_DIR/crowdflower_compare_ques_allpairs.csv \ --previous_csv_file_v3 $CROWDFLOWER_DIR/crowdflower_compare_ques_batchB_100.csv \ --previous_csv_file_v4 $CROWDFLOWER_DIR/crowdflower_compare_ques_batchC_100.csv \ <file_sep>import argparse import gzip import nltk import pdb import sys from collections import defaultdict import csv import random model_list = ['ref', 'lucene', 'seq2seq.beam', 'rl.beam', 'gan.beam'] model_dict = {'ref': 0, 'lucene': 1, 'seq2seq.beam': 2, 'rl.beam': 3, 'gan.beam': 4} def parse(path): g = gzip.open(path, 'r') for l in g: yield eval(l) def main(args): csv_file = open(args.output_csv_file, 'w') writer = csv.writer(csv_file, delimiter=',') writer.writerow(['asin', 'title', 'description', 'model_name', 'question']) all_rows = [] asins_so_far = defaultdict(list) with open(args.previous_csv_file) as csvfile: reader = csv.DictReader(csvfile) for row in reader: asin = row['asin'] if row['model_name'] not in model_list: continue if asin not in asins_so_far[row['model_name']]: asins_so_far[row['model_name']].append(asin) else: print 'Duplicate asin %s in %s' % (asin, row['model_name']) continue all_rows.append([row['asin'], row['title'], row['description'], row['model_name'], row['question']]) random.shuffle(all_rows) for row in all_rows: writer.writerow(row) csv_file.close() if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--previous_csv_file", type=str) argparser.add_argument("--output_csv_file", type=str) args = argparser.parse_args() print args print "" main(args) <file_sep>from constants import * from masked_cross_entropy import * import numpy as np import random import torch from torch.autograd import Variable from constants import * def train(input_batches, input_lens, target_batches, target_lens, encoder, decoder, encoder_optimizer, decoder_optimizer, word2index, args, mode='train'): if mode == 'train': encoder.train() decoder.train() # Zero gradients of both optimizers encoder_optimizer.zero_grad() decoder_optimizer.zero_grad() if USE_CUDA: input_batches = Variable(torch.LongTensor(np.array(input_batches)).cuda()).transpose(0, 1) target_batches = Variable(torch.LongTensor(np.array(target_batches)).cuda()).transpose(0, 1) else: input_batches = Variable(torch.LongTensor(np.array(input_batches))).transpose(0, 1) target_batches = Variable(torch.LongTensor(np.array(target_batches))).transpose(0, 1) # Run post words through encoder encoder_outputs, encoder_hidden = encoder(input_batches, input_lens, None) # Prepare input and output variables decoder_hidden = encoder_hidden[:decoder.n_layers] + encoder_hidden[decoder.n_layers:] if USE_CUDA: decoder_input = Variable(torch.LongTensor([word2index[SOS_token]] * args.batch_size).cuda()) all_decoder_outputs = Variable(torch.zeros(args.max_ans_len, args.batch_size, decoder.output_size).cuda()) decoder_outputs = Variable(torch.zeros(args.max_ans_len, args.batch_size).cuda()) else: decoder_input = Variable(torch.LongTensor([word2index[SOS_token]] * args.batch_size)) all_decoder_outputs = Variable(torch.zeros(args.max_ans_len, args.batch_size, decoder.output_size)) decoder_outputs = Variable(torch.zeros(args.max_ans_len, args.batch_size)) # Run through decoder one time step at a time for t in range(args.max_ans_len): decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden, encoder_outputs) all_decoder_outputs[t] = decoder_output # Teacher Forcing decoder_input = target_batches[t] # Next input is current target decoder_outputs[t] = target_batches[t] # # Greeding # topv, topi = decoder_output.data.topk(1) # decoder_outputs[t] = topi.squeeze(1) decoded_seqs = [] decoded_lens = [] for b in range(args.batch_size): decoded_seq = [] for t in range(args.max_ans_len): topi = decoder_outputs[t][b].data idx = int(topi.item()) if idx == word2index[EOS_token]: decoded_seq.append(idx) break else: decoded_seq.append(idx) decoded_lens.append(len(decoded_seq)) decoded_seq += [word2index[PAD_token]] * (args.max_ans_len - len(decoded_seq)) decoded_seqs.append(decoded_seq) loss_fn = torch.nn.NLLLoss() # Loss calculation and backpropagation loss = masked_cross_entropy( all_decoder_outputs.transpose(0, 1).contiguous(), # -> batch x seq target_batches.transpose(0, 1).contiguous(), # -> batch x seq target_lens, loss_fn, args.max_ans_len ) if mode == 'train': loss.backward() encoder_optimizer.step() decoder_optimizer.step() return loss, decoded_seqs, decoded_lens <file_sep>from constants import * from masked_cross_entropy import * import numpy as np import random import torch from torch.autograd import Variable def train(input_batches, input_lens, target_batches, target_lens, encoder, decoder, encoder_optimizer, decoder_optimizer, SOS_idx, max_target_length, batch_size, teacher_forcing_ratio): # Zero gradients of both optimizers encoder_optimizer.zero_grad() decoder_optimizer.zero_grad() if USE_CUDA: input_batches = Variable(torch.LongTensor(np.array(input_batches)).cuda()).transpose(0, 1) target_batches = Variable(torch.LongTensor(np.array(target_batches)).cuda()).transpose(0, 1) else: input_batches = Variable(torch.LongTensor(np.array(input_batches))).transpose(0, 1) target_batches = Variable(torch.LongTensor(np.array(target_batches))).transpose(0, 1) # Run post words through encoder encoder_outputs, encoder_hidden = encoder(input_batches, input_lens, None) # Prepare input and output variables decoder_hidden = encoder_hidden[:decoder.n_layers] + encoder_hidden[decoder.n_layers:] if USE_CUDA: decoder_input = Variable(torch.LongTensor([SOS_idx] * batch_size).cuda()) all_decoder_outputs = Variable(torch.zeros(max_target_length, batch_size, decoder.output_size).cuda()) else: decoder_input = Variable(torch.LongTensor([SOS_idx] * batch_size)) all_decoder_outputs = Variable(torch.zeros(max_target_length, batch_size, decoder.output_size)) use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False # Run through decoder one time step at a time for t in range(max_target_length): decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden, encoder_outputs) all_decoder_outputs[t] = decoder_output if use_teacher_forcing: # Teacher Forcing decoder_input = target_batches[t] # Next input is current target else: # Greeding decoding for b in range(batch_size): topi = decoder_output[b].topk(1)[1][0] decoder_input[b] = topi.squeeze().detach() loss_fn = torch.nn.NLLLoss() # Loss calculation and backpropagation loss = masked_cross_entropy( all_decoder_outputs.transpose(0, 1).contiguous(), # -> batch x seq target_batches.transpose(0, 1).contiguous(), # -> batch x seq target_lens, loss_fn, max_target_length ) loss.backward() encoder_optimizer.step() decoder_optimizer.step() return loss.item() <file_sep>#!/bin/bash SITENAME=Home_and_Kitchen CQ_DATA_DIR=clarification_question_generation_pytorch/$SITENAME SCRIPT_DIR=clarification_question_generation_pytorch/src EMB_DIR=clarification_question_generation_pytorch/embeddings/$SITENAME PARAMS_DIR=$CQ_DATA_DIR python $SCRIPT_DIR/decode.py --test_context $CQ_DATA_DIR/test_context.txt \ --test_ques $CQ_DATA_DIR/test_ques.txt \ --test_ans $CQ_DATA_DIR/test_ans.txt \ --test_ids $CQ_DATA_DIR/test_asin.txt \ --test_pred_ques $CQ_DATA_DIR/blind_test_pred_ques.txt \ --q_encoder_params $PARAMS_DIR/q_encoder_params.epoch100.RL_selfcritic.epoch8 \ --q_decoder_params $PARAMS_DIR/q_decoder_params.epoch100.RL_selfcritic.epoch8 \ --word_embeddings $EMB_DIR/word_embeddings.p \ --vocab $EMB_DIR/vocab.p \ --model RL_selfcritic.epoch8 \ --max_post_len 100 \ --max_ques_len 20 \ --max_ans_len 20 \ --batch_size 128 \ --beam True <file_sep>import argparse import pickle as p import sys import torch import torch.nn as nn from torch import optim from seq2seq.encoderRNN import * from seq2seq.attnDecoderRNN import * from seq2seq.read_data import * from seq2seq.prepare_data import * from seq2seq.RL_train import * from seq2seq.RL_beam_decoder import * from seq2seq.baselineFF import * from utility.RNN import * from utility.FeedForward import * from utility.RL_train import * from RL_helper import * from constants import * def main(args): word_embeddings = p.load(open(args.word_embeddings, 'rb')) word_embeddings = np.array(word_embeddings) word2index = p.load(open(args.vocab, 'rb')) index2word = reverse_dict(word2index) train_data = read_data(args.train_context, args.train_question, args.train_answer, args.train_ids, # args.max_post_len, args.max_ques_len, args.max_ans_len, count=args.batch_size*5) args.max_post_len, args.max_ques_len, args.max_ans_len) if args.tune_ids is not None: test_data = read_data(args.tune_context, args.tune_question, args.tune_answer, args.tune_ids, args.max_post_len, args.max_ques_len, args.max_ans_len) else: test_data = read_data(args.tune_context, args.tune_question, args.tune_answer, None, # args.max_post_len, args.max_ques_len, args.max_ans_len, count=args.batch_size*2) args.max_post_len, args.max_ques_len, args.max_ans_len) print 'No. of train_data %d' % len(train_data) print 'No. of test_data %d' % len(test_data) run_model(train_data, test_data, word_embeddings, word2index, index2word, args) def run_model(train_data, test_data, word_embeddings, word2index, index2word, args): print 'Preprocessing train data..' tr_id_seqs, tr_post_seqs, tr_post_lens, tr_ques_seqs, tr_ques_lens, \ tr_post_ques_seqs, tr_post_ques_lens, tr_ans_seqs, tr_ans_lens = preprocess_data(train_data, word2index, args.max_post_len, args.max_ques_len, args.max_ans_len) print 'Preprocessing test data..' te_id_seqs, te_post_seqs, te_post_lens, te_ques_seqs, te_ques_lens, \ te_post_ques_seqs, te_post_ques_lens, te_ans_seqs, te_ans_lens = preprocess_data(test_data, word2index, args.max_post_len, args.max_ques_len, args.max_ans_len) print 'Defining encoder decoder models' q_encoder = EncoderRNN(HIDDEN_SIZE, word_embeddings, n_layers=2, dropout=DROPOUT) q_decoder = AttnDecoderRNN(HIDDEN_SIZE, len(word2index), word_embeddings, n_layers=2) a_encoder = EncoderRNN(HIDDEN_SIZE, word_embeddings, n_layers=2, dropout=DROPOUT) a_decoder = AttnDecoderRNN(HIDDEN_SIZE, len(word2index), word_embeddings, n_layers=2) if USE_CUDA: device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') q_encoder = q_encoder.to(device) q_decoder = q_decoder.to(device) a_encoder = a_encoder.to(device) a_decoder = a_decoder.to(device) # Load encoder, decoder params print 'Loading encoded, decoder params' q_encoder.load_state_dict(torch.load(args.q_encoder_params)) q_decoder.load_state_dict(torch.load(args.q_decoder_params)) a_encoder.load_state_dict(torch.load(args.a_encoder_params)) a_decoder.load_state_dict(torch.load(args.a_decoder_params)) # out_fname = args.test_pred_question+'.pretrained' # evaluate_beam(word2index, index2word, q_encoder, q_decoder, # te_post_seqs, te_post_lens, te_ques_seqs, te_ques_lens, # args.batch_size, args.max_ques_len, out_fname) q_encoder_optimizer = optim.Adam([par for par in q_encoder.parameters() if par.requires_grad], lr=LEARNING_RATE) q_decoder_optimizer = optim.Adam([par for par in q_decoder.parameters() if par.requires_grad], lr=LEARNING_RATE * DECODER_LEARNING_RATIO) a_encoder_optimizer = optim.Adam([par for par in a_encoder.parameters() if par.requires_grad], lr=LEARNING_RATE) a_decoder_optimizer = optim.Adam([par for par in a_decoder.parameters() if par.requires_grad], lr=LEARNING_RATE * DECODER_LEARNING_RATIO) context_model = RNN(len(word_embeddings), len(word_embeddings[0]), n_layers=1) question_model = RNN(len(word_embeddings), len(word_embeddings[0]), n_layers=1) answer_model = RNN(len(word_embeddings), len(word_embeddings[0]), n_layers=1) utility_model = FeedForward(HIDDEN_SIZE*3*2) baseline_model = BaselineFF(HIDDEN_SIZE) if USE_CUDA: device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') context_model.to(device) question_model.to(device) answer_model.to(device) utility_model.to(device) baseline_model.to(device) # Load utility calculator model params print 'Loading utility model params' context_model.load_state_dict(torch.load(args.context_params)) question_model.load_state_dict(torch.load(args.question_params)) answer_model.load_state_dict(torch.load(args.answer_params)) utility_model.load_state_dict(torch.load(args.utility_params)) for param in context_model.parameters(): param.requires_grad = False for param in question_model.parameters(): param.requires_grad = False for param in answer_model.parameters(): param.requires_grad = False for param in utility_model.parameters(): param.requires_grad = False baseline_optimizer = optim.Adam(baseline_model.parameters()) baseline_criterion = torch.nn.MSELoss() epoch = 0. start = time.time() n_batches = len(tr_post_seqs)/args.batch_size mixer_delta = args.max_ques_len while epoch < args.n_epochs: epoch += 1 total_loss = 0. total_xe_loss = 0. total_rl_loss = 0. total_u_pred = 0. total_u_b_pred = 0. if mixer_delta >= 2: mixer_delta = mixer_delta - 2 batch_num = 0 for post, pl, ques, ql, pq, pql, ans, al in iterate_minibatches(tr_post_seqs, tr_post_lens, tr_ques_seqs, tr_ques_lens, tr_post_ques_seqs, tr_post_ques_lens, tr_ans_seqs, tr_ans_lens, args.batch_size): batch_num += 1 xe_loss, rl_loss, reward, b_reward = train(post, pl, ques, ql, ans, al, q_encoder, q_decoder, q_encoder_optimizer, q_decoder_optimizer, a_encoder, a_decoder, a_encoder_optimizer, a_decoder_optimizer, baseline_model, baseline_optimizer, baseline_criterion, context_model, question_model, answer_model, utility_model, word2index, index2word, mixer_delta, args) total_u_pred += reward.data.sum() / args.batch_size total_u_b_pred += b_reward.data.sum() / args.batch_size total_xe_loss += xe_loss total_rl_loss += rl_loss print_loss_avg = total_loss / n_batches print_xe_loss_avg = total_xe_loss / n_batches print_rl_loss_avg = total_rl_loss / n_batches print_u_pred_avg = total_u_pred / n_batches print_u_b_pred_avg = total_u_b_pred / n_batches print_summary = '%s %d Loss: %.4f XE_loss: %.4f RL_loss: %.4f U_pred: %.4f B_pred: %.4f' % \ (time_since(start, epoch / args.n_epochs), epoch, print_loss_avg, print_xe_loss_avg, print_rl_loss_avg, print_u_pred_avg, print_u_b_pred_avg) print(print_summary) print 'Saving RL model params' torch.save(q_encoder.state_dict(), args.q_encoder_params + '.' + args.model + '.epoch%d' % epoch) torch.save(q_decoder.state_dict(), args.q_decoder_params + '.' + args.model + '.epoch%d' % epoch) torch.save(a_encoder.state_dict(), args.a_encoder_params + '.' + args.model + '.epoch%d' % epoch) torch.save(a_decoder.state_dict(), args.a_decoder_params + '.' + args.model + '.epoch%d' % epoch) # print 'Running evaluation...' # out_fname = args.test_pred_question + '.' + args.model + '.epoch%d' % int(epoch) # evaluate_beam(word2index, index2word, q_encoder, q_decoder, # te_post_seqs, te_post_lens, te_ques_seqs, te_ques_lens, # args.batch_size, args.max_ques_len, out_fname) if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--train_context", type = str) argparser.add_argument("--train_question", type = str) argparser.add_argument("--train_answer", type = str) argparser.add_argument("--train_ids", type=str) argparser.add_argument("--tune_context", type = str) argparser.add_argument("--tune_question", type = str) argparser.add_argument("--tune_answer", type = str) argparser.add_argument("--tune_ids", type=str) argparser.add_argument("--test_context", type = str) argparser.add_argument("--test_question", type = str) argparser.add_argument("--test_answer", type = str) argparser.add_argument("--test_ids", type=str) argparser.add_argument("--test_pred_question", type = str) argparser.add_argument("--q_encoder_params", type = str) argparser.add_argument("--q_decoder_params", type = str) argparser.add_argument("--a_encoder_params", type = str) argparser.add_argument("--a_decoder_params", type = str) argparser.add_argument("--context_params", type = str) argparser.add_argument("--question_params", type = str) argparser.add_argument("--answer_params", type = str) argparser.add_argument("--utility_params", type = str) argparser.add_argument("--vocab", type = str) argparser.add_argument("--word_embeddings", type = str) argparser.add_argument("--max_post_len", type = int, default=300) argparser.add_argument("--max_ques_len", type = int, default=50) argparser.add_argument("--max_ans_len", type = int, default=50) argparser.add_argument("--n_epochs", type = int, default=20) argparser.add_argument("--batch_size", type = int, default=128) argparser.add_argument("--model", type=str) args = argparser.parse_args() print args print "" main(args) <file_sep>#!/bin/bash #SBATCH --job-name=lucene_data_Home_and_Kitchen #SBATCH --output=lucene_data_Home_and_Kitchen #SBATCH --qos=batch #SBATCH --mem=36g #SBATCH --time=24:00:00 SITENAME=Home_and_Kitchen DATA_DIR=/fs/clip-corpora/amazon_qa SCRATCH_DATA_DIR=/fs/clip-scratch/raosudha/amazon_qa SCRIPT_DIR=/fs/clip-amr/clarification_question_generation/src rm -r $SCRATCH_DATA_DIR/${SITENAME}/prod_docs/ rm -r $SCRATCH_DATA_DIR/${SITENAME}/ques_docs/ mkdir -p $SCRATCH_DATA_DIR/${SITENAME}/prod_docs/ mkdir -p $SCRATCH_DATA_DIR/${SITENAME}/ques_docs/ export PATH="/fs/clip-amr/anaconda2/bin:$PATH" python $SCRIPT_DIR/create_lucene_amazon.py --qa_data_fname $DATA_DIR/qa_${SITENAME}.json.gz \ --metadata_fname $DATA_DIR/meta_${SITENAME}.json.gz \ --product_dir $SCRATCH_DATA_DIR/${SITENAME}/prod_docs/ \ --question_dir $SCRATCH_DATA_DIR/${SITENAME}/ques_docs/ <file_sep>#!/bin/bash #SBATCH --job-name=pqa_data_aus #SBATCH --output=pqa_data_aus #SBATCH --qos=batch #SBATCH --mem=36g #SBATCH --time=24:00:00 SITENAME=askubuntu_unix_superuser DATA_DIR=/fs/clip-amr/ranking_clarification_questions/data/$SITENAME CQ_DATA_DIR=/fs/clip-amr/clarification_question_generation_pytorch/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src python $SCRIPT_DIR/create_pqa_data.py --post_data_tsvfile $DATA_DIR/post_data.tsv \ --qa_data_tsvfile $DATA_DIR/qa_data.tsv \ --train_ids_file $DATA_DIR/train_ids \ --tune_ids_file $DATA_DIR/tune_ids \ --test_ids_file $DATA_DIR/test_ids \ --train_context_fname $CQ_DATA_DIR/train_context.txt \ --train_question_fname $CQ_DATA_DIR/train_question.txt \ --train_answer_fname $CQ_DATA_DIR/train_answer.txt \ --tune_context_fname $CQ_DATA_DIR/tune_context.txt \ --tune_question_fname $CQ_DATA_DIR/tune_question.txt \ --tune_answer_fname $CQ_DATA_DIR/tune_answer.txt \ --test_context_fname $CQ_DATA_DIR/test_context.txt \ --test_question_fname $CQ_DATA_DIR/test_question.txt \ --test_answer_fname $CQ_DATA_DIR/test_answer.txt \ <file_sep>import argparse import csv import sys, os, pdb import nltk import time def get_annotations(line): set_info, post_id, best, valids, confidence = line.split(',') annotator_name = set_info.split('_')[0] sitename = set_info.split('_')[1] best = int(best) valids = [int(v) for v in valids.split()] confidence = int(confidence) return post_id, annotator_name, sitename, best, valids, confidence def read_human_annotations(human_annotations_filename): human_annotations_file = open(human_annotations_filename, 'r') annotations = {} for line in human_annotations_file.readlines(): line = line.strip('\n') splits = line.split('\t') post_id1, annotator_name1, sitename1, best1, valids1, confidence1 = get_annotations(splits[0]) post_id2, annotator_name2, sitename2, best2, valids2, confidence2 = get_annotations(splits[1]) assert(sitename1 == sitename2) assert(post_id1 == post_id2) post_id = sitename1+'_'+post_id1 best_union = list(set([best1, best2])) valids_inter = list(set(valids1).intersection(set(valids2))) annotations[post_id] = list(set(best_union + valids_inter)) return annotations def main(args): question_candidates = {} model_outputs = [] test_ids = [test_id.strip('\n') for test_id in open(args.test_ids_file, 'r').readlines()] with open(args.qa_data_tsvfile, 'rb') as tsvfile: qa_reader = csv.reader(tsvfile, delimiter='\t') i = 0 for row in qa_reader: if i == 0: i += 1 continue post_id,questions = row[0], row[1:11] question_candidates[post_id] = questions annotations = read_human_annotations(args.human_annotations) model_output_file = open(args.model_output_file, 'r') for line in model_output_file.readlines(): model_outputs.append(line.strip('\n')) pred_file = open(args.model_output_file+'.hasrefs', 'w') for i, post_id in enumerate(test_ids): if post_id not in annotations: continue pred_file.write(model_outputs[i]+'\n') if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--qa_data_tsvfile", type = str) argparser.add_argument("--human_annotations", type = str) argparser.add_argument("--model_output_file", type = str) argparser.add_argument("--test_ids_file", type = str) args = argparser.parse_args() print args print "" main(args) <file_sep>#!/bin/bash #SBATCH --job-name=emb_data_Home_and_Kitchen #SBATCH --output=emb_data_Home_and_Kitchen #SBATCH --qos=batch #SBATCH --mem=36g #SBATCH --time=24:00:00 SITENAME=Home_and_Kitchen DATA_DIR=/fs/clip-corpora/amazon_qa EMB_DATA_DIR=/fs/clip-amr/clarification_question_generation_pytorch/embeddings/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/embedding_generation python $SCRIPT_DIR/extract_amazon_data.py --qa_data_fname $DATA_DIR/qa_${SITENAME}.json.gz \ --metadata_fname $DATA_DIR/meta_${SITENAME}.json.gz \ --output_fname $EMB_DATA_DIR/${SITENAME}_data.txt <file_sep>#!/bin/bash #SBATCH --job-name=create_crowdflower_HK_beam #SBATCH --output=create_crowdflower_HK_beam #SBATCH --qos=batch #SBATCH --mem=32g #SBATCH --time=4:00:00 SITENAME=Home_and_Kitchen CORPORA_DIR=/fs/clip-corpora/amazon_qa DATA_DIR=/fs/clip-scratch/raosudha/clarification_question_generation/joint_learning/$SITENAME CROWDFLOWER_DIR=/fs/clip-amr/clarification_question_generation_pytorch/evaluation/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/evaluation export PATH="/fs/clip-amr/anaconda2/bin:$PATH" python $SCRIPT_DIR/create_crowdflower_data_beam.py --previous_csv_file $CROWDFLOWER_DIR/crowdflower_lucene_seq2seq_rl_gan_diverse_beam_seq2seq_beam_gan_beam_rl_beam_epoch8.batch1.aggregate.csv \ --output_csv_file $CROWDFLOWER_DIR/crowdflower_lucene_seq2seq_rl_gan_beam.batch1.csv \<file_sep>#!/bin/bash SITENAME=Home_and_Kitchen DATA_DIR=/fs/clip-corpora/amazon_qa OLD_CQ_DATA_DIR=/fs/clip-amr/clarification_question_generation/data/amazon/$SITENAME CQ_DATA_DIR=/fs/clip-scratch/raosudha/clarification_question_generation/joint_learning/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src export PATH="/fs/clip-amr/anaconda2/bin:$PATH" python $SCRIPT_DIR/filter_amazon_data_byid.py --train_ids $CQ_DATA_DIR/train_asin.txt \ --train_answer $CQ_DATA_DIR/train_answer.txt \ --train_candqs_ids $OLD_CQ_DATA_DIR/train_tgt_candqs.txt.ids \ --train_answer_candqs $CQ_DATA_DIR/train_answer_candqs.txt \ <file_sep>#!/bin/bash #SBATCH --job-name=meteor #SBATCH --output=meteor #SBATCH --qos=batch #SBATCH --mem=4g #SBATCH --time=4:00:00 SITENAME=askubuntu_unix_superuser METEOR=/fs/clip-software/user-supported/meteor-1.5 CQ_DATA_DIR=/fs/clip-amr/clarification_question_generation_pytorch/$SITENAME RESULTS_DIR=/fs/clip-amr/clarification_question_generation_pytorch/evaluation/results/$SITENAME TEST_SET=test_pred_question.txt.RL_selfcritic.epoch8.hasrefs.nounks java -Xmx2G -jar $METEOR/meteor-1.5.jar $CQ_DATA_DIR/$TEST_SET $CQ_DATA_DIR/test_ref_combined \ -l en -norm -r 6 \ > $RESULTS_DIR/${TEST_SET}.meteor <file_sep>#!/bin/bash SITENAME=Home_and_Kitchen CQ_DATA_DIR=clarification_question_generation_pytorch/$SITENAME SCRIPT_DIR=clarification_question_generation_pytorch/src EMB_DIR=clarification_question_generation_pytorch/embeddings/$SITENAME PARAMS_DIR=$CQ_DATA_DIR python $SCRIPT_DIR/main.py --train_context $CQ_DATA_DIR/train_context.txt \ --train_ques $CQ_DATA_DIR/train_ques.txt \ --train_ans $CQ_DATA_DIR/train_ans.txt \ --train_ids $CQ_DATA_DIR/train_asin.txt \ --tune_context $CQ_DATA_DIR/tune_context.txt \ --tune_ques $CQ_DATA_DIR/tune_ques.txt \ --tune_ans $CQ_DATA_DIR/tune_ans.txt \ --tune_ids $CQ_DATA_DIR/tune_asin.txt \ --test_context $CQ_DATA_DIR/test_context.txt \ --test_ques $CQ_DATA_DIR/test_ques.txt \ --test_ans $CQ_DATA_DIR/test_ans.txt \ --test_ids $CQ_DATA_DIR/test_asin.txt \ --q_encoder_params $PARAMS_DIR/q_encoder_params \ --q_decoder_params $PARAMS_DIR/q_decoder_params \ --a_encoder_params $PARAMS_DIR/a_encoder_params \ --a_decoder_params $PARAMS_DIR/a_decoder_params \ --context_params $PARAMS_DIR/context_params \ --question_params $PARAMS_DIR/question_params \ --answer_params $PARAMS_DIR/answer_params \ --utility_params $PARAMS_DIR/utility_params \ --word_embeddings $EMB_DIR/word_embeddings.p \ --vocab $EMB_DIR/vocab.p \ --n_epochs 100 \ --max_post_len 100 \ --max_ques_len 20 \ --max_ans_len 20 \ --pretrain_ans True \ <file_sep>import argparse import os import pickle as p import string import time import datetime import math import sys import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence#, masked_cross_entropy import numpy as np from seq2seq.read_data import * from seq2seq.prepare_data import * from seq2seq.masked_cross_entropy import * from seq2seq.main import * from utility.main import * from constants import * def update_embs(word2index, word_embeddings): word_embeddings[word2index[PAD_token]] = nn.init.normal_(torch.empty(1, len(word_embeddings[0]))) word_embeddings[word2index[SOS_token]] = nn.init.normal_(torch.empty(1, len(word_embeddings[0]))) word_embeddings[word2index[EOP_token]] = nn.init.normal_(torch.empty(1, len(word_embeddings[0]))) word_embeddings[word2index[EOS_token]] = nn.init.normal_(torch.empty(1, len(word_embeddings[0]))) return word_embeddings def main(args): word_embeddings = p.load(open(args.word_embeddings, 'rb')) word_embeddings = np.array(word_embeddings) word2index = p.load(open(args.vocab, 'rb')) #word_embeddings = update_embs(word2index, word_embeddings) --> updating embs gives poor utility results (0.5 acc) index2word = reverse_dict(word2index) train_data = read_data(args.train_context, args.train_question, args.train_answer, args.train_ids, args.max_post_len, args.max_ques_len, args.max_ans_len) if args.tune_ids is not None: test_data = read_data(args.tune_context, args.tune_question, args.tune_answer, args.tune_ids, args.max_post_len, args.max_ques_len, args.max_ans_len) else: test_data = read_data(args.tune_context, args.tune_question, args.tune_answer, None, args.max_post_len, args.max_ques_len, args.max_ans_len) print('No. of train_data %d' % len(train_data)) print('No. of test_data %d' % len(test_data)) ids_seqs, post_seqs, post_lens, ques_seqs, ques_lens, post_ques_seqs, post_ques_lens, ans_seqs, ans_lens = \ preprocess_data(train_data, word2index, args.max_post_len, args.max_ques_len, args.max_ans_len) q_train_data = ids_seqs, post_seqs, post_lens, ques_seqs, ques_lens a_train_data = ids_seqs, post_ques_seqs, post_ques_lens, ans_seqs, ans_lens u_train_data = ids_seqs, post_seqs, post_lens, ques_seqs, ques_lens, ans_seqs, ans_lens ids_seqs, post_seqs, post_lens, ques_seqs, ques_lens, post_ques_seqs, post_ques_lens, ans_seqs, ans_lens = \ preprocess_data(test_data, word2index, args.max_post_len, args.max_ques_len, args.max_ans_len) q_test_data = ids_seqs, post_seqs, post_lens, ques_seqs, ques_lens a_test_data = ids_seqs, post_ques_seqs, post_ques_lens, ans_seqs, ans_lens u_test_data = ids_seqs, post_seqs, post_lens, ques_seqs, ques_lens, ans_seqs, ans_lens if args.pretrain_ques: run_seq2seq(q_train_data, q_test_data, word2index, word_embeddings, args.q_encoder_params, args.q_decoder_params, args.q_encoder_params_contd, args.q_decoder_params_contd, args.max_ques_len, args.n_epochs, args.batch_size, n_layers=2) elif args.pretrain_ans: run_seq2seq(a_train_data, a_test_data, word2index, word_embeddings, args.a_encoder_params, args.a_decoder_params, args.a_encoder_params_contd, args.a_decoder_params_contd, args.max_ans_len, args.n_epochs, args.batch_size, n_layers=2) elif args.pretrain_util: run_utility(u_train_data, u_test_data, word_embeddings, index2word, args, n_layers=1) else: print('Please specify model to pretrain') return if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--train_context", type = str) argparser.add_argument("--train_question", type = str) argparser.add_argument("--train_answer", type = str) argparser.add_argument("--train_ids", type=str) argparser.add_argument("--tune_context", type = str) argparser.add_argument("--tune_question", type = str) argparser.add_argument("--tune_answer", type = str) argparser.add_argument("--tune_ids", type=str) argparser.add_argument("--test_context", type = str) argparser.add_argument("--test_question", type = str) argparser.add_argument("--test_answer", type = str) argparser.add_argument("--test_ids", type=str) argparser.add_argument("--q_encoder_params_contd", type = str) argparser.add_argument("--q_decoder_params_contd", type = str) argparser.add_argument("--a_encoder_params_contd", type = str) argparser.add_argument("--a_decoder_params_contd", type = str) argparser.add_argument("--q_encoder_params", type = str) argparser.add_argument("--q_decoder_params", type = str) argparser.add_argument("--a_encoder_params", type = str) argparser.add_argument("--a_decoder_params", type = str) argparser.add_argument("--context_params", type = str) argparser.add_argument("--question_params", type = str) argparser.add_argument("--answer_params", type = str) argparser.add_argument("--utility_params", type = str) argparser.add_argument("--vocab", type = str) argparser.add_argument("--word_embeddings", type = str) argparser.add_argument("--pretrain_ques", type = bool) argparser.add_argument("--pretrain_ans", type = bool) argparser.add_argument("--pretrain_util", type = bool) argparser.add_argument("--max_post_len", type = int, default=300) argparser.add_argument("--max_ques_len", type = int, default=50) argparser.add_argument("--max_ans_len", type = int, default=50) argparser.add_argument("--n_epochs", type = int, default=20) argparser.add_argument("--batch_size", type = int, default=128) args = argparser.parse_args() print(args) print("") main(args) <file_sep>import argparse import sys from collections import defaultdict import csv import math import nltk MAX_POST_LEN = 100 MAX_QUES_LEN = 20 MAX_ANS_LEN = 20 def write_to_file(ids, args, posts, question_candidates, answer_candidates, split): if split == 'train': context_file = open(args.train_context_fname, 'w') question_file = open(args.train_question_fname, 'w') answer_file = open(args.train_answer_fname, 'w') elif split == 'tune': context_file = open(args.tune_context_fname, 'w') question_file = open(args.tune_question_fname, 'w') answer_file = open(args.tune_answer_fname, 'w') elif split == 'test': context_file = open(args.test_context_fname, 'w') question_file = open(args.test_question_fname, 'w') answer_file = open(args.test_answer_fname, 'w') for k, post_id in enumerate(ids): context_file.write(posts[post_id]+'\n') question_file.write(question_candidates[post_id][0]+'\n') answer_file.write(answer_candidates[post_id][0]+'\n') context_file.close() question_file.close() answer_file.close() def trim_by_len(s, max_len): s = s.lower().strip() words = s.split() s = ' '.join(words[:max_len]) return s def trim_by_tfidf(posts, p_tf, p_idf): for post_id in posts: post = [] words = posts[post_id].split() for w in words: tf = words.count(w) if tf*p_idf[w] >= MIN_TFIDF: post.append(w) if len(post) >= MAX_POST_LEN: break posts[post_id] = ' '.join(post) return posts def read_data(args): print("Reading lines...") posts = {} question_candidates = {} answer_candidates = {} p_tf = defaultdict(int) p_idf = defaultdict(int) with open(args.post_data_tsvfile, 'rb') as tsvfile: post_reader = csv.reader(tsvfile, delimiter='\t') N = 0 for row in post_reader: if N == 0: N += 1 continue N += 1 post_id, title, post = row post = title + ' ' + post post = post.lower().strip() for w in post.split(): p_tf[w] += 1 for w in set(post.split()): p_idf[w] += 1 posts[post_id] = post for w in p_idf: p_idf[w] = math.log(N*1.0/p_idf[w]) # for asin, post in posts.iteritems(): # posts[asin] = trim_by_len(post, MAX_POST_LEN) #posts = trim_by_tfidf(posts, p_tf, p_idf) N = 0 with open(args.qa_data_tsvfile, 'rb') as tsvfile: qa_reader = csv.reader(tsvfile, delimiter='\t') i = 0 for row in qa_reader: if i == 0: i += 1 continue post_id, questions = row[0], row[1:11] answers = row[11:21] # questions = [trim_by_len(question, MAX_QUES_LEN) for question in questions] question_candidates[post_id] = questions # answers = [trim_by_len(answer, MAX_ANS_LEN) for answer in answers] answer_candidates[post_id] = answers train_ids = [train_id.strip('\n') for train_id in open(args.train_ids_file, 'r').readlines()] tune_ids = [tune_id.strip('\n') for tune_id in open(args.tune_ids_file, 'r').readlines()] test_ids = [test_id.strip('\n') for test_id in open(args.test_ids_file, 'r').readlines()] write_to_file(train_ids, args, posts, question_candidates, answer_candidates, 'train') write_to_file(tune_ids, args, posts, question_candidates, answer_candidates, 'tune') write_to_file(test_ids, args, posts, question_candidates, answer_candidates, 'test') if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--post_data_tsvfile", type = str) argparser.add_argument("--qa_data_tsvfile", type = str) argparser.add_argument("--train_ids_file", type = str) argparser.add_argument("--train_context_fname", type = str) argparser.add_argument("--train_question_fname", type = str) argparser.add_argument("--train_answer_fname", type=str) argparser.add_argument("--tune_ids_file", type = str) argparser.add_argument("--tune_context_fname", type = str) argparser.add_argument("--tune_question_fname", type = str) argparser.add_argument("--tune_answer_fname", type=str) argparser.add_argument("--test_ids_file", type = str) argparser.add_argument("--test_context_fname", type=str) argparser.add_argument("--test_question_fname", type = str) argparser.add_argument("--test_answer_fname", type = str) args = argparser.parse_args() print args print "" read_data(args) <file_sep>#!/bin/bash SITENAME=Home_and_Kitchen CQ_DATA_DIR=clarification_question_generation_pytorch/$SITENAME SCRIPT_DIR=clarification_question_generation_pytorch/src EMB_DIR=clarification_question_generation_pytorch/embeddings/$SITENAME PARAMS_DIR=$CQ_DATA_DIR python $SCRIPT_DIR/RL_main.py --train_context $CQ_DATA_DIR/train_context.txt \ --train_ques $CQ_DATA_DIR/train_ques.txt \ --train_ans $CQ_DATA_DIR/train_ans.txt \ --train_ids $CQ_DATA_DIR/train_asin.txt \ --tune_context $CQ_DATA_DIR/tune_context.txt \ --tune_ques $CQ_DATA_DIR/tune_ques.txt \ --tune_ans $CQ_DATA_DIR/tune_ans.txt \ --tune_ids $CQ_DATA_DIR/tune_asin.txt \ --test_context $CQ_DATA_DIR/test_context.txt \ --test_ques $CQ_DATA_DIR/test_ques.txt \ --test_ans $CQ_DATA_DIR/test_ans.txt \ --test_ids $CQ_DATA_DIR/test_asin.txt \ --test_pred_ques $CQ_DATA_DIR/test_pred_ques.txt \ --q_encoder_params $PARAMS_DIR/q_encoder_params.epoch100 \ --q_decoder_params $PARAMS_DIR/q_decoder_params.epoch100 \ --a_encoder_params $PARAMS_DIR/a_encoder_params.epoch100 \ --a_decoder_params $PARAMS_DIR/a_decoder_params.epoch100 \ --context_params $PARAMS_DIR/context_params.epoch10 \ --question_params $PARAMS_DIR/question_params.epoch10 \ --answer_params $PARAMS_DIR/answer_params.epoch10 \ --utility_params $PARAMS_DIR/utility_params.epoch10 \ --word_embeddings $EMB_DIR/word_embeddings.p \ --vocab $EMB_DIR/vocab.p \ --model RL_selfcritic \ --max_post_len 100 \ --max_ques_len 20 \ --max_ans_len 20 \ --batch_size 128 \ --n_epochs 40 \ <file_sep>#!/bin/bash SITENAME=askubuntu_unix_superuser SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/lucene CQ_DATA_DIR=/fs/clip-amr/clarification_question_generation/$SITENAME python $SCRIPT_DIR/create_stackexchange_lucene_baseline.py --post_data_tsvfile $CQ_DATA_DIR/post_data.tsv \ --qa_data_tsvfile $CQ_DATA_DIR/qa_data.tsv \ --test_ids_file $CQ_DATA_DIR/test_ids \ --lucene_output_file $CQ_DATA_DIR/test_pred_question_lucene.txt \ <file_sep>USE_CUDA = True # Configure models HIDDEN_SIZE = 100 DROPOUT = 0.5 # Configure training/optimization LEARNING_RATE = 0.0001 DECODER_LEARNING_RATIO = 5.0 PAD_token = '<PAD>' SOS_token = '<SOS>' EOP_token = '<EOP>' EOS_token = '<EOS>' UNK_token = '<unk>' # UNK_token = 'unk' SPECIFIC_token = '<specific>' GENERIC_token = '<generic>' BEAM_SIZE = 5 <file_sep>from constants import * import sys sys.path.append('src/utility') from helper_utility import * import numpy as np import torch from torch.autograd import Variable def evaluate_utility(context_model, question_model, answer_model, utility_model, c, cl, q, ql, a, al, args): with torch.no_grad(): context_model.eval() question_model.eval() answer_model.eval() utility_model.eval() cm = get_masks(cl, args.max_post_len) qm = get_masks(ql, args.max_ques_len) am = get_masks(al, args.max_ans_len) c = torch.tensor(c) cm = torch.FloatTensor(cm) q = torch.tensor(q) qm = torch.FloatTensor(qm) a = torch.tensor(a) am = torch.FloatTensor(am) if USE_CUDA: c = c.cuda() cm = cm.cuda() q = q.cuda() qm = qm.cuda() a = a.cuda() am = am.cuda() c_hid, c_out = context_model(torch.transpose(c, 0, 1)) cm = torch.transpose(cm, 0, 1).unsqueeze(2) cm = cm.expand(cm.shape[0], cm.shape[1], 2*HIDDEN_SIZE) c_out = torch.sum(c_out * cm, dim=0) q_hid, q_out = question_model(torch.transpose(q, 0, 1)) qm = torch.transpose(qm, 0, 1).unsqueeze(2) qm = qm.expand(qm.shape[0], qm.shape[1], 2*HIDDEN_SIZE) q_out = torch.sum(q_out * qm, dim=0) a_hid, a_out = answer_model(torch.transpose(a, 0, 1)) am = torch.transpose(am, 0, 1).unsqueeze(2) am = am.expand(am.shape[0], am.shape[1], 2*HIDDEN_SIZE) a_out = torch.sum(a_out * am, dim=0) predictions = utility_model(torch.cat((c_out, q_out, a_out), 1)).squeeze(1) # predictions = utility_model(torch.cat((c_out, q_out), 1)).squeeze(1) # predictions = utility_model(q_out).squeeze(1) predictions = torch.nn.functional.sigmoid(predictions) return predictions <file_sep>from constants import * import torch from torch.autograd import Variable from helper import * from utility.RL_evaluate import * from seq2seq.RL_evaluate import * from seq2seq.ans_train import * from seq2seq.RL_beam_decoder import * def get_decoded_seqs(output_seqs, word2index, max_len, batch_size): decoded_seqs = [] decoded_lens = [] for b in range(batch_size): decoded_seq = [] decoded_seq_mask = [0]*max_len for t in range(max_len): idx = int(output_seqs[t][b]) if idx == word2index[EOS_token]: decoded_seq.append(idx) break else: decoded_seq.append(idx) decoded_seq_mask[t] = 1 decoded_lens.append(len(decoded_seq)) decoded_seq += [word2index[PAD_token]]*int(max_len - len(decoded_seq)) decoded_seqs.append(decoded_seq) decoded_lens = np.array(decoded_lens) decoded_seqs = np.array(decoded_seqs) return decoded_seqs, decoded_lens def mixer_baseline(decoder_hiddens, reward, mode, baseline_model, baseline_criterion, baseline_optimizer): # Train baseline reward func model baseline_input = torch.sum(decoder_hiddens, dim=0) baseline_input = torch.FloatTensor(baseline_input.data.cpu().numpy()) if USE_CUDA: baseline_input = baseline_input.cuda() b_reward = baseline_model(baseline_input).squeeze(1) b_loss = baseline_criterion(b_reward, reward) if mode == 'train': b_loss.backward() baseline_optimizer.step() return b_reward def selfcritic_baseline(input_batches, post_seqs, post_lens, target_batches, greedy_output_seqs, q_encoder, q_decoder, a_encoder, a_decoder, mixer_delta, context_model, question_model, answer_model, utility_model, word2index, args): # Prepare input and output variables encoder_outputs, encoder_hidden = q_encoder(input_batches, post_lens, None) decoder_hidden = encoder_hidden[:q_decoder.n_layers] + encoder_hidden[q_decoder.n_layers:] decoder_input = target_batches[mixer_delta - 1] for t in range(args.max_ques_len - mixer_delta): decoder_output, decoder_hidden = q_decoder(decoder_input, decoder_hidden, encoder_outputs) # Greedy decoding topi = decoder_output.data.topk(1)[1] decoder_input = topi.squeeze(1) greedy_output_seqs[mixer_delta + t] = topi.squeeze(1) greedy_decoded_seqs, greedy_decoded_lens = get_decoded_seqs(greedy_output_seqs, word2index, args.max_ques_len, args.batch_size) # b_reward = calculate_bleu(ques_seqs, ques_lens, greedy_decoded_seqs, greedy_decoded_lens, # index2word, args.max_ques_len) greedy_pq_pred = np.concatenate((post_seqs, greedy_decoded_seqs), axis=1) greedy_pql_pred = np.full(args.batch_size, args.max_post_len+args.max_ques_len) greedy_a_pred, greedy_al_pred = evaluate_batch(greedy_pq_pred, greedy_pql_pred, a_encoder, a_decoder, word2index, args.max_ans_len, args.batch_size) # _, greedy_a_pred, greedy_al_pred = train(greedy_pq_pred, greedy_pql_pred, ans_seqs, ans_lens, a_encoder, a_decoder, # a_encoder_optimizer, a_decoder_optimizer, word2index, args, mode) greedy_u_preds = evaluate_utility(context_model, question_model, answer_model, utility_model, post_seqs, post_lens, greedy_decoded_seqs, greedy_decoded_lens, greedy_a_pred, greedy_al_pred, args) b_reward = greedy_u_preds return b_reward, greedy_decoded_seqs, greedy_decoded_lens def GAN_train(post_seqs, post_lens, ques_seqs, ques_lens, ans_seqs, ans_lens, q_encoder, q_decoder, q_encoder_optimizer, q_decoder_optimizer, a_encoder, a_decoder, a_encoder_optimizer, a_decoder_optimizer, baseline_model, baseline_optimizer, baseline_criterion, context_model, question_model, answer_model, utility_model, word2index, index2word, mixer_delta, args, mode='train'): if mode == 'train': # Zero gradients of both optimizers q_encoder_optimizer.zero_grad() q_decoder_optimizer.zero_grad() baseline_optimizer.zero_grad() q_encoder.train() q_decoder.train() baseline_model.train() input_batches = Variable(torch.LongTensor(np.array(post_seqs))).transpose(0, 1) target_batches = Variable(torch.LongTensor(np.array(ques_seqs))).transpose(0, 1) decoder_input = Variable(torch.LongTensor([word2index[SOS_token]] * args.batch_size)) xe_decoder_outputs = Variable(torch.zeros(mixer_delta, args.batch_size, q_decoder.output_size)) rl_decoder_outputs = Variable(torch.zeros((args.max_ques_len - mixer_delta), args.batch_size, q_decoder.output_size)) decoder_hiddens = Variable(torch.zeros(args.max_ques_len, args.batch_size, q_decoder.hidden_size)) output_seqs = Variable(torch.zeros(args.max_ques_len, args.batch_size, dtype=torch.long)) greedy_output_seqs = Variable(torch.zeros(args.max_ques_len, args.batch_size, dtype=torch.long)) if USE_CUDA: input_batches = input_batches.cuda() target_batches = target_batches.cuda() output_seqs = output_seqs.cuda() greedy_output_seqs = greedy_output_seqs.cuda() decoder_input = decoder_input.cuda() xe_decoder_outputs = xe_decoder_outputs.cuda() rl_decoder_outputs = rl_decoder_outputs.cuda() decoder_hiddens = decoder_hiddens.cuda() loss_fn = torch.nn.NLLLoss() if mixer_delta != 0: # Run post words through encoder encoder_outputs, encoder_hidden = q_encoder(input_batches, post_lens, None) # Prepare input and output variables decoder_hidden = encoder_hidden[:q_decoder.n_layers] + encoder_hidden[q_decoder.n_layers:] # Run through decoder one time step at a time for t in range(mixer_delta): decoder_output, decoder_hidden = q_decoder(decoder_input, decoder_hidden, encoder_outputs) xe_decoder_outputs[t] = decoder_output decoder_hiddens[t] = torch.sum(decoder_hidden, dim=0) if mode == 'train': # Teacher Forcing decoder_input = target_batches[t] # Next input is current target output_seqs[t] = target_batches[t] greedy_output_seqs[t] = target_batches[t] elif mode == 'test': # Greedy decoding topv, topi = decoder_output.data.topk(1) decoder_input = topi.squeeze(1) output_seqs[t] = topi.squeeze(1) # # Loss calculation and back-propagation xe_loss = masked_cross_entropy( xe_decoder_outputs.transpose(0, 1).contiguous(), # -> batch x seq target_batches[:mixer_delta].transpose(0, 1).contiguous(), # -> batch x seq ques_lens, loss_fn, mixer_delta ) if mode == 'train': xe_loss.backward() else: xe_loss = 0. if mixer_delta != args.max_ques_len: # Prepare input and output variables encoder_outputs, encoder_hidden = q_encoder(input_batches, post_lens, None) decoder_hidden = encoder_hidden[:q_decoder.n_layers] + encoder_hidden[q_decoder.n_layers:] decoder_input = target_batches[mixer_delta-1] for t in range(args.max_ques_len-mixer_delta): decoder_output, decoder_hidden = q_decoder(decoder_input, decoder_hidden, encoder_outputs) rl_decoder_outputs[t] = decoder_output decoder_hiddens[mixer_delta+t] = torch.sum(decoder_hidden, dim=0) # Sampling for b in range(args.batch_size): token_dist = torch.nn.functional.softmax(decoder_output[b], dim=0) idx = token_dist.multinomial(1, replacement=False).view(-1).data[0] decoder_input[b] = idx output_seqs[mixer_delta+t][b] = idx decoded_seqs, decoded_lens = get_decoded_seqs(output_seqs, word2index, args.max_ques_len, args.batch_size) if mixer_delta != args.max_ques_len: # Calculate reward # reward = calculate_bleu(ques_seqs, ques_lens, decoded_seqs, decoded_lens, index2word, args.max_ques_len) if mode == 'train': pq_pred = np.concatenate((post_seqs, decoded_seqs), axis=1) pql_pred = np.full(args.batch_size, args.max_post_len + args.max_ques_len) # a_loss, _, _ = train(pq_pred, pql_pred, ans_seqs, ans_lens, a_encoder, a_decoder, # a_encoder_optimizer, a_decoder_optimizer, word2index, args, mode) a_pred, al_pred = evaluate_batch(pq_pred, pql_pred, a_encoder, a_decoder, word2index, args.max_ans_len, args.batch_size, ans_seqs, ans_lens) # a_pred, al_pred = evaluate_beam_batch(pq_pred, pql_pred, a_encoder, a_decoder, # word2index, index2word, args.max_ans_len, args.batch_size) a_loss = 0. elif mode == 'test': pq_pred = np.concatenate((post_seqs, decoded_seqs), axis=1) pql_pred = np.full(args.batch_size, args.max_post_len + args.max_ques_len) # if mixer_delta > 8: # a_loss, a_pred, al_pred = train(pq_pred, pql_pred, ans_seqs, ans_lens, a_encoder, a_decoder, # a_encoder_optimizer, a_decoder_optimizer, word2index, args, mode) # else: a_pred, al_pred = evaluate_batch(pq_pred, pql_pred, a_encoder, a_decoder, word2index, args.max_ans_len, args.batch_size, ans_seqs, ans_lens) pq_pred = np.concatenate((post_seqs, ques_seqs), axis=1) a_pred_true, al_pred_true = evaluate_batch(pq_pred, pql_pred, a_encoder, a_decoder, word2index, args.max_ans_len, args.batch_size, ans_seqs, ans_lens) # a_pred, al_pred = evaluate_beam_batch(pq_pred, pql_pred, a_encoder, a_decoder, # word2index, index2word, args.max_ans_len, args.batch_size) a_loss = 0. # u_preds = torch.zeros(args.batch_size) # if USE_CUDA: # u_preds = u_preds.cuda() # for k in range(BEAM_SIZE): # curr_u_preds = evaluate_utility(context_model, question_model, answer_model, utility_model, # post_seqs, post_lens, decoded_seqs, decoded_lens, # a_pred[k], al_pred[k], args) # u_preds = u_preds + curr_u_preds # reward = u_preds / BEAM_SIZE u_preds = evaluate_utility(context_model, question_model, answer_model, utility_model, post_seqs, post_lens, decoded_seqs, decoded_lens, a_pred, al_pred, args) reward = u_preds # b_reward = mixer_baseline(decoder_hiddens, reward, mode, # baseline_model, baseline_criterion, baseline_optimizer) b_reward, greedy_decoded_seqs, greedy_decoded_lens = selfcritic_baseline(input_batches, post_seqs, post_lens, target_batches, greedy_output_seqs, q_encoder, q_decoder, a_encoder, a_decoder, mixer_delta, context_model, question_model, answer_model, utility_model, word2index, args) log_probs = calculate_log_probs( rl_decoder_outputs.transpose(0, 1).contiguous(), # -> batch x seq output_seqs[mixer_delta:].transpose(0, 1).contiguous(), # -> batch x seq decoded_lens, loss_fn, mixer_delta ) rl_loss = torch.sum(log_probs * (reward.data - b_reward.data)) / args.batch_size else: rl_loss = 0 a_loss = 0 reward = 0 b_reward = 0 a_pred = None al_pred = None if mode == 'train': if rl_loss != 0: rl_loss.backward() q_encoder_optimizer.step() q_decoder_optimizer.step() return xe_loss, rl_loss, a_loss, reward, b_reward else: return decoded_seqs, decoded_lens, a_pred, al_pred, a_pred_true, al_pred_true <file_sep>import argparse import csv import sys, os, pdb import nltk import time import random from collections import defaultdict def create_refs(test_ids, question_candidates, ref_prefix): max_ref_count=0 for ques_id in test_ids: asin = ques_id.split('_')[0] N = len(question_candidates[asin]) max_ref_count = max(max_ref_count, N) ref_files = [None]*max_ref_count for i in range(max_ref_count): ref_files[i] = open(ref_prefix+str(i), 'w') for ques_id in test_ids: asin = ques_id.split('_')[0] N = len(question_candidates[asin]) for i, ques in enumerate(question_candidates[asin]): ref_files[i].write(ques+'\n') choices = range(N) random.shuffle(choices) for j in range(N, max_ref_count): r = choices[j%N] ref_files[j].write(question_candidates[asin][r]+'\n') def main(args): question_candidates = {} test_ids = [test_id.strip('\n') for test_id in open(args.test_ids_file, 'r').readlines()] for fname in os.listdir(args.ques_dir): with open(os.path.join(args.ques_dir, fname), 'r') as f: asin = fname[:-4].split('_')[0] if asin not in question_candidates: question_candidates[asin] = [] ques = f.readline().strip('\n') question_candidates[asin].append(ques) create_refs(test_ids, question_candidates, args.ref_prefix) if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--ques_dir", type = str) argparser.add_argument("--test_ids_file", type = str) argparser.add_argument("--ref_prefix", type = str) args = argparser.parse_args() print args print "" main(args) <file_sep>import torch from torch.autograd import Variable import pdb import sys sys.path.append('src/seq2seq') from read_data import * import numpy as np from constants import * UNK_TOKEN='<unk>' # UNK_TOKEN='unk' # Return a list of indexes, one for each word in the sentence, plus EOS def prepare_sequence(seq, word2index, max_len): sequence = [word2index[w] if w in word2index else word2index[UNK_TOKEN] for w in seq.split(' ')[:max_len-1]] sequence.append(word2index[EOS_token]) length = len(sequence) sequence += [word2index[PAD_token]]*int(max_len - len(sequence)) return sequence, length def prepare_pq_sequence(post_seq, ques_seq, word2index, max_post_len, max_ques_len): p_sequence = [word2index[w] if w in word2index else word2index[UNK_TOKEN] for w in post_seq.split(' ')[:(max_post_len-1)]] p_sequence.append(word2index[EOP_token]) p_sequence += [word2index[PAD_token]]*int(max_post_len - len(p_sequence)) q_sequence = [word2index[w] if w in word2index else word2index[UNK_TOKEN] for w in ques_seq.split(' ')[:(max_ques_len-1)]] q_sequence.append(word2index[EOS_token]) q_sequence += [word2index[PAD_token]]*int(max_ques_len - len(q_sequence)) sequence = p_sequence + q_sequence length = max_post_len, max_ques_len return sequence, length def preprocess_data(triples, word2index, max_post_len, max_ques_len, max_ans_len): id_seqs = [] post_seqs = [] post_lens = [] ques_seqs = [] ques_lens = [] post_ques_seqs = [] post_ques_lens = [] ans_seqs = [] ans_lens = [] for i in range(len(triples)): curr_id, post, ques, ans = triples[i] id_seqs.append(curr_id) post_seq, post_len = prepare_sequence(post, word2index, max_post_len) post_seqs.append(post_seq) post_lens.append(post_len) ques_seq, ques_len = prepare_sequence(ques, word2index, max_ques_len) ques_seqs.append(ques_seq) ques_lens.append(ques_len) post_ques_seq, post_ques_len = prepare_pq_sequence(post, ques, word2index, max_post_len, max_ques_len) post_ques_seqs.append(post_ques_seq) post_ques_lens.append(post_ques_len) if ans is not None: ans_seq, ans_len = prepare_sequence(ans, word2index, max_ans_len) ans_seqs.append(ans_seq) ans_lens.append(ans_len) return id_seqs, post_seqs, post_lens, ques_seqs, ques_lens, \ post_ques_seqs, post_ques_lens, ans_seqs, ans_lens <file_sep>import random from constants import * from prepare_data import * from masked_cross_entropy import * from helper import * import torch import torch.nn as nn from torch.autograd import Variable def evaluate_batch(input_batches, input_lens, encoder, decoder, word2index, max_out_len, batch_size, target_batches=None, target_lens=None): input_batches = Variable(torch.LongTensor(np.array(input_batches))).transpose(0, 1) if USE_CUDA: input_batches = input_batches.cuda() # Run post words through encoder encoder_outputs, encoder_hidden = encoder(input_batches, input_lens, None) # Create starting vectors for decoder decoder_input = Variable(torch.LongTensor([word2index[SOS_token]] * batch_size)) decoder_hidden = encoder_hidden[:decoder.n_layers] + encoder_hidden[decoder.n_layers:] decoder_outputs = Variable(torch.zeros(max_out_len, batch_size)) if USE_CUDA: decoder_input = decoder_input.cuda() decoder_outputs = decoder_outputs.cuda() # Run through decoder one time step at a time for t in range(max_out_len): decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden, encoder_outputs) # Choose top word from output topv, topi = decoder_output.data.topk(1) decoder_input = topi.squeeze(1) decoder_outputs[t] = topi.squeeze(1) decoded_seqs = [] decoded_lens = [] for b in range(batch_size): decoded_seq = [] for t in range(max_out_len): topi = decoder_outputs[t][b].data idx = int(topi.item()) if idx == word2index[EOS_token]: decoded_seq.append(idx) break else: decoded_seq.append(idx) # if target_batches is not None and decoded_seq.count(word2index['<unk>']) > 1: # import pdb # pdb.set_trace() # decoded_seq = target_batches[b] # decoded_lens.append(target_lens[b]) # else: decoded_lens.append(len(decoded_seq)) decoded_seq += [word2index[PAD_token]]*int(max_out_len - len(decoded_seq)) decoded_seqs.append(decoded_seq) return decoded_seqs, decoded_lens def evaluate_seq2seq(word2index, index2word, encoder, decoder, id_seqs, input_seqs, input_lens, output_seqs, output_lens, batch_size, max_out_len, out_fname): total_loss = 0. n_batches = len(input_seqs) / batch_size encoder.eval() decoder.eval() has_ids = True if out_fname: out_file = open(out_fname, 'w') if id_seqs[0] is not None: out_ids_file = open(out_fname+'.ids', 'w') else: has_ids = False for id_seqs_batch, input_seqs_batch, input_lens_batch, output_seqs_batch, output_lens_batch in \ iterate_minibatches(id_seqs, input_seqs, input_lens, output_seqs, output_lens, batch_size, shuffle=False): if USE_CUDA: input_seqs_batch = Variable(torch.LongTensor(np.array(input_seqs_batch)).cuda()).transpose(0, 1) output_seqs_batch = Variable(torch.LongTensor(np.array(output_seqs_batch)).cuda()).transpose(0, 1) else: input_seqs_batch = Variable(torch.LongTensor(np.array(input_seqs_batch))).transpose(0, 1) output_seqs_batch = Variable(torch.LongTensor(np.array(output_seqs_batch))).transpose(0, 1) # Run post words through encoder encoder_outputs, encoder_hidden = encoder(input_seqs_batch, input_lens_batch, None) # Create starting vectors for decoder decoder_input = Variable(torch.LongTensor([word2index[SOS_token]] * batch_size)) decoder_hidden = encoder_hidden[:decoder.n_layers] + encoder_hidden[decoder.n_layers:] all_decoder_outputs = Variable(torch.zeros(max_out_len, batch_size, decoder.output_size)) if USE_CUDA: decoder_input = decoder_input.cuda() all_decoder_outputs = all_decoder_outputs.cuda() # Run through decoder one time step at a time for t in range(max_out_len): decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden, encoder_outputs) all_decoder_outputs[t] = decoder_output # Choose top word from output topv_list, topi_list = decoder_output.data.topk(10) topi = topi_list[:, 0] for i in range(len(topi)): j = 0 while topi_list[i][j].item() == word2index[UNK_token]: j += 1 topi[i] = topi_list[i][j] decoder_input = topi for b in range(batch_size): decoded_words = [] for t in range(max_out_len): topv_list, topi_list = all_decoder_outputs[t][b].data.topk(10) for topi in topi_list: if topi.item() != word2index[UNK_token]: ni = topi.item() break if ni == word2index[UNK_token]: import pdb; pdb.set_trace() if ni == word2index[EOS_token]: decoded_words.append(EOS_token) break else: decoded_words.append(index2word[ni]) if out_fname: out_file.write(' '.join(decoded_words)+'\n') if has_ids: out_ids_file.write(id_seqs_batch[b]+'\n') # Loss calculation loss_fn = torch.nn.NLLLoss() loss = masked_cross_entropy( all_decoder_outputs.transpose(0, 1).contiguous(), # -> batch x seq output_seqs_batch.transpose(0, 1).contiguous(), # -> batch x seq output_lens_batch, loss_fn, max_out_len ) total_loss += loss.item() print('Loss: %.2f' % (total_loss/n_batches)) <file_sep>import argparse import gzip import nltk import pdb import sys from collections import defaultdict import csv import random def parse(path): g = gzip.open(path, 'r') for l in g: yield eval(l) def main(args): titles = {} descriptions = {} previous_asins = [] with open(args.previous_csv_file_v1) as csvfile: reader = csv.DictReader(csvfile) for row in reader: asin = row['asin'] previous_asins.append(asin) with open(args.previous_csv_file_v2) as csvfile: reader = csv.DictReader(csvfile) for row in reader: asin = row['asin'] previous_asins.append(asin) with open(args.previous_csv_file_v3) as csvfile: reader = csv.DictReader(csvfile) for row in reader: asin = row['asin'] previous_asins.append(asin) with open(args.previous_csv_file_v4) as csvfile: reader = csv.DictReader(csvfile) for row in reader: asin = row['asin'] previous_asins.append(asin) train_asins = [line.strip('\n') for line in open(args.train_asins, 'r').readlines()] for v in parse(args.metadata_fname): asin = v['asin'] if asin not in train_asins: continue if asin in previous_asins: continue title = v['title'] description = v['description'] length = len(description.split()) if length >= 100 or length < 10 or len(title.split()) == length: continue titles[asin] = title descriptions[asin] = description questions = defaultdict(list) for v in parse(args.qa_data_fname): asin = v['asin'] if asin not in train_asins: continue if asin in previous_asins: continue if asin not in descriptions: continue question = ' '.join(nltk.sent_tokenize(v['question'])).lower() questions[asin].append(question) csv_file = open(args.csv_file, 'w') writer = csv.writer(csv_file, delimiter=',') writer.writerow(['asin', 'title', 'description', 'question_a', 'question_b']) all_rows = [] max_count = 200 i = 0 for asin in titles.keys(): if asin not in train_asins: continue if asin in previous_asins: continue title = titles[asin] description = descriptions[asin] random.shuffle(questions[asin]) for k in range(len(questions[asin])): if k == 6 or k == len(questions[asin])-1: all_rows.append([asin, title, description, questions[asin][k], questions[asin][0]]) print asin, k+1 break else: all_rows.append([asin, title, description, questions[asin][k], questions[asin][k + 1]]) i += 1 if i >= max_count: break random.shuffle(all_rows) for row in all_rows: writer.writerow(row) csv_file.close() if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--qa_data_fname", type = str) argparser.add_argument("--metadata_fname", type = str) argparser.add_argument("--csv_file", type=str) argparser.add_argument("--train_asins", type=str) argparser.add_argument("--previous_csv_file_v1", type=str) argparser.add_argument("--previous_csv_file_v2", type=str) argparser.add_argument("--previous_csv_file_v3", type=str) argparser.add_argument("--previous_csv_file_v4", type=str) args = argparser.parse_args() print args print "" main(args) <file_sep>#!/bin/bash SITENAME=Home_and_Kitchen DATA_DIR=/fs/clip-corpora/amazon_qa OLD_CQ_DATA_DIR=/fs/clip-amr/clarification_question_generation/data/amazon/$SITENAME CQ_DATA_DIR=/fs/clip-scratch/raosudha/clarification_question_generation/joint_learning/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src export PATH="/fs/clip-amr/anaconda2/bin:$PATH" python $SCRIPT_DIR/filter_output_perid.py --test_ids $CQ_DATA_DIR/tune_asin.txt \ --test_output $CQ_DATA_DIR/test_pred_question.txt.pretrained_greedy \ --test_output_perid $CQ_DATA_DIR/test_pred_question.txt.pretrained_greedy.perid \ --batch_size 128 \ # --max_per_id 3 \ # --test_output $CQ_DATA_DIR/test_pred_question.txt.GAN_mixer_pred_ans_3perid.epoch8.beam0 \ # --test_output_perid $CQ_DATA_DIR/test_pred_question.txt.GAN_mixer_pred_ans_3perid.epoch8.beam0.perid \ # --test_output $CQ_DATA_DIR/test_pred_question.txt.pretrained_greedy \ # --test_output_perid $CQ_DATA_DIR/test_pred_question.txt.pretrained_greedy.perid \ <file_sep>#!/bin/bash #SBATCH --job-name=utility_aus_fullmodel_80K #SBATCH --output=utility_aus_fullmodel_80K #SBATCH --qos=gpu-short #SBATCH --partition=gpu #SBATCH --gres=gpu #SBATCH --mem=16g #SITENAME=askubuntu.com #SITENAME=unix.stackexchange.com #SITENAME=superuser.com SITENAME=askubuntu_unix_superuser #SITENAME=Home_and_Kitchen DATA_DIR=/fs/clip-corpora/amazon_qa UTILITY_DATA_DIR=/fs/clip-scratch/raosudha/clarification_question_generation/utility/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/utility EMB_DIR=/fs/clip-amr/clarification_question_generation_pytorch/embeddings/$SITENAME/200_5Kvocab #EMB_DIR=/fs/clip-amr/ranking_clarification_questions/embeddings source /fs/clip-amr/gpu_virtualenv/bin/activate export PATH="/fs/clip-amr/anaconda2/bin:$PATH" python $SCRIPT_DIR/rnn_classifier.py --train_data $UTILITY_DATA_DIR/train_data.p \ --tune_data $UTILITY_DATA_DIR/tune_data.p \ --test_data $UTILITY_DATA_DIR/test_data.p \ --word_embeddings $EMB_DIR/word_embeddings.p \ --vocab $EMB_DIR/vocab.p \ --cuda True \ <file_sep>export LANGUAGE=en_US.UTF-8 export LANG=en_US.UTF-8 export LC_ALL=en_US.UTF-8 NGRAMS_SCRIPT=/fs/clip-amr/clarification_question_generation_pytorch/src/evaluation/all_ngrams.pl count_uniq_trigrams=$( cat $1 | $NGRAMS_SCRIPT 3 | sort | uniq -c | sort -gr | wc -l ) count_all_trigrams=$( cat $1 | $NGRAMS_SCRIPT 3 | sort | sort -gr | wc -l ) echo "Trigram diversity" echo "scale=4; $count_uniq_trigrams / $count_all_trigrams" | bc count_uniq_bigrams=$( cat $1 | $NGRAMS_SCRIPT 2 | sort | uniq -c | sort -gr | wc -l ) count_all_bigrams=$( cat $1 | $NGRAMS_SCRIPT 2 | sort | sort -gr | wc -l ) echo "Bigram diversity" echo "scale=4; $count_uniq_bigrams / $count_all_bigrams" | bc count_uniq_unigrams=$( cat $1 | $NGRAMS_SCRIPT 1 | sort | uniq -c | sort -gr | wc -l ) count_all_unigrams=$( cat $1 | $NGRAMS_SCRIPT 1 | sort | sort -gr | wc -l ) echo "Unigram diversity" echo "scale=4; $count_uniq_unigrams / $count_all_unigrams" | bc <file_sep>#!/bin/bash # Makes programs, downloads sample data, trains a GloVe model, and then evaluates it. # One optional argument can specify the language used for eval script: matlab, octave or [default] python SITENAME=askubuntu_unix_superuser #SITENAME=Home_and_Kitchen DATADIR=clarification_question_generation_pytorch/embeddings/$SITENAME/200_10Kvocab CORPUS=clarification_question_generation_pytorch/embeddings/$SITENAME/${SITENAME}_data.txt VOCAB_FILE=$DATADIR/vocab.txt COOCCURRENCE_FILE=$DATADIR/cooccurrence.bin COOCCURRENCE_SHUF_FILE=$DATADIR/cooccurrence.shuf.bin BUILDDIR=GloVe-1.2/build #Download from https://nlp.stanford.edu/projects/glove/ SAVE_FILE=$DATADIR/vectors VERBOSE=2 MEMORY=4.0 #VOCAB_MIN_COUNT=10 VOCAB_MIN_COUNT=50 #VECTOR_SIZE=100 VECTOR_SIZE=200 MAX_ITER=30 WINDOW_SIZE=15 BINARY=2 NUM_THREADS=4 X_MAX=10 $BUILDDIR/vocab_count -min-count $VOCAB_MIN_COUNT -verbose $VERBOSE < $CORPUS > $VOCAB_FILE $BUILDDIR/cooccur -memory $MEMORY -vocab-file $VOCAB_FILE -verbose $VERBOSE -window-size $WINDOW_SIZE < $CORPUS > $COOCCURRENCE_FILE $BUILDDIR/shuffle -memory $MEMORY -verbose $VERBOSE < $COOCCURRENCE_FILE > $COOCCURRENCE_SHUF_FILE $BUILDDIR/glove -save-file $SAVE_FILE -eta 0.05 -threads $NUM_THREADS -input-file $COOCCURRENCE_SHUF_FILE -x-max $X_MAX -iter $MAX_ITER -vector-size $VECTOR_SIZE -binary $BINARY -vocab-file $VOCAB_FILE -verbose $VERBOSE <file_sep>import argparse import csv import sys def main(args): print("Reading lines...") output_file = open(args.output_data, 'a') with open(args.post_data_tsv, 'rb') as tsvfile: post_reader = csv.DictReader(tsvfile, delimiter='\t') for row in post_reader: post = row['title'] + ' ' + row['post'] post = post.lower().strip() output_file.write(post+'\n') with open(args.qa_data_tsv, 'rb') as tsvfile: qa_reader = csv.DictReader(tsvfile, delimiter='\t') for row in qa_reader: ques = row['q1'].lower().strip() ans = row['a1'].lower().strip() output_file.write(ques+'\n') output_file.write(ans+'\n') output_file.close() if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--post_data_tsv", type = str) argparser.add_argument("--qa_data_tsv", type = str) argparser.add_argument("--output_data", type = str) args = argparser.parse_args() print args print "" main(args) <file_sep>from constants import * import torch from torch.nn import functional from torch.autograd import Variable def calculate_log_probs(logits, output, length, loss_fn, mixer_delta): batch_size = logits.shape[0] log_probs = functional.log_softmax(logits, dim=2) avg_log_probs = Variable(torch.zeros(batch_size)) if USE_CUDA: avg_log_probs = avg_log_probs.cuda() for b in range(batch_size): curr_len = length[b]-mixer_delta if curr_len > 0: avg_log_probs[b] = loss_fn(log_probs[b][:curr_len], output[b][:curr_len]) / curr_len return avg_log_probs def masked_cross_entropy(logits, target, length, loss_fn, mixer_delta=None): batch_size = logits.shape[0] # log_probs: (batch, max_len, num_classes) log_probs = functional.log_softmax(logits, dim=2) loss = 0. for b in range(batch_size): curr_len = min(length[b], mixer_delta) sent_loss = loss_fn(log_probs[b][:curr_len], target[b][:curr_len]) / curr_len loss += sent_loss loss = loss / batch_size return loss <file_sep>import argparse import gzip import nltk import pdb import sys from collections import defaultdict import csv import random def parse(path): g = gzip.open(path, 'r') for l in g: yield eval(l) def read_model_outputs(model_fname): i = 0 model_outputs = {} model_file = open(model_fname, 'r') test_ids = [line.strip('\n') for line in open(model_fname+'.ids', 'r')] for line in model_file.readlines(): model_outputs[test_ids[i]] = line.strip('\n').replace(' <unk>', '').replace(' <EOS>', '') i += 1 return model_outputs def main(args): titles = {} descriptions = {} lucene_model_outs = read_model_outputs(args.lucene_model_fname) seq2seq_model_outs = read_model_outputs(args.seq2seq_model_fname) seq2seq_specific_model_outs = read_model_outputs(args.seq2seq_specific_model_fname) seq2seq_generic_model_outs = read_model_outputs(args.seq2seq_generic_model_fname) prev_asins = [] with open(args.prev_csv_file) as csvfile: reader = csv.DictReader(csvfile) for row in reader: asin = row['asin'] prev_asins.append(asin) for v in parse(args.metadata_fname): asin = v['asin'] if asin in prev_asins: continue if not v.has_key('description') or not v.has_key('title'): continue title = v['title'] description = v['description'] length = len(description.split()) if length >= 100 or length < 10 or len(title.split()) == length: continue titles[asin] = title descriptions[asin] = description questions = defaultdict(list) for v in parse(args.qa_data_fname): asin = v['asin'] if asin in prev_asins: continue if asin not in descriptions: continue question = ' '.join(nltk.sent_tokenize(v['question'])).lower() questions[asin].append(question) csv_file = open(args.csv_file, 'w') writer = csv.writer(csv_file, delimiter=',') writer.writerow(['asin', 'title', 'description', 'model_name', 'question']) all_rows = [] i = 0 max_count = 50 for asin in seq2seq_specific_model_outs.keys(): if asin not in descriptions: continue seq2seq_specific_question = seq2seq_specific_model_outs[asin] seq2seq_specific_question_tokens = seq2seq_specific_question.split() if '?' in seq2seq_specific_question_tokens: if seq2seq_specific_question_tokens.index('?') == len(seq2seq_specific_question_tokens)-1 : continue title = titles[asin] description = descriptions[asin] ref_question = random.choice(questions[asin]) lucene_question = lucene_model_outs[asin] seq2seq_question = seq2seq_model_outs[asin] seq2seq_generic_question = seq2seq_generic_model_outs[asin] all_rows.append([asin, title, description, "ref", ref_question]) all_rows.append([asin, title, description, args.lucene_model_name, lucene_question]) all_rows.append([asin, title, description, args.seq2seq_model_name, seq2seq_question]) all_rows.append([asin, title, description, args.seq2seq_specific_model_name, seq2seq_specific_question]) all_rows.append([asin, title, description, args.seq2seq_generic_model_name, seq2seq_generic_question]) i += 1 if i >= max_count: break random.shuffle(all_rows) for row in all_rows: writer.writerow(row) csv_file.close() if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--qa_data_fname", type = str) argparser.add_argument("--metadata_fname", type = str) argparser.add_argument("--prev_csv_file", type=str) argparser.add_argument("--csv_file", type=str) argparser.add_argument("--lucene_model_name", type=str) argparser.add_argument("--lucene_model_fname", type=str) argparser.add_argument("--seq2seq_model_name", type=str) argparser.add_argument("--seq2seq_model_fname", type=str) argparser.add_argument("--seq2seq_specific_model_name", type=str) argparser.add_argument("--seq2seq_specific_model_fname", type=str) argparser.add_argument("--seq2seq_generic_model_name", type=str) argparser.add_argument("--seq2seq_generic_model_fname", type=str) args = argparser.parse_args() print args print "" main(args) <file_sep>#!/bin/bash #SBATCH --job-name=create_crowdflower_HK_beam_spec_multi_sent #SBATCH --output=create_crowdflower_HK_beam_spec_multi_sent #SBATCH --qos=batch #SBATCH --mem=32g #SBATCH --time=4:00:00 SITENAME=Home_and_Kitchen CORPORA_DIR=/fs/clip-corpora/amazon_qa DATA_DIR=/fs/clip-amr/clarification_question_generation_pytorch/$SITENAME CROWDFLOWER_DIR=/fs/clip-amr/clarification_question_generation_pytorch/evaluation/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/evaluation export PATH="/fs/clip-amr/anaconda2/bin:$PATH" python $SCRIPT_DIR/create_crowdflower_data_specificity.py --qa_data_fname $CORPORA_DIR/qa_${SITENAME}.json.gz \ --metadata_fname $CORPORA_DIR/meta_${SITENAME}.json.gz \ --prev_csv_file $CROWDFLOWER_DIR/crowdflower_seq2seq_epoch100_seq2seq_specific_seq2seq_generic_p100_q30_style_emb_single_sent.epoch100.csv \ --csv_file $CROWDFLOWER_DIR/crowdflower_seq2seq_epoch100_seq2seq_specific_seq2seq_generic_p100_q30_style_emb_multi_sent.epoch100.csv \ --lucene_model_name lucene \ --lucene_model_fname $DATA_DIR/blind_test_pred_question.lucene.txt \ --seq2seq_model_name seq2seq \ --seq2seq_model_fname $DATA_DIR/blind_test_pred_ques.txt.seq2seq.epoch100.beam0 \ --seq2seq_specific_model_name seq2seq.specific \ --seq2seq_specific_model_fname $DATA_DIR/blind_test_pred_ques.txt.seq2seq_tobeginning_tospecific_p100_q30_style_emb.epoch100.beam0 \ --seq2seq_generic_model_name seq2seq.generic \ --seq2seq_generic_model_fname $DATA_DIR/blind_test_pred_ques.txt.seq2seq_tobeginning_togeneric_p100_q30_style_emb.epoch100.beam0 \ <file_sep>import sys import argparse from collections import defaultdict def main(args): test_output_file = open(args.test_output, 'r') test_ids_file = open(args.test_ids, 'r') test_output_perid_file = open(args.test_output_perid, 'w') # ongoing_id = None id_seq_in_output = [] data_ct_per_id = defaultdict(int) for line in test_ids_file.readlines(): curr_id = line.strip('\n') data_ct_per_id[curr_id] += 1 if args.max_per_id is not None: if data_ct_per_id[curr_id] <= args.max_per_id: id_seq_in_output.append(curr_id) else: id_seq_in_output.append(curr_id) i = 0 ongoing_id = None test_output_lines = test_output_file.readlines() test_output_perid = [] for line in test_output_lines: if id_seq_in_output[i] != ongoing_id: test_output_perid.append(line) ongoing_id = id_seq_in_output[i] i += 1 total_count = (len(test_output_perid) / args.batch_size - 1) * args.batch_size print total_count print len(test_output_perid) for line in test_output_perid[:total_count]: test_output_perid_file.write(line) if __name__ == '__main__': argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--test_output", type=str) argparser.add_argument("--test_ids", type=str) argparser.add_argument("--test_output_perid", type=str) argparser.add_argument("--max_per_id", type=int, default=None) argparser.add_argument("--batch_size", type=int) args = argparser.parse_args() print args print "" main(args)<file_sep>python src/GAN_main.py --train_context baseline_data/train_context.txt \ --train_ques baseline_data/train_question.txt \ --train_ans baseline_data/train_answer.txt \ --train_ids baseline_data/train_asin.txt \ --tune_context baseline_data/valid_context.txt \ --tune_ques baseline_data/valid_question.txt \ --tune_ans baseline_data/valid_answer.txt \ --tune_ids baseline_data/valid_asin.txt \ --test_context baseline_data/test_context.txt \ --test_ques baseline_data/test_question.txt \ --test_ans baseline_data/test_answer.txt \ --test_ids baseline_data/test_asin.txt \ --test_pred_ques baseline_data/gan_ques49_ans43_util10_valid_predicted_question.txt \ --q_encoder_params baseline_data/seq2seq-pretrain-ques-v3/q_encoder_params.epoch49 \ --q_decoder_params baseline_data/seq2seq-pretrain-ques-v3/q_decoder_params.epoch49 \ --a_encoder_params baseline_data/seq2seq-pretrain-ans-v3/a_encoder_params.epoch43 \ --a_decoder_params baseline_data/seq2seq-pretrain-ans-v3/a_decoder_params.epoch43 \ --context_params baseline_data/seq2seq-pretrain-util-v3/context_params.epoch10 \ --question_params baseline_data/seq2seq-pretrain-util-v3/question_params.epoch10 \ --answer_params baseline_data/seq2seq-pretrain-util-v3/answer_params.epoch10 \ --utility_params baseline_data/seq2seq-pretrain-util-v3/utility_params.epoch10 \ --word_embeddings embeddings/amazon_200d_embeddings.p \ --vocab embeddings/amazon_200d_vocab.p \ --model GAN_selfcritic_ques49_ans43_util10 \ --max_post_len 100 \ --max_ques_len 20 \ --max_ans_len 20 \ --batch_size 64 \ --n_epochs 20 \ <file_sep>import torch import torch.nn as nn from constants import * class FeedForward(nn.Module): def __init__(self, input_dim): super(FeedForward, self).__init__() self.layer1 = nn.Linear(input_dim, HIDDEN_SIZE) self.relu = nn.ReLU() self.layer2 = nn.Linear(HIDDEN_SIZE, 1) def forward(self, x): x = self.layer1(x) x = self.relu(x) x = self.layer2(x) return x <file_sep>from constants import * import sys sys.path.append('src/utility') from FeedForward import * from evaluate_utility import * import random from RNN import * import time import torch from torch import optim import torch.nn as nn import torch.autograd as autograd from train_utility import * def update_neg_data(data, index2word): ids_seqs, post_seqs, post_lens, ques_seqs, ques_lens, ans_seqs, ans_lens = data N = 2 labels = [0]*int(N*len(post_seqs)) new_post_seqs = [None]*int(N*len(post_seqs)) new_post_lens = [None]*int(N*len(post_lens)) new_ques_seqs = [None]*int(N*len(ques_seqs)) new_ques_lens = [None]*int(N*len(ques_lens)) new_ans_seqs = [None]*int(N*len(ans_seqs)) new_ans_lens = [None]*int(N*len(ans_lens)) for i in range(len(post_seqs)): new_post_seqs[N*i] = post_seqs[i] new_post_lens[N*i] = post_lens[i] new_ques_seqs[N*i] = ques_seqs[i] new_ques_lens[N*i] = ques_lens[i] new_ans_seqs[N*i] = ans_seqs[i] new_ans_lens[N*i] = ans_lens[i] labels[N*i] = 1 for j in range(1, N): r = random.randint(0, len(post_seqs)-1) new_post_seqs[N*i+j] = post_seqs[i] new_post_lens[N*i+j] = post_lens[i] new_ques_seqs[N*i+j] = ques_seqs[r] new_ques_lens[N*i+j] = ques_lens[r] new_ans_seqs[N*i+j] = ans_seqs[r] new_ans_lens[N*i+j] = ans_lens[r] labels[N*i+j] = 0 data = new_post_seqs, new_post_lens, \ new_ques_seqs, new_ques_lens, \ new_ans_seqs, new_ans_lens, labels return data def run_utility(train_data, test_data, word_embeddings, index2word, args, n_layers): context_model = RNN(len(word_embeddings), len(word_embeddings[0]), n_layers) question_model = RNN(len(word_embeddings), len(word_embeddings[0]), n_layers) answer_model = RNN(len(word_embeddings), len(word_embeddings[0]), n_layers) utility_model = FeedForward(HIDDEN_SIZE*3*2) if USE_CUDA: word_embeddings = autograd.Variable(torch.FloatTensor(word_embeddings).cuda()) else: word_embeddings = autograd.Variable(torch.FloatTensor(word_embeddings)) context_model.embedding.weight.data.copy_(word_embeddings) question_model.embedding.weight.data.copy_(word_embeddings) answer_model.embedding.weight.data.copy_(word_embeddings) # Fix word embeddings context_model.embedding.weight.requires_grad = False question_model.embedding.weight.requires_grad = False answer_model.embedding.weight.requires_grad = False optimizer = optim.Adam(list([par for par in context_model.parameters() if par.requires_grad]) + list([par for par in question_model.parameters() if par.requires_grad]) + list([par for par in answer_model.parameters() if par.requires_grad]) + list([par for par in utility_model.parameters() if par.requires_grad])) criterion = nn.BCELoss() # criterion = nn.BCEWithLogitsLoss() if USE_CUDA: device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') context_model = context_model.to(device) question_model = question_model.to(device) answer_model = answer_model.to(device) utility_model = utility_model.to(device) criterion = criterion.to(device) train_data = update_neg_data(train_data, index2word) test_data = update_neg_data(test_data, index2word) for epoch in range(args.n_epochs): start_time = time.time() train_loss, train_acc = train_fn(context_model, question_model, answer_model, utility_model, train_data, optimizer, criterion, args) valid_loss, valid_acc = evaluate(context_model, question_model, answer_model, utility_model, test_data, criterion, args) print('Epoch %d: Train Loss: %.3f, Train Acc: %.3f, Val Loss: %.3f, Val Acc: %.3f' % \ (epoch, train_loss, train_acc, valid_loss, valid_acc)) print('Time taken: ', time.time()-start_time) # if epoch % 5 == 0: print('Saving model params') torch.save(context_model.state_dict(), args.context_params+'.epoch%d' % epoch) torch.save(question_model.state_dict(), args.question_params+'.epoch%d' % epoch) torch.save(answer_model.state_dict(), args.answer_params+'.epoch%d' % epoch) torch.save(utility_model.state_dict(), args.utility_params+'.epoch%d' % epoch) <file_sep>#!/bin/bash #SITENAME=askubuntu.com #SITENAME=unix.stackexchange.com SITENAME=superuser.com CQ_DATA_DIR=/fs/clip-amr/ranking_clarification_questions/data/$SITENAME OUT_DATA_DIR=/fs/clip-amr/clarification_question_generation_pytorch/embeddings SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/embedding_generation python $SCRIPT_DIR/extract_data.py --post_data_tsv $CQ_DATA_DIR/post_data.tsv \ --qa_data_tsv $CQ_DATA_DIR/qa_data.tsv \ --output_data $OUT_DATA_DIR/${SITENAME}.data.txt <file_sep>import argparse import gzip import nltk import pdb import sys, os import re from collections import defaultdict def parse(path): g = gzip.open(path, 'r') for l in g: yield eval(l) exception_chars = ['|', '/', '\\', '-', '(', ')', '!', ':', ';', '<', '>'] def preprocess(text): text = text.replace('|', ' ') text = text.replace('/', ' ') text = text.replace('\\', ' ') text = text.lower() #text = re.sub(r'\W+', ' ', text) ret_text = '' for sent in nltk.sent_tokenize(text): ret_text += ' '.join(nltk.word_tokenize(sent)) + ' ' return ret_text def get_brand_info(metadata_fname): brand_info = {} for v in parse(metadata_fname): if 'description' not in v or 'title' not in v: continue asin = v['asin'] if 'brand' not in v.keys(): brand_info[asin] = None else: brand_info[asin] = v['brand'] return brand_info def get_sim_prods(sim_prods_filename, brand_info): sim_prods_file = open(sim_prods_filename, 'r') sim_prods = {} for line in sim_prods_file.readlines(): parts = line.split() asin = parts[0] sim_prods[asin] = [] for prod_id in parts[2:]: if brand_info[prod_id] and (brand_info[prod_id] != brand_info[asin]): sim_prods[asin].append(prod_id) if len(sim_prods[asin]) == 0: sim_prods[asin] = parts[10:13] return sim_prods def main(args): products = {} for v in parse(args.metadata_fname): if 'description' not in v or 'title' not in v: continue asin = v['asin'] title = preprocess(v['title']) description = preprocess(v['description']) product = title + ' . ' + description products[asin] = product train_asin_file = open(args.train_asin_fname, 'w') train_context_file = open(args.train_context_fname, 'w') train_ques_file = open(args.train_ques_fname, 'w') train_ans_file = open(args.train_ans_fname, 'w') tune_asin_file = open(args.tune_asin_fname, 'w') tune_context_file = open(args.tune_context_fname, 'w') tune_ques_file = open(args.tune_ques_fname, 'w') tune_ans_file = open(args.tune_ans_fname, 'w') test_asin_file = open(args.test_asin_fname, 'w') test_context_file = open(args.test_context_fname, 'w') test_ques_file = open(args.test_ques_fname, 'w') test_ans_file = open(args.test_ans_fname, 'w') brand_info = get_brand_info(args.metadata_fname) sim_prod = get_sim_prods(args.sim_prod_fname, brand_info) asins = [] contexts = [] questions = [] answers = [] for v in parse(args.qa_data_fname): asin = v['asin'] if asin not in products or 'answer' not in v: continue question = preprocess(v['question']) answer = preprocess(v['answer']) if not answer: continue asins.append(asin) contexts.append(products[asin]) questions.append(question) answers.append(answer) for k in range(1, 4): src_line += quess[sim_prod[prod_id][k]][(j) % len(quess[sim_prod[prod_id][k]])] + ' <EOQ> ' N = len(contexts) for i in range(int(N*0.8)): train_asin_file.write(asins[i]+'\n') train_context_file.write(contexts[i]+'\n') train_ques_file.write(questions[i]+'\n') train_ans_file.write(answers[i]+'\n') for i in range(int(N*0.8), int(N*0.9)): tune_asin_file.write(asins[i]+'\n') tune_context_file.write(contexts[i]+'\n') tune_ques_file.write(questions[i]+'\n') tune_ans_file.write(answers[i]+'\n') for i in range(int(N*0.9), N): test_asin_file.write(asins[i]+'\n') test_context_file.write(contexts[i]+'\n') test_ques_file.write(questions[i]+'\n') test_ans_file.write(answers[i]+'\n') train_asin_file.close() train_context_file.close() train_ques_file.close() train_ans_file.close() tune_asin_file.close() tune_context_file.close() tune_ques_file.close() tune_ans_file.close() test_asin_file.close() test_context_file.close() test_ques_file.close() test_ans_file.close() if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--qa_data_fname", type = str) argparser.add_argument("--metadata_fname", type = str) argparser.add_argument("--train_asin_fname", type = str) argparser.add_argument("--train_context_fname", type = str) argparser.add_argument("--train_ques_fname", type = str) argparser.add_argument("--train_ans_fname", type = str) argparser.add_argument("--tune_asin_fname", type = str) argparser.add_argument("--tune_context_fname", type = str) argparser.add_argument("--tune_ques_fname", type = str) argparser.add_argument("--tune_ans_fname", type = str) argparser.add_argument("--test_asin_fname", type = str) argparser.add_argument("--test_context_fname", type = str) argparser.add_argument("--test_ques_fname", type = str) argparser.add_argument("--test_ans_fname", type = str) args = argparser.parse_args() print args print "" main(args) <file_sep>#!/bin/bash #SBATCH --qos=batch #SBATCH --mem=4g #SBATCH --time=05:00:00 SITENAME=askubuntu_unix_superuser CQ_DATA_DIR=/fs/clip-amr/clarification_question_generation_pytorch/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/evaluation PRED_FILE=test_pred_question.txt.GAN_selfcritic_pred_ans_util_dis.epoch8 python $SCRIPT_DIR/create_preds_for_refs.py --qa_data_tsvfile $CQ_DATA_DIR/qa_data.tsv \ --test_ids_file $CQ_DATA_DIR/test_ids \ --human_annotations $CQ_DATA_DIR/human_annotations \ --model_output_file $CQ_DATA_DIR/$PRED_FILE <file_sep>#!/bin/bash SITENAME=askubuntu_unix_superuser CQ_DATA_DIR=clarification_question_generation_pytorch/$SITENAME SCRIPT_DIR=clarification_question_generation_pytorch/src EMB_DIR=clarification_question_generation_pytorch/embeddings/$SITENAME PARAMS_DIR=$CQ_DATA_DIR python $SCRIPT_DIR/main.py --train_context $CQ_DATA_DIR/train_context.txt \ --train_question $CQ_DATA_DIR/train_question.txt \ --train_answer $CQ_DATA_DIR/train_answer.txt \ --train_ids $CQ_DATA_DIR/train_ids \ --tune_context $CQ_DATA_DIR/tune_context.txt \ --tune_question $CQ_DATA_DIR/tune_question.txt \ --tune_answer $CQ_DATA_DIR/tune_answer.txt \ --tune_ids $CQ_DATA_DIR/tune_ids \ --test_context $CQ_DATA_DIR/test_context.txt \ --test_question $CQ_DATA_DIR/test_question.txt \ --test_answer $CQ_DATA_DIR/test_answer.txt \ --test_ids $CQ_DATA_DIR/test_ids \ --q_encoder_params $PARAMS_DIR/q_encoder_params \ --q_decoder_params $PARAMS_DIR/q_decoder_params \ --a_encoder_params $PARAMS_DIR/a_encoder_params \ --a_decoder_params $PARAMS_DIR/a_decoder_params \ --context_params $PARAMS_DIR/context_params \ --question_params $PARAMS_DIR/question_params \ --answer_params $PARAMS_DIR/answer_params \ --utility_params $PARAMS_DIR/utility_params \ --word_embeddings $EMB_DIR/word_embeddings.p \ --vocab $EMB_DIR/vocab.p \ --n_epochs 100 \ --max_post_len 100 \ --max_ques_len 20 \ --max_ans_len 20 \ --pretrain_ques True \ <file_sep>import numpy as np import torch import torch.nn.functional as F def iterate_minibatches(c, cm, q, qm, a, am, l, batch_size, shuffle=True): if shuffle: indices = np.arange(len(c)) np.random.shuffle(indices) for start_idx in range(0, len(c) - batch_size + 1, batch_size): if shuffle: excerpt = indices[start_idx:start_idx + batch_size] else: excerpt = slice(start_idx, start_idx + batch_size) yield c[excerpt], cm[excerpt], q[excerpt], qm[excerpt], a[excerpt], am[excerpt], l[excerpt] def get_masks(lens, max_len): masks = [] for i in range(len(lens)): if lens[i] == None: lens[i] = 0 masks.append([1]*int(lens[i])+[0]*int(max_len-lens[i])) return np.array(masks) def binary_accuracy(predictions, truth): """ Returns accuracy per batch, i.e. if you get 8/10 right, this returns 0.8, NOT 8 """ correct = 0. for i in range(len(predictions)): if predictions[i] >= 0.5 and truth[i] == 1: correct += 1 elif predictions[i] < 0.5 and truth[i] == 0: correct += 1 acc = correct/len(predictions) return acc <file_sep>import sys sys.path.append('src/utility') from helper_utility import * import numpy as np import torch from constants import * def train_fn(context_model, question_model, answer_model, utility_model, train_data, optimizer, criterion, args): epoch_loss = 0 epoch_acc = 0 context_model.train() question_model.train() answer_model.train() utility_model.train() contexts, context_lens, questions, question_lens, answers, answer_lens, labels = train_data context_masks = get_masks(context_lens, args.max_post_len) question_masks = get_masks(question_lens, args.max_ques_len) answer_masks = get_masks(answer_lens, args.max_ans_len) contexts = np.array(contexts) questions = np.array(questions) answers = np.array(answers) labels = np.array(labels) num_batches = 0 for c, cm, q, qm, a, am, l in iterate_minibatches(contexts, context_masks, questions, question_masks, answers, answer_masks, labels, args.batch_size): optimizer.zero_grad() c = torch.tensor(c.tolist()) cm = torch.FloatTensor(cm) q = torch.tensor(q.tolist()) qm = torch.FloatTensor(qm) a = torch.tensor(a.tolist()) am = torch.FloatTensor(am) if USE_CUDA: c = c.cuda() cm = cm.cuda() q = q.cuda() qm = qm.cuda() a = a.cuda() am = am.cuda() # c_out: (sent_len, batch_size, num_directions*HIDDEN_DIM) c_hid, c_out = context_model(torch.transpose(c, 0, 1)) cm = torch.transpose(cm, 0, 1).unsqueeze(2) cm = cm.expand(cm.shape[0], cm.shape[1], 2*HIDDEN_SIZE) c_out = torch.sum(c_out * cm, dim=0) q_hid, q_out = question_model(torch.transpose(q, 0, 1)) qm = torch.transpose(qm, 0, 1).unsqueeze(2) qm = qm.expand(qm.shape[0], qm.shape[1], 2*HIDDEN_SIZE) q_out = torch.sum(q_out * qm, dim=0) a_hid, a_out = answer_model(torch.transpose(a, 0, 1)) am = torch.transpose(am, 0, 1).unsqueeze(2) am = am.expand(am.shape[0], am.shape[1], 2*HIDDEN_SIZE) a_out = torch.sum(a_out * am, dim=0) predictions = utility_model(torch.cat((c_out, q_out, a_out), 1)).squeeze(1) # predictions = utility_model(torch.cat((c_out, q_out), 1)).squeeze(1) # predictions = utility_model(q_out).squeeze(1) predictions = torch.nn.functional.sigmoid(predictions) l = torch.FloatTensor([float(lab) for lab in l]) if USE_CUDA: l = l.cuda() loss = criterion(predictions, l) acc = binary_accuracy(predictions, l) loss.backward() optimizer.step() epoch_loss += loss.item() epoch_acc += acc num_batches += 1 return epoch_loss, epoch_acc / num_batches <file_sep>import argparse import csv from collections import defaultdict import sys import numpy as np import pdb on_topic_levels = {'Yes': 1, 'No': 0} is_grammatical_levels = {'Grammatical': 1, 'Comprehensible': 1, 'Incomprehensible': 0} is_specific_levels = {'Specific pretty much only to this product': 4, 'Specific to this and other very similar products (or the same product from a different manufacturer)': 3, 'Generic enough to be applicable to many other products of this type': 2, 'Generic enough to be applicable to any product under Home and Kitchen': 1, 'N/A (Not Applicable)': -1} asks_new_info_levels = {'Completely': 1, 'Somewhat': 1, 'No': 0, 'N/A (Not Applicable)': -1} useful_levels = {'Useful enough to be included in the product description': 4, 'Useful to a large number of potential buyers (or current users)': 3, 'Useful to a small number of potential buyers (or current users)': 2, 'Useful only to the person asking the question': 1, 'N/A (Not Applicable)': -1} model_dict = {'ref': 0, 'lucene': 1, 'seq2seq.beam': 2, 'rl.beam': 3, 'gan.beam': 4} model_list = ['ref', 'lucene', 'seq2seq.beam', 'rl.beam', 'gan.beam'] frequent_words = ['dimensions', 'dimension', 'size', 'measurements', 'measurement', 'weight', 'height', 'width', 'diameter', 'density', 'bpa', 'difference', 'thread', 'china', 'usa'] def get_avg_score(score_dict, ignore_na=True): curr_on_topic_score = 0. N = 0 for score, count in score_dict.iteritems(): if score != -1: curr_on_topic_score += score * count if ignore_na: if score != -1: N += count else: N += count #print N return curr_on_topic_score * 1.0 / N def main(args): num_models = len(model_list) on_topic_conf_scores = [] is_grammatical_conf_scores = [] is_specific_conf_scores = [] asks_new_info_conf_scores = [] useful_conf_scores = [] asins_so_far = [None] * num_models for i in range(num_models): asins_so_far[i] = [] with open(args.aggregate_results) as csvfile: reader = csv.DictReader(csvfile) for row in reader: if row['_golden'] == 'true' or row['_unit_state'] == 'golden': continue asin = row['asin'] question = row['question'] model_name = row['model_name'] if model_name not in model_list: continue if asin not in asins_so_far[model_dict[model_name]]: asins_so_far[model_dict[model_name]].append(asin) else: print '%s duplicate %s' % (model_name, asin) continue on_topic_score = on_topic_levels[row['on_topic']] on_topic_conf_score = float(row['on_topic:confidence']) is_grammatical_score = is_grammatical_levels[row['grammatical']] is_grammatical_conf_score = float(row['grammatical:confidence']) is_specific_conf_score = float(row['is_specific:confidence']) asks_new_info_score = asks_new_info_levels[row['new_info']] asks_new_info_conf_score = float(row['new_info:confidence']) useful_conf_score = float(row['useful_to_another_buyer:confidence']) on_topic_conf_scores.append(on_topic_conf_score) is_grammatical_conf_scores.append(is_grammatical_conf_score) if on_topic_score != 0 and is_grammatical_score != 0: is_specific_conf_scores.append(is_specific_conf_score) asks_new_info_conf_scores.append(asks_new_info_conf_score) if asks_new_info_score != 0: useful_conf_scores.append(useful_conf_score) print 'On topic confidence: %.4f' % (sum(on_topic_conf_scores)/float(len(on_topic_conf_scores))) print 'Is grammatical confidence: %.4f' % (sum(is_grammatical_conf_scores)/float(len(is_grammatical_conf_scores))) print 'Asks new info confidence: %.4f' % (sum(asks_new_info_conf_scores)/float(len(asks_new_info_conf_scores))) print 'Useful confidence: %.4f' % (sum(useful_conf_scores)/float(len(useful_conf_scores))) print 'Specificity confidence: %.4f' % (sum(is_specific_conf_scores)/float(len(is_specific_conf_scores))) if __name__ == '__main__': argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--aggregate_results", type = str) args = argparser.parse_args() print args print "" main(args) <file_sep>import sys import argparse from collections import defaultdict def main(args): train_ids_file = open(args.train_ids, 'r') train_answer_file = open(args.train_answer, 'r') train_candqs_ids_file = open(args.train_candqs_ids, 'r') train_answer_candqs_file = open(args.train_answer_candqs, 'w') train_ids = [] uniq_id_ct = defaultdict(int) for line in train_ids_file.readlines(): curr_id = line.strip('\n') uniq_id_ct[curr_id] += 1 train_ids.append(curr_id+'_'+str(uniq_id_ct[curr_id])) i = 0 train_answers = {} for line in train_answer_file.readlines(): train_answers[train_ids[i]] = line.strip('\n') i += 1 for line in train_candqs_ids_file.readlines(): curr_id = line.strip('\n') try: train_answer_candqs_file.write(train_answers[curr_id]) except: import pdb pdb.set_trace() if __name__ == '__main__': argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--train_ids", type=str) argparser.add_argument("--train_answer", type=str) argparser.add_argument("--train_candqs_ids", type=str) argparser.add_argument("--train_answer_candqs", type=str) args = argparser.parse_args() print args print "" main(args) <file_sep>#!/bin/bash #SITENAME=askubuntu_unix_superuser SITENAME=Home_and_Kitchen SCRIPTS_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/embedding_generation EMB_DIR=/fs/clip-amr/clarification_question_generation_pytorch/embeddings/$SITENAME/200 python $SCRIPTS_DIR/create_we_vocab.py $EMB_DIR/vectors.txt $EMB_DIR/word_embeddings.p $EMB_DIR/vocab.p <file_sep>#!/bin/bash #SBATCH --job-name=utility_data_aus #SBATCH --output=utility_data_aus #SBATCH --qos=batch #SBATCH --mem=36g #SBATCH --time=24:00:00 #SITENAME=askubuntu.com #SITENAME=unix.stackexchange.com SITENAME=superuser.com #SITENAME=askubuntu_unix_superuser #SITENAME=Home_and_Kitchen QA_DATA_DIR=/fs/clip-scratch/raosudha/clarification_question_generation/question_answering/$SITENAME UTILITY_DATA_DIR=/fs/clip-scratch/raosudha/clarification_question_generation/utility/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/utility export PATH="/fs/clip-amr/anaconda2/bin:$PATH" python $SCRIPT_DIR/data_loader.py --train_contexts_fname $QA_DATA_DIR/train_src \ --train_answers_fname $QA_DATA_DIR/train_tgt \ --tune_contexts_fname $QA_DATA_DIR/tune_src \ --tune_answers_fname $QA_DATA_DIR/tune_tgt \ --test_contexts_fname $QA_DATA_DIR/test_src \ --test_answers_fname $QA_DATA_DIR/test_tgt \ --train_data $UTILITY_DATA_DIR/train_data.p \ --tune_data $UTILITY_DATA_DIR/tune_data.p \ --test_data $UTILITY_DATA_DIR/test_data.p \ #--word_to_ix $UTILITY_DATA_DIR/word_to_ix.p \ <file_sep>import argparse import pickle as p import sys import torch from seq2seq.encoderRNN import * from seq2seq.attnDecoderRNN import * from seq2seq.RL_beam_decoder import * # from seq2seq.diverse_beam_decoder import * from seq2seq.RL_evaluate import * # from RL_helper import * from constants import * def main(args): print('Enter main') word_embeddings = p.load(open(args.word_embeddings, 'rb')) print('Loaded emb of size %d' % len(word_embeddings)) word_embeddings = np.array(word_embeddings) word2index = p.load(open(args.vocab, 'rb')) index2word = reverse_dict(word2index) if args.test_ids is not None: test_data = read_data(args.test_context, args.test_question, None, args.test_ids, args.max_post_len, args.max_ques_len, args.max_ans_len, mode='test') else: test_data = read_data(args.test_context, args.test_question, None, None, args.max_post_len, args.max_ques_len, args.max_ans_len, mode='test') print('No. of test_data %d' % len(test_data)) run_model(test_data, word_embeddings, word2index, index2word, args) def run_model(test_data, word_embeddings, word2index, index2word, args): print('Preprocessing test data..') te_id_seqs, te_post_seqs, te_post_lens, te_ques_seqs, te_ques_lens, \ te_post_ques_seqs, te_post_ques_lens, te_ans_seqs, te_ans_lens = preprocess_data(test_data, word2index, args.max_post_len, args.max_ques_len, args.max_ans_len) print('Defining encoder decoder models') q_encoder = EncoderRNN(HIDDEN_SIZE, word_embeddings, n_layers=2, dropout=DROPOUT) q_decoder = AttnDecoderRNN(HIDDEN_SIZE, len(word2index), word_embeddings, n_layers=2) if USE_CUDA: device = torch.device('cuda:0') else: device = torch.device('cpu') q_encoder = q_encoder.to(device) q_decoder = q_decoder.to(device) # Load encoder, decoder params print('Loading encoded, decoder params') if USE_CUDA: q_encoder.load_state_dict(torch.load(args.q_encoder_params)) q_decoder.load_state_dict(torch.load(args.q_decoder_params)) else: q_encoder.load_state_dict(torch.load(args.q_encoder_params, map_location='cpu')) q_decoder.load_state_dict(torch.load(args.q_decoder_params, map_location='cpu')) out_fname = args.test_pred_question+'.'+args.model # out_fname = None if args.greedy: evaluate_seq2seq(word2index, index2word, q_encoder, q_decoder, te_id_seqs, te_post_seqs, te_post_lens, te_ques_seqs, te_ques_lens, args.batch_size, args.max_ques_len, out_fname) elif args.beam: evaluate_beam(word2index, index2word, q_encoder, q_decoder, te_id_seqs, te_post_seqs, te_post_lens, te_ques_seqs, te_ques_lens, args.batch_size, args.max_ques_len, out_fname) elif args.diverse_beam: evaluate_diverse_beam(word2index, index2word, q_encoder, q_decoder, te_id_seqs, te_post_seqs, te_post_lens, te_ques_seqs, te_ques_lens, args.batch_size, args.max_ques_len, out_fname) else: print('Please specify mode of decoding: --greedy OR --beam OR --diverse_beam') if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--test_context", type = str) argparser.add_argument("--test_question", type = str) argparser.add_argument("--test_answer", type = str) argparser.add_argument("--test_ids", type=str) argparser.add_argument("--test_pred_question", type = str) argparser.add_argument("--q_encoder_params", type = str) argparser.add_argument("--q_decoder_params", type = str) argparser.add_argument("--vocab", type = str) argparser.add_argument("--word_embeddings", type = str) argparser.add_argument("--max_post_len", type = int, default=300) argparser.add_argument("--max_ques_len", type = int, default=50) argparser.add_argument("--max_ans_len", type = int, default=50) argparser.add_argument("--batch_size", type = int, default=128) argparser.add_argument("--model", type=str) argparser.add_argument("--greedy", type=bool, default=False) argparser.add_argument("--beam", type=bool, default=False) argparser.add_argument("--diverse_beam", type=bool, default=False) args = argparser.parse_args() print(args) print("") main(args) <file_sep>import argparse import gzip import nltk import pdb import sys, os import re from collections import defaultdict def parse(path): g = gzip.open(path, 'r') for l in g: yield eval(l) exception_chars = ['|', '/', '\\', '-', '(', ')', '!', ':', ';', '<', '>'] def preprocess(text): text = text.replace('|', ' ') text = text.replace('/', ' ') text = text.replace('\\', ' ') text = text.lower() ret_text = '' for sent in nltk.sent_tokenize(text): ret_text += ' '.join(nltk.word_tokenize(sent)) + ' ' return ret_text def main(args): output_file = open(args.output_fname, 'w') for v in parse(args.metadata_fname): if 'description' not in v or 'title' not in v: continue title = preprocess(v['title']) description = preprocess(v['description']) product = title + ' . ' + description output_file.write(product+'\n') for v in parse(args.qa_data_fname): if 'answer' not in v: continue question = preprocess(v['question']) answer = preprocess(v['answer']) output_file.write(question+'\n') output_file.write(answer+'\n') output_file.close() if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--qa_data_fname", type = str) argparser.add_argument("--metadata_fname", type = str) argparser.add_argument("--output_fname", type = str) args = argparser.parse_args() print args print "" main(args) <file_sep>import argparse, sys import pickle as p import numpy as np import torch from torchtext import data import torch.nn as nn import torch.optim as optim import torch.autograd as autograd class RNN(nn.Module): def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim, n_layers, bidirectional, dropout): super(RNN, self).__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim) self.rnn = nn.LSTM(embedding_dim, hidden_dim, num_layers=n_layers, bidirectional=bidirectional, dropout=dropout) self.fc = nn.Linear(hidden_dim*2, output_dim) self.dropout = nn.Dropout(dropout) def forward(self, x): #x = [sent len, batch size] embedded = self.dropout(self.embedding(x)) #embedded = [sent len, batch size, emb dim] output, (hidden, cell) = self.rnn(embedded) #output = [sent len, batch size, hid dim * num directions] #hidden = [num layers * num directions, batch size, hid. dim] #cell = [num layers * num directions, batch size, hid. dim] hidden = self.dropout(torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim=1)) #hidden [batch size, hid. dim * num directions] return self.fc(hidden.squeeze(0)) class FeedForward(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim): super(FeedForward, self).__init__() self.layer1 = nn.Linear(input_dim, hidden_dim) self.relu = nn.ReLU() self.layer2 = nn.Linear(hidden_dim, output_dim) def forward(self, x): x = self.layer1(x) x = self.relu(x) x = self.layer2(x) return x import torch.nn.functional as F def binary_accuracy(preds, y): """ Returns accuracy per batch, i.e. if you get 8/10 right, this returns 0.8, NOT 8 """ #round predictions to the closest integer rounded_preds = torch.round(F.sigmoid(preds)) correct = (rounded_preds == y).float() #convert into float for division acc = correct.sum()/len(correct) return acc def train_fn(context_model, question_model, answer_model, utility_model, train_data, optimizer, criterion, batch_size): epoch_loss = 0 epoch_acc = 0 context_model.train() question_model.train() answer_model.train() utility_model.train() contexts, questions, answers, labels = train_data num_batches = 0 for c, q, a, l in iterate_minibatches(contexts, questions, answers, labels, batch_size): optimizer.zero_grad() c_out = context_model(torch.transpose(c, 0, 1)).squeeze(1) q_out = question_model(torch.transpose(q, 0, 1)).squeeze(1) a_out = answer_model(torch.transpose(a, 0, 1)).squeeze(1) predictions = utility_model(torch.cat((c_out, q_out, a_out), 1)).squeeze(1) loss = criterion(predictions, l) acc = binary_accuracy(predictions, l) loss.backward() optimizer.step() epoch_loss += loss.item() epoch_acc += acc.item() num_batches += 1 return epoch_loss / num_batches, epoch_acc / num_batches def evaluate(context_model, question_model, answer_model, utility_model, dev_data, criterion, batch_size): epoch_loss = 0 epoch_acc = 0 num_batches = 0 context_model.eval() question_model.eval() answer_model.eval() utility_model.eval() with torch.no_grad(): contexts, questions, answers, labels = dev_data for c, q, a, l in iterate_minibatches(contexts, questions, answers, labels, batch_size): c_out = context_model(torch.transpose(c, 0, 1)).squeeze(1) q_out = question_model(torch.transpose(q, 0, 1)).squeeze(1) a_out = answer_model(torch.transpose(a, 0, 1)).squeeze(1) predictions = utility_model(torch.cat((c_out, q_out, a_out), 1)).squeeze(1) loss = criterion(predictions, l) acc = binary_accuracy(predictions, l) epoch_loss += loss.item() epoch_acc += acc.item() num_batches += 1 return epoch_loss / num_batches, epoch_acc / num_batches def prepare_sequence(seq, to_ix, max_len, cuda=False): sequences = [] mask_idx = 0 for s in seq: sequence = [to_ix[w] if w in to_ix else to_ix['<unk>'] for w in s.split(' ')[:max_len]] sequence += [mask_idx]*int(max_len - len(sequence)) sequences.append(sequence) sequences = torch.LongTensor(sequences).cuda() return sequences def prepare_data(input_data, vocab, split, cuda): input_data = np.array(input_data) input_data = np.transpose(input_data) contexts_data, questions_data, answers_data, labels_data = input_data #contexts_data = contexts_data[:80240] #questions_data = questions_data[:80240] #answers_data = answers_data[:80240] #labels_data = labels_data[:80240] labels_data = np.array(labels_data, dtype=np.int32) contexts = prepare_sequence(contexts_data, vocab, 250, cuda) questions = prepare_sequence(questions_data, vocab, 50, cuda) answers = prepare_sequence(answers_data, vocab, 50, cuda) labels = prepare_label(labels_data, cuda) output_data = [contexts, questions, answers, labels] return output_data def prepare_label(labels, cuda=False): if cuda: #var = autograd.Variable(torch.FloatTensor([float(l) for l in labels]).cuda()) var = torch.FloatTensor([float(l) for l in labels]).cuda() else: var = autograd.Variable(torch.FloatTensor([float(l) for l in labels])) return var def iterate_minibatches(contexts, questions, answers, labels, batch_size, shuffle=True): if shuffle: indices = np.arange(len(contexts)) np.random.shuffle(indices) for start_idx in range(0, len(contexts) - batch_size + 1, batch_size): if shuffle: excerpt = indices[start_idx:start_idx + batch_size] else: excerpt = slice(start_idx, start_idx + batch_size) yield contexts[excerpt], questions[excerpt], answers[excerpt], labels[excerpt] def main(args): SEED = 1234 torch.manual_seed(SEED) torch.cuda.manual_seed(SEED) train_data = p.load(open(args.train_data, 'rb')) dev_data = p.load(open(args.tune_data, 'rb')) test_data = p.load(open(args.test_data, 'rb')) word_embeddings = p.load(open(args.word_embeddings, 'rb')) vocab = p.load(open(args.vocab, 'rb')) BATCH_SIZE = 64 INPUT_DIM = len(vocab) EMBEDDING_DIM = len(word_embeddings[0]) HIDDEN_DIM = 100 OUTPUT_DIM = 1 N_LAYERS = 1 BIDIRECTIONAL = True DROPOUT = 0.5 context_model = RNN(INPUT_DIM, EMBEDDING_DIM, HIDDEN_DIM, HIDDEN_DIM, N_LAYERS, BIDIRECTIONAL, DROPOUT) question_model = RNN(INPUT_DIM, EMBEDDING_DIM, HIDDEN_DIM, HIDDEN_DIM, N_LAYERS, BIDIRECTIONAL, DROPOUT) answer_model = RNN(INPUT_DIM, EMBEDDING_DIM, HIDDEN_DIM, HIDDEN_DIM, N_LAYERS, BIDIRECTIONAL, DROPOUT) utility_model = FeedForward(HIDDEN_DIM*3, HIDDEN_DIM, OUTPUT_DIM) criterion = nn.BCEWithLogitsLoss() device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') utility_model = utility_model.to(device) context_model = context_model.to(device) question_model = question_model.to(device) answer_model = answer_model.to(device) criterion = criterion.to(device) word_embeddings = autograd.Variable(torch.FloatTensor(word_embeddings).cuda()) context_model.embedding.weight.data.copy_(word_embeddings) question_model.embedding.weight.data.copy_(word_embeddings) answer_model.embedding.weight.data.copy_(word_embeddings) # Fix word embeddings context_model.embedding.weight.requires_grad = False question_model.embedding.weight.requires_grad = False answer_model.embedding.weight.requires_grad = False optimizer = optim.Adam(list([par for par in context_model.parameters() if par.requires_grad]) + \ list([par for par in question_model.parameters() if par.requires_grad]) + \ list([par for par in answer_model.parameters() if par.requires_grad]) + \ list([par for par in utility_model.parameters() if par.requires_grad])) N_EPOCHS = 300 train_data = prepare_data(train_data, vocab, 'train', args.cuda) dev_data = prepare_data(dev_data, vocab, 'dev', args.cuda) test_data = prepare_data(test_data, vocab, 'test', args.cuda) for epoch in range(N_EPOCHS): train_loss, train_acc = train_fn(context_model, question_model, answer_model, utility_model, \ train_data, optimizer, criterion, BATCH_SIZE) valid_loss, valid_acc = evaluate(context_model, question_model, answer_model, utility_model, \ dev_data, criterion, BATCH_SIZE) #valid_loss, valid_acc = evaluate(context_model, question_model, answer_model, utility_model, \ # test_data, criterion, BATCH_SIZE) print 'Epoch %d: Train Loss: %.3f, Train Acc: %.3f, Val Loss: %.3f, Val Acc: %.3f' % (epoch, train_loss, train_acc, valid_loss, valid_acc) if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--train_data", type = str) argparser.add_argument("--tune_data", type = str) argparser.add_argument("--test_data", type = str) argparser.add_argument("--word_embeddings", type = str) argparser.add_argument("--vocab", type = str) argparser.add_argument("--cuda", type = bool) args = argparser.parse_args() print args print "" main(args) <file_sep>import argparse import gzip import nltk import pdb import sys, os import re from collections import defaultdict def parse(path): g = gzip.open(path, 'r') for l in g: yield eval(l) exception_chars = ['|', '/', '\\', '-', '(', ')', '!', ':', ';', '<', '>'] def preprocess(text): text = text.replace('|', ' ') text = text.replace('/', ' ') text = text.replace('\\', ' ') text = text.lower() #text = re.sub(r'\W+', ' ', text) ret_text = '' for sent in nltk.sent_tokenize(text): ret_text += ' '.join(nltk.word_tokenize(sent)) + ' ' return ret_text def main(args): products = {} for v in parse(args.metadata_fname): if 'description' not in v or 'title' not in v: continue asin = v['asin'] title = preprocess(v['title']) description = preprocess(v['description']) product = title + ' . ' + description products[asin] = product train_asin_file = open(args.train_asin_fname, 'w') train_context_file = open(args.train_context_fname, 'w') train_ques_file = open(args.train_ques_fname, 'w') train_ans_file = open(args.train_ans_fname, 'w') tune_asin_file = open(args.tune_asin_fname, 'w') tune_context_file = open(args.tune_context_fname, 'w') tune_ques_file = open(args.tune_ques_fname, 'w') tune_ans_file = open(args.tune_ans_fname, 'w') test_asin_file = open(args.test_asin_fname, 'w') test_context_file = open(args.test_context_fname, 'w') test_ques_file = open(args.test_ques_fname, 'w') test_ans_file = open(args.test_ans_fname, 'w') asins = [] contexts = [] questions = [] answers = [] for v in parse(args.qa_data_fname): asin = v['asin'] if asin not in products or 'answer' not in v: continue question = preprocess(v['question']) answer = preprocess(v['answer']) if not answer: continue asins.append(asin) contexts.append(products[asin]) questions.append(question) answers.append(answer) N = len(contexts) for i in range(int(N*0.8)): train_asin_file.write(asins[i]+'\n') train_context_file.write(contexts[i]+'\n') train_ques_file.write(questions[i]+'\n') train_ans_file.write(answers[i]+'\n') for i in range(int(N*0.8), int(N*0.9)): tune_asin_file.write(asins[i]+'\n') tune_context_file.write(contexts[i]+'\n') tune_ques_file.write(questions[i]+'\n') tune_ans_file.write(answers[i]+'\n') for i in range(int(N*0.9), N): test_asin_file.write(asins[i]+'\n') test_context_file.write(contexts[i]+'\n') test_ques_file.write(questions[i]+'\n') test_ans_file.write(answers[i]+'\n') train_asin_file.close() train_context_file.close() train_ques_file.close() train_ans_file.close() tune_asin_file.close() tune_context_file.close() tune_ques_file.close() tune_ans_file.close() test_asin_file.close() test_context_file.close() test_ques_file.close() test_ans_file.close() if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--qa_data_fname", type = str) argparser.add_argument("--metadata_fname", type = str) argparser.add_argument("--train_asin_fname", type = str) argparser.add_argument("--train_context_fname", type = str) argparser.add_argument("--train_ques_fname", type = str) argparser.add_argument("--train_ans_fname", type = str) argparser.add_argument("--tune_asin_fname", type = str) argparser.add_argument("--tune_context_fname", type = str) argparser.add_argument("--tune_ques_fname", type = str) argparser.add_argument("--tune_ans_fname", type = str) argparser.add_argument("--test_asin_fname", type = str) argparser.add_argument("--test_context_fname", type = str) argparser.add_argument("--test_ques_fname", type = str) argparser.add_argument("--test_ans_fname", type = str) args = argparser.parse_args() print args print "" main(args) <file_sep># -*- coding: utf-8 -*- import argparse import sys import torch import torch.autograd as autograd import random import torch.utils.data as Data import pickle as p def load_data(contexts_fname, answers_fname): contexts_file = open(contexts_fname, 'r') answers_file = open(answers_fname, 'r') contexts = [] questions = [] answers = [] for line in contexts_file.readlines(): context, question = line.strip('\n').split('<EOP>') contexts.append(context) questions.append(question) answers = [line.strip('\n') for line in answers_file.readlines()] data = [] for i in range(len(contexts)): data.append([contexts[i], questions[i], answers[i], 1]) r = random.randint(0, len(contexts)-1) data.append([contexts[i], questions[r], answers[r], 0]) random.shuffle(data) return data def main(args): train_data = load_data(args.train_contexts_fname, args.train_answers_fname) dev_data = load_data(args.tune_contexts_fname, args.tune_answers_fname) test_data = load_data(args.test_contexts_fname, args.test_answers_fname) p.dump(train_data, open(args.train_data, 'wb')) p.dump(dev_data, open(args.tune_data, 'wb')) p.dump(test_data, open(args.test_data, 'wb')) if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--train_contexts_fname", type = str) argparser.add_argument("--train_answers_fname", type = str) argparser.add_argument("--tune_contexts_fname", type = str) argparser.add_argument("--tune_answers_fname", type = str) argparser.add_argument("--test_contexts_fname", type = str) argparser.add_argument("--test_answers_fname", type = str) argparser.add_argument("--train_data", type = str) argparser.add_argument("--tune_data", type = str) argparser.add_argument("--test_data", type = str) args = argparser.parse_args() print args print "" main(args) <file_sep>import argparse import gzip import nltk import pdb import sys, os import re from collections import defaultdict def parse(path): g = gzip.open(path, 'r') for l in g: yield eval(l) exception_chars = ['|', '/', '\\', '-', '(', ')', '!', ':', ';', '<', '>'] def preprocess(text): text = text.replace('|', ' ') text = text.replace('/', ' ') text = text.replace('\\', ' ') text = text.lower() #text = re.sub(r'\W+', ' ', text) ret_text = '' for sent in nltk.sent_tokenize(text): ret_text += ' '.join(nltk.word_tokenize(sent)) + ' ' return ret_text def main(args): brand_counts = defaultdict(int) for v in parse(args.metadata_fname): if 'description' not in v or 'title' not in v or 'brand' not in v: continue brand_counts[v['brand']] += 1 low_ct_brands = [] for brand, ct in brand_counts.iteritems(): if ct < 100: low_ct_brands.append(brand) products = {} for v in parse(args.metadata_fname): if 'description' not in v or 'title' not in v or 'brand' not in v: continue if v['brand'] not in low_ct_brands: continue asin = v['asin'] title = preprocess(v['title']) description = preprocess(v['description']) product = title + ' . ' + description products[asin] = product question_list = {} print 'Creating docs' for v in parse(args.qa_data_fname): asin = v['asin'] if asin not in products: continue print asin if asin not in question_list: f = open(os.path.join(args.product_dir, asin + '.txt'), 'w') f.write(products[asin]) f.close() question_list[asin] = [] question = preprocess(v['question']) question_list[asin].append(question) f = open(os.path.join(args.question_dir, asin + '_' + str(len(question_list[asin])) + '.txt'), 'w') f.write(question) f.close() if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--qa_data_fname", type = str) argparser.add_argument("--metadata_fname", type = str) argparser.add_argument("--product_dir", type = str) argparser.add_argument("--question_dir", type = str) args = argparser.parse_args() print args print "" main(args) <file_sep>import argparse import csv from collections import defaultdict import sys import numpy as np import pdb generic_levels = {'Yes': 1, 'No': 0} model_dict = {'ref': 0, 'lucene': 1, 'seq2seq.beam': 2, 'rl.beam': 3, 'gan.beam': 4} model_list = ['ref', 'lucene', 'seq2seq.beam', 'rl.beam', 'gan.beam'] def get_avg_score(score_dict, ignore_na=False): curr_on_topic_score = 0. N = 0 for score, count in score_dict.iteritems(): curr_on_topic_score += score * count if ignore_na: if score != 0: N += count else: N += count # print N return curr_on_topic_score * 1.0 / N def main(args): num_models = len(model_list) generic_scores = [None] * num_models asins_so_far = [None] * num_models for i in range(num_models): generic_scores[i] = defaultdict(int) asins_so_far[i] = [] with open(args.aggregate_results) as csvfile: reader = csv.DictReader(csvfile) for row in reader: if row['_golden'] == 'true' or row['_unit_state'] == 'golden': continue asin = row['asin'] question = row['question'] model_name = row['model_name'] if model_name not in model_list: continue if asin not in asins_so_far[model_dict[model_name]]: asins_so_far[model_dict[model_name]].append(asin) else: print '%s duplicate %s' % (model_name, asin) continue generic_score = generic_levels[row['on_topic']] generic_scores[model_dict[model_name]][generic_score] += 1 for i in range(num_models): print model_list[i] print len(asins_so_far[i]) print 'Avg on generic score: %.2f' % get_avg_score(generic_scores[i]) print 'Generic:', generic_scores[i] if __name__ == '__main__': argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--aggregate_results", type = str) args = argparser.parse_args() print args print "" main(args)<file_sep>import argparse import csv from collections import defaultdict import sys import pdb import numpy as np specificity_levels = ['Question A is more specific', 'Question B is more specific', 'Both are at the same level of specificity', 'N/A: One or both questions are not applicable to the product'] def get_avg_score(score_dict, ignore_na=False): curr_on_topic_score = 0. N = 0 for score, count in score_dict.iteritems(): curr_on_topic_score += score * count if ignore_na: if score != 0: N += count else: N += count # print N return curr_on_topic_score * 1.0 / N def main(args): titles = {} descriptions = {} cand_ques_dict = defaultdict(list) cand_scores_dict = defaultdict(list) curr_asin = None curr_a = None curr_b = None a_scores = [] b_scores = [] ab_scores = [] with open(args.full_results) as csvfile: reader = csv.DictReader(csvfile) for row in reader: if row['_golden'] == 'true' or row['_tainted'] == 'true': continue asin = row['asin'] titles[asin] = row['title'] descriptions[asin] = row['description'] question_a = row['question_a'] question_b = row['question_b'] trust = row['_trust'] if curr_asin is None: curr_asin = asin curr_a = question_a curr_b = question_b elif asin != curr_asin and curr_a != question_a and curr_b != question_b: a_score = np.sum(a_scores)/5 b_score = np.sum(b_scores)/5 ab_score = np.sum(ab_scores)/5 cand_scores_dict[curr_asin][cand_ques_dict[curr_asin].index(curr_a)].append(a_score + 0.5*ab_score) cand_scores_dict[curr_asin][cand_ques_dict[curr_asin].index(curr_b)].append(b_score + 0.5*ab_score) curr_asin = asin curr_a = question_a curr_b = question_b a_scores = [] b_scores = [] ab_scores = [] if question_a not in cand_ques_dict[asin]: cand_ques_dict[asin].append(question_a) cand_scores_dict[asin].append([]) if question_b not in cand_ques_dict[asin]: cand_ques_dict[asin].append(question_b) cand_scores_dict[asin].append([]) if row['on_topic'] == 'Question A is more specific': a_scores.append(float(trust)) elif row['on_topic'] == 'Question B is more specific': b_scores.append(float(trust)) elif row['on_topic'] == 'Both are at the same level of specificity': ab_scores.append(float(trust)) else: print 'ID: %s has irrelevant question' % asin corr = 0 total = 0 fp, tp, fn, tn = 0, 0, 0, 0 for asin in titles: print asin print titles[asin] print descriptions[asin] for i, ques in enumerate(cand_ques_dict[asin]): true_v = np.mean(cand_scores_dict[asin][i]) pred_v = np.mean(cand_scores_dict[asin][i][:int(len(cand_scores_dict[asin][i])/2)]) print true_v, cand_scores_dict[asin][i], ques print pred_v if true_v < 0.5: true_l = 0 else: true_l = 1 if pred_v < 0.5: pred_l = 0 else: pred_l = 1 if true_l == pred_l: corr += 1 if true_l == 0 and pred_l == 1: fp += 1 if true_l == 0 and pred_l == 0: tn += 1 if true_l == 1 and pred_l == 0: fn += 1 if true_l == 1 and pred_l == 1: tp += 1 total += 1 print print 'accuracy' print corr*1.0/total print tp, fp, fn, tn if __name__ == '__main__': argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--full_results", type = str) args = argparser.parse_args() print args print "" main(args) <file_sep>python src/main.py --train_context baseline_data/train_context.txt \ --train_ques baseline_data/train_question.txt \ --train_ans baseline_data/train_answer.txt \ --train_ids baseline_data/train_asin.txt \ --tune_context baseline_data/valid_context.txt \ --tune_ques baseline_data/valid_question.txt \ --tune_ans baseline_data/valid_answer.txt \ --tune_ids baseline_data/valid_asin.txt \ --test_context baseline_data/test_context.txt \ --test_ques baseline_data/test_question.txt \ --test_ans baseline_data/test_answer.txt \ --test_ids baseline_data/test_asin.txt \ --q_encoder_params $PT_OUTPUT_DIR/q_encoder_params \ --q_decoder_params $PT_OUTPUT_DIR/q_decoder_params \ --a_encoder_params $PT_OUTPUT_DIR/a_encoder_params \ --a_decoder_params $PT_OUTPUT_DIR/a_decoder_params \ --context_params $PT_OUTPUT_DIR/context_params \ --question_params $PT_OUTPUT_DIR/question_params \ --answer_params $PT_OUTPUT_DIR/answer_params \ --utility_params $PT_OUTPUT_DIR/utility_params \ --word_embeddings embeddings/amazon_200d_embeddings.p \ --vocab embeddings/amazon_200d_vocab.p \ --n_epochs 100 \ --batch_size 128 \ --max_post_len 100 \ --max_ques_len 20 \ --max_ans_len 20 \ --pretrain_ques True \ #--pretrain_ans True \ #--pretrain_util True \ <file_sep>import torch import torch.nn as nn from constants import * class RNN(nn.Module): def __init__(self, vocab_size, embedding_dim, n_layers): super(RNN, self).__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim) self.rnn = nn.LSTM(embedding_dim, HIDDEN_SIZE, num_layers=n_layers, bidirectional=True) self.fc = nn.Linear(HIDDEN_SIZE*2, HIDDEN_SIZE) self.dropout = nn.Dropout(DROPOUT) def forward(self, x): #x = [sent len, batch size] embedded = self.dropout(self.embedding(x)) #embedded = [sent len, batch size, emb dim] output, (hidden, cell) = self.rnn(embedded) #output = [sent len, batch size, hid dim * num directions] #hidden = [num layers * num directions, batch size, hid. dim] #cell = [num layers * num directions, batch size, hid. dim] hidden = self.dropout(torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1)) #hidden [batch size, hid. dim * num directions] return self.fc(hidden.squeeze(0)), output <file_sep>import argparse import csv from collections import defaultdict import sys import numpy as np import pdb relevance_levels = {'Completely makes sense': 2, 'Somewhat makes sense': 1, 'Does not make sense': 0} is_grammatical_levels = {'Grammatical': 2, 'Comprehensible': 1, 'Incomprehensible': 0} is_specific_levels = {'Specific to this or the same product from a different manufacturer': 3, 'Specific to this or some other similar products': 2, 'Generic enough to be applicable to many other products of this type': 1, 'Generic enough to be applicable to any product under Home and Kitchen': 0, 'N/A (Not Applicable)': 0} asks_new_info_levels = {'Yes': 1, 'No': 0, 'N/A (Not Applicable)': 0} model_dict = {'ref': 0, 'lucene': 1, 'seq2seq': 2, 'seq2seq.generic': 3, 'seq2seq.specific': 4} model_list = ['ref', 'lucene', 'seq2seq', 'seq2seq.generic', 'seq2seq.specific'] def get_avg_score(score_dict, ignore_na=False): curr_relevance_score = 0. N = 0 for score, count in score_dict.iteritems(): curr_relevance_score += score * count if ignore_na: if score != 0: N += count else: N += count # print N return curr_relevance_score * 1.0 / N def main(args): num_models = len(model_list) relevance_scores = [None] * num_models is_grammatical_scores = [None] * num_models is_specific_scores = [None] * num_models asks_new_info_scores = [None] * num_models asins_so_far = [None] * num_models for i in range(num_models): relevance_scores[i] = defaultdict(int) is_grammatical_scores[i] = defaultdict(int) is_specific_scores[i] = defaultdict(int) asks_new_info_scores[i] = defaultdict(int) asins_so_far[i] = [] with open(args.aggregate_results) as csvfile: reader = csv.DictReader(csvfile) for row in reader: if row['_golden'] == 'true' or row['_unit_state'] == 'golden': continue asin = row['asin'] question = row['question'] model_name = row['model_name'] if model_name not in model_list: continue if asin not in asins_so_far[model_dict[model_name]]: asins_so_far[model_dict[model_name]].append(asin) else: #print '%s duplicate %s' % (model_name, asin) continue relevance_score = relevance_levels[row['makes_sense']] is_grammatical_score = is_grammatical_levels[row['grammatical']] specific_score = is_specific_levels[row['is_specific']] asks_new_info_score = asks_new_info_levels[row['new_info']] relevance_scores[model_dict[model_name]][relevance_score] += 1 is_grammatical_scores[model_dict[model_name]][is_grammatical_score] += 1 if relevance_score != 0 and is_grammatical_score != 0: is_specific_scores[model_dict[model_name]][specific_score] += 1 asks_new_info_scores[model_dict[model_name]][asks_new_info_score] += 1 for i in range(num_models): print model_list[i] print len(asins_so_far[i]) print 'Avg on topic score: %.2f' % get_avg_score(relevance_scores[i]) print 'Avg grammaticality score: %.2f' % get_avg_score(is_grammatical_scores[i]) print 'Avg specificity score: %.2f' % get_avg_score(is_specific_scores[i]) print 'Avg new info score: %.2f' % get_avg_score(asks_new_info_scores[i]) print print 'On topic:', relevance_scores[i] print 'Is grammatical: ', is_grammatical_scores[i] print 'Is specific: ', is_specific_scores[i] print 'Asks new info: ', asks_new_info_scores[i] print if __name__ == '__main__': argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--aggregate_results", type = str) args = argparser.parse_args() print args print "" main(args) <file_sep>import sys import pickle as p if __name__ == "__main__": askubuntu = p.load(open(sys.argv[1], 'rb')) unix = p.load(open(sys.argv[2], 'rb')) superuser = p.load(open(sys.argv[3], 'rb')) combined = unix + superuser + askubuntu p.dump(combined, open(sys.argv[4], 'wb')) <file_sep>from constants import * import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F class Attn(nn.Module): def __init__(self, hidden_size): super(Attn, self).__init__() self.hidden_size = hidden_size def forward(self, hidden, encoder_outputs): max_len = encoder_outputs.size(0) this_batch_size = encoder_outputs.size(1) # Create variable to store attention energies attn_energies = Variable(torch.zeros(this_batch_size, max_len)) # B x S if USE_CUDA: attn_energies = attn_energies.cuda() attn_energies = torch.bmm(hidden.transpose(0, 1), encoder_outputs.transpose(0,1).transpose(1,2)).squeeze(1) # Normalize energies to weights in range 0 to 1, resize to 1 x B x S return F.softmax(attn_energies, dim=1).unsqueeze(1) <file_sep>import argparse import gzip import nltk import pdb import sys from collections import defaultdict import csv import random def parse(path): g = gzip.open(path, 'r') for l in g: yield eval(l) def read_model_outputs(model_fname): i = 0 model_outputs = {} model_file = open(model_fname, 'r') test_ids = [line.strip('\n') for line in open(model_fname+'.ids', 'r')] for line in model_file.readlines(): model_outputs[test_ids[i]] = line.strip('\n').replace(' <unk>', '').replace(' <EOS>', '') i += 1 return model_outputs def main(args): titles = {} descriptions = {} lucene_model_outs = read_model_outputs(args.lucene_model_fname) seq2seq_model_outs = read_model_outputs(args.seq2seq_model_fname) rl_model_outs = read_model_outputs(args.rl_model_fname) gan_model_outs = read_model_outputs(args.gan_model_fname) prev_batch_asins = [] with open(args.batch1_csv_file) as csvfile: reader = csv.DictReader(csvfile) for row in reader: asin = row['asin'] prev_batch_asins.append(asin) with open(args.batch2_csv_file) as csvfile: reader = csv.DictReader(csvfile) for row in reader: asin = row['asin'] prev_batch_asins.append(asin) with open(args.batch3_csv_file) as csvfile: reader = csv.DictReader(csvfile) for row in reader: asin = row['asin'] prev_batch_asins.append(asin) for v in parse(args.metadata_fname): asin = v['asin'] if asin in prev_batch_asins: continue if asin not in lucene_model_outs.keys(): continue title = v['title'] description = v['description'] length = len(description.split()) if length >= 100 or length < 10 or len(title.split()) == length: continue titles[asin] = title descriptions[asin] = description questions = defaultdict(list) for v in parse(args.qa_data_fname): asin = v['asin'] if asin in prev_batch_asins: continue if asin not in lucene_model_outs.keys(): continue if asin not in descriptions: continue question = ' '.join(nltk.sent_tokenize(v['question'])).lower() questions[asin].append(question) csv_file = open(args.csv_file, 'w') writer = csv.writer(csv_file, delimiter=',') writer.writerow(['asin', 'title', 'description', 'model_name', 'question']) all_rows = [] max_count = 200 i = 0 for asin in lucene_model_outs.keys(): if asin in prev_batch_asins: continue if asin not in titles: continue title = titles[asin] description = descriptions[asin] ref_question = random.choice(questions[asin]) lucene_question = lucene_model_outs[asin] if lucene_question == '': print 'Found empty line in lucene' continue seq2seq_question = seq2seq_model_outs[asin] rl_question = rl_model_outs[asin] gan_question = gan_model_outs[asin] all_rows.append([asin, title, description, 'ref', ref_question]) all_rows.append([asin, title, description, args.lucene_model_name, lucene_question]) all_rows.append([asin, title, description, args.seq2seq_model_name, seq2seq_question]) all_rows.append([asin, title, description, args.rl_model_name, rl_question]) all_rows.append([asin, title, description, args.gan_model_name, gan_question]) i += 1 if i >= max_count: break random.shuffle(all_rows) for row in all_rows: writer.writerow(row) csv_file.close() if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--qa_data_fname", type = str) argparser.add_argument("--metadata_fname", type = str) argparser.add_argument("--batch1_csv_file", type=str) argparser.add_argument("--batch2_csv_file", type=str) argparser.add_argument("--batch3_csv_file", type=str) argparser.add_argument("--csv_file", type=str) argparser.add_argument("--lucene_model_fname", type=str) argparser.add_argument("--lucene_model_name", type=str) argparser.add_argument("--seq2seq_model_fname", type=str) argparser.add_argument("--seq2seq_model_name", type=str) argparser.add_argument("--rl_model_fname", type=str) argparser.add_argument("--rl_model_name", type=str) argparser.add_argument("--gan_model_fname", type=str) argparser.add_argument("--gan_model_name", type=str) args = argparser.parse_args() print args print "" main(args) <file_sep>import sys import pickle as p PAD_token = '<PAD>' SOS_token = '<SOS>' EOP_token = '<EOP>' EOS_token = '<EOS>' if __name__ == "__main__": if len(sys.argv) < 4: print("usage: python create_we_vocab.py <word_vectors.txt> <output_we.p> <output_vocab.p>") sys.exit(0) word_vectors_file = open(sys.argv[1], 'r') word_embeddings = [] vocab = {} vocab[PAD_token] = 0 vocab[SOS_token] = 1 vocab[EOP_token] = 2 vocab[EOS_token] = 3 word_embeddings.append(None) word_embeddings.append(None) word_embeddings.append(None) word_embeddings.append(None) i = 4 for line in word_vectors_file.readlines(): vals = line.rstrip().split(' ') vocab[vals[0]] = i word_embeddings.append([float(v) for v in vals[1:]]) i += 1 word_embeddings[0] = [0]*len(word_embeddings[4]) word_embeddings[1] = [0]*len(word_embeddings[4]) word_embeddings[2] = [0]*len(word_embeddings[4]) word_embeddings[3] = [0]*len(word_embeddings[4]) p.dump(word_embeddings, open(sys.argv[2], 'wb')) p.dump(vocab, open(sys.argv[3], 'wb')) <file_sep>import argparse import sys import os import pickle as p import string import time import datetime import math import sys import torch import torch.nn as nn from torch import optim from torch.autograd import Variable import torch.nn.functional as F from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence#, masked_cross_entropy import numpy as np from seq2seq.encoderRNN import * from seq2seq.attnDecoderRNN import * from seq2seq.read_data import * from seq2seq.prepare_data import * from seq2seq.masked_cross_entropy import * from seq2seq.RL_train import * from seq2seq.RL_evaluate import * from seq2seq.RL_inference import * from seq2seq.RL_beam_decoder import * from seq2seq.baselineFF import * from seq2seq.GAN_train import * from utility.RNN import * from utility.FeedForward import * from utility.RL_evaluate import * from utility.RL_train import * from utility.train_utility import * from RL_helper import * from constants import * def initialize_generator(word_embeddings, word2index): print('Defining encoder decoder models') q_encoder = EncoderRNN(HIDDEN_SIZE, word_embeddings, n_layers=2, dropout=DROPOUT) q_decoder = AttnDecoderRNN(HIDDEN_SIZE, len(word2index), word_embeddings, n_layers=2) a_encoder = EncoderRNN(HIDDEN_SIZE, word_embeddings, n_layers=2, dropout=DROPOUT) a_decoder = AttnDecoderRNN(HIDDEN_SIZE, len(word2index), word_embeddings, n_layers=2) baseline_model = BaselineFF(HIDDEN_SIZE) if USE_CUDA: device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') q_encoder = q_encoder.to(device) q_decoder = q_decoder.to(device) a_encoder = a_encoder.to(device) a_decoder = a_decoder.to(device) baseline_model.to(device) # Load encoder, decoder params print('Loading encoder, decoder params') q_encoder.load_state_dict(torch.load(args.q_encoder_params)) q_decoder.load_state_dict(torch.load(args.q_decoder_params)) a_encoder.load_state_dict(torch.load(args.a_encoder_params)) a_decoder.load_state_dict(torch.load(args.a_decoder_params)) print('Done!') q_encoder_optimizer = optim.Adam([par for par in q_encoder.parameters() if par.requires_grad], lr=LEARNING_RATE) q_decoder_optimizer = optim.Adam([par for par in q_decoder.parameters() if par.requires_grad], lr=LEARNING_RATE * DECODER_LEARNING_RATIO) a_encoder_optimizer = optim.Adam([par for par in a_encoder.parameters() if par.requires_grad], lr=LEARNING_RATE) a_decoder_optimizer = optim.Adam([par for par in a_decoder.parameters() if par.requires_grad], lr=LEARNING_RATE * DECODER_LEARNING_RATIO) baseline_optimizer = optim.Adam(baseline_model.parameters()) baseline_criterion = torch.nn.MSELoss() return q_encoder, q_decoder, q_encoder_optimizer, q_decoder_optimizer, \ a_encoder, a_decoder, a_encoder_optimizer, a_decoder_optimizer, \ baseline_model, baseline_optimizer, baseline_criterion def initialize_discriminator(word_embeddings): context_model = RNN(len(word_embeddings), len(word_embeddings[0]), n_layers=1) question_model = RNN(len(word_embeddings), len(word_embeddings[0]), n_layers=1) answer_model = RNN(len(word_embeddings), len(word_embeddings[0]), n_layers=1) utility_model = FeedForward(HIDDEN_SIZE * 3 * 2) # utility_model = FeedForward(HIDDEN_SIZE * 2 * 2) # utility_model = FeedForward(HIDDEN_SIZE * 2) utility_criterion = torch.nn.BCELoss() if USE_CUDA: device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') context_model.to(device) question_model.to(device) answer_model.to(device) utility_model.to(device) # Load utility calculator model params print('Loading utility model params') context_model.load_state_dict(torch.load(args.context_params)) question_model.load_state_dict(torch.load(args.question_params)) answer_model.load_state_dict(torch.load(args.answer_params)) utility_model.load_state_dict(torch.load(args.utility_params)) print('Done') u_optimizer = optim.Adam(list([par for par in context_model.parameters() if par.requires_grad]) + list([par for par in question_model.parameters() if par.requires_grad]) + list([par for par in answer_model.parameters() if par.requires_grad]) + list([par for par in utility_model.parameters() if par.requires_grad])) return context_model, question_model, answer_model, utility_model, u_optimizer, utility_criterion def run_generator(tr_post_seqs, tr_post_lens, tr_ques_seqs, tr_ques_lens, tr_post_ques_seqs, tr_post_ques_lens, tr_ans_seqs, tr_ans_lens, q_encoder, q_decoder, q_encoder_optimizer, q_decoder_optimizer, a_encoder, a_decoder, a_encoder_optimizer, a_decoder_optimizer, baseline_model, baseline_optimizer, baseline_criterion, context_model, question_model, answer_model, utility_model, word2index, index2word, mixer_delta, args): epoch = 0. total_xe_loss = 0. total_rl_loss = 0. total_a_loss = 0. total_u_pred = 0. total_u_b_pred = 0. while epoch < args.g_n_epochs: epoch += 1 for post, pl, ques, ql, pq, pql, ans, al in iterate_minibatches(tr_post_seqs, tr_post_lens, tr_ques_seqs, tr_ques_lens, tr_post_ques_seqs, tr_post_ques_lens, tr_ans_seqs, tr_ans_lens, args.batch_size): xe_loss, rl_loss, a_loss, \ reward, b_reward = GAN_train(post, pl, ques, ql, ans, al, q_encoder, q_decoder, q_encoder_optimizer, q_decoder_optimizer, a_encoder, a_decoder, a_encoder_optimizer, a_decoder_optimizer, baseline_model, baseline_optimizer, baseline_criterion, context_model, question_model, answer_model, utility_model, word2index, index2word, mixer_delta, args) total_xe_loss += xe_loss if mixer_delta != args.max_ques_len: total_u_pred += reward.data.sum() / args.batch_size total_u_b_pred += b_reward.data.sum() / args.batch_size total_rl_loss += rl_loss total_a_loss += a_loss total_xe_loss = total_xe_loss / args.g_n_epochs total_rl_loss = total_rl_loss / args.g_n_epochs total_a_loss = total_a_loss / args.g_n_epochs total_u_pred = total_u_pred / args.g_n_epochs total_u_b_pred = total_u_b_pred / args.g_n_epochs return total_xe_loss, total_rl_loss, total_a_loss, total_u_pred, total_u_b_pred def run_discriminator(tr_post_seqs, tr_post_lens, tr_ques_seqs, tr_ques_lens, tr_post_ques_seqs, tr_post_ques_lens, tr_ans_seqs, tr_ans_lens, q_encoder, q_decoder, a_encoder, a_decoder, baseline_model, baseline_criterion, mixer_delta, context_model, question_model, answer_model, utility_model, optimizer, utility_criterion, word2index, index2word, args): epoch = 0. total_loss = 0 total_acc = 0 context_model.train() question_model.train() answer_model.train() utility_model.train() q_encoder.eval() q_decoder.eval() a_encoder.eval() a_decoder.eval() while epoch < args.a_n_epochs: epoch += 1 data_size = int((len(tr_post_seqs)/args.batch_size)*args.batch_size*2) post_data = [None]*data_size post_len_data = [None]*data_size ques_data = [None]*data_size ques_len_data = [None]*data_size ans_data = [None]*data_size ans_len_data = [None]*data_size labels_data = [None]*data_size batch_num = 0 for post, pl, ques, ql, pq, pql, ans, al in iterate_minibatches(tr_post_seqs, tr_post_lens, tr_ques_seqs, tr_ques_lens, tr_post_ques_seqs, tr_post_ques_lens, tr_ans_seqs, tr_ans_lens, args.batch_size): q_pred, ql_pred, a_pred, al_pred, \ a_pred_true, al_pred_true = GAN_train(post, pl, ques, ql, ans, al, q_encoder, q_decoder, None, None, a_encoder, a_decoder, None, None, baseline_model, None, baseline_criterion, context_model, question_model, answer_model, utility_model, word2index, index2word, mixer_delta, args, mode='test') # pq_pred = np.concatenate((post, ques), axis=1) # pql_pred = np.full(args.batch_size, args.max_post_len + args.max_ques_len) # a_pred_true, al_pred_true = evaluate_batch(pq_pred, pql_pred, a_encoder, a_decoder, # word2index, args.max_ans_len, args.batch_size, # ans, al) # if epoch < 2 and batch_num < 5: # # print 'True Q: %s' % ' '.join([index2word[idx] for idx in ques[0]]) # # print 'True A: %s' % ' '.join([index2word[idx] for idx in ans[0]]) # print 'Fake Q: %s' % ' '.join([index2word[idx] for idx in q_pred[0]]) # print 'Fake A: %s' % ' '.join([index2word[idx] for idx in a_pred[0]]) # print post_data[batch_num*2*args.batch_size: batch_num*2*args.batch_size + args.batch_size] = post post_data[batch_num*2*args.batch_size + args.batch_size: batch_num*2*args.batch_size + 2 * args.batch_size] = post post_len_data[batch_num*2*args.batch_size: batch_num*2*args.batch_size + args.batch_size] = pl post_len_data[batch_num*2*args.batch_size + args.batch_size: batch_num*2*args.batch_size + 2 * args.batch_size] = pl ques_data[batch_num*2*args.batch_size: batch_num*2*args.batch_size + args.batch_size] = ques ques_data[batch_num*2*args.batch_size + args.batch_size: batch_num*2*args.batch_size + 2 * args.batch_size] = q_pred ques_len_data[batch_num*2*args.batch_size: batch_num*2*args.batch_size + args.batch_size] = ql ques_len_data[batch_num*2*args.batch_size + args.batch_size: batch_num*2*args.batch_size + 2 * args.batch_size] = ql_pred # ans_data[batch_num*2*args.batch_size: # batch_num*2*args.batch_size + args.batch_size] = ans ans_data[batch_num*2*args.batch_size: batch_num*2*args.batch_size + args.batch_size] = a_pred_true ans_data[batch_num*2*args.batch_size + args.batch_size: batch_num*2*args.batch_size + 2 * args.batch_size] = a_pred # ans_len_data[batch_num*2*args.batch_size: # batch_num*2*args.batch_size + args.batch_size] = al ans_len_data[batch_num*2*args.batch_size: batch_num*2*args.batch_size + args.batch_size] = al_pred_true ans_len_data[batch_num*2*args.batch_size + args.batch_size: batch_num*2*args.batch_size + 2 * args.batch_size] = al_pred labels_data[batch_num*2*args.batch_size: batch_num*2*args.batch_size + 2*args.batch_size] = \ np.concatenate((np.ones(len(post)), np.zeros(len(post))), axis=0) batch_num += 1 permutation = np.random.permutation(len(post_data)) post_data = np.array(post_data)[permutation] post_len_data = np.array(post_len_data)[permutation] ques_data = np.array(ques_data)[permutation] ques_len_data = np.array(ques_len_data)[permutation] ans_data = np.array(ans_data)[permutation] ans_len_data = np.array(ans_len_data)[permutation] labels_data = np.array(labels_data)[permutation] for i in range(len(post_data)): if post_data[i] is None: post_data[i] = np.array([0]*len(post_data[i-1])) for i in range(len(ques_data)): if ques_data[i] is None: ques_data[i] = np.array([0]*len(ques_data[i-1])) for i in range(len(ans_data)): if ans_data[i] is None: ans_data[i] = np.array([0]*len(ans_data[i-1])) for i in range(len(labels_data)): if labels_data[i] == None: labels_data[i] = 0 train_data = post_data, post_len_data, ques_data, ques_len_data, ans_data, ans_len_data, labels_data train_loss, train_acc = train_fn(context_model, question_model, answer_model, utility_model, train_data, optimizer, utility_criterion, args) total_loss += train_loss total_acc += train_acc total_loss = total_loss / args.a_n_epochs total_acc = total_acc / args.a_n_epochs return total_loss, total_acc def run_model(train_data, test_data, word_embeddings, word2index, index2word, args): print('Preprocessing train data..') tr_id_seqs, tr_post_seqs, tr_post_lens, tr_ques_seqs, tr_ques_lens,\ tr_post_ques_seqs, tr_post_ques_lens, tr_ans_seqs, tr_ans_lens = preprocess_data(train_data, word2index, args.max_post_len, args.max_ques_len, args.max_ans_len) print('Preprocessing test data..') te_id_seqs, te_post_seqs, te_post_lens, te_ques_seqs, te_ques_lens, \ te_post_ques_seqs, te_post_ques_lens, te_ans_seqs, te_ans_lens = preprocess_data(test_data, word2index, args.max_post_len, args.max_ques_len, args.max_ans_len) q_encoder, q_decoder, q_encoder_optimizer, q_decoder_optimizer, \ a_encoder, a_decoder, a_encoder_optimizer, a_decoder_optimizer, \ baseline_model, baseline_optimizer, baseline_criterion = initialize_generator(word_embeddings, word2index) context_model, question_model, answer_model, \ utility_model, u_optimizer, utility_criterion = initialize_discriminator(word_embeddings) start = time.time() epoch = 0. n_batches = len(tr_post_seqs)/args.batch_size mixer_delta = args.max_ques_len while epoch < args.n_epochs: epoch += 1 if mixer_delta >= 4: mixer_delta = mixer_delta - 2 total_xe_loss, total_rl_loss, total_a_loss, total_u_pred, total_u_b_pred = \ run_generator(tr_post_seqs, tr_post_lens, tr_ques_seqs, tr_ques_lens, tr_post_ques_seqs, tr_post_ques_lens, tr_ans_seqs, tr_ans_lens, q_encoder, q_decoder, q_encoder_optimizer, q_decoder_optimizer, a_encoder, a_decoder, a_encoder_optimizer, a_decoder_optimizer, baseline_model, baseline_optimizer, baseline_criterion, context_model, question_model, answer_model, utility_model, word2index, index2word, mixer_delta, args) print_xe_loss_avg = total_xe_loss / n_batches print_rl_loss_avg = total_rl_loss / n_batches print_a_loss_avg = total_a_loss / n_batches print_u_pred_avg = total_u_pred / n_batches print_u_b_pred_avg = total_u_b_pred / n_batches print_summary = 'Generator (RL) %s %d XE_loss: %.4f RL_loss: %.4f A_loss: %.4f U_pred: %.4f B_pred: %.4f' % \ (time_since(start, epoch / args.n_epochs), epoch, print_xe_loss_avg, print_rl_loss_avg, print_a_loss_avg, print_u_pred_avg, print_u_b_pred_avg) print(print_summary) if epoch > -1: total_u_loss, total_u_acc = run_discriminator(tr_post_seqs, tr_post_lens, tr_ques_seqs, tr_ques_lens, tr_post_ques_seqs, tr_post_ques_lens, tr_ans_seqs, tr_ans_lens, q_encoder, q_decoder, a_encoder, a_decoder, baseline_model, baseline_criterion, mixer_delta, context_model, question_model, answer_model, utility_model, u_optimizer, utility_criterion, word2index, index2word, args) print_u_loss_avg = total_u_loss print_u_acc_avg = total_u_acc print_summary = 'Discriminator: %s %d U_loss: %.4f U_acc: %.4f ' % \ (time_since(start, epoch / args.n_epochs), epoch, print_u_loss_avg, print_u_acc_avg) print(print_summary) print('Saving GAN model params') torch.save(q_encoder.state_dict(), args.q_encoder_params + '.' + args.model + '.epoch%d' % epoch) torch.save(q_decoder.state_dict(), args.q_decoder_params + '.' + args.model + '.epoch%d' % epoch) # torch.save(a_encoder.state_dict(), args.a_encoder_params + '.' + args.model + '.epoch%d' % epoch) # torch.save(a_decoder.state_dict(), args.a_decoder_params + '.' + args.model + '.epoch%d' % epoch) torch.save(context_model.state_dict(), args.context_params + '.' + args.model + '.epoch%d' % epoch) torch.save(question_model.state_dict(), args.question_params + '.' + args.model + '.epoch%d' % epoch) torch.save(answer_model.state_dict(), args.answer_params + '.' + args.model + '.epoch%d' % epoch) torch.save(utility_model.state_dict(), args.utility_params + '.' + args.model + '.epoch%d' % epoch) #print 'Running evaluation...' #out_fname = args.test_pred_question + '.' + args.model + '.epoch%d' % int(epoch) #evaluate_beam(word2index, index2word, q_encoder, q_decoder, # te_id_seqs, te_post_seqs, te_post_lens, te_ques_seqs, te_ques_lens, # args.batch_size, args.max_ques_len, out_fname) def main(args): word_embeddings = p.load(open(args.word_embeddings, 'rb')) word_embeddings = np.array(word_embeddings) word2index = p.load(open(args.vocab, 'rb')) index2word = reverse_dict(word2index) if args.train_ids is not None: train_data = read_data(args.train_context, args.train_question, args.train_answer, args.train_ids, args.max_post_len, args.max_ques_len, args.max_ans_len, mode='train') #count=args.batch_size*10) else: train_data = read_data(args.train_context, args.train_question, args.train_answer, None, args.max_post_len, args.max_ques_len, args.max_ans_len, mode='train') train_data = train_data[:50000] if args.tune_ids is not None: test_data = read_data(args.tune_context, args.tune_question, args.tune_answer, args.tune_ids, args.max_post_len, args.max_ques_len, args.max_ans_len, mode='test') #count=args.batch_size*5) else: test_data = read_data(args.tune_context, args.tune_question, args.tune_answer, None, args.max_post_len, args.max_ques_len, args.max_ans_len, mode='test') print('No. of train_data %d' % len(train_data)) print('No. of test_data %d' % len(test_data)) run_model(train_data, test_data, word_embeddings, word2index, index2word, args) if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--train_context", type = str) argparser.add_argument("--train_question", type = str) argparser.add_argument("--train_answer", type = str) argparser.add_argument("--train_ids", type=str) argparser.add_argument("--tune_context", type = str) argparser.add_argument("--tune_question", type = str) argparser.add_argument("--tune_answer", type = str) argparser.add_argument("--tune_ids", type=str) argparser.add_argument("--test_context", type = str) argparser.add_argument("--test_question", type = str) argparser.add_argument("--test_answer", type = str) argparser.add_argument("--test_ids", type=str) argparser.add_argument("--test_pred_question", type = str) argparser.add_argument("--q_encoder_params", type = str) argparser.add_argument("--q_decoder_params", type = str) argparser.add_argument("--a_encoder_params", type = str) argparser.add_argument("--a_decoder_params", type = str) argparser.add_argument("--context_params", type = str) argparser.add_argument("--question_params", type = str) argparser.add_argument("--answer_params", type = str) argparser.add_argument("--utility_params", type = str) argparser.add_argument("--vocab", type = str) argparser.add_argument("--word_embeddings", type = str) argparser.add_argument("--max_post_len", type = int, default=300) argparser.add_argument("--max_ques_len", type = int, default=50) argparser.add_argument("--max_ans_len", type = int, default=50) argparser.add_argument("--n_epochs", type = int, default=20) argparser.add_argument("--g_n_epochs", type=int, default=1) argparser.add_argument("--a_n_epochs", type=int, default=1) argparser.add_argument("--batch_size", type = int, default=256) argparser.add_argument("--model", type=str) args = argparser.parse_args() print(args) print("") main(args) <file_sep>#!/bin/bash #SBATCH --job-name=create_crowdflower_HK_beam_batch4 #SBATCH --output=create_crowdflower_HK_beam_batch4 #SBATCH --qos=batch #SBATCH --mem=32g #SBATCH --time=4:00:00 SITENAME=Home_and_Kitchen CORPORA_DIR=/fs/clip-corpora/amazon_qa DATA_DIR=/fs/clip-scratch/raosudha/clarification_question_generation/joint_learning/$SITENAME CROWDFLOWER_DIR=/fs/clip-amr/clarification_question_generation_pytorch/evaluation/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/evaluation export PATH="/fs/clip-amr/anaconda2/bin:$PATH" python $SCRIPT_DIR/create_crowdflower_data.py --qa_data_fname $CORPORA_DIR/qa_${SITENAME}.json.gz \ --metadata_fname $CORPORA_DIR/meta_${SITENAME}.json.gz \ --batch1_csv_file $CROWDFLOWER_DIR/crowdflower_lucene_seq2seq_rl_gan_diverse_beam_epoch8.batch1.csv \ --batch2_csv_file $CROWDFLOWER_DIR/crowdflower_lucene_seq2seq_rl_gan_beam_epoch8.batch2.csv \ --batch3_csv_file $CROWDFLOWER_DIR/crowdflower_lucene_seq2seq_rl_gan_beam_epoch8.batch3.csv \ --csv_file $CROWDFLOWER_DIR/crowdflower_lucene_seq2seq_rl_gan_beam_epoch8.batch4.csv \ --lucene_model_name lucene \ --lucene_model_fname $DATA_DIR/blind_test_pred_question.lucene.txt \ --seq2seq_model_name seq2seq.beam \ --seq2seq_model_fname $DATA_DIR/blind_test_pred_question.txt.seq2seq.len_norm.beam0 \ --rl_model_name rl.beam \ --rl_model_fname $DATA_DIR/blind_test_pred_question.txt.RL_selfcritic.epoch8.len_norm.beam0 \ --gan_model_name gan.beam \ --gan_model_fname $DATA_DIR/blind_test_pred_question.txt.GAN_selfcritic_pred_ans_3perid.epoch8.len_norm.beam0 \ <file_sep>import argparse import sys, os from collections import defaultdict import csv import math import pdb import random import gzip def parse(path): g = gzip.open(path, 'r') for l in g: yield eval(l) def get_brand_info(metadata_fname): brand_info = {} for v in parse(metadata_fname): if 'description' not in v or 'title' not in v: continue asin = v['asin'] if 'brand' not in v.keys(): brand_info[asin] = None else: brand_info[asin] = v['brand'] return brand_info def create_lucene_preds(ids, args, quess, sim_prod): pred_file = open(args.lucene_pred_fname, 'w') for test_id in ids: prod_id = test_id.split('_')[0] choices = [] for i in range(min(len(sim_prod[prod_id]), 3)): choices += quess[sim_prod[prod_id][i]][:3] if len(choices) == 0: pred_file.write('\n') else: pred_ques = random.choice(choices) pred_file.write(pred_ques+'\n') pred_file.close() def get_sim_docs(sim_docs_filename, brand_info): sim_docs_file = open(sim_docs_filename, 'r') sim_docs = {} for line in sim_docs_file.readlines(): parts = line.split() #sim_docs[parts[0]] = parts[1:] asin = parts[0] sim_docs[asin] = [] if len(parts[1:]) == 0: continue for prod_id in parts[2:]: if brand_info[prod_id] and (brand_info[prod_id] != brand_info[asin]): sim_docs[asin].append(prod_id) if len(sim_docs[asin]) == 0: sim_docs[asin] = parts[10:13] if len(sim_docs[asin]) == 0: pdb.set_trace() return sim_docs def read_data(args): print("Reading lines...") quess = {} test_ids = [test_id.strip('\n') for test_id in open(args.test_ids_file, 'r').readlines()] print 'No. of test ids: %d' % len(test_ids) quess_rand = defaultdict(list) for fname in os.listdir(args.ques_dir): with open(os.path.join(args.ques_dir, fname), 'r') as f: ques_id = fname[:-4] asin, q_no = ques_id.split('_') ques = f.readline().strip('\n') quess_rand[asin].append((ques, q_no)) for asin in quess_rand: quess[asin] = [None]*len(quess_rand[asin]) for (ques, q_no) in quess_rand[asin]: q_no = int(q_no)-1 quess[asin][q_no] = ques brand_info = get_brand_info(args.metadata_fname) sim_prod = get_sim_docs(args.sim_prod_fname, brand_info) create_lucene_preds(test_ids, args, quess, sim_prod) if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--ques_dir", type = str) argparser.add_argument("--sim_prod_fname", type = str) argparser.add_argument("--test_ids_file", type = str) argparser.add_argument("--lucene_pred_fname", type = str) argparser.add_argument("--metadata_fname", type = str) args = argparser.parse_args() print args print "" read_data(args) <file_sep>#!/bin/bash #SBATCH --job-name=meteor #SBATCH --qos=batch #SBATCH --mem=4g #SBATCH --time=4:00:00 METEOR=/fs/clip-software/user-supported/meteor-1.5 CQ_DATA_DIR=/fs/clip-amr/clarification_question_generation_pytorch/Home_and_Kitchen/ RESULTS_DIR=/fs/clip-amr/clarification_question_generation_pytorch/evaluation/results/Home_and_Kitchen TEST_SET=test_pred_ques.txt.seq2seq.epoch100.beam0.nounks java -Xmx2G -jar $METEOR/meteor-1.5.jar $CQ_DATA_DIR/$TEST_SET $CQ_DATA_DIR/test_ref_combined \ -l en -norm -r 10 \ > $RESULTS_DIR/${TEST_SET}.meteor <file_sep>import sys import argparse def main(args): ref_sents = [None]*int(args.no_of_refs) for i in range(int(args.no_of_refs)): with open(args.ref_prefix+str(i), 'r') as f: ref_sents[i] = [line.strip('\n') for line in f.readlines()] combined_ref_file = open(args.combined_ref_fname, 'w') for i in range(len(ref_sents[0])): for j in range(int(args.no_of_refs)): combined_ref_file.write(ref_sents[j][i]+'\n') combined_ref_file.close() if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--ref_prefix", type = str) argparser.add_argument("--no_of_refs", type = int) argparser.add_argument("--combined_ref_fname", type = str) args = argparser.parse_args() print args print "" main(args) <file_sep>import argparse import csv from collections import defaultdict import sys import pdb import numpy as np specificity_levels = ['Question A is more specific', 'Question B is more specific', 'Both are at the same level of specificity', 'N/A: One or both questions are not applicable to the product'] def get_avg_score(score_dict, ignore_na=False): curr_on_topic_score = 0. N = 0 for score, count in score_dict.iteritems(): curr_on_topic_score += score * count if ignore_na: if score != 0: N += count else: N += count # print N return curr_on_topic_score * 1.0 / N def main(args): titles = {} descriptions = {} cand_ques_dict = defaultdict(list) cand_scores_dict = defaultdict(list) with open(args.aggregate_results) as csvfile: reader = csv.DictReader(csvfile) for row in reader: if row['_unit_state'] != 'finalized': continue asin = row['asin'] titles[asin] = row['title'] descriptions[asin] = row['description'] question_a = row['question_a'] question_b = row['question_b'] confidence = row['on_topic:confidence'] if question_a not in cand_ques_dict[asin]: cand_ques_dict[asin].append(question_a) cand_scores_dict[asin].append([]) if question_b not in cand_ques_dict[asin]: cand_ques_dict[asin].append(question_b) cand_scores_dict[asin].append([]) if row['on_topic'] == 'Question A is more specific': cand_scores_dict[asin][cand_ques_dict[asin].index(question_a)].append(float(confidence)) cand_scores_dict[asin][cand_ques_dict[asin].index(question_b)].append((1 - float(confidence))) elif row['on_topic'] == 'Question B is more specific': cand_scores_dict[asin][cand_ques_dict[asin].index(question_b)].append(float(confidence)) cand_scores_dict[asin][cand_ques_dict[asin].index(question_a)].append((1 - float(confidence))) elif row['on_topic'] == 'Both are at the same level of specificity': cand_scores_dict[asin][cand_ques_dict[asin].index(question_b)].append(0.5) cand_scores_dict[asin][cand_ques_dict[asin].index(question_a)].append(0.5) else: print 'ID: %s has irrelevant question' % asin for asin in titles: print asin print titles[asin] print descriptions[asin] for i, ques in enumerate(cand_ques_dict[asin]): print np.mean(cand_scores_dict[asin][i]), cand_scores_dict[asin][i], ques print if __name__ == '__main__': argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--aggregate_results", type = str) args = argparser.parse_args() print args print "" main(args)<file_sep>import random from constants import * from prepare_data import * from masked_cross_entropy import * from helper import * import torch from torch.autograd import Variable import pdb def evaluate_beam_batch(input_seqs, input_lens, encoder, decoder, word2index, index2word, max_out_len, batch_size): encoder.eval() decoder.eval() if USE_CUDA: input_seqs_batch = Variable(torch.LongTensor(input_seqs).cuda()).transpose(0, 1) else: input_seqs_batch = Variable(torch.LongTensor(input_seqs)).transpose(0, 1) # Run post words through encoder encoder_outputs, encoder_hidden = encoder(input_seqs_batch, input_lens, None) # Create starting vectors for decoder decoder_input = Variable(torch.LongTensor([word2index[SOS_token]] * batch_size)) decoder_hidden = encoder_hidden[:decoder.n_layers] + encoder_hidden[decoder.n_layers:] if USE_CUDA: decoder_input = decoder_input.cuda() # Run through decoder one time step at a time decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden, encoder_outputs) decoder_out_probs = torch.nn.functional.log_softmax(decoder_output, dim=1) log_probs, indices = decoder_out_probs.data.topk(BEAM_SIZE) prev_decoder_hiddens = [decoder_hidden] * BEAM_SIZE prev_backtrack_seqs = torch.zeros(batch_size, BEAM_SIZE, 1) for k in range(BEAM_SIZE): prev_backtrack_seqs[:, k, 0] = indices[:, k] all_EOS = False for t in range(1, max_out_len): beam_vocab_log_probs = None beam_vocab_idx = None decoder_hiddens = [None] * BEAM_SIZE for k in range(BEAM_SIZE): decoder_input = indices[:, k] decoder_output, decoder_hiddens[k] = decoder(decoder_input, prev_decoder_hiddens[k], encoder_outputs) decoder_out_log_probs = torch.nn.functional.log_softmax(decoder_output, dim=1) vocab_log_probs = Variable(torch.zeros(batch_size, decoder.output_size)) if USE_CUDA: vocab_log_probs = vocab_log_probs.cuda() # make sure EOS has no children all_EOS = True for b in range(batch_size): if word2index[EOS_token] in prev_backtrack_seqs[b, k, :t]: vocab_log_probs[b] = log_probs[b, k] else: all_EOS = False vocab_log_probs[b] = (log_probs[b, k] * pow(6, 0.7) / pow(t, 0.7) + decoder_out_log_probs[b]) / pow(t + 1, 0.7) / pow(6, 0.7) if all_EOS: break topv, topi = vocab_log_probs.data.topk(BEAM_SIZE) if k == 0: beam_vocab_log_probs = topv beam_vocab_idx = topi else: beam_vocab_log_probs = torch.cat((beam_vocab_log_probs, topv), dim=1) beam_vocab_idx = torch.cat((beam_vocab_idx, topi), dim=1) if all_EOS: break topv, topi = beam_vocab_log_probs.data.topk(BEAM_SIZE) log_probs = topv indices = Variable(torch.zeros(batch_size, BEAM_SIZE, dtype=torch.long)) prev_decoder_hiddens = Variable(torch.zeros(BEAM_SIZE, decoder_hiddens[0].shape[0], batch_size, decoder_hiddens[0].shape[2])) if USE_CUDA: indices = indices.cuda() prev_decoder_hiddens = prev_decoder_hiddens.cuda() backtrack_seqs = torch.zeros(batch_size, BEAM_SIZE, t + 1) for b in range(batch_size): indices[b] = torch.index_select(beam_vocab_idx[b], 0, topi[b]) backtrack_seqs[b, :, t] = indices[b] for k in range(BEAM_SIZE): prev_decoder_hiddens[k, :, b, :] = decoder_hiddens[topi[b][k] / BEAM_SIZE][:, b, :] backtrack_seqs[b, k, :t] = prev_backtrack_seqs[b, topi[b][k] / BEAM_SIZE, :t] prev_backtrack_seqs = backtrack_seqs decoded_seqs = [[None]*batch_size]*BEAM_SIZE decoded_lens = [[max_out_len]*batch_size]*BEAM_SIZE for b in range(batch_size): for k in range(BEAM_SIZE): decoded_seq = [] for t in range(backtrack_seqs.shape[2]): idx = int(backtrack_seqs[b, k, t]) if idx == word2index[EOS_token]: decoded_seq.append(idx) break else: decoded_seq.append(idx) decoded_lens[k][b] = len(decoded_seq) decoded_seq += [word2index[PAD_token]] * (max_out_len - len(decoded_seq)) decoded_seqs[k][b] = decoded_seq return decoded_seqs, decoded_lens def evaluate_beam(word2index, index2word, encoder, decoder, id_seqs, input_seqs, input_lens, output_seqs, output_lens, batch_size, max_out_len, out_fname): total_loss = 0. n_batches = len(input_seqs) / batch_size encoder.eval() decoder.eval() has_ids = True if out_fname: out_files = [None] * BEAM_SIZE out_ids_files = [None] * BEAM_SIZE for k in range(BEAM_SIZE): out_files[k] = open(out_fname+'.beam%d' % k, 'w') if id_seqs[0] is not None: out_ids_files[k] = open(out_fname+'.beam%d.ids' % k, 'w') else: has_ids = False for id_seqs_batch, input_seqs_batch, input_lens_batch, output_seqs_batch, output_lens_batch in \ iterate_minibatches(id_seqs, input_seqs, input_lens, output_seqs, output_lens, batch_size, shuffle=False): if USE_CUDA: input_seqs_batch = Variable(torch.LongTensor(np.array(input_seqs_batch)).cuda()).transpose(0, 1) output_seqs_batch = Variable(torch.LongTensor(np.array(output_seqs_batch)).cuda()).transpose(0, 1) else: input_seqs_batch = Variable(torch.LongTensor(np.array(input_seqs_batch))).transpose(0, 1) output_seqs_batch = Variable(torch.LongTensor(np.array(output_seqs_batch))).transpose(0, 1) # Run post words through encoder encoder_outputs, encoder_hidden = encoder(input_seqs_batch, input_lens_batch, None) # Create starting vectors for decoder decoder_input = Variable(torch.LongTensor([word2index[SOS_token]] * batch_size)) decoder_hidden = encoder_hidden[:decoder.n_layers] + encoder_hidden[decoder.n_layers:] all_decoder_outputs = Variable(torch.zeros(max_out_len, batch_size, decoder.output_size)) if USE_CUDA: decoder_input = decoder_input.cuda() all_decoder_outputs = all_decoder_outputs.cuda() # Run through decoder one time step at a time decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden, encoder_outputs) decoder_out_log_probs = torch.nn.functional.log_softmax(decoder_output, dim=1) log_probs, indices = decoder_out_log_probs.data.topk(BEAM_SIZE) prev_decoder_hiddens = [decoder_hidden]*BEAM_SIZE prev_backtrack_seqs = torch.zeros(batch_size, BEAM_SIZE, 1) for k in range(BEAM_SIZE): prev_backtrack_seqs[:, k, 0] = indices[:, k] backtrack_seqs = None for t in range(1, max_out_len): beam_vocab_log_probs = None beam_vocab_idx = None decoder_hiddens = [None]*BEAM_SIZE for k in range(BEAM_SIZE): decoder_input = indices[:, k] decoder_output, decoder_hiddens[k] = decoder(decoder_input, prev_decoder_hiddens[k], encoder_outputs) decoder_out_log_probs = torch.nn.functional.log_softmax(decoder_output, dim=1) vocab_log_probs = Variable(torch.zeros(batch_size, decoder.output_size)) if USE_CUDA: vocab_log_probs = vocab_log_probs.cuda() # make sure EOS has no children for b in range(batch_size): if word2index[EOS_token] in prev_backtrack_seqs[b, k, :t]: # vocab_log_probs[b] = log_probs[b, k] + decoder_out_log_probs[b][word2index[PAD_token]] vocab_log_probs[b] = log_probs[b, k] else: # vocab_log_probs[b] = log_probs[b, k] + decoder_out_log_probs[b] vocab_log_probs[b] = (log_probs[b, k]*t + decoder_out_log_probs[b])/(t+1) # vocab_log_probs[b] = (log_probs[b, k] * pow(5+t, 0.7) / pow(5+1, 0.7) + # decoder_out_log_probs[b]) * pow(5+1, 0.7) / pow(5+t+1, 0.7) topv, topi = vocab_log_probs.data.topk(decoder.output_size) if k == 0: beam_vocab_log_probs = topv beam_vocab_idx = topi else: beam_vocab_log_probs = torch.cat((beam_vocab_log_probs, topv), dim=1) beam_vocab_idx = torch.cat((beam_vocab_idx, topi), dim=1) topv, topi = beam_vocab_log_probs.data.topk(BEAM_SIZE) indices = Variable(torch.zeros(batch_size, BEAM_SIZE, dtype=torch.long)) prev_decoder_hiddens = Variable(torch.zeros(BEAM_SIZE, decoder_hiddens[0].shape[0], batch_size, decoder_hiddens[0].shape[2])) if USE_CUDA: indices = indices.cuda() prev_decoder_hiddens = prev_decoder_hiddens.cuda() backtrack_seqs = torch.zeros(batch_size, BEAM_SIZE, t+1) for b in range(batch_size): indices[b] = torch.index_select(beam_vocab_idx[b], 0, topi[b]) backtrack_seqs[b, :, t] = indices[b] for k in range(BEAM_SIZE): prev_decoder_hiddens[k, :, b, :] = decoder_hiddens[topi[b][k]/decoder.output_size][:, b, :] backtrack_seqs[b, k, :t] = prev_backtrack_seqs[b, topi[b][k]/decoder.output_size, :t] prev_backtrack_seqs = backtrack_seqs if backtrack_seqs is not None: for b in range(batch_size): for k in range(BEAM_SIZE): decoded_words = [] for t in range(backtrack_seqs.shape[2]): idx = int(backtrack_seqs[b, k, t]) if idx == word2index[EOS_token]: decoded_words.append(EOS_token) break else: decoded_words.append(index2word[idx]) if out_fname: out_files[k].write(' '.join(decoded_words)+'\n') if has_ids: out_ids_files[k].write(id_seqs_batch[b]+'\n') loss_fn = torch.nn.NLLLoss() # Loss calculation loss = masked_cross_entropy( all_decoder_outputs.transpose(0, 1).contiguous(), # -> batch x seq output_seqs_batch.transpose(0, 1).contiguous(), # -> batch x seq output_lens_batch, loss_fn, max_out_len ) total_loss += loss.item() if out_fname: for k in range(BEAM_SIZE): out_files[k].close() print('Loss: %.2f' % (total_loss/n_batches)) <file_sep>#!/bin/bash #SBATCH --job-name=create_crowdflower_HK_compare_allpairs #SBATCH --output=create_crowdflower_HK_compare_allpairs #SBATCH --qos=batch #SBATCH --mem=32g #SBATCH --time=4:00:00 SITENAME=Home_and_Kitchen CORPORA_DIR=/fs/clip-corpora/amazon_qa DATA_DIR=/fs/clip-scratch/raosudha/clarification_question_generation/joint_learning/$SITENAME CROWDFLOWER_DIR=/fs/clip-amr/clarification_question_generation_pytorch/evaluation/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/evaluation export PATH="/fs/clip-amr/anaconda2/bin:$PATH" python $SCRIPT_DIR/create_crowdflower_data_compare_ques_allpairs.py --qa_data_fname $CORPORA_DIR/qa_${SITENAME}.json.gz \ --metadata_fname $CORPORA_DIR/meta_${SITENAME}.json.gz \ --csv_file $CROWDFLOWER_DIR/crowdflower_compare_ques_allpairs.csv \ --train_asins $DATA_DIR/train_asin.txt \ --previous_csv_file $CROWDFLOWER_DIR/crowdflower_compare_ques_pilot.csv <file_sep>import argparse import gzip import nltk import pdb import sys, os import re from collections import defaultdict def parse(path): g = gzip.open(path, 'r') for l in g: yield eval(l) exception_chars = ['|', '/', '\\', '-', '(', ')', '!', ':', ';', '<', '>'] def preprocess(text): text = text.replace('|', ' ') text = text.replace('/', ' ') text = text.replace('\\', ' ') text = text.lower() #text = re.sub(r'\W+', ' ', text) ret_text = '' for sent in nltk.sent_tokenize(text): ret_text += ' '.join(nltk.word_tokenize(sent)) + ' ' return ret_text def main(args): products = {} for v in parse(args.metadata_fname): if 'description' not in v or 'title' not in v: continue asin = v['asin'] title = preprocess(v['title']) description = preprocess(v['description']) product = title + ' . ' + description products[asin] = product train_asin_file = open(args.train_asin_fname, 'r') train_ans_file = open(args.train_ans_fname, 'w') tune_asin_file = open(args.tune_asin_fname, 'w') tune_context_file = open(args.tune_context_fname, 'w') tune_ques_file = open(args.tune_ques_fname, 'w') tune_ans_file = open(args.tune_ans_fname, 'w') test_asin_file = open(args.test_asin_fname, 'r') test_ans_file = open(args.test_ans_fname, 'w') train_asins = [] test_asins = [] for line in train_asin_file.readlines(): train_asins.append(line.strip('\n')) for line in test_asin_file.readlines(): test_asins.append(line.strip('\n')) asins = [] contexts = {} questions = {} answers = {} for v in parse(args.qa_data_fname): asin = v['asin'] if asin not in products or 'answer' not in v: continue question = preprocess(v['question']) answer = preprocess(v['answer']) if not answer: continue asins.append(asin) contexts[asin] = products[asin] questions[asin] = question answers[asin] = answer for asin in train_asins: train_ans_file.write(answers[asin]+'\n') for asin in asins: if asin in train_asins or asin in test_asins: continue tune_asin_file.write(asin+'\n') tune_context_file.write(contexts[asin]+'\n') tune_ques_file.write(questions[asin]+'\n') tune_ans_file.write(answers[asin]+'\n') for asin in test_asins: test_ans_file.write(answers[asin]+'\n') train_asin_file.close() train_ans_file.close() tune_asin_file.close() tune_context_file.close() tune_ques_file.close() tune_ans_file.close() test_asin_file.close() test_ans_file.close() if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--qa_data_fname", type = str) argparser.add_argument("--metadata_fname", type = str) argparser.add_argument("--train_asin_fname", type = str) argparser.add_argument("--train_ans_fname", type = str) argparser.add_argument("--tune_asin_fname", type = str) argparser.add_argument("--tune_context_fname", type = str) argparser.add_argument("--tune_ques_fname", type = str) argparser.add_argument("--tune_ans_fname", type = str) argparser.add_argument("--test_asin_fname", type = str) argparser.add_argument("--test_ans_fname", type = str) args = argparser.parse_args() print args print "" main(args) <file_sep>#!/bin/bash DATA_DIR=/fs/clip-scratch/raosudha/clarification_question_generation/utility UBUNTU=askubuntu.com UNIX=unix.stackexchange.com SUPERUSER=superuser.com SCRIPTS_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/utility SITE_NAME=askubuntu_unix_superuser mkdir $DATA_DIR/$SITE_NAME python $SCRIPTS_DIR/combine_pickle.py $DATA_DIR/$UBUNTU/train_data.p \ $DATA_DIR/$UNIX/train_data.p \ $DATA_DIR/$SUPERUSER/train_data.p \ $DATA_DIR/$SITE_NAME/train_data.p python $SCRIPTS_DIR/combine_pickle.py $DATA_DIR/$UBUNTU/tune_data.p \ $DATA_DIR/$UNIX/tune_data.p \ $DATA_DIR/$SUPERUSER/tune_data.p \ $DATA_DIR/$SITE_NAME/tune_data.p python $SCRIPTS_DIR/combine_pickle.py $DATA_DIR/$UBUNTU/test_data.p \ $DATA_DIR/$UNIX/test_data.p \ $DATA_DIR/$SUPERUSER/test_data.p \ $DATA_DIR/$SITE_NAME/test_data.p <file_sep># Repository information This repository contains data and code for the paper below: <i><a href="https://www.aclweb.org/anthology/N19-1013"> Answer-based Adversarial Training for Generating Clarification Questions</a></i><br/> <NAME> (<EMAIL>) and <NAME> (<EMAIL>)<br/> Proceedings of NAACL-HLT 2019 # Downloading data * Download embeddings from https://go.umd.edu/clarification_questions_embeddings and save them into the repository folder * Download data from https://go.umd.edu/clarification_question_generation_dataset Unzip the two folders inside and copy them into the repository folder # Training models on StackExchange dataset * To train an MLE model, run src/run_main.sh * To train a Max-Utility model, follow these three steps: * run src/run_pretrain_ans.sh * run src/run_pretrain_util.sh * run src/run_RL_main.sh * To train a GAN-Utility model, follow these three steps (note, you can skip first two steps if you have already ran them for Max-Utility model): * run src/run_pretrain_ans.sh * run src/run_pretrain_util.sh * run src/run_GAN_main.sh # Training models on Amazon (Home & Kitchen) dataset * To train an MLE model, run src/run_main_HK.sh * To train a Max-Utility model, follow these three steps: * run src/run_pretrain_ans_HK.sh * run src/run_pretrain_util_HK.sh * run src/run_RL_main_HK.sh * To train a GAN-Utility model, follow these three steps (note, you can skip first two steps if you have already ran them for Max-Utility model): * run src/run_pretrain_ans_HK.sh * run src/run_pretrain_util_HK.sh * run src/run_GAN_main_HK.sh # Generating outputs using trained models * Run following scripts to generate outputs for models trained on StackExchange dataset: * For MLE model, run src/run_decode.sh * For Max-Utility model, run src/run_RL_decode.sh * For GAN-Utility model, run src/run_GAN_decode.sh * Run following scripts to generate outputs for models trained on Amazon dataset: * For MLE model, run src/run_decode_HK.sh * For Max-Utility model, run src/run_RL_decode_HK.sh * For GAN-Utility model, run src/run_GAN_decode_HK.sh # Evaluating generated outputs * For StackExchange dataset, reference for a subset of the test set was collected using human annotators. Hence we first create a version of the predictions file for which we have references by running following: src/evaluation/run_create_preds_for_refs.sh * For Amazon dataset, we have references for all instances in the test set. * We remove <UNK> tokens from the generated outputs by simply removing them from the predictions file. * For BLEU score, run src/evaluation/run_bleu.sh * For METEOR score, run src/evaluation/run_meteor.sh * For Diversity score, run src/evaluation/calculate_diversiy.sh <predictions_file> <file_sep>import torch import torch.nn as nn class EncoderRNN(nn.Module): def __init__(self, hidden_size, word_embeddings, n_layers=1, dropout=0.1): super(EncoderRNN, self).__init__() self.hidden_size = hidden_size self.n_layers = n_layers self.dropout = dropout self.embedding = nn.Embedding(len(word_embeddings), len(word_embeddings[0])) self.embedding.weight.data.copy_(torch.from_numpy(word_embeddings)) self.embedding.weight.requires_grad = False self.gru = nn.GRU(len(word_embeddings[0]), hidden_size, n_layers, dropout=self.dropout, bidirectional=True) def forward(self, input_seqs, input_lengths, hidden=None): # Note: we run this all at once (over multiple batches of multiple sequences) embedded = self.embedding(input_seqs) #packed = torch.nn.utils.rnn.pack_padded_sequence(embedded, input_lengths) #outputs, hidden = self.gru(packed, hidden) #outputs, output_lengths = torch.nn.utils.rnn.pad_packed_sequence(outputs) # unpack (back to padded) outputs, hidden = self.gru(embedded, hidden) outputs = outputs[:, :, :self.hidden_size] + outputs[:, : ,self.hidden_size:] # Sum bidirectional outputs return outputs, hidden <file_sep>#!/bin/bash #SBATCH --job-name=pqa_data_Home_and_Kitchen #SBATCH --output=pqa_data_Home_and_Kitchen #SBATCH --qos=batch #SBATCH --mem=36g #SBATCH --time=24:00:00 SITENAME=Home_and_Kitchen DATA_DIR=/fs/clip-corpora/amazon_qa CQ_DATA_DIR=/fs/clip-amr/clarification_question_generation_pytorch/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src export PATH="/fs/clip-amr/anaconda2/bin:$PATH" python $SCRIPT_DIR/create_amazon_pqa_data_from_asins.py --qa_data_fname $DATA_DIR/qa_${SITENAME}.json.gz \ --metadata_fname $DATA_DIR/meta_${SITENAME}.json.gz \ --train_asin_fname $CQ_DATA_DIR/train_asin.txt \ --train_ans_fname $CQ_DATA_DIR/train_ans.txt \ --tune_asin_fname $CQ_DATA_DIR/tune_asin.txt \ --tune_context_fname $CQ_DATA_DIR/tune_context.txt \ --tune_ques_fname $CQ_DATA_DIR/tune_ques.txt \ --tune_ans_fname $CQ_DATA_DIR/tune_ans.txt \ --test_asin_fname $CQ_DATA_DIR/test_asin.txt \ --test_ans_fname $CQ_DATA_DIR/test_ans.txt \ <file_sep>from constants import * from masked_cross_entropy import * import numpy as np import random import torch from torch.autograd import Variable def get_decoded_seqs(decoder_outputs, word2index, max_len, batch_size): decoded_seqs = [] decoded_lens = [] decoded_seq_masks = [] for b in range(batch_size): decoded_seq = [] decoded_seq_mask = [0]*max_len log_prob = 0. for t in range(max_len): topv, topi = decoder_outputs[t][b].data.topk(1) ni = topi[0].item() if ni == word2index[EOS_token]: decoded_seq.append(ni) break else: decoded_seq.append(ni) decoded_seq_mask[t] = 1 decoded_lens.append(len(decoded_seq)) decoded_seq += [word2index[PAD_token]]*int(max_len - len(decoded_seq)) decoded_seqs.append(decoded_seq) decoded_seq_masks.append(decoded_seq_mask) decoded_lens = np.array(decoded_lens) decoded_seqs = np.array(decoded_seqs) return decoded_seqs, decoded_lens, decoded_seq_masks def inference(input_batches, input_lens, target_batches, target_lens, \ encoder, decoder, word2index, max_len, batch_size): input_batches = Variable(torch.LongTensor(np.array(input_batches))).transpose(0, 1) target_batches = Variable(torch.LongTensor(np.array(target_batches))).transpose(0, 1) decoder_input = Variable(torch.LongTensor([word2index[SOS_token]] * batch_size)) decoder_outputs = Variable(torch.zeros(max_len, batch_size, decoder.output_size)) if USE_CUDA: input_batches = input_batches.cuda() target_batches = target_batches.cuda() decoder_input = decoder_input.cuda() decoder_outputs = decoder_outputs.cuda() # Run post words through encoder encoder_outputs, encoder_hidden = encoder(input_batches, input_lens, None) # Prepare input and output variables decoder_hidden = encoder_hidden[:decoder.n_layers] + encoder_hidden[decoder.n_layers:] # Run through decoder one time step at a time for t in range(max_len): decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden, encoder_outputs) decoder_outputs[t] = decoder_output # Without teacher forcing for b in range(batch_size): topv, topi = decoder_output[b].topk(1) decoder_input[b] = topi.squeeze().detach() decoded_seqs, decoded_lens, decoded_seq_masks = get_decoded_seqs(decoder_outputs, word2index, max_len, batch_size) # Loss calculation and backpropagation #loss = masked_cross_entropy( # decoder_outputs.transpose(0, 1).contiguous(), # -> batch x seq # target_batches.transpose(0, 1).contiguous(), # -> batch x seq # target_lens #) log_probs = calculate_log_probs( decoder_outputs.transpose(0, 1).contiguous(), # -> batch x seq decoded_seq_masks, ) return log_probs, decoded_seqs, decoded_lens <file_sep>import argparse import sys, os from collections import defaultdict import csv import math import pdb import gzip MAX_POST_LEN=200 MAX_QUES_LEN=40 #MIN_TFIDF=30 MIN_TFIDF=2 #MIN_QUES_TFIDF=3000 #MIN_QUES_TFIDF=1000 MIN_QUES_TF=200 MAX_QUES_TFIDF=10 #MAX_QUES_TFIDF=8.5 def write_to_file(ids, args, prods, quess, template_quess, sim_prod, sim_ques, split): suffix = '' if args.nocontext: suffix += '_nocontext' if args.simqs: suffix += '_simqs' if args.candqs: suffix += '_candqs' if args.template: suffix += '_template' if args.onlycontext: suffix += '_onlycontext' suffix += '.txt' if split == 'train': src_file = open(args.train_src_fname+suffix, 'w') tgt_file = open(args.train_tgt_fname+suffix, 'w') ids_file = open(args.train_tgt_fname+suffix+'.ids', 'w') elif split == 'tune': src_file = open(args.tune_src_fname+suffix, 'w') tgt_file = open(args.tune_tgt_fname+suffix, 'w') ids_file = open(args.tune_tgt_fname+suffix+'.ids', 'w') if split == 'test': src_file = open(args.test_src_fname+suffix, 'w') tgt_file = open(args.test_tgt_fname+suffix, 'w') ids_file = open(args.test_tgt_fname+suffix+'.ids', 'w') for prod_id in ids: if args.candqs: if len(sim_prod[prod_id]) < 4: print prod_id continue for j in range(len(quess[prod_id])): src_line = '' if not args.nocontext: src_line += prods[prod_id]+' <EOP> ' ques_id = prod_id+'_'+str(j+1) if args.simqs: if ques_id not in sim_ques or len(sim_ques[ques_id]) < 4: break ids_file.write(ques_id+'\n') for k in range(1, 4): if args.candqs: if args.template: src_line += template_quess[sim_prod[prod_id][k]][(j)%len(template_quess[sim_prod[prod_id][k]])] + ' <EOQ> ' else: src_line += quess[sim_prod[prod_id][k]][(j)%len(quess[sim_prod[prod_id][k]])] + ' <EOQ> ' if args.simqs: sim_prod_id, sim_q_no = sim_ques[ques_id][k].split('_') sim_q_no = int(sim_q_no)-1 if args.template: src_line += template_quess[sim_prod_id][sim_q_no] + ' <EOQ> ' else: src_line += quess[sim_prod_id][sim_q_no] + ' <EOQ> ' src_file.write(src_line+'\n') tgt_file.write(quess[prod_id][j]+'\n') src_file.close() tgt_file.close() ids_file.close() def parse(path): g = gzip.open(path, 'r') for l in g: yield eval(l) def get_brand_info(metadata_fname): brand_info = {} for v in parse(metadata_fname): if 'description' not in v or 'title' not in v: continue asin = v['asin'] if 'brand' not in v.keys(): brand_info[asin] = None else: brand_info[asin] = v['brand'] return brand_info def get_sim_prods(sim_prods_filename, brand_info): sim_prods_file = open(sim_prods_filename, 'r') sim_prods = {} for line in sim_prods_file.readlines(): parts = line.split() asin = parts[0] sim_prods[asin] = [] for prod_id in parts[2:]: if brand_info[prod_id] and (brand_info[prod_id] != brand_info[asin]): sim_prods[asin].append(prod_id) if len(sim_prods[asin]) == 0: sim_prods[asin] = parts[10:13] return sim_prods def get_sim_quess(sim_quess_filename, brand_info): sim_quess_file = open(sim_quess_filename, 'r') sim_quess = {} for line in sim_quess_file.readlines(): parts = line.split() asin = parts[0].split('_')[0] sim_prods = [p.split('_')[0] for p in parts[2:]] sim_quess_ids = parts[2:] sim_quess[parts[0]] = [] for i, prod_id in enumerate(sim_prods): if brand_info[prod_id] and (brand_info[prod_id] != brand_info[asin]): sim_quess[parts[0]].append(sim_quess_ids[i]) if len(sim_quess[parts[0]]) == 0: sim_quess[parts[0]] = parts[10:13] print 'No new lucene simqs %s' % parts[0] return sim_quess def trim_by_len(s, max_len): s = s.lower().strip() words = s.split() s = ' '.join(words[:max_len]) return s def trim_by_tfidf(prods, p_tf, p_idf): for prod_id in prods: prod = [] words = prods[prod_id].split() for w in words: tf = words.count(w) #if p_tf[w]*p_idf[w] >= MIN_TFIDF: if tf*p_idf[w] >= MIN_TFIDF: prod.append(w) if len(prod) >= MAX_POST_LEN: break prods[prod_id] = ' '.join(prod) return prods def has_number(string): for char in string: if char.isdigit(): return True return False def template_by_tfidf(quess, q_tf, q_idf): template_quess = {} for prod_id in quess: for ques in quess[prod_id]: template_ques = [] words = ques.split() #print words for w in words: tf = words.count(w) #if q_tf[w]*q_idf[w] >= MIN_QUES_TFIDF or w == '?': #if has_number(w) or tf*q_idf[w] > MAX_QUES_TFIDF: #if has_number(w) or q_idf[w] > MAX_QUES_TFIDF: if has_number(w) or q_tf[w] < MIN_QUES_TF: #print w template_ques.append('<BLANK>') else: template_ques.append(w) #pdb.set_trace() if prod_id not in template_quess: template_quess[prod_id] = [] template_quess[prod_id].append(' '.join(template_ques)) return template_quess def read_data(args): print("Reading lines...") prods = {} quess = {} p_tf = defaultdict(int) p_idf = defaultdict(int) N = 0 for fname in os.listdir(args.prod_dir): with open(os.path.join(args.prod_dir, fname), 'r') as f: asin = fname[:-4] prod = f.readline().strip('\n') for w in prod.split(): p_tf[w] += 1 for w in set(prod.split()): p_idf[w] += 1 prods[asin] = prod N += 1 for w in p_idf: p_idf[w] = math.log(N*1.0/p_idf[w]) prods = trim_by_tfidf(prods, p_tf, p_idf) if os.path.isfile(args.train_ids_file): train_ids = [train_id.strip('\n') for train_id in open(args.train_ids_file, 'r').readlines()] tune_ids = [tune_id.strip('\n') for tune_id in open(args.tune_ids_file, 'r').readlines()] test_ids = [test_id.strip('\n') for test_id in open(args.test_ids_file, 'r').readlines()] else: ids = prods.keys() N = len(ids) train_ids = ids[:int(N*0.8)] tune_ids = ids[int(N*0.8):int(N*0.9)] test_ids = ids[int(N*0.9):] with open(args.train_ids_file, 'w') as f: for train_id in train_ids: f.write(train_id+'\n') with open(args.tune_ids_file, 'w') as f: for tune_id in tune_ids: f.write(tune_id+'\n') with open(args.test_ids_file, 'w') as f: for test_id in test_ids: f.write(test_id+'\n') N = 0 q_tf = defaultdict(int) q_idf = defaultdict(int) quess_rand = defaultdict(list) for fname in os.listdir(args.ques_dir): with open(os.path.join(args.ques_dir, fname), 'r') as f: ques_id = fname[:-4] asin, q_no = ques_id.split('_') ques = f.readline().strip('\n') for w in ques.split(): q_tf[w] += 1 for w in set(ques.split()): q_idf[w] += 1 quess_rand[asin].append((ques, q_no)) N += 1 for asin in quess_rand: quess[asin] = [None]*len(quess_rand[asin]) for (ques, q_no) in quess_rand[asin]: q_no = int(q_no)-1 quess[asin][q_no] = ques for w in q_idf: q_idf[w] = math.log(N*1.0/q_idf[w]) brand_info = get_brand_info(args.metadata_fname) sim_prod = get_sim_prods(args.sim_prod_fname, brand_info) if args.simqs: sim_ques = get_sim_quess(args.sim_ques_fname, brand_info) else: sim_ques = None if args.template: template_quess = template_by_tfidf(quess, q_tf, q_idf) write_to_file(train_ids, args, prods, quess, template_quess, sim_prod, sim_ques, split='train') write_to_file(tune_ids, args, prods, quess, template_quess, sim_prod, sim_ques, split='tune') write_to_file(test_ids, args, prods, quess, template_quess, sim_prod, sim_ques, split='test') else: template_quess = None write_to_file(train_ids, args, prods, quess, template_quess, sim_prod, sim_ques, split='train') write_to_file(tune_ids, args, prods, quess, template_quess, sim_prod, sim_ques, split='tune') write_to_file(test_ids, args, prods, quess, template_quess, sim_prod, sim_ques, split='test') if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--prod_dir", type = str) argparser.add_argument("--ques_dir", type = str) argparser.add_argument("--metadata_fname", type = str) argparser.add_argument("--sim_prod_fname", type = str) argparser.add_argument("--sim_ques_fname", type = str) argparser.add_argument("--train_ids_file", type = str) argparser.add_argument("--train_src_fname", type = str) argparser.add_argument("--train_tgt_fname", type = str) argparser.add_argument("--tune_ids_file", type = str) argparser.add_argument("--tune_src_fname", type = str) argparser.add_argument("--tune_tgt_fname", type = str) argparser.add_argument("--test_ids_file", type = str) argparser.add_argument("--test_src_fname", type = str) argparser.add_argument("--test_tgt_fname", type = str) argparser.add_argument("--candqs", type = bool) argparser.add_argument("--simqs", type = bool) argparser.add_argument("--template", type = bool) argparser.add_argument("--nocontext", type = bool) argparser.add_argument("--onlycontext", type = bool) args = argparser.parse_args() print args print "" read_data(args) <file_sep>#!/bin/bash #SBATCH --job-name=create_amazon_multi_refs #SBATCH --output=create_amazon_multi_refs #SBATCH --qos=batch #SBATCH --mem=4g #SBATCH --time=4:00:00 SITENAME=Home_and_Kitchen DATA_DIR=/fs/clip-corpora/amazon_qa/$SITENAME SCRIPT_DIR=/fs/clip-amr/clarification_question_generation_pytorch/src/evaluation/ CQ_DATA_DIR=/fs/clip-amr/clarification_question_generation_pytorch/$SITENAME python $SCRIPT_DIR/create_amazon_multi_refs.py --ques_dir $DATA_DIR/ques_docs \ --test_ids_file $CQ_DATA_DIR/blind_test_pred_question.txt.GAN_selfcritic_pred_ans_3perid.epoch8.len_norm.beam0.ids \ --ref_prefix $CQ_DATA_DIR/test_ref \ --test_context_file $CQ_DATA_DIR/test_context.txt <file_sep>import random from constants import * from prepare_data import * from masked_cross_entropy import * from helper import * import torch import torch.nn as nn from torch.autograd import Variable def evaluate(word2index, index2word, encoder, decoder, test_data, max_output_length, BATCH_SIZE, out_file): ids_seqs, input_seqs, input_lens, output_seqs, output_lens = test_data total_loss = 0. n_batches = len(input_seqs) / BATCH_SIZE for ids_seqs_batch, input_seqs_batch, input_lens_batch, output_seqs_batch, output_lens_batch in \ iterate_minibatches(ids_seqs, input_seqs, input_lens, output_seqs, output_lens, BATCH_SIZE): if USE_CUDA: input_seqs_batch = Variable(torch.LongTensor(np.array(input_seqs_batch)).cuda()).transpose(0, 1) output_seqs_batch = Variable(torch.LongTensor(np.array(output_seqs_batch)).cuda()).transpose(0, 1) else: input_seqs_batch = Variable(torch.LongTensor(np.array(input_seqs_batch))).transpose(0, 1) output_seqs_batch = Variable(torch.LongTensor(np.array(output_seqs_batch))).transpose(0, 1) # Run post words through encoder encoder_outputs, encoder_hidden = encoder(input_seqs_batch, input_lens_batch, None) # Create starting vectors for decoder decoder_input = Variable(torch.LongTensor([word2index[SOS_token]] * BATCH_SIZE), volatile=True) decoder_hidden = encoder_hidden[:decoder.n_layers] + encoder_hidden[decoder.n_layers:] all_decoder_outputs = Variable(torch.zeros(max_output_length, BATCH_SIZE, decoder.output_size)) if USE_CUDA: decoder_input = decoder_input.cuda() all_decoder_outputs = all_decoder_outputs.cuda() # Run through decoder one time step at a time for t in range(max_output_length): decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden, encoder_outputs) all_decoder_outputs[t] = decoder_output # Choose top word from output topv, topi = decoder_output.data.topk(1) decoder_input = topi.squeeze(1) if out_file: for b in range(BATCH_SIZE): decoded_words = [] for t in range(max_output_length): topv, topi = all_decoder_outputs[t][b].data.topk(1) ni = topi[0].item() if ni == word2index[EOS_token]: decoded_words.append(EOS_token) break else: decoded_words.append(index2word[ni]) out_file.write(' '.join(decoded_words)+'\n') loss_fn = torch.nn.NLLLoss() # Loss calculation loss = masked_cross_entropy( all_decoder_outputs.transpose(0, 1).contiguous(), # -> batch x seq output_seqs_batch.transpose(0, 1).contiguous(), # -> batch x seq output_lens_batch, loss_fn, max_output_length ) total_loss += loss.item() return total_loss/n_batches
f28ca4517145646cc175b51195a82950488dd8ac
[ "Markdown", "Python", "Shell" ]
92
Shell
raosudha89/clarification_question_generation_pytorch
23ae8aa0160eee70565751f4b6de13563a19d6ed
7234637feb22da6980604f2e64886e44a5e59e8c
refs/heads/master
<file_sep>/* Debounces each key for user configurable press/release. Per key debouncing rather than whole-matrix debouncing. */ #include "matrix.h" #include "debounce_matrix.h" #include "timer.h" //How many checks to do. //The first check is instant, the 2nd check may be less than 1ms apart //All further checks are at least 1ms apart. #ifndef DEBOUNCE_PRESS #define DEBOUNCE_PRESS 3 #endif #ifndef DEBOUNCE_RELEASE #define DEBOUNCE_RELEASE 5 #endif #define CHECK_BIT(var,pos) ((var) & (1 <<(pos))) #define CHECK_BITMASK(var, mask) ((var) & (mask)) #define SET_BIT(var,pos) ((var) | (1 << (pos))) #define CLEAR_BIT(var,pos) ((var) & ~(1 << (pos))) #define SET_BITMASK(var, mask) ((var) | (mask)) #define CLEAR_BITMASK(var, mask) ((var) & ~(mask)) static matrix_row_t matrix_debouncing[MATRIX_ROWS]; static uint8_t current_time; typedef uint8_t debounce_t; //checks remaining static debounce_t debounce_data[MATRIX_ROWS*MATRIX_COLS]; #define IS_DEBOUNCING(var) (var) //(var != 0) void debounce_matrix_init(void) { for (uint8_t i = 0; i < MATRIX_ROWS; i++) { matrix_debouncing[i] = 0; } for (uint8_t i = 0; i < MATRIX_ROWS*MATRIX_COLS; i++) { debounce_data[i] = 0; } } //scans non-debounced keys as fast as possible. //scans debouncing keys only once per ms. void update_debounce_matrix(matrix_row_t* raw_values, matrix_row_t* output_matrix) { uint8_t new_time = (uint8_t)timer_read(); //update timer. bool timer_changed = new_time == current_time; current_time = new_time; debounce_t* data = debounce_data; matrix_row_t* local_data = matrix_debouncing; for (uint8_t row_num = 0; row_num < MATRIX_ROWS; row_num++) { matrix_row_t cols = *raw_values; matrix_row_t result = *output_matrix; matrix_row_t existing = *local_data; matrix_row_t bitmask = 1; //scans non-debounced keys as fast as possible. //scans debouncing keys only once per ms. for (uint8_t col_num = 0; col_num < MATRIX_COLS; col_num++) { bool new_col = CHECK_BITMASK(cols, bitmask); bool old_col = CHECK_BITMASK(existing, bitmask); if (IS_DEBOUNCING(*data)) { if (timer_changed) { //only check once per millisecond. if (new_col == old_col) { (*data)--; //decrement count. if (*data == 0) //compare to one so we don't have to decrement { if (new_col) { result = SET_BITMASK(result, bitmask); } else { result = CLEAR_BITMASK(result, bitmask); } } } else { //reset checks because value changed. *data = new_col ? DEBOUNCE_PRESS : DEBOUNCE_RELEASE; } } else if (new_col != old_col) { *data = new_col ? DEBOUNCE_PRESS : DEBOUNCE_RELEASE; } } else if (new_col != old_col) { //not debouncing. time to add a debouncer *data = new_col ? DEBOUNCE_PRESS : DEBOUNCE_RELEASE; } data++; bitmask <<= 1; } *local_data = cols; *output_matrix = result; raw_values++; output_matrix++; local_data++; } } <file_sep>#include <stdint.h> #include <stdbool.h> #include <avr/io.h> #include <util/delay.h> #include "print.h" #include "debug.h" #include "util.h" #include "matrix.h" #include "debounce_matrix.h" //#define BENCHMARK_MATRIX #ifdef BENCHMARK_MATRIX #include "timer.h" #endif /* matrix state(1:on, 0:off) */ static matrix_row_t matrix[MATRIX_ROWS]; static matrix_row_t raw_matrix[MATRIX_ROWS]; static matrix_row_t read_cols(void); static void init_cols(void); static void unselect_rows(void); static void select_row(uint8_t row); inline uint8_t matrix_rows(void) { return MATRIX_ROWS; } inline uint8_t matrix_cols(void) { return MATRIX_COLS; } void matrix_init(void) { // disable JTAG MCUCR |= (1 << JTD); MCUCR |= (1 << JTD); // initialize row and col unselect_rows(); init_cols(); // initialize matrix state: all keys off for (uint8_t i=0; i < MATRIX_ROWS; i++) { matrix[i] = 0; raw_matrix[i] = 0; } // initialize our debounce matrix debounce_matrix_init(); } #ifdef BENCHMARK_MATRIX static int scans = 0; static uint16_t last_print_out = 0; static int last_timer = 0; static void benchmark(void) { scans++; uint16_t timer = timer_read(); if (timer != last_timer && timer != last_timer + 1) { print ("MS:\n"); print_dec(timer); print ("->"); print_dec(last_timer); print("\n"); } last_timer = timer; if ((timer % 1000 == 0) && (timer != last_print_out)) { print("Benchmark:"); print("\n"); print_dec(timer); print("\n"); print_dec(scans); print("\n"); print("-------"); scans = 0; last_print_out = timer; } } #endif uint8_t matrix_scan(void) { for (uint8_t i = 0; i < MATRIX_ROWS; i++) { select_row(i); // must sleep for two nops before calling read_cols() // or get corrupted data asm volatile ("nop"); asm volatile ("nop"); matrix_row_t cols = read_cols(); raw_matrix[i] = cols; unselect_rows(); } //debounce our keys. feed in raw matrix, let it write to final matrix. update_debounce_matrix(raw_matrix, matrix); #ifdef BENCHMARK_MATRIX benchmark(); #endif return 1; } bool matrix_is_modified(void) { return true; } inline bool matrix_is_on(uint8_t row, uint8_t col) { return (matrix[row] & ((matrix_row_t)1<<col)); } inline matrix_row_t matrix_get_row(uint8_t row) { return matrix[row]; } void matrix_print(void) { print("\nr/c 0123456789ABCDEF\n"); for (uint8_t row = 0; row < MATRIX_ROWS; row++) { phex(row); print(": "); pbin_reverse16(matrix_get_row(row)); print("\n"); } } uint8_t matrix_key_count(void) { uint8_t count = 0; for (uint8_t i = 0; i < MATRIX_ROWS; i++) { count += bitpop16(matrix[i]); } return count; } static void init_cols(void) { DDRC &= ~(1 << 6); PORTC |= (1 << 6); DDRD &= ~(1 << 7); PORTD |= (1 << 7); DDRE &= ~(1 << 6); PORTE |= (1 << 6); DDRB &= ~(1 << 4 | 1 << 5 | 1 << 6 | 1 << 2 | 1 << 3 | 1 << 1); PORTB |= (1 << 4 | 1 << 5 | 1 << 6 | 1 << 2 | 1 << 3 | 1 << 1); DDRF &= ~(1 << 7 | 1 << 6 | 1 << 5 | 1 << 4); PORTF |= (1 << 7 | 1 << 6 | 1 << 5 | 1 << 4); } static matrix_row_t read_cols(void) { return (PINC & (1 << 6) ? 0 : (1UL << 0)) | (PIND & (1 << 7) ? 0 : (1UL << 1)) | (PINE & (1 << 6) ? 0 : (1UL << 2)) | (PINB & (1 << 4) ? 0 : (1UL << 3)) | (PINB & (1 << 5) ? 0 : (1UL << 4)) | (PINB & (1 << 6) ? 0 : (1UL << 5)) | (PINB & (1 << 2) ? 0 : (1UL << 6)) | (PINB & (1 << 3) ? 0 : (1UL << 7)) | (PINB & (1 << 1) ? 0 : (1UL << 8)) | (PINF & (1 << 7) ? 0 : (1UL << 9)) | (PINF & (1 << 6) ? 0 : (1UL << 10)) | (PINF & (1 << 5) ? 0 : (1UL << 11)) | (PINF & (1 << 4) ? 0 : (1UL << 12)); } static void unselect_rows(void) { DDRD &= ~0b00011111; PORTD &= ~0b00011111; } static void select_row(uint8_t row) { switch (row) { case 0: DDRD |= (1 << 3); PORTD &= ~(1 << 3); break; case 1: DDRD |= (1 << 2); PORTD &= ~(1 << 2); break; case 2: DDRD |= (1 << 1); PORTD &= ~(1 << 1); break; case 3: DDRD |= (1 << 0); PORTD &= ~(1 << 0); break; case 4: DDRD |= (1 << 4); PORTD &= ~(1 << 4); break; } };<file_sep>#ifndef CONFIG_H #define CONFIG_H /* USB Device descriptor parameter */ #define VENDOR_ID 0xFEED #define PRODUCT_ID 0x6060 #define DEVICE_VER 0x0002 #define MANUFACTURER XeaL #define PRODUCT XeaLouS Keyboard #define DESCRIPTION XeaLouS Keyboard /* key matrix size */ #define MATRIX_ROWS 5 #define MATRIX_COLS 13 //#define NO_ACTION_ONESHOT //#define NO_ACTION_TAPPING //#define NO_ACTION_MACRO //#define NO_TRACK_KEY_PRESS //Try this out for 2016 era layer+shift detection (faster). /* key combination for command */ #define IS_COMMAND() (keyboard_report->mods == (MOD_BIT(KC_LSHIFT) | MOD_BIT(KC_RSHIFT))) #endif<file_sep>/* TMK Algorithm for infinity and newer boards. */ #include "matrix.h" #include "debounce_matrix.h" #include <util/delay.h> #include "timer.h" #ifndef DEBOUNCE #define DEBOUNCE 5 #endif static bool debouncing = false; static uint16_t debouncing_time; static matrix_row_t matrix_debouncing[MATRIX_ROWS]; void debounce_matrix_init(void) { for (int i = 0; i < MATRIX_ROWS; i++) { matrix_debouncing[i] = 0; } } void update_debounce_matrix(matrix_row_t* raw_values, matrix_row_t* output_matrix) { uint16_t current_time = timer_read(); for (uint8_t i = 0; i < MATRIX_ROWS; i++) { matrix_row_t cols = raw_values[i]; if (matrix_debouncing[i] != cols) { matrix_debouncing[i] = cols; debouncing = true; debouncing_time = current_time; } } if (debouncing && timer_elapsed(debouncing_time) > DEBOUNCE) { for (int i = 0; i < MATRIX_ROWS; i++) { output_matrix[i] = matrix_debouncing[i]; } debouncing = false; } } <file_sep>#include "matrix.h" #include "debounce_matrix.h" #include "timer.h" //debounce times in milliseconds. Note that keys are sent on first state change, //so there is no EMI protection. Actual debounce time is between (value) and (value - 1), //due to timer resolution. Relies on all your switches actualy being good. //In testing, a few dud switches completely ruined the experience. #ifndef DEBOUNCE_PRESS #define DEBOUNCE_PRESS 5 #endif #ifndef DEBOUNCE_RELEASE #define DEBOUNCE_RELEASE 10 #endif #define BOUNCE_BIT (0b10000000) #define MAX_DEBOUNCE (0b01111111) #define DEBOUNCE_MODULO_MASK (0b01111111) #define IS_BOUNCING(button_data) (button_data) //just have to check for non-zero #define BOUNCE_EXPIRY(button_data) (button_data & DEBOUNCE_MODULO_MASK) #define CHECK_BIT(var,pos) ((var) & (1<<(pos))) #define CLEAR_BIT(var,pos) ((var) & ~(1 << (pos))) #define SET_BIT(var,pos) ((var) | (1 << (pos))) //first bit is whether we are bouncing, remaining 7 bits is modulo of when we are ready again typedef uint8_t debounce_button_t; static debounce_button_t matrix[MATRIX_ROWS * MATRIX_COLS]; static uint8_t current_time; void debounce_matrix_init(void) { for (uint8_t i = 0; i < MATRIX_ROWS * MATRIX_COLS; i++) { matrix[i] = 0; } } inline static void set_expiry(debounce_button_t* button, uint8_t timeFromNow) { *button = ((current_time + timeFromNow) % MAX_DEBOUNCE) ^ BOUNCE_BIT; } //We assume that this will be called at least once every millisecond! static void check_debounce_matrix(void) { debounce_button_t* button_data = matrix; for (uint8_t i = 0; i < MATRIX_ROWS * MATRIX_COLS; i++) { if (IS_BOUNCING(*button_data) && current_time == BOUNCE_EXPIRY(*button_data)) { *button_data = 0; } button_data++; } } static inline void handle_new_data(matrix_row_t* raw_values, matrix_row_t* output) { for (uint8_t row = 0; row < MATRIX_ROWS; row++) { matrix_row_t raw_row = *raw_values; matrix_row_t existing_row = *output; matrix_row_t result_row = existing_row; if (raw_row != existing_row) { //quick check for change. debounce_button_t* button_data = matrix + row * MATRIX_COLS; for (uint8_t col = 0; col < MATRIX_COLS; col++) { if (!IS_BOUNCING(*button_data)) { bool existing_value = CHECK_BIT(existing_row, col); bool new_value = CHECK_BIT(raw_row, col); if (existing_value != new_value) { //value changed, lets reflect that immediately if (new_value) { result_row = SET_BIT(result_row, col); //send press #if DEBOUNCE_PRESS != 0 set_expiry(button_data, DEBOUNCE_PRESS); #endif } else { result_row = CLEAR_BIT(result_row, col); //send release #if DEBOUNCE_RELEASE != 0 set_expiry(button_data, DEBOUNCE_RELEASE); #endif } } } button_data++; } *output = result_row; } raw_values++; output++; } } void update_debounce_matrix(matrix_row_t* raw_values, matrix_row_t* output_matrix) { current_time = timer_read() % MAX_DEBOUNCE; //update timer. check_debounce_matrix(); //first clear all times if appropriate handle_new_data(raw_values, output_matrix); //reads raw values, writing some of them to output_matrix } <file_sep>#include "time.h" #include "matrix.h" #ifdef __cplusplus extern "C" { #endif /* call this to initialize our matrix */ void debounce_matrix_init(void); /* call this every update loop. writes output to finalMatrix */ void update_debounce_matrix(matrix_row_t* raw_values, matrix_row_t* output_matrix); #ifdef __cplusplus } #endif<file_sep>/* Original TMK algorithm Scans entire matrix, only updating entire matrix if no changes occured in last 5ms */ #include "matrix.h" #include "debounce_matrix.h" #include <util/delay.h> #ifndef DEBOUNCE #define DEBOUNCE 5 #endif static uint8_t debouncing = DEBOUNCE; //debouncing timer in milliseconds. static matrix_row_t matrix_debouncing[MATRIX_ROWS]; void debounce_matrix_init(void) { for (int i = 0; i < MATRIX_ROWS; i++) { matrix_debouncing[i] = 0; } } void update_debounce_matrix(matrix_row_t* raw_values, matrix_row_t* output_matrix) { for (uint8_t i = 0; i < MATRIX_ROWS; i++) { matrix_row_t cols = raw_values[i]; if (matrix_debouncing[i] != cols) { matrix_debouncing[i] = cols; debouncing = DEBOUNCE; } } if (debouncing) { if (--debouncing) { _delay_ms(1); } else { for (uint8_t i = 0; i < MATRIX_ROWS; i++) { output_matrix[i] = matrix_debouncing[i]; } } } } <file_sep>/* Original TMK algorithm Has debounce timers per row. */ #include "matrix.h" #include "debounce_matrix.h" #include <util/delay.h> #include "timer.h" #ifndef DEBOUNCE #define DEBOUNCE 5 #endif static uint8_t debouncing[MATRIX_ROWS]; //debouncing timer in milliseconds. static matrix_row_t matrix_debouncing[MATRIX_ROWS]; static uint8_t last_tick = 0; void debounce_matrix_init(void) { for (int i = 0; i < MATRIX_ROWS; i++) { matrix_debouncing[i] = 0; debouncing[i] = DEBOUNCE; } } bool tick_changed(void) { uint8_t new_tick = timer_read() % 0xFF; //update timer. bool result = new_tick == last_tick; last_tick = new_tick; return result; } void update_debounce_matrix(matrix_row_t* raw_values, matrix_row_t* output_matrix) { bool new_tick = tick_changed(); for (uint8_t i = 0; i < MATRIX_ROWS; i++) { matrix_row_t cols = raw_values[i]; if (matrix_debouncing[i] != cols) { matrix_debouncing[i] = cols; debouncing[i] = DEBOUNCE; } if (debouncing[i]) { if (new_tick) { if (--debouncing[i]) { output_matrix[i] = matrix_debouncing[i]; } } } } } <file_sep>#include "matrix.h" #include "debounce_matrix.h" #include "timer.h" //debounces by checking last n scans (up to 8) //Note that this isn't millisecond based so timing will be based on speed of scanning //each bit is a history of the buttons status. e.g. 0b00000011 means its been down for 2 scans. // past <-- present typedef uint8_t debounce_button_t; static debounce_button_t matrix[MATRIX_ROWS * MATRIX_COLS]; #define CHECK_BIT(var,pos) ((var) & (1<<(pos))) #define DEBOUNCE_KEY_DOWN 5 //number of readings for before we accept that the key is actually down #define DEBOUNCE_KEY_UP 5 #define KEY_DOWN_MASK (0b11111111 >> (8 - DEBOUNCE_KEY_DOWN)) #define KEY_UP_MASK (0b11111111 >> (8 - DEBOUNCE_KEY_UP)) //first key_release after at least 7 cycles of keydown #define IS_KEY_DOWN(var) (((var) & KEY_DOWN_MASK) == KEY_DOWN_MASK) #define IS_KEY_UP(var) (((~(var)) & KEY_UP_MASK) == KEY_UP_MASK) void debounce_matrix_init(void) { for (uint8_t i = 0; i < MATRIX_ROWS * MATRIX_COLS; i++) { matrix[i] = 0; } } void update_debounce_matrix(matrix_row_t* raw_values, matrix_row_t* output_matrix) { debounce_button_t* button_history = matrix; for (uint8_t row = 0; row < MATRIX_ROWS; row++) { matrix_row_t raw_row = *raw_values; matrix_row_t result_row = *output_matrix; //grab original value for (uint8_t col = 0; col < MATRIX_COLS; col++) { bool raw_value = CHECK_BIT(raw_row, col); *button_history = (*button_history << 1) | raw_value; //shift everything along. if (IS_KEY_DOWN(*button_history)) { result_row |= 1 << col; } else if (IS_KEY_UP(*button_history)) { result_row &= ~(1 << col); } //else we don't modify button state, and it stays the same button_history++; } *output_matrix = result_row; //incrememnt to next row of raw/output matrices raw_values++; output_matrix++; } } <file_sep># Target file name (without extension). TARGET = firmware # Directory common source filess exist TMK_DIR = ../tmk_core # Directory keyboard dependent files exist TARGET_DIR = . # project specific files SRC = keymap_common.c matrix.c led.c #DEBOUNCE = debounce_xeal.c #DEBOUNCE = debounce_hasu.c #DEBOUNCE = debounce_soarer.c DEBOUNCE = debounce_hasu_plus.c #DEBOUNCE = debounce_hasu_row.c #DEBOUNCE = debounce_hasu_noblock.c SRC := keymap.c $(SRC) $(DEBOUNCE) CONFIG_H = config.h # MCU name MCU = atmega32u4 # Processor frequency. F_CPU = 16000000 # Target architecture (see library "Board Types" documentation). ARCH = AVR8 # Input clock frequency. F_USB = $(F_CPU) # Interrupt driven control endpoint task(+60) OPT_DEFS += -DINTERRUPT_CONTROL_ENDPOINT # Boot Section Size in *bytes* OPT_DEFS += -DBOOTLOADER_SIZE=4096 # Build Options BOOTMAGIC_ENABLE = yes # Virtual DIP switch configuration(+1000) MOUSEKEY_ENABLE = yes # Mouse keys(+4700) EXTRAKEY_ENABLE = yes # Audio control and System control(+450) CONSOLE_ENABLE = yes # Console for debug(+400) COMMAND_ENABLE = yes # Commands for debug and configuration NKRO_ENABLE = yes # USB Nkey Rollover # Search Path VPATH += $(TARGET_DIR) VPATH += $(TMK_DIR) include $(TMK_DIR)/protocol/lufa.mk include $(TMK_DIR)/common.mk include $(TMK_DIR)/rules.mk
8fcdf1ac7708adc41e42061aae08d55d7fed5fa0
[ "C", "Makefile" ]
10
C
alex-ong/HandWired60
df6d01ec303f3aba31270ef17d947cb2a48c3bc6
236f38673f4441891a5cef0ed910d056854a9aa0
refs/heads/master
<file_sep>// // ViewController.swift // ChuckNorris // // Created by <NAME> on 04/05/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class MainViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var firstNameTextfield: UITextField! @IBOutlet weak var lastNameTextfield: UITextField! @IBOutlet weak var goButton: UIButton! @IBOutlet weak var topOffset: NSLayoutConstraint! @IBOutlet weak var popupView: UIView! let apiEndpoint = "https://api.icndb.com/jokes/random/10?escape=javascript" var dataSource: [JokeModel] = [] override func viewDidLoad() { super.viewDidLoad() title = "Be the next Chuck Norris" setupUI() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) inputUserData() } private func setupUI() { goButton.layer.masksToBounds = true goButton.layer.cornerRadius = 25.0 popupView.layer.masksToBounds = true popupView.layer.cornerRadius = 10.0 popupView.layer.borderColor = UIColor.cnj_darkBrownColor.cgColor popupView.layer.borderWidth = 1.0 popupView.backgroundColor = UIColor.white.withAlphaComponent(0.2) } @IBAction func refresh() { guard var firstName = firstNameTextfield.text, firstName.isEmpty == false, var lastName = lastNameTextfield.text, lastName.isEmpty == false else { return } // trim trailling spaces firstName = firstName.trailingTrim(.whitespaces) lastName = lastName.trailingTrim(.whitespaces) var urlString = apiEndpoint + "&firstName=" + firstName + "&lastName=" + lastName // just in case we have some spaces in names urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! let url = URL(string: urlString) WebService().load(resource: WebService.parseResponse(withURL: url!)) { [unowned self] result in switch result { case .success(let jokes): self.dataSource = jokes case .failure(let fail): self.dataSource = [] print(fail) } self.tableView.reloadData() } } @IBAction func getJokesPressed() { guard let firstName = firstNameTextfield.text, firstName.isEmpty == false, let lastName = lastNameTextfield.text, lastName.isEmpty == false else { return } dataSource = [] tableView.reloadData() tableView.isHidden = false view.endEditing(true) topOffset.constant = -popupView.frame.size.height UIView.animate(withDuration: 0.2, animations: { self.view.layoutIfNeeded() }) refresh() } @IBAction func inputUserData() { guard topOffset.constant < 0 else { return } tableView.isHidden = true firstNameTextfield.text = nil lastNameTextfield.text = nil topOffset.constant = 170.0 UIView.animate(withDuration: 0.2, animations: { self.view.layoutIfNeeded() }) } } extension MainViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "JokeCell") as! JokeCell cell.joke = dataSource[indexPath.row] return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } } class JokeCell: UITableViewCell { @IBOutlet weak var jokeLabel: UILabel! @IBOutlet weak var likeButton: UIButton! var joke: JokeModel! { didSet { jokeLabel.text = joke.jokeText setupLikeButton() } } @IBAction func likeJokePressed() { joke.likedByUser = !joke.likedByUser setupLikeButton() } override func awakeFromNib() { prepareCell() } override func prepareForReuse() { prepareCell() super.prepareForReuse() } private func setupLikeButton() { if joke.likedByUser == true { likeButton.tintColor = UIColor.cnj_redColor } else { likeButton.tintColor = UIColor.cnj_darkBrownColor.withAlphaComponent(0.3) } } private func prepareCell() { jokeLabel.text = nil likeButton.tintColor = UIColor.cnj_darkBrownColor.withAlphaComponent(0.3) } } <file_sep>// // Webservice.swift // RandomUsers // // Created by <NAME> on 18/03/2018. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation public typealias JSONDictionary = [String : Any] final class WebService { func load<A>(resource: Resource<A>, completion: @escaping (Result<A>) -> ()) { URLSession.shared.dataTask(with: resource.url) { data, response, error in // Check for errors in responses. let result = self.checkForNetworkErrors(data, response, error) DispatchQueue.main.async { switch result { case .success(let data): completion(resource.parse(data)) case .failure(let error): completion(.failure(error)) } } }.resume() } } extension WebService { fileprivate func checkForNetworkErrors(_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Result<Data> { if let error = error { let nsError = error as NSError if nsError.domain == NSURLErrorDomain && (nsError.code == NSURLErrorNotConnectedToInternet || nsError.code == NSURLErrorTimedOut) { return .failure(.noInternetConnection) } else { return .failure(.returnedError(error)) } } if let response = response as? HTTPURLResponse, response.statusCode <= 200 && response.statusCode >= 299 { return .failure((.invalidStatusCode("Request returned status code other than 2xx \(response)"))) } guard let data = data else { return .failure(.dataReturnedNil) } return .success(data) } public static func parseResponse(withURL: URL) -> Resource<[JokeModel]> { let parse = Resource<[JokeModel]>(url: withURL, parseJSON: { jsonData in guard let json = jsonData as? JSONDictionary else { return .failure(.errorParsingJSON) } let jokesJson = json["value"] as! Array<Any> let jokes: [JokeModel] = JokeModel.objectsfrom(jsonArray: jokesJson) return .success(jokes) }) return parse } } struct Resource<A> { let url: URL let parse: (Data) -> Result<A> } extension Resource { init(url: URL, parseJSON: @escaping (Any) -> Result<A>) { self.url = url self.parse = { data in do { let jsonData = try JSONSerialization.jsonObject(with: data, options: []) return parseJSON(jsonData) } catch { fatalError("Error parsing data") } } } } enum Result<T> { case success(T) case failure(NetworkingErrors) } enum NetworkingErrors: Error { case errorParsingJSON case noInternetConnection case dataReturnedNil case returnedError(Error) case invalidStatusCode(String) case customError(String) } <file_sep>// // String+CNJ.swift // ChuckNorrisJokes // // Created by <NAME> on 05/05/2018. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation extension String { func trailingTrim(_ characterSet : CharacterSet) -> String { if let range = rangeOfCharacter(from: characterSet, options: [.anchored, .backwards]) { return String(self[..<range.lowerBound]).trailingTrim(characterSet) } return self } } <file_sep>// // DataModel.swift // ChuckNorris // // Created by <NAME> on 04/05/2018. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation class JokeModel: FAAutoCode { var jokeId: Int = 0 var jokeText: String = "" var likedByUser: Bool = false override func setValue(_ value: Any?, forKey key: String) { if let _value = value { if key == "id" { jokeId = _value as! Int } else if key == "joke" { jokeText = _value as! String } else if key == "likedByUser" { likedByUser = _value as! Bool } } } } <file_sep>// // UIColor+WeType.swift // WeType // // Created by <NAME> on 28/04/2018. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit extension UIColor { class var cnj_lightBrownColor: UIColor { return UIColor(red: 251.0/255.0, green: 218.0/255.0, blue: 185.0/255.0, alpha: 1.0) } class var cnj_darkBrownColor: UIColor { return UIColor(red: 144.0/255.0, green: 66.0/255.0, blue: 61.0/255.0, alpha: 1.0) } class var cnj_redColor: UIColor { return UIColor(red: 208.0/255.0, green: 2.0/255.0, blue: 27.0/255.0, alpha: 1.0) } }
f14939a3450599551ff3d9398246bf34f9f87449
[ "Swift" ]
5
Swift
MagdaSzlagor/ChuckNorrisJokes
e1fea2a8e1d284409080d579127659abcc912ed1
d90260921399824320d9b1a4a45f26fb20687722
refs/heads/master
<file_sep># Color-Quantizer Original ![Original](/ankara.jpg) MyKMeans ![Quantized](/Quantized.jpg) <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import scipy.ndimage as im import scipy.misc as sm import numpy as np import PIL from MyKMeans import MyKMeans class ColorQuantizer: """Quantizer for color reduction in images. Use MyKMeans class that you implemented. Parameters ---------- n_colors : int, optional, default: 64 The number of colors that wanted to exist at the end. random_state : int, RandomState instance or None, optional, default: None If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Read more from: http://scikit-learn.org/stable/auto_examples/cluster/plot_color_quantization.html """ def __init__(self, n_colors=64, random_state=None): self.image = None self.centers = None np.set_printoptions(threshold=np.nan) self.d1 = 0 self.d2 = 0 self.d3 = 0 def read_image(self, path): """Reads jpeg image from given path as numpy array. Stores it inside the class in the image variable. Parameters ---------- path : string, path of the jpeg file """ self.image = im.imread(path) self.d1 = self.image.shape[0] self.d2 = self.image.shape[1] self.d3 = self.image.shape[2] self.image = self.image.reshape((self.image.shape[0]*self.image.shape[1]),self.image.shape[2]) def recreate_image(self, path_to_save): """Recreates image from the trained MyKMeans model and saves it to the given path. Parameters ---------- path_to_save : string, path of the png image to save """ self.image = self.image.reshape(self.d1,self.d2,self.d3) sm.imsave(path_to_save, self.image) pass def export_cluster_centers(self, path): """Exports cluster centers of the MyKMeans to given path. Parameters ---------- path : string, path of the txt file """ np.savetxt(path,self.kmeans.cluster_centers) def quantize_image(self, path, weigths_path, path_to_save): """Quantizes the given image to the number of colors given in the constructor. Parameters ---------- path : string, path of the jpeg file weigths_path : string, path of txt file to export weights path_to_save : string, path of the output image file """ """man_centers = np.zeros((64,3)) for i in range(64): man_centers[i] = (255/64.0)*np.random.randint(64) print man_centers""" self.kmeans = MyKMeans(random_state=None,n_clusters=64,max_iter=600,init_method="random") self.read_image(path) self.centers = self.kmeans.initialize(self.image) #image_array_sample = shuffle(image_array, random_state=0)[:1000] temp_image = np.array(self.image) np.random.shuffle(temp_image) self.kmeans.fit(temp_image[:7500]) labels = self.kmeans.predict(self.image) result = [] cents = self.kmeans.cluster_centers for i in range(self.d1*self.d2): result.append(cents[labels[i]]) self.image = np.array(result) self.recreate_image(path_to_save) self.export_cluster_centers(weigths_path) if __name__ == "__main__": if __name__ == "__main__": t = ColorQuantizer() t.quantize_image("../Docs/ankara.jpg","./ankara_cluster_centers.txt","./deneme-ankaradenemerand64.jpg") <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import scipy.spatial.distance as sp import numpy as np class MyKNeighborsClassifier: """Classifier implementing the k-nearest neighbors vote similar to sklearn library but different. https://goo.gl/Cmji3U But still same. Parameters ---------- n_neighbors : int, optional (default = 5) Number of neighbors to use by default. method : string, optional (default = 'classical') method for voting. Possible values: - 'classical' : uniform weights. All points in each neighborhood are weighted equally. - 'weighted' : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. - 'validity' weights are calculated with distance and multiplied of validity for each voter. Note: implementing kd_tree is bonus. norm : {'l1', 'l2'}, optional (default = 'l2') Distance norm. 'l1' is manhattan distance. 'l2' is euclidean distance. Examples -------- """ def __init__(self, n_neighbors=5, method='classical', norm='l2'): self.n_neighbors = n_neighbors self.method = method self.norm = norm self.labels = [] self.distinct_labels = [] self.data = [] self.validity = [] def fit(self, X, y): """Fit the model using X as training data and y as target values Parameters ---------- X : array-like, shape (n_query, n_features), Training data. y : array-like, shape = [n_samples] Target values. """ self.data = X self.labels = y for i in range(len(self.labels)): if self.labels[i] not in self.distinct_labels: self.distinct_labels.append(self.labels[i]) if self.method == "validity": result = np.zeros(len(X)) for i in range(len(X)): val = np.zeros(len(self.distinct_labels)) if self.norm == "l1": distances = sp.cdist([X[i]],self.data,metric="cityblock") else: distances = sp.cdist([X[i]],self.data) nearest_neighs = np.argpartition(distances,self.n_neighbors) for j in range(self.n_neighbors+1): if nearest_neighs[0][j] != i: val[self.labels[nearest_neighs[0][j]]] += 1/distances[0][nearest_neighs[0][j]] val = val/sum(val) result[i] = val[self.labels[i]] self.validity = result def predict(self, X): """Predict the class labels for the provided data Parameters ---------- X : array-like, shape (n_query, n_features), Test samples. Returns ------- y : array of shape [n_samples] Class labels for each data sample. """ if len(self.labels) == 0: raise ValueError("You should fit first!") result = [] if self.method == "classical": for i in range(len(X)): if self.norm == "l1": distances = sp.cdist([X[i]],self.data,metric="cityblock") else: distances = sp.cdist([X[i]],self.data) nearest_neighs = np.argpartition(distances,self.n_neighbors) calculated_label = np.zeros(len(self.distinct_labels)) for j in range(self.n_neighbors): ind = self.labels[nearest_neighs[0][j]] calculated_label[ind] += 1 result.append(np.argmax(calculated_label)) elif self.method == "weighted": for i in range(len(X)): if self.norm == "l1": distances = sp.cdist([X[i]],self.data,metric="cityblock") else: distances = sp.cdist([X[i]],self.data) nearest_neighs = np.argpartition(distances,self.n_neighbors) calculated_label = np.zeros(len(self.distinct_labels)) for j in range(self.n_neighbors): ind = self.labels[nearest_neighs[0][j]] calculated_label[ind] += 1/(distances[0][nearest_neighs[0][j]]+1e-15) result.append(np.argmax(calculated_label)) elif self.method == "validity": for i in range(len(X)): if self.norm == "l1": distances = sp.cdist([X[i]],self.data,metric="cityblock") else: distances = sp.cdist([X[i]],self.data) nearest_neighs = np.argpartition(distances,self.n_neighbors) calculated_label = np.zeros(len(self.distinct_labels)) for j in range(self.n_neighbors): ind = self.labels[nearest_neighs[0][j]] calculated_label[ind] += (1/(distances[0][nearest_neighs[0][j]]+1e-15))*self.validity[nearest_neighs[0][j]] result.append(np.argmax(calculated_label)) return result def predict_proba(self, X, method=None): """Return probability estimates for the test data X. Parameters ---------- X : array-like, shape (n_query, n_features), Test samples. method : string, if None uses self.method. Returns ------- p : array of shape = [n_samples, n_classes] The class probabilities of the input samples. Classes are ordered by lexicographic order. """ result = [] if method == "classical": for i in range(len(X)): if self.norm == "l1": distances = sp.cdist([X[i]],self.data,metric="cityblock") else: distances = sp.cdist([X[i]],self.data) nearest_neighs = np.argpartition(distances,self.n_neighbors) calculated_label = np.zeros(len(self.distinct_labels)) for j in range(self.n_neighbors): ind = self.labels[nearest_neighs[0][j]] calculated_label[ind] += 1 result.append(calculated_label/sum(calculated_label)) elif method == "weighted": for i in range(len(X)): if self.norm == "l1": distances = sp.cdist([X[i]],self.data,metric="cityblock") else: distances = sp.cdist([X[i]],self.data) nearest_neighs = np.argpartition(distances,self.n_neighbors) calculated_label = np.zeros(len(self.distinct_labels)) for j in range(self.n_neighbors): ind = self.labels[nearest_neighs[0][j]] calculated_label[ind] += 1/(distances[0][nearest_neighs[0][j]]+1e-15) result.append(calculated_label/sum(calculated_label)) elif method == "validity": for i in range(len(X)): if self.norm == "l1": distances = sp.cdist([X[i]],self.data,metric="cityblock") else: distances = sp.cdist([X[i]],self.data) nearest_neighs = np.argpartition(distances,self.n_neighbors) calculated_label = np.zeros(len(self.distinct_labels)) for j in range(self.n_neighbors): ind = self.labels[nearest_neighs[0][j]] calculated_label[ind] += (1/(distances[0][nearest_neighs[0][j]]+1e-15))*self.validity[nearest_neighs[0][j]] result.append(calculated_label/sum(calculated_label)) return result if __name__=='__main__': X = [[0], [1], [2], [3]] y = [0, 0, 1, 1] neigh = MyKNeighborsClassifier(n_neighbors=3, method="validity") neigh.fit(X, y) #print neigh.predict(X) n = 0.9 print(neigh.predict_proba([[n]], method='classical')) # [[0.66666667 0.33333333]] print(neigh.predict_proba([[n]], method='weighted')) # [[0.92436975 0.07563025]] print(neigh.predict_proba([[n]], method='validity')) # [[0.92682927 0.07317073]]<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import scipy.spatial.distance as sp import numpy as np EPSILON = 0.0001 class MyKMeans: """K-Means clustering similar to sklearn library but different. https://goo.gl/bnuM33 But still same. Parameters ---------- n_clusters : int, optional, default: 8 The number of clusters to form as well as the number of centroids to generate. init_method : string, optional, default: 'random' Initialization method. Values can be 'random', 'kmeans++' or 'manual'. If 'manual' then cluster_centers need to be set. max_iter : int, default: 300 Maximum number of iterations of the k-means algorithm for a single run. random_state : int, RandomState instance or None, optional, default: None If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. cluster_centers : np.array, used only if init_method is 'manual'. If init_method is 'manual' without fitting, these values can be used for prediction. """ def __init__(self, init_method="random", n_clusters=3, max_iter=300, random_state=None, cluster_centers=[]): self.init_method = init_method self.n_clusters = n_clusters self.max_iter = max_iter self.random_state = np.random.RandomState(random_state) self.labels = [] self.insert_count= [] for _ in range(n_clusters): self.insert_count.append(1) if init_method == "manual": self.cluster_centers = cluster_centers else: self.cluster_centers = [] def fit(self, X): """Compute k-means clustering. Parameters ---------- X : array-like, shape=(n_samples, n_features) Training instances to cluster. Returns ---------- self : MyKMeans """ for it in range(self.max_iter): """print "iteration: ", it print "centers: ", self.cluster_centers""" self.labels = [] inputs = [0 for i in range(len(self.cluster_centers))] res = np.zeros((len(self.cluster_centers),X.shape[1]),dtype = float) #res = self.cluster_centers """for i in range(X.shape[0]): min_index = 0 min_value = np.linalg.norm(self.cluster_centers[0]-X[i]) for j in range(len(self.cluster_centers)): temp = np.linalg.norm(self.cluster_centers[j]-X[i]) if temp < min_value: min_index = j self.labels.append(min_index)""" for i in range(X.shape[0]): distances = sp.cdist([X[i]],self.cluster_centers) self.labels.append(np.argmin(distances)) for k in range(len(self.labels)): res[self.labels[k]] += X[k] inputs[self.labels[k]] += 1 inputs = np.array(inputs) inputs[np.isnan(inputs)]=1 inputs[inputs == 0] = 1 res = res/inputs[:,None] """if np.array_equal(self.cluster_centers,res): break;""" if np.sqrt(np.sum((self.cluster_centers-res)**2)) < EPSILON: self.cluster_centers = np.array(res) break; self.cluster_centers = np.array(res) #self.cluster_centers = np.array(np.rint(res)) return self def initialize(self, X): """ Initialize centroids according to self.init_method Parameters ---------- X : array-like, shape=(n_samples, n_features) Training instances to cluster. Returns ---------- self.cluster_centers : array-like, shape=(n_clusters, n_features) """ if self.init_method == "random": temp = self.random_state.permutation(X.shape[0])[:self.n_clusters] for i in range(len(temp)): self.cluster_centers.append(X[temp[i]]) #print X[temp[i]],"deneme" elif self.init_method == "kmeans++": temp = self.random_state.randint(len(X)) self.cluster_centers.append(X[temp].tolist()) for i in range(1,self.n_clusters): distances = np.sum(sp.cdist(self.cluster_centers,X),axis=0) length = distances.shape[0] dist = np.argsort(distances)[length-65:length] dist = dist[::-1] for j in range(64): index = dist[j] if X[index].tolist() not in self.cluster_centers: break #index = np.argmax(distances) self.cluster_centers.append(X[index].tolist()) print "###############centers#####################" print self.init_method print self.cluster_centers print "###############centers#####################" return self.cluster_centers def predict(self, X): """Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters ---------- X : array-like, shape = [n_samples, n_features] New data to predict. Returns ------- labels : array, shape [n_samples,] Index of the cluster each sample belongs to. """ result = [] """for i in range(len(X)): min_i = 0 min_value = np.linalg.norm(self.cluster_centers[0]-X[i]) for j in range(len(self.cluster_centers)): temp = np.linalg.norm(self.cluster_centers[j]-X[i]) if temp < min_value: min_i = j result.append(min_i)""" for i in range(len(X)): distances = sp.cdist([X[i]],self.cluster_centers) result.append(np.argmin(distances)) res = np.array(result) return res def fit_predict(self, X): """Compute cluster centers and predict cluster index for each sample. Convenience method; equivalent to calling fit(X) followed by predict(X). Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] New data to transform. Returns ------- labels : array, shape [n_samples,] Index of the cluster each sample belongs to. """ res = self.fit(X) return res.predict(X) if __name__ == "__main__": if __name__ == "__main__": X = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]]) kmeans = MyKMeans(n_clusters=2, random_state=0, init_method='kmeans++') print kmeans.initialize(X) # [[4. 4.] # [1. 0.]] kmeans = MyKMeans(n_clusters=5, random_state=0, init_method = 'kmeans++') print kmeans.initialize(X) # [[4. 0.] # [1. 0.]] kmeans.fit(X) print kmeans.labels # array([1, 1, 1, 0, 0, 0]) print kmeans.predict([[0, 0], [4, 4]]) # array([1, 0]) print kmeans.cluster_centers # array([[4, 2], # [1, 2]])<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import copy import numpy as np class MyKMedoids: """KMedoids implementation parametric with 'pam' and 'clara' methods. Parameters ---------- n_clusters : int, optional, default: 3 The number of clusters to form as well as the number of medoids to determine. max_iter : int, default: 300 Maximum number of iterations of the k-medoids algorithm for a single run. method : string, default: 'pam' If it is pam, it applies pam algorithm to whole dataset 'pam'. If it is 'clara' it selects number of samples with sample_ratio and applies pam algorithm to the samples. Returns best medoids of all trials according to cost function. sample_ratio: float, default: .2 It is used if the method is 'clara' clara_trials: int, default: 10, It is used if the method is 'clara' random_state : int, RandomState instance or None, optional, default: None If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Examples """ def __init__(self, n_clusters=3, max_iter=300, method='clara', sample_ratio=.2, clara_trials=10, random_state=0): self.n_clusters = n_clusters self.max_iter = max_iter self.method = method self.sample_ratio = sample_ratio self.clara_trials = clara_trials self.random_state = np.random.RandomState(random_state) self.best_medoids = [] self.min_cost = float('inf') self.data = [] def fit(self, X): """Compute k-medoids clustering. If method is 'pam' Parameters ---------- X : array-like, shape=(n_samples, n_features) Training instances to cluster. Returns ---------- self : MyKMedoids """ self.data = X if self.method == "pam": (m, c) = self.pam(X) self.best_medoids = m self.min_cost = c elif self.method == "clara": min_c = float('Inf') best_med = [] for i in range(self.clara_trials): temp = self.sample() (m,c) = self.pam(temp) clusters = self.generate_clusters(m,X) #2 c = self.calculate_cost(m,clusters) if c < min_c: min_c = c best_med = m self.best_medoids = best_med self.min_cost = min_c return self def sample(self): """Samples from the data with given sample_ratio. Returns ------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] New data to transform. """ return self.random_state.permutation(self.data)[:int(len(self.data)*self.sample_ratio)] def pam(self, X): """ kMedoids - PAM See more : http://en.wikipedia.org/wiki/K-medoids The most common realisation of k-medoid clustering is the Partitioning Around Medoids (PAM) algorithm and is as follows:[2] 1. Initialize: randomly select k of the n data points as the medoids 2. Associate each data point to the closest medoid. ("closest" here is defined using any valid distance metric, most commonly Euclidean distance, Manhattan distance or Minkowski distance) 3. For each medoid m For each non-medoid data point o Swap m and o and compute the total cost of the configuration 4. Select the configuration with the lowest cost. 5. repeat steps 2 to 4 until there is no change in the medoid. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] New data to transform. Returns ------- best_medoids, min_cost : tuple, shape [n_samples,] Best medoids found and the cost according to it. """ temp = self.random_state.permutation(X)[:self.n_clusters] medoids = [temp[i].tolist() for i in range(len(temp))] result_medoids = medoids result_cost = float('Inf') temp_cost = float('Inf') prev_cost = result_cost clus = self.generate_clusters(medoids,X) for it in range(self.max_iter): for i in range(len(medoids)): for j in range(len(X)): if X[j].tolist() not in result_medoids: temp_medoids = copy.deepcopy(result_medoids) temp_medoids[i] = X[j].tolist() temp_cost = self.calculate_cost(temp_medoids,clus) if temp_cost < result_cost: result_cost = temp_cost result_medoids = temp_medoids if prev_cost == result_cost: break; prev_cost = result_cost #print "Sample best medoids: ", result_medoids #print "Sample min cost: ", result_cost return (result_medoids,result_cost) def generate_clusters(self, medoids, samples): """Generates clusters according to distance to medoids. Order is same with given medoids array. Parameters ---------- medoids: array_like, shape = [n_clusters, n_features] samples: array-like, shape = [n_samples, n_features] Returns ------- clusters : array-like, shape = [n_clusters, elemens_inside_cluster, n_features] """ clus = [[] for k in range(len(medoids))] for i in range(len(samples)): #val = distance.euclidean(samples[i],medoids[0]) val = np.sum((samples[i]-medoids[0])**2) #val = np.linalg.norm(samples[i]-medoids[0]) c = 0 for j in range(len(medoids)): #v = np.linalg.norm(samples[i]-medoids[j]) #v = distance.euclidean(samples[i],medoids[j]) v = np.sum((samples[i]-medoids[j])**2) if v < val: val = v c = j clus[c].append(samples[i]) return clus def calculate_cost(self, medoids, clusters): """Calculates cost of each medoid's cluster with squared euclidean function. Parameters ---------- medoids: array_like, shape = [n_clusters, n_features] clusters: array-like, shape = [n_clusters, elemens_inside_cluster, n_features] Returns ------- cost : float total cost of clusters """ result = 0; for i in range(len(medoids)): for j in range(len(clusters[i])): #result += distance.euclidean(medoids[i],clusters[i][j])**2 result += np.sum((medoids[i]-clusters[i][j])**2) #result += np.linalg.norm(medoids[i]-clusters[i][j])**2 return result def predict(self, X): """Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters ---------- X : array-like, shape = [n_samples, n_features] New data to predict. Returns ------- labels : array, shape [n_samples,] Index of the cluster each sample belongs to. """ result = [] for i in range(X.shape[0]): min_i = 0 #min_value = distance.euclidean(self.best_medoids[0],X[i]) min_value = np.sum((self.best_medoids[0]-X[i])**2) #min_value = np.linalg.norm(self.best_medoids[0]-X[i]) for j in range(1,len(self.best_medoids)): #temp = distance.euclidean(self.best_medoids[j],X[i]) temp = np.sum((self.best_medoids[j]-X[i])**2) #temp = np.linalg.norm(self.best_medoids[j]-X[i]) if temp < min_value: min_i = j min_value = temp result.append(min_i) res = np.array(result) return res def fit_predict(self, X): """Compute cluster centers and predict cluster index for each sample. Convenience method; equivalent to calling fit(X) followed by predict(X). Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] New data to transform. Returns ------- labels : array, shape [n_samples,] Index of the cluster each sample belongs to. """ res = self.fit(X) return res.predict(X) if __name__ == "__main__": X = np.array([np.array([2., 6.]), np.array([3., 4.]), np.array([3., 8.]), np.array([4., 7.]), np.array([6., 2.]), np.array([6., 4.]), np.array([7., 3.]), np.array([7., 4.]), np.array([8., 5.]), np.array([7., 6.]) ]) kmedoids = MyKMedoids(n_clusters=2, random_state=0,method="clara",sample_ratio=.5,clara_trials=10,max_iter=300) #print kmedoids.pam(X) print kmedoids.fit_predict(X) # [1 1 1 1 0 0 0 0 0 0] print kmedoids.best_medoids # [array([7., 4.]), array([2., 6.])] print kmedoids.min_cost # 28.0
4b22447f10579b3f81534d9645d6df1ea1fbd2eb
[ "Markdown", "Python" ]
5
Markdown
ozhans/Color-Quantizer
d89af5796afb19c064c65e1ad845fba8a0580519
461a187965d5dee1ad1c8e8cb66a2f98fca09db8
refs/heads/master
<file_sep># Filter data by id A command line tool to filter data from data file using id's from index file. ## Usage The tool reads two text files: - id file: id strings, one in each line -- the id (one word) must be the first word in the line; - data file: one record per line, perhaps *including* an id and whatever else there is. Empty lines from both files are ignored. After building (see below), launch the tool to find data from data files, matching the id's in the id file: `filter id-file data-file outputfile [filter]` Filter is optional; if not included id file is not filtered by the value it contains. Otherwise only those lines from the id file containing the filter word are included. Output file includes those records from the data-file, whose id is listed in the id-file, if not filtered out because of the filter word. Lauch the tool without parameters to see the usage instructions. Project contains sample files you can try out after building the binary (from the build directory): `./filter ../sample-id.txt ../sample-data.txt output.txt` Execution looks like this: ``` ./filter ../sample-id.txt ../sample-data.txt output.txt Reading id's into memory... Read 4 id's. Id's read. Reading data-file into memory... Read 6 entries. Finding matching id's from the data file... Found 3 entries of id's in the datafile. ``` And the contents of the output file are: ``` 1 1234 <NAME> Society for sober lecturers 2 2345 Zipped File Unpack me please 3 3456 Tina London C++ coders unite agains JavaScript ``` Another example, using a filter: ``` ./filter ../id-grade-2020.txt ../all-studs-2020.txt output.txt fail ``` Here, the id file contains the student id and grade, of which one may be "fail": ``` 1915774 fail 2728090 5 2836322 2 ``` Data file contains full student information, including student id, department, etc. Result file then includes information about all failed students: ``` 1915774 <NAME> Dept of Mathematics ``` Please note that data and id files are read into memory, so if you have very large files and little RAM, this might become an issue. ## Dependencies Uses C++ STL, C++17 and Boost 1.74. Build file is CMake so install [CMake](https://cmake.org) or build it manually / write your own makefile. ## Building With CMake, do in the project directory: 1. `mkdir build` 2. `cd build` 3. `cmake ..` (or `cmake -GNinja ..` if you use [Ninja](https://ninja-build.org), or `cmake -GXcode ..` to create a Xcode project, for example) 4. `make` (or `ninja`, if you created build files using `-GNinja`) Binary should be in the build directory. Then launch the tool as instructed above. If you have Doxygen installed and wish to generate documentation of the code, run ``` make doc ``` and you'll have HTML docs in the build/docs directory. ## Who made this (c) <NAME>, 2019-2020. All rights reserved. [INTERACT Research Unit](http://interact.oulu.fi), University of Oulu, Finland. ## License License is [MIT](https://opensource.org/licenses/MIT). <file_sep>cmake_minimum_required(VERSION 3.12) project(FilterDataById VERSION 1.0.0 LANGUAGES CXX) include(GNUInstallDirs) set(APP_NAME filter) find_package(Boost 1.74.0 REQUIRED) add_executable(${APP_NAME} main.cpp ) set_target_properties(${APP_NAME} PROPERTIES CXX_STANDARD 17) target_include_directories(${APP_NAME} PUBLIC ${Boost_INCLUDE_DIRS} ) find_package(Doxygen) if (DOXYGEN_FOUND) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/doxyconfig ${CMAKE_CURRENT_BINARY_DIR}/doxyfile @ONLY) add_custom_target(doc ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/doxyfile   WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} COMMENT "Generating API documentation with Doxygen" VERBATIM ) endif(DOXYGEN_FOUND) <file_sep> #include <iostream> #include <fstream> #include <string> #include <vector> #include <boost/algorithm/string.hpp> /** \file main.cpp */ /** \mainpage A command line tool to filter data from datafile using id's from index file. <p> Files must be text only. Index file must contain only the id's (one word; numbers, strings), and after space (or tab) other data if needed to use it for filtering by id file contents. Files are read into memory, so very large files might be a problem. @author <NAME> */ // Forward declaration of the helper function. [[nodiscard]] int readIdFile(const std::string & fileName, std::vector<std::string> & entries, const std::string & filter); int readDataFile(const std::string & fileName, std::vector<std::string> & entries); /** \fn int main(int argc, char ** argv) Main function of the tool. Lauch the tool without parameters to see usage information. @param argc Count of arguments. Expecting 4-5 (including the app binary name in the first slot). @param argv The parameters. */ int main(int argc, char ** argv) { std::string indexFileName; // Text file, contains the student id's one per line std::string dataFileName; // Text file, contains student data, one per line std::string outputFileName; // Text file to write the matching students. std::string filter; // Filter, if given in startup parameter. std::vector<std::string> indexes; // Student id's read from file. std::vector<std::string> dataEntries; // Student data read from file. if (argc < 3) { std::cout << "Usage: " << argv[0] << " id-file data-file outputfile [filter]" << std::endl; std::cout << " Where id-file contains id's of interest" << std::endl; std::cout << " data-file contains data in text format, one line per data item." << std::endl; std::cout << " output file will contain the results." << std::endl; std::cout << " filter (if given) includes only those records in id-file having said string." << std::endl; return EXIT_SUCCESS; } else { switch (argc) { case 5: filter = argv[4]; [[fallthrough]]; case 4: indexFileName = argv[1]; dataFileName = argv[2]; outputFileName = argv[3]; break; default: std::cout << "Launch without parameters to see usage instructions" << std::endl; return EXIT_SUCCESS; } } std::cout << "Reading id's into memory..." << std::endl; int count = readIdFile(indexFileName, indexes, filter); if (count > 0) { std::cout << "Read " << indexes.size() << " id's." << std::endl; } else { std::cout << "Error in opening the id file or file empty." << std::endl; return EXIT_FAILURE; } std::cout << "Id's read." << std::endl; std::cout << "Reading data-file into memory..." << std::endl; count = readDataFile(dataFileName, dataEntries); if (count > 0) { std::cout << "Read " << dataEntries.size() << " entries." << std::endl; } else { std::cout << "Error in opening the data file or file empty." << std::endl; return EXIT_FAILURE; } // Prepare output either to cout or file. std::ofstream outputFile; outputFile.open(outputFileName); if (outputFile.is_open()) { std::cout << "Output will be in file " << outputFileName << std::endl; } else { std::cout << "Error: could not open the output file" << std::endl; return EXIT_FAILURE; } std::cout << "Finding matching id's from the data file..." << std::endl; int matchCount = 0; std::for_each(std::begin(indexes), std::end(indexes), [&matchCount, &dataEntries, &outputFile](const std::string & index) { std::any_of(std::begin(dataEntries), std::end(dataEntries), [&matchCount, &index, &outputFile](const std::string & dataEntry) { if (dataEntry.find(index) != std::string::npos) { outputFile << matchCount + 1 << " " << dataEntry << std::endl; matchCount++; return true; // Not returning from the app but from the lambda function. } return false; // Not returning from the app but from the lambda function. }); }); std::cout << "Found " << matchCount << " entries of id's in the datafile." << std::endl; return EXIT_SUCCESS; } /** Helper function to extract the first word from the id file record. This is the id we are using to find matches from the data file. @param entry The data record @return The id from the record. */ std::string firstWord(const std::string & entry) { std::vector<std::string> strs; boost::split(strs, entry, boost::is_any_of("\t ")); if (strs.size() >= 1) { return strs.at(0); } return entry; } /** \fn int readIdFile(const std::string & fileName, std::vector<std::string> & entries, const std::string & filter) Reads lines from a text file and puts the first word of the line as a string in a vector. If filter is used, only records where the rest of the string contains the filter string are included in the entries. @param fileName The file to read lines from. @param entries The vector to put lines to. @param filter A value to filter the records to include in the process that satisfy the filter. @return The count of lines read, -1 if failed to open or read the file. */ int readIdFile(const std::string & fileName, std::vector<std::string> & entries, const std::string & filter) { int count = 0; std::ifstream file(fileName); if (file.is_open()) { std::string entry; while (std::getline(file, entry)) { if (entry.length() > 0) { // Are we using a filter to include only records with certain values if (filter.length() > 0) { // Ignore the first word (id) of the entry, and look for the // remainder of the record if it contains the filter word. auto pos = entry.find_first_of(" \t"); if (pos >= 0) { const std::string & substring = entry.substr(pos); if (substring.find(filter) != std::string::npos) { // Filter found in record, add to entries entries.push_back(firstWord(entry)); } } } else { // no filter used, put to entries entries.push_back(firstWord(entry)); } count++; } } file.close(); } else { std::cout << "Error in opening the file." << std::endl; return -1; } return count; } /** \fn int readDataFile(const std::string & fileName, std::vector<std::string> & entries) Reads lines from a text file and puts the the line as a string in a vector. @param fileName The file to read lines from. @param entries The vector to put lines to. @return The count of lines read, -1 if failed to open or read the file. @todo Could already do the matching and saving to output file already here for each datafile record. Would save memory. */ int readDataFile(const std::string & fileName, std::vector<std::string> & entries) { int count = 0; std::ifstream file(fileName); if (file.is_open()) { std::string entry; while (std::getline(file, entry)) { if (entry.length() > 0) { entries.push_back(entry); count++; } } file.close(); } else { std::cout << "Error in opening the file." << std::endl; return -1; } return count; }
538ac720bf96348f857dd1a0288899f978c9e469
[ "Markdown", "CMake", "C++" ]
3
Markdown
anttijuu/filter-by-id
dfb671e68cda590217b59a0d457931a446e0b34e
48c1bc67f120050f33a46ca2ab3986297508b376
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { NotificationService } from '../../../shared/notification/notification.service'; @Component({ selector: 'app-playlist', templateUrl: './playlist.component.html', styleUrls: ['./playlist.component.scss'] }) export class PlaylistComponent implements OnInit { items = [1, 2, 3, 4, 5]; sortablejsOptions = { // handle: '.drag-handle', // draggable: '.collection-item', animation: 150 }; constructor(private notification: NotificationService) { } ngOnInit() { } savePlaylist() { this.notification.message('Playlist saved!'); } successPlaylist() { this.notification.success('Playlist saved!'); } infoPlaylist() { this.notification.info('Playlist saved!'); } warningPlaylist() { this.notification.warning('Playlist saved!'); } errorPlaylist() { this.notification.error('Playlist saved!'); } } <file_sep>import { Component, OnInit, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-article-details', templateUrl: './article-details.component.html', styleUrls: ['./article-details.component.scss'] }) export class ArticleDetailsComponent implements OnInit, AfterViewInit { constructor() { } ngOnInit() { } ngAfterViewInit() { $('ul.tabs').tabs(); } } <file_sep>import { NgModule } from '@angular/core'; import { SharedModule } from './../shared/shared.module'; import { RouterModule } from '@angular/router'; import { LectureListComponent } from './lecture-list/lecture-list.component'; import { LectureItemComponent } from './lecture-item/lecture-item.component'; import { LectureDetailsComponent } from './lecture-details/lecture-details.component'; @NgModule({ imports: [ SharedModule, RouterModule.forChild([ { path: 'lectures', component: LectureListComponent }, { path: 'lectures/:id', component: LectureDetailsComponent }, { path: 'about', component: LectureListComponent } ]) ], declarations: [ LectureListComponent, LectureItemComponent, LectureDetailsComponent ], exports: [ ] }) export class LectureModule { } <file_sep>import { Injectable } from '@angular/core'; @Injectable() export class NotificationService { private duration = 4000; constructor() { } message(message: string) { Materialize.toast(message, this.duration); } success(message: string) { Materialize.toast(message, this.duration, 'success'); } info(message: string) { Materialize.toast(message, this.duration, 'info'); } warning(message: string) { Materialize.toast(message, this.duration, 'warning'); } error(message: string) { Materialize.toast(message, this.duration, 'error'); } } <file_sep>// The file contents for the current environment will overwrite these during build. // The build system defaults to the dev environment which uses `environment.ts`, but if you do // `ng build --env=prod` then `environment.prod.ts` will be used instead. // The list of which env maps to which file can be found in `angular-cli.json`. export const environment = { production: false, envName: 'development', // papersApiUrl: 'assets/articles.json', papersApiUrl: 'http://dev.papers.fm/', apiArticles: 'wp-json/wp/v2/articles/', apiJournals: 'wp-json/wp/v2/journals/', itemsPerPage: 10, client: 'web' }; <file_sep>import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; @Injectable() export class LoadingService { constructor() {} start() { // NProgress.configure({ showSpinner: true, trickleSpeed: 100 }); NProgress.start(); } done() { NProgress.done(); } } <file_sep>import { NgModule } from '@angular/core'; import { SharedModule } from './../shared/shared.module'; import { RouterModule } from '@angular/router'; import { PlaylistsComponent } from './playlists/playlists/playlists.component'; import { PlaylistComponent } from './playlist/playlist/playlist.component'; @NgModule({ imports: [ SharedModule, RouterModule.forChild([ { path: '', component: PlaylistsComponent }, { path: ':id', component: PlaylistComponent } ]) ], declarations: [PlaylistsComponent, PlaylistComponent] }) export class PlaylistsModule { } <file_sep>import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'stringify' }) export class StringifyPipe implements PipeTransform { transform(value: any): string { let text = ''; // if string keep it as it is if (value) { if (typeof value === 'string') { text = value; } else // if array if (Array.isArray(value)) { // loop through its items value.forEach(item => { // if the array item is an object if (typeof(item) === 'object') { for (let property in item) { if (item.hasOwnProperty(property)) { // add the value to the string text += item[property]; // if the first node is empty if (text === '') { // don't add anything } else if (property === 'abstract_section') { text += ': '; } else { text += ' '; } } } } }); } text = this.removeHTMLTags(text); return text; } } private removeHTMLTags(code) { // replace escaped brackets with real ones, code = code.replace(/&(lt|gt);/g, function (strMatch, p1){ return (p1 === 'lt') ? '<' : '>'; }); // remove tags code = code.replace(/<\/?[^>]+(>|$)/g, ''); return code; } } <file_sep>import { NgModule } from '@angular/core'; import { SharedModule } from './../shared/shared.module'; import { RouterModule } from '@angular/router'; import { ArticleListComponent } from './article-list/article-list.component'; import { ArticleItemComponent } from './article-item/article-item.component'; import { ArticleDetailsComponent } from './article-details/article-details.component'; @NgModule({ imports: [ SharedModule, RouterModule.forChild([ { path: 'articles', component: ArticleListComponent }, { path: 'articles/:id', component: ArticleDetailsComponent } ]) ], declarations: [ ArticleListComponent, ArticleItemComponent, ArticleDetailsComponent ], exports: [ ] }) export class ArticleModule { } <file_sep>import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { Ng2PaginationModule } from 'ng2-pagination'; import { SortablejsModule } from 'angular-sortablejs'; import { TruncatePipe } from './truncate/truncate.pipe'; import { StringifyPipe } from './stringify/stringify.pipe'; import { PaginationComponent } from './pagination/pagination.component'; @NgModule({ imports: [ CommonModule, RouterModule, Ng2PaginationModule ], declarations: [ TruncatePipe, StringifyPipe, PaginationComponent ], exports: [ CommonModule, RouterModule, TruncatePipe, StringifyPipe, PaginationComponent, Ng2PaginationModule, SortablejsModule ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) export class SharedModule { } <file_sep>import { Component, OnInit, AfterViewInit, Input } from '@angular/core'; @Component({ selector: 'app-lecture-item', templateUrl: './lecture-item.component.html', styleUrls: ['./lecture-item.component.scss'] }) export class LectureItemComponent implements OnInit, AfterViewInit { @Input() item; constructor() { } ngOnInit() { } ngAfterViewInit() { $('.dropdown-button').dropdown({ inDuration: 300, outDuration: 225, constrain_width: false, // Does not change width of dropdown to that of the activator hover: true, // Activate on hover gutter: 0, // Spacing from edge belowOrigin: false, // Displays dropdown below the button alignment: 'left' // Displays dropdown with edge aligned to the left of button } ); } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule, ErrorHandler } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule, Router, PreloadAllModules } from '@angular/router'; import { AppComponent } from './app.component'; import { LayoutModule } from './layout/layout.module'; import { LectureModule } from './lectures/lecture.module'; import { LectureService } from './lectures/lecture.service'; import { ArticleModule } from './articles/article.module'; import { ArticleService } from './articles/article.service'; import { HomeComponent } from './home/home.component'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; import { LoadingService } from './shared/loading/loading.service'; import { NotificationService } from './shared/notification/notification.service'; import { LogService } from './shared/log/log.service'; @NgModule({ declarations: [ AppComponent, HomeComponent, PageNotFoundComponent ], imports: [ BrowserModule, FormsModule, HttpModule, LayoutModule, LectureModule, ArticleModule, RouterModule.forRoot([ { path: '', component: HomeComponent }, { path: 'bookmarks', loadChildren: './bookmarks/bookmarks.module#BookmarksModule' }, // lazy loaded { path: 'playlists', loadChildren: './playlists/playlists.module#PlaylistsModule' }, // lazy loaded // { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ], {preloadingStrategy: PreloadAllModules} ) ], providers: [ LectureService, ArticleService, LoadingService, NotificationService, LogService, { provide: ErrorHandler, useExisting: LogService } ], bootstrap: [AppComponent] }) export class AppModule { constructor(private router: Router) { router.events.subscribe((val) => { window.scrollTo(0, 0); }); } } <file_sep># Ng2Material Angular 2 app with material design using [materializecss](http://materializecss.com/). https://github.com/hatemhosny/ng2-material ## Development server Run `npm start` for a dev server. Navigate to [http://localhost:4200/](http://localhost:4200/). The app will automatically reload if you change any of the source files. ## API server Run `npm run api` for a fake REST API server. The server address is [http://localhost:3000/](http://localhost:3000/). ## Code scaffolding Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive/pipe/service/class`. ## Build Run `npm run build` to build the project. The build artifacts will be stored in the `dist/` directory. Run the `npm run build:stag` for a staging build. Run the `npm run build:prod` for a production build. ## Running unit tests Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). ## Running end-to-end tests Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). Before running the tests make sure you are serving the app via `ng serve`. ## Deploy - Run `npm run deploy:gh-pages` to deploy to Github Pages. - Run `npm run deploy:surge` to deploy to Surge. Navigate to [http://papersfm.surge.sh](http://papersfm.surge.sh). Configure the domain in the npm script `surge`. - Run `npm run deploy:dev` to deploy Git repo by FTP to server `dev` configured in `dploy.yaml`, using [DPLOY](https://github.com/lucasmotta/dploy) - Run `npm run deploy:stag` to deploy Git repo by FTP to server `stag` configured in `dploy.yaml`. - Run `npm run deploy:prod` to deploy Git repo by FTP to server `prod` configured in `dploy.yaml`. - Run `npm run share` to serve the app through localtunnel. Navigate to [http://papersfm.localtunnel.me](http://papersfm.localtunnel.me). Configure the domain in the npm script `localtunnel`. ## App Documentation Run `npm run docs` to build the app documentation using compodoc. Run `npm run docs:serve` to build the app documentation and serve it on [http://localhost:8080/](http://localhost:8080/). ## Further help This is an [Angular 2](https://github.com/angular/angular) project (version 2.3.1), and was generated with [angular-cli](https://github.com/angular/angular-cli) (version 1.0.0-beta.24). To get more help on the `angular-cli` use `ng --help` or go check out the [Angular-CLI README](https://github.com/angular/angular-cli/blob/master/README.md). <file_sep>import { Component, Input, Output, EventEmitter, OnInit, OnDestroy } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-pagination', templateUrl: './pagination.component.html', styleUrls: ['./pagination.component.scss'] }) export class PaginationComponent implements OnInit, OnDestroy { private subscription: Subscription; p; @Input() id: string; @Output() pageChanged = new EventEmitter<number>(); private currentPage: number = 1; // get QueryString('page') to allow deep linking get pageQuery(): number { let page = this.currentPage; // subscribe to router event this.subscription = this.activatedRoute.queryParams.subscribe( (param: any) => { if (!isNaN(param['page']) && Number(param['page']) > 0) { page = Number(param['page']); } } ); return page; } // update QueryString('page') to match currentPage set pageQuery(page: number) { if (isNaN(page) || page < 1) { page = 1; } this.currentPage = page; // get route without parameters let route = this.router.url.split('?')[0]; // TODO improve this if (page === 1) { this.router.navigate([route]); } else { this.router.navigate([route], {queryParams: {'page': page}}); // TODO allow other filters and sorting } } constructor(private activatedRoute: ActivatedRoute, private router: Router) { } ngOnInit() { this.currentPage = this.pageQuery; } ngOnDestroy() { // prevent memory leak by unsubscribing this.subscription.unsubscribe(); } } <file_sep>export const environment = { production: true, envName: 'production', papersApiUrl: 'http://dev.papers.fm/', apiArticles: 'wp-json/wp/v2/articles/', apiJournals: 'wp-json/wp/v2/journals/', itemsPerPage: 10, client: 'web' }; <file_sep>import { Injectable, ErrorHandler } from '@angular/core'; import { LoadingService } from './../../shared/loading/loading.service'; import { NotificationService } from '../../shared/notification/notification.service'; import { environment } from '../../../environments/environment'; declare let Raven: any; type LogLevel = 'error' | 'warning' | 'info'; @Injectable() export class LogService implements ErrorHandler { private defaultErrorMessage = 'An error has occured! An error report has been sent.'; constructor(private loadingService: LoadingService, private notification: NotificationService) { } /** * This method handles unhandeled exceptions caught by angular. * Exceptions thrown before angular loads should be caught by Raven.config().install() in index.html * For custom error handling use logError() */ handleError(error: any): void { try { this.log(error, true, true, 'error', this.defaultErrorMessage); } catch (err) { console.log(error); console.log(err); } } /** * This method should be used to handle exceptions */ logError(error: any, message = this.defaultErrorMessage): void { this.log(error, true, true, 'error', message); } /** * Log +/- notify warning */ logWarning(message: string, notify = false): void { this.log(null, false, notify, 'warning', message); } /** * Log +/- notify message */ logMessage(message: string, notify = false): void { this.log(null, false, notify, 'info', message); } /** * The actual implementation of logging, * in development environment, it logs to console * otherwise, it sends logs to server */ private log(error: any, stopLoading = false, notify = false, notificationType: LogLevel = 'info', message = ''): void { // stop progress loading if (stopLoading) { this.loadingService.done(); } // show notification message if (notify && message) { switch (notificationType) { case 'error': this.notification.error(message); break; case 'warning': this.notification.warning(message); break; default: // 'info' this.notification.info(message); } } // Raven additional data let options = { level: notificationType, tags: { client: environment.client }, extra: { message: message } }; if (environment.envName === 'development') { console.log(message); if (error) { console.log(error.stack); } } else { if (error) { Raven.captureException(error.originalError, options); } else { Raven.captureMessage(message, options); } } } } <file_sep>import { Component, OnInit, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-lecture-details', templateUrl: './lecture-details.component.html', styleUrls: ['./lecture-details.component.scss'] }) export class LectureDetailsComponent implements OnInit, AfterViewInit { constructor() { } ngOnInit() { } ngAfterViewInit() { $('ul.tabs').tabs(); } } <file_sep>import { ArticleModule } from './../article.module'; import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; import { LogService } from './../../shared/log/log.service'; import { LoadingService } from './../../shared/loading/loading.service'; import { PaginationComponent } from './../../shared/pagination/pagination.component'; import { ArticleService } from './../article.service'; import { IArticle } from '../article.model'; @Component({ templateUrl: './article-list.component.html', styleUrls: ['./article-list.component.scss'] }) export class ArticleListComponent implements OnInit, AfterViewInit { items: IArticle[]; errorMessage: string; currentPage: number = 1; itemsPerPage: number; totalItems: number; @ViewChild('pagination') pagination: PaginationComponent; constructor( private articleService: ArticleService, private loadingService: LoadingService, private logService: LogService ) { } ngOnInit(): void { this.itemsPerPage = this.articleService.getNumberOfArticlesPerPage(); } ngAfterViewInit(): void { this.loadArticles(this.pagination.pageQuery); } loadArticles(page: number) { this.loadingService.start(); this.articleService.getArticles(page).subscribe( articles => { this.items = articles; this.totalItems = this.articleService.getNumberOfTotalItems(); this.currentPage = page; this.loadingService.done(); this.errorMessage = null; this.pagination.pageQuery = page; window.scrollTo(0, 0); // TODO smooth scroll }, error => { this.logService.logError(error, 'Loading error! Network connection failed.'); } ); } } <file_sep>import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/catch'; import { IArticle } from './article.model'; import { environment } from '../../environments/environment'; @Injectable() export class ArticleService { private articles: IArticle[]; private url: string = environment.papersApiUrl + environment.apiArticles; private itemsPerPage: number = environment.itemsPerPage; private totalItems: number; private filters: string = 'filter[meta_key]=has_audio&filter[meta_value]=1'; private fields = { 'id': 'id', 'title': 'title.rendered', 'pmid': 'acf.pmid', 'date': 'acf.publication_date', 'year': 'acf.year', 'month': 'acf.month', 'authors': 'acf.authors', 'abstract': 'acf.abstract', 'journal': 'acf.journal', 'journalIssn': 'acf.journal_issn', 'publicationTypes': 'acf.publication_types', 'audioDuration': 'acf.audio_duration' }; // convert fields object to string and remove double quotes private formattedFields: string = '_query=[*].' + JSON.stringify(this.fields).replace(/"/g, ''); private client: string = 'client=' + environment.client; private fullUrl: string = this.url + '?' + this.filters + '&' + this.formattedFields + '&' + this.client; constructor(private http: Http) { } private requestArticles(url: string) { return this.http.get(url) .do((response: Response) => { this.totalItems = Number(response.headers.get('X-WP-Total')); }) .map((response: Response) => <IArticle[]>response.json()) .do(data => this.articles = data) .catch(this.handleError); } getArticles(page?: number, filters?: {}): Observable<IArticle[]> { let pageQuery = '&per_page=' + this.itemsPerPage; if (page) { pageQuery += '&page=' + String(page); } // this.formatFilters(filters); return this.requestArticles(this.fullUrl + pageQuery); } getArticlesInJournal(journalIssn: string): Observable<IArticle[]> { if (journalIssn) { let journalFilter: string = 'filter[meta_key]=journal_issn&filter[meta_value]=' + journalIssn; return this.requestArticles(this.fullUrl + '&' + journalFilter); } else { this.getArticles(); } } getArticle(id: number): Observable<IArticle> { return this.getArticles() .map((articles: IArticle[]) => articles.find(article => article.id === id)); } getNumberOfArticlesPerPage(): number { return this.itemsPerPage; } getNumberOfTotalItems(): number { return this.totalItems; } // TODO implement (convert filter object to querystring) /* private formatFilters(filters: {}): string { return ''; } */ // TODO log errors private handleError(error: Response) { console.log(error); return Observable.throw(error.json().error || 'server error'); } } <file_sep>import { Angular241Page } from './app.po'; describe('angular241 App', function() { let page: Angular241Page; beforeEach(() => { page = new Angular241Page(); }); it('should display message saying app works', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('app works!'); }); }); <file_sep>export interface ILecture { } <file_sep>import { Component, OnInit } from '@angular/core'; import { LectureService } from './../lecture.service'; @Component({ templateUrl: './lecture-list.component.html', styleUrls: ['./lecture-list.component.scss'] }) export class LectureListComponent implements OnInit { items; constructor(private _lectureService: LectureService) { } ngOnInit() { this.items = this._lectureService.getLectures(); } } <file_sep>export interface IArticle { id: number; title: string; pmid: string; date: string; year: string; month: string; abstract: {}[]; journal: string; journalIssn: string; publicationTypes: {}[]; audioDuration: string; }
03611a7c59aac8efbf2d9c5b58723114ecc90af1
[ "Markdown", "TypeScript" ]
23
TypeScript
hatemhosny/papers-ionic
ce0bdbe59925adf6b221520d8af4bbfcc2ce54d5
3b391a2249cddf30915aca3af32496106f49d198
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk { public interface ISafewalkAdminClient { CreateUserResponse CreateUser(String accessToken, String username, String password, String firstName, String lastName, String mobilePhone, String email, String parent) ; UpdateUserResponse UpdateUser(String accessToken, String username, String mobilePhone, String email); GetUserResponse GetUser(String accessToken, String username); DeleteUserResponse DeleteUser(String accessToken, String username); SetStaticPasswordResponse SetStaticPassword(String accessToken, String username, String password); AssociateTokenResponse AssociateToken(String accessToken, String username, DeviceType deviceType); AssociateTokenResponse AssociateToken(String accessToken, String username, DeviceType deviceType, Boolean? sendRegistrationCode, Boolean? sendDownloadLinks); GetTokenAssociationsResponse GetTokenAssociations(String accessToken, String username); DeleteTokenAssociation DeleteTokenAssociation(String accessToken, String username, DeviceType deviceType, String serialNumber); CreateRegistrationCode CreateRegistrationCode(String accessToken, String username); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk.helper { public class ConnectivityException : Exception { public ConnectivityException(Exception cause) : base(cause.Message, cause) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Net; using System.Web; using System.Security; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using Newtonsoft.Json; namespace safewalk.helper { public class ServerConnectivityHelper : IServerConnectivityHelper { private static readonly int DEFAULT_TIMEOUT = 5000; //30000; private readonly String host; private readonly long port; private readonly bool setBypassSSLCertificate; public ServerConnectivityHelper(String host, long port) { this.host = host; this.port = port; this.setBypassSSLCertificate = false; } public ServerConnectivityHelper(String host, long port, bool byPassSSLCertificate) { this.host = host; this.port = port; this.setBypassSSLCertificate = byPassSSLCertificate; } #region "Publics" public Response post(String path, Dictionary<string,string> parameters, Dictionary<string,string> headers) { return doRequest("POST", path, parameters, headers); } public Response put(String path, Dictionary<string,string> parameters, Dictionary<string,string> headers) { return doRequest("PUT", path, parameters, headers); } public Response get(String path, Dictionary<string,string> parameters, Dictionary<string,string> headers) { return doRequest("GET", path, parameters, headers); } public Response delete(String path, Dictionary<string,string> parameters, Dictionary<string,string> headers) { return doRequest("DELETE", path, parameters, headers); } #endregion #region "privates" private Response doRequest(String method, String path, Dictionary<string,string> parameters, Dictionary<string,string> headers) { try { string _path = this.host + ":" + this.port + path; HttpWebRequest request; if (this.setBypassSSLCertificate) { var certificate = new X509Certificate(); ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; request = (HttpWebRequest)WebRequest.Create(_path); request.ClientCertificates.Add(certificate); } else { request = (HttpWebRequest)WebRequest.Create(_path); } switch (method) { case "POST": request.Method = WebRequestMethods.Http.Post; break; case "GET": request.Method = WebRequestMethods.Http.Get; break; case "PUT": request.Method = WebRequestMethods.Http.Put; break; case "DELETE": request.Method = "DELETE"; break; } request.ContentType = "application/x-www-form-urlencoded"; request.Timeout = DEFAULT_TIMEOUT; request.ReadWriteTimeout = DEFAULT_TIMEOUT; request.Accept = "application/json, text/javascript, */*; q=0.01"; foreach (KeyValuePair<string, string> header in headers) { request.Headers.Add(header.Key, header.Value); } byte[] buffer = Encoding.UTF8.GetBytes(this.urlEncode(parameters)); if (request.Method == WebRequestMethods.Http.Put || request.Method == WebRequestMethods.Http.Post) { request.ContentLength = buffer.Length; //We open a stream for writing the postvars Stream PostData = request.GetRequestStream(); PostData.Write(buffer, 0, buffer.Length); PostData.Close(); } //Get the response handle, we have no true response yet! HttpWebResponse _response = (HttpWebResponse)request.GetResponse(); HttpStatusCode responseCode = this.getResponseCode(_response); Stream stream = _response.GetResponseStream(); StreamReader reader = new StreamReader(stream, Encoding.UTF8); String responseString = reader.ReadToEnd(); return new Response(responseString, (int)responseCode); } catch (IOException e) { throw new ConnectivityException(e); } catch (WebException webException) { // .NET will throw a System.Net.WexException on StatusCodes // other than 200. You can catch that exception and retain // the StatusCode for error handling. if (webException.Status == System.Net.WebExceptionStatus.ProtocolError) { // Protocol Error, you can read the response and handle // the error based on the StatusCode. var exceptionResponse = webException.Response as System.Net.HttpWebResponse; if (exceptionResponse != null) { var exceptionResponseValue = string.Empty; using (var exceptionResponseStream = exceptionResponse.GetResponseStream()) { if (exceptionResponseStream != null) { using (var exceptionReader = new System.IO.StreamReader( exceptionResponseStream)) { exceptionResponseValue = exceptionReader.ReadToEnd(); } } } // Enumerated Protocol Error. int statusCode = (int)exceptionResponse.StatusCode; string statusDescription = exceptionResponse.StatusDescription; string responseBody = exceptionResponseValue; return new Response(responseBody, statusCode); } } else if (webException.Status == System.Net.WebExceptionStatus.ConnectFailure) { var exceptionResponse = webException.Response as System.Net.HttpWebResponse; if (exceptionResponse != null) { var exceptionResponseValue = string.Empty; using (var exceptionResponseStream = exceptionResponse.GetResponseStream()) { if (exceptionResponseStream != null) { using (var exceptionReader = new System.IO.StreamReader( exceptionResponseStream)) { exceptionResponseValue = exceptionReader.ReadToEnd(); } } } // Enumerated Protocol Error. int statusCode = (int)exceptionResponse.StatusCode; string statusDescription = exceptionResponse.StatusDescription; string responseBody = exceptionResponseValue; return new Response(responseBody, statusCode); } else { return new Response("Unknown ConnectFailure Error", 404); } } throw new ConnectivityException(webException); } catch (Exception e) { throw new ConnectivityException(e); } } public static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; } private HttpStatusCode getResponseCode(HttpWebResponse response) { HttpStatusCode responseCode; try { responseCode = response.StatusCode; } catch (IOException e) { responseCode = HttpStatusCode.BadRequest; } return responseCode; } private String urlEncode(Dictionary<string,string> query) { StringBuilder builder = new StringBuilder(); foreach (KeyValuePair<string, string> entry in query) { builder.Append(entry.Key); builder.Append("="); builder.Append(HttpUtility.UrlEncode(entry.Value, Encoding.UTF8)); builder.Append("&"); } builder.ToString(); return builder.ToString(); } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk { public class GetTokenAssociationsResponse : BaseResponse { #region "vars" private List<TokenAssociation> associations; #endregion #region "constr" public GetTokenAssociationsResponse(int httpCode , List<TokenAssociation> associations) : base(httpCode) { this.associations = associations; } public GetTokenAssociationsResponse(int httpCode , Dictionary<String, List<String>> errors) : base(httpCode, errors) { } #endregion #region "publics" public override String ToString() { var sb = new StringBuilder(); sb.Append(this.httpCode.ToString()).Append(SEPARATOR); if (this.httpCode == 200) { if (this.associations != null) { if (this.associations.Count > 0) { sb.Append("["); foreach (var tokenAssociation in this.associations) { sb.Append("("); sb.Append(tokenAssociation); sb.Append("), "); } sb.Append("]"); } else { sb.Append("NO ASSOCIATIONS"); } } else { sb.Append("NO ASSOCIATIONS"); } } foreach (KeyValuePair<String, List<String>> error in this.errors) { sb.Append(error.Key).Append(" ["); foreach (String e in error.Value) { sb.Append(e).Append(", "); } sb.Append("]").Append(SEPARATOR); } return sb.ToString(); } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk { public enum UserStorage { LDAP, DB, } public class CreateUserResponse : BaseResponse { #region "vars" private readonly String dbMobilePhone; private readonly String dbEmail; private readonly String ldapMobilePhone; private readonly String ldapEmail; private readonly UserStorage? userStorage; private readonly String firstName; private readonly String lastName; private readonly String dn; private readonly String username; #endregion #region "constr" public CreateUserResponse(int httpCode , String username , String firstName , String lastName , String dn , String dbMobilePhone , String dbEmail , String ldapMobilePhone , String ldapEmail , UserStorage? userStorage) : base(httpCode) { this.dbMobilePhone = dbMobilePhone; this.dbEmail = dbEmail; this.ldapMobilePhone = ldapMobilePhone; this.ldapEmail = ldapEmail; if (userStorage != null) this.userStorage = userStorage.Value; this.firstName = firstName; this.lastName = lastName; this.dn = dn; this.username = username; this.httpCode = httpCode; } public CreateUserResponse(int httpCode , Dictionary<String, List<String>> errors) : base(httpCode, errors) { this.dbMobilePhone = null; this.dbEmail = null; this.ldapMobilePhone = null; this.ldapEmail = null; this.userStorage = null; this.firstName = null; this.lastName = null; this.dn = null; this.username = null; } #endregion #region "Publics" public override String ToString() { StringBuilder sb = new StringBuilder(); sb.Append(this.httpCode.ToString()).Append(SEPARATOR); if (this.httpCode == 201) { if (this.username != null) sb.Append(this.username).Append(SEPARATOR); if (this.firstName != null) sb.Append(this.firstName).Append(SEPARATOR); if (this.lastName != null) sb.Append(this.lastName).Append(SEPARATOR); if (this.userStorage != null) sb.Append(this.userStorage).Append(SEPARATOR); if (this.dn != null) sb.Append(this.dn).Append(SEPARATOR); if (this.dbEmail != null) sb.Append(this.dbEmail).Append(SEPARATOR); if (this.dbMobilePhone != null) sb.Append(this.dbMobilePhone).Append(SEPARATOR); if (this.ldapEmail != null) sb.Append(this.ldapEmail).Append(SEPARATOR); if (this.ldapMobilePhone != null) sb.Append(this.ldapMobilePhone).Append(SEPARATOR); } else { foreach (KeyValuePair<String, List<String>> error in this.errors) { sb.Append(error.Key).Append(" ["); foreach (String e in error.Value) { sb.Append(e).Append(", "); } sb.Append("]").Append(SEPARATOR); } } return sb.ToString(); } /** * @return the dbMobilePhone */ public String getDbMobilePhone() { return dbMobilePhone; } /** * @return the dbEmail */ public String getDbEmail() { return dbEmail; } /** * @return the ldapMobilePhone */ public String getLdapMobilePhone() { return ldapMobilePhone; } /** * @return the ldapEmail */ public String getLdapEmail() { return ldapEmail; } /** * @return the userStorage */ public UserStorage? getUserStorage() { return userStorage; } /** * @return the firstName */ public String getFirstName() { return firstName; } /** * @return the lastName */ public String getLastName() { return lastName; } /** * @return the dn */ public String getDn() { return dn; } /** * @return the username */ public String getUsername() { return username; } #endregion } } <file_sep>using System; namespace safewalk { /// <summary> /// Safewalk integration Client /// </summary> public interface ISafewalkAuthClient { /// <summary> /// Authenticates the user with the given credentials. /// /// The username will determine if the user is an internal user or an LDAP user. /// If the given username has the format of "username" the user will be created as an internal user(In the database). If it doesn't exist, it will look in the LDAP following the priority order /// If the given username has the format of "username@domain"; the user will be created in the LDAP with the given domain. /// </summary> /// <param name="username"></param> /// <param name="password">Static password or OTP</param> /// <returns></returns> AuthenticationResponse Authenticate(String username, String password); /// <summary> /// Authenticates the user with the given credentials. /// /// The username will determine if the user is an internal user or an LDAP user. /// If the given username has the format of "username" the user will be created as an internal user(In the database). If it doesn't exist, it will look in the LDAP following the priority order /// If the given username has the format of "username@domain"; the user will be created in the LDAP with the given domain. /// </summary> /// <param name="username"></param> /// <param name="password">Static password or OTP</param> /// <param name="transactionId"></param> /// <returns></returns> AuthenticationResponse Authenticate(String username, String password, String transactionId); /// <summary> /// Standard authentication for external users. /// /// The username will determine if the user is an internal user or an LDAP user. /// If the given username has the format of "username" the user will be created as an internal user(In the database). If it doesn't exist, it will look in the LDAP following the priority order /// If the given username has the format of "username@domain" the user will be created in the LDAP with the given domain. /// </summary> /// <param name="username"></param> /// <returns></returns> ExternalAuthenticationResponse AuthenticateExternal( String username); /// <summary> /// Standard authentication for external users. /// /// The username will determine if the user is an internal user or an LDAP user. /// If the given username has the format of "username" the user will be created as an internal user(In the database). If it doesn't exist, it will look in the LDAP following the priority order /// If the given username has the format of "username@domain" the user will be created in the LDAP with the given domain. /// </summary> /// <param name="username"></param> /// <param name="transactionId"></param> /// <returns></returns> ExternalAuthenticationResponse ExternalAuthenticate(String username, String transactionId); /* QR Authentication */ /* step 1 */ /// <summary> /// Get's the sessionKey string to sign /// /// The username will determine if the user is an internal user or an LDAP user. /// If the given username has the format of "username" the user will be created as an internal user(In the database). If it doesn't exist, it will look in the LDAP following the priority order. /// If the given username has the format of "username@domain" the user will be created in the LDAP with the given domain. /// </summary> /// <returns></returns> SessionKeyResponse CreateSessionKeyChallenge(); /// <summary> /// Get's the sessionKey string to sign /// /// The username will determine if the user is an internal user or an LDAP user. /// If the given username has the format of "username" the user will be created as an internal user(In the database). If it doesn't exist, it will look in the LDAP following the priority order. /// If the given username has the format of "username@domain" the user will be created in the LDAP with the given domain. /// </summary> /// <param name="transactionId"></param> /// <returns></returns> SessionKeyResponse CreateSessionKeyChallenge( String transactionId); /* step 2 */ /// <summary> /// Sends a Push signature to the mobile device. /// /// The username will determine if the user is an internal user or an LDAP user. /// If the given username has the format of "username" the user will be created as an internal user(In the database). If it doesn't exist, it will look in the LDAP following the priority order. /// If the given username has the format of "username@domain" the user will be created in the LDAP with the given domain. /// </summary> /// <param name="sessionKey">The challenge obtained with createSessionKeyChallenge()</param> /// <returns></returns> SessionKeyVerificationResponse VerifySessionKeyStatus(String sessionKey); /// <summary> /// Sends a Push signature to the mobile device. /// /// The username will determine if the user is an internal user or an LDAP user. /// If the given username has the format of "username" the user will be created as an internal user(In the database). If it doesn't exist, it will look in the LDAP following the priority order. /// If the given username has the format of "username@domain" the user will be created in the LDAP with the given domain. /// </summary> /// <param name="sessionKey">The challenge obtained with createSessionKeyChallenge()</param> /// <param name="transactionId"></param> /// <returns></returns> SessionKeyVerificationResponse VerifySessionKeyStatus(String sessionKey, String transactionId); /* signature API */ /// <summary> /// Standard authentication for external users. /// /// The username will determine if the user is an internal user or an LDAP user. /// If the given username has the format of "username" the user will be created as an internal user(In the database). If it doesn't exist, it will look in the LDAP following the priority order. /// If the given username has the format of "username@domain" the user will be created in the LDAP with the given domain. /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="_hash"></param> /// <param name="_data"> The data to sign. Data or body are required</param> /// <param name="title">The title displayed in the mobile device. Optional</param> /// <param name="body">The body of the push. Data or body are required</param> /// <returns></returns> SignatureResponse SendPushSignature(String username, String password, String _hash, String _data, String title, String body); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk { public class CreateRegistrationCode : BaseResponse { #region "vars" private String Code; #endregion #region "constr" public CreateRegistrationCode(int httpCode) : base(httpCode) { this.Code = null; } public CreateRegistrationCode(int httpCode , String code) : base(httpCode) { this.Code = code; } public CreateRegistrationCode(int httpCode , Dictionary<String, List<String>> errors , String code) : base(httpCode, errors) { } #endregion #region "publics" public override String ToString() { var sb = new StringBuilder(); sb.Append(this.httpCode.ToString()).Append(SEPARATOR); sb.Append(this.Code.ToString()).Append(SEPARATOR); foreach (KeyValuePair<String, List<String>> error in this.errors) { sb.Append(error.Key).Append(" ["); foreach (String e in error.Value) { sb.Append(e).Append(", "); } sb.Append("]").Append(SEPARATOR); } return sb.ToString(); } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk { public enum AuthenticationCode { ACCESS_ALLOWED, ACCESS_CHALLENGE, ACCESS_DENIED } public enum ReplyCode { ///<sumary> /// The user is locked. ///</sumary> USR_LOCKED, ///<sumary> /// An internal error occured. ///</sumary> INTERNAL_SYSTEM_ERROR, ///<sumary> /// Invalid credentials. ///</sumary> INVALID_CREDENTIALS, ///<sumary> /// OTP required. This is the case where the user has a token with password required enabled (2 Step authentication). ///</sumary> OTP_REQUIRED, ///<sumary> /// The device (token) is out of sync ///</sumary> DEVICE_OUT_OF_SYNC } public class AuthenticationResponse : BaseResponse { #region "vars" private readonly AuthenticationCode? code; private readonly String transactionId; private readonly String username; private readonly String replyMessage; private readonly String detail; private readonly ReplyCode? replyCode; #endregion #region "constr" public AuthenticationResponse(int httpCode , AuthenticationCode? code , String transactionId , String username , String replyMessage , String detail , ReplyCode? replyCode) : base(httpCode) { this.code = code; this.transactionId = transactionId; this.username = username; this.replyMessage = replyMessage; this.detail = detail; this.replyCode = replyCode; } public AuthenticationResponse(int httpCode , Dictionary<String, List<String>> errors) : base(httpCode, errors) { this.code = null; this.transactionId = null; this.username = null; this.replyMessage = null; this.detail = null; this.replyCode = null; } #endregion #region "Publics" public override String ToString() { var sb = new StringBuilder(); sb.Append(this.httpCode.ToString()).Append(SEPARATOR); if (this.code != null) sb.Append(this.code).Append(SEPARATOR); if (this.transactionId != null) sb.Append(this.transactionId).Append(SEPARATOR); if (this.username != null) sb.Append(this.username).Append(SEPARATOR); if (this.replyMessage != null) sb.Append(this.replyMessage).Append(SEPARATOR); if (this.detail != null) sb.Append(this.detail).Append(SEPARATOR); if (this.replyCode != null) sb.Append(this.replyCode).Append(SEPARATOR); foreach (KeyValuePair<String, List<String>> error in this.errors) { sb.Append(error.Key).Append(" ["); foreach (String e in error.Value) { sb.Append(e).Append(", "); } sb.Append("]").Append(SEPARATOR); } return sb.ToString(); } public AuthenticationCode? getCode() { return code; } public String getTransactionId() { return transactionId; } public String getUsername() { return username; } public String getReplyMessage() { return replyMessage; } public int getHttpCode() { return httpCode; } public String getDetail() { return detail; } public ReplyCode? getReplyCode() { return replyCode; } #endregion } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk { public class BaseResponse { #region "vars" protected int httpCode; protected Dictionary<String, List<String>> errors; protected const String SEPARATOR = " | "; #endregion #region "constr" public BaseResponse(int httpCode) { this.httpCode = httpCode; this.errors = new Dictionary<string, List<string>>(); } public BaseResponse(int httpCode , Dictionary<String, List<String>> errors) { this.httpCode = httpCode; this.errors = errors; } #endregion #region "Publics" public Dictionary<String, List<String>> getErrors() { return errors; } public override String ToString() { var sb = new StringBuilder(); sb.Append(this.httpCode.ToString()).Append(SEPARATOR); foreach (KeyValuePair<String, List<String>> error in this.errors) { sb.Append(error.Key).Append(" ["); foreach (String e in error.Value) { sb.Append(e).Append(", "); } sb.Append("]").Append(SEPARATOR); } return sb.ToString(); } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk { public class UpdateUserResponse : BaseResponse { #region "constr" public UpdateUserResponse (int httpCode) :base (httpCode) { } public UpdateUserResponse(int httpCode , Dictionary<String, List<String>> errors) : base(httpCode, errors) { } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Configuration; using safewalk; using safewalk.helper; namespace test { class Program { private static System.Collections.Specialized.NameValueCollection settings = ConfigurationManager.AppSettings; private static readonly String HOST = settings["HOST"]; private static readonly long PORT = long.Parse(settings["PORT"]); private static readonly bool SET_BYPASS_SSL_CERTIFICATE = bool.Parse(settings["setBypassSSLCertificate"]); private static readonly String AUTHENTICATION_API_ACCESS_TOKEN = settings["AUTHENTICATION_API_ACCESS_TOKEN"]; private static readonly String ADMIN_API_ACCESS_TOKEN = settings["ADMIN_API_ACCESS_TOKEN"]; private static readonly String INTERNAL_USERNAME = settings["INTERNAL_USERNAME"]; private static readonly String INTERNAL_PASSWORD = settings["INTERNAL_<PASSWORD>"]; private static readonly String LDAP_USERNAME = settings["LDAP_USERNAME"]; private static readonly String LDAP_PASSWORD = settings["LDAP_PASSWORD"]; /*create user*/ private static readonly string USERNAME = settings["USER_username"]; private static readonly string PASSWORD = settings["<PASSWORD>"]; private static readonly string FIRSTNAME = settings["USER_firstName"]; private static readonly string LASTNAME = settings["USER_lastName"]; private static readonly string MOBILEPHONE = settings["USER_mobilePhone"]; private static readonly string EMAIL = settings["USER_email"]; private static readonly string PARENT = settings["USER_parent"]; /*update user*/ private static readonly string MOBILEPHONE_NEW = settings["USER_mobilePhone_new"]; private static readonly string EMAIL_NEW = settings["USER_email_new"]; /*set static pass*/ private static readonly string PASSWORD_NEW = settings["USER_password_new"]; /*push signature */ private static readonly string HASH = settings["hash"]; private static readonly string DATA = settings["data"]; private static readonly string TITLE = settings["title"]; private static readonly string BODY = settings["body"]; static private IServerConnectivityHelper serverConnectivityHelper ; static void Main(string[] args) { /*auth client */ TestSafewalkClientStandardAuthentication(INTERNAL_USERNAME, INTERNAL_PASSWORD); TestSafewalkClientExternalAuthentication(INTERNAL_USERNAME); TestSafewalkClientGenerateChallenge(INTERNAL_USERNAME); TestSafewalkClientsignature(INTERNAL_USERNAME, INTERNAL_PASSWORD, HASH, DATA, TITLE, BODY); Console.Read(); } private static void TestSafewalkClientStandardAuthentication(String username, String password) { Console.WriteLine("Standard Authentication PROCESS : start"); serverConnectivityHelper = new ServerConnectivityHelper(HOST, PORT, SET_BYPASS_SSL_CERTIFICATE); SafewalkAuthClient client = new SafewalkAuthClient(serverConnectivityHelper, AUTHENTICATION_API_ACCESS_TOKEN); AuthenticationResponse response1 = client.Authenticate(username, password); Console.WriteLine("Standard Authentication RESPONSE : " + response1); Console.WriteLine("Standard Authentication PROCESS : end"); } private static void TestSafewalkClientExternalAuthentication(String username) { Console.WriteLine("External Authentication PROCESS : start"); serverConnectivityHelper = new ServerConnectivityHelper(HOST, PORT, SET_BYPASS_SSL_CERTIFICATE); SafewalkAuthClient client = new SafewalkAuthClient(serverConnectivityHelper, AUTHENTICATION_API_ACCESS_TOKEN); AuthenticationResponse response1 = client.AuthenticateExternal(username); Console.WriteLine("External Authentication RESPONSE : " + response1); Console.WriteLine("External Authentication PROCESS : end"); } private static void TestSafewalkClientGenerateChallenge(String username) { Console.WriteLine("Generate Challenge - 1) Session Key PROCESS : start"); serverConnectivityHelper = new ServerConnectivityHelper(HOST, PORT, SET_BYPASS_SSL_CERTIFICATE); SafewalkAuthClient client = new SafewalkAuthClient(serverConnectivityHelper, AUTHENTICATION_API_ACCESS_TOKEN); SessionKeyResponse response1 = client.CreateSessionKeyChallenge(); Console.WriteLine("Generate Challenge - Session Key RESPONSE : " + response1); Console.WriteLine("\nGenerate Challenge - 2) Verify Session Key: start"); SessionKeyVerificationResponse response2 = client.VerifySessionKeyStatus(response1.GetChallenge()); Console.WriteLine("Generate Challenge - Session Key RESPONSE : " + response2); Console.WriteLine("Generate Challenge PROCESS : end"); } private static void TestSafewalkClientsignature(String username, String password, String _hash, String _data, String title, String body) { Console.WriteLine("Push signature PROCESS : start"); serverConnectivityHelper = new ServerConnectivityHelper(HOST, PORT, SET_BYPASS_SSL_CERTIFICATE); SafewalkAuthClient client = new SafewalkAuthClient(serverConnectivityHelper, AUTHENTICATION_API_ACCESS_TOKEN); SignatureResponse response1 = client.SendPushSignature(username, password, _hash, _data, title, body); Console.WriteLine("Push signature RESPONSE : " + response1); Console.WriteLine("Push signature PROCESS : end"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk { public class GetUserResponse : BaseResponse { private String dbMobilePhone; private String dbEmail; private String ldapMobilePhone; private String ldapEmail; private UserStorage? userStorage; private String firstName; private String lastName; private String dn; private String username; private Boolean? locked; public GetUserResponse(int httpCode , String username , String firstName , String lastName , String dn , String dbMobilePhone , String dbEmail , String ldapMobilePhone , String ldapEmail , UserStorage? userStorage , Boolean locked) : base(httpCode) { this.dbMobilePhone = dbMobilePhone; this.dbEmail = dbEmail; this.ldapMobilePhone = ldapMobilePhone; this.ldapEmail = ldapEmail; this.userStorage = userStorage; this.firstName = firstName; this.lastName = lastName; this.dn = dn; this.username = username; this.locked = locked; } public GetUserResponse(int httpCode , Dictionary<String, List<String>> errors) : base(httpCode, errors) { this.dbMobilePhone = null; this.dbEmail = null; this.ldapMobilePhone = null; this.ldapEmail = null; this.userStorage = null; this.firstName = null; this.lastName = null; this.dn = null; this.username = null; this.locked = null; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Security.Cryptography.X509Certificates; namespace safewalk.web { public class MyWebClient : WebClient { protected override WebRequest GetWebRequest(Uri address) { HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address); request.ClientCertificates.Add(new X509Certificate()); return request; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Json; using safewalk.helper; using System.IO; namespace safewalk { public class SafewalkAuthClient : ISafewalkAuthClient { #region "consts" /* Authentication response */ private readonly String JSON_AUTH_REPLY_MESSAGE_FIELD = "reply-message"; private readonly String JSON_AUTH_REPLY_CODE_FIELD = "reply-code"; private readonly String JSON_AUTH_CODE_FIELD = "code"; private readonly String JSON_AUTH_TRANSACTION_FIELD = "transaction-id"; private readonly String JSON_AUTH_USERNAME_ID_FIELD = "username"; private readonly String JSON_AUTH_DETAIL_FIELD = "detail"; private readonly String JSON_AUTH_CHALLENGE = "challenge"; private readonly String JSON_AUTH_PURPOSE = "purpose"; private readonly String JSON_AUTH_CODE = "code"; #endregion #region "vars" private IServerConnectivityHelper ServerConnetivityHelper; private String AccessToken; #endregion #region "constr" public SafewalkAuthClient(IServerConnectivityHelper serverConnetivityHelper, String accessToken) { this.ServerConnetivityHelper = serverConnetivityHelper; this.AccessToken = accessToken; } #endregion #region "publics" public AuthenticationResponse Authenticate(String username, String password) { return this.Authenticate(username, password, null); } public AuthenticationResponse Authenticate(String username, String password, String transactionId) { var parameters = new Dictionary<String, String>() { { "username", username }, { "password", <PASSWORD> }, { "transaction_id", transactionId } }; var headers = new Dictionary<String, String>() { { "Authorization", "Bearer " + AccessToken } }; Response response = ServerConnetivityHelper.post("/api/v1/auth/authenticate/?format=json", parameters, headers); if (response.getResponseCode() == 200 || response.getResponseCode() == 401) { // convert string to stream byte[] byteArray = Encoding.UTF8.GetBytes(response.getContent()); var stream = new MemoryStream(byteArray); var jsonResponse = (JsonObject)JsonValue.Load(stream); return new AuthenticationResponse( response.getResponseCode() , this.getAuthenticationCode(jsonResponse, JSON_AUTH_CODE_FIELD) , this.getString(jsonResponse, JSON_AUTH_TRANSACTION_FIELD) , this.getString(jsonResponse, JSON_AUTH_USERNAME_ID_FIELD) , this.getString(jsonResponse, JSON_AUTH_REPLY_MESSAGE_FIELD) , this.getString(jsonResponse, JSON_AUTH_DETAIL_FIELD) , this.getReplyCode(jsonResponse, JSON_AUTH_REPLY_CODE_FIELD) ); } else { return new AuthenticationResponse(response.getResponseCode(), getErrors(response.getContent())); } } public ExternalAuthenticationResponse AuthenticateExternal(String username) { return this.ExternalAuthenticate(username, null); } public ExternalAuthenticationResponse ExternalAuthenticate(String username, String transactionId) { var parameters = new Dictionary<String, String>() { { "username", username }, { "transaction_id", transactionId } }; var headers = new Dictionary<String, String>() { { "Authorization", "Bearer " + AccessToken } }; Response response = ServerConnetivityHelper.post("/api/v1/auth/pswdcheckedauth/?format=json", parameters, headers); if (response.getResponseCode() == 200 || response.getResponseCode() == 401) { // convert string to stream byte[] byteArray = Encoding.UTF8.GetBytes(response.getContent()); var stream = new MemoryStream(byteArray); var jsonResponse = (JsonObject)JsonValue.Load(stream); return new ExternalAuthenticationResponse( response.getResponseCode() , this.getAuthenticationCode(jsonResponse, JSON_AUTH_CODE_FIELD) , this.getString(jsonResponse, JSON_AUTH_TRANSACTION_FIELD) , this.getString(jsonResponse, JSON_AUTH_USERNAME_ID_FIELD) , this.getString(jsonResponse, JSON_AUTH_REPLY_MESSAGE_FIELD) , this.getString(jsonResponse, JSON_AUTH_DETAIL_FIELD) , this.getReplyCode(jsonResponse, JSON_AUTH_REPLY_CODE_FIELD) ); } else { return new ExternalAuthenticationResponse(response.getResponseCode(), getErrors(response.getContent())); } } public SessionKeyResponse CreateSessionKeyChallenge() { return this.CreateSessionKeyChallenge(null); } public SessionKeyResponse CreateSessionKeyChallenge(String transactionId) { var parameters = new Dictionary<String, String>() { { "transaction_id", transactionId }, }; var headers = new Dictionary<String, String>() { { "Authorization", "Bearer " + AccessToken } }; Response response = ServerConnetivityHelper.post("/api/v1/auth/session_key/?format=json", parameters, headers); if (response.getResponseCode() == 200 ) { // convert string to stream byte[] byteArray = Encoding.UTF8.GetBytes(response.getContent()); var stream = new MemoryStream(byteArray); var jsonResponse = (JsonObject)JsonValue.Load(stream); return new SessionKeyResponse( response.getResponseCode() , this.getStringWithoutQuotes(jsonResponse, JSON_AUTH_CHALLENGE) , this.getString(jsonResponse, JSON_AUTH_PURPOSE) ); } else { return new SessionKeyResponse(response.getResponseCode(), getErrors(response.getContent())); } } public SessionKeyVerificationResponse VerifySessionKeyStatus(String sessionKey) { return this.VerifySessionKeyStatus(sessionKey, null); } public SessionKeyVerificationResponse VerifySessionKeyStatus( String sessionKey , String transactionId) { var parameters = new Dictionary<String, String>() { { "transaction_id", transactionId }, }; var headers = new Dictionary<String, String>() { { "Authorization", "Bearer " + AccessToken } }; var link = "/api/v1/auth/session_key/" + sessionKey + "/?format=json"; Response response = ServerConnetivityHelper.get(link, parameters, headers); if (response.getResponseCode() == 200) { // convert string to stream byte[] byteArray = Encoding.UTF8.GetBytes(response.getContent()); var stream = new MemoryStream(byteArray); var jsonResponse = (JsonObject)JsonValue.Load(stream); return new SessionKeyVerificationResponse( response.getResponseCode() , this.getString(jsonResponse, JSON_AUTH_CODE) ); } else { return new SessionKeyVerificationResponse(response.getResponseCode(), getErrors(response.getContent())); } } public SignatureResponse SendPushSignature( String username , String <PASSWORD> , String _hash , String _data , String title , String body) { var parameters = new Dictionary<String, String>() { { "username", username }, { "password", <PASSWORD> }, { "hash", _hash }, { "data", _data }, { "title", title }, { "body", body } }; var headers = new Dictionary<String, String>() { { "Authorization", "Bearer " + AccessToken } }; Response response = ServerConnetivityHelper.post("/api/v1/auth/push_signature/", parameters, headers); if (response.getResponseCode() == 200) { return new SignatureResponse(response.getResponseCode()); } else if (response.getResponseCode() == 400) { return new SignatureResponse(response.getResponseCode(), getErrors(response.getContent())); } else { return new SignatureResponse(response.getResponseCode(), getErrors(response.getContent())); } } #endregion #region "privates" private String getString(IDictionary<string, JsonValue> json, String key) { if (json.ContainsKey(key)) if (json[key] != null) return json[key].ToString(); return ""; } private String getStringWithoutQuotes(IDictionary<string, JsonValue> json, String key) { if (json.ContainsKey(key)) if (json[key] != null) return json[key].ToString().Replace("\"", ""); return ""; } private Boolean getBoolean(IDictionary<string, JsonValue> json, String key) { if (json.ContainsKey(key)) if (json[key] != null) return bool.Parse(json[key].ToString()); return false; } private AuthenticationCode? getAuthenticationCode(IDictionary<string, JsonValue> json, String key) { if (json.ContainsKey(key) && json[key] != null) { return (AuthenticationCode)Enum.Parse(typeof(AuthenticationCode), (string)json[key]); } return null; } private UserStorage? getUserStorage(IDictionary<string, JsonValue> json, String key) { if (json.ContainsKey(key) && json[key] != null) { return (UserStorage)Enum.Parse(typeof(UserStorage), (string)json[key]); } return null; } private ReplyCode? getReplyCode(IDictionary<string, JsonValue> json, String key) { if (json.ContainsKey(key) && json[key] != null) { return (ReplyCode)Enum.Parse(typeof(ReplyCode), (string)json[key]); } return null; } private Dictionary<String, List<String>> getErrors(String errors) { var result = new Dictionary<String, List<String>>(); try { // convert string to stream byte[] byteArray = Encoding.UTF8.GetBytes(errors); //byte[] byteArray = Encoding.ASCII.GetBytes(contents); var stream = new MemoryStream(byteArray); var jsonResponse = (JsonObject)JsonValue.Load(stream); List<string> keys = jsonResponse.Keys.ToList(); int cant = 0; while (cant < keys.Count) { var key = (String)keys[cant]; List<String> values = new List<string>(); var data = jsonResponse[key]; foreach (var d in data) { values.Add((String)d.Value); } result.Add(key, values); cant += 1; } return result; } catch (ArgumentException e) { return new Dictionary<String, List<String>>(); } catch (FormatException e) { return new Dictionary<String, List<String>>(); } } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk { public class TokenAssociation { private String serialNumber ; private String deviceType; private Boolean confirmed; private Boolean passwordRequired; public TokenAssociation(String deviceType , String serialNumber , Boolean confirmed , Boolean passwordRequired) { this.serialNumber = serialNumber; this.deviceType = deviceType; this.confirmed = confirmed; this.passwordRequired = password<PASSWORD>; } public override String ToString() { StringBuilder sb = new StringBuilder(); sb.Append(this.deviceType).Append(", "); sb.Append(this.serialNumber).Append(", "); sb.Append(this.confirmed); return sb.ToString(); } public String getSerialNumber() { return serialNumber; } public String getDeviceType() { return deviceType; } public Boolean getConfirmed() { return confirmed; } public Boolean getPasswordRequired() { return passwordRequired; } } } <file_sep># .NET SDK module for Safewalk integration * [Authentication API](#authentication-api) ## Authentication API ### Usage ```csharp String host = "https://192.168.1.160"; long port = 8443; private static string AUTHENTICATION_API_ACCESS_TOKEN = "c4608fc697e844829bb5a27cce13737250161bd0"; private static string INTERNAL_USERNAME = "internal"; private static string STATIC_PASSWORD_USERNAME = "internal"; private static string FAST_AUTH_USERNAME = "fastauth"; private static bool BYPASS_SSL_CHECK = false; /*push signature */ private static readonly string HASH = "AAAB9621D3AECD703833646742818CA64739FAEDDC82C726B8C756E89DB6BBBB"; private static readonly string DATA = "All the data here will be signed. This request was generated from Safewalk API."; private static readonly string TITLE = "Sign Transaction"; private static readonly string BODY = "Push signature triggered from safewalk API"; serverConnectivityHelper = new ServerConnectivityHelper(HOST, PORT, BYPASS_SSL_CHECK); SafewalkAuthClient client = new SafewalkAuthClient(serverConnectivityHelper, AUTHENTICATION_API_ACCESS_TOKEN); /* Standard Authentication */ AuthenticationResponse response1 = client.Authenticate(INTERNAL_USERNAME, STATIC_PASSWORD_USERNAME); /* External Authentication */ AuthenticationResponse response2 = client.AuthenticateExternal(INTERNAL_USERNAME); /* Session Key Challenge and check status */ SessionKeyResponse responseA = client.CreateSessionKeyChallenge(); SessionKeyVerificationResponse responseB = client.VerifySessionKeyStatus(responseA.GetChallenge()); /* Push signature */ SignatureResponse response3 = client.SendPushSignature(FAST_AUTH_USERNAME, STATIC_PASSWORD_USERNAME, HASH, DATA, TITLE, BODY); ``` * host : The server host. * port : The server port. * AUTHENTICATION_API_ACCESS_TOKEN : The access token of the system user created to access the authentication-api. * INTERNAL_USERNAME: An LDAP or internal user * STATIC_PASSWORD_USERNAME : An LDAP or internal user with no licenses asigned and password authentication allowed. * FAST_AUTH_USER : The user registered in safewalk with a Fast:Auth:Sign license. * BYPASS_SSL_CHECK : To allow untrusted certificates. * HASH: The data hash. * DATA: The data to sign. Data or body are required * TITLE: The title displayed in the mobile device. * BODY: The body of the push. Data or body are required * ### Authentication Response Examples (AuthenticationResponse class) The response below show the result of providing valid credentials ``` 200 | ACCESS_ALLOWED | admin ``` The response below show the result when the access token is not valid (to fix it, check for the access token in the superadmin console) ``` 401 | Invalid token ``` The response below show the result when no access token is provided (to fix it, check for the access token in the superadmin console) ``` 401 | Invalid bearer header. No credentials provided. ``` The response below show the result when the credentials (username / password) are not valid ``` 401 | ACCESS_DENIED | Invalid credentials, please make sure you entered your username and up to date password/otp correctly ``` The response below show the result when the user is locked ``` 401 | ACCESS_DENIED | The user is locked, please contact your system administrator ``` The response below show the result when the user is required to enter an OTP ``` 401 | ACCESS_CHALLENGE | admin | Please enter your OTP code ``` ### For Testing 1) EXECUTE TEST.EXE (optional) edit test.exe.config to change the parameters passed to the test app<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk.helper { public interface IServerConnectivityHelper { Response post(String path, Dictionary<string,string> parameters, Dictionary<string,string> headers) ; //throw ConnectivityException; Response put(String path, Dictionary<string,string> parameters, Dictionary<string,string> headers) ; //throws ConnectivityException; Response get(String path, Dictionary<string,string> parameters, Dictionary<string,string> headers) ; //throws ConnectivityException; Response delete(String path, Dictionary<string,string> parameters, Dictionary<string,string> headers) ; //throws ConnectivityException; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Json; using safewalk.helper; using System.IO; namespace safewalk { public class SafewalkAdminClient : ISafewalkAdminClient { #region "consts" /* Create user response */ private readonly String JSON_CREATE_USER_USERNAME_FIELD = "username"; private readonly String JSON_CREATE_USER_FIRST_NAME_FIELD = "first_name"; private readonly String JSON_CREATE_USER_LAST_NAME_FIELD = "last_name"; private readonly String JSON_CREATE_USER_DN_FIELD = "dn"; private readonly String JSON_CREATE_USER_DB_MOBILE_PHONE_FIELD = "db_mobile_phone"; private readonly String JSON_CREATE_USER_DB_EMAIL_FIELD = "db_email"; private readonly String JSON_CREATE_USER_LDAP_MOBILE_PHONE_FIELD = "ldap_mobile_phone"; private readonly String JSON_CREATE_USER_LDAP_EMAIL_FIELD = "ldap_email"; private readonly String JSON_CREATE_USER_STORAGE_FIELD = "user_storage"; /* Get user response */ private readonly String JSON_GET_USER_USERNAME_FIELD = "username"; private readonly String JSON_GET_USER_FIRST_NAME_FIELD = "first_name"; private readonly String JSON_GET_USER_LAST_NAME_FIELD = "last_name"; private readonly String JSON_GET_USER_DN_FIELD = "dn"; private readonly String JSON_GET_USER_DB_MOBILE_PHONE_FIELD = "db_mobile_phone"; private readonly String JSON_GET_USER_DB_EMAIL_FIELD = "db_email"; private readonly String JSON_GET_USER_LDAP_MOBILE_PHONE_FIELD = "ldap_mobile_phone"; private readonly String JSON_GET_USER_LDAP_EMAIL_FIELD = "ldap_email"; private readonly String JSON_GET_USER_STORAGE_FIELD = "user_storage"; private readonly String JSON_GET_USER_IS_LOCKED_FIELD = "is_locked"; /* Associate token response */ private readonly String JSON_ASSOCIATE_TOKEN_FAIL_TO_SEND_REG_CODE_FIELD = "fail_to_send_registration_code"; private readonly String JSON_ASSOCIATE_TOKEN_FAIL_TO_SEND_DOWNLOAD_LINKS_FIELD = "fail_to_send_download_links"; /* Associations response */ private readonly String JSON_GET_TOKEN_ASSOCIATIONS_DEVICE_TYPE_FIELD = "type"; private readonly String JSON_GET_TOKEN_ASSOCIATIONS_SERIAL_NUMBER_FIELD = "serial_number"; private readonly String JSON_GET_TOKEN_ASSOCIATIONS_CONFIRMED_FIELD = "confirmed"; private readonly String JSON_GET_TOKEN_ASSOCIATIONS_PASSWORD_REQUIRED_FIELD = "password_required"; /* Delete associations response */ private readonly String JSON_DELETE_TOKEN_ASSOCIATION_CODE_FIELD = "code"; /* Create registration code response */ private readonly String JSON_CREATE_REGISTRATION_CODE_CODE_FIELD = "code"; #endregion #region "vars" private IServerConnectivityHelper ServerConnetivityHelper; #endregion #region "constr" public SafewalkAdminClient(IServerConnectivityHelper serverConnetivityHelper) { this.ServerConnetivityHelper = serverConnetivityHelper; } #endregion #region "publics" public CreateUserResponse CreateUser(string accessToken, string username, string password, string firstName, string lastName, string mobilePhone, string email, string parent) { var parameters = new Dictionary<String, String>() { { "username", username }, { "password", <PASSWORD> }, {"first_name", firstName }, {"last_name", lastName }, {"mobile_phone", mobilePhone }, {"email", email }, {"parent", parent }, }; var headers = new Dictionary<String, String>() { { "Authorization", "Bearer " + accessToken } }; Response response = ServerConnetivityHelper.post("/api/v1/admin/user/?format=json", parameters, headers); if (response.getResponseCode() == 201) { byte[] byteArray = Encoding.UTF8.GetBytes(response.getContent()); var stream = new MemoryStream(byteArray); var jsonResponse = (JsonObject)JsonValue.Load(stream); return new CreateUserResponse( response.getResponseCode() , this.getString(jsonResponse, JSON_CREATE_USER_USERNAME_FIELD) , this.getString(jsonResponse, JSON_CREATE_USER_FIRST_NAME_FIELD) , this.getString(jsonResponse, JSON_CREATE_USER_LAST_NAME_FIELD) , this.getString(jsonResponse, JSON_CREATE_USER_DN_FIELD) , this.getString(jsonResponse, JSON_CREATE_USER_DB_MOBILE_PHONE_FIELD) , this.getString(jsonResponse, JSON_CREATE_USER_DB_EMAIL_FIELD) , this.getString(jsonResponse, JSON_CREATE_USER_LDAP_MOBILE_PHONE_FIELD) , this.getString(jsonResponse, JSON_CREATE_USER_LDAP_EMAIL_FIELD) , (this.getString(jsonResponse, JSON_CREATE_USER_STORAGE_FIELD) != null ? this.getUserStorage(jsonResponse, JSON_CREATE_USER_STORAGE_FIELD) : null) ); } else { return new CreateUserResponse(response.getResponseCode(), getErrors(response.getContent())); } } public UpdateUserResponse UpdateUser(String accessToken, String username, String mobilePhone, String email) { var parameters = new Dictionary<String, String>() { {"mobile_phone", mobilePhone }, {"email", email }, }; var headers = new Dictionary<String, String>() { { "Authorization", "Bearer " + accessToken } }; Response response = ServerConnetivityHelper.put(String.Format("/api/v1/admin/user/%s/?format=json", username), parameters, headers); if (response.getResponseCode() == 200) { byte[] byteArray = Encoding.UTF8.GetBytes(response.getContent()); var stream = new MemoryStream(byteArray); return new UpdateUserResponse(response.getResponseCode()); } else { return new UpdateUserResponse(response.getResponseCode(), getErrors(response.getContent())); } } public GetUserResponse GetUser(String accessToken, String username) { var parameters = new Dictionary<String, String>() { {"format", "json" }, }; var headers = new Dictionary<String, String>() { { "Authorization", "Bearer " + accessToken } }; Response response = ServerConnetivityHelper.get(String.Format( "/api/v1/admin/user/%s/?format=json", username), parameters, headers); if (response.getResponseCode() == 200) { byte[] byteArray = Encoding.UTF8.GetBytes(response.getContent()); var stream = new MemoryStream(byteArray); var jsonResponse = (JsonObject)JsonValue.Load(stream); return new GetUserResponse( response.getResponseCode() , this.getString(jsonResponse, JSON_GET_USER_USERNAME_FIELD) , this.getString(jsonResponse, JSON_GET_USER_FIRST_NAME_FIELD) , this.getString(jsonResponse, JSON_GET_USER_LAST_NAME_FIELD) , this.getString(jsonResponse, JSON_GET_USER_DN_FIELD) , this.getString(jsonResponse, JSON_GET_USER_DB_MOBILE_PHONE_FIELD) , this.getString(jsonResponse, JSON_GET_USER_DB_EMAIL_FIELD) , this.getString(jsonResponse, JSON_GET_USER_LDAP_MOBILE_PHONE_FIELD) , this.getString(jsonResponse, JSON_GET_USER_LDAP_EMAIL_FIELD) , (this.getString(jsonResponse, JSON_GET_USER_STORAGE_FIELD) != null ? this.getUserStorage(jsonResponse, JSON_GET_USER_STORAGE_FIELD) : null) , this.getBoolean(jsonResponse, JSON_GET_USER_IS_LOCKED_FIELD) ); } else { return new GetUserResponse(response.getResponseCode(), getErrors(response.getContent())); } } public DeleteUserResponse DeleteUser(String accessToken, String username) { var parameters = new Dictionary<String, String>() { }; var headers = new Dictionary<String, String>() { { "Authorization", "Bearer " + accessToken } }; Response response = ServerConnetivityHelper.delete(String.Format("/api/v1/admin/user/%s/", username), parameters, headers); if (response.getResponseCode() == 204) { return new DeleteUserResponse(response.getResponseCode()); } else { return new DeleteUserResponse(response.getResponseCode(), getErrors(response.getContent())); } } public SetStaticPasswordResponse SetStaticPassword(String accessToken, String username, String password) { var parameters = new Dictionary<String, String>() { { "username", username }, { "password", <PASSWORD> }, }; var headers = new Dictionary<String, String>() { { "Authorization", "Bearer " + accessToken } }; Response response = ServerConnetivityHelper.post("/api/v1/admin/staticpassword/set/", parameters, headers); if (response.getResponseCode() == 200) { return new SetStaticPasswordResponse(response.getResponseCode()); } else { return new SetStaticPasswordResponse(response.getResponseCode(), getErrors(response.getContent())); } } public AssociateTokenResponse AssociateToken(String accessToken, String username, DeviceType deviceType) { return AssociateToken(accessToken, username, deviceType, null, null); } public AssociateTokenResponse AssociateToken(String accessToken, String username, DeviceType deviceType, Boolean? sendRegistrationCode, Boolean? sendDownloadLinks) { var parameters = new Dictionary<String, String>() { {"username", username }, {"device_type", deviceType.getCode() }, }; if (sendDownloadLinks != null) { parameters.Add("send_download_links", sendDownloadLinks.ToString()); } if (sendRegistrationCode != null) { parameters.Add("send_registration_code", sendRegistrationCode.ToString()); } var headers = new Dictionary<String, String>() { { "Authorization", "Bearer " + accessToken } }; Response response = ServerConnetivityHelper.post(String.Format("/api/v1/admin/user/%s/devices/?format=json", username), parameters, headers); if (response.getResponseCode() == 200) { byte[] byteArray = Encoding.UTF8.GetBytes(response.getContent()); var stream = new MemoryStream(byteArray); var jsonResponse = (JsonObject)JsonValue.Load(stream); return new AssociateTokenResponse(response.getResponseCode() , this.getBoolean(jsonResponse, JSON_ASSOCIATE_TOKEN_FAIL_TO_SEND_REG_CODE_FIELD) , this.getBoolean(jsonResponse, JSON_ASSOCIATE_TOKEN_FAIL_TO_SEND_DOWNLOAD_LINKS_FIELD)); } else { return new AssociateTokenResponse(response.getResponseCode(), getErrors(response.getContent())); } } public GetTokenAssociationsResponse GetTokenAssociations(String accessToken, String username) { var parameters = new Dictionary<String, String>() { {"format", "json" }, }; var headers = new Dictionary<String, String>() { { "Authorization", "Bearer " + accessToken } }; Response response = ServerConnetivityHelper.get(String.Format("/api/v1/admin/user/%s/devices/", username), parameters, headers); if (response.getResponseCode() == 200) { byte[] byteArray = Encoding.UTF8.GetBytes(response.getContent()); var stream = new MemoryStream(byteArray); var jsonArray = (JsonArray)JsonValue.Load(stream); List<TokenAssociation> associations = new List<TokenAssociation>(); for (int i = 0; jsonArray.Count>0; i++ ) { var json = (JsonObject)jsonArray[i]; associations.Add(new TokenAssociation( this.getString(json, JSON_GET_TOKEN_ASSOCIATIONS_DEVICE_TYPE_FIELD) , this.getString(json, JSON_GET_TOKEN_ASSOCIATIONS_SERIAL_NUMBER_FIELD) , this.getBoolean(json, JSON_GET_TOKEN_ASSOCIATIONS_CONFIRMED_FIELD) , this.getBoolean(json, JSON_GET_TOKEN_ASSOCIATIONS_PASSWORD_REQUIRED_FIELD))); } return new GetTokenAssociationsResponse(response.getResponseCode(), associations); } else { return new GetTokenAssociationsResponse(response.getResponseCode(), getErrors(response.getContent())); } } public DeleteTokenAssociation DeleteTokenAssociation(String accessToken, String username, DeviceType deviceType, String serialNumber) { var parameters = new Dictionary<String, String>() { {"format", "json" }, }; var headers = new Dictionary<String, String>() { { "Authorization", "Bearer " + accessToken } }; Response response = ServerConnetivityHelper.delete(String.Format("/api/v1/admin/user/%s/devices/%s/%s/", username, deviceType.getCode(), serialNumber), parameters, headers); if (response.getResponseCode() == 200 || response.getResponseCode() == 400) { byte[] byteArray = Encoding.UTF8.GetBytes(response.getContent()); var stream = new MemoryStream(byteArray); var jsonResponse = (JsonObject)JsonValue.Load(stream); return new DeleteTokenAssociation(response.getResponseCode(), this.getString(jsonResponse, JSON_DELETE_TOKEN_ASSOCIATION_CODE_FIELD)); } else { return new DeleteTokenAssociation(response.getResponseCode(), getErrors(response.getContent())); } } public CreateRegistrationCode CreateRegistrationCode(String accessToken, String username) { var parameters = new Dictionary<String, String>() { }; var headers = new Dictionary<String, String>() { { "Authorization", "Bearer " + accessToken } }; Response response = ServerConnetivityHelper.post(String.Format("/api/v1/admin/user/%s/registrationtoken/?format=json", username), parameters, headers); if (response.getResponseCode() == 200) { return new CreateRegistrationCode(response.getResponseCode()); } else if (response.getResponseCode() == 400) { byte[] byteArray = Encoding.UTF8.GetBytes(response.getContent()); var stream = new MemoryStream(byteArray); var jsonResponse = (JsonObject)JsonValue.Load(stream); return new CreateRegistrationCode(response.getResponseCode(), getErrors(response.getContent()), this.getString(jsonResponse, JSON_CREATE_REGISTRATION_CODE_CODE_FIELD)); } else { return new CreateRegistrationCode(response.getResponseCode(), getErrors(response.getContent()), null); } } #endregion #region "privates" private String getString(IDictionary<string, JsonValue> json, String key) { if (json.ContainsKey(key)) if (json[key] != null) return json[key].ToString(); return ""; } private Boolean getBoolean(IDictionary<string, JsonValue> json, String key) { if (json.ContainsKey(key)) if (json[key] != null) return bool.Parse(json[key].ToString()); return false; } private AuthenticationCode? getAuthenticationCode(IDictionary<string, JsonValue> json, String key) { if (json.ContainsKey(key) && json[key] != null) { return (AuthenticationCode)Enum.Parse(typeof(AuthenticationCode), (string)json[key]); } return null; } private UserStorage? getUserStorage(IDictionary<string, JsonValue> json, String key) { if (json.ContainsKey(key) && json[key] != null) { return (UserStorage)Enum.Parse(typeof(UserStorage), (string)json[key]); } return null; } private ReplyCode? getReplyCode(IDictionary<string, JsonValue> json, String key) { if (json.ContainsKey(key) && json[key] != null) { return (ReplyCode)Enum.Parse(typeof(ReplyCode), (string)json[key]); } return null; } private Dictionary<String, List<String>> getErrors(String errors) { var result = new Dictionary<String, List<String>>(); try { // convert string to stream byte[] byteArray = Encoding.UTF8.GetBytes(errors); //byte[] byteArray = Encoding.ASCII.GetBytes(contents); var stream = new MemoryStream(byteArray); var jsonResponse = (JsonObject)JsonValue.Load(stream); List<string > keys = jsonResponse.Keys.ToList(); int cant = 0; while (cant < keys.Count) { var key = (String)keys[cant]; List<String> values = new List<string>(); var data = jsonResponse[key]; foreach (var d in data) { values.Add((String)d.Value); } result.Add(key, values); cant += 1; } return result; } catch (ArgumentException e) { return new Dictionary<String, List<String>>(); } catch (FormatException e) { return new Dictionary<String, List<String>>(); } } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk { public class SessionKeyResponse : BaseResponse { #region "vars" private readonly String challenge; private readonly String purpose; #endregion #region "constr" public SessionKeyResponse(int httpCode , String challenge , String purpose) : base(httpCode) { this.challenge = challenge; this.purpose = purpose; } public SessionKeyResponse(int httpCode , Dictionary<String, List<String>> errors) : base(httpCode, errors) { this.challenge = null; this.purpose = null; } #endregion #region "publics" public override string ToString() { var sb = new StringBuilder(); sb.Append(this.httpCode.ToString()).Append(SEPARATOR); if (this.challenge != null) sb.Append(this.challenge.ToString()).Append(SEPARATOR); else sb.Append(SEPARATOR); if (this.purpose != null) sb.Append(this.purpose.ToString()).Append(SEPARATOR); else sb.Append(SEPARATOR); foreach (KeyValuePair<String, List<String>> error in this.errors) { sb.Append(error.Key).Append(" ["); foreach (String e in error.Value) { sb.Append(e).Append(", "); } sb.Append("]").Append(SEPARATOR); } return sb.ToString(); } public String GetChallenge() { return this.challenge; } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk { public class ExternalAuthenticationResponse : AuthenticationResponse { #region "constr" public ExternalAuthenticationResponse(int httpCode , AuthenticationCode? code , String transactionId , String username , String replyMessage , String detail , ReplyCode? replyCode) : base(httpCode , code , transactionId , username , replyMessage , detail , replyCode) { } public ExternalAuthenticationResponse(int httpCode , Dictionary<String, List<String>> errors) : base(httpCode , errors) { } } #endregion } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk.helper { public class Response { private readonly String content; private readonly int responseCode; public Response(String content, int responseCode) { this.content = content; this.responseCode = responseCode; } public String getContent() { return content; } public int getResponseCode() { return responseCode; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk { public class DeviceType { public static readonly DeviceType VIRTUAL = new DeviceType("Virtual"); public static readonly DeviceType SESAMI_MOBILE = new DeviceType("SESAMI:Mobile"); public static readonly DeviceType SESAMI_MOBILE_HYBRID = new DeviceType("SESAMI:Mobile:Hybrid"); public static readonly DeviceType TOTP_MOBILE = new DeviceType("TOTP:Mobile"); public static readonly DeviceType TOTP_MOBILE_HYBRID = new DeviceType("TOTP:Mobile:Hybrid"); public string code { get; private set; } DeviceType(string name) => code = name; public static IEnumerable<DeviceType> Values { get { yield return VIRTUAL; yield return SESAMI_MOBILE; yield return SESAMI_MOBILE_HYBRID; yield return TOTP_MOBILE; yield return TOTP_MOBILE_HYBRID; } } public String getCode() { return code; } public override string ToString() => code; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk { public class SignatureResponse : BaseResponse { public SignatureResponse(int httpCode) : base(httpCode) { } public SignatureResponse(int httpCode , Dictionary<String, List<String>> errors) : base(httpCode, errors) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace safewalk { public class AssociateTokenResponse : BaseResponse { #region "vars" private Boolean? failToSendRegistrationCode; private Boolean? failToSendDownloadLinks; #endregion #region "constr" public AssociateTokenResponse(int httpCode , Boolean failToSendRegistrationCode , Boolean failToSendDownloadLinks) : base(httpCode) { this.failToSendDownloadLinks = failToSendDownloadLinks; this.failToSendRegistrationCode = failToSendRegistrationCode; } public AssociateTokenResponse(int httpCode , Dictionary<String, List<String>> errors) : base(httpCode, errors) { this.failToSendDownloadLinks = null; this.failToSendRegistrationCode = null; } #endregion #region "publics" public override String ToString() { var sb = new StringBuilder(); sb.Append(this.httpCode.ToString()).Append(SEPARATOR); if (this.httpCode == 200) { sb.Append(this.failToSendRegistrationCode).Append(SEPARATOR); sb.Append(this.failToSendDownloadLinks).Append(SEPARATOR); } foreach (KeyValuePair<String, List<String>> error in this.errors) { sb.Append(error.Key).Append(" ["); foreach (String e in error.Value) { sb.Append(e).Append(", "); } sb.Append("]").Append(SEPARATOR); } return sb.ToString(); } #endregion } }
f61f857d0d307e8bb27a3e26147ad65561b0fca2
[ "Markdown", "C#" ]
24
C#
altipeak/safewalk-net-sdk
4133e4e16aa1437e8c34c72ca8f617657b3a9045
911dd2f307a1535c01672f8e99156ffe547a8abc
refs/heads/master
<repo_name>chitcode/CompDataAnalysisR<file_sep>/page_255.R # Computational Methods of data analysis # Source : page 255 ############################ SOURCE #################### # clear all; close all; % clear all variables and figures # L=20; % define the computational domain [-L/2,L/2] # n=128; % define the number of Fourier modes 2^n # x2=linspace(-L/2,L/2,n+1); % define the domain discretization # x=x2(1:n); % consider only the first n points: periodicity # dx=x(2)-x(1); % dx value needed for finite difference # u=sech(x); % function to take a derivative of # ut=fft(u); % FFT the function # k=(2*pi/L)*[0:(n/2-1) (-n/2):-1]; % k rescaled to 2pi domain # % FFT calculation of derivatives # ut1=i*k.*ut; % first derivative # ut2=-k.*k.*ut; % second derivative # u1=real(ifft(ut1)); u2=real(ifft(ut2)); % inverse transform # u1exact=-sech(x).*tanh(x); % analytic first derivative # u2exact=sech(x)-2*sech(x).^3; % analytic second derivative # % Finite difference calculation of first derivative # % 2nd-order accurate # ux(1)=(-3*u(1)+4*u(2)-u(3))/(2*dx); # for j=2:n-1 # ux(j)=(u(j+1)-u(j-1))/(2*dx); # end # ux(n)=(3*u(n)-4*u(n-1)+u(n-2))/(2*dx); # % 4th-order accurate # ux2(1)=(-3*u(1)+4*u(2)-u(3))/(2*dx); # ux2(2)=(-3*u(2)+4*u(3)-u(4))/(2*dx); # for j=3:n-2 # ux2(j)=(-u(j+2)+8*u(j+1)-8*u(j-1)+u(j-2))/(12*dx); # end # ux2(n-1)=(3*u(n-1)-4*u(n-2)+u(n-3))/(2*dx); ######################################### L <- 20 # define the computational domain [-L/2, L/2] n <- 128 #define the number of Fourier modes 2^n #x2 <- seq(from=-L/2, to = L/2, length.out = n+1) # define the domain discretization x2 <- seq(from= -L/2, to = L/2, length.out = n+1) x <- x2[1:n] # consider only the first n points: periodicity dx <- x[2]-x[1] #dx value needed for finite difference sech = function(a){ 1/cosh(a)} u <- sech(x) # function to take a derivative of ut <- fft(u) # FFT the function k <- (2*pi/L)*c(0:(n/2-1),(-n/2):-1) # k rescaled to 2*pi domain # FFT calculation of derivatives i <- 0+1i # in R, i is not defined directly the way of use is 0+1i ut1 <- i*k *ut # first derivative ut2 <- (i*k)^2 * ut # second derivative u1 <- Re(fft(ut1,inverse=T))/n #inversing the transformation u2 <- Re(fft(ut2,inverse=T))/n #inversing the transformation u1exact <- -sech(x)*tanh(x) #analytic first derivative u2exact <- sech(x)-2*sech(x)^3 # analytic second derivative plot(x,u1exact,type='l',col='red') points(x,u1,col='green') plot(x,u2exact,type='l',col='red') points(x,u2,col='green')<file_sep>/README.md CompDataAnalysisR ================= This is R code recreated from the lecture notes of "Computational Methods for Data Analysis"<file_sep>/page_259-260.R # Computational Methods of data analysis # Source : page 255 ########################SOURCE ########################## # clear all; close all; # L=30; % time slot to transform # n=512; % number of Fourier modes 2^9 # t2=linspace(-L,L,n+1); t=t2(1:n); % time discretization # k=(2*pi/(2*L))*[0:(n/2-1) -n/2:-1]; % frequency components of FFT # u=sech(t); % ideal signal in the time domain # figure(1), subplot(3,1,1), plot(t,u,'k'), hold on # # noise=1; # ut=fft(u); # utn=ut+noise*(randn(1,n)+i*randn(1,n)); # # un=ifft(utn); # figure(1), subplot(3,1,2), plot(t,abs(un),’k’), hold on ##################################################### L <- 30 n <- 512 t2 <- seq(from= -L,to=L,length.out=n+1) t <- t2[1:n] k <- (2 * pi/(2 * L)) * c(o:n/2-1, -n/2:-1) sech <- function(a){ 1/cosh(a)} u <- sech(t) layout(1:3) plot(t,u,type='l') noise <- 1 ut <- fft(u) utn <- ut + noise *(rnorm(n)+(0+1i)*rnorm(n)) #white noise is always added to frequency un <- fft(utn,inverse=T) plot(t,abs(un),type='l') noise <- 10 utn <- ut + noise *(rnorm(n)+(0+1i)*rnorm(n)) un <- fft(utn,inverse=T) plot(t,abs(un),type='l')<file_sep>/page_253.R # Computational Methods of data analysis # Source : page 253 ########################### SOURCE ################### # clear all; close all; % clear all variables and figures # L=20; % define the computational domain [-L/2,L/2] # n=128; % define the number of Fourier modes 2^n # x2=linspace(-L/2,L/2,n+1); % define the domain discretization # x=x2(1:n); % consider only the first n points: periodicity # u=exp(-x.*x); % function to take a derivative of # ut=fft(u); % FFT the function # utshift=fftshift(ut); % shift FFT # figure(1), plot(x,u) % plot initial gaussian # figure(2), plot(abs(ut)) % plot unshifted transform # figure(3), plot(abs(utshift)) % plot shifted transform ########################### L <- 20 # define the computational domain [-L/2, L/2] n <- 128 #define the number of Fourier modes 2^n x2 <- seq(from=-L/2, to = L/2, length.out = n+1) # define the domain discretization x <- x2[1:n] # consider only the first n points: periodicity u <- exp(-x^2) # function to take a derivative of ut <- fft(u) # FFT the function plot(x,u,type='l',xlab='x',ylab='u=exp(-x^2)',main='initial Gaussian') #plot initial gaussian plot(Re(ut),type='l',xlab='Fourier models',ylab='real[U]') # plotting the Fourier transformation #but the x axis is the index numbers, not yet marked for frequency #shiftng the values i.e. spliting the values half and moving them other side k <- (2*pi/L)*c(0:(n/2-1),(-n/2):-1) # rescaled to 2*pi domain plot(k,Re(ut), type="l", xlab="Frequencies", ylab="Re(fftshift(u)", main="Fourier modes" ) #plotting the absolute values plot(k,abs(ut), type="l", xlab="Frequencies", ylab="Re(fftshift(u)", main="Fourier modes" ) plot(x,u,type='l') plot(x,Re(ut),type='l')
b0b7b423b220883d2a65464a1d3c36d9cc1edd32
[ "Markdown", "R" ]
4
R
chitcode/CompDataAnalysisR
af288d6c9ed74091dbbcdfb6d1f75f9655857392
560b1c03ad5b1d62a97d4db43a35b7fa1b064859
refs/heads/master
<file_sep>__author__ = 'sanny' COLLECTION = 'users' <file_sep>__author__ = 'sanny' COLLECTION = "items" <file_sep>__author__ = 'sanny' <file_sep> DEBUG = True ADMINS = frozenset(['<EMAIL>']) <file_sep>__author__ = 'sanny' COLLECTION = "stores"
82939ed5c9dec76537538d4d0f634900082c9c7d
[ "Python" ]
5
Python
sannykr/Price-Alert
dc4cd7678f5245f798ab653dc3123a1a71b7b609
e155abdcaac85dee6777f5c73f1d19a93bc41ab1
refs/heads/master
<repo_name>xormsharp/xorm<file_sep>/tags/parser_test.go // Copyright 2020 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package tags import ( "reflect" "testing" "github.com/stretchr/testify/assert" "github.com/xormsharp/xorm/caches" "github.com/xormsharp/xorm/dialects" "github.com/xormsharp/xorm/names" ) type ParseTableName1 struct{} type ParseTableName2 struct{} func (p ParseTableName2) TableName() string { return "p_parseTableName" } func TestParseTableName(t *testing.T) { parser := NewParser( "xorm", dialects.QueryDialect("mysql"), names.SnakeMapper{}, names.SnakeMapper{}, caches.NewManager(), ) table, err := parser.Parse(reflect.ValueOf(new(ParseTableName1))) assert.NoError(t, err) assert.EqualValues(t, "parse_table_name1", table.Name) table, err = parser.Parse(reflect.ValueOf(new(ParseTableName2))) assert.NoError(t, err) assert.EqualValues(t, "p_parseTableName", table.Name) table, err = parser.Parse(reflect.ValueOf(ParseTableName2{})) assert.NoError(t, err) assert.EqualValues(t, "p_parseTableName", table.Name) } <file_sep>/dialects/table_name_test.go // Copyright 2018 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package dialects import ( "testing" "github.com/xormsharp/xorm/names" "github.com/stretchr/testify/assert" ) type MCC struct { ID int64 `xorm:"pk 'id'"` Code string `xorm:"'code'"` Description string `xorm:"'description'"` } func (mcc *MCC) TableName() string { return "mcc" } func TestFullTableName(t *testing.T) { dialect := QueryDialect("mysql") assert.EqualValues(t, "mcc", FullTableName(dialect, names.SnakeMapper{}, &MCC{})) assert.EqualValues(t, "mcc", FullTableName(dialect, names.SnakeMapper{}, "mcc")) } <file_sep>/schemas/quote_test.go // Copyright 2019 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package schemas import ( "strings" "testing" "github.com/stretchr/testify/assert" ) func TestAlwaysQuoteTo(t *testing.T) { var ( quoter = Quoter{'[', ']', AlwaysReserve} kases = []struct { expected string value string }{ {"[mytable]", "mytable"}, {"[mytable]", "`mytable`"}, {"[mytable]", `[mytable]`}, {`["mytable"]`, `"mytable"`}, {"[myschema].[mytable]", "myschema.mytable"}, {"[myschema].[mytable]", "`myschema`.mytable"}, {"[myschema].[mytable]", "myschema.`mytable`"}, {"[myschema].[mytable]", "`myschema`.`mytable`"}, {"[myschema].[mytable]", `[myschema].mytable`}, {"[myschema].[mytable]", `myschema.[mytable]`}, {"[myschema].[mytable]", `[myschema].[mytable]`}, {`["myschema].[mytable"]`, `"myschema.mytable"`}, {"[message_user] AS [sender]", "`message_user` AS `sender`"}, {"[myschema].[mytable] AS [table]", "myschema.mytable AS table"}, {" [mytable]", " mytable"}, {" [mytable]", " mytable"}, {"[mytable] ", "mytable "}, {"[mytable] ", "mytable "}, {" [mytable] ", " mytable "}, {" [mytable] ", " mytable "}, } ) for _, v := range kases { t.Run(v.value, func(t *testing.T) { buf := &strings.Builder{} quoter.QuoteTo(buf, v.value) assert.EqualValues(t, v.expected, buf.String()) }) } } func TestReversedQuoteTo(t *testing.T) { var ( quoter = Quoter{'[', ']', func(s string) bool { if s == "mytable" { return true } return false }} kases = []struct { expected string value string }{ {"[mytable]", "mytable"}, {"[mytable]", "`mytable`"}, {"[mytable]", `[mytable]`}, {`"mytable"`, `"mytable"`}, {"myschema.[mytable]", "myschema.mytable"}, {"myschema.[mytable]", "`myschema`.mytable"}, {"myschema.[mytable]", "myschema.`mytable`"}, {"myschema.[mytable]", "`myschema`.`mytable`"}, {"myschema.[mytable]", `[myschema].mytable`}, {"myschema.[mytable]", `myschema.[mytable]`}, {"myschema.[mytable]", `[myschema].[mytable]`}, {`"myschema.mytable"`, `"myschema.mytable"`}, {"message_user AS sender", "`message_user` AS `sender`"}, {"myschema.[mytable] AS table", "myschema.mytable AS table"}, } ) for _, v := range kases { t.Run(v.value, func(t *testing.T) { buf := &strings.Builder{} quoter.QuoteTo(buf, v.value) assert.EqualValues(t, v.expected, buf.String()) }) } } func TestNoQuoteTo(t *testing.T) { var ( quoter = Quoter{'[', ']', AlwaysNoReserve} kases = []struct { expected string value string }{ {"mytable", "mytable"}, {"mytable", "`mytable`"}, {"mytable", `[mytable]`}, {`"mytable"`, `"mytable"`}, {"myschema.mytable", "myschema.mytable"}, {"myschema.mytable", "`myschema`.mytable"}, {"myschema.mytable", "myschema.`mytable`"}, {"myschema.mytable", "`myschema`.`mytable`"}, {"myschema.mytable", `[myschema].mytable`}, {"myschema.mytable", `myschema.[mytable]`}, {"myschema.mytable", `[myschema].[mytable]`}, {`"myschema.mytable"`, `"myschema.mytable"`}, {"message_user AS sender", "`message_user` AS `sender`"}, {"myschema.mytable AS table", "myschema.mytable AS table"}, } ) for _, v := range kases { t.Run(v.value, func(t *testing.T) { buf := &strings.Builder{} quoter.QuoteTo(buf, v.value) assert.EqualValues(t, v.expected, buf.String()) }) } } func TestJoin(t *testing.T) { cols := []string{"f1", "f2", "f3"} quoter := Quoter{'[', ']', AlwaysReserve} assert.EqualValues(t, "[a],[b]", quoter.Join([]string{"a", " b"}, ",")) assert.EqualValues(t, "[f1], [f2], [f3]", quoter.Join(cols, ", ")) quoter.IsReserved = AlwaysNoReserve assert.EqualValues(t, "f1, f2, f3", quoter.Join(cols, ", ")) } func TestStrings(t *testing.T) { cols := []string{"f1", "f2", "t3.f3"} quoter := Quoter{'[', ']', AlwaysReserve} quotedCols := quoter.Strings(cols) assert.EqualValues(t, []string{"[f1]", "[f2]", "[t3].[f3]"}, quotedCols) } func TestTrim(t *testing.T) { var kases = map[string]string{ "[table_name]": "table_name", "[schema].[table_name]": "schema.table_name", } for src, dst := range kases { assert.EqualValues(t, src, CommonQuoter.Trim(src)) assert.EqualValues(t, dst, Quoter{'[', ']', AlwaysReserve}.Trim(src)) } } func TestReplace(t *testing.T) { q := Quoter{'[', ']', AlwaysReserve} var kases = []struct { source string expected string }{ { "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ?", "SELECT [COLUMN_NAME] FROM [INFORMATION_SCHEMA].[COLUMNS] WHERE [TABLE_SCHEMA] = ? AND [TABLE_NAME] = ? AND [COLUMN_NAME] = ?", }, { "SELECT 'abc```test```''', `a` FROM b", "SELECT 'abc```test```''', [a] FROM b", }, { "UPDATE table SET `a` = ~ `a`, `b`='abc`'", "UPDATE table SET [a] = ~ [a], [b]='abc`'", }, } for _, kase := range kases { t.Run(kase.source, func(t *testing.T) { assert.EqualValues(t, kase.expected, q.Replace(kase.source)) }) } } <file_sep>/integrations/session_iterate_test.go // Copyright 2017 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package integrations import ( "testing" "github.com/stretchr/testify/assert" ) func TestIterate(t *testing.T) { assert.NoError(t, PrepareEngine()) type UserIterate struct { Id int64 IsMan bool } assert.NoError(t, testEngine.Sync2(new(UserIterate))) cnt, err := testEngine.Insert(&UserIterate{ IsMan: true, }) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) cnt = 0 err = testEngine.Iterate(new(UserIterate), func(i int, bean interface{}) error { user := bean.(*UserIterate) assert.EqualValues(t, 1, user.Id) assert.EqualValues(t, true, user.IsMan) cnt++ return nil }) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) } func TestBufferIterate(t *testing.T) { assert.NoError(t, PrepareEngine()) type UserBufferIterate struct { Id int64 IsMan bool } assert.NoError(t, testEngine.Sync2(new(UserBufferIterate))) var size = 20 for i := 0; i < size; i++ { cnt, err := testEngine.Insert(&UserBufferIterate{ IsMan: true, }) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) } var cnt = 0 err := testEngine.BufferSize(9).Iterate(new(UserBufferIterate), func(i int, bean interface{}) error { user := bean.(*UserBufferIterate) assert.EqualValues(t, cnt+1, user.Id) assert.EqualValues(t, true, user.IsMan) cnt++ return nil }) assert.NoError(t, err) assert.EqualValues(t, size, cnt) cnt = 0 err = testEngine.Limit(20).BufferSize(9).Iterate(new(UserBufferIterate), func(i int, bean interface{}) error { user := bean.(*UserBufferIterate) assert.EqualValues(t, cnt+1, user.Id) assert.EqualValues(t, true, user.IsMan) cnt++ return nil }) assert.NoError(t, err) assert.EqualValues(t, size, cnt) cnt = 0 err = testEngine.Limit(7).BufferSize(9).Iterate(new(UserBufferIterate), func(i int, bean interface{}) error { user := bean.(*UserBufferIterate) assert.EqualValues(t, cnt+1, user.Id) assert.EqualValues(t, true, user.IsMan) cnt++ return nil }) assert.NoError(t, err) assert.EqualValues(t, 7, cnt) cnt = 0 err = testEngine.Where("id <= 10").BufferSize(2).Iterate(new(UserBufferIterate), func(i int, bean interface{}) error { user := bean.(*UserBufferIterate) assert.EqualValues(t, cnt+1, user.Id) assert.EqualValues(t, true, user.IsMan) cnt++ return nil }) assert.NoError(t, err) assert.EqualValues(t, 10, cnt) } <file_sep>/integrations/session_test.go // Copyright 2017 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package integrations import ( "database/sql" "testing" "github.com/stretchr/testify/assert" ) func TestClose(t *testing.T) { assert.NoError(t, PrepareEngine()) sess1 := testEngine.NewSession() sess1.Close() assert.True(t, sess1.IsClosed()) sess2 := testEngine.Where("a = ?", 1) sess2.Close() assert.True(t, sess2.IsClosed()) } func TestNullFloatStruct(t *testing.T) { type MyNullFloat64 sql.NullFloat64 type MyNullFloatStruct struct { Uuid string Amount MyNullFloat64 } assert.NoError(t, PrepareEngine()) assert.NoError(t, testEngine.Sync2(new(MyNullFloatStruct))) _, err := testEngine.Insert(&MyNullFloatStruct{ Uuid: "111111", Amount: MyNullFloat64(sql.NullFloat64{ Float64: 0.1111, Valid: true, }), }) assert.NoError(t, err) } func TestMustLogSQL(t *testing.T) { assert.NoError(t, PrepareEngine()) testEngine.ShowSQL(false) defer testEngine.ShowSQL(true) assertSync(t, new(Userinfo)) _, err := testEngine.Table("userinfo").MustLogSQL(true).Get(new(Userinfo)) assert.NoError(t, err) } func TestEnableSessionId(t *testing.T) { assert.NoError(t, PrepareEngine()) testEngine.EnableSessionID(true) assertSync(t, new(Userinfo)) _, err := testEngine.Table("userinfo").MustLogSQL(true).Get(new(Userinfo)) assert.NoError(t, err) } <file_sep>/integrations/types_null_test.go // Copyright 2017 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package integrations import ( "database/sql" "database/sql/driver" "errors" "fmt" "strconv" "strings" "testing" "github.com/stretchr/testify/assert" ) type NullType struct { Id int `xorm:"pk autoincr"` Name sql.NullString Age sql.NullInt64 Height sql.NullFloat64 IsMan sql.NullBool `xorm:"null"` Nil driver.Valuer CustomStruct CustomStruct `xorm:"varchar(64) null"` } type CustomStruct struct { Year int Month int Day int } func (CustomStruct) String() string { return "CustomStruct" } func (m *CustomStruct) Scan(value interface{}) error { if value == nil { m.Year, m.Month, m.Day = 0, 0, 0 return nil } if s, ok := value.([]byte); ok { seps := strings.Split(string(s), "/") m.Year, _ = strconv.Atoi(seps[0]) m.Month, _ = strconv.Atoi(seps[1]) m.Day, _ = strconv.Atoi(seps[2]) return nil } return errors.New("scan data not fit []byte") } func (m CustomStruct) Value() (driver.Value, error) { return fmt.Sprintf("%d/%d/%d", m.Year, m.Month, m.Day), nil } func TestCreateNullStructTable(t *testing.T) { assert.NoError(t, PrepareEngine()) err := testEngine.CreateTables(new(NullType)) assert.NoError(t, err) } func TestDropNullStructTable(t *testing.T) { assert.NoError(t, PrepareEngine()) err := testEngine.DropTables(new(NullType)) assert.NoError(t, err) } func TestNullStructInsert(t *testing.T) { assert.NoError(t, PrepareEngine()) assertSync(t, new(NullType)) item1 := new(NullType) _, err := testEngine.Insert(item1) assert.NoError(t, err) assert.EqualValues(t, 1, item1.Id) item := NullType{ Name: sql.NullString{String: "haolei", Valid: true}, Age: sql.NullInt64{Int64: 34, Valid: true}, Height: sql.NullFloat64{Float64: 1.72, Valid: true}, IsMan: sql.NullBool{Bool: true, Valid: true}, Nil: nil, } _, err = testEngine.Insert(&item) assert.NoError(t, err) assert.EqualValues(t, 2, item.Id) items := []NullType{} for i := 0; i < 5; i++ { item := NullType{ Name: sql.NullString{String: "haolei_" + fmt.Sprint(i+1), Valid: true}, Age: sql.NullInt64{Int64: 30 + int64(i), Valid: true}, Height: sql.NullFloat64{Float64: 1.5 + 1.1*float64(i), Valid: true}, IsMan: sql.NullBool{Bool: true, Valid: true}, CustomStruct: CustomStruct{i, i + 1, i + 2}, Nil: nil, } items = append(items, item) } _, err = testEngine.Insert(&items) assert.NoError(t, err) items = make([]NullType, 0, 7) err = testEngine.Find(&items) assert.NoError(t, err) assert.EqualValues(t, 7, len(items)) } func TestNullStructUpdate(t *testing.T) { assert.NoError(t, PrepareEngine()) assertSync(t, new(NullType)) _, err := testEngine.Insert([]NullType{ { Name: sql.NullString{ String: "name1", Valid: true, }, }, { Name: sql.NullString{ String: "name2", Valid: true, }, }, { Name: sql.NullString{ String: "name3", Valid: true, }, }, { Name: sql.NullString{ String: "name4", Valid: true, }, }, }) assert.NoError(t, err) if true { // 测试可插入NULL item := new(NullType) item.Age = sql.NullInt64{Int64: 23, Valid: true} item.Height = sql.NullFloat64{Float64: 0, Valid: false} // update to NULL affected, err := testEngine.ID(2).Cols("age", "height", "is_man").Update(item) assert.NoError(t, err) assert.EqualValues(t, 1, affected) } if true { // 测试In update item := new(NullType) item.Age = sql.NullInt64{Int64: 23, Valid: true} affected, err := testEngine.In("id", 3, 4).Cols("age", "height", "is_man").Update(item) assert.NoError(t, err) assert.EqualValues(t, 2, affected) } if true { // 测试where item := new(NullType) item.Name = sql.NullString{String: "nullname", Valid: true} item.IsMan = sql.NullBool{Bool: true, Valid: true} item.Age = sql.NullInt64{Int64: 34, Valid: true} _, err := testEngine.Where("age > ?", 34).Update(item) assert.NoError(t, err) } if true { // 修改全部时,插入空值 item := &NullType{ Name: sql.NullString{String: "winxxp", Valid: true}, Age: sql.NullInt64{Int64: 30, Valid: true}, Height: sql.NullFloat64{Float64: 1.72, Valid: true}, // IsMan: sql.NullBool{true, true}, } _, err := testEngine.AllCols().ID(6).Update(item) assert.NoError(t, err) } } func TestNullStructFind(t *testing.T) { assert.NoError(t, PrepareEngine()) assertSync(t, new(NullType)) _, err := testEngine.Insert([]NullType{ { Name: sql.NullString{ String: "name1", Valid: false, }, }, { Name: sql.NullString{ String: "name2", Valid: true, }, }, { Name: sql.NullString{ String: "name3", Valid: true, }, }, { Name: sql.NullString{ String: "name4", Valid: true, }, }, }) assert.NoError(t, err) if true { item := new(NullType) has, err := testEngine.ID(1).Get(item) assert.NoError(t, err) assert.True(t, has) assert.EqualValues(t, item.Id, 1) assert.False(t, item.Name.Valid) assert.False(t, item.Age.Valid) assert.False(t, item.Height.Valid) assert.False(t, item.IsMan.Valid) } if true { item := new(NullType) item.Id = 2 has, err := testEngine.Get(item) assert.NoError(t, err) assert.True(t, has) } if true { item := make([]NullType, 0) err := testEngine.ID(2).Find(&item) assert.NoError(t, err) } if true { item := make([]NullType, 0) err := testEngine.Asc("age").Find(&item) assert.NoError(t, err) } } func TestNullStructIterate(t *testing.T) { assert.NoError(t, PrepareEngine()) assertSync(t, new(NullType)) if true { err := testEngine.Where("age IS NOT NULL").OrderBy("age").Iterate(new(NullType), func(i int, bean interface{}) error { nultype := bean.(*NullType) fmt.Println(i, nultype) return nil }) assert.NoError(t, err) } } func TestNullStructCount(t *testing.T) { assert.NoError(t, PrepareEngine()) assertSync(t, new(NullType)) if true { item := new(NullType) _, err := testEngine.Where("age IS NOT NULL").Count(item) assert.NoError(t, err) } } func TestNullStructRows(t *testing.T) { assert.NoError(t, PrepareEngine()) assertSync(t, new(NullType)) item := new(NullType) rows, err := testEngine.Where("id > ?", 1).Rows(item) assert.NoError(t, err) defer rows.Close() for rows.Next() { err = rows.Scan(item) assert.NoError(t, err) } } func TestNullStructDelete(t *testing.T) { assert.NoError(t, PrepareEngine()) assertSync(t, new(NullType)) item := new(NullType) _, err := testEngine.ID(1).Delete(item) assert.NoError(t, err) _, err = testEngine.Where("id > ?", 1).Delete(item) assert.NoError(t, err) } <file_sep>/contexts/hook_test.go package contexts import ( "context" "errors" "testing" ) type testHook struct { before func(c *ContextHook) (context.Context, error) after func(c *ContextHook) error } func (h *testHook) BeforeProcess(c *ContextHook) (context.Context, error) { if h.before != nil { return h.before(c) } return c.Ctx, nil } func (h *testHook) AfterProcess(c *ContextHook) error { if h.after != nil { return h.after(c) } return c.Err } var _ Hook = &testHook{} func TestBeforeProcess(t *testing.T) { expectErr := errors.New("before error") tests := []struct { msg string hooks []Hook expect error }{ { msg: "first hook return err", hooks: []Hook{ &testHook{ before: func(c *ContextHook) (ctx context.Context, err error) { return c.Ctx, expectErr }, }, &testHook{ before: func(c *ContextHook) (ctx context.Context, err error) { return c.Ctx, nil }, }, }, expect: expectErr, }, { msg: "second hook return err", hooks: []Hook{ &testHook{ before: func(c *ContextHook) (ctx context.Context, err error) { return c.Ctx, nil }, }, &testHook{ before: func(c *ContextHook) (ctx context.Context, err error) { return c.Ctx, expectErr }, }, }, expect: expectErr, }, } for _, tt := range tests { t.Run(tt.msg, func(t *testing.T) { hooks := Hooks{} hooks.AddHook(tt.hooks...) _, err := hooks.BeforeProcess(&ContextHook{ Ctx: context.Background(), }) if err != tt.expect { t.Errorf("got %v, expect %v", err, tt.expect) } }) } } func TestAfterProcess(t *testing.T) { expectErr := errors.New("expect err") tests := []struct { msg string ctx *ContextHook hooks []Hook expect error }{ { msg: "context has err", ctx: &ContextHook{ Ctx: context.Background(), Err: expectErr, }, hooks: []Hook{ &testHook{ after: func(c *ContextHook) error { return errors.New("hook err") }, }, }, expect: expectErr, }, { msg: "last hook has err", ctx: &ContextHook{ Ctx: context.Background(), Err: nil, }, hooks: []Hook{ &testHook{ after: func(c *ContextHook) error { return nil }, }, &testHook{ after: func(c *ContextHook) error { return expectErr }, }, }, expect: expectErr, }, } for _, tt := range tests { t.Run(tt.msg, func(t *testing.T) { hooks := Hooks{} hooks.AddHook(tt.hooks...) err := hooks.AfterProcess(tt.ctx) if err != tt.expect { t.Errorf("got %v, expect %v", err, tt.expect) } }) } } <file_sep>/integrations/engine_group_test.go // Copyright 2020 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package integrations import ( "testing" "github.com/xormsharp/xorm" "github.com/xormsharp/xorm/log" "github.com/xormsharp/xorm/schemas" "github.com/stretchr/testify/assert" ) func TestEngineGroup(t *testing.T) { assert.NoError(t, PrepareEngine()) master := testEngine.(*xorm.Engine) if master.Dialect().URI().DBType == schemas.SQLITE { t.Skip() return } eg, err := xorm.NewEngineGroup(master, []*xorm.Engine{master}) assert.NoError(t, err) eg.SetMaxIdleConns(10) eg.SetMaxOpenConns(100) eg.SetTableMapper(master.GetTableMapper()) eg.SetColumnMapper(master.GetColumnMapper()) eg.SetLogLevel(log.LOG_INFO) eg.ShowSQL(true) } <file_sep>/names/table_name_test.go // Copyright 2020 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package names import ( "fmt" "reflect" "testing" "time" "github.com/stretchr/testify/assert" ) type Userinfo struct { Uid int64 `xorm:"id pk not null autoincr"` Username string `xorm:"unique"` Departname string Alias string `xorm:"-"` Created time.Time Detail Userdetail `xorm:"detail_id int(11)"` Height float64 Avatar []byte IsMan bool } type Userdetail struct { Id int64 Intro string `xorm:"text"` Profile string `xorm:"varchar(2000)"` } type MyGetCustomTableImpletation struct { Id int64 `json:"id"` Name string `json:"name"` } const getCustomTableName = "GetCustomTableInterface" func (MyGetCustomTableImpletation) TableName() string { return getCustomTableName } type TestTableNameStruct struct{} const getTestTableName = "my_test_table_name_struct" func (t *TestTableNameStruct) TableName() string { return getTestTableName } func TestGetTableName(t *testing.T) { var kases = []struct { mapper Mapper v reflect.Value expectedTableName string }{ { SnakeMapper{}, reflect.ValueOf(new(Userinfo)), "userinfo", }, { SnakeMapper{}, reflect.ValueOf(Userinfo{}), "userinfo", }, { SameMapper{}, reflect.ValueOf(new(Userinfo)), "Userinfo", }, { SameMapper{}, reflect.ValueOf(Userinfo{}), "Userinfo", }, { SnakeMapper{}, reflect.ValueOf(new(MyGetCustomTableImpletation)), getCustomTableName, }, { SnakeMapper{}, reflect.ValueOf(MyGetCustomTableImpletation{}), getCustomTableName, }, { SnakeMapper{}, reflect.ValueOf(new(TestTableNameStruct)), new(TestTableNameStruct).TableName(), }, { SnakeMapper{}, reflect.ValueOf(new(TestTableNameStruct)), getTestTableName, }, { SnakeMapper{}, reflect.ValueOf(TestTableNameStruct{}), getTestTableName, }, } for _, kase := range kases { assert.EqualValues(t, kase.expectedTableName, GetTableName(kase.mapper, kase.v)) } } type OAuth2Application struct { } // TableName sets the table name to `oauth2_application` func (app *OAuth2Application) TableName() string { return "oauth2_application" } func TestGonicMapperCustomTable(t *testing.T) { assert.EqualValues(t, "oauth2_application", GetTableName(LintGonicMapper, reflect.ValueOf(new(OAuth2Application)))) assert.EqualValues(t, "oauth2_application", GetTableName(LintGonicMapper, reflect.ValueOf(OAuth2Application{}))) } type MyTable struct { Idx int } func (t *MyTable) TableName() string { return fmt.Sprintf("mytable_%d", t.Idx) } func TestMyTable(t *testing.T) { var table MyTable for i := 0; i < 10; i++ { table.Idx = i assert.EqualValues(t, fmt.Sprintf("mytable_%d", i), GetTableName(SameMapper{}, reflect.ValueOf(&table))) } } <file_sep>/integrations/session_exist_test.go // Copyright 2017 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package integrations import ( "context" "testing" "time" "github.com/stretchr/testify/assert" ) func TestExistStruct(t *testing.T) { assert.NoError(t, PrepareEngine()) type RecordExist struct { Id int64 Name string } assertSync(t, new(RecordExist)) has, err := testEngine.Exist(new(RecordExist)) assert.NoError(t, err) assert.False(t, has) cnt, err := testEngine.Insert(&RecordExist{ Name: "test1", }) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) has, err = testEngine.Exist(new(RecordExist)) assert.NoError(t, err) assert.True(t, has) has, err = testEngine.Exist(&RecordExist{ Name: "test1", }) assert.NoError(t, err) assert.True(t, has) has, err = testEngine.Exist(&RecordExist{ Name: "test2", }) assert.NoError(t, err) assert.False(t, has) has, err = testEngine.Where("name = ?", "test1").Exist(&RecordExist{}) assert.NoError(t, err) assert.True(t, has) has, err = testEngine.Where("name = ?", "test2").Exist(&RecordExist{}) assert.NoError(t, err) assert.False(t, has) has, err = testEngine.SQL("select * from "+testEngine.TableName("record_exist", true)+" where name = ?", "test1").Exist() assert.NoError(t, err) assert.True(t, has) has, err = testEngine.SQL("select * from "+testEngine.TableName("record_exist", true)+" where name = ?", "test2").Exist() assert.NoError(t, err) assert.False(t, has) has, err = testEngine.Table("record_exist").Exist() assert.NoError(t, err) assert.True(t, has) has, err = testEngine.Table("record_exist").Where("name = ?", "test1").Exist() assert.NoError(t, err) assert.True(t, has) has, err = testEngine.Table("record_exist").Where("name = ?", "test2").Exist() assert.NoError(t, err) assert.False(t, has) } func TestExistStructForJoin(t *testing.T) { assert.NoError(t, PrepareEngine()) type Number struct { Id int64 Lid int64 } type OrderList struct { Id int64 Eid int64 } type Player struct { Id int64 Name string } assert.NoError(t, testEngine.Sync2(new(Number), new(OrderList), new(Player))) var ply Player cnt, err := testEngine.Insert(&ply) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) var orderlist = OrderList{ Eid: ply.Id, } cnt, err = testEngine.Insert(&orderlist) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) var um = Number{ Lid: orderlist.Id, } cnt, err = testEngine.Insert(&um) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) session := testEngine.NewSession() defer session.Close() session.Table("number"). Join("INNER", "order_list", "order_list.id = number.lid"). Join("LEFT", "player", "player.id = order_list.eid"). Where("number.lid = ?", 1) has, err := session.Exist() assert.NoError(t, err) assert.True(t, has) session.Table("number"). Join("INNER", "order_list", "order_list.id = number.lid"). Join("LEFT", "player", "player.id = order_list.eid"). Where("number.lid = ?", 2) has, err = session.Exist() assert.NoError(t, err) assert.False(t, has) session.Table("number"). Select("order_list.id"). Join("INNER", "order_list", "order_list.id = number.lid"). Join("LEFT", "player", "player.id = order_list.eid"). Where("order_list.id = ?", 1) has, err = session.Exist() assert.NoError(t, err) assert.True(t, has) session.Table("number"). Select("player.id"). Join("INNER", "order_list", "order_list.id = number.lid"). Join("LEFT", "player", "player.id = order_list.eid"). Where("player.id = ?", 2) has, err = session.Exist() assert.NoError(t, err) assert.False(t, has) session.Table("number"). Select("player.id"). Join("INNER", "order_list", "order_list.id = number.lid"). Join("LEFT", "player", "player.id = order_list.eid") has, err = session.Exist() assert.NoError(t, err) assert.True(t, has) err = session.DropTable("order_list") assert.NoError(t, err) exist, err := session.IsTableExist("order_list") assert.NoError(t, err) assert.False(t, exist) session.Table("number"). Select("player.id"). Join("INNER", "order_list", "order_list.id = number.lid"). Join("LEFT", "player", "player.id = order_list.eid") has, err = session.Exist() assert.Error(t, err) assert.False(t, has) session.Table("number"). Select("player.id"). Join("LEFT", "player", "player.id = number.lid") has, err = session.Exist() assert.NoError(t, err) assert.True(t, has) } func TestExistContext(t *testing.T) { type ContextQueryStruct struct { Id int64 Name string } assert.NoError(t, PrepareEngine()) assertSync(t, new(ContextQueryStruct)) _, err := testEngine.Insert(&ContextQueryStruct{Name: "1"}) assert.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond) defer cancel() time.Sleep(time.Nanosecond) has, err := testEngine.Context(ctx).Exist(&ContextQueryStruct{Name: "1"}) assert.Error(t, err) assert.Contains(t, err.Error(), "context deadline exceeded") assert.False(t, has) } <file_sep>/caches/leveldb_test.go // Copyright 2020 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package caches import ( "testing" "github.com/stretchr/testify/assert" ) func TestLevelDBStore(t *testing.T) { store, err := NewLevelDBStore("./level.db") assert.NoError(t, err) var kvs = map[string]interface{}{ "a": "b", } for k, v := range kvs { assert.NoError(t, store.Put(k, v)) } for k, v := range kvs { val, err := store.Get(k) assert.NoError(t, err) assert.EqualValues(t, v, val) } for k := range kvs { err := store.Del(k) assert.NoError(t, err) } for k := range kvs { _, err := store.Get(k) assert.EqualValues(t, ErrNotExist, err) } } <file_sep>/go.mod module github.com/xormsharp/xorm go 1.11 require ( github.com/denisenkom/go-mssqldb v0.0.0-20200428022330-06a60b6afbbc github.com/go-sql-driver/mysql v1.5.0 github.com/golang/protobuf v1.3.1 // indirect github.com/lib/pq v1.7.0 github.com/mattn/go-sqlite3 v1.14.0 github.com/stretchr/testify v1.4.0 github.com/syndtr/goleveldb v1.0.0 github.com/xormsharp/builder v0.3.7 github.com/ziutek/mymysql v1.5.4 golang.org/x/text v0.3.2 // indirect ) <file_sep>/dialects/postgres_test.go package dialects import ( "reflect" "testing" "github.com/stretchr/testify/assert" ) func TestParsePostgres(t *testing.T) { tests := []struct { in string expected string valid bool }{ {"postgres://auser:password@localhost:5432/db?sslmode=disable", "db", true}, {"postgresql://auser:password@localhost:5432/db?sslmode=disable", "db", true}, {"postg://auser:password@localhost:5432/db?sslmode=disable", "db", false}, //{"postgres://auser:pass with space@localhost:5432/db?sslmode=disable", "db", true}, //{"postgres:// auser : password@localhost:5432/db?sslmode=disable", "db", true}, {"postgres://%20auser%20:pass%20with%20space@localhost:5432/db?sslmode=disable", "db", true}, //{"postgres://auser:パスワード@localhost:5432/データベース?sslmode=disable", "データベース", true}, {"dbname=db sslmode=disable", "db", true}, {"user=auser password=password dbname=db sslmode=disable", "db", true}, {"", "db", false}, {"dbname=db =disable", "db", false}, } driver := QueryDriver("postgres") for _, test := range tests { uri, err := driver.Parse("postgres", test.in) if err != nil && test.valid { t.Errorf("%q got unexpected error: %s", test.in, err) } else if err == nil && !reflect.DeepEqual(test.expected, uri.DBName) { t.Errorf("%q got: %#v want: %#v", test.in, uri.DBName, test.expected) } } } func TestParsePgx(t *testing.T) { tests := []struct { in string expected string valid bool }{ {"postgres://auser:password@localhost:5432/db?sslmode=disable", "db", true}, {"postgresql://auser:password@localhost:5432/db?sslmode=disable", "db", true}, {"postg://auser:password@localhost:5432/db?sslmode=disable", "db", false}, //{"postgres://auser:pass with space@localhost:5432/db?sslmode=disable", "db", true}, //{"postgres:// auser : password@localhost:5432/db?sslmode=disable", "db", true}, {"postgres://%20auser%20:pass%20with%20space@localhost:5432/db?sslmode=disable", "db", true}, //{"postgres://auser:パスワード@localhost:5432/データベース?sslmode=disable", "データベース", true}, {"dbname=db sslmode=disable", "db", true}, {"user=auser password=password dbname=db sslmode=disable", "db", true}, {"", "db", false}, {"dbname=db =disable", "db", false}, } driver := QueryDriver("pgx") for _, test := range tests { uri, err := driver.Parse("pgx", test.in) if err != nil && test.valid { t.Errorf("%q got unexpected error: %s", test.in, err) } else if err == nil && !reflect.DeepEqual(test.expected, uri.DBName) { t.Errorf("%q got: %#v want: %#v", test.in, uri.DBName, test.expected) } // Register DriverConfig uri, err = driver.Parse("pgx", test.in) if err != nil && test.valid { t.Errorf("%q got unexpected error: %s", test.in, err) } else if err == nil && !reflect.DeepEqual(test.expected, uri.DBName) { t.Errorf("%q got: %#v want: %#v", test.in, uri.DBName, test.expected) } } } func TestGetIndexColName(t *testing.T) { t.Run("Index", func(t *testing.T) { s := "CREATE INDEX test2_mm_idx ON test2 (major);" colNames := getIndexColName(s) assert.Equal(t, []string{"major"}, colNames) }) t.Run("Multicolumn indexes", func(t *testing.T) { s := "CREATE INDEX test2_mm_idx ON test2 (major, minor);" colNames := getIndexColName(s) assert.Equal(t, []string{"major", "minor"}, colNames) }) t.Run("Indexes and ORDER BY", func(t *testing.T) { s := "CREATE INDEX test2_mm_idx ON test2 (major NULLS FIRST, minor DESC NULLS LAST);" colNames := getIndexColName(s) assert.Equal(t, []string{"major", "minor"}, colNames) }) t.Run("Combining Multiple Indexes", func(t *testing.T) { s := "CREATE INDEX test2_mm_cm_idx ON public.test2 USING btree (major, minor) WHERE ((major <> 5) AND (minor <> 6))" colNames := getIndexColName(s) assert.Equal(t, []string{"major", "minor"}, colNames) }) t.Run("unique", func(t *testing.T) { s := "CREATE UNIQUE INDEX test2_mm_uidx ON test2 (major);" colNames := getIndexColName(s) assert.Equal(t, []string{"major"}, colNames) }) t.Run("Indexes on Expressions", func(t *testing.T) {}) } <file_sep>/dialects/filter_test.go package dialects import ( "testing" "github.com/stretchr/testify/assert" ) func TestSeqFilter(t *testing.T) { var kases = map[string]string{ "SELECT * FROM TABLE1 WHERE a=? AND b=?": "SELECT * FROM TABLE1 WHERE a=$1 AND b=$2", "SELECT 1, '???', '2006-01-02 15:04:05' FROM TABLE1 WHERE a=? AND b=?": "SELECT 1, '???', '2006-01-02 15:04:05' FROM TABLE1 WHERE a=$1 AND b=$2", "select '1''?' from issue": "select '1''?' from issue", "select '1\\??' from issue": "select '1\\??' from issue", "select '1\\\\',? from issue": "select '1\\\\',$1 from issue", "select '1\\''?',? from issue": "select '1\\''?',$1 from issue", } for sql, result := range kases { assert.EqualValues(t, result, convertQuestionMark(sql, "$", 1)) } } <file_sep>/names/mapper_test.go // Copyright 2019 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package names import ( "strings" "testing" ) func TestGonicMapperFromObj(t *testing.T) { testCases := map[string]string{ "HTTPLib": "http_lib", "id": "id", "ID": "id", "IDa": "i_da", "iDa": "i_da", "IDAa": "id_aa", "aID": "a_id", "aaID": "aa_id", "aaaID": "aaa_id", "MyREalFunkYLONgNAME": "my_r_eal_funk_ylo_ng_name", } for in, expected := range testCases { out := gonicCasedName(in) if out != expected { t.Errorf("Given %s, expected %s but got %s", in, expected, out) } } } func TestGonicMapperToObj(t *testing.T) { testCases := map[string]string{ "http_lib": "HTTPLib", "id": "ID", "ida": "Ida", "id_aa": "IDAa", "aa_id": "AaID", "my_r_eal_funk_ylo_ng_name": "MyREalFunkYloNgName", } for in, expected := range testCases { out := LintGonicMapper.Table2Obj(in) if out != expected { t.Errorf("Given %s, expected %s but got %s", in, expected, out) } } } func BenchmarkSnakeCasedName(b *testing.B) { b.ReportAllocs() b.ResetTimer() s := strings.Repeat("FooBar", 32) for i := 0; i < b.N; i++ { _ = snakeCasedName(s) } } func BenchmarkTitleCasedName(b *testing.B) { b.ReportAllocs() b.ResetTimer() s := strings.Repeat("foo_bar", 32) for i := 0; i < b.N; i++ { _ = titleCasedName(s) } } <file_sep>/integrations/session_cols_test.go // Copyright 2017 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package integrations import ( "testing" "github.com/stretchr/testify/assert" "github.com/xormsharp/builder" "github.com/xormsharp/xorm/schemas" ) func TestSetExpr(t *testing.T) { assert.NoError(t, PrepareEngine()) type UserExprIssue struct { Id int64 Title string } assert.NoError(t, testEngine.Sync2(new(UserExprIssue))) var issue = UserExprIssue{ Title: "my issue", } cnt, err := testEngine.Insert(&issue) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) assert.EqualValues(t, 1, issue.Id) type UserExpr struct { Id int64 IssueId int64 `xorm:"index"` Show bool } assert.NoError(t, testEngine.Sync2(new(UserExpr))) cnt, err = testEngine.Insert(&UserExpr{ Show: true, }) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) var not = "NOT" if testEngine.Dialect().URI().DBType == schemas.MSSQL { not = "~" } cnt, err = testEngine.SetExpr("show", not+" `show`").ID(1).Update(new(UserExpr)) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) tableName := testEngine.TableName(new(UserExprIssue), true) cnt, err = testEngine.SetExpr("issue_id", builder.Select("id"). From(tableName). Where(builder.Eq{"id": issue.Id})). ID(1). Update(new(UserExpr)) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) } func TestCols(t *testing.T) { assert.NoError(t, PrepareEngine()) type ColsTable struct { Id int64 Col1 string Col2 string } assertSync(t, new(ColsTable)) _, err := testEngine.Insert(&ColsTable{ Col1: "1", Col2: "2", }) assert.NoError(t, err) sess := testEngine.ID(1) _, err = sess.Cols("col1").Cols("col2").Update(&ColsTable{ Col1: "", Col2: "", }) assert.NoError(t, err) var tb ColsTable has, err := testEngine.ID(1).Get(&tb) assert.NoError(t, err) assert.True(t, has) assert.EqualValues(t, "", tb.Col1) assert.EqualValues(t, "", tb.Col2) } func TestMustCol(t *testing.T) { assert.NoError(t, PrepareEngine()) type CustomerUpdate struct { Id int64 `form:"id" json:"id"` Username string `form:"username" json:"username" binding:"required"` Email string `form:"email" json:"email"` Sex int `form:"sex" json:"sex"` Name string `form:"name" json:"name" binding:"required"` Telephone string `form:"telephone" json:"telephone"` Type int `form:"type" json:"type" binding:"required"` ParentId int64 `form:"parent_id" json:"parent_id" xorm:"int null"` Remark string `form:"remark" json:"remark"` Status int `form:"status" json:"status" binding:"required"` Age int `form:"age" json:"age"` CreatedAt int64 `xorm:"created" form:"created_at" json:"created_at"` UpdatedAt int64 `xorm:"updated" form:"updated_at" json:"updated_at"` BirthDate int64 `form:"birth_date" json:"birth_date"` Password string `xorm:"varchar(200)" form:"password" json:"password"` } assertSync(t, new(CustomerUpdate)) var customer = CustomerUpdate{ ParentId: 1, } cnt, err := testEngine.Insert(&customer) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) type CustomerOnlyId struct { Id int64 } customer.ParentId = 0 affected, err := testEngine.MustCols("parent_id").Update(&customer, &CustomerOnlyId{Id: customer.Id}) assert.NoError(t, err) assert.EqualValues(t, 1, affected) } <file_sep>/dialects/sqlite3_test.go // Copyright 2019 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package dialects import ( "testing" "github.com/stretchr/testify/assert" ) func TestSplitColStr(t *testing.T) { var kases = []struct { colStr string fields []string }{ { colStr: "`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL", fields: []string{ "`id`", "INTEGER", "PRIMARY", "KEY", "AUTOINCREMENT", "NOT", "NULL", }, }, { colStr: "`created` DATETIME DEFAULT '2006-01-02 15:04:05' NULL", fields: []string{ "`created`", "DATETIME", "DEFAULT", "'2006-01-02 15:04:05'", "NULL", }, }, } for _, kase := range kases { assert.EqualValues(t, kase.fields, splitColStr(kase.colStr)) } } <file_sep>/internal/utils/zero_test.go // Copyright 2020 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package utils import ( "fmt" "reflect" "testing" "time" "github.com/stretchr/testify/assert" ) type MyInt int type ZeroStruct struct{} func TestZero(t *testing.T) { var zeroValues = []interface{}{ int8(0), int16(0), int(0), int32(0), int64(0), uint8(0), uint16(0), uint(0), uint32(0), uint64(0), MyInt(0), reflect.ValueOf(0), nil, time.Time{}, &time.Time{}, nilTime, ZeroStruct{}, &ZeroStruct{}, } for _, v := range zeroValues { t.Run(fmt.Sprintf("%#v", v), func(t *testing.T) { assert.True(t, IsZero(v)) }) } } func TestIsValueZero(t *testing.T) { var zeroReflectValues = []reflect.Value{ reflect.ValueOf(int8(0)), reflect.ValueOf(int16(0)), reflect.ValueOf(int(0)), reflect.ValueOf(int32(0)), reflect.ValueOf(int64(0)), reflect.ValueOf(uint8(0)), reflect.ValueOf(uint16(0)), reflect.ValueOf(uint(0)), reflect.ValueOf(uint32(0)), reflect.ValueOf(uint64(0)), reflect.ValueOf(MyInt(0)), reflect.ValueOf(time.Time{}), reflect.ValueOf(&time.Time{}), reflect.ValueOf(nilTime), reflect.ValueOf(ZeroStruct{}), reflect.ValueOf(&ZeroStruct{}), } for _, v := range zeroReflectValues { t.Run(fmt.Sprintf("%#v", v), func(t *testing.T) { assert.True(t, IsValueZero(v)) }) } } <file_sep>/dialects/oracle_test.go package dialects import ( "reflect" "testing" ) func TestParseOracleConnStr(t *testing.T) { tests := []struct { in string expected string valid bool }{ {"user/pass@tcp(server:1521)/db", "db", true}, {"user/pass@server:1521/db", "db", true}, // test for net service name : https://docs.oracle.com/cd/B13789_01/network.101/b10775/glossary.htm#i998113 {"user/pass@server:1521", "", true}, {"user/pass@", "", false}, {"user/pass", "", false}, {"", "", false}, } driver := QueryDriver("oci8") for _, test := range tests { t.Run(test.in, func(t *testing.T) { driver := driver uri, err := driver.Parse("oci8", test.in) if err != nil && test.valid { t.Errorf("%q got unexpected error: %s", test.in, err) } else if err == nil && !reflect.DeepEqual(test.expected, uri.DBName) { t.Errorf("%q got: %#v want: %#v", test.in, uri.DBName, test.expected) } }) } } <file_sep>/dialects/mssql_test.go // Copyright 2019 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package dialects import ( "reflect" "testing" ) func TestParseMSSQL(t *testing.T) { tests := []struct { in string expected string valid bool }{ {"sqlserver://sa:yourStrong(!)Password@localhost:1433?database=db&connection+timeout=30", "db", true}, {"server=localhost;user id=sa;password=<PASSWORD>(!)Password;database=db", "db", true}, } driver := QueryDriver("mssql") for _, test := range tests { uri, err := driver.Parse("mssql", test.in) if err != nil && test.valid { t.Errorf("%q got unexpected error: %s", test.in, err) } else if err == nil && !reflect.DeepEqual(test.expected, uri.DBName) { t.Errorf("%q got: %#v want: %#v", test.in, uri.DBName, test.expected) } } } <file_sep>/integrations/tags_test.go // Copyright 2017 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package integrations import ( "fmt" "sort" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/xormsharp/xorm/internal/utils" "github.com/xormsharp/xorm/names" "github.com/xormsharp/xorm/schemas" ) type tempUser struct { Id int64 Username string } type tempUser2 struct { TempUser tempUser `xorm:"extends"` Departname string } type tempUser3 struct { Temp *tempUser `xorm:"extends"` Departname string } type tempUser4 struct { TempUser2 tempUser2 `xorm:"extends"` } type Userinfo struct { Uid int64 `xorm:"id pk not null autoincr"` Username string `xorm:"unique"` Departname string Alias string `xorm:"-"` Created time.Time Detail Userdetail `xorm:"detail_id int(11)"` Height float64 Avatar []byte IsMan bool } type Userdetail struct { Id int64 Intro string `xorm:"text"` Profile string `xorm:"varchar(2000)"` } type UserAndDetail struct { Userinfo `xorm:"extends"` Userdetail `xorm:"extends"` } func TestExtends(t *testing.T) { assert.NoError(t, PrepareEngine()) err := testEngine.DropTables(&tempUser2{}) assert.NoError(t, err) err = testEngine.CreateTables(&tempUser2{}) assert.NoError(t, err) tu := &tempUser2{tempUser{0, "extends"}, "dev depart"} _, err = testEngine.Insert(tu) assert.NoError(t, err) tu2 := &tempUser2{} _, err = testEngine.Get(tu2) assert.NoError(t, err) tu3 := &tempUser2{tempUser{0, "extends update"}, ""} _, err = testEngine.ID(tu2.TempUser.Id).Update(tu3) assert.NoError(t, err) err = testEngine.DropTables(&tempUser4{}) assert.NoError(t, err) err = testEngine.CreateTables(&tempUser4{}) assert.NoError(t, err) tu8 := &tempUser4{tempUser2{tempUser{0, "extends"}, "dev depart"}} _, err = testEngine.Insert(tu8) assert.NoError(t, err) tu9 := &tempUser4{} _, err = testEngine.Get(tu9) assert.NoError(t, err) assert.EqualValues(t, tu8.TempUser2.TempUser.Username, tu9.TempUser2.TempUser.Username) assert.EqualValues(t, tu8.TempUser2.Departname, tu9.TempUser2.Departname) tu10 := &tempUser4{tempUser2{tempUser{0, "extends update"}, ""}} _, err = testEngine.ID(tu9.TempUser2.TempUser.Id).Update(tu10) assert.NoError(t, err) err = testEngine.DropTables(&tempUser3{}) assert.NoError(t, err) err = testEngine.CreateTables(&tempUser3{}) assert.NoError(t, err) tu4 := &tempUser3{&tempUser{0, "extends"}, "dev depart"} _, err = testEngine.Insert(tu4) assert.NoError(t, err) tu5 := &tempUser3{} _, err = testEngine.Get(tu5) assert.NoError(t, err) assert.NotNil(t, tu5.Temp) assert.EqualValues(t, 1, tu5.Temp.Id) assert.EqualValues(t, "extends", tu5.Temp.Username) assert.EqualValues(t, "dev depart", tu5.Departname) tu6 := &tempUser3{&tempUser{0, "extends update"}, ""} _, err = testEngine.ID(tu5.Temp.Id).Update(tu6) assert.NoError(t, err) users := make([]tempUser3, 0) err = testEngine.Find(&users) assert.NoError(t, err) assert.EqualValues(t, 1, len(users), "error get data not 1") assertSync(t, new(Userinfo), new(Userdetail)) detail := Userdetail{ Intro: "I'm in China", } _, err = testEngine.Insert(&detail) assert.NoError(t, err) _, err = testEngine.Insert(&Userinfo{ Username: "lunny", Detail: detail, }) assert.NoError(t, err) var info UserAndDetail qt := testEngine.Quote ui := testEngine.TableName(new(Userinfo), true) ud := testEngine.TableName(&detail, true) uiid := testEngine.GetColumnMapper().Obj2Table("Id") udid := "detail_id" sql := fmt.Sprintf("select * from %s, %s where %s.%s = %s.%s", qt(ui), qt(ud), qt(ui), qt(udid), qt(ud), qt(uiid)) b, err := testEngine.SQL(sql).NoCascade().Get(&info) assert.NoError(t, err) assert.True(t, b, "should has lest one record") assert.True(t, info.Userinfo.Uid > 0, "all of the id should has value") assert.True(t, info.Userdetail.Id > 0, "all of the id should has value") var info2 UserAndDetail b, err = testEngine.Table(&Userinfo{}). Join("LEFT", qt(ud), qt(ui)+"."+qt("detail_id")+" = "+qt(ud)+"."+qt(uiid)). NoCascade().Get(&info2) assert.NoError(t, err) assert.True(t, b) assert.True(t, info2.Userinfo.Uid > 0, "all of the id should has value") assert.True(t, info2.Userdetail.Id > 0, "all of the id should has value") var infos2 = make([]UserAndDetail, 0) err = testEngine.Table(&Userinfo{}). Join("LEFT", qt(ud), qt(ui)+"."+qt("detail_id")+" = "+qt(ud)+"."+qt(uiid)). NoCascade(). Find(&infos2) assert.NoError(t, err) } type MessageBase struct { Id int64 `xorm:"int(11) pk autoincr"` TypeId int64 `xorm:"int(11) notnull"` } type Message struct { MessageBase `xorm:"extends"` Title string `xorm:"varchar(100) notnull"` Content string `xorm:"text notnull"` Uid int64 `xorm:"int(11) notnull"` ToUid int64 `xorm:"int(11) notnull"` CreateTime time.Time `xorm:"datetime notnull created"` } type MessageUser struct { Id int64 Name string } type MessageType struct { Id int64 Name string } type MessageExtend3 struct { Message `xorm:"extends"` Sender MessageUser `xorm:"extends"` Receiver MessageUser `xorm:"extends"` Type MessageType `xorm:"extends"` } type MessageExtend4 struct { Message `xorm:"extends"` MessageUser `xorm:"extends"` MessageType `xorm:"extends"` } func TestExtends2(t *testing.T) { assert.NoError(t, PrepareEngine()) err := testEngine.DropTables(&Message{}, &MessageUser{}, &MessageType{}) assert.NoError(t, err) err = testEngine.CreateTables(&Message{}, &MessageUser{}, &MessageType{}) assert.NoError(t, err) var sender = MessageUser{Name: "sender"} var receiver = MessageUser{Name: "receiver"} var msgtype = MessageType{Name: "type"} _, err = testEngine.Insert(&sender, &receiver, &msgtype) assert.NoError(t, err) msg := Message{ MessageBase: MessageBase{ Id: msgtype.Id, }, Title: "test", Content: "test", Uid: sender.Id, ToUid: receiver.Id, } session := testEngine.NewSession() defer session.Close() // MSSQL deny insert identity column excep declare as below if testEngine.Dialect().URI().DBType == schemas.MSSQL { err = session.Begin() assert.NoError(t, err) _, err = session.Exec("SET IDENTITY_INSERT message ON") assert.NoError(t, err) } cnt, err := session.Insert(&msg) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) if testEngine.Dialect().URI().DBType == schemas.MSSQL { err = session.Commit() assert.NoError(t, err) } var mapper = testEngine.GetTableMapper().Obj2Table var quote = testEngine.Quote userTableName := quote(testEngine.TableName(mapper("MessageUser"), true)) typeTableName := quote(testEngine.TableName(mapper("MessageType"), true)) msgTableName := quote(testEngine.TableName(mapper("Message"), true)) list := make([]Message, 0) err = session.Table(msgTableName).Join("LEFT", []string{userTableName, "sender"}, "`sender`.`"+mapper("Id")+"`="+msgTableName+".`"+mapper("Uid")+"`"). Join("LEFT", []string{userTableName, "receiver"}, "`receiver`.`"+mapper("Id")+"`="+msgTableName+".`"+mapper("ToUid")+"`"). Join("LEFT", []string{typeTableName, "type"}, "`type`.`"+mapper("Id")+"`="+msgTableName+".`"+mapper("Id")+"`"). Find(&list) assert.NoError(t, err) assert.EqualValues(t, 1, len(list), fmt.Sprintln("should have 1 message, got", len(list))) assert.EqualValues(t, msg.Id, list[0].Id, fmt.Sprintln("should message equal", list[0], msg)) } func TestExtends3(t *testing.T) { assert.NoError(t, PrepareEngine()) err := testEngine.DropTables(&Message{}, &MessageUser{}, &MessageType{}) assert.NoError(t, err) err = testEngine.CreateTables(&Message{}, &MessageUser{}, &MessageType{}) assert.NoError(t, err) var sender = MessageUser{Name: "sender"} var receiver = MessageUser{Name: "receiver"} var msgtype = MessageType{Name: "type"} _, err = testEngine.Insert(&sender, &receiver, &msgtype) assert.NoError(t, err) msg := Message{ MessageBase: MessageBase{ Id: msgtype.Id, }, Title: "test", Content: "test", Uid: sender.Id, ToUid: receiver.Id, } session := testEngine.NewSession() defer session.Close() // MSSQL deny insert identity column excep declare as below if testEngine.Dialect().URI().DBType == schemas.MSSQL { err = session.Begin() assert.NoError(t, err) _, err = session.Exec("SET IDENTITY_INSERT message ON") assert.NoError(t, err) } _, err = session.Insert(&msg) assert.NoError(t, err) if testEngine.Dialect().URI().DBType == schemas.MSSQL { err = session.Commit() assert.NoError(t, err) } var mapper = testEngine.GetTableMapper().Obj2Table var quote = testEngine.Quote userTableName := quote(testEngine.TableName(mapper("MessageUser"), true)) typeTableName := quote(testEngine.TableName(mapper("MessageType"), true)) msgTableName := quote(testEngine.TableName(mapper("Message"), true)) list := make([]MessageExtend3, 0) err = session.Table(msgTableName).Join("LEFT", []string{userTableName, "sender"}, "`sender`.`"+mapper("Id")+"`="+msgTableName+".`"+mapper("Uid")+"`"). Join("LEFT", []string{userTableName, "receiver"}, "`receiver`.`"+mapper("Id")+"`="+msgTableName+".`"+mapper("ToUid")+"`"). Join("LEFT", []string{typeTableName, "type"}, "`type`.`"+mapper("Id")+"`="+msgTableName+".`"+mapper("Id")+"`"). Find(&list) assert.NoError(t, err) assert.EqualValues(t, 1, len(list)) assert.EqualValues(t, list[0].Message.Id, msg.Id) assert.EqualValues(t, list[0].Sender.Id, sender.Id) assert.EqualValues(t, list[0].Sender.Name, sender.Name) assert.EqualValues(t, list[0].Receiver.Id, receiver.Id) assert.EqualValues(t, list[0].Receiver.Name, receiver.Name) assert.EqualValues(t, list[0].Type.Id, msgtype.Id) assert.EqualValues(t, list[0].Type.Name, msgtype.Name) } func TestExtends4(t *testing.T) { assert.NoError(t, PrepareEngine()) err := testEngine.DropTables(&Message{}, &MessageUser{}, &MessageType{}) assert.NoError(t, err) err = testEngine.CreateTables(&Message{}, &MessageUser{}, &MessageType{}) assert.NoError(t, err) var sender = MessageUser{Name: "sender"} var msgtype = MessageType{Name: "type"} _, err = testEngine.Insert(&sender, &msgtype) assert.NoError(t, err) msg := Message{ MessageBase: MessageBase{ Id: msgtype.Id, }, Title: "test", Content: "test", Uid: sender.Id, } session := testEngine.NewSession() defer session.Close() // MSSQL deny insert identity column excep declare as below if testEngine.Dialect().URI().DBType == schemas.MSSQL { err = session.Begin() assert.NoError(t, err) _, err = session.Exec("SET IDENTITY_INSERT message ON") assert.NoError(t, err) } _, err = session.Insert(&msg) assert.NoError(t, err) if testEngine.Dialect().URI().DBType == schemas.MSSQL { err = session.Commit() assert.NoError(t, err) } var mapper = testEngine.GetTableMapper().Obj2Table var quote = testEngine.Quote userTableName := quote(testEngine.TableName(mapper("MessageUser"), true)) typeTableName := quote(testEngine.TableName(mapper("MessageType"), true)) msgTableName := quote(testEngine.TableName(mapper("Message"), true)) list := make([]MessageExtend4, 0) err = session.Table(msgTableName).Join("LEFT", userTableName, userTableName+".`"+mapper("Id")+"`="+msgTableName+".`"+mapper("Uid")+"`"). Join("LEFT", typeTableName, typeTableName+".`"+mapper("Id")+"`="+msgTableName+".`"+mapper("Id")+"`"). Find(&list) assert.NoError(t, err) assert.EqualValues(t, len(list), 1) assert.EqualValues(t, list[0].Message.Id, msg.Id) assert.EqualValues(t, list[0].MessageUser.Id, sender.Id) assert.EqualValues(t, list[0].MessageUser.Name, sender.Name) assert.EqualValues(t, list[0].MessageType.Id, msgtype.Id) assert.EqualValues(t, list[0].MessageType.Name, msgtype.Name) } type Size struct { ID int64 `xorm:"int(4) 'id' pk autoincr"` Width float32 `json:"width" xorm:"float 'Width'"` Height float32 `json:"height" xorm:"float 'Height'"` } type Book struct { ID int64 `xorm:"int(4) 'id' pk autoincr"` SizeOpen *Size `xorm:"extends('Open')"` SizeClosed *Size `xorm:"extends('Closed')"` Size *Size `xorm:"extends('')"` } func TestExtends5(t *testing.T) { assert.NoError(t, PrepareEngine()) err := testEngine.DropTables(&Book{}, &Size{}) assert.NoError(t, err) err = testEngine.CreateTables(&Size{}, &Book{}) assert.NoError(t, err) var sc = Size{Width: 0.2, Height: 0.4} var so = Size{Width: 0.2, Height: 0.8} var s = Size{Width: 0.15, Height: 1.5} var bk1 = Book{ SizeOpen: &so, SizeClosed: &sc, Size: &s, } var bk2 = Book{ SizeOpen: &so, } var bk3 = Book{ SizeClosed: &sc, Size: &s, } var bk4 = Book{} var bk5 = Book{Size: &s} _, err = testEngine.Insert(&sc, &so, &s, &bk1, &bk2, &bk3, &bk4, &bk5) if err != nil { t.Fatal(err) } var books = map[int64]Book{ bk1.ID: bk1, bk2.ID: bk2, bk3.ID: bk3, bk4.ID: bk4, bk5.ID: bk5, } session := testEngine.NewSession() defer session.Close() var mapper = testEngine.GetTableMapper().Obj2Table var quote = testEngine.Quote bookTableName := quote(testEngine.TableName(mapper("Book"), true)) sizeTableName := quote(testEngine.TableName(mapper("Size"), true)) list := make([]Book, 0) err = session. Select(fmt.Sprintf( "%s.%s, sc.%s AS %s, sc.%s AS %s, s.%s, s.%s", quote(bookTableName), quote("id"), quote("Width"), quote("ClosedWidth"), quote("Height"), quote("ClosedHeight"), quote("Width"), quote("Height"), )). Table(bookTableName). Join( "LEFT", sizeTableName+" AS `sc`", bookTableName+".`SizeClosed`=sc.`id`", ). Join( "LEFT", sizeTableName+" AS `s`", bookTableName+".`Size`=s.`id`", ). Find(&list) assert.NoError(t, err) for _, book := range list { if ok := assert.Equal(t, books[book.ID].SizeClosed.Width, book.SizeClosed.Width); !ok { t.Error("Not bounded size closed") panic("Not bounded size closed") } if ok := assert.Equal(t, books[book.ID].SizeClosed.Height, book.SizeClosed.Height); !ok { t.Error("Not bounded size closed") panic("Not bounded size closed") } if books[book.ID].Size != nil || book.Size != nil { if ok := assert.Equal(t, books[book.ID].Size.Width, book.Size.Width); !ok { t.Error("Not bounded size") panic("Not bounded size") } if ok := assert.Equal(t, books[book.ID].Size.Height, book.Size.Height); !ok { t.Error("Not bounded size") panic("Not bounded size") } } } } func TestCacheTag(t *testing.T) { assert.NoError(t, PrepareEngine()) type CacheDomain struct { Id int64 `xorm:"pk cache"` Name string } assert.NoError(t, testEngine.CreateTables(&CacheDomain{})) assert.True(t, testEngine.GetCacher(testEngine.TableName(&CacheDomain{})) != nil) } func TestNoCacheTag(t *testing.T) { assert.NoError(t, PrepareEngine()) type NoCacheDomain struct { Id int64 `xorm:"pk nocache"` Name string } assert.NoError(t, testEngine.CreateTables(&NoCacheDomain{})) assert.True(t, testEngine.GetCacher(testEngine.TableName(&NoCacheDomain{})) == nil) } type IDGonicMapper struct { ID int64 } func TestGonicMapperID(t *testing.T) { assert.NoError(t, PrepareEngine()) oldMapper := testEngine.GetColumnMapper() testEngine.UnMapType(utils.ReflectValue(new(IDGonicMapper)).Type()) testEngine.SetMapper(names.LintGonicMapper) defer func() { testEngine.UnMapType(utils.ReflectValue(new(IDGonicMapper)).Type()) testEngine.SetMapper(oldMapper) }() err := testEngine.CreateTables(new(IDGonicMapper)) if err != nil { t.Fatal(err) } tables, err := testEngine.DBMetas() if err != nil { t.Fatal(err) } for _, tb := range tables { if tb.Name == "id_gonic_mapper" { if len(tb.PKColumns()) != 1 || tb.PKColumns()[0].Name != "id" { t.Fatal(tb) } return } } t.Fatal("not table id_gonic_mapper") } type IDSameMapper struct { ID int64 } func TestSameMapperID(t *testing.T) { assert.NoError(t, PrepareEngine()) oldMapper := testEngine.GetColumnMapper() testEngine.UnMapType(utils.ReflectValue(new(IDSameMapper)).Type()) testEngine.SetMapper(names.SameMapper{}) defer func() { testEngine.UnMapType(utils.ReflectValue(new(IDSameMapper)).Type()) testEngine.SetMapper(oldMapper) }() err := testEngine.CreateTables(new(IDSameMapper)) if err != nil { t.Fatal(err) } tables, err := testEngine.DBMetas() if err != nil { t.Fatal(err) } for _, tb := range tables { if tb.Name == "IDSameMapper" { if len(tb.PKColumns()) != 1 || tb.PKColumns()[0].Name != "ID" { t.Fatalf("tb %s tb.PKColumns() is %d not 1, tb.PKColumns()[0].Name is %s not ID", tb.Name, len(tb.PKColumns()), tb.PKColumns()[0].Name) } return } } t.Fatal("not table IDSameMapper") } type UserCU struct { Id int64 Name string Created time.Time `xorm:"created"` Updated time.Time `xorm:"updated"` } func TestCreatedAndUpdated(t *testing.T) { assert.NoError(t, PrepareEngine()) u := new(UserCU) err := testEngine.DropTables(u) assert.NoError(t, err) err = testEngine.CreateTables(u) assert.NoError(t, err) u.Name = "sss" cnt, err := testEngine.Insert(u) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) u.Name = "xxx" cnt, err = testEngine.ID(u.Id).Update(u) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) u.Id = 0 u.Created = time.Now().Add(-time.Hour * 24 * 365) u.Updated = u.Created cnt, err = testEngine.NoAutoTime().Insert(u) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) } type StrangeName struct { Id_t int64 `xorm:"pk autoincr"` Name string } func TestStrangeName(t *testing.T) { assert.NoError(t, PrepareEngine()) err := testEngine.DropTables(new(StrangeName)) assert.NoError(t, err) err = testEngine.CreateTables(new(StrangeName)) assert.NoError(t, err) _, err = testEngine.Insert(&StrangeName{Name: "sfsfdsfds"}) assert.NoError(t, err) beans := make([]StrangeName, 0) err = testEngine.Find(&beans) assert.NoError(t, err) } func TestCreatedUpdated(t *testing.T) { assert.NoError(t, PrepareEngine()) type CreatedUpdated struct { Id int64 Name string Value float64 `xorm:"numeric"` Created time.Time `xorm:"created"` Created2 time.Time `xorm:"created"` Updated time.Time `xorm:"updated"` } err := testEngine.Sync2(&CreatedUpdated{}) assert.NoError(t, err) c := &CreatedUpdated{Name: "test"} _, err = testEngine.Insert(c) assert.NoError(t, err) c2 := new(CreatedUpdated) has, err := testEngine.ID(c.Id).Get(c2) assert.NoError(t, err) assert.True(t, has) c2.Value-- _, err = testEngine.ID(c2.Id).Update(c2) assert.NoError(t, err) } func TestCreatedUpdatedInt64(t *testing.T) { assert.NoError(t, PrepareEngine()) type CreatedUpdatedInt64 struct { Id int64 Name string Value float64 `xorm:"numeric"` Created int64 `xorm:"created"` Created2 int64 `xorm:"created"` Updated int64 `xorm:"updated"` } assertSync(t, &CreatedUpdatedInt64{}) c := &CreatedUpdatedInt64{Name: "test"} _, err := testEngine.Insert(c) assert.NoError(t, err) c2 := new(CreatedUpdatedInt64) has, err := testEngine.ID(c.Id).Get(c2) assert.NoError(t, err) assert.True(t, has) c2.Value-- _, err = testEngine.ID(c2.Id).Update(c2) assert.NoError(t, err) } type Lowercase struct { Id int64 Name string ended int64 `xorm:"-"` } func TestLowerCase(t *testing.T) { assert.NoError(t, PrepareEngine()) err := testEngine.Sync2(&Lowercase{}) assert.NoError(t, err) _, err = testEngine.Where("id > 0").Delete(&Lowercase{}) assert.NoError(t, err) _, err = testEngine.Insert(&Lowercase{ended: 1}) assert.NoError(t, err) ls := make([]Lowercase, 0) err = testEngine.Find(&ls) assert.NoError(t, err) assert.EqualValues(t, 1, len(ls)) } func TestAutoIncrTag(t *testing.T) { assert.NoError(t, PrepareEngine()) type TestAutoIncr1 struct { Id int64 } tb, err := testEngine.TableInfo(new(TestAutoIncr1)) assert.NoError(t, err) cols := tb.Columns() assert.EqualValues(t, 1, len(cols)) assert.True(t, cols[0].IsAutoIncrement) assert.True(t, cols[0].IsPrimaryKey) assert.Equal(t, "id", cols[0].Name) type TestAutoIncr2 struct { Id int64 `xorm:"id"` } tb, err = testEngine.TableInfo(new(TestAutoIncr2)) assert.NoError(t, err) cols = tb.Columns() assert.EqualValues(t, 1, len(cols)) assert.False(t, cols[0].IsAutoIncrement) assert.False(t, cols[0].IsPrimaryKey) assert.Equal(t, "id", cols[0].Name) type TestAutoIncr3 struct { Id int64 `xorm:"'ID'"` } tb, err = testEngine.TableInfo(new(TestAutoIncr3)) assert.NoError(t, err) cols = tb.Columns() assert.EqualValues(t, 1, len(cols)) assert.False(t, cols[0].IsAutoIncrement) assert.False(t, cols[0].IsPrimaryKey) assert.Equal(t, "ID", cols[0].Name) type TestAutoIncr4 struct { Id int64 `xorm:"pk"` } tb, err = testEngine.TableInfo(new(TestAutoIncr4)) assert.NoError(t, err) cols = tb.Columns() assert.EqualValues(t, 1, len(cols)) assert.False(t, cols[0].IsAutoIncrement) assert.True(t, cols[0].IsPrimaryKey) assert.Equal(t, "id", cols[0].Name) } func TestTagComment(t *testing.T) { assert.NoError(t, PrepareEngine()) // FIXME: only support mysql if testEngine.Dialect().URI().DBType != schemas.MYSQL { return } type TestComment1 struct { Id int64 `xorm:"comment(主键)"` } assert.NoError(t, testEngine.Sync2(new(TestComment1))) tables, err := testEngine.DBMetas() assert.NoError(t, err) assert.EqualValues(t, 1, len(tables)) assert.EqualValues(t, 1, len(tables[0].Columns())) assert.EqualValues(t, "主键", tables[0].Columns()[0].Comment) assert.NoError(t, testEngine.DropTables(new(TestComment1))) type TestComment2 struct { Id int64 `xorm:"comment('主键')"` } assert.NoError(t, testEngine.Sync2(new(TestComment2))) tables, err = testEngine.DBMetas() assert.NoError(t, err) assert.EqualValues(t, 1, len(tables)) assert.EqualValues(t, 1, len(tables[0].Columns())) assert.EqualValues(t, "主键", tables[0].Columns()[0].Comment) } func TestTagDefault(t *testing.T) { assert.NoError(t, PrepareEngine()) type DefaultStruct struct { Id int64 Name string Age int `xorm:"default(10)"` } assertSync(t, new(DefaultStruct)) tables, err := testEngine.DBMetas() assert.NoError(t, err) var defaultVal string var isDefaultExist bool tableName := testEngine.GetColumnMapper().Obj2Table("DefaultStruct") for _, table := range tables { if table.Name == tableName { col := table.GetColumn("age") assert.NotNil(t, col) defaultVal = col.Default isDefaultExist = !col.DefaultIsEmpty break } } assert.True(t, isDefaultExist) assert.EqualValues(t, "10", defaultVal) cnt, err := testEngine.Omit("age").Insert(&DefaultStruct{ Name: "test", Age: 20, }) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) var s DefaultStruct has, err := testEngine.ID(1).Get(&s) assert.NoError(t, err) assert.True(t, has) assert.EqualValues(t, 10, s.Age) assert.EqualValues(t, "test", s.Name) } func TestTagDefault2(t *testing.T) { assert.NoError(t, PrepareEngine()) type DefaultStruct2 struct { Id int64 Name string } assertSync(t, new(DefaultStruct2)) tables, err := testEngine.DBMetas() assert.NoError(t, err) var defaultVal string var isDefaultExist bool tableName := testEngine.GetColumnMapper().Obj2Table("DefaultStruct2") for _, table := range tables { if table.Name == tableName { col := table.GetColumn("name") assert.NotNil(t, col) defaultVal = col.Default isDefaultExist = !col.DefaultIsEmpty break } } assert.False(t, isDefaultExist, fmt.Sprintf("default value is --%v--", defaultVal)) assert.EqualValues(t, "", defaultVal) } func TestTagDefault3(t *testing.T) { assert.NoError(t, PrepareEngine()) type DefaultStruct3 struct { Id int64 Name string `xorm:"default('myname')"` } assertSync(t, new(DefaultStruct3)) tables, err := testEngine.DBMetas() assert.NoError(t, err) var defaultVal string var isDefaultExist bool tableName := testEngine.GetColumnMapper().Obj2Table("DefaultStruct3") for _, table := range tables { if table.Name == tableName { col := table.GetColumn("name") assert.NotNil(t, col) defaultVal = col.Default isDefaultExist = !col.DefaultIsEmpty break } } assert.True(t, isDefaultExist) assert.EqualValues(t, "'myname'", defaultVal) } func TestTagDefault4(t *testing.T) { assert.NoError(t, PrepareEngine()) type DefaultStruct4 struct { Id int64 Created time.Time `xorm:"default(CURRENT_TIMESTAMP)"` } assertSync(t, new(DefaultStruct4)) tables, err := testEngine.DBMetas() assert.NoError(t, err) var defaultVal string var isDefaultExist bool tableName := testEngine.GetColumnMapper().Obj2Table("DefaultStruct4") for _, table := range tables { if table.Name == tableName { col := table.GetColumn("created") assert.NotNil(t, col) defaultVal = col.Default isDefaultExist = !col.DefaultIsEmpty break } } assert.True(t, isDefaultExist) assert.True(t, "CURRENT_TIMESTAMP" == defaultVal || "current_timestamp()" == defaultVal || // for cockroach "now()" == defaultVal || "getdate" == defaultVal, defaultVal) } func TestTagDefault5(t *testing.T) { assert.NoError(t, PrepareEngine()) type DefaultStruct5 struct { Id int64 Created time.Time `xorm:"default('2006-01-02 15:04:05')"` } assertSync(t, new(DefaultStruct5)) table, err := testEngine.TableInfo(new(DefaultStruct5)) assert.NoError(t, err) createdCol := table.GetColumn("created") assert.NotNil(t, createdCol) assert.EqualValues(t, "'2006-01-02 15:04:05'", createdCol.Default) assert.False(t, createdCol.DefaultIsEmpty) tables, err := testEngine.DBMetas() assert.NoError(t, err) var defaultVal string var isDefaultExist bool tableName := testEngine.GetColumnMapper().Obj2Table("DefaultStruct5") for _, table := range tables { if table.Name == tableName { col := table.GetColumn("created") assert.NotNil(t, col) defaultVal = col.Default isDefaultExist = !col.DefaultIsEmpty break } } assert.True(t, isDefaultExist) assert.EqualValues(t, "'2006-01-02 15:04:05'", defaultVal) } func TestTagDefault6(t *testing.T) { assert.NoError(t, PrepareEngine()) type DefaultStruct6 struct { Id int64 IsMan bool `xorm:"default(true)"` } assertSync(t, new(DefaultStruct6)) tables, err := testEngine.DBMetas() assert.NoError(t, err) var defaultVal string var isDefaultExist bool tableName := testEngine.GetColumnMapper().Obj2Table("DefaultStruct6") for _, table := range tables { if table.Name == tableName { col := table.GetColumn("is_man") assert.NotNil(t, col) defaultVal = col.Default isDefaultExist = !col.DefaultIsEmpty break } } assert.True(t, isDefaultExist) if defaultVal == "1" { defaultVal = "true" } else if defaultVal == "0" { defaultVal = "false" } assert.EqualValues(t, "true", defaultVal) } func TestTagsDirection(t *testing.T) { assert.NoError(t, PrepareEngine()) type OnlyFromDBStruct struct { Id int64 Name string Uuid string `xorm:"<- default '1'"` } assertSync(t, new(OnlyFromDBStruct)) cnt, err := testEngine.Insert(&OnlyFromDBStruct{ Name: "test", Uuid: "2", }) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) var s OnlyFromDBStruct has, err := testEngine.ID(1).Get(&s) assert.NoError(t, err) assert.True(t, has) assert.EqualValues(t, "1", s.Uuid) assert.EqualValues(t, "test", s.Name) cnt, err = testEngine.ID(1).Update(&OnlyFromDBStruct{ Uuid: "3", Name: "test1", }) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) var s3 OnlyFromDBStruct has, err = testEngine.ID(1).Get(&s3) assert.NoError(t, err) assert.True(t, has) assert.EqualValues(t, "1", s3.Uuid) assert.EqualValues(t, "test1", s3.Name) type OnlyToDBStruct struct { Id int64 Name string Uuid string `xorm:"->"` } assertSync(t, new(OnlyToDBStruct)) cnt, err = testEngine.Insert(&OnlyToDBStruct{ Name: "test", Uuid: "2", }) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) var s2 OnlyToDBStruct has, err = testEngine.ID(1).Get(&s2) assert.NoError(t, err) assert.True(t, has) assert.EqualValues(t, "", s2.Uuid) assert.EqualValues(t, "test", s2.Name) } func TestTagTime(t *testing.T) { assert.NoError(t, PrepareEngine()) type TagUTCStruct struct { Id int64 Name string Created time.Time `xorm:"created utc"` } assertSync(t, new(TagUTCStruct)) assert.EqualValues(t, time.Local.String(), testEngine.GetTZLocation().String()) s := TagUTCStruct{ Name: "utc", } cnt, err := testEngine.Insert(&s) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) var u TagUTCStruct has, err := testEngine.ID(1).Get(&u) assert.NoError(t, err) assert.True(t, has) assert.EqualValues(t, s.Created.Format("2006-01-02 15:04:05"), u.Created.Format("2006-01-02 15:04:05")) var tm string has, err = testEngine.Table("tag_u_t_c_struct").Cols("created").Get(&tm) assert.NoError(t, err) assert.True(t, has) assert.EqualValues(t, s.Created.UTC().Format("2006-01-02 15:04:05"), strings.Replace(strings.Replace(tm, "T", " ", -1), "Z", "", -1)) } func TestTagAutoIncr(t *testing.T) { assert.NoError(t, PrepareEngine()) type TagAutoIncr struct { Id int64 Name string } assertSync(t, new(TagAutoIncr)) tables, err := testEngine.DBMetas() assert.NoError(t, err) assert.EqualValues(t, 1, len(tables)) assert.EqualValues(t, tableMapper.Obj2Table("TagAutoIncr"), tables[0].Name) col := tables[0].GetColumn(colMapper.Obj2Table("Id")) assert.NotNil(t, col) assert.True(t, col.IsPrimaryKey) assert.True(t, col.IsAutoIncrement) col2 := tables[0].GetColumn(colMapper.Obj2Table("Name")) assert.NotNil(t, col2) assert.False(t, col2.IsPrimaryKey) assert.False(t, col2.IsAutoIncrement) } func TestTagPrimarykey(t *testing.T) { assert.NoError(t, PrepareEngine()) type TagPrimaryKey struct { Id int64 `xorm:"pk"` Name string `xorm:"VARCHAR(20) pk"` } assertSync(t, new(TagPrimaryKey)) tables, err := testEngine.DBMetas() assert.NoError(t, err) assert.EqualValues(t, 1, len(tables)) assert.EqualValues(t, tableMapper.Obj2Table("TagPrimaryKey"), tables[0].Name) col := tables[0].GetColumn(colMapper.Obj2Table("Id")) assert.NotNil(t, col) assert.True(t, col.IsPrimaryKey) assert.False(t, col.IsAutoIncrement) col2 := tables[0].GetColumn(colMapper.Obj2Table("Name")) assert.NotNil(t, col2) assert.True(t, col2.IsPrimaryKey) assert.False(t, col2.IsAutoIncrement) } type VersionS struct { Id int64 Name string Ver int `xorm:"version"` Created time.Time `xorm:"created"` } func TestVersion1(t *testing.T) { assert.NoError(t, PrepareEngine()) err := testEngine.DropTables(new(VersionS)) assert.NoError(t, err) err = testEngine.CreateTables(new(VersionS)) assert.NoError(t, err) ver := &VersionS{Name: "sfsfdsfds"} _, err = testEngine.Insert(ver) assert.NoError(t, err) assert.EqualValues(t, ver.Ver, 1) newVer := new(VersionS) has, err := testEngine.ID(ver.Id).Get(newVer) assert.NoError(t, err) assert.True(t, has) assert.EqualValues(t, newVer.Ver, 1) newVer.Name = "-------" _, err = testEngine.ID(ver.Id).Update(newVer) assert.NoError(t, err) assert.EqualValues(t, newVer.Ver, 2) newVer = new(VersionS) has, err = testEngine.ID(ver.Id).Get(newVer) assert.NoError(t, err) assert.EqualValues(t, newVer.Ver, 2) } func TestVersion2(t *testing.T) { assert.NoError(t, PrepareEngine()) err := testEngine.DropTables(new(VersionS)) assert.NoError(t, err) err = testEngine.CreateTables(new(VersionS)) assert.NoError(t, err) var vers = []VersionS{ {Name: "sfsfdsfds"}, {Name: "xxxxx"}, } _, err = testEngine.Insert(vers) assert.NoError(t, err) for _, v := range vers { assert.EqualValues(t, v.Ver, 1) } } type VersionUintS struct { Id int64 Name string Ver uint `xorm:"version"` Created time.Time `xorm:"created"` } func TestVersion3(t *testing.T) { assert.NoError(t, PrepareEngine()) err := testEngine.DropTables(new(VersionUintS)) assert.NoError(t, err) err = testEngine.CreateTables(new(VersionUintS)) assert.NoError(t, err) ver := &VersionUintS{Name: "sfsfdsfds"} _, err = testEngine.Insert(ver) assert.NoError(t, err) assert.EqualValues(t, ver.Ver, 1) newVer := new(VersionUintS) has, err := testEngine.ID(ver.Id).Get(newVer) assert.NoError(t, err) assert.True(t, has) assert.EqualValues(t, newVer.Ver, 1) newVer.Name = "-------" _, err = testEngine.ID(ver.Id).Update(newVer) assert.NoError(t, err) assert.EqualValues(t, newVer.Ver, 2) newVer = new(VersionUintS) has, err = testEngine.ID(ver.Id).Get(newVer) assert.NoError(t, err) assert.EqualValues(t, newVer.Ver, 2) } func TestVersion4(t *testing.T) { assert.NoError(t, PrepareEngine()) err := testEngine.DropTables(new(VersionUintS)) assert.NoError(t, err) err = testEngine.CreateTables(new(VersionUintS)) assert.NoError(t, err) var vers = []VersionUintS{ {Name: "sfsfdsfds"}, {Name: "xxxxx"}, } _, err = testEngine.Insert(vers) assert.NoError(t, err) for _, v := range vers { assert.EqualValues(t, v.Ver, 1) } } func TestIndexes(t *testing.T) { assert.NoError(t, PrepareEngine()) type TestIndexesStruct struct { Id int64 Name string `xorm:"index unique(s)"` Email string `xorm:"index unique(s)"` } assertSync(t, new(TestIndexesStruct)) tables, err := testEngine.DBMetas() assert.NoError(t, err) assert.EqualValues(t, 1, len(tables)) assert.EqualValues(t, 3, len(tables[0].Columns())) slice1 := []string{ testEngine.GetColumnMapper().Obj2Table("Id"), testEngine.GetColumnMapper().Obj2Table("Name"), testEngine.GetColumnMapper().Obj2Table("Email"), } slice2 := []string{ tables[0].Columns()[0].Name, tables[0].Columns()[1].Name, tables[0].Columns()[2].Name, } sort.Strings(slice1) sort.Strings(slice2) assert.EqualValues(t, slice1, slice2) assert.EqualValues(t, 3, len(tables[0].Indexes)) } <file_sep>/integrations/engine_test.go // Copyright 2017 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package integrations import ( "context" "fmt" "os" "testing" "time" "github.com/xormsharp/xorm" "github.com/xormsharp/xorm/schemas" _ "github.com/denisenkom/go-mssqldb" _ "github.com/go-sql-driver/mysql" _ "github.com/lib/pq" _ "github.com/mattn/go-sqlite3" "github.com/stretchr/testify/assert" _ "github.com/ziutek/mymysql/godrv" ) func TestPing(t *testing.T) { if err := testEngine.Ping(); err != nil { t.Fatal(err) } } func TestPingContext(t *testing.T) { assert.NoError(t, PrepareEngine()) ctx, canceled := context.WithTimeout(context.Background(), time.Nanosecond) defer canceled() time.Sleep(time.Nanosecond) err := testEngine.(*xorm.Engine).PingContext(ctx) assert.Error(t, err) assert.Contains(t, err.Error(), "context deadline exceeded") } func TestAutoTransaction(t *testing.T) { assert.NoError(t, PrepareEngine()) type TestTx struct { Id int64 `xorm:"autoincr pk"` Msg string `xorm:"varchar(255)"` Created time.Time `xorm:"created"` } assert.NoError(t, testEngine.Sync2(new(TestTx))) engine := testEngine.(*xorm.Engine) // will success engine.Transaction(func(session *xorm.Session) (interface{}, error) { _, err := session.Insert(TestTx{Msg: "hi"}) assert.NoError(t, err) return nil, nil }) has, err := engine.Exist(&TestTx{Msg: "hi"}) assert.NoError(t, err) assert.EqualValues(t, true, has) // will rollback _, err = engine.Transaction(func(session *xorm.Session) (interface{}, error) { _, err := session.Insert(TestTx{Msg: "hello"}) assert.NoError(t, err) return nil, fmt.Errorf("rollback") }) assert.Error(t, err) has, err = engine.Exist(&TestTx{Msg: "hello"}) assert.NoError(t, err) assert.EqualValues(t, false, has) } func assertSync(t *testing.T, beans ...interface{}) { for _, bean := range beans { t.Run(testEngine.TableName(bean, true), func(t *testing.T) { assert.NoError(t, testEngine.DropTables(bean)) assert.NoError(t, testEngine.Sync2(bean)) }) } } func TestDump(t *testing.T) { assert.NoError(t, PrepareEngine()) type TestDumpStruct struct { Id int64 Name string IsMan bool Created time.Time `xorm:"created"` } assertSync(t, new(TestDumpStruct)) cnt, err := testEngine.Insert([]TestDumpStruct{ {Name: "1", IsMan: true}, {Name: "2\n"}, {Name: "3;"}, {Name: "4\n;\n''"}, {Name: "5'\n"}, }) assert.NoError(t, err) assert.EqualValues(t, 5, cnt) fp := fmt.Sprintf("%v.sql", testEngine.Dialect().URI().DBType) os.Remove(fp) assert.NoError(t, testEngine.DumpAllToFile(fp)) assert.NoError(t, PrepareEngine()) sess := testEngine.NewSession() defer sess.Close() assert.NoError(t, sess.Begin()) _, err = sess.ImportFile(fp) assert.NoError(t, err) assert.NoError(t, sess.Commit()) for _, tp := range []schemas.DBType{schemas.SQLITE, schemas.MYSQL, schemas.POSTGRES, schemas.MSSQL} { name := fmt.Sprintf("dump_%v.sql", tp) t.Run(name, func(t *testing.T) { assert.NoError(t, testEngine.DumpAllToFile(name, tp)) }) } } func TestDumpTables(t *testing.T) { assert.NoError(t, PrepareEngine()) type TestDumpTableStruct struct { Id int64 Name string IsMan bool Created time.Time `xorm:"created"` } assertSync(t, new(TestDumpTableStruct)) testEngine.Insert([]TestDumpTableStruct{ {Name: "1", IsMan: true}, {Name: "2\n"}, {Name: "3;"}, {Name: "4\n;\n''"}, {Name: "5'\n"}, }) fp := fmt.Sprintf("%v-table.sql", testEngine.Dialect().URI().DBType) os.Remove(fp) tb, err := testEngine.TableInfo(new(TestDumpTableStruct)) assert.NoError(t, err) assert.NoError(t, testEngine.(*xorm.Engine).DumpTablesToFile([]*schemas.Table{tb}, fp)) assert.NoError(t, PrepareEngine()) sess := testEngine.NewSession() defer sess.Close() assert.NoError(t, sess.Begin()) _, err = sess.ImportFile(fp) assert.NoError(t, err) assert.NoError(t, sess.Commit()) for _, tp := range []schemas.DBType{schemas.SQLITE, schemas.MYSQL, schemas.POSTGRES, schemas.MSSQL} { name := fmt.Sprintf("dump_%v-table.sql", tp) t.Run(name, func(t *testing.T) { assert.NoError(t, testEngine.(*xorm.Engine).DumpTablesToFile([]*schemas.Table{tb}, name, tp)) }) } } func TestSetSchema(t *testing.T) { assert.NoError(t, PrepareEngine()) if testEngine.Dialect().URI().DBType == schemas.POSTGRES { oldSchema := testEngine.Dialect().URI().Schema testEngine.SetSchema("my_schema") assert.EqualValues(t, "my_schema", testEngine.Dialect().URI().Schema) testEngine.SetSchema(oldSchema) assert.EqualValues(t, oldSchema, testEngine.Dialect().URI().Schema) } } <file_sep>/integrations/main_test.go // Copyright 2017 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package integrations import ( "testing" ) func TestMain(m *testing.M) { MainTest(m) }
8b7242428516a4c80ebb5df1627a82cc9b715850
[ "Go Module", "Go" ]
23
Go
xormsharp/xorm
9b60c04546654b75a1a3069c18c82040155f0522
cfcb5b838e4e051a32c24efbb3c2aaa54d29c26d
refs/heads/master
<repo_name>mviniciusfs/Projeto1_AED1<file_sep>/Imposto.cs using System; using System.Globalization; /* PRODUTOS COD IPI TOTAL Videogames = 1 30% 72,18% Relógios = 2 25% 56,14% Geladeiras = 3 15% 46,21% Televisores = 4 15% 44,94% Máquina de lavar = 5 5% 42,56% Celulares = 6 15% 39,80% Notebooks = 7 15% 38,62% Automóveis = 8 54,00% Roupas = 9 34,00% Perfumes = 10 75,00% Medicamentos = 11 33,00% Energia Resid. = 12 48,00% Água Residencial = 13 24,00% */ class Imposto { private double valorImposto; private double nvalorProduto; private double porcentImposto; public int ClassMaterial; public void retornaDados(int cm) { ClassMaterial = cm; } public void CalculaImposto(double preco) { if (ClassMaterial == 1) { valorImposto = (72.18 / 100) * preco; nvalorProduto = preco - valorImposto; porcentImposto = (valorImposto / preco) * 100; } if (ClassMaterial == 2) { valorImposto = (56.14 / 100) * preco; nvalorProduto = preco - valorImposto; porcentImposto = (valorImposto / preco) * 100; } if (ClassMaterial == 3) { valorImposto = (46.21 / 100) * preco; nvalorProduto = preco - valorImposto; porcentImposto = (valorImposto / preco) * 100; } if (ClassMaterial == 4) { valorImposto = (44.94 / 100) * preco; nvalorProduto = preco - valorImposto; porcentImposto = (valorImposto / preco) * 100; } if (ClassMaterial == 5) { valorImposto = (42.56 / 100) * preco; nvalorProduto = preco - valorImposto; porcentImposto = (valorImposto / preco) * 100; } if (ClassMaterial == 6) { valorImposto = (39.80 / 100) * preco; nvalorProduto = preco - valorImposto; porcentImposto = (valorImposto / preco) * 100; } if (ClassMaterial == 7) { valorImposto = (38.62 / 100) * preco; nvalorProduto = preco - valorImposto; porcentImposto = (valorImposto / preco) * 100; } if (ClassMaterial == 8) { valorImposto = (54.00 / 100) * preco; nvalorProduto = preco - valorImposto; porcentImposto = (valorImposto / preco) * 100; } if (ClassMaterial == 9) { valorImposto = (34.00 / 100) * preco; nvalorProduto = preco - valorImposto; porcentImposto = (valorImposto / preco) * 100; } if (ClassMaterial == 10) { valorImposto = (75.00 / 100) * preco; nvalorProduto = preco - valorImposto; porcentImposto = (valorImposto / preco) * 100; } if (ClassMaterial == 11) { valorImposto = (33.00 / 100) * preco; nvalorProduto = preco - valorImposto; porcentImposto = (valorImposto / preco) * 100; } if (ClassMaterial == 12) { valorImposto = (48.00 / 100) * preco; nvalorProduto = preco - valorImposto; porcentImposto = (valorImposto / preco) * 100; } if (ClassMaterial == 13) { valorImposto = (24.00 / 100) * preco; nvalorProduto = preco - valorImposto; porcentImposto = (valorImposto / preco) * 100; } } public void ImprimeCalculoImposto() { Console.WriteLine(); Console.WriteLine("Valor dos impostos R${0}\nValor do produto sem impostos R${1}\nPorcentagem Total de impostos {2}%", valorImposto.ToString("F2", CultureInfo.InvariantCulture), nvalorProduto.ToString("F2", CultureInfo.InvariantCulture), porcentImposto); Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); } }<file_sep>/main.cs using System; class MainClass { public static void Main (string[] args) { Imposto i = new Imposto(); Produto p = new Produto(); Dadosadic da = new Dadosadic(); da.Titulo(); p.listaTipoMaterial(); Console.Write("Digite o código respectivo ao TIPO DE PRODUTO desejado: "); i.ClassMaterial = int.Parse(Console.ReadLine()); Console.WriteLine(); Console.WriteLine("Abaixo, preencha os dados do Produto"); Console.Write("Nome: "); p.Nome = Console.ReadLine(); Console.Write("Marca: "); p.Marca = Console.ReadLine(); Console.Write("Preço: R$"); p.Preco = double.Parse(Console.ReadLine()); p.imprimeProd(); i.CalculaImposto(p.Preco); i.ImprimeCalculoImposto(); da.Infofinal(); } }<file_sep>/Produto.cs using System; using System.Globalization; class Produto { public string Nome { get; set; } public string Marca { get; set; } public double Preco { get; set; } public void dadosProduto(string n, string m, double p) { Nome = n; Marca = m; Preco = p; } public void listaTipoMaterial() { Console.WriteLine(); Console.WriteLine("Videogames = 1 \nRelógios = 2 \nGeladeiras = 3 \nTelevisores = 4 \nMáquina de lavar = 5 \nCelulares = 6 \nNotebooks = 7 \nAutomóveis = 8 \nRoupas = 9 \nPerfumes = 10 \nMedicamentos = 11 \nEnergia Resid. = 12 \nÁgua Resid. = 13"); Console.WriteLine(); } public void imprimeProd() { Console.WriteLine(); Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); Console.WriteLine("Dados: {0} // {1} // R${2},00", Nome, Marca, Preco); } }<file_sep>/Dadosadic.cs using System; using System.Globalization; class Dadosadic { public void Titulo() { Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); Console.WriteLine(" CleanPurchase"); Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); } public void Infofinal() { Console.WriteLine("!!! A T E N Ç Ã O !!!"); Console.Write("Os dados trazem calculos aproximados, portanto devem ser considerados apenas a critério INFORMATIVO"); } }
93de3b6a20f6c67bd8ae5d645761bdc12a008559
[ "C#" ]
4
C#
mviniciusfs/Projeto1_AED1
abcb88bbb8eecc8c84a0333a56ea5f7f91726255
f192254705272e8a849d6b5faa24e9d0efa4942a
refs/heads/main
<repo_name>QuesadaJon/lab-01-chocolate-pizza<file_sep>/src/App.js import './App.css'; import React, { Component } from 'react' import Header from './chocolate-pizza-js/Header' import ImgSection from './chocolate-pizza-js/ImgSection'; import RecipeInstructions from './chocolate-pizza-js/RecipeInstructions'; import Ingredients from './chocolate-pizza-js/Ingredients'; import AboutAuthor from './chocolate-pizza-js/AboutAuthor'; import Footer from './chocolate-pizza-js/Footer' export default class App extends Component { render() { return ( <div className="main"> <Header /> <ImgSection /> <RecipeInstructions /> <Ingredients /> <AboutAuthor /> <Footer /> </div> ) } }<file_sep>/src/chocolate-pizza-js/Ingredients.js import React, { Component } from 'react' import IngredientsListLeft from './IngredientsListLeft' import { data } from './data'; export default class Ingredients extends Component { render() { return ( <div className="list-background"> { data.map(item => { return <IngredientsListLeft one={item.amount} two={item.name} /> }) } </div> ) } } <file_sep>/README.old.md # lab-01-chocolate-pizza<file_sep>/src/chocolate-pizza-js/Delicous.js import React, { Component } from 'react' export default class Delicous extends Component { render() { return ( <div className="header-left"> <div> <img className='header-logo' src="./assets/logo.png" alt='logo' /> </div> <div> <h2> Delicious </h2> <h3> THE BEST FOOD BLOG ON THE WEB </h3> </div> </div> ) } }
58de02908d7713db98c80df114b1bd3b01fa7a36
[ "JavaScript", "Markdown" ]
4
JavaScript
QuesadaJon/lab-01-chocolate-pizza
c71c9dbe137f802543b112bc2805bc5b6242c9b3
d05f762816a51e291c09df19369298cf0268da96
refs/heads/master
<file_sep># JS-Examples Article - [Remove duplicate in JS array](http://mightytechno.com/)<file_sep>const animals = ['🐞','🐌','🐳','🐏','🐙','🐙','🐌']; var removeDuplicateUsingTwoArrays = function(){ let uniqueAnimals = []; for(var i = 0 ; i < animals.length ; i++){ if(!uniqueAnimals.includes(animals[i])){ uniqueAnimals.push(animals[i]) } } return uniqueAnimals; } var removeDuplicateUsingFilter = function(){ return uniqueAnimals = animals.filter(function(item,index){ return animals.indexOf(item) == index; }); } var removeDuplicateUsingSet = function(){ return uniqueAnimals = [...new Set(animals)]; } var removeDuplicateUsingForEach = function(){ let uniqueAnimals = {}; animals.forEach(function(i){ if(!uniqueAnimals[i]){ uniqueAnimals[i] = true; } }) return Object.keys(uniqueAnimals); } var removeDuplicateUsingReduce = function(){ return animals.reduce((uniqueAnimals,currentValue) => { return uniqueAnimals.includes(currentValue) ? uniqueAnimals : [...uniqueAnimals,currentValue]; },[]) } //console.log(removeDuplicateUsingTwoArrays()); //console.log(removeDuplicateUsingFilter()); //onsole.log(removeDuplicateUsingSet()); //console.log(removeDuplicateUsingForEach()); console.log(removeDuplicateUsingReduce());
9e84d33df32203f453d5727e1775f9ab5a720bdb
[ "Markdown", "JavaScript" ]
2
Markdown
mightytechno/JS-Examples
3ed64d4f53a14705e3265c126af6cc894f594fc3
72906c9a20eca0688fd8fcefc372d606cf493217
refs/heads/master
<repo_name>eugeneliu-dev/AyiHockWebAPI<file_sep>/AyiHockWebAPI/Dtos/OrderDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Dtos { public class OrderGetDto { public string OrderId { get; set; } public int Status { get; set; } public int TotalPrice { get; set; } public string OrdererPhone { get; set; } public DateTime CreateTime { get; set; } public DateTime ModifyTime { get; set; } public ICollection<OrderContentGetDto> OrderContents { get; set; } } public class OrderPostDto { public int Status { get; set; } public int TotalPrice { get; set; } public string OrdererPhone { get; set; } public int PayRule { get; set; } public ICollection<OrderContentPostDto> OrderContents { get; set; } } } <file_sep>/AyiHockWebAPI/Helpers/AutoSendEmailHelper.cs using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Threading.Tasks; namespace AyiHockWebAPI.Helpers { public class AutoSendEmailHelper { private readonly IConfiguration _configuration; public AutoSendEmailHelper(IConfiguration configuration) { _configuration = configuration; } public bool SendAuthEmail(string userMail, string authLink) { try { string account = _configuration.GetValue<string>("Email:Account"); string pwd = _configuration.GetValue<string>("Email:Pwd"); string mailBody = ""; MailMessage mail = new MailMessage(); mail.From = new MailAddress(account, "阿奕の腿庫飯-會員驗證信"); mail.To.Add(userMail); mail.Priority = MailPriority.Normal; mail.Subject = "阿奕の腿庫飯-會員驗證信"; mailBody += "<h5>請依以下訊息進行驗證</h5>"; mailBody += "<h5>" + authLink + "</h5><hr>"; mailBody += "<h5>此為系統主動發送信函,請勿直接回覆此封信件。</h5>"; mail.Body = mailBody; mail.IsBodyHtml = true; SmtpClient MySmtp = new SmtpClient("smtp.gmail.com", 587); MySmtp.Credentials = new System.Net.NetworkCredential(account, pwd); MySmtp.EnableSsl = true; MySmtp.Send(mail); MySmtp = null; mail.Dispose(); } catch (Exception ex) { return false; } return true; } } } <file_sep>/AyiHockWebAPI/Dtos/MealDto.cs using AyiHockWebAPI.Helpers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Dtos { public class MealDto { public string Name { get; set; } public string Description { get; set; } public int Price { get; set; } public int Type { get; set; } } public class MealGetDto { public int MealId { get; set; } public string Name { get; set; } public string Description { get; set; } public int Price { get; set; } public int Type { get; set; } public string PicPath { get; set; } } public class MealTypeGetDto { public int TypeId { get; set; } public string Type { get; set; } } public class MealPostDto { [ModelBinder(BinderType = typeof(JsonBinder))] [Required] public MealDto Meal { get; set; } [Required] public IFormFile File { get; set; } } public class MealPutBasicInfoDto { public string Name { get; set; } public string Description { get; set; } public int Price { get; set; } public int Type { get; set; } } public class MealPutTotalInfoDto { [ModelBinder(BinderType = typeof(JsonBinder))] [Required] public MealDto Meal { get; set; } public IFormFile File { get; set; } } } <file_sep>/AyiHockWebAPI/Controllers/OrderController.cs using AyiHockWebAPI.Dtos; using AyiHockWebAPI.Filters; using AyiHockWebAPI.Models; using AyiHockWebAPI.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Controllers { [Route("api/[controller]")] [TypeFilter(typeof(ResultFormatFilter))] [ApiController] public class OrderController : ControllerBase { private readonly OrderService _orderService; public OrderController(OrderService orderService) { _orderService = orderService; } /// <summary> /// 查詢個人訂單列表(ApplyRole: customer) /// </summary> /// <returns></returns> [HttpGet] [Authorize("JtiRestraint")] [Authorize(Roles = "normal, golden, platinum, diamond")] public async Task<ActionResult<List<OrderGetDto>>> Get() { var platform = User.Claims.FirstOrDefault(p => p.Type == "platform").Value.ToString(); var customer = _orderService.GetCustomerInfo(User.Identity.Name, platform); if (customer == null) return BadRequest(); var orderlist = await _orderService.GetOrderList(customer); if (orderlist == null || orderlist.Count() <= 0) return NotFound(); else return Ok(orderlist); } /// <summary> /// 新增個人訂單(ApplyRole: customer) /// </summary> /// <returns></returns> [HttpPost] [Authorize("JtiRestraint")] [Authorize(Roles = "normal, golden, platinum, diamond")] public async Task<ActionResult> Post([FromBody] OrderPostDto value) { var platform = User.Claims.FirstOrDefault(p => p.Type == "platform").Value.ToString(); var customer = _orderService.GetCustomerInfo(User.Identity.Name, platform); if (customer == null) return BadRequest(); await _orderService.PostOrder(customer, value); return NoContent(); } /// <summary> /// 刪除個人訂單(ApplyRole: staff/admin) /// </summary> /// <returns></returns> [HttpDelete("{id}")] [Authorize("JtiRestraint")] [Authorize(Roles = "admin, staff")] public async Task <ActionResult> Delete(string id) { await _orderService.DeleteOrder(id); return NoContent(); } } } <file_sep>/AyiHockWebAPI/Filters/ResultFormatFilter.cs using AyiHockWebAPI.Dtos; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace AyiHockWebAPI.Filters { public class ResultFormatFilter : Attribute, IAsyncResultFilter { private readonly ILogger<ResultFormatFilter> _logger; public ResultFormatFilter(ILogger<ResultFormatFilter> logger) { _logger = logger; } public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { if (!(context.Result is EmptyResult)) { context.HttpContext.Response.ContentType = "application/json"; ResultDto result = new ResultDto(); var statusCode = (context.Result as ObjectResult)?.StatusCode; var retMsg = (context.Result as ObjectResult)?.Value; if (statusCode == null) { StatusCodeResult statusResult = context.Result as StatusCodeResult; statusCode = statusResult?.StatusCode; } if (Is200SeriousStatusCode((int)statusCode)) { result.Success = true; result.Message = statusCode.ToString(); result.Data = (context.Result as ObjectResult)?.Value; } else { result.Success = false; result.Message = statusCode.ToString() + retMsg; result.Data = null; } context.HttpContext.Response.StatusCode = (int)statusCode; await context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(result)); await next(); _logger.LogInformation("StatusCode:" + statusCode.ToString()); } else { context.Cancel = true; } } private bool Is200SeriousStatusCode(int code) { if (code >= 200 && code < 300) return true; else return false; } } } <file_sep>/AyiHockWebAPI/Services/OrderService.cs using AyiHockWebAPI.Dtos; using AyiHockWebAPI.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Services { public class OrderService { private readonly d5qp1l4f2lmt76Context _ayihockDbContext; public OrderService(d5qp1l4f2lmt76Context ayihockDbContext) { _ayihockDbContext = ayihockDbContext; } //public News GetNewsFullInfoFromDB(int id) //{ // var news = (from a in _ayihockDbContext.News // where a.NewsId == id // select a).SingleOrDefault(); // return news; //} public Customer GetCustomerInfo(string sub, string platform) { return _ayihockDbContext.Customers.Select(cus => cus).Where(cus => sub == cus.Email && cus.Platform == Convert.ToInt32(platform)).FirstOrDefault(); } public async Task<List<OrderGetDto>> GetOrderList(Customer customer) { var orderlist = await (from order in _ayihockDbContext.Orders where order.Orderer == customer.CustomerId join cus in _ayihockDbContext.Customers on order.Orderer equals cus.CustomerId select new OrderGetDto { OrderId = order.OrderId, Status = order.Status, TotalPrice = order.TotalPrice, OrdererPhone = order.OrdererPhone, CreateTime = order.CreateTime, ModifyTime = order.ModifyTime, OrderContents = (from content in _ayihockDbContext.Ordercontents where order.OrderId == content.OrderId join meal in _ayihockDbContext.Meals on content.MealId equals meal.MealId select new OrderContentGetDto { OrderId = content.OrderId, MealId = content.MealId, Quantity = content.Quantity, MealName = meal.Name, MealDesc = meal.Description, MealPrice = meal.Price, MealPic = meal.Picture }).ToList() }).OrderBy(a => a.OrderId).ToListAsync(); return orderlist; } public async Task PostOrder(Customer customer, OrderPostDto value) { Order order = new Order { OrderId = DateTime.Now.ToString("yyyyMMddHHmmssffff"), Status = value.Status, TotalPrice = value.TotalPrice, Payrule = value.PayRule, Orderer = customer.CustomerId, OrdererPhone = value.OrdererPhone, CreateTime = DateTime.Now, ModifyTime = DateTime.Now, Ordercontents = TransToModel(value.OrderContents) }; _ayihockDbContext.Orders.Add(order); int money = customer.Money + value.TotalPrice; int type = (int)GetUserNewType(money); customer.Money = value.TotalPrice; if (type != customer.Role) customer.Role = type; await _ayihockDbContext.SaveChangesAsync(); } public async Task DeleteOrder(string id) { var delete_content = (from a in _ayihockDbContext.Ordercontents where a.OrderId == id select a).ToList(); _ayihockDbContext.Ordercontents.RemoveRange(delete_content); _ayihockDbContext.SaveChanges(); var delete_order = (from a in _ayihockDbContext.Orders where a.OrderId == id select a).SingleOrDefault(); if (delete_order != null) { _ayihockDbContext.Orders.Remove(delete_order); await _ayihockDbContext.SaveChangesAsync(); } } private List<Ordercontent> TransToModel(ICollection<OrderContentPostDto> orderContents) { List<Ordercontent> contents = new List<Ordercontent>(); foreach (var item in orderContents) { Ordercontent content = new Ordercontent { MealId = item.MealId, Quantity = item.Quantity }; contents.Add(content); } return contents; } private CustomerType GetUserNewType(int currMoney) { if (currMoney >= 50000) { return CustomerType.Diamond; } else if (currMoney >= 10000) { return CustomerType.Platinum; } else if (currMoney >= 5000) { return CustomerType.Golden; } else { return CustomerType.Normal; } } private enum CustomerType { Normal = 0, Golden = 1, Platinum = 2, Diamond = 3 } } } <file_sep>/AyiHockWebAPI/Helpers/JwtHelper.cs using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace AyiHockWebAPI.Helpers { public class JwtHelper { private readonly IConfiguration Configuration; public JwtHelper(IConfiguration configuration) { this.Configuration = configuration; } public string GenerateToken(string account, int role, string name, int platform) { var issuer = Configuration.GetValue<string>("JwtSettings:Issuer"); var signKey = Configuration.GetValue<string>("JwtSettings:SignKey"); var expireMinutes = Configuration.GetValue<int>("JwtSettings:ExpireMinutes"); // 設定要加入到 JWT Token 中的聲明資訊(Claims) var claims = new List<Claim>(); // 在 RFC 7519 規格中(Section#4),總共定義了 7 個預設的 Claims,我們應該只用的到兩種! claims.Add(new Claim(JwtRegisteredClaimNames.Sub, account)); // User.Identity.Name claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); // JWT ID // 你可以自行擴充 "roles" 加入登入者該有的角色 claims.Add(new Claim(ClaimTypes.Role, _GetRoleName(role))); claims.Add(new Claim(ClaimTypes.Name, name)); claims.Add(new Claim("platform", platform.ToString())); var userClaimsIdentity = new ClaimsIdentity(claims); // 建立一組對稱式加密的金鑰,主要用於 JWT 簽章之用 var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signKey)); // HmacSha256 有要求必須要大於 128 bits,所以 key 不能太短,至少要 16 字元以上 // https://stackoverflow.com/questions/47279947/idx10603-the-algorithm-hs256-requires-the-securitykey-keysize-to-be-greater var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); // 建立 SecurityTokenDescriptor var tokenDescriptor = new SecurityTokenDescriptor { Issuer = issuer, Subject = userClaimsIdentity, Expires = DateTime.Now.AddMinutes(expireMinutes), SigningCredentials = signingCredentials }; // 產出所需要的 JWT securityToken 物件,並取得序列化後的 Token 結果(字串格式) var tokenHandler = new JwtSecurityTokenHandler(); var securityToken = tokenHandler.CreateToken(tokenDescriptor); var serializeToken = tokenHandler.WriteToken(securityToken); return serializeToken; } public string GenerateRefreshToken(string account, string userId) { var issuer = Configuration.GetValue<string>("JwtSettings:RefreshIssuer"); var signKey = Configuration.GetValue<string>("JwtSettings:SignKey"); var expireMinutes = Configuration.GetValue<int>("JwtSettings:RefreshExpireMinutes"); // 設定要加入到 JWT Token 中的聲明資訊(Claims) var claims = new List<Claim>(); // 在 RFC 7519 規格中(Section#4),總共定義了 7 個預設的 Claims,我們應該只用的到兩種! claims.Add(new Claim(JwtRegisteredClaimNames.Sub, account)); // User.Identity.Name claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); // JWT ID var userClaimsIdentity = new ClaimsIdentity(claims); // 建立一組對稱式加密的金鑰,主要用於 JWT 簽章之用 var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signKey)); // HmacSha256 有要求必須要大於 128 bits,所以 key 不能太短,至少要 16 字元以上 // https://stackoverflow.com/questions/47279947/idx10603-the-algorithm-hs256-requires-the-securitykey-keysize-to-be-greater var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); // 建立 SecurityTokenDescriptor var tokenDescriptor = new SecurityTokenDescriptor { Issuer = issuer, Subject = userClaimsIdentity, Expires = DateTime.Now.AddMinutes(expireMinutes), SigningCredentials = signingCredentials }; // 產出所需要的 JWT securityToken 物件,並取得序列化後的 Token 結果(字串格式) var tokenHandler = new JwtSecurityTokenHandler(); var securityToken = tokenHandler.CreateToken(tokenDescriptor); var serializeToken = tokenHandler.WriteToken(securityToken); return serializeToken; } public ClaimsPrincipal GetPrincipalByAccessToken(string token) { var handler = new JwtSecurityTokenHandler(); var signKey = Configuration.GetValue<string>("JwtSettings:SignKey"); try { return handler.ValidateToken(token, new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = true, ValidIssuer = Configuration.GetValue<string>("JwtSettings:Issuer"), ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signKey)), ValidateLifetime = true }, out SecurityToken validatedToken); } catch (Exception) { return null; } } private string _GetRoleName(int role) { string retStr = "normal"; switch (role) { case 0: retStr = "normal"; break; case 1: retStr = "golden"; break; case 2: retStr = "platinum"; break; case 3: retStr = "diamond"; break; case 10: retStr = "staff"; break; case 11: retStr = "admin"; break; default: break; } return retStr; } } } <file_sep>/AyiHockWebAPI/Models/Ordercontent.cs using System; using System.Collections.Generic; #nullable disable namespace AyiHockWebAPI.Models { public partial class Ordercontent { public string OrderId { get; set; } public int MealId { get; set; } public int Quantity { get; set; } public Guid OrdercontentId { get; set; } public virtual Order Order { get; set; } } } <file_sep>/AyiHockWebAPI/Models/Newscategory.cs using System; using System.Collections.Generic; #nullable disable namespace AyiHockWebAPI.Models { public partial class Newscategory { public Newscategory() { News = new HashSet<News>(); } public int NewsCategoryId { get; set; } public string Name { get; set; } public bool IsAdminChoose { get; set; } public virtual ICollection<News> News { get; set; } } } <file_sep>/AyiHockWebAPI/Models/Mealtype.cs using System; using System.Collections.Generic; #nullable disable namespace AyiHockWebAPI.Models { public partial class Mealtype { public Mealtype() { Meals = new HashSet<Meal>(); } public int TypeId { get; set; } public string Type { get; set; } public virtual ICollection<Meal> Meals { get; set; } } } <file_sep>/AyiHockWebAPI/Dtos/LoginDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Dtos { public class LoginDto { public string Email { get; set; } public string Password { get; set; } } public class LoginDtoWithRole { public string Email { get; set; } public string Password { get; set; } public int Role { get; set; } public string Name { get; set; } } public class LoginDtoForSocial { public string Email { get; set; } public string Name { get; set; } public int Role { get; set; } public bool Enable { get; set; } public bool IsBlack { get; set; } } public class SocialUser { public string Name { get; set; } public string Email { get; set; } public string Token { get; set; } } public enum LoginPlatform { Original = 0, Google = 1, Facebook = 2 } } <file_sep>/AyiHockWebAPI/Services/ManagerService.cs using AyiHockWebAPI.Dtos; using AyiHockWebAPI.Helpers; using AyiHockWebAPI.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Services { public class ManagerService { private readonly d5qp1l4f2lmt76Context _ayihockDbContext; private readonly EncryptDecryptHelper _encryptDecryptHelper; private readonly AutoSendEmailHelper _autoSendEmailHelper; public ManagerService(d5qp1l4f2lmt76Context ayihockDbContext, IConfiguration configuration, EncryptDecryptHelper encryptDecryptHelper, AutoSendEmailHelper autoSendEmailHelper) { _ayihockDbContext = ayihockDbContext; _encryptDecryptHelper = encryptDecryptHelper; _autoSendEmailHelper = autoSendEmailHelper; } public Manager GetManagerFullInfoByMail(string mail) { var manager = (from a in _ayihockDbContext.Managers where a.Email == mail select a).SingleOrDefault(); return manager; } public Manager GetManagerFullInfoById(Guid id) { var manager = (from a in _ayihockDbContext.Managers where a.ManagerId == id select a).SingleOrDefault(); return manager; } public Manager GetManagerFullInfoByOldPassword(string mail, string oldPassword) { var manager = (from a in _ayihockDbContext.Managers where a.Email == mail && a.Password == _encryptDecryptHelper.AESDecrypt(oldPassword).Replace("\"", "") select a).SingleOrDefault(); return manager; } public async Task<List<ManagerGetTotalInfoDto>> GetManagersListTotalInfo() { var managers = await (from a in _ayihockDbContext.Managers where a.IsAdmin == false select new ManagerGetTotalInfoDto { ManagerId = a.ManagerId, Name = a.Name, Email = a.Email, Phone = a.Phone, Enable = a.Enable, IsAdmin = a.IsAdmin }).OrderBy(a => a.Enable).ToListAsync(); return managers; } public async Task<ManagerGetTotalInfoDto> GetManagerTotalInfo(Guid id) { var manager = await (from a in _ayihockDbContext.Managers where a.IsAdmin == false && a.ManagerId == id select new ManagerGetTotalInfoDto { ManagerId = a.ManagerId, Name = a.Name, Email = a.Email, Phone = a.Phone, Enable = a.Enable, IsAdmin = a.IsAdmin }).SingleOrDefaultAsync(); return manager; } public async Task<ManagerGetBasicInfoDto> GetManagerBasicInfo(string userEmail) { var manager = await (from a in _ayihockDbContext.Managers where a.Email == userEmail select new ManagerGetBasicInfoDto { Name = a.Name, Email = a.Email, Phone = a.Phone, IsAdmin = a.IsAdmin }).SingleOrDefaultAsync(); return manager; } public async Task PostManager(ManagerPostDto value) { Guid guid = Guid.NewGuid(); Manager manager = new Manager { ManagerId = guid, Name = value.Name, Email = value.Email, Password = _encryptDecryptHelper.AESDecrypt(value.Password).Replace("\"", ""), //需前端加密處理,後端解密 Phone = value.Phone, Enable = true, IsAdmin = false }; _ayihockDbContext.Managers.Add(manager); await _ayihockDbContext.SaveChangesAsync(); } public async Task PutManager(Manager update, ManagerPutDto value) { update.Name = value.Name; update.Email = value.Email; update.Phone = value.Phone; update.Enable = value.Enable; await _ayihockDbContext.SaveChangesAsync(); } public async Task PutManagerNewPassword(ManagerPutPwdDto value, Manager update) { update.Password = _encryptDecryptHelper.AESDecrypt(value.NewPassword).Replace("\"", ""); //需前端加密處理,後端解密 await _ayihockDbContext.SaveChangesAsync(); } public async Task PutManagerResetPassword(string managerMail, Manager update) { string newPwd = _encryptDecryptHelper.GetRandomStr(); update.Password = newPwd; await _ayihockDbContext.SaveChangesAsync(); _autoSendEmailHelper.SendAuthEmail(managerMail, "新密碼:" + newPwd); } public async Task<Manager> DeleteManager(Guid id) { var delete = GetManagerFullInfoById(id); if (delete == null) return null; _ayihockDbContext.Managers.Remove(delete); await _ayihockDbContext.SaveChangesAsync(); return delete; } } } <file_sep>/AyiHockWebAPI/Models/Customer.cs using System; using System.Collections.Generic; #nullable disable namespace AyiHockWebAPI.Models { public partial class Customer { public Guid CustomerId { get; set; } public string Name { get; set; } public string Email { get; set; } public string Password { get; set; } public string Phone { get; set; } public bool Enable { get; set; } public int Role { get; set; } public bool Isblack { get; set; } public DateTime CreateTime { get; set; } public DateTime ModifyTime { get; set; } public int Money { get; set; } public Guid Modifier { get; set; } public int Platform { get; set; } public string PrePassword { get; set; } } } <file_sep>/AyiHockWebAPI/Models/Manager.cs using System; using System.Collections.Generic; #nullable disable namespace AyiHockWebAPI.Models { public partial class Manager { public Manager() { News = new HashSet<News>(); } public Guid ManagerId { get; set; } public string Name { get; set; } public string Email { get; set; } public string Password { get; set; } public string Phone { get; set; } public bool Enable { get; set; } public bool IsAdmin { get; set; } public virtual ICollection<News> News { get; set; } } } <file_sep>/AyiHockWebAPI/Models/Meal.cs using System; using System.Collections.Generic; #nullable disable namespace AyiHockWebAPI.Models { public partial class Meal { public int MealId { get; set; } public string Name { get; set; } public string Description { get; set; } public int Price { get; set; } public int Type { get; set; } public string Picture { get; set; } public string Picturename { get; set; } public bool Disable { get; set; } public virtual Mealtype TypeNavigation { get; set; } } } <file_sep>/AyiHockWebAPI/Middleware/CatchExceptionMiddleware.cs using AyiHockWebAPI.Dtos; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; namespace AyiHockWebAPI.Middleware { public class CatchExceptionMiddleware { private readonly RequestDelegate _next; private readonly ILogger<CatchExceptionMiddleware> _logger; public CatchExceptionMiddleware(RequestDelegate next, ILogger<CatchExceptionMiddleware> logger) { _next = next; _logger = logger; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { await HandleException(context, ex); } } private Task HandleException(HttpContext context, Exception ex) { if (!context.Response.HasStarted) { context.Response.StatusCode = StatusCodes.Status500InternalServerError; context.Response.ContentType = "application/json"; var message = ex.GetType() != null ? ex.Message : "InternalServerError"; _logger.LogError(ex, $"Ex massage: {message}, StackTrace: {ex.StackTrace}", ex); var result = JsonConvert.SerializeObject(new ResultDto { Success = false, Message = string.Format("({0}) - {1}", ((int)HttpStatusCode.InternalServerError).ToString(), ex.Message), Data = null }); return context.Response.WriteAsync(result); } else { return context.Response.WriteAsync(string.Empty); } } } } <file_sep>/AyiHockWebAPI/ValidationAttributes/ValidJtiRequirement.cs using AyiHockWebAPI.Models; using Microsoft.AspNetCore.Authorization; using StackExchange.Redis; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.ValidationAttributes { public class ValidJtiRequirement: IAuthorizationRequirement { public class ValidJtiHandler:AuthorizationHandler<ValidJtiRequirement> { private readonly d5qp1l4f2lmt76Context _ayihockDbContext; private readonly IConnectionMultiplexer _redis; public ValidJtiHandler(d5qp1l4f2lmt76Context ayihockDbContext, IConnectionMultiplexer radis) { _ayihockDbContext = ayihockDbContext; _redis = radis; } protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ValidJtiRequirement requirement) { //檢查Jti是否存在 var jti = context.User.FindFirst("jti")?.Value; if (jti == null) { context.Fail(); //驗證失敗 return Task.CompletedTask; } IDatabase cache = _redis.GetDatabase(0); var tokenExists = cache.KeyExists(jti); if (tokenExists) context.Fail(); else context.Succeed(requirement); //驗證成功 return Task.CompletedTask; } } } } <file_sep>/AyiHockWebAPI/Dtos/OrderContentDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Dtos { public class OrderContentGetDto { public string OrderId { get; set; } public int MealId { get; set; } public int Quantity { get; set; } public string MealName { get; set; } public string MealDesc { get; set; } public int MealPrice { get; set; } public string MealPic { get; set; } } public class OrderContentPostDto { public int MealId { get; set; } public int Quantity { get; set; } } } <file_sep>/AyiHockWebAPI/Services/LoginService.cs using AyiHockWebAPI.Dtos; using AyiHockWebAPI.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using StackExchange.Redis; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Services { public class LoginService { private readonly d5qp1l4f2lmt76Context _ayihockDbContext; private readonly IConfiguration _configuration; private readonly IConnectionMultiplexer _redis; public LoginService(d5qp1l4f2lmt76Context ayihockDbContext, IConfiguration config, IConnectionMultiplexer radis) { _ayihockDbContext = ayihockDbContext; _configuration = config; _redis = radis; } public async Task<LoginDtoWithRole> ValidateUser(LoginDto login) { if (!string.IsNullOrWhiteSpace(login.Email) && !string.IsNullOrWhiteSpace(login.Password)) { var res = await (from a in _ayihockDbContext.Customers where a.Email == login.Email && a.Password == login.Password && a.Enable == true && a.Isblack != true && a.Platform == (int)LoginPlatform.Original select new LoginDtoWithRole { Email = a.Email, Password = <PASSWORD>, Role = a.Role, Name = a.Name }).SingleOrDefaultAsync(); return res; } else { return null; } } public async Task<LoginDtoForSocial> ValidateSocialUser(string email, LoginPlatform platform) { if (!string.IsNullOrWhiteSpace(email)) { int p = (int)platform; var res = await (from a in _ayihockDbContext.Customers where a.Email == email && a.Platform == p select new LoginDtoForSocial { Email = a.Email, Name = a.Name, Role = a.Role, Enable = a.Enable, IsBlack = a.Isblack }).SingleOrDefaultAsync(); return res; } else { return null; } } public async Task<LoginDtoWithRole> ValidateAdmin(LoginDto login) { if (!string.IsNullOrWhiteSpace(login.Email) && !string.IsNullOrWhiteSpace(login.Password)) { var res = await (from a in _ayihockDbContext.Managers where a.Email == login.Email && a.Password == login.Password && a.Enable == true select new LoginDtoWithRole { Email = a.Email, Password = <PASSWORD>, Role = (a.IsAdmin == true) ? 11 : 10, //11:Admin, 10:Staff Name = a.Name }).SingleOrDefaultAsync(); return res; } else { return null; } } public async Task<Customer> AddSocialUser(string name, string email, LoginPlatform platform) { Guid guid = Guid.NewGuid(); int p = (int)platform; Customer customer = new Customer { CustomerId = guid, Name = name, Email = email, Password = "<PASSWORD>", Phone = "0900000000", Enable = true, Isblack = false, Modifier = guid, CreateTime = DateTime.Now, ModifyTime = DateTime.Now, Platform = p }; _ayihockDbContext.Customers.Add(customer); await _ayihockDbContext.SaveChangesAsync(); return customer; } public async Task<bool> SetJtiToBlackList(string jti, int expire ) { if (string.IsNullOrWhiteSpace(jti) || expire <= 0) return false; try { IDatabase cache = _redis.GetDatabase(0); cache.StringSet(jti, expire, TimeSpan.FromSeconds(expire - DateTimeOffset.Now.ToUnixTimeSeconds()), When.NotExists); } catch { //TODO: Catch Exception return false; } return true; } } } <file_sep>/AyiHockWebAPI/Models/Order.cs using System; using System.Collections.Generic; #nullable disable namespace AyiHockWebAPI.Models { public partial class Order { public Order() { Ordercontents = new HashSet<Ordercontent>(); } public string OrderId { get; set; } public int Status { get; set; } public int TotalPrice { get; set; } public Guid Orderer { get; set; } public string OrdererPhone { get; set; } public DateTime CreateTime { get; set; } public DateTime ModifyTime { get; set; } public int? Payrule { get; set; } public virtual ICollection<Ordercontent> Ordercontents { get; set; } } } <file_sep>/AyiHockWebAPI/Controllers/CustomerController.cs using AyiHockWebAPI.Dtos; using AyiHockWebAPI.Filters; using AyiHockWebAPI.Helpers; using AyiHockWebAPI.Models; using AyiHockWebAPI.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.JsonPatch; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Threading.Tasks; namespace AyiHockWebAPI.Controllers { [Route("api/[controller]")] [TypeFilter(typeof(ResultFormatFilter))] [ApiController] public class CustomerController : ControllerBase { private readonly EncryptDecryptHelper _encryptDecryptHelper; private readonly CustomerService _customerService; public CustomerController(EncryptDecryptHelper encryptDecryptHelper, CustomerService customerService) { _encryptDecryptHelper = encryptDecryptHelper; _customerService = customerService; } /// <summary> /// 查詢使用者列表(ApplyRole: admin/staff) /// </summary> /// <returns></returns> [HttpGet] [Authorize("JtiRestraint")] [Authorize(Roles = "admin, staff")] public async Task<ActionResult<List<CustomerGetDto>>> Get() { var customers = await _customerService.GetCustomerList(); if (customers == null || customers.Count() <= 0) return NotFound(); else return Ok(customers); } /// <summary> /// 查詢使用者(ApplyRole: admin/staff) /// </summary> /// <returns></returns> [HttpGet("{id}")] [Authorize("JtiRestraint")] [Authorize(Roles = "admin, staff")] public async Task<ActionResult<CustomerGetDto>> Get(Guid id) { var customerById = await _customerService.GetCustomerFromManager(id); if (customerById == null) return NotFound(); else return Ok(customerById); } /// <summary> /// 查詢使用者(僅提供一般帳號)(ApplyRole: user) /// </summary> /// <returns></returns> [HttpGet("user")] [Authorize("JtiRestraint")] [Authorize(Roles = "normal, golden, platinum, diamond")] public async Task<ActionResult<CustomerGetByUserDto>> GetUser() { var sub = User.Identity.Name; var customer = await _customerService.GetCustomerFromUser(sub); if (customer == null) return NotFound(); else return Ok(customer); } /// <summary> /// 新增使用者(註冊帳戶)(ApplyRole: anonymous) /// </summary> /// <returns></returns> [HttpPost] [AllowAnonymous] public async Task<ActionResult> Post([FromBody] CustomerPostDto value) { var getCusByEmail = await _customerService.GetCustomerFromUser(value.Email); if (getCusByEmail != null) return BadRequest(); await _customerService.PostCustomer(value); return Ok(); } /// <summary> /// 驗證使用者(驗證帳戶)(ApplyRole: anonymous) /// </summary> /// <returns></returns> [HttpGet("auth")] [AllowAnonymous] public async Task<ActionResult> GetAuth(string varify) { //check Guid is exist? var customer = await _customerService.AuthCustomer(varify); if (customer == null) { return NotFound("驗證失敗"); } else { return Ok(); } } /// <summary> /// 更新使用者(僅允許更新系統資料)(ApplyRole: admin/staff) /// </summary> /// <returns></returns> [HttpPut("manager/{id}")] [Authorize("JtiRestraint")] [Authorize(Roles = "admin, staff")] public async Task<ActionResult> Put(Guid id, [FromBody] CustomerPutDto value) { var manager = _customerService.GetManagerInfo(User.Identity.Name); if (manager == null) return BadRequest(); var update = _customerService.GetCustomerFullInfoById(id); if (update != null) { await _customerService.PutCustomerFromManager(manager.ManagerId, value, update); return Ok(); } else { return NotFound(); } } /// <summary> /// 更新使用者(僅允許更新使用者基本資料)(ApplyRole: user) /// </summary> /// <returns></returns> [HttpPut("user")] [Authorize("JtiRestraint")] [Authorize(Roles = "normal, golden, platinum, diamond")] public async Task<ActionResult> Put([FromBody] CustomerPutByUserDto value) { var update = _customerService.GetCustomerFullInfoByMail(User.Identity.Name); if (update != null) { await _customerService.PutCustomerFromUser(value, update); return Ok(); } else { return NotFound(); } } /// <summary> /// 更新使用者密碼(僅提供一般帳號)(ApplyRole: user) /// </summary> /// <returns></returns> [HttpPut("user/pwdmodify")] [Authorize("JtiRestraint")] [Authorize(Roles = "normal, golden, platinum, diamond")] public async Task<ActionResult> PutPwd([FromBody] CustomerPutPwdByUserDto value) { var update = _customerService.GetCustomerFullInfoByOldPassword(User.Identity.Name, value.OldPassword); if (update != null) { await _customerService.PutCustomerNewPassword(value.NewPassword, update); return Ok(); } else { return BadRequest("舊帳號輸入錯誤!"); } } /// <summary> /// 忘記密碼(發送驗證碼至信箱供重置密碼)(ApplyRole: anonymous) /// </summary> /// <returns></returns> [HttpPut("user/pwdforget")] [AllowAnonymous] public async Task<ActionResult> PutPwdForget(CustomerPutPwdByForgetDto value) { var update = _customerService.GetCustomerFullInfoByMail(value.UserAccountMail); if (update != null) { await _customerService.PutCustomerResetPassword(value.UserAccountMail, update); return Ok(); } else { return BadRequest("電子郵件輸入錯誤!"); } } /// <summary> /// 重置使用者密碼(ApplyRole: anonymous) /// </summary> /// <returns></returns> [HttpPut("user/pwdreset")] [AllowAnonymous] public async Task<ActionResult> PutPwdReset([FromBody] CustomerPutPwdByResetDto value) { var update = _customerService.GetCustomerFullInfoByPrePassword(value.UserAccountMail, value.DefaultPassword); if (update != null) { await _customerService.PutCustomerNewPassword(value.NewPassword, update); return Ok(); } else { return BadRequest("驗證碼或郵件信箱輸入錯誤!"); } } /// <summary> /// 刪除使用者(ApplyRole: admin/staff) /// </summary> /// <returns></returns> [HttpDelete("{id}")] [Authorize("JtiRestraint")] [Authorize(Roles = "admin, staff")] public async Task<ActionResult> Delete(Guid id) { var delete = await _customerService.DeleteCustomer(id); if (delete == null) return NotFound("CustomerId不存在!"); else return Ok(); } } } <file_sep>/AyiHockWebAPI/Models/Customertype.cs using System; using System.Collections.Generic; #nullable disable namespace AyiHockWebAPI.Models { public partial class Customertype { public int TypeId { get; set; } public string Name { get; set; } public int UpgradeLimit { get; set; } } } <file_sep>/AyiHockWebAPI/Helpers/JsonBinder.cs using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Threading.Tasks; namespace AyiHockWebAPI.Helpers { public class JsonBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var modelName = bindingContext.ModelName; // Try to fetch the value of the argument by name var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); if (valueProviderResult == ValueProviderResult.None) { return Task.CompletedTask; } bindingContext.ModelState.SetModelValue(modelName, valueProviderResult); var value = valueProviderResult.FirstValue; // Check if the argument value is null or empty if (string.IsNullOrEmpty(value)) { return Task.CompletedTask; } try { object result = JsonSerializer.Deserialize(value, bindingContext.ModelType); bindingContext.Result = ModelBindingResult.Success(result); } catch (Exception ex) { bindingContext.Result = ModelBindingResult.Failed(); } return Task.CompletedTask; } } } <file_sep>/AyiHockWebAPI/Controllers/LoginController.cs using AyiHockWebAPI.Dtos; using AyiHockWebAPI.Filters; using AyiHockWebAPI.Helpers; using AyiHockWebAPI.Models; using AyiHockWebAPI.Services; using Google.Apis.Auth; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace AyiHockWebAPI.Controllers { [Route("api/[controller]")] [TypeFilter(typeof(ResultFormatFilter))] [ApiController] public class LoginController : ControllerBase { //DbContext private readonly d5qp1l4f2lmt76Context _ayihockDbContext; // Services/Helpers private readonly JwtHelper _jwtHelper; private readonly LoginService _loginService; public LoginController(d5qp1l4f2lmt76Context ayihockDbContext, JwtHelper jwt, LoginService loginService, CustomerService customerService) { _ayihockDbContext = ayihockDbContext; _jwtHelper = jwt; _loginService = loginService; } /// <summary> /// 前台帳號登入(ApplyRole: anonymous) /// </summary> /// <returns></returns> [AllowAnonymous] [HttpPost("normal")] public async Task<ActionResult<string>> SignIn([FromBody] LoginDto login) { LoginDtoWithRole loginDtoWithRole = await _loginService.ValidateUser(login); if (loginDtoWithRole != null) { //整理jti黑名單資料 //bool ret = await _loginService.DeleteExpiredJti(30); //回傳JwtToken return Ok(_jwtHelper.GenerateToken(loginDtoWithRole.Email, loginDtoWithRole.Role, loginDtoWithRole.Name, (int)LoginPlatform.Original)); } else { return BadRequest(); } } /// <summary> /// 前台Google帳號登入(ApplyRole: anonymous) /// </summary> /// <returns></returns> [AllowAnonymous] [HttpPost("google")] public async Task<ActionResult<string>> SignInWithSocial([FromBody] SocialUser user) { //驗證GoogleToken並取得Payload var settings = new GoogleJsonWebSignature.ValidationSettings { Audience = new List<string>() { "730644139443-1s6dsft5mu2kf7l4bg5jscggjs2lmr18.apps.googleusercontent.com" } }; var payload = await GoogleJsonWebSignature.ValidateAsync(user.Token, settings); if (payload == null) return BadRequest("Google驗證失敗!"); //檢查帳號是否存在 (Yes:取回相關資訊 ; No:將此帳號加入DB) //最後回傳Jwt LoginDtoForSocial loginDtoForSocial = await _loginService.ValidateSocialUser(payload.Email, LoginPlatform.Google); if (loginDtoForSocial != null) { if (!loginDtoForSocial.IsBlack && loginDtoForSocial.Enable) { return Ok(_jwtHelper.GenerateToken(loginDtoForSocial.Email, loginDtoForSocial.Role, loginDtoForSocial.Name, (int)LoginPlatform.Google)); } else { return BadRequest("使用者為黑名單成員,無法操作!"); } } else { var customer = await _loginService.AddSocialUser(payload.Name, payload.Email, LoginPlatform.Google); return Ok(_jwtHelper.GenerateToken(customer.Email, customer.Role, customer.Name, (int)LoginPlatform.Google)); } } /// <summary> /// 後台帳號登入(ApplyRole: anonymous) /// </summary> /// <returns></returns> [AllowAnonymous] [HttpPost("admin")] public async Task<ActionResult<string>> AdminSignIn([FromBody] LoginDto login) { LoginDtoWithRole loginDtoWithRole = await _loginService.ValidateAdmin(login); if (loginDtoWithRole != null) { //整理jti黑名單資料 //bool ret = await _loginService.DeleteExpiredJti(30); //回傳JwtToken return Ok(_jwtHelper.GenerateToken(loginDtoWithRole.Email, loginDtoWithRole.Role, loginDtoWithRole.Name, (int)LoginPlatform.Original)); } else { return BadRequest(); } } [HttpPost("logout")] [Authorize("JtiRestraint")] [Authorize(Roles = "admin, staff, normal, golden, platinum, diamond")] public async Task<ActionResult> LogoutToken() { //var principal = _jwtHelper.GetPrincipalByAccessToken(token.Access); //if (principal == null) // return Ok("false"); var jti = User.Claims.FirstOrDefault(p => p.Type == JwtRegisteredClaimNames.Jti).Value.ToString(); var expire = Convert.ToInt32(User.Claims.FirstOrDefault(p => p.Type == JwtRegisteredClaimNames.Exp).Value.ToString()); await _loginService.SetJtiToBlackList(jti, expire); return Ok(); } } } <file_sep>/AyiHockWebAPI/Controllers/NewsController.cs using AyiHockWebAPI.Dtos; using AyiHockWebAPI.Filters; using AyiHockWebAPI.Models; using AyiHockWebAPI.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Controllers { [Route("api/[controller]")] [TypeFilter(typeof(ResultFormatFilter))] [ApiController] public class NewsController : ControllerBase { private readonly NewsService _newsService; public NewsController(NewsService newsService) { _newsService = newsService; } /// <summary> /// 查詢新聞列表(ApplyRole: anonymous) /// </summary> /// <returns></returns> [HttpGet] public async Task<ActionResult<List<NewsGetDto>>> Get() { var newses = await _newsService.GetNewsList(); if (newses == null || newses.Count() <= 0) return NotFound(); else return Ok(newses); } /// <summary> /// 查詢新聞(ApplyRole: anonymous) /// </summary> /// <returns></returns> [HttpGet("{id}")] public async Task<ActionResult<NewsGetDto>> Get(int id) { var newsById = await _newsService.GetNews(id); if (newsById == null) return NotFound(); else return Ok(newsById); } /// <summary> /// 新增新聞(ApplyRole: admin/staff) /// </summary> /// <returns></returns> [HttpPost] [Authorize("JtiRestraint")] [Authorize(Roles = "admin, staff")] public async Task<ActionResult> Post([FromBody] NewsPostDto value) { var manager = _newsService.GetManagerInfo(User.Identity.Name); if (manager == null) return BadRequest(); await _newsService.PostNews(manager, value); return NoContent(); } /// <summary> /// 修改新聞(ApplyRole: admin/staff) /// </summary> /// <returns></returns> [HttpPut("{id}")] [Authorize("JtiRestraint")] [Authorize(Roles = "admin, staff")] public async Task<ActionResult> Put(int id, [FromBody] NewsPutDto value) { var manager = _newsService.GetManagerInfo(User.Identity.Name); if (manager == null) return BadRequest(); var update = _newsService.GetNewsFullInfoFromDB(id); if (update != null) { await _newsService.PutNews(id, manager.ManagerId, update, value); } else { return NotFound(); } return NoContent(); } /// <summary> /// 刪除新聞(ApplyRole: admin/staff) /// </summary> /// <returns></returns> [HttpDelete("{id}")] [Authorize("JtiRestraint")] [Authorize(Roles = "admin, staff")] public async Task<ActionResult> Delete(int id) { var delete = await _newsService.DeleteNews(id); if (delete == null) return NotFound("NewsId不存在!"); else return NoContent(); } } } <file_sep>/AyiHockWebAPI/Dtos/CustomerDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Dtos { public class CustomerGetDto { public Guid CustomerId { get; set; } public string Name { get; set; } public string Email { get; set; } public string Phone { get; set; } public bool Enable { get; set; } public int Role { get; set; } public bool Isblack { get; set; } public int Money { get; set; } public Guid Modifier { get; set; } public DateTime CreateTime { get; set; } public DateTime ModifyTime { get; set; } public int Platform { get; set; } } public class CustomerGetByUserDto { public string Name { get; set; } public string Email { get; set; } public string Phone { get; set; } public bool Enable { get; set; } public int Role { get; set; } public DateTime ModifyTime { get; set; } } public class CustomerPostDto { public string Name { get; set; } public string Email { get; set; } public string Password { get; set; } public string Phone { get; set; } } public class CustomerPutByUserDto { public string Name { get; set; } public string Phone { get; set; } } public class CustomerPutPwdByUserDto { public string OldPassword { get; set; } public string NewPassword { get; set; } } public class CustomerPutPwdByForgetDto { public string UserAccountMail { get; set; } } public class CustomerPutPwdByResetDto { public string UserAccountMail { get; set; } public string DefaultPassword { get; set; } public string NewPassword { get; set; } } public class CustomerPutDto { public Guid CustomerId { get; set; } public bool Enable { get; set; } public int Role { get; set; } public bool Isblack { get; set; } public DateTime ModifyTime { get; set; } } } <file_sep>/AyiHockWebAPI/Services/CustomerService.cs using AyiHockWebAPI.Dtos; using AyiHockWebAPI.Helpers; using AyiHockWebAPI.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Services { public class CustomerService { private readonly d5qp1l4f2lmt76Context _ayihockDbContext; private readonly IConfiguration _configuration; private readonly EncryptDecryptHelper _encryptDecryptHelper; private readonly AutoSendEmailHelper _autoSendEmailHelper; public CustomerService(d5qp1l4f2lmt76Context ayihockDbContext, IConfiguration configuration, EncryptDecryptHelper encryptDecryptHelper, AutoSendEmailHelper autoSendEmailHelper) { _ayihockDbContext = ayihockDbContext; _configuration = configuration; _encryptDecryptHelper = encryptDecryptHelper; _autoSendEmailHelper = autoSendEmailHelper; } public Manager GetManagerInfo(string sub) { return _ayihockDbContext.Managers.Where(mgr => sub == mgr.Email).Select(mgr => mgr).FirstOrDefault(); } public Customer GetCustomerFullInfoByMail(string mail) { var customer = (from a in _ayihockDbContext.Customers where a.Email == mail && a.Platform == (int)LoginPlatform.Original select a).SingleOrDefault(); return customer; } public Customer GetCustomerFullInfoById(Guid id) { var customer = (from a in _ayihockDbContext.Customers where a.CustomerId == id select a).SingleOrDefault(); return customer; } public Customer GetCustomerFullInfoByOldPassword(string mail, string oldPassword) { var customer = (from a in _ayihockDbContext.Customers where a.Email == mail && a.Platform == (int)LoginPlatform.Original && a.Password == _encryptDecryptHelper.AESDecrypt(oldPassword).Replace("\"", "") select a).SingleOrDefault(); return customer; } public Customer GetCustomerFullInfoByPrePassword(string mail, string prePassword) { int randomCodeLength = _configuration.GetValue<int>("Encrypt:RandomCodeLength"); var customer = (from a in _ayihockDbContext.Customers where a.Email == mail && a.Platform == (int)LoginPlatform.Original && a.PrePassword.Length == randomCodeLength && a.PrePassword == prePassword select a).SingleOrDefault(); return customer; } public async Task<List<CustomerGetDto>> GetCustomerList() { var customers = await (from a in _ayihockDbContext.Customers select new CustomerGetDto { CustomerId = a.CustomerId, Name = a.Name, Email = a.Email, Phone = a.Phone, Enable = a.Enable, Role = a.Role, Isblack = a.Isblack, Money = a.Money, Modifier = a.Modifier, CreateTime = a.CreateTime, ModifyTime = a.ModifyTime, Platform = a.Platform }).OrderBy(a => a.CreateTime).ToListAsync(); return customers; } public async Task<CustomerGetDto> GetCustomerFromManager(Guid id) { var customerById = await (from a in _ayihockDbContext.Customers where a.CustomerId == id select new CustomerGetDto { CustomerId = a.CustomerId, Name = a.Name, Email = a.Email, Phone = a.Phone, Enable = a.Enable, Role = a.Role, Isblack = a.Isblack, Money = a.Money, Modifier = a.Modifier, CreateTime = a.CreateTime, ModifyTime = a.ModifyTime, Platform = a.Platform }).SingleOrDefaultAsync(); return customerById; } public async Task<CustomerGetByUserDto> GetCustomerFromUser(string sub) { var customerByMail = await (from a in _ayihockDbContext.Customers where a.Email == sub && a.Platform == (int)LoginPlatform.Original select new CustomerGetByUserDto { Name = a.Name, Email = a.Email, Phone = a.Phone, Enable = a.Enable, Role = a.Role, ModifyTime = a.ModifyTime }).SingleOrDefaultAsync(); return customerByMail; } public async Task PostCustomer(CustomerPostDto value) { Guid guid = Guid.NewGuid(); Customer customer = new Customer { CustomerId = guid, Name = value.Name, Email = value.Email, Password = _encryptDecryptHelper.AESDecrypt(value.Password).Replace("\"", ""), //需前端加密處理,後端解密 Phone = value.Phone, Enable = false, Isblack = false, Modifier = guid, CreateTime = DateTime.Now, ModifyTime = DateTime.Now }; _ayihockDbContext.Customers.Add(customer); await _ayihockDbContext.SaveChangesAsync(); string apiRoot = _configuration.GetValue<string>("URL:ApiRoot"); string authLink = "連結如下:\n" + apiRoot + "/api/customer/auth?varify=" + _encryptDecryptHelper.AESEncrypt(guid.ToString()); _autoSendEmailHelper.SendAuthEmail(value.Email, authLink); } public async Task<Customer> AuthCustomer(string varify) { //trans varifyStr to Guid Guid guid = Guid.Parse(_encryptDecryptHelper.AESDecrypt(varify)); //check Guid is exist? var customer = await (from a in _ayihockDbContext.Customers where a.CustomerId == guid && a.Enable == false select a).SingleOrDefaultAsync(); if (customer == null) { return null; } else { //modify Enable to 'true' customer.Enable = true; await _ayihockDbContext.SaveChangesAsync(); string url = _configuration.GetValue<string>("URL:Login"); System.Diagnostics.Process.Start("explorer", url); return customer; } } public async Task PutCustomerFromManager(Guid modifierId, CustomerPutDto value, Customer update) { update.CustomerId = value.CustomerId; update.Enable = value.Enable; update.Role = value.Role; update.Isblack = value.Isblack; update.ModifyTime = value.ModifyTime; update.Modifier = modifierId; await _ayihockDbContext.SaveChangesAsync(); } public async Task PutCustomerFromUser(CustomerPutByUserDto value, Customer update) { update.Name = value.Name; update.Phone = value.Phone; update.ModifyTime = DateTime.Now; update.Modifier = update.CustomerId; await _ayihockDbContext.SaveChangesAsync(); } public async Task PutCustomerNewPassword(string newPassword, Customer update) { update.Password = _encryptDecryptHelper.AESDecrypt(newPassword).Replace("\"", ""); //需前端加密處理,後端解密 update.PrePassword = ""; await _ayihockDbContext.SaveChangesAsync(); } public async Task PutCustomerResetPassword(string userMail, Customer update) { string prePwd = _encryptDecryptHelper.GetRandomStr(); update.PrePassword = prePwd; await _ayihockDbContext.SaveChangesAsync(); string resetPwdUri = _configuration.GetValue<string>("URL:ResetPwd"); string authLink = string.Format("驗證碼: {0},請至以下連結更改密碼\n,{1}", prePwd, resetPwdUri); _autoSendEmailHelper.SendAuthEmail(userMail, authLink); } public async Task<Customer> DeleteCustomer(Guid id) { var delete = GetCustomerFullInfoById(id); if (delete == null) return null; _ayihockDbContext.Customers.Remove(delete); await _ayihockDbContext.SaveChangesAsync(); return delete; } } } <file_sep>/AyiHockWebAPI/Models/Jtiblacklist.cs using System; using System.Collections.Generic; #nullable disable namespace AyiHockWebAPI.Models { public partial class Jtiblacklist { public string Jti { get; set; } public DateTime Expire { get; set; } } } <file_sep>/AyiHockWebAPI/Controllers/MealController.cs using AyiHockWebAPI.Dtos; using AyiHockWebAPI.Filters; using AyiHockWebAPI.Interface; using AyiHockWebAPI.Models; using AyiHockWebAPI.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.JsonPatch; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; using System.Threading.Tasks; namespace AyiHockWebAPI.Controllers { [Route("api/[controller]")] [TypeFilter(typeof(ResultFormatFilter))] [ApiController] public class MealController : ControllerBase { private readonly MealService _mealService; public MealController(MealService mealService) { _mealService = mealService; } /// <summary> /// 查詢菜單列表(ApplyRole: anonymous) /// </summary> /// <returns></returns> [HttpGet] public async Task<ActionResult<List<MealGetDto>>> Get() { var meals = await _mealService.GetMealList(); if (meals == null || meals.Count() <= 0) return NotFound(); else return Ok(meals); } /// <summary> /// 查詢菜單種類(ApplyRole: anonymous) /// </summary> /// <returns></returns> [HttpGet("types")] public async Task<ActionResult<List<Mealtype>>> GetTypes() { var types = await _mealService.GetMealTypes(); if (types == null || types.Count() <= 0) return NotFound(); else return Ok(types); } /// <summary> /// 查詢單一菜色(ApplyRole: anonymous) /// </summary> /// <returns></returns> [HttpGet("{id}")] public async Task<ActionResult<MealGetDto>> Get(int id) { var mealById = await _mealService.GetMeal(id); if (mealById == null) return NotFound(); else return Ok(mealById); } /// <summary> /// 查詢菜單列表(依菜單種類)(ApplyRole: anonymous) /// </summary> /// <returns></returns> [HttpGet("typeid/{type_id}")] public async Task<ActionResult<List<MealGetDto>>> GetByTypeId(int type_id) { var types = await _mealService.GetMealTypes(); if (type_id >= types.First().TypeId || type_id <= types.Last().TypeId) { var mealsByType = await _mealService.GetMealListByTypeId(type_id); if (mealsByType == null || mealsByType.Count() <= 0) { return NotFound(); } else { return Ok(mealsByType); } } else { return BadRequest(); } } /// <summary> /// 新增菜色(ApplyRole: admin/staff) /// </summary> /// <returns></returns> [HttpPost] [Authorize("JtiRestraint")] [Authorize(Roles = "admin, staff")] [ResourceTypeFilter] public async Task<ActionResult> Post([FromForm] MealPostDto value) { await _mealService.PostMeal(value); return Ok(); } /// <summary> /// 修改單一菜色(修改資訊+圖片)(ApplyRole: admin/staff) /// </summary> /// <returns></returns> [HttpPut("{id}")] [Authorize("JtiRestraint")] [Authorize(Roles = "admin, staff")] public async Task<ActionResult> PutAll(int id, [FromForm] MealPutTotalInfoDto value) { var update = _mealService.GetMealFullInfoFromDB(id); if (update != null) { await _mealService.PutMeal(update, value); return Ok(); } else { return NotFound(); } } /// <summary> /// 刪除單一菜色(ApplyRole: admin/staff) /// </summary> /// <returns></returns> [HttpDelete("{id}")] [Authorize("JtiRestraint")] [Authorize(Roles = "admin, staff")] public async Task<ActionResult> Delete(int id) { var delete = await _mealService.DisableMeal(id); if (delete == null) return NotFound("MealId不存在!"); else return Ok(); } } } <file_sep>/AyiHockWebAPI/Filters/ResourceTypeFilter.cs using AyiHockWebAPI.Dtos; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Filters { public class ResourceTypeFilter : Attribute, IResourceFilter { public void OnResourceExecuted(ResourceExecutedContext context) { //throw new NotImplementedException(); } public void OnResourceExecuting(ResourceExecutingContext context) { var files = context.HttpContext.Request.Form.Files; foreach (var file in files) { if (Path.GetExtension(file.FileName) != ".jpg" && Path.GetExtension(file.FileName) != ".bmp" && Path.GetExtension(file.FileName) != ".png" ) { context.Result = new JsonResult(new ResultDto { Success = false, Message = "400-檔案格式錯誤", Data = null }); } } } } } <file_sep>/AyiHockWebAPI/Startup.cs using AyiHockWebAPI.Helpers; using AyiHockWebAPI.Interface; using AyiHockWebAPI.Middleware; using AyiHockWebAPI.Models; using AyiHockWebAPI.Services; using AyiHockWebAPI.ValidationAttributes; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using StackExchange.Redis; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using static AyiHockWebAPI.ValidationAttributes.ValidJtiRequirement; namespace AyiHockWebAPI { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //注入Helper services.AddSingleton<JwtHelper>(); services.AddSingleton<EncryptDecryptHelper>(); services.AddSingleton<AutoSendEmailHelper>(); services.AddSingleton<ICloudStorage, GoogleCloudStorageHelper>(); //注入Service services.AddScoped<LoginService>(); services.AddScoped<MealService>(); services.AddScoped<NewsService>(); services.AddScoped<OrderService>(); services.AddScoped<CustomerService>(); services.AddScoped<ManagerService>(); //注入RadisService var multiplexer = ConnectionMultiplexer.Connect(Configuration.GetValue<string>("Radis:ConnectStr")); services.AddSingleton<IConnectionMultiplexer>(multiplexer); //PostgreSQL Connection services.AddDbContext<d5qp1l4f2lmt76Context>(options => options.UseNpgsql(Configuration.GetConnectionString("AyihockDB"))); //自訂Cors services.AddCors(option => { //Policy名稱CorsPolicy是自訂的,可以自己改 option.AddPolicy("CorsPolicy", policy => { //設定允許跨域的來源,有多個的話可以用`,`隔開 policy.AllowAnyMethod() .AllowAnyHeader() .SetIsOriginAllowed(origin => true) .AllowCredentials(); }); }); services.AddControllers(); //SwaggerDoc services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPI for AyiHockWebSite(Angular)", Version = "v1", Description = "Roles: Customer (normal/golden/platinum/diamond) ; Manager (admin/staff)" }); // 讀取 XML 檔案產生 API 說明 var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); //JWT驗證 services .AddAuthorization(options => { options.AddPolicy("JtiRestraint", policy => { policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme); policy.RequireAuthenticatedUser(); policy.Requirements.Add(new ValidJtiRequirement()); }); }) .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { // 當驗證失敗時,回應標頭會包含 WWW-Authenticate 標頭,這裡會顯示失敗的詳細錯誤原因 options.IncludeErrorDetails = true; // 預設值為 true,有時會特別關閉 options.TokenValidationParameters = new TokenValidationParameters { // 透過這項宣告,就可以從 "sub" 取值並設定給 User.Identity.Name NameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", // 透過這項宣告,就可以從 "roles" 取值,並可讓 [Authorize] 判斷角色 //RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/roles", RoleClaimType = ClaimTypes.Role, // 一般我們都會驗證 Issuer ValidateIssuer = true, ValidIssuer = Configuration.GetValue<string>("JwtSettings:Issuer"), // 通常不太需要驗證 Audience ValidateAudience = false, //ValidAudience = "JwtAuthDemo", // 不驗證就不需要填寫 // 一般我們都會驗證 Token 的有效期間 ValidateLifetime = true, // 如果 Token 中包含 key 才需要驗證,一般都只有簽章而已 ValidateIssuerSigningKey = true, // "1234567890123456" (16個字元) 並應從 IConfiguration 取得 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetValue<string>("JwtSettings:SignKey"))) }; }); services.AddTransient<IAuthorizationHandler, ValidJtiHandler>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //套用CatchException到Middleware app.UseMiddleware<CatchExceptionMiddleware>(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "AyiHockWebAPI v1"); }); //套用Policy到Middleware app.UseCors("CorsPolicy"); app.UseHttpsRedirection(); app.UseRouting(); //先驗證,再授權 app.UseAuthentication(); app.UseAuthorization(); //啟用靜態目錄 app.UseStaticFiles(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } } <file_sep>/AyiHockWebAPI/Controllers/ManagerController.cs using AyiHockWebAPI.Dtos; using AyiHockWebAPI.Filters; using AyiHockWebAPI.Helpers; using AyiHockWebAPI.Models; using AyiHockWebAPI.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Controllers { [Route("api/[controller]")] [TypeFilter(typeof(ResultFormatFilter))] [ApiController] public class ManagerController : ControllerBase { private readonly ManagerService _managerService; public ManagerController(ManagerService managerService) { _managerService = managerService; } /// <summary> /// 查詢管理人員列表(完整資料)(ApplyRole: admin) /// </summary> /// <returns></returns> [HttpGet] [Authorize("JtiRestraint")] [Authorize(Roles = "admin")] public async Task<ActionResult<List<ManagerGetTotalInfoDto>>> GetManagersTotalInfo() { var managers = await _managerService.GetManagersListTotalInfo(); if (managers == null || managers.Count() <= 0) return NotFound(); else return Ok(managers); } /// <summary> /// 查詢管理人員(完整資料)(ApplyRole: admin) /// </summary> /// <returns></returns> [HttpGet("{id}")] [Authorize("JtiRestraint")] [Authorize(Roles = "admin")] public async Task<ActionResult<ManagerGetTotalInfoDto>> GetManagerTotalInfo(Guid id) { var managerById = await _managerService.GetManagerTotalInfo(id); if (managerById == null) return NotFound(); else return Ok(managerById); } /// <summary> /// 查詢管理人員(基本資料)(ApplyRole: staff/admin) /// </summary> /// <returns></returns> [HttpGet("basicinfo")] [Authorize("JtiRestraint")] [Authorize(Roles = "admin, staff")] public async Task<ActionResult<ManagerGetBasicInfoDto>> GetUserBasicInfo() { var sub = User.Identity.Name; var managerById = await _managerService.GetManagerBasicInfo(sub); if (managerById == null) return NotFound(); else return Ok(managerById); } /// <summary> /// 新增管理人員(ApplyRole: admin) /// </summary> /// <returns></returns> [HttpPost] [Authorize("JtiRestraint")] [Authorize(Roles = "admin")] public async Task<ActionResult> Post([FromBody] ManagerPostDto value) { var manager = _managerService.GetManagerFullInfoByMail(value.Email); if (manager != null) return BadRequest(); await _managerService.PostManager(value); return Ok(); } /// <summary> /// 修改管理人員(ApplyRole: admin) /// </summary> /// <returns></returns> [HttpPut("{id}")] [Authorize("JtiRestraint")] [Authorize(Roles = "admin")] public async Task<ActionResult> Put(Guid id, [FromBody] ManagerPutDto value) { var manager = _managerService.GetManagerFullInfoByMail(value.Email); if (manager != null) return BadRequest(); var update = _managerService.GetManagerFullInfoById(id); if (update != null) { await _managerService.PutManager(update, value); return Ok(); } else { return NotFound(); } } /// <summary> /// 修改管理人員個人密碼(ApplyRole: staff/admin) /// </summary> /// <returns></returns> [HttpPut("pwd")] [Authorize("JtiRestraint")] [Authorize(Roles = "admin, staff")] public async Task<ActionResult> PutPwd([FromBody] ManagerPutPwdDto value) { var update = _managerService.GetManagerFullInfoByOldPassword(User.Identity.Name, value.OldPassword); if (update != null) { await _managerService.PutManagerNewPassword(value, update); return Ok(); } else { return BadRequest("舊帳號輸入錯誤!"); } } /// <summary> /// 重置管理人員個人密碼(ApplyRole: anonymous) /// </summary> /// <returns></returns> [HttpPut("pwdreset")] [AllowAnonymous] public async Task<ActionResult> PutPwdReset(string mail) { var update = _managerService.GetManagerFullInfoByMail(mail); if (update != null) { await _managerService.PutManagerResetPassword(mail, update); return Ok(); } else { return BadRequest("電子郵件輸入錯誤!"); } } /// <summary> /// 刪除管理人員(ApplyRole: admin) /// </summary> /// <returns></returns> [HttpDelete("{id}")] [Authorize("JtiRestraint")] [Authorize(Roles = "admin")] public async Task<ActionResult> Delete(Guid id) { var delete = await _managerService.DeleteManager(id); if (delete == null) return NotFound("CustomerId不存在!"); else return Ok(); } } } <file_sep>/AyiHockWebAPI/Services/NewsService.cs using AyiHockWebAPI.Dtos; using AyiHockWebAPI.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Services { public class NewsService { private readonly d5qp1l4f2lmt76Context _ayihockDbContext; public NewsService(d5qp1l4f2lmt76Context ayihockDbContext) { _ayihockDbContext = ayihockDbContext; } public News GetNewsFullInfoFromDB(int id) { var news = (from a in _ayihockDbContext.News where a.NewsId == id select a).SingleOrDefault(); return news; } public Manager GetManagerInfo(string sub) { return _ayihockDbContext.Managers.Where(mgr => sub == mgr.Email).Select(mgr => mgr).FirstOrDefault(); } public async Task<List<NewsGetDto>> GetNewsList() { var newses = await (from a in _ayihockDbContext.News select new NewsGetDto { NewsId = a.NewsId, Title = a.Title, Content = a.Content, ManagerName = _ayihockDbContext.Managers.Where(mgr => mgr.ManagerId == a.Manager).Select(mgr => mgr.Name).SingleOrDefault(), CreateTime = a.CreateTime, ModifyTime = a.ModifyTime, IsHot = a.IsHot, CategoryName = _ayihockDbContext.Newscategories.Where(cate => cate.NewsCategoryId == a.Category).Select(cate => cate.Name).SingleOrDefault() }).ToListAsync(); return newses; } public async Task<NewsGetDto> GetNews(int id) { var newsById = await (from a in _ayihockDbContext.News where a.NewsId == id select new NewsGetDto { NewsId = a.NewsId, Title = a.Title, Content = a.Content, ManagerName = _ayihockDbContext.Managers.Where(mgr => mgr.ManagerId == a.Manager).Select(mgr => mgr.Name).SingleOrDefault(), CreateTime = a.CreateTime, ModifyTime = a.ModifyTime, IsHot = a.IsHot, CategoryName = _ayihockDbContext.Newscategories.Where(cate => cate.NewsCategoryId == a.Category).Select(cate => cate.Name).SingleOrDefault() }).SingleOrDefaultAsync(); return newsById; } public async Task PostNews(Manager manager, NewsPostDto value) { News news = new News { Title = value.Title, Content = value.Content, Manager = manager.ManagerId, IsHot = value.IsHot, Category = value.CategoryId, CreateTime = DateTime.Now, ModifyTime = DateTime.Now }; _ayihockDbContext.News.Add(news); await _ayihockDbContext.SaveChangesAsync(); } public async Task PutNews(int id, Guid managerId, News update, NewsPutDto value) { update.NewsId = id; update.Title = value.Title; update.Content = value.Content; update.Manager = managerId; update.IsHot = value.IsHot; update.Category = value.CategoryId; update.ModifyTime = DateTime.Now; await _ayihockDbContext.SaveChangesAsync(); } public async Task<News> DeleteNews(int id) { var delete = GetNewsFullInfoFromDB(id); if (delete == null) return null; _ayihockDbContext.News.Remove(delete); await _ayihockDbContext.SaveChangesAsync(); return delete; } } } <file_sep>/AyiHockWebAPI/Services/MealService.cs using AyiHockWebAPI.Dtos; using AyiHockWebAPI.Interface; using AyiHockWebAPI.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Services { public class MealService { private readonly d5qp1l4f2lmt76Context _ayihockDbContext; private readonly IWebHostEnvironment _env; private readonly ICloudStorage _cloudStorage; public MealService(d5qp1l4f2lmt76Context ayihockDbContext, IWebHostEnvironment env, ICloudStorage cloudStorage) { _ayihockDbContext = ayihockDbContext; _env = env; _cloudStorage = cloudStorage; } public Meal GetMealFullInfoFromDB(int id) { var meal = (from a in _ayihockDbContext.Meals where a.MealId == id select a).SingleOrDefault(); return meal; } public async Task<List<MealGetDto>> GetMealList() { var meals = await (from a in _ayihockDbContext.Meals where a.Disable == false select new MealGetDto { MealId = a.MealId, Name = a.Name, Description = a.Description, Type = a.Type, Price = a.Price, PicPath = a.Picture }).ToListAsync(); return meals; } public async Task<List<MealTypeGetDto>> GetMealTypes() { var types = await (from a in _ayihockDbContext.Mealtypes select new MealTypeGetDto { TypeId = a.TypeId, Type = a.Type }).OrderBy(a => a.TypeId).ToListAsync(); return types; } public async Task<MealGetDto> GetMeal(int id) { var mealById = await (from a in _ayihockDbContext.Meals where a.MealId == id && a.Disable == false select new MealGetDto { MealId = a.MealId, Name = a.Name, Description = a.Description, Type = a.Type, Price = a.Price, PicPath = a.Picture }).SingleOrDefaultAsync(); return mealById; } public async Task<List<MealGetDto>> GetMealListByTypeId(int type_id) { var mealsByType = await (from a in _ayihockDbContext.Meals where a.Type == type_id && a.Disable == false select new MealGetDto { MealId = a.MealId, Name = a.Name, Description = a.Description, Type = a.Type, Price = a.Price, PicPath = a.Picture }).OrderBy(a => a.MealId).ToListAsync(); return mealsByType; } public async Task PostMeal(MealPostDto value) { var cloudImgPath = await _cloudStorage.UploadFileAsync(value.File, value.File.FileName); Meal meal = new Meal { Name = value.Meal.Name, Description = value.Meal.Description, Type = value.Meal.Type, Price = value.Meal.Price, Picture = cloudImgPath, Picturename = value.File.FileName }; _ayihockDbContext.Meals.Add(meal); await _ayihockDbContext.SaveChangesAsync(); } public async Task PutMeal(Meal update, MealPutTotalInfoDto value) { if (value.File != null) { var cloudImgPath = await _cloudStorage.UploadFileAsync(value.File, value.File.FileName); var oldImgName = update.Picturename; if (update.Picturename == value.File.FileName) { _ayihockDbContext.Meals.Update(update).CurrentValues.SetValues(value.Meal); await _ayihockDbContext.SaveChangesAsync(); } else { update.Name = value.Meal.Name; update.Price = value.Meal.Price; update.Type = value.Meal.Type; update.Description = value.Meal.Description; update.Picture = cloudImgPath; update.Picturename = value.File.FileName; await _ayihockDbContext.SaveChangesAsync(); await _cloudStorage.DeleteFileAsync(oldImgName); } } else { _ayihockDbContext.Meals.Update(update).CurrentValues.SetValues(value.Meal); await _ayihockDbContext.SaveChangesAsync(); } } public async Task<Meal> DisableMeal(int id) { var disableMeal = GetMealFullInfoFromDB(id); if (disableMeal == null) return null; disableMeal.Disable = true; await _ayihockDbContext.SaveChangesAsync(); return disableMeal; } } } <file_sep>/AyiHockWebAPI/Dtos/ManagerDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Dtos { public class ManagerGetTotalInfoDto { public Guid ManagerId { get; set; } public string Name { get; set; } public string Email { get; set; } public string Phone { get; set; } public bool Enable { get; set; } public bool IsAdmin { get; set; } } public class ManagerGetBasicInfoDto { public string Name { get; set; } public string Email { get; set; } public string Phone { get; set; } public bool IsAdmin { get; set; } } public class ManagerPostDto { public string Name { get; set; } public string Email { get; set; } public string Password { get; set; } public string Phone { get; set; } } public class ManagerPutDto { public string Name { get; set; } public string Email { get; set; } public string Phone { get; set; } public bool Enable { get; set; } } public class ManagerPutPwdDto { public string OldPassword { get; set; } public string NewPassword { get; set; } } } <file_sep>/AyiHockWebAPI/Models/d5qp1l4f2lmt76Context.cs using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; #nullable disable namespace AyiHockWebAPI.Models { public partial class d5qp1l4f2lmt76Context : DbContext { public d5qp1l4f2lmt76Context() { } public d5qp1l4f2lmt76Context(DbContextOptions<d5qp1l4f2lmt76Context> options) : base(options) { } public virtual DbSet<Customer> Customers { get; set; } public virtual DbSet<Customertype> Customertypes { get; set; } public virtual DbSet<Jtiblacklist> Jtiblacklists { get; set; } public virtual DbSet<Manager> Managers { get; set; } public virtual DbSet<Meal> Meals { get; set; } public virtual DbSet<Mealtype> Mealtypes { get; set; } public virtual DbSet<News> News { get; set; } public virtual DbSet<Newscategory> Newscategories { get; set; } public virtual DbSet<Order> Orders { get; set; } public virtual DbSet<Ordercontent> Ordercontents { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasAnnotation("Relational:Collation", "en_US.UTF-8"); modelBuilder.Entity<Customer>(entity => { entity.ToTable("customer"); entity.Property(e => e.CustomerId) .ValueGeneratedNever() .HasColumnName("customer_id"); entity.Property(e => e.CreateTime).HasColumnName("create_time"); entity.Property(e => e.Email) .IsRequired() .HasColumnName("email"); entity.Property(e => e.Enable).HasColumnName("enable"); entity.Property(e => e.Isblack).HasColumnName("isblack"); entity.Property(e => e.Modifier).HasColumnName("modifier"); entity.Property(e => e.ModifyTime).HasColumnName("modify_time"); entity.Property(e => e.Money).HasColumnName("money"); entity.Property(e => e.Name) .IsRequired() .HasColumnName("name"); entity.Property(e => e.Password) .IsRequired() .HasColumnName("password"); entity.Property(e => e.Phone) .IsRequired() .HasColumnName("phone"); entity.Property(e => e.Platform) .HasColumnName("platform") .HasComment("0: original\n1: Google\n2. Facebook"); entity.Property(e => e.PrePassword) .HasColumnName("pre_password") .HasDefaultValueSql("''::text"); entity.Property(e => e.Role).HasColumnName("role"); }); modelBuilder.Entity<Customertype>(entity => { entity.HasKey(e => e.TypeId) .HasName("customertype_pkey"); entity.ToTable("customertype"); entity.Property(e => e.TypeId) .ValueGeneratedNever() .HasColumnName("type_id"); entity.Property(e => e.Name) .IsRequired() .HasColumnName("name"); entity.Property(e => e.UpgradeLimit).HasColumnName("upgrade_limit"); }); modelBuilder.Entity<Jtiblacklist>(entity => { entity.HasKey(e => e.Jti) .HasName("jtiblacklist_pkey"); entity.ToTable("jtiblacklist"); entity.Property(e => e.Jti).HasColumnName("jti"); entity.Property(e => e.Expire).HasColumnName("expire"); }); modelBuilder.Entity<Manager>(entity => { entity.ToTable("manager"); entity.Property(e => e.ManagerId) .ValueGeneratedNever() .HasColumnName("manager_id"); entity.Property(e => e.Email) .IsRequired() .HasColumnName("email"); entity.Property(e => e.Enable).HasColumnName("enable"); entity.Property(e => e.IsAdmin).HasColumnName("is_admin"); entity.Property(e => e.Name) .IsRequired() .HasColumnName("name"); entity.Property(e => e.Password) .IsRequired() .HasColumnName("password"); entity.Property(e => e.Phone) .IsRequired() .HasColumnName("phone"); }); modelBuilder.Entity<Meal>(entity => { entity.ToTable("meal"); entity.HasIndex(e => e.Type, "fki_meals_type_fkey"); entity.Property(e => e.MealId).HasColumnName("meal_id"); entity.Property(e => e.Description) .IsRequired() .HasColumnName("description"); entity.Property(e => e.Disable) .HasColumnName("disable") .HasComment("是否為過時菜單\n是: 1\n否: 0"); entity.Property(e => e.Name) .IsRequired() .HasColumnName("name"); entity.Property(e => e.Picture) .IsRequired() .HasColumnName("picture"); entity.Property(e => e.Picturename) .IsRequired() .HasColumnName("picturename"); entity.Property(e => e.Price).HasColumnName("price"); entity.Property(e => e.Type).HasColumnName("type"); entity.HasOne(d => d.TypeNavigation) .WithMany(p => p.Meals) .HasForeignKey(d => d.Type) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("meal_type_fkey"); }); modelBuilder.Entity<Mealtype>(entity => { entity.HasKey(e => e.TypeId) .HasName("mealtype_pkey"); entity.ToTable("mealtype"); entity.Property(e => e.TypeId) .HasColumnName("type_id") .UseIdentityAlwaysColumn(); entity.Property(e => e.Type) .IsRequired() .HasColumnName("type"); }); modelBuilder.Entity<News>(entity => { entity.ToTable("news"); entity.HasIndex(e => e.Manager, "fki_News_Manager_fkey"); entity.HasIndex(e => e.Category, "fki_news_category_fkey"); entity.Property(e => e.NewsId) .HasColumnName("news_id") .UseIdentityAlwaysColumn(); entity.Property(e => e.Category).HasColumnName("category"); entity.Property(e => e.Content) .IsRequired() .HasColumnName("content"); entity.Property(e => e.CreateTime) .HasColumnName("create_time") .HasDefaultValueSql("now()"); entity.Property(e => e.IsHot).HasColumnName("is_hot"); entity.Property(e => e.Manager).HasColumnName("manager"); entity.Property(e => e.ModifyTime).HasColumnName("modify_time"); entity.Property(e => e.Title) .IsRequired() .HasColumnName("title"); entity.HasOne(d => d.CategoryNavigation) .WithMany(p => p.News) .HasForeignKey(d => d.Category) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("news_category_fkey"); entity.HasOne(d => d.ManagerNavigation) .WithMany(p => p.News) .HasForeignKey(d => d.Manager) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("news_Manager_fkey"); }); modelBuilder.Entity<Newscategory>(entity => { entity.ToTable("newscategory"); entity.Property(e => e.NewsCategoryId) .HasColumnName("news_category_id") .UseIdentityAlwaysColumn(); entity.Property(e => e.IsAdminChoose).HasColumnName("is_admin_choose"); entity.Property(e => e.Name) .IsRequired() .HasColumnName("name"); }); modelBuilder.Entity<Order>(entity => { entity.ToTable("order"); entity.Property(e => e.OrderId).HasColumnName("order_id"); entity.Property(e => e.CreateTime) .HasColumnName("create_time") .HasDefaultValueSql("CURRENT_TIMESTAMP"); entity.Property(e => e.ModifyTime) .HasColumnName("modify_time") .HasDefaultValueSql("CURRENT_TIMESTAMP"); entity.Property(e => e.Orderer).HasColumnName("orderer"); entity.Property(e => e.OrdererPhone) .IsRequired() .HasColumnName("orderer_phone"); entity.Property(e => e.Payrule) .HasColumnName("payrule") .HasComment("1: CreditCard\n2: LINE PAY\n3. GOOGLE PAY\n4. APPLE PAY"); entity.Property(e => e.Status).HasColumnName("status"); entity.Property(e => e.TotalPrice).HasColumnName("total_price"); }); modelBuilder.Entity<Ordercontent>(entity => { entity.ToTable("ordercontent"); entity.HasIndex(e => e.OrderId, "fki_ordercontent_orderid_fkey"); entity.Property(e => e.OrdercontentId) .HasColumnName("ordercontent_id") .HasDefaultValueSql("gen_random_uuid()"); entity.Property(e => e.MealId).HasColumnName("meal_id"); entity.Property(e => e.OrderId) .IsRequired() .HasColumnName("order_id"); entity.Property(e => e.Quantity).HasColumnName("quantity"); entity.HasOne(d => d.Order) .WithMany(p => p.Ordercontents) .HasForeignKey(d => d.OrderId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("order_id_fkey"); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } } <file_sep>/AyiHockWebAPI/Dtos/NewsDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Dtos { public class NewsGetDto { public int NewsId { get; set; } public string Title { get; set; } public string Content { get; set; } public string ManagerName { get; set; } public DateTime CreateTime { get; set; } public DateTime ModifyTime { get; set; } public bool IsHot { get; set; } public string CategoryName { get; set; } } public class NewsPostDto { public string Title { get; set; } public string Content { get; set; } public bool IsHot { get; set; } public int CategoryId { get; set; } } public class NewsPutDto { public string Title { get; set; } public string Content { get; set; } public bool IsHot { get; set; } public int CategoryId { get; set; } } } <file_sep>/AyiHockWebAPI/Models/News.cs using System; using System.Collections.Generic; #nullable disable namespace AyiHockWebAPI.Models { public partial class News { public int NewsId { get; set; } public string Title { get; set; } public string Content { get; set; } public Guid Manager { get; set; } public DateTime CreateTime { get; set; } public bool IsHot { get; set; } public int Category { get; set; } public DateTime ModifyTime { get; set; } public virtual Newscategory CategoryNavigation { get; set; } public virtual Manager ManagerNavigation { get; set; } } } <file_sep>/AyiHockWebAPI/Dtos/TokenDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AyiHockWebAPI.Dtos { public class TokenDto { public string Access { get; set; } public string Refresh { get; set; } } }
242556a202e55f1d1f8facbdbf5093d37fa07989
[ "C#" ]
39
C#
eugeneliu-dev/AyiHockWebAPI
efcdd1127271d036cd262a1e9c415965333f4efb
e5d730a7aff1793e87f09dcffccebb596e872d7f
refs/heads/master
<file_sep>import java.io.File; import java.io.FileNotFoundException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by boris on 05.05.16. */ public class DataReader { private static final Pattern PERFECTIVEGROUND = Pattern.compile("((ив|ивши|ившись|ыв|ывши|ывшись)|((?<=[ая])(в|вши|вшись)))$"); private static final Pattern REFLEXIVE = Pattern.compile("(с[яь])$"); private static final Pattern ADJECTIVE = Pattern.compile("(ее|ие|ые|ое|ими|ыми|ей|ий|ый|ой|ем|им|ым|ом|его|ого|ему|ому|их|ых|ую|юю|ая|яя|ою|ею)$"); private static final Pattern PARTICIPLE = Pattern.compile("((ивш|ывш|ующ)|((?<=[ая])(ем|нн|вш|ющ|щ)))$"); private static final Pattern VERB = Pattern.compile("((ила|ыла|ена|ейте|уйте|ите|или|ыли|ей|уй|ил|ыл|им|ым|ен|ило|ыло|ено|ят|ует|уют|ит|ыт|ены|ить|ыть|ишь|ую|ю)|((?<=[ая])(ла|на|ете|йте|ли|й|л|ем|н|ло|но|ет|ют|ны|ть|ешь|нно)))$"); private static final Pattern NOUN = Pattern.compile("(а|ев|ов|ие|ье|е|иями|ями|ами|еи|ии|и|ией|ей|ой|ий|й|иям|ям|ием|ем|ам|ом|о|у|ах|иях|ях|ы|ь|ию|ью|ю|ия|ья|я)$"); private static final Pattern RVRE = Pattern.compile("^(.*?[аеиоуыэюя])(.*)$"); private static final Pattern DERIVATIONAL = Pattern.compile(".*[^аеиоуыэюя]+[аеиоуыэюя].*ость?$"); private static final Pattern DER = Pattern.compile("ость?$"); private static final Pattern SUPERLATIVE = Pattern.compile("(ейше|ейш)$"); private static final Pattern I = Pattern.compile("и$"); private static final Pattern P = Pattern.compile("ь$"); private static final Pattern NN = Pattern.compile("нн$"); HashMap<String, Integer> generalCounter = new HashMap<String, Integer>(); private <K, V extends Comparable<? super V>> SortedSet<Map.Entry<K, V>> entriesSortedByValues(Map<K, V> map) { SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<Map.Entry<K, V>>( new Comparator<Map.Entry<K, V>>() { public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) { int res = e2.getValue().compareTo(e1.getValue()); return res != 0 ? res : 1; } } ); sortedEntries.addAll(map.entrySet()); return sortedEntries; } public void freqFeature(final File folder) throws FileNotFoundException { for (final File fileEntry : folder.listFiles()) { Scanner scanner = new Scanner(fileEntry); countFreq(scanner); } SortedSet<Map.Entry<String, Integer>> entrySortedSet = entriesSortedByValues(generalCounter); Iterator<Map.Entry<String, Integer>> iterator = entrySortedSet.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } private void countFreq(Scanner scanner) { while (scanner.hasNext()) { String token = stem(removePM(scanner.next())).toLowerCase(); if (generalCounter.containsKey(token)) { generalCounter.put(token, generalCounter.get(token) + 1); } else { generalCounter.put(token, 1); } } } public String stem(String word) { word = word.toLowerCase(); word = word.replace('ё', 'е'); Matcher m = RVRE.matcher(word); if (m.matches()) { String pre = m.group(1); String rv = m.group(2); String temp = PERFECTIVEGROUND.matcher(rv).replaceFirst(""); if (temp.equals(rv)) { rv = REFLEXIVE.matcher(rv).replaceFirst(""); temp = ADJECTIVE.matcher(rv).replaceFirst(""); if (!temp.equals(rv)) { rv = temp; rv = PARTICIPLE.matcher(rv).replaceFirst(""); } else { temp = VERB.matcher(rv).replaceFirst(""); if (temp.equals(rv)) { rv = NOUN.matcher(rv).replaceFirst(""); } else { rv = temp; } } } else { rv = temp; } rv = I.matcher(rv).replaceFirst(""); if (DERIVATIONAL.matcher(rv).matches()) { rv = DER.matcher(rv).replaceFirst(""); } temp = P.matcher(rv).replaceFirst(""); if (temp.equals(rv)) { rv = SUPERLATIVE.matcher(rv).replaceFirst(""); rv = NN.matcher(rv).replaceFirst("н"); } else { rv = temp; } word = pre + rv; } return word; } public String removePM(String word) { return word.replaceAll("[^\\p{L}]", ""); } } <file_sep>import java.io.File; import java.io.FileNotFoundException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by boris on 04.05.16. */ public class BayesClassifier { public Feature[] getFeatures() { return features; } private Feature[] features = { new Feature("наук"), new Feature("работ"), new Feature("теор"), new Feature("научн"), new Feature("учен"), new Feature("исследован"), new Feature("институт"), new Feature("университет"), new Feature("творчеств"), new Feature("литературн"), new Feature("писател"), new Feature("поэт"), new Feature("произведен"), }; public String classify(File file) { return ""; } private double[] calculateProbability(final File folder) throws FileNotFoundException { int[] checkList = new int[features.length]; double[] result = new double[features.length]; boolean[] flagList = new boolean[features.length]; for (int i = 0; i < features.length; i++) { checkList[i] = 0; flagList[i] = false; } for (final File fileEntry : folder.listFiles()) { Scanner scanner = new Scanner(fileEntry); for (int i = 0; i < flagList.length; i++) { flagList[i] = false; } DataReader dataReader = new DataReader(); while (scanner.hasNext()) { String token = dataReader.stem(dataReader.removePM(scanner.next())).toLowerCase(); for (int i = 0; i < features.length; i++) { if (features[i].getString().equals(token)) { flagList[i] = true; } } } for (int j = 0; j < flagList.length; j++) { if (flagList[j]) { checkList[j]++; } } } for (int j = 0; j < flagList.length; j++) { result[j] = (double) checkList[j] / folder.listFiles().length; } return result; } public static void main(String args[]) throws FileNotFoundException { File file = new File("/home/boris/task2/scientists"); //new BayesClassifier().freqFeature(file); BayesClassifier bayesClassifier = new BayesClassifier(); double pS[] = bayesClassifier.calculateProbability(new File("/home/boris/task2/scientists")); double pW[] = bayesClassifier.calculateProbability(new File("/home/boris/task2/writers")); for (int i = 0; i < bayesClassifier.features.length; i++) { bayesClassifier.features[i].setpScientist(pS[i]); bayesClassifier.features[i].setpWriter(pW[i]); // System.out.println(bayesClassifier.features[i].getString() + " pW = " + bayesClassifier.features[i].getpWriter() + // " pS = " + bayesClassifier.features[i].getpScientist()); } File test = new File("/home/boris/task2/writers/18833.txt"); Scanner scanner = new Scanner(test); double w = 1; double s = 1; DataReader dataReader = new DataReader(); while (scanner.hasNext()) { String token = dataReader.stem(dataReader.removePM(scanner.next())).toLowerCase(); for (int i = 0; i < bayesClassifier.features.length; i++) { if (token.equals(bayesClassifier.features[i].getString())) { w *= bayesClassifier.features[i].getpWriter(); s *= bayesClassifier.features[i].getpScientist(); } } } if (s > w){ System.out.println("ученый"); } else{ System.out.println("писатель"); } } } <file_sep>/** * Created by boris on 05.05.16. */ import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class LogisticRegression { /** * the learning rate */ private double rate; /** * the weight to learn */ private double[] weights; /** * the number of iterations */ private int ITERATIONS = 3000; private String[] features = { "наук", "работ", "теор", "научн", "учен", "исследован", "институт", "университет", "творчеств", "литературн", "писател", "поэт", "произведен" }; public LogisticRegression() { this.rate = 0.0001; weights = new double[features.length]; } private static double sigmoid(double z) { return 1.0 / (1.0 + Math.exp(-z)); } public void train(List<Instance> instances) { for (int n = 0; n < ITERATIONS; n++) { double lik = 0.0; for (int i = 0; i < instances.size(); i++) { int[] x = instances.get(i).x; double predicted = classify(x); int label = instances.get(i).label; for (int j = 0; j < weights.length; j++) { weights[j] = weights[j] + rate * (label - predicted) * x[j]; } // not necessary for learning lik += label * Math.log(classify(x)) + (1 - label) * Math.log(1 - classify(x)); } System.out.println("iteration: " + n + " " + Arrays.toString(weights) + " mle: " + lik); } } private double classify(int[] x) { double logit = .0; for (int i = 0; i < weights.length; i++) { logit += weights[i] * x[i]; } return sigmoid(logit); } public static class Instance { public int label; public int[] x; public Instance(int label, int[] x) { this.label = label; this.x = x; } } public int[] findFeatures(File file) throws FileNotFoundException { Scanner scanner = new Scanner(file); DataReader dataReader = new DataReader(); int[] data = new int[features.length]; for (int i = 0; i < data.length; i++ ){ data[i] = 0; } while (scanner.hasNext()) { String token = dataReader.stem(dataReader.removePM(scanner.next())).toLowerCase(); for (int i = 0; i < features.length ; i++) { if (token.equals(features[i])){ data[i] = 1; } } } return data; } public List<Instance> readDataSet(File folder, int cl) throws FileNotFoundException { List<Instance> dataset = new ArrayList<Instance>(); try { for (final File fileEntry : folder.listFiles()) { int data[] = findFeatures(fileEntry); int label = cl; Instance instance = new Instance(label, data); dataset.add(instance); } } catch (Exception e){ e.printStackTrace(); } return dataset; } public static void main(String... args) throws FileNotFoundException { List<Instance> instances = null; LogisticRegression logistic = new LogisticRegression(); try { instances = logistic.readDataSet(new File("/home/boris/task2/writers"),0); instances.addAll(logistic.readDataSet(new File("/home/boris/task2/scientists"), 1)); } catch (FileNotFoundException e) { e.printStackTrace(); } logistic.train(instances); int[] x = logistic.findFeatures(new File("/home/boris/task2/scientists/1222.txt")); System.out.println("prob(учёный) = " + logistic.classify(x)); System.out.println("prob(писатель) = " + (1-logistic.classify(x))); } }
2c0468e7d96313d48cba834ce0e13c21940eec07
[ "Java" ]
3
Java
borispinus/lang-task2
d73863ac701c7541ef781e7d19862320383aac40
ce914502e7dfa4112b13c6de8dfa8a48ac3e149d
refs/heads/master
<repo_name>OrhanKupusoglu/cell-distance<file_sep>/distance.py import os import csv import math class Distance(object): def __init__(self, file_name): self.debug = False self.file_name = file_name self.header = ['SC', 'NETWORK_ID', 'LAT', 'LON'] self.neigh_prefix = 'NEIGH' self.data = [] def get_output_filename(self): file_parts = os.path.splitext(self.file_name) return os.path.basename(file_parts[0]) + '.csv' def read_data(self): header = [] if not os.path.exists(self.file_name): raise Exception("data file is missing: '{}'".format(self.file_name)) with open(self.file_name, newline='') as f: # read header reader = csv.reader(f, delimiter=' ', skipinitialspace=True, quoting=csv.QUOTE_NONE) for row in reader: for name in row: header.append(name.upper()) break # check header if header != self.header: raise Exception('header line is missing or incorrect') # read data for row in reader: self.data.append({'SC': int(row[0]), 'NETWORK_ID': row[1], 'LAT': float(row[2]), 'LON': float(row[3])}) if self.debug: print('HEADER:', header) print('DATA:', self.data) def calculate_distance(self, location1, location2): lat1, lon1 = location1 lat2, lon2 = location2 radius = 6371 # radius of the earth dlat = math.radians(lat2 - lat1) dlon = math.radians(lon2 - lon1) #a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \ # * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2) a = math.sin(dlat / 2) ** 2 \ + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) ** 2 c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) d = radius * c return d def get_distance_matrix_with_sc(self, sc): group_sc = list(filter(lambda x: sc == x['SC'], self.data)) header_sc = [] matrix = [] for row in group_sc: matrix.append([None] * len(group_sc)) i = 0 j = 0 for hor in group_sc: j = 0 for ver in group_sc: if hor['NETWORK_ID'] == ver['NETWORK_ID']: matrix[i][j] = 0.0 header_sc.append(hor['NETWORK_ID']) else: if matrix[j][i] is None: matrix[i][j] = self.calculate_distance((hor['LAT'], hor['LON']), (ver['LAT'], ver['LON'])) else: # is already calculated matrix[i][j] = matrix[j][i] j = j + 1 i = i + 1 return (header_sc, matrix) # https://stackoverflow.com/a/38406223 def format_matrix(self, header, matrix, top_format, left_format, cell_format, row_delim, col_delim): table = [[''] + header] + [[name] + row for name, row in zip(header, matrix)] table_format = [['{:^{}}'] + len(header) * [top_format]] \ + len(matrix) * [[left_format] + len(header) * [cell_format]] col_widths = [max( len(format.format(cell, 0)) for format, cell in zip(col_format, col)) for col_format, col in zip(zip(*table_format), zip(*table))] return row_delim.join( col_delim.join( format.format(cell, width) for format, cell, width in zip(row_format, row, col_widths)) for row_format, row in zip(table_format, table)) def print_distance_with_sc(self, sc): header, matrix = self.get_distance_matrix_with_sc(sc) print(self.format_matrix(header, matrix, '{:^{}}', '{:<{}}', '{:>{}.3f}', '\n', ' | ')) def save_data(self): i = 0 max_neigh = 0 matrix = [] is_group_start = False for row in self.data: i = 0 if not matrix: is_group_start = True if is_group_start: is_group_start = False sc = row['SC'] _, matrix = self.get_distance_matrix_with_sc(sc) if self.debug: print('MATRIX:', matrix) matrix = list(reversed(matrix)) distances = matrix.pop() for distance in distances: i = i + 1 if i > max_neigh: max_neigh = i row[self.neigh_prefix.upper() + str(i)] = distance header = self.header for i in range(1, max_neigh + 1): header.append(self.neigh_prefix.upper() + str(i)) if self.debug: print('NEW HEADER:', header) for row in self.data: diff = len(header) - len(row) if diff > 0: for i in range(diff - 1, -1, -1): row[self.neigh_prefix + str(max_neigh - i)] = '' print(self.data) output = self.get_output_filename() if self.debug: print('OUTPUT FILE:', output) with open(output, 'w', newline='') as csvfile: fieldnames = header writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for row in self.data: writer.writerow(row) # execute only if run as a script if __name__ == "__main__": distance = Distance('data.txt') distance.read_data() #distance.print_distance_with_sc(0) distance.save_data()
e2ee5b0f7c662f145b1bdccd1d8e6279ae3620ba
[ "Python" ]
1
Python
OrhanKupusoglu/cell-distance
9a4fbb7e248a9d04b7961b1c3364fd3c7ff6bf32
31113d754b641330b2df6497316cd08212e81d4f
refs/heads/master
<file_sep>exports.helloWorld = function helloworld(req, res) { datastore = require('@google-cloud/datastore')({ projectId: 'southern-lane-170005' }); var q = datastore.createQuery('Todo'); q.run(function(err, entities, info){ res.send(entities); }) } <file_sep>exports.readCloudStorage = function helloWorld(req, res) { var storage = require('@google-cloud/storage'); var gcs = storage({ projectId: 'slider-165214' }); var bucket = gcs.bucket("sample-littlekbt"); var f = bucket.file('sample.json'); var s = ""; var readableStream = f.createReadStream(); readableStream.on('data', function(data) { s += data.toString(); }); readableStream.on('end', function() { res.send(s); }); }; <file_sep>/** * Responds to any HTTP request that can provide a "message" field in the body. * * @param {!Object} req Cloud Function request context. * @param {!Object} res Cloud Function response context. */ function intersection(a, b) { var c = []; a.forEach(function(e){ if(b.indexOf(e) >= 0){ c.push(e); } }) return c } // a: [1,2,3] // b: {1: "foo", 2: "bar"} let toName = (a, b) => a.map(aa => b[parseInt(aa)]); function getTags() { var query = datastore.createQuery('Tag'); return new Promise(function(resolve, reject){ datastore.runQuery(query, function(err, entities, info) { var tags = {} entities.forEach(function(entity){ tags[entity['id']] = entity['name']; }) resolve(tags) }) }) } function getTodos(query){ var requestTags = query['tags']; if(requestTags && requestTags.length > 0){ requestTags = requestTags.map(e => parseInt(e)) } var todos = []; // TODO: promise. must run after getTags. var q = datastore.createQuery('Todo'); if(query['todo']){ q = q.filter('name', query['todo']); } // IN is not supported... return new Promise(function(resolve, reject){ q.run(function(err, entities, info){ entities.forEach(function(entity){ // requestTagsがあった場合は絞り込みを行う if(requestTags) { if(intersection(requestTags, entity['tags']).length > 0){ todos.push({'name': entity['name'], 'tags': entity['tags'], 'created': entity['created']}); } }else{ todos.push({'name': entity['name'], 'tags': entity['tags'], 'created': entity['created']}); } }) resolve(todos); }) }); } function index(req, res) { return new Promise(function(resolve, reject) { // method chainではなく、順番を守りたいだけなので、asyncで対応 const async = require('async'); async.series([ function(callback) { getTags().then((tags) => callback(null, tags)); }, function(callback) { getTodos(req.query).then((todos) => callback(null, todos)); } ], function(err, results){ var tags = results[0]; var todos = results[1]; // todoのtagをtoname if (err) { reject(err) } else { resolve(JSON.stringify(todos.map((todo) => {return {'name': todo.name, 'tags': toName(todo.tags, tags), 'created': todo.created}}))); } }) }) } function invert(obj){ var r = {}; Object.keys(obj).forEach(function(key) { r[obj[key]] = key; }) return r } function findOrCreateTags(requestTags) { return new Promise(function(resolve, reject){ getTags().then(function(tags){ const tagIds = Object.keys(tags).map((e) => parseInt(e)).sort(); const tagKey = datastore.key(['Tag']); const now = Date.now(); var lastId = tagIds[tagIds.length - 1]; var newTags = []; var attachTags = []; const inverted = invert(tags); (requestTags || []).forEach(function(t) { if(!t[0] || !tags[t[0]]) { if(!t[1]){ reject("params not contain tag name"); return } // nullであっても名前の重複は許さない if(inverted[t[1]]) { attachTags.push(inverted[t[1]]); return; } newTags.push({key: tagKey, data: {id: ++lastId, name: t[1], created: now}}); } attachTags.push(t[0] || lastId) }); datastore.save(newTags, function(err, apiResponse){ if(err) { reject(err); } else { resolve(attachTags); } }) }); }); } // in // tags: [[1, "tag1"], [2, "tag2"], [null, "tag3"]] // name: "todo1" // out // {name: "todo1", tags: ["tag1", "tag2", "tag3"]} function create(req) { const params = req.body; return new Promise(function(resolve, reject){ findOrCreateTags(params['tags']).then(function(tags) { if (!params['name']) { reject("params not contain name."); return } const todoKey = datastore.key(['Todo']); const data = {name: params['name'], created: Date.now(), tags: tags}; datastore.save({key: todoKey, data: data}, function(err, apiResponse){ if(err) { reject(err); } else { getTags().then(function(tags){ resolve(JSON.stringify({'name': data.name, 'tags': toName(data.tags, tags), 'created': data.created})); }); } }); }) }); } // can update only todo // int // tags: [[1, "tag1"], [2, "tag2"]] // name: "todo1_update" // todo_id: xxxxx // out // {name: "todo1_update", tags: ["tag1", "tag2"]} function update(req) { const params = req.body; return new Promise(function(resolve, reject) { findOrCreateTags(params['tags']).then(function(tags) { if (!params['name']) { reject("params not contain name."); return } if (!params['todo_id']) { reject("params not contain todo_id."); return } const todoKey = datastore.key(['Todo', params['todo_id']]); const data = {name: params['name'], tags: tags, created: params['created']}; datastore.update({key: todoKey, data: data}, function(err, apiResponse){ if (err) { reject(err); } else { getTags().then(function(tags){ resolve(JSON.stringify({'name': data.name, 'tags': toName(data.tags, tags), 'created': data.created})); }); } }) }) }) } function del(req) { const params = req.body; return new Promise(function(resolve, reject) { if (!params['todo_id']) { reject("params not contain todo_id."); return } const todoKey = datastore.key(['Todo', params['todo_id']]); datastore.delete(todoKey, function(err, apiResponse){ if(err){ reject(err); }else{ resolve({status: "success"}); } }) }) } function onRejected(err){ console.log(err); } exports.todos = function todos (req, res) { datastore = require('@google-cloud/datastore')({ projectId: 'southern-lane-170005' }); switch(req.method) { case 'GET': index(req).then((jsonStr) => res.send(jsonStr)).catch((err) => {onRejected(err); res.send(err)}); break; case 'POST': create(req).then((jsonStr) => res.send(jsonStr)).catch((err) => {onRejected(err); res.send(err)}); break; case 'PATCH': update(req).then((jsonStr) => res.send(jsonStr)).catch((err) => {onRejected(err); res.send(err)}); break; case 'DELETE': del(req).then((jsonStr) => res.send(jsonStr)).catch((err) => {onRejected(err); res.send(err)}); break; } };
58103bfbe5458e0167d4a82f6000dfd9ef6aae95
[ "JavaScript" ]
3
JavaScript
coyote1782/cloud-functions
ddc1bc1d5ce3365d3fd3ef56f4df0a402e961a73
2ca2c3369324fe246bf220e2805d5346b86d30da
refs/heads/master
<file_sep> import numpy as np import pandas as pd from keras import backend as K K.set_image_dim_ordering('th') from keras.optimizers import SGD import os.path from keras.models import Model from keras.layers import Dense, GlobalAveragePooling2D from keras.applications.inception_v3 import InceptionV3 from keras.preprocessing.image import img_to_array, load_img metadata = pd.read_csv('/mnt/metadata_sf.csv') metadata.rename(columns={'id': 'image_id', 'datetaken': 'date_taken'}, inplace=True) def prepare_image(image_path): if os.path.exists(image_path): img = load_img(image_path, target_size=(224, 224)) # this is a PIL image array = img_to_array(img) return array metadata['img_path'] = '/mnt/images/' + metadata['image_id'].astype(str) + '.jpg' metadata['img_array'] = metadata['img_path'].apply(lambda row: prepare_image(row)) metadata = metadata[pd.notnull(metadata['img_array'])] x = np.asarray(metadata['img_array'].tolist()).reshape(len(metadata), 3, 224, 224) def creating_labels(x): if ('topic' in x): return x['topic'] elif ("nature" in str(x['tags_clean'])) or ("lake" in str(x['tags_clean'])) or ( "river" in str(x['tags_clean'])) or ("view" in str(x['tags_clean'])) or ( "beach" in str(x['tags_clean'])) or ("flowers" in str(x['tags_clean'])) or ( "landscape" in str(x['tags_clean'])) or ("waterfall" in str(x['tags_clean'])) or ( "sunrise" in str(x['tags_clean'])) or ("sunset" in str(x['tags_clean'])) or ( "water" in str(x['tags_clean'])) or ("nationalpark" in str(x['tags_clean'])) or ( "alaska" in str(x['tags_clean'])) or ("sky" in str(x['tags_clean'])) or ( "yosemite" in str(x['tags_clean'])) or ("mountains" in str(x['tags_clean'])): return 'Natural Landscape' elif ("birds" in str(x['tags_clean'])) or ("wild" in str(x['tags_clean'])) or ( "wildlife" in str(x['tags_clean'])) or ("forest" in str(x['tags_clean'])) or ( "animals" in str(x['tags_clean'])) or ("zoo" in str(x['tags_clean'])): return 'Animals & Birds' elif ("food" in str(x['tags_clean'])) or ("brunch" in str(x['tags_clean'])) or ( "dinner" in str(x['tags_clean'])) or ("lunch" in str(x['tags_clean'])) or ( "bar" in str(x['tags_clean'])) or ("restaurant" in str(x['tags_clean'])) or ( "drinking" in str(x['tags_clean'])) or ("eating" in str(x['tags_clean'])): return 'Food' elif ("urban" in str(x['tags_clean'])) or ("shop" in str(x['tags_clean'])) or ( "market" in str(x['tags_clean'])) or ("square" in str(x['tags_clean'])) or ( "building" in str(x['tags_clean'])) or ("citylights" in str(x['tags_clean'])) or ( "cars" in str(x['tags_clean'])) or ("traffic" in str(x['tags_clean'])) or ( "city" in str(x['tags_clean'])) or ("downtown" in str(x['tags_clean'])) or ( "sanfrancisco" in str(x['tags_clean'])) or ("newyork" in str(x['tags_clean'])) or ( "newyork" in str(x['tags_clean'])) or ("seattle" in str(x['tags_clean'])) or ( "sandiego" in str(x['tags_clean'])) or ("washington" in str(x['tags_clean'])): return 'Urban Scenes' elif ("hotel" in str(x['tags_clean'])) or ("home" in str(x['tags_clean'])) or ("interior" in str(x['tags_clean'])): return 'Interiors' elif ("us" in str(x['tags_clean'])) or ("people" in str(x['tags_clean'])) or ("group" in str(x['tags_clean'])) or ( "friends" in str(x['tags_clean'])): return 'people' else: return "Others" metadata['tags_clean'] = metadata['tags'].str.split() metadata = metadata.replace(np.nan, '', regex=True) metadata['labels'] = metadata.apply(creating_labels, axis=1) topics = metadata['labels'].unique().tolist() topics = list(set(topics) - set(['Others'])) metadata = metadata.loc[metadata['labels'].isin(topics)] metadata['labels'].value_counts() label_map = d = {x: i for i, x in enumerate(topics)} y = metadata['labels'].apply(lambda row: label_map[row]) y.value_counts() from sklearn.model_selection import train_test_split from keras.utils import np_utils num_classes = 6 x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=13) # Transform targets to keras compatible format y_train = np_utils.to_categorical(y_train, num_classes) y_test = np_utils.to_categorical(y_test, num_classes) # create the base pre-trained model base_model = InceptionV3(weights='imagenet', include_top=False) # add a global spatial average pooling layer x = base_model.output x = GlobalAveragePooling2D()(x) # let's add a fully-connected layer x = Dense(1024, activation='relu')(x) # and a logistic layer -- let's say we have 200 classes predictions = Dense(6, activation='softmax')(x) # this is the model we will train model = Model(inputs=base_model.input, outputs=predictions) # first: train only the top layers (which were randomly initialized) # i.e. freeze all convolutional InceptionV3 layers for layer in base_model.layers: layer.trainable = False # compile the model (should be done *after* setting layers to non-trainable) model.compile(optimizer='rmsprop', loss='categorical_crossentropy') # train the model on the new data for a few epochs model.fit(x_train, y_train, nb_epoch=2, verbose=1, validation_data=(x_test, y_test)) # at this point, the top layers are well trained and we can start fine-tuning # convolutional layers from inception V3. We will freeze the bottom N layers # and train the remaining top layers. # let's visualize layer names and layer indices to see how many layers # we should freeze: # for i, layer in enumerate(base_model.layers): # print(i, layer.name) # we chose to train the top 2 inception blocks, i.e. we will freeze # the first 249 layers and unfreeze the rest: for layer in model.layers[:249]: layer.trainable = False for layer in model.layers[249:]: layer.trainable = True # we need to recompile the model for these modifications to take effect # we use SGD with a low learning rate model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy', metrics=['accuracy']) # we train our model again (this time fine-tuning the top 2 inception blocks # alongside the top Dense layers model.fit(x_train, y_train, nb_epoch=30, verbose=1, validation_data=(x_test, y_test)) model.save_weights('/mnt/cnn_2epoch_1210.1') y_true, y_pred = y_test, model.predict(x_test) <file_sep>import numpy as np import pandas as pd from geopy.distance import great_circle from scipy import spatial from sklearn.cluster import DBSCAN # Read metadata and clean metadata = pd.read_csv('/mnt/metadata.csv') metadata['tags_clean'] = metadata['tags'].str.split() metadata = metadata.replace(np.nan, '', regex=True) # Create labels from tags in the metadata def creating_labels(x): if ("nature" in str(x['tags_clean'])) or ("lake" in str(x['tags_clean'])) or ("river" in str(x['tags_clean'])) or ( "view" in str(x['tags_clean'])) or ("beach" in str(x['tags_clean'])) or ( "flowers" in str(x['tags_clean'])) or ("landscape" in str(x['tags_clean'])) or ( "waterfall" in str(x['tags_clean'])) or ("sunrise" in str(x['tags_clean'])) or ( "sunset" in str(x['tags_clean'])) or ("water" in str(x['tags_clean'])) or ( "nationalpark" in str(x['tags_clean'])) or ("alaska" in str(x['tags_clean'])) or ( "sky" in str(x['tags_clean'])) or ("yosemite" in str(x['tags_clean'])) or ( "mountains" in str(x['tags_clean'])): return 'Natural Landscape' elif ("birds" in str(x['tags_clean'])) or ("wild" in str(x['tags_clean'])) or ( "wildlife" in str(x['tags_clean'])) or ("forest" in str(x['tags_clean'])) or ( "animals" in str(x['tags_clean'])) or ("zoo" in str(x['tags_clean'])): return 'Animals & Birds' elif ("food" in str(x['tags_clean'])) or ("brunch" in str(x['tags_clean'])) or ( "dinner" in str(x['tags_clean'])) or ("lunch" in str(x['tags_clean'])) or ( "bar" in str(x['tags_clean'])) or ("restaurant" in str(x['tags_clean'])) or ( "drinking" in str(x['tags_clean'])) or ("eating" in str(x['tags_clean'])): return 'Food' elif ("urban" in str(x['tags_clean'])) or ("shop" in str(x['tags_clean'])) or ( "market" in str(x['tags_clean'])) or ("square" in str(x['tags_clean'])) or ( "building" in str(x['tags_clean'])) or ("citylights" in str(x['tags_clean'])) or ( "cars" in str(x['tags_clean'])) or ("traffic" in str(x['tags_clean'])) or ( "city" in str(x['tags_clean'])) or ("downtown" in str(x['tags_clean'])) or ( "sanfrancisco" in str(x['tags_clean'])) or ("newyork" in str(x['tags_clean'])) or ( "newyork" in str(x['tags_clean'])) or ("seattle" in str(x['tags_clean'])) or ( "sandiego" in str(x['tags_clean'])) or ("washington" in str(x['tags_clean'])): return 'Urban Scenes' elif ("hotel" in str(x['tags_clean'])) or ("home" in str(x['tags_clean'])) or ("interior" in str(x['tags_clean'])): return 'Interiors' elif ("us" in str(x['tags_clean'])) or ("people" in str(x['tags_clean'])) or ("group" in str(x['tags_clean'])) or ( "friends" in str(x['tags_clean'])): return 'people' else: return "Others" metadata['labels'] = metadata.apply(creating_labels, axis=1) metadata['labels'].value_counts() # Spatial clusters based on the histogram data = metadata[['latitude', 'longitude']] db = DBSCAN(eps=0.06, min_samples=5, metric='haversine', algorithm='ball_tree') db.fit(data) np.unique(db.labels_, return_counts=True) metadata['dblabel'] = db.labels_ dblabel_counts = metadata.groupby(['dblabel'])['image_id'].count().reset_index() list_mean = metadata.groupby(['dblabel'])['latitude', 'longitude'].mean().reset_index() list_mean = list_mean.rename(columns={'latitude': 'mean_lat', 'longitude': 'mean_long'}) metadata = metadata.merge(list_mean, left_on='dblabel', right_on='dblabel') # Temporal bins def temporal_bins(x): if (x['hod'] > 0 and x['hod'] <= 6): return 'dawn' elif (x['hod'] > 6 and x['hod'] <= 10): return 'morning' elif (x['hod'] > 10 and x['hod'] <= 14): return 'noon' elif (x['hod'] > 14 and x['hod'] <= 18): return 'dusk' elif (x['hod'] > 18 and x['hod'] <= 23): return 'night' metadata['date_taken'] = pd.to_datetime(metadata['date_taken']) metadata['hod'] = [r.hour for r in metadata.date_taken] metadata['hour_bins'] = metadata.apply(temporal_bins, axis=1) # No. of images based on spatial clusters, temporal binning and categories identified from tags grouped = metadata.groupby(['labels', 'dblabel', 'hour_bins']).agg({'image_id': 'count', 'views': 'sum'}).reset_index() grouped = pd.merge(grouped, dblabel_counts, left_on='dblabel', right_on='dblabel') grouped = grouped.rename(columns={'image_id_x': 'num_images', 'image_id_y': 'pts_clusters'}) grouped.head() # Get nearby categorized clusters based on a location # input - location and time # find the no. of cluster based on the location and time # ouput images based on categories in that cluster def get_filtered(lat, long, time): point1 = (lat, long) metadata['lat_long'] = metadata[['latitude', 'longitude']].apply(tuple, axis=1) metadata['mean_lat_long'] = metadata[['mean_lat', 'mean_long']].apply(tuple, axis=1) metadata['distances'] = [int(great_circle(point1, point).miles) for point in metadata['mean_lat_long']] filtered = metadata[(metadata['distances'] <= 20) & (metadata['hour_bins'] == time)] grouped = filtered.groupby(['dblabel', 'labels']).agg({'image_id': 'count', 'views': 'sum'}).reset_index() return filtered get_filtered(37.7845212, -122.399388, 'morning') def radius_pts(list_pts): list_diff = [] difference = 0 for point1 in list_pts: for point2 in list_pts: difference = abs(int(great_circle(point1, point2).miles)) list_diff.append(difference) diameter = max(list_diff) return diameter x = metadata.groupby(['dblabel'])['lat_long'].apply(radius_pts) data = metadata[['latitude', 'longitude']] kdtree = spatial.KDTree(data) kdtree.data pts = [40.750277, -73.987777] kdtree.query(pts, k=5, eps=3.0, distance_upper_bound=5.0) metadata.to_csv('/mnt/flask_data.csv') <file_sep>import argparse import logging import os import re import time from urllib.error import URLError from urllib.request import urlretrieve import pandas as pd from flickrapi import FlickrAPI from tqdm import tqdm FLICKR_PUBLIC = '<KEY>' FLICKR_SECRET = '<KEY>' def pull_images(metadata: str, image_dir: str) -> None: """ This function takes a CSV file containing image metadata. It should contain a column named image_id :param metadata: The CSV file containing image metadata :param image_dir: Directory to store all images. """ flickr = FlickrAPI(FLICKR_PUBLIC, FLICKR_SECRET, format='parsed-json') df = pd.read_csv(metadata) df['image_id'] = df['image_id'].astype(str) done_lines = os.listdir(image_dir) done_lines = [re.sub('.jpg', '', x) for x in done_lines] pending_lines = list(set(df['image_id'].tolist()) - set(done_lines)) for row in tqdm(pending_lines): image_id = row.strip() try: file_location = image_dir + image_id + '.jpg' image = flickr.photos.getinfo(photo_id=image_id) secret = image['photo']['secret'] server = image['photo']['server'] farm_id = image['photo']['farm'] urlretrieve('https://farm%s.staticflickr.com/%s/%s_%s.jpg' % (farm_id, server, image_id, secret), file_location) time.sleep(0.2) except (KeyError, URLError): logging.error('error while processing %s' % (image_id)) logging.info('Done downloading images') def main(): parser = argparse.ArgumentParser(description="Utility to generate images dataset") parser.add_argument('--metadata', '-m', required=True, help="CSV file containing image metadata") parser.add_argument('--out', '-o', required=True, help="location for images") args = parser.parse_args() if not os.path.isdir(args.out): logging.info("%s does not exist. Creating it." % args.out) os.mkdir(args.out) pull_images(args.metadata, args.out) if __name__ == '__main__': main() <file_sep># SnapLoc SnapLoc — Personalized recommender for Points of Interest in a city SNAPLOC is a product that I have created as a final project of a data science bootcamp, Metis. It does automatic picture classification and spatio temporal analysis in order to recommend the places of interest for traveling in a new city. I have been a traveler to a new city and felt a need to know about the most interesting places to explore near me and have looked at photos of other people and said I want to go there to capture this beautiful picture of bear in dawn, if feasible. Folder named Code contains three files: 1. Flickr_getimages - Code to download geo-tagged images and it's metadata from Flickr 2. Image_Classification - Code to do the VGG classification of images 3. Spatial_clustering - Code for doing spatial clustering using DBSCAN and the cluster visualization & ranking. Folder named Data contains metadata of images downloaded for San Francisco from Flickr as well as tables created for analysis of clusters of images formed.
fd55195344774128fcde82b395027cc2767d97a1
[ "Markdown", "Python" ]
4
Python
kalgishah02/SnapLoc
668238d0713d62441f7fe7df201437d95c8b746c
6473e8536647147e895ed6ffc2f7f8ceb8bfa397
refs/heads/master
<file_sep>const config = { secret: 'SECRET_CODE', host: 'localhost', port: 8080, public: '../public/', paginate: { default: 10, max: 50 }, googleAPI: { developerToken: "GOOGLE_API_DEVELOPER_TOKEN", client_id: "GOOGLE_API_CLIENT_ID", client_secret: "GOOGLE_API_CLIENT_SECRET", redirect_url: "YOUR_APP_URL" }, facebookAPI: { appId: 'FACEBOOK_API_APP_ID', appSecret: 'FACEBOOK_API_APP_SECRET', }, superMetrics: { functionsAPI: "SUPER_METRICS_FUNCTIONS_API", api: "SUPER_METRICS_API" }, whitelist: ['WHITELIST'], database: { host: 'database-host', user: 'database-user', password: '<PASSWORD>', database: 'database-name' }, monitorInstanceActive: true, sendGridAPI: 'SEND_GRID_API' }; export const templates = { GOOGLE_ADS_HISTORICAL_QUALITY_SCORE: 'YOUR_GOOGLE_ADS_HISTORICAL_REPORT', HIGH_LEVEL_PPC_REPORT: 'YOUR_HIGH_LEVEL_PPC_REPORT' }; export default config; <file_sep>const config = { secret: 'SECRET_CODE', host: 'localhost', port: 8080, public: '../public/', paginate: { default: 10, max: 50 }, googleAPI: { developerToken: "<KEY>", client_id: "280956389765-kr19ld07fbjukaqrji9eke96em13i9fa.apps.googleusercontent.com", client_secret: "<KEY>", redirect_url: "http://localhost:4200/auth-verification" }, facebookAPI: { appId: 'FACEBOOK_API_APP_ID', appSecret: 'FACEBOOK_API_APP_SECRET', }, superMetrics: { functionsAPI: "SUPER_METRICS_FUNCTIONS_API", api: "SUPER_METRICS_API" }, whitelist: ['WHITELIST'], database: { host: '192.168.127.12', user: 'root', password: '<PASSWORD>', database: 'powerads' }, monitorInstanceActive: true, sendGridAPI: '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' }; export config;
877da5c50e4fb4047205996eb357a6503df864ad
[ "TypeScript" ]
2
TypeScript
RomanMykytyn/Waste
9b3373b4ea1ee3df73d2b6232914a3aaa3bf7ca6
96b38fe079d89571e7993324937005dfde00f887
refs/heads/main
<repo_name>Khaled-elias/testNode<file_sep>/main.js // const khaled = require('./arry') const dima = require('./data') const singup = require('./singup') // console.log(khaled) // console.log("hallo khaled") // console.log(__dirname) // console.log(__filename) // // console.log(module) // const hello = () => console.log("hallo") // hello() // console.log(dima.kido) console.log(dima) // dima.georg() console.log(singup("batman")) console.log(singup("rafif"))<file_sep>/singup.js const singup=(myname)=>{ return `wllcome ${myname} you are with us` } module.exports = singup
fb621051bfd8997a5a9d0a1727d2bc7b96bf356c
[ "JavaScript" ]
2
JavaScript
Khaled-elias/testNode
8a44badfb10f1b906aa5d3bf294bc432d9e51bf2
1dc1a40d9787aac46ea39c8269b5cc2fc6c3c718
refs/heads/master
<repo_name>rikoroku/never_look<file_sep>/nl.sh #!/bin/sh set -e readonly FILE="targets.txt" readonly HOSTS="/etc/hosts" readonly PW="${NL_SUDO_PW}" function usage { cat <<EOF $(basename ${0}) is a tool for ... Usage: $(basename ${0}) [command] [<options>] Options: --version, -v print $(basename ${0}) version --help, -h print this --start start never look --stop stop never look EOF exit 1 } function version { echo "$(basename ${0}) version 1.0.0" } function pw_exists { if [ -z "$PW" ]; then echo "You must set the sudo password as '<PASSWORD>' of the environment variable." exit 1 fi } function completed { echo "Completed." } function start { pw_exists cat $FILE | while read line do echo "127.0.0.1 $line" | { echo "$PW"; cat; } | sudo -S tee -a $HOSTS &>/dev/null done # To prevent "$PW" from writing at the same time. echo "$PW" | sudo -S sed -i '' '/'$PW'/d' $HOSTS &>/dev/null completed } function stop { pw_exists cat $FILE | while read line do echo "$PW" | sudo -S sed -i '' '/'$line'/d' $HOSTS &>/dev/null done completed } while [ $# -gt 0 ]; do case ${1} in --start) start ;; --stop) stop ;; --version|-v) version ;; --help|-h) usage ;; *) echo "Try to enter the -h option." 1>&2 ;; esac shift done <file_sep>/README.md # never_look I don't want to waste time. So, I made this. This is a tool that doesn't spend wasted time on social networks. ## Premises This is supposed to run on OS X. ## Installation ``` $ git clone https://github.com/rikoroku/never_look.git $ cd never_look $ export NL_SUDO_PW="<PASSWORD>" ``` ## Usage help: ``` $ sh nl.sh -h nl.sh is a tool for ... Usage: nl.sh [command] [<options>] Options: --version, -v print nl.sh version --help, -h print this --start start never look --stop stop never look ``` Add URL for SNS that you don't want to see. ※ Please enter one URL per line ``` $ vi targets.txt Example--------------- twitter.com www.youtube.com ---------------------- ``` ## Recommend You use cron to operate at a constant time every day. ``` $ chmod 755 nl.sh targets.txt $ vi ~/.bash_profile Note------------------ # Add the following line export NL_SUDO_PW="<PASSWORD>" ---------------------- $ crontab -e Note------------------ 00 07 * * * /bin/bash -l -c 'cd $HOME/Documents/git/never_look && sh nl.sh --start' 00 19 * * * /bin/bash -l -c 'cd $HOME/Documents/git/never_look && sh nl.sh --stop' ---------------------- ``` ## Contributing 1. Fork it ( https://github.com/rikoroku/never_look ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request Bug reports and pull requests are welcome. ## License The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
b110e93e6a288c1889fc9dc050835e16d5031ec1
[ "Markdown", "Shell" ]
2
Shell
rikoroku/never_look
667aac8da1f03ec8d4df9cbe2d14b5ee4898d064
728220f5511e744794bd4a7531d1b74b75a7e3ad
refs/heads/master
<file_sep>from typing import Protocol import numpy as np import pandas as pd from cjwmodule.util.colnames import gen_unique_clean_colnames from pandas.api.types import is_datetime64_dtype SupportedNumberDtypes = frozenset( { np.dtype("float16"), np.dtype("float32"), np.dtype("float64"), np.dtype("int8"), np.dtype("int16"), np.dtype("int32"), np.dtype("int64"), np.dtype("uint8"), np.dtype("uint16"), np.dtype("uint32"), np.dtype("uint64"), } ) class Settings(Protocol): MAX_BYTES_PER_COLUMN_NAME: int = 100 class DefaultSettings(Settings): pass def validate_series(series: pd.Series) -> None: """Ensure `series` is Workbench "Pandas-valid", or raise ValueError. "Workbench Pandas-Valid" means: * If dtype is `object` or `categorical`, all values are `str`, `np.nan` or `None` * Otherwise, series must be numeric (but not "nullable integer"), period[D] or datetime64[ns] (without timezone). """ dtype = series.dtype if dtype in SupportedNumberDtypes: infinities = series.isin([np.inf, -np.inf]) if infinities.any(): idx = series[infinities].index[0] raise ValueError( ("invalid value %r in column %r, row %r " "(infinity is not supported)") % (series[idx], series.name, idx) ) return elif is_datetime64_dtype(dtype): # rejects datetime64ns return elif pd.PeriodDtype(freq="D") == dtype: return elif dtype == object: nonstr = series[~series.isnull()].map(type) != str if nonstr.any(): raise ValueError( "invalid value %r in column %r (object values must all be str)" % (series.iloc[nonstr[nonstr == True].index[0]], series.name) ) elif hasattr(series, "cat"): categories = series.cat.categories if categories.dtype != object: raise ValueError( ( "invalid categorical dtype %s in column %r " "(categories must have dtype=object)" ) % (categories.dtype, series.name) ) nonstr = categories.map(type) != str if nonstr.any(): raise ValueError( "invalid value %r in column %r (categories must all be str)" % (categories[np.flatnonzero(nonstr)[0]], series.name) ) # Detect unused categories: they waste space, and since the module # author need only .remove_unused_categories() there isn't much reason # to allow them (other than the fact this check might be slow?). codes = np.unique(series.cat.codes) # retval is sorted if len(codes) and codes[0] == -1: codes = codes[1:] # At this point, if all categories are used, `codes` is an Array of # [0, 1, ..., len(categories)-1]. Otherwise, there's a "hole" somewhere # in `codes` (it may be at the end). if len(codes) != len(categories): # There are unused categories. That means an index into # `categories` is not in `codes`. Raise it. for i, category in enumerate(categories): if i >= len(codes) or codes[i] != i: raise ValueError( ( "unused category %r in column %r " "(all categories must be used)" ) % (category, series.name) ) # we can't get here assert False # pragma: no cover else: raise ValueError("unsupported dtype %r in column %r" % (dtype, series.name)) def validate_dataframe( df: pd.DataFrame, settings: Settings = DefaultSettings() ) -> None: """Ensure `df` is Workbench "Pandas-valid", or raise ValueError. "Workbench Pandas-Valid" means: * All column names are str * All column names are unique * No column names are "" * The index is a RangeIndex starting at 0 * All columns are "Pandas-valid". The ValueError is not i18n-ized. These errors are targeted at people who programmed buggy Python code. Python is English-only. """ if df.columns.dtype != object or not (df.columns.map(type) == str).all(): raise ValueError("column names must all be str") for colname, uccolname in zip( list(df.columns), gen_unique_clean_colnames(list(df.columns), settings=settings) ): if uccolname.is_ascii_cleaned: raise ValueError( 'column name "%s" must not contain ASCII control characters' % colname ) if uccolname.is_unicode_fixed: # `str("x \ud800 x")` doesn't crash, so this ValueError should be safe to print raise ValueError( 'column name "%s" must not contain invalid Unicode surrogates' % colname, ) if uccolname.is_default: raise ValueError('column name "%s" must not be empty' % colname) if uccolname.is_truncated: raise ValueError( 'column name "%s" must contain %d bytes or fewer' % ( colname, settings.MAX_BYTES_PER_COLUMN_NAME, ) ) if uccolname.is_numbered: raise ValueError( 'column name "%s" must not appear more than once' % colname ) if not df.index.equals(pd.RangeIndex(0, len(df))): raise ValueError( "must use the default RangeIndex — " "try table.reset_index(drop=True, inplace=True)" ) for column in df.columns: validate_series(df[column]) <file_sep>from datetime import date import numpy as np import pandas as pd import pytest from cjwpandasmodule.validate import validate_dataframe def test_index(): with pytest.raises(ValueError, match="must use the default RangeIndex"): validate_dataframe(pd.DataFrame({"A": [1, 2]})[1:]) def test_non_str_objects(): with pytest.raises(ValueError, match="must all be str"): validate_dataframe(pd.DataFrame({"foo": ["a", 1]})) def test_empty_categories_with_wrong_dtype(): with pytest.raises(ValueError, match="must have dtype=object"): validate_dataframe( pd.DataFrame({"foo": [np.nan]}, dtype=float).astype("category") ) def test_non_str_categories(): with pytest.raises(ValueError, match="must all be str"): validate_dataframe(pd.DataFrame({"foo": ["a", 1]}, dtype="category")) def test_unused_categories(): with pytest.raises(ValueError, match="unused category 'b'"): validate_dataframe( pd.DataFrame({"foo": ["a", "a"]}, dtype=pd.CategoricalDtype(["a", "b"])) ) def test_null_is_not_a_category(): # pd.CategoricalDtype means storing nulls as -1. Don't consider -1 when # counting the used categories. with pytest.raises(ValueError, match="unused category 'b'"): validate_dataframe( pd.DataFrame({"foo": ["a", None]}, dtype=pd.CategoricalDtype(["a", "b"])) ) def test_empty_categories(): df = pd.DataFrame({"A": []}, dtype="category") validate_dataframe(df) def test_unique_colnames(): dataframe = pd.DataFrame({"A": [1], "B": [2]}) dataframe.columns = ["A", "A"] with pytest.raises(ValueError, match="must not appear more than once"): validate_dataframe(dataframe) def test_empty_colname(): dataframe = pd.DataFrame({"": [1], "B": [2]}) with pytest.raises(ValueError, match="must not be empty"): validate_dataframe(dataframe) def test_numpy_dtype(): # Numpy dtypes should be treated just like pandas dtypes. dataframe = pd.DataFrame({"A": np.array([1, 2, 3])}) validate_dataframe(dataframe) def test_period_dtype(): dataframe = pd.DataFrame( { "A": pd.PeriodIndex( [date(2020, 1, 1), date(2021, 3, 9), None], freq="D", ) } ) validate_dataframe(dataframe) def test_period_dtype_freq_not_D(): dataframe = pd.DataFrame( { "A": pd.PeriodIndex( [date(2020, 1, 1), date(2021, 3, 1), None], freq="M", ) } ) with pytest.raises( ValueError, match=r"unsupported dtype period\[M\] in column 'A'" ): validate_dataframe(dataframe) def test_unsupported_dtype(): dataframe = pd.DataFrame( { # A type we never plan on supporting "A": pd.Series([pd.Interval(0, 1)], dtype="interval") } ) with pytest.raises(ValueError, match="unsupported dtype"): validate_dataframe(dataframe) def test_datetime64(): dataframe = pd.DataFrame( { # We don't support datetimes with time zone data ... yet "A": pd.Series([pd.to_datetime("2019-04-23T12:34:00")]) } ) validate_dataframe(dataframe) def test_datetime64tz_unsupported(): dataframe = pd.DataFrame( { # We don't support datetimes with time zone data ... yet "A": pd.Series([pd.to_datetime("2019-04-23T12:34:00-0500")]) } ) with pytest.raises(ValueError, match="unsupported dtype"): validate_dataframe(dataframe) def test_nullable_int_unsupported(): dataframe = pd.DataFrame( { # We don't support nullable integer columns ... yet "A": pd.Series([1, np.nan], dtype=pd.Int64Dtype()) } ) with pytest.raises(ValueError, match="unsupported dtype"): validate_dataframe(dataframe) def test_infinity_not_supported(): # Make 'A': [1, -inf, +inf, nan] num = pd.Series([1, -2, 3, np.nan]) denom = pd.Series([1, 0, 0, 1]) dataframe = pd.DataFrame({"A": num / denom}) with pytest.raises( ValueError, match=r"invalid value -inf in column 'A', row 1 \(infinity is not supported\)", ): validate_dataframe(dataframe) def test_unsupported_numpy_dtype_unsupported(): # We can't check if a numpy dtype == 'category'. # https://github.com/pandas-dev/pandas/issues/16697 arr = np.array([1, 2, 3]).astype("complex") # we don't support complex dataframe = pd.DataFrame({"A": arr}) with pytest.raises(ValueError, match="unsupported dtype"): validate_dataframe(dataframe) def test_colnames_dtype_object(): with pytest.raises(ValueError, match="column names"): # df.columns is numeric validate_dataframe(pd.DataFrame({1: [1]})) def test_colnames_all_str(): with pytest.raises(ValueError, match="column names"): # df.columns is object, but not all are str validate_dataframe(pd.DataFrame({"A": [1], 2: [2]})) def test_colnames_control_chars(): with pytest.raises(ValueError, match="ASCII control characters"): validate_dataframe(pd.DataFrame({"A\x01": [1]})) def test_colnames_invalid_unicode(): with pytest.raises(ValueError, match="Unicode surrogates"): validate_dataframe(pd.DataFrame({"A \ud800 B": [1]})) def test_colnames_too_long(): class MySettings: MAX_BYTES_PER_COLUMN_NAME: int = 10 with pytest.raises(ValueError, match="must contain 10 bytes or fewer"): validate_dataframe(pd.DataFrame({"01234567890": [1]}), settings=MySettings()) <file_sep>import numpy as np import pandas as pd import pyarrow as pa def arrow_chunked_array_to_pandas_series(chunked_array: pa.ChunkedArray) -> pd.Series: if pa.types.is_date32(chunked_array.type): return pd.Series(pd.arrays.PeriodArray(chunked_array.to_numpy(), freq="D")) return chunked_array.to_pandas( date_as_object=False, deduplicate_objects=True, ignore_metadata=True ) # TODO ensure dictionaries stay dictionaries def _dtype_to_arrow_type(dtype: np.dtype) -> pa.DataType: if dtype == np.int8: return pa.int8() elif dtype == np.int16: return pa.int16() elif dtype == np.int32: return pa.int32() elif dtype == np.int64: return pa.int64() elif dtype == np.uint8: return pa.uint8() elif dtype == np.uint16: return pa.uint16() elif dtype == np.uint32: return pa.uint32() elif dtype == np.uint64: return pa.uint64() elif dtype == np.float16: return pa.float16() elif dtype == np.float32: return pa.float32() elif dtype == np.float64: return pa.float64() elif dtype.kind == "M": # [2019-09-17] Pandas only allows "ns" unit -- as in, datetime64[ns] # https://github.com/pandas-dev/pandas/issues/7307#issuecomment-224180563 assert dtype.str.endswith("[ns]") return pa.timestamp(unit="ns", tz=None) elif dtype == np.object_: return pa.string() else: raise RuntimeError("Unhandled dtype %r" % dtype) # pragma: no cover def arrow_table_to_pandas_dataframe(table: pa.Table) -> pd.DataFrame: """Convert an Arrow Table to a Pandas DataFrame.""" return pd.DataFrame( { colname: arrow_chunked_array_to_pandas_series(column) for colname, column in zip(table.column_names, table.itercolumns()) }, index=pd.RangeIndex(0, table.num_rows), ) def pandas_series_to_arrow_array(series: pd.Series) -> pa.Array: """Convert a Pandas series to an in-memory Arrow array. """ if hasattr(series, "cat"): return pa.DictionaryArray.from_arrays( # Pandas categorical value "-1" means None pa.Array.from_pandas(series.cat.codes, mask=(series.cat.codes == -1)), pandas_series_to_arrow_array(series.cat.categories), ) elif pd.PeriodDtype(freq="D") == series.dtype: return pa.array(series.array.asi8, pa.int32(), mask=series.array.isna()).cast( pa.date32() ) else: arrow_type = _dtype_to_arrow_type(series.dtype) return pa.array(series, type=arrow_type) def pandas_dataframe_to_arrow_table(dataframe: pd.DataFrame) -> pa.Table: """Copy a Pandas DataFrame to an Arrow Table. This isn't zero-copy. There may be significant RAM costs. (But of course, you accepted this cost when you chose Pandas....) This assumes the input is valid. Run `validate_dataframe()` prior to calling this if you don't know whether the input is valid. Otherwise, you'll get undefined behavior. """ return pa.table( { column: pandas_series_to_arrow_array(dataframe[column]) for column in dataframe.columns } ) <file_sep>[build-system] requires = ["poetry_core>=1.0.0", "cython"] build-backend = "poetry.core.masonry.api" [tool.poetry] name = "cjwpandasmodule" version = "0.0.0" description = "Utilities for Workbench modules that use Pandas" authors = ["<NAME> <<EMAIL>>"] license = "MIT" readme = "README.md" [tool.poetry.dependencies] pandas = "~=0.25.0" python = "~=3.8.0" cjwmodule = "~=4.0" [tool.poetry.dev-dependencies] pytest = "~=6.0" pytest-cov = "~= 2.10" [tool.isort] # Black compatibility multi_line_output = 3 include_trailing_comma = true force_grid_wrap = 0 use_parentheses = true line_length = 88 [tool.tox] legacy_tox_ini = """ [tox] isolated_build = True skipsdist = True envlist = py38-{pyflakes,black,isort,pytest} [flake8] exclude = venv/*,tox/*,specs/*,build/* ignore = E123,E128,E266,E402,W503,E731,W601 max-line-length = 88 [testenv] skip_install = true deps = pyflakes: pyflakes>=2.2 black: black isort: isort pytest: poetry commands_pre = pytest: poetry install -v commands = pyflakes: pyflakes cjwpandasmodule tests black: black --check cjwpandasmodule tests isort: isort --check --diff cjwpandasmodule tests pytest: poetry run pytest --cov=cjwpandasmodule --cov-report term-missing -v """ <file_sep>Utilities for [CJWorkbench](https://github.com/CJWorkbench/cjworkbench) modules that use Pandas. Workbench modules may _optionally_ depend on the latest version of this Python package for its handy utilities: * `cjwpandasmodule.validate`: functions to check if a DataFrame can be saved in Workbench. Developing ========== 0. Run `tox` to confirm that unit tests pass 1. Write a failing unit test in `tests/` 2. Make it pass by editing code in `cjwpandasmodule/` 3. Submit a pull request We use [semver](https://semver.org/). Workbench will upgrade this dependency (minor version only) without module authors' explicit consent. Features in the same major version must be backwards-compatible. Publishing ========== 1. ``git push`` and make sure Travis tests all pass. 2. ``git tag vX.X.X`` 3. ``git push --tags`` TravisCI will push to PyPi. <file_sep>import datetime import numpy as np import pandas as pd import pyarrow as pa import pytest from pandas.testing import assert_frame_equal, assert_series_equal from cjwpandasmodule.convert import ( arrow_chunked_array_to_pandas_series, arrow_table_to_pandas_dataframe, pandas_dataframe_to_arrow_table, pandas_series_to_arrow_array, ) IntSeriesAndArrayParams = [ pytest.param( pd.Series([1, 2], dtype=np.uint8), pa.array([1, 2], pa.uint8()), id="uint8" ), pytest.param( pd.Series([1, -2], dtype=np.int8), pa.array([1, -2], pa.int8()), id="int8" ), pytest.param( pd.Series([1, 2], dtype=np.uint16), pa.array([1, 2], pa.uint16()), id="uint16", ), pytest.param( pd.Series([1, -2], dtype=np.int16), pa.array([1, -2], pa.int16()), id="int16", ), pytest.param( pd.Series([1, 2], dtype=np.uint32), pa.array([1, 2], pa.uint32()), id="uint32", ), pytest.param( pd.Series([1, -2], dtype=np.int32), pa.array([1, -2], pa.int32()), id="int32", ), pytest.param( pd.Series([1, 2], dtype=np.uint64), pa.array([1, 2], pa.uint64()), id="uint64", ), pytest.param( pd.Series([1, -2], dtype=np.int64), pa.array([1, -2], pa.int64()), id="int64", ), pytest.param( pd.Series([1, -2, None], dtype=np.float16), pa.array([np.float16(1), np.float16(-2), None], pa.float16()), id="float16", ), pytest.param( pd.Series([1, -2, None], dtype=np.float32), pa.array([1, -2, None], pa.float32()), id="float32", ), pytest.param( pd.Series([1, -2, None], dtype=np.float64), pa.array([1, -2, None], pa.float64()), id="float64", ), ] @pytest.mark.parametrize("series,expected_array", IntSeriesAndArrayParams) def test_series_to_array_numeric(series, expected_array): assert pandas_series_to_arrow_array(series).equals(expected_array) def test_series_to_array_timestamp(): series = pd.Series(["2021-04-05T17:31:12.456", None], dtype="datetime64[ns]") expected_array = pa.array( [datetime.datetime(2021, 4, 5, 17, 31, 12, 456000, tzinfo=None), None], pa.timestamp(unit="ns"), ) result = pandas_series_to_arrow_array(series) assert result == expected_array def test_series_to_array_date(): series = pd.Series(["2021-04-05", None], dtype="period[D]") expected_array = pa.array([datetime.date(2021, 4, 5), None]) result = pandas_series_to_arrow_array(series) assert result == expected_array def test_series_to_array_str(): series = pd.Series(["a", "b", "c\0d", None]) expected_array = pa.array(["a", "b", "c\0d", None]) result = pandas_series_to_arrow_array(series) assert result == expected_array def test_series_to_array_categorical_int8(): series = pd.Series(["a", "b", "c\0d", "a", None], dtype="category") expected_array = pa.DictionaryArray.from_arrays( pa.array([0, 1, 2, 0, None], pa.int8()), pa.array(["a", "b", "c\0d"]) ) result = pandas_series_to_arrow_array(series) assert result == expected_array def test_series_to_array_categorical_int32(): series = pd.Series([chr(i) for i in range(35536)], dtype="category") expected_array = pa.DictionaryArray.from_arrays( pa.array(list(range(35536)), pa.int32()), pa.array(chr(i) for i in range(35536)) ) result = pandas_series_to_arrow_array(series) assert result == expected_array def test_dataframe_to_table(): dataframe = pd.DataFrame({"A": ["a", "b"], "B": [1, None]}) expected_table = pa.table({"A": ["a", "b"], "B": [1.0, None]}) result = pandas_dataframe_to_arrow_table(dataframe) assert result == expected_table @pytest.mark.parametrize("expected_series,array", IntSeriesAndArrayParams) def test_chunked_array_to_series_numeric(expected_series, array): chunked_array = pa.chunked_array([array]) result = arrow_chunked_array_to_pandas_series(chunked_array) assert_series_equal(result, expected_series) def test_chunked_array_to_series_int_null_becomes_float64(): chunked_array = pa.chunked_array([pa.array([1, 2, None])]) expected_series = pd.Series([1.0, 2.0, None]) result = arrow_chunked_array_to_pandas_series(chunked_array) assert_series_equal(result, expected_series) def test_chunked_array_to_series_timestamp(): chunked_array = pa.chunked_array( [ pa.array( [datetime.datetime(2021, 4, 5, 17, 31, 12, 456000, tzinfo=None), None], pa.timestamp(unit="ns"), ) ] ) expected_series = pd.Series( ["2021-04-05T17:31:12.456", None], dtype="datetime64[ns]" ) result = arrow_chunked_array_to_pandas_series(chunked_array) assert_series_equal(result, expected_series) def test_chunked_array_to_series_date(): chunked_array = pa.chunked_array([pa.array([datetime.date(2021, 4, 5), None])]) expected_series = pd.Series(["2021-04-05", None], dtype="period[D]") result = arrow_chunked_array_to_pandas_series(chunked_array) assert_series_equal(result, expected_series) def test_chunked_array_to_series_str(): chunked_array = pa.chunked_array([pa.array(["a", "b", "c\0d", None])]) expected_series = pd.Series(["a", "b", "c\0d", None]) result = arrow_chunked_array_to_pandas_series(chunked_array) assert_series_equal(result, expected_series) def test_chunked_array_to_series_categorical_int8(): chunked_array = pa.chunked_array( [ pa.DictionaryArray.from_arrays( pa.array([0, 1, 2, 0, None], pa.int8()), pa.array(["a", "b", "c\0d"]) ) ] ) expected_series = pd.Series(["a", "b", "c\0d", "a", None], dtype="category") result = arrow_chunked_array_to_pandas_series(chunked_array) assert_series_equal(result, expected_series) def test_chunked_array_to_series_categorical_int32(): chunked_array = pa.chunked_array( [ pa.DictionaryArray.from_arrays( pa.array(list(range(35536)), pa.int32()), pa.array(chr(i) for i in range(35536)), ) ] ) expected_series = pd.Series([chr(i) for i in range(35536)], dtype="category") result = arrow_chunked_array_to_pandas_series(chunked_array) assert_series_equal(result, expected_series) def test_table_to_dataframe(): table = pa.table( { "A": ["a", "b"], "B": pa.array([1, 2], pa.int32()), } ) expected_dataframe = pd.DataFrame( {"A": ["a", "b"], "B": pd.Series([1, 2], dtype=np.int32)} ) result = arrow_table_to_pandas_dataframe(table) assert_frame_equal(result, expected_dataframe) <file_sep>v0.2.0 - 2021-04-09 ~~~~~~~~~~~~~~~~~~~ * Bump cjwmodule dependency ~=4.0.0 v0.1.0 - 2021-04-05 ~~~~~~~~~~~~~~~~~~~ * `cjwpandasmodule.convert`: convert Pandas to Arrow (and back) * `cjwpandasmodule.validate`: allow `period[D]` values (for forward compatibility -- Workbench does not support this as of 2021-04-05). * 100% unit-test coverage v0.0.2 - 2021-01-22 ~~~~~~~~~~~~~~~~~~~ * `cjwpandasmodule.validate`: validate that a pd.DataFrame is Workbench-compatible.
744a62dae47c1c3c9edca0a7e904398165d6cfd0
[ "TOML", "Python", "Markdown" ]
7
Python
CJWorkbench/cjwpandasmodule
8571a7d09ad08a78ddf42dec12a91ebc7f11cc58
dfac9700ea20d7c7e6413129794cdff2d48cc26f
refs/heads/master
<file_sep>import { createStore } from 'redux'; import boardReducer from './reducers/boardReducer'; export default createStore(boardReducer); <file_sep>import React from 'react'; const Row = ({ row, rowIndex, onClickCell }) => ( <tr key={rowIndex}> { row.map((cell, cellIndex) => ( <td key={[rowIndex, cellIndex].join()} onClick={() => onClickCell(rowIndex, cellIndex)} className={["cell", cell ? 'full' : 'empty'].join(" ")}> &nbsp; </td> )) } </tr> ); export default Row; <file_sep>import { createBoard, tick } from '../lib/game'; export default (state = [{ board: createBoard(20, 20) }], action) => { const latest = state.slice(-1)[0]; switch (action.type) { case 'TOGGLE_CELL': { const cellValue = latest.board[action.row][action.col] ? 0 : 1; latest.board[action.row][action.col] = cellValue; return [ ...state, { board: [...latest.board] } ]; } case 'NEXT': { return [ ...state, { board: tick(latest.board) } ]; } case 'PREVIOUS': { return state.slice(0, -1); } default: { return state; } } }; <file_sep>const getRandomInt = (min, max) => { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive } const createRow = (width, random = false) => Array.from({ length: width }, () => random ? !getRandomInt(0, 4) : 0); const createBoard = (height = 10, width = 10, random = false) => Array.from({length: height}).map((x) => createRow(width, random)); const getIndexBoundaries = (i, length) => { const fromIndex = i - 1 >= 0 ? i - 1 : 0; const toIndex = i + 2 < length ? i + 2 : length + 1; return [ fromIndex, toIndex ]; } const getNeighbourRows = (r, board) => { const [ from, to ] = getIndexBoundaries(r, board.length); return board.slice(from, to); }; const sliceNeighbourRows = (c, neighbourRows) => { const [ from, to ] = getIndexBoundaries(c, neighbourRows[0].length); return neighbourRows.map((x) => x.slice(from, to)); }; const getNeighbourMatrix = (r, c, board) => sliceNeighbourRows(c, getNeighbourRows(r, board)); const getNeighbourCount = (r, c, board) => { const matrix = getNeighbourMatrix(r, c, board); const flattenedMatrix = matrix.reduce((a, b) => a.concat(b)); return flattenedMatrix.reduce((a, b) => a + b) - board[r][c]; }; const survives = (cell, neighbours) => { if (neighbours < 2) { return 0; } else if (neighbours == 2) { return cell; } else if (neighbours == 3) { return 1; } else if (neighbours > 3) { return 0; } } const tick = (board) => { const height = board.length; const width = board[0].length; const nextBoard = createBoard(height, width); let neighbours; for (let row=0; row<height; row++) { for (let cell=0; cell<width; cell++) { neighbours = getNeighbourCount(row, cell, board); nextBoard[row][cell] = survives(board[row][cell], neighbours); } } return nextBoard; } export { createBoard, getNeighbourRows, sliceNeighbourRows, getNeighbourMatrix, getNeighbourCount, tick }; <file_sep>import { createBoard, getNeighbourRows, sliceNeighbourRows, getNeighbourMatrix, getNeighbourCount, tick } from '../../src/lib/game'; describe('Game#createBoard', () => { describe('when a width and a height is given', () => { test('should create a board with H x W', () => { const board = [ [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], ]; expect(createBoard(4, 5)).toEqual(board); }); }); }); describe('For a defined board', () => { const board = [ [ 0, 1, 1, 0, 1 ], [ 1, 0, 1, 1, 1 ], [ 0, 1, 1, 0, 0 ], [ 0, 1, 1, 1, 1 ], [ 0, 0, 0, 0, 0 ] ]; describe('Game#getNeighbourRows', () => { test('should return the neighbour rows', () => { expect(getNeighbourRows(0, board)).toEqual([[ 0, 1, 1, 0, 1 ], [ 1, 0, 1, 1, 1 ]]); expect(getNeighbourRows(1, board)).toEqual([[ 0, 1, 1, 0, 1 ], [ 1, 0, 1, 1, 1 ], [ 0, 1, 1, 0, 0 ]]); expect(getNeighbourRows(2, board)).toEqual([[ 1, 0, 1, 1, 1 ], [ 0, 1, 1, 0, 0 ], [ 0, 1, 1, 1, 1 ]]); expect(getNeighbourRows(3, board)).toEqual([[ 0, 1, 1, 0, 0 ], [ 0, 1, 1, 1, 1 ], [ 0, 0, 0, 0, 0 ]]); expect(getNeighbourRows(4, board)).toEqual([[ 0, 1, 1, 1, 1 ], [ 0, 0, 0, 0, 0 ]]); }); }); describe('Game#getNeighbourMatrix', () => { test('should return the neighbour rows', () => { expect(getNeighbourMatrix(0, 0, board)).toEqual([[0, 1], [1, 0]]); expect(getNeighbourMatrix(0, 1, board)).toEqual([[0, 1, 1], [1, 0, 1]]); expect(getNeighbourMatrix(0, 4, board)).toEqual([[0, 1], [1, 1]]); expect(getNeighbourMatrix(2, 2, board)).toEqual([[0, 1, 1], [1, 1, 0], [1, 1, 1]]); expect(getNeighbourMatrix(4, 0, board)).toEqual([[0, 1], [0, 0]]); expect(getNeighbourMatrix(4, 2, board)).toEqual([[1, 1, 1], [0, 0, 0]]); expect(getNeighbourMatrix(4, 4, board)).toEqual([[1, 1], [0, 0]]); }); }); describe('Game#getNeighbourCount', () => { test('should return count of the neighbours', () => { expect(getNeighbourCount(0, 0, board)).toEqual(2); expect(getNeighbourCount(0, 1, board)).toEqual(3); expect(getNeighbourCount(0, 3, board)).toEqual(5); expect(getNeighbourCount(0, 4, board)).toEqual(2); expect(getNeighbourCount(2, 2, board)).toEqual(6); expect(getNeighbourCount(4, 0, board)).toEqual(1); expect(getNeighbourCount(4, 2, board)).toEqual(3); expect(getNeighbourCount(4, 4, board)).toEqual(2); }); }); describe('Game#tick', () => { test('should return the next phase of the board', () => { const nextBoard = [ [ 0, 1, 1, 0, 1 ], [ 1, 0, 0, 0, 1 ], [ 1, 0, 0, 0, 0 ], [ 0, 1, 0, 1, 0 ], [ 0, 0, 1, 1, 0 ] ]; expect(tick(board)).toEqual(nextBoard); }); }); }); <file_sep>import React from 'react'; import '../assets/css/App.css'; import BoardContainer from '../containers/BoardContainer'; import ControlPanelContainer from '../containers/ControlPanelContainer'; const App = () => ( <div className="App"> <BoardContainer /> <ControlPanelContainer /> </div> ); export default App; <file_sep>import React from 'react'; const ControlPanel = props => ( <div class="controlPanel"> <button id="previousStep" type="button" onClick={() => props.onClickPrevious()}>&lt;</button> <button id="nextStep" type="button" onClick={() => props.onClickNext()}>&gt;</button> </div> ); export default ControlPanel; <file_sep>import React from 'react'; import Row from './Row'; const Board = ({ board, onClickCell }) => ( <table className="board"> <tbody> {board.map((row, rowIndex) => ( <Row row={row} rowIndex={rowIndex} onClickCell={onClickCell} /> ))} </tbody> </table> ); export default Board;
068e0fb424bca358543153100c06f614d330ed64
[ "JavaScript" ]
8
JavaScript
FooVio/game-of-life
646845352049e91cd504989e6b4527a4c44d1b71
141400d62f145aac1bcc3d27aa1339eca7ca0fd5
refs/heads/master
<repo_name>furkankyildirim/sucheduleApp<file_sep>/utils/LocalizedStrings.js // ES6 module syntax import LocalizedStrings from 'react-native-localization'; // CommonJS syntax // let LocalizedStrings = require ('react-native-localization'); export default Strings = new LocalizedStrings({ "en-US":{ how:"How do you want your egg today?", boiledEgg:"Boiled egg", softBoiledEgg:"Soft-boiled egg", choice:"How to choose the egg" }, en:{ how:"How do you want your egg today?", boiledEgg:"Boiled egg", softBoiledEgg:"Soft-boiled egg", choice:"How to choose the egg" }, it: { how:"Come vuoi il tuo uovo oggi?", boiledEgg:"Uovo sodo", softBoiledEgg:"Uovo alla coque", choice:"Come scegliere l'uovo" } }); <file_sep>/utils/FontStyles.js import { StyleSheet } from 'react-native'; import Colors from './Colors'; const defaultColor = Colors.white const fontStyles = StyleSheet.create({ largeTitle:{ fontSize: 30, color: defaultColor, fontWeight: '600', }, largeIcons:{ fontSize: 40, color: defaultColor, opacity: 0.75, fontWeight: '600', }, headerIcons:{ fontSize: 24, color: defaultColor, fontWeight: '600', }, smallTitle:{ fontSize: 15, color: defaultColor, fontWeight: '500', }, tinyTitle:{ fontSize: 12, color: defaultColor, fontWeight: '400', position:'absolute', top:4.5, textAlign:'center', width: '100%', height: '100%' }, picker:{ fontSize: 14, color: defaultColor, fontWeight: '600', }, smallText:{ fontSize: 16, fontWeight: '500', }, courseIcon:{ fontSize: 24, right:0, position:'absolute' }, courseTitle:{ fontSize: 14.5, fontWeight: '400', paddingRight: 20, }, linkIcon:{ color: Colors.white, paddingHorizontal: 2, paddingVertical: 0.5 }, groupTitle:{ fontSize:14, fontWeight:'600' }, infoTitle:{ fontSize: 12, color: defaultColor, fontWeight: '500', }, instructorTitle:{ fontSize:14, fontWeight:'500', }, scheduleTitle:{ color: Colors.grey5, fontSize:14, fontWeight:'500' }, courseDetailTitle:{ fontSize: 18, color: defaultColor, fontWeight: '600', }, checkIcon:{ fontSize: 24, right:0, position:'absolute', color: Colors.green }, selectedCourse:{ fontSize: 15, color: defaultColor, fontWeight: '600', }, cancelIcon:{ fontSize: 18, marginHorizontal: 2, color: defaultColor, } }) export default fontStyles<file_sep>/scripts/runner.sh #ANDROID npx react-native run-android #IOS npx react-native run-ios --simulator="iPhone 12 Pro"<file_sep>/utils/Constants.js import { Dimensions } from "react-native"; export default { DEVICE_WIDTH: Dimensions.get("window").width, DEVICE_HEIGHT: Dimensions.get("window").height, GRID_LARGE_WIDTH: Dimensions.get("window").width * 0.36, GRID_SMALL_WIDTH: Dimensions.get("window").width * 0.16, DRAWER_BUTTON_SIZE: 48, DRAWER_WIDTH: 300,//Dimensions.get("window").width * 0.775, SEARCH_WIDTH: 175,//Dimensions.get("window").width * 0.45, PICKER_WIDTH: 100//Dimensions.get("window").width * 0.25, }<file_sep>/screens/Home.js import React, { useState, useEffect } from 'react'; import { View, Text, StyleSheet, FlatList, ScrollView, TouchableOpacity, ActivityIndicator } from 'react-native'; import AsyncStorage from '@react-native-async-storage/async-storage'; import NetInfo from "@react-native-community/netinfo"; import axios from 'axios'; import Icon from 'react-native-vector-icons/dist/Entypo'; import Drawer from './Drawer' import fontStyles from '../utils/FontStyles'; import Constants from '../utils/Constants'; import { Observer, observer } from 'mobx-react'; import Colors from '../utils/Colors'; import Durations from '../utils/Durations' import SelectedCourses from '../utils/SelectedCourses'; import SelectedColors from '../utils/SelectedColors'; import PressedCourses from '../utils/PressedCourses'; import { action } from 'mobx'; const Home = observer(({ navigation }) => { const [layoutHeight, setLayoutHeight] = useState(0); const [drawerVisibility, setDrawerVisibility] = useState(false); const [data, setData] = useState(null); useEffect(() => NetInfo.fetch().then(async state => { if (state.isConnected) { const versionInfo = await axios.get('https://suchedule.herokuapp.com/version'); if (await AsyncStorage.getItem('@version') !== versionInfo.data.version.toString()) { await AsyncStorage.clear(); await AsyncStorage.setItem('@version', versionInfo.data.version.toString()); const response = await axios.get('https://suchedule.herokuapp.com/data'); await AsyncStorage.setItem('@data', JSON.stringify(response.data)); } } setData(JSON.parse(await AsyncStorage.getItem('@data'))); const sessionValue = await AsyncStorage.getItem('@session'); const Session = sessionValue != null ? JSON.parse(sessionValue) : {}; for (const code in Session) { SelectedCourses[code] = Session[code]; if (SelectedCourses[code].types.length === SelectedCourses[code].typeLenght) { Durations.map(day => day.hour.map(hour => { if (hour.data.code === code) { const color = hour.data.color; const colorIndex = SelectedColors.indexOf(color); SelectedColors.slice(colorIndex, 1); hour.data.title = ''; hour.data.code = ''; hour.data.crn = ''; hour.data.color = ''; } })) let color = Colors.colorPalette[Math.floor(Math.random() * Colors.colorPalette.length)]; while (SelectedColors.includes(color)) { color = Colors.colorPalette[Math.floor(Math.random() * Colors.colorPalette.length)]; } SelectedCourses[code].sections.map(section => { const lessonName = section.lessonName; const crn = section.crn; section.schedule.map(sch => { for (i = 0; i < sch.duration; i++) { Durations[sch.day + 1].hour[sch.start + i].data.title = lessonName; Durations[sch.day + 1].hour[sch.start + i].data.crn = crn; Durations[sch.day + 1].hour[sch.start + i].data.code = code; Durations[sch.day + 1].hour[sch.start + i].data.color = color; } }) }); } } }), []); const deleteSchedule = async item => { const crn = item.crn; for (const code in SelectedCourses) { const idx = SelectedCourses[code].sections.map(sec => sec.crn).indexOf(crn); if (idx > -1) { SelectedCourses[code].sections.map(sec => sec.schedule.map(sch => { for (i = 0; i < sch.duration; i++) { const color = Durations[sch.day + 1].hour[sch.start + i].data.color; const colorIndex = SelectedColors.indexOf(color); SelectedColors.slice(colorIndex, 1); Durations[sch.day + 1].hour[sch.start + i].data.title = ''; Durations[sch.day + 1].hour[sch.start + i].data.crn = ''; Durations[sch.day + 1].hour[sch.start + i].data.code = ''; Durations[sch.day + 1].hour[sch.start + i].data.color = ''; } })); SelectedCourses[code].types.splice(idx, 1); SelectedCourses[code].sections.splice(idx, 1); await AsyncStorage.setItem('@session', JSON.stringify(SelectedCourses)); return; } } } const setPressedCourses = crn => { for (i = 0; i < data.courses.length; i++) { const course = { classes: [], code: data.courses[i].code, name: data.courses[i].name }; const CRNs = []; for (j = 0; j < data.courses[i].classes.length; j++) { const cls = { sections: [], type: data.courses[i].classes[j].type }; for (k = 0; k < data.courses[i].classes[j].sections.length; k++) { const section = { crn: data.courses[i].classes[j].sections[k].crn, group: data.courses[i].classes[j].sections[k].group, instructors: data.courses[i].classes[j].sections[k].instructors, schedule: [] } CRNs.push(section.crn); for (l = 0; l < data.courses[i].classes[j].sections[k].schedule.length; l++) { const schedule = { day: data.courses[i].classes[j].sections[k].schedule[l].day, duration: data.courses[i].classes[j].sections[k].schedule[l].duration, place: data.courses[i].classes[j].sections[k].schedule[l].place, start: data.courses[i].classes[j].sections[k].schedule[l].start } section.schedule.push(schedule); } cls.sections.push(section); } course.classes.push(cls); } if (CRNs.includes(crn) && !PressedCourses.data.map(crs => crs.code).includes(course.code)) { PressedCourses.data.push(course); } } PressedCourses.isPressed = true; setDrawerVisibility(true); } const setLayout = (event) => { setLayoutHeight(event.nativeEvent.layout.height); } const GridRow = ({ item, index }) => { const bgColor = item.dayId % 2 === 0 ? (index % 2 === 0 ? Colors.grey2 : Colors.grey4) : (index % 2 === 0 ? Colors.grey1 : Colors.grey3) const width = item.dayId === 0 ? 64 : Constants.DEVICE_WIDTH * 0.40 const GridRowStyle = StyleSheet.compose({ backgroundColor: bgColor, width: width, height: layoutHeight * 0.96 / 11, alignItems: 'center', justifyContent: 'center' }) const SelectedCourseStyle = StyleSheet.compose({ //width:Constants.DEVICE_WIDTH * 0.375, paddingHorizontal: 5, height: layoutHeight * 0.96 / 20, maxWidth: 350, maxHeight: 75, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: Durations[item.dayId].hour[index].data.color }); return ( <Observer> {() => <View style={GridRowStyle}> {item.dayId === 0 ? <Text style={fontStyles.smallText}>{item.data.title}</Text> : Durations[item.dayId].hour[index].data.title !== '' && <TouchableOpacity onPress={action(() => setPressedCourses(Durations[item.dayId].hour[index].data.crn))} style={{ ...SelectedCourseStyle, backgroundColor: Durations[item.dayId].hour[index].data.color }}> <Text style={fontStyles.selectedCourse}>{item.data.title}</Text> <TouchableOpacity onPress={action(() => deleteSchedule(Durations[item.dayId].hour[index].data))}> <Icon name='cross' style={fontStyles.cancelIcon} /> </TouchableOpacity> </TouchableOpacity> } </View>} </Observer> ) } const GridColumn = ({ item, index }) => { const width = index === 0 ? 64 : Constants.DEVICE_WIDTH * 0.40 const bgColor = index % 2 === 0 ? Colors.blue2 : Colors.blue3 const GridColumnStyle = StyleSheet.compose({ width: width, height: layoutHeight, }) const TitleStyle = StyleSheet.compose({ height: layoutHeight * 0.04, backgroundColor: bgColor, width: width, alignItems: 'center', justifyContent: 'center', }) return ( <View style={GridColumnStyle}> <View style={TitleStyle}> <Text style={fontStyles.smallTitle}>{item.key}</Text> </View> <FlatList renderItem={GridRow} data={item.hour} listKey={item => `${index}*${item.id}`} keyExtractor={item => item.id} scrollEnabled={false} /> </View> ) } const DrawerButtonStyle = StyleSheet.compose({ position: 'absolute', width: Constants.DRAWER_BUTTON_SIZE, height: Constants.DRAWER_BUTTON_SIZE, top: 0, left: drawerVisibility ? Constants.DRAWER_WIDTH : 0, backgroundColor: Colors.black1, alignItems: 'center', justifyContent: 'center', zIndex: 1, }); return ( data ? <View style={{ flex: 1, flexDirection: 'row' }} onLayout={(event) => setLayout(event)}> <TouchableOpacity style={DrawerButtonStyle} onPress={() => setDrawerVisibility(!drawerVisibility)}> <Icon name='menu' style={fontStyles.largeIcons} /> </TouchableOpacity> <Drawer data={data} navigation={navigation} visibility={drawerVisibility} /> <ScrollView horizontal={true} showsVerticalScrollIndicator={false} showsHorizontalScrollIndicator={false}> <FlatList renderItem={GridColumn} data={Durations} keyExtractor={item => item.id} numColumns={Durations.length} scrollEnabled={false} /> </ScrollView> </View> : <ActivityIndicator style={{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0 }} size="large" color={Colors.blue1} /> ); }); export default Home;<file_sep>/README.md ## SUchedule App This app allows Sabancı University students to create their schedule with a friendly user interface. ## Motivation This app was built with the hopes of making the course registration period easier for SU students. ## Code This app was built using React Native (0.65.1). ## License This project is licensed under the terms of the MIT license. ## App Links Google Play Store: https://play.google.com/store/apps/details?id=com.suchedule App Store: https://apps.apple.com/tr/app/suchedule/id1587334993 <file_sep>/screens/CourseDetail.js import React, { Component, useState } from 'react'; import { View, ActivityIndicator } from 'react-native'; import { WebView } from 'react-native-webview'; import Colors from '../utils/Colors'; const CourseDetail = ({ route, navigation }) => { const { url } = route.params; const [visible, setVisible] = useState(true); return ( <View style={{ flex: 1 }}> <WebView style={{ flex: 1 }} onLoad={() => setVisible(false)} source={{ uri: url }} /> {visible && <ActivityIndicator style={{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0 }} size="large" color={Colors.blue1} /> } </View> ); } export default CourseDetail;<file_sep>/utils/Durations.js import { observable } from "mobx"; import Colors from "./Colors"; export default observable([ { id: 0, key: '', hour: [ { dayId: 0, id: 0, data: { title: '08:40', color: Colors.transparent, code: 'time', crn: '' } }, { dayId: 0, id: 1, data: { title: '09:40', color: Colors.transparent, code: 'time', crn: '' } }, { dayId: 0, id: 2, data: { title: '10:40', color: Colors.transparent, code: 'time', crn: '' } }, { dayId: 0, id: 3, data: { title: '11:40', color: Colors.transparent, code: 'time', crn: '' } }, { dayId: 0, id: 4, data: { title: '12:40', color: Colors.transparent, code: 'time', crn: '' } }, { dayId: 0, id: 5, data: { title: '13:40', color: Colors.transparent, code: 'time', crn: '' } }, { dayId: 0, id: 6, data: { title: '14:40', color: Colors.transparent, code: 'time', crn: '' } }, { dayId: 0, id: 7, data: { title: '15:40', color: Colors.transparent, code: 'time', crn: '' } }, { dayId: 0, id: 8, data: { title: '16:40', color: Colors.transparent, code: 'time', crn: '' } }, { dayId: 0, id: 9, data: { title: '17:40', color: Colors.transparent, code: 'time', crn: '' } }, { dayId: 0, id: 10, data: { title: '18:40', color: Colors.transparent, code: 'time', crn: '' } }, ] }, { id: 1, key: 'Mon', hour: [ { dayId: 1, id: 0, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 1, id: 1, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 1, id: 2, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 1, id: 3, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 1, id: 4, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 1, id: 5, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 1, id: 6, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 1, id: 7, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 1, id: 8, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 1, id: 9, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 1, id: 10, data: { title: '', color: '', code: '', crn: '' } }, ] }, { id: 2, key: 'Tue', hour: [ { dayId: 2, id: 0, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 2, id: 1, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 2, id: 2, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 2, id: 3, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 2, id: 4, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 2, id: 5, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 2, id: 6, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 2, id: 7, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 2, id: 8, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 2, id: 9, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 2, id: 10, data: { title: '', color: '', code: '', crn: '' } }, ] }, { id: 3, key: 'Wed', hour: [ { dayId: 3, id: 0, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 3, id: 1, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 3, id: 2, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 3, id: 3, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 3, id: 4, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 3, id: 5, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 3, id: 6, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 3, id: 7, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 3, id: 8, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 3, id: 9, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 3, id: 10, data: { title: '', color: '', code: '', crn: '' } }, ] }, { id: 4, key: 'Thu', hour: [ { dayId: 4, id: 0, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 4, id: 1, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 4, id: 2, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 4, id: 3, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 4, id: 4, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 4, id: 5, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 4, id: 6, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 4, id: 7, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 4, id: 8, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 4, id: 9, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 4, id: 10, data: { title: '', color: '', code: '', crn: '' } }, ] }, { id: 5, key: 'Fri', hour: [ { dayId: 5, id: 0, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 5, id: 1, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 5, id: 2, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 5, id: 3, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 5, id: 4, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 5, id: 5, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 5, id: 6, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 5, id: 7, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 5, id: 8, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 5, id: 9, data: { title: '', color: '', code: '', crn: '' } }, { dayId: 5, id: 10, data: { title: '', color: '', code: '', crn: '' } }, ] }, ] )<file_sep>/scripts/packages.sh #MAIN DIRECTORY cd .. yarn install cd ios && pod install && cd ..
09f69586c99470506147cd491587d2675810a3fc
[ "JavaScript", "Markdown", "Shell" ]
9
JavaScript
furkankyildirim/sucheduleApp
476803c8032a0f81d5d0bbeff9c851f4b88f5973
05c2a917d4bb09b315ccab24a3319ef95fd2da87
refs/heads/master
<repo_name>willhains/patternotations<file_sep>/samples/com/willhains/patterns/samples/gof/decorator/Milk.java package com.willhains.patterns.samples.gof.decorator; import com.willhains.patterns.gof.*; /** * Decorator Milk that mixes milk with coffee * note it extends CoffeeDecorator */ @DecoratorPattern.ConcreteDecorator public class Milk extends CoffeeDecorator { public Milk(Coffee decoratedCoffee) { super(decoratedCoffee); } @Override public double getCost() { // overriding methods defined in the abstract superclass return super.getCost() + 0.5; } @Override public String getIngredients() { return super.getIngredients() + _ingredientSeparator + "Milk"; } } <file_sep>/samples/com/willhains/patterns/samples/gof/decorator/Coffee.java package com.willhains.patterns.samples.gof.decorator; import com.willhains.patterns.gof.*; /** * The abstract Coffee class defines the functionality of Coffee implemented by decorator */ @DecoratorPattern.Component(decorator = CoffeeDecorator.class) public abstract class Coffee { @DecoratorPattern.Component.Operation public abstract double getCost(); // returns the cost of the coffee @DecoratorPattern.Component.Operation public abstract String getIngredients(); // returns the ingredients of the coffee } <file_sep>/README.md # Patternotations: Annotations for Design Patterns Patternotations are a set of Java annotations representing the various components of Design Patterns. They help you to document your code, by expressing the *intent* of your design. They also provide a handy way to access the descriptions of the design patterns themselves. ## Road map My hope is that these annotations can one day be used to automatically generate useful design documentation for any code that uses them. For example, I would love to see UML diagrams of my interfaces & classes in their Javadoc pages, by providing a custom Doclet.<file_sep>/samples/com/willhains/patterns/samples/gof/decorator/Whip.java package com.willhains.patterns.samples.gof.decorator; import com.willhains.patterns.gof.*; /** * Decorator Whip that mixes whip with coffee * note it extends CoffeeDecorator */ @DecoratorPattern.ConcreteDecorator public class Whip extends CoffeeDecorator { public Whip(Coffee decoratedCoffee) { super(decoratedCoffee); } @Override public double getCost() { return super.getCost() + 0.7; } @Override public String getIngredients() { return super.getIngredients() + _ingredientSeparator + "Whip"; } } <file_sep>/src/com/willhains/patterns/gof/DecoratorPattern.java package com.willhains.patterns.gof; import static java.lang.annotation.ElementType.*; import java.lang.annotation.*; /** * Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible * alternative to subclassing for extending functionality. * * @see <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator Pattern on Wikipedia</a> * @author willhains */ public @interface DecoratorPattern { /** * Interface or class interface used by clients. */ @Target(TYPE) public @interface Component { /** * Reference to the {@link Decorator} class. */ Class<?> decorator(); /** * Optional reference to concrete implementation(s) of the {@link Component}. This doesn't need to be an * exhaustive list, just examples that are reachable/visible from the declaration. */ Class<?>[] concreteComponent() default {}; /** * Method to be decorated. */ @Target(METHOD) public @interface Operation { } } /** * Concrete implementation of {@link Component}, which may be at the core of the decorated (wrapped) component. */ @Target(TYPE) public @interface ConcreteComponent { } /** * Decorator class, wrapping an {@link Inner} component, which may be a {@link ConcreteComponent} or another * decorator. Decorator classes are often abstract, to allow multiple {@link ConcreteDecorator} implementations, * each adding a layer of functionality to the {@link Component}. */ @Target(TYPE) public @interface Decorator { /** * Reference to the {@link Component} interface being decorated. */ Class<?> component(); /** * The field containing the decorator's reference to the {@link Component} being decorated (wrapped). */ @Target(FIELD) public @interface Inner { } } /** * Concrete implementation of a {@link Decorator}, adding a layer of functionality to the underlying * {@link Component}. */ @Target(TYPE) public @interface ConcreteDecorator { } } <file_sep>/src/com/willhains/patterns/gof/ObserverPattern.java package com.willhains.patterns.gof; import static java.lang.annotation.ElementType.*; import java.lang.annotation.*; /** * Define a one-to-many dependency between objects where a state change in one object results in all its dependents * being notified and updated automatically. * * @author willhains * @see <a href="http://en.wikipedia.org/wiki/Observer_pattern">Observer Pattern on Wikipedia</a> */ public @interface ObserverPattern { /** * Interface or abstract class defining the events to be observed. */ @Target(TYPE) public @interface Observer { /** * Reference to the {@link Subject} which will be observed (listened to). */ Class<?> subject(); /** * Optional reference to some classes which implement the {@link Observer}, when the observer is an interface or * abstract class. This doesn't need to be an exhaustive list, just examples that are reachable/visible from the * declaration. */ Class<?>[] concreteObservers() default {}; /** * Event callback method. There are often multiple event callback methods on an {@link Observer} interface. */ @Target(METHOD) public @interface OnEvent { } } /** * Interface or class defining the operations for attaching and detaching {@link Observer}s to the client. */ @Target(TYPE) public @interface Subject { /** * Reference to the {@link Observer} (aka "listener") interface(s). */ Class<?>[] observer(); /** * Collection of registered {@link Observer}s. */ @Target(FIELD) public @interface RegisteredObservers { } /** * The method of the {@link Subject} to attach {@link Observer}s (aka the "add listener" method). */ @Target(METHOD) public @interface Register { } /** * The method of the {@link Subject} to detach {@link Observer}s (aka the "remove listener" method). */ @Target(METHOD) public @interface Unregister { } /** * The method of the {@link Subject} to notify all {@link Register}ed {@link Observer}s. */ @Target(METHOD) public @interface Notify { } } /** * Concrete class which implements the {@link Observer}. */ @Target(TYPE) public @interface ConcreteObserver { } }
d9f5df5a84a94cd785279e9c42dfa193264273c8
[ "Markdown", "Java" ]
6
Java
willhains/patternotations
065a2661ba8428aaeb89ad23a379735473a0b84b
083c02df3beb13ee13d2f67de398d4431d3d408f
refs/heads/master
<repo_name>XeonHis/ADA_ass1<file_sep>/client/src/client/UI/Controller.java package client.UI; import client.Communication.Comm; import client.messages.Message; import client.messages.User; import javafx.application.Platform; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Cursor; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.Text; import java.net.URL; import java.text.SimpleDateFormat; import java.util.*; /** * @author paulalan * @create 2019/9/11 10:32 */ public class Controller extends ControlledStage implements Initializable { /** * Controller object */ private static Controller instance; /** * Comm object */ private Comm comm; /** * interface root container */ @FXML private BorderPane borderPane; /** * Default user profile photo */ @FXML private ImageView userImageView; /** * user name */ @FXML private Label usernameLabel; /** * online users */ @FXML private ListView<String> userListView; /** * the number of online users */ @FXML private Label userCountLabel; /** * message show list */ @FXML private ListView<HBox> chatPaneListView; /** * message input area */ @FXML private TextArea messageBoxTextArea; /** * message send button */ @FXML private Button sendButton; /** * whom to talk with */ @FXML private Label otherUserNameLabel; /** * offset */ private double xOffset; private double yOffset; /** * user info list */ ArrayList<String> userInfoList = new ArrayList<>(); /** * current user name */ String userName = null; /** * current user profile photo */ String userPic = null; /** * (talk to all) sign */ String otherUserName = Message.ALL; public Controller() { instance = this; } /** * acquire the object of chat UI * * @return Controller.class */ public static Controller getInstance() { return instance; } public void setComm(Comm comm) { this.comm = comm; userName = comm.getUserName(); init(); } @Override public void initialize(URL location, ResourceBundle resources) { borderPane.setOnMousePressed(event -> { xOffset = myController.getStage(myStageUIID).getX() - event.getScreenX(); yOffset = myController.getStage(myStageUIID).getY() - event.getScreenY(); borderPane.setCursor(Cursor.CLOSED_HAND); }); borderPane.setOnMouseDragged(event -> { myController.getStage(myStageUIID).setX(event.getScreenX() + xOffset); myController.getStage(myStageUIID).setY(event.getScreenY() + yOffset); }); borderPane.setOnMouseReleased(event -> { borderPane.setCursor(Cursor.DEFAULT); }); } /** * send message */ @FXML public void sendBtnAction() { String content = messageBoxTextArea.getText(); if (!content.isEmpty()) { comm.sendMsg(userName, otherUserName, content); messageBoxTextArea.clear(); addYourMessages(content); } } /** * send keyboard shortcut * * @param event Enter press */ @FXML public void sendMethod(KeyEvent event) { if (event.getCode() == KeyCode.ENTER) { sendBtnAction(); } } /** * close interface */ @FXML public void closeImgViewPressedAction() { //login out in server comm.disconnect(); //exit Platform.exit(); System.exit(0); } /** * login out */ @FXML public void logoutImgViewPressedAction() { //login out in server comm.disconnect(); //clear the message dialog chatPaneListView.getItems().clear(); //switch into login interface changeStage(Main.LOGINUIID); } /** * initialize the Chat interface */ private void init() { userImageView.setImage(new Image("asset/images/default.png")); usernameLabel.setText(userName); } /** * set online user list and show the number of online users except user self * * @param userInfolist online user list */ public void setUserList(ArrayList<String> userInfolist) { this.userInfoList = userInfolist; System.out.println("Online user: " + userInfoList); //add ALL selection into ListView if (!userInfolist.get(0).equals(Message.ALL)) { User allUser = new User(Message.ALL); userInfoList.add(0, allUser.getUsername()); System.out.println(userInfoList); } //online user amount int userCount = userInfoList.size() - 1; //remove user self for (String user : userInfoList) { if (user.equals(userName)) { userInfoList.remove(user); break; } } //set online user list Platform.runLater(() -> { ObservableList<String> users = FXCollections.observableList(userInfoList); userListView.setItems(users); userListView.setCellFactory((ListView<String> L) -> new UsersCell()); //set online user amount userCountLabel.setText(userCount + ""); }); //userListView -> click event listener userListView.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String old_val, String new_val) -> { otherUserName = new_val; if (otherUserName.equals(Message.ALL)) { otherUserNameLabel.setText("Chat with everyone.."); } else { otherUserNameLabel.setText("Chat with " + otherUserName + ":"); } }); } /** * custom the ListView */ static class UsersCell extends ListCell<String> { @Override protected void updateItem(String item, boolean empty) { super.updateItem(item, empty); setGraphic(null); setText(null); if (item != null) { HBox hBox = new HBox(); //gap hBox.setSpacing(5); Text name = new Text(item); name.setFont(new Font(20)); ImageView statusImageView = new ImageView(); Image statusImage = new Image("asset/images/online.png", 16, 16, true, true); statusImageView.setImage(statusImage); if (item.equals(Message.ALL)) { name.setText("group chat >"); statusImageView.setImage(null); } ImageView pictureImageView = new ImageView(); hBox.getChildren().addAll(statusImageView, pictureImageView, name); hBox.setAlignment(Pos.CENTER_LEFT); setGraphic(hBox); } } } /** * add message of other users into dialog box * * @param message message.class -> contain From, To, Content, etc. */ public void addOtherMessges(Message message) { Task<HBox> msgHander = new Task<HBox>() { @Override protected HBox call() throws Exception { //set default image Image image = new Image("asset/images/default.png"); ImageView profileImage = new ImageView(image); profileImage.setFitHeight(30); profileImage.setFitWidth(30); Label label = new Label(); label.setFont(Font.font(15)); // determine message type if (message.getTo().equals(Message.ALL)) { label.setText("[public message]" + message.getFrom() + ": " + message.getContent()); label.setBackground(new Background(new BackgroundFill(Color.LIGHTYELLOW, null, null))); } else { label.setText("[private message] " + message.getFrom() + ": " + message.getContent()); label.setBackground(new Background(new BackgroundFill(Color.LIGHTBLUE, null, null))); } HBox x = new HBox(); label.setPadding(new Insets(10, 5, 5, 5)); x.getChildren().addAll(profileImage, label); return x; } }; msgHander.setOnSucceeded(event -> { chatPaneListView.getItems().add(msgHander.getValue()); }); Thread t2 = new Thread(msgHander); t2.setDaemon(true); t2.start(); } /** * add own message into ListView * * @param content message content */ public void addYourMessages(String content) { Platform.runLater(() -> { //default image Image image = new Image("asset/images/default.png"); ImageView profileImage = new ImageView(image); profileImage.setFitHeight(32); profileImage.setFitWidth(32); Label label = new Label(); label.setFont(Font.font(15)); label.setText(content); label.setBackground(new Background(new BackgroundFill(Color.LIGHTGREEN, null, null))); HBox x = new HBox(); x.setMaxWidth(chatPaneListView.getWidth() - 20); x.setAlignment(Pos.TOP_RIGHT); label.setPadding(new Insets(5, 5, 5, 5)); x.getChildren().addAll(label, profileImage); chatPaneListView.getItems().add(x); }); } /** * show online & offline notification * * @param notice online & offline */ public void addNotification(String notice) { Platform.runLater(() -> { SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); String timer = df.format(new Date()); Label label = new Label(); label.setFont(Font.font(15)); label.setTextFill(Color.BLACK); label.setText(timer + ": " + notice); label.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, null, null))); HBox x = new HBox(); x.setAlignment(Pos.TOP_CENTER); label.setPadding(new Insets(5, 5, 5, 5)); x.getChildren().addAll(label); chatPaneListView.getItems().add(x); }); } } <file_sep>/client/src/client/messages/User.java package client.messages; /** * @author paulalan * @create 2019/9/12 13:53 */ public class User { //username private String username; public User(String username) { this.username = username; } public String getUsername() { return username; } } <file_sep>/client/src/client/messages/Message.java package client.messages; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; /** * @author paulalan * @create 2019/9/12 13:51 */ public class Message implements Serializable { public static final String ALL = "@ALL*"; private ArrayList<String> userlist; private HashMap<String, Object> map = new HashMap<>(); public String getType() { return (String) map.get("MessageType"); } public void setType(String type) { map.put("MessageType", type); } public ArrayList<String> getUserlist() { return userlist; } public void setUserlist(ArrayList<String> temp) { this.userlist = temp; } public String getFrom() { return (String) map.get("From"); } public void setFrom(String from) { map.put("From", from); } public String getTo() { return (String) map.get("To"); } public void setTo(String to) { map.put("To", to); } public String getContent() { return (String) map.get("Content"); } public void setContent(String content) { map.put("Content", content); } public HashMap<String, Object> getMap() { return map; } @Override public String toString() { return "(M)UserList=" + String.valueOf(userlist) + " Type=" + getType() + " From=" + getFrom() + " =To" + getTo() + " Content=" + getContent(); } } <file_sep>/README.md # ADA_ass1 ADA ass1, Java Fx chatroom, reference to ChatRoom-JavaFX
72db7723641caf31ee6855a651753f3dfa938aad
[ "Markdown", "Java" ]
4
Java
XeonHis/ADA_ass1
1f0529d5ad6cebc3bc1f391f632bbd784433f4d1
c40a6c43e3036c4c119f25dd9b4e8ca2b2ec908c
refs/heads/master
<file_sep>module.exports = function(grunt) { // 1. All configuration goes here grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), compass: { // Task dist: { // Target options: { // Target options sassDir: 'data/sass', cssDir: 'data/css', imagesDir: 'data/img', fontsDir: 'data/fonts', environment: 'production', outputStyle: 'compressed' } }, dev: { // Another target options: { sassDir: 'data/sass', cssDir: 'data/css/dev', imagesDir: 'data/img', fontsDir: 'data/fonts', environment: 'development', outputStyle: 'expanded' } } }, postcss: { options: { map: false, processors: [ require('autoprefixer-core')({browsers: 'last 2 versions'}) ] }, dev: { src: ['data/css/*.css'] }, dist: { src: ['data/css/dev/*.css'] } }, watch: { css: { files: '**/*.scss', tasks: ['compass','postcss'], options: { livereload: true, }, }, } }); // 3. Where we tell Grunt we plan to use this plug-in. grunt.loadNpmTasks('grunt-contrib-compass'); grunt.loadNpmTasks('grunt-postcss'); grunt.loadNpmTasks('grunt-contrib-watch'); // 4. Where we tell Grunt what to do when we type "grunt" into the terminal. grunt.registerTask('default', ['compass','postcss','watch']); };<file_sep>#!/usr/bin/env bash echo "Installing Apache and setting it up..." apt-get update >/dev/null 2>&1 apt-get install -y apache2 >/dev/null 2>&1 rm -rf /var/www ln -fs /vagrant /var/www echo "Installing Ruby..." apt-get install -y ruby-full >/dev/null 2>&1 echo "Installing node.js..." curl -sL https://deb.nodesource.com/setup_0.12 | sudo bash - >/dev/null 2>&1 apt-get install -y nodejs >/dev/null 2>&1 echo "Installing Sass" su -c "gem install sass" echo "installing compass" gem install compass echo "installing susy" gem install susy echo "Opening shared folder and running Grunt" cd /vagrant/ npm install >/dev/null 2>&1 npm install -g grunt-cli >/dev/null 2>&1<file_sep># vagrant-sassbox
e6f7604970a22f454e6299b89c9faa83382a28d3
[ "JavaScript", "Markdown", "Shell" ]
3
JavaScript
MrSleeth/vagrant-sassbox
1cb39d6a9d2cd80c09c58db3b4af33daaea91cd7
929534a7faa6d5aea41634b2f8114815f5e38c18
refs/heads/master
<file_sep><?php namespace DateTimeTest\Scheduler\Meetings; class MidMonthMeeting extends MeetingAbstract { public function getMeetingDate() { // Set the 14th $this->meetingDate->setDate( $this->meetingDate->format('Y'), $this->meetingDate->format('m'), 14 ); // Check if it is on the weekend, go for next Monday instead. if (in_array($this->meetingDate->format('N'), [6, 7])) { $this->meetingDate->modify('Next Monday'); } return $this->meetingDate; } }<file_sep><?php namespace DateTimeTest\Scheduler; use DateTimeTest\Scheduler\Meetings\MeetingAbstract; class Month { /** * @var \DateTime */ protected $monthDate; /** * @param $monthYear */ public function __construct($monthYear) { $this->monthDate = $this->dateTimeFromString($monthYear); } /** * Get the \DateTime of this Month * * @return \DateTime */ public function getDate() { return $this->monthDate; } /** * Creates a \DateTime object from a valid string * * @param $monthYear * * @return \DateTime * @throws \Exception */ protected function dateTimeFromString($monthYear) { // Check for the format if ( ! preg_match('/^\d{2}-\d{4}$/', $monthYear)) { throw new \Exception('Invalid date-format. Must be in format MM-YYYY.'); } // Create DateTime object $dateTime = (new \DateTime())->createFromFormat('m-Y', $monthYear); return $dateTime; } /** * Get a meeting's \DateTime * * @param MeetingAbstract $meeting * * @return \DateTime */ public function getMeetingDate(MeetingAbstract $meeting) { // Attach this month to the meeting $meeting->setMonth($this); // Return the meeting's date return $meeting->getMeetingDate(); } }<file_sep><?php namespace DateTimeTest\Scheduler\Exporters; interface ExporterInterface { /** * @param $filename * @param array $data * * @return void */ public function export($filename, array $data); }<file_sep><?php namespace DateTimeTest\Scheduler; use DateTimeTest\Console; use DateTimeTest\Scheduler\Exporters\ExporterInterface; use DateTimeTest\Scheduler\Meetings\MidMonthMeeting; use DateTimeTest\Scheduler\Meetings\SocialMeeting; use DateTimeTest\Scheduler\Meetings\TestingMeeting; class Scheduler { /** * @var \DateTime */ protected $currentMonth; /** * @var array */ protected $monthContainer; /** * Generates an array of \Month with the appropriate month/year set * * @return $this */ public function getMonthlySchedule() { // Create start and end \DateTime's $dateStart = new \DateTime(); $dateEnd = (new \DateTime())->modify('+6 months'); // Create \DatePeriod $datePeriod = new \DatePeriod($dateStart, (new \DateInterval('P1M')), $dateEnd); // Get next 6 months foreach ($datePeriod as $currentMonth) { // Log to console Console::log("Creating month container for {$currentMonth->format('m-Y')}..."); // Create new month $month = new Month( $currentMonth->format('m-Y') ); // Add month to container $this->monthContainer[] = $month; } return $this; } /** * Generated an associate array * * @param $filename * @param ExporterInterface $exporter */ public function getScheduleReport($filename, ExporterInterface $exporter) { // Log to console Console::log("Starting report generation..."); $meetings = []; // Build up array foreach ($this->monthContainer as $month) { /** * @var Month $month */ $meetings[] = [ 'Month' => $month->getDate()->format('m/Y'), 'Mid Month Meeting Date' => $month->getMeetingDate(new MidMonthMeeting())->format('Y-m-d'), 'End of Month testing Date' => $month->getMeetingDate(new TestingMeeting())->format('Y-m-d'), //'Social Event Date' => $month->getMeetingDate(new SocialMeeting())->format('Y-m-d') ]; } // Log to console Console::log("Exporting to {$filename}..."); // Export it $exporter->export($filename, $meetings); } }<file_sep># DateTime/OOP PHP Developer Test A simple developer test to schedule meetings through a console app, with an OOP approach. - This app makes it simple to calculate and export upcoming meetings. - Meetings may be added/extended within the \DateTimeTest\Scheduler\Meetings namespace. - Meetings may be exported with the included CSV/JSON exporter. - Exporters may be added/extended within the \DateTimeTest\Scheduler\Exporters namespace. - A static Console class was added to simplify output to the console. ### Requirements - PHP 5.5+ ### Version 0.01 ### How does it work It simply uses PHPs own DateTime object (with DateInterval and DatePeriod) and some SOLID principles (that at this point I am still learning). Some patterns are: - Single Responsibility - Dependency Injection - Open-Closed ### How to use From the command-line simple run the "SchedulerTest.php" and it should generate two files in /exports (export.csv and export.json). ```sh $ php SchedulerTest.php ``` ### Expected Output ``` [2016-01-18 10:28:00] Creating month container for 01-2016... [2016-01-18 10:28:00] Creating month container for 02-2016... [2016-01-18 10:28:00] Creating month container for 03-2016... [2016-01-18 10:28:00] Creating month container for 04-2016... [2016-01-18 10:28:00] Creating month container for 05-2016... [2016-01-18 10:28:00] Creating month container for 06-2016... [2016-01-18 10:28:00] Starting report generation... [2016-01-18 10:28:00] Exporting to /var/www/sandbox.dev/public/upcast/exports/export.csv... [2016-01-18 10:28:00] Starting report generation... [2016-01-18 10:28:00] Exporting to /var/www/sandbox.dev/public/upcast/exports/export.json... ```<file_sep><?php namespace DateTimeTest\Scheduler\Meetings; class TestingMeeting extends MeetingAbstract { public function getMeetingDate() { // Set to the last day of the this (relative) month $this->meetingDate->modify('Last day of this month'); // Check if it is an Fri, Sat or Sun, if so, take previous Thu if (in_array($this->meetingDate->format('N'), [5, 6, 7])) { $this->meetingDate->modify('Last Thursday'); } return $this->meetingDate; } }<file_sep><?php // PSR-4 auto-loading require_once(dirname(__FILE__) . '/vendor/autoload.php'); try { // Create meetings instance from parameter $scheduler = new \DateTimeTest\Scheduler\Scheduler(); // Generate schedule $scheduler->getMonthlySchedule(); // Export with your favourite method (i.e. CSV) $scheduler->getScheduleReport( __DIR__ . '/exports/export.csv', new \DateTimeTest\Scheduler\Exporters\CsvExporter() ); // ... or as JSON $scheduler->getScheduleReport( __DIR__ . '/exports/export.json', new \DateTimeTest\Scheduler\Exporters\JsonExporter() ); } catch (Exception $e) { \DateTimeTest\Console::log("Error: {$e->getMessage()}"); }<file_sep><?php namespace DateTimeTest\Scheduler\Meetings; use DateTimeTest\Scheduler\Month; abstract class MeetingAbstract { /** * @var \DateTime */ protected $meetingDate; /** * Uses a dependency on Month to set a meeting date * * @param Month $month * * @throws \Exception */ public function setMonth(Month $month) { $this->meetingDate = $month->getDate(); } /** * Make sure all Meeting classes have their appropriate date getter * * @return \DateTime */ public abstract function getMeetingDate(); }<file_sep><?php namespace DateTimeTest\Scheduler\Exporters; class JsonExporter implements ExporterInterface { /** * Exports $data to a JSON file * * @param $filename * @param array $data * * @return void */ public function export($filename, array $data) { file_put_contents($filename, json_encode($data, JSON_PRETTY_PRINT)); } }<file_sep><?php namespace DateTimeTest\Scheduler\Meetings; class SocialMeeting extends MeetingAbstract { public function getMeetingDate() { // Get first Friday $this->meetingDate->modify('First Friday of this month'); // If it is in the first 3 days of a month, take next Friday if ($this->meetingDate->format('j') <= 3) { $this->meetingDate->modify('Second Friday of this month'); } return $this->meetingDate; } }<file_sep><?php namespace DateTimeTest; class Console { public static function log($value) { printf("[%s] %s\n", date('Y-m-d H:i:s'), $value); } }<file_sep><?php namespace DateTimeTest\Scheduler\Exporters; class CsvExporter implements ExporterInterface { /** * Exports $data to a CSV file * * @param $filename * @param array $data * * @return void */ public function export($filename, array $data) { // Get handle on file $csv = fopen($filename, 'w'); // Write headers fputcsv($csv, array_keys($data[0]), ','); // Write each row foreach ($data as $row) { fputcsv($csv, $row, ','); } // Close handle fclose($csv); } }
4ef877122cd7d2d7a1ee9fb93a14c3d116660016
[ "Markdown", "PHP" ]
12
PHP
devboxr/datetime-test
4e73cb15d890cbb57961ab4cada37f0890c5b7d8
f574387ffc70ba69bd2eb8b9042996e32cf17cc2
refs/heads/master
<file_sep>import React, { Component } from 'react'; import './covidTracker.styles.css'; class CovidTracker extends Component { constructor(){ super(); this.state = { users: [], search: "" } } componentDidMount() { fetch('https://corona.lmao.ninja/v2/countries') .then(response => response.json()) .then(data => this.setState({ users: data })) } handleInput = (event) => { let x = event.target.value; this.setState({search:x}) } handleClick = (e) => { e.preventDefault(); let filteredValues = this.state.users.filter(a=>{ return this.state.search === a.country}); console.log(filteredValues); filteredValues.map(a=>{return this.setState({search: console.log(a.country)})}); } render() { return( <div><br/> <input className="LeftAlign" onChange={this.handleInput}></input> <button onClick={this.handleClick}>Search</button><br/><br/> <table> <tr> <th>Country</th> <th>Total Cases</th> <th>Active Cases</th> <th>Deaths</th> </tr> {this.state.users.map(a=>{return <tbody id="customers"> <tr> <td>{a.country}</td> <td>{a.cases}</td> <td>{a.activePerOneMillion}</td> <td>{a.deaths}</td> </tr> </tbody> })}; </table> </div> ) } } export default CovidTracker;
07699fff4800e56f5e5052bf58a7f1cecf084941
[ "JavaScript" ]
1
JavaScript
bhumikasha/CovidTracker
b57d70d21ab43507ec03c3fe06ce9e34a682c8cd
94cc4cb669122d3be22eafc83e044fa9aec05e3f
refs/heads/master
<repo_name>ViniciusDeep/desafio-mobile-platform<file_sep>/desafio/Scenes/Advertisements/Domain/Interactor/ListAdsInteractor.swift // // AdsListInteractor.swift // desafio // // Created by <NAME> on 27/06/21. // import ONetwork protocol AdsListBussinessLogic { func fetch() } final class AdsListInteractor { let repository: AdsListConfigurableRepository let presenter: AdsListPresentationLogic init(repository: AdsListConfigurableRepository = AdsListRepository(), presenter: AdsListPresentationLogic = AdsListPresenter()) { self.repository = repository self.presenter = presenter } } extension AdsListInteractor: AdsListBussinessLogic { func fetch() { repository.fetchAds { (result) in switch result { case .failure(let error): self.presenter.show(error: error) case .success(let ads): self.presenter.show(ads: ads) } } } } <file_sep>/desafio/Scenes/Advertisements/Presenter/AdsListViewModel.swift // // AdsListViewModel.swift // desafio // // Created by <NAME> on 27/06/21. // import Foundation struct AdsListViewModel { let ads: [Ad] var adsCount: Int { return self.ads.count } func formatItem(for index: Int) -> Ad { self.ads[index] } } <file_sep>/desafio/Scenes/Advertisements/View/CustomView/AdListCardViewCell.swift // // AdListCardViewCell.swift // desafio // // Created by <NAME> on 15/04/21. // import UIKit import OUIKit import Reusable class AdListCardViewCell: UICollectionViewCell, NibLoadable, Reusable { static var nibName = "AdListCardViewCell" static var reuseIdentifier = "AdListCardViewCellIdentifier" //MARK: - IBOutlets @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var timeLocationLabel: UILabel! @IBOutlet weak var adImageView: UIImageView! @IBOutlet weak var adImageContainer: UIView! @IBOutlet weak var featuredBadge: UIView! @IBOutlet weak var featuredLine: UIView! override func awakeFromNib() { super.awakeFromNib() setupBorder() } //MARK: - Public @discardableResult func configure(ad: Ad?) -> AdListCardViewCell { featuredBadge.backgroundColor = UIColor(rgb: 0x6E0AD6) featuredLine.backgroundColor = UIColor(rgb: 0x6E0AD6) featuredBadge.isHidden = true featuredLine.isHidden = true guard let ad = ad else { return self } self.titleLabel.text = ad.ad.subject self.priceLabel.text = ad.ad.prices?[0].label ?? "" let location = self.getLocation(ad.ad.locations[0]) let date = Date(timeIntervalSinceReferenceDate: TimeInterval(ad.ad.list_time.value)) let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "pt-BR") dateFormatter.dateFormat = "dd/MM 'às' HH:mm" timeLocationLabel.text = "\(location) - \(dateFormatter.string(from: date))" guard let thumb = ad.ad.thumbnail else { return self } let imageUrl = "\(String(describing: thumb.base_url))/images/\(String(describing: thumb.path))" self.adImageView.downloaded(from: imageUrl) return self } private func setupBorder() { self.addRoundedCorners(withColor: UIColor.white, width: 0.0, radius: 5.0) } private func getLocation(_ location: AdLocation) -> String { if location.key == "neighbourhood" { return location.label ?? "" } guard let nextLocation = location.locations?[0] else { return "" } return getLocation(nextLocation) } } <file_sep>/desafio/Scenes/Advertisements/Presenter/AdsListPresenter.swift // // Presenter.swift // desafio // // Created by <NAME> on 27/06/21. // import ONetwork protocol AdsListPresentationLogic: AnyObject { var viewController: AdsListViewController? { get set } func show(ads: ListAds) func show(error: ProviderError) } final class AdsListPresenter { weak var viewController: AdsListViewController? } extension AdsListPresenter: AdsListPresentationLogic { func show(ads: ListAds) { viewController?.viewModel = AdsListViewModel(ads: ads.list_ads ?? []) viewController?.refeshAds() } func show(error: ProviderError) { switch error { case .cannotDecodedData: viewController?.showError(message: "Parece que tivemos um problema ao carregar seus dados", title: "Ops") case .cannotLoadData: viewController?.showError(message: "Parece que tivemos um problema interno no servidor", title: "Ops") } } } <file_sep>/.github/pull_request_template.md :sparkles: ** PR Name ** :sparkles: PR Description #### Tasks: - [X] Task Name - [X] Task Name <file_sep>/desafio/Scenes/Advertisements/AdsFactoryScene.swift // // AdsFactoryScene.swift // desafio // // Created by <NAME> on 27/06/21. // import UIKit struct AdsFactoryScene { static func make() -> UINavigationController { let presenter = AdsListPresenter() let interactor = AdsListInteractor(presenter: presenter) let viewController = AdsListViewController(interactor: interactor) presenter.viewController = viewController let navigation = UINavigationController(rootViewController: viewController) navigation.navigationBar.barTintColor = .purple return navigation } } <file_sep>/desafioTests/Scenes/Advertisements/Seeds.swift // // Seeds.swift // desafioTests // // Created by <NAME> on 27/06/21. // import Foundation @testable import desafio import ONetwork final class FakeRepository: AdsListConfigurableRepository { enum FakeRepositoryTestScenario { case withAds(ListAds) case withError(ProviderError) } var scenario: FakeRepositoryTestScenario = .withError(.cannotLoadData) init(with scenario: FakeRepositoryTestScenario = .withError(.cannotLoadData) ) { self.scenario = scenario } func fetchAds(completion: @escaping (Result<ListAds, ProviderError>) -> ()) { switch scenario { case .withAds(let ads): completion(.success(ads)) case .withError(let error): completion(.failure(error)) } } } <file_sep>/README.md <a href="https://codeclimate.com/github/ViniciusDeep/desafio-mobile-platform/maintainability"><img src="https://api.codeclimate.com/v1/badges/63c71574fd97656ca0df/maintainability" /></a> ## 🧐 DESAFIO IOS - MOBILE PLATFORM Uma das principais responsabilidades do time de *mobile platform* da OLX Brasil é evoluir constantemente a arquitetura dos nossos apps. Para isto, as pessoas engenheiras da nossa squad precisam dominar as melhores práticas de arquitetura de software (ex: modularização e desacoplamento), assim como garantir a qualidade e segurança. Desafio: Faça um fork desse repo e refatore o aplicativo para uma nova arquitetura que garanta: * Escalabilidade, ou seja, permita que novas features sejam adicionadas sem necessidade de alterar o código existente * Reuso, ou seja, permitir que partes do app possam ser reaproveitadas em outros apps * Testabilidade - Aqui gostaríamos de analisar sua implementação de testes unitários e de UI Você poderá ganhar pontos extras se (totalmente opcional): * Implementar automação de CI/CD * Habilitar ferramenta de análise estática de seu código Dica: * Como somos um time de plataforma, estamos mais interessados em analisar seus skills em arquitetura, portanto você não precisa evoluir a UI (usabilidade / telas / interface) * Para que possamos analisar o seu processo de desenvolvimento, não desenvolva tudo em uma única branch ou em um único commit Boa sorte :) ### Essa documentação também pode ser conferida na [WIKI](https://github.com/ViniciusDeep/desafio-mobile-platform/wiki/1--%F0%9F%9B%A0-Setup-&-Workflow-do-Projeto) do projeto ## 🛠 Setup & Workflow do Projeto ### Setup * 1- Clonar a branch * 2- CMD + R * 3- Para rodar os testes CMD + U #### Requisitos: * Swift 5.0 * Xcode 12.1 || 12.2 || 12.3 || 12.4 || 12.5(Versões garantidas a serem suportadas pelo projeto) * iOS 14.4 ### Workflow O projeto conta com um workflow de git que consiste na qual todo artefato que deve ser publicado em master, deve passar pela esteira de integração e rodar os testes para garantir maior integridade no projeto. #### GitHub Project Todo PR criado será automatizado no Project do Github, e passará pelas esteiras de In Progress até chegar em Done <img width="352" alt="Captura de Tela 2021-06-27 às 14 53 28" src="https://user-images.githubusercontent.com/32227073/123554672-703b6780-d757-11eb-8b5d-9db149012523.png"> ### CI + Fastlane + Code Climate = 💜 Como CI utilizamos o Github Action rodando uma pipe de teste em todo PR aberto para master em busca de maior integridade. <img width="903" alt="Captura de Tela 2021-06-27 às 00 49 22" src="https://user-images.githubusercontent.com/32227073/123532185-84dd1880-d6e1-11eb-89d5-b48954e9f8b3.png"> O Code Climate entra como uma ferramenta que gera alguns métricas do nosso código como testes, manutenabilidade, code smells e também é um dos nossos revisores: <a href="https://codeclimate.com/github/ViniciusDeep/desafio-mobile-platform/maintainability"><img src="https://api.codeclimate.com/v1/badges/63c71574fd97656ca0df/maintainability" /></a> <img width="368" alt="Captura de Tela 2021-06-27 às 00 51 34" src="https://user-images.githubusercontent.com/32227073/123532223-d4234900-d6e1-11eb-989c-ccad153a5e2b.png"> #### Branchs: Temos a branch protected sendo a master As branchs devem segui o padrão: * feature/[Name] * test/[Name] * task/[Name] * fix/[Name] #### Commits: Temos um guide de commit, onde o commit deve conter um emoji + prefix sendo eles: ✅ Referente a testes, 🔖 Documentação, 🛠 Ajuste no projeto, 🖌 Mudança no layout, 👨🏽‍🎨 Mudança na Scene * Add: * Chore: * Test: * Improvement: * Update: * Create: ## 💡 Arquitetura: A arquitetura do projeto é visada pensando em garantir maior manutenabilidade do código, com código desacoplado que nos possibilita realizar testes de maneira mais exata, para isso decidimos por usar o [Clean Swift (VIP)](https://clean-swift.com/handbook/) Nossas camadas consistem em: Scene: É a feature englobada no contexto que está sendo aplicada View: Apresenta e representa o contexto de apresentação Interactor: Representa nossa lógica de negócio referente ao contexto da Scene Presenter: Responsável pela lógica de apresentação ![](https://zonneveld.dev/wp-content/uploads/2019/05/VIP-CleanSwift-cycle.png) ## 🕸 Módulos: A modularização foi definida nos seguintes módulos: - OUIKit: Módulo com componentes de UI e segmentações de UI - ONetwork: Módulo com a camada de network. - Desafio: Módulo principal do app com as seguintes scenes ## 🔖 Débitos Técnicos Devido ao tempo alguns pontos no projeto entraram como débito técnico, e aqui elucidaremos formas de resolver * [] Testes de UI utilizando o próprio XCUITest * [] Refatorar a célula para o uso de ViewCode afim de reaproveitar mais ainda * [] Refatorar o download da imagem, para incluir cache e desacoplar a lógica a extesion de UIImageView como exemplo `[Nuke](https://github.com/kean/Nuke)` * [] Utilizar project tool para gerar os módulos e evitar o uso de XcodeProj([Xcode Gen](https://github.com/yonaskolb/XcodeGen), [Tuist](https://tuist.io/)) * [] Refatorar os modelos para retirar o uso de camel case , e usar DTO's para ficarem responsáves pela parte de transferencia de dados entre os objetos concretos * [] Utilização de lint e Dagner para aferir style guide no source * [] Setar Code Climate para pegar o coverage do Repo * [] Cobrir todos os cenários de testes com diferentes complexidades ciclomática. <file_sep>/modules/ONetwork/ONetworkTests/ONetworkTests.swift // // ONetworkTests.swift // ONetworkTests // // Created by <NAME> on 26/06/21. // import XCTest @testable import ONetwork struct FakeModel: Decodable { let id: Int let name: String } class ONetworkTests: XCTestCase { func test_failure_scenario_to_fetch() { var mockData: Data? { """ [{ "id": 2, "name": "Resident Evil Vilage" }] """.data(using: .utf8) } enum ProvideyRouter: String, ProviderEndpoint { case home = "www.any.com/home" // Something to test public var endpoint: String{ switch self { case .home: return rawValue } } } let sessionSpy = SessionSpy(dataTask: DataTaskSpy(data: mockData)) let expectation = XCTestExpectation(description: "Should show error to fetch fake model") Provider<FakeModel>(session: sessionSpy).request(router: ProvideyRouter.home, withMethod: .get, params: nil) { (result) in switch result { case .failure: expectation.fulfill() case .success(let fakeModel): XCTFail("Did not load \(fakeModel)") } } wait(for: [expectation], timeout: 1.0) } } <file_sep>/fastlane/Fastfile # This file contains the fastlane.tools configuration # You can find the documentation at https://docs.fastlane.tools # # For a list of all available actions, check out # # https://docs.fastlane.tools/actions # # For a list of all available plugins, check out # # https://docs.fastlane.tools/plugins/available-plugins # # Uncomment the line if you want fastlane to automatically update itself # update_fastlane default_platform(:ios) platform :ios do desc "Description of what the lane does" lane :custom_lane do # add actions here: https://docs.fastlane.tools/actions end end # Lane with responsible to keep testes running lane :tests do sh "xcrun simctl create iphone-11-14-4 'iPhone 11' com.apple.CoreSimulator.SimRuntime.iOS-14-4" scan( devices: ["iphone-11-14-4"], scheme: "desafio", clean: true, code_coverage: true, only_testing: ["desafioTests"] ) end <file_sep>/desafioTests/Scenes/Advertisements/AdsList.swift // // AdsList.swift // desafioTests // // Created by <NAME> on 27/06/21. // import XCTest @testable import desafio class AdsList: XCTestCase { lazy var presentationLogicSpy = AdsListPresenter() lazy var bussinessLogicSpy = AdsListInteractor(repository: FakeRepository(), presenter: presentationLogicSpy) lazy var viewController = AdsListViewController(interactor: bussinessLogicSpy) func test_scenario_when_failed_to_load_ads_at_controller() { viewController.viewDidLoad() XCTAssertEqual(viewController.collectionView.numberOfItems(inSection: 0), 0) } func test_scenario_when_sucess_to_load_ads_at_controller() { let listAds = ListAds(list_ads: [Ad(ad: AdDetail(subject: "mockSubject", thumbnail: nil, prices: nil, locations: [AdLocation(code: nil, key: nil, label: nil, locations: nil)], list_time: AdListTime(label: "mock", value: 1)))]) let repository = FakeRepository(with: .withAds(listAds)) bussinessLogicSpy = AdsListInteractor(repository: repository, presenter: presentationLogicSpy) viewController = AdsListViewController(interactor: bussinessLogicSpy) viewController.viewDidLoad() XCTAssertNil(viewController.viewModel?.adsCount) } func test_scenario_to_garantee_prensentation_logic_data() { let listAds = ListAds(list_ads: [Ad(ad: AdDetail(subject: "mockSubject", thumbnail: nil, prices: nil, locations: [AdLocation(code: nil, key: nil, label: nil, locations: nil)], list_time: AdListTime(label: "mock", value: 1)))]) self.presentationLogicSpy.viewController = viewController self.presentationLogicSpy.show(ads: listAds) self.presentationLogicSpy.viewController?.viewDidLoad() XCTAssertEqual(self.presentationLogicSpy.viewController?.viewModel?.adsCount, 1) XCTAssertEqual( self.presentationLogicSpy.viewController?.viewModel?.formatItem(for: 0).ad.subject, listAds.list_ads?[0].ad.subject) XCTAssertEqual( self.presentationLogicSpy.viewController?.viewModel?.formatItem(for: 0).ad.list_time.label, listAds.list_ads?[0].ad.list_time.label) } } <file_sep>/modules/ONetwork/ONetworkTests/Seeds.swift // // Seeds.swift // ONetworkTests // // Created by <NAME> on 26/06/21. // import Foundation @testable import ONetwork class DataTaskSpy: DataTaskSessionable { var completionHandler: ((Data?, URLResponse?, Error?) -> Void)? var data: Data? var urlResponse: URLResponse? var error: Error? init(data: Data?) { self.data = data } func resume() { completionHandler?(data, urlResponse, error) } } class SessionSpy: Sessionable { var dataTask: DataTaskSpy init(dataTask: DataTaskSpy) { self.dataTask = dataTask } func dataTask(with url: URLRequest, completion completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> DataTaskSessionable { dataTask.completionHandler = completionHandler return dataTask } } <file_sep>/modules/ONetwork/ONetwork/Service/Provider.swift // // Service.swift // ONetwork // // Created by <NAME> on 26/06/21. // import Foundation public enum ProviderMethod: String { case get = "GET" case post = "POST" case put = "PUT" case delete = "DELETE" } public enum ProviderError: Error { case cannotLoadData case cannotDecodedData } public struct Provider<T: Decodable> { let session: Sessionable public init(session: Sessionable = URLSession.shared) { self.session = session } public func request(router: ProviderEndpoint, withMethod method: ProviderMethod, params: [String : Any]?, completion: @escaping (Result<T, ProviderError>) -> () ) { method.request(session: self.session,router: router, params: params) { (result) in switch result { case .failure(let error): completion(.failure(error)) case .success(let data): do { let refund = try JSONDecoder().decode(T.self, from: data) DispatchQueue.main.async {completion(.success(refund))} } catch { DispatchQueue.main.async {completion(.failure(.cannotDecodedData))} } } } } } extension ProviderMethod { public func request(session: Sessionable,router: ProviderEndpoint, params: [String: Any]?, completion: @escaping (Result<Data, ProviderError>)-> ()) { guard let url = URL(string: router.endpoint) else {return} var urlRequest = URLRequest(url: url) urlRequest.httpMethod = rawValue do { if let dicParams = params { let data = try JSONSerialization.data(withJSONObject: dicParams, options: .init()) urlRequest.httpBody = data urlRequest.setValue("application/json", forHTTPHeaderField: "content-type") } session.dataTask(with: urlRequest) { (data, _, err) in if err != nil { completion(.failure(.cannotLoadData))} guard let data = data else {return print("Does not load data")} completion(.success(data)) }.resume() } catch { completion(.failure(.cannotLoadData)) } } } public protocol ProviderEndpoint{ var endpoint: String{ get } } <file_sep>/modules/OUIKit/OUIKit/Components/InsetLabel.swift // // InsetLabel.swift // OUIKit // // Created by <NAME> on 27/06/21. // import UIKit public final class InsetLabel: UILabel { var edgeInset: UIEdgeInsets? public func setEdgeInset(edgeInset: UIEdgeInsets) { self.edgeInset = edgeInset self.invalidateIntrinsicContentSize() } public override func drawText(in rect: CGRect) { guard let newEdgeInset = self.edgeInset else { return super.drawText(in: rect) } return super.drawText(in: rect.inset(by: newEdgeInset)) } public func intrinsicContentSize() -> CGSize { if (self.text?.count == 0 || self.edgeInset == nil) { return super.intrinsicContentSize } var superSize:CGSize = super.intrinsicContentSize superSize.height += self.edgeInset!.top + self.edgeInset!.bottom superSize.width += self.edgeInset!.left + self.edgeInset!.right return superSize } } <file_sep>/desafio/Scenes/Advertisements/Domain/Repository/ListAdsRepository.swift // // AdsListRepository.swift // desafio // // Created by <NAME> on 27/06/21. // import Foundation import ONetwork protocol AdsListConfigurableRepository { func fetchAds(completion: @escaping (Result<ListAds, ProviderError>) -> ()) } struct AdsListRepository: AdsListConfigurableRepository { func fetchAds(completion: @escaping (Result<ListAds, ProviderError>) -> ()) { let provider = Provider<ListAds>() provider.request(router: ProvideyRouter.home, withMethod: .get, params: nil) { (result) in switch result { case .failure(let error): completion(.failure(error)) case .success(let ads): completion(.success(ads)) } } } } <file_sep>/desafio/Scenes/Advertisements/Domain/Repository/ListAdsEndPoint.swift // // AdsListEndPoint.swift // desafio // // Created by <NAME> on 27/06/21. // import ONetwork public enum ProvideyRouter: String, ProviderEndpoint { case home = "https://nga.olx.com.br/api/v1.2/public/ads?lim=25&region=11&sort=relevance&state=1&lang=pt" public var endpoint: String{ switch self { case .home: return rawValue } } } <file_sep>/modules/ONetwork/ONetwork/Service/Sessionable.swift // // Sessionable.swift // ONetwork // // Created by <NAME> on 26/06/21. // import Foundation public protocol Sessionable { func dataTask(with url: URLRequest, completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> DataTaskSessionable } public protocol DataTaskSessionable { func resume() } extension URLSessionDataTask: DataTaskSessionable { } extension URLSession: Sessionable { public func dataTask(with url: URLRequest, completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> DataTaskSessionable { return dataTask(with: url, completionHandler: completion) } } <file_sep>/modules/OUIKit/OUIKit/Components/AdListViewLayout.swift // // AdListViewLayout.swift // OUIKit // // Created by <NAME> on 27/06/21. // import UIKit public final class FlowListViewLayout: UICollectionViewFlowLayout { let cardCellHeight:CGFloat = 128.0 public override init() { super.init() self.setup() } required init?(coder: NSCoder) { super.init(coder: coder) } public override func prepare() { let height:CGFloat = cardCellHeight guard let collection = self.collectionView else { return } let width:CGFloat = collection.bounds.size.width - (self.sectionInset.left * 2) self.itemSize = CGSize(width: width, height: height) } private func setup() { self.minimumLineSpacing = 10.0 self.minimumInteritemSpacing = 10.0 self.sectionInset = UIEdgeInsets(top: 10,left: 10,bottom: 10,right: 10) } } <file_sep>/desafio/Scenes/Advertisements/View/ViewController/AdsListViewController.swift // // AdsListViewController.swift // desafio // // Created by <NAME> on 13/04/21. // import UIKit import ONetwork import OUIKit import Reusable final class AdsListViewController: UIViewController { private let interactor: AdsListBussinessLogic var viewModel: AdsListViewModel? lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: .zero, collectionViewLayout: FlowListViewLayout()) collectionView.delegate = self collectionView.dataSource = self collectionView.register(cellType: AdListCardViewCell.self) return collectionView }() init(interactor: AdsListBussinessLogic) { self.interactor = interactor super.init(nibName: nil, bundle: .main) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupCollectionView() } fileprivate func setupCollectionView() { collectionView.backgroundColor = .white collectionView.translatesAutoresizingMaskIntoConstraints = false view = collectionView interactor.fetch() } } extension AdsListViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewModel?.adsCount ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { collectionView.dequeueReusableCell(for: indexPath, cellType: AdListCardViewCell.self).configure(ad: viewModel?.formatItem(for: indexPath.row)) } } extension AdsListViewController { func refeshAds() { DispatchQueue.main.async { self.collectionView.reloadData() } } func showError(message: String, title: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) self.present(alertController, animated: true, completion: nil) } } <file_sep>/desafio/Scenes/Advertisements/Entity/Ad.swift // // Ad.swift // desafio // // Created by <NAME> on 13/04/21. // import Foundation struct ListAds: Decodable { let list_ads: [Ad]? } struct Ad: Decodable { let ad: AdDetail } struct AdDetail: Decodable { let subject: String let thumbnail: AdThumbnail? let prices: [AdPrice]? let locations: [AdLocation] let list_time: AdListTime } struct AdThumbnail: Decodable { let height: Int let width: Int let path: String let base_url: String let media_id: String } struct AdPrice: Decodable { let label: String let price_value: Int } struct AdLocation: Decodable { let code: String? let key: String? let label: String? let locations: [AdLocation]? } struct AdListTime: Decodable { let label: String let value: Int } <file_sep>/modules/OUIKit/OUIKit/Extensions/UIView+Extension.swift // // UIView+Extension.swift // OUIKit // // Created by <NAME> on 27/06/21. // import UIKit public enum CALayerBorderPosition { case top case right case bottom case left } public extension UIView { //MARK: - Public func addBorderToPosition(_ position: CALayerBorderPosition, color: UIColor, width: CGFloat) -> CALayer { var border = CALayer() switch position { case .top: border = self.addTopBorder(color, width: width) case .bottom: border = self.addBottomBorder(color, width: width) case .left: border = self.addLeftBorder(color, width: width) case .right: border = self.addRightBorder(color, width: width) } return border } func addRoundedCorners(withColor color: UIColor = UIColor.clear, width: CGFloat, radius : CGFloat) { self.layer.cornerRadius = radius self.layer.borderWidth = width self.layer.masksToBounds = true self.layer.borderColor = color.cgColor } //MARK: - Private private func addTopBorder(_ color: UIColor, width: CGFloat) -> CALayer { let border = CALayer() border.backgroundColor = color.cgColor border.name = "top" border.frame = CGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: width) self.layer.addSublayer(border) return border } private func addBottomBorder(_ color: UIColor, width: CGFloat) -> CALayer { let border = CALayer() border.backgroundColor = color.cgColor border.name = "bottom" border.frame = CGRect(x: 0.0, y: self.frame.size.height - width, width: self.frame.size.width, height: width) self.layer.addSublayer(border) return border } private func addLeftBorder(_ color: UIColor, width: CGFloat) -> CALayer { let border = CALayer() border.backgroundColor = color.cgColor border.name = "left" border.frame = CGRect(x: 0.0, y: 0.0, width: width, height: self.frame.size.height) self.layer.addSublayer(border) return border } private func addRightBorder(_ color: UIColor, width: CGFloat) -> CALayer { let border = CALayer() border.backgroundColor = color.cgColor border.name = "right" border.frame = CGRect(x: self.frame.size.width - width, y: 0.0, width: width, height: self.frame.size.height) self.layer.addSublayer(border) return border } }
754c56c655cf0a4b38f662cd4c8c4f8ea64134e9
[ "Swift", "Ruby", "Markdown" ]
21
Swift
ViniciusDeep/desafio-mobile-platform
0fde443eb15a9df5b82ce57109106c372f582a4f
93c6d188a5a2554d5d30591d7561a006fbd72561
refs/heads/master
<repo_name>magrossi/news_n_stocks<file_sep>/code/stock_downloader.py import logging, datetime, time import pandas_datareader.data as web def download_stock_history(start_date, end_date, stocks, source='yahoo'): start_total_time = time.time() logging.info('downloading historical data from %s to %s for stocks %s and source %s', start_date, end_date, ', '.join(stocks), source) try: data = web.DataReader(stocks, source, start_date, end_date) return data except Exception, e: logging.error('error processing with error %s', e.message) return finally: logging.info('finished processing in %f seconds', time.time() - start_total_time) if __name__ == "__main__": # configure logger logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') # test config params stocks = ['MSFT', 'AA', 'GM'] start = datetime.datetime(2013,01,01) end = datetime.datetime(2014,10,20) stock_data = download_stock_history(start, end, stocks) pass <file_sep>/code/visualization/data.js var dataset = { nodes: [ {'group': 'stock', 'name': 'PFE'}, {'group': 'stock', 'name': 'KO'}, {'group': 'term', 'name': 'jiang'}, {'group': 'term', 'name': 'louis'}, {'group': 'term', 'name': 'political'}, {'group': 'term', 'name': 'sale'}, {'group': 'term', 'name': 'thursday'}, {'group': 'term', 'name': 'fund'}, {'group': 'term', 'name': 'officer'}, {'group': 'term', 'name': 'money'}, {'group': 'term', 'name': 'maliki'}, {'group': 'term', 'name': 'quarter'} ], edges: [ {'source': 4, 'target': 0}, {'source': 5, 'target': 0}, {'source': 11, 'target': 0}, {'source': 2, 'target': 1}, {'source': 3, 'target': 1}, {'source': 6, 'target': 1}, {'source': 7, 'target': 1}, {'source': 8, 'target': 1}, {'source': 9, 'target': 1}, {'source': 10, 'target': 1} ] }; <file_sep>/code/find_terms_n_stocks.py from statsmodels.tsa.stattools import grangercausalitytests, adfuller from statsmodels.api import OLS from kpss import kpssTest import os.path, pickle, logging, datetime, numpy as np, pandas as pd from news_calc_term_ts import get_tfidf_ts # Cointegration is a statistical property of a collection (X1,X2,...,Xk) of time series variables. # First, all of the series must be integrated of order 1 (see Order of Integration). # Next, if a linear combination of this collection is integrated of order zero, # then the collection is said to be co-integrated. def are_cointegrated(x, y): # Step 1: regress one variable on the other ols_result = OLS(x, y).fit() # Step 2: obtain the residual (ols_result.resid) # Step 3: apply Augmented Dickey-Fuller test to see whether the residual is unit root # if residuals are stationary, then there is cointegration between x, y (reject NULL) test_stat, p_value, lag, nobs, crit_values, aic_lag = adfuller(ols_result.resid) return test_stat < crit_values['5%'] def difference(ts, n=1): return (ts - ts.shift(n)).dropna() def is_stationary(kpss_result, alpha=0.05): return kpss_result[1] > alpha def find_diff_stationary(df, max_diff=5): i = 0 while i < max_diff: if is_stationary(kpssTest(np.asarray(df), verbose=False)): return (i, df, True) else: df = difference(df) i += 1 return (i, df, False) def get_stocks_caused_by(terms_panel, stock_panel, term_measure): # now do granger tests for all stocks caused_symbols = [] for symbol in stocks.columns: stock_df = stocks[[symbol]][symbol] diff_level, stock_df_diff, converged = find_diff_stationary(stock_df) if converged: # check if integrated of the same order, if so test for cointegration df_align, stock_df_align = align_dataframes(df, stock_df) if df_diff_level == diff_level and are_cointegrated(df_align, stock_df_align): lag, caused = find_granger_causality(stock_df_diff, df, max_lags=3) if caused: caused_symbols.append((symbol, lag)) #else: #print 'Symbol %s has different order of integration or is not cointegrated. Skipping.' % symbol #else: #print 'Symbol %s did not converge. Skipping.' % symbol return caused_symbols if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') logging.captureWarnings(True) from pymongo import MongoClient client = MongoClient('mongodb://localhost:27017/') db = client['news2'] daily_summaries = db['daily_summary'] period_summaries = db['period_summary'] # stock data sd = pd.read_pickle('D:/Study/DCU/MCM/Practicum/data/stock_panel.pkl') # find top n terms of the day daily_summary = period_summaries.find_one({ 'period_type' : { '$eq' : 'daily' }, 'period_end' : { '$eq' : base_date } }) daily_relevant_terms = map(lambda x : x[0], daily_summary['term_counts']) relevant_terms = daily_relevant_terms[:100] terms_panel = get_tfidf_ts(daily_summaries, relevant_terms, {}) <file_sep>/code/kpss.py """ Created on Sat Jan-03-2015 @author: <NAME> (http://denizstij.blogspot.co.uk/) """ import numpy as np import statsmodels.api as sm from scipy.interpolate import interp1d def kpssTest(x, regression = "LEVEL", lshort = True, verbose = True): """ KPSS Test for Stationarity Computes the Kwiatkowski-Phillips-Schmidt-Shin (KPSS) test for the null hypothesis that x is level or trend stationary. Parameters ---------- x : array_like, 1d data series regression : str {'LEVEL','TREND'} Indicates the null hypothesis and must be one of "Level" (default) or "Trend". lshort : bool a logical indicating whether the short or long version of the truncation lag parameter is used. Returns ------- stat : float Test statistic pvalue : float the p-value of the test. usedlag : int Number of lags used. Notes ----- Based on kpss.test function of tseries libraries in R. To estimate sigma^2 the Newey-West estimator is used. If lshort is TRUE, then the truncation lag parameter is set to trunc(3*sqrt(n)/13), otherwise trunc(10*sqrt(n)/14) is used. The p-values are interpolated from Table 1 of Kwiatkowski et al. (1992). If the computed statistic is outside the table of critical values, then a warning message is generated. Missing values are not handled. References ---------- <NAME>, <NAME>, <NAME>, and <NAME> (1992): Testing the Null Hypothesis of Stationarity against the Alternative of a Unit Root. Journal of Econometrics 54, 159--178. Examples -------- x=numpy.random.randn(1000) # is level stationary kpssTest(x) y=numpy.cumsum(x) # has unit root kpssTest(y) z=x+0.3*arange(1,len(x)+1) # is trend stationary kpssTest(z,"TREND") """ x = np.asarray(x,float) if len(x.shape)>1: raise ValueError("x is not an array or univariate time series") if regression not in ["LEVEL", "TREND"]: raise ValueError(("regression option %s not understood") % regression) n = x.shape[0] if regression=="TREND": t=range(1,n+1) t=sm.add_constant(t) res=sm.OLS(x,t).fit() e=res.resid table=[0.216, 0.176, 0.146, 0.119] else: t=np.ones(n) res=sm.OLS(x,t).fit() e=res.resid table=[0.739, 0.574, 0.463, 0.347] tablep=[0.01, 0.025, 0.05, 0.10] s=np.cumsum(e) eta=np.sum(np.power(s,2))/(np.power(n,2)) s2 = np.sum(np.power(e,2))/n if lshort: l=np.trunc(3*np.sqrt(n)/13) else: l=np.trunc(10*np.sqrt(n)/14) usedlag =int(l) s2=R_pp_sum(e,len(e),usedlag ,s2) stat=eta/s2 pvalue , msg=approx(table, tablep, stat) if verbose: print "KPSS Test for ",regression," Stationarity\n" print ("KPSS %s=%f" % (regression, stat)) print ("Truncation lag parameter=%d"% usedlag ) print ("p-value=%f"%pvalue ) if msg is not None: print "\nWarning:",msg return ( stat, pvalue, usedlag ) def R_pp_sum (u, n, l, s): tmp1 = 0.0 for i in range(1,l+1): tmp2 = 0.0 for j in range(i,n): tmp2 += u[j]*u[j-i] tmp2 = tmp2*(1.0-(float(i)/((float(l)+1.0)))) tmp1 = tmp1+tmp2 tmp1 = tmp1/float(n) tmp1 = tmp1*2.0 return s + tmp1 def approx(x,y,v): if (v>x[0]): return (y[0],"p-value smaller than printed p-value") if (v<x[-1]): return (y[-1],"p-value greater than printed p-value") f=interp1d(x,y) av=f(v) return (av,None) <file_sep>/code/analysis.r require(zoo) require(xts) require(scales) require(forecast) require(tseries) require(caret) # read term csv bank <- read.csv('term_bank_ts.csv', header = FALSE) bank_df <- data.frame(date=as.Date(bank[, 1], format="%Y-%m-%d"), value=bank[, 2]) bank_ts <- ts(bank_df$value, start=min(bank_df$date), frequency = 1) # read stock csv stock <- read.csv('stock_cvx_ts.csv', header = FALSE) stock_df <- data.frame(date=as.Date(stock[, 1], format="%Y-%m-%d"), value=stock[, 2]) stock_ts <- ts(stock_df$value, start=min(stock_df$date), frequency = 1) # intersect data data <- ts.intersect(bank_ts, stock_ts) data[is.na(data)] <- 0 # replace Na with 0 (should have been dealt with earlier) # split data into in sample and out of sample data n_test_obs = 5 split_date = tsp(data)[2]-(n_test_obs-1)/frequency(data) sample = window(data,end=split_date-1) test = window(data,start=split_date) y.sample = sample[,2] x.sample = sample[,1] y.test = test[,2] x.test = test[,1] # do arima analysis arima_coeff <- auto.arima(y.sample, xreg=x.sample) # arima_coeff (0,1,0) y.fit <- Arima(y.sample, xreg=x.sample, order = c(3,1,2)) # Plot the fitted model comparing to real data plot(fitted(y.fit), ylab="", lwd=1.5, lty=2, main = "Fitted model vs Original data") # Fitted model lines(y.sample, col=4, ylab="") # original data # predict y.forecast <- forecast(y.fit, h = nrow(x.test), xreg=x.test) # Plot the prediction and compare it with the real values par(yaxt="n") plot(y.sample, ylab="", type="o", main="Forecast") lines(y.forecast$mean,col=4,ylab="",lty=2,lwd=2,type="o") <file_sep>/code/forecasts.py from statsmodels.tsa.arima_model import ARIMA from statsmodels.tsa.stattools import arma_order_select_ic from kpss import kpssTest import os.path, pickle, logging, datetime, numpy as np, pandas as pd def difference(ts, n=1): return (ts - ts.shift(n)).dropna() def is_stationary(kpss_result, alpha=0.05): return kpss_result[1] > alpha def find_diff_stationary(df, max_diff=5): i = 0 while i < max_diff: if is_stationary(kpssTest(df, verbose=False)): return (i, df, True) else: df = difference(df) i += 1 return (i, df, False) def get_arma_order(endog, exog): if not exog is None: auto_arma_order = arma_order_select_ic(endog, ic=['aic'], model_kw={'exog':exog}, fit_kw={'exog':exog,'maxiter':100}) return auto_arma_order['aic_min_order'][0], auto_arma_order['aic_min_order'][1] else: auto_arma_order = arma_order_select_ic(endog, ic=['aic'], fit_kw={'maxiter':100}) return auto_arma_order['aic_min_order'][0], auto_arma_order['aic_min_order'][1] # order may not be correctly calculated # the auto_arma_order is not reliable at all.. def get_fitted_model(endog, exog, order, transparams=False): try: if not exog is None: return ARIMA(endog, order, exog=exog).fit(transparams=transparams,maxiter=100) else: return ARIMA(endog, order).fit(transparams=transparams,maxiter=100) except Exception as e: (ar, i, ma) = order if ma > 0: ma -= 1 elif ar > 0: ar -= 1 else: return 'fail: ' + e.message logging.warn('auto order failed: trying to fit model with lower order...') return get_fitted_model(endog, exog, (ar, i, ma), transparams=transparams) def scale_df(df): df -= df.min() # equivalent to df = df - df.min() df /= df.max() # equivalent to df = df / df.max() return df def get_forecasts(term_panel, term_measure, stock_panel, start_date, stock_symbol, term_list): logging.info('start get_forecasts for %s with terms (%s)' % (stock_symbol, ','.join(term_list))) transparams = True # let arima model do it for us ks = '[' + stock_symbol + ']' # key for stock only (no exog) ka = ','.join(term_list) # key for aggregate exogs # key for individual terms is the term itself # get endog and exog DataFrames endog = pd.DataFrame(stock_panel[stock_symbol]) endog_diff_order, endog_diff, _ = find_diff_stationary(stock_panel[stock_symbol]) exog_dic = {} for t in term_list: # difference to stationary if needed on the term DataFrame # as exog must be stationary, multiply by 10,000 to make it easier for # the optimizers as there is a considerable difference in scale between # stock and tf-idf weight if transparams: exog_dic[t] = tp[t][term_measure] * 10000 else: _, exog_dic[t], _ = find_diff_stationary(tp[t][term_measure] * 10000) # fill na of exog variables with 0.0000 as it has no score on the day exog = pd.DataFrame(exog_dic).fillna(0) # shift one day to match endog #exog = exog.set_index(exog.index.values + np.timedelta64(1,'D')) exog = exog.shift(1) # align endog and exog aligned = pd.concat([scale_df(endog),scale_df(exog)], axis=1).interpolate().dropna() # create train and test datasets train = aligned[:start_date - datetime.timedelta(days=1)] test = aligned[start_date:] # ####################### # # calculate ARIMAX orders # # ####################### # arima_orders = {} # 0: calculate without exog arma_order = get_arma_order(train[stock_symbol], None) arima_orders[ks] = (arma_order[0], 0, arma_order[1]) # 1: calculate for all (endog, exog=term) pairs for t in term_list: arma_order = get_arma_order(train[stock_symbol], train[[t]]) arima_orders[t] = (arma_order[0], 0, arma_order[1]) # 2: calculate for (endog, exog=[terms]) pair if len(term_list) > 1: arma_order = get_arma_order(train[stock_symbol], train[term_list]) arima_orders[ka] = (arma_order[0], 0, arma_order[1]) # ####################### # # fit models # # ####################### # models = {} # 0: calculate without exog models[ks] = get_fitted_model(train[stock_symbol], None, arima_orders[ks]) # 1: calculate for all (endog, exog=term) pairs for t in term_list: models[t] = get_fitted_model(train[stock_symbol], train[[t]], arima_orders[t]) # 2: calculate for (endog, exog=[terms]) pair if len(term_list) > 1: models[ka] = get_fitted_model(train[stock_symbol], train[term_list], arima_orders[ka], transparams=transparams) # ############################################## # # do forecast out-of-sample for all test dataset # # ############################################## # forecast = {} test_dates = [start_date + datetime.timedelta(days=x) for x in range(0, len(test))] for dt in test_dates: # 0: calculate without exog if not isinstance(models[ks], basestring): fval = models[ks].forecast(steps=1)[0] if ks in forecast: forecast[ks] = np.append(forecast[ks], fval) else: forecast[ks] = fval # 1: calculate for all (endog, exog=term) pairs for t in term_list: # ignore models that failed to fit if not isinstance(models[t], basestring): # forecast next value fval = models[t].forecast(steps=1, exog=test[[t]][dt:dt])[0] # add to forecast array if t in forecast: forecast[t] = np.append(forecast[t], fval) else: forecast[t] = fval # add test value to model in order to predict the next day # using train values, this way it is more realistic as how it # would be done in the real world models[t].data.endog = np.append(models[t].data.endog, test[stock_symbol][dt:dt], axis=0) models[t].data.exog = np.append(models[t].data.exog, test[[t]][dt:dt], axis=0) # 2: calculate for (endog, exog=[terms]) pair if len(term_list) > 1: # ignore if failed fitting if not isinstance(models[ka], basestring): # forecast next value fval = models[ka].forecast(steps=1, exog=test[term_list][dt:dt])[0] # add to forecast array if ka in forecast: forecast[ka] = np.append(forecast[ka], fval) else: forecast[ka] = fval # add test value to model in order to predict the next day # using train values, this way it is more realistic as how it # would be done in the real world models[ka].data.endog = np.append(models[ka].data.endog, test[stock_symbol][dt:dt], axis=0) models[ka].data.exog = np.append(models[ka].data.exog, test[term_list][dt:dt], axis=0) return { 'orders' : arima_orders, 'models': models, 'forecast_dates': test_dates, 'forecasts': forecast, 'actual': aligned[stock_symbol] } #return { stock_symbol: term_list } if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') logging.captureWarnings(True) stock_terms = pickle.load(open("D:/Study/DCU/MCM/Practicum/data/stock_terms.pkl", "rb")) tp = pd.read_pickle('D:/Study/DCU/MCM/Practicum/data/terms_panel.pkl') sd = pd.read_pickle('D:/Study/DCU/MCM/Practicum/data/stock_panel.pkl') start_date = datetime.datetime(2014,8,14) # first symbol for stock_symbol in stock_terms.keys(): fname = "D:/Study/DCU/MCM/Practicum/data/"+stock_symbol+"_forecasts.pkl" if not os.path.isfile(fname): logging.info('fitting models and forecasts for stock %s' % stock_symbol) term_list = list(stock_terms[stock_symbol]) term_measure = 'TF-IDF Score' dic = get_forecasts(tp, term_measure, sd, start_date, stock_symbol, term_list) pickle.dump(dic, open(fname, "wb")) logging.info('finished..') <file_sep>/README.md # News n' Stocks Source code for experiments on analyzing news articles to help in the stock market decision making. This code is meant to be run against a dataset of news articles saved in JSON format that follow the below format: ```json { "author": "author name", "date": "date in YYYY-MM-DD format", "text": "full article text pre-cleaned", "title": "title of article", "url": "url" } ``` ## Converting raw news files to MongoDB ### Pre-process documents into database Just import the process_items and InputItem helper from the *news_preprocessor.py* file. ```python import logging from news_preprocessor import process_items, InputItem from pymongo import MongoClient logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') input_dir = 'D:/Study/DCU/MCM/Datasets/nytimes/raw_data/' ngram_size = [1,2] filename_regex = '(?i).*(\.json)$' date_format = '%Y-%m-%d' source = 'nytimes' # example of source metadata mongo_server = 'mongodb://localhost:27017/' db_name = 'news2' # name of mongo database collection_name = 'docs' # name of mongo collection to save into client = MongoClient(mongo_server) db = client[db_name] coll = db[collection_name] # this is just a helper for my own directory structure # folders_tags = [('world', 'world')] # folders_tags = [('us', 'us'), ('U.S', 'us')] # folders_tags = [('politics', 'politics')] # folders_tags = [('BusinessDay', 'business'), ('Business Day', 'business')] folders_tags = [('business', 'business')] input_items = [] for idx, (folder, tag) in enumerate(folders_tags): input_items.append(InputItem(dir=input_dir+folder, source=source, tags=[tag], date_format=date_format, file_match_regex=filename_regex)) # inserts documents into MongoDB after insert_after documents have been produced in memory process_items(input_items, coll, ngram_sizes=ngram_size, insert_after=1000) ``` This will save the documents into a MongoDB collection in the format below. ```json { "source": "source of news article", "date": "date in the format YYYY-MM-DD", "tags": ["list", "of", "tags"], "title": "title of news article", "url": "url of article", "bag_of_words": [["ngram", ngram_frequency],..] } ``` ### Process documents into daily summary database Uses TF-IDF weighing to convert each bag of words documents into daily aggregated term weighed documents for easy converting to time series of terms and further processing. ```python import logging, datetime from pymongo import MongoClient from news_calc_daily_summary import calculate_daily_summary logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') mongo_server = 'mongodb://localhost:27017/' db_name = 'news2' # name of mongo database collection_name = 'docs' # name of mongo collection to save into mr_collection_name = 'daily_summary' # name of mongo collection to output daily summaries into client = MongoClient(mongo_server) db = client[db_name] coll = db[collection_name] calculate_daily_summary(coll, mr_collection_name, filter={}) # you can inform mongo-like filter here ``` ### Consolidate Daily Summaries into Period Summaries ###### First check available dates on your database to facilitate the process ```js db.daily_summary.aggregate( [{ $group: { _id: "AllSummaries", min_date: { $min: "$value.date" }, max_date: { $max: "$value.date" } } }]) ``` What should return something like the below. ```json { "_id" : "AllSummaries", "min_date" : ISODate("2013-01-01T00:00:00Z"), "max_date" : ISODate("2014-10-19T00:00:00Z") } ``` Then use the dates to calculate the daily period summaries. Any period summary can be calculated. Just make sure to set the period tag accordingly. ```python import logging, datetime from news_calc_period_summary import calculate_period_summary from pymongo import MongoClient from dateutil.relativedelta import relativedelta logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') mongo_server = 'mongodb://localhost:27017/' db_name = 'news2' collection_name = 'daily_summary' out_collection_name = 'period_summary' client = MongoClient(mongo_server) db = client[db_name] coll = db[collection_name] out_coll = db[out_collection_name] start = datetime.datetime(2013,01,01) end = datetime.datetime(2014,10,19) # create all period summaries (daily, weekly, monthly, yearly) curr = end while curr >= start: # daily calculate_period_summary(coll, out_coll, 'daily', curr, curr, 1000, {'_id': { '$eq': curr }}) # weekly past_week = curr - datetime.timedelta(days=7) if past_week >= start: calculate_period_summary(coll, out_coll, 'weekly', past_week, curr, 1000, {'_id': { '$gt': past_week, '$lte': curr }}) # monthly past_month = curr - relativedelta(months=1) if past_month >= start: calculate_period_summary(coll, out_coll, 'monthly', past_month, curr, 1000, {'_id': { '$gt': past_month, '$lte': curr }}) # yearly past_year = curr - relativedelta(years=1) if past_year >= start: calculate_period_summary(coll, out_coll, 'yearly', past_year, curr, 1000, {'_id': { '$gt': past_year, '$lte': curr }}) # decrease current day curr -= datetime.timedelta(days=1) ``` ### Generate time series data for any terms (ngram) The resulting time series will indicate the terms varying importance in your corpus over time. The results will be a dictionary of the input terms and for each key an array of data points with ```[date, term frequency, document frequency, tf-idf score]```. ```python import logging from news_calc_term_ts import get_tfidf_ts logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') from pymongo import MongoClient mongo_server = 'mongodb://localhost:27017/' db_name = 'news' collection_name = 'daily_summary' filter = {} client = MongoClient(mongo_server) db = client[db_name] coll = db[collection_name] terms = ['night', 'day'] logging.debug('testing get_tfidf_ts function for terms %s', ', '.join(terms)) ts = get_tfidf_ts(coll, terms, filter) logging.debug(ts) ``` <file_sep>/code/tokenizer.py # -*- coding: utf-8 -*- from nltk import pos_tag from nltk.util import ngrams from nltk.corpus import wordnet from nltk.tokenize import word_tokenize from replacers import RegexpReplacer def _get_wordnet_pos(treebank_tag): if treebank_tag.startswith('J'): return wordnet.ADJ elif treebank_tag.startswith('V'): return wordnet.VERB elif treebank_tag.startswith('N'): return wordnet.NOUN elif treebank_tag.startswith('R'): return wordnet.ADV else: return wordnet.NOUN # this is the default def _isValid(word): # clear invalid words # words with numbers in them? # is it worth removing it? return True def tokenize(raw, sizes = [1]): ''' Tokenizes raw text into word n-grams of sizes (n in sizes). Applies normal pre-processing techniques: - Removes stopwords and words with length smaller than three - Expands contractions - Splits raw text by sentence and converts text to lowercase - Lemmatizes words based on position (better than stemming) >>> list(tokenize(u'My super text. It's awesome!', [1,2,3])) [u'super', u'text', u'super text', u'awesome'] ''' # load expensive imports only once even if you call the function multiple times # http://blender.stackexchange.com/questions/2665/how-can-i-do-a-one-time-initialization # answer by: ideasman42 if tokenize.pre_load is None: # logs initialization import logging logging.debug('initializing tokenize...') tokenize.pre_load = {} # stopwords dictionary from nltk.corpus import stopwords tokenize.pre_load['stopwords'] = set(stopwords.words('english')) # PunktSentenceTokenizer for english import nltk.data tokenize.pre_load['sent_tokenizer'] = nltk.data.load('tokenizers/punkt/english.pickle') # PorterStemmer stemmer from nltk.stem import PorterStemmer tokenize.pre_load['stemmer'] = PorterStemmer() # WordNetLemmatizer lemmatizer from nltk.stem import WordNetLemmatizer tokenize.pre_load['lemmatizer'] = WordNetLemmatizer() # lemmatizer.lemmatize('cooking', pos='v') # use nltk.pos_tag() then convert using get_wordnet_pos() # must analyze the structure of the sentence first logging.debug('tokenize initialized') # returns word ngrams up to max_size for sentence in tokenize.pre_load['sent_tokenizer'].tokenize(raw): # tokenize sentence into words removing stopwords and punctuation raw_words = [w for w in word_tokenize(RegexpReplacer().replace(sentence.lower())) if len(w) > 3 and w not in tokenize.pre_load['stopwords'] and _isValid(w)] # tag words and lemmatize (instead of stemming) words = [tokenize.pre_load['lemmatizer'].lemmatize(tw[0], pos=_get_wordnet_pos(tw[1])) for tw in pos_tag(raw_words)] # then return ngrams of sizes of the resulting bag of words for i in sizes: for w in ngrams(words, i): yield ' '.join(w) tokenize.pre_load = None if __name__ == "__main__": print list(tokenize(u'My super text. It\'s awesome! Be careful of terrorist attacks!', [2, 3])) <file_sep>/code/pip.py from fastpip import pip import matplotlib.pyplot as plt def _pandas_to_xy_array(pd_df): xy = [] i = 0 for val in pd_df.as_matrix(): xy.append([i, val]) i += 1 return xy def _pip_array_to_dates(pd_df, pip_array): dates = [] for date_index, value in pip_array: dates.append(pd_df.index[date_index]) return dates def get_pip_dates(df, k): return _pip_array_to_dates(df, pip(_pandas_to_xy_array(df), k)) if __name__ == "__main__": import datetime, pandas as pd, pandas.io.data as web, matplotlib, matplotlib.pyplot as plt matplotlib.style.use('ggplot') data = web.DataReader(['IBM'], 'yahoo', datetime.datetime(2013,01,01), datetime.datetime(2014,01,01)) df = data.ix['Close',:,'IBM'] dates = get_pip_dates(df, 15) # plot df.plot() plt.plot_date(x=dates, y=df[dates]) plt.show() <file_sep>/code/replacers.py # -*- coding: utf-8 -*- import re, string ################################################## ## Replacing Words Matching Regular Expressions ## ################################################## replacement_patterns = [ (u'won[\'\u2018\u2019]t', 'will not'), (u'can[\'\u2018\u2019]t', 'cannot'), (u'i[\'\u2018\u2019]m', 'i am'), (u'ain[\'\u2018\u2019]t', 'is not'), (u'(\w+)[\'\u2018\u2019]ll', '\g<1> will'), (u'(\w+)n[\'\u2018\u2019]t', '\g<1> not'), (u'(\w+)[\'\u2018\u2019]ve', '\g<1> have'), (u'[\u201c\u201d\"]', ''), (u'(\w+)[\'\u2018\u2019]s', '\g<1> is'), (u'(\w+)[\'\u2018\u2019]re', '\g<1> are'), (u'(\w+)[\'\u2018\u2019]d', '\g<1> would'), (ur'[{}]'.format(string.punctuation), ' '), ] class RegexpReplacer(object): """ Replaces regular expression in a text. >>> replacer = RegexpReplacer() >>> replacer.replace("can't is a contraction") 'cannot is a contraction' >>> replacer.replace("I should've done that thing I didn't do") 'I should have done that thing I did not do' """ def __init__(self, patterns=replacement_patterns): self.patterns = [(re.compile(regex), repl) for (regex, repl) in patterns] def replace(self, text): s = text for (pattern, repl) in self.patterns: s = re.sub(pattern, repl, s) return s <file_sep>/code/analysis_2_diff.r require(zoo) require(xts) require(scales) require(forecast) require(tseries) require(caret) # read term csv symbol <- 'KO' symbol_term_csv <- read.csv(paste(symbol, '_aligned_with_terms_diff.csv', sep=''), header = TRUE) symbol_term_csv[,1] <- as.Date(symbol_term_csv[,1], format="%Y-%m-%d") # transform into time seris symbol_term_xts <- as.xts(symbol_term_csv[,-1], symbol_term_csv[,1]) # split data into in sample and out of sample data split_date = as.Date('2014-8-14') sample = window(symbol_term_xts,end=split_date-1) test = window(symbol_term_xts,start=split_date) y.all = symbol_term_xts[,1] y.sample = sample[,1] x.sample = sample[,7] y.test = test[,1] x.test = test[,7] # do arima analysis using auto.arima y.fit <- auto.arima(y.sample, xreg=x.sample) y.fit.simple <- auto.arima(y.sample) # Plot the fitted model comparing to real data plot(fitted(y.fit), col="red", ylab="", main = "Fitted model vs Original data") # Fitted model lines(fitted(y.fit.simple), col="pink", ylab="") lines(as.ts(y.sample), col="blue", ylab="") # original data # predict y.forecast <- forecast(y.fit, h = nrow(x.test), xreg=x.test) # Plot the prediction and compare it with the real values par(yaxt="n") plot(as.ts(y.all), ylab="", col="blue", main="Forecast") lines(y.forecast$mean,col="red",ylab="",lty=2,lwd=2) <file_sep>/code/news_calc_daily_summary.py import logging, time, datetime from bson.code import Code from bson.son import SON def _mapper(): return Code(""" function () { var key = this.date, doc = {}; doc[this._id] = true; this.bag_of_words.forEach(function (w) { var term = {}; term[w[0]] = [w[1], 1]; emit(key, { terms : term, docs: doc }); }); } """) def _reducer(): return Code(""" function (dt, values) { var a = values[0], b; for (var i = 1; i < values.length; i++) { b = values[i]; // aggregate the terms Object.keys(b.terms).forEach(function(k) { if (k in a.terms) { a.terms[k][0] += b.terms[k][0]; a.terms[k][1] += b.terms[k][1]; } else { a.terms[k] = b.terms[k]; } }); // aggregate the docs Object.keys(b.docs).forEach(function(k) { if (!(k in a.docs)) { a.docs[k] = true; } }); } return a; } """) def _finalizer(): return Code(""" function (dt, summary) { var d = { date: dt, total_docs: Object.keys(summary.docs).length, total_terms: Object.keys(summary.terms).length, term_counts: summary.terms }; // calculate the tf-idf (daily) per term for (var key in d.term_counts) { var tf = d.term_counts[key][0] / d.total_terms, idf = Math.log(d.total_docs/d.term_counts[key][1]); d.term_counts[key].push(tf * idf); } return d; } """) def calculate_daily_summary(mongo_collection, result_collection_name, filter={}): ''' Calculates the daily summary from mongo_collection and produces a document of the format: { _id: date, value: { date: date, total_docs: total docs in date, total_terms: total terms in date, term_counts: { term: [frequency, doc frequency, tfidf score], ... } } } Saves the results into result_collection_name. ''' start_time = time.time() logging.info('applying map reduce with filter %s', filter) result = mongo_collection.map_reduce(_mapper(), _reducer(), out=SON([('merge', result_collection_name),]), query=filter, finalize=_finalizer(), full_response=True) logging.info(result) logging.info('finished processing in %f seconds', time.time() - start_time) if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') from pymongo import MongoClient mongo_server = 'mongodb://localhost:27017/' db_name = 'test_news_db2' collection_name = 'docs' mr_collection_name = 'daily_summary' filter = { 'date': { '$gte': datetime.datetime(2000, 01, 01), '$lt': datetime.datetime(2100, 01, 02) } } client = MongoClient(mongo_server) db = client[db_name] coll = db[collection_name] calculate_daily_summary(coll, mr_collection_name, filter) pass <file_sep>/code/pandas_to_csv.py from statsmodels.tsa.arima_model import ARIMA from statsmodels.tsa.stattools import arma_order_select_ic from kpss import kpssTest import os.path, pickle, logging, datetime, numpy as np, pandas as pd def difference(ts, n=1): return (ts - ts.shift(n)).dropna() def is_stationary(kpss_result, alpha=0.05): return kpss_result[1] > alpha def find_diff_stationary(df, max_diff=5): i = 0 while i < max_diff: if is_stationary(kpssTest(df, verbose=False)): return (i, df, True) else: df = difference(df) i += 1 return (i, df, False) def save_to_csv(term_panel, term_measure, stock_panel, stock_symbol, term_list): logging.info('saving data for %s and %s' % (stock_symbol, ','.join(term_list))) # get endog and exog DataFrames endog = pd.DataFrame(stock_panel[stock_symbol]) endog_log_ret = np.log(endog) - np.log(endog.shift(1)) exog_dic = {} exog_dic_diff = {} for t in term_list: exog_dic[t] = tp[t][term_measure] _, exog_dic_diff[t], _ = find_diff_stationary(tp[t][term_measure]) # fill na of exog variables with 0.0000 as it has no score on the day exog = pd.DataFrame(exog_dic).fillna(0) exog_diff = pd.DataFrame(exog_dic_diff).fillna(0) # shift one day to match endog exog = exog.shift(1) exog_diff = exog_diff.shift(1) # align endog and exog aligned = pd.concat([endog,exog], axis=1).interpolate().dropna() aligned_diff = pd.concat([endog,exog_diff], axis=1).interpolate().dropna() aligned_log_ret = pd.concat([endog_log_ret,exog], axis=1).interpolate().dropna() aligned_log_ret_diff = pd.concat([endog_log_ret,exog_diff], axis=1).interpolate().dropna() # save to csv so R can read it aligned.to_csv('D:/Study/DCU/MCM/Practicum/data/' + stock_symbol + '_aligned_with_terms.csv') aligned_diff.to_csv('D:/Study/DCU/MCM/Practicum/data/' + stock_symbol + '_aligned_with_terms_diff.csv') aligned_log_ret.to_csv('D:/Study/DCU/MCM/Practicum/data/' + stock_symbol + '_aligned_log_ret_with_terms.csv') aligned_log_ret_diff.to_csv('D:/Study/DCU/MCM/Practicum/data/' + stock_symbol + '_aligned_log_ret_with_terms_diff.csv') if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') logging.captureWarnings(True) stock_terms = pickle.load(open("D:/Study/DCU/MCM/Practicum/data/stock_terms.pkl", "rb")) tp = pd.read_pickle('D:/Study/DCU/MCM/Practicum/data/terms_panel.pkl') sd = pd.read_pickle('D:/Study/DCU/MCM/Practicum/data/stock_panel.pkl') term_measure = 'TF-IDF Score' # first symbol for stock_symbol in stock_terms.keys(): logging.info('saving stock %s and related words to csv..' % stock_symbol) term_list = list(stock_terms[stock_symbol]) save_to_csv(tp, term_measure, sd, stock_symbol, term_list) logging.info('finished..') <file_sep>/code/news_calc_term_ts.py import logging, time, datetime, math, heapq, pandas as pd from bson.code import Code def get_tfidf_ts(input_collection, terms, filter): ''' returns len(terms) time series with count, doc_count and tfidf for each term ''' start_time = time.time() logging.info('finding term time series with %s', filter) cursor = input_collection.find(filter) ct = 0 data = {} # data for ts of term idx = {} # index for ts of term # build data and index arrays for term in terms: idx[term] = [] data[term] = [] for dsum in cursor: ct += 1 for term in terms: if term in dsum['value']['term_counts']: data[term].append(dsum['value']['term_counts'][term]) # counts = [count, doc_count, tfidf] idx[term].append(dsum['value']['date']) # index date # build pandas dataframe out of previously calcualted arrays dfs = {} for term in terms: dfs[term] = pd.DataFrame(data[term], index=idx[term], columns=['Count', 'Document Count', 'TF-IDF Score']) return pd.Panel(dfs) logging.info('finished processing %d documents in %f seconds', ct, time.time() - start_time) if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') from pymongo import MongoClient mongo_server = 'mongodb://localhost:27017/' db_name = 'test_news_db2' collection_name = 'daily_summary' filter = { '_id': { '$gte': datetime.datetime(2000, 01, 01), '$lt': datetime.datetime(2100, 01, 02) } } client = MongoClient(mongo_server) db = client[db_name] coll = db[collection_name] terms = ['night', 'day'] logging.debug('testing get_tfidf_ts function for terms %s', ', '.join(terms)) panel = get_tfidf_ts(coll, terms, filter) logging.debug(panel) pass <file_sep>/code/news_calc_period_summary.py import logging, time, datetime, math, heapq from bson.code import Code def calculate_period_summary(input_collection, output_collection, period_type, period_start, period_end, max_terms=1000, filter={}): ''' Merges daily summary type documents into a merged document of the format: { _id: <auto>, period_type: 'daily', // daily, weekly, monthly, bi-yearly, yearly,.. custom.. period_start: period_start, period_end: period_end, actual_start: <min date>, actual_end: <max date>, total_docs: <total docs in period>, total_terms: <total terms in period>, term_counts: [ // sorted by tfidf score and limited to 'n' top entries [term, frequency, doc frequency, tfidf score], ... ] } Saves the results into result_collection_name. ''' start_time = time.time() logging.info('finding %s summaries with filter %s ', period_type, filter) cursor = input_collection.find(filter) ct = 0 summ = { 'period_type': period_type, 'period_start': period_start, 'period_end': period_end, 'actual_start': datetime.datetime.max, 'actual_end': datetime.datetime.min, 'total_docs': 0, 'total_terms': 0, 'term_counts': [] } terms = {} for dsum in cursor: ct += 1 summ['actual_start'] = summ['actual_start'] if summ['actual_start'] < dsum['value']['date'] else dsum['value']['date'] summ['actual_end'] = summ['actual_end'] if summ['actual_end'] > dsum['value']['date'] else dsum['value']['date'] summ['total_docs'] += dsum['value']['total_docs'] summ['total_terms'] += dsum['value']['total_terms'] for term, counts in dsum['value']['term_counts'].iteritems(): if term in terms: terms[term][0] += counts[0] # ter frequency terms[term][1] += counts[1] # doc frequency else: terms[term] = counts # tfidf score will be overritten later if ct > 0: terms_arr = [] for term, counts in terms.iteritems(): tf = counts[0] / summ['total_terms'] idf = math.log(summ['total_docs'] / counts[1]) terms_arr.append([term, counts[0], counts[1], tf * idf]) summ['term_counts'] = heapq.nlargest(max_terms, terms_arr, key=lambda x: x[3]) logging.info('total of %d documents processed', ct) logging.info('saving to out collection...') output_collection.insert(summ) else: logging.info('no documents found on interval') logging.info('finished processing in %f seconds', time.time() - start_time) if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') from pymongo import MongoClient mongo_server = 'mongodb://localhost:27017/' db_name = 'test_news_db2' collection_name = 'daily_summary' out_collection_name = 'period_summary' start = datetime.datetime(2000, 01, 01) end = datetime.datetime(2100, 01, 02) filter = { '_id' : { '$gte': start, '$lte': end } } client = MongoClient(mongo_server) db = client[db_name] coll = db[collection_name] out_coll = db[out_collection_name] calculate_period_summary(coll, out_coll, 'all', start, end, 100) pass <file_sep>/code/news_preprocessor.py # -*- coding: utf-8 -*- import json, sys, os, time, datetime, re, logging, string from tokenizer import tokenize from itertools import chain, islice from collections import Counter def _process_file(filename, source, date_format, fixed_tags=[], ngram_sizes=[1]): try: with open(filename, 'rb') as f: # Load article in JSON format # { # "author":"<NAME>", # "category":"BusinessDay", # "date":"2013-01-11", # "description":"I always want to...", # "text":"In my last , She Owns It members..", # "textType":"Blogs", # "title":"Business Owners Reflect...", # "url":"http://boss.blogs.nytimes.com/2013/01/11/business-owners-reflect-on-small-victories-and-the-dangers-of-growth/" # } data = json.load(f) # { # source: 'nytimes', # date: '2013-01-01', # tags: [], # title: 'title', # url: 'http://dealbook.nytimes.com/2013/01/01/ackman-herbalife-and-celebrity-short-sellers/', # bag_of_words: [] # } return { 'source': source, 'date': datetime.datetime.strptime(data['date'], date_format), 'tags': fixed_tags, 'title': data['title'], 'url': data['url'], 'bag_of_words': _get_term_frequencies(tokenize(data['text'], ngram_sizes)) } except Exception, e: logging.error('processing %s with error %s', filename, e.message) return None def _get_term_frequencies(tokens): ''' returns a sorted list of sorted term frequencies tuples [ ('term': frequency), .. ] ''' return list(Counter(tokens).most_common()) def _get_files_to_process(initial_dir, match_regex=None, recursive=True): for root, dirs, files in os.walk(initial_dir): for f in files: if match_regex is None or re.search(match_regex, f): yield os.path.join(root, f) def _process_all_files(initial_dir, source, date_format, fixed_tags=[], ngram_sizes=[1], match_regex=None, recursive=True): processed = 0 errored = 0 for filename in _get_files_to_process(initial_dir, match_regex, recursive): doc = _process_file(filename, source, date_format, fixed_tags, ngram_sizes) if doc is not None and len(doc['bag_of_words']) > 0: yield doc processed += 1 else: errored += 1 logging.info('%d docs processed %d successfull and %d errored', processed + errored, processed, errored) def _chunks(iterable, size=100): iterator = iter(iterable) for first in iterator: yield list(chain([first], islice(iterator, size - 1))) class InputItem(object): ''' helper class to hold input configuration ''' def __init__(self, dir, source='', tags=[], date_format='%Y-%m-%d', file_match_regex='(?i).*(\.json)$'): self.dir = dir self.source = source self.tags = tags self.date_format = date_format self.regex = file_match_regex def get_conf(self): return (self.dir, self.source, self.tags, self.date_format, self.regex) def process_items(inputs, mongo_collection, ngram_sizes=[1], insert_after=1000): logging.info('starting to process %d items', len(inputs)) start_total_time = time.time() total_inserted = 0 for dir, source, tags, date_format, regex in map((lambda i: i.get_conf()), inputs): partial_inserted = 0 try: start_time = time.time() logging.info('processing item [dir: %s, source: %s, tags: %s, date_format: %s, regex: %s', dir, source, tags, date_format, regex) for chunk in _chunks(_process_all_files(dir, source, date_format, tags, ngram_sizes, regex), insert_after): res = mongo_collection.insert_many(chunk) logging.info('inserted %d items into db', len(res.inserted_ids)) partial_inserted += len(res.inserted_ids) logging.info('finished processing %d items on dir %s in %f seconds, avg of %f seconds per item', total_inserted, dir, time.time() - start_time, partial_inserted if partial_inserted <= 0 else (time.time() - start_time)/partial_inserted) except Exception, e: logging.error('failed processing dir %s with error %s after %f seconds', dir, e.message, time.time() - start_time) total_inserted += partial_inserted logging.info('finished processing %d items for all dirs in %f seconds', total_inserted, time.time() - start_total_time) if __name__ == "__main__": # configure logger logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s') # test config params input_dir = 'D:/Study/DCU/MCM/Datasets/nytimes/raw_data/sundayreview' ngram_sizes = [1,2,3] filename_regex = '(?i).*(\.json)$' date_format = '%Y-%m-%d' # date_format = '%Y-%m-%d' if has_time else '%Y-%m-%d %H:%M:%S' source = 'nytimes' fixed_tags = ['review'] mongo_server = 'mongodb://localhost:27017/' db_name = 'test_news_db2' collection_name = 'docs' # get mongo collection to insert results to from pymongo import MongoClient client = MongoClient(mongo_server) db = client[db_name] coll = db[collection_name] # process all process_items([InputItem(dir=input_dir, source=source, tags=fixed_tags, date_format=date_format, file_match_regex=filename_regex)], coll, ngram_size=ngram_sizes, insert_after=1000) <file_sep>/sample_data/news/readme.md Sample news data from the NY Time "Sunday Review" section.<file_sep>/code/relate_news_stocks.py import datetime, numpy as np, pandas as pd from statsmodels.tsa.stattools import grangercausalitytests from kpss import kpssTest from stock_downloader import download_stock_history from news_calc_term_ts import get_tfidf_ts def difference(ts, n=1): return (ts - ts.shift(n)).dropna() # Testing the Null Hypothesis of Stationarity against the Alternative of a Unit Root def is_stationary(kpss_result, alpha=0.05): return kpss_result[1] > alpha def find_diff_stationary(df, max_diff=5): i = 0 while i < max_diff: arr = np.asarray(df) if is_stationary(kpssTest(arr, regression = 'LEVEL', verbose=False)) and is_stationary(kpssTest(arr, regression = 'TREND', verbose=False)): return (i, df, True) else: df = difference(df) i += 1 return (i, df, False) # The Null hypothesis for grangercausalitytests is that the time series in the second column, x2, # does NOT Granger cause the time series in the first column, x1. Grange causality means that past # values of x2 have a statistically significant effect on the current value of x1, taking past # values of x1 into account as regressors. We reject the null hypothesis that x2 does not Granger # cause x1 if the pvalues are below a desired size of the test. def is_granger_caused(test_results, alpha=0.05): for lag, r in test_results.iteritems(): p_values = [r[0]['lrtest'][1], r[0]['params_ftest'][1], r[0]['ssr_ftest'][1], r[0]['ssr_chi2test'][1]] if all(p_value < alpha for p_value in p_values): return (lag, True) return (len(test_results), False) def find_granger_causality(x1_df, x2_df, max_lags=5): data = pd.concat([x1_df, x2_df], axis=1).dropna() lag_1_2, causes_1_2 = is_granger_caused(grangercausalitytests(data[[0, 1]], max_lags, verbose=False)) # x1 causes x2 lag_2_1, causes_2_1 = is_granger_caused(grangercausalitytests(data[[1, 0]], max_lags, verbose=False)) # x2 causes x1 # x2 only granger-causes x1 if, and only if, x1 does NOT cause x2 and x2 CAUSES x1 return (lag_2_1, True if causes_2_1 and not causes_1_2 else False) def relate_term_n_stock_ts(term_panel, stocks_panel): # both term_df and stock_df must be stationary # for all stock dfs do: r = grangercausalitytests(stock, max_lags, verbose=False): # result dictionary of terms list of stocks that are granger-caused by term_df def convert_to_matrix(pd_df, col=0): i = 0 for arr in pd_df.as_matrix(): value = arr[0] yield [i, value] i += 1 period_summaries = db['period_summary'] query = period_summaries.aggregate([{ '$group': { '_id': 'date_range', 'min_date': { '$min': '$period_start' }, 'max_date': { '$max': '$period_end' } } }]).next() r = grangercausalitytests(np.random.random((100,2)), 5, addconst=True, verbose=True): example: r[1][0]['lrtest'] r = { 1: ({'lrtest': (2.5498146592526325, 0.11030719462362751, 1), 'params_ftest': (2.5046637818898794, 0.11679877991627048, 96.0, 1), 'ssr_ftest': (2.5046637818898669, 0.1167987799162722, 96.0, 1), 'ssr_chi2test': (2.5829345250739255, 0.1080212350855112, 1)},.... 2: ({'lrtest': ... 3: ... 4: ... 5: ... } >>> r[1][0]['lrtest'] only one df variable.. (1.3813412379881242, 0.23987281780151004, 1) >>> r[1][0]['params_ftest'] Test (F or Chi2), p-value, df_denom, df_num (1.3488708874609374, 0.24835521552836354, 96.0, 1) Granger Causality ('number of lags (no zero)', 1) ssr based F test: F=1.3489 , p=0.2484 , df_denom=96, df_num=1 ssr based chi2 test: chi2=1.3910 , p=0.2382 , df=1 likelihood ratio test: chi2=1.3813 , p=0.2399 , df=1 parameter F test: F=1.3489 , p=0.2484 , df_denom=96, df_num=1 Granger Causality ('number of lags (no zero)', 2) ssr based F test: F=0.9479 , p=0.3913 , df_denom=93, df_num=2 ssr based chi2 test: chi2=1.9977 , p=0.3683 , df=2 likelihood ratio test: chi2=1.9776 , p=0.3720 , df=2 parameter F test: F=0.9479 , p=0.3913 , df_denom=93, df_num=2 Granger Causality ('number of lags (no zero)', 3) ssr based F test: F=0.8053 , p=0.4942 , df_denom=90, df_num=3 ssr based chi2 test: chi2=2.6038 , p=0.4568 , df=3 likelihood ratio test: chi2=2.5695 , p=0.4629 , df=3 parameter F test: F=0.8053 , p=0.4942 , df_denom=90, df_num=3 Granger Causality ('number of lags (no zero)', 4) ssr based F test: F=0.6327 , p=0.6405 , df_denom=87, df_num=4 ssr based chi2 test: chi2=2.7927 , p=0.5931 , df=4 likelihood ratio test: chi2=2.7528 , p=0.6000 , df=4 parameter F test: F=0.6327 , p=0.6405 , df_denom=87, df_num=4 Granger Causality ('number of lags (no zero)', 5) ssr based F test: F=0.5537 , p=0.7351 , df_denom=84, df_num=5 ssr based chi2 test: chi2=3.1312 , p=0.6798 , df=5 likelihood ratio test: chi2=3.0807 , p=0.6875 , df=5 parameter F test: F=0.5537 , p=0.7351 , df_denom=84, df_num=5
a4bd67048a821548d9b73d9064d7518589f81a81
[ "JavaScript", "Python", "R", "Markdown" ]
18
Python
magrossi/news_n_stocks
9eceff6d89b909f3240c02a52ac675d0b6fafc58
db62ff1f38db9f0e797b7641f30e986d1ae9cbc4
refs/heads/master
<file_sep>package org.techtown.webbrowser; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; public class MainActivity extends AppCompatActivity { boolean isPageOpen = false; Animation translateBottomAnim, translateTopAnim; LinearLayout page; Button openButton; private WebView webView; private Button loadButton; @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); page = (LinearLayout) findViewById(R.id.page); translateBottomAnim = AnimationUtils.loadAnimation(this, R.anim.translate_bottom); translateTopAnim = AnimationUtils.loadAnimation(this, R.anim.translate_top); SlidingPageAnimationListener animListener = new SlidingPageAnimationListener(); translateBottomAnim.setAnimationListener(animListener); translateTopAnim.setAnimationListener(animListener); openButton = (Button) findViewById(R.id.openButton); openButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isPageOpen) { page.startAnimation(translateTopAnim); } else { page.setVisibility(View.VISIBLE); page.startAnimation(translateBottomAnim); } } }); webView = (WebView) findViewById(R.id.webView); WebSettings wbSettings; //웹뷰세팅 webView.setWebViewClient(new WebViewClient()); // 클릭시 새창 안뜨게 wbSettings = webView.getSettings(); //세부 세팅 등록 wbSettings.setJavaScriptEnabled(true); // 웹페이지 자바스클비트 허용 여부 wbSettings.setSupportMultipleWindows(false); // 새창 띄우기 허용 여부 wbSettings.setJavaScriptCanOpenWindowsAutomatically(false); // 자바스크립트 새창 띄우기(멀티뷰) 허용 여부 wbSettings.setLoadWithOverviewMode(true); // 메타태그 허용 여부 wbSettings.setUseWideViewPort(true); // 화면 사이즈 맞추기 허용 여부 wbSettings.setSupportZoom(false); // 화면 줌 허용 여부 wbSettings.setBuiltInZoomControls(false); // 화면 확대 축소 허용 여부 wbSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); // 컨텐츠 사이즈 맞추기 wbSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); // 브라우저 캐시 허용 여부 wbSettings.setDomStorageEnabled(true); // 로컬저장소 허용 여부 webView.setWebChromeClient(new WebChromeClient()); final EditText urlEditText = (EditText) findViewById(R.id.urlEditText); loadButton = (Button) findViewById(R.id.loadButton); loadButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String urlInput = urlEditText.getText().toString(); // webView.loadUrl("https://" + urlInput); webView.loadUrl("http://www.naver.com"); page.startAnimation(translateTopAnim); } }); } private class SlidingPageAnimationListener implements Animation.AnimationListener { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (isPageOpen) { page.setVisibility(View.INVISIBLE); openButton.setText("Open"); isPageOpen = false; } else { openButton.setText("Close"); isPageOpen = true; } } @Override public void onAnimationRepeat(Animation animation) { } } }
f5f8637ea7f551dfc2b0f77897ccfa4312c6637f
[ "Java" ]
1
Java
ksy1231/WebBrowser
5960969a779b27dcb7fca99bc25504ca54ea8095
c55f29e4a69442b63027065bf630ff6c65ed4396
refs/heads/master
<repo_name>vanessasickles/urpg-theme-2020<file_sep>/README.md # URPG WordPress Theme - 2020 This is the repository for the building of the new pokemonurpg.com WordPress theme. ## Setup (WIP) 1. Clone this repository to your desired folder using [Git](https://git-scm.com/), or a GUI for Git such as the [GitHub Desktop](https://desktop.github.com/) client. 2. Set up your local environment through your desired method. I use [MAMP](https://www.mamp.info/en/mamp/), but you may use whatever you prefer. <file_sep>/.github/ISSUE_TEMPLATE/development-task.md --- name: Development Task about: Default template for standard development tasks. title: '' labels: '' assignees: '' --- # Overview An overview of the task's purpose. What does this task accomplish? ## Tasks * [ ] Task that needs to be completed to close the issue. <file_sep>/wp-content/themes/urpg-2020/front-page.php <?php get_header(); ?> <main> <div class="container"> test text <hr> testjskldfj </div> </main> <?php get_footer(); ?><file_sep>/wp-content/themes/urpg-2020/navigation.php <nav> <div class="container"> <div class="logo"> </div> <div class="main-nav"> <?php wp_nav_menu(array( 'theme_location' => 'main_navigation' )); ?> </div> </div> </nav><file_sep>/wp-content/themes/urpg-2020/header.php <head> <meta charset="utf-8"> <meta name="theme-color" content="#ffb300"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> <?php echo get_bloginfo('name'); if (!is_front_page()): echo wp_title(); endif; ?> </title> <meta name="description" content="<?php echo get_bloginfo('description'); ?>"> <meta name="author" content="<NAME>"> <?php wp_head(); ?> </head> <body> <?php get_template_part( 'navigation' ) ?><file_sep>/wp-content/themes/urpg-2020/functions.php <?php // Menu Theme Support add_theme_support( 'menus' ); // Featured Image Theme Support add_theme_support( 'post-thumbnails' ); // Creates Image Sizes //add_image_size( 'example', 300, 250, true ); // Register main navigation menus register_nav_menu('main_navigation', 'Main Navigation'); register_nav_menu('footer_menu', 'Footer Menu'); // Enqueue main scripts function main_scripts() { wp_enqueue_style( 'main', '/dist/main.css' ); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'master', '/dist/master.js'); } add_action( 'wp_enqueue_scripts', 'main_scripts' ); // Changes the [...] default readmore add_filter( 'excerpt_more', function ( $more ) { return '…'; }); // Registers post types for each section of the InfoHub $sections = [ 'general' => [ 'label' => 'General', 'icon' => 'dashicons-admin-page' ], 'battles' => [ 'label' => 'Battles', 'icon' => 'dashicons-editor-unlink', 'section_staff_label' => 'Senior Referee', 'section_staff_slug' => 'senior-referee' ], 'contests' => [ 'label' => 'Contests', 'icon' => 'dashicons-buddicons-groups', 'section_staff_label' => 'Chief Judge', 'section_staff_slug' => 'chief-judge' ], 'stories' => [ 'label' => 'Stories', 'icon' => 'dashicons-book-alt', 'section_staff_label' => 'Lead Grader', 'section_staff_slug' => 'lead-grader' ], 'art' => [ 'label' => 'Art', 'icon' => 'dashicons-admin-customizer', 'section_staff_label' => 'Expert Curator', 'section_staff_slug' => 'expert-curator' ], 'national_park' => [ 'label' => 'National Park', 'icon' => 'dashicons-admin-site-alt2', 'section_staff_label' => 'Elite Ranger', 'section_staff_slug' => 'elite-ranger' ], 'morphic' => [ 'label' => 'Morphic', 'icon' => 'dashicons-palmtree', 'section_staff_label' => 'Elder Arbiter', 'section_staff_slug' => 'elder-arbiter' ], ]; $position = 10; foreach ($sections as $section => $value) { register_post_type($section, [ 'label' => __($value['label']), 'public' => true, 'show_ui' => true, 'show_in_rest' => true, 'menu_icon' => $value['icon'], 'menu_position' => $position, 'taxonomies' => array('category'), 'supports' => array( 'title', 'editor', 'revisions', 'thumbnail' ), ]); add_role( $value['section_staff_slug'], __($value['section_staff_label']), [ 'read', 'read_' . $section, 'read_private_' . $section, 'edit_' . $section, 'edit_others_' . $section, 'edit_published_' . $section, 'publish_' . $section, 'delete_others_' . $section, 'delete_private_' . $section, 'delete_published_' . $section, ]); }; // Removes default user roles add_action('admin_menu', function() { global $wp_roles; $roles_to_remove = array('subscriber', 'contributor', 'author', 'editor'); foreach ($roles_to_remove as $role) { if (isset($wp_roles->roles[$role])) { $wp_roles->remove_role($role); } } }); // Removes Posts & Pages add_action('admin_init', function(){ remove_menu_page('edit.php?post_type=page'); remove_menu_page('edit.php'); }); // The below group of functions completely removes comments and comment support add_action('admin_init', function () { // Redirect any user trying to access comments page global $pagenow; if ($pagenow === 'edit-comments.php') { wp_redirect(admin_url()); exit; } // Remove comments metabox from dashboard remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal'); // Disable support for comments and trackbacks in post types foreach (get_post_types() as $post_type) { if (post_type_supports($post_type, 'comments')) { remove_post_type_support($post_type, 'comments'); remove_post_type_support($post_type, 'trackbacks'); } } }); // Close comments on the front-end add_filter('comments_open', '__return_false', 20, 2); add_filter('pings_open', '__return_false', 20, 2); // Hide existing comments add_filter('comments_array', '__return_empty_array', 10, 2); // Remove comments page in menu add_action('admin_menu', function () { remove_menu_page('edit-comments.php'); }); // Remove comments links from admin bar add_action('init', function () { if (is_admin_bar_showing()) { remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60); } }); ?><file_sep>/tailwind.config.js module.exports = { theme: { colors: { white: '#FFFFFF', gold: '#C6A521', blue: { 'dark': '#003C5A', 'default': '#0475AE', }, grey: { 'dark': '#474747', 'default': '#707070', 'light': '#BABABA', 'lighter': '#F5F5F5' } }, extend: { fontFamily: { 'sans': ['Nunito', 'Arial'] } } }, variants: {}, plugins: [] } <file_sep>/wp-content/themes/urpg-2020/footer.php <footer> <?php wp_nav_menu(array( 'theme_location' => 'footer_menu' )); ?> <div class="container"> </div> <?php wp_footer(); ?> </footer> </body>
9ed77b08364e4855f87069fc96c21ffe9e5f27f3
[ "Markdown", "JavaScript", "PHP" ]
8
Markdown
vanessasickles/urpg-theme-2020
42131f3e587bef8c11ace2e51dba16bd23f3b2df
938fe48f5e5a23c52d1caa89417249112de4fd49
refs/heads/main
<repo_name>brunohlabres/ping-pong-os<file_sep>/pingpong-prodcons.c #include <stdio.h> #include <stdlib.h> #include "ppos_data.h" #include "ppos.h" void consumidorBody{ while (1){ down (s_item) down (s_buffer) retira item do buffer up (s_buffer) up (s_vaga) print item task_sleep (1000) } } void produtorBody{ while (1){ task_sleep (1000) item = random (0..99) down (s_vaga) down (s_buffer) insere item no buffer up (s_buffer) up (s_item) } } int main(){ }<file_sep>/teste2.c // PingPongOS - PingPong Operating System // Prof. <NAME>, DINF UFPR // Versão 1.1 -- Julho de 2016 // Teste de semáforos (light) #include <stdio.h> #include <stdlib.h> #include "ppos.h" task_t a1, a2, b1, b2; semaphore_t s1, s2; // corpo da thread A void TaskA(void *arg) { int i; for (i = 0; i < 10; i++) { sem_down(&s1); printf("%s zig (%d)\n", (char *)arg, i); task_sleep(1000); sem_up(&s2); } task_exit(0); } // corpo da thread B void TaskB(void *arg) { int i; for (i = 0; i < 10; i++) { sem_down(&s2); printf("%s zag (%d)\n", (char *)arg, i); task_sleep(1000); sem_up(&s1); } task_exit(0); } int main(int argc, char *argv[]) { printf("main: inicio\n"); ppos_init(); // cria semaforos sem_create(&s1, 1); sem_create(&s2, 0); // cria tarefas task_create(&a1, TaskA, "A1"); task_create(&a2, TaskA, " A2"); task_create(&b1, TaskB, " B1"); task_create(&b2, TaskB, " B2"); // aguarda a1 encerrar task_join(&a1); // destroi semaforos sem_destroy(&s1); sem_destroy(&s2); // aguarda a2, b1 e b2 encerrarem task_join(&a2); task_join(&b1); task_join(&b2); printf("main: fim\n"); task_exit(0); exit(0); } <file_sep>/pingpong-mqueue.c // PingPongOS - PingPong Operating System // Prof. <NAME>, DINF UFPR // Versão 1.1 -- Julho de 2016 // Teste de filas de mensagens #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include "ppos.h" task_t prod[3], somador, cons[2] ; mqueue_t queueValores, queueRaizes ; // corpo da thread produtor void prodBody (void * saida) { int valor ; while (1) { // sorteia um valor inteiro aleatorio valor = random() % 1000 ; // envia o valor inteiro na fila de saida if (mqueue_send (&queueValores, &valor) < 0) { printf ("T%d terminou\n", task_id()) ; task_exit (0) ; } printf ("T%d enviou %d\n", task_id(), valor) ; // dorme um intervalo aleatorio task_sleep (random() % 3000) ; } } // corpo da thread somador void somaBody (void * arg) { int v1, v2, v3, i ; double soma, raiz ; for (i=0; i<10; i++) { // recebe tres valores inteiros mqueue_recv (&queueValores, &v1) ; printf (" T%d: recebeu %d\n", task_id(), v1) ; mqueue_recv (&queueValores, &v2) ; printf (" T%d: recebeu %d\n", task_id(), v2) ; mqueue_recv (&queueValores, &v3) ; printf (" T%d: recebeu %d\n", task_id(), v3) ; // calcula a soma e sua raiz soma = v1 + v2 + v3 ; raiz = sqrt (soma) ; printf (" T%d: %d+%d+%d = %f (raiz %f)\n", task_id(), v1, v2, v3, soma, raiz) ; // envia a raiz da soma mqueue_send (&queueRaizes, &raiz) ; // dorme um intervalo aleatorio task_sleep (random() % 3000) ; } task_exit(0) ; } // corpo da thread consumidor void consBody (void * arg) { double valor ; while(1) { // recebe um valor (double) if (mqueue_recv (&queueRaizes, &valor) < 0) { printf (" T%d terminou\n", task_id()) ; task_exit (0) ; } printf (" T%d consumiu %f\n", task_id(), valor) ; // dorme um intervalo aleatorio task_sleep (random() % 3000) ; } } int main (int argc, char *argv[]) { printf ("main: inicio\n") ; ppos_init () ; // cria as filas de mensagens (5 valores cada) mqueue_create (&queueValores, 5, sizeof(int)) ; mqueue_create (&queueRaizes, 5, sizeof(double)) ; // cria as threads task_create (&somador, somaBody, NULL) ; task_create (&cons[0], consBody, NULL) ; task_create (&cons[1], consBody, NULL) ; task_create (&prod[0], prodBody, NULL) ; task_create (&prod[1], prodBody, NULL) ; task_create (&prod[2], prodBody, NULL) ; // aguarda o somador encerrar task_join (&somador) ; // destroi as filas de mensagens printf ("main: destroi queueValores\n") ; mqueue_destroy (&queueValores) ; printf ("main: destroi queueRaizes\n") ; mqueue_destroy (&queueRaizes) ; // encerra a thread main printf ("main: fim\n") ; task_exit (0) ; exit (0) ; } <file_sep>/ppos_disk.c // GRR20163049 <NAME> // GRR20171588 <NAME> // ------------------------------------------------------- // PingPongOS // Disciplina: Sistemas Operacionais // ------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <signal.h> #include "ppos_disk.h" #include "hard_disk.h" #include "ppos.h" #include "queue.h" struct sigaction disk_interrupt; task_t disk_task; // tarefa do gerente de disco int signal_tratador = 0; // guarda sinal gerado pelo disco extern task_t *ready_queue; // fila de tarefas prontas extern task_t *current_task; // tarefa atual extern int userTasks; extern int preempcao; disk_t disk; // guarda variaveis do disco pedido_t *pedidos; // fila de pedidos para o disco // tratador do sinal do disco void tratador_disk(int signum) { signal_tratador = 1; if (disk.diskState == 0) // Se disco estiver dormindo { preempcao = 0; queue_append((queue_t **)&ready_queue, (queue_t *)&disk_task); disk.diskState = 1; preempcao = 1; } #ifdef DEBUG printf("interrupção do disco\n"); #endif } void diskDriverBody (void * args) { pedido_t *cabeca_pedidos; while (1) { // obtém o semáforo de acesso ao disco sem_down(&disk.disk_sem); // se foi acordado devido a um sinal do disco if (signal_tratador && (pedidos != NULL)) { // acorda a tarefa cujo pedido foi atendido signal_tratador = 0; preempcao = 0; cabeca_pedidos = (pedido_t *)queue_remove((queue_t **)&pedidos, (queue_t *)pedidos); queue_append((queue_t **)&ready_queue, (queue_t *)cabeca_pedidos->task); preempcao = 1; } // se o disco estiver livre e houver pedidos de E/S na fila if (disk_cmd(DISK_CMD_STATUS,0,0) == 1 && (pedidos != NULL)) { // escolhe na fila o pedido a ser atendido, usando FCFS // solicita ao disco a operação de E/S, usando disk_cmd() pedidos->ret = disk_cmd(pedidos->tipo, pedidos->block, pedidos->buffer); } // libera o semáforo de acesso ao disco sem_up(&disk.disk_sem); // suspende a tarefa corrente (retorna ao dispatcher) preempcao = 0; disk.diskState = 0; queue_remove((queue_t **)&ready_queue, (queue_t *)&disk_task); preempcao = 1; task_yield(); } } // inicializacao do gerente de disco // retorna -1 em erro ou 0 em sucesso // numBlocks: tamanho do disco, em blocos // blockSize: tamanho de cada bloco do disco, em bytes int disk_mgr_init (int *numBlocks, int *blockSize){ pedidos = NULL; // verifica se o disco foi inicializado if (disk_cmd (DISK_CMD_STATUS, 0, 0) == DISK_STATUS_UNKNOWN) { if (disk_cmd (DISK_CMD_INIT, 0, 0)) // se deu errou ao inicializar return -1; *numBlocks = disk_cmd (DISK_CMD_DISKSIZE, 0, 0); *blockSize = disk.diskBlockSize = disk_cmd (DISK_CMD_BLOCKSIZE, 0, 0); // registra a acao para o sinal de disco SIGUSR1 disk_interrupt.sa_handler = tratador_disk ; sigemptyset (&disk_interrupt.sa_mask) ; disk_interrupt.sa_flags = 0 ; if (sigaction (SIGUSR1, &disk_interrupt, 0) < 0) { perror ("Erro em sigaction de disco: ") ; exit (1) ; } sem_create(&disk.disk_sem, 1); task_create(&disk_task, diskDriverBody, NULL); // Inicializar tarefa do disco userTasks--; disk.diskState = 0; queue_remove((queue_t **)&ready_queue, (queue_t *)&disk_task); #ifdef DEBUG puts("disk_mgr_init: Disco inicializado"); #endif return 0; } else return -1; // disco ja foi inicializado } // leitura de um bloco, do disco para o buffer int disk_block_read (int block, void *buffer) { // obtém o semáforo de acesso ao disco sem_down(&disk.disk_sem); pedido_t *p = (pedido_t*) malloc(sizeof(pedido_t)); p->block = block; p->buffer = buffer; p->tipo = DISK_CMD_READ; p->task = current_task; p->next = p->prev = NULL; // inclui o pedido na fila_disco queue_append((queue_t **)&pedidos, (queue_t *)p); // libera semáforo de acesso ao disco sem_up(&disk.disk_sem); // suspende a tarefa corrente (retorna ao dispatcher) preempcao = 0; queue_remove((queue_t **)&ready_queue, (queue_t *)current_task); preempcao = 1; if (disk.diskState == 0) { preempcao = 0; queue_append((queue_t **)&ready_queue, (queue_t *)&disk_task); disk.diskState = 1; preempcao = 1; } task_yield(); //executou o comando int ret = p->ret; free(p); return(ret); } // escrita de um bloco, do buffer para o disco int disk_block_write (int block, void *buffer) { // obtém o semáforo de acesso ao disco sem_down(&disk.disk_sem); pedido_t *p = (pedido_t *)malloc(sizeof(pedido_t)); p->buffer = buffer; p->block = block; p->tipo = DISK_CMD_WRITE; p->task = current_task; p->next = p->prev = NULL; // inclui o pedido na fila_disco queue_append((queue_t **)&pedidos, (queue_t *)p); // libera semáforo de acesso ao disco sem_up(&disk.disk_sem); // suspende a tarefa corrente (retorna ao dispatcher) preempcao = 0; queue_remove((queue_t **)&ready_queue, (queue_t *)current_task); preempcao = 1; if (disk.diskState == 0) { preempcao = 0; queue_append((queue_t **)&ready_queue, (queue_t *)&disk_task); disk.diskState = 1; preempcao = 1; } task_yield(); //executou o comando int ret = p->ret; free(p); return(ret); }<file_sep>/queue.c // Biblioteca de Filas - SO - PingPongOS // Alunos: <NAME>, <NAME> //------------------------------------------------------------------------------ #include <stdio.h> #include <stdlib.h> #include "queue.h" //------------------------------------------------------------------------------ // Insere um elemento no final da fila. // Condicoes a verificar, gerando msgs de erro: // - a fila deve existir // - o elemento deve existir // - o elemento nao deve estar em outra fila void queue_append (queue_t **queue, queue_t *elem){ // VERIFICACOES // verifica se fila existe if (queue == NULL){ fprintf(stderr, "Fila nao existe.\n"); return; } // verifica se elemento existe if (elem == NULL){ fprintf(stderr, "Elemento a ser inserido nao existe.\n"); return; } // verifica se elemento nao esta em outra fila if (elem->prev != NULL || elem->next != NULL){ fprintf(stderr, "Elemento pertence a uma fila.\n"); return; } // INSERCAO // inserir em uma fila vazia if (*queue == NULL){ elem->next = elem; elem->prev = elem; *queue = elem; } else { // inserir em uma fila nao vazia queue_t *aux = *queue; while (aux->next != *queue){ aux = aux->next; } elem->prev = aux; elem->next = *queue; aux->next = elem; (*queue)->prev = elem; } } //------------------------------------------------------------------------------ // Remove o elemento indicado da fila, sem o destruir. // Condicoes a verificar, gerando msgs de erro: // - a fila deve existir // - a fila nao deve estar vazia // - o elemento deve existir // - o elemento deve pertencer a fila indicada // Retorno: apontador para o elemento removido, ou NULL se erro queue_t *queue_remove (queue_t **queue, queue_t *elem){ if (queue == NULL){ // verifica se fila existe fprintf(stderr, "Fila nao existe.\n"); return NULL; } if (*queue == NULL){ // verifica se fila esta vazia fprintf(stderr, "Fila vazia.\n"); return NULL; } // verifica se elemento existe if (elem == NULL){ fprintf(stderr, "Elemento a ser removido nao existe.\n"); return NULL; } // encontra elemento a ser removido queue_t *aux = *queue; if (aux == elem){ // se o elemento a ser removido eh a cabeca da fila if ((*queue == elem) && (((*queue)->prev) == *queue) && (((*queue)->next) == *queue)){ // se eh o unico elemento (*queue) = NULL; elem->prev = NULL; elem->next = NULL; return elem; } else{ // se eh a cabeca mas n o unico elemento (*queue)->prev->next = (*queue)->next; (*queue)->next->prev = (*queue)->prev; *queue = (*queue)->next; elem->prev = NULL; elem->next = NULL; return elem; } } aux = aux->next; while (aux != *queue){ if (aux == elem){ // remove aux->prev->next = aux->next; aux->next->prev = aux->prev; elem->prev = NULL; elem->next = NULL; return elem; } aux = aux->next; } if (aux == *queue){ // nao achou elem fprintf(stderr, "Elemento a ser removido nao esta na fila.\n"); return NULL; } return NULL; } //------------------------------------------------------------------------------ // Conta o numero de elementos na fila // Retorno: numero de elementos na fila int queue_size (queue_t *queue){ int cont = 0; queue_t *aux = queue; if (aux != NULL){ cont = 1; aux = aux->next; while ((aux != queue) && (aux != NULL)){ cont++; aux = aux->next; } } return cont; } //------------------------------------------------------------------------------ // Percorre a fila e imprime na tela seu conteúdo. A impressão de cada // elemento é feita por uma função externa, definida pelo programa que // usa a biblioteca. // // Essa função deve ter o seguinte protótipo: // // void print_elem (void *ptr) ; // ptr aponta para o elemento a imprimir void queue_print (char *name, queue_t *queue, void print_elem (void*) ){ queue_t *aux = queue; printf("%s: [", name); if(aux != NULL){ do{ print_elem(aux); aux = aux->next; if(aux != queue) printf(" "); } while (aux != queue); } printf("]\n"); }<file_sep>/ppos_data.h // PingPongOS - PingPong Operating System // Prof. <NAME>, DINF UFPR // Versão 1.1 -- Julho de 2016 // Estruturas de dados internas do sistema operacional #ifndef __PPOS_DATA__ #define __PPOS_DATA__ #include <ucontext.h> // biblioteca POSIX de trocas de contexto #include "queue.h" // biblioteca de filas genéricas // Estrutura que define um Task Control Block (TCB) typedef struct task_t { struct task_t *prev, *next ; // ponteiros para usar em filas int id ; // identificador da tarefa ucontext_t context ; // contexto armazenado da tarefa void *stack ; // aponta para a pilha da tarefa int pe, pd; // Prioridades int ticks; int execTime; int activations; unsigned int timeOfCreation; int exit_code; int running; queue_t *tasks_waiting; unsigned int sleepTime; // Guarda tempo em que deve acordar } task_t ; // estrutura que define um semáforo typedef struct { int cont; // contador do semaforo int active; queue_t *tasks_waiting; // fila de tarefas esperando no semaforo } semaphore_t ; // estrutura que define um mutex typedef struct { // preencher quando necessário } mutex_t ; // estrutura que define uma barreira typedef struct { // preencher quando necessário } barrier_t ; // estrutura que define uma fila de mensagens typedef struct { void *buffer; semaphore_t sem_vaga; semaphore_t sem_item; semaphore_t sem_buf; int qtd_usada_buffer; int read_index; // controle do buffer circular int write_index; // controle do buffer circular int msg_size; // tamanho das msgs int valid; // se a queue foi ou nao destruida } mqueue_t ; #endif <file_sep>/hard_disk.c // PingPongOS - PingPong Operating System // Prof. <NAME>, DINF UFPR // Versão 1.1 -- Julho de 2016 // Este código simula a operação e interface de um disco rígido de computador. // O "hardware" do disco simulado oferece as operações descritas no arquivo // harddisk.h. As operações de leitura e escrita de blocos de dados são atendidas // de forma assíncrona, ou seja: o disco responde à requisição imediatamente, // mas a operação de E/S em si demora um pouco mais; quando ela for completada, // o disco irá informar isso através de um sinal SIGUSR1 (simulando a interrução // de hardware que ocorre em um disco real). // O conteúdo do disco simulado é armazenado em um arquivo no sistema operacional // subjacente. // // Atencao: deve ser usado o flag de ligacao -lrt, para ligar com a // biblioteca POSIX de tempo real, pois o disco simulado usa timers POSIX. // operating system check #if defined(_WIN32) || (!defined(__unix__) && !defined(__unix) && (!defined(__APPLE__) || !defined(__MACH__))) #warning Este codigo foi planejado para ambientes UNIX (LInux, *BSD, MacOS). A compilacao e execucao em outros ambientes e responsabilidade do usuario. #endif #include <signal.h> #include <sys/types.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <time.h> #include <stdlib.h> #include <stdio.h> #include "hard_disk.h" // parâmetros de operação do disco simulado #define DISK_NAME "disk0.dat" // nome do arquivo que simula o disco #define DISK_BLOCK_SIZE 64 // tamanho de cada bloco, em bytes #define DISK_DELAY_MIN 30 // atraso minimo, em milisegundos #define DISK_DELAY_MAX 300 // atraso maximo, em milisegundos //#define DEBUG_HD 1 // para depurar a operação do disco /**********************************************************************/ // estrutura com os dados internos do disco (estado inicial desconhecido) typedef struct { int status ; // estado do disco char *filename ; // nome do arquivo que simula o disco int fd ; // descritor do arquivo que simula o disco int numblocks ; // numero de blocos do disco int blocksize ; // tamanho dos blocos em bytes char *buffer ; // buffer da proxima operacao (read/write) int prev_block ; // bloco da ultima operacao int next_block ; // bloco da proxima operacao int delay_min, delay_max ; // tempos de acesso mínimo e máximo timer_t timer ; // timer que simula o tempo de acesso struct itimerspec delay ; // struct do timer de tempo de acesso struct sigevent sigev ; // evento associado ao timer struct sigaction signal ; // tratador de sinal do timer } harddisk_t ; harddisk_t harddisk ; // hard disk structure /**********************************************************************/ // trata o sinal SIGIO do timer que simula o tempo de acesso ao disco void harddisk_SignalHandle (int sig) { #ifdef DEBUG_HD printf ("Harddisk: signal %d received\n", sig) ; #endif // verificar qual a operacao pendente e realiza-la switch (harddisk.status) { case DISK_STATUS_READ: // faz a leitura previamente agendada lseek (harddisk.fd, harddisk.next_block * harddisk.blocksize, SEEK_SET) ; read (harddisk.fd, harddisk.buffer, harddisk.blocksize) ; break ; case DISK_STATUS_WRITE: // faz a escrita previamente agendada lseek (harddisk.fd, harddisk.next_block * harddisk.blocksize, SEEK_SET) ; write (harddisk.fd, harddisk.buffer, harddisk.blocksize) ; break ; default: // erro: estado desconhecido perror("Harddisk: unknown disk state"); exit(1); } // guarda numero de bloco da ultima operacao harddisk.prev_block = harddisk.next_block ; // disco se torna ocioso novamente harddisk.status = DISK_STATUS_IDLE ; // gerar um sinal SIGUSR1 para o "kernel" do usuario raise (SIGUSR1) ; } /**********************************************************************/ // arma o timer que simula o tempo de acesso ao disco void harddisk_settimer () { int time_ms ; // tempo no intervalo [DISK_DELAY_MIN ... DISK_DELAY_MAX], proporcional a // distancia entre o proximo bloco a ler (next_block) e a ultima leitura // (prev_block), somado a um pequeno fator aleatorio time_ms = abs (harddisk.next_block - harddisk.prev_block) * (harddisk.delay_max - harddisk.delay_min) / harddisk.numblocks + harddisk.delay_min + random () % (harddisk.delay_max - harddisk.delay_min) / 10 ; // printf ("\n[%d->%d, %d]\n", harddisk.prev_block, harddisk.next_block, time_ms) ; // primeiro disparo, em nano-segundos, harddisk.delay.it_value.tv_nsec = time_ms * 1000000 ; // primeiro disparo, em segundos harddisk.delay.it_value.tv_sec = time_ms / 1000 ; // proximos disparos nao ocorrem (disparo unico) harddisk.delay.it_interval.tv_nsec = 0 ; harddisk.delay.it_interval.tv_sec = 0 ; // arma o timer if (timer_settime(harddisk.timer, 0, &harddisk.delay, NULL) == -1) { perror("Harddisk:"); exit(1); } #ifdef DEBUG_HD printf ("Harddisk: timer is set\n") ; #endif } /**********************************************************************/ // inicializa o disco virtual // retorno: 0 (sucesso) ou -1 (erro) int harddisk_init () { // o disco jah foi inicializado ? if ( harddisk.status != DISK_STATUS_UNKNOWN ) return -1 ; // estado atual do disco harddisk.status = DISK_STATUS_IDLE ; harddisk.next_block = harddisk.prev_block = 0 ; // abre o arquivo no disco (leitura/escrita, sincrono) harddisk.filename = DISK_NAME ; harddisk.fd = open (harddisk.filename, O_RDWR|O_SYNC) ; if (harddisk.fd < 0) { perror("Harddisk:"); exit (1) ; } // define seu tamanho em blocos harddisk.blocksize = DISK_BLOCK_SIZE ; harddisk.numblocks = lseek (harddisk.fd, 0, SEEK_END) / harddisk.blocksize ; // ajusta atrasos mínimo e máximo de acesso no disco harddisk.delay_min = DISK_DELAY_MIN ; harddisk.delay_max = DISK_DELAY_MAX ; // associa SIGIO do timer ao handle apropriado harddisk.signal.sa_handler = harddisk_SignalHandle ; sigemptyset (&harddisk.signal.sa_mask); harddisk.signal.sa_flags = 0; sigaction (SIGIO, &harddisk.signal, 0); // cria o timer que simula o tempo de acesso ao disco harddisk.sigev.sigev_notify = SIGEV_SIGNAL; harddisk.sigev.sigev_signo = SIGIO; if (timer_create(CLOCK_REALTIME, &harddisk.sigev, &harddisk.timer) == -1) { perror("Harddisk:"); exit (1) ; } #ifdef DEBUG_HD printf ("Harddisk: initialized\n") ; #endif return 0 ; } /**********************************************************************/ // funcao que implementa a interface de acesso ao disco em baixo nivel int disk_cmd (int cmd, int block, void *buffer) { #ifdef DEBUG_HD printf ("Harddisk: received command %d\n", cmd) ; #endif switch (cmd) { // inicializa o disco case DISK_CMD_INIT: return (harddisk_init ()) ; // solicita status do disco case DISK_CMD_STATUS: return (harddisk.status) ; // solicita tamanho do disco case DISK_CMD_DISKSIZE: if ( harddisk.status == DISK_STATUS_UNKNOWN) return -1 ; return (harddisk.numblocks) ; // solicita tamanho de bloco case DISK_CMD_BLOCKSIZE: if ( harddisk.status == DISK_STATUS_UNKNOWN) return -1 ; return (harddisk.blocksize) ; // solicita atraso mínimo case DISK_CMD_DELAYMIN: if ( harddisk.status == DISK_STATUS_UNKNOWN) return -1 ; return (harddisk.delay_min) ; // solicita atraso máximo case DISK_CMD_DELAYMAX: if ( harddisk.status == DISK_STATUS_UNKNOWN) return -1 ; return (harddisk.delay_max) ; // solicita operação de leitura ou de escrita case DISK_CMD_READ: case DISK_CMD_WRITE: if ( harddisk.status != DISK_STATUS_IDLE) return -1 ; if ( !buffer ) return -1 ; if ( block < 0 || block >= harddisk.numblocks) return -1 ; // registra que ha uma operacao pendente harddisk.buffer = buffer ; harddisk.next_block = block ; if (cmd == DISK_CMD_READ) harddisk.status = DISK_STATUS_READ ; else harddisk.status = DISK_STATUS_WRITE ; // arma o timer que simula o atraso do disco harddisk_settimer () ; return 0 ; default: return -1 ; } } /**********************************************************************/ <file_sep>/Makefile CFLAGS = -Wall -g #-DDEBUG # gerar "warnings" detalhados e infos de depuração LFLAGS = -lm -lrt exec = teste teste = pingpong-disco.c sources = $(teste) ppos_core.c queue.c hard_disk.c ppos_disk.c # regra default (primeira regra) all: $(exec) $(exec): $(sources) gcc $(CFLAGS) $(sources) -o $(exec) $(LFLAGS) # remove arquivos temporários clean: -rm -f $(exec) <file_sep>/pingpong-racecond.c // PingPongOS - PingPong Operating System // Prof. <NAME>, DINF UFPR // Versão 1.1 -- Julho de 2016 // Teste de semáforos (pesado) #include <stdio.h> #include <stdlib.h> #include "ppos.h" #define NUMTASKS 30 #define NUMSTEPS 10000000 task_t task[NUMTASKS] ; semaphore_t s ; long int soma = 0 ; // corpo das threads void taskBody(void *id) { int i ; for (i=0; i< NUMSTEPS; i++) { sem_down (&s) ; soma += 1 ; sem_up (&s) ; } task_exit (0) ; } int main (int argc, char *argv[]) { int i ; printf ("main: inicio\n") ; ppos_init () ; sem_create (&s, 1) ; printf ("%d tarefas somando %d vezes cada, aguarde...\n", NUMTASKS, NUMSTEPS) ; for (i=0; i<NUMTASKS; i++) task_create (&task[i], taskBody, "Task") ; for (i=0; i<NUMTASKS; i++) task_join (&task[i]) ; sem_destroy (&s) ; if (soma == (NUMTASKS*NUMSTEPS)) printf ("Soma deu %ld, valor correto!\n", soma) ; else printf ("Soma deu %ld, mas deveria ser %d!\n", soma, NUMTASKS*NUMSTEPS) ; task_exit (0) ; exit (0) ; } <file_sep>/ppos_disk.h // PingPongOS - PingPong Operating System // Prof. <NAME>, DINF UFPR // Versão 1.2 -- Julho de 2017 // interface do gerente de disco rígido (block device driver) #ifndef __DISK_MGR__ #define __DISK_MGR__ #include "ppos_data.h" // estruturas de dados e rotinas de inicializacao e acesso // a um dispositivo de entrada/saida orientado a blocos, // tipicamente um disco rigido. // estrutura que representa um disco no sistema operacional typedef struct { semaphore_t disk_sem; // semaforo do disco int diskBlockSize; int diskState; } disk_t ; typedef struct { struct queue_t *prev, *next; // ponteiros para usar em filas int tipo; int block; void *buffer; task_t *task; int ret; } pedido_t ; // inicializacao do gerente de disco // retorna -1 em erro ou 0 em sucesso // numBlocks: tamanho do disco, em blocos // blockSize: tamanho de cada bloco do disco, em bytes int disk_mgr_init (int *numBlocks, int *blockSize) ; // leitura de um bloco, do disco para o buffer int disk_block_read (int block, void *buffer) ; // escrita de um bloco, do buffer para o disco int disk_block_write (int block, void *buffer) ; #endif <file_sep>/pingpong-semaphore.c // PingPongOS - PingPong Operating System // Prof. <NAME>, DINF UFPR // Versão 1.1 -- Julho de 2016 // Teste de semáforos (light) #include <stdio.h> #include <stdlib.h> #include "ppos.h" task_t a1, a2, b1, b2; semaphore_t s1, s2 ; // corpo da thread A void TaskA (void * arg) { int i ; for (i=0; i<10; i++) { sem_down (&s1) ; printf ("%s zig (%d)\n", (char *) arg, i) ; task_sleep (1000) ; sem_up (&s2) ; } task_exit (0) ; } // corpo da thread B void TaskB (void * arg) { int i ; for (i=0; i<10; i++) { sem_down (&s2) ; printf ("%s zag (%d)\n", (char *) arg, i) ; task_sleep (1000) ; sem_up (&s1) ; } task_exit (0) ; } int main (int argc, char *argv[]) { printf ("main: inicio\n") ; ppos_init () ; // cria semaforos sem_create (&s1, 1) ; sem_create (&s2, 0) ; // cria tarefas task_create (&a1, TaskA, "A1") ; task_create (&a2, TaskA, " A2") ; task_create (&b1, TaskB, " B1") ; task_create (&b2, TaskB, " B2") ; // aguarda a1 encerrar task_join (&a1) ; // destroi semaforos sem_destroy (&s1) ; sem_destroy (&s2) ; // aguarda a2, b1 e b2 encerrarem task_join (&a2) ; task_join (&b1) ; task_join (&b2) ; printf ("main: fim\n") ; task_exit (0) ; exit (0) ; } <file_sep>/ppos_core.c // GRR20163049 <NAME> // GRR20171588 <NAME> // ------------------------------------------------------- // PingPongOS // Disciplina: Sistemas Operacionais // ------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <sys/time.h> #include <string.h> #include "ppos.h" // estruturas de dados necessárias #include "ppos_disk.h" #define STACKSIZE 32768 /* tamanho de pilha das threads */ #define QUANTUM 20 #define TAM_BUFFER_CIRC 5 #define NUM_VAGAS_PROD TAM_BUFFER_CIRC // operating system check #if defined(_WIN32) || (!defined(__unix__) && !defined(__unix) && (!defined(__APPLE__) || !defined(__MACH__))) #warning Este codigo foi planejado para ambientes UNIX (LInux, *BSD, MacOS). #endif // estrutura que define um tratador de sinal (deve ser global ou static) struct sigaction action ; // estrutura de inicialização to timer struct itimerval timer; task_t *ready_queue; // Fila de tarefas prontas task_t *sleeping_queue; // Fila de tarefas dormindo int last_id = 0; // Guarda o ultimo ID atribuido a uma tarefa int userTasks = 0; // Guarda numero de tarefas prontas para execucao task_t *current_task; // Guarda a tarefa sendo executada no momento task_t dispatcher; // tarefa do dispatcher task_t mainTask; // tarefa da main unsigned int currentTime; // Guarda tempo do sistema int preempcao; // Desativa preempcao extern task_t *disk_task; semaphore_t sem_vaga; semaphore_t sem_item; semaphore_t sem_buf; // --- FILAS DE MENSAGEM ------------------------------ int mqueue_create (mqueue_t *queue, int max_msgs, int msg_size){ sem_create(&queue->sem_buf, 1); sem_create(&queue->sem_item, 0); sem_create(&queue->sem_vaga, NUM_VAGAS_PROD); queue->qtd_usada_buffer = 0; // o quanto do buffer foi usado queue->read_index = 0; // controle do buffer circular queue->write_index = 0; // controle do buffer circular queue->msg_size = msg_size; // tamanho das msgs queue->valid = 1; // queue nao foi destruida queue->buffer = (void *) malloc(TAM_BUFFER_CIRC*msg_size); if (queue->buffer){ return 0; }else{ return -1; } } int mqueue_send (mqueue_t *queue, void *msg){ int tmp; // sera usada para retornar sucesso ou nao na exec da funcao if (queue->valid){ // verifica se fila nao foi destruida if (sem_down(&queue->sem_vaga) == -1) return -1; // se nao tiver vaga, espera if (sem_down(&queue->sem_buf) == -1) return -1; //espera buffer ficar livre if (memcpy(queue->buffer + queue->write_index*queue->msg_size,msg,queue->msg_size)) // escreve msg no buffer circular tmp = 0; else tmp = -1; queue->write_index = (queue->write_index + 1) % TAM_BUFFER_CIRC; queue->qtd_usada_buffer++; // espaco usado no buffer sem_up(&queue->sem_buf); // libera buffer sem_up(&queue->sem_item); // indica novo item no vuffer return tmp; } else { // se fila foi destruida return -1; } } int mqueue_recv (mqueue_t *queue, void *msg){ int tmp; // sera usada para retornar sucesso ou nao na exec da funcao if (queue->valid){ // verifica se fila nao foi destruida if (sem_down(&queue->sem_item) == -1) return -1; //espera novo item if (sem_down(&queue->sem_buf) == -1) return -1; //espera buffer ficar livre if (memcpy(msg, queue->buffer + queue->read_index * queue->msg_size, queue->msg_size)) // escreve msg na saida tmp = 0; else tmp = -1; queue->read_index = (queue->read_index + 1) % TAM_BUFFER_CIRC; queue->qtd_usada_buffer--; sem_up(&queue->sem_buf); // libera buffer sem_up(&queue->sem_vaga); // libera vaga return tmp; } else { // se fila foi destruida return -1; } } int mqueue_destroy (mqueue_t *queue){ if (queue->valid && queue->buffer && queue){ queue->valid = 0; // fila destruida free(queue->buffer); // destroi o conteudo da fila sem_destroy(&queue->sem_buf); sem_destroy(&queue->sem_vaga); sem_destroy(&queue->sem_item); return 0; } else { return -1; } } int mqueue_msgs (mqueue_t *queue){ if (queue->valid){ return queue->qtd_usada_buffer; } else return -1; } // --- FILAS DE MENSAGEM ------------------------------ // Inicializa um semáforo apontado por s com o valor inicial value e uma fila vazia. // A chamada retorna 0 em caso de sucesso ou -1 em caso de erro. int sem_create (semaphore_t *s, int value){ if(s){ s->cont = value; // inicializa contador de s s->active = 1; s->tasks_waiting = NULL; // inicializa fila de tasks esperando s return 0; } else{ return -1; } } int sem_down (semaphore_t *s){ if (s->active){ preempcao = 0; // enter_cs (&lock) ; s->cont--; // leave_cs (&lock) ; if (s->cont < 0){ // sem "vaga" para a tarefa queue_remove((queue_t **)&ready_queue, (queue_t *)current_task); // suspende a tarefa queue_append((queue_t **)&s->tasks_waiting, (queue_t *)current_task); // add tarefa na fila de espera preempcao = 1; task_yield(); // volta a exec para o dispatcher } else { preempcao = 1; } if (!s->active){ // se o semaforo for destruido enquanto a tarefa aguarda, retorna erro preempcao = 1; return -1; // erro } return 0; // sucesso } else{ return -1; // erro } } int sem_up (semaphore_t *s){ if (s->active){ preempcao = 0; s->cont++; if (s->cont <= 0 ) { // insere a cabeca da fila de espera do semaforo na fila de prontas queue_append((queue_t **)&ready_queue, queue_remove((queue_t **)&s->tasks_waiting, (queue_t *)s->tasks_waiting)); } preempcao = 1; return 0; // sucesso } else{ return -1; // erro } } int sem_destroy (semaphore_t *s){ if (s){ while (queue_size((queue_t *)s->tasks_waiting) > 0) // insere a cabeca da fila de espera do semaforo na fila de prontas queue_append((queue_t **)&ready_queue, queue_remove((queue_t **)&s->tasks_waiting, (queue_t *)s->tasks_waiting)); s->active = 0; return 0; // sucesso } else{ return -1; // erro } } // suspende a tarefa corrente por t milissegundos void task_sleep(int t) { preempcao = 0; current_task->sleepTime = currentTime + t; // Suspender tarefa queue_remove((queue_t **)&ready_queue, (queue_t *)current_task); queue_append((queue_t **)&sleeping_queue, (queue_t *)current_task); preempcao = 1; task_yield(); } // a tarefa corrente aguarda o encerramento de outra task int task_join(task_t *task) { preempcao = 0; // Se tarefa nao estiver rodando if (!task->running) { return -1; } // Suspender tarefa queue_remove((queue_t **)&ready_queue, (queue_t *)current_task); queue_append((queue_t **)&task->tasks_waiting, (queue_t *)current_task); preempcao = 1; task_yield(); // Aqui a execucao foi resumida pela tarefa que encerrou return task->exit_code; } // retorna o relogio atual (em milisegundos) unsigned int systime() { return currentTime; } // tratador do sinal void tratador(int signum) { currentTime++; current_task->execTime++; // Tratar tarefas que não são de usuário if (current_task == &dispatcher) return; // Tratar ticks if (current_task->ticks > 0 || !preempcao) { current_task->ticks--; return; } else { // Trocar tarefa em execução task_yield(); } } // Define a prioridade estática de uma tarefa (ou a tarefa atual) void task_setprio(task_t *task, int prio) { if (!task) { task = current_task; } if (prio > 20 || prio < -20) { #ifdef DEBUG printf("task_setprio: prioridade fora dos limites\n"); #endif } else { task->pe = task->pd = prio; } } // Retorna a prioridade estática de uma tarefa (ou a tarefa atual) int task_getprio(task_t *task) { if (!task) { task = current_task; } return task->pe; } // Escolhe tarefa com maior prioridade na lista de prontas task_t* scheduler() { if (!ready_queue) return NULL; // tmp task_t *it = ready_queue; // iterar pela fila task_t *next_task = it; // guarda tarefa com maior prioridade ate o momento int prio = it->pd; // guarda ultima prioridade it->pd--; // Acha tarefa com maior prioridade e incrementa prioridade dos demais elementos do { it = it->next; if (it->pd < prio) { next_task = it; prio = it->pd; } it->pd--; } while (it->next != ready_queue); next_task->pd = next_task->pe; // resetando prioridade da tarefa a ser executada return next_task; } // Coloca a próxima tarefa em execução void dispatcher_body() { #ifdef DEBUG printf("dispatcher_body: dispatcher inicializado\n"); #endif task_t *next; task_t *sleep_it; task_t *aux; while (userTasks > 0) { // Acordar tarefas que estao dormindo if (sleeping_queue){ sleep_it = sleeping_queue; do { aux = sleep_it->next; if (sleep_it->sleepTime <= currentTime) { queue_append((queue_t **)&ready_queue, queue_remove((queue_t **)&sleeping_queue, (queue_t *)sleep_it)); } sleep_it = aux; } while(sleep_it != sleeping_queue && sleeping_queue); } next = scheduler(); // encontra tarefa com maior prioridade if (next) { next->ticks = QUANTUM; task_switch(next); // transfere controle para a tarefa "next" // Liberar stack caso tarefa tenha encerrado execucao if (!next->running) { free(next->stack); } } } if (disk_task) free(disk_task->stack); task_exit(0); // encerra a tarefa dispatcher } // Inicializa o sistema operacional; deve ser chamada no inicio do main() void ppos_init() { /* desativa o buffer da saida padrao (stdout), usado pela função printf */ setvbuf (stdout, 0, _IONBF, 0); ready_queue = NULL; // inicializa fila de tasks // Criando tarefa para main na fila de tarefas com id 0 task_create(&mainTask,NULL,NULL); current_task = &mainTask; currentTime = 0; preempcao = 1; task_create(&dispatcher, dispatcher_body, NULL); // registra a acao para o sinal de timer SIGALRM action.sa_handler = tratador ; sigemptyset (&action.sa_mask) ; action.sa_flags = 0 ; if (sigaction (SIGALRM, &action, 0) < 0) { perror ("Erro em sigaction: ") ; exit (1) ; } // ajusta valores do temporizador timer.it_value.tv_usec = 1000 ; // primeiro disparo, em micro-segundos timer.it_value.tv_sec = 0 ; // primeiro disparo, em segundos timer.it_interval.tv_usec = 1000 ; // disparos subsequentes, em micro-segundos timer.it_interval.tv_sec = 0 ; // disparos subsequentes, em segundos // arma o temporizador ITIMER_REAL (vide man setitimer) if (setitimer (ITIMER_REAL, &timer, 0) < 0) { perror ("Erro em setitimer: ") ; exit (1) ; } #ifdef DEBUG printf("ppos_init: Sistema inicializado\n"); #endif task_yield(); } // Libera o processador para a próxima tarefa, retornando à fila de tarefas // prontas ("ready queue") void task_yield() { task_switch(&dispatcher); } // Alterna a execução para a tarefa indicada int task_switch(task_t *task) { // Salvar contexto da tarefa atual task_t *old_task = current_task; getcontext(&(old_task->context)); // Colocar tarefa em execução current_task = task; current_task->activations++; #ifdef DEBUG // printf("Trocando de tarefa %d para tarefa %d. \n",old_task->id, task->id); #endif return swapcontext(&(old_task->context), &(task->context)); return 0; } // Termina a tarefa corrente, indicando um valor de status encerramento void task_exit(int exitCode) { #ifdef DEBUG printf("task_exit: Encerrando tarefa %d\n", current_task->id); #endif // Enquanto houver tarefas na fila de espera while (current_task->tasks_waiting) { // Tirar tarefa da fila de espera e colocar na fila de prontas queue_append((queue_t **)&ready_queue, queue_remove((queue_t **)&(current_task->tasks_waiting), (queue_t *)current_task->tasks_waiting)); } printf("Task %d exit: running time %4d ms, cpu time %4d ms, %d activations\n", current_task->id, (systime() - current_task->timeOfCreation), current_task->execTime, current_task->activations ); if (current_task == &dispatcher){ // Terminar execucao exit(0); } // Remover tarefa da pilha preempcao = 0; current_task->exit_code = exitCode; current_task->running = 0; userTasks--; queue_remove((queue_t **)&ready_queue, (queue_t *)current_task); preempcao = 1; task_switch(&dispatcher); return; } // Cria uma nova tarefa. Retorna um ID> 0 ou erro. int task_create(task_t *task, // descritor da nova tarefa void (*start_func)(void *), // funcao corpo da tarefa void *arg) // argumentos para a tarefa { // Construindo struct da tarefa task->id = last_id++; task->pe = task->pd = 0; // Prioridades default da tarefa task->ticks = QUANTUM; task->execTime = 0; task->activations = 0; task->timeOfCreation = systime(); getcontext(&(task->context)); task->prev = NULL; task->next = NULL; task->running = 1; if (task != &mainTask) { // Alocando stack da tarefa char *stack = malloc(STACKSIZE); if (stack) { task->context.uc_stack.ss_sp = stack; task->context.uc_stack.ss_size = STACKSIZE; task->context.uc_stack.ss_flags = 0; task->context.uc_link = 0; } else { #ifdef DEBUG printf("task_create: Erro na criação da pilha\n"); #endif return(-1); } // Criar contexto makecontext (&(task->context), (void*)(*start_func), 1, arg); } task->stack = task->context.uc_stack.ss_sp; // Colocar tarefa na fila if (task != &dispatcher) { queue_append((queue_t **)&ready_queue, (queue_t *)task); userTasks++; } #ifdef DEBUG printf ("task_create: criou a tarefa de id %d\n", task->id); #endif return task->id; } // Retorna o identificador da tarefa corrente (main deve ser 0) int task_id() { return current_task->id; } <file_sep>/README.md # Ping Pong OS This project is a proto-operating system. The full documentation and details can be found [here](http://wiki.inf.ufpr.br/maziero/doku.php?id=so:pingpongos).
31a98584fecea9ecbbb0834559a2e97bbf323dec
[ "Markdown", "C", "Makefile" ]
13
C
brunohlabres/ping-pong-os
a32892db86d47cdfedb88f009a4cb580aa0dbccc
a19c5fe09d7ddf06aface3e18230b92898b4fef1
refs/heads/master
<file_sep>package com.atmecs.readerlocation; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class ReaderLocation { static Properties property; public static Properties readLocation(String path) throws IOException { property = new Properties(); FileInputStream file = new FileInputStream(path); property.load(file); return property; } } <file_sep>package com.atmecs.readerlocation; import java.io.FileInputStream; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelReader { public static XSSFWorkbook workbook; public static XSSFSheet sheet; public static String readData(String path,String sheetName,int row,int cell) throws Exception { String data=null; FileInputStream fis = new FileInputStream(path); workbook = new XSSFWorkbook(fis);//create a object for xssfworkbook class sheet = workbook.getSheet(sheetName);//Read the sheet by the name data = sheet.getRow(row).getCell(cell).toString(); return data; } }
724b53127ce48118b6a62f66f00de68c1a344063
[ "Java" ]
2
Java
Maheshprabha/automation
9010091b0e7fead57622b4059b5a9ac6736d8fc5
64edb24e1de43cb0d277e60797b88984a66bc843
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package in.swapnilbhoite.projects.subtitlestudio.vlc; /** * * @author <NAME> */ public interface VlcSdk { VlcPlayer getVlcPlayer(); void setOptions(String[] options); String[] getSupportedFileExtensions(); } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package in.swapnilbhoite.projects.subtitlestudio; /** * * @author <NAME> */ public class MyTime { long hr, min, sec, ms; public MyTime() { hr = min = sec = ms = 0; } public MyTime(long ms1) { ms = ms1; sec = ms / 1000; ms = ms % 1000; min = sec / 60; sec = sec % 60; hr = min / 60; min = min % 60; } MyTime toTime(long ms1) { MyTime temp = new MyTime(); temp.ms = ms1; temp.sec = temp.ms / 1000; temp.ms = temp.ms % 1000; temp.min = temp.sec / 60; temp.sec = temp.sec % 60; temp.hr = temp.min / 60; temp.min = temp.min % 60; return temp; } @Override public String toString() { String temp = ""; if (hr == 0) { temp = "00:"; } else if (hr < 10) { temp = "0" + hr + ":"; } else { temp = hr + ":"; } if (min == 0) { temp = temp + "00:"; } else if (min < 10) { temp = temp + "0" + min + ":"; } else { temp = temp + min + ":"; } if (sec == 0) { temp = temp + "00,"; } else if (sec < 10) { temp = temp + "0" + sec + ","; } else { temp = temp + sec + ","; } if (ms == 0) { temp = temp + "000"; } else if (ms < 10) { temp = temp + "00" + ms; } else if (ms < 100) { temp = temp + "0" + ms; } else { temp = temp + ms; } return temp; } public static String toSSA(String temp) { String ans = temp.subSequence(1, 8) + "."; ans = ans + temp.charAt(9) + temp.charAt(10) + ","; ans = ans + temp.substring(18, 25) + "."; ans = ans + temp.charAt(26) + temp.charAt(27) + ","; return ans; } } <file_sep>package in.swapnilbhoite.projects.subtitlestudio; /** * * @author <NAME> */ public class StopWatch extends Thread { private long startTime = 0; private long stopTime = 0; private boolean running = false; public static int instance = 0; public void sstart() { this.startTime = System.currentTimeMillis() - correction; this.running = true; } public void sstop() { this.stopTime = System.currentTimeMillis(); this.running = false; } //elaspsed time in milliseconds public long getElapsedTime() { long elapsed; if (running) { elapsed = (System.currentTimeMillis() - startTime); } else { elapsed = (stopTime - startTime); } return elapsed; } //elaspsed time in seconds public long getElapsedTimeSecs() { long elapsed; if (running) { elapsed = ((System.currentTimeMillis() - startTime) / 1000); } else { elapsed = ((stopTime - startTime) / 1000); } return elapsed; } public void displayTime() { this.start(); } public void pauseSW() { correction = this.getElapsedTime(); this.sstop(); } public void resumeSW() { this.sstart(); } @Override public void run() { this.sstart(); if (instance == 0) { time1 = new MyTime(); time2 = new MyTime(); while (getElapsedTime() <= Creator.fileLength) { if (getElapsedTime() > 0) { time1 = time1.toTime(getElapsedTime()); Creator.jProgressBarPlayback.setValue((int) ((100 * getElapsedTime()) / Creator.fileLength)); Creator.jLabelDuration.setText("" + time1 + " / " + time2.toTime(Creator.mediaPlayer.getLength())); } } } else if (instance == 1) { //while(true) //Edit.jLabel5.setText(""+new MyTime().toTime(getElapsedTime())); } } MyTime time1, time2; long correction = 0; } <file_sep>package in.swapnilbhoite.projects.subtitlestudio; import in.swapnilbhoite.projects.subtitlestudio.remote_storage.RemoteStorage; import in.swapnilbhoite.projects.subtitlestudio.remote_storage.RemoteStorageApis; import in.swapnilbhoite.projects.subtitlestudio.remote_storage.RemoteStorageException; import in.swapnilbhoite.projects.subtitlestudio.remote_storage.SearchResult; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; /** * * @author <NAME> */ public class Downloader extends javax.swing.JFrame implements Runnable { private List<SearchResult> searchResults; public Downloader() { initComponents(); initiateDownload(); startTime = System.currentTimeMillis(); } final void initiateDownload() { for (int i = 0; i < 100; i++) { jTableSearchResults.setValueAt("", i, 0); jTableSearchResults.setValueAt("", i, 1); jTableSearchResults.setValueAt("", i, 2); jTableSearchResults.setValueAt("", i, 3); } jLabelFileNameValue.setText("-"); jLabelTitleValue.setText("-"); jLabelArtistValue.setText("-"); jLabelAlbumValue.setText("-"); resultDIR.removeAll(resultDIR); serverNo.removeAll(serverNo); totalResults = 0; jLabelSearchStatusTitle.setText("Search File"); jLabelSearchStatus.setText("Status"); jLabelSearchStatusFileName.setText("-"); jLabelSearchStatusFileTitle.setText("-"); jLabelSearchStatusFileArtist.setText("-"); jLabelSearchStatusFileAlbum.setText("-"); jLabelSearchStatusFileNameValue.setText("-"); jLabelSearchStatusTitleValue.setText("-"); jLabelSearchStatusArtistValue.setText("-"); jLabelSearchStatusAlbumValue.setText("-"); jLabelSearchStatusFile.setText("File"); jLabelSearchStatusFileValue.setText("-"); jProgressBarSearchStatus.setValue(0); jButtonSearchStatusSearch.setText("Search"); searching = false; haveOutDir = false; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jDialogjSearchStatus = new javax.swing.JDialog(); jPanelSearchStatusParent = new javax.swing.JPanel(); jPanelSearchStatusTitle = new javax.swing.JPanel(); jLabelSearchStatusTitle = new javax.swing.JLabel(); jPanelSearchStatusBody = new javax.swing.JPanel(); jLabelSearchStatus = new javax.swing.JLabel(); jLabelSearchStatusFile = new javax.swing.JLabel(); jLabelSearchStatusFileValue = new javax.swing.JLabel(); jProgressBarSearchStatus = new javax.swing.JProgressBar(); jLabelSearchStatusFileName = new javax.swing.JLabel(); jLabelSearchStatusFileTitle = new javax.swing.JLabel(); jLabelSearchStatusFileArtist = new javax.swing.JLabel(); jLabelSearchStatusFileAlbum = new javax.swing.JLabel(); jLabelSearchStatusFileNameValue = new javax.swing.JLabel(); jLabelSearchStatusTitleValue = new javax.swing.JLabel(); jLabelSearchStatusArtistValue = new javax.swing.JLabel(); jLabelSearchStatusAlbumValue = new javax.swing.JLabel(); jButtonSearchStatusSearch = new javax.swing.JButton(); jPanelDownloaderParent = new javax.swing.JPanel(); jPanelDownloaderTitle = new javax.swing.JPanel(); jLabelDownloaderTitle = new javax.swing.JLabel(); jPanelDownloaderBody = new javax.swing.JPanel(); jTextFieldSearchKeywords = new javax.swing.JTextField(); jScrollPaneSearchResults = new javax.swing.JScrollPane(); jTableSearchResults = new javax.swing.JTable(); jLabelSelectedFile = new javax.swing.JLabel(); jButtonDownload = new javax.swing.JButton(); jComboBoxSearchCategory = new javax.swing.JComboBox(); jButtonSearch = new javax.swing.JButton(); jLabelFileName = new javax.swing.JLabel(); jLabelTitle = new javax.swing.JLabel(); jLabelArtist = new javax.swing.JLabel(); jLabelAlbum = new javax.swing.JLabel(); jLabelFileNameValue = new javax.swing.JLabel(); jLabelTitleValue = new javax.swing.JLabel(); jLabelArtistValue = new javax.swing.JLabel(); jLabelAlbumValue = new javax.swing.JLabel(); jPanelDownloaderLog = new javax.swing.JPanel(); jScrollPaneDownloaderLog = new javax.swing.JScrollPane(); jTextAreaDownloaderLog = new javax.swing.JTextArea(); jDialogjSearchStatus.setModal(true); jPanelSearchStatusParent.setBackground(new java.awt.Color(102, 102, 102)); jPanelSearchStatusTitle.setBackground(new java.awt.Color(0, 0, 0)); jPanelSearchStatusTitle.setPreferredSize(new java.awt.Dimension(580, 60)); jLabelSearchStatusTitle.setFont(new java.awt.Font("Candara", 0, 24)); // NOI18N jLabelSearchStatusTitle.setForeground(new java.awt.Color(51, 255, 255)); jLabelSearchStatusTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelSearchStatusTitle.setText("Search File"); jLabelSearchStatusTitle.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); javax.swing.GroupLayout jPanelSearchStatusTitleLayout = new javax.swing.GroupLayout(jPanelSearchStatusTitle); jPanelSearchStatusTitle.setLayout(jPanelSearchStatusTitleLayout); jPanelSearchStatusTitleLayout.setHorizontalGroup( jPanelSearchStatusTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelSearchStatusTitleLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabelSearchStatusTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 560, Short.MAX_VALUE) .addContainerGap()) ); jPanelSearchStatusTitleLayout.setVerticalGroup( jPanelSearchStatusTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelSearchStatusTitleLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabelSearchStatusTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE) .addContainerGap()) ); jPanelSearchStatusBody.setBackground(new java.awt.Color(0, 0, 0)); jLabelSearchStatus.setBackground(new java.awt.Color(0, 0, 0)); jLabelSearchStatus.setFont(new java.awt.Font("Candara", 0, 14)); // NOI18N jLabelSearchStatus.setForeground(new java.awt.Color(255, 255, 255)); jLabelSearchStatus.setText("Status"); jLabelSearchStatusFile.setBackground(new java.awt.Color(0, 0, 0)); jLabelSearchStatusFile.setForeground(new java.awt.Color(255, 255, 255)); jLabelSearchStatusFile.setText("File -"); jLabelSearchStatusFileValue.setBackground(new java.awt.Color(0, 0, 0)); jLabelSearchStatusFileValue.setForeground(new java.awt.Color(204, 255, 255)); jLabelSearchStatusFileValue.setText("-"); jProgressBarSearchStatus.setStringPainted(true); jLabelSearchStatusFileName.setBackground(new java.awt.Color(0, 0, 0)); jLabelSearchStatusFileName.setForeground(new java.awt.Color(255, 255, 255)); jLabelSearchStatusFileName.setText("File Name"); jLabelSearchStatusFileTitle.setBackground(new java.awt.Color(0, 0, 0)); jLabelSearchStatusFileTitle.setForeground(new java.awt.Color(255, 255, 255)); jLabelSearchStatusFileTitle.setText("Title"); jLabelSearchStatusFileArtist.setBackground(new java.awt.Color(0, 0, 0)); jLabelSearchStatusFileArtist.setForeground(new java.awt.Color(255, 255, 255)); jLabelSearchStatusFileArtist.setText("Artist"); jLabelSearchStatusFileAlbum.setBackground(new java.awt.Color(0, 0, 0)); jLabelSearchStatusFileAlbum.setForeground(new java.awt.Color(255, 255, 255)); jLabelSearchStatusFileAlbum.setText("Album"); jLabelSearchStatusFileNameValue.setBackground(new java.awt.Color(0, 0, 0)); jLabelSearchStatusFileNameValue.setForeground(new java.awt.Color(204, 255, 255)); jLabelSearchStatusFileNameValue.setText("-"); jLabelSearchStatusTitleValue.setBackground(new java.awt.Color(0, 0, 0)); jLabelSearchStatusTitleValue.setForeground(new java.awt.Color(204, 255, 255)); jLabelSearchStatusTitleValue.setText("-"); jLabelSearchStatusArtistValue.setBackground(new java.awt.Color(0, 0, 0)); jLabelSearchStatusArtistValue.setForeground(new java.awt.Color(204, 255, 255)); jLabelSearchStatusArtistValue.setText("-"); jLabelSearchStatusAlbumValue.setBackground(new java.awt.Color(0, 0, 0)); jLabelSearchStatusAlbumValue.setForeground(new java.awt.Color(204, 255, 255)); jLabelSearchStatusAlbumValue.setText("-"); jButtonSearchStatusSearch.setFont(new java.awt.Font("Candara", 0, 18)); // NOI18N jButtonSearchStatusSearch.setText("Search"); jButtonSearchStatusSearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSearchStatusSearchActionPerformed(evt); } }); javax.swing.GroupLayout jPanelSearchStatusBodyLayout = new javax.swing.GroupLayout(jPanelSearchStatusBody); jPanelSearchStatusBody.setLayout(jPanelSearchStatusBodyLayout); jPanelSearchStatusBodyLayout.setHorizontalGroup( jPanelSearchStatusBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelSearchStatusBodyLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelSearchStatusBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelSearchStatusBodyLayout.createSequentialGroup() .addGroup(jPanelSearchStatusBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(jButtonSearchStatusSearch) .addComponent(jProgressBarSearchStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 560, Short.MAX_VALUE)) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelSearchStatusBodyLayout.createSequentialGroup() .addGroup(jPanelSearchStatusBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelSearchStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 560, Short.MAX_VALUE) .addGroup(jPanelSearchStatusBodyLayout.createSequentialGroup() .addComponent(jLabelSearchStatusFile) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelSearchStatusFileValue, javax.swing.GroupLayout.DEFAULT_SIZE, 531, Short.MAX_VALUE))) .addGap(10, 10, 10)))) .addGroup(jPanelSearchStatusBodyLayout.createSequentialGroup() .addGap(92, 92, 92) .addGroup(jPanelSearchStatusBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelSearchStatusBodyLayout.createSequentialGroup() .addComponent(jLabelSearchStatusFileAlbum) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelSearchStatusAlbumValue, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanelSearchStatusBodyLayout.createSequentialGroup() .addComponent(jLabelSearchStatusFileArtist) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelSearchStatusArtistValue, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)) .addGroup(jPanelSearchStatusBodyLayout.createSequentialGroup() .addComponent(jLabelSearchStatusFileTitle) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelSearchStatusTitleValue, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)) .addGroup(jPanelSearchStatusBodyLayout.createSequentialGroup() .addComponent(jLabelSearchStatusFileName) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelSearchStatusFileNameValue, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE))) .addGap(0, 144, 144)) ); jPanelSearchStatusBodyLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabelSearchStatusFileAlbum, jLabelSearchStatusFileArtist, jLabelSearchStatusFileName, jLabelSearchStatusFileTitle}); jPanelSearchStatusBodyLayout.setVerticalGroup( jPanelSearchStatusBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelSearchStatusBodyLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabelSearchStatus) .addGap(18, 18, 18) .addGroup(jPanelSearchStatusBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelSearchStatusFile) .addComponent(jLabelSearchStatusFileValue)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanelSearchStatusBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelSearchStatusFileName) .addComponent(jLabelSearchStatusFileNameValue)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelSearchStatusBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelSearchStatusFileTitle) .addComponent(jLabelSearchStatusTitleValue)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelSearchStatusBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelSearchStatusFileArtist) .addComponent(jLabelSearchStatusArtistValue)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelSearchStatusBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelSearchStatusFileAlbum) .addComponent(jLabelSearchStatusAlbumValue)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE) .addComponent(jProgressBarSearchStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButtonSearchStatusSearch) .addGap(11, 11, 11)) ); javax.swing.GroupLayout jPanelSearchStatusParentLayout = new javax.swing.GroupLayout(jPanelSearchStatusParent); jPanelSearchStatusParent.setLayout(jPanelSearchStatusParentLayout); jPanelSearchStatusParentLayout.setHorizontalGroup( jPanelSearchStatusParentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelSearchStatusParentLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelSearchStatusParentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanelSearchStatusBody, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanelSearchStatusTitle, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 590, Short.MAX_VALUE)) .addContainerGap()) ); jPanelSearchStatusParentLayout.setVerticalGroup( jPanelSearchStatusParentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelSearchStatusParentLayout.createSequentialGroup() .addContainerGap() .addComponent(jPanelSearchStatusTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanelSearchStatusBody, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout jDialogjSearchStatusLayout = new javax.swing.GroupLayout(jDialogjSearchStatus.getContentPane()); jDialogjSearchStatus.getContentPane().setLayout(jDialogjSearchStatusLayout); jDialogjSearchStatusLayout.setHorizontalGroup( jDialogjSearchStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelSearchStatusParent, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jDialogjSearchStatusLayout.setVerticalGroup( jDialogjSearchStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelSearchStatusParent, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Subtitle Studio 3.1"); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jPanelDownloaderParent.setBackground(new java.awt.Color(51, 51, 51)); jPanelDownloaderTitle.setBackground(new java.awt.Color(0, 0, 0)); jPanelDownloaderTitle.setPreferredSize(new java.awt.Dimension(878, 90)); jLabelDownloaderTitle.setBackground(new java.awt.Color(0, 0, 0)); jLabelDownloaderTitle.setFont(new java.awt.Font("Candara", 0, 36)); // NOI18N jLabelDownloaderTitle.setForeground(new java.awt.Color(0, 255, 255)); jLabelDownloaderTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelDownloaderTitle.setText("Downloader"); javax.swing.GroupLayout jPanelDownloaderTitleLayout = new javax.swing.GroupLayout(jPanelDownloaderTitle); jPanelDownloaderTitle.setLayout(jPanelDownloaderTitleLayout); jPanelDownloaderTitleLayout.setHorizontalGroup( jPanelDownloaderTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDownloaderTitleLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabelDownloaderTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanelDownloaderTitleLayout.setVerticalGroup( jPanelDownloaderTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDownloaderTitleLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabelDownloaderTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE) .addContainerGap()) ); jPanelDownloaderBody.setBackground(new java.awt.Color(0, 0, 0)); jPanelDownloaderBody.setPreferredSize(new java.awt.Dimension(392, 385)); jTextFieldSearchKeywords.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextFieldSearchKeywords.setText("Search Keywords (Minimum 3 characters)"); jTableSearchResults.setBackground(new java.awt.Color(51, 51, 51)); jTableSearchResults.setForeground(new java.awt.Color(255, 255, 255)); jTableSearchResults.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "File Name", "Title", "Artist", "Album" } ) { boolean[] canEdit = new boolean [] { false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTableSearchResults.getTableHeader().setReorderingAllowed(false); jTableSearchResults.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTableSearchResultsMouseClicked(evt); } }); jScrollPaneSearchResults.setViewportView(jTableSearchResults); jLabelSelectedFile.setBackground(new java.awt.Color(0, 0, 0)); jLabelSelectedFile.setForeground(new java.awt.Color(255, 255, 255)); jLabelSelectedFile.setText("Selected File -"); jButtonDownload.setFont(new java.awt.Font("Candara", 0, 18)); // NOI18N jButtonDownload.setText("Download"); jButtonDownload.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonDownloadActionPerformed(evt); } }); jComboBoxSearchCategory.setFont(new java.awt.Font("Candara", 0, 18)); // NOI18N jComboBoxSearchCategory.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Music Video Subtitles", "Movie Subtitles" })); jButtonSearch.setFont(new java.awt.Font("Candara", 0, 18)); // NOI18N jButtonSearch.setText("Search IN >>"); jButtonSearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSearchActionPerformed(evt); } }); jLabelFileName.setBackground(new java.awt.Color(0, 0, 0)); jLabelFileName.setForeground(new java.awt.Color(255, 255, 255)); jLabelFileName.setText("File Name"); jLabelTitle.setBackground(new java.awt.Color(0, 0, 0)); jLabelTitle.setForeground(new java.awt.Color(255, 255, 255)); jLabelTitle.setText("Title"); jLabelArtist.setBackground(new java.awt.Color(0, 0, 0)); jLabelArtist.setForeground(new java.awt.Color(255, 255, 255)); jLabelArtist.setText("Artist"); jLabelAlbum.setBackground(new java.awt.Color(51, 51, 51)); jLabelAlbum.setForeground(new java.awt.Color(255, 255, 255)); jLabelAlbum.setText("Album"); jLabelFileNameValue.setForeground(new java.awt.Color(255, 255, 255)); jLabelFileNameValue.setText("-"); jLabelTitleValue.setBackground(new java.awt.Color(0, 0, 0)); jLabelTitleValue.setForeground(new java.awt.Color(255, 255, 255)); jLabelTitleValue.setText("-"); jLabelArtistValue.setBackground(new java.awt.Color(0, 0, 0)); jLabelArtistValue.setForeground(new java.awt.Color(255, 255, 255)); jLabelArtistValue.setText("-"); jLabelAlbumValue.setBackground(new java.awt.Color(0, 0, 0)); jLabelAlbumValue.setForeground(new java.awt.Color(255, 255, 255)); jLabelAlbumValue.setText("-"); javax.swing.GroupLayout jPanelDownloaderBodyLayout = new javax.swing.GroupLayout(jPanelDownloaderBody); jPanelDownloaderBody.setLayout(jPanelDownloaderBodyLayout); jPanelDownloaderBodyLayout.setHorizontalGroup( jPanelDownloaderBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDownloaderBodyLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelDownloaderBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPaneSearchResults, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanelDownloaderBodyLayout.createSequentialGroup() .addComponent(jTextFieldSearchKeywords, javax.swing.GroupLayout.DEFAULT_SIZE, 426, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonSearch) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBoxSearchCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jButtonDownload) .addComponent(jLabelSelectedFile) .addGroup(jPanelDownloaderBodyLayout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(jPanelDownloaderBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDownloaderBodyLayout.createSequentialGroup() .addComponent(jLabelFileName) .addGap(18, 18, 18) .addComponent(jLabelFileNameValue, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanelDownloaderBodyLayout.createSequentialGroup() .addComponent(jLabelTitle) .addGap(18, 18, 18) .addComponent(jLabelTitleValue, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanelDownloaderBodyLayout.createSequentialGroup() .addComponent(jLabelAlbum) .addGap(18, 18, 18) .addComponent(jLabelAlbumValue, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanelDownloaderBodyLayout.createSequentialGroup() .addComponent(jLabelArtist) .addGap(18, 18, 18) .addComponent(jLabelArtistValue, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))) .addContainerGap()) ); jPanelDownloaderBodyLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabelAlbum, jLabelArtist, jLabelFileName, jLabelTitle}); jPanelDownloaderBodyLayout.setVerticalGroup( jPanelDownloaderBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDownloaderBodyLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelDownloaderBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldSearchKeywords, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBoxSearchCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonSearch)) .addGap(18, 18, 18) .addComponent(jScrollPaneSearchResults, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jLabelSelectedFile) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelDownloaderBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelFileName) .addComponent(jLabelFileNameValue)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelDownloaderBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelTitle) .addComponent(jLabelTitleValue)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelDownloaderBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelArtist) .addComponent(jLabelArtistValue)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelDownloaderBodyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelAlbum) .addComponent(jLabelAlbumValue)) .addGap(11, 11, 11) .addComponent(jButtonDownload) .addContainerGap()) ); jPanelDownloaderBodyLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jButtonSearch, jComboBoxSearchCategory, jTextFieldSearchKeywords}); jPanelDownloaderLog.setBackground(new java.awt.Color(0, 0, 0)); jTextAreaDownloaderLog.setEditable(false); jTextAreaDownloaderLog.setBackground(new java.awt.Color(0, 0, 0)); jTextAreaDownloaderLog.setColumns(20); jTextAreaDownloaderLog.setFont(new java.awt.Font("Lucida Console", 0, 12)); // NOI18N jTextAreaDownloaderLog.setForeground(new java.awt.Color(102, 255, 51)); jTextAreaDownloaderLog.setRows(5); jTextAreaDownloaderLog.setText("Log"); jScrollPaneDownloaderLog.setViewportView(jTextAreaDownloaderLog); javax.swing.GroupLayout jPanelDownloaderLogLayout = new javax.swing.GroupLayout(jPanelDownloaderLog); jPanelDownloaderLog.setLayout(jPanelDownloaderLogLayout); jPanelDownloaderLogLayout.setHorizontalGroup( jPanelDownloaderLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDownloaderLogLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPaneDownloaderLog, javax.swing.GroupLayout.DEFAULT_SIZE, 760, Short.MAX_VALUE) .addContainerGap()) ); jPanelDownloaderLogLayout.setVerticalGroup( jPanelDownloaderLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDownloaderLogLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPaneDownloaderLog) .addContainerGap()) ); javax.swing.GroupLayout jPanelDownloaderParentLayout = new javax.swing.GroupLayout(jPanelDownloaderParent); jPanelDownloaderParent.setLayout(jPanelDownloaderParentLayout); jPanelDownloaderParentLayout.setHorizontalGroup( jPanelDownloaderParentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelDownloaderParentLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelDownloaderParentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanelDownloaderLog, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanelDownloaderTitle, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 784, Short.MAX_VALUE) .addComponent(jPanelDownloaderBody, javax.swing.GroupLayout.DEFAULT_SIZE, 784, Short.MAX_VALUE)) .addContainerGap()) ); jPanelDownloaderParentLayout.setVerticalGroup( jPanelDownloaderParentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelDownloaderParentLayout.createSequentialGroup() .addContainerGap() .addComponent(jPanelDownloaderTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanelDownloaderBody, javax.swing.GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanelDownloaderLog, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelDownloaderParent, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelDownloaderParent, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSearchActionPerformed if (!searching) { searchKey = jTextFieldSearchKeywords.getText(); if (searchKey.length() >= 3) { initiateDownload(); searchClick = true; call = 2; new Thread(this).start(); } else { jTextFieldSearchKeywords.setText("Enter minimum 3 characters..."); } } else { jDialogjSearchStatus.setSize(640, 300); jDialogjSearchStatus.setLocationRelativeTo(null); jDialogjSearchStatus.setVisible(true); } }//GEN-LAST:event_jButtonSearchActionPerformed private void jButtonSearchStatusSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSearchStatusSearchActionPerformed if (searchClick) { if (jButtonSearchStatusSearch.getText().equals("OK")) { jDialogjSearchStatus.dispose(); } else if (!searching) { jButtonSearchStatusSearch.setText("Hide"); call = 3; new Thread(this).start(); searching = true; jTextFieldSearchKeywords.setEditable(false); } else { jDialogjSearchStatus.dispose(); } } else if (jButtonSearchStatusSearch.getText().equals("OK")) { jDialogjSearchStatus.dispose(); } else if (!downloading) { jButtonSearchStatusSearch.setText("Hide"); call = 5; new Thread(this).start(); downloading = true; } else { jDialogjSearchStatus.dispose(); } }//GEN-LAST:event_jButtonSearchStatusSearchActionPerformed private void jTableSearchResultsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableSearchResultsMouseClicked if (totalResults != 0) { int fileNo = jTableSearchResults.getSelectedRow(); if (fileNo < totalResults) { jLabelFileNameValue.setText("- " + jTableSearchResults.getValueAt(fileNo, 0)); jLabelTitleValue.setText("- " + jTableSearchResults.getValueAt(fileNo, 1)); jLabelArtistValue.setText("- " + jTableSearchResults.getValueAt(fileNo, 2)); jLabelAlbumValue.setText("- " + jTableSearchResults.getValueAt(fileNo, 3)); } else { jLabelFileNameValue.setText("-"); jLabelTitleValue.setText("-"); jLabelArtistValue.setText("-"); jLabelAlbumValue.setText("-"); } } }//GEN-LAST:event_jTableSearchResultsMouseClicked private void jButtonDownloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDownloadActionPerformed if (totalResults > 0 && !searching && !"-".equals(jLabelFileNameValue.getText())) { if (downloading) { jDialogjSearchStatus.setSize(640, 360); jDialogjSearchStatus.setLocationRelativeTo(null); jDialogjSearchStatus.setVisible(true); } else { JFileChooser jfc = new JFileChooser(); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); jfc.setVisible(true); jfc.showSaveDialog(this); if (jfc.getSelectedFile() != null) { outDIR = jfc.getSelectedFile() + ""; call = 4; searchClick = false; new Thread(this).start(); } } } }//GEN-LAST:event_jButtonDownloadActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing MainWindow.getFrames()[0].setVisible(true); }//GEN-LAST:event_formWindowClosing // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonDownload; private javax.swing.JButton jButtonSearch; private javax.swing.JButton jButtonSearchStatusSearch; private javax.swing.JComboBox jComboBoxSearchCategory; private javax.swing.JDialog jDialogjSearchStatus; private javax.swing.JLabel jLabelAlbum; private javax.swing.JLabel jLabelAlbumValue; private javax.swing.JLabel jLabelArtist; private javax.swing.JLabel jLabelArtistValue; private javax.swing.JLabel jLabelDownloaderTitle; private javax.swing.JLabel jLabelFileName; private javax.swing.JLabel jLabelFileNameValue; private javax.swing.JLabel jLabelSearchStatus; private javax.swing.JLabel jLabelSearchStatusAlbumValue; private javax.swing.JLabel jLabelSearchStatusArtistValue; private javax.swing.JLabel jLabelSearchStatusFile; private javax.swing.JLabel jLabelSearchStatusFileAlbum; private javax.swing.JLabel jLabelSearchStatusFileArtist; private javax.swing.JLabel jLabelSearchStatusFileName; private javax.swing.JLabel jLabelSearchStatusFileNameValue; private javax.swing.JLabel jLabelSearchStatusFileTitle; private javax.swing.JLabel jLabelSearchStatusFileValue; private javax.swing.JLabel jLabelSearchStatusTitle; private javax.swing.JLabel jLabelSearchStatusTitleValue; private javax.swing.JLabel jLabelSelectedFile; private javax.swing.JLabel jLabelTitle; private javax.swing.JLabel jLabelTitleValue; private javax.swing.JPanel jPanelDownloaderBody; private javax.swing.JPanel jPanelDownloaderLog; private javax.swing.JPanel jPanelDownloaderParent; private javax.swing.JPanel jPanelDownloaderTitle; private javax.swing.JPanel jPanelSearchStatusBody; private javax.swing.JPanel jPanelSearchStatusParent; private javax.swing.JPanel jPanelSearchStatusTitle; private javax.swing.JProgressBar jProgressBarSearchStatus; private javax.swing.JScrollPane jScrollPaneDownloaderLog; private javax.swing.JScrollPane jScrollPaneSearchResults; private javax.swing.JTable jTableSearchResults; private javax.swing.JTextArea jTextAreaDownloaderLog; private javax.swing.JTextField jTextFieldSearchKeywords; // End of variables declaration//GEN-END:variables final private RemoteStorageApis remoteStorage = RemoteStorage.getInstance(); //MyVariabels int call = 0; long startTime = 0; String searchKey = ""; List<SearchResult> results; List<Integer> serverNo = new ArrayList<Integer>(1); List<String> resultDIR = new ArrayList<String>(1); int totalResults; boolean searching = false; boolean downloading = false; boolean haveOutDir = false; boolean searchClick; private String outDIR = ""; @Override public void run() { if (call == 2) { //search jLabelSearchStatusFileName.setText(""); jLabelSearchStatusFileTitle.setText(""); jLabelSearchStatusFileArtist.setText(""); jLabelSearchStatusFileAlbum.setText(""); jLabelSearchStatusFileNameValue.setText(""); jLabelSearchStatusTitleValue.setText(""); jLabelSearchStatusArtistValue.setText(""); jLabelSearchStatusAlbumValue.setText(""); jLabelSearchStatusFileValue.setText(searchKey); jDialogjSearchStatus.setSize(640, 300); jDialogjSearchStatus.setLocationRelativeTo(null); jDialogjSearchStatus.setVisible(true); } else if (call == 3) { //other jLabelSearchStatusTitle.setText("Searching File"); searchFile(searchKey); searching = false; jTextFieldSearchKeywords.setEditable(true); jLabelSearchStatusTitle.setText("Search"); jTextAreaDownloaderLog.append("\n" + new MyTime(System.currentTimeMillis() - startTime) + "-Match found - " + totalResults); jTextAreaDownloaderLog.setCaretPosition(jTextAreaDownloaderLog.getText().length()); jLabelSearchStatus.setText("Match found - " + totalResults); jButtonSearchStatusSearch.setText("OK"); jDialogjSearchStatus.setSize(640, 300); jDialogjSearchStatus.setLocationRelativeTo(null); jDialogjSearchStatus.setVisible(true); jTableSearchResults.setRowSelectionInterval(0, 0); jTableSearchResultsMouseClicked(null); } else if (call == 4) { //download jLabelSearchStatusTitle.setText("Download File"); jLabelSearchStatus.setText("Status"); jLabelSearchStatusFile.setText("Saving to - "); jLabelSearchStatusFileValue.setText(outDIR); int fileNo = jTableSearchResults.getSelectedRow(); jLabelSearchStatusFileName.setText("File Name"); jLabelSearchStatusFileTitle.setText("Title"); jLabelSearchStatusFileArtist.setText("Artist"); jLabelSearchStatusFileAlbum.setText("Album"); jLabelSearchStatusFileNameValue.setText("- " + jTableSearchResults.getValueAt(fileNo, 0)); jLabelSearchStatusTitleValue.setText("- " + jTableSearchResults.getValueAt(fileNo, 1)); jLabelSearchStatusArtistValue.setText("- " + jTableSearchResults.getValueAt(fileNo, 2)); jLabelSearchStatusAlbumValue.setText("- " + jTableSearchResults.getValueAt(fileNo, 3)); jProgressBarSearchStatus.setValue(0); jButtonSearchStatusSearch.setText("Download Now"); jDialogjSearchStatus.setSize(640, 360); jDialogjSearchStatus.setLocationRelativeTo(null); jDialogjSearchStatus.setVisible(true); } else { jLabelSearchStatusTitle.setText("Downloading File"); downloadFile(searchResults.get(jTableSearchResults.getSelectedRow())); } } private void searchFile(String query) { try { searchResults = remoteStorage.searchFile(jComboBoxSearchCategory.getSelectedIndex(), query); for (int current = 0; current < searchResults.size(); current++) { SearchResult searchResult = searchResults.get(current); int subCategary = searchResult.getSubCategary(); String fileName = searchResult.getFileName(); jTableSearchResults.setValueAt(fileName, current, 0); switch (subCategary) { case RemoteStorage.SUB_CATEGARY_TITLE: jTableSearchResults.setValueAt(searchResult.getTitle(), current, 1); break; case RemoteStorage.SUB_CATEGARY_TITLE_ALBUM: jTableSearchResults.setValueAt(searchResult.getTitle(), current, 1); jTableSearchResults.setValueAt(searchResult.getAlbum(), current, 3); break; case RemoteStorage.SUB_CATEGARY_TITLE_ARTIST: jTableSearchResults.setValueAt(searchResult.getTitle(), current, 1); jTableSearchResults.setValueAt(searchResult.getArtist(), current, 2); break; case RemoteStorage.SUB_CATEGARY_TITLE_ARTIST_ALBUM: jTableSearchResults.setValueAt(searchResult.getTitle(), current, 1); jTableSearchResults.setValueAt(searchResult.getArtist(), current, 2); jTableSearchResults.setValueAt(searchResult.getAlbum(), current, 3); break; } } } catch (RemoteStorageException ex) { Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex); } } private void downloadFile(SearchResult searchResult) { jTextAreaDownloaderLog.append("\n" + new MyTime(System.currentTimeMillis() - startTime) + "-Connecting to Subtitle Studio..."); jTextAreaDownloaderLog.setCaretPosition(jTextAreaDownloaderLog.getText().length()); jLabelSearchStatus.setText("Connecting to Subtitle Studio..."); jTextAreaDownloaderLog.append("\n" + new MyTime(System.currentTimeMillis() - startTime) + "-Connected to Subtitle Studio..."); jTextAreaDownloaderLog.setCaretPosition(jTextAreaDownloaderLog.getText().length()); jLabelSearchStatus.setText("Connected to Subtitle Studio..."); jProgressBarSearchStatus.setValue(20); try { remoteStorage.downloadSearchedFile(searchResult, outDIR, null); } catch (RemoteStorageException ex) { Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex); } jProgressBarSearchStatus.setValue(100); jTextAreaDownloaderLog.append("\n" + new MyTime(System.currentTimeMillis() - startTime) + "-Download Complete"); jTextAreaDownloaderLog.setCaretPosition(jTextAreaDownloaderLog.getText().length()); jLabelSearchStatus.setText("Download Complete"); jLabelSearchStatusTitle.setText("Download Complete"); jButtonSearchStatusSearch.setText("OK"); downloading = false; jProgressBarSearchStatus.setValue(100); jDialogjSearchStatus.setSize(640, 360); jDialogjSearchStatus.setLocationRelativeTo(null); jDialogjSearchStatus.setVisible(true); } public static void main(String[] args) { Downloader downloader = new Downloader(); downloader.setLocationRelativeTo(null); downloader.setVisible(true); } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package in.swapnilbhoite.projects.subtitlestudio; /** * * @author <NAME> */ public class MyMapping { public long start, end, fadeIN, fadeOUT; String dialog; public MyMapping() { fadeIN = fadeOUT = start = end = 0; dialog = ""; } public void setTime(String temp) { //00:00:03,000 --> 00:00:06,478 String temp0[], temp1[], temp2[], temp3[], temp4[]; temp0 = temp.split(" --> "); temp1 = temp0[0].split(","); start = new Long(temp1[1]); temp2 = temp1[0].split(":"); start = start + 3600000 * (new Long(temp2[0])); start = start + 60000 * (new Long(temp2[1])); start = start + 1000 * (new Long(temp2[2])); temp3 = temp0[1].split(","); end = new Long(temp3[1]); temp4 = temp3[0].split(":"); end = end + 3600000 * (new Long(temp4[0])); end = end + 60000 * (new Long(temp4[1])); end = end + 1000 * (new Long(temp4[2])); } public void setDialog(String temp) { dialog = temp; } public String getDialog() { return dialog; } public void reset() { dialog = ""; fadeIN = fadeOUT = start = end = 0; } public void adjustFade(MyMapping dialogs[], String in, String out, int total) { long fadeIn = new Long(in); long fadeOut = new Long(out); for (int i = 0; i < total; i++) { dialogs[i].fadeIN = fadeIn; dialogs[i].fadeOUT = fadeOut; long diff = dialogs[i].end - dialogs[i].start; if (diff > 2 * (fadeIn + fadeOut)) { dialogs[i].fadeIN = fadeIn; dialogs[i].fadeOUT = fadeOut; } else { diff = diff / 4; dialogs[i].fadeIN = diff; dialogs[i].fadeOUT = diff; } } } @Override public String toString() { return "Start:" + start + " End:" + end + " " + dialog; } } <file_sep># subtitle-studio Subtitle Studio creates, converts, uploads and download subtitles. The current source is a 4 year old source of [Subtitle Studio 3.1](http://projects.swapnilbhoite.in/subtitlestudio/), hence need **a lot of** refactoring. The project structure is in compliance with NetBeans IDE. Main libraries used: - vlcj 3.10.1 (for video playback) - dropbox sdk 1.3 (for uploads and downloads)<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package in.swapnilbhoite.projects.subtitlestudio.remote_storage; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author <NAME> */ public class SearchResult { private final String fileName; private final String remotePath; private final int categary; private final int subCategary; private final Object extra; private String title; private String artist; private String album; public SearchResult(String fileName, String remotePath, int categary, int subCategary, Object extra) { this.fileName = fileName; this.remotePath = remotePath; this.categary = categary; this.subCategary = subCategary; this.extra = extra; try { title = artist = album = ""; initMetaData(); } catch (Exception ex) { Logger.getLogger(SearchResult.class.getName()).log(Level.WARNING, null, ex); } } private void initMetaData() { String extension = fileName.substring(fileName.lastIndexOf("."), fileName.length() - 1); String[] spilts; switch (subCategary) { case RemoteStorage.SUB_CATEGARY_TITLE: spilts = fileName.split(extension); title = spilts[0]; break; case RemoteStorage.SUB_CATEGARY_TITLE_ALBUM: spilts = fileName.split(RemoteStorage.DELIMITER_ALBUM); title = spilts[0]; spilts = spilts[1].split(extension); album = spilts[0]; break; case RemoteStorage.SUB_CATEGARY_TITLE_ARTIST: spilts = fileName.split(RemoteStorage.DELIMITER_ARTIST); title = spilts[0]; spilts = spilts[1].split(extension); artist = spilts[0]; break; case RemoteStorage.SUB_CATEGARY_TITLE_ARTIST_ALBUM: spilts = fileName.split(RemoteStorage.DELIMITER_ARTIST); title = spilts[0]; spilts = spilts[1].split(RemoteStorage.DELIMITER_ALBUM); artist = spilts[0]; spilts = spilts[1].split(extension); album = spilts[0]; break; } } public String getFileName() { return fileName; } public String getRemotePath() { return remotePath; } public int getCategary() { return categary; } public int getSubCategary() { return subCategary; } public Object getExtra() { return extra; } public String getTitle() { return title; } public String getArtist() { return artist; } public String getAlbum() { return album; } @Override public int hashCode() { int hash = 7; hash = 59 * hash + (this.fileName != null ? this.fileName.hashCode() : 0); hash = 59 * hash + (this.remotePath != null ? this.remotePath.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SearchResult other = (SearchResult) obj; if ((this.fileName == null) ? (other.fileName != null) : !this.fileName.equals(other.fileName)) { return false; } return !((this.remotePath == null) ? (other.remotePath != null) : !this.remotePath.equals(other.remotePath)); } @Override public String toString() { return "SearchResult{" + "fileName=" + fileName + ", remotePath=" + remotePath + ", categary=" + categary + ", subCategary=" + subCategary + ", extra=" + extra + ", title=" + title + ", artist=" + artist + ", album=" + album + '}'; } } <file_sep>package in.swapnilbhoite.projects.subtitlestudio; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.plaf.nimbus.NimbusLookAndFeel; /** * * @author <NAME> */ public class Main { public static void main(String[] args) { try { UIManager.setLookAndFeel(new NimbusLookAndFeel()); } catch (UnsupportedLookAndFeelException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } MainWindow mainWindow = new MainWindow(); mainWindow.setResizable(false); mainWindow.setLocationRelativeTo(null); mainWindow.setVisible(true); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package in.swapnilbhoite.projects.subtitlestudio.remote_storage; /** * * @author <NAME> */ public interface RemoteProgressListener { void onProgressUpdate(int progress, String description); }
107722f72bc7793df2f4330938294a2d59e776ff
[ "Markdown", "Java" ]
9
Java
MarkXLII/subtitle-studio
b9021b874a477256c16dbe20cf4c6d024733e731
3b61c79e69eb82fa0126f9d879730697d1e0654b
refs/heads/master
<file_sep>#include <iostream> #include <string.h> #include <ctype.h> #include <math.h> #include <string> #include <algorithm> #include <cmath> #include <cstdio> #include <limits.h> #include <set> #include <stack> #include <vector> #include <map> #include <queue> #include <sstream> #define mod 1000000007 #define INF 200000000 using namespace std; long long a[500010]; int main() { //freopen("budget.in","r",stdin); //freopen("budget.out","w",stdout); int n; scanf("%d",&n); long long sum=0; for(int i =0;i<n;i++) cin >> a[i],sum+=a[i]; long long c1=0,c2=0; if(sum%3!=0) { printf("0"); return 0; } long long x=0; for(int i=0;i<n - 1;i++) { x+=a[i]; if(sum*2/3==x) { c2+=c1; } if(sum/3==x) { c1++; } } cout << c2; return 0; } <file_sep>int np[10000005]; vector<int > primes; void sieve(){ np[0] = np[1] = 1; for(int i = 2; i <= 10000000 / i; i++){ if(!np[i]){ for(int j = i * i; j <= 10000000; j += i){ if(!np[j]) np[j] = i; } } } for(int i = 2; i <= 10000000; i++){ if(!np[i]) primes.push_back(i); } }<file_sep>#include<bits/stdc++.h> using namespace std; int dp[2][505][505]; int t; int main() { int n,m,b,mod; cin >> n >> m >> b >> mod; dp[0][0][0] = 1; int tmp_i; for(int i = 1, a; i <= n; ++i) { cin >> a; for(int j = 0; j <= m; ++j) { for(int k = 0; k <= b; ++k) { tmp_i = i&1; t = ((k-a) >= 0 && j > 0) ? dp[tmp_i][j-1][k-a] : 0; dp[tmp_i][j][k] = (dp[1-tmp_i][j][k] + t) % mod; } } } int total = 0; for(int i = 0; i <= b; ++i) total = (total + dp[tmp_i][m][i]) % mod; cout << total << endl; return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; int a[200005]; int main() { int n,mn=1e9 + 10; scanf("%d", &n); for(int i = 0; i < n; ++i) { scanf("%d", a + i); } sort(a, a + n); for(int i = 0; i < n / 2; ++i) { mn = min(a[i+n/2]-a[i],mn); } printf("%d", mn); } <file_sep>#include<bits/stdc++.h> using namespace std; char s[1005][1005]; int sum[1005][1005]; int mn = 1000000007, area = 0; int X, Y, n, m; int extend(int x, int y, int dx, int dy){ int mx = 0; if(x + dx <= n && y + dy - 1 <= m && sum[x + dx][y + dy - 1] - sum[x + dx][y - 1] - sum[x][y + dy - 1] + sum[x][y - 1] == dx * dy) mx = dy + extend(x + 1, y, dx, dy); else if(y + dy <= m && x + dx - 1 <= n && sum[x + dx - 1][y + dy] - sum[x + dx - 1][y] - sum[x - 1][y + dy] + sum[x - 1][y] == dx * dy) mx = dx + extend(x, y + 1, dx, dy); // cout << "func " << dx << " " << dy << " " << x << " " << y << " : " << mx << endl; return mx; } int main(){ #ifndef ONLINE_JUDGE freopen("i.in", "r", stdin); #endif // freopen("i.in", "w", stdout); // for(int i = 0; i < 1000; i++){ for(int j = 0; j < 1000; j++) cout << "X"; cout << endl; } ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> m; for(int i = 1; i <= n; i++) cin >> (s[i] + 1); int x, y; for(x = 1; x <= n; x++){ for(y = 1; y <= m; y++) if(s[x][y] == 'X') break; if(y < m + 1) break; } X = x, Y = y; // cout << x << endl << y << endl; int extX = 0, extY = 0; for(int i = x; i <= n; i++) if(s[i][y] == 'X') extX++; for(int i = y; i <= m; i++) if(s[x][i] == 'X') extY++; // cout << extX << endl << extY << endl; for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++){ sum[i][j] = (sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + (s[i][j] == 'X')), area += (s[i][j] == 'X'); // cout << i << " " << j << " : " << sum[i][j] << endl; } for(int dx = 1; dx <= extX; dx++){ if(dx * extY > mn) break; if(sum[x + dx - 1][y + extY - 1] - sum[x + dx - 1][y - 1] - sum[x - 1][y + extY - 1] + sum[x - 1][y - 1] == dx * extY){ int dArea = dx * extY + extend(x, y, dx, extY); // cout << dArea << endl; if(dArea == area && dx * extY < mn) mn = dx * extY; // cout << "for " << dx << " " << dy << " : " << mn << endl; } } for(int dy = 1; dy <= extY; dy++){ if(dy * extX > mn) break; if(sum[x + extX - 1][y + dy - 1] - sum[x + extX - 1][y - 1] - sum[x - 1][y + dy - 1] + sum[x - 1][y - 1] == extX * dy){ int dArea = dy * extX + extend(x, y, extX, dy); // cout << dArea << endl; if(dArea == area && extX * dy < mn) mn = extX * dy; // cout << "for " << dx << " " << dy << " : " << mn << endl; } } if(mn == 1000000007) cout << "-1" << endl; else cout << mn << endl; } <file_sep>int primes[5000080] , primeFactors[41550] , ans[5000080] , z = 1 , a , b; inline void init() { primes[0] = primes[1] = 1; for(long long i = 2;i < 500050;i++) if(!primes[i]) for(long long j = i * i;j < 500050;j += i) primes[j] = 1; primeFactors[0] = 2; for(int i = 3;i < 500050;i += 2) if(!primes[i]) primeFactors[z++] = i; for(int i = 2;i <= 5000040;++i) { int x = i; int j = 0; while(1LL * primeFactors[j] * primeFactors[j] <= x) { while(!(x % primeFactors[j])) { x /= primeFactors[j]; ++ans[i]; } ++j; } if(x != 1) ++ans[i]; ans[i] += ans[i - 1]; } }<file_sep>#include<bits/stdc++.h> using namespace std; long long mod = 1000000007, n, m; typedef vector<vector<long long > > matrix; matrix mul(matrix const &a, matrix const &b){ matrix res(a.size(), vector<long long >(a.size())); for(size_t i = 1; i < a.size(); i++) for(size_t j = 1; j < a.size(); j++) for(size_t k = 1; k < a.size(); k++) res[i][j] += (a[i][k] * b[k][j]) % mod, res[i][j] %= mod; return res; } matrix power(matrix const &a, long long p){ if(p == 1) return a; else if(p & 1) return mul(a, power(a, p - 1)); else{ matrix tmp = power(a, p / 2); return mul(tmp, tmp); } } long long mov(long long n){ matrix t(3, vector<long long >(3)); t[1][1] = 0, t[1][2] = 3, t[2][1] = 1, t[2][2] = 2; t = power(t, n); return (t[1][1]) % mod; } int main(){ cin >> n; cout << mov(n) << endl; } <file_sep>vector<pair<int, pair<int, int> > > G; #define from first #define to second.first #define w second.second int n; int Bell(int source, int dest){ vector<int > dist(n, INF); dist[source] = 0; for(int i = 0; i < n - 1; i++){ for(int j = 0; j < (int)G.size(); j++){ dist[G[j].to] = min(dist[G[j].from] + G[j].w, dist[G[j].to]); } } return dist[dest]; }<file_sep>#include <bits/stdc++.h> using namespace std; #define mod (long long)1000000007 long long hash_[600005]; long long hash_2[600005]; long long pre[600005]; long long pre2[600005]; string s; set<pair<long long, long long > > st; long long pr[] = {3,5,7}; int main(){ hash_[0] = hash_2[0] = 1; for(int i = 1; i <= 600000; i++) hash_[i] = (hash_[i - 1] * 37) % mod; for(int i = 1; i <= 600000; i++) hash_2[i] = (hash_2[i - 1] * 11) % mod; int n, m; cin >> n >> m; while(n--){ cin >> s; int l = s.length(); pre[0] = 0; pre2[0] = 0; for(int i = 1; i <= l; i++){ pre[i] = (pre[i - 1] + pr[(s[i - 1] - 'a')] * hash_[i - 1]) % mod; pre2[i] = (pre2[i - 1] + pr[(s[i - 1] - 'a')] * hash_2[i - 1]) % mod; } for(int i = 0; i < l; i++){ long long a, b; if(s[i] == 'a') a = 5, b = 7; else if(s[i] == 'b') a = 3, b = 7; else a = 3, b = 5; st.insert({(pre[i] + a * hash_[i] + pre[l] - pre[i + 1] + mod) % mod, (pre2[i] + a * hash_2[i] + pre2[l] - pre2[i + 1] + mod) % mod}); st.insert({(pre[i] + b * hash_[i] + pre[l] - pre[i + 1] + mod) % mod, (pre2[i] + b * hash_2[i] + pre2[l] - pre2[i + 1] + mod) % mod}); } } while(m--){ long long hash__ = 0; long long hash___ = 0; cin >> s; int l = s.length(); for(int i = 0; i < l; i++){ hash__ += (long long)(pr[s[i]-'a']) * hash_[i]; hash___ += (long long)(pr[s[i]-'a']) * hash_2[i]; hash__ %= mod; hash___ %= mod; } if(st.find({hash__, hash___}) != st.end()) cout << "YES" << endl; else cout << "NO" << endl; } } <file_sep>#include <cstdio> #include <algorithm> #include <iostream> using namespace std; int main(){ int n, m; scanf("%d%d", &n, &m); int a[n]; int b[m]; for(int i = 0; i < n; i++) scanf("%d", &a[i]); for(int i = 0; i < m; i++) scanf("%d", &b[i]); sort(a, a + n); sort(b, b + m); if(a[0] >= b[m - 1]){ puts("0"); return 0;} long long left = a[0] - 1, right = b[m - 1] + 1; while(right - left >= 3){ long long A = (2 * left + right) / 3; long long B = (left + 2 * right) / 3; long long fA = 0; long long fB = 0; for(int i = 0; i < n; i++) fA += ((A - a[i]) > 0 ? A - a[i] : 0), fB += ((B - a[i]) > 0 ? B - a[i] : 0); for(int i = 0; i < m; i++) fA += ((b[i] - A) > 0 ? b[i] - A : 0), fB += ((b[i] - B) > 0 ? b[i] - B : 0); if(fA > fB) left = A; else{ right = B;} } long long ans = 0; long long A = (left + right) / 2; for(int i = 0; i < n; i++) ans += ((A - a[i]) > 0 ? A - a[i] : 0); for(int i = 0; i < m; i++) ans += ((b[i] - A) > 0 ? b[i] - A : 0); cout << ans << endl; } <file_sep>#include<bits/stdc++.h> using namespace std; string s; int main() { int l,r,k,t; cin >> s; scanf("%d", &t); for(int i = 0; i < t; ++i) { scanf("%d%d%d",&l,&r,&k); l--; k %= (r-l); rotate(s.begin() + l , s.begin() + r - k, s.begin() + r); } cout<<s; } <file_sep>#include <cstdio> char sol[500][500]; int main(){ freopen("chip.in", "r", stdin); freopen("chip.out", "w", stdout); bool solvable = true; int n, m, h, occ = 0; scanf("%d%d%d", &n, &m, &h); int O[n], V[n]; for(int i = 0; i < n; i++) scanf("%d", &O[i]), occ += O[i]; int L[m]; for(int i = 0; i < m; i++) scanf("%d", &L[i]), occ += L[i] * h; if(occ < n * m || occ > n * m) solvable = false; for(int i = 0; i <= n - h; i++){ V[i] = m - O[i]; for(int j = 1; j < h; j++){ if(i - j >= 0) V[i] -= V[i - j]; } for(int j = 1; j < h; j++){ if(m - O[i + j] < V[i]) V[i] = m - O[i + j]; } if(V[i] < 0){ solvable = false; break;} int cnt = 0; for(; cnt < V[i]; cnt++){ int mx = 0, mxRep = 0; for(int k = 0; k < m; k++){ if(L[k] > mx && sol[i][k] != '+' && sol[i][k] != '|') mx = L[k], mxRep = k; } if(mx){ L[mxRep]--; for(int l = 0; l < h; l++){ if((l == 0 || l == h - 1)) sol[i + l][mxRep] = '+'; else sol[i + l][mxRep] = '|'; } } else break; } V[i] = cnt; } for(int i = 0; i < m; i++) solvable = (solvable && !L[i]); for(int i = 0; i < n; i++){ int cnt = O[i]; for(int j = 0; j < m; j++){ if(sol[i][j] != '+' && sol[i][j] != '|'){ if(cnt) sol[i][j] = '*', cnt--; else sol[i][j] = '+'; } } if(cnt) solvable = false; } if(!solvable) printf("inconsistent\n"); else for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ printf("%c", sol[i][j]); } printf("\n"); } } <file_sep>#include<bits/stdc++.h> using namespace std; struct tree{ int p1,p2; tree *l,*r; tree(int p):p2(p),l(0),r(0),p1(0){} }; void expand(tree *t) { t->p2=max(t->p1,t->p2); if(t->l) t->l->p1=max(t->l->p1,t->p1); if(t->r) t->r->p1=max(t->r->p1,t->p1); } int get(tree *t, int l, int r, const int &p) { //cout << l << " " << r << " " << t->p2 << endl; if(l>r) return 0; expand(t); int md=(l+r)>>1; if(t->l&&(l<=p&&p<=md)) return get(t->l,l,md,p); if(t->r&&(md+1<=p&&p<=r)) return get(t->r,md+1,r,p); return t->p2; } void u(tree *t, int l, int r, const int& sl, const int &sr, int v) { expand(t); if(r<sl||l>sr||l>r) return; if(sl<=l&&r<=sr) { //cout << l << " " << r << " " << sl << " " << sr << " " << v << endl; t->p1=v; expand(t); return; } if(!t->l) { t->l=new tree(t->p2); t->r=new tree(t->p2); } int md=(l+r)>>1; if(l>=r) return; u(t->l,l,md,sl,sr,v); u(t->r,md+1,r,sl,sr,v); } int x,y,c,n,q; tree *v,*h; inline void scan(){scanf("%d%d%c%c",&x,&y,&c,&c);} inline int work() { int r,z; if (c == 'U') { r = y - (z=get(v, 1, n, x)); u(h, 1, n, z, y, x); u(v, 1, n, x, x, y); } else { r = x - (z=get(h, 1, n, y)); u(v, 1, n, z, x, y); u(h, 1, n, y, y, x); } return r; } int main() { h=new tree(0); v=new tree(0); scanf("%d%d",&n,&q); for(int i = 0; i < q; ++i) { scan(); printf("%d\n",work()); } return 0; } <file_sep>#include<bits/stdc++.h> using namespace std; const int mxn = 5005; int n,k,m; char s[mxn],r[mxn],d[mxn][mxn]; int solve(int i, int j) { if(i>j) return 1; if(d[i][j]!=-1) return d[i][j]; return d[i][j] = (s[i]==s[j]&&solve(i+2,j-2)); } struct Trie{ int cnt; vector<Trie*> nxt; Trie() { cnt=0; nxt=vector<Trie*>(2,0); } }root; void build(int i) { Trie* cur = &root; for(int j = i; j < n; ++j) { if(!cur->nxt[s[j]-'a']) cur->nxt[s[j]-'a'] = new Trie(); cur = cur->nxt[s[j]-'a']; if(d[i][j]) cur->cnt++; } } int query(Trie* cur) { k -= cur->cnt; if(k<=0) return 1; for(int i = 0; i < 2; ++i) if(cur->nxt[i]&&query(cur->nxt[i])){ r[m++] = ('a'+i); return true; } return false; } int main() { memset(d,-1,sizeof d); scanf("%s%d",s,&k); n = strlen(s); for(int i = 0; i < n; ++i) for(int j = i; j < n; ++j) solve(i,j); for(int i = 0; i < n; ++i) build(i); query(&root); reverse(r,r+m); r[m++]='\0'; puts(r); return 0; } <file_sep>#include<bits/stdc++.h> #define fi first #define se second using namespace std; typedef pair<long double,int> di; di a[100005]; int n,x,y; long double PI=acos(-1.0),re; int main(){ cin>>n; for(int i=0;i<n;i++){ cin>>x>>y; if(y<0) a[i]=di(atan2(y,x)+2*PI,i+1); else a[i]=di(atan2(y,x),i+1); } sort(a,a+n); re=1000.0; for(int i=0;i<n-1;i++){ if((a[i+1].fi-a[i].fi)<re) re=a[i+1].fi-a[i].fi,x=a[i+1].se,y=a[i].se; } if(a[0].fi+2*PI-a[n-1].fi<re) x=a[0].se,y=a[n-1].se; cout<<x<<" "<<y<<endl; return 0; } <file_sep>#include <bits/stdc++.h> using namespace std; const int INF = 1000 * 1000 * 1000; int n,m; int g[105][105], cost; int dijkstra(int source){ vector<int > dist(105, INF); dist[source] = 0; set<pair<int, int > > q; q.insert(make_pair(0, source)); while(!q.empty()){ int current = q.begin()->second; int distance = q.begin()->first; q.erase(q.begin()); if(current == n-1) return distance; for(size_t i = 0; i < n; ++i) { if(g[current][i] + distance < dist[i]){ if(q.count(make_pair(dist[i], i))) q.erase(make_pair(dist[i], i)); dist[i] = g[current][i] + distance; q.insert(make_pair(dist[i], i)); } } } return dist[n-1]; } void dijkstrA(int source){ vector<int > dist(105, INF); dist[source] = 0; set<pair<int, int > > q; q.insert(make_pair(0, source)); while(!q.empty()){ int current = q.begin()->second; int distance = q.begin()->first; q.erase(q.begin()); for(size_t i = 0; i < n; ++i) { //cout << distance << " " << g[current][i] << " " << current << " " << i << endl, if(g[current][i] + distance > cost && i == n-1) g[current][i] = INF; if(g[current][i] + distance < dist[i]){ if(q.count(make_pair(dist[i], i))) q.erase(make_pair(dist[i], i)); dist[i] = g[current][i] + distance; q.insert(make_pair(dist[i], i)); } } } } int c[205][205]; int flow[205][205]; int bottleneck[205]; int pre[205]; void build() { for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { if(g[i][j] < INF) c[i*2+1][j * 2] = INF;//, cout << i << " " << j << endl; } } } int maxflow(){ int ans = 0; for(int i = 0; i <= 100; ++i) c[i*2][i*2+1] = 1; c[0][1] = INF; c[2*(n-1)][2*(n-1)+1] = INF; int S = 0, T = 2*(n-1)+1; while(1){ memset(bottleneck, 0, sizeof bottleneck); bottleneck[0] = INF; queue<int > q; q.push(0); while(!q.empty()&&!bottleneck[T]){ int cur = q.front(); q.pop(); for(int i = S; i <= T; i++){ if(!bottleneck[i]&&c[cur][i] > flow[cur][i]){ q.push(i); pre[i] = cur; bottleneck[i] = min(bottleneck[cur], c[cur][i] - flow[cur][i]); } } } if(bottleneck[T] == 0) break; for (int cur = T; cur != 0; cur = pre[cur]) { flow[pre[cur]][cur] += bottleneck[T]; flow[cur][pre[cur]] -= bottleneck[T]; } ans += bottleneck[T]; } return ans; } int eu[10005], ev[10005], ec[10005]; void build2() { for(int i = 1; i <= m; ++i) { if (g[0][eu[i]] + ec[i] + g[ev[i]][n-1] == g[0][n-1]) { c[eu[i]*2+1][ev[i]*2] = INF; //cout << eu[i] << ec[i] << ev[i] << endl; } if (g[0][ev[i]] + ec[i] + g[eu[i]][n-1] == g[0][n-1]) { c[ev[i]*2+1][eu[i]*2] = INF; //cout << ev[i] << ec[i] << eu[i] << endl; } } } int main() { scanf("%d%d",&n,&m); memset(g,0x3f,sizeof g); for(int i = 0; i <= 100; ++i) g[i][i] = 0; for(int i = 1,a,b,c; i <= m; ++i) { scanf("%d%d%d",&a,&b,&c); eu[i] = a; ev[i] = b; ec[i] = c; g[a][b] = min(c,g[a][b]); g[b][a] = min(c,g[b][a]); } for(int k = 0; k < n; ++k) for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) g[i][j] = min(g[i][j], g[i][k] + g[k][j]); //cout << g[0][n-1] << endl; build2(); /*cost = dijkstra(0); dijkstrA(0); build();*/ cost = maxflow(); if(cost == INF) cout << "IMPOSSIBLE" << endl; else cout << cost << endl; return 0; } /* 13 16 0 12 15 0 1 2 1 3 4 3 8 3 8 9 2 9 12 1 0 2 2 2 4 2 2 5 3 4 6 2 5 7 2 6 9 3 7 10 1 7 11 2 11 12 2 10 12 3 6 6 0 1 1 1 2 1 2 5 1 0 3 1 3 4 1 4 5 1 6 8 0 1 1 0 2 1 0 3 1 0 4 1 1 5 1 1 6 1 1 7 1 1 8 1 */ <file_sep>// dynamics of the profile int m, d[300][10]; void solve(int x, int y, int mask, int nextmask = 0){ if(x == n) return; if(y >= m) d[x + 1][nextmask] += d[x][mask]; else{ int mymask = (1 << y); if(mask & mymask) solve(x, y + 1, mask, nextmask); else{ if(y < m - 1 && !(mask & mymask) && !(mask & (mymask << 1))) solve(x, y + 2, mask | mymask | (mymask << 1), nextmask); solve(x, y + 1, mask | mymask, nextmask | mymask); } } }<file_sep>#include <bits/stdc++.h> #define mems(a,b) memset(a,b,sizeof(a)) #define IT iterator #define mp make_pair #define pb push_back #define eps 1E-9 #define all(a) a.begin(),a.end() #define allr(a) a.rbegin(),a.rend() #define MOD (1000000007) #define llInf (1LL<<62) #define iInf (2123456789) #define o(i, start, n) for(int i = start; i < n; i++) #define I3 (ll)1000 #define I4 (ll)10000 #define I5 (ll)100000 #define I6 (ll)1000000 #define I7 (ll)10000000 #define I8 (ll)100000000 #define I9 (ll)1000000000 #define I10 (ll)10000000000 #define I11 (ll)100000000000 #define I12 (ll)1000000000000 #define I13 (ll)10000000000000 #define I14 (ll)100000000000000 #define I15 (ll)1000000000000000 #define I16 (ll)10000000000000000 #define I17 (ll)100000000000000000 #define I18 (ll)1000000000000000000 using namespace std; typedef long long int ll; typedef unsigned long long ull; typedef double dd; typedef string str; typedef char ch; typedef int I; inline void _(){ ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); } void __(){ #ifndef ONLINE_JUDGE cout << endl << "time elsaped : " << (double)clock() / CLOCKS_PER_SEC << " ms" << endl; #endif } inline void ___(char *i, char *j){ freopen(i, "r", stdin); freopen(j, "w", stdout); } //input templates template<class T1> bool tk(T1 &e1){if(cin>>e1)return true;return false;} template<class T1,class T2> bool tk(T1 &e1,T2 &e2){if(cin>>e1>>e2)return true;return false;} template<class T1,class T2,class T3> bool tk(T1 &e1,T2 &e2,T3 &e3){if(cin>>e1>>e2>>e3)return true;return false;} template<class T1,class T2,class T3,class T4> bool tk(T1 &e1,T2 &e2,T3 &e3,T4 &e4){if(cin>>e1>>e2>>e3>>e4)return true;return false;} template<class T1,class T2,class T3,class T4,class T5> bool tk(T1 &e1,T2 &e2,T3 &e3,T4 &e4,T5 &e5){if(cin>>e1>>e2>>e3>>e4>>e5)return true;return false;} template<class T1,class T2,class T3,class T4,class T5, class T6> bool tk(T1 &e1,T2 &e2,T3 &e3,T4 &e4,T5 &e5,T6 &e6){if(cin>>e1>>e2>>e3>>e4>>e5>>e6)return true;return false;} // output templates template<class T1> void put(T1 e){cout<<e<<endl;} template<class T1,class T2> void put(T1 e1,T2 e2){cout<<e1<<" "<<e2<<endl;} template<class T1,class T2,class T3> void put(T1 e1,T2 e2,T3 e3){cout<<e1<<" "<<e2<<" "<<e3<<endl;} template<class T1,class T2,class T3,class T4> void put(T1 e1,T2 e2,T3 e3,T4 e4){cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<endl;} template<class T1,class T2,class T3,class T4,class T5> void put(T1 e1,T2 e2,T3 e3,T4 e4,T5 e5){cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<" "<<e5<<endl;} template<class T1,class T2,class T3,class T4,class T5,class T6> void put(T1 e1,T2 e2,T3 e3,T4 e4,T5 e5,T6 e6){cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<" "<<e5<<" "<<e6<<endl;} template<class T1> void putVec(vector<T1>e1){for(I i=0; i<(e1).size(); i++)(!i?cout<<e1[i]:cout<<" "<<e1[i]);cout<<endl;} template<class T1> void putArr(T1 arr[],I l){for(I i=0; i<l; i++)(!i?cout<<arr[i]:cout<<" "<<arr[i]);cout<<endl;} // end of output // bug templates template<class T1> void bug(T1 e){ #ifndef ONLINE_JUDGE cout<<e<<endl; #endif } template<class T1,class T2> void bug(T1 e1,T2 e2){ #ifndef ONLINE_JUDGE cout<<e1<<" "<<e2<<endl; #endif } template<class T1,class T2,class T3> void bug(T1 e1,T2 e2,T3 e3){ #ifndef ONLINE_JUDGE cout<<e1<<" "<<e2<<" "<<e3<<endl; #endif } template<class T1,class T2,class T3,class T4> void bug(T1 e1,T2 e2,T3 e3,T4 e4){ #ifndef ONLINE_JUDGE cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<endl; #endif } template<class T1,class T2,class T3,class T4,class T5> void bug(T1 e1,T2 e2,T3 e3,T4 e4,T5 e5){ #ifndef ONLINE_JUDGE cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<" "<<e5<<endl; #endif } template<class T1,class T2,class T3,class T4,class T5,class T6> void bug(T1 e1,T2 e2,T3 e3,T4 e4,T5 e5,T6 e6){ #ifndef ONLINE_JUDGE cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<" "<<e5<<" "<<e6<<endl; #endif } template<class T1> void bugVec(vector<T1>e1){ #ifndef ONLINE_JUDGE for(I i=0; i<(e1).size(); i++)(!i?cout<<e1[i]:cout<<" "<<e1[i]);cout<<endl; #endif } template<class T1> void bugArr(T1 arr[],I l){ #ifndef ONLINE_JUDGE for(I i=0; i<l; i++)(!i?cout<<arr[i]:cout<<" "<<arr[i]);cout<<endl; #endif } // end of bugs namespace gv{ }; long long absolute(long long a){ if(a < 0) return -a; return a; } int f[200005]; int main(){ _(); string s,t; tk(s,t); if(s.length() > t.length()) swap(s,t); size_t sz_s = s.length(), sz_t = t.length(); for(int i = 1, j; i < sz_s; i++){ j = f[i-1]; while(j>0&&s[i]!=s[j]) j = f[j-1]; j+=(s[i]==s[j])?1:0; f[i] = j; } size_t mtch = sz_s - f[sz_s - 1]; if(mtch / sz_s == 0 && sz_s % mtch != 0) mtch = sz_s; string m; for(size_t i = 0; i < mtch; i++){m+=s[i];} m+=t; size_t sz_us = m.length(); for(int i = 1, j; i < sz_us; i++){ j = f[i-1]; while(j>0&&m[i]!=m[j]) j = f[j-1]; j+=(m[i]==m[j])?1:0; f[i] = j; } bug(mtch,f[sz_us-1]); int cnt = 0; if(f[sz_us-1]==sz_t) for(int i = 1; i <= sz_s / mtch;i++){ if(sz_s % (mtch * i) == 0 && sz_t % (mtch * i) == 0) cnt++; } put(cnt); __(); } <file_sep>#include <iostream> #include <fstream> #include <cstdio> #include <iomanip> #include <sstream> #include <cstring> #include <string> #include <cmath> #include <stack> #include <list> #include <queue> #include <deque> #include <set> #include <map> #include <vector> #include <algorithm> #include <numeric> #include <utility> #include <functional> #include <limits> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<int,int> pii; typedef vector<vector<int> > graph; const double pi = acos(-1.0); #define oned(a, x1, x2) { cout << #a << ":"; for(int _i = (x1); _i < (x2); _i++){ cout << " " << a[_i]; } cout << endl; } #define twod(a, x1, x2, y1, y2) { cout << #a << ":" << endl; for(int _i = (x1); _i < (x2); _i++){ for(int _j = (y1); _j < (y2); _j++){ cout << (_j > y1 ? " " : "") << a[_i][_j]; } cout << endl; } } #define mp make_pair #define pb push_back #define fst first #define snd second const int MAXA = 26; const int MAXN = 5005; const int LOG = 15; int n, m, len; char a[2*MAXN], b[2*MAXN]; int group[LOG][2*MAXN]; int cnt[2*MAXN]; int sufArr[2*MAXN], tmp[2*MAXN]; int lcp(int i, int j) { int res = 0; for(int h = LOG-1; h >= 0; h--) { if((1<<h)<=len && group[h][i]==group[h][j]) { res += (1<<h); i = (i+(1<<h))%len; j = (j+(1<<h))%len; } } return res; } void solve() { n = strlen(a); m = strlen(b); a[n] = '#'; for(int i = 0; i < m; i++) { a[n+1+i] = b[i]; } a[n+m+1] = '@'; len = n+m+2; memset(cnt,0,sizeof(cnt)); for(int i = 0; i < len; i++) { cnt[(int)a[i]]++; } for(int i = 1; i < 2*MAXN; i++) { cnt[i] += cnt[i-1]; } for(int i = 0; i < len; i++) { sufArr[--cnt[(int)a[i]]] = i; group[0][i] = a[i]; } for(int h = 0; (1<<h)<len; h++) { for(int i = 0; i < len; i++) { tmp[i] = (len+sufArr[i]-(1<<h))%len; } memset(cnt,0,sizeof(cnt)); for(int i = 0; i < len; i++) { cnt[group[h][tmp[i]]]++; } for(int i = 1; i < 2*MAXN; i++) { cnt[i] += cnt[i-1]; } for(int i = len-1; i >= 0; i--) { sufArr[--cnt[group[h][tmp[i]]]] = tmp[i]; } int groups = 0; for(int i = 0; i < len; i++) { if(i>0) { int a = sufArr[i-1]; int b = sufArr[i]; if(group[h][a]!=group[h][b] || group[h][(a+(1<<h))%len]!=group[h][(b+(1<<h))%len]) { groups++; } } group[h+1][sufArr[i]] = groups; } } // for(int i = 0; i < len; i++) { // cout << (a+sufArr[i]) << endl; // if(i+1<len) cout << lcp(sufArr[i],sufArr[i+1]) << endl; // } int inf = 1000000000; int ans = inf; for(int i = 0; i+1 < len; i++) { int a = sufArr[i]; int b = sufArr[i+1]; if((a<n)!=(b<n)) { int x = (i?lcp(a,sufArr[i-1]):0); int y = (i+2<len?lcp(b,sufArr[i+2]):0); int z = lcp(a,b); int t = max(x,y); if(z > t && ans > t+1) { ans = t+1; } } } if(ans==inf) ans = -1; printf("%d\n", ans); } int main() { // freopen("input.in", "r", stdin); while(scanf("%s",a)==1) { scanf("%s",b); solve(); } }<file_sep>#define weight first #define from second.first #define to second.second void dsu_init(){ for(int i = 0; i < n; i++){ p[i] = i; } } int dsu_get(int a){ return a == p[a] ? a : (p[a] = dsu_get(p[a])); } int dsu_union(int a, int b){ a = dsu_get(a); b = dsu_get(b); if(a == b) return false; if(rand() & 1) swap(a, b); p[a] = b; return true; } int kruskal(){ dsu_init(); sort(G.begin(), G.end()); int ans = 0; for(size_t i = 0; i < g.size(); i++){ if(dsu_union(G[i].from, G[i].to)) ans += G[i].w; } return ans; }<file_sep>#include <bits/stdc++.h> using namespace std; const int m = 1000000007; int c[1001][1001]; int main() { for(int i = 0; i <= 1000; ++i) c[i][0] = 1; for(int i = 1; i <= 1000; ++i) for(int k = 1; k <= i; ++k) c[i][k] = (c[i-1][k] + c[i-1][k-1])%m; int n; cin >> n; int res = 1; int sum = 0; for(int i = 1,a; i <= n; ++i) cin>>a,res = 1LL*res*c[(sum+=a)-1][a-1]%m; cout << res << endl; }<file_sep>#include <cstdio> #include <vector> #include <algorithm> #include <queue> #include <cstdlib> #define INF 1E18 using namespace std; vector<pair<long long, bool> > dist; vector<bool > visited; int n, m, k, a, b; int c; vector<vector<pair<int , pair<long long, bool> > > > AdjList; int main(){ scanf("%d%d%d", &n, &m, &k); AdjList.clear(); AdjList.resize(n); for(int i = 0; i < m; i++){ scanf("%d%d%d", &a, &b, &c); AdjList[a - 1].push_back(make_pair(b - 1, make_pair(c, false))); AdjList[b - 1].push_back(make_pair(a - 1, make_pair(c, false))); } dist.assign(n, make_pair(INF, true)); for(int i = 0; i < k; i++){ scanf("%d%d", &a, &c); AdjList[0].push_back(make_pair(a - 1, make_pair(c, true))); } priority_queue<pair<long long, int >, vector<pair<long long, int > >, greater<pair<long long, int > > > pq; dist[0].first = 0; pq.push(make_pair(0, 0)); while(!pq.empty()){ int u = pq.top().second; long long we = pq.top().first; pq.pop(); if(we > dist[u].first) continue; for(size_t i = 0; i < AdjList[u].size(); i++){ long long w = AdjList[u][i].second.first; int v = AdjList[u][i].first; bool t = AdjList[u][i].second.second; if(dist[v].first > dist[u].first + w) dist[v].first = dist[u].first + w, dist[v].second = t, pq.push(make_pair(dist[v].first, v)); else if(dist[v].first == dist[u].first + w) dist[v].second = (dist[v].second == true)? t : false; } } for(int i = 1; i < n; i++){ if(dist[i].second) k--; } printf("%d\n", k); } <file_sep>#include<bits/stdc++.h> using namespace std; #define mxN (1005) string a,b,r; int n,m; pair<int,int>pre[mxN][mxN]; int dp[mxN][mxN]; int main() { memset(dp,0x3f,sizeof dp); cin>>a>>b; n = a.length(); m = b.length(); dp[0][0] = 0; for(int i = 1; i <= n; ++i) { for(int j = 1; j <= m; ++j) { if(a[i-1]==b[j-1]&&dp[i][j]>dp[i-1][j-1]) dp[i][j] = dp[i-1][j-1]; if(dp[i][j]>dp[i-1][j]+3) dp[i][j] = 3+dp[i-1][j]; if(dp[i][j]>dp[i][j-1]+4) dp[i][j] = 4+dp[i][j-1]; if(dp[i][j]>dp[i-1][j-1]+5) dp[i][j] = 5+dp[i-1][j-1]; } } cout<<dp[n][m]; } <file_sep>vector<vector<pair<int, int > > > GG; int dijkstra(int source, int dest){ int N = G.size(); vector<int > dist(N, INF); dist[source] = 0; set<pair<int, int > > q; q.insert(make_pair(0, source)); while(!q.empty()){ int current = q.begin()->second; int distance = q.begin()->first; for(size_t i = 0; i < GG[current].size(); ++i) { pair<int,int> node = GG[current][i]; if(node.second + distance < dist[node.first]){ if(q.find(make_pair(dist[node.first], node.first)) != q.end()) q.erase(make_pair(dist[node.first], node.first)); dist[node.first] = node.second + distance; q.insert(make_pair(dist[node.first], node.first)); } } } return dist[dest]; }<file_sep>#include<bits/stdc++.h> using namespace std; __int64 a,b,c,r; int main() { cin>>a>>b>>c; if(b<=0&&c>=0) r++; if(c<0&&b<0) r-=(b/a-(c+1)/a); else if(c>=0&&b<0) r+=(c/a-b/a); else if(c>0&&b>0) r+=(c/a-(b-1)/a); else r += c/a; cout<<r; } <file_sep>int tree[100000 << 3]; int lazy[100000 << 3]; #define segpara1(node,rl,rr) (node)<<1,(rl),(rl+rr)>>1 #define segpara2(node,rl,rr) ((node)<<1)|1,((rl+rr)>>1)+1,rr #define bad_value -INF void update(const int &node, const int &rl, const int &rr) { if(lazy[node] != 0) { // This node needs to be updated tree[node] += lazy[node]; // Update it if(rl != rr) { lazy[node<<1] += lazy[node]; // Mark child as lazy lazy[(node<<1)|1] += lazy[node]; // Mark child as lazy } lazy[node] = 0; // Reset it } } int merge_tree(const int &q1, const int &q2) { return max(q1,q2); } void build_tree(int node, int rl, int rr) { if(rl > rr) return; // Out of range if(rl == rr) { // Leaf node scanf("%d", &tree[node]); // Init value return; } build_tree(segpara1(node,rl,rr)); // Init left child build_tree(segpara2(node,rl,rr)); // Init right child tree[node] = merge_tree(tree[node<<1],tree[(node<<1)|1]); // Init root value } void update_tree(int node, int rl, int rr, const int &l, const int &r, const int &value) { update(node,rl,rr); if(rl > rr || rl > r || rr < l) // Current segment is not within range [i, j] return; if(rl >= l && rr <= r) { // Segment is fully within range lazy[node] += value; update(node,rl,rr); return; } update_tree(segpara1(node,rl,rr), l, r, value); // Updating left child update_tree(segpara2(node,rl,rr), l, r, value); // Updating right child tree[node] = merge_tree(tree[node<<1], tree[(node<<1)|1]); // Updating root with max value } int query_tree(int node, int rl, int rr, const int &l, const int &r) { if(rl > rr || rl > r || rr < l) // Current segment is not within range [i, j] return bad_value; update(node,rl,rr); if(rl >= l && rr <= r) {// Current segment is totally within range [i, j] return tree[node]; } int q1 = query_tree(segpara1(node,rl,rr), l, r); // Query left child int q2 = query_tree(segpara2(node,rl,rr), l, r); // Query right child int res = merge_tree(q1, q2); // Return final result return res; }<file_sep>// maximum bibartite matching #include <bits/stdc++.h> using namespace std ; typedef vector < int > vi ; vector < int > adj [211] ; int l [111] , r[111] ; vi owner ; //vi visited; int alternating_path ( int u ){ if( visited[u] )return 0; visited[u] = true ; for (int i = 0 ; i < adj[u].size() ; i++){ int v = adj[u][i] ; if( owner[v] == -1 || alternating_path(owner[v]) ){ owner[v] = u ; return 1 ; } } return 0 ; } int maxbibmatching(){ int n , m , i, j, k , u , v , test; scanf("%d", &test); for( int kase = 1 ; kase <= test ; kase++ ){ scanf("%d", &n) ; for ( i = 0 ; i < n ; i++) scanf("%d", l + i ) ; scanf("%d" , &m) ; for ( i = 0 ; i < m ; i++) scanf("%d" , r + i) ; for ( i = 0 ; i <= n+m ; i++) adj[i].clear() ; for ( i = 0 ; i < n ; i++){ u = l[i]; for ( j = 0 ; j < m ; j++){ v = r[j]; if ( u != 0 ){ if( v%u == 0 || v == 0) adj[i].push_back(j+n);} else if( v == 0 && u == 0) adj[i].push_back(j+n) ; } } int mcbm = 0 ; owner.assign(n+m+1,-1) ; for ( i = 0 ; i < n ; i++){ visited.assign(n+1,0) ; mcbm += alternating_path(i); } //printf("Case %d: %d\n",kase , mcbm) ; return mcbm; } }<file_sep>#include <bits/stdc++.h> using namespace std; int dp[35][35][55],t,n,m,k; int main() { memset(dp, 0x3f, sizeof dp); for(int i = 0; i <= 30; ++i) { for(int j = 0; j <= 30; ++j) { for(int k = 0; k <= 50; ++k) { if(i*j==k||k==0){ dp[i][j][k] = 0; continue; } for(int ic = 1; ic < i; ++ic) { for(int c = 0; c <= k; ++c) { dp[i][j][k] = min(dp[i][j][k], dp[ic][j][c] + dp[i-ic][j][k-c] + j * j); } } for(int jc = 1; jc < j; ++jc) { for(int c = 0; c <= k; ++c) { dp[i][j][k] = min(dp[i][j][k], dp[i][jc][c] + dp[i][j-jc][k-c] + i * i); } } } } } scanf("%d",&t); for (int i=0;i<t;i++) { scanf("%d%d%d",&n,&m,&k); printf("%d\n",dp[n][m][k]); } return 0; } <file_sep>#include<bits/stdc++.h> #define f first #define s second #define mp make_pair #define ll long long using namespace std; vector<pair<int,int> > a; vector<pair<int,int> > b; bool compr(pair<int, int> x, pair<int, int> y) { if(x.f == y.f) return x.s < y.s; return x.f < y.f; } ll coun; int aa [100005] , bb[100005]; vector<int> xx; void merge_sort(int x, int l , int h) { if(l==h) { if(x) { bb[l]=(xx[l]); } else { aa[l]=(xx[l]); } return ; } int mid = (l+h)/2; merge_sort((x^1), l , mid); merge_sort((x^1), mid+1 , h); int z = l ; int y = mid+1; vector<int> cc; int indx = z; while(z <= mid || y <= h) { if(x) { if( (y >h &&z<=mid) || (z <=mid && aa[z] <= aa[y]) ) { bb[indx]=aa[z]; z++; } else { bb[indx]=aa[y++]; coun+=(mid+1)-z; } } else if(!x) { if( (y >h &&z<=mid) || (z <=mid && bb[z] <= bb[y]) ) { aa[indx]=(bb[z]); z++; } else { aa[indx]=(bb[y++]); coun+=(mid+1)-z; } } indx++; } } int main() { freopen("john.in", "r", stdin); freopen("john.out", "w", stdout); int n; scanf("%d", &n); for(int i = 0; i < n; ++i) { int x , y; scanf("%d%d",&x,&y); a.push_back(mp(x,y)); b.push_back(mp(y,x)); } ll ans = LONG_LONG_MAX; sort(a.begin() , a.end() , compr); for(int i = 0 ; i < n ; i++) { aa[i]=bb[i]=a[i].s; xx.push_back(a[i].s); } coun = 0; merge_sort(0, 0 , n-1); ans = min(ans , coun); sort(b.begin() , b.end() , compr); for(int i = 0 ; i < n ; i++) { aa[i]=bb[i]=b[i].s; xx.push_back(b[i].s); } coun = 0; merge_sort(0, 0 , n-1); ans = min(ans , coun); cout << ans << endl; } <file_sep>#include<bits/stdc++.h> using namespace std; #define mxN 1005 int dp[mxN],a[mxN]; int main() { int n; scanf("%d", &n); for(int i = 0; i < n; ++i) { scanf("%d", a + i); dp[i] = 1; for(int j = 0; j < i; ++j) { dp[i] = max(dp[i],(a[i]>=a[j])*(1+dp[j])); } printf("%d\n", dp[i]); } } <file_sep>#include <bits/stdc++.h> using namespace std; double dp[101][101][101], pp, pr, ps; int main() { int r,s,p; cin >> r >> s >> p; dp[r][s][p] = 1; for(int i = r; i >= 0; --i) { for(int j = s; j >= 0; --j) { for(int k = p; k >= 0; --k) { if(!((i&&j)||(i&&k)||(j&&k))) continue; double pp = 1.0/(i*j+i*k+j*k); if(j) dp[i][j-1][k] += pp * (i*j) * dp[i][j][k]; if(i) dp[i-1][j][k] += pp * (i*k) * dp[i][j][k]; if(k) dp[i][j][k-1] += pp * (j*k) * dp[i][j][k]; } } } pp=pr=ps=0.0; for(int i = 1; i <= r; ++i) pr += dp[i][0][0]; for(int i = 1; i <= s; ++i) ps += dp[0][i][0]; for(int i = 1; i <= p; ++i) pp += dp[0][0][i]; cout << setprecision(12) << fixed << pr << " " << ps << " " << pp << endl; } <file_sep>int mzsm(){ int a[300][300]; int ans = 0; vector<int > d(m, -1), d1(m), d2(m); stack<int > st; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++) if(a[i][j] == 1) d[j] = i; while(!st.empty()) st.pop(); for(int j = 0; j < m; j++){ while(!st.empty() && d[st.top()] <= d[j]) st.pop(); d1[j] = st.empty() ? -1 : st.top(); st.push(j); } while(!st.empty()) st.pop(); for(int j = m - 1; j >= 0; j--){ while(!st.empty() && d[st.top()] <= d[j]) st.pop(); d2[j] = st.empty() ? m : st.top(); st.push(j); } for(int j = 0; j < m; j++){ cout << d[j] << " " << d2[j] << " " << d1[j] << endl; ans = max(ans, (i - d[j]) * (d2[j] - d1[j] - 1)); } } return ans; }<file_sep>#include<bits/stdc++.h> #define f first #define s second using namespace std; #define inf 500 * 1000 + 5 unordered_map<int,int> vv; int f1[500007]; int f2[500007]; vector<int > v; pair<int,int > a[100005], b[100005]; int qry1(int k){ int r = 0; for(;k<=inf;k+=(k&-k)) r+=f1[k]; return r; } int qry2(int k){ int r = 0; for(;k<=inf;k+=(k&-k)) r+=f2[k]; return r; } void upd1(int k){ for(;k;k-=(k&-k)) f1[k]++; } void upd2(int k){ for(;k;k-=(k&-k)) f2[k]++; } int main() { freopen("john.in", "r", stdin); freopen("john.out", "w", stdout); int n,id=0; scanf("%d", &n); for(int i = 0; i < n; ++i) { scanf("%d%d",&a[i].f,&a[i].s); v.push_back(a[i].f); v.push_back(a[i].s); } sort(v.begin(),v.end()); for(int i = 0; i < (int)v.size(); ++i) if(!i || v[i] != v[i-1]) vv[v[i]] = ++id; for(int i = 0; i < n; ++i) a[i].f = vv[a[i].f], a[i].s = vv[a[i].s], b[i].s = a[i].f, b[i].f = a[i].s;; sort(a,a+n); sort(b,b+n); long long A = 0, B = 0; for(int i = 0; i < n; ++i) A += qry1(a[i].s+1), upd1(a[i].s); for(int i = 0; i < n; ++i) B += qry2(b[i].s+1), upd2(b[i].s); cout << min(A,B) << endl; } <file_sep>bool bipCheck(){ vi d(V, INF); queue<int > q; d[s] = 0; q.push(s); while(!q.empty()){ int u = q.front(); q.pop(); for(int j = 0; j < (int)AdjList[u].size(); j++){ ii v = AdjList[u][j]; if(d[v.first] == INF){ d[v.first] = 1 - d[u]; q.push(v.first); }else if(d[v.first] == d[u]){ return false; } } } return true; }<file_sep>class trie { trie* child[26]; bool isLeaf; public: trie() { memset(child , 0 , sizeof(child)); isLeaf = false; }; void ins(const char* str) { if(*str == '\0') isLeaf = true; else { int p = *str - 'a'; if(!child[p]) child[p] = new trie(); isLeaf = false; child[p] -> ins(str + 1); } } int exist(const char* str) { if(*str == '\0') return 0; int p = *str - 'a'; if(!child[p]) return 0; return child[p] -> exist(str + 1) + 1; } };<file_sep>vector <pair <int , pair <int , int> > > edges; long long N; int parent[1000050]; int Rank[1000050]; int Find(int i) { if(parent[i] == i) return i; return parent[i] = Find(parent[i]); } bool UNION(int i , int j) { int pi = Find(i); int pj = Find(j); if(pi == pj) return false; if(Rank[pi] < Rank[pj]) parent[pi] = pj; else if(Rank[pi] > Rank[pj]) parent[pj] = pi; else { parent[pj] = pi; ++Rank[pi]; } return true; } long long kuruskal() { for(int i = 0;i < N + 2;++i) parent[i] = i , Rank[i] = 0; long long cost = 0; int selected = 0; for(long long i = 0;i < edges.size();++i) { if(selected == N - 1) break; if(UNION((edges[i].second).first , (edges[i].second).second)) { ++selected; cost += edges[i].first; } } }<file_sep>// matrix fast exponentiation typedef vector<vector<int > > matrix; matrix mul(matrix a, matrix b){ matrix ret(a.size(), vector<int >(a.size())); size_t sz = a.size(); for(size_t i = 0; i < sz; i++){ for(size_t j = 0; j < sz; j++){ for(size_t k = 0; k < sz; k++){ ret[i][j] = (ret[i][j] + a[i][k] * b[k][j]); } } } return ret; } matrix FE(matrix A, int p){ matrix res(2,vector<int > (2,1)); while(p) { if(p & 1) { res = mul(res , A); } A = mul( A , A ); p >>= 1; } return res; }<file_sep>#include <bits/stdc++.h> using namespace std; map<int, int > f; map<int, int > fenwick2; int query2(int k) { int ret = 0; for(;k;k-=(k&-k)) ret += fenwick2[k]; return ret; } void update2(int k) { for(;k<=1000000100;k+=(k&-k)) fenwick2[k]++; } int main() { map<int, int > mp; int n; scanf("%d", &n); for(int i = 0,a,b,c,d; i < n; ++i) { scanf("%d%d", &a, &b); c = (mp[a] == 0 ? a : mp[a]); d = (mp[b] == 0 ? b : mp[b]); mp[b] = c; mp[a] = d; } long long ans = 0; int prev = 0; for(auto it = mp.begin(); it != mp.end(); ++it) { f[it->first]=++prev; ans += query2(1000000000) - query2(it->second); update2(it->second); } for(auto it = mp.begin(); it != mp.end(); ++it) { //if(it->second>=it->first) ans += abs(it->second-it->first) - abs(f[it->second]-f[it->first]); //cout << ans << endl; } cout << ans << endl; } <file_sep>#include<bits/stdc++.h> using namespace std; #define mxn 100005 __int64 f[11][mxn]; int n,k,v; inline void upd(int m,int k,__int64 v){for(;k<mxn;k+=k&-k)f[m][k]+=v;} inline __int64 qry(int m,int k){__int64 r = 0; for(;k;k-=k&-k) r+=f[m][k]; return r;} int main() { scanf("%d%d",&n,&k); for(;n--;) { scanf("%u",&v); for(int i = k; i; --i) upd(i,v,qry(i-1,v)); upd(0,v,1); } cout<<qry(k,mxn^1); return 0; } <file_sep>int V,s; //number of vertices, source void bfs(){ vi d(V, INF); queue<int > q; d[s] = 0; q.push(s); while(!q.empty()){ int u = q.front(); q.pop(); for(int j = 0; j < (int)AdjList[u].size(); j++){ ii v = AdjList[u][j]; if(d[v.first] == INF) d[v.first] = d[u] + 1; q.push(v.first); } } }<file_sep>#include<bits/stdc++.h> using namespace std; vector<int > g[80000]; int out_in[80000],s,e; string r,t; void euler(int v) { while(g[v].size()) { int u = g[v].back(); g[v].pop_back(); euler(u); } r += v%256; } int main() { int n; scanf("%d",&n); for(int i = 0; i < n; ++i) { cin>>t; s=t[0]*256+t[1]; e=t[1]*256+t[2]; g[s].push_back(e); out_in[s]++; out_in[e]--; } s=e=-1; for(int i = 0; i < 70000; ++i) { if(out_in[i]>0) e++,s=i; } if(e>0||out_in[s]>1) puts("NO"),exit(0); if(s==-1) { for(int i = 0; i < 70000; ++i) if(g[i].size()) s = i; } euler(s); r += s/256; if(r.length() == n+2) cout<<"YES"<<endl<<string(r.rbegin(),r.rend())<<endl; else cout << "NO"; } <file_sep>#include<bits/stdc++.h> using namespace std; vector<pair<int,int > > seg; int cur_end = -1, r = 0; int main() { int n; scanf("%d", &n); for(int i = 0, a, b; i < n; ++i) { scanf("%d%d", &a, &b); seg.push_back({b,a}); } sort(seg.begin(),seg.end()); for(int i = 0; i < n; ++i) { if(seg[i].second > cur_end) r++,cur_end=seg[i].first; } cout<<r; } <file_sep>int FE(int A, int p, int mod){ int res = 1; while(p) { if(p & 1) { res = ((1LL) * res * A) % mod; } A = ((1LL) * A * A) % mod; p >>= 1; } return res; }<file_sep>vector<pair<int, int > > aa; void dfs3(int current, int parent = -1){ visited[current] = true; tin[current] = fup[current] = timer++; for(size_t i = 0; i < g[current].size(); ++i){ int node = g[current][i]; if(node == parent) continue; if(visited[node]){ fup[current] = min(fup[current], tin[node]); }else{ dfs(node, current); fup[current] = min(fup[current], fup[node]); if(fup[node] > tin[current] && parent != -1) aa.push_back(make_pair(current, node)); } } }<file_sep>int longestIncreasingSub(){ vector<int > d(n + 1, INF); d[0] = -INF; int ans = 0; for (int i=0; i < n; i++) { int j = upper_bound(d.begin(), d.end(), a[i]) - d.begin(); if(d[j - 1] < a[i] && a[i] < d[j]) d[j] = a[i]; ans = max(ans, j); } return ans; }<file_sep>vi S, visited; void SCC(int u){ dfs_num[u] = dfs_num[u] = dfsNumberCounter++; visited[u] = 1; S.push_back(u); for(int j = 0; j < (int)AdjList[u].size(); j++){ ii v = AdjList[u][j]; if(dfs_num[v.first] == UNVISITED){ SCC(v.first); } if(visited[v.first]) dfs_low[u] = min(dfs_low[u], dfs_low[v.first]); } if(dfs_low[u] == dfs_num[u]){ // SCC // pop until getting u } }<file_sep>#include<bits/stdc++.h> using namespace std; long double a, b, c, d, l, r, mid; long double la, ra, lb, rb, lc, rc, ld, rd, lad, rad, lbc, rbc; int main() { cin >> a >> b >> c >> d; l = 0, r = 1e30; for (int i = 0;i < 100000;i++) { mid = (l + r) / 2; la = a - mid, ra = a + mid; lb = b - mid, rb = b + mid; lc = c - mid, rc = c + mid; ld = d - mid, rd = d + mid; lad = min(min(la*ld, la*rd), min(ra*ld, ra*rd)); rad = max(max(la*ld, la*rd), max(ra*ld, ra*rd)); lbc = min(min(lb*lc, lb*rc), min(rb*lc, rb*rc)); rbc = max(max(lb*lc, lb*rc), max(rb*lc, rb*rc)); if (rad < lbc || rbc < lad) l = mid; else r = mid; } cout << setprecision(12) << fixed << l << endl; }<file_sep>#include <bits/stdc++.h> using namespace std; vector<vector<int > > v(1000005); vector<pair<int, int > > t; int main(){ int n, m,a,b; scanf("%d%d", &n, &m); for(int i = 0; i < m; i++){ scanf("%d%d", &a, &b); v[a].push_back(b); v[b].push_back(a); } for(int i = 1; i <= n; i++){ int h1=0,h2=0, h3=0,h4=0; v[i].push_back(i); sort(v[i].begin(),v[i].end()); for(int ii = 0; ii < (int)v[i].size(); ii++){ h1 = 1000000007*h1+v[i][ii]; h2 = 1000000009*h2+v[i][ii]; if(v[i][ii] != i) h3 = 1000000007*h4+v[i][ii], h4 = 1000000009*h3+v[i][ii]; } t.push_back(make_pair(h1,h2)); t.push_back(make_pair(h3,h4)); } sort(t.begin(),t.end()); long long ans = 0; int cnt = 1; for(size_t i = 1; i < t.size(); i++){ if(t[i].first == t[i-1].first && t[i].second == t[i-1].second) cnt++; else ans += ((long long)cnt * (cnt - 1)) / 2, cnt = 1; } ans += ((long long)cnt * (cnt - 1) / 2); cout << ans << endl; } <file_sep>#include <bits/stdc++.h> using namespace std; int main(){ #ifndef ONLINE_JUDGE freopen("i.in", "r", stdin); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); map<int, long long > gcds, perElement, overAll; int n, m; cin >> n; int a; for(int i = 0; i < n; i++){ cin >> a; gcds[a]++; // gcd with itself perElement.clear(); for(map<int, long long >::iterator it = gcds.begin(); it != gcds.end(); it++) perElement[__gcd(a, it->first)] += it->second, overAll[__gcd(a, it->first)] += it->second; // number of all ways to get here so far gcds = perElement; // new state } cin >> m; for(int i = 0; i < m; i++) cin >> a, cout << overAll[a] << endl; } <file_sep>#include<bits/stdc++.h> using namespace std; #define mxn 305 // capacity int c[mxn][mxn]; // flows int flow[mxn][mxn]; // the max to provide int bottleneck[mxn]; // parents in bfs int pre[mxn]; int tc, n,m,S,T; void maxflow(){ cin >> tc; for(int tcc = 1; tcc <= tc; tcc++){ memset(c,0,sizeof c); memset(flow,0,sizeof flow); cin >> n >> m; // S source , T destination int ans = 0; while(1){ memset(bottleneck, 0, sizeof bottleneck); bottleneck[S] = 999999; queue<int > q; q.push(S); while(!q.empty()&&!bottleneck[T]){ int cur = q.front(); q.pop(); for(int i = 1; i <= T; i++){ if(!bottleneck[i]&&c[cur][i] > flow[cur][i]){ q.push(i); pre[i] = cur; bottleneck[i] = min(bottleneck[cur], c[cur][i] - flow[cur][i]); } } } if(bottleneck[T] == 0) break; for (int cur = T; cur != S; cur = pre[cur]) { flow[pre[cur]][cur] += bottleneck[T]; flow[cur][pre[cur]] -= bottleneck[T]; } ans += bottleneck[T]; } cout << "Case " << "#" << tcc << ": " << ans << endl; } } int main() { maxflow(); } <file_sep>#include <bits/stdc++.h> using namespace std; void execute(){ long long a[3]; cin >> a[0] >> a[1] >> a[2]; sort(a, a + 3); cout << min(a[0] + a[1], (a[0] + a[1] + a[2]) / 3) << endl; } int main() { #ifndef ONLINE_JUDGE freopen("i.in", "r", stdin); while(cin){ #endif ios_base::sync_with_stdio(NULL), cin.tie(NULL), cout.tie(NULL); execute(); #ifndef ONLINE_JUDGE } cout << endl << "time :: " << (double)clock() / CLOCKS_PER_SEC << " ms" << endl; #endif } <file_sep>#include<bits/stdc++.h> using namespace std; #define mxN (1005) int a[mxN]; int dp[mxN][mxN], n; int main() { scanf("%d", &n); for(int i = 0; i < n; ++i) { scanf("%d", a + i); } for (int l = 2; l < n; l++) { for (int i = 0, j = i + l; i < n-l; i++, j = i + l) { dp[i][j] = INT_MAX; for (int k = i + 1; k < j; k++) { int q = dp[i][k] + dp[k][j] + (a[i] + k - i) * a[k] * (a[j] + j - k); cout << i << " " << j << " " << k << " " << l << " " << q << endl; if (q < dp[i][j]) dp[i][j] = q; } } } cout << dp[0][n-1]; } <file_sep>long long inv[max_n]; void compute_inverses(int mod) { inv[1] = 1; for (int i = 2; i < max_n; ++i) inv[i] = inv[mod % i] * (mod - mod / i) % mod; } long long get_inverse(long long num, int mod) { long long inv = 1; for (int i = mod - 2; i != 0; i >>= 1) { if ((i & 1) == 1) inv = inv * num % mod; num = num * num % mod; } return inv; } <file_sep>#include<bits/stdc++.h> using namespace std; const int mxn = 500005; int n,D=1000,q,query,a,b; pair<__int64,int> p[mxn]; __int64 v[mxn],lazy[mxn],x; inline void init() { scanf("%d%d",&n,&q); for(int i = 1; i <= n; ++i) { scanf("%I64d",&v[i]); p[i] = {v[i],i}; } for(int l = 1; l <= n; l += D) { sort(p+l,p+min(n+1,l+D)); } } int main() { init(); for(int qq = 0; qq < q; ++qq) { scanf("%d",&query); if(query == 1) { scanf("%d%d%I64d",&a,&b,&x); for(int l = 1, t = 1; l <= n; l += D, ++t) { int r = min(n,l+D-1); if(r<a||b<l) continue; if(a<=l&&r<=b) { lazy[t]+=x; continue; } for(int i = l; i <= r; ++i) { if(a<=i&&i<=b) v[i]+=x; p[i]={v[i],i}; } sort(p+l,p+r+1); } } else { scanf("%I64d",&x); int lb = n, ub = 0; for(int l = 1, t = 1; l <= n; l += D, ++t) { int r = min(n+1,l+D); int v1 = lower_bound(p+l,p+r,make_pair(x-lazy[t],-1)) - p; int v2 = lower_bound(p+l,p+r,make_pair(x-lazy[t]+1,-1)) - p - 1; if(v1<=v2) lb=min(lb,p[v1].second),ub=max(ub,p[v2].second); } if(lb>ub) lb=1,ub=0; printf("%d\n",ub-lb); } } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; #define EPS 1E-9 struct point{ int x, y; }; bool check(vector<double > d){ for(size_t i = 0; i < 4; i++){ // cout << d[i] << " "; for(size_t j = i + 1; j < 4; j++){ if(d[i] < EPS || fabs(d[i] - d[j]) > EPS) return false; } } if(fabs(d[4] - d[5]) > EPS) return false; return true; } int main(){ /* #ifndef ONLINE_JUDGE freopen("i.in", "r", stdin); #endif */ ios_base::sync_with_stdio(false); cin.tie(NULL); int tc; cin >> tc; while(tc--){ int res = 1000000007; point c[4], h[4]; for(int i = 0; i < 4; i++) cin >> c[i].x >> c[i].y >> h[i].x >> h[i].y; point rotate[4][4]; for(int i = 0; i < 4; i++){ rotate[i][0] = c[i]; for(int j = 1; j < 4; j++){ rotate[i][j].x = (c[i].x -= h[i].x), rotate[i][j].y = (c[i].y -= h[i].y); c[i].y = - c[i].y, swap(c[i].x, c[i].y); c[i].x = c[i].x + h[i].x, c[i].y = c[i].y + h[i].y; rotate[i][j] = c[i]; // cout << rotate[i][j].x << " " << rotate[i][j].y << endl; } } for(int i = 0; i < 4; i++) for(int j = 0; j < 4; j++) for(int k = 0; k < 4; k++) for(int l = 0; l < 4; l++){ point p[4]; p[0] = rotate[0][i], p[1] = rotate[1][j], p[2] = rotate[2][k], p[3] = rotate[3][l]; vector<double > dig; for(int m = 0; m < 4; m++) for(int n = m + 1; n < 4; n++){ dig.push_back(sqrt((p[m].x - p[n].x) * (p[m].x - p[n].x) + (p[m].y - p[n].y) * (p[m].y - p[n].y))); } sort(dig.begin(), dig.end()); if(check(dig)) res = min(res, i + j + k + l); } cout << (res == 1000000007 ? -1 : res) << endl; } } <file_sep>#include<bits/stdc++.h> using namespace std; int n,m,t,cnt,v[1005][1005],sol[1005][1005]; char s[1005][1005]; int flood(int x, int y) { if(s[x][y]==0) return 0; if(s[x][y] == '*') return 1; if(v[x][y]) return 0; v[x][y] = cnt; int ret = 0; ret += flood(x+1,y); ret += flood(x-1,y); ret += flood(x,y+1); ret += flood(x,y-1); return ret; } void fil(int x, int y, int cur) { if(s[x][y]==0) return; if(s[x][y] == '*') return; if(v[x][y] != cnt) return; v[x][y] = 0x7fffffff; sol[x][y] = cur; fil(x+1,y,cur); fil(x-1,y,cur); fil(x,y+1,cur); fil(x,y-1,cur); } int main() { scanf("%d%d%d", &n, &m, &t); for(int i = 1; i <= n; ++i) { scanf("%s", s[i]+1); } for(int i = 0; i < t; ++i) { int a,b; scanf("%d%d", &a, &b); if(sol[a][b]) printf("%d\n", sol[a][b]); else { cnt++; int cur = flood(a,b); fil(a,b,cur); cout<<cur<<endl; } } } <file_sep>#include<stdio.h> #include<math.h> #include<algorithm> struct Point{ int x,y; }p[3000],co[3000]; int n,m,ch[10],N,ans[10],max; bool cmp(Point a,Point b){ if(a.x==b.x) return a.y<b.y; else return a.x<b.x; } double cross(Point o,Point a,Point b){ return (a.x-o.x)*(b.y-o.y)-(a.y-o.y)*(b.x-o.x); } void convex(){ std::sort(p+1,p+n+1,cmp); int i,t; m=0; for(i=1;i<=n;i++){ while(m>=2&&cross(co[m-2],co[m-1],p[i])<=0) m--; co[m]=p[i]; m++; } for(i=n-1,t=m+1;i>=1;i--){ while(m>=t&&cross(co[m-2],co[m-1],p[i])<=0) m--; co[m]=p[i]; m++; } return; } void tru(){ int norm=0,x=0,y=0,to; for(int k=1;k<=N;k++){ norm+=(co[ch[k]].x*co[ch[k]].x+co[ch[k]].y*co[ch[k]].y); x+=co[ch[k]].x; y+=co[ch[k]].y; } to=N*norm-(x*x+y*y); if(to>max){ max=to; for(int k=1;k<=N;k++){ ans[k]=ch[k]; } } return; } void dfs(int x,int y){ if(x==N+1){ tru(); return; } x++; for(int k=y;k<m-1;k++){ ch[x]=k; dfs(x,k); } return; } int main(){ int k,i,r; scanf("%d%d",&N,&r); if(N%2==0){ printf("%d\n",N*N*r*r); for(k=1;k<=N;k++){ if(k<=N/2) printf("%d %d\n",r,0); else printf("%d %d\n",-r,0); } return 0; } for(k=-r;k<=r;k++){ for(i=-r;i<=r;i++){ if(k*k+i*i<=r*r){ n++; p[n].x=k; p[n].y=i; } } } convex(); dfs(0,0); printf("%d\n",max); for(k=1;k<=N;k++) printf("%d %d\n",co[ans[k]].x,co[ans[k]].y); }<file_sep>#include<bits/stdc++.h> #define N (1<<17) #define H 18 using namespace std; int n,m,p[N][H],d[N],sz[N],x,y; vector<int> g[N]; void dfs(int u) { sz[u]=1; for(int v: g[u]) if(p[u][0]!=v) { p[v][0]=u,d[v]=d[u]+1; for(int i = 1; i < H; ++i) p[v][i] = p[p[v][i-1]][i-1]; dfs(v),sz[u]+=sz[v]; } } int get(int x, int d) { for(int i = 0; i < H; ++i) if(d&(1<<i)) x=p[x][i]; return x; } int lca(int x, int y) { x=get(x,d[x]-d[y]); if(x==y) return x; for(int i = H-1; i >= 0; --i) if(p[x][i]!=p[y][i]) x=p[x][i],y=p[y][i]; return p[x][0]; } int main() { scanf("%d",&n); for(int i = 1; i < n; ++i) { scanf("%d%d",&x,&y); g[x].push_back(y),g[y].push_back(x); } for(int i = 0; i < H; ++i) p[1][i]=1; dfs(1); scanf("%d",&m); for(;m--;) { scanf("%d%d",&x,&y); if(d[x]<d[y]) swap(x,y); if(x==y){ printf("%d\n",n); continue; } int z = lca(x,y); int td = d[x]+d[y]-2*d[z]; if(td&1){ puts("0"); continue; } td/=2; int u = get(x,td); if(u==z) { x=get(x,td-1); y=get(y,td-1); printf("%d\n",n-sz[x]-sz[y]); } else { z=get(x,td-1); printf("%d\n",sz[u]-sz[z]); } } }<file_sep>#include<bits/stdc++.h> #define mxn 100005 using namespace std; int n,d,f[2][mxn],dp[mxn],nx[mxn],cu; __int64 h[mxn],t[mxn]; inline void go(int cu){ if(cu) go(nx[cu]); else return; printf("%d ",cu); } inline void add(int k, int x){ int t = 0; if(k < 0) t++,k+=n+1; for(;k<mxn;k+=k&-k) if(dp[x]>dp[f[t][k]]) f[t][k]=x; } inline int qry(int k){ int r = 0, t = 0; if(k < 0) t++,k+=n+1; for(;k;k-=k&-k) if(dp[r]<dp[f[t][k]]) r = f[t][k]; return r; } int main() { scanf("%d%d",&n,&d); for(int i = 1; i <= n; ++i) { scanf("%I64d",h+i); t[i]=h[i]; } sort(t+1,t+n+1); for(int i = 1; i <= n; ++i) { int x0 = lower_bound(t+1,t+n+1,h[i]) - t; int x1 = upper_bound(t+1,t+n+1,h[i]-d) - t - 1; int x2 = t - lower_bound(t+1,t+n+1,h[i]+d); int q1 = qry(x1); int q2 = qry(x2); //cout<<q1 << " " << q2 << endl; if(!dp[q1]&&!dp[q2]) dp[i]=1; else if(dp[q1]>dp[q2]) dp[i]=dp[q1]+1,nx[i]=q1; else dp[i]=dp[q2]+1,nx[i]=q2; add(x0,i); add(-x0,i); if(dp[i]>dp[cu]) cu=i; } printf("%d\n",dp[cu]); go(cu); } <file_sep>#include<bits/stdc++.h> using namespace std; #define mxN (1005) string a,b,r; int n,m; pair<int,int>pre[mxN][mxN]; int dp[mxN][mxN]; int main() { cin>>a>>b; n = a.length(); m = b.length(); for(int i = 1; i <= n; ++i) { for(int j = 1; j <= m; ++j) { if(dp[i][j]<dp[i-1][j]) dp[i][j] = dp[i-1][j],pre[i][j]=pre[i-1][j]; if(dp[i][j]<dp[i][j-1]) dp[i][j] = dp[i][j-1],pre[i][j]=pre[i][j-1]; if(a[i-1]==b[j-1]&&dp[i][j]<=dp[i-1][j-1]) dp[i][j] = 1 + dp[i-1][j-1],pre[i][j]={i,j}; } } int i = n, j = m; for(; i >= 0 && j >= 0;--i,--j) { int k = i; int l = j; pair<int,int> nxt = pre[i][j]; i = nxt.first; j = nxt.second; while(k>i) r+=a[--k]; while(l>j) r+=b[--l]; if(i) r+=a[i-1]; } reverse(r.begin(),r.end()); cout << r << endl; } <file_sep>vector<vector<int > > g; vector<int > a; vector<int > tin, fup; int timer; void dfs(int current, int parent = -1){ visited[current] = true; tin[current] = fup[current] = timer++; int children = 0; for(size_t i = 0; i < g[current].size(); ++i){ int node = g[current][i]; if(node == parent) continue; if(visited[node]){ fup[current] = min(fup[current], tin[node]); }else{ dfs(node, current); fup[current] = min(fup[current], fup[node]); if(fup[node] >= tin[current] && parent != -1) a.push_back(current); children++; } } if(parent == -1 && children > 1) a.push_back(current); }<file_sep>#include<bits/stdc++.h> #define MAX 10000007 using namespace std; long long opt[MAX][2], tot, foe[MAX]; void build(long long x){ int p = 0; for(int i = 40; i--;){ if(!opt[p][x >> i & 1]) opt[p][x >> i & 1] = ++tot; p = opt[p][x >> i & 1]; } } long long query(long long x){ long long ret = 0, p = 0; for(int i = 40; i--;) if(opt[p][~x >> i & 1]) ret += (long long)1 << i, p = opt[p][~x >> i & 1]; else p = opt[p][x >> i & 1]; return ret; } int main(){ int n; cin >> n; long long ans = 0, w = 0; build(w); for(int i = 0; i < n; i++) cin >> foe[i],w ^= foe[i], build(w); build(w); for(int i = 0; i < n; i++) ans = max(ans, query(w ^= foe[i])); cout << ans << endl; }<file_sep>#include<bits/stdc++.h> using namespace std; __int64 inf = 4e18 + 1000; multiset<pair<int,int > > s1,s2; __int64 ans = inf; void solve(int k, int c) { if(k == 0) { ans=min(((max((s1.rbegin()->first - s1.begin()->first),1) + 1) / 2) * 1LL * ((max((s2.rbegin()->first - s2.begin()->first),1) + 1) / 2),ans); return; } pair<int,int > p1; pair<int,int > p2; if(c == 0) p1 = *s1.begin(),p2=p1,swap(p2.first,p2.second); if(c == 1) p1 = *s1.rbegin(),p2=p1,swap(p2.first,p2.second); if(c == 2) p2 = *s2.begin(),p1=p2,swap(p1.first,p1.second); if(c == 3) p2 = *s2.rbegin(),p1=p2,swap(p1.first,p1.second); s1.erase(s1.find(p1)); s2.erase(s2.find(p2)); for(int i = 0; i < 4; ++i) { solve(k-1,i); } s1.insert(p1); s2.insert(p2); } void scan() { int n,k; scanf("%d%d",&n,&k); for(int i = 0 , x1 , y1 , x2 , y2; i < n; ++i) { scanf("%d%d%d%d",&x1,&y1,&x2,&y2); s1.insert({x1+x2,y1+y2}); s2.insert({y1+y2,x1+x2}); } for(int i = 0; i < 4; ++i) { solve(k,i); } } void out() { cout<<ans; } int main() { scan(); out(); } <file_sep>string pp, ss; vector<int > matches; vector<int > failure; void kmpF() { int N = ss.size(); failure.resize(N+1); int pos = failure[0] = failure[N] = -1; for(int i = 1; i <= (int)ss.size(); i++){ while(pos != -1 && ss[pos] != ss[i - 1]) pos = failure[pos]; failure[i] = ++pos; } } void kmp(){ int N = pp.size(); failure.resize(N+1); int pos = failure[0] = failure[N] = -1; for(int i = 1; i <= (int)pp.size(); i++){ while(pos != -1 && pp[pos] != pp[i - 1]) pos = failure[pos]; failure[i] = ++pos; } int sp = 0, tp = 0; while(tp < (int)ss.size()){ while(sp != -1 && (sp == (int)pp.size() || pp[sp] != ss[tp])) sp = failure[sp]; tp++, sp++; if(sp == (int)pp.size()) matches.push_back(tp - pp.size()); } } vector<int > h1; vector<int > h2; vector<int > p1; vector<int > p2; void double_hash() { int N = ss.size(); h1.resize(N+1); h2.resize(N+1); p1.resize(N+1); p2.resize(N+1); int pw1 = 999907; int pw2 = 999917; p1[0] = 1; p2[0] = 1; h1[0] = 0; h2[0] = 0; for(int i = 0; i < N; ++i) { h1[i+1] = ((1LL) * p1[i] * (ss[i]-'a'+1) + h1[i]) % MOD; h2[i+1] = ((1LL) * p2[i] * (ss[i]-'a'+1) + h2[i]) % MOD; p1[i+1] = ((1LL) * p1[i] * pw1) % MOD; p2[i+1] = ((1LL) * p2[i] * pw2) % MOD; } } void testKmpHash() { for(int i = 0; i < 2000000; ++i) { ss += ((char)(rand() % 26) + 'a'); } double_hash(); int H1 = 0; int H2 = 0; pp = "ahmed"; for(size_t i = 0; i < pp.size(); ++i) { H1 = (1LL * (pp[i]-'a'+1) * p1[i] + H1) % MOD; H2 = (1LL * (pp[i]-'a'+1) * p2[i] + H2) % MOD; } for(size_t i = 0; i <= ss.size() - pp.size(); ++i) { int patternH1 = (((1LL) * H1 * p1[i]) % MOD); int patternH2 = (((1LL) * H2 * p2[i]) % MOD); int textH1 = (h1[i+pp.size()] - h1[i] + MOD) % MOD; int textH2 = (h2[i+pp.size()] - h2[i] + MOD) % MOD; if(textH1 == patternH1 && textH2 == patternH2) { cout << i << endl; } } kmp(); for(size_t i = 0; i < matches.size(); ++i) { printf("%d\n", matches[i]); } cout << (double )clock() / CLOCKS_PER_SEC << endl; }<file_sep>// Matrix Traversal int dr[] = {1,1,0,-1,-1,-1,0,1}; int dc[] = {0,1,1,1,0,-1,-1,-1}; int dx[] = {1,0,-1,0}; int dy[] = {0,1,0,-1}; inline bool boundCheck(int& nx,int& ny,int& R,int& C){ return (nx < R && ny < C && nx >= 0 && ny >= 0); }<file_sep>#include<bits/stdc++.h> #define mxn 5005 using namespace std; char s[mxn],p[mxn]; int longest_common_s[mxn],longest_common_p[mxn],prefix[mxn],ans=mxn; inline void process(const char s[], const char p[], int arr[], bool operate) { memset(prefix,0,sizeof prefix); int szs = strlen(s); int szp = strlen(p); for(int i = szs-1; i >= 0; --i) { for(int j = 0; j < szp; ++j) { if(s[i]==p[j]&&(i!=j||operate)) { prefix[j]=prefix[j+1]+1; if(!operate) arr[j]=max(arr[j],prefix[j]); if(operate&&prefix[j]>longest_common_p[j]&&prefix[j]>longest_common_s[i]) ans = min(ans,1+max(longest_common_p[j],longest_common_s[i])); } else prefix[j]=0; } } } int main() { scanf("%s%s",s,p); process(s,s,longest_common_s,0); process(p,p,longest_common_p,0); process(s,p,longest_common_p,1); cout<<(ans==mxn?-1:ans); } <file_sep>// strongly connected components vector<int > CC; void dfs1(int current){ for(size_t i = 0; i < g[current].size(); ++i) { int node = g[current][i]; if(!v[node]){ v[node] = true; dfs1(node); } } top.push_back(current); } void dfs2(int current){ for(size_t i = 0; i < g[current].size(); ++i) { int node = g[current][i]; if(!v[node]){ v[node] = true; dfs6(node); } } CC.push_back(current); } /* dfs1 then dfs2 for top reversed for component C will contain it */<file_sep>int CO[300][300]; void comb(){ for(int i = 0; i < n; i++){ CO[i][0] = CO[i][i] = 1; for(int k = 1; k < i; k++){ CO[i][k] = CO[i - 1][k - 1] + CO[i - 1][k]; cout << i << " " << k << " " << CO[i][k] << endl; } } }<file_sep>#include <bits/stdc++.h> using namespace std; int d[5005][5005]; vector<vector<int > > g(5005); int main() { memset(d,-1,sizeof d); int n,m; cin >> n >> m; for(int j = 0,a,b; j < m; ++j) { cin >> a >> b; a--,b--; g[a].push_back(b); g[b].push_back(a); } for(int i = 0; i < n; ++i) { queue<int > q; d[i][i] = 0; q.push(i); while(!q.empty()) { int c = q.front(); q.pop(); for(auto next = g[c].begin(); next != g[c].end(); ++next) if(d[i][*next] == -1) { d[i][*next] = d[i][c] + 1; q.push(*next); //cout << c << " " << *next << endl; } } } int s[2],t[2],l[2],cost[2]; int so_far = 123456789; cin >> s[0] >> t[0] >> l[0]; cin >> s[1] >> t[1] >> l[1]; s[0]--,s[1]--,t[0]--,t[1]--; for(int k = 0; k < 2; ++k) { swap(s[0],t[0]); for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { cost[0] = d[s[0]][i] + d[i][j] + d[j][t[0]]; cost[1] = d[s[1]][i] + d[i][j] + d[j][t[1]]; if(cost[0] <= l[0] && cost[1] <= l[1]) so_far = min(so_far, cost[0] + cost[1] - d[i][j]); } } } if(d[s[0]][t[0]] <= l[0] && d[s[1]][t[1]] <= l[1]) so_far = min(so_far, d[s[0]][t[0]] + d[s[1]][t[1]]); if(so_far != 123456789) { cout << m - so_far << endl; } else { cout << -1 << endl; } }
06778d9ffdc6bf4a0dc75073c62fc814704ffe32
[ "C++" ]
69
C++
AFGhazy/Library
9ffe8a2b57eb6d6ca5b2822a66ddaecdc571ddd9
43b61322ed6e60e0351ea8a965c185d41df75ad6
refs/heads/master
<repo_name>OreyM/zsh-config<file_sep>/instr/Цветовое оформление консольного вывода.md # Цветовое оформление консольного вывода [https://habr.com/ru/post/319670/] Кратко о том, как сделать для своей консольной программы или скрипта цветной вывод текста, а также дополнить его другими элементами оформления. Собственно, назначить можно цвет текста, цвет фона под ним, сделать текст жирным, подчеркнутым, невидимым и даже мигающим. Шаблон для использования в современных командных оболочках и языках программирования таков: ``` \x1b[...m ``` Это ESCAPE-последовательность, где `\x1b` обозначает символ ESC (десятичный ASCII код 27), а вместо "`...`" подставляются значения из таблицы, приведенной ниже, причем они могут комбинироваться, тогда нужно их перечислить через точку с запятой. Значение | Атрибуты ------- | ------- 0 | нормальный режим 1 | жирный 4 | подчеркнутый 5 | мигающий 7 | инвертированные цвета 8 | невидимый Значение | Цвет текста ------- | ------- 30 | черный 31 | красный 32 | зеленый 33 | желтый 34 | синий 35 | пурпурный 36 | голубой 37 | белый Значение | Цвет фона ------- | ------- 40 | черный 41 | красный 42 | зеленый 43 | желтый 44 | синий 45 | пурпурный 46 | голубой 47 | белый **Примеры:** ``` \x1b[31mTest\x1b[0m \x1b[37;43mTest\x1b[0m \x1b[4;35mTest\x1b[0m ``` ``` man console_codes ```<file_sep>/.zshrc # If you come from bash you might have to change your $PATH. # export PATH=$HOME/bin:/usr/local/bin:$PATH # Path to your oh-my-zsh installation. export ZSH="/home/orey/.oh-my-zsh" # Директория по умолчанию cd /var/www ### Theme ### # See https://github.com/robbyrussell/oh-my-zsh/wiki/Themes ZSH_THEME="powerlevel9k/powerlevel9k" POWERLEVEL9K_MODE="nerdfont-complete" #POWERLEVEL9K_DISABLE_RPROMPT=true POWERLEVEL9K_PROMPT_ON_NEWLINE=true POWERLEVEL9K_MULTILINE_LAST_PROMPT_PREFIX="▶ " #POWERLEVEL9K_MULTILINE_LAST_PROMPT_PREFIX="↳ " POWERLEVEL9K_MULTILINE_FIRST_PROMPT_PREFIX="" ENABLE_CORRECTION="true" # Would you like to use another custom folder than $ZSH/custom? # ZSH_CUSTOM=/path/to/new-custom-folder ### Plugins ### # Standard plugins can be found in ~/.oh-my-zsh/plugins/* # Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/ plugins=( git npm vagrant composer sudo web-search laravel5 docker colored-man-pages ) source $ZSH/oh-my-zsh.sh ### Alias ### # BASH alias c='clear' alias x='exit' alias i='sudo apt install' alias my-icc="xrandr | sed -n 's/ connected.*//p' | xargs -n1 -tri xrandr --output {} --brightness 1 --gamma 1:1:1" alias group='vs /etc/group' # Visual Code alias vs='/snap/bin/code' # MC Edit alias edit='mcedit' # alias edit='/usr/local/Cellar/midnight-commander/4.8.22/bin/mcedit' #PHP Storm alias storm='phpstorm' # ZSH Config alias zconf="code ~/.zshrc" alias ohmyzsh="cd ~/.oh-my-zsh" alias sourcezsh='source ~/.zshrc' # OS param alias os='screenfetch' #DIR Alias alias vpath="cd ~/Google/WEB_DEV/_localServer/domains" alias localpath="cd ~/domain/" alias project="cd ~/_project/" alias dockpath="cd ~/_docker/" #GIT Alias alias status='git status' alias add='git add .' alias push='git push origin master' alias pull='git pull' # glog # PHP alias phpini="cd /usr/local/etc/php/" # + vers PHP, ex 7.3 ### Apache alias ### # Управление сервером alias apache-status='sudo service apache2 status' alias apache-start='sudo service apache2 start' alias apache-restart='sudo service apache2 restart' alias apache-stop='sudo service apache2 stop' # Вывести список всех виртуальных сайтов apache-hosts() { cd /var/www apache2 -v echo "\n" declare -a dirs=(*/) for dir in "${dirs[@]}"; do var=${dir%/} echo "<[ \x1b[0;32m http://$var \x1b[0m ]>"; done echo "\n" } alias apache-error-check='apache2ctl -t' # Создаем новую директорию для сайта # apache-make-site $SITE_NAME $USER apache-make-site() { SITE_NAME=$1 USER=$(whoami) if [ -z "$SITE_NAME" ]; then # Не указано имя сайта первым параметром echo "\x1b[1;31mНе задано имя сайта [apache-make-site SITE_NAME USER]\x1b[0m" elif [ -z "$USER" ]; then # Не указан пользователь вторым параметром echo "\x1b[1;31mНе задан пользователь, для назначения прав [apache-make-site SITE_NAME USER]\x1b[0m" user=$(whoami) echo "\x1b[0;37;44mТекущий пользователь:\x1b[0m $user" else if [ -d /var/www/"$SITE_NAME".local ]; then # Существует ли уже такой сайт echo "\x1b[1;31mСайт $SITE_NAME.local уже существует, выберите другое имя\n\x1b[0m" curl -Is http://"$SITE_NAME".local else # Создаем новую директорию для сайта sudo mkdir -p "/var/www/$SITE_NAME.local/public" # Копируем тестовую стартовую страницу index.php # sudo cp /var/www/index.php "/var/www/$SITE_NAME.local/public/" # Назначаем права на директорию сайта sudo chown -R "$USER":"$USER" /var/www/"$SITE_NAME".local # Создаем новый кофигурационный файл sudo touch "/etc/apache2/sites-available/$SITE_NAME.local.conf" # Конфигурация if [ ! -d ~/.custom_domain/_site_config ]; then mkdir -p ~/.custom_domain/_site_config fi touch ~/.custom_domain/_site_config/"$SITE_NAME".local.conf echo "<VirtualHost *:80> ServerAdmin admin@$SITE_NAME.local ServerName $SITE_NAME.local ServerAlias www.$SITE_NAME.local DocumentRoot /var/www/$SITE_NAME.local/public ErrorLog \${APACHE_LOG_DIR}/$SITE_NAME.error.log CustomLog \${APACHE_LOG_DIR}/$SITE_NAME.access.log combined </VirtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet" > ~/.custom_domain/_site_config/"$SITE_NAME".local.conf sudo cp ~/.custom_domain/_site_config/"$SITE_NAME".local.conf /etc/apache2/sites-available/"$SITE_NAME".local.conf # Подключаем сайт в Apache sudo a2ensite "$SITE_NAME.local.conf" # Добавляем хост sudo sed -i "$ a 127.0.1.1 $SITE_NAME.local" "/etc/hosts" # Перезагружаем Apache sudo service apache2 restart echo -e "The server was rebooted\n" curl -Is http://"$SITE_NAME".local cd /var/www/"$SITE_NAME".local vs /var/www/"$SITE_NAME".local fi fi } # Удаляем сайт apache-delete-site() { SITE_NAME=$1 if [ -z "$SITE_NAME" ]; then # Не указано имя сайта первым параметром echo "\x1b[1;31mНе задано имя сайта, который необходимо удалить [apache-delete-site SITE_NAME]\x1b[0m" else if [ -d /var/www/"$SITE_NAME".local ]; then # Удаляем диреткорию с сайтом sudo rm -rf "/var/www/$SITE_NAME.local" # Удаляем конфигурационный файл сайта sudo rm "/etc/apache2/sites-available/$SITE_NAME.local.conf" # Отключаем сайт от сервера sudo a2dissite "$SITE_NAME.local.conf" # Убираем адресс сайта из хоста sudo sed -i "/127.0.1.1 $SITE_NAME.local/d" "/etc/hosts" # Перезагружаем Apache sudo service apache2 restart echo -e "\x1b[1;42mСайт удален. Сервер перезагружен\x1b[0m\n" else echo "\x1b[1;31mСайт $SITE_NAME.local НЕ существует, проверте имя\n\x1b[0m" fi fi } # Laravel alias laravel="~/.composer/vendor/bin/laravel" alias larperm='sudo chgrp -R www-data storage bootstrap/cache; sudo chmod -R ug+rwx storage bootstrap/cache' alias lara='php artisan' alias serve='php artisan serve' alias controller='php artisan make:controller' alias model='php artisan make:model' alias migration='php artisan make:migration' alias migrate='php artisan migrate' alias seed='php artisan make:seed' alias refresh='php artisan migrate:refresh --seed' alias routelist='php artisan route:list' # Генерация PHPDoc для моделей (Laravel IDE Helper) alias modelhelp='php artisan ide-helper:models --dir="app/src/Models"' # laravel-create-project PROJECT_NAME VERSION laravel-create-project(){ PROJECT_NAME=$1; VERSION=$2 USER=$(whoami) if [ -z "$PROJECT_NAME" ]; then # Не указано имя сайта первым параметром echo "\x1b[1;31mНе задано имя сайта [laravel-create-project PROJECT_NAME VERSION]\x1b[0m" elif [ -z "$VERSION" ]; then echo "\x1b[1;31mНе указана версия пакета Laravel [laravel-create-project PROJECT_NAME VERSION]\x1b[0m" else if [ -d /var/www/"$PROJECT_NAME".local ]; then echo "\x1b[1;31mСайт $PROJECT_NAME.local уже существует, выберите другое имя\n\x1b[0m" curl -Is http://"$PROJECT_NAME".local else sudo chown -R "$USER":"$USER" /var/www cd "/var/www/" composer create-project laravel/laravel="$VERSION.*" "$PROJECT_NAME".local sudo chown -R "$USER":"$USER" /var/www/"$PROJECT_NAME".local sudo touch "/etc/apache2/sites-available/$PROJECT_NAME.local.conf" if [ ! -d ~/.custom_domain/_site_config ]; then mkdir -p ~/.custom_domain/_site_config fi touch ~/.custom_domain/_site_config/"$PROJECT_NAME".local.conf echo "<VirtualHost *:80> ServerAdmin admin@$PROJECT_NAME.local ServerName $PROJECT_NAME.local ServerAlias www.$PROJECT_NAME.local DocumentRoot /var/www/$PROJECT_NAME.local/public ErrorLog \${APACHE_LOG_DIR}/$PROJECT_NAME.error.log CustomLog \${APACHE_LOG_DIR}/$PROJECT_NAME.access.log combined </VirtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet" > ~/.custom_domain/_site_config/"$PROJECT_NAME".local.conf sudo cp ~/.custom_domain/_site_config/"$PROJECT_NAME".local.conf /etc/apache2/sites-available/"$PROJECT_NAME".local.conf sudo a2ensite "$PROJECT_NAME.local.conf" sudo sed -i "$ a 127.0.1.1 $PROJECT_NAME.local" "/etc/hosts" sudo service apache2 restart echo -e "The server was rebooted\n" cd /var/www/"$PROJECT_NAME".local sudo chmod 777 -R storage && sudo chmod 777 -R bootstrap/cache composer require --dev barryvdh/laravel-ide-helper composer require barryvdh/laravel-debugbar --dev npm install npm run dev php artisan cache:clear echo "\n" echo "\x1b[0;32mNode ver:\x1b[0m" $(node --version) echo "\x1b[0;32mNPM ver:\x1b[0m" $(npm --version) composer --version php -v php artisan --version echo "\n" curl -Is http://"$SITE_NAME".local echo "\n" echo "\x1b[0;32mLaravel development server started:\x1b[0m <[ http://$PROJECT_NAME.local ]>" vs /var/www/"$PROJECT_NAME".local echo "\n" fi fi } ### Docker ### alias dres='sudo service docker restart' alias dimg='docker images' alias dcont='docker ps -a' alias dstart='docker start' alias dstop='docker stop' alias dstop-all='' alias ddelete='docker rm' alias ddelete-all='docker rm -v $(docker ps -aq -f status=exited)' alias ddelete-image='docker rmi -f' # Docker compose alias dcup='docker-compose up' alias dcdown='docker-compose stop' dcommit(){ MYAPP="$1" USER="$2" IMAGE="$3" docker commit "$MYAPP" "$USER"/"$IMAGE" } dpush(){ USER="$1" IMAGE="$2" docker push "$USER"/"$IMAGE" } # laradock ## https://github.com/Laradock/laradock.git # DB_HOST=mysql # REDIS_HOST=redis # QUEUE_HOST=beanstalkd alias laradock='git clone https://github.com/Laradock/laradock.git' alias laradockenv='cp env-example .env' alias ldbash='docker-compose exec --user=laradock workspace bash' alias ldserve='docker-compose up -d nginx mysql phpmyadmin redis workspace' alias ldstop='docker-compose stop' alias ldwork='docker-compose exec --user=laradock workspace bash' #NPM alias ndev='npm run dev' alias nprod='npm run prod' alias nwatch='npm run watch' #PHPUnit Alias alias testy='vendor/bin/phpunit --colors=always' # Обновляем конфигурацию ZSH в репозитории [gitzsh $COMMIT] gitzsh() { if [ -z "$1" ]; then echo "\x1b[1;31mНе добавлен коммит для git [gitzsh 'COMMIT']\x1b[0m" else cp ~/.zshrc ~/Project/_zsh/.zshrc cd ~/Project/_zsh git add . git commit -m "$1" git push -u origin master fi } # Sources source /home/orey/.zsh-syntax-highlighting/zsh-syntax-highlighting.zsh <file_sep>/README.md # Конфигуратор оболочки ZSH v. 0.9.11 ## Дополнительные команды #### Терминал * `c` - очистить консоль * `x` - выйти из терминала #### Редакторы * `vs` - Visual Studio Code * `edit` - MC Edit #### Директории * `dir-proj` - cd ~/Project * `dir-domain` - cd ~/Domain * `dir-docker` - cd ~/Docker #### Дополнительные команды * `zconf` - конфигурация zsh * `phpini` - редактирование php.ini /PHP 7.2/ * `linux` - информация о хосте пользователя #### Apache сервер * `apache-status` - статус сервера * `apache-start` - запуск сервера * `apache-restart` - перезагрузка сервера * `apache-stop` - остановка сервера * `apache-make-site SITE_NAME` - создание локального сайта, дача прав к нему указанному пользователю * `apache-delete-site SITE_NAME` - удаление локального сайта * `apache-error-check` - проверка синтаксических ошибок настроек сервера * `apache-hosts` - вывести список всех виртуальных сайтов #### Laravel * Cоздание проекта на Laravel, с указанием версии фреймворка. Будет установлена указананя вкоманде версия фреймворка, подключен Laravel Debugbar. ``` laravel-create-project SITE_NAME LARAVEL_VERS ``` * `lar` - php artisan ## Плагины * git * npm * vagrant * composer * sudo * web-search * laravel5 * docker * colored-man-pages ## Требования Должно быть установлено: * curl ```bash sudo apt install curl ``` PHP >= 7.2 ``` sudo apt install php7.2 php7.2-fpm php-pear php-pecl php7.2-cli php7.2-curl php7.2-dev libapache2-mod-php7.2 php7.2-mbstring php7.2-xml php7.2-xmlrpc php7.2-zip php7.2-mysql php7.2-imagick php7.2-gd php7.2-tidy php7.2-intl php7.2-recode # install PHP 7.2 MCrypt sudo apt install libmcrypt-dev libreadline-dev pecl install mcrypt-1.0.1 # You should add "extension=mcrypt.so" to php.ini ``` * GIT ```bash sudo apt install git ``` * Composer ``` sudo apt install composer ``` * NPM ``` sudo apt install npm ``` * MC ``` sudo apt install mc ``` * Visual Studio Code ## Установка ```bash # Install ZSH sudo apt-get install zsh #Install Oh My ZSH! # Curl curl -L http://install.ohmyz.sh | sh # еще вариант sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" # Вариант через Wget wget https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | zsh # либо sh -c "$(wget https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)" # ZSH оболочко по умолчанию в терминале chsh -s /bin/zsh ``` ```bash # Powerline sudo apt install powerline ``` Устанавливаем шрифты: ```bash # Powerline fonts git clone https://github.com/powerline/fonts.git cd fonts ./install.sh cd .. rm -rf fonts # or sudo apt install fonts-powerline ``` ```bash # ZSH Powerlevel9k Theme sudo apt install zsh-theme-powerlevel9k echo "source /usr/share/powerlevel9k/powerlevel9k.zsh-theme" >> ~/.zshrc ``` ```bash # ZSH Syntax Highlighting sudo apt install zsh-syntax-highlighting echo "source /usr/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh" >> ~/.zshrc ``` Установить шрифт `Hack Regular Nerd Font Complete.ttf` из данного репозитория. ## Удаление ```bash # Удаляем Oh My Zsh и всё что с ним связано uninstall_oh_my_zsh # Удаляем Zsh sudo apt uninstall zsh ```
409ae8e8bb4ad2075d70a5a9a8be9343c997877a
[ "Markdown", "Shell" ]
3
Markdown
OreyM/zsh-config
e519ab1dc2743dd12f6b8edbb8258bc25f26f280
5a2eec37090724e132071c7331d22bc15aa37032
refs/heads/master
<file_sep>const { biggerIsGreater, getSequenceStartIndex, swapPivot, reverseSequence, } = require('./bigger_is_greater') describe('bigger is greater tests', () => { describe('permutation tests', () => { test('string permutation 0', () => { const str = 'dhck' const expected = 'dhkc' const actual = biggerIsGreater(str) expect(actual).toBe(expected) }) test('string permutation', () => { const str = 'hefg' const expected = 'hegf' const actual = biggerIsGreater(str) expect(actual).toBe(expected) }) test('string permutation 1', () => { const str = 'ab' const expected = 'ba' const actual = biggerIsGreater(str) expect(actual).toBe(expected) }) test('string permutation 2', () => { const str = 'ba' const expected = 'no answer' const actual = biggerIsGreater(str) expect(actual).toBe(expected) }) test('string permutation 3', () => { const str = 'bb' const expected = 'no answer' const actual = biggerIsGreater(str) expect(actual).toBe(expected) }) test('string permutation 4', () => { const str = 'fedcbabcd' const expected = 'fedcbabdc' const actual = biggerIsGreater(str) expect(actual).toBe(expected) }) test('string permutation 5', () => { const str = 'zxvuutttrrrpoookiihhgggfdca' const expected = 'no answer' const actual = biggerIsGreater(str) expect(actual).toBe(expected) }) test('string permutation 6', () => { const str = 'zzzayybbaa' const expected = 'zzzbaaabyy' const actual = biggerIsGreater(str) expect(actual).toBe(expected) }) }) describe('sequence tests', () => { test('string length === 1', () => { const arr = ['a'] const expected = 0 const actual = getSequenceStartIndex(arr) expect(actual).toBe(expected) }) test('string length === 2 (pos 1)', () => { const arr = ['a', 'b'] const expected = 1 const actual = getSequenceStartIndex(arr) expect(actual).toBe(expected) }) test('string length === 2 (pos 0)', () => { const arr = ['b', 'a'] const expected = 0 const actual = getSequenceStartIndex(arr) expect(actual).toBe(expected) }) test('string length > 2 (pos 1)', () => { const arr = ['a', 'c', 'b'] const expected = 1 const actual = getSequenceStartIndex(arr) expect(actual).toBe(expected) }) test('no sequence', () => { const arr = [100, 104, 99, 107] const expected = 3 const actual = getSequenceStartIndex(arr) expect(actual).toBe(expected) }) }) describe('pivot tests', () => { test('1 element', () => { const arr = ['a'] const expected = ['a'] const actual = swapPivot(arr, 0) expect(actual).toStrictEqual(expected) }) test('no pivot', () => { const arr = ['b', 'a'] const expected = ['b', 'a'] const actual = swapPivot(arr, 0) expect(actual).toStrictEqual(expected) }) test('2 elements', () => { const arr = ['a', 'b'] const expected = ['b', 'a'] const actual = swapPivot(arr, 1) expect(actual).toStrictEqual(expected) }) test('7 elements', () => { const arr = [0, 1, 2, 5, 3, 3, 0] const expected = [0, 1, 3, 5, 3, 2, 0] const actual = swapPivot(arr, 3) expect(actual).toStrictEqual(expected) }) }) describe('reverse tests', () => { test('reverse sequence test', () => { const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] const expected = ['a', 'b', 'c', 'g', 'f', 'e', 'd'] const actual = reverseSequence(arr, 3) expect(actual).toStrictEqual(expected) }) }) }) <file_sep>/* simple generator example */ function* generator() { yield 1 yield 2 yield 3 } const gen1 = generator() console.log(gen1.next()) // {value: 1, done: false} console.log('test') console.log(gen1.next()) // {value: 2, done: false} console.log(gen1.next()) // {value: undefined, done: true} /* generator that accepts value */ function* acceptGenerator() { const test = yield 1 if (test) { console.log(test) } } const test = acceptGenerator() test.next('bla') test.next() <file_sep>const { write, findIndexBinary } = require('./ranking'); describe('ranking tests', function() { test('should find index with binary search', () => { const arr = [20,16,13,10,1] const el = 12 const index = findIndexBinary(arr, el) expect(index).toBe(4); }); test('should find index with binary search 1', () => { const arr = [20,16,13,10,1] const el = 10 const index = findIndexBinary(arr, el) expect(index).toBe(4); }); test('should find index with binary search 2', () => { const arr = [20,16,13,10,1] const el = 1 const index = findIndexBinary(arr, el) expect(index).toBe(5); }); test('should find index with binary search 3', () => { const arr = [20,16,13,10,1] const el = 3 const index = findIndexBinary(arr, el) expect(index).toBe(5); }); test('should find index with binary search 4', () => { const arr = [20,16,13,10,1] const el = 21 const index = findIndexBinary(arr, el) expect(index).toBe(1); }); });<file_sep>const { verifyFullPattern, findPatternOccurences, hasMatch, } = require('./grid_search') describe('grid search tests', () => { describe('pattern verification tests', () => { test('should verify full pattern (true)', () => { const matrix = [ '112121212', '111255564', '441447899', '113456722', '112121212', ] const pattern = ['12555', '14478', '34567'] const expected = true const actual = verifyFullPattern(matrix, pattern, 1, 2) expect(actual).toBe(expected) }) test('should verify full pattern (false)', () => { const matrix = ['112121212', '111255564'] const pattern = ['12555', '14478', '34567'] const expected = false const actual = verifyFullPattern(matrix, pattern, 1, 2) expect(actual).toBe(expected) }) }) describe('find pattern tests', () => { it('should find pattern', () => { const array = [ '7283455864', '6731158619', '8988242643', '3830589324', '2229505813', '5633845374', '6473530293', '7053106601', '0834282956', '4607924137', ] const pattern = ['9505', '3845', '3530'] const actual = findPatternOccurences(array, pattern) const expected = 'YES' expect(actual).toBe(expected) }) it('should find pattern 2', () => { const array = [ '400453592126560', '114213133098692', '474386082879648', '522356951189169', '887109450487496', '252802633388782', '502771484966748', '075975207693780', '511799789562806', '404007454272504', '549043809916080', '962410809534811', '445893523733475', '768705303214174', '650629270887160', ] const pattern = ['99', '99'] const actual = findPatternOccurences(array, pattern) const expected = 'NO' expect(actual).toBe(expected) }) it('should find pattern 3', () => { const array = ['123412', '561212', '123634', '781288'] const pattern = ['12', '34'] const actual = findPatternOccurences(array, pattern) const expected = 'YES' expect(actual).toBe(expected) }) it('should find pattern 4', () => { const array = [ '111111111111111', '111111111111111', '111111011111111', '111111111111111', '111111111111111', ] const pattern = ['11111', '11111', '11110'] const actual = findPatternOccurences(array, pattern) const expected = 'YES' expect(actual).toBe(expected) }) it('should not find pattern', () => { const array = ['7283455864', '6731158619'] const pattern = ['9505', '3845', '3530'] const actual = findPatternOccurences(array, pattern) const expected = 'NO' expect(actual).toBe(expected) }) }) describe('has match tests', () => { it('has match (false)', () => { const string = 'ssssshello' const pattern = 'hello' const actual = hasMatch(string, pattern, 0) const expected = false expect(actual).toBe(expected) }) it('has match (true)', () => { const string = 'ssssshello' const pattern = 'hello' const actual = hasMatch(string, pattern, 5) const expected = true expect(actual).toBe(expected) }) it('has match with duplicates (true)', () => { const string = 'hellohello' const pattern = 'hello' const actual = hasMatch(string, pattern, 0) const expected = true expect(actual).toBe(expected) }) it('has match with duplicates (second dup - true)', () => { const string = 'hellohello' const pattern = 'hello' const actual = hasMatch(string, pattern, 5) const expected = true expect(actual).toBe(expected) }) }) }) <file_sep>function biggerIsGreater2(w) { w = w.split('') // Find non-increasing suffix let i = w.length - 1 while (i > 0 && w[i - 1] >= w[i]) { i-- } if (i <= 0) return 'no answer' // Find the rightmost successor to pivot in the suffix let j = w.length - 1 while (w[j] <= w[i - 1]) j-- // Swap the pivot with the rightmost character const temp = w[i - 1] w[i - 1] = w[j] w[j] = temp // Reverse suffix j = w.length - 1 while (i < j) { const temp = w[i] w[i] = w[j] w[j] = temp i++ j-- } return w.join('') } function biggerIsGreater(str) { if (str.length === 1) { return 'no answer' } const arr = str.split('') let sequenceStartIndex = getSequenceStartIndex(arr) if (sequenceStartIndex === 0) { return 'no answer' } // swap pivot const swapped = swapPivot(arr, sequenceStartIndex) const reversed = reverseSequence(swapped, sequenceStartIndex) return reversed.join('') } function getSequenceStartIndex(arr) { let sequenceStartIndex = arr.length - 1 while ( sequenceStartIndex > 0 && arr[sequenceStartIndex - 1] >= arr[sequenceStartIndex] ) { sequenceStartIndex-- } return sequenceStartIndex } function swapPivot(arr, sequenceIndex) { if (arr.length === 1 || sequenceIndex === 0) { return arr } const pivotIndex = sequenceIndex - 1 let successorIndex = arr.length - 1 const swapped = [...arr] while (arr[successorIndex] <= arr[pivotIndex]) { successorIndex-- } const temp = swapped[pivotIndex] swapped[pivotIndex] = swapped[successorIndex] swapped[successorIndex] = temp return swapped } function reverseSequence(arr, sequenceStartIndex) { const array = [...arr] const sequence = arr.slice(sequenceStartIndex, array.length) const reversed = sequence.reverse() array.splice(sequenceStartIndex, array.length, ...reversed) return array } module.exports = { biggerIsGreater, getSequenceStartIndex, swapPivot, reverseSequence, } <file_sep>class Device { call = () => { console.info('Calling....'); }; constructor(display, keyboard, microphone) { this.display = display; this.keyboard = keyboard; this.microphone = microphone; } } class Display { test = () => { console.log('display test success'); return true; }; } class Keyboard { test = () => { console.log('keyboard test success'); return true; }; } class Microphone { test = () => { console.log('microphone test success'); return true; }; } class DeviceBuilder { createDisplay = () => { console.log('display added'); return new Display(); }; createKeyboard = () => { console.log('keyboard added'); return new Keyboard(); }; createMicrophone = () => { console.log('microphone added'); return new Microphone(); }; testDevice = (device) => { if ( device.display.test() && device.keyboard.test() && device.microphone.test() ) { return true; } }; buidDevice = () => { const display = this.createDisplay(); const keyboard = this.createKeyboard(); const microphone = this.createMicrophone(); const device = new Device(display, keyboard, microphone); console.log('testing device'); const testSuccess = this.testDevice(device); if (testSuccess) { console.log('device test success'); return device; } else { throw Error('Error during device creation'); } }; } module.exports = { DeviceBuilder, }; <file_sep>// A Factory Method creates new objects as instructed by the client. // One way to create objects in JavaScript is by invoking a constructor function with the new operator. // There are situations however, where the client does not, or should not, know which one of several candidate objects to instantiate. // The Factory Method allows the client to delegate object creation while still retaining control over which type to instantiate. const SOME_CLASS_TYPE = { TYPE_1: 'type1', TYPE_2: 'type2', }; class SomeClass1 { constructor() { this.someProperty1 = 'class 1 property 1'; this.someProperty2 = 'class 1 property 2'; } getMyProperties() { console.log(this.someProperty1); console.log(this.someProperty2); return; } } class SomeClass2 { constructor() { this.someProperty1 = 'class 2 property 1'; this.someProperty2 = 'class 2 property 2'; } getMyProperties() { console.log(this.someProperty1); console.log(this.someProperty2); return; } } class SomeClassFactory { constructor() { this.instance = null; } getInstance(type) { switch (type) { case SOME_CLASS_TYPE.TYPE_1: this.instance = new SomeClass1(); break; case SOME_CLASS_TYPE.TYPE_2: this.instance = new SomeClass2(); break; } return this.instance; } } const someClassFactory = new SomeClassFactory(); const instance = someClassFactory.getInstance(SOME_CLASS_TYPE.TYPE_1); instance.getMyProperties(); <file_sep>class Service { play = () => console.log('play'); stop = () => console.log('stop'); } class MouseController { constructor(service) { this.service = service; } leftBtnClick = () => { this.service.play(); }; rightBtnClick = () => { this.service.stop(); }; } class KeyboardController { constructor(service) { this.service = service; } spaceBtnPress = () => { this.service.play(); }; escapeBtnPress = () => { this.service.stop(); }; } module.exports = { Service, MouseController, KeyboardController, }; <file_sep>const { getTypesSortedCounts, verifyTypesCountsAreEqual, isPossibleToSort, } = require('./balls') describe('balls sorting tests', () => { describe('matrix type sorting tests', () => { it('should sort 2 types', () => { const matrix = [ [1, 1], [1, 1], ] const sorted = getTypesSortedCounts(matrix) const expected = [2, 2] expect(sorted).toStrictEqual(expected) }) it('should sort 3 types', () => { const matrix = [ [1, 1, 5], [0, 0, 0], [1, 1, 0], ] const sorted = getTypesSortedCounts(matrix) const expected = [2, 2, 5] expect(sorted).toStrictEqual(expected) }) }) it('verify swapping possible', () => { const matrix = [ [0, 2, 1], [1, 1, 1], [2, 0, 0], ] const actual = isPossibleToSort(matrix) const expected = 'Possible' expect(actual).toBe(expected) }) }) <file_sep>const { nonDivisibleSubset, getRemainders, calculateCounts, } = require('./non_dividable_subset') describe('subset tests', () => { // test('get remainders', () => { // const elements = [ // 2375782, // 21836421, // 2139842193, // 2138723, // 23816, // 21836219, // 2948784, // 43864923, // 283648327, // 23874673, // ] // const expected = [6, 9, 8, 2, 0, 2, 7, 11, 1, 4] // const actual = getRemainders(elements, 13) // expect(actual).toStrictEqual(expected) // }) // test('should calculate counts', () => { // const values = [6, 9, 8, 2, 0, 2, 7, 11, 1, 4] // const actual = calculateCounts(values) // const expected = { 0: 1, 1: 1, 2: 2, 4: 1, 6: 1, 7: 1, 8: 1, 9: 1, 11: 1 } // expect(actual).toStrictEqual(expected) // }) describe('subset tests', () => { test('should find subset 1', () => { const elements = [ 2375782, 21836421, 2139842193, 2138723, 23816, 21836219, 2948784, 43864923, 283648327, 23874673, ] const expected = 7 const actual = nonDivisibleSubset(13, elements) expect(actual).toStrictEqual(expected) }) test('should find subset 2', () => { const elements = [1, 2, 3, 4, 5] const expected = 1 const actual = nonDivisibleSubset(1, elements) expect(actual).toStrictEqual(expected) }) test('should find subset 3', () => { const elements = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const expected = 5 const actual = nonDivisibleSubset(4, elements) expect(actual).toStrictEqual(expected) }) test('should find subset 4', () => { const elements = [1, 7, 2, 4] const expected = 3 const actual = nonDivisibleSubset(3, elements) expect(actual).toStrictEqual(expected) }) }) describe('subset tests 2', () => { test('should find subset 1', () => { const elements = [ 582740017, 954896345, 590538156, 298333230, 859747706, 155195851, 331503493, 799588305, 164222042, 563356693, 80522822, 432354938, 652248359, ] const expected = 11 const actual = nonDivisibleSubset(11, elements) expect(actual).toStrictEqual(expected) }) test('should find subset 2', () => { const elements = [1, 2, 3, 4, 5] const expected = 1 const actual = nonDivisibleSubset(1, elements) expect(actual).toStrictEqual(expected) }) test('should find subset 3', () => { const elements = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const expected = 5 const actual = nonDivisibleSubset(4, elements) expect(actual).toStrictEqual(expected) }) test('should find subset 4', () => { const elements = [1, 7, 2, 4] const expected = 3 const actual = nonDivisibleSubset(3, elements) expect(actual).toStrictEqual(expected) }) }) }) <file_sep># training repository for training algorithms, patterns etc skills in javascript test<file_sep>/* 20 10 30 5 15 25 35 2 7 13 17 23 27 32 37 BFS traversal: 20, 10, 30, 5, 15, 25, 35, 2, 7, 13, 17, 23, 27, 32, 37 */ const Tree = require('../Tree') const tree = new Tree() tree.push(20) tree.push(10) tree.push(30) tree.push(5) tree.push(15) tree.push(25) tree.push(35) tree.push(2) tree.push(7) tree.push(13) tree.push(17) tree.push(23) tree.push(27) tree.push(32) tree.push(37) function bfs(tree) { const node = tree.root const queue = [] const ordered = [] queue.push(node) while (queue.length) { const node = queue.shift() ordered.push(node.root) node.left && queue.push(node.left) node.right && queue.push(node.right) } return ordered } module.exports = { bfs, } <file_sep> const bubble_sort = (array) => { let finished = false; while(!finished) { for(let i=0; i<array.length; i++) { if(array[i] > array[i+1]) { const temp = array[i+1]; array[i+1] = array[i]; array[i] = temp; break; } if(i===array.length-1) { finished=true; } } } return array; }; module.exports = bubble_sort;<file_sep>const { groupByChar, groupByCounts, sortCounts, checkString, } = require('./sherlock') describe('sherlock tests', () => { test('char grouping test', () => { const str = 'asdfghhjkklll' const actual = groupByChar(str) const expected = { a: 1, s: 1, d: 1, f: 1, g: 1, h: 2, j: 1, k: 2, l: 3, } expect(actual).toStrictEqual(expected) }) test('counts grouping test', () => { const charGroup = { a: 3, b: 3, c: 5, d: 9, } const actual = groupByCounts(charGroup) const expected = { 3: 2, 5: 1, 9: 1, } expect(actual).toStrictEqual(expected) }) test('counts sorting', () => { const countsGroupArr = [ [9, 1], [3, 2], [5, 1], ] const actual = sortCounts(countsGroupArr) const expected = [ [3, 2], [9, 1], [5, 1], ] expect(actual).toStrictEqual(expected) }) describe('check string tests', () => { test('NO - more then 2 counts groups', () => { const str = 'aabbcccdddd' const actual = checkString(str) expect(actual).toBe('NO') }) test('NO - 2 counts groups (1)', () => { const str = 'aabbcccddd' const actual = checkString(str) expect(actual).toBe('NO') }) test('NO - 2 counts groups (2)', () => { const str = 'aabbccccc' const actual = checkString(str) expect(actual).toBe('NO') }) test('NO - hackerrank use case', () => { const str = 'aabbccddeefghi' const actual = checkString(str) expect(actual).toBe('NO') }) test('YES - 2 counts groups', () => { const str = 'aabbccc' const actual = checkString(str) expect(actual).toBe('YES') }) test('YES - valid string', () => { const str = 'aabbcc' const actual = checkString(str) expect(actual).toBe('YES') }) }) }) <file_sep>// Capture and restore an object's internal state // The Memento pattern provides temporary storage as well as restoration of an object. // The mechanism in which you store the object’s state depends on the required duration of persistence, which may vary. const SomeObject = function (prop1, prop2, prop3) { this.id = Math.random(); this.prop1 = prop1; this.prop2 = prop2; this.prop3 = prop3; }; SomeObject.prototype = { backup: function () { const data = JSON.stringify(this); return data; }, restore: function (backup) { const data = JSON.parse(backup); Object.entries(data).forEach(([key, value]) => { this[key] = value; }); }, }; const BackupStorage = function () { this.backups = {}; }; BackupStorage.prototype = { addBackup: function (key, data) { this.backups[key] = data; }, getBackup: function (key) { const data = this.backups[key]; delete this.backups.key; return data; }, }; const storage = new BackupStorage(); const obj = new SomeObject('a', 'b', 'c'); const backup = obj.backup(); storage.addBackup(obj.key, backup); obj.prop1 = 'bla bla'; console.log('obj', obj); const data = storage.getBackup(obj.key); obj.restore(data); console.log('restored obj', obj); <file_sep>/** * PSEUDO CODE * * 1. Find all occurences of pattern start * 2. Function that verifies full pattern * * */ function hasMatch(string, patternString, index) { const str = string.slice(index, patternString.length + index) return str === patternString } function findPatternOccurences(G, P) { for (let row = 0; row < G.length; row++) { const patternString = P[0] const string = G[row] for (let i = 0; i < string.length; i++) { if (hasMatch(string, patternString, i)) { const patternVerified = verifyFullPattern(G, P, row, i) if (patternVerified) { return 'YES' } } } } return 'NO' } function verifyFullPattern(matrix, pattern, row, index) { let result = true for (let i = 1; i < pattern.length; i++) { const patternString = pattern[i] const matrixString = matrix[row + i] if (!matrixString) { result = false break } const matrixPatternString = matrixString.slice( index, patternString.length + index ) if (matrixPatternString !== patternString) { result = false break } } return result } module.exports = { verifyFullPattern, findPatternOccurences, hasMatch, } <file_sep>//An Abstract Factory creates objects that are related by a common theme. //In object-oriented programming a Factory is an object that creates other objects. //An Abstract Factory has abstracted out a theme which is shared by the newly created objects. class Employee { constructor(salary) { this.salary = salary; } showSalary = () => { console.log(this.salary); }; } class EmployeeFactory { create = (salary) => { return new Employee(salary); }; } const employeeFactory = new EmployeeFactory(); const employeeA = employeeFactory.create(1200); const employeeB = employeeFactory.create(1400); employeeA.showSalary(); employeeB.showSalary(); <file_sep>const { sortWithNegative } = require('./bucket_sort') describe('bucker sort tests', () => { test('sort with negative', () => { const arr = [-1, 10, -5, -2, 50, 100] const expected = [-5, -2, -1, 10, 50, 100] const actual = sortWithNegative(arr) expect(actual).toStrictEqual(expected) }) }) <file_sep>// The objective of the example is to show that with the Bridge pattern input and output devices can vary independently (without changes to the code); // the devices are loosely coupled by two levels of abstraction. const { Service, MouseController, KeyboardController } = require('./helpers'); const service = new Service(); const mouseController = new MouseController(service); const keyboard = new KeyboardController(service); mouseController.leftBtnClick(); mouseController.rightBtnClick(); keyboard.spaceBtnPress(); keyboard.escapeBtnPress(); <file_sep>/* 1. replace half elements with dashes 2. bucket sort */ function sort(arr) { const replacedWithDashes = replaceElementswithDashes(arr) const sorted = bucketSort(replacedWithDashes) const str = convertToString(sorted) return str } function replaceElementswithDashes(arr) { if (arr.length === 1) { return arr } for (let i = 0; i < parseInt(arr.length / 2); i++) { arr[i][1] = '-' } return arr } function bucketSort(unsortedArr) { const sortedArr = [] unsortedArr.forEach((el) => { const [index, value] = el const sortedArrEl = sortedArr[index] if (sortedArrEl) { sortedArrEl.push(value) } else { sortedArr[index] = [value] } }) return Array.from(sortedArr).filter((el) => el) } function convertToString(flattenArr) { return flattenArr.flat().join(' ') } module.exports = { replaceElementswithDashes, bucketSort, convertToString, sort, } <file_sep>function permutation(arr, index = 0, final = []) { const el = arr[index] if (index === arr.length - 1) { final.push(arr) } for (let i = index; i < arr.length; i++) { const perm = [...arr] const temp = perm[i] perm[i] = el perm[index] = temp if (index < arr.length - 1) { permutation(perm, index + 1, final) } } return final } const permuted = permutation(['a', 'b', 'c']) console.log(permuted) module.exports = { permutation, } <file_sep>// By default, the JavaScript engine provides the Object() function // and an anonymous object that can be referenced via the Object.prototype. // object literal const a = {}; // Object create const b = Object.create({}); // new Object const c = new Object(); // constructor const d = new SomeObject(); function SomeObject(prop1) { this.prop1 = prop1; } SomeObject.prototype = { test = 'test' }<file_sep> const singleton = (() => { let instance = null; const init = () => { let number = 0; return { setNumber: (a) => { number = a; }, getNumber: () => number } }; const getInstance = () => { if(!instance) { instance = init() } return instance; }; return { getInstance } })(); const instance1 = singleton.getInstance(); const instance2 = singleton.getInstance(); instance1.setNumber(5); console.log(instance2.getNumber()); <file_sep>require('marko/node-require'); const express = require('express'); const spdy = require('spdy'); const fs = require('fs'); const path = require('path'); var template = require('../src/index.marko'); var markoExpress = require('marko/express'); const app = express(); const PORT = 4000; app.use(express.static(path.join(__dirname, '../src/public'))); app.use(markoExpress()); app.get('/', function (req, res) { res.marko(template, { port: PORT, secure: true, }); }); app.get('/styles', (req, res) => { setTimeout(function () { res.sendFile(path.join(__dirname, '../src/public/styles.css')); }, 1000); }); const options = { key: fs.readFileSync(path.join(__dirname, '../certificate/localhost.key')), cert: fs.readFileSync(path.join(__dirname, '../certificate/localhost.crt')), }; spdy.createServer(options, app).listen(PORT, (err) => { if (err) { throw new Error(err); } console.log('Listening on port: ' + PORT + '.'); }); <file_sep>/* PSEUDOCODE 1. remove spaces 2. get sqrt 3. define number of rows and columns 4. Ensure rows*col > L 4. Eplit string into array of rows 5. Encode */ function encryptString(s) { const formattedString = removeSpacesFromString(s) const rowsAndCols = getRowsAndCols(formattedString) const matrix = getMatrix(formattedString, rowsAndCols.cols) const encrypted = encryptMatrix(matrix) return encrypted } function removeSpacesFromString(s) { return s.replace(/ /g, '') } function getRowsAndCols(s) { const length = s.length const sqrt = Math.sqrt(length) const rows = parseInt(sqrt) const cols = sqrt > rows ? rows + 1 : rows return { rows, cols, } } function verifyRowsAndCols(rows, cols, length) { return rows * cols >= length } function getMatrix(s, cols) { const length = s.length const step = cols const chunks = [] for (var i = 0; i < length; i += step) { const str = s.slice(i, i + step) chunks.push(str) } return chunks } function encryptMatrix(matrix) { const cols = matrix[0].length let encryptedPhrase = '' for (var i = 0; i < cols; i++) { let encryptedWord = '' for (var j = 0; j < matrix.length; j++) { const letter = matrix[j][i] if (!letter) { break } encryptedWord += letter } encryptedPhrase += `${encryptedWord} ` } return encryptedPhrase.trim() } module.exports = { removeSpacesFromString, getRowsAndCols, verifyRowsAndCols, getMatrix, encryptMatrix, encryptString, } <file_sep>function nonDivisibleSubset(k, s) { if (k === 0 || k === 1) { return 1 } let count = 0 const remainders = getRemaindersWithCounts(s, k) for (let remainder = 0; remainder < k; remainder++) { const remainderCount = remainders[remainder] if (!remainderCount) { continue } const diff = k - remainder if (diff === remainder) { count += 1 delete remainders[remainder] continue } if (remainder === 0) { count += 1 delete remainders[remainder] continue } const diffCount = remainders[diff] if (diffCount) { const remainderCountIsBigger = remainderCount > diffCount count += remainderCountIsBigger ? remainderCount : diffCount } else { count += remainderCount } delete remainders[remainder] delete remainders[diff] } return count } function getRemaindersWithCounts(s, k) { return s.reduce((acc, number) => { const remainder = number % k const exists = acc[remainder] return { ...acc, [remainder]: exists ? (acc[remainder] += 1) : 1, } }, {}) } function getSubsetArrayCount(remainders, k, counts) { let count = 0 for (let i = 0; i < remainders.length; i++) { if (Object.keys(counts).length === 0) { break } const remainder = remainders[i] const remainderCount = counts[remainder] if (!remainderCount) { continue } const diff = k - remainder if (diff === remainder) { count += 1 delete counts[remainder] continue } if (remainder === 0) { count += 1 delete counts[remainder] continue } const diffCount = counts[diff] if (diffCount) { const remainderCountIsBigger = remainderCount > diffCount count += remainderCountIsBigger ? remainderCount : diffCount } else { count += remainderCount } delete counts[remainder] delete counts[diff] } return count } function getRemainders(arr, k) { return arr.reduce((acc, el) => { return [...acc, el % k] }, []) } function calculateCounts(arr) { return arr.reduce((acc, el) => { return { ...acc, [el]: acc[el] ? acc[el] + 1 : 1, } }, {}) } module.exports = { nonDivisibleSubset, nonDivisibleSubset2, getRemainders, calculateCounts, } <file_sep> const bubble_sort_recursive = (array) => { for(let i=0; i<array.length-1; i++) { if(array[i] > array[i+1]) { const temp = array[i]; array[i] = array[i+1]; array[i+1] = temp; return bubble_sort_recursive(array); } } console.log(array); }; bubble_sort_recursive([9,7,5,3,99,1,100]);<file_sep>// The Interpreter pattern offers a scripting language that allows end-users to customize their solution. const en_ua = { Hello: 'Привіт', GoodBye: 'Бувай', }; const en_de = { Hello: '<NAME>', GoodBye: 'Aufiderzein', }; const LANGUAGE_CONTEXT = { UA: 'en_ua', DE: 'en_de', }; class Translator { constructor(context) { this.context = context; } translate(word) { switch (this.context) { case LANGUAGE_CONTEXT.UA: { console.log(en_ua[word]); break; } case LANGUAGE_CONTEXT.DE: { console.log(en_de[word]); break; } default: { console.log('context not found'); } } } } const translator = new Translator(LANGUAGE_CONTEXT.DE); translator.translate('Hello'); <file_sep>const linear_search = (arr, number) => { let index; for(let i=0; i<arr.length; i++) { if(arr[i] === number) { index=i; break; } } return index ? index : false; }; module.exports = linear_search;<file_sep>const linear_search = require('./linear_search'); describe('linear search algorithm', function() { test('should return correct index of number', () => { const element = linear_search([1,3,5,7,9], 9); expect(element).toBe(4); }); test('should return false because number does not exist', () => { const element = linear_search([1,3,5,7,9], 10); expect(element).toBe(false); }); });<file_sep>function factorial(f) { let n = BigInt(f) let sum = 1n while (n > 0) { sum = sum * n n-- } return sum } const a = factorial(100) console.log(a.toString()) <file_sep>// Encapsulate a command request as an object const Command = (execute, undo, n) => ({ execute, undo, n, }); const sum = (a, b) => a + b; const sub = (a, b) => a - b; const mul = (a, b) => a * b; const div = (a, b) => a / b; const SumCommand = (n) => Command(sum, sub, n); const SubCommand = (n) => Command(sub, sum, n); const MulCommand = (n) => Command(mul, div, n); const DivCommand = (n) => Command(div, mul, n); class Calculator { commands = []; result = 0; execute = (command) => { this.result = command.execute(this.result, command.n); this.commands.push(command); console.log('command executed, result - ', this.result); }; undo = () => { if (!this.commands.length) { console.log('Nothing to undo'); } if (this.commands.length === 1) { this.commands.pop(); this.result = null; } const command = this.commands.pop(); this.result = command.undo(this.result, command.n); console.log('undo last command, result - ', this.result); }; } const calc = new Calculator(); calc.execute(SumCommand(4)); calc.execute(MulCommand(8)); calc.execute(SumCommand(4)); calc.undo(); calc.undo(); <file_sep>const { permutate } = require('./permutation') describe('permutation tests', () => { test('abc', () => { const arr = ['a', 'b', 'c'] const expected = [ ['a', 'b', 'c'], ['b', 'a', 'c'], ['c', 'b', 'a'], ] const actual = permutate(arr) expect(actual).toStrictEqual(expected) }) }) <file_sep>/* 20 10 30 5 15 25 35 2 7 13 17 23 27 32 37 preorder: 20, 10, 5, 2, 7, 15, 13, 17, 30, 25, 23, 27, 35, 32, 37 inorder: 2, 5, 7, 10, 13, 15, 17, 20, 23, 25, 27, 30, 32, 35, 37 postorder: */ const Tree = require('../Tree') const tree = new Tree() tree.push(20) tree.push(10) tree.push(30) tree.push(5) tree.push(15) tree.push(25) tree.push(35) tree.push(2) tree.push(7) tree.push(13) tree.push(17) tree.push(23) tree.push(27) tree.push(32) tree.push(37) function preorder(node, ordered = []) { ordered.push(node.root) node.left && preorder(node.left, ordered) node.right && preorder(node.right, ordered) return ordered } function inorder(node, ordered = []) { node.left && inorder(node.left, ordered) ordered.push(node.root) node.right && inorder(node.right, ordered) return ordered } function postorder(node, ordered = []) { node.left && postorder(node.left, ordered) node.right && postorder(node.right, ordered) ordered.push(node.root) return ordered } console.log(postorder(tree.root)) module.exports = { preorder, inorder, postorder, } <file_sep>// A way of passing a request between a chain of objects // The Chain of Responsibility pattern provides a chain of loosely coupled objects // one of which can satisfy a request. // This pattern is essentially a linear search for an object that can handle a particular request. class DeviceBuilder { device = null; constructor(budget) { this.device = {}; this.budget = budget; } printDeviceConfiguration = () => { console.log(this.device); return this; }; addDisplay = () => { const price = 50; if (price < this.budget) { this.device.display = true; this.amount -= price; } else { console.info('No budget for display'); } return this; }; addKeyboard = () => { const price = 20; if (price < this.budget) { this.device.keyboard = true; this.amount -= price; } else { console.info('No budget for keyboard'); } return this; }; addCamera = () => { const price = 100; if (price < this.budget) { this.device.camera = true; this.amount -= price; } else { console.info('No budget for camera'); } return this; }; } const device = new DeviceBuilder(100); device.addDisplay().addCamera().addKeyboard(); device.printDeviceConfiguration(); class NumberFinder { constructor(number) { this.number = number; this.numbers = {}; } findCount = (number) => { if (this.numbers[number]) { console.info(`${number} already used`); return this; } const count = Math.floor(this.number / number); const left = this.number % number; this.numbers[number] = count; this.number = left; return this; }; printResults = () => { Object.entries(this.numbers).forEach(([key, value]) => { console.log(`number ${key} -> ${value}`); }); console.log(`left - ${this.number}`); }; } const finder = new NumberFinder(347); finder.findCount(100).findCount(7).findCount(2).findCount(1); finder.printResults(); <file_sep>import Tree from '../../structures/Tree/Tree'; const tree = new Tree(); // Tree structure is an implementation of composite pattern tree.push(5); tree.push(24); tree.push(2); tree.push(7); tree.push(98); tree.push(65); <file_sep>var array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 12, 8, 11] function quickSort(array) { if (array.length == 0) return [] var left = [] var right = [] var el = array[0] for (var i = 1; i < array.length; i++) { if (array[i] < el) { left.push(array[i]) } else { right.push(array[i]) } } return quickSort(left).concat(el, quickSort(right)) } const sorted = quickSort(array) console.log(sorted) <file_sep>const { replaceElementswithDashes, bucketSort, convertToString, sort, } = require('./counting_sort') describe('counting sort tests', () => { describe('replace elements with dashes', () => { test('1 element', () => { const arr = [[0, 'aa']] const actual = replaceElementswithDashes(arr) const expected = [[0, 'aa']] expect(actual).toStrictEqual(expected) }) test('2 elements', () => { const arr = [ [0, 'aa'], [1, 'bb'], ] const actual = replaceElementswithDashes(arr) const expected = [ [0, '-'], [1, 'bb'], ] expect(actual).toStrictEqual(expected) }) test('3 elements', () => { const arr = [ [0, 'aa'], [1, 'bb'], [2, 'cc'], ] const actual = replaceElementswithDashes(arr) const expected = [ [0, '-'], [1, 'bb'], [2, 'cc'], ] expect(actual).toStrictEqual(expected) }) test('> 3 elements', () => { const arr = [ [0, 'aa'], [1, 'bb'], [2, 'cc'], [3, 'dd'], ] const actual = replaceElementswithDashes(arr) const expected = [ [0, '-'], [1, '-'], [2, 'cc'], [3, 'dd'], ] expect(actual).toStrictEqual(expected) }) }) test('bucket sort', () => { const arr = [ [3, '1c'], [2, '1b'], [1, '1a'], [3, '2c'], [2, '2b'], [1, '2a'], [3, '3c'], [2, '3b'], [1, '3a'], ] const expected = [ ['1a', '2a', '3a'], ['1b', '2b', '3b'], ['1c', '2c', '3c'], ] const actual = bucketSort(arr) expect(actual).toStrictEqual(expected) }) test('convert to string', () => { const arr = [ ['aa', 'bb'], ['cc', 'dd'], ['ee', 'ff'], ] const expected = 'aa bb cc dd ee ff' const actual = convertToString(arr) expect(actual).toBe(expected) }) describe('sorting tests', () => { test('sort 1', () => { const arr = [ [0, 'a'], [1, 'b'], [0, 'c'], [1, 'd'], ] const expected = '- c - d' const actual = sort(arr) expect(actual).toBe(expected) }) test('sort 2', () => { const arr = [ ['0', 'ab'], ['6', 'cd'], ['0', 'ef'], ['6', 'gh'], ['4', 'ij'], ['0', 'ab'], ['6', 'cd'], ['0', 'ef'], ['6', 'gh'], ['0', 'ij'], ['4', 'that'], ['3', 'be'], ['0', 'to'], ['1', 'be'], ['5', 'question'], ['1', 'or'], ['2', 'not'], ['4', 'is'], ['2', 'to'], ['4', 'the'], ] const expected = '- - - - - to be or not to be - that is the question - - - -' const actual = sort(arr) expect(actual).toBe(expected) }) }) }) <file_sep>const express = require('express'); const app = express(); const path = require('path'); const port = 3001; app.all('*', function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); next(); }); app.get('/test', (_req, res) => { res.json({ test: 'test' }); }); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); }); <file_sep>function Event() { this.subscribers = []; } Event.prototype = { subscribe: function (id, fn) { this.subscribers.push([id, fn]); }, unsubscribe: function (id) { this.subscribers = this.subscribers.filter(([_id]) => _id !== id); }, startSale: function (event) { this.subscribers.forEach(([_id, subscriber]) => subscriber(event)); }, }; function Dealer(id, name) { this.id = id; this.name = name; } Dealer.prototype = { startSale: function (event) { console.log(`${this.name} start ticket sale for event ${event}!!!`); }, }; const ticketUA = new Dealer(1, 'Ticket UA'); const karabas = new Dealer(2, 'Karabas'); const ev = new Event(); ev.subscribe(ticketUA.id, ticketUA.startSale.bind(ticketUA)); ev.subscribe(karabas.id, karabas.startSale.bind(karabas)); ev.startSale('IT Arena'); ev.unsubscribe(karabas.id); ev.startSale('Lviv JS'); <file_sep>/* 1. create array with counts by index 2. modify array - every index stores sum of prev count - e.g. i = i + [i-1] 3. rotate clockwise (arr.unshift()) 4. place elements - get element from unsorted array - get value from shifted array by index - calculate index in sorted array - e.g. i = value + count - update element count */ function sort(arr) { const counts = getArrayWithCounts(arr) const sum = sumCounts(counts) const shifted = moveArray(sum) const sorted = placeElements(arr, shifted) return sorted } function getArrayWithCounts(arr) { const counts = arr.reduce((acc, number) => { if (number > acc.length) { acc.length = number } acc[number] = acc[number] ? acc[number] + 1 : 1 return acc }, []) return Array.from(counts, (item) => item || 0) } function sumCounts(arr) { return arr.reduce((acc, el, i) => { if (i === 0) { return [el] } const prev = acc[i - 1] acc[i] = prev + el return acc }, []) } function moveArray(arr) { arr.unshift(0) return arr } function placeElements(array, shiftedCounts) { const sortedArray = [] const counts = {} for (el of array) { const count = counts[el] || 0 const position = shiftedCounts[el] + count sortedArray[position] = el counts[el] = count + 1 } return sortedArray } module.exports = { sort, getArrayWithCounts, sumCounts, moveArray, placeElements, sort, }
4bb9442664cf21719eb2491df51914de7165c271
[ "JavaScript", "Markdown" ]
41
JavaScript
mmaksymovych/training
0fc0283dd6435173e9f491c8aaa4514c0f040100
7d8ac4b68f66c054db5d7f3cd6c551a38f63d453
refs/heads/master
<file_sep>import { Component, OnInit, OnDestroy } from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; @Component({ selector: 'app-caps', templateUrl: './caps.component.html', styleUrls: ['./caps.component.css'] }) export class CapsComponent implements OnInit, OnDestroy { public id: number; private sub: any; constructor(private route:ActivatedRoute) { } ngOnInit() { this.sub = this.route.params.subscribe(params => { this.id = +params['id']; }) } ngOnDestroy() { this.sub.unsubscribe(); } }
3b138b9a29ce4a7802acb3d61b5646eb4219c658
[ "TypeScript" ]
1
TypeScript
coolJenny/front
c3cf759ccf33f763b236390c89d45605b7e6cfb4
56bd835303028ba3a7759e9cae646f6b511a6f6c
refs/heads/master
<repo_name>aliceas2/Tidy-Data<file_sep>/run_analysis.R ## Fetch # Read in test data x_test <- read.table("./data/UCI HAR Dataset/test/x_test.txt") y_test <- read.table("./data/UCI HAR Dataset/test/y_test.txt") subject_test <- read.table("./data/UCI HAR Dataset/test/subject_test.txt") # Read in train data x_train <- read.table("./data/UCI HAR Dataset/train/x_train.txt") y_train <- read.table("./data/UCI HAR Dataset/train/y_train.txt") subject_train <- read.table("./data/UCI HAR Dataset/train/subject_train.txt") ## First - modify test data # Read in labels activity_labels <- read.table("./data/UCI HAR Dataset/activity_labels.txt")[,2] features <- read.table("./data/UCI HAR Dataset/features.txt")[,2] names(x_test) = features # Filter to only mean and std select <- grepl("mean|std", features) x_test = x_test[,select] # Change Test Labels y_test[,2] = activity_labels[y_test[,1]] names(y_test) = c("Activity_ID", "Activity_Label") names(subject_test) = "Subject" # Bind data testData <- cbind(as.data.table(subject_test), y_test, x_test) ## Second - Modify train data # Read in labels names(x_train) = features # Filter to only mean and std x_train = x_train[,select] # Change Test Labels y_train[,2] = activity_labels[y_train[,1]] names(y_train) = c("Activity_ID", "Activity_Label") names(subject_train) = "Subject" # Bind data trainData <- cbind(as.data.table(subject_train), y_train, x_train) ## Merge Away! data = rbind(testData, trainData) idLabels = c("Subject", "Activity_ID", "Activity_Label") dataLabels = setdiff(colnames(data), idLabels) meltData = melt(data, id = idLabels, measure.vars = dataLabels) # tidy data set with the mean of each variable for each activity and subject tidy = dcast(meltData, Subject + Activity_Label ~ variable, mean) write.table(tidy, file = "./tidy.txt") <file_sep>/README.md # Tidy-Data ## Project for Getting and Cleaning Data Course The purpose of this project is to demonstrate your ability to collect, work with, and clean a data set. ## Deliverables You should create one R script called run_analysis.R that does the following. 1) Merges the training and the test sets to create one data set. 2) Extracts only the measurements on the mean and standard deviation for each measurement. 3) Uses descriptive activity names to name the activities in the data set 4) Appropriately labels the data set with descriptive variable names. 5) From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. ## Set Up There is minimal setup required. To set up, do the follwoing. 1) Download the data from https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip. 2) Extract the files to your desired location. 3) Set your working directory to the parent directory of the downloaded folder ```UCI HAR Dataset``` 4) Place ```run_analysis.R``` in the parent directory of the downloaded folder ```UCI HAR Dataset``` 5) Run ```source("run_analysis.R")``` 6) Running the script will create a tidy data file called ```tidy.txt``` in your working directory. <file_sep>/Codebook.md # Codebook for Tidy-Data ## Introduction One of the most exciting areas in all of data science right now is wearable computing. Companies like Fitbit, Nike, and Jawbone Up are racing to develop the most advanced algorithms to attract new users. The data linked to from the course website represent data collected from the accelerometers from the Samsung Galaxy S smartphone. ## Data Sources * Original Data: ```https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip``` * Description: ```http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones``` ## Information The experiments have been carried out with a group of 30 volunteers within an age bracket of 19-48 years. Each person performed six activities (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING) wearing a smartphone (Samsung Galaxy S II) on the waist. Using its embedded accelerometer and gyroscope, we captured 3-axial linear acceleration and 3-axial angular velocity at a constant rate of 50Hz. The experiments have been video-recorded to label the data manually. The obtained dataset has been randomly partitioned into two sets, where 70% of the volunteers was selected for generating the training data and 30% the test data. The sensor signals (accelerometer and gyroscope) were pre-processed by applying noise filters and then sampled in fixed-width sliding windows of 2.56 sec and 50% overlap (128 readings/window). The sensor acceleration signal, which has gravitational and body motion components, was separated using a Butterworth low-pass filter into body acceleration and gravity. The gravitational force is assumed to have only low frequency components, therefore a filter with 0.3 Hz cutoff frequency was used. From each window, a vector of features was obtained by calculating variables from the time and frequency domain. See 'features_info.txt' for more details. ## Included Files * 'README.txt' * 'Tidy.txt' * 'Codebook.md' * 'run_analysis.R' * 'UCI HAR Dataset' Note: UCI HAR Dataset is included but the files are not needed if you downloaded as instructed in the README.md file. ## Transformation Details 1. Merges the training and the test sets to create one data set. 2. Extracts only the measurements on the mean and standard deviation for each measurement. 3. Uses descriptive activity names to name the activities in the data set 4. Appropriately labels the data set with descriptive activity names. 5. Creates independent tidy data set with the average of each variable for each activity and each subject. ## Transformation Implementation run_analysis.R performs all transformation steps necessary by doing the following. * Loads all data, * Loads the labels, * Extract the mean and standard deviation column names and data, * Processes both test and train data, * Merges the test and train data, * Creates a 'tidy.txt' file.
25742e2c0f66deb112cc3839c88e39a26eea53c7
[ "Markdown", "R" ]
3
R
aliceas2/Tidy-Data
acc077b9e2294971dd571847f6426838c9127930
cba3d1214843108c9a724afa5f7ac8f008a0e96e
refs/heads/master
<file_sep>#' robustODE function #' #' @export robustODE <- function(LS, init = initPars, crit.Tukey = 0.01, crit.huber = 0.05, optim.ctrl, resODE, maxit = 10) { environment(LS) <- environment() if (missing(resODE)) stop("Provide function to calculate residual") ## ========================================================================= ## IRLS and robust ## ========================================================================= # 1. Obtain starting values. ## ------------------------------------------------------------------------- # Use OLS to compute residuals and message("Step 1. Estimating initial scale and weights") weighted <- FALSE fit <- optim(init, LS, optim.ctrl) e <- resODE(fit) s <- mad(e) # MAD scale median(abs(resid))/0.6745 # 2. Huber estimation: ## ------------------------------------------------------------------------- # Use Huber function with C = 1.345. es <- abs(e) / s old.Huber <- w <- first.w <- getWeight(es, "Huber") # iteration until the maximum change in weights value is less than 0.05. hubercv <- FALSE weighted <- TRUE CheckConv <- function(old, current, crit) { change <- abs(current - old) # absolute changes return(max(change) < crit) } message("Step 2. Starting Huber estimation...") iter <- 0 while(!hubercv) { iter <- iter + 1 message("H-iter: ", iter) current.fit <- optim(init, LS, optim.ctrl) current.e <- resODE(current.fit) current.s <- mad(current.e) # MAD scale median(abs(resid))/0.6745 current.es <- abs(current.e) / current.s current.Huber <- getWeight(current.es, "Huber") convergedH <- CheckConv(old.Huber, current.Huber, crit.huber) if (convergedH) { hubercv <- TRUE message("Huber weights converged!") } else if (iter == maxit) { hubercv <- TRUE message("Huber weights are not converged after ", maxit, " iterations!") message("Continuing Tukey step") } else { old.Huber <- w <- current.Huber } } # 3. Tukey estimation: ## ------------------------------------------------------------------------- # Calculate case weight by using the biweight function with c = 4.685. tukeycv <- FALSE iter <- 0 old.Tukey <- w <- getWeight(current.es, "biweight") message("Step 3. Starting Tukey estimation...") while(!tukeycv) { iter <- iter + 1 message("T-iter: ", iter) current.fit <- optim(init, LS, optim.ctrl) current.e <- resODE(current.fit) current.s <- mad(current.e) # MAD scale median(abs(resid))/0.6745 current.es <- abs(current.e) / current.s current.Tukey <- getWeight(current.es, "biweight") convergedT <- CheckConv(old.Tukey, current.Tukey, crit.Tukey) if (convergedT) { tukeycv <- TRUE message("Tukey weights converged!") } else if (iter == maxit) { tukeycv <- TRUE message("Tukey weights are not converged after ", maxit, " iterations!") } else { old.Tukey <- w <- current.Tukey } } message("Done") # return(list(L2 = fit$par, robust = current.fit$par) ) return(list(L2 = fit$par, robust = current.fit$par, first.w = first.w, first.r = e, final.w = current.Tukey, final.r = current.e)) } <file_sep># Clean the web ## Philosophy No big deals, just use adblock to **remove annoying, garbage, and bias areas on a website, but keeping an usable website, and more friendly user interface if possible**. Code will be tidied up gradually. The worse the content, the more info are blocked, prevent the stupid info to spread. Keeping the news as its nature: delivering only the pure info. Focusing on news site, starting with Vietnamese, for example: [before](http://i.imgur.com/LxxeX72.jpg) and [after](http://i.imgur.com/qILnAiL.jpg). Sometimes it could become too extreme because of bad coding of website. Btw, sorry web designer for their efforts (this ironically including me). ## Rules The following site' sections will be considered to be removed, by order 1. Comments blocks - Ridiculous polls, statistics - Redundant spaces, e.g., useless header and footer, - Recommendation blocks - Floating boxes - Abusing use of tags lines - Share buttons - Embded unrelated videos (usually at the bottom) - Rich images blocks - Newsletter boxes - Info from another sources - Tags cloud - Unhonest "hot/top" news, - Reupload videos, images (some site does have time to do this) Will be extended! ## How to - Install [adblock](https://getadblock.com/) - Append the filter list content here to your filter # Lists of website included Let me know if your frequently visit website is not included. 1. 2sao.vn - 4231.vn - 8showbiz.com - addictivetips.com - afamily.vn - allvpop.com - alobacsi.com - anninhthudo.vn - antt.vn - antv.gov.vn - askubuntu.com - atgt.vn - autopro.com.vn - baodatviet.vn - baodautu.vn - baodientu.chinhphu.vn - baodongkhoi.com.vn - baodongnai.com.vn - baogiaothong.vn - baophapluat.vn - baophuyen.com.vn - baotintuc.vn - batdongsan.vietnamnet.vn - bbc.com - biphim.com - bizlive.vn - blogtamsu.vn - bongda.com.vn - bongdaplus.vn - bongdaso.com - cafebiz.vn - cafef.vn - cafeland.vn - cand.com.vn - cherryradio.com.au - chiasenhac.com - citeseerx.ist.psu.edu - dailymail.co.uk - danong.com - dantri.com.vn - danviet.vn - dautubds.baodautu.vn - dep.com.vn - diendan.vietgiaitri.com - docbao.com.vn - doisong.vn - doisongphapluat.com - download.chiasenhac.com - dulich.vnexpress.net - echip.com.vn - edition.cnn.com - en.wikipedia.org - findaphd.com - foxnews.com - fshare.vn - fsharefilm.com - genk.vn - giadinh.net.vn - giadinhvn.vn - giaoduc.net.vn - giaoducthoidai.vn - google.de - hanoimoi.com.vn - huffingtonpost.com - huffingtonpost.de - ictnews.vn - ictpress.vn - ihay.thanhnien.com.vn - infonet.vn - inlook.vn - ione.vnexpress.net - keeng.vn - kenh13.info - kenh14.vn - kenhcongnghe.vn - khampha.vn - kienthuc.net.vn - laodong.com.vn - lite.baomoi.com - megafun.vn - monbalcon.net - motthegioi.vn - mp3.zing.vn - muare.vn - nbcnews.com - news.go.vn - news.ringring.vn - news.yahoo.com - news.zing.vn - ngoisao.net - ngoisao.vn - nguoi-viet.com - nguoiduatin.vn - nguoivietphone.com - nhac.vui.vn - nhaccuatui.com - nhandan.com.vn - nhipsongso.tuoitre.vn - nld.com.vn - nongnghiep.vn - omgubuntu.co.uk - phapluattp.vn - phununews.vn - phunuonline.com.vn - playlist.chiasenhac.com - quantrimang.com.vn - r-bloggers.com - r.789695.n4.nabble.com - reiseauskunft.bahn.de - rfa.org - ringring.vn - sannhac.com - saoonline.vn - sggp.org.vn - snt148.mail.live.com - soha.vn - songkhoe.vn - stardaily.vn - suckhoedoisong.vn - superuser.com - taiphimhd.com - takataka.coccoc.com - tamguong.vn - tamnhin.net - tccl.info - techblog.vn - thanhnien.com.vn - thegioi.baotintuc.vn - thegioitre.vn - theguardian.com - thethao.tuoitre.vn - thethao.vietnamnet.vn - thethaovanhoa.vn - thoibaotaichinhvietnam.vn - tienphong.vn - tiin.vn - tinhte.vn - tinmoi.vn - tinngan.vn - tinnhanhchungkhoan.vn - tinthethao.com.vn - tintuconline.com.vn - tivituansan.com.au - ttvn.vn - tuanvietnam.vietnamnet.vn - tuoitre.vn - ubuntu.com - uk.reuters.com - uploaded.net - us.24h.com.vn - us.baoduhoc.vn - usatoday.com - vef.vn - vi.rfi.fr - viet-times.com.au - vietbao.com - vietbao.vn - vietnamnet.vn - vietnamplus.vn - vietq.vn - vimeo.com - vitalk.vn - vn-zoom.com - vneconomy.vn - vnexpress.net - vnmedia.vn - voatiengviet.com - voh.com.vn - vov.vn - vovgiaothong.vn - vtc.vn - vtv.vn - webtretho.com - windowscentral.com - xaluan.com - yan.vn - yeah1.com - youtube.com and others... Cheers, <file_sep>#' Priors function #' #' Add background and grid lines similar to ggplot. #' @param bg (string) Background color Defaults to "gray90". #' @param cols (string) Gridlines color Defaults to "white". #' @keywords grid #' @export #' @examples #' Priors() Priors <- function(value = 1, a = 0, b = 1, dists = c('normal', 'gamma', 'uniform'), logp = TRUE) { dists <- match.arg(dists) if (value=='random') { switch(dists, normal = rnorm(1, a, b), gamma = rgamma(1, a, b), uniform = runif(1, a, b)) } else { switch(dists, normal = dnorm(value, a, b, log=logp), gamma = dgamma(value, a, b, log=logp), uniform = dunif(value, a, b, log=logp)) } }<file_sep>#' MetropolisAP function #' #' Using fixed range covariance adjusting strategy. #' @param bg (string) Background color Defaults to "gray90". #' @param cols (string) Gridlines color Defaults to "white". #' @keywords grid #' @export #' @examples #' MetropolisAP() MetropolisAP <- function(Y, # the data tData, # corresponding time points Inits = smidR:::state,# Vector of initial values model = smidR::UIV, # Model for deSolve tODE = smidR:::times,# Time evaluating with deSolve Sidm = c(3), # indices of the observed state in model Sidd = c(1), # indices of the observed state in data nPars = 5, # number of parameters nStates = 3, # number of equations in the model vPriors, # require uniSteps = 0.1, gui = FALSE, nPost = 1000, rMonitor = 500, nTunes = 10, n.chains = 3, Burnin = nTunes * rMonitor, thinning = 1, unitarget = 0.45, target = 0.35, largetarget = 0.234, acceptTol = 0.075, optim = FALSE, Scale = 2.38) { startt <- proc.time() tData <- as.character(tData) # avoid rounding error nReps <- rle(tData)$length # save time computing LL tData <- unique(tData) minusLLL <- function(x) { pB <- x[1] pD <- x[2] pP <- x[3] pC <- x[4] noise <- x[5] paras <- c(pB = pB, pD = pD, pP = pP, pC = pC) tryCatch( { out <- deSolve::ode(Inits, tODE, model, 10^(paras)) yhat <- out[as.character(out[,1]) %in% tData, "V"] if (any(yhat < 0)) { # message("Predict negative viral load, ABORT!") mll <- 1e+8 return(mll) } else { # Number of replicates # Run Length Encoding # nm <- rle(tData)$lengths # x <- Y[Sidd,] - rep(log10(yhat), times = nm) x <- Y - rep(log10(yhat), times = nReps) ll <- dnorm(x, mean = 0, sd = noise, log = TRUE) mll <- -sum(ll) return(mll) } }, error = function(e) { message(e) mll <- 1e+8 return(mll) } ) } findLL <- function(params, noise) { tryCatch( { # Run ODE, get UIV and sensitivities XData <- deSolve::ode(Inits, tODE, model, 10^(params)) # par in raw scale XData <- XData[as.character(XData[,1]) %in% tData, "V"] # XData <- XData[,-1] # in raw scale, removing time # Xpred <- t(XData[, 1:nStates]) # replicate because many measurements per time point # nReps <- rle(tData)$length Xpred <- rep(XData, times = nReps) error <- Y - log10(Xpred) # error <- log10(rep(Xpred[Sidm,], times = nReps)) - Y[Sidd,] # Calculate the log-likelihoods of the parameters # # Calculate the current likelihoods of the current X estimates # Noting that the estimates are in raw scale tempLL <- sum(dnorm(error, mean = 0, sd = noise, log=TRUE)) return(tempLL) }, warning = function(warn) { # message(warn) tempLL <- -1e300 return(tempLL) }, error=function(e) { message(e) tempLL <- -1e300 return(tempLL) }) } # Jump <- function(params, mu, Sigma, noise) { # foo <- mvtnorm::dmvnorm(params, mu, Sigma, TRUE) # if( is.na(foo) ) foo <- -1e300 # foo <- foo + Priors(noise, vPriors$firstM[5], # vPriors$secondM[5], vPriors$family[5]) # if (foo == 0 | is.na(foo)) foo = -1e300 # return(foo) # } naiveMu <- vPriors$firstM[-5] naiveSigma <- InitSigma() naivePars <- MASS::mvrnorm(n = 1, naiveMu, naiveSigma) naiveNoise <- Priors('random', vPriors$firstM[5], vPriors$secondM[5], vPriors$family[5]) lower <- c(qnorm(1e-4, vPriors$firstM[1:4], vPriors$secondM[1:4]), qunif(1e-4, vPriors$firstM[5], vPriors$secondM[5])) upper <- c(qnorm(1-1e-4, vPriors$firstM[1:4], vPriors$secondM[1:4]), qunif(1-1e-4, vPriors$firstM[5], vPriors$secondM[5])) fit <- NULL if (optim) { message("\nEstimating asymtotic posterior covariance matrix...") # Generating starting values for finding covariance matrix Starts <- c(naivePars, naiveNoise) fit <- tryCatch({ fit <- optim(Starts, minusLLL, method = "L-BFGS-B", lower = lower, upper = upper, control = list(trace=1), hessian = TRUE) }, error = function(e) { message("Failed to estimates the posterior asymtotic covariance matrix, use naive sigma") message(e) return(NULL) }) } # This part can add option robust to make positive definite # and handling error of not able to inverse if (!is.null(fit)) { fisher_info <- solve(fit$hessian[1:4, 1:4]) prop_sigma <- sqrt(diag(fisher_info)) Sigma <- diag(prop_sigma) * (Scale^2) / 4 } else { Sigma <- InitSigma(std = 0.5) } # print(Sigma) message("\nInitialisation Completed. Computing chains...") # ===================================================================== chainFn <- function(...) { # Still starting at random, but propose using the estimated covariance if ( optim & (!is.null(fit)) ) { Pars <- MASS::mvrnorm(n = 1, fit$par[1:4], Sigma) Noise <- fit$par[5] + rnorm(1) * uniSteps } else { Pars <- MASS::mvrnorm(n = 1, naiveMu, Sigma) Noise <- naiveNoise + rnorm(1) * uniSteps } Pars <- setNames(Pars, c("pB", "pD", "pP", "pC")) CurrentLL <- findLL(Pars, Noise) # Set up proposal counters Accepted <- rep(0, 2) Mutation <- rep(0, 2) # Set up parameter history variable ParaHistory <- matrix(0, nPost, nPars) LLHistory <- vector('numeric', nPost) #only one state # Store the burnIn for adjusting JUMP BurnResults <- matrix(0, Burnin, nPars) # Initialise iteration number nIter <- 0 Continue <- TRUE Converged <- FALSE # Main loop while (Continue) { nIter = nIter + 1 if(nIter %% rMonitor == 0) cat('iter ', nIter, '\n') NewParas <- MASS::mvrnorm(n = 1, Pars, Sigma) Mutation[1] <- Mutation[1] + 1 # checking boundary isInBound <- all(NewParas[-5] < upper[-5] & NewParas[-5] > lower[-5]) if (isInBound == FALSE | any(is.na(NewParas)) ) { badMove <- TRUE } else { badMove <- FALSE } # JumpBack <- Jump(Pars, NewParas, Sigma, Noise) # the same # JumpNext <- Jump(NewParas, Pars, Sigma, Noise) # the same isAccept <- FALSE if (badMove == FALSE) { ProposedLL <- findLL(NewParas, Noise) Ratio <- ProposedLL - CurrentLL # Ratio <- ProposedLL - CurrentLL + JumpBack - JumpNext isAccept <- !is.na(Ratio) & ( Ratio > 0 | (Ratio > log(runif(1))) ) } if (isAccept) { Pars <- NewParas CurrentLL <- ProposedLL Accepted[1] <- Accepted[1] + 1 } # Now mutating the noise given the new (if updated)/current par newNoise <- Noise + rnorm(1) * uniSteps Mutation[2] <- Mutation[2] + 1 ProposedLL <- findLL(Pars, newNoise) isAccept <- FALSE Ratio <- ProposedLL - CurrentLL isAccept <- !is.na(Ratio) & ( Ratio > 0 | (Ratio > log(runif(1))) ) if (isAccept) { Noise <- newNoise CurrentLL <- ProposedLL Accepted[2] <- Accepted[2] + 1 } # Save parameters if converged and according to thinning rate if (Converged & (nIter %% thinning)==0 ) { ParaHistory[(nIter-nIterConverg)/thinning, 1:4] <- Pars ParaHistory[(nIter-nIterConverg)/thinning, 5] <- Noise LLHistory[(nIter-nIterConverg)/thinning] <- CurrentLL } # If not yet converged if (!Converged) { # Save parameters in burn in for adjusting BurnResults[nIter, 1:4] <- Pars BurnResults[nIter, 5] <- Noise # Adjust parameter proposal widths if (nIter > rMonitor & (nIter %% rMonitor) == 1) { message("Iteration", nIter) message(rep('=', 80)) arate <- Accepted/Mutation cat(100*arate[1], '% mutation acceptance for parameter ', 1:4, '\n') cat(100*arate[2], '% mutation acceptance for parameter ', 5, '\n') # Adjust JUMP if out range outBound <- (arate[1] < (target - acceptTol) | arate[1] > (target + acceptTol)) if (outBound) { # Update default scale Scale <- tuneScale(Scale, arate[1], targetRate = target) # update cov region <- (nIter - rMonitor):(nIter - 1) covv <- cov(BurnResults[region, 1:4]) Sigma <- tuneCov(covv, Sigma) * (Scale^2) /4 } # Adjust for sd if (arate[2] < (unitarget - acceptTol)) { uniSteps <- uniSteps * 0.9 } else if (arate[2] > (unitarget + acceptTol)) { uniSteps <- uniSteps * 1.1 } message('Current estimates: ') cat(round(BurnResults[nIter,], 5), "\n") # Reset counters Accepted <- rep(0, 2) Mutation <- rep(0, 2) } if (nIter >= Burnin) { Converged <- TRUE nIterConverg <- nIter message("\n", rep('=', 80)) message('Stop tuning at iteration number ', nIterConverg, "\n") cat('Accepted rate ', arate, "\n") message(rep('=', 80)) } } else if (nIter == nIterConverg + nPost * thinning) { Continue <- FALSE } } colnames(ParaHistory) <- colnames(BurnResults) <- c("pB", "pD", "pP", "pC","sd") attr(ParaHistory, "mcpar") <- c(thinning, nPost*thinning, thinning) attr(BurnResults, "mcpar") <- c(1, Burnin, thinning) attr(ParaHistory, "class") <- attr(BurnResults, "class") <- "mcmc" return(list(ParaHistory = ParaHistory, LLHistory = LLHistory, Burn = BurnResults)) } #end chains # ===================================================================== OutParallel <- do.call( c, parallel::mclapply(seq_len(n.chains), chainFn, mc.cores = n.chains, mc.silent = FALSE)) MCMClist <- OutParallel[c(1, 4, 7)] LLlist <- OutParallel[c(2, 5, 8)] Burnlist <- OutParallel[c(3, 6, 9)] class(MCMClist) <- class(Burnlist) <- "mcmc.list" endt <- proc.time() - startt return(list(MCMC = MCMClist, Burn = Burnlist, LL = LLlist, runtime = endt)) }<file_sep>#' UIV model #' #' Add background and grid lines similar to ggplot. #' @param bg (string) Background color Defaults to "gray90". #' @param cols (string) Gridlines color Defaults to "white". #' @keywords grid #' @export #' @examples #' UIV() UIV = function(t,state,parameters) { with(as.list(c(state,parameters)),{ dU = - pB*U*V dI = pB*U*V - pD*I dV = pP*I - pC*V list(c(dU,dI,dV)) }) } UIVsens <- function(t, state, parameters) { with(as.list(c(state, parameters)), { dU = - pB*U*V dI = pB*U*V - pD*I dV = pP*I - pC*V dUb = -pB*V*Ub - pB*U*Vb - U*V dIb = -pD*Ib + pB*U*Vb + pB*V*Ub + U*V dVb = -pC*Vb + pP*Ib dUd = -pB*V*Ud - pB*U*Vd dId = -pD*Id + pB*U*Vd + pB*V*Ud - I dVd = -pC*Vd + pP*Id dUp = -pB*V*Up - pB*U*Vp dIp = -pD*Ip + pB*U*Vp + pB*V*Up dVp = -pC*Vp + pP*Ip + I dUc = -pB*V*Uc - pB*U*Vc dIc = -pD*Ic + pB*U*Vc + pB*V*Uc dVc = -pC*Vc + pP*Ic - V list(c(dU, dI, dV, dUb, dIb, dVb, dUd, dId, dVd, dUp, dIp, dVp, dUc, dIc, dVc)) }) } UIVsens2 <- function(t, state, parameters) { with(as.list(c(state, parameters)), { dU = - pB*U*V dI = pB*U*V - pD*I dV = pP*I - pC*V dUb = -pB*V*Ub - pB*U*Vb - U*V dIb = -pD*Ib + pB*U*Vb + pB*V*Ub + U*V dVb = -pC*Vb + pP*Ib dUd = -pB*V*Ud - pB*U*Vd dId = -pD*Id + pB*U*Vd + pB*V*Ud - I dVd = -pC*Vd + pP*Id dUp = -pB*V*Up - pB*U*Vp dIp = -pD*Ip + pB*U*Vp + pB*V*Up dVp = -pC*Vp + pP*Ip + I dUc = -pB*V*Uc - pB*U*Vc dIc = -pD*Ic + pB*U*Vc + pB*V*Uc dVc = -pC*Vc + pP*Ic - V # dUbb = (- pB * Vb - V ) * Ub + ( -pB * Ub - U ) * Vb - V * Ub - U * Vb dUbb = - 2 * pB * Vb * Ub - 2 * V * Ub - 2 * U * Vb # dIbb = (pB * Vb + V ) * Ub + ( pB * Ub + U ) * Vb + V * Ub + U * Vb dIbb = 2 * pB * Vb * Ub + 2 * V * Ub + 2 * U * Vb dVbb = 0 dUbd = - pB * Vd * Ub - pB * Ud * Vb - V * Ud - U * Vd dIbd = pB * Vd * Ub - Ib + pB * Ud * Vb + V * Ud + U * Vd dVbd = 0 dUbp = - pB * Vp * Ub - pB * Up * Vb - V * Up - U * Vp dIbp = pB * Vp * Ub + pB * Up * Vb + V * Up + U * Vp dVbp = Ib dUbc = - pB * Vc * Ub - pB * Uc * Vb - V * Uc - U * Vc dIbc = pB * Vc * Ub + pB * Uc * Vb + V * Uc + U * Vc dVbc = - Vb dUdd = - pB * Vd * Ud - pB * Ud * Vd dIdd = pB * Vd * Ud - Id + pB * Ud * Vd - Id dVdd = 0 dUdp = - pB * Vp * Ud - pB * Up * Vd dIdp = pB * Vp * Ud + pB * Up * Vd - Ip dVdp = Id dUdc = - pB * Vc * Ud - pB * Uc * Vd dIdc = pB * Vc * Ud + pB * Uc * Vd - Ic dVdc = - Vd dUpp = - pB * Vp * Up - pB * Up * Vp dIpp = pB * Vp * Up + pB * Up * Vp dVpp = 2 * Ip + Ip dUpc = - pB * Vc * Up - pB * Uc * Vp dIpc = pB * Vc * Up + pB * Uc * Vp dVpc = - Vp + Ic dUcc = - pB * Vc * Uc - pB * Uc * Vc dIcc = pB * Vc * Uc + pB * Uc * Vc dVcc = - 2 * Vc # list(c(dU, dI, dV, dUb, dIb, dVb, dUd, dId, dVd, dUp, dIp, dVp, dUc, dIc, dVc)) list(c(dU, dI, dV, dUb, dIb, dVb, dUd, dId, dVd, dUp, dIp, dVp, dUc, dIc, dVc, dUbb, dIbb, dVbb, dUbd, dIbd, dVbd, dUbp, dIbp, dVbp, dUbc, dIbc, dVbc, dUdd, dIdd, dVdd, dUdp, dIdp, dVdp, dUdc, dIdc, dVdc, dUpp, dIpp, dVpp, dUpc, dIpc, dVpc, dUcc, dIcc, dVc)) }) } mparas <- c(pB = 1e-05, pD = 1.6, pP = 5, pC = 3.7) mstate1 = c(U = 1e+6, I = 0, V = 10, Ub = 0, Ib = 0, Vb = 0, Ud = 0, Id = 0, Vd = 0, Up = 0, Ip = 0, Vp = 0, Uc = 0, Ic = 0, Vc = 0) mstate2 = c(U = 1e+6, I = 0, V = 10, Ub = 0, Ib = 0, Vb = 0, Ud = 0, Id = 0, Vd = 0, Up = 0, Ip = 0, Vp = 0, Uc = 0, Ic = 0, Vc = 0, Ubb = 0, Ibb = 0, Vbb = 0, Ubd = 0, Ibd = 0, Vbd = 0, Ubp = 0, Ibp = 0, Vbp = 0, Ubc = 0, Ibc = 0, Vbc = 0, Udd = 0, Idd = 0, Vdd = 0, Udp = 0, Idp = 0, Vdp = 0, Udc = 0, Idc = 0, Vdc = 0, Upp = 0, Ipp = 0, Vpp = 0, Upc = 0, Ipc = 0, Vpc = 0, Ucc = 0, Icc = 0, Vc = 0) LogPriorDerivs <- function(parindex, Value) { # Return the partial derivative of the log(prior) w.r.t. the parameter # d(log normal)/d(x) if (parindex == 1) { PP <- (-5 - Value)/(0.5^2) } else if (parindex == 2) { PP <- ( 0 - Value)/(0.5^2) } else if (parindex == 3) { PP <- ( 1 - Value)/(0.5^2) } else if (parindex == 4) { PP <- (0.5- Value)/(0.5^2) } return(PP) } times <- seq(0, 12, by = 0.01) state <- c(U = 10^6, I = 0, V = 10) paras <- c(pBeta = 1e-05, pDelta = 1.6, pP = 5, pC = 3.7) t3 <- c( round(seq(0, 12*24, by = 3)/24, 2) ) [-1] t6 <- c( round(seq(0, 12*24, by = 6)/24, 2) ) [-1] t8 <- c( round(seq(0, 12*24, by = 8)/24, 2) ) [-1] t12 <- c( round(seq(0, 12*24, by = 12)/24, 2) ) [-1] t16 <- c( round(seq(0, 12*24, by = 16)/24, 2) ) [-1] t20 <- c( round(seq(0, 12*24, by = 20)/24, 2) ) [-1] t24 <- c( round(seq(0, 12*24, by = 24)/24, 2) ) [-1] tn1 <- c(1, 2, 3, 5, 7, 9) tn2 <- c(1, 2, 4, 5, 7, 9, 11, 12) lower = log10(c(1e-7, 1e-2, 1e+0, 1e-1)) upper = log10(c(1e-3, 1e+2, 1e+2, 1e+2)) tnames <- c('t3','t6','t8','t12','t16','t20','t24','tn1','tn2') pnames <- c("beta", "delta", "p", "c") ndata <- c(3,5,7,10,13,15,20)<file_sep>#' getWeight Huber and biweight #' #' @export getWeight <- function(es, method = c("Huber", "biweight")) { if (method == "Huber") { # Defme case weights (W_i) # W_i = 1 if |e_i| / s_i <= 1.345 # W_i = 1.345 / (|e_i| / s_i) if |e_i| / s_i > 1.345 w <- rep(1, length(es)) cons <- 1.345 index <- which(es > cons) w[index] <- cons / es[index] } else if (method == "biweight") { ## Wi = { 1 - [(e_i / s_i) / 4.685]^2 }^2 if |e_i| / s_i <= 4.685 ## Wi = 0 otherwise cons <- 4.685 w <- rep(0, length(es)) index <- which(es <= cons) w[index] <- (1 - (es[index]/cons)^2)^2 } else { stop("Only Huber and biweight is OK!") } return(w) }<file_sep>#' tuneScale function #' #' Run a single MH chain #' @param params (vector) Background color Defaults to "gray90". #' @param noise (string) Gridlines color Defaults to "white". #' @keywords log-likelihood #' @export #' @examples #' tuneScale() tuneScale <- function(currentScale, acceptRate, targetRate = 0.35) { if (acceptRate == 0) acceptRate <- 0.001 # avoid divide -Inf newScale <- currentScale * qnorm(targetRate/2) / qnorm(acceptRate/2) return(newScale) } #' tuneCov function #' #' Tuneing the cov of jumping distribution #' @param current (matrix) Current observed posterior covariance. #' @param old (matrix) The previous estimates/starting/observed posterior covariance. #' @param w (numeric) How much weigth put on observed covariance, in (0,1). #' @keywords Metropolis, Hasting, Adaptive #' @export #' @examples #' tuneCov() tuneCov <- function(currentCov, oldCov, w = 0.75) { AdjustCov <- w * currentCov + (1 - w) * oldCov # SAS adjust return(AdjustCov) } #' InitSigma function #' #' Run a single MH chain #' @param params (vector) Background color Defaults to "gray90". #' @param noise (string) Gridlines color Defaults to "white". #' @keywords log-likelihood #' @export #' @examples #' InitSigma() InitSigma <- function(npar = 4, std, scale) { if (missing(scale)) scale <- 2.38 ^2 / npar if (missing(std)) std <- 1 Sigma <- diag(rep(std, npar)) * scale return(Sigma) } # http://support.sas.com/documentation/cdl/en/statug/63033/HTML/default/viewer.htm#statug_mcmc_sect022.htm
6f5ab83b53b585087cb5c238e5f57be919c29168
[ "Markdown", "R" ]
7
R
rdditdo/CleanTheWeb
55890306f350585e1974d539f5dfd5425824fe66
1ffa1be4dc2ca85c73053f6e4fdf9f3cc86c2604
refs/heads/master
<repo_name>jjohnstz/BeerFacts<file_sep>/BeerFactsTests/TestHelper/Beer+TestHelper.swift @testable import BeerFacts extension Beer { static func testMake(name: String = "", tagline: String = "", description: String = "", image_url: String = "", target_fg: Double = 0.0, target_og: Double = 0.0, ebc: Double? = nil, srm: Double? = nil, ph: Double? = nil, attenuation_level: Double = 0.0, abv: Double = 0.0, ibu: Double? = nil, food_pairing: [String] = []) -> Beer { return Beer(name: name, tagline: tagline, description: description, image_url: image_url, target_fg: target_fg, target_og: target_og, ebc: ebc, srm: srm, ph: ph, attenuation_level: attenuation_level, abv: abv, ibu: ibu, food_pairing: food_pairing) } } <file_sep>/BeerFactsTests/Mock/MockBeerListInteractor.swift @testable import BeerFacts class MockBeerListInteractor: BeerListInteractorProtocol { public var event: BeerListViewEvent? func handle(event: BeerListViewEvent) { self.event = event } } <file_sep>/BeerFacts/Utility/ImageCacheWrapper.swift import UIKit protocol ImageCacheProtocol { func cacheAndDisplayImage(on imageView: UIImageView, imageURL: URL?) } class ImageCacheWrapper: ImageCacheProtocol { func cacheAndDisplayImage(on imageView: UIImageView, imageURL: URL?) { imageView.kf.setImage(with: imageURL) } } <file_sep>/BeerFacts/BeerList/BeerListInteractor.swift import Foundation enum BeerListViewEvent: Equatable { case viewDidLoad case didSelectIndex(Int) } protocol BeerListInteractorProtocol { func handle(event: BeerListViewEvent) } class BeerListInteractor: BeerListInteractorProtocol { private let beerService: BeerServiceProtocol private let beerListPresenter: BeerListPresenterProtocol private var beers: [Beer]? weak var view: BeerListViewProcotol? init(beerService: BeerServiceProtocol, beerListPresenter: BeerListPresenterProtocol) { self.beerService = beerService self.beerListPresenter = beerListPresenter } func handle(event: BeerListViewEvent) { switch event { case .viewDidLoad: handleViewDidLoad() case .didSelectIndex(let index): handleSelectIndex(index) } } private func handleViewDidLoad() { view?.perform(action: .showActivityIndicator(true)) beerService.getBeers() .onSuccess { (beers) in self.beers = beers let beerListViewState = self.beerListPresenter.getBeerListViewState(beers: beers) self.view?.perform(action: .display(beerListViewState)) } .onFailure { (error) in self.view?.perform(action: .errorMessage("Failed to load beers. Sorry :(")) } } private func handleSelectIndex(_ index: Int) { if let beer = beers?[index] { view?.perform(action: .routeToBeerDetails(beerName: beer.name)) } } } <file_sep>/BeerFacts/BeerList/Test/BeerListPresenterSpec.swift import Quick import Nimble @testable import BeerFacts class BeerListPresenterSpec: QuickSpec { override func spec() { describe("BeerListPresenter") { var subject: BeerListPresenter! let beer1 = Beer.testMake(name: "Beer1", tagline: "tag1", abv: 1.5) let beer2 = Beer.testMake(name: "Beer2", tagline: "tag2", abv: 2.5) let beer3 = Beer.testMake(name: "Beer3", tagline: "tag3", abv: 3.5) var viewState: BeerListViewState! beforeEach { subject = BeerListPresenter() viewState = subject.getBeerListViewState(beers: [beer1, beer2, beer3]) } it("should have created correct viewStates") { expect(viewState.beerTableViewStates[0].name).to(equal(beer1.name)) expect(viewState.beerTableViewStates[0].tagLine).to(equal(beer1.tagline)) expect(viewState.beerTableViewStates[0].abv).to(equal("\(beer1.abv) %")) expect(viewState.beerTableViewStates[1].name).to(equal(beer2.name)) expect(viewState.beerTableViewStates[1].tagLine).to(equal(beer2.tagline)) expect(viewState.beerTableViewStates[1].abv).to(equal("\(beer2.abv) %")) expect(viewState.beerTableViewStates[2].name).to(equal(beer3.name)) expect(viewState.beerTableViewStates[2].tagLine).to(equal(beer3.tagline)) expect(viewState.beerTableViewStates[2].abv).to(equal("\(beer3.abv) %")) } } } } <file_sep>/BeerFactsTests/TestConfiguration.swift import Quick import KIF class TestConfiguration: QuickConfiguration { override class func configure(_ configuration: Quick.Configuration) { KIFEnableAccessibility() } } <file_sep>/BeerFactsTests/Mock/MockImageCache.swift import UIKit @testable import BeerFacts class MockImageCache: ImageCacheProtocol { var inputImageView: UIImageView? var inputImageURL: URL? func cacheAndDisplayImage(on imageView: UIImageView, imageURL: URL?) { inputImageView = imageView inputImageURL = imageURL } } <file_sep>/BeerFacts/AppDelegate.swift import UIKit import Swinject import SwinjectStoryboard class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var assembler: Assembler? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Instantiate a window. let window = UIWindow(frame: UIScreen.main.bounds) window.makeKeyAndVisible() self.window = window let assemblies: [Assembly] = [MainAssembly()] assembler = Assembler(assemblies, container: SwinjectStoryboard.defaultContainer) // Instantiate the root view controller from swinject let storyboard = SwinjectStoryboard.create(name: "BeerList", bundle: nil, container: SwinjectStoryboard.defaultContainer) window.rootViewController = storyboard.instantiateInitialViewController() return true } } <file_sep>/BeerFacts/BeerDetails/BeerDetailsViewController.swift import Foundation import UIKit import Kingfisher enum BeerDetailsViewAction: Equatable { case showActivityIndicator(Bool) case display(BeerDetailsViewState) case errorMessage(String) } protocol BeerDetailsViewProcotol: class { func perform(action: BeerDetailsViewAction) } class BeerDetailsViewController: UIViewController, BeerDetailsViewProcotol { enum AccessibilityLabel { static let activityIndicator = "activityIndicator" static let imageView = "imageView" static let nameLabel = "nameLabel" static let tagLabel = "tagLabel" static let ibuLabel = "ibuLabel" static let abvLabel = "abvLabel" static let descriptionLabel = "descriptionLabel" static let stackView = "stackView" static let errorLabel = "errorLabel" } @IBOutlet weak var activityIndicator: UIActivityIndicatorView! { didSet { activityIndicator.accessibilityLabel = AccessibilityLabel.activityIndicator } } @IBOutlet weak var nameLabel: UILabel! { didSet { nameLabel.accessibilityLabel = AccessibilityLabel.nameLabel } } @IBOutlet weak var tagLabel: UILabel! { didSet { tagLabel.accessibilityLabel = AccessibilityLabel.tagLabel } } @IBOutlet weak var ibuLabel: UILabel! { didSet { ibuLabel.accessibilityLabel = AccessibilityLabel.ibuLabel } } @IBOutlet weak var abvLabel: UILabel! { didSet { abvLabel.accessibilityLabel = AccessibilityLabel.abvLabel } } @IBOutlet weak var descriptionLabel: UILabel! { didSet { descriptionLabel.accessibilityLabel = AccessibilityLabel.descriptionLabel } } @IBOutlet weak var stackView: UIStackView! { didSet { stackView.accessibilityLabel = AccessibilityLabel.stackView } } @IBOutlet weak var errorLabel: UILabel! { didSet { errorLabel.accessibilityLabel = AccessibilityLabel.errorLabel } } @IBOutlet weak var imageView: UIImageView! { didSet { imageView.accessibilityLabel = AccessibilityLabel.imageView } } private var beerName: String? private var viewState: BeerDetailsViewState? { didSet { guard let viewState = viewState else { return } activityIndicator.isHidden = true errorLabel.isHidden = true stackView.isHidden = false imageView.isHidden = false nameLabel.text = viewState.name tagLabel.text = viewState.tagline descriptionLabel.text = viewState.description abvLabel.text = viewState.abv ibuLabel.text = viewState.ibu imageCache.cacheAndDisplayImage(on: imageView, imageURL: viewState.imageURL) for pairing in viewState.foodPairings { let label = UILabel() label.text = pairing label.numberOfLines = 0 label.lineBreakMode = .byWordWrapping label.font = UIFont.systemFont(ofSize: 15) stackView.addArrangedSubview(label) } } } private var interactor: BeerDetailsInteractorProtocol! private var router: SegueRouterProtocol! private var imageCache: ImageCacheProtocol! func inject(interactor: BeerDetailsInteractorProtocol, router: SegueRouterProtocol, imageCache: ImageCacheProtocol) { self.interactor = interactor self.router = router self.imageCache = imageCache } func configure(beerName: String) { self.beerName = beerName } override func viewDidLoad() { if let beerName = beerName { interactor.handle(event: .viewDidLoad(beerName: beerName)) } } func perform(action: BeerDetailsViewAction) { switch(action) { case .showActivityIndicator(let show): handleShowActivityIndicator(show) case .display(let viewState): self.viewState = viewState case .errorMessage(let message): handleErrorMessage(message) } } private func handleShowActivityIndicator(_ show: Bool) { activityIndicator.isHidden = !show errorLabel.isHidden = true stackView.isHidden = true imageView.isHidden = true } private func handleErrorMessage(_ message: String) { activityIndicator.isHidden = true errorLabel.isHidden = false stackView.isHidden = true imageView.isHidden = true errorLabel.text = message } } <file_sep>/BeerFactsTests/Mock/MockBeerDetailsInteractor.swift @testable import BeerFacts class MockBeerDetailsInteractor: BeerDetailsInteractorProtocol { public var event: BeerDetailsViewEvent? func handle(event: BeerDetailsViewEvent) { self.event = event } } <file_sep>/BeerFacts/BeerDetails/BeerDetailsInteractor.swift import Foundation enum BeerDetailsViewEvent: Equatable { case viewDidLoad(beerName:String) } protocol BeerDetailsInteractorProtocol { func handle(event: BeerDetailsViewEvent) } class BeerDetailsInteractor: BeerDetailsInteractorProtocol { weak var view: BeerDetailsViewProcotol? private let beerService: BeerServiceProtocol private let presenter: BeerDetailsPresenterProtocol init(beerService: BeerServiceProtocol, presenter: BeerDetailsPresenterProtocol) { self.beerService = beerService self.presenter = presenter } func handle(event: BeerDetailsViewEvent) { switch event { case .viewDidLoad(let beerName): handleViewDidLoad(with: beerName) } } private func handleViewDidLoad(with beerName: String) { view?.perform(action: .showActivityIndicator(true)) beerService.getBeer(withName: beerName) .onSuccess { (beer) in let viewState = self.presenter.getViewState(beer: beer) self.view?.perform(action: .display(viewState)) } .onFailure { (error) in self.view?.perform(action: .errorMessage("Failed to load beers. Sorry :(")) } } } <file_sep>/BeerFacts/BeerList/Test/BeerListTableViewCellSpec.swift import Quick import Nimble @testable import BeerFacts class BeerListTableViewCellSpec: QuickSpec { override func spec() { describe("BeerListTableViewCell") { var subject: BeerListTableViewCell! let viewState = BeerListTableViewState(name: "beerName", tagLine: "beer tag line", abv: "10.0 %") beforeEach { subject = Bundle.main.loadNibNamed("BeerListTableViewCell", owner: nil, options: nil)?.first as! BeerListTableViewCell subject.configure(with: viewState) TestView.displayTableViewCell(subject) } it("should have configured labels") { let nameLabel = self.tester().waitForView(withAccessibilityLabel: BeerListTableViewCell.AccessibilityLabel.nameLabel) as! UILabel let tagLabel = self.tester().waitForView(withAccessibilityLabel: BeerListTableViewCell.AccessibilityLabel.tagLabel) as! UILabel expect(nameLabel.text).to(equal(viewState.name)) let abvLabel = self.tester().waitForView(withAccessibilityLabel: BeerListTableViewCell.AccessibilityLabel.abvLabel) as! UILabel expect(nameLabel.text).to(equal(viewState.name)) expect(tagLabel.text).to(equal(viewState.tagLine)) expect(abvLabel.text).to(equal(viewState.abv)) } } } } <file_sep>/Podfile # Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'BeerFacts' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for BeerFacts pod 'Alamofire' pod 'BrightFutures' pod 'Kingfisher' pod 'Swinject' pod 'SwinjectStoryboard' target 'BeerFactsTests' do inherit! :search_paths # Pods for testing pod 'Quick' pod 'Nimble' pod 'KIF', :configurations => ['Debug'] end end <file_sep>/BeerFacts/Utility/SegueRouter.swift import Foundation import UIKit protocol SegueRouterProtocol { func route(from viewController: UIViewController, to segueIdentifier: String, handler: ((UIViewController) -> Void)?) } class SegueRouter: SegueRouterProtocol { var handler: ((UIViewController) -> Void)? func route(from viewController:UIViewController, to segueIdentifier: String, handler: ((UIViewController) -> Void)? = nil ) { self.handler = handler viewController.performSegue(withIdentifier: segueIdentifier, sender: self) } } <file_sep>/BeerFacts/Services/Test/BeerSpec.swift import Quick import Nimble @testable import BeerFacts class BeerSpec: QuickSpec { override func spec() { describe("Beer") { var subject: [Beer]! describe("Decode Beers") { beforeEach { let bundle = Bundle(for: type(of: self)) let fileUrl = bundle.url(forResource: "GetBeersFixture", withExtension: "json") let jsonData: Data = try! Data(contentsOf: fileUrl!) subject = try! JSONDecoder().decode([Beer].self, from: jsonData) } it("should have decoded data for first beer") { expect(subject.count).to(equal(3)) expect(subject[0].name).to(equal("Buzz")) expect(subject[0].tagline).to(equal("A Real Bitter Experience.")) expect(subject[0].description).to(equal("A light, crisp and bitter IPA brewed with English and American hops. A small batch brewed only once.")) expect(subject[0].abv).to(equal(4.5)) expect(subject[0].ibu).to(equal(60)) expect(subject[0].image_url).to(equal("https://images.punkapi.com/v2/keg.png")) expect(subject[0].target_fg).to(equal(1010)) expect(subject[0].target_og).to(equal(1044)) expect(subject[0].ebc).to(equal(20)) expect(subject[0].srm).to(equal(10)) expect(subject[0].ph).to(equal(4.4)) expect(subject[0].attenuation_level).to(equal(75)) expect(subject[0].food_pairing).to(equal(["Spicy chicken tikka masala", "Grilled chicken quesadilla", "Caramel toffee cake"])) } it("should have decoded data for second beer") { expect(subject[1].name).to(equal("<NAME>")) expect(subject[1].tagline).to(equal("You Know You Shouldn't")) expect(subject[1].description).to(equal("A titillating, neurotic, peroxide punk of a Pale Ale. Combining attitude, style, substance, and a little bit of low self esteem for good measure; what would your mother say? The seductive lure of the sassy passion fruit hop proves too much to resist. All that is even before we get onto the fact that there are no additives, preservatives, pasteurization or strings attached. All wrapped up with the customary BrewDog bite and imaginative twist.")) expect(subject[1].abv).to(equal(4.1)) expect(subject[1].ibu).to(equal(41.5)) expect(subject[1].image_url).to(equal("https://images.punkapi.com/v2/2.png")) expect(subject[1].target_fg).to(equal(1010)) expect(subject[1].target_og).to(equal(1041.7)) expect(subject[1].ebc).to(equal(15)) expect(subject[1].srm).to(equal(15)) expect(subject[1].ph).to(equal(4.4)) expect(subject[1].attenuation_level).to(equal(76)) expect(subject[1].food_pairing).to(equal(["Fresh crab with lemon", "Garlic butter dipping sauce", "Goats cheese salad", "Creamy lemon bar doused in powdered sugar"])) } it("should have decoded data for third beer") { expect(subject[2].name).to(equal("Berliner Weisse With Yuzu - B-Sides")) expect(subject[2].tagline).to(equal("Japanese Citrus Berliner Weisse.")) expect(subject[2].description).to(equal("Japanese citrus fruit intensifies the sour nature of this German classic.")) expect(subject[2].abv).to(equal(4.2)) expect(subject[2].ibu).to(beNil()) expect(subject[2].image_url).to(equal("https://images.punkapi.com/v2/keg.png")) expect(subject[2].target_fg).to(equal(1007)) expect(subject[2].target_og).to(equal(1040)) expect(subject[2].ebc).to(equal(8)) expect(subject[2].srm).to(equal(4)) expect(subject[2].ph).to(equal(3.2)) expect(subject[2].attenuation_level).to(equal(83)) expect(subject[2].food_pairing).to(equal(["Smoked chicken wings", "Miso ramen", "Yuzu cheesecake"])) } } } } } <file_sep>/BeerFactsTests/Mock/MockBeerService.swift import BrightFutures @testable import BeerFacts class MockBeerService: BeerServiceProtocol { public var getBeerStub: Promise<Beer, BeerError>? public var getBeerInput: String = "" public var getBeersStub: Promise<[Beer], BeerError>? public var didCallGetBeers: Bool = false func getBeer(withName name: String) -> Future<Beer, BeerError> { getBeerInput = name guard let stub = getBeerStub else { return Promise<Beer, BeerError>().future } return stub.future } func getBeers() -> Future<[Beer], BeerError> { didCallGetBeers = true guard let stub = getBeersStub else { return Promise<[Beer], BeerError>().future } return stub.future } } <file_sep>/BeerFacts/BeerList/BeerListPresenter.swift import Foundation struct BeerListViewState: Equatable { let beerTableViewStates: [BeerListTableViewState] } struct BeerListTableViewState: Equatable { let name: String let tagLine: String let abv: String } protocol BeerListPresenterProtocol { func getBeerListViewState(beers:[Beer]) -> BeerListViewState } class BeerListPresenter: BeerListPresenterProtocol { func getBeerListViewState(beers:[Beer]) -> BeerListViewState { var beerTableViewStates: [BeerListTableViewState] = [] for beer in beers { let beerListTableViewState = BeerListTableViewState( name: beer.name, tagLine: beer.tagline, abv: "\(beer.abv) %") beerTableViewStates.append(beerListTableViewState) } return BeerListViewState(beerTableViewStates: beerTableViewStates) } } <file_sep>/BeerFacts/BeerDetails/Test/BeerDetailsInteractorSpec.swift import BrightFutures import Quick import Nimble @testable import BeerFacts class BeerDetailsInteractorSpec: QuickSpec { override func spec() { describe("BeerDetailsInteractor") { var subject: BeerDetailsInteractor! var view: MockBeerDetailsViewController! var service: MockBeerService! var presenter: MockBeerDetailsPresenter! beforeEach { view = MockBeerDetailsViewController() service = MockBeerService() presenter = MockBeerDetailsPresenter() subject = BeerDetailsInteractor(beerService: service, presenter: presenter) subject.view = view } describe("handle events") { describe("viewDidLoad event") { var promise: Promise<Beer, BeerError>! let beerName = "Beer1" beforeEach { promise = Promise<Beer, BeerError>() service.getBeerStub = promise subject.handle(event: .viewDidLoad(beerName: beerName)) } it("should send showActivityIndicator with true") { expect(view.action).to(equal(BeerDetailsViewAction.showActivityIndicator(true))) } it("should have called getBeers()") { expect(service.getBeerInput).to(equal(beerName)) } describe("resolving promise") { context("promise suceeds") { let beer = Beer.testMake(name: "Beer1") let mockViewState = BeerDetailsViewState.testMake(name: "Beer1") beforeEach { presenter.mockViewState = mockViewState promise.success(beer) } it("should call presenter with data from service") { expect(presenter.inputBeer).toEventually(equal(beer)) } it("should send viewState to view") { expect(view.action).toEventually(equal(BeerDetailsViewAction.display(mockViewState))) } } context("promise fails") { beforeEach { promise.failure(.serviceError) } it("should display error message") { expect(view.action).toEventually(equal(BeerDetailsViewAction.errorMessage("Failed to load beers. Sorry :("))) } } } } } } } } <file_sep>/BeerFactsTests/Mock/MockSegueRouter.swift import UIKit @testable import BeerFacts class MockSegueRouter: SegueRouterProtocol { var inputViewController: UIViewController? var inputSegueIdentifier: String? var inputHandler: ((UIViewController) -> Void)? func route(from viewController: UIViewController, to segueIdentifier: String, handler: ((UIViewController) -> Void)?) { inputViewController = viewController inputSegueIdentifier = segueIdentifier inputHandler = handler } } <file_sep>/BeerFactsTests/TestHelper/BeerDetailsViewState+TestHelper.swift import Foundation @testable import BeerFacts extension BeerDetailsViewState { static func testMake(name: String = "", tagline: String = "", description: String = "", abv: String = "", ibu: String = "", imageURL: URL? = nil, foodPairings: [String] = []) -> BeerDetailsViewState { return BeerDetailsViewState(name: name, tagline: tagline, description: description, abv: abv, ibu: ibu, imageURL: imageURL, foodPairings: foodPairings) } } <file_sep>/BeerFacts/BeerDetails/Test/BeerDetailsViewControllerSpec.swift import Quick import Nimble @testable import BeerFacts class BeerDetailsViewControllerSpec: QuickSpec { override func spec() { describe("BeerDetailsViewController") { var subject: BeerDetailsViewController! var interactor: MockBeerDetailsInteractor! var segueRouter: MockSegueRouter! var imageCache: MockImageCache! let beerName = "BeerName" beforeEach { interactor = MockBeerDetailsInteractor() segueRouter = MockSegueRouter() imageCache = MockImageCache() let storyboard = UIStoryboard(name: "BeerDetails", bundle: nil) subject = storyboard.instantiateViewController(withIdentifier: "BeerDetailsView") as! BeerDetailsViewController subject.inject(interactor: interactor, router: segueRouter, imageCache: imageCache) subject.configure(beerName: beerName) TestView.displayViewController(subject) } it("should have sent viewDidLoad to interactor") { expect(interactor.event).to(equal(BeerDetailsViewEvent.viewDidLoad(beerName: beerName))) } describe("perform actions") { context("activity spinner, show = true") { beforeEach { subject.perform(action: .showActivityIndicator(true)) } it("should have hidden imageview, stackview, and errorLabel ") { self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.errorLabel) self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.imageView) self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.stackView) } it("should have shown activity indicator") { self.tester().waitForView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.activityIndicator) } } context("activity spinner, show = false") { beforeEach { subject.perform(action: .showActivityIndicator(false)) } it("should have hidden activity indicator") { self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.activityIndicator) } } context("error message") { let message = "Something bad" beforeEach { subject.perform(action: .errorMessage(message)) } it("should have hidden imageView, stackView, and activity spinner") { self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.activityIndicator) self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.stackView) self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.activityIndicator) } it("should have shown errorLabel with message") { let label = self.tester().waitForView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.errorLabel) as! UILabel expect(label.text).to(equal(message)) } } context("display view state") { let viewState = BeerDetailsViewState.testMake( name: "Beer", tagline: "Tage line", description: "Beer description", abv: "ABV", ibu: "IBU", imageURL: URL(string: "https://fakeimage.com"), foodPairings: ["Food1", "Food2"]) beforeEach { subject.perform(action: .display(viewState)) } it("should have hidden errorLabel and activity spinner") { self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerListViewController.AccessibilityLabel.activityIndicator) self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerListViewController.AccessibilityLabel.errorLabel) } it("should have displayed data from viewState") { let nameLabel = self.tester().waitForView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.nameLabel) as! UILabel let tagLabel = self.tester().waitForView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.tagLabel) as! UILabel let descriptionLabel = self.tester().waitForView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.descriptionLabel) as! UILabel let ibuLabel = self.tester().waitForView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.ibuLabel) as! UILabel let abvLabel = self.tester().waitForView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.abvLabel) as! UILabel expect(nameLabel.text).to(equal(viewState.name)) expect(tagLabel.text).to(equal(viewState.tagline)) expect(descriptionLabel.text).to(equal(viewState.description)) expect(ibuLabel.text).to(equal(viewState.ibu)) expect(abvLabel.text).to(equal(viewState.abv)) } it("should have called image cache") { let imageView = self.tester().waitForView(withAccessibilityLabel: BeerDetailsViewController.AccessibilityLabel.imageView) as! UIImageView expect(imageCache.inputImageView).to(be(imageView)) expect(imageCache.inputImageURL).to(equal(viewState.imageURL)) } } } } } } <file_sep>/BeerFacts/Services/BeerService.swift import Foundation import Alamofire import BrightFutures public enum BeerError: Error { case decodeError case serviceError } protocol BeerServiceProtocol: class { func getBeers() -> Future<[Beer], BeerError> func getBeer(withName name:String) -> Future<Beer, BeerError> } class BeerService: BeerServiceProtocol { private enum Constants { static let beersEndPoint = "https://api.punkapi.com/v2/beers" static let beerNameParam = "beer_name" } func getBeers() -> Future<[Beer], BeerError> { let promise = Promise<[Beer], BeerError>() Alamofire.request(Constants.beersEndPoint).responseJSON { response in if let jsonData = response.data{ do { let beers = try JSONDecoder().decode([Beer].self, from: jsonData) promise.success(beers) } catch { promise.failure(.decodeError) } } else { promise.failure(.serviceError) } } return promise.future } func getBeer(withName name:String) -> Future<Beer, BeerError> { let promise = Promise<Beer, BeerError>() let parameters: Parameters = [Constants.beerNameParam: name] Alamofire.request(Constants.beersEndPoint, method: .get, parameters: parameters, encoding: URLEncoding(destination: .queryString)).responseJSON { response in if let jsonData = response.data{ do { let beer = try JSONDecoder().decode([Beer].self, from: jsonData)[0] promise.success(beer) } catch { promise.failure(.decodeError) } } else { promise.failure(.serviceError) } } return promise.future } } <file_sep>/BeerFactsTests/TestView.swift import Foundation import UIKit // Helpers to display view controller so that KIF can interact with it class TestView { static func displayViewController(_ viewController: UIViewController) { UIApplication.shared.keyWindow?.rootViewController = viewController } static func displayTableViewCell(_ cell: UITableViewCell) { let tableViewController = UITableViewController() let delegate = TableViewCellDelegate(cell) tableViewController.tableView.delegate = delegate tableViewController.tableView.dataSource = delegate displayViewController(tableViewController) } } private class TableViewCellDelegate: NSObject, UITableViewDataSource, UITableViewDelegate { let tableViewCell: UITableViewCell init(_ cell: UITableViewCell) { self.tableViewCell = cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableViewCell } } <file_sep>/BeerFacts/BeerDetails/Test/BeerDetailsPresenterSpec.swift import Quick import Nimble @testable import BeerFacts class BeerDetailsPresenterSpec: QuickSpec { override func spec() { describe("BeerDetailsPresenter") { var subject: BeerDetailsPresenter! let beer = Beer.testMake( name: "Beer1", tagline: "tag1", description: "This beer is great", image_url: "https://fake.com/image", abv: 1.5, food_pairing: ["food1", "food2"]) var viewState: BeerDetailsViewState! beforeEach { subject = BeerDetailsPresenter() viewState = subject.getViewState(beer: beer) } it("should have created correct viewState") { expect(viewState.name).to(equal(beer.name)) expect(viewState.tagline).to(equal(beer.tagline)) expect(viewState.description).to(equal(beer.description)) expect(viewState.abv).to(equal("ABV: 1.5 %")) expect(viewState.imageURL).to(equal(URL(string:beer.image_url))) expect(viewState.foodPairings).to(equal(beer.food_pairing)) } describe("ibu") { context("beer ibu is nil") { beforeEach { viewState = subject.getViewState(beer: Beer.testMake(ibu: nil)) } it("it should be Unkown") { expect(viewState.ibu).to(equal("IBU: Unknown")) } } context("beer ibu is NOT nil") { beforeEach { viewState = subject.getViewState(beer: Beer.testMake(ibu: 7.0)) } it("it should be IBU value") { expect(viewState.ibu).to(equal("IBU: 7.0")) } } } } } } <file_sep>/BeerFacts/BeerList/BeerListTableViewCell.swift import Foundation import UIKit class BeerListTableViewCell: UITableViewCell { static let nibName = "BeerListTableViewCell" static let identifier = "beerListCellIdentifier" enum AccessibilityLabel { static let nameLabel = "nameLabel" static let tagLabel = "tagLabel" static let abvLabel = "abvLabel" } @IBOutlet weak var nameLabel: UILabel! { didSet { nameLabel.accessibilityLabel = AccessibilityLabel.nameLabel } } @IBOutlet weak var tagLabel: UILabel! { didSet { tagLabel.accessibilityLabel = AccessibilityLabel.tagLabel } } @IBOutlet weak var abvLabel: UILabel! { didSet { abvLabel.accessibilityLabel = AccessibilityLabel.abvLabel } } var viewState: BeerListTableViewState? { didSet { guard let viewState = viewState else { return } nameLabel.text = viewState.name tagLabel.text = viewState.tagLine abvLabel.text = viewState.abv } } func configure(with viewState: BeerListTableViewState) { self.viewState = viewState let bgColorView = UIView() bgColorView.backgroundColor = UIColor.brown self.selectedBackgroundView = bgColorView } } <file_sep>/BeerFacts/BeerList/Test/BeerListViewControllerSpec.swift import Quick import Nimble @testable import BeerFacts class BeerListViewControllerSpec: QuickSpec { override func spec() { describe("BeerListViewController") { var subject: BeerListViewController! var interactor: MockBeerListInteractor! var segueRouter: MockSegueRouter! beforeEach { interactor = MockBeerListInteractor() segueRouter = MockSegueRouter() let storyboard = UIStoryboard(name: "BeerList", bundle: nil) subject = storyboard.instantiateViewController(withIdentifier: "BeerListView") as! BeerListViewController subject.inject(interactor: interactor, router: segueRouter) TestView.displayViewController(subject) } it("should have sent viewDidLoad to interactor") { expect(interactor.event).to(equal(BeerListViewEvent.viewDidLoad)) } describe("perform actions") { context("activity spinner, show = true") { beforeEach { subject.perform(action: .showActivityIndicator(true)) } it("should have shown activity spinner and hidden tableview, errorLabel ") { self.tester().waitForView(withAccessibilityLabel: BeerListViewController.AccessibilityLabel.activityIndicator) self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerListViewController.AccessibilityLabel.errorLabel) self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerListViewController.AccessibilityLabel.tableView) } } context("activity spinner, show = false") { beforeEach { subject.perform(action: .showActivityIndicator(false)) } it("should have hidden activity indicator") { self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerListViewController.AccessibilityLabel.activityIndicator) } } context("error message") { let message = "Something bad" beforeEach { subject.perform(action: .errorMessage(message)) } it("should have hidden tableview and activity spinner") { self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerListViewController.AccessibilityLabel.activityIndicator) self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerListViewController.AccessibilityLabel.tableView) } it("should have shown errorLabel with message") { let label = self.tester().waitForView(withAccessibilityLabel: BeerListViewController.AccessibilityLabel.errorLabel) as! UILabel expect(label.text).to(equal(message)) } } context("display view state") { let viewState = BeerListViewState(beerTableViewStates: [ BeerListTableViewState.testMake(name: "Beer1"), BeerListTableViewState.testMake(name: "Beer2"), BeerListTableViewState.testMake(name: "Beer3") ]) beforeEach { subject.perform(action: .display(viewState)) } it("should have hidden errorLabel and activity spinner") { self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerListViewController.AccessibilityLabel.activityIndicator) self.tester().waitForAbsenceOfView(withAccessibilityLabel: BeerListViewController.AccessibilityLabel.errorLabel) } it("should have shown tableview and configured table view cells") { let tableView = self.tester().waitForView(withAccessibilityLabel: BeerListViewController.AccessibilityLabel.tableView) as! UITableView expect(tableView.numberOfRows(inSection: 0)).to(equal(3)) let cell0 = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! BeerListTableViewCell let cell1 = tableView.cellForRow(at: IndexPath(row: 1, section: 0)) as! BeerListTableViewCell let cell2 = tableView.cellForRow(at: IndexPath(row: 2, section: 0)) as! BeerListTableViewCell expect(cell0.viewState).to(equal(viewState.beerTableViewStates[0])) expect(cell1.viewState).to(equal(viewState.beerTableViewStates[1])) expect(cell2.viewState).to(equal(viewState.beerTableViewStates[2])) } describe("tapping cell") { let index = 2 var tableView: UITableView! beforeEach { tableView = self.tester().waitForView(withAccessibilityLabel: BeerListViewController.AccessibilityLabel.tableView) as! UITableView self.tester().tapRow(at: IndexPath(row: index, section: 0), in: tableView) } it("should send select index event to interactor") { expect(interactor.event).to(equal(BeerListViewEvent.didSelectIndex(index))) } describe("route to details") { beforeEach { subject.perform(action: .routeToBeerDetails(beerName: "Beer1")) } it("should deselect table view row") { expect(tableView.indexPathForSelectedRow).to(beNil()) } it("should call segue router") { expect(segueRouter.inputViewController).to(be(subject)) expect(segueRouter.inputSegueIdentifier).to(equal(BeerListViewController.Constants.showDetailsSegue)) } } } } } } } } <file_sep>/BeerFactsTests/Mock/MockBeerListViewController.swift @testable import BeerFacts class MockBeerListViewController: BeerListViewProcotol { public var action: BeerListViewAction? func perform(action: BeerListViewAction) { self.action = action } } <file_sep>/BeerFactsTests/TestHelper/BeerListTableViewState+TestHelper.swift @testable import BeerFacts extension BeerListTableViewState { static func testMake(name: String = "", tagLine: String = "", abv: String = "") -> BeerListTableViewState { return BeerListTableViewState(name: name, tagLine: tagLine, abv: abv) } } <file_sep>/BeerFacts/BeerList/Test/BeerListInteractorSpec.swift import BrightFutures import Quick import Nimble @testable import BeerFacts class BeerListInteractorSpec: QuickSpec { override func spec() { describe("BeerListInteractor") { var subject: BeerListInteractor! var view: MockBeerListViewController! var service: MockBeerService! var presenter: MockBeerListPresenter! beforeEach { view = MockBeerListViewController() service = MockBeerService() presenter = MockBeerListPresenter() subject = BeerListInteractor(beerService: service, beerListPresenter: presenter) subject.view = view } describe("handle events") { describe("viewDidLoad event") { var promise: Promise<[Beer], BeerError>! beforeEach { promise = Promise<[Beer], BeerError>() service.getBeersStub = promise subject.handle(event: .viewDidLoad) } it("should send showActivityIndicator with true") { expect(view.action).to(equal(BeerListViewAction.showActivityIndicator(true))) } it("should have called getBeers()") { expect(service.didCallGetBeers).to(beTrue()) } describe("resolving promise") { context("promise suceeds") { let beers = [Beer.testMake(name: "Beer1"), Beer.testMake(name: "Beer2")] let mockViewState = BeerListViewState(beerTableViewStates: [BeerListTableViewState.testMake(name: "Beer1")]) beforeEach { presenter.mockViewState = mockViewState promise.success(beers) } it("should call presenter with data from service") { expect(presenter.inputBeers).toEventually(equal(beers)) } it("should send viewState to view") { expect(view.action).toEventually(equal(BeerListViewAction.display(mockViewState))) } describe("beer selected") { beforeEach { //Wait for previous test to finish expect(view.action).toEventually(equal(BeerListViewAction.display(mockViewState))) subject.handle(event: .didSelectIndex(1)) } it("should send route to view") { expect(view.action).toEventually(equal(BeerListViewAction.routeToBeerDetails(beerName: beers[1].name))) } } } context("promise fails") { beforeEach { promise.failure(.serviceError) } it("should display error message") { expect(view.action).toEventually(equal(BeerListViewAction.errorMessage("Failed to load beers. Sorry :("))) } } } } } } } } <file_sep>/BeerFactsTests/Mock/MockBeerDetailsPresenter.swift @testable import BeerFacts class MockBeerDetailsPresenter: BeerDetailsPresenterProtocol { var inputBeer: Beer = Beer.testMake() var mockViewState: BeerDetailsViewState = BeerDetailsViewState.testMake() func getViewState(beer: Beer) -> BeerDetailsViewState { inputBeer = beer return mockViewState } } <file_sep>/BeerFacts/BeerDetails/BeerDetailsPresenter.swift import Foundation struct BeerDetailsViewState: Equatable { let name: String let tagline: String let description: String let abv: String let ibu: String let imageURL: URL? let foodPairings: [String] } protocol BeerDetailsPresenterProtocol { func getViewState(beer:Beer) -> BeerDetailsViewState } class BeerDetailsPresenter: BeerDetailsPresenterProtocol { func getViewState(beer: Beer) -> BeerDetailsViewState { let imageURL = URL(string: beer.image_url) let ibuString: String if let ibu = beer.ibu { ibuString = "IBU: \(ibu)" } else { ibuString = "IBU: Unknown" } return BeerDetailsViewState( name: beer.name, tagline: beer.tagline, description: beer.description, abv: "ABV: \(beer.abv) %", ibu: ibuString, imageURL: imageURL, foodPairings: beer.food_pairing) } } <file_sep>/BeerFacts/BeerList/BeerListViewController.swift import Foundation import UIKit enum BeerListViewAction: Equatable { case showActivityIndicator(Bool) case display(BeerListViewState) case errorMessage(String) case routeToBeerDetails(beerName: String) } protocol BeerListViewProcotol: class { func perform(action: BeerListViewAction) } class BeerListViewController: UIViewController { enum AccessibilityLabel { static let activityIndicator = "activityIndicator" static let tableView = "tableView" static let errorLabel = "errorLabel" } enum Constants { static let showDetailsSegue = "ShowBeerDetails" } @IBOutlet private weak var activityIndicator: UIActivityIndicatorView! { didSet { activityIndicator.accessibilityLabel = AccessibilityLabel.activityIndicator activityIndicator.isHidden = true } } @IBOutlet weak var tableView: UITableView! { didSet { tableView.accessibilityLabel = AccessibilityLabel.tableView tableView.dataSource = self tableView.delegate = self tableView.register(UINib(nibName: BeerListTableViewCell.nibName, bundle: nil), forCellReuseIdentifier: BeerListTableViewCell.identifier) } } @IBOutlet weak var errorLabel: UILabel! { didSet { errorLabel.accessibilityLabel = AccessibilityLabel.errorLabel } } private var viewState: BeerListViewState? { didSet { guard viewState != nil else { return } activityIndicator.isHidden = true errorLabel.isHidden = true tableView.isHidden = false tableView.reloadData() } } private var interactor: BeerListInteractorProtocol! private var router: SegueRouterProtocol! func inject(interactor: BeerListInteractorProtocol, router: SegueRouterProtocol) { self.interactor = interactor self.router = router } override func viewDidLoad() { super.viewDidLoad() interactor?.handle(event: .viewDidLoad) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let router = sender as? SegueRouter { router.handler?(segue.destination) } } } extension BeerListViewController: BeerListViewProcotol { func perform(action: BeerListViewAction) { switch(action) { case .showActivityIndicator(let show): handleShowActivityIndicator(show) case .display(let viewState): self.viewState = viewState case .errorMessage(let message): handleErrorMessage(message) case .routeToBeerDetails(let name): handleRouteToBeerDetails(name: name) } } private func handleShowActivityIndicator(_ show: Bool) { activityIndicator.isHidden = !show errorLabel.isHidden = true tableView.isHidden = true } private func handleErrorMessage(_ message: String) { activityIndicator.isHidden = true errorLabel.isHidden = false tableView.isHidden = true errorLabel.text = message } private func handleRouteToBeerDetails(name: String) { if let selectedIndex = tableView.indexPathForSelectedRow { tableView.deselectRow(at: selectedIndex, animated: true) } router.route(from: self, to: Constants.showDetailsSegue) { (destinationVC) in if let beerDetailsVC = destinationVC as? BeerDetailsViewController { beerDetailsVC.configure(beerName: name) } } } } extension BeerListViewController: UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewState?.beerTableViewStates.count ?? 0 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: BeerListTableViewCell.identifier, for: indexPath) as? BeerListTableViewCell, let viewState = viewState?.beerTableViewStates[indexPath.row] else { return UITableViewCell() } cell.configure(with: viewState) return cell } } extension BeerListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { interactor.handle(event: .didSelectIndex(indexPath.row)) } } <file_sep>/BeerFactsTests/Mock/MockBeerDetailsViewController.swift @testable import BeerFacts class MockBeerDetailsViewController: BeerDetailsViewProcotol { public var action: BeerDetailsViewAction? func perform(action: BeerDetailsViewAction) { self.action = action } } <file_sep>/BeerFacts/Services/Beer.swift import Foundation struct Beer: Codable, Equatable { let name: String let tagline: String let description: String let image_url: String let target_fg: Double let target_og: Double let ebc: Double? let srm: Double? let ph: Double? let attenuation_level: Double let abv: Double let ibu: Double? let food_pairing: [String] } <file_sep>/BeerFactsTests/Mock/MockBeerListPresenter.swift @testable import BeerFacts class MockBeerListPresenter: BeerListPresenterProtocol { var inputBeers: [Beer] = [] var mockViewState: BeerListViewState = BeerListViewState(beerTableViewStates: []) func getBeerListViewState(beers: [Beer]) -> BeerListViewState { inputBeers = beers return mockViewState } } <file_sep>/BeerFacts/Assembly/MainAssembly.swift import Swinject import SwinjectStoryboard class MainAssembly: Assembly { func assemble(container: Container) { container.storyboardInitCompleted(BeerListViewController.self) { (resolver, viewController) in let interactor = resolver.resolve(BeerListInteractor.self)! let router = resolver.resolve(SegueRouter.self)! viewController.inject(interactor: interactor, router: router) interactor.view = viewController } container.storyboardInitCompleted(BeerDetailsViewController.self) { (resolver, viewController) in let interactor = resolver.resolve(BeerDetailsInteractor.self)! let router = resolver.resolve(SegueRouter.self)! let imageCache = resolver.resolve(ImageCacheWrapper.self)! viewController.inject(interactor: interactor, router: router, imageCache: imageCache) interactor.view = viewController } container.register(BeerListInteractor.self) { resolver in let beerService = resolver.resolve(BeerService.self)! let beerListPresenter = resolver.resolve(BeerListPresenter.self)! return BeerListInteractor(beerService: beerService, beerListPresenter: beerListPresenter) } container.register(BeerDetailsInteractor.self) { resolver in let beerService = resolver.resolve(BeerService.self)! let presenter = resolver.resolve(BeerDetailsPresenter.self)! return BeerDetailsInteractor(beerService: beerService, presenter: presenter) } container.register(BeerService.self) { _ in return BeerService() } container.register(BeerListPresenter.self) { _ in return BeerListPresenter() } container.register(BeerDetailsPresenter.self) { _ in return BeerDetailsPresenter() } container.register(SegueRouter.self) { _ in return SegueRouter() } container.register(ImageCacheWrapper.self) { _ in return ImageCacheWrapper() } } } <file_sep>/BeerFacts/Services/Test/BeerServiceSpec.swift // TODO : should test with Mockingjay <file_sep>/BeerFacts/Assembly/Test/MainAssemblySpec.swift import Quick import Nimble import Swinject import SwinjectStoryboard @testable import BeerFacts class MainAssemblySpec: QuickSpec { override func spec() { describe("MainAssembly") { var resolver: Resolver! let testContainer = Container() beforeEach { let assemblies = [MainAssembly()] let assembler = Assembler(assemblies, container: testContainer) resolver = assembler.resolver } describe("BeerListViewController") { var beerListViewController: BeerListViewController? beforeEach { let storyboard = SwinjectStoryboard.create(name: "BeerList", bundle: nil, container: testContainer) beerListViewController = storyboard.instantiateViewController(withIdentifier: "BeerListView") as? BeerListViewController } it("should get resolved") { expect(beerListViewController).toNot(beNil()) } } describe("BeerListInteractor") { var beerListInteractor: BeerListInteractor? beforeEach { beerListInteractor = resolver.resolve(BeerListInteractor.self) } it("should get resolved") { expect(beerListInteractor).toNot(beNil()) } } describe("BeerDetailsViewController") { var beerDetailsViewController: BeerDetailsViewController? beforeEach { let storyboard = SwinjectStoryboard.create(name: "BeerDetails", bundle: nil, container: testContainer) beerDetailsViewController = storyboard.instantiateInitialViewController() as? BeerDetailsViewController } it("should get resolved") { expect(beerDetailsViewController).toNot(beNil()) } } describe("BeerService") { var beerService: BeerService? beforeEach { beerService = resolver.resolve(BeerService.self) } it("should get resolved") { expect(beerService).toNot(beNil()) } } describe("SegueRouter") { var segueRouter: SegueRouter? beforeEach { segueRouter = resolver.resolve(SegueRouter.self) } it("should get resolved") { expect(segueRouter).toNot(beNil()) } } } } }
aeab964ebf19b2fa60baa72defb756ca0713ed6d
[ "Swift", "Ruby" ]
38
Swift
jjohnstz/BeerFacts
b861eb26162c8123118ce72aeeacb0d69a59d9a1
2d556f8b101ec1bf479972b31a8ede000a81685a
refs/heads/master
<file_sep># Maintainer: <NAME> (<EMAIL>) pkgname=ttf-inconsolata-g pkgver=20090213 pkgrel=3 conflicts=('ttf-inconsolata-g') provides=('ttf-inconsolata-g') pkgdesc="Monospace font for pretty code listings and for the terminal modified by Le<NAME> (http://www.fantascienza.net/leonardo/)" url='https://github.com/justinwalker/' license=('unknown') depends=('fontconfig' 'xorg-font-utils') source=('inconsolata_g::git+ssh://[email protected]/justinwwalker/inconsolata_g.git') install=ttf-inconsolata-g.install arch=('any') md5sums=('SKIP') package() { install -Dm644 $srcdir/inconsolata_g/Inconsolata-g.ttf $pkgdir/usr/share/fonts/TTF/ttf-inconsolata-g.ttf }
507ea269eddf6553722feb2eba8ead527cbdddc4
[ "Shell" ]
1
Shell
justinwwalker/ttf-inconsolata-g
4c4342612a750a3da241469b836b71c3b381a785
cac9618acde888664ffd46623dbc0a8fa7698361
refs/heads/master
<repo_name>KevinAS28/Python-Training<file_sep>/helloworld.py #!/usr/bin/python3 import random print(random.randint(5, 10))<file_sep>/test_mod0.py import test_mod1 print("Test mod 0") <file_sep>/tes_zip.py import zipfile with zipfile.ZipFile("oke", mode="w") as oke: oke.write("solo1.py")<file_sep>/latihan_matplotlib.py from matplotlib import pyplot as pp pp.plot([0, 1, 2], [0, 1, 2]) pp.title = "Latihan" pp.xlabel = "Kenaikan Harga" pp.ylabel = "Tahun" pp.show()<file_sep>/latiiha sysos #!/usr/bin/python #latihan os dan sys import os import sys <file_sep>/buat_file.py #!/usr/bin/python3 import time time.sleep(5) open("tes_buat_file", "w+") <file_sep>/youtube_dl.py import youtube_dl #pake subprocess, ada di folder download web<file_sep>/solo5.py #!/usr/bin/python #latihan input(1) oke = input("angka dong:") + input("lagi dong bang:") print oke #end(1) #latihan lagi(2) jadi = '7' jadi = int(jadi) + int("2") #pas int(jadi) jn pk " jadilagi = int(jadi) + int("2") #pas int(jadi) jn pk " mantap = int(jadi) + 3 print jadi print jadilagi<file_sep>/make_db.py import sys from PyQt4 import QtCore, QtGui, uic import MySQLdb qtCreatorFile = "make_db.ui" # Enter file here. Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile) def SQL_com(perintah, host="127.0.0.1", user="root"): db = MySQLdb.connect(host=host, user=user) cur = db.cursor() cur.execute(perintah) output = "" for baris in cur.fetchall(): output += baris return output class MyApp(QtGui.QMainWindow, Ui_MainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) self.Buat.clicked.connect(self.Buat_db) def Buat_db(self): nama_db = self.Kotak_nama.toPlainText() #tax = (self.putar.value()) #total_price = price + ((tax / 100) * price) #total_price_string = "hasil: " + str(total_price) self.hasil.setText("DataBase %s telah dibuat\n%s" %(nama_db, str(SQL_com("create database %s" %(nama_db))))) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) window = MyApp() window.show() sys.exit(app.exec_())<file_sep>/web_img.py import sys from urllib.parse import urlsplit import re if (len(sys.argv)==1): print("Web Image Scrapper By <NAME>") print("Usage: python web_img.py [https/http]://url") sys.exit(0) url = sys.argv[1] urls = urlsplit(url) allimage = [] data = b"" sys.exit(0) if (urls.scheme=="https"): import http.client as hc a = hc.HTTPSConnection(urls.netloc) a.request("GET", urls.path) data = a.getresponse().read() else: import socket con = socket.socket(socket.AF_INET, socket.SOCK_STREAM) con.connect((urls.netloc, 80)) req = b'GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nCookie: ciNav=no\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1\r\n\r\n' con.send(req) data = con.recv(10000) #max is 10 mb <file_sep>/inputbagus.py #!/usr/bin/python oke = input("kece: ") if oke == "mantap": print "benar" if oke == "super": print "entah" <file_sep>/5.py #!/usr/bin/python import socket s=socket.socket() s.connect(("192.168.1.107",22)) answer =s.recv(1024) print answer s.close<file_sep>/cal.py #!/usr/bin/python kali = '*' bagi = '/' tambah = '+' kurang = '-' kuadrat = '**' angkast = input("angka pertama:") lambang = input("lambang:") angkand = input("angka kedua:") hasil = float(angkast+lambang+angkand) print hasil <file_sep>/kalkulator.py #!/usr/bin/python #first calculator print 5*5 print 5**5 print 25/5 print 3125/5 <file_sep>/static.py class oke: def __init__(self, oke, eko): self.oke = oke self.eko = eko def kali(self): return self.oke + self.eko @classmethod def baru(cls, satu, dua): return cls(satu, dua) @staticmethod def lama(masa, sih): print(masa * sih) ooo = oke.baru(5, 6) print(ooo.kali()) oke.lama(10, 6) <file_sep>/neural_network.py from numpy import exp, array, random, dot class neural_network: def __init__(self): random.seed(1) self.weights = 2 * random.random((2, 1)) - 1 def train(self, inputs, outputs, num): for iteration in range(num): output = self.think(inputs) error = outputs-outputs adjusment = 0.01*dot(inputs.T, error) self.weights += adjusment def think(self, inputs): return (dot(inputs, self.weights)) neural_network = neural_network() inputs = array([[2, 3], [1, 1], [5, 2], [12, 3]]) outputs = array([[10, 4, 14, 30]]).T neural_network.train(inputs, outputs, 10000) print(neural_network.think(array([15, 2]))) <file_sep>/wanjer.py #!/usr/bin/python print (True) print ("oke") #tipe string print ("oke 1") print ('oke 2') #tipe integer print (3.14) print (("satu", "dua", "tiga")) #tipe data dictonary print ({"nama":"budi", 'umur':20}) #data dictonary masuk kedalam variable biodata = {"nama":"andi", 'umur':21} print (biodata) type (biodata)<file_sep>/tg.py import time a = "y" while a=="y": print(""" 1 2 3 """) time.sleep(2) print(""" 4 5 6 """) a = input("hah? ")<file_sep>/tur2.py import turtle wn = turtle.Screen() wn.bgcolor("grey") wn.title("nice") tess = turtle.Turtle() tess.color("blue") tess.pensize(3) tess.forward(50) tess.left(120) tess.forward(50) turtle.mainloop() <file_sep>/latihansysos.py #!/usr/bin/python #latihan os dan sys import os import sys def spab(x): for cbc in range(x): print(' ') lines = [line.rstrip('\n') for line in (os.popen('ls'))] print(lines) spab(5) <file_sep>/game.py #!/usr/bin/python import os import sys import random #game = "y" #while game.lower() == "y": print("you are using python version "+sys.version) print(""" """) print(""" select the game: 1.pattern game 2.pin game insert the number and hit enter """) menug = input("your choice? ") #game pattern def diff(): print(""" select difficulty: 1.easy 2.normal 3.hard type the number and hit enter """) diff() dif1 = input("your choice? ") #pattern easy if dif1 == 1: num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0,] ans = [random.choice(num), random.choice(num), random.choice(num)] print(ans) <file_sep>/solo4.py #!/usr/bin/python #menempatkan function dalam variable (1) print """x = 2 print x output 2 x +=3 print x output 5""" #ulangan susulan input wokeh = (input('y or no')) wokehlagi = 'mantap' y = "y berhasil" if wokeh == (y): print wokehlagi <file_sep>/db_latihan.py import MySQLdb basis_data = MySQLdb.connect(host="127.0.0.1", user="root") arahan = basis_data.cursor() while True: try: arahan.execute(input("MySQL Command: ")) for output in arahan.fetchall(): print(output) except KeyboardInterrupt: break except Exception as error: print(str(error)) basis_data.close()<file_sep>/test_mod1.py import test_mod0 print("Test mod 1") <file_sep>/latihan4.py #!/usr/bin/python mantap = "yeee" oke = input("kece: ") print(oke)<file_sep>/teslaglagi.py #!/usr/bin/python oke = float(input("angka dong:")) + float(input("lagi dong bang:")) print oke<file_sep>/solo3.py #!/usr/bin/python #integers(tau dah)(1) oke = "2" + "3" #ini dah biasa print oke lagi = int("2")+int("3") print lagi #float dan input gabungan (2) okejadi = (input("angka dong:"))+(input("angka lagi dong:")) print okejadi #end (2) #float lagi okejadi = float(input("angka dong yg float:"))+float(input("angka lagi dong:")) #tadi pake float hasilnya ada .0 dibelakangnya <file_sep>/latihaninputlagi.py #!/usr/bin/python #0 = 0 #1 = 1 #2 = 2 #3 = 3 #4 = 4 #5 = 5 #6 = 6 #7 = 7 #8 = 8 #9 = 9 kali = '*' angkap = (input("masukan angka")) angkaked = (input("lambang")) angkaket = (input("angka kedua")) print int(angkap '+' angkaked '+' angkaket) <file_sep>/vscodetes.py #!/usr/bin/python3 import time def waktu(): time.sleep(2) oke = input('wwow') print(oke) waktu() <file_sep>/solo1.py #!/usr/bin/python print 'kevin\'s toy' print 'kevin\ #nyambungin kevin diatas sama dong dibawah oke' print """customer:buset dah.. ..gue:santai dong,gila.sono kluar lo.""" #diantara sono sama kluar ga ada ' print """customer:buset dah.. ..gue:santai dong,gila.sono' kluar lo.""" #diantara sono sama kluar ada ' print "santai dong" #biasa print """santai dong""" #dong dibawah print "kocag\nshit" #penggunaan /n #penggunaan () didalam print print ('print("print")') #keluar print("print") #xyregz <file_sep>/tur5.py import turtle wn = turtle.Screen() wn.bgcolor("black") wn.title("wow") alex = turtle.Turtle() col = ["red", "yellow", "green", "purple", "blue"] alex.penup() size = 20 co = 0 alex.color("white") alex.shape("turtle") for i in range(30): alex.color(col[co]) alex.stamp() size = size + 3 alex.forward(size) alex.left(24) co = co + 1 if co == 5: co = 0 """ size1 = 20 ales = turtle.Turtle() ales.penup() ales.color("white") ales.shape("turtle") for a in range(30): ales.color(col[co]) ales.stamp() size1 = size1 + 3 ales.forward(size1) ales.right(24) co = co + 1 if co == 5: co = 0 """ turtle.mainloop() <file_sep>/tur4.py import turtle wn = turtle.Screen() wn.bgcolor("black") wn.title("mantap") alex = turtle.Turtle() alex.color("white") alex.pensize(3) col = ["yellow", "white", "blue", "red", "green"] for i in col: alex.color(i) alex.speed(1) alex.forward(50) alex.left(90) turtle.mainloop() <file_sep>/udah.py #!/usr/bin/python if time 12:09 print "uudah" else: print "blom"<file_sep>/solo12.py #!/usr/bin/python print 'penggunaan while if dan continue' i = 0 while True: i = i + 1 if i == 2: print 'lewatin 2' continue if i == 5: print 'break' break print i print 'selsai' print ' ' print 'lagi' print ' ' apa = 2 while True: apa = apa + 2 #KALI INI SPASI HARUS TEPAT if apa == 20: print 'lanjut' continue if apa == 40: print 'selsai' break print apa #LINE INI SPASI HARUS MUNDUR:PERHATIKAN print ' ' print 'Penggunaan Lists' print ' ' kata = ["I","DID","IT"] print kata[1] print kata[0] #ga perlu penjelasan lah print kata[2] print ' ' print 'empty list' #empty = ksong <file_sep>/tur6.py import turtle import time from turtle import * kevin = turtle.Screen() agusto = turtle.Turtle() kevin.bgpic("loading.gif") kevin.title("hahahaha") col = ["red", "yellow", "green", "purple", "blue"] agusto.pensize(3) ss = 0 for i in range(3): agusto.color(col[ss]) agusto.forward(200) agusto.left(120) ss = ss + 1 if ss == 6: ss = 0 time.sleep(5) wow = turtle.Screen() oww = turtle.Turtle() wow.bgcolor("black") wow.title("ahhh") oww.pensize(3) sss = 0 for o in range(4): oww.color(col[sss]) oww.forward(100) oww.left(90) sss = sss + 1 if sss == 6: sss = 0 turtle.mainloop() <file_sep>/8.py #!/usr/bin/python while (count<=10): print count count+=1<file_sep>/1.py #!/usr/bin/python okestringvariable = "Mungkin itu"; okeintegervariable = 10 okefloatingpointvariable= 0110.110 okelist = [1,2,3,4,5,6] okedictonary = {'name': 'kocag', 'value':27} print okevariable print okeintegervariable print okefloatingpointvariable<file_sep>/game1.py #!/usr/bin/python #import module import os import time import random import sys from threading import Thread if True: print ("written by <NAME> "+(sys.version)) print(" ") print("3.5.3 is recomended") time.sleep(2) a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9] b = [(random.choice(a)), (random .choice(a)), (random.choice(a))] b.sort() rans0 = int(b[0]) rans1 = int(b[1]) rans2 = int(b[2]) c = [" "] #supaya tidak ada yang sama if (rans0 == rans2) and (rans0 == rans1) and (rans2 == rans1): print("maaf ada kesalahan pada program.silahkan jalankan ulang programnya") time.sleep(3) # b = [(random.choice(a)), (random .choice(a)), (random.choice(a))] # b.sort() # rans0 = int(b[0]) # rans1 = int(b[1]) # rans2 = int(b[2]) # c = [" "] print(rans0, rans1, rans2) exit() if rans0 == rans1: print("maaf ada kesalahan pada program.silahkan jalankan ulang programnya") time.sleep(3) print(rans0, rans1, rans2) exit() if rans2 == rans1: print("maaf ada kesalahan pada program.silahkan jalankan ulang programnya") time.sleep(3) print(rans0, rans1, rans2) exit() def hadiah1(): print(""" +-------------------------------------------------------+ | PIN GAME BY <NAME> | +---------------------------+---------------------------+ | __________________ | ___________ | | ==c(______(o(______(_() | | |======[*** | | )=\ | | ANDA \ | | // \ | |_____________\_______ | | // \ | |==[WOW >]============\ | | // \ | |______________________\ | | //SELAMAT \ | \(@)(@)(@)(@)(@)(@)(@)/ | | // \ | ********************* | +---------------------------+---------------------------+ | o O o | \'\/\/\/'/ | | o O | )======( | | o | .' MENANG '. | | |^^^^^^^^^^^^^^|l___ | / _||__ \ | | | TELAH |""\___, | / (_||_ \ | | |________________|__|)__| | | __||_) | | | |(@)(@)"" **|(@)(@)**|(@) | " || " | | = = = = = = = = = = = = | '--------------' | +---------------------------+---------------------------+ """) def ms(): print(""" """) def ms1(): print(""" """) #perfect ms() time.sleep(2) print(c[0], c[0], c[0], a[0], c[0], c[0], c[0], a[1], c[0], c[0], c[0], a[2]) print(" ") print(" ") print(c[0], c[0], c[0], a[3], c[0], c[0], c[0], a[4], c[0], c[0], c[0], a[5]) print(" ") print(" ") print(c[0], c[0], c[0], a[6], c[0], c[0], c[0], a[7], c[0], c[0], c[0], a[8]) ms1() def perfect(): ms() print(c[0], c[0], c[0], a[0], c[0], c[0], c[0], a[1], c[0], c[0], c[0], a[2]) print(" ") print(" ") print(c[0], c[0], c[0], a[3], c[0], c[0], c[0], a[4], c[0], c[0], c[0], a[5]) print(" ") print(" ") print(c[0], c[0], c[0], a[6], c[0], c[0], c[0], a[7], c[0], c[0], c[0], a[8]) ms1() #jika 1 time.sleep(2) if (rans0 == a[0]) or (rans1 == a[0]) or (rans2 == a[0]): ms() print(c[0], c[0], c[0], c[0], c[0], c[0], c[0], a[1], c[0], c[0], c[0], a[2]) print(" ") print(" ") print(c[0], c[0], c[0], a[3], c[0], c[0], c[0], a[4], c[0], c[0], c[0], a[5]) print(" ") print(" ") print(c[0], c[0], c[0], a[6], c[0], c[0], c[0], a[7], c[0], c[0], c[0], a[8]) ms1() time.sleep(2) perfect() #jika 2 if (rans0 == a[1]) or (rans1 == a[1]) or (rans2 == a[1]): ms() print(c[0], c[0], c[0], a[0], c[0], c[0], c[0], c[0], c[0], c[0], c[0], a[2]) print(" ") print(" ") print(c[0], c[0], c[0], a[3], c[0], c[0], c[0], a[4], c[0], c[0], c[0], a[5]) print(" ") print(" ") print(c[0], c[0], c[0], a[6], c[0], c[0], c[0], a[7], c[0], c[0], c[0], a[8]) ms1() time.sleep(2) perfect() #jika 3 if (rans0 == a[2]) or (rans1 == a[2]) or (rans2 == a[2]): ms() print(c[0], c[0], c[0], a[0], c[0], c[0], c[0], a[1], c[0], c[0], c[0], c[0]) print(" ") print(" ") print(c[0], c[0], c[0], a[3], c[0], c[0], c[0], a[4], c[0], c[0], c[0], a[5]) print(" ") print(" ") print(c[0], c[0], c[0], a[6], c[0], c[0], c[0], a[7], c[0], c[0], c[0], a[8]) ms1() time.sleep(2) perfect() #jika 4 if (rans0 == a[3]) or (rans1 == a[3]) or (rans2 == a[3]): ms() print(c[0], c[0], c[0], a[0], c[0], c[0], c[0], a[1], c[0], c[0], c[0], a[2]) print(" ") print(" ") print(c[0], c[0], c[0], c[0], c[0], c[0], c[0], a[4], c[0], c[0], c[0], a[5]) print(" ") print(" ") print(c[0], c[0], c[0], a[6], c[0], c[0], c[0], a[7], c[0], c[0], c[0], a[8]) ms1() time.sleep(2) perfect() #jika 5 if (rans0 == a[4]) or (rans1 == a[4]) or (rans2 == a[4]): ms() print(c[0], c[0], c[0], a[0], c[0], c[0], c[0], a[1], c[0], c[0], c[0], a[2]) print(" ") print(" ") print(c[0], c[0], c[0], a[3], c[0], c[0], c[0], c[0], c[0], c[0], c[0], a[5]) print(" ") print(" ") print(c[0], c[0], c[0], a[6], c[0], c[0], c[0], a[7], c[0], c[0], c[0], a[8]) ms1() time.sleep(2) perfect() #jika 6 if (rans0 == a[5]) or (rans1 == a[5]) or (rans2 == a[5]): ms() print(c[0], c[0], c[0], a[0], c[0], c[0], c[0], a[1], c[0], c[0], c[0], a[2]) print(" ") print(" ") print(c[0], c[0], c[0], a[3], c[0], c[0], c[0], a[4], c[0], c[0], c[0], c[0]) print(" ") print(" ") print(c[0], c[0], c[0], a[6], c[0], c[0], c[0], a[7], c[0], c[0], c[0], a[8]) ms1() time.sleep(2) perfect() #jika 7 if (rans0 == a[6]) or (rans1 == a[6]) or (rans2 == a[6]): ms() print(c[0], c[0], c[0], a[0], c[0], c[0], c[0], a[1], c[0], c[0], c[0], a[2]) print(" ") print(" ") print(c[0], c[0], c[0], a[3], c[0], c[0], c[0], a[4], c[0], c[0], c[0], a[5]) print(" ") print(" ") print(c[0], c[0], c[0], c[0], c[0], c[0], c[0], a[7], c[0], c[0], c[0], a[8]) ms1() time.sleep(2) perfect() #jika 8 if (rans0 == a[7]) or (rans1 == a[7]) or (rans2 == a[7]): ms() print(c[0], c[0], c[0], a[0], c[0], c[0], c[0], a[1], c[0], c[0], c[0], a[2]) print(" ") print(" ") print(c[0], c[0], c[0], a[3], c[0], c[0], c[0], a[4], c[0], c[0], c[0], a[5]) print(" ") print(" ") print(c[0], c[0], c[0], a[6], c[0], c[0], c[0], c[0], c[0], c[0], c[0], a[8]) ms1() time.sleep(2) perfect() #jika 9 if (rans0 == a[8]) or (rans1 == a[8]) or (rans2 == a[8]): ms() print(c[0], c[0], c[0], a[0], c[0], c[0], c[0], a[1], c[0], c[0], c[0], a[2]) print(" ") print(" ") print(c[0], c[0], c[0], a[3], c[0], c[0], c[0], a[4], c[0], c[0], c[0], a[5]) print(" ") print(" ") print(c[0], c[0], c[0], a[6], c[0], c[0], c[0], a[7], c[0], c[0], c[0], c[0]) ms1() time.sleep(2) perfect() b.sort() #masukan input print(""" angka berapa saja tadi yang hilang2an? (harus berurutan) hitugan 10 detik dari sekarang! """) #minta jawaban dan mengkoreksinya # jawab0 = None # jawab1 = None # jawab2 = None # jawabrr = [jawabb0, jawabb1, jawabb2] # jawabrr.sort # jawabr0 = jawabrr[0] # jawabr1 = jawabrr[1] # jawabr2 = jawabrr[2] # if (jawabr[0] == rans0) and (jawabr[1] == rans[1]) and (jawab[2] == rans[2]): # print("anda menang!!! selamat yaaa!!! ;) ") # time.sleep(3) # print(rans0, rans1, rans2) # exit() # else: # print("anda kalah.silahkan coba lagi") # exit() def periksa(): try: time.sleep(5) # print(jawabr0, jawabr1, jawabr2) if ((jawabr0) == (rans0)) and ((jawabr1) == (rans1)) and ((jawabr2) == (rans2)): # print("menang") hadiah1() print(rans0, rans1, rans2) print(jawabr0, jawabr1, jawabr2) exit() return print(""" kalah""") exit() except NameError: ms() print("waktu habis") exit() # ms() # print("waktu habis.anda kalah") # print(rans0 == jawabr0) Thread(target = periksa).start() try: jawab0 = input("jawaban mu? ") jawab1 = input("jawaban mu? ") jawab2 = input("jawaban mu? ") jawabrr = [jawab0, jawab1, jawab2] jawabrr.sort() jawabr0 = int(jawabrr[0]) jawabr1 = int(jawabrr[1]) jawabr2 = int(jawabrr[2]) print(rans0, rans1, rans2) print(jawabr0, jawabr1, jawabr2) except: exit() print(rans0, rans1, rans2) print(jawabr0, jawabr1, jawabr2) <file_sep>/inh.py class oke: def __init__(self, x, y): self.x = x self.y = y def __del__(self): namaclass = self.__class__.__name__ class eko: def __init__(self, x, y): self.x = x print(self.x) <file_sep>/solo6.py #!/usr/bin/python print "boolean menggunakan ==" print "boolean itu pernyataan benar dan salah" print 'contoh' #latihan booleans menggunakan 2 tanda sama dengan (pernyataan benar dan salah) (1) misal_contoh = True print misal_contoh oke = 2 == 3 print oke jadi = "mantap" == "mantap" print jadi #end (1) print ' ' print ' ' print "latihan booleans kebalikan dari menggunakan == menggunakan !=" print 'contoh' boolean_kebalikan = 1 != 1 print boolean_kebalikan kevinganteng = "kevin" != "ganteng" print kevinganteng print ' ' print ' ' print ' ' print 'latihan comparsion menggunakan < dan >' contoh_comparsion = 7 > 5 print contoh_comparsion comparsion_lagi = 100 < 100 print comparsion_lagi lagilagi = 9 >= 9.0 print "9 >= 9.0" print lagilagi print ' ' print "sekarang 8.7 <= 8.70 hasilnya" anjay = 8.7 <= 8.70 print anjay <file_sep>/who_has_to_pay.py import random import string import sys #pinjemnya berapa #banyak orang juga #semua harus terstruktur spab = lambda x: [print(" ") for i in range(x)] people_have_money_count = 2 people_need_money_count = 5 people = list(string.ascii_uppercase) people_have_money = [] people_need_money = [] history = [] #people_need_money should not equal to people_have_money for i in range(people_have_money_count): name = random.choice(people) if (not name in people_have_money): people_have_money.append((name, 1)) for i in range(people_need_money_count): name = random.choice(people) if (not name in people_need_money): people_need_money.append((name, 0)) print("Peoples that need money: ") for i in (people_need_money): print(i[0]) print("Peoples that have money: ") for i in (people_have_money): print(i[0]) spab(5) for i in range(len(people_need_money)): angka0 = random.randint(0, len(people_need_money)-1) angka1 = random.randint(0, len(people_have_money)-1) borrow = people_need_money[angka0] lend = people_have_money[angka1] if (lend[0] == borrow[0]): continue print(lend[0], " Lending Money to ", borrow[0]) history += (lend, borrow) people_have_money.append(people_need_money[angka0]) #del people_need_money[angka0] del people_have_money[angka1] class Node: def __init__(self, data=None, selanjutnya=None): self.data = data self.selanjutnya = selanjutnya class Linked_List: head = None def __init__(self): pass def add(self, data): self.head = Node(data=data, selanjutnya=self.head) def the_last(self): return self.head.data def the_first(self): curr = self.head while (curr): if (curr.selanjutnya==None): break curr = curr.selanjutnya return curr.data LS = Linked_List() for i in range(len(history)): LS.add(history[i]) must_pay = LS.the_last() must_recv = LS.the_first() if must_pay[0] == must_recv[0]: print("No one must Pay") sys.exit(0) print(must_pay[0], "Must Pay to ", must_recv[0]) <file_sep>/4.py #!/usr/bin/python NullByteStringVariable = "Null Byte on wonderhowto.com is the Best Place on the Web to learn hacking"; NullByteIntegerVariable = 12 NullByteFloatingPointVariable = 3.1415 NullByteList = [1,2,3,4,5,6] NullByteDictonary = {'name': 'Occupytheweb', 'value': 27} print NullByteStringVariable print NullByteIntegerVariable print NullByteFloatingPointVariable<file_sep>/timer_input.py #!/usr/bin/python import time from threading import Thread answer = None def check(): time.sleep(10) if answer != None: return print("oke") Thread(target = check).start() answer = input("aku ") <file_sep>/tur7.py #!/usr/bin/python import turtle from turtle import * import random import time wn = turtle.Screen() #wn.bgpic("giphy.gif") wn.title("tesss") wn.bgcolor("black") kevin = turtle.Turtle() col = ["red", "yellow", "green", "purple", "blue", "pink"] oke = 0#str(random.choice(col)) kevin.shape("turtle") kevin.color(random.choice(col)) kevin.penup() kevin.stamp() kevin.right(90) kevin.forward(200) kevin.left(90) kevin.forward(90) kevin.left(30) kevin.forward(150) time.sleep(2) for i in range(12): kevin.penup() kevin.color(col[oke]) kevin.left(30) kevin.forward(150) kevin.stamp() oke += 1 if oke == 6: oke = 0 """ kevin.penup() for a in range(2): kevin.left(90) kevin.forward(250) for i in range(11): kevin.pendown() kevin.color(col[oke]) kevin.stamp() kevin.left(30) kevin.penup() kevin.forward(150) oke += 1 if oke == 6: oke = 0 """ """ if True:#for i in range(6): kevin.color(col[oke]) kevin.forward(200) kevin.right(135) kevin.forward(300) kevin.right(150) kevin.forward(400) kevin.right(150) kevin.forward(400) kevin.right(150) kevin.forward(300) kevin.right(135) kevin.forward(200) oke += 1 if oke == 6: oke = 0 """ turtle.mainloop() <file_sep>/kev.py import re def bilbul(x): if float != type(x): return False y = str(x).replace(".", ",") y = int(y[0:((re.search(",", y).start()))]) if x <= (y + 0.5): return y else: return y + 1 spab = lambda x: [print(' ') for i in range(x)] <file_sep>/solo2.py #!/usr/bin/python #contoh input angka (1) oke=input ("masukan angka") print oke #end (1) #tambah2 kata (2) print 'aku'+' '+'hebat' #end (2) #tambah angka dan kata (3) print 'oke'+' '+'lah'+' '+'angkanya'+' '+'2'+' '+'dan'+' '+'3' #end (3) #penggandaan angka dan kata (4) print 4 * '2' #tanpa spasi jg gpp contohvariable = 2 * 'hebat' print "aku memang "+contohvariable+"" #string harus 2 dan set juga di varibalcall <file_sep>/urllib1.py import urllib.request from urllib.parse import urlsplit as spl import requests #print(urllib.request.urlopen("http://192.168.43.171").read()) #print(requests.get("http://192.168.43.171", headers={"user-agent": "Firefox-5.0"})) print(spl("http://127.0.0.1/kevin")) #requests.post("http://192.168.43.171", data={"Username": "kevin", "password": "<PASSWORD>"}) <file_sep>/timer_input2.py from threading import Thread import time import sys a = None def get(): global a a = input('press Y now! ') def timer(): time.sleep(2) if a != 'Y'.lower(): print('\ntoo slow\n') sys.exit() c = Thread(target = get, args = []) d = Thread(target = timer, args = []) d.start() c.start() <file_sep>/args.py #!/usr/bin/pyhton3 import sys #print(sys.argv[0]) print('commandnya %s' %(sys.argv[1])) <file_sep>/kivy0.py import kivy from kivy.app import App from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.uix.gridlayout import GridLayout class Login(GridLayout): def __init__(self, **kwargs): super(Login, self).__init__(**kwargs) self.cols = 2 self.add_widget(Label(text="Nama")) self.nama = TextInput(multiline=False) self.add_widget(self.nama) self.add_widget(Label(text="kata-kata sandi")) self.sandi = TextInput(multiline=False, password=True) self.add_widget(self.sandi) class aplikasi(App): def build(self): return Login() aplikasi().run()<file_sep>/numpy_latihan.py import numpy a = numpy.array([1, 2, 3], ndmin=2, dtype=complex) print(a) b = numpy.array([1, 2, 3], dtype=complex, order='C') print(b) <file_sep>/tur9.py #!/usr/bin/python import turtle from turtle import * import random agusto = turtle.Screen() kevin = turtle.Turtle() kevin1 = turtle.Turtle() agusto.bgcolor('black') agusto.title('mantap jiwa') col = ['red', 'yellow', 'green', 'blue', 'purple', 'orange'] colll = 0 si = 50 kevin.color('white') kevin.speed(10) def minisr(x): for i in range(5): kevin.color(col[x]) kevin.forward(50) kevin.right(90) def squarer(coll): kevin.penup() kevin.left(90) plur = kevin.forward(50) kevin.forward(300) kevin.right(90) kevin.forward(650) coll = 0 kevin.right(90) kevin.pendown() for a in range(14): minisr(coll) coll += 1 tuf = kevin.left(90) if coll == 6: coll = 0 squarer(1) """ for i in range (10): squarer(1) si += 50 coll += 1 if coll == 6: coll = 1 """ turtle.mainloop() <file_sep>/turtle.py #!/usr/bin/python import turtle wn = turtle.Screen() alex = turtle.Turtle() wn.bgcolor("blue") wn.title("kevin") alex.color("green") alex.pensize(10) alex.forward(50) alex.left(90) alex.forward(30) turtle.mainloop() <file_sep>/latihan5.py class coba: def __init__(self, x): print("from init") def __new__(self, x): print("from new") def coba1(massa, kecepatan) -> "Joules": return massa+kecepatan def main(): print(coba1.__annotations__) print(coba1(100, 200)) print(coba1.__name__) oke = coba(10) main() <file_sep>/monitoring.py #!/usr/bin/python import time import random import string while True: lis = list(string.ascii_uppercase) ran = str(random.choice(lis)) mac = (str('(') + ran + ran + str(':') + ran + ran + str(':') + ran + ran + str(')')) print('MONINTORING IP AND PORT(HONEYPOT ACTIVATED) %s' % (mac)) time.sleep(1) <file_sep>/tg1.py import time num = "WOW" for i in range(10): print(num, end='\r') time.sleep(1) num = "wOW" <file_sep>/solo8.py #!/usr/bin/python print 'penggunaan elif' nomor = 3 if nomor == 5: print 'nomor 5' elif nomor == 4: #jadi if nomor 5 print anu...elif print apa elif print apa print 'kece' elif nomor == 2: print 'salah' elif nomor == 3: print "bener" print ' ' print ' ' print 'penggunaan and atau boolean magic' lagi = 1 == 1 and 2==2 lagi1 = 1==1 and 2==3 print lagi print lagi1 print 'penggunaan boolean magic kurung' if(1==1) and (2+4>5): print 'benerbngt' else: #ga bisa pake elif print 'salahbngt'<file_sep>/Node.py class Node: def __init__(self, cargo=None, next=None): self.cargo = cargo self.next = next def __str__(self): return str(self.cargo) node = Node("test") node1 = Node(1) node2 = Node(2) node3 = Node(3) def print_list(node): while (not node==None): print(node, end = " ") node = node.next print() node1.next = node2 node2.next = node3 print(node1.next) print_list(node1) <file_sep>/userid.py #!/usr/bin/python if username == root: print "aku root" <file_sep>/tur.py #!/usr/bin/python import turtle wn = turtle.Screen() alex = turtle.Turtle() alex.forward(50) alex.left(90) alex.forward(30) turtle.mainloop() <file_sep>/6.py #!/usr/bin/python if uid == 0: print "aku root" else: print "aku invisiblename" <file_sep>/solo13.py #!/usr/bin/python print 'penggunaan list yodaf' print ' ' nomor = 3 things = ["strings",0,[1,2,nomor],4.56] print things[1] print things[2] print things[2][2] print things [3] print ' ' print 'penggunaan lists lebih detail.ga detail amat' oke = "<NAME>" print oke[6] print ' ' print 'list beroperasi....asik...' mantap = [1,2,3,4,5,6,7,8] mantap[3] = 10 #list ketiga diubah menjadi 10 print mantap print ' lagi yuk' apalah = [1,2,3,4,5,6,7,8] apalah[4] = apalah[2] print apalah print ' ' print 'list beroprasi lagi...katanya gitu sih wkwkwk' hellium = [1,2,3] print hellium + [4,5,6] #di print juga bisa ditambahin....bebas print hellium * 3 print hellium[2] * 3<file_sep>/tur8.py #!/usr/bin/python import turtle from turtle import * agusto = turtle.Screen() kevin = turtle.Turtle() agusto.title("kevin") agusto.bgcolor("black") leftt = 5 size = 3 co = 0 col = ["red", "yellow", "green", "purple", "blue", "pink"] for i in range(100): kevin.color(col[co]) kevin.pensize(size) kevin.hideturtle() kevin.left(10) kevin.forward(leftt) co += 1 size += 1 if co == 6: co = 0 leftt += 1 leftt = 5 size = 3 kevinn = turtle.Turtle() for i in range(100): kevinn.color(col[co]) kevinn.pensize(size) kevinn.hideturtle() kevinn.right(10) kevinn.forward(leftt) co += 1 size += 1 if co == 6: co = 0 leftt += 1 turtle.mainloop() <file_sep>/thlatih.py #!/usr/bin/python3 from threading import Thread import time import random def waktu(detik): <file_sep>/data_hiding.py #!/usr/bin/python3 class oke: def __init__(self): self.__rahasia = "ini rahasia" s = oke() print(s._oke__rahasia) <file_sep>/solo7.py #!/usr/bin/python print "penggunaan if" aku = 9 if aku > 7: print("five") if aku < 100: print("buset") print ' ' print 'pake else' kamu = 90 if kamu == 900: print 'pas' else: print 'nga pas' print ' ' print ' ' print "ADVANCED PEMAKAIAN IF DAN ELSE DENGAN CHAIN" masa = 12 if masa == 90: print 'sembilan puluh' else: if masa == 12: print 'benar' else: if masa == 30: print 'salah' <file_sep>/tur10.py #!/usr/bin/python import turtle from turtle import * agusto = turtle.Screen() kevin = turtle.Turtle() # lingkaran besar kevinn = turtle.Turtle() #lingkaran kecil kevinnn = turtle.Turtle() #spiral kevin.hideturtle() kevinn.hideturtle() #kevinnn.hideturtle() agusto.bgcolor("black") agusto.title("mantap jiwa") kevinn.color("lightgreen") kevinn.speed(0) kevinn.right(90) kevinn.forward(50) kevinn.left(90) #spiral def spiral(loo): kevinnn.penup() kevinnn.color("lightgreen") kevinnn.speed(0) kevinnn.forward(60) kevinnn.left(90) kevinnn.pendown() kevinnn.forward(275) for b in range(180): kevinnn.left(1) kevinnn.forward(1) kevinnn.forward(550) for c in range(180): kevinnn.left(1) kevinnn.forward(1) kevinnn.forward(275) def spirall(lo): kevinnn.forward(275) for b in range(180): kevinnn.left(1) kevinnn.forward(1) kevinnn.forward(550) for c in range(180): kevinnn.left(1) kevinnn.forward(1) kevinnn.forward(275) spiral(1) for f in range(360): angk = 1 kevinnn.right(angk) spirall(1) angk += 1 #spiral(1) #lingkaran kecil kevinn for a in range(360): kevinn.left(1) kevinn.forward(1) kevin.penup() kevin.color("lightgreen") kevin.speed(10) kevin.right(90) kevin.forward(300) kevin.left(90) kevin.pendown() #lingkaran besar kevin for x in range(360): kevin.left(1) kevin.forward(5) turtle.mainloop() <file_sep>/aestes.py #!/usr/bin/python from Crypto.Cipher import AES #oke = input("e or d? ") ulang = 1 while ulang == 1: oke = input("apa ? ") if oke.lower() == 'e': key = '<KEY>' IV = '<PASSWORD>'#16 * '\x00' mode = AES.MODE_CBC encryptor = AES.new(key, mode, IV=IV) text = 'kevinkevinkevin1' ciphertext = encryptor.encrypt(text) print(ciphertext) if oke.lower() == 'd': key = '<KEY>' IV = '<PASSWORD>' #16 * '\x00' mode = AES.MODE_CBC decryptor = AES.new(key, mode, IV=IV) # text = 'kevinkevinkevin1' ciphertext1 = decryptor.decrypt(ciphertext).decode('utf-8') print(ciphertext1) ulang = int(input('lagi? ')) #oke = input("E / D? ") #if oke.lower == 'e': <file_sep>/latihana.py #!/usr/bin/python x = 4 y = 2 if not 1+1 == y or x == 4 and 7 == 8: print 'yes' elif x > y: print 'no'<file_sep>/thread1.py #!/usr/bin/python from threading import Thread import time jawab = None def inp(): jawab = input('kata-kata : ') return jawab = jawab def waktu(sec): time.sleep(sec) if jawab != None: return print(""" too slow baby""") exit() oke = Thread(target=inp, args=[]) eko = Thread(target=waktu, args=[5]) oke.start() eko.start() <file_sep>/solo11.py #!/usr/bin/python apakek = 0 while True: i = apakek + 2 if apakek == 2: print "lewati 2" continue if apakek == 8: print "stop" break print apakek print "oke"<file_sep>/access.py #!/usr/bin/python3 import os os.chdir('aes') chk = os.access("korban1.txt", os.W_OK) print(chk)<file_sep>/self.py class Yay: sen = 10 def __init__(self): print("INIT") self.x = 10 self.sen = self def bomb(self): return "Bomb" @bomb def bomb1(self): print("Bomb1") def wow(self, wo): print(wo.bomb()) def ooo(oke): print(oke) #ooo(10) def diri(self): return self @diri def dut(x): return x.bomb() x = 10 y = sen dut(y) y = Yay() print(y.dut())<file_sep>/2.py #!/usr/bin/python >>>2+2 4 >>>5+4-3 6<file_sep>/__str__.py class Oke: def __init__(self, oke): self.x = oke def __str__(self): return self.x + " WOw" print(Oke("kevin")) <file_sep>/tesurllib.py import urllib3 import urllib.request import re import math re.match #urllib.request.urlopen('https://www.whatismyip.org/').readlines()[0] import shutil import os import sys from Crypto.Hash import MD5 oke = MD5.new(b"wow") oke = oke.hexdigest() import math math.sin(10) print(oke) import daemon import socket socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.SO_REUSEADDR, 1) #print("oke banget".replace("banget", "gila")) "oke nice".split("\n") sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) oke = "wow" import platform import subprocess import zipfile #zipfile.ZipFile.setpassword(b"oke") sys.stderr import pwn import random import binascii <file_sep>/solo14.py #!/usr/bin/python print 'masih list yang beroperasi...jadi LETS GO' kata = ["nothing","to","see","here"] print "to" in kata print "nothing" in kata print "aku" in kata print ' ' print 'lisst emang simple..pake if dan in' nomor = [10,9,8,7,6,5] nomor[0] = nomor[1] - 5 if 4 in nomor: print nomor[3] else: print nomor[4] print ' ' print 'list pake not dan in' apaan = [1,2,3] print not 4 in apaan #tdk ada 4 in apaan....true print 4 not in apaan print not 3 in apaan #tdk ada 3 in apaan....salahFALSE print 3 not in apaan print ' ' print 'list function....asekk...kece' aseek = [1,2,3] aseek.append(4) #pake append menambahkan item di akhir list yang sdh ad print aseek print ' ' print 'function len' asoy = [3,5,1,5,6,1] print len(asoy) #len untuk gitu lah...itu di list ada 6 item jd 6 #hasilnya print ' ' print 'fucntion insert pada list' joz = ["python","fun"] index = 1 #bisa juga g pke index joz.insert(2,"kawan") joz.insert(index,"is") #2 diatas itu posisi print joz print ' ' print '' <file_sep>/warworld.py class Warworld: roboot = [None, 'Panther', 'Python', 'Thunder', 'Assault', 'Leviathan'] handgun = [[None, 'Yellow', 'Blacker', 'Blade1', 'Blade2'], [None, 'Singlegun', 'Triplegun', 'Xenon']] missile = [None, 'TwoShot', 'StormExtreme'] mortar = [None, 'Bomber', 'Armageddon'] speeder = [None, 'SideSpeed', 'ForwardSpeed', 'JumpSpeed'] shield = ['Sideshield', 'OracleShield', 'PerfectShield1', 'PerfectShield2'] spec = [] count = 0 def __init__(self, robot): self.robot = Warworld.roboot[robot] Warworld.spec.append(["Robot1 spec: "]) Warworld.spec[Warworld.count].append("Model: %s " %(self.robot)) def frontgun(self, type0, type1, gun0, gun1): lefthand = Warworld.handgun[type0][gun0] righthand = Warworld.handgun[type1][gun1] Warworld.spec[Warworld.count].append("Right Gun model: %s" %(righthand)) Warworld.spec[Warworld.count].append("Left Gun model: %s" %(lefthand)) def backequip(self, mis, mor, spe): misil = missile[mis] mortaar = mortar[mor] speder = speeder[spe] oke = Warworld(1) oke.frontgun(0, 1, 2, 3) print(oke.spec[len(oke.spec) - 1]) <file_sep>/wanjer1.py #!/usr/bin/python nama="KOCAG" namapanjang="purwira" print "nama depananya "+nama+" nama belakangnya "+namapanjang+"" umur=20 print umur type (umur) umur = "dua puluh satu" print (umur) print ""+umur+"" type (umur) namaDepan = "Budi" namaBelakang="Susanto" nama = namaDepan + " " + namaBelakang umur = 22 hobi="Berenang" print ("Biodata", nama, "\n", umur, "\n", hobi) #contoh vairable lain inivariable = "hello" ini_juga_variable = "you alive" _inivariablejuga = "of course thats my job to shooted at my head" inivariable = "great" panjang = 50 lebar = 5 luas = panjang * lebar print (luas)<file_sep>/th.py #!/usr/bin//python3 from threading import Thread as th from time import sleep as sl import os import sys import time import platform import getpass from Crypto.Cipher import AES jawab = None def periksa(): sl(2) if jawab != None: return print(""" too slow baby""") try: raise KeyboardInterrupt except KeyboardInterrupt: exit() trit = th(target = periksa, args = []) trit.start() jawab = input('message: ') #periksa configuration file cwd = os.getcwd() print('now in dir %s' % (cwd)) sl(1) print(""" now checking conf file at root dir """) """ lanj = 0 null = 0 agg0 = 'Kevin' agg1 = 'kEvin' agg2 = 'keVin' agg3 = 'kevIn' agg4 = 'keviN' for aaa in range(10): if null == 0: print(agg0, end='\r') elif null == 1: print(agg1, end='\r') elif null == 2: print(agg2, end='\r') elif null == 3: print(agg3, end='\r') elif null == 4: print(agg4, end='\r') else: print('error') null += 1 if null == 4: lanj = 1 null = 0 sl(1) """ def spab(jml): for abc in range(jml): print(' ') os.chdir('/') os.access('rootkit.conf', os.W_OK) with open('rootkit.conf', 'r') as file: print(file.read()) time.sleep(2) spab(5) with open('rootkit.conf', 'r') as filee: print(list(filee.readlines(1))) print(filee[0]) #okea = open('rootkit.conf', 'r') #print(list(okea.readline(1))) <file_sep>/tesdic.py #!/usr/bin/python import socket import string mldi = 0 dicti = {} dictii = {} kata = list(string.ascii_lowercase) for lala in range(26): dicti[kata[mldi]] = mldi dictii[mldi] = [kata[mldi]] mldi += 1 spasi = " " kata.append(spasi) dicti[spasi] = '/' print(dicti) print("============") print(dicti['a']) <file_sep>/tur3.py #!/usr/bin/python import turtle wn = turtle.Screen() wn.bgcolor("yellow") wn.title("ikeh") tess = turtle.Turtle() tess.color("hotpink") tess.pensize(5) alex = turtle.Turtle() tess.forward(80) tess.left(120) tess.forward(80) tess.left(120) tess.forward(80) tess.left(120) alex.forward(50) alex.left(90) alex.forward(50) alex.left(90) alex.forward(50) alex.left(90) alex.forward(50) alex.left(90) turtle.mainloop() <file_sep>/solo9.py #!/usr/bin/python print 'penggunaan and or not' #and or not itu boolean magic print "(and:)" boandst = 1 == 1 and 2 == 2 #kalo dua2ny bener true print boandst boandnd = 1 == 1 and 2 == 3 print boandnd print " " print "pake or" #kalo salah satu dari mereka atau dua2ny bener true boorst = 1 == 1 or 2 == 2 boornd = 1==1 or 2==3 boorrd = 1==2 or 3==4 print boorst print boornd print boorrd print ' ' print 'pake not' #cuma satu argument bonotst = 1 == 1 #sma kaya 1 != 1 bonotnd = 2 == 3 print bonotst print bonotnd print ' ' print 'boolean pke if' mjk = 1+1 if not True: print '1' elif not (1+1 == 3): print ("2") else: print '3'<file_sep>/game2.py import os import time print("okebangetkan") time.sleep(5) os.system("clear") time.sleep(5) print("okebANGETKAN")
062478b4ae30d2b3f1b65f340953bd919be68fed
[ "Python" ]
84
Python
KevinAS28/Python-Training
2da3c18842071789a6e7e116b58d1ef407b35a5b
af7c162ee86ffd5d89cce60e9b2db98b4d65a21d
refs/heads/master
<file_sep># AutoUpgrade.Net <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AutoUpgrade.Net.Release { internal class ConfigTextProperty : TextBox { #region 变量 private Config config; private string propertyName; #endregion #region 属性 public Config Config { get => this.config; set { this.config = value; this.SetText(); } } public string PropertyName { get => this.propertyName; set { this.propertyName = value; this.SetText(); } } #endregion protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); PropertyInfo propertyInfo = typeof(Config).GetProperty(this.PropertyName); object property = propertyInfo.GetValue(this.Config); if (propertyInfo.PropertyType.IsArray) { propertyInfo.SetValue(this.Config, this.Text.Split(',').Select(s => s.Trim()).Where(s => s != string.Empty).ToArray()); } else { propertyInfo.SetValue(this.Config, this.Text); } config.SaveAsXML(); } private void SetText() { if (this.Config == null || this.PropertyName == null) { return; } PropertyInfo propertyInfo = typeof(Config).GetProperty(this.PropertyName); object property = propertyInfo.GetValue(this.Config); if (propertyInfo.PropertyType.IsArray) { this.Text = property == null ? string.Empty : string.Join(",", ((string[])property)); } else { this.Text = property == null ? string.Empty : property.ToString(); } } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Text; namespace AutoUpgrade.Net.Core { public class PartialFileStream : Stream { #region 变量 private long from; private long to; private long position; private FileStream fileStream; #endregion public override bool CanRead => this.fileStream.CanRead; public override bool CanSeek => this.fileStream.CanSeek; public override bool CanWrite => this.fileStream.CanWrite; public override long Length => this.to - this.from + 1; public override long Position { get => this.position; set { this.position = value; this.fileStream.Seek(this.position, SeekOrigin.Begin); } } public PartialFileStream(string filePath, long from, long to) { this.from = from; this.position = from; this.to = to; this.fileStream =System.IO. File.OpenRead(filePath); if (from > 0) { this.fileStream.Seek(from, SeekOrigin.Begin); } } public override void Flush() => this.fileStream.Flush(); public override int Read(byte[] buffer, int offset, int count) { int byteCountToRead = count; if (this.position + count > this.to) { byteCountToRead = (int)(this.to - this.position) + 1; } var result = this.fileStream.Read(buffer, offset, byteCountToRead); this.position += byteCountToRead; return result; } public override long Seek(long offset, SeekOrigin origin) { if (origin == SeekOrigin.Begin) { this.position = this.from + offset; return this.fileStream.Seek(this.from + offset, origin); } else if (origin == SeekOrigin.Current) { this.position += offset; return this.fileStream.Seek(this.position + offset, origin); } else { throw new NotImplementedException("SeekOrigin.End未实现"); } } public override void SetLength(long value) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { int byteCountToRead = count; if (this.position + count > this.to) { byteCountToRead = (int)(this.to - this.position); } var result = this.fileStream.BeginRead(buffer, offset, count, (s) => { this.position += byteCountToRead; callback(s); }, state); return result; } public override int EndRead(IAsyncResult asyncResult) { return this.fileStream.EndRead(asyncResult); } public override int ReadByte() { int result = this.fileStream.ReadByte(); this.position++; return result; } protected override void Dispose(bool disposing) { if (disposing) { this.fileStream.Dispose(); } base.Dispose(disposing); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutoUpgrade.Net.Client.ServerAPIs { public class APIProvider { public static IAuthAPI AuthAPI { get; } = new APIMock.AuthAPIMock(); public static IUpgradeAPI UpgradeAPI { get; } = new APIMock.UpgradeAPIMock(); } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace AutoUpgrade.Net.Client.ServerAPIs.APIMock { internal class AuthAPIMock : IAuthAPI { public async Task<string> GetToken(string userName, string password) { using (HttpClient httpClient = new HttpClient()) { try { HttpResponseMessage httpResponseMessage = await httpClient.GetAsync($"http://127.0.0.1:9099/api/Authenticate/token?name={userName}&password={password}&appId=Upgrader"); if (httpResponseMessage.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<Token>(await httpResponseMessage.Content.ReadAsStringAsync()).access_token; } } catch (Exception ex) { return null; } } return null; } private class Token { public string access_token { get; set; } public int expires_in { get; set; } } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using IdentityModel; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json.Serialization; using Swashbuckle.AspNetCore.Swagger; namespace AutoUpgrade.Net.Server { public class Startup { //Auth秘钥 public static readonly SymmetricSecurityKey symmetricKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("<KEY>")); public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss.fff"; }); var tokenProviderOptions = new TokenProviderOptions(Configuration); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(tokenProviderOptions.SetJwtBearerOptions); services.AddSingleton(tokenProviderOptions); //注册Swagger生成器,定义一个和多个Swagger 文档 services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info { Title = "UpgradeServer API", Version = "v1" }); //启用auth支持 options.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"", Name = "Authorization",//jwt默认的参数名称 In = "header",//jwt默认存放Authorization信息的位置(请求头中) Type = "apiKey" }); // 为 Swagger JSON and UI设置xml文档注释路径 var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径) var xmlPath = Path.Combine(basePath, "UpgradeServer.xml"); options.IncludeXmlComments(xmlPath); options.OperationFilter<HttpHeaderOperation>(); options.DocumentFilter<ControllerDescFilter>(xmlPath); options.OrderActionsBy(a => a.HttpMethod); }); services.Configure<IISOptions>(options => { }); //依赖注入获取HttpContext services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseAuthentication(); //启用中间件服务生成Swagger作为JSON终结点 app.UseSwagger(); //启用中间件服务对swagger-ui,指定Swagger JSON终结点 app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "UpgradeServer API V1"); c.RoutePrefix = string.Empty; }); app.UseMvc(); } } } <file_sep>namespace AutoUpgrade.Net.Args { public class ErrorArgs { /// <summary> /// /// </summary> /// <param name="error">错误内容</param> public ErrorArgs(string error) { Error = error; } /// <summary> /// 错误内容 /// </summary> public string Error { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; using System.Text; namespace AutoUpgrade.Net.Tools { /// <summary> MD5工具类 /// </summary> public static class MD5Tools { /// <summary> 获取文件的MD5特征码 /// </summary> /// <param name="filePath">文件路径</param> /// <returns></returns> public static string GetFileMd5(string filePath) { try { using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { return GetStreamMd5(fs); } } catch (Exception e) { return ""; } } /// <summary> 获取文件的MD5特征码 /// </summary> /// <param name="filePath">文件路径</param> /// <returns></returns> public static byte[] GetFileMd5Bytes(string filePath) { try { using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { return GetStreamMd5Bytes(fs); } } catch (Exception e) { return null; } } /// <summary> 获取流的MD5特征码 /// </summary> /// <param name="filePath">文件路径</param> /// <returns></returns> public static string GetStreamMd5(Stream stream) { try { using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) { return Md5BytesToMd5(md5.ComputeHash(stream)); } } catch (Exception e) { return ""; } } /// <summary> 获取流的MD5特征码 /// </summary> /// <param name="filePath">文件路径</param> /// <returns></returns> public static byte[] GetStreamMd5Bytes(Stream stream) { try { using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) { return md5.ComputeHash(stream); } } catch (Exception e) { return null; } } /** * 16进制字符集 */ private static char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /** * 将单个字节码转换成16进制字符串 * @param bt 目标字节 * @return 转换结果 */ public static String byteToHex(byte bt) { return HEX_DIGITS[(bt & 0xf0) >> 4] + "" + HEX_DIGITS[bt & 0xf]; } public static string bytesToHex(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { sb.Append(byteToHex(bytes[i])); } return sb.ToString(); } /// <summary> byte[]转MD5 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetBytesMd5(byte[] data) { try { using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) { return Md5BytesToMd5(md5.ComputeHash(data)); } } catch (Exception e) { return ""; } } /// <summary> Md5的byte[]转MD5 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string Md5BytesToMd5(byte[] data) { try { return BitConverter.ToString(data).Replace("-", ""); } catch (Exception e) { return ""; } } /// <summary> 字符串转MD5 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetStringMd5(string str, Encoding encoding) { byte[] data = encoding.GetBytes(str); try { using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) { return Md5BytesToMd5(md5.ComputeHash(data)); } } catch (Exception e) { return ""; } } /// <summary> 字符串转MD5 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetStringMd5(string str) { return GetStringMd5(str, Encoding.GetEncoding("GB2312")); } } } <file_sep>using AutoUpgrade.Net.Json; using AutoUpgrade.Net.Tools; using System.IO; namespace AutoUpgrade.Net.Release { public class FileScan { /// <summary> 比较结果 /// </summary> public enum CompareResult { /// <summary> /// 正常 /// </summary> Normal = 0, /// <summary> /// 新增 /// </summary> Filter = 1, /// <summary> /// 新增 /// </summary> Add = 2, /// <summary> /// 移除 /// </summary> Remove = 3, /// <summary> /// 更新 /// </summary> Update = 4 } /// <summary> /// 文件名 /// </summary> public string Name { get; set; } /// <summary> /// 文件名 /// </summary> public string FullPath { get; set; } /// <summary> /// 文件MD5 /// </summary> public string MD5 { get; set; } /// <summary> /// 文件大小 /// </summary> public long Length { get; set; } /// <summary> /// 文件版本号 /// </summary> public string Version { get; set; } /// <summary> /// 文件比对结果 /// </summary> public CompareResult Result { get; set; } public FileScan(JsonFileDetail jsonFileDetail) { this.Name = jsonFileDetail.Name; this.MD5 = jsonFileDetail.MD5; this.Length = jsonFileDetail.Length; } public FileScan(string dir, string name, bool calcMD5 = true) { this.FullPath = Path.Combine(dir, name); this.Length = new FileInfo(this.FullPath).Length; this.Version = System.Diagnostics.FileVersionInfo.GetVersionInfo(this.FullPath).ProductVersion; this.Name = name; if (calcMD5) { this.MD5 = MD5Tools.GetFileMd5(this.FullPath); } } public override string ToString() { return Name + "-----" + MD5; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutoUpgrade.Net.Client.ServerAPIs { public interface IAuthAPI { Task<string> GetToken(string userName, string password); } } <file_sep>namespace AutoUpgrade.Net.Args { public class ProgressChangedArgs { /// <summary> /// /// </summary> /// <param name="read">当次读取</param> /// <param name="loaded">已读取</param> /// <param name="total">总长度</param> public ProgressChangedArgs(int read, long loaded, long total) { Read = read; Loaded = loaded; Total = total; } /// <summary> /// 当次读取 /// </summary> public int Read { get; set; } /// <summary> /// 已读取 /// </summary> public long Loaded { get; set; } /// <summary> /// 总长度 /// </summary> public long Total { get; set; } public override string ToString() { return "Read:" + Read + "|" + "Loaded:" + Loaded + "|" + "Total:"+ Total; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AutoUpgrade.Net.Release { internal class ConfigBoolProperty : CheckBox { #region 变量 private Config config; private string propertyName; #endregion #region 属性 public Config Config { get => this.config; set { this.config = value; this.SetChecked(); } } public string PropertyName { get => this.propertyName; set { this.propertyName = value; this.SetChecked(); } } #endregion protected override void OnCheckedChanged(EventArgs e) { base.OnCheckedChanged(e); PropertyInfo propertyInfo = typeof(Config).GetProperty(this.PropertyName); propertyInfo.SetValue(this.Config, this.Checked); config.SaveAsXML(); } private void SetChecked() { if (this.Config == null || this.PropertyName == null) { return; } PropertyInfo propertyInfo = typeof(Config).GetProperty(this.PropertyName); this.Checked = (bool)propertyInfo.GetValue(this.Config); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutoUpgrade.Net.Client.Json { public class FileItem { /// <summary> /// 文件名 /// </summary> public string Name { get; set; } /// <summary> /// 文件Url /// </summary> public string Url { get; set; } /// <summary> /// 文件MD5 /// </summary> public string MD5 { get; set; } /// <summary> /// 文件大小 /// </summary> public long Length { get; set; } } } <file_sep>using AutoUpgrade.Net.Json; using Newtonsoft.Json; using System; using System.Diagnostics; using System.IO; using System.Linq; namespace AutoUpgrade.Net.Server { public class UpgradeServer { private string upgradeRoot = string.Empty; /// <summary> /// 服务端升级 /// </summary> /// <param name="downloadRoot">升级目录</param> public UpgradeServer(string upgradeRoot) { this.upgradeRoot = upgradeRoot; } private static string baseDirector = AppContext.BaseDirectory; #region const private const int BufferSize = 80 * 1024; #endregion /// <summary> 升级根目录 /// </summary> private string UpgradeRoot { get { string downloadRoot = Path.Combine(baseDirector, this.upgradeRoot); if (!Directory.Exists(downloadRoot)) { Directory.CreateDirectory(downloadRoot); } return downloadRoot; } } /// <summary> 通过文件名获取服务器上的文件路径 /// </summary> /// <param name="fileName"></param> /// <returns></returns> private string GetServerFilePath(string fileName) { return Path.Combine(UpgradeRoot, fileName); } public JsonRespondResult CreateVersion(JsonReleaseVersion jsonReleaseVersion) { JsonReleaseVersion[] jsonReleaseVersions = this.GetVersionList(); if (jsonReleaseVersions.Length > 0) { jsonReleaseVersion += jsonReleaseVersions[jsonReleaseVersions.Length - 1]; } string dir = GetServerFilePath(jsonReleaseVersion.Version); string path = dir + ".json"; try { if (!File.Exists(path)) { File.WriteAllText(path, JsonConvert.SerializeObject(jsonReleaseVersion)); } if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (File.Exists(path) && Directory.Exists(dir)) { return new JsonRespondResult() { Message = "新增版本" + jsonReleaseVersion.Version }; } return new JsonRespondResult() { Result = false, Message = "版本" + jsonReleaseVersion.Version + "新增失败" }; } catch (Exception ex) { return new JsonRespondResult() { Result = false, Message = ex.Message }; } } public JsonRespondResult DeleteVersion(string version) { string dir = GetServerFilePath(version); string path = dir + ".json"; try { if (File.Exists(path)) { File.Delete(path); } if (Directory.Exists(dir)) { Directory.Delete(dir, true); } if (!File.Exists(path) && !Directory.Exists(dir)) { return new JsonRespondResult() { Message = "已删除版本" + version }; } return new JsonRespondResult() { Result = false, Message = "版本" + version + "删除失败" }; } catch (Exception ex) { return new JsonRespondResult() { Result = false, Message = ex.Message }; } } public JsonRespondResult DeleteFile(string fileName) { string filePath = GetServerFilePath(fileName); try { if (File.Exists(filePath)) { File.Delete(filePath); } if (!File.Exists(filePath)) { return new JsonRespondResult() { Message = "已删除文件" + fileName }; } return new JsonRespondResult() { Result = false, Message = "文件" + fileName + "删除失败" }; } catch (Exception ex) { return new JsonRespondResult() { Result = false, Message = ex.Message }; } } public JsonReleaseVersion[] GetVersionList() { string[] files = Directory.GetFiles(this.UpgradeRoot, "*.json"); return files.Select(f => JsonConvert.DeserializeObject<JsonReleaseVersion>(File.ReadAllText(f))).OrderBy(v => new Version(v.Version)).ToArray(); } public JsonReleaseVersion CheckVersion(string version) { if (Version.TryParse(version, out Version v)) { string[] files = Directory.GetFiles(this.UpgradeRoot, "*.json"); JsonReleaseVersion[] jsonReleaseVersions = files .OrderByDescending(f => Version.Parse(Path.GetFileNameWithoutExtension(f))) .TakeWhile((f) => Version.Parse(Path.GetFileNameWithoutExtension(f)) > v) .Select(f => JsonConvert.DeserializeObject<JsonReleaseVersion>(File.ReadAllText(f))).ToArray(); if (jsonReleaseVersions.Length == 0) { return null; } string updateContent = string.Join("\r\n-----------------------------------\r\n" , jsonReleaseVersions .Reverse() .Select(j => "V" + j.Version + "版本更新内容:\r\n" + j.UpdateContent)); jsonReleaseVersions[0].Type = jsonReleaseVersions.Select(j => j.Type).Aggregate((t1, t2) => (t1 == JsonReleaseVersion.ReleaseType.Force || t2 == JsonReleaseVersion.ReleaseType.Force) ? JsonReleaseVersion.ReleaseType.Force : JsonReleaseVersion.ReleaseType.Choice); jsonReleaseVersions[0].UpdateContent = updateContent; return jsonReleaseVersions[0]; } else { return null; } } /// <summary> /// 是否可升级 /// </summary> /// <param name="version"></param> /// <returns></returns> public bool Upgradeable(string version) { if (Version.TryParse(version, out Version v)) { return Directory.GetFiles(this.UpgradeRoot, "*.json") .Select(f => Version.Parse(Path.GetFileNameWithoutExtension(f))) .OrderByDescending(vs => vs) .FirstOrDefault() > v; } else { return false; } } public JsonRespondResult GetFileVersion(string fileName) { string filePath = Path.Combine(this.UpgradeRoot, fileName); if (File.Exists(filePath)) { return new JsonRespondResult() { Message = FileVersionInfo.GetVersionInfo(filePath).ProductVersion }; } else { return new JsonRespondResult() { Result = false, Message = "无法找到文件" }; } } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace AutoUpgrade.Net.Release { /// <summary> /// 对象xml序列化 /// </summary> /// <typeparam name="T"></typeparam> public class IPersistenceXML<T> where T : IPersistenceXML<T>, new() { /// <summary> 根据类型获取持久化文件的名称 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> private static string GetPersistenceFileName() { return AppDomain.CurrentDomain.BaseDirectory + typeof(T).Name; } /// <summary> 是否存在默认路径的XML文档 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public bool ExistDefaultXMLConfig() { string path = GetPersistenceFileName() + ".xml"; return File.Exists(path); } /// <summary> 将对象保存为XML文档 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="persistenceXML"></param> public void SaveAsXML() { string path = GetPersistenceFileName() + ".xml"; using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write)) { new XmlSerializer(typeof(T)).Serialize(fileStream, this); } } /// <summary> 加载XML文件 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="createInstanceWhenNonExists">如果文件不存在,指定一个创建函数</param> /// <returns>返回对象</returns> public static T LoadFromXML(Func<T> createInstanceWhenNonExists = null) { string path = GetPersistenceFileName() + ".xml"; if (!File.Exists(path)) { return createInstanceWhenNonExists?.Invoke() ?? new T(); } using (StreamReader streamReader = new StreamReader(path)) { try { return new XmlSerializer(typeof(T)).Deserialize(streamReader) as T; } catch(Exception ex) { return new T(); } } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace AutoUpgrade.Net.Client.Winform { public partial class Form1 : Form, IUILinker { private SynchronizationContext synchronizationContext; public Form1() { InitializeComponent(); synchronizationContext = SynchronizationContext.Current; } public bool Version { get; set; } public bool UpgradeLog { get; set; } public bool Skipable { get; set; } public bool RemindMeLaterable { get; set; } public bool Skip => true; public TimeSpan RemindMeLater => TimeSpan.FromMilliseconds(0); public void OutputMessage(string msg) { synchronizationContext.Send((obj) => { this.Text = msg; }, null); } public void Upgrade() { } protected async override void OnShown(EventArgs e) { base.OnShown(e); await UpgradeProcess.DoUpgradeAsync(this); this.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace AutoUpgrade.Net.Client.Commands { public abstract class Command { public abstract string Name { get; } public abstract string Code { get; } public abstract string Descript { get; } public virtual string Value { get; set; } internal virtual bool Nullable { get; } = true; internal virtual bool NullableCheck(out string msg) { var result = Nullable || (Value != null); msg = result ? null : $"{Name}({Code}): value can not be null!"; return result; } public override string ToString() { return Code + ":" + Name + "(" + Descript + ")"; } } } <file_sep>using AutoUpgrade.Net.Json; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace AutoUpgrade.Net.Core { /// <summary> 服务端上传 /// </summary> public class UploadServer { private string uploadRoot = string.Empty; /// <summary> /// 服务端上传 /// </summary> /// <param name="downloadRoot">上传目录</param> public UploadServer(string uploadRoot) { this.uploadRoot = uploadRoot; } private static string baseDirector = AppContext.BaseDirectory; #region const private const int BufferSize = 80 * 1024; #endregion /// <summary> 上传跟目录 /// </summary> private string UploadRoot { get { string uploadRoot = Path.Combine(baseDirector, this.uploadRoot); if (!Directory.Exists(uploadRoot)) { Directory.CreateDirectory(uploadRoot); } return uploadRoot; } } /// <summary> 异步获取下载流 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public Task<JsonRespondResult> Upload(HttpRequest httpRequest, string uploadDir = null) { return Task<JsonRespondResult>.Run(() => { try { List<JsonRespondResult> error = new List<JsonRespondResult>(); foreach (var formFile in httpRequest.Form.Files) { JsonRespondResult respondResult = null; if (formFile.Name == "file") { respondResult = this.UploadOnce(formFile, uploadDir); } else { respondResult = this.UploadChunk(formFile, uploadDir); } if (!respondResult.Result) { error.Add(respondResult); } } if (error.Count == 0) { return new JsonRespondResult() { Message = "上传成功" }; } else { return new JsonRespondResult() { Result = false, Message = "上传失败", Details = error.Select(e => e.Message).ToArray() }; } } catch (Exception ex) { return new JsonRespondResult() { Result = false, Message = "上传失败" + ex.Message }; } }); } /// <summary> 上传 /// </summary> /// <param name="fileName"></param> /// <returns></returns> private JsonRespondResult UploadOnce(IFormFile formFile, string uploadDir) { try { string dir = UploadRoot; if (!string.IsNullOrEmpty(uploadDir)) { dir = Path.Combine(UploadRoot, uploadDir); } if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } string filePath = Path.Combine(dir, formFile.FileName); if (!System.IO.File.Exists(filePath)) { using (Stream stream = System.IO.File.Create(filePath)) { formFile.CopyTo(stream); } return new JsonRespondResult() { Message = "上传成功" }; } return new JsonRespondResult() { Message = "已经存在无需上传" }; } catch (Exception ex) { return new JsonRespondResult() { Result = false, Message = formFile.FileName + ":上传失败" + ex.Message }; } } /// <summary> 分块上传 /// </summary> /// <param name="fileName"></param> /// <returns></returns> private JsonRespondResult UploadChunk(IFormFile formFile, string uploadDir) { try { string dir = Path.Combine(UploadRoot, formFile.FileName + "_Merge"); if (!string.IsNullOrEmpty(uploadDir)) { dir = Path.Combine(UploadRoot, uploadDir, formFile.FileName + "_Merge"); } if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } string chunkPath = Path.Combine(dir, formFile.Name); if (!System.IO.File.Exists(chunkPath)) { using (Stream stream = System.IO.File.Create(chunkPath)) { formFile.CopyTo(stream); } return new JsonRespondResult() { Message = "上传成功" }; } return new JsonRespondResult() { Message = "已经存在无需上传" }; } catch (Exception ex) { return new JsonRespondResult() { Result = false, Message = formFile.FileName + ":的分块" + formFile.Name + " 上传失败" + ex.Message }; } } /// <summary> /// 合并分块 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public Task<JsonRespondResult> Merge(string fileName) { return Task<JsonRespondResult>.Run(() => { string dir = Path.Combine(this.UploadRoot, fileName + "_Merge"); if (!Directory.Exists(dir)) { return new JsonRespondResult() { Result = false, Message = "不存在合并的文件" + fileName }; } string filePath = Path.Combine(this.UploadRoot, fileName); try { string[] files = Directory.GetFiles(dir).OrderBy(p => Convert.ToInt32(Path.GetFileNameWithoutExtension(p))).ToArray(); using (Stream writeStream = System.IO.File.Create(filePath)) { for (int i = 0; i < files.Length; i++) { using (FileStream chunk = System.IO.File.OpenRead(files[i])) { byte[] buffer = new byte[1024]; int readLength = chunk.Read(buffer, 0, buffer.Length); while (readLength > 0) { writeStream.Write(buffer, 0, readLength); readLength = chunk.Read(buffer, 0, buffer.Length); } } } } return new JsonRespondResult() { Message = "合并成功" }; } catch (Exception ex) { return new JsonRespondResult() { Result = false, Message = "文件合并出错!请重新上传!" }; } finally { Directory.Delete(dir, true); } }); } ///// <summary> 通过文件名获取服务器上的文件路径 ///// </summary> ///// <param name="fileName"></param> ///// <returns></returns> //private static string GetServerFilePath(this string fileName) //{ // return Path.Combine(DownloadRoot, fileName); //} ///// <summary> 获取文件分块信息 ///// </summary> ///// <param name="request"></param> ///// <param name="filePath"></param> ///// <returns></returns> //private static PartialFileInfo GetPartialFileInfo(this HttpRequest request, string filePath) //{ // PartialFileInfo partialFileInfo = new PartialFileInfo(filePath); // if (RangeHeaderValue.TryParse(request.Headers[HeaderNames.Range].ToString(), out RangeHeaderValue rangeHeaderValue)) // { // var range = rangeHeaderValue.Ranges.FirstOrDefault(); // if (range.From.HasValue && range.From < 0 || range.To.HasValue && range.To > partialFileInfo.FileLength - 1) // { // return null; // } // var from = range.From; // var to = range.To; // if (from.HasValue) // { // if (from.Value >= partialFileInfo.FileLength) // { // return null; // } // if (!to.HasValue || to.Value >= partialFileInfo.FileLength) // { // to = partialFileInfo.FileLength - 1; // } // } // else // { // if (to.Value == 0) // { // return null; // } // var bytes = Math.Min(to.Value, partialFileInfo.FileLength); // from = partialFileInfo.FileLength - bytes; // to = from + bytes - 1; // } // partialFileInfo.IsPartial = true; // partialFileInfo.Length = to.Value - from.Value + 1; // } // return partialFileInfo; //} ///// <summary> 获取分块文件流 ///// </summary> ///// <param name="partialFileInfo"></param> ///// <returns></returns> //private static Stream GetPartialFileStream(this PartialFileInfo partialFileInfo) //{ // return new PartialFileStream(partialFileInfo.FilePath, partialFileInfo.From, partialFileInfo.To); //} ///// <summary> ///// 设置响应头信息 ///// </summary> ///// <param name="response"></param> ///// <param name="partialFileInfo"></param> ///// <param name="fileLength"></param> ///// <param name="fileName"></param> //private static void SetResponseHeaders(this HttpResponse response, PartialFileInfo partialFileInfo) //{ // response.Headers[HeaderNames.AcceptRanges] = "bytes"; // response.StatusCode = partialFileInfo.IsPartial ? StatusCodes.Status206PartialContent : StatusCodes.Status200OK; // var contentDisposition = new ContentDispositionHeaderValue("attachment"); // contentDisposition.SetHttpFileName(partialFileInfo.Name); // response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); // response.Headers[HeaderNames.ContentType] = "application/octet-stream"; // //response.Headers[HeaderNames.ContentMD5] = partialFileInfo.MD5; // response.Headers[HeaderNames.ContentLength] = partialFileInfo.Length.ToString(); // if (partialFileInfo.IsPartial) // { // response.Headers[HeaderNames.ContentRange] = new ContentRangeHeaderValue(partialFileInfo.From, partialFileInfo.To, partialFileInfo.FileLength).ToString(); // } //} ///// <summary> 获取下载流 ///// </summary> ///// <param name="fileName"></param> ///// <returns></returns> //public static Task<Stream> GetDownloadStreamAsync(HttpContext httpContext, string fileName) //{ // return Task.Run<Stream>(() => // { // string filePath = fileName.GetServerFilePath(); // PartialFileInfo partialFileInfo = httpContext.Request.GetPartialFileInfo(filePath); // httpContext.Response.SetResponseHeaders(partialFileInfo); // return partialFileInfo.GetPartialFileStream(); // }); //} ///// <summary> 获取下载流 ///// </summary> ///// <param name="fileName"></param> ///// <returns></returns> //public static Stream GetDownloadStream(HttpContext httpContext, string fileName) //{ // string filePath = fileName.GetServerFilePath(); // PartialFileInfo partialFileInfo = httpContext.Request.GetPartialFileInfo(filePath); // httpContext.Response.SetResponseHeaders(partialFileInfo); // return partialFileInfo.GetPartialFileStream(); //} } } <file_sep>using AutoUpgrade.Net.Tools; using System; using System.IO; using System.Text; using System.Threading.Tasks; namespace AutoUpgrade.Net.Core { public class DownloadFile : IDisposable { public static string Ext { get; } = ".downloadPart"; /// <summary> /// 是否是本地加载的还是从url加载的 /// </summary> private bool isLocal = true; private bool isAppend = false; private string downloadPartPath = string.Empty; private FileStream fileStream = null; public string URL { get; set; } public string MD5 { get; set; } public long Length { get; set; } public long RangeBegin => (this.fileStream?.Length ?? 0) - Position; public int Position => (this.isLocal || this.isAppend) ? (Encoding.UTF8.GetBytes(this.URL).Length + Encoding.UTF8.GetBytes(this.MD5 ?? string.Empty).Length + 4 + 4) : 0; private DownloadFile() { } /// <summary> /// 从url加载对象 /// </summary> /// <param name="downloadPartPath">文件路径</param> /// <param name="uRL">url</param> /// <param name="mD5">文件md5</param> /// <returns></returns> public static DownloadFile FromUrl(string downloadPartPath, string uRL) { DownloadFile downloadFile = new DownloadFile(); downloadFile.downloadPartPath = downloadPartPath; downloadFile.URL = uRL; //downloadFile.fileStream = System.IO.File.Create(downloadPartPath); downloadFile.isLocal = false; return downloadFile; } /// <summary> /// 执行本地化,如果是url下载 则赋值url上的md5,如果是本地文件续传则对比md5,md5不一致返回false并且删除本地文件 /// </summary> /// <param name="length"></param> /// <param name="mD5"></param> /// <returns></returns> public bool DoLocal(long? length, string mD5) { this.Length = length ?? -1; if (this.isLocal) { if (this.MD5 != mD5) { this.fileStream.Dispose(); System.IO.File.Delete(this.downloadPartPath); return false; } } else { this.fileStream = System.IO.File.Create(this.downloadPartPath); this.MD5 = MD5; this.AppendFileStream(); } return true; } /// <summary> 从文件流加载对象 /// </summary> /// <param name="fileStream"></param> /// <returns></returns> public static DownloadFile FromPartPath(string downloadPartPath) { DownloadFile downloadFile = new DownloadFile(); downloadFile.downloadPartPath = downloadPartPath; if (System.IO.File.Exists(downloadPartPath)) { //downloadFile.fileInfo = new FileInfo(partPath); downloadFile.fileStream = System.IO.File.Open(downloadPartPath, FileMode.Open, FileAccess.ReadWrite); if (downloadFile.fileStream.Length == 0) { downloadFile.fileStream.Dispose(); System.IO.File.Delete(downloadPartPath); return null; } byte[] urlLengthBytes = new byte[4]; downloadFile.fileStream.Read(urlLengthBytes, 0, 4); int urlLength = BitConverter.ToInt32(urlLengthBytes, 0); byte[] urlBytes = new byte[urlLength]; downloadFile.fileStream.Read(urlBytes, 0, urlLength); byte[] md5LengthBytes = new byte[4]; downloadFile.fileStream.Read(md5LengthBytes, 0, 4); int md5Length = BitConverter.ToInt32(md5LengthBytes, 0); byte[] md5Bytes = new byte[md5Length]; downloadFile.fileStream.Read(md5Bytes, 0, md5Length); //byte[] lengthBytes = new byte[8]; //downloadFile.fileStream.Read(lengthBytes, 0, 8); downloadFile.URL = Encoding.UTF8.GetString(urlBytes); downloadFile.MD5 = Encoding.UTF8.GetString(md5Bytes); downloadFile.MD5 = downloadFile.MD5 == string.Empty ? null : downloadFile.MD5; //downloadFile.Length = BitConverter.ToInt64(lengthBytes, 0); downloadFile.fileStream.Position = downloadFile.fileStream.Length; } return downloadFile; } public async Task Write(byte[] array, int offset, int count) { this.fileStream.Write(array, offset, count); await this.fileStream.FlushAsync(); } /// <summary> 吧对象追加到文件流的结尾 /// </summary> private void AppendFileStream() { byte[] urlBytes = Encoding.UTF8.GetBytes(this.URL); int urlLength = urlBytes.Length; byte[] urlLengthBytes = BitConverter.GetBytes(urlLength); this.fileStream.Write(urlLengthBytes, 0, urlLengthBytes.Length); this.fileStream.Write(urlBytes, 0, urlBytes.Length); byte[] md5Bytes = Encoding.UTF8.GetBytes(this.MD5 ?? string.Empty); int md5Length = md5Bytes.Length; byte[] md5LengthBytes = BitConverter.GetBytes(md5Length); this.fileStream.Write(md5LengthBytes, 0, md5LengthBytes.Length); this.fileStream.Write(md5Bytes, 0, md5Bytes.Length); this.fileStream.Flush(); //byte[] lengthBytes = BitConverter.GetBytes(this.Length); //this.fileStream.Write(lengthBytes, 0, lengthBytes.Length); this.isAppend = true; } public void Dispose() { this.fileStream?.Dispose(); } /// <summary> /// 将分块续传的文件释放出来并删除分块续传文件 /// </summary> /// <returns></returns> public async Task<bool> Release() { string filePath = this.downloadPartPath.Replace(DownloadFile.Ext, string.Empty); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } using (FileStream write = System.IO.File.Create(filePath)) { this.fileStream.Position = this.Position; await this.fileStream.CopyToAsync(write); } //校验服务器上的md5 如果服务器上下载数据不包含md5则视为md5校验通过 if (this.MD5 == null || this.MD5 == MD5Tools.GetFileMd5(filePath)) { this.fileStream?.Dispose(); System.IO.File.Delete(this.downloadPartPath); return true; } else { System.IO.File.Delete(filePath); return false; } } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace AutoUpgrade.Net.Client.Commands { internal class CommandVersion : Command { public override string Name => "主程序的版本"; public override string Code => "-vs"; public override string Descript => "使用这个版本号去请求服务器来判断是否需要升级"; internal override bool Nullable => false; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace AutoUpgrade.Net.Release { /// <summary> /// 频率限制器 Debounce(防抖) Throttle(节流) /// </summary> public class RateLimitor { #region Private Properties private Timer throttleTimer; private Timer debounceTimer; #endregion #region Debounce /// <summary> /// 防抖 /// </summary> /// <param name="obj">Your object</param> /// <param name="interval">Milisecond interval</param> /// <param name="debounceAction">Called when last item call this method and after interval was finished</param> public void Debounce(int interval, Action debounceAction) { debounceTimer?.Dispose(); debounceTimer = new Timer((state) => { debounceTimer?.Dispose(); if (debounceTimer != null) { debounceAction?.Invoke(); } debounceTimer = null; }, null, interval, 0); } #endregion #region Throttle /// <summary> /// 节流 /// </summary> /// <param name="obj">Your object</param> /// <param name="interval">Milisecond interval</param> /// <param name="throttleAction">Invoked last object when timer ticked invoked</param> public void Throttle(int interval, Action throttleAction) { if (throttleTimer == null) { throttleTimer = new Timer((state) => { throttleTimer?.Dispose(); throttleTimer = null; throttleAction?.Invoke(); }, null, interval, 0); } } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutoUpgrade.Net.Client.Json { public class UpgradeInfo { public string Version { get; set; } public FileItem[] Files { get; set; } public string UpgradeLog { get; set; } } } <file_sep>using System; using System.Linq; namespace AutoUpgrade.Net.Json { /// <summary> /// 发布版本 /// </summary> public class JsonReleaseVersion { /// <summary> 发布类型 /// </summary> public enum ReleaseType { /// <summary> /// 选择更新 /// </summary> Choice = 0, /// <summary> /// 强制更新 /// </summary> Force = 1 } /// <summary> /// 版本号 /// </summary> public string Version { get; set; } /// <summary> /// 发布的文件详细信息 /// </summary> public JsonFileDetail[] Files { get; set; } /// <summary> /// 需要删除的文件 /// </summary> public string[] Deletes { get; set; } /// <summary> /// 更新内容 /// </summary> public string UpdateContent { get; set; } /// <summary> /// 发布类型 /// </summary> public ReleaseType Type { get; set; } public static JsonReleaseVersion operator +(JsonReleaseVersion jsonReleaseVersion1, JsonReleaseVersion jsonReleaseVersion2) { JsonReleaseVersion highVersion = new Version(jsonReleaseVersion1.Version) > new Version(jsonReleaseVersion2.Version) ? jsonReleaseVersion1 : jsonReleaseVersion2; JsonReleaseVersion lowVersion = new Version(jsonReleaseVersion1.Version) > new Version(jsonReleaseVersion2.Version) ? jsonReleaseVersion2 : jsonReleaseVersion1; //ReleaseType releaseType = (highVersion.Type == ReleaseType.Force || lowVersion.Type == ReleaseType.Force) ? ReleaseType.Force : ReleaseType.Choice; return new JsonReleaseVersion() { Version = highVersion.Version, UpdateContent = highVersion.UpdateContent, Type = highVersion.Type, Deletes = lowVersion.Deletes .Where(d => highVersion.Files.FirstOrDefault(f => f.Name == d) == null) .Concat(highVersion.Deletes) .ToArray(), Files = lowVersion.Files .Where(f => !highVersion.Deletes.Contains(f.Name)) .Select(f => highVersion.Files.FirstOrDefault(fd => fd.Name == f.Name) ?? f) .Concat(highVersion.Files.Where(f => lowVersion.Files.FirstOrDefault(fd => fd.Name == f.Name) == null)) .ToArray() }; } } } <file_sep>namespace AutoUpgrade.Net.Args { public class SpeedChangedArgs { /// <summary> /// /// </summary> /// <param name="speed">下载速度(MB/S)</param> public SpeedChangedArgs(float speed) { Speed = speed; } /// <summary> /// 下载速度(MB/S) /// </summary> public float Speed { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.IO; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using AutoUpgrade.Net.Core; using AutoUpgrade.Net.Json; using IdentityModel; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using Microsoft.Net.Http.Headers; namespace AutoUpgrade.Net.Server.Controllers { [Route("api/[controller]")] [ApiController] public class UpgradeServerController : Controller { private DownloadServer serverDownload = new DownloadServer("Upgrade"); private UpgradeServer upgradeServer = new UpgradeServer("Upgrade"); /// <summary> /// 用文件名获取下载链接 /// </summary> /// <remarks> /// 例子: /// Get api/UpgradeService/download?fileName=xxxxxxxxxxxx /// </remarks> /// <param name="fileName">文件名</param> /// <returns>文件下载请求结果</returns> [Authorize] [HttpGet("download")] public async Task<IActionResult> Download(string fileName) { Stream stream = await serverDownload.GetDownloadStreamAsync(this.HttpContext, fileName); if (stream == null) { return NotFound(); } return File(stream, this.HttpContext.Response.Headers[HeaderNames.ContentType].ToString(), true); } [Authorize] [HttpGet("checkVersion")] public async Task<IActionResult> CheckVersion(string version) { return await Task.Run(() => { return Json(upgradeServer.CheckVersion(version)); }); } [HttpGet("upgradeable")] public async Task<IActionResult> Upgradeable(string version) { return await Task.Run(() => { return Json(upgradeServer.Upgradeable(version)); }); } } } <file_sep>namespace AutoUpgrade.Net.Json { public class JsonFileDetail { /// <summary> /// 文件名 /// </summary> public string Name { get; set; } /// <summary> /// 所在版本 /// </summary> public string Version { get; set; } /// <summary> /// 文件MD5 /// </summary> public string MD5 { get; set; } /// <summary> /// 文件MD5 /// </summary> public long Length { get; set; } public JsonFileDetail() { } public override string ToString() { return this.Name + "|" + this.MD5; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AutoUpgrade.Net.Client.Json; namespace AutoUpgrade.Net.Client.ServerAPIs.APIMock { internal class UpgradeAPIMock : IUpgradeAPI { public bool DownloadFile(FileItem fileItem, string token) { return true; } public UpgradeInfo GetUpgradeInfo(string version, string token) { return new UpgradeInfo() { UpgradeLog = "this is upgrage log", Version = "1.1.1.1", Files = new FileItem[] { new FileItem() { Length =1, MD5 ="md51", Name ="f1", Url ="url1" }, new FileItem() { Length =2, MD5 ="md52", Name ="f2", Url ="url2" } } }; } public bool IsNeedUpgrade(string version) { return true; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace AutoUpgrade.Net.Json { public class JsonRespondResult { public bool Result { get; set; } = true; public string Message { get; set; } public string[] Details { get; set; } } } <file_sep>using AutoUpgrade.Net.Tools; using System.IO; namespace AutoUpgrade.Net.Core { /// <summary> 分块文件信息 /// </summary> public class PartialFileInfo { private string md5; private FileInfo fileInfo; public long From { get; set; } public long To { get; set; } public bool IsPartial { get; set; } public long Length { get; set; } public long FileLength => this.fileInfo.Length; public string Name => this.fileInfo.Name; public string FilePath => this.fileInfo.FullName; public string MD5 => this.md5 ?? (this.md5 = MD5Tools.GetFileMd5(this.FilePath)); public PartialFileInfo(string filePath) { this.fileInfo = new FileInfo(filePath); this.From = 0; this.To = this.FileLength - 1; this.IsPartial = false; this.Length = this.FileLength; } } } <file_sep>using AutoUpgrade.Net.Json; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace AutoUpgrade.Net.Release { public partial class FmRelease : Form { private Config config = Config.LoadFromXML(); private UpgradeClient upgradeClient = null; private JsonReleaseVersion[] versions = null; /// <summary> /// 当前文件扫描 /// </summary> private FileScan[] fileScans = null; private bool callRefreshFileScans = true; /// <summary> /// 上一次版本号 /// </summary> private Version lastVersion; /// <summary> /// 当前版本号 /// </summary> private Version currentVersion; private JsonReleaseVersion ServerVersion => this.GetJsonReleaseVersion(); private FileScan[] FileScans { get { if (this.fileScans == null || this.callRefreshFileScans) { //是否被过滤 Func<string, bool> funcFilter = (f) => ((config.ExcludeExt ?? new string[0]).Contains(Path.GetExtension(f)) || (config.ExcludeFile ?? new string[0]).Contains(Path.GetFileName(f)) || (config.ExcludeDir ?? new string[0]).Contains(this.GetBaseDirectoryName(f, null))) && !(config.IncludeFile ?? new string[0]).Contains(Path.GetFileName(f)) || (config.UpgradeExe ?? string.Empty) == Path.GetFileName(f); //查找到的所有文件 IEnumerable<string> files = Directory.GetFiles(config.ProgramDirectory, "*", SearchOption.AllDirectories) .Select(f => f.Replace(config.ProgramDirectory + "\\", "")); //过滤后的文件 IEnumerable<string> filters = files.Where(f => !funcFilter(f)); //对比之前的文件信息计算出当前需要被删除的文件 var deletes = (this.ServerVersion?.Files?.Where(f => files.FirstOrDefault(fn => fn == f.Name) == null).ToArray() ?? new JsonFileDetail[0]).Select(d => new FileScan(d) { Result = FileScan.CompareResult.Remove }); this.fileScans = files .AsParallel() .AsOrdered() .Select(p => { bool isFilter = funcFilter.Invoke(p); FileScan fileScan = new FileScan(config.ProgramDirectory, p, !isFilter); if (isFilter) { fileScan.Result = FileScan.CompareResult.Filter; } else { JsonFileDetail equal = this.ServerVersion?.Files?.FirstOrDefault(l => l.Name == fileScan.Name); fileScan.Result = equal == null ? FileScan.CompareResult.Add : (equal.MD5 == fileScan.MD5 ? FileScan.CompareResult.Normal : FileScan.CompareResult.Update); } return fileScan; }).ToArray().Concat(deletes).ToArray(); this.callRefreshFileScans = false; } return this.fileScans; } } public FmRelease() { InitializeComponent(); RateLimitor rateLimitor = new RateLimitor(); this.upgradeClient = new UpgradeClient(config.ServerUrl); this.upgradeClient.UpgradeProgressChanged += (s, e) => { this.Invoke(new MethodInvoker(() => { if (e.Total <= 0) { this.tspbProgress.Value = 0; } else { this.tspbProgress.Value = (int)((decimal)e.Loaded / e.Total * 100); } this.tspbProgress.Maximum = 100; this.tslbProgress.Text = e.ToString(); })); }; this.upgradeClient.UpgradeCompleted += (s, e) => { this.Invoke(new MethodInvoker(() => { this.tspbProgress.Value = 0; this.tspbProgress.Maximum = 100; this.tslbProgress.Text = "就绪"; })); }; this.lvFiles.MouseDoubleClick += (s, e) => { if (this.lvFiles.SelectedItems.Count == 0) { return; } Clipboard.SetText(this.lvFiles.SelectedItems[0].Text); MessageBox.Show("“" + this.lvFiles.SelectedItems[0].Text + "” 已经复制到剪切板"); }; this.cbxDifferenceOnly.CheckedChanged += async (s, e) => { this.cbxDifferenceOnly.Enabled = false; await this.RefreshfileScans(); this.cbxDifferenceOnly.Enabled = true; }; this.cbxFilterContain.CheckedChanged += async (s, e) => { this.cbxDifferenceOnly.Enabled = false; await this.RefreshfileScans(); this.cbxDifferenceOnly.Enabled = true; }; this.btnOpenDirectory.Click += (s, e) => { Process.Start("explorer", this.config.ProgramDirectory); }; this.btnRefresh.Click += async (s, e) => { this.btnRefresh.Enabled = false; await this.RefreshfileScans(); this.btnRefresh.Enabled = true; }; this.btnProgramDirectory.Click += async (s, e) => { this.btnProgramDirectory.Enabled = false; FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog(); folderBrowserDialog.SelectedPath = config.ProgramDirectory; folderBrowserDialog.Description = "请选择发布程序所在的目录"; if (folderBrowserDialog.ShowDialog() == DialogResult.OK) { config.ProgramDirectory = folderBrowserDialog.SelectedPath; config.SaveAsXML(); await this.SelectProgramDirectory(); } this.btnProgramDirectory.Enabled = true; }; this.tbxProgramDirectory.Config = this.config; this.tbxProgramDirectory.PropertyName = nameof(this.config.ProgramDirectory); this.tbxExcludeExt.Config = this.config; this.tbxExcludeExt.PropertyName = nameof(this.config.ExcludeExt); this.tbxExcludeFile.Config = this.config; this.tbxExcludeFile.PropertyName = nameof(this.config.ExcludeFile); this.tbxExcludeDir.Config = this.config; this.tbxExcludeDir.PropertyName = nameof(this.config.ExcludeDir); this.tbxIncludeFile.Config = this.config; this.tbxIncludeFile.PropertyName = nameof(this.config.IncludeFile); this.tbxMainExe.Config = this.config; this.tbxMainExe.PropertyName = nameof(this.config.MainExe); this.tbxUpgradeExe.Config = this.config; this.tbxUpgradeExe.PropertyName = nameof(this.config.UpgradeExe); this.tbxUpgradeExe.TextChanged += (s, e) => { rateLimitor.Debounce(800, () => { this.Invoke(new MethodInvoker(async () => { await this.RefreshVersion(); })); }); }; this.cbxDifferenceOnly.Config = this.config; this.cbxDifferenceOnly.PropertyName = nameof(this.config.DifferenceOnly); this.cbxFilterContain.Config = this.config; this.cbxFilterContain.PropertyName = nameof(this.config.FilterContain); this.Enabled = false; } private async Task RefreshVersion() { if (this.config.ProgramDirectory == null) { return; } string serverVersion = await this.upgradeClient.GetVersion("Upgrade.exe"); if (serverVersion != null) { this.tbxUpgradeServerVersion.Text = serverVersion; } else { this.tbxUpgradeServerVersion.Text = string.Empty; } string upgradePath = Path.Combine(this.config.ProgramDirectory, this.tbxUpgradeExe.Text); if (File.Exists(upgradePath)) { this.tbxUpgradeExe.BackColor = Color.GreenYellow; this.tbxUpgradeLocalVersion.Text = FileVersionInfo.GetVersionInfo(upgradePath).ProductVersion; this.btnUpdateUpgradeProgram.Enabled = this.tbxUpgradeServerVersion.Text != this.tbxUpgradeLocalVersion.Text; } else { this.tbxUpgradeExe.BackColor = Color.OrangeRed; this.tbxUpgradeLocalVersion.Text = string.Empty; this.btnUpdateUpgradeProgram.Enabled = false; } } protected async override void OnLoad(EventArgs e) { base.OnLoad(e); await RefreshVersions(); await this.SelectProgramDirectory(); await this.RefreshVersion(); this.Enabled = true; } /// <summary> 选择程序目录 /// </summary> private async Task SelectProgramDirectory() { if (!Directory.Exists(config.ProgramDirectory)) { return; } await this.RefreshfileScans(); } /// <summary> /// 刷新版本列表 /// </summary> /// <returns></returns> private async Task RefreshVersions() { this.versions = await this.upgradeClient.GetVersionList(); if (this.versions != null) { this.lsvVersion.Items.Clear(); foreach (JsonReleaseVersion jsonReleaseVersion in this.versions.Reverse()) { this.lsvVersion.Items.Add(jsonReleaseVersion.Version); } } } /// <summary> /// 刷新文件扫描列表 /// </summary> /// <returns></returns> private async Task RefreshfileScans() { await Task<FileScan[]>.Run(() => { this.callRefreshFileScans = true; return this.FileScans .Where(f => this.cbxFilterContain.Checked ? true : f.Result != FileScan.CompareResult.Filter) .Where(f => this.cbxDifferenceOnly.Checked ? f.Result != FileScan.CompareResult.Normal : f.Result == FileScan.CompareResult.Normal).ToArray(); }).ContinueWith((fs) => { this.Invoke(new MethodInvoker(() => { var fss = fs.Result; this.lvFiles.Items.Clear(); this.lvFiles.Items.AddRange(fss.Select(r => { Color color = Color.Transparent; switch (r.Result) { case FileScan.CompareResult.Filter: color = Color.Gray; break; case FileScan.CompareResult.Add: color = Color.LightGreen; break; case FileScan.CompareResult.Normal: color = Color.Transparent; break; case FileScan.CompareResult.Remove: color = Color.PaleVioletRed; break; case FileScan.CompareResult.Update: color = Color.Yellow; break; } return new ListViewItem(r.Name) { BackColor = color }; }).ToArray()); if (this.config?.MainExe != null) { this.lastVersion = new Version(this.ServerVersion?.Version ?? "0.0.0.0"); this.currentVersion = new Version(fss?.FirstOrDefault(f => f.Name == this.config.MainExe)?.Version ?? "0.0.0.0"); this.lvVersion.Text = "版本号:" + lastVersion.ToString() + " -----> " + currentVersion.ToString(); } else { this.lvVersion.Text = string.Empty; } })); }); } /// <summary> /// 获取版本信息 /// </summary> /// <returns></returns> private JsonReleaseVersion GetJsonReleaseVersion() { return (this.versions == null || this.versions.Length == 0) ? null : this.versions[this.versions.Length - 1]; } /// <summary> /// 获取程序目录下的文件的基目录 /// </summary> /// <param name="basePath"></param> /// <param name="path"></param> /// <returns></returns> private string GetBaseDirectoryName(string basePath, string path = null) { string baseDirectoryName = Path.GetDirectoryName(path ?? basePath); if (baseDirectoryName == string.Empty) { if (path == null) { return string.Empty; } else { return path; } } return GetBaseDirectoryName(basePath, baseDirectoryName); } /// <summary> /// 获取升级类型 /// </summary> private JsonReleaseVersion.ReleaseType ReleaseType { get { if (this.rdbForceUpdate.Checked) { return JsonReleaseVersion.ReleaseType.Force; } if (this.rdbSelectUpdate.Checked) { return JsonReleaseVersion.ReleaseType.Choice; } return JsonReleaseVersion.ReleaseType.Force; } } private async void BtnRelease_Click(object sender, EventArgs e) { this.btnRelease.Enabled = false; if (this.Check()) { JsonReleaseVersion jsonReleaseVersion = new JsonReleaseVersion() { Version = this.currentVersion.ToString(), Files = this.FileScans .Where(f => f.Result == FileScan.CompareResult.Add || f.Result == FileScan.CompareResult.Update) .Select(f => new JsonFileDetail() { Name = f.Name, MD5 = f.MD5, Length = f.Length, Version = this.currentVersion.ToString() }) .ToArray(), Deletes = this.FileScans .Where(f => f.Result == FileScan.CompareResult.Remove) .Select(f => f.Name) .ToArray(), Type = this.ReleaseType, UpdateContent = this.tbxUpdateContent.Text }; if (await this.upgradeClient.Upgrade(config.ProgramDirectory, jsonReleaseVersion)) { await this.RefreshVersions(); await this.RefreshfileScans(); MessageBox.Show("版本:" + jsonReleaseVersion.Version + "发布成功!"); } else { MessageBox.Show("发布失败!"); } } this.btnRelease.Enabled = true; } private bool Check() { FileScan fileScan = this.FileScans .Where(f => f.Result == FileScan.CompareResult.Add || f.Result == FileScan.CompareResult.Update) .FirstOrDefault(f => f.Name == config.MainExe); if (this.lastVersion > this.currentVersion) { MessageBox.Show("发布的版本号低于服务器版本!请重新编译主程序版本号!"); return false; } if (this.lastVersion == this.currentVersion) { MessageBox.Show("发布的版本号与上次相同!请重新编译主程序版本号!"); return false; } return true; } private async void BtnUpdateUpgradeProgram_Click(object sender, EventArgs e) { string upgradePath = Path.Combine(this.config.ProgramDirectory, this.tbxUpgradeExe.Text); if (File.Exists(upgradePath)) { if (await this.upgradeClient.UpdateUpgradePrograme(upgradePath)) { MessageBox.Show("升级程序:" + FileVersionInfo.GetVersionInfo(upgradePath).ProductVersion + " 发布成功!"); await this.RefreshVersion(); return; } } MessageBox.Show("升级程序发布失败"); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace AutoUpgrade.Net.Tools { public static class FileTools { /// <summary> /// 删除文件 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static async Task<bool> DeleteFile(string filePath) { try { if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(5000); return await Task<bool>.Run(() => { while (System.IO.File.Exists(filePath) && !cancellationTokenSource.IsCancellationRequested) { Task.Delay(100); } return !cancellationTokenSource.IsCancellationRequested; }, cancellationTokenSource.Token); } else { return true; } } catch { return false; } } /// <summary> /// 移动文件 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static async Task<bool> MoveFile(string fromFilePath, string toFilePath) { try { if (await DeleteFile(toFilePath)) { string dir = System.IO.Path.GetDirectoryName(toFilePath); if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } System.IO.File.Move(fromFilePath, toFilePath); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(5000); return await Task<bool>.Run(() => { while (!System.IO.File.Exists(toFilePath) && !cancellationTokenSource.IsCancellationRequested) { Task.Delay(100); } return !cancellationTokenSource.IsCancellationRequested; }, cancellationTokenSource.Token); } return false; } catch { return false; } } /// <summary> /// 删除文件夹 /// </summary> /// <param name="dir"></param> /// <returns></returns> public static async Task<bool> DeleteDirectory(string dir) { try { System.IO.Directory.Delete(dir, true); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(5000); return await Task<bool>.Run(() => { while (System.IO.Directory.Exists(dir) && !cancellationTokenSource.IsCancellationRequested) { Task.Delay(100); } return !cancellationTokenSource.IsCancellationRequested; }, cancellationTokenSource.Token); } catch { return false; } } } } <file_sep>using AutoUpgrade.Net.Client.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutoUpgrade.Net.Client.ServerAPIs { public interface IUpgradeAPI { bool IsNeedUpgrade(string version); UpgradeInfo GetUpgradeInfo(string version, string token); bool DownloadFile(FileItem fileItem, string token); } } <file_sep>namespace AutoUpgrade.Net.Args { public class CompletedArgs { /// <summary> /// /// </summary> /// <param name="success">是否成功</param> /// <param name="result">结果内容</param> public CompletedArgs(bool success, string result = null) { Success = success; Result = result; } /// <summary> /// 是否成功 /// </summary> public bool Success { get; set; } /// <summary> /// 结果内容 /// </summary> public string Result { get; set; } } } <file_sep>using AutoUpgrade.Net.Args; using AutoUpgrade.Net.Delegates; using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace AutoUpgrade.Net.Core { /// <summary> 客户端下载 /// </summary> public class DownloadClient { #region 事件 /// <summary> /// 下载进度变化事件 /// </summary> public event ProgressChangedHandler DownloadProgressChanged; protected virtual void OnDownloadProgressChanged(ProgressChangedArgs progressChangedArgs) { this.DownloadProgressChanged?.Invoke(this, progressChangedArgs); } /// <summary> /// 下载速度变化事件 /// </summary> public event SpeedChangedHandler DownloadSpeedChanged; protected virtual void OnDownloadSpeedChanged(SpeedChangedArgs speedChangedArgs) { this.DownloadSpeedChanged?.Invoke(this, speedChangedArgs); } /// <summary> /// 下载完成事件 /// </summary> /// <param name="progress"></param> /// <param name="speed"></param> public event CompletedHandler DownloadCompleted; protected virtual void OnDownloadCompleted(CompletedArgs completedArgs) { this.DownloadCompleted?.Invoke(this, completedArgs); } /// <summary> /// 下载错误事件 /// </summary> /// <param name="progress"></param> /// <param name="speed"></param> public event ErrorHandler DownloadError; protected virtual void OnDownloadError(ErrorArgs errorArgs) { this.DownloadError?.Invoke(this, errorArgs); } #endregion #region 变量 /// <summary> 下载的url /// </summary> private string downloadUrl = string.Empty; #endregion public DownloadClient(string downloadUrl) { this.downloadUrl = downloadUrl; } /// <summary> /// 断点续传下载 /// </summary> /// <param name="uri"></param> /// <returns></returns> public async Task<bool> ResumeDownload(string downloadPartPath) { using (DownloadFile downloadFile = DownloadFile.FromPartPath(downloadPartPath)) { if (downloadFile == null) { return false; } return await DoDownloadFile(downloadFile); } } /// <summary> /// 根据url下载 /// </summary> /// <param name="uri"></param> /// <returns></returns> public async Task<bool> UrlDownload(string urlFileName, string savefilePath) { string downloadPartPath = savefilePath + DownloadFile.Ext; string downloadPartDir = Path.GetDirectoryName(downloadPartPath); if (downloadPartDir != string.Empty) { if (!Directory.Exists(downloadPartDir)) { Directory.CreateDirectory(downloadPartDir); } } string url = this.downloadUrl + "?fileName=" + urlFileName; using (DownloadFile downloadFile = DownloadFile.FromUrl(downloadPartPath, url)) { return await DoDownloadFile(downloadFile); } } /// <summary> /// 执行DownloadFile /// </summary> /// <param name="downloadFile"></param> /// <returns></returns> public async Task<bool> DoDownloadFile(DownloadFile downloadFile) { using (HttpClient httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) }) { try { httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(downloadFile.RangeBegin, null); HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(downloadFile.URL, HttpCompletionOption.ResponseHeadersRead); long? contentLength = httpResponseMessage.Content.Headers.ContentLength; if (httpResponseMessage.Content.Headers.ContentRange != null) //如果为空,则说明服务器不支持断点续传 { contentLength = httpResponseMessage.Content.Headers.ContentRange.Length;//服务器上的文件大小 } long? length = (httpResponseMessage.Content.Headers.ContentRange == null ? //如果为空,则说明服务器不支持断点续传 httpResponseMessage.Content.Headers.ContentLength : httpResponseMessage.Content.Headers.ContentRange.Length) ?? -1;//服务器上的文件大小 string md5 = downloadFile.MD5 ?? (httpResponseMessage.Content.Headers.ContentMD5 == null ? null : Convert.ToBase64String(httpResponseMessage.Content.Headers.ContentMD5)); if (downloadFile.DoLocal(length, md5)) { using (Stream stream = await httpResponseMessage.Content.ReadAsStreamAsync()) { stream.ReadTimeout = 10 * 1000; bool success = await Download(stream, downloadFile) & await downloadFile.Release(); this.OnDownloadCompleted(new CompletedArgs(success)); return success; } } else { this.OnDownloadError(new ErrorArgs("服务器的上的版本已经变化")); return false; } } catch (Exception ex) { this.OnDownloadError(new ErrorArgs(ex.Message)); return false; } } } private async Task<bool> Download(Stream downloadStream, DownloadFile downloadFile) { int bufferSize = 81920; //缓存 byte[] buffer = new byte[bufferSize]; long position = downloadFile.RangeBegin; int readLength = 0; try { decimal downloadSpeed = 0;//下载速度 var beginSecond = DateTime.Now.Second;//当前时间秒 while ((readLength = await downloadStream.ReadAsync(buffer, 0, buffer.Length)) != 0) { position += readLength; downloadSpeed += readLength; await downloadFile.Write(buffer, 0, readLength); var endSecond = DateTime.Now.Second; if (endSecond != beginSecond)//计算速度 { downloadSpeed = downloadSpeed / (endSecond - beginSecond); this.OnDownloadSpeedChanged(new SpeedChangedArgs((float)(downloadSpeed / 1024))); beginSecond = DateTime.Now.Second; downloadSpeed = 0;//清空 } this.OnDownloadProgressChanged(new ProgressChangedArgs(readLength, downloadFile.RangeBegin, downloadFile.Length)); } return true; } catch (Exception ex) { this.OnDownloadError(new ErrorArgs(ex.Message)); } return false; } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace AutoUpgrade.Net.Release { public class Config : IPersistenceXML<Config> { public string ServerUrl { get; set; } /// <summary> /// 程序目录 /// </summary> public string ProgramDirectory { get; set; } /// <summary> 排除的后缀 /// </summary> public string[] ExcludeExt { get; set; } /// <summary> 排除的文件 /// </summary> public string[] ExcludeFile { get; set; } /// <summary> 排除的目录 /// </summary> public string[] ExcludeDir { get; set; } /// <summary> 包含的文件 /// </summary> public string[] IncludeFile { get; set; } /// <summary> 主程序 /// </summary> public string MainExe { get; set; } /// <summary> 主程序 /// </summary> public string UpgradeExe { get; set; } /// <summary> 只显示不同 /// </summary> public bool DifferenceOnly { get; set; } /// <summary> 显示过滤 /// </summary> public bool FilterContain { get; set; } } } <file_sep>using AutoUpgrade.Net.Client.Commands; using AutoUpgrade.Net.Client.ServerAPIs; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace AutoUpgrade.Net.Client.Winform { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main(string[] args) { var asd = APIProvider.AuthAPI.GetToken("<KEY>", "<KEY>").Result; MainStart.Start(args, () => { if (CommandProvider.UpgraderVisible) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } else { Application.Run(); } }); Console.WriteLine("-unupgradable"); } } } <file_sep>using AutoUpgrade.Net.Args; namespace AutoUpgrade.Net.Delegates { /// <summary> /// 进度变化事件委托 /// </summary> /// <param name="sender"></param> /// <param name="progressChangedArgs"></param> public delegate void ProgressChangedHandler(object sender, ProgressChangedArgs progressChangedArgs); /// <summary> /// 速度变化事件委托 /// </summary> /// <param name="sender"></param> /// <param name="speedChangedArgs"></param> public delegate void SpeedChangedHandler(object sender, SpeedChangedArgs speedChangedArgs); /// <summary> /// 完成事件委托 /// </summary> /// <param name="sender"></param> /// <param name="completedArgs"></param> public delegate void CompletedHandler(object sender, CompletedArgs completedArgs); /// <summary> /// 错误事件委托 /// </summary> /// <param name="sender"></param> /// <param name="errorArgs"></param> public delegate void ErrorHandler(object sender, ErrorArgs errorArgs); /// <summary> /// pipe消息事件委托 /// </summary> /// <param name="msg"></param> public delegate void PipeMessageHandler(byte[] data); } <file_sep>using AutoUpgrade.Net.Args; using AutoUpgrade.Net.Delegates; using AutoUpgrade.Net.Json; using Newtonsoft.Json; using System; using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace AutoUpgrade.Net.Core { /// <summary> 客户端上传 /// </summary> public class UploadClient { #region 事件 /// <summary> /// 上传进度变化事件 /// </summary> public event ProgressChangedHandler UploadProgressChanged; protected virtual void OnUploadProgressChanged(ProgressChangedArgs progressChangedArgs) { this.UploadProgressChanged?.Invoke(this, progressChangedArgs); } /// <summary> /// 上传速度变化事件 /// </summary> public event SpeedChangedHandler UploadSpeedChanged; protected virtual void OnUploadSpeedChanged(SpeedChangedArgs speedChangedArgs) { this.UploadSpeedChanged?.Invoke(this, speedChangedArgs); } /// <summary> /// 上传完成事件 /// </summary> /// <param name="progress"></param> /// <param name="speed"></param> public event CompletedHandler UploadCompleted; protected virtual void OnUploadCompleted(CompletedArgs completedArgs) { this.UploadCompleted?.Invoke(this, completedArgs); } /// <summary> /// 上传错误事件 /// </summary> /// <param name="progress"></param> /// <param name="speed"></param> public event ErrorHandler UploadError; protected virtual void OnUploadError(ErrorArgs errorArgs) { this.UploadError?.Invoke(this, errorArgs); } #endregion #region const /// <summary> /// 上传缓存大小 /// </summary> private const int UploadBufferSize = 1024 * 4; /// <summary> /// 分块大小 /// </summary> private const int ChunkSize = 1024 * 512; //分块大小512k #endregion #region 变量 /// <summary> 上传的url /// </summary> private string uploadUrl = string.Empty; /// <summary> 分块合并的url(可以为空,如果为空不分块上传) /// </summary> private string mergeURL = string.Empty; #endregion #region 属性 #endregion /// <summary> /// 文件上传 /// </summary> /// <param name="uploadUrl">上传的url</param> /// <param name="mergeURL">分块合并的url(可以为空,如果为空不分块上传)</param> public UploadClient(string uploadUrl, string mergeURL = null) { this.uploadUrl = uploadUrl; this.mergeURL = mergeURL; } public void UploadAsync(string filePath, string dir = null) { Task.Run(async () => { FileInfo fileInfo = new FileInfo(filePath); long length = fileInfo.Length; if (length > ChunkSize) { this.OnUploadCompleted(new CompletedArgs(await UploadLarge(filePath, dir))); } else { this.OnUploadCompleted(new CompletedArgs(await UploadOnce(filePath, dir))); } }); } public async Task<bool> UploadTaskAsync(string filePath, string dir = null) { FileInfo fileInfo = new FileInfo(filePath); long length = fileInfo.Length; if (length > ChunkSize) { return await UploadLarge(filePath, dir); } else { return await UploadOnce(filePath, dir); } } /// <summary> /// 一次性上传 /// </summary> /// <param name="uri"></param> /// <param name="filePath"></param> /// <returns></returns> private async Task<bool> UploadOnce(string filePath, string dir) { using (FileStream fileStream = System.IO.File.OpenRead(filePath)) using (HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }) { Timeout = TimeSpan.FromSeconds(10) })//若想手动设置Cookie则必须设置UseCookies = false { MultipartFormDataContent multipartFormDataContent = new MultipartFormDataContent(); multipartFormDataContent.Add(new ProgressableStreamContent( fileStream, UploadBufferSize, (r, u) => this.OnUploadProgressChanged(new ProgressChangedArgs(r, u, fileStream.Length)), (s) => this.OnUploadSpeedChanged(new SpeedChangedArgs(s))), "file", Path.GetFileName(filePath)); try { var result = await client.PostAsync(new Uri(this.uploadUrl + "?uploadDir=" + dir), multipartFormDataContent); if (result.IsSuccessStatusCode) { JsonRespondResult respondResult = JsonConvert.DeserializeObject<JsonRespondResult>(await result.Content.ReadAsStringAsync()); if (!respondResult.Result) { this.OnUploadError(new ErrorArgs(respondResult.Message)); } return respondResult.Result; } } catch (Exception ex) { this.OnUploadError(new ErrorArgs(ex.Message)); } } return false; } /// <summary> /// 上传大文件 /// </summary> /// <param name="uri"></param> /// <param name="filePath"></param> /// <returns></returns> private async Task<bool> UploadLarge(string filePath, string dir) { try { bool success = true; using (FileStream fileStream = System.IO.File.OpenRead(filePath)) { long uploaded = 0; string mergeDir = "Merge"; string chunkPath = Path.Combine(mergeDir, "chunk"); if (!Directory.Exists(mergeDir)) { Directory.CreateDirectory(mergeDir); } for (long i = 0; i < fileStream.Length; i += ChunkSize) { fileStream.Position = i; using (Stream writeStream = System.IO.File.Create(chunkPath)) { byte[] buffer = new byte[ChunkSize]; int readLength = fileStream.Read(buffer, 0, buffer.Length); writeStream.Write(buffer, 0, readLength); } using (Stream readStream = System.IO.File.OpenRead(chunkPath)) { long readLength = readStream.Length; if (!await UploadChunk(readStream, filePath, (i / ChunkSize).ToString(), uploaded, fileStream.Length, dir)) { success = false; break; } uploaded += readLength; } } try { System.IO.Directory.Delete(mergeDir, true); } catch (Exception ex) { this.OnUploadError(new ErrorArgs(ex.Message)); } } if (success && await this.Merge(filePath, dir)) { return true; } else { return false; } } catch (Exception ex) { this.OnUploadError(new ErrorArgs(ex.Message)); return false; } } /// <summary> /// 上传分块 /// </summary> /// <param name="uri"></param> /// <param name="stream"></param> /// <param name="filePath"></param> /// <param name="chunkName"></param> /// <param name="tryCount"></param> /// <returns></returns> private async Task<bool> UploadChunk(Stream stream, string filePath, string chunkName, long uploaded, long totalLength, string dir, int tryCount = 0) { bool success = false; long loaded = 0; using (HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }) { Timeout = TimeSpan.FromSeconds(10) }) //若想手动设置Cookie则必须设置UseCookies = false { MultipartFormDataContent multipartFormDataContent = new MultipartFormDataContent(); multipartFormDataContent.Add(new ProgressableStreamContent( stream, UploadBufferSize, (r, u) => { loaded = uploaded + u; this.OnUploadProgressChanged(new ProgressChangedArgs(r, uploaded + u, totalLength)); }, (s) => this.OnUploadSpeedChanged(new SpeedChangedArgs(s))), chunkName, Path.GetFileName(filePath)); try { var result = await client.PostAsync(new Uri(this.uploadUrl + "?uploadDir=" + dir), multipartFormDataContent); if (result.IsSuccessStatusCode) { JsonRespondResult respondResult = JsonConvert.DeserializeObject<JsonRespondResult>(await result.Content.ReadAsStringAsync()); success = respondResult.Result; if (!respondResult.Result) { this.OnUploadError(new ErrorArgs(respondResult.Message)); } } } catch (Exception ex) { this.OnUploadError(new ErrorArgs(ex.Message)); } } if (!success && tryCount < 3) { this.OnUploadProgressChanged(new ProgressChangedArgs((int)(uploaded - loaded), uploaded, totalLength)); success |= await UploadChunk(stream, filePath, chunkName, uploaded, totalLength, dir, tryCount + 1); } return success; } /// <summary> /// 合并上传的分块 /// </summary> /// <param name="uri"></param> /// <param name="filePath"></param> /// <returns></returns> private async Task<bool> Merge(string filePath, string dir) { using (HttpClient httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(10) }) { try { string fileName = Path.GetFileName(filePath); if (!string.IsNullOrEmpty(dir)) { fileName = Path.Combine(dir, Path.GetFileName(filePath)).Replace(Path.DirectorySeparatorChar, '/'); } var result = await httpClient.GetAsync(this.mergeURL + "?fileName=" + fileName); if (result.IsSuccessStatusCode) { JsonRespondResult respondResult = JsonConvert.DeserializeObject<JsonRespondResult>(await result.Content.ReadAsStringAsync()); if (!respondResult.Result) { this.OnUploadError(new ErrorArgs(respondResult.Message)); } return respondResult.Result; } } catch (Exception ex) { this.OnUploadError(new ErrorArgs(ex.Message)); } } return false; } private class ProgressableStreamContent : StreamContent { private Stream content = null; private int bufferSize = 4096; private Action<int, long> uploaded = null; private Action<float> speed = null; public ProgressableStreamContent(Stream content, int bufferSize, Action<int, long> uploaded, Action<float> speed) : base(content, bufferSize) { this.content = content; this.bufferSize = bufferSize; this.uploaded = uploaded; this.speed = speed; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { return Task.Run(() => { var buffer = new Byte[this.bufferSize]; long upload = 0; int readLength = 0; decimal downloadSpeed = 0;//下载速度 var beginSecond = DateTime.Now.Second;//当前时间秒 while (content.CanRead && (readLength = content.Read(buffer, 0, buffer.Length)) != 0) { upload += readLength; downloadSpeed += readLength; stream.Write(buffer, 0, readLength); var endSecond = DateTime.Now.Second; if (endSecond != beginSecond)//计算速度 { downloadSpeed = downloadSpeed / (endSecond - beginSecond); this.speed?.Invoke((float)(downloadSpeed / 1024)); beginSecond = DateTime.Now.Second; downloadSpeed = 0;//清空 } this.uploaded?.Invoke(readLength, upload); } }); } } } } <file_sep>using Microsoft.AspNetCore.Http; using Microsoft.Net.Http.Headers; using System; using System.IO; using System.Linq; using System.Threading.Tasks; namespace AutoUpgrade.Net.Core { /// <summary> 服务端下载 /// </summary> public class DownloadServer { private string downloadRoot = string.Empty; /// <summary> /// 服务端下载 /// </summary> /// <param name="downloadRoot">下载目录</param> public DownloadServer(string downloadRoot) { this.downloadRoot = downloadRoot; } private static string baseDirector = AppContext.BaseDirectory; #region const private const int BufferSize = 80 * 1024; #endregion /// <summary> 下载根目录 /// </summary> private string DownloadRoot { get { string downloadRoot = Path.Combine(baseDirector, this.downloadRoot); if (!Directory.Exists(downloadRoot)) { Directory.CreateDirectory(downloadRoot); } return downloadRoot; } } /// <summary> 通过文件名获取服务器上的文件路径 /// </summary> /// <param name="fileName"></param> /// <returns></returns> private string GetServerFilePath(string fileName) { if (string.IsNullOrEmpty(fileName)) { return null; } return Path.Combine(DownloadRoot, fileName); } /// <summary> 获取文件分块信息 /// </summary> /// <param name="request"></param> /// <param name="filePath"></param> /// <returns></returns> private PartialFileInfo GetPartialFileInfo(HttpRequest request, string filePath) { PartialFileInfo partialFileInfo = new PartialFileInfo(filePath); if (RangeHeaderValue.TryParse(request.Headers[HeaderNames.Range].ToString(), out RangeHeaderValue rangeHeaderValue)) { var range = rangeHeaderValue.Ranges.FirstOrDefault(); if (range.From.HasValue && range.From < 0 || range.To.HasValue && range.To > partialFileInfo.FileLength - 1) { return null; } var from = range.From; var to = range.To; if (from.HasValue) { if (from.Value >= partialFileInfo.FileLength) { return null; } if (!to.HasValue || to.Value >= partialFileInfo.FileLength) { to = partialFileInfo.FileLength - 1; } } else { if (to.Value == 0) { return null; } var bytes = Math.Min(to.Value, partialFileInfo.FileLength); from = partialFileInfo.FileLength - bytes; to = from + bytes - 1; } partialFileInfo.IsPartial = true; partialFileInfo.Length = to.Value - from.Value + 1; } return partialFileInfo; } /// <summary> 获取分块文件流 /// </summary> /// <param name="partialFileInfo"></param> /// <returns></returns> private Stream GetPartialFileStream(PartialFileInfo partialFileInfo) { return new PartialFileStream(partialFileInfo.FilePath, partialFileInfo.From, partialFileInfo.To); } /// <summary> /// 设置响应头信息 /// </summary> /// <param name="response"></param> /// <param name="partialFileInfo"></param> /// <param name="fileLength"></param> /// <param name="fileName"></param> private void SetResponseHeaders(HttpResponse response, PartialFileInfo partialFileInfo) { response.Headers[HeaderNames.AcceptRanges] = "bytes"; response.StatusCode = partialFileInfo.IsPartial ? StatusCodes.Status206PartialContent : StatusCodes.Status200OK; var contentDisposition = new ContentDispositionHeaderValue("attachment"); contentDisposition.SetHttpFileName(partialFileInfo.Name); response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); response.Headers[HeaderNames.ContentType] = "application/octet-stream"; //response.Headers[HeaderNames.ContentMD5] = partialFileInfo.MD5; response.Headers[HeaderNames.ContentLength] = partialFileInfo.Length.ToString(); if (partialFileInfo.IsPartial) { response.Headers[HeaderNames.ContentRange] = new ContentRangeHeaderValue(partialFileInfo.From, partialFileInfo.To, partialFileInfo.FileLength).ToString(); } } /// <summary> 异步获取下载流 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public Task<Stream> GetDownloadStreamAsync(HttpContext httpContext, string fileName) { return Task.Run<Stream>(() => { string filePath = this.GetServerFilePath(fileName); if (!File.Exists(filePath)) { return null; } PartialFileInfo partialFileInfo = this.GetPartialFileInfo(httpContext.Request, filePath); this.SetResponseHeaders(httpContext.Response, partialFileInfo); return this.GetPartialFileStream(partialFileInfo); }); } /// <summary> 获取下载流 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public Stream GetDownloadStream(HttpContext httpContext, string fileName) { string filePath = this.GetServerFilePath(fileName); if (!File.Exists(filePath)) { return null; } PartialFileInfo partialFileInfo = this.GetPartialFileInfo(httpContext.Request, filePath); this.SetResponseHeaders(httpContext.Response, partialFileInfo); return this.GetPartialFileStream(partialFileInfo); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace AutoUpgrade.Net.Client.Commands { internal class CommandMainProcessID : Command { public override string Name => "主程序的进程ID"; public override string Code => "-pid"; public override string Descript => "使用这个ID来判断主程序是否开启/关闭"; internal override bool Nullable => false; internal override bool NullableCheck(out string msg) { msg = null; var result = Nullable || (Value != null); if (result) { if (int.TryParse(Value, out int proecssID)) { return true; } else { msg = $"{Name}({Code}): proecssID format error!"; return false; } } else { msg = $"{Name}({Code}): value can not be null!"; return false; } } } } <file_sep>using AutoUpgrade.Net.Args; using AutoUpgrade.Net.Core; using AutoUpgrade.Net.Delegates; using AutoUpgrade.Net.Json; using Newtonsoft.Json; using System; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace AutoUpgrade.Net.Release { public class UpgradeClient { #region 事件 /// <summary> /// 升级进度变化事件 /// </summary> public event ProgressChangedHandler UpgradeProgressChanged; protected virtual void OnUpgradeProgressChanged(ProgressChangedArgs progressChangedArgs) { this.UpgradeProgressChanged?.Invoke(this, progressChangedArgs); } /// <summary> /// 升级速度变化事件 /// </summary> public event SpeedChangedHandler UpgradeSpeedChanged; protected virtual void OnUpgradeSpeedChanged(SpeedChangedArgs speedChangedArgs) { this.UpgradeSpeedChanged?.Invoke(this, speedChangedArgs); } /// <summary> /// 升级完成事件 /// </summary> /// <param name="progress"></param> /// <param name="speed"></param> public event CompletedHandler UpgradeCompleted; protected virtual void OnUpgradeCompleted(CompletedArgs completedArgs) { this.UpgradeCompleted?.Invoke(this, completedArgs); } /// <summary> /// 升级错误事件 /// </summary> /// <param name="progress"></param> /// <param name="speed"></param> public event ErrorHandler UpgradeError; protected virtual void OnUpgradeError(ErrorArgs errorArgs) { this.UpgradeError?.Invoke(this, errorArgs); } #endregion private string url = string.Empty; private UploadClient clientUpload = null; private long totalProgress = 0; private long currentProgress = 0; public UpgradeClient(string url) { this.url = url; this.clientUpload = new UploadClient(url + "/upload", url + "/merge"); this.clientUpload.UploadProgressChanged += (s, e) => { currentProgress += e.Read; this.OnUpgradeProgressChanged(new ProgressChangedArgs(e.Read, currentProgress, totalProgress)); }; } /// <summary> 删除版本 /// </summary> /// <param name="version">版本号</param> public async Task<bool> DeleteVersion(string version) { using (HttpClient httpClient = new HttpClient()) { try { HttpResponseMessage httpResponseMessage = await httpClient.DeleteAsync(this.url + "/deleteVersion?version=" + version); if (httpResponseMessage.IsSuccessStatusCode) { JsonRespondResult respondResult = JsonConvert.DeserializeObject<JsonRespondResult>(await httpResponseMessage.Content.ReadAsStringAsync()); if (!respondResult.Result) { this.OnUpgradeError(new ErrorArgs(respondResult.Message)); } return respondResult.Result; } } catch (Exception ex) { this.OnUpgradeError(new ErrorArgs(ex.Message)); return true; } } return false; } /// <summary> 新增版本 /// </summary> /// <param name="version">版本号</param> public async Task<bool> CreateVersion(JsonReleaseVersion jsonReleaseVersion) { using (HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }))//若想手动设置Cookie则必须设置UseCookies = false { StringContent stringContent = new StringContent(JsonConvert.SerializeObject(jsonReleaseVersion)); stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); try { var result = await client.PostAsync(new Uri(this.url + "/createVersion"), stringContent); if (result.IsSuccessStatusCode) { JsonRespondResult respondResult = JsonConvert.DeserializeObject<JsonRespondResult>(await result.Content.ReadAsStringAsync()); if (!respondResult.Result) { this.OnUpgradeError(new ErrorArgs(respondResult.Message)); } return respondResult.Result; } } catch (Exception ex) { this.OnUpgradeError(new ErrorArgs(ex.Message)); return false; } } return true; } /// <summary> 删除版本 /// </summary> /// <param name="version">版本号</param> public async Task<JsonReleaseVersion[]> GetVersionList() { using (HttpClient httpClient = new HttpClient()) { try { HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(this.url + "/getVersionList"); if (httpResponseMessage.IsSuccessStatusCode) { JsonReleaseVersion[] jsonReleaseVersions = JsonConvert.DeserializeObject<JsonReleaseVersion[]>(await httpResponseMessage.Content.ReadAsStringAsync()); return jsonReleaseVersions; } } catch (Exception ex) { this.OnUpgradeError(new ErrorArgs(ex.Message)); } } return null; } public async Task<bool> Upgrade(string root, JsonReleaseVersion jsonReleaseVersion) { this.currentProgress = 0; this.totalProgress = jsonReleaseVersion.Files.Sum(f => f.Length); bool success = true; foreach (JsonFileDetail jsonFileDetail in jsonReleaseVersion.Files) { if (!(success &= await this.clientUpload.UploadTaskAsync(Path.Combine(root, jsonFileDetail.Name), Path.Combine(jsonReleaseVersion.Version, jsonFileDetail.Name.Replace(Path.GetFileName(jsonFileDetail.Name), "")).Replace(Path.DirectorySeparatorChar, '/')))) { break; } } if (await this.CreateVersion(jsonReleaseVersion)) { this.OnUpgradeCompleted(new CompletedArgs(success)); return success; } else { this.OnUpgradeCompleted(new CompletedArgs(false)); return false; } } /// <summary> /// 更新升级程序 /// </summary> /// <param name="upgradeProgramePath"></param> /// <returns></returns> public async Task<bool> UpdateUpgradePrograme(string upgradeProgramePath) { return await this.clientUpload.UploadTaskAsync(upgradeProgramePath); } /// <summary> /// 获取文件版本号 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public async Task<string> GetVersion(string fileName) { using (HttpClient httpClient = new HttpClient()) { try { HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(this.url + "/getFileVersion?fileName=" + fileName); if (httpResponseMessage.IsSuccessStatusCode) { JsonRespondResult respondResult = JsonConvert.DeserializeObject<JsonRespondResult>(await httpResponseMessage.Content.ReadAsStringAsync()); if (respondResult.Result) { return respondResult.Message; } else { return null; } } } catch (Exception ex) { this.OnUpgradeError(new ErrorArgs(ex.Message)); } } return null; } } }
3500e248e8f5b39ae28fbf010994da6dcca4d2a1
[ "Markdown", "C#" ]
41
Markdown
ft9788501/AutoUpgrade.Net
bab4d3c3b0aa16177b783ff45f00f8f68268edd0
47122626b6197954061a664aaea1a22aabd8fd15
refs/heads/main
<file_sep><?php include("../includes/db_con.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <link rel="apple-touch-icon" sizes="57x57" href="../favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="../favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="../favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="../favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="../favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="../favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="../favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="../favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="../favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="../favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="../favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="../favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="../favicons/favicon-16x16.png"> <link rel="manifest" href="../favicons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="../favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JockTech EMS</title> <!-- <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap-material-design.min.css" integrity="<KEY>" crossorigin="anonymous" /> --> <link href="../plugins/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="../css/sb-admin-2.min.css" rel="stylesheet"> <link rel="stylesheet" href="../plugins/datatables/dataTables.bootstrap4.min.css"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <?php include("pages/header.php") ?> <!-- page begin content --> <div class="container-fluid"> <?php include("pages/nav-cards.php") ?> <div class="card shadow mb-4"> <div class="card-header py-3"> <a href="#collapseCard" class="d-block card-header py-3" data-toggle="collapse" role="button" aria-expanded="true" aria-controls="collapseCard"> <h6 class="m-0 font-weight-bold text-primary">Tasks</h6> </a> </div> <div class="collapse show" id="collapseCard"> <div class="card-body collapse show"> <section class="form-row"> <div class="form-group col-md-2"> <input type="date" name="first_name" class="form-control"> </div> <div class="form-group col-md-2"> <button type="button" class="btn btn-primary form-control" data-toggle="modal" data-target="#AddTask">Add new Task</button> </div> </section> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Task Name</th> <th>Date</th> <th>Deadline</th> <th>Duration</th> <th>Assigned To</th> <th>Description</th> </tr> </thead> <tbody> <?php $getEmpID = "SELECT * FROM tbl_employee"; $run = mysqli_query($conn, $getEmpID); while ($row = mysqli_fetch_array($run)) { $id = $row['emp_ID']; $name = $row['Name']; $surname = $row['surname']; $getTasks = "SELECT * FROM tbl_tasks WHERE employee = '$id'"; $run_task = mysqli_query($conn, $getTasks); while ($row = mysqli_fetch_array($run_task)) { $taskname = $row['task_name']; $startdate = $row['task_date']; $deadline = $row['deadline']; $duration = $row['duration']; $assigned_to = $name . " " . $surname; $description = $row['description']; echo " <tr> <td> $taskname </td> <td> $startdate </td> <td> $deadline </td> <td> $duration Days </td> <td> $assigned_to</td> <td> $description </td> </tr>"; } } ?> </tbody> </table> </div> </div> </div> <!-- Content Row --> <div class="row"> <div class="col-lg-6 mb-4"> </div> </div> </div> </div> <!-- Footer --> <footer class="sticky-footer bg-white"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright &copy; <script> document.write(new Date().getFullYear()); </script> JockTech EMS</span> </div> </div> </footer> <!-- End of Footer --> </div> </div> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- add task modal --> <!-- Modal --> <div class="modal fade" id="AddTask" tabindex="-1" role="dialog" aria-labelledby="task" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="task">Add New Task</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="POST" enctype="multipart/form-data"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4"> Task name</label> <input type="text" class="form-control" id="inputEmail4" name="name" placeholder="Task Name" required> </div> <div class="form-group col-md-6"> <label for="inputEmail4">Date</label> <input type="date" class="form-control" id="inputEmail4" name="date" required> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Deadline</label> <input type="date" class="form-control" id="inputPassword4" name="deadline" required> </div> <div class="form-group col-md-6"> <label for="inputState">Assign To</label> <select id="inputState" class="form-control" name="assign" required> <option></option> <?php $get_emp = "SELECT * FROM tbl_employee"; $run = mysqli_query($conn, $get_emp); while ($row = mysqli_fetch_array($run)) { $emp_id = $row['emp_ID']; $name = $row['Name']; $surname = $row['surname']; $Display_name = $name . " " . $surname; echo " <option value='$emp_id'>$Display_name</option> "; } ?> <!-- <option selected>Choose...</option> <option>Male</option> <option>Female</option> --> </select> </div> <div class="form-group col-md-12"> <label for="inputPassword4">Description</label> <input type="text" class="form-control" name="description" placeholder="Description" required> </div> </div> <div class="form-group"> </div> <button type="submit" name="add_task" class="btn btn-primary">Add</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="../plugins/jquery/jquery.min.js"></script> <script src="../plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="../plugins/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="../js/sb-admin-2.min.js"></script> <!-- Page level plugins --> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <!-- Page level custom scripts --> <script src="../js/demo/chart-area-demo.js"></script> <script src="../js/demo/chart-pie-demo.js"></script> <script src="../js/demo/datatables-demo.js"></script> <script src="../plugins/datatables/jquery.dataTables.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> </body> </html> <?php if (isset($_POST['add_task'])) { $taskname = $_POST['name']; $date = $_POST['date']; $end = $_POST['deadline']; $status = "inprogress"; $assigned_to = $_POST['assign']; $description = $_POST['description']; $progress = 0; $content = "New task "; $today = date("F j, Y, g:i a"); $admin = $_SESSION['user']; $diff = abs(strtotime($end) - strtotime($date)); $years = floor($diff / (365 * 60 * 60 * 24)); $months = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24)); $days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24)); $duration = $days; $query = "SELECT * FROM tbl_tasks"; $statement = mysqli_stmt_init($conn); //initialize prepared statement $checkTask = "SELECT * FROM tbl_tasks where employee = '$assigned_to' AND task_name='$taskname' and status ='inprogress' "; $run_check = mysqli_query($conn, $checkTask); $count = mysqli_num_rows($run_check); if ($count > 0) { echo "<script>alert('Task already assigned to this employee and has to be completed first!!')</script>"; echo "<script>window.open('Tasks.php','_self')</script>"; } else { //check if it does not work if (!mysqli_stmt_prepare($statement, $query)) { echo "<script>alert('Server error! please try again later')</script>"; echo "<script>window.open('Tasks.php','_self')</script>"; } else { $insert = "INSERT INTO tbl_tasks (task_name,task_date,deadline,duration,employee,description,progress,status) VALUES(?,?,?,?,?,?,?,?)"; $insert_notification = "INSERT INTO emp_notifications(content,date,emp_id,admin) values(?,?,?,?)"; $statement = mysqli_stmt_init($conn); $statement2 = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($statement, $insert) || !mysqli_stmt_prepare($statement2, $insert_notification)) { echo "<script>alert('Server error! please try again later')</script>"; echo "<script>window.open('Tasks.php','_self')</script>"; } else { mysqli_stmt_bind_param($statement, "ssssisis", $taskname, $date, $end, $duration, $assigned_to, $description, $progress, $status); //bind data mysqli_stmt_bind_param($statement2, "ssis", $content, $today, $assigned_to, $admin); //bind data mysqli_stmt_execute($statement); mysqli_stmt_execute($statement2); echo "<script>alert('New Task has been been created')</script>"; echo "<script>window.open('Tasks.php','_self')</script>"; } } } } ?><file_sep><?php include("../includes/db_con.php"); ?> <link rel="apple-touch-icon" sizes="57x57" href="../favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="../favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="../favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="../favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="../favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="../favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="../favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="../favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="../favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="../favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="../favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="../favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="../favicons/favicon-16x16.png"> <link rel="manifest" href="../favicons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="../favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JockTech EMS</title> <!-- <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap-material-design.min.css" integrity="<KEY>" crossorigin="anonymous" /> --> <link href="../plugins/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="../css/sb-admin-2.min.css" rel="stylesheet"> <link rel="stylesheet" href="../plugins/datatables/dataTables.bootstrap4.min.css"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <?php include("pages/header.php") ?> <!-- page begin content --> <div class="container-fluid"> <?php include("pages/nav-cards.php") ?> <!-- Page Heading --> <h1 class="h3 mb-2 text-gray-800">Reports</h1> <!-- <p class="mb-4">DataTables is a third party plugin that is used to generate the demo table below. For more information about DataTables, please visit the <a target="_blank" href="https://datatables.net">official DataTables documentation</a>.</p> --> <!-- DataTales Example --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary"></h6> </div> <div class="card-body"> <form method="POST" enctype="multipart/form-data"> <div class="form-group"> <label>Report Name</label> <input type="text" class="form-control" name="reportname" placeholder="Report Name"> </div> <div class="form-group"> <label for="exampleFormControlSelect1">Employee</label> <select class="form-control" name="employee" required> <option></option> <?php $get_emp = "SELECT * FROM tbl_employee"; $run = mysqli_query($conn, $get_emp); while ($row = mysqli_fetch_array($run)) { $emp_id = $row['emp_ID']; $name = $row['Name']; $surname = $row['surname']; $Display_name = $name . " " . $surname; echo "<option value='$emp_id'>$Display_name</option> "; } ?> </select> </div> <div class="form-group"> <label>Goals</label> <textarea class="form-control" name="goals" rows="3"></textarea> </div> <div class="form-group"> <label>Improvement Areas</label> <textarea class="form-control" name="areas" rows="3"></textarea> </div> <div class="form-group"> <label>Comments</label> <textarea class="form-control" name="comments" rows="3"></textarea> </div> <div class="col-md-8"> <button type="submit" name="create" class="btn btn-primary">Create</button> </div> </form> </div> </div> </div> <!-- Footer --> <footer class="sticky-footer bg-white"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright &copy; <script> document.write(new Date().getFullYear()); </script> JockTech EMS</span> </div> </div> </footer> <!-- End of Footer --> </div> </div> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Bootstrap core JavaScript--> <script src="../plugins/jquery/jquery.min.js"></script> <script src="../plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="../plugins/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="../js/sb-admin-2.min.js"></script> <!-- Page level plugins --> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <!-- Page level custom scripts --> <script src="../js/demo/chart-area-demo.js"></script> <script src="../js/demo/chart-pie-demo.js"></script> <script src="../js/demo/datatables-demo.js"></script> <script src="../plugins/datatables/jquery.dataTables.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> </body> </html> <?php if (isset($_POST['create'])) { $reportname = $_POST['reportname']; $employeID = $_POST['employee']; $goals = $_POST['goals']; $areasToImprove = $_POST['areas']; $comments = $_POST['comments']; $content = "New Report available"; $today = date("F j, Y, g:i a"); $admin = $_SESSION['user']; $get_Employee = "SELECT * FROM tbl_employee WHERE emp_ID ='$employeID'"; $run = mysqli_query($conn,$get_Employee); $row = mysqli_fetch_array($run); $name = $row['Name']; $surname = $row['surname']; $position = $row['position']; $insert = "INSERT INTO tbl_report(Report_name,Emp_Name,emp_surname,position,Goals,improvement_area,Comments,emp_ID) values('$reportname','$name','$surname','$position','$goals','$areasToImprove','$comments','$employeID')"; $run_insert = mysqli_query($conn,$insert); if(!$run_insert){ echo "<script>alert('Server error! please try again later')</script>"; echo "<script>window.open('reports.php','_self')</script>"; } else{ $insert_notification = "INSERT INTO emp_notifications(content,date,emp_id,admin) values('$content','$today','$employeID','$admin')"; $run = mysqli_query($conn,$insert_notification); echo "<script>alert('New report has been been created')</script>"; echo "<script>window.open('reports.php','_self')</script>"; } } ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <link rel="apple-touch-icon" sizes="57x57" href="../favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="../favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="../favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="../favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="../favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="../favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="../favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="../favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="../favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="../favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="../favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="../favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="../favicons/favicon-16x16.png"> <link rel="manifest" href="../favicons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="../favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JockTech EMS</title> <!-- <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap-material-design.min.css" integrity="<KEY>" crossorigin="anonymous" /> --> <link href="../plugins/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="../css/sb-admin-2.min.css" rel="stylesheet"> <link rel="stylesheet" href="../plugins/datatables/dataTables.bootstrap4.min.css"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <?php include("pages/header.php") ?> <!-- page begin content --> <div class="container-fluid"> <?php include("pages/nav-cards.php") ?> <div class="card shadow mb-4"> <div class="card-header py-3"> <a href="#collapseCard" class="d-block card-header py-3" data-toggle="collapse" role="button" aria-expanded="true" aria-controls="collapseCard"> <h6 class="m-0 font-weight-bold text-primary">Salary increase requests</h6> </a> </div> <div class="collapse show" id="collapseCard"> <div class="card-body collapse show"> <div class="form-row"> <div class="form-group col-md-2"> <button class="btn btn-success " data-toggle="modal" data-target="#Approve"> <i class="fas fa-check-circle"></i> Approve</button> </div> <div class="form-group col-md-2"> <button class="btn btn-danger " data-toggle="modal" data-target="#Decline"> <i class="fas fa-times"></i> Decline</button> </div> </div> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Emplyee ID</th> <th>Name</th> <th>Surname</th> <th>Position</th> <th>Start date</th> </tr> </thead> <tbody> <?php $status = "pending"; $getIncreaseRequests = "SELECT * FROM tbl_increaserequest where status ='$status'"; $run = mysqli_query($conn, $getIncreaseRequests); while ($row = mysqli_fetch_array($run)) { $id = $row['emp_ID']; $name = $row['Emp_Name']; $surname = $row['Emp_surname']; $startdate = $row['Start_Date']; $position = $row['Position']; echo " <tr> <td> $id </td> <td> $name </td> <td> $surname </td> <td> $position</td> <td> $startdate </td> </tr>"; } ?> </tbody> </table> </div> </div> </div> </div> </div> </div> <!-- Footer --> <footer class="sticky-footer bg-white"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright &copy; <script> document.write(new Date().getFullYear()); </script> JockTech EMS</span> </div> </div> </footer> <!-- End of Footer --> </div> </div> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- add decline modal --> <!-- Modal --> <div class="modal fade" id="Decline" tabindex="-1" role="dialog" aria-labelledby="announcementCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="announcementModalLongTitle">Decline Application</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="POST" enctype="multipart/form-data"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputState">Employee</label> <select id="inputState" class="form-control" name="id" required> <option></option> <?php $get_emp = "SELECT * FROM tbl_increaserequest where status ='$status'"; $run = mysqli_query($conn, $get_emp); while ($row = mysqli_fetch_array($run)) { $emp_id = $row['emp_ID']; $name = $row['Emp_Name']; $surname = $row['Emp_surname']; $Display_name = $name . " " . $surname; echo "<option value='$emp_id'> $emp_id - $Display_name</option> "; } ?> </select> </div> <div class="form-group col-md-6"> <label for="inputState">Decision</label> <select id="inputState" class="form-control" name="decisions" required> <option></option> <option>Declined</option> </select> </div> </div> <div class="form-group"> </div> <button type="submit" name="decline" class="btn btn-primary">Submit</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- add approved modal --> <!-- Modal --> <div class="modal fade" id="Approve" tabindex="-1" role="dialog" aria-labelledby="announcementCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="announcementModalLongTitle">Approve Application</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="POST" enctype="multipart/form-data"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputState">Employee</label> <select id="inputState" class="form-control" name="id" required> <option></option> <?php $status = "pending"; $get_emp = "SELECT * FROM tbl_increaserequest where status ='$status'"; $run = mysqli_query($conn, $get_emp); while ($row = mysqli_fetch_array($run)) { $emp_id = $row['emp_ID']; $name = $row['Emp_Name']; $surname = $row['Emp_surname']; $Display_name = $name . " " . $surname; echo "<option value='$emp_id'> $emp_id - $Display_name</option> "; } ?> </select> </div> <div class="form-group col-md-6"> <label for="inputState">Decision</label> <select id="inputState" class="form-control" name="decision" required> <option></option> <option>Approved</option> </select> </div> </div> <div class="form-group col-md-6"> <span>Increase Amount(%)</span> <input type="number" class="form-control" name="amount" required> </div> <button type="submit" name="Approve" class="btn btn-primary">Submit</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="../plugins/jquery/jquery.min.js"></script> <script src="../plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="../plugins/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="../js/sb-admin-2.min.js"></script> <!-- Page level plugins --> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <!-- Page level custom scripts --> <script src="../js/demo/chart-area-demo.js"></script> <script src="../js/demo/chart-pie-demo.js"></script> <script src="../js/demo/datatables-demo.js"></script> <script src="../plugins/datatables/jquery.dataTables.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> </body> </html> <?php if (isset($_POST['decline'])) { $decision = $_POST['decisions']; $emp_id = $_POST['id']; $admin = $_SESSION['user']; $content = "Salary increase Application " . " " . $decision; $today = date("F j, Y, g:i a"); $select = "SELECT * FROM tbl_increaserequest where emp_ID ='$id' and status ='pending'"; $run = mysqli_query($conn, $select); $row = mysqli_fetch_array($run); $app_id = $row['Req_ID']; $Update = "UPDATE tbl_increaserequest SET status='$decision' where emp_ID='$emp_id' AND Req_ID ='$app_id'"; $run_update = mysqli_query($conn, $Update); $insert_notification = "INSERT INTO emp_notifications(content,date,emp_id,admin) values('$content','$today','$emp_id','$admin')"; $run_insert = mysqli_query($conn, $insert_notification); if ($run_update || $run_insert) { echo "<script>alert('Application has been processed')</script>"; echo "<script>window.open('increase.php','_self')</script>"; } else { echo "<script>alert('Server error! Application could not be processed please try again later')</script>"; } } ?> <!-- approve increase --> <?php // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; if (isset($_POST['Approve'])) { $decision = $_POST['decision']; $emp_id = $_POST['id']; $admin = $_SESSION['user']; $amount = $_POST['amount']; $increase_rate = $_POST['rate']; $content = "Salary increase Application " . " " . $decision; $today = date("F j, Y, g:i a"); $total; $subject = $_POST['subject']; $admin = $_SESSION['user']; $select = "SELECT * FROM tbl_increaserequest where emp_ID ='$id' and status = 'pending'"; $run = mysqli_query($conn, $select); $row = mysqli_fetch_array($run); $app_id = $row['Req_ID']; // calculate increase $query = "SELECT * FROM tbl_employee where emp_ID = '$emp_id'"; $run_query = mysqli_query($conn, $query); $row = mysqli_fetch_array($run_query); $salary = $row['SALARY']; $email = $row['EMAIL_ADDRESS']; $name = $row['Name']; $surname = $row['surname']; $Display_name = $name ." ". $surname; $rate = $amount /100; $increase = $salary * $rate; $total = $salary + $increase; require 'vendor/autoload.php'; // Instantiation and passing `true` enables exceptions $mail = new PHPMailer(true); try { //Server settings //$mail->SMTPDebug = 2; //SMTP::DEBUG_SERVER; // Enable verbose debug output $mail->isSMTP(); // Send using SMTP $mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = '<EMAIL>'; // SMTP username $mail->Password = <PASSWORD>'; // SMTP password $mail->SMTPSecure = 'tls'; //PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged $mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above //Recipients $mail->setFrom('<EMAIL>', $admin); $mail->addAddress($email); // Add a recipient $body = '<table align="center" border="0" cellpadding="0" cellspacing="0" width="600" style="border: 1px solid #cccccc; border-collapse: collapse;"> <tr> <td style="padding: 10px 0 30px 0;"> <table align="center" border="0" cellpadding="0" cellspacing="0" width="600" style="border: 1px solid #cccccc; border-collapse: collapse;"> <tr> <td align="center" bgcolor="#70bbd9" style="padding: 40px 0 30px 0; color: #153643; font-size: 28px; font-weight: bold; font-family: Arial, sans-serif;"> <img src="images\logo.png" alt="Welcome" width="300" height="230" style="display: block;" /> </td> </tr> <tr> <td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td style="color: #153643; font-family: Arial, sans-serif; font-size: 24px;"> <b>Hey there ' . $Display_name . '</b> </td> </tr> <tr> <td style="padding: 20px 0 30px 0; color: #153643; font-family: Arial, sans-serif; font-size: 16px; line-height: 20px;"> Your salary increase request has been reviewed and approved. starting from next month you will recieve a raise of '.$amount.'% on your current salary <br> <br> Administration <br> Thank you! </td> </tr> </table> </td> </tr> <tr> </tr> </table> </td> </tr> </table> </td> </tr> </table>'; // Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = $content; $mail->Body = $body; $mail->AltBody = "username is $Username and the defaults password is <PASSWORD>"; $Update_salary = "UPDATE tbl_employee SET SALARY='$total' where emp_ID='$emp_id'"; $run_salaryUpdate = mysqli_query($conn, $Update_salary); $Update = "UPDATE tbl_increaserequest SET status='$decision' where emp_ID='$emp_id' AND Req_ID ='$app_id'"; $run_update = mysqli_query($conn, $Update); $insert_notification = "INSERT INTO emp_notifications(content,date,emp_id,admin) values('$content','$today','$emp_id','$admin')"; $run_insert = mysqli_query($conn, $insert_notification); if ($run_update || $run_insert||$run_salaryUpdate) { $mail->send(); echo "<script>alert('Application has been processed ! Salary has been updated')</script>"; echo "<script>window.open('increase.php','_self')</script>"; } else { echo "<script>alert('Server error! Application could not be processed please try again later')</script>"; echo "<script>window.open('increase.php','_self')</script>"; } } catch (Exception $e) { //echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; echo "<script>alert('eMessage could not be sent. Mailer Error:'{$mail->ErrorInfo}')</script>"; //echo "<script>window.open('employees.php','_self')</script>"; } } ?><file_sep> <?php //copyright jocktech inc 2020 //check if the user accessed to this script if(isset($_POST['submit_btn'])){ include("../includes/db_con.php"); //fetch data from text fields $name = $_POST['first_name']; $surname = $_POST['last_name']; $ID_No = $_POST['id_no']; $Phone_No = $_POST['phone']; $Email = $_POST['email']; $Username = $_POST['username']; $Password = $_POST['<PASSWORD>']; //use prepared statements to create queries // check if user already exists $check_user = "SELECT USERNAME FROM tbl_admin WHERE USERNAME =?"; $statement = mysqli_stmt_init($conn); //initialize prepared statement //check if it does not work if(!mysqli_stmt_prepare($statement,$check_user)){ header("Location: register.php?error=sqlerror"); exit(); } else{ mysqli_stmt_bind_param($statement,"s",$Username); mysqli_stmt_execute($statement); mysqli_stmt_store_result($statement); $check_results = mysqli_stmt_num_rows($statement); if($check_results >0 ){ header("Location: register.php?error=usernametaken".$Username); exit(); } else{ //insert users $insert_user = "INSERT INTO tbl_admin(NAME,SURNAME,ID_NUMBER,PHONE_NUMBER,EMAIL,USERNAME,PASSWORD) VALUES(?,?,?,?,?,?,?)"; $statement = mysqli_stmt_init($conn); if(!mysqli_stmt_prepare($statement,$insert_user)){ header("Location: register.php?error=sqlerror"); exit(); } else{ //hash password $pass_hash = password_hash($Password,PASSWORD_DEFAULT); mysqli_stmt_bind_param($statement,"sssssss",$name,$surname,$ID_No,$Phone_No,$Email,$Username,$pass_hash);//bind data mysqli_stmt_execute($statement); session_start(); // $name = $row['NAME']; // $surname = $row['SURNAME']; // $Display_name = $name." ".$surname; // $_SESSION['user'] = $Display_name; header("Location: index.php?signup=success"); exit(); } } } mysqli_stmt_close($statement); //close statement mysqli_stmt_close($conn); //close connection } else{ //send user to register page if they tried to header("Location: register.php"); exit(); }<file_sep><?php if(isset($_POST['login-btn'])){ include("../includes/db_con.php"); //get data from text fields $username = $_POST['username']; $password = $_POST['<PASSWORD>']; $select = "SELECT * FROM tbl_admin where USERNAME =?"; $statement = mysqli_stmt_init($conn); if(!mysqli_stmt_prepare($statement,$select)){ header("Location: index.php?error=sqlerror"); exit(); } else{ //get info from database mysqli_stmt_bind_param($statement,"s",$username); mysqli_stmt_execute($statement); $results = mysqli_stmt_get_result($statement); if($row = mysqli_fetch_assoc($results)){ $check_pass = password_verify($password,$row['PASSWORD']); if($check_pass == false){ header("Location: index.php?error=wrongpassword"); exit(); } elseif($check_pass ==true){ $id = $row['ADMIN_ID']; $name = $row['NAME']; $surname = $row['SURNAME']; $Display_name = $name." ".$surname; session_start(); $_SESSION['id'] = $id; $_SESSION['user'] = $Display_name; header("Location: dashboard.php?login=success"); exit(); } } else{ header("Location: index.php?error=nouser"); exit(); } } } else{ header("Location: index.php"); }<file_sep># employee-management-system This is an employee management system demo web app developed with bootstrap, php and MySQL database using the SB Admin 2 admin theme. <file_sep><?php if (isset($_POST['submit'])) { include "includes/db_con.php"; session_start(); $name = $_POST['name']; $surname = $_POST['surname']; $position = $_POST['position']; $start_date = $_POST['date']; $Reasons = $_POST['reason']; $id = $_SESSION['id']; $status = "pending"; $content = "salary increase application request"; $today = date("F j, Y, g:i a"); $now = date("Y-m-d H:i:s"); $employee = $_SESSION['user']; //$diff = abs(strtotime($to) - strtotime($from)); // $years = floor($diff / (365 * 60 * 60 * 24)); // $months = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24)); // $days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24)); // $duration = $days; $query = "SELECT * FROM tbl_increaserequest where emp_ID =? and status =?"; $statement = mysqli_stmt_init($conn); //initialize prepared statement //check if it does not work if (!mysqli_stmt_prepare($statement, $query)) { echo "<script>alert('Server error! please try again later')</script>"; echo "<script>window.open('increase.php','_self')</script>"; } else { mysqli_stmt_bind_param($statement, "is", $id,$status); mysqli_stmt_execute($statement); mysqli_stmt_store_result($statement); $check_results = mysqli_stmt_num_rows($statement); if ($check_results > 0) { echo "<script>alert('You Application is Still Pending! You can not apply for another one')</script>"; echo "<script>window.open('Progress.php','_self')</script>"; } else { $insert = "INSERT INTO tbl_increaserequest (Emp_Name,Emp_surname,Position,Start_Date,reason,emp_ID,date_applied,status) VALUES(?,?,?,?,?,?,?,?)"; $insert_notification = "INSERT INTO admin_notifications(content,date,employee) values(?,?,?)"; $statement = mysqli_stmt_init($conn); $statement2 = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($statement, $insert) || !mysqli_stmt_prepare($statement2, $insert_notification)) { echo "<script>alert('Server error! Application could not be processed please try again later')</script>"; echo "<script>window.open('increase.php','_self')</script>"; } else { mysqli_stmt_bind_param($statement, "sssssiss", $name, $surname, $position, $start_date,$Reasons, $id, $now,$status); //bind data mysqli_stmt_bind_param($statement2, "sss", $content, $today, $employee); //bind data mysqli_stmt_execute($statement); mysqli_stmt_execute($statement2); echo "<script>alert('Your Application has been submitted and is now being Processed')</script>"; echo "<script>window.open('Progress.php','_self')</script>"; } } } } <file_sep><?php include("../includes/db_con.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <link rel="apple-touch-icon" sizes="57x57" href="../favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="../favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="../favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="../favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="../favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="../favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="../favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="../favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="../favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="../favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="../favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="../favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="../favicons/favicon-16x16.png"> <link rel="manifest" href="../favicons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="../favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JockTech EMS</title> <!-- <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap-material-design.min.css" integrity="<KEY>" crossorigin="anonymous" /> --> <link href="../plugins/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="../css/sb-admin-2.min.css" rel="stylesheet"> <link rel="stylesheet" href="../plugins/datatables/dataTables.bootstrap4.min.css"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <?php include("pages/header.php") ?> <!-- page begin content --> <div class="container-fluid"> <?php include("pages/nav-cards.php") ?> <div class="row"> <!-- Area Chart --> <div class="col-xl-8 col-lg-7"> <div class="card shadow mb-4"> <!-- Card Header - Dropdown --> <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"> <h6 class="m-0 font-weight-bold text-primary">Earnings Overview</h6> </div> <!-- Card Body --> <div class="card-body"> <div class="chart-area"> <canvas id="myAreaChart"></canvas> </div> </div> </div> </div> <!-- Pie Chart --> <div class="col-xl-4 col-lg-5"> <div class="card shadow mb-4"> <!-- Card Header - Dropdown --> <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"> <h6 class="m-0 font-weight-bold text-primary">Revenue Sources</h6> </div> <!-- Card Body --> <div class="card-body"> <div class="chart-pie pt-4 pb-2"> <canvas id="myPieChart"></canvas> </div> <div class="mt-4 text-center small"> <span class="mr-2"> <i class="fas fa-circle text-primary"></i> Hydraulics Repairs </span> <span class="mr-2"> <i class="fas fa-circle text-success"></i> Pipe Jacking </span> <span class="mr-2"> <i class="fas fa-circle text-info"></i> Hydarulics Hose sell </span> </div> </div> </div> </div> </div> <!-- Content Row --> <div class="row"> <!-- Content Column --> <div class="col-lg-6 mb-4"> <!-- Project Card Example --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">work progress</h6> </div> <?php getTasks(); ?> </div> <div class="row"> </div> </div> <div class="col-lg-6 mb-4"> <!-- Illustrations --> <div class="card shadow mb-4"> </div> <!-- Approach --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Announcements</h6> </div> <?php getAnnouncements(); ?> </div> </div> </div> </div> </div> <!-- Footer --> <footer class="sticky-footer bg-white"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright &copy; <script> document.write(new Date().getFullYear()); </script> JockTech EMS</span> </div> </div> </footer> <!-- End of Footer --> </div> </div> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Bootstrap core JavaScript--> <script src="../plugins/jquery/jquery.min.js"></script> <script src="../plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="../plugins/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="../js/sb-admin-2.min.js"></script> <!-- Page level plugins --> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <!-- Page level custom scripts --> <script src="../js/demo/chart-area-demo.js"></script> <script src="../js/demo/chart-pie-demo.js"></script> <script src="../js/demo/datatables-demo.js"></script> <script src="../plugins/datatables/jquery.dataTables.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> </body> </html><file_sep> <?php include("../includes/db_con.php"); session_start(); ?> <!-- Sidebar --> <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar"> <!-- Sidebar - Brand --> <a class="sidebar-brand d-flex align-items-center justify-content-center" href="dashboard.php"> <div class="sidebar-brand-icon rotate-n-15"> <!-- <i class="fas fa-laugh-wink"></i> --> </div> <div class="sidebar-brand-text mx-3">JockTech EMS </sup></div> </a> <!-- Divider --> <hr class="sidebar-divider my-0"> <!-- Nav Item - Dashboard --> <li class="nav-item active"> <a class="nav-link" href="dashboard.php"> <i class="fas fa-fw fa-tachometer-alt"></i> <span>Dashboard</span></a> </li> <!-- Divider --> <hr class="sidebar-divider"> <!-- Heading --> <div class="sidebar-heading"> Interface </div> <!-- Nav Item - Pages Collapse Menu --> <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo"> <i class="fas fa-fw fa-users"></i> <span>Employee Management</span> </a> <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <!-- <h6 class="collapse-header">Manage Employees:</h6> <a type="button" class="collapse-item btn-success" data-toggle="modal" data-target="#AddEmployee"> New Employee</a> --> <a class="collapse-item btn-warning" href="employees.php">Manage Employees</a> </div> </div> </li> <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapse3" aria-expanded="true" aria-controls="collapse3"> <i class="fas fa-fw fa-money-check"></i> <span>Salary Management</span> </a> <div id="collapse3" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Manage Salaries:</h6> <a class="collapse-item btn-success" href="salary.php"> Employee Salaries</a> <a class="collapse-item" href="increase.php">Salary increase requests</a> </div> </div> </li> <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseLeave" aria-expanded="true" aria-controls="collapseLeave"> <i class="fas fa-fw fa-door-open"></i> <span>Leave Management</span> </a> <div id="collapseLeave" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Manage Leave Applications:</h6> <a class="collapse-item" href="leave.php"> View Leave Applications</a> </div> </div> </li> <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseReport" aria-expanded="true" aria-controls="collapseReport"> <i class="fas fa-fw fa-clipboard"></i> <span>Reports Management</span> </a> <div id="collapseReport" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Manage reports:</h6> <a class="collapse-item" href="reports.php">Performance Report</a> </div> </div> </li> <!-- Nav Item - Utilities Collapse Menu --> <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseNotice" aria-expanded="true" aria-controls="collapseNotice"> <i class="fas fa-fw fa-flag"></i> <span>Notices</span> </a> <div id="collapseNotice" class="collapse" aria-labelledby="headingUtilities" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Manage Utilities:</h6> <a class="collapse-item" href="Timesheet.php">Timesheet</a> <!-- <a class="collapse-item" href="reports.php">Reports</a> --> <a class="collapse-item" type="button"data-toggle="modal" data-target="#AddMeeting">Meetings</a> <a class="collapse-item" href="Tasks.php">Tasks</a> <a type="button" class="collapse-item" data-toggle="modal" data-target="#PostAnnouncement">Announcements</a> </div> </div> </li> <div class="text-center d-none d-md-inline"> <button class="rounded-circle border-0" id="sidebarToggle"></button> </div> </ul> <!-- End of Sidebar --> <!-- content wrapper --> <div id="content-wrapper" class="d-flex flex-column"> <div id="content"> <!-- Topbar --> <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow"> <!-- Sidebar Toggle (Topbar) --> <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3"> <i class="fa fa-bars"></i> </button> <!-- Topbar Navbar --> <ul class="navbar-nav ml-auto"> <!-- Nav Item - Messages --> <li class="nav-item dropdown no-arrow mx-1"> <a class="nav-link dropdown-toggle" href="#" id="messagesDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-envelope fa-fw"></i> <?php $id = $_SESSION['id']; $getNotifications = "SELECT * FROM admin_notifications"; $run = mysqli_query($conn, $getNotifications); $count = mysqli_num_rows($run); if ($count==0) { echo ' <span class="badge badge-danger badge-counter">0</span>'; } else { echo ' <span class="badge badge-danger badge-counter">'.$count.'</span> </a>'; } ?> </a> <!-- Dropdown - Messages --> <div class="dropdown-list dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="messagesDropdown"> <h6 class="dropdown-header"> Message Center </h6> <?php while($row = mysqli_fetch_array($run)){ $content = $row['content']; $date = $row['date']; $admin = $row['employee']; echo ' <a class="dropdown-item d-flex align-items-center" href="#"> <div class="dropdown-list-image mr-3"> <img class="rounded-circle" src="../images/logo.png" alt=""> <div class="status-indicator bg-success"></div> </div> <div class="font-weight-bold"> <div class="text-truncate">'.$content.'</div> <div class="small text-gray-500">'.$admin.' '.$date.'</div> </div> </a> '; } ?> </div> </li> <div class="topbar-divider d-none d-sm-block"></div> <!-- Nav Item - User Information --> <li class="nav-item dropdown no-arrow"> <a class="nav-link dropdown-toggle" href="profile.php" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="mr-2 d-none d-lg-inline text-gray-600 small"><?php if (isset($_SESSION['user'])) { echo $_SESSION['user'] ; } ?></span> <img class="img-profile rounded-circle img-fluid" src="../images/logo.png"> </a> <!-- Dropdown - User Information --> <div class="dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="userDropdown"> <a class="dropdown-item" href="profile.php?id=<?php echo $_SESSION['id'] ;?> "> <i class="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i> Profile </a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#" data-toggle="modal" data-target="#logoutModal"> <i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i> Logout </a> </div> </li> </ul> </nav> <!-- End of Topbar --> <?php if (isset($_POST['add_announcement'])) { $date = $_POST['date']; $agenda = $_POST['agenda']; $now = (new DateTime('now'))->format('Y-m-d H:i:s'); $query = "SELECT * FROM tbl_announcements"; $statement = mysqli_stmt_init($conn); //initialize prepared statement //check if it does not work if (!mysqli_stmt_prepare($statement, $query)) { echo "<script>alert('Server error! please try again later')</script>"; echo "<script>window.open('dashboard.php','_self')</script>"; } else { $insert = "INSERT INTO tbl_announcements (Date,time,Agenda) VALUES(?,?,?)"; $statement = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($statement, $insert)) { echo "<script>alert('Server error! please try again later')</script>"; echo "<script>window.open('dashboard.php','_self')</script>"; } else { mysqli_stmt_bind_param($statement, "sss", $date, $now, $agenda);//bind data mysqli_stmt_execute($statement); echo "<script>alert('New Announcement has been posted')</script>"; echo "<script>window.open('dashboard.php','_self')</script>"; } } } ?> <!-- add announcement modal --> <!-- Modal --> <div class="modal fade" id="PostAnnouncement" tabindex="-1" role="dialog" aria-labelledby="announcementCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="announcementModalLongTitle">Post new announcements</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="POST" enctype="multipart/form-data"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4">Date</label> <input type="date" class="form-control" id="inputEmail4" name="date" placeholder="Date" required> </div> <div class="form-group col-md-6"> <label for="inputEmail4">Agenda</label> <input type="text" class="form-control" id="inputEmail4" name="agenda" placeholder="Agenda" required> </div> </div> <div class="form-group"> </div> <button type="submit" name="add_announcement" class="btn btn-primary">Post</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <?php if (isset($_POST['add_Meeting'])) { $date = $_POST['date']; $subject = $_POST['subject']; $start = $_POST['start']; $end = $_POST['end']; $query = "SELECT * FROM tbl_meetings"; $statement = mysqli_stmt_init($conn); //initialize prepared statement //check if it does not work if (!mysqli_stmt_prepare($statement, $query)) { echo "<script>alert('Server error! please try again later')</script>"; echo "<script>window.open('dashboard.php','_self')</script>"; } else { $insert = "INSERT INTO tbl_meetings (Subject,Meeting_Date,Start_time,End_time) VALUES(?,?,?,?)"; $statement = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($statement, $insert)) { echo "<script>alert('Server error! please try again later')</script>"; echo "<script>window.open('dashboard.php','_self')</script>"; } else { mysqli_stmt_bind_param($statement, "ssss", $subject, $date, $start, $end);//bind data mysqli_stmt_execute($statement); echo "<script>alert('New Meeting has been created')</script>"; echo "<script>window.open('dashboard.php','_self')</script>"; } } } ?> <!-- add meetings modal --> <!-- Modal --> <div class="modal fade" id="AddMeeting" tabindex="-1" role="dialog" aria-labelledby="MeetingCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="MeetingModalLongTitle">Create new Meeting</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="POST" enctype="multipart/form-data"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4">Subject</label> <input type="text" class="form-control" name="subject" placeholder="Subject" required> </div> <div class="form-group col-md-6"> <label for="inputEmail4">Date</label> <input type="date" class="form-control" name="date" required> </div> <div class="form-group col-md-6"> <label for="inputEmail4">Start Time</label> <input type="time" class="form-control" name="start" required> </div> <div class="form-group col-md-6"> <label for="inputEmail4">End Time</label> <input type="time" class="form-control" name="end" required> </div> </div> <div class="form-group"> </div> <button type="submit" name="add_Meeting" class="btn btn-primary">Post</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Logout Modal--> <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <form action="logout.inc.php"> <a type="button" class="btn btn-primary" href="logout.inc.php">Logout</a> </form> </div> </div> </div> </div> <file_sep><?php include "includes/db_con.php"; ?> <!DOCTYPE html> <html lang="en"> <head> <link rel="apple-touch-icon" sizes="57x57" href="favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="favicons/favicon-16x16.png"> <link rel="manifest" href="../favicons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JockTech EMS</title> <!-- <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap-material-design.min.css" integrity="<KEY>" crossorigin="anonymous" /> --> <link href="plugins/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="css/sb-admin-2.min.css" rel="stylesheet"> <link rel="stylesheet" href="plugins/datatables/dataTables.bootstrap4.min.css"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <?php include "pages/header.php" ?> <!-- page begin content --> <div class="container-fluid"> <?php include "pages/nav-cards.php" ?> <div class="card shadow mb-4"> <div class="card-header py-3"> <a href="#collapseCard" class="d-block card-header py-3" data-toggle="collapse" role="button" aria-expanded="true" aria-controls="collapseCard"> <h6 class="m-0 font-weight-bold text-primary">My Tasks</h6> </a> </div> <div class="collapse show" id="collapseCard"> <div class="card-body collapse show"> <div class="form-row"> <div class="form-group col-md-2"> <button class="btn btn-success " data-toggle="modal" data-target="#UpdateTask"> <i class="fas fa-wrench"></i> Update Progress</button> </div> </div> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Task Name</th> <th>Task Description</th> <th>Date Assigned</th> <th>Dealine Date</th> <th>Progress</th> <th>Status</th> </tr> </thead> <tbody> <?php $id = $_SESSION['id']; $getEmployees = "SELECT * FROM tbl_tasks where employee ='$id'"; $run = mysqli_query($conn, $getEmployees); while ($row = mysqli_fetch_array($run)) { $task_name = $row['task_name']; $date = $row['task_date']; $end = $row['deadline']; $status = $row['status']; $progress = $row['progress']; $description = $row['description']; echo " <tr> <td> $task_name </td> <td> $description </td> <td> $date </td> <td> $end </td> <td> $progress </td> <td> $status </td> </tr>"; } ?> </tbody> </table> </div> </div> </div> </div> </div> <!-- Footer --> <footer class="sticky-footer bg-white"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright &copy; <script> document.write(new Date().getFullYear()); </script> JockTech EMS</span> </div> </div> </footer> <!-- End of Footer --> <!-- update task modal --> <!-- Modal --> <div class="modal fade" id="UpdateTask" tabindex="-1" role="dialog" aria-labelledby="task" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="task">Update Task Progress</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="POST" enctype="multipart/form-data"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputState">Task Name</label> <select id="inputState" class="form-control" name="task_id" required> <option ></option> <?php $id = $_SESSION['id']; $stat = "inprogress"; $get_task = "SELECT * FROM tbl_tasks where employee ='$id' and status ='$stat'"; $run = mysqli_query($conn, $get_task); while ($row = mysqli_fetch_array($run)) { $task_id = $row['task_ID']; $name = $row['task_name']; echo " <option value='$task_id'>$name</option> "; } ?> </select> </div> <div class="form-group col-md-4"> <label for="inputPassword4">Progress %</label> <input type="number" class="form-control" name="progress" placeholder="Task Progress" required> </div> </div> <div class="form-group"> </div> <button type="submit" name="update" class="btn btn-primary">Update</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> </div> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Bootstrap core JavaScript--> <script src="plugins/jquery/jquery.min.js"></script> <script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="plugins/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="js/sb-admin-2.min.js"></script> <!-- Page level plugins --> <script src="plugins/chart.js/Chart.bundle.min.js"></script> <script src="plugins/datatables/dataTables.bootstrap4.min.js"></script> <script src="plugins/chart.js/Chart.bundle.min.js"></script> <!-- Page level custom scripts --> <script src="js/demo/chart-area-demo.js"></script> <script src="js/demo/chart-pie-demo.js"></script> <script src="js/demo/datatables-demo.js"></script> <script src="plugins/datatables/jquery.dataTables.min.js"></script> <script src="plugins/datatables/dataTables.bootstrap4.min.js"></script> </body> </html> <?php if(isset($_POST['update'])){ $Task_id = $_POST['task_id']; $progress = $_POST['progress']; $stat ="inprogress"; $value =100; $min =0; $query = "SELECT * FROM tbl_tasks WHERE employee ='$id' and task_ID ='$Task_id'"; $run = mysqli_query($conn,$query); $row = mysqli_fetch_array($run); $total = $row['progress']; $sum = $total + $progress; if($sum == $value){ $stat = "Complete"; } if ($progress <$min) { echo "<script>alert('No negative numbers are allowed')</script>"; echo "<script>window.open('mytasks.php','_self')</script>"; } else if($sum >$value){ echo "<script>alert(' Large Percentage entered !!! Progress is currently at $total% and can not exceed 100% please enter a valid percentage!')</script>"; echo "<script>window.open('mytasks.php','_self')</script>"; } else{ $query = "UPDATE tbl_tasks SET progress ='$sum' ,status ='$stat' WHERE task_ID ='$Task_id'"; $run = mysqli_query($conn,$query); if($run){ echo "<script>alert('Task Progress Updated')</script>"; echo "<script>window.open('mytasks.php','_self')</script>"; } else{ echo "<script>alert('Server Error! Could Not Update Task progress this time . Try again later')</script>"; // mail($to_email,$subject,$message,$headers); echo "<script>window.open('mytasks.php','_self')</script>"; } } } ?><file_sep> <?php include("includes/db_con.php"); session_start(); ?> <!-- Sidebar --> <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar"> <!-- Sidebar - Brand --> <a class="sidebar-brand d-flex align-items-center justify-content-center" href="Dashboard.php"> <div class="sidebar-brand-icon rotate-n-15"> <!-- <i class="fas fa-laugh-wink"></i> --> </div> <div class="sidebar-brand-text mx-3">JockTech EMS </sup></div> </a> <!-- Divider --> <hr class="sidebar-divider my-0"> <!-- Nav Item - Dashboard --> <li class="nav-item active"> <a class="nav-link" href="Dashboard.php"> <i class="fas fa-fw fa-tachometer-alt"></i> <span>Dashboard</span></a> </li> <!-- Divider --> <hr class="sidebar-divider"> <!-- Heading --> <div class="sidebar-heading"> Interface </div> <!-- Nav Item - Pages Collapse Menu --> <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo"> <i class="fas fa-fw fa-door-open"></i> <span>Leave</span> </a> <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <!-- <h6 class="collapse-header">Manage Employees:</h6> <a type="button" class="collapse-item btn-success" data-toggle="modal" data-target="#AddEmployee"> New Employee</a> --> <a class="collapse-item btn-success" href="leave.php">Leave Application</a> <a class="collapse-item btn-primary" href="track.php">Track progress</a> </div> </div> </li> <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseSalary" aria-expanded="true" aria-controls="collapseSalary"> <i class="fas fa-fw fa-money-check"></i> <span>salary requests</span> </a> <div id="collapseSalary" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <!-- <h6 class="collapse-header">Manage Employees:</h6> <a type="button" class="collapse-item btn-success" data-toggle="modal" data-target="#AddEmployee"> New Employee</a> --> <a class="collapse-item btn-warning" href="increase.php">Increase Application</a> <a class="collapse-item btn-success" href="Progress.php">Track Progress</a> </div> </div> </li> <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapse3" aria-expanded="true" aria-controls="collapse3"> <i class="fas fa-fw fa-clock"></i> <span>View Timesheet</span> </a> <div id="collapse3" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">View Timesheet:</h6> <a class="collapse-item btn-success" href="timesheet.php"> My timesheet</a> </div> </div> </li> <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseLeave" aria-expanded="true" aria-controls="collapseLeave"> <i class="fas fa-fw fa-file-alt"></i> <span>Reports</span> </a> <div id="collapseLeave" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">My reports:</h6> <a class="collapse-item" href="report.php"> Perfomance report</a> </div> </div> </li> <!-- Nav Item - Utilities Collapse Menu --> <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseNotice" aria-expanded="true" aria-controls="collapseNotice"> <i class="fas fa-fw fa-flag"></i> <span>Notices</span> </a> <div id="collapseNotice" class="collapse" aria-labelledby="headingUtilities" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Manage Utilities:</h6> <a class="collapse-item" href="meetings.php">Meetings</a> <a class="collapse-item" href="mytasks.php">Tasks</a> <a class="collapse-item" href="register.php">Change Password</a> </div> </div> </li> <div class="text-center d-none d-md-inline"> <button class="rounded-circle border-0" id="sidebarToggle"></button> </div> </ul> <!-- End of Sidebar --> <!-- content wrapper --> <div id="content-wrapper" class="d-flex flex-column"> <div id="content"> <!-- Topbar --> <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow"> <!-- Sidebar Toggle (Topbar) --> <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3"> <i class="fa fa-bars"></i> </button> <!-- Topbar Search --> <!-- Topbar Navbar --> <ul class="navbar-nav ml-auto"> <!-- Nav Item - Messages --> <li class="nav-item dropdown no-arrow mx-1"> <a class="nav-link dropdown-toggle" href="#" id="messagesDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-envelope fa-fw"></i> <?php $id = $_SESSION['id']; $getNotifications = "SELECT * FROM emp_notifications where emp_id ='$id'"; $run = mysqli_query($conn, $getNotifications); $count = mysqli_num_rows($run); if ($count==0) { echo ' <span class="badge badge-danger badge-counter">0</span>'; } else { echo ' <span class="badge badge-danger badge-counter">'.$count.'</span> </a>'; } ?> </a> <!-- Dropdown - Messages --> <div class="dropdown-list dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="messagesDropdown"> <h6 class="dropdown-header"> Message Center </h6> <?php while($row = mysqli_fetch_array($run)){ $content = $row['content']; $date = $row['date']; $admin = $row['admin']; echo ' <a class="dropdown-item d-flex align-items-center" href="#"> <div class="dropdown-list-image mr-3"> <img class="rounded-circle" src="images/logo.png" alt=""> <div class="status-indicator bg-success"></div> </div> <div class="font-weight-bold"> <div class="text-truncate">'.$content.'</div> <div class="small text-gray-500">'.$admin.' '.$date.'</div> </div> </a> '; } ?> </div> </li> <div class="topbar-divider d-none d-sm-block"></div> <!-- Nav Item - User Information --> <li class="nav-item dropdown no-arrow"> <a class="nav-link dropdown-toggle" href="profile.php?id=<?php echo $_SESSION['id'] ;?>" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="mr-2 d-none d-lg-inline text-gray-600 small"><?php if (isset($_SESSION['user'])) { echo $_SESSION['user'] ; } ?> </span> <img class="img-profile rounded-circle img-fluid" src="images/logo.png"> </a> <!-- Dropdown - User Information --> <div class="dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="userDropdown"> <a class="dropdown-item" href="profile.php?id=<?php echo $_SESSION['id'] ;?> "> <i class="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i> Profile </a> <!-- <a class="dropdown-item" href="#"> <i class="fas fa-cogs fa-sm fa-fw mr-2 text-gray-400"></i> Settings </a> --> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#" data-toggle="modal" data-target="#logoutModal"> <i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i> Logout </a> </div> </li> </ul> </nav> <!-- End of Topbar --> <!-- Logout Modal--> <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <form action="logout.inc.php"> <a type="button" class="btn btn-primary" href="logout.inc.php">Logout</a> </form> </div> </div> </div> </div> <file_sep><?php if (isset($_POST['apply'])) { include("includes/db_con.php"); session_start(); $name = $_POST['name']; $surname = $_POST['surname']; $position =$_POST['position']; $leaveType = $_POST['type']; $from = $_POST['from_date']; $to = $_POST['to_date']; $Reasons = $_POST['reason']; $id = $_SESSION['id']; $status = "pending"; $content = "Leave application request"; $today = date("F j, Y, g:i a"); $now =date("Y-m-d H:i:s"); $employee = $_SESSION['user']; $diff = abs(strtotime($to) - strtotime($from)); $years = floor($diff / (365*60*60*24)); $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24)); $duration = $days; $leave_days =21; $query = "SELECT * FROM tbl_leave where emp_id =? AND status=?"; $statement = mysqli_stmt_init($conn); //initialize prepared statement //check if it does not work if (!mysqli_stmt_prepare($statement, $query)) { echo "<script>alert('Server error! please try again later')</script>"; echo "<script>window.open('leave.php','_self')</script>"; } else { mysqli_stmt_bind_param($statement, "is", $id,$status); mysqli_stmt_execute($statement); mysqli_stmt_store_result($statement); $check_results = mysqli_stmt_num_rows($statement); if ($check_results >0) { echo "<script>alert('You Application is Still Pending! You can not apply for another one')</script>"; echo "<script>window.open('track.php','_self')</script>"; } else { $insert = "INSERT INTO tbl_leave (Emp_Name,Emp_surname,Position,type,from_date,to_date,Reason,status,Number_of_Days,leave_days,emp_id,date_applied) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)"; $insert_notification = "INSERT INTO admin_notifications(content,date,employee) values(?,?,?)"; $statement = mysqli_stmt_init($conn); $statement2 = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($statement, $insert) || !mysqli_stmt_prepare($statement2, $insert_notification)) { echo "<script>alert('Server error! Application could not be processed please try again later')</script>"; echo "<script>window.open('leave.php','_self')</script>"; } else { mysqli_stmt_bind_param($statement, "ssssssssiiis", $name, $surname, $position, $leaveType, $from, $to, $Reasons,$status,$duration,$leave_days,$id,$now);//bind data mysqli_stmt_bind_param($statement2, "sss", $content, $today, $employee);//bind data mysqli_stmt_execute($statement); mysqli_stmt_execute($statement2); echo "<script>alert('Your Application has been submitted and is now being Processed')</script>"; echo "<script>window.open('track.php','_self')</script>"; } } } } <file_sep> <!DOCTYPE html> <html lang="en"> <head> <link rel="apple-touch-icon" sizes="57x57" href="../favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="../favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="../favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="../favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="../favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="../favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="../favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="../favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="../favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="../favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="../favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="../favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="../favicons/favicon-16x16.png"> <link rel="manifest" href="../favicons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="../favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JockTech EMS</title> <!-- <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap-material-design.min.css" integrity="<KEY>" crossorigin="anonymous" /> --> <link href="../plugins/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="../css/sb-admin-2.min.css" rel="stylesheet"> <link rel="stylesheet" href="../plugins/datatables/dataTables.bootstrap4.min.css"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <?php include("pages/header.php") ?> <!-- page begin content --> <div class="container-fluid"> <?php include("pages/nav-cards.php") ?> <!-- Page Heading --> <h1 class="h3 mb-2 text-gray-800">Edit / delete </h1> <!-- <p class="mb-4">DataTables is a third party plugin that is used to generate the demo table below. For more information about DataTables, please visit the <a target="_blank" href="https://datatables.net">official DataTables documentation</a>.</p> --> <div class="card shadow mb-4"> <div class="card-header py-3"> <a href="#collapseCard" class="d-block card-header py-3" data-toggle="collapse" role="button" aria-expanded="true" aria-controls="collapseCard"> <h6 class="m-0 font-weight-bold text-primary">Edit / Delete Employee</h6> </a> </div> <div class="collapse show " id="collapseCard"> <div class="card-body collapse show"> <form method="POST"> <div class="form-row"> <div class="form-group col-md-4"> <label for="inputState">Employee</label> <select id="inputState" class="form-control" name="id" required> <option >choose....</option> <?php $get_emp = "SELECT * FROM tbl_employee"; $run = mysqli_query($conn, $get_emp); while ($row = mysqli_fetch_array($run)) { $emp_id = $row['emp_ID']; $name = $row['Name']; $surname = $row['surname']; $Display_name = $name." ".$surname; echo "<option value='$emp_id'>$Display_name</option> "; } ?> </select> </div> </div> <div class="form-group col-md-4"> <button class="btn btn-success " name="edit"> <i class="fas fa-check-circle"></i>Edit</button> </div> <?php if(isset($_POST['edit'])){ $ID = $_POST['id']; $get_emp = "SELECT * FROM tbl_employee where emp_ID ='$ID'"; $run = mysqli_query($conn, $get_emp); while ($row = mysqli_fetch_array($run)) { $emp_id = $row['emp_ID']; $name = $row['Name']; $surname = $row['surname']; $email = $row['EMAIL_ADDRESS']; $idno = $row['ID_NUMBER']; $telno = $row['PHONE_NUMBER']; $gender = $row['GENDER']; $age = $row['AGE']; $position = $row['position']; $startdate = $row['START_DATE']; $salary = $row['SALARY']; $address1 = $row['ADDRESS_1']; $address2 = $row['ADDRESS_2']; $city = $row['CITY']; $zip = $row['ZIP']; } echo ' <div class="col-lg-8"> <div class="card2 card border-0 px-4 py-5 center" > <form method="POST" enctype="multipart/form-data"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4">name</label> <input type="text" class="form-control" value="'.$name.'" name="name" required> </div> <div class="form-group col-md-6"> <label for="inputEmail4">surname</label> <input type="text" class="form-control" value="'.$surname.'" name="surname"> </div> <div class="form-group col-md-6"> <label for="inputEmail4">Email Address</label> <input type="email" class="form-control" value="'.$email.'" name="email" placeholder="Email Address" > </div> <div class="form-group col-md-6"> <label for="inputPassword4">ID Number</label> <input type="number" class="form-control" value="'.$idno.'" name="id_number" readonly> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Phone Number</label> <input type="number" class="form-control" value="'.$telno.'" name="phone_number" placeholder="Phone Number" > </div> <div class="form-group col-md-4"> <label for="inputState">Gender</label> <input id="inputState" class="form-control" value="'.$gender.'" name="gender" readonly> </input> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Age</label> <input type="number" class="form-control" name="age" value="'.$age.'" placeholder="Age" readonly> </div> <div class="form-group col-md-4"> <label for="inputState">Position</label> <input id="inputState" class="form-control" value="'.$position.'" name="position" readonly> </input> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Start Date</label> <input type="date" class="form-control" value="'.$startdate.'" name="start_date" placeholder="Start date" readonly> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Salary</label> <input type="number" class="form-control" value="'.$salary.'" name="salary" placeholder="Salary" readonly> </div> </div> <div class="form-group"> <label for="inputAddress">Address</label> <input type="text" class="form-control" value="'.$address1.'" name="address1" placeholder="1234 Main St"> </div> <div class="form-group"> <label for="inputAddress2">Address 2</label> <input type="text" class="form-control" value="'.$address2.'" name="address2" placeholder="Apartment, studio, or floor"> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputCity">City</label> <input type="text" class="form-control" value="'.$city.'" name="city" > </div> <div class="form-group col-md-2"> <label for="inputZip">Zip</label> <input type="text" class="form-control" name="zip" value="'.$zip.'" > </div> </div> <div class="form-group"> </div> <div class="form-row"> <div class="form-group col-md-2"> <button class="btn btn-success " type="submit" name="update" > <i class="fas fa-plus"></i> Update</button> </div> <div class="form-group col-md-2"> <button class="btn btn-danger " type="submit" name="delete" > <i class="fas fa-times"></i> delete</button> </div> </div> </form> </div> </div>'; } ?> <?php ///delete employee if (isset($_POST['delete'])) { $delete_product = "DELETE FROM tbl_employee where emp_ID ='$emp_id'"; $run_delete = mysqli_query($conn, $delete_product); if ($run_delete) { echo "<script>window.open('edit.php','_self')</script>"; } } ?> <?php ///delete employee if (isset($_POST['update'])) { //fetch data from text fields $id =$_POST['id']; $name = $_POST['name']; $surname = $_POST['surname']; $email = $_POST['email']; $telno = $_POST['phone_number']; $address1 = $_POST['address1']; $address2 = $_POST['address2']; $city = $_POST['city']; $zip = $_POST['zip']; $update_user = "UPDATE tbl_employee SET Name='$name',surname='$surname',EMAIL_ADDRESS='$email',PHONE_NUMBER='$telno',ADDRESS_1='$address1',ADDRESS_2='$address2',CITY='$city',ZIP='$zip' WHERE emp_ID ='$id'"; $run_update = mysqli_query($conn, $update_user); if (!$run_update) { echo"<script language='javascript'>alert('Employee information not updated!')</script>"; echo "<script>window.open('dashboard.php','_self')</script>"; } else{ echo"<script language='javascript'>alert('Employee information updated!')</script>"; echo "<script>window.open('dashboard.php','_self')</script>"; } } ?> </div> </div> <!-- Footer --> <footer class="sticky-footer bg-white"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright &copy; <script> document.write(new Date().getFullYear()); </script> JockTech EMS</span> </div> </div> </footer> <!-- End of Footer --> </div> </div> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Bootstrap core JavaScript--> <script src="../plugins/jquery/jquery.min.js"></script> <script src="../plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="../plugins/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="../js/sb-admin-2.min.js"></script> <!-- Page level plugins --> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <!-- Page level custom scripts --> <script src="../js/demo/chart-area-demo.js"></script> <script src="../js/demo/chart-pie-demo.js"></script> <script src="../js/demo/datatables-demo.js"></script> <script src="../plugins/datatables/jquery.dataTables.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> </body> </html> <?php if(isset($_POST['updatess'])){ include("../includes/db_con.php"); // include_once "edit.php"; //fetch data from text fields $id =$_POST['id']; $name = $_POST['name']; $surname = $_POST['surname']; $email = $_POST['email']; $telno = $_POST['phone_number']; $address1 = $_POST['address1']; $address2 = $_POST['address2']; $city = $_POST['city']; $zip = $_POST['zip']; $update_user = "UPDATE tbl_employee SET Name=?,surname=?,EMAIL_ADDRESS=?,PHONE_NUMBER=?,ADDRESS_1=?,ADDRESS_2=?,CITY=?,ZIP=? WHERE emp_ID =?"; $statement = mysqli_stmt_init($conn); if(!mysqli_stmt_prepare($statement,$update_user)){ echo"<script language='javascript'>alert('Server Error!')</script>"; echo"<script>document.location='edit.php';</script>"; } else{ mysqli_stmt_bind_param($statement,"ssssssssi",$name,$surname,$email,$telno,$address1,$address2,$city,$zip,$id);//bind data mysqli_stmt_execute($statement); echo"<script language='javascript'>alert('Employee info updated!')</script>"; echo"<script>document.location='edit.php';</script>"; } } ?><file_sep><?php $user = 'root'; $pasword = ''; //To be completed if you have set a password to root $database = 'ems_db'; //To be completed to connect to a database. The database must exist. $port = 3308; //Default must be NULL to use default port $conn = new mysqli('localhost', $user, $pasword, $database, $port); if(!$conn){ die("Connection failed: ".mysqli_connect_error()); } <file_sep>-- phpMyAdmin SQL Dump -- version 4.9.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3308 -- Generation Time: Oct 21, 2020 at 07:42 AM -- Server version: 8.0.18 -- PHP Version: 7.4.0 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `ems_db` -- CREATE DATABASE IF NOT EXISTS `ems_db` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `ems_db`; -- -------------------------------------------------------- -- -- Table structure for table `admin_notifications` -- DROP TABLE IF EXISTS `admin_notifications`; CREATE TABLE IF NOT EXISTS `admin_notifications` ( `id` int(11) NOT NULL AUTO_INCREMENT, `content` text, `date` date DEFAULT NULL, `admin_id` int(11) DEFAULT NULL, `employee` text, PRIMARY KEY (`id`), KEY `admin_id` (`admin_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `emp_notifications` -- DROP TABLE IF EXISTS `emp_notifications`; CREATE TABLE IF NOT EXISTS `emp_notifications` ( `id` int(11) NOT NULL AUTO_INCREMENT, `content` text, `date` text, `emp_id` int(11) DEFAULT NULL, `admin` varchar(75) NOT NULL, PRIMARY KEY (`id`), KEY `emp_id` (`emp_id`) ) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=latin1; -- -- Dumping data for table `emp_notifications` -- INSERT INTO `emp_notifications` (`id`, `content`, `date`, `emp_id`, `admin`) VALUES (5, 'New task has been assigned to you', 'October 15, 2020, 3:01 pm', 20037, 'ted gumede'), (4, 'New task has been assigned to you', 'October 15, 2020, 2:52 pm', 20037, 'tebza Manyora'), (6, 'New task ', 'October 15, 2020, 3:05 pm', 20037, 'ted gumede'), (7, 'New task ', 'October 19, 2020, 9:33 am', 20038, 'tebza Manyora'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_admin` -- DROP TABLE IF EXISTS `tbl_admin`; CREATE TABLE IF NOT EXISTS `tbl_admin` ( `ADMIN_ID` int(11) NOT NULL AUTO_INCREMENT, `NAME` varchar(75) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, `SURNAME` varchar(75) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, `ID_NUMBER` char(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, `PHONE_NUMBER` char(13) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, `EMAIL` varchar(75) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, `USERNAME` varchar(75) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, `PASSWORD` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, PRIMARY KEY (`ADMIN_ID`) ) ENGINE=MyISAM AUTO_INCREMENT=20015 DEFAULT CHARSET=latin1; -- -- Dumping data for table `tbl_admin` -- INSERT INTO `tbl_admin` (`ADMIN_ID`, `NAME`, `SURNAME`, `ID_NUMBER`, `PHONE_NUMBER`, `EMAIL`, `USERNAME`, `PASSWORD`) VALUES (20009, 'test', 'test', '2345345345', '0626422830', '<EMAIL>', '<EMAIL>', '$2y$10$jr0ki5x6p2rijDenWm29mO51y414MjWRgTD22koBkzFK.BTS8iJtS'), (20010, 'test', 'test', '542345234', '32423423', '<EMAIL>', '<EMAIL>', '$2y$10$QLBhKFNvz2ukg4GPmFFjeuLcOLxeDYcQ.zXcHkOeSQDH16CS1GMKy'), (20012, 'Teddy', 'Kisala', '78652345677', '0626422830', '<EMAIL>', '<EMAIL>', '$2y$10$KPX5TvANZbP81D3.tomJQO2Jkc3uFpLdQOfoTqvocOVtAz3lqsfjy'), (20013, 'tebza', 'Manyora', '232323', '0626422830', '<EMAIL>', '<EMAIL>', '$2y$10$r82KxAT7yDm1KfgKLqbZvOI5fu0YCFGbqHhvXOIFJAxG4Mk8kaLqG'), (20014, 'billy', 'mike', '123124214', '12421421', '<EMAIL>', '<EMAIL>', '$2y$10$9fEXYk8fB4jpnwq4LHPQY.IRbYuWIe4kgaqAvGTz1uNcBxAMsujCm'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_announcements` -- DROP TABLE IF EXISTS `tbl_announcements`; CREATE TABLE IF NOT EXISTS `tbl_announcements` ( `id` int(11) NOT NULL AUTO_INCREMENT, `Date` varchar(50) NOT NULL, `time` timestamp NOT NULL, `Agenda` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; -- -- Dumping data for table `tbl_announcements` -- INSERT INTO `tbl_announcements` (`id`, `Date`, `time`, `Agenda`) VALUES (7, '23/09/2020', '2020-10-10 11:03:00', 'Permance report due'), (6, '23/09/2020', '2020-10-08 15:19:53', 'meeting on tuesday 30 october at 10pm'), (8, '23/09/2020', '2020-10-19 07:41:33', 'meeting'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_employee` -- DROP TABLE IF EXISTS `tbl_employee`; CREATE TABLE IF NOT EXISTS `tbl_employee` ( `emp_ID` int(11) NOT NULL AUTO_INCREMENT, `Name` varchar(175) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL, `surname` varchar(75) NOT NULL, `EMAIL_ADDRESS` varchar(150) DEFAULT NULL, `ID_NUMBER` char(20) DEFAULT NULL, `PHONE_NUMBER` char(13) DEFAULT NULL, `GENDER` varchar(10) DEFAULT NULL, `AGE` int(11) DEFAULT NULL, `position` varchar(50) NOT NULL, `START_DATE` text, `SALARY` decimal(10,2) DEFAULT NULL, `ADDRESS_1` text, `ADDRESS_2` text, `CITY` text, `ZIP` char(5) DEFAULT NULL, `USERNAME` varchar(75) DEFAULT NULL, `PASSWORD` varchar(75) DEFAULT NULL, PRIMARY KEY (`emp_ID`) ) ENGINE=MyISAM AUTO_INCREMENT=20040 DEFAULT CHARSET=latin1; -- -- Dumping data for table `tbl_employee` -- INSERT INTO `tbl_employee` (`emp_ID`, `Name`, `surname`, `EMAIL_ADDRESS`, `ID_NUMBER`, `PHONE_NUMBER`, `GENDER`, `AGE`, `position`, `START_DATE`, `SALARY`, `ADDRESS_1`, `ADDRESS_2`, `CITY`, `ZIP`, `USERNAME`, `PASSWORD`) VALUES (20037, 'ted', 'gumede', '<EMAIL>', '2342343', '34234', 'Male', 22, 'Mechanic', '2020-10-16', '234324.00', '149 high street Rosettenvilve', '', 'Johannesburg', '2190', '<EMAIL>', '$2y$10$gdTr78AWMwRSIdhVaiuf0uItmGwFeVTCU9ikPg7fgub8wE7pDdPGO'), (20038, 'jared', 'Maake', '<EMAIL>', '3212214', '1241421', 'Male', 22, 'Mechanic', '2020-10-09', '4123421.00', '14212', '', 'Johannesburg', '2190', '<EMAIL>', <PASSWORD>'), (20039, 'ted', 'dev', '<EMAIL>', '213213', '21321', 'Male', 22, 'Cleaner', '2020-10-16', '123123.00', '149 high street Rosettenvilve', '', 'Johannesburg', '2190', '<EMAIL>', '$2y$10$Hof8m8qf2GIlMvlJeLT.b.egH/LJ4pgpbv2vvO4eemdo/6usNHiOa'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_increaserequest` -- DROP TABLE IF EXISTS `tbl_increaserequest`; CREATE TABLE IF NOT EXISTS `tbl_increaserequest` ( `Req_ID` int(11) NOT NULL AUTO_INCREMENT, `Emp_Name` varchar(75) DEFAULT NULL, `Emp_surname` varchar(75) DEFAULT NULL, `Position` varchar(75) DEFAULT NULL, `Start_Date` date DEFAULT NULL, `Current_Salary` int(11) DEFAULT NULL, `emp_ID` int(11) DEFAULT NULL, PRIMARY KEY (`Req_ID`), KEY `emp_ID` (`emp_ID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `tbl_leave` -- DROP TABLE IF EXISTS `tbl_leave`; CREATE TABLE IF NOT EXISTS `tbl_leave` ( `leave_ID` int(11) NOT NULL AUTO_INCREMENT, `Emp_Name` varchar(75) DEFAULT NULL, `Emp_surname` varchar(75) DEFAULT NULL, `Reason` varchar(75) DEFAULT NULL, `Number_of_Days` int(11) DEFAULT NULL, `emp_id` int(11) DEFAULT NULL, PRIMARY KEY (`leave_ID`), KEY `emp_id` (`emp_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `tbl_meetings` -- DROP TABLE IF EXISTS `tbl_meetings`; CREATE TABLE IF NOT EXISTS `tbl_meetings` ( `Meeting_ID` int(11) NOT NULL AUTO_INCREMENT, `Subject` varchar(75) DEFAULT NULL, `Meeting_Date` date DEFAULT NULL, `Start_time` time DEFAULT NULL, `End_time` time DEFAULT NULL, PRIMARY KEY (`Meeting_ID`) ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; -- -- Dumping data for table `tbl_meetings` -- INSERT INTO `tbl_meetings` (`Meeting_ID`, `Subject`, `Meeting_Date`, `Start_time`, `End_time`) VALUES (1, NULL, '2020-10-20', '12:23:00', '13:23:00'), (2, 'staff', '2020-10-21', '14:24:00', '15:26:00'), (3, 'new email and pass', '2020-10-20', '12:36:00', '13:36:00'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_report` -- DROP TABLE IF EXISTS `tbl_report`; CREATE TABLE IF NOT EXISTS `tbl_report` ( `Report_ID` int(11) NOT NULL AUTO_INCREMENT, `Report_name` varchar(75) DEFAULT NULL, `Emp_Name` varchar(75) DEFAULT NULL, `Emp_surname` varchar(75) DEFAULT NULL, `Start_Date` date DEFAULT NULL, `Salary` int(11) DEFAULT NULL, `Position` varchar(75) DEFAULT NULL, `Job_Description` varchar(120) DEFAULT NULL, `Goals` varchar(75) DEFAULT NULL, `Comments` varchar(275) DEFAULT NULL, `emp_ID` int(11) DEFAULT NULL, PRIMARY KEY (`Report_ID`), KEY `emp_ID` (`emp_ID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `tbl_tasks` -- DROP TABLE IF EXISTS `tbl_tasks`; CREATE TABLE IF NOT EXISTS `tbl_tasks` ( `task_ID` int(11) NOT NULL AUTO_INCREMENT, `task_name` varchar(250) DEFAULT NULL, `task_date` date DEFAULT NULL, `deadline` date DEFAULT NULL, `duration` text NOT NULL, `employee` int(11) DEFAULT NULL, `description` text, `progress` int(11) NOT NULL, PRIMARY KEY (`task_ID`), KEY `employee` (`employee`) ) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=latin1; -- -- Dumping data for table `tbl_tasks` -- INSERT INTO `tbl_tasks` (`task_ID`, `task_name`, `task_date`, `deadline`, `duration`, `employee`, `description`, `progress`) VALUES (14, 'Hose removal', '2020-10-22', '2020-10-30', '8', 20037, 'Remove current hose', 0), (13, 'Hose replacement', '2020-10-14', '2020-10-16', '2', 20037, 'Replace old Hose and install new ones ', 0), (12, 'Pipe intallation', '2020-10-22', '2020-10-16', '6', 20037, 'Replace old Pipes and install new ones ', 0), (15, 'bob', '2020-10-21', '2020-10-15', '6', 20038, 'test pipes', 0); -- -------------------------------------------------------- -- -- Table structure for table `tbl_timesheet` -- DROP TABLE IF EXISTS `tbl_timesheet`; CREATE TABLE IF NOT EXISTS `tbl_timesheet` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `Date` date DEFAULT NULL, `Start_Time` text, `Finish_Time` text, `Regular_Hours` int(11) DEFAULT NULL, `Overtime_Hours` int(11) DEFAULT NULL, `Totalworked_hours` int(11) DEFAULT NULL, `emp_ID` int(11) DEFAULT NULL, PRIMARY KEY (`ID`), KEY `emp_ID` (`emp_ID`) ) ENGINE=MyISAM AUTO_INCREMENT=390 DEFAULT CHARSET=latin1; -- -- Dumping data for table `tbl_timesheet` -- INSERT INTO `tbl_timesheet` (`ID`, `Date`, `Start_Time`, `Finish_Time`, `Regular_Hours`, `Overtime_Hours`, `Totalworked_hours`, `emp_ID`) VALUES (387, '2020-10-22', '16:18', '19:18', 3, 3, 6, 20037), (388, '2020-10-20', '16:43', '20:43', 4, 4, 8, 20038), (389, '2020-10-23', '16:44', '22:44', 6, 0, 6, 20037); DELIMITER $$ -- -- Events -- DROP EVENT `prune_table`$$ CREATE DEFINER=`root`@`localhost` EVENT `prune_table` ON SCHEDULE EVERY 2 WEEK STARTS '2020-10-08 18:31:04' ON COMPLETION NOT PRESERVE ENABLE DO DELETE FROM tbl_announcements WHERE time < NOW() - 120$$ DELIMITER ; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php include("../includes/db_con.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <link rel="apple-touch-icon" sizes="57x57" href="../favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="../favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="../favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="../favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="../favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="../favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="../favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="../favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="../favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="../favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="../favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="../favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="../favicons/favicon-16x16.png"> <link rel="manifest" href="../favicons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="../favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JockTech EMS</title> <!-- <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap-material-design.min.css" integrity="<KEY>" crossorigin="anonymous" /> --> <link href="../plugins/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="../css/sb-admin-2.min.css" rel="stylesheet"> <link rel="stylesheet" href="../plugins/datatables/dataTables.bootstrap4.min.css"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <?php include("pages/header.php") ?> <!-- page begin content --> <div class="container-fluid"> <?php include("pages/nav-cards.php") ?> <!-- Page Heading --> <h1 class="h3 mb-2 text-gray-800">Company Employees</h1> <!-- <p class="mb-4">DataTables is a third party plugin that is used to generate the demo table below. For more information about DataTables, please visit the <a target="_blank" href="https://datatables.net">official DataTables documentation</a>.</p> --> <!-- DataTales Example --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Employees</h6> <br> </div> <div class="form-row"> <div class="form-group col-md-2"> <button class="btn btn-primary " data-toggle="modal" data-target="#AddEmployee"> <i class="fas fa-plus"></i> add Employee</button> </div> <div class="form-group col-md-2"> <a class="btn btn-success " href="edit.php"> <i class="fas fa-plus"></i> edit Employee</a> </div> <div class="form-group col-md-2"> <button class="btn btn-warning " data-toggle="modal" data-target="#sendmail"> <i class="fas fa-envelope"></i> Send Mail</button> </div> </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>ID Number</th> <th>Name</th> <th>Surname</th> <th>Position</th> <th>Age</th> <th>gender</th> <th>Phone</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tbody> <?php $getEmployees = "SELECT * FROM tbl_employee"; $run = mysqli_query($conn, $getEmployees); while ($row = mysqli_fetch_array($run)) { $name = $row['Name']; $surname = $row['surname']; $id_no = $row['ID_NUMBER']; $position = $row['position']; $age = $row['AGE']; $startdate = $row['START_DATE']; $salary = $row['SALARY']; $phone = $row['PHONE_NUMBER']; $gender = $row['GENDER']; echo " <tr> <td> $id_no </td> <td> $name </td> <td> $surname </td> <td> $position </td> <td> $age</td> <td> $gender </td> <td> $phone </td> <td> $startdate </td> <td> R $salary </td> </tr>"; } ?> </tbody> </table> </div> </div> </div> </div> </div> <!-- Footer --> <footer class="sticky-footer bg-white"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright &copy; <script> document.write(new Date().getFullYear()); </script> JockTech EMS</span> </div> </div> </footer> <!-- End of Footer --> </div> </div> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- add employee modal --> <!-- Modal --> <div class="modal fade" id="AddEmployee" tabindex="-1" role="dialog" aria-labelledby="NewEmployeeCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="NewEmployeeModalLongTitle">Add New Employee</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="POST" enctype="multipart/form-data"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4">name</label> <input type="text" class="form-control" id="inputEmail4" name="name" placeholder="<NAME>" required> </div> <div class="form-group col-md-6"> <label for="inputEmail4">surname</label> <input type="text" class="form-control" id="inputEmail4" name="surname" placeholder="Surname" required> </div> <div class="form-group col-md-6"> <label for="inputEmail4">Email Address</label> <input type="email" class="form-control" id="inputEmail4" name="email" placeholder="Email Address" required> </div> <div class="form-group col-md-6"> <label for="inputPassword4">ID Number</label> <input type="number" class="form-control" id="inputPassword4" name="id_number" placeholder="ID Number" required> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Phone Number</label> <input type="number" class="form-control" id="inputPassword4" name="phone_number" placeholder="Phone Number" required> </div> <div class="form-group col-md-4"> <label for="inputState">Gender</label> <select id="inputState" class="form-control" name="gender" required> <option ></option> <option>Male</option> <option>Female</option> </select> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Age</label> <input type="number" class="form-control" name="age" id="inputPassword4" placeholder="Age" required> </div> <div class="form-group col-md-4"> <label for="inputState">Position</label> <select id="inputState" class="form-control" name="position"> <option></option> <option>Mechanic</option> <option>Cleaner</option> <option>Technician</option> <option>Driver</option> </select> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Start Date</label> <input type="date" class="form-control" id="inputPassword4" name="start_date" placeholder="Start date" required> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Salary</label> <input type="number" class="form-control" id="inputPassword4" name="salary" placeholder="Salary" required> </div> </div> <div class="form-group"> <label for="inputAddress">Address</label> <input type="text" class="form-control" id="inputAddress" name="address1" placeholder="1234 Main St"> </div> <div class="form-group"> <label for="inputAddress2">Address 2</label> <input type="text" class="form-control" id="inputAddress2" name="address2" placeholder="Apartment, studio, or floor"> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputCity">City</label> <input type="text" class="form-control" id="inputCity" name="city" required> </div> <div class="form-group col-md-2"> <label for="inputZip">Zip</label> <input type="text" class="form-control" name="zip" id="inputZip" required> </div> </div> <div class="form-group"> </div> <button type="submit" name="add_emp" class="btn btn-primary">Add</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- send modal --> <!-- Modal --> <div class="modal fade" id="sendmail" tabindex="-1" role="dialog" aria-labelledby="NewEmployeeCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="NewEmployeeModalLongTitle">Send mail</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="POST" enctype="multipart/form-data"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputState">email address</label> <select id="inputState" class="form-control" name="email" required> <option></option> <?php $get_emp = "SELECT * FROM tbl_employee"; $run = mysqli_query($conn, $get_emp); while ($row = mysqli_fetch_array($run)) { $emp_id = $row['emp_ID']; $name = $row['Name']; $surname = $row['surname']; $email = $row['EMAIL_ADDRESS']; $Display_name = $name . " " . $surname; echo " <option value='$email'>$email</option> "; $get_emp = "SELECT * FROM tbl_employee where EMAIL_ADDRESS ='$email'"; $run_QUERY = mysqli_query($conn, $get_emp); while ($row = mysqli_fetch_array($run_QUERY)) { $Username = $row['USERNAME']; $Password = "<PASSWORD>"; $name = $row['Name']; $surname = $row['surname']; $Display_name = $name . " " . $surname; } } ?> </select> </div> <div class="form-group col-md-12"> <label for="inputEmail4">Subject</label> <input type="text" class="form-control" name="subject" required> </div> </div> <div class="form-group"> </div> <button type="submit" name="send-email" class="btn btn-primary">Send </button> </form> <?php // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; if (isset($_POST['send-email'])) { $subject = $_POST['subject']; $admin = $_SESSION['user']; // Load Composer's autoloader require 'vendor/autoload.php'; // Instantiation and passing `true` enables exceptions $mail = new PHPMailer(true); try { //Server settings //$mail->SMTPDebug = 2; //SMTP::DEBUG_SERVER; // Enable verbose debug output $mail->isSMTP(); // Send using SMTP $mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = '<EMAIL>'; // SMTP username $mail->Password = <PASSWORD>'; // SMTP password $mail->SMTPSecure = 'tls'; //PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged $mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above //Recipients $mail->setFrom('<EMAIL>', $admin); $mail->addAddress($email); // Add a recipient $body = '<table align="center" border="0" cellpadding="0" cellspacing="0" width="600" style="border: 1px solid #cccccc; border-collapse: collapse;"> <tr> <td style="padding: 10px 0 30px 0;"> <table align="center" border="0" cellpadding="0" cellspacing="0" width="600" style="border: 1px solid #cccccc; border-collapse: collapse;"> <tr> <td align="center" bgcolor="#70bbd9" style="padding: 40px 0 30px 0; color: #153643; font-size: 28px; font-weight: bold; font-family: Arial, sans-serif;"> <img src="https://socpsy.boun.edu.tr/sites/socpsy.boun.edu.tr/files/unnamed.png" alt="Welcome" width="300" height="230" style="display: block;" /> </td> </tr> <tr> <td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td style="color: #153643; font-family: Arial, sans-serif; font-size: 24px;"> <b>Hey there ' . $Display_name . '</b> </td> </tr> <tr> <td style="padding: 20px 0 30px 0; color: #153643; font-family: Arial, sans-serif; font-size: 16px; line-height: 20px;"> I would like to welcome you to SXM Trading. We are excited that you have agreed to join us. I believe that you are mutually excited about your new employment with Us. <br> <br> Your username is ' . $Username . ' and the default password is "<PASSWORD>" <br> use these credentials to log into the system <br> Use this <a href ="http://jockteck.hstn.me/register.php">Link </a> to register a new password of your choice </td> </tr> </table> </td> </tr> <tr> </tr> </table> </td> </tr> </table> </td> </tr> </table>'; // Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = $subject; $mail->Body = $body; $mail->AltBody = "username is $Username and the defaults password is <PASSWORD>"; $mail->send(); echo "<script>alert('message sent')</script>"; echo "<script>window.open('employees.php','_self')</script>"; } catch (Exception $e) { //echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; echo "<script>alert('eMessage could not be sent. Mailer Error:'{$mail->ErrorInfo}')</script>"; echo "<script>window.open('employees.php','_self')</script>"; } } ?> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="../plugins/jquery/jquery.min.js"></script> <script src="../plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="../plugins/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="../js/sb-admin-2.min.js"></script> <!-- Page level plugins --> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <!-- Page level custom scripts --> <script src="../js/demo/chart-area-demo.js"></script> <script src="../js/demo/chart-pie-demo.js"></script> <script src="../js/demo/datatables-demo.js"></script> <script src="../plugins/datatables/jquery.dataTables.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> </body> </html> <?php if (isset($_POST['add_emp'])) { include("../includes/db_con.php"); //fetch data from text fields $domain = "@sxm.co.za"; $name = $_POST['name']; $surname = $_POST['surname']; $email = $_POST['email']; $ID_No = $_POST['id_number']; $Phone_No = $_POST['phone_number']; $gender = $_POST['gender']; $age = $_POST['age']; $position = $_POST['position']; $salary = $_POST['salary']; $address1 = $_POST['address1']; $address2 = $_POST['address2']; $city = $_POST['city']; $zip = $_POST['zip']; $startdate = $_POST['start_date']; $Password = "<PASSWORD>"; //use prepared statements to create queries // check if user already exists $check_user = "SELECT EMAIL_ADDRESS FROM tbl_employee WHERE EMAIL_ADDRESS =?"; $statement = mysqli_stmt_init($conn); //initialize prepared statement //check if it does not work if (!mysqli_stmt_prepare($statement, $check_user)) { echo "<script>alert('Server error! please try again later')</script>"; echo "<script>window.open('employees.php','_self')</script>"; } else { mysqli_stmt_bind_param($statement, "s", $email); mysqli_stmt_execute($statement); mysqli_stmt_store_result($statement); $check_results = mysqli_stmt_num_rows($statement); if ($check_results > 0) { echo "<script>alert('Employee with this email address already exists!')</script>"; echo "<script>window.open('employees.php','_self')</script>"; } else { //insert users $pass_hash = password_hash($Password, PASSWORD_DEFAULT); $random = rand(1, 100); $Username = strtolower($name . $surname . $random . $domain); $insert_user = "INSERT INTO tbl_employee(Name,surname,EMAIL_ADDRESS,ID_NUMBER,PHONE_NUMBER,GENDER,AGE,position,START_DATE,SALARY,ADDRESS_1,ADDRESS_2,CITY,ZIP,USERNAME,PASSWORD) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; $statement = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($statement, $insert_user)) { echo "<script>alert('Server error! please try again later!')</script>"; echo "<script>window.open('employees.php','_self')</script>"; } else { mysqli_stmt_bind_param($statement, "ssssssississssss", $name, $surname, $email, $ID_No, $Phone_No, $gender, $age, $position, $startdate, $salary, $address1, $address2, $city, $zip, $Username, $pass_hash); //bind data mysqli_stmt_execute($statement); echo "<script>alert('employee successfully added')</script>"; // mail($to_email,$subject,$message,$headers); echo "<script>window.open('employees.php','_self')</script>"; } } } } ?><file_sep> <?php //copyright jocktech inc 2020 //check if the user accessed to this script if(isset($_POST['update'])){ // include("./includes/db_con.php"); // include_once "edit.php"; //fetch data from text fields $id =$_POST['id']; $name = $_POST['name']; $surname = $_POST['Surname']; $email = $_POST['email']; $telno = $_POST['phone_number']; $address1 = $_POST['address1']; $address2 = $_POST['address2']; $city = $_POST['city']; $zip = $_POST['zip']; $update_user = "UPDATE tbl_employee SET Name=?,surname=?,EMAIL_ADDRESS=?,PHONE_NUMBER=?,ADDRESS_1=?,ADDRESS_2=?,CITY=?,ZIP=? WHERE emp_ID =?"; $statement = mysqli_stmt_init($conn); if(!mysqli_stmt_prepare($statement,$update_user)){ echo"<script language='javascript'>alert('Server Error!')</script>"; echo"<script>document.location='edit.php';</script>"; } else{ mysqli_stmt_bind_param($statement,"ssssssssi",$name,$surname,$email,$telno,$address1,$address2,$city,$zip,$id);//bind data mysqli_stmt_execute($statement); echo"<script language='javascript'>alert('Employee info updated!')</script>"; echo"<script>document.location='edit.php';</script>"; } mysqli_stmt_close($statement); //close statement mysqli_stmt_close($conn); //close connection } else{ //send user to register page if they tried to header("Location: dashboard.php"); exit(); }<file_sep><?php include("includes/db_con.php"); function getEmpNumber(){ global $conn; $getCount = "SELECT * FROM tbl_employee"; $run = mysqli_query($conn,$getCount); $count = mysqli_num_rows($run); if($count==0){ echo ' <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Number of Employees</div> <div class="h5 mb-0 font-weight-bold text-gray-800">0</div>'; } else{ echo '<div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Number of Employees</div> <div class="h5 mb-0 font-weight-bold text-gray-800"> '.$count.'</div>'; } } function getAnnouncements(){ global $conn; $getCount = "SELECT * FROM tbl_announcements"; $run = mysqli_query($conn,$getCount); $count = mysqli_num_rows($run); if($count==0){ echo ' <div class="h5 mb-0 font-weight-bold text-gray-800">no announcements have been posted</div>'; } else{ while($row = mysqli_fetch_array($run)){ $agenda = $row['Agenda']; echo " <div class='card-body'> $agenda </div>"; } } } function getTasksNumber(){ global $conn; $id = $_SESSION['id']; $getCount = "SELECT * FROM tbl_Tasks where employee = '$id' and status='inprogress'"; $run = mysqli_query($conn,$getCount); $count = mysqli_num_rows($run); if($count==0){ echo ' <div class="h5 mb-0 mr-3 font-weight-bold text-gray-800">0</div>'; } else{ echo ' <div class="h5 mb-0 mr-3 font-weight-bold text-gray-800"> '.$count.'</div>'; } } function getTasks(){ global $conn; $id = $_SESSION['id']; $getCount = "SELECT * FROM tbl_tasks where employee ='$id'"; $run = mysqli_query($conn,$getCount); $count = mysqli_num_rows($run); if($count==0){ echo ' <h4 class="small font-weight-bold">No Tasks have been assigned to you yet </h4>'; } else{ while($row = mysqli_fetch_array($run)){ $task_name = $row['task_name']; $progress = $row['progress']; echo ' <div class="card-body"> <h4 class="small font-weight-bold">'.$task_name.' <span class="float-right">'.$progress.'%</span></h4> <div class="progress mb-4"> <div class="progress-bar bg-success" role="progressbar" style="width: '.$progress.'%" aria-valuenow="'.$progress.'" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> '; } } } function getLeaveDays(){ global $conn; session_start(); $id = $_SESSION['id']; $getCount = "SELECT * FROM tbl_leave where emp_id ='$id'"; $run = mysqli_query($conn,$getCount); $row = mysqli_fetch_array($run); $number = $row['leave_days']; echo ' <div class="h5 mb-0 mr-3 font-weight-bold text-gray-800"> '.$number.'</div>'; } <file_sep><?php include("includes/db_con.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <link rel="apple-touch-icon" sizes="57x57" href="favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="favicons/favicon-16x16.png"> <link rel="manifest" href="../favicons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JockTech EMS</title> <!-- <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap-material-design.min.css" integrity="<KEY>" crossorigin="anonymous" /> --> <link href="plugins/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="css/sb-admin-2.min.css" rel="stylesheet"> <link rel="stylesheet" href="plugins/datatables/dataTables.bootstrap4.min.css"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <?php include("pages/header.php") ?> <!-- page begin content --> <div class="container-fluid"> <?php include("pages/nav-cards.php") ?> <div class="card shadow mb-4"> <div class="card-header py-3"> <a href="#collapseCard" class="d-block card-header py-3" data-toggle="collapse" role="button" aria-expanded="true" aria-controls="collapseCard"> <h6 class="m-0 font-weight-bold text-primary">My Reports</h6> </a> </div> <div class="collapse show" id="collapseCard"> <div class="card-body collapse show"> <div class="container"> <?php $id = $_SESSION['id']; $select = "SELECT * FROM tbl_report WHERE emp_ID = '$id'"; $run = mysqli_query($conn,$select); while($row=mysqli_fetch_array($run)){ $report = $row['Report_name']; $goals = $row['Goals']; $areas = $row['improvement_area']; $comment = $row['Comments']; echo ' <form> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4">Report Name</label> <input class="form-control" readonly value ='.$report.'> </div> </div> <div class="form-group"> <label>Goals Achieved</label> <textarea class="form-control" readonly rows="3" >'.$goals.'</textarea> </div> <div class="form-group"> <label >Areas To Improve</label> <textarea class="form-control" readonly rows="3" >'.$areas.'</textarea> </div> <div class="form-group"> <label >Comments</label> <textarea class="form-control" readonly rows="3" >'.$comment.'</textarea> </div> <div class="form-row"> </div> </form> '; } ?> </div> </div> </div> </div> </div> <!-- Footer --> <footer class="sticky-footer bg-white"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright &copy; <script> document.write(new Date().getFullYear()); </script> JockTech EMS</span> </div> </div> </footer> <!-- End of Footer --> </div> </div> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Bootstrap core JavaScript--> <script src="plugins/jquery/jquery.min.js"></script> <script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="plugins/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="js/sb-admin-2.min.js"></script> <!-- Page level plugins --> <script src="plugins/chart.js/Chart.bundle.min.js"></script> <script src="plugins/datatables/dataTables.bootstrap4.min.js"></script> <script src="plugins/chart.js/Chart.bundle.min.js"></script> <!-- Page level custom scripts --> <script src="js/demo/chart-area-demo.js"></script> <script src="js/demo/chart-pie-demo.js"></script> <script src="js/demo/datatables-demo.js"></script> <script src="plugins/datatables/jquery.dataTables.min.js"></script> <script src="plugins/datatables/dataTables.bootstrap4.min.js"></script> </body> </html> <file_sep> <!DOCTYPE html> <html lang="en"> <head> <link rel="apple-touch-icon" sizes="57x57" href="favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="favicons/favicon-16x16.png"> <link rel="manifest" href="../favicons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JockTech EMS</title> <!-- <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap-material-design.min.css" integrity="<KEY>" crossorigin="anonymous" /> --> <link href="plugins/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="css/sb-admin-2.min.css" rel="stylesheet"> <link rel="stylesheet" href="css/profile.css"> <link rel="stylesheet" href="plugins/datatables/dataTables.bootstrap4.min.css"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <?php include("pages/header.php") ?> <!-- page begin content --> <div class="container-fluid"> <?php include("pages/nav-cards.php") ?> <!-- Page Heading --> <h1 class="h3 mb-2 text-gray-800">Profile</h1> <!-- <p class="mb-4">DataTables is a third party plugin that is used to generate the demo table below. For more information about DataTables, please visit the <a target="_blank" href="https://datatables.net">official DataTables documentation</a>.</p> --> <!-- DataTales Example --> <div class="card shadow mb-4"> <div class="container emp-profile"> <form method="post"> <div class="row"> <div class="col-md-4"> <div class="profile-img img-fluid"> <img src="images/logo.png" alt=""> <div class="file btn btn-lg btn-primary"> <input type="file" name="file"/> </div> </div> </div> <?php $id = $_GET['id']; $query = "SELECT * FROM tbl_employee where emp_ID ='$id'"; $run = mysqli_query($conn,$query); while($row = mysqli_fetch_array($run)){ $name = $row['Name']; $SURNAME = $row['surname']; $email = $row['EMAIL_ADDRESS']; $phone = $row['PHONE_NUMBER']; $ID = $row['ID_NUMBER']; $username = $row['USERNAME']; $position = $row['position']; $salary = $row['SALARY']; $benefits = "Medical Aids ,Car Allowance"; $start = $row['START_DATE']; // $name = $row['NAME']; } ?> <div class="col-md-6"> <div class="profile-head"> <h5> <?php echo $name ." ". $SURNAME ; ?> </h5> <h6> <?php echo $position; ?> </h6> <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">About</a> </li> <li class="nav-item"> <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profiles" role="tab" aria-controls="profile" aria-selected="false">Personal</a> </li> </ul> </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="profile-work"> </div> </div> <div class="col-md-8"> <div class="tab-content profile-tab" id="myTabContent"> <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab"> <div class="row"> <div class="col-md-6"> <label>Employee ID:</label> </div> <div class="col-md-6"> <p><?php echo $_SESSION['id']; ?></p> </div> </div> <div class="row"> <div class="col-md-6"> <label>Name</label> </div> <div class="col-md-6"> <p> <?php echo $name ?></p> </div> </div> <div class="row"> <div class="col-md-6"> <label>Surname</label> </div> <div class="col-md-6"> <p> <?php echo $SURNAME ; ?></p> </div> </div> <div class="row"> <div class="col-md-6"> <label>Email</label> </div> <div class="col-md-6"> <p> <?php echo $email?></p> </div> </div> <div class="row"> <div class="col-md-6"> <label>Phone</label> </div> <div class="col-md-6"> <p> <?php echo $phone?></p> </div> </div> </div> <div class="tab-pane fade" id="profiles" role="tabpanel" aria-labelledby="profile-tab"> <div class="row"> <div class="col-md-6"> <label>ID Number</label> </div> <div class="col-md-6"> <p> <?php echo $ID?></p> </div> </div> <div class="row"> <div class="col-md-6"> <label>Username</label> </div> <div class="col-md-6"> <p> <?php echo $username?></p> </div> </div> <div class="row"> <div class="col-md-6"> <label>Benefits</label> </div> <div class="col-md-6"> <p> <?php echo $benefits?></p> </div> </div> <div class="row"> <div class="col-md-6"> <label>Start date</label> </div> <div class="col-md-6"> <p> <?php echo $start; ?> </p> </div> </div> <div class="row"> <div class="col-md-6"> <label>Salary</label> </div> <div class="col-md-6"> <p> <?php echo "R". $salary; ?> </p> </div> </div> <div class="row"> </div> </div> </div> </div> </div> </form> </div> </div> </div> </div> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Bootstrap core JavaScript--> <script src="plugins/jquery/jquery.min.js"></script> <script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="plugins/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="js/sb-admin-2.min.js"></script> <!-- Page level plugins --> <script src="plugins/chart.js/Chart.bundle.min.js"></script> <script src="plugins/datatables/dataTables.bootstrap4.min.js"></script> <script src="plugins/chart.js/Chart.bundle.min.js"></script> <!-- Page level custom scripts --> <script src="js/demo/chart-area-demo.js"></script> <script src="js/demo/chart-pie-demo.js"></script> <script src="js/demo/datatables-demo.js"></script> <script src="plugins/datatables/jquery.dataTables.min.js"></script> <script src="plugins/datatables/dataTables.bootstrap4.min.js"></script> </body> </html> <file_sep><?php if (isset($_POST['create'])) { include("../includes/db_con.php"); include_once "Timesheet.php"; $date = $_POST['date']; $start_time = $_POST['start_time']; $end_time = $_POST['end_time'] ; $diff = (int) $end_time - (int) $start_time; $overtime = $_POST['overtime']; $totalhours = $diff + $overtime; $regularhours = $diff; $emp_id = $_POST['name']; $query = "SELECT * FROM tbl_timesheet"; $statement = mysqli_stmt_init($conn); //initialize prepared statement //check if it does not work if (!mysqli_stmt_prepare($statement, $query)) { echo"<script language='javascript'>alert('Server Error!')</script>"; echo"<script>document.location='Timesheet.php';</script>"; } else { $insert = "INSERT INTO tbl_timesheet (Date,Start_Time,Finish_Time,Regular_Hours,Overtime_Hours,Totalworked_hours,emp_ID) VALUES(?,?,?,?,?,?,?)"; $statement = mysqli_stmt_init($conn); // $getTasks = "SELECT * FROM tbl_employee WHERE emp_ID = '$emp_id'"; // $run = mysqli_query($conn,$getTasks); // $row = mysqli_fetch_array($run); // $name = $row['Name']; if (!mysqli_stmt_prepare($statement, $insert)) { echo"<script language='javascript'>alert('Server Error!')</script>"; echo"<script>document.location='Timesheet.php';</script>"; } else { mysqli_stmt_bind_param($statement, "sssiiii", $date, $start_time, $end_time, $regularhours, $overtime, $totalhours, $emp_id);//bind data mysqli_stmt_execute($statement); echo"<script language='javascript'>alert('Timesheet Created')</script>"; echo"<script>document.location='Timesheet.php';</script>"; } } } ?><file_sep> <?php include("./functions/functions.php"); ?> <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h1 class="h3 mb-0 text-gray-800">Dashboard</h1> </div> <!-- Content Row --> <div class="row"> <!-- Number of employees Card Example --> <div class="col-xl-3 col-md-6 mb-4"> <div class="card border-left-primary shadow h-100 py-2"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <?php getEmpNumber(); ?> </div> <div class="col-auto"> <i class="fas fa-users fa-2x text-gray-300"></i> </div> </div> </div> </div> </div> <!-- Faults Card Example --> <div class="col-xl-3 col-md-6 mb-4"> <div class="card border-left-success shadow h-100 py-2"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Salary increase request</div> <?php getSalaryRequestsNumber(); ?> </div> <div class="col-auto"> <i class="fas fa-exclamation-circle fa-2x text-gray-300"></i> </div> </div> </div> </div> </div> <!-- Task Card Example --> <div class="col-xl-3 col-md-6 mb-4"> <div class="card border-left-info shadow h-100 py-2"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Tasks</div> <div class="row no-gutters align-items-center"> <div class="col-auto"> <?php getTasksNumber(); ?> </div> </div> </div> <div class="col-auto"> <i class="fas fa-clipboard-list fa-2x text-gray-300"></i> </div> </div> </div> </div> </div> <!-- Leave Requests Card Example --> <div class="col-xl-3 col-md-6 mb-4"> <div class="card border-left-warning shadow h-100 py-2"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Leave Requests</div> <?php getLeaveNumber(); ?> </div> <div class="col-auto"> <i class="fas fa-comments fa-2x text-gray-300"></i> </div> </div> </div> </div> </div> </div> <!-- Content Row --><file_sep><!DOCTYPE html> <html lang="en"> <head> <link rel="apple-touch-icon" sizes="57x57" href="../favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="../favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="../favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="../favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="../favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="../favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="../favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="../favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="../favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="../favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="../favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="../favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="../favicons/favicon-16x16.png"> <link rel="manifest" href="../favicons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="../favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>JockTech EMS</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap-material-design.min.css" integrity="<KEY>" crossorigin="anonymous" /> --> <link rel="stylesheet" href="../css/styles.css"> <script src="https://kit.fontawesome.com/47ecf318ef.js" crossorigin="anonymous"></script> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script> </head> <body> <div id="top" class="container-fluid"> <div class="row"> <div class="col-md-12"> <h2>JockTech Employee Management System</h2> <div class="spinner-grow " role="status"> </div> <div class="spinner-grow text-primary" role="status"> <span class="sr-only">Loading...</span> </div> <div class="spinner-grow text-success" role="status"> <span class="sr-only">Loading...</span> </div> <div class="spinner-grow text-danger" role="status"> <span class="sr-only">Loading...</span> </div> <div class="spinner-grow text-warning" role="status"> <span class="sr-only">Loading...</span> </div> </div> </div> </div> <div class="container-fluid px-1 px-md-5 px-lg-1 px-xl-5 py-5 mx-auto"> <div class="card card0 border-0"> <div class="row d-flex"> <div class="col-lg-6"> <div class="card1 pb-5"> <div class="row"> <img src="../images/logo.png" class=" img-fluid"> </div> <div class="row px-3 justify-content-center mt-4 mb-5 border-line"> <img src="../images/animation_640_kfl01jel.gif" class="img-fluid image"> </div> </div> </div> <div class="col-lg-6"> <div class="card2 card border-0 px-4 py-5"> <?php if(isset($_GET['error'])){ if(isset($_GET['error']) =="nouser"){ echo ' <h5 class ="text-danger">Invalid Username or Password</h5>'; } else if(isset($_GET['error']) =="wrongpassword"){ echo ' <h5 class ="text-danger">Invalid Password</h5>'; } } ?> <form action="login.inc.php" method="POST"> <div class="form-group"> <span >Email address</span> <input type="email" name="username" class="form-control" placeholder="<EMAIL>" required > </div> <div class="form-group"> <span >Password</span> <input type="<PASSWORD>" name="password" class="form-control" required placeholder="Enter password"> </div> <button type="submit" name="login-btn" class="btn btn-warning btn-lg btn-block">Login</button> </form> <div class="regiater-btn btn"> <a href="register.php">Register</a> </div> </div> </div> </div> <div class="bg-blue py-4"> <div class="row px-3"> <small class="ml-4 ml-sm-5 mb-2">Copyright &copy; <script> document.write(new Date().getFullYear()); </script>. All rights reserved.</small> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"> </script> <!-- <script src="https://unpkg.com/[email protected]/dist/umd/popper.js" integrity="<KEY>" crossorigin="anonymous"> </script> --> <!-- <script src="https://unpkg.com/[email protected]/dist/js/bootstrap-material-design.js" integrity="<KEY>" crossorigin="anonymous"> </script> --> <!-- <script> $(document).ready(function () { $('body').bootstrapMaterialDesign(); }); </script> --> </body> </html><file_sep><!DOCTYPE html> <html lang="en"> <head> <link rel="apple-touch-icon" sizes="57x57" href="../favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="../favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="../favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="../favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="../favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="../favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="../favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="../favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="../favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="../favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="../favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="../favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="../favicons/favicon-16x16.png"> <link rel="manifest" href="../favicons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="../favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JockTech EMS</title> <!-- <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap-material-design.min.css" integrity="<KEY>" crossorigin="anonymous" /> --> <link href="../plugins/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="../css/sb-admin-2.min.css" rel="stylesheet"> <link rel="stylesheet" href="../plugins/datatables/dataTables.bootstrap4.min.css"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <?php include("pages/header.php") ?> <!-- page begin content --> <div class="container-fluid"> <?php include("pages/nav-cards.php") ?> <!-- Page Heading --> <h1 class="h3 mb-2 text-gray-800">Leave Requests</h1> <!-- <p class="mb-4">DataTables is a third party plugin that is used to generate the demo table below. For more information about DataTables, please visit the <a target="_blank" href="https://datatables.net">official DataTables documentation</a>.</p> --> <!-- DataTales Example --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Employees</h6> </div> <div class="card-body"> <div class="form-row"> <div class="form-group col-md-2"> <button class="btn btn-success " data-toggle="modal" data-target="#Approve"> <i class="fas fa-check-circle"></i> Approve / Decline</button> </div> </div> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Name</th> <th>Surname</th> <th>Position</th> <th>Leave Type</th> <th>From</th> <th>To </th> <th>Reason</th> <th>Duration</th> </tr> </thead> <tbody> <?php $status = "pending"; $getLeaves = "SELECT * FROM tbl_leave where status='$status'"; $run = mysqli_query($conn, $getLeaves); while ($row = mysqli_fetch_array($run)) { $name = $row['Emp_Name']; $surname = $row['Emp_surname']; $reason = $row['Reason']; $position = $row['Position']; $duration = $row['Number_of_Days']; $start = $row['from_date']; $end = $row['to_date']; $type = $row['type']; echo " <tr> <td> $name </td> <td> $surname </td> <td> $position </td> <td> $type </td> <td> $start </td> <td> $end </td> <td> $reason </td> <td> $duration Days </td> </tr>"; } ?> </tbody> </table> </div> </div> </div> </div> <!-- Footer --> <footer class="sticky-footer bg-white"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright &copy; <script> document.write(new Date().getFullYear()); </script> JockTech EMS</span> </div> </div> </footer> <!-- End of Footer --> </div> </div> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- add approve modal --> <!-- Modal --> <div class="modal fade" id="Approve" tabindex="-1" role="dialog" aria-labelledby="announcementCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="announcementModalLongTitle">Approve Application</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="POST" enctype="multipart/form-data"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputState">Employee</label> <select id="inputState" class="form-control" name="id" required> <option></option> <?php $status = "pending"; $get_emp = "SELECT * FROM tbl_leave WHERE status='$status'"; $run = mysqli_query($conn, $get_emp); while ($row = mysqli_fetch_array($run)) { $emp_id = $row['emp_id']; $name = $row['Emp_Name']; $surname = $row['Emp_surname']; $Display_name = $name . " " . $surname; echo "<option value='$emp_id'>$Display_name</option> "; } ?> </select> </div> <div class="form-group col-md-6"> <label for="inputState">Decision</label> <select id="inputState" class="form-control" name="decision" required> <option></option> <option>Approved</option> <option>Declined</option> </select> </div> </div> <div class="form-group"> </div> <button type="submit" name="approve" class="btn btn-primary">Submit</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="../plugins/jquery/jquery.min.js"></script> <script src="../plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="../plugins/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="../js/sb-admin-2.min.js"></script> <!-- Page level plugins --> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <!-- Page level custom scripts --> <script src="../js/demo/chart-area-demo.js"></script> <script src="../js/demo/chart-pie-demo.js"></script> <script src="../js/demo/datatables-demo.js"></script> <script src="../plugins/datatables/jquery.dataTables.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> </body> </html> <?php // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; if (isset($_POST['approve'])) { require 'vendor/autoload.php'; $decision = $_POST['decision']; $emp_id = $_POST['id']; $admin = $_SESSION['user']; $content = "Leave Application " . " " . $decision; $today = date("F j, Y, g:i a"); $days_rem; $select = "SELECT * FROM tbl_leave where emp_id ='$emp_id' and status = 'pending'"; $run = mysqli_query($conn, $select); $row = mysqli_fetch_array($run); $app_id = $row['leave_ID']; $days = $row['Number_of_Days']; $total = $row['leave_days']; $type = $row['type']; $from =$row['from_date']; $to =$row['to_date']; if ($decision == "Approved") { $days_rem = $total - $days; } else { $days_rem = $total; } // Instantiation and passing `true` enables exceptions $mail = new PHPMailer(true); try { $query = "SELECT * FROM tbl_employee where emp_ID = '$emp_id'"; $run_query = mysqli_query($conn, $query); $row = mysqli_fetch_array($run_query); $salary = $row['SALARY']; $email = $row['EMAIL_ADDRESS']; $name = $row['Name']; $surname = $row['surname']; $Display_name = $name . " " . $surname; //Server settings //$mail->SMTPDebug = 2; //SMTP::DEBUG_SERVER; // Enable verbose debug output $mail->isSMTP(); // Send using SMTP $mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'jocktech23@<EMAIL>'; // SMTP username $mail->Password = <PASSWORD>'; // SMTP password $mail->SMTPSecure = 'tls'; //PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged $mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above //Recipients $mail->setFrom('<EMAIL>', $admin); $mail->addAddress($email); // Add a recipient $body = '<table align="center" border="0" cellpadding="0" cellspacing="0" width="600" style="border: 1px solid #cccccc; border-collapse: collapse;"> <tr> <td style="padding: 10px 0 30px 0;"> <table align="center" border="0" cellpadding="0" cellspacing="0" width="600" style="border: 1px solid #cccccc; border-collapse: collapse;"> <tr> <td align="center" bgcolor="#70bbd9" style="padding: 40px 0 30px 0; color: #153643; font-size: 28px; font-weight: bold; font-family: Arial, sans-serif;"> <img src="../images/logo.png" alt="Welcome" width="300" height="230" style="display: block;" /> </td> </tr> <tr> <td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td style="color: #153643; font-family: Arial, sans-serif; font-size: 24px;"> <b>Hey there ' . $Display_name . '</b> </td> </tr> <tr> <td style="padding: 20px 0 30px 0; color: #153643; font-family: Arial, sans-serif; font-size: 16px; line-height: 20px;"> I am pleased to inform you that your '.$days.' days '.$type.' leave has been approved and sanctioned from '.$from.' to '.$to.' as requested by you. <br> <br> Administration <br> Thank you! </td> </tr> </table> </td> </tr> <tr> </tr> </table> </td> </tr> </table> </td> </tr> </table>'; // Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = $content; $mail->Body = $body; $mail->AltBody = ""; $Update = "UPDATE tbl_leave SET status='$decision' , leave_days ='$days_rem' where emp_id ='$emp_id' AND leave_ID ='$app_id'"; $run_update = mysqli_query($conn, $Update); $insert_notification = "INSERT INTO emp_notifications(content,date,emp_id,admin) values('$content','$today','$emp_id','$admin')"; $run_insert = mysqli_query($conn, $insert_notification); if ($run_update || $run_insert) { $mail->send(); echo "<script>alert('Application has been processed')</script>"; echo "<script>window.open('leave.php','_self')</script>"; } else { echo "<script>alert('Server error! Application could not be processed please try again later')</script>"; echo "<script>window.open('leave.php','_self')</script>"; } } catch (Exception $e) { } // else { // $Update = "UPDATE tbl_leave SET status='$decision' , leave_days ='$days_rem' where emp_id ='$emp_id' AND leave_ID ='$app_id'"; // $run_update = mysqli_query($conn, $Update); // $insert_notification = "INSERT INTO emp_notifications(content,date,emp_id,admin) values('$content','$today','$emp_id','$admin')"; // $run_insert = mysqli_query($conn, $insert_notification); // if ($run_update || $run_insert) { // echo "<script>alert('Application has been processed')</script>"; // echo "<script>window.open('leave.php','_self')</script>"; // } else { // echo "<script>alert('Server error! Application could not be processed please try again later')</script>"; // echo "<script>window.open('leave.php','_self')</script>"; // } // } } ?><file_sep><?php include("includes/db_con.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <link rel="apple-touch-icon" sizes="57x57" href="favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="favicons/favicon-16x16.png"> <link rel="manifest" href="../favicons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JockTech EMS</title> <!-- <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap-material-design.min.css" integrity="<KEY>" crossorigin="anonymous" /> --> <link href="plugins/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="css/sb-admin-2.min.css" rel="stylesheet"> <link rel="stylesheet" href="plugins/datatables/dataTables.bootstrap4.min.css"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <?php include("pages/header.php") ?> <!-- page begin content --> <div class="container-fluid"> <?php include("pages/nav-cards.php") ?> <div class="card shadow mb-4"> <div class="card-header py-3"> <a href="#collapseCard" class="d-block card-header py-3" data-toggle="collapse" role="button" aria-expanded="true" aria-controls="collapseCard"> <h6 class="m-0 font-weight-bold text-primary">Company meetings</h6> </a> </div> <div class="collapse show" id="collapseCard"> <div class="card-body collapse show"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Date</th> <th>Agenda</th> <th>From</th> <th>To</th> </tr> </thead> <tbody> <?php $id = $_SESSION['id']; $getEmployees = "SELECT * FROM tbl_meetings"; $run = mysqli_query($conn,$getEmployees); while($row = mysqli_fetch_array($run)){ $date = $row['Meeting_Date']; $agenda = $row['Subject']; $start = $row['Start_time']; $end = $row['End_time']; echo " <tr> <td> $date </td> <td> $agenda </td> <td> $start </td> <td> $end </td> </tr>"; } ?> </tbody> </table> </div> </div> </div> </div> </div> <!-- Footer --> <footer class="sticky-footer bg-white"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright &copy; <script> document.write(new Date().getFullYear()); </script> JockTech EMS</span> </div> </div> </footer> <!-- End of Footer --> </div> </div> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Bootstrap core JavaScript--> <script src="plugins/jquery/jquery.min.js"></script> <script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="plugins/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="js/sb-admin-2.min.js"></script> <!-- Page level plugins --> <script src="plugins/chart.js/Chart.bundle.min.js"></script> <script src="plugins/datatables/dataTables.bootstrap4.min.js"></script> <script src="plugins/chart.js/Chart.bundle.min.js"></script> <!-- Page level custom scripts --> <script src="js/demo/chart-area-demo.js"></script> <script src="js/demo/chart-pie-demo.js"></script> <script src="js/demo/datatables-demo.js"></script> <script src="plugins/datatables/jquery.dataTables.min.js"></script> <script src="plugins/datatables/dataTables.bootstrap4.min.js"></script> </body> </html> <file_sep> <?php include("functions/functions.php"); ?> <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h1 class="h3 mb-0 text-gray-800">Dashboard</h1> <!-- <a href="#" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i class="fas fa-download fa-sm text-white-50"></i> DownloadReport</a> --> </div> <!-- Content Row --> <div class="row"> <!-- Task Card Example --> <div class="col-xl-3 col-md-6 mb-4"> <div class="card border-left-info shadow h-100 py-2"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Tasks</div> <div class="row no-gutters align-items-center"> <div class="col-auto"> <?php getTasksNumber(); ?> </div> </div> </div> <div class="col-auto"> <i class="fas fa-clipboard-list fa-2x text-gray-300"></i> </div> </div> </div> </div> </div> <!-- Leave Requests Card Example --> <div class="col-xl-3 col-md-6 mb-4"> <div class="card border-left-warning shadow h-100 py-2"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Leave days remaining</div> <?php $id = $_SESSION['id']; $getCount = "SELECT * FROM tbl_leave where emp_id ='$id'"; $run = mysqli_query($conn,$getCount); $count = mysqli_num_rows($run); $row = mysqli_fetch_array($run); $value=0 ; if($count >0){ $number = $row['leave_days']; echo ' <div class="h5 mb-0 font-weight-bold text-gray-800"> '.$number.'</div>'; } else{ // if($number == "null"){ // $value = 21; // echo ' <div class="h5 mb-0 font-weight-bold text-gray-800"> '.$number.' </div>'; // } echo ' <div class="h5 mb-0 font-weight-bold text-gray-800"> 21 </div> '; } ?> </div> <div class="col-auto"> <i class="fas fa-comments fa-2x text-gray-300"></i> </div> </div> </div> </div> </div> </div> <!-- Content Row --><file_sep> <!DOCTYPE html> <html lang="en"> <head> <link rel="apple-touch-icon" sizes="57x57" href="../favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="../favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="../favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="../favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="../favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="../favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="../favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="../favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="../favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="../favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="../favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="../favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="../favicons/favicon-16x16.png"> <link rel="manifest" href="../favicons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="../favicons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JockTech EMS</title> <!-- <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap-material-design.min.css" integrity="<KEY>" crossorigin="anonymous" /> --> <link href="../plugins/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="../css/sb-admin-2.min.css" rel="stylesheet"> <link rel="stylesheet" href="../plugins/datatables/dataTables.bootstrap4.min.css"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <?php include("pages/header.php") ?> <!-- page begin content --> <div class="container-fluid"> <?php include("pages/nav-cards.php") ?> <div class="card shadow mb-4"> <div class="card-header py-3"> <a href="#collapseCard" class="d-block card-header py-3" data-toggle="collapse" role="button" aria-expanded="true" aria-controls="collapseCard"> <h6 class="m-0 font-weight-bold text-primary">Team Sheet Management</h6> </a> </div> <div class="collapse show" id="collapseCard"> <div class="card-body collapse show"> <!-- Page Heading --> <h1 class="h3 mb-2 text-gray-800">Time sheet</h1> <!-- <p class="mb-4">DataTables is a third party plugin that is used to generate the demo table below. For more information about DataTables, please visit the <a target="_blank" href="https://datatables.net">official DataTables documentation</a>.</p> --> <form action="Timesheet.inc.php" method="post"> <div class="form-row"> <div class="form-group col-md-4"> <label for="inputState">Employee</label> <select id="inputState" class="form-control" name="name" required> <option selected>Choose...</option> <?php $get_emp = "SELECT * FROM tbl_employee"; $run = mysqli_query($conn, $get_emp); while ($row = mysqli_fetch_array($run)) { $emp_id = $row['emp_ID']; $name = $row['Name']; $surname = $row['surname']; $email = $row['EMAIL_ADDRESS']; $Display_name = $name." ".$surname; echo " <option value='$emp_id'>$Display_name</option> "; } ?> </select> </div> <div class="form-group col-md-4"> <label for="inputPassword4">Date</label> <input type="date" class="form-control" name="date" required> </div> </div> <div class="form-row"> <div class="form-group col-md-4"> <label for="inputEmail4">Start Time</label> <input type="time" class="form-control" name="start_time" required> </div> <div class="form-group col-md-4"> <label for="inputPassword4">End Time</label> <input type="time" class="form-control" name="end_time" required> </div> </div> <div class="form-row"> <div class="form-group col-md-4"> <label for="inputCity">Over time(Hours)</label> <input type="number" class="form-control" name="overtime" required> </div> </div> <div class="form-group"> </div> <button type="submit" name="create" class="btn btn-primary">Create</button> </form> </div> </div> </div> <div class="card shadow mb-4"> <div class="card-header py-3"> <a href="#collapseCards" class="d-block card-header py-3" data-toggle="collapse" role="button" aria-expanded="true" aria-controls="collapseCard"> <h6 class="m-0 font-weight-bold text-primary">Employee Timesheet</h6> </a> </div> <div class="collapse show " id="collapseCards"> <div class="card-body collapse show"> <form method="POST"> <div class="form-row"> <div class="form-group col-md-4"> <label for="inputState">Employee</label> <select id="inputState" class="form-control" name="name" required> <option ></option> <?php $get_emp = "SELECT * FROM tbl_employee"; $run = mysqli_query($conn, $get_emp); while ($row = mysqli_fetch_array($run)) { $emp_id = $row['emp_ID']; $name = $row['Name']; $surname = $row['surname']; $email = $row['EMAIL_ADDRESS']; $Display_name = $name." ".$surname; echo "<option value='$emp_id'>$Display_name</option> "; } ?> </select> </div> </div> <div class="form-group col-md-2"> <button class="btn btn-success " name="view"> <i class="fas fa-check-circle"></i>View</button> </div> </form> <?php if (isset($_POST['view'])) { $id = $_POST['name']; echo '<div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Date</th> <th>start</th> <th>end</th> <th>Regular hours</th> <th>Overtime (Hours)</th> <th>Total Hours Worked</th> </tr> </thead> '; ?> <?php $getIncreaseRequests = "SELECT * FROM tbl_timesheet where emp_ID='$id'"; $run = mysqli_query($conn, $getIncreaseRequests); while ($row = mysqli_fetch_array($run)) { $startdate = $row['Date']; $start = $row['Start_Time']; $end = $row['Finish_Time']; $regular = $row['Regular_Hours']; $overtime = $row['Overtime_Hours']; $total = $row['Totalworked_hours']; echo " <tbody> <tr> <td> $startdate </td> <td> $start </td> <td> $end </td> <td> $regular hrs </td> <td> $overtime hrs </td> <td> $total hrs </td> </tr>"; } } ?> </tbody> </table> </div> </div> </div> <!-- Footer --> <footer class="sticky-footer bg-white"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright &copy; <script> document.write(new Date().getFullYear()); </script> JockTech EMS</span> </div> </div> </footer> <!-- End of Footer --> </div> </div> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Bootstrap core JavaScript--> <script src="../plugins/jquery/jquery.min.js"></script> <script src="../plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="../plugins/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="../js/sb-admin-2.min.js"></script> <!-- Page level plugins --> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> <script src="../plugins/chart.js/Chart.bundle.min.js"></script> <!-- Page level custom scripts --> <script src="../js/demo/chart-area-demo.js"></script> <script src="../js/demo/chart-pie-demo.js"></script> <script src="../js/demo/datatables-demo.js"></script> <script src="../plugins/datatables/jquery.dataTables.min.js"></script> <script src="../plugins/datatables/dataTables.bootstrap4.min.js"></script> </body> </html>
24ad580a04cd4f3eb6b7d289a8774767e09e4024
[ "Markdown", "SQL", "PHP" ]
27
PHP
dev-ted/employee-management-system
214f2f13ff23fc2341e0213dce26d533d320438d
46ea8545ded6807b71d987e86ed6b80717872345
refs/heads/master
<file_sep>package com.bdpatron; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class FamiliarDAO implements DAO<Familiar> { static Scanner teclado = new Scanner (System.in); @Override public Familiar get(long id, Connection con) { Familiar fam = new Familiar(); try { PreparedStatement ps = con.prepareStatement("SELECT * FROM familiares where fcode = ?"); ps.setLong(1, id); ResultSet rs = ps.executeQuery(); while (rs.next()) { fam.setFcode(rs.getInt("fcode")); fam.setFname(rs.getString("fname")); fam.setFpar(rs.getString("fpar")); fam.setEdad(rs.getInt("edad")); fam.setPariente(rs.getInt("pariente")); } } catch (Exception e) { e.printStackTrace(); } return fam; } @Override public List<Familiar> getAll(Connection conn) { List<Familiar> lista = null; try { Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = s.executeQuery("SELECT * FROM Familiares;"); int totalRows = 0; rs.last(); totalRows = rs.getRow(); rs.beforeFirst(); lista = new ArrayList<Familiar>(totalRows); while (rs.next()) { Familiar fam = new Familiar(); fam.setFcode(rs.getInt("fcode")); fam.setFname(rs.getString("fname")); fam.setFpar(rs.getString("fpar")); fam.setEdad(rs.getInt("edad")); fam.setPariente(rs.getInt("pariente")); lista.add(fam); } } catch (SQLException e) { e.printStackTrace(); } return lista; } public List<Familiar> getByEmp(int emp, Connection con) { List<Familiar> lista = null; try { PreparedStatement ps = con.prepareStatement("SELECT * FROM familiares where pariente = ?;", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ps.setInt(1, emp); ResultSet rs = ps.executeQuery(); int totalRows = 0; rs.last(); totalRows = rs.getRow(); rs.beforeFirst(); lista = new ArrayList<Familiar>(totalRows); while (rs.next()) { Familiar fam = new Familiar(); fam.setFcode(rs.getInt("fcode")); fam.setFname(rs.getString("fname")); fam.setFpar(rs.getString("fpar")); fam.setEdad(rs.getInt("edad")); fam.setPariente(rs.getInt("pariente")); lista.add(fam); } } catch (SQLException e) { e.printStackTrace(); } return lista; } public void insertFam(int emp, int emp2, Connection con) { try { PreparedStatement ps = con.prepareStatement("SELECT * FROM familiares where pariente = ?;", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ps.setInt(1, emp); ResultSet rs = ps.executeQuery(); List<Familiar> fams = getByEmp(emp2, con); for (int i = 0; i < fams.size(); i++) { rs.moveToInsertRow(); rs.updateInt("fcode", fams.size() + fams.get(i).getFcode()); rs.updateString("fname", fams.get(i).getFname()); rs.updateString("fpar", fams.get(i).getFpar()); rs.updateInt("edad", fams.get(i).getEdad()); rs.updateInt("pariente", emp); rs.insertRow(); } } catch (Exception e) { e.printStackTrace(); } } public void insertarLote (Connection con) { try { PreparedStatement ps = con.prepareStatement("INSERT INTO proyectos (fcode, fname, fpar, edad, pariente) VALUES (?, ?, ?, ?, ?);" , ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); for (int i = 0; i < 3; i++) { System.out.println("Inserte número familiar: "); ps.setInt(1, Integer.parseInt(teclado.nextLine())); System.out.println("Inserte nombre familiar: "); ps.setString(2, teclado.nextLine()); System.out.println("Inserte parentesco familiar: "); ps.setString(3, teclado.nextLine()); System.out.println("Inserte edad familiar: "); ps.setInt(4, Integer.parseInt(teclado.nextLine())); System.out.println("Inserte número pariente: "); ps.setInt(5, Integer.parseInt(teclado.nextLine())); ps.addBatch(); } ps.executeBatch(); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>package com.bdpatron; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class ProyectoDAO implements DAO <Proyecto> { static Scanner teclado = new Scanner (System.in); @Override public Proyecto get (long id, Connection con) { Proyecto proy = new Proyecto(); try { PreparedStatement ps = con.prepareStatement("SELECT * FROM proyectos where pcode = ?"); ps.setLong(1, id); ResultSet rs = ps.executeQuery(); while (rs.next()) { proy.setDeptno(rs.getInt("deptno")); proy.setPcode(rs.getInt("pcode")); proy.setDesc(rs.getString("descp")); proy.setPres(rs.getDouble("pres")); proy.setPname(rs.getString("pname")); } } catch (Exception e) { e.printStackTrace(); } return proy; } @Override public List <Proyecto> getAll (Connection conn) { List <Proyecto> lista = null; try { Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = s.executeQuery("SELECT * FROM Proyectos;"); int totalRows = 0; rs.last(); totalRows = rs.getRow(); rs.beforeFirst(); lista = new ArrayList <Proyecto> (totalRows); while(rs.next()) { Proyecto proy = new Proyecto(); proy.setDeptno(rs.getInt("deptno")); proy.setPcode(rs.getInt("pcode")); proy.setDesc(rs.getString("descp")); proy.setPres(rs.getDouble("pres")); proy.setPname(rs.getString("pname")); lista.add(proy); } } catch (SQLException e) { e.printStackTrace(); } return lista; } public void insertarLote (Connection con) { try { PreparedStatement ps = con.prepareStatement("INSERT INTO proyectos (pcode, pname, descp, pres, deptno) VALUES (?, ?, ?, ?, ?);" , ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); for (int i = 0; i < 3; i++) { System.out.println("Inserte número proyecto: "); ps.setInt(1, Integer.parseInt(teclado.nextLine())); System.out.println("Inserte nombre proyecto: "); ps.setString(2, teclado.nextLine()); System.out.println("Inserte descripción proyecto: "); ps.setString(3, teclado.nextLine()); System.out.println("Inserte presupuesto proyecto: "); ps.setFloat(4, Float.parseFloat(teclado.nextLine())); System.out.println("Inserte número departamento: "); ps.setInt(5, Integer.parseInt(teclado.nextLine())); ps.addBatch(); } ps.executeBatch(); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>package com.bdpatron; public class Familiar { String fname, fpar; int edad, pariente, fcode; public String getFname() { return this.fname; } public void setFname(String fname) { this.fname = fname; } public String getFpar() { return this.fpar; } public void setFpar(String fpar) { this.fpar = fpar; } public int getEdad() { return this.edad; } public void setEdad(int edad) { this.edad = edad; } public int getPariente() { return this.pariente; } public void setPariente(int pariente) { this.pariente = pariente; } public int getFcode() { return this.fcode; } public void setFcode(int fcode) { this.fcode = fcode; } @Override public String toString() { return "{" + " fname='" + getFname() + "'" + ", fpar='" + getFpar() + "'" + ", edad='" + getEdad() + "'" + ", pariente='" + getPariente() + "'" + ", fcode='" + getFcode() + "'" + "}"; } } <file_sep>package com.bdpatron; import java.util.Scanner; public class View { static Scanner teclado = new Scanner (System.in); public int mostrarMenu () { System.out.println("1) Mostrar empleados"); System.out.println("2) Mostrar departamentos"); System.out.println("3) Mostrar proyectos"); System.out.println("4) Mostrar familiares"); System.out.println("5) Mostrar x empleado"); System.out.println("6) Mostrar x departamento"); System.out.println("7) Mostrar x proyecto"); System.out.println("8) Mostrar x familiar"); System.out.println("9) Buscar empleado por departamento"); System.out.println("10) Buscar empleados por hiredate"); System.out.println("11) Buscar empleados por trabajo"); System.out.println("12) Buscar familiares por empleado"); System.out.println("13) Buscar empleado por salario y departamento"); System.out.println("14) Mostrar empleados en minúsculas"); System.out.println("15) Insertar familiares empleados"); System.out.println("16) Actualizar comisiones"); System.out.println("17) Crear vistas departamentos"); System.out.println("18) Mostrar vistas departamentos"); System.out.println("19) Crear vistas jefes"); System.out.println("20) Mostrar vistas jefes"); System.out.println("21) Mostrar número de jefes"); System.out.println("22) Mostrar nombre de empleado por empno"); System.out.println("23) Añadir 3 empleados"); System.out.println("24) Añadir 3 departamentos"); System.out.println("25) Añadir 3 proyectos"); System.out.println("26) Añadir 3 familiares"); System.out.println("27) Salir"); int opc = Integer.parseInt(teclado.nextLine()); return opc; } public boolean showMessage(String message) { System.out.println(message); return true; } } <file_sep>package com.bdpatron; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class EmpleadoDAO implements DAO <Empleado> { static Scanner teclado = new Scanner (System.in); @Override public Empleado get (long id, Connection con) { try { PreparedStatement ps = con.prepareStatement("SELECT * FROM EMP where empno = ?", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ps.setLong(1, id); ResultSet rs = ps.executeQuery(); while(rs.next()) { Empleado emp = new Empleado(); emp.setEmpno(rs.getInt(1)); emp.setEname(rs.getString(2)); emp.setJob(rs.getString(3)); emp.setMgr(rs.getInt(4)); emp.setHiredate(LocalDate.parse(rs.getString(5))); emp.setSal(rs.getFloat(6)); emp.setComm(rs.getFloat(7)); emp.setDeptno(rs.getInt(8)); return emp; } } catch (Exception e) { e.printStackTrace(); } return new Empleado(); } @Override public List <Empleado> getAll (Connection conn) { List <Empleado> lista = null; try { Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = s.executeQuery("SELECT * FROM EMP;"); int totalRows = 0; rs.last(); totalRows = rs.getRow(); rs.beforeFirst(); lista = new ArrayList<Empleado>(totalRows); while(rs.next()) { Empleado emp = new Empleado(); emp.setEmpno(rs.getInt(1)); emp.setEname(rs.getString(2)); emp.setJob(rs.getString(3)); emp.setMgr(rs.getInt(4)); emp.setHiredate(LocalDate.parse(rs.getString(5))); emp.setSal(rs.getFloat(6)); emp.setComm(rs.getFloat(7)); emp.setDeptno(rs.getInt(8)); lista.add(emp); } } catch (SQLException e) { e.printStackTrace(); } return lista; } public List <Empleado> getByDept (long deptno, Connection con) { List <Empleado> lista = null; try { PreparedStatement ps = con.prepareStatement("SELECT * FROM EMP where deptno = ? order by empno asc;", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ps.setLong(1, deptno); ResultSet rs = ps.executeQuery(); int totalRows = 0; rs.last(); totalRows = rs.getRow(); rs.afterLast(); lista = new ArrayList <Empleado> (totalRows); while(rs.previous()) { Empleado emp = new Empleado(); emp.setEmpno(rs.getInt(1)); emp.setEname(rs.getString(2)); emp.setJob(rs.getString(3)); emp.setMgr(rs.getInt(4)); emp.setHiredate(LocalDate.parse(rs.getString(5))); emp.setSal(rs.getFloat(6)); emp.setComm(rs.getFloat(7)); emp.setDeptno(rs.getInt(8)); lista.add(emp); } } catch (Exception e) { e.printStackTrace(); } return lista; } public List <Empleado> getByDate (LocalDate date, Connection con) { List <Empleado> lista = null; try { PreparedStatement ps = con.prepareStatement("SELECT * FROM EMP where hiredate = ?;", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ps.setString(1, date.toString()); ResultSet rs = ps.executeQuery(); int totalRows = 0; rs.last(); totalRows = rs.getRow(); rs.beforeFirst(); lista = new ArrayList <Empleado> (totalRows); while(rs.next()) { Empleado emp = new Empleado(); emp.setEmpno(rs.getInt(1)); emp.setEname(rs.getString(2)); emp.setJob(rs.getString(3)); emp.setMgr(rs.getInt(4)); emp.setHiredate(LocalDate.parse(rs.getString(5))); emp.setSal(rs.getFloat(6)); emp.setComm(rs.getFloat(7)); emp.setDeptno(rs.getInt(8)); lista.add(emp); } } catch (Exception e) { e.printStackTrace(); } return lista; } public List <Empleado> getByJob (String job, Connection con) { List <Empleado> lista = null; try { PreparedStatement ps = con.prepareStatement("SELECT * FROM EMP where job = ?;", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ps.setString(1, job); ResultSet rs = ps.executeQuery(); int totalRows = 0; rs.last(); totalRows = rs.getRow(); rs.beforeFirst(); lista = new ArrayList <Empleado> (totalRows); while(rs.next()) { Empleado emp = new Empleado(); emp.setEmpno(rs.getInt(1)); emp.setEname(rs.getString(2)); emp.setJob(rs.getString(3)); emp.setMgr(rs.getInt(4)); emp.setHiredate(LocalDate.parse(rs.getString(5))); emp.setSal(rs.getFloat(6)); emp.setComm(rs.getFloat(7)); emp.setDeptno(rs.getInt(8)); lista.add(emp); } } catch (Exception e) { e.printStackTrace(); } return lista; } public List <Empleado> getBySalDept (Float sal, int dept, Connection con) { List <Empleado> lista = null; try { PreparedStatement ps = con.prepareStatement("SELECT * FROM EMP where sal = ? and deptno = ?;", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ps.setFloat(1, sal); ps.setInt(2, dept); ResultSet rs = ps.executeQuery(); int totalRows = 0; rs.last(); totalRows = rs.getRow(); rs.beforeFirst(); lista = new ArrayList <Empleado> (totalRows); while(rs.next()) { Empleado emp = new Empleado(); emp.setEmpno(rs.getInt(1)); emp.setEname(rs.getString(2)); emp.setJob(rs.getString(3)); emp.setMgr(rs.getInt(4)); emp.setHiredate(LocalDate.parse(rs.getString(5))); emp.setSal(rs.getFloat(6)); emp.setComm(rs.getFloat(7)); emp.setDeptno(rs.getInt(8)); lista.add(emp); } } catch (Exception e) { e.printStackTrace(); } return lista; } public List <Empleado> getAllToLowerCase (Connection conn) { List <Empleado> lista = null; try { Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = s.executeQuery("SELECT * FROM EMP;"); rs.beforeFirst(); while (rs.next()) { rs.updateString("ENAME", rs.getString(2).toLowerCase()); rs.updateRow(); } int totalRows = 0; rs.last(); totalRows = rs.getRow(); rs.beforeFirst(); lista = new ArrayList<Empleado>(totalRows); while(rs.next()) { Empleado emp = new Empleado(); emp.setEmpno(rs.getInt(1)); emp.setEname(rs.getString(2)); emp.setJob(rs.getString(3)); emp.setMgr(rs.getInt(4)); emp.setHiredate(LocalDate.parse(rs.getString(5))); emp.setSal(rs.getFloat(6)); emp.setComm(rs.getFloat(7)); emp.setDeptno(rs.getInt(8)); lista.add(emp); } rs.beforeFirst(); while (rs.next()) { rs.updateString("ENAME", rs.getString(2).toUpperCase()); rs.updateRow(); } } catch (SQLException e) { e.printStackTrace(); } return lista; } public List <Empleado> actualizarComisiones (Connection con) { List <Empleado> lista = null; try { PreparedStatement ps = con.prepareStatement("SELECT * from EMP where EMPNO in (SELECT mgr FROM emp where mgr is not null);", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = ps.executeQuery(); List <Empleado> emps = getByMgr(con); while (rs.next()) { for (int i = 0; i < emps.size(); i++ ) { if (emps.get(i).getMgr() == rs.getInt(1)) { rs.updateFloat("COMM", emps.get(i).getComm() * 2); rs.updateRow(); } } } Statement s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs2 = s.executeQuery("SELECT * from EMP where EMPNO in (SELECT mgr FROM emp where mgr is not null);"); int totalRows = 0; rs2.last(); totalRows = rs2.getRow(); rs2.beforeFirst(); lista = new ArrayList<Empleado>(totalRows); while(rs2.next()) { Empleado emp = new Empleado(); emp.setEmpno(rs2.getInt(1)); emp.setEname(rs2.getString(2)); emp.setJob(rs2.getString(3)); emp.setMgr(rs2.getInt(4)); emp.setHiredate(LocalDate.parse(rs2.getString(5))); emp.setSal(rs2.getFloat(6)); emp.setComm(rs2.getFloat(7)); emp.setDeptno(rs2.getInt(8)); lista.add(emp); } } catch (Exception e) { e.printStackTrace(); } return lista; } public List <Empleado> getByMgr (Connection con) { List <Empleado> lista = null; try { Statement s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = s.executeQuery("SELECT * FROM EMP where mgr is not null;"); int totalRows = 0; rs.last(); totalRows = rs.getRow(); rs.beforeFirst(); lista = new ArrayList<Empleado>(totalRows); while(rs.next()) { Empleado emp = new Empleado(); emp.setEmpno(rs.getInt(1)); emp.setEname(rs.getString(2)); emp.setJob(rs.getString(3)); emp.setMgr(rs.getInt(4)); emp.setHiredate(LocalDate.parse(rs.getString(5))); emp.setSal(rs.getFloat(6)); emp.setComm(rs.getFloat(7)); emp.setDeptno(rs.getInt(8)); lista.add(emp); } } catch (Exception e) { e.printStackTrace(); } return lista; } public void crearVistaDepts (Connection con) { try { Statement s = con.createStatement(); s.execute("CREATE OR REPLACE VIEW viewDept10(deptno, dname, empno, ename, job, sal, comm, hiredate) as SELECT d.deptno, dname, empno, ename, job, sal, comm, hiredate from dept d NATURAL JOIN emp e where deptno = 10;"); s.execute("CREATE OR REPLACE VIEW viewDept30(deptno, dname, empno, ename, job, sal, comm, hiredate) as SELECT d.deptno, dname, empno, ename, job, sal, comm, hiredate from dept d NATURAL JOIN emp e where deptno = 30;"); } catch (Exception e) { e.printStackTrace(); } } public void verVistas (Connection con) { try { Statement s = con.createStatement(); ResultSet rs = s.executeQuery("SELECT * FROM viewDept10"); while (rs.next()) { System.out.println(rs.getInt(1)); System.out.println(rs.getString(2)); System.out.println(rs.getInt(3)); System.out.println(rs.getString(4)); System.out.println(rs.getString(5)); System.out.println(rs.getFloat(6)); System.out.println(rs.getFloat(7)); System.out.println(LocalDate.parse(rs.getString(8))); } ResultSet rs2 = s.executeQuery("SELECT * FROM viewDept30"); while (rs2.next()) { System.out.println(rs2.getInt(1)); System.out.println(rs2.getString(2)); System.out.println(rs2.getInt(3)); System.out.println(rs2.getString(4)); System.out.println(rs2.getString(5)); System.out.println(rs2.getFloat(6)); System.out.println(rs2.getFloat(7)); System.out.println(LocalDate.parse(rs2.getString(8))); } } catch (Exception e) { e.printStackTrace(); } } public void crearVistasJefes (Connection con) { try { Statement s = con.createStatement(); s.execute("CREATE OR REPLACE VIEW viewJefes(deptno, empno, ename, job, sal, comm, hiredate) as SELECT deptno, empno, ename, job, sal, comm, hiredate from emp where empno in (select mgr from emp where mgr is not null);"); s.execute("CREATE OR REPLACE VIEW viewEmp(deptno, empno, ename, job, sal, comm, hiredate) as SELECT deptno, empno, ename, job, sal, comm, hiredate from emp where empno in (select mgr from emp where mgr is null);"); } catch (Exception e) { e.printStackTrace(); } } public void verVistasJefes (Connection con) { try { Statement s = con.createStatement(); ResultSet rs = s.executeQuery("SELECT * FROM viewJefes"); while (rs.next()) { System.out.println(rs.getInt(1)); System.out.println(rs.getInt(2)); System.out.println(rs.getString(3)); System.out.println(rs.getString(4)); System.out.println(rs.getFloat(5)); System.out.println(rs.getFloat(6)); System.out.println(LocalDate.parse(rs.getString(7))); } ResultSet rs2 = s.executeQuery("SELECT * FROM viewEmp"); while (rs2.next()) { System.out.println(rs2.getInt(1)); System.out.println(rs2.getInt(2)); System.out.println(rs2.getString(3)); System.out.println(rs2.getString(4)); System.out.println(rs2.getFloat(5)); System.out.println(rs2.getFloat(6)); System.out.println(LocalDate.parse(rs2.getString(7))); } } catch (Exception e) { e.printStackTrace(); } } public void getNumJefes (Connection con) { try { CallableStatement cs = con.prepareCall("{call GETNUMJEFES()}"); ResultSet result = cs.executeQuery(); while (result.next()) { System.out.println("Número de jefes: " + result.getInt(1)); } } catch (Exception e) { e.printStackTrace(); } } public void getNombreEmp (int num, Connection con) { try { CallableStatement cs = con.prepareCall("{call GETNOMBREEMP(?)}"); cs.setInt(1, num); ResultSet result = cs.executeQuery(); while (result.next()) { System.out.println("Nombre del empleado con número: " + num + " = " + result.getString(1)); } } catch (Exception e) { e.printStackTrace(); } } public void insertarLote (Connection con) { try { PreparedStatement ps = con.prepareStatement("INSERT INTO EMP (empno, ename, job, mgr, hiredate, sal, comm, deptno) VALUES (?, ?, ?, ?, ?, ?, ?, ?);" , ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); for (int i = 0; i < 3; i++) { System.out.println("Inserte número empleado: "); ps.setInt(1, Integer.parseInt(teclado.nextLine())); System.out.println("Inserte nombre empleado: "); ps.setString(2, teclado.nextLine()); System.out.println("Inserte trabajo empleado: "); ps.setString(3, teclado.nextLine()); System.out.println("Inserte mgr empleado: "); ps.setInt(4, Integer.parseInt(teclado.nextLine())); System.out.println("Inserte día contratación empleado: "); int dia = Integer.parseInt(teclado.nextLine()); System.out.println("Inserte mes contratación empleado: "); int mes = Integer.parseInt(teclado.nextLine()); System.out.println("Inserte año contratación empleado: "); int año = Integer.parseInt(teclado.nextLine()); LocalDate fecha = LocalDate.of(año, mes, dia); ps.setString(5, fecha.toString()); System.out.println("Inserte salario del empleado: "); ps.setFloat(6, Float.parseFloat(teclado.nextLine())); System.out.println("Inserte comisiones del empleado: "); ps.setFloat(7, Float.parseFloat(teclado.nextLine())); System.out.println("Inserte número de departamento del empleado: "); ps.setInt(8, Integer.parseInt(teclado.nextLine())); ps.addBatch(); } ps.executeBatch(); } catch (Exception e) { e.printStackTrace(); } } }<file_sep>package com.bdpatron; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class DepartamentoDAO implements DAO <Departamento> { static Scanner teclado = new Scanner (System.in); @Override public Departamento get (long id, Connection con) { Departamento dept = new Departamento(); try { PreparedStatement ps = con.prepareStatement("SELECT * FROM dept where deptno = ?"); ps.setLong(1, id); ResultSet rs = ps.executeQuery(); while (rs.next()) { dept.setDeptno(rs.getInt(1)); dept.setDname(rs.getString(2)); dept.setLoc(rs.getString(3)); } } catch (Exception e) { e.printStackTrace(); } return dept; } @Override public List <Departamento> getAll (Connection conn) { List <Departamento> lista = null; try { Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = s.executeQuery("SELECT * FROM DEPT;"); int totalRows = 0; rs.last(); totalRows = rs.getRow(); rs.beforeFirst(); lista = new ArrayList <Departamento> (totalRows); while(rs.next()) { Departamento dept = new Departamento(); dept.setDeptno(rs.getInt(1)); dept.setDname(rs.getString(2)); dept.setLoc(rs.getString(3)); lista.add(dept); } } catch (SQLException e) { e.printStackTrace(); } return lista; } public void insertarLote (Connection con) { try { PreparedStatement ps = con.prepareStatement("INSERT INTO dept (deptno, dname, loc) VALUES (?, ?, ?);" , ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); for (int i = 0; i < 3; i++) { System.out.println("Inserte número departamento: "); ps.setInt(1, Integer.parseInt(teclado.nextLine())); System.out.println("Inserte nombre departamento: "); ps.setString(2, teclado.nextLine()); System.out.println("Inserte localidad departamento: "); ps.setString(3, teclado.nextLine()); ps.addBatch(); } ps.executeBatch(); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>package com.bdpatron; import java.sql.Connection; import java.util.List; public interface DAO <T> { T get(long id, Connection con); List<T> getAll(Connection conn); }
74b1ca49123224d91b6216f0b6872ec5fff9f893
[ "Java" ]
7
Java
Samuel-SnD/Acceso_a_Datos
76bed54af6bb0f337d1e2d7157e5595afb161154
250f985ecc28ccbc9c6a04aa60a287baec840ef9
refs/heads/master
<file_sep>import cv2 from torchvision import transforms, utils import pickle import os import numpy as np import torch from torch.utils.data import Dataset, DataLoader import pandas as pd import scipy.misc from random import random def center_crop(img, target_size=224): shape = img.shape min_l = np.min(shape[:-1]) ratio = float(target_size)/min_l img = scipy.misc.imresize(img, ratio) h, w = img.shape[:-1] if h>w: b = (h-w)/2 + int(np.round(random()*15)) img = img[b:b+target_size, :, :] if h<w: b = (w-h)/2 + int(np.round(random()*15)) img = img[:, b:b+target_size, :] return cv2.resize(img, (target_size, target_size)) class TestDataset(Dataset): def __init__(self, root_dir, label_csv_name): self.root_dir = root_dir df = pd.read_csv(label_csv_name) self.id = list(df.id) self.class_mapping = {label:idx for idx, label in enumerate(np.unique(df.breed))} self.ce_weight = np.array([np.sum(df.breed==dog) for dog in np.unique(df.breed)], dtype=np.float32) self.ce_weight = np.sum(self.ce_weight) / self.ce_weight self.ce_weight = self.ce_weight/ np.sum(self.ce_weight) df['class_idx'] = df['breed'].map(self.class_mapping) self.labels = list(df.class_idx) def __len__(self): return len(self.id) def __getitem__(self, idx): target_size = 224 img = cv2.imread(os.path.join(self.root_dir, self.id[idx]+'.jpg'), -1) img = center_crop(img, target_size=target_size).astype(np.float32).transpose((2,0,1)) return img, self.labels[idx] class TrainDataSet(Dataset): def __init__(self, root_dir): self.root_dir = root_dir with open(os.path.join(self.root_dir, 'labels.pickle'), 'rb') as f: self.labels = pickle.load(f) def __len__(self): return len(self.labels) def __getitem__(self, idx): target_size = 224 img = cv2.imread(os.path.join(self.root_dir, '%s.png'%idx), -1) img = img.transpose((2,0,1)).astype(np.float32) return img, self.labels[idx] <file_sep>import pandas as pd import torchvision.models as models import dogdataset import numpy as np import sys import os import vgg import cv2 import time import torch from torch.autograd import Variable from dogdataset import center_crop def main(): model_para = sys.argv[1] files = os.listdir('./data/test/') train_dataset = dogdataset.TestDataset('./data/train/', './data/labels.csv') pre_dict = {} # net = vgg.MyVGG().cuda() net = models.resnet50(num_classes=120) net = torch.nn.DataParallel(net, device_ids=[0,1]).cuda() net.load_state_dict(torch.load('./checkpoints/res50/model-%s0000'%model_para)) net.eval() df = pd.DataFrame(columns=[id_.split('.')[0] for id_ in (['id'] + sorted(train_dataset.class_mapping.keys()))]) idx = 0 for file_name in files: idx += 1 print '%s image, name: %s'%(idx, file_name) img = cv2.imread('./data/test/'+file_name, -1) img = center_crop(img).astype(np.float32).transpose((2,0,1)).reshape(1, 3, 224, 224) img = Variable(torch.from_numpy(img).cuda()) probability = torch.nn.functional.softmax(net(img), dim=1) # probability = net(img) probability = list(probability.data.cpu().numpy().reshape([120])) id_name = file_name.split('.')[0] probability.insert(0, id_name) temp_df = pd.DataFrame([probability], columns=[id_.split('.')[0] for id_ in (['id'] + sorted(train_dataset.class_mapping.keys()))]) df = df.append(temp_df) df.to_csv('./submit/submit%s.csv'%model_para, index=False, index_label=False) if __name__ == '__main__': main() <file_sep>import dogdataset import vgg import sys # import models import torchvision.models as models import os from torch.utils.data import Dataset, DataLoader from torchvision import transforms import torch.nn as nn from torch.autograd import Variable from time import time import numpy as np import torch import resnet import torch.nn.functional as F def main(): lr = 0.0001 batch_size = 30 test_batch_size = 20 model_save_dir = sys.argv[1] if not os.path.exists(model_save_dir): os.mkdir(model_save_dir) net = models.resnet50(num_classes=120, pretrained=True) net = torch.nn.DataParallel(net, device_ids=[0, 1]) # net = vgg.MyVGG() net = net.cuda() train_dataset = dogdataset.TrainDataSet('./data_gen/train/') test_dataset = dogdataset.TestDataset('./data/train/', './data/test.csv') train_loader = DataLoader(train_dataset, batch_size=batch_size, \ shuffle=True, num_workers=10, pin_memory=True, drop_last=False) test_loader = DataLoader(test_dataset, batch_size=10, \ shuffle=False, num_workers=10, pin_memory=True, drop_last=True) ce_weight = test_dataset.ce_weight criterion = nn.CrossEntropyLoss(torch.from_numpy(np.array(ce_weight))).cuda() # criterion = nn.CrossEntropyLoss().cuda() optimizer = torch.optim.SGD(net.parameters(), lr=lr, momentum=0.9, weight_decay=1e-4, nesterov=True) # optimizer = torch.optim.Adam(net.parameters(), lr=lr, weight_decay=1e-4) print 'start to run' step = 0 net.load_state_dict(torch.load('./checkpoints/dense_weightedloss/model-4000')) for epoch in range(300): net.train() for i, data in enumerate(train_loader): step += 1 imgs = Variable(data[0].cuda()) labels = Variable(data[1].cuda()) predicted = net(imgs) optimizer.zero_grad() loss = criterion(predicted, labels) if step % 50 == 0: print 'at step %s loss: '%step, loss.data[0], 'lr: %s'%lr, 'acc: ', predicted.data.max(1)[1].eq(labels.data).cpu().sum()/float(batch_size) # acc = (s_pos.round()==train_target_constant).type(torch.FloatTensor) # acc2 = (s_neg.round()==train_target_constant-train_target_constant).type(torch.FloatTensor) # acc = (acc+acc2)/2 # print 'acc: ', acc.mean().data[0] loss.backward() optimizer.step() lr = lr*0.9**(1e-4) if step % 600 == 0: net.eval() correct = 0 loss_ = 0 for i_test, data_test in enumerate(test_loader): imgs_test = Variable(data_test[0].cuda()) labels_test = Variable(data_test[1].cuda()) results = net(imgs_test) loss = criterion(results, labels_test) loss_ += loss.data[0] predict = results.data.max(1)[1] correct += predict.eq(labels_test.data).cpu().sum() print 'test acc is :', float(correct) / 990, 'loss is : ', float(loss_) / i_test net.train() if step % 2000 == 0: torch.save(net.state_dict(), os.path.join(model_save_dir, 'model-%s'%step)) for param_group in optimizer.param_groups: param_group['lr'] = lr if __name__ == '__main__': main() <file_sep>import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import resnet class DogBreedNet(nn.Module): def __init__(self): super(DogBreedNet).__init__(self)
6ecbdcc74088d296387bb9ad1e48b7b7a1bba53e
[ "Python" ]
4
Python
WongChen/kaggle-dogbreed
e413cf7465d649563bff98ac51256b3b1b983028
8159556201e9b51d17700ce4bc44d543ae8d8276
refs/heads/master
<repo_name>takumab/f_m_s<file_sep>/spec/controllers/static_pages_controller_spec.rb require 'rails_helper' RSpec.describe StaticPagesController, :type => :controller do describe '#POST' do it "routes to /static_pages/thank_you" do expect(:post => '/static_pages/thank_you').to be_routable end end end<file_sep>/lib/html_tagger.rb class MethodsForStrings < String def italics styles('italics') end end<file_sep>/app/models/user.rb class User < ActiveRecord::Base has_secure_password validates :email, presence: true, uniqueness: true validates :password, length: { minimum: 8 } has_many :bookings has_many :services end <file_sep>/app/controllers/bookings_controller.rb class BookingsController < ApplicationController def index @bookings = Booking.all @bookings_by_date = @bookings.group_by(&:date) @date = params[:date] ? Date.parse(params[:date]) : Date.today end def show @booking = Booking.find(params[:id]) end def new end def create end def destroy end end<file_sep>/app/views/services/show.json.jbuilder json.extract! @service, :id, :name, :description, :image_url, :created_at, :updated_at <file_sep>/db/migrate/20160412104310_rename_type_in_services.rb class RenameTypeInServices < ActiveRecord::Migration def change rename_column :services, :type, :location_of_service end end <file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception private def current_user # Find user model based on the session's user_id # and only do this if session user id exists. # Cache above in instance variable due to likelyhood of # being called more than once @current_user ||= User.find(session[:user_id]) if session[:user_id] end # Helper method allows us to access the current user method # inside the views. helper_method :current_user def authorize redirect_to login_path, alert: "Not authorized" if current_user.nil? end end <file_sep>/spec/helpers/calendar_helper_spec.rb require 'rails_helper' RSpec.describe CalendarHelper, type: :helper do pending end<file_sep>/spec/factories/service_factroy.rb FactoryGirl.define do factory :service do name "Example service" description "Example cleaning" image_url "exampe.jpg" location_of_service "Residential/Commercial" end end<file_sep>/spec/models/user_spec.rb require 'rails_helper' RSpec.describe User, :type => :model do describe "validations" do before { @user = FactoryGirl.build(:user, email: "<EMAIL>", password_digest: <PASSWORD>") } it "is not valid without email" do @user.email = nil expect(@user).not_to be_valid end it "is not valid without password" do @user.password = nil expect(@user).not_to be_valid end end end<file_sep>/app/models/booking.rb class Booking < ActiveRecord::Base belongs_to :service end<file_sep>/spec/models/service_spec.rb require 'rails_helper' describe Service, :type => :model do describe "validations" do subject { FactoryGirl.build(:service, name: "Example service", description: "Clean example", image_url: "example.jpg") } it "does not validate service without a name" do subject.name = nil expect(subject).not_to be_valid end it "does not validate service without a description" do subject.description = nil expect(subject).not_to be_valid end it "does not validate service without a image" do subject.image_url = nil expect(subject).not_to be_valid end end end<file_sep>/app/models/service.rb class Service < ActiveRecord::Base has_many :bookings validates :name, presence: true validates :description, presence: true validates :image_url, presence: true end
e69bbbe902170ae8ee0d92777bc8a753b5a74369
[ "Ruby" ]
13
Ruby
takumab/f_m_s
122c409e9133c8857b6e178bb1f4b157a8755dad
cf7bc0dc9847177fff9d3d58fb109fe2fc647bda
refs/heads/main
<repo_name>Jaumz/Checagem_senha<file_sep>/js/jquery.js /*window.onload = function() { if (window.jQuery) { // jQuery is loaded alert("Yeah!"); } else { // jQuery is not loaded alert("Doesn't Work"); } } */ $(document).ready(function () { $('#txtPassword').keyup(function () { $('#msg').html(forca($('#txtPassword').val())); if ($('#txtPassword').val() == 0) { $('#msg').removeClass(); } }) $('#rePassword').keyup(function () { $('#remsg').html(reforca($('#rePassword').val())); /*if ($('#rePassword'.val()) == $('#txtPassword'.val())) { $('#remsg').removeClass(); $('#remsg').addClass('Good'); alert("As senhas coincidem"); }*/ if ($('#rePassword').val() == 0) { $('#remsg').removeClass(); } }) $("#exampleModal").modal('hide'); $('form').submit(function(event) { negarsenha(); validarSenha(); return false; }); }); function forca(password) { var strength = 0; if (password.length == 0) { $('#msg').removeClass(); return ''; } if (password.length < 6) { $('#msg').removeClass(); $('#msg').addClass('Short') return 'Senha muito pequena'; } if (password.length > 7) strength += 1; // Tendo letra maiúscula e minúscula ganha +1 no valor total if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1; // Tendo letras e números ganha +1 no valor total if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1; // Tendo caractere especial ganha +1 no valor total if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1; // Tendo 2 caracteres especiais ganha +1 no valor total if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1; if (strength < 2) { $('#msg').removeClass(); $('#msg').addClass('Weak'); return 'Senha Fraca'; } else if (strength == 2) { $('#msg').removeClass(); $('#msg').addClass('Good'); return 'Boa senha'; } else { $('#msg').removeClass(); $('#msg').addClass('Strong'); return 'Senha forte'; } } function reforca(password) { var strength = 0 if (password.length == 0) { $('#remsg').removeClass(); return ''; } if (password.length < 6) { $('#remsg').removeClass(); $('#remsg').addClass('Short'); return 'Senha muito pequena'; } if (password.length > 7) strength += 1; // Tendo letra maiúscula e minúscula ganha +1 no valor total if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1; // Tendo letras e números ganha +1 no valor total if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1; // Tendo caractere especial ganha +1 no valor total if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1; // Tendo 2 caracteres especiais ganha +1 no valor total if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1; if (strength < 2) { $('#remsg').removeClass(); $('#remsg').addClass('Weak'); return 'Senha Fraca'; } else if (strength == 2) { $('#remsg').removeClass(); $('#remsg').addClass('Good'); return 'Boa senha'; } else { $('#remsg').removeClass(); $('#remsg').addClass('Strong'); return 'Senha forte'; } } function negarsenha(){ if ($('#msg').hasClass('Short')) { $('#exampleModal').modal('show'); $('.change').text("Sua senha é muito pequena."); $('.changeb').text("Ok, vou digitar de novo."); } if ($('#msg').hasClass('Weak')) { $('#exampleModal').modal('show'); $('.change').text("Sua senha é muito fraca."); $('.changeb').text("Ok, vou digitar de novo."); } } function validarSenha(){ if ($('#msg').hasClass('Short')) { $('#exampleModal').modal('show'); $('.change').text("Sua senha é muito pequena."); $('#buttonm').text("Ok, vou digitar outra mais forte."); $('#txtPassword').val(""); $('#msg').text("").removeClass('Short'); $('#rePassword').val(""); $('#remsg').text("").removeClass('Short'); } if ($('#msg').hasClass('Weak')) { $('#exampleModal').modal('show'); $('.change').text("Sua senha é muito fraca, tente novamente com uma mais forte"); $('#buttonm').text("Ok, vou digitar outra mais forte."); } if ($('#txtPassword').val() === $('#rePassword').val() && $('#msg').hasClass('Good') && $('#remsg').hasClass('Good')) { $('#exampleModal').modal('show'); $('.change').text("Suas senhas coincidem. Obrigado por preencher o formulário!"); $('#buttonm').remove(); $('#exampleModal').on('hide.bs.modal', function (event) { $('input').val(""); $('#txtPassword').val(""); $('#msg').text("").removeClass('Short Weak Good Strong'); $('#rePassword').val(""); $('#remsg').text("").removeClass('Short Weak Good Strong'); }) } if ($('#txtPassword').val() === $('#rePassword').val() && $('#msg').hasClass('Strong') && $('#remsg').hasClass('Strong')) { $('#exampleModal').modal('show'); $('.change').text("Suas senhas coincidem. Obrigado por preencher o formulário!"); $('#buttonm').remove(); $('#exampleModal').on('hide.bs.modal', function (event) { $('input').val(""); $('#txtPassword').val(""); $('#msg').text("").removeClass('Strong'); $('#rePassword').val(""); $('#remsg').text("").removeClass('Strong'); }) } if ($('#txtPassword').val() > $('#rePassword').val()) { $('#exampleModal').modal('show'); $('.change').text("Suas senhas são diferentes, digite corretamente e tente novamente."); $('.buttonm').text("Ok, vou digitar de novo."); } if ($('#txtPassword').val() < $('#rePassword').val()) { $('#exampleModal').modal('show'); $('.change').text("Suas senhas são diferentes, digite corretamente e tente novamente."); $('.buttonm').text("Ok, vou digitar de novo."); } }
857b2c9206fcd9480eb25e6dba887642c71600fb
[ "JavaScript" ]
1
JavaScript
Jaumz/Checagem_senha
32283650ead42e00a9bf7ac66daa672fa01d6d2a
129d627c073a23c037c19692899a82201ca0e5e3
refs/heads/master
<file_sep># sensor-dashboard <file_sep>import time, requests from random import randint # http://localhost:5000/update def run(): r = requests.post("http://smartmetropolis-dashboard.herokuapp.com/update", data={'sensor1': randint(1, 100), 'sensor2': randint(1, 100), 'sensor3': randint(1, 100), 'sensor4': randint(1, 100)}) print(r.status_code, r.reason) if __name__ == "__main__": while True: run() time.sleep(10) <file_sep>from flask import Flask, Blueprint, render_template, jsonify from flask_restful import Api, Resource, url_for, reqparse ## ## Setup the API ## api_bp = Blueprint('api', __name__) api = Api(api_bp) parser = reqparse.RequestParser() parser.add_argument('sensor1') parser.add_argument('sensor2') parser.add_argument('sensor3') parser.add_argument('sensor4') field1 = field2 = field3 = field4 = 0 class Sensor(Resource): def post(self): global field1, field2, field3, field4 args = parser.parse_args() field1 = args['sensor1'] field2 = args['sensor2'] field3 = args['sensor3'] field4 = args['sensor4'] return '', 201 api.add_resource(Sensor, '/update') ## ## Setup the App ## app = Flask(__name__) app.register_blueprint(api_bp) @app.route("/") def index(): return render_template('index.html') @app.route("/sensor_data", methods=['GET']) def sensor_data(): return jsonify(sensor1=field1, sensor2=field2, sensor3=field3, sensor4=field4) if __name__ == "__main__": app.run()
7d45093ce544e2cbc2fd5e7632b16ceb029f6df8
[ "Markdown", "Python" ]
3
Markdown
gabicavalcante/sensor-dashboard
23cf0990d737258b1599f65d881d2fab9d303060
849503a00057657a7120dcc7626f8b8792e79225
refs/heads/master
<file_sep>import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options class PythonOrgSearch(unittest.TestCase): def setUp(self): chrome_options = Options() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--headless") self.driver = webdriver.Chrome(options=chrome_options) def test_search_in_python_org_positive(self): driver = self.driver driver.get("https://www.python.org") self.assertIn("Python", driver.title) elem = driver.find_element_by_name("q") elem.send_keys("pycon") elem.send_keys(Keys.RETURN) assert "No results found." not in driver.page_source def test_search_in_python_org_negative(self): driver = self.driver driver.get("https://www.python.org") self.assertIn("Python", driver.title) elem = driver.find_element_by_name("q") elem.send_keys("missingkeyword") elem.send_keys(Keys.RETURN) assert "No results found." in driver.page_source def tearDown(self): #self.driver.quit() pass if __name__ == "__main__": unittest.main(verbosity=2) <file_sep># Selenium WebDriver - Example with GitHub Actions ![selenium-tests](https://github.com/nakov/selenium-webdriver-example/workflows/selenium-tests/badge.svg) Example of using Selenium WebDriver to automate Chrome Web browser from Python. Selenium tests are automatically executed when the code is changed. Testing is implemented as GitHub workflow, using GitHub Actions. ## Running the Example This app is based on "**poetry**" package manager for Python. First, install `poetry`. Then run the following commands: ``` poetry install ``` ``` poetry run python main.py ``` Try to comment uncomment the following lines, if Chrome fails to start: ``` chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--headless") ``` ## Source Code https://github.com/nakov/selenium-webdriver-example ## Automated Build in GitHub Actions https://github.com/nakov/selenium-webdriver-example/actions ## Live Example at Repl.it https://repl.it/@nakov/selenium-webdriver-example
1bbeb8677e25960ab827ad30c446d81192f75ed9
[ "Markdown", "Python" ]
2
Python
Krishnamurtyp/selenium-webdriver-example
aca6df4f4607e77870f28675e97f0e43e6208b71
764d156b5663066f4db1463cb415eeff6b6e5c9f
refs/heads/master
<file_sep>from django.http import HttpResponse def index(request): return HttpResponse("hello world your at poll index")
094692d7097d1a450debc10e04fd6bf170d49c50
[ "Python" ]
1
Python
shivapyin/polls
874ae7df97d0978a56ba3749bf7ebe0224b3eba9
f748705e5a21658098f2b56662988e619c7a1968
refs/heads/master
<file_sep>Vue.config.devtools = true; const vueApp = new Vue({ el: "#app", data: { inputSearchText : "", inputTextMess : "", activeOpacity : null, activeChat: { name: "", timesent : "", avatar : "", messages_list : [] }, users_list: [ { name: "Michele", timesent: "04/10/2021 09:00:00", avatar: "img/avatar_1.jpg", messages_list: [ { message: "Hello !", time_mess : "04/11/2021", sent: true, }, { message: "Hello. how are you?", time_mess : "04/11/2021", sent: false, }, ], }, { name: "Fabio", timesent: "04/10/2021 09:00:00", avatar: "img/avatar_2.jpg", messages_list: [ { message: "Ciao , Hai portato il cane fuori !", time_mess : "04/11/2021", sent: true, }, { message: "Si", time_mess : "04/11/2021", sent: false, }, ], }, { name: "Samuele", timesent: "04/10/2021 09:00:00", avatar: "img/avatar_3.jpg", messages_list: [] }, { name: "Luisa", timesent: "04/10/2021 09:00:00", avatar: "img/avatar_6.jpg", messages_list: [] }, { name: "Tim", timesent: "04/10/2021 09:00:00", avatar: "img/avatar_4.jpg", messages_list: [] }, { name: "Mario", timesent: "04/10/2021 09:00:00", avatar: "img/avatar_5.jpg", messages_list: [] }, { name: "Marco", timesent: "04/10/2021 09:00:00", avatar: "img/avatar_8.jpg", messages_list: [] }, ], }, methods: { chooseChat(chatToActivate, index) { this.activeChat = chatToActivate; this.activeOpacity = index; }, addNewMess(){ if(this.activeOpacity===null){ return; } if (this.inputTextMess.trim() === "") { return; } this.users_list[this.activeOpacity].messages_list.push({ message: this.inputTextMess, time_mess : "04/11/2021", sent: true, }); this.answerOk(); }, answerOk(){ setTimeout(() => { this.users_list[this.activeOpacity].messages_list.push({ message: "Ok", time_mess : "04/11/2021", sent: false, }); }, 1000); }, getNow: function() { const today = new Date(); const date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate(); const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds(); const dateTime = date +' '+ time; this.timestamp = dateTime; } }, mounted() { const focusToInput = document.getElementById("inputFocusSendMess"); focusToInput.focus(); const focusToSearchInput = document.getElementById("search-input"); focusToInput.focus(); }, // https://stackoverflow.com/questions/52558770/vuejs-search-filter computed: { filteredList() { return this.users_list.filter(user => { return user.name.toLowerCase().includes(this.inputSearchText.toLowerCase()) }) } } }); <file_sep>Vue.config.devtools = true; const vueApp = new Vue({ el: "#app", data: { inputTextMess : "", activeOpacity : null, activeChat: { name: "", timesent : "", avatar : "", messages_list : [] }, users_list: [ { name: "Michele", timesent: "04/10/2021 09:00:00", avatar: "img/avatar_1.jpg", messages_list: [ { message: "Hello !", time_mess : "04/11/2021", sent: true, }, { message: "Hello. how are you?", time_mess : "04/11/2021", sent: false, }, ], }, { name: "Fabio", timesent: "04/10/2021 09:00:00", avatar: "img/avatar_2.jpg", messages_list: [ { message: "Ciao , Hai portato il cane fuori !", time_mess : "04/11/2021", sent: true, }, { message: "Si", time_mess : "04/11/2021", sent: false, }, ], }, { name: "Samuele", timesent: "04/10/2021 09:00:00", avatar: "img/avatar_3.jpg", messages_list: [] }, { name: "Luisa", timesent: "04/10/2021 09:00:00", avatar: "img/avatar_6.jpg", messages_list: [] }, { name: "Tim", timesent: "04/10/2021 09:00:00", avatar: "img/avatar_4.jpg", messages_list: [] }, { name: "Mario", timesent: "04/10/2021 09:00:00", avatar: "img/avatar_5.jpg", messages_list: [] }, { name: "Marco", timesent: "04/10/2021 09:00:00", avatar: "img/avatar_8.jpg", messages_list: [] }, ], }, methods: { chooseChat(chatToActivate, index) { this.activeChat = chatToActivate; this.activeOpacity = index; }, addNewMess(){ if(this.activeOpacity===null){ return; } if (this.inputTextMess.trim() === "") { return; } this.users_list[this.activeOpacity].messages_list.push({ message: this.inputTextMess, time_mess : "04/11/2021", sent: true, }); this.answerOk(); }, answerOk(){ setTimeout(() => { this.users_list[this.activeOpacity].messages_list.push({ message: "Ok", time_mess : "04/11/2021", sent: false, }); }, 1000); } }, mounted() { const focusToInput = document.getElementById("inputFocusSendMess"); focusToInput.focus(); } });
d65d954c390c5035cd322259c9db569eeb6d5687
[ "JavaScript" ]
2
JavaScript
tastytim/vue-boolzapp
95258da0d706f6e437949e9fb2a9eb429eb95da7
435333599e0e8e7f719eabcae4c423444f8eec2c
refs/heads/master
<repo_name>vishakha111/movie_rental<file_sep>/src/component/movieform.jsx import React, { Component } from "react"; class MoviesDetails extends Component { handleSave = () => { //Navigate to /moviess // this.props.history.push('/movies'); this.props.history.replace('/movies'); }; render() { return ( <div> <h1>Movies Details -{this.props.match.params.id} </h1> <button onClick={this.handleSave}>Save</button> </div> ); } } export default MoviesDetails; <file_sep>/src/component/loginform1.jsx import React, { Component } from "react"; import Joi from "joi-browser"; class LoginForm extends Component { state = { account: { username: "", password: "" }, errors: {} }; schema = { username: Joi.string().required(), password: Joi.string().required() }; handleChange = e => { //console.log(e.currentTarget); const account = { ...this.state.account }; account[e.currentTarget.name] = e.currentTarget.value; this.setState({ account }); }; handleSubmit = e => { e.preventDefault(); const error = this.validate(); console.log(error); this.setState({ errors: error || {} }); //console.log(JSON.stringify(this.state)); if (error) return; //yet to be done }; validate = () => { const options = { abortEarly: false }; const { error } = Joi.validate(this.state.account, this.schema, options); if (!error) return null; const errors = {}; for (let item of error.details) { errors[item.path[0]] = item.message; } return errors; }; render() { return ( <React.Fragment> <h1>Login Form</h1> <form onSubmit={this.handleSubmit}> <div className="form-group"> <label htmlFor="username">Username</label> <input type="text" name="username" value={this.state.account.username} id="username" onChange={this.handleChange} className="form-control" /> {this.state.errors.username && ( <div className="alert alert-danger"> {this.state.errors.username} </div> )} </div> <div className="form-group"> <label htmlFor="password">Password</label> <input type="text" name="password" value={this.state.account.password} id="password" onChange={this.handleChange} className="form-control" /> {this.state.errors.password && ( <div className="alert alert-danger"> {this.state.errors.password} </div> )} </div> <button className="btn btn-primary">Login</button> </form> </React.Fragment> ); } } export default LoginForm;
810666e9da27415b3aad6d105a65341284a8b2d2
[ "JavaScript" ]
2
JavaScript
vishakha111/movie_rental
b44894065df9d6f817e50295b59d913927a2cb4b
a4eedafc6d2bd198cd93b11b9b29cab1e7aa694f
refs/heads/master
<repo_name>magidmroueh/scout-apm-laravel<file_sep>/src/Listeners/QueryExecutedListener.php <?php declare(strict_types=1); namespace Scoutapm\Laravel\Listeners; use Illuminate\Database\Events\QueryExecuted; use Scoutapm\Laravel\Database\QueryListener; use Scoutapm\ScoutApmAgent; use function microtime; class QueryExecutedListener { /** * @var ScoutApmAgent */ private $agent; public function __construct(ScoutApmAgent $agent) { $this->agent = $agent; } public function handle(QueryExecuted $queryExecuted) { (new QueryListener($this->agent))->__invoke($queryExecuted); } } <file_sep>/src/Middleware/ActionInstrument.php <?php declare(strict_types=1); namespace Scoutapm\Laravel\Middleware; use Closure; use Illuminate\Http\Request; use Laravel\Lumen\Routing\Router; use Scoutapm\Events\Span\Span; use Scoutapm\Logger\FilteredLogLevelDecorator; use Scoutapm\ScoutApmAgent; use Throwable; final class ActionInstrument { /** @var ScoutApmAgent */ private $agent; /** @var FilteredLogLevelDecorator */ private $logger; /** @var Router */ private $router; public function __construct(ScoutApmAgent $agent, FilteredLogLevelDecorator $logger, Router $router) { $this->agent = $agent; $this->logger = $logger; $this->router = $router; } /** * @return mixed * * @throws Throwable */ public function handle(Request $request, Closure $next) { $this->logger->debug('Handle ActionInstrument'); return $this->agent->webTransaction( 'unknown', /** @return mixed */ function (Span $span) use ($request, $next) { try { $response = $next($request); } catch (Throwable $e) { $this->agent->tagRequest('error', 'true'); throw $e; } $span->updateName($this->automaticallyDetermineControllerName($request)); return $response; } ); } /** * Lumen uses a different router, so... */ private function automaticallyDetermineControllerName(Request $request) : string { $name = 'unknown'; try { $router = $this->router; $method = $request->getMethod(); $pathInfo = $request->getPathInfo(); $routes = $router->getRoutes(); $matchedRoute = null; foreach ($routes as $route => $data) { $route = preg_replace("%\{.*?\}%", "([^/]+?)", $route); if (preg_match("%^{$route}$%", $method.$pathInfo)) { $matchedRoute = $data; break; } } if ($matchedRoute !== null) { $name = $matchedRoute['action']['as'] ?? $matchedRoute['action']['uses']; } } catch (Throwable $e) { $this->logger->debug( 'Exception obtaining name of endpoint: ' . $e->getMessage(), ['exception' => $e] ); } return 'Controller/' . $name; } }
bf13dfd23c9f82dce6d4415d7bcf1de216088372
[ "PHP" ]
2
PHP
magidmroueh/scout-apm-laravel
31b22e9be90fedfea867ffc0d01b21ee479827e1
8e0d03eea822ee62f73caa87dc84fa43bb7675a7
refs/heads/master
<repo_name>fikisyihab72/WebFilm-Codeigniter<file_sep>/application/controllers/Mahasiswa.php <?php /** * */ class Mahasiswa extends CI_Controller // Mahasiswa = harus sama dengan nama file // enxtend tergantung kegunaan class CI_Controller { function __construct() { parent::__construct(); $this->load->model('Model_mahasiswa','mhs'); //mhs = alias, biar pendek $this->load->model('Model_film','flm'); error_reporting(0); } function index() // diganti dengan index sebelumnya default code { if(!isset($this->session->login_status)) { $this->load->view('view_login'); } else { if($this->session->role=="admin"){ $data = $this->flm->read(); $this->load->view('view_admin',array('data' => $data)); } else{ $data = $this->flm->read(); $this->load->view('view_home',array('data' => $data)); //fungsi yang dimiliki CI_Controller } } } function insert_mahasiswa() { $nama=$this->input->post('nama'); $nim=$this->input->post('nim'); $data = array( 'nama'=>$nama, 'nim'=>$nim ); //array asosiatif agar semua data jadi 1 array, di model_mahasiswa cuma 1 parameter (function insert($data)) $cek = $this->mhs->insert($data); // pakai array asosiatif biar ga ribet $data1, $data2, $data3..... if($cek>0) { echo "<script type='text/javascript'>alert('Berhasil Ditambah');</script>"; //$this->load->view('view_dashboard'); sama dengan redirect //redirect(base_url('index.php/Mahasiswa?m=sukses')); $this->index(); } } function delete_mahasiswa() { $id = $this->input->get('id'); //pakai get karena dari view dilempar pakai '?id=' jadi nampak di url $cek = $this->mhs->delete($id); if($cek>0){ echo "<script type='text/javascript'>alert('Berhasil Dihapus');</script>"; $this->index(); } } function update_mahasiswa() //digunakan untuk mengambil data dan ditampilkan di view_formedit.php { $id = $this->input->get('id'); //get id yg diinginkan $data = $this->mhs->getDataById($id); //mengambil data dari database berdasar id diatas $this->load->view('view_formedit',array('data'=>$data)); } function update_proses() //proses saat di pencet tombol Edit { $id = $this->input->post('id'); $nama = $this->input->post('nama'); $nim = $this->input->post('nim'); $data = array( // dijadikan array asosiatif dulu sebelum di kirim ke model 'id' => $id, 'nama' => $nama, 'nim' => $nim ); $cek = $this->mhs->update($id,$data); if($cek){ echo "<script type='text/javascript'>alert('Berhasil Diedit');</script>"; $this->index(); } else{ echo "<script type='text/javascript'>alert('Gagal Diedit');</script>"; $this->index(); } } function login() { $data['nama'] = $this->input->post('username'); $data['nim'] = $this->input->post('password'); $data['role'] = $this->input->post('role'); $cek = $this->mhs->getLogin($data); if($cek->num_rows() > 0) //mengecek apakah ada data username dan passowrd di DB, menampilkan brp byk data yg ada di DB { $data_session = array( 'username' => $data['nama'], 'role' => $data['role'], 'login_status' => TRUE ); $this->session->set_userdata($data_session); $this->index(); } else { $this->index(); } } function logout() { unset($_SESSION['username']); unset($_SESSION['role']); unset($_SESSION['login_status']); $this->index(); } function masuk() { $this->load->view('view_login'); } } ?><file_sep>/application/controllers/Film.php <?php /** * */ class Film extends CI_Controller // Mahasiswa = harus sama dengan nama file // enxtend tergantung kegunaan class CI_Controller { function __construct() { parent::__construct(); $this->load->model('Model_film','flm'); //mhs = alias, biar pendek $this->load->helper(array('form', 'url')); $this->load->library('upload'); } function index() // diganti dengan index sebelumnya default code { if(!isset($this->session->login_status)) { $this->load->view('view_login'); } else { if($_SESSION['username']=="admin"){ $data = $this->flm->read(); $this->load->view('view_admin',array('data' => $data)); } else{ $data = $this->flm->read(); $this->load->view('view_home',array('data' => $data)); //fungsi yang dimiliki CI_Controller } } } function insert_mahasiswa() { $id_film=$this->input->post('id_film'); $nama_film=$this->input->post('nama_film'); $kategori =$this->input->post('kategori'); $rating =$this->input->post('rating'); $tgl_rilis =$this->input->post('tgl_rilis'); $produksi =$this->input->post('produksi'); $sinopsis =$this->input->post('sinopsis'); $durasi =$this->input->post('durasi'); $trailer =$this->input->post('trailer'); $trailer2 = str_replace("watch?v=", "embed/", $trailer); // get foto $config['upload_path'] = './assets/images/gambar'; $config['allowed_types'] = 'jpg|png|jpeg|gif'; $config['max_size'] = '2048'; //2MB max $config['max_width'] = '4480'; // pixel $config['max_height'] = '4480'; // pixel $config['file_name'] = $_FILES['fotopost']['name']; $this->upload->initialize($config); if (!empty($_FILES['fotopost']['name'])) { if ( $this->upload->do_upload('fotopost') ) { $foto = $this->upload->data(); $data = array( 'nama_film'=>$nama_film, 'kategori'=>$kategori, 'rating'=>$rating, 'tgl_rilis'=>$tgl_rilis, 'produksi'=>$produksi, 'sinopsis'=>$sinopsis, 'durasi'=>$durasi, 'trailer'=>$trailer2, 'gambar' => $foto['file_name'] ); $cek = $this->flm->insert($data); redirect(''); }else { die("gagal upload"); } }else { echo "tidak masuk"; } //array asosiatif agar semua data jadi 1 array, di model_mahasiswa cuma 1 parameter (function insert($data)) // pakai array asosiatif biar ga ribet $data1, $data2, $data3..... if($cek>0) { echo "<script type='text/javascript'>alert('Berhasil Ditambah');</script>"; //$this->load->view('view_dashboard'); sama dengan redirect //redirect(base_url('index.php/Mahasiswa?m=sukses')); $this->tambah(); } } function delete_mahasiswa() { $id_film = $this->input->get('id_film'); //pakai get karena dari view dilempar pakai '?id=' jadi nampak di url $cek = $this->flm->delete($id_film); if($cek>0){ //echo "<script type='text/javascript'>alert('Berhasil Dihapus');</script>"; $this->admin(); } } function delete_kelola() { $id = $this->input->get('id'); //pakai get karena dari view dilempar pakai '?id=' jadi nampak di url $cek = $this->flm->deleteKelola($id); if($cek>0){ //echo "<script type='text/javascript'>alert('Berhasil Dihapus');</script>"; $data = $this->flm->readKelola(); $this->load->view('view_kelola',array('data' => $data)); } } function update_mahasiswa() //digunakan untuk mengambil data dan ditampilkan di view_formedit.php { $id_film = $this->input->get('id_film'); //get id yg diinginkan $data = $this->flm->getDataById($id_film); //mengambil data dari database berdasar id diatas $this->load->view('view_detail',array('data'=>$data)); } function update_mahasiswa2() //digunakan untuk mengambil data dan ditampilkan di view_formedit.php { $id_film = $this->input->get('id_film'); //get id yg diinginkan $data = $this->flm->getDataById($id_film); //mengambil data dari database berdasar id diatas $this->load->view('view_formedit',array('data'=>$data)); } function update_kelola() //digunakan untuk mengambil data dan ditampilkan di view_formedit.php { $id = $this->input->get('id'); //get id yg diinginkan $data = $this->flm->getDataById_kelola($id); //mengambil data dari database berdasar id diatas $this->load->view('view_formedit_kelola',array('data'=>$data)); } function update_proses() //proses saat di pencet tombol Edit { $id_film=$this->input->post('id_film'); $nama_film=$this->input->post('nama_film'); $kategori =$this->input->post('kategori'); $rating =$this->input->post('rating'); $tgl_rilis =$this->input->post('tgl_rilis'); $produksi =$this->input->post('produksi'); $sinopsis =$this->input->post('sinopsis'); $durasi =$this->input->post('durasi'); $trailer =$this->input->post('trailer'); $trailer2 = str_replace("watch?v=", "embed/", $trailer); $path = './assets/images/gambar/'; // get foto $config['upload_path'] = './assets/images/gambar'; $config['allowed_types'] = 'jpg|png|jpeg|gif'; $config['max_size'] = '2048'; //2MB max $config['max_width'] = '4480'; // pixel $config['max_height'] = '4480'; // pixel $config['file_name'] = $_FILES['fotopost']['name']; $this->upload->initialize($config); if (!empty($_FILES['fotopost']['name'])) { if ( $this->upload->do_upload('fotopost') ) { $foto = $this->upload->data(); $data = array( 'nama_film'=>$nama_film, 'kategori'=>$kategori, 'rating'=>$rating, 'tgl_rilis'=>$tgl_rilis, 'produksi'=>$produksi, 'sinopsis'=>$sinopsis, 'durasi'=>$durasi, 'trailer'=>$trailer2, 'gambar'=> $foto['file_name'] ); // hapus foto pada direktori @unlink($path.$this->input->post('filelama')); $cek = $this->flm->update($id_film,$data); $this->index(); }else { die("gagal update"); } }else { echo "tidak masuk"; } } function update_proses_kelola() //proses saat di pencet tombol Edit { $id = $this->input->post('id'); $nama = $this->input->post('nama'); $nim = $this->input->post('nim'); $role = $this->input->post('role'); $data = array( // dijadikan array asosiatif dulu sebelum di kirim ke model 'id' => $id, 'nama' => $nama, 'nim' => $nim, 'role' => $role ); $cek = $this->flm->update_kelola($id,$data); if($cek){ $data = $this->flm->readKelola(); $this->load->view('view_kelola',array('data' => $data)); } else{ echo "<script type='text/javascript'>alert('Gagal Diedit');</script>"; $data = $this->flm->readKelola(); $this->load->view('view_kelola',array('data' => $data)); } } function login() { $data['nama'] = $this->input->post('username'); $data['nim'] = $this->input->post('password'); $cek = $this->flm->getLogin($data); if($cek->num_rows() > 0) //mengecek apakah ada data username dan passowrd di DB, menampilkan brp byk data yg ada di DB { $data_session = array( 'username' => $data['nama'], 'login_status' => TRUE ); $this->session->set_userdata($data_session); $this->index(); } else { $this->index(); } } function logout() { unset($_SESSION['username']); unset($_SESSION['login_status']); $this->index(); } function admin() { $data = $this->flm->read(); $this->load->view('view_admin',array('data' => $data)); } function tambah() { $this->load->view('view_tambah'); } function kategori(){ $kategori = $this->input->get('kategori'); //get id yg diinginkan $data = $this->flm->getKategori($kategori); //mengambil data dari database berdasar id diatas $this->load->view('view_kategori',array('data'=>$data)); } function kelola() { $data = $this->flm->readKelola(); $this->load->view('view_kelola',array('data' => $data)); } } ?><file_sep>/application/views/view_detail.php <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/css/style.css"> <title>Detail Film</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #1F2533; color: white;"> <div class="container"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo01"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li> <a class="navbar-brand" href="<?php echo base_url('index.php/Film');?>" style="color: white; font-weight: bold;">CinemaTV</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="color: white;"> Kategori </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="<?php echo base_url('index.php/Film/kategori?kategori=Anime'); ?>">Anime</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> </ul> </div> <ul class="navbar-nav mr-auto mt-2 mt-lg-0" style="list-style: none;"> <li class="nav-item"> <a class="nav-link" href="#" style="color: white; font-size: 20px; border: 4px;">Hey, <?php echo $_SESSION['username']; ?>!</a> </li> <li class="nav-item"> <a class="nav-link" href="<?php echo base_url('index.php/Mahasiswa/logout'); ?>"><button type="button" class="btn btn-outline-danger">LOGOUT</button></a> </li> </ul> </div> </nav> <form action="<?php echo base_url('index.php/Film/update_proses'); ?>" method="POST"> <!-- base url hanya bisa di php --> <?php foreach($data as $flm){ ?> <div class="container"> <div class="row"> <div class="col-sm-12"> <iframe width="1100" height="500" src="<?php echo $flm->trailer;?>?autoplay=1" allow="autoplay;"> </iframe> </div> <div class="row"> <div class="col-sm-3"> <img src="http://localhost/editci/assets/images/gambar/<?php echo $flm->gambar;?>" width="100%"> </div> <div class="col-sm-9"> <table class="table"> <thead class="thead-dark"> <th colspan="3" style="text-align: center;">DESKRIPSI</th> </thead> <tr> <td>Nama</td> <td>:</td> <td> <?php echo $flm->nama_film; ?></td> </tr> <tr> <td>Kategori</td> <td>:</td> <td><?php echo $flm->kategori; ?></td> </tr> <tr> <td>Rating</td> <td>:</td> <td><?php echo $flm->rating; ?></td> </tr> <tr> <td>Rilis</td> <td>:</td> <td><?php echo $flm->tgl_rilis; ?></td> </tr> <tr> <td>Produksi</td> <td>:</td> <td><?php echo $flm->produksi; ?></td> </tr> <tr> <td>Durasi</td> <td>:</td> <td><?php echo $flm->durasi; ?></td> </tr> <tr> <td>Sinopsis</td> <td>:</td> <td><?php echo $flm->sinopsis; ?></td> </tr> </table> </div> </div> </div> <?php } ?> </div> </form> <footer id="sticky-footer"> <div class="container text-center" > <small>Copyright &copy; CinemaTV</small> </div> </footer> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html> <file_sep>/application/views/view_kelola.php <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/css/style.css"> <title>Admin</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #1F2533; color: white;"> <div class="container"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo01"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li> <a class="navbar-brand" href="<?php echo base_url('index.php/Film/admin');?>" style="color: white; font-weight: bold;">ADMIN PANEL</a> </li> </ul> </div> <ul class="navbar-nav mr-auto mt-2 mt-lg-0" style="list-style: none;"> <li class="nav-item"> <a class="nav-link" href="#" style="color: white; font-size: 20px; border: 4px;">Hey, <?php echo $_SESSION['username']; ?>!</a> </li> <li class="nav-item"> <a class="nav-link" href="<?php echo base_url('index.php/Mahasiswa/logout'); ?>"><button type="button" class="btn btn-outline-danger">LOGOUT</button></a> </li> </ul> </div> </nav> <div class="container-fluid"> <a href="<?php echo base_url('index.php/Film/kelola'); ?>"><button type="button" class="btn btn-outline-dark" >KELOLA DATA PENGGUNA</button></a> <table class="table table-striped" style="text-align: center;"> <thead class="thead-dark"> <th>ID</th> <th>Username</th> <th>Password</th> <th>Role</th> <th>Aksi</th> </thead> <?php $no = 1; foreach($data as $flm){ ?> <tr> <td><?php echo $flm->id; ?></td> <td><?php echo $flm->nama; ?></td> <td><?php echo $flm->nim; ?></td> <td><?php echo $flm->role; ?></td> <td> <a href="<?php echo base_url('index.php/Film/update_kelola?id=').$flm->id; ?>"><button type="button" class="btn btn-warning">EDIT</button></a> <a href="<?php echo base_url('index.php/Film/delete_kelola?id=').$flm->id; ?>"><button type="button" class="btn btn-danger">DELETE</button></a> </td> </tr> <?php $no++; } ?> </table> </div> <footer id="sticky-footer"> <div class="container text-center" > <small>Copyright &copy; CinemaTV</small> </div> </footer> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html><file_sep>/application/models/Model_film.php <?php /** * */ class Model_film extends CI_Model { function insert($data) //$data = array asosiatif { return $this->db->insert('film',$data); } function read() { $this->db->select('*'); $this->db->from('film'); return $this->db->get()->result(); } function readKelola() { $this->db->select('*'); $this->db->from('akun'); return $this->db->get()->result(); } function delete($id_film) { $this->db->where('id_film',$id_film); return $this->db->delete('film'); } function deleteKelola($id) { $this->db->where('id',$id); return $this->db->delete('akun'); } function getDataById($id) //digunakan untuk menampilkan data dari databse ke view_formedit.php { $this->db->select('*'); $this->db->from('film'); $this->db->where('id_film',$id); return $this->db->get()->result(); } function getDataById_kelola($id) //digunakan untuk menampilkan data dari databse ke view_formedit.php { $this->db->select('*'); $this->db->from('akun'); $this->db->where('id',$id); return $this->db->get()->result(); } function update($id_film, $data) { $this->db->where('id_film',$id_film); $this->db->update('film',$data); return $this->db->affected_rows(); //fungsinya untuk memberikan informasi berapa banyak row yang berubah } function update_kelola($id, $data) { $this->db->where('id',$id); $this->db->update('akun',$data); return $this->db->affected_rows(); //fungsinya untuk memberikan informasi berapa banyak row yang berubah } function getLogin($data) { return $this->db->get_where('film',$data); } function getKategori($kategori) //digunakan untuk menampilkan data dari databse ke view_formedit.php { $this->db->select('*'); $this->db->from('film'); $this->db->where('kategori',$kategori); return $this->db->get()->result(); } } ?><file_sep>/application/views/view_home.php <!-- https://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg --> <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY> crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/css/style.css"> <title>CinemaTV</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #1F2533; color: white;"> <div class="container"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo01"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li> <a class="navbar-brand" href="<?php echo base_url('index.php/Film');?>" style="color: white; font-weight: bold;">CinemaTV</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="color: white;"> Kategori </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="<?php echo base_url('index.php/Film/kategori?kategori=Anime'); ?>">Anime</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> </ul> </div> <ul class="navbar-nav mr-auto mt-2 mt-lg-0" style="list-style: none;"> <li class="nav-item"> <a class="nav-link" href="#" style="color: white; font-size: 20px; border: 4px;">Hey, <?php echo $_SESSION['username']; ?>!</a> </li> <li class="nav-item"> <a class="nav-link" href="<?php echo base_url('index.php/Mahasiswa/logout'); ?>"><button type="button" class="btn btn-outline-danger">LOGOUT</button></a> </li> </ul> </div> </nav> <hr> <div class="container"> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="<?php echo base_url(); ?>/assets/images/gambar/gambar1.jpg" alt="First slide"> <div class="carousel-caption d-none d-md-block"> <h5>Welcome to CinemaTV</h5> <p>Just a normal movie database</p> </div> </div> <div class="carousel-item"> <img class="d-block w-100" src="<?php echo base_url(); ?>/assets/images/gambar/gambar0.jpg" alt="Second slide"> <div class="carousel-caption d-none d-md-block"> <h5>Dont forget to eat healty!</h5> <p>Cabbage boy</p> </div> </div> <div class="carousel-item"> <img class="d-block w-100" src="<?php echo base_url(); ?>/assets/images/gambar/gambar3.jpg" alt="Third slide"> <div class="carousel-caption d-none d-md-block"> <h5>1 2 3 Count on me</h5> <p>Listen up i will stand out by my own</p> </div> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <hr> <center> <div class="col-sm-6"> <!-- <input type="" name="" value="MOVIE SELECTION" style="text-align: center; font-size: 40px; font-family: helvetica; border-width: 0px;" readonly> --> <img src="<?php echo base_url(); ?>/assets/images/gambar/selection.gif"> </div> </center> <hr> <div class="row"> <?php $no = 1; foreach($data as $flm){ ?> <div class="col-sm-3"> <div class="thumbnail"> <a id="aa" href=""> <img src="http://localhost/editci/assets/images/gambar/<?php echo $flm->gambar;?>" width="90%"> </a> </div> <div class="judul" style="font-weight: bold;"> <input type="text" name="judul" value="<?php echo $flm->nama_film; ?>" style="font-weight: bold; text-align: center; border-width: 0px;" readonly > </div> <div class="detail"> <a href="<?php echo base_url('index.php/Film/update_mahasiswa?id_film=').$flm->id_film; ?>"><button type="button" class="btn btn-danger btn-lg btn-block ">DETAIL</button> </a> </div> </div> <?php $no++; } ?> </div> </div> <footer id="sticky-footer"> <div class="container text-center" > <small>Copyright &copy; CinemaTV</small> </div> </footer> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html><file_sep>/application/views/view_login.php <!DOCTYPE html> <html lang="en"> <head> <title>CinemaTV</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--===============================================================================================--> <link rel="icon" type="image/png" href="<?php echo base_url(); ?>/assets/images/icons/favicon.ico"/> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/vendor/bootstrap/css/bootstrap.min.css"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/fonts/font-awesome-4.7.0/css/font-awesome.min.css"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/fonts/Linearicons-Free-v1.0.0/icon-font.min.css"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/vendor/animate/animate.css"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/vendor/css-hamburgers/hamburgers.min.css"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/vendor/animsition/css/animsition.min.css"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/vendor/select2/select2.min.css"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/vendor/daterangepicker/daterangepicker.css"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/css/util.css"> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/css/main.css"> <!--===============================================================================================--> </head> <body style="padding-top: 50px;"> <div class="container" > <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-item nav-link active" id="nav-home-tab" data-toggle="tab" href="#nav-home" role="tab" aria-controls="nav-home" aria-selected="true" style="background-color: #1F2533; color: white;">Login</a> <a class="nav-item nav-link" id="nav-profile-tab" data-toggle="tab" href="#nav-profile" role="tab" aria-controls="nav-profile" aria-selected="false" style="background-color: #1F2533; color: white;">Register</a> </div> </nav> <div class="tab-content" id="nav-tabContent" style="background-color: white;"> <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab"> <div class="limiter"> <div class="container-login100" style="background-color: #1F2533;"> <div class="wrap-login100 p-l-55 p-r-55 p-t-65 p-b-50"> <form class="login100-form validate-form" action="<?php echo base_url('index.php/Mahasiswa/login') ?>" method="post"> <span class="login100-form-title p-b-33"> Account Login </span> <div class="wrap-input100 validate-input" data-validate = "Valid email is required: <EMAIL>"> <input class="input100" type="text" name="username" placeholder="Username"> <span class="focus-input100-1"></span> <span class="focus-input100-2"></span> </div> <div class="wrap-input100 rs1 validate-input" data-validate="Password is required"> <input class="input100" type="password" name="password" placeholder="<PASSWORD>"> <span class="focus-input100-1"></span> <span class="focus-input100-2"></span> </div> <select class="form-control" name="role" placeholder> <option value="user">User</option> <option value="admin">Admin</option> </select> <div class="container-login100-form-btn m-t-20"> <button class="login100-form-btn" style="background-color: red;"> LOGIN </button> </div> </form> </div> </div> </div> </div> <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab"> <div class="limiter"> <div class="container-login100" style="background-color: #1F2533;"> <div class="wrap-login100 p-l-55 p-r-55 p-t-65 p-b-50"> <form action="<?php echo base_url('index.php/Mahasiswa/insert_mahasiswa') ?>" method="POST"> <!-- base url hanya bisa di php --> <span class="login100-form-title p-b-33"> Registration </span> <div class="wrap-input100 validate-input"> <input class="input100" type="text" name="nama" placeholder="Username"> <span class="focus-input100-1"></span> <span class="focus-input100-2"></span> </div> <div class="wrap-input100 validate-input"> <input class="input100" type="password" name="nim" placeholder="<PASSWORD>"> <span class="focus-input100-1"></span> <span class="focus-input100-2"></span> </div> <div class="wrap-input100 validate-input" data-validate = "Valid email is required: <EMAIL>"> <input class="input100" type="email" name="email" placeholder="<EMAIL>"> <span class="focus-input100-1"></span> <span class="focus-input100-2"></span> </div> <div class="container-login100-form-btn m-t-20"> <button class="login100-form-btn" style="background-color: red;"> SIGN UP </button> </div> </form> </div> </div> </div> </div> </div> <!--===============================================================================================--> <script src="<?php echo base_url(); ?>/assets/vendor/jquery/jquery-3.2.1.min.js"></script> <!--===============================================================================================--> <script src="<?php echo base_url(); ?>/assets/vendor/animsition/js/animsition.min.js"></script> <!--===============================================================================================--> <script src="<?php echo base_url(); ?>/assets/vendor/bootstrap/js/popper.js"></script> <script src="<?php echo base_url(); ?>/assets/vendor/bootstrap/js/bootstrap.min.js"></script> <!--===============================================================================================--> <script src="<?php echo base_url(); ?>/assets/vendor/select2/select2.min.js"></script> <!--===============================================================================================--> <script src="<?php echo base_url(); ?>/assets/vendor/daterangepicker/moment.min.js"></script> <script src="<?php echo base_url(); ?>/assets/vendor/daterangepicker/daterangepicker.js"></script> <!--===============================================================================================--> <script src="<?php echo base_url(); ?>/assets/vendor/countdowntime/countdowntime.js"></script> <!--===============================================================================================--> <script src="<?php echo base_url(); ?>/assets/s/main.js"></script> </body> </html><file_sep>/application/views/view_formedit_kelola.php <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/css/style.css"> <title>Tambah Data</title> </head> <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #1F2533; color: white;"> <div class="container"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo01"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li> <a class="navbar-brand" href="<?php echo base_url('index.php/Film/admin');?>" style="color: white; font-weight: bold;">ADMIN PANEL</a> </li> </ul> </div> <ul class="navbar-nav mr-auto mt-2 mt-lg-0" style="list-style: none;"> <li class="nav-item"> <a class="nav-link" href="#" style="color: white; font-size: 20px; border: 4px;">Hey, <?php echo $_SESSION['username']; ?>!</a> </li> <li class="nav-item"> <a class="nav-link" href="<?php echo base_url('index.php/Mahasiswa/logout'); ?>"><button type="button" class="btn btn-outline-danger">LOGOUT</button></a> </li> </ul> </div> </nav> <div class="container"> <body> <?php foreach($data as $flm){ ?> <form action="<?php echo base_url('index.php/Film/update_proses_kelola'); ?>" method="POST" enctype="multipart/form-data"> <!-- base url hanya bisa di php --> <div class="form-group"> <label for="inputName3" class="col-sm-2 col-form-label">ID User</label> <div class="col-sm-10"> <input type="text" class="form-control" name="id" placeholder="ID" value="<?php echo $flm->id; ?>" readonly> </div> </div> <div class="form-group"> <label for="inputName3" class="col-sm-2 col-form-label">Nama Film</label> <div class="col-sm-10"> <input type="text" class="form-control" name="nama" placeholder="Nama Film" value="<?php echo $flm->nama; ?>"> </div> </div> <div class="form-group"> <label for="inputName3" class="col-sm-2 col-form-label">Password</label> <div class="col-sm-10"> <input type="text" class="form-control" name="nim" placeholder="Password" value="<?php echo $flm->nim; ?>"> </div> </div> <div class="form-group"> <label for="inputName3" class="col-sm-2 col-form-label">Role</label> <div class="col-sm-10"> <select class="form-control" name="role"> <option value="user">User</option> <option value="admin">Admin</option> </select> </div> </div> <?php } ?> <div class="col-sm-6"> <button type="submit" class="btn btn-warning">Update</button> </div> </form> </div> <footer id="sticky-footer"> <div class="container text-center" > <small>Copyright &copy; CinemaTV</small> </div> </footer> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html> <file_sep>/application/views/view_admin.php <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/css/style.css"> <title>Admin</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #1F2533; color: white;"> <div class="container"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo01"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li> <a class="navbar-brand" href="<?php echo base_url('index.php/Film/admin');?>" style="color: white; font-weight: bold;">ADMIN PANEL</a> </li> </ul> </div> <ul class="navbar-nav mr-auto mt-2 mt-lg-0" style="list-style: none;"> <li class="nav-item"> <a class="nav-link" href="#" style="color: white; font-size: 20px; border: 4px;">Hey, <?php echo $_SESSION['username']; ?>!</a> </li> <li class="nav-item"> <a class="nav-link" href="<?php echo base_url('index.php/Mahasiswa/logout'); ?>"><button type="button" class="btn btn-outline-danger">LOGOUT</button></a> </li> </ul> </div> </nav> <div class="container-fluid"> <a href="<?php echo base_url('index.php/Film/tambah'); ?>"><button type="button" class="btn btn-outline-success" >TAMBAH DATA FILM</button></a> <a href="<?php echo base_url('index.php/Film/kelola'); ?>"><button type="button" class="btn btn-outline-dark" >KELOLA DATA PENGGUNA</button></a> <table class="table table-striped" style="text-align: center;"> <thead class="thead-dark"> <th>No</th> <th>Nama Film</th> <th>Kategori</th> <th>Rating</th> <th>Tanggal Rilis</th> <th>Produksi</th> <th>Sinopsis</th> <th>Durasi</th> <th>Trailer</th> <th>Gambar</th> <th>Aksi</th> </thead> <?php $no = 1; foreach($data as $flm){ ?> <tr> <td><?php echo $no; ?></td> <td><?php echo $flm->nama_film; ?></td> <td><?php echo $flm->kategori; ?></td> <td><?php echo $flm->rating; ?></td> <td><?php echo $flm->tgl_rilis; ?></td> <td><?php echo $flm->produksi; ?></td> <td><?php echo $flm->sinopsis; ?></td> <td><?php echo $flm->durasi; ?></td> <td><?php echo $flm->trailer; ?></td> <td><img src="http://localhost/editci/assets/images/gambar/<?php echo $flm->gambar;?>" width="105px" height="152px"></td> <td> <a href="<?php echo base_url('index.php/Film/update_mahasiswa2?id_film=').$flm->id_film; ?>"><button type="button" class="btn btn-warning">EDIT</button></a> <a href="<?php echo base_url('index.php/Film/delete_mahasiswa?id_film=').$flm->id_film; ?>"><button type="button" class="btn btn-danger">DELETE</button></a> </td> </tr> <?php $no++; } ?> </table> </div> <footer id="sticky-footer"> <div class="container text-center" > <small>Copyright &copy; CinemaTV</small> </div> </footer> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html>
69304ba43b177485c04974bd3bcde8f8c6eb5518
[ "PHP" ]
9
PHP
fikisyihab72/WebFilm-Codeigniter
b5fdfec6d7a97e866bd3a8a530aac43afd18e1af
c2b6df1b8c67c15e21b2a928b635a44f35a59e6b
refs/heads/master
<repo_name>yzxdmb01/Weather<file_sep>/app/src/main/java/com/jr/weather/bean/RequestParams.java package com.jr.weather.bean; import android.net.Uri; import android.util.SparseArray; import java.io.File; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * //请求参数 * 文件先不管 * Created by Administrator on 2016-11-11. */ public class RequestParams { public LinkedHashMap<String, String> getParams() { return params; } public void setParams(LinkedHashMap<String, String> params) { this.params = params; } private LinkedHashMap<String, String> params = new LinkedHashMap<>(); public RequestParams add(String key, String val) { params.put(key, val); return this; } public String append2Url(String url) { if (params == null || params.size() <= 0) { return url; } else { Uri.Builder uriBuilder = Uri.parse(url).buildUpon(); for (Map.Entry<String, String> entry : params.entrySet()) { uriBuilder.appendQueryParameter(entry.getKey(), entry.getValue()); } return uriBuilder.build().toString(); } } } <file_sep>/README.md # Weather okhttp3+glide+mvp <file_sep>/app/src/main/java/com/jr/weather/util/HttpsUtils.java package com.jr.weather.util; import com.google.gson.Gson; import com.jr.weather.base.BaseApplication; import com.jr.weather.base.BaseCallBack; import com.jr.weather.bean.RequestParams; import java.io.IOException; import java.lang.reflect.Type; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * 网络请求 * 可以设置不同的请求超时等 * Created by Administrator on 2016-11-11. */ public class HttpsUtils { private static final long CONNECT_TIMEOUT = 10 * 1000l; private static OkHttpClient okHttpClient; private static HttpsUtils mInstance; private static int cacheSize = 10 * 1024 * 1024; private static Cache cache = new Cache(BaseApplication.getContext().getCacheDir(), cacheSize); public HttpsUtils(OkHttpClient okHttpClient) { if (okHttpClient == null) { this.okHttpClient = new OkHttpClient.Builder().cache(cache). connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS).build(); } else { this.okHttpClient = okHttpClient; } } public static HttpsUtils getInstance() { return initHttpsUtils(null); } private static HttpsUtils initHttpsUtils(OkHttpClient okHttpClient) { /*正常的单例写法*/ if (mInstance == null) { synchronized (HttpsUtils.class) { if (mInstance == null) { mInstance = new HttpsUtils(okHttpClient); } } } return mInstance; } public OkHttpClient getOkHttpClient() { return okHttpClient; } //get方法 //先想用法HttpsUtils.get(url,params,callback); public static void get(String url, RequestParams params, BaseCallBack callBack) { url = params.append2Url(url); Request request = new Request.Builder().url(url).get().build(); if (callBack == null) { callBack = BaseCallBack.CALLBACK_DEFAULT; } BaseCallBack finalCallBack = callBack; okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { finalCallBack.onError(e); } @Override public void onResponse(Call call, Response response) throws IOException { if (finalCallBack.type == String.class) { finalCallBack.onResponse(response.body().string()); } else { try { Object o = parseResponse(response.body().string(), finalCallBack.type); finalCallBack.onResponse(o); } catch (Exception e) { e.printStackTrace(); finalCallBack.onError(e); } } } }); } private static Object parseResponse(String response, Type type) throws Exception { Gson gson = new Gson(); Object o = gson.fromJson(response, type); return o; } }
64810dc29ec9ab98899855bcdbf49b7c84d3bf60
[ "Markdown", "Java" ]
3
Java
yzxdmb01/Weather
afae049f15950885a9215b310b72b993e23e58c1
422ceddd1202ea6f253ac36897eb22730b73fd86
refs/heads/main
<file_sep>library("optimbase") mytranspose <- function(x) { if (is.vector(x)== T ){ y <- transpose(x) } else if (is.matrix(x)==T){ y <- matrix(1, nrow=ncol(x), ncol = nrow(x)) if( ncol(x) == 0 || nrow(x)==0){ return(x) break } for(i in 1:nrow(x)) { for(j in 1:ncol(x)) { y[j,i] <- x[i,j] } } } else if (is.null(x)==T){ y <- x } else{ y <- as.data.frame(t(as.matrix(x))) } return(y) } mytest <- function(x){ if (length(x)==0){ print("nothing") } else if(is.na(x)==T){ print("NA") } else if(mytranspose(mytranspose(x))== x){ print("Collect") } else{ print("Error") } } myvar1 <- matrix(1:10, nrow=5, ncol=2) myvar1 mytranspose(myvar1) mytest(myvar1) myvar1 <- matrix(NA, nrow=0, ncol=0) myvar1 mytranspose(myvar1) mytest(myvar1) myvar1 <- matrix(c(1,2), nrow=1, ncol=2) myvar1 mytranspose(myvar1) mytest(myvar1) myvar1 <- matrix(c(1,2), nrow=2, ncol=1) myvar1 mytranspose(myvar1) mytest(myvar1) myvar2 <- c(1,2,NA,3) myvar2 mytranspose(myvar2) mytest(myvar2) myvar2 <- c(NA) myvar2 mytranspose(myvar2) mytest(myvar2) myvar2 <- c() myvar2 mytranspose(myvar2) mytest(myvar2) d <- c(1,2,3,4) e <- c("red", "white", "red", NA) f <- c(TRUE,TRUE,TRUE,FALSE) mydata3 <- data.frame(d,e,f) mydata3 mytranspose(mydata3) mytest(mydata3) <file_sep>library("optimbase") mytranspose <- function(x) { if (is.vector(x)== T ){ y <- transpose(x) } else if (is.matrix(x)==T){ y <- matrix(1, nrow=ncol(x), ncol = nrow(x)) if( ncol(x) == 0 || nrow(x)==0){ return(x) break } for(i in 1:nrow(x)) { for(j in 1:ncol(x)) { y[j,i] <- x[i,j] } } } else if (is.null(x)==T){ y <- x } else{ y <- as.data.frame(t(as.matrix(x))) } return(y) } mytest <- function(x){ if (length(x)==0){ print("nothing") } else if(is.na(x)==T){ print("NA") } else if(mytranspose(mytranspose(x))== x){ print("Collect") } else{ print("Error") } } <file_sep># CRP_hw_skylee CRP_HW#2
3bdfe4684cebbc7604e512474f2a38f512b2feef
[ "Markdown", "R" ]
3
R
Vic-eun/CRP_hw_skylee
c34d31e3c3ae9617ffd86162eeaa79d9c170dc94
fd86513ff33c40cf6a55f0bbcde1672178414ad5
refs/heads/main
<file_sep>var a = 0; var q2 = () => { a = 5; console.log("ini child scope: " + a); } q2(); console.log("ini root scope: " + a); (a==5) ? console.log("true") : console.log("false"); var angka = [1,2,3]; var dobel = angka.map(function(num){ return num; })<file_sep># Praktikum_RPLBK
9757923e40fdf94471daa9ce63ca97a6038e02cd
[ "JavaScript", "Markdown" ]
2
JavaScript
ahmadhufron/Praktikum_RPLBK
ce92b2200fcef890fb7c0805a025603f3cf0d4cf
0a9a46e57511f827160dbde5d1ccc476290a2b32
refs/heads/master
<repo_name>leviharbin2/Java<file_sep>/Link lists and queues/MyQueueTester.java package assignment3; public class MyQueueTester { public static void main(String[] args) { MyQueue<Integer> myQueue = new MyQueue<>(); myQueue.insert(5); myQueue.insert(7); myQueue.insert(9); myQueue.insert(12); myQueue.insert(15); myQueue.insert(17);//inserts value at the end of the queue myQueue.printList(); System.out.println(myQueue.peek());//returns the head of the queue System.out.println(myQueue.remove());//removes the head of the queue myQueue.printList(); System.out.println(myQueue.remove()); myQueue.printList(); System.out.println(myQueue.peek()); } } <file_sep>/Array Sorting/SortingMethods.java package assignment7; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; public class SortingMethods { //method static so the class doesn't need to be initialized as an object //E must have comparable implemented on itself or one of its parents public static <E extends Comparable<? super E>> void insertSort(E[] arr) { //hole where item will move to int hole = 1; int positionsMoved = 0; //process from 2nd item to end of list, skip first item because already considered sorted for(int i = 1; i < arr.length; i++) { //temp variable holding item at current position while others moved E temp = arr[i]; //hole starts at position and moves to start of list //stop when hole is zero or comparison says prev item is smaller for(hole = i;hole > 0 && temp.compareTo(arr[hole-1]) < 0; hole--) { //move item from prev forward to current hole location arr[hole] = arr[hole-1]; positionsMoved++; } //set temp into hole arr[hole] = temp; } System.out.println("Arr Size:"+arr.length); System.out.println("Total Moves:"+positionsMoved); } //E must have comparable implemented on itself or one of its parents public static <E extends Comparable<? super E>> void shellSort(E[] arr) { //hole where item will move to int hole = 1; int positionsMoved = 0; //set sequence/shell layer to be processed, starting at half array size, //divide by 2 each time as long as sequence > 0 for(int sequence = arr.length/2;sequence > 0;sequence /= 2) { //System.out.println("Sequence:"+sequence); //loop through each sub-list, starting at sequence and going to end of list for(int sublist = sequence; sublist < arr.length ;sublist++) { //temp variable holding item at current sub-list while others moved E temp = arr[sublist]; //hole set to sublist, then moved down by sequence at a time //continue while hole >= sequence and compare temp to hole - prev(by sequence) for(hole = sublist; hole >= sequence && temp.compareTo(arr[hole-sequence]) < 0 ;hole -= sequence) { //move prev val forward arr[hole] = arr[hole-sequence]; positionsMoved++; } //put temp into hole arr[hole] = temp; } //System.out.println(Arrays.toString(arr)); } System.out.println("Arr Size:"+arr.length); System.out.println("Total Moves:"+positionsMoved); } //E must have comparable implemented on itself or one of its parents public static <E extends Comparable<? super E>> void heapSort(E[] arr) { //create heap from array PriorityQueue<E> heap = new PriorityQueue<>(); heap.addAll(Arrays.asList(arr));//performs buildHeap in O(N) //loop until heap empty int pos = 0; while(!heap.isEmpty()) { //copy back into array arr[pos] = heap.poll(); pos++; } } //E must have comparable implemented on itself or one of its parents public static <E extends Comparable<? super E>> void mergeSort(E[] arr) { //call mergeSort(arr, temp[], 0, length-1) mergeSort(arr, (E[])new Comparable[arr.length], 0, arr.length-1); } public static <E extends Comparable<? super E>> void mergeSort(E[] arr, E[] temp, int left, int right) { //System.out.println("Left:"+left+" :: Right:"+right + " :: Center:"+((right+left)/2)); //if left < right if(left < right) { //find center int center = (right+left)/2; //call mergeSort on left half (left,center) mergeSort(arr, temp, left, center); //call mergeSort on right half (center+1,right) mergeSort(arr, temp, center+1, right); //call merge over left/right halves merge(arr, temp, left, center+1, right); //System.out.println(left+":"+right+"::"+Arrays.toString(arr)); } } public static <E extends Comparable<? super E>> void merge(E[] arr, E[] temp, int leftStart, int rightStart, int rightEnd) { //System.out.println("Merge "+leftStart+":"+rightEnd); //determine leftEnd int leftEnd = rightStart-1; //set temp array position (same as left start) int currPos = leftStart; //determine number of elements (end - start + 1) int mergeCount = rightEnd-leftStart+1; //while items left in both lists while(leftStart <= leftEnd && rightStart <= rightEnd) { //put smaller into temp array, move pointers forward if(arr[leftStart].compareTo(arr[rightStart]) < 0) { temp[currPos] = arr[leftStart]; leftStart++; } else { temp[currPos] = arr[rightStart]; rightStart++; } currPos++; } //while items left in either list while(leftStart <= leftEnd) { //add left over items to end of temp array temp[currPos] = arr[leftStart]; leftStart++; currPos++; } //while items left in either list while(rightStart <= rightEnd) { //add left over items to end of temp array temp[currPos] = arr[rightStart]; rightStart++; currPos++; } //merge temp data to original using number of items and rightEnd for(; mergeCount > 0; mergeCount--, rightEnd--) { arr[rightEnd] = temp[rightEnd]; } } //E must have comparable implemented on itself or one of its parents public static <E extends Comparable<? super E>> void quickSort(E[] list) { //This method is used when trying to sort an array instead of a list //convert array to list List<E> newList = new LinkedList<>(); newList.addAll(Arrays.asList(list)); //run quicksort on list quickSort(newList); //convert list back to array int pos = 0; for(E item : newList) { list[pos] = item; pos++; } } public static <E extends Comparable<? super E>> void quickSort(List<E> list) { //if list has more than 1 item if(list.size() > 1) { //create 3 lists (smaller, same, larger) List<E> smaller = new LinkedList<>(); List<E> same = new LinkedList<>(); List<E> larger = new LinkedList<>(); //pick item for middle/pivot //E pivot = list.get(0);//not best if list is sorted/reverse /**/ E pivota = list.get(0); E pivotb = list.get(list.size()-1); E pivotc = list.get(list.size()/2); E pivot; if(pivota.compareTo(pivotb) > 0 && pivota.compareTo(pivotc) < 0) pivot = pivota; else if(pivotb.compareTo(pivota) > 0 && pivotb.compareTo(pivotc) < 0) pivot = pivotb; else pivot = pivotc; /**/ //loop through list putting items into correct containers for(E item : list)//O(N) { if(item.compareTo(pivot) > 0) { larger.add(item); } else if(item.compareTo(pivot) < 0) { smaller.add(item); } else { same.add(item); } } //System.out.println("Smaller:"+smaller.size()+" :: Same:"+same.size()+" :: Larger:"+larger.size()); //recursively sort smaller/larger quickSort(smaller); quickSort(larger); //put all items into original list [.clear(), .addAll()] list.clear(); list.addAll(smaller); list.addAll(same); list.addAll(larger); } } public static void bucketSort(Integer[] arr, int min, int max) { //number of buckets int bucketCount = max-min+1; //create buckets for range int[] buckets = new int[bucketCount]; //add each item from array to correct bucket counter (shift if needed) for(int i = 0; i < arr.length; i++) { buckets[arr[i]-min]++;//-min to shift into correct index range } //run through buckets to refill array in correct order (shift back if needed) int pos = 0; for(int i = 0; i < buckets.length; i++) { //put the number of identical items back into the array for(int j = 0; j < buckets[i]; j++) { arr[pos] = i+min;//+min is to shift back into correct range pos++; } } } public static void radixSortSameLength(String[] arr, int maxLength) { //number of buckets (256 in standard character set) int bucketCount = 256; //buckets can't be counters, need to be lists List<String>[] buckets = new LinkedList[bucketCount]; //create all buckets needed for(int i = 0; i < buckets.length; i++) { buckets[i] = new LinkedList<>(); } //loop from end of string to beginning to properly sort for(int currChar = maxLength-1;currChar >= 0; currChar--) { //loop through each string for(int i = 0; i < arr.length; i++) { //add to appropriate bucket buckets[arr[i].charAt(currChar)].add(arr[i]); //arr[i].charAt(currChar) converts to the ASCII number automatically } //loop through buckets int pos = 0; for(int i = 0; i < buckets.length; i++) { //put each item from the bucket into original array for(String item : buckets[i]) { arr[pos] = item; pos++; } //clear bucket buckets[i].clear(); } System.out.println(Arrays.toString(arr)); } } public static void radixSortDifferentLength(String[] arr) { //number of buckets (256 in standard character set) int bucketCount = 256; //buckets can't be counters, need to be lists List<String>[] buckets = new LinkedList[bucketCount]; //create all buckets needed for(int i = 0; i < buckets.length; i++) { buckets[i] = new LinkedList<>(); } //loop from end of string to beginning to properly sort for(int currChar = 1;currChar >= 0; currChar--) { //loop through each string for(int b = 0; b < arr.length; b++) { //add to appropriate bucket buckets[arr[b].charAt(currChar)].add(arr[b]); //arr[i].charAt(currChar) converts to the ASCII number automatically } //loop through buckets int pos = 0; for(int c = 0; c < buckets.length; c++) { //put each item from the bucket into original array for(String item : buckets[c]) { arr[pos] = item; pos++; } //clear bucket buckets[c].clear(); } System.out.println(Arrays.toString(arr)); } } }<file_sep>/Link lists and queues/CircularSinglyLinkedList.java package assignment3; class Node { protected int data; protected Node link; public Node() { link = null; data = 0; } public Node(int d,Node n) { data = d; link = n; } public void setLink(Node n) { link = n; } public void setData(int d) { data = d; } public Node getLink() { return link; } public int getData() { return data; } } class linkedList { protected Node start ; protected Node end ; public int size ; public linkedList(int numberOfPlayers, int numberOfPasses) { start = null; end = null; size = numberOfPlayers; } public boolean isEmpty() { return start == null; } public int getSize() { return size; } public void insertAtEnd(int val) { Node node = new Node(val,null); node.setLink(start); if(start == null) { start = node; node.setLink(start); end = start; } else { end.setLink(node); end = node; } size++ ; } public void pass(int moves){ if (size == 1 && moves == 1) { start = null; end = null; size = 0; return ; } if (moves == 1) { start = start.getLink(); end.setLink(start); size--; return ; } if (moves == size) { Node s = start; Node t = start; while (s != end) { t = s; s = s.getLink(); } end = t; end.setLink(start); size --; return; } Node star = start; moves = moves - 1 ; for (int i = 1; i < size - 1; i++) { if (i == moves) { Node temp = star.getLink(); temp = temp.getLink(); star.setLink(temp); break; } star = star.getLink(); } size-- ; } public void display() { System.out.print("\nList = "); Node nd = start; if (size == 0) { System.out.print("empty\n"); return; } if(size ==10) { System.out.print("the winner is "+start.getData()); return; } if (start.getLink() == start) { System.out.print(start.getData()+ "->"+nd.getData()+ "\n"); return; } System.out.print(start.getData()+ "->"); nd = start.getLink(); while (nd.getLink() != start) { System.out.print(nd.getData()+ "->"); nd = nd.getLink(); } System.out.print(nd.getData()+ "->"); nd = nd.getLink(); System.out.print(nd.getData()+ "\n"); } } <file_sep>/Trees/NumberFourTester.java package assignment6; public class NumberFourTester { public static void main(String[] args) {//creates a heap and then prints out kth largest element Integer[] ar1 = {1,2,3,4,5,6,7,8,9,10}; //Integer[] ar1 = {2,4,6,8,10,12,14,16,18,20}; //Integer[] ar1 = {1,8,6,4,12,33}; NumberFour<Integer> mbh2 = new NumberFour<Integer>(ar1); System.out.println(mbh2.kTHLargestElement(ar1,4)); } } <file_sep>/Hashing/Map.java package assignment5; import java.util.Arrays; public class Map<KeyType, ValueType> { private Entry<KeyType, ValueType> entries[]; private final static int DEFAULT_CAPACITY = 10; private int size; private int numberOfEntries; // map with no parameters public Map() { size = DEFAULT_CAPACITY; entries = new Entry[size]; numberOfEntries = 0; } // map with defined size public Map(int size) { this.size = size; entries = new Entry[size]; numberOfEntries = 0; } // hash to determine where to place value private int getHash(KeyType key) { int hashVal = key.hashCode(); hashVal %= entries.length; if( hashVal < 0 ) hashVal += entries.length; return hashVal; } //put method to insert value into map, uses hash public void put(KeyType key, ValueType val) { int hashcode = getHash(key); Entry<KeyType, ValueType> tmp = entries[hashcode]; Entry<KeyType, ValueType> newEntry = new Entry<KeyType, ValueType>(key, val); entries[hashcode] = newEntry; numberOfEntries++; } //get value based off key, return null if key = null etc. public ValueType get(KeyType key) { if (key == null) { return null; } int hc = getHash(key); Entry<KeyType, ValueType> tmp = entries[hc]; while (tmp != null) { if (tmp.getKey().equals(key)) { return tmp.getValue(); } tmp = tmp.getNext(); } return null; } //check if map is empty public boolean isEmpty() { for(int i = 0; i<entries.length;i++) { if (entries[i] != null) { return false; } } return true; } //re-make array but empty public void makeEmpty() { entries = new Entry[size]; numberOfEntries = 0; } public String toString() { return "Map [size=" + size + ", numEntries=" + numberOfEntries + "], entries=" + Arrays.toString(entries) + "]"; } private static class Entry<KeyType, ValueType> { private KeyType key; private ValueType value; private Entry<KeyType, ValueType> next; Entry(KeyType k , ValueType v){ this.key = k; this.value = v; } public KeyType getKey() { return key; } public void setKey(KeyType key) { this.key = key; } public ValueType getValue() { return value; } public void setValue(ValueType value) { this.value = value; } public Entry<KeyType, ValueType> getNext() { return next; } public void setNext(Entry<KeyType, ValueType> next) { this.next = next; } public String toString() { return " key = "+key+" value = "+value; } } } <file_sep>/Trees/NumberThreeTester.java package assignment6; public class NumberThreeTester { public static void main(String[] args) {//creates a heap and removes k smallest elements from heap Integer[] ar1 = {1,2,3,4,5,6,7,8,9,10}; NumberThree<Integer> mbh2 = new NumberThree<Integer>(ar1); System.out.println(mbh2); System.out.println(mbh2.deleteKElements(4)); } } <file_sep>/Trees/EquationBinaryTree.java package assignment4; public class EquationBinaryTree { private Node root; public EquationBinaryTree() { root = null; } //left -> parent -> right public void printInfix() { if(root != null) { printInfixHelper(root); System.out.println(); } } //left -> parent -> right private void printInfixHelper(Node n) { if(n.left != null)//know the right also exists { System.out.print("("); printInfixHelper(n.left); System.out.print(n.data); printInfixHelper(n.right); System.out.print(")"); } else { System.out.print(n.data); } } //left -> right -> parent public void printPostfix() { if(root != null) { printPostfixHelper(root); System.out.println(); } } private void printPostfixHelper(Node n) { if(n.left != null)//know the right also exists { printPostfixHelper(n.left); printPostfixHelper(n.right); System.out.print(n.data); } else { System.out.print(n.data); } } //parent -> left -> right public void printPrefix() { if(root != null) { printPrefixHelper(root); System.out.println(); } } private void printPrefixHelper(Node n) { if(n.left != null)//know the right also exists { System.out.print(n.data); printPrefixHelper(n.left); printPrefixHelper(n.right); } else { System.out.print(n.data); } } //abc*+de*f+g*+ public void populateFromPostfix(String postfix) { root = populateFromPostfixHelper(postfix); } private Node populateFromPostfixHelper(String postfix){ String[] parts = postfixSplitter(postfix);//0 = left, 1 = middle, 2 = right Node item = new Node(parts[1]); if(parts[0].length() > 0) item.left = populateFromPrefixHelper(parts[0]); if(parts[2].length() > 0) item.right = populateFromPrefixHelper(parts[2]); return item; } private String[] postfixSplitter(String postfix) { String[] temp = new String[3]; if(postfix.length() > 1) { postfix = postfix.substring(1, postfix.length()-1);//remove outer paren int parenCount = 0; int i; for(i = 0; i < postfix.length(); i++) { if(postfix.charAt(i) == '(') parenCount++; else if(postfix.charAt(i) == ')') parenCount--; if(parenCount == 0) break; } temp[0] = postfix.substring(0, i+1); temp[1] = ""+postfix.charAt(i+1); temp[2] = postfix.substring(i+2); /* System.out.println(infix.substring(0, i+1));//left point System.out.println(infix.charAt(i+1));//middle point System.out.println(infix.substring(i+2));//right point System.out.println(infix + ":" + i); */ } else { temp[0] = ""; temp[1] = postfix; temp[2] = ""; } return temp; } //++a*bc*+*defg public void populateFromPrefix(String prefix) { root = populateFromPrefixHelper(prefix); } private Node populateFromPrefixHelper(String prefix){ String[] parts = prefixSplitter(prefix);//0 = left, 1 = middle, 2 = right Node item = new Node(parts[1]); if(parts[0].length() > 0) item.left = populateFromInfixHelper(parts[0]); if(parts[2].length() > 0) item.right = populateFromInfixHelper(parts[2]); return item; } private String[] prefixSplitter(String prefix) { String[] temp = new String[3]; if(prefix.length() > 1) { prefix = prefix.substring(1, prefix.length()-1);//remove outer paren int parenCount = 0; int i; for(i = 0; i < prefix.length(); i++) { if(prefix.charAt(i) == '(') parenCount++; else if(prefix.charAt(i) == ')') parenCount--; if(parenCount == 0) break; } temp[0] = prefix.substring(0, i+1); temp[1] = ""+prefix.charAt(i+1); temp[2] = prefix.substring(i+2); /* System.out.println(infix.substring(0, i+1));//left point System.out.println(infix.charAt(i+1));//middle point System.out.println(infix.substring(i+2));//right point System.out.println(infix + ":" + i); */ } else { temp[0] = ""; temp[1] = prefix; temp[2] = ""; } return temp; } //(a+b) //((a+b)+c) //(a+(b+c)) //((a+(b*c))+(((d*e)+f)*g)) public void populateFromInfix(String infix) { root = populateFromInfixHelper(infix); } private Node populateFromInfixHelper(String infix) { String[] parts = infixSplitter(infix);//0 = left, 1 = middle, 2 = right Node item = new Node(parts[1]); if(parts[0].length() > 0) item.left = populateFromInfixHelper(parts[0]); if(parts[2].length() > 0) item.right = populateFromInfixHelper(parts[2]); return item; } private String[] infixSplitter(String infix) { String[] temp = new String[3]; if(infix.length() > 1) { infix = infix.substring(1, infix.length()-1);//remove outer paren int parenCount = 0; int i; for(i = 0; i < infix.length(); i++) { if(infix.charAt(i) == '(') parenCount++; else if(infix.charAt(i) == ')') parenCount--; if(parenCount == 0) break; } temp[0] = infix.substring(0, i+1); temp[1] = ""+infix.charAt(i+1); temp[2] = infix.substring(i+2); /* System.out.println(infix.substring(0, i+1));//left point System.out.println(infix.charAt(i+1));//middle point System.out.println(infix.substring(i+2));//right point System.out.println(infix + ":" + i); */ } else { temp[0] = ""; temp[1] = infix; temp[2] = ""; } return temp; } private class Node { String data; Node left, right; public Node(String d) { data = d; left = null; right = null; } } } <file_sep>/Trees/NumberSix.java package assignment4; import java.util.ArrayList; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import java.util.Scanner; public class NumberSix{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); TreeMap<String, String> map1 = new TreeMap<>(); String userYN = null; Boolean flag = true; int vowels = 0; while (flag!=false) { System.out.println("Enter a name: "); String name = sc.nextLine(); for (int i = 0; i < name.length(); i++) { if (name.charAt(i) == 'a' || name.charAt(i) == 'e' || name.charAt(i) == 'i' || name.charAt(i) == 'o' || name.charAt(i) == 'u') { vowels++; } } map1.put(name, vowels+""); vowels = 0; System.out.println("Would you like to enter another name? Enter Y or N : "); userYN = sc.nextLine(); if (userYN.equalsIgnoreCase("n")){ flag = false; } } System.out.println(map1); } }<file_sep>/Hashing/HopscotchHashTableTester.java package bonus2; public class HopscotchHashTableTester { public static void main(String[] args) { HopscotchHashTable<Integer> hshs = new HopscotchHashTable<>(); hshs.printHashTable(); hshs.insert(1000); hshs.printHashTable(); hshs.insert(1111); hshs.printHashTable(); hshs.insert(2001); hshs.printHashTable(); } } <file_sep>/Link lists and queues/MySingleLinkedList.java package assignment3; public class MySingleLinkedList<E> { private Node start; private int currentSize; public MySingleLinkedList() { start = null; currentSize = 0; } public void swap(int index) { Node current = start; Node temp = null; if ( index == 0){ temp = start; start = start.next; System.out.println(); if ( index == 10){ current = start; while(current != null) { System.out.print(current.val+","); current = current.next;//move to next Node/container in the list if(current.val.equals(10)) { current.next = current; } } System.out.println(); } } } //1 8 5 9 /* if (10 !=null) swap 10 and 11; } */ public void printList()//O(N) { Node current = start; while(current != null) { System.out.print(current.val+","); current = current.next;//move to next Node/container in the list } System.out.println(); } public void insert(E val, int index)//O(index) { //fix index values to correct range if(index > currentSize) index = currentSize; if(index < 0) index = 0; Node newItem = new Node(val); //start is null//list is empty if(start == null) { start = newItem; currentSize++; } else if(index == 0) { //newItem will be before start newItem.next = start; start = newItem; currentSize++; } else { Node current = start;//current is now position 0 for(int i = 0; i < index-1; i++)//stop current at the item before where the new one goes { current = current.next; } //current is the item before where we want the new one newItem.next = current.next; current.next = newItem; currentSize++; } } public void add(E val)//O(N) { insert(val, currentSize); } public void addFirst(E val)//O(1) { insert(val, 0); } public E remove(E val) { if(start == null) return null; if(start.val.equals(val)) { E temp = start.val; start = start.next; currentSize--; return temp; } else { Node current = start; while(current.next != null && !current.next.val.equals(val))//next containers value equal to what we want to delete { current = current.next; } if(current.next == null)//wasn't found return null; else { E temp = current.next.val;//value found current.next = current.next.next; currentSize--; return temp; } } } public E delete(int index) { if(index < 0 && index >= currentSize) return null; else { if(index == 0) { E temp = start.val; start = start.next; currentSize--; return temp; } else { Node current = start; for(int i = 0; i < index-1; i++) { current = current.next; } E temp = current.next.val;//value found current.next = current.next.next; currentSize--; return temp; } } } public E find(E val) { if(start == null) return null; if(start.val.equals(val)) { return start.val; } else { Node current = start; while(current.next != null && !current.next.val.equals(val))//next containers value equal to what we want to delete { current = current.next; } if(current.next == null)//wasn't found return null; else { return current.next.val; } } } public E get(int index) { if(index < 0 && index >= currentSize) return null; else { if(index == 0) { return start.val; } else { Node current = start; for(int i = 0; i < index-1; i++) { current = current.next; } return current.next.val; } } } public class Node { public E val; public Node next; public Node(E v) { val = v; next = null; } } } <file_sep>/Lexical Analyzer/LexicalAnalyzer.java package lexicalAnalyzerPackage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; import java.io.Reader; //<NAME> public class LexicalAnalyzer { public static void main(String[] args) throws IOException { //Setup for scanning a file in, aswell as using scanner to read each line as it is in the file. //Scanner scanner = new Scanner("C:\\Users\\L-PC\\Desktop\\lexInput.txt");//change these paths to the file location of testing txt file... make sure to use double slashes //File file = new File("C:\\Users\\L-PC\\Desktop\\lexInput.txt");//change these paths to the file location of testing txt file Scanner scanner = new Scanner("D:\\other\\eclipse\\assignments\\assignment\\src\\lexicalAnalyzerPackage\\lexInput");//change these paths to the file location of testing txt file... make sure to use double slashes File file = new File("D:\\other\\eclipse\\assignments\\assignment\\src\\lexicalAnalyzerPackage\\lexInput");//change these paths to the file location of testing txt file Scanner scanner2 = new Scanner(file); String inputLine = scanner.nextLine(); System.out.println("<NAME>, CSCI4200-DB, Fall 2018, Lexical Analyzer"); //try to read in the file and run main method try{ reader = new FileReader(inputLine); getChar();//initial getChar //loop through file as long as there is a next line for(int i = 0; scanner2.hasNextLine();) { System.out.println("********************************************************************************"); System.out.println(scanner2.nextLine()); getChar(); do{ lex(); }while (nextToken != "END_OF_FILE"); } System.out.println("********************************************************************************"); System.out.println("Lexical analysis of the program is complete!"); //catch filenotfound and exception } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //============================================================================= //tokens static int INT_LIT = 10; static int IDENT = 11; static int ASSIGN_OP = 20; static int ADD_OP = 21; static int SUB_OP = 22; static int MULT_OP = 23; static int DIV_OP = 24; static int LEFT_PAREN = 25; static int RIGHT_PAREN = 26; static int END_OF_FILE = 27; static int LETTER = 0; static int DIGIT = 1; static int UNKNOWN = 99; static int charClass; static char lexeme [] = new char[100]; static char nextChar; static int lexLen; int token; static String nextToken; static FileReader reader; static int blankCount=0; //============================================================================ public static void addChar() {//adds each character to make up a full lexeme if(lexLen <= 98) { lexeme[lexLen++] = nextChar; lexeme[lexLen] = 0; } else System.out.println("Error - lexeme is too long \n"); } //============================================================================ public static void getChar() throws IOException {// Categorizes a character into LETTER,DIGIT,UNKNOWN, and EOF int character; if((character = reader.read()) != END_OF_FILE){ nextChar = (char) character; if(Character.isLetter(nextChar)) charClass = LETTER; else if (Character.isDigit(nextChar)) charClass = DIGIT; else charClass = UNKNOWN; }else{ charClass = END_OF_FILE; } } //============================================================================ public static void getNonBlank() throws IOException {//find a character that isn't a blank while(nextChar ==' ') { getChar(); } } //============================================================================ public static String lex() throws IOException {//Main part, gets a nonblank, and then based off LETTER DIGIT UNKNOWN EOF value it does appropriate rules lexLen = 0; getNonBlank(); switch (charClass) { case 0: addChar(); getChar(); while(charClass == LETTER || charClass == DIGIT) { addChar(); getChar(); } nextToken = "IDENT"; break; case 1: addChar(); getChar(); while(charClass == DIGIT) { addChar(); getChar(); } nextToken = "INT_LIT"; break; case 99: lookup(nextChar); getChar(); break; case 27: nextToken = "END_OF_FILE"; lexeme[0] = 'E'; lexeme[1] = 'O'; lexeme[2] = 'F'; break; } System.out.println("Next token is: "+nextToken+"\t"+"Next lexeme is: "+convertLexeme());// print statement in console return nextToken; } //============================================================================ static String lookup(char ch) {//converts operators and symbols to appropriate Token of type String. switch (ch) { case '(': addChar(); nextToken = "LEFT_PAREN"; break; case ')': addChar(); nextToken = "RIGHT_PAREN"; break; case '+': addChar(); nextToken = "ADD_OP"; break; case '-': addChar(); nextToken = "SUB_OP"; break; case '*': addChar(); nextToken = "MULT_OP"; break; case '/': addChar(); nextToken = "DIV_OP"; break; case '=': addChar(); nextToken = "ASSIGN_OP"; break; default: addChar(); nextToken = "END_OF_FILE"; break; } return nextToken; } //============================================================================ static String convertLexeme() {// takes the character array lexeme[] and returns the character(s) stored in it String results = ""; for (int i = 0; i<lexeme.length; i++) { if(lexeme[i] ==0) break; results+= lexeme[i]; } return results; } //============================================================================ } <file_sep>/Trees/EquationBinaryTreeTester.java package assignment4; public class EquationBinaryTreeTester { public static void main(String[] args) { EquationBinaryTree ebt = new EquationBinaryTree(); ebt.populateFromInfix("(a+b)"); ebt.printInfix(); ebt.printPostfix(); ebt.printPrefix(); System.out.println(); ebt.populateFromInfix("((a+b)+c)"); ebt.printInfix(); ebt.printPostfix(); ebt.printPrefix(); System.out.println(); ebt.populateFromInfix("(a+(b+c))"); ebt.printInfix(); ebt.printPostfix(); ebt.printPrefix(); System.out.println(); ebt.populateFromInfix("((a+(b*c))+(((d*e)+f)*g))"); ebt.printInfix(); ebt.printPostfix(); ebt.printPrefix(); System.out.println(); ebt.populateFromPrefix("(+ab)"); ebt.printInfix(); ebt.printPostfix(); ebt.printPrefix(); System.out.println(); ebt.populateFromPostfix("(ab+)"); ebt.printInfix(); ebt.printPostfix(); ebt.printPrefix(); } } <file_sep>/Trees/Dheap.java package bonus3; public class Dheap<E extends Comparable<? super E>> { private static int DEFAULT_CAPACITY = 0; private int currentSize; private E[] heap; private int localDValue; public Dheap() { this(DEFAULT_CAPACITY); } public Dheap(int newSize) { heap = (E[]) new Comparable[nextSize(newSize)]; currentSize = 0; } /* public Dheap(E[] items) { heap = (E[]) new Comparable[nextSize(items.length)]; currentSize = items.length; for(int i = 0; i < items.length; i++) { heap[i+1] = items[i]; } buildHeap(); } */ public Dheap(E[] items,int DValue) { localDValue = DValue; heap = (E[]) new Comparable[nextSize(items.length)]; //System.out.println("items lenght"+items.length); currentSize = items.length; for(int i = 0; i < items.length; i++) { heap[i+1] = items[i]; } buildHeap(); } public void addAll(E[] items) { if(currentSize + items.length+1 > heap.length)//array is full or more than full { growArray(nextSize(currentSize+items.length+1)); } currentSize++; for(int i = 0; i < items.length; i++, currentSize++) { heap[currentSize] = items[i]; } buildHeap(); } private void buildHeap()//restore heap order property { for(int i = currentSize>>1; i > 0; i--) { percolateDown(i); } } public boolean isEmpty() { return (currentSize == 0); } public void makeEmpty() { currentSize = 0; } private void growArray(int newSize) { //System.out.println("Grow"); E[] temp = heap; heap = (E[]) new Comparable[newSize]; for(int i = 1; i <= currentSize; i++) { heap[i] = temp[i]; } } private void growArray()//size of the heap +1 for new value, * Dheap value, add 2 for hole and new value { growArray(((currentSize+1)*localDValue)+2); } private int nextSize(int newSize)//When loading the heap from an Array, take the size of the array and multiply it by the Dheap value, add 2 to account for hole and null value { //System.out.println("newSize:"+newSize+"localD"+localDValue); return (newSize*localDValue)+2; //return 1 << (Integer.toBinaryString(newSize).length()); } public String toString() { //current size can never be equal to length, because we are reserving heap[0] for inserts String output = "Heap Space:"+heap.length+":Space Used:"+currentSize+"\n"; for(int i = 1; i <= currentSize; i++) { output += heap[i]+","; } return output; } public void insert(E value)// when you insert a value, add the children in as null { //System.out.println("CurrentSize before insert:"+currentSize+"Heap Length before insert:"+heap.length); //if(currentSize+1 == heap.length)//array is full //{ growArray(); //} currentSize++;//update to position that needs to be filled heap[0] = value;//temporary home for value while making room percolateUp(currentSize); } private void percolateUp(int pos) { //pos>>1 == pos/2 //check if parent is larger than what is being inserted for(; heap[pos>>1].compareTo(heap[0]) > 0; pos = pos>>1) { //if parent larger, move down and try again on next level heap[pos] = heap[pos>>1]; } heap[pos] = heap[0];//insert into empty position made by percolate } public E findMin() { //heap[1] always contains smallest value if(currentSize > 0) return heap[1]; else return null; } public E deleteMin() { if(currentSize > 0) { E temp = heap[1]; heap[1] = heap[currentSize];//not using heap[0] so this works the same for buildHeap method currentSize--; percolateDown(1); return temp; } else return null; } private void percolateDown(int pos) { int child = pos << 1; E temp = heap[pos];//not using heap[0] so this works the same for buildHeap method //pos<<1 == pos * 2 for(; pos<<1 <= currentSize; pos = child, child = pos<<1) { if(child != currentSize //there is a second child && heap[child+1].compareTo(heap[child]) < 0)//second is smaller than first { child++; } //child is now the index of the smaller of the two children if there are two //if child is smaller than temp, move child up if(heap[child].compareTo(temp) < 0) { heap[pos] = heap[child]; } else { break;//prevent increment from running in for loop } } heap[pos] = temp; } } <file_sep>/Trees/DheapTester.java package bonus3; public class DheapTester { public static void main(String[] args) { // Integer[] array = {10, 8, 6, 4, 2, 12, 14, 16, 18, 20}; Integer[] array = {1}; Dheap<Integer> DHP = new Dheap<>(array,3);//3 is Dheap Value, change to 4 for 4-heap System.out.println(DHP); DHP.insert(2); System.out.println(DHP); DHP.insert(3); System.out.println(DHP); DHP.insert(4); System.out.println(DHP); //DHP.insert(5); } } <file_sep>/Trees/NumberFour.java package assignment6; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class NumberFour<E extends Comparable<? super E>> { /* We are interested in finding the kth largest element. Generate N elements into an array. At any point in time, we want to maintain a set 'S' of the k largest elements. Create a heap from the first k elements in the array, ensuring the buildHeap is used and not individual inserts. For each remaining element in the array, if it is larger than the smallest value in the heap, remove the smallest and insert the new value. When all array elements have been processed, the smallest value in the heap is the kth largest value in the list, return this value. */ private static int DEFAULT_CAPACITY = 0; private int currentSize; private E[] heap; public NumberFour() { this(DEFAULT_CAPACITY); } public NumberFour(int newSize) { heap = (E[]) new Comparable[nextSize(newSize)]; currentSize = 0; } public NumberFour(E[] items) { heap = (E[]) new Comparable[nextSize(items.length)]; currentSize = items.length; System.out.println("size of array: "+items.length); for(int i = 0; i < items.length; i++) { heap[i+1] = items[i]; } buildHeap(); } public void addAll(E[] items) { if(currentSize + items.length+1 > heap.length)//array is full or more than full { growArray(nextSize(currentSize+items.length+1)); } currentSize++; for(int i = 0; i < items.length; i++, currentSize++) { heap[currentSize] = items[i]; } buildHeap(); } private void buildHeap()//restore heap order property { for(int i = currentSize>>1; i > 0; i--) { percolateDown(i); } } public boolean isEmpty() { return (currentSize == 0); } public void makeEmpty() { currentSize = 0; } private void growArray(int newSize) { //System.out.println("Grow"); E[] temp = heap; heap = (E[]) new Comparable[newSize]; for(int i = 1; i <= currentSize; i++) { heap[i] = temp[i]; } } private void growArray() { growArray(heap.length << 1);//same as heap.length * 2 } private int nextSize(int newSize) { return 1 << (Integer.toBinaryString(newSize).length()); } public String toString() { //current size can never be equal to length, because we are reserving heap[0] for inserts String output = "Heap Space:"+heap.length+":Space Used:"+currentSize+"\n"; for(int i = 1; i <= currentSize; i++) { output += heap[i]+","; } return output; } public void insert(E value) { if(currentSize + 1 == heap.length)//array is full { growArray(); } currentSize++;//update to position that needs to be filled heap[0] = value;//temporary home for value while making room percolateUp(currentSize); } private void percolateUp(int pos) { //pos>>1 == pos/2 //check if parent is larger than what is being inserted for(; heap[pos>>1].compareTo(heap[0]) > 0; pos = pos>>1) { //if parent larger, move down and try again on next level heap[pos] = heap[pos>>1]; } heap[pos] = heap[0];//insert into empty position made by percolate } public E findMin() { //heap[1] always contains smallest value if(currentSize > 0) return heap[1]; else return null; } public E deleteMin() { if(currentSize > 0) { E temp = heap[1]; heap[1] = heap[currentSize];//not using heap[0] so this works the same for buildHeap method currentSize--; percolateDown(1); return temp; } else return null; } private void percolateDown(int pos) { int child = pos << 1; E temp = heap[pos];//not using heap[0] so this works the same for buildHeap method //pos<<1 == pos * 2 for(; pos<<1 <= currentSize; pos = child, child = pos<<1) { if(child != currentSize //there is a second child && heap[child+1].compareTo(heap[child]) < 0)//second is smaller than first { child++; } //child is now the index of the smaller of the two children if there are two //if child is smaller than temp, move child up if(heap[child].compareTo(temp) < 0) { heap[pos] = heap[child]; } else { break;//prevent increment from running in for loop } } heap[pos] = temp; } public String kTHLargestElement(E[] userArrayChoice, int userIntChoice) {// pass user selected number and array E finalInt = null; currentSize = userIntChoice; if(userArrayChoice.length<userIntChoice) {//if k> length of array, tell user to change k return"Array size is too small for value picked"; } else { heap = (E[]) new Comparable[userIntChoice+1]; for(int i = 0; i < userIntChoice; i++)//copy user values to array based off number of large values { heap[i+1] = userArrayChoice[i]; } buildHeap(); System.out.println("******************************"); for(int i = userIntChoice; i < userArrayChoice.length; i++) {//loop through the larger elements if((int)userArrayChoice[i]>(int)findMin()) {//if the value in array is bigger than the smallest heap value, switch it into the heap deleteMin(); insert(userArrayChoice[i]); } } finalInt = findMin(); HashSet <E> newset = new HashSet <E>(Arrays.asList(heap));//pass the heap of large values into a unique set, deleting redundant values System.out.println("unique set of largest elements"+"\n"+newset+"\n"); System.out.println("userArray"+"\n"+Arrays.toString(userArrayChoice)+"\n"); return "The number "+userIntChoice +" largest element is: "+finalInt;//the last item deleted } } } <file_sep>/Trees/MyBinaryHeap.java package assignment6; public class MyBinaryHeap<E extends Comparable<? super E>> { private static int DEFAULT_CAPACITY = 0; private int currentSize; private E[] heap; public int operationcountIndividual = 0; public int operationcountBulk = 0; public MyBinaryHeap() { this(DEFAULT_CAPACITY); operationcountIndividual++; operationcountBulk++; } public MyBinaryHeap(int newSize) { heap = (E[]) new Comparable[nextSize(newSize)]; operationcountIndividual+=2; operationcountBulk+=2; currentSize = 0; operationcountIndividual++; operationcountBulk++; } public MyBinaryHeap(E[] items) { heap = (E[]) new Comparable[nextSize(items.length)]; operationcountBulk+=2; currentSize = items.length; operationcountBulk+=2; //System.out.println(items.length); operationcountBulk+=2; for(int i = 0; i < items.length; i++) { heap[i+1] = items[i]; operationcountBulk++; operationcountBulk+=2; } buildHeap(); operationcountBulk++; } public void addAll(E[] items) { operationcountBulk+=5;// 1 for size, 2 for length and add operation , 1 for heap length, 1 for comparison if(currentSize + items.length+1 > heap.length)//array is full or more than full { growArray(nextSize(currentSize+items.length+1)); operationcountBulk+=6;//1 for grow array, 1 for next size, 1 for currentsize, 2 for length+1, 1 for current+items } currentSize++; operationcountBulk+=2; for(int i = 0; i < items.length; i++, currentSize++) { operationcountBulk++; heap[currentSize] = items[i]; operationcountBulk+=2; } buildHeap(); operationcountBulk++; } private void buildHeap()//restore heap order property { operationcountIndividual+=2; operationcountBulk+=2; for(int i = currentSize>>1; i > 0; i--) { operationcountBulk++; operationcountIndividual++; percolateDown(i); operationcountBulk+=2; operationcountIndividual+=2; } } public boolean isEmpty() { operationcountBulk+=2; operationcountIndividual+=2; return (currentSize == 0); } public void makeEmpty() { operationcountBulk++; operationcountIndividual++; currentSize = 0; } private void growArray(int newSize) { //System.out.println("Grow"); E[] temp = heap; operationcountBulk++; operationcountIndividual++; heap = (E[]) new Comparable[newSize]; operationcountBulk+=2; operationcountIndividual+=2; operationcountBulk+=2; operationcountIndividual+=2; for(int i = 1; i <= currentSize; i++) { operationcountBulk++; operationcountIndividual++; heap[i] = temp[i]; operationcountBulk+=2; operationcountIndividual+=2; } } private void growArray() { operationcountBulk+=3;//one for grow array, one for heap length, one for shift one binary operationcountIndividual+=3; growArray(heap.length << 1);//same as heap.length * 2 } private int nextSize(int newSize) { operationcountBulk+=5;// one for return, one for shift, one for integer method, one for newsize call, one for length call operationcountIndividual+=5; return 1 << (Integer.toBinaryString(newSize).length()); } public String toString() { //current size can never be equal to length, because we are reserving heap[0] for inserts operationcountBulk++; operationcountIndividual++; String output = "Heap: "; operationcountBulk+=2; operationcountIndividual+=2; for(int i = 1; i <= currentSize; i++) { operationcountBulk+=2; operationcountIndividual+=2; output += heap[i]+","; operationcountBulk+=2; operationcountIndividual+=2; } operationcountBulk++; operationcountIndividual++; return output; } public void insert(E value) { operationcountIndividual+=3;//one for addition, one for ==, one for heap length if(currentSize + 1 == heap.length)//array is full { operationcountIndividual++; growArray(); } operationcountIndividual++; currentSize++;//update to position that needs to be filled operationcountIndividual++; heap[0] = value;//temporary home for value while making room operationcountIndividual+=2; percolateUp(currentSize); } private void percolateUp(int pos) { //pos>>1 == pos/2 //check if parent is larger than what is being inserted operationcountBulk+=2; operationcountIndividual+=2; for(; heap[pos>>1].compareTo(heap[0]) > 0; pos = pos>>1) { operationcountBulk+=2; operationcountIndividual+=2; //if parent larger, move down and try again on next level heap[pos] = heap[pos>>1]; operationcountBulk+=2; operationcountIndividual+=2; } operationcountBulk+=2; operationcountIndividual+=2; heap[pos] = heap[0];//insert into empty position made by percolate } public E findMin() { //heap[1] always contains smallest value operationcountBulk++; operationcountIndividual++; if(currentSize > 0) { operationcountBulk++; operationcountIndividual++; return heap[1]; } else { operationcountBulk++; operationcountIndividual++; return null; } } public E deleteMin() { operationcountBulk++; operationcountIndividual++; if(currentSize > 0) { operationcountBulk++; operationcountIndividual++; E temp = heap[1]; operationcountBulk++; operationcountIndividual++; heap[1] = heap[currentSize];//not using heap[0] so this works the same for buildHeap method operationcountBulk++; operationcountIndividual++; currentSize--; operationcountBulk++; operationcountIndividual++; percolateDown(1); operationcountBulk++; operationcountIndividual++; return temp; } else { operationcountBulk++; operationcountIndividual++; return null; } } private void percolateDown(int pos) { operationcountBulk+=2; operationcountIndividual+=2; int child = pos << 1; operationcountBulk++; operationcountIndividual++; E temp = heap[pos];//not using heap[0] so this works the same for buildHeap method //pos<<1 == pos * 2 operationcountBulk+=2; operationcountIndividual+=2; for(; pos<<1 <= currentSize; pos = child, child = pos<<1) { operationcountBulk+=5;//1 for != , 1 for &&, 1 for child+1, 1 for compareTo,1 for<0 operationcountIndividual+=5; if(child != currentSize //there is a second child && heap[child+1].compareTo(heap[child]) < 0)//second is smaller than first { operationcountBulk++; operationcountIndividual++; child++; } //child is now the index of the smaller of the two children if there are two //if child is smaller than temp, move child up operationcountBulk+=2; operationcountIndividual+=2; if(heap[child].compareTo(temp) < 0) { operationcountBulk++; operationcountIndividual++; heap[pos] = heap[child]; } else { operationcountBulk++; operationcountIndividual++; break;//prevent increment from running in for loop } } operationcountBulk++; operationcountIndividual++; heap[pos] = temp; } public int operationCount(String choice) { if(choice.equalsIgnoreCase("operationcountIndividual")) { return operationcountIndividual; } else if(choice.equalsIgnoreCase("operationcountBulk")) { return operationcountBulk; } else return 0; } } <file_sep>/Trees/Graph.java package assignment8; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.Vector; public class Graph { private TreeMap<String, Vertex> graph; private int V; // No. of vertices public Graph() { graph = new TreeMap<>(); } public void addEdge(String v1, String v2, Integer w) { //ensure vertex exist in graph addVertex(v1); addVertex(v2); //get vertex object from graph for v1, add an adjacent edge to v2 graph.get(v1).addEdge(v2, w); } public void addEdge(String v1, String v2) { addEdge(v1, v2, 1); } public void addEdgeUndirected(String v1, String v2, Integer w) { //ensure vertex exist in graph addVertex(v1); addVertex(v2); //get vertex object from graph for v1, add an adjacent edge to v2 graph.get(v1).addEdge(v2, w); graph.get(v2).addEdge(v1, w); } public void addEdgeUndirected(String v1, String v2) { addEdgeUndirected(v1, v2, 1); } private void addVertex(String v) { if(!graph.containsKey(v)) { graph.put(v, new Vertex(v)); } } public String toString() { String output = ""; for(Map.Entry<String,Vertex> e : graph.entrySet()) { output += e.getValue()+"\n"; } return output; } public void printPath(String vs, String ve, String type) { if(graph.containsKey(vs) && graph.containsKey(ve)) { System.out.println(type.toUpperCase()); Vertex s = graph.get(vs); if(type.toLowerCase().equals("unweighted")) { unweighted(s); } else if(type.toLowerCase().equals("weighted")) { weighted(s); } else if(type.toLowerCase().equals("negative")) { negative(s); } Vertex e = graph.get(ve); /* * Pseudocode if(e.dist != INFINITY){ String path = ""; Vertex curr = e; while(curr.path != null){ path += curr; curr = curr.path; } path = s + path; print(path) print(dist) }else{ print("can not reach end"); } */ if(e.dist != Integer.MAX_VALUE) { String path = ""; Vertex curr = e; while(curr.path != null){ path = curr.getName()+", " + path; curr = curr.path; } path = s.getName()+", " + path; System.out.println(path); System.out.println(e.dist); } else { System.out.println("can not reach end"); } } } public void unweighted(Vertex s) { /* * Pseudocode from textbook PG 372 Queue<Vertex> q = new Queue<Vertex>(); for each Vertex v{ v.dist = INFINITY; v.path = null;//added to make sure we clear the path between runs of pathing methods } s.dist = 0; q.enqueue(s); while(!q.isEmpty()){ Vertex v = q.dequeue(); for each Vertex w adjacent to v{ if(w.dist == INFINITY){ w.dist = v.dist + 1; w.path = v; q.enqueue(w); } } } */ Queue<Vertex> q = new LinkedList<>(); for(Map.Entry<String,Vertex> e : graph.entrySet()) { Vertex v = e.getValue(); v.dist = Integer.MAX_VALUE;//max int is around 2 billion, basically Infinity v.path = null; } s.dist = 0; q.offer(s); while(!q.isEmpty()) { Vertex v = q.poll(); for(Map.Entry<String, Integer> temp : v.adjacent.entrySet()) { Vertex w = graph.get(temp.getKey()); if(w.dist == Integer.MAX_VALUE){ w.dist = v.dist + 1; w.path = v; q.offer(w); } } } } public void weighted(Vertex s) { /* * Pseudocode PriorityQueue<Vertex> q = new PriorityQueue<Vertex>(); //implement Comparable<Vertex> based on distance for PriorityQueue for each Vertex v{ v.dist = INFINITY; v.path = null;//added to make sure we clear the path between runs of pathing methods v.known = false; } s.dist = 0; q.enqueue(s); while(!q.isEmpty()){ Vertex v = q.dequeue();//smallest distance in queue v.known = true; for each Vertex w adjacent to v{ if(w.dist > v.dist + w.weight){ w.dist = v.dist + w.weight; w.path = v; } if(!w.known){ q.enqueue(w); } } } */ PriorityQueue<Vertex> q = new PriorityQueue<>(); for(Map.Entry<String,Vertex> e : graph.entrySet()) { Vertex v = e.getValue(); v.dist = Integer.MAX_VALUE;//max int is around 2 billion, basically Infinity v.path = null; v.known = false; } s.dist = 0; q.offer(s); while(!q.isEmpty()) { Vertex v = q.poll(); v.known = true; for(Map.Entry<String, Integer> temp : v.adjacent.entrySet()) { Vertex w = graph.get(temp.getKey()); Integer weight = temp.getValue(); if(w.dist > v.dist + weight){ w.dist = v.dist + weight; w.path = v; } if(!w.known){ q.offer(w); } } } } public void negative(Vertex s) { /* * Pseudocode Queue<Vertex> q = new Queue<Vertex>(); for each Vertex v{ v.dist = INFINITY; v.path = null;//added to make sure we clear the path between runs of pathing methods } s.dist = 0; q.enqueue(s); while(!q.isEmpty()){ Vertex v = q.dequeue(); for each Vertex w adjacent to v{ if(w.dist > v.dist + w.weight){ w.dist = v.dist + w.weight; w.path = v; if(!q.contains(w)){ q.enqueue(w); } } } } */ Queue<Vertex> q = new LinkedList<>(); for(Map.Entry<String,Vertex> e : graph.entrySet()) { Vertex v = e.getValue(); v.dist = Integer.MAX_VALUE;//max int is around 2 billion, basically Infinity v.path = null; } s.dist = 0; q.offer(s); while(!q.isEmpty()) { Vertex v = q.poll(); for(Map.Entry<String, Integer> temp : v.adjacent.entrySet()) { Vertex w = graph.get(temp.getKey()); Integer weight = temp.getValue(); if(w.dist > v.dist + weight){ w.dist = v.dist + weight; w.path = v; if(!q.contains(w)){ q.offer(w); } } } } } public void printMaxDistance() { int maxDist = 0; String vert = ""; for(Map.Entry<String, Vertex> vertex : graph.entrySet()) if(vertex.getValue().dist != Integer.MAX_VALUE && vertex.getValue().dist > maxDist) { maxDist = vertex.getValue().dist; vert = vertex.getKey(); } System.out.println("MAX:"+vert+":"+maxDist); } public void printTopologicalSort() { System.out.println("Topological Sort:"); int degree[] = new int[V];// array to store the values of vertices for(int i = 0; i < V; i++) { ArrayList<Integer> temp = (ArrayList<Integer>) graph.clone(); for(int node : temp)// traverse the array list that is cloned off the graph { degree[node]++; } } // create a queue that will hold the actual values from the graph at each value of number of vertices Queue<Integer> q = new LinkedList<Integer>(); for(int i = 0;i < V; i++) { if(degree[i]==0) q.add(i); } int count = 0; // Vector that will keep the final sorted list Vector <String> topOrder=new Vector<String>(); while(!q.isEmpty()) { // grab front of queue // and add it to topological order // Go through all the neighboring nodes ArrayList<Integer> temp = (ArrayList<Integer>) graph.clone(); for(int node : temp); { // If in-degree becomes zero, add it to queue } count++; } } } <file_sep>/Recursion/PerimeterComparator.java public class PerimeterComparator { public int compare(Rectangle o1, Rectangle o2) { // TODO Auto-generated method stub return 0; } }
6894fca74969c0d8154c0d42471f54cfea219b7e
[ "Java" ]
18
Java
leviharbin2/Java
d3ab45045189f419f2a1daf00c84a5d69a426032
4daffd3a5d9779675567f1b9c9ad83a213f2fe4c
refs/heads/master
<file_sep>const url= 'https://app.fillgoods.co/login' describe('login to fillgoods',() =>{ it('visit fillgood.co', function(){ cy.visit(url) }) it('Input username', function(){ cy.get('input[data-testid="emailInput"]').type('<EMAIL>') }) it('Input password', function(){ cy.get('input[data-testid="passwordInput"]').type('<PASSWORD>') }) it('Click login', function(){ cy.wait(5000) cy.get('button[data-testid="loginBtn"]').click() cy.wait(5000) }) })<file_sep>const url='https://app.fillgoods.co/app/home/dashboard' describe('go to dashboard page',() => { it('go to dashboard page', function(){ cy.visit(url) }) it('click create orderbtn', function(){ cy.wait(5000) cy.contains('button[aria-label="Close"]').click() cy.get('#Orders').click() //cy.get('#Orders').click() }) })
e4703d69b212007baec2a68d22a3cde8eff86fce
[ "JavaScript" ]
2
JavaScript
Nattawat-Sirirat/test-cypress-fillgoods
2b2164ae5c742f782526859e15afa63221bb44f8
2253da8713b425b7255d5d18bbbab40f7c75e826
refs/heads/master
<repo_name>AlfiyaU/vge<file_sep>/vge/window.h #ifndef WINDOW_H #define WINDOW_H #include <QMainWindow> #include <QWidget> namespace Ui { class Window; } class Window : public QMainWindow { Q_OBJECT public: explicit Window(QWidget *parent = 0); ~Window(); public slots: void openFile(const QString &path = QString()); private: Ui::Window *ui; }; #endif // WINDOW_H <file_sep>/vge/window.cpp #include "window.h" #include "ui_window.h" #include <QtWidgets> #include <QtSvg> #include <QSvgRenderer> #include <renderarea.h> Window::Window(QWidget *parent) : QMainWindow(parent) { QMenu *fileMenu = new QMenu("File", this); QAction *openFileAction = fileMenu->addAction("Open..."); menuBar()->addMenu(fileMenu); connect(openFileAction, SIGNAL(triggered()), this, SLOT(openFile())); ui->setupUi(this); } Window::~Window() { //delete ui; } void Window::openFile(const QString &path) { QString pathToFile; if(path.isNull()){ pathToFile = QFileDialog::getOpenFileName(this, tr("Open file"),"","SVG file (*.svg)"); } else pathToFile = path; QFile file(pathToFile,this); QSvgWidget *svg = new QSvgWidget(file.fileName(),this); svg->show(); //setCentralWidget(); //QSvgRenderer *ren = svg.renderer(); } <file_sep>/vge/main.cpp #include "window.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Window w; if (argc == 2){//argc - количество аргументов запуска //какие то действия, если открываем файл перетаскиванием на экзешник } w.show(); //QSvgWidget svg(":/Svg.svg"); //svg.show(); //QObject::connect(svg.renderer(), SIGNAL(repaintNeeded()), &svg, SLOT(repaint())); return a.exec(); } <file_sep>/vge/renderarea.cpp #include "renderarea.h" renderArea::renderArea(QWidget *parent) : QWidget(parent) { } <file_sep>/vge/renderarea.h #ifndef RENDERAREA_H #define RENDERAREA_H #include <QWidget> #include <QGraphicsView> class renderArea : public QWidget { Q_OBJECT public: explicit renderArea(QWidget *parent = 0); signals: public slots: }; #endif // RENDERAREA_H
93caa2e63e2b479731f7e7343e72c47717447afa
[ "C++" ]
5
C++
AlfiyaU/vge
f3a093183a917a4109e2188cfa96cf0d71ef25de
eb2a29f9cf0c76ce5df1e93ce66db3ed86ee7b47
refs/heads/master
<file_sep>package com.itshareplus.googlemapdemo; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void setupMapButton(View view) { Intent intent = new Intent(this, MapsActivity.class); this.startActivity(intent); } public void setupSearchButton(View view) { Toast msg = Toast.makeText(MainActivity.this, "Search Button", Toast.LENGTH_LONG); msg.show(); } public void setupAboutButton(View view) { Intent intent = new Intent(this, AboutActivity.class); this.startActivity(intent); } public void setupHelpButton(View view) { Intent intent = new Intent(this, HelpActivity.class); this.startActivity(intent); } }
39bcca603b142e13a4b4497458d1287e9d6dd673
[ "Java" ]
1
Java
nowaynoway402/noWay
5f00ed27034b74a77ca9c12b8e71a48aae75c0bf
70ed67a580b128ef2d70012308a235f300375353
refs/heads/master
<repo_name>WilliamMoller/Webbserverprogrammering<file_sep>/Uppgifter/login/submit.php <?php $dbc = mysqli_connect("localhost","root","","users"); $FirstName = $_POST['Fname']; $Password = $_POST['psw']; $query = "SELECT * FROM form WHERE First_Name='$FirstName' AND Password='$Password';"; mysqli_query($dbc,$query); $result = mysqli_query($dbc,$query); if($row = mysqli_fetch_array($result)){ echo "Logged in successfully!"; } else{ echo "Failed to login, wrong name or password"; } ?><file_sep>/Uppgifter/register/submit.php <?php $dbc = mysqli_connect("localhost","root","","users"); $Username = $_POST['Uname']; $FirstName = $_POST['Fname']; $LastName = $_POST['Lname']; $Email = $_POST['Email']; $Birthday = $_POST['Birthday']; $Password = $_POST['psw']; $query = "INSERT INTO form(Username,First_Name,Last_Name,Email,Birthday,Password) VALUES('$Username','$FirstName','$LastName','$Email','$Birthday','$Password');"; mysqli_query($dbc,$query); ?>
d5cf68fbef9fceb59d01ae119644a341c6959273
[ "PHP" ]
2
PHP
WilliamMoller/Webbserverprogrammering
1da4d72689ceda0d3ad015c651227960a347d40e
3890b07785663157438384a89ededaf1eef3b134
refs/heads/master
<file_sep>main: main.go go build main.go clean: rm main <file_sep>package main import ( "fmt" "html/template" "net/http" ) /* Server will be available on localhost:port */ var port = 4321 /* * Initialize request handlers and begin listening for requests. */ func main() { http.HandleFunc("/", index) http.HandleFunc("/greetings", greetings) http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources/")))) fmt.Printf("Server listening on port %d\n", port) err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil) if err != nil { fmt.Println(err) } } /* * Handles requests to the site root. */ func index(w http.ResponseWriter, r *http.Request) { tmpl, err := template.ParseFiles("index.html") if err != nil { fmt.Println(err) } else { _ = tmpl.Execute(w, nil) } } /* * Endpoint to display a greeting after form submission. * Redirect back to site root if request isn't a POST. */ func greetings(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { name := r.FormValue("name") fmt.Printf("Name %s\n", name) tmpl, err := template.ParseFiles("greeting.html") if err != nil { fmt.Println(err) } else { _ = tmpl.Execute(w, name) } } else { http.Redirect(w, r, "/", http.StatusSeeOther) } }
4bccce42c0bad1ed83de7f7f8d52414382dc7f9d
[ "Go", "Makefile" ]
2
Makefile
thomed/go-web-template
cff4f45d92d26025718315697f8ecb7738f01535
3f52a14ea0dd0545e43baa1ecc1ac573a69f08c0
refs/heads/master
<repo_name>AdnanLapendic/workspace<file_sep>/ba.bitcamp.week11/src/ba/bitcamp/week11/day5/vjezbe/Server.java package ba.bitcamp.week11.day5.vjezbe; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class Server extends JFrame { private static final long serialVersionUID = 1369967673628477747L; private int x = 200; private int y = 200; private int deltaY = 0; private int deltaX = 0; private MyPanel panel = new MyPanel(); private ServerSocket server; private Socket client; private BufferedReader reader; private BufferedWriter writer; private String key = ""; public Server() { Timer t = new Timer(20, new Action()); t.start(); setLayout(new BorderLayout()); setSize(400, 400); setLocationRelativeTo(null); setTitle("Server"); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(panel); addKeyListener(new Motion()); setVisible(true); try { server = new ServerSocket(8000); client = server.accept(); reader = new BufferedReader(new InputStreamReader( client.getInputStream())); writer = new BufferedWriter(new OutputStreamWriter( client.getOutputStream())); while (true) { String step = reader.readLine(); if (step.equals("A")) { deltaX -= 1; deltaY = 0; } else if (step.equals("D")) { deltaX += 1; deltaY = 0; } else if (step.equals("W")) { deltaY -= 1; deltaX = 0; } else if (step.equals("S")) { deltaY += 1; deltaX = 0; } repaint(); System.out.println(key); } } catch (IOException e) { e.printStackTrace(); } } private class Action implements ActionListener { @Override public void actionPerformed(ActionEvent e) { x += deltaX; y += deltaY; } } private class MyPanel extends JPanel { private static final long serialVersionUID = -3604159756556836756L; @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLUE); g.fillRect(x, y, 20, 20); repaint(); } } private class Motion implements KeyListener { @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_A) { deltaX -= 1; deltaY = 0; try { writer.write("A"); writer.newLine(); writer.flush(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else if (e.getKeyCode() == KeyEvent.VK_D) { deltaX += 1; deltaY = 0; try { writer.write("D"); writer.newLine(); writer.flush(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else if (e.getKeyCode() == KeyEvent.VK_W) { deltaY -= 1; deltaX = 0; try { writer.write("W"); writer.newLine(); writer.flush(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else if (e.getKeyCode() == KeyEvent.VK_S) { deltaY += 1; deltaX = 0; try { writer.write("S"); writer.newLine(); writer.flush(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } repaint(); } @Override public void keyReleased(KeyEvent e) { } } public static void main(String[] args) { new Server(); } } <file_sep>/ba.bitcamp.week07/src/ba/bitcamp/week7/day4/vjezbe/Task3.java package ba.bitcamp.week7.day4.vjezbe; import java.awt.BorderLayout; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; public class Task3 extends JFrame{ private static final long serialVersionUID = 1575068511776448780L; private JPanel panel1=new JPanel(); private JPanel panel2 = new JPanel(); private JTextArea text = new JTextArea(); private JPanel panel21 = new JPanel(); private JPanel panel22= new JPanel(); public Task3(){ setLayout(new BorderLayout()); add(panel1, BorderLayout.CENTER); add(panel2, BorderLayout.EAST); setSize(500,300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); panel1.setBorder(BorderFactory.createTitledBorder("Center panel")); panel2.setBorder(BorderFactory.createTitledBorder("East panel")); panel1.add(text); panel2.setLayout(new GridLayout(2,1)); panel2.add(panel21); panel2.add(panel22); panel21.setLayout(new GridLayout(3,1)); panel21.setBorder(BorderFactory.createTitledBorder("Panel 1")); for (int i = 1; i <= 3; i++) { panel21.add(new JLabel("This seems to be a label" + i)); } panel22.setBorder(BorderFactory.createTitledBorder("Panel 2")); panel22.add(new JButton("Button 1")); panel22.add(new JButton("Button 2")); setVisible(true); } public static void main(String[] args) { new Task3(); } } <file_sep>/ba.bitcamp.week07/src/ba/bitcamp/week7/day4/Main.java package ba.bitcamp.week7.day4; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class Main { public static void main(String[] args) { JFrame window = new JFrame(); JPanel container = new JPanel(); JButton[] buttons = new JButton[5]; container.setLayout(new FlowLayout(FlowLayout.LEADING,0,0)); //container.setLayout(new BorderLayout()); //container.setLayout(new GridLayout(2,3)); for (int i = 0; i < buttons.length; i++) { buttons[i] = new JButton("Button" + i); buttons[i].setPreferredSize(new Dimension(100,100)); int red=(int)(Math.random()*255); int green=(int)(Math.random()*255); int blue=(int)(Math.random()*255); container.add(buttons[i]); buttons[i].setOpaque(true); //buttons[i].setBorder(BorderFactory.createEmptyBorder()); //buttons[i].setBorder(BorderFactory.createLineBorder(Color.BLACK, 5,true)); //buttons[i].setBorder(BorderFactory.createMatteBorder(5, 5, 10, 10, Color.GRAY)); //buttons[i].setBorder(BorderFactory.createEtchedBorder()); if(i%2==0){ buttons[i].setBorder(BorderFactory.createRaisedBevelBorder()); }else{ buttons[i].setBorder(BorderFactory.createLoweredBevelBorder()); } buttons[i].setBackground(new Color(red,green,blue)); } // container.add(buttons[0], BorderLayout.EAST); // container.add(buttons[1], BorderLayout.WEST); // container.add(buttons[2], BorderLayout.NORTH); // container.add(buttons[3], BorderLayout.SOUTH); // container.add(buttons[4], BorderLayout.CENTER); window.add(container); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setSize(400, 400); window.setVisible(true); } } <file_sep>/ba.bitcamp.week14/src/ba/bitcamp/week14/day1/vjezbe/Team.java package ba.bitcamp.week14.day1.vjezbe; public class Team { private int id; private String name; String wins; String losses; String points; String scoredPlus; String scoredMinus; String fromGroup; public Team(int id, String name, String wins, String losses, String points, String scoredPlus, String scoredMinus, String fromGroup) { this.id = id; this.name = name; this.wins = wins; this.losses = losses; this.points = points; this.scoredPlus = scoredPlus; this.scoredMinus = scoredMinus; this.fromGroup = fromGroup; } public int getId() { return id; } public String getName() { return name; } public String getWins() { return wins; } public String getLosses() { return losses; } public String getPoints() { return points; } public String getScoredPlus() { return scoredPlus; } public String getScoredMinus() { return scoredMinus; } public String getFromGroup() { return fromGroup; } @Override public String toString() { return "Team [id=" + id + ", name=" + name + ", wins=" + wins + ", losses=" + losses + ", points=" + points + ", scoredPlus=" + scoredPlus + ", scoredMinus=" + scoredMinus + ", fromGroup=" + fromGroup + "]"; } } <file_sep>/ba.bitcamp.week12/src/ba/bitcamp/week12/day2/vjezbe/StopThreads.java package ba.bitcamp.week12.day2.vjezbe; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class StopThreads extends JFrame { private static final long serialVersionUID = -9173660197136295504L; private JPanel panel; private JPanel buttons; private JLabel label; private JButton stop; private JButton start; private List<Thread>list = new ArrayList<>(); public StopThreads() { setLayout(new BorderLayout()); setSize(300, 100); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(panel = new JPanel()); panel.add(label = new JLabel("Stopping Multiple Threads"), BorderLayout.CENTER); add(buttons = new JPanel(), BorderLayout.SOUTH); buttons.setLayout(new GridLayout(1, 2)); buttons.add(start = new JButton("START")); buttons.add(stop = new JButton("S T O P")); stop.addActionListener(new Action()); start.addActionListener(new Action()); setVisible(true); } private class Action implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == start) { Thread t = new Thread(new MyThread()); list.add(t); t.start(); } if (e.getSource() == stop) { for(Thread t:list){ t.interrupt(); try { t.sleep(300); } catch (InterruptedException e1) { e1.printStackTrace(); } System.out.println(t.isAlive()); } } } } class MyThread implements Runnable { @Override public void run() { for (int i = 1; i < 101; i++) { System.out.println(i); try { Thread.sleep(400); } catch (InterruptedException e) { return; } } } } public static void main(String[] args) { new StopThreads(); } } <file_sep>/ba.bitcamp.week06/src/ba/bitcamp/week6/day6/vjezbe/Main.java package ba.bitcamp.week6.day6.vjezbe; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; public class Main extends JFrame { private static final long serialVersionUID = 1L; private JLabel text = new JLabel("Neki text"); private JLabel button1 = new JLabel("Exit"); private JLabel button2 = new JLabel("Right"); private JLabel button3 = new JLabel("Left"); public Main() { // JLabel text = new JLabel("Hello World"); // add(text); setLayout(new BorderLayout()); add(text); add(button1, BorderLayout.WEST); add(button2, BorderLayout.EAST); add(button3, BorderLayout.WEST); JButton dugme = new JButton("OK"); add(dugme); dugme.addActionListener(new Action()); setVisible(true); setTitle("Prozor"); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); } private class Action implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==button1){ System.exit(0); }else if(e.getSource()==button2){ text.setText("Pritisnuo si lijevo dugme"); } } } public static void main(String[] args) { @SuppressWarnings("unused") Main prozor = new Main(); // JFrame prozor = new JFrame(); // prozor.setVisible(true); // prozor.setTitle("Prozor"); // prozor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // prozor.setSize(400, 300); // prozor.setLocation(520, 250); // prozor.setLocationRelativeTo(null); // prozor.setResizable(false); // prozor.setIconImage(image); // // prozor.set } } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day4/Task3InsertionSort.java package ba.bitcamp.week8.day4; import java.util.Arrays; import java.util.Random; public class Task3InsertionSort { public static void main(String[] args) { Random rnd = new Random(); int arraySize = 1000; int[] arr = new int[arraySize]; for (int i = 0; i < arraySize; i++) { arr[i] = rnd.nextInt(3 * arraySize); } System.out.println(Arrays.toString(arr)); insertionSort(arr); System.out.println(Arrays.toString(arr)); } public static void insertionSort(int[] arr) { for (int i = 1; i < arr.length; i++) { int temp = arr[i]; int location = i - 1; while (location >= 0 && temp < arr[location]) { arr[location + 1] = arr[location]; location--; } arr[location + 1] = temp; } } } <file_sep>/ba.bitcamp.week09/src/ba/bitcamp/week9/day2/vjezbe/Main.java package ba.bitcamp.week9.day2.vjezbe; public class Main { public static void main(String[] args) { StackListString stack = new StackListString(); //System.out.println(stack.isEmpty()); stack.push("a"); stack.push("b"); stack.push("c"); System.out.println(stack.isEmpty()); System.out.println(stack); // System.out.println(stack.pop()); //System.out.println(stack.isEmpty()); //System.out.println(stack.pop()); System.out.println(stack.isEmpty()); System.out.println(stack); } } <file_sep>/ba.bitcamp.week06/src/ba/bitcamp/day4/rekurzija/Task1.java package ba.bitcamp.day4.rekurzija; public class Task1 { public static void main(String[] args) { print("Adnan", 3); } public static void print(String s, int n) { if (n == 0) { return; } System.out.println(s.toString()); print(s, n-1); } } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day4/vjezbe/Employee.java package ba.bitcamp.week8.day4.vjezbe; public class Employee { private int Id; private static int counter = 1001; private String firstName; private String lastName; private String gender; private int salary; private DateOfBirth date; public Employee() { Id = counter; counter++; } public Employee(String firstName, String lastName, String gender, int salary, int day, int month, int year) { Id = counter; counter++; this.firstName = firstName; this.lastName = lastName; this.gender = gender; this.salary = salary; this.date = new DateOfBirth(day, month, year); } public int getId() { return Id; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getGender() { return gender; } public int getSalary() { return salary; } public DateOfBirth getDate() { return date; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setSalary(int salary) { this.salary = salary; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Employee other = (Employee) obj; if (date == null) { if (other.date != null) return false; } else if (!date.equals(other.date)) return false; if (firstName == null) { if (other.firstName != null) return false; } else if (!firstName.equals(other.firstName)) return false; if (gender == null) { if (other.gender != null) return false; } else if (!gender.equals(other.gender)) return false; if (lastName == null) { if (other.lastName != null) return false; } else if (!lastName.equals(other.lastName)) return false; if (salary != other.salary) return false; return true; } @Override public String toString() { return "Employee: \n" + "Name=" + firstName + " " + lastName + "\n" + "ID:" + Id + "\n" + "Gender: " + gender + "\n" + "Salary: " + salary + "$" + "\n" + "Date of birth: " + date + "\n" + "===========================" + "\n"; } protected class DateOfBirth { private int day; private int month; private int year; public DateOfBirth(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } public int getDay() { return day; } public int getMonth() { return month; } public int getYear() { return year; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DateOfBirth other = (DateOfBirth) obj; if (day != other.day) return false; if (month != other.month) return false; if (year != other.year) return false; return true; } @Override public String toString() { return day + "." + month + "." + year; } } } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day1/vjezbe/TwoJDialogs.java package ba.bitcamp.week8.day1.vjezbe; import java.awt.Dialog.ModalityType; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; public class TwoJDialogs extends JFrame{ private static final long serialVersionUID = 4437567114133600056L; private JDialog dialog1 = new JDialog(); private JDialog dialog2 = new JDialog(); private JButton button1 = new JButton("1"); private JButton button2 = new JButton("2"); public TwoJDialogs(){ setLayout(new GridLayout(2,1)); setSize(200,100); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(button1); add(button2); button1.addActionListener(new Action()); button2.addActionListener(new Action()); setVisible(true); } private class Action implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==button1){ dialog1=new JDialog(); dialog1.setSize(100,100); dialog1.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog1.setLocationRelativeTo(null); dialog1.setModalityType(ModalityType.MODELESS); dialog1.setVisible(true); } else if(e.getSource()==button2){ dialog2=new JDialog(); dialog2.setSize(100,100); dialog2.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog2.setLocationRelativeTo(null); dialog2.setModalityType(ModalityType.APPLICATION_MODAL); dialog2.setVisible(true); } } } public static void main(String[] args) { new TwoJDialogs(); } } <file_sep>/ba.bitcamp.week05/src/ba/bitcamp/week5/day5/PogodiBroj.java package ba.bitcamp.week5.day5; import java.util.Random; import java.util.Scanner; public class PogodiBroj { private int maxBroj; private int maxBrojPokusaja; public PogodiBroj(int maxBroj, int maxBrojPokusaja) { super(); this.maxBroj = maxBroj; this.maxBrojPokusaja = maxBrojPokusaja; } public PogodiBroj(int maxBroj) { this(maxBroj, maxBroj / 100 + 1); } public PogodiBroj() { this(1000, 10); } public void igraj() { @SuppressWarnings("resource") Scanner in = new Scanner(System.in); Random rand = new Random(); int zamisljeniBroj = rand.nextInt(maxBroj - 1) + 1; int counter = 0; int broj = 0; while (counter < maxBrojPokusaja) { counter++; broj = in.nextInt(); if (broj == zamisljeniBroj) { System.out.println("Pogodak!"); return; } if (broj < zamisljeniBroj) { System.out.println("Zamisljeni broj je veci!"); } if (broj > zamisljeniBroj) { System.out.println("Zamisljeni broj je manji"); } else { System.out.println("Niste pogodili"); } } } @Override public String toString() { return "PogodiBroj [maxBroj=" + maxBroj + ", maxBrojPokusaja=" + maxBrojPokusaja + "]"; } }<file_sep>/ba.bitcamp.week06/src/ba/bitcamp/week6/day5/Task3.java package ba.bitcamp.week6.day5; import java.util.Arrays; public class Task3 { @SuppressWarnings("unused") public static int[] getSumm(int[] arr1, int[] arr2) { String s1 = Arrays.toString(arr1); String s2 = Arrays.toString(arr2); int a = Integer.parseInt(s2) + Integer.parseInt(s1); return arr1; } public static void main(String[] args) { } } <file_sep>/ba.bitcamp.week13/src/ba/bitcamp/week13/snake/Snake.java package ba.bitcamp.week13.snake; import java.awt.Point; public class Snake { static private final int GRID_SIZE = 10; private Point head; private Point[] tail; private int snakeLength; public Snake() { head = new Point(GRID_SIZE, GRID_SIZE); tail = new Point[300]; snakeLength = 5; for(int i = 0; i < snakeLength; i++) { tail[i] = new Point(head.x, head.y); } } public void moveSnake() { for(int i = 1; i < snakeLength; i++) { tail[snakeLength-i].x = tail[snakeLength-i-1].x; tail[snakeLength-i].y = tail[snakeLength-i-1].y; } tail[0].x = head.x; tail[0].y = head.y; } public void setHeadPosition(int x, int y) { head.x += x; head.y += y; } public boolean checkGameOver() { for(int i = 1; i < snakeLength; i++) { if((tail[i].x == head.x) && (tail[i].y == head.y)) { return true; } } if(head.x < 0 || head.x > GRID_SIZE * 14 || head.y < 0 || head.y > GRID_SIZE * 14) { return true; } return false; } public synchronized void increaseLength() { tail[snakeLength] = new Point(tail[snakeLength-1].x, tail[snakeLength-1].y); snakeLength++; } public int getSnakeLength() { return snakeLength; } static public int getGridSize() { return GRID_SIZE; } public Point[] getAllPositions() { return tail; } public Point getHead() { return head; } }<file_sep>/ba.bitcamp.week12/src/ba/bitcamp/week12/day1/vjezbe/Client.java package ba.bitcamp.week12.day1.vjezbe; import java.io.File; import java.io.IOException; import java.util.ArrayList; import org.codehaus.jackson.map.ObjectMapper; public class Client { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); ObjectMapper mapper = new ObjectMapper(); try { mapper.writeValue(new File("/Users/adnan.lapendic/Desktop/message.txt"), list); System.out.println("It worked!"); } catch (IOException e) { e.printStackTrace(); } } }<file_sep>/ba.bitcamp.week09/src/ba/bitcamp/week9/day3/ColectionUtils.java package ba.bitcamp.week9.day3; import java.util.Collection; public class ColectionUtils { public static void print(Collection<String> strings){ } public static void main(String[] args) { } } <file_sep>/ba.bitcamp.week14/src/ba/bitcamp/week14/day1/vjezbe/Main.java package ba.bitcamp.week14.day1.vjezbe; import java.io.ObjectInputStream.GetField; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; public class Main { public static void main(String[] args) { String db = "jdbc:sqlite:/Users/adnan.lapendic/Desktop/BitSql/standings.db"; SqlConnection.getConnection(db); System.out.println("Connection established"); ArrayList<Player> players = new ArrayList<>(); ArrayList<Team> teams = new ArrayList<>(); // Player p1 = new Player(1, "<NAME>", 15); // players.add(p1); // Player p2 = new Player(2, "<NAME>", 16); // players.add(p2); // Player p3 = new Player(3, "Bit Camp", 15); // players.add(p3); // try { // for(Player p:players){ // Statement statement = SqlConnection.getConn().createStatement(); // // String command = "INSERT INTO test VALUES(" + p.getId() + ", '" + // p.getName() + "', " + p.getAge()+")"; // // statement.executeUpdate(command); // } // } catch (SQLException e) { // System.out.println("Bas SQL Command"); // System.err.println(e.getMessage()); // } try { Statement statement = SqlConnection.getConn().createStatement(); ResultSet result = statement.executeQuery("SELECT * FROM team"); while (result.next()) { int id = result.getInt(1); String name = result.getString(2); String wins = result.getString(3); String losses = result.getString(4); String points = result.getString(5); String scoredPlus = result.getString(6); String scoredMinus = result.getString(7); String fromGroup = result.getString(8); Team t = new Team(id, name, wins, losses, points, scoredPlus, scoredMinus, fromGroup); teams.add(t); } statement.close(); result.close(); } catch (SQLException e) { System.out.println("Bas SQL Command"); System.err.println(e.getMessage()); } System.out.println(teams); try { Statement statement = SqlConnection.getConn().createStatement(); ResultSet result = statement .executeQuery("SELECT * FROM team ORDER BY scoredplus"); while (result.next()) { System.out.println(result.getString(1) + "|" + result.getString(2) + "|" + result.getString(3) + "|" + result.getString(4) + "|" + result.getString(5) + "|" + result.getString(6) + "|" + result.getString(7) + "|" + result.getString(8)); } statement.close(); result.close(); } catch (SQLException e) { System.out.println("Bas SQL Command"); System.err.println(e.getMessage()); } System.out.println("*********TASK 3**********"); try { Statement statement = SqlConnection.getConn().createStatement(); ResultSet result = statement .executeQuery("SELECT * FROM team ORDER BY fromgroup, scoredplus"); while (result.next()) { System.out.println(result.getString(1) + "|" + result.getString(2) + "|" + result.getString(3) + "|" + result.getString(4) + "|" + result.getString(5) + "|" + result.getString(6) + "|" + result.getString(7) + "|" + result.getString(8)); } } catch (SQLException e) { System.out.println("Bas SQL Command"); System.err.println(e.getMessage()); } System.out.println("*********TASK 4**********"); try { String group = "A"; Statement statement = SqlConnection.getConn().createStatement(); ResultSet result = statement .executeQuery("SELECT * FROM team WHERE fromgroup =" + "\"" + group + "\""); while (result.next()) { System.out.println(result.getString(1) + "|" + result.getString(2) + "|" + result.getString(3) + "|" + result.getString(4) + "|" + result.getString(5) + "|" + result.getString(6) + "|" + result.getString(7) + "|" + result.getString(8)); } } catch (SQLException e) { System.out.println("Bas SQL Command"); System.err.println(e.getMessage()); } System.out.println("*********TASK 5**********"); try { Statement statement = SqlConnection.getConn().createStatement(); ResultSet result = statement .executeQuery("SELECT * FROM team WHERE points>4"); while (result.next()) { System.out.println(result.getString(1) + "|" + result.getString(2) + "|" + result.getString(3) + "|" + result.getString(4) + "|" + result.getString(5) + "|" + result.getString(6) + "|" + result.getString(7) + "|" + result.getString(8)); } } catch (SQLException e) { System.out.println("Bas SQL Command"); System.err.println(e.getMessage()); } System.out.println("*********TASK 6**********"); try { Statement statement = SqlConnection.getConn().createStatement(); ResultSet result = statement .executeQuery("SELECT * FROM team WHERE (scoredplus/ points)>60"); while (result.next()) { System.out.println(result.getString(1) + "|" + result.getString(2) + "|" + result.getString(3) + "|" + result.getString(4) + "|" + result.getString(5) + "|" + result.getString(6) + "|" + result.getString(7) + "|" + result.getString(8)); } } catch (SQLException e) { System.out.println("Bas SQL Command"); System.err.println(e.getMessage()); } } } <file_sep>/ba.bitcamp.week09/src/ba/bitcamp/week9/day1/vjezbe/Genre.java package ba.bitcamp.week9.day1.vjezbe; public class Genre { public static final String ROCK = "Rock"; public static final String METAL = "Metal"; public static final String EX_YU_ROCK = "Ex Yu Rock"; public Genre(){ } @Override public String toString() { return "Genre []"; } } <file_sep>/ba.bitcamp.week11/src/ba/bitcamp/week11/day4/Main.java package ba.bitcamp.week11.day4; import java.util.Date; public class Main { // public static void main(String[] args) { // // NamedThread t1 = new NamedThread("Ross"); // NamedThread t2 = new NamedThread("Joey"); // NamedThread t3 = new NamedThread("Rachel"); // // t1.start(); // t2.start(); // t3.start(); // // try { // t1.join(); // t2.join(); // t3.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // System.out.println("END OF MAIN!"); // // } // // public static void main(String[] args) { Date start = new Date(); PrimeCounter[] counters = new PrimeCounter[20]; // int startInterval = 1; int endInterval = 1000000; int step = endInterval / counters.length; for (int i = 0; i < counters.length; i++) { counters[i] = new PrimeCounter(i * step, (i + 1) * step); counters[i].start(); } for (int i = 0; i < counters.length; i++) { try { counters[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Primes count: " + counters[0].getCount()); Date end = new Date(); long timeLapse = (end.getTime() - start.getTime()) / 1000; System.out.println("Time (s): " + timeLapse); System.out.println("End of Main!"); } } <file_sep>/ba.bitcamp.week07/src/ba/bitcamp/week7/day1/vjezbe/Task3.java package ba.bitcamp.week7.day1.vjezbe; import java.awt.BorderLayout; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JLabel; public class Task3 extends JFrame { private static final long serialVersionUID = 7490402481379348281L; private JLabel label = new JLabel(); public Task3() { setLayout(new BorderLayout()); add(label); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(300, 200); label.addMouseListener(new Mouse()); setVisible(true); } private class Mouse implements MouseListener { @Override public void mouseClicked(MouseEvent e) { if (e.getSource() == label) { switch (e.getButton()) { case 1: label.setText("Button Left"); case 2: label.setText("Button MIddle"); case 3: label.setText("Button Right"); } } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } } public static void main(String[] args) { new Task3(); } } <file_sep>/ba.bitcamp.week09/src/ba/bitcamp/week9/day1/Main.java package ba.bitcamp.week9.day1; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); Place head = null; Place last = null; while (true) { String s = in.nextLine(); if (s.length() != 0) { Place newPlace = new Place(s); if (head == null && last == null) { head = newPlace; last = newPlace; } else { last.setNext(newPlace); last = newPlace; } }else{ break; } } // Trip t = new Trip(head); // Place currentPlace =t.getStart(); // int length = 0; // Place currentPlace = head; // ArrayList<Place> places = new ArrayList<>(); // while(currentPlace != null){ // places.add(currentPlace); // currentPlace = currentPlace.getNext(); // // length+=1; // } // Place place = new Place("Aaaaa"); // // System.out.printf("You have visited %d places", length); // System.out.println("You have visited" +places); // // LinkedList<Place> list = new LinkedList<>(); // list. in.close(); } } <file_sep>/ba.bitcamp.week10/src/ba/bitcamp/week10/day2/vjezbe/Task3Employee.java package ba.bitcamp.week10.day2.vjezbe; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.LinkedList; public class Task3Employee implements Serializable { /** * */ private static final long serialVersionUID = -4991647844806408503L; private String name; private int age; private String gender; public Task3Employee(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } public String toString() { return "->Name: " + name + "\nAge :" + age + "\nGender: " + gender + "\n"; } public static void main(String[] args) { LinkedList<Task3Employee> list = new LinkedList<>(); Task3Employee e1 = new Task3Employee("Adnan", 29, "M"); Task3Employee e2 = new Task3Employee("Boris", 28, "M"); Task3Employee e3 = new Task3Employee("Medina", 25, "F"); Task3Employee e4 = new Task3Employee("Edin", 30, "M"); list.add(e4); list.add(e3); list.add(e2); list.add(e1); System.out.println(list); try { @SuppressWarnings("resource") ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Employees")); for(Task3Employee e:list){ oos.writeObject(e); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>/ba.bitcamp.week12/src/ba/bitcamp/week12/day4/GUI.java package ba.bitcamp.week12.day4; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JTextArea; import javax.swing.JTextField; public class GUI extends JFrame { private static final long serialVersionUID = 8955243869222692807L; private JPanel southPanel; private JTextField msgField; private JButton sendButton; private JTextArea msgTextArea; @SuppressWarnings("unused") private JScrollBar scroll; private String textFromServer; private static Socket client; BufferedWriter writer; BufferedReader reader; private ExecutorService pool = Executors.newSingleThreadExecutor(); public GUI() { setLayout(new BorderLayout()); setSize(430, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setTitle("GUI Chat Client"); add(southPanel = new JPanel(), BorderLayout.SOUTH); southPanel.setLayout(new GridLayout(1,2)); southPanel.add(msgField = new JTextField(30)); southPanel.add(sendButton = new JButton("Send")); add(msgTextArea = new JTextArea()); msgTextArea.setEditable(false); add(scroll = new JScrollBar(), BorderLayout.EAST); sendButton.addActionListener(new Action()); setVisible(true); // Socket for server connection try { client = new Socket("10.0.82.27", 6815); writer = new BufferedWriter(new OutputStreamWriter( client.getOutputStream())); reader = new BufferedReader(new InputStreamReader( client.getInputStream())); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } new Thread(new Runnable() { @Override public void run() { for (;;) { try { textFromServer = reader.readLine(); msgTextArea.append("Server: " + textFromServer + "\n"); } catch (IOException e) { e.printStackTrace(); } } } }).start(); } /** * This private class implements ActionListener, it has one method * actionPerformed() which is used to send messages when button "Send" is * clicked. * * @author <NAME> * */ private class Action implements ActionListener { @Override public void actionPerformed(ActionEvent e) { pool.submit(new Runnable() { @Override public void run() { String msg = msgField.getText(); try { writer.write(msg); writer.newLine(); writer.flush(); } catch (IOException e) { e.printStackTrace(); } msgTextArea.append("Me: " + msg + "\n"); msgField.setText(""); } }); // Setting field to be blank } } /** * This method is checking every message for "special" commands from Task#2 * /open - open file, /web - open web page, /delete - delete file specified * in path, /list - write all files in that directory * * @param text * - Received messages */ public static void main(String[] args) { new GUI(); } }<file_sep>/ba.bitcamp.week07/src/ba/bitcamp/week7/day2/GameRunner.java package ba.bitcamp.week7.day2; import javax.swing.JFrame; public class GameRunner { public static void main(String[] args) { RaceingGame raceingGame = new RaceingGame(0, 0, null); JFrame window = new JFrame(); window.setSize(800,600); window.setLocation(50, 50); window.setResizable(false); window.setContentPane(raceingGame); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); } } <file_sep>/ba.bitcamp.week5/src/ba/bitcamp/week5/day3/practice/Speaker.java package ba.bitcamp.week5.day3.practice; public class Speaker { private static final int MAX_VOLUME = 100; private String name; private int price; private boolean isItOn = false; private int batteryPercent; private int volume = 0; /** * Constructor for Speaker * * @param name * - name of manufacturer * @param batteryPercent * - how much battery uses in an hour * @param price * - Cell phone price */ public Speaker(String name, int batteryProcent, int price) { this.name = name; this.batteryPercent = batteryProcent; this.price = price; } /** * Get phone manufacturer * * @return -Manufacturer name */ public String getName() { return name; } /** * Get phone price * * @return - Price of the phone */ public int getPrice() { return price; } /** * Tells us is phone on or of * * @return true or false */ public boolean getIsItOn() { return isItOn; } /** * Gets current volume of speakers * * @return Current volume */ public int getVolume() { return volume; } /** * Tells us how much battery speakers use in an hour * @return Battery percent */ public int getBatteryPercent(){ return batteryPercent; } /** * Turning speakers on */ public void enable() { if (isItOn == false) { isItOn = true; } else { } } /** * Turning speakers off */ public void disable() { if (isItOn == true) { isItOn = false; } else { } } /** * Decreases volume by 10 */ public void lowerVolume() { if (volume < 10 || isItOn == false) { volume = 0; } else volume -= 10; } /** * Increases volume by 10 */ public void increaseVolume() { if (volume < MAX_VOLUME && isItOn == true) { volume += 10; } else if (volume + 10 > MAX_VOLUME) { volume = MAX_VOLUME; } } public String toString() { String s = ""; s += "Name: " + name + "\n"; if (isItOn == true) { s += "Volume: " + volume + "\n"; } else { s += "Off"; } return s; } } <file_sep>/ba.bitcamp.week11/src/ba/bitcamp/week11/day4/vjezbe/NewChat.java package ba.bitcamp.week11.day4.vjezbe; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class NewChat { public static void main(String[] args) { try { @SuppressWarnings("resource") ServerSocket server = new ServerSocket(9912); while (true) { Socket client = server.accept(); Thread t = new Thread(new MyThread(client)); t.start(); } } catch (IOException e) { e.printStackTrace(); } } public static class MyThread implements Runnable { Scanner in = new Scanner(System.in); private Socket client; public MyThread(Socket client) { this.client = client; } @Override public void run() { try { BufferedReader reader = new BufferedReader( new InputStreamReader(client.getInputStream())); System.out.println("Neko: " + reader.readLine()); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(client.getOutputStream())); System.out.print("Ado: "); writer.write(in.nextLine()); writer.flush(); } catch (IOException e) { e.printStackTrace(); } } }public static class MyThread2 implements Runnable{ @Override public void run() { // TODO Auto-generated method stub } } } <file_sep>/ba.bitcamp.week5/src/ba/bitcamp/week5/day2/Point.java package ba.bitcamp.week5.day2; public class Point { private int x; private int y; public Point(int x, int y) { this.x = x; this.y = y; } public String toString() { String output = String.format("X = : %d, Y = : %d", x, y); return output; } public boolean equals(Point other) { boolean bool = true; if (this.x == other.x && this.y == other.y) { bool = true; } else if (this.y != other.y || this.x != other.x) { bool = false; } return bool; } public static double getDistance(Point p1, Point p2) { double d = 0; return d = Math.sqrt((p1.x - p2.y) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)); } } <file_sep>/ba.bitcamp.week07/src/ba/bitcamp/week7/day1/vjezbe/Task5.java package ba.bitcamp.week7.day1.vjezbe; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JPanel; /** * Class that describes a frame that contains * a single panel on it. The panel draws * two diagonal lines if the mouse is hovering * over the panel. * @author Zaid * */ public class Task5 extends JFrame { private static final long serialVersionUID = 2582034378739982019L; private MyPanel panel; private boolean toDraw = false; /** * Constructs a frame with a panel on it that has * a mouse listener attached to it. */ public Task5() { panel = new MyPanel(); panel.addMouseListener(new Mouse()); add(panel); setTitle("Task 5"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 300); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new Task5(); } /** * <p>Class that represents a custom <code>JPanel</code>. * The unique thing about it is the fact that it * only draws two diagonal lines when the <code>toDraw</code> * variable is <code>true</code> * <p><b>Note</b>: This could have put in an anonymous class, * but I opted to do it this way. * @author Zaid * */ private class MyPanel extends JPanel { private static final long serialVersionUID = 7313237643102486156L; @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (toDraw) { g.drawLine(0, 0, getWidth(), getHeight()); g.drawLine(0, getHeight(), getWidth(), 0); } } } private class Mouse implements MouseListener { @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { toDraw = true; panel.repaint(); } @Override public void mouseExited(MouseEvent e) { toDraw = false; panel.repaint(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } } }<file_sep>/ba.bitcamp.week12/src/ba/bitcamp/week12/day3/vjezbe/Task1ProducerConsumer.java package ba.bitcamp.week12.day3.vjezbe; import java.util.ArrayList; import java.util.concurrent.LinkedBlockingQueue; public class Task1ProducerConsumer { static LinkedBlockingQueue<Task> tasks; static ArrayList<Worker> workers; static Object o = new Object(); static int counter = 0; public static void main(String[] args) { tasks = new LinkedBlockingQueue<Task>(); for(int i = 0; i < 10; i++){ tasks.add(new Task()); } workers = new ArrayList<>(); for (int j = 0; j < 10; j++) { Worker w = new Worker(); w.start(); workers.add(w); } } static class Worker extends Thread{ @Override public void run() { while(!tasks.isEmpty()){ try { Runnable r = tasks.take(); r.run(); } catch (InterruptedException e) { e.printStackTrace(); } } } } static class Task implements Runnable{ long start = System.currentTimeMillis(); @Override public void run() { for (int i = 10; i < 1000000; i++) { if (isPrime(i)) { synchronized (o) { counter++; } } } System.out.println(System.currentTimeMillis() - start); System.out.println(counter); } } public static boolean isPrime(int number) { for (int i = 2; i < number / 2; i++) { if (number % i == 0) { return false; } } return true; } } <file_sep>/ba.bitcamp.week10/src/ba/bitcamp/week10/day4/vjezbe/Museum.java package ba.bitcamp.week10.day4.vjezbe; import java.util.ArrayList; /** * Class Museum represent one museum. It has two ArrayList, list of Artifacts * and list of Employees * * @author adnan.lapendic * */ public class Museum{ protected ArrayList<Artifact> museumArtifacts; protected ArrayList<MuseumEmployee> employees; public Museum(ArrayList<Artifact> museumArtifacts, ArrayList<MuseumEmployee> employees) { this.museumArtifacts = museumArtifacts; this.employees = employees; } } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day3/InvertArrayList.java package ba.bitcamp.week8.day3; import java.util.ArrayList; import java.util.Random; public class InvertArrayList { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); long start = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { Random rand = new Random(); list.add(rand.nextInt(30)); } System.out.println(list); ArrayList<Integer> temp = new ArrayList<Integer>(); for (int i = list.size() - 1; i >= 0; i--) { temp.add(list.get(i)); } System.out.println(temp); System.out.println(System.currentTimeMillis() - start); } } <file_sep>/ba.bitcamp.week05/src/ba/bitcamp/week5/day2/Main.java package ba.bitcamp.week5.day2; public class Main { public static void main(String[] args) { // System.out.println("User count :" + User.userCount); // User u1 = new User("Bruce", "Dickinson"); // System.out.println("User count :" + User.userCount); // User u2 = new User("Steve", "Harris"); // System.out.println("User count :" + User.userCount); // // System.out.println(u2); Point p1 = new Point(5, 4); Point p2 = new Point(3, 7); Point.getDistance(p1,p2); } } <file_sep>/ba.bitcamp.week05/src/ba/bitcamp/week5/day4/practice/tasks2/MarineAnimal.java package ba.bitcamp.week5.day4.practice.tasks2; public class MarineAnimal extends Animal { private boolean isItMammal; private boolean hasGills; } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day1/Task3.java package ba.bitcamp.week8.day1; public class Task3 { public static boolean isItSubstring(String s1, String s2) { int a = 0; for (int i = 0; i < s1.length(); i++) { switch (s1.charAt(i)) { case 'a': a = i; break; case 'e': a = i; break; case 'i': a = i; break; case 'o': a = i; break; case 'u': a = i; break; } @SuppressWarnings("unused") String s = s1.substring(a, s1.length())+s1.substring(0,a); } return false; } static void main(String[] args) { } } <file_sep>/ba.bitcamp.week10/src/ba/bitcamp/week10/day1/vjezbe/MyStack.java package ba.bitcamp.week10.day1.vjezbe; import java.util.Collection; public class MyStack<T> { private Node start; public Node getLast() { Node temp = start; while (temp.getNext() != null) { temp = temp.getNext(); } return temp; } public Node getPrevious(Node n) { Node temp = start; while (temp.getNext() != n) { temp = temp.getNext(); } return temp; } public T push(T element) { Node newNode = new Node(element); newNode.setNext(start); start = newNode; return element; } public T peek() { return start.getValue(); } public T pop() { T value = start.getValue(); start = start.getNext(); return value; } public void addAll(Collection<T>coll){ } public String toString() { if (start == null) { return "Stack is empty"; } else { return start.toString(); } } class Node { private Node next; private T value; public Node(T value) { next = null; this.value = value; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public T getValue() { return value; } public void setValue(T value) { this.value = value; } public String toString() { if (next == null) { return String.valueOf(value); } else { return value.toString() + " " + next.toString(); } } } public static void main(String[] args) { MyStack<Integer> stack = new MyStack<>(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); System.out.println(stack); stack.pop(); System.out.println(stack); } } <file_sep>/ba.bitcamp.week06/src/ba/bitcamp/week6/day1/Main.java package ba.bitcamp.week6.day1; public class Main { public static void main(String[] args) { Foo[] array = new Foo[5]; for (int i = 0; i < array.length; i++) { array[i] = new Foo(i + 1); } OuterClass oc = new OuterClass(); oc.ic.PrintVariables(0); Bar[] barArray = new Bar[3]; barArray[0] = new Bar("A"); barArray[1] = new Bar("AB"); barArray[2] = new Bar("ABC"); System.out.println(getMax(array)); System.out.println(getMax(barArray)); } public static Compare getMax(Compare[] array) { Compare max = array[0]; for (int i = 0; i < array.length; i++) { if (max.compere(array[i]) == -1) { max = array[i]; } } return max; } public static Bar getMax(Bar[] array) { Bar max = array[0]; for (int i = 0; i < array.length; i++) { if (max.compare(array[i]) == -1) { max = array[i]; } } return max; } } <file_sep>/ba.bitcamp.week13/src/ba/bitcamp/snake/mladen/Client.java package ba.bitcamp.snake.mladen; import java.net.Socket; public class Client { private Socket socket; private Snake snake; public Client(Socket socket, Snake snake) { super(); this.socket = socket; this.snake = snake; } public Socket getSocket() { return socket; } public void setSocket(Socket socket) { this.socket = socket; } public Snake getSnake() { return snake; } public void setSnake(Snake snake) { this.snake = snake; } }<file_sep>/W12D05/src/predavanja/SiteRead.java package predavanja; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class SiteRead { public static void main(String[] args) throws IOException { try { URL url = new URL("http://klix.ba"); URLConnection c = url.openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream())); while (br.ready()){ System.out.println(br.readLine()); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day1/vjezbe/Reodering.java package ba.bitcamp.week8.day1.vjezbe; import java.util.Arrays; public class Reodering { static int counter = 1; static int counter2 = 0; public static void main(String[] args) { int [] array ={1,2,3,1,2,3,4,5,6,1,2,5,4}; System.out.println(doReodering(array)); } public static int[] doReodering(int... array) { int array2[] = new int[array.length]; int array3[] = new int[array.length]; for (int i : array) { counter++; if (counter % 2 == 0 && counter!=0) { array2[counter2] = i; }else if(counter % 2!=0 && counter!=0){ array3[counter2]=i; counter2++; } } int counter3=0; int counter4=0; for(int i:array2){ counter3++; if(i==0){ array2[counter3]=array3[counter4]; counter4++; } } System.out.println(Arrays.toString(array2)); System.out.println(Arrays.toString(array3)); return array; } } <file_sep>/ba.bitcamp.week11/src/ba/bitcamp/week11/day1/EchoClient.java package ba.bitcamp.week11.day1; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; public class EchoClient { private static final String HOST = "localhost"; private static final int PORT = EchoServer.ECHO_PORT; public static void main(String[] args) throws UnknownHostException, IOException { System.out.println("Connecting to " + HOST +":" + PORT); Socket client = new Socket(HOST,PORT); System.out.println("Connection established, sending request..."); OutputStream rqStream = client.getOutputStream(); OutputStreamWriter rqWriter = new OutputStreamWriter(rqStream); rqWriter.write("Hello server\n"); rqWriter.flush(); System.out.println("Request sent, waiting for response..."); InputStream is =client.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); System.out.println(br.readLine()); client.close(); } } <file_sep>/ba.bitcamp.week07/src/ba/bitcamp/week7/day45/snake/Snake.java package ba.bitcamp.week7.day45.snake; import java.awt.Color; import java.awt.Desktop; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.Timer; public class Snake extends JFrame { private MyPanel panel = new MyPanel(); private static int x = 300; private static int y = 300; private int deltaX = 1; private int deltaY = 0; private static int foodX = 200; private static int foodY = 200; private static int size = 10; private int score = 0; private JLabel label = new JLabel(); private JLabel label2 = new JLabel(); private int counter = 0; private JLabel gitHub = new JLabel("GitHub"); private static ArrayList<Rectangle> snake; private static Rectangle head = new Rectangle(x, y, size, size);; private static Rectangle f = new Rectangle(foodX, foodY, 10, 10); private static final long serialVersionUID = -6912466392784209001L; // Rectangle s = new Rectangle(x, y, 50, 50); // Rectangle f = new Rectangle(foodX, foodY, 100, 100); Timer time = new Timer(10, new Action()); //Timer foodTime = new Timer(10000, new Action2()); Timer scoreTime = new Timer(1000, new Action3()); public Snake() { panel.add(label); panel.add(label2); label.setLocation(290, 50); label2.setLocation(350, 50); label2.setForeground(Color.BLUE); label.setForeground(Color.RED); time.start(); //foodTime.start(); scoreTime.start(); add(panel); setTitle("Fat Snake"); addKeyListener(new Key()); setSize(600, 600); panel.setBounds(10, 10, getWidth() - 20, getHeight() - 20); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 5)); panel.setBackground(Color.GREEN); foodX = (int) (Math.random() * 600); foodY = (int) (Math.random() * 600); label.setText("Score=" + score); panel.add(gitHub); gitHub.setForeground(Color.BLACK); gitHub.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(e.getSource().equals(gitHub)){ try { Desktop.getDesktop().browse(new URI("https://github.com/AdnanLapendic/FatSnake")); } catch (IOException e1) { e1.printStackTrace(); } catch (URISyntaxException e1) { e1.printStackTrace(); } } super.mouseClicked(e); } }); setVisible(true); } private class MyPanel extends JPanel { private static final long serialVersionUID = -8328349862308317225L; @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.RED); g.fillRect((int) head.getX() + deltaX, (int) head.getY() + deltaY, size, size); g.setColor(Color.YELLOW); g.fillOval((int) head.getX()+1 + deltaX, (int) head.getY()+1 + deltaY, size-3, size-3); snake.add(head); g.setColor(Color.RED); g.fillRect((int) f.getX(), (int) f.getY(), 10, 10); Rectangle s2 = new Rectangle(head.x + 5, head.y + 5, size, size); if (head.intersects(f)) { size+=1;//increase size if food collected snake.add(s2); repaint(); } } } private class Action implements ActionListener { @Override public void actionPerformed(ActionEvent e) { head.x += deltaX; head.y += deltaY; if (f.intersects(head)) { score += 10; label.setText("Score=" + score); foodX = (int) (Math.random() * 600); foodY = (int) (Math.random() * 600); f = new Rectangle(foodX, foodY); repaint(); } if (x == 0 || y == 0 || x + size == getWidth() || y + size == getHeight()) { scoreTime.stop(); JOptionPane.showMessageDialog(panel, "Game Over"); System.exit(0); } repaint(); } } // private class Action2 implements ActionListener { // // @Override // public void actionPerformed(ActionEvent e) { // size-=1;//decrease size every 15 seconds // if (s.intersects(f)) { // foodTime.start(); // } // foodX = (int) (Math.random() * 600); // foodY = (int) (Math.random() * 600); // // repaint(); // // } // // } private class Action3 implements ActionListener { @Override public void actionPerformed(ActionEvent e) { counter++; label2.setText("Time: " + counter); repaint(); } } private class Key implements KeyListener { @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_RIGHT) { deltaX = 1; deltaY = 0; } else if (e.getKeyCode() == KeyEvent.VK_LEFT) { deltaX = -1; deltaY = 0; } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { deltaX = 0; deltaY = 1; } else if (e.getKeyCode() == KeyEvent.VK_UP) { deltaX = 0; deltaY = -1; } repaint(); } @Override public void keyReleased(KeyEvent e) { } } public static void main(String[] args) { snake = new ArrayList<>(); new Snake(); } }<file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day1/vjezbe/MiniTextEditor.java package ba.bitcamp.week8.day1.vjezbe; import java.awt.BorderLayout; import java.awt.Dialog.ModalityType; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; public class MiniTextEditor extends JFrame { private static final long serialVersionUID = -4886116952533465025L; private JMenu file = new JMenu("File"); private JMenu edit = new JMenu("Edit"); private JMenu insert = new JMenu("Insert"); private JMenuBar menuBar = new JMenuBar(); private JMenuItem exit = new JMenuItem("Exit"); private JMenuItem insertText = new JMenuItem("Insert Text"); private JTextArea textArea = new JTextArea(); private JDialog dialog = new JDialog(); private JButton button = new JButton("Insert Text"); private JTextField index = new JTextField(5); private JLabel label = new JLabel("Insert index"); private JTextArea dialogTextArea = new JTextArea(); private JPanel panel = new JPanel(); private String text = ""; public MiniTextEditor() { setJMenuBar(menuBar); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); menuBar.add(file); exit.addActionListener(new Action()); insertText.addActionListener(new Action()); menuBar.add(edit); menuBar.add(insert); file.add(exit); insert.add(insertText); add(textArea); textArea.setEditable(true); setVisible(true); } private class Action implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == exit) { System.exit(0); } else if (e.getSource() == insertText) { dialog = new JDialog(); setLayout(new BorderLayout()); dialog.setSize(300, 400); dialog.setLocationRelativeTo(null); dialog.setModalityType(ModalityType.APPLICATION_MODAL); dialog.add(panel, BorderLayout.NORTH); dialog.add(dialogTextArea, BorderLayout.CENTER); dialogTextArea.setEnabled(true); panel.setLayout(new GridLayout(1, 2)); panel.add(label); panel.add(index); dialog.add(button, BorderLayout.SOUTH); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { text = dialogTextArea.getText(); int split = Integer.valueOf(index.getText()); String first = textArea.getText().substring(0, split); String second = textArea.getText().substring(split); StringBuilder sb = new StringBuilder(); sb.append(first); sb.append(text); sb.append(second); textArea.setText(sb.toString()); } } }); dialog.setVisible(true); } } } public static void main(String[] args) { new MiniTextEditor(); } } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day4/Task2BinarrySearch.java package ba.bitcamp.week8.day4; import java.util.Arrays; import java.util.Random; public class Task2BinarrySearch { public static void main(String[] args) { Random rnd = new Random(); int arraySize = 1000; int[] arr = new int[arraySize]; for (int i = 0; i < arraySize; i++) { arr[i] = rnd.nextInt(3 * arraySize); } System.out.println(Arrays.toString(arr)); System.out.println(Arrays.binarySearch(arr, 17)); System.out.println("************************************"); Arrays.sort(arr); System.out.println(); System.out.println(Arrays.toString(arr)); System.out.println(arraySearch(arr, 17)); } public static int arraySearch(int[] arr, int num) { int min = 0; int max = arr.length - 1; while (min<=max) { int mid = (min + max) / 2; if (arr[mid] == num) { return mid; } else if (arr[mid] > num) { max = mid - 1; } else { min = mid + 1; } } return -1; } } <file_sep>/ba.bitcamp.week12/src/ba/bitcamp/week12/day3/vjezbe/Task3.java package ba.bitcamp.week12.day3.vjezbe; import java.io.File; import java.util.ArrayList; import java.util.concurrent.LinkedBlockingQueue; public class Task3 { static int dirCounter = 0; static int fileCounter = 0; static LinkedBlockingQueue<Task> queue; static ArrayList<Worker> workers; static Object o = new Object(); public static void main(String[] args) { long start = System.currentTimeMillis(); queue = new LinkedBlockingQueue<>(); workers = new ArrayList<>(); File f = new File("/"); Task t = new Task(f); queue.add(t); for (int i = 0; i < 20; i++) { Worker w = new Worker(); w.start(); workers.add(w); } for (Worker w : workers) { try { w.join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(System.currentTimeMillis() - start); System.out.println("Files: " + fileCounter); System.out.println("Directories: " + dirCounter); } static class Task implements Runnable { private File root; public Task(File root) { this.root = root; } @Override public void run() { synchronized (o) { try { for (File f : root.listFiles()) { if (f.isFile()) { fileCounter++; } else if (f.isDirectory()) { dirCounter++; queue.add(new Task(f)); } } } catch (NullPointerException e) { } } } } static class Worker extends Thread { @Override public void run() { while (!queue.isEmpty()) { try { Task t = queue.take(); t.run(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } <file_sep>/ba.bitcamp.week11/src/ba/bitcamp/week11/day1/vjezbe/URLExamples.java package ba.bitcamp.week11.day1.vjezbe; import java.awt.image.BufferedImage; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; public class URLExamples { public static void main(String[] args) { URL url1 = null; try { url1 = new URL( "http://i.testfreaks.co.uk/images/products/600x400/92/fender-marcus-miller-jazz-bass-v-5-string.21196124.jpg"); } catch (MalformedURLException e) { System.out.println("URL problem!"); e.printStackTrace(); System.exit(1); } ImageIcon imageIcon = new ImageIcon(url1); JFrame frame = new JFrame(); frame.setSize(600, 300); frame.add(new JLabel(imageIcon)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); // Another example @SuppressWarnings("unused") BufferedImage image = null; try { image = ImageIO.read(url1); } catch (IOException e) { e.printStackTrace(); } URLConnection con = null; try { con = url1.openConnection(); System.out.println(con.getContent()); InputStream input = con.getInputStream(); File file = new File("output.jpg"); FileOutputStream fileWrite = new FileOutputStream(file); byte[] data = new byte[1024]; int bytesRead; // Radi dok ima sta citati while ((bytesRead = input.read(data, 0, data.length)) > 0) { fileWrite.write(data, 0, bytesRead); } fileWrite.close(); // ili fileWrite.flush(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/ba.bitcamp.week07/src/ba/bitcamp/week7/day1/vjezbe/Task4.java package ba.bitcamp.week7.day1.vjezbe; import java.awt.Color; import java.awt.Font; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JLabel; public class Task4 extends JFrame { private static final long serialVersionUID = -7414182425602279277L; private JLabel label = new JLabel("BIT Camp"); private Font font1 = new Font("Monospaced", Font.PLAIN, 30); private Font font2 = new Font("Monospaced", Font.BOLD, 30); public Task4() { add(label); label.setFont(font1); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(300, 200); label.setHorizontalAlignment(JLabel.CENTER); label.addMouseListener(new Mouse()); setVisible(true); } private class Mouse implements MouseListener { @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { if(e.getSource()==label){ label.setFont(font2); } } @Override public void mouseReleased(MouseEvent e) { if(e.getSource()==label){ label.setFont(font1); } } @Override public void mouseEntered(MouseEvent e) { if(e.getSource()==label){ label.setForeground(Color.GRAY); } } @Override public void mouseExited(MouseEvent e) { if(e.getSource()==label){ label.setForeground(Color.BLACK); } } } public static void main(String[] args) { new Task4(); } } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day3/vjezbe/Task6ArrayOfFonts.java package ba.bitcamp.week8.day3.vjezbe; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JLabel; public class Task6ArrayOfFonts extends JFrame { private static final long serialVersionUID = 2608488847954347449L; private int[] fonts = new int[40]; private JLabel label = new JLabel(); public Task6ArrayOfFonts() { setLayout(new GridLayout(7,7)); setSize(100, 100); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); label.setForeground(Color.RED); for (int i = 0; i < fonts.length; i++) { fonts[i] = i; add(label= new JLabel("Iron Maiden")); label.setFont(new Font("SerifSans", Font.BOLD, fonts[i])); } setVisible(true); } public static void main(String[] args) { new Task6ArrayOfFonts(); } } <file_sep>/ba.bitcamp.week07/src/ba/bitcamp/week7/day3/vjezbe/Task7CircleDrawer.java package ba.bitcamp.week7.day3.vjezbe; import java.awt.BorderLayout; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class Task7CircleDrawer extends JFrame { private static final long serialVersionUID = 1769690653577998087L; private MyPanel panel = new MyPanel(); private JSlider slider = new JSlider(0,500); private int x; private int y; private int size; public Task7CircleDrawer() { setLayout(new BorderLayout()); add(panel, BorderLayout.CENTER); add(slider, BorderLayout.SOUTH); panel.addMouseListener(new Mouse()); slider.addChangeListener(new Change()); setSize(400, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } private class MyPanel extends JPanel { private static final long serialVersionUID = -5939467972888991633L; @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawOval(x, y, size, size); repaint(); } } private class Change implements ChangeListener{ @Override public void stateChanged(ChangeEvent e) { if(e.getSource()==slider){ size=slider.getValue(); } } } private class Mouse implements MouseListener{ @Override public void mouseClicked(MouseEvent e) { x=e.getX(); y=e.getY(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } } public static void main(String[] args) { new Task7CircleDrawer(); } } <file_sep>/ba.bitcamp.week07/src/ba/bitcamp/week7/day4/ColorPicker2.java package ba.bitcamp.week7.day4; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; public class ColorPicker2 extends JFrame { private static final long serialVersionUID = -1936297588711757175L; private JPanel left = new JPanel(); private JPanel center = new JPanel(); private JPanel right = new JPanel(); private JButton[] leftButtons = new JButton[20]; private JSlider redSlider = new JSlider(); private JSlider greenSlider = new JSlider(); private JSlider blueSlider = new JSlider(); private Color activeColor = Color.GREEN; public ColorPicker2() { setLayout(new GridLayout(1, 3)); setSize(600, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(left); left.setSize(200, 400); left.setBackground(Color.RED); add(center); center.setSize(200, 400); center.setBackground(activeColor); add(right); right.setSize(200, 400); right.setBackground(Color.YELLOW); left.setLayout(new GridLayout(5, 4)); // adding colors to left panel addColors(); addSlider(); setVisible(true); } public void addColors() { for (int i = 0; i < leftButtons.length; i++) { leftButtons[i] = new JButton(); left.add(leftButtons[i]); leftButtons[i].setOpaque(true); leftButtons[i].setBorderPainted(false); leftButtons[i].setBackground(new Color((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255))); // adding listener to left color panel leftButtons[i].addMouseListener(new MouseAction()); } } private class MouseAction implements MouseListener { @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { activeColor = (Color) e.getSource(); center.setBackground(activeColor); } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } } public void addSlider() { right.add(new JLabel("Red")); right.add(redSlider); redSlider.setOrientation(JSlider.VERTICAL); right.add(new JLabel("Green")); right.add(greenSlider); greenSlider.setOrientation(JSlider.VERTICAL); right.add(new JLabel("Blue")); right.add(blueSlider); blueSlider.setOrientation(JSlider.VERTICAL); } public static void main(String[] args) { new ColorPicker2(); } } <file_sep>/ba.bitcamp.week10/src/ba/bitcamp/week10/day2/vjezbe/Task1PrintWriter.java package ba.bitcamp.week10.day2.vjezbe; import java.io.*; public class Task1PrintWriter { public static void main(String[] args) { PrintWriter pw = null; int i = 0; try { pw = new PrintWriter(new File("text.txt")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } while (i < 100) { pw.print(i); pw.println(); if (i % 2 == 0) { pw.print("String"); pw.println(); } i++; } pw.close(); System.out.println("Done"); } } <file_sep>/ba.bitcamp.week09/src/ba/bitcamp/week9/day4/vjezbe/Task1.java package ba.bitcamp.week9.day4.vjezbe; import java.util.LinkedList; import java.util.ListIterator; import java.util.Random; public class Task1 { public static void main(String[] args) { LinkedList<Integer> list1 = new LinkedList<>(); Random rand = new Random(); while(list1.size() != 20){ int randomNumber = rand.nextInt(100); if(randomNumber>=50){ list1.add(randomNumber); } } System.out.println(list1); ListIterator<Integer> it = list1.listIterator(); LinkedList<Integer> list2 = new LinkedList<>(); while(it.hasNext()){ list2.add(it.next()); } System.out.println(list2); while(it.hasPrevious()){ list2.add(it.previous()); } System.out.println(list2); } } <file_sep>/ba.bitcamp.week09/src/ba/bitcamp/week9/day3/vjezbe/Planet.java package ba.bitcamp.week9.day3.vjezbe; import java.util.ArrayList; import java.util.Comparator; public class Planet implements Comparable<Planet> { private String name; private int diameter; private double weigth; private int distance; public final static long EARTH = (597219 * 10 ^ 20); public final static int AU = 149597871; public Planet(String name, int diametar, double weigth, int distance) { this.name = name; this.diameter = diametar; this.weigth = weigth / EARTH; this.distance = distance / AU; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getDiameter() { return diameter; } public void setDiameter(int diameter) { this.diameter = diameter; } public double getWeigth() { return weigth; } public void setWeigth(double weigth) { this.weigth = weigth; } public int getDistance() { return distance; } public void setDistance(int distance) { this.distance = distance; } @Override public int compareTo(Planet o) { return this.name.compareTo(o.name); } public static void sortByDiameter(ArrayList<Planet> list) { list.sort(new Comparator<Planet>() { @Override public int compare(Planet o1, Planet o2) { return o1.diameter - o2.diameter; } }); } public static void sortByWeigth(ArrayList<Planet> list) { list.sort(new Comparator<Planet>() { @Override public int compare(Planet o1, Planet o2) { return (int) (o1.weigth - o2.weigth); } }); } public static void sortByDistance(ArrayList<Planet> list) { list.sort(new Comparator<Planet>() { @Override public int compare(Planet o1, Planet o2) { return o1.distance - o2.distance; } }); } @Override public String toString() { return "" + getName() + " {" + getDiameter() + " km}" + " {" + getWeigth() + " E}" + " {" + getDistance() + " AU}\n"; } public static void main(String[] args) { ArrayList<Planet> planets = new ArrayList<>(); Planet p1 = new Planet("Saturn", 158000, 2 * EARTH, 3 * AU); Planet p2 = new Planet("Jupiter", 14000, 0.2 * EARTH, 7 * AU); Planet p3 = new Planet("Pluton", 55000, 5 * EARTH, 6 * AU); Planet p4 = new Planet("Earth", 15800, 1 * EARTH, 1 * AU); planets.add(p1); planets.add(p2); planets.add(p3); planets.add(p4); System.out.println(planets); System.out.println("=============================="); System.out.println("Sort by name"); planets.sort(null); System.out.println(planets); System.out.println("=============================="); System.out.println("Sotr by diameter"); sortByDiameter(planets); System.out.println(planets); System.out.println("=============================="); System.out.println("Sort by weigth"); sortByWeigth(planets); System.out.println(planets); System.out.println("=============================="); System.out.println("Sort by distance"); sortByDistance(planets); System.out.println(planets); System.out.println("=============================="); } } <file_sep>/ba.bitcamp.week11/src/ba/bitcamp/week11/day2/vjezbe/RandomIPAddress.java package ba.bitcamp.week11.day2.vjezbe; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.Iterator; import java.util.Random; import java.util.Scanner; import java.util.Set; import java.util.StringTokenizer; public class RandomIPAddress { public static void main(String[] args) { HashMap<String, String> iPAddress = new HashMap<>(); try { @SuppressWarnings("resource") BufferedReader reader = new BufferedReader(new FileReader("IP.txt")); while (reader.ready()) { String line = reader.readLine(); StringTokenizer st = new StringTokenizer(line, " "); String key = st.nextToken(); String value = st.nextToken(); iPAddress.put(key, value); } } catch (IOException e) { e.printStackTrace(); } // System.out.println(iPAddress); // System.out.println(); System.out.println(getRandomIPAddress(iPAddress)); ServerSocket server = null; Socket client = null; Socket zaid = null; Scanner in = new Scanner(System.in); Socket client2 = null; String text = ""; try { server = new ServerSocket(8888); client2 = server.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader( client2.getInputStream())); //Scanner in = new Scanner(System.in); String s = in.nextLine(); text += reader.readLine() +" "+ s; System.out.println(text); zaid = new Socket("10.0.82.98", 8888); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( zaid.getOutputStream())); // Write to Zaid writer.write(text); System.out.println(text); writer.newLine(); writer.flush(); boolean bool = false; while (!bool) { try { client = new Socket(getRandomIPAddress(iPAddress), 8888); BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter( client.getOutputStream())); // Write to other writer2.write(text); writer2.newLine(); writer2.flush(); break; } catch (Exception e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } in.close(); // END } public static String getRandomIPAddress(HashMap<String, String> map) { Random rand = new Random(); String iPAddress = null; Set keys = map.keySet(); Iterator it = keys.iterator(); int randomNumber = rand.nextInt(25); for (int i = 0; i < randomNumber; i++) { it.next(); } return iPAddress = (String) it.next(); } } <file_sep>/ba.bitcamp.week09/src/ba/bitcamp/week9/day3/Student.java package ba.bitcamp.week9.day3; public class Student { private String ime; public Student(String ime){ this.ime = ime; } @Override public String toString() { return ime; } } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day3/vjezbe/Task2ShiftingAnArray.java package ba.bitcamp.week8.day3.vjezbe; import java.util.Arrays; public class Task2ShiftingAnArray { char [] chars; private static char temp; public static void main(String[] args) { char [] chars = {'A','B','C','D','E','F'}; System.out.println(Arrays.toString(chars)); shiftChars(chars); System.out.println(Arrays.toString(chars)); } private static void shiftChars(char [] chars){ for (int j = 0; j < chars.length-1; j++) { if(chars.length>j+1) temp = chars[j+1]; chars[j]=temp; } } } <file_sep>/ba.bitcamp.week10/src/ba/bitcamp/week10/day4/vjezbe/Searchable.java package ba.bitcamp.week10.day4.vjezbe; public interface Searchable { boolean fiitsSearch(String s); } <file_sep>/ba.bitcamp.week12/src/ba/bitcamp/week12/day3/Runner.java package ba.bitcamp.week12.day3; public class Runner { public static void main(String[] args) { //BlockingQueueExample.startExample(); //LacthExemple.startExemple(); //ExecutorExample.runExample(); CallableExemple.runExemple(); } } <file_sep>/ba.bitcamp.week05/src/ba/bitcamp/week5/day5/IgrajPogodiBroj.java package ba.bitcamp.week5.day5; public class IgrajPogodiBroj { public static void main(String[] args) { PogodiBroj pb = new PogodiBroj(100, 5); System.out.println(pb); pb.igraj(); } }<file_sep>/ba.bitcamp.week06/src/ba/bitcamp/week6/day6/vjezbe/Task1.java package ba.bitcamp.week6.day6.vjezbe; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; public class Task1 extends JFrame { private static final long serialVersionUID = 5454075137477694620L; private JLabel text = new JLabel("Hello World!"); private JButton button = new JButton("Hello!"); public Task1(){ text.setAlignmentX(CENTER_ALIGNMENT); setLayout(new BorderLayout()); add(text, BorderLayout.CENTER); add(button, BorderLayout.SOUTH); setVisible(true); setTitle("Hello!"); setSize(400, 300); Action listen = new Action(); button.addActionListener(listen); } public static void main(String[] args) { new Task1(); } private class Action implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==button){ JOptionPane.showMessageDialog(null, "Hello World!"); System.exit(0); } } } } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day3/vjezbe/Task4FindTheOne.java package ba.bitcamp.week8.day3.vjezbe; import java.util.Arrays; public class Task4FindTheOne { public static void main(String[] args) { System.out.println(isInString("ASDFDSAS", 'h')); } public static boolean isInString(String s, char c){ Character [] chars = new Character [s.length()]; for (int i = 0; i < s.length(); i++) { chars[i]=s.charAt(i); } Arrays.sort(chars); if(Arrays.binarySearch(chars, c)>0){ return true; }else{ return false; } } } <file_sep>/ba.bitcamp.week06/src/ba/bitcamp/week6/day1/practice/Clock.java package ba.bitcamp.week6.day1.practice; public class Clock implements WriteableClock { private String time; public Clock(String time) { this.time = time; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Clock other = (Clock) obj; if (time == null) { if (other.time != null) return false; } else if (!time.equals(other.time)) return false; return true; } @Override public String toString() { return "Clock [time=" + time + "]"; } @Override public void addToFile(String filename, int format) { } }<file_sep>/ba.bitcamp.week10/src/ba/bitcamp/week10/day3/vjezbe/Employee.java package ba.bitcamp.week10.day3.vjezbe; import java.io.BufferedReader; import java.util.StringTokenizer; public class Employee { private String name; private String surname; private String gender; private String position; private String salary; private BufferedReader br; private StringTokenizer st; public Employee(String line) { this.st = new StringTokenizer(line, ","); this.name = st.nextToken(); this.surname = st.nextToken(); this.gender = st.nextToken(); this.position = st.nextToken(); this.salary = st.nextToken(); } public String getName() { return name; } public String getSurname() { return surname; } public String getGender() { return gender; } public String getPosition() { return position; } public String getSalary() { return salary; } public BufferedReader getBr() { return br; } public StringTokenizer getSt() { return st; } public String toString(){ return "Name: " + name + " " + "Surname: " + surname +" " + "Gender: " + gender + " " + "Position: " + position + " " + "Salary: " + salary; } } <file_sep>/ba.bitcamp.week05/src/ba/bitcamp/week5/day4/practice/tasks2/LandAnimal.java package ba.bitcamp.week5.day4.practice.tasks2; public class LandAnimal extends Animal { private int numOfLegs; private boolean activeDayOrNight; } <file_sep>/ba.bitcamp.week5/src/ba/bitcamp/week5/day4/practice/tasks/Laptop.java package ba.bitcamp.week5.day4.practice.tasks; public class Laptop extends PortableComputer { private int numOfBatteryCells; private boolean hasBluetooth; private boolean hasNumericKeyboard; public Laptop(String os, int ram, int price, int weight, int displaySize, boolean hasWiFi, int numOfBatteryCells, boolean hasBluetooth, boolean hasNumericKeyboard) { super(os, ram, price, weight, displaySize, hasWiFi); this.numOfBatteryCells = numOfBatteryCells; this.hasBluetooth = hasBluetooth; this.hasNumericKeyboard = hasNumericKeyboard; } public void printInformation() { super.printInformation(); } public int getNumOfBatteryCells() { return numOfBatteryCells; } public void setNumOfBatteryCells(int numOfBatteryCells) { this.numOfBatteryCells = numOfBatteryCells; } public boolean isHasBluetooth() { return hasBluetooth; } public void setHasBluetooth(boolean hasBluetooth) { this.hasBluetooth = hasBluetooth; } public boolean isHasNumericKeyboard() { return hasNumericKeyboard; } public void setHasNumericKeyboard(boolean hasNumericKeyboard) { this.hasNumericKeyboard = hasNumericKeyboard; } public void PrintType() { System.out .println("Laptop is a lightweight portable computer, it has battery so it can be used without power suplly for a certain time. It's mostly used by business people."); } } <file_sep>/ba.bitcamp.week12/src/ba/bitcamp/week12/day2/vjezbe/Task3.java package ba.bitcamp.week12.day2.vjezbe; import java.awt.BorderLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class Task3 extends JFrame { private JPanel panel; private JLabel label; private JButton start; private Object o = new Object(); public static int counter; public static long startTime; public Task3() { setLayout(new BorderLayout()); setSize(300, 100); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); add(panel = new JPanel(), BorderLayout.CENTER); add(start = new JButton("Start"), BorderLayout.SOUTH); start.addActionListener(new Action()); panel.add(label = new JLabel("0"), BorderLayout.CENTER); label.setFont(new Font("Serif", 3, 14)); setVisible(true); } class MyThread implements Runnable { @Override public void run() { for (int i = 10; i < 1000000; i++) { if (isPrime(i)) { synchronized (o) { counter++; } } } label.setText("From 10 to 10.000.000 there are " + counter + " numbers."); System.out.println(System.currentTimeMillis() - startTime); counter = 0; } } private class Action implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == start) { startTime = System.currentTimeMillis(); label.setText("..."); Thread t = new Thread(new MyThread()); t.start(); } } } public boolean isPrime(int number) { for (int i = 2; i < number / 2; i++) { if (number % i == 0) { return false; } } return true; } public static void main(String[] args) { new Task3(); } } <file_sep>/ca.bitcamp.week5/src/ca/bitcamp/week5/day1/Main.java package ca.bitcamp.week5.day1; public class Main { public static void main(String[] args) { Suitcase s1 = new Suitcase(50); } } <file_sep>/ba.bitcamp.week05/src/ba/bitcamp/week5/day5/practice/LifeForm/Tigar.java package ba.bitcamp.week5.day5.practice.LifeForm; public class Tigar extends Animal { public Tigar(String alive, String foodType) { super(alive, foodType); // TODO Auto-generated constructor stub } public static final String RESTING = "Resting"; public static final String HUNT = "Huntig"; public static final String EATING = "Eating"; private int speed; private String state; //public Tigar(String alive) { //super(alive); // TODO Auto-generated constructor stub //} public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public static String getResting() { return RESTING; } public static String getHunt() { return HUNT; } public static String getEating() { return EATING; } public String toString() { String s = "Speed: " + speed + "\n"; // s += "Alive? " + LifeForm.getAlive() + "\n"; s += "Kg: " + getKg() + "\n"; s += "Meat or plant eater? " + getMeatEater() + "\n"; s += "Tigar is " + getHunt() + "\n"; return s; } }<file_sep>/.metadata/version.ini #Wed Aug 19 13:06:56 CEST 2015 org.eclipse.core.runtime=2 org.eclipse.platform=4.4.2.v20150204-1700 <file_sep>/ba.bitcamp.week10/src/ba/bitcamp/week10/day2/vjezbe/Task2CharArray.java package ba.bitcamp.week10.day2.vjezbe; import java.io.PrintWriter; public class Task2CharArray { public static void main(String[] args) { char [] arr = new char[25]; PrintWriter pw = new PrintWriter(System.out); for (int i = 65; i <=90; i++) { int j = 0; arr[j] = (char)i; pw.write(arr,0,10); j++; } pw.close(); } } <file_sep>/ba.bitcamp.week12/src/ba/bitcamp/week12/day2/vjezbe/Sensor.java package ba.bitcamp.week12.day2.vjezbe; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.Socket; import java.util.Scanner; public class Sensor { public static void main(String[] args) { Scanner in = new Scanner(System.in); try { Socket sensor = new Socket("10.0.82.33",8000); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(sensor.getOutputStream())); writer.write(in.nextLine()); writer.newLine(); writer.flush(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/ba.bitcamp.week14.maven/src/ba/bitcamp/w14d1/ebean/ShopApplication.java package ba.bitcamp.w14d1.ebean; import java.math.BigDecimal; import org.avaje.agentloader.AgentLoader; import ba.bitcamp.w14d1.models.Product; import ba.bitcamp.w14d1.models.Purchase; import ba.bitcamp.w14d1.models.User; import com.avaje.ebean.Ebean; import com.avaje.ebean.EbeanServer; public class ShopApplication { static { if (!AgentLoader.loadAgentFromClasspath("avaje-ebeanorm-agent", "debug=1;packages=ba.bitcamp.w14d1.models.**")); } private static EbeanServer server = Ebean.getServer("h2"); public static void main(String[] args) { User first = new User(); first.setFullName("<NAME>"); first.setEmail("<EMAIL>"); first.setBalance(new BigDecimal(0)); //Ebean.save(first); Product monitor = new Product(); monitor.setTitle("Monitor, Dell\""); monitor.setPrice(new BigDecimal("399.95")); monitor.setQuantity(0); //Ebean.save(monitor); monitor.setQuantity(10);//update //Ebean.save(monitor); /* Nova kupovina*/ Purchase firstUserPurchaseMonitor = new Purchase(); firstUserPurchaseMonitor.setUser(first); firstUserPurchaseMonitor.setProduct(monitor); first.setBalance(first.getBalance().subtract(monitor.getPrice())); monitor.setQuantity(monitor.getQuantity()-1); Ebean.save(firstUserPurchaseMonitor); System.out.println(first.getId()); System.out.println(monitor.getId()); System.out.println(firstUserPurchaseMonitor.getId()); } } <file_sep>/ba.bitcamp.week10/src/ba/bitcamp/week10/day4/vjezbe/Main.java package ba.bitcamp.week10.day4.vjezbe; import java.util.ArrayList; import ba.bitcamp.week10.day4.vjezbe.HistoricalArtifact.Era; import ba.bitcamp.week10.day4.vjezbe.WorkOfArt.Period; public class Main { public static void main(String[] args) { ArrayList<Artifact> artifacts = new ArrayList<>(); ArrayList<MuseumEmployee> employees = new ArrayList<>(); @SuppressWarnings("unused") Museum museum = new Museum(artifacts, employees); Author daVinci = new Author("Leonardo", "<NAME>", 1365, 1455); WorkOfArt art1 = new WorkOfArt(1582, "<NAME>", "Paintng", daVinci, Period.RENAISSANCE); HistoricalArtifact history1 = new HistoricalArtifact(555, "Excalibur", "Sword Of King Arthur", "England", Era.MIDDLE_AGES); artifacts.add(art1); artifacts.add(history1); artifacts.sort(null); System.out.println(artifacts); MuseumEmployee emp1 = new MuseumEmployee("Adnan", "Lapendic", 30, 800); MuseumEmployee emp2 = new MuseumEmployee("Boris", "Tomic", 29, 900); employees.add(emp1); employees.add(emp2); System.out.println(employees); employees.sort(null); System.out.println(emp1.fiitsSearch("29"));//Adnan System.out.println(art1.fiitsSearch("1582"));//<NAME> } } <file_sep>/ba.bitcamp.week13/src/ba/bitcamp/week13/snake/SnakeServer.java package ba.bitcamp.week13.snake; public class SnakeServer { private final SnakeServerThread serverThread; private Engine engine; public SnakeServer() { engine = new Engine(); serverThread = new SnakeServerThread(); serverThread.setPriority(1); serverThread.start(); } class SnakeServerThread extends Thread { public void run() { while(true) { engine.moveSnakeInNewDirection(SnakeGlobal.SNAKE_NEW_DIRECTION); try { Thread.sleep(150); } catch (InterruptedException ex) { ex.printStackTrace(); } if(SnakeGlobal.IS_GAME_OVER) { extracted(); } } } private void extracted() { stop(); } } }<file_sep>/ba.bitcamp.week13/src/ba/bitcamp/week13/snake/SnakeMain.java package ba.bitcamp.week13.snake; import java.awt.Container; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JApplet; import javax.swing.JFrame; public class SnakeMain extends JApplet implements KeyListener { private SnakeServer gameServer; private SnakePanel gamePanel; public void init() { gameServer = new SnakeServer(); try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } gamePanel = new SnakePanel(); setSize(320, 320); Container cpane = getContentPane(); cpane.add(gamePanel); addKeyListener(this); } public static void main(String[] args) { // TODO code application logic here SnakeMain snakeGame = new SnakeMain(); JFrame mainFrame = new JFrame(" Simple Snake Game "); mainFrame.setSize(320, 320); mainFrame.getContentPane().add(snakeGame); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.addKeyListener(snakeGame); snakeGame.init(); snakeGame.start(); snakeGame.setVisible(true); mainFrame.setVisible(true); } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { System.out.println("Key " + e.getKeyCode() + " Pressed!"); if(e.getKeyCode() == KeyEvent.VK_UP) { gamePanel.setDirection(1); } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { gamePanel.setDirection(2); } else if(e.getKeyCode() == KeyEvent.VK_DOWN) { gamePanel.setDirection(3); } else if(e.getKeyCode() == KeyEvent.VK_LEFT) { gamePanel.setDirection(4); } else { System.out.println("Wrong Keyboard Input!"); } } public void keyReleased(KeyEvent e) { } } <file_sep>/ba.bitcamp.week05/src/ba/bitcamp/week5/day4/practice/tasks/DesktopComputer.java package ba.bitcamp.week5.day4.practice.tasks; public class DesktopComputer extends StationaryComputer { private int freeRamSlots; private boolean isItOverclocked; private boolean hasDvd; public DesktopComputer(String os, int ram, int price, int processorSpeed, int powerSuply, int hdCapacity, int freeRamSlots, boolean isItOverclocked, boolean hasDvd) { super(os, ram, price, processorSpeed, powerSuply, hdCapacity); this.freeRamSlots = freeRamSlots; this.isItOverclocked = isItOverclocked; this.hasDvd = hasDvd; } public void printInformation() { super.printInformation(); } public int getFreeRamSlots() { return freeRamSlots; } public void setFreeRamSlots(int freeRamSlots) { this.freeRamSlots = freeRamSlots; } public boolean isItOverclocked() { return isItOverclocked; } public void setItOverclocked(boolean isItOverclocked) { this.isItOverclocked = isItOverclocked; } public boolean getHasDvd() { return hasDvd; } public void setHasDvd(boolean hasDvd) { this.hasDvd = hasDvd; } public void PrintType() { System.out .println("PC-Personal Computer is made for everyone. Best feature of this kind of computers is posibility to change and personalise components"); } } <file_sep>/ba.bitcamp.week10/src/ba/bitcamp/week10/day2/Part1.java package ba.bitcamp.week10.day2; import java.io.*; public class Part1 { public static void main(String[] args) { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream("nesto.txt"))); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } @SuppressWarnings("unused") BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); PrintWriter pw = new PrintWriter(System.out); String line = null; try { while((line = br.readLine()) != null){ pw.println(line); } pw.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //pw.close(); } } <file_sep>/ba.bitcamp.week5/src/ba/bitcamp/week5/day5/practice/LifeForm/Zebra.java package ba.bitcamp.week5.day5.practice.LifeForm; public class Zebra extends Animal { public Zebra(String alive, String foodType) { super(alive, foodType); // TODO Auto-generated constructor stub } public static final String HEALTHY = "Healthy"; public static final String SICK = "Sick"; public static final String DEADLY_SICK = "Deadly sick"; private int age; private String state; //public Zebra(String alive) { // super(alive); // // } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public static String getHealthy() { return HEALTHY; } public static String getSick() { return SICK; } public static String getDeadlySick() { return DEADLY_SICK; } @Override public String toString() { String s = "Meat or plant eater? " + Animal.getPlantEater() + " "; s += "Age: " + age + " "; s += "Zebra is " + getDeadlySick() + " "; return s; } } <file_sep>/ba.bitcamp.week5/src/ba/bitcamp/week5/day4/practice/Hospital.java package ba.bitcamp.week5.day4.practice; public class Hospital extends Building { public Integer numberOfSurgeons; public Boolean hasCT; public Integer numberOfBeds; public Boolean isItPublic; public void printInformation() { System.out.println(location); System.out.println(population); System.out.println(area); } } <file_sep>/ca.bitcamp.week5/src/ca/bitcamp/week5/day1/Wallet.java package ca.bitcamp.week5.day1; public class Wallet { } <file_sep>/W12D05/src/vjezbe/LafoServer.java package vjezbe; import java.io.BufferedWriter; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; public class LafoServer { public static String ipAdd = ""; public static ArrayList<String> list; // public static ObjectMapper map = new ObjectMapper(); public static ArrayList<Snake> snakes; public static void main(String[] args) { list = new ArrayList<String>(); Thread t = null; try { ServerSocket server = new ServerSocket(5555); BufferedWriter writer; Socket client = null; snakes = new ArrayList<Snake>(); while (true) { client = server.accept(); System.out.println("Client connected"); ClientThread ct = new ClientThread(client); snakes.add(new Snake()); t = new Thread(ct); list.add(client.getInetAddress().getHostAddress()); t.start(); } } catch (IOException e) { e.printStackTrace(); } } public static class ClientThread implements Runnable { private Socket client; public String ip; ObjectOutputStream writer = null; public ClientThread(Socket client) { this.client = client; this.ip = client.getInetAddress().getHostAddress(); } public void run() { try { writer = new ObjectOutputStream(client.getOutputStream()); // while (client.isConnected()) { synchronized (snakes) { writer.writeObject(snakes); } // } } catch (IOException e) { e.printStackTrace(); } } } } <file_sep>/ba.bitcamp.week07/src/ba/bitcamp/week7/day1/vjezbe/Task6.java package ba.bitcamp.week7.day1.vjezbe; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class Task6 extends JFrame { private static final long serialVersionUID = 2960004784751333508L; private JPanel panel = new JPanel(); private JLabel label = new JLabel(); public Task6() { add(panel); panel.add(label); label.setHorizontalAlignment(JLabel.CENTER); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(300, 200); panel.addMouseMotionListener(new Mouse()); setVisible(true); } private class Mouse implements MouseMotionListener { @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { if (e.getSource() == panel) { e.getX(); e.getY(); label.setText("x=" +e.getX() +" " +"y=" + e.getY()); } } } public static void main(String[] args) { new Task6(); } } <file_sep>/ba.bitcamp.week5/src/ba/bitcamp/week5/day3/employee/HourlyEmployee.java package ba.bitcamp.week5.day3.employee; public class HourlyEmployee extends Employee { private int hourlyRate; public HourlyEmployee(String name, String gender, int hourlyRate){ super(name,gender); this.hourlyRate=hourlyRate; } } <file_sep>/ba.bitcamp.week09/src/ba/bitcamp/week9/day2/vjezbe/StackListArray.java package ba.bitcamp.week9.day2.vjezbe; import java.util.Arrays; public class StackListArray { private static String [] array; @SuppressWarnings("static-access") public StackListArray(){ this.array=new String [0]; } public boolean isEmpty(String [] array){ return array.length==0; } public String push(String string){ String [] temp = new String [array.length+1]; temp = Arrays.copyOf(array, temp.length); temp[temp.length-1] = string; array = temp; return string; } public String pop(){ String [] temp = new String [array.length-1]; temp = Arrays.copyOf(array, temp.length); array = temp; return array[array.length-1]; } public String peek(){ return array[array.length-1]; } public String toString(){ return Arrays.toString(array); } public static void main(String[] args) { StackListArray stack = new StackListArray(); System.out.println(stack.isEmpty(array)); stack.push("String"); System.out.println(stack.isEmpty(array)); stack.push("String2"); stack.push("String3"); stack.pop(); System.out.println(stack.toString()); System.out.println(stack.peek()); } } <file_sep>/ba.bitcamp.week10/src/ba/bitcamp/week10/day3/vjezbe/Task1WarmingUp.java package ba.bitcamp.week10.day3.vjezbe; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; public class Task1WarmingUp { public static void main(String[] args) { BufferedReader br = null; try { br = new BufferedReader(new FileReader( "/Users/adnan.lapendic/Desktop/example.csv")); } catch (FileNotFoundException e) { e.printStackTrace(); } ArrayList<Employee> arr = new ArrayList<>(); try { br.readLine(); while (br.ready()) { String line = br.readLine(); Employee e = new Employee(line); arr.add(e); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } arr.sort(new Comparator<Employee>() { @Override public int compare(Employee o1, Employee o2) { return o1.getName().compareTo(o2.getName()); } });; System.out.println(arr); } } <file_sep>/ba.bitcamp.week06/src/ba/bitcamp/week6/day5/Task1.java package ba.bitcamp.week6.day5; public class Task1 { public static void main(String[] args) { int n = 290472; for (int i = 1; n >= 0;) { if (n % i == 0 && i != 1) { n = n / i; System.out.print(i + " "); } else { i++; } } } } <file_sep>/ba.bitcamp.week12/src/ba/bitcamp/week12/day2/vjezbe/Task2.java package ba.bitcamp.week12.day2.vjezbe; public class Task2 { private static int counter = 0; private static Object o = new Object(); public static void runThreads() { Thread t1 = new Thread(new MyThread()); Thread t2 = new Thread(new MyThread()); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } } static class MyThread implements Runnable { @Override public void run() { for (int i = 0; i < 100; i++) { synchronized (o) { counter += 10; } } } } public static void main(String[] args) { long start = System.currentTimeMillis(); for (int i = 0; i < 20; i++) { runThreads(); System.out.println(counter); counter = 0; } System.out.println(); System.out.println("Counter resets: " + counter); System.out.println("Time needed for this task:" + (System.currentTimeMillis() - start)); } } <file_sep>/ba.bitcamp.week06/src/ba/bitcamp/week6/day6/vjezbe/Window4.java package ba.bitcamp.week6.day6.vjezbe; import java.awt.BorderLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; public class Window4 extends JFrame { private static final long serialVersionUID = 192927056409613413L; private JLabel text = new JLabel("Don't click"); private JButton button = new JButton("Press me if you dare"); private int counter = 0; public Window4() { setLayout(new BorderLayout()); add(button, BorderLayout.SOUTH); Font font = new Font("Cambria", Font.BOLD, 18); text.setFont(font); add(text, BorderLayout.CENTER); text.setHorizontalAlignment(NORMAL); setVisible(true); setSize(300, 200); Action listen = new Action(); button.addActionListener(listen); } private class Action implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String[] s = { "I told you not to press", "You did it again", "And again", "One more click if you dare" }; if (e.getSource() == button) { text.setText(s[counter]); counter++; } if (counter==s.length){ System.exit(0); } } } public static void main(String[] args) { new Window4(); } } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day4/vjezbe/Company.java package ba.bitcamp.week8.day4.vjezbe; import java.util.ArrayList; public class Company { private ArrayList<Employee> employeeList = new ArrayList<>(); public Company() { } public void hireEmployee(Employee employer) { if (!employeeList.contains(employer)) { employeeList.add(employer); } else { System.out.println("Person allready works in company "); } } public void fireEmployee(Employee employer) { if (employeeList.contains(employer)) { employeeList.remove(employer); } else { System.out.println("Person don't work in company"); } } public boolean isWorkingHere(Employee employer) { boolean isWorking = false; for (int i = 0; i < employeeList.size(); i++) { if (employeeList.contains(employer)) { isWorking = true; } else { isWorking = false; } } return isWorking; } public boolean hasFemaleWorking() { boolean hasFemale = false; for (int i = 0; i < employeeList.size(); i++) { Employee employer = employeeList.get(i); if (employer.getGender().equals("Female")) { hasFemale = true; } else { hasFemale = false; } } return hasFemale; } public void sortByID() { for (int i = 0; i < employeeList.size(); i++) { int minIndex = 0; for (int j = 1; j < employeeList.size(); j++) { if (employeeList.get(i).getId() > employeeList.get(minIndex) .getId()) { minIndex = j; } } Employee temp = employeeList.get(i); employeeList.set(i, employeeList.get(minIndex)); employeeList.set(minIndex, temp); } } public void sortByAge() { for (int i = 0; i < employeeList.size(); i++) { int minIndex = 0; for (int j = 1; j < employeeList.size(); j++) { if (employeeList.get(i).getDate().getYear() > employeeList .get(minIndex).getDate().getYear()) { minIndex = j; } } Employee temp = employeeList.get(i); employeeList.set(i, employeeList.get(minIndex)); employeeList.set(minIndex, temp); } } public ArrayList<Employee> getEmployeeList() { return employeeList; } public void addEmployees(Employee... list) { for (int i = 0; i < list.length; i++) { employeeList.add(list[i]); } } public void addEmployees2(Employee[] employers) { for (Employee employer : employers) { employeeList.add(employer); } } public void addEmployee3(ArrayList<Employee> list) { for (Employee employer : list) { employeeList.add(employer); } } public Integer indexOf(Employee employer) { Integer index = null; for (int i = 0; i < employeeList.size(); i++) { if (employeeList.contains(employer)) { index = employeeList.indexOf(employer); return index; } else { index = null; ; } } return index; } public void removeEmployeeOnIndex(int indexOfEmployer) { if (indexOfEmployer <= employeeList.size()) { employeeList.remove(indexOfEmployer); } } public void removeEmployeeWithSelectedID(int employerID) { for (int i = 0; i < employeeList.size(); i++) { Employee employer = employeeList.get(i); if (employer.getId()==employerID) { employeeList.remove(employer); } } } /** * Sorts Employees by first name. */ public void sortByName() { for (int i = 0; i < employeeList.size(); i++) { for (int j = employeeList.size() - 1; j > 0; j--) { if (employeeList.get(j - 1).getFirstName().compareToIgnoreCase(employeeList.get(j).getFirstName()) > 0) { Employee temp = employeeList.get(j); employeeList.set(j, employeeList.get(j - 1)); employeeList.set(j - 1, temp); } } } } public Employee [] getEmployeeArray(){ Employee [] employers = new Employee[employeeList.size()]; for (int i = 0; i < employers.length; i++) { employers [i] = employeeList.get(i); } return employers; } public ArrayList<String> getNameList(){ ArrayList<String> names = new ArrayList<>(); for (int i = 0; i < employeeList.size(); i++) { String name = employeeList.get(i).getFirstName(); names.add(name); } return names; } @Override public String toString() { return "Company employers" + employeeList; } } <file_sep>/ba.bitcamp.week10/src/ba/bitcamp/week10/day1/vjezbe/MyArrayList.java package ba.bitcamp.week10.day1.vjezbe; public class MyArrayList<T> { private Node start; /** * * @param element * @return */ public boolean add(T element) { Node temp = new Node(element); if (start == null) { start = temp; } else { while (temp.getNext() != null) { temp = temp.getNext(); } getLast().setNext(temp); } return true; } /** * * @param index * @param element */ public void add(int index, T element) { int counter = 0; Node temp = start; Node newNode = new Node(element); while (temp.getNext() != null) { counter++; if (counter == index) { newNode.setNext(temp.getNext()); temp.setNext(newNode); } temp = temp.getNext(); } } /** * * @param element * @return */ public int indexOf(T element) { Node temp = start; int count = 0; while (temp.getNext() != null) { if(temp.getValue().equals(element)){ return count; } count++; temp = temp.getNext(); } return -1; } /** * * @param index * @return */ public T elementAtIndex(int index) { Node temp = start; int count = 0; while (temp.getNext() != null) { if (count == index) { return temp.getValue(); } count++; temp = temp.getNext(); } return temp.getValue(); } /** * * @param element * @return */ public boolean contains(T element) { Node temp = start; while (temp.getNext() != null) { if (temp.getValue().equals(element)){ return true; } temp = temp.getNext(); } return false; } /** * * @param element * @return */ private int lastIndexOf(T element) { Node temp = start; while(temp.getNext() != null){ if(temp.getValue().equals(element)){ return indexOf(element); } temp = temp.getNext(); } return -1; } public Node getLast(){ Node temp = start; while(temp.getNext() != null){ temp = temp.getNext(); } return temp; } public String toString(){ if(start == null){ return "List is empty"; }else{ return start.toString(); } } class Node { private Node next; private T value; public Node(T value) { next = null; this.value = value; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public T getValue() { return value; } public void setValue(T value) { this.value = value; } public String toString(){ if(next == null){ return String.valueOf(value); }else{ return value.toString() +" " + next.toString(); } } } public static void main(String[] args) { MyArrayList<Integer> myList = new MyArrayList<>(); myList.add(5); myList.add(4); myList.add(3); myList.add(2); myList.add(1); myList.add(0); myList.add(3, 9); System.out.println(myList.indexOf(3)); System.out.println(myList.elementAtIndex(2)); System.out.println(myList); System.out.println(myList.contains(5)); System.out.println(myList.lastIndexOf(1)); } } <file_sep>/ba.bitcamp.week13/src/ba/bitcamp/snake/mladen/Person.java package ba.bitcamp.snake.mladen; public class Person extends Model { static String tableName = "Table"; public static void main(String[] args) { Person p = new Person(); System.out.println(p.findByAttribute("Adnan", "BitCamp")); System.out.println(p.findByPk(5)); } } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day3/vjezbe/Task3PartiallyFilled.java package ba.bitcamp.week8.day3.vjezbe; public class Task3PartiallyFilled { private static int j = 1; private static String[] full; public static void main(String[] args) { System.out.println(deleteNull("ad", null, "asda", null, "sdsds", null, "aaa")); } public static String[] deleteNull(String... s) { full=new String [j]; for (int i = 0; i < s.length; i++) { String s3 = null; if(!s[i].equals(s3)){ full[j]=s[i]; j++; } } return full; } } <file_sep>/ba.bitcamp.week12/src/ba/bitcamp/week12/day2/vjezbe/LoggerServer.java package ba.bitcamp.week12.day2.vjezbe; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class LoggerServer { static class MyThread implements Runnable { private Socket client; public MyThread(Socket client) { this.client = client; } @Override public void run() { BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader( client.getInputStream())); String data = ""; data = reader.readLine(); String [] s = data.split(" "); BufferedWriter writer = new BufferedWriter( new FileWriter( new File( "/Users/adnan.lapendic/Documents/workspace/ba.bitcamp.week12/src/ba/bitcamp/week12/day2/vjezbe/text.txt"),true)); int a = Integer.parseInt(s[0]); if(s[0].equals("2")) { writer.write("[Pressure] " + s[1] + " hPa"); writer.newLine(); writer.flush(); }else if(s[0].equals("3")){ writer.write("[Movement] " + s[1]); writer.newLine(); writer.flush(); }else if(s[0].equals("1")){ writer.write("[Temperature] " + s[1] + " K"); writer.newLine(); writer.flush(); }else if(s[0].equals("4")){ writer.write("[Error] " + data); writer.newLine(); writer.flush(); }else{ writer.write("[COMM. ERROR] N is not a valid communication identification number!"); writer.newLine(); writer.flush(); } } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { ServerSocket server; try { server = new ServerSocket(8000); Socket client = server.accept(); Thread t = new Thread(new MyThread(client)); t.start(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day3/vjezbe/Task1IntegerToDay.java package ba.bitcamp.week8.day3.vjezbe; public class Task1IntegerToDay { private static String[] days = { "Monday", "Thusday", "Wensday", "Thursday", "Friday", "Saturday", "Sunday" }; private static String s; public static void main(String[] args) { System.out.println(getDay(7)); } public static String getDay (int day){ try{ s = days[day-1].toString(); } catch (IndexOutOfBoundsException e){ System.out.println("Day must be number from 1 to 7"); } return s; } } <file_sep>/ba.bitcamp.week05/src/ba/bitcamp/week5/day3/Card.java package ba.bitcamp.week5.day3; /** * this class represents a Card from a standard deck the values goes from 1 -13 * 11 - Jack 12 - Queen 13 - King Suits go from 0-4 0- Heart 1 - Spades 2 - * Diamond 3 - Club 4 - Joker * * @author adnan.lapendic * */ public class Card { private static final int MIN_VALUE = 1; private static final int MAX_VALUE = 13; private static final int MIN_SUIT = 0; private static final int MAX_SUIT = 4; public static final int HEART = 0; public static final int DIAMOND =1; public static final int CLUBS = 2; public static final int SPADE =3; public static final int JOKER =4; public static final int ACE =1; public static final int JACK = 11; public static final int QUEEN =12; public static final int KING = 13; private int value; private int suit; private boolean isJoker = false; public Card() { this.suit = JOKER; this.value = 0; isJoker = true; } public Card(int value, int suit) { if (suit < MIN_SUIT || MAX_SUIT > 4) { throw new IllegalArgumentException("Suit has be in range 0 to 4"); } if (suit < MIN_VALUE || MAX_VALUE > 13) { throw new IllegalArgumentException("Value mus be in range 1 to 13"); } this.value = value; this.suit = suit; isJoker = true; } public int getValue() { return value; } public int getSuit() { return suit; } public void setValue(int value) { if (isJoker == false) { throw new UnsupportedOperationException( "Can't change the value of Joker"); } if (value < 0 || value > 13) { throw new IllegalArgumentException("Value mus be in range 1 to 13"); } this.value = value; } public void setSuit(int suit) { if (isJoker == false) { throw new UnsupportedOperationException( "Can't change the value of Joker"); } this.suit = suit; } public String getValueString(){ if(value == 1 || value>10){ switch (value) { case ACE: return "Ace"; case JACK: return "Jack"; case QUEEN: return "Queen"; case KING: return "King"; default: return ""; } }else { return Integer.toString(value); } } public String getSuitString(){ switch(suit){ case HEART: return "Heart"; case DIAMOND: return "Diamond"; case CLUBS: return "Club"; case SPADE: return "Spades"; default: return ""; } } public String getCard(int a, int b) { return getValueString() +" " + getSuitString(); } } <file_sep>/ba.bitcamp.week11/src/ba/bitcamp/week11/day4/ThreadesExample1.java package ba.bitcamp.week11.day4; public class ThreadesExample1 implements Runnable { public static void main(String[] args) { ThreadesExample1 thr = new ThreadesExample1(); // thr.run(); Thread t = new Thread(thr); t.start(); for (int i = 0; i < 10; i++) { System.out.println("BIT Camp"); } } @Override public void run() { System.out.println("Going to sleep"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("wake up!"); } } <file_sep>/ba.bitcamp.week5/src/ba/bitcamp/week5/day5/practice/LifeForm/Plant.java package ba.bitcamp.week5.day5.practice.LifeForm; public class Plant extends LifeForm { public static final String IT_IS_EDIBLE = "It is edible"; public static final String SOME_PARTS_ARE_EDIBLE = "Some parts are adible"; public static final String IT_IS_NOT_EDIBLE = "It is not edible"; private boolean isItPoison; private String isEdible; public Plant(String alive, String edible) { super(alive); edible = getItIsEdible(); } public boolean isItPoison() { return isItPoison; } public void setItPoison(boolean isItPoison) { this.isItPoison = isItPoison; } public static String getItIsEdible() { return IT_IS_EDIBLE; } public static String getSomePartsAreEdible() { return SOME_PARTS_ARE_EDIBLE; } public static String getItIsNotEdible() { return IT_IS_NOT_EDIBLE; } } <file_sep>/ba.bitcamp.week06/src/ba/bitcamp/week6/day6/vjezbe/Window5.java package ba.bitcamp.week6.day6.vjezbe; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; public class Window5 extends JFrame{ private static final long serialVersionUID = 8669950363696169046L; private JLabel text = new JLabel("<NAME>"); private JButton right = new JButton(">"); private JButton left = new JButton("<"); private JButton remove = new JButton("Remove"); private int counter = 0; public Window5(){ setLayout(new BorderLayout()); add(text, BorderLayout.CENTER); text.setHorizontalAlignment(NORMAL); add(right,BorderLayout.EAST); add(left, BorderLayout.WEST); add(remove,BorderLayout.SOUTH); setVisible(true); setSize(300,200); Action listener = new Action(); right.addActionListener(listener); left.addActionListener(listener); remove.addActionListener(listener); } private class Action implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { String s = text.getText(); StringBuilder sb = new StringBuilder(s); if(e.getSource()==right){ counter++; String s2 = s.substring(0, counter) + "_" + s.substring(counter+1, s.length()); text.setText(s2.toString()); }else if(e.getSource()==left){ counter--; String s2 =s.substring(0, counter) + "_" + s.substring(counter+1, s.length()); text.setText(s2.toString()); }else if(e.getSource()==remove){ sb.deleteCharAt(counter); } text.setText(sb.toString()); } } public static void main(String[] args) { new Window5(); } } <file_sep>/ba.bitcamp.week11/src/ba/bitcamp/week11/day3/Result.java package ba.bitcamp.week11.day3; import java.io.BufferedWriter; import java.io.IOException; public class Result { public static void ok(BufferedWriter writer, String content) throws IOException{ response(writer, "200 OK", content); } public static void notFound(BufferedWriter writer) throws IOException{ response(writer, "404 Not Found", "This is not the page you are loking for"); } public static void serverError(BufferedWriter writer) throws IOException{ response(writer, "500 Iternal Server Error", "Something Went Wrong"); } private static void response(BufferedWriter writer, String responseCode, String responseContent) throws IOException{ writer.write(String.format("HTTP/1.1 %s \n", responseCode)); writer.write("content-type: text/html\n"); writer.newLine(); writer.write(responseContent); writer.flush(); } } <file_sep>/ba.bitcamp.week5/src/ba/bitcamp/week5/day4/practice/Building.java package ba.bitcamp.week5.day4.practice; public class Building { public String location; public Integer population; public Integer area; public double getPopulationDensity(){ return (double) area/population; } public void printInformation(){ System.out.println(location); System.out.println(population); System.out.println(area); } } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day3/vjezbe/Task7FillArray.java package ba.bitcamp.week8.day3.vjezbe; import java.util.Arrays; public class Task7FillArray { public static void main(String[] args) { System.out.println(Arrays.toString(fillArray(10, 3, 2, 6))); } public static int[] fillArray(int numOfElements, int numToPut, int indexStart, int indexStop) { int[] array = new int[numOfElements]; for (int i = 0; i < array.length; i++) { array[i] = -1; if (i >= indexStart && i <= indexStop) { array[i] = numToPut; } } return array; } } <file_sep>/ba.bitcamp.week06/src/ba/bitcamp/week6/day2/Main.java package ba.bitcamp.week6.day2; public class Main { public static void main(String[] args) { ITijelo [] testTijela = new ITijelo[]{ new Krug(1), new Pravougaonik(5,10), new Kvadrat(5)}; for (ITijelo tijelo:testTijela){ System.out.println(tijelo.toString()); System.out.println("Povrsina:" + tijelo.povrsina()); } Krug k = new Krug(1); System.out.println("Povrsina:" + k.povrsina()); System.out.println("Obim:" + k.obim()); Kvadrat kv = new Kvadrat(10); System.out.println("Povrsina:" + kv.povrsina()); System.out.println("Obim:" + kv.obim()); } } <file_sep>/ba.bitcamp.week06/src/ba/bitcamp/week6/day2/ITijelo.java package ba.bitcamp.week6.day2; public interface ITijelo { double povrsina(); double obim(); } <file_sep>/ba.bitcamp.week08/src/ba/bitcamp/week8/day3/StringArrayList.java package ba.bitcamp.week8.day3; import java.util.ArrayList; import java.util.Arrays; public class StringArrayList { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>( Arrays.asList("This","is","lots","of","fun", "for","every","java","programer")); System.out.println(list); ArrayList<String>temp= new ArrayList<String>(); for (int i = 0; i < list.size()-1; i++) { if(list.get(i).length()==4){ temp.add("****"); temp.add(list.get(i)); }else{ temp.add(list.get(i)); } } System.out.println(temp); } }
b8fc17846a0dad87ad9ee85ad8396e483ada074c
[ "Java", "INI" ]
103
Java
AdnanLapendic/workspace
c1b15b6e94cb86dec431105939934c2554cd32c4
4a86920209f6227ca0f409ef4fd06afddb11e581
refs/heads/master
<file_sep>using System; namespace myProjectApp.Core.Model { public class Account { public int AccountId { get; set; } public string AccountDescription { get; set; } public int AccountStatus { get; set; } } } <file_sep>using System; namespace myProjectApp.Core { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } <file_sep>using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using myProjectApp.api.Options; using myProjectApp.Core.Services; using myProjectApp.Core.Services.Options; using System; namespace myProjectApp.api.Controllers { [ApiController] [Route("[controller]")] public class CustomerController : Controller { private readonly ILogger<CustomerController> _logger; private readonly ICustomerService _customers; public CustomerController(ILogger<CustomerController> logger, ICustomerService customers) { _logger = logger; _customers = customers; } //[HttpGet] //public string Get() //{ // return "Hello World!"; //} [HttpGet] public IActionResult GetAllCustomers() { var custList = _customers.GetAllCustomers(); return Json(custList); } [HttpGet("{id:int}")] public IActionResult GetById(int id) { var customer = _customers.GetById(id); return Json(customer); } [HttpGet("{custid:int}/account/{accountId:int}")] public IActionResult GetAcountByCustomerId(int custid, int accountId) { var customer = _customers.GetAccountByCustomerId(custid, accountId); return Json(customer); } //[HttpPost] //public IActionResult RegisterCustomer( // [FromBody] RegisterCustomerOptions options) //{ // var cust = _customers.Register(options); // return Json(cust); //} [HttpPost] public IActionResult RegisterCustomerAccount( [FromBody] OptionsCustomerAccount options) { var optionsCust = new RegisterCustomerOptions(); optionsCust.Name = options.Name; optionsCust.Surname = options.Surname; optionsCust.VatNumber = options.VatNumber; var optionsAcc = new RegisterAccountOptions(); optionsAcc.AccountDescription = options.AccountDescription; optionsAcc.AccountStatus = options.AccountStatus; var cust = _customers.RegisterCustomerAndAccount(optionsCust, optionsAcc); return Json(cust); } } } <file_sep>using Microsoft.EntityFrameworkCore; using myProjectApp.Core.Data; using myProjectApp.Core.Model; using myProjectApp.Core.Services.Options; using System.Collections.Generic; using System.Linq; namespace myProjectApp.Core.Services { public class CustomerService : ICustomerService { private ΜyBDContext _cust_DBContext; public CustomerService(ΜyBDContext dbContext) { _cust_DBContext = dbContext; } public Customer Register(RegisterCustomerOptions options) { if (string.IsNullOrWhiteSpace(options.Name)) { return null; } if (string.IsNullOrWhiteSpace(options.Surname)) { return null; } if (string.IsNullOrWhiteSpace(options?.VatNumber)) { return null; } var customer = new Customer { Name = options.Name, Surname = options.Surname, VatNumber = options.VatNumber }; _cust_DBContext.Add(customer); _cust_DBContext.SaveChanges(); return customer; } public Customer RegisterCustomerAndAccount(RegisterCustomerOptions optionsCust, RegisterAccountOptions optionsAcc) { if (string.IsNullOrWhiteSpace(optionsCust.Name)) { return null; } if (string.IsNullOrWhiteSpace(optionsCust.Surname)) { return null; } if (string.IsNullOrWhiteSpace(optionsCust?.VatNumber)) { return null; } var customer = new Customer { Name = optionsCust.Name, Surname = optionsCust.Surname, VatNumber = optionsCust.VatNumber }; customer.Accounts.Add( new Account() { AccountDescription = optionsAcc.AccountDescription, AccountStatus = optionsAcc.AccountStatus }); _cust_DBContext.Add(customer); _cust_DBContext.SaveChanges(); return customer; } public Customer GetById(int customerId) { var cust = _cust_DBContext.Set<Customer>() .Where(c => c.CustomerId == customerId) .SingleOrDefault(); return cust; } public List<Customer> GetAllCustomers() { List<Customer> custList = _cust_DBContext.Set<Customer>() .Include(c => c.Accounts) .ToList(); return custList; } public Customer GetAccountByCustomerId(int customerId, int accountId) { var cust = _cust_DBContext.Set<Customer>() .Where(c => c.CustomerId == customerId) .Include(e => e.Accounts) .SingleOrDefault(); return cust; } } } <file_sep>using Microsoft.Extensions.Configuration; namespace myProjectApp.Core.Config.Extensions { public static class ConfigurationExtensions { public static AppConfig ReadAppConfiguration( this IConfiguration @this) { var minLoggingLevel = @this.GetSection("MinLoggingLevel").Value; var connectionString = @this.GetConnectionString("myDatabase"); return new AppConfig() { ConnectionString = connectionString, MinLoggingLevel = minLoggingLevel }; } } } <file_sep>using System; using System.Collections.Generic; namespace myProjectApp.Core.Model { public class Customer { public int CustomerId { get; set; } public string Name { get; set; } public string Surname { get; set; } public string Address { get; set; } public string VatNumber { get; set; } public CustomerCategory CustomerCategory { get; set; } public List<Account> Accounts { get; set; } public Customer() { Accounts = new List<Account>(); } } } <file_sep>using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using myProjectApp.Core.Config.Extensions; using myProjectApp.Core.Data; using myProjectApp.Core.Model; using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApp { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); Console.WriteLine("Hello World2!"); var configuration = new ConfigurationBuilder() .SetBasePath($"{AppDomain.CurrentDomain.BaseDirectory}") .AddJsonFile("appsettings.json", false) .Build(); var config = configuration.ReadAppConfiguration(); var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseSqlServer( config.ConnectionString, options => { options.MigrationsAssembly("myProjectApp"); }); using (var db = new ΜyBDContext(optionsBuilder.Options)) { //var newCustomer = new Customer() //{ // Name = "Sophia", // Surname = "Pogka", // Address = "Pelopida 1", // VatNumber = "123456789", // CustomerCategory = CustomerCategory.Retail //}; //newCustomer.Accounts.Add( // new Account() // { // AccountDescription = "Account 1", // AccountStatus = 1 // }); //newCustomer.Accounts.Add( // new Account() // { // AccountDescription = "Account 2", // AccountStatus = 2 // }); //db.Add(newCustomer); //db.SaveChanges(); List<Account> myAccount = new List<Account>(); myAccount = db.Set<Account>() //.Where(c => c.CustomerId == 1) //.Where(c => c.AccountId == 1) .ToList(); //.SingleOrDefault() //.ToString; Console.WriteLine($"I found Account! VatNumber"); } } } } <file_sep>using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; using System; using myProjectApp.Core.Data; using myProjectApp.Core.Config.Extensions; namespace myProjectApp { public class DbContextFactory : IDesignTimeDbContextFactory<ΜyBDContext> { public ΜyBDContext CreateDbContext(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath($"{AppDomain.CurrentDomain.BaseDirectory}") .AddJsonFile("appsettings.json", false) .Build(); var config = configuration.ReadAppConfiguration(); var optionsBuilder = new DbContextOptionsBuilder<ΜyBDContext>(); optionsBuilder.UseSqlServer( config.ConnectionString, options => { options.MigrationsAssembly("ConsoleAppMigrations"); }); return new ΜyBDContext(optionsBuilder.Options); } } } <file_sep>using System; namespace myProjectApp.Core.Model { public enum CustomerCategory { Undefined = 0, Retail = 1, Business = 2 } } <file_sep>using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using myProjectApp.Core.Config; using myProjectApp.Core.Config.Extensions; using myProjectApp.Core.Data; using Microsoft.EntityFrameworkCore; namespace myProjectApp.Core.Services.Extensions { public static class ServiceCollectionExtensions { public static void AddAppServices( this IServiceCollection @this, IConfiguration configuration) { @this.AddSingleton<AppConfig>( configuration.ReadAppConfiguration()); // AddScoped @this.AddDbContext<ΜyBDContext>( (serviceProvider, optionsBuilder) => { var appConfig = serviceProvider.GetRequiredService<AppConfig>(); optionsBuilder.UseSqlServer(appConfig.ConnectionString); }); @this.AddScoped<ICustomerService, CustomerService>(); } } } <file_sep>using myProjectApp.Core.Model; using myProjectApp.Core.Services.Options; using System.Collections.Generic; namespace myProjectApp.Core.Services { public interface ICustomerService { public Customer Register(RegisterCustomerOptions options); public Customer GetById(int customerId); public List<Customer> GetAllCustomers(); public Customer RegisterCustomerAndAccount(RegisterCustomerOptions optionsCust, RegisterAccountOptions optionsAcc); public Customer GetAccountByCustomerId(int customerId, int accountId); } } <file_sep>#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. FROM mcr.microsoft.com/dotnet/aspnet:5.0-buster-slim AS base WORKDIR /app EXPOSE 80 EXPOSE 443 FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build WORKDIR /src COPY ["app/myProjectApp.api/myProjectApp.api.csproj", "app/myProjectApp.api/"] RUN dotnet restore "app/myProjectApp.api/myProjectApp.api.csproj" COPY . . WORKDIR "/src/app/myProjectApp.api" RUN dotnet build "myProjectApp.api.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "myProjectApp.api.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "myProjectApp.api.dll"]<file_sep>using Microsoft.Extensions.DependencyInjection; using myProjectApp.Core.Data; using myProjectApp.Core.Model; using myProjectApp.Core.Services; using System.Linq; using Xunit; namespace myProjectApp.Tests { public class myCustomerTests : IClassFixture<myProjectFixture> { private ICustomerService _customers; private ΜyBDContext _dbContext; public myCustomerTests(myProjectFixture fixture) { _customers = fixture.Scope.ServiceProvider .GetRequiredService<ICustomerService>(); _dbContext = fixture.Scope.ServiceProvider .GetRequiredService<ΜyBDContext>(); } [Fact] public Customer Add_Customer_Success() { var options = new Core.Services.Options.RegisterCustomerOptions() { Name = "Jim", Surname = "Antivachis", VatNumber = "" }; var cust = _customers.Register(options); Assert.NotNull(cust); var savedCustomer = _dbContext.Set<Customer>() .Where(c => c.CustomerId == cust.CustomerId) .SingleOrDefault(); Assert.NotNull(savedCustomer); Assert.Equal(options.Name, savedCustomer.Name); Assert.Equal(options.Surname, savedCustomer.Surname); Assert.Equal(options.VatNumber, savedCustomer.VatNumber); return cust; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace myProjectApp.Core.Services.Options { public class RegisterAccountOptions { public string AccountDescription { get; set; } public int AccountStatus { get; set; } } } <file_sep>using Microsoft.EntityFrameworkCore; using myProjectApp.Core.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace myProjectApp.Core.Data { public class ΜyBDContext : DbContext { string connectionstring = "Server=localhost;Database=TinyBank;User Id=sa;Password=<PASSWORD>;"; public ΜyBDContext( DbContextOptions options) : base(options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseSqlServer(connectionstring); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Customer>() .ToTable("Customer"); modelBuilder.Entity<Account>() .ToTable("Account"); } } }
5539eb9e8779ca9b0e97108dcf789ba7bb917583
[ "C#", "Dockerfile" ]
15
C#
SophiaPogka/myProjectApp2
83d7fd7da8219d9bac275b96822e258f330890ba
676415d61b7583fcc58454af88822cbe031b0fba
refs/heads/master
<file_sep>#__________________________Jogo__da__Velha__________________________________ #A variável "jogar" permite ao usuário escolher #continuar jogando indefinidamente ou sair do programa #__________________________________________________________ jogar = str(input('Digite J para jogar ou S para sair: ')) while jogar == 'J': #_________________________Início__do__jogo__________________________________ #Temos a função "tabuleiro", com uma matriz 3x3, permitindo que o tabuleiro #seja impresso no decorrer do código, de forma atualizada a cada jogada print ("_____________________________________________") print ("Sejam bem-vindos ao Jogo da Velha!") print ("Preparados??? Lá vamos nós!!!") posiçao = [['1', '2', '3'],['4', '5', '6'],['7', '8', '9']] def tabuleiro(): print(' ',posiçao[2][0],' | ' ,posiçao[2][1], ' | ' ,posiçao[2][2], '') print("----+-----+----") print(' ',posiçao[1][0],' | ' ,posiçao[1][1], ' | ' ,posiçao[1][2],'') print("-----+-----+----") print(' ',posiçao[0][0],' | ' ,posiçao[0][1], ' | ' ,posiçao[0][2], '') tabuleiro() #=================================================================================== #_________________Mostrando__a__jogada__no__tabuleiro_______________________ #As funções "jogada_X" e "jogada_O" armazenam o valor da respectiva jogada, #caso seja um valor válido, será impresso no tabuleiro, do contrário, #o programa pedirá a posição até que seja um valor válido. #A variável "casaVazia" verifica se a posição escolhida está sendo ocupada ou não def jogada_X(): casaVazia = True while casaVazia: jogada_X = str(input('Digite a posição onde X vai jogar: ')) if jogada_X == '1': if posiçao[0][0] != 'O' and posiçao[0][0] != 'X': posiçao[0][0] = 'X' casaVazia= False elif jogada_X == '2': if posiçao[0][1] != 'O' and posiçao[0][1] != 'X': posiçao[0][1] = 'X' casaVazia= False elif jogada_X == '3': if posiçao[0][2] != 'O' and posiçao[0][2] != 'X': posiçao[0][2] = 'X' casaVazia= False elif jogada_X == '4': if posiçao[1][0] != 'O' and posiçao[1][0] != 'X': posiçao[1][0] = 'X' casaVazia= False elif jogada_X == '5': if posiçao[1][1] != 'O' and posiçao[1][1] != 'X': posiçao[1][1] = 'X' casaVazia= False elif jogada_X == '6': if posiçao[1][2] != 'O' and posiçao[1][2] != 'X': posiçao[1][2] = 'X' casaVazia= False elif jogada_X == '7': if posiçao[2][0] != 'O' and posiçao[2][0] != 'X': posiçao[2][0]= 'X' casaVazia= False elif jogada_X == '8': if posiçao[2][1] != 'O' and posiçao[2][1] != 'X': posiçao[2][1] = 'X' casaVazia= False elif jogada_X == '9': if posiçao[2][2] != 'O' and posiçao[2][2] != 'X': posiçao[2][2] = 'X' casaVazia= False if casaVazia: print('Posição inválida! Jogue novamente!') tabuleiro() def jogada_O(): casaVazia = True while casaVazia: jogada_O = str(input('Digite a posição onde O vai jogar: ')) if jogada_O == '1': if posiçao[0][0] != 'O' and posiçao[0][0] != 'X': posiçao[0][0] = 'O' casaVazia= False elif jogada_O == '2': if posiçao[0][1] != 'O' and posiçao[0][1] != 'X': posiçao[0][1]= 'O' casaVazia= False elif jogada_O == '3': if posiçao[0][2] != 'O' and posiçao[0][2] != 'X': posiçao[0][2] = 'O' casaVazia= False elif jogada_O == '4': if posiçao[1][0] != 'O' and posiçao[1][0] != 'X': posiçao[1][0] = 'O' casaVazia= False elif jogada_O == '5': if posiçao[1][1] != 'O' and posiçao[1][1] != 'X': posiçao[1][1] = 'O' casaVazia= False elif jogada_O == '6': if posiçao[1][2] != 'O' and posiçao[1][2] != 'X': posiçao[1][2] = 'O' casaVazia= False elif jogada_O == '7': if posiçao[2][0] != 'O' and posiçao[2][0] != 'X': posiçao[2][0]= 'O' casaVazia= False elif jogada_O == '8': if posiçao[2][1] != 'O' and posiçao[2][1] != 'X': posiçao[2][1]= 'O' casaVazia= False elif jogada_O == '9': if posiçao[2][2] != 'O' and posiçao[2][2] != 'X': posiçao[2][2] = 'O' casaVazia= False elif casaVazia: print('Posição inválida! Jogue novamente!') tabuleiro() #======================================================================== #____________________Verificando__vencedor!_________________________ #Foi criado um while True para a “jogada_O()” e “jogada_X()”, #contendo as formas que os jogadores tem de ganhar. #Temos um contador de jogadas que inicia em 0, se no final for ==9, #significa que todas as casas estão preenchidas e não temos um vencedor. contaJogadas = 0 while True: jogada_O() contaJogadas = contaJogadas + 1 horizontal3 = [posiçao[2][0],posiçao[2][1],posiçao[2][2]] horizontal2 = [posiçao[1][0],posiçao[1][1],posiçao[1][2]] horizontal1 = [posiçao[0][0],posiçao[0][1],posiçao[0][2]] vertical1 = [posiçao[2][0],posiçao[1][0],posiçao[0][0]] vertical2 = [posiçao[2][1],posiçao[1][1],posiçao[0][1]] vertical3 = [posiçao[2][2],posiçao[1][2],posiçao[0][2]] diagonal1 = [posiçao[2][0],posiçao[1][1],posiçao[0][2]] diagonal2 = [posiçao[2][2],posiçao[1][1],posiçao[0][0]] if horizontal1 == ['X','X','X']: print ('X Ganhou!') break elif horizontal1 == ['O','O','O']: print ('O Ganhou!') break elif horizontal2 == ['X','X','X']: print ('X Ganhou!') break elif horizontal2 == ['O','O','O']: print ('O Ganhou!') break elif horizontal3 == ['X','X','X']: print ('X Ganhou!') break elif horizontal3 == ['O','O','O']: print ('O Ganhou!') break elif vertical1 == ['X','X','X']: print ('X Ganhou!') break elif vertical1 == ['O','O','O']: print ('O Ganhou!') break elif vertical2 == ['X','X','X']: print ('X Ganhou!') break elif vertical2 == ['O','O','O']: print ('O Ganhou!') break elif vertical3 == ['X','X','X']: print ('X Ganhou!') break elif vertical3 == ['O','O','O']: print ('O Ganhou!') break elif diagonal1 == ['X','X','X']: print ('X Ganhou!') break elif diagonal1 == ['O','O','O']: print ('O Ganhou!') break elif diagonal2 == ['X','X','X']: print ('X Ganhou!') break elif diagonal2 == ['O','O','O']: print ('O Ganhou!') break else: if contaJogadas==9: print('Que pena... Deu velha! Ninguém ganhou!') break jogada_X() contaJogadas = contaJogadas + 1 horizontal3 = [posiçao[2][0],posiçao[2][1],posiçao[2][2]] horizontal2 = [posiçao[1][0],posiçao[1][1],posiçao[1][2]] horizontal1 = [posiçao[0][0],posiçao[0][1],posiçao[0][2]] vertical1 = [posiçao[2][0],posiçao[1][0],posiçao[0][0]] vertical2 = [posiçao[2][1],posiçao[1][1],posiçao[0][1]] vertical3 = [posiçao[2][2],posiçao[1][2],posiçao[0][2]] diagonal1 = [posiçao[2][0],posiçao[1][1],posiçao[0][2]] diagonal2 = [posiçao[2][2],posiçao[1][1],posiçao[0][0]] if horizontal1 == ['X','X','X']: print ('X Ganhou!') break elif horizontal1 == ['O','O','O']: print ('O Ganhou!') break elif horizontal2 == ['X','X','X']: print ('X Ganhou!') break elif horizontal2 == ['O','O','O']: print ('O Ganhou!') break elif horizontal3 == ['X','X','X']: print ('X Ganhou!') break elif horizontal3 == ['O','O','O']: print ('O Ganhou!') break elif vertical1 == ['X','X','X']: print ('X Ganhou!') break elif vertical1 == ['O','O','O']: print ('O Ganhou!') break elif vertical2 == ['X','X','X']: print ('X Ganhou!') break elif vertical2 == ['O','O','O']: print ('O Ganhou!') break elif vertical3 == ['X','X','X']: print ('X Ganhou!') break elif vertical1 == ['O','O','O']: print ('O Ganhou!') break elif diagonal1 == ['X','X','X']: print ('X Ganhou!') break elif diagonal1 == ['O','O','O']: print ('O Ganhou!') break elif diagonal2 == ['X','X','X']: print ('X Ganhou!') break elif diagonal2 == ['O','O','O']: print ('O Ganhou!') break else: if contaJogadas==9: print('Que pena... Deu velha! Ninguém ganhou!') break #====================================================================== #________________________Finalizando______________________ #A variável "jogar" permite ao usuário continuar jogando indefinidamente #(porém os pontos do jogo anterior não serão levados em consideração) ou sair do jogo. print (" ") print ("________________________________________________") jogar = str(input('Digite J para jogar ou S para sair: ')) else: print ("Okay! Bye!") #======================================================================
023262be151ee2d0cfdb34ecc8ebc4cdff0b4241
[ "Python" ]
1
Python
stefanie-bevilaqua/jogo-da-velha
7fcd763bb3a03f1a2614b96db3b03bd12e1cb4bd
350a2ca18654363d38758032232cffb6ed6791fb
refs/heads/master
<file_sep># rookalkar.github.io <file_sep> L.mapbox.accessToken = '<KEY>'; var new_map = L.mapbox.map('map2', 'initdot.ljplbdcp').setView([21, 80], 4.5) var map = L.mapbox.map('map1', 'initdot.ljplbdcp').setView([21,80], 4.5), // color reference from color brewer mapBrew = ["#edd997",'#E6B71E','#DA9C20','#CA8323','#B86B25','#A25626','#723122'], // population density range used for choropleth and legend mapRange = [ 4000, 3000, 2000, 1000, 500, 100, 0 ]; // map legend for population density var legend = L.mapbox.legendControl( { position: "bottomleft" } ).addLegend( getLegendHTML() ).addTo(map), // popup for displaying state census details popup = new L.Popup({ autoPan: false, className: 'statsPopup' }), popup2 = new L.Popup({ autoPan: false, className: 'statsPopup' }), // layer for each state feature from geojson statesLayer, closeTooltip; var legend = L.mapbox.legendControl( { position: "bottomleft" } ).addLegend( getLegendHTML() ).addTo(new_map) map.scrollWheelZoom.disable(); new_map.scrollWheelZoom.disable(); // fetch the state geojson data d3.json( "IND_adm1.geojson", function (statesData) { var passvalue; statesLayer = L.geoJson(statesData, { style: getStyle1, onEachFeature: onEachFeature }).addTo(map); statesLayer = L.geoJson(statesData, { style: getStyle2, onEachFeature: onEachFeature }).addTo(new_map); } ); function getStyle1(feature) { return { weight: 2, opacity: 0.1, color: 'black', fillOpacity: 0.85, fillColor: getDensityColor(datatotal.data2001[feature.properties.NAME_1.toUpperCase()].Total) }; } function getStyle2(feature) { return { weight: 2, opacity: 0.1, color: 'black', fillOpacity: 0.85, fillColor: getDensityColor(datatotal.data2014[feature.properties.NAME_1.toUpperCase()].Total) }; } // get color depending on population density value function getDensityColor(d) { var colors = Array.prototype.slice.call(mapBrew).reverse(), // creates a copy of the mapBrew array and reverses it range = mapRange; return d > range[0] ? colors[0] : d > range[1] ? colors[1] : d > range[2] ? colors[2] : d > range[3] ? colors[3] : d > range[4] ? colors[4] : d > range[5] ? colors[5] : colors[6]; } function onEachFeature(feature, layer) { layer.on({ mousemove: mousemove, mouseout: mouseout, click: zoomToFeature }); } function mousemove(e) { var layer = e.target; var popupData2014 = { Total: datatotal.data2014[layer.feature.properties.NAME_1.toUpperCase()].Total, Year: datatotal.data2014[layer.feature.properties.NAME_1.toUpperCase()].Year, state: layer.feature.properties.NAME_1 }; var popupData2001 = { Total: datatotal.data2001[layer.feature.properties.NAME_1.toUpperCase()].Total, Year: datatotal.data2001[layer.feature.properties.NAME_1.toUpperCase()].Year, state: layer.feature.properties.NAME_1 }; popup.setLatLng(e.latlng); var popContent = L.mapbox.template( d3.select("#popup-template").text() , popupData2014 ); popup.setContent( popContent ); if (!popup._map) popup.openOn(new_map); window.clearTimeout(closeTooltip); popup2.setLatLng(e.latlng); var popContent2 = L.mapbox.template( d3.select("#popup-template").text() , popupData2001 ); popup2.setContent( popContent2 ); if (!popup2._map) popup2.openOn(map); window.clearTimeout(closeTooltip); if (!L.Browser.ie && !L.Browser.opera) { layer.bringToFront(); } } function mouseout(e) { closeTooltip = window.setTimeout(function() { // ref: https://www.mapbox.com/mapbox.js/api/v2.1.6/l-map-class/ map.closePopup( popup2 ); new_map.closePopup( popup );// close only the state details popup }, 100); } function zoomToFeature(e) { map.fitBounds(e.target.getBounds()); } function getLegendHTML() { var grades = Array.prototype.slice.call(mapRange).reverse(), // creates a copy of ranges and reverses it labels = [], from, to; // color reference from color brewer var brew = mapBrew; for (var i = 0; i < grades.length; i++) { from = grades[i]; to = grades[i + 1]; labels.push( '<i style="background:' + brew[i] + '"></i> ' + from + (to ? '&ndash;' + to : '+')); } //return '<span>Farmer Suicides per State/UT</span><br>' + labels.join('<br>'); return labels.join('<br>'); }
1c1cadc2ffc25234f5a09aa82b9722e65ef600b4
[ "Markdown", "JavaScript" ]
2
Markdown
rookalkar/old-rookalkar.github.io
98f22df3ea192a2a95b765784b668e2c6a6a5a43
00892ff3435164bd15c9c00dc9b8a8878e5dff84
refs/heads/main
<file_sep>const useOverlay = () => { const animation = { exit: { opacity: 1, pointerEvents: "unset", visibility: "visible", overFlow: "hidden", transition: { duration: 1, ease: "easeOut" }, }, exitImg: { opacity: 1, pointerEvents: "unset", transition: { duration: 0.5, ease: "easeOut" }, }, animate: { opacity: 0, pointerEvents: "none", overFlow: "unset", transition: { delay: 0.5, duration: 1, ease: "easeOut" }, }, animateImg: { opacity: 0, pointerEvents: "none", transition: { duration: 0.5, ease: "easeOut" }, }, }; return [animation]; }; export default useOverlay; <file_sep>import React from "react"; import "./style.css"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faCopyright } from "@fortawesome/free-regular-svg-icons"; const Footer = ({ dark }) => { return ( <footer className={`footer ${dark ? "footer--dark" : null}`}> <p className="footer_text"> <FontAwesomeIcon icon={faCopyright} /> 2020 Prospa Inc </p> </footer> ); }; export default Footer; <file_sep>import React, { useState, useEffect } from "react"; import image1 from "../../assets/[email protected]"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faChevronDown } from "@fortawesome/free-solid-svg-icons"; import "./style.css"; const DashboardSelect = ({ options }) => { const [businessName, setBusinessName] = useState(); const [clickButton, setClickButton] = useState(true); useEffect(() => { setBusinessName(options[0].name); }, []); // eslint-disable-line react-hooks/exhaustive-deps const clickSelect = () => { clickButton ? setClickButton(false) : setClickButton(true); }; return ( <> <div className="dashboardSelect"> <div className="dashboardSelect_accDetails"> <div className="dashboardSelect_accDetails_img"> <img src={image1} alt="businessImg" /> </div> <div className="dashboardSelect_accDetails_text"> <span className="dashboardSelect_accDetails_text_header"> {businessName} </span> <span className="dashboardSelect_accDetails_text_paragraph"> Manage account </span> </div> </div> <div className="dashboardSelect_icon" onClick={clickSelect}> <span className={` icon ${ clickButton ? "icon_spin_on" : " icon_spin_off" }`} > <FontAwesomeIcon icon={faChevronDown} className="icon" /> </span> </div> <div className={`dashboardSelect_options ${ clickButton ? "disappear" : "appear" }`} onClick={clickSelect} > <ul className="dashboardSelect_options_container"> {options.map((option) => { return ( <li className={`dashboardSelect_options_container_option ${ businessName === option.name ? "dashboardSelect_options_container_option--active" : null }`} onClick={() => { setBusinessName(option.name); }} > {option.name} </li> ); })} <span className="dashboardSelect_options_container_cta"> Add a business </span> </ul> </div> </div> </> ); }; export default DashboardSelect; <file_sep>import React, { useState, useEffect } from "react"; import { Link } from "react-router-dom"; import Sidebar from "../../Components/Sidebar/Sidebar"; import Navbar from "../../Components/Navbar/Navbar"; import Footer from "../../Components/Footer/Footer"; import "./style.css"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faCheck } from "@fortawesome/free-solid-svg-icons"; import logo from "../../assets/Combined Shape [email protected]"; import { motion } from "framer-motion"; import useOverlay from "../../hooks/useOverlay"; const SignUpBusiness = () => { const [selectedOption, setSelectedOption] = useState(false); const [animation] = useOverlay(); useEffect(() => { window.scrollTo(0, 0); window.onbeforeunload = function () { window.scrollTo(0, 0); }; }, []); // eslint-disable-line react-hooks/exhaustive-deps return ( <div className="container"> {/* Page Transition Div */} <motion.div className="overlay" variants={animation} animate="animate" exit="exit" > <motion.img variants={animation} animate="animateImg" exit="exitImg" src={logo} alt="logo" /> </motion.div> {/* Page Transition Div */} {/* Sidebar Div */} <aside className="sideContent"> <Sidebar /> </aside> {/* Sidebar Div */} {/* Main Content Div */} <section className="main"> {/* Sub Div 1 */} <div className="main_head"> <Navbar /> </div> {/* Sub Div 1 */} {/* Sub Div 2 */} <div className="main_body"> {/* Sub Div 2 Header*/} <div className="main_body_top"> <span className="main_body_top_header"> Open a new business account </span> <p className="main_body_top_paragraph"> {" "} A short description comes here{" "} </p> </div>{" "} {/* Sub Div 2 Header*/} {/* Sub Div 2 Form*/} <div className="main_body_middle"> <form className="main_body_middle_form"> {/* CAC Section */} <div className={`main_body_middle_form_container ${ selectedOption === "cac" ? "box_active" : "null" }`} onClick={() => { setSelectedOption("cac"); }} > <div className="main_body_middle_form_container_radio"> <div className="main_body_middle_form_container_radio_container"> <div className={`main_body_middle_form_container_radio_container--active ${ selectedOption === "cac" ? "show_content" : "hide_content" }`} ></div> </div> </div> <div className="main_body_middle_form_container_text"> <div className="main_body_middle_form_container_text_header"> <span>I have a registered business /</span> <span>charity with CAC</span> </div> <div className={`main_body_middle_form_container_text_body ${ selectedOption === "cac" ? "show_content" : "hide_content" }`} > <div className="main_body_middle_form_container_text_body_head"> <p>As a registered business you'll get:</p> </div> <ul className="main_body_middle_form_container_text_body_body"> <li> <span className="main_body_middle_form_container_text_body_body_icon"> {" "} <FontAwesomeIcon icon={faCheck} /> </span> <p>Account in your business name</p> </li> <li> <span className="main_body_middle_form_container_text_body_body_icon"> {" "} <FontAwesomeIcon icon={faCheck} /> </span> <p> Send to and receive transfers from all Nigerian banks </p> </li> <li> <span className="main_body_middle_form_container_text_body_body_icon"> {" "} <FontAwesomeIcon icon={faCheck} /> </span> <p>Tools for business management</p> </li> </ul> </div> </div> </div> {/* Business Not Registered Section */} <div className={`main_body_middle_form_container ${ selectedOption === "not" ? "box_active" : "null" }`} onClick={() => { setSelectedOption("not"); }} > <div className="main_body_middle_form_container_radio"> <div className="main_body_middle_form_container_radio_container"> <div className={`main_body_middle_form_container_radio_container--active ${ selectedOption === "not" ? "show_content" : "hide_content" }`} ></div> </div> </div> <div className="main_body_middle_form_container_text"> <div className="main_body_middle_form_container_text_header"> <span>My business is not yet registered,</span> <span>I would like to register</span> </div> <div className={`main_body_middle_form_container_text_body ${ selectedOption === "not" ? "show_content" : "hide_content" }`} > <div className="main_body_middle_form_container_text_body_head"> <p>Everything you need to start your business</p> </div> <ul className="main_body_middle_form_container_text_body_body"> <li> <span className="main_body_middle_form_container_text_body_body_icon"> {" "} <FontAwesomeIcon icon={faCheck} /> </span> <p>Registered business name with the CAC</p> </li> <li> <span className="main_body_middle_form_container_text_body_body_icon"> {" "} <FontAwesomeIcon icon={faCheck} /> </span> <p>Tax identification number</p> </li> <li> <span className="main_body_middle_form_container_text_body_body_icon"> {" "} <FontAwesomeIcon icon={faCheck} /> </span> <p> Your account will be automatically opened on completion </p> </li> </ul> </div> </div> </div> {/* Freelancer Section */} <div className={`main_body_middle_form_container ${ selectedOption === "freelance" ? "box_active" : "null" }`} onClick={() => { setSelectedOption("freelance"); }} > <div className="main_body_middle_form_container_radio"> <div className="main_body_middle_form_container_radio_container"> <div className={`main_body_middle_form_container_radio_container--active ${ selectedOption === "freelance" ? "show_content" : "hide_content" }`} ></div> </div> </div> <div className="main_body_middle_form_container_text"> <div className="main_body_middle_form_container_text_header"> <span> I’m a freelancer I do business in my personal name </span> </div> <div className={`main_body_middle_form_container_text_body ${ selectedOption === "freelance" ? "show_content" : "hide_content" }`} > <div className="main_body_middle_form_container_text_body_head"> <p>Everything you need to start your business</p> </div> <ul className="main_body_middle_form_container_text_body_body"> <li> <span className="main_body_middle_form_container_text_body_body_icon"> {" "} <FontAwesomeIcon icon={faCheck} /> </span> <p>Registered business name with the CAC</p> </li> <li> <span className="main_body_middle_form_container_text_body_body_icon"> {" "} <FontAwesomeIcon icon={faCheck} /> </span> <p>Tax identification number</p> </li> <li> <span className="main_body_middle_form_container_text_body_body_icon"> {" "} <FontAwesomeIcon icon={faCheck} /> </span> <p> Your account will be automatically opened on completion </p> </li> </ul> </div> </div> </div> </form> </div>{" "} {/* Sub Div 2 Form*/} {/* Sub Div 2 Button*/} <div className="main_body_bottom"> <Link to="/signIn"> <button>Next</button> </Link> </div> {/* Sub Div 2 Button*/} </div> {/* Sub Div 2 */} </section> {/* Main Content Div */} <Footer /> </div> ); }; export default SignUpBusiness; <file_sep>import React from "react"; import "./style.css"; const Input = ({ name, text, type }) => { return ( <div className="input"> <input type={type} name={name} required /> <label for={name} className="label_name"> <span className="content_name">{text}</span> </label> </div> ); }; export default Input; <file_sep>import React, { useState, useEffect } from "react"; import DashboardSidebar from "../../Components/DashboardSidebar/DashboardSidebar"; import DashboardNavbar from "../../Components/DashboardNavbar/DashboardNavbar"; import AccountCard from "../../Components/DashboardAccountCard/DashboardAccountCard"; import Footer from "../../Components/Footer/Footer"; import image1 from "../../assets/Group [email protected]"; import image2 from "../../assets/Group [email protected]"; import image3 from "../../assets/Group [email protected]"; import image4 from "../../assets/Group [email protected]"; import image5 from "../../assets/Group [email protected]"; import image6 from "../../assets/Group [email protected]"; import image7 from "../../assets/Group [email protected]"; import logo from "../../assets/Combined Shape [email protected]"; import { motion } from "framer-motion"; import useOverlay from "../../hooks/useOverlay"; import "./style.css"; const Dashboard = () => { const [showMobile, setShowMobile] = useState(false); const [animation] = useOverlay(); useEffect(() => { window.scrollTo(0, 0); window.onbeforeunload = function () { window.scrollTo(0, 0); }; }, []); // eslint-disable-line react-hooks/exhaustive-deps const mobileNav = () => { showMobile ? setShowMobile(false) : setShowMobile(true); }; return ( <div className={`dashboardContainer ${showMobile ? "overFlow" : null}`}> {/* Page Transition Div */} <motion.div className="overlay" variants={animation} animate="animate" exit="exit" > <motion.img variants={animation} animate="animateImg" exit="exitImg" src={logo} alt="logo" /> </motion.div> {/* Page Transition Div */} {/* Sidebar Div */} <aside className={`dashboardSideContent ${ showMobile ? "dashboardSideContent--move" : null }`} > <DashboardSidebar /> </aside> {/* Sidebar Div */} {/* Main Content Div */} <section className="dashboardMain"> {/* Sub Div 1 */} <div className="dashboardMain_head"> <DashboardNavbar func={mobileNav} /> </div> {/* Sub Div 1 */} {/* Sub Div 2 */} <div className="dashboardMain_body"> {/* Sub Div 2 Top */} <div className="dashboardMain_body_head"> <div className="dashboardMain_body_head_text"> <span className="dashboardMain_body_head_text_header"> Welcome back, Kathy </span> <p className="dashboardMain_body_head_text_paragraph"> Here’s what has been happening in the last{" "} <span className="dashboardMain_body_head_text_paragraph_days"> 7 days </span> </p> </div> <button className="dashboardMain_body_head_cta"> Add a sub account </button> </div>{" "} {/* Sub Div 2 Top */} {/* Sub Div 2 Main */} <div className="dashboardMain_body_body"> {/* Accounts Div */} <div className="dashboardMain_body_body_top"> <AccountCard bank="PROVIDUS BANK" accountNo="9906533917" balance="814,800" kobo="45" current /> <AccountCard bank="SUB ACCOUNT" accountNo="12346789" balance="39,342" kobo="45" /> </div> {/* Accounts Div */} {/* Summary Div */} <div className="dashboardMain_body_body_middle"> <div className="dashboardMain_body_body_middle_summary"> <span className="dashboardMain_body_body_middle_summary_month"> June summary </span> <div className="dashboardMain_body_body_middle_summary_transaction"> <div className="dashboardMain_body_body_middle_summary_transaction_text"> <span className="dashboardMain_body_body_middle_summary_transaction_text_top"> Money in </span> <span className="dashboardMain_body_body_middle_summary_transaction_text_bottom"> ₦ 5,650,000 </span> </div> <div className="dashboardMain_body_body_middle_summary_transaction_text"> <span className="dashboardMain_body_body_middle_summary_transaction_text_top"> Money out </span> <span className="dashboardMain_body_body_middle_summary_transaction_text_bottom"> ₦ 5,650,000 </span> </div> <div className="dashboardMain_body_body_middle_summary_transaction_text"> <span className="dashboardMain_body_body_middle_summary_transaction_text_top"> Difference </span> <span className="dashboardMain_body_body_middle_summary_transaction_text_bottom"> ₦ 5,650,000 </span> </div> </div> <div className="dashboardMain_body_body_middle_summary_graph"> <img src={image1} alt="graph" /> </div> </div> <div className="dashboardMain_body_body_middle_outflow"> <span className="dashboardMain_body_body_middle_outflow_head"> Cash outflow </span> <div className="dashboardMain_body_body_middle_outflow_body"> {/* Bank */} <div className="dashboardMain_body_body_middle_outflow_body_type"> <div className="dashboardMain_body_body_middle_outflow_body_type_bank"> <div className="dashboardMain_body_body_middle_outflow_body_type_bank_image"> <img src={image2} alt="bank" /> </div> <span className="dashboardMain_body_body_middle_outflow_body_type_bank_text"> Bank Fees </span> </div> <div className="dashboardMain_body_body_middle_outflow_body_type_bank_range"> <span className="dashboardMain_body_body_middle_outflow_body_type_bank_range_price"> - ₦ 250, 000 </span> <div className="dashboardMain_body_body_middle_outflow_body_type_bank_range_progress"></div> </div> </div> {/* Bank */} {/* Internet */} <div className="dashboardMain_body_body_middle_outflow_body_type"> <div className="dashboardMain_body_body_middle_outflow_body_type_internet"> <div className="dashboardMain_body_body_middle_outflow_body_type_internet_image"> <img src={image3} alt="Internet" /> </div> <span className="dashboardMain_body_body_middle_outflow_body_type_internet_text"> Internet </span> </div> <div className="dashboardMain_body_body_middle_outflow_body_type_internet_range"> <span className="dashboardMain_body_body_middle_outflow_body_type_internet_range_price"> - ₦ 250, 000 </span> <div className="dashboardMain_body_body_middle_outflow_body_type_internet_range_progress"></div> </div> </div> {/* Internet */} {/* Marketing */} <div className="dashboardMain_body_body_middle_outflow_body_type"> <div className="dashboardMain_body_body_middle_outflow_body_type_marketing"> <div className="dashboardMain_body_body_middle_outflow_body_type_marketing_image"> <img src={image4} alt="Marketing" /> </div> <div className="dashboardMain_body_body_middle_outflow_body_type_marketing_text"> Marketing </div> </div> <div className="dashboardMain_body_body_middle_outflow_body_type_marketing_range"> <span className="dashboardMain_body_body_middle_outflow_body_type_marketing_range_price"> - ₦ 250, 000 </span> <div className="dashboardMain_body_body_middle_outflow_body_type_marketing_range_progress"></div> </div> </div> {/* Marketing */} {/* Transfer */} <div className="dashboardMain_body_body_middle_outflow_body_type"> <div className="dashboardMain_body_body_middle_outflow_body_type_transfer"> <div className="dashboardMain_body_body_middle_outflow_body_type_transfer_image"> <img src={image5} alt="transfer" /> </div> <span className="dashboardMain_body_body_middle_outflow_body_type_transfer_text"> Transfer </span> </div> <div className="dashboardMain_body_body_middle_outflow_body_type_transfer_range"> <span className="dashboardMain_body_body_middle_outflow_body_type_transfer_range_price"> - ₦ 250, 000 </span> <div className="dashboardMain_body_body_middle_outflow_body_type_transfer_range_progress"></div> </div> </div> {/* Transfer */} </div> </div> </div> {/* Summary Div */} {/* Transaction Div */} <div className="dashboardMain_body_body_bottom"> <div className="dashboardMain_body_body_bottom_head"> <span className="dashboardMain_body_body_bottom_head_text"> Recent transactions </span> <button className="dashboardMain_body_body_bottom_head_cta"> See all </button> </div> <div className="dashboardMain_body_body_bottom_body"> <div className="dashboardMain_body_body_bottom_body_transactions"> <div className="dashboardMain_body_body_bottom_body_transactions_transaction"> <div className="dashboardMain_body_body_bottom_body_transactions_transaction_icon"> <img src={image6} alt="icon" /> </div> <div className="dashboardMain_body_body_bottom_body_transactions_transaction_details"> <span className="dashboardMain_body_body_bottom_body_transactions_transaction_details_text"> Transfer Fee </span> <span className="dashboardMain_body_body_bottom_body_transactions_transaction_details_time"> 12:49 Am </span> </div> </div> <span className="dashboardMain_body_body_bottom_body_transactions_price"> -₦145.90 </span> </div> <div className="dashboardMain_body_body_bottom_body_transactions"> <div className="dashboardMain_body_body_bottom_body_transactions_transaction"> <div className="dashboardMain_body_body_bottom_body_transactions_transaction_icon"> <img src={image7} alt="icon" /> </div> <div className="dashboardMain_body_body_bottom_body_transactions_transaction_details"> <span className="dashboardMain_body_body_bottom_body_transactions_transaction_details_text"> <NAME> </span> <span className="dashboardMain_body_body_bottom_body_transactions_transaction_details_time"> 12:49 Am </span> </div> </div> <span className="dashboardMain_body_body_bottom_body_transactions_price"> -₦2,000.00 </span> </div> <div className="dashboardMain_body_body_bottom_body_transactions"> <div className="dashboardMain_body_body_bottom_body_transactions_transaction"> <div className="dashboardMain_body_body_bottom_body_transactions_transaction_icon"> <img src={image7} alt="icon" /> </div> <div className="dashboardMain_body_body_bottom_body_transactions_transaction_details"> <span className="dashboardMain_body_body_bottom_body_transactions_transaction_details_text"> <NAME> </span> <span className="dashboardMain_body_body_bottom_body_transactions_transaction_details_time"> 12:49 Am </span> </div> </div> <span className="dashboardMain_body_body_bottom_body_transactions_price"> -₦2,000.00 </span> </div> </div> </div> {/* Transaction Div */} </div> {/* Sub Div 2 Main */} </div> {/* Sub Div 2 */} </section> {/* Main Content Div */} <Footer dark /> </div> ); }; export default Dashboard; <file_sep>import "./App.css"; import { Route, Switch, useLocation } from "react-router-dom"; import SignUp from "./pages/signUp/signUp"; import SignUpBusiness from "./pages/signUpBusiness/signUpBusiness"; import SignIn from "./pages/signIn/signIn"; import Dashboard from "./pages/dashboard/dashboard"; import { AnimatePresence } from "framer-motion"; function App() { const location = useLocation(); return ( <div className="App"> <AnimatePresence exitBeforeEnter> <Switch location={location} key={location.key}> <Route path="/" exact component={SignUp} /> <Route path="/signupbusiness" exact component={SignUpBusiness} /> <Route path="/signin" exact component={SignIn} /> <Route path="/dashboard" exact component={Dashboard} /> </Switch> </AnimatePresence> </div> ); } export default App; <file_sep>import React from "react"; import "./style.css"; const DashboardAccountCard = ({ current, bank, accountNo, balance, kobo }) => { return ( <div className="accCard"> <div className="accCard_top"> <div className="accCard_top_text"> <span className="accCard_top_text_header"> {current ? "current account" : "savings account"} </span> <p className="accCard_top_text_paragraph"> {bank} - {accountNo} </p> </div> <div className={`accCard_top_icon ${ current ? null : "accCard_top_icon--bgc" }`} > <div className={`accCard_top_icon_inner ${ current ? null : "accCard_top_icon_inner--bgc" }`} ></div> </div> </div> <div className="accCard_bottom"> <span className="accCard_bottom_price">₦{balance}</span> <span className="accCard_bottom_unit">.{kobo}</span> </div> </div> ); }; export default DashboardAccountCard; <file_sep>import React from "react"; import logo from "../../assets/Combined [email protected]"; import image1 from "../../assets/[email protected]"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faCopyright } from "@fortawesome/free-regular-svg-icons"; import "./style.css"; const Sidebar = ({ dark }) => { return ( <> <div className={`sidebar ${dark ? "sidebar--dark" : null}`}> <div className="sidebar_top"> <img src={logo} alt="logo" />{" "} </div> <div className="sidebar_middle"> <div className="sidebar_middle_slide"> <div className="sidebar_middle_slide_1"></div> <div className="sidebar_middle_slide_2"></div> <div className="sidebar_middle_slide_3"></div> <div className="sidebar_middle_slide_4"></div> <div className="sidebar_middle_slide_5"></div> </div> <div className="sidebar_middle_text"> {" "} <div className="sidebar_middle_text_header"> {" "} <span>Create multiple</span> <span>sub-account</span> </div> <p className="sidebar_middle_text_paragraph"> Organize your business finances easily with multiple accounts, No limits! </p> </div> <div className="sidebar_middle_img"> <img src={image1} alt="money-img" />{" "} </div> </div> <div className="sidebar_bottom"> <p className="sidebar_bottom_text"> <FontAwesomeIcon icon={faCopyright} /> 2020 Prospa Inc </p> </div> </div> </> ); }; export default Sidebar; <file_sep>import React from "react"; import logo from "../../assets/Combined Shape [email protected]"; import image1 from "../../assets/[email protected]"; import image2 from "../../assets/[email protected]"; import image3 from "../../assets/[email protected]"; import image4 from "../../assets/[email protected]"; import image5 from "../../assets/[email protected]"; import "./style.css"; import DashboardSelect from "../DashboardSelect/DashboardSelect"; const DashboardSidebar = () => { const options = [ { name: "Clayvant Inc", }, { name: "Business name 2", }, { name: "Business name 3", }, ]; return ( <div className="dashboardSidebar "> <div className="dashboardSidebar_head"> <DashboardSelect options={options} /> </div> <div className="dashboardSidebar_body"> <div className="dashboardSidebar_body_head"> <div className="dashboardSidebar_body_head_body"> <div className="dashboardSidebar_body_head_body_icon"> <img src={image1} alt="account" /> </div> <span className="dashboardSidebar_body_head_body_text"> Account </span> </div> <div className="dashboardSidebar_body_head_body"> <div className="dashboardSidebar_body_head_body_icon"> <img src={image2} alt="transfer" /> </div> <span className="dashboardSidebar_body_head_body_text"> Transfer </span> </div> <div className="dashboardSidebar_body_head_body"> <div className="dashboardSidebar_body_head_body_icon"> <img src={image3} alt="invoice" /> </div> <span className="dashboardSidebar_body_head_body_text"> Invoice </span> </div> <div className="dashboardSidebar_body_head_body"> <div className="dashboardSidebar_body_head_body_icon"> <img src={image4} alt="management" /> </div> <span className="dashboardSidebar_body_head_body_text"> Management </span> </div> <div className="dashboardSidebar_body_head_body"> <div className="dashboardSidebar_body_head_body_icon"> <img src={image4} alt="security" /> </div> <span className="dashboardSidebar_body_head_body_text"> Security </span> </div> <div className="dashboardSidebar_body_head_body"> <div className="dashboardSidebar_body_head_body_icon"> <img src={image4} alt="support" /> </div> <span className="dashboardSidebar_body_head_body_text"> Support </span> </div> </div> <div className="dashboardSidebar_body_body"> <img src={logo} alt="logo" /> </div> <div className="dashboardSidebar_userPicture"> <img src={image5} alt="user profile" /> </div> </div> </div> ); }; export default DashboardSidebar; <file_sep>import React from "react"; import { Link } from "react-router-dom"; import "./style.css"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faChevronLeft } from "@fortawesome/free-solid-svg-icons"; const Navbar = ({ back, signIn }) => { return ( <> <nav> <ul className="nav"> <li className={`nav_back ${back ? null : "disappear"}`}> <FontAwesomeIcon icon={faChevronLeft} className="icon" /> </li> <li className="nav_sign_in"> <span> Already a member?</span>{" "} <span className="nav_sign_in--danger"> {signIn ? ( <Link to="/">Sign Up</Link> ) : ( <Link to="/signin">Sign In</Link> )} </span> </li> </ul> </nav> </> ); }; export default Navbar;
cd41ea162684fde4b98ded2d6fb4e9505194681c
[ "JavaScript" ]
11
JavaScript
LordTricto/TestSite
070f0450f050c02c064f534e27d60152003594dd
80ff0d393785b6681f895d75254161ff46e22c49
refs/heads/master
<file_sep>from django.db import models from django.contrib.auth.models import User # Create your models here. class Location(models.Model): user = models.OneToOneField(User, primary_key=True) latitude = models.DecimalField(max_digits=13, decimal_places=10) longitude = models.DecimalField(max_digits=13, decimal_places=10)<file_sep>from django.conf.urls import url from . import views urlpatterns = [ # Examples: # url(r'^$', 'regtest.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^(?P<user_pk>[0-9]+)/$', views.profile, name='profile'), ] <file_sep>from django.shortcuts import get_object_or_404, render from django.contrib.auth.models import User # Create your views here. def profile(request, user_pk): u = get_object_or_404(User, pk=user_pk) return render(request, 'people/profile.html', { 'user': u })
65a46b7102cc878688d6f69fc47dbe835c6ccb7c
[ "Python" ]
3
Python
Yasserius/firstdjangoproject
856db0bb7b3d9a6788a88d5cfe294305f9a52aa4
9fadacf9e023b080a38d730c856488219b7c02d9
refs/heads/master
<file_sep><?php $portrait1 = array('name'=>'Victor', 'firstname'=>'Hugo', 'portrait'=>'http://upload.wikimedia.org/wikipedia/commons/5/5a/Bonnat_Hugo001z.jpg'); $portrait2 = array('name'=>'Jean', 'firstname'=>'de La Fontaine', 'portrait'=>'http://upload.wikimedia.org/wikipedia/commons/e/e1/La_Fontaine_par_Rigaud.jpg'); $portrait3 = array('name'=>'Pierre', 'firstname'=>'Corneille', 'portrait'=>'http://upload.wikimedia.org/wikipedia/commons/2/2a/Pierre_Corneille_2.jpg'); $portrait4 = array('name'=>'Jean', 'firstname'=>'Racine', 'portrait'=>'http://upload.wikimedia.org/wikipedia/commons/d/d5/Jean_racine.jpg'); showArrayValue($portrait1); showArrayValue($portrait2); showArrayValue($portrait3); showArrayValue($portrait4); ?> <!DOCTYPE html> <html lang="fr" dir="ltr"> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.css" integrity="<KEY>" crossorigin="anonymous" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous" /> <link href="https://fonts.googleapis.com/css?family=Handlee" rel="stylesheet"> <link rel="stylesheet" href="../assets/style.css"> <title>Exercice 3</title> </head> <body> <?php function showArrayValue($array){ ?> <p><?= $array['name'] . ' ' . $array['firstname']; ?></p> <img src="<?php echo $array['portrait'] ?>" /> <?php } ?> </body> </html>
0b94dbd9f8df28f95300f190f490e464899a26a9
[ "PHP" ]
1
PHP
RyanElr/Php-Part10
1f9f3b39c3e2ea50d3e69df555281f47daf4a4f1
c721b8119ccb7e8284fb3323ce69a7760a0a9913
refs/heads/master
<file_sep>import java.util.Random; import java.util.ArrayList; import java.util.List; import java.lang.StringBuilder; import java.io.*; import com.google.gson.Gson; import com.google.gson.JsonElement; public class Stock { public static void main(String[] args) { int count = 10; int maxCycles = 500; double[][] prices = new double[maxCycles][count]; List<Stock> stocks; Stock.Builder builder = new Stock.Builder(maxCycles); builder.priceRangeOf(25, 100) .hasAvailable(100) .volatilityRangeOf(-1, 1) .driftRangeOf(.01, .5); stocks = builder.buildMulti(count); for(int i = 0; i < stocks.size(); i++) { Stock curr = stocks.get(i); System.out.println(curr.id); Util.addArrayAsColumn(curr.getPriceHistory(), prices, i); } Util.writeMatrixToFile(prices, "stocks"); } private static final double timeStep = 0.01; private static final Random rand = new Random(); private static final Gson gson = new Gson(); public int numAvailable; public String id; public transient int maxCycles; private transient double[] priceHistory; private transient double startingPrice; private transient double volatility; private transient double drift; private Stock() {} public String getJSONRep(int tick) { JsonElement jsonElement = gson.toJsonTree(this); jsonElement.getAsJsonObject().addProperty("currentPrice", priceHistory[tick]); return gson.toJson(jsonElement).toString(); } public double[] getPriceHistory() { return priceHistory; } public void dumpToPriceHistoryToFile(String file) { try { FileWriter fstream = new FileWriter(file + id + ".stock"); BufferedWriter out = new BufferedWriter(fstream); for(int i = 0; i < maxCycles; i++) { out.write(Double.toString(priceHistory[i]) + "\n"); } out.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } private void fillPriceHistory() { // see here for math explaination: http://investexcel.net/geometric-brownian-motion-excel/ double delta, totalDrift, uncertainty; priceHistory[0] = startingPrice; for(int i = 1; i < maxCycles; i++) { totalDrift = (priceHistory[i - 1] * drift * timeStep); uncertainty = (priceHistory[i - 1] * volatility * rand.nextGaussian() * Math.sqrt(timeStep)); delta = totalDrift + uncertainty; priceHistory[i] = priceHistory[i - 1] + delta; if(priceHistory[i] == 0) { break; } } } public double getValue(int tick) { return (double) Math.round(priceHistory[tick] * 100) / 100; } public void decrementAvailable(int quantity) { if(quantity > numAvailable) { throw new IllegalArgumentException("Cannot decrement more stock than is availble."); } else { numAvailable -= quantity; } } public void incrementAvailable(int quantity) { numAvailable += quantity; } public String toString() { String ret = ""; ret += "Id: "+ id + " | "; ret += "Num Available: " + numAvailable; return ret; } public static class Builder { private final Stock stock; private double minDrift = .01, maxDrift = .5; private double minVol = -1, maxVol = 1; private double minPrice, maxPrice; public Builder(int maxCycles) { stock = new Stock(); stock.id = Util.genRandomId(); stock.maxCycles = maxCycles; stock.priceHistory = new double[maxCycles]; } public Builder hasAvailable(int numAvailable) { stock.numAvailable = numAvailable; return this; } public Builder atPrice(double price) { this.minPrice = price; this.maxPrice = price; return this; } public Builder priceRangeOf(double minPrice, double maxPrice) { this.minPrice = minPrice; this.maxPrice = maxPrice; return this; } public Builder withVolatility(double volatility) { this.minVol = volatility; this.maxVol = volatility; return this; } public Builder volatilityRangeOf(double minVol, double maxVol) { this.minVol = minVol; this.maxVol = maxVol; return this; } public Builder withDrift(double drift) { this.minDrift = drift; this.maxDrift = drift; return this; } public Builder driftRangeOf(double minDrift, double maxDrift) { this.minDrift = minDrift; this.maxDrift = maxDrift; return this; } public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("ID: " + stock.id); stringBuilder.append("\nMax Cycles: " + stock.maxCycles); stringBuilder.append("\nPrice Range: " + this.minPrice + " " + this.maxPrice); stringBuilder.append("\nVolatility Range: " + this.minVol + " " + this.maxVol); stringBuilder.append("\nDrift Range: " + this.minDrift + " " + this.maxDrift); return stringBuilder.toString(); } public Stock build() { if(!validate()) { return null; } else { genRandomParams(); stock.fillPriceHistory(); return stock; } } public List<Stock> buildMulti(int num) { List<Stock> stocks = new ArrayList<Stock>(); if(!validate()) { return null; } else { for(int i = 0; i < num; i++) { // copy params of the current builder over to a new one Builder temp = new Builder(stock.maxCycles); temp.hasAvailable(stock.numAvailable); temp.priceRangeOf(this.minPrice, this.maxPrice); temp.volatilityRangeOf(this.minVol, this.maxVol); temp.driftRangeOf(this.minDrift, this.maxDrift); temp.genRandomParams(); temp.stock.fillPriceHistory(); stocks.add(temp.stock); } return stocks; } } private void genRandomParams() { // drift if(this.minDrift == this.maxDrift) { stock.drift = maxDrift; } else { stock.drift = Util.randomDouble(minDrift, maxDrift); } // volatility if(this.minVol == this.maxVol) { stock.volatility = maxVol; } else { stock.volatility = Util.randomDouble(minVol, maxVol); } // starting price if(this.minPrice == this.maxPrice) { stock.startingPrice = maxPrice; } else { stock.startingPrice = Util.randomDouble(minPrice, maxPrice); } } private boolean validate() { if(stock.maxCycles < 0) { return false; } if(minDrift > maxDrift) { return false; } if(minVol > maxVol) { return false; } if(minPrice > maxPrice) { return false; } if(stock.numAvailable < 0) { return false; } return true; } } } <file_sep>StockTrader ========== This project is being created as a learning exercise in the fields of autonomous multi-agent systems and genetic learning algorithms. The general idea of the project is to run a simplified simulation of a stock market, which agents can then buy and sell stocks on. The project is currently very much a WIP and all components are likely to change greatly between now and completion. A high level roadmap can be formed by looking at the issues page for the repository. That being said, the current plan is to get the the main components completely finished before writing any AIs. Large tasks left to be completed include object serialization, scenario definitions, and documentation. Work is currently focused on integrating Gradle into the project. Build & Execution ================= To run the project, make sure that you have Gradle installed on your machine. Then, simply run `gradle build` at the root of the project to build the project. You may then use the `run.ps1` script to execute the project. Flags for said script are as follows. * `server`: Starts the server and an example human client. Each will open in a new window. * `console`: Only has a purpose when used along with the `server` flag. Adding this flag will also cause the console client to be started in a new window. It will automatically connect to the server. The console can be used to view debug information at run time and start/stop the simulation. More functionality will be added at a later date. Currently, the console sends output back already formatted, but this will soon change to a JSON format to allow for console customization. * `stock`: Runs code found in the main of `Stock.java`.<file_sep>import java.net.*; import java.io.*; import java.util.Scanner; public class ConsoleClient { public static void main(String[] args) { ConsoleClient console = new ConsoleClient(); try { console.connectToMarket(); console.start(); } catch(Exception e) {} } private final String consoleKey = "SECRET_KEY"; private Scanner console; private String prompt = "> "; private Socket consoleSocket; private DataOutputStream outStream; private DataInputStream inStream; private final String marketAddress = "127.0.0.1"; private int consolePort = 5655; public ConsoleClient() { console = new Scanner(System.in); } private void connectToMarket() throws IOException { System.out.println("Connecting to console socket..."); if(consoleSocket != null) { consoleSocket.close(); } consoleSocket = new Socket(marketAddress, consolePort); System.out.println("Succesfully connected to console socket at " + consoleSocket.getRemoteSocketAddress()); outStream = new DataOutputStream(consoleSocket.getOutputStream()); inStream = new DataInputStream(consoleSocket.getInputStream()); outStream.writeUTF(consoleKey); System.out.println(inStream.readUTF()); } private void start() throws IOException { System.out.print("> "); while(console.hasNextLine()) { String cmd = console.nextLine(); outStream.writeUTF(cmd); System.out.println(inStream.readUTF()); System.out.print("> "); } } } <file_sep>dependencies { compile group: 'com.google.code.gson', name: 'gson', version: '2.6.2' } jar { baseName = 'HumanClient' from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) } } manifest { attributes 'Main-Class': 'HumanClient' } } <file_sep>jar { baseName = 'ConsoleClient' from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) } } manifest { attributes 'Main-Class': 'ConsoleClient' } } <file_sep>dependencies { compile group: 'com.google.code.gson', name: 'gson', version: '2.6.2' } jar { baseName = 'StockTrader' from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) } } manifest { attributes 'Main-Class': 'StockTrader' } } task Stock(type: Jar) { baseName = 'Stock' from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) } } manifest { attributes 'Main-Class': 'Stock' } with jar } tasks.build.doLast() { tasks.Stock.execute() } <file_sep>import java.util.Map; import java.util.HashMap; public class ConsoleCommand { public String command; public String help; public CommandCallback callback; public ConsoleCommand(String command, String help, CommandCallback callback) { this.command = command; this.help = help; this.callback = callback; } public abstract static class CommandCallback { public Map<String, String> args = new HashMap<String, String>(); abstract public String onInvoke(); abstract public boolean matchesCommand(String candidiate); } }<file_sep>include ":server", ":console", ":client"
291fa20b227352883d9f639e005065bf243bc4af
[ "Markdown", "Java", "Gradle" ]
8
Java
rolledback/StockTrader
4c45b0aeeafe5bc7b182b3f6e77d9f4a825d0240
c3f21c7f61a37518ce06ef55e90b02779845ff0d
refs/heads/master
<repo_name>yansanz/project-maven-eclipse<file_sep>/src/main/java/fr/afpa/jeelibrary/model/Person.java package fr.afpa.jeelibrary.model; public class Person { private String lastName; private String fisrtName; private int id; public Person() {} public Person(int id, String lastName, String firstName) { this.lastName = lastName; this.fisrtName = firstName; this.id =id; } @Override public String toString() { return "Person [ " + lastName + " " + fisrtName + "]"; } public Person(String lastName, String firstName) { setLastName(lastName); setFisrtName(firstName); } public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFisrtName() { return this.fisrtName; } public void setFisrtName(String firstName) { this.fisrtName = firstName; } public int getId() { return id; } public void setId(int id) { this.id = id; } } <file_sep>/src/main/java/fr/afpa/jeelibrary/web/AppTablBord.java package fr.afpa.jeelibrary.web; import java.io.IOException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import fr.afpa.jeelibrary.dao.DaoImpl; import fr.afpa.jeelibrary.model.Author; import fr.afpa.jeelibrary.model.Book; import fr.afpa.jeelibrary.model.Catalog; import fr.afpa.jeelibrary.model.Copy; import fr.afpa.jeelibrary.model.Subscriber; import fr.afpa.jeelibrary.service.IService; import fr.afpa.jeelibrary.service.Service; public class AppTablBord extends HttpServlet { /** * */ private static final long serialVersionUID = 6374645171296130824L; /** * */ IService service; public void init() throws ServletException { DaoImpl dao = new DaoImpl(); service = new Service(dao); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String action = request.getPathInfo(); if (action == null || action.equals("/")) { TablBord(request, response); } else if (action.equals("/rechercheBook")) { rechercheBook(request, response); } else if (action.equals("/rechercheSub")) { rechercheSub(request, response); } else if (action.equals("/info")) { info(request, response); } else if (action.equals("/modif")) { modif(request, response); } else if (action.equals("/modifSub")) { modifSub(request, response); } else if (action.equals("/supr")) { supression(request, response); } else if (action.equals("/modifBook")) { modifBook(request, response); } else if (action.equals("/add")) { add(request, response); } else if (action.equals("/addBook")) { addBook(request, response); } else if (action.equals("/addSub")) { addSub(request, response); } else if (action.equals("/Librairie")) { librairie(request, response); } else if (action.equals("/Emprunt")) { emprunt(request, response); } else if (action.equals("/Retour")) { retour(request, response); } else if (action.equals("/RetourValid")) { retourValid(request, response); } else if (action.equals("/EmpruntValid")) { empruntValid(request, response); } else if (action.equals("/addCopy")) { addCopy(request, response); } else if (action.equals("/suprCopy")) { suprCopy(request, response); } else if (action.equals("/infoValid")) { infoValid(request, response); } else if (action.equals("/ReturnInfoCopy")) { ReturnInfoCopy(request, response); } else if (action.equals("/LibrairieA")) { LibrairieA(request, response); } else if (action.equals("/LibrairieG")) { LibrairieG(request, response); } else if (action.equals("/search")) { librairieS(request, response); } else if (action.equals("/searchTitle")) { TableTitle(request, response); } } /** * Looks up for books by title * * @param request * the request object * @param response * the response object * @throws IOException * @throws ServletException */ private void TableTitle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub String rechercheTitre = request.getParameter("valeur"); ArrayList<Book> bk = service.RechTitreExact(rechercheTitre); ObjectMapper oMapper = new ObjectMapper(); oMapper.enable(SerializationFeature.INDENT_OUTPUT); String retourJSon = oMapper.writeValueAsString(bk); System.out.println(retourJSon); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(retourJSon); } /** * * @param request * @param response * @throws IOException * @throws ServletException */ private void librairieS(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub String rechercheNom = request.getParameter("valeur"); ArrayList<Subscriber> sub = service.recherchNom(rechercheNom); ObjectMapper objectMapper = new ObjectMapper(); // Set pretty printing of json objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // 1. Convert List of Person objects to JSON String arrayJson = objectMapper.writeValueAsString(sub); // System.out.println("1. Convert List of Book objects to JSON :"); System.out.println(arrayJson); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(arrayJson); } private void LibrairieG(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub ArrayList<Subscriber> sub = new ArrayList<Subscriber>(); ArrayList<Book> livre = new ArrayList<Book>(); sub = service.getAllSub(); livre = service.RechTitreG(); request.setAttribute("emprunteur", sub); request.setAttribute("livre", livre); request.setAttribute("infoBul", "selectionner 1 emprunteur et 1 exemplaire pour l'emprunt "); getServletContext().getRequestDispatcher("/WEB-INF/views/Librairie.jsp").forward(request, response); } private void LibrairieA(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub ArrayList<Subscriber> sub = new ArrayList<Subscriber>(); ArrayList<Book> livre = new ArrayList<Book>(); sub = service.getAllSub(); livre = service.RechTitreA(); request.setAttribute("emprunteur", sub); request.setAttribute("livre", livre); request.setAttribute("infoBul", "selectionner 1 emprunteur et 1 exemplaire pour l'emprunt "); getServletContext().getRequestDispatcher("/WEB-INF/views/Librairie.jsp").forward(request, response); } /** * Allows returning of a copy. * @param request * the request object * @param response * the response object * @throws IOException * @throws ServletException */ private void ReturnInfoCopy(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (request.getParameter("txtCibl13").equals("")) { request.setAttribute("infoBul", "operation impossible"); } else { int idCopy = Integer.valueOf(request.getParameter("txtCibl13")).intValue(); Subscriber s = service.getSubExemplaire(idCopy); if (s == null) { request.setAttribute("infoBul", "Les infos abonné n'ont pu être récupérées."); } else { int idClient = s.getId(); service.Restitue(idCopy, idClient); // TODO code written by DMA //service.returnCopy(idCopy); } } TablBord(request, response); } /** * * @param request * @param response * @throws IOException * @throws ServletException */ private void infoValid(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (request.getParameter("txtCibl10").equals("") && request.getParameter("txtCibl11").equals("")) { request.setAttribute("infoBul", "operation impossible"); } else { int idCopy = Integer.valueOf(request.getParameter("txtCibl10")).intValue(); String isbn = request.getParameter("txtCibl11"); ArrayList<Copy> exemplaire = new ArrayList<Copy>(); exemplaire = service.getCopy(isbn); Subscriber s = service.getSubExemplaire(idCopy); request.setAttribute("isbnInfo", isbn); request.setAttribute("modeInf", isbn); if (s != null) { request.setAttribute("idSub", s.getId()); request.setAttribute("infoBul", s.getFisrtName() + " " + s.getLastName() + " a emprunté l'exemplaire N°" + idCopy); request.setAttribute("exemplaire", exemplaire); } else { request.setAttribute("infoBul", "R.A.S"); request.setAttribute("exemplaire", exemplaire); } } TablBord(request, response); } private void suprCopy(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (request.getParameter("txtCibl7").equals("")) { request.setAttribute("infoBul", "operation impossible"); } else { int idCopy = Integer.valueOf(request.getParameter("txtCibl7")).intValue(); if (service.dispoCopy(idCopy)) { service.modifCopy(idCopy); } else { request.setAttribute("infoBul", "exemplaire a restituer avant suppression"); } } TablBord(request, response); } private void addCopy(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub if (request.getParameter("txtCibl9").equals("")) { request.setAttribute("infoBul", "operation impossible"); } else { String isbn = request.getParameter("txtCibl9"); service.addCopy(isbn); } TablBord(request, response); } private void empruntValid(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub int idCopy = Integer.valueOf(request.getParameter("txtCibl7")).intValue(); int idClient = Integer.valueOf(request.getParameter("txtCibl8")).intValue(); String isbn = service.getIsbn(idCopy); if (service.getNbreEmprunt(idClient)) { service.Emprunte(isbn, idCopy, idClient); Subscriber s = service.getOneEmprunteur(idClient); request.setAttribute("infoBul", "Emprunt Ok : " + s.getLastName()); } else { request.setAttribute("infoBul", "nbre maxi emprunt deja atteint"); } TablBord(request, response); } private void retourValid(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { int idCopy = Integer.valueOf(request.getParameter("txtCibl5")).intValue(); int idClient = Integer.valueOf(request.getParameter("txtCibl6")).intValue(); service.Restitue(idCopy, idClient); Subscriber s = service.getOneEmprunteur(idClient); request.setAttribute("infoBul", "Retour Ok : " + s.getLastName()); TablBord(request, response); } private void retour(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { int id = Integer.valueOf(request.getParameter("txtCibl4")).intValue(); ArrayList<Copy> exemplaire = new ArrayList<Copy>(); Subscriber s = service.getOneEmprunteur(id); String lastName = s.getLastName(); String fisrtName = s.getFisrtName(); request.setAttribute("modeLib", id); request.setAttribute("id", id); request.setAttribute("infoBul", fisrtName + " " + lastName); exemplaire = service.getCopyByBorrower(id); request.setAttribute("exemplaire", exemplaire); getServletContext().getRequestDispatcher("/WEB-INF/views/Librairie.jsp").forward(request, response); } private void emprunt(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (request.getParameter("txtCibl2").equals("") || request.getParameter("txtCibl1").equals("")) { librairie(request, response); } else { int id = Integer.valueOf(request.getParameter("txtCibl2")).intValue(); String isbn = request.getParameter("txtCibl1"); ArrayList<Copy> exemplaire = service.getCopy(isbn); Subscriber s = service.getOneEmprunteur(id); System.out.println(s.getFisrtName() + "test app"); String lastName = s.getLastName(); String fisrtName = s.getFisrtName(); request.setAttribute("modeEmpr", id); request.setAttribute("id", id); request.setAttribute("infoBul", fisrtName + " " + lastName + " a deja: " + service.getNbreExactEmpruntparSub(id) + " emprunts en cours"); request.setAttribute("exemplaire", exemplaire); getServletContext().getRequestDispatcher("/WEB-INF/views/Librairie.jsp").forward(request, response); } } private void librairie(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ArrayList<Subscriber> sub = new ArrayList<Subscriber>(); ArrayList<Book> exemplaire = new ArrayList<Book>(); ArrayList<Book> livre = new ArrayList<Book>(); sub = service.getAllSub(); exemplaire = service.RechTitre(); for (int i = 0; i < exemplaire.size(); i++) { if (service.dispoLivre(exemplaire.get(i).getIsbn())) { Book b = service.RechIsbn(exemplaire.get(i).getIsbn()); livre.add(b); } } request.setAttribute("emprunteur", sub); request.setAttribute("livre", livre); request.setAttribute("infoBul", "selectionner 1 emprunteur et 1 exemplaire pour l'emprunt "); getServletContext().getRequestDispatcher("/WEB-INF/views/Librairie.jsp").forward(request, response); } private void addSub(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String nomProvisoire = request.getParameter("txtNom"); String nom = nomProvisoire.replaceFirst(".", (nomProvisoire.charAt(0) + "").toUpperCase()); String prenomProvisoire = request.getParameter("txtPrenom"); String prenom = prenomProvisoire.replaceFirst(".", (prenomProvisoire.charAt(0) + "").toUpperCase()); int id = 0; Subscriber s = new Subscriber(nom, prenom, id); service.ajouterEmprunteur(s); TablBord(request, response); } private void addBook(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub Author a = null; Book b = null; String isbn = request.getParameter("txtIsbn"); String titre = request.getParameter("txtTitre"); String ssTitre = request.getParameter("txtSsTitre"); int nbCopy = Integer.valueOf(request.getParameter("NbrCopy")).intValue(); String genre = request.getParameter("genre"); if (request.getParameter("auteur") != null) { if (request.getParameter("auteur").equals("") || request.getParameter("auteur").equals("Auteur")) { String nom = request.getParameter("namAut"); String prenom = request.getParameter("prenAut"); int age = Integer.valueOf(request.getParameter("agAut")).intValue(); a = new Author(nom, prenom, age); b = new Book(isbn, titre, ssTitre, a, genre, nbCopy); service.ajouterLivre(b); } } else { String chaine = request.getParameter("auteur"); String[] sousChaine = chaine.split(" "); String nomAuteur = sousChaine[1]; String prenomAuteur = sousChaine[0]; a = service.existOrNo(nomAuteur, prenomAuteur); b = new Book(isbn, titre, ssTitre, a, genre, nbCopy); service.ajouterLivreAuteurExistant(b); } TablBord(request, response); } private void add(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String isbn = request.getParameter("txtCibl7"); if (isbn.equals("book")) { ArrayList<Catalog> catalog = service.getCatalog(); ArrayList<Author> author = service.ListAuthor(); request.setAttribute("catalog", catalog); request.setAttribute("auteur", author); request.setAttribute("nbCopy", isbn); } else { request.setAttribute("modeSub", isbn); } getServletContext().getRequestDispatcher("/WEB-INF/views/tablBordUpgrade.jsp").forward(request, response); } private void modifBook(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Author a = null; String isbn = request.getParameter("txtIsbn"); String titre = request.getParameter("txtTitre"); String ssTitre = request.getParameter("txtSsTitre"); int nbCopy = Integer.valueOf(request.getParameter("txtNbrCopy")).intValue(); String genre = request.getParameter("genre"); if (request.getParameter("auteur") != null) { if (request.getParameter("auteur").equals("") || request.getParameter("auteur").equals("Auteur")) { String nom = request.getParameter("namAut"); String prenom = request.getParameter("prenAut"); int age = Integer.valueOf(request.getParameter("agAut")).intValue(); a = new Author(nom, prenom, age); } } else { String chaine = request.getParameter("auteur"); String[] sousChaine = chaine.split(" "); String nomAuteur = sousChaine[1]; String prenomAuteur = sousChaine[0]; a = service.existOrNo(nomAuteur, prenomAuteur); } Book b = new Book(isbn, titre, ssTitre, a, genre, nbCopy); service.modifierLivre(b); TablBord(request, response); } private void supression(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (request.getParameter("txtCibl5").equals("") && request.getParameter("txtCibl6").equals("")) { request.setAttribute("infoBul", "selectionner un livre ou un emprunteur"); } else { if (request.getParameter("txtCibl5").equals("")) { int id = Integer.valueOf(request.getParameter("txtCibl6")).intValue(); if (service.verifEmpruntAvanSuppression(id)) { service.supprimEmprunteur(id); } else { request.setAttribute("infoBul", "emprunt a restutuer avant"); } TablBord(request, response); } else { String isbn = request.getParameter("txtCibl5"); ArrayList<Copy> livre = new ArrayList<Copy>(); request.setAttribute("infoBul", "choisir exemplaire a supprimer "); livre = service.getCopy(isbn); request.setAttribute("exemplaire", livre); request.setAttribute("btnSuprCopy", "supprCopy"); } } TablBord(request, response); } private void modifSub(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub int id = Integer.valueOf(request.getParameter("txtId")).intValue(); String nomProvisoire = request.getParameter("txtNom"); String nom = nomProvisoire.replaceFirst(".", (nomProvisoire.charAt(0) + "").toUpperCase()); String prenomProvisoire = request.getParameter("txtPrenom"); String prenom = prenomProvisoire.replaceFirst(".", (prenomProvisoire.charAt(0) + "").toUpperCase()); Subscriber s = new Subscriber(prenom, nom, id); service.modifEmprunteur(s); TablBord(request, response); } private void modif(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub if (request.getParameter("txtCibl4").equals("") && request.getParameter("txtCibl3").equals("")) { request.setAttribute("infoBul", "selectionner un livre ou un emprunteur"); } else { if (!request.getParameter("txtCibl4").equals("")) { int id = Integer.valueOf(request.getParameter("txtCibl4")).intValue(); Subscriber s = service.getOneEmprunteur(id); System.out.println(s); String lastName = s.getLastName(); String fisrtName = s.getFisrtName(); request.setAttribute("id", id); request.setAttribute("lastName", lastName); request.setAttribute("fisrtName", fisrtName); } else { String isbn = request.getParameter("txtCibl3"); Book b = service.RechIsbn(isbn); String titre = b.getTitle(); String subTitre = b.getSubtitle(); int nbrCopy = b.getNbrCopy(); ArrayList<Catalog> catalog = service.getCatalog(); ArrayList<Author> author = service.ListAuthor(); Author auteur = b.getAuthor(); String genre = b.getGenre(); String namAut = auteur.getLastName(); String prenAut = auteur.getFisrtName(); int agAut = auteur.getDateOfBirth(); request.setAttribute("isbn", isbn); request.setAttribute("nbrCopy", nbrCopy); request.setAttribute("titre", titre); request.setAttribute("subTitre", subTitre); request.setAttribute("namAut", namAut); request.setAttribute("prenAut", prenAut); request.setAttribute("agAut", agAut); request.setAttribute("catalog", catalog); request.setAttribute("auteur", author); request.setAttribute("genre", genre); } getServletContext().getRequestDispatcher("/WEB-INF/views/tablBordUpgrade.jsp").forward(request, response); } TablBord(request, response); } private void info(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub String isbn = request.getParameter("txtCibl1"); ArrayList<Copy> livre = new ArrayList<Copy>(); if (isbn.equals("") && request.getParameter("txtCibl2").equals("")) { request.setAttribute("infoBul", "selectionner un livre ou un emprunteur"); } else { if (!isbn.equals("")) { request.setAttribute("modeInf", isbn); request.setAttribute("isbn", isbn); livre = service.getCopy(isbn); request.setAttribute("isbnInfo", isbn); } else { int id = Integer.valueOf(request.getParameter("txtCibl2")).intValue(); System.out.println("test sub2 " + id); livre = service.getCopyByBorrower(id); Subscriber s = service.getOneEmprunteur(id); request.setAttribute("modeInf", id); String lastName = s.getLastName(); String fisrtName = s.getFisrtName(); request.setAttribute("idSub", s.getId()); request.setAttribute("infoBul", fisrtName + " " + lastName + " a " + service.getNbreExactEmpruntparSub(id) + " emprunts en cours"); } request.setAttribute("exemplaire", livre); } TablBord(request, response); } private void rechercheSub(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub ArrayList<Subscriber> emprunteur = new ArrayList<Subscriber>(); String name = request.getParameter("txtNom"); if (name == null) { emprunteur = service.getAllSub(); } else { emprunteur = service.recherchNom(name); } request.setAttribute("emprunteur", emprunteur); TablBord(request, response); } private void rechercheBook(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub ArrayList<Book> livre = new ArrayList<Book>(); String name = request.getParameter("txtTitre"); String genre = request.getParameter("genre"); if (name != null) { if (!name.equals("")) { livre = service.RechTitreExact(name); request.setAttribute("livre", livre); } else if (request.getParameter("auteur") != null) { String chaine = request.getParameter("auteur"); String[] sousChaine = chaine.split(" "); String nomAuteur = sousChaine[1]; livre = service.RechAuthor(nomAuteur); request.setAttribute("livre", livre); } else if (!genre.equals("")) { livre = service.RechGenre(genre); request.setAttribute("livre", livre); } else { livre = service.RechTitre(); request.setAttribute("livre", livre); } } TablBord(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // on passe la main au get doGet(request, response); } private void TablBord(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // TODO Auto-generated method stub ArrayList<Author> auteur = new ArrayList<Author>(); ArrayList<Catalog> catalog = new ArrayList<Catalog>(); String contact = request.getParameter("contact"); String infLeg = request.getParameter("infLeg"); String condUtil = request.getParameter("condUtil"); if (contact != null) { request.setAttribute("contact", "<EMAIL>"); } if (infLeg != null) { request.setAttribute("infoLegal", "loi n° 2004-575 du 21 juin 2004 , Article 6"); } if (condUtil != null) { request.setAttribute("condUtil", "Document à but pedagogique - AFPA"); } auteur = service.ListAuthor(); catalog = service.getCatalog(); request.setAttribute("auteur", auteur); request.setAttribute("catalog", catalog); getServletContext().getRequestDispatcher("/WEB-INF/views/TablBord.jsp").forward(request, response); } } <file_sep>/src/main/java/fr/afpa/jeelibrary/dao/DaoImpl.java package fr.afpa.jeelibrary.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import fr.afpa.jeelibrary.model.Author; import fr.afpa.jeelibrary.model.Book; import fr.afpa.jeelibrary.model.Catalog; import fr.afpa.jeelibrary.model.Copy; import fr.afpa.jeelibrary.model.Subscriber; public class DaoImpl implements IDao { String url = "jdbc:mysql://localhost:3306/libraryeval"; String login = "root"; String password = "<PASSWORD>"; Connection connection = null; Statement statement = null; ResultSet result = null; private Statement statement2 = null; public DaoImpl() { init(); } private void init() { // TODO Auto-generated method stub try { // chargement du driver Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public int getIdPersonne() { int id = 0; try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String init = "select max(id_personne) as nbre from personne"; result = statement.executeQuery(init); while (result.next()) { String idTemp = result.getString("nbre"); id = Integer.valueOf(idTemp).intValue(); } return id; } catch (SQLException e) { e.printStackTrace(); } return id; } public void modifierLivre(Book b) { int idClient = 0; try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String init = "select _ecrit.id_personne from _ecrit where _ecrit.isbn ='" + b.getIsbn() + "';"; result = statement.executeQuery(init); while (result.next()) { idClient = result.getInt("id_personne"); } System.out.println("test requete " + idClient); String query1 = "update personne set nom = '" + b.getAuthor().getFisrtName() + "', prenom = '" + b.getAuthor().getLastName() + "' where personne.id_personne = '" + idClient + "';"; String query2 = "update _auteur set annee_naissance = '" + b.getAuthor().getDateOfBirth() + "'where _auteur.id_personne = '" + idClient + "';"; String query3 = "update _livre set isbn ='" + b.getIsbn() + "', titre_livre='" + b.getTitle() + "'," + " sous_titre='" + b.getSubtitle() + "', nbre_exemplaire = nbre_exemplaire +'" + b.getNbrCopy() + "', nom_collection ='" + b.getGenre() + "' where _livre.isbn = '" + b.getIsbn() + "';"; statement.executeUpdate(query1); statement.executeUpdate(query2); statement.executeUpdate(query3); } catch (SQLException e) { e.printStackTrace(); } finally { try { // liberer les reesources.. memoire statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public void ajouterLivre(Book b) { int id = 0; try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql id = getIdPersonne() + 1; String query2 = "insert into personne values ('" + id + "','" + b.getAuthor().getFisrtName() + "','" + b.getAuthor().getLastName() + "')"; String query3 = "insert into _auteur values('" + b.getAuthor().getDateOfBirth() + "','" + id + "')"; String query4 = "insert into _livre values('" + b.getIsbn() + "','" + b.getTitle() + "','" + b.getSubtitle() + "','" + b.getNbrCopy() + "','" + 1 + "','" + b.getGenre() + "')"; String query5 = "insert into _ecrit values('" + b.getIsbn() + "','" + id + "')"; statement.executeUpdate(query2); // statement.executeUpdate(query); statement.executeUpdate(query3); statement.executeUpdate(query4); statement.executeUpdate(query5); if (b.getNbrCopy() != 0) { int idCopy = getIdcopy() + 1; for (int i = 0; i < b.getNbrCopy(); i++) { idCopy++; String query6 = "insert into _exemplaire values('" + idCopy + "','" + 1 + "','" + "en stock" + "','" + b.getIsbn() + "')"; statement.executeUpdate(query6); } } } catch (SQLException e) { e.printStackTrace(); } finally { try { // liberer les reesources.. memoire statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public Subscriber getSubExemplaire(int numeroCopy) { Subscriber s = null; try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String init = "select _emprunte.id_personne,personne.nom, personne.prenom, _emprunte.id_exemplaire" + " from _emprunte,personne where _emprunte.id_personne = personne.id_personne and _emprunte.id_exemplaire ='" + numeroCopy + "';"; result = statement.executeQuery(init); while (result.next()) { int id = result.getInt("id_personne"); String nom = result.getString("nom"); String prenom = result.getString("prenom"); s = new Subscriber(nom, prenom, id); System.out.println(s.toString()); } return s; } catch (SQLException e) { e.printStackTrace(); } return s; } public Author existOrNo(String name, String surname) { Author a = null; try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String init = "select personne.id_personne, personne.nom , personne.prenom, _auteur.annee_naissance " + " from personne,_auteur where personne.id_personne = _auteur.id_personne and personne.nom = '" + name + "' and personne.prenom = '" + surname + "';"; result = statement.executeQuery(init); while (result.next()) { String nom = result.getString("nom"); String prenom = result.getString("prenom"); int idClient = result.getInt("id_personne"); int anneeNaissance = result.getInt("annee_naissance"); a = new Author(nom, prenom, anneeNaissance, idClient); } return a; } catch (SQLException e) { e.printStackTrace(); } return null; } public void ajouterLivreAuteurExistant(Book b) { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql System.out.println(b.getAuthor().getFisrtName() + " " + b.getAuthor().getIdAuteur()); String query4 = "insert into _livre values('" + b.getIsbn() + "','" + b.getTitle() + "','" + b.getSubtitle() + "','" + b.getNbrCopy() + "','" + 1 + "','" + b.getGenre() + "')"; String query5 = "insert into _ecrit values('" + b.getIsbn() + "','" + b.getAuthor().getIdAuteur() + "')"; // statement.executeUpdate(query); statement.executeUpdate(query4); statement.executeUpdate(query5); if (b.getNbrCopy() != 0) { int idCopy = getIdcopy() + 1; for (int i = 0; i < b.getNbrCopy(); i++) { idCopy++; String query6 = "insert into _exemplaire values('" + idCopy + "','" + 1 + "','" + "en stock" + "','" + b.getIsbn() + "')"; statement.executeUpdate(query6); } } } catch (SQLException e) { e.printStackTrace(); } finally { try { // liberer les reesources.. memoire statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public ArrayList<Book> RechTitreExact(String name) { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select _livre.ISBN , _livre.Titre_livre, _livre.Sous_titre,_livre.Nbre_exemplaire, _livre.nom_collection,personne.nom, personne.prenom, _auteur.Annee_naissance " + "from _auteur,_livre, _ecrit,personne where _auteur.id_personne = personne.id_personne and _ecrit.id_personne = personne.id_personne\r\n" + " and _livre.ISBN= _ecrit.ISBN and _livre.Titre_livre like '%" + name + "%';"; result = statement.executeQuery(query); ArrayList<Book> livre = new ArrayList<Book>(); while (result.next()) { String Isbn = result.getString("ISBN"); String Titre = result.getString("Titre_livre"); String sousTitre = result.getString("Sous_titre"); int nbrCopy = Integer.valueOf((String) result.getString("Nbre_exemplaire")).intValue(); Author Auteur = new Author(result.getString("nom"), result.getString("prenom"), Integer.parseInt(result.getString("Annee_naissance"))); String genre = result.getString("_livre.nom_collection"); Book b = new Book(Isbn, Titre, sousTitre, Auteur, genre, nbrCopy); livre.add(b); } statement.close(); connection.close(); return livre; } catch (SQLException e) { e.printStackTrace(); } return null; } public ArrayList<Book> RechTitre() { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select _livre.ISBN , _livre.Titre_livre, _livre.Sous_titre,_livre.Nbre_exemplaire, _livre.nom_collection,personne.nom, personne.prenom, _auteur.Annee_naissance " + "from _auteur,_livre, _ecrit,personne where _auteur.id_personne = personne.id_personne and _ecrit.id_personne = personne.id_personne\r\n" + " and _livre.ISBN= _ecrit.ISBN order by _livre.Titre_livre" ; result = statement.executeQuery(query); ArrayList<Book> livre = new ArrayList<Book>(); while (result.next()) { String Isbn = result.getString("ISBN"); String Titre = result.getString("Titre_livre"); String sousTitre = result.getString("Sous_titre"); int nbrCopy = Integer.valueOf((String) result.getString("Nbre_exemplaire")).intValue(); Author Auteur = new Author(result.getString("nom"), result.getString("prenom"), Integer.parseInt(result.getString("Annee_naissance"))); String genre = result.getString("_livre.nom_collection"); Book b = new Book(Isbn, Titre, sousTitre, Auteur, genre, nbrCopy); livre.add(b); } statement.close(); connection.close(); return livre; } catch (SQLException e) { e.printStackTrace(); } return null; } public ArrayList<Book> RechTitreA() { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select _livre.ISBN , _livre.Titre_livre, _livre.Sous_titre,_livre.Nbre_exemplaire, _livre.nom_collection,personne.nom, personne.prenom, _auteur.Annee_naissance " + "from _auteur,_livre, _ecrit,personne where _auteur.id_personne = personne.id_personne and _ecrit.id_personne = personne.id_personne\r\n" + " and _livre.ISBN= _ecrit.ISBN order by personne.nom" ; result = statement.executeQuery(query); ArrayList<Book> livre = new ArrayList<Book>(); while (result.next()) { String Isbn = result.getString("ISBN"); String Titre = result.getString("Titre_livre"); String sousTitre = result.getString("Sous_titre"); int nbrCopy = Integer.valueOf((String) result.getString("Nbre_exemplaire")).intValue(); Author Auteur = new Author(result.getString("nom"), result.getString("prenom"), Integer.parseInt(result.getString("Annee_naissance"))); String genre = result.getString("_livre.nom_collection"); Book b = new Book(Isbn, Titre, sousTitre, Auteur, genre, nbrCopy); livre.add(b); } statement.close(); connection.close(); return livre; } catch (SQLException e) { e.printStackTrace(); } return null; } public ArrayList<Book> RechTitreG() { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select _livre.ISBN , _livre.Titre_livre, _livre.Sous_titre,_livre.Nbre_exemplaire, _livre.nom_collection,personne.nom, personne.prenom, _auteur.Annee_naissance " + "from _auteur,_livre, _ecrit,personne where _auteur.id_personne = personne.id_personne and _ecrit.id_personne = personne.id_personne\r\n" + " and _livre.ISBN= _ecrit.ISBN order by _livre.nom_collection" ; result = statement.executeQuery(query); ArrayList<Book> livre = new ArrayList<Book>(); while (result.next()) { String Isbn = result.getString("ISBN"); String Titre = result.getString("Titre_livre"); String sousTitre = result.getString("Sous_titre"); int nbrCopy = Integer.valueOf((String) result.getString("Nbre_exemplaire")).intValue(); Author Auteur = new Author(result.getString("nom"), result.getString("prenom"), Integer.parseInt(result.getString("Annee_naissance"))); String genre = result.getString("_livre.nom_collection"); Book b = new Book(Isbn, Titre, sousTitre, Auteur, genre, nbrCopy); livre.add(b); } statement.close(); connection.close(); return livre; } catch (SQLException e) { e.printStackTrace(); } return null; } public Boolean dispoLivre(String ISBN) { try { boolean dispo = true; connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select count(disponible) as dispo from _exemplaire where disponible = 1 and ISBN = '" + ISBN + "';"; result = statement.executeQuery(query); while (result.next()) { if (result.getInt("dispo") >= 1) { dispo = true; } else { dispo = false; } } statement.close(); connection.close(); return dispo; } catch (SQLException e) { e.printStackTrace(); } return null; } public String getIsbn(int idCopy) { try { String Isbn = null; connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select ISBN from _exemplaire where Id_exemplaire = '" + idCopy + "';"; result = statement.executeQuery(query); while (result.next()) { Isbn = result.getString("ISBN"); } statement.close(); connection.close(); return Isbn; } catch (SQLException e) { e.printStackTrace(); } return null; } public Book RechIsbn(String ISBN) { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select _livre.ISBN , _livre.Titre_livre,_livre.Nbre_exemplaire, _livre.Sous_titre,_livre.nom_collection,personne.nom, personne.prenom, _auteur.Annee_naissance " + "from _auteur,_livre, _ecrit,personne where _auteur.id_personne = personne.id_personne and _ecrit.id_personne = personne.id_personne\r\n" + " and _livre.ISBN= _ecrit.ISBN and _livre.ISBN ='" + ISBN + "';"; result = statement.executeQuery(query); Book book = null; while (result.next()) { String Isbn = result.getString("ISBN"); String Titre = result.getString("Titre_livre"); String sousTitre = result.getString("Sous_titre"); int nbrCopy = Integer.valueOf((String) result.getString("Nbre_exemplaire")).intValue(); Author Auteur = new Author(result.getString("nom"), result.getString("prenom"), Integer.parseInt(result.getString("Annee_naissance"))); String genre = result.getString("_livre.nom_collection"); book = new Book(Isbn, Titre, sousTitre, Auteur, genre, nbrCopy); } System.out.println(book); statement.close(); connection.close(); return book; } catch (SQLException e) { e.printStackTrace(); } return null; } public ArrayList<Book> RechAuthor(String auteur) { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select _livre.ISBN , _livre.Titre_livre,_livre.Nbre_exemplaire, _livre.Sous_titre, _livre.nom_collection,personne.nom, personne.prenom, _auteur.Annee_naissance " + "from _auteur,_livre, _ecrit,personne where _auteur.id_personne = personne.id_personne and _ecrit.id_personne = personne.id_personne\r\n" + " and _livre.ISBN= _ecrit.ISBN and personne.nom = '" + auteur + "'order by _livre.Titre_livre;"; result = statement.executeQuery(query); ArrayList<Book> livre = new ArrayList<Book>(); System.out.println(livre); while (result.next()) { String Isbn = result.getString("ISBN"); String Titre = result.getString("Titre_livre"); int nbrCopy = Integer.valueOf((String) result.getString("Nbre_exemplaire")).intValue(); String sousTitre = result.getString("Sous_titre"); Author Auteur = new Author(result.getString("nom"), result.getString("prenom"), Integer.parseInt(result.getString("Annee_naissance"))); String genre = result.getString("_livre.nom_collection"); Book b = new Book(Isbn, Titre, sousTitre, Auteur, genre, nbrCopy); livre.add(b); } statement.close(); connection.close(); return livre; } catch (SQLException e) { e.printStackTrace(); } return null; } public ArrayList<Book> RechGenre(String genre) { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select _livre.ISBN , _livre.Titre_livre,_livre.Nbre_exemplaire, _livre.Sous_titre, _livre.nom_collection,personne.nom, personne.prenom, _auteur.Annee_naissance " + "from _auteur,_livre, _ecrit,personne where _auteur.id_personne = personne.id_personne and _ecrit.id_personne = personne.id_personne\r\n" + " and _livre.ISBN= _ecrit.ISBN and _livre.nom_collection = '" + genre + "'order by _livre.Titre_livre;"; result = statement.executeQuery(query); ArrayList<Book> livre = new ArrayList<Book>(); ArrayList<Book> books = new ArrayList<Book>(); Catalog c = new Catalog(books); System.out.println(livre); while (result.next()) { String Isbn = result.getString("ISBN"); String Titre = result.getString("Titre_livre"); String sousTitre = result.getString("Sous_titre"); int nbrCopy = Integer.valueOf((String) result.getString("Nbre_exemplaire")).intValue(); Author Auteur = new Author(result.getString("nom"), result.getString("prenom"), Integer.parseInt(result.getString("Annee_naissance"))); String genre1 = result.getString("_livre.nom_collection"); Book b = new Book(Isbn, Titre, sousTitre, Auteur, genre1, nbrCopy); c.setCatalogName(result.getString("nom_collection")); c.addBook(b); livre.add(b); } statement.close(); connection.close(); return (ArrayList<Book>) c.getBooks(); } catch (SQLException e) { e.printStackTrace(); } return null; } public ArrayList<Copy> getCopy(String ISBN) { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select _livre.ISBN ,_exemplaire.id_exemplaire,_exemplaire.disponible, _exemplaire.info_exemplaire, _livre.Titre_livre,_livre.Nbre_exemplaire, _livre.Sous_titre," + "_livre.nom_collection,personne.nom, personne.prenom, _auteur.Annee_naissance " + "from _auteur,_livre,_exemplaire, _ecrit,personne where _auteur.id_personne = personne.id_personne and _exemplaire.ISBN = _livre.ISBN and _ecrit.id_personne = personne.id_personne\r\n" + " and _livre.ISBN= _ecrit.ISBN and _livre.ISBN ='" + ISBN + "';"; result = statement.executeQuery(query); ArrayList<Copy> exemplaire = new ArrayList<Copy>(); while (result.next()) { String Isbn = result.getString("ISBN"); String Titre = result.getString("Titre_livre"); String sousTitre = result.getString("Sous_titre"); int dispo = result.getInt("disponible"); int NumCopy = Integer.valueOf((String) result.getString("id_exemplaire")).intValue(); Author Auteur = new Author(result.getString("nom"), result.getString("prenom"), Integer.parseInt(result.getString("Annee_naissance"))); Copy c = new Copy(Isbn, Titre, sousTitre, Auteur, NumCopy, dispo); exemplaire.add(c); } statement.close(); connection.close(); return exemplaire; } catch (SQLException e) { e.printStackTrace(); } return null; } public ArrayList<Copy> getAllCopy() { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select _livre.ISBN ,_exemplaire.id_exemplaire,_exemplaire.disponible, _exemplaire.info_exemplaire, _livre.Titre_livre,_livre.Nbre_exemplaire, _livre.Sous_titre," + "_livre.nom_collection,personne.nom, personne.prenom, _auteur.Annee_naissance " + "from _auteur,_livre,_exemplaire, _ecrit,personne where _auteur.id_personne = personne.id_personne and _exemplaire.ISBN = _livre.ISBN and _ecrit.id_personne = personne.id_personne\r\n" + " and _livre.ISBN= _ecrit.ISBN;"; result = statement.executeQuery(query); ArrayList<Copy> exemplaire = new ArrayList<Copy>(); while (result.next()) { String Isbn = result.getString("ISBN"); String Titre = result.getString("Titre_livre"); String sousTitre = result.getString("Sous_titre"); int dispo = result.getInt("disponible"); int NumCopy = Integer.valueOf((String) result.getString("id_exemplaire")).intValue(); Author Auteur = new Author(result.getString("nom"), result.getString("prenom"), Integer.parseInt(result.getString("Annee_naissance"))); Copy c = new Copy(Isbn, Titre, sousTitre, Auteur, NumCopy, dispo); exemplaire.add(c); } statement.close(); connection.close(); return exemplaire; } catch (SQLException e) { e.printStackTrace(); } return null; } public void modifCopy(int numeroCopy) { String ISBN = null; try { connection = DriverManager.getConnection(url, login, password); statement2 = connection.createStatement(); // correspond à la requete sql if (dispoCopy(numeroCopy) == true) { String init = "select ISBN from _exemplaire where id_exemplaire ='" + numeroCopy + "';"; result = statement2.executeQuery(init); while (result.next()) { ISBN = result.getString("ISBN"); } String query2 = "delete from _exemplaire where id_exemplaire = '" + numeroCopy + "';"; String query = "update _livre set _livre.Nbre_exemplaire = Nbre_exemplaire -1 where _livre.ISBN = '" + ISBN + "';"; statement2.executeUpdate(query2); statement2.executeUpdate(query); } } catch (SQLException e) { e.printStackTrace(); } finally { try { // liberer les reesources.. memoire statement2.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public Boolean dispoCopy(int idCopy) { try { boolean dispo = true; connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select Disponible from _exemplaire where Id_exemplaire = " + idCopy + ";"; result = statement.executeQuery(query); while (result.next()) { if (result.getInt("Disponible") == 1) { dispo = true; } else { dispo = false; } } System.out.println("traitement ok"); statement.close(); connection.close(); return dispo; } catch (SQLException e) { e.printStackTrace(); } return null; } public int getIdcopy() { int id = 0; try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String init = "select max(id_exemplaire) as nbre from _exemplaire"; result = statement.executeQuery(init); while (result.next()) { String idTemp = result.getString("nbre"); System.out.println(idTemp); id = Integer.valueOf(idTemp).intValue(); } return id; } catch (SQLException e) { e.printStackTrace(); } return id; } public ArrayList<Author> ListAuthor() { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String init = "select personne.nom ,_auteur.annee_naissance,personne.id_personne, personne.prenom from _auteur, personne where personne.id_personne = _auteur.id_personne"; result = statement.executeQuery(init); ArrayList<Author> list = new ArrayList<Author>(); while (result.next()) { String nom = result.getString("nom"); String prenom = result.getString("prenom"); int year = result.getInt("annee_naissance"); int id = result.getInt("id_personne"); Author a = new Author(nom, prenom, year, id); list.add(a); } return list; } catch (SQLException e) { e.printStackTrace(); } return null; } public ArrayList<Catalog> getCatalog() { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String init = "select nom_collection from _collection"; ArrayList<Catalog> catalog = new ArrayList<Catalog>(); result = statement.executeQuery(init); while (result.next()) { String nomCollection = result.getString("nom_collection"); Catalog c = new Catalog(nomCollection); catalog.add(c); } System.out.println(catalog); return catalog; } catch (SQLException e) { e.printStackTrace(); } return null; } public void addCopy(String ISBN) { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); int numCopy = getIdcopy() + 1; System.out.println("test dao" + numCopy + ISBN); // correspond à la requete sql String query2 = "insert into _exemplaire values ('" + numCopy + "','" + 1 + "','" + "en stock" + "','" + ISBN + "')"; String query = "update _livre set Nbre_exemplaire = Nbre_exemplaire +1 where _livre.ISBN = '" + ISBN + "';"; statement.executeUpdate(query2); statement.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); } finally { try { // liberer les reesources.. memoire statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public ArrayList<Subscriber> getAllSub() { // TODO Auto-generated method stub try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select personne.nom, personne.prenom , personne.id_personne, _emprunteur.nbre_emprunt_en_cours" + " from _emprunteur, personne where personne.id_personne = _emprunteur.id_personne order by personne.nom"; result = statement.executeQuery(query); ArrayList<Subscriber> emprunteur = new ArrayList<Subscriber>(); while (result.next()) { String nom = result.getString("nom"); String prenom = result.getString("prenom"); int id_personne = Integer.parseInt(result.getString("id_personne")); int nbrEmprunt = result.getInt("nbre_emprunt_en_cours"); Subscriber s = new Subscriber(nom, prenom, id_personne, nbrEmprunt); emprunteur.add(s); } statement.close(); connection.close(); return emprunteur; } catch (SQLException e) { e.printStackTrace(); } return null; } public ArrayList<Copy> getCopyByBorrower(int idClient) { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String init = "select _emprunte.id_personne, _emprunte.id_exemplaire, _exemplaire.isbn,_livre.titre_livre from _emprunte , _exemplaire , _livre where _emprunte.id_exemplaire = _exemplaire.id_exemplaire " + "and _exemplaire.isbn = _livre.isbn and _emprunte.id_personne ='" + idClient + "';"; result = statement.executeQuery(init); ArrayList<Copy> livre = new ArrayList<Copy>(); while (result.next()) { String Isbn = result.getString("ISBN"); String title = result.getString("Titre_livre"); int idCopy = result.getInt("id_exemplaire"); Copy c = new Copy(Isbn, title, idCopy); livre.add(c); } return livre; } catch (SQLException e) { e.printStackTrace(); } return null; } public ArrayList<Subscriber> recherchNom(String name) { // TODO Auto-generated method stub try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select personne.nom, personne.prenom , personne.id_personne, _emprunteur.nbre_emprunt_en_cours " + "from _emprunteur, personne where personne.id_personne = _emprunteur.id_personne and personne.nom like '%" + name + "%';"; result = statement.executeQuery(query); ArrayList<Subscriber> emprunteur = new ArrayList<Subscriber>(); System.out.println(emprunteur); while (result.next()) { String nom = result.getString("nom"); String prenom = result.getString("prenom"); int id_personne = Integer.parseInt(result.getString("id_personne")); int nbrEmprunt = result.getInt("nbre_emprunt_en_cours"); Subscriber s = new Subscriber(nom, prenom, id_personne, nbrEmprunt); emprunteur.add(s); } statement.close(); connection.close(); return emprunteur; } catch (SQLException e) { e.printStackTrace(); } return null; } public Boolean getNbreEmprunt(int idClient) { boolean statut = true; try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select Nbre_emprunt_en_cours from _emprunteur where Id_personne = " + idClient + ";"; result = statement.executeQuery(query); System.out.println(result); while (result.next()) { if (result.getInt("Nbre_emprunt_en_cours") >= 5) { statut = false; } else { statut = true; } } System.out.println("traitement ok"); statement.close(); connection.close(); return statut; } catch (SQLException e) { e.printStackTrace(); } return null; } public void supprimEmprunteur(int id) { try { connection = DriverManager.getConnection(url, login, password); statement2 = connection.createStatement(); System.out.println(id); // correspond à la requete sql if (verifEmpruntAvanSuppression(id)) { String query = "delete from _emprunteur where id_personne='" + id + "';"; String query2 = "delete from personne where id_personne='" + id + "';"; statement2.executeUpdate(query); statement2.executeUpdate(query2); } } catch (SQLException e) { e.printStackTrace(); } finally { try { // liberer les reesources.. memoire statement2.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public int getNbreExactEmpruntparSub(int id) { int nbExactEmprunt =0; try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); System.out.println(id); // correspond à la requete sql String query = "select nbre_emprunt_en_cours, id_personne from _emprunteur " + " where id_personne ='" + id + "';"; result = statement.executeQuery(query); while (result.next()) { nbExactEmprunt = result.getInt("nbre_emprunt_en_cours"); return nbExactEmprunt; } } catch (SQLException e) { e.printStackTrace(); } finally { try { // liberer les reesources.. memoire statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } return nbExactEmprunt; } public Subscriber getOneEmprunteur(int id) { Subscriber s = null; try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); System.out.println(id); // correspond à la requete sql String query = "select personne.id_personne, personne.nom, personne.prenom from _emprunteur,personne " + " where personne.id_personne =_emprunteur.id_personne and personne.id_personne='" + id + "';"; result = statement.executeQuery(query); while (result.next()) { id = result.getInt("id_personne"); String nom = result.getString("nom"); String prenom = result.getString("prenom"); s = new Subscriber(nom, prenom, id); return s; } return s; } catch (SQLException e) { e.printStackTrace(); } finally { try { // liberer les reesources.. memoire statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } return s; } public void Emprunte(String numeroIsbn, int numeroCopy, int idClient) { try { connection = DriverManager.getConnection(url, login, password); statement2 = connection.createStatement(); // correspond à la requete sql if (dispoCopy(numeroCopy) == true && getNbreEmprunt(idClient) == true) { String query = "insert into _emprunte values (" + idClient + "," + numeroCopy + ",'" + numeroIsbn + "')"; String query2 = "update _exemplaire set Disponible = 0 where id_exemplaire = " + numeroCopy + ";"; String query3 = "update _emprunteur set nbre_emprunt_en_cours = nbre_emprunt_en_cours + 1 where id_personne = " + idClient + ";"; statement2.executeUpdate(query); statement2.executeUpdate(query2); statement2.executeUpdate(query3); } // liberer les reesources.. memoire statement2.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } public void Restitue(int numeroCopy, int idClient) { try { connection = DriverManager.getConnection(url, login, password); statement2 = connection.createStatement(); // correspond à la requete sql String query = "delete from _emprunte where id_personne= '" + idClient + "' and id_exemplaire ='" + numeroCopy + "';"; String query2 = "update _exemplaire set Disponible = Disponible +1 where id_exemplaire = " + numeroCopy + ";"; String query3 = "update _emprunteur set nbre_emprunt_en_cours = nbre_emprunt_en_cours - 1 where id_personne = " + idClient + ";"; statement2.executeUpdate(query); statement2.executeUpdate(query2); statement2.executeUpdate(query3); statement2.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } public void modifEmprunteur(Subscriber s) { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query2 = "update personne set nom = '" + s.getFisrtName() + "', prenom= '" + s.getLastName() + "' where id_personne='" + s.getId() + "';"; statement.executeUpdate(query2); } catch (SQLException e) { e.printStackTrace(); } finally { try { // liberer les reesources.. memoire statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public Boolean verifEmpruntAvanSuppression(int idClient) { boolean statut = true; try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql String query = "select Nbre_emprunt_en_cours from _emprunteur where Id_personne = " + idClient + ";"; result = statement.executeQuery(query); System.out.println(result); while (result.next()) { if (result.getInt("Nbre_emprunt_en_cours") >= 1) { statut = false; } else { statut = true; } } System.out.println("traitement ok"); statement.close(); connection.close(); return statut; } catch (SQLException e) { e.printStackTrace(); } return null; } public void ajouterEmprunteur(Subscriber s) { try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); // correspond à la requete sql int id = getIdPersonne() + 1; String query = "insert into _emprunteur values ('" + 1 + "','" + 0 + "','" + id + "')"; String query2 = "insert into personne values ('" + id + "','" + s.getLastName() + "','" + s.getFisrtName() + "')"; statement.executeUpdate(query2); statement.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); } finally { try { // liberer les reesources.. memoire statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } <file_sep>/src/main/java/fr/afpa/jeelibrary/model/Author.java package fr.afpa.jeelibrary.model; public class Author extends Person { private int idPerson; private int dateOfBirth; //private Calendar dateOfBirth; public Author() {} public Author(String lastName, String firstName,int dateOfBirth) { super(lastName, firstName); this.dateOfBirth = dateOfBirth; } public Author(String lastName, String firstName,int dateOfBirth,int idPerson) { super(lastName, firstName); this.dateOfBirth = dateOfBirth; this.setIdAuteur(idPerson); } @Override public String toString() { String info = this.getFisrtName() + " " +this.getLastName(); return info; } public int getDateOfBirth() { return this.dateOfBirth; } public void setDateOfBirth(int dateOfBirth) { this.dateOfBirth = dateOfBirth; } public int getIdAuteur() { return idPerson; } public void setIdAuteur(int idPerson) { this.idPerson = idPerson; } } <file_sep>/src/main/webapp/js/tablBord.js document.getElementById('zonRech').style.visibility = "hidden"; document.getElementById('zonRechSub').style.visibility = "hidden"; // Get the modal var modal = document.getElementById('myModal'); // Get the button that opens the modal var btn = document.getElementById("myBtn"); // Get the <span> element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks the button, open the modal btn.onclick = function() { modal.style.display = "block"; } // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } var requete; //function AJAX envoie requete function rechercheDonnee(){ var donnees = document.getElementById("donnees"); var url = "search?valeur=" +escape(donnees.value); if (window.XMLHttpRequest){ requete = new XMLHttpRequest(); requete.open("GET",url,true); requete.onreadystatechange = majIHM; requete.send(null); }else if (window.ActiveXObject){ requete = new ActiveXObject("Microsoft.XMLHTTP"); if(requete){ requete.open("GET",url,true); requete.onreadystatechange = majIHM; requete.send(); } }else{ alert("le navigateur ne supporte pas cette techno") } } // function AJAX retour requete function majIHM(){ if (requete.readyState == 4) { if (requete.status == 200) { console.log(requete.responseText) var reponse = JSON.parse(requete.responseText); var select = document.getElementById('tableSub'); if (reponse.length !=0){ document.getElementById('iTable').style.visibility ='hidden'; select.innerHTML=""; for (var i = 0; i <reponse.length; i++){ var opt = document.createElement('tr'); var tdLastName = document.createElement('td'); var tdFirstName = document.createElement('td'); var tdEmprunt = document.createElement('td'); var tdRadioButton = document.createElement('td'); tdRadioButton.setAttribute('class','tdButton'); var radioInput = document.createElement('input'); radioInput.setAttribute('type','radio'); radioInput.setAttribute('name','choixSub'); radioInput.setAttribute('value',reponse[i].id); radioInput.setAttribute('onchange','getId('+reponse[i].id+');highLight(this)'); tdRadioButton.appendChild(radioInput); opt.appendChild(tdRadioButton); opt.appendChild(tdLastName); tdLastName.innerHTML = reponse[i].lastName; opt.appendChild(tdFirstName); tdFirstName.innerHTML = reponse[i].fisrtName; opt.appendChild(tdEmprunt); if (reponse[i].nbrEmprunt>0){ tdEmprunt.innerHTML = "emprunt en cours"; }else{ tdEmprunt.innerHTML = "pas d'emprunt"; } opt.value = reponse[i].id; select.appendChild(opt); } }else{ document.getElementById('iTable').style.visibility ='visible'; } } else { alert('Une erreur est survenue lors de la mise à jour de la page.'+ '\n\nCode retour = '+requete.statusText); } } } function choixAdd(n) { if (n == 1) { document.getElementById('txtCibl7').value = "sub"; } else { document.getElementById('txtCibl7').value = "book"; } document.add.submit(); } function rechAuteur() { var btnBoxAuteur = document.getElementById('boxA'); var txtBox = document.getElementById("boxA").value; boxG.value = ""; txtTitre.value = ""; } function rechAuteurTexUp() { document.getElementById('boxA').value = ""; } function popUpInfo2() { var popup = document.getElementById("myPopup2"); popup.classList.toggle("show"); } function rechAuteurUp() { document.getElementById('namAut').value = ""; document.getElementById('prenAut').value = ""; document.getElementById('agAut').value = ""; } function modeBook() { document.getElementById('zonRech').style.visibility = "visible"; document.getElementById('zonRechSub').style.visibility = "hidden"; } function modeSub() { document.getElementById('zonRech').style.visibility = "hidden"; document.getElementById('zonRechSub').style.visibility = "visible"; } //AJAX rechTitle var xhr_object = null; function rechTitre() { boxG.value = ""; boxA.value = ""; var donneesTitre = document.getElementById("txtTitre"); var urlT = "Acceuil/searchTitle?valeur=" +escape(donneesTitre.value); if (window.XMLHttpRequest) // Firefox { xhr_object = new XMLHttpRequest(); xhr_object.open("GET",urlT,true); xhr_object.onreadystatechange = majTitle; xhr_object.send(null); }else if (window.ActiveXObject) // Internet explorer { xhr_object = new ActiveXObject("Microsoft.XMLHTTP"); if(xhr_object){ xhr_object.open("GET",urlT,true); xhr_object.onreadystatechange = majIHMTitle; xhr_object.send(); } }else{ alert("le navigateur ne supporte pas cette techno") } } function majTitle(){ if (xhr_object.readyState == 4) { if (xhr_object.status == 200) { console.log(xhr_object.responseText); var reponse = JSON.parse(xhr_object.responseText); console.log(reponse); var tableBook = document.getElementById('bookTable'); if (reponse.length !=0){ document.getElementById('TableBook').style.visibility ='hidden'; tableBook.innerHTML=""; for (var i = 0; i < reponse.length; i++){ var rowT = document.createElement('tr'); var tdTitle = document.createElement('td'); var tdSubTitle = document.createElement('td'); var tdAuthor = document.createElement('td'); var tdGenre = document.createElement('td'); var tdRadioButton = document.createElement('td'); tdRadioButton.setAttribute('class','tdButton2'); var radioInput = document.createElement('input'); radioInput.setAttribute('type','radio'); radioInput.setAttribute('name','choixBook'); radioInput.setAttribute('value',reponse[i].isbn); radioInput.setAttribute('onchange','getIsbn('+reponse[i].isbn+');highLight2(this)'); tdRadioButton.appendChild(radioInput); rowT.appendChild(tdRadioButton); rowT.appendChild(tdTitle); tdTitle.innerHTML = reponse[i].title; rowT.appendChild(tdSubTitle); tdSubTitle.innerHTML = reponse[i].subtitle; rowT.appendChild(tdSubTitle); tdAuthor.innerHTML = reponse[i].author.lastName; rowT.appendChild(tdAuthor); tdGenre.innerHTML = reponse[i].genre; rowT.appendChild(tdGenre); rowT.value = reponse[i].isbn; tableBook.appendChild(rowT); } }else{ document.getElementById('iTableBook').style.visibility ='visible'; } } else { alert('Une erreur est survenue lors de la mise à jour de la page.'+ '\n\nCode retour = '+ xhr_object.statusText); } } } function highLight(e){ var x = document.getElementsByClassName("tdButton"); // reinitialise affichage for( var i=0; i<x.length;i++){ x[i].style.backgroundColor = "lightYellow"; } // Get parent of e var parent = e.parentNode; // Change css style of parent of e parent.style.backgroundColor = "lightBlue"; } function highLight2(f){ var x = document.getElementsByClassName("tdButton2"); // reinitialise affichage for( var i=0; i<x.length;i++){ x[i].style.backgroundColor = "lightYellow"; } // Get parent of f var parent = f.parentNode; // Change css style of parent of e parent.style.backgroundColor = "lightBlue"; } function rechGenre() { boxA.value = ""; txtTitre.value = ""; } function getIsbn(isbn) { document.getElementById('txtCibl1').value = isbn; document.getElementById('txtCibl3').value = isbn; document.getElementById('txtCibl5').value = isbn; } function getId(id) { document.getElementById('txtCibl2').value = id; document.getElementById('txtCibl4').value = id; document.getElementById('txtCibl6').value = id; } function getIdCopy(nb) { document.getElementById('txtCibl1').value = nb; document.getElementById('txtCibl5').value = nb; document.getElementById('txtCibl7').value = nb; document.getElementById('txtCibl10').value = nb; document.getElementById('txtCibl13').value = nb; }<file_sep>/src/main/java/fr/afpa/jeelibrary/model/Subscriber.java package fr.afpa.jeelibrary.model; import java.util.ArrayList; import java.util.List; // TODO Complete Subscriber class! public class Subscriber extends Person { private int id; private List<Copy> copies = new ArrayList<Copy>(); private int nbrEmprunt; public Subscriber() { super(); } /** * @param subscriptionNumber */ public Subscriber(String lastName, String firstName, int id) { super(lastName, firstName); this.setId(id); } public Subscriber(int id){ this.setId(id); } public Subscriber(String lastName, String firstName, int id, int nbrEmprunt) { super(lastName, firstName); this.setId(id); this.setNbrEmprunt(nbrEmprunt); } public void borrowCopy(Copy copy) { if (copies.size() == 5) System.out.println("Sorry! Maximum number of borrowing reached."); // Remark 1 : ArrayList accepts null values. Null values are counted in // the size of // the list just like non null elements. // Adding null values to a list is discouraged (unless specific needs). // Remark 2: a subscriber cannot borrow the same copy twice. else if (copy != null && !copies.contains(copy)) { copies.add(copy); copy.setSubscriber(this); copy.setAvailable(false); } } public boolean returnCopy(Copy copy) { if (copy.getSubscriber() != null) copy.setSubscriber(null); // TODO Should implement the method 'equals' in Copy to use the 'remove' // method efficiently. return copies.remove(copy); } public String toString() { String info = null; info = getFisrtName() + " " + getLastName() ; // The subscriber has borrowed at least one copy return info; } public List<Copy> getCopies() { return this.copies; } public void setCopies(List<Copy> value) { this.copies = value; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getNbrEmprunt() { return nbrEmprunt; } public void setNbrEmprunt(int nbrEmprunt) { this.nbrEmprunt = nbrEmprunt; } }
92a7adf7a7b31525c7d9ed0d2a3865ab7d87dcd3
[ "JavaScript", "Java" ]
6
Java
yansanz/project-maven-eclipse
e883e5aca0d03d15742df7f91fdcf9133b848744
fd5bb690ccdc8d8703e6d36c48e50c63a7c4cbb5
refs/heads/master
<repo_name>pasadinhas/so-project<file_sep>/tests/test_kos_single_threaded_put_get_remove_put_dump.c #include <kos_client.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define NUM_EL 100 #define NUM_SHARDS 10 #define KEY_SIZE 20 // #define DEBUG_PRINT_ENABLED 1 // uncomment to enable DEBUG statements #if DEBUG_PRINT_ENABLED #define DEBUG printf #else #define DEBUG(format, args...) ((void)0) #endif int lookup(char* key, char* value, KV_t* dump,int dim) { int i=0; for (;i<dim;i++) { if ( (!strncmp(key,dump[i].key,KEY_SIZE)) && (!strncmp(value,dump[i].value,KEY_SIZE) ) ) return 0; } return -1; } int main(int argc, const char* argv[] ) { char key[KEY_SIZE], value[KEY_SIZE], value2[KEY_SIZE]; char* v; int i,j,dim; int client_id=0; KV_t* dump; kos_init(1,1,NUM_SHARDS); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=NUM_EL-1; i>=0; i--) { sprintf(key, "k%d",i); sprintf(value, "val:%d",i); DEBUG("Element <%s,%s> being inserted in shard %d....\n", key, value, j); fflush(stdin); v=kos_put(client_id,j, key,value); if (v!=NULL) { printf("TEST FAILED - SHOULD RETURN NULL AND HAS RETURNED %s",v); exit(-1); } } } printf("------------------ ended inserting --------------------------------\n"); for (j=0; j<NUM_SHARDS; j++) { for (i=0; i<NUM_EL; i++) { sprintf(key, "k%d",i); sprintf(value, "val:%d",i); v=kos_get(client_id,j, key); if (v==NULL || strncmp(v,value,KEY_SIZE)!=0) { printf("TEST FAILED - Error on key %s, shard %d value should be %s and was returned %s",key,j,value,v); exit(-1); } } } printf("------------------- ended querying -------------------------------\n"); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=NUM_EL-1; i>=NUM_EL/2; i--) { sprintf(key, "k%d",i); sprintf(value, "val:%d",i); v=kos_remove(client_id, j, key); if (v==NULL || strncmp(v,value,KEY_SIZE)!=0) { printf("Error when removing key %s from shard %d value should be %s and was returned %s",key,j,value,(v==NULL?"NULL":v)); exit(1); } DEBUG("C:%d %s %s removed from shard %d. value =%s\n", client_id, key, ( v==NULL ? "has not been" : "has been" ),j, ( v==NULL ? "<missing>" : v ) ); } } printf("------------------ ended removing ------------------------\n"); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=NUM_EL-1; i>=NUM_EL/2; i--) { sprintf(key, "k%d",i); sprintf(value, "val:%d",i); sprintf(value2, "val:%d",i*10); DEBUG("Element <%s,%s> being inserted in shard %d....\n", key, value, j); fflush(stdin); v=kos_put(client_id,j, key,value2); if (i<NUM_EL/2) { if (v==NULL || strncmp(v,value,KEY_SIZE)!=0) { printf("TEST FAILED - Error on key %s, shard %d value should be %s and was returned %s",key,j,value,v); exit(-1); } } else { if (v!=NULL) { printf("TEST FAILED - Error on key %s, shard %d value should be NULL and was returned %s",key,j,v); exit(-1); } } } } printf("------------------ ended updating --------------------------------\n"); for (j=0; j<NUM_SHARDS; j++) { dump=kos_getAllKeys(client_id, j, &dim); if (dim!=NUM_EL) { printf("TEST FAILED - SHOULD RETURN %d ELEMS AND HAS RETURNED %d",NUM_EL,dim); exit(-1); } for (i=0; i<NUM_EL; i++) { sprintf(key, "k%d",i); sprintf(value, "val:%d",i); sprintf(value2, "val:%d",i*10); if (i<NUM_EL/2) { if (lookup(key,value,dump, dim)!=0) { printf("TEST FAILED - Error on <%s,%s>, shard %d - not returned in dump\n",key,value,j); exit(-1); } } else { if (lookup(key,value2,dump, dim)!=0) { printf("TEST FAILED - Error on <%s,%s>, shard %d - not returned in dump\n",key,value,j); exit(-1); } } } } printf("------------------- ended querying again ---------------------------\n"); printf("\n--> TEST PASSED <--\n"); return 0; } <file_sep>/tests/test_kos_multi_threaded_put_get_remove_get.c #include <kos_client.h> #include <pthread.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define NUM_EL 1000 #define NUM_SHARDS 10 #define NUM_CLIENT_THREADS 10 #define NUM_SERVER_THREADS 3 #define KEY_SIZE 20 // #define DEBUG_PRINT_ENABLED 1 // uncomment to enable DEBUG statements #if DEBUG_PRINT_ENABLED #define DEBUG printf #else #define DEBUG(format, args...) ((void)0) #endif void *client_thread(void *arg) { char key[KEY_SIZE], value[KEY_SIZE]; char* v; int i,j; int client_id=*( (int*)arg); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=NUM_EL; i>=0; i--) { sprintf(key, "k-c%d-%d",client_id,i); sprintf(value, "val:%d",i); v=kos_put(client_id, j, key,value); DEBUG("C:%d <%s,%s> inserted in shard %d. Prev Value=%s\n", client_id, key, value, j, ( v==NULL ? "<missing>" : v ) ); } } printf("------------------- %d:1/4 ENDED INSERTING -----------------------\n",client_id); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=0; i<NUM_EL; i++) { sprintf(key, "k-c%d-%d",client_id,i); sprintf(value, "val:%d",i); v=kos_get(client_id, j, key); if (strncmp(v,value,KEY_SIZE)!=0) { printf("Error on key %s value should be %s and was returned %s",key,value,v); exit(1); } DEBUG("C:%d %s %s found in shard %d: value=%s\n", client_id, key, ( v==NULL ? "has not been" : "has been" ),j, ( v==NULL ? "<missing>" : v ) ); } } printf("------------------ %d:2/4 ENDED READING ---------------------\n",client_id); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=NUM_EL-1; i>=NUM_EL/2; i--) { sprintf(key, "k-c%d-%d",client_id,i); sprintf(value, "val:%d",i); v=kos_remove(client_id, j, key); if (strncmp(v,value,KEY_SIZE)!=0) { printf("Error when removing key %s value should be %s and was returned %s",key,value,v); exit(1); } DEBUG("C:%d %s %s removed from shard %d. value =%s\n", client_id, key, ( v==NULL ? "has not been" : "has been" ),j, ( v==NULL ? "<missing>" : v ) ); } } printf("----------------- %d-3/4 ENDED REMOVING -------------------------\n",client_id); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=0; i<NUM_EL; i++) { sprintf(key, "k-c%d-%d",client_id,i); sprintf(value, "val:%d",i); v=kos_get(client_id, j, key); if (i>=NUM_EL/2 && v!=NULL) { printf("Error when gettin key %s value should be NULL and was returned %s",key,v); exit(1); } if (i<NUM_EL/2 && strncmp(v,value,KEY_SIZE)!=0 ) { printf("Error on key %s value should be %s and was returned %s",key,value,v); exit(1); } DEBUG("C:%d %s %s found in shard %d. value=%s\n", client_id, key, ( v==NULL ? "has not been" : "has been" ) ,j, ( v==NULL ? "<missing>" : v ) ); } } printf("----------------- %d-4/4 ENDED CHECKING AFTER REMOVE -----------------\n",client_id); return NULL; } int main(int argc, const char* argv[] ) { int i,s,ret; int* res; pthread_t* threads=(pthread_t*)malloc(sizeof(pthread_t)*NUM_CLIENT_THREADS); int* ids=(int*) malloc(sizeof(int)*NUM_CLIENT_THREADS); ret=kos_init(NUM_CLIENT_THREADS,NUM_SERVER_THREADS,NUM_SHARDS); //printf("KoS inited"); if (ret!=0) { printf("kos_init failed with code %d!\n",ret); return -1; } for (i=0; i<NUM_CLIENT_THREADS; i++) { ids[i]=i; if ( (s=pthread_create(&threads[i], NULL, &client_thread, &(ids[i])) ) ) { printf("pthread_create failed with code %d!\n",s); return -1; } } for (i=0; i<NUM_CLIENT_THREADS; i++) { s = pthread_join(threads[i], (void**) &res); if (s != 0) { printf("pthread_join failed with code %d",s); return -1; } } printf("\n--> TEST PASSED <--\n"); return 0; } <file_sep>/kos/kos_server.c #include <pthread.h> #include <semaphore.h> #include <stdlib.h> #include <stdio.h> #include "shard.h" #include "buffer.h" #include "kos_request.h" #include "delay.h" Shard** shards; Semaphores_t * semaphores; void** buffer; void *server_thread(void *arg) { int id = *((int *) arg); kos_request_t *request; while(1) { sem_wait(&(semaphores[id].client)); //printf(">>> Server Thread (#%d) running. \n", id); request = (kos_request_t *) bufferGetPosition(id); //delay(); if(request) { //pthread_mutex_lock(&(shards[request->shardID]->mutex)); switch(request->action) { case GET: bufferPutPosition(id, (void *) ShardSearch(shards[request->shardID], request->key)); break; case PUT: bufferPutPosition(id, (void *) ShardInsert(shards[request->shardID], request->key, request->value)); break; case REMOVE: bufferPutPosition(id, (void *) ShardDelete(shards[request->shardID], request->key)); break; case GETALL: bufferPutPosition(id, (void *) ShardGetAll(shards[request->shardID], request->dim_ptr)); break; default: bufferPutPosition(id, NULL); break; } //pthread_mutex_unlock(&(shards[request->shardID]->mutex)); } else bufferPutPosition(id, NULL); sem_post(&(semaphores[id].server)); } } int newServerThreadsArray(int n) { pthread_t * server_threads; int * ids = (int *) malloc(sizeof(int) * n); int i, s; server_threads = malloc(sizeof(pthread_t) * n); if (!server_threads) return -1; for (i = 0; i < n; i++) { ids[i] = i; s = pthread_create(&server_threads[i], NULL, &server_thread, &(ids[i])); if (s) { printf("Server pthread_create failed with code %d!\n",s); return -1; } } return 0; } <file_sep>/kos/files.c #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include "files.h" #include "shard.h" typedef struct intList { int value; struct intList* next; } IntegerList; IntegerList* newIntegerListNode(int value, IntegerList* next) { IntegerList* newNode = (IntegerList *) malloc(sizeof(IntegerList)); newNode->value = value; newNode->next = next; return newNode; } IntegerList* popIntegerListValue(IntegerList* head, int* value) { IntegerList* newHead = head->next; *value = head->value; //free(head); return newHead; } // Global Variables to this file int* fileSize; pthread_mutex_t* fileLocks; pthread_mutex_t* freeIDsLocks; IntegerList** freeIDs; // This is done assuming the shards start at 0 and end ate nShards - 1 int initFiles(int nShards) { int i; fileSize = (int*) malloc(sizeof(int) * nShards); freeIDs = (IntegerList**) malloc(sizeof(IntegerList*) * nShards); fileLocks = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t) * nShards); freeIDsLocks = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t) * nShards); if (fileSize == NULL || freeIDs == NULL || fileLocks == NULL) return -1; for (i = 0; i < nShards; i++) { freeIDs[i] = NULL; fileSize[i] = fileInit(i); } return 0; } /* PASADINHAS FUNCTION */ int fileCalculateOffset(int KVID) { return KVID * 2 * KV_SIZE + sizeof(int); } /* Used to get the next KVID */ int fileIncrementSize(int fd, int shardID) { fileSize[shardID]++; lseek(fd, 0, SEEK_SET); write(fd, &(fileSize[shardID]), sizeof(int)); // example: if file size was 0 (no KVs in the file) we increment the file size to 1 and return the index 0 (which is empty) return fileSize[shardID] - 1; } int fileDecrementSize(int fd, int shardID) { fileSize[shardID]--; lseek(fd, 0, SEEK_SET); write(fd, &(fileSize[shardID]), sizeof(int)); // example: if file size was 0 (no KVs in the file) we increment the file size to 1 and return the index 0 (which is empty) return fileSize[shardID]; } /* Used in ShardInsert if key already exists */ int fileUpdateValue(int shardID, int KVID, char* value) { int fd, i; char fileName[FILE_NAME_SIZE]; char cleanValue[KV_SIZE]; // open file sprintf(fileName, "f%d", shardID); fd = open(fileName, O_RDWR, S_IRUSR | S_IWUSR); if(fd < 0) return -1; // create string to write for (i = 0; i < KV_SIZE; i++) cleanValue[i] = '\0'; sprintf(cleanValue, "%s", value); // position offset and write lseek(fd, fileCalculateOffset(KVID) + KV_SIZE, SEEK_SET); write(fd, cleanValue, KV_SIZE); close(fd); return 0; } /* Used in ShardInsert if key was not found in KOS */ int fileWriteKV(int shardID, int KVID, char* key, char* value) { int fd, i; char fileName[FILE_NAME_SIZE]; char cleanValue[KV_SIZE], cleanKey[KV_SIZE]; // open file sprintf(fileName, "f%d", shardID); fd = open(fileName, O_RDWR, S_IRUSR | S_IWUSR); if(fd < 0) return -1; // create strings to write for (i = 0; i < KV_SIZE; i++) { cleanValue[i] = '\0'; cleanKey[i] = '\0'; } sprintf(cleanValue, "%s", value); sprintf(cleanKey, "%s", key); // position offset and write lseek(fd, fileCalculateOffset(KVID), SEEK_SET); write(fd, cleanKey, KV_SIZE); write(fd, cleanValue, KV_SIZE); close(fd); return 0; } /* Returns file size */ int fileGetSize(int fd) { int size; lseek(fd, 0, SEEK_SET); read(fd, &size, sizeof(int)); return size; } /* Used in ShardDelete */ // Isn't the push to the freeIDs missing? int fileDeleteKV(int shardID, int KVID) { int fd, i; char fileName[FILE_NAME_SIZE]; char cleanString[KV_SIZE * 2]; // open file sprintf(fileName, "f%d", shardID); fd = open(fileName, O_RDWR, S_IRUSR | S_IWUSR); if(fd < 0) return -1; // create string to write for (i = 0; i < KV_SIZE * 2; i++) cleanString[i] = '\0'; // position offset and write lseek(fd, fileCalculateOffset(KVID), SEEK_SET); write(fd, cleanString, KV_SIZE * 2); close(fd); pthread_mutex_lock(&(freeIDsLocks[shardID])); freeIDs[shardID] = newIntegerListNode(KVID, freeIDs[shardID]); pthread_mutex_unlock(&(freeIDsLocks[shardID])); //printf("»»» New free spot <%d> in Shard %d\n", KVID, shardID); return 0; } /* Returns file size if file exists, returns 0 and creates file is file doesnt exist */ int fileInit(int shardID) { int fd, i; char fileName[FILE_NAME_SIZE]; char key[KV_SIZE], value[KV_SIZE]; // open file sprintf(fileName, "f%d", shardID); fd = open(fileName, O_RDWR, S_IRUSR | S_IWUSR); if (fd < 0) { // file doesn't exist - creating new one. fd = open(fileName, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); if (fd < 0) return -1; lseek(fd, 0, SEEK_SET); write(fd, 0, sizeof(int)); close(fd); return 0; } else { fileSize[shardID] = fileGetSize(fd); lseek(fd, fileCalculateOffset(0), SEEK_SET); for (i = 0; i < fileSize[shardID]; i++) { read(fd, key, KV_SIZE); read(fd, value, KV_SIZE); if (key[0] == '\0') { do { lseek(fd, fileCalculateOffset(fileDecrementSize(fd, shardID)), SEEK_SET); read(fd, key, KV_SIZE); read(fd, value, KV_SIZE); } while(key[0] == '\0' && fileSize[shardID] > (i + 1)); lseek(fd, fileCalculateOffset(i), SEEK_SET); write(fd, key, KV_SIZE); write(fd, value, KV_SIZE); } ShardInsertFromFile(shards[shardID], key, value, i); } ftruncate(fd, (off_t) (sizeof(int) + fileSize[shardID] * 2 * KV_SIZE * sizeof(char))); close(fd); return 0; } } int fileNextKVID(int shardID) { int aux, fd; char fileName[FILE_NAME_SIZE]; // open file sprintf(fileName, "f%d", shardID); fd = open(fileName, O_RDWR, S_IRUSR | S_IWUSR); if(fd < 0) return -1; // update value pthread_mutex_lock(&(freeIDsLocks[shardID])); if(freeIDs[shardID] != NULL) { freeIDs[shardID] = popIntegerListValue(freeIDs[shardID], &aux); pthread_mutex_unlock(&(freeIDsLocks[shardID])); //printf(">>> Insert (Shard %d) - free spot at <%d>\n", shardID, aux); } else { pthread_mutex_unlock(&(freeIDsLocks[shardID])); pthread_mutex_lock(&(fileLocks[shardID])); aux = fileIncrementSize(fd, shardID); pthread_mutex_unlock(&(fileLocks[shardID])); //printf(">>> WRITE at Shard #%d - Too bad, no free spot :c writing at <%d> and file size is now <%d>\n", shardID, aux, fileSize[shardID]); } // close file close(fd); return aux; }<file_sep>/kos/kos_request.c #include <stdlib.h> #include "kos_request.h" /* Generic new kos_request_t */ kos_request_t * newKosRequest(kos_request_action_t action, int shardID, char *key, char *value, int *size) { kos_request_t *request = (kos_request_t *) malloc(sizeof(kos_request_t)); request->action = action; request->shardID = shardID; request->key = key; request->value = value; request->dim_ptr = size; return request; } kos_request_t * newKosRequestGET(int shardID, char *key) { return newKosRequest(GET, shardID, key, NULL, NULL); } kos_request_t * newKosRequestPUT(int shardID, char *key, char *value) { return newKosRequest(PUT, shardID, key, value, NULL); } kos_request_t * newKosRequestREMOVE(int shardID, char *key) { return newKosRequest(REMOVE, shardID, key, NULL, NULL); } kos_request_t * newKosRequestGETALL(int shardID, int *dim) { return newKosRequest(GETALL, shardID, NULL, NULL, dim); } <file_sep>/tests/doAllTests.sh #!/bin/bash TESTS="test_kos_multi_threaded_all_getAll_fromFile test_kos_single_threaded_put_get test_kos_single_threaded_put_remove_get test_kos_single_threaded_put_get_put_get test_kos_single_threaded_put_get_remove_put_get test_kos_single_threaded_put_dump test_kos_single_threaded_put_get_remove_put_dump test_kos_multi_threaded_put_get test_kos_multi_threaded_put_get_remove_get test_kos_multi_threaded_all test_kos_multi_threaded_all_getAll test_kos_multi_threaded_all_shared" cd .. make clean >/dev/null make >/dev/null cd tests c=0 for i in $TESTS do (( c++ )) echo ######################################################### echo Executing test $c: $i echo ######################################################### rm f* time ./${i} echo --------------------------------------------------------- echo press a key to continue read a done <file_sep>/include/kos_server.h #ifndef __KOS_SERVER_H__ #define __KOS_SERVER_H__ int newServerThreadsArray(int n); #endif <file_sep>/kos/delay.c #include <delay.h> #include <unistd.h> #define DELAY 0 #define DELAY_TIME 1 void delay() { #ifdef DELAY sleep(DELAY_TIME); #endif } <file_sep>/Makefile SUBDIRS = kos tests # # Dados sobre o grupo e turno frequentado # CAMPUS = preencher com A ou T consoante Alameda ou Tagus # CURSO = indicar o curso do turno frequentado: LEIC ou LERC # GRUPO = indicar o numero do grupo # ALUNO1/ALUNO2/ALUNO3 = indicar os numeros dos alunos # CAMPUS=A CURSO=LEIC GRUPO=28 ALUNO1=75714 ALUNO2=76012 ALUNO3=75522 CFLAGS = -g -O0 -Wall -pthread export DEFS export CFLAGS all: build build: @list='$(SUBDIRS)'; for p in $$list; do \ echo "Building $$p"; \ $(MAKE) -C $$p; \ done clean: @list='$(SUBDIRS)'; for p in $$list; do \ echo "Cleaning $$p"; \ $(MAKE) clean -C $$p; \ done package: clean zip zip: ifndef CAMPUS @echo "ERROR: Must setup macro 'CAMPUS' correcly." else ifndef CURSO @echo "ERROR: Must setup macro 'CURSO' correcly." else ifndef GRUPO @echo "ERROR: Must setup macro 'GRUPO' correcly." else tar -czf project-$(CAMPUS)-$(CURSO)-$(GRUPO)-$(ALUNO1)-$(ALUNO2)-$(ALUNO3).tgz * endif endif endif <file_sep>/include/delay.h #ifndef DELAY_H #define DELAY_H 1 /* This function *MUST* be invoked before processing each client request. It injects artificial delays (simulating for instance interactions with some remote server) and allows stressing the synchronization mechanisms. */ void delay(); #endif <file_sep>/kos/buffer.c #include <stdlib.h> #include <pthread.h> #include "buffer.h" int bufferCompleteInit(int size) { if(initBufferArray(size) != 0) return -1; if(initSemaphoresArray(size) != 0) return -1; if(initAccessBufferSem(size) != 0) return -1; if(stackInit(size) != 0) return -1; return 0; } /** * Buffer implementation */ void ** buffer; int initBufferArray(int size) { buffer = (void **) malloc(sizeof(void *) * size); if(!buffer) return -1; return 0; } void *bufferGetPosition(int i) { return buffer[i]; } void bufferPutPosition(int i, void *ptr) { buffer[i] = ptr; } /** * Semaphores to sync clients and servers implementation */ Semaphores_t * semaphores; int initSemaphoresArray(int n) { int i; semaphores = (Semaphores_t *) malloc(sizeof(Semaphores_t) * n); if (!semaphores) return -1; for (i = 0; i < n; i++) { sem_init(&(semaphores[i].client), 0, 0); sem_init(&(semaphores[i].server), 0, 0); } return 0; } /** * Access Buffer Semaphore implementation */ sem_t accessBufferSem; int initAccessBufferSem(int n) { return sem_init(&accessBufferSem, 0, n); } /** * Stack implementation */ pthread_mutex_t stackMutex; int* stack; static int stackIndex; int stackInit(int n) { int i; stackIndex = 0; if (!(stack = (int *) malloc(sizeof(int) * n))) return -1; for (i=0; i<n; i++) stackPush(i); return 0; } int stackPop() { int aux; pthread_mutex_lock(&stackMutex); //printf(">>> DEBUG\n StackPop ~> aux = stack[stackIndex] = stack[%d] = %d \n" , stackIndex, stack[stackIndex]); aux = stack[--stackIndex]; //printf(">>> Stack Pop: index is now %d and stack returned %d \n", stackIndex, aux); //printf("WAITING ... zzzzzzzzzzzZZZZZZZZZZZZZZZZZZZZZzzzzzzzzzzZZZZZZZZZZZZZZZZZZZ\n"); //getchar(); pthread_mutex_unlock(&stackMutex); return aux; } void stackPush(int i) { pthread_mutex_lock(&stackMutex); stack[stackIndex++] = i; //printf(">>> Stack Push: index is now %d and inserted stack[%d] = %d \n", stackIndex, stackIndex -1, i); //printf("WAITING ... zzzzzzzzzzzZZZZZZZZZZZZZZZZZZZZZzzzzzzzzzzZZZZZZZZZZZZZZZZZZZ\n"); //getchar(); pthread_mutex_unlock(&stackMutex); //printf(">>> DEBUG\n STACK ~> Inserting ticket %d in stack\n", i); } /** * Buffer tickets system */ int bufferGetTicket() { //printf(">>> Getting ticket. Stack Index = %d", stackIndex); sem_wait(&accessBufferSem); return stackPop(); } void bufferPostTicket(int ticket) { //printf(">>> Getting ticket. Stack Index = %d", stackIndex); stackPush(ticket); sem_post(&accessBufferSem); } <file_sep>/include/kos_client.h #ifndef KOS_H #define KOS_H 1 #define KV_SIZE 20 typedef struct KV_t { char key[KV_SIZE]; char value[KV_SIZE]; } KV_t; /* Functions exposed by the KOS system to the Clients */ /* Used to initialize the server side of the application. It takes as input parameter the number of threads to be concurrently activated on the server side, the size of the internal buffer used to enqueue user client requests, and the number of existing shards. This function returns: * 0, if the initialization was successful; * -1 if the initialization failed; */ int kos_init(int num_server_threads, int buf_size, int num_shards); /*NOTE: All the operations specified below takes, among others, the following parameters: - the clientid: which is meant to be used to allow mapping the client to a specific server thread (needed by the first part of the project). - the shardId: which identifies the shard in which the key should be removed. In case an invalid clientId/shardId is passed as input parameter, all functions should return NULL. - The keys maintained by KOS must be not NULL, but the values (of key/value pairs) can be NULL. */ /* returns NULL if key is not present. Otherwise, it returns the value associated with the key passed as input. */ char* kos_get(int clientid, int shardId, char* key); /* insert the <key, value> pair passed as input parameter in KOS,returning: NULL, if the key was not previously present in KOS; the previous value associated with the key, otherwise. */ char* kos_put(int clientid, int shardId, char* key, char* value); /* Removes the <key, value> pair passed as input parameter in KOS, returning: NULL, if the key was not present in KOS; the value associated with the key whose removal was requested, if the key was previously present in KOS. */ char* kos_remove(int clientid, int shardId, char* key); /* returns an array of KV_t containing all the key value pairs stored in the specified shard of KOS (NULL in case the shard is empty). It stores in dim the number of key/value pairs present in the specified shard. If the clientId or shardId are invalid (e.g. too large with respect to the value specified upon inizialitization of KOS), this function assigns -1 to the "dim" parameter. */ KV_t* kos_getAllKeys(int clientid, int shardId, int* dim); #endif <file_sep>/include/shard.h #ifndef __SHARD_H__ #define __SHARD_H__ #include <pthread.h> #include <semaphore.h> #include "kos_client.h" #define HT_SIZE 10 #define FALSE 0 #define TRUE 1 /** ***************** * Data Structures ** ****************/ typedef struct node { KV_t* item; int KVID; struct node *next; } * List; typedef struct syncedList { List list; pthread_mutex_t mutex; sem_t readers, writers; int waitingReaders, waitingWriters, writing, nReaders; } SynchronizedList; typedef struct shard { pthread_mutex_t fileMutex; SynchronizedList** hashTable; int nElems; int shardID; } Shard; /** ***************** * Functions ** ****************/ /* Hashtable */ int hash(char* key); SynchronizedList** newHashTable(int hashSize); /* List */ KV_t* NewKV(char* key, char* value); List NewListNode(KV_t* item); List insertList(List head, int shardID, KV_t* item, char** result, int* KVID); KV_t* searchList(List head, char* key); List removeItemList(List head, char* key, char** result, int* KVID); /* SynchronizedList */ SynchronizedList *newSynchronizedList(); void beginReading(SynchronizedList *sl); void endReading(SynchronizedList *sl); void beginWriting(SynchronizedList *sl); void endWriting(SynchronizedList *sl); /* Shard */ extern Shard** shards; int newShardArray(int n, int hashSize); Shard* newShard(int hashSize, int shardID); char* ShardSearch(Shard* shard, char* key); char* ShardInsert(Shard* shard, char* key, char* value); char* ShardDelete(Shard* shard, char* key); KV_t* ShardGetAll(Shard* shard, int* n); void ShardInsertFromFile(Shard* shard, char* key, char* value, int KVID); #endif <file_sep>/kos/shard.c #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include "kos_client.h" #include "shard.h" #include "buffer.h" #include "files.h" #include "delay.h" /** ***************** * HashTable Functions ** ****************/ int hash(char* key) { int i = 0; if (key == NULL) return -1; while (*key != '\0') { i += (int) *key; key++; } return i % HT_SIZE; } SynchronizedList** newHashTable(int hashSize) { int i; SynchronizedList** hashTable = (SynchronizedList**) malloc(hashSize * sizeof(SynchronizedList*)); for (i = 0; i < hashSize; i++) hashTable[i] = newSynchronizedList(); return hashTable; } /** ***************** * Synchronized List Functions ** ****************/ SynchronizedList* newSynchronizedList() { SynchronizedList* sl = (SynchronizedList *) malloc(sizeof(SynchronizedList)); if(!sl) return NULL; sl->list = NULL; sem_init(&(sl->readers), 0, 0); sem_init(&(sl->writers), 0, 0); sl->nReaders = 0; sl->waitingReaders = 0; sl->waitingWriters = 0; sl->writing = FALSE; return sl; } void beginReading(SynchronizedList *sl){ pthread_mutex_lock(&(sl->mutex)); if (sl->writing || sl->waitingWriters > 0) { (sl->waitingReaders)++; pthread_mutex_unlock(&(sl->mutex)); sem_wait(&(sl->readers)); pthread_mutex_lock(&(sl->mutex)); if (sl->waitingReaders > 0) { (sl->nReaders)++ ; (sl->waitingReaders)-- ; sem_post(&(sl->readers)); } } else sl->nReaders++; pthread_mutex_unlock(&(sl->mutex)); } void endReading(SynchronizedList *sl) { pthread_mutex_lock(&(sl->mutex)); (sl->nReaders)-- ; if (sl->nReaders == 0 && sl->waitingWriters > 0) { sem_post(&(sl->writers)); sl->writing = TRUE; (sl->waitingWriters)-- ; } pthread_mutex_unlock(&(sl->mutex)); } void beginWriting(SynchronizedList *sl){ pthread_mutex_lock(&(sl->mutex)); if (sl->writing || sl->nReaders > 0 || sl->waitingReaders > 0) { (sl->waitingWriters)++; pthread_mutex_unlock(&(sl->mutex)); sem_wait(&(sl->writers)); pthread_mutex_lock(&(sl->mutex)); } sl->writing = TRUE; pthread_mutex_unlock(&(sl->mutex)); } void endWriting(SynchronizedList *sl){ pthread_mutex_lock(&(sl->mutex)); sl->writing = FALSE; if(sl->waitingReaders > 0) { sem_post(&(sl->readers)); (sl->nReaders)++ ; (sl->waitingReaders)-- ; } else if (sl->waitingWriters > 0) { sem_post(&(sl->writers)); sl->writing = TRUE; (sl->waitingWriters)-- ; } pthread_mutex_unlock(&(sl->mutex)); } /** ***************** * List Functions ** ****************/ KV_t* NewKV(char* key, char* value){ KV_t* new = (KV_t*) malloc(sizeof(KV_t)); strncpy(new->key, key, KV_SIZE); strncpy(new->value, value, KV_SIZE); return new; } List NewListNode(KV_t* item) { List x = (List) malloc(sizeof(struct node)); x->item = item; x->next = NULL; x->KVID = -1; return x; } List insertList(List head, int shardID, KV_t* item, char** result, int* KVID) { List current, previous; List newNode = NewListNode(item); for (current = head, previous = NULL; current != NULL; previous = current, current = current->next) { if (strcmp(current->item->key, item->key) == 0) { // the element already exists *result = current->item->value; *KVID = current->KVID; if (current == head) { head = newNode; } else { previous->next = newNode; } newNode->KVID = current->KVID; newNode->next = current->next; //free(current); return head; } } // if we dont found the element, we insert in the begin *result = NULL; *KVID = fileNextKVID(shardID); newNode->KVID = (*KVID); newNode->next = head; return newNode; } List insertListFromFile(List head, KV_t* item, int KVID) { List newNode = NewListNode(item); newNode->KVID = KVID; newNode->next = head; return newNode; } KV_t* searchList(List head, char* key) { List current; KV_t* item; for (current = head; current != NULL; current = current->next) { item = current->item; if (strcmp(item->key, key) == 0) return item; } return NULL; } List removeItemList(List head, char* key, char** result, int* KVID) { List current, prev; KV_t* item; for (current = head, prev = NULL; current != NULL; prev = current, current = current->next) { item = current->item; if (strcmp(item->key, key) == 0) { *result = item->value; *KVID = current->KVID; if (current == head) { head = current->next; } else { prev->next = current->next; } //free(current); return head; } } *result = NULL; *KVID = -1; return head; } /** ***************** * Shards Functions ** ****************/ Shard** shards; Semaphores_t * semaphores; void** buffer; int newShardArray(int n, int hashSize){ int i; shards = (Shard**) malloc(sizeof(Shard*) * n); if(!shards) return -1; for(i = 0; i < n; i++) { shards[i] = newShard(hashSize, i); } initFiles(n); return 0; } Shard* newShard(int hashSize, int shardID){ Shard* shard = (Shard*) malloc(sizeof(Shard)); shard->hashTable = newHashTable(hashSize); shard->nElems = 0; shard->shardID = shardID; return shard; } char* ShardSearch(Shard* shard, char* key) { int i = hash(key); beginReading(shard->hashTable[i]); //delay(); KV_t* elem = searchList(shard->hashTable[i]->list, key); endReading(shard->hashTable[i]); return (elem) ? elem->value : NULL; } char* ShardInsert(Shard* shard, char* key, char* value) { int i = hash(key); int KVID; char* result; KV_t *newKV = NewKV(key, value); beginWriting(shard->hashTable[i]); //delay(); shard->hashTable[i]->list = insertList(shard->hashTable[i]->list, shard->shardID, newKV, &result, &KVID); if (result){ fileUpdateValue(shard->shardID, KVID, value); //printf(">>> FILE UPDATE VALUE: <%s,%s>\n", key, value); } else { shard->nElems++; fileWriteKV(shard->shardID, KVID, key, value); } endWriting(shard->hashTable[i]); return result; } void ShardInsertFromFile(Shard* shard, char* key, char* value, int KVID) { int i = hash(key); KV_t *newKV = NewKV(key, value); shard->hashTable[i]->list = insertListFromFile(shard->hashTable[i]->list, newKV, KVID); shard->nElems++; } char* ShardDelete(Shard* shard, char* key) { int i = hash(key); int KVID; char* result; beginWriting(shard->hashTable[i]); //delay(); shard->hashTable[i]->list = removeItemList(shard->hashTable[i]->list, key, &result, &KVID); if (result) { shard->nElems--; fileDeleteKV(shard->shardID, KVID); } endWriting(shard->hashTable[i]); return result; } KV_t* ShardGetAll(Shard* shard, int* n){ int i, j; KV_t* array; List current; if(shard->nElems == 0) return NULL; array = (KV_t*) malloc(sizeof(KV_t) * shard->nElems); //delay(); for (i = 0, j = 0; i < HT_SIZE; i++) { beginReading(shard->hashTable[i]); current = shard->hashTable[i]->list; while (current != NULL) { array[j] = *(current->item); j++; current = current->next; } endReading(shard->hashTable[i]); } *n = shard->nElems; return array; } <file_sep>/include/kos_request.h #ifndef __KOS_REQUEST_H__ #define __KOS_REQUEST_H__ typedef enum kos_request_action { PUT, GET, GETALL, REMOVE } kos_request_action_t; typedef struct { kos_request_action_t action; int shardID; int *dim_ptr; /* Used only with GETALL */ char *key; char *value; /* Used only with PUT */ } kos_request_t; kos_request_t * newKosRequestGET(int shardID, char *key); kos_request_t * newKosRequestPUT(int shardID, char *key, char *value); kos_request_t * newKosRequestREMOVE(int shardID, char *key); kos_request_t * newKosRequestGETALL(int shardID, int *dim); #endif <file_sep>/tests/Makefile SRCS=test_kos_multi_threaded_truncateFile.c test_kos_multi_threaded.c test_kos_multi_threaded_all_getAll_fromFile.c test_kos_single_threaded.c test_kos_single_threaded_put_get.c test_kos_single_threaded_put_remove_get.c test_kos_single_threaded_put_get_put_get.c test_kos_single_threaded_put_get_remove_put_get.c test_kos_single_threaded_put_dump.c test_kos_single_threaded_put_get_remove_put_dump.c test_kos_multi_threaded_put_get.c test_kos_multi_threaded_put_get_remove_get.c test_kos_multi_threaded_all.c test_kos_multi_threaded_all_getAll.c test_kos_multi_threaded_all_shared.c OBJS=${SRCS:.c=} INCLUDES = -I ../include CC = gcc LIBKOS = ../kos/libkos.a CFLAGS = -g -O0 -Wall -pthread $(INCLUDES) COMPILE = $(CC) $(DEFS) $(INCLUDES) $(CFLAGS) all: $(OBJS) test_kos_multi_threaded_truncateFile: test_kos_multi_threaded_truncateFile.c $(LIBKOS) test_kos_multi_threaded_all_getAll_fromFile: test_kos_multi_threaded_all_getAll_fromFile.c $(LIBKOS) test_kos_multi_threaded: test_kos_multi_threaded.c $(LIBKOS) test_kos_single_threaded: test_kos_single_threaded.c $(LIBKOS) test_kos_single_threaded_put_get: test_kos_single_threaded_put_get.c $(LIBKOS) test_kos_single_threaded_put_remove_get: test_kos_single_threaded_put_remove_get.c $(LIBKOS) test_kos_single_threaded_put_get_put_get: test_kos_single_threaded_put_get_put_get.c $(LIBKOS) test_kos_single_threaded_put_get_remove_put_get: test_kos_single_threaded_put_get_remove_put_get.c $(LIBKOS) test_kos_single_threaded_put_dump: test_kos_single_threaded_put_dump.c $(LIBKOS) test_kos_single_threaded_put_get_remove_put_dump: test_kos_single_threaded_put_get_remove_put_dump.c $(LIBKOS) test_kos_multi_threaded_put_get: test_kos_multi_threaded_put_get.c $(LIBKOS) test_kos_multi_threaded_put_get_remove_get: test_kos_multi_threaded_put_get_remove_get.c $(LIBKOS) test_kos_multi_threaded_all: test_kos_multi_threaded_all.c $(LIBKOS) test_kos_multi_threaded_all_getAll: test_kos_multi_threaded_all_getAll.c $(LIBKOS) test_kos_multi_threaded_all_shared: test_kos_multi_threaded_all_shared.c $(LIBKOS) clean: rm -f $(OBJS) rm -f f* # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: <file_sep>/tests/test_kos_single_threaded_put_remove_get.c #include <kos_client.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define NUM_EL 100 #define NUM_SHARDS 10 #define KEY_SIZE 20 //#define DEBUG_PRINT_ENABLED 1 // uncomment to enable DEBUG statements #if DEBUG_PRINT_ENABLED #define DEBUG printf #else #define DEBUG(format, args...) ((void)0) #endif int main(int argc, const char* argv[] ) { char key[KEY_SIZE], value[KEY_SIZE]; char* v; int i,j; int client_id=0; kos_init(1,1,NUM_SHARDS); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=NUM_EL; i>=0; i--) { sprintf(key, "k%d",i); sprintf(value, "val:%d",i); DEBUG("Element <%s,%s> being inserted in shard %d....\n", key, value, j); fflush(stdin); v=kos_put(client_id,j, key,value); if (v!=NULL) { printf("TEST FAILED - SHOULD RETURN NULL AND HAS RETURNED %s",v); exit(-1); } } } printf("------------------ ended inserting --------------------------------\n"); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=NUM_EL-1; i>=NUM_EL/2; i--) { sprintf(key, "k%d",i); sprintf(value, "val:%d",i); v=kos_remove(client_id, j, key); if (v==NULL || strncmp(v,value,KEY_SIZE)!=0) { printf("Error when removing key %s from shard %d value should be %s and was returned %s",key,j,value,(v==NULL?"NULL":v)); exit(1); } DEBUG("C:%d %s %s removed from shard %d. value =%s\n", client_id, key, ( v==NULL ? "has not been" : "has been" ),j, ( v==NULL ? "<missing>" : v ) ); } } printf("------------------ ended removing --------------------------------\n"); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=0; i<NUM_EL; i++) { sprintf(key, "k%d",i); sprintf(value, "val:%d",i); v=kos_get(client_id, j, key); if (i>=NUM_EL/2 && v!=NULL) { printf("Error when gettin key %s value should be NULL and was returned %s",key,v); exit(1); } if (i<NUM_EL/2 && strncmp(v,value,KEY_SIZE)!=0 ) { printf("Error on key %s value should be %s and was returned %s",key,value,v); exit(1); } DEBUG("C:%d %s %s found in shard %d. value=%s\n", client_id, key, ( v==NULL ? "has not been" : "has been" ) ,j, ( v==NULL ? "<missing>" : v ) ); } } printf("------------------ ended checking after removing --------------------------------\n"); printf("\n--> TEST PASSED <--\n"); return 0; } <file_sep>/tests/test_kos_single_threaded.c #include <kos_client.h> #include <stdio.h> #define NUM_EL 6 #define NUM_SHARDS 3 int main(int argc, const char* argv[] ) { char key[20], value[20]; char* v; int i,j,ret; int client_id=0; ret=kos_init(1, 1, NUM_SHARDS); if (ret!=0) { printf("kos_init failed with code %d!\n",ret); return -1; } printf("KOS Workin\n"); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=NUM_EL; i>=0; i--) { sprintf(key, "k%d",i); sprintf(value, "val:%d",i); printf("Element <%s,%s> being inserted in shard %d....", key, value, j); fflush(stdin); printf("Will put <%s,%s>\n",key,value); v=kos_put(client_id,j, key,value); printf("Element <%s,%s> inserted in shard %d. Prev Value=%s\n", key, value, j, ( v==NULL ? "<missing>" : v ) ); fflush(stdin); } } printf("--------------------------------------------------\n"); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=0; i<NUM_EL; i++) { sprintf(key, "k%d",i); v=kos_get(client_id,j, key); printf("Element %s %s found in shard %d: value=%s\n", key, ( v==NULL ? "has not been" : "has been" ),j, ( v==NULL ? "<missing>" : v ) ); } } printf("--------------------------------------------------\n"); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=NUM_EL; i>=NUM_EL/2; i--) { sprintf(key, "k%d",i); v=kos_remove(client_id,j, key); printf("Element %s %s removed from shard %d. value =%s\n", key, ( v==NULL ? "has not been" : "has been" ),j, ( v==NULL ? "<missing>" : v ) ); } } printf("--------------------------------------------------\n"); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=0; i<NUM_EL; i++) { sprintf(key, "k%d",i); v=kos_get(client_id,j, key); printf("Element %s %s found in shard %d. value=%s\n", key, ( v==NULL ? "has not been" : "has been" ) ,j, ( v==NULL ? "<missing>" : v ) ); } } printf("--------------------------------------------------\n"); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=0; i<NUM_EL; i++) { sprintf(key, "k%d",i); sprintf(value, "val:%d",i*10); v=kos_put(client_id,j, key,value); printf("Element <%s,%s> inserted in shard %d. Prev Value=%s\n", key, value, j, ( v==NULL ? "<missing>" : v ) ); } } printf("--------------------------------------------------\n"); for (j=NUM_SHARDS-1; j>=0; j--) { for (i=0; i<NUM_EL; i++) { sprintf(key, "k%d",i); v=kos_get(client_id,j, key); printf("Element %s %s found in shard %d: value=%s\n", key, ( v==NULL ? "has not been" : "has been" ),j, ( v==NULL ? "<missing>" : v ) ); } } printf("--------------------------------------------------\n"); return 0; } <file_sep>/include/buffer.h #ifndef __BUFFER_H__ #define __BUFFER_H__ #include <semaphore.h> #include <pthread.h> int bufferCompleteInit(int size); int bufferGetTicket(); void bufferPostTicket(int ticket); /** * The buffer itself */ extern void ** buffer; extern int buffer_size; int initBufferArray(int size); void *bufferGetPosition(int i); void bufferPutPosition(int i, void *ptr); /** * Semaphores to sync the client and the server */ typedef struct semaphores_t { sem_t client, server; } Semaphores_t; extern Semaphores_t * semaphores; int initSemaphoresArray(int n); /** * Semaphore that controls the client's access to the buffer itself */ extern sem_t accessBufferSem; int initAccessBufferSem(int n); /** * Stack to give an index to the client */ extern int *stack; pthread_mutex_t stackMutex; int stackInit(int n); void stackPush(int i); int stackPop(); #endif <file_sep>/include/files.h #ifndef __FILES_H__ #define __FILES_H__ #include <pthread.h> #define MAXSIZE 42 //20 from key + 20 from value + 1 from '&' + 1 from '\n' #define FILE_NAME_SIZE 5 //1 from 'f' + 3 from shardID + 1 from '\0' #define KV_SIZE 20 int initFiles(int nShards); int fileUpdateValue(int shardID, int KVID, char* value); int fileWriteKV(int shardID, int KVID, char* key, char* value); int fileDeleteKV(int shardID, int KVID); int fileInit(int shardID); int fileReadAll(int shardID); int fileNextKVID(int shardID); #endif<file_sep>/kos/kos.c #include <kos_client.h> #include <stdlib.h> #include <stdio.h> #include <semaphore.h> #include <pthread.h> #include <unistd.h> #include "shard.h" #include "buffer.h" #include "kos_request.h" #include "kos_server.h" #include "files.h" Shard** shards; Semaphores_t * semaphores; void** buffer; int kos_init(int num_server_threads, int buf_size, int num_shards) { // Args validation if(num_shards <= 0) return -1; if(num_server_threads <= 0) return -1; if(buf_size <= 0) return -1; if(num_server_threads != buf_size) { // we take the minimum value if (num_server_threads < buf_size) { buf_size = num_server_threads; } else { num_server_threads = buf_size; } } if(bufferCompleteInit(buf_size) != 0) return -1; if(newShardArray(num_shards, HT_SIZE) != 0) return -1; if(newServerThreadsArray(num_server_threads) != 0) return -1; //if(initFiles(num_shards) != 0) return -1; return 0; } char* kos_get(int clientid, int shardId, char* key) { char * result; int ticket = bufferGetTicket(); bufferPutPosition(ticket, (void *) newKosRequestGET(shardId, key)); //printf(">>> Client Request (Thread #%d) - GET REQUEST - ticket = %d \n", clientid, ticket); sem_post(&(semaphores[ticket].client)); sem_wait(&(semaphores[ticket].server)); result = (char*) bufferGetPosition(ticket); bufferPostTicket(ticket); return result; } char* kos_put(int clientid, int shardId, char* key, char* value) { char * result; int ticket = bufferGetTicket(); bufferPutPosition(ticket, (void*) newKosRequestPUT(shardId, key, value)); //printf(">>> Client Request (Thread #%d) - PUT REQUEST - ticket = %d \n", clientid, ticket); sem_post(&(semaphores[ticket].client)); sem_wait(&(semaphores[ticket].server)); result = (char*) bufferGetPosition(ticket); bufferPostTicket(ticket); return result; } char* kos_remove(int clientid, int shardId, char* key) { char * result; int ticket = bufferGetTicket(); bufferPutPosition(ticket, (void*) newKosRequestREMOVE(shardId, key)); //printf(">>> Client Request (Thread #%d) - REMOVE REQUEST - ticket = %d \n", clientid, ticket); sem_post(&(semaphores[ticket].client)); sem_wait(&(semaphores[ticket].server)); result = (char*) bufferGetPosition(ticket); bufferPostTicket(ticket); return result; } KV_t* kos_getAllKeys(int clientid, int shardId, int* dim) { KV_t * result; int ticket = bufferGetTicket(); bufferPutPosition(ticket, (void*) newKosRequestGETALL(shardId, dim)); //printf(">>> Client Request (Thread #%d) - GET ALL REQUEST - ticket = %d \n", clientid, ticket); sem_post(&(semaphores[ticket].client)); sem_wait(&(semaphores[ticket].server)); result = (KV_t *) bufferGetPosition(ticket); bufferPostTicket(ticket); return result; }
46adcafe4fc81e593a4164a9449ddc332996876c
[ "C", "Makefile", "Shell" ]
21
C
pasadinhas/so-project
adffad39394182b4fc21b3fb5f52f0626b7e1f7f
483c75fd50147737ce66cfb93eb2e7d4c708b837
refs/heads/master
<repo_name>supriyd/Scraping-Lion-Air-Reviews-on-TripAdvisor-with-R<file_sep>/README.md # Scraping-Lion-Air-Reviews-on-TripAdvisor-with-R ulasan pelanggan merupakan hal penting bagi perusahaan terutama dalam bidang jasa, hal ini menjadi tolak ukur seberapa maksimal usaha yang telah dilakukan untuk memberikan pelayanan terhadap pelanggan. jika membaca satu persatu tentu akan sulit menarik kesimpulan apa saja yang dibahas dalam ulasan tersebut apa lagi jika jumlahnya ribuan ulasan. cara ini akan mempermudah untuk mendapakan seluruh ulasan dalam file excel yang kemudian dapat di analisis, namun untuk analisisnya akan dibahas pada postingan berikutnya. Best Regards, SPRYD <file_sep>/Scraping.R library(rvest) url<-read_html("https://www.tripadvisor.com/Airline_Review-d8729111-Reviews-Lion-Air") #menemukan page terakhir pada review npages<-url%>% html_nodes(" .pageNum")%>% html_attr(name="data-page-number")%>% tail(.,1)%>% as.numeric() npages #find index page a<-0:(npages-1) b<-10 res<-numeric(length=length(a)) for (i in seq_along(a)) { res[i]<-a[i]*b } tableout <- data.frame() for(i in res){ cat(".") #Change URL address here depending on attraction for review url <- paste ("https://www.tripadvisor.com/Airline_Review-d8729111-Reviews-or",i,"-Lion-Air#REVIEWS",sep="") reviews <- url %>% html() %>% html_nodes("#REVIEWS .innerBubble") id <- reviews %>% html_node(".quote a") %>% html_attr("id") quote <- reviews %>% html_node(".quote span") %>% html_text() rating <- reviews %>% html_node(".rating .ui_bubble_rating") %>% html_attrs() %>% gsub("ui_bubble_rating bubble_", "", .) %>% as.integer() / 10 date <- reviews %>% html_node(".innerBubble, .ratingDate") %>% html_text() review <- reviews %>% html_node(".entry .partial_entry") %>% html_text() #get rid of \n in reviews as this stands for 'enter' and is confusing dataframe layout reviewnospace <- gsub("\n", "", review) temp.tableout <- data.frame(id, quote, rating, date, reviewnospace) tableout <- rbind(tableout,temp.tableout) } #simpan review dalam file excel write.csv(tableout, "F:/DOC/lionGithub/datalion.csv")
99e9855e8d64c55880a42f0b7d901e40c9b475f9
[ "Markdown", "R" ]
2
Markdown
supriyd/Scraping-Lion-Air-Reviews-on-TripAdvisor-with-R
020821f2156c5329be74dba45b2769fe34653a10
a11af29f2210950e61b4970679e5ad25a24f74ff
refs/heads/master
<file_sep>infix fun Array<Int>.dot(another: Array<Int>): Int { if (this.size != another.size) throw IllegalAccessError("It isn't same shape") return this.foldIndexed(0, { i, sum, v -> sum + v * another[i] }) // reduceIndexed start at 1 not 0 @A@# } fun main(args: Array<String>) { val a: Array<Int> = arrayOf(1, 2, 3, 4, 5) val b: Array<Int> = arrayOf(2, 3, 4, 5, 6) println(a dot b) println((1..5).sumBy { it * (it + 1) }) println(asList(1, 2, 3, "abmi", *a)) } fun <T> asList(vararg ts: T): List<T> { return ts.toList() }<file_sep>class Invoice { } class Empty //class Person constructor(firstName: String) {} class Person( firstName: String, val lastName: String = firstName + 's', var age: Int ) { init { println("I'm $firstName") age++ } val upperCase = this.lastName.toUpperCase() + " " + age } fun main(args: Array<String>) { val l = Person("Lambda", age = 18) val u = l.upperCase println(u) println(l.age) println(l.lastName) }<file_sep>fun main(args: Array<String>) { // Number // Note that characters are not numbers in kotlin. // val d: Double = 64.00 // val f: Float = 32.0F // 32.0f // val l: Long = 64L // val i: Int = 32 // val s: Short = 16 // val b: Byte = 8 // val hex = 0x0F // val bin = 0b00000010 // underscores in numeric literals (since 1.1) // val oneMillion = 1_000_000 // val r = 123_12_12345_1L val a: Int = 2010 println(a === a) // true println(a == a) // true val boxedA: Int? = a val anotherBoxedA: Int? = a println(boxedA === anotherBoxedA) // false println(boxedA == anotherBoxedA) // true val b: Int? = 1 // val c: Long? = b // Error // val c: Byte? = b // Error // val c: Byte = b.toByte() // Error val i: Byte = 1 val j: Int = i.toInt() // Characters // val c: Char = 1 // Error val c: Char = '1' val int: Int = c.toInt() // Booleans // Array val src = Array(5, { i -> (i * i).toString() }) for (si in src) { print(si + ", ") } val intArr: IntArray = intArrayOf(1, 2, 3) intArr[0] = intArr[1] + intArr[2] println("${intArr[0]}") // String val s: String = "hello-kotlin" print(s[2]) for (si in s) { print(" " + si) } }<file_sep>/** * Created by L6ml on 2017/5/19. */ fun getStringLengthA(obj: Any): Int? { if (obj is String) { return obj.length } return null } fun getStringLengthB(obj: Any): Int? { if (obj !is String) { return null } // It is String branch return obj.length } fun main(args: Array<String>) { // 1. I want to pass a function as a argument. How? // 2. What the '?:' is? fun printLengthA(obj: Any) = println("'$obj' strLen is ${getStringLengthA(obj)?: "... err, is empty or not a string at all"} ") printLengthA("Incomprehensibilities") printLengthA("") printLengthA(1000) fun printLengthB(obj: Any) { println("'$obj' strLen is ${getStringLengthB(obj)?: "... err, is empty or not a string at all"} ") } printLengthB("Incomprehensibilities") printLengthB("") printLengthB(1000) }<file_sep>/** * Created by L6ml on 2017/5/19. */ fun parseInt(str: String) : Int? { /* * val a = str.toInt() // It will throw a NumberFormatException * return if (a is Int) a else null */ try { return str.toInt() } catch (e: NumberFormatException) { println("One of the arguments isn't Int") } return null } fun printProduct(arg1: String, arg2: String = "b") : Unit { val x = parseInt(arg1) val y = parseInt(arg2) if (x != null && y != null) { println(x * y) } else { println("either '$arg1' or '$arg2' is not a number") } } fun main(args: Array<String>) { printProduct("2", "3") printProduct("2") printProduct("a", "b") }<file_sep>fun describe(obj: Any): String = // Just one export when (obj) { 1 -> "One" "apple" -> "apple" is Long -> "Long" is Int -> "Int, but not 1" !is String -> "Not a String" else -> "Unkown" } fun main(args: Array<String>) { val items = listOf<String>("apple", "banana", "kiwi") for (item in items) { println(item) } for (index in items.indices) { println(items[index]) } var index = 0 while (index < items.size) { println(items[index++]) } println(describe(1)) println(describe(items[0])) println(describe(1000L)) println(describe(2)) println(describe(2.134)) println(describe("other")) val a: Int = if (true) 1 else 0 println(a) val b: Int = 3 val max = if (a > b) { println("choose a") a } else { println("choose b") b } println(max) }<file_sep>/** * Created by L6ml on 2017/5/19. */ fun main(args: Array<String>) { val a = 2 var b: Int = 3 b += 1 println("Hello kotlin!") println("$a + $b = ${sum(a, b)}") } fun sum(a: Int, b: Int) = a + b
517cc6e05f422a265fee96aeb61ea674b5a69f7d
[ "Kotlin" ]
7
Kotlin
zhufuge/kotlin-demo
bbb3251c18cf400f1da3166a9d1049c6e074598f
0131ecf699fe6c5a82468bb27f3e935ba18773ea
refs/heads/master
<file_sep># i2psnark-desktop Desktop files for i2psnark <file_sep>#!/bin/bash # Add url to i2psnark # by <NAME> <<EMAIL>> # Define i2psnark URL i2psnark="http://localhost:7657/i2psnark/" # Get the secret nonce from i2psnark # curl -s = silent # use tail to skip nonce from messages nonce=$(curl -s $i2psnark | grep "nonce" | tail -n1 | grep -o "[0-9]*") echo "Nonce: $nonce" curl -s -X POST -d "nonce=$nonce&action=Add&newURL=$1" $i2psnark xdg-open $i2psnark
5fb5ad6131ee430f1b81d7b249411de1c5189aa7
[ "Markdown", "Shell" ]
2
Markdown
mattias-ohlsson/i2psnark-desktop
a552f879b1a25ff45511155f2800e1f0e1f87e61
0fd0cccf919e315ee4ac8760761fd8dd51ed0207
refs/heads/master
<repo_name>QGfcc/Calculator<file_sep>/js/main.js /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ function state() { var lastVal = undefined; var curVal = undefined; var input = ""; var curOp = ""; var nextOp = ""; // this.value2 = "test this.value"; this.addOperator = function (operator) { curOp = nextOp; nextOp = operator; if (input !== "") { this.updateCurVal(); input = ""; if (lastVal !== undefined) { this.compute() } } }; this.updateInput = function (lastChar) { if (lastChar !== "." || !(input.indexOf(".") > -1)) { input += lastChar; this.displayInput(); } }; this.updateCurVal = function () { lastVal = curVal; curVal = parseFloat(input); }; this.compute = function () { switch (curOp) { case "+": curVal = lastVal + curVal; this.displayAnswer(); break; case "-": curVal = lastVal - curVal; this.displayAnswer(); break; case "*": curVal = lastVal * curVal; this.displayAnswer(); break; case "/": curVal = lastVal / curVal; this.displayAnswer(); break; case "=": break; default : this.displayErr(); } } this.clearInput = function () { input = ""; this.displayInput(); } this.clearAll = function () { lastVal = undefined; curVal = undefined; input = ""; curOp = ""; nextOp = ""; this.displayInput(); } this.display = function (str) { // document.getElementById("calScreen").innerHTML = str; $("#calScreen").text(str); }; this.displayInput = function () { this.display(input); }; this.displayAnswer = function () { this.display(curVal); }; this.displayErr = function () { this.display("ERROR"); }; } $(document).ready(function () { var calculator = new state(); // $(".inputs div div button").addClass("digit"); // $(".inputs .row div").addClass("col-xs-3 col-sm-2 col-sm-offset-4"); // $(".inputs .row div").addClass("col-xs-3 col-sm-2 col-sm-offset-4"); // $(".buttons").addClass("col-xs-3 col-sm-2"); // $(".buttons:first-child").addClass("col-sm-offset-4"); // $(".buttons").addClass("col-xs-3 text-center"); $(".buttons").addClass("text-center"); // $(".inputs div div:last-child button").removeClass("digit"); // $(".inputs div div:last-child button").addClass("operator"); // $(".inputs div button:nth-child(4)").removeClass("digit"); // $(".inputs div button:nth-child(4)").addClass("digit"); // $(".digit").click(calculator.updateInput.bind(calculator, this.value2)); // $(".digit").click(function () { // calculator.updateInput.call(calculator, this.value); // }); // $(".equal").removeClass("digit"); // $(".equal").addClass("operator"); // $(".CE").removeClass("digit"); $(".digit").click(function () { calculator.updateInput.call(calculator, this.value); }); $(".operator").click(function () { calculator.addOperator.call(calculator, this.value); }); // $(".equal").click(function () { //// calculator.compute.bind(calculator)(); // calculator.addOperator.bind(calculator, this.value)(); // }); $("#CE").click(function () { // calculator.compute.bind(calculator)(); calculator.clearInput.call(calculator); // alert("dqs"); }); $("#CA").click(function () { calculator.clearAll.call(calculator); }); });
4d7b6773a5228951b4fe6ce50f844412cd271983
[ "JavaScript" ]
1
JavaScript
QGfcc/Calculator
32ced7c804b3ae5963e72b8708aabcc32f9a9961
3cc82167ea9bff97c72feea889521361d9df232f
refs/heads/master
<repo_name>inteGerVariable/land.github.io<file_sep>/script.js var color1 = "#2c2b3e" var color2 = '#21212f'
9019530cef62478a49d75a54c595af1978c67c4d
[ "JavaScript" ]
1
JavaScript
inteGerVariable/land.github.io
96017ef16f4675134a93f3e765e77a9955ad0c17
ef79739aa1baaf0c4c68d5b43cb7b19439b4c527
refs/heads/master
<file_sep>var counter = 0; $(function() { console.log("I am here!"); $("#btnSubmit").click(function() { var guessMe = $("#guessMe").val(); var btnValue = $("#btnSubmit").val(); if(btnValue.match(/^([\d])((?!\1)[\d])(?!\2)((?!\1)[\d])(?!\3)(?!\2)((?!\1)[\d])$/)){ $.ajax({ url : "Solver", data : { 'guessMe' : guessMe }, dataType : "json", type : "POST", success : winner, fail : looser }) } else{ $("<div class='alert alert-warning'>") .html("<strong>Please enter 4 different digits. </strong>") .appendTo("#winner"); //$("#btnSubmit").attr("disabled",false); } }); function winner(response) { console.log(response); if (response != undefined) { // $("#displayTable").hide(); counter++; console.log("counter " +counter); if (counter == 1) { $("<div>") .html( "<table class='table'>" + "<tr class='danger'>" + "<td><strong>#</strong></td>" + "<td align='center'>&nbsp;&nbsp;<strong>Your guessing Number</strong></td>" + "<td align='center'><strong>(Matching Digit , Matching Position)</td></tr></strong>") .appendTo("#dataDiv"); } } if(counter%2 ==0){ $("<div>") .html( "<table class='table'>" + "<tr class='success'>" + "<td>" + counter + "</td>" + "<td>" + response.number + "</td>" + "<td>(" + response.match[0] + "," + response.match[1] + ")</td></td></tr>") .appendTo( "#dataDiv"); }else{ $("<div>") .html( "<table class='table'>" + "<tr class='info'>" + "<td>" + counter + "</td>" + "<td>" + response.number + "</td>" + "<td>(" + response.match[0] + "," + response.match[1] + ")</td></td></tr>") .appendTo( "#dataDiv"); } if((response.match[0] ==4) && (response.match[1] == 4)){ $("<div class='alert alert-success'>") .html("<strong>Congratulations ! You Won!</strong>") .appendTo("#winner"); $("#btnSubmit").attr("disabled", true); } if(counter > 10){ $("<div class='alert alert-danger'>") .html("<strong>Sorry, you have reached the maximum attempt. You Fail ! </strong>") .appendTo("#winner"); $("#btnSubmit").attr("disabled", true); } } function looser() { $("<div class='alert alert-warning'>") .html("<strong>Error ! Please try again later. </strong>") .appendTo("#winner"); $("#btnSubmit").attr("disabled",false); } $("#btnReset").click(function(){ $("#dataDiv").empty(); $("#btnSubmit").attr("disabled",false); $("#winner").empty(); $("#guessMe").clear(); counter = 0; }); });
5700332fdbbc0e8b0328d95b4bfacd65b8c70db9
[ "JavaScript" ]
1
JavaScript
romiezaw/Guess_Me
033dadbe03108fa7f210da19e797a50051074b3b
02a842799bcd7ee90c7d0cb1181f317243c75e99
refs/heads/master
<repo_name>PedroGusso/simple-assembler<file_sep>/src/assemble.py import sys import re opcodes = {} regcodes = {} def loadOpCode(filename): opCodeDict = {} with open(filename, "r") as opCodeFile: for line in opCodeFile: splitted = line.split("|") opCodeDict[splitted[0]] = splitted[1].strip() print("Opcodes loaded. \n") return opCodeDict def loadRegCode(filename): regCodeDict = {} with open(filename, "r") as regCodeFile: for line in regCodeFile: splitted = line.split("|") regCodeDict[splitted[0]] = splitted[1].strip() print("Regcodes loaded. \n") return regCodeDict def getRegister(reg): global regcodes aux = regcodes.get(reg) if aux is None: print("Register " + reg + " does not exists. \n") sys.exit(0) return aux def decode(line): global opcodes try: commentPosition = line.index(";") line = line[:commentPosition-1] except ValueError: pass if re.search('NOP', line): return opcodes['NOP'] elif re.search('HALT', line): return opcodes['HALT'] elif re.search('MOV(\s)*([a-zA-Z]+)(\s)*,(\s)*(\[[0-9]+\])(\s)*', line): line = line.strip() return opcodes["MOV_RM"] + " " + getRegister(line[4:6]) + " " + line[8:len(line) - 1] elif re.search('MOV(\s)*([a-zA-Z]+)(\s)*,(\s)*([a-zA-Z]+)(\s)*', line): line = line.strip() regs = line[3:].split(",") return opcodes['MOV_RR'] + " " + getRegister(regs[0].strip()) + " " + getRegister(regs[1].strip()) elif re.search('MOV(\s)*(\[[0-9]+\])(\s)*,(\s)*([a-zA-Z]+)(\s)*', line): line = line.strip() args = line[4:].split(",") return opcodes["MOV_MR"] + " " + (args[0])[1:len(args[0])-1] + " " + getRegister(args[1]) elif re.search('MOV(\s)*([a-zA-Z]+)(\s)*,(\s)*([0-9]+)(\s)*', line): line = line.strip() args = line[3:].split(",") return opcodes['MOV_RI'] + " " + getRegister(args[0].strip()) + " " + args[1] elif re.search('MOV(\s)*(\[[0-9]+\])(\s)*,(\s)*([0-9]+)(\s)*', line): line = line.strip() args = line[3:].split(",") return opcodes['MOV_MI'] + " " + (args[0])[2:len(args[0]) - 1] + " " + args[1] elif re.search('JL(\s)*([0-9]+)(\s)*', line): line = line.strip() args = re.sub(r"JL(\s)*","",line) return opcodes['JL'] + " " + args elif re.search('OUT(\s)*([a-zA-Z]+)(\s)*', line): line = line.strip() args = re.sub(r"OUT(\s)*","",line) return opcodes['OUT'] + " " + getRegister(args) elif re.search('INC(\s)*([a-zA-Z]+)(\s)*', line): line = line.strip() args = re.sub(r"INC(\s)*","",line) return opcodes['INC'] + " " + getRegister(args) elif re.search('DEC(\s)*([a-zA-Z]+)(\s)*', line): line = line.strip() args = re.sub(r"DEC(\s)*","",line) return opcodes['DEC'] + " " + getRegister(args) elif re.search('MUL(\s)*([a-zA-Z]+)(\s)*,(\s)*([a-zA-Z]+)(\s)*', line): line = line.strip() line = re.sub(r"MUL(\s)*","",line) regs = line.split(",") return opcodes['MUL'] + " " + getRegister(regs[0].strip()) + " " + getRegister(regs[1].strip()) elif re.search('DIV(\s)*([a-zA-Z]+)(\s)*,(\s)*([a-zA-Z]+)(\s)*', line): line = line.strip() line = re.sub(r"DIV(\s)*","",line) regs = line.split(",") return opcodes['DIV'] + " " + getRegister(regs[0].strip()) + " " + getRegister(regs[1].strip()) else: print("Command " + line.strip() + " not found") sys.exit(0) return def main(): global opcodes global regcodes opcodes = loadOpCode(sys.argv[2]) regcodes = loadRegCode(sys.argv[3]) output = "" with open(sys.argv[1], "r") as inputFile: for line in inputFile: opcode = decode(line) output += opcode + " " print output outputfile = open("bin/" + sys.argv[4], "a") if re.search('([a-zA-Z]+).run', sys.argv[4]) else open("bin/" + sys.argv[4] + ".run", "a") outputfile.write(output) if __name__ == "__main__": main()
772c67203d28095b9c6ebe0dd1fb442410ffec66
[ "Python" ]
1
Python
PedroGusso/simple-assembler
83cbb6a1a52d143c8f6d88ec7387349491ea7e75
bb95a5a1edc6dbff357c7060b317bbaff388e9d0
refs/heads/master
<repo_name>JAlbizures/runnable<file_sep>/app.js //declaración de variables var express = require('express'), app = require('express')(), http = require('http').Server(app), port = process.env.PORT || 3000, io = require('socket.io')(http), mongoose = require('mongoose'), bodyParser = require('body-parser'), cookieParser = require('cookie-parser'), methodOverride = require('method-override'); //Middleware app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(bodyParser.json()); app.use(methodOverride()); app.use(express.static(__dirname + '/public')); //Conexión a Base de Datos mongoose.connect('mongodb://localhost:27017/runnable', function(err, res){ if(err) throw err; console.log('Base de datos conectada') }); //Instanciación de modelos y controladores var Post = require('./models/post')(app, mongoose), PostCtrl = require('./controllers/post'); //Enrutamiento var router = express.Router(); app.use(router); var posts = express.Router(); //Enrutamiento hacia posts posts.route('/posts') .get(PostCtrl.buscarPosts) .post(PostCtrl.agregarPost); app.use('/api',posts); //Funcionamiento socket en la aplicación (Tiempo real de publicaciones) io.on('connection', function(socket){ //Si un usuario se conecta se alerta al servidor console.log('Un usuario se ha conectado.'); socket.on('disconnect', function(){ //Si un usuario se desconecta se alerta al servidor console.log('Un usuario se ha desconectado.'); }); //Evento que captura cuando se postea algo socket.on('post message', function(msgPost){ console.log('Post: ' + msgPost); //Se alerta al servidor que se envió io.emit('post message', msgPost); //Se muestra el post en tiempo real en la página }); }); //Iniciación de servidor http.listen(port, function(){ console.log('Esperando en el puerto '+port); });<file_sep>/models/seguidor.js exports = module.exports = function(app.mongoose){ var seguidorSchema =new mongoose.Schema({ nombre : {type : String}, apellido : {type : String}, edad : {type : Number}, correo : {type : String}, coment : {type : String}, nickName : {type : String}, pass : {type : String}, exp : {type : Number}, filtros : {type : String}, seguidores : {type : Schema.Types._idSeguidor, ref : 'seguidores'}, }); mongoose.model('Seguidor', seguidorSchema); };<file_sep>/models/usuario.js exports = module.exports = function(app, mongoose){ var usuarioSchema =new mongoose.Schema({ nombre : {type : String}, apellido : {type : String}, edad : {type : Number}, correo : {type : String}, comment : {type : String}, //era coment nickname : {type : String}, //era nickName pass : {type : String}, exp : {type : Number}, filtros : {type : String}, seguidores : {type : Schema.Types.ObjectId, ref : 'seguidores'}, post : {type : Schema.Types.ObjectId, ref : 'post'} }); mongoose.model('Usuario', usuarioSchema); };<file_sep>/models/like.js exports = module.exports = function(app, mongoose){ var likeSchema = new mongoose.Schema({ Historia : {type: Schema.Types.ObjectID, ref : 'Historia'}, like : {type: boolean} }); mongoose.model('Like', likeSchema); };<file_sep>/models/historia.js exports = module.exports = function(app ,mongoose){ var historiaSchema = new mongoose.Schema({ titulo : {type : String}, historia : {type : String}, tipoHistoria : {type : String}, genero : {type : String}, seguidores : {type : Schema.Types.ObjectId, ref : 'seguidores'}, post : {type : Schema.Types.ObjectId, ref : 'post'}, likes : {type : Schema.Types.ObjectId, ref : 'like'}, usuario : {type : Schema.Types.ObjectId, ref: 'usuario'} }); mongoose.model('Historia', historiaSchema); }; <file_sep>/models/post.js exports = module.exports = function(app, mongoose){ var postSchema = new mongoose.Schema({ contenido : {type : String}, historia : {type : Schema.Types.ObjectId, ref: 'historia'} like : [{type : Schema.Types.ObjectId, ref: 'like'}], usuario : {type : Schema.Types.ObjectId, ref: 'usuario'} }); mongoose.model('Post',postSchema); };<file_sep>/public/js/main.js $(document).ready(function(){ $('.slide-new-feed').slick({ dots: false, infinite: true, speed: 300, slidesToShow: 4, touchMove: true, slidesToScroll: 1, responsive: [ { breakpoint: 3000, settings: { slidesToShow:8, slidesToScroll: 1, dots: false } }, { breakpoint: 2000, settings: { slidesToShow:6, slidesToScroll: 1, dots: false } }, { breakpoint: 1600, settings: { slidesToShow:4, slidesToScroll: 1, dots: false } }, { breakpoint: 996, settings: { slidesToShow: 4, slidesToScroll: 1, dots: false } }, { breakpoint: 971, settings: { slidesToShow: 4, slidesToScroll: 1, dots: false } }, { breakpoint: 768, settings: { dots:false, slidesToShow: 2, slidesToScroll: 1 } }, { breakpoint: 510, settings: { dots:false, slidesToShow: 1, slidesToScroll: 1 } }, { breakpoint: 500, settings: { dots:false, slidesToShow: 1, slidesToScroll: 1 } }, ] }); });<file_sep>/controllers/usuario.js var mongoose = require('mongoose'), Usuario = mongoose.model('Usuario'); exports.buscarUsuario = function(req, res){ Usuario.find(function(err, usuarios){ if(err) res.send(500, err.message); console.log('Get /usuarios'); res.status(200).jsonp(usuarios); }); }; exports.buscarPorId = function(res, res){ Usuario.findById(req.params.id, function(err, usuario){ if(err) return res.send(500, err.message); console.log('Get /usuario/' + req.params.id); res.status(200).jsonp(usuario); }); }; exports.agregarUsuario = function(req, res){ console.log('Agergar usuario'); console.log(req.body); var usuario = new Usuario({ nombre : req.body.nombre, apellido : req.body.apellido, edad : req.body.edad, correo : req.body.correo, comment : req.body.comment, nickname : req.body.nickname, pass : <PASSWORD>, exp : 0, filtros : req.body.filtros, seguidores : 0, post : null }); }; exports.editarUsuario = function(req, res){ console.log('Editar usuario'); console.log(req.body); Usuario.findById(req.params.id, function(err, usuario){ usuario.nombre = req.body.nombre; usuario.apellido = req.body.apellido; usuario.edad = req.body.edad; usuario.correo = req.body.correo; usuario.comment = req.body.comment; //no estoy seguro usuario.nickname = req.body.nickname; usuario.pass = <PASSWORD>; usuario.filtros = req.body.filtros; usuario.save(function(err){ if(err) return res.send(500, err.message); res.status(200).jsonp(usuario); }); }); }; exports.eliminarUsuario = function(req, res){ Usuario.findById(res.params.id, function(err, usuario){ usuario.remove(function(err){ res.statu(200); }); }); };
6c629081d43e7591c5b5511baa389a6f408f5ec0
[ "JavaScript" ]
8
JavaScript
JAlbizures/runnable
543ee3ac4fcf86c1711804a29b5ea9f14bc4616f
171d27afbbfe04952d95b0c05dd455842f9661df
refs/heads/master
<repo_name>M-Onitsuka/robot-programming<file_sep>/dxl_armed_turtlebot/scripts/test.py #!/usr/bin/env python import rospy #import Python client API for ROS from opencv_apps.msg import RotatedRectStamped #import RotatedRectStamped which is subscribed by ? #Motion Analysis Nodes of opencv_apps.msg ? #using camshift algorithms from image_view2.msg import ImageMarker2 #message to draw on image_view2 canvas from geometry_msgs.msg import Point #Message type which contains the position of a point in free space def cb(msg): print msg.rect #print msg.rect subscribed by RotatedRectStamped? #angle,center(x,y),size(width,height) marker = ImageMarker2() #set marker marker.type = 0 #draw circle? marker.position = Point(msg.rect.center.x, msg.rect.center.y, 0) #at msg.rect position pub.publish(marker)#publish marker/draw marker on canvas? rospy.init_node('client') #initialize node rospy.Subscriber('/camshift/track_box',RotatedRectStamped,cb) #set subscriber callback. #rospy.Subscriber('topic_name',std_msgs.msg.String?,callback) #the topic /camshift/track_box is opencv_apps. #and String RotatedRectStamped has #header: # seq # stamp: # secs # nsecs # frameid #rect: # angle # center # size #give msg to callback pub = rospy.Publisher('/image_marker', ImageMarker2) #rospy.Publisher initialization #pub = rospy.Publisher('topic_name', std_msgs.msg.String, queue_size=10) rospy.spin() #run
7c8b2a0d285ee01b4955dad046682298bb3b0e76
[ "Python" ]
1
Python
M-Onitsuka/robot-programming
da0afde0d09af62902e340ff384dafc0209ce5ff
0f21e6957a7b9ce0d254c1292912b61e6ad3b029
refs/heads/master
<repo_name>vlasy/jest-test<file_sep>/dummy.test.js test('server run', () => { console.log(require.resolve('passport')); });
dbfe45835a6c69db8d23c0e4994cc7097f1cd0df
[ "JavaScript" ]
1
JavaScript
vlasy/jest-test
130073d52e603ed5eaa8aa1ac140a15a4ad9a871
271bbaf61650547ebbe3abaa82807e6b5b0e538e
refs/heads/master
<repo_name>bmoers/playground<file_sep>/springsecurity/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ch.rasc</groupId> <artifactId>springsecurity</artifactId> <version>0.0.1</version> <packaging>war</packaging> <prerequisites> <maven>3.0.0</maven> </prerequisites> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.debug>true</maven.compiler.debug> <spring.version>4.0.2.RELEASE</spring.version> <spring-security.version>3.2.2.RELEASE</spring-security.version> <hibernate.version>4.3.4.Final</hibernate.version> <querydsl.version>3.3.1</querydsl.version> </properties> <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>http://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>http://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>jboss.release</id> <name>JBoss Release Repository</name> <url>https://repository.jboss.org/nexus/content/repositories/releases/</url> </repository> </repositories> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring-security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring-security.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> <exclusions> <exclusion> <artifactId>xml-apis</artifactId> <groupId>xml-apis</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.jadira.usertype</groupId> <artifactId>usertype.core</artifactId> <version>3.1.0.GA</version> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.0.2.Final</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>16.0.1</version> </dependency> <dependency> <groupId>com.mysema.querydsl</groupId> <artifactId>querydsl-jpa</artifactId> <version>${querydsl.version}</version> <exclusions> <exclusion> <artifactId>asm</artifactId> <groupId>asm</groupId> </exclusion> <exclusion> <artifactId>cglib</artifactId> <groupId>cglib</groupId> </exclusion> <exclusion> <artifactId>jsr305</artifactId> <groupId>net.sourceforge.findbugs</groupId> </exclusion> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.0-rc1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.0-rc1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-jcl</artifactId> <version>2.0-rc1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.0-rc1</version> </dependency> <dependency> <groupId>ch.rasc</groupId> <artifactId>embeddedtc</artifactId> <version>1.12</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.3.175</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>com.mysema.maven</groupId> <artifactId>apt-maven-plugin</artifactId> <version>1.1.1</version> <executions> <execution> <id>jpa</id> <goals> <goal>process</goal> </goals> <configuration> <outputDirectory>target/generated-sources/java</outputDirectory> <processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor> </configuration> </execution> </executions> <dependencies> <dependency> <groupId>com.mysema.querydsl</groupId> <artifactId>querydsl-apt</artifactId> <version>${querydsl.version}</version> </dependency> <dependency> <groupId>com.mysema.querydsl</groupId> <artifactId>querydsl-jpa</artifactId> <classifier>apt</classifier> <version>${querydsl.version}</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.8</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>${project.build.directory}/generated-sources/java/</source> </sources> </configuration> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/springsecurity/src/main/java/ch/rasc/sec/security/SecurityConfig.java package ch.rasc.sec.security; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity // @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Autowired private UserDetailsService userDetailsService; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override public UserDetailsService userDetailsService() { return userDetailsService; } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { TwoFactorAuthenticationConfigurer configurer = new TwoFactorAuthenticationConfigurer(userDetailsService) .passwordEncoder(passwordEncoder()); auth.apply(configurer); } @Override public void configure(WebSecurity builder) throws Exception { builder.ignoring().antMatchers("/resources/**", "/favicon.ico", "/robots.txt"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/sayHello").hasRole("ADMIN").anyRequest().authenticated() .and().formLogin().authenticationDetailsSource(new AdditionalWebAuthenticationDetailsSource()) .loginPage("/login.jsp").failureUrl("/login.jsp?error").permitAll() .and().logout().logoutSuccessUrl("/login.jsp?logout").deleteCookies("JSESSIONID").permitAll(); } }<file_sep>/springsecurity/src/main/java/ch/rasc/sec/security/TwoFactorAuthenticationProvider.java package ch.rasc.sec.security; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.util.StringUtils; public class TwoFactorAuthenticationProvider extends DaoAuthenticationProvider { @Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { super.additionalAuthenticationChecks(userDetails, authentication); if (authentication.getDetails() instanceof AdditionalWebAuthenticationDetails) { Integer googleAuthenticatorCode = ((AdditionalWebAuthenticationDetails) authentication.getDetails()) .getCode(); String secret = ((JpaUserDetails) userDetails).getSecret(); if (StringUtils.hasText(secret)) { if (googleAuthenticatorCode != null) { try { if (!GoogleAuthenticatorUtil.verifyCode(secret, googleAuthenticatorCode, 2)) { throw new BadCredentialsException("Google Authenticator Code is not valid"); } } catch (InvalidKeyException | NoSuchAlgorithmException e) { throw new InternalAuthenticationServiceException("google authenticator code verify failed", e); } } else { throw new MissingGoogleAuthenticatorException("Google Authenticator Code is mandatory"); } } } } } <file_sep>/taffy/src/main/java/ch/rasc/taffy/controller/BirthdaySerializer.java package ch.rasc.taffy.controller; import java.io.IOException; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.SerializerProvider; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; public class BirthdaySerializer extends JsonSerializer<LocalDate> { private final static DateTimeFormatter BIRTHDAY_FORMATTER = DateTimeFormat.forPattern("MM-dd-yyyy"); @Override public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(BIRTHDAY_FORMATTER.print(value)); } } <file_sep>/springsecurity/src/main/java/Test.java import java.util.Set; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration.Dynamic; import org.springframework.web.servlet.DispatcherServlet; public class Test implements ServletContainerInitializer { @Override public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { Dynamic dispatcherServlet = ctx.addServlet("dispatcherServlet", new DispatcherServlet()); dispatcherServlet.setAsyncSupported(true); dispatcherServlet.setLoadOnStartup(1); dispatcherServlet.addMapping("/"); } } <file_sep>/springsecurity/src/main/java/ch/rasc/sec/config/WebAppInitializer.java package ch.rasc.sec.config; import org.springframework.core.annotation.Order; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import ch.rasc.sec.security.SecurityConfig; @Order(1) public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { ComponentConfig.class, DataConfig.class, SecurityConfig.class, WebConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Class<?>[] getServletConfigClasses() { return null; } @Override protected WebApplicationContext createServletApplicationContext() { return new GenericWebApplicationContext(); } }<file_sep>/cors/src/main/java/ch/rasc/cors/config/MyWebAppInitializer.java package ch.rasc.cors.config; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class MyWebAppInitializer implements WebApplicationInitializer { @SuppressWarnings("resource") @Override public void onStartup(ServletContext container) { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(WebConfig.class); container.addListener(new ContextLoaderListener(rootContext)); final DispatcherServlet dispatcherServlet = new DispatcherServlet(new GenericWebApplicationContext()); dispatcherServlet.setDispatchOptionsRequest(true); /* * <init-param> <param-name>dispatchOptionsRequest</param-name> * <param-value>true</param-value> </init-param> */ ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", dispatcherServlet); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/action/*"); } }<file_sep>/springsecurity/src/main/java/ch/rasc/sec/config/DataConfig.java package ch.rasc.sec.config; import java.util.Map; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.hibernate.jpa.HibernatePersistenceProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.collect.Maps; @Configuration @EnableTransactionManagement public class DataConfig { @Autowired private Environment environment; @Bean public DataSource dataSource() throws NamingException { Context ctx = new InitialContext(); return (DataSource) ctx.lookup("java:comp/env/jdbc/example"); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException { LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); emf.setDataSource(dataSource()); emf.setPersistenceProvider(new HibernatePersistenceProvider()); emf.setPackagesToScan("ch.rasc.sec.entity"); Map<String, String> properties = Maps.newHashMap(); properties.put("hibernate.hbm2ddl.auto", "update"); properties.put("hibernate.show_sql", "true"); properties.put("jadira.usertype.databaseZone", "UTC"); properties.put("jadira.usertype.javaZone", "UTC"); emf.setJpaPropertyMap(properties); return emf; } @Bean public PlatformTransactionManager transactionManager() throws NamingException { return new JpaTransactionManager(entityManagerFactory().getObject()); } } <file_sep>/springsecurity/src/main/java/ch/rasc/sec/security/JpaUserDetails.java package ch.rasc.sec.security; import java.util.Collection; import org.joda.time.DateTime; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import ch.rasc.sec.entity.Role; import ch.rasc.sec.entity.User; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet.Builder; public class JpaUserDetails implements UserDetails { private static final long serialVersionUID = 1L; private final ImmutableSet<GrantedAuthority> authorities; private final String password; private final String username; private final String secret; private final boolean enabled; private final Long userDbId; private final boolean locked; private final boolean expired; public JpaUserDetails(User user) { this.userDbId = user.getId(); this.password = <PASSWORD>.<PASSWORD>(); this.username = user.getUserName(); this.secret = user.getSecret(); this.enabled = user.isEnabled(); if (user.getLockedOut() != null && user.getLockedOut().isAfter(DateTime.now())) { locked = true; } else { locked = false; } if (user.getExpirationDate() != null && DateTime.now().isAfter(user.getExpirationDate())) { expired = true; } else { expired = false; } Builder<GrantedAuthority> builder = ImmutableSet.builder(); for (Role role : user.getRoles()) { builder.add(new SimpleGrantedAuthority(role.getName())); } this.authorities = builder.build(); } @Override public Collection<GrantedAuthority> getAuthorities() { return authorities; } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } public Long getUserDbId() { return userDbId; } @Override public boolean isAccountNonExpired() { return !expired; } @Override public boolean isAccountNonLocked() { return !locked; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return enabled; } public String getSecret() { return secret; } } <file_sep>/springsecurity/src/main/java/ch/rasc/sec/security/AdditionalWebAuthenticationDetails.java package ch.rasc.sec.security; import javax.servlet.http.HttpServletRequest; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.security.web.authentication.WebAuthenticationDetails; public class AdditionalWebAuthenticationDetails extends WebAuthenticationDetails { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private Integer code; public AdditionalWebAuthenticationDetails(HttpServletRequest request) { super(request); String codeString = request.getParameter("code"); try { code = Integer.valueOf(codeString); } catch (NumberFormatException e) { code = null; } } public Integer getCode() { return code; } }
2ec92a3352884a428f400e34a4b75d4195521a6c
[ "Java", "Maven POM" ]
10
Maven POM
bmoers/playground
ad25ff49f0dc56969588b5a59169952271a6381d
d7d2f5af27123f18575999e133d96dbf11b71146
refs/heads/master
<repo_name>BlakeShortland/GAM111.2<file_sep>/Assets/Scripts/GameController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameController : MonoBehaviour { [System.Serializable] struct Player { public int health; public int damage; public int speed; public int skillPointsRemaining; public int healthPotions; public Color myColor; } [System.Serializable] struct Enemy { public int health; public int damage; public int speed; public int skillPointsRemaining; public int healthPotions; } [SerializeField] Player playerStruct; [SerializeField] Enemy[] enemyStructArray; [SerializeField] static GameObject enemy1; [SerializeField] static GameObject enemy2; public static Transform playerTransform; public static int skillPointsAvailable = 10; public static int maxSkillPointsPerSkill = 5; public bool battleMode = false; public static Color colorToSet; int enemyID; void Start() { RandomiseEnemies(); } //A series of functions that randomise the enemies and atificially get them to "spend" skill points void RandomiseEnemies() { int i; for (i = 0; i < enemyStructArray.Length; i++) { enemyStructArray[i].skillPointsRemaining = skillPointsAvailable; enemyStructArray[i].health = GiveRandomSkillPoints(enemyStructArray[i].skillPointsRemaining); enemyStructArray[i].skillPointsRemaining -= enemyStructArray[i].health; enemyStructArray[i].damage = GiveRandomSkillPoints(enemyStructArray[i].skillPointsRemaining); enemyStructArray[i].skillPointsRemaining -= enemyStructArray[i].damage; enemyStructArray[i].speed = GiveRemainingSkillPoints(enemyStructArray[i].skillPointsRemaining); enemyStructArray[i].skillPointsRemaining -= enemyStructArray[i].speed; } } int GiveRandomSkillPoints(int skillPoints) { int skillPointsUsed; skillPointsUsed = Random.Range(1, MaxSkillPointsToApply(skillPoints)); return skillPointsUsed; } int MaxSkillPointsToApply(int skillPointsLeft) { int maxSkillPoints; if (skillPointsLeft > maxSkillPointsPerSkill) maxSkillPoints = maxSkillPointsPerSkill; else maxSkillPoints = skillPointsLeft; return maxSkillPoints; } int GiveRemainingSkillPoints(int skillPointsRemaining) { int skillPointsUsed; skillPointsUsed = skillPointsRemaining; return skillPointsUsed; } public void EnterBattleMode() { enemyID = Random.Range(0,enemyStructArray.Length - 1); battleMode = true; SceneManager.LoadScene("BattleScene"); } //A function to send the relevant data to the battle controller public void SendBattleDataToBattleController() { BattleController.playerHealth = playerStruct.health; BattleController.playerDamage = playerStruct.damage; BattleController.playerSpeed = playerStruct.speed; BattleController.playerHealthPotions = playerStruct.healthPotions; BattleController.enemyHealth = enemyStructArray[enemyID].health; BattleController.enemyDamage = enemyStructArray[enemyID].damage; BattleController.enemySpeed = enemyStructArray[enemyID].speed; BattleController.enemyHealthPotions = enemyStructArray[enemyID].healthPotions; } //A function to recieve the relevant data from the battle controller public void RecieveBattleDataFromBattleController() { playerStruct.health = BattleController.playerHealth; playerStruct.damage = BattleController.playerDamage; playerStruct.speed = BattleController.playerSpeed; playerStruct.healthPotions = BattleController.playerHealthPotions; enemyStructArray[enemyID].health = BattleController.enemyHealth; enemyStructArray[enemyID].damage = BattleController.enemyDamage; enemyStructArray[enemyID].speed = BattleController.enemySpeed; enemyStructArray[enemyID].healthPotions = BattleController.enemyHealthPotions; } //A function to send the relevant data to the ui controller public void SendPlayerDataToUIController() { UIController.playerHealth = playerStruct.health; UIController.playerAttack = playerStruct.damage; UIController.playerSpeed = playerStruct.speed; } //A function to recieve the relevant data from the ui controller public void RecievePlayerDataFromUIController() { playerStruct.health = UIController.playerHealth; playerStruct.damage = UIController.playerAttack; playerStruct.speed = UIController.playerSpeed; } } <file_sep>/Assets/Scripts/PlayerStaticController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerStaticController : MonoBehaviour { //This script sets the colour of the static non functioning player model in the background of the chacracter customisation scene. It's done the same way as the real player in the player controller Material myMaterial; void Start() { GetComponents(); } void Update () { SetMyColor(); } void GetComponents() { myMaterial = GetComponent<Renderer>().material; } void SetMyColor() { myMaterial.color = GameController.colorToSet; } } <file_sep>/Assets/Scripts/Bootstrap.cs using UnityEngine; using UnityEngine.SceneManagement; public class Bootstrap : MonoBehaviour { //This script keeps my GameController active across all scenes void Awake () { DontDestroyOnLoad(gameObject); } void Start () { SceneManager.LoadScene(1); } } <file_sep>/README.md # GAM111.2 Unity Standard Assets (modified player controller) Low Poly: Foliage<file_sep>/Assets/Scripts/UIController.cs using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class UIController : MonoBehaviour { //This script controls everything UI, whether it's user input, reciting variables, or changing scenes //Different scenes pull what they need from the script and some functions only run on certain scenes //If I were to do this again, I would break it up into multiple scripts [SerializeField] GameObject fadeImageObject; [SerializeField] Slider redSlider; [SerializeField] Slider greenSlider; [SerializeField] Slider blueSlider; [SerializeField] Slider attackSlider; [SerializeField] Slider healthSlider; [SerializeField] Slider speedSlider; [SerializeField] Text redSliderValueText; [SerializeField] Text greenSliderValueText; [SerializeField] Text blueSliderValueText; [SerializeField] Text playerHealthText; [SerializeField] Text playerPotionsText; [SerializeField] Text enemyHealthText; [SerializeField] Text enemyPotionsText; [SerializeField] Text attackSliderValueText; [SerializeField] Text healthSliderValueText; [SerializeField] Text speedSliderValueText; [SerializeField] Text skillPointsLeftText; [SerializeField] Button attackButton; [SerializeField] Button defendButton; [SerializeField] Button healButton; [SerializeField] Button ContinueButton; public static int playerAttack; public static int playerHealth; public static int playerSpeed; Image fadeImage; GameObject gameController; bool fading = true; void Awake () { AssignObjects(); } void Start() { if (SceneManager.GetActiveScene().name == "MainMenu") { GameController.colorToSet = new Color32((byte)0, (byte)255, (byte)0, (byte)255); } if (SceneManager.GetActiveScene().name == "CharacterCreator") { SetUpSliders(); ContinueButton.interactable = false; } } void Update () { if (UsingFadeIn()) { FadeFromBlack(); } if (SceneManager.GetActiveScene().name == "BattleScene") { if (BattleController.playersTurn) { attackButton.interactable = true; defendButton.interactable = true; if (BattleController.playerHealthPotions <= 0) healButton.interactable = false; else healButton.interactable = true; } else { attackButton.interactable = false; defendButton.interactable = false; healButton.interactable = false; } playerHealthText.text = ("Health: " + BattleController.playerHealth.ToString() + " "); playerPotionsText.text = ("Health Potions: " + BattleController.playerHealthPotions.ToString() + " "); enemyHealthText.text = ("Health: " + BattleController.enemyHealth.ToString() + " "); enemyPotionsText.text = ("Health Potions: " + BattleController.enemyHealthPotions.ToString() + " "); } } void SetUpSliders() { redSlider.onValueChanged.AddListener(delegate { SetPlayerColor(); }); greenSlider.onValueChanged.AddListener(delegate { SetPlayerColor(); }); blueSlider.onValueChanged.AddListener(delegate { SetPlayerColor(); }); attackSlider.onValueChanged.AddListener(delegate { SetPlayerSkillPoints(); }); healthSlider.onValueChanged.AddListener(delegate { SetPlayerSkillPoints(); }); speedSlider.onValueChanged.AddListener(delegate { SetPlayerSkillPoints(); }); gameController.GetComponent<GameController>().SendPlayerDataToUIController(); attackSlider.value = playerAttack; healthSlider.value = playerHealth; speedSlider.value = playerSpeed; SetPlayerColor(); } void AssignObjects() { if (UsingFadeIn()) { fadeImageObject = GameObject.Find("FadeFromBlackContainer"); fadeImage = fadeImageObject.GetComponentInChildren<Image>(); } if (SceneManager.GetActiveScene().name == "BattleScene") { attackButton = GameObject.Find("Attack Button").GetComponent<Button>(); defendButton = GameObject.Find("Defend Button").GetComponent<Button>(); healButton = GameObject.Find("Heal Button").GetComponent<Button>(); } gameController = GameObject.FindGameObjectWithTag("GameController"); } void FadeFromBlack() { if (fadeImageObject.transform.GetChild(0).gameObject.activeInHierarchy == false) fadeImageObject.transform.GetChild(0).gameObject.SetActive(true); fadeImage = fadeImageObject.GetComponentInChildren<Image>(); if (fading == true) { fadeImage.CrossFadeAlpha(1, 3.0f, false); fading = false; } if (fading == false) { fadeImage.CrossFadeAlpha(0, 3.0f, false); } } public void ChangeSceneToMainMenu() { SceneManager.LoadScene("MainMenu"); } public void ChangeSceneToCharacterCreator() { SceneManager.LoadScene("CharacterCreator"); } public void ChangeSceneToGame() { SceneManager.LoadScene("Game"); } public void QuitGame() { Application.Quit(); } public void SetPlayerColor() { GameController.colorToSet = new Color32((byte) redSlider.value, (byte) greenSlider.value, (byte) blueSlider.value, (byte) 255); redSliderValueText.text = (" " + redSlider.value.ToString()); greenSliderValueText.text = (" " + greenSlider.value.ToString()); blueSliderValueText.text = (" " + blueSlider.value.ToString()); } public void SetPlayerSkillPoints() { gameController.GetComponent<GameController>().RecievePlayerDataFromUIController(); attackSliderValueText.text = (" " + attackSlider.value.ToString()); healthSliderValueText.text = (" " + healthSlider.value.ToString()); speedSliderValueText.text = (" " + speedSlider.value.ToString()); playerAttack = Mathf.RoundToInt(attackSlider.value); playerHealth = Mathf.RoundToInt(healthSlider.value); playerSpeed = Mathf.RoundToInt(speedSlider.value); int skillPointsLeft = GameController.skillPointsAvailable - playerAttack - playerHealth - playerSpeed; skillPointsLeftText.text = "Skill Points Left: " + (skillPointsLeft).ToString(); if (skillPointsLeftText.text == "Skill Points Left: 0") ContinueButton.interactable = true; else ContinueButton.interactable = false; } public bool UsingFadeIn() { if (SceneManager.GetActiveScene().name == "Game" || SceneManager.GetActiveScene().name == "BattleScene") return true; else return false; } } <file_sep>/Assets/Scripts/CameraController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraController : MonoBehaviour { public static Transform playerTransform; // Stores the player transform. Vector3 playerPosition; // Stores the player vector. Camera mainCamera; // Stores the camera component of the main camera. [SerializeField] GameObject playerTarget; // Stores the player target prefab. GameObject oldTarget; void Start () { mainCamera = GetComponent<Camera>(); // Gets the camera component. } void Update () { MatchPlayerPosition(); // Run the Match Target Position function. CheckInputs(); } void MatchPlayerPosition () { if (playerTransform != null) { playerPosition = new Vector3(playerTransform.position.x, playerTransform.position.y + 10, playerTransform.position.z + 2); // Sets the target position 10 units above the player and 2 units down screen from the player. transform.position = Vector3.MoveTowards(transform.position, playerPosition, 100f); // Moves the camera towards the start position. mainCamera.depth = playerTransform.transform.position.y + 4; // Changes the "height" of the camear depending on what level the player is on. return; } Debug.Log("No player detected."); } //This function checks for player inputs and runs their respective functions void CheckInputs () { // Delete the old target and put a new one down then the player clicks if (Input.GetMouseButtonDown(0)) { ClearOldTarget(); SetPlayerTarget(); } } //Set the target location for the player navmesh agent to navigate to void SetPlayerTarget () { RaycastHit hit; Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit)) { if(playerTarget != null) { Instantiate(playerTarget, hit.point, Quaternion.Euler(90f,0f,0f)); } else { Debug.Log("Set player target prefab"); } } } //Delete the old target void ClearOldTarget () { oldTarget = GameObject.Find("PlayerTarget(Clone)"); Destroy(oldTarget); } } <file_sep>/Assets/Scripts/PlayerSpawner.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerSpawner : MonoBehaviour { [SerializeField] GameObject playerPrefab; GameObject player; [SerializeField] Vector3 startPosition = new Vector3(9, 1, 7); void Start () { //If there is no playerTransform defined, define it and then spawn the player at the starting position. if (GameController.playerTransform == null) { GameController.playerTransform = playerPrefab.transform; Instantiate(playerPrefab, startPosition, Quaternion.identity); } //Otherwise instantiate at the last position else Instantiate(playerPrefab, GameController.playerTransform.position, Quaternion.identity); player = playerPrefab; FindPlayer(); } public void FindPlayer() { CameraController.playerTransform = GameObject.FindGameObjectWithTag("Player").transform; // Sets the player transform by finding the object with the tag "player". } } <file_sep>/Assets/Scripts/EnemyController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class EnemyController : MonoBehaviour { Material myMaterial; bool isDead = false; GameObject gameController; public NavMeshAgent agent; public Transform[] waypoints; public float targetThreshold = 0f; private int currentWaypointIndex = 0; private Transform target; void Start () { gameController = GameObject.FindGameObjectWithTag("GameController"); GetComponents(); if (waypoints.Length != 0) { //Setup initial target based on the first waypoint target = waypoints[0]; } } void Update () { DeadCheck(); if(isDead == false) { RayCast(); Patrol(); } } //Raycast to detect if the player is in view, then switch to the battle scene using the Enter Battle Mode function void RayCast () { RaycastHit hit; if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit)) { if (hit.transform.tag == "Player") { gameController.GetComponent<GameController>().EnterBattleMode(); isDead = true; } } Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.red); } //Change the color of the enemy if they are dead void DeadCheck () { if(isDead) { myMaterial.color = Color.grey; return; } myMaterial.color = Color.red; } //My get components script that runs all my get components, keeping it neater in the start function void GetComponents () { myMaterial = GetComponent<Renderer>().material; } void Patrol () { //Do not patrol if there is more than one waypoint if (waypoints.Length != 0) { agent.SetDestination(target.position); //If the enemy has reached the current waypoint, iterate to the next waypoint if ((transform.position - target.position).magnitude <= targetThreshold) { UpdateWaypoint(); } } } void UpdateWaypoint() { currentWaypointIndex++; if (currentWaypointIndex >= waypoints.Length) { currentWaypointIndex = 0; } target = waypoints[currentWaypointIndex]; } } <file_sep>/Assets/Scripts/PlayerController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class PlayerController : MonoBehaviour { Material myMaterial; // Stores my material GameObject target; // Stores the target postion for the player to move to. void Start () { GetComponents(); SetMyColor(); } void Update () { MoveToTarget(); // Runs my MoveToTarget function. GameController.playerTransform.position = transform.position; } void GetComponents() { myMaterial = GetComponent<Renderer>().material; } //Set my color to the custom color defined in the Game Controller void SetMyColor() { myMaterial.color = GameController.colorToSet; } //Move to the target using the navmeshagent void MoveToTarget() { if (GameObject.Find("PlayerTarget(Clone)") != null) { target = GameObject.Find("PlayerTarget(Clone)"); NavMeshAgent agent = GetComponent<NavMeshAgent>(); agent.destination = target.transform.position; } } //Destroy the target when the player reaches the target void OnCollisionEnter(Collision collision) { if (collision.gameObject.name == "PlayerTarget(Clone)") { Destroy(target); } } } <file_sep>/Assets/Scripts/BattleController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class BattleController : MonoBehaviour { //Player stats public static int playerHealth; public static int playerDamage; public static int playerSpeed; public static int playerHealthPotions; //Enemy stats public static int enemyHealth; public static int enemyDamage; public static int enemySpeed; public static int enemyHealthPotions; //Game controller container GameObject gameController; //Booleans for managing the turn system public static bool playersTurn; bool playerMadeMove = false; bool enemyMadeMove = false; bool gamePlaying = true; void Awake() { gameController = GameObject.FindGameObjectWithTag("GameController"); gameController.GetComponent<GameController>().SendBattleDataToBattleController(); } void Start () { CheckWhoseTurn(); StartCoroutine(GameLoop()); } //This function detirmins who goes first void CheckWhoseTurn() { if (playerSpeed >= enemySpeed) playersTurn = true; else playersTurn = false; } //This IEnumerator was made to replace the Update function, because I believed my game was freezing when the lower coroutines were yielding. It turned out to be a UI element that was blocking my clicks, but this IEnumerator still works seemingly as well. IEnumerator GameLoop () { while (gamePlaying) { if (playersTurn) StartCoroutine(PlayersTurn()); else StartCoroutine(EnemysTurn()); DeadCheck(); //Wait 2 seconds before continuing to allow speech pop ups to be readable yield return new WaitForSecondsRealtime(2); } } IEnumerator PlayersTurn () { playerMadeMove = false; while (playerMadeMove != true) yield return null; playersTurn = false; } IEnumerator EnemysTurn() { enemyMadeMove = false; EnemyBattleAI(); while (enemyMadeMove != true) yield return null; playersTurn = true; } //If the player or the enemy is defeated, leave the battle scene public void DeadCheck() { if (playerHealth <= 0) SceneManager.LoadScene("MainMenu"); if (enemyHealth <= 0) SceneManager.LoadScene("Game"); } //Depending on whose turn it is, take away the damage from the oposing health public void Attack () { if (playersTurn) { enemyHealth -= playerDamage; Debug.Log("Player attacking."); playerMadeMove = true; } else { playerHealth -= enemyDamage; Debug.Log("Enemy attacking."); enemyMadeMove = true; } } //If someone defends then the opponents damage is reduced for the remainder of the battle public void Defend() { if (playersTurn) { if (enemyDamage > 1) enemyDamage -= 1; Debug.Log("Player defending."); playerMadeMove = true; } else { if (playerDamage > 1) playerDamage -= 1; Debug.Log("Enemy defending."); enemyMadeMove = true; } } //If someone has health potions they can heal up to the maximum possible health. public void Heal() { if (playersTurn) { if (playerHealthPotions > 0) { playerHealth += GameController.maxSkillPointsPerSkill - playerHealth; playerHealthPotions--; Debug.Log("Player healing."); playerMadeMove = true; } } else { if (enemyHealthPotions > 0) { enemyHealth += GameController.maxSkillPointsPerSkill - enemyHealth; enemyHealthPotions--; Debug.Log("Enemy healing."); enemyMadeMove = true; } } } //Detirmines what move the enemy makes using a simulated D20 public void EnemyBattleAI() { int roll = Random.Range(1, 21); if (LowHealth(enemyHealth)) { if (roll > 5) Heal(); else AttackDefend(); } else { if (roll < 5) Heal(); else AttackDefend(); } } //If attacking, attack. Otherwise defend public void AttackDefend() { if (Attacking()) Attack(); else Defend(); } //A boolean to check if the enemy has less than half health. If they do, they are more likely to heal bool LowHealth(int health) { if (health < GameController.maxSkillPointsPerSkill / 2) return true; else return false; } bool Attacking() { int roll = Random.Range(0,1); if (roll != 0) return true; else return false; } }
b4ac0a8fd6f9a55a66e2f5e69945eae7bc9256bc
[ "Markdown", "C#" ]
10
C#
BlakeShortland/GAM111.2
2eb8ffe674b42bafc4be4b9f7b418438ce9f9f96
ab866aa2529355b7588e14049c2ab7f3612b5d8d
refs/heads/dev
<repo_name>EFF/webargs<file_sep>/dev-requirements-py3.txt -r dev-requirements.txt aiohttp>=0.21.0 webtest-aiohttp==1.1.0 <file_sep>/tests/test_aiohttpparser.py # -*- coding: utf-8 -*- import webtest_aiohttp import pytest from tests.common import CommonTestCase from tests.apps.aiohttp_app import create_app class TestAIOHTTPParser(CommonTestCase): def create_app(self): return create_app() def create_testapp(self, app): return webtest_aiohttp.TestApp(app) @pytest.mark.skip(reason='files location not supported for aiohttpparser') def test_parse_files(self, testapp): pass def test_parse_match_info(self, testapp): assert testapp.get('/echo_match_info/42').json == {'mymatch': 42} def test_use_args_on_method_handler(self, testapp): assert testapp.get('/echo_method').json == {'name': 'World'} assert testapp.get('/echo_method?name=Steve').json == {'name': 'Steve'} def test_invalid_status_code_passed_to_validation_error(self, testapp): with pytest.raises(LookupError) as excinfo: testapp.get('/error_invalid?text=foo') assert excinfo.value.args[0] == 'No exception for 12345' <file_sep>/docs/requirements.txt -r ../dev-requirements-py3.txt sphinx==1.4.8 sphinx-issues==0.3.0
6dd138d041dab1cdefb96a45f9d4387a8003bc42
[ "Python", "Text" ]
3
Text
EFF/webargs
599b7abebd9b2abb7e91db516537fe2f278e00fa
70f9d5ee1f33d0b63c7a63f2cc2331f20c499f6a
refs/heads/master
<file_sep>log("--> Running ajax.ts") match($path) { # Match the Ajax path with(/CrossSellAjax/i) { $(".//dl") { name("dll") } } } # needed for product images # replace("%24", "$") # replace("&amp;", "&")<file_sep>$('./body') { insert_top("header", class: "mw-header") { insert("a", class: 'mw-logo', href:'/') { move_here("//img[@id='hfLifetechLogoImage']") } insert("div", class:"mw-header-icons") { # Account move_here("//li[@id='hfGreetByName']") { # CHange the account button to remove the onclick attribute("id", "mw-account-btn") attribute("style", "") } # Cart move_here("//li[@id='miniCartButton']") # Navigation Button insert_bottom("div", class:'mw-nav-icon', "|||", data-ur-toggler-component:'button', data-ur-id:'menubtn') } hide("//div[contains(@class,'globalHeader')]") move_here("//div[contains(@class,'g6') and contains(@class,'search')]") { $(".//button[@id='searchButton']") { move_to("..", "bottom") } } # Navigation Menu insert_bottom("nav", class:'mw-navigation', data-ur-toggler-component:'content', data-ur-id:'menubtn') { move_here("//ul[contains(@class,'meganav')]") $(".//li[contains(@class,'nav-4-col')]") { attributes(data-ur-set:'toggler') $("./a") { attributes(data-ur-toggler-component:'button') %hreffun = fetch("./@href") attributes(href:'') } $("./ul") { attributes(data-ur-toggler-component:'content') remove(".//img/ancestor::li[1]") $("./li") { # Section header $(".//b") { add_class("mw-section-header") } # Section links $("./ul/li/a") { add_class("mw-navigation-link") } } } } } } } <file_sep># The main file executed by Tritium. The start of all other files. $cont_type = inferred_content_type() match($path) { with(/CrossSellAjax/i) { $cont_type = 'ajax' } with(/HWFastProductDetailAjax/) { $cont_type = 'ajax' } } match($cont_type) { with(/html/) { protect_xmlns() # Force UTF-8 encoding. If you'd like to auto-detect the encoding, # simply remove the "UTF-8" argument. e.g. html(){ ... } html("UTF-8") { @import "html.ts" } restore_xmlns() restore_dollar_sign() } with(/ajax/) { html_fragment("UTF-8") { @import "ajax.ts" } } else() { log("Passing through " + $content_type + " unmodified.") } }
75679637613108449ab1beb2bf0ca959e6debcd8
[ "TypeScript" ]
3
TypeScript
moovweb-projects/lifetech-training
c5c7b56bf7b60deffe602e84ebb53436605e2495
894261555ce5dc57c7dc37e04ebaea36bda3793b