index
int64
1
4.83k
file_id
stringlengths
5
9
content
stringlengths
167
16.5k
repo
stringlengths
7
82
path
stringlengths
8
164
token_length
int64
72
4.23k
original_comment
stringlengths
11
2.7k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
142
16.5k
Inclusion
stringclasses
4 values
file-tokens-Qwen/Qwen2-7B
int64
64
3.93k
comment-tokens-Qwen/Qwen2-7B
int64
4
972
file-tokens-bigcode/starcoder2-7b
int64
74
3.98k
comment-tokens-bigcode/starcoder2-7b
int64
4
959
file-tokens-google/codegemma-7b
int64
56
3.99k
comment-tokens-google/codegemma-7b
int64
3
953
file-tokens-ibm-granite/granite-8b-code-base
int64
74
3.98k
comment-tokens-ibm-granite/granite-8b-code-base
int64
4
959
file-tokens-meta-llama/CodeLlama-7b-hf
int64
77
4.12k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
4
1.11k
excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
1,725
2300_4
package is103.lostluggage; import is103.lostluggage.Database.MyJDBC; import is103.lostluggage.Model.User; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Locale; import java.util.ResourceBundle; import java.util.Scanner; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.event.EventType; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.geometry.Rectangle2D; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.stage.FileChooser; /** * Main class * * @author Michael de Boer * */ public class MainApp extends Application { private static BorderPane root; public static int serviceChangeValue = 99; //Database instance private static MyJDBC DB; public static String language = "english"; public static String currentView; public static User currentUser = null; public static Stage mainStage; @Override public void start(Stage stage) throws Exception { //Method to set the db property setDatabase("corendonlostluggage", "root", "admin"); //set root root = FXMLLoader.load(getClass().getResource("/fxml/MainView.fxml")); Scene mainScene = new Scene(root); checkLoggedInStatus(currentUser); mainScene.getStylesheets().add("/styles/Styles.css"); stage.setTitle("Corendon Lost Luggage"); stage.setScene(mainScene); Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds(); stage.setX(primaryScreenBounds.getMinX()); stage.setY(primaryScreenBounds.getMinY()); stage.setWidth(primaryScreenBounds.getWidth()); stage.setHeight(primaryScreenBounds.getHeight()); stage.setMinWidth(1000); stage.setMinHeight(700); Image logo = new Image("Images/Stage logo.png"); //Image applicationIcon = new Image(getClass().getResourceAsStream("Images/Logo.png")); stage.getIcons().add(logo); stage.show(); //Set the mainstage as a property MainApp.mainStage = stage; } //methode voor het switchen van schermen public static void switchView(String view) throws IOException { //parent vanuit MainApp laden Parent fxmlView; if (language.equals("dutch")) { ResourceBundle bundle = ResourceBundle.getBundle("resources.Bundle", new Locale("nl")); fxmlView = FXMLLoader.load(MainApp.class.getResource(view), bundle); } else { ResourceBundle bundle = ResourceBundle.getBundle("resources.Bundle"); fxmlView = FXMLLoader.load(MainApp.class.getResource(view), bundle); } //scene zetten ( in Center van BorderPane ) //fxmlView. root.setCenter(fxmlView); } public static File selectFileToSave(String defaultFileName) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Specify filename"); //todo: provide the file selection dialog to the user File file = fileChooser.showSaveDialog(mainStage); //File selected? return the file, else return null if (file != null) { return file; } else { return null; } } //set the database instance public static void setDatabase(String dbname, String user, String password) throws FileNotFoundException { // //config file // File file = new File("src/main/resources/config"); // // //Scanner object // Scanner input = new Scanner(file); // // String dbname = input.next(); // String user = input.next(); // String password = input.next(); //init db MainApp.DB = new MyJDBC(dbname, user, password); } //method to connect to the database public static MyJDBC getDatabase() { return MainApp.DB; } public static String getLanguage() { return language; } public static void checkLoggedInStatus(User user) throws IOException { if (user != null) { currentUser = user; System.out.println(user); if (user.getRole().equals("Administrator")) { switchView("/Views/Admin/HomeUserView.fxml"); System.out.println("The correct user role is selected: " + user); } if (user.getRole().equals("Manager")) { switchView("/Views/ManagerHomeView.fxml"); } if (user.getRole().equals("Service")) { switchView("/Views/Service/ServiceHomeView.fxml"); } } else { switchView("/Views/Admin/LogInView.fxml"); } } /** * The main() method is ignored in correctly deployed JavaFX application. * main() serves only as fallback in case the application can not be * launched through deployment artifacts, e.g., in IDEs with limited FX * support. NetBeans ignores main(). * * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
ThijsZijdel/Corendon-LostLuggage
app/LostLuggage/src/main/java/is103/lostluggage/MainApp.java
1,472
//methode voor het switchen van schermen
line_comment
nl
package is103.lostluggage; import is103.lostluggage.Database.MyJDBC; import is103.lostluggage.Model.User; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Locale; import java.util.ResourceBundle; import java.util.Scanner; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.event.EventType; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.geometry.Rectangle2D; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.stage.FileChooser; /** * Main class * * @author Michael de Boer * */ public class MainApp extends Application { private static BorderPane root; public static int serviceChangeValue = 99; //Database instance private static MyJDBC DB; public static String language = "english"; public static String currentView; public static User currentUser = null; public static Stage mainStage; @Override public void start(Stage stage) throws Exception { //Method to set the db property setDatabase("corendonlostluggage", "root", "admin"); //set root root = FXMLLoader.load(getClass().getResource("/fxml/MainView.fxml")); Scene mainScene = new Scene(root); checkLoggedInStatus(currentUser); mainScene.getStylesheets().add("/styles/Styles.css"); stage.setTitle("Corendon Lost Luggage"); stage.setScene(mainScene); Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds(); stage.setX(primaryScreenBounds.getMinX()); stage.setY(primaryScreenBounds.getMinY()); stage.setWidth(primaryScreenBounds.getWidth()); stage.setHeight(primaryScreenBounds.getHeight()); stage.setMinWidth(1000); stage.setMinHeight(700); Image logo = new Image("Images/Stage logo.png"); //Image applicationIcon = new Image(getClass().getResourceAsStream("Images/Logo.png")); stage.getIcons().add(logo); stage.show(); //Set the mainstage as a property MainApp.mainStage = stage; } //methode voor<SUF> public static void switchView(String view) throws IOException { //parent vanuit MainApp laden Parent fxmlView; if (language.equals("dutch")) { ResourceBundle bundle = ResourceBundle.getBundle("resources.Bundle", new Locale("nl")); fxmlView = FXMLLoader.load(MainApp.class.getResource(view), bundle); } else { ResourceBundle bundle = ResourceBundle.getBundle("resources.Bundle"); fxmlView = FXMLLoader.load(MainApp.class.getResource(view), bundle); } //scene zetten ( in Center van BorderPane ) //fxmlView. root.setCenter(fxmlView); } public static File selectFileToSave(String defaultFileName) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Specify filename"); //todo: provide the file selection dialog to the user File file = fileChooser.showSaveDialog(mainStage); //File selected? return the file, else return null if (file != null) { return file; } else { return null; } } //set the database instance public static void setDatabase(String dbname, String user, String password) throws FileNotFoundException { // //config file // File file = new File("src/main/resources/config"); // // //Scanner object // Scanner input = new Scanner(file); // // String dbname = input.next(); // String user = input.next(); // String password = input.next(); //init db MainApp.DB = new MyJDBC(dbname, user, password); } //method to connect to the database public static MyJDBC getDatabase() { return MainApp.DB; } public static String getLanguage() { return language; } public static void checkLoggedInStatus(User user) throws IOException { if (user != null) { currentUser = user; System.out.println(user); if (user.getRole().equals("Administrator")) { switchView("/Views/Admin/HomeUserView.fxml"); System.out.println("The correct user role is selected: " + user); } if (user.getRole().equals("Manager")) { switchView("/Views/ManagerHomeView.fxml"); } if (user.getRole().equals("Service")) { switchView("/Views/Service/ServiceHomeView.fxml"); } } else { switchView("/Views/Admin/LogInView.fxml"); } } /** * The main() method is ignored in correctly deployed JavaFX application. * main() serves only as fallback in case the application can not be * launched through deployment artifacts, e.g., in IDEs with limited FX * support. NetBeans ignores main(). * * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
True
1,082
10
1,256
11
1,317
9
1,256
11
1,462
12
false
false
false
false
false
true
2,319
22470_13
package driver;_x000D_ _x000D_ import java.util.ArrayList;_x000D_ import models.Instructie;_x000D_ import models.Knaller;_x000D_ import static models.Product.EURO;_x000D_ import models.Vuurpijl;_x000D_ import models.Vuurwerk;_x000D_ _x000D_ public class HappyNewYearDriver {_x000D_ _x000D_ /**_x000D_ * @param args the command line arguments_x000D_ */_x000D_ public static void main(String[] args) {_x000D_ ArrayList<Vuurwerk> pakket = new ArrayList<Vuurwerk>();_x000D_ _x000D_ System.out.println("Happy new year from: Burak, IS109, 500740123");_x000D_ _x000D_ stap1(pakket);_x000D_ stap2(pakket);_x000D_ stap3(pakket);_x000D_ stap4(pakket);_x000D_ stap5(pakket);_x000D_ stap6(pakket);_x000D_ }_x000D_ _x000D_ private static void stap1(ArrayList<Vuurwerk> pakket) {_x000D_ System.out.println("\n--- STAP 1 ---");_x000D_ _x000D_ Vuurwerk vuurwerk;_x000D_ _x000D_ vuurwerk = new Vuurwerk("Veiligheidsbril", 2.5,_x000D_ new Instructie(true, 6, "Draag bij aansteken"));_x000D_ pakket.add(vuurwerk);_x000D_ System.out.println(vuurwerk);_x000D_ _x000D_ vuurwerk = new Vuurwerk("Safety glass", 2.5,_x000D_ new Instructie(false, 6, "Wear before ignition"));_x000D_ pakket.add(vuurwerk);_x000D_ System.out.println(vuurwerk);_x000D_ _x000D_ vuurwerk = new Vuurwerk("Aansteeklont zonder instructie", 0.25, null);_x000D_ pakket.add(vuurwerk);_x000D_ System.out.println(vuurwerk);_x000D_ }_x000D_ _x000D_ private static void stap2(ArrayList<Vuurwerk> pakket) {_x000D_ System.out.println("\n--- STAP 2 ---");_x000D_ _x000D_ Knaller knaller;_x000D_ _x000D_ // knaller met Engelstalige instructie en 75 decibel_x000D_ knaller = new Knaller(777, 75, "Celebration Crackers", 10,_x000D_ new Instructie(false, 21, "Keep minimum 10 ft distance"));_x000D_ pakket.add(knaller);_x000D_ System.out.println(knaller);_x000D_ _x000D_ // knaller met Nederlandstalige instructie en 120 decibel_x000D_ knaller = new Knaller(500, 120, "Peking Rol", 45,_x000D_ new Instructie(true, 21, "Houd minimaal 5 meter afstand"));_x000D_ pakket.add(knaller);_x000D_ System.out.println(knaller);_x000D_ _x000D_ // knaller met Nederlandstalige instructie en 125 decibel_x000D_ knaller = new Knaller(1000, 125, "Shanghai Rol", 85,_x000D_ new Instructie(true, 21, "Houd minimaal 5 meter afstand"));_x000D_ pakket.add(knaller);_x000D_ System.out.println(knaller);_x000D_ _x000D_ // knaller zonder instructie en 100 decibel_x000D_ knaller = new Knaller(1000, 100, "Hongkong Rol", 82.5, null);_x000D_ pakket.add(knaller);_x000D_ System.out.println(knaller);_x000D_ }_x000D_ _x000D_ private static void stap3(ArrayList<Vuurwerk> pakket) {_x000D_ System.out.println("\n--- STAP 3 ---");_x000D_ _x000D_ Vuurpijl vuurpijl;_x000D_ _x000D_ // vuurpijl met Nederlandstalige instructie, correcte kleurverhouding, leeftijd 10_x000D_ vuurpijl = new Vuurpijl(40, new int[]{50, 25, 25}, "Cruise Rocket", 2.50,_x000D_ new Instructie(true, 10, "Niet in de hand houden"));_x000D_ pakket.add(vuurpijl);_x000D_ System.out.println(vuurpijl);_x000D_ _x000D_ // vuurpijl met Nederlandstalige instructie, incorrecte kleurverhouding, leeftijd 16_x000D_ vuurpijl = new Vuurpijl(40, new int[]{25, 30, 44}, "Killing Arrow", 4.25,_x000D_ new Instructie(true, 16, "Niet in de hand houden"));_x000D_ pakket.add(vuurpijl);_x000D_ System.out.println(vuurpijl);_x000D_ _x000D_ // vuurpijl met Engelstalige instructie, incorrecte kleurverhouding, leeftijd 20_x000D_ vuurpijl = new Vuurpijl(40, new int[]{50, 41, 10}, "Magic Sky", 2.75,_x000D_ new Instructie(false, 20, "Keep minimum 10 ft distance"));_x000D_ pakket.add(vuurpijl);_x000D_ System.out.println(vuurpijl);_x000D_ _x000D_ // vuurpijl zonder instructie, correcte kleurverhouding_x000D_ vuurpijl = new Vuurpijl(40, new int[]{50, 50, 0}, "Golden Sky", 3.25, null);_x000D_ pakket.add(vuurpijl);_x000D_ System.out.println(vuurpijl);_x000D_ }_x000D_ _x000D_ public static void stap4(ArrayList<Vuurwerk> pakket) {_x000D_ System.out.println("\n--- STAP 4 ---");_x000D_ toonVuurwerk(pakket);_x000D_ }_x000D_ _x000D_ private static void toonVuurwerk(ArrayList<Vuurwerk> pakket) {_x000D_ double totaalPrijs = 0;_x000D_ for (Vuurwerk i : pakket) { //loop door de array Vuurwerk_x000D_ totaalPrijs += i.getPrijs(); //totaalPrijs telt op i aantal keren met getPrijs_x000D_ System.out.println(i.toString()); //print al het vuurwerk_x000D_ }_x000D_ System.out.println("\n Kosten vuurwerkpakket: " + EURO + totaalPrijs); //print totaalprijs_x000D_ }_x000D_ _x000D_ private static void toonInstructies(ArrayList<Vuurwerk> pakket, int index) {_x000D_ if ((index >= 0) && (index < pakket.size())) { //als index binnen bereik is doe:_x000D_ if (pakket.get(index).getInstructie() != null) { //als getInstructie() uit array niet null is:_x000D_ System.out.println(pakket.get(index).getInstructie()); //print de instructie voor opgegeven index_x000D_ } else {_x000D_ System.out.println("Instructie ontbreekt."); //als deze null is, print instructie ontbreekt_x000D_ }_x000D_ _x000D_ } else {_x000D_ System.out.println("Index valt buiten grenzen."); //als index buiten bereik is, print_x000D_ }_x000D_ }_x000D_ _x000D_ public static void stap5(ArrayList<Vuurwerk> pakket) {_x000D_ System.out.println("\n--- STAP 5 ---");_x000D_ toonInstructies(pakket, -1);_x000D_ toonInstructies(pakket, 3);_x000D_ toonInstructies(pakket, 10);_x000D_ toonInstructies(pakket, 11);_x000D_ }_x000D_ _x000D_ public static void stap6(ArrayList<Vuurwerk> pakket) {_x000D_ System.out.println("\n--- STAP 6 ---");_x000D_ _x000D_ printHardeKnallers(pakket, 100);_x000D_ }_x000D_ _x000D_ private static void printHardeKnallers(ArrayList<Vuurwerk> pakket, int maxDecibel) {_x000D_ for (Vuurwerk i : pakket) { //loop door de array_x000D_ if (i instanceof Knaller) { //gebruik instanceof om methodes van de subclass te kunnen gebruiken_x000D_ if (((Knaller) i).getDecibel() > maxDecibel) { //als getDecibel() groter is dan opgegeven maxDecibel_x000D_ System.out.println(i.toString()); //print de toString van i (index)_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_
buracc/OOP1-Exam
src/driver/HappyNewYearDriver.java
2,100
//als getInstructie() uit array niet null is:_x000D_
line_comment
nl
package driver;_x000D_ _x000D_ import java.util.ArrayList;_x000D_ import models.Instructie;_x000D_ import models.Knaller;_x000D_ import static models.Product.EURO;_x000D_ import models.Vuurpijl;_x000D_ import models.Vuurwerk;_x000D_ _x000D_ public class HappyNewYearDriver {_x000D_ _x000D_ /**_x000D_ * @param args the command line arguments_x000D_ */_x000D_ public static void main(String[] args) {_x000D_ ArrayList<Vuurwerk> pakket = new ArrayList<Vuurwerk>();_x000D_ _x000D_ System.out.println("Happy new year from: Burak, IS109, 500740123");_x000D_ _x000D_ stap1(pakket);_x000D_ stap2(pakket);_x000D_ stap3(pakket);_x000D_ stap4(pakket);_x000D_ stap5(pakket);_x000D_ stap6(pakket);_x000D_ }_x000D_ _x000D_ private static void stap1(ArrayList<Vuurwerk> pakket) {_x000D_ System.out.println("\n--- STAP 1 ---");_x000D_ _x000D_ Vuurwerk vuurwerk;_x000D_ _x000D_ vuurwerk = new Vuurwerk("Veiligheidsbril", 2.5,_x000D_ new Instructie(true, 6, "Draag bij aansteken"));_x000D_ pakket.add(vuurwerk);_x000D_ System.out.println(vuurwerk);_x000D_ _x000D_ vuurwerk = new Vuurwerk("Safety glass", 2.5,_x000D_ new Instructie(false, 6, "Wear before ignition"));_x000D_ pakket.add(vuurwerk);_x000D_ System.out.println(vuurwerk);_x000D_ _x000D_ vuurwerk = new Vuurwerk("Aansteeklont zonder instructie", 0.25, null);_x000D_ pakket.add(vuurwerk);_x000D_ System.out.println(vuurwerk);_x000D_ }_x000D_ _x000D_ private static void stap2(ArrayList<Vuurwerk> pakket) {_x000D_ System.out.println("\n--- STAP 2 ---");_x000D_ _x000D_ Knaller knaller;_x000D_ _x000D_ // knaller met Engelstalige instructie en 75 decibel_x000D_ knaller = new Knaller(777, 75, "Celebration Crackers", 10,_x000D_ new Instructie(false, 21, "Keep minimum 10 ft distance"));_x000D_ pakket.add(knaller);_x000D_ System.out.println(knaller);_x000D_ _x000D_ // knaller met Nederlandstalige instructie en 120 decibel_x000D_ knaller = new Knaller(500, 120, "Peking Rol", 45,_x000D_ new Instructie(true, 21, "Houd minimaal 5 meter afstand"));_x000D_ pakket.add(knaller);_x000D_ System.out.println(knaller);_x000D_ _x000D_ // knaller met Nederlandstalige instructie en 125 decibel_x000D_ knaller = new Knaller(1000, 125, "Shanghai Rol", 85,_x000D_ new Instructie(true, 21, "Houd minimaal 5 meter afstand"));_x000D_ pakket.add(knaller);_x000D_ System.out.println(knaller);_x000D_ _x000D_ // knaller zonder instructie en 100 decibel_x000D_ knaller = new Knaller(1000, 100, "Hongkong Rol", 82.5, null);_x000D_ pakket.add(knaller);_x000D_ System.out.println(knaller);_x000D_ }_x000D_ _x000D_ private static void stap3(ArrayList<Vuurwerk> pakket) {_x000D_ System.out.println("\n--- STAP 3 ---");_x000D_ _x000D_ Vuurpijl vuurpijl;_x000D_ _x000D_ // vuurpijl met Nederlandstalige instructie, correcte kleurverhouding, leeftijd 10_x000D_ vuurpijl = new Vuurpijl(40, new int[]{50, 25, 25}, "Cruise Rocket", 2.50,_x000D_ new Instructie(true, 10, "Niet in de hand houden"));_x000D_ pakket.add(vuurpijl);_x000D_ System.out.println(vuurpijl);_x000D_ _x000D_ // vuurpijl met Nederlandstalige instructie, incorrecte kleurverhouding, leeftijd 16_x000D_ vuurpijl = new Vuurpijl(40, new int[]{25, 30, 44}, "Killing Arrow", 4.25,_x000D_ new Instructie(true, 16, "Niet in de hand houden"));_x000D_ pakket.add(vuurpijl);_x000D_ System.out.println(vuurpijl);_x000D_ _x000D_ // vuurpijl met Engelstalige instructie, incorrecte kleurverhouding, leeftijd 20_x000D_ vuurpijl = new Vuurpijl(40, new int[]{50, 41, 10}, "Magic Sky", 2.75,_x000D_ new Instructie(false, 20, "Keep minimum 10 ft distance"));_x000D_ pakket.add(vuurpijl);_x000D_ System.out.println(vuurpijl);_x000D_ _x000D_ // vuurpijl zonder instructie, correcte kleurverhouding_x000D_ vuurpijl = new Vuurpijl(40, new int[]{50, 50, 0}, "Golden Sky", 3.25, null);_x000D_ pakket.add(vuurpijl);_x000D_ System.out.println(vuurpijl);_x000D_ }_x000D_ _x000D_ public static void stap4(ArrayList<Vuurwerk> pakket) {_x000D_ System.out.println("\n--- STAP 4 ---");_x000D_ toonVuurwerk(pakket);_x000D_ }_x000D_ _x000D_ private static void toonVuurwerk(ArrayList<Vuurwerk> pakket) {_x000D_ double totaalPrijs = 0;_x000D_ for (Vuurwerk i : pakket) { //loop door de array Vuurwerk_x000D_ totaalPrijs += i.getPrijs(); //totaalPrijs telt op i aantal keren met getPrijs_x000D_ System.out.println(i.toString()); //print al het vuurwerk_x000D_ }_x000D_ System.out.println("\n Kosten vuurwerkpakket: " + EURO + totaalPrijs); //print totaalprijs_x000D_ }_x000D_ _x000D_ private static void toonInstructies(ArrayList<Vuurwerk> pakket, int index) {_x000D_ if ((index >= 0) && (index < pakket.size())) { //als index binnen bereik is doe:_x000D_ if (pakket.get(index).getInstructie() != null) { //als getInstructie()<SUF> System.out.println(pakket.get(index).getInstructie()); //print de instructie voor opgegeven index_x000D_ } else {_x000D_ System.out.println("Instructie ontbreekt."); //als deze null is, print instructie ontbreekt_x000D_ }_x000D_ _x000D_ } else {_x000D_ System.out.println("Index valt buiten grenzen."); //als index buiten bereik is, print_x000D_ }_x000D_ }_x000D_ _x000D_ public static void stap5(ArrayList<Vuurwerk> pakket) {_x000D_ System.out.println("\n--- STAP 5 ---");_x000D_ toonInstructies(pakket, -1);_x000D_ toonInstructies(pakket, 3);_x000D_ toonInstructies(pakket, 10);_x000D_ toonInstructies(pakket, 11);_x000D_ }_x000D_ _x000D_ public static void stap6(ArrayList<Vuurwerk> pakket) {_x000D_ System.out.println("\n--- STAP 6 ---");_x000D_ _x000D_ printHardeKnallers(pakket, 100);_x000D_ }_x000D_ _x000D_ private static void printHardeKnallers(ArrayList<Vuurwerk> pakket, int maxDecibel) {_x000D_ for (Vuurwerk i : pakket) { //loop door de array_x000D_ if (i instanceof Knaller) { //gebruik instanceof om methodes van de subclass te kunnen gebruiken_x000D_ if (((Knaller) i).getDecibel() > maxDecibel) { //als getDecibel() groter is dan opgegeven maxDecibel_x000D_ System.out.println(i.toString()); //print de toString van i (index)_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_
True
2,729
19
3,011
19
2,922
18
3,010
19
3,171
20
false
false
false
false
false
true
4,596
46427_8
/** * Syncnapsis Framework - Copyright (c) 2012-2014 ultimate * * This program is free software; you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by the Free Software Foundation; either version * 3 of the License, or any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Plublic License along with this program; * if not, see <http://www.gnu.org/licenses/>. */ package com.syncnapsis.enums; import com.syncnapsis.constants.ApplicationBaseConstants; /** * Enum f�r die Spezifizierung des Alters eines News-Objekts. Bei der Suche nach * News kann ein EnumNewsAge-Objekt �bergeben werden und es werden alle News * zur�ckgeliefert, die neuer sind als das spezifizierte Alter. Die Aufl�sung * der Enum-Werte als Zeitangeben geschiet �ber die Tabelle Parameter und das * Namens-Pattern Constants.PARAM_NEWS_MAXAGE = "news.%L.maxAge" * * @author ultimate */ public enum EnumNewsAge { /** * Alters-Interval 1 (k�rzester Wert) */ length1, /** * Alters-Interval 2 (2. k�rzester Wert) */ length2, /** * Alters-Interval 3 */ length3, /** * Alters-Interval 4 */ length4, /** * Alters-Interval 5 */ length5, /** * Alters-Interval 6 */ length6, /** * Alters-Interval 7 */ length7, /** * Alters-Interval 8 (2. l�ngster Wert) */ length8, /** * Alters-Interval 9 (l�ngster Wert) */ length9; /** * Wandelt dieses Enum in einen Primary-Key f�r die Verwendung mit der * Parameter-Tabelle um. Es wird das Namens-Pattern * Constants.PARAM_NEWS_MAXAGE = "news.%L.maxAge" verwendet. * * @return der Parameter-Key zu diesem Enum zu diesem Enum */ public String getParameterKey() { return ApplicationBaseConstants.PARAM_NEWS_MAXAGE.getName().replace("%L", this.toString()); } }
ultimate/syncnapsis
syncnapsis-dev/syncnapsis-dev-archive/src/main/java/com/syncnapsis/enums/EnumNewsAge.java
718
/** * Alters-Interval 7 */
block_comment
nl
/** * Syncnapsis Framework - Copyright (c) 2012-2014 ultimate * * This program is free software; you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by the Free Software Foundation; either version * 3 of the License, or any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MECHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Plublic License along with this program; * if not, see <http://www.gnu.org/licenses/>. */ package com.syncnapsis.enums; import com.syncnapsis.constants.ApplicationBaseConstants; /** * Enum f�r die Spezifizierung des Alters eines News-Objekts. Bei der Suche nach * News kann ein EnumNewsAge-Objekt �bergeben werden und es werden alle News * zur�ckgeliefert, die neuer sind als das spezifizierte Alter. Die Aufl�sung * der Enum-Werte als Zeitangeben geschiet �ber die Tabelle Parameter und das * Namens-Pattern Constants.PARAM_NEWS_MAXAGE = "news.%L.maxAge" * * @author ultimate */ public enum EnumNewsAge { /** * Alters-Interval 1 (k�rzester Wert) */ length1, /** * Alters-Interval 2 (2. k�rzester Wert) */ length2, /** * Alters-Interval 3 */ length3, /** * Alters-Interval 4 */ length4, /** * Alters-Interval 5 */ length5, /** * Alters-Interval 6 */ length6, /** * Alters-Interval 7 <SUF>*/ length7, /** * Alters-Interval 8 (2. l�ngster Wert) */ length8, /** * Alters-Interval 9 (l�ngster Wert) */ length9; /** * Wandelt dieses Enum in einen Primary-Key f�r die Verwendung mit der * Parameter-Tabelle um. Es wird das Namens-Pattern * Constants.PARAM_NEWS_MAXAGE = "news.%L.maxAge" verwendet. * * @return der Parameter-Key zu diesem Enum zu diesem Enum */ public String getParameterKey() { return ApplicationBaseConstants.PARAM_NEWS_MAXAGE.getName().replace("%L", this.toString()); } }
False
581
12
652
11
648
12
652
11
736
13
false
false
false
false
false
true
2,038
60696_0
package uml.about; import javax.xml.bind.annotation.XmlRootElement; /** * Amory Hoste * Houdt informatie bij over de applicatie (ingelezen mbv JAXB uit config.xml) */ @XmlRootElement public class Config { private String email; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } private String version; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } private String info; public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } }
amohoste/UML-Editor
src/uml/about/Config.java
201
/** * Amory Hoste * Houdt informatie bij over de applicatie (ingelezen mbv JAXB uit config.xml) */
block_comment
nl
package uml.about; import javax.xml.bind.annotation.XmlRootElement; /** * Amory Hoste <SUF>*/ @XmlRootElement public class Config { private String email; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } private String version; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } private String info; public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } }
True
151
29
180
32
189
31
180
32
214
36
false
false
false
false
false
true
1,613
33116_18
package be.uantwerpen.sc.services; import be.uantwerpen.sc.models.*; import be.uantwerpen.sc.models.jobs.Job; import be.uantwerpen.sc.models.map.Link; import be.uantwerpen.sc.models.map.Map; import be.uantwerpen.sc.models.map.MapPoint; import be.uantwerpen.sc.repositories.LinkRepository; import be.uantwerpen.sc.repositories.MapPointRepository; import be.uantwerpen.sc.repositories.TransitPointRepository; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; @Service public class PathService { private static final Logger logger = LoggerFactory.getLogger(PathService.class); @Autowired LinkRepository linkRepository; @Autowired MapPointRepository mapPointRepository; @Autowired BackendInfoService backendInfoService; @Autowired BackendService backendService; @Autowired LinkService linkService; @Value("${backends.enabled}") boolean backendsEnabled; public PathService(){ } public Path makePathFromPointPairs(Integer[] pointpairs, int userStartPid, int startMapId, int stopPid, int stopMapId){ Path path = new Path(); ArrayList<Link> transitPath = new ArrayList<Link>(); logger.info("--- determining new path ---"); // Check if the starting point of path is the same as the point where the user wants to depart from int userStartId = mapPointRepository.findByPointIdAndMap_Id(userStartPid,startMapId).getId(); if(userStartId != pointpairs[0]){ logger.info("Startpoint is on the same map: First Job is within the staring map"); // int userPid = transitPointService.getPointWithId(userStartId).getPid(); // redundant call to get userStartPid BackendInfo mapInfo = backendInfoService.getInfoByMapId(startMapId); int botStartPid = mapPointRepository.findById(pointpairs[0]).getPointId(); float weight = backendService.getWeight(mapInfo, userStartPid, botStartPid); //float weight = 10; path.addWeight(weight); path.addJob(userStartPid, botStartPid, startMapId,weight); } String linkLog = "TransitLink ids: "; // traverse points two by two and determine the weights between them for(int i = 0; i < pointpairs.length; i+=2){ int startId = pointpairs[i]; int stopId = pointpairs[i+1]; MapPoint startPoint = mapPointRepository.findById(startId); MapPoint stopPoint = mapPointRepository.findById(stopId); if(startPoint.getMapId() != stopPoint.getMapId()){ logger.info("current points " + startId + "," + stopId + ", part of a transit link" ); Link link = linkService.getLinkWithStartidAndStopid(startId,stopId); // check if the transitlink exists with start and stopid in different order if(link == null) { link = linkService.getLinkWithStartidAndStopid(stopId, startId); } linkLog+= link.getId() + "-"; transitPath.add(link); }else{ logger.info("current points " + startId + "," + stopId + ", part of a inner map link" ); BackendInfo mapInfo = backendInfoService.getInfoByMapId(stopPoint.getMapId()); float weight = backendService.getWeight(mapInfo, startPoint.getPointId(), stopPoint.getPointId()); // // Request weight between points from backend // String url = "http://" + mapinfo.getHostname() + ":" + mapinfo.getPort() + "/" + startPoint.getPid() + "/" + stopPoint.getPid(); // logger.info("--requesting from cost from:+" + url); // // int weight = 1; // if(backendsEnabled) { // JSONObject response = backendService.requestJsonObject(url); // System.out.println("response: " + response.toString()); // weight = Integer.parseInt(response.get("cost").toString()); // }else { // weight = (int)(Math.random() * 10); // to test wo/ backends // } logger.info("--got weight: " + weight); // Add the inner weights that the map calculated path.addWeight(weight); // add a new job to the path Job job = new Job((long) startPoint.getPointId(), (long) stopPoint.getPointId(), mapInfo.getMapId(),weight); path.addJob(job); } } // TODO check if the endpoint is in the endpoint map int lastIndex = pointpairs.length -1; int destinationId = mapPointRepository.findByPointIdAndMap_Id(stopPid, stopMapId).getId(); if(destinationId != pointpairs[lastIndex]){ logger.info("EndPoint is on the same map: Last Job is within the end map"); // int userPid = transitPointService.getPointWithId(userStartId).getPid(); // redundant call to get userStartPid BackendInfo mapInfo = backendInfoService.getInfoByMapId(stopMapId); int lastTransitPid = mapPointRepository.findById(pointpairs[lastIndex]).getPointId(); // TODO get the internal cost by, identify by mapid float weight = backendService.getWeight(mapInfo, lastTransitPid, stopPid); path.addWeight(weight); path.addJob(lastTransitPid, stopPid, stopMapId ,weight); } path.setTransitPath(transitPath); logger.info(linkLog); path.addWeight(path.getTotalTransitWeight()); return path; } // Eerst gaf de A* service de paden door in de vorm van een array van linkids. Hier ontstand het probleem dat we onmogelijk de richting konden bepalen // daarom is er overgegaan op point ids op volgorde . @Deprecated public Path makePathFromLinkIds(Integer[] linkids, int startpid, int startmapid){ String linkLog = "Links: "; Path path = new Path(); ArrayList<Link> transitPath = new ArrayList<Link>(); // Get a the full TranistLink Objects for (int i = 0; i < linkids.length; i++) { int linkId = linkids[i]; linkLog += linkId+","; Link transitLink = linkService.getLinkWithId(linkId); transitPath.add(transitLink); } logger.info(linkLog); path.setTransitPath(transitPath); // check if there needs to be a job from the starting pid to a point on the same map. int firstStartid = transitPath.get(0).getPointA(); MapPoint userStartPoint = mapPointRepository.findByPointIdAndMap_Id(startpid, startmapid); // if the starting id is not equal to the path's starting point id where the user wants to depart from: if(firstStartid != userStartPoint.getId()){ logger.info("-startpoint on same map: TODO GET THE COST "); // TODO request cost of navigation to point on same map // TODO better naming int startLinkPid = mapPointRepository.findById(firstStartid).getPointId(); path.addJob(startpid, startLinkPid, startmapid ,1); } // construct path object // Get the combined weight of the inner map links on the route // add these to the path object together with the topmap weights int length = transitPath.size() -1; logger.info("length " + length); for (int i = 0; i < length; i++) { // endpoint of one link and startpoint of second link should be on the same map int stopid = transitPath.get(i).getPointB(); int startid = transitPath.get(i+1).getPointA(); logger.info("-handling link" + stopid +"-"+ startid); // Check if the startpoint of the optimal path is another point on the same map, // -> if so dispatch first jobfrom the current point to the path // get points of link from database MapPoint stopPoint = mapPointRepository.findById(stopid); MapPoint startPoint = mapPointRepository.findById(startid); // TODO check if points belong to the same map // TODO build in check for flagpoints (destination) and handle accordingly // Get the connection info of the map where the points belong to BackendInfo mapInfo = backendInfoService.getInfoByMapId(stopPoint.getMapId()); float weight = backendService.getWeight(mapInfo, stopPoint.getPointId(), startPoint.getPointId()); // // Request weight between points from backend // String url = "http://" + mapinfo.getHostname() + ":" + mapinfo.getPort() + "/" + stopPoint.getPid() + "/" + startPoint.getPid(); // logger.info("--requesting from cost from:+" + url); // // int weight = 1; // if(backendsEnabled) { // // JSONObject response = backendService.requestJsonObject(url); // System.out.println("response: " + response.toString()); // weight = Integer.parseInt(response.get("cost").toString()); // }else { // weight = (int)(Math.random() * 10); // to test wo/ backends // } // logger.info("--got weight: " + weight); // Add the inner weights that the map calculated path.addWeight(weight); // add a new job to the path Job job = new Job((long) startPoint.getPointId(), (long) stopPoint.getPointId(), mapInfo.getMapId(),weight); path.addJob(job); } // add the total weight of the transitlinks, now we have the complete weight of the path path.addWeight(path.getTotalTransitWeight()); return path; } }
SmartCity-UAntwerpen/SmartCityBackbone
SmartCity Core/src/main/java/be/uantwerpen/sc/services/PathService.java
2,727
// Eerst gaf de A* service de paden door in de vorm van een array van linkids. Hier ontstand het probleem dat we onmogelijk de richting konden bepalen
line_comment
nl
package be.uantwerpen.sc.services; import be.uantwerpen.sc.models.*; import be.uantwerpen.sc.models.jobs.Job; import be.uantwerpen.sc.models.map.Link; import be.uantwerpen.sc.models.map.Map; import be.uantwerpen.sc.models.map.MapPoint; import be.uantwerpen.sc.repositories.LinkRepository; import be.uantwerpen.sc.repositories.MapPointRepository; import be.uantwerpen.sc.repositories.TransitPointRepository; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; @Service public class PathService { private static final Logger logger = LoggerFactory.getLogger(PathService.class); @Autowired LinkRepository linkRepository; @Autowired MapPointRepository mapPointRepository; @Autowired BackendInfoService backendInfoService; @Autowired BackendService backendService; @Autowired LinkService linkService; @Value("${backends.enabled}") boolean backendsEnabled; public PathService(){ } public Path makePathFromPointPairs(Integer[] pointpairs, int userStartPid, int startMapId, int stopPid, int stopMapId){ Path path = new Path(); ArrayList<Link> transitPath = new ArrayList<Link>(); logger.info("--- determining new path ---"); // Check if the starting point of path is the same as the point where the user wants to depart from int userStartId = mapPointRepository.findByPointIdAndMap_Id(userStartPid,startMapId).getId(); if(userStartId != pointpairs[0]){ logger.info("Startpoint is on the same map: First Job is within the staring map"); // int userPid = transitPointService.getPointWithId(userStartId).getPid(); // redundant call to get userStartPid BackendInfo mapInfo = backendInfoService.getInfoByMapId(startMapId); int botStartPid = mapPointRepository.findById(pointpairs[0]).getPointId(); float weight = backendService.getWeight(mapInfo, userStartPid, botStartPid); //float weight = 10; path.addWeight(weight); path.addJob(userStartPid, botStartPid, startMapId,weight); } String linkLog = "TransitLink ids: "; // traverse points two by two and determine the weights between them for(int i = 0; i < pointpairs.length; i+=2){ int startId = pointpairs[i]; int stopId = pointpairs[i+1]; MapPoint startPoint = mapPointRepository.findById(startId); MapPoint stopPoint = mapPointRepository.findById(stopId); if(startPoint.getMapId() != stopPoint.getMapId()){ logger.info("current points " + startId + "," + stopId + ", part of a transit link" ); Link link = linkService.getLinkWithStartidAndStopid(startId,stopId); // check if the transitlink exists with start and stopid in different order if(link == null) { link = linkService.getLinkWithStartidAndStopid(stopId, startId); } linkLog+= link.getId() + "-"; transitPath.add(link); }else{ logger.info("current points " + startId + "," + stopId + ", part of a inner map link" ); BackendInfo mapInfo = backendInfoService.getInfoByMapId(stopPoint.getMapId()); float weight = backendService.getWeight(mapInfo, startPoint.getPointId(), stopPoint.getPointId()); // // Request weight between points from backend // String url = "http://" + mapinfo.getHostname() + ":" + mapinfo.getPort() + "/" + startPoint.getPid() + "/" + stopPoint.getPid(); // logger.info("--requesting from cost from:+" + url); // // int weight = 1; // if(backendsEnabled) { // JSONObject response = backendService.requestJsonObject(url); // System.out.println("response: " + response.toString()); // weight = Integer.parseInt(response.get("cost").toString()); // }else { // weight = (int)(Math.random() * 10); // to test wo/ backends // } logger.info("--got weight: " + weight); // Add the inner weights that the map calculated path.addWeight(weight); // add a new job to the path Job job = new Job((long) startPoint.getPointId(), (long) stopPoint.getPointId(), mapInfo.getMapId(),weight); path.addJob(job); } } // TODO check if the endpoint is in the endpoint map int lastIndex = pointpairs.length -1; int destinationId = mapPointRepository.findByPointIdAndMap_Id(stopPid, stopMapId).getId(); if(destinationId != pointpairs[lastIndex]){ logger.info("EndPoint is on the same map: Last Job is within the end map"); // int userPid = transitPointService.getPointWithId(userStartId).getPid(); // redundant call to get userStartPid BackendInfo mapInfo = backendInfoService.getInfoByMapId(stopMapId); int lastTransitPid = mapPointRepository.findById(pointpairs[lastIndex]).getPointId(); // TODO get the internal cost by, identify by mapid float weight = backendService.getWeight(mapInfo, lastTransitPid, stopPid); path.addWeight(weight); path.addJob(lastTransitPid, stopPid, stopMapId ,weight); } path.setTransitPath(transitPath); logger.info(linkLog); path.addWeight(path.getTotalTransitWeight()); return path; } // Eerst gaf<SUF> // daarom is er overgegaan op point ids op volgorde . @Deprecated public Path makePathFromLinkIds(Integer[] linkids, int startpid, int startmapid){ String linkLog = "Links: "; Path path = new Path(); ArrayList<Link> transitPath = new ArrayList<Link>(); // Get a the full TranistLink Objects for (int i = 0; i < linkids.length; i++) { int linkId = linkids[i]; linkLog += linkId+","; Link transitLink = linkService.getLinkWithId(linkId); transitPath.add(transitLink); } logger.info(linkLog); path.setTransitPath(transitPath); // check if there needs to be a job from the starting pid to a point on the same map. int firstStartid = transitPath.get(0).getPointA(); MapPoint userStartPoint = mapPointRepository.findByPointIdAndMap_Id(startpid, startmapid); // if the starting id is not equal to the path's starting point id where the user wants to depart from: if(firstStartid != userStartPoint.getId()){ logger.info("-startpoint on same map: TODO GET THE COST "); // TODO request cost of navigation to point on same map // TODO better naming int startLinkPid = mapPointRepository.findById(firstStartid).getPointId(); path.addJob(startpid, startLinkPid, startmapid ,1); } // construct path object // Get the combined weight of the inner map links on the route // add these to the path object together with the topmap weights int length = transitPath.size() -1; logger.info("length " + length); for (int i = 0; i < length; i++) { // endpoint of one link and startpoint of second link should be on the same map int stopid = transitPath.get(i).getPointB(); int startid = transitPath.get(i+1).getPointA(); logger.info("-handling link" + stopid +"-"+ startid); // Check if the startpoint of the optimal path is another point on the same map, // -> if so dispatch first jobfrom the current point to the path // get points of link from database MapPoint stopPoint = mapPointRepository.findById(stopid); MapPoint startPoint = mapPointRepository.findById(startid); // TODO check if points belong to the same map // TODO build in check for flagpoints (destination) and handle accordingly // Get the connection info of the map where the points belong to BackendInfo mapInfo = backendInfoService.getInfoByMapId(stopPoint.getMapId()); float weight = backendService.getWeight(mapInfo, stopPoint.getPointId(), startPoint.getPointId()); // // Request weight between points from backend // String url = "http://" + mapinfo.getHostname() + ":" + mapinfo.getPort() + "/" + stopPoint.getPid() + "/" + startPoint.getPid(); // logger.info("--requesting from cost from:+" + url); // // int weight = 1; // if(backendsEnabled) { // // JSONObject response = backendService.requestJsonObject(url); // System.out.println("response: " + response.toString()); // weight = Integer.parseInt(response.get("cost").toString()); // }else { // weight = (int)(Math.random() * 10); // to test wo/ backends // } // logger.info("--got weight: " + weight); // Add the inner weights that the map calculated path.addWeight(weight); // add a new job to the path Job job = new Job((long) startPoint.getPointId(), (long) stopPoint.getPointId(), mapInfo.getMapId(),weight); path.addJob(job); } // add the total weight of the transitlinks, now we have the complete weight of the path path.addWeight(path.getTotalTransitWeight()); return path; } }
True
2,149
45
2,399
47
2,482
36
2,399
47
2,726
43
false
false
false
false
false
true
534
200231_39
/** * Copyright (c) 2010-2016 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.novelanheatpump; import org.openhab.core.items.Item; import org.openhab.core.library.items.NumberItem; import org.openhab.core.library.items.StringItem; /** * Represents all valid commands which could be processed by this binding * * @author Jan-Philipp Bolle * @since 1.0.0 */ public enum HeatpumpCommandType { // in german Außentemperatur TYPE_TEMPERATURE_OUTSIDE { { command = "temperature_outside"; itemClass = NumberItem.class; } }, // in german Außentemperatur TYPE_TEMPERATURE_OUTSIDE_AVG { { command = "temperature_outside_avg"; itemClass = NumberItem.class; } }, // in german Rücklauf TYPE_TEMPERATURE_RETURN { { command = "temperature_return"; itemClass = NumberItem.class; } }, // in german Rücklauf Soll TYPE_TEMPERATURE_REFERENCE_RETURN { { command = "temperature_reference_return"; itemClass = NumberItem.class; } }, // in german Vorlauf TYPE_TEMPERATURE_SUPPLAY { { command = "temperature_supplay"; itemClass = NumberItem.class; } }, // in german Brauchwasser Soll TYPE_TEMPERATURE_SERVICEWATER_REFERENCE { { command = "temperature_servicewater_reference"; itemClass = NumberItem.class; } }, // in german Brauchwasser Ist TYPE_TEMPERATURE_SERVICEWATER { { command = "temperature_servicewater"; itemClass = NumberItem.class; } }, TYPE_HEATPUMP_STATE { { command = "state"; itemClass = StringItem.class; } }, TYPE_HEATPUMP_EXTENDED_STATE { { command = "extended_state"; itemClass = StringItem.class; } }, TYPE_HEATPUMP_SOLAR_COLLECTOR { { command = "temperature_solar_collector"; itemClass = NumberItem.class; } }, // in german Temperatur Heissgas TYPE_TEMPERATURE_HOT_GAS { { command = "temperature_hot_gas"; itemClass = NumberItem.class; } }, // in german Sondentemperatur WP Eingang TYPE_TEMPERATURE_PROBE_IN { { command = "temperature_probe_in"; itemClass = NumberItem.class; } }, // in german Sondentemperatur WP Ausgang TYPE_TEMPERATURE_PROBE_OUT { { command = "temperature_probe_out"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 IST TYPE_TEMPERATURE_MK1 { { command = "temperature_mk1"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 SOLL TYPE_TEMPERATURE_MK1_REFERENCE { { command = "temperature_mk1_reference"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 IST TYPE_TEMPERATURE_MK2 { { command = "temperature_mk2"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 SOLL TYPE_TEMPERATURE_MK2_REFERENCE { { command = "temperature_mk2_reference"; itemClass = NumberItem.class; } }, // in german Temperatur externe Energiequelle TYPE_TEMPERATURE_EXTERNAL_SOURCE { { command = "temperature_external_source"; itemClass = NumberItem.class; } }, // in german Betriebsstunden Verdichter1 TYPE_HOURS_COMPRESSOR1 { { command = "hours_compressor1"; itemClass = StringItem.class; } }, // in german Impulse (Starts) Verdichter 1 TYPE_STARTS_COMPRESSOR1 { { command = "starts_compressor1"; itemClass = NumberItem.class; } }, // in german Betriebsstunden Verdichter2 TYPE_HOURS_COMPRESSOR2 { { command = "hours_compressor2"; itemClass = StringItem.class; } }, // in german Impulse (Starts) Verdichter 2 TYPE_STARTS_COMPRESSOR2 { { command = "starts_compressor2"; itemClass = NumberItem.class; } }, // Temperatur_TRL_ext TYPE_TEMPERATURE_OUT_EXTERNAL { { command = "temperature_out_external"; itemClass = NumberItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE1 { { command = "hours_zwe1"; itemClass = StringItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE2 { { command = "hours_zwe2"; itemClass = StringItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE3 { { command = "hours_zwe3"; itemClass = StringItem.class; } }, // in german Betriebsstunden Wärmepumpe TYPE_HOURS_HETPUMP { { command = "hours_heatpump"; itemClass = StringItem.class; } }, // in german Betriebsstunden Heizung TYPE_HOURS_HEATING { { command = "hours_heating"; itemClass = StringItem.class; } }, // in german Betriebsstunden Brauchwasser TYPE_HOURS_WARMWATER { { command = "hours_warmwater"; itemClass = StringItem.class; } }, // in german Betriebsstunden Brauchwasser TYPE_HOURS_COOLING { { command = "hours_cooling"; itemClass = StringItem.class; } }, // in german Waermemenge Heizung TYPE_THERMALENERGY_HEATING { { command = "thermalenergy_heating"; itemClass = NumberItem.class; } }, // in german Waermemenge Brauchwasser TYPE_THERMALENERGY_WARMWATER { { command = "thermalenergy_warmwater"; itemClass = NumberItem.class; } }, // in german Waermemenge Schwimmbad TYPE_THERMALENERGY_POOL { { command = "thermalenergy_pool"; itemClass = NumberItem.class; } }, // in german Waermemenge gesamt seit Reset TYPE_THERMALENERGY_TOTAL { { command = "thermalenergy_total"; itemClass = NumberItem.class; } }, // in german Massentrom TYPE_MASSFLOW { { command = "massflow"; itemClass = NumberItem.class; } }, TYPE_HEATPUMP_SOLAR_STORAGE { { command = "temperature_solar_storage"; itemClass = NumberItem.class; } }, // in german Heizung Betriebsart TYPE_HEATING_OPERATION_MODE { { command = "heating_operation_mode"; itemClass = NumberItem.class; } }, // in german Heizung Temperatur (Parallelverschiebung) TYPE_HEATING_TEMPERATURE { { command = "heating_temperature"; itemClass = NumberItem.class; } }, // in german Warmwasser Betriebsart TYPE_WARMWATER_OPERATION_MODE { { command = "warmwater_operation_mode"; itemClass = NumberItem.class; } }, // in german Warmwasser Temperatur TYPE_WARMWATER_TEMPERATURE { { command = "warmwater_temperature"; itemClass = NumberItem.class; } }, // in german Comfort Kühlung Betriebsart TYPE_COOLING_OPERATION_MODE { { command = "cooling_operation_mode"; itemClass = NumberItem.class; } }, // in german Comfort Kühlung AT-Freigabe TYPE_COOLING_RELEASE_TEMPERATURE { { command = "cooling_release_temperature"; itemClass = NumberItem.class; } }, // in german Solltemp MK1 TYPE_COOLING_INLET_TEMP { { command = "cooling_inlet_temperature"; itemClass = NumberItem.class; } }, // in german AT-Überschreitung TYPE_COOLING_START_AFTER_HOURS { { command = "cooling_start_hours"; itemClass = NumberItem.class; } }, // in german AT-Unterschreitung TYPE_COOLING_STOP_AFTER_HOURS { { command = "cooling_stop_hours"; itemClass = NumberItem.class; } }; /** Represents the heatpump command as it will be used in *.items configuration */ String command; Class<? extends Item> itemClass; public String getCommand() { return command; } public Class<? extends Item> getItemClass() { return itemClass; } /** * * @param bindingConfig command string e.g. state, temperature_solar_storage,.. * @param itemClass class to validate * @return true if item class can bound to heatpumpCommand */ public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) { boolean ret = false; for (HeatpumpCommandType c : HeatpumpCommandType.values()) { if (c.getCommand().equals(bindingConfig.getCommand()) && c.getItemClass().equals(itemClass)) { ret = true; break; } } return ret; } public static HeatpumpCommandType fromString(String heatpumpCommand) { if ("".equals(heatpumpCommand)) { return null; } for (HeatpumpCommandType c : HeatpumpCommandType.values()) { if (c.getCommand().equals(heatpumpCommand)) { return c; } } throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '" + heatpumpCommand + "'"); } }
FlorianSW/openhab
bundles/binding/org.openhab.binding.novelanheatpump/src/main/java/org/openhab/binding/novelanheatpump/HeatpumpCommandType.java
3,172
// in german Solltemp MK1
line_comment
nl
/** * Copyright (c) 2010-2016 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.novelanheatpump; import org.openhab.core.items.Item; import org.openhab.core.library.items.NumberItem; import org.openhab.core.library.items.StringItem; /** * Represents all valid commands which could be processed by this binding * * @author Jan-Philipp Bolle * @since 1.0.0 */ public enum HeatpumpCommandType { // in german Außentemperatur TYPE_TEMPERATURE_OUTSIDE { { command = "temperature_outside"; itemClass = NumberItem.class; } }, // in german Außentemperatur TYPE_TEMPERATURE_OUTSIDE_AVG { { command = "temperature_outside_avg"; itemClass = NumberItem.class; } }, // in german Rücklauf TYPE_TEMPERATURE_RETURN { { command = "temperature_return"; itemClass = NumberItem.class; } }, // in german Rücklauf Soll TYPE_TEMPERATURE_REFERENCE_RETURN { { command = "temperature_reference_return"; itemClass = NumberItem.class; } }, // in german Vorlauf TYPE_TEMPERATURE_SUPPLAY { { command = "temperature_supplay"; itemClass = NumberItem.class; } }, // in german Brauchwasser Soll TYPE_TEMPERATURE_SERVICEWATER_REFERENCE { { command = "temperature_servicewater_reference"; itemClass = NumberItem.class; } }, // in german Brauchwasser Ist TYPE_TEMPERATURE_SERVICEWATER { { command = "temperature_servicewater"; itemClass = NumberItem.class; } }, TYPE_HEATPUMP_STATE { { command = "state"; itemClass = StringItem.class; } }, TYPE_HEATPUMP_EXTENDED_STATE { { command = "extended_state"; itemClass = StringItem.class; } }, TYPE_HEATPUMP_SOLAR_COLLECTOR { { command = "temperature_solar_collector"; itemClass = NumberItem.class; } }, // in german Temperatur Heissgas TYPE_TEMPERATURE_HOT_GAS { { command = "temperature_hot_gas"; itemClass = NumberItem.class; } }, // in german Sondentemperatur WP Eingang TYPE_TEMPERATURE_PROBE_IN { { command = "temperature_probe_in"; itemClass = NumberItem.class; } }, // in german Sondentemperatur WP Ausgang TYPE_TEMPERATURE_PROBE_OUT { { command = "temperature_probe_out"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 IST TYPE_TEMPERATURE_MK1 { { command = "temperature_mk1"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 SOLL TYPE_TEMPERATURE_MK1_REFERENCE { { command = "temperature_mk1_reference"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 IST TYPE_TEMPERATURE_MK2 { { command = "temperature_mk2"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 SOLL TYPE_TEMPERATURE_MK2_REFERENCE { { command = "temperature_mk2_reference"; itemClass = NumberItem.class; } }, // in german Temperatur externe Energiequelle TYPE_TEMPERATURE_EXTERNAL_SOURCE { { command = "temperature_external_source"; itemClass = NumberItem.class; } }, // in german Betriebsstunden Verdichter1 TYPE_HOURS_COMPRESSOR1 { { command = "hours_compressor1"; itemClass = StringItem.class; } }, // in german Impulse (Starts) Verdichter 1 TYPE_STARTS_COMPRESSOR1 { { command = "starts_compressor1"; itemClass = NumberItem.class; } }, // in german Betriebsstunden Verdichter2 TYPE_HOURS_COMPRESSOR2 { { command = "hours_compressor2"; itemClass = StringItem.class; } }, // in german Impulse (Starts) Verdichter 2 TYPE_STARTS_COMPRESSOR2 { { command = "starts_compressor2"; itemClass = NumberItem.class; } }, // Temperatur_TRL_ext TYPE_TEMPERATURE_OUT_EXTERNAL { { command = "temperature_out_external"; itemClass = NumberItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE1 { { command = "hours_zwe1"; itemClass = StringItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE2 { { command = "hours_zwe2"; itemClass = StringItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE3 { { command = "hours_zwe3"; itemClass = StringItem.class; } }, // in german Betriebsstunden Wärmepumpe TYPE_HOURS_HETPUMP { { command = "hours_heatpump"; itemClass = StringItem.class; } }, // in german Betriebsstunden Heizung TYPE_HOURS_HEATING { { command = "hours_heating"; itemClass = StringItem.class; } }, // in german Betriebsstunden Brauchwasser TYPE_HOURS_WARMWATER { { command = "hours_warmwater"; itemClass = StringItem.class; } }, // in german Betriebsstunden Brauchwasser TYPE_HOURS_COOLING { { command = "hours_cooling"; itemClass = StringItem.class; } }, // in german Waermemenge Heizung TYPE_THERMALENERGY_HEATING { { command = "thermalenergy_heating"; itemClass = NumberItem.class; } }, // in german Waermemenge Brauchwasser TYPE_THERMALENERGY_WARMWATER { { command = "thermalenergy_warmwater"; itemClass = NumberItem.class; } }, // in german Waermemenge Schwimmbad TYPE_THERMALENERGY_POOL { { command = "thermalenergy_pool"; itemClass = NumberItem.class; } }, // in german Waermemenge gesamt seit Reset TYPE_THERMALENERGY_TOTAL { { command = "thermalenergy_total"; itemClass = NumberItem.class; } }, // in german Massentrom TYPE_MASSFLOW { { command = "massflow"; itemClass = NumberItem.class; } }, TYPE_HEATPUMP_SOLAR_STORAGE { { command = "temperature_solar_storage"; itemClass = NumberItem.class; } }, // in german Heizung Betriebsart TYPE_HEATING_OPERATION_MODE { { command = "heating_operation_mode"; itemClass = NumberItem.class; } }, // in german Heizung Temperatur (Parallelverschiebung) TYPE_HEATING_TEMPERATURE { { command = "heating_temperature"; itemClass = NumberItem.class; } }, // in german Warmwasser Betriebsart TYPE_WARMWATER_OPERATION_MODE { { command = "warmwater_operation_mode"; itemClass = NumberItem.class; } }, // in german Warmwasser Temperatur TYPE_WARMWATER_TEMPERATURE { { command = "warmwater_temperature"; itemClass = NumberItem.class; } }, // in german Comfort Kühlung Betriebsart TYPE_COOLING_OPERATION_MODE { { command = "cooling_operation_mode"; itemClass = NumberItem.class; } }, // in german Comfort Kühlung AT-Freigabe TYPE_COOLING_RELEASE_TEMPERATURE { { command = "cooling_release_temperature"; itemClass = NumberItem.class; } }, // in german<SUF> TYPE_COOLING_INLET_TEMP { { command = "cooling_inlet_temperature"; itemClass = NumberItem.class; } }, // in german AT-Überschreitung TYPE_COOLING_START_AFTER_HOURS { { command = "cooling_start_hours"; itemClass = NumberItem.class; } }, // in german AT-Unterschreitung TYPE_COOLING_STOP_AFTER_HOURS { { command = "cooling_stop_hours"; itemClass = NumberItem.class; } }; /** Represents the heatpump command as it will be used in *.items configuration */ String command; Class<? extends Item> itemClass; public String getCommand() { return command; } public Class<? extends Item> getItemClass() { return itemClass; } /** * * @param bindingConfig command string e.g. state, temperature_solar_storage,.. * @param itemClass class to validate * @return true if item class can bound to heatpumpCommand */ public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) { boolean ret = false; for (HeatpumpCommandType c : HeatpumpCommandType.values()) { if (c.getCommand().equals(bindingConfig.getCommand()) && c.getItemClass().equals(itemClass)) { ret = true; break; } } return ret; } public static HeatpumpCommandType fromString(String heatpumpCommand) { if ("".equals(heatpumpCommand)) { return null; } for (HeatpumpCommandType c : HeatpumpCommandType.values()) { if (c.getCommand().equals(heatpumpCommand)) { return c; } } throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '" + heatpumpCommand + "'"); } }
False
2,378
8
2,653
10
2,724
7
2,653
10
3,306
10
false
false
false
false
false
true
1,422
4799_5
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class MyWorld extends World { private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public MyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(800, 600, 1, false); this.setBackground("startScreen.jpg"); //startScreen(); TileEngine te = new TileEngine(this, 60, 60); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); prepare(); } public void act() { ce.update(); } /** * Prepare the world for the start of the program. * That is: create the initial objects and add them to the world. */ private void prepare() { StartPlay startPlay = new StartPlay(); addObject(startPlay,414,314); removeObject(startPlay); StartPlay startPlay2 = new StartPlay(); addObject(startPlay2,402,305); } }
ROCMondriaanTIN/project-greenfoot-game-velocida
MyWorld.java
563
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class MyWorld extends World { private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public MyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(800, 600, 1, false); this.setBackground("startScreen.jpg"); //startScreen(); TileEngine te = new TileEngine(this, 60, 60); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de<SUF> Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); prepare(); } public void act() { ce.update(); } /** * Prepare the world for the start of the program. * That is: create the initial objects and add them to the world. */ private void prepare() { StartPlay startPlay = new StartPlay(); addObject(startPlay,414,314); removeObject(startPlay); StartPlay startPlay2 = new StartPlay(); addObject(startPlay2,402,305); } }
True
507
21
544
24
538
15
544
24
605
24
false
false
false
false
false
true
4,348
186096_2
package studentpersist.gui; import studentpersist.application.controller.Controller; import studentpersist.application.model.Student; import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class StartWindow extends Application { @Override public void start(Stage stage) { stage.setTitle("Administrer studerende"); GridPane pane = new GridPane(); this.initContent(pane); Scene scene = new Scene(pane); stage.setScene(scene); stage.show(); } // ------------------------------------------------------------------------- private TextField txfName; private CheckBox chkActive; private ListView<Student> lvwStudents; private Button btnAdd; private Button btnSave; private Button btnDelete; private Controller controller; private void initContent(GridPane pane) { controller = Controller.getController(); controller.loadStorage(); // show or hide grid lines pane.setGridLinesVisible(false); // set padding of the pane pane.setPadding(new Insets(20)); // set horizontal gap between components pane.setHgap(10); // set vertical gap between components pane.setVgap(10); Label lblName = new Label("Navn"); pane.add(lblName, 1, 1); Label lblActive = new Label("Aktiv"); pane.add(lblActive, 1, 3); txfName = new TextField(); pane.add(txfName, 2, 1, 4, 1); chkActive = new CheckBox(); pane.add(chkActive, 2, 3); // add a buttons to the pane btnAdd = new Button("Opret"); pane.add(btnAdd, 1, 5); btnSave = new Button("Gem"); btnSave.setDisable(true); pane.add(btnSave, 2, 5); btnDelete = new Button("Slet"); pane.add(btnDelete, 3, 5); btnDelete.setDisable(true); // connect a method to the button btnAdd.setOnAction(event -> addAction()); btnSave.setOnAction(event -> saveAction()); btnDelete.setOnAction(event -> deleteAction()); lvwStudents = new ListView<>(); pane.add(lvwStudents, 0, 1, 1, 3); lvwStudents.setPrefWidth(250); lvwStudents.setPrefHeight(200); lvwStudents.getItems().setAll(controller.getStudents()); ChangeListener<Student> listener = (ov, oldCompny, newCompany) -> selectedStudentChanged(); lvwStudents.getSelectionModel().selectedItemProperty().addListener(listener); } @Override public void stop() { controller.saveStorage(); } /** * This class controls access to the model in this application. In this * case, the model is a single Student object. */ private Student studerende = null; private void addAction() { studerende = controller.createStudent(txfName.getText().trim(), 20, chkActive.isSelected()); clearFields(); btnAdd.setDisable(true); lvwStudents.getItems().setAll(controller.getStudents()); } private void saveAction() { if (studerende != null) { controller.updateStudent(studerende, txfName.getText().trim(), 20, chkActive.isSelected()); clearFields(); btnSave.setDisable(true); btnDelete.setDisable(true); lvwStudents.getItems().setAll(controller.getStudents()); } } private void deleteAction() { if (studerende != null) { controller.deleteStudent(studerende); studerende = null; clearFields(); btnDelete.setDisable(true); btnSave.setDisable(true); btnAdd.setDisable(false); lvwStudents.getItems().setAll(controller.getStudents()); } } private void clearFields() { txfName.clear(); chkActive.setSelected(false); } private void selectedStudentChanged() { studerende = lvwStudents.getSelectionModel().getSelectedItem(); if (studerende != null) { txfName.setText(studerende.getName()); chkActive.setSelected(studerende.isActive()); btnSave.setDisable(false); btnDelete.setDisable(false); } } }
soenderstrup/PRO2
14_ArchLayers&Serializable/src/studentpersist/gui/StartWindow.java
1,377
// set horizontal gap between components
line_comment
nl
package studentpersist.gui; import studentpersist.application.controller.Controller; import studentpersist.application.model.Student; import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class StartWindow extends Application { @Override public void start(Stage stage) { stage.setTitle("Administrer studerende"); GridPane pane = new GridPane(); this.initContent(pane); Scene scene = new Scene(pane); stage.setScene(scene); stage.show(); } // ------------------------------------------------------------------------- private TextField txfName; private CheckBox chkActive; private ListView<Student> lvwStudents; private Button btnAdd; private Button btnSave; private Button btnDelete; private Controller controller; private void initContent(GridPane pane) { controller = Controller.getController(); controller.loadStorage(); // show or hide grid lines pane.setGridLinesVisible(false); // set padding of the pane pane.setPadding(new Insets(20)); // set horizontal<SUF> pane.setHgap(10); // set vertical gap between components pane.setVgap(10); Label lblName = new Label("Navn"); pane.add(lblName, 1, 1); Label lblActive = new Label("Aktiv"); pane.add(lblActive, 1, 3); txfName = new TextField(); pane.add(txfName, 2, 1, 4, 1); chkActive = new CheckBox(); pane.add(chkActive, 2, 3); // add a buttons to the pane btnAdd = new Button("Opret"); pane.add(btnAdd, 1, 5); btnSave = new Button("Gem"); btnSave.setDisable(true); pane.add(btnSave, 2, 5); btnDelete = new Button("Slet"); pane.add(btnDelete, 3, 5); btnDelete.setDisable(true); // connect a method to the button btnAdd.setOnAction(event -> addAction()); btnSave.setOnAction(event -> saveAction()); btnDelete.setOnAction(event -> deleteAction()); lvwStudents = new ListView<>(); pane.add(lvwStudents, 0, 1, 1, 3); lvwStudents.setPrefWidth(250); lvwStudents.setPrefHeight(200); lvwStudents.getItems().setAll(controller.getStudents()); ChangeListener<Student> listener = (ov, oldCompny, newCompany) -> selectedStudentChanged(); lvwStudents.getSelectionModel().selectedItemProperty().addListener(listener); } @Override public void stop() { controller.saveStorage(); } /** * This class controls access to the model in this application. In this * case, the model is a single Student object. */ private Student studerende = null; private void addAction() { studerende = controller.createStudent(txfName.getText().trim(), 20, chkActive.isSelected()); clearFields(); btnAdd.setDisable(true); lvwStudents.getItems().setAll(controller.getStudents()); } private void saveAction() { if (studerende != null) { controller.updateStudent(studerende, txfName.getText().trim(), 20, chkActive.isSelected()); clearFields(); btnSave.setDisable(true); btnDelete.setDisable(true); lvwStudents.getItems().setAll(controller.getStudents()); } } private void deleteAction() { if (studerende != null) { controller.deleteStudent(studerende); studerende = null; clearFields(); btnDelete.setDisable(true); btnSave.setDisable(true); btnAdd.setDisable(false); lvwStudents.getItems().setAll(controller.getStudents()); } } private void clearFields() { txfName.clear(); chkActive.setSelected(false); } private void selectedStudentChanged() { studerende = lvwStudents.getSelectionModel().getSelectedItem(); if (studerende != null) { txfName.setText(studerende.getName()); chkActive.setSelected(studerende.isActive()); btnSave.setDisable(false); btnDelete.setDisable(false); } } }
False
974
6
1,201
6
1,150
6
1,201
6
1,484
6
false
false
false
false
false
true
823
101939_8
/* * 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. */ import models.*; import DAO.*; /** * * @author joycee */ public class runierun { /** * @param args the command line arguments */ public static void main(String[] args) { // aanmaken van connectie UsersDAO userdao = new UsersDAO(); // Toevoegen van een user //Users user1 = new Users("test", "testiie", "19940629", "Hitek", "Directeur", "/../img/lekker.jpg", "[email protected]", "passwoord", true); //userdao.insertUser(user1); // Updaten van een user //Users user1 = userdao.findById(1); //user1.setName("Mario"); //user1.setForename("Van Corselis"); //userdao.updateUser(user1); // sluiten van connectie userdao.close(); } }
JensGryspeert/Eindopdracht
webcafe/src/main/java/runierun.java
302
// sluiten van connectie
line_comment
nl
/* * 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. */ import models.*; import DAO.*; /** * * @author joycee */ public class runierun { /** * @param args the command line arguments */ public static void main(String[] args) { // aanmaken van connectie UsersDAO userdao = new UsersDAO(); // Toevoegen van een user //Users user1 = new Users("test", "testiie", "19940629", "Hitek", "Directeur", "/../img/lekker.jpg", "[email protected]", "passwoord", true); //userdao.insertUser(user1); // Updaten van een user //Users user1 = userdao.findById(1); //user1.setName("Mario"); //user1.setForename("Van Corselis"); //userdao.updateUser(user1); // sluiten van<SUF> userdao.close(); } }
True
249
6
272
7
281
6
272
7
307
7
false
false
false
false
false
true
3,871
28381_0
package com.odenktools.authserver.entity; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Date; import java.util.Set; /** * @author Odenktools */ @Getter @Setter @JsonSerialize @AllArgsConstructor @NoArgsConstructor @Entity(name = "Permission") @Table(name = "permissions", uniqueConstraints = {@UniqueConstraint(columnNames = {"name_permission", "readable_name"})}) @JsonIgnoreProperties( ignoreUnknown = true, value = {"createdAt", "updatedAt"}, allowGetters = true ) public class Permission implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_perm", nullable = false) private Long idPerm; /** * Alias untuk kolum ``readableName``. ini digunakan agar data tetap konstant, tidak berpengaruh oleh update. * Ini harus digenerate ``UNIQUE`` berdasarkan kolum ``readableName``. * Misalkan : * named = Write ApiKey * coded = ROLE_WRITE_APIKEY (UPPERCASE, hapus SPACE menjadi UNDERSCORES, Tambahkan ROLE_) * </p> */ @NotNull @Column(name = "name_permission", nullable = false) private String namePermission; @NotNull @Column(name = "readable_name", nullable = false) private String readableName; @Temporal(TemporalType.TIMESTAMP) @Column(name = "created_at", updatable = false) @JsonProperty("created_at") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") private Date createdAt; @Temporal(TemporalType.TIMESTAMP) @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") @Column(name = "updated_at") private Date updatedAt; @Temporal(TemporalType.TIMESTAMP) @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") @Column(name = "deleted_at") private Date deletedAt; public Permission(@NotNull @Size(max = 100) String namePermission, @NotNull @Size(max = 100) String readableName) { this.namePermission = namePermission; this.readableName = readableName; } /** * Sets created_at before insert. */ @PrePersist public void setCreationDate() { this.createdAt = new Date(); } /** * Sets updated_at before update. */ @PreUpdate public void setChangedDate() { this.updatedAt = new Date(); } @ManyToMany(mappedBy = "usersPermissions") private Set<Group> usersGroups; }
odenktools/springboot-oauth2-jwt
authorization_server/src/main/java/com/odenktools/authserver/entity/Permission.java
949
/** * @author Odenktools */
block_comment
nl
package com.odenktools.authserver.entity; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Date; import java.util.Set; /** * @author Odenktools <SUF>*/ @Getter @Setter @JsonSerialize @AllArgsConstructor @NoArgsConstructor @Entity(name = "Permission") @Table(name = "permissions", uniqueConstraints = {@UniqueConstraint(columnNames = {"name_permission", "readable_name"})}) @JsonIgnoreProperties( ignoreUnknown = true, value = {"createdAt", "updatedAt"}, allowGetters = true ) public class Permission implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_perm", nullable = false) private Long idPerm; /** * Alias untuk kolum ``readableName``. ini digunakan agar data tetap konstant, tidak berpengaruh oleh update. * Ini harus digenerate ``UNIQUE`` berdasarkan kolum ``readableName``. * Misalkan : * named = Write ApiKey * coded = ROLE_WRITE_APIKEY (UPPERCASE, hapus SPACE menjadi UNDERSCORES, Tambahkan ROLE_) * </p> */ @NotNull @Column(name = "name_permission", nullable = false) private String namePermission; @NotNull @Column(name = "readable_name", nullable = false) private String readableName; @Temporal(TemporalType.TIMESTAMP) @Column(name = "created_at", updatable = false) @JsonProperty("created_at") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") private Date createdAt; @Temporal(TemporalType.TIMESTAMP) @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") @Column(name = "updated_at") private Date updatedAt; @Temporal(TemporalType.TIMESTAMP) @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") @Column(name = "deleted_at") private Date deletedAt; public Permission(@NotNull @Size(max = 100) String namePermission, @NotNull @Size(max = 100) String readableName) { this.namePermission = namePermission; this.readableName = readableName; } /** * Sets created_at before insert. */ @PrePersist public void setCreationDate() { this.createdAt = new Date(); } /** * Sets updated_at before update. */ @PreUpdate public void setChangedDate() { this.updatedAt = new Date(); } @ManyToMany(mappedBy = "usersPermissions") private Set<Group> usersGroups; }
False
628
10
814
11
799
10
814
11
972
11
false
false
false
false
false
true
993
31954_3
/*_x000D_ * To change this license header, choose License Headers in Project Properties._x000D_ * To change this template file, choose Tools | Templates_x000D_ * and open the template in the editor._x000D_ */_x000D_ _x000D_ package hw4.dutch;_x000D_ _x000D_ /**_x000D_ *_x000D_ * @author hessel_x000D_ */_x000D_ public interface Speler {_x000D_ public int Speel(Bord b); //Geeft public int Speel(Bord b);aan in welke kolom de speler wil spelen_x000D_ public String getNaam(); //Geeft de naam van de speler_x000D_ public Kleur getKleur(); //Geeft de kleur waar de speler mee speelt_x000D_ }_x000D_
Lucus16/oop
src/hw4/dutch/Speler.java
166
//Geeft de naam van de speler_x000D_
line_comment
nl
/*_x000D_ * To change this license header, choose License Headers in Project Properties._x000D_ * To change this template file, choose Tools | Templates_x000D_ * and open the template in the editor._x000D_ */_x000D_ _x000D_ package hw4.dutch;_x000D_ _x000D_ /**_x000D_ *_x000D_ * @author hessel_x000D_ */_x000D_ public interface Speler {_x000D_ public int Speel(Bord b); //Geeft public int Speel(Bord b);aan in welke kolom de speler wil spelen_x000D_ public String getNaam(); //Geeft de<SUF> public Kleur getKleur(); //Geeft de kleur waar de speler mee speelt_x000D_ }_x000D_
True
235
16
264
18
249
16
264
18
269
17
false
false
false
false
false
true
393
152117_0
package theWario.cards; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.monsters.AbstractMonster; import theWario.powers.TrekkingPower; public class TrekTime extends AbstractWarioCard { public final static String ID = makeID("TrekTime"); //stupid intellij stuff POWER, SELF, UNCOMMON private static final int MAGIC = 2; private static final int UPG_MAGIC = 1; public TrekTime() { super(ID, 1, CardType.POWER, CardRarity.UNCOMMON, CardTarget.SELF); baseMagicNumber = magicNumber = MAGIC; } public void us(AbstractPlayer p, AbstractMonster m) { applyToSelf(new TrekkingPower(magicNumber)); } public void upgrade() { if (!upgraded) { upgradeName(); upgradeMagicNumber(UPG_MAGIC); } } }
DarkVexon/OldBandit
src/main/java/theWario/cards/TrekTime.java
273
//stupid intellij stuff POWER, SELF, UNCOMMON
line_comment
nl
package theWario.cards; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.monsters.AbstractMonster; import theWario.powers.TrekkingPower; public class TrekTime extends AbstractWarioCard { public final static String ID = makeID("TrekTime"); //stupid intellij<SUF> private static final int MAGIC = 2; private static final int UPG_MAGIC = 1; public TrekTime() { super(ID, 1, CardType.POWER, CardRarity.UNCOMMON, CardTarget.SELF); baseMagicNumber = magicNumber = MAGIC; } public void us(AbstractPlayer p, AbstractMonster m) { applyToSelf(new TrekkingPower(magicNumber)); } public void upgrade() { if (!upgraded) { upgradeName(); upgradeMagicNumber(UPG_MAGIC); } } }
False
202
12
227
14
230
11
227
14
284
19
false
false
false
false
false
true
1,739
35593_7
/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ package com.tigervnc.rfb; public class LogWriter { public LogWriter(String name_) { name = name_; level = globalLogLevel; next = log_writers; log_writers = this; } public void setLevel(int level_) { level = level_; } public void write(int level, String str) { if (level <= this.level) { System.err.println(name+": "+str); } } public void error(String fmt, Object... args) { write(0, String.format(fmt, args)); } public void status(String fmt, Object... args) { write(10, String.format(fmt, args)); } public void info(String fmt, Object... args) { write(30, String.format(fmt, args)); } public void debug(String fmt, Object... args) { write(100, String.format(fmt, args)); } public static boolean setLogParams(String params) { globalLogLevel = Integer.parseInt(params); LogWriter current = log_writers; while (current != null) { current.setLevel(globalLogLevel); current = current.next; } return true; // int colon = params.indexOf(':'); // String logwriter_name = params.substring(0, colon); // params = params.substring(colon+1); // colon = params.indexOf(':'); // String logger_name = params.substring(0, colon); // params = params.substring(colon+1); // int level = Integer.parseInt(params); // // XXX ignore logger name for the moment // System.err.println("setting level to "+level); // System.err.println("logwriters is "+log_writers); // if (logwriter_name.equals("*")) { // LogWriter current = log_writers; // while (current != null) { // //current.setLog(logger); // System.err.println("setting level of "+current.name+" to "+level); // current.setLevel(level); // current = current.next; // } // return true; // } // LogWriter logwriter = getLogWriter(logwriter_name); // if (logwriter == null) { // System.err.println("no logwriter found: "+logwriter_name); // return false; // } // //logwriter.setLog(logger); // logwriter.setLevel(level); // return true; } static LogWriter getLogWriter(String name) { LogWriter current = log_writers; while (current != null) { if (name.equalsIgnoreCase(current.name)) return current; current = current.next; } return null; } String name; int level; LogWriter next; static LogWriter log_writers; static int globalLogLevel = 30; }
TigerVNC/tigervnc
java/com/tigervnc/rfb/LogWriter.java
1,008
// int level = Integer.parseInt(params);
line_comment
nl
/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ package com.tigervnc.rfb; public class LogWriter { public LogWriter(String name_) { name = name_; level = globalLogLevel; next = log_writers; log_writers = this; } public void setLevel(int level_) { level = level_; } public void write(int level, String str) { if (level <= this.level) { System.err.println(name+": "+str); } } public void error(String fmt, Object... args) { write(0, String.format(fmt, args)); } public void status(String fmt, Object... args) { write(10, String.format(fmt, args)); } public void info(String fmt, Object... args) { write(30, String.format(fmt, args)); } public void debug(String fmt, Object... args) { write(100, String.format(fmt, args)); } public static boolean setLogParams(String params) { globalLogLevel = Integer.parseInt(params); LogWriter current = log_writers; while (current != null) { current.setLevel(globalLogLevel); current = current.next; } return true; // int colon = params.indexOf(':'); // String logwriter_name = params.substring(0, colon); // params = params.substring(colon+1); // colon = params.indexOf(':'); // String logger_name = params.substring(0, colon); // params = params.substring(colon+1); // int level<SUF> // // XXX ignore logger name for the moment // System.err.println("setting level to "+level); // System.err.println("logwriters is "+log_writers); // if (logwriter_name.equals("*")) { // LogWriter current = log_writers; // while (current != null) { // //current.setLog(logger); // System.err.println("setting level of "+current.name+" to "+level); // current.setLevel(level); // current = current.next; // } // return true; // } // LogWriter logwriter = getLogWriter(logwriter_name); // if (logwriter == null) { // System.err.println("no logwriter found: "+logwriter_name); // return false; // } // //logwriter.setLog(logger); // logwriter.setLevel(level); // return true; } static LogWriter getLogWriter(String name) { LogWriter current = log_writers; while (current != null) { if (name.equalsIgnoreCase(current.name)) return current; current = current.next; } return null; } String name; int level; LogWriter next; static LogWriter log_writers; static int globalLogLevel = 30; }
False
795
9
915
11
946
11
915
11
1,014
11
false
false
false
false
false
true
3,661
114618_0
package nl.quintor.staq.service; import nl.quintor.staq.client.database.DatabaseClient; import nl.quintor.staq.client.bookservice.MetabookClient; public class BookService { private final DatabaseClient databaseClient = new DatabaseClient(); private final MetabookClient metabookClient = new MetabookClient(); public String getLanguage(final String bookId) { // 1. Implementeer deze methode. // 2. Zet hier eens een breakpoint neer. Op welke thread draait deze code? throw new UnsupportedOperationException(); } }
milanboers/staq-loom-handson
src/main/java/nl/quintor/staq/service/BookService.java
157
// 1. Implementeer deze methode.
line_comment
nl
package nl.quintor.staq.service; import nl.quintor.staq.client.database.DatabaseClient; import nl.quintor.staq.client.bookservice.MetabookClient; public class BookService { private final DatabaseClient databaseClient = new DatabaseClient(); private final MetabookClient metabookClient = new MetabookClient(); public String getLanguage(final String bookId) { // 1. Implementeer<SUF> // 2. Zet hier eens een breakpoint neer. Op welke thread draait deze code? throw new UnsupportedOperationException(); } }
True
124
10
146
10
143
11
146
10
164
13
false
false
false
false
false
true
846
150998_3
// Importeer de Scanner klasse import java.util.Scanner; public class DayOfWeek { /** * @param args */ public static void main(String[] args) { // Instantieer een nieuw Scanner object Scanner input = new Scanner(System.in); // Vraag gebruiker het jaar, de maand en de dag van de maand in te voeren: jaar, maand en dag. System.out.print("Voer het jaartal in, bijvoorbeeld '1978': "); int jaar = input.nextInt(); System.out.print("Voer de maand in, 1 voor januari, 4 voor april, etc.: "); int maand = input.nextInt(); System.out.print("Voer de dag van de maand in (1-31): "); int dag = input.nextInt(); // Bereken q: = dag int q = dag; // Bereken m: = maand als de maand niet januari of februari is, anders m = maand+12 en jaar = jaar-1 int m = maand; if (m < 3) { m = m + 12; jaar = jaar - 1; } // bereken j, de eeuw = jaar / 100 int j = jaar / 100; // bereken k, het jaar van de eeuw: = jaar % 100 int k = jaar % 100; // bereken h, de numerieke waarde van de dag van de week: h = (q + (26*(m + 1))/10 + k + k/4 + j/4 + 5*j)%7 int h = (q + (26 * (m + 1)) / 10 + k + (k / 4) + (j / 4) + (5 * j)) % 7; // Geef de naam van de dag met een switch statement switch (h) { case 0: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een zaterdag."); break; case 1: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een zondag."); break; case 2: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een maandag."); break; case 3: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een dinsdag."); break; case 4: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een woensdag."); break; case 5: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een donderdag."); break; case 6: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een vrijdag."); break; } } }
JobSarneel/java
h1-3/DayOfWeek.java
794
// Vraag gebruiker het jaar, de maand en de dag van de maand in te voeren: jaar, maand en dag.
line_comment
nl
// Importeer de Scanner klasse import java.util.Scanner; public class DayOfWeek { /** * @param args */ public static void main(String[] args) { // Instantieer een nieuw Scanner object Scanner input = new Scanner(System.in); // Vraag gebruiker<SUF> System.out.print("Voer het jaartal in, bijvoorbeeld '1978': "); int jaar = input.nextInt(); System.out.print("Voer de maand in, 1 voor januari, 4 voor april, etc.: "); int maand = input.nextInt(); System.out.print("Voer de dag van de maand in (1-31): "); int dag = input.nextInt(); // Bereken q: = dag int q = dag; // Bereken m: = maand als de maand niet januari of februari is, anders m = maand+12 en jaar = jaar-1 int m = maand; if (m < 3) { m = m + 12; jaar = jaar - 1; } // bereken j, de eeuw = jaar / 100 int j = jaar / 100; // bereken k, het jaar van de eeuw: = jaar % 100 int k = jaar % 100; // bereken h, de numerieke waarde van de dag van de week: h = (q + (26*(m + 1))/10 + k + k/4 + j/4 + 5*j)%7 int h = (q + (26 * (m + 1)) / 10 + k + (k / 4) + (j / 4) + (5 * j)) % 7; // Geef de naam van de dag met een switch statement switch (h) { case 0: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een zaterdag."); break; case 1: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een zondag."); break; case 2: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een maandag."); break; case 3: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een dinsdag."); break; case 4: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een woensdag."); break; case 5: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een donderdag."); break; case 6: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een vrijdag."); break; } } }
True
697
31
764
33
726
26
764
33
858
31
false
false
false
false
false
true
1,941
29727_0
package view; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; /** * @Autor: Isaak Malik, Michal Mytkowski * @Team: Team29 * @Date: 25/10/2015 * @Project: KroegenTocht * @Purpose: De JavaFX GUI */ public class StartGUI extends Application { @Override public void start(Stage scherm) { scherm.setTitle("Kroegentocht Applicatie"); GridPane gridPaneel = new GridPane(); gridPaneel.setAlignment(Pos.CENTER); gridPaneel.setPadding(new Insets(20, 20, 20, 20)); gridPaneel.setVgap(10); gridPaneel.setHgap(10); VBox vboxBtn = new VBox(); vboxBtn.setSpacing(10); vboxBtn.setPadding(new Insets(0, 20, 10, 20)); Text txtWelkom = new Text("KROEGENTOCHT"); txtWelkom.setId("welkomTekst"); gridPaneel.add(txtWelkom, 2, 0); // Button naar --> Toevoegen cafe Scene Button btnToevoegenCafe = new Button("Cafe Toevoegen"); btnToevoegenCafe.setAlignment(Pos.CENTER); btnToevoegenCafe.setMaxWidth(Double.MAX_VALUE); GridPane.setConstraints(btnToevoegenCafe, 2, 1); btnToevoegenCafe.setOnAction((ActionEvent e) -> { AlertBox.displayCafeToevoegenScene("Cafe Toevoegen", "Probleem bij toevoegen"); }); // Button naar --> Selectie cafe Button btnStarten = new Button("Start"); btnStarten.setMaxWidth(Double.MAX_VALUE); GridPane.setConstraints(btnStarten, 2, 2); btnStarten.setOnAction((ActionEvent e) -> { AlertBox.kiesStartCafeScene("Get ready!"); }); // Button naar --> Statistieken Scene Button btnStatistieken = new Button("Lijst Bezoeken"); btnStatistieken.setMaxWidth(Double.MAX_VALUE); GridPane.setConstraints(btnStatistieken, 2, 3); btnStatistieken.setOnAction((ActionEvent e) -> AlertBox.cafeStatistiekenScene("Statistieken")); // Exit knop Button btnExit = new Button("Exit"); btnExit.setMaxWidth(Double.MAX_VALUE); GridPane.setConstraints(btnExit, 2, 4); btnExit.setOnAction((ActionEvent e) -> { scherm.close(); }); // Setup scene gridPaneel.getChildren().addAll(btnToevoegenCafe, btnStarten, btnStatistieken, btnExit); Scene homeScene = new Scene(gridPaneel, 300, 400); scherm.setScene(homeScene); homeScene.getStylesheets().add(StartGUI.class.getResource("Kroegentocht.css").toExternalForm()); scherm.show(); } }
aardbol/Kroegentocht
src/view/StartGUI.java
951
/** * @Autor: Isaak Malik, Michal Mytkowski * @Team: Team29 * @Date: 25/10/2015 * @Project: KroegenTocht * @Purpose: De JavaFX GUI */
block_comment
nl
package view; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; /** * @Autor: Isaak Malik,<SUF>*/ public class StartGUI extends Application { @Override public void start(Stage scherm) { scherm.setTitle("Kroegentocht Applicatie"); GridPane gridPaneel = new GridPane(); gridPaneel.setAlignment(Pos.CENTER); gridPaneel.setPadding(new Insets(20, 20, 20, 20)); gridPaneel.setVgap(10); gridPaneel.setHgap(10); VBox vboxBtn = new VBox(); vboxBtn.setSpacing(10); vboxBtn.setPadding(new Insets(0, 20, 10, 20)); Text txtWelkom = new Text("KROEGENTOCHT"); txtWelkom.setId("welkomTekst"); gridPaneel.add(txtWelkom, 2, 0); // Button naar --> Toevoegen cafe Scene Button btnToevoegenCafe = new Button("Cafe Toevoegen"); btnToevoegenCafe.setAlignment(Pos.CENTER); btnToevoegenCafe.setMaxWidth(Double.MAX_VALUE); GridPane.setConstraints(btnToevoegenCafe, 2, 1); btnToevoegenCafe.setOnAction((ActionEvent e) -> { AlertBox.displayCafeToevoegenScene("Cafe Toevoegen", "Probleem bij toevoegen"); }); // Button naar --> Selectie cafe Button btnStarten = new Button("Start"); btnStarten.setMaxWidth(Double.MAX_VALUE); GridPane.setConstraints(btnStarten, 2, 2); btnStarten.setOnAction((ActionEvent e) -> { AlertBox.kiesStartCafeScene("Get ready!"); }); // Button naar --> Statistieken Scene Button btnStatistieken = new Button("Lijst Bezoeken"); btnStatistieken.setMaxWidth(Double.MAX_VALUE); GridPane.setConstraints(btnStatistieken, 2, 3); btnStatistieken.setOnAction((ActionEvent e) -> AlertBox.cafeStatistiekenScene("Statistieken")); // Exit knop Button btnExit = new Button("Exit"); btnExit.setMaxWidth(Double.MAX_VALUE); GridPane.setConstraints(btnExit, 2, 4); btnExit.setOnAction((ActionEvent e) -> { scherm.close(); }); // Setup scene gridPaneel.getChildren().addAll(btnToevoegenCafe, btnStarten, btnStatistieken, btnExit); Scene homeScene = new Scene(gridPaneel, 300, 400); scherm.setScene(homeScene); homeScene.getStylesheets().add(StartGUI.class.getResource("Kroegentocht.css").toExternalForm()); scherm.show(); } }
False
745
58
907
64
829
59
907
64
995
65
false
false
false
false
false
true
3,977
10058_4
package helpers; import java.math.BigInteger; import java.util.Arrays; /** * * @author Arno, Nick, Peter */ public class ByteHelper { // joins two blocks each containing 4 significant bits (4 right most bits contain data) public static byte joinBlocks(byte block1, byte block2) { return (byte) (block1 << 4 | block2); } // based on http://stackoverflow.com/a/784842 public static byte[] concatBlocks(byte[] left, byte[] right) { byte[] result = Arrays.copyOf(left, left.length + right.length); System.arraycopy(right, 0, result, left.length, right.length); return result; } // Herschikt de bits in de source byte array volgens de positions array // - Lengte van resultaat wordt bepaald door lengte van positions array public static byte[] permutate(byte[] source, int[] positions) { byte[] newBlock = new byte[positions.length / 8]; int byteIndex = -1; // voor elke positie for (int i = 0; i < positions.length; i++) { // neem de index van de bit int bitIndex = positions[i] - 1; // neem de waarde van de bit (0 of 1) byte bit = getBit(source, bitIndex); if (i % 8 == 0) { byteIndex++; } // zet de bit in de nieuwe blok op de juiste plaats newBlock[byteIndex] = (byte) ((bit << (bitIndex % 8)) | newBlock[byteIndex]); } return newBlock; } // http://n3vrax.wordpress.com/2011/07/23/des-algorithm-java-implementation/ public static byte[] permutFunc(byte[] input, int[] table) { int nrBytes = (table.length - 1) / 8 + 1; byte[] out = new byte[nrBytes]; for (int i = 0; i < table.length; i++) { int val = getBitInt(input, table[i] - 1); setBit(out, i, val); } return out; } // Kijkt of een bepaalde bit in een byte array gelijk aan 1 is public static byte getBit(byte[] data, int pos) { int posByte = pos / 8; int posBit = pos % 8; byte valByte = data[posByte]; return (byte) (isBitSet(valByte, posBit) ? 1 : 0); } // Kijkt of een bepaalde bit in een byte gelijk aan 1 is // Source: http://stackoverflow.com/questions/1034473/java-iterate-bits-in-byte-array public static Boolean isBitSet(byte value, int bit) { return (value & (1 << bit)) != 0; } // Voert XOR uit op twee byte arrays // Arrays moeten van de zelfde lengte zijn public static byte[] xorByteBlocks(byte[] blockOne, byte[] blockTwo) { byte[] newBlock = new byte[blockOne.length]; for (int i = 0; i < newBlock.length; i++) { newBlock[i] = (byte) (blockOne[i] ^ blockTwo[i]); } return newBlock; } // Zorgt voor de left shift // Source: http://www.herongyang.com/Java/Bit-String-Left-Rotation-All-Bits-in-Byte-Array.html public static byte[] rotateLeft(byte[] in, int len, int step) { int numOfBytes = (len - 1) / 8 + 1; byte[] out = new byte[numOfBytes]; for (int i = 0; i < len; i++) { int val = getBitInt(in, (i + step) % len); setBit(out, i, val); } return out; } //nick: Arno heeft hier een functie voor weet niet zeker of zelfde resultaat, later testen. // Haalt de bit op op positie pos in de byte array data // Source: http://www.herongyang.com/Java/Bit-String-Get-Bit-from-Byte-Array.html public static int getBitInt(byte[] data, int pos) { int posByte = pos / 8; int posBit = pos % 8; byte valByte = data[posByte]; int valInt = valByte >> (8 - (posBit + 1)) & 0x0001; return valInt; } //nick: misschien deze functie zelf uitschrijven, deze komt rechstreeks van de site. // Stelt de bit op op positie pos in de byte array data // Source: http://www.herongyang.com/Java/Bit-String-Get-Bit-from-Byte-Array.html public static void setBit(byte[] data, int pos, int val) { int posByte = pos / 8; int posBit = pos % 8; byte oldByte = data[posByte]; oldByte = (byte) (((0xFF7F >> posBit) & oldByte) & 0x00FF); byte newByte = (byte) ((val << (8 - (posBit + 1))) | oldByte); data[posByte] = newByte; } // http://stackoverflow.com/a/6393904 public static void printByteArray(byte[] bytes) { for (byte b : bytes) { System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1) + " "); } System.out.println(); } public static void printByte(byte b){ System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1) + " \n"); } public static byte[] convertBinaryStringToByteArray(String binaryString) { byte[] bytes = new BigInteger(binaryString.replace(" ", ""), 2).toByteArray(); // als eerste bit == 1 wordt een extra byte met allemaal nullen toegevoegd if (binaryString.charAt(0) == '1') { return Arrays.copyOfRange(bytes, 1, bytes.length); } return bytes; } /** * Get the first half of the specified block. * The significant bits are on the left. * eg. when a block with an odd length is split in half, only the first 4 bits * of the last byte are significant. * * @param block the block to be split in half * @return byte[] the first half of the specified block */ public static byte[] getFirstHalf(byte[] block) { return Arrays.copyOfRange(block, 0, (int) Math.ceil(block.length / 2.0)); } /** * Get the second half of the specified block. * The significant bits are on the left. * eg. when a block with an odd length is split in half, only the first 4 bits * of the last byte are significant. * * @param block the block to be split in half * @return byte[] the second half of the specified block */ public static byte[] getSecondHalf(byte[] block) { byte[] temp = Arrays.copyOfRange(block, block.length / 2, block.length); // middle of block is in the middle of a byte if ( (block.length / 2d) % 1 == 0.5) { temp = ByteHelper.rotateLeft(temp, temp.length * 8, 4); } return temp; } }
peterneyens/DES
src/main/java/helpers/ByteHelper.java
1,999
// - Lengte van resultaat wordt bepaald door lengte van positions array
line_comment
nl
package helpers; import java.math.BigInteger; import java.util.Arrays; /** * * @author Arno, Nick, Peter */ public class ByteHelper { // joins two blocks each containing 4 significant bits (4 right most bits contain data) public static byte joinBlocks(byte block1, byte block2) { return (byte) (block1 << 4 | block2); } // based on http://stackoverflow.com/a/784842 public static byte[] concatBlocks(byte[] left, byte[] right) { byte[] result = Arrays.copyOf(left, left.length + right.length); System.arraycopy(right, 0, result, left.length, right.length); return result; } // Herschikt de bits in de source byte array volgens de positions array // - Lengte<SUF> public static byte[] permutate(byte[] source, int[] positions) { byte[] newBlock = new byte[positions.length / 8]; int byteIndex = -1; // voor elke positie for (int i = 0; i < positions.length; i++) { // neem de index van de bit int bitIndex = positions[i] - 1; // neem de waarde van de bit (0 of 1) byte bit = getBit(source, bitIndex); if (i % 8 == 0) { byteIndex++; } // zet de bit in de nieuwe blok op de juiste plaats newBlock[byteIndex] = (byte) ((bit << (bitIndex % 8)) | newBlock[byteIndex]); } return newBlock; } // http://n3vrax.wordpress.com/2011/07/23/des-algorithm-java-implementation/ public static byte[] permutFunc(byte[] input, int[] table) { int nrBytes = (table.length - 1) / 8 + 1; byte[] out = new byte[nrBytes]; for (int i = 0; i < table.length; i++) { int val = getBitInt(input, table[i] - 1); setBit(out, i, val); } return out; } // Kijkt of een bepaalde bit in een byte array gelijk aan 1 is public static byte getBit(byte[] data, int pos) { int posByte = pos / 8; int posBit = pos % 8; byte valByte = data[posByte]; return (byte) (isBitSet(valByte, posBit) ? 1 : 0); } // Kijkt of een bepaalde bit in een byte gelijk aan 1 is // Source: http://stackoverflow.com/questions/1034473/java-iterate-bits-in-byte-array public static Boolean isBitSet(byte value, int bit) { return (value & (1 << bit)) != 0; } // Voert XOR uit op twee byte arrays // Arrays moeten van de zelfde lengte zijn public static byte[] xorByteBlocks(byte[] blockOne, byte[] blockTwo) { byte[] newBlock = new byte[blockOne.length]; for (int i = 0; i < newBlock.length; i++) { newBlock[i] = (byte) (blockOne[i] ^ blockTwo[i]); } return newBlock; } // Zorgt voor de left shift // Source: http://www.herongyang.com/Java/Bit-String-Left-Rotation-All-Bits-in-Byte-Array.html public static byte[] rotateLeft(byte[] in, int len, int step) { int numOfBytes = (len - 1) / 8 + 1; byte[] out = new byte[numOfBytes]; for (int i = 0; i < len; i++) { int val = getBitInt(in, (i + step) % len); setBit(out, i, val); } return out; } //nick: Arno heeft hier een functie voor weet niet zeker of zelfde resultaat, later testen. // Haalt de bit op op positie pos in de byte array data // Source: http://www.herongyang.com/Java/Bit-String-Get-Bit-from-Byte-Array.html public static int getBitInt(byte[] data, int pos) { int posByte = pos / 8; int posBit = pos % 8; byte valByte = data[posByte]; int valInt = valByte >> (8 - (posBit + 1)) & 0x0001; return valInt; } //nick: misschien deze functie zelf uitschrijven, deze komt rechstreeks van de site. // Stelt de bit op op positie pos in de byte array data // Source: http://www.herongyang.com/Java/Bit-String-Get-Bit-from-Byte-Array.html public static void setBit(byte[] data, int pos, int val) { int posByte = pos / 8; int posBit = pos % 8; byte oldByte = data[posByte]; oldByte = (byte) (((0xFF7F >> posBit) & oldByte) & 0x00FF); byte newByte = (byte) ((val << (8 - (posBit + 1))) | oldByte); data[posByte] = newByte; } // http://stackoverflow.com/a/6393904 public static void printByteArray(byte[] bytes) { for (byte b : bytes) { System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1) + " "); } System.out.println(); } public static void printByte(byte b){ System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1) + " \n"); } public static byte[] convertBinaryStringToByteArray(String binaryString) { byte[] bytes = new BigInteger(binaryString.replace(" ", ""), 2).toByteArray(); // als eerste bit == 1 wordt een extra byte met allemaal nullen toegevoegd if (binaryString.charAt(0) == '1') { return Arrays.copyOfRange(bytes, 1, bytes.length); } return bytes; } /** * Get the first half of the specified block. * The significant bits are on the left. * eg. when a block with an odd length is split in half, only the first 4 bits * of the last byte are significant. * * @param block the block to be split in half * @return byte[] the first half of the specified block */ public static byte[] getFirstHalf(byte[] block) { return Arrays.copyOfRange(block, 0, (int) Math.ceil(block.length / 2.0)); } /** * Get the second half of the specified block. * The significant bits are on the left. * eg. when a block with an odd length is split in half, only the first 4 bits * of the last byte are significant. * * @param block the block to be split in half * @return byte[] the second half of the specified block */ public static byte[] getSecondHalf(byte[] block) { byte[] temp = Arrays.copyOfRange(block, block.length / 2, block.length); // middle of block is in the middle of a byte if ( (block.length / 2d) % 1 == 0.5) { temp = ByteHelper.rotateLeft(temp, temp.length * 8, 4); } return temp; } }
True
1,749
18
1,856
19
1,931
13
1,856
19
2,050
19
false
false
false
false
false
true
2,720
190699_2
package generator; import configuration.DataConfigEntry; import configuration.ProcessorConfigEntry; import graql.lang.Graql; import graql.lang.pattern.Pattern; import graql.lang.pattern.variable.ThingVariable; import graql.lang.pattern.variable.ThingVariable.Thing; import graql.lang.pattern.variable.UnboundVariable; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import static generator.GeneratorUtil.addAttribute; import static generator.GeneratorUtil.malformedRow; public class AppendAttributeGenerator extends InsertGenerator { private static final Logger appLogger = LogManager.getLogger("com.bayer.dt.grami"); private static final Logger dataLogger = LogManager.getLogger("com.bayer.dt.grami.data"); private final DataConfigEntry dce; private final ProcessorConfigEntry pce; public AppendAttributeGenerator(DataConfigEntry dataConfigEntry, ProcessorConfigEntry processorConfigEntry) { super(); this.dce = dataConfigEntry; this.pce = processorConfigEntry; appLogger.debug("Creating AppendAttribute for processor " + processorConfigEntry.getProcessor() + " of type " + processorConfigEntry.getProcessorType()); } public HashMap<String, ArrayList<ArrayList<ThingVariable<?>>>> graknAppendAttributeInsert(ArrayList<String> rows, String header, int rowCounter) throws Exception { HashMap<String, ArrayList<ArrayList<ThingVariable<?>>>> matchInsertPatterns = new HashMap<>(); ArrayList<ArrayList<ThingVariable<?>>> matchPatterns = new ArrayList<>(); ArrayList<ArrayList<ThingVariable<?>>> insertPatterns = new ArrayList<>(); int insertCounter = 0; int batchCounter = 1; for (String row : rows) { ArrayList<ArrayList<ThingVariable<?>>> tmp = graknAppendAttributeQueryFromRow(row, header, insertCounter, rowCounter + batchCounter); if (tmp != null) { if (tmp.get(0) != null && tmp.get(1) != null) { matchPatterns.add(tmp.get(0)); insertPatterns.add(tmp.get(1)); insertCounter++; } } batchCounter = batchCounter + 1; } matchInsertPatterns.put("match", matchPatterns); matchInsertPatterns.put("insert", insertPatterns); return matchInsertPatterns; } public ArrayList<ArrayList<ThingVariable<?>>> graknAppendAttributeQueryFromRow(String row, String header, int insertCounter, int rowCounter) throws Exception { String fileSeparator = dce.getSeparator(); String[] rowTokens = row.split(fileSeparator); String[] columnNames = header.split(fileSeparator); appLogger.debug("processing tokenized row: " + Arrays.toString(rowTokens)); malformedRow(row, rowTokens, columnNames.length); if (!validateDataConfigEntry()) { throw new IllegalArgumentException("data config entry for " + dce.getDataPath() + " is incomplete - it needs at least one attribute used for matching (\"match\": true) and at least one attribute to be appended (\"match\": false or not set at all"); } ArrayList<ThingVariable<?>> matchPatterns = new ArrayList<>(); ArrayList<ThingVariable<?>> insertPatterns = new ArrayList<>(); // get all attributes that are isMatch() --> construct match clause Thing appendAttributeMatchPattern = addEntityToMatchPattern(insertCounter); for (DataConfigEntry.DataConfigGeneratorMapping generatorMappingForMatchAttribute : dce.getAttributes()) { if (generatorMappingForMatchAttribute.isMatch()) { appendAttributeMatchPattern = addAttribute(rowTokens, appendAttributeMatchPattern, columnNames, rowCounter, generatorMappingForMatchAttribute, pce, generatorMappingForMatchAttribute.getPreprocessor()); } } matchPatterns.add(appendAttributeMatchPattern); // get all attributes that are !isMatch() --> construct insert clause UnboundVariable thingVar = addEntityToInsertPattern(insertCounter); Thing appendAttributeInsertPattern = null; for (DataConfigEntry.DataConfigGeneratorMapping generatorMappingForAppendAttribute : dce.getAttributes()) { if (!generatorMappingForAppendAttribute.isMatch()) { appendAttributeInsertPattern = addAttribute(rowTokens, thingVar, rowCounter, columnNames, generatorMappingForAppendAttribute, pce, generatorMappingForAppendAttribute.getPreprocessor()); } } if (appendAttributeInsertPattern != null) { insertPatterns.add(appendAttributeInsertPattern); } ArrayList<ArrayList<ThingVariable<?>>> assembledPatterns = new ArrayList<>(); assembledPatterns.add(matchPatterns); assembledPatterns.add(insertPatterns); if (isValid(assembledPatterns)) { appLogger.debug("valid query: <" + assembleQuery(assembledPatterns) + ">"); return assembledPatterns; } else { dataLogger.warn("in datapath <" + dce.getDataPath() + ">: skipped row " + rowCounter + " b/c does not contain at least one match attribute and one insert attribute. Faulty tokenized row: " + Arrays.toString(rowTokens)); return null; } } private boolean validateDataConfigEntry() { boolean containsMatchAttribute = false; boolean containsAppendAttribute = false; for (DataConfigEntry.DataConfigGeneratorMapping attributeMapping : dce.getAttributes()) { if (attributeMapping.isMatch()) { containsMatchAttribute = true; } if (!attributeMapping.isMatch()) { containsAppendAttribute = true; } } return containsMatchAttribute && containsAppendAttribute; } private Thing addEntityToMatchPattern(int insertCounter) { if (pce.getSchemaType() != null) { // return Graql.var("e-" + insertCounter).isa(pce.getSchemaType()); return Graql.var("e").isa(pce.getSchemaType()); } else { throw new IllegalArgumentException("Required field <schemaType> not set in processor " + pce.getProcessor()); } } private UnboundVariable addEntityToInsertPattern(int insertCounter) { if (pce.getSchemaType() != null) { // return Graql.var("e-" + insertCounter); return Graql.var("e"); } else { throw new IllegalArgumentException("Required field <schemaType> not set in processor " + pce.getProcessor()); } } private String assembleQuery(ArrayList<ArrayList<ThingVariable<?>>> queries) { StringBuilder ret = new StringBuilder(); for (ThingVariable st : queries.get(0)) { ret.append(st.toString()); } ret.append(queries.get(1).get(0).toString()); return ret.toString(); } private boolean isValid(ArrayList<ArrayList<ThingVariable<?>>> si) { ArrayList<ThingVariable<?>> matchPatterns = si.get(0); ArrayList<ThingVariable<?>> insertPatterns = si.get(1); if (insertPatterns.size() < 1) { return false; } StringBuilder matchPattern = new StringBuilder(); for (Pattern st : matchPatterns) { matchPattern.append(st.toString()); } String insertPattern = insertPatterns.get(0).toString(); // missing match attribute for (DataConfigEntry.DataConfigGeneratorMapping attributeMapping : dce.getMatchAttributes()) { String generatorKey = attributeMapping.getGenerator(); ProcessorConfigEntry.ConceptGenerator generatorEntry = pce.getAttributeGenerator(generatorKey); if (!matchPattern.toString().contains("has " + generatorEntry.getAttributeType())) { return false; } } // missing required insert attribute for (Map.Entry<String, ProcessorConfigEntry.ConceptGenerator> generatorEntry : pce.getRequiredAttributes().entrySet()) { if (!insertPattern.contains("has " + generatorEntry.getValue().getAttributeType())) { return false; } } return true; } }
flyingsilverfin/typedb-loader
src/main/java/generator/AppendAttributeGenerator.java
2,151
// return Graql.var("e-" + insertCounter).isa(pce.getSchemaType());
line_comment
nl
package generator; import configuration.DataConfigEntry; import configuration.ProcessorConfigEntry; import graql.lang.Graql; import graql.lang.pattern.Pattern; import graql.lang.pattern.variable.ThingVariable; import graql.lang.pattern.variable.ThingVariable.Thing; import graql.lang.pattern.variable.UnboundVariable; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import static generator.GeneratorUtil.addAttribute; import static generator.GeneratorUtil.malformedRow; public class AppendAttributeGenerator extends InsertGenerator { private static final Logger appLogger = LogManager.getLogger("com.bayer.dt.grami"); private static final Logger dataLogger = LogManager.getLogger("com.bayer.dt.grami.data"); private final DataConfigEntry dce; private final ProcessorConfigEntry pce; public AppendAttributeGenerator(DataConfigEntry dataConfigEntry, ProcessorConfigEntry processorConfigEntry) { super(); this.dce = dataConfigEntry; this.pce = processorConfigEntry; appLogger.debug("Creating AppendAttribute for processor " + processorConfigEntry.getProcessor() + " of type " + processorConfigEntry.getProcessorType()); } public HashMap<String, ArrayList<ArrayList<ThingVariable<?>>>> graknAppendAttributeInsert(ArrayList<String> rows, String header, int rowCounter) throws Exception { HashMap<String, ArrayList<ArrayList<ThingVariable<?>>>> matchInsertPatterns = new HashMap<>(); ArrayList<ArrayList<ThingVariable<?>>> matchPatterns = new ArrayList<>(); ArrayList<ArrayList<ThingVariable<?>>> insertPatterns = new ArrayList<>(); int insertCounter = 0; int batchCounter = 1; for (String row : rows) { ArrayList<ArrayList<ThingVariable<?>>> tmp = graknAppendAttributeQueryFromRow(row, header, insertCounter, rowCounter + batchCounter); if (tmp != null) { if (tmp.get(0) != null && tmp.get(1) != null) { matchPatterns.add(tmp.get(0)); insertPatterns.add(tmp.get(1)); insertCounter++; } } batchCounter = batchCounter + 1; } matchInsertPatterns.put("match", matchPatterns); matchInsertPatterns.put("insert", insertPatterns); return matchInsertPatterns; } public ArrayList<ArrayList<ThingVariable<?>>> graknAppendAttributeQueryFromRow(String row, String header, int insertCounter, int rowCounter) throws Exception { String fileSeparator = dce.getSeparator(); String[] rowTokens = row.split(fileSeparator); String[] columnNames = header.split(fileSeparator); appLogger.debug("processing tokenized row: " + Arrays.toString(rowTokens)); malformedRow(row, rowTokens, columnNames.length); if (!validateDataConfigEntry()) { throw new IllegalArgumentException("data config entry for " + dce.getDataPath() + " is incomplete - it needs at least one attribute used for matching (\"match\": true) and at least one attribute to be appended (\"match\": false or not set at all"); } ArrayList<ThingVariable<?>> matchPatterns = new ArrayList<>(); ArrayList<ThingVariable<?>> insertPatterns = new ArrayList<>(); // get all attributes that are isMatch() --> construct match clause Thing appendAttributeMatchPattern = addEntityToMatchPattern(insertCounter); for (DataConfigEntry.DataConfigGeneratorMapping generatorMappingForMatchAttribute : dce.getAttributes()) { if (generatorMappingForMatchAttribute.isMatch()) { appendAttributeMatchPattern = addAttribute(rowTokens, appendAttributeMatchPattern, columnNames, rowCounter, generatorMappingForMatchAttribute, pce, generatorMappingForMatchAttribute.getPreprocessor()); } } matchPatterns.add(appendAttributeMatchPattern); // get all attributes that are !isMatch() --> construct insert clause UnboundVariable thingVar = addEntityToInsertPattern(insertCounter); Thing appendAttributeInsertPattern = null; for (DataConfigEntry.DataConfigGeneratorMapping generatorMappingForAppendAttribute : dce.getAttributes()) { if (!generatorMappingForAppendAttribute.isMatch()) { appendAttributeInsertPattern = addAttribute(rowTokens, thingVar, rowCounter, columnNames, generatorMappingForAppendAttribute, pce, generatorMappingForAppendAttribute.getPreprocessor()); } } if (appendAttributeInsertPattern != null) { insertPatterns.add(appendAttributeInsertPattern); } ArrayList<ArrayList<ThingVariable<?>>> assembledPatterns = new ArrayList<>(); assembledPatterns.add(matchPatterns); assembledPatterns.add(insertPatterns); if (isValid(assembledPatterns)) { appLogger.debug("valid query: <" + assembleQuery(assembledPatterns) + ">"); return assembledPatterns; } else { dataLogger.warn("in datapath <" + dce.getDataPath() + ">: skipped row " + rowCounter + " b/c does not contain at least one match attribute and one insert attribute. Faulty tokenized row: " + Arrays.toString(rowTokens)); return null; } } private boolean validateDataConfigEntry() { boolean containsMatchAttribute = false; boolean containsAppendAttribute = false; for (DataConfigEntry.DataConfigGeneratorMapping attributeMapping : dce.getAttributes()) { if (attributeMapping.isMatch()) { containsMatchAttribute = true; } if (!attributeMapping.isMatch()) { containsAppendAttribute = true; } } return containsMatchAttribute && containsAppendAttribute; } private Thing addEntityToMatchPattern(int insertCounter) { if (pce.getSchemaType() != null) { // return Graql.var("e-"<SUF> return Graql.var("e").isa(pce.getSchemaType()); } else { throw new IllegalArgumentException("Required field <schemaType> not set in processor " + pce.getProcessor()); } } private UnboundVariable addEntityToInsertPattern(int insertCounter) { if (pce.getSchemaType() != null) { // return Graql.var("e-" + insertCounter); return Graql.var("e"); } else { throw new IllegalArgumentException("Required field <schemaType> not set in processor " + pce.getProcessor()); } } private String assembleQuery(ArrayList<ArrayList<ThingVariable<?>>> queries) { StringBuilder ret = new StringBuilder(); for (ThingVariable st : queries.get(0)) { ret.append(st.toString()); } ret.append(queries.get(1).get(0).toString()); return ret.toString(); } private boolean isValid(ArrayList<ArrayList<ThingVariable<?>>> si) { ArrayList<ThingVariable<?>> matchPatterns = si.get(0); ArrayList<ThingVariable<?>> insertPatterns = si.get(1); if (insertPatterns.size() < 1) { return false; } StringBuilder matchPattern = new StringBuilder(); for (Pattern st : matchPatterns) { matchPattern.append(st.toString()); } String insertPattern = insertPatterns.get(0).toString(); // missing match attribute for (DataConfigEntry.DataConfigGeneratorMapping attributeMapping : dce.getMatchAttributes()) { String generatorKey = attributeMapping.getGenerator(); ProcessorConfigEntry.ConceptGenerator generatorEntry = pce.getAttributeGenerator(generatorKey); if (!matchPattern.toString().contains("has " + generatorEntry.getAttributeType())) { return false; } } // missing required insert attribute for (Map.Entry<String, ProcessorConfigEntry.ConceptGenerator> generatorEntry : pce.getRequiredAttributes().entrySet()) { if (!insertPattern.contains("has " + generatorEntry.getValue().getAttributeType())) { return false; } } return true; } }
False
1,647
20
1,825
22
1,956
23
1,825
22
2,122
24
false
false
false
false
false
true
1,185
132132_15
package nl.hr.cmi.infdev226a; public class GelinkteLijst { private Node first, last; private int size; public Object getFirst() { return first.data; } public Object getLast() { return last.data; } /** * Done - Nav Appaiya 29 November * Voeg toe aan de voorkant */ public void insertFirst(Object o) { Node newNode = new Node(); newNode.data = o; newNode.next = first; newNode.previous = null; if (this.first != null) { //set the old first's previous to the newNode this.first.previous = newNode; } else { //list was empty, newNode will be the only node. //so also set the last this.last = newNode; } //set the head to the newNode this.first = newNode; size++; } /** * Done - Nav Appaiya 29 November * Voeg toe aan de achterkant */ public void insertLast(Object o) { // n = new Node(); Node n = new Node(); n.data = o; n.next = null; n.previous = last; //if the list is not empty if (last != null) { last.previous = n; } else { this.last = n; } size++; } /** * Done - Nav Appaiya 29 November * Voeg toe voor een ander element */ public void insertBefore(Object o, Object before) { Node s = first; while (s != null) { if (s.data.equals(before)) { Node n = new Node(); n.data = o; n.next = s; n.next.previous = n; if (!isFirst(before)) { n.previous = s.previous; n.previous.next = n; } else { first = n; } size++; break; } else { s = s.next; } } this.size++; } /** * Done - Nav Appaiya 29 November * Voeg toe na een ander element */ public void insertAfter(Object o, Object after) { Node s = first; while (s != null) { if (s.data.equals(after)) { Node n = new Node(); n.data = o; n.previous = s; n.previous.next = n; // System.out.println("@Nav Todo: debug till here ==============="); if (!isLast(after)) { n.next = s.next; n.next.previous = n; } else { last = n; } size++; break; } else { s = s.next; } } size++; } /** * Done - Nav Appaiya 29 November * Verwijder een element * * @param data */ public void remove(Object data) { Node s = first; while (s != null) { if (s.data.equals(data)) { if (!isFirst(s.data) && !isLast(s.data)) { s.previous.next = s.next; s.next.previous = s.previous; } else if (getSize() == 1) { first = null; last = null; } else if (isFirst(s.data)) { first = s.next; s.next.previous = null; } else if (isLast(s.data)) { last = s.previous; s.previous.next = null; } size--; break; } else { s = s.next; } } } /** * Done - Nav Appaiya 29 November * Het aantal elementen in de gelinkte lijst * * @return */ public int getSize() { return size; } /** * @param o * @return */ boolean isFirst(Object o) { return first.data.equals(o); } /** * @param o * @return */ boolean isLast(Object o) { return last.data.equals(o); } Object getData(Node n) { return n.data; } @Override public String toString() { Node s = first; String r = ""; int c = 1; while (s != null) { r += "Node " + c++ + ":" + s + "\n"; s = s.next; } return r; } /** * Alleen de gelinkte lijst heeft toegang tot de node */ private class Node { //Dit is de data die je opslaat Object data; // referenties naar de eerste en laatste nodes Node next, previous; } }
Nav-Appaiya/INFDEV226A-LinkedLists
src/main/java/nl/hr/cmi/infdev226a/GelinkteLijst.java
1,391
/** * Alleen de gelinkte lijst heeft toegang tot de node */
block_comment
nl
package nl.hr.cmi.infdev226a; public class GelinkteLijst { private Node first, last; private int size; public Object getFirst() { return first.data; } public Object getLast() { return last.data; } /** * Done - Nav Appaiya 29 November * Voeg toe aan de voorkant */ public void insertFirst(Object o) { Node newNode = new Node(); newNode.data = o; newNode.next = first; newNode.previous = null; if (this.first != null) { //set the old first's previous to the newNode this.first.previous = newNode; } else { //list was empty, newNode will be the only node. //so also set the last this.last = newNode; } //set the head to the newNode this.first = newNode; size++; } /** * Done - Nav Appaiya 29 November * Voeg toe aan de achterkant */ public void insertLast(Object o) { // n = new Node(); Node n = new Node(); n.data = o; n.next = null; n.previous = last; //if the list is not empty if (last != null) { last.previous = n; } else { this.last = n; } size++; } /** * Done - Nav Appaiya 29 November * Voeg toe voor een ander element */ public void insertBefore(Object o, Object before) { Node s = first; while (s != null) { if (s.data.equals(before)) { Node n = new Node(); n.data = o; n.next = s; n.next.previous = n; if (!isFirst(before)) { n.previous = s.previous; n.previous.next = n; } else { first = n; } size++; break; } else { s = s.next; } } this.size++; } /** * Done - Nav Appaiya 29 November * Voeg toe na een ander element */ public void insertAfter(Object o, Object after) { Node s = first; while (s != null) { if (s.data.equals(after)) { Node n = new Node(); n.data = o; n.previous = s; n.previous.next = n; // System.out.println("@Nav Todo: debug till here ==============="); if (!isLast(after)) { n.next = s.next; n.next.previous = n; } else { last = n; } size++; break; } else { s = s.next; } } size++; } /** * Done - Nav Appaiya 29 November * Verwijder een element * * @param data */ public void remove(Object data) { Node s = first; while (s != null) { if (s.data.equals(data)) { if (!isFirst(s.data) && !isLast(s.data)) { s.previous.next = s.next; s.next.previous = s.previous; } else if (getSize() == 1) { first = null; last = null; } else if (isFirst(s.data)) { first = s.next; s.next.previous = null; } else if (isLast(s.data)) { last = s.previous; s.previous.next = null; } size--; break; } else { s = s.next; } } } /** * Done - Nav Appaiya 29 November * Het aantal elementen in de gelinkte lijst * * @return */ public int getSize() { return size; } /** * @param o * @return */ boolean isFirst(Object o) { return first.data.equals(o); } /** * @param o * @return */ boolean isLast(Object o) { return last.data.equals(o); } Object getData(Node n) { return n.data; } @Override public String toString() { Node s = first; String r = ""; int c = 1; while (s != null) { r += "Node " + c++ + ":" + s + "\n"; s = s.next; } return r; } /** * Alleen de gelinkte<SUF>*/ private class Node { //Dit is de data die je opslaat Object data; // referenties naar de eerste en laatste nodes Node next, previous; } }
True
1,069
21
1,149
21
1,295
19
1,149
21
1,370
22
false
false
false
false
false
true
1,737
17451_4
package Objects; import java.io.Serializable; import java.time.DayOfWeek; import java.time.LocalTime; import java.time.temporal.ChronoUnit; import java.util.UUID; public class ScheduleItem implements CRUD, Serializable { private UUID id; private String locationId; private UUID attractionId; private DayOfWeek day; private LocalTime startTime, endTime; // Constructor voor het maken van een ScheduleItem met de verchillende parameters public ScheduleItem(Location location, Attraction attraction, DayOfWeek day, String startTime, String endTime) { this.id = UUID.randomUUID(); this.locationId = location.getName(); this.attractionId = attraction.getId(); this.day = day; this.startTime = LocalTime.parse(startTime); this.endTime = LocalTime.parse(endTime); this.update(); } // Methode om alle velden van het ScheduleItem in één keer te updaten public void setAll(Location location, Attraction attraction, DayOfWeek day, String startTime, String endTime) { this.locationId = location.getName(); this.attractionId = attraction.getId(); this.day = day; this.startTime = LocalTime.parse(startTime); this.endTime = LocalTime.parse(endTime); this.update(); } public UUID getId() { return this.id; } public Location getLocation(Schedule schedule) { return schedule.getLocation(this.locationId); } public Attraction getAttraction(Schedule schedule) { return schedule.getAttraction(this.attractionId); } public DayOfWeek getDay() { return day; } public LocalTime getStartTime() { return startTime; } public LocalTime getEndTime() { return endTime; } public LocalTime getDuration() { LocalTime returnTime = LocalTime.MIDNIGHT; return returnTime.plusMinutes(this.startTime.until(this.endTime, ChronoUnit.MINUTES)); } public String getLocationId() { return locationId; } @Override public void update() { // Roep de IOController aan om dit ScheduleItem te updaten in de database IOController.update(this.id, this, IOController.ObjectType.SCHEDULE_ITEM); } @Override public void delete(Schedule schedule) { //todo idk if it's right to pass the schedule... but it needs to access it somewhere I think schedule.deleteScheduleItem(this.getId()); // Verwijder dit ScheduleItem uit de database via de IOController IOController.delete(this.id, IOController.ObjectType.SCHEDULE_ITEM); } @Override public String toString() // Methode voor het printen van informatie over dit ScheduleItem { return "ScheduleItem{" + "id=" + id + ", locationId=" + locationId + ", attractionId=" + attractionId + ", day=" + day + ", startTime=" + startTime + ", endTime=" + endTime + '}'; } }
Tiemenbr/KermisPlanner
src/Objects/ScheduleItem.java
839
// Verwijder dit ScheduleItem uit de database via de IOController
line_comment
nl
package Objects; import java.io.Serializable; import java.time.DayOfWeek; import java.time.LocalTime; import java.time.temporal.ChronoUnit; import java.util.UUID; public class ScheduleItem implements CRUD, Serializable { private UUID id; private String locationId; private UUID attractionId; private DayOfWeek day; private LocalTime startTime, endTime; // Constructor voor het maken van een ScheduleItem met de verchillende parameters public ScheduleItem(Location location, Attraction attraction, DayOfWeek day, String startTime, String endTime) { this.id = UUID.randomUUID(); this.locationId = location.getName(); this.attractionId = attraction.getId(); this.day = day; this.startTime = LocalTime.parse(startTime); this.endTime = LocalTime.parse(endTime); this.update(); } // Methode om alle velden van het ScheduleItem in één keer te updaten public void setAll(Location location, Attraction attraction, DayOfWeek day, String startTime, String endTime) { this.locationId = location.getName(); this.attractionId = attraction.getId(); this.day = day; this.startTime = LocalTime.parse(startTime); this.endTime = LocalTime.parse(endTime); this.update(); } public UUID getId() { return this.id; } public Location getLocation(Schedule schedule) { return schedule.getLocation(this.locationId); } public Attraction getAttraction(Schedule schedule) { return schedule.getAttraction(this.attractionId); } public DayOfWeek getDay() { return day; } public LocalTime getStartTime() { return startTime; } public LocalTime getEndTime() { return endTime; } public LocalTime getDuration() { LocalTime returnTime = LocalTime.MIDNIGHT; return returnTime.plusMinutes(this.startTime.until(this.endTime, ChronoUnit.MINUTES)); } public String getLocationId() { return locationId; } @Override public void update() { // Roep de IOController aan om dit ScheduleItem te updaten in de database IOController.update(this.id, this, IOController.ObjectType.SCHEDULE_ITEM); } @Override public void delete(Schedule schedule) { //todo idk if it's right to pass the schedule... but it needs to access it somewhere I think schedule.deleteScheduleItem(this.getId()); // Verwijder dit<SUF> IOController.delete(this.id, IOController.ObjectType.SCHEDULE_ITEM); } @Override public String toString() // Methode voor het printen van informatie over dit ScheduleItem { return "ScheduleItem{" + "id=" + id + ", locationId=" + locationId + ", attractionId=" + attractionId + ", day=" + day + ", startTime=" + startTime + ", endTime=" + endTime + '}'; } }
True
625
14
699
15
739
14
699
15
870
15
false
false
false
false
false
true
1,807
30791_0
package be.ucll.java.ent.utils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Service; /** * Beanutil is een utility class voor het inladen/ophalen van Spring Beans/Services * Omdat het zelf ook een @Service service is heeft hij toegang tot de Spring applicatiecontext * voor het ophalen of 'on the fly' instantiëren van Spring Beans. * <p> * Het wordt gebruikt omdat je Autowired Beans eigenlijk pas gebruikt worden NA de constructors allemaal zijn afgewerkt * Daardoor is het gebruik van een Autowired Bean in een Constructor vaak niet mogelijk. Via dit tooltje kan het toch. */ @Service public class BeanUtil implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } public static <T> T getBean(Class<T> beanClass) { return context.getBean(beanClass); } }
UcllJavaEnterprise/stubs-spring-vaadin-demo
src/main/java/be/ucll/java/ent/utils/BeanUtil.java
293
/** * Beanutil is een utility class voor het inladen/ophalen van Spring Beans/Services * Omdat het zelf ook een @Service service is heeft hij toegang tot de Spring applicatiecontext * voor het ophalen of 'on the fly' instantiëren van Spring Beans. * <p> * Het wordt gebruikt omdat je Autowired Beans eigenlijk pas gebruikt worden NA de constructors allemaal zijn afgewerkt * Daardoor is het gebruik van een Autowired Bean in een Constructor vaak niet mogelijk. Via dit tooltje kan het toch. */
block_comment
nl
package be.ucll.java.ent.utils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Service; /** * Beanutil is een<SUF>*/ @Service public class BeanUtil implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } public static <T> T getBean(Class<T> beanClass) { return context.getBean(beanClass); } }
False
231
127
283
147
261
117
283
147
301
144
false
false
false
false
false
true
3,503
200372_42
package composantsg; // // IUT de Nice / Departement informatique / Module APO-Java // Annee 2011_2012 - Composants generiques // // Classe ModeleTempsG : partie Modele (MVC) d'un compteur/decompteur de // temps // // Edition Draft : externalisation d'un modele de donnees observable // exploite par les demonstrateurs de la classe EspionG // // + Version 0.0.0 : derivation de la classe Observable // + Version 0.1.0 : l'heure courante est notifiee a l'observateur // + Version 0.2.0 : exploitation d'un fichier de configuration du // composant TempsG // + Version 0.3.0 : ajout d'un attribut de controle d'execution du // thread et accesseur de modification associe // // Edition A : ajout des moyens de pilotage externe du thread sous // jacent // // + Version 1.0.0 : ajout d'un attribut de controle d'execution du // thread et accesseur de modification associe // + Version 1.1.0 : ajout d'une butee cible eventuelle pour fin // d'execution du thread, definie par parametre // de configuration // + Version 1.2.0 : notifications simultanees de plusieurs modifs. // eventuelles de donnees // // Edition B : ajout de plusieurs modes de fonctionnement du modele // (choix par parametre de configuration) // // + Version 2.0.0 : reorganisation du code pour preparer l'ajout des // modes de fonctionnement // + Version 2.1.0 : introduction du mode "chronometre" // + Version 2.2.0 : introduction du mode "sablier" // + Version 2.3.0 : ajout methode privee notifier // + ajout notification aux observateurs avant la // premiere attente (correction du decalage initial // de visualisation) // // Auteur : A. Thuaire // import java.util.*; public class ModeleTempsG extends Observable implements Runnable { private String tempsCourant= "0 : 00 : 00"; private String separateur; private boolean statusThread= true; private Integer increment; private String mode; private String buteeCible; // --- Premier constructeur normal public ModeleTempsG(HashMap config) throws RuntimeException { // Controler la valeur du parametre // if (config == null) config= new HashMap(); // Extraire et memoriser le mode de fonctionnement // mode= (String)config.get("mode"); if (mode == null) mode= "horloge"; // Controler la validite du mode cible // boolean p1= mode.equals("horloge"); boolean p2= mode.equals("chronometre"); boolean p3= mode.equals("sablier"); if (!p1 && !p2 && !p3) throw new RuntimeException ("-3.1"); // Extraire et memoriser le separateur de champs // separateur= (String)config.get("separateur"); if (separateur == null) separateur= " : "; // Extraire et memoriser l'unite de temps // increment= (Integer)config.get("increment"); if (increment == null) increment= new Integer(1); // Extraire et memoriser la butee cible eventuelle // buteeCible= (String)config.get("butee"); } // --- Second constructeur normal public ModeleTempsG(HashMap config, int tempsTotal) throws RuntimeException { // Invoquer le premier constructeur // this (config); // Controler la validite du second parametre // if (tempsTotal < 0) throw new RuntimeException ("-2.2"); // Decomposer le second parametre en heures, minutes et secondes // int heures= 0, minutes=0, secondes= 0; secondes= tempsTotal; if (secondes >= 60) { minutes= secondes / 60; secondes -= minutes*60; } if (minutes >= 60) { heures= minutes / 60; minutes -= heures*60; } // Memoriser le resultat dans l'attribut "tempsCourant" // tempsCourant= timeToString(separateur, heures, minutes, secondes); } // --- Methode getTempsCourant public String getTempsCourant() {return tempsCourant;} // --- Methode resetStatus public void resetStatus() {statusThread= false;} // --- Methode setButee public void setButee(String cible) {buteeCible= cible;} // --- Methode run public void run() { boolean buteeAtteinte; // Notifier l'etat initial aux observateurs // buteeAtteinte= notifier(); // Suspendre le thread courant de la duree specifiee par le // parametre de configuration "increment" // if (!buteeAtteinte) { try {Thread.sleep(increment.intValue()*1000);} catch (InterruptedException e) {} } while(statusThread) { // Acquerir et controler le mode de fonctionnement du modele // if (mode.equals("horloge")) // Executer le mode "horloge" // executerHorloge(); else if (mode.equals("chronometre")) // Executer le mode "chronometre" // executerChronometre(); else // Executer le mode "sablier" // executerSablier(); // Notifier l'etat courant aux observateurs // buteeAtteinte= notifier(); // Stopper la boucle si la butee cible a ete atteinte // if (buteeAtteinte) break; // Suspendre le thread courant de la duree specifiee par le // parametre de configuration "increment" // try {Thread.sleep(increment.intValue()*1000);} catch (InterruptedException e) {} } } // --- Methode timeToString private static String timeToString (String separateur, int heures, int minutes, int secondes) { String resultat= ""; resultat= heures + separateur; if (minutes < 10) resultat += "0" + minutes; else resultat += minutes; resultat += separateur; if (secondes < 10) resultat += "0" + secondes; else resultat += secondes; return resultat; } // --- Methode stringToTime private static int stringToTime (String separateur, String label) { int heures, minutes, secondes; // Fractionner le label en trois champs suivant le separateur // et convertir en numerique // String[] champsLabel= label.split(" : "); heures = new Integer(champsLabel[0]).intValue(); minutes = new Integer(champsLabel[1]).intValue(); secondes= new Integer(champsLabel[2]).intValue(); // Restituer le resultat // return 3600*heures + 60*minutes + secondes; } // --- Methode controleButee private static boolean controleButee (String separateur, String temps, String butee, int seuil) { // Controler la validite du second parametre // if (butee == null) return false; // Convertir le label du temps en numerique // int op1= stringToTime(separateur, temps); // Convertir le label de la butee en numerique // int op2= stringToTime(separateur, butee); // Restituer le resultat // return Math.abs(op1-op2) < seuil; } // --- Methode executerHorloge private void executerHorloge() { Calendar calendrier; int heures= 0, minutes=0, secondes= 0; // Acquerir et fractionner la description du temps // calendrier = Calendar.getInstance(); heures= calendrier.get(Calendar.HOUR_OF_DAY); minutes= calendrier.get(Calendar.MINUTE); secondes= calendrier.get(Calendar.SECOND); // Mettre a jour le temps courant // tempsCourant= timeToString(separateur, heures, minutes, secondes); } // --- Methode executerChronometre private void executerChronometre() { int heures= 0, minutes=0, secondes= 0; // Fractionner le label du temps courant en trois champs et // convertir en numerique // String[] champsTempsCourant= tempsCourant.split(" : "); heures = new Integer(champsTempsCourant[0]).intValue(); minutes = new Integer(champsTempsCourant[1]).intValue(); secondes= new Integer(champsTempsCourant[2]).intValue(); // Determiner le rafraichissement du champ de droite (secondes) // du label tempsCourant // int deltaMinutes = 0; secondes += increment; if (secondes >= 60) { deltaMinutes= secondes / 60; secondes -= deltaMinutes*60; } // Determiner le rafraichissement du champ du centre (minutes) // du label tempsCourant // int deltaHeures = 0; minutes += deltaMinutes; if (minutes >= 60) { deltaHeures= minutes / 60; minutes -= deltaHeures*60; } // Determiner le rafraichissement du champ de gauche (heures) // du label tempsCourant // heures += deltaHeures; // Mettre a jour le temps courant // tempsCourant= timeToString(separateur, heures, minutes, secondes); } // --- Methode executerSablier private void executerSablier() { int heures= 0, minutes=0, secondes= 0; // Fractionner le label du temps courant en trois champs et // convertir en numerique // String[] champsTempsCourant= tempsCourant.split(" : "); heures = new Integer(champsTempsCourant[0]).intValue(); minutes = new Integer(champsTempsCourant[1]).intValue(); secondes= new Integer(champsTempsCourant[2]).intValue(); // Traiter le cas de l'arret du sablier pour temps disponible // epuise // if (heures == 0 && minutes == 0 && secondes == 0) resetStatus(); // Determiner le rafraichissement du champ de droite (secondes) // du label tempsCourant // int deltaMinutes = 0; secondes -= increment; if (secondes < 0) { deltaMinutes= 1; secondes= 59; } // Determiner le rafraichissement du champ du centre (minutes) // du label tempsCourant // int deltaHeures = 0; minutes -= deltaMinutes; if (minutes < 0) { deltaHeures= 1; minutes= 59; } // Determiner le rafraichissement du champ de gauche (heures) // du label tempsCourant // heures -= deltaHeures; // Mettre a jour le temps courant // tempsCourant= timeToString(separateur, heures, minutes, secondes); } // --- Methode notifier private boolean notifier () { // Etablir si la butee eventuelle a ete atteinte // boolean buteeAtteinte= controleButee(separateur, tempsCourant, buteeCible, increment); // Construire le dictionnaire des modifications // HashMap modifs= new HashMap(); modifs.put("tempsCourant", tempsCourant); modifs.put("buteeAtteinte", new Boolean(buteeAtteinte)); // Fournir l'etat courant aux observateurs // setChanged(); notifyObservers(modifs); // Mettre a jour le status du thread courant // if (buteeAtteinte) resetStatus(); // Restituer le resultat // return buteeAtteinte; } }
loic-vial/belote
src/composantsg/ModeleTempsG.java
3,997
// --- Methode setButee
line_comment
nl
package composantsg; // // IUT de Nice / Departement informatique / Module APO-Java // Annee 2011_2012 - Composants generiques // // Classe ModeleTempsG : partie Modele (MVC) d'un compteur/decompteur de // temps // // Edition Draft : externalisation d'un modele de donnees observable // exploite par les demonstrateurs de la classe EspionG // // + Version 0.0.0 : derivation de la classe Observable // + Version 0.1.0 : l'heure courante est notifiee a l'observateur // + Version 0.2.0 : exploitation d'un fichier de configuration du // composant TempsG // + Version 0.3.0 : ajout d'un attribut de controle d'execution du // thread et accesseur de modification associe // // Edition A : ajout des moyens de pilotage externe du thread sous // jacent // // + Version 1.0.0 : ajout d'un attribut de controle d'execution du // thread et accesseur de modification associe // + Version 1.1.0 : ajout d'une butee cible eventuelle pour fin // d'execution du thread, definie par parametre // de configuration // + Version 1.2.0 : notifications simultanees de plusieurs modifs. // eventuelles de donnees // // Edition B : ajout de plusieurs modes de fonctionnement du modele // (choix par parametre de configuration) // // + Version 2.0.0 : reorganisation du code pour preparer l'ajout des // modes de fonctionnement // + Version 2.1.0 : introduction du mode "chronometre" // + Version 2.2.0 : introduction du mode "sablier" // + Version 2.3.0 : ajout methode privee notifier // + ajout notification aux observateurs avant la // premiere attente (correction du decalage initial // de visualisation) // // Auteur : A. Thuaire // import java.util.*; public class ModeleTempsG extends Observable implements Runnable { private String tempsCourant= "0 : 00 : 00"; private String separateur; private boolean statusThread= true; private Integer increment; private String mode; private String buteeCible; // --- Premier constructeur normal public ModeleTempsG(HashMap config) throws RuntimeException { // Controler la valeur du parametre // if (config == null) config= new HashMap(); // Extraire et memoriser le mode de fonctionnement // mode= (String)config.get("mode"); if (mode == null) mode= "horloge"; // Controler la validite du mode cible // boolean p1= mode.equals("horloge"); boolean p2= mode.equals("chronometre"); boolean p3= mode.equals("sablier"); if (!p1 && !p2 && !p3) throw new RuntimeException ("-3.1"); // Extraire et memoriser le separateur de champs // separateur= (String)config.get("separateur"); if (separateur == null) separateur= " : "; // Extraire et memoriser l'unite de temps // increment= (Integer)config.get("increment"); if (increment == null) increment= new Integer(1); // Extraire et memoriser la butee cible eventuelle // buteeCible= (String)config.get("butee"); } // --- Second constructeur normal public ModeleTempsG(HashMap config, int tempsTotal) throws RuntimeException { // Invoquer le premier constructeur // this (config); // Controler la validite du second parametre // if (tempsTotal < 0) throw new RuntimeException ("-2.2"); // Decomposer le second parametre en heures, minutes et secondes // int heures= 0, minutes=0, secondes= 0; secondes= tempsTotal; if (secondes >= 60) { minutes= secondes / 60; secondes -= minutes*60; } if (minutes >= 60) { heures= minutes / 60; minutes -= heures*60; } // Memoriser le resultat dans l'attribut "tempsCourant" // tempsCourant= timeToString(separateur, heures, minutes, secondes); } // --- Methode getTempsCourant public String getTempsCourant() {return tempsCourant;} // --- Methode resetStatus public void resetStatus() {statusThread= false;} // --- <SUF> public void setButee(String cible) {buteeCible= cible;} // --- Methode run public void run() { boolean buteeAtteinte; // Notifier l'etat initial aux observateurs // buteeAtteinte= notifier(); // Suspendre le thread courant de la duree specifiee par le // parametre de configuration "increment" // if (!buteeAtteinte) { try {Thread.sleep(increment.intValue()*1000);} catch (InterruptedException e) {} } while(statusThread) { // Acquerir et controler le mode de fonctionnement du modele // if (mode.equals("horloge")) // Executer le mode "horloge" // executerHorloge(); else if (mode.equals("chronometre")) // Executer le mode "chronometre" // executerChronometre(); else // Executer le mode "sablier" // executerSablier(); // Notifier l'etat courant aux observateurs // buteeAtteinte= notifier(); // Stopper la boucle si la butee cible a ete atteinte // if (buteeAtteinte) break; // Suspendre le thread courant de la duree specifiee par le // parametre de configuration "increment" // try {Thread.sleep(increment.intValue()*1000);} catch (InterruptedException e) {} } } // --- Methode timeToString private static String timeToString (String separateur, int heures, int minutes, int secondes) { String resultat= ""; resultat= heures + separateur; if (minutes < 10) resultat += "0" + minutes; else resultat += minutes; resultat += separateur; if (secondes < 10) resultat += "0" + secondes; else resultat += secondes; return resultat; } // --- Methode stringToTime private static int stringToTime (String separateur, String label) { int heures, minutes, secondes; // Fractionner le label en trois champs suivant le separateur // et convertir en numerique // String[] champsLabel= label.split(" : "); heures = new Integer(champsLabel[0]).intValue(); minutes = new Integer(champsLabel[1]).intValue(); secondes= new Integer(champsLabel[2]).intValue(); // Restituer le resultat // return 3600*heures + 60*minutes + secondes; } // --- Methode controleButee private static boolean controleButee (String separateur, String temps, String butee, int seuil) { // Controler la validite du second parametre // if (butee == null) return false; // Convertir le label du temps en numerique // int op1= stringToTime(separateur, temps); // Convertir le label de la butee en numerique // int op2= stringToTime(separateur, butee); // Restituer le resultat // return Math.abs(op1-op2) < seuil; } // --- Methode executerHorloge private void executerHorloge() { Calendar calendrier; int heures= 0, minutes=0, secondes= 0; // Acquerir et fractionner la description du temps // calendrier = Calendar.getInstance(); heures= calendrier.get(Calendar.HOUR_OF_DAY); minutes= calendrier.get(Calendar.MINUTE); secondes= calendrier.get(Calendar.SECOND); // Mettre a jour le temps courant // tempsCourant= timeToString(separateur, heures, minutes, secondes); } // --- Methode executerChronometre private void executerChronometre() { int heures= 0, minutes=0, secondes= 0; // Fractionner le label du temps courant en trois champs et // convertir en numerique // String[] champsTempsCourant= tempsCourant.split(" : "); heures = new Integer(champsTempsCourant[0]).intValue(); minutes = new Integer(champsTempsCourant[1]).intValue(); secondes= new Integer(champsTempsCourant[2]).intValue(); // Determiner le rafraichissement du champ de droite (secondes) // du label tempsCourant // int deltaMinutes = 0; secondes += increment; if (secondes >= 60) { deltaMinutes= secondes / 60; secondes -= deltaMinutes*60; } // Determiner le rafraichissement du champ du centre (minutes) // du label tempsCourant // int deltaHeures = 0; minutes += deltaMinutes; if (minutes >= 60) { deltaHeures= minutes / 60; minutes -= deltaHeures*60; } // Determiner le rafraichissement du champ de gauche (heures) // du label tempsCourant // heures += deltaHeures; // Mettre a jour le temps courant // tempsCourant= timeToString(separateur, heures, minutes, secondes); } // --- Methode executerSablier private void executerSablier() { int heures= 0, minutes=0, secondes= 0; // Fractionner le label du temps courant en trois champs et // convertir en numerique // String[] champsTempsCourant= tempsCourant.split(" : "); heures = new Integer(champsTempsCourant[0]).intValue(); minutes = new Integer(champsTempsCourant[1]).intValue(); secondes= new Integer(champsTempsCourant[2]).intValue(); // Traiter le cas de l'arret du sablier pour temps disponible // epuise // if (heures == 0 && minutes == 0 && secondes == 0) resetStatus(); // Determiner le rafraichissement du champ de droite (secondes) // du label tempsCourant // int deltaMinutes = 0; secondes -= increment; if (secondes < 0) { deltaMinutes= 1; secondes= 59; } // Determiner le rafraichissement du champ du centre (minutes) // du label tempsCourant // int deltaHeures = 0; minutes -= deltaMinutes; if (minutes < 0) { deltaHeures= 1; minutes= 59; } // Determiner le rafraichissement du champ de gauche (heures) // du label tempsCourant // heures -= deltaHeures; // Mettre a jour le temps courant // tempsCourant= timeToString(separateur, heures, minutes, secondes); } // --- Methode notifier private boolean notifier () { // Etablir si la butee eventuelle a ete atteinte // boolean buteeAtteinte= controleButee(separateur, tempsCourant, buteeCible, increment); // Construire le dictionnaire des modifications // HashMap modifs= new HashMap(); modifs.put("tempsCourant", tempsCourant); modifs.put("buteeAtteinte", new Boolean(buteeAtteinte)); // Fournir l'etat courant aux observateurs // setChanged(); notifyObservers(modifs); // Mettre a jour le status du thread courant // if (buteeAtteinte) resetStatus(); // Restituer le resultat // return buteeAtteinte; } }
False
3,047
9
3,194
9
3,287
9
3,194
9
3,672
13
false
false
false
false
false
true
518
31824_2
package drie.nieuw.relatiesindrie.model; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; @Entity public class Pagina { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String title; private String subtitle; private String author; @Column(length=20000) // Q:het heeft GEEN effect op de varchar size in de database, // het wordt een text-veld -> ik begrijp het verschil niet met song.java uit SONGBOOK // bovendien heb ik het veld handmatig goed gezet in phpMyAdmin... dat moet beter! String codetext; @OneToMany(mappedBy = "pagina", cascade = CascadeType.REMOVE) private List<PaginaPerLijst> lijsten; //------------------------------------------------- public String getAuthor() { return author; } //------------------------------------------------- public void setAuthor(String author) { this.author = author; } //------------------------------------------------- public String getCodetext() { return codetext; } //------------------------------------------------- public void setCodetext(String codetext) { this.codetext = codetext; } //------------------------------------------------ public String getSubtitle() { return subtitle; } //------------------------------------------------- public void setSubtitle(String subtitle) { this.subtitle = subtitle; } //------------------------------------------------- public long getId() { return id; } //------------------------------------------------- public void setId(long id) { this.id = id; } //------------------------------------------------- public String getTitle() { return title; } //------------------------------------------------- public void setTitle(String title) { this.title = title; } //------------------------------------------------- @JsonIgnore public List<PaginaPerLijst> getLijsten() { return lijsten; } //------------------------------------------------- @JsonIgnore public void setLijsten(List<PaginaPerLijst> lijsten) { this.lijsten = lijsten; } //------------------------------------------------- }
FelixvL/mavendriemanytomanyspring
src/main/java/drie/nieuw/relatiesindrie/model/Pagina.java
691
// bovendien heb ik het veld handmatig goed gezet in phpMyAdmin... dat moet beter!
line_comment
nl
package drie.nieuw.relatiesindrie.model; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; @Entity public class Pagina { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String title; private String subtitle; private String author; @Column(length=20000) // Q:het heeft GEEN effect op de varchar size in de database, // het wordt een text-veld -> ik begrijp het verschil niet met song.java uit SONGBOOK // bovendien heb<SUF> String codetext; @OneToMany(mappedBy = "pagina", cascade = CascadeType.REMOVE) private List<PaginaPerLijst> lijsten; //------------------------------------------------- public String getAuthor() { return author; } //------------------------------------------------- public void setAuthor(String author) { this.author = author; } //------------------------------------------------- public String getCodetext() { return codetext; } //------------------------------------------------- public void setCodetext(String codetext) { this.codetext = codetext; } //------------------------------------------------ public String getSubtitle() { return subtitle; } //------------------------------------------------- public void setSubtitle(String subtitle) { this.subtitle = subtitle; } //------------------------------------------------- public long getId() { return id; } //------------------------------------------------- public void setId(long id) { this.id = id; } //------------------------------------------------- public String getTitle() { return title; } //------------------------------------------------- public void setTitle(String title) { this.title = title; } //------------------------------------------------- @JsonIgnore public List<PaginaPerLijst> getLijsten() { return lijsten; } //------------------------------------------------- @JsonIgnore public void setLijsten(List<PaginaPerLijst> lijsten) { this.lijsten = lijsten; } //------------------------------------------------- }
True
461
26
598
28
594
20
598
28
695
29
false
false
false
false
false
true
4,137
111337_2
/* * Firebird Open Source JDBC Driver * * Distributable under LGPL license. * You may obtain a copy of the License at http://www.gnu.org/copyleft/lgpl.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * LGPL License for more details. * * This file was created by members of the firebird development team. * All individual contributions remain the Copyright (C) of those * individuals. Contributors to this file are either listed here or * can be obtained from a source control history command. * * All rights reserved. */ package org.firebirdsql.gds.ng.jna; import com.sun.jna.Native; import com.sun.jna.Platform; import org.firebirdsql.gds.JaybirdSystemProperties; import org.firebirdsql.gds.ng.IAttachProperties; import org.firebirdsql.jaybird.util.Cleaners; import org.firebirdsql.jna.embedded.FirebirdEmbeddedLookup; import org.firebirdsql.jna.embedded.spi.DisposableFirebirdEmbeddedLibrary; import org.firebirdsql.jna.embedded.spi.FirebirdEmbeddedLibrary; import org.firebirdsql.jna.fbclient.FbClientLibrary; import org.firebirdsql.jna.fbclient.WinFbClientLibrary; import java.lang.ref.Cleaner; import java.nio.file.Path; import java.util.*; import static java.lang.System.Logger.Level.DEBUG; import static java.lang.System.Logger.Level.ERROR; import static java.lang.System.Logger.Level.INFO; import static java.util.Objects.requireNonNull; /** * Implementation of {@link org.firebirdsql.gds.ng.FbDatabaseFactory} for establishing connection using the * Firebird embedded library. * * @author Mark Rotteveel * @since 3.0 */ public final class FbEmbeddedDatabaseFactory extends AbstractNativeDatabaseFactory { private static final System.Logger log = System.getLogger(FbEmbeddedDatabaseFactory.class.getName()); // Note Firebird 3+ embedded is fbclient + engineNN (e.g. engine12 for Firebird 3.0 / ODS 12) private static final List<String> LIBRARIES_TO_TRY = List.of("fbembed", FbClientDatabaseFactory.LIBRARY_NAME_FBCLIENT); private static final FbEmbeddedDatabaseFactory INSTANCE = new FbEmbeddedDatabaseFactory(); private FbEmbeddedDatabaseFactory() { // only through getInstance() } public static FbEmbeddedDatabaseFactory getInstance() { return INSTANCE; } @Override protected <T extends IAttachProperties<T>> T filterProperties(T attachProperties) { T attachPropertiesCopy = attachProperties.asNewMutable(); // Clear server name attachPropertiesCopy.setServerName(null); return attachPropertiesCopy; } @Override protected Collection<String> defaultLibraryNames() { return LIBRARIES_TO_TRY; } @Override protected FbClientLibrary createClientLibrary() { final List<Throwable> throwables = new ArrayList<>(); final List<String> librariesToTry = findLibrariesToTry(); for (String libraryName : librariesToTry) { try { if (Platform.isWindows()) { return Native.load(libraryName, WinFbClientLibrary.class); } else { return Native.load(libraryName, FbClientLibrary.class); } } catch (RuntimeException | UnsatisfiedLinkError e) { throwables.add(e); log.log(DEBUG, () -> "Attempt to load %s failed".formatted(libraryName), e); // continue with next } } assert throwables.size() == librariesToTry.size(); if (log.isLoggable(ERROR)) { log.log(ERROR, "Could not load any of the libraries in {0}:", librariesToTry); for (int idx = 0; idx < librariesToTry.size(); idx++) { log.log(ERROR, "Loading %s failed".formatted(librariesToTry.get(idx)), throwables.get(idx)); } } throw new NativeLibraryLoadException("Could not load any of " + librariesToTry + "; linking first exception", throwables.get(0)); } private List<String> findLibrariesToTry() { final String libraryPath = JaybirdSystemProperties.getNativeLibraryFbclient(); if (libraryPath != null) { return Collections.singletonList(libraryPath); } Optional<FirebirdEmbeddedLibrary> optionalFbEmbeddedInstance = FirebirdEmbeddedLookup.findFirebirdEmbedded(); if (optionalFbEmbeddedInstance.isPresent()) { FirebirdEmbeddedLibrary firebirdEmbeddedLibrary = optionalFbEmbeddedInstance.get(); log.log(INFO, "Found Firebird Embedded {0} on classpath", firebirdEmbeddedLibrary.getVersion()); if (firebirdEmbeddedLibrary instanceof DisposableFirebirdEmbeddedLibrary disposableLibrary) { NativeResourceTracker.strongRegisterNativeResource( new FirebirdEmbeddedLibraryNativeResource(disposableLibrary)); } Path entryPointPath = firebirdEmbeddedLibrary.getEntryPointPath().toAbsolutePath(); List<String> librariesToTry = new ArrayList<>(LIBRARIES_TO_TRY.size() + 1); librariesToTry.add(entryPointPath.toString()); librariesToTry.addAll(LIBRARIES_TO_TRY); return librariesToTry; } return LIBRARIES_TO_TRY; } private static final class FirebirdEmbeddedLibraryNativeResource extends NativeResourceTracker.NativeResource { private final Cleaner.Cleanable cleanable; private FirebirdEmbeddedLibraryNativeResource(DisposableFirebirdEmbeddedLibrary firebirdEmbeddedLibrary) { requireNonNull(firebirdEmbeddedLibrary, "firebirdEmbeddedLibrary"); cleanable = Cleaners.getJbCleaner().register(this, new DisposeAction(firebirdEmbeddedLibrary)); } @Override void dispose() { cleanable.clean(); } private record DisposeAction(DisposableFirebirdEmbeddedLibrary firebirdEmbeddedLibrary) implements Runnable { @Override public void run() { firebirdEmbeddedLibrary.dispose(); } } } }
red-soft-ru/jaybird
jaybird-native/src/main/java/org/firebirdsql/gds/ng/jna/FbEmbeddedDatabaseFactory.java
1,755
// Note Firebird 3+ embedded is fbclient + engineNN (e.g. engine12 for Firebird 3.0 / ODS 12)
line_comment
nl
/* * Firebird Open Source JDBC Driver * * Distributable under LGPL license. * You may obtain a copy of the License at http://www.gnu.org/copyleft/lgpl.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * LGPL License for more details. * * This file was created by members of the firebird development team. * All individual contributions remain the Copyright (C) of those * individuals. Contributors to this file are either listed here or * can be obtained from a source control history command. * * All rights reserved. */ package org.firebirdsql.gds.ng.jna; import com.sun.jna.Native; import com.sun.jna.Platform; import org.firebirdsql.gds.JaybirdSystemProperties; import org.firebirdsql.gds.ng.IAttachProperties; import org.firebirdsql.jaybird.util.Cleaners; import org.firebirdsql.jna.embedded.FirebirdEmbeddedLookup; import org.firebirdsql.jna.embedded.spi.DisposableFirebirdEmbeddedLibrary; import org.firebirdsql.jna.embedded.spi.FirebirdEmbeddedLibrary; import org.firebirdsql.jna.fbclient.FbClientLibrary; import org.firebirdsql.jna.fbclient.WinFbClientLibrary; import java.lang.ref.Cleaner; import java.nio.file.Path; import java.util.*; import static java.lang.System.Logger.Level.DEBUG; import static java.lang.System.Logger.Level.ERROR; import static java.lang.System.Logger.Level.INFO; import static java.util.Objects.requireNonNull; /** * Implementation of {@link org.firebirdsql.gds.ng.FbDatabaseFactory} for establishing connection using the * Firebird embedded library. * * @author Mark Rotteveel * @since 3.0 */ public final class FbEmbeddedDatabaseFactory extends AbstractNativeDatabaseFactory { private static final System.Logger log = System.getLogger(FbEmbeddedDatabaseFactory.class.getName()); // Note Firebird<SUF> private static final List<String> LIBRARIES_TO_TRY = List.of("fbembed", FbClientDatabaseFactory.LIBRARY_NAME_FBCLIENT); private static final FbEmbeddedDatabaseFactory INSTANCE = new FbEmbeddedDatabaseFactory(); private FbEmbeddedDatabaseFactory() { // only through getInstance() } public static FbEmbeddedDatabaseFactory getInstance() { return INSTANCE; } @Override protected <T extends IAttachProperties<T>> T filterProperties(T attachProperties) { T attachPropertiesCopy = attachProperties.asNewMutable(); // Clear server name attachPropertiesCopy.setServerName(null); return attachPropertiesCopy; } @Override protected Collection<String> defaultLibraryNames() { return LIBRARIES_TO_TRY; } @Override protected FbClientLibrary createClientLibrary() { final List<Throwable> throwables = new ArrayList<>(); final List<String> librariesToTry = findLibrariesToTry(); for (String libraryName : librariesToTry) { try { if (Platform.isWindows()) { return Native.load(libraryName, WinFbClientLibrary.class); } else { return Native.load(libraryName, FbClientLibrary.class); } } catch (RuntimeException | UnsatisfiedLinkError e) { throwables.add(e); log.log(DEBUG, () -> "Attempt to load %s failed".formatted(libraryName), e); // continue with next } } assert throwables.size() == librariesToTry.size(); if (log.isLoggable(ERROR)) { log.log(ERROR, "Could not load any of the libraries in {0}:", librariesToTry); for (int idx = 0; idx < librariesToTry.size(); idx++) { log.log(ERROR, "Loading %s failed".formatted(librariesToTry.get(idx)), throwables.get(idx)); } } throw new NativeLibraryLoadException("Could not load any of " + librariesToTry + "; linking first exception", throwables.get(0)); } private List<String> findLibrariesToTry() { final String libraryPath = JaybirdSystemProperties.getNativeLibraryFbclient(); if (libraryPath != null) { return Collections.singletonList(libraryPath); } Optional<FirebirdEmbeddedLibrary> optionalFbEmbeddedInstance = FirebirdEmbeddedLookup.findFirebirdEmbedded(); if (optionalFbEmbeddedInstance.isPresent()) { FirebirdEmbeddedLibrary firebirdEmbeddedLibrary = optionalFbEmbeddedInstance.get(); log.log(INFO, "Found Firebird Embedded {0} on classpath", firebirdEmbeddedLibrary.getVersion()); if (firebirdEmbeddedLibrary instanceof DisposableFirebirdEmbeddedLibrary disposableLibrary) { NativeResourceTracker.strongRegisterNativeResource( new FirebirdEmbeddedLibraryNativeResource(disposableLibrary)); } Path entryPointPath = firebirdEmbeddedLibrary.getEntryPointPath().toAbsolutePath(); List<String> librariesToTry = new ArrayList<>(LIBRARIES_TO_TRY.size() + 1); librariesToTry.add(entryPointPath.toString()); librariesToTry.addAll(LIBRARIES_TO_TRY); return librariesToTry; } return LIBRARIES_TO_TRY; } private static final class FirebirdEmbeddedLibraryNativeResource extends NativeResourceTracker.NativeResource { private final Cleaner.Cleanable cleanable; private FirebirdEmbeddedLibraryNativeResource(DisposableFirebirdEmbeddedLibrary firebirdEmbeddedLibrary) { requireNonNull(firebirdEmbeddedLibrary, "firebirdEmbeddedLibrary"); cleanable = Cleaners.getJbCleaner().register(this, new DisposeAction(firebirdEmbeddedLibrary)); } @Override void dispose() { cleanable.clean(); } private record DisposeAction(DisposableFirebirdEmbeddedLibrary firebirdEmbeddedLibrary) implements Runnable { @Override public void run() { firebirdEmbeddedLibrary.dispose(); } } } }
False
1,277
35
1,447
36
1,495
35
1,447
36
1,740
37
false
false
false
false
false
true
4,780
161649_11
/* * DragSortRecycler * * Added drag and drop functionality to your RecyclerView * * * Copyright 2014 Emile Belanger. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yoavst.quickapps.tools; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.support.annotation.Nullable; import java.lang.reflect.Modifier; public class DragSortRecycler extends RecyclerView.ItemDecoration implements RecyclerView.OnItemTouchListener { final String TAG = "DragSortRecycler"; final boolean DEBUG = false; private int dragHandleWidth = 0; private int selectedDragItemPos = -1; private int fingerAnchorY; private int fingerY; private int fingerOffsetInViewY; private float autoScrollWindow = 0.1f; private float autoScrollSpeed = 0.5f; private BitmapDrawable floatingItem; private Rect floatingItemStatingBounds; private Rect floatingItemBounds; private float floatingItemAlpha = 0.5f; private int floatingItemBgColor = 0; private int viewHandleId = -1; OnItemMovedListener moveInterface; private boolean isDragging; @Nullable OnDragStateChangedListener dragStateChangedListener; public interface OnItemMovedListener { public void onItemMoved(int from, int to); } public interface OnDragStateChangedListener { public void onDragStart(); public void onDragStop(); } private void debugLog(String log) { if (DEBUG) Log.d(TAG, log); } public RecyclerView.OnScrollListener getScrollListener() { return scrollListener; } /* * Set the item move interface */ public void setOnItemMovedListener(OnItemMovedListener swif) { moveInterface = swif; } public void setViewHandleId(int id) { viewHandleId = id; } public void setLeftDragArea(int w) { dragHandleWidth = w; } public void setFloatingAlpha(float a) { floatingItemAlpha = a; } public void setFloatingBgColor(int c) { floatingItemBgColor = c; } /* Set the window at top and bottom of list, must be between 0 and 0.5 For example 0.1 uses the top and bottom 10% of the lists for scrolling */ public void setAutoScrollWindow(float w) { autoScrollWindow = w; } /* Set the autoscroll speed, default is 0.5 */ public void setAutoScrollSpeed(float speed) { autoScrollSpeed = speed; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView rv, RecyclerView.State state) { super.getItemOffsets(outRect, view, rv, state); debugLog("getItemOffsets"); debugLog("View top = " + view.getTop()); if (selectedDragItemPos != -1) { int itemPos = rv.getChildPosition(view); debugLog("itemPos =" + itemPos); if(!canDragOver(itemPos)) { return; } //Movement of finger float totalMovement = fingerY-fingerAnchorY; if (itemPos == selectedDragItemPos) { view.setVisibility(View.INVISIBLE); } else { //Make view visible incase invisible view.setVisibility(View.VISIBLE); //Find middle of the floatingItem float floatMiddleY = floatingItemBounds.top + floatingItemBounds.height()/2; //Moving down the list //These will auto-animate if the device continually sends touch motion events // if (totalMovment>0) { if ((itemPos > selectedDragItemPos) && (view.getTop() < floatMiddleY)) { float amountUp = (floatMiddleY - view.getTop()) / (float)view.getHeight(); // amountUp *= 0.5f; if (amountUp > 1) amountUp = 1; outRect.top = -(int)(floatingItemBounds.height()*amountUp); outRect.bottom = (int)(floatingItemBounds.height()*amountUp); } }//Moving up the list // else if (totalMovment < 0) { if((itemPos < selectedDragItemPos) && (view.getBottom() > floatMiddleY)) { float amountDown = ((float)view.getBottom() - floatMiddleY) / (float)view.getHeight(); // amountDown *= 0.5f; if (amountDown > 1) amountDown = 1; outRect.top = (int)(floatingItemBounds.height()*amountDown); outRect.bottom = -(int)(floatingItemBounds.height()*amountDown); } } } } else { outRect.top = 0; outRect.bottom = 0; //Make view visible incase invisible view.setVisibility(View.VISIBLE); } } /** * Find the new position by scanning through the items on * screen and finding the positional relationship. * This *seems* to work, another method would be to use * getItemOffsets, but I think that could miss items?.. */ private int getNewPostion(RecyclerView rv) { int itemsOnScreen = rv.getLayoutManager().getChildCount(); float floatMiddleY = floatingItemBounds.top + floatingItemBounds.height()/2; int above=0; int below = Integer.MAX_VALUE; for (int n=0;n < itemsOnScreen;n++) //Scan though items on screen, however they may not { // be in order! View view = rv.getLayoutManager().getChildAt(n); if (view.getVisibility() != View.VISIBLE) continue; int itemPos = rv.getChildPosition(view); if (itemPos == selectedDragItemPos) //Don't check against itself! continue; float viewMiddleY = view.getTop() + view.getHeight()/2; if (floatMiddleY > viewMiddleY) //Is above this item { if (itemPos > above) above = itemPos; } else if (floatMiddleY <= viewMiddleY) //Is below this item { if (itemPos < below) below = itemPos; } } debugLog("above = " + above + " below = " + below); if (below != Integer.MAX_VALUE) { if (below < selectedDragItemPos) //Need to count itself below++; return below - 1; } else { if (above < selectedDragItemPos) above++; return above; } } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { debugLog("onInterceptTouchEvent"); //if (e.getAction() == MotionEvent.ACTION_DOWN) { View itemView = rv.findChildViewUnder(e.getX(), e.getY()); if (itemView==null) return false; boolean dragging = false; if ((dragHandleWidth > 0 ) && (e.getX() < dragHandleWidth)) { dragging = true; } else if (viewHandleId != -1) { //Find the handle in the list item View handleView = itemView.findViewById(viewHandleId); if (handleView == null) { Log.e(TAG, "The view ID " + viewHandleId + " was not found in the RecycleView item"); return false; } //View should be visible to drag if(handleView.getVisibility()!=View.VISIBLE) { return false; } //We need to find the relative position of the handle to the parent view //Then we can work out if the touch is within the handle int[] parentItemPos = new int[2]; itemView.getLocationInWindow(parentItemPos); int[] handlePos = new int[2]; handleView.getLocationInWindow(handlePos); int xRel = handlePos[0] - parentItemPos[0]; int yRel = handlePos[1] - parentItemPos[1]; Rect touchBounds = new Rect(itemView.getLeft() + xRel, itemView.getTop() + yRel, itemView.getLeft() + xRel + handleView.getWidth(), itemView.getTop() + yRel + handleView.getHeight() ); if (touchBounds.contains((int)e.getX(), (int)e.getY())) dragging = true; debugLog("parentItemPos = " + parentItemPos[0] + " " + parentItemPos[1]); debugLog("handlePos = " + handlePos[0] + " " + handlePos[1]); } if (dragging) { debugLog("Started Drag"); setIsDragging(true); floatingItem = createFloatingBitmap(itemView); fingerAnchorY = (int)e.getY(); fingerOffsetInViewY = fingerAnchorY - itemView.getTop(); fingerY = fingerAnchorY; selectedDragItemPos = rv.getChildPosition(itemView); debugLog("selectedDragItemPos = " + selectedDragItemPos); return true; } } return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { debugLog("onTouchEvent"); if ((e.getAction() == MotionEvent.ACTION_UP) || (e.getAction() == MotionEvent.ACTION_CANCEL)) { if ((e.getAction() == MotionEvent.ACTION_UP) && selectedDragItemPos != -1) { int newPos = getNewPostion(rv); if (moveInterface != null) moveInterface.onItemMoved(selectedDragItemPos, newPos); } setIsDragging(false); selectedDragItemPos = -1; floatingItem = null; rv.invalidateItemDecorations(); return; } fingerY = (int)e.getY(); if (floatingItem!=null) { floatingItemBounds.top = fingerY - fingerOffsetInViewY; if (floatingItemBounds.top < -floatingItemStatingBounds.height()/2) //Allow half the view out the top floatingItemBounds.top = -floatingItemStatingBounds.height()/2; floatingItemBounds.bottom = floatingItemBounds.top + floatingItemStatingBounds.height(); floatingItem.setBounds(floatingItemBounds); } //Do auto scrolling at end of list float scrollAmount=0; if (fingerY > (rv.getHeight() * (1-autoScrollWindow))) { scrollAmount = (fingerY - (rv.getHeight() * (1-autoScrollWindow))); } else if (fingerY < (rv.getHeight() * autoScrollWindow)) { scrollAmount = (fingerY - (rv.getHeight() * autoScrollWindow)); } debugLog("Scroll: " + scrollAmount); scrollAmount *= autoScrollSpeed; rv.scrollBy(0, (int)scrollAmount); rv.invalidateItemDecorations();// Redraw } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { //FIXME } private void setIsDragging(final boolean dragging) { if(dragging != isDragging) { isDragging = dragging; if(dragStateChangedListener != null) { if (isDragging) { dragStateChangedListener.onDragStart(); } else { dragStateChangedListener.onDragStop(); } } } } public void setOnDragStateChangedListener(final OnDragStateChangedListener dragStateChangedListener) { this.dragStateChangedListener = dragStateChangedListener; } Paint bgColor = new Paint(); @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { if (floatingItem != null) { floatingItem.setAlpha((int)(255 * floatingItemAlpha)); bgColor.setColor(floatingItemBgColor); c.drawRect(floatingItemBounds,bgColor); floatingItem.draw(c); } } RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); debugLog("Scrolled: " + dx + " " + dy); fingerAnchorY -= dy; } }; /** * * * @param position * @return True if we can drag the item over this position, False if not. */ protected boolean canDragOver(int position) { return true; } private BitmapDrawable createFloatingBitmap(View v) { floatingItemStatingBounds = new Rect(v.getLeft(), v.getTop(),v.getRight(), v.getBottom()); floatingItemBounds = new Rect(floatingItemStatingBounds); Bitmap bitmap = Bitmap.createBitmap(floatingItemStatingBounds.width(), floatingItemStatingBounds.height(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); v.draw(canvas); BitmapDrawable retDrawable = new BitmapDrawable(v.getResources(), bitmap); retDrawable.setBounds(floatingItemBounds); return retDrawable; } }
yoavst/quickapps
app/src/main/java/com/yoavst/quickapps/tools/DragSortRecycler.java
4,075
// else if (totalMovment < 0)
line_comment
nl
/* * DragSortRecycler * * Added drag and drop functionality to your RecyclerView * * * Copyright 2014 Emile Belanger. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yoavst.quickapps.tools; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.support.annotation.Nullable; import java.lang.reflect.Modifier; public class DragSortRecycler extends RecyclerView.ItemDecoration implements RecyclerView.OnItemTouchListener { final String TAG = "DragSortRecycler"; final boolean DEBUG = false; private int dragHandleWidth = 0; private int selectedDragItemPos = -1; private int fingerAnchorY; private int fingerY; private int fingerOffsetInViewY; private float autoScrollWindow = 0.1f; private float autoScrollSpeed = 0.5f; private BitmapDrawable floatingItem; private Rect floatingItemStatingBounds; private Rect floatingItemBounds; private float floatingItemAlpha = 0.5f; private int floatingItemBgColor = 0; private int viewHandleId = -1; OnItemMovedListener moveInterface; private boolean isDragging; @Nullable OnDragStateChangedListener dragStateChangedListener; public interface OnItemMovedListener { public void onItemMoved(int from, int to); } public interface OnDragStateChangedListener { public void onDragStart(); public void onDragStop(); } private void debugLog(String log) { if (DEBUG) Log.d(TAG, log); } public RecyclerView.OnScrollListener getScrollListener() { return scrollListener; } /* * Set the item move interface */ public void setOnItemMovedListener(OnItemMovedListener swif) { moveInterface = swif; } public void setViewHandleId(int id) { viewHandleId = id; } public void setLeftDragArea(int w) { dragHandleWidth = w; } public void setFloatingAlpha(float a) { floatingItemAlpha = a; } public void setFloatingBgColor(int c) { floatingItemBgColor = c; } /* Set the window at top and bottom of list, must be between 0 and 0.5 For example 0.1 uses the top and bottom 10% of the lists for scrolling */ public void setAutoScrollWindow(float w) { autoScrollWindow = w; } /* Set the autoscroll speed, default is 0.5 */ public void setAutoScrollSpeed(float speed) { autoScrollSpeed = speed; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView rv, RecyclerView.State state) { super.getItemOffsets(outRect, view, rv, state); debugLog("getItemOffsets"); debugLog("View top = " + view.getTop()); if (selectedDragItemPos != -1) { int itemPos = rv.getChildPosition(view); debugLog("itemPos =" + itemPos); if(!canDragOver(itemPos)) { return; } //Movement of finger float totalMovement = fingerY-fingerAnchorY; if (itemPos == selectedDragItemPos) { view.setVisibility(View.INVISIBLE); } else { //Make view visible incase invisible view.setVisibility(View.VISIBLE); //Find middle of the floatingItem float floatMiddleY = floatingItemBounds.top + floatingItemBounds.height()/2; //Moving down the list //These will auto-animate if the device continually sends touch motion events // if (totalMovment>0) { if ((itemPos > selectedDragItemPos) && (view.getTop() < floatMiddleY)) { float amountUp = (floatMiddleY - view.getTop()) / (float)view.getHeight(); // amountUp *= 0.5f; if (amountUp > 1) amountUp = 1; outRect.top = -(int)(floatingItemBounds.height()*amountUp); outRect.bottom = (int)(floatingItemBounds.height()*amountUp); } }//Moving up the list // else if<SUF> { if((itemPos < selectedDragItemPos) && (view.getBottom() > floatMiddleY)) { float amountDown = ((float)view.getBottom() - floatMiddleY) / (float)view.getHeight(); // amountDown *= 0.5f; if (amountDown > 1) amountDown = 1; outRect.top = (int)(floatingItemBounds.height()*amountDown); outRect.bottom = -(int)(floatingItemBounds.height()*amountDown); } } } } else { outRect.top = 0; outRect.bottom = 0; //Make view visible incase invisible view.setVisibility(View.VISIBLE); } } /** * Find the new position by scanning through the items on * screen and finding the positional relationship. * This *seems* to work, another method would be to use * getItemOffsets, but I think that could miss items?.. */ private int getNewPostion(RecyclerView rv) { int itemsOnScreen = rv.getLayoutManager().getChildCount(); float floatMiddleY = floatingItemBounds.top + floatingItemBounds.height()/2; int above=0; int below = Integer.MAX_VALUE; for (int n=0;n < itemsOnScreen;n++) //Scan though items on screen, however they may not { // be in order! View view = rv.getLayoutManager().getChildAt(n); if (view.getVisibility() != View.VISIBLE) continue; int itemPos = rv.getChildPosition(view); if (itemPos == selectedDragItemPos) //Don't check against itself! continue; float viewMiddleY = view.getTop() + view.getHeight()/2; if (floatMiddleY > viewMiddleY) //Is above this item { if (itemPos > above) above = itemPos; } else if (floatMiddleY <= viewMiddleY) //Is below this item { if (itemPos < below) below = itemPos; } } debugLog("above = " + above + " below = " + below); if (below != Integer.MAX_VALUE) { if (below < selectedDragItemPos) //Need to count itself below++; return below - 1; } else { if (above < selectedDragItemPos) above++; return above; } } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { debugLog("onInterceptTouchEvent"); //if (e.getAction() == MotionEvent.ACTION_DOWN) { View itemView = rv.findChildViewUnder(e.getX(), e.getY()); if (itemView==null) return false; boolean dragging = false; if ((dragHandleWidth > 0 ) && (e.getX() < dragHandleWidth)) { dragging = true; } else if (viewHandleId != -1) { //Find the handle in the list item View handleView = itemView.findViewById(viewHandleId); if (handleView == null) { Log.e(TAG, "The view ID " + viewHandleId + " was not found in the RecycleView item"); return false; } //View should be visible to drag if(handleView.getVisibility()!=View.VISIBLE) { return false; } //We need to find the relative position of the handle to the parent view //Then we can work out if the touch is within the handle int[] parentItemPos = new int[2]; itemView.getLocationInWindow(parentItemPos); int[] handlePos = new int[2]; handleView.getLocationInWindow(handlePos); int xRel = handlePos[0] - parentItemPos[0]; int yRel = handlePos[1] - parentItemPos[1]; Rect touchBounds = new Rect(itemView.getLeft() + xRel, itemView.getTop() + yRel, itemView.getLeft() + xRel + handleView.getWidth(), itemView.getTop() + yRel + handleView.getHeight() ); if (touchBounds.contains((int)e.getX(), (int)e.getY())) dragging = true; debugLog("parentItemPos = " + parentItemPos[0] + " " + parentItemPos[1]); debugLog("handlePos = " + handlePos[0] + " " + handlePos[1]); } if (dragging) { debugLog("Started Drag"); setIsDragging(true); floatingItem = createFloatingBitmap(itemView); fingerAnchorY = (int)e.getY(); fingerOffsetInViewY = fingerAnchorY - itemView.getTop(); fingerY = fingerAnchorY; selectedDragItemPos = rv.getChildPosition(itemView); debugLog("selectedDragItemPos = " + selectedDragItemPos); return true; } } return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { debugLog("onTouchEvent"); if ((e.getAction() == MotionEvent.ACTION_UP) || (e.getAction() == MotionEvent.ACTION_CANCEL)) { if ((e.getAction() == MotionEvent.ACTION_UP) && selectedDragItemPos != -1) { int newPos = getNewPostion(rv); if (moveInterface != null) moveInterface.onItemMoved(selectedDragItemPos, newPos); } setIsDragging(false); selectedDragItemPos = -1; floatingItem = null; rv.invalidateItemDecorations(); return; } fingerY = (int)e.getY(); if (floatingItem!=null) { floatingItemBounds.top = fingerY - fingerOffsetInViewY; if (floatingItemBounds.top < -floatingItemStatingBounds.height()/2) //Allow half the view out the top floatingItemBounds.top = -floatingItemStatingBounds.height()/2; floatingItemBounds.bottom = floatingItemBounds.top + floatingItemStatingBounds.height(); floatingItem.setBounds(floatingItemBounds); } //Do auto scrolling at end of list float scrollAmount=0; if (fingerY > (rv.getHeight() * (1-autoScrollWindow))) { scrollAmount = (fingerY - (rv.getHeight() * (1-autoScrollWindow))); } else if (fingerY < (rv.getHeight() * autoScrollWindow)) { scrollAmount = (fingerY - (rv.getHeight() * autoScrollWindow)); } debugLog("Scroll: " + scrollAmount); scrollAmount *= autoScrollSpeed; rv.scrollBy(0, (int)scrollAmount); rv.invalidateItemDecorations();// Redraw } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { //FIXME } private void setIsDragging(final boolean dragging) { if(dragging != isDragging) { isDragging = dragging; if(dragStateChangedListener != null) { if (isDragging) { dragStateChangedListener.onDragStart(); } else { dragStateChangedListener.onDragStop(); } } } } public void setOnDragStateChangedListener(final OnDragStateChangedListener dragStateChangedListener) { this.dragStateChangedListener = dragStateChangedListener; } Paint bgColor = new Paint(); @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { if (floatingItem != null) { floatingItem.setAlpha((int)(255 * floatingItemAlpha)); bgColor.setColor(floatingItemBgColor); c.drawRect(floatingItemBounds,bgColor); floatingItem.draw(c); } } RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); debugLog("Scrolled: " + dx + " " + dy); fingerAnchorY -= dy; } }; /** * * * @param position * @return True if we can drag the item over this position, False if not. */ protected boolean canDragOver(int position) { return true; } private BitmapDrawable createFloatingBitmap(View v) { floatingItemStatingBounds = new Rect(v.getLeft(), v.getTop(),v.getRight(), v.getBottom()); floatingItemBounds = new Rect(floatingItemStatingBounds); Bitmap bitmap = Bitmap.createBitmap(floatingItemStatingBounds.width(), floatingItemStatingBounds.height(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); v.draw(canvas); BitmapDrawable retDrawable = new BitmapDrawable(v.getResources(), bitmap); retDrawable.setBounds(floatingItemBounds); return retDrawable; } }
False
3,027
11
3,261
11
3,537
11
3,261
11
3,987
12
false
false
false
false
false
true
1,919
39119_1
import jdk.nashorn.internal.ir.ContinueNode; import java.security.acl.Owner; /** * Created by yketd on 14-9-2016. */ public class Ontwikkelaar extends Thread { private long workTime = 3000; private boolean isWaiting; public void run() { while (true) { work(); meldBeschikbaar(); } } private void work() { try { Thread.sleep(OntwikkelBedrijf.getRandomTime()); } catch (InterruptedException ie) { } } private void meldBeschikbaar() { // System.out.println("proberen beschikbaar te melden"); try { isWaiting = true; OntwikkelBedrijf.increaseDevsWaiting.acquire(); if (!OntwikkelBedrijf.leiderInOverleg && OntwikkelBedrijf.ontwikkelaarsInMeeting != 3) { OntwikkelBedrijf.ontwikkelaarsInMeeting += 1; OntwikkelBedrijf.readyForUserMeeting.release(); System.out.println("ik ben de " + OntwikkelBedrijf.ontwikkelaarsInMeeting + "'e persoon in de wachtrij"); OntwikkelBedrijf.devMeeting.countDown(); OntwikkelBedrijf.increaseDevsWaiting.release(); OntwikkelBedrijf.devInvitation.acquire(); isWaiting = false; System.out.println("invite acquired, meeting starts.."); haveMeeting(); OntwikkelBedrijf.readyForUserMeeting.acquire(); } else { OntwikkelBedrijf.increaseDevsWaiting.release(); } } catch (InterruptedException ie) { System.out.println("i am not needed, going back to work"); } } private void haveMeeting() { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } public boolean isWaiting(){ return isWaiting; } }
YketD/concurrency-week-2
src/Ontwikkelaar.java
608
// System.out.println("proberen beschikbaar te melden");
line_comment
nl
import jdk.nashorn.internal.ir.ContinueNode; import java.security.acl.Owner; /** * Created by yketd on 14-9-2016. */ public class Ontwikkelaar extends Thread { private long workTime = 3000; private boolean isWaiting; public void run() { while (true) { work(); meldBeschikbaar(); } } private void work() { try { Thread.sleep(OntwikkelBedrijf.getRandomTime()); } catch (InterruptedException ie) { } } private void meldBeschikbaar() { // System.out.println("proberen beschikbaar<SUF> try { isWaiting = true; OntwikkelBedrijf.increaseDevsWaiting.acquire(); if (!OntwikkelBedrijf.leiderInOverleg && OntwikkelBedrijf.ontwikkelaarsInMeeting != 3) { OntwikkelBedrijf.ontwikkelaarsInMeeting += 1; OntwikkelBedrijf.readyForUserMeeting.release(); System.out.println("ik ben de " + OntwikkelBedrijf.ontwikkelaarsInMeeting + "'e persoon in de wachtrij"); OntwikkelBedrijf.devMeeting.countDown(); OntwikkelBedrijf.increaseDevsWaiting.release(); OntwikkelBedrijf.devInvitation.acquire(); isWaiting = false; System.out.println("invite acquired, meeting starts.."); haveMeeting(); OntwikkelBedrijf.readyForUserMeeting.acquire(); } else { OntwikkelBedrijf.increaseDevsWaiting.release(); } } catch (InterruptedException ie) { System.out.println("i am not needed, going back to work"); } } private void haveMeeting() { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } public boolean isWaiting(){ return isWaiting; } }
False
448
16
502
20
490
14
502
20
596
18
false
false
false
false
false
true
4,673
78672_0
package be.cegeka.stickyprint.core; import be.cegeka.stickyprint.core.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.awt.*; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; @Service public class PrintingApplicationServiceImpl implements PrintingApplicationService { @Autowired private Printer printer; @Autowired private ImageRenderService imageRenderService; static { System.setProperty("com.sun.media.jai.disableMediaLib", "true"); } //de volgende waarden zijn "good enough" voor 58mm papier, vooral gevonden door trail&error public static final int FONT_SIZE = 200; public static final int LIJN1_OFFSET = 40; public static final int LIJN2_OFFSET = 42; public static final Font FONT = new Font("SansSerif", Font.PLAIN, FONT_SIZE); @Override public PrintingResult print(PrintTask printTask) { BufferedImage imageToPrint = createBitmap(printTask.getFirstLine(), printTask.getSecondLine()); printer.print(imageToPrint); return new PrintingResult(); } @Override public ImageRenderResult print(HtmlSnippet htmlSnippet, PaperHeight paperHeight, PaperWidth paperWidth) { ImageRenderResult imageRenderResult = imageRenderService.renderImage(htmlSnippet, paperHeight, paperWidth); printer.print(rotate90DX(imageRenderResult.getResult())); return imageRenderResult; } public BufferedImage createBitmap(PrintLine lijn1, PrintLine lijn2) { int imgHeight = Printer.HEIGHT_58MM; int imgWidth = getMinimumWidth(Printer.WIDTH_120MM, lijn1); imgWidth = getMinimumWidth(imgWidth, lijn2); BufferedImage img = new BufferedImage(imgWidth,imgHeight,BufferedImage.TYPE_BYTE_BINARY); Graphics2D g2 = img.createGraphics(); g2.setColor(Color.WHITE); g2.fillRect(0, 0, imgWidth, imgHeight); g2.setColor(Color.black); g2.setFont(FONT); g2.drawString(lijn1.getLineToPrint(),0 ,(imgHeight/2)- LIJN1_OFFSET); g2.drawString(lijn2.getLineToPrint(),0,imgHeight- LIJN2_OFFSET); return rotate90DX(img); } private static BufferedImage rotate90DX(BufferedImage src) { int newWidth = src.getHeight(); int newHeight = src.getWidth(); AffineTransform transform = new AffineTransform(); transform.translate(newWidth, 0); transform.rotate(Math.toRadians(90)); BufferedImage result = new BufferedImage(newWidth,newHeight,BufferedImage.TYPE_BYTE_BINARY); Graphics2D g2d = result.createGraphics(); g2d.drawImage(src, transform, null); g2d.dispose(); return result; } static int getMinimumWidth(int currentWidth, PrintLine lijn) { BufferedImage dummyImg = new BufferedImage(10000,400,BufferedImage.TYPE_BYTE_BINARY); Graphics2D g2 = dummyImg.createGraphics(); FontRenderContext fontRenderContext = g2.getFontRenderContext(); Rectangle2D stringBounds = FONT.getStringBounds(lijn.getLineToPrint(), fontRenderContext); int width = Math.max(currentWidth,(int)stringBounds.getWidth()+20); return width; } }
wannessels/stickyprint
stickyprint-core/src/main/java/be/cegeka/stickyprint/core/PrintingApplicationServiceImpl.java
1,021
//de volgende waarden zijn "good enough" voor 58mm papier, vooral gevonden door trail&error
line_comment
nl
package be.cegeka.stickyprint.core; import be.cegeka.stickyprint.core.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.awt.*; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; @Service public class PrintingApplicationServiceImpl implements PrintingApplicationService { @Autowired private Printer printer; @Autowired private ImageRenderService imageRenderService; static { System.setProperty("com.sun.media.jai.disableMediaLib", "true"); } //de volgende<SUF> public static final int FONT_SIZE = 200; public static final int LIJN1_OFFSET = 40; public static final int LIJN2_OFFSET = 42; public static final Font FONT = new Font("SansSerif", Font.PLAIN, FONT_SIZE); @Override public PrintingResult print(PrintTask printTask) { BufferedImage imageToPrint = createBitmap(printTask.getFirstLine(), printTask.getSecondLine()); printer.print(imageToPrint); return new PrintingResult(); } @Override public ImageRenderResult print(HtmlSnippet htmlSnippet, PaperHeight paperHeight, PaperWidth paperWidth) { ImageRenderResult imageRenderResult = imageRenderService.renderImage(htmlSnippet, paperHeight, paperWidth); printer.print(rotate90DX(imageRenderResult.getResult())); return imageRenderResult; } public BufferedImage createBitmap(PrintLine lijn1, PrintLine lijn2) { int imgHeight = Printer.HEIGHT_58MM; int imgWidth = getMinimumWidth(Printer.WIDTH_120MM, lijn1); imgWidth = getMinimumWidth(imgWidth, lijn2); BufferedImage img = new BufferedImage(imgWidth,imgHeight,BufferedImage.TYPE_BYTE_BINARY); Graphics2D g2 = img.createGraphics(); g2.setColor(Color.WHITE); g2.fillRect(0, 0, imgWidth, imgHeight); g2.setColor(Color.black); g2.setFont(FONT); g2.drawString(lijn1.getLineToPrint(),0 ,(imgHeight/2)- LIJN1_OFFSET); g2.drawString(lijn2.getLineToPrint(),0,imgHeight- LIJN2_OFFSET); return rotate90DX(img); } private static BufferedImage rotate90DX(BufferedImage src) { int newWidth = src.getHeight(); int newHeight = src.getWidth(); AffineTransform transform = new AffineTransform(); transform.translate(newWidth, 0); transform.rotate(Math.toRadians(90)); BufferedImage result = new BufferedImage(newWidth,newHeight,BufferedImage.TYPE_BYTE_BINARY); Graphics2D g2d = result.createGraphics(); g2d.drawImage(src, transform, null); g2d.dispose(); return result; } static int getMinimumWidth(int currentWidth, PrintLine lijn) { BufferedImage dummyImg = new BufferedImage(10000,400,BufferedImage.TYPE_BYTE_BINARY); Graphics2D g2 = dummyImg.createGraphics(); FontRenderContext fontRenderContext = g2.getFontRenderContext(); Rectangle2D stringBounds = FONT.getStringBounds(lijn.getLineToPrint(), fontRenderContext); int width = Math.max(currentWidth,(int)stringBounds.getWidth()+20); return width; } }
True
745
27
865
29
889
23
865
29
1,028
27
false
false
false
false
false
true
2,861
17408_12
/** * Spectral Clustering : Normalized * -------------------------------- * Implementatie van het "Normalized Spectral Clustering"-algoritme. * * @author Uyttersprot Bram */ package net.sf.javaml.clustering; import Jama.*; import java.io.*; import net.sf.javaml.core.Dataset; import net.sf.javaml.distance.DistanceMeasure; import net.sf.javaml.distance.CosineDistance; import net.sf.javaml.distance.EuclideanDistance; import net.sf.javaml.distance.ManhattanDistance; import net.sf.javaml.distance.NormDistance; import net.sf.javaml.tools.data.FileHandler; public class Normalized implements Clusterer{ /* Veld om het aantal clusters bij te houden.*/ private int numberOfClusters = 4; /* Variabele die tijdens het cluseren zijn nut zal bewijzen. */ private double maximum = 0; /* Index bijhouden van de te gebruiken afstandsmaat. */ private int indexOfDistance = 1; /* Constructor verwacht 2 argumenten: het aantal clusters en de index van de te gebruiken afstandsmaat.*/ public Normalized(int number, int dist){ numberOfClusters = number; indexOfDistance = dist; } public Dataset[] cluster(Dataset data){ /* Benodigde matrices aanmaken */ Matrix m = new Matrix(data.size(),data.size()); Matrix d = new Matrix(data.size(),data.size()); /* Afstandsmaat tussen datapunten*/ DistanceMeasure distance; switch(indexOfDistance){ case 0: distance = new CosineDistance(); break; case 1: distance = new EuclideanDistance(); break; case 2: distance = new ManhattanDistance(); break; case 3: distance = new NormDistance(); break; default:distance = new EuclideanDistance(); } /* Gewichtsmatrix aanmaken */ for(int i=0; i < m.getRowDimension(); i++){ for(int j=0; j < m.getColumnDimension(); j++){ m.set(i, j, distance.measure(data.get(i), data.get(j))); if(m.get(i, j) > maximum) maximum = m.get(i, j); } } /* Similariteitsmatrix en degree matrix hieruit berekenen. */ for(int i=0; i < m.getRowDimension(); i++){ for(int j=0; j < m.getColumnDimension(); j++){ double temp = Math.abs(maximum - m.get(i, j)); m.set(i, j, temp); d.set(i, i, d.get(i, i) + temp); } } /* Laplace matrix berekenen L = D - W */ Matrix l = d.minus(m); /* Symmetrische Laplace matrix hieruit berekenen */ d = d.inverse(); for(int i=0; i < d.getRowDimension(); i++) d.set(i, i, Math.sqrt(d.get(i, i))); l = l.times(d); d = d.times(l); /* Gewenste eigenvectoren berekenen. */ EigenvalueDecomposition e = d.eig(); Matrix V = e.getV(); V = V.getMatrix(0, V.getRowDimension() - 1, 0, numberOfClusters-1); Matrix T = new Matrix(V.getRowDimension(),V.getColumnDimension()); for(int i=0; i < V.getRowDimension(); i++){ Matrix P = V.getMatrix(i, i, 0, V.getColumnDimension() - 1); double norm = P.normF(); for(int j=0; j < V.getColumnDimension(); j++){ T.set(i, j, V.get(i, j)/norm); } } /* Tijdelijk wegschrijven van de eigenvectoren naar een bestand temp.data */ try{ FileWriter w = new FileWriter(new File("temp.data")); /* Eigenvectoren één voor één wegschrijven */ for(int i=0; i < T.getRowDimension(); i++){ for(int j=0; j < T.getColumnDimension(); j++){ w.write("" + T.get(i, j) + ""); if(j != (T.getColumnDimension() - 1)) w.write(", "); } w.write("\n"); } w.flush(); /* FileWriter sluiten*/ w.close(); }catch(Exception ex){ // leeg } /* Net aangemaakt bestand inlezen om te laten verwerken door het KMeans-algoritme */ try{ Dataset dataset = FileHandler.loadDataset(new File("temp.data"),","); Clusterer km = new KMeans(numberOfClusters); Dataset[] clusters = km.cluster(dataset); return clusters; }catch(Exception exception){ return null; } } }
greenmoon55/textclustering
src/net/sf/javaml/clustering/Normalized.java
1,378
/* Net aangemaakt bestand inlezen om te laten verwerken door het KMeans-algoritme */
block_comment
nl
/** * Spectral Clustering : Normalized * -------------------------------- * Implementatie van het "Normalized Spectral Clustering"-algoritme. * * @author Uyttersprot Bram */ package net.sf.javaml.clustering; import Jama.*; import java.io.*; import net.sf.javaml.core.Dataset; import net.sf.javaml.distance.DistanceMeasure; import net.sf.javaml.distance.CosineDistance; import net.sf.javaml.distance.EuclideanDistance; import net.sf.javaml.distance.ManhattanDistance; import net.sf.javaml.distance.NormDistance; import net.sf.javaml.tools.data.FileHandler; public class Normalized implements Clusterer{ /* Veld om het aantal clusters bij te houden.*/ private int numberOfClusters = 4; /* Variabele die tijdens het cluseren zijn nut zal bewijzen. */ private double maximum = 0; /* Index bijhouden van de te gebruiken afstandsmaat. */ private int indexOfDistance = 1; /* Constructor verwacht 2 argumenten: het aantal clusters en de index van de te gebruiken afstandsmaat.*/ public Normalized(int number, int dist){ numberOfClusters = number; indexOfDistance = dist; } public Dataset[] cluster(Dataset data){ /* Benodigde matrices aanmaken */ Matrix m = new Matrix(data.size(),data.size()); Matrix d = new Matrix(data.size(),data.size()); /* Afstandsmaat tussen datapunten*/ DistanceMeasure distance; switch(indexOfDistance){ case 0: distance = new CosineDistance(); break; case 1: distance = new EuclideanDistance(); break; case 2: distance = new ManhattanDistance(); break; case 3: distance = new NormDistance(); break; default:distance = new EuclideanDistance(); } /* Gewichtsmatrix aanmaken */ for(int i=0; i < m.getRowDimension(); i++){ for(int j=0; j < m.getColumnDimension(); j++){ m.set(i, j, distance.measure(data.get(i), data.get(j))); if(m.get(i, j) > maximum) maximum = m.get(i, j); } } /* Similariteitsmatrix en degree matrix hieruit berekenen. */ for(int i=0; i < m.getRowDimension(); i++){ for(int j=0; j < m.getColumnDimension(); j++){ double temp = Math.abs(maximum - m.get(i, j)); m.set(i, j, temp); d.set(i, i, d.get(i, i) + temp); } } /* Laplace matrix berekenen L = D - W */ Matrix l = d.minus(m); /* Symmetrische Laplace matrix hieruit berekenen */ d = d.inverse(); for(int i=0; i < d.getRowDimension(); i++) d.set(i, i, Math.sqrt(d.get(i, i))); l = l.times(d); d = d.times(l); /* Gewenste eigenvectoren berekenen. */ EigenvalueDecomposition e = d.eig(); Matrix V = e.getV(); V = V.getMatrix(0, V.getRowDimension() - 1, 0, numberOfClusters-1); Matrix T = new Matrix(V.getRowDimension(),V.getColumnDimension()); for(int i=0; i < V.getRowDimension(); i++){ Matrix P = V.getMatrix(i, i, 0, V.getColumnDimension() - 1); double norm = P.normF(); for(int j=0; j < V.getColumnDimension(); j++){ T.set(i, j, V.get(i, j)/norm); } } /* Tijdelijk wegschrijven van de eigenvectoren naar een bestand temp.data */ try{ FileWriter w = new FileWriter(new File("temp.data")); /* Eigenvectoren één voor één wegschrijven */ for(int i=0; i < T.getRowDimension(); i++){ for(int j=0; j < T.getColumnDimension(); j++){ w.write("" + T.get(i, j) + ""); if(j != (T.getColumnDimension() - 1)) w.write(", "); } w.write("\n"); } w.flush(); /* FileWriter sluiten*/ w.close(); }catch(Exception ex){ // leeg } /* Net aangemaakt bestand<SUF>*/ try{ Dataset dataset = FileHandler.loadDataset(new File("temp.data"),","); Clusterer km = new KMeans(numberOfClusters); Dataset[] clusters = km.cluster(dataset); return clusters; }catch(Exception exception){ return null; } } }
True
1,036
24
1,207
27
1,219
22
1,207
27
1,367
28
false
false
false
false
false
true
3,318
92814_2
// License: GPL. For details, see LICENSE file. package com.kaart.laneconnectivity; import org.openstreetmap.josm.data.validation.OsmValidator; import org.openstreetmap.josm.gui.MapFrame; import org.openstreetmap.josm.plugins.Plugin; import org.openstreetmap.josm.plugins.PluginInformation; import com.kaart.laneconnectivity.gui.TurnLanesDialog; import com.kaart.laneconnectivity.validation.ConnectivityRelationCheck; /** * * @author Taylor Smock * */ public class LaneConnectivity extends Plugin { public static final String NAME = "Lane Connectivity"; private static PluginInformation info; public static final String PLUGIN_IMAGE = "turnlanes"; // TODO get an image public LaneConnectivity(PluginInformation info) { super(info); setInformation(info); OsmValidator.addTest(ConnectivityRelationCheck.class); } /** * Get the version number of the plugin * * @return The version number of the plugin */ public static String getVersion() { if (info == null) { return ""; } return info.localversion; } private static synchronized void setInformation(PluginInformation tInfo) { info = tInfo; } @Override public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { if (oldFrame == null && newFrame != null) { // there was none before newFrame.addToggleDialog(new TurnLanesDialog()); } } }
kaart-labs/lane-connectivity_plugin
src/main/java/com/kaart/laneconnectivity/LaneConnectivity.java
421
// TODO get an image
line_comment
nl
// License: GPL. For details, see LICENSE file. package com.kaart.laneconnectivity; import org.openstreetmap.josm.data.validation.OsmValidator; import org.openstreetmap.josm.gui.MapFrame; import org.openstreetmap.josm.plugins.Plugin; import org.openstreetmap.josm.plugins.PluginInformation; import com.kaart.laneconnectivity.gui.TurnLanesDialog; import com.kaart.laneconnectivity.validation.ConnectivityRelationCheck; /** * * @author Taylor Smock * */ public class LaneConnectivity extends Plugin { public static final String NAME = "Lane Connectivity"; private static PluginInformation info; public static final String PLUGIN_IMAGE = "turnlanes"; // TODO get<SUF> public LaneConnectivity(PluginInformation info) { super(info); setInformation(info); OsmValidator.addTest(ConnectivityRelationCheck.class); } /** * Get the version number of the plugin * * @return The version number of the plugin */ public static String getVersion() { if (info == null) { return ""; } return info.localversion; } private static synchronized void setInformation(PluginInformation tInfo) { info = tInfo; } @Override public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { if (oldFrame == null && newFrame != null) { // there was none before newFrame.addToggleDialog(new TurnLanesDialog()); } } }
False
329
5
358
5
386
5
358
5
416
5
false
false
false
false
false
true
194
92263_5
package smpt42.nl.printmanager.control; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import smpt42.nl.printmanager.model.Scan; import smpt42.nl.printmanager.model.enums.SORT_TYPE; /** * Created by Daan on 12/19/2014. */ public class ScanManager { public static Comparator<Scan> sortByDate = new Comparator<Scan>() { public int compare(Scan scan1, Scan scan2) { return scan1.getPrintDate().compareTo(scan2.getPrintDate()); } }; public static Comparator<Scan> sortByCompany = new Comparator<Scan>() { public int compare(Scan scan1, Scan scan2) { return scan1.getCompany().getName().compareTo(scan2.getCompany().getName()); } }; public static Comparator<Scan> sortByStarred = new Comparator<Scan>() { public int compare(Scan scan1, Scan scan2) { Boolean s1 = scan1.getIsStarred(); Boolean s2 = scan2.getIsStarred(); return s2.compareTo(s1); } }; ArrayList<Scan> scans; /** * Constructor */ public ScanManager(ArrayList<Scan> scans) { this.scans = scans; //db = new Database(); //try { // scans = db.getScans(); //} catch (ParseException pe) { // pe.printStackTrace(); //} } /** * Voeg een scan toe aan de lijst met scans * * @param scan De toe te voegen scan */ public void addScan(Scan scan) { scans.add(scan); } /** * Haalt de scans op, gesorteerd op de aangegeven eigenschap * * @param sorttype De eigenschap waarop gesorteerd moet worden * @return De gesorteerde lijst met scans */ public ArrayList<Scan> getScans(SORT_TYPE sorttype) { if (sorttype == SORT_TYPE.DATE) { Collections.sort(scans, sortByDate); } else if (sorttype == SORT_TYPE.COMPANY) { Collections.sort(scans, sortByCompany); } else if (sorttype == SORT_TYPE.STARRED) { Collections.sort(scans, sortByStarred); } else { return null; } return scans; } public ArrayList<Scan> getScans(String s) { ArrayList<Scan> returner = new ArrayList<>(); for (Scan scan : scans) { if (scan.hasString(s)) { returner.add(scan); } } return returner; } /** * Zoekt naar scans waarvan de naam (deels) bestaat uit de ingevulde zoekterm. * * @param input String met de zoekterm van de gebruiker * @return Gevonden scans, null bij geen resultaat */ public List<Scan> searchByName(String input) { List<Scan> result = null; for (Scan s : scans) { if (s.getName().contains(input)) { result.add(s); } } return result; } /** * Zoekt naar de scan met de opgegeven barcode * * @param barcode String met de barcode waarop gezocht moet worden * @return Gevonden scan, null bij geen resultaat */ public Scan searchByBarcode(String barcode) { Scan result = null; for (Scan s : scans) { if (s.getBarcode() == barcode) { // Immediately cancel after barcode has been found. return result; } } return null; } }
BasThomas/SMPT42
Printmanager/app/src/main/java/smpt42/nl/printmanager/control/ScanManager.java
1,050
/** * Voeg een scan toe aan de lijst met scans * * @param scan De toe te voegen scan */
block_comment
nl
package smpt42.nl.printmanager.control; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import smpt42.nl.printmanager.model.Scan; import smpt42.nl.printmanager.model.enums.SORT_TYPE; /** * Created by Daan on 12/19/2014. */ public class ScanManager { public static Comparator<Scan> sortByDate = new Comparator<Scan>() { public int compare(Scan scan1, Scan scan2) { return scan1.getPrintDate().compareTo(scan2.getPrintDate()); } }; public static Comparator<Scan> sortByCompany = new Comparator<Scan>() { public int compare(Scan scan1, Scan scan2) { return scan1.getCompany().getName().compareTo(scan2.getCompany().getName()); } }; public static Comparator<Scan> sortByStarred = new Comparator<Scan>() { public int compare(Scan scan1, Scan scan2) { Boolean s1 = scan1.getIsStarred(); Boolean s2 = scan2.getIsStarred(); return s2.compareTo(s1); } }; ArrayList<Scan> scans; /** * Constructor */ public ScanManager(ArrayList<Scan> scans) { this.scans = scans; //db = new Database(); //try { // scans = db.getScans(); //} catch (ParseException pe) { // pe.printStackTrace(); //} } /** * Voeg een scan<SUF>*/ public void addScan(Scan scan) { scans.add(scan); } /** * Haalt de scans op, gesorteerd op de aangegeven eigenschap * * @param sorttype De eigenschap waarop gesorteerd moet worden * @return De gesorteerde lijst met scans */ public ArrayList<Scan> getScans(SORT_TYPE sorttype) { if (sorttype == SORT_TYPE.DATE) { Collections.sort(scans, sortByDate); } else if (sorttype == SORT_TYPE.COMPANY) { Collections.sort(scans, sortByCompany); } else if (sorttype == SORT_TYPE.STARRED) { Collections.sort(scans, sortByStarred); } else { return null; } return scans; } public ArrayList<Scan> getScans(String s) { ArrayList<Scan> returner = new ArrayList<>(); for (Scan scan : scans) { if (scan.hasString(s)) { returner.add(scan); } } return returner; } /** * Zoekt naar scans waarvan de naam (deels) bestaat uit de ingevulde zoekterm. * * @param input String met de zoekterm van de gebruiker * @return Gevonden scans, null bij geen resultaat */ public List<Scan> searchByName(String input) { List<Scan> result = null; for (Scan s : scans) { if (s.getName().contains(input)) { result.add(s); } } return result; } /** * Zoekt naar de scan met de opgegeven barcode * * @param barcode String met de barcode waarop gezocht moet worden * @return Gevonden scan, null bij geen resultaat */ public Scan searchByBarcode(String barcode) { Scan result = null; for (Scan s : scans) { if (s.getBarcode() == barcode) { // Immediately cancel after barcode has been found. return result; } } return null; } }
True
814
31
892
30
954
31
892
30
1,053
34
false
false
false
false
false
true
1,773
147769_3
package net.tropicraft.core.common.entity.projectile;_x000D_ _x000D_ import net.minecraft.core.BlockPos;_x000D_ import net.minecraft.core.particles.ParticleTypes;_x000D_ import net.minecraft.nbt.CompoundTag;_x000D_ import net.minecraft.network.protocol.Packet;_x000D_ import net.minecraft.network.protocol.game.ClientGamePacketListener;_x000D_ import net.minecraft.world.entity.Entity;_x000D_ import net.minecraft.world.entity.EntityType;_x000D_ import net.minecraft.world.entity.MoverType;_x000D_ import net.minecraft.world.level.Level;_x000D_ import net.minecraft.world.level.block.Blocks;_x000D_ import net.minecraft.world.level.block.state.BlockState;_x000D_ import net.minecraft.world.phys.Vec3;_x000D_ import net.minecraftforge.api.distmarker.Dist;_x000D_ import net.minecraftforge.api.distmarker.OnlyIn;_x000D_ import net.minecraftforge.network.NetworkHooks;_x000D_ _x000D_ public class LavaBallEntity extends Entity {_x000D_ public boolean setFire;_x000D_ public float size;_x000D_ public boolean held;_x000D_ public int lifeTimer;_x000D_ _x000D_ public double accelerationX;_x000D_ public double accelerationY;_x000D_ public double accelerationZ;_x000D_ _x000D_ public LavaBallEntity(EntityType<? extends LavaBallEntity> type, Level world) {_x000D_ super(type, world);_x000D_ setFire = false;_x000D_ held = false;_x000D_ size = 1;_x000D_ lifeTimer = 0;_x000D_ }_x000D_ _x000D_ public LavaBallEntity(EntityType<? extends LavaBallEntity> type,Level world, double i, double j, double k, double motX, double motY, double motZ) {_x000D_ super(type, world);_x000D_ setFire = false;_x000D_ moveTo(i, j, k, 0, 0);_x000D_ accelerationX = motX;_x000D_ accelerationY = motY;_x000D_ accelerationZ = motZ;_x000D_ size = 1;_x000D_ held = false;_x000D_ lifeTimer = 0;_x000D_ }_x000D_ _x000D_ public LavaBallEntity(EntityType<? extends LavaBallEntity> type, Level world, float startSize) {_x000D_ super(type, world);_x000D_ size = startSize;_x000D_ setFire = false;_x000D_ held = true;_x000D_ lifeTimer = 0;_x000D_ }_x000D_ _x000D_ @Override_x000D_ public boolean isPickable() {_x000D_ return true;_x000D_ }_x000D_ _x000D_ @Override_x000D_ public boolean isPushable() {_x000D_ return true;_x000D_ }_x000D_ _x000D_ @OnlyIn(Dist.CLIENT)_x000D_ public void supahDrip() {_x000D_ float x = (float) getX();_x000D_ float y = (float) getY();_x000D_ float z = (float) getZ();_x000D_ _x000D_ if (level().isClientSide) {_x000D_ level().addParticle(ParticleTypes.LAVA, x, y, z, this.getDeltaMovement().x, -1.5F, this.getDeltaMovement().z);_x000D_ }_x000D_ }_x000D_ _x000D_ @Override_x000D_ protected void defineSynchedData() {_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void tick() {_x000D_ super.tick();_x000D_ // System.out.println("laba ball: " + posX + " " + posY + " " + posZ);_x000D_ _x000D_ if (lifeTimer < 500) {_x000D_ lifeTimer++;_x000D_ } else {_x000D_ this.remove(RemovalReason.DISCARDED);_x000D_ }_x000D_ _x000D_ double motionX = this.getDeltaMovement().x;_x000D_ double motionY = this.getDeltaMovement().y;_x000D_ double motionZ = this.getDeltaMovement().z;_x000D_ _x000D_ if (size < 1) {_x000D_ size += .025;_x000D_ }_x000D_ _x000D_ if (onGround()) {_x000D_ motionZ *= .95;_x000D_ motionX *= .95;_x000D_ }_x000D_ _x000D_ motionY *= .99;_x000D_ _x000D_ if (!onGround()) {_x000D_ motionY -=.05F;_x000D_ if (level().isClientSide) {_x000D_ for (int i = 0; i < 5 + random.nextInt(3); i++){_x000D_ supahDrip();_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ if (horizontalCollision) {_x000D_ motionZ = 0;_x000D_ motionX = 0;_x000D_ }_x000D_ _x000D_ //TODO: Note below, these used to be tempLavaMoving - maybe they still need to be?_x000D_ int thisX = (int)Math.floor(getX());_x000D_ int thisY = (int)Math.floor(getY());_x000D_ int thisZ = (int)Math.floor(getZ());_x000D_ _x000D_ BlockPos posCurrent = new BlockPos(thisX, thisY, thisZ);_x000D_ BlockPos posBelow = posCurrent.below();_x000D_ BlockState stateBelow = level().getBlockState(posBelow);_x000D_ _x000D_ if (!stateBelow.isAir() && !stateBelow.is(Blocks.LAVA) && !held) {_x000D_ if (setFire) {_x000D_ level().setBlock(posCurrent, Blocks.LAVA.defaultBlockState(), 3);_x000D_ this.remove(RemovalReason.DISCARDED);_x000D_ }_x000D_ _x000D_ if (!setFire) {_x000D_ if (level().isEmptyBlock(posCurrent.west())) {_x000D_ level().setBlock(posCurrent.west(), Blocks.LAVA.defaultBlockState(), 2);_x000D_ }_x000D_ _x000D_ if (level().isEmptyBlock(posCurrent.east())) {_x000D_ level().setBlock(posCurrent.east(), Blocks.LAVA.defaultBlockState(), 2);_x000D_ }_x000D_ _x000D_ if (level().isEmptyBlock(posCurrent.south())) {_x000D_ level().setBlock(posCurrent.south(), Blocks.LAVA.defaultBlockState(), 2);_x000D_ }_x000D_ _x000D_ if (level().isEmptyBlock(posCurrent.north())) {_x000D_ level().setBlock(posCurrent.north(), Blocks.LAVA.defaultBlockState(), 2);_x000D_ }_x000D_ _x000D_ level().setBlock(posCurrent, Blocks.LAVA.defaultBlockState(), 3);_x000D_ setFire = true;_x000D_ }_x000D_ }_x000D_ _x000D_ Vec3 motion = new Vec3(motionX + this.accelerationX, motionY + this.accelerationY, motionZ + this.accelerationZ);_x000D_ this.setDeltaMovement(motion);_x000D_ _x000D_ this.move(MoverType.SELF, motion);_x000D_ }_x000D_ _x000D_ // TODO: Need this again? 1.14_x000D_ /*@Override_x000D_ protected void entityInit() {_x000D_ _x000D_ }*/_x000D_ _x000D_ @Override_x000D_ protected void readAdditionalSaveData(CompoundTag nbt) {_x000D_ this.lifeTimer = nbt.getInt("lifeTimer");_x000D_ }_x000D_ _x000D_ @Override_x000D_ protected void addAdditionalSaveData(CompoundTag nbt) {_x000D_ nbt.putInt("lifeTimer", this.lifeTimer);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public Packet<ClientGamePacketListener> getAddEntityPacket() {_x000D_ return NetworkHooks.getEntitySpawningPacket(this);_x000D_ }_x000D_ _x000D_ }_x000D_
Tropicraft/Tropicraft
src/main/java/net/tropicraft/core/common/entity/projectile/LavaBallEntity.java
1,804
/*@Override_x000D_ protected void entityInit() {_x000D_ _x000D_ }*/
block_comment
nl
package net.tropicraft.core.common.entity.projectile;_x000D_ _x000D_ import net.minecraft.core.BlockPos;_x000D_ import net.minecraft.core.particles.ParticleTypes;_x000D_ import net.minecraft.nbt.CompoundTag;_x000D_ import net.minecraft.network.protocol.Packet;_x000D_ import net.minecraft.network.protocol.game.ClientGamePacketListener;_x000D_ import net.minecraft.world.entity.Entity;_x000D_ import net.minecraft.world.entity.EntityType;_x000D_ import net.minecraft.world.entity.MoverType;_x000D_ import net.minecraft.world.level.Level;_x000D_ import net.minecraft.world.level.block.Blocks;_x000D_ import net.minecraft.world.level.block.state.BlockState;_x000D_ import net.minecraft.world.phys.Vec3;_x000D_ import net.minecraftforge.api.distmarker.Dist;_x000D_ import net.minecraftforge.api.distmarker.OnlyIn;_x000D_ import net.minecraftforge.network.NetworkHooks;_x000D_ _x000D_ public class LavaBallEntity extends Entity {_x000D_ public boolean setFire;_x000D_ public float size;_x000D_ public boolean held;_x000D_ public int lifeTimer;_x000D_ _x000D_ public double accelerationX;_x000D_ public double accelerationY;_x000D_ public double accelerationZ;_x000D_ _x000D_ public LavaBallEntity(EntityType<? extends LavaBallEntity> type, Level world) {_x000D_ super(type, world);_x000D_ setFire = false;_x000D_ held = false;_x000D_ size = 1;_x000D_ lifeTimer = 0;_x000D_ }_x000D_ _x000D_ public LavaBallEntity(EntityType<? extends LavaBallEntity> type,Level world, double i, double j, double k, double motX, double motY, double motZ) {_x000D_ super(type, world);_x000D_ setFire = false;_x000D_ moveTo(i, j, k, 0, 0);_x000D_ accelerationX = motX;_x000D_ accelerationY = motY;_x000D_ accelerationZ = motZ;_x000D_ size = 1;_x000D_ held = false;_x000D_ lifeTimer = 0;_x000D_ }_x000D_ _x000D_ public LavaBallEntity(EntityType<? extends LavaBallEntity> type, Level world, float startSize) {_x000D_ super(type, world);_x000D_ size = startSize;_x000D_ setFire = false;_x000D_ held = true;_x000D_ lifeTimer = 0;_x000D_ }_x000D_ _x000D_ @Override_x000D_ public boolean isPickable() {_x000D_ return true;_x000D_ }_x000D_ _x000D_ @Override_x000D_ public boolean isPushable() {_x000D_ return true;_x000D_ }_x000D_ _x000D_ @OnlyIn(Dist.CLIENT)_x000D_ public void supahDrip() {_x000D_ float x = (float) getX();_x000D_ float y = (float) getY();_x000D_ float z = (float) getZ();_x000D_ _x000D_ if (level().isClientSide) {_x000D_ level().addParticle(ParticleTypes.LAVA, x, y, z, this.getDeltaMovement().x, -1.5F, this.getDeltaMovement().z);_x000D_ }_x000D_ }_x000D_ _x000D_ @Override_x000D_ protected void defineSynchedData() {_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void tick() {_x000D_ super.tick();_x000D_ // System.out.println("laba ball: " + posX + " " + posY + " " + posZ);_x000D_ _x000D_ if (lifeTimer < 500) {_x000D_ lifeTimer++;_x000D_ } else {_x000D_ this.remove(RemovalReason.DISCARDED);_x000D_ }_x000D_ _x000D_ double motionX = this.getDeltaMovement().x;_x000D_ double motionY = this.getDeltaMovement().y;_x000D_ double motionZ = this.getDeltaMovement().z;_x000D_ _x000D_ if (size < 1) {_x000D_ size += .025;_x000D_ }_x000D_ _x000D_ if (onGround()) {_x000D_ motionZ *= .95;_x000D_ motionX *= .95;_x000D_ }_x000D_ _x000D_ motionY *= .99;_x000D_ _x000D_ if (!onGround()) {_x000D_ motionY -=.05F;_x000D_ if (level().isClientSide) {_x000D_ for (int i = 0; i < 5 + random.nextInt(3); i++){_x000D_ supahDrip();_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ if (horizontalCollision) {_x000D_ motionZ = 0;_x000D_ motionX = 0;_x000D_ }_x000D_ _x000D_ //TODO: Note below, these used to be tempLavaMoving - maybe they still need to be?_x000D_ int thisX = (int)Math.floor(getX());_x000D_ int thisY = (int)Math.floor(getY());_x000D_ int thisZ = (int)Math.floor(getZ());_x000D_ _x000D_ BlockPos posCurrent = new BlockPos(thisX, thisY, thisZ);_x000D_ BlockPos posBelow = posCurrent.below();_x000D_ BlockState stateBelow = level().getBlockState(posBelow);_x000D_ _x000D_ if (!stateBelow.isAir() && !stateBelow.is(Blocks.LAVA) && !held) {_x000D_ if (setFire) {_x000D_ level().setBlock(posCurrent, Blocks.LAVA.defaultBlockState(), 3);_x000D_ this.remove(RemovalReason.DISCARDED);_x000D_ }_x000D_ _x000D_ if (!setFire) {_x000D_ if (level().isEmptyBlock(posCurrent.west())) {_x000D_ level().setBlock(posCurrent.west(), Blocks.LAVA.defaultBlockState(), 2);_x000D_ }_x000D_ _x000D_ if (level().isEmptyBlock(posCurrent.east())) {_x000D_ level().setBlock(posCurrent.east(), Blocks.LAVA.defaultBlockState(), 2);_x000D_ }_x000D_ _x000D_ if (level().isEmptyBlock(posCurrent.south())) {_x000D_ level().setBlock(posCurrent.south(), Blocks.LAVA.defaultBlockState(), 2);_x000D_ }_x000D_ _x000D_ if (level().isEmptyBlock(posCurrent.north())) {_x000D_ level().setBlock(posCurrent.north(), Blocks.LAVA.defaultBlockState(), 2);_x000D_ }_x000D_ _x000D_ level().setBlock(posCurrent, Blocks.LAVA.defaultBlockState(), 3);_x000D_ setFire = true;_x000D_ }_x000D_ }_x000D_ _x000D_ Vec3 motion = new Vec3(motionX + this.accelerationX, motionY + this.accelerationY, motionZ + this.accelerationZ);_x000D_ this.setDeltaMovement(motion);_x000D_ _x000D_ this.move(MoverType.SELF, motion);_x000D_ }_x000D_ _x000D_ // TODO: Need this again? 1.14_x000D_ /*@Override_x000D_ <SUF>*/_x000D_ _x000D_ @Override_x000D_ protected void readAdditionalSaveData(CompoundTag nbt) {_x000D_ this.lifeTimer = nbt.getInt("lifeTimer");_x000D_ }_x000D_ _x000D_ @Override_x000D_ protected void addAdditionalSaveData(CompoundTag nbt) {_x000D_ nbt.putInt("lifeTimer", this.lifeTimer);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public Packet<ClientGamePacketListener> getAddEntityPacket() {_x000D_ return NetworkHooks.getEntitySpawningPacket(this);_x000D_ }_x000D_ _x000D_ }_x000D_
False
2,531
30
2,687
33
2,825
34
2,687
33
3,037
37
false
false
false
false
false
true
4,725
75974_3
package byps.http; import java.util.concurrent.atomic.AtomicLong; /* USE THIS FILE ACCORDING TO THE COPYRIGHT RULES IN LICENSE.TXT WHICH IS PART OF THE SOURCE CODE PACKAGE */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import byps.BAsyncResult; import byps.BException; import byps.BExceptionC; import byps.BMessage; import byps.BMessageHeader; import byps.BOutput; import byps.BServer; import byps.BServerR; import byps.BTransport; /** * LongPoll-Nachricht: * */ public class HServerR extends BServerR { protected static final AtomicLong requstCounter = new AtomicLong(); public HServerR(BTransport transport, BServer server, int nbOfConns) { super(transport, server); this.nbOfConns = nbOfConns; this.sleepMillisBeforeRetry = 30 * 1000; } @Override public void start() throws BException { if (log.isDebugEnabled()) log.debug("start("); synchronized (refDone) { refDone[0] = false; } for (int i = 0; i < nbOfConns; i++) { sendLongPoll(null); } if (log.isDebugEnabled()) log.debug(")start"); } @Override public void done() { if (log.isDebugEnabled()) log.debug("done("); synchronized (refDone) { refDone[0] = true; refDone.notifyAll(); } // Wird von HWireClient.done() aufgerufen. // Dort werden die Long-Polls vom Server beendet. // workerThread.interrupt(); // // try { // workerThread.join(1000); // } // catch (InterruptedException ignored) {} if (log.isDebugEnabled()) log.debug(")done"); } protected class LongPoll implements Runnable { protected BMessage methodResult; protected LongPoll(BMessage methodResult) throws BException { if (log.isDebugEnabled()) log.debug("LongPoll(" + methodResult); final long requestId = HServerR.requstCounter.incrementAndGet(); if (methodResult != null) { this.methodResult = methodResult; } else { BOutput outp = transport.getOutput(); outp.header.flags |= BMessageHeader.FLAG_RESPONSE; outp.store(null); // irgendwas, damit auch der Header in den ByteBuffer // geschrieben wird. this.methodResult = outp.toMessage(requestId); } if (log.isDebugEnabled()) log.debug(")LongPoll"); } public void run() { if (log.isDebugEnabled()) log.debug("run("); final long startTime = System.currentTimeMillis(); if (log.isInfoEnabled()) log.info("sendr-" + methodResult.header.getTrackingId()); final BAsyncResult<BMessage> asyncResult = new BAsyncResult<BMessage>() { @Override public void setAsyncResult(BMessage msg, Throwable e) { if (log.isDebugEnabled()) log.debug("setAsyncResult(" + msg); final long requestId = HServerR.requstCounter.incrementAndGet(); try { if (e != null) { BOutput out = transport.getOutput(); out.header.flags = BMessageHeader.FLAG_RESPONSE; out.setException(e); msg = out.toMessage(requestId); } sendLongPoll(msg); } catch (BException e1) { if (log.isErrorEnabled()) log.error("Failed to send longpoll for obj=" + msg, e1); } if (log.isDebugEnabled()) log.debug(")setAsyncResult"); } }; BAsyncResult<BMessage> nextAsyncMethod = new BAsyncResult<BMessage>() { @Override public void setAsyncResult(BMessage msg, Throwable e) { if (log.isDebugEnabled()) log.debug("asyncMethod.setAsyncResult(" + msg + ", e=" + e); try { long endTime = System.currentTimeMillis(); if (log.isInfoEnabled()) log.info("sendr-" + methodResult.header.getTrackingId() + "[" + (endTime-startTime) + "]"); if (e == null) { // Execute the method received from server. transport.recv(server, msg, asyncResult); } else { BException ex = (BException) e; switch (ex.code) { case BExceptionC.SESSION_CLOSED: // Session was invalidated. log.info("Reverse request stops due to closed session."); break; case BExceptionC.UNAUTHORIZED: // Re-login required log.info("Reverse request was unauthorized."); break; case BExceptionC.CANCELLED: log.info("Reverse request was cancelled."); // no retry break; case BExceptionC.RESEND_LONG_POLL: log.info("Reverse request refreshs long-poll."); // HWireClientR has released the expried long-poll. // Ignore the error and send a new long-poll. asyncResult.setAsyncResult(null, null); break; default: onLostConnection(ex); break; } } } catch (Throwable ex) { // transport.recv failed if (log.isDebugEnabled()) log.debug("recv failed.", e); asyncResult.setAsyncResult(null, ex); } if (log.isDebugEnabled()) log.debug(")asyncMethod.setAsyncResult"); } private void onLostConnection(BException ex) { boolean callLostConnectionHandler = false; synchronized (refDone) { // Server still running? if (!refDone[0]) { try { if (lostConnectionHandler != null) { callLostConnectionHandler = true; } else { // Wait some seconds before next retry refDone.wait(sleepMillisBeforeRetry); } } catch (InterruptedException e1) { } } } if (callLostConnectionHandler) { log.info("Reverse request lost connection due to " + ex + ", call handler for lost connection."); lostConnectionHandler.onLostConnection(ex); } else { log.info("Reverse request refreshs long-poll after due to " + ex); asyncResult.setAsyncResult(null, null); } } }; // Sende den longPoll-Request // Im Body befindet sich die Antwort auf die vorige vom Server gestellte // Anfrage. // Als Ergebnis des longPoll kommt eine neue Serveranfrage (Methode). transport.getWire().sendR(methodResult, nextAsyncMethod); if (log.isDebugEnabled()) log.debug(")run"); } } protected void sendLongPoll(BMessage obj) throws BException { if (log.isDebugEnabled()) log.debug("sendLongPollInWorkerThread(" + obj); synchronized (refDone) { if (!refDone[0]) { LongPoll lp = new LongPoll(obj); lp.run(); } } // synchronized(this) { // if (log.isDebugEnabled()) log.debug("execute in worker thread"); // currentLongPoll_access_sync = lp; // this.notifyAll(); // } if (log.isDebugEnabled()) log.debug(")sendLongPollInWorkerThread"); } // protected class WorkerThread extends Thread { // WorkerThread() { // setName("longpoll-" + c_longPollCounter.incrementAndGet()); // } // // public void run() { // if (log.isDebugEnabled()) log.debug("LongPoll.run("); // try { // while (!isInterrupted()) { // LongPoll lp = null; // synchronized(HServerR.this) { // while (currentLongPoll_access_sync == null) { // if (log.isDebugEnabled()) log.debug("wait for LongPoll"); // HServerR.this.wait(); // } // lp = currentLongPoll_access_sync; // currentLongPoll_access_sync = null; // } // // try { // if (log.isDebugEnabled()) log.debug("execute LongPoll"); // lp.run(); // } // catch (Throwable e) { // log.error("LongPoll worker thread received uncaught exception.", e); // } // } // if (log.isDebugEnabled()) log.debug("Worker interrupted"); // } // catch (InterruptedException e) { // if (log.isDebugEnabled()) log.debug("Recevied "+ e); // } // if (log.isDebugEnabled()) log.debug(")LongPoll.run"); // } // } protected int nbOfConns; protected boolean[] refDone = new boolean[1]; protected final long sleepMillisBeforeRetry; // protected final Thread workerThread = new WorkerThread(); // protected LongPoll currentLongPoll_access_sync; private final static Logger log = LoggerFactory.getLogger(HServerR.class); }
wolfgangimig/byps
java/bypshttp/src/byps/http/HServerR.java
2,616
// Dort werden die Long-Polls vom Server beendet.
line_comment
nl
package byps.http; import java.util.concurrent.atomic.AtomicLong; /* USE THIS FILE ACCORDING TO THE COPYRIGHT RULES IN LICENSE.TXT WHICH IS PART OF THE SOURCE CODE PACKAGE */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import byps.BAsyncResult; import byps.BException; import byps.BExceptionC; import byps.BMessage; import byps.BMessageHeader; import byps.BOutput; import byps.BServer; import byps.BServerR; import byps.BTransport; /** * LongPoll-Nachricht: * */ public class HServerR extends BServerR { protected static final AtomicLong requstCounter = new AtomicLong(); public HServerR(BTransport transport, BServer server, int nbOfConns) { super(transport, server); this.nbOfConns = nbOfConns; this.sleepMillisBeforeRetry = 30 * 1000; } @Override public void start() throws BException { if (log.isDebugEnabled()) log.debug("start("); synchronized (refDone) { refDone[0] = false; } for (int i = 0; i < nbOfConns; i++) { sendLongPoll(null); } if (log.isDebugEnabled()) log.debug(")start"); } @Override public void done() { if (log.isDebugEnabled()) log.debug("done("); synchronized (refDone) { refDone[0] = true; refDone.notifyAll(); } // Wird von HWireClient.done() aufgerufen. // Dort werden<SUF> // workerThread.interrupt(); // // try { // workerThread.join(1000); // } // catch (InterruptedException ignored) {} if (log.isDebugEnabled()) log.debug(")done"); } protected class LongPoll implements Runnable { protected BMessage methodResult; protected LongPoll(BMessage methodResult) throws BException { if (log.isDebugEnabled()) log.debug("LongPoll(" + methodResult); final long requestId = HServerR.requstCounter.incrementAndGet(); if (methodResult != null) { this.methodResult = methodResult; } else { BOutput outp = transport.getOutput(); outp.header.flags |= BMessageHeader.FLAG_RESPONSE; outp.store(null); // irgendwas, damit auch der Header in den ByteBuffer // geschrieben wird. this.methodResult = outp.toMessage(requestId); } if (log.isDebugEnabled()) log.debug(")LongPoll"); } public void run() { if (log.isDebugEnabled()) log.debug("run("); final long startTime = System.currentTimeMillis(); if (log.isInfoEnabled()) log.info("sendr-" + methodResult.header.getTrackingId()); final BAsyncResult<BMessage> asyncResult = new BAsyncResult<BMessage>() { @Override public void setAsyncResult(BMessage msg, Throwable e) { if (log.isDebugEnabled()) log.debug("setAsyncResult(" + msg); final long requestId = HServerR.requstCounter.incrementAndGet(); try { if (e != null) { BOutput out = transport.getOutput(); out.header.flags = BMessageHeader.FLAG_RESPONSE; out.setException(e); msg = out.toMessage(requestId); } sendLongPoll(msg); } catch (BException e1) { if (log.isErrorEnabled()) log.error("Failed to send longpoll for obj=" + msg, e1); } if (log.isDebugEnabled()) log.debug(")setAsyncResult"); } }; BAsyncResult<BMessage> nextAsyncMethod = new BAsyncResult<BMessage>() { @Override public void setAsyncResult(BMessage msg, Throwable e) { if (log.isDebugEnabled()) log.debug("asyncMethod.setAsyncResult(" + msg + ", e=" + e); try { long endTime = System.currentTimeMillis(); if (log.isInfoEnabled()) log.info("sendr-" + methodResult.header.getTrackingId() + "[" + (endTime-startTime) + "]"); if (e == null) { // Execute the method received from server. transport.recv(server, msg, asyncResult); } else { BException ex = (BException) e; switch (ex.code) { case BExceptionC.SESSION_CLOSED: // Session was invalidated. log.info("Reverse request stops due to closed session."); break; case BExceptionC.UNAUTHORIZED: // Re-login required log.info("Reverse request was unauthorized."); break; case BExceptionC.CANCELLED: log.info("Reverse request was cancelled."); // no retry break; case BExceptionC.RESEND_LONG_POLL: log.info("Reverse request refreshs long-poll."); // HWireClientR has released the expried long-poll. // Ignore the error and send a new long-poll. asyncResult.setAsyncResult(null, null); break; default: onLostConnection(ex); break; } } } catch (Throwable ex) { // transport.recv failed if (log.isDebugEnabled()) log.debug("recv failed.", e); asyncResult.setAsyncResult(null, ex); } if (log.isDebugEnabled()) log.debug(")asyncMethod.setAsyncResult"); } private void onLostConnection(BException ex) { boolean callLostConnectionHandler = false; synchronized (refDone) { // Server still running? if (!refDone[0]) { try { if (lostConnectionHandler != null) { callLostConnectionHandler = true; } else { // Wait some seconds before next retry refDone.wait(sleepMillisBeforeRetry); } } catch (InterruptedException e1) { } } } if (callLostConnectionHandler) { log.info("Reverse request lost connection due to " + ex + ", call handler for lost connection."); lostConnectionHandler.onLostConnection(ex); } else { log.info("Reverse request refreshs long-poll after due to " + ex); asyncResult.setAsyncResult(null, null); } } }; // Sende den longPoll-Request // Im Body befindet sich die Antwort auf die vorige vom Server gestellte // Anfrage. // Als Ergebnis des longPoll kommt eine neue Serveranfrage (Methode). transport.getWire().sendR(methodResult, nextAsyncMethod); if (log.isDebugEnabled()) log.debug(")run"); } } protected void sendLongPoll(BMessage obj) throws BException { if (log.isDebugEnabled()) log.debug("sendLongPollInWorkerThread(" + obj); synchronized (refDone) { if (!refDone[0]) { LongPoll lp = new LongPoll(obj); lp.run(); } } // synchronized(this) { // if (log.isDebugEnabled()) log.debug("execute in worker thread"); // currentLongPoll_access_sync = lp; // this.notifyAll(); // } if (log.isDebugEnabled()) log.debug(")sendLongPollInWorkerThread"); } // protected class WorkerThread extends Thread { // WorkerThread() { // setName("longpoll-" + c_longPollCounter.incrementAndGet()); // } // // public void run() { // if (log.isDebugEnabled()) log.debug("LongPoll.run("); // try { // while (!isInterrupted()) { // LongPoll lp = null; // synchronized(HServerR.this) { // while (currentLongPoll_access_sync == null) { // if (log.isDebugEnabled()) log.debug("wait for LongPoll"); // HServerR.this.wait(); // } // lp = currentLongPoll_access_sync; // currentLongPoll_access_sync = null; // } // // try { // if (log.isDebugEnabled()) log.debug("execute LongPoll"); // lp.run(); // } // catch (Throwable e) { // log.error("LongPoll worker thread received uncaught exception.", e); // } // } // if (log.isDebugEnabled()) log.debug("Worker interrupted"); // } // catch (InterruptedException e) { // if (log.isDebugEnabled()) log.debug("Recevied "+ e); // } // if (log.isDebugEnabled()) log.debug(")LongPoll.run"); // } // } protected int nbOfConns; protected boolean[] refDone = new boolean[1]; protected final long sleepMillisBeforeRetry; // protected final Thread workerThread = new WorkerThread(); // protected LongPoll currentLongPoll_access_sync; private final static Logger log = LoggerFactory.getLogger(HServerR.class); }
False
1,889
12
2,075
14
2,264
12
2,075
14
2,556
14
false
false
false
false
false
true
3,745
150417_1
package be.kdg.blog.controllers; import be.kdg.blog.model.Blog; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.print.attribute.standard.Media; import javax.servlet.http.HttpServletRequest; /** * Created by Michael on 11/02/2018. */ @Controller public class ResponseBodyController { private final Blog blog; @Autowired public ResponseBodyController(Blog blog) { this.blog = blog; } @GetMapping(value = "/", produces = MediaType.TEXT_PLAIN_VALUE) @ResponseBody public String sayHello() { return "Hello, World!"; } @GetMapping(value = "/html", produces = MediaType.TEXT_HTML_VALUE) @ResponseBody public String sayHelloHtml() { final String hello = "<html><head><title>Hello!</title></head><body><h1>Hello, world!</h1></body></html>"; return hello; } @GetMapping(value="/blog", produces = MediaType.TEXT_HTML_VALUE) @ResponseBody public String getBlog() { StringBuilder html = new StringBuilder(); html.append("<!DOCTYPE html>"); html.append("<html> <body>"); html.append("<h1> My Blog </h1>"); for(int i = 0; i < blog.getEntries().size();i++) { html.append("<span>"); // Maken de header van de blog html.append("<h2>" + blog.getEntries().get(i).getSubject() + "</h2>"); //Voegen de tags toe html.append("<p>"+blog.getTags().get(i).getName()+"</p>"); // Voegen de tekst toe html.append("<p>"+blog.getEntries().get(i).getMessage()+"</p>"); // Voegen de datum toe html.append("<p>"+blog.getEntries().get(i).getDateTime()+"</p>"); html.append("</span>"); } html.append("</body> </html>"); return html.toString(); } @GetMapping(value = "/api/blog/entries/{entryId}", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public String getEntry(@PathVariable("entryId") int entryId) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); // Gaan er even vanuit dat de id overeenkomen met de volgorde waarin de entries worden toegevoegd. // Indien dit niet het geval, is lopen we over alle entries en kijken we waar de id gelijk is aan entryid. String json = gson.toJson(blog.getEntries().get(entryId-1)); return json; //return new Gson().toJson(blog.getEntries().get(entryId)); } @GetMapping(value = "/api/blog", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public String getEntryWithQueryString(@RequestParam("entryId") int entryId) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(blog.getEntries().get(entryId-1)); return json; } @GetMapping(value = "/api/blog/dynamic", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity<String> dynamic(@RequestParam("entryId") int entryId) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = null; HttpStatus status; // De Try catch is niet de mooiste oplossing. Beter zou zoals in het boek je een aparte private methode // schrijven die de blog entries doorzoeket en null teruggeeft als niets gevonden is. try { json = gson.toJson(blog.getEntries().get(entryId - 1)); } catch (Exception ex) { //No enryy is found json = null; } finally { status = json != null ? HttpStatus.OK : HttpStatus.NOT_FOUND; return new ResponseEntity<String>(json,status); } } }
msnm/sa2_opdracht1
src/main/java/be/kdg/blog/controllers/ResponseBodyController.java
1,231
// Maken de header van de blog
line_comment
nl
package be.kdg.blog.controllers; import be.kdg.blog.model.Blog; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.print.attribute.standard.Media; import javax.servlet.http.HttpServletRequest; /** * Created by Michael on 11/02/2018. */ @Controller public class ResponseBodyController { private final Blog blog; @Autowired public ResponseBodyController(Blog blog) { this.blog = blog; } @GetMapping(value = "/", produces = MediaType.TEXT_PLAIN_VALUE) @ResponseBody public String sayHello() { return "Hello, World!"; } @GetMapping(value = "/html", produces = MediaType.TEXT_HTML_VALUE) @ResponseBody public String sayHelloHtml() { final String hello = "<html><head><title>Hello!</title></head><body><h1>Hello, world!</h1></body></html>"; return hello; } @GetMapping(value="/blog", produces = MediaType.TEXT_HTML_VALUE) @ResponseBody public String getBlog() { StringBuilder html = new StringBuilder(); html.append("<!DOCTYPE html>"); html.append("<html> <body>"); html.append("<h1> My Blog </h1>"); for(int i = 0; i < blog.getEntries().size();i++) { html.append("<span>"); // Maken de<SUF> html.append("<h2>" + blog.getEntries().get(i).getSubject() + "</h2>"); //Voegen de tags toe html.append("<p>"+blog.getTags().get(i).getName()+"</p>"); // Voegen de tekst toe html.append("<p>"+blog.getEntries().get(i).getMessage()+"</p>"); // Voegen de datum toe html.append("<p>"+blog.getEntries().get(i).getDateTime()+"</p>"); html.append("</span>"); } html.append("</body> </html>"); return html.toString(); } @GetMapping(value = "/api/blog/entries/{entryId}", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public String getEntry(@PathVariable("entryId") int entryId) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); // Gaan er even vanuit dat de id overeenkomen met de volgorde waarin de entries worden toegevoegd. // Indien dit niet het geval, is lopen we over alle entries en kijken we waar de id gelijk is aan entryid. String json = gson.toJson(blog.getEntries().get(entryId-1)); return json; //return new Gson().toJson(blog.getEntries().get(entryId)); } @GetMapping(value = "/api/blog", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public String getEntryWithQueryString(@RequestParam("entryId") int entryId) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(blog.getEntries().get(entryId-1)); return json; } @GetMapping(value = "/api/blog/dynamic", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity<String> dynamic(@RequestParam("entryId") int entryId) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = null; HttpStatus status; // De Try catch is niet de mooiste oplossing. Beter zou zoals in het boek je een aparte private methode // schrijven die de blog entries doorzoeket en null teruggeeft als niets gevonden is. try { json = gson.toJson(blog.getEntries().get(entryId - 1)); } catch (Exception ex) { //No enryy is found json = null; } finally { status = json != null ? HttpStatus.OK : HttpStatus.NOT_FOUND; return new ResponseEntity<String>(json,status); } } }
True
911
8
1,072
8
1,096
8
1,072
8
1,274
8
false
false
false
false
false
true
4,505
38801_7
package com.taobao.rigel.rap.auto.generate.contract; import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.GeneratorType; import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.TargetObjectType; import com.taobao.rigel.rap.project.bo.Project.STAGE_TYPE; /** * generator interface, all generator class should * implement this interface * * @author Bosn */ public interface Generator { /** * is available on specific stage * * @param stage * @return */ boolean isAvailable(STAGE_TYPE stage); /** * get generator type * * @return */ GeneratorType getGeneratorType(); /** * get author * * @return author */ String getAuthor(); /** * get introduction of generator * * @return */ String getIntroduction(); /** * get target object type * * @return */ TargetObjectType getTargetObjectType(); /** * this method will be invoked automatically * by RAP before using, the type of Object is * decided by the return value of * getTargetObjectType() method, eg. if * result PROJECT, RAP will pass the proper * Project object automatically. * * @param project */ void setObject(Object obj); /** * do generate * * @return generated result */ String doGenerate(); }
thx/RAP
src/main/java/com/taobao/rigel/rap/auto/generate/contract/Generator.java
399
/** * do generate * * @return generated result */
block_comment
nl
package com.taobao.rigel.rap.auto.generate.contract; import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.GeneratorType; import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.TargetObjectType; import com.taobao.rigel.rap.project.bo.Project.STAGE_TYPE; /** * generator interface, all generator class should * implement this interface * * @author Bosn */ public interface Generator { /** * is available on specific stage * * @param stage * @return */ boolean isAvailable(STAGE_TYPE stage); /** * get generator type * * @return */ GeneratorType getGeneratorType(); /** * get author * * @return author */ String getAuthor(); /** * get introduction of generator * * @return */ String getIntroduction(); /** * get target object type * * @return */ TargetObjectType getTargetObjectType(); /** * this method will be invoked automatically * by RAP before using, the type of Object is * decided by the return value of * getTargetObjectType() method, eg. if * result PROJECT, RAP will pass the proper * Project object automatically. * * @param project */ void setObject(Object obj); /** * do generate <SUF>*/ String doGenerate(); }
False
319
17
343
15
375
19
343
15
410
19
false
false
false
false
false
true
1,573
154279_9
package com.example.examenopdracht; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.SearchView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements ReceptAdapter.onReceptClickListener { public static final String EXTRA_RECEPT_ID = "id"; public static final String EXTRA_RECEPT_TITLE = "title"; private RecyclerView rRecyclerView; private ReceptAdapter rReceptAdapter; private ArrayList<Recept> rReceptList; private RequestQueue rRequestQueue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rRecyclerView = findViewById(R.id.recyclerView); rRecyclerView.setHasFixedSize(true); rRecyclerView.setLayoutManager(new LinearLayoutManager(this)); rReceptList = new ArrayList<>(); rRequestQueue = Volley.newRequestQueue(this); parseJSON("chicken"); } // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.mainmenu, menu); // MenuItem search = findViewById(R.id.action_search); // SearchView searchView = (SearchView) search.getActionView(); // searchView.setQueryHint("Search"); // // searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { // @Override // public boolean onQueryTextSubmit(String text) { // parseJSON(text); // return false; // } // // @Override // public boolean onQueryTextChange(String newText) { // return false; // } // }); // return super.onCreateOptionsMenu(menu); // } private void parseJSON(String text){ String host = "https://api.spoonacular.com/recipes/"; String what = "complexSearch?"; String key = "apiKey=f370281a5a7947a08019c2134d25b356"; String number = "&number=2"; String search = "&query=" + text; String params = number + search; String url = host + what + key + params; JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { //Responsen aanvragen met GET en de url @Override public void onResponse(JSONObject response) { try { JSONArray jsonArray = response.getJSONArray("results"); for(int i = 0; i <jsonArray.length(); i++){ JSONObject result = jsonArray.getJSONObject(i); String receptId = result.getString("id"); String receptTitle = result.getString("title"); String imageUrl = result.getString("image"); //Responsen opvangen en uithalen wat nodig rReceptList.add(new Recept(imageUrl,receptTitle,receptId)); //Responsen in Recept object steken } rReceptAdapter = new ReceptAdapter(MainActivity.this,rReceptList); rRecyclerView.setAdapter(rReceptAdapter); rReceptAdapter.setOnReceptClickListener(MainActivity.this); //zorgen er voor dat data in recyclerview terechtkomt } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); rRequestQueue.add(request); } @Override public void onReceptClick(int position) { Intent detailIntent = new Intent(this,DetailRecept.class); Recept clickedRecept = rReceptList.get(position); detailIntent.putExtra(EXTRA_RECEPT_ID, clickedRecept.getReceptId()); detailIntent.putExtra(EXTRA_RECEPT_TITLE, clickedRecept.getRreceptTitel()); startActivity(detailIntent); } }
SeppeBe1/AndroidDevelopmentApp
examenOpdracht/app/src/main/java/com/example/examenopdracht/MainActivity.java
1,327
//zorgen er voor dat data in recyclerview terechtkomt
line_comment
nl
package com.example.examenopdracht; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.SearchView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements ReceptAdapter.onReceptClickListener { public static final String EXTRA_RECEPT_ID = "id"; public static final String EXTRA_RECEPT_TITLE = "title"; private RecyclerView rRecyclerView; private ReceptAdapter rReceptAdapter; private ArrayList<Recept> rReceptList; private RequestQueue rRequestQueue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rRecyclerView = findViewById(R.id.recyclerView); rRecyclerView.setHasFixedSize(true); rRecyclerView.setLayoutManager(new LinearLayoutManager(this)); rReceptList = new ArrayList<>(); rRequestQueue = Volley.newRequestQueue(this); parseJSON("chicken"); } // public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.mainmenu, menu); // MenuItem search = findViewById(R.id.action_search); // SearchView searchView = (SearchView) search.getActionView(); // searchView.setQueryHint("Search"); // // searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { // @Override // public boolean onQueryTextSubmit(String text) { // parseJSON(text); // return false; // } // // @Override // public boolean onQueryTextChange(String newText) { // return false; // } // }); // return super.onCreateOptionsMenu(menu); // } private void parseJSON(String text){ String host = "https://api.spoonacular.com/recipes/"; String what = "complexSearch?"; String key = "apiKey=f370281a5a7947a08019c2134d25b356"; String number = "&number=2"; String search = "&query=" + text; String params = number + search; String url = host + what + key + params; JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { //Responsen aanvragen met GET en de url @Override public void onResponse(JSONObject response) { try { JSONArray jsonArray = response.getJSONArray("results"); for(int i = 0; i <jsonArray.length(); i++){ JSONObject result = jsonArray.getJSONObject(i); String receptId = result.getString("id"); String receptTitle = result.getString("title"); String imageUrl = result.getString("image"); //Responsen opvangen en uithalen wat nodig rReceptList.add(new Recept(imageUrl,receptTitle,receptId)); //Responsen in Recept object steken } rReceptAdapter = new ReceptAdapter(MainActivity.this,rReceptList); rRecyclerView.setAdapter(rReceptAdapter); rReceptAdapter.setOnReceptClickListener(MainActivity.this); //zorgen er<SUF> } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); rRequestQueue.add(request); } @Override public void onReceptClick(int position) { Intent detailIntent = new Intent(this,DetailRecept.class); Recept clickedRecept = rReceptList.get(position); detailIntent.putExtra(EXTRA_RECEPT_ID, clickedRecept.getReceptId()); detailIntent.putExtra(EXTRA_RECEPT_TITLE, clickedRecept.getRreceptTitel()); startActivity(detailIntent); } }
True
897
16
1,109
18
1,090
12
1,109
18
1,291
16
false
false
false
false
false
true
368
28754_9
package net.minecraft.src; import java.util.List; import java.util.Random; import net.minecraft.client.Minecraft; import org.lwjgl.input.Keyboard; public class GuiCreateWorld extends GuiScreen { private GuiScreen parentGuiScreen; private GuiTextField textboxWorldName; private GuiTextField textboxSeed; private String folderName; /** hardcore', 'creative' or 'survival */ private String gameMode; private boolean field_35365_g; private boolean field_40232_h; private boolean createClicked; /** * True if the extra options (Seed box, structure toggle button, world type button, etc.) are being shown */ private boolean moreOptions; /** The GUIButton that you click to change game modes. */ private GuiButton gameModeButton; /** * The GUIButton that you click to get to options like the seed when creating a world. */ private GuiButton moreWorldOptions; /** The GuiButton in the 'More World Options' screen. Toggles ON/OFF */ private GuiButton generateStructuresButton; /** * the GUIButton in the more world options screen. It's currently greyed out and unused in minecraft 1.0.0 */ private GuiButton worldTypeButton; /** The first line of text describing the currently selected game mode. */ private String gameModeDescriptionLine1; /** The second line of text describing the currently selected game mode. */ private String gameModeDescriptionLine2; /** The current textboxSeed text */ private String seed; /** E.g. New World, Neue Welt, Nieuwe wereld, Neuvo Mundo */ private String localizedNewWorldText; private int field_46030_z; public GuiCreateWorld(GuiScreen par1GuiScreen) { gameMode = "survival"; field_35365_g = true; field_40232_h = false; field_46030_z = 0; parentGuiScreen = par1GuiScreen; seed = ""; localizedNewWorldText = StatCollector.translateToLocal("selectWorld.newWorld"); } /** * Called from the main game loop to update the screen. */ public void updateScreen() { textboxWorldName.updateCursorCounter(); textboxSeed.updateCursorCounter(); } /** * Adds the buttons (and other controls) to the screen in question. */ public void initGui() { StringTranslate stringtranslate = StringTranslate.getInstance(); Keyboard.enableRepeatEvents(true); controlList.clear(); controlList.add(new GuiButton(0, width / 2 - 155, height - 28, 150, 20, stringtranslate.translateKey("selectWorld.create"))); controlList.add(new GuiButton(1, width / 2 + 5, height - 28, 150, 20, stringtranslate.translateKey("gui.cancel"))); controlList.add(gameModeButton = new GuiButton(2, width / 2 - 75, 100, 150, 20, stringtranslate.translateKey("selectWorld.gameMode"))); controlList.add(moreWorldOptions = new GuiButton(3, width / 2 - 75, 172, 150, 20, stringtranslate.translateKey("selectWorld.moreWorldOptions"))); controlList.add(generateStructuresButton = new GuiButton(4, width / 2 - 155, 100, 150, 20, stringtranslate.translateKey("selectWorld.mapFeatures"))); generateStructuresButton.drawButton = false; controlList.add(worldTypeButton = new GuiButton(5, width / 2 + 5, 100, 150, 20, stringtranslate.translateKey("selectWorld.mapType"))); worldTypeButton.drawButton = false; textboxWorldName = new GuiTextField(fontRenderer, width / 2 - 100, 60, 200, 20); textboxWorldName.setFocused(true); textboxWorldName.setText(localizedNewWorldText); textboxSeed = new GuiTextField(fontRenderer, width / 2 - 100, 60, 200, 20); textboxSeed.setText(seed); makeUseableName(); func_35363_g(); } /** * Makes a the name for a world save folder based on your world name, replacing specific characters for _s and * appending -s to the end until a free name is available. */ private void makeUseableName() { folderName = textboxWorldName.getText().trim(); char ac[] = ChatAllowedCharacters.allowedCharactersArray; int i = ac.length; for (int j = 0; j < i; j++) { char c = ac[j]; folderName = folderName.replace(c, '_'); } if (MathHelper.stringNullOrLengthZero(folderName)) { folderName = "World"; } folderName = func_25097_a(mc.getSaveLoader(), folderName); } private void func_35363_g() { StringTranslate stringtranslate; stringtranslate = StringTranslate.getInstance(); gameModeButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.gameMode")).append(" ").append(stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).toString())).toString(); gameModeDescriptionLine1 = stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).append(".line1").toString()); gameModeDescriptionLine2 = stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).append(".line2").toString()); generateStructuresButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.mapFeatures")).append(" ").toString(); if (!(!field_35365_g)) { generateStructuresButton.displayString += stringtranslate.translateKey("options.on"); } else { generateStructuresButton.displayString += stringtranslate.translateKey("options.off"); } worldTypeButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.mapType")).append(" ").append(stringtranslate.translateKey(WorldType.worldTypes[field_46030_z].getTranslateName())).toString(); return; } public static String func_25097_a(ISaveFormat par0ISaveFormat, String par1Str) { for (par1Str = par1Str.replaceAll("[\\./\"]|COM", "_"); par0ISaveFormat.getWorldInfo(par1Str) != null; par1Str = (new StringBuilder()).append(par1Str).append("-").toString()) { } return par1Str; } /** * Called when the screen is unloaded. Used to disable keyboard repeat events */ public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } /** * Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e). */ protected void actionPerformed(GuiButton par1GuiButton) { if (!par1GuiButton.enabled) { return; } if (par1GuiButton.id == 1) { mc.displayGuiScreen(parentGuiScreen); } else if (par1GuiButton.id == 0) { mc.displayGuiScreen(null); if (createClicked) { return; } createClicked = true; long l = (new Random()).nextLong(); String s = textboxSeed.getText(); if (!MathHelper.stringNullOrLengthZero(s)) { try { long l1 = Long.parseLong(s); if (l1 != 0L) { l = l1; } } catch (NumberFormatException numberformatexception) { l = s.hashCode(); } } int i = 0; if (gameMode.equals("creative")) { i = 1; mc.playerController = new PlayerControllerCreative(mc); } else { mc.playerController = new PlayerControllerSP(mc); } mc.startWorld(folderName, textboxWorldName.getText(), new WorldSettings(l, i, field_35365_g, field_40232_h, WorldType.worldTypes[field_46030_z])); mc.displayGuiScreen(null); } else if (par1GuiButton.id == 3) { moreOptions = !moreOptions; gameModeButton.drawButton = !moreOptions; generateStructuresButton.drawButton = moreOptions; worldTypeButton.drawButton = moreOptions; if (moreOptions) { StringTranslate stringtranslate = StringTranslate.getInstance(); moreWorldOptions.displayString = stringtranslate.translateKey("gui.done"); } else { StringTranslate stringtranslate1 = StringTranslate.getInstance(); moreWorldOptions.displayString = stringtranslate1.translateKey("selectWorld.moreWorldOptions"); } } else if (par1GuiButton.id == 2) { if (gameMode.equals("survival")) { field_40232_h = false; gameMode = "hardcore"; field_40232_h = true; func_35363_g(); } else if (gameMode.equals("hardcore")) { field_40232_h = false; gameMode = "creative"; func_35363_g(); field_40232_h = false; } else { gameMode = "survival"; func_35363_g(); field_40232_h = false; } func_35363_g(); } else if (par1GuiButton.id == 4) { field_35365_g = !field_35365_g; func_35363_g(); } else if (par1GuiButton.id == 5) { field_46030_z++; if (field_46030_z >= WorldType.worldTypes.length) { field_46030_z = 0; } do { if (WorldType.worldTypes[field_46030_z] != null && WorldType.worldTypes[field_46030_z].getCanBeCreated()) { break; } field_46030_z++; if (field_46030_z >= WorldType.worldTypes.length) { field_46030_z = 0; } } while (true); func_35363_g(); } } /** * Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e). */ protected void keyTyped(char par1, int par2) { if (textboxWorldName.getIsFocused() && !moreOptions) { textboxWorldName.textboxKeyTyped(par1, par2); localizedNewWorldText = textboxWorldName.getText(); } else if (textboxSeed.getIsFocused() && moreOptions) { textboxSeed.textboxKeyTyped(par1, par2); seed = textboxSeed.getText(); } if (par1 == '\r') { actionPerformed((GuiButton)controlList.get(0)); } ((GuiButton)controlList.get(0)).enabled = textboxWorldName.getText().length() > 0; makeUseableName(); } /** * Called when the mouse is clicked. */ protected void mouseClicked(int par1, int par2, int par3) { super.mouseClicked(par1, par2, par3); if (!moreOptions) { textboxWorldName.mouseClicked(par1, par2, par3); } else { textboxSeed.mouseClicked(par1, par2, par3); } } /** * Draws the screen and all the components in it. */ public void drawScreen(int par1, int par2, float par3) { StringTranslate stringtranslate = StringTranslate.getInstance(); drawDefaultBackground(); drawCenteredString(fontRenderer, stringtranslate.translateKey("selectWorld.create"), width / 2, 20, 0xffffff); if (!moreOptions) { drawString(fontRenderer, stringtranslate.translateKey("selectWorld.enterName"), width / 2 - 100, 47, 0xa0a0a0); drawString(fontRenderer, (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.resultFolder")).append(" ").append(folderName).toString(), width / 2 - 100, 85, 0xa0a0a0); textboxWorldName.drawTextBox(); drawString(fontRenderer, gameModeDescriptionLine1, width / 2 - 100, 122, 0xa0a0a0); drawString(fontRenderer, gameModeDescriptionLine2, width / 2 - 100, 134, 0xa0a0a0); } else { drawString(fontRenderer, stringtranslate.translateKey("selectWorld.enterSeed"), width / 2 - 100, 47, 0xa0a0a0); drawString(fontRenderer, stringtranslate.translateKey("selectWorld.seedInfo"), width / 2 - 100, 85, 0xa0a0a0); drawString(fontRenderer, stringtranslate.translateKey("selectWorld.mapFeatures.info"), width / 2 - 150, 122, 0xa0a0a0); textboxSeed.drawTextBox(); } super.drawScreen(par1, par2, par3); } }
DND91/mod_Discord
GuiCreateWorld.java
3,711
/** E.g. New World, Neue Welt, Nieuwe wereld, Neuvo Mundo */
block_comment
nl
package net.minecraft.src; import java.util.List; import java.util.Random; import net.minecraft.client.Minecraft; import org.lwjgl.input.Keyboard; public class GuiCreateWorld extends GuiScreen { private GuiScreen parentGuiScreen; private GuiTextField textboxWorldName; private GuiTextField textboxSeed; private String folderName; /** hardcore', 'creative' or 'survival */ private String gameMode; private boolean field_35365_g; private boolean field_40232_h; private boolean createClicked; /** * True if the extra options (Seed box, structure toggle button, world type button, etc.) are being shown */ private boolean moreOptions; /** The GUIButton that you click to change game modes. */ private GuiButton gameModeButton; /** * The GUIButton that you click to get to options like the seed when creating a world. */ private GuiButton moreWorldOptions; /** The GuiButton in the 'More World Options' screen. Toggles ON/OFF */ private GuiButton generateStructuresButton; /** * the GUIButton in the more world options screen. It's currently greyed out and unused in minecraft 1.0.0 */ private GuiButton worldTypeButton; /** The first line of text describing the currently selected game mode. */ private String gameModeDescriptionLine1; /** The second line of text describing the currently selected game mode. */ private String gameModeDescriptionLine2; /** The current textboxSeed text */ private String seed; /** E.g. New World,<SUF>*/ private String localizedNewWorldText; private int field_46030_z; public GuiCreateWorld(GuiScreen par1GuiScreen) { gameMode = "survival"; field_35365_g = true; field_40232_h = false; field_46030_z = 0; parentGuiScreen = par1GuiScreen; seed = ""; localizedNewWorldText = StatCollector.translateToLocal("selectWorld.newWorld"); } /** * Called from the main game loop to update the screen. */ public void updateScreen() { textboxWorldName.updateCursorCounter(); textboxSeed.updateCursorCounter(); } /** * Adds the buttons (and other controls) to the screen in question. */ public void initGui() { StringTranslate stringtranslate = StringTranslate.getInstance(); Keyboard.enableRepeatEvents(true); controlList.clear(); controlList.add(new GuiButton(0, width / 2 - 155, height - 28, 150, 20, stringtranslate.translateKey("selectWorld.create"))); controlList.add(new GuiButton(1, width / 2 + 5, height - 28, 150, 20, stringtranslate.translateKey("gui.cancel"))); controlList.add(gameModeButton = new GuiButton(2, width / 2 - 75, 100, 150, 20, stringtranslate.translateKey("selectWorld.gameMode"))); controlList.add(moreWorldOptions = new GuiButton(3, width / 2 - 75, 172, 150, 20, stringtranslate.translateKey("selectWorld.moreWorldOptions"))); controlList.add(generateStructuresButton = new GuiButton(4, width / 2 - 155, 100, 150, 20, stringtranslate.translateKey("selectWorld.mapFeatures"))); generateStructuresButton.drawButton = false; controlList.add(worldTypeButton = new GuiButton(5, width / 2 + 5, 100, 150, 20, stringtranslate.translateKey("selectWorld.mapType"))); worldTypeButton.drawButton = false; textboxWorldName = new GuiTextField(fontRenderer, width / 2 - 100, 60, 200, 20); textboxWorldName.setFocused(true); textboxWorldName.setText(localizedNewWorldText); textboxSeed = new GuiTextField(fontRenderer, width / 2 - 100, 60, 200, 20); textboxSeed.setText(seed); makeUseableName(); func_35363_g(); } /** * Makes a the name for a world save folder based on your world name, replacing specific characters for _s and * appending -s to the end until a free name is available. */ private void makeUseableName() { folderName = textboxWorldName.getText().trim(); char ac[] = ChatAllowedCharacters.allowedCharactersArray; int i = ac.length; for (int j = 0; j < i; j++) { char c = ac[j]; folderName = folderName.replace(c, '_'); } if (MathHelper.stringNullOrLengthZero(folderName)) { folderName = "World"; } folderName = func_25097_a(mc.getSaveLoader(), folderName); } private void func_35363_g() { StringTranslate stringtranslate; stringtranslate = StringTranslate.getInstance(); gameModeButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.gameMode")).append(" ").append(stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).toString())).toString(); gameModeDescriptionLine1 = stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).append(".line1").toString()); gameModeDescriptionLine2 = stringtranslate.translateKey((new StringBuilder()).append("selectWorld.gameMode.").append(gameMode).append(".line2").toString()); generateStructuresButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.mapFeatures")).append(" ").toString(); if (!(!field_35365_g)) { generateStructuresButton.displayString += stringtranslate.translateKey("options.on"); } else { generateStructuresButton.displayString += stringtranslate.translateKey("options.off"); } worldTypeButton.displayString = (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.mapType")).append(" ").append(stringtranslate.translateKey(WorldType.worldTypes[field_46030_z].getTranslateName())).toString(); return; } public static String func_25097_a(ISaveFormat par0ISaveFormat, String par1Str) { for (par1Str = par1Str.replaceAll("[\\./\"]|COM", "_"); par0ISaveFormat.getWorldInfo(par1Str) != null; par1Str = (new StringBuilder()).append(par1Str).append("-").toString()) { } return par1Str; } /** * Called when the screen is unloaded. Used to disable keyboard repeat events */ public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } /** * Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e). */ protected void actionPerformed(GuiButton par1GuiButton) { if (!par1GuiButton.enabled) { return; } if (par1GuiButton.id == 1) { mc.displayGuiScreen(parentGuiScreen); } else if (par1GuiButton.id == 0) { mc.displayGuiScreen(null); if (createClicked) { return; } createClicked = true; long l = (new Random()).nextLong(); String s = textboxSeed.getText(); if (!MathHelper.stringNullOrLengthZero(s)) { try { long l1 = Long.parseLong(s); if (l1 != 0L) { l = l1; } } catch (NumberFormatException numberformatexception) { l = s.hashCode(); } } int i = 0; if (gameMode.equals("creative")) { i = 1; mc.playerController = new PlayerControllerCreative(mc); } else { mc.playerController = new PlayerControllerSP(mc); } mc.startWorld(folderName, textboxWorldName.getText(), new WorldSettings(l, i, field_35365_g, field_40232_h, WorldType.worldTypes[field_46030_z])); mc.displayGuiScreen(null); } else if (par1GuiButton.id == 3) { moreOptions = !moreOptions; gameModeButton.drawButton = !moreOptions; generateStructuresButton.drawButton = moreOptions; worldTypeButton.drawButton = moreOptions; if (moreOptions) { StringTranslate stringtranslate = StringTranslate.getInstance(); moreWorldOptions.displayString = stringtranslate.translateKey("gui.done"); } else { StringTranslate stringtranslate1 = StringTranslate.getInstance(); moreWorldOptions.displayString = stringtranslate1.translateKey("selectWorld.moreWorldOptions"); } } else if (par1GuiButton.id == 2) { if (gameMode.equals("survival")) { field_40232_h = false; gameMode = "hardcore"; field_40232_h = true; func_35363_g(); } else if (gameMode.equals("hardcore")) { field_40232_h = false; gameMode = "creative"; func_35363_g(); field_40232_h = false; } else { gameMode = "survival"; func_35363_g(); field_40232_h = false; } func_35363_g(); } else if (par1GuiButton.id == 4) { field_35365_g = !field_35365_g; func_35363_g(); } else if (par1GuiButton.id == 5) { field_46030_z++; if (field_46030_z >= WorldType.worldTypes.length) { field_46030_z = 0; } do { if (WorldType.worldTypes[field_46030_z] != null && WorldType.worldTypes[field_46030_z].getCanBeCreated()) { break; } field_46030_z++; if (field_46030_z >= WorldType.worldTypes.length) { field_46030_z = 0; } } while (true); func_35363_g(); } } /** * Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e). */ protected void keyTyped(char par1, int par2) { if (textboxWorldName.getIsFocused() && !moreOptions) { textboxWorldName.textboxKeyTyped(par1, par2); localizedNewWorldText = textboxWorldName.getText(); } else if (textboxSeed.getIsFocused() && moreOptions) { textboxSeed.textboxKeyTyped(par1, par2); seed = textboxSeed.getText(); } if (par1 == '\r') { actionPerformed((GuiButton)controlList.get(0)); } ((GuiButton)controlList.get(0)).enabled = textboxWorldName.getText().length() > 0; makeUseableName(); } /** * Called when the mouse is clicked. */ protected void mouseClicked(int par1, int par2, int par3) { super.mouseClicked(par1, par2, par3); if (!moreOptions) { textboxWorldName.mouseClicked(par1, par2, par3); } else { textboxSeed.mouseClicked(par1, par2, par3); } } /** * Draws the screen and all the components in it. */ public void drawScreen(int par1, int par2, float par3) { StringTranslate stringtranslate = StringTranslate.getInstance(); drawDefaultBackground(); drawCenteredString(fontRenderer, stringtranslate.translateKey("selectWorld.create"), width / 2, 20, 0xffffff); if (!moreOptions) { drawString(fontRenderer, stringtranslate.translateKey("selectWorld.enterName"), width / 2 - 100, 47, 0xa0a0a0); drawString(fontRenderer, (new StringBuilder()).append(stringtranslate.translateKey("selectWorld.resultFolder")).append(" ").append(folderName).toString(), width / 2 - 100, 85, 0xa0a0a0); textboxWorldName.drawTextBox(); drawString(fontRenderer, gameModeDescriptionLine1, width / 2 - 100, 122, 0xa0a0a0); drawString(fontRenderer, gameModeDescriptionLine2, width / 2 - 100, 134, 0xa0a0a0); } else { drawString(fontRenderer, stringtranslate.translateKey("selectWorld.enterSeed"), width / 2 - 100, 47, 0xa0a0a0); drawString(fontRenderer, stringtranslate.translateKey("selectWorld.seedInfo"), width / 2 - 100, 85, 0xa0a0a0); drawString(fontRenderer, stringtranslate.translateKey("selectWorld.mapFeatures.info"), width / 2 - 150, 122, 0xa0a0a0); textboxSeed.drawTextBox(); } super.drawScreen(par1, par2, par3); } }
False
3,072
19
3,337
24
3,599
18
3,337
24
3,834
20
false
false
false
false
false
true
2,555
109790_3
/* Licensed to Diennea S.r.l. under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Diennea S.r.l. licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package herddb.utils; import io.netty.buffer.ByteBuf; import java.nio.charset.StandardCharsets; import java.util.List; /** * Utilities for write variable length values on {@link ByteBuf}. * * @author diego.salvi */ public class ByteBufUtils { public static void writeArray(ByteBuf buffer, byte[] array) { writeVInt(buffer, array.length); buffer.writeBytes(array); } public static void writeFloatArray(ByteBuf buffer, float[] array) { writeVInt(buffer, array.length); for (float f : array) { buffer.writeFloat(f); } } public static void writeFloatArray(ByteBuf buffer, List<Number> array) { writeVInt(buffer, array.size()); for (Number f : array) { buffer.writeFloat(f.floatValue()); } } public static void writeArray(ByteBuf buffer, Bytes array) { writeVInt(buffer, array.getLength()); buffer.writeBytes(array.getBuffer(), array.getOffset(), array.getLength()); } public static void writeArray(ByteBuf buffer, byte[] array, int offset, int length) { writeVInt(buffer, length); buffer.writeBytes(array, offset, length); } public static void writeString(ByteBuf buffer, String string) { writeArray(buffer, string.getBytes(StandardCharsets.UTF_8)); } public static void writeRawString(ByteBuf buffer, RawString string) { writeArray(buffer, string.getData(), string.getOffset(), string.getLength()); } public static byte[] readArray(ByteBuf buffer) { final int len = readVInt(buffer); final byte[] array = new byte[len]; buffer.readBytes(array); return array; } public static float[] readFloatArray(ByteBuf buffer) { final int len = readVInt(buffer); final float[] array = new float[len]; for (int i = 0; i < len; i++) { array[i] = buffer.readFloat(); } return array; } public static String readString(ByteBuf buffer) { final int len = readVInt(buffer); final byte[] array = new byte[len]; buffer.readBytes(array); return new String(array, StandardCharsets.UTF_8); } public static RawString readRawString(ByteBuf buffer) { final int len = readVInt(buffer); final byte[] array = new byte[len]; buffer.readBytes(array); return RawString.newPooledRawString(array, 0, len); } public static RawString readUnpooledRawString(ByteBuf buffer) { final int len = readVInt(buffer); final byte[] array = new byte[len]; buffer.readBytes(array); return RawString.newUnpooledRawString(array, 0, len); } public static void skipArray(ByteBuf buffer) { final int len = readVInt(buffer); buffer.skipBytes(len); } public static void writeVInt(ByteBuf buffer, int i) { if ((i & ~0x7F) != 0) { buffer.writeByte((byte) ((i & 0x7F) | 0x80)); i >>>= 7; if ((i & ~0x7F) != 0) { buffer.writeByte((byte) ((i & 0x7F) | 0x80)); i >>>= 7; if ((i & ~0x7F) != 0) { buffer.writeByte((byte) ((i & 0x7F) | 0x80)); i >>>= 7; if ((i & ~0x7F) != 0) { buffer.writeByte((byte) ((i & 0x7F) | 0x80)); i >>>= 7; } } } } buffer.writeByte((byte) i); } public static int readVInt(ByteBuf buffer) { byte b = buffer.readByte(); int i = b & 0x7F; if ((b & 0x80) != 0) { b = buffer.readByte(); i |= (b & 0x7F) << 7; if ((b & 0x80) != 0) { b = buffer.readByte(); i |= (b & 0x7F) << 14; if ((b & 0x80) != 0) { b = buffer.readByte(); i |= (b & 0x7F) << 21; if ((b & 0x80) != 0) { b = buffer.readByte(); i |= (b & 0x7F) << 28; } } } } return i; } public static void writeZInt(ByteBuf buffer, int i) { writeVInt(buffer, zigZagEncode(i)); } public static int readZInt(ByteBuf buffer) { return zigZagDecode(readVInt(buffer)); } public static void writeVLong(ByteBuf buffer, long i) { if (i < 0) { throw new IllegalArgumentException("cannot write negative vLong (got: " + i + ")"); } writeSignedVLong(buffer, i); } // write a potentially negative vLong private static void writeSignedVLong(ByteBuf buffer, long i) { while ((i & ~0x7FL) != 0L) { buffer.writeByte((byte) ((i & 0x7FL) | 0x80L)); i >>>= 7; } buffer.writeByte((byte) i); } public static long readVLong(ByteBuf buffer) { return readVLong(buffer, false); } private static long readVLong(ByteBuf buffer, boolean allowNegative) { byte b = buffer.readByte(); if (b >= 0) { return b; } long i = b & 0x7FL; b = buffer.readByte(); i |= (b & 0x7FL) << 7; if (b >= 0) { return i; } b = buffer.readByte(); i |= (b & 0x7FL) << 14; if (b >= 0) { return i; } b = buffer.readByte(); i |= (b & 0x7FL) << 21; if (b >= 0) { return i; } b = buffer.readByte(); i |= (b & 0x7FL) << 28; if (b >= 0) { return i; } b = buffer.readByte(); i |= (b & 0x7FL) << 35; if (b >= 0) { return i; } b = buffer.readByte(); i |= (b & 0x7FL) << 42; if (b >= 0) { return i; } b = buffer.readByte(); i |= (b & 0x7FL) << 49; if (b >= 0) { return i; } b = buffer.readByte(); i |= (b & 0x7FL) << 56; if (b >= 0) { return i; } if (allowNegative) { b = buffer.readByte(); i |= (b & 0x7FL) << 63; if (b == 0 || b == 1) { return i; } throw new IllegalArgumentException("Invalid vLong detected (more than 64 bits)"); } else { throw new IllegalArgumentException("Invalid vLong detected (negative values disallowed)"); } } public static void writeZLong(ByteBuf buffer, long i) { writeVLong(buffer, zigZagEncode(i)); } public static long readZLong(ByteBuf buffer) { return zigZagDecode(readVLong(buffer)); } public static void writeDouble(ByteBuf buffer, double i) { buffer.writeLong(Double.doubleToLongBits(i)); } public static double readDouble(ByteBuf buffer) { return Double.longBitsToDouble(buffer.readLong()); } /** * Same as {@link #zigZagEncode(long)} but on integers. */ private static int zigZagEncode(int i) { return (i >> 31) ^ (i << 1); } /** * <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">Zig-zag</a> * encode the provided long. Assuming the input is a signed long whose * absolute value can be stored on <tt>n</tt> bits, the returned value will * be an unsigned long that can be stored on <tt>n+1</tt> bits. */ private static long zigZagEncode(long l) { return (l >> 63) ^ (l << 1); } /** * Decode an int previously encoded with {@link #zigZagEncode(int)}. */ private static int zigZagDecode(int i) { return ((i >>> 1) ^ -(i & 1)); } /** * Decode a long previously encoded with {@link #zigZagEncode(long)}. */ private static long zigZagDecode(long l) { return ((l >>> 1) ^ -(l & 1)); } }
diennea/herddb
herddb-utils/src/main/java/herddb/utils/ByteBufUtils.java
2,745
/** * Same as {@link #zigZagEncode(long)} but on integers. */
block_comment
nl
/* Licensed to Diennea S.r.l. under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Diennea S.r.l. licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package herddb.utils; import io.netty.buffer.ByteBuf; import java.nio.charset.StandardCharsets; import java.util.List; /** * Utilities for write variable length values on {@link ByteBuf}. * * @author diego.salvi */ public class ByteBufUtils { public static void writeArray(ByteBuf buffer, byte[] array) { writeVInt(buffer, array.length); buffer.writeBytes(array); } public static void writeFloatArray(ByteBuf buffer, float[] array) { writeVInt(buffer, array.length); for (float f : array) { buffer.writeFloat(f); } } public static void writeFloatArray(ByteBuf buffer, List<Number> array) { writeVInt(buffer, array.size()); for (Number f : array) { buffer.writeFloat(f.floatValue()); } } public static void writeArray(ByteBuf buffer, Bytes array) { writeVInt(buffer, array.getLength()); buffer.writeBytes(array.getBuffer(), array.getOffset(), array.getLength()); } public static void writeArray(ByteBuf buffer, byte[] array, int offset, int length) { writeVInt(buffer, length); buffer.writeBytes(array, offset, length); } public static void writeString(ByteBuf buffer, String string) { writeArray(buffer, string.getBytes(StandardCharsets.UTF_8)); } public static void writeRawString(ByteBuf buffer, RawString string) { writeArray(buffer, string.getData(), string.getOffset(), string.getLength()); } public static byte[] readArray(ByteBuf buffer) { final int len = readVInt(buffer); final byte[] array = new byte[len]; buffer.readBytes(array); return array; } public static float[] readFloatArray(ByteBuf buffer) { final int len = readVInt(buffer); final float[] array = new float[len]; for (int i = 0; i < len; i++) { array[i] = buffer.readFloat(); } return array; } public static String readString(ByteBuf buffer) { final int len = readVInt(buffer); final byte[] array = new byte[len]; buffer.readBytes(array); return new String(array, StandardCharsets.UTF_8); } public static RawString readRawString(ByteBuf buffer) { final int len = readVInt(buffer); final byte[] array = new byte[len]; buffer.readBytes(array); return RawString.newPooledRawString(array, 0, len); } public static RawString readUnpooledRawString(ByteBuf buffer) { final int len = readVInt(buffer); final byte[] array = new byte[len]; buffer.readBytes(array); return RawString.newUnpooledRawString(array, 0, len); } public static void skipArray(ByteBuf buffer) { final int len = readVInt(buffer); buffer.skipBytes(len); } public static void writeVInt(ByteBuf buffer, int i) { if ((i & ~0x7F) != 0) { buffer.writeByte((byte) ((i & 0x7F) | 0x80)); i >>>= 7; if ((i & ~0x7F) != 0) { buffer.writeByte((byte) ((i & 0x7F) | 0x80)); i >>>= 7; if ((i & ~0x7F) != 0) { buffer.writeByte((byte) ((i & 0x7F) | 0x80)); i >>>= 7; if ((i & ~0x7F) != 0) { buffer.writeByte((byte) ((i & 0x7F) | 0x80)); i >>>= 7; } } } } buffer.writeByte((byte) i); } public static int readVInt(ByteBuf buffer) { byte b = buffer.readByte(); int i = b & 0x7F; if ((b & 0x80) != 0) { b = buffer.readByte(); i |= (b & 0x7F) << 7; if ((b & 0x80) != 0) { b = buffer.readByte(); i |= (b & 0x7F) << 14; if ((b & 0x80) != 0) { b = buffer.readByte(); i |= (b & 0x7F) << 21; if ((b & 0x80) != 0) { b = buffer.readByte(); i |= (b & 0x7F) << 28; } } } } return i; } public static void writeZInt(ByteBuf buffer, int i) { writeVInt(buffer, zigZagEncode(i)); } public static int readZInt(ByteBuf buffer) { return zigZagDecode(readVInt(buffer)); } public static void writeVLong(ByteBuf buffer, long i) { if (i < 0) { throw new IllegalArgumentException("cannot write negative vLong (got: " + i + ")"); } writeSignedVLong(buffer, i); } // write a potentially negative vLong private static void writeSignedVLong(ByteBuf buffer, long i) { while ((i & ~0x7FL) != 0L) { buffer.writeByte((byte) ((i & 0x7FL) | 0x80L)); i >>>= 7; } buffer.writeByte((byte) i); } public static long readVLong(ByteBuf buffer) { return readVLong(buffer, false); } private static long readVLong(ByteBuf buffer, boolean allowNegative) { byte b = buffer.readByte(); if (b >= 0) { return b; } long i = b & 0x7FL; b = buffer.readByte(); i |= (b & 0x7FL) << 7; if (b >= 0) { return i; } b = buffer.readByte(); i |= (b & 0x7FL) << 14; if (b >= 0) { return i; } b = buffer.readByte(); i |= (b & 0x7FL) << 21; if (b >= 0) { return i; } b = buffer.readByte(); i |= (b & 0x7FL) << 28; if (b >= 0) { return i; } b = buffer.readByte(); i |= (b & 0x7FL) << 35; if (b >= 0) { return i; } b = buffer.readByte(); i |= (b & 0x7FL) << 42; if (b >= 0) { return i; } b = buffer.readByte(); i |= (b & 0x7FL) << 49; if (b >= 0) { return i; } b = buffer.readByte(); i |= (b & 0x7FL) << 56; if (b >= 0) { return i; } if (allowNegative) { b = buffer.readByte(); i |= (b & 0x7FL) << 63; if (b == 0 || b == 1) { return i; } throw new IllegalArgumentException("Invalid vLong detected (more than 64 bits)"); } else { throw new IllegalArgumentException("Invalid vLong detected (negative values disallowed)"); } } public static void writeZLong(ByteBuf buffer, long i) { writeVLong(buffer, zigZagEncode(i)); } public static long readZLong(ByteBuf buffer) { return zigZagDecode(readVLong(buffer)); } public static void writeDouble(ByteBuf buffer, double i) { buffer.writeLong(Double.doubleToLongBits(i)); } public static double readDouble(ByteBuf buffer) { return Double.longBitsToDouble(buffer.readLong()); } /** * Same as {@link<SUF>*/ private static int zigZagEncode(int i) { return (i >> 31) ^ (i << 1); } /** * <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">Zig-zag</a> * encode the provided long. Assuming the input is a signed long whose * absolute value can be stored on <tt>n</tt> bits, the returned value will * be an unsigned long that can be stored on <tt>n+1</tt> bits. */ private static long zigZagEncode(long l) { return (l >> 63) ^ (l << 1); } /** * Decode an int previously encoded with {@link #zigZagEncode(int)}. */ private static int zigZagDecode(int i) { return ((i >>> 1) ^ -(i & 1)); } /** * Decode a long previously encoded with {@link #zigZagEncode(long)}. */ private static long zigZagDecode(long l) { return ((l >>> 1) ^ -(l & 1)); } }
False
2,265
20
2,438
21
2,601
22
2,438
21
2,837
24
false
false
false
false
false
true
45
65830_0
package aimene.doex.bestelling.controller; import aimene.doex.bestelling.model.Bestelling; import aimene.doex.bestelling.model.Product; import aimene.doex.bestelling.repository.BestellingRepository; import aimene.doex.bestelling.repository.ProductRepository; import org.springframework.data.jdbc.core.mapping.AggregateReference; import org.springframework.web.bind.annotation.*; import java.util.Map; @RestController @RequestMapping("/bestellingen") public class BestellingController { private final ProductRepository productRepository; private final BestellingRepository bestellingRepository; public BestellingController(BestellingRepository bestellingRepository, ProductRepository productRepository) { this.bestellingRepository = bestellingRepository; this.productRepository = productRepository; } @GetMapping public Iterable<Bestelling> findAll() { return bestellingRepository.findAll(); } @GetMapping("{id}") public Bestelling findById(@PathVariable("id") Bestelling bestelling) { return bestelling; } @PatchMapping("{id}/plaats") public void plaatstBestelling(@PathVariable("id") Bestelling bestelling) { /* ******************************************************************** */ // Geef in het sequentiediagram wel expliciet aan dat je het product // ophaalt uit de repository met een findById(productId) // daarmee wordt het makkelijker te zien wanneer er een // optimistic lock exception kan optreden /* ******************************************************************** */ /* ******************************************************************** */ // Geef deze regel in het sequentiediagram aan met een rnote bestelling.plaatsBestelling(); /* ******************************************************************** */ bestellingRepository.save(bestelling); } @PostMapping("{id}/producten") public void voegProductToe(@PathVariable("id") Bestelling bestelling, @RequestBody Map<String, Object> requestBody) { Product product = productRepository.findById((Integer) requestBody.get("product_id")).orElseThrow(); int aantal = (int) requestBody.get("aantal"); AggregateReference<Product, Integer> productRef = AggregateReference.to(product.getId()); bestelling.voegProductToe(productRef, aantal, product.getPrijs()); bestellingRepository.save(bestelling); } }
AIM-ENE/doex-opdracht-3
oefeningen/les-3/voorbereiding/onderdeel2/bestelling/src/main/java/aimene/doex/bestelling/controller/BestellingController.java
611
// Geef in het sequentiediagram wel expliciet aan dat je het product
line_comment
nl
package aimene.doex.bestelling.controller; import aimene.doex.bestelling.model.Bestelling; import aimene.doex.bestelling.model.Product; import aimene.doex.bestelling.repository.BestellingRepository; import aimene.doex.bestelling.repository.ProductRepository; import org.springframework.data.jdbc.core.mapping.AggregateReference; import org.springframework.web.bind.annotation.*; import java.util.Map; @RestController @RequestMapping("/bestellingen") public class BestellingController { private final ProductRepository productRepository; private final BestellingRepository bestellingRepository; public BestellingController(BestellingRepository bestellingRepository, ProductRepository productRepository) { this.bestellingRepository = bestellingRepository; this.productRepository = productRepository; } @GetMapping public Iterable<Bestelling> findAll() { return bestellingRepository.findAll(); } @GetMapping("{id}") public Bestelling findById(@PathVariable("id") Bestelling bestelling) { return bestelling; } @PatchMapping("{id}/plaats") public void plaatstBestelling(@PathVariable("id") Bestelling bestelling) { /* ******************************************************************** */ // Geef in<SUF> // ophaalt uit de repository met een findById(productId) // daarmee wordt het makkelijker te zien wanneer er een // optimistic lock exception kan optreden /* ******************************************************************** */ /* ******************************************************************** */ // Geef deze regel in het sequentiediagram aan met een rnote bestelling.plaatsBestelling(); /* ******************************************************************** */ bestellingRepository.save(bestelling); } @PostMapping("{id}/producten") public void voegProductToe(@PathVariable("id") Bestelling bestelling, @RequestBody Map<String, Object> requestBody) { Product product = productRepository.findById((Integer) requestBody.get("product_id")).orElseThrow(); int aantal = (int) requestBody.get("aantal"); AggregateReference<Product, Integer> productRef = AggregateReference.to(product.getId()); bestelling.voegProductToe(productRef, aantal, product.getPrijs()); bestellingRepository.save(bestelling); } }
True
463
18
538
19
562
18
538
19
625
18
false
false
false
false
false
true
3,227
125134_6
package com.jidesoft.swing;_x000D_ _x000D_ import javax.swing.*;_x000D_ import javax.swing.event.MouseInputAdapter;_x000D_ import javax.swing.event.MouseInputListener;_x000D_ import java.awt.*;_x000D_ import java.awt.event.MouseEvent;_x000D_ import java.awt.geom.Area;_x000D_ import java.awt.image.BufferedImage;_x000D_ _x000D_ /**_x000D_ * Original code http://forums.java.net/jive/thread.jspa?forumID=73&threadID=14674 under "Do whatever you want with this_x000D_ * code" license_x000D_ */_x000D_ @SuppressWarnings("serial")_x000D_ public class ScrollPaneOverview extends JComponent {_x000D_ _x000D_ private static final int MAX_SIZE = 400;_x000D_ private static final int MAX_SCALE = 20;_x000D_ _x000D_ private Component _owner;_x000D_ private JScrollPane _scrollPane;_x000D_ private Component _viewComponent;_x000D_ _x000D_ protected JPopupMenu _popupMenu;_x000D_ _x000D_ private BufferedImage _image;_x000D_ private Rectangle _startRectangle;_x000D_ private Rectangle _rectangle;_x000D_ private Point _startPoint;_x000D_ private double _scale;_x000D_ private int xOffset;_x000D_ private int yOffset;_x000D_ _x000D_ private Color _selectionBorder = Color.BLACK;_x000D_ _x000D_ public ScrollPaneOverview(JScrollPane scrollPane, Component owner) {_x000D_ _scrollPane = scrollPane;_x000D_ _owner = owner;_x000D_ _image = null;_x000D_ _startRectangle = null;_x000D_ _rectangle = null;_x000D_ _startPoint = null;_x000D_ _scale = 0.0;_x000D_ _x000D_ setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));_x000D_ setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));_x000D_ MouseInputListener mil = new MouseInputAdapter() {_x000D_ // A new approach suggested by [email protected]_x000D_ _x000D_ @Override_x000D_ public void mousePressed(MouseEvent e) {_x000D_ if (_startPoint != null) {_x000D_ Point newPoint = e.getPoint();_x000D_ int deltaX = (int) ((newPoint.x - _startPoint.x) / _scale);_x000D_ int deltaY = (int) ((newPoint.y - _startPoint.y) / _scale);_x000D_ scroll(deltaX, deltaY);_x000D_ }_x000D_ _startPoint = null;_x000D_ _startRectangle = _rectangle;_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void mouseMoved(MouseEvent e) {_x000D_ if (_startPoint == null) {_x000D_ _startPoint = new Point(_rectangle.x + _rectangle.width / 2, _rectangle.y + _rectangle.height / 2);_x000D_ }_x000D_ Point newPoint = e.getPoint();_x000D_ moveRectangle(newPoint.x - _startPoint.x, newPoint.y - _startPoint.y);_x000D_ }_x000D_ };_x000D_ addMouseListener(mil);_x000D_ addMouseMotionListener(mil);_x000D_ _popupMenu = new JPopupMenu();_x000D_ _popupMenu.setLayout(new BorderLayout());_x000D_ _popupMenu.add(this, BorderLayout.CENTER);_x000D_ }_x000D_ _x000D_ public void setSelectionBorderColor(Color selectionBorder) {_x000D_ _selectionBorder = selectionBorder;_x000D_ }_x000D_ _x000D_ public Color getSelectionBorder() {_x000D_ return _selectionBorder;_x000D_ }_x000D_ _x000D_ @Override_x000D_ protected void paintComponent(Graphics g) {_x000D_ if (_image == null || _rectangle == null)_x000D_ return;_x000D_ Graphics2D g2d = (Graphics2D) g;_x000D_ Insets insets = getInsets();_x000D_ int xOffset = insets.left;_x000D_ int yOffset = insets.top;_x000D_ _x000D_ g.setColor(_scrollPane.getViewport().getView().getBackground());_x000D_ g.fillRect(0, 0, getWidth(), getHeight());_x000D_ g.drawImage(_image, xOffset, yOffset, null);_x000D_ _x000D_ int availableWidth = getWidth() - insets.left - insets.right;_x000D_ int availableHeight = getHeight() - insets.top - insets.bottom;_x000D_ Area area = new Area(new Rectangle(xOffset, yOffset, availableWidth, availableHeight));_x000D_ area.subtract(new Area(_rectangle));_x000D_ g.setColor(new Color(255, 255, 255, 128));_x000D_ g2d.fill(area);_x000D_ _x000D_ Color oldcolor = g.getColor();_x000D_ g.setColor(_selectionBorder);_x000D_ g.drawRect(_rectangle.x, _rectangle.y, _rectangle.width, _rectangle.height);_x000D_ _x000D_ g.setColor(oldcolor);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public Dimension getPreferredSize() {_x000D_ if (_image == null || _rectangle == null)_x000D_ return new Dimension();_x000D_ Insets insets = getInsets();_x000D_ return new Dimension(_image.getWidth(null) + insets.left + insets.right, _image.getHeight(null) + insets.top + insets.bottom);_x000D_ }_x000D_ _x000D_ public void display() {_x000D_ _viewComponent = _scrollPane.getViewport().getView();_x000D_ if (_viewComponent == null) {_x000D_ return;_x000D_ }_x000D_ _x000D_ int maxSize = Math.max(MAX_SIZE, Math.max(_scrollPane.getWidth(), _scrollPane.getHeight()) / 2);_x000D_ _x000D_ int width = Math.min(_viewComponent.getWidth(), _scrollPane.getViewport().getWidth() * MAX_SCALE);_x000D_ if (width <= 0) {_x000D_ return;_x000D_ }_x000D_ int height = Math.min(_viewComponent.getHeight(), _scrollPane.getViewport().getHeight() * MAX_SCALE);_x000D_ if (height <= 0) {_x000D_ return;_x000D_ }_x000D_ double scaleX = (double) maxSize / width;_x000D_ double scaleY = (double) maxSize / height;_x000D_ _x000D_ _scale = Math.max(1.0 / MAX_SCALE, Math.min(scaleX, scaleY));_x000D_ _x000D_ _image = new BufferedImage((int) (width * _scale), (int) (height * _scale), BufferedImage.TYPE_INT_RGB);_x000D_ Graphics2D g = _image.createGraphics();_x000D_ _x000D_ // If the view is larger than the max scale allows only the the top left most part will now be painted_x000D_ // One solution would be paint only the part around the current position, but I can't get it to paint - Walter Laan._x000D_ // note that without limiting the scale, the width/height will become zero (illegal for BufferedImage)_x000D_ // See CornerScrollerVisualTest in the test folder_x000D_ _x000D_ // g.setColor(_viewComponent.getBackground());_x000D_ // g.fillRect(0, 0, _viewComponent.getWidth(), _viewComponent.getHeight());_x000D_ // Point viewPosition = _scrollPane.getViewport().getViewPosition();_x000D_ // xOffset = Math.max(0, viewPosition.x - (width / 2)); _x000D_ // yOffset = Math.max(0, viewPosition.y - (height / 2)); _x000D_ // g.translate(-xOffset, -yOffset);_x000D_ // g.setClip(0, 0, width, height);_x000D_ _x000D_ g.scale(_scale, _scale);_x000D_ g.setClip(xOffset, yOffset, width, height);_x000D_ /// {{{ Qian Qian 10/72007_x000D_ boolean wasDoubleBuffered = _viewComponent.isDoubleBuffered();_x000D_ try {_x000D_ if (_viewComponent instanceof JComponent) {_x000D_ ((JComponent) _viewComponent).setDoubleBuffered(false);_x000D_ }_x000D_ _viewComponent.paint(g);_x000D_ }_x000D_ finally {_x000D_ if (_viewComponent instanceof JComponent) {_x000D_ ((JComponent) _viewComponent).setDoubleBuffered(wasDoubleBuffered);_x000D_ }_x000D_ g.dispose();_x000D_ }_x000D_ /// QianQian 10/7/2007 }}}_x000D_ _startRectangle = _scrollPane.getViewport().getViewRect();_x000D_ Insets insets = getInsets();_x000D_ _startRectangle.x = (int) (_scale * _startRectangle.x + insets.left);_x000D_ _startRectangle.y = (int) (_scale * _startRectangle.y + insets.right);_x000D_ _startRectangle.width *= _scale;_x000D_ _startRectangle.height *= _scale;_x000D_ _rectangle = _startRectangle;_x000D_ Point centerPoint = new Point(_rectangle.x + _rectangle.width / 2, _rectangle.y + _rectangle.height / 2);_x000D_ showPopup(-centerPoint.x, -centerPoint.y, _owner);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Show popup at designated location._x000D_ * <p/>_x000D_ * You could override this method to show the popup in different location._x000D_ *_x000D_ * @param x the x axis pixel_x000D_ * @param y the y axis pixel_x000D_ * @param owner the owner of the popup_x000D_ */_x000D_ protected void showPopup(int x, int y, Component owner) {_x000D_ _popupMenu.show(owner, x, y);_x000D_ }_x000D_ _x000D_ private void moveRectangle(int aDeltaX, int aDeltaY) {_x000D_ if (_startRectangle == null)_x000D_ return;_x000D_ Insets insets = getInsets();_x000D_ Rectangle newRect = new Rectangle(_startRectangle);_x000D_ newRect.x += aDeltaX;_x000D_ newRect.y += aDeltaY;_x000D_ newRect.x = Math.min(Math.max(newRect.x, insets.left), getWidth() - insets.right - newRect.width);_x000D_ newRect.y = Math.min(Math.max(newRect.y, insets.right), getHeight() - insets.bottom - newRect.height);_x000D_ Rectangle clip = new Rectangle();_x000D_ Rectangle.union(_rectangle, newRect, clip);_x000D_ clip.grow(2, 2);_x000D_ _rectangle = newRect;_x000D_ paintImmediately(clip);_x000D_ }_x000D_ _x000D_ private void scroll(int aDeltaX, int aDeltaY) {_x000D_ JComponent component = (JComponent) _scrollPane.getViewport().getView();_x000D_ Rectangle rect = component.getVisibleRect();_x000D_ rect.x += xOffset + aDeltaX;_x000D_ rect.y += yOffset + aDeltaY;_x000D_ component.scrollRectToVisible(rect);_x000D_ _popupMenu.setVisible(false);_x000D_ }_x000D_ }_x000D_
jidesoft/jide-oss
src/com/jidesoft/swing/ScrollPaneOverview.java
2,652
// g.fillRect(0, 0, _viewComponent.getWidth(), _viewComponent.getHeight());_x000D_
line_comment
nl
package com.jidesoft.swing;_x000D_ _x000D_ import javax.swing.*;_x000D_ import javax.swing.event.MouseInputAdapter;_x000D_ import javax.swing.event.MouseInputListener;_x000D_ import java.awt.*;_x000D_ import java.awt.event.MouseEvent;_x000D_ import java.awt.geom.Area;_x000D_ import java.awt.image.BufferedImage;_x000D_ _x000D_ /**_x000D_ * Original code http://forums.java.net/jive/thread.jspa?forumID=73&threadID=14674 under "Do whatever you want with this_x000D_ * code" license_x000D_ */_x000D_ @SuppressWarnings("serial")_x000D_ public class ScrollPaneOverview extends JComponent {_x000D_ _x000D_ private static final int MAX_SIZE = 400;_x000D_ private static final int MAX_SCALE = 20;_x000D_ _x000D_ private Component _owner;_x000D_ private JScrollPane _scrollPane;_x000D_ private Component _viewComponent;_x000D_ _x000D_ protected JPopupMenu _popupMenu;_x000D_ _x000D_ private BufferedImage _image;_x000D_ private Rectangle _startRectangle;_x000D_ private Rectangle _rectangle;_x000D_ private Point _startPoint;_x000D_ private double _scale;_x000D_ private int xOffset;_x000D_ private int yOffset;_x000D_ _x000D_ private Color _selectionBorder = Color.BLACK;_x000D_ _x000D_ public ScrollPaneOverview(JScrollPane scrollPane, Component owner) {_x000D_ _scrollPane = scrollPane;_x000D_ _owner = owner;_x000D_ _image = null;_x000D_ _startRectangle = null;_x000D_ _rectangle = null;_x000D_ _startPoint = null;_x000D_ _scale = 0.0;_x000D_ _x000D_ setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));_x000D_ setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));_x000D_ MouseInputListener mil = new MouseInputAdapter() {_x000D_ // A new approach suggested by [email protected]_x000D_ _x000D_ @Override_x000D_ public void mousePressed(MouseEvent e) {_x000D_ if (_startPoint != null) {_x000D_ Point newPoint = e.getPoint();_x000D_ int deltaX = (int) ((newPoint.x - _startPoint.x) / _scale);_x000D_ int deltaY = (int) ((newPoint.y - _startPoint.y) / _scale);_x000D_ scroll(deltaX, deltaY);_x000D_ }_x000D_ _startPoint = null;_x000D_ _startRectangle = _rectangle;_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void mouseMoved(MouseEvent e) {_x000D_ if (_startPoint == null) {_x000D_ _startPoint = new Point(_rectangle.x + _rectangle.width / 2, _rectangle.y + _rectangle.height / 2);_x000D_ }_x000D_ Point newPoint = e.getPoint();_x000D_ moveRectangle(newPoint.x - _startPoint.x, newPoint.y - _startPoint.y);_x000D_ }_x000D_ };_x000D_ addMouseListener(mil);_x000D_ addMouseMotionListener(mil);_x000D_ _popupMenu = new JPopupMenu();_x000D_ _popupMenu.setLayout(new BorderLayout());_x000D_ _popupMenu.add(this, BorderLayout.CENTER);_x000D_ }_x000D_ _x000D_ public void setSelectionBorderColor(Color selectionBorder) {_x000D_ _selectionBorder = selectionBorder;_x000D_ }_x000D_ _x000D_ public Color getSelectionBorder() {_x000D_ return _selectionBorder;_x000D_ }_x000D_ _x000D_ @Override_x000D_ protected void paintComponent(Graphics g) {_x000D_ if (_image == null || _rectangle == null)_x000D_ return;_x000D_ Graphics2D g2d = (Graphics2D) g;_x000D_ Insets insets = getInsets();_x000D_ int xOffset = insets.left;_x000D_ int yOffset = insets.top;_x000D_ _x000D_ g.setColor(_scrollPane.getViewport().getView().getBackground());_x000D_ g.fillRect(0, 0, getWidth(), getHeight());_x000D_ g.drawImage(_image, xOffset, yOffset, null);_x000D_ _x000D_ int availableWidth = getWidth() - insets.left - insets.right;_x000D_ int availableHeight = getHeight() - insets.top - insets.bottom;_x000D_ Area area = new Area(new Rectangle(xOffset, yOffset, availableWidth, availableHeight));_x000D_ area.subtract(new Area(_rectangle));_x000D_ g.setColor(new Color(255, 255, 255, 128));_x000D_ g2d.fill(area);_x000D_ _x000D_ Color oldcolor = g.getColor();_x000D_ g.setColor(_selectionBorder);_x000D_ g.drawRect(_rectangle.x, _rectangle.y, _rectangle.width, _rectangle.height);_x000D_ _x000D_ g.setColor(oldcolor);_x000D_ }_x000D_ _x000D_ @Override_x000D_ public Dimension getPreferredSize() {_x000D_ if (_image == null || _rectangle == null)_x000D_ return new Dimension();_x000D_ Insets insets = getInsets();_x000D_ return new Dimension(_image.getWidth(null) + insets.left + insets.right, _image.getHeight(null) + insets.top + insets.bottom);_x000D_ }_x000D_ _x000D_ public void display() {_x000D_ _viewComponent = _scrollPane.getViewport().getView();_x000D_ if (_viewComponent == null) {_x000D_ return;_x000D_ }_x000D_ _x000D_ int maxSize = Math.max(MAX_SIZE, Math.max(_scrollPane.getWidth(), _scrollPane.getHeight()) / 2);_x000D_ _x000D_ int width = Math.min(_viewComponent.getWidth(), _scrollPane.getViewport().getWidth() * MAX_SCALE);_x000D_ if (width <= 0) {_x000D_ return;_x000D_ }_x000D_ int height = Math.min(_viewComponent.getHeight(), _scrollPane.getViewport().getHeight() * MAX_SCALE);_x000D_ if (height <= 0) {_x000D_ return;_x000D_ }_x000D_ double scaleX = (double) maxSize / width;_x000D_ double scaleY = (double) maxSize / height;_x000D_ _x000D_ _scale = Math.max(1.0 / MAX_SCALE, Math.min(scaleX, scaleY));_x000D_ _x000D_ _image = new BufferedImage((int) (width * _scale), (int) (height * _scale), BufferedImage.TYPE_INT_RGB);_x000D_ Graphics2D g = _image.createGraphics();_x000D_ _x000D_ // If the view is larger than the max scale allows only the the top left most part will now be painted_x000D_ // One solution would be paint only the part around the current position, but I can't get it to paint - Walter Laan._x000D_ // note that without limiting the scale, the width/height will become zero (illegal for BufferedImage)_x000D_ // See CornerScrollerVisualTest in the test folder_x000D_ _x000D_ // g.setColor(_viewComponent.getBackground());_x000D_ // g.fillRect(0, 0,<SUF> // Point viewPosition = _scrollPane.getViewport().getViewPosition();_x000D_ // xOffset = Math.max(0, viewPosition.x - (width / 2)); _x000D_ // yOffset = Math.max(0, viewPosition.y - (height / 2)); _x000D_ // g.translate(-xOffset, -yOffset);_x000D_ // g.setClip(0, 0, width, height);_x000D_ _x000D_ g.scale(_scale, _scale);_x000D_ g.setClip(xOffset, yOffset, width, height);_x000D_ /// {{{ Qian Qian 10/72007_x000D_ boolean wasDoubleBuffered = _viewComponent.isDoubleBuffered();_x000D_ try {_x000D_ if (_viewComponent instanceof JComponent) {_x000D_ ((JComponent) _viewComponent).setDoubleBuffered(false);_x000D_ }_x000D_ _viewComponent.paint(g);_x000D_ }_x000D_ finally {_x000D_ if (_viewComponent instanceof JComponent) {_x000D_ ((JComponent) _viewComponent).setDoubleBuffered(wasDoubleBuffered);_x000D_ }_x000D_ g.dispose();_x000D_ }_x000D_ /// QianQian 10/7/2007 }}}_x000D_ _startRectangle = _scrollPane.getViewport().getViewRect();_x000D_ Insets insets = getInsets();_x000D_ _startRectangle.x = (int) (_scale * _startRectangle.x + insets.left);_x000D_ _startRectangle.y = (int) (_scale * _startRectangle.y + insets.right);_x000D_ _startRectangle.width *= _scale;_x000D_ _startRectangle.height *= _scale;_x000D_ _rectangle = _startRectangle;_x000D_ Point centerPoint = new Point(_rectangle.x + _rectangle.width / 2, _rectangle.y + _rectangle.height / 2);_x000D_ showPopup(-centerPoint.x, -centerPoint.y, _owner);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Show popup at designated location._x000D_ * <p/>_x000D_ * You could override this method to show the popup in different location._x000D_ *_x000D_ * @param x the x axis pixel_x000D_ * @param y the y axis pixel_x000D_ * @param owner the owner of the popup_x000D_ */_x000D_ protected void showPopup(int x, int y, Component owner) {_x000D_ _popupMenu.show(owner, x, y);_x000D_ }_x000D_ _x000D_ private void moveRectangle(int aDeltaX, int aDeltaY) {_x000D_ if (_startRectangle == null)_x000D_ return;_x000D_ Insets insets = getInsets();_x000D_ Rectangle newRect = new Rectangle(_startRectangle);_x000D_ newRect.x += aDeltaX;_x000D_ newRect.y += aDeltaY;_x000D_ newRect.x = Math.min(Math.max(newRect.x, insets.left), getWidth() - insets.right - newRect.width);_x000D_ newRect.y = Math.min(Math.max(newRect.y, insets.right), getHeight() - insets.bottom - newRect.height);_x000D_ Rectangle clip = new Rectangle();_x000D_ Rectangle.union(_rectangle, newRect, clip);_x000D_ clip.grow(2, 2);_x000D_ _rectangle = newRect;_x000D_ paintImmediately(clip);_x000D_ }_x000D_ _x000D_ private void scroll(int aDeltaX, int aDeltaY) {_x000D_ JComponent component = (JComponent) _scrollPane.getViewport().getView();_x000D_ Rectangle rect = component.getVisibleRect();_x000D_ rect.x += xOffset + aDeltaX;_x000D_ rect.y += yOffset + aDeltaY;_x000D_ component.scrollRectToVisible(rect);_x000D_ _popupMenu.setVisible(false);_x000D_ }_x000D_ }_x000D_
False
3,417
27
3,690
30
3,854
30
3,690
30
4,101
33
false
false
false
false
false
true
1,523
76777_4
package mjava.util; import java.io.*; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ResolveJar { public static final String JAR_DIR_NAME = "apk2jar"; /** * parse apk into dex * @param apkPath * @param outputDir */ static public void zipDecompressing(String apkPath, String outputDir){ System.out.println("Starting decompress apk file ......"); long startTime=System.currentTimeMillis(); try { ZipInputStream Zin=new ZipInputStream(new FileInputStream(apkPath));//Input source zip path BufferedInputStream Bin=new BufferedInputStream(Zin); ZipEntry entry; try { while((entry = Zin.getNextEntry())!=null && !entry.isDirectory()){ if(!entry.getName().endsWith(".dex")){ continue; } File Fout=new File(outputDir,entry.getName()); if(!Fout.exists()){ (new File(Fout.getParent())).mkdirs(); } FileOutputStream out=new FileOutputStream(Fout); BufferedOutputStream Bout=new BufferedOutputStream(out); int b; while((b=Bin.read())!=-1){ Bout.write(b); } Bout.close(); out.close(); System.out.println(Fout+" decompressing succeeded."); } Bin.close(); Zin.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } long endTime=System.currentTimeMillis(); System.out.println("Apk decompression takes time: "+(endTime-startTime)+" ms."); } /** * parse dex into jar * @param inputDir */ static public void dexDecompressing(String inputDir){ System.out.println("Starting decompress dex file ......"); long startTime=System.currentTimeMillis(); File inputFileDir = new File(inputDir); if(!inputFileDir.exists()){ return; } String[] paramArr = new String[6]; paramArr[0] = "-f"; for(File f : inputFileDir.listFiles()){ if(f.getName().endsWith(".dex")){ paramArr[1] = "-o"; paramArr[2] = inputDir+"\\"+f.getName().replace(".dex","")+"-dex2jar.jar"; paramArr[3] = "-e"; paramArr[4] = inputDir+"\\"+f.getName().replace(".dex","")+"-error.zip"; paramArr[5] = f.getAbsolutePath(); //com.googlecode.dex2jar.tools.Dex2jarCmd.main(paramArr); //System.out.println("absPath: "+f.getAbsolutePath()); } } long endTime=System.currentTimeMillis(); System.out.println("Dex decompression takes time: "+(endTime-startTime)+" ms."); } /** * add the class path dynamically * */ private static void addURL(String classPath) { try{ Method addClass = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class}); addClass.setAccessible(true); ClassLoader cl = ClassLoader.getSystemClassLoader(); // load app's dependence jars File[] jarFiles = new File(classPath).listFiles(); for (File ff : jarFiles) { if(ff.getName().endsWith(".jar")){ addClass.invoke(cl, new Object[]{ff.toURL()}); System.out.println("FileName: "+ff.getName()); } } }catch (Exception e){ e.printStackTrace(); System.err.println(e.toString()); } } /** * parse apk into jar * @param apkPath */ public static void doApk2Jar(String apkPath){ if("".equals(apkPath)) return; File path = new File(apkPath); if(path.exists() && path.isDirectory()){ boolean flag = false; for(File f: path.listFiles()){ if(f.getName().endsWith(".apk")){ flag = true; File apk2jarDir = new File(apkPath+File.separator+JAR_DIR_NAME); if(!apk2jarDir.exists()){ apk2jarDir.mkdirs(); } zipDecompressing(f.getAbsolutePath(),apk2jarDir.getAbsolutePath()); dexDecompressing(apk2jarDir.getAbsolutePath()); } } if(!flag){ System.err.println("Can not find apk file. Parsing apk into jar failed."); } }else if(path.isFile()){ File apk2jarDir = new File(path.getParent()+File.separator+JAR_DIR_NAME); if(!apk2jarDir.exists()){ apk2jarDir.mkdirs(); } zipDecompressing(path.getAbsolutePath(),apk2jarDir.getAbsolutePath()); dexDecompressing(apk2jarDir.getAbsolutePath()); } else{ System.err.println("Can not find path ["+apkPath+"]. parsing apk into jar failed."); } } public static void main(String[] args){ //my testing //zipDecompressing("E:\\AndroidStudioProjects\\MyApplication\\app\\build\\outputs\\apk\\app-debug.apk","E:\\mutatorHome\\classes"); //zipDecompressing("E:\\andriod_project\\AnyMemo\\app\\build\\outputs\\apk\\debug\\AnyMemo-debug.apk","E:\\mutatorHome\\classes"); //dexDecompressing("E:\\mutatorHome\\classes"); addURL("E:\\mutatorHome\\classes"); String[] className = new String[]{"org.liberty.android.fantastischmemo.ui.CardEditor", "org.apache.commons.io.ByteOrderMark", "android.support.v7.app.AppCompatActivity", "org.jacoco.core.data.SessionInfo"}; try{ for(String name: className){ Class c = Class.forName(name); System.out.println("ClassName: "+c.getName()+ " superClass:"+c.getSuperclass().getName()); } }catch (ClassNotFoundException cnfe){ System.err.println(cnfe.toString()); } } }
SQS-JLiu/DroidMutator
src/main/java/mjava/util/ResolveJar.java
1,861
// load app's dependence jars
line_comment
nl
package mjava.util; import java.io.*; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ResolveJar { public static final String JAR_DIR_NAME = "apk2jar"; /** * parse apk into dex * @param apkPath * @param outputDir */ static public void zipDecompressing(String apkPath, String outputDir){ System.out.println("Starting decompress apk file ......"); long startTime=System.currentTimeMillis(); try { ZipInputStream Zin=new ZipInputStream(new FileInputStream(apkPath));//Input source zip path BufferedInputStream Bin=new BufferedInputStream(Zin); ZipEntry entry; try { while((entry = Zin.getNextEntry())!=null && !entry.isDirectory()){ if(!entry.getName().endsWith(".dex")){ continue; } File Fout=new File(outputDir,entry.getName()); if(!Fout.exists()){ (new File(Fout.getParent())).mkdirs(); } FileOutputStream out=new FileOutputStream(Fout); BufferedOutputStream Bout=new BufferedOutputStream(out); int b; while((b=Bin.read())!=-1){ Bout.write(b); } Bout.close(); out.close(); System.out.println(Fout+" decompressing succeeded."); } Bin.close(); Zin.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } long endTime=System.currentTimeMillis(); System.out.println("Apk decompression takes time: "+(endTime-startTime)+" ms."); } /** * parse dex into jar * @param inputDir */ static public void dexDecompressing(String inputDir){ System.out.println("Starting decompress dex file ......"); long startTime=System.currentTimeMillis(); File inputFileDir = new File(inputDir); if(!inputFileDir.exists()){ return; } String[] paramArr = new String[6]; paramArr[0] = "-f"; for(File f : inputFileDir.listFiles()){ if(f.getName().endsWith(".dex")){ paramArr[1] = "-o"; paramArr[2] = inputDir+"\\"+f.getName().replace(".dex","")+"-dex2jar.jar"; paramArr[3] = "-e"; paramArr[4] = inputDir+"\\"+f.getName().replace(".dex","")+"-error.zip"; paramArr[5] = f.getAbsolutePath(); //com.googlecode.dex2jar.tools.Dex2jarCmd.main(paramArr); //System.out.println("absPath: "+f.getAbsolutePath()); } } long endTime=System.currentTimeMillis(); System.out.println("Dex decompression takes time: "+(endTime-startTime)+" ms."); } /** * add the class path dynamically * */ private static void addURL(String classPath) { try{ Method addClass = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class}); addClass.setAccessible(true); ClassLoader cl = ClassLoader.getSystemClassLoader(); // load app's<SUF> File[] jarFiles = new File(classPath).listFiles(); for (File ff : jarFiles) { if(ff.getName().endsWith(".jar")){ addClass.invoke(cl, new Object[]{ff.toURL()}); System.out.println("FileName: "+ff.getName()); } } }catch (Exception e){ e.printStackTrace(); System.err.println(e.toString()); } } /** * parse apk into jar * @param apkPath */ public static void doApk2Jar(String apkPath){ if("".equals(apkPath)) return; File path = new File(apkPath); if(path.exists() && path.isDirectory()){ boolean flag = false; for(File f: path.listFiles()){ if(f.getName().endsWith(".apk")){ flag = true; File apk2jarDir = new File(apkPath+File.separator+JAR_DIR_NAME); if(!apk2jarDir.exists()){ apk2jarDir.mkdirs(); } zipDecompressing(f.getAbsolutePath(),apk2jarDir.getAbsolutePath()); dexDecompressing(apk2jarDir.getAbsolutePath()); } } if(!flag){ System.err.println("Can not find apk file. Parsing apk into jar failed."); } }else if(path.isFile()){ File apk2jarDir = new File(path.getParent()+File.separator+JAR_DIR_NAME); if(!apk2jarDir.exists()){ apk2jarDir.mkdirs(); } zipDecompressing(path.getAbsolutePath(),apk2jarDir.getAbsolutePath()); dexDecompressing(apk2jarDir.getAbsolutePath()); } else{ System.err.println("Can not find path ["+apkPath+"]. parsing apk into jar failed."); } } public static void main(String[] args){ //my testing //zipDecompressing("E:\\AndroidStudioProjects\\MyApplication\\app\\build\\outputs\\apk\\app-debug.apk","E:\\mutatorHome\\classes"); //zipDecompressing("E:\\andriod_project\\AnyMemo\\app\\build\\outputs\\apk\\debug\\AnyMemo-debug.apk","E:\\mutatorHome\\classes"); //dexDecompressing("E:\\mutatorHome\\classes"); addURL("E:\\mutatorHome\\classes"); String[] className = new String[]{"org.liberty.android.fantastischmemo.ui.CardEditor", "org.apache.commons.io.ByteOrderMark", "android.support.v7.app.AppCompatActivity", "org.jacoco.core.data.SessionInfo"}; try{ for(String name: className){ Class c = Class.forName(name); System.out.println("ClassName: "+c.getName()+ " superClass:"+c.getSuperclass().getName()); } }catch (ClassNotFoundException cnfe){ System.err.println(cnfe.toString()); } } }
False
1,288
6
1,453
8
1,578
7
1,453
8
1,781
8
false
false
false
false
false
true
1,720
82273_11
package org.example; import java.util.Scanner; import java.math.RoundingMode; import java.text.DecimalFormat; public class App { private static final DecimalFormat df = new DecimalFormat("0.00"); public static double berekenMaxTeLenenBedrag(double maandinkomen, boolean heeftStudieschuld, int rentevastePeriode, String postcode) { // Check of alle invoeren correct zijn if (maandinkomen <= 0 || (rentevastePeriode != 1 && rentevastePeriode != 5 && rentevastePeriode != 10 && rentevastePeriode != 20 && rentevastePeriode != 30)) { throw new IllegalArgumentException("Ongeldige invoer"); } // Check voor aardbevinggebied boolean postcodeCheck = extraBerekener.checkPostcode(postcode); if (!postcodeCheck) { return 0.0; } // Kijk wat de rentevasteperiode is double rentePercentage = extraBerekener.renteVastePeriode(rentevastePeriode); // Bereken het maximale te lenen bedrag double maxTeLenen = extraBerekener.maxTelenenBedrag(maandinkomen, heeftStudieschuld); // Bereken de rente en aflossingsbedrag double renteBedrag = maxTeLenen * (rentePercentage / 12); double aflossingsBedrag = maxTeLenen / (rentevastePeriode * 12); // Bereken het totaalbedrag double totaalBedrag = renteBedrag + aflossingsBedrag; // Bereken het totaalbedrag na 30 jaar double totaalBetaald = totaalBedrag * rentevastePeriode * 12; // Print alle overige uitkomsten! System.out.println("Maximaal te lenen:" + df.format(maxTeLenen)); System.out.println("Rente bedrag:" + df.format(renteBedrag)); System.out.println("Aflossingsbedrag:" + df.format(aflossingsBedrag)); System.out.println("Totaal maandbedrag " + df.format(totaalBedrag)); // Geef het totaalbedrag na 30 jaar terug return totaalBetaald; } public static void main(String[] args) { // Vraag voor alle invoeren Scanner scanner = new Scanner(System.in); System.out.println("Welkom bij de Hypotheekberekeningstool!"); System.out.print("Voer uw maandinkomen in: "); double maandinkomen = scanner.nextDouble(); System.out.print("Heeft u een partner? (ja/nee): "); boolean heeftPartner = scanner.next().equalsIgnoreCase("ja"); double partnerInkomen = 0.0; if (heeftPartner) { System.out.print("Voer het maandinkomen van uw partner in: "); partnerInkomen = scanner.nextDouble(); } System.out.print("Heeft u een studieschuld? (ja/nee): "); boolean heeftStudieschuld = scanner.next().equalsIgnoreCase("ja"); System.out.print("Selecteer de rentevaste periode (1/5/10/20/30 jaar): "); int rentevastePeriode = scanner.nextInt(); System.out.print("Voer uw postcode in: "); String postcode = scanner.next(); // Roep de functie aan om alles te berekenen double maxTeLenenBedrag = berekenMaxTeLenenBedrag(maandinkomen + partnerInkomen, heeftStudieschuld, rentevastePeriode, postcode); // Print het resultaat System.out.println("Totaal betaald na 30 jaar: " + df.format(maxTeLenenBedrag)); scanner.close(); } }
TheunissenSil/Hypotheek-tool
src/main/java/org/example/App.java
1,062
// Print het resultaat
line_comment
nl
package org.example; import java.util.Scanner; import java.math.RoundingMode; import java.text.DecimalFormat; public class App { private static final DecimalFormat df = new DecimalFormat("0.00"); public static double berekenMaxTeLenenBedrag(double maandinkomen, boolean heeftStudieschuld, int rentevastePeriode, String postcode) { // Check of alle invoeren correct zijn if (maandinkomen <= 0 || (rentevastePeriode != 1 && rentevastePeriode != 5 && rentevastePeriode != 10 && rentevastePeriode != 20 && rentevastePeriode != 30)) { throw new IllegalArgumentException("Ongeldige invoer"); } // Check voor aardbevinggebied boolean postcodeCheck = extraBerekener.checkPostcode(postcode); if (!postcodeCheck) { return 0.0; } // Kijk wat de rentevasteperiode is double rentePercentage = extraBerekener.renteVastePeriode(rentevastePeriode); // Bereken het maximale te lenen bedrag double maxTeLenen = extraBerekener.maxTelenenBedrag(maandinkomen, heeftStudieschuld); // Bereken de rente en aflossingsbedrag double renteBedrag = maxTeLenen * (rentePercentage / 12); double aflossingsBedrag = maxTeLenen / (rentevastePeriode * 12); // Bereken het totaalbedrag double totaalBedrag = renteBedrag + aflossingsBedrag; // Bereken het totaalbedrag na 30 jaar double totaalBetaald = totaalBedrag * rentevastePeriode * 12; // Print alle overige uitkomsten! System.out.println("Maximaal te lenen:" + df.format(maxTeLenen)); System.out.println("Rente bedrag:" + df.format(renteBedrag)); System.out.println("Aflossingsbedrag:" + df.format(aflossingsBedrag)); System.out.println("Totaal maandbedrag " + df.format(totaalBedrag)); // Geef het totaalbedrag na 30 jaar terug return totaalBetaald; } public static void main(String[] args) { // Vraag voor alle invoeren Scanner scanner = new Scanner(System.in); System.out.println("Welkom bij de Hypotheekberekeningstool!"); System.out.print("Voer uw maandinkomen in: "); double maandinkomen = scanner.nextDouble(); System.out.print("Heeft u een partner? (ja/nee): "); boolean heeftPartner = scanner.next().equalsIgnoreCase("ja"); double partnerInkomen = 0.0; if (heeftPartner) { System.out.print("Voer het maandinkomen van uw partner in: "); partnerInkomen = scanner.nextDouble(); } System.out.print("Heeft u een studieschuld? (ja/nee): "); boolean heeftStudieschuld = scanner.next().equalsIgnoreCase("ja"); System.out.print("Selecteer de rentevaste periode (1/5/10/20/30 jaar): "); int rentevastePeriode = scanner.nextInt(); System.out.print("Voer uw postcode in: "); String postcode = scanner.next(); // Roep de functie aan om alles te berekenen double maxTeLenenBedrag = berekenMaxTeLenenBedrag(maandinkomen + partnerInkomen, heeftStudieschuld, rentevastePeriode, postcode); // Print het<SUF> System.out.println("Totaal betaald na 30 jaar: " + df.format(maxTeLenenBedrag)); scanner.close(); } }
True
858
5
968
5
923
4
968
5
1,092
6
false
false
false
false
false
true
4,442
142842_10
//------------------------------------------------------------------------------ // Copyright (c) 2010 Carnegie Institution for Science. All rights reserved. // $Revision: 1.11 $ // $Date: 2004/04/05 22:43:46 $ //------------------------------------------------------------------------------ package org.tair.querytools; import org.tair.utilities.*; import org.tair.tfc.*; import java.sql.*; import java.io.*; import java.util.*; /** * RestrictionEnzymeDetail is a composite class to represent all information * associated with an entry in the restriction enzyme table. * RestrictionEnzymeDetail contains an instance of * <code>TfcRestrictionEnzyme</code> in addition to all information in * <code>TairObjectDetail</code> superclass. * * <p> * RestrictionEnzymeDetail overrides the getElementType() method implemented * in TairObjectDetail to satisfy Accessible interface so that a type specific * element type can be returned. */ public class RestrictionEnzymeDetail extends TairObjectDetail { private TfcRestrictionEnzyme restrictionEnzyme; /** * Creates an empty instance of RestrictionEnzymeDetail */ public RestrictionEnzymeDetail() { } /** * Creates an instance of RestrictionEnzymeDetail to reflect data referenced * by submitted restriction_enzyme_id * * @param conn An active connection to the database * @param restriction_enzyme_id Restriction enzyme id to retrieve data for * @throws SQLException if a database error occurs */ public RestrictionEnzymeDetail( DBconnection conn, Long restriction_enzyme_id ) throws SQLException { get_information( conn, restriction_enzyme_id ); } /** * Creates an instance of RestrictionEnzymeDetail to reflect data referenced * by submitted restriction_enzyme name * * @param conn An active connection to the database * @param name Restriction enzyme name to retrieve data for * @throws SQLException if a database error occurs */ public RestrictionEnzymeDetail( DBconnection conn, String name ) throws SQLException { if ( name != null ) { get_information( conn, name ); } } // // TfcRestrictionEnzyme wrappers // public String get_name() { return restrictionEnzyme.get_name(); } public String get_site() { return restrictionEnzyme.get_site(); } public String get_cleavage() { return restrictionEnzyme.get_cleavage(); } public String get_isoschizomer() { return restrictionEnzyme.get_isoschizomer(); } public Integer get_offset() { return restrictionEnzyme.get_offset(); } public Integer get_overhang() { return restrictionEnzyme.get_overhang(); } public java.util.Date get_date_last_modified() { return restrictionEnzyme.get_date_last_modified(); } public java.util.Date get_date_entered() { return restrictionEnzyme.get_date_entered(); } public String get_original_name() { return restrictionEnzyme.get_original_name(); } /** * Retrieves data for submitted restriction enzyme id * * @param conn An active connection to the database * @param restriction_enzyme_id Restriction enzyme id to retrieve data for * @throws SQLException if a database error occurs */ public void get_information( DBconnection conn, Long restriction_enzyme_id ) throws SQLException { restrictionEnzyme = new TfcRestrictionEnzyme( conn, restriction_enzyme_id ); // populate superclass data super.populateBaseObject( restrictionEnzyme ); getTairObjectInformation( conn ); } /** * Retrieves data for submitted restriction enzyme name * * @param conn An active connection to the database * @param name Restriction enzyme name to retrieve data for * @throws SQLException if a database error occurs */ public void get_information( DBconnection conn, String name ) throws SQLException { if ( name != null ) { get_information( conn, get_id( conn, name ) ); } } // get restriction enzyme id given name private Long get_id( DBconnection conn, String name ) throws SQLException { Long id = null; ResultSet results = null; String query = "SELECT restriction_enzyme_id " + "FROM RestrictionEnzyme " + "WHERE name = " + TextConverter.dbQuote( name ); conn.setQuery( query ); results = conn.getResultSet(); if ( results.next() ) { id = new Long( results.getLong( "restriction_enzyme_id" ) ); } conn.releaseResources(); return id; } /** * Retrieves element type of this object for use in creating TAIR accession * number. Implemented here to satisfy the <code>Accessible</code> interface * * @return Object's element type (restrictionenzyme) for use in creating * TAIR accession */ public final String getElementType() { return "restrictionenzyme"; } /** * For unit testing only */ public void test() { super.test(); System.out.println( "*** RestrictionEnzymeDetail content test **" ); restrictionEnzyme.test(); System.out.println( "*** RestrictionEnzymeDetail content test end **" ); } /** * For unit testing only */ public static void main( String[] args ) { try { DBconnection connection = new DBconnection(); Long test_id = new Long( 60 ); RestrictionEnzymeDetail restriction_enzyme = new RestrictionEnzymeDetail( connection, test_id ); restriction_enzyme.test(); } catch ( Exception e ) { e.printStackTrace(); } } }
tair/tairwebapp
src/org/tair/querytools/RestrictionEnzymeDetail.java
1,682
// get restriction enzyme id given name
line_comment
nl
//------------------------------------------------------------------------------ // Copyright (c) 2010 Carnegie Institution for Science. All rights reserved. // $Revision: 1.11 $ // $Date: 2004/04/05 22:43:46 $ //------------------------------------------------------------------------------ package org.tair.querytools; import org.tair.utilities.*; import org.tair.tfc.*; import java.sql.*; import java.io.*; import java.util.*; /** * RestrictionEnzymeDetail is a composite class to represent all information * associated with an entry in the restriction enzyme table. * RestrictionEnzymeDetail contains an instance of * <code>TfcRestrictionEnzyme</code> in addition to all information in * <code>TairObjectDetail</code> superclass. * * <p> * RestrictionEnzymeDetail overrides the getElementType() method implemented * in TairObjectDetail to satisfy Accessible interface so that a type specific * element type can be returned. */ public class RestrictionEnzymeDetail extends TairObjectDetail { private TfcRestrictionEnzyme restrictionEnzyme; /** * Creates an empty instance of RestrictionEnzymeDetail */ public RestrictionEnzymeDetail() { } /** * Creates an instance of RestrictionEnzymeDetail to reflect data referenced * by submitted restriction_enzyme_id * * @param conn An active connection to the database * @param restriction_enzyme_id Restriction enzyme id to retrieve data for * @throws SQLException if a database error occurs */ public RestrictionEnzymeDetail( DBconnection conn, Long restriction_enzyme_id ) throws SQLException { get_information( conn, restriction_enzyme_id ); } /** * Creates an instance of RestrictionEnzymeDetail to reflect data referenced * by submitted restriction_enzyme name * * @param conn An active connection to the database * @param name Restriction enzyme name to retrieve data for * @throws SQLException if a database error occurs */ public RestrictionEnzymeDetail( DBconnection conn, String name ) throws SQLException { if ( name != null ) { get_information( conn, name ); } } // // TfcRestrictionEnzyme wrappers // public String get_name() { return restrictionEnzyme.get_name(); } public String get_site() { return restrictionEnzyme.get_site(); } public String get_cleavage() { return restrictionEnzyme.get_cleavage(); } public String get_isoschizomer() { return restrictionEnzyme.get_isoschizomer(); } public Integer get_offset() { return restrictionEnzyme.get_offset(); } public Integer get_overhang() { return restrictionEnzyme.get_overhang(); } public java.util.Date get_date_last_modified() { return restrictionEnzyme.get_date_last_modified(); } public java.util.Date get_date_entered() { return restrictionEnzyme.get_date_entered(); } public String get_original_name() { return restrictionEnzyme.get_original_name(); } /** * Retrieves data for submitted restriction enzyme id * * @param conn An active connection to the database * @param restriction_enzyme_id Restriction enzyme id to retrieve data for * @throws SQLException if a database error occurs */ public void get_information( DBconnection conn, Long restriction_enzyme_id ) throws SQLException { restrictionEnzyme = new TfcRestrictionEnzyme( conn, restriction_enzyme_id ); // populate superclass data super.populateBaseObject( restrictionEnzyme ); getTairObjectInformation( conn ); } /** * Retrieves data for submitted restriction enzyme name * * @param conn An active connection to the database * @param name Restriction enzyme name to retrieve data for * @throws SQLException if a database error occurs */ public void get_information( DBconnection conn, String name ) throws SQLException { if ( name != null ) { get_information( conn, get_id( conn, name ) ); } } // get restriction<SUF> private Long get_id( DBconnection conn, String name ) throws SQLException { Long id = null; ResultSet results = null; String query = "SELECT restriction_enzyme_id " + "FROM RestrictionEnzyme " + "WHERE name = " + TextConverter.dbQuote( name ); conn.setQuery( query ); results = conn.getResultSet(); if ( results.next() ) { id = new Long( results.getLong( "restriction_enzyme_id" ) ); } conn.releaseResources(); return id; } /** * Retrieves element type of this object for use in creating TAIR accession * number. Implemented here to satisfy the <code>Accessible</code> interface * * @return Object's element type (restrictionenzyme) for use in creating * TAIR accession */ public final String getElementType() { return "restrictionenzyme"; } /** * For unit testing only */ public void test() { super.test(); System.out.println( "*** RestrictionEnzymeDetail content test **" ); restrictionEnzyme.test(); System.out.println( "*** RestrictionEnzymeDetail content test end **" ); } /** * For unit testing only */ public static void main( String[] args ) { try { DBconnection connection = new DBconnection(); Long test_id = new Long( 60 ); RestrictionEnzymeDetail restriction_enzyme = new RestrictionEnzymeDetail( connection, test_id ); restriction_enzyme.test(); } catch ( Exception e ) { e.printStackTrace(); } } }
False
1,301
7
1,380
8
1,472
7
1,380
8
1,717
9
false
false
false
false
false
true
2,343
41425_0
package be.acerta.ce.calendar; import lombok.extern.slf4j.Slf4j; import org.atmosphere.config.service.ManagedService; import org.atmosphere.config.service.PathParam; import org.atmosphere.interceptor.IdleResourceInterceptor; /** * Om een websocket te definiëren volstaat het om een klasse te annoteren met een @ManagedService annotatie waarin het * pad van de websocket wordt gespecifieerd en nog een aantal extra parameters. * Van belang hier is de IdleResourceInterceptor en de DistributedBroadcaster, de broadcasterCache is normaal * standaard UUIDBroadcasterCache maar is hier voor de volledigheid ook aan toegevoegd. * <p> * Het pad hieronder is een dynamisch pad gespecifieerd "/websocket/{qm: [0-9]*}" met een named parameter "qm". * De reguliere expressie [0-9]* is eerder informatief en gaat atmosphere niet strikt afchecken. * Uiteraard zijn ook vaste paden mogelijk in het geval er meer algemene gepushed moeten worden naar een browser client. */ @ManagedService( path = "/websocket/{qm: [0-9]*}", interceptors = {IdleResourceInterceptor.class} ) @Slf4j public class QueryModelWebsocket { @PathParam("qm") private String qm; }
cbonami/ce-calendar-web
src/main/java/be/acerta/ce/calendar/QueryModelWebsocket.java
370
/** * Om een websocket te definiëren volstaat het om een klasse te annoteren met een @ManagedService annotatie waarin het * pad van de websocket wordt gespecifieerd en nog een aantal extra parameters. * Van belang hier is de IdleResourceInterceptor en de DistributedBroadcaster, de broadcasterCache is normaal * standaard UUIDBroadcasterCache maar is hier voor de volledigheid ook aan toegevoegd. * <p> * Het pad hieronder is een dynamisch pad gespecifieerd "/websocket/{qm: [0-9]*}" met een named parameter "qm". * De reguliere expressie [0-9]* is eerder informatief en gaat atmosphere niet strikt afchecken. * Uiteraard zijn ook vaste paden mogelijk in het geval er meer algemene gepushed moeten worden naar een browser client. */
block_comment
nl
package be.acerta.ce.calendar; import lombok.extern.slf4j.Slf4j; import org.atmosphere.config.service.ManagedService; import org.atmosphere.config.service.PathParam; import org.atmosphere.interceptor.IdleResourceInterceptor; /** * Om een websocket<SUF>*/ @ManagedService( path = "/websocket/{qm: [0-9]*}", interceptors = {IdleResourceInterceptor.class} ) @Slf4j public class QueryModelWebsocket { @PathParam("qm") private String qm; }
True
292
189
345
217
300
176
345
217
364
214
false
false
false
false
false
true
1,256
39049_0
package net.opvolger.piaanuit.piaanuit; import android.content.Intent; import android.support.test.espresso.contrib.DrawerActions; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import net.opvolger.piaanuit.api.ApiModule; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static junit.framework.TestCase.assertEquals; @RunWith(AndroidJUnit4.class) public class MainActivityTest { @Rule public ActivityTestRule<MainActivity> mActivityRule; private MockWebServer server; @Before public void setUp() throws Exception { mActivityRule = new ActivityTestRule<>(MainActivity.class, true, true); server = new MockWebServer(); server.start(); String baseUrl = server.url("/").toString(); // Singleton ApiModule apimodule = ApiModule.getInstance(); apimodule.url = baseUrl; } @After public void tearDown() throws IOException { mActivityRule = null; // Singleton leeg halen, anders blijft hij oude mock server houden. // Dit probleem moet ik nog overwinnen ApiModule.resetInstance(); server.shutdown(); server = null; } @Test public void LightOn_Error_x_On() throws Exception { String serverResponse = "On"; server.enqueue(new MockResponse() .setResponseCode(200) .setBody(serverResponse)); Intent intent = new Intent(); mActivityRule.launchActivity(intent); onView(withId(R.id.drawer_layout)).perform(DrawerActions.open()); onView(withText(R.string.on)).perform(click()); onView(withText(serverResponse)).check(matches(isDisplayed())); } @Test public void LightOn() throws Exception { String serverResponse = "Test"; server.enqueue(new MockResponse() .setResponseCode(200) .setBody(serverResponse)); Intent intent = new Intent(); mActivityRule.launchActivity(intent); onView(withId(R.id.drawer_layout)).perform(DrawerActions.open()); onView(withText(R.string.on)).perform(click()); onView(withText(serverResponse)).check(matches(isDisplayed())); } @Test public void LightOn_Error_x_On_Fix() throws Exception { String serverResponse = "On"; server.enqueue(new MockResponse() .setResponseCode(200) .setBody(serverResponse)); Intent intent = new Intent(); mActivityRule.launchActivity(intent); onView(withId(R.id.drawer_layout)).perform(DrawerActions.open()); onView(withText(R.string.on)).perform(click()); onView(withId(R.id.info)).check(matches(isDisplayed())).check(matches(withText(serverResponse))); } @Test public void LightOffAndOn() throws Exception { server.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { if (request.getPath().contains("/On")){ return new MockResponse().setBody("On").setResponseCode(200); } else if (request.getPath().equals("/Off")){ return new MockResponse().setBody("Off").setResponseCode(200); } return new MockResponse().setResponseCode(404); } }); Intent intent = new Intent(); mActivityRule.launchActivity(intent); onView(withId(R.id.drawer_layout)).perform(DrawerActions.open()); onView(withText(R.string.off)).perform(click()); onView(withId(R.id.info)).check(matches(isDisplayed())).check(matches(withText("Off"))); RecordedRequest request = server.takeRequest(); assertEquals("/Off", request.getPath()); onView(withId(R.id.drawer_layout)).perform(DrawerActions.open()); onView(withText(R.string.on)).perform(click()); onView(withId(R.id.info)).check(matches(isDisplayed())).check(matches(withText("On"))); request = server.takeRequest(); assertEquals("/On", request.getPath()); } }
Opvolger/pi_on_off
PiAanUit/mobile/src/androidTest/java/net/opvolger/piaanuit/piaanuit/MainActivityTest.java
1,409
// Singleton leeg halen, anders blijft hij oude mock server houden.
line_comment
nl
package net.opvolger.piaanuit.piaanuit; import android.content.Intent; import android.support.test.espresso.contrib.DrawerActions; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import net.opvolger.piaanuit.api.ApiModule; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static junit.framework.TestCase.assertEquals; @RunWith(AndroidJUnit4.class) public class MainActivityTest { @Rule public ActivityTestRule<MainActivity> mActivityRule; private MockWebServer server; @Before public void setUp() throws Exception { mActivityRule = new ActivityTestRule<>(MainActivity.class, true, true); server = new MockWebServer(); server.start(); String baseUrl = server.url("/").toString(); // Singleton ApiModule apimodule = ApiModule.getInstance(); apimodule.url = baseUrl; } @After public void tearDown() throws IOException { mActivityRule = null; // Singleton leeg<SUF> // Dit probleem moet ik nog overwinnen ApiModule.resetInstance(); server.shutdown(); server = null; } @Test public void LightOn_Error_x_On() throws Exception { String serverResponse = "On"; server.enqueue(new MockResponse() .setResponseCode(200) .setBody(serverResponse)); Intent intent = new Intent(); mActivityRule.launchActivity(intent); onView(withId(R.id.drawer_layout)).perform(DrawerActions.open()); onView(withText(R.string.on)).perform(click()); onView(withText(serverResponse)).check(matches(isDisplayed())); } @Test public void LightOn() throws Exception { String serverResponse = "Test"; server.enqueue(new MockResponse() .setResponseCode(200) .setBody(serverResponse)); Intent intent = new Intent(); mActivityRule.launchActivity(intent); onView(withId(R.id.drawer_layout)).perform(DrawerActions.open()); onView(withText(R.string.on)).perform(click()); onView(withText(serverResponse)).check(matches(isDisplayed())); } @Test public void LightOn_Error_x_On_Fix() throws Exception { String serverResponse = "On"; server.enqueue(new MockResponse() .setResponseCode(200) .setBody(serverResponse)); Intent intent = new Intent(); mActivityRule.launchActivity(intent); onView(withId(R.id.drawer_layout)).perform(DrawerActions.open()); onView(withText(R.string.on)).perform(click()); onView(withId(R.id.info)).check(matches(isDisplayed())).check(matches(withText(serverResponse))); } @Test public void LightOffAndOn() throws Exception { server.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { if (request.getPath().contains("/On")){ return new MockResponse().setBody("On").setResponseCode(200); } else if (request.getPath().equals("/Off")){ return new MockResponse().setBody("Off").setResponseCode(200); } return new MockResponse().setResponseCode(404); } }); Intent intent = new Intent(); mActivityRule.launchActivity(intent); onView(withId(R.id.drawer_layout)).perform(DrawerActions.open()); onView(withText(R.string.off)).perform(click()); onView(withId(R.id.info)).check(matches(isDisplayed())).check(matches(withText("Off"))); RecordedRequest request = server.takeRequest(); assertEquals("/Off", request.getPath()); onView(withId(R.id.drawer_layout)).perform(DrawerActions.open()); onView(withText(R.string.on)).perform(click()); onView(withId(R.id.info)).check(matches(isDisplayed())).check(matches(withText("On"))); request = server.takeRequest(); assertEquals("/On", request.getPath()); } }
True
946
18
1,215
22
1,224
14
1,215
22
1,413
22
false
false
false
false
false
true
4,144
2220_3
/* * Copyright 2007 Pieter De Rycke * * This file is part of JMTP. * * JTMP is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or any later version. * * JMTP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU LesserGeneral Public * License along with JMTP. If not, see <http://www.gnu.org/licenses/>. */ package be.derycke.pieter.com; import java.lang.ref.WeakReference; import java.util.HashSet; import java.util.Set; /** * * @author Pieter De Rycke */ public class COMReference { private static Set<WeakReference<COMReference>> references; private static Object lock; static { lock = new Object(); references = new HashSet<WeakReference<COMReference>>(); //dit wordt nog voor de finalizers aangeroepen als finalizen //bij exit aan staat //dit is voor de objecten die niet of nog niet door de gc //gefinalized werden //http://en.allexperts.com/q/Java-1046/Constructor-destructor.htm Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { synchronized(lock) { for(WeakReference<COMReference> reference : references) { try { reference.get().release(); } catch(NullPointerException e) {} } } } }); } private WeakReference<COMReference> reference; private long pIUnknown; public COMReference(long pIUnkown) { this.pIUnknown = pIUnkown; reference = new WeakReference<COMReference>(this); synchronized(lock) { references.add(reference); } } public long getMemoryAddress() { return pIUnknown; } native long release(); native long addRef(); @Override protected void finalize() { synchronized(lock) { references.remove(reference); release(); } } }
reindahl/jmtp
java/src/be/derycke/pieter/com/COMReference.java
693
//bij exit aan staat
line_comment
nl
/* * Copyright 2007 Pieter De Rycke * * This file is part of JMTP. * * JTMP is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or any later version. * * JMTP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU LesserGeneral Public * License along with JMTP. If not, see <http://www.gnu.org/licenses/>. */ package be.derycke.pieter.com; import java.lang.ref.WeakReference; import java.util.HashSet; import java.util.Set; /** * * @author Pieter De Rycke */ public class COMReference { private static Set<WeakReference<COMReference>> references; private static Object lock; static { lock = new Object(); references = new HashSet<WeakReference<COMReference>>(); //dit wordt nog voor de finalizers aangeroepen als finalizen //bij exit<SUF> //dit is voor de objecten die niet of nog niet door de gc //gefinalized werden //http://en.allexperts.com/q/Java-1046/Constructor-destructor.htm Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { synchronized(lock) { for(WeakReference<COMReference> reference : references) { try { reference.get().release(); } catch(NullPointerException e) {} } } } }); } private WeakReference<COMReference> reference; private long pIUnknown; public COMReference(long pIUnkown) { this.pIUnknown = pIUnkown; reference = new WeakReference<COMReference>(this); synchronized(lock) { references.add(reference); } } public long getMemoryAddress() { return pIUnknown; } native long release(); native long addRef(); @Override protected void finalize() { synchronized(lock) { references.remove(reference); release(); } } }
True
528
5
575
7
629
5
575
7
702
5
false
false
false
false
false
true
3,123
19026_8
package afvink3;_x000D_ _x000D_ /**_x000D_ * Race class_x000D_ * Class Race maakt gebruik van de class Paard_x000D_ *_x000D_ * @author Martijn van der Bruggen_x000D_ * @version alpha - aanroep van cruciale methodes ontbreekt_x000D_ * (c) 2009 Hogeschool van Arnhem en Nijmegen_x000D_ *_x000D_ * Note: deze code is bewust niet op alle punten generiek_x000D_ * dit om nog onbekende constructies te vermijden._x000D_ *_x000D_ * Updates_x000D_ * 2010: verduidelijking van opdrachten in de code MvdB_x000D_ * 2011: verbetering leesbaarheid code MvdB_x000D_ * 2012: verbetering layout code en aanpassing commentaar MvdB_x000D_ * 2013: commentaar aangepast aan nieuwe opdracht MvdB_x000D_ *_x000D_ *************************************************_x000D_ * Afvinkopdracht: werken met methodes en objecten_x000D_ *************************************************_x000D_ * Opdrachten zitten verwerkt in de code_x000D_ * 1) Declaratie constante_x000D_ * 2) Declaratie van Paard (niet instantiering)_x000D_ * 3) Declareer een button_x000D_ * 4) Zet breedte en hoogte van het frame_x000D_ * 5) Teken een finish streep_x000D_ * 6) Creatie van 4 paarden_x000D_ * 7) Pauzeer_x000D_ * 8) Teken 4 paarden_x000D_ * 9) Plaats tekst op de button_x000D_ * 10) Start de race, methode aanroep_x000D_ *_x000D_ *_x000D_ */_x000D_ import java.awt.*;_x000D_ import java.awt.event.*;_x000D_ import javax.swing.*;_x000D_ _x000D_ public class Race extends JFrame implements ActionListener {_x000D_ _x000D_ /** declaratie van variabelen */_x000D_ int var = 250; /*var van 250_x000D_ /* (2) Declareer hier h1, h2, h3, h4 van het type Paard_x000D_ * Deze paarden instantieer je later in het programma_x000D_ */_x000D_ Image foto = Toolkit.getDefaultToolkit().getImage("C:\\Users\\aloys\\Desktop\\opdrachten\\jaar 2\\Afvink 3 jaar 2\\Mylittlepony.GIF");_x000D_ Image newimage = foto.getScaledInstance(40, 40, Image.SCALE_DEFAULT);_x000D_ _x000D_ Paard h1 = new Paard("Pinkie Pie", newimage);_x000D_ Paard h2 = new Paard("Twilight Sparkle", newimage);_x000D_ Paard h3 = new Paard("Fluttershy", newimage);_x000D_ Paard h4 = new Paard("Rainbow Dash", newimage);_x000D_ Paard h5 = new Paard("Applejack", newimage);_x000D_ _x000D_ /* (3) Declareer een button met de naam button van het type JButton */_x000D_ private JButton button;_x000D_ private JPanel panel;_x000D_ _x000D_ /** Applicatie - main functie voor runnen applicatie */_x000D_ public static void main(String[] args) {_x000D_ Race frame = new Race();_x000D_ /* (4) Geef het frame een breedte van 400 en hoogte van 140 */_x000D_ frame.setSize(800, 400);_x000D_ _x000D_ frame.createGUI();_x000D_ frame.setVisible(true);_x000D_ }_x000D_ _x000D_ /** Loop de race_x000D_ */_x000D_ private void startRace(Graphics g) {_x000D_ panel.setBackground(Color.white);_x000D_ /** Tekenen van de finish streep */_x000D_ /* (5) Geef de finish streep een rode kleur */_x000D_ int lengte = 250;_x000D_ Graphics paper = panel.getGraphics();_x000D_ _x000D_ g.setColor(Color.RED);_x000D_ g.fillRect(lengte, 0, 3, 350);_x000D_ /**(6) Creatie van 4 paarden_x000D_ * Dit is een instantiering van de 4 paard objecten_x000D_ * Bij de instantiering geef je de paarden een naam en een kleur mee_x000D_ * Kijk in de class Paard hoe je de paarden_x000D_ * kunt initialiseren._x000D_ */_x000D_ /** Loop tot een paard over de finish is*/_x000D_ while (h1.getAfstand() < lengte_x000D_ && h2.getAfstand() < lengte_x000D_ && h3.getAfstand() < lengte_x000D_ && h4.getAfstand() < lengte_x000D_ && h5.getAfstand() < lengte) {_x000D_ h1.run();_x000D_ h2.run();_x000D_ h3.run();_x000D_ h4.run();_x000D_ h5.run();_x000D_ _x000D_ /* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig_x000D_ * dat er 1 seconde pauze is. De methode pauzeer is onderdeel_x000D_ * van deze class_x000D_ */_x000D_ pauzeer(300);_x000D_ /* (8) Voeg hier code in om 4 paarden te tekenen die rennen_x000D_ * Dus een call van de methode tekenPaard_x000D_ */_x000D_ tekenPaard( paper, h1);_x000D_ tekenPaard( paper, h2);_x000D_ tekenPaard( paper, h3);_x000D_ tekenPaard( paper, h4);_x000D_ tekenPaard( paper, h5);_x000D_ }_x000D_ /** Kijk welk paard gewonnen heeft_x000D_ */_x000D_ if (h1.getAfstand() > lengte) {_x000D_ JOptionPane.showMessageDialog(null, h1.getNaam() + " gewonnen!");_x000D_ }_x000D_ if (h2.getAfstand() > lengte) {_x000D_ JOptionPane.showMessageDialog(null, h2.getNaam() + " gewonnen!");_x000D_ }_x000D_ if (h3.getAfstand() > lengte) {_x000D_ JOptionPane.showMessageDialog(null, h3.getNaam() + " gewonnen!");_x000D_ }_x000D_ if (h4.getAfstand() > lengte) {_x000D_ JOptionPane.showMessageDialog(null, h4.getNaam() + " gewonnen!");_x000D_ }_x000D_ if (h5.getAfstand() > lengte) {_x000D_ JOptionPane.showMessageDialog(null, h5.getNaam() + " gewonnen!");_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_ /** Creatie van de GUI*/_x000D_ private void createGUI() {_x000D_ setDefaultCloseOperation(EXIT_ON_CLOSE);_x000D_ Container window = getContentPane();_x000D_ window.setLayout(new FlowLayout());_x000D_ panel = new JPanel();_x000D_ panel.setPreferredSize(new Dimension(600, 250));_x000D_ panel.setBackground(Color.white);_x000D_ window.add(panel);_x000D_ /* (9) Zet hier de tekst Run! op de button */_x000D_ button = new JButton("RUN!");_x000D_ window.add(button);_x000D_ button.addActionListener(this);_x000D_ }_x000D_ _x000D_ /** Teken het paard */_x000D_ private void tekenPaard(Graphics g, Paard h) {_x000D_ g.setColor(Color.white);_x000D_ g.fillRect(0, 40 * h.getPaardNummer(), h.getAfstand(), 44);_x000D_ Image img = h.getimage();_x000D_ g.drawImage(img, h.getAfstand(), 40*h.getPaardNummer(), this);_x000D_ }_x000D_ _x000D_ /** Actie indien de button geklikt is*/_x000D_ public void actionPerformed(ActionEvent event) {_x000D_ Graphics paper = panel.getGraphics();_x000D_ /* (10) Roep hier de methode startrace aan met de juiste parameterisering */_x000D_ startRace (paper);_x000D_ }_x000D_ _x000D_ /** Pauzeer gedurende x millisecondes*/_x000D_ public void pauzeer(int msec) {_x000D_ try {_x000D_ Thread.sleep(msec);_x000D_ } catch (InterruptedException e) {_x000D_ System.out.println("Pauze interruptie");_x000D_ }_x000D_ }_x000D_ _x000D_ _x000D_ }_x000D_
itbc-bin/1819-owe5a-afvinkopdracht3-AloysKuster1
afvink3/Race.java
2,025
/* (5) Geef de finish streep een rode kleur */
block_comment
nl
package afvink3;_x000D_ _x000D_ /**_x000D_ * Race class_x000D_ * Class Race maakt gebruik van de class Paard_x000D_ *_x000D_ * @author Martijn van der Bruggen_x000D_ * @version alpha - aanroep van cruciale methodes ontbreekt_x000D_ * (c) 2009 Hogeschool van Arnhem en Nijmegen_x000D_ *_x000D_ * Note: deze code is bewust niet op alle punten generiek_x000D_ * dit om nog onbekende constructies te vermijden._x000D_ *_x000D_ * Updates_x000D_ * 2010: verduidelijking van opdrachten in de code MvdB_x000D_ * 2011: verbetering leesbaarheid code MvdB_x000D_ * 2012: verbetering layout code en aanpassing commentaar MvdB_x000D_ * 2013: commentaar aangepast aan nieuwe opdracht MvdB_x000D_ *_x000D_ *************************************************_x000D_ * Afvinkopdracht: werken met methodes en objecten_x000D_ *************************************************_x000D_ * Opdrachten zitten verwerkt in de code_x000D_ * 1) Declaratie constante_x000D_ * 2) Declaratie van Paard (niet instantiering)_x000D_ * 3) Declareer een button_x000D_ * 4) Zet breedte en hoogte van het frame_x000D_ * 5) Teken een finish streep_x000D_ * 6) Creatie van 4 paarden_x000D_ * 7) Pauzeer_x000D_ * 8) Teken 4 paarden_x000D_ * 9) Plaats tekst op de button_x000D_ * 10) Start de race, methode aanroep_x000D_ *_x000D_ *_x000D_ */_x000D_ import java.awt.*;_x000D_ import java.awt.event.*;_x000D_ import javax.swing.*;_x000D_ _x000D_ public class Race extends JFrame implements ActionListener {_x000D_ _x000D_ /** declaratie van variabelen */_x000D_ int var = 250; /*var van 250_x000D_ /* (2) Declareer hier h1, h2, h3, h4 van het type Paard_x000D_ * Deze paarden instantieer je later in het programma_x000D_ */_x000D_ Image foto = Toolkit.getDefaultToolkit().getImage("C:\\Users\\aloys\\Desktop\\opdrachten\\jaar 2\\Afvink 3 jaar 2\\Mylittlepony.GIF");_x000D_ Image newimage = foto.getScaledInstance(40, 40, Image.SCALE_DEFAULT);_x000D_ _x000D_ Paard h1 = new Paard("Pinkie Pie", newimage);_x000D_ Paard h2 = new Paard("Twilight Sparkle", newimage);_x000D_ Paard h3 = new Paard("Fluttershy", newimage);_x000D_ Paard h4 = new Paard("Rainbow Dash", newimage);_x000D_ Paard h5 = new Paard("Applejack", newimage);_x000D_ _x000D_ /* (3) Declareer een button met de naam button van het type JButton */_x000D_ private JButton button;_x000D_ private JPanel panel;_x000D_ _x000D_ /** Applicatie - main functie voor runnen applicatie */_x000D_ public static void main(String[] args) {_x000D_ Race frame = new Race();_x000D_ /* (4) Geef het frame een breedte van 400 en hoogte van 140 */_x000D_ frame.setSize(800, 400);_x000D_ _x000D_ frame.createGUI();_x000D_ frame.setVisible(true);_x000D_ }_x000D_ _x000D_ /** Loop de race_x000D_ */_x000D_ private void startRace(Graphics g) {_x000D_ panel.setBackground(Color.white);_x000D_ /** Tekenen van de finish streep */_x000D_ /* (5) Geef de<SUF>*/_x000D_ int lengte = 250;_x000D_ Graphics paper = panel.getGraphics();_x000D_ _x000D_ g.setColor(Color.RED);_x000D_ g.fillRect(lengte, 0, 3, 350);_x000D_ /**(6) Creatie van 4 paarden_x000D_ * Dit is een instantiering van de 4 paard objecten_x000D_ * Bij de instantiering geef je de paarden een naam en een kleur mee_x000D_ * Kijk in de class Paard hoe je de paarden_x000D_ * kunt initialiseren._x000D_ */_x000D_ /** Loop tot een paard over de finish is*/_x000D_ while (h1.getAfstand() < lengte_x000D_ && h2.getAfstand() < lengte_x000D_ && h3.getAfstand() < lengte_x000D_ && h4.getAfstand() < lengte_x000D_ && h5.getAfstand() < lengte) {_x000D_ h1.run();_x000D_ h2.run();_x000D_ h3.run();_x000D_ h4.run();_x000D_ h5.run();_x000D_ _x000D_ /* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig_x000D_ * dat er 1 seconde pauze is. De methode pauzeer is onderdeel_x000D_ * van deze class_x000D_ */_x000D_ pauzeer(300);_x000D_ /* (8) Voeg hier code in om 4 paarden te tekenen die rennen_x000D_ * Dus een call van de methode tekenPaard_x000D_ */_x000D_ tekenPaard( paper, h1);_x000D_ tekenPaard( paper, h2);_x000D_ tekenPaard( paper, h3);_x000D_ tekenPaard( paper, h4);_x000D_ tekenPaard( paper, h5);_x000D_ }_x000D_ /** Kijk welk paard gewonnen heeft_x000D_ */_x000D_ if (h1.getAfstand() > lengte) {_x000D_ JOptionPane.showMessageDialog(null, h1.getNaam() + " gewonnen!");_x000D_ }_x000D_ if (h2.getAfstand() > lengte) {_x000D_ JOptionPane.showMessageDialog(null, h2.getNaam() + " gewonnen!");_x000D_ }_x000D_ if (h3.getAfstand() > lengte) {_x000D_ JOptionPane.showMessageDialog(null, h3.getNaam() + " gewonnen!");_x000D_ }_x000D_ if (h4.getAfstand() > lengte) {_x000D_ JOptionPane.showMessageDialog(null, h4.getNaam() + " gewonnen!");_x000D_ }_x000D_ if (h5.getAfstand() > lengte) {_x000D_ JOptionPane.showMessageDialog(null, h5.getNaam() + " gewonnen!");_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_ /** Creatie van de GUI*/_x000D_ private void createGUI() {_x000D_ setDefaultCloseOperation(EXIT_ON_CLOSE);_x000D_ Container window = getContentPane();_x000D_ window.setLayout(new FlowLayout());_x000D_ panel = new JPanel();_x000D_ panel.setPreferredSize(new Dimension(600, 250));_x000D_ panel.setBackground(Color.white);_x000D_ window.add(panel);_x000D_ /* (9) Zet hier de tekst Run! op de button */_x000D_ button = new JButton("RUN!");_x000D_ window.add(button);_x000D_ button.addActionListener(this);_x000D_ }_x000D_ _x000D_ /** Teken het paard */_x000D_ private void tekenPaard(Graphics g, Paard h) {_x000D_ g.setColor(Color.white);_x000D_ g.fillRect(0, 40 * h.getPaardNummer(), h.getAfstand(), 44);_x000D_ Image img = h.getimage();_x000D_ g.drawImage(img, h.getAfstand(), 40*h.getPaardNummer(), this);_x000D_ }_x000D_ _x000D_ /** Actie indien de button geklikt is*/_x000D_ public void actionPerformed(ActionEvent event) {_x000D_ Graphics paper = panel.getGraphics();_x000D_ /* (10) Roep hier de methode startrace aan met de juiste parameterisering */_x000D_ startRace (paper);_x000D_ }_x000D_ _x000D_ /** Pauzeer gedurende x millisecondes*/_x000D_ public void pauzeer(int msec) {_x000D_ try {_x000D_ Thread.sleep(msec);_x000D_ } catch (InterruptedException e) {_x000D_ System.out.println("Pauze interruptie");_x000D_ }_x000D_ }_x000D_ _x000D_ _x000D_ }_x000D_
True
2,712
15
2,984
18
2,926
14
2,984
18
3,169
16
false
false
false
false
false
true
1,690
206048_12
package model; import java.util.ArrayList; import java.util.HashMap; import database.DatabaseEntity; import database.DatabaseSQLite; /** * Die Klasse Student bildet einen Studenten des b.i.b International College ab. * * Sie besitzt Attribute wie <code>name</code> oder <code>firstName</code>. * * @author Cornelia Stussig * */ public class Student extends DatabaseEntity { /** * Name der Datenbanktabelle */ public static final String TABLE_NAME = "Studenten"; /** * Spaltenname der Spalte StudentenID */ private static final String STUDENTEN_ID = "StudentenID"; /** * Spaltenname der Spalte Name */ private static final String NAME = "Name"; /** * Spaltenname der Spalte Nachname */ private static final String SECONDTNAME = "Nachname"; /** * Spaltenname der Spalte Bild Pfad */ private static final String PICTURE = "Bild"; /** * Spaltenname der Spalte Klasse */ private static final String STUDENTCLASS = "Klasse"; /** * Attribut für die Studenten-ID */ private String studentID; /** * Attribut für den Namen */ private String name; /** * Attribut für den Nachnamen */ private String secondName; /** * Attribut für das Bild */ private String picture; /** * Attribut für die Klasse */ private String studentClass; /** * Konstruktor, der die Parameter zur intialen Belegung entgegen nimmt * * @param studentID * @param name * @param secondName * @param picture * @param studentClass */ public Student(String studentID, String name, String secondName, String picture, String studentClass){ super(DatabaseSQLite.getInstance()); this.setStudentID(studentID); this.setName(name); this.setSecondName(secondName); this.setPicture(picture); this.setStudentClass(studentClass); } /** * Leerer Konstruktor * * Dient hauptsächlich zur Instanzierung durch die Datenbank-Klassen. * */ public Student() { this(null, null, null, null, null); } public String getStudentID() { return studentID; } public void setStudentID(String studentID) { this.studentID = studentID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSecondName() { return secondName; } public void setSecondName(String secondName) { this.secondName = secondName; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public String getStudentClass() { return studentClass; } public void setStudentClass(String studentClass) { this.studentClass = studentClass; } /** * Liefert Alle Studenten, die Anhand einer Like-Suche auf den Nachnamen in der Datenbank gesucht werden. * * @param name Name oder Teilname des Studenten * @return ArrayList aus Studenten-Objekten */ public static ArrayList<Student> getByName(String secondName){ String where = SECONDTNAME + " LIKE '" + secondName + "'"; return getByAttribute(where); } /** * Liefert Alle Studenten, die Anhand einer Like-Suche auf den Vornamen in der Datenbank gesucht werden. * * @param firstName Name oder Teilname des Studenten * @return ArrayList aus Studenten-Objekten */ public static ArrayList<Student> getByFirstame(String name){ String where = NAME + " LIKE '" + name + "'"; return getByAttribute(where); } /** * Liefert Alle Studenten, die Anhand einer Like-Suche auf die Studenten-ID in der Datenbank gesucht werden. * * @param studentenID studenten-ID des Studenten * @return ArrayList aus Studenten-Objekten */ public static ArrayList<Student> getByStudentID(String studentID){ String where = STUDENTEN_ID + " LIKE '" + studentID + "'"; return getByAttribute(where); } /** * Liefert Alle Studenten. * * @return ArrayList aus Studenten-Objekten */ public static ArrayList<Student> get(){ return getByAttribute(""); } /** * Führt auf der Datenbank-Objekt-Instanz die get-Methode aus und generiert aus dem zurückgegebenen Werten die Studenten-Objekte. * * @param where * @return */ private static ArrayList<Student> getByAttribute(String where) { ArrayList<HashMap<String, Object>> entries = DatabaseSQLite.getInstance().get(TABLE_NAME, where); ArrayList<Student> students = new ArrayList<Student>(); for (int i = 0; i < entries.size(); i++) { Student s = new Student(); s.studentID = (String) entries.get(i).get(STUDENTEN_ID); s.name = (String) entries.get(i).get(NAME); s.secondName = (String) entries.get(i).get(SECONDTNAME); s.picture = (String) entries.get(i).get(PICTURE); s.studentClass = (String) entries.get(i).get(STUDENTCLASS); s.isInDB = true; students.add(s); } return students; } /* (non-Javadoc) * @see db.DatabaseEntity#getValueMap() */ @Override protected HashMap<String, Object> getValueMap() { HashMap<String, Object> fields = new HashMap<String, Object>(); fields.put(STUDENTEN_ID, this.studentID); fields.put(NAME, this.name); fields.put(SECONDTNAME, this.secondName); fields.put(PICTURE, this.picture); fields.put(STUDENTCLASS, this.studentClass); return fields; } /* (non-Javadoc) * @see db.DatabaseEntity#getTableName() */ @Override protected String getTableName() { return TABLE_NAME; } /* (non-Javadoc) * @see db.DatabaseEntity#getPrimaryKey() */ @Override protected HashMap<String, Object> getPrimaryKey() { HashMap<String, Object> fields = new HashMap<String, Object>(); fields.put(STUDENTEN_ID, this.studentID); return fields; } }
Taunterl/VPR
model/Student.java
1,870
/** * Konstruktor, der die Parameter zur intialen Belegung entgegen nimmt * * @param studentID * @param name * @param secondName * @param picture * @param studentClass */
block_comment
nl
package model; import java.util.ArrayList; import java.util.HashMap; import database.DatabaseEntity; import database.DatabaseSQLite; /** * Die Klasse Student bildet einen Studenten des b.i.b International College ab. * * Sie besitzt Attribute wie <code>name</code> oder <code>firstName</code>. * * @author Cornelia Stussig * */ public class Student extends DatabaseEntity { /** * Name der Datenbanktabelle */ public static final String TABLE_NAME = "Studenten"; /** * Spaltenname der Spalte StudentenID */ private static final String STUDENTEN_ID = "StudentenID"; /** * Spaltenname der Spalte Name */ private static final String NAME = "Name"; /** * Spaltenname der Spalte Nachname */ private static final String SECONDTNAME = "Nachname"; /** * Spaltenname der Spalte Bild Pfad */ private static final String PICTURE = "Bild"; /** * Spaltenname der Spalte Klasse */ private static final String STUDENTCLASS = "Klasse"; /** * Attribut für die Studenten-ID */ private String studentID; /** * Attribut für den Namen */ private String name; /** * Attribut für den Nachnamen */ private String secondName; /** * Attribut für das Bild */ private String picture; /** * Attribut für die Klasse */ private String studentClass; /** * Konstruktor, der die<SUF>*/ public Student(String studentID, String name, String secondName, String picture, String studentClass){ super(DatabaseSQLite.getInstance()); this.setStudentID(studentID); this.setName(name); this.setSecondName(secondName); this.setPicture(picture); this.setStudentClass(studentClass); } /** * Leerer Konstruktor * * Dient hauptsächlich zur Instanzierung durch die Datenbank-Klassen. * */ public Student() { this(null, null, null, null, null); } public String getStudentID() { return studentID; } public void setStudentID(String studentID) { this.studentID = studentID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSecondName() { return secondName; } public void setSecondName(String secondName) { this.secondName = secondName; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public String getStudentClass() { return studentClass; } public void setStudentClass(String studentClass) { this.studentClass = studentClass; } /** * Liefert Alle Studenten, die Anhand einer Like-Suche auf den Nachnamen in der Datenbank gesucht werden. * * @param name Name oder Teilname des Studenten * @return ArrayList aus Studenten-Objekten */ public static ArrayList<Student> getByName(String secondName){ String where = SECONDTNAME + " LIKE '" + secondName + "'"; return getByAttribute(where); } /** * Liefert Alle Studenten, die Anhand einer Like-Suche auf den Vornamen in der Datenbank gesucht werden. * * @param firstName Name oder Teilname des Studenten * @return ArrayList aus Studenten-Objekten */ public static ArrayList<Student> getByFirstame(String name){ String where = NAME + " LIKE '" + name + "'"; return getByAttribute(where); } /** * Liefert Alle Studenten, die Anhand einer Like-Suche auf die Studenten-ID in der Datenbank gesucht werden. * * @param studentenID studenten-ID des Studenten * @return ArrayList aus Studenten-Objekten */ public static ArrayList<Student> getByStudentID(String studentID){ String where = STUDENTEN_ID + " LIKE '" + studentID + "'"; return getByAttribute(where); } /** * Liefert Alle Studenten. * * @return ArrayList aus Studenten-Objekten */ public static ArrayList<Student> get(){ return getByAttribute(""); } /** * Führt auf der Datenbank-Objekt-Instanz die get-Methode aus und generiert aus dem zurückgegebenen Werten die Studenten-Objekte. * * @param where * @return */ private static ArrayList<Student> getByAttribute(String where) { ArrayList<HashMap<String, Object>> entries = DatabaseSQLite.getInstance().get(TABLE_NAME, where); ArrayList<Student> students = new ArrayList<Student>(); for (int i = 0; i < entries.size(); i++) { Student s = new Student(); s.studentID = (String) entries.get(i).get(STUDENTEN_ID); s.name = (String) entries.get(i).get(NAME); s.secondName = (String) entries.get(i).get(SECONDTNAME); s.picture = (String) entries.get(i).get(PICTURE); s.studentClass = (String) entries.get(i).get(STUDENTCLASS); s.isInDB = true; students.add(s); } return students; } /* (non-Javadoc) * @see db.DatabaseEntity#getValueMap() */ @Override protected HashMap<String, Object> getValueMap() { HashMap<String, Object> fields = new HashMap<String, Object>(); fields.put(STUDENTEN_ID, this.studentID); fields.put(NAME, this.name); fields.put(SECONDTNAME, this.secondName); fields.put(PICTURE, this.picture); fields.put(STUDENTCLASS, this.studentClass); return fields; } /* (non-Javadoc) * @see db.DatabaseEntity#getTableName() */ @Override protected String getTableName() { return TABLE_NAME; } /* (non-Javadoc) * @see db.DatabaseEntity#getPrimaryKey() */ @Override protected HashMap<String, Object> getPrimaryKey() { HashMap<String, Object> fields = new HashMap<String, Object>(); fields.put(STUDENTEN_ID, this.studentID); return fields; } }
False
1,454
61
1,725
56
1,691
59
1,725
56
1,913
63
false
false
false
false
false
true
2,101
171074_1
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.driver.state.circuit.statement; import org.apache.shardingsphere.driver.jdbc.unsupported.AbstractUnsupportedOperationStatement; import org.apache.shardingsphere.driver.state.circuit.connection.CircuitBreakerConnection; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; /** * Circuit breaker statement. */ public final class CircuitBreakerStatement extends AbstractUnsupportedOperationStatement { @Override public void close() { } @Override public int getMaxFieldSize() { return 0; } @Override public void setMaxFieldSize(final int max) { } @Override public int getMaxRows() { return 0; } @Override public void setMaxRows(final int max) { } @Override public void setEscapeProcessing(final boolean enable) { } @Override public int getQueryTimeout() { return 0; } @Override public void setQueryTimeout(final int seconds) { } @Override public void cancel() { } @Override public SQLWarning getWarnings() { return null; } @Override public void clearWarnings() { } @Override public ResultSet getResultSet() { return null; } @Override public int getUpdateCount() { return 0; } @Override public void setFetchSize(final int rows) { } @Override public int getFetchSize() { return 0; } @Override public int getFetchDirection() { return ResultSet.FETCH_FORWARD; } @Override public void setFetchDirection(final int direction) { } @Override public int getResultSetConcurrency() { return ResultSet.CONCUR_READ_ONLY; } @Override public int getResultSetType() { return ResultSet.TYPE_FORWARD_ONLY; } @Override public void addBatch(final String sql) { } @Override public void clearBatch() { } @Override public int[] executeBatch() throws SQLException { return new int[0]; } @Override public Connection getConnection() { return new CircuitBreakerConnection(); } @Override public boolean getMoreResults() { return false; } @Override public boolean getMoreResults(final int current) { return false; } @Override public ResultSet getGeneratedKeys() { return null; } @Override public ResultSet executeQuery(final String sql) { return null; } @Override public int executeUpdate(final String sql) { return 0; } @Override public int executeUpdate(final String sql, final int autoGeneratedKeys) { return 0; } @Override public int executeUpdate(final String sql, final int[] columnIndexes) { return 0; } @Override public int executeUpdate(final String sql, final String[] columnNames) { return 0; } @Override public boolean execute(final String sql) { return false; } @Override public boolean execute(final String sql, final int autoGeneratedKeys) { return false; } @Override public boolean execute(final String sql, final int[] columnIndexes) { return false; } @Override public boolean execute(final String sql, final String[] columnNames) { return false; } @Override public int getResultSetHoldability() { return 0; } @Override public boolean isClosed() { return false; } @Override public void setPoolable(final boolean poolable) { } @Override public boolean isPoolable() { return false; } }
apache/shardingsphere
jdbc/src/main/java/org/apache/shardingsphere/driver/state/circuit/statement/CircuitBreakerStatement.java
1,329
/** * Circuit breaker statement. */
block_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.driver.state.circuit.statement; import org.apache.shardingsphere.driver.jdbc.unsupported.AbstractUnsupportedOperationStatement; import org.apache.shardingsphere.driver.state.circuit.connection.CircuitBreakerConnection; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; /** * Circuit breaker statement.<SUF>*/ public final class CircuitBreakerStatement extends AbstractUnsupportedOperationStatement { @Override public void close() { } @Override public int getMaxFieldSize() { return 0; } @Override public void setMaxFieldSize(final int max) { } @Override public int getMaxRows() { return 0; } @Override public void setMaxRows(final int max) { } @Override public void setEscapeProcessing(final boolean enable) { } @Override public int getQueryTimeout() { return 0; } @Override public void setQueryTimeout(final int seconds) { } @Override public void cancel() { } @Override public SQLWarning getWarnings() { return null; } @Override public void clearWarnings() { } @Override public ResultSet getResultSet() { return null; } @Override public int getUpdateCount() { return 0; } @Override public void setFetchSize(final int rows) { } @Override public int getFetchSize() { return 0; } @Override public int getFetchDirection() { return ResultSet.FETCH_FORWARD; } @Override public void setFetchDirection(final int direction) { } @Override public int getResultSetConcurrency() { return ResultSet.CONCUR_READ_ONLY; } @Override public int getResultSetType() { return ResultSet.TYPE_FORWARD_ONLY; } @Override public void addBatch(final String sql) { } @Override public void clearBatch() { } @Override public int[] executeBatch() throws SQLException { return new int[0]; } @Override public Connection getConnection() { return new CircuitBreakerConnection(); } @Override public boolean getMoreResults() { return false; } @Override public boolean getMoreResults(final int current) { return false; } @Override public ResultSet getGeneratedKeys() { return null; } @Override public ResultSet executeQuery(final String sql) { return null; } @Override public int executeUpdate(final String sql) { return 0; } @Override public int executeUpdate(final String sql, final int autoGeneratedKeys) { return 0; } @Override public int executeUpdate(final String sql, final int[] columnIndexes) { return 0; } @Override public int executeUpdate(final String sql, final String[] columnNames) { return 0; } @Override public boolean execute(final String sql) { return false; } @Override public boolean execute(final String sql, final int autoGeneratedKeys) { return false; } @Override public boolean execute(final String sql, final int[] columnIndexes) { return false; } @Override public boolean execute(final String sql, final String[] columnNames) { return false; } @Override public int getResultSetHoldability() { return 0; } @Override public boolean isClosed() { return false; } @Override public void setPoolable(final boolean poolable) { } @Override public boolean isPoolable() { return false; } }
False
1,047
7
1,038
10
1,257
9
1,038
10
1,345
11
false
false
false
false
false
true
3,570
204021_3
package com.alipay.util.httpClient;_x000D_ _x000D_ import org.apache.commons.httpclient.NameValuePair;_x000D_ _x000D_ /* *_x000D_ *类名:HttpRequest_x000D_ *功能:Http请求对象的封装_x000D_ *详细:封装Http请求_x000D_ *版本:3.3_x000D_ *日期:2011-08-17_x000D_ *说明:_x000D_ *以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。_x000D_ *该代码仅供学习和研究支付宝接口使用,只是提供一个参考。_x000D_ */_x000D_ _x000D_ public class HttpRequest {_x000D_ _x000D_ /** HTTP GET method */_x000D_ public static final String METHOD_GET = "GET";_x000D_ _x000D_ /** HTTP POST method */_x000D_ public static final String METHOD_POST = "POST";_x000D_ _x000D_ /**_x000D_ * 待请求的url_x000D_ */_x000D_ private String url = null;_x000D_ _x000D_ /**_x000D_ * 默认的请求方式_x000D_ */_x000D_ private String method = METHOD_POST;_x000D_ _x000D_ private int timeout = 0;_x000D_ _x000D_ private int connectionTimeout = 0;_x000D_ _x000D_ /**_x000D_ * Post方式请求时组装好的参数值对_x000D_ */_x000D_ private NameValuePair[] parameters = null;_x000D_ _x000D_ /**_x000D_ * Get方式请求时对应的参数_x000D_ */_x000D_ private String queryString = null;_x000D_ _x000D_ /**_x000D_ * 默认的请求编码方式_x000D_ */_x000D_ private String charset = "GBK";_x000D_ _x000D_ /**_x000D_ * 请求发起方的ip地址_x000D_ */_x000D_ private String clientIp;_x000D_ _x000D_ /**_x000D_ * 请求返回的方式_x000D_ */_x000D_ private HttpResultType resultType = HttpResultType.BYTES;_x000D_ _x000D_ public HttpRequest(HttpResultType resultType) {_x000D_ super();_x000D_ this.resultType = resultType;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @return Returns the clientIp._x000D_ */_x000D_ public String getClientIp() {_x000D_ return clientIp;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @param clientIp The clientIp to set._x000D_ */_x000D_ public void setClientIp(String clientIp) {_x000D_ this.clientIp = clientIp;_x000D_ }_x000D_ _x000D_ public NameValuePair[] getParameters() {_x000D_ return parameters;_x000D_ }_x000D_ _x000D_ public void setParameters(NameValuePair[] parameters) {_x000D_ this.parameters = parameters;_x000D_ }_x000D_ _x000D_ public String getQueryString() {_x000D_ return queryString;_x000D_ }_x000D_ _x000D_ public void setQueryString(String queryString) {_x000D_ this.queryString = queryString;_x000D_ }_x000D_ _x000D_ public String getUrl() {_x000D_ return url;_x000D_ }_x000D_ _x000D_ public void setUrl(String url) {_x000D_ this.url = url;_x000D_ }_x000D_ _x000D_ public String getMethod() {_x000D_ return method;_x000D_ }_x000D_ _x000D_ public void setMethod(String method) {_x000D_ this.method = method;_x000D_ }_x000D_ _x000D_ public int getConnectionTimeout() {_x000D_ return connectionTimeout;_x000D_ }_x000D_ _x000D_ public void setConnectionTimeout(int connectionTimeout) {_x000D_ this.connectionTimeout = connectionTimeout;_x000D_ }_x000D_ _x000D_ public int getTimeout() {_x000D_ return timeout;_x000D_ }_x000D_ _x000D_ public void setTimeout(int timeout) {_x000D_ this.timeout = timeout;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @return Returns the charset._x000D_ */_x000D_ public String getCharset() {_x000D_ return charset;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @param charset The charset to set._x000D_ */_x000D_ public void setCharset(String charset) {_x000D_ this.charset = charset;_x000D_ }_x000D_ _x000D_ public HttpResultType getResultType() {_x000D_ return resultType;_x000D_ }_x000D_ _x000D_ public void setResultType(HttpResultType resultType) {_x000D_ this.resultType = resultType;_x000D_ }_x000D_ _x000D_ }_x000D_
marquisthunder/newarch
kaas/kaas-pay/src/main/java/com/alipay/util/httpClient/HttpRequest.java
988
/**_x000D_ * 待请求的url_x000D_ */
block_comment
nl
package com.alipay.util.httpClient;_x000D_ _x000D_ import org.apache.commons.httpclient.NameValuePair;_x000D_ _x000D_ /* *_x000D_ *类名:HttpRequest_x000D_ *功能:Http请求对象的封装_x000D_ *详细:封装Http请求_x000D_ *版本:3.3_x000D_ *日期:2011-08-17_x000D_ *说明:_x000D_ *以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。_x000D_ *该代码仅供学习和研究支付宝接口使用,只是提供一个参考。_x000D_ */_x000D_ _x000D_ public class HttpRequest {_x000D_ _x000D_ /** HTTP GET method */_x000D_ public static final String METHOD_GET = "GET";_x000D_ _x000D_ /** HTTP POST method */_x000D_ public static final String METHOD_POST = "POST";_x000D_ _x000D_ /**_x000D_ * 待请求的url_x000D_ <SUF>*/_x000D_ private String url = null;_x000D_ _x000D_ /**_x000D_ * 默认的请求方式_x000D_ */_x000D_ private String method = METHOD_POST;_x000D_ _x000D_ private int timeout = 0;_x000D_ _x000D_ private int connectionTimeout = 0;_x000D_ _x000D_ /**_x000D_ * Post方式请求时组装好的参数值对_x000D_ */_x000D_ private NameValuePair[] parameters = null;_x000D_ _x000D_ /**_x000D_ * Get方式请求时对应的参数_x000D_ */_x000D_ private String queryString = null;_x000D_ _x000D_ /**_x000D_ * 默认的请求编码方式_x000D_ */_x000D_ private String charset = "GBK";_x000D_ _x000D_ /**_x000D_ * 请求发起方的ip地址_x000D_ */_x000D_ private String clientIp;_x000D_ _x000D_ /**_x000D_ * 请求返回的方式_x000D_ */_x000D_ private HttpResultType resultType = HttpResultType.BYTES;_x000D_ _x000D_ public HttpRequest(HttpResultType resultType) {_x000D_ super();_x000D_ this.resultType = resultType;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @return Returns the clientIp._x000D_ */_x000D_ public String getClientIp() {_x000D_ return clientIp;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @param clientIp The clientIp to set._x000D_ */_x000D_ public void setClientIp(String clientIp) {_x000D_ this.clientIp = clientIp;_x000D_ }_x000D_ _x000D_ public NameValuePair[] getParameters() {_x000D_ return parameters;_x000D_ }_x000D_ _x000D_ public void setParameters(NameValuePair[] parameters) {_x000D_ this.parameters = parameters;_x000D_ }_x000D_ _x000D_ public String getQueryString() {_x000D_ return queryString;_x000D_ }_x000D_ _x000D_ public void setQueryString(String queryString) {_x000D_ this.queryString = queryString;_x000D_ }_x000D_ _x000D_ public String getUrl() {_x000D_ return url;_x000D_ }_x000D_ _x000D_ public void setUrl(String url) {_x000D_ this.url = url;_x000D_ }_x000D_ _x000D_ public String getMethod() {_x000D_ return method;_x000D_ }_x000D_ _x000D_ public void setMethod(String method) {_x000D_ this.method = method;_x000D_ }_x000D_ _x000D_ public int getConnectionTimeout() {_x000D_ return connectionTimeout;_x000D_ }_x000D_ _x000D_ public void setConnectionTimeout(int connectionTimeout) {_x000D_ this.connectionTimeout = connectionTimeout;_x000D_ }_x000D_ _x000D_ public int getTimeout() {_x000D_ return timeout;_x000D_ }_x000D_ _x000D_ public void setTimeout(int timeout) {_x000D_ this.timeout = timeout;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @return Returns the charset._x000D_ */_x000D_ public String getCharset() {_x000D_ return charset;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @param charset The charset to set._x000D_ */_x000D_ public void setCharset(String charset) {_x000D_ this.charset = charset;_x000D_ }_x000D_ _x000D_ public HttpResultType getResultType() {_x000D_ return resultType;_x000D_ }_x000D_ _x000D_ public void setResultType(HttpResultType resultType) {_x000D_ this.resultType = resultType;_x000D_ }_x000D_ _x000D_ }_x000D_
False
1,682
23
1,786
24
1,888
25
1,786
24
2,084
29
false
false
false
false
false
true
1,896
96557_2
package project23.framework; import javafx.scene.paint.Color; import project23.framework.board.Board; import project23.framework.player.LocalPlayer; import project23.framework.player.Player; import project23.util.Logger; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; /** * Returns relevant Board-objects, Player-objects (and more?) */ public abstract class Game { public static final String AI_NAME = "Computer"; private boolean online = false; private String helpText; public abstract Function<GameManager, Board> createBoardFactory(); public abstract BiFunction<Board, Integer, Player> createAIPlayerFactory(); public BiFunction<Board, Integer, Player> createLocalPlayerFactory() { return ((board, id) -> new LocalPlayer(board, id, ConfigData.getInstance().getPlayerName())); } /** * creates a GameManager. * * @return the gameManger */ public GameManager createGameManager() { if (online) { try { ConnectedGameManager cgm = new ConnectedGameManager( createBoardFactory(), ConfigData.getInstance().getServerIP(), ConfigData.getInstance().getServerPort(), createAIPlayerFactory() ); cgm.setSelfName(ConfigData.getInstance().getPlayerName()); cgm.login(); return cgm; } catch (IOException e) { Logger.error("Couldn't connect to server!"); e.printStackTrace(); } return null; } else { return new GameManager( createBoardFactory(), createLocalPlayerFactory(), createAIPlayerFactory() ); } } public abstract Color getBoardBackgroundColor(); public abstract List<URL> getBoardPieceIcons(); public abstract String[] getBoardPieceNames(); public abstract GameType getGameType(); public abstract boolean showPiecesCount(); // Aanroepen in GameMenu (lobby of lokale wedstrijd) public void setOnline(boolean isOnline) { this.online = isOnline; } public boolean isOnline() { return online; } public String getHelpText() { if (helpText == null) { loadHelpFile(); } return helpText; } // Moet aangeroepen worden door child-klassen protected void loadHelpFile() { StringBuilder helpTextBuilder = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream( "/helpfiles/" + getGameType().serverName + "-help.txt")))) { String line; while ((line = reader.readLine()) != null) { helpTextBuilder.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } helpText = helpTextBuilder.toString(); } }
WouterGritter/project-2.3
src/main/java/project23/framework/Game.java
827
// Aanroepen in GameMenu (lobby of lokale wedstrijd)
line_comment
nl
package project23.framework; import javafx.scene.paint.Color; import project23.framework.board.Board; import project23.framework.player.LocalPlayer; import project23.framework.player.Player; import project23.util.Logger; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; /** * Returns relevant Board-objects, Player-objects (and more?) */ public abstract class Game { public static final String AI_NAME = "Computer"; private boolean online = false; private String helpText; public abstract Function<GameManager, Board> createBoardFactory(); public abstract BiFunction<Board, Integer, Player> createAIPlayerFactory(); public BiFunction<Board, Integer, Player> createLocalPlayerFactory() { return ((board, id) -> new LocalPlayer(board, id, ConfigData.getInstance().getPlayerName())); } /** * creates a GameManager. * * @return the gameManger */ public GameManager createGameManager() { if (online) { try { ConnectedGameManager cgm = new ConnectedGameManager( createBoardFactory(), ConfigData.getInstance().getServerIP(), ConfigData.getInstance().getServerPort(), createAIPlayerFactory() ); cgm.setSelfName(ConfigData.getInstance().getPlayerName()); cgm.login(); return cgm; } catch (IOException e) { Logger.error("Couldn't connect to server!"); e.printStackTrace(); } return null; } else { return new GameManager( createBoardFactory(), createLocalPlayerFactory(), createAIPlayerFactory() ); } } public abstract Color getBoardBackgroundColor(); public abstract List<URL> getBoardPieceIcons(); public abstract String[] getBoardPieceNames(); public abstract GameType getGameType(); public abstract boolean showPiecesCount(); // Aanroepen in<SUF> public void setOnline(boolean isOnline) { this.online = isOnline; } public boolean isOnline() { return online; } public String getHelpText() { if (helpText == null) { loadHelpFile(); } return helpText; } // Moet aangeroepen worden door child-klassen protected void loadHelpFile() { StringBuilder helpTextBuilder = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream( "/helpfiles/" + getGameType().serverName + "-help.txt")))) { String line; while ((line = reader.readLine()) != null) { helpTextBuilder.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } helpText = helpTextBuilder.toString(); } }
True
610
18
691
20
739
13
691
20
821
19
false
false
false
false
false
true
4,158
207401_5
package views;_x000D_ _x000D_ import controllers.AccountController;_x000D_ import helpers.MenuButton;_x000D_ _x000D_ import javax.swing.*;_x000D_ import java.awt.*;_x000D_ import java.awt.event.ActionEvent;_x000D_ import java.awt.event.ActionListener;_x000D_ _x000D_ /**_x000D_ * User: Reinier Koops_x000D_ * Class: View, shows what the user sees (and gets its info through the controller)_x000D_ */_x000D_ _x000D_ public class AccessView extends IpsenView implements ActionListener_x000D_ {_x000D_ private AccountController controller;_x000D_ _x000D_ private JTable table;_x000D_ private JButton btnRightGrp, btnRight, btnAccount, btnStatistics;_x000D_ private JPanel topPanel;_x000D_ _x000D_ /**_x000D_ * Class Constructor_x000D_ * @param controller Account Controller_x000D_ */_x000D_ _x000D_ public AccessView(AccountController controller) // controller mist_x000D_ {_x000D_ //link aan betreffende controller_x000D_ _x000D_ this.setLayout( new BorderLayout() );_x000D_ topPanel = new JPanel();_x000D_ topPanel.setPreferredSize( new Dimension( 1000, 68 ) );_x000D_ _x000D_ //buttons afbeelding nog toewijzen_x000D_ _x000D_ btnRight = new MenuButton( "assets/rechten.png", null, null );_x000D_ btnRightGrp = new MenuButton( "assets/nw_rightgroep_btn.png", null, null );_x000D_ btnAccount = new MenuButton( "assets/accounts.png", null, null );_x000D_ btnStatistics = new MenuButton( "assets/statistiek_inzien", null, null );_x000D_ _x000D_ //buttons laten werken als je erop klikt_x000D_ _x000D_ btnRight.addActionListener( this );_x000D_ btnAccount.addActionListener( this );_x000D_ btnRightGrp.addActionListener( this );_x000D_ btnStatistics.addActionListener( this );_x000D_ _x000D_ //buttons toevoegen aan het topPanel_x000D_ _x000D_ this.topPanel.add( btnRight );_x000D_ this.topPanel.add( btnRightGrp );_x000D_ this.topPanel.add( btnAccount );_x000D_ this.topPanel.add( btnStatistics );_x000D_ _x000D_ this.add( topPanel, BorderLayout.NORTH );_x000D_ _x000D_ }_x000D_ _x000D_ /**_x000D_ * Method to actionPerformed changes the view, by using the controller and displaying the next view_x000D_ *_x000D_ * the actionPerfomed performs no action in this class only showing the buttons_x000D_ */_x000D_ _x000D_ @Override_x000D_ public void actionPerformed( ActionEvent e )_x000D_ {_x000D_ Object s = e.getSource();_x000D_ if (s == btnRight)_x000D_ {_x000D_ //Right button geselecteerd -> ga naar dit submenu_x000D_ // AccessRightView accesRightView;_x000D_ // {_x000D_ // accesRightView = new AccessRightView();_x000D_ // }_x000D_ }_x000D_ _x000D_ if (s == btnRightGrp)_x000D_ {_x000D_ //Rightgroup button geselecteerd -> ga naar dit submenu_x000D_ // AccessRightGroupView accesRightGroupView;_x000D_ // {_x000D_ // accesRightGroupView = new AccessRightGroupView();_x000D_ // }_x000D_ }_x000D_ _x000D_ if (s == btnAccount)_x000D_ {_x000D_ //Account button geselecteerd -> ga naar dit submenu_x000D_ // AccesAccountView accesAccountView;_x000D_ // {_x000D_ // accesAccountView = new AccesAccountView();_x000D_ // }_x000D_ }_x000D_ _x000D_ if (s == btnStatistics)_x000D_ {_x000D_ //Statistics button geselecteerd -> ga naar dit submenu_x000D_ // AccessStatisticsView accesStatisticsView;_x000D_ // {_x000D_ // accesStatisticsView = new AccessStatisticsView();_x000D_ // }_x000D_ }_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_
reshadf/ipsen3-app
src/views/AccessView.java
925
//buttons toevoegen aan het topPanel_x000D_
line_comment
nl
package views;_x000D_ _x000D_ import controllers.AccountController;_x000D_ import helpers.MenuButton;_x000D_ _x000D_ import javax.swing.*;_x000D_ import java.awt.*;_x000D_ import java.awt.event.ActionEvent;_x000D_ import java.awt.event.ActionListener;_x000D_ _x000D_ /**_x000D_ * User: Reinier Koops_x000D_ * Class: View, shows what the user sees (and gets its info through the controller)_x000D_ */_x000D_ _x000D_ public class AccessView extends IpsenView implements ActionListener_x000D_ {_x000D_ private AccountController controller;_x000D_ _x000D_ private JTable table;_x000D_ private JButton btnRightGrp, btnRight, btnAccount, btnStatistics;_x000D_ private JPanel topPanel;_x000D_ _x000D_ /**_x000D_ * Class Constructor_x000D_ * @param controller Account Controller_x000D_ */_x000D_ _x000D_ public AccessView(AccountController controller) // controller mist_x000D_ {_x000D_ //link aan betreffende controller_x000D_ _x000D_ this.setLayout( new BorderLayout() );_x000D_ topPanel = new JPanel();_x000D_ topPanel.setPreferredSize( new Dimension( 1000, 68 ) );_x000D_ _x000D_ //buttons afbeelding nog toewijzen_x000D_ _x000D_ btnRight = new MenuButton( "assets/rechten.png", null, null );_x000D_ btnRightGrp = new MenuButton( "assets/nw_rightgroep_btn.png", null, null );_x000D_ btnAccount = new MenuButton( "assets/accounts.png", null, null );_x000D_ btnStatistics = new MenuButton( "assets/statistiek_inzien", null, null );_x000D_ _x000D_ //buttons laten werken als je erop klikt_x000D_ _x000D_ btnRight.addActionListener( this );_x000D_ btnAccount.addActionListener( this );_x000D_ btnRightGrp.addActionListener( this );_x000D_ btnStatistics.addActionListener( this );_x000D_ _x000D_ //buttons toevoegen<SUF> _x000D_ this.topPanel.add( btnRight );_x000D_ this.topPanel.add( btnRightGrp );_x000D_ this.topPanel.add( btnAccount );_x000D_ this.topPanel.add( btnStatistics );_x000D_ _x000D_ this.add( topPanel, BorderLayout.NORTH );_x000D_ _x000D_ }_x000D_ _x000D_ /**_x000D_ * Method to actionPerformed changes the view, by using the controller and displaying the next view_x000D_ *_x000D_ * the actionPerfomed performs no action in this class only showing the buttons_x000D_ */_x000D_ _x000D_ @Override_x000D_ public void actionPerformed( ActionEvent e )_x000D_ {_x000D_ Object s = e.getSource();_x000D_ if (s == btnRight)_x000D_ {_x000D_ //Right button geselecteerd -> ga naar dit submenu_x000D_ // AccessRightView accesRightView;_x000D_ // {_x000D_ // accesRightView = new AccessRightView();_x000D_ // }_x000D_ }_x000D_ _x000D_ if (s == btnRightGrp)_x000D_ {_x000D_ //Rightgroup button geselecteerd -> ga naar dit submenu_x000D_ // AccessRightGroupView accesRightGroupView;_x000D_ // {_x000D_ // accesRightGroupView = new AccessRightGroupView();_x000D_ // }_x000D_ }_x000D_ _x000D_ if (s == btnAccount)_x000D_ {_x000D_ //Account button geselecteerd -> ga naar dit submenu_x000D_ // AccesAccountView accesAccountView;_x000D_ // {_x000D_ // accesAccountView = new AccesAccountView();_x000D_ // }_x000D_ }_x000D_ _x000D_ if (s == btnStatistics)_x000D_ {_x000D_ //Statistics button geselecteerd -> ga naar dit submenu_x000D_ // AccessStatisticsView accesStatisticsView;_x000D_ // {_x000D_ // accesStatisticsView = new AccessStatisticsView();_x000D_ // }_x000D_ }_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_
True
1,364
15
1,494
17
1,521
15
1,494
17
1,617
17
false
false
false
false
false
true
4,211
75231_0
package pojo;_x000D_ _x000D_ import javax.xml.bind.annotation.XmlElement;_x000D_ _x000D_ public class VertrekkendeTrein {_x000D_ _x000D_ private int ritNummer;_x000D_ private String vertrekTijd;_x000D_ private String eindBestemming;_x000D_ private String treinSoort;_x000D_ private String routeTekst;_x000D_ private String vervoerder;_x000D_ private String vertrekSpoor;_x000D_ _x000D_ @XmlElement(name = "RitNummer")_x000D_ public int getRitNummer() {_x000D_ return ritNummer;_x000D_ }_x000D_ _x000D_ @XmlElement(name = "VertrekTijd")_x000D_ public String getVertrekTijd() {_x000D_ return vertrekTijd;_x000D_ }_x000D_ _x000D_ @XmlElement(name = "EindBestemming")_x000D_ public String getEindBestemming() {_x000D_ return eindBestemming;_x000D_ }_x000D_ _x000D_ @XmlElement(name = "TreinSoort")_x000D_ public String getTreinSoort() {_x000D_ return treinSoort;_x000D_ }_x000D_ _x000D_ @XmlElement(name = "RouteTekst")_x000D_ public String getRouteTekst() {_x000D_ return routeTekst;_x000D_ }_x000D_ _x000D_ @XmlElement(name = "Vervoerder")_x000D_ public String getVervoerder() {_x000D_ return vervoerder;_x000D_ }_x000D_ _x000D_ @XmlElement(name = "VertrekSpoor")_x000D_ public String getVertrekSpoor() {_x000D_ return vertrekSpoor;_x000D_ }_x000D_ _x000D_ public void setRitNummer(int ritNummer) {_x000D_ this.ritNummer = ritNummer;_x000D_ }_x000D_ _x000D_ public void setVertrekTijd(String vertrekTijd) {_x000D_ this.vertrekTijd = vertrekTijd;_x000D_ }_x000D_ _x000D_ public void setEindBestemming(String eindBestemming) {_x000D_ this.eindBestemming = eindBestemming;_x000D_ }_x000D_ _x000D_ public void setTreinSoort(String treinSoort) {_x000D_ this.treinSoort = treinSoort;_x000D_ }_x000D_ _x000D_ public void setRouteTekst(String routeTekst) {_x000D_ this.routeTekst = routeTekst;_x000D_ }_x000D_ _x000D_ public void setVervoerder(String vervoerder) {_x000D_ this.vervoerder = vervoerder;_x000D_ }_x000D_ _x000D_ public void setVertrekSpoor(String vertrekSpoor) {_x000D_ this.vertrekSpoor = vertrekSpoor;_x000D_ }_x000D_ _x000D_ /*_x000D_ * <RitNummer>9844</RitNummer>_x000D_ * <VertrekTijd>2013-06-05T14:05:00+0200</VertrekTijd> <EindBestemming>Den_x000D_ * Haag Centraal</EindBestemming> <TreinSoort>Sprinter</TreinSoort>_x000D_ * <RouteTekst>Woerden, Gouda, Zoetermeer</RouteTekst>_x000D_ * <Vervoerder>NS</Vervoerder> <VertrekSpoor_x000D_ * wijziging="false">18a</VertrekSpoor>_x000D_ */_x000D_ }_x000D_
roydekleijn/webservicetests
src/test/java/pojo/VertrekkendeTrein.java
812
/*_x000D_ * <RitNummer>9844</RitNummer>_x000D_ * <VertrekTijd>2013-06-05T14:05:00+0200</VertrekTijd> <EindBestemming>Den_x000D_ * Haag Centraal</EindBestemming> <TreinSoort>Sprinter</TreinSoort>_x000D_ * <RouteTekst>Woerden, Gouda, Zoetermeer</RouteTekst>_x000D_ * <Vervoerder>NS</Vervoerder> <VertrekSpoor_x000D_ * wijziging="false">18a</VertrekSpoor>_x000D_ */
block_comment
nl
package pojo;_x000D_ _x000D_ import javax.xml.bind.annotation.XmlElement;_x000D_ _x000D_ public class VertrekkendeTrein {_x000D_ _x000D_ private int ritNummer;_x000D_ private String vertrekTijd;_x000D_ private String eindBestemming;_x000D_ private String treinSoort;_x000D_ private String routeTekst;_x000D_ private String vervoerder;_x000D_ private String vertrekSpoor;_x000D_ _x000D_ @XmlElement(name = "RitNummer")_x000D_ public int getRitNummer() {_x000D_ return ritNummer;_x000D_ }_x000D_ _x000D_ @XmlElement(name = "VertrekTijd")_x000D_ public String getVertrekTijd() {_x000D_ return vertrekTijd;_x000D_ }_x000D_ _x000D_ @XmlElement(name = "EindBestemming")_x000D_ public String getEindBestemming() {_x000D_ return eindBestemming;_x000D_ }_x000D_ _x000D_ @XmlElement(name = "TreinSoort")_x000D_ public String getTreinSoort() {_x000D_ return treinSoort;_x000D_ }_x000D_ _x000D_ @XmlElement(name = "RouteTekst")_x000D_ public String getRouteTekst() {_x000D_ return routeTekst;_x000D_ }_x000D_ _x000D_ @XmlElement(name = "Vervoerder")_x000D_ public String getVervoerder() {_x000D_ return vervoerder;_x000D_ }_x000D_ _x000D_ @XmlElement(name = "VertrekSpoor")_x000D_ public String getVertrekSpoor() {_x000D_ return vertrekSpoor;_x000D_ }_x000D_ _x000D_ public void setRitNummer(int ritNummer) {_x000D_ this.ritNummer = ritNummer;_x000D_ }_x000D_ _x000D_ public void setVertrekTijd(String vertrekTijd) {_x000D_ this.vertrekTijd = vertrekTijd;_x000D_ }_x000D_ _x000D_ public void setEindBestemming(String eindBestemming) {_x000D_ this.eindBestemming = eindBestemming;_x000D_ }_x000D_ _x000D_ public void setTreinSoort(String treinSoort) {_x000D_ this.treinSoort = treinSoort;_x000D_ }_x000D_ _x000D_ public void setRouteTekst(String routeTekst) {_x000D_ this.routeTekst = routeTekst;_x000D_ }_x000D_ _x000D_ public void setVervoerder(String vervoerder) {_x000D_ this.vervoerder = vervoerder;_x000D_ }_x000D_ _x000D_ public void setVertrekSpoor(String vertrekSpoor) {_x000D_ this.vertrekSpoor = vertrekSpoor;_x000D_ }_x000D_ _x000D_ /*_x000D_ * <RitNummer>9844</RitNummer>_x000D_ <SUF>*/_x000D_ }_x000D_
False
1,205
197
1,274
207
1,257
191
1,274
207
1,384
219
false
false
false
false
false
true
870
18925_6
package les08.opdracht8_1; public class Main { public static void main(String[] args) { /* Opgave a t/m f */ // Gebouw g; // Huis h = new Huis(10, 7, 1); // // g = h; // wel // g = new Huis(); // wel // h = g; // niet // h = (Huis)g; // wel // if (g instanceof Huis) h = (Huis)g; // wel // h.super.laatsteRenovatie = 1980; // niet /* Opgave g t/m k */ // Gebouw g; // Huis h = new Huis(10, 7, 2); // g = h; // // g.laatsteRenovatie = 1985; // binnen = 0 buiten = 1985 // h.laatsteRenovatie = 1990; // binnen = 1990 buiten = 1985 // ((Huis)g).laatsteRenovatie = 1995; // binnen = 1995 buiten = 1985 // h.renoveer(2000, 2005); // binnen = 2000 buiten = 2005 // g.isGeisoleerd = true; // niet /* Opgave l t/m o */ // Gebouw g; // Huis h = new Huis(10, 7, 3); // g = h; // // h.berekenHuur(); // klasse Huis // g.berekenHuur(); // klasse Huis // g.isoleer(); // niet // ((Huis)g).isoleer(); // wel } }
Josvanreenen/DU1OOP_werkboek
src/les08/opdracht8_1/Main.java
488
// h = (Huis)g; // wel
line_comment
nl
package les08.opdracht8_1; public class Main { public static void main(String[] args) { /* Opgave a t/m f */ // Gebouw g; // Huis h = new Huis(10, 7, 1); // // g = h; // wel // g = new Huis(); // wel // h = g; // niet // h =<SUF> // if (g instanceof Huis) h = (Huis)g; // wel // h.super.laatsteRenovatie = 1980; // niet /* Opgave g t/m k */ // Gebouw g; // Huis h = new Huis(10, 7, 2); // g = h; // // g.laatsteRenovatie = 1985; // binnen = 0 buiten = 1985 // h.laatsteRenovatie = 1990; // binnen = 1990 buiten = 1985 // ((Huis)g).laatsteRenovatie = 1995; // binnen = 1995 buiten = 1985 // h.renoveer(2000, 2005); // binnen = 2000 buiten = 2005 // g.isGeisoleerd = true; // niet /* Opgave l t/m o */ // Gebouw g; // Huis h = new Huis(10, 7, 3); // g = h; // // h.berekenHuur(); // klasse Huis // g.berekenHuur(); // klasse Huis // g.isoleer(); // niet // ((Huis)g).isoleer(); // wel } }
False
483
14
539
15
468
13
539
15
592
20
false
false
false
false
false
true
1,526
25530_12
package org.firstinspires.ftc.teamcode.auton; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.util.ElapsedTime; @Disabled//@Autonomous(name="AutonomousBlueWing", group="LinearOpmode") public class AutonomousBlueWing extends LinearOpMode { private ElapsedTime runtime = new ElapsedTime(); private DcMotorEx leftFront; private DcMotorEx rightFront; private DcMotorEx leftBack; private DcMotorEx rightBack; private DcMotorEx arm1; private Servo servoGripper; private Servo servoMoveGripper; private Servo servoIntake; double power = .6; private double servoGripperMin = 0.0; // Minimum position for servo1 (in degrees) private double servoGripperMax = 180.0; // Maximum position for servo1 (in degrees) private double servoMoveGripperMin = 0.0; // Minimum position for servo2 (in degrees) private double servoMoveGripperMax = 180.0; // Maximum position for servo2 (in degrees) public void init(HardwareMap map) { leftFront = map.get(DcMotorEx.class, "left_front"); rightFront = map.get(DcMotorEx.class, "right_front"); leftBack = map.get(DcMotorEx.class, "left_back"); rightBack = map.get(DcMotorEx.class, "right_back"); arm1 = hardwareMap.get(DcMotorEx.class, "arm1"); servoGripper = hardwareMap.get(Servo.class, "servoGripper"); servoMoveGripper = hardwareMap.get(Servo.class, "servoMoveGripper"); servoIntake = hardwareMap.get(Servo.class, "Intake"); servoGripper.setPosition(0); servoIntake.setPosition(1); leftFront.setDirection(DcMotorSimple.Direction.REVERSE); leftBack.setDirection(DcMotorSimple.Direction.REVERSE); leftFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); leftBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); rightFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); rightBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); /*leftBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); leftFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); leftBack.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightBack.setMode(DcMotor.RunMode.RUN_USING_ENCODER); leftFront.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightFront.setMode(DcMotor.RunMode.RUN_USING_ENCODER);*/ } @Override public void runOpMode() { runtime.reset(); telemetry.addData("Status", "Initialized"); telemetry.update(); init(hardwareMap); waitForStart(); runtime.reset(); //pak pixel en wacht servoGripper.setPosition(.2); servoIntake.setPosition(1); sleep(100); //Vanuit startpositie naar rechts leftFront.setPower(power); rightFront.setPower(-power); leftBack.setPower(-power); rightBack.setPower(power); sleep(650); //Intake open voor loslaten paarse pixel servoIntake.setPosition(0); //Klein beetje naar rechts leftFront.setPower(0); leftBack.setPower(0); rightBack.setPower(0); rightFront.setPower(0); sleep(200); //stukje naar achteren voor pixel leftFront.setPower(-power); rightFront.setPower(-power); leftBack.setPower(-power); rightBack.setPower(-power); sleep(180); //Recht naar voren leftFront.setPower(power); rightFront.setPower(power); leftBack.setPower(power); rightBack.setPower(power); sleep(1600); //Arm omhoog (tijdens het naar voren rijden) arm1.setPower(power); leftFront.setPower(0.5*power); rightFront.setPower(0.5*power); leftBack.setPower(0.5*power); rightBack.setPower(0.5*power); sleep(400); //langzaam tegen het bord aan rijden arm1.setPower(0); leftFront.setPower(0.3*power); rightFront.setPower(0.3*power); leftBack.setPower(0.3*power); rightBack.setPower(0.3*power); sleep(3000); //Alles uit leftFront.setPower(0); rightFront.setPower(0); leftBack.setPower(0); rightBack.setPower(0); sleep(100); //gele pixel op bord plaatsen servoMoveGripper.setPosition(0); sleep(800); //laat gele pixel los servoGripper.setPosition(.45); sleep(800); //alles uit leftFront.setPower(0); rightFront.setPower(0); leftBack.setPower(0); rightBack.setPower(0); sleep(250); //kléin stukje naar voren leftFront.setPower(-power); rightFront.setPower(-power); leftBack.setPower(-power); rightBack.setPower(-power); arm1.setPower(-power); sleep(60); //alles uit leftFront.setPower(-0); rightFront.setPower(-0); leftBack.setPower(-0); rightBack.setPower(-0); sleep(200); arm1.setPower(0); servoMoveGripper.setPosition(1); } } /* leftBack.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightBack.setMode(DcMotor.RunMode.RUN_USING_ENCODER); leftFront.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightFront.setMode(DcMotor.RunMode.RUN_USING_ENCODER); leftBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); leftFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); leftBack.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightBack.setMode(DcMotor.RunMode.RUN_USING_ENCODER); leftFront.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightFront.setMode(DcMotor.RunMode.RUN_USING_ENCODER); /* leftFront.setPower(20000); rightFront.setPower(20000); leftBack.setPower(20000); rightBack.setPower(20000); sleep( 500); leftFront.setPower(300); rightFront.setPower(0); leftBack.setPower(3); rightBack.setPower(0); leftBack.setPower(0); leftFront.setPower(0); leftFront.setPower(7); rightFront.setPower(7); leftBack.setPower(7); rightBack.setPower(7); arm1.setPower(power); arm1.setPower(0); leftFront.setPower(0); rightFront.setPower(0); leftBack.setPower(0); rightBack.setPower(0);*/
STACenterstage/FtcRobotController
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/auton/AutonomousBlueWing.java
2,497
//langzaam tegen het bord aan rijden
line_comment
nl
package org.firstinspires.ftc.teamcode.auton; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.util.ElapsedTime; @Disabled//@Autonomous(name="AutonomousBlueWing", group="LinearOpmode") public class AutonomousBlueWing extends LinearOpMode { private ElapsedTime runtime = new ElapsedTime(); private DcMotorEx leftFront; private DcMotorEx rightFront; private DcMotorEx leftBack; private DcMotorEx rightBack; private DcMotorEx arm1; private Servo servoGripper; private Servo servoMoveGripper; private Servo servoIntake; double power = .6; private double servoGripperMin = 0.0; // Minimum position for servo1 (in degrees) private double servoGripperMax = 180.0; // Maximum position for servo1 (in degrees) private double servoMoveGripperMin = 0.0; // Minimum position for servo2 (in degrees) private double servoMoveGripperMax = 180.0; // Maximum position for servo2 (in degrees) public void init(HardwareMap map) { leftFront = map.get(DcMotorEx.class, "left_front"); rightFront = map.get(DcMotorEx.class, "right_front"); leftBack = map.get(DcMotorEx.class, "left_back"); rightBack = map.get(DcMotorEx.class, "right_back"); arm1 = hardwareMap.get(DcMotorEx.class, "arm1"); servoGripper = hardwareMap.get(Servo.class, "servoGripper"); servoMoveGripper = hardwareMap.get(Servo.class, "servoMoveGripper"); servoIntake = hardwareMap.get(Servo.class, "Intake"); servoGripper.setPosition(0); servoIntake.setPosition(1); leftFront.setDirection(DcMotorSimple.Direction.REVERSE); leftBack.setDirection(DcMotorSimple.Direction.REVERSE); leftFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); leftBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); rightFront.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); rightBack.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); /*leftBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); leftFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); leftBack.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightBack.setMode(DcMotor.RunMode.RUN_USING_ENCODER); leftFront.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightFront.setMode(DcMotor.RunMode.RUN_USING_ENCODER);*/ } @Override public void runOpMode() { runtime.reset(); telemetry.addData("Status", "Initialized"); telemetry.update(); init(hardwareMap); waitForStart(); runtime.reset(); //pak pixel en wacht servoGripper.setPosition(.2); servoIntake.setPosition(1); sleep(100); //Vanuit startpositie naar rechts leftFront.setPower(power); rightFront.setPower(-power); leftBack.setPower(-power); rightBack.setPower(power); sleep(650); //Intake open voor loslaten paarse pixel servoIntake.setPosition(0); //Klein beetje naar rechts leftFront.setPower(0); leftBack.setPower(0); rightBack.setPower(0); rightFront.setPower(0); sleep(200); //stukje naar achteren voor pixel leftFront.setPower(-power); rightFront.setPower(-power); leftBack.setPower(-power); rightBack.setPower(-power); sleep(180); //Recht naar voren leftFront.setPower(power); rightFront.setPower(power); leftBack.setPower(power); rightBack.setPower(power); sleep(1600); //Arm omhoog (tijdens het naar voren rijden) arm1.setPower(power); leftFront.setPower(0.5*power); rightFront.setPower(0.5*power); leftBack.setPower(0.5*power); rightBack.setPower(0.5*power); sleep(400); //langzaam tegen<SUF> arm1.setPower(0); leftFront.setPower(0.3*power); rightFront.setPower(0.3*power); leftBack.setPower(0.3*power); rightBack.setPower(0.3*power); sleep(3000); //Alles uit leftFront.setPower(0); rightFront.setPower(0); leftBack.setPower(0); rightBack.setPower(0); sleep(100); //gele pixel op bord plaatsen servoMoveGripper.setPosition(0); sleep(800); //laat gele pixel los servoGripper.setPosition(.45); sleep(800); //alles uit leftFront.setPower(0); rightFront.setPower(0); leftBack.setPower(0); rightBack.setPower(0); sleep(250); //kléin stukje naar voren leftFront.setPower(-power); rightFront.setPower(-power); leftBack.setPower(-power); rightBack.setPower(-power); arm1.setPower(-power); sleep(60); //alles uit leftFront.setPower(-0); rightFront.setPower(-0); leftBack.setPower(-0); rightBack.setPower(-0); sleep(200); arm1.setPower(0); servoMoveGripper.setPosition(1); } } /* leftBack.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightBack.setMode(DcMotor.RunMode.RUN_USING_ENCODER); leftFront.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightFront.setMode(DcMotor.RunMode.RUN_USING_ENCODER); leftBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightBack.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); leftFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); rightFront.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); leftBack.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightBack.setMode(DcMotor.RunMode.RUN_USING_ENCODER); leftFront.setMode(DcMotor.RunMode.RUN_USING_ENCODER); rightFront.setMode(DcMotor.RunMode.RUN_USING_ENCODER); /* leftFront.setPower(20000); rightFront.setPower(20000); leftBack.setPower(20000); rightBack.setPower(20000); sleep( 500); leftFront.setPower(300); rightFront.setPower(0); leftBack.setPower(3); rightBack.setPower(0); leftBack.setPower(0); leftFront.setPower(0); leftFront.setPower(7); rightFront.setPower(7); leftBack.setPower(7); rightBack.setPower(7); arm1.setPower(power); arm1.setPower(0); leftFront.setPower(0); rightFront.setPower(0); leftBack.setPower(0); rightBack.setPower(0);*/
True
1,820
10
2,086
13
2,088
8
2,086
13
2,542
11
false
false
false
false
false
true
3,265
87784_5
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.byonder.zephyrbank.model; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.OneToOne; /** * * @author jvdgriendt */ @Entity public class SpaarRekening extends Rekening implements Serializable { private static final long serialVersionUID = 1L; private float opgebouwdeRente; @OneToOne private Rekening gekoppeldeRekening; public SpaarRekening(){ super(); } SpaarRekening(float saldo){ super(saldo); } /** * @param gekoppeldeRekening the gekoppeldeRekening to set */ public void setGekoppeldeRekening(Rekening gekoppeldeRekening) { this.gekoppeldeRekening = gekoppeldeRekening; } /** * @return the gekoppeldeRekening */ public Rekening getGekoppeldeRekening() { return gekoppeldeRekening; } public float getOpgebouwdeRente(){ return opgebouwdeRente; } /** * Update de rente met de nieuwe opbouw. * * @param rente de rente die is opgebouwd in de afgelope periode */ public void updateRente(float rente){ this.opgebouwdeRente += rente; } /** * keert het bedrag uit dat is opgebouwd aan rente. * En reset het opgebouwde bedrag naar 0. * * @return de opgebouwde rente */ public float keerRenteUit(){ float rente = opgebouwdeRente; opgebouwdeRente = 0.0f; return rente; } @Override public int hashCode() { int hash = 0; hash += (getId() != null ? getId().hashCode() : 0); return hash; } @Override public boolean equals(Object object) { if (!(object instanceof SpaarRekening)) { return false; } SpaarRekening other = (SpaarRekening) object; if ((this.getId() == null && other.getId() != null) || (this.getId() != null && !this.getId().equals(other.getId()))) { return false; } return true; } @Override public String toString() { return "SpaarRekening[id=" + getId() + "]"; } }
joostvdg/ZephyrBank-JBoss-7
ZephyrBank-ejb/src/main/java/net/byonder/zephyrbank/model/SpaarRekening.java
731
/** * keert het bedrag uit dat is opgebouwd aan rente. * En reset het opgebouwde bedrag naar 0. * * @return de opgebouwde rente */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.byonder.zephyrbank.model; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.OneToOne; /** * * @author jvdgriendt */ @Entity public class SpaarRekening extends Rekening implements Serializable { private static final long serialVersionUID = 1L; private float opgebouwdeRente; @OneToOne private Rekening gekoppeldeRekening; public SpaarRekening(){ super(); } SpaarRekening(float saldo){ super(saldo); } /** * @param gekoppeldeRekening the gekoppeldeRekening to set */ public void setGekoppeldeRekening(Rekening gekoppeldeRekening) { this.gekoppeldeRekening = gekoppeldeRekening; } /** * @return the gekoppeldeRekening */ public Rekening getGekoppeldeRekening() { return gekoppeldeRekening; } public float getOpgebouwdeRente(){ return opgebouwdeRente; } /** * Update de rente met de nieuwe opbouw. * * @param rente de rente die is opgebouwd in de afgelope periode */ public void updateRente(float rente){ this.opgebouwdeRente += rente; } /** * keert het bedrag<SUF>*/ public float keerRenteUit(){ float rente = opgebouwdeRente; opgebouwdeRente = 0.0f; return rente; } @Override public int hashCode() { int hash = 0; hash += (getId() != null ? getId().hashCode() : 0); return hash; } @Override public boolean equals(Object object) { if (!(object instanceof SpaarRekening)) { return false; } SpaarRekening other = (SpaarRekening) object; if ((this.getId() == null && other.getId() != null) || (this.getId() != null && !this.getId().equals(other.getId()))) { return false; } return true; } @Override public String toString() { return "SpaarRekening[id=" + getId() + "]"; } }
True
579
53
668
51
644
49
668
51
734
55
false
false
false
false
false
true
1,321
162618_1
package Services; import Domain.Controller; import Domain.RequestData; import com.google.gson.Gson; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import java.sql.*; import java.util.ArrayList; /** * Created by Polle on 3-2-2017. */ @Path("/generator") public class DeleterResource { @GET @Produces("application/json") @Path("deleteRule/{ruleData}") public String deleteRule(@PathParam("ruleData") String data) { Gson gson = new Gson(); RequestData requestData = gson.fromJson(data, RequestData.class); Controller.printToConsole("<span class=\"requestHead\">----------------------DELETING RULE---------------------</span>"); //in request data staan de gegevens van de database dus je kan bijvoorbeeld requestData.getUrl() gebruiken //Controller.printToConsole(requestData.toString()); String URL = requestData.getUrl(); String USER = requestData.getUserName(); String PASS = requestData.getPassword(); String DB_ID = requestData.getDbId(); String TABLE = requestData.getRuleTable(); String RULE = requestData.getRuleName(); String RULETYPE = requestData.getRuleTypeId(); ArrayList<String> s = getTargetDatabaseCredit(URL, USER, PASS, DB_ID); //Controller.printToConsole(Integer.toString(s.size())); if (s.size() > 2) { deleteConstraints(s.get(0), s.get(1), s.get(2), s.get(3), TABLE, RULE, RULETYPE); } //Domain.Controller.out += data + "<br>"; //Dit is voor debugging :) return null; } private void deleteConstraints(String DB_URL, String USER, String PASS, String DB_DRIVER, String TABLE, String RULE, String RULETYPE) { String driver = null; String url = null; if (DB_DRIVER.equals("oracle")) { url = "jdbc:oracle:thin:@" + DB_URL; driver = "oracle.jdbc.driver.OracleDriver"; } else if (DB_DRIVER.equals("mysql") ) { url = "sql:mysql:thin:@" + DB_URL; driver = "mysql.jdbc.driver.OracleDriver"; } Controller.printToConsole("Deleting constraints:"); //Controller.printToConsole("Database url: " + url); Connection conn = null; Statement stmt = null; String sql; if(RULETYPE.equals("6")){ sql = "DROP TRIGGER \"" + RULE + "\""; } else{ sql = "ALTER TABLE " + TABLE + " DROP CONSTRAINT " + RULE; } try { //Controller.printToConsole(driver); Class.forName(driver); conn = DriverManager.getConnection(url, USER, PASS); //Controller.printToConsole("Targetdb Connected"); stmt = conn.createStatement(); Controller.printToConsole(sql); //ResultSet rs = stmt.executeQuery(sql); stmt.execute(sql); stmt.close(); conn.close(); } catch (SQLException se) { se.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (stmt != null) stmt.close(); } catch (SQLException se2) { } try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } Controller.printToConsole("Done!"); } private ArrayList<String> getTargetDatabaseCredit(String DB_URL, String USER, String PASS, String DB_ID) { Connection conn = null; Statement stmt = null; String sql = null; String db_name = null; String url = "jdbc:oracle:thin:@" + DB_URL; ArrayList<String> DataList = new ArrayList<String>(); try { Class.forName("oracle.jdbc.driver.OracleDriver"); /*Controller.printToConsole("Target DB:"); Controller.printToConsole(url); Controller.printToConsole(USER); Controller.printToConsole(PASS);*/ conn = DriverManager.getConnection(url, USER, PASS); //Controller.printToConsole("Connected"); stmt = conn.createStatement(); sql = "SELECT * FROM TARGETDB WHERE IDTARGETDB = " + DB_ID; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { DataList.add(rs.getString("URL")); DataList.add(rs.getString("USERNAME")); DataList.add(rs.getString("PASSWORD")); DataList.add(rs.getString("LANGUAGE")); } rs.close(); stmt.close(); conn.close(); } catch (SQLException se) { se.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (stmt != null) stmt.close(); } catch (SQLException se2) { } try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } return DataList; } }
Polleps/TOSAD
src/main/java/Services/DeleterResource.java
1,525
//in request data staan de gegevens van de database dus je kan bijvoorbeeld requestData.getUrl() gebruiken
line_comment
nl
package Services; import Domain.Controller; import Domain.RequestData; import com.google.gson.Gson; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import java.sql.*; import java.util.ArrayList; /** * Created by Polle on 3-2-2017. */ @Path("/generator") public class DeleterResource { @GET @Produces("application/json") @Path("deleteRule/{ruleData}") public String deleteRule(@PathParam("ruleData") String data) { Gson gson = new Gson(); RequestData requestData = gson.fromJson(data, RequestData.class); Controller.printToConsole("<span class=\"requestHead\">----------------------DELETING RULE---------------------</span>"); //in request<SUF> //Controller.printToConsole(requestData.toString()); String URL = requestData.getUrl(); String USER = requestData.getUserName(); String PASS = requestData.getPassword(); String DB_ID = requestData.getDbId(); String TABLE = requestData.getRuleTable(); String RULE = requestData.getRuleName(); String RULETYPE = requestData.getRuleTypeId(); ArrayList<String> s = getTargetDatabaseCredit(URL, USER, PASS, DB_ID); //Controller.printToConsole(Integer.toString(s.size())); if (s.size() > 2) { deleteConstraints(s.get(0), s.get(1), s.get(2), s.get(3), TABLE, RULE, RULETYPE); } //Domain.Controller.out += data + "<br>"; //Dit is voor debugging :) return null; } private void deleteConstraints(String DB_URL, String USER, String PASS, String DB_DRIVER, String TABLE, String RULE, String RULETYPE) { String driver = null; String url = null; if (DB_DRIVER.equals("oracle")) { url = "jdbc:oracle:thin:@" + DB_URL; driver = "oracle.jdbc.driver.OracleDriver"; } else if (DB_DRIVER.equals("mysql") ) { url = "sql:mysql:thin:@" + DB_URL; driver = "mysql.jdbc.driver.OracleDriver"; } Controller.printToConsole("Deleting constraints:"); //Controller.printToConsole("Database url: " + url); Connection conn = null; Statement stmt = null; String sql; if(RULETYPE.equals("6")){ sql = "DROP TRIGGER \"" + RULE + "\""; } else{ sql = "ALTER TABLE " + TABLE + " DROP CONSTRAINT " + RULE; } try { //Controller.printToConsole(driver); Class.forName(driver); conn = DriverManager.getConnection(url, USER, PASS); //Controller.printToConsole("Targetdb Connected"); stmt = conn.createStatement(); Controller.printToConsole(sql); //ResultSet rs = stmt.executeQuery(sql); stmt.execute(sql); stmt.close(); conn.close(); } catch (SQLException se) { se.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (stmt != null) stmt.close(); } catch (SQLException se2) { } try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } Controller.printToConsole("Done!"); } private ArrayList<String> getTargetDatabaseCredit(String DB_URL, String USER, String PASS, String DB_ID) { Connection conn = null; Statement stmt = null; String sql = null; String db_name = null; String url = "jdbc:oracle:thin:@" + DB_URL; ArrayList<String> DataList = new ArrayList<String>(); try { Class.forName("oracle.jdbc.driver.OracleDriver"); /*Controller.printToConsole("Target DB:"); Controller.printToConsole(url); Controller.printToConsole(USER); Controller.printToConsole(PASS);*/ conn = DriverManager.getConnection(url, USER, PASS); //Controller.printToConsole("Connected"); stmt = conn.createStatement(); sql = "SELECT * FROM TARGETDB WHERE IDTARGETDB = " + DB_ID; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { DataList.add(rs.getString("URL")); DataList.add(rs.getString("USERNAME")); DataList.add(rs.getString("PASSWORD")); DataList.add(rs.getString("LANGUAGE")); } rs.close(); stmt.close(); conn.close(); } catch (SQLException se) { se.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (stmt != null) stmt.close(); } catch (SQLException se2) { } try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } return DataList; } }
True
1,044
24
1,222
28
1,309
20
1,222
28
1,477
27
false
false
false
false
false
true
3,329
87804_1
package org.molgenis.animaldb.convertors.locations;_x000D_ _x000D_ import java.io.File;_x000D_ import java.util.ArrayList;_x000D_ import java.util.Date;_x000D_ import java.util.List;_x000D_ _x000D_ import org.molgenis.animaldb.commonservice.CommonService;_x000D_ import org.molgenis.framework.db.Database;_x000D_ import org.molgenis.framework.security.Login;_x000D_ import org.molgenis.pheno.Location;_x000D_ import org.molgenis.util.CsvFileReader;_x000D_ import org.molgenis.util.Tuple;_x000D_ _x000D_ public class ImportAteLocations_x000D_ {_x000D_ private Database db;_x000D_ private CommonService ct;_x000D_ private List<String> seenLocs = new ArrayList<String>();_x000D_ private String userName;_x000D_ _x000D_ public ImportAteLocations(Database db, Login login) throws Exception_x000D_ {_x000D_ this.db = db;_x000D_ ct = CommonService.getInstance();_x000D_ ct.setDatabase(this.db);_x000D_ userName = login.getUserName();_x000D_ }_x000D_ _x000D_ public void doImport(String filename) throws Exception_x000D_ {_x000D_ final String investigationName = ct.getOwnUserInvestigationNames(userName).get(0);_x000D_ _x000D_ File file = new File(filename);_x000D_ CsvFileReader reader = new CsvFileReader(file);_x000D_ for (Tuple tuple : reader)_x000D_ {_x000D_ // gebouw nr -> name of building_x000D_ String buildingName = tuple.getString("gebouw nr");_x000D_ if (!seenLocs.contains(buildingName))_x000D_ {_x000D_ seenLocs.add(buildingName);_x000D_ Location newBuilding = new Location();_x000D_ newBuilding.setName(buildingName);_x000D_ newBuilding.setInvestigation_Name(investigationName);_x000D_ db.add(newBuilding);_x000D_ }_x000D_ // etage_x000D_ String floor = tuple.getString("etage");_x000D_ // kamer nr_x000D_ String room = tuple.getString("kamer nr");_x000D_ // omschrijving -> skip_x000D_ _x000D_ // Make location and link to building_x000D_ Location newLoc = new Location();_x000D_ newLoc.setName(floor + "." + room);_x000D_ newLoc.setInvestigation_Name(investigationName);_x000D_ db.add(newLoc);_x000D_ db.add(ct.createObservedValueWithProtocolApplication(investigationName, new Date(), null,_x000D_ "SetSublocationOf", "Location", newLoc.getName(), null, buildingName));_x000D_ }_x000D_ }_x000D_ _x000D_ }_x000D_
kantale/molgenis_apps
apps/animaldb/org/molgenis/animaldb/convertors/locations/ImportAteLocations.java
629
// omschrijving -> skip_x000D_
line_comment
nl
package org.molgenis.animaldb.convertors.locations;_x000D_ _x000D_ import java.io.File;_x000D_ import java.util.ArrayList;_x000D_ import java.util.Date;_x000D_ import java.util.List;_x000D_ _x000D_ import org.molgenis.animaldb.commonservice.CommonService;_x000D_ import org.molgenis.framework.db.Database;_x000D_ import org.molgenis.framework.security.Login;_x000D_ import org.molgenis.pheno.Location;_x000D_ import org.molgenis.util.CsvFileReader;_x000D_ import org.molgenis.util.Tuple;_x000D_ _x000D_ public class ImportAteLocations_x000D_ {_x000D_ private Database db;_x000D_ private CommonService ct;_x000D_ private List<String> seenLocs = new ArrayList<String>();_x000D_ private String userName;_x000D_ _x000D_ public ImportAteLocations(Database db, Login login) throws Exception_x000D_ {_x000D_ this.db = db;_x000D_ ct = CommonService.getInstance();_x000D_ ct.setDatabase(this.db);_x000D_ userName = login.getUserName();_x000D_ }_x000D_ _x000D_ public void doImport(String filename) throws Exception_x000D_ {_x000D_ final String investigationName = ct.getOwnUserInvestigationNames(userName).get(0);_x000D_ _x000D_ File file = new File(filename);_x000D_ CsvFileReader reader = new CsvFileReader(file);_x000D_ for (Tuple tuple : reader)_x000D_ {_x000D_ // gebouw nr -> name of building_x000D_ String buildingName = tuple.getString("gebouw nr");_x000D_ if (!seenLocs.contains(buildingName))_x000D_ {_x000D_ seenLocs.add(buildingName);_x000D_ Location newBuilding = new Location();_x000D_ newBuilding.setName(buildingName);_x000D_ newBuilding.setInvestigation_Name(investigationName);_x000D_ db.add(newBuilding);_x000D_ }_x000D_ // etage_x000D_ String floor = tuple.getString("etage");_x000D_ // kamer nr_x000D_ String room = tuple.getString("kamer nr");_x000D_ // omschrijving -><SUF> _x000D_ // Make location and link to building_x000D_ Location newLoc = new Location();_x000D_ newLoc.setName(floor + "." + room);_x000D_ newLoc.setInvestigation_Name(investigationName);_x000D_ db.add(newLoc);_x000D_ db.add(ct.createObservedValueWithProtocolApplication(investigationName, new Date(), null,_x000D_ "SetSublocationOf", "Location", newLoc.getName(), null, buildingName));_x000D_ }_x000D_ }_x000D_ _x000D_ }_x000D_
True
878
14
994
15
985
13
994
15
1,107
14
false
false
false
false
false
true
3,834
7599_10
package wiimote; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; import wiiusej.WiiUseApiManager; import wiiusej.Wiimote; import wiiusej.utils.AccelerationPanel; import wiiusej.utils.AccelerationWiimoteEventPanel; import wiiusej.values.RawAcceleration; import wiiusej.wiiusejevents.GenericEvent; import wiiusej.wiiusejevents.physicalevents.ExpansionEvent; import wiiusej.wiiusejevents.physicalevents.IREvent; import wiiusej.wiiusejevents.physicalevents.MotionSensingEvent; import wiiusej.wiiusejevents.physicalevents.WiimoteButtonsEvent; import wiiusej.wiiusejevents.utils.WiimoteListener; import wiiusej.wiiusejevents.wiiuseapievents.ClassicControllerInsertedEvent; import wiiusej.wiiusejevents.wiiuseapievents.ClassicControllerRemovedEvent; import wiiusej.wiiusejevents.wiiuseapievents.DisconnectionEvent; import wiiusej.wiiusejevents.wiiuseapievents.GuitarHeroInsertedEvent; import wiiusej.wiiusejevents.wiiuseapievents.GuitarHeroRemovedEvent; import wiiusej.wiiusejevents.wiiuseapievents.NunchukInsertedEvent; import wiiusej.wiiusejevents.wiiuseapievents.NunchukRemovedEvent; import wiiusej.wiiusejevents.wiiuseapievents.StatusEvent; public class Opdracht2 extends JFrame { public static void main(String args[]) { JFrame frame = new JFrame("Opdracht 2"); JPanel panel = new Panel(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } public Opdracht2() { } } class Panel extends JPanel implements WiimoteListener, ActionListener { Wiimote[] wiimotes; AccelerationPanel aPanel; Wiimote wiimote; JPanel panel; RawAcceleration rawAcc; float yaw; int x; int y; int z; int xx; int yy; int zz; short time; short oldTime; Timer timer = new Timer(1, this); ArrayList<RawAcceleration> values; Font bigFont; Font smallFont; int xTurns; int zTurns; boolean xTurned; boolean zTurned; public Panel() { xTurned = false; zTurned = false; xTurns = 0; zTurns = 0; yaw = 0; time = 0; oldTime = 0; setPreferredSize(new Dimension(1366, 768)); timer.start(); System.loadLibrary("WiiuseJ"); wiimotes = WiiUseApiManager.getWiimotes(1, false); wiimote = wiimotes[0]; values = new ArrayList<>(); wiimote.activateMotionSensing(); wiimote.addWiiMoteEventListeners(this); aPanel = new AccelerationWiimoteEventPanel(); rawAcc = new RawAcceleration(); values.add(rawAcc); x = 0; y = 0; z = 0; xx = 0; yy = 0; zz = 0; smallFont = new Font("Arial", 0, 10); bigFont = new Font("Arial", 0, 12); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.BLACK); // x lijnen g2.drawLine(0, 163, getWidth(), 163); g2.drawLine(0, 363, getWidth(), 363); g2.drawLine(0, 575, getWidth(), 575); // hulp x lijnen voor x RawAcc g2.setColor(Color.GREEN); g2.drawLine(0, 100, getWidth(), 100); g2.drawLine(0, 137, getWidth(), 137); g2.drawLine(0, 200, getWidth(), 200); // hulp x lijnen voor y RawAcc g2.drawLine(0, 337, getWidth(), 337); g2.drawLine(0, 400, getWidth(), 400); // hulp x lijnen voor z RawAcc g2.drawLine(0, 500, getWidth(), 500); g2.drawLine(0, 550, getWidth(), 550); g2.drawLine(0, 625, getWidth(), 625); // y lijnen g2.setColor(Color.BLACK); for (int yl = 100; yl < 200; yl = yl + 300) { g2.drawLine(yl, 100, yl, 200); g2.drawLine(yl, 337, yl, 400); g2.drawLine(yl, 500, yl, 625); } // font kleiner maken g2.setFont(smallFont); // x waardes for (int xw = 105; xw < 200; xw = xw + 300) { g2.drawString("0", xw, 100); g2.drawString("75", xw, 137); g2.drawString("125", xw, 163); g2.drawString("200", xw, 200); } // y waardes for (int yw = 105; yw < 200; yw = yw + 300) { g2.drawString("75", yw, 337); g2.drawString("125", yw, 363); g2.drawString("200", yw, 400); } // z waardes for (int zw = 105; zw < 200; zw = zw + 300) { g2.drawString("0", zw, 500); g2.drawString("100", zw, 550); g2.drawString("150", zw, 575); g2.drawString("250", zw, 625); } // font groter maken g2.setFont(bigFont); // telkens als er een nieuwe waarde in de arraylist wordt toegevoegd // wordt deze toegevoegd en dus getekend. for (int i = 0; i < values.size() && i < getWidth(); i++) { // Uitlezen van RawAcceleration waarde RawAcceleration r = values.get(i); xx = x; yy = y; zz = z; Short xShort = r.getX(); Short yShort = r.getY(); Short zShort = r.getZ(); x = (int) xShort / 2; y = (int) yShort / 2; z = (int) zShort / 2; // hulp printline voor de waarde niet gedeeld door 2. // System.out.println(xShort + " " + yShort + " " + zShort); // RawAcceleration lijnen voor de x, y en z waarde van de RawAcc g2.setColor(Color.RED); g2.drawString("X lijn", 50, 75); g2.drawString(xTurns + " ", 200, 75); g2.drawLine(i - 1, xx + 100, i, x + 100); g2.setColor(Color.MAGENTA); g2.drawString("Y lijn", 50, 275); g2.drawLine(i - 1, yy + 300, i, y + 300); g2.setColor(Color.BLUE); g2.drawString("Z lijn", 50, 475); g2.drawString(zTurns + " ", 200, 475); g2.drawLine(i - 1, zz + 500, i, z + 500); } System.out.println(xTurns + " " + zTurns); // 95 155, 100 200 RawAcceleration rA = values.get(values.size() - 1); short xShort = rA.getX(); if (xTurned) { if (xShort > 165) { xTurns++; xTurned = false; } } else { if (xShort > 85) { xTurned = true; } } short zShort = rA.getZ(); if (zTurned) { if (zShort > 200) { zTurns++; zTurned = false; } } else { if (zShort > 100) { zTurned = true; } } } @Override public void onButtonsEvent(WiimoteButtonsEvent arg0) { } @Override public void onClassicControllerInsertedEvent(ClassicControllerInsertedEvent arg0) { } @Override public void onClassicControllerRemovedEvent(ClassicControllerRemovedEvent arg0) { } @Override public void onDisconnectionEvent(DisconnectionEvent arg0) { values.clear(); repaint(); } @Override public void onExpansionEvent(ExpansionEvent arg0) { draw(arg0); } @Override public void onGuitarHeroInsertedEvent(GuitarHeroInsertedEvent arg0) { } @Override public void onGuitarHeroRemovedEvent(GuitarHeroRemovedEvent arg0) { } @Override public void onIrEvent(IREvent arg0) { } @Override public void onMotionSensingEvent(MotionSensingEvent arg0) { draw(arg0); } @Override public void onNunchukInsertedEvent(NunchukInsertedEvent arg0) { } @Override public void onNunchukRemovedEvent(NunchukRemovedEvent arg0) { } @Override public void onStatusEvent(StatusEvent arg0) { } private void draw(GenericEvent arg0) { if (values.size() >= getWidth()) { // als de grafiek buiten beeld gaat de waarde verwijderen zodat // de lijn weer vanaf links begint values.clear(); } RawAcceleration rawAcceleration = aPanel.getRawAccelerationValue(arg0); // System.out.println(turns + " " + yaw); if (rawAcceleration != null) { // toevoegen van waarde om te tekenen values.add(rawAcceleration); } repaint(); } @Override public void actionPerformed(ActionEvent arg0) { time++; repaint(); timer.restart(); } }
nlreturns/WiiMote
src/wiimote/Opdracht2.java
3,081
// RawAcceleration lijnen voor de x, y en z waarde van de RawAcc
line_comment
nl
package wiimote; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; import wiiusej.WiiUseApiManager; import wiiusej.Wiimote; import wiiusej.utils.AccelerationPanel; import wiiusej.utils.AccelerationWiimoteEventPanel; import wiiusej.values.RawAcceleration; import wiiusej.wiiusejevents.GenericEvent; import wiiusej.wiiusejevents.physicalevents.ExpansionEvent; import wiiusej.wiiusejevents.physicalevents.IREvent; import wiiusej.wiiusejevents.physicalevents.MotionSensingEvent; import wiiusej.wiiusejevents.physicalevents.WiimoteButtonsEvent; import wiiusej.wiiusejevents.utils.WiimoteListener; import wiiusej.wiiusejevents.wiiuseapievents.ClassicControllerInsertedEvent; import wiiusej.wiiusejevents.wiiuseapievents.ClassicControllerRemovedEvent; import wiiusej.wiiusejevents.wiiuseapievents.DisconnectionEvent; import wiiusej.wiiusejevents.wiiuseapievents.GuitarHeroInsertedEvent; import wiiusej.wiiusejevents.wiiuseapievents.GuitarHeroRemovedEvent; import wiiusej.wiiusejevents.wiiuseapievents.NunchukInsertedEvent; import wiiusej.wiiusejevents.wiiuseapievents.NunchukRemovedEvent; import wiiusej.wiiusejevents.wiiuseapievents.StatusEvent; public class Opdracht2 extends JFrame { public static void main(String args[]) { JFrame frame = new JFrame("Opdracht 2"); JPanel panel = new Panel(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } public Opdracht2() { } } class Panel extends JPanel implements WiimoteListener, ActionListener { Wiimote[] wiimotes; AccelerationPanel aPanel; Wiimote wiimote; JPanel panel; RawAcceleration rawAcc; float yaw; int x; int y; int z; int xx; int yy; int zz; short time; short oldTime; Timer timer = new Timer(1, this); ArrayList<RawAcceleration> values; Font bigFont; Font smallFont; int xTurns; int zTurns; boolean xTurned; boolean zTurned; public Panel() { xTurned = false; zTurned = false; xTurns = 0; zTurns = 0; yaw = 0; time = 0; oldTime = 0; setPreferredSize(new Dimension(1366, 768)); timer.start(); System.loadLibrary("WiiuseJ"); wiimotes = WiiUseApiManager.getWiimotes(1, false); wiimote = wiimotes[0]; values = new ArrayList<>(); wiimote.activateMotionSensing(); wiimote.addWiiMoteEventListeners(this); aPanel = new AccelerationWiimoteEventPanel(); rawAcc = new RawAcceleration(); values.add(rawAcc); x = 0; y = 0; z = 0; xx = 0; yy = 0; zz = 0; smallFont = new Font("Arial", 0, 10); bigFont = new Font("Arial", 0, 12); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.BLACK); // x lijnen g2.drawLine(0, 163, getWidth(), 163); g2.drawLine(0, 363, getWidth(), 363); g2.drawLine(0, 575, getWidth(), 575); // hulp x lijnen voor x RawAcc g2.setColor(Color.GREEN); g2.drawLine(0, 100, getWidth(), 100); g2.drawLine(0, 137, getWidth(), 137); g2.drawLine(0, 200, getWidth(), 200); // hulp x lijnen voor y RawAcc g2.drawLine(0, 337, getWidth(), 337); g2.drawLine(0, 400, getWidth(), 400); // hulp x lijnen voor z RawAcc g2.drawLine(0, 500, getWidth(), 500); g2.drawLine(0, 550, getWidth(), 550); g2.drawLine(0, 625, getWidth(), 625); // y lijnen g2.setColor(Color.BLACK); for (int yl = 100; yl < 200; yl = yl + 300) { g2.drawLine(yl, 100, yl, 200); g2.drawLine(yl, 337, yl, 400); g2.drawLine(yl, 500, yl, 625); } // font kleiner maken g2.setFont(smallFont); // x waardes for (int xw = 105; xw < 200; xw = xw + 300) { g2.drawString("0", xw, 100); g2.drawString("75", xw, 137); g2.drawString("125", xw, 163); g2.drawString("200", xw, 200); } // y waardes for (int yw = 105; yw < 200; yw = yw + 300) { g2.drawString("75", yw, 337); g2.drawString("125", yw, 363); g2.drawString("200", yw, 400); } // z waardes for (int zw = 105; zw < 200; zw = zw + 300) { g2.drawString("0", zw, 500); g2.drawString("100", zw, 550); g2.drawString("150", zw, 575); g2.drawString("250", zw, 625); } // font groter maken g2.setFont(bigFont); // telkens als er een nieuwe waarde in de arraylist wordt toegevoegd // wordt deze toegevoegd en dus getekend. for (int i = 0; i < values.size() && i < getWidth(); i++) { // Uitlezen van RawAcceleration waarde RawAcceleration r = values.get(i); xx = x; yy = y; zz = z; Short xShort = r.getX(); Short yShort = r.getY(); Short zShort = r.getZ(); x = (int) xShort / 2; y = (int) yShort / 2; z = (int) zShort / 2; // hulp printline voor de waarde niet gedeeld door 2. // System.out.println(xShort + " " + yShort + " " + zShort); // RawAcceleration lijnen<SUF> g2.setColor(Color.RED); g2.drawString("X lijn", 50, 75); g2.drawString(xTurns + " ", 200, 75); g2.drawLine(i - 1, xx + 100, i, x + 100); g2.setColor(Color.MAGENTA); g2.drawString("Y lijn", 50, 275); g2.drawLine(i - 1, yy + 300, i, y + 300); g2.setColor(Color.BLUE); g2.drawString("Z lijn", 50, 475); g2.drawString(zTurns + " ", 200, 475); g2.drawLine(i - 1, zz + 500, i, z + 500); } System.out.println(xTurns + " " + zTurns); // 95 155, 100 200 RawAcceleration rA = values.get(values.size() - 1); short xShort = rA.getX(); if (xTurned) { if (xShort > 165) { xTurns++; xTurned = false; } } else { if (xShort > 85) { xTurned = true; } } short zShort = rA.getZ(); if (zTurned) { if (zShort > 200) { zTurns++; zTurned = false; } } else { if (zShort > 100) { zTurned = true; } } } @Override public void onButtonsEvent(WiimoteButtonsEvent arg0) { } @Override public void onClassicControllerInsertedEvent(ClassicControllerInsertedEvent arg0) { } @Override public void onClassicControllerRemovedEvent(ClassicControllerRemovedEvent arg0) { } @Override public void onDisconnectionEvent(DisconnectionEvent arg0) { values.clear(); repaint(); } @Override public void onExpansionEvent(ExpansionEvent arg0) { draw(arg0); } @Override public void onGuitarHeroInsertedEvent(GuitarHeroInsertedEvent arg0) { } @Override public void onGuitarHeroRemovedEvent(GuitarHeroRemovedEvent arg0) { } @Override public void onIrEvent(IREvent arg0) { } @Override public void onMotionSensingEvent(MotionSensingEvent arg0) { draw(arg0); } @Override public void onNunchukInsertedEvent(NunchukInsertedEvent arg0) { } @Override public void onNunchukRemovedEvent(NunchukRemovedEvent arg0) { } @Override public void onStatusEvent(StatusEvent arg0) { } private void draw(GenericEvent arg0) { if (values.size() >= getWidth()) { // als de grafiek buiten beeld gaat de waarde verwijderen zodat // de lijn weer vanaf links begint values.clear(); } RawAcceleration rawAcceleration = aPanel.getRawAccelerationValue(arg0); // System.out.println(turns + " " + yaw); if (rawAcceleration != null) { // toevoegen van waarde om te tekenen values.add(rawAcceleration); } repaint(); } @Override public void actionPerformed(ActionEvent arg0) { time++; repaint(); timer.restart(); } }
True
2,613
18
3,098
19
2,866
17
3,098
19
3,519
20
false
false
false
false
false
true
111
176589_1
package nl.novi.les11docenten.models; import jakarta.persistence.*; import lombok.Data; import java.time.LocalDate; @Entity // // Deze klasse kan vertaald worden naar een tabel in de database. @Table(name = "teachers") // Vul je dit niet in, dan wordt de naam van de tabel hetzelfde als de naam van de klasse @Data // Lombok: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, @Setter on all non-final fields, and @RequiredArgsConstructor. public class Teacher { @Id // Maakt dat dit veld de primary key van de tabel wordt. Uniek. Not null @GeneratedValue // Zorgt er voor dat Hibernate de waarde van ons id zelf bepaald én verhoogd. private Long id; // Wordt bigint, NOT NULL, PRIMARY KEY @Column(name = "first_name") private String firstName; // Wordt first_name, varchar(255). In Postman: firstName private String lastName; private LocalDate dob; // En alle Getters & Setters via (eventueel) Lombok // Wel de benodigde Getters/Setters noteren ivm Postman volledige response van het JSON object. // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public LocalDate getDob() { // return dob; // } // // public void setDob(LocalDate dob) { // this.dob = dob; // } }
Aphelion-im/Les-11-uitwerking-opdracht-docenten
src/main/java/nl/novi/les11docenten/models/Teacher.java
531
// Vul je dit niet in, dan wordt de naam van de tabel hetzelfde als de naam van de klasse
line_comment
nl
package nl.novi.les11docenten.models; import jakarta.persistence.*; import lombok.Data; import java.time.LocalDate; @Entity // // Deze klasse kan vertaald worden naar een tabel in de database. @Table(name = "teachers") // Vul je<SUF> @Data // Lombok: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, @Setter on all non-final fields, and @RequiredArgsConstructor. public class Teacher { @Id // Maakt dat dit veld de primary key van de tabel wordt. Uniek. Not null @GeneratedValue // Zorgt er voor dat Hibernate de waarde van ons id zelf bepaald én verhoogd. private Long id; // Wordt bigint, NOT NULL, PRIMARY KEY @Column(name = "first_name") private String firstName; // Wordt first_name, varchar(255). In Postman: firstName private String lastName; private LocalDate dob; // En alle Getters & Setters via (eventueel) Lombok // Wel de benodigde Getters/Setters noteren ivm Postman volledige response van het JSON object. // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public LocalDate getDob() { // return dob; // } // // public void setDob(LocalDate dob) { // this.dob = dob; // } }
True
421
24
501
28
466
21
501
28
532
27
false
false
false
false
false
true
4,110
133854_0
package vechterspel.ui; import vechterspel.domain.*; public class SpelUI { public static void main(String[] args) { Spel spel = new Spel(); //voeg actoren toe aan spel try { spel.voegActortoe(new Elf("elfje")); spel.voegActortoe(new Elf("twaalfje")); spel.voegActortoe(new Rover("elfje", 200)); spel.voegActortoe(new Rover("Maurice", 300)); spel.voegActortoe(new Rover("Lowie", 4000)); spel.voegActortoe(new Rover("Twan", 500)); spel.voegActortoe(new Rover("Jakke", 200, 2000)); spel.voegActortoe(new Vampier("Toon", 300)); spel.voegActortoe(new Vampier("Uno", 300, 1500)); spel.voegActortoe(new Vampier("Dos", 50)); } catch (DomainException e) {System.out.println(e.getMessage());} System.out.println("Actoren in spel\n"+spel); //speel spel for (int i = 1; i <= 10; i++) { // get random vechter Vechter aanvaller = spel.getRandomVechter(); if (aanvaller == null) break; // get random tegenstander Actor tegenstander = spel.getRandomActor(aanvaller); if (tegenstander == null) break; // aanvaller valt tegenstander aan try{ System.out.println("-----------------------------------------------------"); System.out.println("🎲 Round " + i); System.out.println(aanvaller + " \nvs\n" + tegenstander); spel.valAan(aanvaller,tegenstander); } catch (DomainException e) { System.out.println(e.getMessage()); } } System.out.println("-----------------------------------------------------"); System.out.println("Actoren in spel\n" + spel); System.out.println("Aantal levende vechters na aanvallen: " + spel.getLevendeVechters().size()); spel.reincarneerDodeActoren(); System.out.println("Aantal levende vechters na reincarnatie: " + spel.getLevendeVechters().size()); } }
randmon/ucl_ti_ooo
labo0/src/vechterspel/ui/SpelUI.java
676
//voeg actoren toe aan spel
line_comment
nl
package vechterspel.ui; import vechterspel.domain.*; public class SpelUI { public static void main(String[] args) { Spel spel = new Spel(); //voeg actoren<SUF> try { spel.voegActortoe(new Elf("elfje")); spel.voegActortoe(new Elf("twaalfje")); spel.voegActortoe(new Rover("elfje", 200)); spel.voegActortoe(new Rover("Maurice", 300)); spel.voegActortoe(new Rover("Lowie", 4000)); spel.voegActortoe(new Rover("Twan", 500)); spel.voegActortoe(new Rover("Jakke", 200, 2000)); spel.voegActortoe(new Vampier("Toon", 300)); spel.voegActortoe(new Vampier("Uno", 300, 1500)); spel.voegActortoe(new Vampier("Dos", 50)); } catch (DomainException e) {System.out.println(e.getMessage());} System.out.println("Actoren in spel\n"+spel); //speel spel for (int i = 1; i <= 10; i++) { // get random vechter Vechter aanvaller = spel.getRandomVechter(); if (aanvaller == null) break; // get random tegenstander Actor tegenstander = spel.getRandomActor(aanvaller); if (tegenstander == null) break; // aanvaller valt tegenstander aan try{ System.out.println("-----------------------------------------------------"); System.out.println("🎲 Round " + i); System.out.println(aanvaller + " \nvs\n" + tegenstander); spel.valAan(aanvaller,tegenstander); } catch (DomainException e) { System.out.println(e.getMessage()); } } System.out.println("-----------------------------------------------------"); System.out.println("Actoren in spel\n" + spel); System.out.println("Aantal levende vechters na aanvallen: " + spel.getLevendeVechters().size()); spel.reincarneerDodeActoren(); System.out.println("Aantal levende vechters na reincarnatie: " + spel.getLevendeVechters().size()); } }
True
571
8
668
9
611
8
668
9
760
8
false
false
false
false
false
true
3,925
142834_1
package net.rhizomik.rhizomer.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.net.*; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.persistence.CascadeType; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import lombok.Data; import net.rhizomik.rhizomer.service.Queries.QueryType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by http://rhizomik.net/~roberto/ */ @Entity @Data public class Dataset { private static final Logger logger = LoggerFactory.getLogger(Dataset.class); @Id private String id; private QueryType queryType = QueryType.OPTIMIZED; private boolean inferenceEnabled = false; private int sampleSize = 0; private double coverage = 0.0; private boolean isPublic = false; @ElementCollection private Set<String> datasetOntologies = new HashSet<>(); @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "dataset", cascade = CascadeType.ALL) @OrderBy("instanceCount DESC") private List<Class> classes = new ArrayList<>(); private String owner; public Dataset() {} public Dataset(String id) { this.id = id; } public Dataset(String id, Set<String> ontologies) throws MalformedURLException { this.id = id; this.datasetOntologies = ontologies; } @JsonIgnore public List<Class> getClasses() { return new ArrayList<>(classes); } public List<Class> getClasses(int top) { int max = Integer.min(top, classes.size()); return new ArrayList<>(classes.subList(0, max)); } public List<Class> getClassesContaining(String containing) { return getClassesContaining(containing, -1); } public List<Class> getClassesContaining(String containing, int top) { Stream<Class> selected = classes.stream(); if (!containing.isEmpty()) selected = classes.stream() .filter(c -> c.getUri().toString().toLowerCase().contains(containing.toLowerCase()) || c.getLabel().toLowerCase().contains(containing.toLowerCase())); if (top >= 0) selected = selected.sorted(Comparator.comparingInt(Class::getInstanceCount).reversed()).limit(top); return selected.collect(Collectors.toList()); } public void setClasses(List<Class> classes) { this.classes.clear(); this.classes.addAll(classes); } public void addClass(Class aClass) { classes.add(aClass); } public void removeClass(Class aClass) { classes.remove(aClass); } public void addDatasetOntology(String ontology) { this.datasetOntologies.add(ontology); } @JsonIgnore public List<String> getDatasetOntologies() { return new ArrayList<>(datasetOntologies); } public void setDatasetOntologies(Set<String> datasetOntologies) { this.datasetOntologies = datasetOntologies; } @JsonIgnore public URI getDatasetUri() { URI datasetURI = null; try { datasetURI = new URI("http://" + InetAddress.getLocalHost().getHostName() + "/dataset/"+getId()); } catch (Exception e) { logger.error(e.getMessage()); } return datasetURI; } @JsonIgnore public URI getDatasetOntologiesGraph() { URI datasetOntologiesGraphURI = null; try { datasetOntologiesGraphURI = new URI(getDatasetUri()+"/ontologies"); } catch (URISyntaxException e) { logger.error(e.getMessage()); } return datasetOntologiesGraphURI; } @JsonIgnore public URI getDatasetInferenceGraph() { URI datasetInferenceGraphURI = null; try { datasetInferenceGraphURI = new URI(getDatasetUri()+"/inference"); } catch (URISyntaxException e) { logger.error(e.getMessage()); } return datasetInferenceGraphURI; } }
oriolaguilar/rhizomerAPI
src/main/java/net/rhizomik/rhizomer/model/Dataset.java
1,207
//" + InetAddress.getLocalHost().getHostName() + "/dataset/"+getId());
line_comment
nl
package net.rhizomik.rhizomer.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.net.*; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.persistence.CascadeType; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import lombok.Data; import net.rhizomik.rhizomer.service.Queries.QueryType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by http://rhizomik.net/~roberto/ */ @Entity @Data public class Dataset { private static final Logger logger = LoggerFactory.getLogger(Dataset.class); @Id private String id; private QueryType queryType = QueryType.OPTIMIZED; private boolean inferenceEnabled = false; private int sampleSize = 0; private double coverage = 0.0; private boolean isPublic = false; @ElementCollection private Set<String> datasetOntologies = new HashSet<>(); @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "dataset", cascade = CascadeType.ALL) @OrderBy("instanceCount DESC") private List<Class> classes = new ArrayList<>(); private String owner; public Dataset() {} public Dataset(String id) { this.id = id; } public Dataset(String id, Set<String> ontologies) throws MalformedURLException { this.id = id; this.datasetOntologies = ontologies; } @JsonIgnore public List<Class> getClasses() { return new ArrayList<>(classes); } public List<Class> getClasses(int top) { int max = Integer.min(top, classes.size()); return new ArrayList<>(classes.subList(0, max)); } public List<Class> getClassesContaining(String containing) { return getClassesContaining(containing, -1); } public List<Class> getClassesContaining(String containing, int top) { Stream<Class> selected = classes.stream(); if (!containing.isEmpty()) selected = classes.stream() .filter(c -> c.getUri().toString().toLowerCase().contains(containing.toLowerCase()) || c.getLabel().toLowerCase().contains(containing.toLowerCase())); if (top >= 0) selected = selected.sorted(Comparator.comparingInt(Class::getInstanceCount).reversed()).limit(top); return selected.collect(Collectors.toList()); } public void setClasses(List<Class> classes) { this.classes.clear(); this.classes.addAll(classes); } public void addClass(Class aClass) { classes.add(aClass); } public void removeClass(Class aClass) { classes.remove(aClass); } public void addDatasetOntology(String ontology) { this.datasetOntologies.add(ontology); } @JsonIgnore public List<String> getDatasetOntologies() { return new ArrayList<>(datasetOntologies); } public void setDatasetOntologies(Set<String> datasetOntologies) { this.datasetOntologies = datasetOntologies; } @JsonIgnore public URI getDatasetUri() { URI datasetURI = null; try { datasetURI = new URI("http://" +<SUF> } catch (Exception e) { logger.error(e.getMessage()); } return datasetURI; } @JsonIgnore public URI getDatasetOntologiesGraph() { URI datasetOntologiesGraphURI = null; try { datasetOntologiesGraphURI = new URI(getDatasetUri()+"/ontologies"); } catch (URISyntaxException e) { logger.error(e.getMessage()); } return datasetOntologiesGraphURI; } @JsonIgnore public URI getDatasetInferenceGraph() { URI datasetInferenceGraphURI = null; try { datasetInferenceGraphURI = new URI(getDatasetUri()+"/inference"); } catch (URISyntaxException e) { logger.error(e.getMessage()); } return datasetInferenceGraphURI; } }
False
854
15
995
18
1,046
17
995
18
1,192
23
false
false
false
false
false
true
1,777
23982_6
package com.enklave.game.Utils; public class NameFiles { private static String prefix = "Images/"; //intro public static final String intro_sprite_enklave_logo = prefix +"sprite-enklave-glitch-logo.png"; public static final String intro_sprite_enklave = prefix +"sprite-glitch-enklave-intro.png"; public static final String intro_logo_center = prefix + "enklave-icon-btn2.png"; //button control background public static final String buttonLeft = prefix + "buttonLeft.png"; public static final String buttonRight = prefix + "Button_Right.png"; public static final String buttontwoLeft = prefix + "left-two-image.png"; public static final String button_describe = prefix +"button_gold_describe_screen.png"; public static final String logoEnklave = prefix + "enklave-icon-btn-circ.png"; // public static final String buttonBac = prefix + "back-button.png"; public static final String buttonBack1 = prefix + "back_button1.png"; public static final String buttonShowEnklave = prefix + "buttonShow.png"; public static final String imageInformationEnklave = prefix + "tooltip-friendly-blue.png"; public static final String buttonTabCraft = prefix + "buttonmenu.png"; public static final String buttonMinusCraft = prefix + "butonminus.png"; public static final String buttonPlusCraft = prefix + "butonplus.png"; public static final String cursorTextField = prefix + "cursor_text_input.png"; public static final String disaibleButton = prefix + "disaibleButton.png"; //screen Loading normal public static final String loadoverlayshape = prefix + "loading-overlay-shape.png"; public static final String loadtransientred = prefix + "loading-transient2red2.jpg"; public static final String loadtransientgreen = prefix + "loading-transient2green2.jpg"; public static final String loadtransientblue = prefix + "loading-transient2blue2.jpg"; public static final String logoTextENKLAVE = prefix + "logo.png"; //screen circle loading public static final String loadingCircle = prefix + "loadingCircle.png"; //maps public static final String imgPossition = prefix +"arrowblue.png"; //"icon_navigation.png"; public static final String imgCirclePos = prefix + "circle-pos.png"; public static final String buttonChat = prefix + "btn_fab_chat.png"; public static final String buttoncrafting = prefix + "btn_fab_menu.png"; public static final String imageFactionArhitects = prefix + "architects-logo.png"; public static final String imageFactionEdenites = prefix + "logo-edenites.png"; public static final String imageFactionPrometheans = prefix + "logo-prometheans.png"; //tutorial public static final String tutorialProfile = prefix + "tooltip-your-profile-cu-text.png"; public static final String tutorialComm = prefix + "tooltip-the-comm-simplu.png"; public static final String tutorialCrafting = prefix + "tooltip-this-one-is-up-to-you-simplu.png"; public static final String tutorialScrap = prefix + "tooltip-go-to-scrap-simplu.png"; public static final String tutorialEnergy = prefix + "tooltip-your-energy.png"; public static final String circlePulsTutorial = prefix + "your-profile-touch-this-area.png"; public static final String logoHeader = prefix + "logo-header1.png"; public static final String labeltextfollow = prefix + "Label-Follow.png"; public static final String PulsCircleScalable = prefix + "circleScalable.png"; //cursor Position public static final String CursorPositionBlue = prefix + "arrowblue.png"; public static final String CursorPositionGreen = prefix + "arrowgreen.png"; public static final String CursorPositionRed = prefix + "arrowred.png"; //profile // public static final String profileObject = "Object3D/Character/Character.obj"; public static final String profileObject = "Object3D/Defender/defender.g3db"; public static final String enklave3D = "Object3D/fbx.g3db";//"Object3D/EnklaveModel/siglaenklave02.g3db"; public static final String backgroundScroll = prefix + "backgroundScroll.png"; //enklave 3D public static final String enklaveBlue3D = "Object3D/EnklaveModel/BlueEnklave/blueenklave.g3db"; public static final String enklaveRed3D = "Object3D/EnklaveModel/RedEnklave/redenklave.g3db"; public static final String enklaveGreen3D = "Object3D/EnklaveModel/GreenEnklave/greenenklave.g3db"; public static final String enklaveGrey3D = "Object3D/EnklaveModel/GreyEnklave/greyenklave.g3db"; //lofo faction public static final String logoArhitects3D = "Object3D/LogoFaction/Arhitects/sigla1.g3db"; public static final String logoPrometheans3D = "Object3D/LogoFaction/Prometheans/sigla3.g3db"; public static final String logoEdenites3D = "Object3D/LogoFaction/Edenites/sigla2.g3db"; public static final String suport3D = "Object3D/Crafting/Suport/postamentresurse.g3db"; //crafting modele 3D public static final String cellModel3D = "Object3D/Crafting/cellanim/modelCELL3D.g3db"; public static final String scrapModel3D = "Object3D/Crafting/scrap/scrap3d.g3db"; public static final String brickModel3D = "Object3D/Crafting/Brick/brick.g3db"; //crafting public static final String backgroundCrafting = prefix + "backgroundCrafting.png"; public static final String backgroundModel3d = prefix + "backgroundmodel3D.png"; public static final String buttonCraft = prefix + "butoncraft.png"; public static final String backgroundbuttoncreft = prefix + "backgroundbuton.png"; public static final String arrowcrafting = prefix + "sageata.png"; //ENKLAVE 3D public static final String baseEnklave3D = prefix + "enklava-lvl_base_motion_ray.png"; public static final String insideEnklave = prefix + "enkl-ettage-blue.png"; public static final String topEnklave3D = prefix + "enkl--brick-lvl-upbar-blue.png"; public static final String circleEnklave = prefix + "circle.png"; //describe Enklave public static final String backDeployBricks = prefix + "backDeployBricks.png"; public static final String buttonExtendCollapse = prefix + "button_expand_colapse.png"; public static final String frameEnk = prefix + "room-type-selection-bg-extend.png"; public static final String profileButtonimage = prefix + "architects-logo.png"; public static final String buttonViewGallery = prefix + "view-enklave-galery.png"; public static final String buttonFavoriteEnklave = prefix + "add-to-favorites.png"; public static final String proportionEnklave = prefix + "enklave-rooms-pie.png"; public static final String cornerBG = prefix + "extension-cross-lines-bg.png"; //rooms public static final String imageBarrack = prefix + "barrack.png"; public static final String imageLaboratory = prefix + "laboratory.png"; public static final String imageCommCenter = prefix + "commcenter.png"; //extensions public static final String imageExtensionAutoTurret = prefix + "turret-extension-img.jpg"; public static final String imageExtensionRemoteTurret = prefix + "remote-turret-extension-img.jpg"; public static final String imageExtensionGammaShield = prefix + "gamma-shield-extension-img.jpg"; public static final String imageExtensionRegularShield = prefix + "shield-extension-img.jpg"; //screen extension public static final String frameCarousel = prefix + "extension-bg.png"; public static final String imageArrowRight = prefix + "right-arrow-icon-btn.png"; public static final String imageArrowBottom = prefix + "down-gold-arrow.png"; public static final String txtSelectExtension = prefix + "title-select-extension-slot.png"; public static final String imagePulse = prefix + "circle puls.png"; public static final String extensionImgBackground = prefix + "room-type-items-box-bg.png"; public static final String leftselectextension = prefix + "extension-slots-selected-left.png"; public static final String rightselectextension = prefix + "extension-slots-selected-right.png"; public static final String bottomselectextension = prefix + "extension-slots-selected-bottom.png"; public static final String centerselectextension = prefix + "extension-slots-selected-center.png"; public static final String noselectextension = prefix + "extension-slots-all-empty.png"; public static final String topenklaveimage = prefix + "enklava-lvl_base_fixed2.png"; public static final String progressbarcircular = prefix + "progressbarcircle.png"; //screen Rooms public static final String selectroomleft = prefix +"room-select-top-left.png"; public static final String selectroomright = prefix +"room-select-top-right.png"; public static final String selectroombottom = prefix +"room-select-bottom.png"; public static final String noselectRooms = prefix +"room-slots-top.png"; public static final String txtSelectRoom = prefix +"title-select-room-to-configure.png"; public static final String borderImageBlue = prefix +"border-fade-in-blue.png"; public static final String borderUpdown = prefix + "room-type-selection-pluses.png"; //screen combat public final static String setCombat = prefix + "pass-btn.png"; public final static String labelCombat = prefix + "LabelCombat.png"; public final static String framePlayers = prefix + "FramePlayer.png"; public final static String framedefender = prefix + "FramePlayerDefender.png"; public final static String frameattachers = prefix + "FramePlayeratactor.png"; public final static String imgplayerBlue = prefix + "playerBlue.png"; public final static String imgplayerGreen = prefix + "playerGreen.png"; public final static String imgplayerRed = prefix + "playerRed.png"; public final static String barLifeWhite = prefix + "enklave_tooltip_energy_bar_White.png"; public static final String enklaveblue = prefix + "enkl_blue.png"; public static final String enklavegreen = prefix + "enkl_green.png"; public static final String enklavered = prefix + "enkl_red.png"; public static final String brickLoader = prefix + "brick_loader.png"; public static final String maskLoader = prefix + "loader_mask.png"; public static final String turretsimpleCombat = prefix + "turret_combat.png"; public static final String target = prefix + "target.png"; public static final String targetRecharge = prefix + "target_recharge.png"; public static final String buttonFire = prefix + "fire.png"; public static final String buttonRecharge = prefix + "recharge.png"; public static final String buttonStartCombat = prefix + "buttonStartCombat.png"; //screen bricks public static final String bricksMaps = prefix + "map-3d-enkl-blue-alpha-vector1.jpg"; //screen setting public static final String buttonSwith = prefix + "switch.png"; //screen CHOOSE FACTION public static final String labelEdenites = prefix + "choose-faction_0003_Edenites.png"; public static final String labelPrometheans = prefix + "choose-faction_0009_Prometheans.png"; public static final String labelArhitects = prefix + "choose-faction_0008_Architects.png"; public static final String txtDescribeEdenites = prefix + "choose-faction_0004_You-aim-to-be-part-of-a-super-organism-composed-of-all-of-Earth.png"; public static final String txtDescribePrometheans = prefix + "choose-faction_0006_Self-determination-is-what-makes-us-human!-Society-functioned-j.png"; public static final String txtDescribeArhitects = prefix + "choose-faction_0005_You-are-certain-that-humans-emotions-stand-in-the-way-of-effici.png"; public static final String labelTitle = prefix + "choose-faction_0007_Choose-your-faction.png"; public static final String frameSelected = prefix + "choose-faction_0010_selection-viewing-mode-intro.png"; //Raider public static final String raiderMap = "Object3D/Raider/RaiderMap/RAIDER.g3db"; public static final String raiderFull = "Object3D/Raider/RaiderFull/raider.g3db"; //queue actions public static final String btnfadeaction = prefix + "buttonfadein.png"; public static final String btnStopaction = prefix +"stopBtnQueue.png"; public static final String iconfinishaction = prefix + "iconfinishaction.png"; public static final String iconcurrentaction = prefix + "iconcurrentaction.png"; public static final String iconnextaction = prefix + "iconnextaction.png"; public static final String queuebackFadein = prefix + "buttonwindow.png"; //chat screen public static final String btnchatfadein = prefix + "buttonuser.png"; public static final String btnchatfadeout = prefix + "buttonback.png"; public static final String btnchatsend = prefix + "buttonsend.png"; public static final String backgroundchat = prefix + "buttonscris.png"; public static final String btnchattabmenu = prefix + "buttonsocial.png"; public static final String backgroundchattop = prefix + "guisus.png"; public static final String backgroundchatmiddle = prefix + "GUImid.png"; public static final String backgroundchatbottom = prefix + "GUibot (2).png"; }
TudorRosca/enklave
core/src/com/enklave/game/Utils/NameFiles.java
3,789
//screen CHOOSE FACTION
line_comment
nl
package com.enklave.game.Utils; public class NameFiles { private static String prefix = "Images/"; //intro public static final String intro_sprite_enklave_logo = prefix +"sprite-enklave-glitch-logo.png"; public static final String intro_sprite_enklave = prefix +"sprite-glitch-enklave-intro.png"; public static final String intro_logo_center = prefix + "enklave-icon-btn2.png"; //button control background public static final String buttonLeft = prefix + "buttonLeft.png"; public static final String buttonRight = prefix + "Button_Right.png"; public static final String buttontwoLeft = prefix + "left-two-image.png"; public static final String button_describe = prefix +"button_gold_describe_screen.png"; public static final String logoEnklave = prefix + "enklave-icon-btn-circ.png"; // public static final String buttonBac = prefix + "back-button.png"; public static final String buttonBack1 = prefix + "back_button1.png"; public static final String buttonShowEnklave = prefix + "buttonShow.png"; public static final String imageInformationEnklave = prefix + "tooltip-friendly-blue.png"; public static final String buttonTabCraft = prefix + "buttonmenu.png"; public static final String buttonMinusCraft = prefix + "butonminus.png"; public static final String buttonPlusCraft = prefix + "butonplus.png"; public static final String cursorTextField = prefix + "cursor_text_input.png"; public static final String disaibleButton = prefix + "disaibleButton.png"; //screen Loading normal public static final String loadoverlayshape = prefix + "loading-overlay-shape.png"; public static final String loadtransientred = prefix + "loading-transient2red2.jpg"; public static final String loadtransientgreen = prefix + "loading-transient2green2.jpg"; public static final String loadtransientblue = prefix + "loading-transient2blue2.jpg"; public static final String logoTextENKLAVE = prefix + "logo.png"; //screen circle loading public static final String loadingCircle = prefix + "loadingCircle.png"; //maps public static final String imgPossition = prefix +"arrowblue.png"; //"icon_navigation.png"; public static final String imgCirclePos = prefix + "circle-pos.png"; public static final String buttonChat = prefix + "btn_fab_chat.png"; public static final String buttoncrafting = prefix + "btn_fab_menu.png"; public static final String imageFactionArhitects = prefix + "architects-logo.png"; public static final String imageFactionEdenites = prefix + "logo-edenites.png"; public static final String imageFactionPrometheans = prefix + "logo-prometheans.png"; //tutorial public static final String tutorialProfile = prefix + "tooltip-your-profile-cu-text.png"; public static final String tutorialComm = prefix + "tooltip-the-comm-simplu.png"; public static final String tutorialCrafting = prefix + "tooltip-this-one-is-up-to-you-simplu.png"; public static final String tutorialScrap = prefix + "tooltip-go-to-scrap-simplu.png"; public static final String tutorialEnergy = prefix + "tooltip-your-energy.png"; public static final String circlePulsTutorial = prefix + "your-profile-touch-this-area.png"; public static final String logoHeader = prefix + "logo-header1.png"; public static final String labeltextfollow = prefix + "Label-Follow.png"; public static final String PulsCircleScalable = prefix + "circleScalable.png"; //cursor Position public static final String CursorPositionBlue = prefix + "arrowblue.png"; public static final String CursorPositionGreen = prefix + "arrowgreen.png"; public static final String CursorPositionRed = prefix + "arrowred.png"; //profile // public static final String profileObject = "Object3D/Character/Character.obj"; public static final String profileObject = "Object3D/Defender/defender.g3db"; public static final String enklave3D = "Object3D/fbx.g3db";//"Object3D/EnklaveModel/siglaenklave02.g3db"; public static final String backgroundScroll = prefix + "backgroundScroll.png"; //enklave 3D public static final String enklaveBlue3D = "Object3D/EnklaveModel/BlueEnklave/blueenklave.g3db"; public static final String enklaveRed3D = "Object3D/EnklaveModel/RedEnklave/redenklave.g3db"; public static final String enklaveGreen3D = "Object3D/EnklaveModel/GreenEnklave/greenenklave.g3db"; public static final String enklaveGrey3D = "Object3D/EnklaveModel/GreyEnklave/greyenklave.g3db"; //lofo faction public static final String logoArhitects3D = "Object3D/LogoFaction/Arhitects/sigla1.g3db"; public static final String logoPrometheans3D = "Object3D/LogoFaction/Prometheans/sigla3.g3db"; public static final String logoEdenites3D = "Object3D/LogoFaction/Edenites/sigla2.g3db"; public static final String suport3D = "Object3D/Crafting/Suport/postamentresurse.g3db"; //crafting modele 3D public static final String cellModel3D = "Object3D/Crafting/cellanim/modelCELL3D.g3db"; public static final String scrapModel3D = "Object3D/Crafting/scrap/scrap3d.g3db"; public static final String brickModel3D = "Object3D/Crafting/Brick/brick.g3db"; //crafting public static final String backgroundCrafting = prefix + "backgroundCrafting.png"; public static final String backgroundModel3d = prefix + "backgroundmodel3D.png"; public static final String buttonCraft = prefix + "butoncraft.png"; public static final String backgroundbuttoncreft = prefix + "backgroundbuton.png"; public static final String arrowcrafting = prefix + "sageata.png"; //ENKLAVE 3D public static final String baseEnklave3D = prefix + "enklava-lvl_base_motion_ray.png"; public static final String insideEnklave = prefix + "enkl-ettage-blue.png"; public static final String topEnklave3D = prefix + "enkl--brick-lvl-upbar-blue.png"; public static final String circleEnklave = prefix + "circle.png"; //describe Enklave public static final String backDeployBricks = prefix + "backDeployBricks.png"; public static final String buttonExtendCollapse = prefix + "button_expand_colapse.png"; public static final String frameEnk = prefix + "room-type-selection-bg-extend.png"; public static final String profileButtonimage = prefix + "architects-logo.png"; public static final String buttonViewGallery = prefix + "view-enklave-galery.png"; public static final String buttonFavoriteEnklave = prefix + "add-to-favorites.png"; public static final String proportionEnklave = prefix + "enklave-rooms-pie.png"; public static final String cornerBG = prefix + "extension-cross-lines-bg.png"; //rooms public static final String imageBarrack = prefix + "barrack.png"; public static final String imageLaboratory = prefix + "laboratory.png"; public static final String imageCommCenter = prefix + "commcenter.png"; //extensions public static final String imageExtensionAutoTurret = prefix + "turret-extension-img.jpg"; public static final String imageExtensionRemoteTurret = prefix + "remote-turret-extension-img.jpg"; public static final String imageExtensionGammaShield = prefix + "gamma-shield-extension-img.jpg"; public static final String imageExtensionRegularShield = prefix + "shield-extension-img.jpg"; //screen extension public static final String frameCarousel = prefix + "extension-bg.png"; public static final String imageArrowRight = prefix + "right-arrow-icon-btn.png"; public static final String imageArrowBottom = prefix + "down-gold-arrow.png"; public static final String txtSelectExtension = prefix + "title-select-extension-slot.png"; public static final String imagePulse = prefix + "circle puls.png"; public static final String extensionImgBackground = prefix + "room-type-items-box-bg.png"; public static final String leftselectextension = prefix + "extension-slots-selected-left.png"; public static final String rightselectextension = prefix + "extension-slots-selected-right.png"; public static final String bottomselectextension = prefix + "extension-slots-selected-bottom.png"; public static final String centerselectextension = prefix + "extension-slots-selected-center.png"; public static final String noselectextension = prefix + "extension-slots-all-empty.png"; public static final String topenklaveimage = prefix + "enklava-lvl_base_fixed2.png"; public static final String progressbarcircular = prefix + "progressbarcircle.png"; //screen Rooms public static final String selectroomleft = prefix +"room-select-top-left.png"; public static final String selectroomright = prefix +"room-select-top-right.png"; public static final String selectroombottom = prefix +"room-select-bottom.png"; public static final String noselectRooms = prefix +"room-slots-top.png"; public static final String txtSelectRoom = prefix +"title-select-room-to-configure.png"; public static final String borderImageBlue = prefix +"border-fade-in-blue.png"; public static final String borderUpdown = prefix + "room-type-selection-pluses.png"; //screen combat public final static String setCombat = prefix + "pass-btn.png"; public final static String labelCombat = prefix + "LabelCombat.png"; public final static String framePlayers = prefix + "FramePlayer.png"; public final static String framedefender = prefix + "FramePlayerDefender.png"; public final static String frameattachers = prefix + "FramePlayeratactor.png"; public final static String imgplayerBlue = prefix + "playerBlue.png"; public final static String imgplayerGreen = prefix + "playerGreen.png"; public final static String imgplayerRed = prefix + "playerRed.png"; public final static String barLifeWhite = prefix + "enklave_tooltip_energy_bar_White.png"; public static final String enklaveblue = prefix + "enkl_blue.png"; public static final String enklavegreen = prefix + "enkl_green.png"; public static final String enklavered = prefix + "enkl_red.png"; public static final String brickLoader = prefix + "brick_loader.png"; public static final String maskLoader = prefix + "loader_mask.png"; public static final String turretsimpleCombat = prefix + "turret_combat.png"; public static final String target = prefix + "target.png"; public static final String targetRecharge = prefix + "target_recharge.png"; public static final String buttonFire = prefix + "fire.png"; public static final String buttonRecharge = prefix + "recharge.png"; public static final String buttonStartCombat = prefix + "buttonStartCombat.png"; //screen bricks public static final String bricksMaps = prefix + "map-3d-enkl-blue-alpha-vector1.jpg"; //screen setting public static final String buttonSwith = prefix + "switch.png"; //screen CHOOSE<SUF> public static final String labelEdenites = prefix + "choose-faction_0003_Edenites.png"; public static final String labelPrometheans = prefix + "choose-faction_0009_Prometheans.png"; public static final String labelArhitects = prefix + "choose-faction_0008_Architects.png"; public static final String txtDescribeEdenites = prefix + "choose-faction_0004_You-aim-to-be-part-of-a-super-organism-composed-of-all-of-Earth.png"; public static final String txtDescribePrometheans = prefix + "choose-faction_0006_Self-determination-is-what-makes-us-human!-Society-functioned-j.png"; public static final String txtDescribeArhitects = prefix + "choose-faction_0005_You-are-certain-that-humans-emotions-stand-in-the-way-of-effici.png"; public static final String labelTitle = prefix + "choose-faction_0007_Choose-your-faction.png"; public static final String frameSelected = prefix + "choose-faction_0010_selection-viewing-mode-intro.png"; //Raider public static final String raiderMap = "Object3D/Raider/RaiderMap/RAIDER.g3db"; public static final String raiderFull = "Object3D/Raider/RaiderFull/raider.g3db"; //queue actions public static final String btnfadeaction = prefix + "buttonfadein.png"; public static final String btnStopaction = prefix +"stopBtnQueue.png"; public static final String iconfinishaction = prefix + "iconfinishaction.png"; public static final String iconcurrentaction = prefix + "iconcurrentaction.png"; public static final String iconnextaction = prefix + "iconnextaction.png"; public static final String queuebackFadein = prefix + "buttonwindow.png"; //chat screen public static final String btnchatfadein = prefix + "buttonuser.png"; public static final String btnchatfadeout = prefix + "buttonback.png"; public static final String btnchatsend = prefix + "buttonsend.png"; public static final String backgroundchat = prefix + "buttonscris.png"; public static final String btnchattabmenu = prefix + "buttonsocial.png"; public static final String backgroundchattop = prefix + "guisus.png"; public static final String backgroundchatmiddle = prefix + "GUImid.png"; public static final String backgroundchatbottom = prefix + "GUibot (2).png"; }
False
3,141
6
3,438
7
3,547
5
3,438
7
3,764
8
false
false
false
false
false
true
4,252
126156_0
public class ArchiveerContractUseCaseHandler implements UseCaseHandler<ArchiveerContractUseCase> { private readonly Mediator mediator; public ArchiveerContractUseCase(Mediator mediator) { this.mediator = mediator; } public void handle(RegistreerVerkoopUseCase useCase) { var aanvraag = mediator.ask(new GeefBorgstellingAanvraag(useCase.borgstellingId)); var maakContract = new MaakContract(); maakContract.BorgstellingId = aanvraag.BorgstellingId; maakContract.Kenmerk = aanvraag.Kenmerk; maakContractv.Bedrag = aanvraag.BrutoKredietsom; maakContract.Datum = new Date(); maakContract.EindDatum = port.Datum.plusMonths(36); maakContract.Kredietbank = aanvraag.Kredietbank; var contract = mediator.ask(maakContract); var archiveerDocument = new ArchiveerBorgstellingDocument(); archiveerDocument.DocumentId = useCase.ContractId; archiveerDocument.KredietbankId = aanvraag.KredietbankId; archiveerDocument.Onderwerp = String.format("Borgstelling contract %s met kenmerk %s.", aanvraag.BorgstellingId, aanvraag.Kenmerk); archiveerDocument.VerlooptOp = port.Datum.plusYears(7); archiveerDocument.Kenmerken = [ aanvraag.BorgstellingId, "Borgstelling contract", aanvraag.KredietbankId, aanvraag.Kenmerk ]; archiveerDocument.Bestand = new Bestand(); archiveerDocument.Bestand.Naam = String.format("borgstelling-contract-%s.pdf", aanvraag.BorgstellingId);; archiveerDocument.Bestand.Data = contract.toBase64String(); mediator.send(archiveerDocument); } } public class ExactService implements PortHandler<ArchiveerBorgstellingDocument> { private readonly ExactApi api; public ExactService(ExactApi api) { this.api = api; } public void handle(RegistreerVerkoop port) { var accountId = api.getAccountId(port.KredietbankId); const document = new Document(); document.ID = port.DocumentId; document.Account = accountId; document.Subject = port.Omschrijving; document.ExpiryDate = port.VerlooptOp; //TODO: uitzoeken hoe kenmerken toe te voegen? api.createDocument(document); const documentAttachment = new DocumentAttachment(); documentAttachment.Attachment = port.Bestand.Data; documentAttachment.Document = port.DocumentId; documentAttachment.FileName = port.Bestand.Naam; api.createDocumentAttachment(documentAttachment); } }
sbnnl/documentatie
docs/100_producten/100_borgstelling/010_aanvragen-borgstelling/010_afhandelen-aanvraag-borgstelling/ArchiveerContractUseCase.java
794
//TODO: uitzoeken hoe kenmerken toe te voegen?
line_comment
nl
public class ArchiveerContractUseCaseHandler implements UseCaseHandler<ArchiveerContractUseCase> { private readonly Mediator mediator; public ArchiveerContractUseCase(Mediator mediator) { this.mediator = mediator; } public void handle(RegistreerVerkoopUseCase useCase) { var aanvraag = mediator.ask(new GeefBorgstellingAanvraag(useCase.borgstellingId)); var maakContract = new MaakContract(); maakContract.BorgstellingId = aanvraag.BorgstellingId; maakContract.Kenmerk = aanvraag.Kenmerk; maakContractv.Bedrag = aanvraag.BrutoKredietsom; maakContract.Datum = new Date(); maakContract.EindDatum = port.Datum.plusMonths(36); maakContract.Kredietbank = aanvraag.Kredietbank; var contract = mediator.ask(maakContract); var archiveerDocument = new ArchiveerBorgstellingDocument(); archiveerDocument.DocumentId = useCase.ContractId; archiveerDocument.KredietbankId = aanvraag.KredietbankId; archiveerDocument.Onderwerp = String.format("Borgstelling contract %s met kenmerk %s.", aanvraag.BorgstellingId, aanvraag.Kenmerk); archiveerDocument.VerlooptOp = port.Datum.plusYears(7); archiveerDocument.Kenmerken = [ aanvraag.BorgstellingId, "Borgstelling contract", aanvraag.KredietbankId, aanvraag.Kenmerk ]; archiveerDocument.Bestand = new Bestand(); archiveerDocument.Bestand.Naam = String.format("borgstelling-contract-%s.pdf", aanvraag.BorgstellingId);; archiveerDocument.Bestand.Data = contract.toBase64String(); mediator.send(archiveerDocument); } } public class ExactService implements PortHandler<ArchiveerBorgstellingDocument> { private readonly ExactApi api; public ExactService(ExactApi api) { this.api = api; } public void handle(RegistreerVerkoop port) { var accountId = api.getAccountId(port.KredietbankId); const document = new Document(); document.ID = port.DocumentId; document.Account = accountId; document.Subject = port.Omschrijving; document.ExpiryDate = port.VerlooptOp; //TODO: uitzoeken<SUF> api.createDocument(document); const documentAttachment = new DocumentAttachment(); documentAttachment.Attachment = port.Bestand.Data; documentAttachment.Document = port.DocumentId; documentAttachment.FileName = port.Bestand.Naam; api.createDocumentAttachment(documentAttachment); } }
True
648
16
710
19
674
12
710
19
786
18
false
false
false
false
false
true
4,148
103049_0
package example.controller; import example.model.Blog; import example.model.Status; import example.service.BlogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; import java.util.stream.Collectors; @Controller @RequestMapping("/teBekijken") public class TeBekijkenController { @Autowired private BlogService blogService; @GetMapping("/") public String teBekijken(Model model) { List<Blog> teBekijkenItems = blogService.findByStatus(Status.TE_BEKIJKEN); model.addAttribute("havenSuggestion", new Blog()); model.addAttribute("teBekijkenItems", teBekijkenItems); // debug what is in TeBekijkenItems System.out.println(teBekijkenItems.stream().map(Object::toString).collect(Collectors.joining(", "))); return "teBekijken"; } @PostMapping("/suggest") public String suggestBlog(@ModelAttribute("havenSuggestion") Blog blog) { blog.setStatus(Status.TE_BEKIJKEN); blog.setContact("sampleContactTestingPurposesOnly"); blogService.add(blog); return "redirect:/teBekijken/"; } // update status of blog to "te bekijken" @PostMapping("/updateStatus") public String UpdateTeBekijkenStatus(Long id, String status) { blogService.updateStatus(id, Status.valueOf(status)); return "redirect:/teBekijken/"; } }
remzisahbaz/spring-boot-3-security-6
src/main/java/example/controller/TeBekijkenController.java
506
// debug what is in TeBekijkenItems
line_comment
nl
package example.controller; import example.model.Blog; import example.model.Status; import example.service.BlogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; import java.util.stream.Collectors; @Controller @RequestMapping("/teBekijken") public class TeBekijkenController { @Autowired private BlogService blogService; @GetMapping("/") public String teBekijken(Model model) { List<Blog> teBekijkenItems = blogService.findByStatus(Status.TE_BEKIJKEN); model.addAttribute("havenSuggestion", new Blog()); model.addAttribute("teBekijkenItems", teBekijkenItems); // debug what<SUF> System.out.println(teBekijkenItems.stream().map(Object::toString).collect(Collectors.joining(", "))); return "teBekijken"; } @PostMapping("/suggest") public String suggestBlog(@ModelAttribute("havenSuggestion") Blog blog) { blog.setStatus(Status.TE_BEKIJKEN); blog.setContact("sampleContactTestingPurposesOnly"); blogService.add(blog); return "redirect:/teBekijken/"; } // update status of blog to "te bekijken" @PostMapping("/updateStatus") public String UpdateTeBekijkenStatus(Long id, String status) { blogService.updateStatus(id, Status.valueOf(status)); return "redirect:/teBekijken/"; } }
False
347
10
445
11
446
10
445
11
516
11
false
false
false
false
false
true
2,567
197170_33
package aksis.alignment; import java.util.Iterator; import java.util.List; import java.util.ArrayList; /** * a list with information about alignable elements in one text. * doesn't span the whole text, * just a suitable range, * starting with the first element not yet aligned. * belongs to a Compare object */ class ElementsInfo { // which interval is stored // - first and last elementNumber, ikke sant?### int first = 0; int last = -1; // list of ElementInfo objects private List elementInfo = new ArrayList(); public ElementsInfo() { // } public void purge() { first = 0; last = -1; elementInfo.clear(); } //public ElementInfo getElementInfo(AlignmentModel model, int elementNumber, int t) { public ElementInfo getElementInfo(AlignmentModel model, int elementNumber, int t) throws EndOfTextException { //System.out.println("\ngetElementInfo. t = " + t + ", elementNumber = " + elementNumber); //System.out.println("getElementInfo. first = " + first + ", last = " + last); if (elementNumber < first) { // wanted element is outside range // expand range. //System.out.println("wanted element is outside range. expand range"); setFirst(model, elementNumber, t); ////setFirst(model, elementNumber, t, elementNumber); // 2006-04-05 } else if (elementNumber > last) { // wanted element is outside range - too high. // expand range. //System.out.println("wanted element is outside range - too high. expand range"); try { setLast(model, elementNumber, t); ////setLast(model, elementNumber, t, elementNumber); // 2006-04-05 } catch (EndOfTextException e) { throw e; } } //System.out.println("first = " + first + ", last = " + last); // debug ElementInfo temp = (ElementInfo)elementInfo.get(elementNumber - first); //System.out.println("getElementInfo. " + temp + "\n"); // end debug return (ElementInfo)elementInfo.get(elementNumber - first); } /* public setElementInfo(int elementNumber, int t) { ... element = ...[t]...; String text = XmlTools.getText(element); ### heller bruke .getTextContent() elementInfo.set... } */ //public int getFirst(AlignmentModel model, int t) { public int getFirst() { return first; } /** * change range - set a new start point * update content accordingly. */ public void setFirst(AlignmentModel model, int newFirst, int t) { ////public void setFirst(AlignmentModel model, int newFirst, int t, int elementNumber) { // 2006-04-05 //System.out.println("enter setFirst(). t = " + t + ", first = " + first + ", last = " + last + ", newFirst = " + newFirst); if (newFirst < first) { //System.out.println("setFirst(). tilfelle 1"); List more = new ArrayList(); for (int count = 0; count < first - newFirst; count++) { int index = newFirst + count; String text = model.nodes[t].item(index).getTextContent(); more.add(new ElementInfo(model, text, t, index)); // index = elementNumber. ???? 20056-04-05 } elementInfo.addAll(0, more); first = newFirst; } else if (newFirst > last) { //System.out.println("setFirst(). tilfelle 2"); elementInfo.clear(); first = newFirst; int husk = last; last = first - 1; //System.out.println("setFirst endret last fra " + husk + " til " + last); } else { //System.out.println("setFirst(). tilfelle 3"); for (int count = 0; count < newFirst - first; count++) { //elementInfo.remove(first); ### ugh elementInfo.remove(0); } first = newFirst; } //System.out.println("end setFirst(). t = " + t + ", first = " + first + ", last = " + last + ", newFirst = " + newFirst); //System.out.println("end setFirst(). ElementsInfo = " + ElementsInfo.this); } /** * change range - set a new end point * update content accordingly. */ //public void setLast(AlignmentModel model, int newLast, int t) { public void setLast(AlignmentModel model, int newLast, int t) throws EndOfTextException { ////public void setLast(AlignmentModel model, int newLast, int t, int elementNumber) throws EndOfTextException { // 2006-04-05 //System.out.println("enter setLast(). t = " + t + ", first = " + first + ", last = " + last + ", newLast = " + newLast); if (newLast > last) { //System.out.println("setLast(). tilfelle 1"); for (int count = 0; count < newLast - last; count++) { /* //Object element = ((AElement)(model.unaligned.elements[t].get(last + 1 + count))).element; // ###################### // last + 1 + count is absolute index. // calculate index relative unaligned. // ###### griseri. trenger metoder aligned.size(t) og toAlign.size(t) System.out.println("# aligned = " + model.aligned.elements[t].size()); System.out.println("# to align = " + model.toAlign.elements[t].getSize()); System.out.println("vil ha el nr " + (last + 1 + count) + " globalt"); int index = last + 1 + count - (model.aligned.elements[t].size() + model.toAlign.elements[t].getSize()); System.out.println("vil ha el nr " + index + " i unaligned"); Object element = ((AElement)(model.unaligned.elements[t].get(index))).element; */ //String text = XmlTools.getText((Node)element); ### heller bruke .getTextContent() int index = last + 1 + count; if (index >= model.nodes[t].getLength()) { last = index - 1 - count; //System.out.println("setter last = " + last + " (sjekk at verdien er riktig!), og throw'er en EndOfTextException"); throw new EndOfTextException(); } //String text = XmlTools.getText(model.nodes[t].item(index)); String text = model.nodes[t].item(index).getTextContent(); /* skal dette aktiveres her også? // 2006-9-15 // ###replace all " by ' because of a bug in LineBreakMeasurer System.out.println("1"); Pattern pattern = Pattern.compile("\""); Matcher matcher = pattern.matcher(text); text = matcher.replaceAll("'"); // end 2006-9-15 */ //elementInfo.add(new ElementInfo(model, text, t)); elementInfo.add(new ElementInfo(model, text, t, index)); // index = elementNumber. ???? 2006-04-05 } last = newLast; } else if (newLast < first) { //System.out.println("setLast(). tilfelle 2"); elementInfo.clear(); last = first - 1; } else { //System.out.println("setLast(). tilfelle 3"); for (int count = 0; count < last - newLast; count++) { //elementInfo.remove(last - count); ### ugh elementInfo.remove(last - first - count); } last = newLast; } //System.out.println("end setLast(). t = " + t + ", first = " + first + ", last = " + last + ", newLast = " + newLast); //System.out.println("end setLast(). ElementsInfo = " + ElementsInfo.this); } // ### for debuggingsformål public String toString() { StringBuffer ret = new StringBuffer(); ret.append("[\n"); Iterator it = elementInfo.iterator(); while (it.hasNext()) { ElementInfo e = (ElementInfo)it.next(); ret.append("" + e + "\n"); } ret.append("]\n"); return new String(ret); } }
divvun/CorpusTools
corpustools/tca2/aksis/alignment/ElementsInfo.java
2,339
/* //Object element = ((AElement)(model.unaligned.elements[t].get(last + 1 + count))).element; // ###################### // last + 1 + count is absolute index. // calculate index relative unaligned. // ###### griseri. trenger metoder aligned.size(t) og toAlign.size(t) System.out.println("# aligned = " + model.aligned.elements[t].size()); System.out.println("# to align = " + model.toAlign.elements[t].getSize()); System.out.println("vil ha el nr " + (last + 1 + count) + " globalt"); int index = last + 1 + count - (model.aligned.elements[t].size() + model.toAlign.elements[t].getSize()); System.out.println("vil ha el nr " + index + " i unaligned"); Object element = ((AElement)(model.unaligned.elements[t].get(index))).element; */
block_comment
nl
package aksis.alignment; import java.util.Iterator; import java.util.List; import java.util.ArrayList; /** * a list with information about alignable elements in one text. * doesn't span the whole text, * just a suitable range, * starting with the first element not yet aligned. * belongs to a Compare object */ class ElementsInfo { // which interval is stored // - first and last elementNumber, ikke sant?### int first = 0; int last = -1; // list of ElementInfo objects private List elementInfo = new ArrayList(); public ElementsInfo() { // } public void purge() { first = 0; last = -1; elementInfo.clear(); } //public ElementInfo getElementInfo(AlignmentModel model, int elementNumber, int t) { public ElementInfo getElementInfo(AlignmentModel model, int elementNumber, int t) throws EndOfTextException { //System.out.println("\ngetElementInfo. t = " + t + ", elementNumber = " + elementNumber); //System.out.println("getElementInfo. first = " + first + ", last = " + last); if (elementNumber < first) { // wanted element is outside range // expand range. //System.out.println("wanted element is outside range. expand range"); setFirst(model, elementNumber, t); ////setFirst(model, elementNumber, t, elementNumber); // 2006-04-05 } else if (elementNumber > last) { // wanted element is outside range - too high. // expand range. //System.out.println("wanted element is outside range - too high. expand range"); try { setLast(model, elementNumber, t); ////setLast(model, elementNumber, t, elementNumber); // 2006-04-05 } catch (EndOfTextException e) { throw e; } } //System.out.println("first = " + first + ", last = " + last); // debug ElementInfo temp = (ElementInfo)elementInfo.get(elementNumber - first); //System.out.println("getElementInfo. " + temp + "\n"); // end debug return (ElementInfo)elementInfo.get(elementNumber - first); } /* public setElementInfo(int elementNumber, int t) { ... element = ...[t]...; String text = XmlTools.getText(element); ### heller bruke .getTextContent() elementInfo.set... } */ //public int getFirst(AlignmentModel model, int t) { public int getFirst() { return first; } /** * change range - set a new start point * update content accordingly. */ public void setFirst(AlignmentModel model, int newFirst, int t) { ////public void setFirst(AlignmentModel model, int newFirst, int t, int elementNumber) { // 2006-04-05 //System.out.println("enter setFirst(). t = " + t + ", first = " + first + ", last = " + last + ", newFirst = " + newFirst); if (newFirst < first) { //System.out.println("setFirst(). tilfelle 1"); List more = new ArrayList(); for (int count = 0; count < first - newFirst; count++) { int index = newFirst + count; String text = model.nodes[t].item(index).getTextContent(); more.add(new ElementInfo(model, text, t, index)); // index = elementNumber. ???? 20056-04-05 } elementInfo.addAll(0, more); first = newFirst; } else if (newFirst > last) { //System.out.println("setFirst(). tilfelle 2"); elementInfo.clear(); first = newFirst; int husk = last; last = first - 1; //System.out.println("setFirst endret last fra " + husk + " til " + last); } else { //System.out.println("setFirst(). tilfelle 3"); for (int count = 0; count < newFirst - first; count++) { //elementInfo.remove(first); ### ugh elementInfo.remove(0); } first = newFirst; } //System.out.println("end setFirst(). t = " + t + ", first = " + first + ", last = " + last + ", newFirst = " + newFirst); //System.out.println("end setFirst(). ElementsInfo = " + ElementsInfo.this); } /** * change range - set a new end point * update content accordingly. */ //public void setLast(AlignmentModel model, int newLast, int t) { public void setLast(AlignmentModel model, int newLast, int t) throws EndOfTextException { ////public void setLast(AlignmentModel model, int newLast, int t, int elementNumber) throws EndOfTextException { // 2006-04-05 //System.out.println("enter setLast(). t = " + t + ", first = " + first + ", last = " + last + ", newLast = " + newLast); if (newLast > last) { //System.out.println("setLast(). tilfelle 1"); for (int count = 0; count < newLast - last; count++) { /* //Object element =<SUF>*/ //String text = XmlTools.getText((Node)element); ### heller bruke .getTextContent() int index = last + 1 + count; if (index >= model.nodes[t].getLength()) { last = index - 1 - count; //System.out.println("setter last = " + last + " (sjekk at verdien er riktig!), og throw'er en EndOfTextException"); throw new EndOfTextException(); } //String text = XmlTools.getText(model.nodes[t].item(index)); String text = model.nodes[t].item(index).getTextContent(); /* skal dette aktiveres her også? // 2006-9-15 // ###replace all " by ' because of a bug in LineBreakMeasurer System.out.println("1"); Pattern pattern = Pattern.compile("\""); Matcher matcher = pattern.matcher(text); text = matcher.replaceAll("'"); // end 2006-9-15 */ //elementInfo.add(new ElementInfo(model, text, t)); elementInfo.add(new ElementInfo(model, text, t, index)); // index = elementNumber. ???? 2006-04-05 } last = newLast; } else if (newLast < first) { //System.out.println("setLast(). tilfelle 2"); elementInfo.clear(); last = first - 1; } else { //System.out.println("setLast(). tilfelle 3"); for (int count = 0; count < last - newLast; count++) { //elementInfo.remove(last - count); ### ugh elementInfo.remove(last - first - count); } last = newLast; } //System.out.println("end setLast(). t = " + t + ", first = " + first + ", last = " + last + ", newLast = " + newLast); //System.out.println("end setLast(). ElementsInfo = " + ElementsInfo.this); } // ### for debuggingsformål public String toString() { StringBuffer ret = new StringBuffer(); ret.append("[\n"); Iterator it = elementInfo.iterator(); while (it.hasNext()) { ElementInfo e = (ElementInfo)it.next(); ret.append("" + e + "\n"); } ret.append("]\n"); return new String(ret); } }
False
2,001
204
2,252
242
2,219
239
2,252
242
2,561
282
false
true
true
true
true
false
3,053
71941_2
package io.dropwizard.resources; import com.fasterxml.jackson.annotation.JsonView; import io.dropwizard.View; import io.dropwizard.models.RegisteredHour; import io.dropwizard.services.RegisteredHourService; import javax.annotation.security.RolesAllowed; import javax.inject.Singleton; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.List; @Singleton @Path("/uren") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({"1", "0"}) // 1 = admin, 0 = personeel; public class HourResource { private RegisteredHourService service; public HourResource(RegisteredHourService service){ this.service = service; } // Voorbeelden voor de URL: // localhost:8080/uren/getby?begindatum=2017-1-1&einddatum=2018-1-1 // localhost:8080/uren/getby?begindatum=2017-1-1&einddatum=2018-1-1&klant=WebEdu // localhost:8080/uren/getby?begindatum=2017-1-1&einddatum=2018-1-1&klant=WebEdu&project=UrenRegistratieApplicatie // localhost:8080/uren/getby?begindatum=2017-1-1&einddatum=2018-1-1&klant=WebEdu&project=UrenRegistratieApplicatie&onderwerp=Applicatie /** * Ontvangt een personeelID en geeft alle gewerkte uren voor dit personeelID terug. * @param id * @return */ @GET @Path("/getbyid") @JsonView(View.Public.class) public List<RegisteredHour> getUren( @QueryParam("id") int id){ return service.getUrenByPersoneelId(id); } @GET @Path("/getall") @JsonView(View.OnlyAdmins.class) @RolesAllowed("1") public List<RegisteredHour> getAllUren(){ return service.getAllUren(); } @POST @Path("/setHour") @Consumes(MediaType.APPLICATION_JSON) @JsonView(View.OnlyAdmins.class) public void setHours( RegisteredHour registeredHour) { this.service.setHours(registeredHour); } @POST @Path("/confirm") @Consumes(MediaType.APPLICATION_JSON) @JsonView(View.OnlyAdmins.class) @RolesAllowed("1") public void setConfirmed(RegisteredHour uur){ this.service.setConfirmed(uur); } @POST @Path("/updateHour") @Consumes(MediaType.APPLICATION_JSON) @JsonView(View.Public.class) public void updateHour(RegisteredHour hour){ System.out.println(hour.getHourID()); this.service.updateHour(hour);} }
ianbeemsterboerr/ipsen3-api
src/main/java/io/dropwizard/resources/HourResource.java
841
/** * Ontvangt een personeelID en geeft alle gewerkte uren voor dit personeelID terug. * @param id * @return */
block_comment
nl
package io.dropwizard.resources; import com.fasterxml.jackson.annotation.JsonView; import io.dropwizard.View; import io.dropwizard.models.RegisteredHour; import io.dropwizard.services.RegisteredHourService; import javax.annotation.security.RolesAllowed; import javax.inject.Singleton; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.List; @Singleton @Path("/uren") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({"1", "0"}) // 1 = admin, 0 = personeel; public class HourResource { private RegisteredHourService service; public HourResource(RegisteredHourService service){ this.service = service; } // Voorbeelden voor de URL: // localhost:8080/uren/getby?begindatum=2017-1-1&einddatum=2018-1-1 // localhost:8080/uren/getby?begindatum=2017-1-1&einddatum=2018-1-1&klant=WebEdu // localhost:8080/uren/getby?begindatum=2017-1-1&einddatum=2018-1-1&klant=WebEdu&project=UrenRegistratieApplicatie // localhost:8080/uren/getby?begindatum=2017-1-1&einddatum=2018-1-1&klant=WebEdu&project=UrenRegistratieApplicatie&onderwerp=Applicatie /** * Ontvangt een personeelID<SUF>*/ @GET @Path("/getbyid") @JsonView(View.Public.class) public List<RegisteredHour> getUren( @QueryParam("id") int id){ return service.getUrenByPersoneelId(id); } @GET @Path("/getall") @JsonView(View.OnlyAdmins.class) @RolesAllowed("1") public List<RegisteredHour> getAllUren(){ return service.getAllUren(); } @POST @Path("/setHour") @Consumes(MediaType.APPLICATION_JSON) @JsonView(View.OnlyAdmins.class) public void setHours( RegisteredHour registeredHour) { this.service.setHours(registeredHour); } @POST @Path("/confirm") @Consumes(MediaType.APPLICATION_JSON) @JsonView(View.OnlyAdmins.class) @RolesAllowed("1") public void setConfirmed(RegisteredHour uur){ this.service.setConfirmed(uur); } @POST @Path("/updateHour") @Consumes(MediaType.APPLICATION_JSON) @JsonView(View.Public.class) public void updateHour(RegisteredHour hour){ System.out.println(hour.getHourID()); this.service.updateHour(hour);} }
True
653
39
744
42
765
37
744
42
876
42
false
false
false
false
false
true
58
43930_0
package be.ap.teamrap.teamrap; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import com.crashlytics.android.Crashlytics; import io.fabric.sdk.android.Fabric; public class MainActivity extends AppCompatActivity { //Dit is een zeer mooie comment @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Fabric.with(this, new Crashlytics()); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
AP-IT-GH/sprint-ci-cd-in-team-pm_teamrap
app/src/main/java/be/ap/teamrap/teamrap/MainActivity.java
556
//Dit is een zeer mooie comment
line_comment
nl
package be.ap.teamrap.teamrap; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import com.crashlytics.android.Crashlytics; import io.fabric.sdk.android.Fabric; public class MainActivity extends AppCompatActivity { //Dit is<SUF> @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Fabric.with(this, new Crashlytics()); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
True
359
9
450
11
470
7
450
11
532
11
false
false
false
false
false
true
2,236
37331_17
package jmri.jmrit.beantable.routetable; import jmri.InstanceManager; import jmri.Route; import jmri.Sensor; import jmri.Turnout; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; /** * Edit frame for the Route Table. * * Split from {@link jmri.jmrit.beantable.RouteTableAction} * * @author Dave Duchamp Copyright (C) 2004 * @author Bob Jacobsen Copyright (C) 2007 * @author Simon Reader Copyright (C) 2008 * @author Pete Cressman Copyright (C) 2009 * @author Egbert Broerse Copyright (C) 2016 * @author Paul Bender Copyright (C) 2020 */ public class RouteEditFrame extends AbstractRouteAddEditFrame { private final String systemName; public RouteEditFrame(String systemName) { this(Bundle.getMessage("TitleEditRoute"), systemName); } public RouteEditFrame(String name, String systemName) { this(name,false,true, systemName); } public RouteEditFrame(String name, boolean saveSize, boolean savePosition, String systemName) { super(name, saveSize, savePosition); this.systemName = systemName; initComponents(); } @Override public void initComponents() { super.initComponents(); _systemName.setText(systemName); // identify the Route with this name if it already exists String sName = _systemName.getText(); Route g = InstanceManager.getDefault(jmri.RouteManager.class).getBySystemName(sName); if (g == null) { sName = _userName.getText(); g = InstanceManager.getDefault(jmri.RouteManager.class).getByUserName(sName); if (g == null) { // Route does not exist, so cannot be edited status1.setText(Bundle.getMessage("RouteAddStatusErrorNotFound")); return; } } // Route was found, make its system name not changeable curRoute = g; _systemName.setVisible(true); _systemName.setText(sName); _systemName.setEnabled(false); nameLabel.setEnabled(true); _autoSystemName.setVisible(false); // deactivate this Route curRoute.deActivateRoute(); // get information for this route _userName.setText(g.getUserName()); // set up Turnout list for this route int setRow = 0; for (int i = _turnoutList.size() - 1; i >= 0; i--) { RouteTurnout turnout = _turnoutList.get(i); String tSysName = turnout.getSysName(); if (g.isOutputTurnoutIncluded(tSysName)) { turnout.setIncluded(true); turnout.setState(g.getOutputTurnoutSetState(tSysName)); setRow = i; } else { turnout.setIncluded(false); turnout.setState(Turnout.CLOSED); } } setRow -= 1; if (setRow < 0) { setRow = 0; } _routeTurnoutScrollPane.getVerticalScrollBar().setValue(setRow * ROW_HEIGHT); _routeTurnoutModel.fireTableDataChanged(); // set up Sensor list for this route for (int i = _sensorList.size() - 1; i >= 0; i--) { RouteSensor sensor = _sensorList.get(i); String tSysName = sensor.getSysName(); if (g.isOutputSensorIncluded(tSysName)) { sensor.setIncluded(true); sensor.setState(g.getOutputSensorSetState(tSysName)); setRow = i; } else { sensor.setIncluded(false); sensor.setState(Sensor.INACTIVE); } } setRow -= 1; if (setRow < 0) { setRow = 0; } _routeSensorScrollPane.getVerticalScrollBar().setValue(setRow * ROW_HEIGHT); _routeSensorModel.fireTableDataChanged(); // get Sound and Script file names scriptFile.setText(g.getOutputScriptName()); soundFile.setText(g.getOutputSoundName()); // get Turnout Aligned sensor turnoutsAlignedSensor.setSelectedItem(g.getTurnoutsAlgdSensor()); // set up Sensors if there are any Sensor[] temNames = new Sensor[Route.MAX_CONTROL_SENSORS]; int[] temModes = new int[Route.MAX_CONTROL_SENSORS]; for (int k = 0; k < Route.MAX_CONTROL_SENSORS; k++) { temNames[k] = g.getRouteSensor(k); temModes[k] = g.getRouteSensorMode(k); } sensor1.setSelectedItem(temNames[0]); setSensorModeBox(temModes[0], sensor1mode); sensor2.setSelectedItem(temNames[1]); setSensorModeBox(temModes[1], sensor2mode); sensor3.setSelectedItem(temNames[2]); setSensorModeBox(temModes[2], sensor3mode); // set up Control Turnout if there is one cTurnout.setSelectedItem(g.getCtlTurnout()); setTurnoutModeBox(g.getControlTurnoutState(), cTurnoutStateBox); // set up Lock Control Turnout if there is one cLockTurnout.setSelectedItem(g.getLockCtlTurnout()); setTurnoutModeBox(g.getLockControlTurnoutState(), cLockTurnoutStateBox); // set up additional route specific Delay timeDelay.setValue(g.getRouteCommandDelay()); // begin with showing all Turnouts // set up buttons and notes status1.setText(Bundle.getMessage("RouteAddStatusInitial3", Bundle.getMessage("ButtonUpdate"))); status2.setText(Bundle.getMessage("RouteAddStatusInitial4", Bundle.getMessage("ButtonCancelEdit", Bundle.getMessage("ButtonEdit")))); status2.setVisible(true); setTitle(Bundle.getMessage("TitleEditRoute")); editMode = true; } @Override protected JPanel getButtonPanel() { final JButton cancelEditButton = new JButton(Bundle.getMessage("ButtonCancelEdit", Bundle.getMessage("ButtonEdit"))); // I18N for word sequence "Cancel Edit" final JButton deleteButton = new JButton(Bundle.getMessage("ButtonDelete") + " " + Bundle.getMessage("BeanNameRoute")); // I18N "Delete Route" final JButton updateButton = new JButton(Bundle.getMessage("ButtonUpdate")); final JButton exportButton = new JButton(Bundle.getMessage("ButtonExport")); // add Buttons panel JPanel pb = new JPanel(); pb.setLayout(new FlowLayout(FlowLayout.TRAILING)); // CancelEdit button pb.add(cancelEditButton); cancelEditButton.addActionListener(this::cancelPressed); cancelEditButton.setToolTipText(Bundle.getMessage("TooltipCancelRoute")); // Delete Route button pb.add(deleteButton); deleteButton.addActionListener(this::deletePressed); deleteButton.setToolTipText(Bundle.getMessage("TooltipDeleteRoute")); // Update Route button pb.add(updateButton); updateButton.addActionListener((ActionEvent e1) -> updatePressed(false)); updateButton.setToolTipText(Bundle.getMessage("TooltipUpdateRoute")); // Export button pb.add(exportButton); exportButton.addActionListener(this::exportButtonPressed); exportButton.setToolTipText(Bundle.getMessage("TooltipExportRoute")); // Show the initial buttons, and hide the others deleteButton.setVisible(true); cancelEditButton.setVisible(true); updateButton.setVisible(true); exportButton.setVisible(true); return pb; } /** * Respond to the export button. * * @param e the action event */ private void exportButtonPressed(ActionEvent e){ new RouteExportToLogix(_systemName.getText()).export(); status1.setText(Bundle.getMessage("BeanNameRoute") + "\"" + _systemName.getText() + "\" " + Bundle.getMessage("RouteAddStatusExported") + " (" + get_includedTurnoutList().size() + Bundle.getMessage("Turnouts") + ", " + get_includedSensorList().size() + " " + Bundle.getMessage("Sensors") + ")"); finishUpdate(); closeFrame(); } /** * Respond to the CancelEdit button. * * @param e the action event */ private void cancelPressed(ActionEvent e) { cancelEdit(); } /** * Respond to the Delete button. * * @param e the action event */ private void deletePressed(ActionEvent e) { // route is already deactivated, just delete it routeManager.deleteRoute(curRoute); curRoute = null; finishUpdate(); closeFrame(); } }
bentamircea/JMRI
java/src/jmri/jmrit/beantable/routetable/RouteEditFrame.java
2,504
// I18N "Delete Route"
line_comment
nl
package jmri.jmrit.beantable.routetable; import jmri.InstanceManager; import jmri.Route; import jmri.Sensor; import jmri.Turnout; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; /** * Edit frame for the Route Table. * * Split from {@link jmri.jmrit.beantable.RouteTableAction} * * @author Dave Duchamp Copyright (C) 2004 * @author Bob Jacobsen Copyright (C) 2007 * @author Simon Reader Copyright (C) 2008 * @author Pete Cressman Copyright (C) 2009 * @author Egbert Broerse Copyright (C) 2016 * @author Paul Bender Copyright (C) 2020 */ public class RouteEditFrame extends AbstractRouteAddEditFrame { private final String systemName; public RouteEditFrame(String systemName) { this(Bundle.getMessage("TitleEditRoute"), systemName); } public RouteEditFrame(String name, String systemName) { this(name,false,true, systemName); } public RouteEditFrame(String name, boolean saveSize, boolean savePosition, String systemName) { super(name, saveSize, savePosition); this.systemName = systemName; initComponents(); } @Override public void initComponents() { super.initComponents(); _systemName.setText(systemName); // identify the Route with this name if it already exists String sName = _systemName.getText(); Route g = InstanceManager.getDefault(jmri.RouteManager.class).getBySystemName(sName); if (g == null) { sName = _userName.getText(); g = InstanceManager.getDefault(jmri.RouteManager.class).getByUserName(sName); if (g == null) { // Route does not exist, so cannot be edited status1.setText(Bundle.getMessage("RouteAddStatusErrorNotFound")); return; } } // Route was found, make its system name not changeable curRoute = g; _systemName.setVisible(true); _systemName.setText(sName); _systemName.setEnabled(false); nameLabel.setEnabled(true); _autoSystemName.setVisible(false); // deactivate this Route curRoute.deActivateRoute(); // get information for this route _userName.setText(g.getUserName()); // set up Turnout list for this route int setRow = 0; for (int i = _turnoutList.size() - 1; i >= 0; i--) { RouteTurnout turnout = _turnoutList.get(i); String tSysName = turnout.getSysName(); if (g.isOutputTurnoutIncluded(tSysName)) { turnout.setIncluded(true); turnout.setState(g.getOutputTurnoutSetState(tSysName)); setRow = i; } else { turnout.setIncluded(false); turnout.setState(Turnout.CLOSED); } } setRow -= 1; if (setRow < 0) { setRow = 0; } _routeTurnoutScrollPane.getVerticalScrollBar().setValue(setRow * ROW_HEIGHT); _routeTurnoutModel.fireTableDataChanged(); // set up Sensor list for this route for (int i = _sensorList.size() - 1; i >= 0; i--) { RouteSensor sensor = _sensorList.get(i); String tSysName = sensor.getSysName(); if (g.isOutputSensorIncluded(tSysName)) { sensor.setIncluded(true); sensor.setState(g.getOutputSensorSetState(tSysName)); setRow = i; } else { sensor.setIncluded(false); sensor.setState(Sensor.INACTIVE); } } setRow -= 1; if (setRow < 0) { setRow = 0; } _routeSensorScrollPane.getVerticalScrollBar().setValue(setRow * ROW_HEIGHT); _routeSensorModel.fireTableDataChanged(); // get Sound and Script file names scriptFile.setText(g.getOutputScriptName()); soundFile.setText(g.getOutputSoundName()); // get Turnout Aligned sensor turnoutsAlignedSensor.setSelectedItem(g.getTurnoutsAlgdSensor()); // set up Sensors if there are any Sensor[] temNames = new Sensor[Route.MAX_CONTROL_SENSORS]; int[] temModes = new int[Route.MAX_CONTROL_SENSORS]; for (int k = 0; k < Route.MAX_CONTROL_SENSORS; k++) { temNames[k] = g.getRouteSensor(k); temModes[k] = g.getRouteSensorMode(k); } sensor1.setSelectedItem(temNames[0]); setSensorModeBox(temModes[0], sensor1mode); sensor2.setSelectedItem(temNames[1]); setSensorModeBox(temModes[1], sensor2mode); sensor3.setSelectedItem(temNames[2]); setSensorModeBox(temModes[2], sensor3mode); // set up Control Turnout if there is one cTurnout.setSelectedItem(g.getCtlTurnout()); setTurnoutModeBox(g.getControlTurnoutState(), cTurnoutStateBox); // set up Lock Control Turnout if there is one cLockTurnout.setSelectedItem(g.getLockCtlTurnout()); setTurnoutModeBox(g.getLockControlTurnoutState(), cLockTurnoutStateBox); // set up additional route specific Delay timeDelay.setValue(g.getRouteCommandDelay()); // begin with showing all Turnouts // set up buttons and notes status1.setText(Bundle.getMessage("RouteAddStatusInitial3", Bundle.getMessage("ButtonUpdate"))); status2.setText(Bundle.getMessage("RouteAddStatusInitial4", Bundle.getMessage("ButtonCancelEdit", Bundle.getMessage("ButtonEdit")))); status2.setVisible(true); setTitle(Bundle.getMessage("TitleEditRoute")); editMode = true; } @Override protected JPanel getButtonPanel() { final JButton cancelEditButton = new JButton(Bundle.getMessage("ButtonCancelEdit", Bundle.getMessage("ButtonEdit"))); // I18N for word sequence "Cancel Edit" final JButton deleteButton = new JButton(Bundle.getMessage("ButtonDelete") + " " + Bundle.getMessage("BeanNameRoute")); // I18N "Delete<SUF> final JButton updateButton = new JButton(Bundle.getMessage("ButtonUpdate")); final JButton exportButton = new JButton(Bundle.getMessage("ButtonExport")); // add Buttons panel JPanel pb = new JPanel(); pb.setLayout(new FlowLayout(FlowLayout.TRAILING)); // CancelEdit button pb.add(cancelEditButton); cancelEditButton.addActionListener(this::cancelPressed); cancelEditButton.setToolTipText(Bundle.getMessage("TooltipCancelRoute")); // Delete Route button pb.add(deleteButton); deleteButton.addActionListener(this::deletePressed); deleteButton.setToolTipText(Bundle.getMessage("TooltipDeleteRoute")); // Update Route button pb.add(updateButton); updateButton.addActionListener((ActionEvent e1) -> updatePressed(false)); updateButton.setToolTipText(Bundle.getMessage("TooltipUpdateRoute")); // Export button pb.add(exportButton); exportButton.addActionListener(this::exportButtonPressed); exportButton.setToolTipText(Bundle.getMessage("TooltipExportRoute")); // Show the initial buttons, and hide the others deleteButton.setVisible(true); cancelEditButton.setVisible(true); updateButton.setVisible(true); exportButton.setVisible(true); return pb; } /** * Respond to the export button. * * @param e the action event */ private void exportButtonPressed(ActionEvent e){ new RouteExportToLogix(_systemName.getText()).export(); status1.setText(Bundle.getMessage("BeanNameRoute") + "\"" + _systemName.getText() + "\" " + Bundle.getMessage("RouteAddStatusExported") + " (" + get_includedTurnoutList().size() + Bundle.getMessage("Turnouts") + ", " + get_includedSensorList().size() + " " + Bundle.getMessage("Sensors") + ")"); finishUpdate(); closeFrame(); } /** * Respond to the CancelEdit button. * * @param e the action event */ private void cancelPressed(ActionEvent e) { cancelEdit(); } /** * Respond to the Delete button. * * @param e the action event */ private void deletePressed(ActionEvent e) { // route is already deactivated, just delete it routeManager.deleteRoute(curRoute); curRoute = null; finishUpdate(); closeFrame(); } }
False
1,837
9
2,054
9
2,179
9
2,054
9
2,429
9
false
false
false
false
false
true
3,833
8390_2
/*_x000D_ * Copyright (c) 2014, Netherlands Forensic Institute_x000D_ * All rights reserved._x000D_ */_x000D_ package nl.minvenj.nfi.prnu;_x000D_ _x000D_ import java.awt.color.CMMException;_x000D_ import java.awt.image.BufferedImage;_x000D_ import java.awt.image.ColorModel;_x000D_ import java.io.BufferedInputStream;_x000D_ import java.io.BufferedOutputStream;_x000D_ import java.io.File;_x000D_ import java.io.FileInputStream;_x000D_ import java.io.FileOutputStream;_x000D_ import java.io.IOException;_x000D_ import java.io.InputStream;_x000D_ import java.io.ObjectInputStream;_x000D_ import java.io.ObjectOutputStream;_x000D_ import java.io.OutputStream;_x000D_ _x000D_ import javax.imageio.ImageIO;_x000D_ _x000D_ import nl.minvenj.nfi.prnu.filter.FastNoiseFilter;_x000D_ import nl.minvenj.nfi.prnu.filter.ImageFilter;_x000D_ import nl.minvenj.nfi.prnu.filter.WienerFilter;_x000D_ import nl.minvenj.nfi.prnu.filter.ZeroMeanTotalFilter;_x000D_ _x000D_ public final class PrnuExtract {_x000D_ static final File TESTDATA_FOLDER = new File("testdata");_x000D_ _x000D_ static final File INPUT_FOLDER = new File(TESTDATA_FOLDER, "input");_x000D_ // public static final File INPUT_FILE = new File(INPUT_FOLDER, "test.jpg");_x000D_ public static final File INPUT_FILE = new File("/var/scratch/bwn200/Dresden/2748x3664/Kodak_M1063_4_12664.JPG");_x000D_ static final File EXPECTED_PATTERN_FILE = new File(INPUT_FOLDER, "expected.pat");_x000D_ _x000D_ static final File OUTPUT_FOLDER = new File(TESTDATA_FOLDER, "output");_x000D_ static final File OUTPUT_FILE = new File(OUTPUT_FOLDER, "test.pat");_x000D_ _x000D_ public static void main(final String[] args) throws IOException {_x000D_ long start = System.currentTimeMillis();_x000D_ long end = 0;_x000D_ _x000D_ // Laad de input file in_x000D_ final BufferedImage image = readImage(INPUT_FILE);_x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Load image: " + (end-start) + " ms.");_x000D_ _x000D_ // Zet de input file om in 3 matrices (rood, groen, blauw)_x000D_ start = System.currentTimeMillis();_x000D_ final float[][][] rgbArrays = convertImageToFloatArrays(image);_x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Convert image:" + (end-start) + " ms.");_x000D_ _x000D_ // Bereken van elke matrix het PRNU patroon (extractie stap)_x000D_ start = System.currentTimeMillis();_x000D_ for (int i = 0; i < 3; i++) {_x000D_ extractImage(rgbArrays[i]);_x000D_ }_x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("PRNU extracted: " + (end-start) + " ms.");_x000D_ _x000D_ // Schrijf het patroon weg als een Java object_x000D_ writeJavaObject(rgbArrays, OUTPUT_FILE);_x000D_ _x000D_ System.out.println("Pattern written");_x000D_ _x000D_ // Controleer nu het gemaakte bestand_x000D_ final float[][][] expectedPattern = (float[][][]) readJavaObject(EXPECTED_PATTERN_FILE);_x000D_ final float[][][] actualPattern = (float[][][]) readJavaObject(OUTPUT_FILE);_x000D_ for (int i = 0; i < 3; i++) {_x000D_ // Het patroon zoals dat uit PRNU Compare komt, bevat een extra matrix voor transparantie. Deze moeten we overslaan (+1)!_x000D_ compare2DArray(expectedPattern[i + 1], actualPattern[i], 0.0001f);_x000D_ }_x000D_ _x000D_ System.out.println("Validation completed");_x000D_ _x000D_ //This exit is inserted because the program will otherwise hang for a about a minute_x000D_ //most likely explanation for this is the fact that the FFT library spawns a couple_x000D_ //of threads which cannot be properly destroyed_x000D_ System.exit(0);_x000D_ }_x000D_ _x000D_ private static BufferedImage readImage(final File file) throws IOException {_x000D_ final InputStream fileInputStream = new FileInputStream(file);_x000D_ try {_x000D_ final BufferedImage image = ImageIO.read(new BufferedInputStream(fileInputStream));_x000D_ if ((image != null) && (image.getWidth() >= 0) && (image.getHeight() >= 0)) {_x000D_ return image;_x000D_ }_x000D_ }_x000D_ catch (final CMMException e) {_x000D_ // Image file is unsupported or corrupt_x000D_ }_x000D_ catch (final RuntimeException e) {_x000D_ // Internal error processing image file_x000D_ }_x000D_ catch (final IOException e) {_x000D_ // Error reading image from disk_x000D_ }_x000D_ finally {_x000D_ fileInputStream.close();_x000D_ }_x000D_ _x000D_ // Image unreadable or too smalld array_x000D_ return null;_x000D_ }_x000D_ _x000D_ private static float[][][] convertImageToFloatArrays(final BufferedImage image) {_x000D_ final int width = image.getWidth();_x000D_ final int height = image.getHeight();_x000D_ final float[][][] pixels = new float[3][height][width];_x000D_ _x000D_ final ColorModel colorModel = ColorModel.getRGBdefault();_x000D_ for (int y = 0; y < height; y++) {_x000D_ for (int x = 0; x < width; x++) {_x000D_ final int pixel = image.getRGB(x, y); // aa bb gg rr_x000D_ pixels[0][y][x] = colorModel.getRed(pixel);_x000D_ pixels[1][y][x] = colorModel.getGreen(pixel);_x000D_ pixels[2][y][x] = colorModel.getBlue(pixel);_x000D_ }_x000D_ }_x000D_ return pixels;_x000D_ }_x000D_ _x000D_ private static void extractImage(final float[][] pixels) {_x000D_ final int width = pixels[0].length;_x000D_ final int height = pixels.length;_x000D_ _x000D_ long start = System.currentTimeMillis();_x000D_ long end = 0;_x000D_ _x000D_ final ImageFilter fastNoiseFilter = new FastNoiseFilter(width, height);_x000D_ fastNoiseFilter.apply(pixels);_x000D_ _x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Fast Noise Filter: " + (end-start) + " ms.");_x000D_ _x000D_ start = System.currentTimeMillis();_x000D_ final ImageFilter zeroMeanTotalFilter = new ZeroMeanTotalFilter(width, height);_x000D_ zeroMeanTotalFilter.apply(pixels);_x000D_ _x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Zero Mean Filter: " + (end-start) + " ms.");_x000D_ _x000D_ start = System.currentTimeMillis();_x000D_ final ImageFilter wienerFilter = new WienerFilter(width, height);_x000D_ wienerFilter.apply(pixels);_x000D_ _x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Wiener Filter: " + (end-start) + " ms.");_x000D_ }_x000D_ _x000D_ public static Object readJavaObject(final File inputFile) throws IOException {_x000D_ final ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile)));_x000D_ try {_x000D_ return inputStream.readObject();_x000D_ }_x000D_ catch (final ClassNotFoundException e) {_x000D_ throw new IOException("Cannot read pattern: " + inputFile.getAbsolutePath(), e);_x000D_ }_x000D_ finally {_x000D_ inputStream.close();_x000D_ }_x000D_ }_x000D_ _x000D_ private static void writeJavaObject(final Object object, final File outputFile) throws IOException {_x000D_ final OutputStream outputStream = new FileOutputStream(outputFile);_x000D_ try {_x000D_ final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream));_x000D_ objectOutputStream.writeObject(object);_x000D_ objectOutputStream.close();_x000D_ }_x000D_ finally {_x000D_ outputStream.close();_x000D_ }_x000D_ }_x000D_ _x000D_ private static boolean compare2DArray(final float[][] expected, final float[][] actual, final float delta) {_x000D_ for (int i = 0; i < expected.length; i++) {_x000D_ for (int j = 0; j < expected[i].length; j++) {_x000D_ if (Math.abs(actual[i][j] - expected[i][j]) > delta) {_x000D_ System.err.println("de waarde op " + i + "," + j + " is " + actual[i][j] + " maar had moeten zijn " + expected[i][j]);_x000D_ return false;_x000D_ }_x000D_ }_x000D_ }_x000D_ return true;_x000D_ }_x000D_ _x000D_ }_x000D_
nlesc-sherlock/cluster-analysis
prnuextract/src/nl/minvenj/nfi/prnu/PrnuExtract.java
2,212
// Laad de input file in_x000D_
line_comment
nl
/*_x000D_ * Copyright (c) 2014, Netherlands Forensic Institute_x000D_ * All rights reserved._x000D_ */_x000D_ package nl.minvenj.nfi.prnu;_x000D_ _x000D_ import java.awt.color.CMMException;_x000D_ import java.awt.image.BufferedImage;_x000D_ import java.awt.image.ColorModel;_x000D_ import java.io.BufferedInputStream;_x000D_ import java.io.BufferedOutputStream;_x000D_ import java.io.File;_x000D_ import java.io.FileInputStream;_x000D_ import java.io.FileOutputStream;_x000D_ import java.io.IOException;_x000D_ import java.io.InputStream;_x000D_ import java.io.ObjectInputStream;_x000D_ import java.io.ObjectOutputStream;_x000D_ import java.io.OutputStream;_x000D_ _x000D_ import javax.imageio.ImageIO;_x000D_ _x000D_ import nl.minvenj.nfi.prnu.filter.FastNoiseFilter;_x000D_ import nl.minvenj.nfi.prnu.filter.ImageFilter;_x000D_ import nl.minvenj.nfi.prnu.filter.WienerFilter;_x000D_ import nl.minvenj.nfi.prnu.filter.ZeroMeanTotalFilter;_x000D_ _x000D_ public final class PrnuExtract {_x000D_ static final File TESTDATA_FOLDER = new File("testdata");_x000D_ _x000D_ static final File INPUT_FOLDER = new File(TESTDATA_FOLDER, "input");_x000D_ // public static final File INPUT_FILE = new File(INPUT_FOLDER, "test.jpg");_x000D_ public static final File INPUT_FILE = new File("/var/scratch/bwn200/Dresden/2748x3664/Kodak_M1063_4_12664.JPG");_x000D_ static final File EXPECTED_PATTERN_FILE = new File(INPUT_FOLDER, "expected.pat");_x000D_ _x000D_ static final File OUTPUT_FOLDER = new File(TESTDATA_FOLDER, "output");_x000D_ static final File OUTPUT_FILE = new File(OUTPUT_FOLDER, "test.pat");_x000D_ _x000D_ public static void main(final String[] args) throws IOException {_x000D_ long start = System.currentTimeMillis();_x000D_ long end = 0;_x000D_ _x000D_ // Laad de<SUF> final BufferedImage image = readImage(INPUT_FILE);_x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Load image: " + (end-start) + " ms.");_x000D_ _x000D_ // Zet de input file om in 3 matrices (rood, groen, blauw)_x000D_ start = System.currentTimeMillis();_x000D_ final float[][][] rgbArrays = convertImageToFloatArrays(image);_x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Convert image:" + (end-start) + " ms.");_x000D_ _x000D_ // Bereken van elke matrix het PRNU patroon (extractie stap)_x000D_ start = System.currentTimeMillis();_x000D_ for (int i = 0; i < 3; i++) {_x000D_ extractImage(rgbArrays[i]);_x000D_ }_x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("PRNU extracted: " + (end-start) + " ms.");_x000D_ _x000D_ // Schrijf het patroon weg als een Java object_x000D_ writeJavaObject(rgbArrays, OUTPUT_FILE);_x000D_ _x000D_ System.out.println("Pattern written");_x000D_ _x000D_ // Controleer nu het gemaakte bestand_x000D_ final float[][][] expectedPattern = (float[][][]) readJavaObject(EXPECTED_PATTERN_FILE);_x000D_ final float[][][] actualPattern = (float[][][]) readJavaObject(OUTPUT_FILE);_x000D_ for (int i = 0; i < 3; i++) {_x000D_ // Het patroon zoals dat uit PRNU Compare komt, bevat een extra matrix voor transparantie. Deze moeten we overslaan (+1)!_x000D_ compare2DArray(expectedPattern[i + 1], actualPattern[i], 0.0001f);_x000D_ }_x000D_ _x000D_ System.out.println("Validation completed");_x000D_ _x000D_ //This exit is inserted because the program will otherwise hang for a about a minute_x000D_ //most likely explanation for this is the fact that the FFT library spawns a couple_x000D_ //of threads which cannot be properly destroyed_x000D_ System.exit(0);_x000D_ }_x000D_ _x000D_ private static BufferedImage readImage(final File file) throws IOException {_x000D_ final InputStream fileInputStream = new FileInputStream(file);_x000D_ try {_x000D_ final BufferedImage image = ImageIO.read(new BufferedInputStream(fileInputStream));_x000D_ if ((image != null) && (image.getWidth() >= 0) && (image.getHeight() >= 0)) {_x000D_ return image;_x000D_ }_x000D_ }_x000D_ catch (final CMMException e) {_x000D_ // Image file is unsupported or corrupt_x000D_ }_x000D_ catch (final RuntimeException e) {_x000D_ // Internal error processing image file_x000D_ }_x000D_ catch (final IOException e) {_x000D_ // Error reading image from disk_x000D_ }_x000D_ finally {_x000D_ fileInputStream.close();_x000D_ }_x000D_ _x000D_ // Image unreadable or too smalld array_x000D_ return null;_x000D_ }_x000D_ _x000D_ private static float[][][] convertImageToFloatArrays(final BufferedImage image) {_x000D_ final int width = image.getWidth();_x000D_ final int height = image.getHeight();_x000D_ final float[][][] pixels = new float[3][height][width];_x000D_ _x000D_ final ColorModel colorModel = ColorModel.getRGBdefault();_x000D_ for (int y = 0; y < height; y++) {_x000D_ for (int x = 0; x < width; x++) {_x000D_ final int pixel = image.getRGB(x, y); // aa bb gg rr_x000D_ pixels[0][y][x] = colorModel.getRed(pixel);_x000D_ pixels[1][y][x] = colorModel.getGreen(pixel);_x000D_ pixels[2][y][x] = colorModel.getBlue(pixel);_x000D_ }_x000D_ }_x000D_ return pixels;_x000D_ }_x000D_ _x000D_ private static void extractImage(final float[][] pixels) {_x000D_ final int width = pixels[0].length;_x000D_ final int height = pixels.length;_x000D_ _x000D_ long start = System.currentTimeMillis();_x000D_ long end = 0;_x000D_ _x000D_ final ImageFilter fastNoiseFilter = new FastNoiseFilter(width, height);_x000D_ fastNoiseFilter.apply(pixels);_x000D_ _x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Fast Noise Filter: " + (end-start) + " ms.");_x000D_ _x000D_ start = System.currentTimeMillis();_x000D_ final ImageFilter zeroMeanTotalFilter = new ZeroMeanTotalFilter(width, height);_x000D_ zeroMeanTotalFilter.apply(pixels);_x000D_ _x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Zero Mean Filter: " + (end-start) + " ms.");_x000D_ _x000D_ start = System.currentTimeMillis();_x000D_ final ImageFilter wienerFilter = new WienerFilter(width, height);_x000D_ wienerFilter.apply(pixels);_x000D_ _x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Wiener Filter: " + (end-start) + " ms.");_x000D_ }_x000D_ _x000D_ public static Object readJavaObject(final File inputFile) throws IOException {_x000D_ final ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile)));_x000D_ try {_x000D_ return inputStream.readObject();_x000D_ }_x000D_ catch (final ClassNotFoundException e) {_x000D_ throw new IOException("Cannot read pattern: " + inputFile.getAbsolutePath(), e);_x000D_ }_x000D_ finally {_x000D_ inputStream.close();_x000D_ }_x000D_ }_x000D_ _x000D_ private static void writeJavaObject(final Object object, final File outputFile) throws IOException {_x000D_ final OutputStream outputStream = new FileOutputStream(outputFile);_x000D_ try {_x000D_ final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream));_x000D_ objectOutputStream.writeObject(object);_x000D_ objectOutputStream.close();_x000D_ }_x000D_ finally {_x000D_ outputStream.close();_x000D_ }_x000D_ }_x000D_ _x000D_ private static boolean compare2DArray(final float[][] expected, final float[][] actual, final float delta) {_x000D_ for (int i = 0; i < expected.length; i++) {_x000D_ for (int j = 0; j < expected[i].length; j++) {_x000D_ if (Math.abs(actual[i][j] - expected[i][j]) > delta) {_x000D_ System.err.println("de waarde op " + i + "," + j + " is " + actual[i][j] + " maar had moeten zijn " + expected[i][j]);_x000D_ return false;_x000D_ }_x000D_ }_x000D_ }_x000D_ return true;_x000D_ }_x000D_ _x000D_ }_x000D_
True
2,837
13
3,105
14
3,214
14
3,105
14
3,450
14
false
false
false
false
false
true
1,833
125434_2
/* * This class is distributed as part of the Botania Mod. * Get the Source Code in github: * https://github.com/Vazkii/Botania * * Botania is Open Source and distributed under the * Botania License: http://botaniamod.net/license.php */ package vazkii.botania.common.entity; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.vehicle.AbstractMinecart; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import org.jetbrains.annotations.NotNull; import vazkii.botania.api.mana.ManaPool; import vazkii.botania.client.fx.WispParticleData; import vazkii.botania.common.annotations.SoftImplement; import vazkii.botania.common.block.BotaniaBlocks; import vazkii.botania.common.block.block_entity.mana.ManaPoolBlockEntity; import vazkii.botania.common.block.block_entity.mana.ManaPumpBlockEntity; import vazkii.botania.common.item.BotaniaItems; import vazkii.botania.xplat.XplatAbstractions; public class ManaPoolMinecartEntity extends AbstractMinecart { private static final int TRANSFER_RATE = 10000; private static final String TAG_MANA = "mana"; private static final EntityDataAccessor<Integer> MANA = SynchedEntityData.defineId(ManaPoolMinecartEntity.class, EntityDataSerializers.INT); public ManaPoolMinecartEntity(EntityType<ManaPoolMinecartEntity> type, Level world) { super(type, world); } public ManaPoolMinecartEntity(Level world, double x, double y, double z) { super(BotaniaEntities.POOL_MINECART, world, x, y, z); } @Override protected void defineSynchedData() { super.defineSynchedData(); entityData.define(MANA, 0); } @NotNull @Override public BlockState getDisplayBlockState() { return BotaniaBlocks.manaPool.defaultBlockState(); } @NotNull @Override public AbstractMinecart.Type getMinecartType() { return Type.RIDEABLE; } @Override protected boolean canAddPassenger(Entity passenger) { return false; } @Override protected void applyNaturalSlowdown() { float f = 0.98F; this.setDeltaMovement(getDeltaMovement().multiply(f, 0, f)); } @NotNull @Override public ItemStack getPickResult() { return new ItemStack(BotaniaItems.poolMinecart); } @Override public int getDefaultDisplayOffset() { return 8; } @Override public void tick() { super.tick(); if (level().isClientSide) { double particleChance = 1F - (double) getMana() / (double) ManaPoolBlockEntity.MAX_MANA * 0.1; int color = ManaPoolBlockEntity.PARTICLE_COLOR; float red = (color >> 16 & 0xFF) / 255F; float green = (color >> 8 & 0xFF) / 255F; float blue = (color & 0xFF) / 255F; double x = Mth.floor(getX()); double y = Mth.floor(getY()); double z = Mth.floor(getZ()); if (Math.random() > particleChance) { WispParticleData data = WispParticleData.wisp((float) Math.random() / 3F, red, green, blue, 2F); level().addParticle(data, x + 0.3 + Math.random() * 0.5, y + 0.85 + Math.random() * 0.25, z + Math.random(), 0, (float) Math.random() / 25F, 0); } } } @Override public void moveAlongTrack(BlockPos pos, BlockState state) { super.moveAlongTrack(pos, state); for (Direction dir : Direction.Plane.HORIZONTAL) { BlockPos pumpPos = pos.relative(dir); BlockState pumpState = level().getBlockState(pumpPos); if (pumpState.is(BotaniaBlocks.pump)) { ManaPumpBlockEntity pump = (ManaPumpBlockEntity) level().getBlockEntity(pumpPos); BlockPos poolPos = pumpPos.relative(dir); var receiver = XplatAbstractions.INSTANCE.findManaReceiver(level(), poolPos, dir.getOpposite()); if (receiver instanceof ManaPool pool) { Direction pumpDir = pumpState.getValue(BlockStateProperties.HORIZONTAL_FACING); boolean did = false; boolean can = false; if (pumpDir == dir) { // Pool -> Cart can = true; if (!pump.hasRedstone) { int cartMana = getMana(); int poolMana = pool.getCurrentMana(); int transfer = Math.min(TRANSFER_RATE, poolMana); int actualTransfer = Math.min(ManaPoolBlockEntity.MAX_MANA - cartMana, transfer); if (actualTransfer > 0) { pool.receiveMana(-transfer); setMana(cartMana + actualTransfer); did = true; } } } else if (pumpDir == dir.getOpposite()) { // Cart -> Pool can = true; if (!pump.hasRedstone && !pool.isFull()) { int cartMana = getMana(); int transfer = Math.min(TRANSFER_RATE, cartMana); if (transfer > 0) { pool.receiveMana(transfer); setMana(cartMana - transfer); did = true; } } } if (did) { pump.hasCart = true; pump.setActive(true); } if (can) { pump.hasCartOnTop = true; pump.comparator = (int) ((double) getMana() / (double) ManaPoolBlockEntity.MAX_MANA * 15); // different from ManaPoolBlockEntity.calculateComparatorLevel, kept for compatibility } } } } } @Override protected void addAdditionalSaveData(@NotNull CompoundTag cmp) { super.addAdditionalSaveData(cmp); cmp.putInt(TAG_MANA, getMana()); } @Override protected void readAdditionalSaveData(CompoundTag cmp) { super.readAdditionalSaveData(cmp); setMana(cmp.getInt(TAG_MANA)); } @Override public Item getDropItem() { return BotaniaItems.poolMinecart; } @SoftImplement("IForgeMinecart") public int getComparatorLevel() { return ManaPoolBlockEntity.calculateComparatorLevel(getMana(), ManaPoolBlockEntity.MAX_MANA); } public int getMana() { return entityData.get(MANA); } public void setMana(int mana) { entityData.set(MANA, mana); } }
VazkiiMods/Botania
Xplat/src/main/java/vazkii/botania/common/entity/ManaPoolMinecartEntity.java
2,189
// Cart -> Pool
line_comment
nl
/* * This class is distributed as part of the Botania Mod. * Get the Source Code in github: * https://github.com/Vazkii/Botania * * Botania is Open Source and distributed under the * Botania License: http://botaniamod.net/license.php */ package vazkii.botania.common.entity; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.vehicle.AbstractMinecart; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import org.jetbrains.annotations.NotNull; import vazkii.botania.api.mana.ManaPool; import vazkii.botania.client.fx.WispParticleData; import vazkii.botania.common.annotations.SoftImplement; import vazkii.botania.common.block.BotaniaBlocks; import vazkii.botania.common.block.block_entity.mana.ManaPoolBlockEntity; import vazkii.botania.common.block.block_entity.mana.ManaPumpBlockEntity; import vazkii.botania.common.item.BotaniaItems; import vazkii.botania.xplat.XplatAbstractions; public class ManaPoolMinecartEntity extends AbstractMinecart { private static final int TRANSFER_RATE = 10000; private static final String TAG_MANA = "mana"; private static final EntityDataAccessor<Integer> MANA = SynchedEntityData.defineId(ManaPoolMinecartEntity.class, EntityDataSerializers.INT); public ManaPoolMinecartEntity(EntityType<ManaPoolMinecartEntity> type, Level world) { super(type, world); } public ManaPoolMinecartEntity(Level world, double x, double y, double z) { super(BotaniaEntities.POOL_MINECART, world, x, y, z); } @Override protected void defineSynchedData() { super.defineSynchedData(); entityData.define(MANA, 0); } @NotNull @Override public BlockState getDisplayBlockState() { return BotaniaBlocks.manaPool.defaultBlockState(); } @NotNull @Override public AbstractMinecart.Type getMinecartType() { return Type.RIDEABLE; } @Override protected boolean canAddPassenger(Entity passenger) { return false; } @Override protected void applyNaturalSlowdown() { float f = 0.98F; this.setDeltaMovement(getDeltaMovement().multiply(f, 0, f)); } @NotNull @Override public ItemStack getPickResult() { return new ItemStack(BotaniaItems.poolMinecart); } @Override public int getDefaultDisplayOffset() { return 8; } @Override public void tick() { super.tick(); if (level().isClientSide) { double particleChance = 1F - (double) getMana() / (double) ManaPoolBlockEntity.MAX_MANA * 0.1; int color = ManaPoolBlockEntity.PARTICLE_COLOR; float red = (color >> 16 & 0xFF) / 255F; float green = (color >> 8 & 0xFF) / 255F; float blue = (color & 0xFF) / 255F; double x = Mth.floor(getX()); double y = Mth.floor(getY()); double z = Mth.floor(getZ()); if (Math.random() > particleChance) { WispParticleData data = WispParticleData.wisp((float) Math.random() / 3F, red, green, blue, 2F); level().addParticle(data, x + 0.3 + Math.random() * 0.5, y + 0.85 + Math.random() * 0.25, z + Math.random(), 0, (float) Math.random() / 25F, 0); } } } @Override public void moveAlongTrack(BlockPos pos, BlockState state) { super.moveAlongTrack(pos, state); for (Direction dir : Direction.Plane.HORIZONTAL) { BlockPos pumpPos = pos.relative(dir); BlockState pumpState = level().getBlockState(pumpPos); if (pumpState.is(BotaniaBlocks.pump)) { ManaPumpBlockEntity pump = (ManaPumpBlockEntity) level().getBlockEntity(pumpPos); BlockPos poolPos = pumpPos.relative(dir); var receiver = XplatAbstractions.INSTANCE.findManaReceiver(level(), poolPos, dir.getOpposite()); if (receiver instanceof ManaPool pool) { Direction pumpDir = pumpState.getValue(BlockStateProperties.HORIZONTAL_FACING); boolean did = false; boolean can = false; if (pumpDir == dir) { // Pool -> Cart can = true; if (!pump.hasRedstone) { int cartMana = getMana(); int poolMana = pool.getCurrentMana(); int transfer = Math.min(TRANSFER_RATE, poolMana); int actualTransfer = Math.min(ManaPoolBlockEntity.MAX_MANA - cartMana, transfer); if (actualTransfer > 0) { pool.receiveMana(-transfer); setMana(cartMana + actualTransfer); did = true; } } } else if (pumpDir == dir.getOpposite()) { // Cart -><SUF> can = true; if (!pump.hasRedstone && !pool.isFull()) { int cartMana = getMana(); int transfer = Math.min(TRANSFER_RATE, cartMana); if (transfer > 0) { pool.receiveMana(transfer); setMana(cartMana - transfer); did = true; } } } if (did) { pump.hasCart = true; pump.setActive(true); } if (can) { pump.hasCartOnTop = true; pump.comparator = (int) ((double) getMana() / (double) ManaPoolBlockEntity.MAX_MANA * 15); // different from ManaPoolBlockEntity.calculateComparatorLevel, kept for compatibility } } } } } @Override protected void addAdditionalSaveData(@NotNull CompoundTag cmp) { super.addAdditionalSaveData(cmp); cmp.putInt(TAG_MANA, getMana()); } @Override protected void readAdditionalSaveData(CompoundTag cmp) { super.readAdditionalSaveData(cmp); setMana(cmp.getInt(TAG_MANA)); } @Override public Item getDropItem() { return BotaniaItems.poolMinecart; } @SoftImplement("IForgeMinecart") public int getComparatorLevel() { return ManaPoolBlockEntity.calculateComparatorLevel(getMana(), ManaPoolBlockEntity.MAX_MANA); } public int getMana() { return entityData.get(MANA); } public void setMana(int mana) { entityData.set(MANA, mana); } }
False
1,586
4
1,980
4
1,919
4
1,980
4
2,450
4
false
false
false
false
false
true
1,004
110179_0
package nl.han.ooad.classes; public class Data { public Vragenlijst getVragenlijst() { String[] antwoorden1 = { "11", "elf" }; String[] antwoorden2 = { "Ottawa" }; String juisteAntwoord1 = "Queen"; String[] fouteAntwoorden1 = { "The Beatles", "Coldplay", "ABBA" }; String juisteAntwoord2 = "50"; String[] fouteAntwoorden2 = { "40", "48", "52" }; Vraag[] vragen = { new OpenVraag("Hoeveel tijdzones zijn er in Rusland", antwoorden1), new OpenVraag("Hoeveel tijdzones zijn er in Rusland", antwoorden2), new MeerkeuzeVraag("Welke band staat het vaakst in de Top 2000 van 2022", juisteAntwoord1, fouteAntwoorden1), new MeerkeuzeVraag("Uit hoeveel staten bestaan de Verenigde Staten", juisteAntwoord2, fouteAntwoorden2) }; return new Vragenlijst(vragen); } } /* * * Open vragen: * 1) * Vraag: Hoeveel tijdzones zijn er in Rusland? * Antwoord: 11 * * 2) * Vraag: Wat is de hoofdstad van Canada? * Antwoord: Ottawa * * Meerkeuze vragen: * 3) * Vraag: Welke band staat het vaakst in de Top 2000 van 2022? * A: The Beatles (fout) * B: coldplay (fout) * C: Queen (goed) * D: ABBA (fout) * * 4) * Vraag: Uit hoeveel staten bestaan de Verenigde Staten? * A: 40 (fout) * B: 48 (fout) * C: 50 (goed) * D: 52 (fout) */
MAGerritsen/finch
finch/src/main/java/nl/han/ooad/classes/Data.java
526
/* * * Open vragen: * 1) * Vraag: Hoeveel tijdzones zijn er in Rusland? * Antwoord: 11 * * 2) * Vraag: Wat is de hoofdstad van Canada? * Antwoord: Ottawa * * Meerkeuze vragen: * 3) * Vraag: Welke band staat het vaakst in de Top 2000 van 2022? * A: The Beatles (fout) * B: coldplay (fout) * C: Queen (goed) * D: ABBA (fout) * * 4) * Vraag: Uit hoeveel staten bestaan de Verenigde Staten? * A: 40 (fout) * B: 48 (fout) * C: 50 (goed) * D: 52 (fout) */
block_comment
nl
package nl.han.ooad.classes; public class Data { public Vragenlijst getVragenlijst() { String[] antwoorden1 = { "11", "elf" }; String[] antwoorden2 = { "Ottawa" }; String juisteAntwoord1 = "Queen"; String[] fouteAntwoorden1 = { "The Beatles", "Coldplay", "ABBA" }; String juisteAntwoord2 = "50"; String[] fouteAntwoorden2 = { "40", "48", "52" }; Vraag[] vragen = { new OpenVraag("Hoeveel tijdzones zijn er in Rusland", antwoorden1), new OpenVraag("Hoeveel tijdzones zijn er in Rusland", antwoorden2), new MeerkeuzeVraag("Welke band staat het vaakst in de Top 2000 van 2022", juisteAntwoord1, fouteAntwoorden1), new MeerkeuzeVraag("Uit hoeveel staten bestaan de Verenigde Staten", juisteAntwoord2, fouteAntwoorden2) }; return new Vragenlijst(vragen); } } /* * * Open vragen: <SUF>*/
True
485
200
582
248
466
205
582
248
586
236
false
true
false
true
false
false
4,043
11912_5
package xdi2.core.features.digests; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import xdi2.core.ContextNode; import xdi2.core.Graph; import xdi2.core.constants.XDIConstants; import xdi2.core.constants.XDISecurityConstants; import xdi2.core.features.datatypes.DataTypes; import xdi2.core.features.nodetypes.XdiAbstractAttribute; import xdi2.core.features.nodetypes.XdiAbstractAttribute.MappingContextNodeXdiAttributeIterator; import xdi2.core.features.nodetypes.XdiAbstractContext; import xdi2.core.features.nodetypes.XdiAttribute; import xdi2.core.features.nodetypes.XdiAttributeCollection; import xdi2.core.features.nodetypes.XdiAttributeSingleton; import xdi2.core.features.nodetypes.XdiContext; import xdi2.core.syntax.XDIAddress; import xdi2.core.syntax.XDIArc; import xdi2.core.util.CopyUtil.AbstractCopyStrategy; import xdi2.core.util.CopyUtil.CopyStrategy; import xdi2.core.util.iterators.CompositeIterator; import xdi2.core.util.iterators.MappingIterator; import xdi2.core.util.iterators.NotNullIterator; import xdi2.core.util.iterators.ReadOnlyIterator; import xdi2.core.util.iterators.SingleItemIterator; public class Digests { private Digests() { } /** * Given a graph, lists all digests. * @param graph The graph. * @return An iterator over digests. */ public static Iterator<Digest> getAllDigests(Graph graph) { ContextNode root = graph.getRootContextNode(true); Iterator<ContextNode> allContextNodes = root.getAllContextNodes(); return new MappingXdiAttributeDigestIterator(new MappingContextNodeXdiAttributeIterator(allContextNodes)); } /** * Creates an XDI digest on a context node. * @return The XDI digest. */ public static Digest createDigest(ContextNode contextNode, String digestAlgorithm, Integer digestVersion, boolean singleton) { XdiAttribute digestXdiAttribute; if (singleton) digestXdiAttribute = XdiAbstractContext.fromContextNode(contextNode).getXdiAttributeSingleton(XdiAttributeSingleton.createXDIArc(XDISecurityConstants.XDI_ARC_DIGEST), true); else digestXdiAttribute = XdiAbstractContext.fromContextNode(contextNode).getXdiAttributeCollection(XdiAttributeCollection.createXDIArc(XDISecurityConstants.XDI_ARC_DIGEST), true).setXdiInstanceUnordered(true, false); XDIAddress dataTypeXDIAddress = createDataTypeXDIAddress(digestAlgorithm, digestVersion); if (dataTypeXDIAddress != null) DataTypes.setDataType(digestXdiAttribute.getContextNode(), dataTypeXDIAddress); return Digest.fromXdiAttribute(digestXdiAttribute); } /** * Returns the XDI digests on a context node. */ public static ReadOnlyIterator<Digest> getDigests(ContextNode contextNode) { List<Iterator<? extends Digest>> iterators = new ArrayList<Iterator<? extends Digest>> (); XdiContext<?> xdiContext = XdiAbstractContext.fromContextNode(contextNode); // add digest that is an XDI attribute singleton XdiAttributeSingleton digestAttributeSingleton = xdiContext.getXdiAttributeSingleton(XdiAttributeSingleton.createXDIArc(XDISecurityConstants.XDI_ARC_DIGEST), false); Digest digestSingleton = digestAttributeSingleton == null ? null : Digest.fromXdiAttribute(digestAttributeSingleton); if (digestSingleton != null) iterators.add(new SingleItemIterator<Digest> (digestSingleton)); // add digests that are XDI attribute instances XdiAttributeCollection digestAttributeCollection = xdiContext.getXdiAttributeCollection(XdiAttributeCollection.createXDIArc(XDISecurityConstants.XDI_ARC_DIGEST), false); if (digestAttributeCollection != null) iterators.add(new MappingXdiAttributeDigestIterator(digestAttributeCollection.getXdiInstancesDeref())); return new CompositeIterator<Digest> (iterators.iterator()); } /* * Helper methods */ public static String getDigestAlgorithm(XdiAttribute xdiAttribute) { XDIAddress dataTypeXDIAddress = DataTypes.getDataType(xdiAttribute.getContextNode()); return dataTypeXDIAddress == null ? null : getDigestAlgorithm(dataTypeXDIAddress); } public static String getDigestAlgorithm(XDIAddress dataTypeXDIAddress) { XDIArc digestAlgorithmAddress = dataTypeXDIAddress.getNumXDIArcs() > 1 ? dataTypeXDIAddress.getXDIArc(0) : null; if (digestAlgorithmAddress == null) return null; if (! XDIConstants.CS_CLASS_RESERVED.equals(digestAlgorithmAddress.getCs())) return null; if (digestAlgorithmAddress.hasXRef()) return null; if (! digestAlgorithmAddress.hasLiteral()) return null; return digestAlgorithmAddress.getLiteral(); } public static Integer getDigestVersion(XdiAttribute xdiAttribute) { XDIAddress dataTypeXDIAddress = DataTypes.getDataType(xdiAttribute.getContextNode()); return dataTypeXDIAddress == null ? null : getDigestVersion(dataTypeXDIAddress); } public static Integer getDigestVersion(XDIAddress dataTypeXDIAddress) { XDIArc digestVersionAddress = dataTypeXDIAddress.getNumXDIArcs() > 1 ? dataTypeXDIAddress.getXDIArc(1) : null; if (digestVersionAddress == null) return null; if (! XDIConstants.CS_CLASS_RESERVED.equals(digestVersionAddress.getCs())) return null; if (digestVersionAddress.hasXRef()) return null; if (! digestVersionAddress.hasLiteral()) return null; return Integer.valueOf(digestVersionAddress.getLiteral()); } public static XDIAddress createDataTypeXDIAddress(String digestAlgorithm, Integer digestVersion) { StringBuilder builder = new StringBuilder(); if (digestAlgorithm != null) builder.append(XDIConstants.CS_CLASS_RESERVED + digestAlgorithm.toLowerCase()); if (digestVersion != null) builder.append(XDIConstants.CS_CLASS_RESERVED + digestVersion.toString()); if (builder.length() == 0) return null; return XDIAddress.create(builder.toString()); } /* * Helper classes */ public static class NoDigestsCopyStrategy extends AbstractCopyStrategy implements CopyStrategy { @Override public List<ContextNode> replaceContextNode(ContextNode contextNode) { if (contextNode == null) throw new NullPointerException(); XdiAttribute xdiAttribute = XdiAbstractAttribute.fromContextNode(contextNode); if (xdiAttribute == null) return null; Digest digest = Digest.fromXdiAttribute(xdiAttribute); if (digest == null) return null; return Collections.emptyList(); } } public static class MappingXdiAttributeDigestIterator extends NotNullIterator<Digest> { public MappingXdiAttributeDigestIterator(Iterator<XdiAttribute> iterator) { super(new MappingIterator<XdiAttribute, Digest> (iterator) { @Override public Digest map(XdiAttribute xdiAttribute) { return Digest.fromXdiAttribute(xdiAttribute); } }); } } }
projectdanube/xdi2
core/src/main/java/xdi2/core/features/digests/Digests.java
2,020
/* * Helper methods */
block_comment
nl
package xdi2.core.features.digests; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import xdi2.core.ContextNode; import xdi2.core.Graph; import xdi2.core.constants.XDIConstants; import xdi2.core.constants.XDISecurityConstants; import xdi2.core.features.datatypes.DataTypes; import xdi2.core.features.nodetypes.XdiAbstractAttribute; import xdi2.core.features.nodetypes.XdiAbstractAttribute.MappingContextNodeXdiAttributeIterator; import xdi2.core.features.nodetypes.XdiAbstractContext; import xdi2.core.features.nodetypes.XdiAttribute; import xdi2.core.features.nodetypes.XdiAttributeCollection; import xdi2.core.features.nodetypes.XdiAttributeSingleton; import xdi2.core.features.nodetypes.XdiContext; import xdi2.core.syntax.XDIAddress; import xdi2.core.syntax.XDIArc; import xdi2.core.util.CopyUtil.AbstractCopyStrategy; import xdi2.core.util.CopyUtil.CopyStrategy; import xdi2.core.util.iterators.CompositeIterator; import xdi2.core.util.iterators.MappingIterator; import xdi2.core.util.iterators.NotNullIterator; import xdi2.core.util.iterators.ReadOnlyIterator; import xdi2.core.util.iterators.SingleItemIterator; public class Digests { private Digests() { } /** * Given a graph, lists all digests. * @param graph The graph. * @return An iterator over digests. */ public static Iterator<Digest> getAllDigests(Graph graph) { ContextNode root = graph.getRootContextNode(true); Iterator<ContextNode> allContextNodes = root.getAllContextNodes(); return new MappingXdiAttributeDigestIterator(new MappingContextNodeXdiAttributeIterator(allContextNodes)); } /** * Creates an XDI digest on a context node. * @return The XDI digest. */ public static Digest createDigest(ContextNode contextNode, String digestAlgorithm, Integer digestVersion, boolean singleton) { XdiAttribute digestXdiAttribute; if (singleton) digestXdiAttribute = XdiAbstractContext.fromContextNode(contextNode).getXdiAttributeSingleton(XdiAttributeSingleton.createXDIArc(XDISecurityConstants.XDI_ARC_DIGEST), true); else digestXdiAttribute = XdiAbstractContext.fromContextNode(contextNode).getXdiAttributeCollection(XdiAttributeCollection.createXDIArc(XDISecurityConstants.XDI_ARC_DIGEST), true).setXdiInstanceUnordered(true, false); XDIAddress dataTypeXDIAddress = createDataTypeXDIAddress(digestAlgorithm, digestVersion); if (dataTypeXDIAddress != null) DataTypes.setDataType(digestXdiAttribute.getContextNode(), dataTypeXDIAddress); return Digest.fromXdiAttribute(digestXdiAttribute); } /** * Returns the XDI digests on a context node. */ public static ReadOnlyIterator<Digest> getDigests(ContextNode contextNode) { List<Iterator<? extends Digest>> iterators = new ArrayList<Iterator<? extends Digest>> (); XdiContext<?> xdiContext = XdiAbstractContext.fromContextNode(contextNode); // add digest that is an XDI attribute singleton XdiAttributeSingleton digestAttributeSingleton = xdiContext.getXdiAttributeSingleton(XdiAttributeSingleton.createXDIArc(XDISecurityConstants.XDI_ARC_DIGEST), false); Digest digestSingleton = digestAttributeSingleton == null ? null : Digest.fromXdiAttribute(digestAttributeSingleton); if (digestSingleton != null) iterators.add(new SingleItemIterator<Digest> (digestSingleton)); // add digests that are XDI attribute instances XdiAttributeCollection digestAttributeCollection = xdiContext.getXdiAttributeCollection(XdiAttributeCollection.createXDIArc(XDISecurityConstants.XDI_ARC_DIGEST), false); if (digestAttributeCollection != null) iterators.add(new MappingXdiAttributeDigestIterator(digestAttributeCollection.getXdiInstancesDeref())); return new CompositeIterator<Digest> (iterators.iterator()); } /* * Helper methods <SUF>*/ public static String getDigestAlgorithm(XdiAttribute xdiAttribute) { XDIAddress dataTypeXDIAddress = DataTypes.getDataType(xdiAttribute.getContextNode()); return dataTypeXDIAddress == null ? null : getDigestAlgorithm(dataTypeXDIAddress); } public static String getDigestAlgorithm(XDIAddress dataTypeXDIAddress) { XDIArc digestAlgorithmAddress = dataTypeXDIAddress.getNumXDIArcs() > 1 ? dataTypeXDIAddress.getXDIArc(0) : null; if (digestAlgorithmAddress == null) return null; if (! XDIConstants.CS_CLASS_RESERVED.equals(digestAlgorithmAddress.getCs())) return null; if (digestAlgorithmAddress.hasXRef()) return null; if (! digestAlgorithmAddress.hasLiteral()) return null; return digestAlgorithmAddress.getLiteral(); } public static Integer getDigestVersion(XdiAttribute xdiAttribute) { XDIAddress dataTypeXDIAddress = DataTypes.getDataType(xdiAttribute.getContextNode()); return dataTypeXDIAddress == null ? null : getDigestVersion(dataTypeXDIAddress); } public static Integer getDigestVersion(XDIAddress dataTypeXDIAddress) { XDIArc digestVersionAddress = dataTypeXDIAddress.getNumXDIArcs() > 1 ? dataTypeXDIAddress.getXDIArc(1) : null; if (digestVersionAddress == null) return null; if (! XDIConstants.CS_CLASS_RESERVED.equals(digestVersionAddress.getCs())) return null; if (digestVersionAddress.hasXRef()) return null; if (! digestVersionAddress.hasLiteral()) return null; return Integer.valueOf(digestVersionAddress.getLiteral()); } public static XDIAddress createDataTypeXDIAddress(String digestAlgorithm, Integer digestVersion) { StringBuilder builder = new StringBuilder(); if (digestAlgorithm != null) builder.append(XDIConstants.CS_CLASS_RESERVED + digestAlgorithm.toLowerCase()); if (digestVersion != null) builder.append(XDIConstants.CS_CLASS_RESERVED + digestVersion.toString()); if (builder.length() == 0) return null; return XDIAddress.create(builder.toString()); } /* * Helper classes */ public static class NoDigestsCopyStrategy extends AbstractCopyStrategy implements CopyStrategy { @Override public List<ContextNode> replaceContextNode(ContextNode contextNode) { if (contextNode == null) throw new NullPointerException(); XdiAttribute xdiAttribute = XdiAbstractAttribute.fromContextNode(contextNode); if (xdiAttribute == null) return null; Digest digest = Digest.fromXdiAttribute(xdiAttribute); if (digest == null) return null; return Collections.emptyList(); } } public static class MappingXdiAttributeDigestIterator extends NotNullIterator<Digest> { public MappingXdiAttributeDigestIterator(Iterator<XdiAttribute> iterator) { super(new MappingIterator<XdiAttribute, Digest> (iterator) { @Override public Digest map(XdiAttribute xdiAttribute) { return Digest.fromXdiAttribute(xdiAttribute); } }); } } }
False
1,525
8
1,819
7
1,836
9
1,819
7
2,184
10
false
false
false
false
false
true
1
18424_13
package com.example.idek; import androidx.appcompat.app.AppCompatActivity; import androidx.camera.core.CameraX; import androidx.camera.core.ImageAnalysis; import androidx.camera.core.ImageAnalysisConfig; import androidx.camera.core.ImageCapture; import androidx.camera.core.ImageCaptureConfig; import androidx.camera.core.ImageProxy; import androidx.camera.core.Preview; import androidx.camera.core.PreviewConfig; import androidx.lifecycle.LifecycleOwner; import android.graphics.Rect; import android.os.Bundle; import android.util.Log; import android.util.Rational; import android.util.Size; import android.view.TextureView; import android.view.ViewGroup; import android.widget.Toast; import com.google.zxing.BinaryBitmap; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.PlanarYUVLuminanceSource; import com.google.zxing.common.HybridBinarizer; import java.nio.ByteBuffer; //ik haat mijzelf dus daarom maak ik een camera ding met een api dat nog niet eens in de beta stage is //en waarvan de tutorial in een taal is dat ik 0% begrijp //saus: https://codelabs.developers.google.com/codelabs/camerax-getting-started/ public class MainActivity extends AppCompatActivity { //private int REQUEST_CODE_PERMISSIONS = 10; //idek volgens tutorial is dit een arbitraire nummer zou helpen als je app meerdere toestimmingen vraagt //private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"}; //array met permissions vermeld in manifest TextureView txView; String result = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txView = findViewById(R.id.view_finder); startCamera(); /*if(allPermissionsGranted()){ } else{ ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS); }*/ } private void startCamera() {//heel veel dingen gebeuren hier //eerst zeker zijn dat de camera niet gebruikt wordt. CameraX.unbindAll(); /* doe preview weergeven */ int aspRatioW = txView.getWidth(); //haalt breedte scherm op int aspRatioH = txView.getHeight(); //haalt hoogte scherm op Rational asp = new Rational (aspRatioW, aspRatioH); //helpt bij zetten aspect ratio Size screen = new Size(aspRatioW, aspRatioH); //grootte scherm ofc PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build(); Preview pview = new Preview(pConfig); pview.setOnPreviewOutputUpdateListener( new Preview.OnPreviewOutputUpdateListener() { //eigenlijk maakt dit al een nieuwe texturesurface aan //maar aangezien ik al eentje heb gemaakt aan het begin... @Override public void onUpdated(Preview.PreviewOutput output){ ViewGroup parent = (ViewGroup) txView.getParent(); parent.removeView(txView); //moeten wij hem eerst yeeten parent.addView(txView, 0); txView.setSurfaceTexture(output.getSurfaceTexture()); //dan weer toevoegen //updateTransform(); //en dan updaten } }); /* image capture */ /*ImageCaptureConfig imgConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build(); ImageCapture imgCap = new ImageCapture(imgConfig);*/ /* image analyser */ ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build(); final ImageAnalysis imgAsys = new ImageAnalysis(imgAConfig); imgAsys.setAnalyzer( new ImageAnalysis.Analyzer(){ @Override public void analyze(ImageProxy image, int rotationDegrees){ try { ByteBuffer bf = image.getPlanes()[0].getBuffer(); byte[] b = new byte[bf.capacity()]; bf.get(b); Rect r = image.getCropRect(); int w = image.getWidth(); int h = image.getHeight(); PlanarYUVLuminanceSource sauce = new PlanarYUVLuminanceSource(b ,w, h, r.left, r.top, r.width(), r.height(),false); BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(sauce)); result = new qrReader().decoded(bit); System.out.println(result); Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show(); Log.wtf("F: ", result); } catch (NotFoundException e) { e.printStackTrace(); } catch (FormatException e) { e.printStackTrace(); } } } ); //bindt de shit hierboven aan de lifecycle: CameraX.bindToLifecycle((LifecycleOwner)this, imgAsys, /*imgCap,*/ pview); } /*private void updateTransform(){ //compenseert veranderingen in orientatie voor viewfinder, aangezien de rest van de layout in portrait mode blijft. //methinks :thonk: Matrix mx = new Matrix(); float w = txView.getMeasuredWidth(); float h = txView.getMeasuredHeight(); //berekent het midden float cX = w / 2f; float cY = h / 2f; int rotDgr; //voor de switch < propt in hoeveel graden shit is gekanteld //Display a = txView.getDisplay(); //ok dan stoppen wij .getdisplay in z'n eigen shit. int rtrn = (int)txView.getRotation(); //dan dit maar in een aparte int zetten want alles deed boem bij het opstarten //omfg het komt omdat .getDisplay erin zit. switch(rtrn){ case Surface.ROTATION_0: rotDgr = 0; break; case Surface.ROTATION_90: rotDgr = 90; break; case Surface.ROTATION_180: rotDgr = 180; break; case Surface.ROTATION_270: rotDgr = 270; break; default: return; } mx.postRotate((float)rotDgr, cX, cY); //berekent preview out put aan de hand van hoe de toestel gedraaid is float buffer = txView.getMeasuredHeight() / txView.getMeasuredWidth() ; int scaleW; int scaleH; if(w > h){ //center-crop transformation scaleH = (int)w; scaleW = Math.round(w * buffer); } else{ scaleH = (int)h; scaleW = Math.round(h * buffer); } float x = scaleW / w; //doet schaal berekenen float y = scaleH / h; mx.preScale(x, y, cX, cY); //vult preview op txView.setTransform(mx); //past dit op preview toe } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //als alle permissies zijn toegestaan start camera if(requestCode == REQUEST_CODE_PERMISSIONS){ if(allPermissionsGranted()){ startCamera(); } else{ Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show(); finish(); } } } private boolean allPermissionsGranted(){ //kijken of alle permissies zijn toegestaan for(String permission : REQUIRED_PERMISSIONS){ if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){ return false; } } return true; }*/ }
0974201/code-bin
java/backup camerax proj.java
2,322
//maar aangezien ik al eentje heb gemaakt aan het begin...
line_comment
nl
package com.example.idek; import androidx.appcompat.app.AppCompatActivity; import androidx.camera.core.CameraX; import androidx.camera.core.ImageAnalysis; import androidx.camera.core.ImageAnalysisConfig; import androidx.camera.core.ImageCapture; import androidx.camera.core.ImageCaptureConfig; import androidx.camera.core.ImageProxy; import androidx.camera.core.Preview; import androidx.camera.core.PreviewConfig; import androidx.lifecycle.LifecycleOwner; import android.graphics.Rect; import android.os.Bundle; import android.util.Log; import android.util.Rational; import android.util.Size; import android.view.TextureView; import android.view.ViewGroup; import android.widget.Toast; import com.google.zxing.BinaryBitmap; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.PlanarYUVLuminanceSource; import com.google.zxing.common.HybridBinarizer; import java.nio.ByteBuffer; //ik haat mijzelf dus daarom maak ik een camera ding met een api dat nog niet eens in de beta stage is //en waarvan de tutorial in een taal is dat ik 0% begrijp //saus: https://codelabs.developers.google.com/codelabs/camerax-getting-started/ public class MainActivity extends AppCompatActivity { //private int REQUEST_CODE_PERMISSIONS = 10; //idek volgens tutorial is dit een arbitraire nummer zou helpen als je app meerdere toestimmingen vraagt //private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"}; //array met permissions vermeld in manifest TextureView txView; String result = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txView = findViewById(R.id.view_finder); startCamera(); /*if(allPermissionsGranted()){ } else{ ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS); }*/ } private void startCamera() {//heel veel dingen gebeuren hier //eerst zeker zijn dat de camera niet gebruikt wordt. CameraX.unbindAll(); /* doe preview weergeven */ int aspRatioW = txView.getWidth(); //haalt breedte scherm op int aspRatioH = txView.getHeight(); //haalt hoogte scherm op Rational asp = new Rational (aspRatioW, aspRatioH); //helpt bij zetten aspect ratio Size screen = new Size(aspRatioW, aspRatioH); //grootte scherm ofc PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build(); Preview pview = new Preview(pConfig); pview.setOnPreviewOutputUpdateListener( new Preview.OnPreviewOutputUpdateListener() { //eigenlijk maakt dit al een nieuwe texturesurface aan //maar aangezien<SUF> @Override public void onUpdated(Preview.PreviewOutput output){ ViewGroup parent = (ViewGroup) txView.getParent(); parent.removeView(txView); //moeten wij hem eerst yeeten parent.addView(txView, 0); txView.setSurfaceTexture(output.getSurfaceTexture()); //dan weer toevoegen //updateTransform(); //en dan updaten } }); /* image capture */ /*ImageCaptureConfig imgConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build(); ImageCapture imgCap = new ImageCapture(imgConfig);*/ /* image analyser */ ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build(); final ImageAnalysis imgAsys = new ImageAnalysis(imgAConfig); imgAsys.setAnalyzer( new ImageAnalysis.Analyzer(){ @Override public void analyze(ImageProxy image, int rotationDegrees){ try { ByteBuffer bf = image.getPlanes()[0].getBuffer(); byte[] b = new byte[bf.capacity()]; bf.get(b); Rect r = image.getCropRect(); int w = image.getWidth(); int h = image.getHeight(); PlanarYUVLuminanceSource sauce = new PlanarYUVLuminanceSource(b ,w, h, r.left, r.top, r.width(), r.height(),false); BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(sauce)); result = new qrReader().decoded(bit); System.out.println(result); Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show(); Log.wtf("F: ", result); } catch (NotFoundException e) { e.printStackTrace(); } catch (FormatException e) { e.printStackTrace(); } } } ); //bindt de shit hierboven aan de lifecycle: CameraX.bindToLifecycle((LifecycleOwner)this, imgAsys, /*imgCap,*/ pview); } /*private void updateTransform(){ //compenseert veranderingen in orientatie voor viewfinder, aangezien de rest van de layout in portrait mode blijft. //methinks :thonk: Matrix mx = new Matrix(); float w = txView.getMeasuredWidth(); float h = txView.getMeasuredHeight(); //berekent het midden float cX = w / 2f; float cY = h / 2f; int rotDgr; //voor de switch < propt in hoeveel graden shit is gekanteld //Display a = txView.getDisplay(); //ok dan stoppen wij .getdisplay in z'n eigen shit. int rtrn = (int)txView.getRotation(); //dan dit maar in een aparte int zetten want alles deed boem bij het opstarten //omfg het komt omdat .getDisplay erin zit. switch(rtrn){ case Surface.ROTATION_0: rotDgr = 0; break; case Surface.ROTATION_90: rotDgr = 90; break; case Surface.ROTATION_180: rotDgr = 180; break; case Surface.ROTATION_270: rotDgr = 270; break; default: return; } mx.postRotate((float)rotDgr, cX, cY); //berekent preview out put aan de hand van hoe de toestel gedraaid is float buffer = txView.getMeasuredHeight() / txView.getMeasuredWidth() ; int scaleW; int scaleH; if(w > h){ //center-crop transformation scaleH = (int)w; scaleW = Math.round(w * buffer); } else{ scaleH = (int)h; scaleW = Math.round(h * buffer); } float x = scaleW / w; //doet schaal berekenen float y = scaleH / h; mx.preScale(x, y, cX, cY); //vult preview op txView.setTransform(mx); //past dit op preview toe } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //als alle permissies zijn toegestaan start camera if(requestCode == REQUEST_CODE_PERMISSIONS){ if(allPermissionsGranted()){ startCamera(); } else{ Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show(); finish(); } } } private boolean allPermissionsGranted(){ //kijken of alle permissies zijn toegestaan for(String permission : REQUIRED_PERMISSIONS){ if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){ return false; } } return true; }*/ }
True
1,724
19
1,945
21
1,962
15
1,941
21
2,321
20
false
false
false
false
false
true
1,242
3612_8
/* * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.model; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.StringJoiner; import java.util.Objects; import java.util.Map; import java.util.HashMap; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import java.math.BigDecimal; import java.util.Arrays; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * BananaReq */ @JsonPropertyOrder({ BananaReq.JSON_PROPERTY_LENGTH_CM, BananaReq.JSON_PROPERTY_SWEET }) @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.6.0-SNAPSHOT") public class BananaReq { public static final String JSON_PROPERTY_LENGTH_CM = "lengthCm"; private BigDecimal lengthCm; public static final String JSON_PROPERTY_SWEET = "sweet"; private Boolean sweet; public BananaReq() { } public BananaReq lengthCm(BigDecimal lengthCm) { this.lengthCm = lengthCm; return this; } /** * Get lengthCm * @return lengthCm **/ @javax.annotation.Nonnull @JsonProperty(JSON_PROPERTY_LENGTH_CM) @JsonInclude(value = JsonInclude.Include.ALWAYS) public BigDecimal getLengthCm() { return lengthCm; } @JsonProperty(JSON_PROPERTY_LENGTH_CM) @JsonInclude(value = JsonInclude.Include.ALWAYS) public void setLengthCm(BigDecimal lengthCm) { this.lengthCm = lengthCm; } public BananaReq sweet(Boolean sweet) { this.sweet = sweet; return this; } /** * Get sweet * @return sweet **/ @javax.annotation.Nullable @JsonProperty(JSON_PROPERTY_SWEET) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public Boolean getSweet() { return sweet; } @JsonProperty(JSON_PROPERTY_SWEET) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setSweet(Boolean sweet) { this.sweet = sweet; } /** * Return true if this bananaReq object is equal to o. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BananaReq bananaReq = (BananaReq) o; return Objects.equals(this.lengthCm, bananaReq.lengthCm) && Objects.equals(this.sweet, bananaReq.sweet); } @Override public int hashCode() { return Objects.hash(lengthCm, sweet); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class BananaReq {\n"); sb.append(" lengthCm: ").append(toIndentedString(lengthCm)).append("\n"); sb.append(" sweet: ").append(toIndentedString(sweet)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } /** * Convert the instance into URL query string. * * @return URL query string */ public String toUrlQueryString() { return toUrlQueryString(null); } /** * Convert the instance into URL query string. * * @param prefix prefix of the query string * @return URL query string */ public String toUrlQueryString(String prefix) { String suffix = ""; String containerSuffix = ""; String containerPrefix = ""; if (prefix == null) { // style=form, explode=true, e.g. /pet?name=cat&type=manx prefix = ""; } else { // deepObject style e.g. /pet?id[name]=cat&id[type]=manx prefix = prefix + "["; suffix = "]"; containerSuffix = "]"; containerPrefix = "["; } StringJoiner joiner = new StringJoiner("&"); // add `lengthCm` to the URL query string if (getLengthCm() != null) { joiner.add(String.format("%slengthCm%s=%s", prefix, suffix, URLEncoder.encode(String.valueOf(getLengthCm()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); } // add `sweet` to the URL query string if (getSweet() != null) { joiner.add(String.format("%ssweet%s=%s", prefix, suffix, URLEncoder.encode(String.valueOf(getSweet()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); } return joiner.toString(); } public static class Builder { private BananaReq instance; public Builder() { this(new BananaReq()); } protected Builder(BananaReq instance) { this.instance = instance; } public BananaReq.Builder lengthCm(BigDecimal lengthCm) { this.instance.lengthCm = lengthCm; return this; } public BananaReq.Builder sweet(Boolean sweet) { this.instance.sweet = sweet; return this; } /** * returns a built BananaReq instance. * * The builder is not reusable. */ public BananaReq build() { try { return this.instance; } finally { // ensure that this.instance is not reused this.instance = null; } } @Override public String toString() { return getClass() + "=(" + instance + ")"; } } /** * Create a builder with no initialized field. */ public static BananaReq.Builder builder() { return new BananaReq.Builder(); } /** * Create a builder with a shallow copy of this instance. */ public BananaReq.Builder toBuilder() { return new BananaReq.Builder() .lengthCm(getLengthCm()) .sweet(getSweet()); } }
OpenAPITools/openapi-generator
samples/client/petstore/java/native/src/main/java/org/openapitools/client/model/BananaReq.java
2,071
// deepObject style e.g. /pet?id[name]=cat&id[type]=manx
line_comment
nl
/* * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.model; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.StringJoiner; import java.util.Objects; import java.util.Map; import java.util.HashMap; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import java.math.BigDecimal; import java.util.Arrays; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * BananaReq */ @JsonPropertyOrder({ BananaReq.JSON_PROPERTY_LENGTH_CM, BananaReq.JSON_PROPERTY_SWEET }) @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.6.0-SNAPSHOT") public class BananaReq { public static final String JSON_PROPERTY_LENGTH_CM = "lengthCm"; private BigDecimal lengthCm; public static final String JSON_PROPERTY_SWEET = "sweet"; private Boolean sweet; public BananaReq() { } public BananaReq lengthCm(BigDecimal lengthCm) { this.lengthCm = lengthCm; return this; } /** * Get lengthCm * @return lengthCm **/ @javax.annotation.Nonnull @JsonProperty(JSON_PROPERTY_LENGTH_CM) @JsonInclude(value = JsonInclude.Include.ALWAYS) public BigDecimal getLengthCm() { return lengthCm; } @JsonProperty(JSON_PROPERTY_LENGTH_CM) @JsonInclude(value = JsonInclude.Include.ALWAYS) public void setLengthCm(BigDecimal lengthCm) { this.lengthCm = lengthCm; } public BananaReq sweet(Boolean sweet) { this.sweet = sweet; return this; } /** * Get sweet * @return sweet **/ @javax.annotation.Nullable @JsonProperty(JSON_PROPERTY_SWEET) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public Boolean getSweet() { return sweet; } @JsonProperty(JSON_PROPERTY_SWEET) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setSweet(Boolean sweet) { this.sweet = sweet; } /** * Return true if this bananaReq object is equal to o. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BananaReq bananaReq = (BananaReq) o; return Objects.equals(this.lengthCm, bananaReq.lengthCm) && Objects.equals(this.sweet, bananaReq.sweet); } @Override public int hashCode() { return Objects.hash(lengthCm, sweet); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class BananaReq {\n"); sb.append(" lengthCm: ").append(toIndentedString(lengthCm)).append("\n"); sb.append(" sweet: ").append(toIndentedString(sweet)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } /** * Convert the instance into URL query string. * * @return URL query string */ public String toUrlQueryString() { return toUrlQueryString(null); } /** * Convert the instance into URL query string. * * @param prefix prefix of the query string * @return URL query string */ public String toUrlQueryString(String prefix) { String suffix = ""; String containerSuffix = ""; String containerPrefix = ""; if (prefix == null) { // style=form, explode=true, e.g. /pet?name=cat&type=manx prefix = ""; } else { // deepObject style<SUF> prefix = prefix + "["; suffix = "]"; containerSuffix = "]"; containerPrefix = "["; } StringJoiner joiner = new StringJoiner("&"); // add `lengthCm` to the URL query string if (getLengthCm() != null) { joiner.add(String.format("%slengthCm%s=%s", prefix, suffix, URLEncoder.encode(String.valueOf(getLengthCm()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); } // add `sweet` to the URL query string if (getSweet() != null) { joiner.add(String.format("%ssweet%s=%s", prefix, suffix, URLEncoder.encode(String.valueOf(getSweet()), StandardCharsets.UTF_8).replaceAll("\\+", "%20"))); } return joiner.toString(); } public static class Builder { private BananaReq instance; public Builder() { this(new BananaReq()); } protected Builder(BananaReq instance) { this.instance = instance; } public BananaReq.Builder lengthCm(BigDecimal lengthCm) { this.instance.lengthCm = lengthCm; return this; } public BananaReq.Builder sweet(Boolean sweet) { this.instance.sweet = sweet; return this; } /** * returns a built BananaReq instance. * * The builder is not reusable. */ public BananaReq build() { try { return this.instance; } finally { // ensure that this.instance is not reused this.instance = null; } } @Override public String toString() { return getClass() + "=(" + instance + ")"; } } /** * Create a builder with no initialized field. */ public static BananaReq.Builder builder() { return new BananaReq.Builder(); } /** * Create a builder with a shallow copy of this instance. */ public BananaReq.Builder toBuilder() { return new BananaReq.Builder() .lengthCm(getLengthCm()) .sweet(getSweet()); } }
False
1,458
18
1,634
23
1,748
23
1,634
23
2,034
23
false
false
false
false
false
true
4,243
26668_1
public class Dossier {_x000D_ private String vluchtelingId;_x000D_ private boolean paspoortGetoond;_x000D_ private boolean asielAanvraagCompleet;_x000D_ private boolean rechterToegewezen;_x000D_ private boolean uitspraakRechter;_x000D_ private boolean toegelatenTotSamenleving;_x000D_ private boolean terugkeerNaarLandVanHerkomst;_x000D_ _x000D_ public Dossier(String vluchtelingId,boolean paspoortGetoond,boolean asielAanvraagCompleet ,boolean rechterToegewezen, boolean uitspraakRechter, boolean toegelatenTotSamenleving, boolean terugkeerNaarLandVanHerkomst) {_x000D_ // Standaard waarden instellen_x000D_ this.vluchtelingId= vluchtelingId;_x000D_ this.paspoortGetoond = false;_x000D_ this.asielAanvraagCompleet = false;_x000D_ this.rechterToegewezen = false;_x000D_ this.uitspraakRechter = false;_x000D_ this.toegelatenTotSamenleving = false;_x000D_ this.terugkeerNaarLandVanHerkomst = false;_x000D_ }_x000D_ _x000D_ _x000D_ // Getters en setters voor de variabelen_x000D_ public String getVluchtelingId(){_x000D_ return vluchtelingId;_x000D_ }_x000D_ public boolean isPaspoortGetoond() {_x000D_ return paspoortGetoond;_x000D_ }_x000D_ _x000D_ public void setPaspoortGetoond(boolean paspoortGetoond) {_x000D_ this.paspoortGetoond = paspoortGetoond;_x000D_ }_x000D_ _x000D_ public boolean isAsielAanvraagCompleet() {_x000D_ return asielAanvraagCompleet;_x000D_ }_x000D_ _x000D_ public void setAsielAanvraagCompleet(boolean asielAanvraagCompleet) {_x000D_ this.asielAanvraagCompleet = asielAanvraagCompleet;_x000D_ }_x000D_ _x000D_ public boolean isRechterToegewezen() {_x000D_ return rechterToegewezen;_x000D_ }_x000D_ _x000D_ public void setRechterToegewezen(boolean rechterToegewezen) {_x000D_ this.rechterToegewezen = rechterToegewezen;_x000D_ }_x000D_ _x000D_ public boolean isUitspraakRechter() {_x000D_ return uitspraakRechter;_x000D_ }_x000D_ _x000D_ public void setUitspraakRechter(boolean uitspraakRechter) {_x000D_ this.uitspraakRechter = uitspraakRechter;_x000D_ }_x000D_ _x000D_ public boolean isToegelatenTotSamenleving() {_x000D_ return toegelatenTotSamenleving;_x000D_ }_x000D_ _x000D_ public void setToegelatenTotSamenleving(boolean toegelatenTotSamenleving) {_x000D_ this.toegelatenTotSamenleving = toegelatenTotSamenleving;_x000D_ }_x000D_ _x000D_ public boolean isTerugkeerNaarLandVanHerkomst() {_x000D_ return terugkeerNaarLandVanHerkomst;_x000D_ }_x000D_ _x000D_ public void setTerugkeerNaarLandVanHerkomst(boolean terugkeerNaarLandVanHerkomst) {_x000D_ this.terugkeerNaarLandVanHerkomst = terugkeerNaarLandVanHerkomst;_x000D_ }_x000D_ _x000D_ @Override_x000D_ public String toString() {_x000D_ return String.format("Paspoort Getoond: %b, Asielaanvraag Compleet: %b, Rechter Toegewezen: %b, Uitspraak Rechter: %b, Toegelaten Tot Samenleving: %b, Terugkeer Naar Land Van Herkomst: %b, VluvhtelingID: %s",_x000D_ paspoortGetoond, asielAanvraagCompleet, rechterToegewezen, uitspraakRechter, toegelatenTotSamenleving, terugkeerNaarLandVanHerkomst, vluchtelingId);_x000D_ }_x000D_ }_x000D_
samuel2597/Portefolio-2
Dossier.java
1,029
// Getters en setters voor de variabelen_x000D_
line_comment
nl
public class Dossier {_x000D_ private String vluchtelingId;_x000D_ private boolean paspoortGetoond;_x000D_ private boolean asielAanvraagCompleet;_x000D_ private boolean rechterToegewezen;_x000D_ private boolean uitspraakRechter;_x000D_ private boolean toegelatenTotSamenleving;_x000D_ private boolean terugkeerNaarLandVanHerkomst;_x000D_ _x000D_ public Dossier(String vluchtelingId,boolean paspoortGetoond,boolean asielAanvraagCompleet ,boolean rechterToegewezen, boolean uitspraakRechter, boolean toegelatenTotSamenleving, boolean terugkeerNaarLandVanHerkomst) {_x000D_ // Standaard waarden instellen_x000D_ this.vluchtelingId= vluchtelingId;_x000D_ this.paspoortGetoond = false;_x000D_ this.asielAanvraagCompleet = false;_x000D_ this.rechterToegewezen = false;_x000D_ this.uitspraakRechter = false;_x000D_ this.toegelatenTotSamenleving = false;_x000D_ this.terugkeerNaarLandVanHerkomst = false;_x000D_ }_x000D_ _x000D_ _x000D_ // Getters en<SUF> public String getVluchtelingId(){_x000D_ return vluchtelingId;_x000D_ }_x000D_ public boolean isPaspoortGetoond() {_x000D_ return paspoortGetoond;_x000D_ }_x000D_ _x000D_ public void setPaspoortGetoond(boolean paspoortGetoond) {_x000D_ this.paspoortGetoond = paspoortGetoond;_x000D_ }_x000D_ _x000D_ public boolean isAsielAanvraagCompleet() {_x000D_ return asielAanvraagCompleet;_x000D_ }_x000D_ _x000D_ public void setAsielAanvraagCompleet(boolean asielAanvraagCompleet) {_x000D_ this.asielAanvraagCompleet = asielAanvraagCompleet;_x000D_ }_x000D_ _x000D_ public boolean isRechterToegewezen() {_x000D_ return rechterToegewezen;_x000D_ }_x000D_ _x000D_ public void setRechterToegewezen(boolean rechterToegewezen) {_x000D_ this.rechterToegewezen = rechterToegewezen;_x000D_ }_x000D_ _x000D_ public boolean isUitspraakRechter() {_x000D_ return uitspraakRechter;_x000D_ }_x000D_ _x000D_ public void setUitspraakRechter(boolean uitspraakRechter) {_x000D_ this.uitspraakRechter = uitspraakRechter;_x000D_ }_x000D_ _x000D_ public boolean isToegelatenTotSamenleving() {_x000D_ return toegelatenTotSamenleving;_x000D_ }_x000D_ _x000D_ public void setToegelatenTotSamenleving(boolean toegelatenTotSamenleving) {_x000D_ this.toegelatenTotSamenleving = toegelatenTotSamenleving;_x000D_ }_x000D_ _x000D_ public boolean isTerugkeerNaarLandVanHerkomst() {_x000D_ return terugkeerNaarLandVanHerkomst;_x000D_ }_x000D_ _x000D_ public void setTerugkeerNaarLandVanHerkomst(boolean terugkeerNaarLandVanHerkomst) {_x000D_ this.terugkeerNaarLandVanHerkomst = terugkeerNaarLandVanHerkomst;_x000D_ }_x000D_ _x000D_ @Override_x000D_ public String toString() {_x000D_ return String.format("Paspoort Getoond: %b, Asielaanvraag Compleet: %b, Rechter Toegewezen: %b, Uitspraak Rechter: %b, Toegelaten Tot Samenleving: %b, Terugkeer Naar Land Van Herkomst: %b, VluvhtelingID: %s",_x000D_ paspoortGetoond, asielAanvraagCompleet, rechterToegewezen, uitspraakRechter, toegelatenTotSamenleving, terugkeerNaarLandVanHerkomst, vluchtelingId);_x000D_ }_x000D_ }_x000D_
True
1,385
16
1,463
18
1,356
16
1,463
18
1,558
18
false
false
false
false
false
true
1,453
43983_1
/* * 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 dao; import contstants.BetaalStatus; import domain.Auto; import domain.Cartracker; import domain.Eigenaar; import domain.Factuur; import domain.FactuurOnderdeel; import domain.Kilometertarief; import java.util.List; import javax.ejb.Singleton; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.transaction.Transactional; import service.RekeningAdministratie; /** * * @author kay de groot */ @Singleton public class DatabaseManager { //HIER MOETEN WE ECHT WAT AAN DOEN! CENTRALE DB ERGENS? @PersistenceContext(unitName = "MooieUnit") private EntityManager em; public DatabaseManager() { } public List<Cartracker> findAllCartracker() { Query query = em.createQuery("SELECT c FROM Cartracker c"); List<Cartracker> cartrackers = query.getResultList(); return cartrackers; } public List<FactuurOnderdeel> findOnderdelenForMonth(String Maand) { Query query = em.createQuery("SELECT c FROM FactuurOnderdeel c WHERE c.maand = '" + Maand + "'"); List<FactuurOnderdeel> facturen = query.getResultList(); for (FactuurOnderdeel fo : facturen) { fo.setMonth(); } return facturen; } public void addFactuur(Factuur factuur) { em.persist(factuur); } public void mergeCartracker(Cartracker c) { em.merge(c); } public void addOnderdeel(FactuurOnderdeel fo) { System.out.println(fo.getFactuurID()); em.persist(fo); } public Factuur findFactuurWithID(int nummer) { Query query = em.createQuery("SELECT c FROM Factuur c WHERE c.nummer = " + nummer); List<Factuur> facturen = query.getResultList(); if (facturen.size() > 0) { return facturen.get(0); } else { return null; } } public void mergeFactuur(Factuur factuur) { em.merge(factuur); } public void addCartracker(Cartracker cartracker) { System.out.println(cartracker); em.persist(cartracker); } public Cartracker findCartrackerWithId(int nummer) { Query query = em.createQuery("SELECT c FROM Cartracker c WHERE c.id = " + nummer); List<Cartracker> cartrackers = query.getResultList(); if (cartrackers.size() > 0) { return cartrackers.get(0); } else { return null; } } public List<Auto> getAllAutos() { Query query = em.createQuery("SELECT c FROM Auto c ");//"SELECT c FROM Auto c WHERE c.id = " + i List<Auto> autos = query.getResultList(); return autos; } public Auto getAuto(int i) { Query query = em.createQuery("SELECT c FROM Auto c WHERE c.id = " + i); List<Auto> autos = query.getResultList(); if (autos.size() > 0) { return autos.get(0); } else { return null; } } public List<Kilometertarief> getAlleKilometerTarieven() { Query query = em.createQuery("SELECT c FROM Kilometertarief c"); List<Kilometertarief> tarieven = query.getResultList(); return tarieven; } public Kilometertarief getKilometerTarief(int id) { Query query = em.createQuery("SELECT c FROM Kilometertarief c WHERE c.id = " + id); List<Kilometertarief> tarieven = query.getResultList(); if (tarieven.size() > 0) { return tarieven.get(0); } else { return null; } } public void addKilometerTarief(Kilometertarief kt) { em.persist(kt); } public void editKilometerTarief(Kilometertarief kt) { em.merge(kt); } public void deleteKilometerTarief(int id) { em.remove(id); } public List<Factuur> getAlleFacturen() { Query query = em.createQuery("SELECT c FROM Factuur c"); List<Factuur> factuurs = query.getResultList(); for (Factuur factuur : factuurs) { factuur.setFactuuronderdelen(this.getFactuurOnderdelen(factuur.getNummer())); } return factuurs; } public void addAuto(Auto nieuweAuto) { em.persist(nieuweAuto); } public List<Cartracker> getCartrackers() { Query query = em.createQuery("SELECT c FROM Cartracker c"); List<Cartracker> c = query.getResultList(); return c; } public Cartracker getCartracker(int id) { Query query = em.createQuery("SELECT c FROM Cartracker c WHERE c.id =" + id); List<Cartracker> c = query.getResultList(); if (c.size() > 0) { return c.get(0); } else { return null; } } public void modifyAuto(Auto a) { em.merge(a); } public void modifyEigenaar(Eigenaar a) { em.merge(a); } public Eigenaar getEigenaar(int id) { Query query = em.createQuery("SELECT c FROM Eigenaar c WHERE c.id = " + id); List<Eigenaar> eigenaar = query.getResultList(); if (eigenaar.size() > 0) { return eigenaar.get(0); } else { return null; } } public void mergeAuto(Auto auto) { em.merge(auto); } public List<Eigenaar> getAllEigenaars() { Query query = em.createQuery("SELECT c FROM Eigenaar c"); List<Eigenaar> c = query.getResultList(); return c; } public Factuur getFactuur(int id) { Query query = em.createQuery("SELECT c FROM Factuur c WHERE c.nummer = " + id); List<Factuur> facturen = query.getResultList(); if (facturen.size() > 0) { Factuur factuur = facturen.get(0); factuur.setFactuuronderdelen(getFactuurOnderdelen(id)); return factuur; } else { return null; } } public List<FactuurOnderdeel> getFactuurOnderdelen(int id) { Query query = em.createQuery("SELECT o FROM FactuurOnderdeel o where o.factuurID = " + id); List<FactuurOnderdeel> factuuronderdelen = query.getResultList(); return factuuronderdelen; } public FactuurOnderdeel getFactuurOnderdeel(int id) { Query query = em.createQuery("SELECT o FROM FactuurOnderdeel o where o.FactuurOnderdeelID = " + id); List<FactuurOnderdeel> factuuronderdelen = query.getResultList(); if (factuuronderdelen.size() > 0) { FactuurOnderdeel onderdeel = factuuronderdelen.get(0); return onderdeel; } else { return null; } } public void MergeFactuurOnderdeel(FactuurOnderdeel fac) { em.merge(fac); } public String init(RekeningAdministratie r) { return new DataInit().init(r, this); } public void factuurBetaald(int id) { Factuur factuur = this.getFactuur(id); factuur.setBetaalStatus(BetaalStatus.BETAALD); em.merge(factuur); } public Factuur getLaatsteFactuur() { Query query = em.createQuery("SELECT c FROM Factuur c WHERE c.nummer = (SELECT MAX(c.nummer) FROM Factuur c)"); List<Factuur> facturen = query.getResultList(); if (facturen.size() > 0) { Factuur factuur = facturen.get(0); System.out.println("output nummer: "+factuur.getNummer()); factuur.setFactuuronderdelen(getFactuurOnderdelen(factuur.getNummer())); return factuur; } else { return null; } } }
Renellekes/ProftaakS63C
RekeningAdministratieBackend/src/main/java/dao/DatabaseManager.java
2,458
/** * * @author kay de groot */
block_comment
nl
/* * 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 dao; import contstants.BetaalStatus; import domain.Auto; import domain.Cartracker; import domain.Eigenaar; import domain.Factuur; import domain.FactuurOnderdeel; import domain.Kilometertarief; import java.util.List; import javax.ejb.Singleton; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.transaction.Transactional; import service.RekeningAdministratie; /** * * @author kay de<SUF>*/ @Singleton public class DatabaseManager { //HIER MOETEN WE ECHT WAT AAN DOEN! CENTRALE DB ERGENS? @PersistenceContext(unitName = "MooieUnit") private EntityManager em; public DatabaseManager() { } public List<Cartracker> findAllCartracker() { Query query = em.createQuery("SELECT c FROM Cartracker c"); List<Cartracker> cartrackers = query.getResultList(); return cartrackers; } public List<FactuurOnderdeel> findOnderdelenForMonth(String Maand) { Query query = em.createQuery("SELECT c FROM FactuurOnderdeel c WHERE c.maand = '" + Maand + "'"); List<FactuurOnderdeel> facturen = query.getResultList(); for (FactuurOnderdeel fo : facturen) { fo.setMonth(); } return facturen; } public void addFactuur(Factuur factuur) { em.persist(factuur); } public void mergeCartracker(Cartracker c) { em.merge(c); } public void addOnderdeel(FactuurOnderdeel fo) { System.out.println(fo.getFactuurID()); em.persist(fo); } public Factuur findFactuurWithID(int nummer) { Query query = em.createQuery("SELECT c FROM Factuur c WHERE c.nummer = " + nummer); List<Factuur> facturen = query.getResultList(); if (facturen.size() > 0) { return facturen.get(0); } else { return null; } } public void mergeFactuur(Factuur factuur) { em.merge(factuur); } public void addCartracker(Cartracker cartracker) { System.out.println(cartracker); em.persist(cartracker); } public Cartracker findCartrackerWithId(int nummer) { Query query = em.createQuery("SELECT c FROM Cartracker c WHERE c.id = " + nummer); List<Cartracker> cartrackers = query.getResultList(); if (cartrackers.size() > 0) { return cartrackers.get(0); } else { return null; } } public List<Auto> getAllAutos() { Query query = em.createQuery("SELECT c FROM Auto c ");//"SELECT c FROM Auto c WHERE c.id = " + i List<Auto> autos = query.getResultList(); return autos; } public Auto getAuto(int i) { Query query = em.createQuery("SELECT c FROM Auto c WHERE c.id = " + i); List<Auto> autos = query.getResultList(); if (autos.size() > 0) { return autos.get(0); } else { return null; } } public List<Kilometertarief> getAlleKilometerTarieven() { Query query = em.createQuery("SELECT c FROM Kilometertarief c"); List<Kilometertarief> tarieven = query.getResultList(); return tarieven; } public Kilometertarief getKilometerTarief(int id) { Query query = em.createQuery("SELECT c FROM Kilometertarief c WHERE c.id = " + id); List<Kilometertarief> tarieven = query.getResultList(); if (tarieven.size() > 0) { return tarieven.get(0); } else { return null; } } public void addKilometerTarief(Kilometertarief kt) { em.persist(kt); } public void editKilometerTarief(Kilometertarief kt) { em.merge(kt); } public void deleteKilometerTarief(int id) { em.remove(id); } public List<Factuur> getAlleFacturen() { Query query = em.createQuery("SELECT c FROM Factuur c"); List<Factuur> factuurs = query.getResultList(); for (Factuur factuur : factuurs) { factuur.setFactuuronderdelen(this.getFactuurOnderdelen(factuur.getNummer())); } return factuurs; } public void addAuto(Auto nieuweAuto) { em.persist(nieuweAuto); } public List<Cartracker> getCartrackers() { Query query = em.createQuery("SELECT c FROM Cartracker c"); List<Cartracker> c = query.getResultList(); return c; } public Cartracker getCartracker(int id) { Query query = em.createQuery("SELECT c FROM Cartracker c WHERE c.id =" + id); List<Cartracker> c = query.getResultList(); if (c.size() > 0) { return c.get(0); } else { return null; } } public void modifyAuto(Auto a) { em.merge(a); } public void modifyEigenaar(Eigenaar a) { em.merge(a); } public Eigenaar getEigenaar(int id) { Query query = em.createQuery("SELECT c FROM Eigenaar c WHERE c.id = " + id); List<Eigenaar> eigenaar = query.getResultList(); if (eigenaar.size() > 0) { return eigenaar.get(0); } else { return null; } } public void mergeAuto(Auto auto) { em.merge(auto); } public List<Eigenaar> getAllEigenaars() { Query query = em.createQuery("SELECT c FROM Eigenaar c"); List<Eigenaar> c = query.getResultList(); return c; } public Factuur getFactuur(int id) { Query query = em.createQuery("SELECT c FROM Factuur c WHERE c.nummer = " + id); List<Factuur> facturen = query.getResultList(); if (facturen.size() > 0) { Factuur factuur = facturen.get(0); factuur.setFactuuronderdelen(getFactuurOnderdelen(id)); return factuur; } else { return null; } } public List<FactuurOnderdeel> getFactuurOnderdelen(int id) { Query query = em.createQuery("SELECT o FROM FactuurOnderdeel o where o.factuurID = " + id); List<FactuurOnderdeel> factuuronderdelen = query.getResultList(); return factuuronderdelen; } public FactuurOnderdeel getFactuurOnderdeel(int id) { Query query = em.createQuery("SELECT o FROM FactuurOnderdeel o where o.FactuurOnderdeelID = " + id); List<FactuurOnderdeel> factuuronderdelen = query.getResultList(); if (factuuronderdelen.size() > 0) { FactuurOnderdeel onderdeel = factuuronderdelen.get(0); return onderdeel; } else { return null; } } public void MergeFactuurOnderdeel(FactuurOnderdeel fac) { em.merge(fac); } public String init(RekeningAdministratie r) { return new DataInit().init(r, this); } public void factuurBetaald(int id) { Factuur factuur = this.getFactuur(id); factuur.setBetaalStatus(BetaalStatus.BETAALD); em.merge(factuur); } public Factuur getLaatsteFactuur() { Query query = em.createQuery("SELECT c FROM Factuur c WHERE c.nummer = (SELECT MAX(c.nummer) FROM Factuur c)"); List<Factuur> facturen = query.getResultList(); if (facturen.size() > 0) { Factuur factuur = facturen.get(0); System.out.println("output nummer: "+factuur.getNummer()); factuur.setFactuuronderdelen(getFactuurOnderdelen(factuur.getNummer())); return factuur; } else { return null; } } }
False
1,928
10
2,176
13
2,193
12
2,176
13
2,446
13
false
false
false
false
false
true
4,794
68722_20
// Copyright (C) 2013 Andrew Allen // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package prettify.lang; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import prettify.parser.Prettify; /** * This is similar to the lang-erlang.js in JavaScript Prettify. * <p> * All comments are adapted from the JavaScript Prettify. * <p> * <p> * <p> * Derived from https://raw.github.com/erlang/otp/dev/lib/compiler/src/core_parse.yrl * Modified from Mike Samuel's Haskell plugin for google-code-prettify * * @author [email protected] */ public class LangErlang extends Lang { public LangErlang() { List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>(); List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>(); // Whitespace // whitechar -> newline | vertab | space | tab | uniWhite // newline -> return linefeed | return | linefeed | formfeed _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("\\t\\n\\x0B\\x0C\\r ]+"), null, "\t\n" + Character.toString((char) 0x0B) + Character.toString((char) 0x0C) + "\r "})); // Single line double-quoted strings. _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^\\\"(?:[^\\\"\\\\\\n\\x0C\\r]|\\\\[\\s\\S])*(?:\\\"|$)"), null, "\""})); // Handle atoms _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^[a-z][a-zA-Z0-9_]*")})); // Handle single quoted atoms _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^\\'(?:[^\\'\\\\\\n\\x0C\\r]|\\\\[^&])+\\'?"), null, "'"})); // Handle macros. Just to be extra clear on this one, it detects the ? // then uses the regexp to end it so be very careful about matching // all the terminal elements _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^\\?[^ \\t\\n({]+"), null, "?"})); // decimal -> digit{digit} // octal -> octit{octit} // hexadecimal -> hexit{hexit} // integer -> decimal // | 0o octal | 0O octal // | 0x hexadecimal | 0X hexadecimal // float -> decimal . decimal [exponent] // | decimal exponent // exponent -> (e | E) [+ | -] decimal _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^(?:0o[0-7]+|0x[\\da-f]+|\\d+(?:\\.\\d+)?(?:e[+\\-]?\\d+)?)", Pattern.CASE_INSENSITIVE), null, "0123456789"})); // TODO: catch @declarations inside comments // Comments in erlang are started with % and go till a newline _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^%[^\\n\\r]*")})); // Catch macros //[PR['PR_TAG'], /?[^( \n)]+/], /** * %% Keywords (atoms are assumed to always be single-quoted). * 'module' 'attributes' 'do' 'let' 'in' 'letrec' * 'apply' 'call' 'primop' * 'case' 'of' 'end' 'when' 'fun' 'try' 'catch' 'receive' 'after' */ _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^(?:module|attributes|do|let|in|letrec|apply|call|primop|case|of|end|when|fun|try|catch|receive|after|char|integer|float,atom,string,var)\\b")})); /** * Catch definitions (usually defined at the top of the file) * Anything that starts -something */ _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^-[a-z_]+")})); // Catch variables _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_TYPE, Pattern.compile("^[A-Z_][a-zA-Z0-9_]*")})); // matches the symbol production _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PUNCTUATION, Pattern.compile("^[.,;]")})); setShortcutStylePatterns(_shortcutStylePatterns); setFallthroughStylePatterns(_fallthroughStylePatterns); } public static List<String> getFileExtensions() { return Arrays.asList(new String[]{"erlang", "erl"}); } }
yydcdut/RxMarkdown
markdown-processor/src/main/java/prettify/lang/LangErlang.java
1,633
// integer -> decimal
line_comment
nl
// Copyright (C) 2013 Andrew Allen // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package prettify.lang; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import prettify.parser.Prettify; /** * This is similar to the lang-erlang.js in JavaScript Prettify. * <p> * All comments are adapted from the JavaScript Prettify. * <p> * <p> * <p> * Derived from https://raw.github.com/erlang/otp/dev/lib/compiler/src/core_parse.yrl * Modified from Mike Samuel's Haskell plugin for google-code-prettify * * @author [email protected] */ public class LangErlang extends Lang { public LangErlang() { List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>(); List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>(); // Whitespace // whitechar -> newline | vertab | space | tab | uniWhite // newline -> return linefeed | return | linefeed | formfeed _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("\\t\\n\\x0B\\x0C\\r ]+"), null, "\t\n" + Character.toString((char) 0x0B) + Character.toString((char) 0x0C) + "\r "})); // Single line double-quoted strings. _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^\\\"(?:[^\\\"\\\\\\n\\x0C\\r]|\\\\[\\s\\S])*(?:\\\"|$)"), null, "\""})); // Handle atoms _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^[a-z][a-zA-Z0-9_]*")})); // Handle single quoted atoms _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^\\'(?:[^\\'\\\\\\n\\x0C\\r]|\\\\[^&])+\\'?"), null, "'"})); // Handle macros. Just to be extra clear on this one, it detects the ? // then uses the regexp to end it so be very careful about matching // all the terminal elements _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^\\?[^ \\t\\n({]+"), null, "?"})); // decimal -> digit{digit} // octal -> octit{octit} // hexadecimal -> hexit{hexit} // integer <SUF> // | 0o octal | 0O octal // | 0x hexadecimal | 0X hexadecimal // float -> decimal . decimal [exponent] // | decimal exponent // exponent -> (e | E) [+ | -] decimal _shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^(?:0o[0-7]+|0x[\\da-f]+|\\d+(?:\\.\\d+)?(?:e[+\\-]?\\d+)?)", Pattern.CASE_INSENSITIVE), null, "0123456789"})); // TODO: catch @declarations inside comments // Comments in erlang are started with % and go till a newline _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^%[^\\n\\r]*")})); // Catch macros //[PR['PR_TAG'], /?[^( \n)]+/], /** * %% Keywords (atoms are assumed to always be single-quoted). * 'module' 'attributes' 'do' 'let' 'in' 'letrec' * 'apply' 'call' 'primop' * 'case' 'of' 'end' 'when' 'fun' 'try' 'catch' 'receive' 'after' */ _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^(?:module|attributes|do|let|in|letrec|apply|call|primop|case|of|end|when|fun|try|catch|receive|after|char|integer|float,atom,string,var)\\b")})); /** * Catch definitions (usually defined at the top of the file) * Anything that starts -something */ _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^-[a-z_]+")})); // Catch variables _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_TYPE, Pattern.compile("^[A-Z_][a-zA-Z0-9_]*")})); // matches the symbol production _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PUNCTUATION, Pattern.compile("^[.,;]")})); setShortcutStylePatterns(_shortcutStylePatterns); setFallthroughStylePatterns(_fallthroughStylePatterns); } public static List<String> getFileExtensions() { return Arrays.asList(new String[]{"erlang", "erl"}); } }
False
1,268
6
1,398
6
1,435
6
1,398
6
1,655
6
false
false
false
false
false
true
671
36779_0
package model; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.util.*; /** * Gemaakt door Vincent & Niek * Met hulp van Ronan * Bronnen: http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java * http://stackoverflow.com/questions/23075689/how-to-do-a-recursive-search-for-a-word-in-the-boggle-game-board */ public class Solver { private boolean[][] isVisited; private ArrayList<String> woordenLijst = new ArrayList<>(); private Set<String> foundWords = new HashSet<String>(); public Set<String> solve(String[][] board){ loadWordList(); isVisited = new boolean[board.length][board[0].length]; for(int i = 0; i < board.length; i++){ for(int j = 0; j < board[0].length; j++){ searchWord(board, i, j, ""); clearVisited(board.length,board[0].length); } } return foundWords; } private void loadWordList(){ try { URL url = getClass().getResource("dict.txt"); BufferedReader br = new BufferedReader(new FileReader(url.getPath())); String line; while ((line = br.readLine()) != null) { woordenLijst.add(line); } } catch (IOException ex){ ex.printStackTrace(); } } private void clearVisited(int xSize, int ySize){ for(int i = 0; i <xSize; i++) { for(int j = 0; j <ySize; j++) { isVisited[i][j] = false; } } } private void searchWord(String[][] board, int xPos, int yPos, String word){ word += board[xPos][yPos]; if (isVisited[xPos][yPos]) {return;} isVisited[xPos][yPos] = true; for(String checkWord: woordenLijst){ if (checkWord.equals(word)){ foundWords.add(word); } if(checkWord.startsWith(word) && xPos>0 && yPos>0 && xPos<board.length-1 && yPos<board.length-1 ){ searchWord(board,xPos+1, yPos, word); // positie naar rechts searchWord(board,xPos, yPos+1, word); // positie omhoog searchWord(board,xPos-1, yPos, word); // positie naar links searchWord(board,xPos, yPos-1, word); // positie naar beneden searchWord(board,xPos+1, yPos+1, word); //topright searchWord(board,xPos-1, yPos-1, word);//bottomleft searchWord(board,xPos-1, yPos+1, word);//topleft searchWord(board,xPos+1, yPos-1, word);//bottomright break; } } } }
HanzehogeschoolSICT/Inleveropdracht2-VincentLuder-NiekBeukema-ITV2E
src/model/Solver.java
875
/** * Gemaakt door Vincent & Niek * Met hulp van Ronan * Bronnen: http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java * http://stackoverflow.com/questions/23075689/how-to-do-a-recursive-search-for-a-word-in-the-boggle-game-board */
block_comment
nl
package model; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.util.*; /** * Gemaakt door Vincent<SUF>*/ public class Solver { private boolean[][] isVisited; private ArrayList<String> woordenLijst = new ArrayList<>(); private Set<String> foundWords = new HashSet<String>(); public Set<String> solve(String[][] board){ loadWordList(); isVisited = new boolean[board.length][board[0].length]; for(int i = 0; i < board.length; i++){ for(int j = 0; j < board[0].length; j++){ searchWord(board, i, j, ""); clearVisited(board.length,board[0].length); } } return foundWords; } private void loadWordList(){ try { URL url = getClass().getResource("dict.txt"); BufferedReader br = new BufferedReader(new FileReader(url.getPath())); String line; while ((line = br.readLine()) != null) { woordenLijst.add(line); } } catch (IOException ex){ ex.printStackTrace(); } } private void clearVisited(int xSize, int ySize){ for(int i = 0; i <xSize; i++) { for(int j = 0; j <ySize; j++) { isVisited[i][j] = false; } } } private void searchWord(String[][] board, int xPos, int yPos, String word){ word += board[xPos][yPos]; if (isVisited[xPos][yPos]) {return;} isVisited[xPos][yPos] = true; for(String checkWord: woordenLijst){ if (checkWord.equals(word)){ foundWords.add(word); } if(checkWord.startsWith(word) && xPos>0 && yPos>0 && xPos<board.length-1 && yPos<board.length-1 ){ searchWord(board,xPos+1, yPos, word); // positie naar rechts searchWord(board,xPos, yPos+1, word); // positie omhoog searchWord(board,xPos-1, yPos, word); // positie naar links searchWord(board,xPos, yPos-1, word); // positie naar beneden searchWord(board,xPos+1, yPos+1, word); //topright searchWord(board,xPos-1, yPos-1, word);//bottomleft searchWord(board,xPos-1, yPos+1, word);//topleft searchWord(board,xPos+1, yPos-1, word);//bottomright break; } } } }
False
656
81
773
117
783
109
780
117
858
113
false
false
false
false
false
true
3,785
83494_1
package be.thomasmore.party.controllers; import be.thomasmore.party.model.Client; import be.thomasmore.party.repositories.ClientRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.time.LocalDateTime; import java.util.Optional; import static java.time.LocalDateTime.now; @Controller public class ClientController { @Autowired ClientRepository clientRepository; @GetMapping("/clienthome") public String home(Model model) { final Optional<Client> clientFromDb = clientRepository.findById(1); if (clientFromDb.isPresent()) { } return "clienthome"; } @GetMapping("/clientgreeting") public String clientGreeting(Model model) { final Optional<Client> clientFromDb = clientRepository.findById(1); if (clientFromDb.isPresent()) { final Client client = clientFromDb.get(); String message = "%s %s%s%s".formatted( getGreeting(), getPrefix(client), client.getName(), getPostfix(client)); model.addAttribute("message", message); } return "clientgreeting"; } @GetMapping("/clientdetails") public String clientDetails(Model model) { final Optional<Client> clientFromDb = clientRepository.findById(1); if (clientFromDb.isPresent()) { final Client client = clientFromDb.get(); model.addAttribute("client", client); model.addAttribute("discount", calculateDiscount(client)); } return "clientdetails"; } private String getPrefix(Client client) { if (client.getNrOfOrders() < 10) return ""; if (client.getNrOfOrders() < 50) return "beste "; return "allerliefste "; } private String getGreeting() { LocalDateTime now = now(); //LocalDateTime now = LocalDateTime.parse("2023-09-23T17:15"); //for test purposes //NOTE: dit is de meest naieve manier om iets te testen. Volgend jaar zien we daar meer over. if (now.getHour() < 6) return "Goedenacht"; if (now.getHour() < 12) return "Goedemorgen"; if (now.getHour() < 17) return "Goedemiddag"; if (now.getHour() < 22) return "Goedenavond"; return "Goedenacht"; } private String getPostfix(Client client) { if (client.getNrOfOrders() == 0) return ", en welkom!"; if (client.getNrOfOrders() >= 80) return ", jij bent een topper!"; return ""; } private double calculateDiscount(Client client) { if (client.getTotalAmount() < 50) return 0; return client.getTotalAmount() / 200; } }
neeraj543/Toets-1
src/main/java/be/thomasmore/party/controllers/ClientController.java
806
//NOTE: dit is de meest naieve manier om iets te testen. Volgend jaar zien we daar meer over.
line_comment
nl
package be.thomasmore.party.controllers; import be.thomasmore.party.model.Client; import be.thomasmore.party.repositories.ClientRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.time.LocalDateTime; import java.util.Optional; import static java.time.LocalDateTime.now; @Controller public class ClientController { @Autowired ClientRepository clientRepository; @GetMapping("/clienthome") public String home(Model model) { final Optional<Client> clientFromDb = clientRepository.findById(1); if (clientFromDb.isPresent()) { } return "clienthome"; } @GetMapping("/clientgreeting") public String clientGreeting(Model model) { final Optional<Client> clientFromDb = clientRepository.findById(1); if (clientFromDb.isPresent()) { final Client client = clientFromDb.get(); String message = "%s %s%s%s".formatted( getGreeting(), getPrefix(client), client.getName(), getPostfix(client)); model.addAttribute("message", message); } return "clientgreeting"; } @GetMapping("/clientdetails") public String clientDetails(Model model) { final Optional<Client> clientFromDb = clientRepository.findById(1); if (clientFromDb.isPresent()) { final Client client = clientFromDb.get(); model.addAttribute("client", client); model.addAttribute("discount", calculateDiscount(client)); } return "clientdetails"; } private String getPrefix(Client client) { if (client.getNrOfOrders() < 10) return ""; if (client.getNrOfOrders() < 50) return "beste "; return "allerliefste "; } private String getGreeting() { LocalDateTime now = now(); //LocalDateTime now = LocalDateTime.parse("2023-09-23T17:15"); //for test purposes //NOTE: dit<SUF> if (now.getHour() < 6) return "Goedenacht"; if (now.getHour() < 12) return "Goedemorgen"; if (now.getHour() < 17) return "Goedemiddag"; if (now.getHour() < 22) return "Goedenavond"; return "Goedenacht"; } private String getPostfix(Client client) { if (client.getNrOfOrders() == 0) return ", en welkom!"; if (client.getNrOfOrders() >= 80) return ", jij bent een topper!"; return ""; } private double calculateDiscount(Client client) { if (client.getTotalAmount() < 50) return 0; return client.getTotalAmount() / 200; } }
True
628
27
717
32
750
24
717
32
839
31
false
false
false
false
false
true
1,563
162774_5
package nl.vanlaar.bart.topid.Activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import nl.vanlaar.bart.topid.Model.Comment; import nl.vanlaar.bart.topid.Model.Idee; import nl.vanlaar.bart.topid.Model.IdeeënLijst; import nl.vanlaar.bart.topid.R; import nl.vanlaar.bart.topid.View.ReactiesAdapter; /** * De reageer activity laat de gebruiker een reactie plaatsen op een idee */ public class ReageerActivity extends AppCompatActivity { private Button btPlaatsReactie; private EditText etReactie; private Comment comment = new Comment(); private ArrayList<Idee> ideeënLijst; private Idee idee; private ArrayList<Comment> commentList; private ListView lv; private ReactiesAdapter reactiesAdapter; private ImageView backArrow; private ListView commentListView; private int ideePositieIdee; private int ideePositieKlacht; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reageer); //idee en ideeënlijst vullen ideePositieIdee = getIntent().getIntExtra(ShowIdeeActivity.EXTRA_IDEE,-1); ideePositieKlacht = getIntent().getIntExtra(ShowIdeeActivity.EXTRA_KLACHT,-1); /* laden van dummy data */ if(ideePositieIdee>-1){ ideeënLijst = IdeeënLijst.getInstance().getIdeeën(); idee = ideeënLijst.get(ideePositieIdee); } else if (ideePositieKlacht > -1) { ideeënLijst = IdeeënLijst.getInstance().getKlachten(); idee = ideeënLijst.get(ideePositieKlacht); } //commentlist vullen, sanity check voor als die list nog niet gemaakt is. if(commentList != null) { commentList = idee.getComments(); } else { idee.createCommentList(); commentList = idee.getComments(); } //kopellen aan views btPlaatsReactie = (Button) findViewById(R.id.btPlaats_reactie); etReactie = (EditText) findViewById(R.id.et_reageer_text); backArrow = (ImageView) findViewById(R.id.iv_reageren_toolbar_backbutton); commentListView = (ListView) findViewById(R.id.lvReacties_showIdee); //adapter configuratie reactiesAdapter = new ReactiesAdapter(this, commentList); commentListView.setAdapter(reactiesAdapter); //als de terug knop wordt ingedrukt ga dan naar de vorige activity backArrow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); //onclicklisnter voor de post knop btPlaatsReactie.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //als er nog velden leeg zijn laat dat aan de user zien if (TextUtils.isEmpty(etReactie.getText())) { Toast toast = Toast.makeText(getApplicationContext(), "U mag geen lege reactie plaatsen", Toast.LENGTH_SHORT); toast.show(); return; //maak een comment, vul hem met de velden en voeg hem toe aan een idee } else { comment = new Comment(MainActivity.LOGGED_IN_USER.getName(), etReactie.getText().toString(), MainActivity.LOGGED_IN_USER.getTempImage(), MainActivity.LOGGED_IN_USER); commentList.add(comment); reactiesAdapter.notifyDataSetChanged(); Toast toast = Toast.makeText(getApplicationContext(), "Uw Reactie is geplaatst", Toast.LENGTH_SHORT); toast.show(); etReactie.setText(""); } } }); } }
SaxionHBO-ICT/topicus-ict-solutions-deventer
TopID/app/src/main/java/nl/vanlaar/bart/topid/Activity/ReageerActivity.java
1,261
//als de terug knop wordt ingedrukt ga dan naar de vorige activity
line_comment
nl
package nl.vanlaar.bart.topid.Activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import nl.vanlaar.bart.topid.Model.Comment; import nl.vanlaar.bart.topid.Model.Idee; import nl.vanlaar.bart.topid.Model.IdeeënLijst; import nl.vanlaar.bart.topid.R; import nl.vanlaar.bart.topid.View.ReactiesAdapter; /** * De reageer activity laat de gebruiker een reactie plaatsen op een idee */ public class ReageerActivity extends AppCompatActivity { private Button btPlaatsReactie; private EditText etReactie; private Comment comment = new Comment(); private ArrayList<Idee> ideeënLijst; private Idee idee; private ArrayList<Comment> commentList; private ListView lv; private ReactiesAdapter reactiesAdapter; private ImageView backArrow; private ListView commentListView; private int ideePositieIdee; private int ideePositieKlacht; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reageer); //idee en ideeënlijst vullen ideePositieIdee = getIntent().getIntExtra(ShowIdeeActivity.EXTRA_IDEE,-1); ideePositieKlacht = getIntent().getIntExtra(ShowIdeeActivity.EXTRA_KLACHT,-1); /* laden van dummy data */ if(ideePositieIdee>-1){ ideeënLijst = IdeeënLijst.getInstance().getIdeeën(); idee = ideeënLijst.get(ideePositieIdee); } else if (ideePositieKlacht > -1) { ideeënLijst = IdeeënLijst.getInstance().getKlachten(); idee = ideeënLijst.get(ideePositieKlacht); } //commentlist vullen, sanity check voor als die list nog niet gemaakt is. if(commentList != null) { commentList = idee.getComments(); } else { idee.createCommentList(); commentList = idee.getComments(); } //kopellen aan views btPlaatsReactie = (Button) findViewById(R.id.btPlaats_reactie); etReactie = (EditText) findViewById(R.id.et_reageer_text); backArrow = (ImageView) findViewById(R.id.iv_reageren_toolbar_backbutton); commentListView = (ListView) findViewById(R.id.lvReacties_showIdee); //adapter configuratie reactiesAdapter = new ReactiesAdapter(this, commentList); commentListView.setAdapter(reactiesAdapter); //als de<SUF> backArrow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); //onclicklisnter voor de post knop btPlaatsReactie.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //als er nog velden leeg zijn laat dat aan de user zien if (TextUtils.isEmpty(etReactie.getText())) { Toast toast = Toast.makeText(getApplicationContext(), "U mag geen lege reactie plaatsen", Toast.LENGTH_SHORT); toast.show(); return; //maak een comment, vul hem met de velden en voeg hem toe aan een idee } else { comment = new Comment(MainActivity.LOGGED_IN_USER.getName(), etReactie.getText().toString(), MainActivity.LOGGED_IN_USER.getTempImage(), MainActivity.LOGGED_IN_USER); commentList.add(comment); reactiesAdapter.notifyDataSetChanged(); Toast toast = Toast.makeText(getApplicationContext(), "Uw Reactie is geplaatst", Toast.LENGTH_SHORT); toast.show(); etReactie.setText(""); } } }); } }
True
913
19
1,066
20
1,044
15
1,066
20
1,203
18
false
false
false
false
false
true
438
84013_2
package site.nerdygadgets.views; import site.nerdygadgets.functions.ComboRenderer; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; /** * DesignPanel class * DesignPanel for infrastructures * * @author Tristan Scholten & Jordy Wielaard * @version 1.0 * @since 14-05-2020 */ public class DesignPanel extends JPanel { private JPanel jpDesign; private JPanel jpMakeDesign; private JPanel jpDisplay; private JPanel jpDisplayPanel; private JPanel jpDisplayControls; private JComboBox jcDatabase; private JComboBox jcWeb; private JComboBox jcFirewall; private JButton jbOpt; private JButton saveButton; private JLabel jlPrice; private JLabel jlAvailability; private JTable jTable; private DefaultTableModel tableModel; public DesignPanel() { setLayout(new GridLayout(0, 2)); jpMakeDesign = new JPanel(); jpMakeDesign.setPreferredSize(new Dimension(600, 650)); jpMakeDesign.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0)); //Make panel left side jpDesign = new JPanel(); add(jpDesign); jpDesign.setLayout(new FlowLayout()); jpDesign.add(jpMakeDesign); //init Content left panel jcDatabase = new JComboBox(new String[]{""}); jcDatabase.setPreferredSize(new Dimension(120, 17)); jcWeb = new JComboBox(new String[]{""}); jcWeb.setPreferredSize(new Dimension(120, 17)); jcFirewall = new JComboBox(new String[]{""}); jcFirewall.setPreferredSize(new Dimension(120, 17)); jcDatabase.setRenderer(new ComboRenderer("Databaseservers")); jcDatabase.setSelectedIndex(-1); jcWeb.setRenderer(new ComboRenderer("Webservers")); jcWeb.setSelectedIndex(-1); jcFirewall.setRenderer(new ComboRenderer("Firewall")); jcFirewall.setSelectedIndex(-1); tableModel = new DefaultTableModel() { @Override public boolean isCellEditable(int row, int column) { //Add custom amount if (column == 4) return true; //make buttons function if (column == 5 || column == 6 || column == 7) return true; return false; } //Only able to enter integer in amount column @Override public Class<?> getColumnClass(int columnIndex) { if (columnIndex == 4) return Integer.class; return super.getColumnClass(columnIndex); } @Override //check if amount is not negative and/or below 1 public void fireTableCellUpdated(int row, int column) { if (column == 4) { if (Integer.parseInt(super.getValueAt(row, column).toString()) < 0) super.setValueAt(Integer.parseInt(super.getValueAt(row, column).toString()) * -1, row, column); else if (Integer.parseInt(super.getValueAt(row, column).toString()) < 1) super.setValueAt(1, row, column); } super.fireTableCellUpdated(row, column); } }; //adds the columnnames tableModel.addColumn("Type"); tableModel.addColumn("Naam"); tableModel.addColumn("Beschikbaarheid"); tableModel.addColumn("Prijs"); tableModel.addColumn("Aantal"); tableModel.addColumn("Verhogen"); tableModel.addColumn("Verlagen"); tableModel.addColumn("Verwijder"); jTable = new JTable(tableModel); JScrollPane sp = new JScrollPane(jTable); sp.setPreferredSize(new Dimension(550, 590)); sp.setBorder(BorderFactory.createLineBorder(Color.black)); saveButton = new JButton("Opslaan Als"); jpMakeDesign.add(jcDatabase); jpMakeDesign.add(jcWeb); jpMakeDesign.add(jcFirewall); jpMakeDesign.add(sp); jpMakeDesign.add(saveButton); jlPrice = new JLabel("€0.0"); jlAvailability = new JLabel("0.0%"); //Panels right side //jpDisplayPanel is for graphics jpDisplay = new JPanel(); add(jpDisplay); jpDisplay.setLayout(new FlowLayout()); jpDisplayPanel = new JPanel(); jpDisplayPanel.setPreferredSize(new Dimension(550, 590)); jpDisplayPanel.setBorder(BorderFactory.createLineBorder(Color.black)); jpDisplayControls = new JPanel(); jpDisplayControls.setPreferredSize(new Dimension(600, 650)); jpDisplayControls.setBorder(BorderFactory.createEmptyBorder(0, 50, 0, 50)); //init Content right panel jbOpt = new JButton("Optimaliseer"); //Add all content jpDisplay.add(jpDisplayControls); jpDisplayControls.add(jbOpt); jpDisplayControls.add(jpDisplayPanel); jpDisplayControls.add(new JLabel("Prijs")); jpDisplayControls.add(jlPrice); jpDisplayControls.add(new JLabel("Beschikbaarheid")); jpDisplayControls.add(jlAvailability); } public JComboBox getJcDatabase() { return jcDatabase; } public JComboBox getJcFirewall() { return jcFirewall; } public JComboBox getJcWeb() { return jcWeb; } public JButton getJbOpt() { return jbOpt; } public JButton getSaveButton() { return saveButton; } public JLabel getJlPrice() { return jlPrice; } public JLabel getJlAvailability() { return jlAvailability; } public JTable getJTable() { return jTable; } public DefaultTableModel getTableModel() { return tableModel; } public JPanel getJpDisplayPanel() { return jpDisplayPanel; } }
DylanMRoubos/ICTM2o2
NerdyGadgetsApp/src/main/java/site/nerdygadgets/views/DesignPanel.java
1,753
//init Content left panel
line_comment
nl
package site.nerdygadgets.views; import site.nerdygadgets.functions.ComboRenderer; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; /** * DesignPanel class * DesignPanel for infrastructures * * @author Tristan Scholten & Jordy Wielaard * @version 1.0 * @since 14-05-2020 */ public class DesignPanel extends JPanel { private JPanel jpDesign; private JPanel jpMakeDesign; private JPanel jpDisplay; private JPanel jpDisplayPanel; private JPanel jpDisplayControls; private JComboBox jcDatabase; private JComboBox jcWeb; private JComboBox jcFirewall; private JButton jbOpt; private JButton saveButton; private JLabel jlPrice; private JLabel jlAvailability; private JTable jTable; private DefaultTableModel tableModel; public DesignPanel() { setLayout(new GridLayout(0, 2)); jpMakeDesign = new JPanel(); jpMakeDesign.setPreferredSize(new Dimension(600, 650)); jpMakeDesign.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0)); //Make panel left side jpDesign = new JPanel(); add(jpDesign); jpDesign.setLayout(new FlowLayout()); jpDesign.add(jpMakeDesign); //init Content<SUF> jcDatabase = new JComboBox(new String[]{""}); jcDatabase.setPreferredSize(new Dimension(120, 17)); jcWeb = new JComboBox(new String[]{""}); jcWeb.setPreferredSize(new Dimension(120, 17)); jcFirewall = new JComboBox(new String[]{""}); jcFirewall.setPreferredSize(new Dimension(120, 17)); jcDatabase.setRenderer(new ComboRenderer("Databaseservers")); jcDatabase.setSelectedIndex(-1); jcWeb.setRenderer(new ComboRenderer("Webservers")); jcWeb.setSelectedIndex(-1); jcFirewall.setRenderer(new ComboRenderer("Firewall")); jcFirewall.setSelectedIndex(-1); tableModel = new DefaultTableModel() { @Override public boolean isCellEditable(int row, int column) { //Add custom amount if (column == 4) return true; //make buttons function if (column == 5 || column == 6 || column == 7) return true; return false; } //Only able to enter integer in amount column @Override public Class<?> getColumnClass(int columnIndex) { if (columnIndex == 4) return Integer.class; return super.getColumnClass(columnIndex); } @Override //check if amount is not negative and/or below 1 public void fireTableCellUpdated(int row, int column) { if (column == 4) { if (Integer.parseInt(super.getValueAt(row, column).toString()) < 0) super.setValueAt(Integer.parseInt(super.getValueAt(row, column).toString()) * -1, row, column); else if (Integer.parseInt(super.getValueAt(row, column).toString()) < 1) super.setValueAt(1, row, column); } super.fireTableCellUpdated(row, column); } }; //adds the columnnames tableModel.addColumn("Type"); tableModel.addColumn("Naam"); tableModel.addColumn("Beschikbaarheid"); tableModel.addColumn("Prijs"); tableModel.addColumn("Aantal"); tableModel.addColumn("Verhogen"); tableModel.addColumn("Verlagen"); tableModel.addColumn("Verwijder"); jTable = new JTable(tableModel); JScrollPane sp = new JScrollPane(jTable); sp.setPreferredSize(new Dimension(550, 590)); sp.setBorder(BorderFactory.createLineBorder(Color.black)); saveButton = new JButton("Opslaan Als"); jpMakeDesign.add(jcDatabase); jpMakeDesign.add(jcWeb); jpMakeDesign.add(jcFirewall); jpMakeDesign.add(sp); jpMakeDesign.add(saveButton); jlPrice = new JLabel("€0.0"); jlAvailability = new JLabel("0.0%"); //Panels right side //jpDisplayPanel is for graphics jpDisplay = new JPanel(); add(jpDisplay); jpDisplay.setLayout(new FlowLayout()); jpDisplayPanel = new JPanel(); jpDisplayPanel.setPreferredSize(new Dimension(550, 590)); jpDisplayPanel.setBorder(BorderFactory.createLineBorder(Color.black)); jpDisplayControls = new JPanel(); jpDisplayControls.setPreferredSize(new Dimension(600, 650)); jpDisplayControls.setBorder(BorderFactory.createEmptyBorder(0, 50, 0, 50)); //init Content right panel jbOpt = new JButton("Optimaliseer"); //Add all content jpDisplay.add(jpDisplayControls); jpDisplayControls.add(jbOpt); jpDisplayControls.add(jpDisplayPanel); jpDisplayControls.add(new JLabel("Prijs")); jpDisplayControls.add(jlPrice); jpDisplayControls.add(new JLabel("Beschikbaarheid")); jpDisplayControls.add(jlAvailability); } public JComboBox getJcDatabase() { return jcDatabase; } public JComboBox getJcFirewall() { return jcFirewall; } public JComboBox getJcWeb() { return jcWeb; } public JButton getJbOpt() { return jbOpt; } public JButton getSaveButton() { return saveButton; } public JLabel getJlPrice() { return jlPrice; } public JLabel getJlAvailability() { return jlAvailability; } public JTable getJTable() { return jTable; } public DefaultTableModel getTableModel() { return tableModel; } public JPanel getJpDisplayPanel() { return jpDisplayPanel; } }
False
1,270
5
1,391
5
1,465
5
1,391
5
1,761
5
false
false
false
false
false
true
880
156331_6
/*_x000D_ * Copyright (c) 2014, Netherlands Forensic Institute_x000D_ * All rights reserved._x000D_ */_x000D_ package nl.minvenj.nfi.common_source_identification;_x000D_ _x000D_ import java.awt.color.CMMException;_x000D_ import java.awt.image.BufferedImage;_x000D_ import java.awt.image.ColorModel;_x000D_ import java.io.BufferedInputStream;_x000D_ import java.io.BufferedOutputStream;_x000D_ import java.io.File;_x000D_ import java.io.FileInputStream;_x000D_ import java.io.FileOutputStream;_x000D_ import java.io.IOException;_x000D_ import java.io.InputStream;_x000D_ import java.io.ObjectInputStream;_x000D_ import java.io.ObjectOutputStream;_x000D_ import java.io.OutputStream;_x000D_ _x000D_ import javax.imageio.ImageIO;_x000D_ _x000D_ import nl.minvenj.nfi.common_source_identification.filter.FastNoiseFilter;_x000D_ import nl.minvenj.nfi.common_source_identification.filter.ImageFilter;_x000D_ import nl.minvenj.nfi.common_source_identification.filter.WienerFilter;_x000D_ import nl.minvenj.nfi.common_source_identification.filter.ZeroMeanTotalFilter;_x000D_ _x000D_ public final class CommonSourceIdentification {_x000D_ static final File TESTDATA_FOLDER = new File("testdata");_x000D_ _x000D_ static final File INPUT_FOLDER = new File(TESTDATA_FOLDER, "input");_x000D_ // public static final File INPUT_FILE = new File(INPUT_FOLDER, "test.jpg");_x000D_ public static final File INPUT_FILE = new File("/var/scratch/bwn200/Dresden/2748x3664/Kodak_M1063_4_12664.JPG");_x000D_ static final File EXPECTED_PATTERN_FILE = new File(INPUT_FOLDER, "expected.pat");_x000D_ _x000D_ static final File OUTPUT_FOLDER = new File(TESTDATA_FOLDER, "output");_x000D_ static final File OUTPUT_FILE = new File(OUTPUT_FOLDER, "test.pat");_x000D_ _x000D_ public static void main(final String[] args) throws IOException {_x000D_ long start = System.currentTimeMillis();_x000D_ long end = 0;_x000D_ _x000D_ // Laad de input file in_x000D_ final BufferedImage image = readImage(INPUT_FILE);_x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Load image: " + (end-start) + " ms.");_x000D_ _x000D_ // Zet de input file om in 3 matrices (rood, groen, blauw)_x000D_ start = System.currentTimeMillis();_x000D_ final float[][][] rgbArrays = convertImageToFloatArrays(image);_x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Convert image:" + (end-start) + " ms.");_x000D_ _x000D_ // Bereken van elke matrix het PRNU patroon (extractie stap)_x000D_ start = System.currentTimeMillis();_x000D_ for (int i = 0; i < 3; i++) {_x000D_ extractImage(rgbArrays[i]);_x000D_ }_x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("PRNU extracted: " + (end-start) + " ms.");_x000D_ _x000D_ // Schrijf het patroon weg als een Java object_x000D_ writeJavaObject(rgbArrays, OUTPUT_FILE);_x000D_ _x000D_ System.out.println("Pattern written");_x000D_ _x000D_ // Controleer nu het gemaakte bestand_x000D_ final float[][][] expectedPattern = (float[][][]) readJavaObject(EXPECTED_PATTERN_FILE);_x000D_ final float[][][] actualPattern = (float[][][]) readJavaObject(OUTPUT_FILE);_x000D_ for (int i = 0; i < 3; i++) {_x000D_ // Het patroon zoals dat uit PRNU Compare komt, bevat een extra matrix voor transparantie. Deze moeten we overslaan (+1)!_x000D_ compare2DArray(expectedPattern[i + 1], actualPattern[i], 0.0001f);_x000D_ }_x000D_ _x000D_ System.out.println("Validation completed");_x000D_ _x000D_ //This exit is inserted because the program will otherwise hang for a about a minute_x000D_ //most likely explanation for this is the fact that the FFT library spawns a couple_x000D_ //of threads which cannot be properly destroyed_x000D_ System.exit(0);_x000D_ }_x000D_ _x000D_ private static BufferedImage readImage(final File file) throws IOException {_x000D_ final InputStream fileInputStream = new FileInputStream(file);_x000D_ try {_x000D_ final BufferedImage image = ImageIO.read(new BufferedInputStream(fileInputStream));_x000D_ if ((image != null) && (image.getWidth() >= 0) && (image.getHeight() >= 0)) {_x000D_ return image;_x000D_ }_x000D_ }_x000D_ catch (final CMMException e) {_x000D_ // Image file is unsupported or corrupt_x000D_ }_x000D_ catch (final RuntimeException e) {_x000D_ // Internal error processing image file_x000D_ }_x000D_ catch (final IOException e) {_x000D_ // Error reading image from disk_x000D_ }_x000D_ finally {_x000D_ fileInputStream.close();_x000D_ }_x000D_ _x000D_ // Image unreadable or too smalld array_x000D_ return null;_x000D_ }_x000D_ _x000D_ private static float[][][] convertImageToFloatArrays(final BufferedImage image) {_x000D_ final int width = image.getWidth();_x000D_ final int height = image.getHeight();_x000D_ final float[][][] pixels = new float[3][height][width];_x000D_ _x000D_ final ColorModel colorModel = ColorModel.getRGBdefault();_x000D_ for (int y = 0; y < height; y++) {_x000D_ for (int x = 0; x < width; x++) {_x000D_ final int pixel = image.getRGB(x, y); // aa bb gg rr_x000D_ pixels[0][y][x] = colorModel.getRed(pixel);_x000D_ pixels[1][y][x] = colorModel.getGreen(pixel);_x000D_ pixels[2][y][x] = colorModel.getBlue(pixel);_x000D_ }_x000D_ }_x000D_ return pixels;_x000D_ }_x000D_ _x000D_ private static void extractImage(final float[][] pixels) {_x000D_ final int width = pixels[0].length;_x000D_ final int height = pixels.length;_x000D_ _x000D_ long start = System.currentTimeMillis();_x000D_ long end = 0;_x000D_ _x000D_ final ImageFilter fastNoiseFilter = new FastNoiseFilter(width, height);_x000D_ fastNoiseFilter.apply(pixels);_x000D_ _x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Fast Noise Filter: " + (end-start) + " ms.");_x000D_ _x000D_ start = System.currentTimeMillis();_x000D_ final ImageFilter zeroMeanTotalFilter = new ZeroMeanTotalFilter(width, height);_x000D_ zeroMeanTotalFilter.apply(pixels);_x000D_ _x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Zero Mean Filter: " + (end-start) + " ms.");_x000D_ _x000D_ start = System.currentTimeMillis();_x000D_ final ImageFilter wienerFilter = new WienerFilter(width, height);_x000D_ wienerFilter.apply(pixels);_x000D_ _x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Wiener Filter: " + (end-start) + " ms.");_x000D_ }_x000D_ _x000D_ public static Object readJavaObject(final File inputFile) throws IOException {_x000D_ final ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile)));_x000D_ try {_x000D_ return inputStream.readObject();_x000D_ }_x000D_ catch (final ClassNotFoundException e) {_x000D_ throw new IOException("Cannot read pattern: " + inputFile.getAbsolutePath(), e);_x000D_ }_x000D_ finally {_x000D_ inputStream.close();_x000D_ }_x000D_ }_x000D_ _x000D_ private static void writeJavaObject(final Object object, final File outputFile) throws IOException {_x000D_ final OutputStream outputStream = new FileOutputStream(outputFile);_x000D_ try {_x000D_ final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream));_x000D_ objectOutputStream.writeObject(object);_x000D_ objectOutputStream.close();_x000D_ }_x000D_ finally {_x000D_ outputStream.close();_x000D_ }_x000D_ }_x000D_ _x000D_ private static boolean compare2DArray(final float[][] expected, final float[][] actual, final float delta) {_x000D_ for (int i = 0; i < expected.length; i++) {_x000D_ for (int j = 0; j < expected[i].length; j++) {_x000D_ if (Math.abs(actual[i][j] - expected[i][j]) > delta) {_x000D_ System.err.println("de waarde op " + i + "," + j + " is " + actual[i][j] + " maar had moeten zijn " + expected[i][j]);_x000D_ return false;_x000D_ }_x000D_ }_x000D_ }_x000D_ return true;_x000D_ }_x000D_ _x000D_ }_x000D_
JungleComputing/common-source-identification-desktop
src/main/java/nl/minvenj/nfi/common_source_identification/CommonSourceIdentification.java
2,232
// Controleer nu het gemaakte bestand_x000D_
line_comment
nl
/*_x000D_ * Copyright (c) 2014, Netherlands Forensic Institute_x000D_ * All rights reserved._x000D_ */_x000D_ package nl.minvenj.nfi.common_source_identification;_x000D_ _x000D_ import java.awt.color.CMMException;_x000D_ import java.awt.image.BufferedImage;_x000D_ import java.awt.image.ColorModel;_x000D_ import java.io.BufferedInputStream;_x000D_ import java.io.BufferedOutputStream;_x000D_ import java.io.File;_x000D_ import java.io.FileInputStream;_x000D_ import java.io.FileOutputStream;_x000D_ import java.io.IOException;_x000D_ import java.io.InputStream;_x000D_ import java.io.ObjectInputStream;_x000D_ import java.io.ObjectOutputStream;_x000D_ import java.io.OutputStream;_x000D_ _x000D_ import javax.imageio.ImageIO;_x000D_ _x000D_ import nl.minvenj.nfi.common_source_identification.filter.FastNoiseFilter;_x000D_ import nl.minvenj.nfi.common_source_identification.filter.ImageFilter;_x000D_ import nl.minvenj.nfi.common_source_identification.filter.WienerFilter;_x000D_ import nl.minvenj.nfi.common_source_identification.filter.ZeroMeanTotalFilter;_x000D_ _x000D_ public final class CommonSourceIdentification {_x000D_ static final File TESTDATA_FOLDER = new File("testdata");_x000D_ _x000D_ static final File INPUT_FOLDER = new File(TESTDATA_FOLDER, "input");_x000D_ // public static final File INPUT_FILE = new File(INPUT_FOLDER, "test.jpg");_x000D_ public static final File INPUT_FILE = new File("/var/scratch/bwn200/Dresden/2748x3664/Kodak_M1063_4_12664.JPG");_x000D_ static final File EXPECTED_PATTERN_FILE = new File(INPUT_FOLDER, "expected.pat");_x000D_ _x000D_ static final File OUTPUT_FOLDER = new File(TESTDATA_FOLDER, "output");_x000D_ static final File OUTPUT_FILE = new File(OUTPUT_FOLDER, "test.pat");_x000D_ _x000D_ public static void main(final String[] args) throws IOException {_x000D_ long start = System.currentTimeMillis();_x000D_ long end = 0;_x000D_ _x000D_ // Laad de input file in_x000D_ final BufferedImage image = readImage(INPUT_FILE);_x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Load image: " + (end-start) + " ms.");_x000D_ _x000D_ // Zet de input file om in 3 matrices (rood, groen, blauw)_x000D_ start = System.currentTimeMillis();_x000D_ final float[][][] rgbArrays = convertImageToFloatArrays(image);_x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Convert image:" + (end-start) + " ms.");_x000D_ _x000D_ // Bereken van elke matrix het PRNU patroon (extractie stap)_x000D_ start = System.currentTimeMillis();_x000D_ for (int i = 0; i < 3; i++) {_x000D_ extractImage(rgbArrays[i]);_x000D_ }_x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("PRNU extracted: " + (end-start) + " ms.");_x000D_ _x000D_ // Schrijf het patroon weg als een Java object_x000D_ writeJavaObject(rgbArrays, OUTPUT_FILE);_x000D_ _x000D_ System.out.println("Pattern written");_x000D_ _x000D_ // Controleer nu<SUF> final float[][][] expectedPattern = (float[][][]) readJavaObject(EXPECTED_PATTERN_FILE);_x000D_ final float[][][] actualPattern = (float[][][]) readJavaObject(OUTPUT_FILE);_x000D_ for (int i = 0; i < 3; i++) {_x000D_ // Het patroon zoals dat uit PRNU Compare komt, bevat een extra matrix voor transparantie. Deze moeten we overslaan (+1)!_x000D_ compare2DArray(expectedPattern[i + 1], actualPattern[i], 0.0001f);_x000D_ }_x000D_ _x000D_ System.out.println("Validation completed");_x000D_ _x000D_ //This exit is inserted because the program will otherwise hang for a about a minute_x000D_ //most likely explanation for this is the fact that the FFT library spawns a couple_x000D_ //of threads which cannot be properly destroyed_x000D_ System.exit(0);_x000D_ }_x000D_ _x000D_ private static BufferedImage readImage(final File file) throws IOException {_x000D_ final InputStream fileInputStream = new FileInputStream(file);_x000D_ try {_x000D_ final BufferedImage image = ImageIO.read(new BufferedInputStream(fileInputStream));_x000D_ if ((image != null) && (image.getWidth() >= 0) && (image.getHeight() >= 0)) {_x000D_ return image;_x000D_ }_x000D_ }_x000D_ catch (final CMMException e) {_x000D_ // Image file is unsupported or corrupt_x000D_ }_x000D_ catch (final RuntimeException e) {_x000D_ // Internal error processing image file_x000D_ }_x000D_ catch (final IOException e) {_x000D_ // Error reading image from disk_x000D_ }_x000D_ finally {_x000D_ fileInputStream.close();_x000D_ }_x000D_ _x000D_ // Image unreadable or too smalld array_x000D_ return null;_x000D_ }_x000D_ _x000D_ private static float[][][] convertImageToFloatArrays(final BufferedImage image) {_x000D_ final int width = image.getWidth();_x000D_ final int height = image.getHeight();_x000D_ final float[][][] pixels = new float[3][height][width];_x000D_ _x000D_ final ColorModel colorModel = ColorModel.getRGBdefault();_x000D_ for (int y = 0; y < height; y++) {_x000D_ for (int x = 0; x < width; x++) {_x000D_ final int pixel = image.getRGB(x, y); // aa bb gg rr_x000D_ pixels[0][y][x] = colorModel.getRed(pixel);_x000D_ pixels[1][y][x] = colorModel.getGreen(pixel);_x000D_ pixels[2][y][x] = colorModel.getBlue(pixel);_x000D_ }_x000D_ }_x000D_ return pixels;_x000D_ }_x000D_ _x000D_ private static void extractImage(final float[][] pixels) {_x000D_ final int width = pixels[0].length;_x000D_ final int height = pixels.length;_x000D_ _x000D_ long start = System.currentTimeMillis();_x000D_ long end = 0;_x000D_ _x000D_ final ImageFilter fastNoiseFilter = new FastNoiseFilter(width, height);_x000D_ fastNoiseFilter.apply(pixels);_x000D_ _x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Fast Noise Filter: " + (end-start) + " ms.");_x000D_ _x000D_ start = System.currentTimeMillis();_x000D_ final ImageFilter zeroMeanTotalFilter = new ZeroMeanTotalFilter(width, height);_x000D_ zeroMeanTotalFilter.apply(pixels);_x000D_ _x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Zero Mean Filter: " + (end-start) + " ms.");_x000D_ _x000D_ start = System.currentTimeMillis();_x000D_ final ImageFilter wienerFilter = new WienerFilter(width, height);_x000D_ wienerFilter.apply(pixels);_x000D_ _x000D_ end = System.currentTimeMillis();_x000D_ System.out.println("Wiener Filter: " + (end-start) + " ms.");_x000D_ }_x000D_ _x000D_ public static Object readJavaObject(final File inputFile) throws IOException {_x000D_ final ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile)));_x000D_ try {_x000D_ return inputStream.readObject();_x000D_ }_x000D_ catch (final ClassNotFoundException e) {_x000D_ throw new IOException("Cannot read pattern: " + inputFile.getAbsolutePath(), e);_x000D_ }_x000D_ finally {_x000D_ inputStream.close();_x000D_ }_x000D_ }_x000D_ _x000D_ private static void writeJavaObject(final Object object, final File outputFile) throws IOException {_x000D_ final OutputStream outputStream = new FileOutputStream(outputFile);_x000D_ try {_x000D_ final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream));_x000D_ objectOutputStream.writeObject(object);_x000D_ objectOutputStream.close();_x000D_ }_x000D_ finally {_x000D_ outputStream.close();_x000D_ }_x000D_ }_x000D_ _x000D_ private static boolean compare2DArray(final float[][] expected, final float[][] actual, final float delta) {_x000D_ for (int i = 0; i < expected.length; i++) {_x000D_ for (int j = 0; j < expected[i].length; j++) {_x000D_ if (Math.abs(actual[i][j] - expected[i][j]) > delta) {_x000D_ System.err.println("de waarde op " + i + "," + j + " is " + actual[i][j] + " maar had moeten zijn " + expected[i][j]);_x000D_ return false;_x000D_ }_x000D_ }_x000D_ }_x000D_ return true;_x000D_ }_x000D_ _x000D_ }_x000D_
True
2,847
17
3,120
19
3,229
15
3,120
19
3,470
18
false
false
false
false
false
true
1,759
32522_0
package nl.tomkemper.usessoap; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class ClientRunner implements CommandLineRunner { private final CountryClient client; public ClientRunner(CountryClient client){ this.client = client; } @Override public void run(String... args) throws Exception { Thread.sleep(1000); //lelijke hack om even te wachten tot de webservice wakker is:) var resp = this.client.getCountry("Nederland"); System.out.println(resp.getCountry().getName()); } }
TomKemperNL/usessoap
client/src/main/java/nl/tomkemper/usessoap/ClientRunner.java
168
//lelijke hack om even te wachten tot de webservice wakker is:)
line_comment
nl
package nl.tomkemper.usessoap; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class ClientRunner implements CommandLineRunner { private final CountryClient client; public ClientRunner(CountryClient client){ this.client = client; } @Override public void run(String... args) throws Exception { Thread.sleep(1000); //lelijke hack<SUF> var resp = this.client.getCountry("Nederland"); System.out.println(resp.getCountry().getName()); } }
True
126
18
151
20
153
16
151
20
170
19
false
false
false
false
false
true
3,866
15147_7
package osoc.leiedal.android.aandacht.View; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.astuetz.PagerSlidingTabStrip; import com.google.android.gms.gcm.GoogleCloudMessaging; import java.io.IOException; import osoc.leiedal.android.aandacht.R; import osoc.leiedal.android.aandacht.View.fragments.ReportTabFragment; public class ViewReportsActivity extends ParentActivity implements View.OnCreateContextMenuListener { /* ============================================================================================ NESTED CLASSES ============================================================================================ */ private class MyPagerAdapter extends FragmentPagerAdapter { private final String[] TITLES = { getResources().getString(R.string.tab_reports_active), getResources().getString(R.string.tab_reports_all), getResources().getString(R.string.tab_reports_mine) }; public MyPagerAdapter(FragmentManager fm) { super(fm); } @Override public CharSequence getPageTitle(int position) { return TITLES[position]; } @Override public int getCount() { return TITLES.length; } @Override public Fragment getItem(int position) { return ReportTabFragment.instantiate(position); } } /* ============================================================================================ METHODS ============================================================================================ */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.view_reports, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { super.onBackPressed(); //clear login data getSharedPreferences(getResources().getString(R.string.app_pref), 0).edit().clear().commit(); this.startActivity(new Intent(this, LoginActivity.class)); } public void call(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.reports_popup_title); builder.setMessage(R.string.reports_popup_text); builder.setPositiveButton(R.string.reports_btnCall, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:0478927411")); startActivity(callIntent); } }); builder.setNegativeButton(R.string.reports_popup_btnCancel, null); AlertDialog dialog = builder.show(); TextView messageText = (TextView) dialog.findViewById(android.R.id.message); messageText.setGravity(Gravity.CENTER); dialog.show(); } // -------------------------------------------------------------------------------------------- @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //get reports in area setContentView(R.layout.activity_view_reports); PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs); ViewPager pager = (ViewPager) findViewById(R.id.pager); MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager()); tabs.setIndicatorColor(getResources().getColor(R.color.aandacht_dark_blue)); tabs.setTextColor(getResources().getColor(R.color.aandacht_dark_blue)); tabs.setBackgroundColor(getResources().getColor(R.color.aandacht_background)); pager.setAdapter(adapter); tabs.setViewPager(pager); } @Override protected void onResume() { super.onResume(); } // UNUSED METHOD /** public void send(final View view) { new AsyncTask() { @Override protected Object doInBackground(Object[] params) { String msg = ""; try { Bundle data = new Bundle(); data.putString("my_message", "Hello World"); data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW"); String id = Long.toString(System.currentTimeMillis()); GoogleCloudMessaging.getInstance(getApplicationContext()) .send(LoginActivity.SENDER_ID + "@gcm.googleapis.com", id, data); msg = "Sent message"; } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } }.execute(null, null, null); } */ }
oSoc14/Leiedal-ComProNet-Android
Aandacht/app/src/main/java/osoc/leiedal/android/aandacht/View/ViewReportsActivity.java
1,544
//get reports in area
line_comment
nl
package osoc.leiedal.android.aandacht.View; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.astuetz.PagerSlidingTabStrip; import com.google.android.gms.gcm.GoogleCloudMessaging; import java.io.IOException; import osoc.leiedal.android.aandacht.R; import osoc.leiedal.android.aandacht.View.fragments.ReportTabFragment; public class ViewReportsActivity extends ParentActivity implements View.OnCreateContextMenuListener { /* ============================================================================================ NESTED CLASSES ============================================================================================ */ private class MyPagerAdapter extends FragmentPagerAdapter { private final String[] TITLES = { getResources().getString(R.string.tab_reports_active), getResources().getString(R.string.tab_reports_all), getResources().getString(R.string.tab_reports_mine) }; public MyPagerAdapter(FragmentManager fm) { super(fm); } @Override public CharSequence getPageTitle(int position) { return TITLES[position]; } @Override public int getCount() { return TITLES.length; } @Override public Fragment getItem(int position) { return ReportTabFragment.instantiate(position); } } /* ============================================================================================ METHODS ============================================================================================ */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.view_reports, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { super.onBackPressed(); //clear login data getSharedPreferences(getResources().getString(R.string.app_pref), 0).edit().clear().commit(); this.startActivity(new Intent(this, LoginActivity.class)); } public void call(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.reports_popup_title); builder.setMessage(R.string.reports_popup_text); builder.setPositiveButton(R.string.reports_btnCall, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:0478927411")); startActivity(callIntent); } }); builder.setNegativeButton(R.string.reports_popup_btnCancel, null); AlertDialog dialog = builder.show(); TextView messageText = (TextView) dialog.findViewById(android.R.id.message); messageText.setGravity(Gravity.CENTER); dialog.show(); } // -------------------------------------------------------------------------------------------- @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //get reports<SUF> setContentView(R.layout.activity_view_reports); PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs); ViewPager pager = (ViewPager) findViewById(R.id.pager); MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager()); tabs.setIndicatorColor(getResources().getColor(R.color.aandacht_dark_blue)); tabs.setTextColor(getResources().getColor(R.color.aandacht_dark_blue)); tabs.setBackgroundColor(getResources().getColor(R.color.aandacht_background)); pager.setAdapter(adapter); tabs.setViewPager(pager); } @Override protected void onResume() { super.onResume(); } // UNUSED METHOD /** public void send(final View view) { new AsyncTask() { @Override protected Object doInBackground(Object[] params) { String msg = ""; try { Bundle data = new Bundle(); data.putString("my_message", "Hello World"); data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW"); String id = Long.toString(System.currentTimeMillis()); GoogleCloudMessaging.getInstance(getApplicationContext()) .send(LoginActivity.SENDER_ID + "@gcm.googleapis.com", id, data); msg = "Sent message"; } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } }.execute(null, null, null); } */ }
False
976
5
1,237
5
1,316
5
1,237
5
1,514
5
false
false
false
false
false
true
763
181882_0
package me.kyllian.netflixstatistix.controllers; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import me.kyllian.netflixstatistix.NetflixStatistix; import me.kyllian.netflixstatistix.models.PercentagePerEpisodeModel; import me.kyllian.netflixstatistix.post.PostBuilder; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; public class PercentagePerEpisodeController extends Controller implements Initializable { //Voor een geselecteerde account en serie, geef per aflevering het gemiddeld //bekeken percentage van de totale tijdsduur. @FXML private TableView<PercentagePerEpisodeModel> table; @FXML private TableColumn<PercentagePerEpisodeModel, String> tableSerie; @FXML private TableColumn<PercentagePerEpisodeModel, Integer> tableEpisode; @FXML private TableColumn<PercentagePerEpisodeModel, Integer> tableAverageTime; @Override public void initialize(URL location, ResourceBundle resources) { tableSerie.setCellValueFactory(new PropertyValueFactory<>("Serie")); tableEpisode.setCellValueFactory(new PropertyValueFactory<>("Episode")); tableAverageTime.setCellValueFactory(new PropertyValueFactory<>("AverageTime")); new PostBuilder() .withIdentifier("averageTime") .post(this); } @Override public void handleResponse(String response) { List<PercentagePerEpisodeModel> percentagePerEpisodeModels = new ArrayList<>(); try { JSONArray array = new JSONArray(response); for (int i = 0; i != array.length(); i++) { JSONObject data = array.getJSONObject(i); percentagePerEpisodeModels.add(new PercentagePerEpisodeModel(data.getString("name_serie"), data.getInt("episode_id"), data.getInt("average"))); } } catch (JSONException exception) { System.out.println("Error reading JSON from server"); exception.printStackTrace(); } table.setItems(FXCollections.observableArrayList(percentagePerEpisodeModels)); } public void back() { try { Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("view/statistic.fxml")); root.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm()); NetflixStatistix.parentWindow.getScene().setRoot(root); } catch (Exception exc) { exc.printStackTrace(); } } }
InstantlyMoist/NetflixStatistix
src/main/java/me/kyllian/netflixstatistix/controllers/PercentagePerEpisodeController.java
834
//Voor een geselecteerde account en serie, geef per aflevering het gemiddeld
line_comment
nl
package me.kyllian.netflixstatistix.controllers; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import me.kyllian.netflixstatistix.NetflixStatistix; import me.kyllian.netflixstatistix.models.PercentagePerEpisodeModel; import me.kyllian.netflixstatistix.post.PostBuilder; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; public class PercentagePerEpisodeController extends Controller implements Initializable { //Voor een<SUF> //bekeken percentage van de totale tijdsduur. @FXML private TableView<PercentagePerEpisodeModel> table; @FXML private TableColumn<PercentagePerEpisodeModel, String> tableSerie; @FXML private TableColumn<PercentagePerEpisodeModel, Integer> tableEpisode; @FXML private TableColumn<PercentagePerEpisodeModel, Integer> tableAverageTime; @Override public void initialize(URL location, ResourceBundle resources) { tableSerie.setCellValueFactory(new PropertyValueFactory<>("Serie")); tableEpisode.setCellValueFactory(new PropertyValueFactory<>("Episode")); tableAverageTime.setCellValueFactory(new PropertyValueFactory<>("AverageTime")); new PostBuilder() .withIdentifier("averageTime") .post(this); } @Override public void handleResponse(String response) { List<PercentagePerEpisodeModel> percentagePerEpisodeModels = new ArrayList<>(); try { JSONArray array = new JSONArray(response); for (int i = 0; i != array.length(); i++) { JSONObject data = array.getJSONObject(i); percentagePerEpisodeModels.add(new PercentagePerEpisodeModel(data.getString("name_serie"), data.getInt("episode_id"), data.getInt("average"))); } } catch (JSONException exception) { System.out.println("Error reading JSON from server"); exception.printStackTrace(); } table.setItems(FXCollections.observableArrayList(percentagePerEpisodeModels)); } public void back() { try { Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("view/statistic.fxml")); root.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm()); NetflixStatistix.parentWindow.getScene().setRoot(root); } catch (Exception exc) { exc.printStackTrace(); } } }
True
553
22
673
25
673
19
673
25
802
24
false
false
false
false
false
true
4,674
87108_4
/** * Author : wardb * naam : Ward Beyens * studentNr : r0703044 */ package fact.it.www; import fact.it.www.beans.Attractie; import fact.it.www.beans.Bezoeker; import fact.it.www.beans.Personeelslid; import fact.it.www.beans.Persoon; import fact.it.www.beans.Pretpark; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Author : wardb * naam : Ward Beyens * studentNr : r0703044 */ @WebServlet(name = "ManageServlet", urlPatterns = {"/ManageServlet"}) public class ManageServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { Personeelslid personeelslidEerste = new Personeelslid("Gertje", "Optnippertje"); Personeelslid personeelslidTweede = new Personeelslid("Thibaut", "Defrisco"); Personeelslid personeelslidDerde = new Personeelslid("Knapen", "Dokter"); Bezoeker bezoeker_1 = new Bezoeker("Noor", "Baeyens"); bezoeker_1.voegToeAanWishlist("Symbolica"); bezoeker_1.voegToeAanWishlist("Droomvlucht"); bezoeker_1.voegToeAanWishlist("Carnaval Festival"); bezoeker_1.voegToeAanWishlist("Fata Morgana"); bezoeker_1.voegToeAanWishlist("Sprookjesbos"); bezoeker_1.setPretparkcode(50); Bezoeker bezoeker_2 = new Bezoeker("Ward", "Beyens"); bezoeker_2.voegToeAanWishlist("Baron 1898"); bezoeker_2.voegToeAanWishlist("Python"); bezoeker_2.voegToeAanWishlist("De Vliegende Hollander"); bezoeker_2.voegToeAanWishlist("Joris en de Draak"); bezoeker_2.voegToeAanWishlist("Fata Morgana"); bezoeker_2.setPretparkcode(100); Persoon persoon = new Persoon("Ryan", "Reynolds"); Pretpark pretpark = new Pretpark("Magneto"); Attractie attractieEerste = new Attractie("Python", 3); attractieEerste.setVerantwoordelijke(personeelslidEerste); Attractie attractieTweede = new Attractie("Symbolica", 6); attractieTweede.setVerantwoordelijke(personeelslidTweede); Attractie attractieDerde = new Attractie("Fata Morgana", 10); attractieDerde.setVerantwoordelijke(personeelslidDerde); pretpark.voegAttractieToe(attractieEerste); pretpark.voegAttractieToe(attractieTweede); pretpark.voegAttractieToe(attractieDerde); /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Ward beyens</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1> Pretpark: " + pretpark.getNaam() + " </h1>"); out.println("<h3> Attracties: </h3>"); /* out.println("<p> " + attractieEerste.getNaam() + " <br> " + "Met als verantwoordelijke: " + attractieEerste.getVerantwoordelijke() + " <br> " + attractieEerste.getFoto()+ " </p>"); out.println("<p> " + attractieTweede.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieTweede.getVerantwoordelijke() + " <br> " + attractieTweede.getFoto()+ " </p>"); out.println("<p> " + attractieDerde.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieDerde.getVerantwoordelijke() + " <br> " + attractieDerde.getFoto()+ " </p>"); */ out.println("<p> " + attractieEerste.getNaam() + " <br> " + "Met als verantwoordelijke: " + attractieEerste.getVerantwoordelijke() + " <br> " + " </p>"); out.println("<p> " + attractieTweede.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieTweede.getVerantwoordelijke() + " <br> " + " </p>"); out.println("<p> " + attractieDerde.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieDerde.getVerantwoordelijke() + " <br> " + " </p>"); out.println("<h3> Bezoekers: </h3>"); out.println("<p> " + bezoeker_1.toString() + " heeft als wishlist: " + " <br> "); for (int i = 0; i < 5; i++) { out.print(bezoeker_1.getWishlist().get(i) + " "); } out.println("</p>"); out.println("<p> " + bezoeker_2.toString() + " heeft als wishlist: " + " <br> "); for (int i = 0; i < 5; i++) { out.print(bezoeker_2.getWishlist().get(i) + " "); } out.println("</p>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
wardbeyens/miniproject-java
Beyens_Ward_r0703044_Pretpark/src/java/fact/it/www/ManageServlet.java
2,071
/* out.println("<p> " + attractieEerste.getNaam() + " <br> " + "Met als verantwoordelijke: " + attractieEerste.getVerantwoordelijke() + " <br> " + attractieEerste.getFoto()+ " </p>"); out.println("<p> " + attractieTweede.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieTweede.getVerantwoordelijke() + " <br> " + attractieTweede.getFoto()+ " </p>"); out.println("<p> " + attractieDerde.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieDerde.getVerantwoordelijke() + " <br> " + attractieDerde.getFoto()+ " </p>"); */
block_comment
nl
/** * Author : wardb * naam : Ward Beyens * studentNr : r0703044 */ package fact.it.www; import fact.it.www.beans.Attractie; import fact.it.www.beans.Bezoeker; import fact.it.www.beans.Personeelslid; import fact.it.www.beans.Persoon; import fact.it.www.beans.Pretpark; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Author : wardb * naam : Ward Beyens * studentNr : r0703044 */ @WebServlet(name = "ManageServlet", urlPatterns = {"/ManageServlet"}) public class ManageServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { Personeelslid personeelslidEerste = new Personeelslid("Gertje", "Optnippertje"); Personeelslid personeelslidTweede = new Personeelslid("Thibaut", "Defrisco"); Personeelslid personeelslidDerde = new Personeelslid("Knapen", "Dokter"); Bezoeker bezoeker_1 = new Bezoeker("Noor", "Baeyens"); bezoeker_1.voegToeAanWishlist("Symbolica"); bezoeker_1.voegToeAanWishlist("Droomvlucht"); bezoeker_1.voegToeAanWishlist("Carnaval Festival"); bezoeker_1.voegToeAanWishlist("Fata Morgana"); bezoeker_1.voegToeAanWishlist("Sprookjesbos"); bezoeker_1.setPretparkcode(50); Bezoeker bezoeker_2 = new Bezoeker("Ward", "Beyens"); bezoeker_2.voegToeAanWishlist("Baron 1898"); bezoeker_2.voegToeAanWishlist("Python"); bezoeker_2.voegToeAanWishlist("De Vliegende Hollander"); bezoeker_2.voegToeAanWishlist("Joris en de Draak"); bezoeker_2.voegToeAanWishlist("Fata Morgana"); bezoeker_2.setPretparkcode(100); Persoon persoon = new Persoon("Ryan", "Reynolds"); Pretpark pretpark = new Pretpark("Magneto"); Attractie attractieEerste = new Attractie("Python", 3); attractieEerste.setVerantwoordelijke(personeelslidEerste); Attractie attractieTweede = new Attractie("Symbolica", 6); attractieTweede.setVerantwoordelijke(personeelslidTweede); Attractie attractieDerde = new Attractie("Fata Morgana", 10); attractieDerde.setVerantwoordelijke(personeelslidDerde); pretpark.voegAttractieToe(attractieEerste); pretpark.voegAttractieToe(attractieTweede); pretpark.voegAttractieToe(attractieDerde); /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Ward beyens</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1> Pretpark: " + pretpark.getNaam() + " </h1>"); out.println("<h3> Attracties: </h3>"); /* out.println("<p> " +<SUF>*/ out.println("<p> " + attractieEerste.getNaam() + " <br> " + "Met als verantwoordelijke: " + attractieEerste.getVerantwoordelijke() + " <br> " + " </p>"); out.println("<p> " + attractieTweede.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieTweede.getVerantwoordelijke() + " <br> " + " </p>"); out.println("<p> " + attractieDerde.getNaam()+ " <br> " + "Met als verantwoordelijke: " + attractieDerde.getVerantwoordelijke() + " <br> " + " </p>"); out.println("<h3> Bezoekers: </h3>"); out.println("<p> " + bezoeker_1.toString() + " heeft als wishlist: " + " <br> "); for (int i = 0; i < 5; i++) { out.print(bezoeker_1.getWishlist().get(i) + " "); } out.println("</p>"); out.println("<p> " + bezoeker_2.toString() + " heeft als wishlist: " + " <br> "); for (int i = 0; i < 5; i++) { out.print(bezoeker_2.getWishlist().get(i) + " "); } out.println("</p>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
False
1,725
189
2,008
229
1,843
184
2,008
229
2,150
216
false
true
false
true
false
false
1,272
128157_1
package nl.pdok; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; /** * * @author Raymond Kroon <[email protected]> */ public class BoyerMoorePatternMatcher { public final static int NO_OF_CHARS = 256; public final static int MAX_BUFFER_SIZE = 1024; private InputStream src; private HashMap<String, PatternCache> cache = new HashMap<>(); private boolean isAtMatch = false; private int bufferSize = 0; private byte[] buffer = new byte[MAX_BUFFER_SIZE]; private int bufferPosition = 0; private String previousPatternId = null; private int suggestedBufferPosition = 0; public BoyerMoorePatternMatcher(InputStream src) { this.src = src; } public boolean currentPositionIsMatch() { return isAtMatch; } public byte[] flushToNextMatch(String patternId) throws IOException { // een stukje buffer lezen, en de buffer aanvullen mits nodig // fuck de copy pasta onzin.... if (previousPatternId != null && previousPatternId.equals(patternId)) { bufferPosition = suggestedBufferPosition; } previousPatternId = patternId; byte[] flushResult = new byte[0]; isAtMatch = false; PatternCache pc = cache.get(patternId); while (true) { SearchResult result = search(buffer, bufferSize, pc.pattern, pc.patternLength, pc.badchars, bufferPosition); bufferPosition = result.offset; suggestedBufferPosition = result.suggestedNewOffset; flushResult = concat(flushResult, flushBuffer()); if (result.matched) { isAtMatch = true; return flushResult; } else { if (!fillBuffer()) { isAtMatch = false; flushResult = concat(flushResult, flushBuffer()); return flushResult; } } } } private byte[] flushBuffer() { // System.out.println("buffer"); // System.out.println(new String(buffer)); // System.out.println("/buffer/" + bufferPosition); byte[] flushed = Arrays.copyOfRange(buffer, 0, bufferPosition); // move currentPosition to front; buffer = Arrays.copyOfRange(buffer, bufferPosition, MAX_BUFFER_SIZE + bufferPosition); bufferSize = bufferSize - bufferPosition; suggestedBufferPosition = suggestedBufferPosition - bufferPosition; bufferPosition = 0; return flushed; } private boolean fillBuffer() throws IOException { if (bufferSize < MAX_BUFFER_SIZE) { int read = src.read(buffer, bufferSize, MAX_BUFFER_SIZE - bufferSize); bufferSize += read; return read > 0; } return true; } public byte[] concat(byte[] a, byte[] b) { int aLen = a.length; int bLen = b.length; byte[] c = new byte[aLen + bLen]; System.arraycopy(a, 0, c, 0, aLen); System.arraycopy(b, 0, c, aLen, bLen); return c; } private class PatternCache { public final byte[] pattern; public final int patternLength; public final int[] badchars; public PatternCache(byte[] pattern) { this.pattern = pattern; this.patternLength = pattern.length; this.badchars = badCharHeuristic(pattern); } } public void setPattern(String id, byte[] pattern) { cache.put(id, new PatternCache(pattern)); } public static int[] badCharHeuristic(byte[] pattern) { int[] result = new int[NO_OF_CHARS]; int patternSize = pattern.length; // default = -1 Arrays.fill(result, -1); for (int i = 0; i < patternSize; ++i) { result[byteValue(pattern[i])] = i; } return result; } public static class SearchResult { public final boolean matched; public final int offset; public final int suggestedNewOffset; public SearchResult(boolean matched, int offset, int suggestedNewOffset) { this.matched = matched; this.offset = offset; this.suggestedNewOffset = suggestedNewOffset; } } public static SearchResult search(byte[] src, byte[] pattern, int offset) { /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ return search(src, src.length, pattern, pattern.length, badCharHeuristic(pattern), offset); } /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */ public static SearchResult search(byte[] src, int srcLength, byte[] pattern, int patternLength, int[] badchars, int offset) { int s = offset; // s is shift of the pattern with respect to text while (s <= (srcLength - patternLength)) { int j = patternLength - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while (j >= 0 && pattern[j] == src[s + j]) { j--; } /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { //System.out.println("pattern found at index = " + s); /* Shift the pattern so that the next character in src aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ //s += (s+patternLength < srcLength) ? patternLength - badchars[src[s+patternLength]] : 1; return new SearchResult(true, s, (s + patternLength < srcLength) ? s + patternLength - badchars[src[s + patternLength]] : s + 1); } else { /* Shift the pattern so that the bad character in src aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += Math.max(1, j - badchars[byteValue(src[s + j])]); } } return new SearchResult(false, srcLength, s); } private static int byteValue(byte b) { return (int) b & 0xFF; } }
PDOK/xml-splitter
src/java/nl/pdok/BoyerMoorePatternMatcher.java
1,748
// een stukje buffer lezen, en de buffer aanvullen mits nodig
line_comment
nl
package nl.pdok; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; /** * * @author Raymond Kroon <[email protected]> */ public class BoyerMoorePatternMatcher { public final static int NO_OF_CHARS = 256; public final static int MAX_BUFFER_SIZE = 1024; private InputStream src; private HashMap<String, PatternCache> cache = new HashMap<>(); private boolean isAtMatch = false; private int bufferSize = 0; private byte[] buffer = new byte[MAX_BUFFER_SIZE]; private int bufferPosition = 0; private String previousPatternId = null; private int suggestedBufferPosition = 0; public BoyerMoorePatternMatcher(InputStream src) { this.src = src; } public boolean currentPositionIsMatch() { return isAtMatch; } public byte[] flushToNextMatch(String patternId) throws IOException { // een stukje<SUF> // fuck de copy pasta onzin.... if (previousPatternId != null && previousPatternId.equals(patternId)) { bufferPosition = suggestedBufferPosition; } previousPatternId = patternId; byte[] flushResult = new byte[0]; isAtMatch = false; PatternCache pc = cache.get(patternId); while (true) { SearchResult result = search(buffer, bufferSize, pc.pattern, pc.patternLength, pc.badchars, bufferPosition); bufferPosition = result.offset; suggestedBufferPosition = result.suggestedNewOffset; flushResult = concat(flushResult, flushBuffer()); if (result.matched) { isAtMatch = true; return flushResult; } else { if (!fillBuffer()) { isAtMatch = false; flushResult = concat(flushResult, flushBuffer()); return flushResult; } } } } private byte[] flushBuffer() { // System.out.println("buffer"); // System.out.println(new String(buffer)); // System.out.println("/buffer/" + bufferPosition); byte[] flushed = Arrays.copyOfRange(buffer, 0, bufferPosition); // move currentPosition to front; buffer = Arrays.copyOfRange(buffer, bufferPosition, MAX_BUFFER_SIZE + bufferPosition); bufferSize = bufferSize - bufferPosition; suggestedBufferPosition = suggestedBufferPosition - bufferPosition; bufferPosition = 0; return flushed; } private boolean fillBuffer() throws IOException { if (bufferSize < MAX_BUFFER_SIZE) { int read = src.read(buffer, bufferSize, MAX_BUFFER_SIZE - bufferSize); bufferSize += read; return read > 0; } return true; } public byte[] concat(byte[] a, byte[] b) { int aLen = a.length; int bLen = b.length; byte[] c = new byte[aLen + bLen]; System.arraycopy(a, 0, c, 0, aLen); System.arraycopy(b, 0, c, aLen, bLen); return c; } private class PatternCache { public final byte[] pattern; public final int patternLength; public final int[] badchars; public PatternCache(byte[] pattern) { this.pattern = pattern; this.patternLength = pattern.length; this.badchars = badCharHeuristic(pattern); } } public void setPattern(String id, byte[] pattern) { cache.put(id, new PatternCache(pattern)); } public static int[] badCharHeuristic(byte[] pattern) { int[] result = new int[NO_OF_CHARS]; int patternSize = pattern.length; // default = -1 Arrays.fill(result, -1); for (int i = 0; i < patternSize; ++i) { result[byteValue(pattern[i])] = i; } return result; } public static class SearchResult { public final boolean matched; public final int offset; public final int suggestedNewOffset; public SearchResult(boolean matched, int offset, int suggestedNewOffset) { this.matched = matched; this.offset = offset; this.suggestedNewOffset = suggestedNewOffset; } } public static SearchResult search(byte[] src, byte[] pattern, int offset) { /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ return search(src, src.length, pattern, pattern.length, badCharHeuristic(pattern), offset); } /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */ public static SearchResult search(byte[] src, int srcLength, byte[] pattern, int patternLength, int[] badchars, int offset) { int s = offset; // s is shift of the pattern with respect to text while (s <= (srcLength - patternLength)) { int j = patternLength - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while (j >= 0 && pattern[j] == src[s + j]) { j--; } /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { //System.out.println("pattern found at index = " + s); /* Shift the pattern so that the next character in src aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ //s += (s+patternLength < srcLength) ? patternLength - badchars[src[s+patternLength]] : 1; return new SearchResult(true, s, (s + patternLength < srcLength) ? s + patternLength - badchars[src[s + patternLength]] : s + 1); } else { /* Shift the pattern so that the bad character in src aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += Math.max(1, j - badchars[byteValue(src[s + j])]); } } return new SearchResult(false, srcLength, s); } private static int byteValue(byte b) { return (int) b & 0xFF; } }
True
1,420
20
1,545
21
1,666
15
1,545
21
1,778
21
false
false
false
false
false
true
1,023
204127_4
/** * Oefening 1.11 * @author Matthew Smet * @import importeren van nodige libraries */ import java.lang.*; /** * klasse Eersteprog gebaseerd op oefening 1.11 met 2 methoden * Methode main met @param args array van strings met meegegeven parameters * Methode drukaf met @param integer m */ public class Eersteprog { public static void main(String args[]) { //Methode drukaf word opgeroepen met parameter 100 drukaf(100); } private static void(int m) { //Locale variablen wordt aangemaakt(a) int a; //herhaalt de lus 100x (meegegeven parameter) for (a=0;a<m;a++) { //print het getal uit in de cmd System.out.println(a); } } }
MTA-Digital-Broadcast-2/C-Vdovlov-Evgeni-Smet-Matthew-Project-MHP
Matthew smet - Oefeningen Java + mhp/LaboJava/blz12/Eersteprog.java
249
//herhaalt de lus 100x (meegegeven parameter)
line_comment
nl
/** * Oefening 1.11 * @author Matthew Smet * @import importeren van nodige libraries */ import java.lang.*; /** * klasse Eersteprog gebaseerd op oefening 1.11 met 2 methoden * Methode main met @param args array van strings met meegegeven parameters * Methode drukaf met @param integer m */ public class Eersteprog { public static void main(String args[]) { //Methode drukaf word opgeroepen met parameter 100 drukaf(100); } private static void(int m) { //Locale variablen wordt aangemaakt(a) int a; //herhaalt de<SUF> for (a=0;a<m;a++) { //print het getal uit in de cmd System.out.println(a); } } }
True
227
20
256
19
236
16
256
19
268
19
false
false
false
false
false
true
4,503
10426_10
package model.datum; import java.util.Date; /** * * @author Isaak * */ public class Datum { private int dag; private int maand; private int jaar; /** * @throws Exception * */ public Datum() throws Exception { HuidigeSysteemDatum(); } /** * * @param Datum * @throws Exception */ @SuppressWarnings("deprecation") public Datum(Date datum) throws Exception { setDatum(datum.getDate(), datum.getMonth() + 1, datum.getYear() + 1900); } /** * * @param datum * @throws Exception */ public Datum(Datum datum) throws Exception { setDatum(datum.getDag(), datum.getMaand(), datum.getJaar()); } /** * * @param dag * @param maand * @param jaar * @throws Exception */ public Datum(int dag, int maand, int jaar) throws Exception { setDatum(dag, maand, jaar); } /** * Datum als string DDMMJJJJ * @param datum * @throws Exception * @throws NumberFormatException */ public Datum(String datum) throws NumberFormatException, Exception { String[] datumDelen = datum.split("/"); if (datumDelen.length != 3 || datumDelen[0].length() < 1 || datumDelen[1].length() != 2 || datumDelen[2].length() != 4) { throw new IllegalArgumentException("De gegeven datum is onjuist. " + "Geldig formaat: (D)D/MM/YYYY"); } setDatum(Integer.parseInt(datumDelen[0]), Integer.parseInt(datumDelen[1]), Integer.parseInt(datumDelen[2])); } /** * Stel de datumvariabelen in. Doe ook de validatie en werp exceptions indien nodig * * @param dag * @param maand * @param jaar * @return * @throws Exception */ public boolean setDatum(int dag, int maand, int jaar) throws Exception { // Eerst de basale controle if (dag < 1 || dag > 31) { throw new Exception("Ongeldige dag gegeven"); } if (maand < 1 || maand > 12) { throw new Exception("Ongeldige numerieke maand gegeven"); } if (jaar < 0) { throw new Exception("Ongeldig jaar gegeven"); } // Nu een precieze controle switch (maand) { case 2: // 1) Als het geen schrikkeljaar is, heeft februari max 28 dagen // 2) Wel een schrikkeljaar? Max 29 dagen if ((!Maanden.isSchrikkeljaar(jaar) && dag >= 29) || (Maanden.isSchrikkeljaar(jaar) && dag > 29)) { throw new Exception("De dag is niet juist voor de gegeven maand februari"); } break; case 4: case 6: case 9: case 11: if (dag > 30) { throw new Exception("De dag is niet juist voor de gegeven maand " + Maanden.get(maand)); } break; } // Alles is goed verlopen this.dag = dag; this.maand = maand; this.jaar = jaar; return true; } /** * * @return */ public String getDatumInAmerikaansFormaat() { return String.format("%04d/%02d/%02d", jaar, maand, dag); } /** * * @return */ public String getDatumInEuropeesFormaat() { return String.format("%02d/%02d/%04d", dag, maand, jaar); } /** * Haal de dag van het Datum object op * @return */ public int getDag() { return dag; } /** * Haal de maand van het Datum object op * @return */ public int getMaand() { return maand; } /** * Haal het jaar van het Datum object op * @return */ public int getJaar() { return jaar; } /** * Is de gegeven datum kleiner dan het huidid datum object? * * @param datum * @return */ public boolean kleinerDan(Datum datum) { return compareTo(datum) > 0; } /** * * @param datum * @return * @throws Exception */ public int verschilInJaren(Datum datum) throws Exception { return new DatumVerschil(this, datum).getJaren(); } /** * * @param datum * @return * @throws Exception */ public int verschilInMaanden(Datum datum) throws Exception { return new DatumVerschil(this, datum).getMaanden(); } /** * * @param aantalDagen * @return * @throws Exception */ public Datum veranderDatum(int aantalDagen) throws Exception { if (aantalDagen > 0) { while (aantalDagen + dag > Maanden.get(maand).aantalDagen(jaar)) { aantalDagen -= Maanden.get(maand).aantalDagen(jaar) - dag + 1; // Jaar verhogen jaar += (maand == 12 ? 1 : 0); // Maand verhogen maand = (maand == 12 ? 1 : ++maand); // We hebben een nieuwe maand, dus terug van 1 beginnen dag = 1; } } // Negatieve waarde, dus terug in de tijd gaan else { while (-dag >= aantalDagen) { // Verminder met aantal dagen in huidige maand. aantalDagen += dag; // Verminder jaartal? jaar -= (maand == 1 ? 1 : 0); // Verminder maand maand = (maand == 1 ? 12 : --maand); // Zet als laatste dag van (vorige) maand dag = Maanden.get(maand).aantalDagen(jaar); } } return new Datum(dag += aantalDagen, maand, jaar); } /** * */ @Override public boolean equals(Object obj) { // Is het exact hetzelfde object? if (this == obj) { return true; } // Is het hetzelfde type? if (obj == null || !(obj instanceof Datum)) { return false; } // Nu zien of de inhoud dezelfde is return compareTo((Datum) obj) == 0; } /** * Ik snap er de ballen van */ @Override public int hashCode() { final int prime = 37; int hash = 1; hash = prime * hash + dag; hash = prime * hash + maand; hash = prime * hash + jaar; return hash; } /** * Vergelijk de onze datum met de nieuwe */ public int compareTo(Datum datum2) { if (jaar > datum2.jaar) { return 1; } else if (jaar < datum2.jaar) { return -1; } if (maand > datum2.maand) { return 1; } else if (maand < datum2.maand) { return -1; } if (dag > datum2.dag) { return 1; } else if (dag < datum2.dag) { return -1; } return 0; } /** * Geef een string representatie terug van de datum * @return Datum in string formaat */ public String toString() { return dag + " " + Maanden.get(maand) + " " + jaar; } /** * Return de huidige datum van het systeem * @return Date * @throws Exception */ @SuppressWarnings("deprecation") private void HuidigeSysteemDatum() throws Exception { Date datum = new Date(); setDatum(datum.getDate(), datum.getMonth() + 1, datum.getYear() + 1900); } }
thunder-tw/JavaPractOpdrachten
Opdracht 1/src/model/datum/Datum.java
2,560
// 2) Wel een schrikkeljaar? Max 29 dagen
line_comment
nl
package model.datum; import java.util.Date; /** * * @author Isaak * */ public class Datum { private int dag; private int maand; private int jaar; /** * @throws Exception * */ public Datum() throws Exception { HuidigeSysteemDatum(); } /** * * @param Datum * @throws Exception */ @SuppressWarnings("deprecation") public Datum(Date datum) throws Exception { setDatum(datum.getDate(), datum.getMonth() + 1, datum.getYear() + 1900); } /** * * @param datum * @throws Exception */ public Datum(Datum datum) throws Exception { setDatum(datum.getDag(), datum.getMaand(), datum.getJaar()); } /** * * @param dag * @param maand * @param jaar * @throws Exception */ public Datum(int dag, int maand, int jaar) throws Exception { setDatum(dag, maand, jaar); } /** * Datum als string DDMMJJJJ * @param datum * @throws Exception * @throws NumberFormatException */ public Datum(String datum) throws NumberFormatException, Exception { String[] datumDelen = datum.split("/"); if (datumDelen.length != 3 || datumDelen[0].length() < 1 || datumDelen[1].length() != 2 || datumDelen[2].length() != 4) { throw new IllegalArgumentException("De gegeven datum is onjuist. " + "Geldig formaat: (D)D/MM/YYYY"); } setDatum(Integer.parseInt(datumDelen[0]), Integer.parseInt(datumDelen[1]), Integer.parseInt(datumDelen[2])); } /** * Stel de datumvariabelen in. Doe ook de validatie en werp exceptions indien nodig * * @param dag * @param maand * @param jaar * @return * @throws Exception */ public boolean setDatum(int dag, int maand, int jaar) throws Exception { // Eerst de basale controle if (dag < 1 || dag > 31) { throw new Exception("Ongeldige dag gegeven"); } if (maand < 1 || maand > 12) { throw new Exception("Ongeldige numerieke maand gegeven"); } if (jaar < 0) { throw new Exception("Ongeldig jaar gegeven"); } // Nu een precieze controle switch (maand) { case 2: // 1) Als het geen schrikkeljaar is, heeft februari max 28 dagen // 2) Wel<SUF> if ((!Maanden.isSchrikkeljaar(jaar) && dag >= 29) || (Maanden.isSchrikkeljaar(jaar) && dag > 29)) { throw new Exception("De dag is niet juist voor de gegeven maand februari"); } break; case 4: case 6: case 9: case 11: if (dag > 30) { throw new Exception("De dag is niet juist voor de gegeven maand " + Maanden.get(maand)); } break; } // Alles is goed verlopen this.dag = dag; this.maand = maand; this.jaar = jaar; return true; } /** * * @return */ public String getDatumInAmerikaansFormaat() { return String.format("%04d/%02d/%02d", jaar, maand, dag); } /** * * @return */ public String getDatumInEuropeesFormaat() { return String.format("%02d/%02d/%04d", dag, maand, jaar); } /** * Haal de dag van het Datum object op * @return */ public int getDag() { return dag; } /** * Haal de maand van het Datum object op * @return */ public int getMaand() { return maand; } /** * Haal het jaar van het Datum object op * @return */ public int getJaar() { return jaar; } /** * Is de gegeven datum kleiner dan het huidid datum object? * * @param datum * @return */ public boolean kleinerDan(Datum datum) { return compareTo(datum) > 0; } /** * * @param datum * @return * @throws Exception */ public int verschilInJaren(Datum datum) throws Exception { return new DatumVerschil(this, datum).getJaren(); } /** * * @param datum * @return * @throws Exception */ public int verschilInMaanden(Datum datum) throws Exception { return new DatumVerschil(this, datum).getMaanden(); } /** * * @param aantalDagen * @return * @throws Exception */ public Datum veranderDatum(int aantalDagen) throws Exception { if (aantalDagen > 0) { while (aantalDagen + dag > Maanden.get(maand).aantalDagen(jaar)) { aantalDagen -= Maanden.get(maand).aantalDagen(jaar) - dag + 1; // Jaar verhogen jaar += (maand == 12 ? 1 : 0); // Maand verhogen maand = (maand == 12 ? 1 : ++maand); // We hebben een nieuwe maand, dus terug van 1 beginnen dag = 1; } } // Negatieve waarde, dus terug in de tijd gaan else { while (-dag >= aantalDagen) { // Verminder met aantal dagen in huidige maand. aantalDagen += dag; // Verminder jaartal? jaar -= (maand == 1 ? 1 : 0); // Verminder maand maand = (maand == 1 ? 12 : --maand); // Zet als laatste dag van (vorige) maand dag = Maanden.get(maand).aantalDagen(jaar); } } return new Datum(dag += aantalDagen, maand, jaar); } /** * */ @Override public boolean equals(Object obj) { // Is het exact hetzelfde object? if (this == obj) { return true; } // Is het hetzelfde type? if (obj == null || !(obj instanceof Datum)) { return false; } // Nu zien of de inhoud dezelfde is return compareTo((Datum) obj) == 0; } /** * Ik snap er de ballen van */ @Override public int hashCode() { final int prime = 37; int hash = 1; hash = prime * hash + dag; hash = prime * hash + maand; hash = prime * hash + jaar; return hash; } /** * Vergelijk de onze datum met de nieuwe */ public int compareTo(Datum datum2) { if (jaar > datum2.jaar) { return 1; } else if (jaar < datum2.jaar) { return -1; } if (maand > datum2.maand) { return 1; } else if (maand < datum2.maand) { return -1; } if (dag > datum2.dag) { return 1; } else if (dag < datum2.dag) { return -1; } return 0; } /** * Geef een string representatie terug van de datum * @return Datum in string formaat */ public String toString() { return dag + " " + Maanden.get(maand) + " " + jaar; } /** * Return de huidige datum van het systeem * @return Date * @throws Exception */ @SuppressWarnings("deprecation") private void HuidigeSysteemDatum() throws Exception { Date datum = new Date(); setDatum(datum.getDate(), datum.getMonth() + 1, datum.getYear() + 1900); } }
True
2,103
17
2,242
20
2,323
16
2,242
20
2,700
18
false
false
false
false
false
true
1,734
37768_8
package com.KineFit.app.activities; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Switch; import android.widget.TextView; import android.widget.ToggleButton; import com.KineFit.app.R; import com.KineFit.app.adapters.TakenAdapter; import com.KineFit.app.model.Taak; import com.KineFit.app.model.enums.TaskStatus; import com.KineFit.app.services.JSONParser; import org.json.JSONArray; import org.json.JSONObject; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.ArrayList; /** * Activity voor het taken overzicht. * Op deze activity kan de gebruiker taken bekijken en voltooien. * * Created by Thomas on 30/04/16. * @author Thomas Vandenabeele */ public class TakenActivity extends BasisActivity { //region DATAMEMBERS /** pDialog voor de UI */ private ProgressDialog pDialog; /** LinearLayout voor het filtermenu */ private LinearLayout filterTakenMenu; /** ToggleButton voor filteren */ private ToggleButton tbFilter; /** Switch voor gesloten taken */ private Switch sGeslotenTaken; /** Switch voor gefaalde taken */ private Switch sGefaaldeTaken; /** Boolean gesloten taken */ private boolean geslotenTaken; /** Boolean gefaalde taken */ private boolean gefaaldeTaken; /** ListView voor de taken */ private ListView lvTaken; /** TextView voor melding geen taken */ private TextView txtGeenTaken; /** TakenLijst */ private ArrayList<Taak> takenLijst; /** SQL datum formatter */ private SimpleDateFormat sqlDatumFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** Korte datum formatter */ private SimpleDateFormat korteDatum = new SimpleDateFormat("dd-MM-yyyy"); /** Korte tijd formatter */ private SimpleDateFormat korteTijd = new SimpleDateFormat("HH:mm"); //endregion //region REST: TAGS & URL /** JSONParser voor de REST client aan te spreken */ JSONParser jParser = new JSONParser(); /** Tag voor gebruikersnaam */ private static final String TAG_GEBRUIKERSNAAM = "username"; //-------------------------------------------------------------------------------------------------------------------------------// /** URL om alle taken op te vragen */ private static String url_alle_taken = "http://thomasvandenabeele.no-ip.org/KineFit/get_all_tasks.php"; /** Tag voor succes */ private static final String TAG_SUCCES = "success"; /** Tag voor taken */ private static final String TAG_TAKEN = "tasks"; /** Tag voor taak id */ private static final String TAG_ID = "id"; /** Tag voor taak naam */ private static final String TAG_NAAM = "message"; /** Tag voor taak aanmaak datum */ private static final String TAG_AANMAAKDATUM = "created_at"; /** Tag voor taak status */ private static final String TAG_STATUS = "status"; //-------------------------------------------------------------------------------------------------------------------------------// /** URL om het de status van een taak te updaten */ private static String url_update_taak_status = "http://thomasvandenabeele.no-ip.org/KineFit/update_status_task.php"; /** ID van de status */ private static final String TAG_STATUS_ID = "id"; /** Naam van de status */ private static final String TAG_STATUS_NAAM = "name"; //-------------------------------------------------------------------------------------------------------------------------------// //endregion /** * Methode die opgeroepen wordt bij aanmaak activity. * @param savedInstanceState */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.taken_lijst); //region UI componenten toekennen txtGeenTaken = (TextView) findViewById(R.id.txtGeenTaken); filterTakenMenu = (LinearLayout)findViewById(R.id.filterMenuTaken); tbFilter = (ToggleButton)findViewById(R.id.tbFilter); sGeslotenTaken = (Switch)findViewById(R.id.sGeslotenTaken); sGefaaldeTaken = (Switch)findViewById(R.id.sGefaaldeTaken); lvTaken = (ListView)findViewById(R.id.lvTaken); //endregion // OnCheckedChangeListener voor togglebutton filteren tbFilter.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ // Toon filter menu filterTakenMenu.setVisibility(View.VISIBLE); } else{ // Verberg filter menu filterTakenMenu.setVisibility(View.GONE); } } }); // OnCheckedChangeListener voor sGeslotenTaken sGeslotenTaken.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { geslotenTaken = isChecked; // Herlaad de listView new LaadAlleTaken().execute(); } }); // OnCheckedChangeListener voor sGefaaldeTaken sGefaaldeTaken.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { gefaaldeTaken = isChecked; // Herlaad de listView new LaadAlleTaken().execute(); } }); // Instantiëren members geslotenTaken = sGeslotenTaken.isChecked(); gefaaldeTaken = sGefaaldeTaken.isChecked(); takenLijst = new ArrayList<Taak>(); // Laad de listView new LaadAlleTaken().execute(); // OnItemClickListener voor ListView lvTaken.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Get de geselecteerde taak Taak t = takenLijst.get(position); // Volgende code enkel wanneer de status nieuw of open is: if(t.getStatus().equals(TaskStatus.OPEN)||t.getStatus().equals(TaskStatus.NEW)){ final String pid = ((TextView) view.findViewById(R.id.task_pid)).getText().toString(); final ContentValues parameters = new ContentValues(); parameters.put(TAG_STATUS_ID, pid); // Maak alert venster new AlertDialog.Builder(TakenActivity.this) .setTitle("Voltooi taak") .setMessage("Is u in deze taak geslaagd?") .setPositiveButton("Geslaagd", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { parameters.put(TAG_STATUS_NAAM, TaskStatus.DONE.toString()); new UpdateTaakStatus().execute(parameters); // Sluit alert dialog.cancel(); } }) .setNeutralButton("Gefaald", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { parameters.put(TAG_STATUS_NAAM, TaskStatus.FAILED.toString()); new UpdateTaakStatus().execute(parameters); // Sluit alert dialog.cancel(); } }) .setNegativeButton("Annuleren", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Sluit alert dialog.cancel(); } }) .setCancelable(false) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } } }); } /** * Async Taak op achtergrond om het aantal ongelezen taken op te halen en weer te geven. * Via HTTP Request naar REST client. * */ class LaadAlleTaken extends AsyncTask<String, String, String> { /** * Methode die opgeroepen wordt voor uitvoeren van taak. * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(TakenActivity.this); pDialog.setMessage("Taken laden, gelieve even te wachten aub..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * Deze methode wordt in de achtergrond uitgevoerd. * @param params Strings niet relevant * @return niet relevant */ protected String doInBackground(String... params) { // Maakt de request en geeft het resultaat ContentValues parameters = new ContentValues(); parameters.put(TAG_GEBRUIKERSNAAM, sessie.getUsername()); JSONObject json = jParser.makeHttpRequest(url_alle_taken, "GET", parameters); Log.d("Alle taken: ", json.toString()); try { if (json.getInt(TAG_SUCCES) == 1) { // Taken ophalen JSONArray tasks = json.getJSONArray(TAG_TAKEN); takenLijst.clear(); // Omzetten in ArrayList<Taak> for (int i = 0; i < tasks.length(); i++) { JSONObject c = tasks.getJSONObject(i); java.sql.Date aanmaakDatum = new java.sql.Date(sqlDatumFormatter.parse(c.getString(TAG_AANMAAKDATUM)).getTime()); Taak t = new Taak(c.getInt(TAG_ID), c.getString(TAG_NAAM), aanmaakDatum, TaskStatus.valueOf(c.getString(TAG_STATUS))); // Filtercriteria checken boolean add = true; switch (t.getStatus()){ case DONE: if(!geslotenTaken) add = false; break; case FAILED: if(!gefaaldeTaken) add = false; break; default: add = true; break; } // Toevoegen aan lijst if(add) takenLijst.add(t); } } } catch (Exception e) { e.printStackTrace(); } return null; } /** * Methode voor na uitvoering taak. * Update de UI door ListView te vullen. * **/ protected void onPostExecute(String file_url) { // pDialog sluiten pDialog.dismiss(); if(takenLijst.size()>0) { // Geen melding txtGeenTaken.setVisibility(View.GONE); lvTaken.setVisibility(View.VISIBLE); runOnUiThread(new Runnable() { public void run() { TakenAdapter ta = new TakenAdapter(TakenActivity.this, R.layout.task_list_item, takenLijst); lvTaken.setAdapter(ta); } }); } else { // Toon melding txtGeenTaken.setVisibility(View.VISIBLE); lvTaken.setVisibility(View.GONE); } } } /** * Async Taak op achtergrond om het aantal ongelezen taken op te halen en weer te geven. * Via HTTP Request naar REST client. * */ class UpdateTaakStatus extends AsyncTask<ContentValues, String, Integer> { /** * Methode die opgeroepen wordt voor uitvoeren van taak. * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(TakenActivity.this); pDialog.setMessage("Updating Taak ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Deze methode wordt in de achtergrond uitgevoerd. * @param parameters Strings niet relevant * @return int geslaagd */ protected Integer doInBackground(ContentValues... parameters) { // Maakt de request en geeft het resultaat JSONObject json = jParser.makeHttpRequest(url_update_taak_status, "POST", parameters[0]); Log.d("Update taak status: ", json.toString()); try { return json.getInt(TAG_SUCCES); } catch (Exception e) { e.printStackTrace(); } return 0; } /** * Methode voor na uitvoering taak. * Update de UI door de ListView voor taken te herladen. * **/ protected void onPostExecute(Integer success) { // pDialog sluiten pDialog.dismiss(); if (success == 1) { new LaadAlleTaken().execute(); } } } }
ThomasVandenabeele/kinefit-android-app
src/main/java/com/KineFit/app/activities/TakenActivity.java
3,851
/** ListView voor de taken */
block_comment
nl
package com.KineFit.app.activities; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Switch; import android.widget.TextView; import android.widget.ToggleButton; import com.KineFit.app.R; import com.KineFit.app.adapters.TakenAdapter; import com.KineFit.app.model.Taak; import com.KineFit.app.model.enums.TaskStatus; import com.KineFit.app.services.JSONParser; import org.json.JSONArray; import org.json.JSONObject; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.ArrayList; /** * Activity voor het taken overzicht. * Op deze activity kan de gebruiker taken bekijken en voltooien. * * Created by Thomas on 30/04/16. * @author Thomas Vandenabeele */ public class TakenActivity extends BasisActivity { //region DATAMEMBERS /** pDialog voor de UI */ private ProgressDialog pDialog; /** LinearLayout voor het filtermenu */ private LinearLayout filterTakenMenu; /** ToggleButton voor filteren */ private ToggleButton tbFilter; /** Switch voor gesloten taken */ private Switch sGeslotenTaken; /** Switch voor gefaalde taken */ private Switch sGefaaldeTaken; /** Boolean gesloten taken */ private boolean geslotenTaken; /** Boolean gefaalde taken */ private boolean gefaaldeTaken; /** ListView voor de<SUF>*/ private ListView lvTaken; /** TextView voor melding geen taken */ private TextView txtGeenTaken; /** TakenLijst */ private ArrayList<Taak> takenLijst; /** SQL datum formatter */ private SimpleDateFormat sqlDatumFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** Korte datum formatter */ private SimpleDateFormat korteDatum = new SimpleDateFormat("dd-MM-yyyy"); /** Korte tijd formatter */ private SimpleDateFormat korteTijd = new SimpleDateFormat("HH:mm"); //endregion //region REST: TAGS & URL /** JSONParser voor de REST client aan te spreken */ JSONParser jParser = new JSONParser(); /** Tag voor gebruikersnaam */ private static final String TAG_GEBRUIKERSNAAM = "username"; //-------------------------------------------------------------------------------------------------------------------------------// /** URL om alle taken op te vragen */ private static String url_alle_taken = "http://thomasvandenabeele.no-ip.org/KineFit/get_all_tasks.php"; /** Tag voor succes */ private static final String TAG_SUCCES = "success"; /** Tag voor taken */ private static final String TAG_TAKEN = "tasks"; /** Tag voor taak id */ private static final String TAG_ID = "id"; /** Tag voor taak naam */ private static final String TAG_NAAM = "message"; /** Tag voor taak aanmaak datum */ private static final String TAG_AANMAAKDATUM = "created_at"; /** Tag voor taak status */ private static final String TAG_STATUS = "status"; //-------------------------------------------------------------------------------------------------------------------------------// /** URL om het de status van een taak te updaten */ private static String url_update_taak_status = "http://thomasvandenabeele.no-ip.org/KineFit/update_status_task.php"; /** ID van de status */ private static final String TAG_STATUS_ID = "id"; /** Naam van de status */ private static final String TAG_STATUS_NAAM = "name"; //-------------------------------------------------------------------------------------------------------------------------------// //endregion /** * Methode die opgeroepen wordt bij aanmaak activity. * @param savedInstanceState */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.taken_lijst); //region UI componenten toekennen txtGeenTaken = (TextView) findViewById(R.id.txtGeenTaken); filterTakenMenu = (LinearLayout)findViewById(R.id.filterMenuTaken); tbFilter = (ToggleButton)findViewById(R.id.tbFilter); sGeslotenTaken = (Switch)findViewById(R.id.sGeslotenTaken); sGefaaldeTaken = (Switch)findViewById(R.id.sGefaaldeTaken); lvTaken = (ListView)findViewById(R.id.lvTaken); //endregion // OnCheckedChangeListener voor togglebutton filteren tbFilter.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ // Toon filter menu filterTakenMenu.setVisibility(View.VISIBLE); } else{ // Verberg filter menu filterTakenMenu.setVisibility(View.GONE); } } }); // OnCheckedChangeListener voor sGeslotenTaken sGeslotenTaken.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { geslotenTaken = isChecked; // Herlaad de listView new LaadAlleTaken().execute(); } }); // OnCheckedChangeListener voor sGefaaldeTaken sGefaaldeTaken.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { gefaaldeTaken = isChecked; // Herlaad de listView new LaadAlleTaken().execute(); } }); // Instantiëren members geslotenTaken = sGeslotenTaken.isChecked(); gefaaldeTaken = sGefaaldeTaken.isChecked(); takenLijst = new ArrayList<Taak>(); // Laad de listView new LaadAlleTaken().execute(); // OnItemClickListener voor ListView lvTaken.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Get de geselecteerde taak Taak t = takenLijst.get(position); // Volgende code enkel wanneer de status nieuw of open is: if(t.getStatus().equals(TaskStatus.OPEN)||t.getStatus().equals(TaskStatus.NEW)){ final String pid = ((TextView) view.findViewById(R.id.task_pid)).getText().toString(); final ContentValues parameters = new ContentValues(); parameters.put(TAG_STATUS_ID, pid); // Maak alert venster new AlertDialog.Builder(TakenActivity.this) .setTitle("Voltooi taak") .setMessage("Is u in deze taak geslaagd?") .setPositiveButton("Geslaagd", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { parameters.put(TAG_STATUS_NAAM, TaskStatus.DONE.toString()); new UpdateTaakStatus().execute(parameters); // Sluit alert dialog.cancel(); } }) .setNeutralButton("Gefaald", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { parameters.put(TAG_STATUS_NAAM, TaskStatus.FAILED.toString()); new UpdateTaakStatus().execute(parameters); // Sluit alert dialog.cancel(); } }) .setNegativeButton("Annuleren", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Sluit alert dialog.cancel(); } }) .setCancelable(false) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } } }); } /** * Async Taak op achtergrond om het aantal ongelezen taken op te halen en weer te geven. * Via HTTP Request naar REST client. * */ class LaadAlleTaken extends AsyncTask<String, String, String> { /** * Methode die opgeroepen wordt voor uitvoeren van taak. * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(TakenActivity.this); pDialog.setMessage("Taken laden, gelieve even te wachten aub..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * Deze methode wordt in de achtergrond uitgevoerd. * @param params Strings niet relevant * @return niet relevant */ protected String doInBackground(String... params) { // Maakt de request en geeft het resultaat ContentValues parameters = new ContentValues(); parameters.put(TAG_GEBRUIKERSNAAM, sessie.getUsername()); JSONObject json = jParser.makeHttpRequest(url_alle_taken, "GET", parameters); Log.d("Alle taken: ", json.toString()); try { if (json.getInt(TAG_SUCCES) == 1) { // Taken ophalen JSONArray tasks = json.getJSONArray(TAG_TAKEN); takenLijst.clear(); // Omzetten in ArrayList<Taak> for (int i = 0; i < tasks.length(); i++) { JSONObject c = tasks.getJSONObject(i); java.sql.Date aanmaakDatum = new java.sql.Date(sqlDatumFormatter.parse(c.getString(TAG_AANMAAKDATUM)).getTime()); Taak t = new Taak(c.getInt(TAG_ID), c.getString(TAG_NAAM), aanmaakDatum, TaskStatus.valueOf(c.getString(TAG_STATUS))); // Filtercriteria checken boolean add = true; switch (t.getStatus()){ case DONE: if(!geslotenTaken) add = false; break; case FAILED: if(!gefaaldeTaken) add = false; break; default: add = true; break; } // Toevoegen aan lijst if(add) takenLijst.add(t); } } } catch (Exception e) { e.printStackTrace(); } return null; } /** * Methode voor na uitvoering taak. * Update de UI door ListView te vullen. * **/ protected void onPostExecute(String file_url) { // pDialog sluiten pDialog.dismiss(); if(takenLijst.size()>0) { // Geen melding txtGeenTaken.setVisibility(View.GONE); lvTaken.setVisibility(View.VISIBLE); runOnUiThread(new Runnable() { public void run() { TakenAdapter ta = new TakenAdapter(TakenActivity.this, R.layout.task_list_item, takenLijst); lvTaken.setAdapter(ta); } }); } else { // Toon melding txtGeenTaken.setVisibility(View.VISIBLE); lvTaken.setVisibility(View.GONE); } } } /** * Async Taak op achtergrond om het aantal ongelezen taken op te halen en weer te geven. * Via HTTP Request naar REST client. * */ class UpdateTaakStatus extends AsyncTask<ContentValues, String, Integer> { /** * Methode die opgeroepen wordt voor uitvoeren van taak. * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(TakenActivity.this); pDialog.setMessage("Updating Taak ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Deze methode wordt in de achtergrond uitgevoerd. * @param parameters Strings niet relevant * @return int geslaagd */ protected Integer doInBackground(ContentValues... parameters) { // Maakt de request en geeft het resultaat JSONObject json = jParser.makeHttpRequest(url_update_taak_status, "POST", parameters[0]); Log.d("Update taak status: ", json.toString()); try { return json.getInt(TAG_SUCCES); } catch (Exception e) { e.printStackTrace(); } return 0; } /** * Methode voor na uitvoering taak. * Update de UI door de ListView voor taken te herladen. * **/ protected void onPostExecute(Integer success) { // pDialog sluiten pDialog.dismiss(); if (success == 1) { new LaadAlleTaken().execute(); } } } }
True
2,670
6
3,048
6
3,150
6
3,048
6
3,752
6
false
false
false
false
false
true
4,422
177505_9
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controller; import bean.CartBean; import dao.OrderDAO; import dao.OrderProductDAO; import model.hibernate.Order; import model.hibernate.OrderProduct; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Vector; /** * * @author Stefan */ public class CartController extends HttpServlet { CartBean cartBean = new CartBean(); HttpSession session; /* HTTP GET request */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { /* Call the session, or create it of it does not exist */ this.session = request.getSession(true); // Check if there is already an instance of the cartBean in the session if(this.session.getAttribute("cartBean") != null) // And assign it if there is cartBean = (CartBean) this.session.getAttribute("cartBean"); // Set an attribute containing the cart bean request.setAttribute("cartBean", cartBean); // Set a session attribute containing the cart bean this.session.setAttribute("cartBean", cartBean); // Stel de pagina in die bij deze controller hoort String address = "cart.jsp"; // Doe een verzoek naar het adres RequestDispatcher dispatcher = request.getRequestDispatcher(address); // Stuur door naar bovenstaande adres dispatcher.forward(request, response); } /* HTTP POST request */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Set a variable for the address to the JSP file that'll be shown at runtime String address; // Create an instance of the order/orderProduct DAO & Model OrderDAO orderDao = new OrderDAO(); OrderProductDAO orderProductDao = new OrderProductDAO(); Order order; OrderProduct orderProduct; /* Call the session, or create it of it does not exist */ this.session = request.getSession(true); // Check if there is already an instance of the cartBean in the session if(this.session.getAttribute("cartBean") != null) // And assign it if there is cartBean = (CartBean) this.session.getAttribute("cartBean"); /* * Check if a customer is logged in prior to placing the order, and make * sure products are present in the cart. */ if( cartBean.getProduct().size() > 0 && cartBean.getCustomer() != null ) { order = new Order(); order.setCustomer(cartBean.getCustomer()); order.setOrderDate(new Date()); orderDao.create(order); List orderProductList = new LinkedList(); for(int i = 0; i < cartBean.getProduct().size(); i++) { orderProduct = new OrderProduct(); orderProduct.setOrder(order); orderProduct.setProduct(cartBean.getProduct().get(i).getProduct()); orderProduct.setProductQuantity(cartBean.getProduct().get(i).getProductAmount()); orderProductDao.create(orderProduct); orderProductList.add(orderProduct); } // Assign a new empty vector to the product vector cartBean.setProduct(new Vector()); // Set the page that will be shown when the POST is made address = "order_success.jsp"; } else { // Set the page that will be shown when the POST is made address = "order_failure.jsp"; } // Set an attribute containing the cart bean request.setAttribute("cartBean", cartBean); // Set a session attribute containing the cart bean this.session.setAttribute("cartBean", cartBean); // Doe een verzoek naar het adres RequestDispatcher dispatcher = request.getRequestDispatcher(address); // Stuur door naar bovenstaande adres dispatcher.forward(request, response); } }
svbeusekom/WEBShop
src/java/controller/CartController.java
1,080
// Doe een verzoek naar het adres
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controller; import bean.CartBean; import dao.OrderDAO; import dao.OrderProductDAO; import model.hibernate.Order; import model.hibernate.OrderProduct; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Vector; /** * * @author Stefan */ public class CartController extends HttpServlet { CartBean cartBean = new CartBean(); HttpSession session; /* HTTP GET request */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { /* Call the session, or create it of it does not exist */ this.session = request.getSession(true); // Check if there is already an instance of the cartBean in the session if(this.session.getAttribute("cartBean") != null) // And assign it if there is cartBean = (CartBean) this.session.getAttribute("cartBean"); // Set an attribute containing the cart bean request.setAttribute("cartBean", cartBean); // Set a session attribute containing the cart bean this.session.setAttribute("cartBean", cartBean); // Stel de pagina in die bij deze controller hoort String address = "cart.jsp"; // Doe een<SUF> RequestDispatcher dispatcher = request.getRequestDispatcher(address); // Stuur door naar bovenstaande adres dispatcher.forward(request, response); } /* HTTP POST request */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Set a variable for the address to the JSP file that'll be shown at runtime String address; // Create an instance of the order/orderProduct DAO & Model OrderDAO orderDao = new OrderDAO(); OrderProductDAO orderProductDao = new OrderProductDAO(); Order order; OrderProduct orderProduct; /* Call the session, or create it of it does not exist */ this.session = request.getSession(true); // Check if there is already an instance of the cartBean in the session if(this.session.getAttribute("cartBean") != null) // And assign it if there is cartBean = (CartBean) this.session.getAttribute("cartBean"); /* * Check if a customer is logged in prior to placing the order, and make * sure products are present in the cart. */ if( cartBean.getProduct().size() > 0 && cartBean.getCustomer() != null ) { order = new Order(); order.setCustomer(cartBean.getCustomer()); order.setOrderDate(new Date()); orderDao.create(order); List orderProductList = new LinkedList(); for(int i = 0; i < cartBean.getProduct().size(); i++) { orderProduct = new OrderProduct(); orderProduct.setOrder(order); orderProduct.setProduct(cartBean.getProduct().get(i).getProduct()); orderProduct.setProductQuantity(cartBean.getProduct().get(i).getProductAmount()); orderProductDao.create(orderProduct); orderProductList.add(orderProduct); } // Assign a new empty vector to the product vector cartBean.setProduct(new Vector()); // Set the page that will be shown when the POST is made address = "order_success.jsp"; } else { // Set the page that will be shown when the POST is made address = "order_failure.jsp"; } // Set an attribute containing the cart bean request.setAttribute("cartBean", cartBean); // Set a session attribute containing the cart bean this.session.setAttribute("cartBean", cartBean); // Doe een verzoek naar het adres RequestDispatcher dispatcher = request.getRequestDispatcher(address); // Stuur door naar bovenstaande adres dispatcher.forward(request, response); } }
True
823
8
928
9
972
8
928
9
1,064
11
false
false
false
false
false
true
4,731
23373_7
package nl.b3p.geotools.data.dxf.entities; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import nl.b3p.geotools.data.dxf.parser.DXFLineNumberReader; import java.io.EOFException; import java.io.IOException; import java.text.MessageFormat; import java.util.regex.Pattern; import nl.b3p.geotools.data.GeometryType; import nl.b3p.geotools.data.dxf.parser.DXFUnivers; import nl.b3p.geotools.data.dxf.header.DXFLayer; import nl.b3p.geotools.data.dxf.header.DXFLineType; import nl.b3p.geotools.data.dxf.header.DXFTables; import nl.b3p.geotools.data.dxf.parser.DXFCodeValuePair; import nl.b3p.geotools.data.dxf.parser.DXFGroupCode; import nl.b3p.geotools.data.dxf.parser.DXFParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class DXFText extends DXFEntity { private static final Log log = LogFactory.getLog(DXFText.class); private Double x = null, y = null; public DXFText(DXFText newText) { this(newText.getColor(), newText.getRefLayer(), 0, newText.getLineType(), 0.0); setStartingLineNumber(newText.getStartingLineNumber()); setType(newText.getType()); setUnivers(newText.getUnivers()); } public DXFText(int c, DXFLayer l, int visibility, DXFLineType lineType, double thickness) { super(c, l , visibility, lineType, thickness); } public Double getX() { return x; } public void setX(Double x) { this.x = x; } public Double getY() { return y; } public void setY(Double y) { this.y = y; } public static DXFText read(DXFLineNumberReader br, DXFUnivers univers, boolean isMText) throws IOException { DXFText t = new DXFText(0, null, 0, null, DXFTables.defaultThickness); t.setUnivers(univers); t.setName(isMText ? "DXFMText" : "DXFText"); t.setTextrotation(0.0); t.setStartingLineNumber(br.getLineNumber()); DXFCodeValuePair cvp = null; DXFGroupCode gc = null; // MTEXT direction vector Double directionX = null, directionY = null; String textposhor = "left"; String textposver = "bottom"; boolean doLoop = true; while (doLoop) { cvp = new DXFCodeValuePair(); try { gc = cvp.read(br); } catch (DXFParseException ex) { throw new IOException("DXF parse error" + ex.getLocalizedMessage()); } catch (EOFException e) { doLoop = false; break; } switch (gc) { case TYPE: // geldt voor alle waarden van type br.reset(); doLoop = false; break; case X_1: //"10" t.setX(cvp.getDoubleValue()); break; case Y_1: //"20" t.setY(cvp.getDoubleValue()); break; case TEXT: //"1" t.setText(processOrStripTextCodes(cvp.getStringValue())); break; case ANGLE_1: //"50" t.setTextrotation(cvp.getDoubleValue()); break; case X_2: // 11, X-axis direction vector directionX = cvp.getDoubleValue(); break; case Y_2: // 21, Y-axis direction vector directionY = cvp.getDoubleValue(); break; case THICKNESS: //"39" t.setThickness(cvp.getDoubleValue()); break; case DOUBLE_1: //"40" t.setTextheight(cvp.getDoubleValue()); break; case INT_2: // 71: MTEXT attachment point switch(cvp.getShortValue()) { case 1: textposver = "top"; textposhor = "left"; break; case 2: textposver = "top"; textposhor = "center"; break; case 3: textposver = "top"; textposhor = "right"; break; case 4: textposver = "middle"; textposhor = "left"; break; case 5: textposver = "middle"; textposhor = "center"; break; case 6: textposver = "middle"; textposhor = "right"; break; case 7: textposver = "bottom"; textposhor = "left"; break; case 8: textposver = "bottom"; textposhor = "center"; break; case 9: textposver = "bottom"; textposhor = "right"; break; } break; case INT_3: // 72: TEXT horizontal text justification type // komen niet helemaal overeen, maar maak voor TEXT en MTEXT hetzelfde switch(cvp.getShortValue()) { case 0: textposhor = "left"; break; case 1: textposhor = "center"; break; case 2: textposhor = "right"; break; case 3: // aligned case 4: // middle case 5: // fit // negeer, maar hier "center" van textposhor = "center"; } break; case INT_4: switch(cvp.getShortValue()) { case 0: textposver = "bottom"; break; // eigenlijk baseline case 1: textposver = "bottom"; break; case 2: textposver = "middle"; break; case 3: textposver = "top"; break; } break; case LAYER_NAME: //"8" t._refLayer = univers.findLayer(cvp.getStringValue()); break; case COLOR: //"62" t.setColor(cvp.getShortValue()); break; case VISIBILITY: //"60" t.setVisible(cvp.getShortValue() == 0); break; default: break; } } t.setTextposvertical(textposver); t.setTextposhorizontal(textposhor); if(isMText && directionX != null && directionY != null) { t.setTextrotation(calculateRotationFromDirectionVector(directionX, directionY)); if(log.isDebugEnabled()) { log.debug(MessageFormat.format("MTEXT entity at line number %d: text pos (%.4f,%.4f), direction vector (%.4f,%.4f), calculated text rotation %.2f degrees", t.getStartingLineNumber(), t.getX(), t.getY(), directionX, directionY, t.getTextrotation())); } } t.setType(GeometryType.POINT); return t; } private static String processOrStripTextCodes(String text) { if(text == null) { return null; } // http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%202010%20User%20Documentation/index.html?url=WS1a9193826455f5ffa23ce210c4a30acaf-63b9.htm,topicNumber=d0e123454 text = text.replaceAll("%%[cC]", "Ø"); text = text.replaceAll("\\\\[Pp]", "\r\n"); text = text.replaceAll("\\\\[Ll~]", ""); text = text.replaceAll(Pattern.quote("\\\\"), "\\"); text = text.replaceAll(Pattern.quote("\\{"), "{"); text = text.replaceAll(Pattern.quote("\\}"), "}"); text = text.replaceAll("\\\\[CcFfHhTtQqWwAa].*;", ""); return text; } private static double calculateRotationFromDirectionVector(double x, double y) { double rotation; // Hoek tussen vector (1,0) en de direction vector uit MText als theta: // arccos (theta) = inproduct(A,B) / lengte(A).lengte(B) // arccos (theta) = Bx / wortel(Bx^2 + By^2) // indien hoek in kwadrant III of IV, dan theta = -(theta-2PI) double length = Math.sqrt(x*x + y*y); if(length == 0) { rotation = 0; } else { double theta = Math.acos(x / length); if((x <= 0 && y <= 0) || (x >= 0 && y <= 0)) { theta = -(theta - 2*Math.PI); } // conversie van radialen naar graden rotation = theta * (180/Math.PI); if(Math.abs(360 - rotation) < 1e-4) { rotation = 0; } } return rotation; } @Override public Geometry getGeometry() { if (geometry == null) { updateGeometry(); } return geometry; } @Override public void updateGeometry() { if(x != null && y != null) { Coordinate c = rotateAndPlace(new Coordinate(x, y)); setGeometry(getUnivers().getGeometryFactory().createPoint(c)); } else { setGeometry(null); } } @Override public DXFEntity translate(double x, double y) { this.x += x; this.y += y; return this; } @Override public DXFEntity clone() { return new DXFText(this); //throw new UnsupportedOperationException(); } }
wscherphof/b3p-gt2-dxf
src/main/java/nl/b3p/geotools/data/dxf/entities/DXFText.java
2,844
// negeer, maar hier "center" van
line_comment
nl
package nl.b3p.geotools.data.dxf.entities; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import nl.b3p.geotools.data.dxf.parser.DXFLineNumberReader; import java.io.EOFException; import java.io.IOException; import java.text.MessageFormat; import java.util.regex.Pattern; import nl.b3p.geotools.data.GeometryType; import nl.b3p.geotools.data.dxf.parser.DXFUnivers; import nl.b3p.geotools.data.dxf.header.DXFLayer; import nl.b3p.geotools.data.dxf.header.DXFLineType; import nl.b3p.geotools.data.dxf.header.DXFTables; import nl.b3p.geotools.data.dxf.parser.DXFCodeValuePair; import nl.b3p.geotools.data.dxf.parser.DXFGroupCode; import nl.b3p.geotools.data.dxf.parser.DXFParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class DXFText extends DXFEntity { private static final Log log = LogFactory.getLog(DXFText.class); private Double x = null, y = null; public DXFText(DXFText newText) { this(newText.getColor(), newText.getRefLayer(), 0, newText.getLineType(), 0.0); setStartingLineNumber(newText.getStartingLineNumber()); setType(newText.getType()); setUnivers(newText.getUnivers()); } public DXFText(int c, DXFLayer l, int visibility, DXFLineType lineType, double thickness) { super(c, l , visibility, lineType, thickness); } public Double getX() { return x; } public void setX(Double x) { this.x = x; } public Double getY() { return y; } public void setY(Double y) { this.y = y; } public static DXFText read(DXFLineNumberReader br, DXFUnivers univers, boolean isMText) throws IOException { DXFText t = new DXFText(0, null, 0, null, DXFTables.defaultThickness); t.setUnivers(univers); t.setName(isMText ? "DXFMText" : "DXFText"); t.setTextrotation(0.0); t.setStartingLineNumber(br.getLineNumber()); DXFCodeValuePair cvp = null; DXFGroupCode gc = null; // MTEXT direction vector Double directionX = null, directionY = null; String textposhor = "left"; String textposver = "bottom"; boolean doLoop = true; while (doLoop) { cvp = new DXFCodeValuePair(); try { gc = cvp.read(br); } catch (DXFParseException ex) { throw new IOException("DXF parse error" + ex.getLocalizedMessage()); } catch (EOFException e) { doLoop = false; break; } switch (gc) { case TYPE: // geldt voor alle waarden van type br.reset(); doLoop = false; break; case X_1: //"10" t.setX(cvp.getDoubleValue()); break; case Y_1: //"20" t.setY(cvp.getDoubleValue()); break; case TEXT: //"1" t.setText(processOrStripTextCodes(cvp.getStringValue())); break; case ANGLE_1: //"50" t.setTextrotation(cvp.getDoubleValue()); break; case X_2: // 11, X-axis direction vector directionX = cvp.getDoubleValue(); break; case Y_2: // 21, Y-axis direction vector directionY = cvp.getDoubleValue(); break; case THICKNESS: //"39" t.setThickness(cvp.getDoubleValue()); break; case DOUBLE_1: //"40" t.setTextheight(cvp.getDoubleValue()); break; case INT_2: // 71: MTEXT attachment point switch(cvp.getShortValue()) { case 1: textposver = "top"; textposhor = "left"; break; case 2: textposver = "top"; textposhor = "center"; break; case 3: textposver = "top"; textposhor = "right"; break; case 4: textposver = "middle"; textposhor = "left"; break; case 5: textposver = "middle"; textposhor = "center"; break; case 6: textposver = "middle"; textposhor = "right"; break; case 7: textposver = "bottom"; textposhor = "left"; break; case 8: textposver = "bottom"; textposhor = "center"; break; case 9: textposver = "bottom"; textposhor = "right"; break; } break; case INT_3: // 72: TEXT horizontal text justification type // komen niet helemaal overeen, maar maak voor TEXT en MTEXT hetzelfde switch(cvp.getShortValue()) { case 0: textposhor = "left"; break; case 1: textposhor = "center"; break; case 2: textposhor = "right"; break; case 3: // aligned case 4: // middle case 5: // fit // negeer, maar<SUF> textposhor = "center"; } break; case INT_4: switch(cvp.getShortValue()) { case 0: textposver = "bottom"; break; // eigenlijk baseline case 1: textposver = "bottom"; break; case 2: textposver = "middle"; break; case 3: textposver = "top"; break; } break; case LAYER_NAME: //"8" t._refLayer = univers.findLayer(cvp.getStringValue()); break; case COLOR: //"62" t.setColor(cvp.getShortValue()); break; case VISIBILITY: //"60" t.setVisible(cvp.getShortValue() == 0); break; default: break; } } t.setTextposvertical(textposver); t.setTextposhorizontal(textposhor); if(isMText && directionX != null && directionY != null) { t.setTextrotation(calculateRotationFromDirectionVector(directionX, directionY)); if(log.isDebugEnabled()) { log.debug(MessageFormat.format("MTEXT entity at line number %d: text pos (%.4f,%.4f), direction vector (%.4f,%.4f), calculated text rotation %.2f degrees", t.getStartingLineNumber(), t.getX(), t.getY(), directionX, directionY, t.getTextrotation())); } } t.setType(GeometryType.POINT); return t; } private static String processOrStripTextCodes(String text) { if(text == null) { return null; } // http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%202010%20User%20Documentation/index.html?url=WS1a9193826455f5ffa23ce210c4a30acaf-63b9.htm,topicNumber=d0e123454 text = text.replaceAll("%%[cC]", "Ø"); text = text.replaceAll("\\\\[Pp]", "\r\n"); text = text.replaceAll("\\\\[Ll~]", ""); text = text.replaceAll(Pattern.quote("\\\\"), "\\"); text = text.replaceAll(Pattern.quote("\\{"), "{"); text = text.replaceAll(Pattern.quote("\\}"), "}"); text = text.replaceAll("\\\\[CcFfHhTtQqWwAa].*;", ""); return text; } private static double calculateRotationFromDirectionVector(double x, double y) { double rotation; // Hoek tussen vector (1,0) en de direction vector uit MText als theta: // arccos (theta) = inproduct(A,B) / lengte(A).lengte(B) // arccos (theta) = Bx / wortel(Bx^2 + By^2) // indien hoek in kwadrant III of IV, dan theta = -(theta-2PI) double length = Math.sqrt(x*x + y*y); if(length == 0) { rotation = 0; } else { double theta = Math.acos(x / length); if((x <= 0 && y <= 0) || (x >= 0 && y <= 0)) { theta = -(theta - 2*Math.PI); } // conversie van radialen naar graden rotation = theta * (180/Math.PI); if(Math.abs(360 - rotation) < 1e-4) { rotation = 0; } } return rotation; } @Override public Geometry getGeometry() { if (geometry == null) { updateGeometry(); } return geometry; } @Override public void updateGeometry() { if(x != null && y != null) { Coordinate c = rotateAndPlace(new Coordinate(x, y)); setGeometry(getUnivers().getGeometryFactory().createPoint(c)); } else { setGeometry(null); } } @Override public DXFEntity translate(double x, double y) { this.x += x; this.y += y; return this; } @Override public DXFEntity clone() { return new DXFText(this); //throw new UnsupportedOperationException(); } }
True
2,175
11
2,416
12
2,560
10
2,416
12
2,890
11
false
false
false
false
false
true
385
77268_2
package com.jypec.wavelet.liftingTransforms; import com.jypec.util.arrays.ArrayTransforms; import com.jypec.wavelet.Wavelet; import com.jypec.wavelet.kernelTransforms.cdf97.KernelCdf97WaveletTransform; /** * CDF 9 7 adaptation from: * https://github.com/VadimKirilchuk/jawelet/wiki/CDF-9-7-Discrete-Wavelet-Transform * * @author Daniel * */ public class LiftingCdf97WaveletTransform implements Wavelet { private static final float COEFF_PREDICT_1 = -1.586134342f; private static final float COEFF_PREDICT_2 = 0.8829110762f; private static final float COEFF_UPDATE_1= -0.05298011854f; private static final float COEFF_UPDATE_2 = 0.4435068522f; private static final float COEFF_K = 1.230174105f; private static final float COEFF_K0 = 1.0f/COEFF_K; private static final float COEFF_K1 = COEFF_K/2.0f; /** * Adds to each odd indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array <br> * E.g: {1, 0, 1} with COEFF = 1 -> {1, 2, 1} <br> * {1, 0, 2, 0} with COEFF = 1 -> {1, 3, 1, 4} * @param s the signal to be treated * @param n the length of s * @param COEFF the prediction coefficient */ private void predict(float[] s, int n, float COEFF) { // Predict inner values for (int i = 1; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 == 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Adds to each EVEN indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array * E.g: {1, 1, 1} with COEFF = 1 -> {3, 1, 3} * {1, 1, 2, 1} with COEFF = 1 -> {3, 1, 4, 1} * @param s the signal to be treated * @param n the length of s * @param COEFF the updating coefficient */ private void update(float[]s, int n, float COEFF) { // Update first coeff if (n > 1) { s[0] += 2*COEFF*s[1]; } // Update inner values for (int i = 2; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 != 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Scales the ODD samples by COEFF, and the EVEN samples by 1/COEFF * @param s the signal to be scaled * @param n the length of s * @param COEFF the coefficient applied */ private void scale(float[] s, int n, float kEven, float kOdd) { for (int i = 0; i < n; i++) { if (i%2 == 1) { s[i] *= kOdd; } else { s[i] *= kEven; } } } @Override public void forwardTransform(float[] s, int n) { //predict and update predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_1); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_2); //scale values scale(s, n, LiftingCdf97WaveletTransform.COEFF_K0, LiftingCdf97WaveletTransform.COEFF_K1); //pack values (low freq first, high freq last) ArrayTransforms.pack(s, n); } @Override public void reverseTransform(float[] s, int n) { //unpack values ArrayTransforms.unpack(s, n); //unscale values scale(s, n, 1/LiftingCdf97WaveletTransform.COEFF_K0, 1/LiftingCdf97WaveletTransform.COEFF_K1); //unpredict and unupdate update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_2); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_1); } @Override public float maxResult(float min, float max) { return new KernelCdf97WaveletTransform().maxResult(min, max); } @Override public float minResult(float min, float max) { return new KernelCdf97WaveletTransform().minResult(min, max); } }
Daniel-BG/Jypec
src/com/jypec/wavelet/liftingTransforms/LiftingCdf97WaveletTransform.java
1,595
// Predict inner values
line_comment
nl
package com.jypec.wavelet.liftingTransforms; import com.jypec.util.arrays.ArrayTransforms; import com.jypec.wavelet.Wavelet; import com.jypec.wavelet.kernelTransforms.cdf97.KernelCdf97WaveletTransform; /** * CDF 9 7 adaptation from: * https://github.com/VadimKirilchuk/jawelet/wiki/CDF-9-7-Discrete-Wavelet-Transform * * @author Daniel * */ public class LiftingCdf97WaveletTransform implements Wavelet { private static final float COEFF_PREDICT_1 = -1.586134342f; private static final float COEFF_PREDICT_2 = 0.8829110762f; private static final float COEFF_UPDATE_1= -0.05298011854f; private static final float COEFF_UPDATE_2 = 0.4435068522f; private static final float COEFF_K = 1.230174105f; private static final float COEFF_K0 = 1.0f/COEFF_K; private static final float COEFF_K1 = COEFF_K/2.0f; /** * Adds to each odd indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array <br> * E.g: {1, 0, 1} with COEFF = 1 -> {1, 2, 1} <br> * {1, 0, 2, 0} with COEFF = 1 -> {1, 3, 1, 4} * @param s the signal to be treated * @param n the length of s * @param COEFF the prediction coefficient */ private void predict(float[] s, int n, float COEFF) { // Predict inner<SUF> for (int i = 1; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 == 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Adds to each EVEN indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array * E.g: {1, 1, 1} with COEFF = 1 -> {3, 1, 3} * {1, 1, 2, 1} with COEFF = 1 -> {3, 1, 4, 1} * @param s the signal to be treated * @param n the length of s * @param COEFF the updating coefficient */ private void update(float[]s, int n, float COEFF) { // Update first coeff if (n > 1) { s[0] += 2*COEFF*s[1]; } // Update inner values for (int i = 2; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 != 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Scales the ODD samples by COEFF, and the EVEN samples by 1/COEFF * @param s the signal to be scaled * @param n the length of s * @param COEFF the coefficient applied */ private void scale(float[] s, int n, float kEven, float kOdd) { for (int i = 0; i < n; i++) { if (i%2 == 1) { s[i] *= kOdd; } else { s[i] *= kEven; } } } @Override public void forwardTransform(float[] s, int n) { //predict and update predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_1); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_2); //scale values scale(s, n, LiftingCdf97WaveletTransform.COEFF_K0, LiftingCdf97WaveletTransform.COEFF_K1); //pack values (low freq first, high freq last) ArrayTransforms.pack(s, n); } @Override public void reverseTransform(float[] s, int n) { //unpack values ArrayTransforms.unpack(s, n); //unscale values scale(s, n, 1/LiftingCdf97WaveletTransform.COEFF_K0, 1/LiftingCdf97WaveletTransform.COEFF_K1); //unpredict and unupdate update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_2); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_1); } @Override public float maxResult(float min, float max) { return new KernelCdf97WaveletTransform().maxResult(min, max); } @Override public float minResult(float min, float max) { return new KernelCdf97WaveletTransform().minResult(min, max); } }
False
1,386
4
1,505
4
1,509
4
1,505
4
1,711
5
false
false
false
false
false
true
1,723
120692_11
package com.google.havlak.client; import com.google.havlak.shared.FieldVerifier; import com.google.havlak.shared.cfg.BasicBlock; import com.google.havlak.shared.cfg.BasicBlockEdge; import com.google.havlak.shared.cfg.CFG; import com.google.havlak.shared.lsg.LSG; import com.google.havlak.shared.lsg.SimpleLoop; import com.google.havlak.shared.havlakloopfinder.HavlakLoopFinder; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; class LoopTesterApp { public LoopTesterApp() { cfg = new CFG(); lsg = new LSG(); root = cfg.createNode(0); } // Create 4 basic blocks, corresponding to and if/then/else clause // with a CFG that looks like a diamond public int buildDiamond(int start) { int bb0 = start; new BasicBlockEdge(cfg, bb0, bb0 + 1); new BasicBlockEdge(cfg, bb0, bb0 + 2); new BasicBlockEdge(cfg, bb0 + 1, bb0 + 3); new BasicBlockEdge(cfg, bb0 + 2, bb0 + 3); return bb0 + 3; } // Connect two existing nodes public void buildConnect(int start, int end) { new BasicBlockEdge(cfg, start, end); } // Form a straight connected sequence of n basic blocks public int buildStraight(int start, int n) { for (int i = 0; i < n; i++) { buildConnect(start + i, start + i + 1); } return start + n; } // Construct a simple loop with two diamonds in it public int buildBaseLoop(int from) { int header = buildStraight(from, 1); int diamond1 = buildDiamond(header); int d11 = buildStraight(diamond1, 1); int diamond2 = buildDiamond(d11); int footer = buildStraight(diamond2, 1); buildConnect(diamond2, d11); buildConnect(diamond1, header); buildConnect(footer, from); footer = buildStraight(footer, 1); return footer; } public CFG cfg; public LSG lsg; private BasicBlock root; } /** * Entry point classes define <code>onModuleLoad()</code>. */ public class Havlak implements EntryPoint { /** * The message displayed to the user when the server cannot be reached or * returns an error. */ private static final String SERVER_ERROR = "An error occurred while " + "attempting to contact the server. Please check your network " + "connection and try again."; /** * Create a remote service proxy to talk to the server-side Greeting service. */ private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class); /** * This is the entry point method. */ public void onModuleLoad() { final Button sendButton = new Button("Send to Havlak"); final TextBox nameField = new TextBox(); nameField.setText("GWT User"); final Label errorLabel = new Label(); // We can add style names to widgets sendButton.addStyleName("sendButton"); // Add the nameField and sendButton to the RootPanel // Use RootPanel.get() to get the entire body element RootPanel.get("nameFieldContainer").add(nameField); RootPanel.get("sendButtonContainer").add(sendButton); RootPanel.get("errorLabelContainer").add(errorLabel); // Focus the cursor on the name field when the app loads nameField.setFocus(true); nameField.selectAll(); // Create the popup dialog box final DialogBox dialogBox = new DialogBox(); dialogBox.setText("Loop Recognition"); dialogBox.setAnimationEnabled(true); final Button closeButton = new Button("Close"); // We can set the id of a widget by accessing its Element closeButton.getElement().setId("closeButton"); final Label textToServerLabel = new Label(); final HTML serverResponseLabel = new HTML(); VerticalPanel dialogVPanel = new VerticalPanel(); dialogVPanel.addStyleName("dialogVPanel"); dialogVPanel.add(textToServerLabel); dialogVPanel.add(new HTML("<br><b>Algorithm replies:</b>")); dialogVPanel.add(serverResponseLabel); dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT); dialogVPanel.add(closeButton); dialogBox.setWidget(dialogVPanel); // Add a handler to close the DialogBox closeButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { dialogBox.hide(); sendButton.setEnabled(true); sendButton.setFocus(true); } }); // Create a handler for the sendButton and nameField class MyHandler implements ClickHandler, KeyUpHandler { /** * Fired when the user clicks on the sendButton. */ public void onClick(ClickEvent event) { sendNameToServer(); } /** * Fired when the user types in the nameField. */ public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { sendNameToServer(); } } /** * Send the name from the nameField to the server and wait for a response. */ private void sendNameToServer() { // First, we validate the input. errorLabel.setText(""); String textToServer = nameField.getText(); //======================================================= // HAVLAK //======================================================= long start = System.currentTimeMillis(); String result = "Welcome to LoopTesterApp, GWT edition<br>"; LoopTesterApp app = new LoopTesterApp(); app.cfg.createNode(0); app.lsg.dump(); app.buildBaseLoop(0); app.cfg.createNode(1); new BasicBlockEdge(app.cfg, 0, 2); int found = 0; result += "15000 dummy loops<br>"; serverResponseLabel.setHTML(result); for (int dummyloop = 0; dummyloop < 1; dummyloop++) { HavlakLoopFinder finder = new HavlakLoopFinder(app.cfg, app.lsg); finder.findLoops(); } result += "Constructing CFG...<br>"; serverResponseLabel.setHTML(result); int n = 2; for (int parlooptrees = 0; parlooptrees < 10; parlooptrees++) { app.cfg.createNode(n + 1); app.buildConnect(2, n + 1); n = n + 1; for (int i = 0; i < 2; i++) { int top = n; n = app.buildStraight(n, 1); for (int j = 0; j < 25; j++) { n = app.buildBaseLoop(n); } int bottom = app.buildStraight(n, 1); app.buildConnect(n, top); n = bottom; } app.buildConnect(n, 1); } result += "Performing Loop Recognition\n1 Iteration<br>"; HavlakLoopFinder finder = new HavlakLoopFinder(app.cfg, app.lsg); finder.findLoops(); long t = System.currentTimeMillis() - start; result += "Found: " + app.lsg.getNumLoops() + " in " + t + " [ms]"; result += "Another 100 iterations...<br>"; for (int i = 0; i < 100; i++) { HavlakLoopFinder finder2 = new HavlakLoopFinder(app.cfg, new LSG()); finder2.findLoops(); } t = System.currentTimeMillis() - start; result += "<br>Found: " + app.lsg.getNumLoops() + " in " + t + " [ms]"; //======================================================= sendButton.setEnabled(false); dialogBox.setText("Find Loops"); serverResponseLabel.setHTML(result); dialogBox.center(); closeButton.setFocus(true); /* // if (!FieldVerifier.isValidName(textToServer)) { // errorLabel.setText("Please enter at least four characters"); // return; // } // Then, we send the input to the server. textToServerLabel.setText(textToServer); serverResponseLabel.setText(""); greetingService.greetServer(textToServer, new AsyncCallback<String>() { public void onFailure(Throwable caught) { // Show the RPC error message to the user dialogBox.setText("Remote Procedure Call - Failure"); serverResponseLabel.addStyleName("serverResponseLabelError"); serverResponseLabel.setHTML(SERVER_ERROR); dialogBox.center(); closeButton.setFocus(true); } public void onSuccess(String result) { dialogBox.setText("Finding Loops..."); serverResponseLabel.removeStyleName("serverResponseLabelError"); serverResponseLabel.setHTML(result); dialogBox.center(); closeButton.setFocus(true); } }); */ } } // Add a handler to send the name to the server MyHandler handler = new MyHandler(); sendButton.addClickHandler(handler); nameField.addKeyUpHandler(handler); } }
Thiez/multi-language-bench
src/havlak/gwt/src/com/google/havlak/client/Havlak.java
2,888
// Use RootPanel.get() to get the entire body element
line_comment
nl
package com.google.havlak.client; import com.google.havlak.shared.FieldVerifier; import com.google.havlak.shared.cfg.BasicBlock; import com.google.havlak.shared.cfg.BasicBlockEdge; import com.google.havlak.shared.cfg.CFG; import com.google.havlak.shared.lsg.LSG; import com.google.havlak.shared.lsg.SimpleLoop; import com.google.havlak.shared.havlakloopfinder.HavlakLoopFinder; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; class LoopTesterApp { public LoopTesterApp() { cfg = new CFG(); lsg = new LSG(); root = cfg.createNode(0); } // Create 4 basic blocks, corresponding to and if/then/else clause // with a CFG that looks like a diamond public int buildDiamond(int start) { int bb0 = start; new BasicBlockEdge(cfg, bb0, bb0 + 1); new BasicBlockEdge(cfg, bb0, bb0 + 2); new BasicBlockEdge(cfg, bb0 + 1, bb0 + 3); new BasicBlockEdge(cfg, bb0 + 2, bb0 + 3); return bb0 + 3; } // Connect two existing nodes public void buildConnect(int start, int end) { new BasicBlockEdge(cfg, start, end); } // Form a straight connected sequence of n basic blocks public int buildStraight(int start, int n) { for (int i = 0; i < n; i++) { buildConnect(start + i, start + i + 1); } return start + n; } // Construct a simple loop with two diamonds in it public int buildBaseLoop(int from) { int header = buildStraight(from, 1); int diamond1 = buildDiamond(header); int d11 = buildStraight(diamond1, 1); int diamond2 = buildDiamond(d11); int footer = buildStraight(diamond2, 1); buildConnect(diamond2, d11); buildConnect(diamond1, header); buildConnect(footer, from); footer = buildStraight(footer, 1); return footer; } public CFG cfg; public LSG lsg; private BasicBlock root; } /** * Entry point classes define <code>onModuleLoad()</code>. */ public class Havlak implements EntryPoint { /** * The message displayed to the user when the server cannot be reached or * returns an error. */ private static final String SERVER_ERROR = "An error occurred while " + "attempting to contact the server. Please check your network " + "connection and try again."; /** * Create a remote service proxy to talk to the server-side Greeting service. */ private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class); /** * This is the entry point method. */ public void onModuleLoad() { final Button sendButton = new Button("Send to Havlak"); final TextBox nameField = new TextBox(); nameField.setText("GWT User"); final Label errorLabel = new Label(); // We can add style names to widgets sendButton.addStyleName("sendButton"); // Add the nameField and sendButton to the RootPanel // Use RootPanel.get()<SUF> RootPanel.get("nameFieldContainer").add(nameField); RootPanel.get("sendButtonContainer").add(sendButton); RootPanel.get("errorLabelContainer").add(errorLabel); // Focus the cursor on the name field when the app loads nameField.setFocus(true); nameField.selectAll(); // Create the popup dialog box final DialogBox dialogBox = new DialogBox(); dialogBox.setText("Loop Recognition"); dialogBox.setAnimationEnabled(true); final Button closeButton = new Button("Close"); // We can set the id of a widget by accessing its Element closeButton.getElement().setId("closeButton"); final Label textToServerLabel = new Label(); final HTML serverResponseLabel = new HTML(); VerticalPanel dialogVPanel = new VerticalPanel(); dialogVPanel.addStyleName("dialogVPanel"); dialogVPanel.add(textToServerLabel); dialogVPanel.add(new HTML("<br><b>Algorithm replies:</b>")); dialogVPanel.add(serverResponseLabel); dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT); dialogVPanel.add(closeButton); dialogBox.setWidget(dialogVPanel); // Add a handler to close the DialogBox closeButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { dialogBox.hide(); sendButton.setEnabled(true); sendButton.setFocus(true); } }); // Create a handler for the sendButton and nameField class MyHandler implements ClickHandler, KeyUpHandler { /** * Fired when the user clicks on the sendButton. */ public void onClick(ClickEvent event) { sendNameToServer(); } /** * Fired when the user types in the nameField. */ public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { sendNameToServer(); } } /** * Send the name from the nameField to the server and wait for a response. */ private void sendNameToServer() { // First, we validate the input. errorLabel.setText(""); String textToServer = nameField.getText(); //======================================================= // HAVLAK //======================================================= long start = System.currentTimeMillis(); String result = "Welcome to LoopTesterApp, GWT edition<br>"; LoopTesterApp app = new LoopTesterApp(); app.cfg.createNode(0); app.lsg.dump(); app.buildBaseLoop(0); app.cfg.createNode(1); new BasicBlockEdge(app.cfg, 0, 2); int found = 0; result += "15000 dummy loops<br>"; serverResponseLabel.setHTML(result); for (int dummyloop = 0; dummyloop < 1; dummyloop++) { HavlakLoopFinder finder = new HavlakLoopFinder(app.cfg, app.lsg); finder.findLoops(); } result += "Constructing CFG...<br>"; serverResponseLabel.setHTML(result); int n = 2; for (int parlooptrees = 0; parlooptrees < 10; parlooptrees++) { app.cfg.createNode(n + 1); app.buildConnect(2, n + 1); n = n + 1; for (int i = 0; i < 2; i++) { int top = n; n = app.buildStraight(n, 1); for (int j = 0; j < 25; j++) { n = app.buildBaseLoop(n); } int bottom = app.buildStraight(n, 1); app.buildConnect(n, top); n = bottom; } app.buildConnect(n, 1); } result += "Performing Loop Recognition\n1 Iteration<br>"; HavlakLoopFinder finder = new HavlakLoopFinder(app.cfg, app.lsg); finder.findLoops(); long t = System.currentTimeMillis() - start; result += "Found: " + app.lsg.getNumLoops() + " in " + t + " [ms]"; result += "Another 100 iterations...<br>"; for (int i = 0; i < 100; i++) { HavlakLoopFinder finder2 = new HavlakLoopFinder(app.cfg, new LSG()); finder2.findLoops(); } t = System.currentTimeMillis() - start; result += "<br>Found: " + app.lsg.getNumLoops() + " in " + t + " [ms]"; //======================================================= sendButton.setEnabled(false); dialogBox.setText("Find Loops"); serverResponseLabel.setHTML(result); dialogBox.center(); closeButton.setFocus(true); /* // if (!FieldVerifier.isValidName(textToServer)) { // errorLabel.setText("Please enter at least four characters"); // return; // } // Then, we send the input to the server. textToServerLabel.setText(textToServer); serverResponseLabel.setText(""); greetingService.greetServer(textToServer, new AsyncCallback<String>() { public void onFailure(Throwable caught) { // Show the RPC error message to the user dialogBox.setText("Remote Procedure Call - Failure"); serverResponseLabel.addStyleName("serverResponseLabelError"); serverResponseLabel.setHTML(SERVER_ERROR); dialogBox.center(); closeButton.setFocus(true); } public void onSuccess(String result) { dialogBox.setText("Finding Loops..."); serverResponseLabel.removeStyleName("serverResponseLabelError"); serverResponseLabel.setHTML(result); dialogBox.center(); closeButton.setFocus(true); } }); */ } } // Add a handler to send the name to the server MyHandler handler = new MyHandler(); sendButton.addClickHandler(handler); nameField.addKeyUpHandler(handler); } }
False
2,165
12
2,477
13
2,616
13
2,477
13
2,847
13
false
false
false
false
false
true
1,458
62866_7
package stamboom.domain; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.*; import javafx.beans.property.LongProperty; import javafx.beans.property.SimpleLongProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import stamboom.util.StringUtilities; public class Gezin implements Serializable { // *********datavelden************************************* private final int nr; private final Persoon ouder1; private final Persoon ouder2; private final List<Persoon> kinderen; private transient ObservableList<Persoon> obsKinderen; private String childnames = ""; /** * kan onbekend zijn (dan is het een ongehuwd gezin): */ private Calendar huwelijksdatum ; /** * kan null zijn; als huwelijksdatum null is, dan zal scheidingsdatum ook null * zijn; Als huwelijksdatum en scheidingsdatum bekend zijn, dan zal de * scheidingsdatum na het huewelijk zijn. */ private Calendar scheidingsdatum ; // *********constructoren*********************************** /** * er wordt een (kinderloos) gezin met ouder1 en ouder2 als ouders * geregistreerd; de huwelijks-(en scheidings)datum zijn onbekend (null); * het gezin krijgt gezinsNr als nummer; * * @param ouder1 mag niet null zijn, moet al geboren zijn, * en mag geen famillie van ouder2 zijn. * @param ouder2 ongelijk aan ouder1, moet al geboren zijn, * en mag geen familie van ouder1 zijn. */ Gezin(int gezinsNr, Persoon ouder1, Persoon ouder2) { if (ouder1 == null) { throw new RuntimeException("Eerste ouder mag niet null zijn"); } if (ouder1 == ouder2) { throw new RuntimeException("ouders hetzelfde"); } if (ouder2 != null) { if (ouder1.getOuderlijkGezin() != null && ouder1.getOuderlijkGezin().isFamilieVan(ouder2)) { throw new RuntimeException("ouder 2 is familie van ouder 1"); } if (ouder2.getOuderlijkGezin() != null && ouder2.getOuderlijkGezin().isFamilieVan(ouder1)) { throw new RuntimeException("ouder 1 is familie van ouder 2"); } } if (ouder1.getGebDat().compareTo(Calendar.getInstance()) > 0){ throw new RuntimeException("ouder1 moet nog geboren worden"); } if (ouder2 != null && ouder2.getGebDat().compareTo(Calendar.getInstance()) > 0) { throw new RuntimeException("ouder2 moet nog geboren worden"); } this.nr = gezinsNr; this.ouder1 = ouder1; this.ouder2 = ouder2; this.huwelijksdatum = null; this.scheidingsdatum = null; kinderen = new ArrayList<>(); obsKinderen = FXCollections.observableList(kinderen); } // ********methoden***************************************** public ObservableList<Persoon> getKinderen() { return (ObservableList<Persoon>) FXCollections.unmodifiableObservableList(obsKinderen); } /** * @return alle kinderen uit dit gezin */ // public List<Persoon> getKinderen() { // return (List<Persoon>) Collections.unmodifiableList(kinderen); // } /** * * @return het aantal kinderen in dit gezin */ public int aantalKinderen() { return kinderen.size(); } /** * * @return het nummer van dit gezin */ public int getNr() { return nr; } /** * @return de eerste ouder van dit gezin */ public Persoon getOuder1() { return ouder1; } /** * @return de tweede ouder van dit gezin (kan null zijn) */ public Persoon getOuder2() { return ouder2; } /** * * @return het nr, de naam van de eerste ouder, gevolgd door de naam van de * eventuele tweede ouder. Als dit gezin getrouwd is, wordt ook de huwelijksdatum * vermeld. */ @Override public String toString() { StringBuilder s = new StringBuilder(); s.append(this.nr).append(" "); s.append(ouder1.getNaam()); if (ouder2 != null) { s.append(" met "); s.append(ouder2.getNaam()); } if (heeftGetrouwdeOudersOp(Calendar.getInstance())) { s.append(" ").append(StringUtilities.datumString(huwelijksdatum)); } return s.toString().trim(); } /** * @return de datum van het huwelijk (kan null zijn) */ public Calendar getHuwelijksdatum() { return huwelijksdatum; } /** * @return de datum van scheiding (kan null zijn) */ public Calendar getScheidingsdatum() { return scheidingsdatum; } /** * Als ouders zijn gehuwd, en er nog geen scheidingsdatum is dan wordt deze * geregistreerd. * * @param datum moet na de huwelijksdatum zijn. * @return true als scheiding kan worden voltrokken, anders false */ boolean setScheiding(Calendar datum) { if (this.scheidingsdatum == null && huwelijksdatum != null && datum != null && datum.after(huwelijksdatum)) { this.scheidingsdatum = datum; return true; } else { return false; } } /** * registreert het huwelijk, mits dit gezin nog geen huwelijk is en beide * ouders op deze datum mogen trouwen (pas op: het is mogelijk dat er al wel * een huwelijk staat gepland, maar nog niet is voltrokken op deze datum) * Mensen mogen niet trouwen voor hun achttiende. * * @param datum de huwelijksdatum * @return false als huwelijk niet mocht worden voltrokken, anders true */ boolean setHuwelijk(Calendar datum) { //todo opgave 1 Calendar today = Calendar.getInstance(); int ageOuder1 = today.get(Calendar.YEAR) - ouder1.getGebDat().get(Calendar.YEAR); int ageOuder2 = today.get(Calendar.YEAR) - ouder2.getGebDat().get(Calendar.YEAR); if(ageOuder1 < 18 || ageOuder2 < 18) { return false; } if(datum.before(huwelijksdatum)|| huwelijksdatum == null) { huwelijksdatum = datum; return true; } else { return false; } } /** * @return het gezinsnummer, gevolgd door de namen van de ouder(s), * de eventueel bekende huwelijksdatum, (als er kinderen zijn) * de constante tekst '; kinderen:', en de voornamen van de * kinderen uit deze relatie (per kind voorafgegaan door ' -') */ public String beschrijving() { //todo opgave 1 String result = this.nr + " " + this.ouder1.getNaam() + " met " + this.ouder2.getNaam(); if (this.huwelijksdatum != null) { result = result + " " + StringUtilities.datumString(huwelijksdatum); } if (this.kinderen != null && this.kinderen.size() >= 1) { result = result + "; kinderen: "; for (Persoon persoon : this.kinderen) { result = result + "-" + persoon.getVoornamen() + " "; } } return result.trim(); } public String beschrijvingKinderen() { //todo opgave 1 String result = ""; if (this.kinderen != null && this.kinderen.size() >= 1) { for (Persoon persoon : this.kinderen) { result = result + persoon.getVoornamen() + " "; } } return result.trim(); } /** * Voegt kind toe aan dit gezin. Doet niets als dit kind al deel uitmaakt * van deze familie. * * @param kind */ void breidUitMet(Persoon kind) { if (!kinderen.contains(kind) && !this.isFamilieVan(kind)) { kinderen.add(kind); } } /** * Controleert of deze familie niet al de gegeven persoon bevat. * * @param input * @return true als deze familie de gegeven persoon bevat. */ boolean isFamilieVan(Persoon input) { if (this.ouder1.getNr() == input.getNr() || (this.ouder2 != null && this.ouder2.getNr() == input.getNr()) || kinderen.contains(input)) { return true; } boolean output = this.ouder1.getOuderlijkGezin() != null && this.ouder1.getOuderlijkGezin().isFamilieVan(input); if (!output && this.ouder2 != null) { output = this.ouder2.getOuderlijkGezin() != null && this.ouder2.getOuderlijkGezin().isFamilieVan(input); } return output; } /** * * @param datum * @return true als dit gezin op datum getrouwd en nog niet gescheiden is, * anders false */ public boolean heeftGetrouwdeOudersOp(Calendar datum) { return isHuwelijkOp(datum) && (scheidingsdatum == null || scheidingsdatum.after(datum)); } /** * * @param datum * @return true als dit gezin op of voor deze datum getrouwd is, ongeacht of * de ouders hierna gingen/gaan scheiden. */ public boolean isHuwelijkOp(Calendar datum) { //todo opgave 1 if(huwelijksdatum == null){ return false; } else if(huwelijksdatum.before(datum)){ return true; } return false; } /** * * @return true als de ouders van dit gezin niet getrouwd zijn, anders false */ public boolean isOngehuwd() { if(huwelijksdatum == null){ return true; } return false; } /** * * @param datum * @return true als dit een gescheiden huwelijk is op datum, anders false */ public boolean heeftGescheidenOudersOp(Calendar datum) { //todo opgave 1 boolean isGescheiden = false; if(ouder1.isGescheidenOp(datum)) { isGescheiden = true; } if(ouder2.isGescheidenOp(datum)) { isGescheiden = true; } return isGescheiden; } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); obsKinderen = FXCollections.observableList(kinderen); } }
Requinard/C2j
src/stamboom/domain/Gezin.java
3,221
/** * * @return het nummer van dit gezin */
block_comment
nl
package stamboom.domain; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.*; import javafx.beans.property.LongProperty; import javafx.beans.property.SimpleLongProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import stamboom.util.StringUtilities; public class Gezin implements Serializable { // *********datavelden************************************* private final int nr; private final Persoon ouder1; private final Persoon ouder2; private final List<Persoon> kinderen; private transient ObservableList<Persoon> obsKinderen; private String childnames = ""; /** * kan onbekend zijn (dan is het een ongehuwd gezin): */ private Calendar huwelijksdatum ; /** * kan null zijn; als huwelijksdatum null is, dan zal scheidingsdatum ook null * zijn; Als huwelijksdatum en scheidingsdatum bekend zijn, dan zal de * scheidingsdatum na het huewelijk zijn. */ private Calendar scheidingsdatum ; // *********constructoren*********************************** /** * er wordt een (kinderloos) gezin met ouder1 en ouder2 als ouders * geregistreerd; de huwelijks-(en scheidings)datum zijn onbekend (null); * het gezin krijgt gezinsNr als nummer; * * @param ouder1 mag niet null zijn, moet al geboren zijn, * en mag geen famillie van ouder2 zijn. * @param ouder2 ongelijk aan ouder1, moet al geboren zijn, * en mag geen familie van ouder1 zijn. */ Gezin(int gezinsNr, Persoon ouder1, Persoon ouder2) { if (ouder1 == null) { throw new RuntimeException("Eerste ouder mag niet null zijn"); } if (ouder1 == ouder2) { throw new RuntimeException("ouders hetzelfde"); } if (ouder2 != null) { if (ouder1.getOuderlijkGezin() != null && ouder1.getOuderlijkGezin().isFamilieVan(ouder2)) { throw new RuntimeException("ouder 2 is familie van ouder 1"); } if (ouder2.getOuderlijkGezin() != null && ouder2.getOuderlijkGezin().isFamilieVan(ouder1)) { throw new RuntimeException("ouder 1 is familie van ouder 2"); } } if (ouder1.getGebDat().compareTo(Calendar.getInstance()) > 0){ throw new RuntimeException("ouder1 moet nog geboren worden"); } if (ouder2 != null && ouder2.getGebDat().compareTo(Calendar.getInstance()) > 0) { throw new RuntimeException("ouder2 moet nog geboren worden"); } this.nr = gezinsNr; this.ouder1 = ouder1; this.ouder2 = ouder2; this.huwelijksdatum = null; this.scheidingsdatum = null; kinderen = new ArrayList<>(); obsKinderen = FXCollections.observableList(kinderen); } // ********methoden***************************************** public ObservableList<Persoon> getKinderen() { return (ObservableList<Persoon>) FXCollections.unmodifiableObservableList(obsKinderen); } /** * @return alle kinderen uit dit gezin */ // public List<Persoon> getKinderen() { // return (List<Persoon>) Collections.unmodifiableList(kinderen); // } /** * * @return het aantal kinderen in dit gezin */ public int aantalKinderen() { return kinderen.size(); } /** * * @return het nummer<SUF>*/ public int getNr() { return nr; } /** * @return de eerste ouder van dit gezin */ public Persoon getOuder1() { return ouder1; } /** * @return de tweede ouder van dit gezin (kan null zijn) */ public Persoon getOuder2() { return ouder2; } /** * * @return het nr, de naam van de eerste ouder, gevolgd door de naam van de * eventuele tweede ouder. Als dit gezin getrouwd is, wordt ook de huwelijksdatum * vermeld. */ @Override public String toString() { StringBuilder s = new StringBuilder(); s.append(this.nr).append(" "); s.append(ouder1.getNaam()); if (ouder2 != null) { s.append(" met "); s.append(ouder2.getNaam()); } if (heeftGetrouwdeOudersOp(Calendar.getInstance())) { s.append(" ").append(StringUtilities.datumString(huwelijksdatum)); } return s.toString().trim(); } /** * @return de datum van het huwelijk (kan null zijn) */ public Calendar getHuwelijksdatum() { return huwelijksdatum; } /** * @return de datum van scheiding (kan null zijn) */ public Calendar getScheidingsdatum() { return scheidingsdatum; } /** * Als ouders zijn gehuwd, en er nog geen scheidingsdatum is dan wordt deze * geregistreerd. * * @param datum moet na de huwelijksdatum zijn. * @return true als scheiding kan worden voltrokken, anders false */ boolean setScheiding(Calendar datum) { if (this.scheidingsdatum == null && huwelijksdatum != null && datum != null && datum.after(huwelijksdatum)) { this.scheidingsdatum = datum; return true; } else { return false; } } /** * registreert het huwelijk, mits dit gezin nog geen huwelijk is en beide * ouders op deze datum mogen trouwen (pas op: het is mogelijk dat er al wel * een huwelijk staat gepland, maar nog niet is voltrokken op deze datum) * Mensen mogen niet trouwen voor hun achttiende. * * @param datum de huwelijksdatum * @return false als huwelijk niet mocht worden voltrokken, anders true */ boolean setHuwelijk(Calendar datum) { //todo opgave 1 Calendar today = Calendar.getInstance(); int ageOuder1 = today.get(Calendar.YEAR) - ouder1.getGebDat().get(Calendar.YEAR); int ageOuder2 = today.get(Calendar.YEAR) - ouder2.getGebDat().get(Calendar.YEAR); if(ageOuder1 < 18 || ageOuder2 < 18) { return false; } if(datum.before(huwelijksdatum)|| huwelijksdatum == null) { huwelijksdatum = datum; return true; } else { return false; } } /** * @return het gezinsnummer, gevolgd door de namen van de ouder(s), * de eventueel bekende huwelijksdatum, (als er kinderen zijn) * de constante tekst '; kinderen:', en de voornamen van de * kinderen uit deze relatie (per kind voorafgegaan door ' -') */ public String beschrijving() { //todo opgave 1 String result = this.nr + " " + this.ouder1.getNaam() + " met " + this.ouder2.getNaam(); if (this.huwelijksdatum != null) { result = result + " " + StringUtilities.datumString(huwelijksdatum); } if (this.kinderen != null && this.kinderen.size() >= 1) { result = result + "; kinderen: "; for (Persoon persoon : this.kinderen) { result = result + "-" + persoon.getVoornamen() + " "; } } return result.trim(); } public String beschrijvingKinderen() { //todo opgave 1 String result = ""; if (this.kinderen != null && this.kinderen.size() >= 1) { for (Persoon persoon : this.kinderen) { result = result + persoon.getVoornamen() + " "; } } return result.trim(); } /** * Voegt kind toe aan dit gezin. Doet niets als dit kind al deel uitmaakt * van deze familie. * * @param kind */ void breidUitMet(Persoon kind) { if (!kinderen.contains(kind) && !this.isFamilieVan(kind)) { kinderen.add(kind); } } /** * Controleert of deze familie niet al de gegeven persoon bevat. * * @param input * @return true als deze familie de gegeven persoon bevat. */ boolean isFamilieVan(Persoon input) { if (this.ouder1.getNr() == input.getNr() || (this.ouder2 != null && this.ouder2.getNr() == input.getNr()) || kinderen.contains(input)) { return true; } boolean output = this.ouder1.getOuderlijkGezin() != null && this.ouder1.getOuderlijkGezin().isFamilieVan(input); if (!output && this.ouder2 != null) { output = this.ouder2.getOuderlijkGezin() != null && this.ouder2.getOuderlijkGezin().isFamilieVan(input); } return output; } /** * * @param datum * @return true als dit gezin op datum getrouwd en nog niet gescheiden is, * anders false */ public boolean heeftGetrouwdeOudersOp(Calendar datum) { return isHuwelijkOp(datum) && (scheidingsdatum == null || scheidingsdatum.after(datum)); } /** * * @param datum * @return true als dit gezin op of voor deze datum getrouwd is, ongeacht of * de ouders hierna gingen/gaan scheiden. */ public boolean isHuwelijkOp(Calendar datum) { //todo opgave 1 if(huwelijksdatum == null){ return false; } else if(huwelijksdatum.before(datum)){ return true; } return false; } /** * * @return true als de ouders van dit gezin niet getrouwd zijn, anders false */ public boolean isOngehuwd() { if(huwelijksdatum == null){ return true; } return false; } /** * * @param datum * @return true als dit een gescheiden huwelijk is op datum, anders false */ public boolean heeftGescheidenOudersOp(Calendar datum) { //todo opgave 1 boolean isGescheiden = false; if(ouder1.isGescheidenOp(datum)) { isGescheiden = true; } if(ouder2.isGescheidenOp(datum)) { isGescheiden = true; } return isGescheiden; } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); obsKinderen = FXCollections.observableList(kinderen); } }
True
2,695
17
2,941
17
2,828
17
2,941
17
3,236
19
false
false
false
false
false
true
4,751
16526_3
/*-------------------------------------------------------------------------- * Copyright 2008 Taro L. Saito * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *--------------------------------------------------------------------------*/ //-------------------------------------- // snappy-java Project // // OSInfo.java // Since: May 20, 2008 // // $URL$ // $Author$ //-------------------------------------- package org.xerial.snappy; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Locale; /** * Provides OS name and architecture name. * * @author leo */ public class OSInfo { private static HashMap<String, String> archMapping = new HashMap<String, String>(); public static final String X86 = "x86"; public static final String X86_64 = "x86_64"; public static final String IA64_32 = "ia64_32"; public static final String IA64 = "ia64"; public static final String PPC = "ppc"; public static final String PPC64 = "ppc64"; public static final String IBMZ = "s390"; public static final String IBMZ_64 = "s390x"; public static final String AARCH_64 = "aarch64"; public static final String RISCV_64 = "riscv64"; public static final String LOONGARCH_64 = "loongarch64"; static { // x86 mappings archMapping.put(X86, X86); archMapping.put("i386", X86); archMapping.put("i486", X86); archMapping.put("i586", X86); archMapping.put("i686", X86); archMapping.put("pentium", X86); // x86_64 mappings archMapping.put(X86_64, X86_64); archMapping.put("amd64", X86_64); archMapping.put("em64t", X86_64); archMapping.put("universal", X86_64); // Needed for openjdk7 in Mac // Itenium 64-bit mappings archMapping.put(IA64, IA64); archMapping.put("ia64w", IA64); // Itenium 32-bit mappings, usually an HP-UX construct archMapping.put(IA64_32, IA64_32); archMapping.put("ia64n", IA64_32); // PowerPC mappings archMapping.put(PPC, PPC); archMapping.put("power", PPC); archMapping.put("powerpc", PPC); archMapping.put("power_pc", PPC); archMapping.put("power_rs", PPC); // TODO: PowerPC 64bit mappings archMapping.put(PPC64, PPC64); archMapping.put("power64", PPC64); archMapping.put("powerpc64", PPC64); archMapping.put("power_pc64", PPC64); archMapping.put("power_rs64", PPC64); // IBM z mappings archMapping.put(IBMZ, IBMZ); // IBM z 64-bit mappings archMapping.put(IBMZ_64, IBMZ_64); // Aarch64 mappings archMapping.put(AARCH_64, AARCH_64); // RISC-V mappings archMapping.put(RISCV_64, RISCV_64); // LoongArch64 mappings archMapping.put(LOONGARCH_64, LOONGARCH_64); } public static void main(String[] args) { if(args.length >= 1) { if("--os".equals(args[0])) { System.out.print(getOSName()); return; } else if("--arch".equals(args[0])) { System.out.print(getArchName()); return; } } System.out.print(getNativeLibFolderPathForCurrentOS()); } public static String getNativeLibFolderPathForCurrentOS() { return getOSName() + "/" + getArchName(); } public static String getOSName() { return translateOSNameToFolderName(System.getProperty("os.name")); } public static boolean isAndroid() { return System.getProperty("java.runtime.name", "").toLowerCase().contains("android"); } static String getHardwareName() { try { Process p = Runtime.getRuntime().exec("uname -m"); p.waitFor(); InputStream in = p.getInputStream(); try { int readLen = 0; ByteArrayOutputStream b = new ByteArrayOutputStream(); byte[] buf = new byte[32]; while((readLen = in.read(buf, 0, buf.length)) >= 0) { b.write(buf, 0, readLen); } return b.toString(); } finally { if(in != null) { in.close(); } } } catch(Throwable e) { System.err.println("Error while running uname -m: " + e.getMessage()); return "unknown"; } } static String resolveArmArchType() { if(System.getProperty("os.name").contains("Linux")) { String armType = getHardwareName(); // armType (uname -m) can be armv5t, armv5te, armv5tej, armv5tejl, armv6, armv7, armv7l, i686 if(armType.startsWith("armv6")) { // Raspberry PI return "armv6"; } else if(armType.startsWith("armv7")) { // Generic return "armv7"; } // Java 1.8 introduces a system property to determine armel or armhf // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8005545 String abi = System.getProperty("sun.arch.abi"); if(abi != null && abi.startsWith("gnueabihf")) { return "armv7"; } // For java7, we stil need to if run some shell commands to determine ABI of JVM try { // determine if first JVM found uses ARM hard-float ABI int exitCode = Runtime.getRuntime().exec("which readelf").waitFor(); if(exitCode == 0) { String javaHome = System.getProperty("java.home"); String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome + "' -name 'libjvm.so' | head -1 | xargs readelf -A | " + "grep 'Tag_ABI_VFP_args: VFP registers'"}; exitCode = Runtime.getRuntime().exec(cmdarray).waitFor(); if(exitCode == 0) { return "armv7"; } } else { System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " + "armel architecture will be presumed."); } } catch(IOException e) { // ignored: fall back to "arm" arch (soft-float ABI) } catch(InterruptedException e) { // ignored: fall back to "arm" arch (soft-float ABI) } } // Use armv5, soft-float ABI return "arm"; } public static String getArchName() { String osArch = System.getProperty("os.arch"); // For Android if(isAndroid()) { return "android-arm"; } if(osArch.startsWith("arm")) { osArch = resolveArmArchType(); } else { String lc = osArch.toLowerCase(Locale.US); if(archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); } static String translateOSNameToFolderName(String osName) { if(osName.contains("Windows")) { return "Windows"; } else if(osName.contains("Mac")) { return "Mac"; } else if(osName.contains("Linux")) { return "Linux"; } else if(osName.contains("AIX")) { return "AIX"; } else { return osName.replaceAll("\\W", ""); } } static String translateArchNameToFolderName(String archName) { return archName.replaceAll("\\W", ""); } }
xerial/snappy-java
src/main/java/org/xerial/snappy/OSInfo.java
2,444
// Needed for openjdk7 in Mac
line_comment
nl
/*-------------------------------------------------------------------------- * Copyright 2008 Taro L. Saito * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *--------------------------------------------------------------------------*/ //-------------------------------------- // snappy-java Project // // OSInfo.java // Since: May 20, 2008 // // $URL$ // $Author$ //-------------------------------------- package org.xerial.snappy; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Locale; /** * Provides OS name and architecture name. * * @author leo */ public class OSInfo { private static HashMap<String, String> archMapping = new HashMap<String, String>(); public static final String X86 = "x86"; public static final String X86_64 = "x86_64"; public static final String IA64_32 = "ia64_32"; public static final String IA64 = "ia64"; public static final String PPC = "ppc"; public static final String PPC64 = "ppc64"; public static final String IBMZ = "s390"; public static final String IBMZ_64 = "s390x"; public static final String AARCH_64 = "aarch64"; public static final String RISCV_64 = "riscv64"; public static final String LOONGARCH_64 = "loongarch64"; static { // x86 mappings archMapping.put(X86, X86); archMapping.put("i386", X86); archMapping.put("i486", X86); archMapping.put("i586", X86); archMapping.put("i686", X86); archMapping.put("pentium", X86); // x86_64 mappings archMapping.put(X86_64, X86_64); archMapping.put("amd64", X86_64); archMapping.put("em64t", X86_64); archMapping.put("universal", X86_64); // Needed for<SUF> // Itenium 64-bit mappings archMapping.put(IA64, IA64); archMapping.put("ia64w", IA64); // Itenium 32-bit mappings, usually an HP-UX construct archMapping.put(IA64_32, IA64_32); archMapping.put("ia64n", IA64_32); // PowerPC mappings archMapping.put(PPC, PPC); archMapping.put("power", PPC); archMapping.put("powerpc", PPC); archMapping.put("power_pc", PPC); archMapping.put("power_rs", PPC); // TODO: PowerPC 64bit mappings archMapping.put(PPC64, PPC64); archMapping.put("power64", PPC64); archMapping.put("powerpc64", PPC64); archMapping.put("power_pc64", PPC64); archMapping.put("power_rs64", PPC64); // IBM z mappings archMapping.put(IBMZ, IBMZ); // IBM z 64-bit mappings archMapping.put(IBMZ_64, IBMZ_64); // Aarch64 mappings archMapping.put(AARCH_64, AARCH_64); // RISC-V mappings archMapping.put(RISCV_64, RISCV_64); // LoongArch64 mappings archMapping.put(LOONGARCH_64, LOONGARCH_64); } public static void main(String[] args) { if(args.length >= 1) { if("--os".equals(args[0])) { System.out.print(getOSName()); return; } else if("--arch".equals(args[0])) { System.out.print(getArchName()); return; } } System.out.print(getNativeLibFolderPathForCurrentOS()); } public static String getNativeLibFolderPathForCurrentOS() { return getOSName() + "/" + getArchName(); } public static String getOSName() { return translateOSNameToFolderName(System.getProperty("os.name")); } public static boolean isAndroid() { return System.getProperty("java.runtime.name", "").toLowerCase().contains("android"); } static String getHardwareName() { try { Process p = Runtime.getRuntime().exec("uname -m"); p.waitFor(); InputStream in = p.getInputStream(); try { int readLen = 0; ByteArrayOutputStream b = new ByteArrayOutputStream(); byte[] buf = new byte[32]; while((readLen = in.read(buf, 0, buf.length)) >= 0) { b.write(buf, 0, readLen); } return b.toString(); } finally { if(in != null) { in.close(); } } } catch(Throwable e) { System.err.println("Error while running uname -m: " + e.getMessage()); return "unknown"; } } static String resolveArmArchType() { if(System.getProperty("os.name").contains("Linux")) { String armType = getHardwareName(); // armType (uname -m) can be armv5t, armv5te, armv5tej, armv5tejl, armv6, armv7, armv7l, i686 if(armType.startsWith("armv6")) { // Raspberry PI return "armv6"; } else if(armType.startsWith("armv7")) { // Generic return "armv7"; } // Java 1.8 introduces a system property to determine armel or armhf // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8005545 String abi = System.getProperty("sun.arch.abi"); if(abi != null && abi.startsWith("gnueabihf")) { return "armv7"; } // For java7, we stil need to if run some shell commands to determine ABI of JVM try { // determine if first JVM found uses ARM hard-float ABI int exitCode = Runtime.getRuntime().exec("which readelf").waitFor(); if(exitCode == 0) { String javaHome = System.getProperty("java.home"); String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome + "' -name 'libjvm.so' | head -1 | xargs readelf -A | " + "grep 'Tag_ABI_VFP_args: VFP registers'"}; exitCode = Runtime.getRuntime().exec(cmdarray).waitFor(); if(exitCode == 0) { return "armv7"; } } else { System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " + "armel architecture will be presumed."); } } catch(IOException e) { // ignored: fall back to "arm" arch (soft-float ABI) } catch(InterruptedException e) { // ignored: fall back to "arm" arch (soft-float ABI) } } // Use armv5, soft-float ABI return "arm"; } public static String getArchName() { String osArch = System.getProperty("os.arch"); // For Android if(isAndroid()) { return "android-arm"; } if(osArch.startsWith("arm")) { osArch = resolveArmArchType(); } else { String lc = osArch.toLowerCase(Locale.US); if(archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); } static String translateOSNameToFolderName(String osName) { if(osName.contains("Windows")) { return "Windows"; } else if(osName.contains("Mac")) { return "Mac"; } else if(osName.contains("Linux")) { return "Linux"; } else if(osName.contains("AIX")) { return "AIX"; } else { return osName.replaceAll("\\W", ""); } } static String translateArchNameToFolderName(String archName) { return archName.replaceAll("\\W", ""); } }
False
2,010
8
2,182
9
2,354
8
2,182
9
2,544
9
false
false
false
false
false
true
1,987
210472_0
package org.aion.zero.impl.config; import com.google.common.base.Objects; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import org.aion.log.AionLoggerFactory; import org.slf4j.Logger; public class CfgApiZmq { public static final String ZMQ_KEY_DIR = "zmq_keystore"; CfgApiZmq() { this.active = true; this.ip = "127.0.0.1"; this.port = 8547; this.filtersEnabled = true; this.blockSummaryCacheEnabled = false; this.secureConnectEnabled = false; } protected boolean active; protected String ip; protected int port; private boolean filtersEnabled; private boolean blockSummaryCacheEnabled; private boolean secureConnectEnabled; private static Logger LOG_GEN = AionLoggerFactory.getLogger("GEN"); public void fromXML(final XMLStreamReader sr) throws XMLStreamException { this.active = Boolean.parseBoolean(sr.getAttributeValue(null, "active")); this.ip = sr.getAttributeValue(null, "ip"); this.port = Integer.parseInt(sr.getAttributeValue(null, "port")); // get the nested elements loop: while (sr.hasNext()) { int eventType = sr.next(); switch (eventType) { case XMLStreamReader.START_ELEMENT: String elementName = sr.getLocalName().toLowerCase(); switch (elementName) { case "filters-enabled": try { filtersEnabled = Boolean.parseBoolean(ConfigUtil.readValue(sr)); } catch (Exception e) { LOG_GEN.warn( "failed to read config node: aion.api.zmq.filters-enabled; using preset: {}\n {}" + this.filtersEnabled, e); e.printStackTrace(); } break; case "block-summary-cache": try { blockSummaryCacheEnabled = Boolean.parseBoolean(ConfigUtil.readValue(sr)); } catch (Exception e) { LOG_GEN.warn( "failed to read config node: aion.api.zmq.block-summary-cache; using preset: {}\n {}", this.blockSummaryCacheEnabled, e); } break; case "secure-connect": try { secureConnectEnabled = Boolean.parseBoolean(ConfigUtil.readValue(sr)); } catch (Exception e) { LOG_GEN.warn( "failed to read config node: aion.api.zmq.secure-connect; using preset: {}\n {}" + this.secureConnectEnabled, e); } break; default: ConfigUtil.skipElement(sr); break; } break; case XMLStreamReader.END_ELEMENT: break loop; } } sr.next(); } String toXML() { final XMLOutputFactory output = XMLOutputFactory.newInstance(); output.setProperty("escapeCharacters", false); XMLStreamWriter xmlWriter; String xml; try { // <rpc active="false" ip="127.0.0.1" port="8545"/> Writer strWriter = new StringWriter(); xmlWriter = output.createXMLStreamWriter(strWriter); xmlWriter.writeCharacters("\r\n\t\t"); xmlWriter.writeStartElement("java"); xmlWriter.writeAttribute("active", this.active ? "true" : "false"); xmlWriter.writeAttribute("ip", this.ip); xmlWriter.writeAttribute("port", this.port + ""); xmlWriter.writeCharacters("\r\n\t\t\t"); xmlWriter.writeStartElement("secure-connect"); xmlWriter.writeCharacters(String.valueOf(this.secureConnectEnabled)); xmlWriter.writeEndElement(); xmlWriter.writeCharacters("\r\n\t\t"); xmlWriter.writeEndElement(); xml = strWriter.toString(); strWriter.flush(); strWriter.close(); xmlWriter.flush(); xmlWriter.close(); return xml; } catch (IOException | XMLStreamException e) { e.printStackTrace(); return ""; } } public void setActive(boolean active) { this.active = active; } public boolean getActive() { return this.active; } public String getIp() { return this.ip; } public int getPort() { return this.port; } public boolean isFiltersEnabled() { return this.filtersEnabled; } public boolean isBlockSummaryCacheEnabled() { return this.blockSummaryCacheEnabled; } public boolean isSecureConnectEnabledEnabled() { return this.secureConnectEnabled; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CfgApiZmq cfgApiZmq = (CfgApiZmq) o; return active == cfgApiZmq.active && port == cfgApiZmq.port && filtersEnabled == cfgApiZmq.filtersEnabled && blockSummaryCacheEnabled == cfgApiZmq.blockSummaryCacheEnabled && secureConnectEnabled == cfgApiZmq.secureConnectEnabled && Objects.equal(ip, cfgApiZmq.ip); } @Override public int hashCode() { return Objects.hashCode( active, ip, port, filtersEnabled, blockSummaryCacheEnabled, secureConnectEnabled); } }
aionnetwork/aion
modAionImpl/src/org/aion/zero/impl/config/CfgApiZmq.java
1,641
// get the nested elements
line_comment
nl
package org.aion.zero.impl.config; import com.google.common.base.Objects; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import org.aion.log.AionLoggerFactory; import org.slf4j.Logger; public class CfgApiZmq { public static final String ZMQ_KEY_DIR = "zmq_keystore"; CfgApiZmq() { this.active = true; this.ip = "127.0.0.1"; this.port = 8547; this.filtersEnabled = true; this.blockSummaryCacheEnabled = false; this.secureConnectEnabled = false; } protected boolean active; protected String ip; protected int port; private boolean filtersEnabled; private boolean blockSummaryCacheEnabled; private boolean secureConnectEnabled; private static Logger LOG_GEN = AionLoggerFactory.getLogger("GEN"); public void fromXML(final XMLStreamReader sr) throws XMLStreamException { this.active = Boolean.parseBoolean(sr.getAttributeValue(null, "active")); this.ip = sr.getAttributeValue(null, "ip"); this.port = Integer.parseInt(sr.getAttributeValue(null, "port")); // get the<SUF> loop: while (sr.hasNext()) { int eventType = sr.next(); switch (eventType) { case XMLStreamReader.START_ELEMENT: String elementName = sr.getLocalName().toLowerCase(); switch (elementName) { case "filters-enabled": try { filtersEnabled = Boolean.parseBoolean(ConfigUtil.readValue(sr)); } catch (Exception e) { LOG_GEN.warn( "failed to read config node: aion.api.zmq.filters-enabled; using preset: {}\n {}" + this.filtersEnabled, e); e.printStackTrace(); } break; case "block-summary-cache": try { blockSummaryCacheEnabled = Boolean.parseBoolean(ConfigUtil.readValue(sr)); } catch (Exception e) { LOG_GEN.warn( "failed to read config node: aion.api.zmq.block-summary-cache; using preset: {}\n {}", this.blockSummaryCacheEnabled, e); } break; case "secure-connect": try { secureConnectEnabled = Boolean.parseBoolean(ConfigUtil.readValue(sr)); } catch (Exception e) { LOG_GEN.warn( "failed to read config node: aion.api.zmq.secure-connect; using preset: {}\n {}" + this.secureConnectEnabled, e); } break; default: ConfigUtil.skipElement(sr); break; } break; case XMLStreamReader.END_ELEMENT: break loop; } } sr.next(); } String toXML() { final XMLOutputFactory output = XMLOutputFactory.newInstance(); output.setProperty("escapeCharacters", false); XMLStreamWriter xmlWriter; String xml; try { // <rpc active="false" ip="127.0.0.1" port="8545"/> Writer strWriter = new StringWriter(); xmlWriter = output.createXMLStreamWriter(strWriter); xmlWriter.writeCharacters("\r\n\t\t"); xmlWriter.writeStartElement("java"); xmlWriter.writeAttribute("active", this.active ? "true" : "false"); xmlWriter.writeAttribute("ip", this.ip); xmlWriter.writeAttribute("port", this.port + ""); xmlWriter.writeCharacters("\r\n\t\t\t"); xmlWriter.writeStartElement("secure-connect"); xmlWriter.writeCharacters(String.valueOf(this.secureConnectEnabled)); xmlWriter.writeEndElement(); xmlWriter.writeCharacters("\r\n\t\t"); xmlWriter.writeEndElement(); xml = strWriter.toString(); strWriter.flush(); strWriter.close(); xmlWriter.flush(); xmlWriter.close(); return xml; } catch (IOException | XMLStreamException e) { e.printStackTrace(); return ""; } } public void setActive(boolean active) { this.active = active; } public boolean getActive() { return this.active; } public String getIp() { return this.ip; } public int getPort() { return this.port; } public boolean isFiltersEnabled() { return this.filtersEnabled; } public boolean isBlockSummaryCacheEnabled() { return this.blockSummaryCacheEnabled; } public boolean isSecureConnectEnabledEnabled() { return this.secureConnectEnabled; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CfgApiZmq cfgApiZmq = (CfgApiZmq) o; return active == cfgApiZmq.active && port == cfgApiZmq.port && filtersEnabled == cfgApiZmq.filtersEnabled && blockSummaryCacheEnabled == cfgApiZmq.blockSummaryCacheEnabled && secureConnectEnabled == cfgApiZmq.secureConnectEnabled && Objects.equal(ip, cfgApiZmq.ip); } @Override public int hashCode() { return Objects.hashCode( active, ip, port, filtersEnabled, blockSummaryCacheEnabled, secureConnectEnabled); } }
False
1,144
5
1,310
5
1,439
5
1,310
5
1,574
5
false
false
false
false
false
true
587
19753_4
/*_x000D_ * To change this template, choose Tools | Templates_x000D_ * and open the template in the editor._x000D_ */_x000D_ // https://netbeans.org/kb/docs/web/hibernate-webapp.html_x000D_ package Hibernate;_x000D_ _x000D_ import java.util.List;_x000D_ import javax.faces.bean.ManagedBean;_x000D_ import javax.faces.bean.SessionScoped;_x000D_ import javax.faces.model.DataModel;_x000D_ import javax.faces.model.ListDataModel;_x000D_ _x000D_ /**_x000D_ *_x000D_ * @author Eusebius_x000D_ */_x000D_ @ManagedBean_x000D_ @SessionScoped_x000D_ public class festivalManagedBean {_x000D_ _x000D_ /**_x000D_ * Creates a new instance of festivalManagedBean_x000D_ */_x000D_ _x000D_ int startId;_x000D_ int endId;_x000D_ DataModel festivalNames;_x000D_ festivalHelper helper;_x000D_ private int recordCount = 2;_x000D_ private int pageSize = 10;_x000D_ _x000D_ private Festivals current;_x000D_ private int selectedItemIndex;_x000D_ _x000D_ public festivalManagedBean() {_x000D_ helper = new festivalHelper();_x000D_ startId = 1;_x000D_ endId = 10;_x000D_ }_x000D_ _x000D_ public festivalManagedBean(int startId, int endId) {_x000D_ helper = new festivalHelper();_x000D_ this.startId = startId;_x000D_ this.endId = endId;_x000D_ }_x000D_ _x000D_ public Festivals getSelected() {_x000D_ if (current == null) {_x000D_ current = new Festivals();_x000D_ selectedItemIndex = -1;_x000D_ }_x000D_ return current;_x000D_ }_x000D_ _x000D_ _x000D_ public DataModel getFestivalNames() {_x000D_ if (festivalNames == null) {_x000D_ festivalNames = new ListDataModel(helper.getFestivalNames(startId, endId));_x000D_ }_x000D_ return festivalNames;_x000D_ }_x000D_ _x000D_ void recreateModel() {_x000D_ festivalNames = null;_x000D_ }_x000D_ _x000D_ public boolean isHasNextPage() {_x000D_ if (endId + pageSize <= recordCount) {_x000D_ return true;_x000D_ }_x000D_ return false;_x000D_ }_x000D_ _x000D_ public boolean isHasPreviousPage() {_x000D_ if (startId-pageSize > 0) {_x000D_ return true;_x000D_ }_x000D_ return false;_x000D_ }_x000D_ _x000D_ public String next() {_x000D_ startId = endId+1;_x000D_ endId = endId + pageSize;_x000D_ recreateModel();_x000D_ return "index";_x000D_ }_x000D_ _x000D_ public String previous() {_x000D_ startId = startId - pageSize;_x000D_ endId = endId - pageSize;_x000D_ recreateModel();_x000D_ return "index";_x000D_ }_x000D_ _x000D_ public int getPageSize() {_x000D_ return pageSize;_x000D_ }_x000D_ _x000D_ public String prepareView(){_x000D_ current = (Festivals) getFestivalNames().getRowData();_x000D_ return "browse";_x000D_ }_x000D_ public String prepareList(){_x000D_ recreateModel();_x000D_ return "index";_x000D_ }_x000D_ // alle bands van een bepaald festival ophalen en achter elkaar zetten_x000D_ public String getBands() {_x000D_ List bands = helper.getBandsByID(current.getFestId());_x000D_ StringBuilder totalLineUp = new StringBuilder();_x000D_ for (int i = 0; i < bands.size(); i++) {_x000D_ Bands band = (Bands) bands.get(i);_x000D_ totalLineUp.append(band.getBandNaam());_x000D_ totalLineUp.append(" : ");_x000D_ totalLineUp.append(band.getBandSoortMuziek());_x000D_ totalLineUp.append("; ");_x000D_ }_x000D_ return totalLineUp.toString();_x000D_ }_x000D_ // alle tickets en hun prijs van een bepaald festival ophalen en achter elkaar zetten_x000D_ public String getTicketypes() {_x000D_ List tickets = helper.getTicketsByID(current.getFestId());_x000D_ StringBuilder totalTickets = new StringBuilder();_x000D_ for (int i = 0; i < tickets.size(); i++) {_x000D_ Tickettypes ticket = (Tickettypes) tickets.get(i);_x000D_ totalTickets.append(ticket.getTypOmschr());_x000D_ totalTickets.append(" : €");_x000D_ totalTickets.append(ticket.getTypPrijs().toString());_x000D_ totalTickets.append("; ");_x000D_ }_x000D_ return totalTickets.toString();_x000D_ }_x000D_ }_x000D_
GeintegreerdProjectGroep16/ProjectDeel2
src/java/Hibernate/festivalManagedBean.java
1,089
// alle tickets en hun prijs van een bepaald festival ophalen en achter elkaar zetten_x000D_
line_comment
nl
/*_x000D_ * To change this template, choose Tools | Templates_x000D_ * and open the template in the editor._x000D_ */_x000D_ // https://netbeans.org/kb/docs/web/hibernate-webapp.html_x000D_ package Hibernate;_x000D_ _x000D_ import java.util.List;_x000D_ import javax.faces.bean.ManagedBean;_x000D_ import javax.faces.bean.SessionScoped;_x000D_ import javax.faces.model.DataModel;_x000D_ import javax.faces.model.ListDataModel;_x000D_ _x000D_ /**_x000D_ *_x000D_ * @author Eusebius_x000D_ */_x000D_ @ManagedBean_x000D_ @SessionScoped_x000D_ public class festivalManagedBean {_x000D_ _x000D_ /**_x000D_ * Creates a new instance of festivalManagedBean_x000D_ */_x000D_ _x000D_ int startId;_x000D_ int endId;_x000D_ DataModel festivalNames;_x000D_ festivalHelper helper;_x000D_ private int recordCount = 2;_x000D_ private int pageSize = 10;_x000D_ _x000D_ private Festivals current;_x000D_ private int selectedItemIndex;_x000D_ _x000D_ public festivalManagedBean() {_x000D_ helper = new festivalHelper();_x000D_ startId = 1;_x000D_ endId = 10;_x000D_ }_x000D_ _x000D_ public festivalManagedBean(int startId, int endId) {_x000D_ helper = new festivalHelper();_x000D_ this.startId = startId;_x000D_ this.endId = endId;_x000D_ }_x000D_ _x000D_ public Festivals getSelected() {_x000D_ if (current == null) {_x000D_ current = new Festivals();_x000D_ selectedItemIndex = -1;_x000D_ }_x000D_ return current;_x000D_ }_x000D_ _x000D_ _x000D_ public DataModel getFestivalNames() {_x000D_ if (festivalNames == null) {_x000D_ festivalNames = new ListDataModel(helper.getFestivalNames(startId, endId));_x000D_ }_x000D_ return festivalNames;_x000D_ }_x000D_ _x000D_ void recreateModel() {_x000D_ festivalNames = null;_x000D_ }_x000D_ _x000D_ public boolean isHasNextPage() {_x000D_ if (endId + pageSize <= recordCount) {_x000D_ return true;_x000D_ }_x000D_ return false;_x000D_ }_x000D_ _x000D_ public boolean isHasPreviousPage() {_x000D_ if (startId-pageSize > 0) {_x000D_ return true;_x000D_ }_x000D_ return false;_x000D_ }_x000D_ _x000D_ public String next() {_x000D_ startId = endId+1;_x000D_ endId = endId + pageSize;_x000D_ recreateModel();_x000D_ return "index";_x000D_ }_x000D_ _x000D_ public String previous() {_x000D_ startId = startId - pageSize;_x000D_ endId = endId - pageSize;_x000D_ recreateModel();_x000D_ return "index";_x000D_ }_x000D_ _x000D_ public int getPageSize() {_x000D_ return pageSize;_x000D_ }_x000D_ _x000D_ public String prepareView(){_x000D_ current = (Festivals) getFestivalNames().getRowData();_x000D_ return "browse";_x000D_ }_x000D_ public String prepareList(){_x000D_ recreateModel();_x000D_ return "index";_x000D_ }_x000D_ // alle bands van een bepaald festival ophalen en achter elkaar zetten_x000D_ public String getBands() {_x000D_ List bands = helper.getBandsByID(current.getFestId());_x000D_ StringBuilder totalLineUp = new StringBuilder();_x000D_ for (int i = 0; i < bands.size(); i++) {_x000D_ Bands band = (Bands) bands.get(i);_x000D_ totalLineUp.append(band.getBandNaam());_x000D_ totalLineUp.append(" : ");_x000D_ totalLineUp.append(band.getBandSoortMuziek());_x000D_ totalLineUp.append("; ");_x000D_ }_x000D_ return totalLineUp.toString();_x000D_ }_x000D_ // alle tickets<SUF> public String getTicketypes() {_x000D_ List tickets = helper.getTicketsByID(current.getFestId());_x000D_ StringBuilder totalTickets = new StringBuilder();_x000D_ for (int i = 0; i < tickets.size(); i++) {_x000D_ Tickettypes ticket = (Tickettypes) tickets.get(i);_x000D_ totalTickets.append(ticket.getTypOmschr());_x000D_ totalTickets.append(" : €");_x000D_ totalTickets.append(ticket.getTypPrijs().toString());_x000D_ totalTickets.append("; ");_x000D_ }_x000D_ return totalTickets.toString();_x000D_ }_x000D_ }_x000D_
True
1,686
27
1,791
35
1,835
23
1,791
35
1,973
31
false
false
false
false
false
true
2,346
137928_15
/****************************************************************************** * Compilation: javac Quick.java * Execution: java Quick < input.txt * Dependencies: StdOut.java StdIn.java * Data files: https://algs4.cs.princeton.edu/23quicksort/tiny.txt * https://algs4.cs.princeton.edu/23quicksort/words3.txt * * Sorts a sequence of strings from standard input using quicksort. * * % more tiny.txt * S O R T E X A M P L E * * % java Quick < tiny.txt * A E E L M O P R S T X [ one string per line ] * * % more words3.txt * bed bug dad yes zoo ... all bad yet * * % java Quick < words3.txt * all bad bed bug dad ... yes yet zoo [ one string per line ] * * * Remark: For a type-safe version that uses static generics, see * * https://algs4.cs.princeton.edu/23quicksort/QuickPedantic.java * ******************************************************************************/ package edu.princeton.cs.algs4; /** * The {@code Quick} class provides static methods for sorting an * array and selecting the ith smallest element in an array using quicksort. * <p> * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/23quicksort">Section 2.3</a> * of <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Quick { // This class should not be instantiated. private Quick() { } /** * Rearranges the array in ascending order, using the natural order. * @param a the array to be sorted */ public static void sort(Comparable[] a) { StdRandom.shuffle(a); sort(a, 0, a.length - 1); assert isSorted(a); } // quicksort the subarray from a[lo] to a[hi] private static void sort(Comparable[] a, int lo, int hi) { if (hi <= lo) return; int j = partition(a, lo, hi); sort(a, lo, j-1); sort(a, j+1, hi); assert isSorted(a, lo, hi); } // partition the subarray a[lo..hi] so that a[lo..j-1] <= a[j] <= a[j+1..hi] // and return the index j. private static int partition(Comparable[] a, int lo, int hi) { int i = lo; int j = hi + 1; Comparable v = a[lo]; while (true) { // find item on lo to swap while (less(a[++i], v)) { if (i == hi) break; } // find item on hi to swap while (less(v, a[--j])) { if (j == lo) break; // redundant since a[lo] acts as sentinel } // check if pointers cross if (i >= j) break; exch(a, i, j); } // put partitioning item v at a[j] exch(a, lo, j); // now, a[lo .. j-1] <= a[j] <= a[j+1 .. hi] return j; } /** * Rearranges the array so that {@code a[k]} contains the kth smallest key; * {@code a[0]} through {@code a[k-1]} are less than (or equal to) {@code a[k]}; and * {@code a[k+1]} through {@code a[n-1]} are greater than (or equal to) {@code a[k]}. * * @param a the array * @param k the rank of the key * @return the key of rank {@code k} * @throws IllegalArgumentException unless {@code 0 <= k < a.length} */ public static Comparable select(Comparable[] a, int k) { if (k < 0 || k >= a.length) { throw new IllegalArgumentException("index is not between 0 and " + a.length + ": " + k); } StdRandom.shuffle(a); int lo = 0, hi = a.length - 1; while (hi > lo) { int i = partition(a, lo, hi); if (i > k) hi = i - 1; else if (i < k) lo = i + 1; else return a[i]; } return a[lo]; } /*************************************************************************** * Helper sorting functions. ***************************************************************************/ // is v < w ? private static boolean less(Comparable v, Comparable w) { if (v == w) return false; // optimization when reference equals return v.compareTo(w) < 0; } // exchange a[i] and a[j] private static void exch(Object[] a, int i, int j) { Object swap = a[i]; a[i] = a[j]; a[j] = swap; } /*************************************************************************** * Check if array is sorted - useful for debugging. ***************************************************************************/ private static boolean isSorted(Comparable[] a) { return isSorted(a, 0, a.length - 1); } private static boolean isSorted(Comparable[] a, int lo, int hi) { for (int i = lo + 1; i <= hi; i++) if (less(a[i], a[i-1])) return false; return true; } // print array to standard output private static void show(Comparable[] a) { for (int i = 0; i < a.length; i++) { StdOut.println(a[i]); } } /** * Reads in a sequence of strings from standard input; quicksorts them; * and prints them to standard output in ascending order. * Shuffles the array and then prints the strings again to * standard output, but this time, using the select method. * * @param args the command-line arguments */ public static void main(String[] args) { String[] a = StdIn.readAllStrings(); Quick.sort(a); show(a); assert isSorted(a); // shuffle StdRandom.shuffle(a); // display results again using select StdOut.println(); for (int i = 0; i < a.length; i++) { String ith = (String) Quick.select(a, i); StdOut.println(ith); } } } /****************************************************************************** * Copyright 2002-2022, Robert Sedgewick and Kevin Wayne. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * * algs4.jar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * algs4.jar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/
cchampio/algs4
src/main/java/edu/princeton/cs/algs4/Quick.java
2,149
// is v < w ?
line_comment
nl
/****************************************************************************** * Compilation: javac Quick.java * Execution: java Quick < input.txt * Dependencies: StdOut.java StdIn.java * Data files: https://algs4.cs.princeton.edu/23quicksort/tiny.txt * https://algs4.cs.princeton.edu/23quicksort/words3.txt * * Sorts a sequence of strings from standard input using quicksort. * * % more tiny.txt * S O R T E X A M P L E * * % java Quick < tiny.txt * A E E L M O P R S T X [ one string per line ] * * % more words3.txt * bed bug dad yes zoo ... all bad yet * * % java Quick < words3.txt * all bad bed bug dad ... yes yet zoo [ one string per line ] * * * Remark: For a type-safe version that uses static generics, see * * https://algs4.cs.princeton.edu/23quicksort/QuickPedantic.java * ******************************************************************************/ package edu.princeton.cs.algs4; /** * The {@code Quick} class provides static methods for sorting an * array and selecting the ith smallest element in an array using quicksort. * <p> * For additional documentation, see * <a href="https://algs4.cs.princeton.edu/23quicksort">Section 2.3</a> * of <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Quick { // This class should not be instantiated. private Quick() { } /** * Rearranges the array in ascending order, using the natural order. * @param a the array to be sorted */ public static void sort(Comparable[] a) { StdRandom.shuffle(a); sort(a, 0, a.length - 1); assert isSorted(a); } // quicksort the subarray from a[lo] to a[hi] private static void sort(Comparable[] a, int lo, int hi) { if (hi <= lo) return; int j = partition(a, lo, hi); sort(a, lo, j-1); sort(a, j+1, hi); assert isSorted(a, lo, hi); } // partition the subarray a[lo..hi] so that a[lo..j-1] <= a[j] <= a[j+1..hi] // and return the index j. private static int partition(Comparable[] a, int lo, int hi) { int i = lo; int j = hi + 1; Comparable v = a[lo]; while (true) { // find item on lo to swap while (less(a[++i], v)) { if (i == hi) break; } // find item on hi to swap while (less(v, a[--j])) { if (j == lo) break; // redundant since a[lo] acts as sentinel } // check if pointers cross if (i >= j) break; exch(a, i, j); } // put partitioning item v at a[j] exch(a, lo, j); // now, a[lo .. j-1] <= a[j] <= a[j+1 .. hi] return j; } /** * Rearranges the array so that {@code a[k]} contains the kth smallest key; * {@code a[0]} through {@code a[k-1]} are less than (or equal to) {@code a[k]}; and * {@code a[k+1]} through {@code a[n-1]} are greater than (or equal to) {@code a[k]}. * * @param a the array * @param k the rank of the key * @return the key of rank {@code k} * @throws IllegalArgumentException unless {@code 0 <= k < a.length} */ public static Comparable select(Comparable[] a, int k) { if (k < 0 || k >= a.length) { throw new IllegalArgumentException("index is not between 0 and " + a.length + ": " + k); } StdRandom.shuffle(a); int lo = 0, hi = a.length - 1; while (hi > lo) { int i = partition(a, lo, hi); if (i > k) hi = i - 1; else if (i < k) lo = i + 1; else return a[i]; } return a[lo]; } /*************************************************************************** * Helper sorting functions. ***************************************************************************/ // is v<SUF> private static boolean less(Comparable v, Comparable w) { if (v == w) return false; // optimization when reference equals return v.compareTo(w) < 0; } // exchange a[i] and a[j] private static void exch(Object[] a, int i, int j) { Object swap = a[i]; a[i] = a[j]; a[j] = swap; } /*************************************************************************** * Check if array is sorted - useful for debugging. ***************************************************************************/ private static boolean isSorted(Comparable[] a) { return isSorted(a, 0, a.length - 1); } private static boolean isSorted(Comparable[] a, int lo, int hi) { for (int i = lo + 1; i <= hi; i++) if (less(a[i], a[i-1])) return false; return true; } // print array to standard output private static void show(Comparable[] a) { for (int i = 0; i < a.length; i++) { StdOut.println(a[i]); } } /** * Reads in a sequence of strings from standard input; quicksorts them; * and prints them to standard output in ascending order. * Shuffles the array and then prints the strings again to * standard output, but this time, using the select method. * * @param args the command-line arguments */ public static void main(String[] args) { String[] a = StdIn.readAllStrings(); Quick.sort(a); show(a); assert isSorted(a); // shuffle StdRandom.shuffle(a); // display results again using select StdOut.println(); for (int i = 0; i < a.length; i++) { String ith = (String) Quick.select(a, i); StdOut.println(ith); } } } /****************************************************************************** * Copyright 2002-2022, Robert Sedgewick and Kevin Wayne. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * * algs4.jar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * algs4.jar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/
False
1,752
6
1,914
6
2,027
6
1,914
6
2,189
6
false
false
false
false
false
true
2,139
111368_6
/* * Firebird Open Source JavaEE Connector - JDBC Driver * * Distributable under LGPL license. * You may obtain a copy of the License at http://www.gnu.org/copyleft/lgpl.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * LGPL License for more details. * * This file was created by members of the firebird development team. * All individual contributions remain the Copyright (C) of those * individuals. Contributors to this file are either listed here or * can be obtained from a source control history command. * * All rights reserved. */ package org.firebirdsql.jdbc.field; import org.firebirdsql.gds.ng.fields.FieldDescriptor; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.sql.Date; import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; /** * FBField implementation for NULL fields (eg in condition ? IS NULL). * * @author <a href="mailto:[email protected]">Mark Rotteveel</a> */ final class FBNullField extends FBField { private static final String NULL_CONVERSION_ERROR = "Received non-NULL value of a NULL field."; private static final byte[] DUMMY_OBJECT = new byte[0]; FBNullField(FieldDescriptor fieldDescriptor, FieldDataProvider dataProvider, int requiredType) throws SQLException { super(fieldDescriptor, dataProvider, requiredType); } @Override public Object getObject() throws SQLException { checkNull(); return null; } @Override public void setObject(Object value) throws SQLException { if (value == null) setNull(); else setDummyObject(); } // TODO set/getClob and set/getBlob are missing, relevant to add? private void setDummyObject() { setFieldData(DUMMY_OBJECT); } private void checkNull() throws SQLException { if (isNull()) { throw new TypeConversionException(NULL_CONVERSION_ERROR); } } // ----- Math code public byte getByte() throws SQLException { checkNull(); return BYTE_NULL_VALUE; } public short getShort() throws SQLException { checkNull(); return SHORT_NULL_VALUE; } public int getInt() throws SQLException { checkNull(); return INT_NULL_VALUE; } public long getLong() throws SQLException { checkNull(); return LONG_NULL_VALUE; } public BigDecimal getBigDecimal() throws SQLException { checkNull(); return null; } public float getFloat() throws SQLException { checkNull(); return FLOAT_NULL_VALUE; } public double getDouble() throws SQLException { checkNull(); return DOUBLE_NULL_VALUE; } // ----- getBoolean, getString and getObject code public boolean getBoolean() throws SQLException { checkNull(); return BOOLEAN_NULL_VALUE; } public String getString() throws SQLException { checkNull(); return null; } // ----- getXXXStream code public InputStream getBinaryStream() throws SQLException { checkNull(); return null; } public byte[] getBytes() throws SQLException { checkNull(); return null; } // ----- getDate, getTime and getTimestamp code public Date getDate(Calendar cal) throws SQLException { checkNull(); return null; } public Date getDate() throws SQLException { checkNull(); return null; } public Time getTime(Calendar cal) throws SQLException { checkNull(); return null; } public Time getTime() throws SQLException { checkNull(); return null; } public Timestamp getTimestamp(Calendar cal) throws SQLException { checkNull(); return null; } public Timestamp getTimestamp() throws SQLException { checkNull(); return null; } // --- setXXX methods public void setByte(byte value) throws SQLException { setDummyObject(); } public void setShort(short value) throws SQLException { setDummyObject(); } public void setInteger(int value) throws SQLException { setDummyObject(); } public void setLong(long value) throws SQLException { setDummyObject(); } public void setFloat(float value) throws SQLException { setDummyObject(); } public void setDouble(double value) throws SQLException { setDummyObject(); } public void setBigDecimal(BigDecimal value) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } // ----- setBoolean, setObject and setObject code public void setBoolean(boolean value) throws SQLException { setDummyObject(); } // ----- setXXXStream code @Override protected void setBinaryStreamInternal(InputStream in, long length) throws SQLException { if (in == null) { setNull(); return; } // TODO Do we need to consume and/or close streams? setDummyObject(); } @Override protected void setCharacterStreamInternal(Reader in, long length) throws SQLException { if (in == null) { setNull(); return; } // TODO Do we need to consume and/or close streams? setDummyObject(); } public void setBytes(byte[] value) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } // ----- setDate, setTime and setTimestamp code public void setDate(Date value, Calendar cal) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } public void setDate(Date value) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } public void setTime(Time value, Calendar cal) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } public void setTime(Time value) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } public void setTimestamp(Timestamp value, Calendar cal) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } public void setTimestamp(Timestamp value) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } @Override public void setString(String value) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } }
asfernandes/jaybird
src/main/org/firebirdsql/jdbc/field/FBNullField.java
2,006
// ----- getDate, getTime and getTimestamp code
line_comment
nl
/* * Firebird Open Source JavaEE Connector - JDBC Driver * * Distributable under LGPL license. * You may obtain a copy of the License at http://www.gnu.org/copyleft/lgpl.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * LGPL License for more details. * * This file was created by members of the firebird development team. * All individual contributions remain the Copyright (C) of those * individuals. Contributors to this file are either listed here or * can be obtained from a source control history command. * * All rights reserved. */ package org.firebirdsql.jdbc.field; import org.firebirdsql.gds.ng.fields.FieldDescriptor; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.sql.Date; import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; /** * FBField implementation for NULL fields (eg in condition ? IS NULL). * * @author <a href="mailto:[email protected]">Mark Rotteveel</a> */ final class FBNullField extends FBField { private static final String NULL_CONVERSION_ERROR = "Received non-NULL value of a NULL field."; private static final byte[] DUMMY_OBJECT = new byte[0]; FBNullField(FieldDescriptor fieldDescriptor, FieldDataProvider dataProvider, int requiredType) throws SQLException { super(fieldDescriptor, dataProvider, requiredType); } @Override public Object getObject() throws SQLException { checkNull(); return null; } @Override public void setObject(Object value) throws SQLException { if (value == null) setNull(); else setDummyObject(); } // TODO set/getClob and set/getBlob are missing, relevant to add? private void setDummyObject() { setFieldData(DUMMY_OBJECT); } private void checkNull() throws SQLException { if (isNull()) { throw new TypeConversionException(NULL_CONVERSION_ERROR); } } // ----- Math code public byte getByte() throws SQLException { checkNull(); return BYTE_NULL_VALUE; } public short getShort() throws SQLException { checkNull(); return SHORT_NULL_VALUE; } public int getInt() throws SQLException { checkNull(); return INT_NULL_VALUE; } public long getLong() throws SQLException { checkNull(); return LONG_NULL_VALUE; } public BigDecimal getBigDecimal() throws SQLException { checkNull(); return null; } public float getFloat() throws SQLException { checkNull(); return FLOAT_NULL_VALUE; } public double getDouble() throws SQLException { checkNull(); return DOUBLE_NULL_VALUE; } // ----- getBoolean, getString and getObject code public boolean getBoolean() throws SQLException { checkNull(); return BOOLEAN_NULL_VALUE; } public String getString() throws SQLException { checkNull(); return null; } // ----- getXXXStream code public InputStream getBinaryStream() throws SQLException { checkNull(); return null; } public byte[] getBytes() throws SQLException { checkNull(); return null; } // ----- getDate,<SUF> public Date getDate(Calendar cal) throws SQLException { checkNull(); return null; } public Date getDate() throws SQLException { checkNull(); return null; } public Time getTime(Calendar cal) throws SQLException { checkNull(); return null; } public Time getTime() throws SQLException { checkNull(); return null; } public Timestamp getTimestamp(Calendar cal) throws SQLException { checkNull(); return null; } public Timestamp getTimestamp() throws SQLException { checkNull(); return null; } // --- setXXX methods public void setByte(byte value) throws SQLException { setDummyObject(); } public void setShort(short value) throws SQLException { setDummyObject(); } public void setInteger(int value) throws SQLException { setDummyObject(); } public void setLong(long value) throws SQLException { setDummyObject(); } public void setFloat(float value) throws SQLException { setDummyObject(); } public void setDouble(double value) throws SQLException { setDummyObject(); } public void setBigDecimal(BigDecimal value) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } // ----- setBoolean, setObject and setObject code public void setBoolean(boolean value) throws SQLException { setDummyObject(); } // ----- setXXXStream code @Override protected void setBinaryStreamInternal(InputStream in, long length) throws SQLException { if (in == null) { setNull(); return; } // TODO Do we need to consume and/or close streams? setDummyObject(); } @Override protected void setCharacterStreamInternal(Reader in, long length) throws SQLException { if (in == null) { setNull(); return; } // TODO Do we need to consume and/or close streams? setDummyObject(); } public void setBytes(byte[] value) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } // ----- setDate, setTime and setTimestamp code public void setDate(Date value, Calendar cal) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } public void setDate(Date value) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } public void setTime(Time value, Calendar cal) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } public void setTime(Time value) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } public void setTimestamp(Timestamp value, Calendar cal) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } public void setTimestamp(Timestamp value) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } @Override public void setString(String value) throws SQLException { if (value == null) { setNull(); return; } setDummyObject(); } }
False
1,435
9
1,545
10
1,730
9
1,545
10
1,944
12
false
false
false
false
false
true