index
int64
1
4.82k
file_id
stringlengths
6
10
content
stringlengths
233
30k
repo
stringlengths
7
108
path
stringlengths
8
133
token_length
int64
72
8.17k
original_comment
stringlengths
13
2.72k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
142
29.9k
Inclusion
stringclasses
1 value
Exclusion
stringclasses
1 value
__index_level_0__
int64
1
2.15k
1,030
172967_3
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hellotvxlet; import org.havi.ui.*; import java.awt.*; import org.dvb.ui.*; /** * * @author student */ public class Sprite extends HComponent { private Image spaceship; private MediaTracker mtrack; //plaats en lovatie instellen in de constructor public Sprite(String file, int x, int y) { spaceship = this.getToolkit().getImage(file); mtrack = new MediaTracker(this); mtrack.addImage(spaceship, 0); try { mtrack.waitForAll(); // wacht tot alle bitmaps geladen zijn } catch (InterruptedException ex) { ex.printStackTrace(); } this.setBounds(x, y, spaceship.getWidth(null), spaceship.getHeight(null)); //opgeven plaats en afmetingen bitmap } //paint methode overschrijven public void paint(Graphics g) { g.drawImage(spaceship, 0, 0, null); } public void Verplaats(int x, int y) { this.setBounds(x, y, spaceship.getWidth(this), spaceship.getHeight(this)); } }
MTA-Digital-Broadcast-2/K-De-Maeyer-Didier-Schuddinck-Sam-Project-MHP
Didier De Maeyer/blz47/Oef1/HelloTVXlet/src/hellotvxlet/Sprite.java
367
// wacht tot alle bitmaps geladen zijn
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hellotvxlet; import org.havi.ui.*; import java.awt.*; import org.dvb.ui.*; /** * * @author student */ public class Sprite extends HComponent { private Image spaceship; private MediaTracker mtrack; //plaats en lovatie instellen in de constructor public Sprite(String file, int x, int y) { spaceship = this.getToolkit().getImage(file); mtrack = new MediaTracker(this); mtrack.addImage(spaceship, 0); try { mtrack.waitForAll(); // wacht tot<SUF> } catch (InterruptedException ex) { ex.printStackTrace(); } this.setBounds(x, y, spaceship.getWidth(null), spaceship.getHeight(null)); //opgeven plaats en afmetingen bitmap } //paint methode overschrijven public void paint(Graphics g) { g.drawImage(spaceship, 0, 0, null); } public void Verplaats(int x, int y) { this.setBounds(x, y, spaceship.getWidth(this), spaceship.getHeight(this)); } }
True
False
1
600
11641_4
import java.util.ArrayList;_x000D_ _x000D_ /**_x000D_ * Presentation houdt de slides in de presentatie bij._x000D_ * <p>_x000D_ * In the Presentation's world, page numbers go from 0 to n-1 * <p>_x000D_ * This program is distributed under the terms of the accompanying_x000D_ * COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_ * Please read it. Your use of the software constitutes acceptance_x000D_ * of the terms in the COPYRIGHT.txt file._x000D_ * @author Ian F. Darwin, ian@darwinsys.com_x000D_ * @version $Id: Presentation.java,v 1.1 2002/12/17 Gert Florijn_x000D_ * @version $Id: Presentation.java,v 1.2 2003/11/19 Sylvia Stuurman_x000D_ * @version $Id: Presentation.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_ * @version $Id: Presentation.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_ */_x000D_ _x000D_ // Verandering: Presentation wordt een Observable_x000D_ public class Presentation {_x000D_ private String showTitle; // de titel van de presentatie_x000D_ private ArrayList<Slide> showList = null; // een ArrayList met de Slides_x000D_ private int currentSlideNumber = 0; // het slidenummer van de huidige Slide_x000D_ // Verandering: we kennen slideViewComponent niet meer direct_x000D_ // private SlideViewerComponent slideViewComponent = null; // de viewcomponent voor de Slides_x000D_ _x000D_ public Presentation() {_x000D_ // Verandering: Presentation heeft slideViewComponent nu niet meer als attribuut_x000D_ //slideViewComponent = null;_x000D_ clear();_x000D_ }_x000D_ _x000D_ // Methode die wordt gebruikt door de Controller_x000D_ // om te bepalen wat er getoond wordt._x000D_ public int getSize() {_x000D_ return showList.size();_x000D_ }_x000D_ _x000D_ public String getTitle() {_x000D_ return showTitle;_x000D_ }_x000D_ _x000D_ public void setTitle(String nt) {_x000D_ showTitle = nt;_x000D_ }_x000D_ _x000D_ // Verandering: deze methode hebben we niet meer nodig_x000D_ // public void setShowView(SlideViewerComponent slideViewerComponent) {_x000D_ // this.slideViewComponent = slideViewerComponent;_x000D_ // }_x000D_ _x000D_ // geef het nummer van de huidige slide_x000D_ public int getSlideNumber() {_x000D_ return currentSlideNumber;_x000D_ }_x000D_ _x000D_ // verander het huidige-slide-nummer en laat het aan het window weten._x000D_ public void setSlideNumber(int number) {_x000D_ currentSlideNumber = number;_x000D_ // Verandering: het updaten van de SlideViewerComponent gebeurt nu via het Observer patroon_x000D_ //if (slideViewComponent != null) {_x000D_ // slideViewComponent.update(this, getCurrentSlide());_x000D_ //}_x000D_ }_x000D_ _x000D_ // Verwijder de presentatie, om klaar te zijn voor de volgende_x000D_ void clear() {_x000D_ showList = new ArrayList<Slide>();_x000D_ setTitle("New presentation");_x000D_ setSlideNumber(-1);_x000D_ }_x000D_ _x000D_ // Voeg een slide toe aan de presentatie_x000D_ public void append(Slide slide) {_x000D_ showList.add(slide);_x000D_ }_x000D_ _x000D_ // Geef een slide met een bepaald slidenummer_x000D_ public Slide getSlide(int number) {_x000D_ if (number < 0 || number >= getSize()){_x000D_ return null;_x000D_ }_x000D_ return (Slide)showList.get(number);_x000D_ }_x000D_ _x000D_ // Geef de huidige Slide_x000D_ public Slide getCurrentSlide() {_x000D_ return getSlide(currentSlideNumber);_x000D_ }_x000D_ }_x000D_
GertSallaerts/jabbertest
Presentation.java
935
// het slidenummer van de huidige Slide_x000D_
line_comment
nl
import java.util.ArrayList;_x000D_ _x000D_ /**_x000D_ * Presentation houdt de slides in de presentatie bij._x000D_ * <p>_x000D_ * In the Presentation's world, page numbers go from 0 to n-1 * <p>_x000D_ * This program is distributed under the terms of the accompanying_x000D_ * COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_ * Please read it. Your use of the software constitutes acceptance_x000D_ * of the terms in the COPYRIGHT.txt file._x000D_ * @author Ian F. Darwin, ian@darwinsys.com_x000D_ * @version $Id: Presentation.java,v 1.1 2002/12/17 Gert Florijn_x000D_ * @version $Id: Presentation.java,v 1.2 2003/11/19 Sylvia Stuurman_x000D_ * @version $Id: Presentation.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_ * @version $Id: Presentation.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_ */_x000D_ _x000D_ // Verandering: Presentation wordt een Observable_x000D_ public class Presentation {_x000D_ private String showTitle; // de titel van de presentatie_x000D_ private ArrayList<Slide> showList = null; // een ArrayList met de Slides_x000D_ private int currentSlideNumber = 0; // het slidenummer<SUF> // Verandering: we kennen slideViewComponent niet meer direct_x000D_ // private SlideViewerComponent slideViewComponent = null; // de viewcomponent voor de Slides_x000D_ _x000D_ public Presentation() {_x000D_ // Verandering: Presentation heeft slideViewComponent nu niet meer als attribuut_x000D_ //slideViewComponent = null;_x000D_ clear();_x000D_ }_x000D_ _x000D_ // Methode die wordt gebruikt door de Controller_x000D_ // om te bepalen wat er getoond wordt._x000D_ public int getSize() {_x000D_ return showList.size();_x000D_ }_x000D_ _x000D_ public String getTitle() {_x000D_ return showTitle;_x000D_ }_x000D_ _x000D_ public void setTitle(String nt) {_x000D_ showTitle = nt;_x000D_ }_x000D_ _x000D_ // Verandering: deze methode hebben we niet meer nodig_x000D_ // public void setShowView(SlideViewerComponent slideViewerComponent) {_x000D_ // this.slideViewComponent = slideViewerComponent;_x000D_ // }_x000D_ _x000D_ // geef het nummer van de huidige slide_x000D_ public int getSlideNumber() {_x000D_ return currentSlideNumber;_x000D_ }_x000D_ _x000D_ // verander het huidige-slide-nummer en laat het aan het window weten._x000D_ public void setSlideNumber(int number) {_x000D_ currentSlideNumber = number;_x000D_ // Verandering: het updaten van de SlideViewerComponent gebeurt nu via het Observer patroon_x000D_ //if (slideViewComponent != null) {_x000D_ // slideViewComponent.update(this, getCurrentSlide());_x000D_ //}_x000D_ }_x000D_ _x000D_ // Verwijder de presentatie, om klaar te zijn voor de volgende_x000D_ void clear() {_x000D_ showList = new ArrayList<Slide>();_x000D_ setTitle("New presentation");_x000D_ setSlideNumber(-1);_x000D_ }_x000D_ _x000D_ // Voeg een slide toe aan de presentatie_x000D_ public void append(Slide slide) {_x000D_ showList.add(slide);_x000D_ }_x000D_ _x000D_ // Geef een slide met een bepaald slidenummer_x000D_ public Slide getSlide(int number) {_x000D_ if (number < 0 || number >= getSize()){_x000D_ return null;_x000D_ }_x000D_ return (Slide)showList.get(number);_x000D_ }_x000D_ _x000D_ // Geef de huidige Slide_x000D_ public Slide getCurrentSlide() {_x000D_ return getSlide(currentSlideNumber);_x000D_ }_x000D_ }_x000D_
True
False
4
645
69594_0
package AbsentieLijst.userInterfaceLaag;_x000D_ _x000D_ import AbsentieLijst.*;_x000D_ import javafx.collections.FXCollections;_x000D_ import javafx.collections.ObservableList;_x000D_ import javafx.event.ActionEvent;_x000D_ import javafx.fxml.FXMLLoader;_x000D_ import javafx.scene.Parent;_x000D_ import javafx.scene.Scene;_x000D_ import javafx.scene.control.Button;_x000D_ import javafx.scene.control.ComboBox;_x000D_ import javafx.scene.control.DatePicker;_x000D_ import javafx.scene.control.Label;_x000D_ import javafx.scene.image.Image;_x000D_ import javafx.stage.Modality;_x000D_ import javafx.stage.Stage;_x000D_ _x000D_ import java.sql.Time;_x000D_ import java.time.LocalDate;_x000D_ import java.util.ArrayList;_x000D_ import java.util.HashMap;_x000D_ _x000D_ public class ToekomstigAfmeldenController {_x000D_ public Button ButtonOpslaan;_x000D_ public Button ButtonAnnuleren;_x000D_ public DatePicker DatePickerDate;_x000D_ public ComboBox ComboBoxReden;_x000D_ public static ArrayList<Afspraak> afGmeld = new ArrayList<>();_x000D_ public Button overzicht;_x000D_ public Label label;_x000D_ public ComboBox tijd;_x000D_ _x000D_ School HU = School.getSchool();_x000D_ ObservableList<String> options =_x000D_ FXCollections.observableArrayList(_x000D_ "Bruiloft",_x000D_ "Tandarts afspraak",_x000D_ "Begravenis", "Wegens corona.", "Overig"_x000D_ );_x000D_ _x000D_ _x000D_ public void initialize() {_x000D_ ComboBoxReden.setItems(options);_x000D_ _x000D_ }_x000D_ _x000D_ _x000D_ public void ActionOpslaan(ActionEvent actionEvent) {_x000D_ if (DatePickerDate.getValue() != null && ComboBoxReden != null) {_x000D_ LocalDate datum = DatePickerDate.getValue();_x000D_ Object time = tijd.getValue();_x000D_ try {_x000D_ for (Klas klas : HU.getKlassen()) {_x000D_ for (Student student : klas.getStudenten()) {_x000D_ if (student.getisIngelogd()) {_x000D_ HashMap<String, Les> alleLessen = klas.getLessen();_x000D_ for (String lesNaam : alleLessen.keySet()) {_x000D_ if (alleLessen.get(lesNaam).getDatum().equals(datum)) {_x000D_ alleLessen.get(lesNaam).setAbsent(student, " met reden:"+" "+(String) ComboBoxReden.getValue()); //afgemeld_lijst in de les_x000D_ student.setAfgemeld("Vooraf afgemeld: " + alleLessen.get(lesNaam).getDatum() + " " + alleLessen.get(lesNaam).getLescode() + " met als reden: " + ComboBoxReden.getValue()); //afgemeld overzicht student._x000D_ Button source = (Button) actionEvent.getSource();_x000D_ Stage stage = (Stage) source.getScene().getWindow();_x000D_ stage.close();_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ } catch (Exception e) {_x000D_ label.setText("ddddd");_x000D_ }_x000D_ } else label.setText("Je moet Datum en reden kiezen");_x000D_ }_x000D_ _x000D_ public void ActionAnnuleren(ActionEvent actionEvent) {_x000D_ Button source = (Button) actionEvent.getSource();_x000D_ Stage stage = (Stage) source.getScene().getWindow();_x000D_ stage.close();_x000D_ }_x000D_ _x000D_ public void DatapickerOnAction(ActionEvent actionEvent) {_x000D_ ObservableList<String> lessen = FXCollections.observableArrayList();_x000D_ for (Klas klas : HU.getKlassen()) {_x000D_ for (Student student : klas.getStudenten()) {_x000D_ if (student.getisIngelogd()) {_x000D_ ArrayList<String> les = new ArrayList<>();_x000D_ _x000D_ HashMap<String, Les> alleLessen = klas.getLessen();_x000D_ for (Les lesNaam : alleLessen.values())_x000D_ if (lesNaam.getDatum().equals(DatePickerDate.getValue())) {_x000D_ // for (String les1 : alleLessen.keySet()) {_x000D_ les.add(lesNaam.getNaam());_x000D_ lessen.addAll(les);_x000D_ tijd.setItems(lessen);_x000D_ }_x000D_ _x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_
HBO-ICT-GP-SD/Laatsteversie
AbsentieLijst/src/AbsentieLijst/userInterfaceLaag/ToekomstigAfmeldenController.java
1,160
//afgemeld_lijst in de les_x000D_
line_comment
nl
package AbsentieLijst.userInterfaceLaag;_x000D_ _x000D_ import AbsentieLijst.*;_x000D_ import javafx.collections.FXCollections;_x000D_ import javafx.collections.ObservableList;_x000D_ import javafx.event.ActionEvent;_x000D_ import javafx.fxml.FXMLLoader;_x000D_ import javafx.scene.Parent;_x000D_ import javafx.scene.Scene;_x000D_ import javafx.scene.control.Button;_x000D_ import javafx.scene.control.ComboBox;_x000D_ import javafx.scene.control.DatePicker;_x000D_ import javafx.scene.control.Label;_x000D_ import javafx.scene.image.Image;_x000D_ import javafx.stage.Modality;_x000D_ import javafx.stage.Stage;_x000D_ _x000D_ import java.sql.Time;_x000D_ import java.time.LocalDate;_x000D_ import java.util.ArrayList;_x000D_ import java.util.HashMap;_x000D_ _x000D_ public class ToekomstigAfmeldenController {_x000D_ public Button ButtonOpslaan;_x000D_ public Button ButtonAnnuleren;_x000D_ public DatePicker DatePickerDate;_x000D_ public ComboBox ComboBoxReden;_x000D_ public static ArrayList<Afspraak> afGmeld = new ArrayList<>();_x000D_ public Button overzicht;_x000D_ public Label label;_x000D_ public ComboBox tijd;_x000D_ _x000D_ School HU = School.getSchool();_x000D_ ObservableList<String> options =_x000D_ FXCollections.observableArrayList(_x000D_ "Bruiloft",_x000D_ "Tandarts afspraak",_x000D_ "Begravenis", "Wegens corona.", "Overig"_x000D_ );_x000D_ _x000D_ _x000D_ public void initialize() {_x000D_ ComboBoxReden.setItems(options);_x000D_ _x000D_ }_x000D_ _x000D_ _x000D_ public void ActionOpslaan(ActionEvent actionEvent) {_x000D_ if (DatePickerDate.getValue() != null && ComboBoxReden != null) {_x000D_ LocalDate datum = DatePickerDate.getValue();_x000D_ Object time = tijd.getValue();_x000D_ try {_x000D_ for (Klas klas : HU.getKlassen()) {_x000D_ for (Student student : klas.getStudenten()) {_x000D_ if (student.getisIngelogd()) {_x000D_ HashMap<String, Les> alleLessen = klas.getLessen();_x000D_ for (String lesNaam : alleLessen.keySet()) {_x000D_ if (alleLessen.get(lesNaam).getDatum().equals(datum)) {_x000D_ alleLessen.get(lesNaam).setAbsent(student, " met reden:"+" "+(String) ComboBoxReden.getValue()); //afgemeld_lijst in<SUF> student.setAfgemeld("Vooraf afgemeld: " + alleLessen.get(lesNaam).getDatum() + " " + alleLessen.get(lesNaam).getLescode() + " met als reden: " + ComboBoxReden.getValue()); //afgemeld overzicht student._x000D_ Button source = (Button) actionEvent.getSource();_x000D_ Stage stage = (Stage) source.getScene().getWindow();_x000D_ stage.close();_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ } catch (Exception e) {_x000D_ label.setText("ddddd");_x000D_ }_x000D_ } else label.setText("Je moet Datum en reden kiezen");_x000D_ }_x000D_ _x000D_ public void ActionAnnuleren(ActionEvent actionEvent) {_x000D_ Button source = (Button) actionEvent.getSource();_x000D_ Stage stage = (Stage) source.getScene().getWindow();_x000D_ stage.close();_x000D_ }_x000D_ _x000D_ public void DatapickerOnAction(ActionEvent actionEvent) {_x000D_ ObservableList<String> lessen = FXCollections.observableArrayList();_x000D_ for (Klas klas : HU.getKlassen()) {_x000D_ for (Student student : klas.getStudenten()) {_x000D_ if (student.getisIngelogd()) {_x000D_ ArrayList<String> les = new ArrayList<>();_x000D_ _x000D_ HashMap<String, Les> alleLessen = klas.getLessen();_x000D_ for (Les lesNaam : alleLessen.values())_x000D_ if (lesNaam.getDatum().equals(DatePickerDate.getValue())) {_x000D_ // for (String les1 : alleLessen.keySet()) {_x000D_ les.add(lesNaam.getNaam());_x000D_ lessen.addAll(les);_x000D_ tijd.setItems(lessen);_x000D_ }_x000D_ _x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_
True
False
9
4,470
18288_9
/* * Copyright 2008, 2009, 2010, 2011: * Tobias Fleig (tfg[AT]online[DOT]de), * Michael Haas (mekhar[AT]gmx[DOT]de), * Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de) * * - All rights reserved - * * * This file is part of Centuries of Rage. * * Centuries of Rage 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. * * Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>. * */ package de._13ducks.cor.game.server; import de._13ducks.cor.debug.UltimateDebug; import de._13ducks.cor.game.server.movement.ServerMoveManager; import de._13ducks.cor.networks.server.ServerNetController; import de._13ducks.cor.game.Building; import de._13ducks.cor.game.Unit; import de._13ducks.cor.game.NetPlayer.races; import java.io.*; import java.util.*; import javax.swing.JFrame; import javax.swing.JOptionPane; import de._13ducks.cor.game.Core; import de._13ducks.cor.game.NetPlayer; import de._13ducks.cor.game.server.movement.ServerAttackManager; /** * Der Server-Kern * * Startet einen Server mit den dazugehörigen Server-Modulen etc... * * Erzeugt ein seperates Logfile (server_log.txt) * * @author tfg */ public class ServerCore extends Core { ServerCore.InnerServer rgi; ServerNetController servNet; ServerMapModule mapMod; ServerGameController gamectrl; ServerStatistics sstat; //Statistik ServerMoveManager smoveman; public boolean ready; // gibt an, ob das Spiel gestartet werden soll. public ServerCore(boolean debug, String Mapname) { debugmode = debug; rgi = new ServerCore.InnerServer(); initLogger(); rgi.logger("[Core] Reading config..."); if (debugmode) { System.out.println("Configuration:"); } // Konfigurationsdatei lesen cfgvalues = new HashMap(); File cfgFile = new File("server_cfg.txt"); try { FileReader cfgReader = new FileReader(cfgFile); BufferedReader reader = new BufferedReader(cfgReader); String zeile = null; int i = 0; // Anzahl der Durchläufe zählen while ((zeile = reader.readLine()) != null) { // Liest Zeile fuer Zeile, jetzt auswerten und in Variablen // schreiben int indexgleich = zeile.indexOf('='); // Istgleich suchen if (indexgleich == -1) { } else { String v1 = zeile.substring(0, indexgleich); // Vor dem = // rauschneiden String v2 = zeile.substring(indexgleich + 1); // Nach dem // = // rausschneiden System.out.println(v1 + " = " + v2); cfgvalues.put(v1, v2); if (debugmode) { // Im Debugmode alles ausgeben, zum nachvollziehen rgi.logger("[Core-Log] " + v1 + "=" + v2); } } } reader.close(); } catch (FileNotFoundException e1) { // cfg-Datei nicht gefunden - inakzeptabel! rgi.logger("[Core-ERROR] Configfile (server_cfg.txt) not found, creating new one..."); try { cfgFile.createNewFile(); } catch (IOException ex) { System.out.print("Error creating server_cfg.txt ."); } //rgi.shutdown(1); } catch (IOException e2) { // Inakzeptabel e2.printStackTrace(); rgi.logger("[Core-ERROR] Critical I/O Error"); rgi.shutdown(1); } if ("true".equals(cfgvalues.get("ultimateDebug"))) { UltimateDebug udb = UltimateDebug.getInstance(); udb.authorizeDebug(this, rgi); } // Läuft als Server rgi.logger("[CoreInit]: Starting server mode..."); // Module laden rgi.logger("[CoreInit]: Loading modules..."); rgi.logger("[CoreInit]: Loading gamecontroller"); gamectrl = new ServerGameController(rgi); // Netzwerk rgi.logger("[CoreInit]: Loading serverNetController"); servNet = new ServerNetController(rgi, this); rgi.logger("[CoreInit]: Loading serverMapmodul"); mapMod = new ServerMapModule(rgi); rgi.logger("[CoreInit]: Loading serverStatistics"); sstat = new ServerStatistics(rgi); rgi.logger("[CoreInit]: Loading serverMoveManager"); smoveman = new ServerMoveManager(); // Alle Module geladen, starten rgi.initInner(); rgi.logger("[Core]: Initializing modules..."); mapMod.initModule(); rgi.logger("[Core]: Init done, starting Server..."); Thread t = new Thread(servNet); t.start(); rgi.logger("[Core]: Server running"); try { // Auf Startsignal warten while (!this.ready) { Thread.sleep(1000); } // Jetzt darf niemand mehr rein servNet.closeAcception(); // Zufallsvölker bestimmen und allen Clients mitteilen: for (NetPlayer p : this.gamectrl.playerList) { if (p.lobbyRace == races.random) { if (Math.rint(Math.random()) == 1) { p.lobbyRace = 1; this.servNet.broadcastString(("91" + p.nickName), (byte) 14); } else { p.lobbyRace = 2; this.servNet.broadcastString(("92" + p.nickName), (byte) 14); } } } // Clients vorbereiten servNet.loadGame(); // Warte darauf, das alle soweit sind waitForStatus(1); // Spiel laden mapMod.loadMap(Mapname); waitForStatus(2); // Game vorbereiten servNet.initGame((byte) 8); // Starteinheiten & Gebäude an das gewählte Volk anpassen: for (NetPlayer player : this.gamectrl.playerList) { // Gebäude: for (Building building : this.rgi.netmap.buildingList) { if (building.getPlayerId() == player.playerId) { if (player.lobbyRace == races.undead) { building.performUpgrade(rgi, 1001); } else if (player.lobbyRace == races.human) { building.performUpgrade(rgi, 1); } } } // Einheiten: for (Unit unit : this.rgi.netmap.unitList) { if (unit.getPlayerId() == player.playerId) { if (player.lobbyRace == races.undead) { // 401=human worker, 1401=undead worker if (unit.getDescTypeId() == 401) { unit.performUpgrade(rgi, 1401); } // 402=human scout, 1402=undead mage if (unit.getDescTypeId() == 402) { unit.performUpgrade(rgi, 1402); } } else if (player.lobbyRace == races.human) { // 1401=undead worker, 401=human worker if (unit.getDescTypeId() == 1401) { unit.performUpgrade(rgi, 401); } // 1402=undead mage, 402=human scout if (unit.getDescTypeId() == 1402) { unit.performUpgrade(rgi, 402); } } } } } waitForStatus(3); servNet.startGame(); } catch (InterruptedException ex) { } } /** * Synchronisierte Funktipon zum Strings senden * wird für die Lobby gebraucht, vielleicht später auch mal für ingame-chat * @param s - zu sendender String * @param cmdid - command-id */ public synchronized void broadcastStringSynchronized(String s, byte cmdid) { s += "\0"; this.servNet.broadcastString(s, cmdid); } private void waitForStatus(int status) throws InterruptedException { while (true) { Thread.sleep(50); boolean go = true; for (ServerNetController.ServerHandler servhan : servNet.clientconnection) { if (servhan.loadStatus < status) { go = false; break; } } if (go) { break; } } } @Override public void initLogger() { if (!logOFF) { // Erstellt ein neues Logfile try { FileWriter logcreator = new FileWriter("server_log.txt"); logcreator.close(); } catch (IOException ex) { // Warscheinlich darf man das nicht, den Adminmodus emfehlen JOptionPane.showMessageDialog(new JFrame(), "Cannot write to logfile. Please start CoR as Administrator", "admin required", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); rgi.shutdown(2); } } } public class InnerServer extends Core.CoreInner { public ServerNetController netctrl; public ServerMapModule netmap; public ServerGameController game; public ServerStatistics serverstats; String lastlog = ""; public ServerMoveManager moveMan; public ServerAttackManager atkMan; @Override public void initInner() { super.initInner(); // Server-Referenz initialisiern: Server.setInnerServer(this); netctrl = servNet; netmap = mapMod; game = gamectrl; serverstats = sstat; moveMan = smoveman; atkMan = new ServerAttackManager(); } @Override public void logger(String x) { if (!logOFF) { if (!lastlog.equals(x)) { // Nachrichten nicht mehrfach speichern lastlog = x; // Schreibt den Inhalt des Strings zusammen mit dem Zeitpunkt in die // log-Datei try { FileWriter logwriter = new FileWriter("server_log.txt", true); String temp = String.format("%tc", new Date()) + " - " + x + "\n"; logwriter.append(temp); logwriter.flush(); logwriter.close(); } catch (IOException ex) { ex.printStackTrace(); shutdown(2); } } } } @Override public void logger(Throwable t) { if (!logOFF) { // Nimmt Exceptions an und schreibt den Stacktrace ins // logfile try { if (debugmode) { System.out.println("ERROR!!!! More info in logfile..."); } FileWriter logwriter = new FileWriter("server_log.txt", true); logwriter.append('\n' + String.format("%tc", new Date()) + " - "); logwriter.append("[JavaError]: " + t.toString() + '\n'); StackTraceElement[] errorArray; errorArray = t.getStackTrace(); for (int i = 0; i < errorArray.length; i++) { logwriter.append(" " + errorArray[i].toString() + '\n'); } logwriter.flush(); logwriter.close(); } catch (IOException ex) { ex.printStackTrace(); shutdown(2); } } } } }
tfg13/Centuries-of-Rage
src/de/_13ducks/cor/game/server/ServerCore.java
3,501
// Alle Module geladen, starten
line_comment
nl
/* * Copyright 2008, 2009, 2010, 2011: * Tobias Fleig (tfg[AT]online[DOT]de), * Michael Haas (mekhar[AT]gmx[DOT]de), * Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de) * * - All rights reserved - * * * This file is part of Centuries of Rage. * * Centuries of Rage 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. * * Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>. * */ package de._13ducks.cor.game.server; import de._13ducks.cor.debug.UltimateDebug; import de._13ducks.cor.game.server.movement.ServerMoveManager; import de._13ducks.cor.networks.server.ServerNetController; import de._13ducks.cor.game.Building; import de._13ducks.cor.game.Unit; import de._13ducks.cor.game.NetPlayer.races; import java.io.*; import java.util.*; import javax.swing.JFrame; import javax.swing.JOptionPane; import de._13ducks.cor.game.Core; import de._13ducks.cor.game.NetPlayer; import de._13ducks.cor.game.server.movement.ServerAttackManager; /** * Der Server-Kern * * Startet einen Server mit den dazugehörigen Server-Modulen etc... * * Erzeugt ein seperates Logfile (server_log.txt) * * @author tfg */ public class ServerCore extends Core { ServerCore.InnerServer rgi; ServerNetController servNet; ServerMapModule mapMod; ServerGameController gamectrl; ServerStatistics sstat; //Statistik ServerMoveManager smoveman; public boolean ready; // gibt an, ob das Spiel gestartet werden soll. public ServerCore(boolean debug, String Mapname) { debugmode = debug; rgi = new ServerCore.InnerServer(); initLogger(); rgi.logger("[Core] Reading config..."); if (debugmode) { System.out.println("Configuration:"); } // Konfigurationsdatei lesen cfgvalues = new HashMap(); File cfgFile = new File("server_cfg.txt"); try { FileReader cfgReader = new FileReader(cfgFile); BufferedReader reader = new BufferedReader(cfgReader); String zeile = null; int i = 0; // Anzahl der Durchläufe zählen while ((zeile = reader.readLine()) != null) { // Liest Zeile fuer Zeile, jetzt auswerten und in Variablen // schreiben int indexgleich = zeile.indexOf('='); // Istgleich suchen if (indexgleich == -1) { } else { String v1 = zeile.substring(0, indexgleich); // Vor dem = // rauschneiden String v2 = zeile.substring(indexgleich + 1); // Nach dem // = // rausschneiden System.out.println(v1 + " = " + v2); cfgvalues.put(v1, v2); if (debugmode) { // Im Debugmode alles ausgeben, zum nachvollziehen rgi.logger("[Core-Log] " + v1 + "=" + v2); } } } reader.close(); } catch (FileNotFoundException e1) { // cfg-Datei nicht gefunden - inakzeptabel! rgi.logger("[Core-ERROR] Configfile (server_cfg.txt) not found, creating new one..."); try { cfgFile.createNewFile(); } catch (IOException ex) { System.out.print("Error creating server_cfg.txt ."); } //rgi.shutdown(1); } catch (IOException e2) { // Inakzeptabel e2.printStackTrace(); rgi.logger("[Core-ERROR] Critical I/O Error"); rgi.shutdown(1); } if ("true".equals(cfgvalues.get("ultimateDebug"))) { UltimateDebug udb = UltimateDebug.getInstance(); udb.authorizeDebug(this, rgi); } // Läuft als Server rgi.logger("[CoreInit]: Starting server mode..."); // Module laden rgi.logger("[CoreInit]: Loading modules..."); rgi.logger("[CoreInit]: Loading gamecontroller"); gamectrl = new ServerGameController(rgi); // Netzwerk rgi.logger("[CoreInit]: Loading serverNetController"); servNet = new ServerNetController(rgi, this); rgi.logger("[CoreInit]: Loading serverMapmodul"); mapMod = new ServerMapModule(rgi); rgi.logger("[CoreInit]: Loading serverStatistics"); sstat = new ServerStatistics(rgi); rgi.logger("[CoreInit]: Loading serverMoveManager"); smoveman = new ServerMoveManager(); // Alle Module<SUF> rgi.initInner(); rgi.logger("[Core]: Initializing modules..."); mapMod.initModule(); rgi.logger("[Core]: Init done, starting Server..."); Thread t = new Thread(servNet); t.start(); rgi.logger("[Core]: Server running"); try { // Auf Startsignal warten while (!this.ready) { Thread.sleep(1000); } // Jetzt darf niemand mehr rein servNet.closeAcception(); // Zufallsvölker bestimmen und allen Clients mitteilen: for (NetPlayer p : this.gamectrl.playerList) { if (p.lobbyRace == races.random) { if (Math.rint(Math.random()) == 1) { p.lobbyRace = 1; this.servNet.broadcastString(("91" + p.nickName), (byte) 14); } else { p.lobbyRace = 2; this.servNet.broadcastString(("92" + p.nickName), (byte) 14); } } } // Clients vorbereiten servNet.loadGame(); // Warte darauf, das alle soweit sind waitForStatus(1); // Spiel laden mapMod.loadMap(Mapname); waitForStatus(2); // Game vorbereiten servNet.initGame((byte) 8); // Starteinheiten & Gebäude an das gewählte Volk anpassen: for (NetPlayer player : this.gamectrl.playerList) { // Gebäude: for (Building building : this.rgi.netmap.buildingList) { if (building.getPlayerId() == player.playerId) { if (player.lobbyRace == races.undead) { building.performUpgrade(rgi, 1001); } else if (player.lobbyRace == races.human) { building.performUpgrade(rgi, 1); } } } // Einheiten: for (Unit unit : this.rgi.netmap.unitList) { if (unit.getPlayerId() == player.playerId) { if (player.lobbyRace == races.undead) { // 401=human worker, 1401=undead worker if (unit.getDescTypeId() == 401) { unit.performUpgrade(rgi, 1401); } // 402=human scout, 1402=undead mage if (unit.getDescTypeId() == 402) { unit.performUpgrade(rgi, 1402); } } else if (player.lobbyRace == races.human) { // 1401=undead worker, 401=human worker if (unit.getDescTypeId() == 1401) { unit.performUpgrade(rgi, 401); } // 1402=undead mage, 402=human scout if (unit.getDescTypeId() == 1402) { unit.performUpgrade(rgi, 402); } } } } } waitForStatus(3); servNet.startGame(); } catch (InterruptedException ex) { } } /** * Synchronisierte Funktipon zum Strings senden * wird für die Lobby gebraucht, vielleicht später auch mal für ingame-chat * @param s - zu sendender String * @param cmdid - command-id */ public synchronized void broadcastStringSynchronized(String s, byte cmdid) { s += "\0"; this.servNet.broadcastString(s, cmdid); } private void waitForStatus(int status) throws InterruptedException { while (true) { Thread.sleep(50); boolean go = true; for (ServerNetController.ServerHandler servhan : servNet.clientconnection) { if (servhan.loadStatus < status) { go = false; break; } } if (go) { break; } } } @Override public void initLogger() { if (!logOFF) { // Erstellt ein neues Logfile try { FileWriter logcreator = new FileWriter("server_log.txt"); logcreator.close(); } catch (IOException ex) { // Warscheinlich darf man das nicht, den Adminmodus emfehlen JOptionPane.showMessageDialog(new JFrame(), "Cannot write to logfile. Please start CoR as Administrator", "admin required", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); rgi.shutdown(2); } } } public class InnerServer extends Core.CoreInner { public ServerNetController netctrl; public ServerMapModule netmap; public ServerGameController game; public ServerStatistics serverstats; String lastlog = ""; public ServerMoveManager moveMan; public ServerAttackManager atkMan; @Override public void initInner() { super.initInner(); // Server-Referenz initialisiern: Server.setInnerServer(this); netctrl = servNet; netmap = mapMod; game = gamectrl; serverstats = sstat; moveMan = smoveman; atkMan = new ServerAttackManager(); } @Override public void logger(String x) { if (!logOFF) { if (!lastlog.equals(x)) { // Nachrichten nicht mehrfach speichern lastlog = x; // Schreibt den Inhalt des Strings zusammen mit dem Zeitpunkt in die // log-Datei try { FileWriter logwriter = new FileWriter("server_log.txt", true); String temp = String.format("%tc", new Date()) + " - " + x + "\n"; logwriter.append(temp); logwriter.flush(); logwriter.close(); } catch (IOException ex) { ex.printStackTrace(); shutdown(2); } } } } @Override public void logger(Throwable t) { if (!logOFF) { // Nimmt Exceptions an und schreibt den Stacktrace ins // logfile try { if (debugmode) { System.out.println("ERROR!!!! More info in logfile..."); } FileWriter logwriter = new FileWriter("server_log.txt", true); logwriter.append('\n' + String.format("%tc", new Date()) + " - "); logwriter.append("[JavaError]: " + t.toString() + '\n'); StackTraceElement[] errorArray; errorArray = t.getStackTrace(); for (int i = 0; i < errorArray.length; i++) { logwriter.append(" " + errorArray[i].toString() + '\n'); } logwriter.flush(); logwriter.close(); } catch (IOException ex) { ex.printStackTrace(); shutdown(2); } } } } }
True
False
17
3,832
169507_0
package nl.njtromp.adventofcode_2020; import java.util.Arrays; public class Infi { static long aantalPakjes(long lengteZijkant) { return 3 * lengteZijkant * lengteZijkant + // Middenstuk horizontaal 4 * sommatie(lengteZijkant) + // Schuine zijden (4 halve driehoeken) 2 * lengteZijkant * lengteZijkant; // Rechte stukken tussen de schuine zijden (onder en boven) } private static long sommatie(long n) { return (n-1)*n/2; } private static long bepaalLengte(long aantalInwoners) { long lengte = 1; while (aantalPakjes(lengte) < aantalInwoners) { lengte++; } return lengte; } public static void main(String[] args) { long lengte = bepaalLengte(17_493_412); System.out.printf("De minimale lengte van een zijde is: %d\n", lengte); long[] aantalInwoners = {42_732_096L, 369_030_498L, 430_839_868L, 747_685_826L, 1_340_952_816L, 4_541_536_619L}; System.out.printf("Totaal aantal lappen stof: %d\n", Arrays.stream(aantalInwoners).map(Infi::bepaalLengte).sum() * 8); } }
njtromp/AdventOfCode-2020
src/main/java/nl/njtromp/adventofcode_2020/Infi.java
436
// Schuine zijden (4 halve driehoeken)
line_comment
nl
package nl.njtromp.adventofcode_2020; import java.util.Arrays; public class Infi { static long aantalPakjes(long lengteZijkant) { return 3 * lengteZijkant * lengteZijkant + // Middenstuk horizontaal 4 * sommatie(lengteZijkant) + // Schuine zijden<SUF> 2 * lengteZijkant * lengteZijkant; // Rechte stukken tussen de schuine zijden (onder en boven) } private static long sommatie(long n) { return (n-1)*n/2; } private static long bepaalLengte(long aantalInwoners) { long lengte = 1; while (aantalPakjes(lengte) < aantalInwoners) { lengte++; } return lengte; } public static void main(String[] args) { long lengte = bepaalLengte(17_493_412); System.out.printf("De minimale lengte van een zijde is: %d\n", lengte); long[] aantalInwoners = {42_732_096L, 369_030_498L, 430_839_868L, 747_685_826L, 1_340_952_816L, 4_541_536_619L}; System.out.printf("Totaal aantal lappen stof: %d\n", Arrays.stream(aantalInwoners).map(Infi::bepaalLengte).sum() * 8); } }
True
False
19
808
152641_17
package intecbrussel.be.Vaccination;_x000D_ _x000D_ import java.util.*;_x000D_ import java.util.stream.Collectors;_x000D_ _x000D_ public class AnimalShelter {_x000D_ private List<Animal> animals;_x000D_ private int animalId;_x000D_ _x000D_ public AnimalShelter() {_x000D_ this.animals = new ArrayList<>();_x000D_ this.animalId = 1;_x000D_ }_x000D_ _x000D_ public List<Animal> getAnimals() {_x000D_ return animals;_x000D_ }_x000D_ _x000D_ public void setAnimals(List<Animal> animals) {_x000D_ this.animals = animals;_x000D_ }_x000D_ _x000D_ public int getAnimalId() {_x000D_ return animalId;_x000D_ }_x000D_ _x000D_ public void setAnimalId(int animalId) {_x000D_ this.animalId = animalId;_x000D_ }_x000D_ //1_x000D_ public void printAnimals(){_x000D_ for (Animal animal : animals){_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }_x000D_ }_x000D_ // sorteert de dieren volgens hun natuurlijke volgorde, dit is volgens hun animalNumber._x000D_ //2_x000D_ public void sortAnimals(){_x000D_ animals.sort(Comparator.comparing(Animal::getAnimalNumber));_x000D_ }_x000D_ //sorteert de dieren op naam_x000D_ //3_x000D_ public void sortAnimalsByName(){_x000D_ animals.sort(Comparator.comparing(Animal::getName));_x000D_ }_x000D_ // sorteert de dieren op leeftijd_x000D_ //4_x000D_ public void sortAnimalsByAge(){_x000D_ animals.sort(Comparator.comparing(Animal::getAge));_x000D_ }_x000D_ //print alle dieren af die niet gevaccineert zijn voor een opgegeven ziekte_x000D_ //5_x000D_ public void printAnimalsNotVaccinated(Disease disease){_x000D_ List<Animal> notVaccinated = animals.stream().filter(animal -> animal.getIsVaccinated().getOrDefault(disease, false)).collect(Collectors.toList());_x000D_ for (Animal animal : notVaccinated){_x000D_ System.out.println(animal.getName()+" is not vaccinated "+disease.name());_x000D_ }_x000D_ }_x000D_ //zoek dier op dierennummer_x000D_ //6_x000D_ public Animal findAnimal(int animalNumber) {_x000D_ for (Animal animal : animals){_x000D_ if (animal.getAnimalNumber() == animalNumber){_x000D_ return animal;_x000D_ }_x000D_ }_x000D_ return null;_x000D_ // return animals.stream().filter(animal -> animal.getAnimalNumber()==animalNumber).findFirst();_x000D_ }_x000D_ _x000D_ //zoek dier op dierennaam_x000D_ //7_x000D_ public Optional<Animal> findAnimal(String name){_x000D_ return animals.stream().filter(animal -> animal.getName().equalsIgnoreCase(name)).findFirst();_x000D_ _x000D_ }_x000D_ // behandel opgegeven dier_x000D_ //8_x000D_ public void treatAnimal(int animalNumber){_x000D_ for (Animal animal : animals){_x000D_ if (animal.getAnimalNumber()==animalNumber){_x000D_ System.out.println("treat animal by number: "+animal.getAnimalNumber()+animal.getIsVaccinated());_x000D_ _x000D_ }_x000D_ }_x000D_ _x000D_ //System.out.println("animal with number "+animalNumber+"not found");_x000D_ /* animals.stream()_x000D_ .sorted(Comparator.comparingInt(Animal::getAnimalNumber))_x000D_ .forEach(animal -> System.out.println(_x000D_ "Animal number: "+animal.getAnimalNumber()+_x000D_ "| name: "+animal.getName()+_x000D_ "| age: "+animal.getAge()+_x000D_ "| is clean? "+animal.getIsVaccinated()_x000D_ ));///////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_ /*Optional<Animal> optionalAnimal = findAnimal(animalNumber);_x000D_ if (optionalAnimal.isPresent()){_x000D_ Animal animal = optionalAnimal.get();_x000D_ animal.treatAnimal();_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }else {_x000D_ System.out.println("animal met number "+animalNumber+"not found");_x000D_ }*/_x000D_ }_x000D_ //behandel opgegeven dier_x000D_ //9_x000D_ public void treatAnimal(String name){_x000D_ for (Animal animal : animals){_x000D_ if (animal.getName()==name){_x000D_ System.out.println("treat animal by name: "+animal.getName()+animal.getIsVaccinated());_x000D_ _x000D_ }_x000D_ }_x000D_ /*animals.stream()_x000D_ .sorted(Comparator.comparing(Animal::getName))_x000D_ .forEach(animal -> System.out.println(_x000D_ "name: "+animal.getName()+_x000D_ "| animal number: "+animal.getAnimalNumber()+_x000D_ "| age: "+animal.getAge()+_x000D_ "| is clean? "+animal.getIsVaccinated()_x000D_ ));/////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_ /* Optional<Animal> optionalAnimal = findAnimal(name);_x000D_ if (optionalAnimal.isPresent()){_x000D_ Animal animal = optionalAnimal.get();_x000D_ animal.treatAnimal();_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }else {_x000D_ System.out.println("animal met name "+name+ "not found");_x000D_ }*/_x000D_ _x000D_ }_x000D_ //behandel alle dieren_x000D_ //10_x000D_ public void treatAllAnimals(){_x000D_ for (Animal animal : animals){_x000D_ animal.treatAnimal();_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }_x000D_ _x000D_ }_x000D_ //geef het oudste dier terug_x000D_ //11_x000D_ public Animal findOldestAnimal() throws NoSuchElementException {_x000D_ if (animals.isEmpty()) {_x000D_ throw new NoSuchElementException("No animal found in this list");_x000D_ }_x000D_ Animal oldestAnimal = animals.get(0);_x000D_ for (Animal animal : animals){_x000D_ if (animal.getAge() > oldestAnimal.getAge()){_x000D_ oldestAnimal = animal;_x000D_ //System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }_x000D_ }_x000D_ return oldestAnimal;_x000D_ _x000D_ }_x000D_ _x000D_ // geef het aantal dieren terug_x000D_ //12_x000D_ public int countAnimals(){_x000D_ if (animals != null){_x000D_ return animals.size();_x000D_ }else {_x000D_ return 0;_x000D_ }_x000D_ }_x000D_ _x000D_ //voeg een dier toe aan de lijst van animals_x000D_ //13_x000D_ public void addAnimal(Animal animal) throws IllegalArgumentException{_x000D_ if (animal != null){_x000D_ animal.setAnimalNumber(animalId);//toewijzen de nummer animal_x000D_ animals.add(animal);//add de animal to de list_x000D_ animalId++;//verhoog de animal id_x000D_ }else {_x000D_ throw new IllegalArgumentException("Can not add null animal to de list");_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_ }_x000D_
JananJavdan/Vaccination
Vaccination/src/main/java/intecbrussel/be/Vaccination/AnimalShelter.java
2,073
//toewijzen de nummer animal_x000D_
line_comment
nl
package intecbrussel.be.Vaccination;_x000D_ _x000D_ import java.util.*;_x000D_ import java.util.stream.Collectors;_x000D_ _x000D_ public class AnimalShelter {_x000D_ private List<Animal> animals;_x000D_ private int animalId;_x000D_ _x000D_ public AnimalShelter() {_x000D_ this.animals = new ArrayList<>();_x000D_ this.animalId = 1;_x000D_ }_x000D_ _x000D_ public List<Animal> getAnimals() {_x000D_ return animals;_x000D_ }_x000D_ _x000D_ public void setAnimals(List<Animal> animals) {_x000D_ this.animals = animals;_x000D_ }_x000D_ _x000D_ public int getAnimalId() {_x000D_ return animalId;_x000D_ }_x000D_ _x000D_ public void setAnimalId(int animalId) {_x000D_ this.animalId = animalId;_x000D_ }_x000D_ //1_x000D_ public void printAnimals(){_x000D_ for (Animal animal : animals){_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }_x000D_ }_x000D_ // sorteert de dieren volgens hun natuurlijke volgorde, dit is volgens hun animalNumber._x000D_ //2_x000D_ public void sortAnimals(){_x000D_ animals.sort(Comparator.comparing(Animal::getAnimalNumber));_x000D_ }_x000D_ //sorteert de dieren op naam_x000D_ //3_x000D_ public void sortAnimalsByName(){_x000D_ animals.sort(Comparator.comparing(Animal::getName));_x000D_ }_x000D_ // sorteert de dieren op leeftijd_x000D_ //4_x000D_ public void sortAnimalsByAge(){_x000D_ animals.sort(Comparator.comparing(Animal::getAge));_x000D_ }_x000D_ //print alle dieren af die niet gevaccineert zijn voor een opgegeven ziekte_x000D_ //5_x000D_ public void printAnimalsNotVaccinated(Disease disease){_x000D_ List<Animal> notVaccinated = animals.stream().filter(animal -> animal.getIsVaccinated().getOrDefault(disease, false)).collect(Collectors.toList());_x000D_ for (Animal animal : notVaccinated){_x000D_ System.out.println(animal.getName()+" is not vaccinated "+disease.name());_x000D_ }_x000D_ }_x000D_ //zoek dier op dierennummer_x000D_ //6_x000D_ public Animal findAnimal(int animalNumber) {_x000D_ for (Animal animal : animals){_x000D_ if (animal.getAnimalNumber() == animalNumber){_x000D_ return animal;_x000D_ }_x000D_ }_x000D_ return null;_x000D_ // return animals.stream().filter(animal -> animal.getAnimalNumber()==animalNumber).findFirst();_x000D_ }_x000D_ _x000D_ //zoek dier op dierennaam_x000D_ //7_x000D_ public Optional<Animal> findAnimal(String name){_x000D_ return animals.stream().filter(animal -> animal.getName().equalsIgnoreCase(name)).findFirst();_x000D_ _x000D_ }_x000D_ // behandel opgegeven dier_x000D_ //8_x000D_ public void treatAnimal(int animalNumber){_x000D_ for (Animal animal : animals){_x000D_ if (animal.getAnimalNumber()==animalNumber){_x000D_ System.out.println("treat animal by number: "+animal.getAnimalNumber()+animal.getIsVaccinated());_x000D_ _x000D_ }_x000D_ }_x000D_ _x000D_ //System.out.println("animal with number "+animalNumber+"not found");_x000D_ /* animals.stream()_x000D_ .sorted(Comparator.comparingInt(Animal::getAnimalNumber))_x000D_ .forEach(animal -> System.out.println(_x000D_ "Animal number: "+animal.getAnimalNumber()+_x000D_ "| name: "+animal.getName()+_x000D_ "| age: "+animal.getAge()+_x000D_ "| is clean? "+animal.getIsVaccinated()_x000D_ ));///////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_ /*Optional<Animal> optionalAnimal = findAnimal(animalNumber);_x000D_ if (optionalAnimal.isPresent()){_x000D_ Animal animal = optionalAnimal.get();_x000D_ animal.treatAnimal();_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }else {_x000D_ System.out.println("animal met number "+animalNumber+"not found");_x000D_ }*/_x000D_ }_x000D_ //behandel opgegeven dier_x000D_ //9_x000D_ public void treatAnimal(String name){_x000D_ for (Animal animal : animals){_x000D_ if (animal.getName()==name){_x000D_ System.out.println("treat animal by name: "+animal.getName()+animal.getIsVaccinated());_x000D_ _x000D_ }_x000D_ }_x000D_ /*animals.stream()_x000D_ .sorted(Comparator.comparing(Animal::getName))_x000D_ .forEach(animal -> System.out.println(_x000D_ "name: "+animal.getName()+_x000D_ "| animal number: "+animal.getAnimalNumber()+_x000D_ "| age: "+animal.getAge()+_x000D_ "| is clean? "+animal.getIsVaccinated()_x000D_ ));/////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_ /* Optional<Animal> optionalAnimal = findAnimal(name);_x000D_ if (optionalAnimal.isPresent()){_x000D_ Animal animal = optionalAnimal.get();_x000D_ animal.treatAnimal();_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }else {_x000D_ System.out.println("animal met name "+name+ "not found");_x000D_ }*/_x000D_ _x000D_ }_x000D_ //behandel alle dieren_x000D_ //10_x000D_ public void treatAllAnimals(){_x000D_ for (Animal animal : animals){_x000D_ animal.treatAnimal();_x000D_ System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }_x000D_ _x000D_ }_x000D_ //geef het oudste dier terug_x000D_ //11_x000D_ public Animal findOldestAnimal() throws NoSuchElementException {_x000D_ if (animals.isEmpty()) {_x000D_ throw new NoSuchElementException("No animal found in this list");_x000D_ }_x000D_ Animal oldestAnimal = animals.get(0);_x000D_ for (Animal animal : animals){_x000D_ if (animal.getAge() > oldestAnimal.getAge()){_x000D_ oldestAnimal = animal;_x000D_ //System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_ }_x000D_ }_x000D_ return oldestAnimal;_x000D_ _x000D_ }_x000D_ _x000D_ // geef het aantal dieren terug_x000D_ //12_x000D_ public int countAnimals(){_x000D_ if (animals != null){_x000D_ return animals.size();_x000D_ }else {_x000D_ return 0;_x000D_ }_x000D_ }_x000D_ _x000D_ //voeg een dier toe aan de lijst van animals_x000D_ //13_x000D_ public void addAnimal(Animal animal) throws IllegalArgumentException{_x000D_ if (animal != null){_x000D_ animal.setAnimalNumber(animalId);//toewijzen de<SUF> animals.add(animal);//add de animal to de list_x000D_ animalId++;//verhoog de animal id_x000D_ }else {_x000D_ throw new IllegalArgumentException("Can not add null animal to de list");_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_ }_x000D_
True
False
24
3,576
72814_22
package org.molgenis.animaldb.plugins.administration;_x000D_ _x000D_ import java.text.SimpleDateFormat;_x000D_ import java.util.ArrayList;_x000D_ import java.util.Date;_x000D_ import java.util.List;_x000D_ import java.util.Locale;_x000D_ _x000D_ import org.molgenis.animaldb.commonservice.CommonService;_x000D_ import org.molgenis.framework.db.Database;_x000D_ import org.molgenis.framework.db.Query;_x000D_ import org.molgenis.framework.db.QueryRule;_x000D_ import org.molgenis.framework.db.QueryRule.Operator;_x000D_ import org.molgenis.pheno.ObservationTarget;_x000D_ import org.molgenis.pheno.ObservedValue;_x000D_ _x000D_ _x000D_ public class VWAReport5 extends AnimalDBReport {_x000D_ _x000D_ private ArrayList<ArrayList<String>> matrix = new ArrayList<ArrayList<String>>();_x000D_ private List<Integer> nrOfAnimalList = new ArrayList<Integer>();_x000D_ private String userName;_x000D_ _x000D_ public VWAReport5(Database db, String userName) {_x000D_ this.userName = userName;_x000D_ this.db = db;_x000D_ ct = CommonService.getInstance();_x000D_ ct.setDatabase(db);_x000D_ nrCol = 17;_x000D_ warningsList = new ArrayList<String>();_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void makeReport(int year, String type) {_x000D_ try {_x000D_ this.year = year;_x000D_ SimpleDateFormat fullFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);_x000D_ SimpleDateFormat dbFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);_x000D_ String startOfYearString = year + "-01-01 00:00:00";_x000D_ Date startOfYear = fullFormat.parse(startOfYearString);_x000D_ String endOfYearString = (year + 1) + "-01-01 00:00:00";_x000D_ Date endOfYear = fullFormat.parse(endOfYearString);_x000D_ _x000D_ List<String> investigationNames = ct.getOwnUserInvestigationNames(userName);_x000D_ List<ObservationTarget> decappList = ct.getAllMarkedPanels("DecApplication", investigationNames);_x000D_ for (ObservationTarget d : decappList) {_x000D_ String decName = d.getName();_x000D_ // Check if the DEC application was (partly) in this year_x000D_ Date startOfDec = null;_x000D_ String startOfDecString = ct.getMostRecentValueAsString(decName, "StartDate");_x000D_ if (startOfDecString != null && !startOfDecString.equals("")) {_x000D_ startOfDec = dbFormat.parse(startOfDecString);_x000D_ if (startOfDec.after(endOfYear)) {_x000D_ continue;_x000D_ }_x000D_ } else {_x000D_ continue;_x000D_ }_x000D_ Date endOfDec = null;_x000D_ String endOfDecString = ct.getMostRecentValueAsString(decName, "EndDate");_x000D_ if (endOfDecString != null && !endOfDecString.equals("")) {_x000D_ endOfDec = dbFormat.parse(endOfDecString);_x000D_ if (endOfDec.before(startOfYear)) {_x000D_ continue;_x000D_ }_x000D_ }_x000D_ // Get DEC number_x000D_ String decNr = ct.getMostRecentValueAsString(decName, "DecNr");_x000D_ // Find the experiments belonging to this DEC_x000D_ List<Integer> experimentIdList = new ArrayList<Integer>();_x000D_ Query<ObservedValue> q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, decName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "DecApplication"));_x000D_ List<ObservedValue> valueList = q.find();_x000D_ // Make sure we have a list of unique experiments!_x000D_ for (ObservedValue v : valueList) {_x000D_ if (!experimentIdList.contains(v.getTarget_Id())) {_x000D_ experimentIdList.add(v.getTarget_Id());_x000D_ }_x000D_ }_x000D_ for (int expid : experimentIdList) {_x000D_ String expName = ct.getObservationTargetLabel(expid);_x000D_ // Get the experiment subcode_x000D_ String expCode = ct.getMostRecentValueAsString(expName, "ExperimentNr");_x000D_ // Doel vd proef (experiment's Goal)_x000D_ String goal = ct.getMostRecentValueAsString(expName, "Goal");_x000D_ // Belang van de proef (experiment's Concern)_x000D_ String concern = ct.getMostRecentValueAsString(expName, "Concern");_x000D_ // Wettelijke bepalingen (experiment's LawDef)_x000D_ String lawDef = ct.getMostRecentValueAsString(expName, "LawDef");_x000D_ // Toxicologisch / veiligheidsonderzoek (experiment's ToxRes)_x000D_ String toxRes = ct.getMostRecentValueAsString(expName, "ToxRes");_x000D_ // Technieken byzondere (experiment's SpecialTechn)_x000D_ String specialTechn = ct.getMostRecentValueAsString(expName, "SpecialTechn");_x000D_ _x000D_ // Get the animals that were in the experiment this year_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, expName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Experiment"));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.LESS_EQUAL, endOfYearString));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.NOT, null));_x000D_ valueList = q.find();_x000D_ for (ObservedValue animalInExpValue : valueList) {_x000D_ // Get the corresponding protocol application_x000D_ int protocolApplicationId = animalInExpValue.getProtocolApplication_Id();_x000D_ // Get animal ID_x000D_ String animalName = animalInExpValue.getTarget_Name();_x000D_ // Get dates_x000D_ Date entryDate = animalInExpValue.getTime();_x000D_ Date exitDate = animalInExpValue.getEndtime();_x000D_ // Check dates_x000D_ if (entryDate.after(endOfYear)) {_x000D_ continue;_x000D_ }_x000D_ if (exitDate == null) { // should not be possible_x000D_ continue;_x000D_ } else if (exitDate.before(startOfYear)) {_x000D_ continue;_x000D_ }_x000D_ _x000D_ // Get the data about the animal in the experiment_x000D_ // Bijzonderheid dier (animal's AnimalType)_x000D_ String animalType = ct.getMostRecentValueAsString(animalName, "AnimalType");_x000D_ // Diersoort (animal's Species -> VWASpecies and LatinSpecies)_x000D_ String vwaSpecies = "";_x000D_ String latinSpecies = "";_x000D_ String normalSpecies = ct.getMostRecentValueAsXrefName(animalName, "Species");_x000D_ // Get VWA species_x000D_ Query<ObservedValue> vwaSpeciesQuery = db.query(ObservedValue.class);_x000D_ vwaSpeciesQuery.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, normalSpecies));_x000D_ vwaSpeciesQuery.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "VWASpecies"));_x000D_ List<ObservedValue> vwaSpeciesValueList = vwaSpeciesQuery.find();_x000D_ if (vwaSpeciesValueList.size() == 1) {_x000D_ vwaSpecies = vwaSpeciesValueList.get(0).getValue();_x000D_ }_x000D_ // Get scientific (Latin) species_x000D_ Query<ObservedValue> latinSpeciesQuery = db.query(ObservedValue.class);_x000D_ latinSpeciesQuery.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, normalSpecies));_x000D_ latinSpeciesQuery.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "LatinSpecies"));_x000D_ List<ObservedValue> latinSpeciesValueList = latinSpeciesQuery.find();_x000D_ if (latinSpeciesValueList.size() == 1) {_x000D_ latinSpecies = latinSpeciesValueList.get(0).getValue();_x000D_ }_x000D_ _x000D_ // Herkomst en hergebruik (animal's SourceTypeSubproject, which includes reuse)_x000D_ String sourceType = "";_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "SourceTypeSubproject"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ sourceType = valueList.get(0).getValue();_x000D_ }_x000D_ // Aantal dieren (count later on!)_x000D_ _x000D_ // Anesthesie (animal's Anaesthesia)_x000D_ String anaesthesia = "";_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Anaesthesia"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ anaesthesia = valueList.get(0).getValue();_x000D_ }_x000D_ _x000D_ // Pijnbestrijding, postoperatief (animal's PainManagement)_x000D_ String painManagement = "";_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "PainManagement"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ painManagement = valueList.get(0).getValue();_x000D_ }_x000D_ _x000D_ String actualDiscomfort = "";_x000D_ String actualAnimalEndStatus = ""; _x000D_ // Find protocol application ID for the removing of this animal from this DEC subproject_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, expName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "FromExperiment"));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ int removalProtocolApplicationId = valueList.get(0).getProtocolApplication_Id();_x000D_ _x000D_ // Ongerief (animal's ActualDiscomfort)_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "ActualDiscomfort"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, removalProtocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ actualDiscomfort = valueList.get(0).getValue();_x000D_ } else {_x000D_ // Something's wrong here..._x000D_ warningsList.add("No 'ActualDiscomfort' value found for Animal " + animalName + _x000D_ " in DEC subproject " + expName);_x000D_ }_x000D_ _x000D_ // Toestand dier na beeindiging proef (animal's most recent ActualAnimalEndStatus)_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "ActualAnimalEndStatus"));_x000D_ q.sortDESC(ObservedValue.TIME);_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ // Check if most recent end status was in the PA we're now looking at_x000D_ if (valueList.get(0).getProtocolApplication_Id().equals(removalProtocolApplicationId)) {_x000D_ actualAnimalEndStatus = valueList.get(0).getValue();_x000D_ // If most recent end status was 'in leven gelaten' but animal died in given year,_x000D_ // change to 'dood ihkv de proef' because that's how the law wants it..._x000D_ if (actualAnimalEndStatus.equals("C. Na einde proef in leven gelaten")) {_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Active"));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.GREATER_EQUAL, startOfYearString));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.LESS_EQUAL, endOfYearString));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.NOT, null));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ // So animal did indeed die in the given year_x000D_ actualAnimalEndStatus = "B. Gedood na beeindiging van de proef";_x000D_ }_x000D_ }_x000D_ } else {_x000D_ // Find the end status value in the PA we're looking at_x000D_ for (ObservedValue endStatusValue : valueList) {_x000D_ if (endStatusValue.getProtocolApplication_Id().equals(removalProtocolApplicationId)) {_x000D_ actualAnimalEndStatus = endStatusValue.getValue();_x000D_ }_x000D_ }_x000D_ }_x000D_ } else {_x000D_ // Something's wrong here..._x000D_ warningsList.add("No 'ActualAnimalEndStatus' value(s) found for Animal " + animalName + _x000D_ " in DEC subproject " + expName);_x000D_ }_x000D_ } else {_x000D_ // Something's wrong here..._x000D_ warningsList.add("No 'FromExperiment' value found for Animal " + animalName + _x000D_ " in DEC subproject " + expName);_x000D_ }_x000D_ _x000D_ ArrayList<String> newRow = new ArrayList<String>();_x000D_ newRow.add(decNr + expCode + " - " + d.getName());_x000D_ if (endOfDec != null) {_x000D_ newRow.add(dbFormat.format(endOfDec));_x000D_ } else {_x000D_ newRow.add("");_x000D_ }_x000D_ newRow.add(animalType);_x000D_ newRow.add(vwaSpecies);_x000D_ newRow.add(sourceType);_x000D_ newRow.add("");_x000D_ newRow.add(goal);_x000D_ newRow.add(concern);_x000D_ newRow.add(lawDef);_x000D_ newRow.add(toxRes);_x000D_ newRow.add(specialTechn);_x000D_ newRow.add(anaesthesia);_x000D_ newRow.add(painManagement);_x000D_ newRow.add(actualDiscomfort);_x000D_ newRow.add(actualAnimalEndStatus);_x000D_ newRow.add(decNr + expCode);_x000D_ newRow.add(latinSpecies);_x000D_ _x000D_ if (matrix.contains(newRow)) {_x000D_ // If the above values are exactly the same as an earlier row, aggregate them_x000D_ int rowIndex = matrix.indexOf(newRow);_x000D_ int tmpNr = nrOfAnimalList.get(rowIndex);_x000D_ nrOfAnimalList.set(rowIndex, tmpNr + 1);_x000D_ } else {_x000D_ // Else, make a new row_x000D_ matrix.add(newRow);_x000D_ nrOfAnimalList.add(1);_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ }_x000D_ _x000D_ @Override_x000D_ public String toString() {_x000D_ String output = "<br /><p><strong>JAARSTAAT DIERPROEVEN registratiejaar " + year + " - Registratieformulier 5</strong></p>";_x000D_ output += "<br /><div id='reporttablediv'><table border='1' cellpadding='5' cellspacing='5'>";_x000D_ output += "<tr>";_x000D_ output += "<th></th>";_x000D_ output += "<th></th>";_x000D_ for (int col = 1; col < 15; col++) {_x000D_ output += ("<th>" + col + "</th>");_x000D_ }_x000D_ output += "<th></th>";_x000D_ output += "</tr>";_x000D_ output += "<tr>";_x000D_ output += "<td style='padding:5px'>DEC-nr.</td>";_x000D_ output += "<td style='padding:5px'>DEC verlopen op</td>";_x000D_ output += "<td style='padding:5px'>Bijzonderheid dier</td>";_x000D_ output += "<td style='padding:5px'>Diersoort</td>";_x000D_ output += "<td style='padding:5px'>Herkomst en hergebruik</td>";_x000D_ output += "<td style='padding:5px'>Aantal dieren</td>";_x000D_ output += "<td style='padding:5px'>Doel vd proef</td>";_x000D_ output += "<td style='padding:5px'>Belang van de proef</td>";_x000D_ output += "<td style='padding:5px'>Wettelijke bepalingen</td>";_x000D_ output += "<td style='padding:5px'>Toxicologisch / veiligheidsonderzoek</td>";_x000D_ output += "<td style='padding:5px'>Bijzondere technieken</td>";_x000D_ output += "<td style='padding:5px'>Anesthesie</td>";_x000D_ output += "<td style='padding:5px'>Pijnbestrijding, postoperatief</td>";_x000D_ output += "<td style='padding:5px'>Ongerief</td>";_x000D_ output += "<td style='padding:5px'>Toestand dier na beeindiging proef</td>";_x000D_ output += "<td style='padding:5px'>DEC-nummer / Onderzoeksprotocol</td>";_x000D_ output += "<td style='padding:5px'>Naam (wetenschappelijke naam)</td>";_x000D_ output += "</tr>";_x000D_ int counter = 0;_x000D_ for (ArrayList<String> currentRow : matrix) {_x000D_ output += "<tr>";_x000D_ for (int col = 0; col < nrCol; col++) {_x000D_ if (col == 5) {_x000D_ output += ("<td style='padding:5px'>" + nrOfAnimalList.get(counter) + "</td>");_x000D_ } else {_x000D_ output += ("<td style='padding:5px'>" + currentRow.get(col) + "</td>");_x000D_ }_x000D_ }_x000D_ output += "</tr>";_x000D_ counter++;_x000D_ }_x000D_ output += "</table></div>";_x000D_ _x000D_ // Warnings_x000D_ if (warningsList.size() > 0) {_x000D_ output += "<p><strong>Warnings</strong><br />";_x000D_ for (String warning : warningsList) {_x000D_ output += (warning + "<br />");_x000D_ }_x000D_ output += "</p>";_x000D_ }_x000D_ _x000D_ return output;_x000D_ }_x000D_ }_x000D_
martijnvermaat/molgenis_apps
apps/animaldb/org/molgenis/animaldb/plugins/administration/VWAReport5.java
5,368
// Pijnbestrijding, postoperatief (animal's PainManagement)_x000D_
line_comment
nl
package org.molgenis.animaldb.plugins.administration;_x000D_ _x000D_ import java.text.SimpleDateFormat;_x000D_ import java.util.ArrayList;_x000D_ import java.util.Date;_x000D_ import java.util.List;_x000D_ import java.util.Locale;_x000D_ _x000D_ import org.molgenis.animaldb.commonservice.CommonService;_x000D_ import org.molgenis.framework.db.Database;_x000D_ import org.molgenis.framework.db.Query;_x000D_ import org.molgenis.framework.db.QueryRule;_x000D_ import org.molgenis.framework.db.QueryRule.Operator;_x000D_ import org.molgenis.pheno.ObservationTarget;_x000D_ import org.molgenis.pheno.ObservedValue;_x000D_ _x000D_ _x000D_ public class VWAReport5 extends AnimalDBReport {_x000D_ _x000D_ private ArrayList<ArrayList<String>> matrix = new ArrayList<ArrayList<String>>();_x000D_ private List<Integer> nrOfAnimalList = new ArrayList<Integer>();_x000D_ private String userName;_x000D_ _x000D_ public VWAReport5(Database db, String userName) {_x000D_ this.userName = userName;_x000D_ this.db = db;_x000D_ ct = CommonService.getInstance();_x000D_ ct.setDatabase(db);_x000D_ nrCol = 17;_x000D_ warningsList = new ArrayList<String>();_x000D_ }_x000D_ _x000D_ @Override_x000D_ public void makeReport(int year, String type) {_x000D_ try {_x000D_ this.year = year;_x000D_ SimpleDateFormat fullFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);_x000D_ SimpleDateFormat dbFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);_x000D_ String startOfYearString = year + "-01-01 00:00:00";_x000D_ Date startOfYear = fullFormat.parse(startOfYearString);_x000D_ String endOfYearString = (year + 1) + "-01-01 00:00:00";_x000D_ Date endOfYear = fullFormat.parse(endOfYearString);_x000D_ _x000D_ List<String> investigationNames = ct.getOwnUserInvestigationNames(userName);_x000D_ List<ObservationTarget> decappList = ct.getAllMarkedPanels("DecApplication", investigationNames);_x000D_ for (ObservationTarget d : decappList) {_x000D_ String decName = d.getName();_x000D_ // Check if the DEC application was (partly) in this year_x000D_ Date startOfDec = null;_x000D_ String startOfDecString = ct.getMostRecentValueAsString(decName, "StartDate");_x000D_ if (startOfDecString != null && !startOfDecString.equals("")) {_x000D_ startOfDec = dbFormat.parse(startOfDecString);_x000D_ if (startOfDec.after(endOfYear)) {_x000D_ continue;_x000D_ }_x000D_ } else {_x000D_ continue;_x000D_ }_x000D_ Date endOfDec = null;_x000D_ String endOfDecString = ct.getMostRecentValueAsString(decName, "EndDate");_x000D_ if (endOfDecString != null && !endOfDecString.equals("")) {_x000D_ endOfDec = dbFormat.parse(endOfDecString);_x000D_ if (endOfDec.before(startOfYear)) {_x000D_ continue;_x000D_ }_x000D_ }_x000D_ // Get DEC number_x000D_ String decNr = ct.getMostRecentValueAsString(decName, "DecNr");_x000D_ // Find the experiments belonging to this DEC_x000D_ List<Integer> experimentIdList = new ArrayList<Integer>();_x000D_ Query<ObservedValue> q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, decName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "DecApplication"));_x000D_ List<ObservedValue> valueList = q.find();_x000D_ // Make sure we have a list of unique experiments!_x000D_ for (ObservedValue v : valueList) {_x000D_ if (!experimentIdList.contains(v.getTarget_Id())) {_x000D_ experimentIdList.add(v.getTarget_Id());_x000D_ }_x000D_ }_x000D_ for (int expid : experimentIdList) {_x000D_ String expName = ct.getObservationTargetLabel(expid);_x000D_ // Get the experiment subcode_x000D_ String expCode = ct.getMostRecentValueAsString(expName, "ExperimentNr");_x000D_ // Doel vd proef (experiment's Goal)_x000D_ String goal = ct.getMostRecentValueAsString(expName, "Goal");_x000D_ // Belang van de proef (experiment's Concern)_x000D_ String concern = ct.getMostRecentValueAsString(expName, "Concern");_x000D_ // Wettelijke bepalingen (experiment's LawDef)_x000D_ String lawDef = ct.getMostRecentValueAsString(expName, "LawDef");_x000D_ // Toxicologisch / veiligheidsonderzoek (experiment's ToxRes)_x000D_ String toxRes = ct.getMostRecentValueAsString(expName, "ToxRes");_x000D_ // Technieken byzondere (experiment's SpecialTechn)_x000D_ String specialTechn = ct.getMostRecentValueAsString(expName, "SpecialTechn");_x000D_ _x000D_ // Get the animals that were in the experiment this year_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, expName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Experiment"));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.LESS_EQUAL, endOfYearString));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.NOT, null));_x000D_ valueList = q.find();_x000D_ for (ObservedValue animalInExpValue : valueList) {_x000D_ // Get the corresponding protocol application_x000D_ int protocolApplicationId = animalInExpValue.getProtocolApplication_Id();_x000D_ // Get animal ID_x000D_ String animalName = animalInExpValue.getTarget_Name();_x000D_ // Get dates_x000D_ Date entryDate = animalInExpValue.getTime();_x000D_ Date exitDate = animalInExpValue.getEndtime();_x000D_ // Check dates_x000D_ if (entryDate.after(endOfYear)) {_x000D_ continue;_x000D_ }_x000D_ if (exitDate == null) { // should not be possible_x000D_ continue;_x000D_ } else if (exitDate.before(startOfYear)) {_x000D_ continue;_x000D_ }_x000D_ _x000D_ // Get the data about the animal in the experiment_x000D_ // Bijzonderheid dier (animal's AnimalType)_x000D_ String animalType = ct.getMostRecentValueAsString(animalName, "AnimalType");_x000D_ // Diersoort (animal's Species -> VWASpecies and LatinSpecies)_x000D_ String vwaSpecies = "";_x000D_ String latinSpecies = "";_x000D_ String normalSpecies = ct.getMostRecentValueAsXrefName(animalName, "Species");_x000D_ // Get VWA species_x000D_ Query<ObservedValue> vwaSpeciesQuery = db.query(ObservedValue.class);_x000D_ vwaSpeciesQuery.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, normalSpecies));_x000D_ vwaSpeciesQuery.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "VWASpecies"));_x000D_ List<ObservedValue> vwaSpeciesValueList = vwaSpeciesQuery.find();_x000D_ if (vwaSpeciesValueList.size() == 1) {_x000D_ vwaSpecies = vwaSpeciesValueList.get(0).getValue();_x000D_ }_x000D_ // Get scientific (Latin) species_x000D_ Query<ObservedValue> latinSpeciesQuery = db.query(ObservedValue.class);_x000D_ latinSpeciesQuery.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, normalSpecies));_x000D_ latinSpeciesQuery.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "LatinSpecies"));_x000D_ List<ObservedValue> latinSpeciesValueList = latinSpeciesQuery.find();_x000D_ if (latinSpeciesValueList.size() == 1) {_x000D_ latinSpecies = latinSpeciesValueList.get(0).getValue();_x000D_ }_x000D_ _x000D_ // Herkomst en hergebruik (animal's SourceTypeSubproject, which includes reuse)_x000D_ String sourceType = "";_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "SourceTypeSubproject"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ sourceType = valueList.get(0).getValue();_x000D_ }_x000D_ // Aantal dieren (count later on!)_x000D_ _x000D_ // Anesthesie (animal's Anaesthesia)_x000D_ String anaesthesia = "";_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Anaesthesia"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ anaesthesia = valueList.get(0).getValue();_x000D_ }_x000D_ _x000D_ // Pijnbestrijding, postoperatief<SUF> String painManagement = "";_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "PainManagement"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, protocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ painManagement = valueList.get(0).getValue();_x000D_ }_x000D_ _x000D_ String actualDiscomfort = "";_x000D_ String actualAnimalEndStatus = ""; _x000D_ // Find protocol application ID for the removing of this animal from this DEC subproject_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.RELATION_NAME, Operator.EQUALS, expName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "FromExperiment"));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ int removalProtocolApplicationId = valueList.get(0).getProtocolApplication_Id();_x000D_ _x000D_ // Ongerief (animal's ActualDiscomfort)_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "ActualDiscomfort"));_x000D_ q.addRules(new QueryRule(ObservedValue.PROTOCOLAPPLICATION, Operator.EQUALS, removalProtocolApplicationId));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ actualDiscomfort = valueList.get(0).getValue();_x000D_ } else {_x000D_ // Something's wrong here..._x000D_ warningsList.add("No 'ActualDiscomfort' value found for Animal " + animalName + _x000D_ " in DEC subproject " + expName);_x000D_ }_x000D_ _x000D_ // Toestand dier na beeindiging proef (animal's most recent ActualAnimalEndStatus)_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "ActualAnimalEndStatus"));_x000D_ q.sortDESC(ObservedValue.TIME);_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ // Check if most recent end status was in the PA we're now looking at_x000D_ if (valueList.get(0).getProtocolApplication_Id().equals(removalProtocolApplicationId)) {_x000D_ actualAnimalEndStatus = valueList.get(0).getValue();_x000D_ // If most recent end status was 'in leven gelaten' but animal died in given year,_x000D_ // change to 'dood ihkv de proef' because that's how the law wants it..._x000D_ if (actualAnimalEndStatus.equals("C. Na einde proef in leven gelaten")) {_x000D_ q = db.query(ObservedValue.class);_x000D_ q.addRules(new QueryRule(ObservedValue.TARGET_NAME, Operator.EQUALS, animalName));_x000D_ q.addRules(new QueryRule(ObservedValue.FEATURE_NAME, Operator.EQUALS, "Active"));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.GREATER_EQUAL, startOfYearString));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.LESS_EQUAL, endOfYearString));_x000D_ q.addRules(new QueryRule(ObservedValue.ENDTIME, Operator.NOT, null));_x000D_ valueList = q.find();_x000D_ if (valueList.size() > 0) {_x000D_ // So animal did indeed die in the given year_x000D_ actualAnimalEndStatus = "B. Gedood na beeindiging van de proef";_x000D_ }_x000D_ }_x000D_ } else {_x000D_ // Find the end status value in the PA we're looking at_x000D_ for (ObservedValue endStatusValue : valueList) {_x000D_ if (endStatusValue.getProtocolApplication_Id().equals(removalProtocolApplicationId)) {_x000D_ actualAnimalEndStatus = endStatusValue.getValue();_x000D_ }_x000D_ }_x000D_ }_x000D_ } else {_x000D_ // Something's wrong here..._x000D_ warningsList.add("No 'ActualAnimalEndStatus' value(s) found for Animal " + animalName + _x000D_ " in DEC subproject " + expName);_x000D_ }_x000D_ } else {_x000D_ // Something's wrong here..._x000D_ warningsList.add("No 'FromExperiment' value found for Animal " + animalName + _x000D_ " in DEC subproject " + expName);_x000D_ }_x000D_ _x000D_ ArrayList<String> newRow = new ArrayList<String>();_x000D_ newRow.add(decNr + expCode + " - " + d.getName());_x000D_ if (endOfDec != null) {_x000D_ newRow.add(dbFormat.format(endOfDec));_x000D_ } else {_x000D_ newRow.add("");_x000D_ }_x000D_ newRow.add(animalType);_x000D_ newRow.add(vwaSpecies);_x000D_ newRow.add(sourceType);_x000D_ newRow.add("");_x000D_ newRow.add(goal);_x000D_ newRow.add(concern);_x000D_ newRow.add(lawDef);_x000D_ newRow.add(toxRes);_x000D_ newRow.add(specialTechn);_x000D_ newRow.add(anaesthesia);_x000D_ newRow.add(painManagement);_x000D_ newRow.add(actualDiscomfort);_x000D_ newRow.add(actualAnimalEndStatus);_x000D_ newRow.add(decNr + expCode);_x000D_ newRow.add(latinSpecies);_x000D_ _x000D_ if (matrix.contains(newRow)) {_x000D_ // If the above values are exactly the same as an earlier row, aggregate them_x000D_ int rowIndex = matrix.indexOf(newRow);_x000D_ int tmpNr = nrOfAnimalList.get(rowIndex);_x000D_ nrOfAnimalList.set(rowIndex, tmpNr + 1);_x000D_ } else {_x000D_ // Else, make a new row_x000D_ matrix.add(newRow);_x000D_ nrOfAnimalList.add(1);_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ } catch (Exception e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ }_x000D_ _x000D_ @Override_x000D_ public String toString() {_x000D_ String output = "<br /><p><strong>JAARSTAAT DIERPROEVEN registratiejaar " + year + " - Registratieformulier 5</strong></p>";_x000D_ output += "<br /><div id='reporttablediv'><table border='1' cellpadding='5' cellspacing='5'>";_x000D_ output += "<tr>";_x000D_ output += "<th></th>";_x000D_ output += "<th></th>";_x000D_ for (int col = 1; col < 15; col++) {_x000D_ output += ("<th>" + col + "</th>");_x000D_ }_x000D_ output += "<th></th>";_x000D_ output += "</tr>";_x000D_ output += "<tr>";_x000D_ output += "<td style='padding:5px'>DEC-nr.</td>";_x000D_ output += "<td style='padding:5px'>DEC verlopen op</td>";_x000D_ output += "<td style='padding:5px'>Bijzonderheid dier</td>";_x000D_ output += "<td style='padding:5px'>Diersoort</td>";_x000D_ output += "<td style='padding:5px'>Herkomst en hergebruik</td>";_x000D_ output += "<td style='padding:5px'>Aantal dieren</td>";_x000D_ output += "<td style='padding:5px'>Doel vd proef</td>";_x000D_ output += "<td style='padding:5px'>Belang van de proef</td>";_x000D_ output += "<td style='padding:5px'>Wettelijke bepalingen</td>";_x000D_ output += "<td style='padding:5px'>Toxicologisch / veiligheidsonderzoek</td>";_x000D_ output += "<td style='padding:5px'>Bijzondere technieken</td>";_x000D_ output += "<td style='padding:5px'>Anesthesie</td>";_x000D_ output += "<td style='padding:5px'>Pijnbestrijding, postoperatief</td>";_x000D_ output += "<td style='padding:5px'>Ongerief</td>";_x000D_ output += "<td style='padding:5px'>Toestand dier na beeindiging proef</td>";_x000D_ output += "<td style='padding:5px'>DEC-nummer / Onderzoeksprotocol</td>";_x000D_ output += "<td style='padding:5px'>Naam (wetenschappelijke naam)</td>";_x000D_ output += "</tr>";_x000D_ int counter = 0;_x000D_ for (ArrayList<String> currentRow : matrix) {_x000D_ output += "<tr>";_x000D_ for (int col = 0; col < nrCol; col++) {_x000D_ if (col == 5) {_x000D_ output += ("<td style='padding:5px'>" + nrOfAnimalList.get(counter) + "</td>");_x000D_ } else {_x000D_ output += ("<td style='padding:5px'>" + currentRow.get(col) + "</td>");_x000D_ }_x000D_ }_x000D_ output += "</tr>";_x000D_ counter++;_x000D_ }_x000D_ output += "</table></div>";_x000D_ _x000D_ // Warnings_x000D_ if (warningsList.size() > 0) {_x000D_ output += "<p><strong>Warnings</strong><br />";_x000D_ for (String warning : warningsList) {_x000D_ output += (warning + "<br />");_x000D_ }_x000D_ output += "</p>";_x000D_ }_x000D_ _x000D_ return output;_x000D_ }_x000D_ }_x000D_
True
False
25
3,819
27626_0
package semisplay; public interface SearchTree<E extends Comparable<E>> extends Iterable<E> { /** Voeg de gegeven sleutel toe aan de boom als deze er nog niet in zit. * @return true als de sleutel effectief toegevoegd werd. */ boolean add(E e); /** Zoek de gegeven sleutel op in de boom. * @return true als de sleutel gevonden werd. */ boolean contains(E e); /** Verwijder de gegeven sleutel uit de boom. * @return true als de sleutel gevonden en verwijderd werd. */ boolean remove(E e); /** @return het aantal sleutels in de boom. */ int size(); /** @return de diepte van de boom. */ int depth(); }
nielsdos/Semisplay-tree
src/semisplay/SearchTree.java
203
/** Voeg de gegeven sleutel toe aan de boom als deze er nog niet in zit. * @return true als de sleutel effectief toegevoegd werd. */
block_comment
nl
package semisplay; public interface SearchTree<E extends Comparable<E>> extends Iterable<E> { /** Voeg de gegeven<SUF>*/ boolean add(E e); /** Zoek de gegeven sleutel op in de boom. * @return true als de sleutel gevonden werd. */ boolean contains(E e); /** Verwijder de gegeven sleutel uit de boom. * @return true als de sleutel gevonden en verwijderd werd. */ boolean remove(E e); /** @return het aantal sleutels in de boom. */ int size(); /** @return de diepte van de boom. */ int depth(); }
True
False
30
646
172943_2
package timeutil; import java.util.LinkedList; import java.util.List; /** * Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te * geven, deze op te slaan en deze daarna te printen (via toString). * * Tijdsperiodes worden bepaald door een begintijd en een eindtijd. * * begintijd van een periode kan gezet worden door setBegin, de eindtijd kan * gezet worden door de methode setEind. * * Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven * worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat * tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die * automatisch opgehoogd wordt. * * Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan * t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende * kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven. * * Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als * begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb. * * alle tijdsperiodes kunnen gereset worden dmv init() * * @author erik * */ public class TimeStamp { private static long counter = 0; private long curBegin; private String curBeginS; private List<Period> list; public TimeStamp() { TimeStamp.counter = 0; this.init(); } /** * initialiseer klasse. begin met geen tijdsperiodes. */ public void init() { this.curBegin = 0; this.curBeginS = null; this.list = new LinkedList(); } /** * zet begintijdstip. gebruik interne teller voor identificatie van het * tijdstip */ public void setBegin() { this.setBegin(String.valueOf(TimeStamp.counter++)); } /** * zet begintijdstip * * @param timepoint betekenisvolle identificatie van begintijdstip */ public void setBegin(String timepoint) { this.curBegin = System.currentTimeMillis(); this.curBeginS = timepoint; } /** * zet eindtijdstip. gebruik interne teller voor identificatie van het * tijdstip */ public void setEnd() { this.setEnd(String.valueOf(TimeStamp.counter++)); } /** * zet eindtijdstip * * @param timepoint betekenisvolle identificatie vanhet eindtijdstip */ public void setEnd(String timepoint) { this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint)); } /** * zet eindtijdstip plus begintijdstip * * @param timepoint identificatie van het eind- en begintijdstip. */ public void setEndBegin(String timepoint) { this.setEnd(timepoint); this.setBegin(timepoint); } /** * verkorte versie van setEndBegin * * @param timepoint */ public void seb(String timepoint) { this.setEndBegin(timepoint); } /** * interne klasse voor bijhouden van periodes. * * @author erik * */ private class Period { long begin; String beginS; long end; String endS; public Period(long b, String sb, long e, String se) { this.setBegin(b, sb); this.setEnd(e, se); } private void setBegin(long b, String sb) { this.begin = b; this.beginS = sb; } private void setEnd(long e, String se) { this.end = e; this.endS = se; } @Override public String toString() { return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec."; } } /** * override van toString methode. Geeft alle tijdsperiode weer. */ public String toString() { StringBuilder buffer = new StringBuilder(); for (Period p : this.list) { buffer.append(p.toString()); buffer.append('\n'); } return buffer.toString(); } }
HDauven/S32JSF3
JSF31_w04_KochFractalFX-startup/JSF31KochFractalFX - startup/src/timeutil/TimeStamp.java
1,267
/** * zet begintijdstip. gebruik interne teller voor identificatie van het * tijdstip */
block_comment
nl
package timeutil; import java.util.LinkedList; import java.util.List; /** * Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te * geven, deze op te slaan en deze daarna te printen (via toString). * * Tijdsperiodes worden bepaald door een begintijd en een eindtijd. * * begintijd van een periode kan gezet worden door setBegin, de eindtijd kan * gezet worden door de methode setEind. * * Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven * worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat * tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die * automatisch opgehoogd wordt. * * Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan * t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende * kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven. * * Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als * begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb. * * alle tijdsperiodes kunnen gereset worden dmv init() * * @author erik * */ public class TimeStamp { private static long counter = 0; private long curBegin; private String curBeginS; private List<Period> list; public TimeStamp() { TimeStamp.counter = 0; this.init(); } /** * initialiseer klasse. begin met geen tijdsperiodes. */ public void init() { this.curBegin = 0; this.curBeginS = null; this.list = new LinkedList(); } /** * zet begintijdstip. gebruik<SUF>*/ public void setBegin() { this.setBegin(String.valueOf(TimeStamp.counter++)); } /** * zet begintijdstip * * @param timepoint betekenisvolle identificatie van begintijdstip */ public void setBegin(String timepoint) { this.curBegin = System.currentTimeMillis(); this.curBeginS = timepoint; } /** * zet eindtijdstip. gebruik interne teller voor identificatie van het * tijdstip */ public void setEnd() { this.setEnd(String.valueOf(TimeStamp.counter++)); } /** * zet eindtijdstip * * @param timepoint betekenisvolle identificatie vanhet eindtijdstip */ public void setEnd(String timepoint) { this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint)); } /** * zet eindtijdstip plus begintijdstip * * @param timepoint identificatie van het eind- en begintijdstip. */ public void setEndBegin(String timepoint) { this.setEnd(timepoint); this.setBegin(timepoint); } /** * verkorte versie van setEndBegin * * @param timepoint */ public void seb(String timepoint) { this.setEndBegin(timepoint); } /** * interne klasse voor bijhouden van periodes. * * @author erik * */ private class Period { long begin; String beginS; long end; String endS; public Period(long b, String sb, long e, String se) { this.setBegin(b, sb); this.setEnd(e, se); } private void setBegin(long b, String sb) { this.begin = b; this.beginS = sb; } private void setEnd(long e, String se) { this.end = e; this.endS = se; } @Override public String toString() { return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec."; } } /** * override van toString methode. Geeft alle tijdsperiode weer. */ public String toString() { StringBuilder buffer = new StringBuilder(); for (Period p : this.list) { buffer.append(p.toString()); buffer.append('\n'); } return buffer.toString(); } }
True
False
31
2,480
35814_3
import java.io.File; import java.lang.reflect.Array; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; public class MP1 { Random generator; String userName; String inputFileName; String delimiters = " \t,;.?!-:@[](){}_*/"; String[] stopWordsArray = {"i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours", "yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself", "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that", "these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having", "do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while", "of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before", "after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again", "further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very", "s", "t", "can", "will", "just", "don", "should", "now"}; void initialRandomGenerator(String seed) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(seed.toLowerCase().trim().getBytes()); byte[] seedMD5 = messageDigest.digest(); long longSeed = 0; for (int i = 0; i < seedMD5.length; i++) { longSeed += ((long) seedMD5[i] & 0xffL) << (8 * i); } this.generator = new Random(longSeed); } Integer[] getIndexes() throws NoSuchAlgorithmException { Integer n = 10000; Integer number_of_lines = 50000; Integer[] ret = new Integer[n]; this.initialRandomGenerator(this.userName); for (int i = 0; i < n; i++) { ret[i] = generator.nextInt(number_of_lines); } return ret; } public MP1(String userName, String inputFileName) { this.userName = userName; this.inputFileName = inputFileName; } public String[] process() throws Exception { String[] ret = new String[20]; //TODO // read input file String line; try ( InputStream fis = new FileInputStream(this.inputFileName); InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(isr); ) { int i=0; /* begin Code B */ String regel=""; //debug regel="A._B._een_twee(drie)vier_(vijf)"; //debug /* code1 */ String[] result = regel.split("[\\s_()]"); // split op whitespace, of '_' of '(' of ')' // resultaat zit nu in een Array van strings //print het aantal elementen in de array //debug System.out.println(result.length); //debug for (int x=0; x<result.length; x++) System.out.println(result[x]); /*eind code B */ // zie nog https://d396qusza40orc.cloudfront.net/cloudapplications/mps/mp1/MP1_Instructions.pdf /* begin code A*/ while ((line = br.readLine()) != null) { // Deal with the line // nog "nod code A verwerken voor de variable line" // dit nog vervangen if (i<20) { ret[i] = line; } i++; // dit nog vervangen } /* einde code A*/ } return ret; } public static void main(String[] args) throws Exception { if (args.length < 1){ System.out.println("MP1 <User ID>"); } else { String userName = args[0]; String inputFileName = "./input.txt"; MP1 mp = new MP1(userName, inputFileName); String[] topItems = mp.process(); for (String item: topItems){ System.out.println(item); } } } }
cx1964/cx1964BladMuziek
Klassiek/Chopin_Frédéric/MP1.v002.java
1,466
// resultaat zit nu in een Array van strings
line_comment
nl
import java.io.File; import java.lang.reflect.Array; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; public class MP1 { Random generator; String userName; String inputFileName; String delimiters = " \t,;.?!-:@[](){}_*/"; String[] stopWordsArray = {"i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours", "yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself", "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that", "these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having", "do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while", "of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before", "after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again", "further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very", "s", "t", "can", "will", "just", "don", "should", "now"}; void initialRandomGenerator(String seed) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(seed.toLowerCase().trim().getBytes()); byte[] seedMD5 = messageDigest.digest(); long longSeed = 0; for (int i = 0; i < seedMD5.length; i++) { longSeed += ((long) seedMD5[i] & 0xffL) << (8 * i); } this.generator = new Random(longSeed); } Integer[] getIndexes() throws NoSuchAlgorithmException { Integer n = 10000; Integer number_of_lines = 50000; Integer[] ret = new Integer[n]; this.initialRandomGenerator(this.userName); for (int i = 0; i < n; i++) { ret[i] = generator.nextInt(number_of_lines); } return ret; } public MP1(String userName, String inputFileName) { this.userName = userName; this.inputFileName = inputFileName; } public String[] process() throws Exception { String[] ret = new String[20]; //TODO // read input file String line; try ( InputStream fis = new FileInputStream(this.inputFileName); InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(isr); ) { int i=0; /* begin Code B */ String regel=""; //debug regel="A._B._een_twee(drie)vier_(vijf)"; //debug /* code1 */ String[] result = regel.split("[\\s_()]"); // split op whitespace, of '_' of '(' of ')' // resultaat zit<SUF> //print het aantal elementen in de array //debug System.out.println(result.length); //debug for (int x=0; x<result.length; x++) System.out.println(result[x]); /*eind code B */ // zie nog https://d396qusza40orc.cloudfront.net/cloudapplications/mps/mp1/MP1_Instructions.pdf /* begin code A*/ while ((line = br.readLine()) != null) { // Deal with the line // nog "nod code A verwerken voor de variable line" // dit nog vervangen if (i<20) { ret[i] = line; } i++; // dit nog vervangen } /* einde code A*/ } return ret; } public static void main(String[] args) throws Exception { if (args.length < 1){ System.out.println("MP1 <User ID>"); } else { String userName = args[0]; String inputFileName = "./input.txt"; MP1 mp = new MP1(userName, inputFileName); String[] topItems = mp.process(); for (String item: topItems){ System.out.println(item); } } } }
True
False
35
1,117
18183_3
import java.awt.Rectangle;_x000D_ import java.awt.Graphics;_x000D_ import java.awt.image.BufferedImage;_x000D_ import java.awt.image.ImageObserver;_x000D_ import java.io.File;_x000D_ import javax.imageio.ImageIO;_x000D_ import java.io.IOException;_x000D_ _x000D_ _x000D_ /** De klasse voor een Bitmap item_x000D_ * <P>_x000D_ * This program is distributed under the terms of the accompanying_x000D_ * COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_ * Please read it. Your use of the software constitutes acceptance_x000D_ * of the terms in the COPYRIGHT.txt file._x000D_ * @author Ian F. Darwin, ian@darwinsys.com_x000D_ * @version $Id: BitmapItem.java,v 1.1 2002/12/17 Gert Florijn_x000D_ * @version $Id: BitmapItem.java,v 1.2 2003/12/17 Sylvia Stuurman_x000D_ * @version $Id: BitmapItem.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_ * @version $Id: BitmapItem.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_ */_x000D_ _x000D_ public class BitmapItem extends SlideItem {_x000D_ private BufferedImage bufferedImage;_x000D_ private String imageName;_x000D_ _x000D_ // level staat voor het item-level; name voor de naam van het bestand met het plaatje_x000D_ public BitmapItem(int level, String name) {_x000D_ super(level);_x000D_ imageName = name;_x000D_ try {_x000D_ bufferedImage = ImageIO.read(new File(imageName));_x000D_ }_x000D_ catch (IOException e) {_x000D_ System.err.println("Bestand " + imageName + " niet gevonden") ;_x000D_ }_x000D_ }_x000D_ _x000D_ // Een leeg bitmap-item_x000D_ public BitmapItem() {_x000D_ this(0, null);_x000D_ }_x000D_ _x000D_ // geef de bestandsnaam van het plaatje_x000D_ public String getName() {_x000D_ return imageName;_x000D_ }_x000D_ _x000D_ // geef de bounding box van het plaatje_x000D_ public Rectangle getBoundingBox(Graphics g, ImageObserver observer, float scale, Style myStyle) {_x000D_ return new Rectangle((int) (myStyle.indent * scale), 0,_x000D_ (int) (bufferedImage.getWidth(observer) * scale),_x000D_ ((int) (myStyle.leading * scale)) + (int) (bufferedImage.getHeight(observer) * scale));_x000D_ }_x000D_ _x000D_ // teken het plaatje_x000D_ public void draw(int x, int y, float scale, Graphics g, Style myStyle, ImageObserver observer) {_x000D_ int width = x + (int) (myStyle.indent * scale);_x000D_ int height = y + (int) (myStyle.leading * scale);_x000D_ g.drawImage(bufferedImage, width, height,(int) (bufferedImage.getWidth(observer)*scale),_x000D_ (int) (bufferedImage.getHeight(observer)*scale), observer);_x000D_ }_x000D_ _x000D_ public String toString() {_x000D_ return "BitmapItem[" + getLevel() + "," + imageName + "]";_x000D_ }_x000D_ }_x000D_
MichielMertens/OU_JP_MM_EVB
src/BitmapItem.java
794
// geef de bestandsnaam van het plaatje_x000D_
line_comment
nl
import java.awt.Rectangle;_x000D_ import java.awt.Graphics;_x000D_ import java.awt.image.BufferedImage;_x000D_ import java.awt.image.ImageObserver;_x000D_ import java.io.File;_x000D_ import javax.imageio.ImageIO;_x000D_ import java.io.IOException;_x000D_ _x000D_ _x000D_ /** De klasse voor een Bitmap item_x000D_ * <P>_x000D_ * This program is distributed under the terms of the accompanying_x000D_ * COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_ * Please read it. Your use of the software constitutes acceptance_x000D_ * of the terms in the COPYRIGHT.txt file._x000D_ * @author Ian F. Darwin, ian@darwinsys.com_x000D_ * @version $Id: BitmapItem.java,v 1.1 2002/12/17 Gert Florijn_x000D_ * @version $Id: BitmapItem.java,v 1.2 2003/12/17 Sylvia Stuurman_x000D_ * @version $Id: BitmapItem.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_ * @version $Id: BitmapItem.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_ */_x000D_ _x000D_ public class BitmapItem extends SlideItem {_x000D_ private BufferedImage bufferedImage;_x000D_ private String imageName;_x000D_ _x000D_ // level staat voor het item-level; name voor de naam van het bestand met het plaatje_x000D_ public BitmapItem(int level, String name) {_x000D_ super(level);_x000D_ imageName = name;_x000D_ try {_x000D_ bufferedImage = ImageIO.read(new File(imageName));_x000D_ }_x000D_ catch (IOException e) {_x000D_ System.err.println("Bestand " + imageName + " niet gevonden") ;_x000D_ }_x000D_ }_x000D_ _x000D_ // Een leeg bitmap-item_x000D_ public BitmapItem() {_x000D_ this(0, null);_x000D_ }_x000D_ _x000D_ // geef de<SUF> public String getName() {_x000D_ return imageName;_x000D_ }_x000D_ _x000D_ // geef de bounding box van het plaatje_x000D_ public Rectangle getBoundingBox(Graphics g, ImageObserver observer, float scale, Style myStyle) {_x000D_ return new Rectangle((int) (myStyle.indent * scale), 0,_x000D_ (int) (bufferedImage.getWidth(observer) * scale),_x000D_ ((int) (myStyle.leading * scale)) + (int) (bufferedImage.getHeight(observer) * scale));_x000D_ }_x000D_ _x000D_ // teken het plaatje_x000D_ public void draw(int x, int y, float scale, Graphics g, Style myStyle, ImageObserver observer) {_x000D_ int width = x + (int) (myStyle.indent * scale);_x000D_ int height = y + (int) (myStyle.leading * scale);_x000D_ g.drawImage(bufferedImage, width, height,(int) (bufferedImage.getWidth(observer)*scale),_x000D_ (int) (bufferedImage.getHeight(observer)*scale), observer);_x000D_ }_x000D_ _x000D_ public String toString() {_x000D_ return "BitmapItem[" + getLevel() + "," + imageName + "]";_x000D_ }_x000D_ }_x000D_
True
False
37
839
57662_0
package servlets;_x000D_ _x000D_ import java.io.IOException;_x000D_ import java.sql.Connection;_x000D_ import java.util.ArrayList;_x000D_ _x000D_ import javax.servlet.RequestDispatcher;_x000D_ import javax.servlet.ServletException;_x000D_ import javax.servlet.http.HttpServlet;_x000D_ import javax.servlet.http.HttpServletRequest;_x000D_ import javax.servlet.http.HttpServletResponse;_x000D_ _x000D_ import database.ConnectDBProduct;_x000D_ import domeinklassen.Product;_x000D_ _x000D_ public class ProductServlet extends HttpServlet{_x000D_ private static final long serialVersionUID = 1L;_x000D_ _x000D_ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {_x000D_ _x000D_ Connection con = (Connection)req.getSession().getAttribute("verbinding");_x000D_ String knop = req.getParameter("knop");_x000D_ _x000D_ ConnectDBProduct conn = new ConnectDBProduct(con); _x000D_ ArrayList<Product> deVoorraad = conn.getProducten();_x000D_ RequestDispatcher rd = req.getRequestDispatcher("product.jsp"); //stuur bij default naar voorraadoverzicht_x000D_ _x000D_ //forward voorraadlijst naar de overzicht-pagina._x000D_ if(knop.equals("overzicht")){_x000D_ if(deVoorraad.size() == 0){_x000D_ req.setAttribute("msg", "Geen producten beschikbaar!");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("voorraadlijst", deVoorraad);_x000D_ rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_ }_x000D_ } _x000D_ //forward lijst producten onder min voorraad_x000D_ else if (knop.equals("OnderVoorraad")){_x000D_ ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_ if(ondermin.size() == 0){_x000D_ req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("voorraadlijst", ondermin);_x000D_ rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_ }_x000D_ }_x000D_ //bestel producten onder min voorraad_x000D_ else if(knop.equals("WerkVoorraadBij")){_x000D_ ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_ if(ondermin.size() == 0){_x000D_ req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_ }_x000D_ else{_x000D_ rd = req.getRequestDispatcher("nieuwebestelling.jsp");_x000D_ req.setAttribute("stap1", "Done");_x000D_ req.setAttribute("teBestellenProducten", ondermin);_x000D_ }_x000D_ }_x000D_ //maak een nieuw product aan_x000D_ else if(knop.equals("nieuw")){_x000D_ String nm = req.getParameter("naam");_x000D_ String ma = req.getParameter("minaantal");_x000D_ String eh = req.getParameter("eenheid");_x000D_ String pps = req.getParameter("pps");_x000D_ ArrayList<String> velden = new ArrayList<String>();_x000D_ velden.add(nm); velden.add(ma); velden.add(eh); velden.add("pps");_x000D_ _x000D_ //check of nodige velden in zijn gevuld (artikelnummer bestaat niet meer omdat de database die straks gaat aanmaken)_x000D_ boolean allesIngevuld = true;_x000D_ for(String s : velden){_x000D_ if(s.equals("")){_x000D_ allesIngevuld = false;_x000D_ req.setAttribute("error", "Vul alle velden in!");_x000D_ break;_x000D_ }_x000D_ }_x000D_ //als gegevens ingevuld_x000D_ if(allesIngevuld){ _x000D_ try{ //check voor geldige nummers_x000D_ //maak product aan in database en haal op_x000D_ Product nieuw = conn.nieuwProduct(nm, Integer.parseInt(ma), eh, Double.parseDouble(pps));_x000D_ //stuur toString() van nieuwe product terug_x000D_ String terug = "Nieuw product aangemaakt: " + nieuw.toString();_x000D_ req.setAttribute("msg", terug);_x000D_ }_x000D_ catch(Exception ex){_x000D_ System.out.println(ex);_x000D_ req.setAttribute("error", "Voer geldige nummers in!");_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ //zoek product op naam of artikelnummer_x000D_ else if(knop.equals("zoek")){_x000D_ String nm = req.getParameter("zoeknaam");_x000D_ String eh = req.getParameter("zoekeenheid");_x000D_ String anr = req.getParameter("zoeknummer"); _x000D_ ArrayList<Product> terug = new ArrayList<Product>();_x000D_ //check welke zoekterm er in is gevoerd_x000D_ if(!anr.equals("")){_x000D_ //check voor geldig artikelnummer (int)_x000D_ try{_x000D_ int nummer = Integer.parseInt(anr);_x000D_ terug.add(conn.zoekProduct(nummer));_x000D_ }catch(NumberFormatException e){_x000D_ req.setAttribute("error", "Vul een geldig artikelnummer in!");_x000D_ }_x000D_ }_x000D_ if(!nm.equals("")){_x000D_ for(Product p : conn.zoekProductNaam(nm)){_x000D_ terug.add(p);_x000D_ }_x000D_ } _x000D_ if(!eh.equals("")){_x000D_ for(Product p : conn.zoekProductEenheid(eh)){_x000D_ terug.add(p);_x000D_ }_x000D_ } _x000D_ else{_x000D_ req.setAttribute("error", "Vul een zoekcriterium in!");_x000D_ }_x000D_ if(terug.size() == 0){_x000D_ req.setAttribute("zoekmsg", "Geen producten gevonden met ingevulde criteria");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("zoekmsg", "Product(en) gevonden!"); _x000D_ req.setAttribute("arraygevonden", terug); _x000D_ }_x000D_ }_x000D_ _x000D_ //wijzig gezochte product_x000D_ else if(knop.equals("wijzig")){_x000D_ String productnummer = req.getParameter("product");_x000D_ Product hetProduct = conn.zoekProduct(Integer.parseInt(productnummer));_x000D_ req.setAttribute("product", hetProduct);_x000D_ rd = req.getRequestDispatcher("wijzigproduct.jsp");_x000D_ } _x000D_ else if(knop.equals("verwijder")){_x000D_ String p = req.getParameter("product");_x000D_ if(conn.verwijderProduct(Integer.parseInt(p))){_x000D_ req.setAttribute("msg", "Product met succes verwijderd.");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("error", "Kon product niet verwijderen!");_x000D_ }_x000D_ deVoorraad = conn.getProducten();_x000D_ req.setAttribute("voorraadlijst", deVoorraad);_x000D_ rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_ } _x000D_ rd.forward(req, resp); _x000D_ }_x000D_ }
Jfeurich/Themaopdracht2
Themaopdracht/src/servlets/ProductServlet.java
1,844
//stuur bij default naar voorraadoverzicht_x000D_
line_comment
nl
package servlets;_x000D_ _x000D_ import java.io.IOException;_x000D_ import java.sql.Connection;_x000D_ import java.util.ArrayList;_x000D_ _x000D_ import javax.servlet.RequestDispatcher;_x000D_ import javax.servlet.ServletException;_x000D_ import javax.servlet.http.HttpServlet;_x000D_ import javax.servlet.http.HttpServletRequest;_x000D_ import javax.servlet.http.HttpServletResponse;_x000D_ _x000D_ import database.ConnectDBProduct;_x000D_ import domeinklassen.Product;_x000D_ _x000D_ public class ProductServlet extends HttpServlet{_x000D_ private static final long serialVersionUID = 1L;_x000D_ _x000D_ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {_x000D_ _x000D_ Connection con = (Connection)req.getSession().getAttribute("verbinding");_x000D_ String knop = req.getParameter("knop");_x000D_ _x000D_ ConnectDBProduct conn = new ConnectDBProduct(con); _x000D_ ArrayList<Product> deVoorraad = conn.getProducten();_x000D_ RequestDispatcher rd = req.getRequestDispatcher("product.jsp"); //stuur bij<SUF> _x000D_ //forward voorraadlijst naar de overzicht-pagina._x000D_ if(knop.equals("overzicht")){_x000D_ if(deVoorraad.size() == 0){_x000D_ req.setAttribute("msg", "Geen producten beschikbaar!");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("voorraadlijst", deVoorraad);_x000D_ rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_ }_x000D_ } _x000D_ //forward lijst producten onder min voorraad_x000D_ else if (knop.equals("OnderVoorraad")){_x000D_ ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_ if(ondermin.size() == 0){_x000D_ req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("voorraadlijst", ondermin);_x000D_ rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_ }_x000D_ }_x000D_ //bestel producten onder min voorraad_x000D_ else if(knop.equals("WerkVoorraadBij")){_x000D_ ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_ if(ondermin.size() == 0){_x000D_ req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_ }_x000D_ else{_x000D_ rd = req.getRequestDispatcher("nieuwebestelling.jsp");_x000D_ req.setAttribute("stap1", "Done");_x000D_ req.setAttribute("teBestellenProducten", ondermin);_x000D_ }_x000D_ }_x000D_ //maak een nieuw product aan_x000D_ else if(knop.equals("nieuw")){_x000D_ String nm = req.getParameter("naam");_x000D_ String ma = req.getParameter("minaantal");_x000D_ String eh = req.getParameter("eenheid");_x000D_ String pps = req.getParameter("pps");_x000D_ ArrayList<String> velden = new ArrayList<String>();_x000D_ velden.add(nm); velden.add(ma); velden.add(eh); velden.add("pps");_x000D_ _x000D_ //check of nodige velden in zijn gevuld (artikelnummer bestaat niet meer omdat de database die straks gaat aanmaken)_x000D_ boolean allesIngevuld = true;_x000D_ for(String s : velden){_x000D_ if(s.equals("")){_x000D_ allesIngevuld = false;_x000D_ req.setAttribute("error", "Vul alle velden in!");_x000D_ break;_x000D_ }_x000D_ }_x000D_ //als gegevens ingevuld_x000D_ if(allesIngevuld){ _x000D_ try{ //check voor geldige nummers_x000D_ //maak product aan in database en haal op_x000D_ Product nieuw = conn.nieuwProduct(nm, Integer.parseInt(ma), eh, Double.parseDouble(pps));_x000D_ //stuur toString() van nieuwe product terug_x000D_ String terug = "Nieuw product aangemaakt: " + nieuw.toString();_x000D_ req.setAttribute("msg", terug);_x000D_ }_x000D_ catch(Exception ex){_x000D_ System.out.println(ex);_x000D_ req.setAttribute("error", "Voer geldige nummers in!");_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ //zoek product op naam of artikelnummer_x000D_ else if(knop.equals("zoek")){_x000D_ String nm = req.getParameter("zoeknaam");_x000D_ String eh = req.getParameter("zoekeenheid");_x000D_ String anr = req.getParameter("zoeknummer"); _x000D_ ArrayList<Product> terug = new ArrayList<Product>();_x000D_ //check welke zoekterm er in is gevoerd_x000D_ if(!anr.equals("")){_x000D_ //check voor geldig artikelnummer (int)_x000D_ try{_x000D_ int nummer = Integer.parseInt(anr);_x000D_ terug.add(conn.zoekProduct(nummer));_x000D_ }catch(NumberFormatException e){_x000D_ req.setAttribute("error", "Vul een geldig artikelnummer in!");_x000D_ }_x000D_ }_x000D_ if(!nm.equals("")){_x000D_ for(Product p : conn.zoekProductNaam(nm)){_x000D_ terug.add(p);_x000D_ }_x000D_ } _x000D_ if(!eh.equals("")){_x000D_ for(Product p : conn.zoekProductEenheid(eh)){_x000D_ terug.add(p);_x000D_ }_x000D_ } _x000D_ else{_x000D_ req.setAttribute("error", "Vul een zoekcriterium in!");_x000D_ }_x000D_ if(terug.size() == 0){_x000D_ req.setAttribute("zoekmsg", "Geen producten gevonden met ingevulde criteria");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("zoekmsg", "Product(en) gevonden!"); _x000D_ req.setAttribute("arraygevonden", terug); _x000D_ }_x000D_ }_x000D_ _x000D_ //wijzig gezochte product_x000D_ else if(knop.equals("wijzig")){_x000D_ String productnummer = req.getParameter("product");_x000D_ Product hetProduct = conn.zoekProduct(Integer.parseInt(productnummer));_x000D_ req.setAttribute("product", hetProduct);_x000D_ rd = req.getRequestDispatcher("wijzigproduct.jsp");_x000D_ } _x000D_ else if(knop.equals("verwijder")){_x000D_ String p = req.getParameter("product");_x000D_ if(conn.verwijderProduct(Integer.parseInt(p))){_x000D_ req.setAttribute("msg", "Product met succes verwijderd.");_x000D_ }_x000D_ else{_x000D_ req.setAttribute("error", "Kon product niet verwijderen!");_x000D_ }_x000D_ deVoorraad = conn.getProducten();_x000D_ req.setAttribute("voorraadlijst", deVoorraad);_x000D_ rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_ } _x000D_ rd.forward(req, resp); _x000D_ }_x000D_ }
True
False
38
804
203327_6
package be.ucll.workloadplanner; import static android.content.ContentValues.TAG; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.navigation.NavController; import androidx.navigation.fragment.NavHostFragment; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; // Hoofdscherm waarin de verschillende fragmenten geladen worden public class MainActivity extends AppCompatActivity { private NavController navController; private FirebaseAuth firebaseAuth; private FirebaseFirestore db; private String userRole; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); firebaseAuth = FirebaseAuth.getInstance(); db = FirebaseFirestore.getInstance(); setSupportActionBar(findViewById(R.id.toolbar)); NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view); navController = navHostFragment.getNavController(); logCurrentUserId(); } // Controle ingelogde user om te checken of de login gewerkt heeft private void logCurrentUserId() { FirebaseUser user = getCurrentUser(); if (user != null) { String phoneNumber = user.getPhoneNumber(); if (phoneNumber != null) { FirebaseFirestore db = FirebaseFirestore.getInstance(); db.collection("users").whereEqualTo("userId", phoneNumber) .get() .addOnSuccessListener(queryDocumentSnapshots -> { if (!queryDocumentSnapshots.isEmpty()) { DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0); String userId = documentSnapshot.getString("userId"); Log.d("MainActivity", "User ID: " + userId); getUserRole(userId); // Call to get user role after user ID retrieval } else { Log.d("MainActivity", "User document does not exist"); } }) .addOnFailureListener(e -> { Log.e("MainActivity", "Error getting user document", e); }); } else { Log.d("MainActivity", "No phone number associated with the current user"); } } else { Log.d("MainActivity", "No user is currently authenticated"); } } // Huidige gebruiker ophalen private FirebaseUser getCurrentUser() { return firebaseAuth.getCurrentUser(); } // Voor het weergeven van het menu rechtsboven @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); // Hide or show menu items based on user role MenuItem homeItem = menu.findItem(R.id.action_home); MenuItem addTicketItem = menu.findItem(R.id.action_addTicket); MenuItem logoutItem = menu.findItem(R.id.action_logout); if (userRole != null && userRole.equals("Project Manager")) { homeItem.setVisible(true); addTicketItem.setVisible(true); logoutItem.setVisible(true); } else if (userRole != null && userRole.equals("Member")) { homeItem.setVisible(true); addTicketItem.setVisible(false); logoutItem.setVisible(true); } else { addTicketItem.setVisible(false); logoutItem.setVisible(false); } return true; } // Instellen van de opties van het menu @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.action_home) { navController.navigate(R.id.action_any_fragment_to_tickets); return true; } NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view); if (navHostFragment != null) { Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment(); // Now you have the current fragment Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName()); if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) { if (item.getItemId() == R.id.action_addTicket) { Log.d("MainActivity", "Adding ticket..."); navController.navigate(R.id.action_any_fragment_to_addTicket); return true; } } } if (item.getItemId() == R.id.action_logout) { firebaseAuth.signOut(); Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null)); Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class); startActivity(loginIntent); finish(); return true; } return super.onOptionsItemSelected(item); } // De rol van de gebruiker opzoeken, member of project manager private void getUserRole(String userId) { FirebaseFirestore.getInstance() .collection("users") .whereEqualTo("userId", userId) .get() .addOnSuccessListener(queryDocumentSnapshots -> { if (!queryDocumentSnapshots.isEmpty()) { DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0); String role = documentSnapshot.getString("role"); if (role != null) { Log.d(TAG, "User id found: " + userId); Log.d(TAG, "User role found: " + role); userRole = role; // Update user role variable invalidateOptionsMenu(); // Refresh menu to reflect changes } else { Log.d(TAG, "Role field not found in user document"); } } else { Log.d(TAG, "User document not found for userId: " + userId); } }) .addOnFailureListener(e -> { Log.e(TAG, "Error fetching user document", e); }); } }
JanVHanssen/WorkloadPlanner
app/src/main/java/be/ucll/workloadplanner/MainActivity.java
1,848
// Instellen van de opties van het menu
line_comment
nl
package be.ucll.workloadplanner; import static android.content.ContentValues.TAG; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.navigation.NavController; import androidx.navigation.fragment.NavHostFragment; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; // Hoofdscherm waarin de verschillende fragmenten geladen worden public class MainActivity extends AppCompatActivity { private NavController navController; private FirebaseAuth firebaseAuth; private FirebaseFirestore db; private String userRole; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); firebaseAuth = FirebaseAuth.getInstance(); db = FirebaseFirestore.getInstance(); setSupportActionBar(findViewById(R.id.toolbar)); NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view); navController = navHostFragment.getNavController(); logCurrentUserId(); } // Controle ingelogde user om te checken of de login gewerkt heeft private void logCurrentUserId() { FirebaseUser user = getCurrentUser(); if (user != null) { String phoneNumber = user.getPhoneNumber(); if (phoneNumber != null) { FirebaseFirestore db = FirebaseFirestore.getInstance(); db.collection("users").whereEqualTo("userId", phoneNumber) .get() .addOnSuccessListener(queryDocumentSnapshots -> { if (!queryDocumentSnapshots.isEmpty()) { DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0); String userId = documentSnapshot.getString("userId"); Log.d("MainActivity", "User ID: " + userId); getUserRole(userId); // Call to get user role after user ID retrieval } else { Log.d("MainActivity", "User document does not exist"); } }) .addOnFailureListener(e -> { Log.e("MainActivity", "Error getting user document", e); }); } else { Log.d("MainActivity", "No phone number associated with the current user"); } } else { Log.d("MainActivity", "No user is currently authenticated"); } } // Huidige gebruiker ophalen private FirebaseUser getCurrentUser() { return firebaseAuth.getCurrentUser(); } // Voor het weergeven van het menu rechtsboven @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); // Hide or show menu items based on user role MenuItem homeItem = menu.findItem(R.id.action_home); MenuItem addTicketItem = menu.findItem(R.id.action_addTicket); MenuItem logoutItem = menu.findItem(R.id.action_logout); if (userRole != null && userRole.equals("Project Manager")) { homeItem.setVisible(true); addTicketItem.setVisible(true); logoutItem.setVisible(true); } else if (userRole != null && userRole.equals("Member")) { homeItem.setVisible(true); addTicketItem.setVisible(false); logoutItem.setVisible(true); } else { addTicketItem.setVisible(false); logoutItem.setVisible(false); } return true; } // Instellen van<SUF> @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.action_home) { navController.navigate(R.id.action_any_fragment_to_tickets); return true; } NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view); if (navHostFragment != null) { Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment(); // Now you have the current fragment Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName()); if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) { if (item.getItemId() == R.id.action_addTicket) { Log.d("MainActivity", "Adding ticket..."); navController.navigate(R.id.action_any_fragment_to_addTicket); return true; } } } if (item.getItemId() == R.id.action_logout) { firebaseAuth.signOut(); Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null)); Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class); startActivity(loginIntent); finish(); return true; } return super.onOptionsItemSelected(item); } // De rol van de gebruiker opzoeken, member of project manager private void getUserRole(String userId) { FirebaseFirestore.getInstance() .collection("users") .whereEqualTo("userId", userId) .get() .addOnSuccessListener(queryDocumentSnapshots -> { if (!queryDocumentSnapshots.isEmpty()) { DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0); String role = documentSnapshot.getString("role"); if (role != null) { Log.d(TAG, "User id found: " + userId); Log.d(TAG, "User role found: " + role); userRole = role; // Update user role variable invalidateOptionsMenu(); // Refresh menu to reflect changes } else { Log.d(TAG, "Role field not found in user document"); } } else { Log.d(TAG, "User document not found for userId: " + userId); } }) .addOnFailureListener(e -> { Log.e(TAG, "Error fetching user document", e); }); } }
True
False
42
1,508
37934_2
package nl.sbdeveloper.leastslack; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LeastSlack { private static final Pattern pattern = Pattern.compile("(\\d+)[ \\t]+(\\d+)"); public static void main(String[] args) throws IOException { if (args.length < 1) { System.out.println("Geef een bestandsnaam mee!"); System.exit(0); return; } URL resource = LeastSlack.class.getClassLoader().getResource(args[0]); if (resource == null) { System.out.println("De meegegeven bestandsnaam bestaat niet!"); System.exit(0); return; } Scanner fileScanner = new Scanner(resource.openStream()); JobShop shop = new JobShop(); int jobs = 0; int machines = 0; int lowestMachine = Integer.MAX_VALUE; boolean wasFirstLine; int currentJob = 0; Matcher matcher; while (fileScanner.hasNextLine()) { matcher = pattern.matcher(fileScanner.nextLine()); wasFirstLine = false; if (jobs != 0 && machines != 0) { Job job = new Job(currentJob); shop.getJobs().add(job); } while (matcher.find()) { if (jobs == 0 || machines == 0) { jobs = Integer.parseInt(matcher.group(1)); machines = Integer.parseInt(matcher.group(2)); wasFirstLine = true; break; } else { int id = Integer.parseInt(matcher.group(1)); int duration = Integer.parseInt(matcher.group(2)); if (id < lowestMachine) lowestMachine = id; Task task = new Task(id, duration); int finalCurrentJob = currentJob; Optional<Job> jobOpt = shop.getJobs().stream().filter(j -> j.getId() == finalCurrentJob).findFirst(); if (jobOpt.isEmpty()) break; jobOpt.get().getTasks().add(task); } } if (!wasFirstLine) currentJob++; } fileScanner.close(); ////////////////////////////////// shop.getJobs().forEach(Job::calculateEarliestStart); shop.getJobs().stream().max(Comparator.comparing(Job::calculateTotalDuration)) .ifPresent(job -> shop.getJobs().forEach(j -> j.calculateLatestStart(job.calculateTotalDuration()))); shop.calculateSlack(); for (Job j : shop.getJobs()) { System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":"); for (Task t : j.getTasks()) { System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart()); } } //TODO Fix dat hij de earliest start update als een taak begint die langer duurt dan de earliest start van een taak op de machine //TODO In het huidige voorbeeld start Job 1 op Machine 0 (ES van 40, tijd 40) en heeft Job 2 op Machine 0 een ES van 60. Machine 0 is bezet tot 80, wat betekent dat die van Machine 0 moet updaten naar 80. // int loop = 0; int time = 0; // while (loop < 40) { while (!shop.isAllJobsDone()) { // loop++; System.out.println("------START------"); List<Job> conflictedJobs = new ArrayList<>(); int smallestTaskDuration = Integer.MAX_VALUE; Map<Integer, Integer> foundTaskDurations = new HashMap<>(); //Key = machine ID, value = duration for (Map.Entry<Job, Task> pair : shop.getTasksWithEarliestTimeNow(time)) { if (foundTaskDurations.containsKey(pair.getValue().getMachineID())) { //Er is al een task met een kleinere slack gestart, er was dus een conflict op dit tijdstip! pair.getValue().setEarliestStart(foundTaskDurations.get(pair.getValue().getMachineID())); conflictedJobs.add(pair.getKey()); continue; } System.out.println("Job " + pair.getKey().getId() + " wordt uitgevoerd op machine " + pair.getValue().getMachineID() + "."); pair.getValue().setDone(true); pair.getKey().setBeginTime(time); foundTaskDurations.put(pair.getValue().getMachineID(), pair.getValue().getDuration()); if (pair.getValue().getDuration() < smallestTaskDuration) smallestTaskDuration = pair.getValue().getDuration(); } for (Job job : conflictedJobs) { job.calculateEarliestStart(); } if (!conflictedJobs.isEmpty()) { shop.calculateSlack(); for (Job j : shop.getJobs()) { System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":"); for (Task t : j.getTasks()) { System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart()); } } } if (smallestTaskDuration == Integer.MAX_VALUE) smallestTaskDuration = 1; //Als er op dit tijdstip geen taken draaien, tellen we er 1 bij op tot we weer wat vinden. time += smallestTaskDuration; for (Job j : shop.getJobs()) { if (j.getEndTime() == 0 && j.hasAllTasksDone()) j.setEndTime(time); } System.out.println("Time: " + time); } for (Job j : shop.getJobs()) { System.out.println(j.getId() + "\t" + j.getBeginTime() + "\t" + j.getEndTime()); } } }
SBDPlugins/LeastSlackTime-OSM
src/main/java/nl/sbdeveloper/leastslack/LeastSlack.java
1,705
// int loop = 0;
line_comment
nl
package nl.sbdeveloper.leastslack; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LeastSlack { private static final Pattern pattern = Pattern.compile("(\\d+)[ \\t]+(\\d+)"); public static void main(String[] args) throws IOException { if (args.length < 1) { System.out.println("Geef een bestandsnaam mee!"); System.exit(0); return; } URL resource = LeastSlack.class.getClassLoader().getResource(args[0]); if (resource == null) { System.out.println("De meegegeven bestandsnaam bestaat niet!"); System.exit(0); return; } Scanner fileScanner = new Scanner(resource.openStream()); JobShop shop = new JobShop(); int jobs = 0; int machines = 0; int lowestMachine = Integer.MAX_VALUE; boolean wasFirstLine; int currentJob = 0; Matcher matcher; while (fileScanner.hasNextLine()) { matcher = pattern.matcher(fileScanner.nextLine()); wasFirstLine = false; if (jobs != 0 && machines != 0) { Job job = new Job(currentJob); shop.getJobs().add(job); } while (matcher.find()) { if (jobs == 0 || machines == 0) { jobs = Integer.parseInt(matcher.group(1)); machines = Integer.parseInt(matcher.group(2)); wasFirstLine = true; break; } else { int id = Integer.parseInt(matcher.group(1)); int duration = Integer.parseInt(matcher.group(2)); if (id < lowestMachine) lowestMachine = id; Task task = new Task(id, duration); int finalCurrentJob = currentJob; Optional<Job> jobOpt = shop.getJobs().stream().filter(j -> j.getId() == finalCurrentJob).findFirst(); if (jobOpt.isEmpty()) break; jobOpt.get().getTasks().add(task); } } if (!wasFirstLine) currentJob++; } fileScanner.close(); ////////////////////////////////// shop.getJobs().forEach(Job::calculateEarliestStart); shop.getJobs().stream().max(Comparator.comparing(Job::calculateTotalDuration)) .ifPresent(job -> shop.getJobs().forEach(j -> j.calculateLatestStart(job.calculateTotalDuration()))); shop.calculateSlack(); for (Job j : shop.getJobs()) { System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":"); for (Task t : j.getTasks()) { System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart()); } } //TODO Fix dat hij de earliest start update als een taak begint die langer duurt dan de earliest start van een taak op de machine //TODO In het huidige voorbeeld start Job 1 op Machine 0 (ES van 40, tijd 40) en heeft Job 2 op Machine 0 een ES van 60. Machine 0 is bezet tot 80, wat betekent dat die van Machine 0 moet updaten naar 80. // int loop<SUF> int time = 0; // while (loop < 40) { while (!shop.isAllJobsDone()) { // loop++; System.out.println("------START------"); List<Job> conflictedJobs = new ArrayList<>(); int smallestTaskDuration = Integer.MAX_VALUE; Map<Integer, Integer> foundTaskDurations = new HashMap<>(); //Key = machine ID, value = duration for (Map.Entry<Job, Task> pair : shop.getTasksWithEarliestTimeNow(time)) { if (foundTaskDurations.containsKey(pair.getValue().getMachineID())) { //Er is al een task met een kleinere slack gestart, er was dus een conflict op dit tijdstip! pair.getValue().setEarliestStart(foundTaskDurations.get(pair.getValue().getMachineID())); conflictedJobs.add(pair.getKey()); continue; } System.out.println("Job " + pair.getKey().getId() + " wordt uitgevoerd op machine " + pair.getValue().getMachineID() + "."); pair.getValue().setDone(true); pair.getKey().setBeginTime(time); foundTaskDurations.put(pair.getValue().getMachineID(), pair.getValue().getDuration()); if (pair.getValue().getDuration() < smallestTaskDuration) smallestTaskDuration = pair.getValue().getDuration(); } for (Job job : conflictedJobs) { job.calculateEarliestStart(); } if (!conflictedJobs.isEmpty()) { shop.calculateSlack(); for (Job j : shop.getJobs()) { System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":"); for (Task t : j.getTasks()) { System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart()); } } } if (smallestTaskDuration == Integer.MAX_VALUE) smallestTaskDuration = 1; //Als er op dit tijdstip geen taken draaien, tellen we er 1 bij op tot we weer wat vinden. time += smallestTaskDuration; for (Job j : shop.getJobs()) { if (j.getEndTime() == 0 && j.hasAllTasksDone()) j.setEndTime(time); } System.out.println("Time: " + time); } for (Job j : shop.getJobs()) { System.out.println(j.getId() + "\t" + j.getBeginTime() + "\t" + j.getEndTime()); } } }
True
False
43
1,356
4744_9
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class DemoWorld extends World { // Declareren van CollisionEngine private CollisionEngine ce; // Declareren van TileEngine private TileEngine te; /** * Constructor for objects of class MyWorld. * */ public DemoWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 8, 8, 8, 8, -1, -1, -1, -1, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},}; // initialiseren van de TileEngine klasse om de map aan de world toe te voegen te = new TileEngine(this, 60, 60); te.setTileFactory(new DemoTileFactory()); te.setMap(map); // 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); // 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); // 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 DemoHero hero = new DemoHero(ce, te); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 300, 200); addObject(new Enemy(), 1170, 410); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); } @Override public void act() { ce.update(); } }
ROCMondriaanTIN/project-greenfoot-game-2dook
DemoWorld.java
3,194
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class DemoWorld extends World { // Declareren van CollisionEngine private CollisionEngine ce; // Declareren van TileEngine private TileEngine te; /** * Constructor for objects of class MyWorld. * */ public DemoWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 8, 8, 8, 8, -1, -1, -1, -1, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},}; // initialiseren van de TileEngine klasse om de map aan de world toe te voegen te = new TileEngine(this, 60, 60); te.setTileFactory(new DemoTileFactory()); te.setMap(map); // 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); // Initialiseren van<SUF> // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // 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 DemoHero hero = new DemoHero(ce, te); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 300, 200); addObject(new Enemy(), 1170, 410); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); } @Override public void act() { ce.update(); } }
True
False
44

Dataset Card for "LLM-OF-BABEL-NL3"

More Information needed

Downloads last month
38